@softistx/janus 0.76.0 → 0.78.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 (99) hide show
  1. package/README.md +11 -6
  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 +1 -1
  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/resolved-config.d.ts +8 -0
  29. package/dist/auth/config/resolved-config.d.ts.map +1 -1
  30. package/dist/auth/index.d.ts +3 -2
  31. package/dist/auth/index.d.ts.map +1 -1
  32. package/dist/auth/port/memory/api-keys/capabilities.d.ts.map +1 -1
  33. package/dist/auth/port/memory/api-keys/index.d.ts.map +1 -1
  34. package/dist/auth/port/types/api-keys.d.ts +25 -5
  35. package/dist/auth/port/types/api-keys.d.ts.map +1 -1
  36. package/dist/auth/sessions/amr.d.ts +2 -2
  37. package/dist/auth/sessions/authenticate.d.ts +3 -2
  38. package/dist/auth/sessions/authenticate.d.ts.map +1 -1
  39. package/dist/auth/sessions/fresh.d.ts +2 -2
  40. package/dist/auth/sessions/fresh.d.ts.map +1 -1
  41. package/dist/auth/sessions/shared-api.d.ts +3 -2
  42. package/dist/auth/sessions/shared-api.d.ts.map +1 -1
  43. package/dist/auth/shared-api.d.ts +11 -3
  44. package/dist/auth/shared-api.d.ts.map +1 -1
  45. package/dist/auth/signed-token.d.ts +41 -0
  46. package/dist/auth/signed-token.d.ts.map +1 -0
  47. package/dist/auth/types/api-keys-of.d.ts +6 -1
  48. package/dist/auth/types/api-keys-of.d.ts.map +1 -1
  49. package/dist/auth/types/api-keys.d.ts +18 -6
  50. package/dist/auth/types/api-keys.d.ts.map +1 -1
  51. package/dist/auth/types/checks.d.ts +17 -1
  52. package/dist/auth/types/checks.d.ts.map +1 -1
  53. package/dist/auth/types/index.d.ts +3 -2
  54. package/dist/auth/types/index.d.ts.map +1 -1
  55. package/dist/auth/types/service-keys.d.ts +58 -0
  56. package/dist/auth/types/service-keys.d.ts.map +1 -0
  57. package/dist/auth/types/session.d.ts +21 -2
  58. package/dist/auth/types/session.d.ts.map +1 -1
  59. package/dist/auth/types/shared-api.d.ts +15 -1
  60. package/dist/auth/types/shared-api.d.ts.map +1 -1
  61. package/dist/auth/types/sign-in.d.ts +1 -1
  62. package/dist/auth/types/sign-in.d.ts.map +1 -1
  63. package/dist/chunks/{index-7h34nqrm.js → index-5hcajrrx.js} +5 -5
  64. package/dist/chunks/{index-7h34nqrm.js.map → index-5hcajrrx.js.map} +4 -4
  65. package/dist/chunks/{index-n8jxmxeg.js → index-gzc472ar.js} +2 -2
  66. package/dist/chunks/{index-ftz0ne6j.js → index-r8fcessc.js} +2 -2
  67. package/dist/chunks/{index-2ttdcz7n.js → index-vx9a5cpy.js} +9 -3
  68. package/dist/chunks/{index-2ttdcz7n.js.map → index-vx9a5cpy.js.map} +4 -4
  69. package/dist/conformance/api-keys/cases/index.d.ts.map +1 -1
  70. package/dist/conformance/api-keys/cases/outage.d.ts.map +1 -1
  71. package/dist/conformance/api-keys/cases/service.d.ts +3 -0
  72. package/dist/conformance/api-keys/cases/service.d.ts.map +1 -0
  73. package/dist/conformance/index.js +407 -302
  74. package/dist/conformance/index.js.map +6 -5
  75. package/dist/errors/janus-error/codes.invitations.d.ts +6 -0
  76. package/dist/errors/janus-error/codes.invitations.d.ts.map +1 -1
  77. package/dist/errors/janus-error/index.d.ts +1 -1
  78. package/dist/errors/janus-error/index.d.ts.map +1 -1
  79. package/dist/errors/janus-error/options.d.ts +1 -1
  80. package/dist/errors/janus-error/options.d.ts.map +1 -1
  81. package/dist/errors/janus-error/refusals.d.ts +5 -0
  82. package/dist/errors/janus-error/refusals.d.ts.map +1 -1
  83. package/dist/errors/janus-error/status.d.ts.map +1 -1
  84. package/dist/index.d.ts +1 -1
  85. package/dist/index.d.ts.map +1 -1
  86. package/dist/index.js +428 -100
  87. package/dist/index.js.map +22 -16
  88. package/dist/permissions/index.js +3 -3
  89. package/docs/README.md +1 -0
  90. package/docs/guide/api-keys.md +78 -1
  91. package/docs/guide/errors.md +1 -0
  92. package/docs/guide/second-factor.md +1 -1
  93. package/docs/guide/sessions.md +3 -1
  94. package/docs/guide/signed-tokens.md +46 -0
  95. package/docs/roadmap.md +3 -1
  96. package/docs/troubleshooting.md +17 -5
  97. package/package.json +1 -1
  98. /package/dist/chunks/{index-n8jxmxeg.js.map → index-gzc472ar.js.map} +0 -0
  99. /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]+$/;
@@ -839,7 +867,7 @@ var AMR = {
839
867
  oneTimeCode: ["otp"],
840
868
  passkey: ["hwk", "user"],
841
869
  appCode: ["otp", "mfa"],
842
- recoveryCode: ["otp", "mfa"],
870
+ recoveryCode: ["rec", "mfa"],
843
871
  passkeySecondFactor: ["hwk", "user", "mfa"],
844
872
  social: ["fed"]
845
873
  };
