@plasgos/oidc-client 0.0.0-stage → 0.1.0-next.2

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 (47) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +15 -0
  3. package/README.md +145 -2
  4. package/dist/index.cjs +884 -0
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.cts +33 -0
  7. package/dist/index.d.ts +33 -0
  8. package/dist/index.js +860 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/service.cjs +432 -0
  11. package/dist/service.cjs.map +1 -0
  12. package/dist/service.d.cts +88 -0
  13. package/dist/service.d.ts +88 -0
  14. package/dist/service.js +419 -0
  15. package/dist/service.js.map +1 -0
  16. package/dist/session.cjs +601 -0
  17. package/dist/session.cjs.map +1 -0
  18. package/dist/session.d.cts +289 -0
  19. package/dist/session.d.ts +289 -0
  20. package/dist/session.js +568 -0
  21. package/dist/session.js.map +1 -0
  22. package/dist/types-JE0OMyoi.d.cts +375 -0
  23. package/dist/types-JE0OMyoi.d.ts +375 -0
  24. package/docs/consumers.md +90 -0
  25. package/docs/contoh-hitungcuan.md +255 -0
  26. package/docs/contoh-plaslink.md +244 -0
  27. package/docs/error.md +428 -0
  28. package/docs/examples/auth-verify-readme.ts +18 -0
  29. package/docs/examples/config-error.ts +24 -0
  30. package/docs/examples/env.ts +99 -0
  31. package/docs/examples/failure-log.ts +18 -0
  32. package/docs/examples/login-client.ts +46 -0
  33. package/docs/examples/login-flow.ts +186 -0
  34. package/docs/examples/plaslink-connect.ts +48 -0
  35. package/docs/examples/readme.ts +60 -0
  36. package/docs/examples/service-client.ts +105 -0
  37. package/docs/examples/session-store.ts +53 -0
  38. package/docs/examples/webhook-express.ts +46 -0
  39. package/docs/examples/webhook-fetch.ts +60 -0
  40. package/docs/examples/webhook-nestjs.ts +59 -0
  41. package/docs/examples/webhook-testing.ts +60 -0
  42. package/docs/examples/webhook-verifier.ts +143 -0
  43. package/docs/login-web.md +618 -0
  44. package/docs/memulai.md +339 -0
  45. package/docs/server-ke-server.md +275 -0
  46. package/docs/webhook.md +625 -0
  47. package/package.json +67 -3
