@oatscenter/trellis 0.100.0-rc.53 → 0.100.0-rc.55

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 (81) hide show
  1. package/auth/authority.d.ts +14 -4
  2. package/auth/authority.js +50 -42
  3. package/auth/browser/oauth.d.ts +10 -2
  4. package/auth/browser/oauth.js +42 -10
  5. package/auth/browser/storage.d.ts +9 -1
  6. package/auth/browser/storage.js +14 -2
  7. package/auth/connection.js +25 -32
  8. package/auth/http_error.d.ts +9 -1
  9. package/auth/http_error.js +17 -3
  10. package/auth/message_digests.js +1 -0
  11. package/auth/protocol_wasm/client/trellis_protocol_wasm_bg.wasm +0 -0
  12. package/auth/protocol_wasm/provider/trellis_protocol_wasm_bg.wasm +0 -0
  13. package/auth/protocol_wasm.d.ts +3 -0
  14. package/backoff.d.ts +19 -0
  15. package/backoff.js +32 -0
  16. package/client_connect.d.ts +8 -1
  17. package/client_connect.js +28 -2
  18. package/device.d.ts +1 -1
  19. package/device.js +18 -4
  20. package/errors/ResourceExhaustedError.d.ts +61 -0
  21. package/errors/ResourceExhaustedError.js +109 -0
  22. package/errors/index.d.ts +1 -0
  23. package/errors/index.js +1 -0
  24. package/index.d.ts +1 -1
  25. package/internal_sdk/generated/_internal/evidence.js +4 -4
  26. package/internal_sdk/generated/apis/auth/mod.d.ts +112 -5
  27. package/internal_sdk/generated/apis/auth/mod.js +77 -1
  28. package/internal_sdk/generated/apis/health/mod.d.ts +3 -2
  29. package/internal_sdk/generated/apis/health/mod.js +1 -1
  30. package/internal_sdk/generated/apis/state/mod.d.ts +16 -3
  31. package/internal_sdk/generated/apis/state/mod.js +32 -1
  32. package/internal_sdk/generated/apps/cli/mod.d.ts +84 -4
  33. package/internal_sdk/generated/apps/cli/mod.js +41 -1
  34. package/internal_sdk/generated/apps/console/mod.d.ts +60 -6
  35. package/internal_sdk/generated/apps/console/mod.js +26 -0
  36. package/internal_sdk/generated/package.json +2 -2
  37. package/internal_sdk/generated/participants/eventsRuntime/mod.d.ts +5 -0
  38. package/internal_sdk/generated/participants/eventsRuntime/mod.js +5 -0
  39. package/internal_sdk/generated/participants/healthRuntime/mod.d.ts +3 -2
  40. package/internal_sdk/generated/participants/healthRuntime/mod.js +2 -2
  41. package/internal_sdk/generated/participants/jobsRuntime/mod.d.ts +5 -0
  42. package/internal_sdk/generated/participants/jobsRuntime/mod.js +5 -0
  43. package/internal_sdk/generated/participants/platform/mod.d.ts +55 -8
  44. package/internal_sdk/generated/participants/platform/mod.js +7 -2
  45. package/internal_sdk/generated/types/_internal/p0.d.ts +797 -0
  46. package/internal_sdk/generated/types/_internal/p0.js +236 -1
  47. package/internal_sdk/generated/types/index.d.ts +80 -0
  48. package/internal_sdk/generated/types/index.js +40 -0
  49. package/kv.d.ts +11 -2
  50. package/kv.js +12 -4
  51. package/live/client_open.js +5 -4
  52. package/native/oauth.d.ts +14 -7
  53. package/native/oauth.js +21 -17
  54. package/own_authority.d.ts +6 -1
  55. package/own_authority.js +26 -6
  56. package/package.json +2 -2
  57. package/service/config.d.ts +118 -11
  58. package/service/config.js +484 -48
  59. package/service/mod.d.ts +2 -2
  60. package/service/outbox_inbox.d.ts +2 -1
  61. package/service/runtime/core.js +44 -10
  62. package/service/runtime/enrollment.js +6 -8
  63. package/service/runtime/service.d.ts +5 -2
  64. package/service/runtime/service.js +63 -12
  65. package/session/durable_events.d.ts +2 -0
  66. package/session/durable_events.js +14 -7
  67. package/session/facades.d.ts +3 -3
  68. package/session/handler_errors.d.ts +34 -0
  69. package/session/handler_errors.js +83 -1
  70. package/session/helpers.d.ts +12 -0
  71. package/session/helpers.js +28 -0
  72. package/session/local_authorization.js +8 -0
  73. package/session/state.js +10 -2
  74. package/session.d.ts +14 -5
  75. package/session.js +200 -60
  76. package/store.d.ts +11 -2
  77. package/store.js +12 -2
  78. package/tasks.js +2 -1
  79. package/transport/generations.d.ts +1 -1
  80. package/webhooks.d.ts +42 -5
  81. package/webhooks.js +80 -3
