Require Logto scopes for KYC auth
Build and deploy Docker image / build (push) Successful in 2m31s

This commit is contained in:
Ruslan Bakiev
2026-06-05 12:53:05 +07:00
parent d2a2a13b3b
commit 74303068f2
+30 -24
View File
@@ -5,10 +5,8 @@ import type { FastifyRequest } from "fastify";
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 TEAMS_USER_GRAPHQL_URL =
process.env.TEAMS_USER_GRAPHQL_URL ||
"https://teams.optovia.ru/graphql/user/";
const SESSION_TOKEN_PREFIX = "optovia-session:";
const LOGTO_KYC_AUDIENCE =
process.env.LOGTO_KYC_AUDIENCE || "https://kyc.optovia.ru";
const jwks = createRemoteJWKSet(new URL(LOGTO_JWKS_URL));
@@ -26,11 +24,28 @@ function getBearerToken(req: FastifyRequest): string | null {
return token;
}
function scopesFromPayload(payload: JWTPayload): string[] {
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(req: FastifyRequest): Promise<AuthContext> {
const token = getBearerToken(req);
if (!token) return { scopes: [] };
const { payload } = await jwtVerify(token, jwks, { issuer: LOGTO_ISSUER });
return { userId: payload.sub, scopes: [] };
const { payload } = await jwtVerify(token, jwks, {
issuer: LOGTO_ISSUER,
audience: LOGTO_KYC_AUDIENCE,
});
const scopes = scopesFromPayload(payload);
if (!scopes.includes("teams:user")) {
throw new GraphQLError("Unauthorized", {
extensions: { code: "UNAUTHENTICATED" },
});
}
return { userId: payload.sub, scopes };
}
export async function userContext(req: FastifyRequest): Promise<AuthContext> {
@@ -40,26 +55,17 @@ export async function userContext(req: FastifyRequest): Promise<AuthContext> {
extensions: { code: "UNAUTHENTICATED" },
});
}
if (token.startsWith(SESSION_TOKEN_PREFIX)) {
const response = await fetch(TEAMS_USER_GRAPHQL_URL, {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${token}`,
},
body: JSON.stringify({ query: `query KycSessionMe { me { id } }` }),
const { payload } = await jwtVerify(token, jwks, {
issuer: LOGTO_ISSUER,
audience: LOGTO_KYC_AUDIENCE,
});
const scopes = scopesFromPayload(payload);
if (!scopes.includes("teams:user")) {
throw new GraphQLError("Unauthorized", {
extensions: { code: "UNAUTHENTICATED" },
});
const body = (await response.json()) as { data?: { me?: { id?: string } } };
const userId = body.data?.me?.id;
if (!userId) {
throw new GraphQLError("Unauthorized", {
extensions: { code: "UNAUTHENTICATED" },
});
}
return { userId, scopes: [] };
}
const { payload } = await jwtVerify(token, jwks, { issuer: LOGTO_ISSUER });
return { userId: payload.sub, scopes: [] };
return { userId: payload.sub, scopes };
}
export async function m2mContext(): Promise<AuthContext> {