@softistx/janus-social 0.0.0-stage → 0.7.0

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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +356 -2
  3. package/dist/authorization-url.d.ts +21 -0
  4. package/dist/authorization-url.d.ts.map +1 -0
  5. package/dist/check-options.d.ts +22 -0
  6. package/dist/check-options.d.ts.map +1 -0
  7. package/dist/claims.d.ts +15 -0
  8. package/dist/claims.d.ts.map +1 -0
  9. package/dist/code-exchange.d.ts +79 -0
  10. package/dist/code-exchange.d.ts.map +1 -0
  11. package/dist/connections/abort.d.ts +8 -0
  12. package/dist/connections/abort.d.ts.map +1 -0
  13. package/dist/connections/at-hash.d.ts +24 -0
  14. package/dist/connections/at-hash.d.ts.map +1 -0
  15. package/dist/connections/body-limit.d.ts +15 -0
  16. package/dist/connections/body-limit.d.ts.map +1 -0
  17. package/dist/connections/build.d.ts +7 -0
  18. package/dist/connections/build.d.ts.map +1 -0
  19. package/dist/connections/check.d.ts +25 -0
  20. package/dist/connections/check.d.ts.map +1 -0
  21. package/dist/connections/claims.d.ts +16 -0
  22. package/dist/connections/claims.d.ts.map +1 -0
  23. package/dist/connections/discovery.d.ts +20 -0
  24. package/dist/connections/discovery.d.ts.map +1 -0
  25. package/dist/connections/domain.d.ts +15 -0
  26. package/dist/connections/domain.d.ts.map +1 -0
  27. package/dist/connections/guarded-fetch.d.ts +49 -0
  28. package/dist/connections/guarded-fetch.d.ts.map +1 -0
  29. package/dist/connections/id-token-steps.d.ts +15 -0
  30. package/dist/connections/id-token-steps.d.ts.map +1 -0
  31. package/dist/connections/id-token.d.ts +63 -0
  32. package/dist/connections/id-token.d.ts.map +1 -0
  33. package/dist/connections/index.d.ts +10 -0
  34. package/dist/connections/index.d.ts.map +1 -0
  35. package/dist/connections/ip.d.ts +14 -0
  36. package/dist/connections/ip.d.ts.map +1 -0
  37. package/dist/connections/issuer-cache.d.ts +40 -0
  38. package/dist/connections/issuer-cache.d.ts.map +1 -0
  39. package/dist/connections/issuer.d.ts +4 -0
  40. package/dist/connections/issuer.d.ts.map +1 -0
  41. package/dist/connections/key-flights.d.ts +16 -0
  42. package/dist/connections/key-flights.d.ts.map +1 -0
  43. package/dist/connections/memory.d.ts +10 -0
  44. package/dist/connections/memory.d.ts.map +1 -0
  45. package/dist/connections/oidc-connections.d.ts +63 -0
  46. package/dist/connections/oidc-connections.d.ts.map +1 -0
  47. package/dist/connections/provider.d.ts +25 -0
  48. package/dist/connections/provider.d.ts.map +1 -0
  49. package/dist/connections/server.d.ts +55 -0
  50. package/dist/connections/server.d.ts.map +1 -0
  51. package/dist/connections/types.d.ts +87 -0
  52. package/dist/connections/types.d.ts.map +1 -0
  53. package/dist/connections/url-policy.d.ts +30 -0
  54. package/dist/connections/url-policy.d.ts.map +1 -0
  55. package/dist/connections/wiring.d.ts +5 -0
  56. package/dist/connections/wiring.d.ts.map +1 -0
  57. package/dist/discovery.d.ts +11 -0
  58. package/dist/discovery.d.ts.map +1 -0
  59. package/dist/dpop.d.ts +18 -0
  60. package/dist/dpop.d.ts.map +1 -0
  61. package/dist/failure.d.ts +14 -0
  62. package/dist/failure.d.ts.map +1 -0
  63. package/dist/github-identity.d.ts +11 -0
  64. package/dist/github-identity.d.ts.map +1 -0
  65. package/dist/github.d.ts +11 -0
  66. package/dist/github.d.ts.map +1 -0
  67. package/dist/google.d.ts +11 -0
  68. package/dist/google.d.ts.map +1 -0
  69. package/dist/guard-error.d.ts +14 -0
  70. package/dist/guard-error.d.ts.map +1 -0
  71. package/dist/index.d.ts +23 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +1821 -0
  74. package/dist/index.js.map +51 -0
  75. package/dist/microsoft-tenant.d.ts +32 -0
  76. package/dist/microsoft-tenant.d.ts.map +1 -0
  77. package/dist/microsoft.d.ts +16 -0
  78. package/dist/microsoft.d.ts.map +1 -0
  79. package/dist/oauth2.d.ts +13 -0
  80. package/dist/oauth2.d.ts.map +1 -0
  81. package/dist/oidc-engine.d.ts +62 -0
  82. package/dist/oidc-engine.d.ts.map +1 -0
  83. package/dist/oidc-step-up.d.ts +15 -0
  84. package/dist/oidc-step-up.d.ts.map +1 -0
  85. package/dist/oidc.d.ts +11 -0
  86. package/dist/oidc.d.ts.map +1 -0
  87. package/dist/options.d.ts +108 -0
  88. package/dist/options.d.ts.map +1 -0
  89. package/dist/pushed-authorization.d.ts +23 -0
  90. package/dist/pushed-authorization.d.ts.map +1 -0
  91. package/dist/step-up.d.ts +50 -0
  92. package/dist/step-up.d.ts.map +1 -0
  93. package/dist/transport.d.ts +18 -0
  94. package/dist/transport.d.ts.map +1 -0
  95. package/docs/README.md +35 -0
  96. package/docs/guide/custom-providers.md +182 -0
  97. package/docs/guide/github.md +109 -0
  98. package/docs/guide/google.md +103 -0
  99. package/docs/guide/microsoft.md +158 -0
  100. package/docs/guide/oidc-connections.md +255 -0
  101. package/docs/guide/oidc-step-up.md +122 -0
  102. package/docs/guide/par-dpop.md +63 -0
  103. package/docs/roadmap.md +33 -0
  104. package/docs/troubleshooting.md +632 -0
  105. package/package.json +67 -5
