@softistx/janus 0.77.0 → 0.79.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 (124) hide show
  1. package/README.md +42 -15
  2. package/dist/auth/api-keys/authenticate-key.d.ts +3 -2
  3. package/dist/auth/api-keys/authenticate-key.d.ts.map +1 -1
  4. package/dist/auth/api-keys/count.d.ts.map +1 -1
  5. package/dist/auth/api-keys/create/after-insert.d.ts +11 -0
  6. package/dist/auth/api-keys/create/after-insert.d.ts.map +1 -0
  7. package/dist/auth/api-keys/create/checks.d.ts +17 -0
  8. package/dist/auth/api-keys/create/checks.d.ts.map +1 -1
  9. package/dist/auth/api-keys/create/index.d.ts.map +1 -1
  10. package/dist/auth/api-keys/create/service-checks.d.ts +25 -0
  11. package/dist/auth/api-keys/create/service-checks.d.ts.map +1 -0
  12. package/dist/auth/api-keys/create/service.d.ts +12 -0
  13. package/dist/auth/api-keys/create/service.d.ts.map +1 -0
  14. package/dist/auth/api-keys/expiry.d.ts.map +1 -1
  15. package/dist/auth/api-keys/flows.d.ts +6 -2
  16. package/dist/auth/api-keys/flows.d.ts.map +1 -1
  17. package/dist/auth/api-keys/owned.d.ts +12 -0
  18. package/dist/auth/api-keys/owned.d.ts.map +1 -0
  19. package/dist/auth/api-keys/read.d.ts.map +1 -1
  20. package/dist/auth/api-keys/service-flows.d.ts +13 -0
  21. package/dist/auth/api-keys/service-flows.d.ts.map +1 -0
  22. package/dist/auth/api-keys/to-api-key.d.ts.map +1 -1
  23. package/dist/auth/config/api-keys-config.d.ts +29 -2
  24. package/dist/auth/config/api-keys-config.d.ts.map +1 -1
  25. package/dist/auth/config/index.d.ts +2 -2
  26. package/dist/auth/config/index.d.ts.map +1 -1
  27. package/dist/auth/config/resolve-api-keys.d.ts.map +1 -1
  28. package/dist/auth/config/resolve-social.d.ts +1 -1
  29. package/dist/auth/config/resolve-social.d.ts.map +1 -1
  30. package/dist/auth/config/resolved-config.d.ts +11 -1
  31. package/dist/auth/config/resolved-config.d.ts.map +1 -1
  32. package/dist/auth/config/social-config.d.ts +31 -0
  33. package/dist/auth/config/social-config.d.ts.map +1 -1
  34. package/dist/auth/events.d.ts +3 -2
  35. package/dist/auth/events.d.ts.map +1 -1
  36. package/dist/auth/first-proof.d.ts +10 -2
  37. package/dist/auth/first-proof.d.ts.map +1 -1
  38. package/dist/auth/index.d.ts +3 -2
  39. package/dist/auth/index.d.ts.map +1 -1
  40. package/dist/auth/port/memory/api-keys/capabilities.d.ts.map +1 -1
  41. package/dist/auth/port/memory/api-keys/index.d.ts.map +1 -1
  42. package/dist/auth/port/types/api-keys.d.ts +25 -5
  43. package/dist/auth/port/types/api-keys.d.ts.map +1 -1
  44. package/dist/auth/sessions/authenticate.d.ts +3 -2
  45. package/dist/auth/sessions/authenticate.d.ts.map +1 -1
  46. package/dist/auth/sessions/fresh.d.ts +2 -2
  47. package/dist/auth/sessions/fresh.d.ts.map +1 -1
  48. package/dist/auth/sessions/shared-api.d.ts +3 -2
  49. package/dist/auth/sessions/shared-api.d.ts.map +1 -1
  50. package/dist/auth/shared-api.d.ts +11 -3
  51. package/dist/auth/shared-api.d.ts.map +1 -1
  52. package/dist/auth/signed-token.d.ts +41 -0
  53. package/dist/auth/signed-token.d.ts.map +1 -0
  54. package/dist/auth/social/complete-link.d.ts +9 -1
  55. package/dist/auth/social/complete-link.d.ts.map +1 -1
  56. package/dist/auth/social/complete.d.ts +1 -0
  57. package/dist/auth/social/complete.d.ts.map +1 -1
  58. package/dist/auth/social/finish.d.ts +3 -0
  59. package/dist/auth/social/finish.d.ts.map +1 -1
  60. package/dist/auth/social/link-holder.d.ts +10 -1
  61. package/dist/auth/social/link-holder.d.ts.map +1 -1
  62. package/dist/auth/social/redeem.d.ts +2 -0
  63. package/dist/auth/social/redeem.d.ts.map +1 -1
  64. package/dist/auth/social/replace-holder.d.ts +37 -0
  65. package/dist/auth/social/replace-holder.d.ts.map +1 -0
  66. package/dist/auth/social/sign-in.d.ts +4 -1
  67. package/dist/auth/social/sign-in.d.ts.map +1 -1
  68. package/dist/auth/social/sign-up.d.ts +1 -0
  69. package/dist/auth/social/sign-up.d.ts.map +1 -1
  70. package/dist/auth/types/api-keys-of.d.ts +6 -1
  71. package/dist/auth/types/api-keys-of.d.ts.map +1 -1
  72. package/dist/auth/types/api-keys.d.ts +18 -6
  73. package/dist/auth/types/api-keys.d.ts.map +1 -1
  74. package/dist/auth/types/checks.d.ts +17 -1
  75. package/dist/auth/types/checks.d.ts.map +1 -1
  76. package/dist/auth/types/index.d.ts +3 -2
  77. package/dist/auth/types/index.d.ts.map +1 -1
  78. package/dist/auth/types/service-keys.d.ts +58 -0
  79. package/dist/auth/types/service-keys.d.ts.map +1 -0
  80. package/dist/auth/types/session.d.ts +21 -2
  81. package/dist/auth/types/session.d.ts.map +1 -1
  82. package/dist/auth/types/shared-api.d.ts +15 -1
  83. package/dist/auth/types/shared-api.d.ts.map +1 -1
  84. package/dist/auth/types/social.d.ts +4 -1
  85. package/dist/auth/types/social.d.ts.map +1 -1
  86. package/dist/chunks/{index-7h34nqrm.js → index-5hcajrrx.js} +5 -5
  87. package/dist/chunks/{index-7h34nqrm.js.map → index-5hcajrrx.js.map} +4 -4
  88. package/dist/chunks/{index-n8jxmxeg.js → index-gzc472ar.js} +2 -2
  89. package/dist/chunks/{index-ftz0ne6j.js → index-r8fcessc.js} +2 -2
  90. package/dist/chunks/{index-2ttdcz7n.js → index-vx9a5cpy.js} +9 -3
  91. package/dist/chunks/{index-2ttdcz7n.js.map → index-vx9a5cpy.js.map} +4 -4
  92. package/dist/conformance/api-keys/cases/index.d.ts.map +1 -1
  93. package/dist/conformance/api-keys/cases/outage.d.ts.map +1 -1
  94. package/dist/conformance/api-keys/cases/service.d.ts +3 -0
  95. package/dist/conformance/api-keys/cases/service.d.ts.map +1 -0
  96. package/dist/conformance/index.js +407 -302
  97. package/dist/conformance/index.js.map +6 -5
  98. package/dist/errors/janus-error/codes.invitations.d.ts +6 -0
  99. package/dist/errors/janus-error/codes.invitations.d.ts.map +1 -1
  100. package/dist/errors/janus-error/index.d.ts +1 -1
  101. package/dist/errors/janus-error/index.d.ts.map +1 -1
  102. package/dist/errors/janus-error/options.d.ts +1 -1
  103. package/dist/errors/janus-error/options.d.ts.map +1 -1
  104. package/dist/errors/janus-error/refusals.d.ts +5 -0
  105. package/dist/errors/janus-error/refusals.d.ts.map +1 -1
  106. package/dist/errors/janus-error/status.d.ts.map +1 -1
  107. package/dist/index.d.ts +1 -1
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +517 -117
  110. package/dist/index.js.map +32 -25
  111. package/dist/permissions/index.js +3 -3
  112. package/docs/README.md +1 -0
  113. package/docs/guide/api-keys.md +78 -1
  114. package/docs/guide/email-flows.md +6 -1
  115. package/docs/guide/errors.md +4 -3
  116. package/docs/guide/events.md +7 -7
  117. package/docs/guide/magic-link.md +1 -1
  118. package/docs/guide/signed-tokens.md +46 -0
  119. package/docs/guide/social.md +102 -5
  120. package/docs/roadmap.md +3 -0
  121. package/docs/troubleshooting.md +33 -0
  122. package/package.json +1 -1
  123. /package/dist/chunks/{index-n8jxmxeg.js.map → index-gzc472ar.js.map} +0 -0
  124. /package/dist/chunks/{index-ftz0ne6j.js.map → index-r8fcessc.js.map} +0 -0
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  guardRelations,
4
4
  isStorable,
