This commit is contained in:
+111
-87
@@ -1,125 +1,149 @@
|
||||
import { createRemoteJWKSet, jwtVerify, SignJWT, decodeJwt, type JWTPayload } from 'jose'
|
||||
import { GraphQLError } from 'graphql'
|
||||
import type { Request } from 'express'
|
||||
import { prisma } from './db.js'
|
||||
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";
|
||||
import { GraphQLError } from "graphql";
|
||||
import type { Request } from "express";
|
||||
import { prisma } from "./db.js";
|
||||
|
||||
const LOGTO_JWKS_URL = process.env.LOGTO_JWKS_URL || 'https://auth.optovia.ru/oidc/jwks'
|
||||
const LOGTO_ISSUER = process.env.LOGTO_ISSUER || 'https://auth.optovia.ru/oidc'
|
||||
const LOGTO_TEAMS_AUDIENCE = process.env.LOGTO_TEAMS_AUDIENCE || 'https://teams.optovia.ru'
|
||||
const APP_JWT_ISSUER = 'optovia:teams'
|
||||
const APP_JWT_AUDIENCES = ['https://teams.optovia.ru', 'https://orders.optovia.ru', 'https://logistics.optovia.ru']
|
||||
const LOGTO_JWKS_URL =
|
||||
process.env.LOGTO_JWKS_URL || "https://auth.optovia.ru/oidc/jwks";
|
||||
const LOGTO_ISSUER = process.env.LOGTO_ISSUER || "https://auth.optovia.ru/oidc";
|
||||
const LOGTO_TEAMS_AUDIENCE =
|
||||
process.env.LOGTO_TEAMS_AUDIENCE || "https://teams.optovia.ru";
|
||||
|
||||
const jwks = createRemoteJWKSet(new URL(LOGTO_JWKS_URL))
|
||||
const jwks = createRemoteJWKSet(new URL(LOGTO_JWKS_URL));
|
||||
|
||||
export interface AuthContext {
|
||||
userId?: string
|
||||
teamUuid?: string
|
||||
sessionToken?: string
|
||||
scopes: string[]
|
||||
isM2M?: boolean
|
||||
userId?: string;
|
||||
teamUuid?: string;
|
||||
sessionToken?: string;
|
||||
scopes: string[];
|
||||
isM2M?: boolean;
|
||||
}
|
||||
|
||||
export const SESSION_TOKEN_PREFIX = 'optovia-session:'
|
||||
export const SESSION_TOKEN_PREFIX = "optovia-session:";
|
||||
|
||||
function getBearerToken(req: Request): string {
|
||||
const auth = req.headers.authorization || ''
|
||||
if (!auth.startsWith('Bearer ')) throw new GraphQLError('Missing Bearer token', { extensions: { code: 'UNAUTHENTICATED' } })
|
||||
const token = auth.slice(7)
|
||||
if (!token || token === 'undefined') throw new GraphQLError('Empty Bearer token', { extensions: { code: 'UNAUTHENTICATED' } })
|
||||
return token
|
||||
const auth = req.headers.authorization || "";
|
||||
if (!auth.startsWith("Bearer "))
|
||||
throw new GraphQLError("Missing Bearer token", {
|
||||
extensions: { code: "UNAUTHENTICATED" },
|
||||
});
|
||||
const token = auth.slice(7);
|
||||
if (!token || token === "undefined")
|
||||
throw new GraphQLError("Empty Bearer token", {
|
||||
extensions: { code: "UNAUTHENTICATED" },
|
||||
});
|
||||
return token;
|
||||
}
|
||||
|
||||
function optionalBearerToken(req: Request): string | null {
|
||||
const auth = req.headers.authorization || ''
|
||||
if (!auth.startsWith('Bearer ')) return null
|
||||
const token = auth.slice(7)
|
||||
if (!token || token === 'undefined') return null
|
||||
return token
|
||||
const auth = req.headers.authorization || "";
|
||||
if (!auth.startsWith("Bearer ")) return null;
|
||||
const token = auth.slice(7);
|
||||
if (!token || token === "undefined") return null;
|
||||
return token;
|
||||
}
|
||||
|
||||
function scopesFromPayload(payload: JWTPayload): string[] {
|
||||
const scope = payload.scope
|
||||
if (!scope) return []
|
||||
if (typeof scope === 'string') return scope.split(' ')
|
||||
return []
|
||||
const scope = payload.scope;
|
||||
if (!scope) return [];
|
||||
if (typeof scope === "string") return scope.split(" ");
|
||||
if (Array.isArray(scope)) return scope as string[];
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function publicContext(): Promise<AuthContext> { return { scopes: [] } }
|
||||
|
||||
function appJwtSecret(): Uint8Array {
|
||||
const secret = process.env.APP_JWT_SECRET
|
||||
if (!secret) throw new GraphQLError('APP_JWT_SECRET is required', { extensions: { code: 'INTERNAL_SERVER_ERROR' } })
|
||||
return new TextEncoder().encode(secret)
|
||||
export async function publicContext(): Promise<AuthContext> {
|
||||
return { scopes: [] };
|
||||
}
|
||||
|
||||
export async function issueAppJwt(input: { userId: string; teamUuid?: string | null; isManager: boolean }): Promise<string> {
|
||||
const scopes = ['teams:user']
|
||||
if (input.isManager) scopes.push('manager')
|
||||
return new SignJWT({
|
||||
scope: scopes.join(' '),
|
||||
roles: input.isManager ? ['manager'] : [],
|
||||
team_uuid: input.teamUuid ?? undefined,
|
||||
})
|
||||
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
|
||||
.setIssuer(APP_JWT_ISSUER)
|
||||
.setAudience(APP_JWT_AUDIENCES)
|
||||
.setSubject(input.userId)
|
||||
.setIssuedAt()
|
||||
.setExpirationTime(`${Number.parseInt(process.env.LOGIN_SESSION_TTL_DAYS || '30', 10)}d`)
|
||||
.sign(appJwtSecret())
|
||||
function claimList(payload: JWTPayload, key: string): string[] {
|
||||
const value = (payload as Record<string, unknown>)[key];
|
||||
if (typeof value === "string") return value.split(" ");
|
||||
if (Array.isArray(value))
|
||||
return value.filter((item): item is string => typeof item === "string");
|
||||
return [];
|
||||
}
|
||||
|
||||
async function verifyAppJwt(token: string, audience: string = LOGTO_TEAMS_AUDIENCE): Promise<AuthContext> {
|
||||
const { payload } = await jwtVerify(token, appJwtSecret(), { issuer: APP_JWT_ISSUER, audience })
|
||||
const scopes = scopesFromPayload(payload)
|
||||
if (!payload.sub) {
|
||||
throw new GraphQLError('Unauthorized', { extensions: { code: 'UNAUTHENTICATED' } })
|
||||
}
|
||||
return {
|
||||
userId: payload.sub,
|
||||
teamUuid: (payload as Record<string, unknown>).team_uuid as string | undefined,
|
||||
scopes,
|
||||
}
|
||||
function hasManagerClaim(payload: JWTPayload): boolean {
|
||||
const scopes = scopesFromPayload(payload);
|
||||
return (
|
||||
scopes.includes("manager") ||
|
||||
claimList(payload, "roles").includes("manager") ||
|
||||
claimList(payload, "permissions").includes("manager")
|
||||
);
|
||||
}
|
||||
|
||||
export async function userContext(req: Request): Promise<AuthContext> {
|
||||
const token = optionalBearerToken(req)
|
||||
if (token === null) return { scopes: [] }
|
||||
const token = optionalBearerToken(req);
|
||||
if (token === null) return { scopes: [] };
|
||||
if (token.startsWith(SESSION_TOKEN_PREFIX)) {
|
||||
const session = await prisma.authSession.findUnique({ where: { token }, include: { user: true } })
|
||||
if (session === null || session.revokedAt !== null || session.expiresAt <= new Date()) {
|
||||
throw new GraphQLError('Session expired', { extensions: { code: 'UNAUTHENTICATED' } })
|
||||
const session = await prisma.authSession.findUnique({
|
||||
where: { token },
|
||||
include: { user: true },
|
||||
});
|
||||
if (
|
||||
session === null ||
|
||||
session.revokedAt !== null ||
|
||||
session.expiresAt <= new Date()
|
||||
) {
|
||||
throw new GraphQLError("Session expired", {
|
||||
extensions: { code: "UNAUTHENTICATED" },
|
||||
});
|
||||
}
|
||||
return { userId: session.user.username, sessionToken: token, scopes: ['teams:user'] }
|
||||
return {
|
||||
userId: session.user.username,
|
||||
sessionToken: token,
|
||||
scopes: ["teams:user"],
|
||||
};
|
||||
}
|
||||
const unverifiedPayload = decodeJwt(token)
|
||||
if (unverifiedPayload.iss === APP_JWT_ISSUER) return verifyAppJwt(token)
|
||||
const { payload } = await jwtVerify(token, jwks, { issuer: LOGTO_ISSUER })
|
||||
return { userId: payload.sub, scopes: [] }
|
||||
const { payload } = await jwtVerify(token, jwks, { issuer: LOGTO_ISSUER });
|
||||
return { userId: payload.sub, scopes: scopesFromPayload(payload) };
|
||||
}
|
||||
|
||||
export async function managerContext(req: Request): Promise<AuthContext> {
|
||||
const token = optionalBearerToken(req)
|
||||
if (token === null) return { scopes: [] }
|
||||
const context = await verifyAppJwt(token)
|
||||
if (!context.scopes.includes('manager')) {
|
||||
throw new GraphQLError('Manager access required', { extensions: { code: 'FORBIDDEN' } })
|
||||
const token = getBearerToken(req);
|
||||
const { payload } = await jwtVerify(token, jwks, {
|
||||
issuer: LOGTO_ISSUER,
|
||||
audience: LOGTO_TEAMS_AUDIENCE,
|
||||
});
|
||||
if (!payload.sub || !hasManagerClaim(payload)) {
|
||||
throw new GraphQLError("Manager access required", {
|
||||
extensions: { code: "FORBIDDEN" },
|
||||
});
|
||||
}
|
||||
return context
|
||||
return {
|
||||
userId: payload.sub,
|
||||
teamUuid: (payload as Record<string, unknown>).team_uuid as
|
||||
| string
|
||||
| undefined,
|
||||
scopes: [...new Set([...scopesFromPayload(payload), "manager"])],
|
||||
};
|
||||
}
|
||||
|
||||
export async function teamContext(req: Request): Promise<AuthContext> {
|
||||
const token = getBearerToken(req)
|
||||
const { payload } = await jwtVerify(token, jwks, { issuer: LOGTO_ISSUER, audience: LOGTO_TEAMS_AUDIENCE })
|
||||
const teamUuid = (payload as Record<string, unknown>).team_uuid as string | undefined
|
||||
const scopes = scopesFromPayload(payload)
|
||||
if (!teamUuid || !scopes.includes('teams:member')) throw new GraphQLError('Unauthorized', { extensions: { code: 'UNAUTHENTICATED' } })
|
||||
return { userId: payload.sub, teamUuid, scopes }
|
||||
const token = getBearerToken(req);
|
||||
const { payload } = await jwtVerify(token, jwks, {
|
||||
issuer: LOGTO_ISSUER,
|
||||
audience: LOGTO_TEAMS_AUDIENCE,
|
||||
});
|
||||
const teamUuid = (payload as Record<string, unknown>).team_uuid as
|
||||
| string
|
||||
| undefined;
|
||||
const scopes = scopesFromPayload(payload);
|
||||
if (!teamUuid || !scopes.includes("teams:member"))
|
||||
throw new GraphQLError("Unauthorized", {
|
||||
extensions: { code: "UNAUTHENTICATED" },
|
||||
});
|
||||
return { userId: payload.sub, teamUuid, scopes };
|
||||
}
|
||||
|
||||
export async function m2mContext(): Promise<AuthContext> { return { scopes: [], isM2M: true } }
|
||||
export async function m2mContext(): Promise<AuthContext> {
|
||||
return { scopes: [], isM2M: true };
|
||||
}
|
||||
|
||||
export function requireScopes(ctx: AuthContext, ...required: string[]): void {
|
||||
const missing = required.filter(s => !ctx.scopes.includes(s))
|
||||
if (missing.length > 0) throw new GraphQLError(`Missing required scopes: ${missing.join(', ')}`, { extensions: { code: 'FORBIDDEN' } })
|
||||
const missing = required.filter((s) => !ctx.scopes.includes(s));
|
||||
if (missing.length > 0)
|
||||
throw new GraphQLError(`Missing required scopes: ${missing.join(", ")}`, {
|
||||
extensions: { code: "FORBIDDEN" },
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user