@plasgos/auth-verify 0.0.0-stage → 0.1.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +15 -0
  3. package/README.md +122 -2
  4. package/THIRD_PARTY_NOTICES.md +31 -0
  5. package/dist/express.cjs +157 -0
  6. package/dist/express.cjs.map +1 -0
  7. package/dist/express.d.cts +90 -0
  8. package/dist/express.d.ts +90 -0
  9. package/dist/express.js +127 -0
  10. package/dist/express.js.map +1 -0
  11. package/dist/index.cjs +1254 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +67 -0
  14. package/dist/index.d.ts +67 -0
  15. package/dist/index.js +499 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/nestjs.cjs +1395 -0
  18. package/dist/nestjs.cjs.map +1 -0
  19. package/dist/nestjs.d.cts +153 -0
  20. package/dist/nestjs.d.ts +153 -0
  21. package/dist/nestjs.js +637 -0
  22. package/dist/nestjs.js.map +1 -0
  23. package/dist/types-CGtRnj59.d.cts +193 -0
  24. package/dist/types-CGtRnj59.d.ts +193 -0
  25. package/dist/webhook.cjs +296 -0
  26. package/dist/webhook.cjs.map +1 -0
  27. package/dist/webhook.d.cts +196 -0
  28. package/dist/webhook.d.ts +196 -0
  29. package/dist/webhook.js +265 -0
  30. package/dist/webhook.js.map +1 -0
  31. package/docs/bff-express.md +1314 -0
  32. package/docs/consumers.md +98 -0
  33. package/docs/contoh-hitungcuan.md +255 -0
  34. package/docs/contoh-plaslink.md +244 -0
  35. package/docs/error.md +613 -0
  36. package/docs/examples/auth-verify-readme.ts +42 -0
  37. package/docs/examples/bff-express.ts +370 -0
  38. package/docs/examples/bff-proxy.ts +335 -0
  39. package/docs/examples/bff-redis-lock.ts +187 -0
  40. package/docs/examples/bff-revocation.ts +136 -0
  41. package/docs/examples/config-error.ts +24 -0
  42. package/docs/examples/env.ts +150 -0
  43. package/docs/examples/failure-log.ts +18 -0
  44. package/docs/examples/login-client.ts +46 -0
  45. package/docs/examples/login-flow.ts +186 -0
  46. package/docs/examples/plaslink-connect.ts +48 -0
  47. package/docs/examples/readme.ts +60 -0
  48. package/docs/examples/service-client.ts +105 -0
  49. package/docs/examples/session-store.ts +53 -0
  50. package/docs/examples/token-commonjs.cjs +95 -0
  51. package/docs/examples/token-express.ts +56 -0
  52. package/docs/examples/token-fetch.ts +24 -0
  53. package/docs/examples/token-nestjs-jest.ts +77 -0
  54. package/docs/examples/token-nestjs.ts +127 -0
  55. package/docs/examples/token-socket.ts +59 -0
  56. package/docs/examples/token-testing.ts +100 -0
  57. package/docs/examples/token-verifier.ts +132 -0
  58. package/docs/examples/user-events.ts +110 -0
  59. package/docs/examples/webhook-express.ts +46 -0
  60. package/docs/examples/webhook-fetch.ts +60 -0
  61. package/docs/examples/webhook-nestjs.ts +59 -0
  62. package/docs/examples/webhook-testing.ts +60 -0
  63. package/docs/examples/webhook-verifier.ts +197 -0
  64. package/docs/login-web.md +650 -0
  65. package/docs/memulai.md +419 -0
  66. package/docs/server-ke-server.md +287 -0
  67. package/docs/verifikasi-token.md +1219 -0
  68. package/docs/webhook.md +810 -0
  69. package/package.json +101 -3