@@ -2364,6 +2392,9 @@ function anyTypeVerifyEmail(context) {
2364
2392
  // src/auth/sessions/fresh.ts
2365
2393
  function assertFresh(subject, maxAge, clock = systemClock) {
2366
2394
  if ("via" in subject) {
2395
+ if (subject.via === "serviceKey") {
2396
+ throw new StepUpRequiredError2("assertFresh: an API key is never fresh — the caller needs a signed-in session", { reason: "apiKey" });
2397
+ }
2367
2398
  if (subject.via === "apiKey") {
2368
2399
  throw new StepUpRequiredError2("assertFresh: an API key is never fresh — the caller needs a signed-in session", { userId: subject.apiKey.userId, reason: "apiKey" });
2369
2400
  }
@@ -2698,12 +2729,20 @@ function apiKeyHint(prefix, id) {
2698
2729
 
2699
2730
  // src/auth/api-keys/to-api-key.ts
2700
2731
  function toApiKey(prefix, record) {
2701
- const { secretHash: _hash, scopes, bound, expiryNotifiedAt, ...key } = record;
2732
+ const {
2733
+ secretHash: _hash,
2734
+ scopes,
2735
+ bound,
2736
+ details,
2737
+ expiryNotifiedAt,
2738
+ ...key
2739
+ } = record;
2702
2740
  return {
2703
2741
  ...key,
2704
2742
  hint: apiKeyHint(prefix, record.id),
2705
2743
  scopes: scopes ?? null,
2706
2744
  bound: bound ?? null,
2745
+ details: details === undefined ? null : structuredClone(details),
2707
2746
  expiryNotifiedAt: expiryNotifiedAt ?? null
2708
2747
  };
2709
2748
  }
@@ -2728,17 +2767,19 @@ async function authenticateKey(context, keys, token, options) {
2728
2767
  return null;
2729
2768
  }
2730
2769
  const now = context.clock.now();
2731
- if (record.revokedAt !== null || record.expiresAt.getTime() <= now.getTime()) {
2770
+ if (record.revokedAt !== null || record.expiresAt !== null && record.expiresAt.getTime() <= now.getTime()) {
2732
2771
  return null;
2733
2772
  }
2773
+ if (record.userId === null) {
2774
+ if (options?.service !== true || options.type !== undefined)
2775
+ return null;
2776
+ return serviceKeyPrincipal(settings, keys, record, token, now);
2777
+ }
2734
2778
  const user = await context.store.users.findUser(record.userId);
2735
2779
  if (user === null || !user.active || !settings.types.has(user.type) || options?.type !== undefined && user.type !== options.type) {
2736
2780
  return null;
2737
2781
  }
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);
2782
+ const apiKey = await touch(settings, keys, record, now);
2742
2783
  return {
2743
2784
  via: "apiKey",
2744
2785
  user: toUser(user),
@@ -2750,6 +2791,27 @@ async function authenticateKey(context, keys, token, options) {
2750
2791
  renewed: false
2751
2792
  };
2752
2793
  }
2794
+ async function touch(settings, keys, record, now) {
2795
+ const staleBefore = new Date(now.getTime() - settings.lastUsedEveryMs);
2796
+ const stale = record.lastUsedAt === null || record.lastUsedAt.getTime() < staleBefore.getTime();
2797
+ const touched = stale && await keys.touchApiKey(record.id, now, staleBefore);
2798
+ return toApiKey(settings.prefix, touched ? { ...record, lastUsedAt: now } : record);
2799
+ }
2800
+ async function serviceKeyPrincipal(settings, keys, record, token, now) {
2801
+ if (record.bound === undefined || record.scopes === undefined)
2802
+ return null;
2803
+ const apiKey = await touch(settings, keys, record, now);
2804
+ return {
2805
+ via: "serviceKey",
2806
+ apiKey,
2807
+ scopes: record.scopes,
2808
+ bound: { type: record.bound.type, id: record.bound.id },
2809
+ user: null,
2810
+ session: null,
2811
+ token,
2812
+ renewed: false
2813
+ };
2814
+ }
2753
2815
 
2754
2816
  // src/auth/sessions/standing.ts
2755
2817
  function absoluteEnd(type, session) {
@@ -3447,6 +3509,20 @@ function boundApi(context, prefix, keys) {
3447
3509
  };
3448
3510
  }
3449
3511
 
3512
+ // src/auth/api-keys/create/after-insert.ts
3513
+ async function settleInsert(keys, clock, id, checks, noun) {
3514
+ const [after] = await Promise.allSettled([checks]);
3515
+ if (after.status === "fulfilled")
3516
+ return;
3517
+ const [revoked] = await Promise.allSettled([
3518
+ keys.revokeApiKey(id, clock.now())
3519
+ ]);
3520
+ if (revoked.status === "rejected") {
3521
+ 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" });
3522
+ }
3523
+ throw after.reason;
3524
+ }
3525
+
3450
3526
  // src/auth/api-keys/count.ts
3451
3527
  async function countStanding(keys, userId, now, stopAt) {
3452
3528
  let standing = 0;
@@ -3457,7 +3533,7 @@ async function countStanding(keys, userId, now, stopAt) {
3457
3533
  after
3458
3534
  });
3459
3535
  for (const key of page.items) {
3460
- if (key.revokedAt === null && key.expiresAt.getTime() > now.getTime()) {
3536
+ if (key.revokedAt === null && (key.expiresAt === null || key.expiresAt.getTime() > now.getTime())) {
3461
3537
  standing += 1;
3462
3538
  }
3463
3539
  }
@@ -3470,47 +3546,60 @@ async function countStanding(keys, userId, now, stopAt) {
3470
3546
  var NAME_MAX2 = 100;
3471
3547
  var WHERE = "apiKeys.create";
3472
3548
  async function checkBeforeInsert(context, settings, keys, current, input) {
3473
- const { store, clock } = context;
3549
+ const { clock } = context;
3474
3550
  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);
3551
+ assertFreshCreator(context, settings, current);
3479
3552
  const name = checkName2(input?.name);
3480
3553
  const lifetimeMs = checkLifetime(settings, input?.lifetime);
3481
3554
  const scopes = checkScopes(input?.scopes, WHERE);
3482
3555
  const bound = checkBound(input?.bound, WHERE);
3483
3556
  if (scopes !== undefined || bound !== undefined)
3484
3557
  boundMethods(keys, WHERE);
3558
+ const user = await loadCreator(context, settings, current);
3559
+ if (await countStanding(keys, user.id, clock.now(), settings.maxActive) >= settings.maxActive) {
3560
+ throw limitReached2(settings, userId);
3561
+ }
3562
+ return {
3563
+ user,
3564
+ name,
3565
+ lifetimeMs,
3566
+ extra: {
3567
+ ...scopes === undefined ? {} : { scopes },
3568
+ ...bound === undefined ? {} : { bound }
3569
+ }
3570
+ };
3571
+ }
3572
+ function assertFreshCreator(context, settings, current, where = WHERE) {
3573
+ const userId = refOf(current);
3574
+ if (current.via !== "session") {
3575
+ 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" });
3576
+ }
3577
+ assertFresh({
3578
+ authenticatedAt: current.session.authenticatedAt,
3579
+ userId
3580
+ }, settings.freshWithinMs, context.clock);
3581
+ }
3582
+ async function loadCreator(context, settings, current, where = WHERE) {
3583
+ const { store } = context;
3584
+ const userId = refOf(current);
3485
3585
  const user = await store.users.findUser(userId);
3486
3586
  if (user === null || !settings.types.has(user.type)) {
3487
- throw new NotFoundError2(`${WHERE}: no such user can hold API keys`, {
3587
+ throw new NotFoundError2(`${where}: no such user can hold API keys`, {
3488
3588
  userId
3489
3589
  });
3490
3590
  }
3491
3591
  if (!user.active) {
3492
- throw new UserInactiveError2(`${WHERE}: the user is inactive`, { userId });
3592
+ throw new UserInactiveError2(`${where}: the user is inactive`, { userId });
3493
3593
  }
3494
3594
  const type = context.config.types.get(user.type);
3495
3595
  if (user.emailVerifiedAt === null && type !== undefined && emailOf(type, user.fields) !== null) {
3496
- throw new EmailUnverifiedError2(`${WHERE}: the e-mail is not verified`, {
3596
+ throw new EmailUnverifiedError2(`${where}: the e-mail is not verified`, {
3497
3597
  userId,
3498
3598
  userType: user.type
3499
3599
  });
3500
3600
  }
3501
3601
  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
- };
3602
+ return user;
3514
3603
  }
3515
3604
  function limitReached2(settings, userId) {
3516
3605
  return new ApiKeyLimitError2(`${WHERE}: the user already holds ${settings.maxActive} API keys — revoke one first`, { userId, maxActive: settings.maxActive });
@@ -3522,25 +3611,29 @@ function checkPasswordHeld(current, user) {
3522
3611
  }
3523
3612
  }
3524
3613
  async function checkAfterInsert(context, settings, keys, current, userId) {
3525
- const { store, clock } = context;
3614
+ const { clock } = context;
3526
3615
  const standing = await countStanding(keys, userId, clock.now(), settings.maxActive + 1);
3527
3616
  if (standing > settings.maxActive)
3528
3617
  throw limitReached2(settings, userId);
3618
+ await checkCreatorStands(context, current, userId);
3619
+ }
3620
+ async function checkCreatorStands(context, current, userId, where = WHERE) {
3621
+ const { store, clock } = context;
3529
3622
  const user = await store.users.findUser(userId);
3530
3623
  if (user === null) {
3531
- throw new NotFoundError2(`${WHERE}: no such user can hold API keys`, {
3624
+ throw new NotFoundError2(`${where}: no such user can hold API keys`, {
3532
3625
  userId
3533
3626
  });
3534
3627
  }
3535
3628
  if (!user.active) {
3536
- throw new UserInactiveError2(`${WHERE}: the user is inactive`, { userId });
3629
+ throw new UserInactiveError2(`${where}: the user is inactive`, { userId });
3537
3630
  }
3538
3631
  checkPasswordHeld(current, user);
3539
3632
  if (current.via === "apiKey")
3540
3633
  return;
3541
3634
  const session = await store.sessions.findSessionByTokenHash(hashSecret(current.token));
3542
3635
  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 });
3636
+ throw new StepUpRequiredError2(`${where}: the session ended while the key was made — sign in again`, { userId });
3544
3637
  }
3545
3638
  }
3546
3639
  function refOf(current) {
@@ -3582,18 +3675,7 @@ async function createApiKey(context, settings, keys, current, input) {
3582
3675
  ...extra
3583
3676
  };
3584
3677
  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
- }
3678
+ await settleInsert(keys, clock, id, checkAfterInsert(context, settings, keys, current, user.id), "an API key");
3597
3679
  await keyCreated(context, user, createdAt);
3598
3680
  return {
3599
3681
  apiKey: toApiKey(settings.prefix, record),
@@ -3621,7 +3703,7 @@ function expiryApi(context, prefix, keys) {
3621
3703
  after
3622
3704
  });
3623
3705
  return {
3624
- items: found.items.map((record) => toApiKey(prefix, record)),
3706
+ items: found.items.filter((record) => record.userId !== null).map((record) => toApiKey(prefix, record)),
3625
3707
  nextCursor: found.nextCursor
3626
3708
  };
3627
3709
  },
@@ -3712,6 +3794,179 @@ function readApi(prefix, keys) {
3712
3794
  };
3713
3795
  }
3714
3796
 
3797
+ // src/auth/api-keys/owned.ts
3798
+ var READ2 = 100;
3799
+ async function listOwnedRecords(keys, owner, { first, after }, where) {
3800
+ const store = boundMethods(keys, where);
3801
+ const kept = [];
3802
+ let cursor = after;
3803
+ do {
3804
+ const found = await store.list({ type: owner.type, id: owner.id }, { first: READ2, after: cursor });
3805
+ for (const record of found.items) {
3806
+ if (record.userId === null)
3807
+ kept.push(record);
3808
+ }
3809
+ cursor = found.nextCursor;
3810
+ } while (cursor !== null && kept.length <= first);
3811
+ const items = kept.slice(0, first);
3812
+ const last = items.at(-1);
3813
+ return {
3814
+ items,
3815
+ nextCursor: kept.length > first && last !== undefined ? last.id : null
3816
+ };
3817
+ }
3818
+ async function countOwnedStanding(keys, owner, now, stopAt, where) {
3819
+ let standing = 0;
3820
+ let after = null;
3821
+ do {
3822
+ const page = await listOwnedRecords(keys, owner, { first: MAX_PAGE_SIZE2, after }, where);
3823
+ for (const key of page.items) {
3824
+ if (key.revokedAt === null && (key.expiresAt === null || key.expiresAt.getTime() > now.getTime())) {
3825
+ standing += 1;
3826
+ }
3827
+ }
3828
+ after = page.nextCursor;
3829
+ } while (after !== null && standing < stopAt);
3830
+ return standing;
3831
+ }
3832
+
3833
+ // src/auth/api-keys/create/service-checks.ts
3834
+ var WHERE2 = "apiKeys.createService";
3835
+ var DETAILS_MAX = 4000;
3836
+ function limitReached3(maxActive) {
3837
+ return new ApiKeyLimitError2(`${WHERE2}: the owner already holds ${maxActive} service keys — revoke one first`, { maxActive });
3838
+ }
3839
+ function checkOwner(owner) {
3840
+ if (!isBound(owner)) {
3841
+ 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" });
3842
+ }
3843
+ return { type: owner.type, id: owner.id };
3844
+ }
3845
+ function checkServiceLifetime(settings, lifetime) {
3846
+ if (lifetime === "never") {
3847
+ if (settings.never)
3848
+ return null;
3849
+ throw new ApiKeyInvalidError2(`${WHERE2}: lifetime "never" is not enabled: list it in apiKeys.lifetimes`, { field: "lifetime" });
3850
+ }
3851
+ return checkLifetime(settings, lifetime);
3852
+ }
3853
+ function checkDetails(details) {
3854
+ if (details === undefined)
3855
+ return;
3856
+ const refuse = () => new ApiKeyInvalidError2(`${WHERE2}: details must be a plain JSON object of at most ${DETAILS_MAX} characters`, { field: "details" });
3857
+ if (typeof details !== "object" || details === null || Array.isArray(details) || Object.getPrototypeOf(details) !== Object.prototype) {
3858
+ throw refuse();
3859
+ }
3860
+ let json;
3861
+ try {
3862
+ json = JSON.stringify(details);
3863
+ } catch {
3864
+ throw refuse();
3865
+ }
3866
+ if (json === undefined || json.length > DETAILS_MAX || !isStorable(json)) {
3867
+ throw refuse();
3868
+ }
3869
+ return JSON.parse(json);
3870
+ }
3871
+ function checkServiceInput(settings, input) {
3872
+ const name = checkName2(input?.name);
3873
+ const owner = checkOwner(input?.owner);
3874
+ const scopes = checkScopes(input?.scopes, WHERE2);
3875
+ if (scopes === undefined) {
3876
+ throw new ApiKeyInvalidError2(`${WHERE2}: a service key needs scopes`, {
3877
+ field: "scopes"
3878
+ });
3879
+ }
3880
+ const lifetimeMs = checkServiceLifetime(settings, input?.lifetime);
3881
+ const details = checkDetails(input?.details);
3882
+ return { name, owner, scopes, lifetimeMs, details };
3883
+ }
3884
+
3885
+ // src/auth/api-keys/create/service.ts
3886
+ async function createServiceKey(context, settings, keys, current, input) {
3887
+ const service = settings.service;
3888
+ if (service === null) {
3889
+ throw new TypeError(`${WHERE2} needs janus({ apiKeys: { service } })`);
3890
+ }
3891
+ const { clock } = context;
3892
+ assertFreshCreator(context, settings, current, WHERE2);
3893
+ const { name, owner, scopes, lifetimeMs, details } = checkServiceInput(settings, input);
3894
+ boundMethods(keys, WHERE2);
3895
+ const user = await loadCreator(context, settings, current, WHERE2);
3896
+ if (!await service.authorize({
3897
+ user: { id: user.id, type: user.type },
3898
+ owner,
3899
+ scopes
3900
+ })) {
3901
+ throw new ApiKeyRefusedError2(`${WHERE2}: the application refused this service key`, { userId: user.id });
3902
+ }
3903
+ if (await countOwnedStanding(keys, owner, clock.now(), service.maxActive, WHERE2) >= service.maxActive) {
3904
+ throw limitReached3(service.maxActive);
3905
+ }
3906
+ const secret = mintSecret();
3907
+ const id = mintId2();
3908
+ const createdAt = clock.now();
3909
+ const record = {
3910
+ id,
3911
+ userId: null,
3912
+ name,
3913
+ secretHash: hashSecret(secret),
3914
+ createdAt,
3915
+ expiresAt: lifetimeMs === null ? null : new Date(createdAt.getTime() + lifetimeMs),
3916
+ lastUsedAt: null,
3917
+ revokedAt: null,
3918
+ scopes,
3919
+ bound: owner,
3920
+ ...details === undefined ? {} : { details }
3921
+ };
3922
+ await keys.insertApiKey(record);
3923
+ await settleInsert(keys, clock, id, (async () => {
3924
+ const standing = await countOwnedStanding(keys, owner, clock.now(), service.maxActive + 1, WHERE2);
3925
+ if (standing > service.maxActive)
3926
+ throw limitReached3(service.maxActive);
3927
+ await checkCreatorStands(context, current, user.id, WHERE2);
3928
+ })(), "a service key");
3929
+ return {
3930
+ apiKey: toApiKey(settings.prefix, record),
3931
+ token: apiKeyToken(settings.prefix, id, secret)
3932
+ };
3933
+ }
3934
+
3935
+ // src/auth/api-keys/service-flows.ts
3936
+ function serviceApi(context, settings, keys) {
3937
+ const { clock } = context;
3938
+ return {
3939
+ async createService(current, input) {
3940
+ return createServiceKey(context, settings, keys, current, input);
3941
+ },
3942
+ async listOwned(owner, page) {
3943
+ const after = page?.after ?? null;
3944
+ if (after !== null && !isId2(after)) {
3945
+ throw invalidCursor2("apiKeys.listOwned", after);
3946
+ }
3947
+ const first = pageLimit2(page?.limit, "apiKeys.listOwned");
3948
+ if (!isBound(owner))
3949
+ return { items: [], nextCursor: null };
3950
+ const found = await listOwnedRecords(keys, owner, { first, after }, "apiKeys.listOwned");
3951
+ return {
3952
+ items: found.items.map((record) => toApiKey(settings.prefix, record)),
3953
+ nextCursor: found.nextCursor
3954
+ };
3955
+ },
3956
+ async revokeOwned(owner, id) {
3957
+ const missing = () => new NotFoundError2("apiKeys.revokeOwned: no such service key");
3958
+ if (typeof id !== "string" || !isId2(id) || !isBound(owner))
3959
+ throw missing();
3960
+ const record = await keys.findApiKey(id);
3961
+ if (record === null || record.userId !== null || record.bound?.type !== owner.type || record.bound.id !== owner.id) {
3962
+ throw missing();
3963
+ }
3964
+ if (!await keys.revokeApiKey(id, clock.now()))
3965
+ throw missing();
3966
+ }
3967
+ };
3968
+ }
3969
+
3715
3970
  // src/auth/api-keys/flows.ts
3716
3971
  function apiKeysApi(context, keys) {
3717
3972
  const settings = context.config.apiKeys;
@@ -3719,7 +3974,7 @@ function apiKeysApi(context, keys) {
3719
3974
  throw new TypeError("janus: apiKeysApi needs janus({ apiKeys })");
3720
3975
  }
3721
3976
  const { clock } = context;
3722
- return {
3977
+ const api = {
3723
3978
  async create(current, input) {
3724
3979
  return createApiKey(context, settings, keys, current, input);
3725
3980
  },
@@ -3733,7 +3988,7 @@ function apiKeysApi(context, keys) {
3733
3988
  if (typeof options === "object" && options !== null && "owner" in options && record.userId !== refId(options.owner)) {
3734
3989
  throw missing();
3735
3990
  }
3736
- const owner = await ownerForEvent(context, record.userId);
3991
+ const owner = record.userId === null ? null : await ownerForEvent(context, record.userId);
3737
3992
  const at = clock.now();
3738
3993
  if (!await keys.revokeApiKey(id, at))
3739
3994
  throw missing();
@@ -3753,6 +4008,7 @@ function apiKeysApi(context, keys) {
3753
4008
  ...boundApi(context, settings.prefix, keys),
3754
4009
  ...expiryApi(context, settings.prefix, keys)
3755
4010
  };
4011
+ return settings.service === null ? api : { ...api, ...serviceApi(context, settings, keys) };
3756
4012
  }
3757
4013
  // src/auth/email-flows/reset-password.ts
3758
4014
  function resetPasswordFlows(context, type, at) {
@@ -5379,21 +5635,21 @@ function toPreview(record, type, needsPassword) {
5379
5635
  }
5380
5636
 
5381
5637
  // src/auth/invitations/accept.ts
5382
- var WHERE2 = "invitations.accept";
5638
+ var WHERE3 = "invitations.accept";
5383
5639
  async function acceptInvitation(context, settings, invitations, invited, input) {
5384
5640
  const { clock } = context;
5385
5641
  const code = input?.code;
5386
5642
  if (!isCode(code))
5387
- throw invalidCode(WHERE2);
5643
+ throw invalidCode(WHERE3);
5388
5644
  const options = input.device === undefined ? {} : { device: input.device };
5389
- deviceHint(context, options, WHERE2);
5645
+ deviceHint(context, options, WHERE3);
5390
5646
  const found = await invitations.findInvitationByCodeHash(hashSecret(code));
5391
5647
  const name = found === null ? null : configuredType(settings, found);
5392
5648
  if (name === null)
5393
- throw invalidCode(WHERE2);
5649
+ throw invalidCode(WHERE3);
5394
5650
  const { api: typed, type } = invited(name);
5395
5651
  await beforeAccept(clock, settings, typed, found);
5396
- const claimed = await claim(invitations, clock, found, WHERE2);
5652
+ const claimed = await claim(invitations, clock, found, WHERE3);
5397
5653
  const prepared = await releasedOnFailure(invitations, clock, claimed, () => prepare(context, settings, invitations, typed, type, claimed, input.password));
5398
5654
  const invitation = toInvitation(prepared.record, settings.types[0]);
5399
5655
  await emitInvitation(settings.events, "invitation.accepted", prepared.record, prepared.record.updatedAt);
@@ -5406,21 +5662,21 @@ async function acceptInvitation(context, settings, invitations, invited, input)
5406
5662
  async function beforeAccept(clock, settings, typed, found) {
5407
5663
  if (settings.beforeAccept === null)
5408
5664
  return;
5409
- const pending = pendingRecord(clock, found, WHERE2);
5665
+ const pending = pendingRecord(clock, found, WHERE3);
5410
5666
  const existing = await typed.findByEmail(pending.email);
5411
5667
  if (existing !== null && !existing.active)
5412
- throw invalidCode(WHERE2);
5668
+ throw invalidCode(WHERE3);
5413
5669
  const proceed = await settings.beforeAccept({
5414
5670
  invitation: toInvitation(pending, settings.types[0]),
5415
5671
  user: existing === null ? null : { id: existing.id, type: existing.type }
5416
5672
  });
5417
5673
  if (!proceed) {
5418
- throw new InvitationRefusedError2(`${WHERE2}: the application refused this acceptance; the invitation is still pending`);
5674
+ throw new InvitationRefusedError2(`${WHERE3}: the application refused this acceptance; the invitation is still pending`);
5419
5675
  }
5420
5676
  }
5421
5677
  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);
5678
+ const { user, proved } = await inviteeOf(typed, type, toInvitation(claimed, settings.types[0]), settings.create, password, WHERE3);
5679
+ const record = await recordAcceptor(invitations, context.clock, claimed, user.id, WHERE3);
5424
5680
  await settings.onAccepted({
5425
5681
  invitation: toInvitation(record, settings.types[0]),
5426
5682
  user: { id: user.id, type: user.type }
@@ -5648,17 +5904,17 @@ function checkHistoryRecord(context, settings, input) {
5648
5904
  }
5649
5905
 
5650
5906
  // src/auth/invitations/history.ts
5651
- var WHERE3 = "invitations.importHistory";
5907
+ var WHERE4 = "invitations.importHistory";
5652
5908
  var IMPORT_MAX = 1000;
5653
5909
  function dryRunOf(options) {
5654
5910
  if (options === undefined)
5655
5911
  return false;
5656
5912
  if (typeof options !== "object" || options === null || Array.isArray(options)) {
5657
- throw new TypeError(`${WHERE3}: options must be an object`);
5913
+ throw new TypeError(`${WHERE4}: options must be an object`);
5658
5914
  }
5659
5915
  const { dryRun } = options;
5660
5916
  if (dryRun !== undefined && typeof dryRun !== "boolean") {
5661
- throw new TypeError(`${WHERE3}: options.dryRun must be a boolean`);
5917
+ throw new TypeError(`${WHERE4}: options.dryRun must be a boolean`);
5662
5918
  }
5663
5919
  return dryRun === true;
5664
5920
  }
@@ -5673,10 +5929,10 @@ function refused(key, id, reason, field) {
5673
5929
  }
5674
5930
  async function importHistory(context, settings, invitations, records, options) {
5675
5931
  if (!Array.isArray(records)) {
5676
- throw new TypeError(`${WHERE3}: records must be an array`);
5932
+ throw new TypeError(`${WHERE4}: records must be an array`);
5677
5933
  }
5678
5934
  if (records.length > IMPORT_MAX) {
5679
- throw new TypeError(`${WHERE3}: at most ${IMPORT_MAX} records per call`);
5935
+ throw new TypeError(`${WHERE4}: at most ${IMPORT_MAX} records per call`);
5680
5936
  }
5681
5937
  const dryRun = dryRunOf(options);
5682
5938
  const items = [];
@@ -5726,23 +5982,23 @@ async function importHistory(context, settings, invitations, records, options) {
5726
5982
  }
5727
5983
 
5728
5984
  // src/auth/invitations/limit.ts
5729
- function limitReached3(where, settings) {
5985
+ function limitReached4(where, settings) {
5730
5986
  return new InvitationLimitError2(`${where}: the scope already holds ${settings.maxPending} pending invitations — revoke one first`, settings.maxPending === null ? {} : { maxActive: settings.maxPending });
5731
5987
  }
5732
5988
 
5733
5989
  // src/auth/invitations/issue.ts
5734
- var WHERE4 = "invitations.issue";
5990
+ var WHERE5 = "invitations.issue";
5735
5991
  var ATTEMPTS2 = 3;
5736
5992
  async function issueInvitation(context, settings, invitations, input) {
5737
5993
  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);
5994
+ const scope = scopeOf(WHERE5, input?.scope);
5995
+ const email = emailOf2(WHERE5, input?.email);
5996
+ const name = nameOf(WHERE5, input?.name);
5997
+ const role = roleOf(WHERE5, input?.role);
5998
+ const locale = localeOf(WHERE5, input?.locale);
5999
+ const invitedBy = inviterOf(WHERE5, input?.invitedBy);
6000
+ const ref = refOf2(WHERE5, input?.ref);
6001
+ const type = issuedType(WHERE5, settings, input?.type);
5746
6002
  await checkRoom(context, settings, invitations, scope, email);
5747
6003
  const preexisting = await findPending(invitations, scope, email);
5748
6004
  const code = mintSecret();
@@ -5773,7 +6029,7 @@ async function issueInvitation(context, settings, invitations, input) {
5773
6029
  const pending = await invitations.countPendingInvitations(scope, clock.now());
5774
6030
  if (pending > settings.maxPending) {
5775
6031
  await withdraw(context, settings, invitations, record);
5776
- throw limitReached3(WHERE4, settings);
6032
+ throw limitReached4(WHERE5, settings);
5777
6033
  }
5778
6034
  }
5779
6035
  await emitInvitation(settings.events, "invitation.issued", record, createdAt);
@@ -5784,7 +6040,7 @@ async function checkTypeKept(settings, invitations, record) {
5784
6040
  return;
5785
6041
  const stored = await invitations.findInvitation(record.id);
5786
6042
  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`);
6043
+ 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
6044
  }
5789
6045
  }
5790
6046
  async function checkRoom(context, settings, invitations, scope, email) {
@@ -5796,7 +6052,7 @@ async function checkRoom(context, settings, invitations, scope, email) {
5796
6052
  return;
5797
6053
  const held = await findPending(invitations, scope, email);
5798
6054
  if (held === null || held.expiresAt.getTime() <= now.getTime()) {
5799
- throw limitReached3(WHERE4, settings);
6055
+ throw limitReached4(WHERE5, settings);
5800
6056
  }
5801
6057
  }
5802
6058
  async function insertInPlaceOfPending(context, settings, invitations, record, replaceable) {
@@ -5818,7 +6074,7 @@ async function insertInPlaceOfPending(context, settings, invitations, record, re
5818
6074
  continue;
5819
6075
  await emitInvitation(settings.events, "invitation.revoked", held, revokedAt);
5820
6076
  }
5821
- throw new StoreConflict2("pending", `${WHERE4}: another pending invitation holds this scope and address`, { operation: "insertInvitation" });
6077
+ throw new StoreConflict2("pending", `${WHERE5}: another pending invitation holds this scope and address`, { operation: "insertInvitation" });
5822
6078
  }
5823
6079
  async function withdraw(context, settings, invitations, record) {
5824
6080
  const revokedAt = context.clock.now();
@@ -5840,17 +6096,17 @@ async function withdraw(context, settings, invitations, record) {
5840
6096
  import { createHash as createHash3 } from "node:crypto";
5841
6097
 
5842
6098
  // src/auth/invitations/preview.ts
5843
- var WHERE5 = "invitations.preview";
6099
+ var WHERE6 = "invitations.preview";
5844
6100
  async function previewInvitation(invitations, clock, settings, invited, code) {
5845
6101
  if (!isCode(code))
5846
- throw invalidCode(WHERE5);
6102
+ throw invalidCode(WHERE6);
5847
6103
  const record = await invitations.findInvitationByCodeHash(hashSecret(code));
5848
6104
  const name = record === null ? null : configuredType(settings, record);
5849
6105
  if (record === null || name === null)
5850
- throw invalidCode(WHERE5);
6106
+ throw invalidCode(WHERE6);
5851
6107
  const refusal = refusalOf(clock, record);
5852
6108
  if (refusal !== null)
5853
- throw invalidCode(WHERE5, refusal);
6109
+ throw invalidCode(WHERE6, refusal);
5854
6110
  const { api, type } = invited(name);
5855
6111
  if (type.password === null)
5856
6112
  return toPreview(record, name, false);
@@ -5976,12 +6232,12 @@ function readApi2(invitations, clock, settings, invited) {
5976
6232
  }
5977
6233
 
5978
6234
  // src/auth/invitations/resend.ts
5979
- var WHERE6 = "invitations.resend";
6235
+ var WHERE7 = "invitations.resend";
5980
6236
  async function resendInvitation(context, settings, invitations, input) {
5981
6237
  const { clock } = context;
5982
6238
  const code = mintSecret();
5983
6239
  let lapsed = null;
5984
- const { record, now } = await changePending(invitations, clock, WHERE6, input, (at) => ({
6240
+ const { record, now } = await changePending(invitations, clock, WHERE7, input, (at) => ({
5985
6241
  codeHash: hashSecret(code),
5986
6242
  expiresAt: new Date(at.getTime() + settings.lifetimeMs),
5987
6243
  resentBy: input.by ?? null
@@ -5994,7 +6250,7 @@ async function resendInvitation(context, settings, invitations, input) {
5994
6250
  lapsed = found;
5995
6251
  const pending = await invitations.countPendingInvitations(found.scope, at);
5996
6252
  if (pending >= settings.maxPending)
5997
- throw limitReached3(WHERE6, settings);
6253
+ throw limitReached4(WHERE7, settings);
5998
6254
  });
5999
6255
  const revived = lapsed;
6000
6256
  if (revived !== null && settings.maxPending !== null) {
@@ -6006,7 +6262,7 @@ async function resendInvitation(context, settings, invitations, input) {
6006
6262
  expiresAt: revived.expiresAt,
6007
6263
  resentBy: revived.resentBy ?? null
6008
6264
  });
6009
- throw limitReached3(WHERE6, settings);
6265
+ throw limitReached4(WHERE7, settings);
6010
6266
  }
6011
6267
  }
6012
6268
  await emitInvitation(settings.events, "invitation.resent", record, now, input.by);
@@ -6606,36 +6862,36 @@ function stepUpOutcome(meta, identity, now, where) {
6606
6862
  }
6607
6863
 
6608
6864
  // src/auth/social/complete.ts
6609
- var WHERE7 = "social.complete";
6865
+ var WHERE8 = "social.complete";
6610
6866
  async function completeFlow(context, finishers, input, options) {
6611
6867
  if (!(input?.callback instanceof URLSearchParams)) {
6612
- throw new TypeError(`${WHERE7}: callback must be the URLSearchParams of the callback URL — new URL(request.url).searchParams`);
6868
+ throw new TypeError(`${WHERE8}: callback must be the URLSearchParams of the callback URL — new URL(request.url).searchParams`);
6613
6869
  }
6614
6870
  const { purpose } = input;
6615
6871
  if (purpose !== undefined && purpose !== "signIn" && purpose !== "link") {
6616
- throw new TypeError(`${WHERE7}: purpose must be 'signIn' or 'link' when given`);
6872
+ throw new TypeError(`${WHERE8}: purpose must be 'signIn' or 'link' when given`);
6617
6873
  }
6618
- const device = deviceHint(context, options, WHERE7);
6874
+ const device = deviceHint(context, options, WHERE8);
6619
6875
  const redeemed = await redeemFlow(context, {
6620
6876
  callback: input.callback,
6621
6877
  flow: input.flow,
6622
6878
  current: input.current ?? null,
6623
6879
  purpose
6624
- }, WHERE7);
6880
+ }, WHERE8);
6625
6881
  const { type, meta, values, provider: configured } = redeemed;
6626
6882
  const finish = finishers.get(type.name);
6627
6883
  if (finish === undefined) {
6628
- throw new TypeError(`${WHERE7}: the user type lost its social configuration`);
6884
+ throw new TypeError(`${WHERE8}: the user type lost its social configuration`);
6629
6885
  }
6630
6886
  if (meta.stepUp !== null && configured.supportsStepUp !== true) {
6631
- throw unsupportedStepUp(meta, WHERE7);
6887
+ throw unsupportedStepUp(meta, WHERE8);
6632
6888
  }
6633
6889
  const identity = checkIdentity(await callProvider(() => configured.exchange({
6634
6890
  callback: input.callback,
6635
6891
  ...values,
6636
6892
  stepUp: meta.stepUp
6637
- }), meta.provider, WHERE7, meta), meta.provider, WHERE7, meta);
6638
- const stepUp = stepUpOutcome(meta, identity, context.clock.now(), WHERE7);
6893
+ }), meta.provider, WHERE8, meta), meta.provider, WHERE8, meta);
6894
+ const stepUp = stepUpOutcome(meta, identity, context.clock.now(), WHERE8);
6639
6895
  const ending = {
6640
6896
  context,
6641
6897
  type,
@@ -6644,7 +6900,7 @@ async function completeFlow(context, finishers, input, options) {
6644
6900
  returnTo: meta.returnTo,
6645
6901
  stepUp,
6646
6902
  amr: federatedMethods(configured.federatedAmr, identity),
6647
- where: WHERE7
6903
+ where: WHERE8
6648
6904
  };
6649
6905
  return redeemed.userId === null ? signInAccount(ending, meta.provider, identity) : completeLink(ending, redeemed.userId, meta.provider, identity);
6650
6906
  }
@@ -6945,6 +7201,75 @@ function sealerFor(keys, purpose) {
6945
7201
  }
6946
7202
  };
6947
7203
  }
7204
+ // src/auth/signed-token.ts
7205
+ import { createHmac as createHmac3, timingSafeEqual as timingSafeEqual7 } from "node:crypto";
7206
+ var MAX_PURPOSE2 = 256;
7207
+ var MAX_TOKEN = 8192;
7208
+ function checkPurpose(purpose, where) {
7209
+ if (typeof purpose !== "string" || purpose === "" || purpose.length > MAX_PURPOSE2 || !isStorable(purpose)) {
7210
+ throw new TypeError(`${where}: purpose must be a well-formed string of 1 to ${MAX_PURPOSE2} characters`);
7211
+ }
7212
+ return `janus/signed-token/v1/${purpose}`;
7213
+ }
7214
+ function mac2(key, signed) {
7215
+ return createHmac3("sha256", key).update(signed).digest();
7216
+ }
7217
+ function signToken(keys, purpose, payload, options) {
7218
+ const named = checkPurpose(purpose, "signToken");
7219
+ const sealer = resolveSealer(keys, "signToken");
7220
+ const ttl = parseDuration(options.expiresIn, "signToken: expiresIn");
7221
+ const json = payload === undefined ? undefined : JSON.stringify({ d: payload });
7222
+ if (json === undefined) {
7223
+ throw new TypeError("signToken: the payload must be a JSON value");
7224
+ }
7225
+ const e = (options.clock ?? systemClock).now().getTime() + ttl;
7226
+ const body = Buffer.from(JSON.stringify({ e, d: payload })).toString("base64url");
7227
+ const head = `v1.${sealer.sealWith}.${body}`;
7228
+ const key = derivedKey(sealer, named);
7229
+ const token = `${head}.${mac2(key, head).toString("base64url")}`;
7230
+ if (token.length > MAX_TOKEN) {
7231
+ throw new TypeError("signToken: the token is over 8 KiB; keep the payload small");
7232
+ }
7233
+ return token;
7234
+ }
7235
+ function verifyToken(keys, purpose, token, options = {}) {
7236
+ const named = checkPurpose(purpose, "verifyToken");
7237
+ const sealer = resolveSealer(keys, "verifyToken");
7238
+ if (typeof token !== "string" || token.length > MAX_TOKEN)
7239
+ return null;
7240
+ const parts = token.split(".");
7241
+ const [version, keyId, body, sig] = parts;
7242
+ if (parts.length !== 4 || version !== "v1" || keyId === undefined || body === undefined || sig === undefined) {
7243
+ return null;
7244
+ }
7245
+ const key = derivedKey(sealer, named, keyId);
7246
+ if (key === undefined)
7247
+ return null;
7248
+ const expected = mac2(key, `v1.${keyId}.${body}`);
7249
+ const given = Buffer.from(sig, "base64url");
7250
+ if (given.toString("base64url") !== sig)
7251
+ return null;
7252
+ if (given.length !== expected.length || !timingSafeEqual7(given, expected)) {
7253
+ return null;
7254
+ }
7255
+ let parsed;
7256
+ try {
7257
+ parsed = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
7258
+ } catch {
7259
+ return null;
7260
+ }
7261
+ if (typeof parsed.e !== "number" || !Number.isFinite(parsed.e))
7262
+ return null;
7263
+ const now = (options.clock ?? systemClock).now().getTime();
7264
+ if (now >= parsed.e)
7265
+ return null;
7266
+ return {
7267
+ payload: parsed.d,
7268
+ expiresAt: new Date(parsed.e),
7269
+ keyId,
7270
+ needsResign: keyId !== sealer.sealWith
7271
+ };
7272
+ }
6948
7273
  // src/background/background.ts
6949
7274
  function background(log = (line) => console.error(line)) {
6950
7275
  const running = new Set;
@@ -6969,6 +7294,7 @@ export {
6969
7294
  AMR,
6970
7295
  ApiKeyInvalidError2 as ApiKeyInvalidError,
6971
7296
  ApiKeyLimitError2 as ApiKeyLimitError,
7297
+ ApiKeyRefusedError2 as ApiKeyRefusedError,
6972
7298
  AvatarIdInvalidError2 as AvatarIdInvalidError,
6973
7299
  CredentialError2 as CredentialError,
6974
7300
  CursorFilterMismatchError2 as CursorFilterMismatchError,
@@ -7032,10 +7358,12 @@ export {
7032
7358
  scryptHasher,
7033
7359
  sealerFor,
7034
7360
  setOf2 as setOf,
7361
+ signToken,
7035
7362
  statusOf2 as statusOf,
7036
7363
  subjectOf2 as subjectOf,
7037
- systemClock
7364
+ systemClock,
7365
+ verifyToken
7038
7366
  };
7039
7367
 
7040
- //# debugId=FF3059166E410A0064756E2164756E21
7368
+ //# debugId=C75BD80E375EBBE064756E2164756E21
7041
7369
  //# sourceMappingURL=index.js.map