@@ -88,12 +88,22 @@ export declare class SessionAuthorityOwner {
88
88
  get trustSnapshot(): RuntimeAuthorizationTrust;
89
89
  /** Obtain successor trust only from this owner's verified chain rooted at the exact retained credential pin. */
90
90
  trustForCredential(anchor: RuntimeAuthorizationTrust): RuntimeAuthorizationTrust;
91
- /** Attach read-only public material and one snapshot-and-update mirror for all logical sessions. */
91
+ /**
92
+ * Attach read-only public material and one snapshot-and-update mirror for all logical sessions.
93
+ *
94
+ * Resolves once material reads and issuer metadata use `nats`. The mirror
95
+ * then catches up in the background: `caughtUp` settles when its initial
96
+ * snapshot is applied, or rejects if the mirror fails first. Nothing waits
97
+ * for it: verification of other parties' messages uses the revocations
98
+ * observed so far, and own authority never depends on the mirror.
99
+ */
92
100
  attach(nats: NatsConnection, binding: AuthorityRegistryBinding, options?: {
93
101
  signal?: AbortSignal;
94
102
  timeoutMs?: number;
95
103
  inboxPrefix?: string;
96
- }): Promise<void>;
104
+ }): Promise<{
105
+ readonly caughtUp: Promise<void>;
106
+ }>;
97
107
  /** Verify an issuer-signed lookup reply against the actual pending ephemeral request. */
98
108
  verifyAdmissionContext(bytes: Uint8Array, request: AdmissionGet, subject: string, reply: string): Promise<AdmissionContext>;
99
109
  /** Clock and bounds shared by all request/event/provider verification. */
@@ -102,8 +112,8 @@ export declare class SessionAuthorityOwner {
102
112
  get ownDigest(): string | undefined;
103
113
  /** Whether a verified sticky retirement affects the installed own logical session, even while its live lease is unavailable. */
104
114
  get ownRevoked(): boolean;
105
- /** Loss of current revocation coverage requiring private snapshot recovery. */
106
- get coverageLost(): boolean;
115
+ /** The revocation mirror failed and needs reattaching; verification carries on with the revocations already observed. */
116
+ get mirrorFailed(): boolean;
107
117
  /** Verified retirement observed by the runtime's single mirror. */
108
118
  isRevoked(sessionId: string): boolean;
109
119
  /** Observe promotion and sticky lifecycle changes, without a per-context subscription. */
package/auth/authority.js CHANGED
@@ -211,7 +211,15 @@ export class SessionAuthorityOwner {
211
211
  rotationSequence: this.#rotationSequence.toString(),
212
212
  });
213
213
  }