package/dist/index.cjs ADDED
@@ -0,0 +1,884 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ ConfigError: () => import_auth_shared9.ConfigError,
24
+ OidcError: () => import_auth_shared9.OidcError,
25
+ accessTokenExpiry: () => accessTokenExpiry,
26
+ createOidcClient: () => createOidcClient,
27
+ memoryLockStore: () => memoryLockStore
28
+ });
29
+ module.exports = __toCommonJS(src_exports);
30
+
31
+ // src/core/callback.ts
32
+ var import_auth_shared4 = require("@plasgos/auth-shared");
33
+
34
+ // src/core/failure.ts
35
+ var PLAIN = /^[\w.:-]{1,128}$/;
36
+ var PLAIN_PATH = /^\/[\w./~-]{0,255}$/;
37
+ var plain = (value) => value !== null && PLAIN.test(value) ? value : null;
38
+ var pathOnly = (path) => {
39
+ if (path === null) return null;
40
+ const bare = path.split(/[?#]/, 1)[0] ?? "";
41
+ return PLAIN_PATH.test(bare) ? bare : null;
42
+ };
43
+ function sanitizeEvent(event) {
44
+ return {
45
+ environment: event.environment,
46
+ operation: event.operation,
47
+ reason: event.reason,
48
+ method: plain(event.method),
49
+ path: pathOnly(event.path),
50
+ status: Number.isInteger(event.status) ? event.status : null,
51
+ requestId: plain(event.requestId),
52
+ providerError: plain(event.providerError)
53
+ };
54
+ }
55
+ var ignore = () => void 0;
56
+ function report(hook, event) {
57
+ if (hook === void 0) return;
58
+ try {
59
+ const run = hook;
60
+ const result = run(sanitizeEvent(event));
61
+ if (result instanceof Promise) result.catch(ignore);
62
+ } catch {
63
+ }
64
+ }
65
+
66
+ // src/core/id-token.ts
67
+ var import_auth_shared = require("@plasgos/auth-shared");
68
+ var SKEW_SECONDS = 60;
69
+ var MAX_IAT_AGE_SECONDS = 600;
70
+ var MAX_EXTRA_STRING_CHARS = 512;
71
+ var SEGMENT = /^[A-Za-z0-9_-]+$/;
72
+ var invalid = () => new import_auth_shared.OidcError("id_token_invalid");
73
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
74
+ var own = (record, key) => Object.hasOwn(record, key) ? record[key] : void 0;
75
+ function decodeSegment(segment) {
76
+ if (segment === void 0 || !SEGMENT.test(segment)) throw invalid();
77
+ try {
78
+ return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
79
+ } catch (error) {
80
+ if (error instanceof SyntaxError) throw invalid();
81
+ throw error;
82
+ }
83
+ }
84
+ var isOptionalString = (value) => value === void 0 || typeof value === "string";
85
+ var isAudience = (value) => typeof value === "string" || Array.isArray(value) && value.every((entry) => typeof entry === "string");
86
+ function shapeOf(payload) {
87
+ if (!isRecord(payload)) return null;
88
+ const [iss, sub, aud, azp] = [own(payload, "iss"), own(payload, "sub"), own(payload, "aud"), own(payload, "azp")];
89
+ const [exp, iat, nonce, authTime] = [own(payload, "exp"), own(payload, "iat"), own(payload, "nonce"), own(payload, "auth_time")];
90
+ const [name, picture, email] = [own(payload, "name"), own(payload, "picture"), own(payload, "email")];
91
+ if (typeof iss !== "string" || typeof sub !== "string" || sub === "" || !isAudience(aud)) return null;
92
+ if (!isOptionalString(azp) || typeof nonce !== "string") return null;
93
+ if (typeof exp !== "number" || !Number.isFinite(exp) || typeof iat !== "number" || !Number.isFinite(iat)) return null;
94
+ if (authTime !== void 0 && !(typeof authTime === "number" && Number.isSafeInteger(authTime) && authTime >= 0)) {
95
+ return null;
96
+ }
97
+ if (!isOptionalString(name) || !isOptionalString(picture) || !isOptionalString(email)) return null;
98
+ return {
99
+ iss,
100
+ sub,
101
+ aud,
102
+ ...azp !== void 0 ? { azp } : {},
103
+ exp,
104
+ iat,
105
+ nonce,
106
+ ...authTime !== void 0 ? { auth_time: authTime } : {},
107
+ ...name !== void 0 ? { name } : {},
108
+ ...picture !== void 0 ? { picture } : {},
109
+ ...email !== void 0 ? { email } : {}
110
+ };
111
+ }
112
+ function extraOf(payload, names) {
113
+ const extra = /* @__PURE__ */ Object.create(null);
114
+ for (const name of names) {
115
+ const value = own(payload, name);
116
+ const kept = typeof value === "string" && value.length <= MAX_EXTRA_STRING_CHARS || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
117
+ if (kept) extra[name] = value;
118
+ }
119
+ return Object.freeze(extra);
120
+ }
121
+ function verifyIdToken(config, idToken, expected) {
122
+ if (idToken.length > import_auth_shared.MAX_JWT_LENGTH) throw invalid();
123
+ const parts = idToken.split(".");
124
+ if (parts.length !== 3) throw invalid();
125
+ const header = decodeSegment(parts[0]);
126
+ if (!isRecord(header) || own(header, "alg") !== import_auth_shared.SIGNING_ALG) throw invalid();
127
+ const payload = decodeSegment(parts[1]);
128
+ if (!SEGMENT.test(parts[2] ?? "")) throw invalid();
129
+ const claims = shapeOf(payload);
130
+ if (claims === null || !isRecord(payload)) throw invalid();
131
+ const nowSec = expected.now / 1e3;
132
+ const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
133
+ const ok = claims.iss === config.issuer && audiences.includes(config.clientId) && (audiences.length === 1 || claims.azp === config.clientId) && (claims.azp === void 0 || claims.azp === config.clientId) && claims.exp > nowSec - SKEW_SECONDS && claims.iat <= nowSec + SKEW_SECONDS && claims.iat >= nowSec - MAX_IAT_AGE_SECONDS && (0, import_auth_shared.safeEqual)(claims.nonce, expected.nonce);
134
+ if (!ok) throw invalid();
135
+ if (expected.maxAge !== void 0) {
136
+ if (claims.auth_time === void 0 || !(nowSec - claims.auth_time <= expected.maxAge + SKEW_SECONDS)) throw invalid();
137
+ }
138
+ return { ...claims, extra: extraOf(payload, config.extraClaims) };
139
+ }
140
+
141
+ // src/core/token.ts
142
+ var import_auth_shared3 = require("@plasgos/auth-shared");
143
+
144
+ // src/core/http.ts
145
+ var import_auth_shared2 = require("@plasgos/auth-shared");
146
+ var MAX_RESPONSE_BYTES = 16384;
147
+ var ignore2 = () => void 0;
148
+ var isRedirect = (res) => res.type === "opaqueredirect" || res.status >= 300 && res.status < 400;
149
+ async function send(url, init, options) {
150
+ const { method, path } = options.call;
151
+ const controller = new AbortController();
152
+ const timer = setTimeout(() => {
153
+ controller.abort();
154
+ }, options.timeoutMs);
155
+ const done = () => {
156
+ clearTimeout(timer);
157
+ };
158
+ let res;
159
+ try {
160
+ res = await options.fetch(url, { ...init, redirect: "manual", signal: controller.signal });
161
+ } catch {
162
+ done();
163
+ throw new import_auth_shared2.OidcError("unavailable", { method, path, status: null, requestId: null });
164
+ }
165
+ if (isRedirect(res)) {
166
+ done();
167
+ await res.body?.cancel().catch(ignore2);
168
+ const at = upstreamOf(method, path, res);
169
+ throw new import_auth_shared2.OidcError("provider_error", res.status === 0 ? { ...at, status: null } : at);
170
+ }
171
+ return { res, done, timedOut: () => controller.signal.aborted };
172
+ }
173
+ async function readCappedBody(res, maxBytes) {
174
+ const declared = Number(res.headers.get("content-length") ?? "0");
175
+ if (declared > maxBytes) {
176
+ await res.body?.cancel().catch(ignore2);
177
+ return { kind: "too_large" };
178
+ }
179
+ const chunks = [];
180
+ let size = 0;
181
+ try {
182
+ const reader = res.body?.getReader();
183
+ while (reader !== void 0) {
184
+ const chunk = await reader.read();
185
+ const value = chunk.value;
186
+ if (chunk.done || value === void 0) break;
187
+ size += value.byteLength;
188
+ if (size > maxBytes) {
189
+ await reader.cancel().catch(ignore2);
190
+ return { kind: "too_large" };
191
+ }
192
+ chunks.push(value);
193
+ }
194
+ } catch {
195
+ return { kind: "unreadable" };
196
+ }
197
+ return { kind: "bytes", bytes: Buffer.concat(chunks) };
198
+ }
199
+ async function readJson(res) {
200
+ const body = await readCappedBody(res, MAX_RESPONSE_BYTES);
201
+ if (body.kind === "too_large") return void 0;
202
+ if (body.kind === "unreadable") return null;
203
+ try {
204
+ return JSON.parse(body.bytes.toString("utf8"));
205
+ } catch (error) {
206
+ if (error instanceof SyntaxError) return null;
207
+ throw error;
208
+ }
209
+ }
210
+ function upstreamOf(method, path, res) {
211
+ return { method, path, status: res.status, requestId: plain(res.headers.get("x-request-id")) };
212
+ }
213
+ function failOnStatus(res, body, at) {
214
+ if (res.status >= 500 || res.status === 429) throw new import_auth_shared2.OidcError("unavailable", at);
215
+ if (body === void 0) throw new import_auth_shared2.OidcError("provider_error", at);
216
+ }
217
+ async function requestJson(url, init, options) {
218
+ const { res, done, timedOut } = await send(url, init, options);
219
+ const body = await readJson(res).finally(done);
220
+ const at = upstreamOf(options.call.method, options.call.path, res);
221
+ if (timedOut()) throw new import_auth_shared2.OidcError("unavailable", at);
222
+ return { res, body, at };
223
+ }
224
+
225
+ // src/core/token.ts
226
+ var TOKEN_CALL = { method: "POST", path: import_auth_shared3.OIDC_PATHS.token };
227
+ var CONFIG_ERRORS = /* @__PURE__ */ new Set([
228
+ "invalid_client",
229
+ "unauthorized_client",
230
+ "invalid_scope",
231
+ "unsupported_grant_type"
232
+ ]);
233
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
234
+ var own2 = (record, key) => Object.hasOwn(record, key) ? record[key] : void 0;
235
+ var HEADER_SAFE = /^[\x21-\x7e]+$/;
236
+ var isToken = (value) => typeof value === "string" && HEADER_SAFE.test(value);
237
+ function tokenSetOf(body, refreshTokenRequired) {
238
+ if (!isRecord2(body)) return null;
239
+ const accessToken = own2(body, "access_token");
240
+ const refreshToken = own2(body, "refresh_token");
241
+ const idToken = own2(body, "id_token");
242
+ const expiresIn = own2(body, "expires_in");
243
+ const tokenType = own2(body, "token_type");
244
+ const scope = own2(body, "scope");
245
+ if (!isToken(accessToken)) return null;
246
+ if (refreshToken === void 0 && refreshTokenRequired) return null;
247
+ if (refreshToken !== void 0 && !isToken(refreshToken)) return null;
248
+ if (idToken !== void 0 && !isToken(idToken)) return null;
249
+ if (typeof expiresIn !== "number" || !Number.isSafeInteger(expiresIn) || expiresIn <= 0) return null;
250
+ if (typeof tokenType !== "string" || tokenType.toLowerCase() !== "bearer") return null;
251
+ if (scope !== void 0 && typeof scope !== "string") return null;
252
+ return {
253
+ access_token: accessToken,
254
+ ...refreshToken !== void 0 ? { refresh_token: refreshToken } : {},
255
+ ...idToken !== void 0 ? { id_token: idToken } : {},
256
+ expires_in: expiresIn,
257
+ token_type: "Bearer",
258
+ ...scope !== void 0 ? { scope } : {}
259
+ };
260
+ }
261
+ var reasonOf = (code) => {
262
+ if (code === "invalid_grant" || code === "invalid_target") return code;
263
+ return code !== null && CONFIG_ERRORS.has(code) ? "config_invalid" : "provider_error";
264
+ };
265
+ async function tokenEndpointRequest(endpoint, operation, params) {
266
+ let providerError = null;
267
+ try {
268
+ const form = new URLSearchParams({ ...params, ...endpoint.resource !== null ? { resource: endpoint.resource } : {} });
269
+ const { res, body, at } = await requestJson(
270
+ `${endpoint.origin}${TOKEN_CALL.path}`,
271
+ {
272
+ method: TOKEN_CALL.method,
273
+ headers: {
274
+ Authorization: (0, import_auth_shared3.basicAuthHeader)(endpoint.clientId, endpoint.clientSecret),
275
+ "Content-Type": "application/x-www-form-urlencoded",
276
+ Accept: "application/json"
277
+ },
278
+ body: form.toString()
279
+ },
280
+ { timeoutMs: endpoint.timeoutMs, fetch: endpoint.fetch, call: TOKEN_CALL }
281
+ );
282
+ if (!res.ok && isRecord2(body)) {
283
+ const code = own2(body, "error");
284
+ if (typeof code === "string") providerError = code;
285
+ }
286
+ failOnStatus(res, body, at);
287
+ if (!res.ok) throw new import_auth_shared3.OidcError(reasonOf(providerError), at);
288
+ const tokens = tokenSetOf(body, endpoint.refreshTokenRequired);
289
+ if (tokens === null) throw new import_auth_shared3.OidcError("provider_error", at);
290
+ return tokens;
291
+ } catch (error) {
292
+ if (error instanceof import_auth_shared3.OidcError) {
293
+ report(endpoint.onFailure, {
294
+ environment: endpoint.environment,
295
+ operation,
296
+ reason: error.reason,
297
+ method: TOKEN_CALL.method,
298
+ path: TOKEN_CALL.path,
299
+ status: error.upstream?.status ?? null,
300
+ requestId: error.upstream?.requestId ?? null,
301
+ providerError
302
+ });
303
+ }
304
+ throw error;
305
+ }
306
+ }
307
+ function tokenRequest(config, operation, params) {
308
+ return tokenEndpointRequest(
309
+ {
310
+ environment: config.environment,
311
+ origin: config.backchannelUrl ?? config.issuer,
312
+ clientId: config.clientId,
313
+ clientSecret: config.clientSecret,
314
+ resource: config.resource,
315
+ timeoutMs: config.timeouts.tokenMs,
316
+ fetch: config.fetch,
317
+ onFailure: config.onFailure,
318
+ refreshTokenRequired: config.profile === "first-party"
319
+ },
320
+ operation,
321
+ params
322
+ );
323
+ }
324
+
325
+ // src/core/callback.ts
326
+ var CLOCK_SKEW_MS = 5e3;
327
+ var MAX_AGE_MS = 6e5;
328
+ var refuse = (reason, providerError = null) => ({
329
+ ok: false,
330
+ reason,
331
+ providerError
332
+ });
333
+ var parseUrl = (url) => {
334
+ if (url instanceof URL) return url;
335
+ return typeof url === "string" && URL.canParse(url) ? new URL(url) : null;
336
+ };
337
+ var isSecret = (value) => typeof value === "string" && value !== "";
338
+ var isUsable = (transaction) => {
339
+ if (typeof transaction !== "object" || transaction === null) return false;
340
+ const { state, nonce, code_verifier: verifier, created_at: createdAt } = transaction;
341
+ return isSecret(state) && isSecret(nonce) && isSecret(verifier) && typeof createdAt === "number" && Number.isFinite(createdAt);
342
+ };
343
+ function checkCallback(config, url, transaction, now) {
344
+ const parsed2 = parseUrl(url);
345
+ if (parsed2 === null) return refuse("missing");
346
+ if (!isUsable(transaction)) return refuse("missing");
347
+ const tx = transaction;
348
+ const age = now - tx.created_at;
349
+ if (!(age >= -CLOCK_SKEW_MS && age <= MAX_AGE_MS)) return refuse("expired");
350
+ const query = parsed2.searchParams;
351
+ const state = query.get("state");
352
+ if (state === null || !(0, import_auth_shared4.safeEqual)(state, tx.state)) return refuse("state_mismatch");
353
+ const iss = query.get("iss");
354
+ if (iss !== null && iss !== config.issuer) return refuse("provider_error");
355
+ const error = query.get("error");
356
+ if (error !== null) return refuse(error === "invalid_target" ? "invalid_target" : "provider_error", error);
357
+ const codes = query.getAll("code");
358
+ const code = codes[0];
359
+ if (codes.length !== 1 || code === void 0 || code === "") return refuse("missing");
360
+ return { ok: true, code, transaction: tx };
361
+ }
362
+ function callbackFailure(config, reason, providerError) {
363
+ report(config.onFailure, {
364
+ environment: config.environment,
365
+ operation: "callback",
366
+ reason,
367
+ method: "GET",
368
+ path: new URL(config.redirectUri).pathname,
369
+ status: null,
370
+ requestId: null,
371
+ providerError
372
+ });
373
+ return new import_auth_shared4.OidcError(reason);
374
+ }
375
+ async function handleCallback(config, url, transaction, options) {
376
+ const now = options?.now ?? Date.now();
377
+ const checked = checkCallback(config, url, transaction, now);
378
+ if (!checked.ok) throw callbackFailure(config, checked.reason, checked.providerError);
379
+ const tx = checked.transaction;
380
+ const tokens = await tokenRequest(config, "token", {
381
+ grant_type: "authorization_code",
382
+ code: checked.code,
383
+ redirect_uri: config.redirectUri,
384
+ code_verifier: tx.code_verifier
385
+ });
386
+ if (tokens.id_token === void 0) throw callbackFailure(config, "id_token_invalid", null);
387
+ let claims;
388
+ try {
389
+ claims = verifyIdToken(config, tokens.id_token, {
390
+ nonce: tx.nonce,
391
+ now,
392
+ ...tx.max_age !== void 0 ? { maxAge: tx.max_age } : {}
393
+ });
394
+ } catch (error) {
395
+ if (error instanceof import_auth_shared4.OidcError) throw callbackFailure(config, error.reason, null);
396
+ throw error;
397
+ }
398
+ return { tokens, claims, transaction: tx };
399
+ }
400
+
401
+ // src/core/config.ts
402
+ var import_auth_shared5 = require("@plasgos/auth-shared");
403
+
404
+ // src/core/refresh-lock.ts
405
+ function memoryLockStore(options = {}) {
406
+ const now = options.now ?? Date.now;
407
+ const locks = /* @__PURE__ */ new Map();
408
+ return {
409
+ run(key, refresh2, reuseMs) {
410
+ const t = now();
411
+ for (const [storedKey, entry2] of locks) {
412
+ if (entry2.settledAt !== void 0 && t - entry2.settledAt >= entry2.reuseMs) locks.delete(storedKey);
413
+ }
414
+ const hit = locks.get(key);
415
+ if (hit) return hit.promise;
416
+ const entry = { promise: refresh2(), reuseMs };
417
+ locks.set(key, entry);
418
+ entry.promise.then(
419
+ () => {
420
+ entry.settledAt = now();
421
+ },
422
+ () => {
423
+ if (locks.get(key) === entry) locks.delete(key);
424
+ }
425
+ );
426
+ return entry.promise;
427
+ }
428
+ };
429
+ }
430
+
431
+ // src/core/config.ts
432
+ var DEFAULT_TOKEN_MS = 1e4;
433
+ var DEFAULT_LOGOUT_MS = 3e3;
434
+ var MAX_TIMEOUT_MS = 6e4;
435
+ var CLAIM_NAME = /^[A-Za-z0-9_:.-]{1,64}$/;
436
+ var RESERVED_CLAIMS = /* @__PURE__ */ new Set([
437
+ "iss",
438
+ "sub",
439
+ "aud",
440
+ "azp",
441
+ "exp",
442
+ "iat",
443
+ "nbf",
444
+ "jti",
445
+ "nonce",
446
+ "auth_time",
447
+ "at_hash",
448
+ "c_hash",
449
+ "s_hash",
450
+ "name",
451
+ "picture",
452
+ "email",
453
+ "__proto__",
454
+ "constructor",
455
+ "prototype"
456
+ ]);
457
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
458
+ var isBlank = (value) => typeof value === "string" && value.trim() === "";
459
+ var distinctScopes = (scopes) => Object.freeze([...new Set(Array.isArray(scopes) ? scopes.filter((scope) => typeof scope === "string") : [])]);
460
+ var globalFetch = (input, init) => globalThis.fetch(input, init);
461
+ function parsed(problems, parse) {
462
+ try {
463
+ return parse();
464
+ } catch (error) {
465
+ if (!(error instanceof import_auth_shared5.ConfigError)) throw error;
466
+ problems.push(...error.problems);
467
+ return void 0;
468
+ }
469
+ }
470
+ function timeoutsOf(problems, raw, defaults) {
471
+ const given = raw ?? {};
472
+ if (!isObject(given)) problems.push("timeouts must be an object");
473
+ const resolved = { ...defaults };
474
+ for (const name of Object.keys(defaults)) {
475
+ const value = isObject(given) ? given[name] : void 0;
476
+ if (value === void 0) continue;
477
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_TIMEOUT_MS) {
478
+ resolved[name] = value;
479
+ } else {
480
+ problems.push(`timeouts.${name} must be an integer from 1 to ${String(MAX_TIMEOUT_MS)}`);
481
+ }
482
+ }
483
+ return resolved;
484
+ }
485
+ function redirectUriProblem(value, field, allowInsecureHttp) {
486
+ if (value === "") return `${field} is required`;
487
+ if (value.includes("*")) return `${field} must not contain a wildcard`;
488
+ if (!URL.canParse(value)) return `${field} must be an absolute URL`;
489
+ if (/[\u0000- \u007f\\]/.test(value)) {
490
+ return `${field} must not contain whitespace, control characters or a backslash`;
491
+ }
492
+ const url = new URL(value);
493
+ if (url.hash || value.includes("#")) return `${field} must not contain a fragment`;
494
+ const authority = /^[a-z][a-z0-9+.-]*:\/\/([^/?]*)/i.exec(value)?.[1] ?? "";
495
+ if (url.username || url.password || authority.includes("@")) return `${field} must not contain credentials`;
496
+ if (url.protocol !== "https:" && !(allowInsecureHttp && url.protocol === "http:")) return `${field} must use https`;
497
+ if (!/^https?:\/\//i.test(value)) return `${field} must be an absolute URL`;
498
+ return void 0;
499
+ }
500
+ function redirectUriOf(problems, raw, field, allowInsecureHttp) {
501
+ const value = raw?.trim() ?? "";
502
+ const problem = redirectUriProblem(value, field, allowInsecureHttp);
503
+ if (problem === void 0) return value;
504
+ problems.push(problem);
505
+ return void 0;
506
+ }
507
+ function resolveConfig(raw) {
508
+ if (!isObject(raw)) throw new import_auth_shared5.ConfigError(["options must be an object"]);
509
+ const problems = [];
510
+ const text = (field) => {
511
+ const value = raw[field];
512
+ if (value === void 0 || typeof value === "string") return value;
513
+ problems.push(`${field} must be a string`);
514
+ return void 0;
515
+ };
516
+ const given = (field) => raw[field] !== void 0;
517
+ const present = (field) => given(field) && !isBlank(raw[field]);
518
+ const optional = (field) => present(field) ? text(field) : void 0;
519
+ const required = (field) => {
520
+ const value = text(field);
521
+ const blank = isBlank(value);
522
+ if (blank || !given(field)) problems.push(`${field} is required`);
523
+ return blank ? void 0 : value;
524
+ };
525
+ const allowInsecureHttp = raw["allowInsecureHttp"] === true;
526
+ const issuerRaw = text("issuer");
527
+ const issuer = given("issuer") && issuerRaw === void 0 ? void 0 : parsed(problems, () => (0, import_auth_shared5.parseIssuer)(issuerRaw, { field: "issuer", allowInsecureHttp }));
528
+ const backchannelRaw = optional("backchannelUrl");
529
+ const backchannelUrl = backchannelRaw === void 0 ? void 0 : parsed(problems, () => (0, import_auth_shared5.parseIssuer)(backchannelRaw, { field: "backchannelUrl", allowInsecureHttp: true }));
530
+ const clientId = required("clientId");
531
+ const clientSecret = required("clientSecret");
532
+ const redirectRaw = text("redirectUri");
533
+ const redirectUri = given("redirectUri") && redirectRaw === void 0 ? void 0 : redirectUriOf(problems, redirectRaw, "redirectUri", allowInsecureHttp);
534
+ const postLogoutRaw = optional("postLogoutRedirectUri");
535
+ const postLogoutRedirectUri = postLogoutRaw === void 0 ? void 0 : redirectUriOf(problems, postLogoutRaw, "postLogoutRedirectUri", allowInsecureHttp);
536
+ const profileRaw = text("profile");
537
+ const profile = profileRaw === "first-party" || profileRaw === "third-party" ? profileRaw : void 0;
538
+ const scopesRaw = raw["scopes"];
539
+ problems.push(...(0, import_auth_shared5.userScopeProblems)(scopesRaw, { profile: profile ?? "first-party", resource: present("resource") }));
540
+ if (profile === void 0 && !(given("profile") && profileRaw === void 0)) {
541
+ problems.push('profile must be "first-party" or "third-party"');
542
+ }
543
+ const resourceRaw = optional("resource");
544
+ const resource = resourceRaw === void 0 ? void 0 : parsed(problems, () => (0, import_auth_shared5.parseAudience)(resourceRaw, { field: "resource", allowInsecureHttp }));
545
+ if (present("resource") && profile === "third-party") {
546
+ problems.push('resource is not allowed for profile "third-party"');
547
+ }
548
+ const endSessionRaw = text("endSession");
549
+ const endSession2 = endSessionRaw ?? (given("endSession") ? void 0 : "redirect");
550
+ const endSessionKnown = endSession2 === "redirect" || endSession2 === "form-post";
551
+ const logoutTicketRaw = raw["logoutTicket"];
552
+ if (logoutTicketRaw !== void 0 && typeof logoutTicketRaw !== "boolean") {
553
+ problems.push("logoutTicket must be a boolean");
554
+ } else if (logoutTicketRaw === true) {
555
+ if (profile === "third-party") {
556
+ problems.push('logoutTicket is not allowed for profile "third-party"');
557
+ } else if (endSession2 === "form-post") {
558
+ problems.push('logoutTicket is not used with endSession "form-post"');
559
+ } else if (!present("backchannelUrl")) {
560
+ problems.push("logoutTicket requires backchannelUrl (the internal Plasgos server URL)");
561
+ }
562
+ }
563
+ const logoutTicket = logoutTicketRaw === true || logoutTicketRaw === void 0 && profile === "first-party" && endSession2 === "redirect" && backchannelUrl !== void 0;
564
+ if (endSession2 !== void 0 && !endSessionKnown) {
565
+ problems.push('endSession must be "redirect" or "form-post"');
566
+ } else if (
567
+ // Sandbox is left alone: local development runs the app and the issuer on two ports. The
568
+ // provider still answers a cross-origin form POST with 403.
569
+ raw["environment"] === "production" && endSession2 === "form-post" && issuer !== void 0 && redirectUri !== void 0 && new URL(redirectUri).origin !== issuer
570
+ ) {
571
+ problems.push('endSession "form-post" requires redirectUri on the issuer origin');
572
+ }
573
+ const extraClaimsRaw = raw["extraClaims"] === void 0 ? [] : raw["extraClaims"];
574
+ const extraClaims = Array.isArray(extraClaimsRaw) && extraClaimsRaw.every(
575
+ (name) => typeof name === "string" && CLAIM_NAME.test(name) && !RESERVED_CLAIMS.has(name)
576
+ ) ? [...new Set(extraClaimsRaw)] : void 0;
577
+ if (extraClaims === void 0) problems.push("extraClaims contains an invalid claim name");
578
+ if (raw["allowInsecureHttp"] !== void 0 && typeof raw["allowInsecureHttp"] !== "boolean") {
579
+ problems.push("allowInsecureHttp must be a boolean");
580
+ }
581
+ const timeouts = timeoutsOf(problems, raw["timeouts"], { tokenMs: DEFAULT_TOKEN_MS, logoutMs: DEFAULT_LOGOUT_MS });
582
+ const { fetch, refreshLock, onFailure } = raw;
583
+ if (fetch !== void 0 && typeof fetch !== "function") problems.push("fetch must be a function");
584
+ if (refreshLock !== void 0 && !(isObject(refreshLock) && typeof refreshLock["run"] === "function")) {
585
+ problems.push("refreshLock must have a run function");
586
+ }
587
+ if (onFailure !== void 0 && typeof onFailure !== "function") problems.push("onFailure must be a function");
588
+ const environment = raw["environment"];
589
+ const guard = (0, import_auth_shared5.environmentProblems)({
590
+ environment,
591
+ issuer: issuer ?? (environment === "production" ? import_auth_shared5.PRODUCTION_ISSUER : ""),
592
+ allowInsecureHttp: raw["allowInsecureHttp"],
593
+ ...resource !== void 0 ? { audiences: [resource] } : {},
594
+ ...backchannelUrl !== void 0 ? { backchannelUrl } : {}
595
+ });
596
+ if (guard.length > 0 || problems.length > 0) throw new import_auth_shared5.ConfigError([...guard, ...problems]);
597
+ return Object.freeze({
598
+ environment,
599
+ issuer,
600
+ backchannelUrl: backchannelUrl ?? null,
601
+ clientId,
602
+ clientSecret,
603
+ redirectUri,
604
+ postLogoutRedirectUri: postLogoutRedirectUri ?? null,
605
+ scopes: distinctScopes(scopesRaw),
606
+ profile,
607
+ resource: resource ?? null,
608
+ logoutTicket,
609
+ endSession: endSession2,
610
+ extraClaims: Object.freeze(extraClaims),
611
+ timeouts: Object.freeze(timeouts),
612
+ fetch: fetch ?? globalFetch,
613
+ refreshLock: refreshLock ?? memoryLockStore(),
614
+ onFailure
615
+ });
616
+ }
617
+
618
+ // src/core/login.ts
619
+ var import_node_crypto = require("crypto");
620
+ var import_auth_shared6 = require("@plasgos/auth-shared");
621
+ var MAX_RETURN_TO_CHARS = 512;
622
+ var MAX_LOGIN_HINT_CHARS = 512;
623
+ var PROMPTS = ["login", "consent", "none"];
624
+ var random43 = () => (0, import_node_crypto.randomBytes)(32).toString("base64url");
625
+ var refuse2 = (rule) => {
626
+ throw new TypeError(`startLogin: ${rule}`);
627
+ };
628
+ var REWRITTEN_BY_BROWSERS = /[\u0000-\u001f\u007f\\]/;
629
+ var isLocalPath = (value) => typeof value === "string" && value.length <= MAX_RETURN_TO_CHARS && value.startsWith("/") && value[1] !== "/" && !REWRITTEN_BY_BROWSERS.test(value);
630
+ function checkInput(input) {
631
+ if (input === null || typeof input !== "object") refuse2("input must be an object");
632
+ const { returnTo, prompt, maxAge, loginHint, reauth, now } = input;
633
+ if (!isLocalPath(returnTo)) refuse2('returnTo must start with exactly one "/", be at most 512 characters, and contain no control character or backslash');
634
+ if (prompt !== void 0 && !PROMPTS.includes(prompt)) refuse2('prompt must be "login", "consent" or "none"');
635
+ if (maxAge !== void 0 && !(Number.isSafeInteger(maxAge) && maxAge >= 0)) {
636
+ refuse2("maxAge must be a non-negative integer");
637
+ }
638
+ if (loginHint !== void 0 && !(typeof loginHint === "string" && loginHint.length <= MAX_LOGIN_HINT_CHARS)) {
639
+ refuse2("loginHint must be a string of at most 512 characters");
640
+ }
641
+ if (reauth !== void 0 && typeof reauth !== "boolean") refuse2("reauth must be a boolean");
642
+ if (now !== void 0 && !Number.isFinite(now)) refuse2("now must be a finite number");
643
+ }
644
+ function startLogin(config, input) {
645
+ checkInput(input);
646
+ const transaction = {
647
+ state: random43(),
648
+ nonce: random43(),
649
+ code_verifier: random43(),
650
+ return_to: input.returnTo,
651
+ created_at: input.now ?? Date.now(),
652
+ ...input.reauth === true ? { reauth: true } : {},
653
+ ...input.maxAge !== void 0 ? { max_age: input.maxAge } : {}
654
+ };
655
+ const params = new URLSearchParams({
656
+ response_type: "code",
657
+ client_id: config.clientId,
658
+ redirect_uri: config.redirectUri,
659
+ scope: config.scopes.join(" "),
660
+ state: transaction.state,
661
+ nonce: transaction.nonce,
662
+ code_challenge: (0, import_node_crypto.createHash)("sha256").update(transaction.code_verifier).digest("base64url"),
663
+ code_challenge_method: "S256",
664
+ ...input.prompt !== void 0 ? { prompt: input.prompt } : {},
665
+ ...input.maxAge !== void 0 ? { max_age: String(input.maxAge) } : {},
666
+ ...input.loginHint !== void 0 ? { login_hint: input.loginHint } : {},
667
+ ...config.resource !== null ? { resource: config.resource } : {}
668
+ });
669
+ return { location: `${config.issuer}${import_auth_shared6.OIDC_PATHS.authorization}?${params.toString()}`, transaction };
670
+ }
671
+
672
+ // src/core/logout.ts
673
+ var import_auth_shared7 = require("@plasgos/auth-shared");
674
+ var REVOCATION_CALL = { method: "POST", path: import_auth_shared7.OIDC_PATHS.revocation };
675
+ var TICKET_CALL = { method: "POST", path: import_auth_shared7.OIDC_PATHS.logoutTickets };
676
+ var TICKET = /^[A-Za-z0-9_-]{43}$/;
677
+ var ignore3 = () => void 0;
678
+ var isText = (value) => typeof value === "string" && value !== "";
679
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
680
+ var own3 = (record, key) => Object.hasOwn(record, key) ? record[key] : void 0;
681
+ var reasonOfStatus = (res) => res.status >= 500 || res.status === 429 ? "unavailable" : "provider_error";
682
+ var failureOf = (error) => error instanceof import_auth_shared7.OidcError ? { reason: error.reason, status: error.upstream?.status ?? null, requestId: error.upstream?.requestId ?? null } : { reason: "unavailable", status: null, requestId: null };
683
+ function reportFailure(config, operation, call, failure, providerError) {
684
+ report(config.onFailure, {
685
+ environment: config.environment,
686
+ operation,
687
+ reason: failure.reason,
688
+ method: call.method,
689
+ path: call.path,
690
+ status: failure.status,
691
+ requestId: failure.requestId,
692
+ providerError
693
+ });
694
+ }
695
+ async function revoke(config, refreshToken) {
696
+ try {
697
+ const { res, done } = await send(
698
+ `${config.backchannelUrl ?? config.issuer}${REVOCATION_CALL.path}`,
699
+ {
700
+ method: REVOCATION_CALL.method,
701
+ headers: {
702
+ Authorization: (0, import_auth_shared7.basicAuthHeader)(config.clientId, config.clientSecret),
703
+ "Content-Type": "application/x-www-form-urlencoded",
704
+ Accept: "application/json"
705
+ },
706
+ body: new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token" }).toString()
707
+ },
708
+ { timeoutMs: config.timeouts.logoutMs, fetch: config.fetch, call: REVOCATION_CALL }
709
+ );
710
+ done();
711
+ await res.body?.cancel().catch(ignore3);
712
+ if (!res.ok) {
713
+ const at = upstreamOf(REVOCATION_CALL.method, REVOCATION_CALL.path, res);
714
+ reportFailure(config, "revocation", REVOCATION_CALL, { ...at, reason: reasonOfStatus(res) }, null);
715
+ }
716
+ } catch (error) {
717
+ reportFailure(config, "revocation", REVOCATION_CALL, failureOf(error), null);
718
+ }
719
+ }
720
+ function browserHeaders(browser) {
721
+ const clientIp = browser?.clientIp;
722
+ const userAgent = browser?.userAgent;
723
+ return {
724
+ ...isText(clientIp) ? { "X-Client-Ip": clientIp } : {},
725
+ ...isText(userAgent) ? { "X-Client-User-Agent": userAgent } : {}
726
+ };
727
+ }
728
+ async function mintTicket(config, backchannelUrl, idToken, browser) {
729
+ try {
730
+ const { res, body, at } = await requestJson(
731
+ `${backchannelUrl}${TICKET_CALL.path}`,
732
+ {
733
+ method: TICKET_CALL.method,
734
+ headers: {
735
+ Authorization: (0, import_auth_shared7.basicAuthHeader)(config.clientId, config.clientSecret),
736
+ "Content-Type": "application/json",
737
+ Accept: "application/json, application/problem+json",
738
+ ...browserHeaders(browser)
739
+ },
740
+ body: JSON.stringify({ id_token: idToken })
741
+ },
742
+ { timeoutMs: config.timeouts.logoutMs, fetch: config.fetch, call: TICKET_CALL }
743
+ );
744
+ const record = isRecord3(body) ? body : {};
745
+ const ticket = own3(record, "ticket");
746
+ if (res.status === 201 && typeof ticket === "string" && TICKET.test(ticket)) return ticket;
747
+ const reason = reasonOfStatus(res);
748
+ const code = own3(record, "code");
749
+ const providerError = typeof code === "string" && !TICKET.test(code) ? code : reason;
750
+ reportFailure(config, "logout_ticket", TICKET_CALL, { ...at, reason }, providerError);
751
+ return null;
752
+ } catch (error) {
753
+ const failure = failureOf(error);
754
+ reportFailure(config, "logout_ticket", TICKET_CALL, failure, failure.reason);
755
+ return null;
756
+ }
757
+ }
758
+ function endSession(config, idToken, ticket) {
759
+ const endpoint = `${config.issuer}${import_auth_shared7.OIDC_PATHS.endSession}`;
760
+ const postLogout = config.postLogoutRedirectUri !== null ? { post_logout_redirect_uri: config.postLogoutRedirectUri } : {};
761
+ if (config.endSession === "form-post") {
762
+ return {
763
+ kind: "form",
764
+ action: endpoint,
765
+ fields: Object.freeze({
766
+ ...idToken !== void 0 ? { id_token_hint: idToken } : {},
767
+ client_id: config.clientId,
768
+ ...postLogout
769
+ })
770
+ };
771
+ }
772
+ const params = new URLSearchParams({
773
+ client_id: config.clientId,
774
+ ...ticket !== null ? { logout_ticket: ticket } : {},
775
+ ...postLogout
776
+ });
777
+ return { kind: "redirect", location: `${endpoint}?${params.toString()}`, ticket: ticket !== null };
778
+ }
779
+ async function logout(config, input) {
780
+ const refreshToken = input?.refreshToken;
781
+ const idTokenRaw = input?.idToken;
782
+ const idToken = isText(idTokenRaw) ? idTokenRaw : void 0;
783
+ const backchannelUrl = config.logoutTicket ? config.backchannelUrl : null;
784
+ const [ticket] = await Promise.all([
785
+ backchannelUrl !== null && idToken !== void 0 ? mintTicket(config, backchannelUrl, idToken, input?.browser) : null,
786
+ isText(refreshToken) ? revoke(config, refreshToken) : void 0
787
+ ]);
788
+ return endSession(config, idToken, ticket);
789
+ }
790
+
791
+ // src/core/refresh.ts
792
+ var import_node_crypto2 = require("crypto");
793
+ var import_auth_shared8 = require("@plasgos/auth-shared");
794
+
795
+ // src/core/expiry.ts
796
+ function accessTokenExpiry(tokens, nowMs) {
797
+ return Math.floor(nowMs / 1e3) + tokens.expires_in;
798
+ }
799
+
800
+ // src/core/refresh.ts
801
+ var REUSE_MS = 3e4;
802
+ var DEFAULT_SKEW_SECONDS = 60;
803
+ var isText2 = (value) => typeof value === "string" && value !== "";
804
+ function missing(config) {
805
+ report(config.onFailure, {
806
+ environment: config.environment,
807
+ operation: "refresh",
808
+ reason: "missing",
809
+ method: null,
810
+ path: null,
811
+ status: null,
812
+ requestId: null,
813
+ providerError: null
814
+ });
815
+ return new import_auth_shared8.OidcError("missing");
816
+ }
817
+ async function refresh(config, refreshToken) {
818
+ if (!isText2(refreshToken)) throw missing(config);
819
+ const key = (0, import_node_crypto2.createHash)("sha256").update(refreshToken, "utf8").digest("hex");
820
+ return config.refreshLock.run(
821
+ key,
822
+ () => tokenRequest(config, "refresh", { grant_type: "refresh_token", refresh_token: refreshToken }),
823
+ REUSE_MS
824
+ );
825
+ }
826
+ async function ensureFresh(config, auth, options = {}) {
827
+ const skewSeconds = options.skewSeconds ?? DEFAULT_SKEW_SECONDS;
828
+ if (!Number.isSafeInteger(skewSeconds) || skewSeconds < 0) {
829
+ throw new TypeError("skewSeconds must be a non-negative integer");
830
+ }
831
+ const force = options.force === true;
832
+ const left = auth.expires_at * 1e3 - (options.now ?? Date.now());
833
+ if (!force && left >= skewSeconds * 1e3) return { auth, changed: false };
834
+ const stillValid = !force && left > 0;
835
+ const refreshToken = auth.refresh_token;
836
+ if (!isText2(refreshToken)) {
837
+ if (stillValid) return { auth, changed: false };
838
+ throw missing(config);
839
+ }
840
+ let tokens;
841
+ try {
842
+ tokens = await refresh(config, refreshToken);
843
+ } catch (error) {
844
+ const sessionOver = error instanceof import_auth_shared8.OidcError && (error.reason === "invalid_grant" || error.reason === "invalid_target");
845
+ if (error instanceof import_auth_shared8.OidcError && !sessionOver && stillValid) return { auth, changed: false };
846
+ throw error;
847
+ }
848
+ return {
849
+ auth: {
850
+ ...auth,
851
+ access_token: tokens.access_token,
852
+ ...tokens.refresh_token !== void 0 ? { refresh_token: tokens.refresh_token } : {},
853
+ expires_at: accessTokenExpiry(tokens, options.now ?? Date.now())
854
+ },
855
+ changed: true
856
+ };
857
+ }
858
+
859
+ // src/core/client.ts
860
+ function createOidcClient(options) {
861
+ const config = resolveConfig(options);
862
+ return Object.freeze({
863
+ environment: config.environment,
864
+ issuer: config.issuer,
865
+ clientId: config.clientId,
866
+ startLogin: (input) => startLogin(config, input),
867
+ handleCallback: (url, transaction, options2) => handleCallback(config, url, transaction, options2),
868
+ refresh: (refreshToken) => refresh(config, refreshToken),
869
+ ensureFresh: (auth, options2) => ensureFresh(config, auth, options2),
870
+ logout: (input) => logout(config, input)
871
+ });
872
+ }
873
+
874
+ // src/index.ts
875
+ var import_auth_shared9 = require("@plasgos/auth-shared");
876
+ // Annotate the CommonJS export names for ESM import in node:
877
+ 0 && (module.exports = {
878
+ ConfigError,
879
+ OidcError,
880
+ accessTokenExpiry,
881
+ createOidcClient,
882
+ memoryLockStore
883
+ });
884
+ //# sourceMappingURL=index.cjs.map