package/dist/index.js ADDED
@@ -0,0 +1,1821 @@
1
+ // src/check-options.ts
2
+ var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
3
+ function requireText(where, name, value) {
4
+ if (typeof value !== "string" || value.trim() === "") {
5
+ throw new TypeError(`${where}: "${name}" must be a non-empty string`);
6
+ }
7
+ }
8
+ function requireHttps(where, name, value) {
9
+ requireText(where, name, value);
10
+ const url = parse(value);
11
+ if (url === null || url.protocol !== "https:") {
12
+ throw new TypeError(`${where}: "${name}" must be an https URL`);
13
+ }
14
+ return url;
15
+ }
16
+ function checkRedirectUri(where, redirectUri) {
17
+ requireText(where, "redirectUri", redirectUri);
18
+ const url = parse(redirectUri);
19
+ const ok = url !== null && (url.protocol === "https:" || url.protocol === "http:" && LOOPBACK.has(url.hostname));
20
+ if (!ok) {
21
+ throw new TypeError(`${where}: "redirectUri" must be an https URL (http only on localhost)`);
22
+ }
23
+ }
24
+ function checkFetch(where, fetch2) {
25
+ if (fetch2 !== undefined && typeof fetch2 !== "function") {
26
+ throw new TypeError(`${where}: "fetch" must be a function`);
27
+ }
28
+ }
29
+ function checkTimeout(where, timeout) {
30
+ if (timeout !== undefined && (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0)) {
31
+ throw new TypeError(`${where}: "timeout" must be a positive number`);
32
+ }
33
+ }
34
+ function checkCredentials(where, options) {
35
+ requireText(where, "clientId", options.clientId);
36
+ requireText(where, "clientSecret", options.clientSecret);
37
+ checkRedirectUri(where, options.redirectUri);
38
+ checkFetch(where, options.fetch);
39
+ checkTimeout(where, options.timeout);
40
+ }
41
+ function checkScopes(where, scopes) {
42
+ if (!Array.isArray(scopes) || scopes.some((s) => typeof s !== "string" || s === "" || /\s/.test(s))) {
43
+ throw new TypeError(`${where}: "scopes" must be an array of scope names with no spaces`);
44
+ }
45
+ return [...new Set(scopes)];
46
+ }
47
+ function parse(text) {
48
+ try {
49
+ return new URL(text);
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ function checkSecurity(where, options) {
55
+ const { pushedAuthorization, dpop } = options;
56
+ if (pushedAuthorization !== undefined && pushedAuthorization !== "auto" && pushedAuthorization !== "always") {
57
+ throw new TypeError(`${where}: "pushedAuthorization" must be 'auto' or 'always'`);
58
+ }
59
+ if (dpop === undefined || dpop === true)
60
+ return;
61
+ const algorithm = dpop?.algorithm;
62
+ if (algorithm !== "ES256" && algorithm !== "EdDSA") {
63
+ throw new TypeError(`${where}: "dpop" must be true or { algorithm: 'ES256' | 'EdDSA' }`);
64
+ }
65
+ }
66
+
67
+ // src/step-up.ts
68
+ var TOLERANCE_MS = 60000;
69
+ var MAX_ACR = 256;
70
+ function checkStepUp(where, acrValues, maxAge) {
71
+ if (acrValues !== undefined && (!Array.isArray(acrValues) || acrValues.length === 0 || acrValues.some((v) => typeof v !== "string" || v === "" || /\s/.test(v)))) {
72
+ throw new TypeError(`${where}: "acrValues" must be a non-empty array of values with no spaces`);
73
+ }
74
+ if (maxAge !== undefined && (typeof maxAge !== "number" || !Number.isInteger(maxAge) || maxAge < 0)) {
75
+ throw new TypeError(`${where}: "maxAge" must be a non-negative integer (seconds)`);
76
+ }
77
+ }
78
+ function stepUpParams({
79
+ acrValues,
80
+ maxAge
81
+ }) {
82
+ const params = {};
83
+ if (acrValues !== undefined)
84
+ params["acr_values"] = acrValues.join(" ");
85
+ if (maxAge !== undefined)
86
+ params["max_age"] = String(maxAge);
87
+ return params;
88
+ }
89
+ function combineStepUp(fixed, request) {
90
+ const asked = request?.acrValues ?? undefined;
91
+ let acrValues = fixed.acrValues ?? asked;
92
+ if (fixed.acrValues !== undefined && asked !== undefined) {
93
+ const held = fixed.acrValues;
94
+ acrValues = [...new Set(asked.filter((value) => held.includes(value)))];
95
+ if (acrValues.length === 0) {
96
+ throw new TypeError("step-up: the flow asks for no authentication context class the provider is configured to accept");
97
+ }
98
+ }
99
+ const wanted = request?.maxAge ?? undefined;
100
+ const maxAge = fixed.maxAge === undefined || wanted === undefined ? fixed.maxAge ?? wanted : Math.min(fixed.maxAge, wanted);
101
+ return { acrValues, maxAge };
102
+ }
103
+ function stepUpClaims(claims) {
104
+ const acr = claims["acr"];
105
+ const time = claims["auth_time"];
106
+ const authTime = typeof time === "number" && Number.isFinite(time) ? new Date(time * 1000) : undefined;
107
+ return {
108
+ ...typeof acr === "string" && acr !== "" && acr.length <= MAX_ACR ? { acr } : {},
109
+ ...authTime === undefined || Number.isNaN(authTime.getTime()) ? {} : { authTime }
110
+ };
111
+ }
112
+ function holdsStepUp(claims, acrValues, maxAge, now) {
113
+ if (acrValues !== undefined) {
114
+ const acr = claims["acr"];
115
+ if (typeof acr !== "string" || !acrValues.includes(acr))
116
+ return false;
117
+ }
118
+ if (maxAge !== undefined) {
119
+ const authTime = claims["auth_time"];
120
+ if (typeof authTime !== "number" || !Number.isFinite(authTime)) {
121
+ return false;
122
+ }
123
+ const at = authTime * 1000;
124
+ if (at < now - maxAge * 1000 - TOLERANCE_MS)
125
+ return false;
126
+ if (at > now + TOLERANCE_MS)
127
+ return false;
128
+ }
129
+ return true;
130
+ }
131
+
132
+ // src/connections/build.ts
133
+ var CLIENT_KEYS = [
134
+ "id",
135
+ "secret",
136
+ "authentication",
137
+ "idTokenSignedResponseAlg"
138
+ ];
139
+ var CLAIM_KEYS = [
140
+ "email",
141
+ "emailVerified",
142
+ "name",
143
+ "picture"
144
+ ];
145
+ function build(record, scopes, domains, emailTrust) {
146
+ const client = record["client"];
147
+ const claims = record["claims"];
148
+ const stepUp = record["stepUp"];
149
+ const dpop = record["dpop"];
150
+ const out = {
151
+ id: record["id"],
152
+ issuer: record["issuer"],
153
+ client: pick(client, CLIENT_KEYS),
154
+ scopes: [...scopes],
155
+ domains: [...domains],
156
+ emailTrust
157
+ };
158
+ if (record["revision"] !== undefined)
159
+ out["revision"] = record["revision"];
160
+ if (claims !== undefined)
161
+ out["claims"] = pick(claims, CLAIM_KEYS);
162
+ if (stepUp !== undefined) {
163
+ const copy = pick(stepUp, ["acrValues", "maxAge"]);
164
+ if (Array.isArray(copy["acrValues"])) {
165
+ copy["acrValues"] = [...copy["acrValues"]];
166
+ }
167
+ out["stepUp"] = copy;
168
+ }
169
+ if (record["pushedAuthorization"] !== undefined) {
170
+ out["pushedAuthorization"] = record["pushedAuthorization"];
171
+ }
172
+ if (dpop !== undefined) {
173
+ out["dpop"] = isObject(dpop) ? { ...dpop } : dpop;
174
+ }
175
+ return freeze(out);
176
+ }
177
+ function pick(source, keys) {
178
+ const out = {};
179
+ for (const key of keys) {
180
+ if (source[key] !== undefined)
181
+ out[key] = source[key];
182
+ }
183
+ return out;
184
+ }
185
+ function freeze(value) {
186
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
187
+ Object.freeze(value);
188
+ for (const inner of Object.values(value))
189
+ freeze(inner);
190
+ }
191
+ return value;
192
+ }
193
+
194
+ // src/connections/domain.ts
195
+ import { domainToASCII } from "node:url";
196
+ var MAX_DOMAIN = 253;
197
+ var MAX_LABEL = 63;
198
+ function wellFormed(domain) {
199
+ if (domain.length > MAX_DOMAIN || !domain.includes("."))
200
+ return false;
201
+ const labels = domain.split(".");
202
+ for (const label of labels) {
203
+ if (label === "" || label.length > MAX_LABEL)
204
+ return false;
205
+ if (!/^[a-z0-9-]+$/.test(label))
206
+ return false;
207
+ if (label.startsWith("-") || label.endsWith("-"))
208
+ return false;
209
+ }
210
+ return !/^[0-9]+$/.test(labels[labels.length - 1] ?? "");
211
+ }
212
+ function normalizeDomain(value) {
213
+ if (typeof value !== "string")
214
+ return null;
215
+ const trimmed = value.trim().toLowerCase();
216
+ if (trimmed === "" || /[\s@/:*?#%\\]/.test(trimmed))
217
+ return null;
218
+ const ascii = domainToASCII(trimmed).replace(/\.$/, "");
219
+ return wellFormed(ascii) ? ascii : null;
220
+ }
221
+ function domainOfEmail(address) {
222
+ if (/\s/.test(address))
223
+ return null;
224
+ const at = address.indexOf("@");
225
+ if (at < 1 || at !== address.lastIndexOf("@"))
226
+ return null;
227
+ return normalizeDomain(address.slice(at + 1));
228
+ }
229
+
230
+ // src/connections/issuer.ts
231
+ var WHERE = "checkConnection";
232
+ function checkIssuer(problems, issuer) {
233
+ try {
234
+ const url = requireHttps(WHERE, "issuer", issuer);
235
+ if (url.search !== "" || url.hash !== "" || url.username !== "") {
236
+ throw new TypeError(`${WHERE}: "issuer" must have no query, fragment or credentials`);
237
+ }
238
+ const text = issuer;
239
+ const host = url.host;
240
+ if (!text.startsWith(`https://${host}`)) {
241
+ throw new TypeError(`${WHERE}: "issuer" must be written with a lowercase https scheme and host`);
242
+ }
243
+ const rest = text.slice("https://".length);
244
+ const slash = rest.indexOf("/");
245
+ const segments = slash < 0 ? [] : rest.slice(slash).split("/").slice(1);
246
+ const last = segments.length - 1;
247
+ const bad = segments.some((segment, index) => segment === "." || segment === ".." || segment === "" && index !== last);
248
+ if (bad) {
249
+ throw new TypeError(`${WHERE}: "issuer" must have no empty, "." or ".." path segment`);
250
+ }
251
+ } catch (error) {
252
+ problems.push(error instanceof Error ? error.message : String(error));
253
+ }
254
+ }
255
+
256
+ // src/connections/types.ts
257
+ var CONNECTION_ALGORITHMS = [
258
+ "RS256",
259
+ "RS384",
260
+ "RS512",
261
+ "PS256",
262
+ "PS384",
263
+ "PS512",
264
+ "ES256",
265
+ "ES384",
266
+ "ES512",
267
+ "EdDSA"
268
+ ];
269
+
270
+ // src/connections/check.ts
271
+ var WHERE2 = "checkConnection";
272
+ var PROVIDER_NAME = /^[a-z][a-z0-9-]{0,31}$/;
273
+ var TRUSTS = ["claimAndDomain", "domain", "claim"];
274
+ var RECORD_KEYS = [
275
+ "id",
276
+ "issuer",
277
+ "client",
278
+ "domains",
279
+ "revision",
280
+ "emailTrust",
281
+ "scopes",
282
+ "claims",
283
+ "stepUp",
284
+ "pushedAuthorization",
285
+ "dpop"
286
+ ];
287
+ var DEFAULT_SCOPES = ["openid", "email", "profile"];
288
+ var PROTOCOL_CLAIMS = [
289
+ "sub",
290
+ "iss",
291
+ "aud",
292
+ "azp",
293
+ "nonce",
294
+ "at_hash",
295
+ "acr",
296
+ "amr",
297
+ "auth_time"
298
+ ];
299
+ function collect(problems, run) {
300
+ try {
301
+ run();
302
+ } catch (error) {
303
+ problems.push(error instanceof Error ? error.message : String(error));
304
+ }
305
+ }
306
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
307
+ function refuseUnknown(problems, object, allowed, prefix) {
308
+ for (const key of Object.keys(object)) {
309
+ if (!allowed.includes(key)) {
310
+ problems.push(`${WHERE2}: "${prefix}${key}" is not a known field`);
311
+ }
312
+ }
313
+ }
314
+ function checkClient(problems, client) {
315
+ if (!isObject(client)) {
316
+ problems.push(`${WHERE2}: "client" must be an object`);
317
+ return;
318
+ }
319
+ refuseUnknown(problems, client, CLIENT_KEYS, "client.");
320
+ collect(problems, () => requireText(WHERE2, "client.id", client["id"]));
321
+ collect(problems, () => requireText(WHERE2, "client.secret", client["secret"]));
322
+ const auth = client["authentication"];
323
+ if (auth !== undefined && auth !== "post" && auth !== "basic") {
324
+ problems.push(`${WHERE2}: "client.authentication" must be 'post' or 'basic'`);
325
+ }
326
+ const alg = client["idTokenSignedResponseAlg"];
327
+ if (alg !== undefined && !CONNECTION_ALGORITHMS.includes(alg)) {
328
+ problems.push(`${WHERE2}: "client.idTokenSignedResponseAlg" must be one of ${CONNECTION_ALGORITHMS.join(", ")} (never none or HS*)`);
329
+ }
330
+ }
331
+ function checkDomains(problems, domains, trust) {
332
+ if (!Array.isArray(domains)) {
333
+ problems.push(`${WHERE2}: "domains" must be an array of e-mail domains`);
334
+ return [];
335
+ }
336
+ const before = problems.length;
337
+ const found = [];
338
+ for (const domain of domains) {
339
+ const ascii = normalizeDomain(domain);
340
+ if (ascii === null) {
341
+ problems.push(`${WHERE2}: "domains" holds a value that is not a domain name`);
342
+ } else if (!found.includes(ascii)) {
343
+ found.push(ascii);
344
+ }
345
+ }
346
+ if (found.length === 0 && trust !== "claim" && problems.length === before) {
347
+ problems.push(`${WHERE2}: "domains" must not be empty unless emailTrust is 'claim'`);
348
+ }
349
+ return found;
350
+ }
351
+ function checkClaimNames(problems, claims) {
352
+ if (claims === undefined)
353
+ return;
354
+ if (!isObject(claims)) {
355
+ problems.push(`${WHERE2}: "claims" must be an object`);
356
+ return;
357
+ }
358
+ for (const key of Object.keys(claims)) {
359
+ if (!CLAIM_KEYS.includes(key)) {
360
+ problems.push(`${WHERE2}: "claims.${key}" is not a claim that can be mapped`);
361
+ }
362
+ }
363
+ for (const key of CLAIM_KEYS) {
364
+ const name = claims[key];
365
+ if (name === undefined)
366
+ continue;
367
+ collect(problems, () => requireText(WHERE2, `claims.${key}`, name));
368
+ if (typeof name === "string" && PROTOCOL_CLAIMS.includes(name.trim())) {
369
+ problems.push(`${WHERE2}: "claims.${key}" must not name a protocol claim (${PROTOCOL_CLAIMS.join(", ")})`);
370
+ }
371
+ }
372
+ }
373
+ function checkStep(problems, stepUp) {
374
+ if (stepUp === undefined)
375
+ return;
376
+ if (!isObject(stepUp)) {
377
+ problems.push(`${WHERE2}: "stepUp" must be an object`);
378
+ return;
379
+ }
380
+ collect(problems, () => checkStepUp(WHERE2, stepUp["acrValues"], stepUp["maxAge"]));
381
+ }
382
+ function checkRevision(problems, revision) {
383
+ if (revision === undefined)
384
+ return;
385
+ const ok = typeof revision === "string" && revision !== "" || typeof revision === "number" && Number.isInteger(revision) && revision >= 0;
386
+ if (!ok) {
387
+ problems.push(`${WHERE2}: "revision" must be a non-empty string or a non-negative integer when given`);
388
+ }
389
+ }
390
+ function checkConnection(record) {
391
+ if (!isObject(record)) {
392
+ throw new TypeError(`${WHERE2}: the record must be an object`);
393
+ }
394
+ const problems = [];
395
+ if (typeof record["id"] !== "string" || !PROVIDER_NAME.test(record["id"])) {
396
+ problems.push(`${WHERE2}: "id" must match ${PROVIDER_NAME}`);
397
+ }
398
+ refuseUnknown(problems, record, RECORD_KEYS, "");
399
+ checkIssuer(problems, record["issuer"]);
400
+ checkClient(problems, record["client"]);
401
+ const trust = record["emailTrust"] ?? "claimAndDomain";
402
+ if (!TRUSTS.includes(trust)) {
403
+ problems.push(`${WHERE2}: "emailTrust" must be 'claimAndDomain', 'domain' or 'claim'`);
404
+ }
405
+ const domains = checkDomains(problems, record["domains"], trust);
406
+ let scopes = DEFAULT_SCOPES;
407
+ collect(problems, () => {
408
+ scopes = checkScopes(WHERE2, record["scopes"] ?? DEFAULT_SCOPES);
409
+ });
410
+ collect(problems, () => checkSecurity(WHERE2, record));
411
+ checkClaimNames(problems, record["claims"]);
412
+ checkStep(problems, record["stepUp"]);
413
+ checkRevision(problems, record["revision"]);
414
+ if (problems.length > 0)
415
+ throw new TypeError(problems.join(`
416
+ `));
417
+ return build(record, scopes, domains, trust);
418
+ }
419
+ // src/connections/memory.ts
420
+ function createMemoryConnections(records) {
421
+ const byId = new Map;
422
+ const byDomain = new Map;
423
+ for (const raw of records) {
424
+ const record = checkConnection(raw);
425
+ if (byId.has(record.id)) {
426
+ throw new TypeError(`createMemoryConnections: duplicate id "${record.id}"`);
427
+ }
428
+ byId.set(record.id, record);
429
+ for (const domain of record.domains) {
430
+ if (byDomain.has(domain)) {
431
+ throw new TypeError(`createMemoryConnections: the domain "${domain}" belongs to two connections`);
432
+ }
433
+ byDomain.set(domain, record);
434
+ }
435
+ }
436
+ return {
437
+ findConnection: async (id) => byId.get(id) ?? null,
438
+ findConnectionByDomain: async (domain) => {
439
+ const ascii = normalizeDomain(domain);
440
+ return ascii === null ? null : byDomain.get(ascii) ?? null;
441
+ }
442
+ };
443
+ }
444
+ // src/failure.ts
445
+ import { SocialError } from "@softistx/janus";
446
+ import {
447
+ AuthorizationResponseError,
448
+ OperationProcessingError,
449
+ ResponseBodyError,
450
+ UnsupportedOperationError,
451
+ WWWAuthenticateChallengeError
452
+ } from "oauth4webapi";
453
+
454
+ // src/guard-error.ts
455
+ class GuardError extends Error {
456
+ code;
457
+ constructor(code) {
458
+ super(`the guarded transport refused the request (${code})`);
459
+ this.name = "GuardError";
460
+ this.code = code;
461
+ }
462
+ }
463
+
464
+ // src/failure.ts
465
+ function providerError(step, reason, cause) {
466
+ const said = reason === "denied" ? "the visitor refused the authorization" : reason === "unreachable" ? "the identity provider could not be reached" : "the identity provider refused or answered something unusable";
467
+ return new SocialError("PROVIDER_ERROR", `${step}: ${said}`, {
468
+ reason,
469
+ ...cause === undefined ? {} : { cause }
470
+ });
471
+ }
472
+ async function inStep(step, run) {
473
+ try {
474
+ return await run();
475
+ } catch (failure) {
476
+ throw classify(step, failure);
477
+ }
478
+ }
479
+ function scrubbed(failure) {
480
+ const { code, error } = failure;
481
+ return {
482
+ name: failure.name,
483
+ ...typeof code === "string" ? { code } : {},
484
+ ...typeof error === "string" && /^[\x20-\x7e]{1,64}$/.test(error) ? { error } : {}
485
+ };
486
+ }
487
+ function classify(step, failure) {
488
+ if (failure instanceof SocialError)
489
+ return failure;
490
+ if (failure instanceof GuardError) {
491
+ return providerError(step, failure.code === "dns" || failure.code === "server-error" ? "unreachable" : "refused", scrubbed(failure));
492
+ }
493
+ if (failure instanceof AuthorizationResponseError) {
494
+ return providerError(step, failure.error === "access_denied" ? "denied" : "refused", scrubbed(failure));
495
+ }
496
+ if (failure instanceof ResponseBodyError || failure instanceof WWWAuthenticateChallengeError || failure instanceof UnsupportedOperationError || failure instanceof OperationProcessingError) {
497
+ return providerError(step, "refused", scrubbed(failure));
498
+ }
499
+ return providerError(step, reached(failure) ? "refused" : "unreachable", failure instanceof Error ? scrubbed(failure) : undefined);
500
+ }
501
+ function reached(failure) {
502
+ if (failure instanceof TypeError)
503
+ return false;
504
+ if (failure instanceof DOMException)
505
+ return false;
506
+ const cause = failure?.cause;
507
+ if (cause instanceof TypeError || cause instanceof DOMException)
508
+ return false;
509
+ return true;
510
+ }
511
+
512
+ // src/authorization-url.ts
513
+ import { calculatePKCECodeChallenge } from "oauth4webapi";
514
+ async function authorizationUrl(request, flow, withNonce) {
515
+ const url = new URL(request.endpoint);
516
+ if (url.protocol !== "https:")
517
+ throw providerError("authorization URL", "refused");
518
+ const query = url.searchParams;
519
+ query.delete("response_mode");
520
+ for (const [name, value] of Object.entries(request.extra ?? {})) {
521
+ query.set(name, value);
522
+ }
523
+ query.set("response_type", "code");
524
+ query.set("client_id", request.clientId);
525
+ query.set("redirect_uri", request.redirectUri);
526
+ query.set("scope", request.scopes.join(" "));
527
+ query.set("state", flow.state);
528
+ if (withNonce)
529
+ query.set("nonce", flow.nonce);
530
+ query.set("code_challenge", await calculatePKCECodeChallenge(flow.codeVerifier));
531
+ query.set("code_challenge_method", "S256");
532
+ return url;
533
+ }
534
+
535
+ // src/code-exchange.ts
536
+ import * as oauth2 from "oauth4webapi";
537
+
538
+ // src/dpop.ts
539
+ import * as oauth from "oauth4webapi";
540
+ function dpopAlgorithm(dpop) {
541
+ if (dpop === undefined)
542
+ return;
543
+ return dpop === true ? "ES256" : dpop.algorithm;
544
+ }
545
+ async function newHandle(algorithm) {
546
+ const keyPair = await oauth.generateKeyPair(algorithm);
547
+ return oauth.DPoP({}, keyPair);
548
+ }
549
+ async function withNonceRetry(attempt) {
550
+ try {
551
+ return await attempt();
552
+ } catch (failure) {
553
+ if (!oauth.isDPoPNonceError(failure))
554
+ throw failure;
555
+ return attempt();
556
+ }
557
+ }
558
+
559
+ // src/code-exchange.ts
560
+ function clientOf(clientId, extras = {}) {
561
+ return {
562
+ client_id: clientId,
563
+ ...extras.idTokenSignedResponseAlg === undefined ? {} : { id_token_signed_response_alg: extras.idTokenSignedResponseAlg },
564
+ ...extras.clockTolerance === undefined ? {} : { [oauth2.clockTolerance]: extras.clockTolerance }
565
+ };
566
+ }
567
+ async function newKey(algorithm) {
568
+ try {
569
+ return await newHandle(algorithm);
570
+ } catch (failure) {
571
+ throw new TypeError(`this runtime cannot generate a "${algorithm}" DPoP key`, { cause: failure });
572
+ }
573
+ }
574
+ async function redeem(setup, flow) {
575
+ const client = clientOf(setup.clientId, setup.idToken?.clientExtras);
576
+ const parameters = await inStep("the authorization response", () => oauth2.validateAuthResponse(setup.server, client, flow.callback, flow.state));
577
+ const algorithm = setup.dpop;
578
+ const handle = algorithm === undefined ? undefined : await newKey(algorithm);
579
+ const run = (attempt) => handle === undefined ? attempt() : withNonceRetry(attempt);
580
+ const tokens = await inStep("the token response", () => run(async () => {
581
+ const answer = await inStep("the token request", () => oauth2.authorizationCodeGrantRequest(setup.server, client, setup.auth, parameters, setup.redirectUri, flow.codeVerifier, { ...setup.http, ...handle === undefined ? {} : { DPoP: handle } }));
582
+ const server = setup.serverForTokens === undefined ? setup.server : await setup.serverForTokens(answer.clone());
583
+ const processed = await oauth2.processAuthorizationCodeResponse(server, client, answer, {
584
+ expectedNonce: setup.oidc ? flow.nonce : oauth2.expectNoNonce,
585
+ requireIdToken: setup.oidc
586
+ });
587
+ if (handle !== undefined && processed.token_type !== "dpop") {
588
+ throw providerError("the token response", "refused");
589
+ }
590
+ await trusted(setup, answer, processed);
591
+ return processed;
592
+ }));
593
+ return { tokens, claims: oauth2.getValidatedIdTokenClaims(tokens) };
594
+ }
595
+ async function trusted(setup, answer, tokens) {
596
+ const steps = setup.idToken;
597
+ if (steps === undefined)
598
+ return;
599
+ await inStep("the ID token", async () => {
600
+ await steps.verifySignature(answer, tokens);
601
+ const claims = oauth2.getValidatedIdTokenClaims(tokens);
602
+ if (claims === undefined)
603
+ throw providerError("the ID token", "refused");
604
+ await steps.checkIdToken(tokens, claims);
605
+ });
606
+ }
607
+
608
+ // src/pushed-authorization.ts
609
+ import * as oauth3 from "oauth4webapi";
610
+ var STEP = "the pushed authorization request";
611
+ function shouldPush(server, mode) {
612
+ const endpoint = server.pushed_authorization_request_endpoint;
613
+ const required = server.require_pushed_authorization_requests === true;
614
+ if (mode === "auto" && !required)
615
+ return false;
616
+ if (endpoint === undefined)
617
+ throw providerError(STEP, "refused");
618
+ return true;
619
+ }
620
+ function push(setup, url, endpoint) {
621
+ const client = clientOf(setup.clientId);
622
+ const own = new URL(endpoint).searchParams;
623
+ const parameters = new URLSearchParams;
624
+ for (const [key, value] of url.searchParams) {
625
+ if (!own.has(key) || own.get(key) !== value)
626
+ parameters.append(key, value);
627
+ }
628
+ return inStep(STEP, async () => {
629
+ const answer = await oauth3.pushedAuthorizationRequest(setup.server, client, setup.auth, parameters, setup.http);
630
+ const { request_uri } = await oauth3.processPushedAuthorizationResponse(setup.server, client, answer);
631
+ const sent = new URL(endpoint);
632
+ sent.searchParams.delete("response_mode");
633
+ sent.searchParams.set("client_id", setup.clientId);
634
+ sent.searchParams.set("request_uri", request_uri);
635
+ return sent;
636
+ });
637
+ }
638
+
639
+ // src/transport.ts
640
+ import * as oauth4 from "oauth4webapi";
641
+ var DEFAULT_TIMEOUT = 1e4;
642
+ function transport(fetchWith, timeout) {
643
+ const signal = () => AbortSignal.timeout(timeout ?? DEFAULT_TIMEOUT);
644
+ if (fetchWith === undefined)
645
+ return { signal };
646
+ return {
647
+ signal,
648
+ [oauth4.customFetch]: (url, options) => fetchWith(url, options)
649
+ };
650
+ }
651
+ function fetcher(fetchWith, timeout) {
652
+ const base = fetchWith ?? ((input, init) => fetch(input, init));
653
+ return (input, init) => base(input, {
654
+ ...init,
655
+ signal: init?.signal ?? AbortSignal.timeout(timeout ?? DEFAULT_TIMEOUT)
656
+ });
657
+ }
658
+ function clientAuth(secret, method) {
659
+ return method === "basic" ? oauth4.ClientSecretBasic(secret) : oauth4.ClientSecretPost(secret);
660
+ }
661
+
662
+ // src/oidc-engine.ts
663
+ function methodOf(server) {
664
+ const listed = server.token_endpoint_auth_methods_supported;
665
+ if (listed === undefined)
666
+ return "basic";
667
+ return listed.includes("client_secret_post") ? "post" : "basic";
668
+ }
669
+ function createOidcProvider(engine) {
670
+ const { credentials } = engine;
671
+ const dpop = dpopAlgorithm(engine.security?.dpop);
672
+ const open = async () => engine.session === undefined ? {
673
+ server: await engine.server(),
674
+ http: transport(credentials.fetch, credentials.timeout)
675
+ } : engine.session();
676
+ const methodFor = (server) => engine.authentication ?? methodOf(server);
677
+ return {
678
+ supportsStepUp: engine.perRequestStepUp,
679
+ async authorizationUrl(flow) {
680
+ const { server, http } = await open();
681
+ const endpoint = server.authorization_endpoint;
682
+ if (endpoint === undefined) {
683
+ throw providerError("authorization URL", "refused");
684
+ }
685
+ const stepUp = engine.perRequestStepUp ? stepUpParams(combineStepUp(engine.fixedStepUp ?? {}, flow.stepUp)) : {};
686
+ const extra = { ...engine.authorizationParams, ...stepUp };
687
+ const url = await authorizationUrl({
688
+ endpoint,
689
+ clientId: credentials.clientId,
690
+ redirectUri: credentials.redirectUri,
691
+ scopes: engine.scopes,
692
+ ...Object.keys(extra).length === 0 ? {} : { extra }
693
+ }, flow, true);
694
+ if (!shouldPush(server, engine.security?.pushedAuthorization ?? "auto")) {
695
+ return url;
696
+ }
697
+ return push({
698
+ server,
699
+ clientId: credentials.clientId,
700
+ auth: clientAuth(credentials.clientSecret, methodFor(server)),
701
+ http
702
+ }, url, endpoint);
703
+ },
704
+ async exchange(flow) {
705
+ const { server, http, idToken } = await open();
706
+ const { serverForTokens } = engine;
707
+ const { claims } = await redeem({
708
+ clientId: credentials.clientId,
709
+ auth: clientAuth(credentials.clientSecret, methodFor(server)),
710
+ redirectUri: credentials.redirectUri,
711
+ http,
712
+ server,
713
+ oidc: true,
714
+ ...idToken === undefined ? {} : { idToken },
715
+ ...dpop === undefined ? {} : { dpop },
716
+ ...serverForTokens === undefined ? {} : { serverForTokens: (answer) => serverForTokens(server, answer) }
717
+ }, flow);
718
+ if (claims === undefined)
719
+ throw providerError("the ID token", "refused");
720
+ return inStep("the ID token", () => ({
721
+ ...engine.identity(claims),
722
+ ...engine.perRequestStepUp ? stepUpClaims(claims) : {}
723
+ }));
724
+ }
725
+ };
726
+ }
727
+
728
+ // src/claims.ts
729
+ function text(claims, name) {
730
+ const value = claims[name];
731
+ return typeof value === "string" && value !== "" ? value : undefined;
732
+ }
733
+ function isTrue(claims, name) {
734
+ const value = claims[name];
735
+ return value === true || value === "true";
736
+ }
737
+ function identityOf(claims, verified, step) {
738
+ const accountId = text(claims, "sub");
739
+ if (accountId === undefined) {
740
+ throw providerError(step, "refused");
741
+ }
742
+ const email = text(claims, "email") ?? null;
743
+ const name = text(claims, "name");
744
+ const picture = text(claims, "picture");
745
+ return {
746
+ accountId,
747
+ email,
748
+ emailVerified: email !== null && verified,
749
+ ...name === undefined ? {} : { name },
750
+ ...picture === undefined ? {} : { picture }
751
+ };
752
+ }
753
+
754
+ // src/connections/claims.ts
755
+ function canonical(address) {
756
+ const domain = domainOfEmail(address);
757
+ return domain === null ? null : {
758
+ email: `${address.slice(0, address.indexOf("@"))}@${domain}`,
759
+ domain
760
+ };
761
+ }
762
+ function listed(domains, domain) {
763
+ return domains.includes(domain);
764
+ }
765
+ function connectionIdentity(connection, claims, step) {
766
+ const accountId = text(claims, "sub");
767
+ if (accountId === undefined) {
768
+ throw providerError(step, "refused");
769
+ }
770
+ const names = connection.claims ?? {};
771
+ const address = text(claims, names.email ?? "email");
772
+ const parsed = address === undefined ? null : canonical(address);
773
+ const email = parsed === null ? null : parsed.email;
774
+ const domain = parsed === null ? null : parsed.domain;
775
+ const claimed = isTrue(claims, names.emailVerified ?? "email_verified");
776
+ const owned = domain !== null && listed(connection.domains, domain);
777
+ const trust = connection.emailTrust ?? "claimAndDomain";
778
+ const verified = email !== null && (trust === "claim" ? claimed : trust === "domain" ? owned : claimed && owned);
779
+ const name = text(claims, names.name ?? "name");
780
+ const picture = text(claims, names.picture ?? "picture");
781
+ return {
782
+ accountId,
783
+ email,
784
+ emailVerified: verified,
785
+ ...name === undefined ? {} : { name },
786
+ ...picture === undefined ? {} : { picture }
787
+ };
788
+ }
789
+
790
+ // src/connections/id-token.ts
791
+ import { SocialError as SocialError2 } from "@softistx/janus";
792
+
793
+ // src/connections/at-hash.ts
794
+ import { timingSafeEqual } from "node:crypto";
795
+ function atHashAlgorithm(alg) {
796
+ if (alg === "EdDSA")
797
+ return "SHA-512";
798
+ const size = /^(?:RS|PS|ES)(256|384|512)$/.exec(alg)?.[1];
799
+ return size === undefined ? undefined : `SHA-${size}`;
800
+ }
801
+ async function atHashOf(alg, accessToken) {
802
+ const hash = atHashAlgorithm(alg);
803
+ if (hash === undefined || !/^[\x20-\x7e]+$/.test(accessToken))
804
+ return;
805
+ const digest = await crypto.subtle.digest(hash, new TextEncoder().encode(accessToken));
806
+ return Buffer.from(digest.slice(0, digest.byteLength / 2)).toString("base64url");
807
+ }
808
+ async function atHashMatches(alg, claim, accessToken) {
809
+ if (typeof claim !== "string")
810
+ return false;
811
+ const expected = await atHashOf(alg, accessToken);
812
+ if (expected === undefined)
813
+ return false;
814
+ const given = Buffer.from(claim);
815
+ const wanted = Buffer.from(expected);
816
+ return given.length === wanted.length && timingSafeEqual(given, wanted);
817
+ }
818
+
819
+ // src/connections/id-token.ts
820
+ var CLOCK_TOLERANCE = 30;
821
+ var DEFAULT_ALGORITHMS = [
822
+ "RS256",
823
+ "PS256",
824
+ "ES256",
825
+ "EdDSA"
826
+ ];
827
+ var MAX_SUB = 255;
828
+ function refused(check) {
829
+ return providerError("the ID token", "refused", { check });
830
+ }
831
+ function algorithmsOf(pinned) {
832
+ if (pinned === undefined)
833
+ return DEFAULT_ALGORITHMS;
834
+ if (!CONNECTION_ALGORITHMS.includes(pinned)) {
835
+ throw new TypeError('oidcConnections: "client.idTokenSignedResponseAlg" is not an accepted algorithm');
836
+ }
837
+ return [pinned];
838
+ }
839
+ function headerAlgorithm(idToken) {
840
+ if (typeof idToken !== "string")
841
+ throw refused("alg");
842
+ try {
843
+ const header = JSON.parse(Buffer.from(idToken.split(".", 1)[0] ?? "", "base64url").toString());
844
+ const alg = header?.alg;
845
+ if (typeof alg === "string")
846
+ return alg;
847
+ } catch {}
848
+ throw refused("alg");
849
+ }
850
+ function checkAlgorithm(idToken, algorithms) {
851
+ const alg = headerAlgorithm(idToken);
852
+ if (!algorithms.includes(alg))
853
+ throw refused("alg");
854
+ return alg;
855
+ }
856
+ function checkClaims(claims, policy, nowSeconds) {
857
+ if (claims.iss !== policy.issuer)
858
+ throw refused("iss");
859
+ const { sub, azp, iat } = claims;
860
+ if (typeof sub !== "string" || sub === "" || sub.length > MAX_SUB) {
861
+ throw refused("sub");
862
+ }
863
+ if (azp !== undefined && azp !== policy.clientId)
864
+ throw refused("azp");
865
+ if (Array.isArray(claims.aud) && claims.aud.length > 1 && azp === undefined) {
866
+ throw refused("azp");
867
+ }
868
+ if (typeof iat !== "number" || !Number.isFinite(iat))
869
+ throw refused("iat");
870
+ if (iat > nowSeconds + CLOCK_TOLERANCE)
871
+ throw refused("iat");
872
+ }
873
+ async function checkAtHash(claims, alg, accessToken) {
874
+ const claim = claims["at_hash"];
875
+ if (claim === undefined)
876
+ return;
877
+ if (!await atHashMatches(alg, claim, accessToken))
878
+ throw refused("at_hash");
879
+ }
880
+ function requireStepUp(claims, stepUp, nowMs) {
881
+ if (stepUp === undefined)
882
+ return;
883
+ if (!holdsStepUp(claims, stepUp.acrValues, stepUp.maxAge, nowMs)) {
884
+ throw new SocialError2("SOCIAL_STEP_UP_UNMET", "the ID token: the identity provider did not prove the step-up this provider requires");
885
+ }
886
+ }
887
+
888
+ // src/connections/id-token-steps.ts
889
+ function idTokenSteps(policy, verifyKeys) {
890
+ const algorithms = algorithmsOf(policy.algorithm);
891
+ const now = policy.now ?? Date.now;
892
+ const read = new WeakMap;
893
+ return {
894
+ clientExtras: {
895
+ clockTolerance: CLOCK_TOLERANCE,
896
+ ...policy.algorithm === undefined ? {} : { idTokenSignedResponseAlg: policy.algorithm }
897
+ },
898
+ async verifySignature(answer, tokens) {
899
+ read.set(tokens, checkAlgorithm(tokens.id_token, algorithms));
900
+ await verifyKeys(answer);
901
+ },
902
+ async checkIdToken(tokens, claims) {
903
+ const nowMs = now();
904
+ checkClaims(claims, policy, Math.floor(nowMs / 1000));
905
+ await checkAtHash(claims, read.get(tokens) ?? headerAlgorithm(tokens.id_token), tokens.access_token);
906
+ requireStepUp(claims, policy.stepUp, nowMs);
907
+ }
908
+ };
909
+ }
910
+
911
+ // src/connections/provider.ts
912
+ function policyOf(connection) {
913
+ return {
914
+ issuer: connection.issuer,
915
+ clientId: connection.client.id,
916
+ algorithm: connection.client.idTokenSignedResponseAlg,
917
+ stepUp: connection.stepUp
918
+ };
919
+ }
920
+ function connectionProvider(connection, wiring) {
921
+ const policy = policyOf(connection);
922
+ idTokenSteps(policy, async () => {});
923
+ const scopes = connection.scopes ?? DEFAULT_SCOPES;
924
+ return createOidcProvider({
925
+ credentials: {
926
+ clientId: connection.client.id,
927
+ clientSecret: connection.client.secret,
928
+ redirectUri: wiring.redirectUri
929
+ },
930
+ security: connection,
931
+ scopes: scopes.includes("openid") ? scopes : ["openid", ...scopes],
932
+ ...connection.client.authentication === undefined ? {} : { authentication: connection.client.authentication },
933
+ perRequestStepUp: true,
934
+ ...connection.stepUp === undefined ? {} : { fixedStepUp: connection.stepUp },
935
+ session: async () => {
936
+ const found = await wiring.servers(connection);
937
+ return {
938
+ server: found.as,
939
+ http: found.http,
940
+ idToken: idTokenSteps(policy, found.verifySignature)
941
+ };
942
+ },
943
+ identity: (claims) => connectionIdentity(connection, claims, "the ID token")
944
+ });
945
+ }
946
+
947
+ // src/connections/server.ts
948
+ import { systemClock } from "@softistx/janus";
949
+ import * as oauth6 from "oauth4webapi";
950
+
951
+ // src/connections/abort.ts
952
+ function untilAborted(promise, signal, discard) {
953
+ return new Promise((resolve, reject) => {
954
+ if (signal.aborted) {
955
+ if (discard !== undefined)
956
+ promise.then(discard, () => {
957
+ return;
958
+ });
959
+ return reject(signal.reason);
960
+ }
961
+ const stop = () => {
962
+ if (discard !== undefined)
963
+ promise.then(discard, () => {
964
+ return;
965
+ });
966
+ reject(signal.reason);
967
+ };
968
+ signal.addEventListener("abort", stop, { once: true });
969
+ promise.then(resolve, reject).finally(() => {
970
+ signal.removeEventListener("abort", stop);
971
+ });
972
+ });
973
+ }
974
+
975
+ // src/connections/body-limit.ts
976
+ var DEFAULT_MAX_BYTES = 64 * 1024;
977
+ var LARGE_MAX_BYTES = 256 * 1024;
978
+ function isJson(contentType) {
979
+ const type = (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
980
+ return /^application\/(?:[a-z0-9.!#$&^_-]+\+)?json$/.test(type);
981
+ }
982
+ async function capped(response, max, signal) {
983
+ const declared = response.headers.get("content-length");
984
+ if (declared !== null && Number(declared) > max) {
985
+ await response.body?.cancel().catch(() => {
986
+ return;
987
+ });
988
+ throw new GuardError("oversize");
989
+ }
990
+ const chunks = [];
991
+ let total = 0;
992
+ const reader = response.body?.getReader();
993
+ while (reader !== undefined) {
994
+ const { done, value } = await untilAborted(reader.read(), signal).catch(async (stop) => {
995
+ await reader.cancel().catch(() => {
996
+ return;
997
+ });
998
+ throw stop;
999
+ });
1000
+ if (done)
1001
+ break;
1002
+ total += value.byteLength;
1003
+ if (total > max) {
1004
+ await reader.cancel().catch(() => {
1005
+ return;
1006
+ });
1007
+ throw new GuardError("oversize");
1008
+ }
1009
+ chunks.push(value);
1010
+ }
1011
+ const body = new Uint8Array(total);
1012
+ let offset = 0;
1013
+ for (const chunk of chunks) {
1014
+ body.set(chunk, offset);
1015
+ offset += chunk.byteLength;
1016
+ }
1017
+ const headers = new Headers(response.headers);
1018
+ headers.delete("content-length");
1019
+ headers.delete("content-encoding");
1020
+ const empty = total === 0 && [101, 204, 205, 304].includes(response.status);
1021
+ return new Response(empty ? null : body, {
1022
+ status: response.status,
1023
+ statusText: response.statusText,
1024
+ headers
1025
+ });
1026
+ }
1027
+
1028
+ // src/connections/discovery.ts
1029
+ import * as oauth5 from "oauth4webapi";
1030
+
1031
+ // src/connections/ip.ts
1032
+ function parseV4(text) {
1033
+ const parts = text.split(".");
1034
+ if (parts.length !== 4)
1035
+ return;
1036
+ const bytes = [];
1037
+ for (const part of parts) {
1038
+ if (!/^(?:0|[1-9]\d{0,2})$/.test(part))
1039
+ return;
1040
+ const value = Number(part);
1041
+ if (value > 255)
1042
+ return;
1043
+ bytes.push(value);
1044
+ }
1045
+ return bytes;
1046
+ }
1047
+ function parseV6(text) {
1048
+ let source = text.replace(/^\[|\]$/g, "");
1049
+ if (!source.includes(":") || source.includes("%"))
1050
+ return;
1051
+ const tail = source.slice(source.lastIndexOf(":") + 1);
1052
+ if (tail.includes(".")) {
1053
+ const v4 = parseV4(tail);
1054
+ if (v4 === undefined)
1055
+ return;
1056
+ const hex = (a, b) => (a << 8 | b).toString(16);
1057
+ source = `${source.slice(0, source.length - tail.length)}${hex(v4[0], v4[1])}:${hex(v4[2], v4[3])}`;
1058
+ }
1059
+ const halves = source.split("::");
1060
+ if (halves.length > 2)
1061
+ return;
1062
+ const groups = (side) => side === "" ? [] : side.split(":");
1063
+ const head = groups(halves[0] ?? "");
1064
+ const rest = halves.length === 2 ? groups(halves[1] ?? "") : [];
1065
+ const missing = 8 - head.length - rest.length;
1066
+ if (halves.length === 2 ? missing < 1 : missing !== 0)
1067
+ return;
1068
+ const all = [
1069
+ ...head,
1070
+ ...Array(halves.length === 2 ? missing : 0).fill("0"),
1071
+ ...rest
1072
+ ];
1073
+ if (all.length !== 8 || !all.every((group) => /^[0-9a-f]{1,4}$/i.test(group))) {
1074
+ return;
1075
+ }
1076
+ return all.map((group) => Number.parseInt(group, 16));
1077
+ }
1078
+ function publicV4([a, b, c]) {
1079
+ if (a === 0 || a === 10 || a === 127 || a >= 224)
1080
+ return false;
1081
+ if (a === 100 && b >= 64 && b <= 127)
1082
+ return false;
1083
+ if (a === 169 && b === 254)
1084
+ return false;
1085
+ if (a === 172 && b >= 16 && b <= 31)
1086
+ return false;
1087
+ if (a === 192 && b === 168)
1088
+ return false;
1089
+ if (a === 192 && b === 88 && c === 99)
1090
+ return false;
1091
+ if (a === 192 && b === 0 && (c === 0 || c === 2))
1092
+ return false;
1093
+ if (a === 198 && (b === 18 || b === 19))
1094
+ return false;
1095
+ if (a === 198 && b === 51 && c === 100)
1096
+ return false;
1097
+ if (a === 203 && b === 0 && c === 113)
1098
+ return false;
1099
+ return true;
1100
+ }
1101
+ var embedded = (high, low) => [
1102
+ high >> 8,
1103
+ high & 255,
1104
+ low >> 8,
1105
+ low & 255
1106
+ ];
1107
+ function publicV6(g) {
1108
+ const [g0, g1, g2, g3, g4, g5, g6, g7] = g;
1109
+ if ([g0, g1, g2, g3, g4, g5].every((group) => group === 0))
1110
+ return false;
1111
+ if ([g0, g1, g2, g3, g4].every((group) => group === 0) && g5 === 65535) {
1112
+ return publicV4(embedded(g6, g7));
1113
+ }
1114
+ if ([g0, g1, g2, g3].every((group) => group === 0) && g4 === 65535 && g5 === 0) {
1115
+ return publicV4(embedded(g6, g7));
1116
+ }
1117
+ if (g0 === 16383 && g1 < 4096)
1118
+ return false;
1119
+ if (g0 === 100 && g1 === 65435) {
1120
+ if (g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0) {
1121
+ return publicV4(embedded(g6, g7));
1122
+ }
1123
+ return g2 !== 1;
1124
+ }
1125
+ if (g0 === 8194)
1126
+ return publicV4(embedded(g1, g2));
1127
+ if (g0 === 8193 && g1 === 0)
1128
+ return false;
1129
+ if (g0 === 8193 && g1 === 3512)
1130
+ return false;
1131
+ if (g0 === 8193 && g1 === 2 && g2 === 0)
1132
+ return false;
1133
+ if (g0 === 8193 && (g1 & 65520) === 16)
1134
+ return false;
1135
+ if (g0 === 8193 && (g1 & 65520) === 32)
1136
+ return false;
1137
+ if (g0 === 256 && g1 === 0 && g2 === 0 && g3 === 0)
1138
+ return false;
1139
+ if ((g0 & 65024) === 64512)
1140
+ return false;
1141
+ if ((g0 & 65472) === 65152)
1142
+ return false;
1143
+ if ((g0 & 65472) === 65216)
1144
+ return false;
1145
+ if (g0 >> 8 === 255)
1146
+ return false;
1147
+ return true;
1148
+ }
1149
+ function publicAddress(text) {
1150
+ const v4 = parseV4(text);
1151
+ if (v4 !== undefined)
1152
+ return publicV4(v4);
1153
+ const v6 = parseV6(text);
1154
+ return v6 !== undefined && publicV6(v6);
1155
+ }
1156
+
1157
+ // src/connections/url-policy.ts
1158
+ function urlRefusal(url, allowUrl) {
1159
+ if (url.protocol !== "https:")
1160
+ return "scheme";
1161
+ if (url.username !== "" || url.password !== "")
1162
+ return "credentials";
1163
+ const refused = hostRefusal(url.hostname);
1164
+ if (refused !== undefined)
1165
+ return refused;
1166
+ return allowUrl !== undefined && allowUrl(url) !== true ? "allowUrl" : undefined;
1167
+ }
1168
+ function literalOf(hostname) {
1169
+ const host = hostname.toLowerCase();
1170
+ if (host.startsWith("["))
1171
+ return host;
1172
+ return parseV4(host) === undefined ? undefined : host;
1173
+ }
1174
+ function hostRefusal(hostname) {
1175
+ const host = hostname.toLowerCase().replace(/\.$/, "");
1176
+ if (host === "" || host.endsWith("."))
1177
+ return "host";
1178
+ if (host.startsWith("[")) {
1179
+ const groups = parseV6(host);
1180
+ return groups !== undefined && publicV6(groups) ? undefined : "address";
1181
+ }
1182
+ const v4 = parseV4(host);
1183
+ if (v4 !== undefined)
1184
+ return publicV4(v4) ? undefined : "address";
1185
+ if (/^[0-9.]+$/.test(host) || /(?:^|\.)(?:0x[0-9a-f]*|\d+)$/.test(host)) {
1186
+ return "host";
1187
+ }
1188
+ if (host === "localhost" || host.endsWith(".localhost"))
1189
+ return "localhost";
1190
+ return host.includes(".") ? undefined : "single-label";
1191
+ }
1192
+ function addressesRefusal(addresses) {
1193
+ if (addresses.length === 0)
1194
+ return "empty";
1195
+ return addresses.every(publicAddress) ? undefined : "address";
1196
+ }
1197
+
1198
+ // src/connections/discovery.ts
1199
+ var REQUIRED = [
1200
+ "authorization_endpoint",
1201
+ "token_endpoint",
1202
+ "jwks_uri"
1203
+ ];
1204
+ function discoverIssuer(issuer, http, allowUrl) {
1205
+ return inStep("discovery", async () => {
1206
+ const url = new URL(issuer);
1207
+ const as = await oauth5.processDiscoveryResponse(url, await oauth5.discoveryRequest(url, { algorithm: "oidc", ...http }));
1208
+ if (as.issuer !== issuer)
1209
+ throw providerError("discovery", "refused");
1210
+ for (const name of REQUIRED) {
1211
+ if (typeof as[name] !== "string")
1212
+ throw providerError("discovery", "refused");
1213
+ }
1214
+ for (const value of urlMembers(as)) {
1215
+ if (!allowed(value, allowUrl))
1216
+ throw providerError("discovery", "refused");
1217
+ }
1218
+ const algs = as.id_token_signing_alg_values_supported;
1219
+ if (algs !== undefined && (!Array.isArray(algs) || algs.includes("none"))) {
1220
+ throw providerError("discovery", "refused");
1221
+ }
1222
+ return as;
1223
+ });
1224
+ }
1225
+ function urlMembers(as) {
1226
+ const found = [];
1227
+ for (const [name, value] of Object.entries(as)) {
1228
+ if (name.endsWith("_endpoint") || name.endsWith("_uri") || name === "check_session_iframe") {
1229
+ found.push(value);
1230
+ } else if (name === "mtls_endpoint_aliases") {
1231
+ if (typeof value !== "object" || value === null)
1232
+ found.push(value);
1233
+ else
1234
+ found.push(...Object.values(value));
1235
+ }
1236
+ }
1237
+ return found;
1238
+ }
1239
+ function allowed(value, allowUrl) {
1240
+ if (typeof value !== "string")
1241
+ return false;
1242
+ try {
1243
+ return urlRefusal(new URL(value), allowUrl) === undefined;
1244
+ } catch {
1245
+ return false;
1246
+ }
1247
+ }
1248
+
1249
+ // src/connections/guarded-fetch.ts
1250
+ import { lookup } from "node:dns/promises";
1251
+ var GUARD_TIMEOUT = 1e4;
1252
+ var dnsLookup = async (host) => (await lookup(host, { all: true })).map((entry) => entry.address);
1253
+ function guardedFetch(options = {}) {
1254
+ const send = options.fetch ?? ((input, init) => fetch(input, init));
1255
+ const resolveHost = options.resolveHost ?? dnsLookup;
1256
+ return async (input, init) => {
1257
+ const url = urlOf(input);
1258
+ if (urlRefusal(url, options.allowUrl) !== undefined)
1259
+ throw new GuardError("url");
1260
+ const timeout = AbortSignal.timeout(options.timeout ?? GUARD_TIMEOUT);
1261
+ const signals = [timeout];
1262
+ if (init?.signal)
1263
+ signals.push(init.signal);
1264
+ if (input instanceof Request)
1265
+ signals.push(input.signal);
1266
+ const signal = AbortSignal.any(signals);
1267
+ signal.throwIfAborted();
1268
+ await checkAddresses(url, resolveHost, signal);
1269
+ const response = await untilAborted(send(input, { ...init, redirect: "manual", signal }), signal, (late) => void late.body?.cancel().catch(() => {
1270
+ return;
1271
+ }));
1272
+ if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
1273
+ await response.body?.cancel().catch(() => {
1274
+ return;
1275
+ });
1276
+ throw new GuardError("redirect");
1277
+ }
1278
+ if (!isJson(response.headers.get("content-type"))) {
1279
+ await response.body?.cancel().catch(() => {
1280
+ return;
1281
+ });
1282
+ throw new GuardError(response.status >= 500 ? "server-error" : "content-type");
1283
+ }
1284
+ const { maxBytes = DEFAULT_MAX_BYTES } = options;
1285
+ const max = typeof maxBytes === "number" ? maxBytes : maxBytes(url);
1286
+ return capped(response, max, signal);
1287
+ };
1288
+ }
1289
+ function urlOf(input) {
1290
+ try {
1291
+ return new URL(typeof input === "string" || input instanceof URL ? input : input.url);
1292
+ } catch {
1293
+ throw new GuardError("url");
1294
+ }
1295
+ }
1296
+ async function checkAddresses(url, resolveHost, signal) {
1297
+ if (literalOf(url.hostname) !== undefined)
1298
+ return;
1299
+ let addresses;
1300
+ try {
1301
+ addresses = await untilAborted(resolveHost(url.hostname.replace(/\.$/, "")), signal);
1302
+ } catch {
1303
+ signal.throwIfAborted();
1304
+ throw new GuardError("dns");
1305
+ }
1306
+ if (addressesRefusal(addresses) !== undefined)
1307
+ throw new GuardError("address");
1308
+ }
1309
+
1310
+ // src/connections/issuer-cache.ts
1311
+ var ISSUER_TTL_MS = 3600000;
1312
+ var FAILURE_COOLDOWN_MS = 30000;
1313
+ var DEFAULT_MAX_ISSUERS = 500;
1314
+ var DEFAULT_IDLE_MS = 3600000;
1315
+ function createIssuerCache(clock, options = {}) {
1316
+ const max = options.max ?? DEFAULT_MAX_ISSUERS;
1317
+ const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
1318
+ const pendingMs = options.pendingMs ?? Number.POSITIVE_INFINITY;
1319
+ const entries = new Map;
1320
+ const now = () => clock.now().getTime();
1321
+ function start(issuer, load, at) {
1322
+ const entry = {
1323
+ pending: Promise.resolve().then(load),
1324
+ state: "pending",
1325
+ endedAt: at,
1326
+ usedAt: at
1327
+ };
1328
+ entry.pending.then(() => {
1329
+ entry.state = "found";
1330
+ entry.endedAt = now();
1331
+ }, (failure) => {
1332
+ entry.state = "failed";
1333
+ entry.failure = failure;
1334
+ entry.endedAt = now();
1335
+ });
1336
+ entries.delete(issuer);
1337
+ entries.set(issuer, entry);
1338
+ for (const oldest of entries.keys()) {
1339
+ if (entries.size <= max)
1340
+ break;
1341
+ entries.delete(oldest);
1342
+ }
1343
+ return entry;
1344
+ }
1345
+ return {
1346
+ get(issuer, load) {
1347
+ const at = now();
1348
+ for (const [key, entry] of entries) {
1349
+ if (at - entry.usedAt >= idleMs)
1350
+ entries.delete(key);
1351
+ }
1352
+ const entry = entries.get(issuer);
1353
+ if (entry !== undefined) {
1354
+ const age = at - entry.endedAt;
1355
+ const usable = entry.state === "pending" && age < pendingMs || entry.state === "found" && age < ISSUER_TTL_MS || entry.state === "failed" && age < FAILURE_COOLDOWN_MS;
1356
+ if (usable) {
1357
+ entry.usedAt = at;
1358
+ entries.delete(issuer);
1359
+ entries.set(issuer, entry);
1360
+ return entry.state === "failed" ? Promise.reject(entry.failure) : entry.pending;
1361
+ }
1362
+ }
1363
+ return start(issuer, load, at).pending;
1364
+ }
1365
+ };
1366
+ }
1367
+
1368
+ // src/connections/key-flights.ts
1369
+ function keyFlights(clock) {
1370
+ const flights = new Map;
1371
+ return (base) => async (input, init) => {
1372
+ const url = String(input instanceof Request ? input.url : input instanceof URL ? input.href : input);
1373
+ const at = clock.now().getTime();
1374
+ for (const [key, flight] of flights) {
1375
+ if (flight.failure !== undefined && at - flight.failure.at >= FAILURE_COOLDOWN_MS) {
1376
+ flights.delete(key);
1377
+ }
1378
+ }
1379
+ let flight = flights.get(url);
1380
+ if (flight?.failure !== undefined)
1381
+ throw flight.failure.error;
1382
+ if (flight === undefined) {
1383
+ const made = {
1384
+ pending: Promise.resolve().then(() => base(input, init))
1385
+ };
1386
+ flight = made;
1387
+ flights.set(url, made);
1388
+ made.pending.then(() => {
1389
+ if (flights.get(url) === made)
1390
+ flights.delete(url);
1391
+ }, (error) => {
1392
+ made.failure = { error, at: clock.now().getTime() };
1393
+ });
1394
+ }
1395
+ return (await flight.pending).clone();
1396
+ };
1397
+ }
1398
+
1399
+ // src/connections/server.ts
1400
+ function isMalformedKey(failure) {
1401
+ return failure instanceof DOMException && (failure.name === "DataError" || failure.name === "NotSupportedError" || failure.name === "OperationError");
1402
+ }
1403
+ var PENDING_MARGIN_MS = 5000;
1404
+ function connectionServers(options = {}) {
1405
+ const guard = {
1406
+ ...options.fetch === undefined ? {} : { fetch: options.fetch },
1407
+ ...options.timeout === undefined ? {} : { timeout: options.timeout },
1408
+ ...options.allowUrl === undefined ? {} : { allowUrl: options.allowUrl },
1409
+ ...options.resolveHost === undefined ? {} : { resolveHost: options.resolveHost }
1410
+ };
1411
+ const clock = options.clock ?? systemClock;
1412
+ const flights = keyFlights(clock);
1413
+ const http = transport(guardedFetch(guard), options.timeout);
1414
+ const cache = createIssuerCache(clock, {
1415
+ ...options.cache,
1416
+ pendingMs: (options.timeout ?? GUARD_TIMEOUT) + PENDING_MARGIN_MS
1417
+ });
1418
+ return ({ issuer }) => {
1419
+ const problems = [];
1420
+ checkIssuer(problems, issuer);
1421
+ if (problems.length > 0) {
1422
+ return Promise.reject(providerError("discovery", "refused"));
1423
+ }
1424
+ return cache.get(issuer, async () => {
1425
+ const as = await discoverIssuer(issuer, http, options.allowUrl);
1426
+ const large = new Set([as.jwks_uri, as.userinfo_endpoint].filter((value) => value !== undefined).map((value) => new URL(value).href));
1427
+ const sized = guardedFetch({
1428
+ ...guard,
1429
+ maxBytes: (url) => large.has(url.href) ? LARGE_MAX_BYTES : DEFAULT_MAX_BYTES
1430
+ });
1431
+ const sizedHttp = transport(sized, options.timeout);
1432
+ const keys = transport(flights(sized), options.timeout);
1433
+ return {
1434
+ as,
1435
+ http: sizedHttp,
1436
+ verifySignature: (ref) => inStep("the ID token signature", async () => {
1437
+ try {
1438
+ await oauth6.validateApplicationLevelSignature(as, ref, keys);
1439
+ } catch (failure) {
1440
+ if (isMalformedKey(failure)) {
1441
+ throw providerError("the ID token signature", "refused");
1442
+ }
1443
+ throw failure;
1444
+ }
1445
+ })
1446
+ };
1447
+ });
1448
+ };
1449
+ }
1450
+
1451
+ // src/connections/wiring.ts
1452
+ var WHERE3 = "oidcConnections";
1453
+ function positive(name, value) {
1454
+ if (value !== undefined && !(Number.isInteger(value) && Number(value) > 0)) {
1455
+ throw new TypeError(`${WHERE3}: "cache.${name}" must be a positive integer`);
1456
+ }
1457
+ }
1458
+ function checkOptions(options) {
1459
+ if (!isObject(options)) {
1460
+ throw new TypeError(`${WHERE3}: the options must be an object`);
1461
+ }
1462
+ const source = options["source"];
1463
+ if (!isObject(source) || typeof source["findConnection"] !== "function" || typeof source["findConnectionByDomain"] !== "function") {
1464
+ throw new TypeError(`${WHERE3}: "source" must have findConnection and findConnectionByDomain`);
1465
+ }
1466
+ checkRedirectUri(WHERE3, options["redirectUri"]);
1467
+ checkFetch(WHERE3, options["fetch"]);
1468
+ checkTimeout(WHERE3, options["timeout"]);
1469
+ if (options["allowUrl"] !== undefined && typeof options["allowUrl"] !== "function") {
1470
+ throw new TypeError(`${WHERE3}: "allowUrl" must be a function`);
1471
+ }
1472
+ const cache = options["cache"];
1473
+ if (cache !== undefined) {
1474
+ if (!isObject(cache)) {
1475
+ throw new TypeError(`${WHERE3}: "cache" must be an object`);
1476
+ }
1477
+ positive("max", cache["max"]);
1478
+ positive("idleMs", cache["idleMs"]);
1479
+ }
1480
+ const clock = options["clock"];
1481
+ if (clock !== undefined && (!isObject(clock) || typeof clock["now"] !== "function")) {
1482
+ throw new TypeError(`${WHERE3}: "clock" must have a now() method`);
1483
+ }
1484
+ }
1485
+
1486
+ // src/connections/oidc-connections.ts
1487
+ function createConnections(options, resolveHost) {
1488
+ checkOptions(options);
1489
+ const { source } = options;
1490
+ const servers = connectionServers({
1491
+ ...options.fetch === undefined ? {} : { fetch: options.fetch },
1492
+ ...options.timeout === undefined ? {} : { timeout: options.timeout },
1493
+ ...options.allowUrl === undefined ? {} : { allowUrl: options.allowUrl },
1494
+ ...options.cache === undefined ? {} : { cache: options.cache },
1495
+ ...options.clock === undefined ? {} : { clock: options.clock },
1496
+ ...resolveHost === undefined ? {} : { resolveHost }
1497
+ });
1498
+ const wiring = { servers, redirectUri: options.redirectUri };
1499
+ const warned = new Set;
1500
+ function refuse(id) {
1501
+ if (!warned.has(id)) {
1502
+ warned.add(id);
1503
+ process.emitWarning(`oidcConnections: the stored connection "${id}" is malformed and is refused`, { code: "JANUS_SOCIAL_CONNECTION_REFUSED" });
1504
+ }
1505
+ return providerError("the connection", "refused");
1506
+ }
1507
+ return {
1508
+ async resolve(name) {
1509
+ if (typeof name !== "string" || !PROVIDER_NAME.test(name))
1510
+ return null;
1511
+ const stored = await source.findConnection(name);
1512
+ if (stored === null) {
1513
+ warned.delete(name);
1514
+ return null;
1515
+ }
1516
+ let provider;
1517
+ try {
1518
+ const record = checkConnection(stored);
1519
+ if (record.id !== name)
1520
+ throw new TypeError("id mismatch");
1521
+ provider = connectionProvider(record, wiring);
1522
+ } catch {
1523
+ throw refuse(name);
1524
+ }
1525
+ warned.delete(name);
1526
+ return provider;
1527
+ },
1528
+ async forEmail(email) {
1529
+ if (typeof email !== "string")
1530
+ return null;
1531
+ const domain = domainOfEmail(email);
1532
+ if (domain === null)
1533
+ return null;
1534
+ const found = await source.findConnectionByDomain(domain);
1535
+ return isObject(found) && typeof found["id"] === "string" && PROVIDER_NAME.test(found["id"]) ? found["id"] : null;
1536
+ }
1537
+ };
1538
+ }
1539
+ function oidcConnections(options) {
1540
+ return createConnections(options);
1541
+ }
1542
+ // src/github-identity.ts
1543
+ var API = "https://api.github.com";
1544
+ async function get(fetch2, path, accessToken) {
1545
+ const answer = await fetch2(`${API}${path}`, {
1546
+ headers: {
1547
+ accept: "application/vnd.github+json",
1548
+ authorization: `Bearer ${accessToken}`,
1549
+ "user-agent": "softistx-janus-social",
1550
+ "x-github-api-version": "2022-11-28"
1551
+ },
1552
+ redirect: "manual"
1553
+ });
1554
+ if (!answer.ok)
1555
+ throw providerError(`GitHub ${path}`, "refused");
1556
+ return answer.json();
1557
+ }
1558
+ async function githubIdentity(accessToken, fetch2) {
1559
+ const user = await get(fetch2, "/user", accessToken);
1560
+ const id = user?.id;
1561
+ if (typeof id !== "number" || !Number.isSafeInteger(id)) {
1562
+ throw providerError("GitHub /user", "refused");
1563
+ }
1564
+ const emails = await get(fetch2, "/user/emails", accessToken);
1565
+ const primary = Array.isArray(emails) ? emails.find((entry) => entry?.primary === true && entry.verified === true && typeof entry.email === "string" && entry.email !== "") : undefined;
1566
+ const email = typeof primary?.email === "string" ? primary.email : null;
1567
+ const name = typeof user?.name === "string" ? user.name : undefined;
1568
+ const picture = typeof user?.avatar_url === "string" ? user.avatar_url : undefined;
1569
+ return {
1570
+ accountId: String(id),
1571
+ email,
1572
+ emailVerified: email !== null,
1573
+ ...name === undefined ? {} : { name },
1574
+ ...picture === undefined ? {} : { picture }
1575
+ };
1576
+ }
1577
+
1578
+ // src/oauth2.ts
1579
+ function oauth2Provider(options) {
1580
+ const where = "oauth2Provider";
1581
+ const authorization = requireHttps(where, "authorizationEndpoint", options.authorizationEndpoint);
1582
+ requireHttps(where, "tokenEndpoint", options.tokenEndpoint);
1583
+ checkCredentials(where, options);
1584
+ const scopes = checkScopes(where, options.scopes);
1585
+ if (typeof options.identity !== "function") {
1586
+ throw new TypeError(`${where}: "identity" must be a function`);
1587
+ }
1588
+ const method = options.clientAuthentication ?? "post";
1589
+ if (method !== "post" && method !== "basic") {
1590
+ throw new TypeError(`${where}: "clientAuthentication" must be 'post' or 'basic'`);
1591
+ }
1592
+ const server = {
1593
+ issuer: authorization.origin,
1594
+ authorization_endpoint: options.authorizationEndpoint,
1595
+ token_endpoint: options.tokenEndpoint
1596
+ };
1597
+ const http = transport(options.fetch, options.timeout);
1598
+ return {
1599
+ authorizationUrl: (flow) => authorizationUrl({
1600
+ endpoint: options.authorizationEndpoint,
1601
+ clientId: options.clientId,
1602
+ redirectUri: options.redirectUri,
1603
+ scopes
1604
+ }, flow, false),
1605
+ async exchange(flow) {
1606
+ const { tokens } = await redeem({
1607
+ clientId: options.clientId,
1608
+ auth: clientAuth(options.clientSecret, method),
1609
+ redirectUri: options.redirectUri,
1610
+ http,
1611
+ server,
1612
+ oidc: false
1613
+ }, flow);
1614
+ const accessToken = tokens.access_token;
1615
+ if (typeof accessToken !== "string" || accessToken === "") {
1616
+ throw providerError("the token response", "refused");
1617
+ }
1618
+ return inStep("the account request", () => options.identity(accessToken, fetcher(options.fetch, options.timeout)));
1619
+ }
1620
+ };
1621
+ }
1622
+
1623
+ // src/github.ts
1624
+ function github(options) {
1625
+ return oauth2Provider({
1626
+ ...options,
1627
+ authorizationEndpoint: "https://github.com/login/oauth/authorize",
1628
+ tokenEndpoint: "https://github.com/login/oauth/access_token",
1629
+ scopes: ["read:user", "user:email"],
1630
+ identity: githubIdentity
1631
+ });
1632
+ }
1633
+ // src/discovery.ts
1634
+ import * as oauth7 from "oauth4webapi";
1635
+ function discover(issuer, http) {
1636
+ let found;
1637
+ return () => {
1638
+ if (found === undefined) {
1639
+ const url = new URL(issuer);
1640
+ const attempt = inStep("discovery", async () => oauth7.processDiscoveryResponse(url, await oauth7.discoveryRequest(url, { algorithm: "oidc", ...http })));
1641
+ found = attempt;
1642
+ attempt.catch(() => {
1643
+ if (found === attempt)
1644
+ found = undefined;
1645
+ });
1646
+ }
1647
+ return found;
1648
+ };
1649
+ }
1650
+
1651
+ // src/google.ts
1652
+ var ISSUER = "https://accounts.google.com";
1653
+ function google(options) {
1654
+ const where = "google";
1655
+ checkCredentials(where, options);
1656
+ const domain = options.hostedDomain;
1657
+ if (domain !== undefined)
1658
+ requireText(where, "hostedDomain", domain);
1659
+ return createOidcProvider({
1660
+ credentials: options,
1661
+ perRequestStepUp: false,
1662
+ scopes: ["openid", "email", "profile"],
1663
+ server: discover(ISSUER, transport(options.fetch, options.timeout)),
1664
+ ...domain === undefined ? {} : { authorizationParams: { hd: domain } },
1665
+ identity: (claims) => {
1666
+ if (domain !== undefined && text(claims, "hd") !== domain) {
1667
+ throw providerError("the ID token", "refused");
1668
+ }
1669
+ return identityOf(claims, isTrue(claims, "email_verified"), "the ID token");
1670
+ }
1671
+ });
1672
+ }
1673
+ // src/microsoft-tenant.ts
1674
+ var LOGIN = "https://login.microsoftonline.com";
1675
+ var GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1676
+ var DOMAIN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i;
1677
+ var CONSUMERS_TENANT = "9188040d-6c67-4c5b-b112-36a304b66dad";
1678
+ function isTenant(tenant) {
1679
+ return tenant === "common" || tenant === "organizations" || tenant === "consumers" || GUID.test(tenant) || DOMAIN.test(tenant);
1680
+ }
1681
+ function serverOf(tenant) {
1682
+ const base = `${LOGIN}/${tenant}/oauth2/v2.0`;
1683
+ return {
1684
+ issuer: `${LOGIN}/{tenantid}/v2.0`,
1685
+ authorization_endpoint: `${base}/authorize`,
1686
+ token_endpoint: `${base}/token`,
1687
+ token_endpoint_auth_methods_supported: ["client_secret_post"]
1688
+ };
1689
+ }
1690
+ function tenantOf(idToken) {
1691
+ const payload = idToken.split(".")[1];
1692
+ if (payload === undefined)
1693
+ return;
1694
+ try {
1695
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1696
+ return typeof claims.tid === "string" && GUID.test(claims.tid) ? claims.tid.toLowerCase() : undefined;
1697
+ } catch {
1698
+ return;
1699
+ }
1700
+ }
1701
+ function admits(tenant, tid, pinned) {
1702
+ if (tenant === "consumers")
1703
+ return tid === CONSUMERS_TENANT;
1704
+ if (tenant === "organizations")
1705
+ return tid !== CONSUMERS_TENANT;
1706
+ if (GUID.test(tenant))
1707
+ return tid === tenant.toLowerCase();
1708
+ if (pinned !== undefined)
1709
+ return tid === pinned;
1710
+ return true;
1711
+ }
1712
+ function resolveTenant(tenant, fetchWith) {
1713
+ if (tenant === "common" || tenant === "organizations" || tenant === "consumers" || GUID.test(tenant)) {
1714
+ return async () => {
1715
+ return;
1716
+ };
1717
+ }
1718
+ let found;
1719
+ return async () => {
1720
+ if (found !== undefined)
1721
+ return found;
1722
+ const answer = await fetchWith(`${LOGIN}/${tenant}/v2.0/.well-known/openid-configuration`, { redirect: "manual" });
1723
+ const body = answer.ok ? await answer.json().catch(() => null) : null;
1724
+ const guid = typeof body?.issuer === "string" ? /^https:\/\/login\.microsoftonline\.com\/([^/]+)\/v2\.0$/.exec(body.issuer)?.[1] : undefined;
1725
+ if (guid === undefined || !GUID.test(guid)) {
1726
+ throw providerError("the tenant lookup", "refused");
1727
+ }
1728
+ found = guid.toLowerCase();
1729
+ return found;
1730
+ };
1731
+ }
1732
+ async function serverForTokens(tenant, pinned, server, answer) {
1733
+ if (answer.status !== 200)
1734
+ return server;
1735
+ const body = await answer.json().catch(() => null);
1736
+ const tid = typeof body?.id_token === "string" ? tenantOf(body.id_token) : undefined;
1737
+ if (tid === undefined || !admits(tenant, tid, await pinned())) {
1738
+ throw providerError("the ID token", "refused");
1739
+ }
1740
+ return { ...server, issuer: `${LOGIN}/${tid}/v2.0` };
1741
+ }
1742
+
1743
+ // src/microsoft.ts
1744
+ function microsoft(options) {
1745
+ const where = "microsoft";
1746
+ checkCredentials(where, options);
1747
+ const tenant = options.tenant ?? "common";
1748
+ requireText(where, "tenant", tenant);
1749
+ if (!isTenant(tenant)) {
1750
+ throw new TypeError(`${where}: "tenant" must be common, organizations, consumers, a tenant id or a domain`);
1751
+ }
1752
+ const server = serverOf(tenant);
1753
+ const pinned = resolveTenant(tenant, (url, init) => inStep("the tenant lookup", () => fetcher(options.fetch, options.timeout)(url, init)));
1754
+ return createOidcProvider({
1755
+ credentials: options,
1756
+ perRequestStepUp: false,
1757
+ scopes: ["openid", "email", "profile"],
1758
+ server: async () => server,
1759
+ serverForTokens: (fixed, answer) => serverForTokens(tenant, pinned, fixed, answer),
1760
+ identity: (claims) => identityOf(claims, claims["xms_edov"] === true, "the ID token")
1761
+ });
1762
+ }
1763
+ // src/oidc.ts
1764
+ var DEFAULT_SCOPES2 = ["openid", "email", "profile"];
1765
+ function oidcProvider(options) {
1766
+ const where = "oidcProvider";
1767
+ requireHttps(where, "issuer", options.issuer);
1768
+ checkCredentials(where, options);
1769
+ checkSecurity(where, options);
1770
+ const scopes = checkScopes(where, options.scopes ?? DEFAULT_SCOPES2);
1771
+ return createOidcProvider({
1772
+ credentials: options,
1773
+ security: options,
1774
+ scopes: scopes.includes("openid") ? scopes : ["openid", ...scopes],
1775
+ perRequestStepUp: true,
1776
+ server: discover(options.issuer, transport(options.fetch, options.timeout)),
1777
+ identity: (claims) => identityOf(claims, isTrue(claims, "email_verified"), "the ID token")
1778
+ });
1779
+ }
1780
+ // src/oidc-step-up.ts
1781
+ import { SocialError as SocialError3 } from "@softistx/janus";
1782
+ function oidcStepUp(options) {
1783
+ const where = "oidcStepUp";
1784
+ requireHttps(where, "issuer", options.issuer);
1785
+ checkCredentials(where, options);
1786
+ checkSecurity(where, options);
1787
+ const { acrValues, maxAge } = options;
1788
+ checkStepUp(where, acrValues, maxAge);
1789
+ return createOidcProvider({
1790
+ credentials: options,
1791
+ security: options,
1792
+ scopes: ["openid", "email", "profile"],
1793
+ server: discover(options.issuer, transport(options.fetch, options.timeout)),
1794
+ fixedStepUp: {
1795
+ ...acrValues === undefined ? {} : { acrValues },
1796
+ ...maxAge === undefined ? {} : { maxAge }
1797
+ },
1798
+ perRequestStepUp: true,
1799
+ identity: (claims) => {
1800
+ if (!holdsStepUp(claims, acrValues, maxAge, Date.now())) {
1801
+ throw new SocialError3("SOCIAL_STEP_UP_UNMET", "the ID token: the identity provider did not prove the step-up this provider requires");
1802
+ }
1803
+ return identityOf(claims, isTrue(claims, "email_verified"), "the ID token");
1804
+ }
1805
+ });
1806
+ }
1807
+ export {
1808
+ CONNECTION_ALGORITHMS,
1809
+ checkConnection,
1810
+ createMemoryConnections,
1811
+ github,
1812
+ google,
1813
+ microsoft,
1814
+ oauth2Provider,
1815
+ oidcConnections,
1816
+ oidcProvider,
1817
+ oidcStepUp
1818
+ };
1819
+
1820
+ //# debugId=81FA006CA57599A964756E2164756E21
1821
+ //# sourceMappingURL=index.js.map