5
5
  UNSTORABLE
6
- } from "./chunks/index-n8jxmxeg.js";
6
+ } from "./chunks/index-gzc472ar.js";
7
7
  import {
8
8
  mintId2,
9
9
  isId2,
@@ -11,7 +11,7 @@ import {
11
11
  createMemoryApiKeys2,
12
12
  createMemoryInvitations2,
13
13
  createMemoryStores2
14
- } from "./chunks/index-7h34nqrm.js";
14
+ } from "./chunks/index-5hcajrrx.js";
15
15
  import {
16
16
  JanusError2,
17
17
  UserInvalidError2,
@@ -30,6 +30,7 @@ import {
30
30
  PermissionDepthError2,
31
31
  ApiKeyLimitError2,
32
32
  ApiKeyInvalidError2,
33
+ ApiKeyRefusedError2,
33
34
  InvitationInvalidError2,
34
35
  InvitationRefusedError2,
35
36
  InvitationLimitError2,
@@ -56,7 +57,7 @@ import {
56
57
  formatTuple2,
57
58
  parseTuple2,
58
59
  parseSubject2
59
- } from "./chunks/index-2ttdcz7n.js";
60
+ } from "./chunks/index-vx9a5cpy.js";
60
61
  import {
61
62
  mintTotpSecret,
62
63
  fromBase32,
@@ -463,13 +464,19 @@ function resolveApiKeys(config, types, where) {
463
464
  if (!Array.isArray(config.lifetimes) || config.lifetimes.length === 0) {
464
465
  throw new TypeError(`${at}.lifetimes must list at least one lifetime: there is no default and no key without an expiry`);
465
466
  }
466
- const lifetimesMs = config.lifetimes.map((value) => {
467
+ const listed = config.lifetimes;
468
+ const never = listed.includes("never");
469
+ const service = resolveService(config.service, never, at);
470
+ const lifetimesMs = listed.filter((value) => value !== "never").map((value) => {
467
471
  const ms = parseDuration(value, `${at}.lifetimes`);
468
472
  if (ms < DAY_MS) {
469
473
  throw new TypeError(`${at}.lifetimes: "${String(value)}" is under one day; a key lives at least "1d"`);
470
474
  }
471
475
  return ms;
472
476
  });
477
+ if (lifetimesMs.length === 0 && !never) {
478
+ throw new TypeError(`${at}.lifetimes must list at least one lifetime`);
479
+ }
473
480
  const maxActive = config.maxActive ?? 10;
474
481
  if (!Number.isInteger(maxActive) || maxActive < 1 || maxActive > 100) {
475
482
  throw new TypeError(`${at}.maxActive must be an integer from 1 to 100`);
@@ -481,6 +488,8 @@ function resolveApiKeys(config, types, where) {
481
488
  return {
482
489
  prefix: config.prefix,
483
490
  lifetimesMs,
491
+ never,
492
+ service,
484
493
  maxActive,
485
494
  freshWithinMs: parseDuration(config.freshWithin ?? "10m", `${at}.freshWithin`),
486
495
  lastUsedEveryMs: parseDuration(config.lastUsedEvery ?? "1h", `${at}.lastUsedEvery`),
@@ -501,6 +510,25 @@ function allowedTypes(listed, types, at) {
501
510
  }
502
511
  return new Set(listed);
503
512
  }
513
+ function resolveService(service, never, at) {
514
+ if (service === undefined) {
515
+ if (never) {
516
+ throw new TypeError(`${at}.lifetimes lists "never", which only service keys take: add ${at}.service`);
517
+ }
518
+ return null;
519
+ }
520
+ if (typeof service !== "object" || service === null) {
521
+ throw new TypeError(`${at}.service must be an object`);
522
+ }
523
+ if (typeof service.authorize !== "function") {
524
+ throw new TypeError(`${at}.service.authorize must be a function: it decides who may make a service key`);
525
+ }
526
+ const maxActive = service.maxActive ?? 10;
527
+ if (!Number.isInteger(maxActive) || maxActive < 1 || maxActive > 100) {
528
+ throw new TypeError(`${at}.service.maxActive must be an integer from 1 to 100`);
529
+ }
530
+ return { authorize: service.authorize, maxActive };
531
+ }
504
532
 
505
533
  // src/auth/config/resolve-cookie.ts
506
534
  var COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
@@ -954,10 +982,15 @@ function resolveSocial(social, type, at) {
954
982
  if (signUp !== false && type.login !== null && type.login !== type.email) {
955
983
  throw new TypeError(`${at}: social.signUp needs a type whose login is its e-mail — password.login is "${type.login}", not "${type.email}"`);
956
984
  }
985
+ const unverifiedHolder = social.unverifiedHolder ?? "refuse";
986
+ if (unverifiedHolder !== "refuse" && unverifiedHolder !== "replace" && typeof unverifiedHolder !== "function") {
987
+ throw new TypeError(`${at}: social.unverifiedHolder must be 'refuse', 'replace' or a function that takes the holder and the profile and answers one of them`);
988
+ }
957
989
  return {
958
990
  providers,
959
991
  resolveProvider,
960
992
  signUp,
993
+ unverifiedHolder,
961
994
  freshWithinMs: parseDuration(social.freshWithin ?? "10m", `${at}: social.freshWithin`)
962
995
  };
963
996
  }
@@ -2139,8 +2172,10 @@ async function sweepWaitingFactorPasskeys(context, type, user, where) {
2139
2172
  }
2140
2173
 
2141
2174
  // src/auth/first-proof.ts
2142
- async function proveFirstEmail(context, type, user, where) {
2143
- await endWhatTheSquatterOpened(context, user);
2175
+ async function proveFirstEmail(context, type, user, where, options = {}) {
2176
+ if (options.revokeFirst !== false) {
2177
+ await endWhatTheSquatterOpened(context, user);
2178
+ }
2144
2179
  let dropped = false;
2145
2180
  let disabled = false;
2146
2181
  let formerAvatarId = null;
@@ -2155,6 +2190,7 @@ async function proveFirstEmail(context, type, user, where) {
2155
2190
  ...formerAvatarId === null ? {} : { avatar: null }
2156
2191
  };
2157
2192
  });
2193
+ options.onWritten?.();
2158
2194
  try {
2159
2195
  await endWhatTheSquatterOpened(context, proved);
2160
2196
  } finally {
@@ -2182,6 +2218,12 @@ async function proveFirstEmail(context, type, user, where) {
2182
2218
  }
2183
2219
  return proved;
2184
2220
  }
2221
+ var LEFT_WAITING = [
2222
+ "changeEmail",
2223
+ "socialFlow",
2224
+ "passkeyRegistration",
2225
+ "stepUp"
2226
+ ];
2185
2227
  async function endWhatTheSquatterOpened(context, user) {
2186
2228
  const userId = user.id;
2187
2229
  await endEach([
@@ -2191,7 +2233,8 @@ async function endWhatTheSquatterOpened(context, user) {
2191
2233
  const count = await context.apiKeys?.revokeUserApiKeys(userId, at);
2192
2234
  await keysRevoked(context, user, at, count ?? 0);
2193
2235
  },
2194
- () => endWhatThePasswordOpened(context, userId)
2236
+ () => endWhatThePasswordOpened(context, userId),
2237
+ ...LEFT_WAITING.map((kind) => () => context.store.tokens.spendUserTokens(userId, kind, context.clock.now()))
2195
2238
  ]);
2196
2239
  }
2197
2240
 
@@ -2364,6 +2407,9 @@ function anyTypeVerifyEmail(context) {
2364
2407
  // src/auth/sessions/fresh.ts
2365
2408
  function assertFresh(subject, maxAge, clock = systemClock) {
2366
2409
  if ("via" in subject) {
2410
+ if (subject.via === "serviceKey") {
2411
+ throw new StepUpRequiredError2("assertFresh: an API key is never fresh — the caller needs a signed-in session", { reason: "apiKey" });
2412
+ }
2367
2413
  if (subject.via === "apiKey") {
2368
2414
  throw new StepUpRequiredError2("assertFresh: an API key is never fresh — the caller needs a signed-in session", { userId: subject.apiKey.userId, reason: "apiKey" });
2369
2415
  }
@@ -2698,12 +2744,20 @@ function apiKeyHint(prefix, id) {
2698
2744
 
2699
2745
  // src/auth/api-keys/to-api-key.ts
2700
2746
  function toApiKey(prefix, record) {
2701
- const { secretHash: _hash, scopes, bound, expiryNotifiedAt, ...key } = record;
2747
+ const {
2748
+ secretHash: _hash,
2749
+ scopes,
2750
+ bound,
2751
+ details,
2752
+ expiryNotifiedAt,
2753
+ ...key
2754
+ } = record;
2702
2755
  return {
2703
2756
  ...key,
2704
2757
  hint: apiKeyHint(prefix, record.id),
2705
2758
  scopes: scopes ?? null,
2706
2759
  bound: bound ?? null,
2760
+ details: details === undefined ? null : structuredClone(details),
2707
2761
  expiryNotifiedAt: expiryNotifiedAt ?? null
2708
2762
  };
2709
2763
  }
@@ -2728,17 +2782,19 @@ async function authenticateKey(context, keys, token, options) {
2728
2782
  return null;
2729
2783
  }
2730
2784
  const now = context.clock.now();
2731
- if (record.revokedAt !== null || record.expiresAt.getTime() <= now.getTime()) {
2785
+ if (record.revokedAt !== null || record.expiresAt !== null && record.expiresAt.getTime() <= now.getTime()) {
2732
2786
  return null;
2733
2787
  }
2788
+ if (record.userId === null) {
2789
+ if (options?.service !== true || options.type !== undefined)
2790
+ return null;
2791
+ return serviceKeyPrincipal(settings, keys, record, token, now);
2792
+ }
2734
2793
  const user = await context.store.users.findUser(record.userId);
2735
2794
  if (user === null || !user.active || !settings.types.has(user.type) || options?.type !== undefined && user.type !== options.type) {
2736
2795
  return null;
2737
2796
  }
2738
- const staleBefore = new Date(now.getTime() - settings.lastUsedEveryMs);
2739
- const stale = record.lastUsedAt === null || record.lastUsedAt.getTime() < staleBefore.getTime();
2740
- const touched = stale && await keys.touchApiKey(record.id, now, staleBefore);
2741
- const apiKey = toApiKey(settings.prefix, touched ? { ...record, lastUsedAt: now } : record);
2797
+ const apiKey = await touch(settings, keys, record, now);
2742
2798
  return {
2743
2799
  via: "apiKey",
2744
2800
  user: toUser(user),
@@ -2750,6 +2806,27 @@ async function authenticateKey(context, keys, token, options) {
2750
2806
  renewed: false
2751
2807
  };
2752
2808
  }
2809
+ async function touch(settings, keys, record, now) {
2810
+ const staleBefore = new Date(now.getTime() - settings.lastUsedEveryMs);
2811
+ const stale = record.lastUsedAt === null || record.lastUsedAt.getTime() < staleBefore.getTime();
2812
+ const touched = stale && await keys.touchApiKey(record.id, now, staleBefore);
2813
+ return toApiKey(settings.prefix, touched ? { ...record, lastUsedAt: now } : record);
2814
+ }
2815
+ async function serviceKeyPrincipal(settings, keys, record, token, now) {
2816
+ if (record.bound === undefined || record.scopes === undefined)
2817
+ return null;
2818
+ const apiKey = await touch(settings, keys, record, now);
2819
+ return {
2820
+ via: "serviceKey",
2821
+ apiKey,
2822
+ scopes: record.scopes,
2823
+ bound: { type: record.bound.type, id: record.bound.id },
2824
+ user: null,
2825
+ session: null,
2826
+ token,
2827
+ renewed: false
2828
+ };
2829
+ }
2753
2830
 
2754
2831
  // src/auth/sessions/standing.ts
2755
2832
  function absoluteEnd(type, session) {
@@ -3447,6 +3524,20 @@ function boundApi(context, prefix, keys) {
3447
3524
  };
3448
3525
  }
3449
3526
 
3527
+ // src/auth/api-keys/create/after-insert.ts
3528
+ async function settleInsert(keys, clock, id, checks, noun) {
3529
+ const [after] = await Promise.allSettled([checks]);
3530
+ if (after.status === "fulfilled")
3531
+ return;
3532
+ const [revoked] = await Promise.allSettled([
3533
+ keys.revokeApiKey(id, clock.now())
3534
+ ]);
3535
+ if (revoked.status === "rejected") {
3536
+ process.emitWarning(`janus: ${noun} could not be revoked after its creation failed: ${revoked.reason instanceof Error ? revoked.reason.name : typeof revoked.reason}`, { code: "JANUS_API_KEY_REVOKE_FAILED" });
3537
+ }
3538
+ throw after.reason;
3539
+ }
3540
+
3450
3541
  // src/auth/api-keys/count.ts
3451
3542
  async function countStanding(keys, userId, now, stopAt) {
3452
3543
  let standing = 0;
@@ -3457,7 +3548,7 @@ async function countStanding(keys, userId, now, stopAt) {
3457
3548
  after
3458
3549
  });
3459
3550
  for (const key of page.items) {
3460
- if (key.revokedAt === null && key.expiresAt.getTime() > now.getTime()) {
3551
+ if (key.revokedAt === null && (key.expiresAt === null || key.expiresAt.getTime() > now.getTime())) {
3461
3552
  standing += 1;
3462
3553
  }
3463
3554
  }
@@ -3470,47 +3561,60 @@ async function countStanding(keys, userId, now, stopAt) {
3470
3561
  var NAME_MAX2 = 100;
3471
3562
  var WHERE = "apiKeys.create";
3472
3563
  async function checkBeforeInsert(context, settings, keys, current, input) {
3473
- const { store, clock } = context;
3564
+ const { clock } = context;
3474
3565
  const userId = refOf(current);
3475
- if (current.via === "apiKey") {
3476
- throw new StepUpRequiredError2(`${WHERE}: an API key cannot create a key — it is never fresh; sign in or confirm a step-up`, { userId, reason: "apiKey" });
3477
- }
3478
- assertFresh({ authenticatedAt: current.session.authenticatedAt, userId }, settings.freshWithinMs, clock);
3566
+ assertFreshCreator(context, settings, current);
3479
3567
  const name = checkName2(input?.name);
3480
3568
  const lifetimeMs = checkLifetime(settings, input?.lifetime);
3481
3569
  const scopes = checkScopes(input?.scopes, WHERE);
3482
3570
  const bound = checkBound(input?.bound, WHERE);
3483
3571
  if (scopes !== undefined || bound !== undefined)
3484
3572
  boundMethods(keys, WHERE);
3573
+ const user = await loadCreator(context, settings, current);
3574
+ if (await countStanding(keys, user.id, clock.now(), settings.maxActive) >= settings.maxActive) {
3575
+ throw limitReached2(settings, userId);
3576
+ }
3577
+ return {
3578
+ user,
3579
+ name,
3580
+ lifetimeMs,
3581
+ extra: {
3582
+ ...scopes === undefined ? {} : { scopes },
3583
+ ...bound === undefined ? {} : { bound }
3584
+ }
3585
+ };
3586
+ }
3587
+ function assertFreshCreator(context, settings, current, where = WHERE) {
3588
+ const userId = refOf(current);
3589
+ if (current.via !== "session") {
3590
+ throw new StepUpRequiredError2(`${where}: an API key cannot create a key — it is never fresh; sign in or confirm a step-up`, { userId, reason: "apiKey" });
3591
+ }
3592
+ assertFresh({
3593
+ authenticatedAt: current.session.authenticatedAt,
3594
+ userId
3595
+ }, settings.freshWithinMs, context.clock);
3596
+ }
3597
+ async function loadCreator(context, settings, current, where = WHERE) {
3598
+ const { store } = context;
3599
+ const userId = refOf(current);
3485
3600
  const user = await store.users.findUser(userId);
3486
3601
  if (user === null || !settings.types.has(user.type)) {
3487
- throw new NotFoundError2(`${WHERE}: no such user can hold API keys`, {
3602
+ throw new NotFoundError2(`${where}: no such user can hold API keys`, {
3488
3603
  userId
3489
3604
  });
3490
3605
  }
3491
3606
  if (!user.active) {
3492
- throw new UserInactiveError2(`${WHERE}: the user is inactive`, { userId });
3607
+ throw new UserInactiveError2(`${where}: the user is inactive`, { userId });
3493
3608
  }
3494
3609
  const type = context.config.types.get(user.type);
3495
3610
  if (user.emailVerifiedAt === null && type !== undefined && emailOf(type, user.fields) !== null) {
3496
- throw new EmailUnverifiedError2(`${WHERE}: the e-mail is not verified`, {
3611
+ throw new EmailUnverifiedError2(`${where}: the e-mail is not verified`, {
3497
3612
  userId,
3498
3613
  userType: user.type
3499
3614
  });
3500
3615
  }
3501
3616
  checkPasswordHeld(current, user);
3502
- if (await countStanding(keys, user.id, clock.now(), settings.maxActive) >= settings.maxActive) {
3503
- throw limitReached2(settings, userId);
3504
- }
3505
- return {
3506
- user,
3507
- name,
3508
- lifetimeMs,
3509
- extra: {
3510
- ...scopes === undefined ? {} : { scopes },
3511
- ...bound === undefined ? {} : { bound }
3512
- }
3513
- };
3617
+ return user;
3514
3618
  }
3515
3619
  function limitReached2(settings, userId) {
3516
3620
  return new ApiKeyLimitError2(`${WHERE}: the user already holds ${settings.maxActive} API keys — revoke one first`, { userId, maxActive: settings.maxActive });
@@ -3522,25 +3626,29 @@ function checkPasswordHeld(current, user) {
3522
3626
  }
3523
3627
  }
3524
3628
  async function checkAfterInsert(context, settings, keys, current, userId) {
3525
- const { store, clock } = context;
3629
+ const { clock } = context;
3526
3630
  const standing = await countStanding(keys, userId, clock.now(), settings.maxActive + 1);
3527
3631
  if (standing > settings.maxActive)
3528
3632
  throw limitReached2(settings, userId);
3633
+ await checkCreatorStands(context, current, userId);
3634
+ }
3635
+ async function checkCreatorStands(context, current, userId, where = WHERE) {
3636
+ const { store, clock } = context;
3529
3637
  const user = await store.users.findUser(userId);
3530
3638
  if (user === null) {
3531
- throw new NotFoundError2(`${WHERE}: no such user can hold API keys`, {
3639
+ throw new NotFoundError2(`${where}: no such user can hold API keys`, {
3532
3640
  userId
3533
3641
  });
3534
3642
  }
3535
3643
  if (!user.active) {
3536
- throw new UserInactiveError2(`${WHERE}: the user is inactive`, { userId });
3644
+ throw new UserInactiveError2(`${where}: the user is inactive`, { userId });
3537
3645
  }
3538
3646
  checkPasswordHeld(current, user);
3539
3647
  if (current.via === "apiKey")
3540
3648
  return;
3541
3649
  const session = await store.sessions.findSessionByTokenHash(hashSecret(current.token));
3542
3650
  if (session === null || session.revokedAt !== null || session.expiresAt.getTime() <= clock.now().getTime() || pastAbsolute(context.config.types.get(user.type), session, clock.now().getTime())) {
3543
- throw new StepUpRequiredError2(`${WHERE}: the session ended while the key was made — sign in again`, { userId });
3651
+ throw new StepUpRequiredError2(`${where}: the session ended while the key was made — sign in again`, { userId });
3544
3652
  }
3545
3653
  }
3546
3654
  function refOf(current) {
@@ -3582,18 +3690,7 @@ async function createApiKey(context, settings, keys, current, input) {
3582
3690
  ...extra
3583
3691
  };
3584
3692
  await keys.insertApiKey(record);
3585
- const [after] = await Promise.allSettled([
3586
- checkAfterInsert(context, settings, keys, current, user.id)
3587
- ]);
3588
- if (after.status === "rejected") {
3589
- const [revoked] = await Promise.allSettled([
3590
- keys.revokeApiKey(id, clock.now())
3591
- ]);
3592
- if (revoked.status === "rejected") {
3593
- process.emitWarning(`janus: an API key could not be revoked after its creation failed: ${revoked.reason instanceof Error ? revoked.reason.name : typeof revoked.reason}`, { code: "JANUS_API_KEY_REVOKE_FAILED" });
3594
- }
3595
- throw after.reason;
3596
- }
3693
+ await settleInsert(keys, clock, id, checkAfterInsert(context, settings, keys, current, user.id), "an API key");
3597
3694
  await keyCreated(context, user, createdAt);
3598
3695
  return {
3599
3696
  apiKey: toApiKey(settings.prefix, record),
@@ -3621,7 +3718,7 @@ function expiryApi(context, prefix, keys) {
3621
3718
  after
3622
3719
  });
3623
3720
  return {
3624
- items: found.items.map((record) => toApiKey(prefix, record)),
3721
+ items: found.items.filter((record) => record.userId !== null).map((record) => toApiKey(prefix, record)),
3625
3722
  nextCursor: found.nextCursor
3626
3723
  };
3627
3724
  },
@@ -3712,6 +3809,179 @@ function readApi(prefix, keys) {
3712
3809
  };
3713
3810
  }
3714
3811
 
3812
+ // src/auth/api-keys/owned.ts
3813
+ var READ2 = 100;
3814
+ async function listOwnedRecords(keys, owner, { first, after }, where) {
3815
+ const store = boundMethods(keys, where);
3816
+ const kept = [];
3817
+ let cursor = after;
3818
+ do {
3819
+ const found = await store.list({ type: owner.type, id: owner.id }, { first: READ2, after: cursor });
3820
+ for (const record of found.items) {
3821
+ if (record.userId === null)
3822
+ kept.push(record);
3823
+ }
3824
+ cursor = found.nextCursor;
3825
+ } while (cursor !== null && kept.length <= first);
3826
+ const items = kept.slice(0, first);
3827
+ const last = items.at(-1);
3828
+ return {
3829
+ items,
3830
+ nextCursor: kept.length > first && last !== undefined ? last.id : null
3831
+ };
3832
+ }
3833
+ async function countOwnedStanding(keys, owner, now, stopAt, where) {
3834
+ let standing = 0;
3835
+ let after = null;
3836
+ do {
3837
+ const page = await listOwnedRecords(keys, owner, { first: MAX_PAGE_SIZE2, after }, where);
3838
+ for (const key of page.items) {
3839
+ if (key.revokedAt === null && (key.expiresAt === null || key.expiresAt.getTime() > now.getTime())) {
3840
+ standing += 1;
3841
+ }
3842
+ }
3843
+ after = page.nextCursor;
3844
+ } while (after !== null && standing < stopAt);
3845
+ return standing;
3846
+ }
3847
+
3848
+ // src/auth/api-keys/create/service-checks.ts
3849
+ var WHERE2 = "apiKeys.createService";
3850
+ var DETAILS_MAX = 4000;
3851
+ function limitReached3(maxActive) {
3852
+ return new ApiKeyLimitError2(`${WHERE2}: the owner already holds ${maxActive} service keys — revoke one first`, { maxActive });
3853
+ }
3854
+ function checkOwner(owner) {
3855
+ if (!isBound(owner)) {
3856
+ throw new ApiKeyInvalidError2(`${WHERE2}: owner must be { type, id }, a type of 1 to 64 characters and an id of 1 to 200`, { field: "owner" });
3857
+ }
3858
+ return { type: owner.type, id: owner.id };
3859
+ }
3860
+ function checkServiceLifetime(settings, lifetime) {
3861
+ if (lifetime === "never") {
3862
+ if (settings.never)
3863
+ return null;
3864
+ throw new ApiKeyInvalidError2(`${WHERE2}: lifetime "never" is not enabled: list it in apiKeys.lifetimes`, { field: "lifetime" });
3865
+ }
3866
+ return checkLifetime(settings, lifetime);
3867
+ }
3868
+ function checkDetails(details) {
3869
+ if (details === undefined)
3870
+ return;
3871
+ const refuse = () => new ApiKeyInvalidError2(`${WHERE2}: details must be a plain JSON object of at most ${DETAILS_MAX} characters`, { field: "details" });
3872
+ if (typeof details !== "object" || details === null || Array.isArray(details) || Object.getPrototypeOf(details) !== Object.prototype) {
3873
+ throw refuse();
3874
+ }
3875
+ let json;
3876
+ try {
3877
+ json = JSON.stringify(details);
3878
+ } catch {
3879
+ throw refuse();
3880
+ }
3881
+ if (json === undefined || json.length > DETAILS_MAX || !isStorable(json)) {
3882
+ throw refuse();
3883
+ }
3884
+ return JSON.parse(json);
3885
+ }
3886
+ function checkServiceInput(settings, input) {
3887
+ const name = checkName2(input?.name);
3888
+ const owner = checkOwner(input?.owner);
3889
+ const scopes = checkScopes(input?.scopes, WHERE2);
3890
+ if (scopes === undefined) {
3891
+ throw new ApiKeyInvalidError2(`${WHERE2}: a service key needs scopes`, {
3892
+ field: "scopes"
3893
+ });
3894
+ }
3895
+ const lifetimeMs = checkServiceLifetime(settings, input?.lifetime);
3896
+ const details = checkDetails(input?.details);
3897
+ return { name, owner, scopes, lifetimeMs, details };
3898
+ }
3899
+
3900
+ // src/auth/api-keys/create/service.ts
3901
+ async function createServiceKey(context, settings, keys, current, input) {
3902
+ const service = settings.service;
3903
+ if (service === null) {
3904
+ throw new TypeError(`${WHERE2} needs janus({ apiKeys: { service } })`);
3905
+ }
3906
+ const { clock } = context;
3907
+ assertFreshCreator(context, settings, current, WHERE2);
3908
+ const { name, owner, scopes, lifetimeMs, details } = checkServiceInput(settings, input);
3909
+ boundMethods(keys, WHERE2);
3910
+ const user = await loadCreator(context, settings, current, WHERE2);
3911
+ if (!await service.authorize({
3912
+ user: { id: user.id, type: user.type },
3913
+ owner,
3914
+ scopes
3915
+ })) {
3916
+ throw new ApiKeyRefusedError2(`${WHERE2}: the application refused this service key`, { userId: user.id });
3917
+ }
3918
+ if (await countOwnedStanding(keys, owner, clock.now(), service.maxActive, WHERE2) >= service.maxActive) {
3919
+ throw limitReached3(service.maxActive);
3920
+ }
3921
+ const secret = mintSecret();
3922
+ const id = mintId2();
3923
+ const createdAt = clock.now();
3924
+ const record = {
3925
+ id,
3926
+ userId: null,
3927
+ name,
3928
+ secretHash: hashSecret(secret),
3929
+ createdAt,
3930
+ expiresAt: lifetimeMs === null ? null : new Date(createdAt.getTime() + lifetimeMs),
3931
+ lastUsedAt: null,
3932
+ revokedAt: null,
3933
+ scopes,
3934
+ bound: owner,
3935
+ ...details === undefined ? {} : { details }
3936
+ };
3937
+ await keys.insertApiKey(record);
3938
+ await settleInsert(keys, clock, id, (async () => {
3939
+ const standing = await countOwnedStanding(keys, owner, clock.now(), service.maxActive + 1, WHERE2);
3940
+ if (standing > service.maxActive)
3941
+ throw limitReached3(service.maxActive);
3942
+ await checkCreatorStands(context, current, user.id, WHERE2);
3943
+ })(), "a service key");
3944
+ return {
3945
+ apiKey: toApiKey(settings.prefix, record),
3946
+ token: apiKeyToken(settings.prefix, id, secret)
3947
+ };
3948
+ }
3949
+
3950
+ // src/auth/api-keys/service-flows.ts
3951
+ function serviceApi(context, settings, keys) {
3952
+ const { clock } = context;
3953
+ return {
3954
+ async createService(current, input) {
3955
+ return createServiceKey(context, settings, keys, current, input);
3956
+ },
3957
+ async listOwned(owner, page) {
3958
+ const after = page?.after ?? null;
3959
+ if (after !== null && !isId2(after)) {
3960
+ throw invalidCursor2("apiKeys.listOwned", after);
3961
+ }
3962
+ const first = pageLimit2(page?.limit, "apiKeys.listOwned");
3963
+ if (!isBound(owner))
3964
+ return { items: [], nextCursor: null };
3965
+ const found = await listOwnedRecords(keys, owner, { first, after }, "apiKeys.listOwned");
3966
+ return {
3967
+ items: found.items.map((record) => toApiKey(settings.prefix, record)),
3968
+ nextCursor: found.nextCursor
3969
+ };
3970
+ },
3971
+ async revokeOwned(owner, id) {
3972
+ const missing = () => new NotFoundError2("apiKeys.revokeOwned: no such service key");
3973
+ if (typeof id !== "string" || !isId2(id) || !isBound(owner))
3974
+ throw missing();
3975
+ const record = await keys.findApiKey(id);
3976
+ if (record === null || record.userId !== null || record.bound?.type !== owner.type || record.bound.id !== owner.id) {
3977
+ throw missing();
3978
+ }
3979
+ if (!await keys.revokeApiKey(id, clock.now()))
3980
+ throw missing();
3981
+ }
3982
+ };
3983
+ }
3984
+
3715
3985
  // src/auth/api-keys/flows.ts
3716
3986
  function apiKeysApi(context, keys) {
3717
3987
  const settings = context.config.apiKeys;
@@ -3719,7 +3989,7 @@ function apiKeysApi(context, keys) {
3719
3989
  throw new TypeError("janus: apiKeysApi needs janus({ apiKeys })");
3720
3990
  }
3721
3991
  const { clock } = context;
3722
- return {
3992
+ const api = {
3723
3993
  async create(current, input) {
3724
3994
  return createApiKey(context, settings, keys, current, input);
3725
3995
  },
@@ -3733,7 +4003,7 @@ function apiKeysApi(context, keys) {
3733
4003
  if (typeof options === "object" && options !== null && "owner" in options && record.userId !== refId(options.owner)) {
3734
4004
  throw missing();
3735
4005
  }
3736
- const owner = await ownerForEvent(context, record.userId);
4006
+ const owner = record.userId === null ? null : await ownerForEvent(context, record.userId);
3737
4007
  const at = clock.now();
3738
4008
  if (!await keys.revokeApiKey(id, at))
3739
4009
  throw missing();
@@ -3753,6 +4023,7 @@ function apiKeysApi(context, keys) {
3753
4023
  ...boundApi(context, settings.prefix, keys),
3754
4024
  ...expiryApi(context, settings.prefix, keys)
3755
4025
  };
4026
+ return settings.service === null ? api : { ...api, ...serviceApi(context, settings, keys) };
3756
4027
  }
3757
4028
  // src/auth/email-flows/reset-password.ts
3758
4029
  function resetPasswordFlows(context, type, at) {
@@ -5379,21 +5650,21 @@ function toPreview(record, type, needsPassword) {
5379
5650
  }
5380
5651
 
5381
5652
  // src/auth/invitations/accept.ts
5382
- var WHERE2 = "invitations.accept";
5653
+ var WHERE3 = "invitations.accept";
5383
5654
  async function acceptInvitation(context, settings, invitations, invited, input) {
5384
5655
  const { clock } = context;
5385
5656
  const code = input?.code;
5386
5657
  if (!isCode(code))
5387
- throw invalidCode(WHERE2);
5658
+ throw invalidCode(WHERE3);
5388
5659
  const options = input.device === undefined ? {} : { device: input.device };
5389
- deviceHint(context, options, WHERE2);
5660
+ deviceHint(context, options, WHERE3);
5390
5661
  const found = await invitations.findInvitationByCodeHash(hashSecret(code));
5391
5662
  const name = found === null ? null : configuredType(settings, found);
5392
5663
  if (name === null)
5393
- throw invalidCode(WHERE2);
5664
+ throw invalidCode(WHERE3);
5394
5665
  const { api: typed, type } = invited(name);
5395
5666
  await beforeAccept(clock, settings, typed, found);
5396
- const claimed = await claim(invitations, clock, found, WHERE2);
5667
+ const claimed = await claim(invitations, clock, found, WHERE3);
5397
5668
  const prepared = await releasedOnFailure(invitations, clock, claimed, () => prepare(context, settings, invitations, typed, type, claimed, input.password));
5398
5669
  const invitation = toInvitation(prepared.record, settings.types[0]);
5399
5670
  await emitInvitation(settings.events, "invitation.accepted", prepared.record, prepared.record.updatedAt);
@@ -5406,21 +5677,21 @@ async function acceptInvitation(context, settings, invitations, invited, input)
5406
5677
  async function beforeAccept(clock, settings, typed, found) {
5407
5678
  if (settings.beforeAccept === null)
5408
5679
  return;
5409
- const pending = pendingRecord(clock, found, WHERE2);
5680
+ const pending = pendingRecord(clock, found, WHERE3);
5410
5681
  const existing = await typed.findByEmail(pending.email);
5411
5682
  if (existing !== null && !existing.active)
5412
- throw invalidCode(WHERE2);
5683
+ throw invalidCode(WHERE3);
5413
5684
  const proceed = await settings.beforeAccept({
5414
5685
  invitation: toInvitation(pending, settings.types[0]),
5415
5686
  user: existing === null ? null : { id: existing.id, type: existing.type }
5416
5687
  });
5417
5688
  if (!proceed) {
5418
- throw new InvitationRefusedError2(`${WHERE2}: the application refused this acceptance; the invitation is still pending`);
5689
+ throw new InvitationRefusedError2(`${WHERE3}: the application refused this acceptance; the invitation is still pending`);
5419
5690
  }
5420
5691
  }
5421
5692
  async function prepare(context, settings, invitations, typed, type, claimed, password) {
5422
- const { user, proved } = await inviteeOf(typed, type, toInvitation(claimed, settings.types[0]), settings.create, password, WHERE2);
5423
- const record = await recordAcceptor(invitations, context.clock, claimed, user.id, WHERE2);
5693
+ const { user, proved } = await inviteeOf(typed, type, toInvitation(claimed, settings.types[0]), settings.create, password, WHERE3);
5694
+ const record = await recordAcceptor(invitations, context.clock, claimed, user.id, WHERE3);
5424
5695
  await settings.onAccepted({
5425
5696
  invitation: toInvitation(record, settings.types[0]),
5426
5697
  user: { id: user.id, type: user.type }
@@ -5648,17 +5919,17 @@ function checkHistoryRecord(context, settings, input) {
5648
5919
  }
5649
5920
 
5650
5921
  // src/auth/invitations/history.ts
5651
- var WHERE3 = "invitations.importHistory";
5922
+ var WHERE4 = "invitations.importHistory";
5652
5923
  var IMPORT_MAX = 1000;
5653
5924
  function dryRunOf(options) {
5654
5925
  if (options === undefined)
5655
5926
  return false;
5656
5927
  if (typeof options !== "object" || options === null || Array.isArray(options)) {
5657
- throw new TypeError(`${WHERE3}: options must be an object`);
5928
+ throw new TypeError(`${WHERE4}: options must be an object`);
5658
5929
  }
5659
5930
  const { dryRun } = options;
5660
5931
  if (dryRun !== undefined && typeof dryRun !== "boolean") {
5661
- throw new TypeError(`${WHERE3}: options.dryRun must be a boolean`);
5932
+ throw new TypeError(`${WHERE4}: options.dryRun must be a boolean`);
5662
5933
  }
5663
5934
  return dryRun === true;
5664
5935
  }
@@ -5673,10 +5944,10 @@ function refused(key, id, reason, field) {
5673
5944
  }
5674
5945
  async function importHistory(context, settings, invitations, records, options) {
5675
5946
  if (!Array.isArray(records)) {
5676
- throw new TypeError(`${WHERE3}: records must be an array`);
5947
+ throw new TypeError(`${WHERE4}: records must be an array`);
5677
5948
  }
5678
5949
  if (records.length > IMPORT_MAX) {
5679
- throw new TypeError(`${WHERE3}: at most ${IMPORT_MAX} records per call`);
5950
+ throw new TypeError(`${WHERE4}: at most ${IMPORT_MAX} records per call`);
5680
5951
  }
5681
5952
  const dryRun = dryRunOf(options);
5682
5953
  const items = [];
@@ -5726,23 +5997,23 @@ async function importHistory(context, settings, invitations, records, options) {
5726
5997
  }
5727
5998
 
5728
5999
  // src/auth/invitations/limit.ts
5729
- function limitReached3(where, settings) {
6000
+ function limitReached4(where, settings) {
5730
6001
  return new InvitationLimitError2(`${where}: the scope already holds ${settings.maxPending} pending invitations — revoke one first`, settings.maxPending === null ? {} : { maxActive: settings.maxPending });
5731
6002
  }
5732
6003
 
5733
6004
  // src/auth/invitations/issue.ts
5734
- var WHERE4 = "invitations.issue";
6005
+ var WHERE5 = "invitations.issue";
5735
6006
  var ATTEMPTS2 = 3;
5736
6007
  async function issueInvitation(context, settings, invitations, input) {
5737
6008
  const { clock } = context;
5738
- const scope = scopeOf(WHERE4, input?.scope);
5739
- const email = emailOf2(WHERE4, input?.email);
5740
- const name = nameOf(WHERE4, input?.name);
5741
- const role = roleOf(WHERE4, input?.role);
5742
- const locale = localeOf(WHERE4, input?.locale);
5743
- const invitedBy = inviterOf(WHERE4, input?.invitedBy);
5744
- const ref = refOf2(WHERE4, input?.ref);
5745
- const type = issuedType(WHERE4, settings, input?.type);
6009
+ const scope = scopeOf(WHERE5, input?.scope);
6010
+ const email = emailOf2(WHERE5, input?.email);
6011
+ const name = nameOf(WHERE5, input?.name);
6012
+ const role = roleOf(WHERE5, input?.role);
6013
+ const locale = localeOf(WHERE5, input?.locale);
6014
+ const invitedBy = inviterOf(WHERE5, input?.invitedBy);
6015
+ const ref = refOf2(WHERE5, input?.ref);
6016
+ const type = issuedType(WHERE5, settings, input?.type);
5746
6017
  await checkRoom(context, settings, invitations, scope, email);
5747
6018
  const preexisting = await findPending(invitations, scope, email);
5748
6019
  const code = mintSecret();
@@ -5773,7 +6044,7 @@ async function issueInvitation(context, settings, invitations, input) {
5773
6044
  const pending = await invitations.countPendingInvitations(scope, clock.now());
5774
6045
  if (pending > settings.maxPending) {
5775
6046
  await withdraw(context, settings, invitations, record);
5776
- throw limitReached3(WHERE4, settings);
6047
+ throw limitReached4(WHERE5, settings);
5777
6048
  }
5778
6049
  }
5779
6050
  await emitInvitation(settings.events, "invitation.issued", record, createdAt);
@@ -5784,7 +6055,7 @@ async function checkTypeKept(settings, invitations, record) {
5784
6055
  return;
5785
6056
  const stored = await invitations.findInvitation(record.id);
5786
6057
  if (stored === null || stored.type !== record.type) {
5787
- throw new TypeError(`${WHERE4}: the invitation store did not keep the invitation's type: with several invitation types, the store must keep \`type\` — update the adapter`);
6058
+ throw new TypeError(`${WHERE5}: the invitation store did not keep the invitation's type: with several invitation types, the store must keep \`type\` — update the adapter`);
5788
6059
  }
5789
6060
  }
5790
6061
  async function checkRoom(context, settings, invitations, scope, email) {
@@ -5796,7 +6067,7 @@ async function checkRoom(context, settings, invitations, scope, email) {
5796
6067
  return;
5797
6068
  const held = await findPending(invitations, scope, email);
5798
6069
  if (held === null || held.expiresAt.getTime() <= now.getTime()) {
5799
- throw limitReached3(WHERE4, settings);
6070
+ throw limitReached4(WHERE5, settings);
5800
6071
  }
5801
6072
  }
5802
6073
  async function insertInPlaceOfPending(context, settings, invitations, record, replaceable) {
@@ -5818,7 +6089,7 @@ async function insertInPlaceOfPending(context, settings, invitations, record, re
5818
6089
  continue;
5819
6090
  await emitInvitation(settings.events, "invitation.revoked", held, revokedAt);
5820
6091
  }
5821
- throw new StoreConflict2("pending", `${WHERE4}: another pending invitation holds this scope and address`, { operation: "insertInvitation" });
6092
+ throw new StoreConflict2("pending", `${WHERE5}: another pending invitation holds this scope and address`, { operation: "insertInvitation" });
5822
6093
  }
5823
6094
  async function withdraw(context, settings, invitations, record) {
5824
6095
  const revokedAt = context.clock.now();
@@ -5840,17 +6111,17 @@ async function withdraw(context, settings, invitations, record) {
5840
6111
  import { createHash as createHash3 } from "node:crypto";
5841
6112
 
5842
6113
  // src/auth/invitations/preview.ts
5843
- var WHERE5 = "invitations.preview";
6114
+ var WHERE6 = "invitations.preview";
5844
6115
  async function previewInvitation(invitations, clock, settings, invited, code) {
5845
6116
  if (!isCode(code))
5846
- throw invalidCode(WHERE5);
6117
+ throw invalidCode(WHERE6);
5847
6118
  const record = await invitations.findInvitationByCodeHash(hashSecret(code));
5848
6119
  const name = record === null ? null : configuredType(settings, record);
5849
6120
  if (record === null || name === null)
5850
- throw invalidCode(WHERE5);
6121
+ throw invalidCode(WHERE6);
5851
6122
  const refusal = refusalOf(clock, record);
5852
6123
  if (refusal !== null)
5853
- throw invalidCode(WHERE5, refusal);
6124
+ throw invalidCode(WHERE6, refusal);
5854
6125
  const { api, type } = invited(name);
5855
6126
  if (type.password === null)
5856
6127
  return toPreview(record, name, false);
@@ -5976,12 +6247,12 @@ function readApi2(invitations, clock, settings, invited) {
5976
6247
  }
5977
6248
 
5978
6249
  // src/auth/invitations/resend.ts
5979
- var WHERE6 = "invitations.resend";
6250
+ var WHERE7 = "invitations.resend";
5980
6251
  async function resendInvitation(context, settings, invitations, input) {
5981
6252
  const { clock } = context;
5982
6253
  const code = mintSecret();
5983
6254
  let lapsed = null;
5984
- const { record, now } = await changePending(invitations, clock, WHERE6, input, (at) => ({
6255
+ const { record, now } = await changePending(invitations, clock, WHERE7, input, (at) => ({
5985
6256
  codeHash: hashSecret(code),
5986
6257
  expiresAt: new Date(at.getTime() + settings.lifetimeMs),
5987
6258
  resentBy: input.by ?? null
@@ -5994,7 +6265,7 @@ async function resendInvitation(context, settings, invitations, input) {
5994
6265
  lapsed = found;
5995
6266
  const pending = await invitations.countPendingInvitations(found.scope, at);
5996
6267
  if (pending >= settings.maxPending)
5997
- throw limitReached3(WHERE6, settings);
6268
+ throw limitReached4(WHERE7, settings);
5998
6269
  });
5999
6270
  const revived = lapsed;
6000
6271
  if (revived !== null && settings.maxPending !== null) {
@@ -6006,7 +6277,7 @@ async function resendInvitation(context, settings, invitations, input) {
6006
6277
  expiresAt: revived.expiresAt,
6007
6278
  resentBy: revived.resentBy ?? null
6008
6279
  });
6009
- throw limitReached3(WHERE6, settings);
6280
+ throw limitReached4(WHERE7, settings);
6010
6281
  }
6011
6282
  }
6012
6283
  await emitInvitation(settings.events, "invitation.resent", record, now, input.by);
@@ -6119,9 +6390,9 @@ function accountTaken(ending, provider) {
6119
6390
  }
6120
6391
 
6121
6392
  // src/auth/social/complete-link.ts
6122
- async function completeLink(ending, userId, provider, identity) {
6393
+ async function completeLink(ending, flow, provider, identity) {
6123
6394
  const { context, type, returnTo, stepUp, where } = ending;
6124
- const record = await getRecord(context, userId, type.name, where);
6395
+ const record = await getRecord(context, flow.userId, type.name, where);
6125
6396
  if (!record.active) {
6126
6397
  throw new UserInactiveError2(`${where}: the user is inactive`, {
6127
6398
  userId: record.id,
@@ -6129,6 +6400,9 @@ async function completeLink(ending, userId, provider, identity) {
6129
6400
  ...afterFlow(ending)
6130
6401
  });
6131
6402
  }
6403
+ if (record.emailVerifiedAt !== null && record.emailVerifiedAt.getTime() > flow.startedAt.getTime()) {
6404
+ throw new SocialError2("FLOW_MISMATCH", `${where}: the user's e-mail was proved after this link was started — start it again`, { provider, flowSpent: true });
6405
+ }
6132
6406
  const attached = await attachLink(context, record, provider, identity);
6133
6407
  if (attached.taken)
6134
6408
  throw accountTaken(ending, provider);
@@ -6456,31 +6730,79 @@ async function redeemFlow(context, input, where) {
6456
6730
  meta,
6457
6731
  provider,
6458
6732
  values,
6459
- userId: meta.link ? token.userId : null
6733
+ userId: meta.link ? token.userId : null,
6734
+ startedAt: token.createdAt
6460
6735
  };
6461
6736
  }
6462
6737
 
6738
+ // src/auth/social/replace-holder.ts
6739
+ async function allowsReplacing(ending, holder, provider, identity) {
6740
+ const policy = ending.type.social?.unverifiedHolder ?? "refuse";
6741
+ if (typeof policy !== "function")
6742
+ return policy === "replace";
6743
+ const answer = await policy(Object.freeze({ id: holder.id, type: holder.type }), Object.freeze({ ...identity, provider }));
6744
+ return answer === "replace";
6745
+ }
6746
+ async function replaceHolder(ending, record) {
6747
+ const { context, type, where } = ending;
6748
+ let written = false;
6749
+ try {
6750
+ return await proveFirstEmail(context, type, record, where, {
6751
+ revokeFirst: false,
6752
+ onWritten: () => {
6753
+ written = true;
6754
+ }
6755
+ });
6756
+ } finally {
6757
+ if (written)
6758
+ await dropLinks(context, record);
6759
+ }
6760
+ }
6761
+ async function dropLinks(context, user) {
6762
+ const store = linkStore(context);
6763
+ for (const link of await store.listUserSocialLinks(user.id)) {
6764
+ if (await store.deleteSocialLink(user.id, link.provider, link.accountId)) {
6765
+ await emit(context, "user.socialUnlinked", user, context.clock.now(), {
6766
+ provider: link.provider
6767
+ });
6768
+ }
6769
+ }
6770
+ }
6771
+
6463
6772
  // src/auth/social/link-holder.ts
6464
6773
  async function linkHolder(ending, holder, provider, identity) {
6465
- const { context, where } = ending;
6466
- if (!identity.emailVerified || holder.emailVerifiedAt === null) {
6467
- throw new SocialError2("EMAIL_NOT_VERIFIED_FOR_LINK", `${where}: a user holds this e-mail, and the provider or the account does not vouch for it — sign in another way, then link the account`, afterFlow(ending, provider));
6468
- }
6469
- const record = await getRecord(context, holder.id, holder.type, where);
6470
- if (!record.active) {
6774
+ const { context, type, where } = ending;
6775
+ const unverified = () => new SocialError2("EMAIL_NOT_VERIFIED_FOR_LINK", `${where}: a user holds this e-mail, and the provider or the account does not vouch for it — sign in another way, then link the account`, afterFlow(ending, provider));
6776
+ if (!identity.emailVerified)
6777
+ throw unverified();
6778
+ const replacing = holder.emailVerifiedAt === null;
6779
+ if (replacing && !await allowsReplacing(ending, holder, provider, identity)) {
6780
+ throw unverified();
6781
+ }
6782
+ const read = await getRecord(context, holder.id, holder.type, where);
6783
+ if (!read.active) {
6471
6784
  throw new UserInactiveError2(`${where}: the user is inactive`, {
6472
- userId: record.id,
6473
- userType: record.type,
6785
+ userId: read.id,
6786
+ userType: read.type,
6474
6787
  ...afterFlow(ending)
6475
6788
  });
6476
6789
  }
6790
+ let record = read;
6791
+ if (read.emailVerifiedAt === null) {
6792
+ const held = emailOf(type, read.fields);
6793
+ if (!replacing || identity.email === null || held === null || normalizeEmail(held) !== normalizeEmail(identity.email)) {
6794
+ throw unverified();
6795
+ }
6796
+ record = await replaceHolder(ending, read);
6797
+ }
6477
6798
  const attached = await attachLink(context, record, provider, identity);
6478
6799
  if (attached.taken)
6479
6800
  throw accountTaken(ending, provider);
6480
6801
  return finishSocial(ending, record, {
6481
6802
  provider,
6482
6803
  created: false,
6483
- linked: attached.won
6804
+ linked: attached.won,
6805
+ replaced: record !== read
6484
6806
  });
6485
6807
  }
6486
6808
 
@@ -6521,7 +6843,8 @@ async function signUpNew(ending, provider, identity) {
6521
6843
  return finishSocial(ending, written, {
6522
6844
  provider,
6523
6845
  created: true,
6524
- linked: true
6846
+ linked: true,
6847
+ replaced: false
6525
6848
  });
6526
6849
  }
6527
6850
  function mustBeTheirs(fields, ending, email) {
@@ -6552,7 +6875,8 @@ async function signInAccount(ending, provider, identity) {
6552
6875
  return finishSocial(ending, record, {
6553
6876
  provider,
6554
6877
  created: false,
6555
- linked: false
6878
+ linked: false,
6879
+ replaced: false
6556
6880
  });
6557
6881
  }
6558
6882
  await store.deleteSocialLink(link.userId, provider, identity.accountId);
@@ -6606,36 +6930,36 @@ function stepUpOutcome(meta, identity, now, where) {
6606
6930
  }
6607
6931
 
6608
6932
  // src/auth/social/complete.ts
6609
- var WHERE7 = "social.complete";
6933
+ var WHERE8 = "social.complete";
6610
6934
  async function completeFlow(context, finishers, input, options) {
6611
6935
  if (!(input?.callback instanceof URLSearchParams)) {
6612
- throw new TypeError(`${WHERE7}: callback must be the URLSearchParams of the callback URL — new URL(request.url).searchParams`);
6936
+ throw new TypeError(`${WHERE8}: callback must be the URLSearchParams of the callback URL — new URL(request.url).searchParams`);
6613
6937
  }
6614
6938
  const { purpose } = input;
6615
6939
  if (purpose !== undefined && purpose !== "signIn" && purpose !== "link") {
6616
- throw new TypeError(`${WHERE7}: purpose must be 'signIn' or 'link' when given`);
6940
+ throw new TypeError(`${WHERE8}: purpose must be 'signIn' or 'link' when given`);
6617
6941
  }
6618
- const device = deviceHint(context, options, WHERE7);
6942
+ const device = deviceHint(context, options, WHERE8);
6619
6943
  const redeemed = await redeemFlow(context, {
6620
6944
  callback: input.callback,
6621
6945
  flow: input.flow,
6622
6946
  current: input.current ?? null,
6623
6947
  purpose
6624
- }, WHERE7);
6948
+ }, WHERE8);
6625
6949
  const { type, meta, values, provider: configured } = redeemed;
6626
6950
  const finish = finishers.get(type.name);
6627
6951
  if (finish === undefined) {
6628
- throw new TypeError(`${WHERE7}: the user type lost its social configuration`);
6952
+ throw new TypeError(`${WHERE8}: the user type lost its social configuration`);
6629
6953
  }
6630
6954
  if (meta.stepUp !== null && configured.supportsStepUp !== true) {
6631
- throw unsupportedStepUp(meta, WHERE7);
6955
+ throw unsupportedStepUp(meta, WHERE8);
6632
6956
  }
6633
6957
  const identity = checkIdentity(await callProvider(() => configured.exchange({
6634
6958
  callback: input.callback,
6635
6959
  ...values,
6636
6960
  stepUp: meta.stepUp
6637
- }), meta.provider, WHERE7, meta), meta.provider, WHERE7, meta);
6638
- const stepUp = stepUpOutcome(meta, identity, context.clock.now(), WHERE7);
6961
+ }), meta.provider, WHERE8, meta), meta.provider, WHERE8, meta);
6962
+ const stepUp = stepUpOutcome(meta, identity, context.clock.now(), WHERE8);
6639
6963
  const ending = {
6640
6964
  context,
6641
6965
  type,
@@ -6644,9 +6968,13 @@ async function completeFlow(context, finishers, input, options) {
6644
6968
  returnTo: meta.returnTo,
6645
6969
  stepUp,
6646
6970
  amr: federatedMethods(configured.federatedAmr, identity),
6647
- where: WHERE7
6971
+ where: WHERE8
6648
6972
  };
6649
- return redeemed.userId === null ? signInAccount(ending, meta.provider, identity) : completeLink(ending, redeemed.userId, meta.provider, identity);
6973
+ return endFlow(ending, redeemed, identity);
6974
+ }
6975
+ function endFlow(ending, redeemed, identity) {
6976
+ const { userId, startedAt, meta } = redeemed;
6977
+ return userId === null ? signInAccount(ending, meta.provider, identity) : completeLink(ending, { userId, startedAt }, meta.provider, identity);
6650
6978
  }
6651
6979
 
6652
6980
  // src/auth/social/return-to.ts
@@ -6945,6 +7273,75 @@ function sealerFor(keys, purpose) {
6945
7273
  }
6946
7274
  };
6947
7275
  }
7276
+ // src/auth/signed-token.ts
7277
+ import { createHmac as createHmac3, timingSafeEqual as timingSafeEqual7 } from "node:crypto";
7278
+ var MAX_PURPOSE2 = 256;
7279
+ var MAX_TOKEN = 8192;
7280
+ function checkPurpose(purpose, where) {
7281
+ if (typeof purpose !== "string" || purpose === "" || purpose.length > MAX_PURPOSE2 || !isStorable(purpose)) {
7282
+ throw new TypeError(`${where}: purpose must be a well-formed string of 1 to ${MAX_PURPOSE2} characters`);
7283
+ }
7284
+ return `janus/signed-token/v1/${purpose}`;
7285
+ }
7286
+ function mac2(key, signed) {
7287
+ return createHmac3("sha256", key).update(signed).digest();
7288
+ }
7289
+ function signToken(keys, purpose, payload, options) {
7290
+ const named = checkPurpose(purpose, "signToken");
7291
+ const sealer = resolveSealer(keys, "signToken");
7292
+ const ttl = parseDuration(options.expiresIn, "signToken: expiresIn");
7293
+ const json = payload === undefined ? undefined : JSON.stringify({ d: payload });
7294
+ if (json === undefined) {
7295
+ throw new TypeError("signToken: the payload must be a JSON value");
7296
+ }
7297
+ const e = (options.clock ?? systemClock).now().getTime() + ttl;
7298
+ const body = Buffer.from(JSON.stringify({ e, d: payload })).toString("base64url");
7299
+ const head = `v1.${sealer.sealWith}.${body}`;
7300
+ const key = derivedKey(sealer, named);
7301
+ const token = `${head}.${mac2(key, head).toString("base64url")}`;
7302
+ if (token.length > MAX_TOKEN) {
7303
+ throw new TypeError("signToken: the token is over 8 KiB; keep the payload small");
7304
+ }
7305
+ return token;
7306
+ }
7307
+ function verifyToken(keys, purpose, token, options = {}) {
7308
+ const named = checkPurpose(purpose, "verifyToken");
7309
+ const sealer = resolveSealer(keys, "verifyToken");
7310
+ if (typeof token !== "string" || token.length > MAX_TOKEN)
7311
+ return null;
7312
+ const parts = token.split(".");
7313
+ const [version, keyId, body, sig] = parts;
7314
+ if (parts.length !== 4 || version !== "v1" || keyId === undefined || body === undefined || sig === undefined) {
7315
+ return null;
7316
+ }
7317
+ const key = derivedKey(sealer, named, keyId);
7318
+ if (key === undefined)
7319
+ return null;
7320
+ const expected = mac2(key, `v1.${keyId}.${body}`);
7321
+ const given = Buffer.from(sig, "base64url");
7322
+ if (given.toString("base64url") !== sig)
7323
+ return null;
7324
+ if (given.length !== expected.length || !timingSafeEqual7(given, expected)) {
7325
+ return null;
7326
+ }
7327
+ let parsed;
7328
+ try {
7329
+ parsed = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
7330
+ } catch {
7331
+ return null;
7332
+ }
7333
+ if (typeof parsed.e !== "number" || !Number.isFinite(parsed.e))
7334
+ return null;
7335
+ const now = (options.clock ?? systemClock).now().getTime();
7336
+ if (now >= parsed.e)
7337
+ return null;
7338
+ return {
7339
+ payload: parsed.d,
7340
+ expiresAt: new Date(parsed.e),
7341
+ keyId,
7342
+ needsResign: keyId !== sealer.sealWith
7343
+ };
7344
+ }
6948
7345
  // src/background/background.ts
6949
7346
  function background(log = (line) => console.error(line)) {
6950
7347
  const running = new Set;
@@ -6969,6 +7366,7 @@ export {
6969
7366
  AMR,
6970
7367
  ApiKeyInvalidError2 as ApiKeyInvalidError,
6971
7368
  ApiKeyLimitError2 as ApiKeyLimitError,
7369
+ ApiKeyRefusedError2 as ApiKeyRefusedError,
6972
7370
  AvatarIdInvalidError2 as AvatarIdInvalidError,
6973
7371
  CredentialError2 as CredentialError,
6974
7372
  CursorFilterMismatchError2 as CursorFilterMismatchError,
@@ -7032,10 +7430,12 @@ export {
7032
7430
  scryptHasher,
7033
7431
  sealerFor,
7034
7432
  setOf2 as setOf,
7433
+ signToken,
7035
7434
  statusOf2 as statusOf,
7036
7435
  subjectOf2 as subjectOf,
7037
- systemClock
7436
+ systemClock,
7437
+ verifyToken
7038
7438
  };
7039
7439
 
7040
- //# debugId=53A8959760904ABA64756E2164756E21
7440
+ //# debugId=51DCD587093E020564756E2164756E21
7041
7441
  //# sourceMappingURL=index.js.map