@plasgos/oidc-client 0.1.0-next.1 → 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 (62) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +4 -3
  3. package/README.md +27 -14
  4. package/dist/index.cjs +2 -2
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +2 -2
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +2 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/service.cjs +1 -1
  11. package/dist/service.cjs.map +1 -1
  12. package/dist/service.d.cts +3 -3
  13. package/dist/service.d.ts +3 -3
  14. package/dist/service.js +1 -1
  15. package/dist/service.js.map +1 -1
  16. package/dist/session.cjs +71 -20
  17. package/dist/session.cjs.map +1 -1
  18. package/dist/session.d.cts +57 -6
  19. package/dist/session.d.ts +57 -6
  20. package/dist/session.js +63 -13
  21. package/dist/session.js.map +1 -1
  22. package/dist/{types-Cncksfeo.d.cts → types-JE0OMyoi.d.cts} +1 -1
  23. package/dist/{types-Cncksfeo.d.ts → types-JE0OMyoi.d.ts} +1 -1
  24. package/docs/bff-express.md +1314 -0
  25. package/docs/consumers.md +98 -0
  26. package/docs/contoh-hitungcuan.md +255 -0
  27. package/docs/contoh-plaslink.md +244 -0
  28. package/docs/error.md +613 -0
  29. package/docs/examples/auth-verify-readme.ts +42 -0
  30. package/docs/examples/bff-express.ts +370 -0
  31. package/docs/examples/bff-proxy.ts +335 -0
  32. package/docs/examples/bff-redis-lock.ts +187 -0
  33. package/docs/examples/bff-revocation.ts +136 -0
  34. package/docs/examples/config-error.ts +24 -0
  35. package/docs/examples/env.ts +150 -0
  36. package/docs/examples/failure-log.ts +18 -0
  37. package/docs/examples/login-client.ts +46 -0
  38. package/docs/examples/login-flow.ts +186 -0
  39. package/docs/examples/plaslink-connect.ts +48 -0
  40. package/docs/examples/readme.ts +60 -0
  41. package/docs/examples/service-client.ts +105 -0
  42. package/docs/examples/session-store.ts +53 -0
  43. package/docs/examples/token-commonjs.cjs +95 -0
  44. package/docs/examples/token-express.ts +56 -0
  45. package/docs/examples/token-fetch.ts +24 -0
  46. package/docs/examples/token-nestjs-jest.ts +77 -0
  47. package/docs/examples/token-nestjs.ts +127 -0
  48. package/docs/examples/token-socket.ts +59 -0
  49. package/docs/examples/token-testing.ts +100 -0
  50. package/docs/examples/token-verifier.ts +132 -0
  51. package/docs/examples/user-events.ts +110 -0
  52. package/docs/examples/webhook-express.ts +46 -0
  53. package/docs/examples/webhook-fetch.ts +60 -0
  54. package/docs/examples/webhook-nestjs.ts +59 -0
  55. package/docs/examples/webhook-testing.ts +60 -0
  56. package/docs/examples/webhook-verifier.ts +197 -0
  57. package/docs/login-web.md +650 -0
  58. package/docs/memulai.md +419 -0
  59. package/docs/server-ke-server.md +287 -0
  60. package/docs/verifikasi-token.md +1219 -0
  61. package/docs/webhook.md +810 -0
  62. package/package.json +3 -2