@@ -0,0 +1,42 @@
1
+ import { createAccessTokenVerifier } from "@plasgos/auth-verify";
2
+ import type { AccessTokenVerifier, UserAccessPrincipal } from "@plasgos/auth-verify";
3
+ import { principalOf, requirePlasgosToken } from "@plasgos/auth-verify/express";
4
+ import { createWebhookVerifier, presets } from "@plasgos/auth-verify/webhook";
5
+ import type { VerifiedWebhook, WebhookVerifier } from "@plasgos/auth-verify/webhook";
6
+ import type { Express } from "express";
7
+
8
+ // #region webhook
9
+ /** Once, at start: a wrong option throws one ConfigError here. */
10
+ export function createVerifier(): WebhookVerifier {
11
+ return createWebhookVerifier({
12
+ environment: "production",
13
+ secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
14
+ preset: presets.payments,
15
+ });
16
+ }
17
+
18
+ /** Per delivery: the headers and the raw body, before JSON parsing. Throws WebhookVerifyError. */
19
+ export function receive(verifier: WebhookVerifier, request: Request, rawBody: Uint8Array): VerifiedWebhook {
20
+ return verifier.verify({ headers: request.headers, rawBody });
21
+ }
22
+ // #endregion webhook
23
+
24
+ // #region token
25
+ /** Once, at start: a wrong option throws one ConfigError here. */
26
+ export function createTokenVerifier(isRevoked: (principal: UserAccessPrincipal) => Promise<boolean>): AccessTokenVerifier {
27
+ return createAccessTokenVerifier({
28
+ environment: "production",
29
+ issuer: "https://accounts.plasgos.co.id",
30
+ audience: "https://api.plasgos.co.id/crm",
31
+ requireClaims: ["plasgos_public_id", "cv"],
32
+ isRevoked,
33
+ });
34
+ }
35
+
36
+ /** Per route: 401, 403 or 503 is answered by the middleware; the handler runs only with a valid token. */
37
+ export function mountContacts(app: Express, verifier: AccessTokenVerifier): void {
38
+ app.get("/contacts", requirePlasgosToken(verifier, { scopes: ["crm:access"] }), (req, res) => {
39
+ res.json({ owner: principalOf(req).claims.plasgos_public_id });
40
+ });
41
+ }
42
+ // #endregion token
@@ -0,0 +1,370 @@
1
+ import { OidcError, accessTokenExpiry, createOidcClient } from "@plasgos/oidc-client";
2
+ import type { OidcClient } from "@plasgos/oidc-client";
3
+ import { createSessionStore } from "@plasgos/oidc-client/session";
4
+ import type { AuthState, SessionHandle, SessionSchema, SessionStore } from "@plasgos/oidc-client/session";
5
+ import express from "express";
6
+ import type { NextFunction, Request, Response, Router } from "express";
7
+
8
+ import { RefreshLockTimeoutError, RefreshLockUnavailableError, redisRefreshLock, tokenSealer } from "./bff-redis-lock.js";
9
+ import type { RedisLike } from "./bff-redis-lock.js";
10
+ import { MarkerStoreUnavailableError, checkSession, markerKeys } from "./bff-revocation.js";
11
+ import type { ForcedRefresh, MarkerKeys } from "./bff-revocation.js";
12
+ import { readBffEnv, readLoginCredentials, readSessionSecrets } from "./env.js";
13
+ import { logFailure } from "./failure-log.js";
14
+
15
+ // #region setup
16
+ /** This BFF keeps no data of its own in the session, only the SDK's auth. */
17
+ export type BffSession = object;
18
+ export type BffSessionHandle = SessionHandle<BffSession>;
19
+
20
+ const bffSchema: SessionSchema<BffSession> = {
21
+ parse: (input) => (typeof input === "object" && input !== null ? {} : null),
22
+ };
23
+
24
+ /** Everything the routes need. Created once at start: a wrong option stops the process with a ConfigError. */
25
+ export interface Bff {
26
+ client: OidcClient;
27
+ store: SessionStore<BffSession>;
28
+ redis: RedisLike;
29
+ markerKeys: MarkerKeys;
30
+ /** Public origin of the BFF (APP_URL), for the Origin checks and the callback URL. */
31
+ appOrigin: string;
32
+ /** "" at the root of the host, or a sub-path such as "/crm". */
33
+ basePath: string;
34
+ /** Origin of the app's own API, which verifies the token with @plasgos/auth-verify. */
35
+ apiOrigin: string;
36
+ }
37
+
38
+ export function createBff(redis: RedisLike, basePath = ""): Bff {
39
+ const env = readBffEnv();
40
+ const credentials = readLoginCredentials();
41
+ const secrets = readSessionSecrets();
42
+ const client = createOidcClient({
43
+ environment: env.environment,
44
+ issuer: env.issuer,
45
+ // Only inside the Plasgos network. There is no logoutTicket option here on purpose: it is on by
46
+ // default for a first-party client with endSession "redirect" and a backchannelUrl, and an
47
+ // explicit true without backchannelUrl is a ConfigError. Without backchannelUrl there is no
48
+ // ticket, and Plasgos asks the user to confirm the logout.
49
+ backchannelUrl: env.backchannelUrl,
50
+ clientId: credentials.clientId,
51
+ clientSecret: credentials.clientSecret,
52
+ redirectUri: `${credentials.appUrl}${basePath}/auth/callback`,
53
+ postLogoutRedirectUri: `${credentials.appUrl}${basePath}/`,
54
+ // plasgos:public_id puts the user's public id (plasgos_public_id) into the access token; without it
55
+ // an API that requires the claim refuses every token with 401. crm:access is the example API's scope.
56
+ scopes: ["openid", "profile", "email", "plasgos:public_id", "crm:access"],
57
+ profile: "first-party",
58
+ // The audience of the app's own API: every access token is issued for it.
59
+ resource: env.resource,
60
+ // One refresh per refresh token across every instance of the BFF.
61
+ refreshLock: redisRefreshLock(redis, tokenSealer(secrets)),
62
+ onFailure: logFailure,
63
+ });
64
+ const store = createSessionStore<BffSession>({
65
+ environment: env.environment,
66
+ secrets,
67
+ // Never change the salt, the names or the path after the first release: every user would be signed out.
68
+ hkdfSalt: "contoh-bff",
69
+ cookies: { app: "bff", auth: "bff-auth", idToken: "bff-idt", transaction: "bff-oidc" },
70
+ // "/" at the root of the host: __Host- cookies. Under a sub-path: __Secure- cookies with that Path.
71
+ path: `${basePath}/`,
72
+ authMaxAgeSeconds: 2_592_000,
73
+ appSchema: bffSchema,
74
+ });
75
+ return { client, store, redis, markerKeys, appOrigin: credentials.appUrl, basePath, apiOrigin: env.apiOrigin };
76
+ }
77
+ // #endregion setup
78
+
79
+ // #region setup-subpath
80
+ /**
81
+ * The same BFF served under https://app.example.com/crm/. Everything follows from the base path:
82
+ * - cookies __Secure-bff, __Secure-bff-auth, __Secure-bff-idt, __Secure-bff-oidc, each with Path=/crm/,
83
+ * when set and when cleared;
84
+ * - the redirect URI to register: https://app.example.com/crm/auth/callback;
85
+ * - the routes are mounted under /crm (startBff in bff-proxy.ts).
86
+ */
87
+ export function createSubpathBff(redis: RedisLike): Bff {
88
+ return createBff(redis, "/crm");
89
+ }
90
+ // #endregion setup-subpath
91
+
92
+ // #region respond
93
+ /** Express 4 does not catch a rejected handler promise; Express 5 does. This form works with both. */
94
+ export function route(handler: (req: Request, res: Response) => Promise<void>) {
95
+ return (req: Request, res: Response, next: NextFunction): void => {
96
+ void handler(req, res).catch(next);
97
+ };
98
+ }
99
+
100
+ /** Sends JSON with every session cookie that changed: a renewed auth, or a destroyed session. */
101
+ export function sendJson(res: Response, bff: Bff, session: BffSessionHandle, status: number, body: unknown): void {
102
+ for (const cookie of bff.store.commit(session)) res.append("Set-Cookie", cookie);
103
+ res.set("Cache-Control", "no-store").status(status).json(body);
104
+ }
105
+
106
+ /**
107
+ * A failure that is not the end of the session. Plasgos or Redis unreachable (the markers or the
108
+ * refresh lock), or a refresh lock that timed out: 503, the session is kept. config_invalid or provider_error: 500 (a bug to fix, already
109
+ * reported through onFailure), the session is kept. Anything else is thrown to the error handler.
110
+ */
111
+ export function sendFailure(res: Response, bff: Bff, session: BffSessionHandle, error: unknown): void {
112
+ const temporary =
113
+ (error instanceof OidcError && error.reason === "unavailable") ||
114
+ error instanceof RefreshLockTimeoutError ||
115
+ error instanceof RefreshLockUnavailableError ||
116
+ error instanceof MarkerStoreUnavailableError;
117
+ if (temporary) {
118
+ res.set("Retry-After", "5");
119
+ sendJson(res, bff, session, 503, { error: "temporarily_unavailable" });
120
+ return;
121
+ }
122
+ if (error instanceof OidcError) {
123
+ sendJson(res, bff, session, 500, { error: "internal_error" });
124
+ return;
125
+ }
126
+ throw error;
127
+ }
128
+ // #endregion respond
129
+
130
+ // #region fresh
131
+ /** OidcError reasons that end the session: Plasgos no longer accepts it. */
132
+ const ENDING_REASONS: ReadonlySet<string> = new Set(["invalid_grant", "invalid_target", "missing"]);
133
+
134
+ /**
135
+ * The session's auth, renewed when the access token is about to expire (always with `force`). Null when
136
+ * there is no session or Plasgos ended it; the session is then destroyed here. Any other failure is
137
+ * thrown and the session is kept (see sendFailure).
138
+ */
139
+ export async function freshAuth(bff: Bff, session: BffSessionHandle, force = false): Promise<AuthState | null> {
140
+ const current = session.data.auth;
141
+ if (current === undefined) return null;
142
+ try {
143
+ const { auth, changed } = await bff.client.ensureFresh(current, { force });
144
+ // Store a renewed auth at once: its refresh token replaced the old one at Plasgos.
145
+ if (changed) session.update({ auth });
146
+ return auth;
147
+ } catch (error) {
148
+ if (error instanceof OidcError && ENDING_REASONS.has(error.reason)) {
149
+ session.destroy();
150
+ return null;
151
+ }
152
+ // Redis failed before the refresh ran, so the refresh token is unused. An access token that still
153
+ // works carries this request; a forced refresh (its token was refused or is below a marker) cannot.
154
+ if (error instanceof RefreshLockUnavailableError && !force && current.expires_at * 1000 > Date.now()) return current;
155
+ throw error;
156
+ }
157
+ }
158
+
159
+ /** The forced refreshes of one request (see ForcedRefresh), and whether one already ran. */
160
+ export interface RequestRefresh extends ForcedRefresh {
161
+ /** True once force() ran in this request: the proxy then passes an API 401 on instead of retrying. */
162
+ readonly forced: boolean;
163
+ }
164
+
165
+ /**
166
+ * Per request: at most one refresh because the token expires soon (checkedAuth), at most one forced
167
+ * refresh (the credential-version check or the proxy's retry after a 401, whichever asks first; the
168
+ * other gets the same result), and only for the credential-version check one follow-up (again()).
169
+ */
170
+ export function requestRefresh(bff: Bff, session: BffSessionHandle): RequestRefresh {
171
+ let forced: Promise<AuthState | null> | undefined;
172
+ let again: Promise<AuthState | null> | undefined;
173
+ return {
174
+ get forced() {
175
+ return forced !== undefined;
176
+ },
177
+ force: () => (forced ??= freshAuth(bff, session, true)),
178
+ // freshAuth reads the session's auth, which force() replaced: the newest refresh token.
179
+ again: () => (again ??= freshAuth(bff, session, true)),
180
+ };
181
+ }
182
+
183
+ /** The request's auth: renewed when needed, then checked against the revocation markers. Null: signed out. */
184
+ export async function checkedAuth(bff: Bff, session: BffSessionHandle, refresh: RequestRefresh): Promise<AuthState | null> {
185
+ if ((await freshAuth(bff, session)) === null) return null;
186
+ if (!(await checkSession(bff.redis, bff.markerKeys, session, refresh))) return null;
187
+ return session.data.auth ?? null;
188
+ }
189
+ // #endregion fresh
190
+
191
+ // #region login
192
+ /**
193
+ * Only a path of this app: basePath itself or a path below it ("/crm", "/crm/…"; any path when basePath
194
+ * is ""). Printable ASCII, no "//", no backslash, no "." or ".." segment (also as %2e), no encoded "/"
195
+ * or "\" (%2f, %5c). It starts with "/" and has no "//", so it never carries a scheme or another host.
196
+ */
197
+ export function safeReturnTo(value: unknown, basePath: string): string {
198
+ const fallback = `${basePath}/`;
199
+ if (typeof value !== "string" || value.length > 512) return fallback;
200
+ if (!/^\/[\x21-\x7E]*$/.test(value) || value.includes("//") || value.includes("\\")) return fallback;
201
+ if (value !== basePath && !value.startsWith(`${basePath}/`)) return fallback;
202
+ const path = value.split(/[?#]/, 1)[0] ?? "";
203
+ if (/%(?:2f|5c)/i.test(path)) return fallback;
204
+ const segments = path.split("/").map((segment) => segment.replace(/%2e/gi, "."));
205
+ if (segments.some((segment) => segment === "." || segment === "..")) return fallback;
206
+ return value;
207
+ }
208
+
209
+ /** GET /auth/login?return_to=/path: a full-page redirect to Plasgos. */
210
+ function login(bff: Bff, req: Request, res: Response): void {
211
+ const returnTo = safeReturnTo(req.query["return_to"], bff.basePath);
212
+ const { location, transaction } = bff.client.startLogin({ returnTo });
213
+ res.append("Set-Cookie", bff.store.commitTransaction(transaction));
214
+ res.set("Cache-Control", "no-store").redirect(302, location);
215
+ }
216
+ // #endregion login
217
+
218
+ // #region callback
219
+ function loginFailed(res: Response, status: number): void {
220
+ res.status(status).set("Cache-Control", "no-store").type("text/plain").send("Login gagal. Silakan coba lagi.");
221
+ }
222
+
223
+ /** GET /auth/callback: Plasgos sends the browser back here with code and state. */
224
+ async function callback(bff: Bff, req: Request, res: Response): Promise<void> {
225
+ const { client, store } = bff;
226
+ // The transaction is single use: its cookie is cleared on every path.
227
+ res.append("Set-Cookie", store.clearTransaction());
228
+ try {
229
+ // The full URL from the configured origin, never from the Host header.
230
+ const url = `${bff.appOrigin}${req.originalUrl}`;
231
+ const { tokens, claims, transaction } = await client.handleCallback(url, store.readTransaction(req.headers.cookie));
232
+ const auth: AuthState = {
233
+ access_token: tokens.access_token,
234
+ refresh_token: tokens.refresh_token,
235
+ expires_at: accessTokenExpiry(tokens, Date.now()),
236
+ user: { id: claims.sub, name: claims.name ?? "", email: claims.email ?? null, avatar_url: claims.picture ?? null },
237
+ id_token: tokens.id_token,
238
+ auth_time: claims.auth_time,
239
+ };
240
+ const fits = store.fits(auth);
241
+ if (!fits.auth) {
242
+ loginFailed(res, 500);
243
+ return;
244
+ }
245
+ // A fresh session, never merged into what the browser sent: a session planted before the login
246
+ // (for example by another app on the same host) cannot survive it.
247
+ const session = store.read(null);
248
+ session.destroy();
249
+ session.update({ auth: fits.idToken ? auth : { ...auth, id_token: undefined } });
250
+ for (const cookie of store.commit(session)) res.append("Set-Cookie", cookie);
251
+ res.set("Cache-Control", "no-store").redirect(302, safeReturnTo(transaction.return_to, bff.basePath));
252
+ } catch (error) {
253
+ if (!(error instanceof OidcError)) throw error;
254
+ loginFailed(res, error.reason === "unavailable" ? 503 : 400);
255
+ }
256
+ }
257
+ // #endregion callback
258
+
259
+ // #region me
260
+ /** GET /auth/me: who is signed in, for the SPA; never a token. Also renews an expiring access token. */
261
+ async function me(bff: Bff, req: Request, res: Response): Promise<void> {
262
+ const session = bff.store.read(req.headers.cookie);
263
+ try {
264
+ const auth = await checkedAuth(bff, session, requestRefresh(bff, session));
265
+ if (auth === null) {
266
+ sendJson(res, bff, session, 401, { error: "login_required" });
267
+ return;
268
+ }
269
+ const { name, email, avatar_url } = auth.user;
270
+ sendJson(res, bff, session, 200, { user: { name, email, avatar_url } });
271
+ } catch (error) {
272
+ sendFailure(res, bff, session, error);
273
+ }
274
+ }
275
+ // #endregion me
276
+
277
+ // #region logout
278
+ const escapeHtml = (text: string): string => text.replace(/[&<>"']/g, (char) => `&#${String(char.charCodeAt(0))};`);
279
+
280
+ /** POST /auth/logout, from a form of this app (csrfGuard checks its Origin). */
281
+ async function logout(bff: Bff, req: Request, res: Response): Promise<void> {
282
+ const session = bff.store.read(req.headers.cookie);
283
+ const auth = session.data.auth;
284
+ // Never rejects: a failed call to Plasgos is reported through onFailure and the logout goes on.
285
+ const result = await bff.client.logout({
286
+ refreshToken: auth?.refresh_token,
287
+ idToken: auth?.id_token,
288
+ // clientIp: the address your reverse proxy vouches for, or null.
289
+ browser: { clientIp: null, userAgent: req.get("user-agent") ?? null },
290
+ });
291
+ // The local session ends whatever Plasgos answered, also when it could not be reached.
292
+ session.destroy();
293
+ for (const cookie of bff.store.commit(session)) res.append("Set-Cookie", cookie);
294
+ res.set("Cache-Control", "no-store");
295
+ // LogoutResult is a union: read `location` only after checking `kind`.
296
+ if (result.kind === "redirect") {
297
+ res.redirect(303, result.location);
298
+ return;
299
+ }
300
+ // "form" comes only with endSession "form-post", for an app on the issuer's own origin: not a BFF.
301
+ const fields = Object.entries(result.fields)
302
+ .map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`)
303
+ .join("");
304
+ res
305
+ .type("html")
306
+ .send(`<!doctype html><form method="post" action="${escapeHtml(result.action)}">${fields}</form><script>document.forms[0].submit()</script>`);
307
+ }
308
+ // #endregion logout
309
+
310
+ // #region csrf
311
+ /**
312
+ * The custom header the SPA sends on every API call that changes data. A form of another site cannot
313
+ * set a custom header. The name and value are this app's own choice; pick your own pair.
314
+ */
315
+ export const CSRF_HEADER_NAME = "x-bff-request";
316
+ export const CSRF_HEADER_VALUE = "1";
317
+ const SAFE_METHODS: ReadonlySet<string> = new Set(["GET", "HEAD", "OPTIONS"]);
318
+
319
+ /**
320
+ * A request that changes something must come from this app's own pages: its Origin must be the app's
321
+ * origin, and API calls also carry the custom header. The logout is a plain form post, which cannot
322
+ * send a custom header, so it is checked by Origin only. The BFF sends no CORS headers, so no other
323
+ * origin can read its answers.
324
+ */
325
+ export function csrfGuard(appOrigin: string, requireHeader: boolean) {
326
+ return (req: Request, res: Response, next: NextFunction): void => {
327
+ if (SAFE_METHODS.has(req.method)) {
328
+ next();
329
+ return;
330
+ }
331
+ if (req.get("origin") !== appOrigin || (requireHeader && req.get(CSRF_HEADER_NAME) !== CSRF_HEADER_VALUE)) {
332
+ res.status(403).json({ error: "forbidden" });
333
+ return;
334
+ }
335
+ next();
336
+ };
337
+ }
338
+
339
+ /**
340
+ * For Socket.IO's long-polling requests: they carry the session cookie, so every method, GET included,
341
+ * must come from this app's pages. No custom header (the Socket.IO client does not send one). A browser
342
+ * sends Origin on every POST and every cross-origin request; on a same-origin GET it leaves Origin out
343
+ * but sends Sec-Fetch-Site: same-origin. A request with neither is refused.
344
+ */
345
+ export function sameOriginOnly(appOrigin: string) {
346
+ return (req: Request, res: Response, next: NextFunction): void => {
347
+ const origin = req.get("origin");
348
+ const sameOrigin = origin === undefined ? req.get("sec-fetch-site") === "same-origin" : origin === appOrigin;
349
+ if (!sameOrigin) {
350
+ res.status(403).json({ error: "forbidden" });
351
+ return;
352
+ }
353
+ next();
354
+ };
355
+ }
356
+ // #endregion csrf
357
+
358
+ // #region router
359
+ /** The auth routes. Mounted at the root of the host, or under the sub-path (startBff in bff-proxy.ts). */
360
+ export function createBffRouter(bff: Bff): Router {
361
+ const router = express.Router();
362
+ router.get("/auth/login", (req, res) => {
363
+ login(bff, req, res);
364
+ });
365
+ router.get("/auth/callback", route((req, res) => callback(bff, req, res)));
366
+ router.get("/auth/me", route((req, res) => me(bff, req, res)));
367
+ router.post("/auth/logout", csrfGuard(bff.appOrigin, false), route((req, res) => logout(bff, req, res)));
368
+ return router;
369
+ }
370
+ // #endregion router