214
- /** Attach read-only public material and one snapshot-and-update mirror for all logical sessions. */
214
+ /**
215
+ * Attach read-only public material and one snapshot-and-update mirror for all logical sessions.
216
+ *
217
+ * Resolves once material reads and issuer metadata use `nats`. The mirror
218
+ * then catches up in the background: `caughtUp` settles when its initial
219
+ * snapshot is applied, or rejects if the mirror fails first. Nothing waits
220
+ * for it: verification of other parties' messages uses the revocations
221
+ * observed so far, and own authority never depends on the mirror.
222
+ */
215
223
  async attach(nats, binding, options = {}) {
216
224
  if (this.#stopped)
217
225
  throw new Error("authority owner stopped");
@@ -227,8 +235,10 @@ export class SessionAuthorityOwner {
227
235
  inboxPrefix: options.inboxPrefix ?? "_INBOX",
228
236
  signal: options.signal,
229
237
  };
230
- if (!this.#mirrorCovered)
231
- this.#metadataTransport = metadataTransport;
238
+ // A new attachment serves metadata reads at once; the mirror it starts
239
+ // never gates them.
240
+ this.#metadataTransport = metadataTransport;
241
+ const bound = Promise.withResolvers();
232
242
  const ready = Promise.withResolvers();
233
243
  void ready.promise.catch(() => undefined);
234
244
  let watch;
@@ -248,7 +258,12 @@ export class SessionAuthorityOwner {
248
258
  if (ended)
249
259
  return;
250
260
  ended = true;
251
- if (promoted && epoch === this.#mirrorEpoch) {
261
+ // A failed candidate with no current mirror to fall back on also needs
262
+ // recovery, like a promoted mirror that failed.
263
+ if ((promoted && epoch === this.#mirrorEpoch) ||
264
+ (!promoted &&
265
+ this.#mirrorPreparationStop === abort &&
266
+ !this.#mirrorCovered)) {
252
267
  this.#mirrorCovered = false;
253
268
  this.#mirrorFailed = !transportLost && !nats.isClosed();
254
269
  for (const listener of this.#listeners) {
@@ -337,10 +352,10 @@ export class SessionAuthorityOwner {
337
352
  bindOnly: true,
338
353
  });
339
354
  check();
340
- if (!this.#mirrorCovered)
341
- this.#material = material;
355
+ this.#material = material;
342
356
  await this.#advanceTrust(BigInt(binding.rotationSequence));
343
357
  check();
358
+ bound.resolve();
344
359
  const inbox = createInbox(options.inboxPrefix);
345
360
  const prefix = `$KV.${binding.revocationBucket}.`;
346
361
  const stream = `KV_${binding.revocationBucket}`;
@@ -449,15 +464,20 @@ export class SessionAuthorityOwner {
449
464
  watch?.stop();
450
465
  throw error;
451
466
  });
452
- try {
453
- await Promise.race([setup, ready.promise]);
454
- check();
455
- }
456
- catch (error) {
457
- fail(error instanceof Error ? error : new Error(String(error)));
458
- watch?.stop();
459
- throw error;
460
- }
467
+ const caughtUp = (async () => {
468
+ try {
469
+ await Promise.race([setup, ready.promise]);
470
+ check();
471
+ }
472
+ catch (error) {
473
+ fail(error instanceof Error ? error : new Error(String(error)));
474
+ watch?.stop();
475
+ throw error;
476
+ }
477
+ })();
478
+ void caughtUp.catch(() => undefined);
479
+ await Promise.race([bound.promise, caughtUp]);
480
+ return { caughtUp };
461
481
  }
462
482
  /** Verify an issuer-signed lookup reply against the actual pending ephemeral request. */
463
483
  async verifyAdmissionContext(bytes, request, subject, reply) {
@@ -501,8 +521,8 @@ export class SessionAuthorityOwner {
501
521
  return (this.#own !== undefined &&
502
522
  this.isRevoked(this.#own.authority.authorizationSessionId));
503
523
  }
504
- /** Loss of current revocation coverage requiring private snapshot recovery. */
505
- get coverageLost() {
524
+ /** The revocation mirror failed and needs reattaching; verification carries on with the revocations already observed. */
525
+ get mirrorFailed() {
506
526
  return this.#mirrorFailed;
507
527
  }
508
528
  /** Verified retirement observed by the runtime's single mirror. */
@@ -523,7 +543,6 @@ export class SessionAuthorityOwner {
523
543
  /** Verify a private candidate; commit only at checked transport publication. */
524
544
  async prepareOwn(bytes, expected) {
525
545
  const epoch = ++this.#ownPreparationEpoch;
526
- const mirrorEpoch = this.#mirrorEpoch;
527
546
  const candidate = await this.#verify(bytes, "live");
528
547
  candidate.unpublished = true;
529
548
  try {
@@ -535,9 +554,7 @@ export class SessionAuthorityOwner {
535
554
  this.assertCurrent(candidate);
536
555
  let finished = false;
537
556
  const assertPreparedCurrent = () => {
538
- if (finished ||
539
- epoch !== this.#ownPreparationEpoch ||
540
- mirrorEpoch !== this.#mirrorEpoch)
557
+ if (finished || epoch !== this.#ownPreparationEpoch)
541
558
  throw new Error("own authority candidate superseded");
542
559
  this.assertCurrent(candidate);
543
560
  };
@@ -759,7 +776,7 @@ export class SessionAuthorityOwner {
759
776
  if (entry.digest !== event.authorityDigest)
760
777
  throw new Error("event authority digest mismatch");
761
778
  await this.authorize(entry, event.apiId, action, originalPublication !== null, {
762
- at: Math.floor(Date.parse(event.eventTime) / 1000),
779
+ at: event.issuedAt,
763
780
  ...(originalPublication
764
781
  ? {
765
782
  publishedAt: Math.floor(Date.parse(originalPublication.publishedAt) / 1000),
@@ -836,23 +853,19 @@ export class SessionAuthorityOwner {
836
853
  }
837
854
  }
838
855
  async #settleMirrorUpdates() {
839
- const epoch = this.#mirrorEpoch;
840
856
  let updates;
841
857
  do {
842
858
  updates = this.#mirrorUpdates;
843
859
  await updates;
844
- if (epoch !== this.#mirrorEpoch)
845
- throw new AuthorityUnavailableError("authority mirror superseded");
846
860
  } while (updates !== this.#mirrorUpdates);
847
- // This waits only for updates already received, never for lost coverage or
848
- // a replacement mirror. Callers still perform their normal live checks.
861
+ // This waits only for updates already received and being verified, never
862
+ // for a lost, lagging or replacement mirror. Callers then check what is
863
+ // known.
849
864
  }
850
865
  /** Recheck observed revocation and expiry after every cold asynchronous boundary. */
851
866
  assertCurrent(entry) {
852
867
  if (this.#stopped || this.#overloaded)
853
868
  throw new Error("authority owner unavailable");
854
- if (!this.#mirrorCovered)
855
- throw new AuthorityUnavailableError("revocation mirror is not current");
856
869
  const issuer = this.#liveIssuer(entry.authority.issuerKeyId);
857
870
  if (issuer?.state !== "active")
858
871
  throw new Error("issuer unavailable for live authority");
@@ -982,16 +995,13 @@ export class SessionAuthorityOwner {
982
995
  }
983
996
  /** Read public verification material using a fresh, pinned-issuer authenticated exchange. */
984
997
  async readIssuerMetadata(query) {
985
- return this.#readIssuerMetadata(query, true);
998
+ return this.#readIssuerMetadata(query);
986
999
  }
987
- async #readIssuerMetadata(query, requireCoverage) {
1000
+ async #readIssuerMetadata(query) {
988
1001
  const transport = this.#metadataTransport;
989
- const epoch = this.#mirrorEpoch;
990
1002
  const assertCurrent = () => {
991
1003
  if (!transport ||
992
1004
  this.#stopped ||
993
- (requireCoverage && !this.#mirrorCovered) ||
994
- this.#mirrorEpoch !== epoch ||
995
1005
  transport.nats.isClosed() ||
996
1006
  transport.nats.isDraining())
997
1007
  throw new Error("issuer metadata transport unavailable");
@@ -1043,9 +1053,7 @@ export class SessionAuthorityOwner {
1043
1053
  if (status.authorizationSessionId !== query.authorizationSessionId)
1044
1054
  throw new Error("issuer metadata status identity mismatch");
1045
1055
  if (status.revocation)
1046
- await this.observeRevocation(signedBytes(status.revocation), query.authorizationSessionId, () => epoch === this.#mirrorEpoch &&
1047
- this.#mirrorCovered &&
1048
- !this.#stopped);
1056
+ await this.observeRevocation(signedBytes(status.revocation), query.authorizationSessionId, () => !this.#stopped);
1049
1057
  assertCurrent();
1050
1058
  }
1051
1059
  return response;
@@ -1088,7 +1096,7 @@ export class SessionAuthorityOwner {
1088
1096
  continue;
1089
1097
  }
1090
1098
  // A failed read leaves the key to its signed deadline.
1091
- await this.#readIssuerMetadata({ kind: "issuerKey", keyId }, false).catch(() => undefined);
1099
+ await this.#readIssuerMetadata({ kind: "issuerKey", keyId }).catch(() => undefined);
1092
1100
  }
1093
1101
  }
1094
1102
  /**
@@ -1112,7 +1120,10 @@ export class SessionAuthorityOwner {
1112
1120
  if (!issuer && (await this.#forwardIssuer(keyId)))
1113
1121
  issuer = this.#liveIssuer(keyId);
1114
1122
  if (!issuer) {
1115
- const response = await this.#readIssuerMetadata({ kind: "issuerKey", keyId }, false);
1123
+ const response = await this.#readIssuerMetadata({
1124
+ kind: "issuerKey",
1125
+ keyId,
1126
+ });
1116
1127
  if (response.result.kind !== "value")
1117
1128
  throw new Error("historical authority issuer unavailable");
1118
1129
  issuer = this.#liveIssuer(keyId);
@@ -1210,7 +1221,6 @@ export class SessionAuthorityOwner {
1210
1221
  return value;
1211
1222
  }
1212
1223
  async #verify(bytes, purpose, historicalCutoff) {
1213
- const mirrorEpoch = this.#mirrorEpoch;
1214
1224
  const hints = this.#hints(bytes);
1215
1225
  if (typeof hints.issuerKeyId !== "string")
1216
1226
  throw new Error("missing issuer lookup identity");
@@ -1250,8 +1260,6 @@ export class SessionAuthorityOwner {
1250
1260
  try {
1251
1261
  if (purpose === "live") {
1252
1262
  await this.#settleMirrorUpdates();
1253
- if (mirrorEpoch !== this.#mirrorEpoch)
1254
- throw new Error("authority verification coverage superseded");
1255
1263
  this.assertCurrent(entry);
1256
1264
  }
1257
1265
  return entry;
@@ -79,12 +79,20 @@ export declare class BrowserOAuthClient {
79
79
  /**
80
80
  * Build a PKCE authorization URL and retain only this tab's continuation.
81
81
  * With `extendGrant`, approval widens that grant of this app instead of
82
- * creating another, so its live session gains what the user approves.
82
+ * creating another, so its live session gains what the user approves. With
83
+ * `askAgain`, the approval page also asks about choices the user declined
84
+ * before, which sign-in otherwise leaves declined without asking.
83
85
  */
84
86
  authorize(redirectUri: string, capabilities: BrowserCapabilityRequest, options?: {
85
87
  extendGrant?: string;
88
+ askAgain?: boolean;
86
89
  }): Promise<Result<string, AuthError>>;
87
- /** Consume this tab's exact callback once; install signed authority before remembering its grant. */
90
+ /**
91
+ * Consume this tab's exact callback once; install signed authority before
92
+ * remembering its grant. A callback for no sign-in this tab is waiting on,
93
+ * such as an old link opened again, fails with `OAuthCallbackNotPending`
94
+ * and leaves the tab's own continuation in place.
95
+ */
88
96
  complete(callback?: string): Promise<Result<{
89
97
  value: BrowserOAuthAdmission;
90
98
  refreshToken: string;
@@ -63,6 +63,9 @@ export class BrowserOAuthClient {
63
63
  #nonce;
64
64
  #runtime;
65
65
  #owner;
66
+ // The user this document signed in as. Another tab can rebind a lapsed
67
+ // stored session to someone else; this document never follows it.
68
+ #principal;
66
69
  // Discovery read while opening. The refresh a page load starts with
67
70
  // authenticates it instead of reading the same document again.
68
71
  #discovered;
@@ -158,7 +161,9 @@ export class BrowserOAuthClient {
158
161
  /**
159
162
  * Build a PKCE authorization URL and retain only this tab's continuation.
160
163
  * With `extendGrant`, approval widens that grant of this app instead of
161
- * creating another, so its live session gains what the user approves.
164
+ * creating another, so its live session gains what the user approves. With
165
+ * `askAgain`, the approval page also asks about choices the user declined
166
+ * before, which sign-in otherwise leaves declined without asking.
162
167
  */
163
168
  async authorize(redirectUri, capabilities, options = {}) {
164
169
  try {
@@ -200,6 +205,7 @@ export class BrowserOAuthClient {
200
205
  },
201
206
  ]),
202
207
  ...(options.extendGrant ? { trellis_grant: options.extendGrant } : {}),
208
+ ...(options.askAgain ? { prompt: "consent" } : {}),
203
209
  }).toString();
204
210
  return ok(url.href);
205
211
  }
@@ -207,17 +213,22 @@ export class BrowserOAuthClient {
207
213
  return err(new AuthError({ reason: "StorageUnavailable" }));
208
214
  }
209
215
  }
210
- /** Consume this tab's exact callback once; install signed authority before remembering its grant. */
216
+ /**
217
+ * Consume this tab's exact callback once; install signed authority before
218
+ * remembering its grant. A callback for no sign-in this tab is waiting on,
219
+ * such as an old link opened again, fails with `OAuthCallbackNotPending`
220
+ * and leaves the tab's own continuation in place.
221
+ */
211
222
  async complete(callback = location.href) {
212
223
  // A later refresh renews a session, perhaps after the signer changed, so
213
224
  // it discovers afresh.
214
225
  this.#discovered = undefined;
215
226
  try {
216
227
  const raw = sessionStorage.getItem(this.#pendingKey());
217
- if (!raw)
218
- return err(new AuthError({ reason: "OAuthRecoveryRequired" }));
219
- const pending = pendingSchema.parse(JSON.parse(raw));
220
228
  const url = new URL(callback);
229
+ const pending = raw ? pendingSchema.parse(JSON.parse(raw)) : undefined;
230
+ if (!pending || url.searchParams.get("state") !== pending.state)
231
+ return err(new AuthError({ reason: "OAuthCallbackNotPending" }));
221
232
  const redirect = new URL(pending.redirectUri);
222
233
  if (pending.issuer !== this.scope.issuer ||
223
234
  pending.clientId !== this.scope.clientId ||
@@ -374,12 +385,22 @@ export class BrowserOAuthClient {
374
385
  if (response.nonce)
375
386
  this.#nonce = response.nonce;
376
387
  // Neither unsigned NATS errors nor transient HTTP failures delete the durable grant/key.
377
- if (!response.ok)
388
+ if (!response.ok) {
389
+ const refused = z
390
+ .object({
391
+ error: z.string().optional(),
392
+ error_description: z.string().optional(),
393
+ })
394
+ .safeParse(response.data).data;
378
395
  return err(new AuthError({
396
+ // A server failure's description names its reference.
397
+ message: refused?.error_description,
398
+ context: { status: response.status, error: refused?.error },
379
399
  reason: response.status >= 500 || response.status === 429
380
400
  ? "OAuthUnavailable"
381
401
  : "OAuthRecoveryRequired",
382
402
  }));
403
+ }
383
404
  const token = tokenSchema.parse(response.data);
384
405
  if (form.get("grant_type") === "refresh_token") {
385
406
  const saved = await this.store.retainRotatedToken(token.refresh_token, form.get("refresh_token") ?? "");
@@ -403,6 +424,7 @@ export class BrowserOAuthClient {
403
424
  const body = verified.admission.credential;
404
425
  const jkt = await dpopThumbprint(publicJwk);
405
426
  const grant = this.store.grant;
427
+ const refresh = form.get("grant_type") === "refresh_token";
406
428
  if ((this.#owner &&
407
429
  this.#owner.trustSnapshot.issuer.keyId !== trust.issuer.keyId) ||
408
430
  body.runtimeId !== runtimeId ||
@@ -411,12 +433,22 @@ export class BrowserOAuthClient {
411
433
  body.binding.bindingKind !== "browser" ||
412
434
  body.binding.browserOrigin !== location.origin ||
413
435
  body.binding.browserOrigin !== this.scope.browserOrigin ||
414
- (grant &&
436
+ (this.#principal !== undefined &&
437
+ body.principalId !== this.#principal) ||
438
+ (refresh &&
439
+ grant &&
415
440
  (body.principalId !== grant.principalId ||
416
- (form.get("grant_type") === "refresh_token" &&
417
- (body.oauthGrantId !== grant.oauthGrantId ||
418
- body.loginSessionId !== grant.loginSessionId)))))
441
+ body.oauthGrantId !== grant.oauthGrantId ||
442
+ body.loginSessionId !== grant.loginSessionId)))
419
443
  return err(new AuthError({ reason: "OAuthRecoveryRequired" }));
444
+ // A new sign-in as someone else takes over a stored session only once
445
+ // that session can no longer renew; a live one stays its user's.
446
+ if (!refresh &&
447
+ grant &&
448
+ !this.store.lapsed &&
449
+ body.principalId !== grant.principalId)
450
+ return err(new AuthError({ reason: "OAuthAccountChanged" }));
451
+ this.#principal = body.principalId;
420
452
  return ok({
421
453
  value: {
422
454
  auth,
@@ -46,11 +46,19 @@ export declare class BrowserSessionStore {
46
46
  get trust(): RuntimeAuthorizationTrust;
47
47
  /** Grant identity already committed under the credential's durable key. */
48
48
  get grant(): Readonly<OAuthRecord["grant"]>;
49
+ /**
50
+ * Whether the stored session can no longer renew: its last refresh failed,
51
+ * or never answered, so its token is spent. Only a new sign-in restores it.
52
+ */
53
+ get lapsed(): boolean;
49
54
  /** Persist only a successor authenticated from this record's retained pin. */
50
55
  retainTrust(owner: SessionAuthorityOwner): Promise<void>;
51
56
  /** Decrypt this exact scope's refresh credential into transient SDK memory. */
52
57
  refreshToken(): Promise<Result<string | undefined, AuthError>>;
53
- /** Bind an unused credential handle to the verified user and initial family. */
58
+ /**
59
+ * Bind an unused or lapsed credential handle to the verified user and
60
+ * initial family. A handle whose session still renews stays its user's.
61
+ */
54
62
  rememberGrant(grant: BrowserOAuthGrant): Promise<Result<void, AuthError>>;
55
63
  /**
56
64
  * One cross-tab owner rereads, exchanges, and commits a refresh. Mark recovery
@@ -158,6 +158,13 @@ export class BrowserSessionStore {
158
158
  get grant() {
159
159
  return this.#record.grant && Object.freeze({ ...this.#record.grant });
160
160
  }
161
+ /**
162
+ * Whether the stored session can no longer renew: its last refresh failed,
163
+ * or never answered, so its token is spent. Only a new sign-in restores it.
164
+ */
165
+ get lapsed() {
166
+ return this.#record.recoveryRequired === true;
167
+ }
161
168
  /** Persist only a successor authenticated from this record's retained pin. */
162
169
  async retainTrust(owner) {
163
170
  const trust = SessionAuthorityOwner.prototype.trustForCredential.call(owner, this.trust);
@@ -244,7 +251,10 @@ export class BrowserSessionStore {
244
251
  return err(new AuthError({ reason: "StorageUnavailable" }));
245
252
  }
246
253
  }
247
- /** Bind an unused credential handle to the verified user and initial family. */
254
+ /**
255
+ * Bind an unused or lapsed credential handle to the verified user and
256
+ * initial family. A handle whose session still renews stays its user's.
257
+ */
248
258
  async rememberGrant(grant) {
249
259
  if (!grant.principalId ||
250
260
  !grant.oauthGrantId ||
@@ -256,7 +266,9 @@ export class BrowserSessionStore {
256
266
  return await navigator.locks.request(this.#scope, async () => {
257
267
  const current = await recordTransaction(this.#database, "readonly", (store) => requestValue(store.get(this.#scope)));
258
268
  if (!current ||
259
- (current.grant && current.grant.principalId !== grant.principalId)) {
269
+ (current.grant &&
270
+ !current.recoveryRequired &&
271
+ current.grant.principalId !== grant.principalId)) {
260
272
  return err(new AuthError({ reason: "Conflict" }));
261
273
  }
262
274
  this.#record = current;
@@ -9,6 +9,7 @@ import { base64urlDecode, base64urlEncode, sha256, utf8 } from "./utils.js";
9
9
  import { initializeProtocolWasm, signProvisionedAdmissionWasm, verifyOAuthAdmissionWasm, createSessionAuthorityHandleWasm, assertSessionAuthorityHandleCurrentWasm, transportAuthorizationDigestWasm, classifyTransportAuthorizationWasm, } from "./protocol_wasm.js";
10
10
  import { loadDefaultRuntimeTransport, } from "../runtime_transport.js";
11
11
  import { TransportGenerationManager, } from "../transport/generations.js";
12
+ import { Backoff } from "../backoff.js";
12
13
  /** Subjects on which Auth announces a new provider of an API the session calls. */
13
14
  const PROVIDERS_NOTICE_SUBJECT_PREFIX = "trellis.auth.providers.";
14
15
  const ISSUER_NOTICE_SUBJECT = "trellis.auth.issuers";
@@ -365,6 +366,9 @@ export async function connectAdmitted(options) {
365
366
  const value = candidates.get(generation.nc);
366
367
  if (!value)
367
368
  throw new Error("AdmissionUnavailable");
369
+ // The revocation mirror only informs verification of other parties'
370
+ // messages, so activation does not wait for its snapshot. A mirror that
371
+ // fails is recovered in the background.
368
372
  await owner.attach(generation.nc, registrySchema.parse(value.context.registry), { signal: options.signal, timeoutMs: options.timeout, inboxPrefix });
369
373
  if (!value.committed) {
370
374
  value.candidate?.dispose();
@@ -450,8 +454,8 @@ export async function connectAdmitted(options) {
450
454
  /** Revalidate current authority through the admitted runtime key without rotating OAuth custody or replacing an equal-policy attachment. */
451
455
  const refreshAuthority = () => {
452
456
  if (renewalTask) {
453
- // Coverage loss cancels the attempt, but broker-info requests can only be
454
- // bounded by their transport timeout. Join settlement, not its cancelled
457
+ // Transport loss cancels the attempt, but broker-info requests can only
458
+ // be bounded by their transport timeout. Join settlement, not its cancelled
455
459
  // result, before the single renewal owner starts another exchange.
456
460
  if (renewalAbort?.signal.aborted) {
457
461
  return renewalTask
@@ -644,14 +648,13 @@ export async function connectAdmitted(options) {
644
648
  options.signal?.removeEventListener("abort", abort);
645
649
  unsubscribeOwner();
646
650
  });
647
- const unsubscribeOwner = owner.subscribeChanges(() => {
651
+ const onOwnerChange = () => {
648
652
  if (manager.isClosed())
649
653
  return;
650
- if (owner.coverageLost) {
651
- if (renewalTimer !== undefined)
652
- clearTimeout(renewalTimer);
653
- renewalTimer = undefined;
654
- renewalAbort?.abort();
654
+ if (owner.mirrorFailed) {
655
+ // Reattach the mirror in the background. Nothing waits for it:
656
+ // renewal and application work carry on with the revocations
657
+ // observed so far.
655
658
  if (mirrorRecovery)
656
659
  return;
657
660
  const controller = new AbortController();
@@ -659,11 +662,9 @@ export async function connectAdmitted(options) {
659
662
  const signal = options.signal
660
663
  ? AbortSignal.any([options.signal, controller.signal])
661
664
  : controller.signal;
662
- // Private maintenance may retain the physically published attachment
663
- // while application authority stays fenced by the missing snapshot.
664
665
  void (async () => {
665
- let delay = 100;
666
- while (!signal.aborted && !manager.isClosed() && owner.coverageLost) {
666
+ const backoff = new Backoff(100, 5_000);
667
+ while (!signal.aborted && !manager.isClosed() && owner.mirrorFailed) {
667
668
  try {
668
669
  const lease = await manager.acquirePublishedAttachment();
669
670
  if (!lease)
@@ -672,44 +673,32 @@ export async function connectAdmitted(options) {
672
673
  const value = candidates.get(lease.nc);
673
674
  if (!value)
674
675
  return;
675
- await owner.attach(lease.nc, registrySchema.parse(value.context.registry), {
676
+ const { caughtUp } = await owner.attach(lease.nc, registrySchema.parse(value.context.registry), {
676
677
  signal,
677
678
  timeoutMs: options.timeout,
678
679
  inboxPrefix,
679
680
  });
681
+ await caughtUp;
680
682
  }
681
683
  finally {
682
684
  lease.release();
683
685
  }
684
- if (!signal.aborted) {
685
- if (installedAuthority &&
686
- installedAuthority.expiresAt <= options.auth.currentIat()) {
687
- // Snapshot recovery is not authority renewal. Admission is
688
- // proved by the retained runtime key, not the expired context.
689
- await refreshAuthority();
690
- }
691
- else {
692
- manager.authorizationPromoted();
693
- scheduleRenewal();
694
- }
695
- }
696
686
  }
697
687
  catch {
698
- // Failed preparation never restores coverage or clears cutoffs.
688
+ // A failed mirror never clears observed cutoffs.
699
689
  }
700
- if (!signal.aborted && owner.coverageLost) {
690
+ if (!signal.aborted && owner.mirrorFailed) {
701
691
  await new Promise((resolve) => {
702
692
  const done = () => {
703
693
  clearTimeout(timer);
704
694
  signal.removeEventListener("abort", done);
705
695
  resolve();
706
696
  };
707
- const timer = setTimeout(done, delay);
697
+ const timer = setTimeout(done, backoff.failed());
708
698
  signal.addEventListener("abort", done, { once: true });
709
699
  if (signal.aborted)
710
700
  done();
711
701
  });
712
- delay = Math.min(delay * 2, 5_000);
713
702
  }
714
703
  }
715
704
  })().finally(() => {
@@ -732,11 +721,15 @@ export async function connectAdmitted(options) {
732
721
  }
733
722
  }
734
723
  else {
735
- // An ordinary ordered mirror update can restore coverage without
736
- // renewal or transport adoption. Wake acquisitions fenced at ingress.
724
+ // Promotion, retirement or a rotation can change what own authority
725
+ // permits without a transport change.
737
726
  manager.applicationUsabilityChanged();
738
727
  }
739
- });
728
+ };
729
+ const unsubscribeOwner = owner.subscribeChanges(onOwnerChange);
730
+ // A mirror that already failed while connecting is recovered now.
731
+ if (owner.mirrorFailed)
732
+ onOwnerChange();
740
733
  return {
741
734
  manager,
742
735
  owner,
@@ -6,7 +6,15 @@ export declare class TrellisHttpError extends Error {
6
6
  readonly status: number;
7
7
  /** Exact machine-readable Trellis error code. */
8
8
  readonly code: string;
9
- constructor(status: number, code: string, message?: string);
9
+ /** For a server failure, the reference its line in the Trellis log has. */
10
+ readonly reference?: string;
11
+ /**
12
+ * @param status HTTP status returned by Trellis.
13
+ * @param code Machine-readable Trellis error code.
14
+ * @param message Optional detail from the envelope.
15
+ * @param reference The server failure's reference, ending the message.
16
+ */
17
+ constructor(status: number, code: string, message?: string, reference?: string);
10
18
  }
11
19
  /** Decode one authoritative Trellis HTTP error envelope. */
12
20
  export declare function decodeTrellisHttpError(response: Response): Promise<TrellisHttpError>;
@@ -6,17 +6,27 @@ export class TrellisHttpError extends Error {
6
6
  status;
7
7
  /** Exact machine-readable Trellis error code. */
8
8
  code;
9
- constructor(status, code, message) {
10
- super(`Trellis HTTP ${status}: ${code}${message ? `: ${message}` : ""}`);
9
+ /** For a server failure, the reference its line in the Trellis log has. */
10
+ reference;
11
+ /**
12
+ * @param status HTTP status returned by Trellis.
13
+ * @param code Machine-readable Trellis error code.
14
+ * @param message Optional detail from the envelope.
15
+ * @param reference The server failure's reference, ending the message.
16
+ */
17
+ constructor(status, code, message, reference) {
18
+ super(`Trellis HTTP ${status}: ${code}${message ? `: ${message}` : ""}${reference ? ` Reference: ${reference}` : ""}`);
11
19
  this.name = "TrellisHttpError";
12
20
  this.status = status;
13
21
  this.code = code;
22
+ this.reference = reference;
14
23
  }
15
24
  }
16
25
  /** Decode one authoritative Trellis HTTP error envelope. */
17
26
  export async function decodeTrellisHttpError(response) {
18
27
  let code = INVALID_HTTP_ERROR_ENVELOPE;
19
28
  let message;
29
+ let reference;
20
30
  try {
21
31
  const body = await response.json();
22
32
  if (typeof body === "object" &&
@@ -31,12 +41,16 @@ export async function decodeTrellisHttpError(response) {
31
41
  if ("message" in body.error && typeof body.error.message === "string") {
32
42
  message = body.error.message;
33
43
  }
44
+ if ("reference" in body.error &&
45
+ typeof body.error.reference === "string") {
46
+ reference = body.error.reference;
47
+ }
34
48
  }
35
49
  }
36
50
  catch {
37
51
  // The local code keeps malformed responses distinct from server error codes.
38
52
  }
39
- return new TrellisHttpError(response.status, code, message);
53
+ return new TrellisHttpError(response.status, code, message, reference);
40
54
  }
41
55
  /**
42
56
  * Authorization codes that report in-flight materialization rather than denial.
@@ -205,6 +205,7 @@ export async function sessionEventSigningDigest(event, payload) {
205
205
  encoder.encode(event.subject),
206
206
  encoder.encode(event.eventId),
207
207
  encoder.encode(event.eventTime),
208
+ i64(event.issuedAt, "issuedAt"),
208
209
  await sha256([payload]),
209
210
  ])),
210
211
  ]);