@@ -0,0 +1,335 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { request as httpRequest } from "node:http";
3
+ import type { IncomingMessage, Server } from "node:http";
4
+ import { request as httpsRequest } from "node:https";
5
+ import { Readable, pipeline } from "node:stream";
6
+ import type { Duplex } from "node:stream";
7
+
8
+ import express from "express";
9
+ import type { Request, Response, Router } from "express";
10
+
11
+ import {
12
+ checkedAuth,
13
+ createBff,
14
+ createBffRouter,
15
+ csrfGuard,
16
+ requestRefresh,
17
+ route,
18
+ sameOriginOnly,
19
+ sendFailure,
20
+ sendJson,
21
+ } from "./bff-express.js";
22
+ import type { Bff } from "./bff-express.js";
23
+ import type { RedisLike } from "./bff-redis-lock.js";
24
+ import { checkSession } from "./bff-revocation.js";
25
+ import type { ForcedRefresh } from "./bff-revocation.js";
26
+
27
+ // #region http
28
+ /** A JSON body up to this size is buffered and can be retried. Anything else is streamed, never retried. */
29
+ const MAX_BUFFERED_BODY = 64 * 1024;
30
+ /**
31
+ * The browser's request headers the API gets: an allowlist. Everything else stays at the BFF: the
32
+ * browser's credentials, hop-by-hop headers, and headers the browser could forge to impersonate the
33
+ * BFF or another client.
34
+ */
35
+ const FORWARDED_REQUEST_HEADERS: readonly string[] = [
36
+ "accept",
37
+ "accept-language",
38
+ "content-type",
39
+ "content-length",
40
+ "if-none-match",
41
+ "if-modified-since",
42
+ "range",
43
+ "x-request-id",
44
+ ];
45
+ /** Your app's own extra request headers for its API, for example "x-client-version". Never credentials. */
46
+ export const APP_REQUEST_HEADERS: readonly string[] = [];
47
+ /** Never sent from the browser to the API, whatever the lists above say. */
48
+ function neverForwarded(name: string): boolean {
49
+ return (
50
+ ["authorization", "cookie", "host", "x-auth-agent", "fingerprint"].includes(name) ||
51
+ name.startsWith("x-mobile-") ||
52
+ name.startsWith("x-forwarded-")
53
+ );
54
+ }
55
+ /** The API's answer headers the browser gets. Set-Cookie of the API never reaches the browser. */
56
+ const PASSED_RESPONSE_HEADERS = [
57
+ "content-type",
58
+ "content-language",
59
+ "content-disposition",
60
+ "content-range",
61
+ "accept-ranges",
62
+ "cache-control",
63
+ "etag",
64
+ "last-modified",
65
+ "location",
66
+ "retry-after",
67
+ "www-authenticate",
68
+ "x-request-id",
69
+ ];
70
+
71
+ const isSmallJson = (req: IncomingMessage): boolean =>
72
+ (req.headers["content-type"] ?? "").startsWith("application/json") &&
73
+ Number(req.headers["content-length"] ?? Number.NaN) <= MAX_BUFFERED_BODY;
74
+
75
+ const hasBody = (req: IncomingMessage): boolean =>
76
+ req.headers["transfer-encoding"] !== undefined || Number(req.headers["content-length"] ?? "0") > 0;
77
+
78
+ /** The allowed browser headers plus `extra`, each name once, never one of the forbidden ones. */
79
+ export function allowedHeaders(req: IncomingMessage, extra: readonly string[] = []): Record<string, string> {
80
+ const headers: Record<string, string> = {};
81
+ for (const name of [...FORWARDED_REQUEST_HEADERS, ...APP_REQUEST_HEADERS, ...extra]) {
82
+ const value = req.headers[name];
83
+ if (value === undefined || neverForwarded(name)) continue;
84
+ headers[name] = Array.isArray(value) ? value.join(", ") : value;
85
+ }
86
+ // One id per request in the logs of the BFF and the API: the browser's, or a new one.
87
+ headers["x-request-id"] ??= randomUUID();
88
+ return headers;
89
+ }
90
+
91
+ /** A Web stream of the browser's body for fetch, typed alike with and without the DOM lib. */
92
+ function bodyStream(source: AsyncIterable<Uint8Array>): ReadableStream<Uint8Array> {
93
+ const chunks = source[Symbol.asyncIterator]();
94
+ return new ReadableStream<Uint8Array>({
95
+ async pull(controller) {
96
+ const next = await chunks.next();
97
+ if (next.done === true) controller.close();
98
+ else controller.enqueue(next.value);
99
+ },
100
+ async cancel() {
101
+ await chunks.return?.();
102
+ },
103
+ });
104
+ }
105
+
106
+ const isInvalidToken = (answer: globalThis.Response): boolean =>
107
+ answer.status === 401 && (answer.headers.get("www-authenticate") ?? "").includes("invalid_token");
108
+
109
+ /** A request of the BFF to the same request on the app's own API (`upstreamPath`), with the session's token. */
110
+ async function forward(bff: Bff, req: Request, res: Response, upstreamPath: string): Promise<void> {
111
+ const session = bff.store.read(req.headers.cookie);
112
+ const refresh = requestRefresh(bff, session);
113
+ try {
114
+ let auth = await checkedAuth(bff, session, refresh);
115
+ if (auth === null) {
116
+ sendJson(res, bff, session, 401, { error: "login_required" });
117
+ return;
118
+ }
119
+ const buffered: unknown = req.body;
120
+ // A copy as a plain Uint8Array: fetch accepts it whatever the project's lib setting.
121
+ const body = Buffer.isBuffer(buffered) ? new Uint8Array(buffered) : null;
122
+ const streamed = body === null && hasBody(req);
123
+ const call = async (token: string): Promise<globalThis.Response | null> => {
124
+ const headers = allowedHeaders(req);
125
+ // fetch sets the length of a buffered body itself (express.raw may have inflated it).
126
+ if (body !== null) delete headers["content-length"];
127
+ headers["authorization"] = `Bearer ${token}`;
128
+ // A variable, not a literal: `duplex` is missing from the DOM lib's RequestInit.
129
+ const init: RequestInit & { duplex: "half" } = {
130
+ method: req.method,
131
+ headers,
132
+ body: body ?? (streamed ? bodyStream(req) : null),
133
+ duplex: "half",
134
+ // A redirect of the API goes to the browser as it is (Location passed on), never followed here.
135
+ redirect: "manual",
136
+ };
137
+ try {
138
+ return await fetch(`${bff.apiOrigin}${upstreamPath}`, init);
139
+ } catch {
140
+ return null;
141
+ }
142
+ };
143
+
144
+ let answer = await call(auth.access_token);
145
+ // The API refused a token that looked valid: one forced refresh and one retry, only when the body
146
+ // can be sent again (never a streamed upload) and the revocation check has not already forced a
147
+ // refresh in this request (a second one would not give a newer token).
148
+ if (answer !== null && isInvalidToken(answer) && !streamed && !refresh.forced) {
149
+ await answer.body?.cancel();
150
+ auth = await refresh.force();
151
+ if (auth === null) {
152
+ sendJson(res, bff, session, 401, { error: "login_required" });
153
+ return;
154
+ }
155
+ answer = await call(auth.access_token);
156
+ }
157
+ if (answer === null) {
158
+ sendJson(res, bff, session, 502, { error: "bad_gateway" });
159
+ return;
160
+ }
161
+
162
+ // The API's status (a 503 or a 3xx too) and body are passed on as they are, with the session
163
+ // cookies that changed.
164
+ for (const cookie of bff.store.commit(session)) res.append("Set-Cookie", cookie);
165
+ res.status(answer.status);
166
+ for (const name of PASSED_RESPONSE_HEADERS) {
167
+ const value = answer.headers.get(name);
168
+ if (value !== null) res.setHeader(name, value);
169
+ }
170
+ if (answer.body === null) {
171
+ res.end();
172
+ return;
173
+ }
174
+ // pipeline closes the upstream request when the browser disconnects (long-polls, downloads).
175
+ pipeline(Readable.from(answer.body), res, () => {});
176
+ } catch (error) {
177
+ sendFailure(res, bff, session, error);
178
+ }
179
+ }
180
+
181
+ /** /api/* of the BFF to /api/* of the app's own API. */
182
+ export function apiProxy(bff: Bff): Router {
183
+ const proxy = express.Router();
184
+ // Buffers a small JSON body (it can be retried); anything else stays a stream.
185
+ proxy.use(express.raw({ type: isSmallJson, limit: MAX_BUFFERED_BODY }));
186
+ proxy.use(route((req, res) => forward(bff, req, res, `/api${req.url}`)));
187
+ return proxy;
188
+ }
189
+ // #endregion http
190
+
191
+ // #region socket
192
+ /** Socket.IO's default path. Under a sub-path the browser's client uses `path: "/crm/socket.io/"`. */
193
+ export const SOCKET_PATH = "/socket.io";
194
+ /** A token needs this many seconds of validity left to open a socket: the upgrade never refreshes. */
195
+ const SOCKET_MIN_VALIDITY_SECONDS = 60;
196
+ /** How often the sessions of open sockets are checked again against the revocation markers. */
197
+ const SOCKET_RECHECK_MS = 2 * 60_000;
198
+ /** The upgrade path cannot write cookies, so it cannot refresh: a needed refresh ends the attempt. */
199
+ const noRefresh: ForcedRefresh = { force: () => Promise.resolve(null), again: () => Promise.resolve(null) };
200
+ /** The WebSocket handshake headers, forwarded next to the allowed headers of the http region. */
201
+ const WEBSOCKET_HEADERS = ["sec-websocket-key", "sec-websocket-version", "sec-websocket-extensions", "sec-websocket-protocol"];
202
+
203
+ function refuse(socket: Duplex, status: number, reason: string): void {
204
+ socket.end(`HTTP/1.1 ${String(status)} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
205
+ }
206
+
207
+ /**
208
+ * Socket.IO's HTTP long-polling requests: `${basePath}/socket.io/*` of the BFF to `/socket.io/*` of the
209
+ * app's own API, through the same forward as /api/*. Every method must come from this app's pages
210
+ * (sameOriginOnly); there is no custom header to require. Polling bodies are not JSON, so they are
211
+ * streamed and never retried.
212
+ */
213
+ export function socketPollingProxy(bff: Bff): Router {
214
+ const polling = express.Router();
215
+ polling.use(sameOriginOnly(bff.appOrigin));
216
+ polling.use(route((req, res) => forward(bff, req, res, `${SOCKET_PATH}${req.url}`)));
217
+ return polling;
218
+ }
219
+
220
+ /**
221
+ * Forwards WebSocket upgrades under `${basePath}/socket.io/` to `/socket.io/` of the app's own API with
222
+ * the session's token. The upgrade never refreshes, because a renewed session could not be written back
223
+ * to the cookie from here: with no token, or one about to expire, it answers 401; the browser calls
224
+ * /auth/me (which refreshes the normal way) and connects again. Returns a function that stops the
225
+ * periodic re-check.
226
+ */
227
+ export function attachSocketProxy(server: Server, bff: Bff): () => void {
228
+ const prefix = `${bff.basePath}${SOCKET_PATH}`;
229
+ const open = new Map<Duplex, { cookie: string | undefined; upstream: Duplex }>();
230
+
231
+ async function upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {
232
+ // Only pages of this app may open a socket with the user's session. Browsers always send Origin here.
233
+ if (req.headers.origin !== bff.appOrigin) {
234
+ refuse(socket, 403, "Forbidden");
235
+ return;
236
+ }
237
+ const session = bff.store.read(req.headers.cookie);
238
+ const auth = session.data.auth;
239
+ if (auth === undefined || auth.expires_at - Math.floor(Date.now() / 1000) < SOCKET_MIN_VALIDITY_SECONDS) {
240
+ refuse(socket, 401, "Unauthorized");
241
+ return;
242
+ }
243
+ if (!(await checkSession(bff.redis, bff.markerKeys, session, noRefresh))) {
244
+ refuse(socket, 401, "Unauthorized");
245
+ return;
246
+ }
247
+
248
+ // The same path on the API: /crm/socket.io/?EIO=4 → /socket.io/?EIO=4.
249
+ const target = new URL(`${bff.apiOrigin}${(req.url ?? "/").slice(bff.basePath.length)}`);
250
+ // The same allowlist as the http region, plus the handshake; the browser's credentials never pass.
251
+ const headers: Record<string, string> = { ...allowedHeaders(req, WEBSOCKET_HEADERS), connection: "Upgrade", upgrade: "websocket" };
252
+ headers["authorization"] = `Bearer ${auth.access_token}`;
253
+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;
254
+ const upstreamRequest = send(target, { method: "GET", headers });
255
+
256
+ upstreamRequest.on("upgrade", (answer: IncomingMessage, upstream: Duplex, upstreamHead: Buffer) => {
257
+ const lines = [`HTTP/1.1 101 ${answer.statusMessage ?? "Switching Protocols"}`];
258
+ for (let index = 0; index + 1 < answer.rawHeaders.length; index += 2) {
259
+ const name = answer.rawHeaders[index] ?? "";
260
+ if (name.toLowerCase() !== "set-cookie") lines.push(`${name}: ${answer.rawHeaders[index + 1] ?? ""}`);
261
+ }
262
+ socket.write(`${lines.join("\r\n")}\r\n\r\n`);
263
+ if (upstreamHead.length > 0) socket.write(upstreamHead);
264
+ if (head.length > 0) upstream.write(head);
265
+ upstream.pipe(socket).pipe(upstream);
266
+ const close = (): void => {
267
+ open.delete(socket);
268
+ socket.destroy();
269
+ upstream.destroy();
270
+ };
271
+ for (const side of [socket, upstream]) side.on("close", close).on("error", close);
272
+ open.set(socket, { cookie: req.headers.cookie, upstream });
273
+ });
274
+ // The API answered without upgrading (for example 401): pass the status on and close.
275
+ upstreamRequest.on("response", (answer: IncomingMessage) => {
276
+ answer.resume();
277
+ refuse(socket, answer.statusCode ?? 502, answer.statusMessage ?? "Bad Gateway");
278
+ });
279
+ upstreamRequest.on("error", () => {
280
+ refuse(socket, 502, "Bad Gateway");
281
+ });
282
+ upstreamRequest.end();
283
+ }
284
+
285
+ server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {
286
+ const url = req.url ?? "";
287
+ // Other paths are left to the server's other upgrade listeners.
288
+ if (url !== prefix && !url.startsWith(`${prefix}/`) && !url.startsWith(`${prefix}?`)) return;
289
+ upgrade(req, socket, head).catch(() => {
290
+ // The markers could not be read: no socket now, the session is kept.
291
+ refuse(socket, 503, "Service Unavailable");
292
+ });
293
+ });
294
+
295
+ // A revoked session or a blocked user also closes the sockets that are already open.
296
+ const timer = setInterval(() => {
297
+ for (const [socket, entry] of open) {
298
+ const session = bff.store.read(entry.cookie);
299
+ checkSession(bff.redis, bff.markerKeys, session, noRefresh).then(
300
+ (ok) => {
301
+ if (ok) return;
302
+ socket.destroy();
303
+ entry.upstream.destroy();
304
+ },
305
+ () => {
306
+ // Redis unreachable: keep the socket and check again at the next round.
307
+ },
308
+ );
309
+ }
310
+ }, SOCKET_RECHECK_MS);
311
+ timer.unref();
312
+ return () => {
313
+ clearInterval(timer);
314
+ };
315
+ }
316
+ // #endregion socket
317
+
318
+ // #region server
319
+ /** The whole BFF: the auth routes, the API proxy (with the CSRF header) and the socket proxy. */
320
+ export function startBff(redis: RedisLike, port: number, basePath = ""): Server {
321
+ const bff = createBff(redis, basePath);
322
+ const routes = express.Router();
323
+ routes.use(createBffRouter(bff));
324
+ routes.use("/api", csrfGuard(bff.appOrigin, true), apiProxy(bff));
325
+ // Socket.IO long-polling: the same path on the API, Origin checked on every method.
326
+ routes.use(SOCKET_PATH, socketPollingProxy(bff));
327
+
328
+ const app = express();
329
+ app.disable("x-powered-by");
330
+ app.use(basePath === "" ? "/" : basePath, routes);
331
+ const server = app.listen(port);
332
+ server.on("close", attachSocketProxy(server, bff));
333
+ return server;
334
+ }
335
+ // #endregion server
@@ -0,0 +1,187 @@
1
+ import { createCipheriv, createDecipheriv, hkdfSync, randomBytes, randomUUID } from "node:crypto";
2
+ import { setTimeout as sleep } from "node:timers/promises";
3
+
4
+ import type { RefreshLockStore, TokenSet } from "@plasgos/oidc-client";
5
+
6
+ // #region redis-type
7
+ /** The three commands used; an ioredis client satisfies it. */
8
+ export interface RedisLike {
9
+ set(key: string, value: string, px: "PX", ms: number, nx: "NX"): Promise<"OK" | null>;
10
+ get(key: string): Promise<string | null>;
11
+ del(key: string): Promise<number>;
12
+ }
13
+ // #endregion redis-type
14
+
15
+ // #region seal
16
+ /** Seals and opens the stored token set. The app's own code: the stored value holds tokens. */
17
+ export interface TokenSealer {
18
+ seal(value: string): string;
19
+ /** The plaintext, or null when the value was not sealed with one of the secrets. */
20
+ open(sealed: string): string | null;
21
+ }
22
+
23
+ const keyOf = (secret: string): Buffer =>
24
+ Buffer.from(hkdfSync("sha256", secret, "bff-refresh-lock", "token-set", 32));
25
+
26
+ /**
27
+ * AES-256-GCM with a key derived from the session secrets: the first seals, all open (rotation,
28
+ * as SESSION_SECRET="new,old"). Output: base64url of IV (12 bytes) + tag (16 bytes) + ciphertext.
29
+ */
30
+ export function tokenSealer(secrets: readonly string[]): TokenSealer {
31
+ const keys = secrets.map(keyOf);
32
+ const [current] = keys;
33
+ if (current === undefined) throw new Error("tokenSealer needs at least one secret");
34
+ return {
35
+ seal(value) {
36
+ const iv = randomBytes(12);
37
+ const cipher = createCipheriv("aes-256-gcm", current, iv);
38
+ const body = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
39
+ return Buffer.concat([iv, cipher.getAuthTag(), body]).toString("base64url");
40
+ },
41
+ open(sealed) {
42
+ const bytes = Buffer.from(sealed, "base64url");
43
+ if (bytes.length < 29) return null;
44
+ for (const key of keys) {
45
+ try {
46
+ const decipher = createDecipheriv("aes-256-gcm", key, bytes.subarray(0, 12));
47
+ decipher.setAuthTag(bytes.subarray(12, 28));
48
+ return Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]).toString("utf8");
49
+ } catch {
50
+ // Not this key: try the next one.
51
+ }
52
+ }
53
+ return null;
54
+ },
55
+ };
56
+ }
57
+ // #endregion seal
58
+
59
+ // #region lock
60
+ /** No result and no free lock within `waitMs`. The route answers 503 and keeps the session. */
61
+ export class RefreshLockTimeoutError extends Error {
62
+ constructor() {
63
+ super("refresh lock: timed out waiting for another refresh");
64
+ this.name = "RefreshLockTimeoutError";
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Redis could not be reached while taking the lock or reading a stored result. Temporary: the route
70
+ * answers 503 and keeps the session (or keeps using an access token that is still valid).
71
+ */
72
+ export class RefreshLockUnavailableError extends Error {
73
+ constructor(options?: ErrorOptions) {
74
+ super("refresh lock: redis unavailable", options);
75
+ this.name = "RefreshLockUnavailableError";
76
+ }
77
+ }
78
+
79
+ /** A Redis call of the lock; its failure becomes RefreshLockUnavailableError, never a raw client error. */
80
+ async function lockCall<T>(call: () => Promise<T>): Promise<T> {
81
+ try {
82
+ return await call();
83
+ } catch (error) {
84
+ throw new RefreshLockUnavailableError({ cause: error });
85
+ }
86
+ }
87
+
88
+ export interface RedisRefreshLockOptions extends TokenSealer {
89
+ /** The app's own key prefix. Default "bff:refresh:". */
90
+ keyPrefix?: string | undefined;
91
+ /** Lock expiry: longer than the token request's timeout (10 s by default). Default 15 000 ms. */
92
+ lockMs?: number | undefined;
93
+ /** How long a caller waits for another caller's refresh. Default 12 000 ms. */
94
+ waitMs?: number | undefined;
95
+ /** Pause between two looks at Redis while waiting. Default 100 ms. */
96
+ pollMs?: number | undefined;
97
+ }
98
+
99
+ /** The stored token set, after its seal is checked; null when absent or not ours. */
100
+ function readTokenSet(sealed: string | null, sealer: TokenSealer): TokenSet | null {
101
+ const json = sealed === null ? null : sealer.open(sealed);
102
+ if (json === null) return null;
103
+ let value: unknown;
104
+ try {
105
+ value = JSON.parse(json);
106
+ } catch {
107
+ return null;
108
+ }
109
+ if (typeof value !== "object" || value === null) return null;
110
+ const { access_token, refresh_token, id_token, expires_in, scope } = value as Record<string, unknown>;
111
+ if (typeof access_token !== "string" || typeof expires_in !== "number") return null;
112
+ return {
113
+ access_token,
114
+ expires_in,
115
+ token_type: "Bearer",
116
+ ...(typeof refresh_token === "string" ? { refresh_token } : {}),
117
+ ...(typeof id_token === "string" ? { id_token } : {}),
118
+ ...(typeof scope === "string" ? { scope } : {}),
119
+ };
120
+ }
121
+
122
+ /**
123
+ * A RefreshLockStore shared by every instance of the app. Plasgos rotates the refresh token on every
124
+ * use, and a second use of the old token revokes the whole session. So for one refresh token
125
+ * (`key` is the SHA-256 the SDK hands in, never the token):
126
+ * - the caller that wins `SET lock NX PX` runs refresh() once, stores the result for `reuseMs`, then
127
+ * releases the lock;
128
+ * - every other caller, on this instance or another, waits for that result and returns it; it never
129
+ * calls refresh() itself while the lock is held;
130
+ * - a caller that finds neither a result nor a lock (the winner failed: a failed refresh did not
131
+ * consume the token) takes the lock itself;
132
+ * - a caller that waits longer than `waitMs` throws RefreshLockTimeoutError;
133
+ * - Redis failing before refresh() ran throws RefreshLockUnavailableError (the refresh token is unused);
134
+ * - a failure is never stored, and the stored token set is sealed.
135
+ * Callers on one instance share one promise per key, so one instance makes one round of Redis calls.
136
+ */
137
+ export function redisRefreshLock(redis: RedisLike, options: RedisRefreshLockOptions): RefreshLockStore {
138
+ const prefix = options.keyPrefix ?? "bff:refresh:";
139
+ const lockMs = options.lockMs ?? 15_000;
140
+ const waitMs = options.waitMs ?? 12_000;
141
+ const pollMs = options.pollMs ?? 100;
142
+ const inFlight = new Map<string, Promise<TokenSet>>();
143
+
144
+ async function runShared(key: string, refresh: () => Promise<TokenSet>, reuseMs: number): Promise<TokenSet> {
145
+ const resultKey = `${prefix}result:${key}`;
146
+ const lockKey = `${prefix}lock:${key}`;
147
+ const deadline = Date.now() + waitMs;
148
+ for (;;) {
149
+ const done = readTokenSet(await lockCall(() => redis.get(resultKey)), options);
150
+ if (done !== null) return done;
151
+
152
+ const owner = randomUUID();
153
+ if ((await lockCall(() => redis.set(lockKey, owner, "PX", lockMs, "NX"))) === "OK") {
154
+ try {
155
+ // Another instance may have stored its result between our first look and our lock.
156
+ const late = readTokenSet(await lockCall(() => redis.get(resultKey)), options);
157
+ if (late !== null) return late;
158
+ const tokens = await refresh();
159
+ // The old refresh token is spent now: whatever Redis does next, this caller gets the new set.
160
+ await redis.set(resultKey, options.seal(JSON.stringify(tokens)), "PX", reuseMs, "NX").catch(() => null);
161
+ return tokens;
162
+ } finally {
163
+ // Release only our own lock. The lock outlives the token request, so it is still ours here;
164
+ // if Redis fails now, the lock expires by itself after lockMs.
165
+ await redis
166
+ .get(lockKey)
167
+ .then((holder) => (holder === owner ? redis.del(lockKey) : 0))
168
+ .catch(() => 0);
169
+ }
170
+ }
171
+
172
+ if (Date.now() >= deadline) throw new RefreshLockTimeoutError();
173
+ await sleep(pollMs);
174
+ }
175
+ }
176
+
177
+ return {
178
+ run(key, refresh, reuseMs) {
179
+ const running = inFlight.get(key);
180
+ if (running !== undefined) return running;
181
+ const promise = runShared(key, refresh, reuseMs).finally(() => inFlight.delete(key));
182
+ inFlight.set(key, promise);
183
+ return promise;
184
+ },
185
+ };
186
+ }
187
+ // #endregion lock
@@ -0,0 +1,136 @@
1
+ import type { AuthState, SessionHandle } from "@plasgos/oidc-client/session";
2
+ import { readAccessTokenClaims } from "@plasgos/oidc-client/session";
3
+
4
+ import type { RedisLike } from "./bff-redis-lock.js";
5
+
6
+ // #region markers
7
+ /**
8
+ * The app's own marker keys. The app's webhook receiver writes them from the user.* events Plasgos
9
+ * sends to the app's webhook endpoint; the names and the prefix are yours.
10
+ */
11
+ export interface MarkerKeys {
12
+ /** Present when the Plasgos session `sid` was revoked. */
13
+ session(sid: string): string;
14
+ /** Present while the user is blocked. */
15
+ blockedUser(publicId: string): string;
16
+ /** The newest credential version Plasgos announced for the user, as text ("3"). */
17
+ credentialVersion(publicId: string): string;
18
+ }
19
+
20
+ export const markerKeys: MarkerKeys = {
21
+ session: (sid) => `myapp:revocation:sid:${sid}`,
22
+ blockedUser: (publicId) => `myapp:revocation:blocked:${publicId}`,
23
+ credentialVersion: (publicId) => `myapp:revocation:cv:${publicId}`,
24
+ };
25
+
26
+ /** Redis could not be read. The request is answered 503 and the session is kept. */
27
+ export class MarkerStoreUnavailableError extends Error {
28
+ constructor(options?: ErrorOptions) {
29
+ super("revocation markers unavailable", options);
30
+ this.name = "MarkerStoreUnavailableError";
31
+ }
32
+ }
33
+
34
+ interface Markers {
35
+ /** The session was revoked or the user is blocked. */
36
+ ended: boolean;
37
+ /** The stored credential version, or null when there is none. */
38
+ credentialVersion: number | null;
39
+ }
40
+
41
+ async function readMarkers(redis: RedisLike, keys: MarkerKeys, sid: string, publicId: string | null): Promise<Markers> {
42
+ let values: (string | null)[];
43
+ try {
44
+ values = await Promise.all([
45
+ redis.get(keys.session(sid)),
46
+ // Without a public id the user markers cannot be looked up. An audience whose sessions must end
47
+ // by user has Plasgos issue plasgos_public_id on its tokens.
48
+ publicId === null ? null : redis.get(keys.blockedUser(publicId)),
49
+ publicId === null ? null : redis.get(keys.credentialVersion(publicId)),
50
+ ]);
51
+ } catch (error) {
52
+ throw new MarkerStoreUnavailableError({ cause: error });
53
+ }
54
+ const [revokedSession, blocked, version] = values;
55
+ if (version === null || version === undefined) {
56
+ return { ended: revokedSession !== null || blocked !== null, credentialVersion: null };
57
+ }
58
+ const credentialVersion = Number(version);
59
+ // A marker this app did not write is a store problem, not a reason to log the user out.
60
+ if (!Number.isSafeInteger(credentialVersion)) throw new MarkerStoreUnavailableError();
61
+ return { ended: revokedSession !== null || blocked !== null, credentialVersion };
62
+ }
63
+ // #endregion markers
64
+
65
+ // #region check
66
+ /**
67
+ * The forced refreshes (ensureFresh({ force: true }) through the Redis lock) checkSession may run for
68
+ * one request. Each resolves the renewed auth, or null when Plasgos ended the session (the session is
69
+ * then destroyed).
70
+ */
71
+ export interface ForcedRefresh {
72
+ /** At most one per request: the revocation check and the proxy's retry share it. */
73
+ force(): Promise<AuthState | null>;
74
+ /**
75
+ * At most one per request, and only after force(): one more forced refresh with the refresh token
76
+ * force() stored, the newest one. The lock may hand force() a token set another request received
77
+ * a few seconds earlier, before the credential version went up; this one is a new refresh.
78
+ */
79
+ again(): Promise<AuthState | null>;
80
+ }
81
+
82
+ /**
83
+ * The per-request revocation check of a BFF, before the proxy or /auth/me answers. True: the session
84
+ * may go on (possibly with a renewed token). False: the session is destroyed here; the caller commits
85
+ * the cookies (every one cleared, with the store's Path) and answers 401.
86
+ *
87
+ * sid, cv and plasgos_public_id come from the access token the session holds, read without
88
+ * verification: the BFF received that token itself from the Plasgos token endpoint. They are the
89
+ * values of the token's issue, so they are read again after every refresh. An app that must end
90
+ * sessions by sid or by user without waiting for a request keeps its own index of sessions on the
91
+ * server.
92
+ *
93
+ * Throws MarkerStoreUnavailableError when Redis cannot be read: answer 503 and keep the session.
94
+ */
95
+ export async function checkSession<App extends object>(
96
+ redis: RedisLike,
97
+ keys: MarkerKeys,
98
+ session: SessionHandle<App>,
99
+ refresh: ForcedRefresh,
100
+ ): Promise<boolean> {
101
+ const auth = session.data.auth;
102
+ if (auth === undefined) return false;
103
+ const claims = readAccessTokenClaims(auth.access_token);
104
+ // A user token without a session id cannot be checked.
105
+ if (claims === null || claims.sid === null) {
106
+ session.destroy();
107
+ return false;
108
+ }
109
+
110
+ const markers = await readMarkers(redis, keys, claims.sid, claims.plasgos_public_id);
111
+ if (markers.ended) {
112
+ session.destroy();
113
+ return false;
114
+ }
115
+ const stored = markers.credentialVersion;
116
+ if (stored === null || (claims.cv !== null && claims.cv >= stored)) return true;
117
+
118
+ // The user's credentials changed after this token was issued: a forced refresh. Plasgos refuses it
119
+ // when the change ended the session; otherwise the new token carries the new version.
120
+ const below = (renewed: AuthState): boolean => {
121
+ const fresh = readAccessTokenClaims(renewed.access_token);
122
+ return fresh === null || fresh.cv === null || fresh.cv < stored;
123
+ };
124
+ let renewed = await refresh.force();
125
+ if (renewed === null) return false;
126
+ // Still below: the lock may have reused a token set from before the marker. One new refresh with the
127
+ // newest refresh token; never an older one, which Plasgos would treat as reuse.
128
+ if (below(renewed)) renewed = await refresh.again();
129
+ if (renewed === null) return false;
130
+ if (below(renewed)) {
131
+ session.destroy();
132
+ return false;
133
+ }
134
+ return true;
135
+ }
136
+ // #endregion check
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The problems of a ConfigError, or null when `error` is something else. `instanceof ConfigError`
3
+ * works too when the class is imported from `@plasgos/oidc-client`; checking the name also works
4
+ * when the app loads the SDK through both `import` and `require`.
5
+ */
6
+ export function configProblems(error: unknown): string[] | null {
7
+ if (!(error instanceof Error) || error.name !== "ConfigError") return null;
8
+ const problems: unknown = "problems" in error ? error.problems : undefined;
9
+ if (!Array.isArray(problems)) return [error.message];
10
+ return problems.filter((problem): problem is string => typeof problem === "string");
11
+ }
12
+
13
+ /** Runs `create` at start. A configuration mistake stops the process with every problem printed. */
14
+ export function createOrExit<T>(create: () => T): T {
15
+ try {
16
+ return create();
17
+ } catch (error) {
18
+ const problems = configProblems(error);
19
+ if (problems === null) throw error;
20
+ process.stderr.write("Plasgos configuration is invalid:\n");
21
+ for (const problem of problems) process.stderr.write(`- ${problem}\n`);
22
+ process.exit(1);
23
+ }
24
+ }