@oatscenter/trellis 0.100.0-rc.4 → 0.100.0-rc.41

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 (120) hide show
  1. package/README.md +17 -11
  2. package/auth/authority.d.ts +11 -0
  3. package/auth/authority.js +79 -10
  4. package/auth/browser/oauth.d.ts +17 -3
  5. package/auth/browser/oauth.js +44 -11
  6. package/auth/connection.d.ts +4 -0
  7. package/auth/connection.js +63 -3
  8. package/auth/device_activation.d.ts +5 -0
  9. package/auth/device_activation.js +1 -1
  10. package/auth/issuer_trust.d.ts +2 -1
  11. package/auth/issuer_trust.js +13 -4
  12. package/auth/oauth_core.d.ts +15 -0
  13. package/auth/oauth_core.js +7 -2
  14. package/auth/protocol_wasm/client/trellis_protocol_wasm.d.ts +28 -24
  15. package/auth/protocol_wasm/client/trellis_protocol_wasm.js +557 -359
  16. package/auth/protocol_wasm/client/trellis_protocol_wasm_bg.wasm +0 -0
  17. package/auth/protocol_wasm/provider/trellis_protocol_wasm.d.ts +33 -29
  18. package/auth/protocol_wasm/provider/trellis_protocol_wasm.js +628 -407
  19. package/auth/protocol_wasm/provider/trellis_protocol_wasm_bg.wasm +0 -0
  20. package/auth/protocol_wasm.d.ts +17 -0
  21. package/auth/session_auth.d.ts +5 -0
  22. package/auth/session_auth.js +1 -0
  23. package/caller.d.ts +26 -7
  24. package/caller.js +68 -31
  25. package/client_connect.d.ts +55 -3
  26. package/client_connect.js +298 -8
  27. package/connection.d.ts +6 -1
  28. package/connection.js +2 -0
  29. package/data_plane/budget.js +1 -1
  30. package/device/activation.js +3 -0
  31. package/device.d.ts +4 -0
  32. package/device.js +32 -0
  33. package/generated.d.ts +1 -1
  34. package/generated_support.d.ts +49 -2
  35. package/generated_support.js +70 -0
  36. package/index.d.ts +1 -0
  37. package/internal_sdk/generated/apis/auth/mod.d.ts +343 -32
  38. package/internal_sdk/generated/apis/auth/mod.js +441 -63
  39. package/internal_sdk/generated/apis/core/mod.d.ts +5 -5
  40. package/internal_sdk/generated/apis/core/mod.js +36 -20
  41. package/internal_sdk/generated/apis/events/mod.d.ts +20 -15
  42. package/internal_sdk/generated/apis/events/mod.js +121 -70
  43. package/internal_sdk/generated/apis/health/mod.d.ts +8 -7
  44. package/internal_sdk/generated/apis/health/mod.js +53 -30
  45. package/internal_sdk/generated/apis/jobs/mod.d.ts +8 -7
  46. package/internal_sdk/generated/apis/jobs/mod.js +53 -30
  47. package/internal_sdk/generated/apis/state/mod.d.ts +13 -9
  48. package/internal_sdk/generated/apis/state/mod.js +72 -44
  49. package/internal_sdk/generated/apps/cli/mod.d.ts +129 -18
  50. package/internal_sdk/generated/apps/cli/mod.js +169 -18
  51. package/internal_sdk/generated/apps/console/mod.d.ts +123 -17
  52. package/internal_sdk/generated/apps/console/mod.js +161 -18
  53. package/internal_sdk/generated/package.json +2 -2
  54. package/internal_sdk/generated/participants/eventsRuntime/mod.d.ts +32 -2
  55. package/internal_sdk/generated/participants/eventsRuntime/mod.js +33 -6
  56. package/internal_sdk/generated/participants/healthRuntime/mod.d.ts +4 -0
  57. package/internal_sdk/generated/participants/healthRuntime/mod.js +5 -4
  58. package/internal_sdk/generated/participants/jobsRuntime/mod.d.ts +32 -2
  59. package/internal_sdk/generated/participants/jobsRuntime/mod.js +33 -6
  60. package/internal_sdk/generated/participants/platform/mod.d.ts +33 -3
  61. package/internal_sdk/generated/participants/platform/mod.js +35 -8
  62. package/internal_sdk/generated/types/_internal/p0.d.ts +709 -58
  63. package/internal_sdk/generated/types/_internal/p0.js +919 -433
  64. package/internal_sdk/generated/types/index.d.ts +136 -10
  65. package/internal_sdk/generated/types/index.js +68 -5
  66. package/kv.js +4 -4
  67. package/live/client_open.js +30 -11
  68. package/native/certificate_acceptance.d.ts +73 -0
  69. package/native/certificate_acceptance.js +344 -0
  70. package/native/connection.d.ts +5 -0
  71. package/native/connection.js +18 -0
  72. package/native/custody.d.ts +2 -0
  73. package/native/custody.js +10 -1
  74. package/native/discovery.d.ts +5 -0
  75. package/native/discovery.js +61 -21
  76. package/native/oauth.js +56 -25
  77. package/native.d.ts +1 -0
  78. package/native.js +1 -0
  79. package/operations.d.ts +4 -0
  80. package/own_authority.js +2 -2
  81. package/package.json +4 -2
  82. package/pagination.d.ts +1 -1
  83. package/pagination.js +1 -1
  84. package/participant_runtime/participant.d.ts +3 -1
  85. package/participant_runtime/participant.js +1 -0
  86. package/portable.d.ts +3 -1
  87. package/portable.js +1 -0
  88. package/provider.d.ts +8 -1
  89. package/provider.js +7 -0
  90. package/runtime_transport.js +18 -2
  91. package/service/config.d.ts +129 -0
  92. package/service/config.js +247 -0
  93. package/service/mod.d.ts +3 -1
  94. package/service/outbox_inbox.d.ts +2 -2
  95. package/service/outbox_inbox.js +2 -2
  96. package/service/runtime/core.js +52 -9
  97. package/service/runtime/internal_jobs/job-manager.d.ts +2 -0
  98. package/service/runtime/internal_jobs/job-manager.js +112 -67
  99. package/service/runtime/internal_jobs/key-coordinator.js +7 -6
  100. package/service/runtime/internal_jobs/runtime-worker.js +13 -1
  101. package/service/runtime/service.d.ts +20 -12
  102. package/service/runtime/service.js +196 -19
  103. package/service/runtime/transfer/queue.js +5 -5
  104. package/service/runtime/transfer.js +1 -1
  105. package/session/handler_errors.d.ts +7 -1
  106. package/session/handler_errors.js +13 -1
  107. package/session/operations.d.ts +5 -0
  108. package/session/state.d.ts +1 -1
  109. package/session/state.js +1 -1
  110. package/session/wire.d.ts +2 -0
  111. package/session/wire.js +21 -2
  112. package/session.d.ts +23 -2
  113. package/session.js +95 -9
  114. package/transfer/session.d.ts +4 -4
  115. package/transfer/session.js +6 -6
  116. package/transfer.d.ts +3 -3
  117. package/transfer.js +3 -3
  118. package/transport/generations.js +13 -0
  119. package/values.d.ts +33 -0
  120. package/values.js +52 -0
package/README.md CHANGED
@@ -5,8 +5,8 @@ and runtime error types.
5
5
 
6
6
  The npm package contains ESM JavaScript and TypeScript declarations. Use
7
7
  `import`; CommonJS output and `require()` support have intentionally been
8
- removed. Node and Deno adapters remain available as ESM subpaths. JSR
9
- publication remains supported.
8
+ removed. Node and Deno adapters remain available as ESM subpaths. The package is
9
+ published to npm.
10
10
 
11
11
  For AI-agent context, start with the generated package `TRELLIS.md` files and
12
12
  the raw docs index:
@@ -16,24 +16,30 @@ the raw docs index:
16
16
 
17
17
  ```typescript
18
18
  import { TrellisClient } from "@oatscenter/trellis";
19
- import { participants } from "example-trellis";
19
+ import { apps } from "example-trellis";
20
20
 
21
21
  const client = await TrellisClient.connect({
22
22
  trellisUrl: "https://trellis.example.com",
23
- participant: participants.exampleApp.participant,
23
+ request: apps.ExampleApp.request,
24
+ auth: { clientId: "example-app", redirectTo: `${location.origin}/callback` },
24
25
  }).orThrow();
25
26
  ```
26
27
 
27
28
  The local package name comes from `trellis.toml`. Generation emits one ordinary
28
- ESM package with `apis` and `participants` namespaces, executable JavaScript and
29
- declarations, and the matching published runtime dependency. Commit that package
29
+ ESM package with `apis`, `apps`, and `participants` namespaces, executable
30
+ JavaScript and declarations, and the matching published runtime dependency. Apps
31
+ connect with their generated `apps.<App>.request`; services connect with
32
+ `TrellisService.connect({ participant: participants.<Service>.participant, ... })`. Commit that package
30
33
  when ordinary builds should not require the Trellis CLI or API cache.
31
34
 
32
- Connected API facades group actions by surface: `.rpc.<group>.<leaf>(input)`,
33
- `.event.<group>.<leaf>.listen(handler)` or `.publish(event)`,
34
- `.feed.<group>.<leaf>(input)`, and `.operation.<group>.<leaf>.start(input)`.
35
- Inspect generated declarations for the exact selected APIs and action names. Do
36
- not reconstruct transport subjects or use handwritten contract metadata.
35
+ Generated clients expose flat methods named after each action: an RPC `Get` is
36
+ `client.get(input)`, an operation `Reindex` is `client.reindex(input).start()`,
37
+ and a live observation `Watch` is `client.watch(input, { signal })`. Services
38
+ register RPC and operation handlers with `service.handleGet(...)` and
39
+ `service.handleReindex(...)`, publish events with `service.publishShipped(...)`,
40
+ and listen with `service.onShipped(...)`. Calls return `Result` values. Inspect
41
+ the generated declarations for the exact names. Do not reconstruct transport
42
+ subjects or use handwritten contract metadata.
37
43
 
38
44
  Prepared events support durable publish flows. `prepare(...)` returns a
39
45
  `PreparedTrellisEvent`; services can persist prepared events in SQL or NATS KV
@@ -160,6 +160,17 @@ export declare class SessionAuthorityOwner {
160
160
  stop(): void;
161
161
  /** Read public verification material using a fresh, pinned-issuer authenticated exchange. */
162
162
  readIssuerMetadata(query: IssuerMetadataQuery): Promise<IssuerMetadataResponse>;
163
+ /**
164
+ * Re-read each rotated-out key still inside its live overlap. Auth sends
165
+ * the issuer notice on revocation too, and a revoked key then stops
166
+ * authorizing live use at once instead of at its signed deadline.
167
+ */
168
+ recheckRetiringIssuers(): Promise<void>;
169
+ /**
170
+ * The issuer key with this id while it authorizes live use: the current key,
171
+ * or a rotated-out key inside its signed overlap that is not revoked.
172
+ */
173
+ liveIssuer(keyId: string): AuthorityIssuerKey | undefined;
163
174
  /** Authenticate one signed successor from this owner's existing durable pin. */
164
175
  acceptIssuerRotation(bytes: Uint8Array): Promise<void>;
165
176
  }
package/auth/authority.js CHANGED
@@ -44,6 +44,30 @@ export class VerifiedAuthority {
44
44
  /** Verified logical caller identity usable by all SDK adapters. */
45
45
  get caller() {
46
46
  const authority = this.#entry.authority;
47
+ // Auth signs the user's own profile into a user principal's authority.
48
+ const profile = authority.principalKind === "user"
49
+ ? authority.extensions["trellis.user.v1"]
50
+ : undefined;
51
+ const text = (value) => typeof value === "string" ? value : undefined;
52
+ const user = profile !== null &&
53
+ typeof profile === "object" &&
54
+ !Array.isArray(profile) &&
55
+ typeof profile.displayName === "string"
56
+ ? {
57
+ displayName: profile.displayName,
58
+ ...(text(profile.givenName) && {
59
+ givenName: text(profile.givenName),
60
+ }),
61
+ ...(text(profile.familyName) && {
62
+ familyName: text(profile.familyName),
63
+ }),
64
+ ...(text(profile.email) && { email: text(profile.email) }),
65
+ emailVerified: profile.emailVerified === true,
66
+ ...(text(profile.avatarUrl) && {
67
+ avatarUrl: text(profile.avatarUrl),
68
+ }),
69
+ }
70
+ : undefined;
47
71
  return {
48
72
  authorityDigest: this.digest,
49
73
  principalId: authority.principalId,
@@ -57,6 +81,7 @@ export class VerifiedAuthority {
57
81
  oauthGrantId: authority.oauthGrantId,
58
82
  capabilities: authority.capabilities,
59
83
  apis: authority.apis,
84
+ ...(user && { user }),
60
85
  };
61
86
  }
62
87
  /** Time and observed retirement are checked again immediately before authorized work. */
@@ -103,6 +128,7 @@ export class SessionAuthorityOwner {
103
128
  instanceId;
104
129
  account;
105
130
  #keys = new Map();
131
+ #liveUntil = new Map();
106
132
  #peers = new Map();
107
133
  #materials = new Map();
108
134
  #pending = new Map();
@@ -443,7 +469,7 @@ export class SessionAuthorityOwner {
443
469
  const issuer = await this.#issuer(keyId);
444
470
  const verified = await verifyAdmissionContextWasm(bytes, issuer, request, subject, reply, this.account, this.#now());
445
471
  if (this.#stopped ||
446
- this.#keys.get(issuer.keyId)?.state !== "active" ||
472
+ this.#liveIssuer(issuer.keyId)?.state !== "active" ||
447
473
  verified.expiresAt <= this.#now())
448
474
  throw new Error("Unavailable");
449
475
  return verified;
@@ -815,7 +841,7 @@ export class SessionAuthorityOwner {
815
841
  assertCurrent(entry) {
816
842
  if (this.#stopped || this.#overloaded || !this.#mirrorCovered)
817
843
  throw new Error("authority owner unavailable");
818
- const issuer = this.#keys.get(entry.authority.issuerKeyId);
844
+ const issuer = this.#liveIssuer(entry.authority.issuerKeyId);
819
845
  if (issuer?.state !== "active")
820
846
  throw new Error("issuer unavailable for live authority");
821
847
  assertSessionAuthorityHandleCurrentWasm(entry.handle, this.policy(), this.#revocations.has(entry.authority.authorizationSessionId));
@@ -978,8 +1004,10 @@ export class SessionAuthorityOwner {
978
1004
  assertCurrent,
979
1005
  });
980
1006
  if (query.kind === "issuerKey" && response.result.kind === "value") {
981
- // The shared verifier checked the exact requested key and non-live state.
982
- const historical = JSON.parse(response.result.payload);
1007
+ // The shared verifier checked the exact requested key, its non-live
1008
+ // state, and that only a retired key carries a live deadline.
1009
+ const answer = JSON.parse(response.result.payload);
1010
+ const historical = answer.key;
983
1011
  const previous = this.#keys.get(historical.keyId);
984
1012
  if (previous && previous.publicKey !== historical.publicKey)
985
1013
  throw new Error("historical issuer conflict");
@@ -987,8 +1015,15 @@ export class SessionAuthorityOwner {
987
1015
  throw new Error("historical issuer is a live pin");
988
1016
  if (!previous && this.#keys.size >= 128)
989
1017
  throw new Error("issuer history budget exceeded");
990
- if (previous?.state !== "revoked")
1018
+ if (previous?.state !== "revoked") {
991
1019
  this.#keys.set(historical.keyId, historical);
1020
+ // A key Auth reports inside its overlap is live until the signed
1021
+ // deadline, as if this owner had followed the chain.
1022
+ if (!previous &&
1023
+ answer.liveUntil !== undefined &&
1024
+ answer.liveUntil > this.#now())
1025
+ this.#liveUntil.set(historical.keyId, answer.liveUntil);
1026
+ }
992
1027
  }
993
1028
  if (query.kind === "authorityStatus" &&
994
1029
  response.result.kind === "value") {
@@ -1027,16 +1062,46 @@ export class SessionAuthorityOwner {
1027
1062
  throw new Error("authority material unavailable");
1028
1063
  return entry.value;
1029
1064
  }
1030
- async #issuer(keyId) {
1031
- let issuer = this.#keys.get(keyId);
1032
- if (!issuer) {
1033
- issuer = await this.#forwardIssuer(keyId);
1065
+ /**
1066
+ * Re-read each rotated-out key still inside its live overlap. Auth sends
1067
+ * the issuer notice on revocation too, and a revoked key then stops
1068
+ * authorizing live use at once instead of at its signed deadline.
1069
+ */
1070
+ async recheckRetiringIssuers() {
1071
+ for (const [keyId, until] of this.#liveUntil) {
1072
+ if (until <= this.#now()) {
1073
+ this.#liveUntil.delete(keyId);
1074
+ continue;
1075
+ }
1076
+ // A failed read leaves the key to its signed deadline.
1077
+ await this.#readIssuerMetadata({ kind: "issuerKey", keyId }, false).catch(() => undefined);
1034
1078
  }
1079
+ }
1080
+ /**
1081
+ * The issuer key with this id while it authorizes live use: the current key,
1082
+ * or a rotated-out key inside its signed overlap that is not revoked.
1083
+ */
1084
+ liveIssuer(keyId) {
1085
+ const issuer = this.#liveIssuer(keyId);
1086
+ return issuer?.state === "active" ? issuer : undefined;
1087
+ }
1088
+ /** A rotated-out key stays live until its signed deadline, as in the Rust owner. */
1089
+ #liveIssuer(keyId) {
1090
+ const issuer = this.#keys.get(keyId);
1091
+ return issuer?.state === "retired" &&
1092
+ (this.#liveUntil.get(keyId) ?? 0) > this.#now()
1093
+ ? { ...issuer, state: "active" }
1094
+ : issuer;
1095
+ }
1096
+ async #issuer(keyId) {
1097
+ let issuer = this.#liveIssuer(keyId);
1098
+ if (!issuer && (await this.#forwardIssuer(keyId)))
1099
+ issuer = this.#liveIssuer(keyId);
1035
1100
  if (!issuer) {
1036
1101
  const response = await this.#readIssuerMetadata({ kind: "issuerKey", keyId }, false);
1037
1102
  if (response.result.kind !== "value")
1038
1103
  throw new Error("historical authority issuer unavailable");
1039
- issuer = this.#keys.get(keyId);
1104
+ issuer = this.#liveIssuer(keyId);
1040
1105
  }
1041
1106
  if (!issuer || issuer.state === "revoked")
1042
1107
  throw new Error("untrusted authority issuer");
@@ -1085,7 +1150,11 @@ export class SessionAuthorityOwner {
1085
1150
  const existing = this.#keys.get(verified.successor.keyId);
1086
1151
  if (existing)
1087
1152
  throw new Error("issuer rotation conflict");
1153
+ const retiredAt = verified.record.previousRetiredAt;
1154
+ if (typeof retiredAt !== "number")
1155
+ throw new Error("invalid rotation");
1088
1156
  this.#keys.set(previous.keyId, { ...previous, state: "retired" });
1157
+ this.#liveUntil.set(previous.keyId, retiredAt);
1089
1158
  this.#keys.set(verified.successor.keyId, verified.successor);
1090
1159
  this.#rotationSequence++;
1091
1160
  this.#authenticatedIssuerSequences.set(verified.successor.keyId, this.#rotationSequence.toString());
@@ -10,12 +10,14 @@ declare const metadataSchema: z.ZodObject<{
10
10
  authorization_endpoint: z.ZodString;
11
11
  token_endpoint: z.ZodString;
12
12
  revocation_endpoint: z.ZodString;
13
+ end_session_endpoint: z.ZodString;
13
14
  code_challenge_methods_supported: z.ZodArray<z.ZodString>;
14
15
  trellis: z.ZodObject<{
15
16
  trellisInstanceId: z.ZodString;
16
17
  audienceNatsAccount: z.ZodString;
17
18
  rotationSequence: z.ZodString;
18
19
  natsEndpoints: z.ZodArray<z.ZodString>;
20
+ natsSentinel: z.ZodString;
19
21
  issuers: z.ZodArray<z.ZodObject<{
20
22
  keyId: z.ZodString;
21
23
  publicKey: z.ZodString;
@@ -37,6 +39,7 @@ declare const tokenSchema: z.ZodObject<{
37
39
  type: z.ZodLiteral<"trellis_capabilities">;
38
40
  required: z.ZodArray<z.ZodString>;
39
41
  optional: z.ZodArray<z.ZodString>;
42
+ requested_optional: z.ZodOptional<z.ZodArray<z.ZodString>>;
40
43
  }, z.core.$strip>>>;
41
44
  }, z.core.$strip>;
42
45
  /** HTTPS-authenticated discovery scoped to the user's selected server. */
@@ -70,17 +73,28 @@ export declare class BrowserOAuthClient {
70
73
  issuer: string;
71
74
  clientId: string;
72
75
  credentialHandle: string;
73
- loopbackDevelopment?: boolean;
74
76
  }): Promise<Result<BrowserOAuthClient, AuthError>>;
75
77
  /** Revoke this app's refresh family and clear custody; does not log out of the Portal. */
76
78
  revoke(): Promise<Result<void, AuthError>>;
77
- /** Build a PKCE authorization URL and retain only this tab's continuation. */
78
- authorize(redirectUri: string, capabilities: BrowserCapabilityRequest): Promise<Result<string, AuthError>>;
79
+ /**
80
+ * Build a PKCE authorization URL and retain only this tab's continuation.
81
+ * With `extendGrant`, approval widens that grant of this app instead of
82
+ * creating another, so its live session gains what the user approves.
83
+ */
84
+ authorize(redirectUri: string, capabilities: BrowserCapabilityRequest, options?: {
85
+ extendGrant?: string;
86
+ }): Promise<Result<string, AuthError>>;
79
87
  /** Consume this tab's exact callback once; install signed authority before remembering its grant. */
80
88
  complete(callback?: string): Promise<Result<{
81
89
  value: BrowserOAuthAdmission;
82
90
  refreshToken: string;
83
91
  }, AuthError>>;
92
+ /**
93
+ * Whether the user approved an extension whose callback reached another
94
+ * window, checked against this tab's continuation like {@link complete}.
95
+ * The code is not exchanged: the extended grant already holds the approval.
96
+ */
97
+ approvalOutcome(callback: string): Result<boolean, AuthError>;
84
98
  /** Serialize refresh across tabs and atomically commit rotation; reload makes a fresh runtime key. */
85
99
  resume(install?: (admission: BrowserOAuthAdmission) => Promise<void>): Promise<Result<BrowserOAuthAdmission, AuthError>>;
86
100
  /** Bind the authenticated connection to the retained credential trust root. */
@@ -13,12 +13,14 @@ const metadataSchema = z.object({
13
13
  authorization_endpoint: z.string().url(),
14
14
  token_endpoint: z.string().url(),
15
15
  revocation_endpoint: z.string().url(),
16
+ end_session_endpoint: z.string().url(),
16
17
  code_challenge_methods_supported: z.array(z.string()),
17
18
  trellis: z.object({
18
19
  trellisInstanceId: z.string().min(1),
19
20
  audienceNatsAccount: z.string().min(1),
20
21
  rotationSequence: z.string().regex(/^(0|[1-9][0-9]*)$/),
21
22
  natsEndpoints: z.array(z.string().min(1)).min(1),
23
+ natsSentinel: z.string().min(1),
22
24
  issuers: z
23
25
  .array(z.object({
24
26
  keyId: z.string().min(1),
@@ -39,6 +41,8 @@ const tokenSchema = z.object({
39
41
  type: z.literal("trellis_capabilities"),
40
42
  required: z.array(z.string()),
41
43
  optional: z.array(z.string()),
44
+ /** Every optional capability the grant asked for, declined ones too. */
45
+ requested_optional: z.array(z.string()).optional(),
42
46
  }))
43
47
  .optional(),
44
48
  });
@@ -68,18 +72,16 @@ export class BrowserOAuthClient {
68
72
  static async open(options) {
69
73
  try {
70
74
  const issuer = new URL(options.issuer);
75
+ // Plain HTTP only reaches this machine, which browsers already trust.
71
76
  const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(issuer.hostname);
72
77
  if (issuer.username ||
73
78
  issuer.password ||
74
79
  issuer.hash ||
75
80
  issuer.search ||
76
- issuer.pathname !== "/" ||
77
81
  (issuer.protocol !== "https:" &&
78
- !(options.loopbackDevelopment &&
79
- loopback &&
80
- issuer.protocol === "http:")))
82
+ !(loopback && issuer.protocol === "http:")))
81
83
  return err(new AuthError({ reason: "InvalidIssuer" }));
82
- const response = await fetch(new URL("/.well-known/oauth-authorization-server", issuer), {
84
+ const response = await fetch(`${issuer.href.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`, {
83
85
  redirect: "error",
84
86
  credentials: "omit",
85
87
  signal: AbortSignal.timeout(30_000),
@@ -93,6 +95,7 @@ export class BrowserOAuthClient {
93
95
  metadata.authorization_endpoint,
94
96
  metadata.token_endpoint,
95
97
  metadata.revocation_endpoint,
98
+ metadata.end_session_endpoint,
96
99
  ].some((endpoint) => new URL(endpoint).origin !== issuer.origin))
97
100
  return err(new AuthError({ reason: "InvalidIssuer" }));
98
101
  const scope = {
@@ -144,8 +147,12 @@ export class BrowserOAuthClient {
144
147
  }
145
148
  });
146
149
  }
147
- /** Build a PKCE authorization URL and retain only this tab's continuation. */
148
- async authorize(redirectUri, capabilities) {
150
+ /**
151
+ * Build a PKCE authorization URL and retain only this tab's continuation.
152
+ * With `extendGrant`, approval widens that grant of this app instead of
153
+ * creating another, so its live session gains what the user approves.
154
+ */
155
+ async authorize(redirectUri, capabilities, options = {}) {
149
156
  try {
150
157
  const redirect = new URL(redirectUri);
151
158
  if (redirect.origin !== location.origin ||
@@ -184,6 +191,7 @@ export class BrowserOAuthClient {
184
191
  optional: capabilities.optional,
185
192
  },
186
193
  ]),
194
+ ...(options.extendGrant ? { trellis_grant: options.extendGrant } : {}),
187
195
  }).toString();
188
196
  return ok(url.href);
189
197
  }
@@ -231,6 +239,32 @@ export class BrowserOAuthClient {
231
239
  return err(new AuthError({ reason: "OAuthRecoveryRequired" }));
232
240
  }
233
241
  }
242
+ /**
243
+ * Whether the user approved an extension whose callback reached another
244
+ * window, checked against this tab's continuation like {@link complete}.
245
+ * The code is not exchanged: the extended grant already holds the approval.
246
+ */
247
+ approvalOutcome(callback) {
248
+ try {
249
+ const raw = sessionStorage.getItem(this.#pendingKey());
250
+ if (!raw)
251
+ return err(new AuthError({ reason: "OAuthRecoveryRequired" }));
252
+ const pending = pendingSchema.parse(JSON.parse(raw));
253
+ const url = new URL(callback);
254
+ const redirect = new URL(pending.redirectUri);
255
+ if (Date.now() - pending.createdAt > 600_000 ||
256
+ url.origin !== redirect.origin ||
257
+ url.pathname !== redirect.pathname ||
258
+ url.searchParams.getAll("state").length !== 1 ||
259
+ url.searchParams.get("state") !== pending.state)
260
+ return err(new AuthError({ reason: "InvalidOAuthCallback" }));
261
+ sessionStorage.removeItem(this.#pendingKey());
262
+ return ok(url.searchParams.has("code") && !url.searchParams.has("error"));
263
+ }
264
+ catch {
265
+ return err(new AuthError({ reason: "InvalidOAuthCallback" }));
266
+ }
267
+ }
234
268
  /** Serialize refresh across tabs and atomically commit rotation; reload makes a fresh runtime key. */
235
269
  async resume(install) {
236
270
  if (!install && !this.#owner)
@@ -257,7 +291,7 @@ export class BrowserOAuthClient {
257
291
  }
258
292
  async #prepareTrust(metadata) {
259
293
  if (!metadata) {
260
- const response = await fetch(new URL("/.well-known/oauth-authorization-server", this.scope.issuer), {
294
+ const response = await fetch(`${this.scope.issuer.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`, {
261
295
  redirect: "error",
262
296
  credentials: "omit",
263
297
  signal: AbortSignal.timeout(30000),
@@ -267,8 +301,7 @@ export class BrowserOAuthClient {
267
301
  metadata = metadataSchema.parse(await boundedJson(response));
268
302
  }
269
303
  const active = metadata.trellis.issuers.filter((key) => key.state === "active");
270
- if (new URL(metadata.issuer).origin !== this.scope.issuer ||
271
- active.length !== 1)
304
+ if (metadata.issuer !== this.scope.issuer || active.length !== 1)
272
305
  throw new AuthError({ reason: "OAuthTrustUnavailable" });
273
306
  const owner = await authenticateIssuerChain(this.scope.issuer, this.#owner?.trustSnapshot ?? this.store.trust, {
274
307
  instanceId: metadata.trellis.trellisInstanceId,
@@ -318,7 +351,7 @@ export class BrowserOAuthClient {
318
351
  // Neither unsigned NATS errors nor transient HTTP failures delete the durable grant/key.
319
352
  if (!response.ok)
320
353
  return err(new AuthError({
321
- reason: response.status >= 500
354
+ reason: response.status >= 500 || response.status === 429
322
355
  ? "OAuthUnavailable"
323
356
  : "OAuthRecoveryRequired",
324
357
  }));
@@ -9,6 +9,8 @@ export type ProvisionedConnectionOptions = {
9
9
  trellisInstanceId: string;
10
10
  audienceNatsAccount: string;
11
11
  issuers: readonly AuthorityIssuerKey[];
12
+ /** Sentinel user JWT from the installation's metadata. */
13
+ natsSentinel: string;
12
14
  seed: string;
13
15
  timeout?: number;
14
16
  signal?: AbortSignal;
@@ -32,6 +34,8 @@ export declare function connectAdmitted(options: {
32
34
  audienceNatsAccount: string;
33
35
  issuers: readonly AuthorityIssuerKey[];
34
36
  rotationSequence?: string;
37
+ /** Sentinel user JWT from the installation's metadata. */
38
+ natsSentinel: string;
35
39
  auth: TrellisAuth;
36
40
  runtimeId: string;
37
41
  kind: "user" | "service" | "device";
@@ -8,6 +8,9 @@ import { base64urlDecode, base64urlEncode, sha256, utf8 } from "./utils.js";
8
8
  import { initializeProtocolWasm, signProvisionedAdmissionWasm, verifyOAuthAdmissionWasm, createSessionAuthorityHandleWasm, assertSessionAuthorityHandleCurrentWasm, transportAuthorizationDigestWasm, classifyTransportAuthorizationWasm, } from "./protocol_wasm.js";
9
9
  import { loadDefaultRuntimeTransport, } from "../runtime_transport.js";
10
10
  import { TransportGenerationManager, } from "../transport/generations.js";
11
+ /** Subjects on which Auth announces a new provider of an API the session calls. */
12
+ const PROVIDERS_NOTICE_SUBJECT_PREFIX = "trellis.auth.providers.";
13
+ const ISSUER_NOTICE_SUBJECT = "trellis.auth.issuers";
11
14
  const policySchema = z.object({
12
15
  format: z.literal("trellis.transport-authorization.v1"),
13
16
  account: z.string(),
@@ -87,8 +90,12 @@ export async function connectAdmitted(options) {
87
90
  let renewalTimer;
88
91
  let renewalAbort;
89
92
  let renewalTask;
93
+ // Set by a notice that arrives while a renewal is in flight: that renewal
94
+ // may already hold Auth's answer from before the change it announces.
95
+ let renewalNoticed = false;
90
96
  let mirrorRecovery;
91
97
  const credentials = new WeakMap();
98
+ const noticed = new WeakSet();
92
99
  const preparedCredentials = new WeakMap();
93
100
  const pendingAdmissions = new WeakMap();
94
101
  const candidates = new WeakMap();
@@ -157,10 +164,16 @@ export async function connectAdmitted(options) {
157
164
  registry.admittedTransportAuthorization.account !==
158
165
  options.audienceNatsAccount)
159
166
  throw new Error("AdmissionAttachmentMismatch");
167
+ // Verify against the key that signed this answer. A rotation during the
168
+ // renewal moves the owner's pin on, but that key stays live through its
169
+ // overlap, and the issuer notice renews again under the new one.
170
+ const issuer = owner.liveIssuer(context.issuerKeyId);
171
+ if (!issuer)
172
+ throw new Error("AdmissionSuperseded");
160
173
  const verified = await createSessionAuthorityHandleWasm({
161
174
  authorityBytes: utf8(context.sessionAuthority),
162
175
  verification: {
163
- issuer: owner.trustSnapshot.issuer,
176
+ issuer,
164
177
  trellisInstanceId: options.trellisInstanceId,
165
178
  audienceNatsAccount: options.audienceNatsAccount,
166
179
  policy: owner.policy(),
@@ -198,7 +211,7 @@ export async function connectAdmitted(options) {
198
211
  owner.ownDigest !== originalDigest ||
199
212
  signal?.aborted ||
200
213
  nc.isClosed() ||
201
- owner.trustSnapshot.issuer.keyId !== authority.issuerKeyId)
214
+ !owner.liveIssuer(authority.issuerKeyId))
202
215
  throw new Error("AdmissionSuperseded");
203
216
  assertSessionAuthorityHandleCurrentWasm(verified.handle, owner.policy(), owner.isRevoked(authority.authorizationSessionId));
204
217
  const value = candidates.get(nc);
@@ -261,6 +274,7 @@ export async function connectAdmitted(options) {
261
274
  const connect = await options.auth.natsConnectOptions({
262
275
  inboxPrefix,
263
276
  admission,
277
+ natsSentinel: options.natsSentinel,
264
278
  });
265
279
  const prepared = {
266
280
  policy,
@@ -336,6 +350,33 @@ export async function connectAdmitted(options) {
336
350
  const value = candidates.get(generation.nc);
337
351
  if (!value)
338
352
  throw new Error("AdmissionUnavailable");
353
+ if (!noticed.has(generation.nc)) {
354
+ noticed.add(generation.nc);
355
+ // Routes name the providers that existed at admission. Auth announces
356
+ // one added since, and renewing adopts the route to it at once. Auth
357
+ // also announces an issuer key rotation or revocation: renewing moves
358
+ // this session onto authority the current key signed, and the re-check
359
+ // ends a revoked key's overlap.
360
+ for (const subject of value.admission.policy.subscribeAllow) {
361
+ if (!subject.startsWith(PROVIDERS_NOTICE_SUBJECT_PREFIX) &&
362
+ subject !== ISSUER_NOTICE_SUBJECT)
363
+ continue;
364
+ generation.nc.subscribe(subject, {
365
+ callback: (error) => {
366
+ if (error || manager.isClosed())
367
+ return;
368
+ if (renewalTask)
369
+ renewalNoticed = true;
370
+ else
371
+ void refreshAuthority().catch(() => {
372
+ /* typed failure is retained by closed() */
373
+ });
374
+ if (subject === ISSUER_NOTICE_SUBJECT)
375
+ void owner.recheckRetiringIssuers();
376
+ },
377
+ });
378
+ }
379
+ }
339
380
  if (value.committed)
340
381
  return;
341
382
  if (!value.candidate)
@@ -392,6 +433,9 @@ export async function connectAdmitted(options) {
392
433
  const signal = options.signal
393
434
  ? AbortSignal.any([options.signal, renewalAbort.signal])
394
435
  : renewalAbort.signal;
436
+ // Set when the attachment this renewal leased closed under it: ordinary
437
+ // transport recovery then owns readmission, and this failure ends nothing.
438
+ let withdrawn = false;
395
439
  const task = (async () => {
396
440
  // A reduction can withdraw the attachment while the existing admission
397
441
  // pipeline is preparing its replacement. Explicit renewal must join that
@@ -450,13 +494,18 @@ export async function connectAdmitted(options) {
450
494
  manager.authorizationPromoted();
451
495
  scheduleRenewal();
452
496
  }
497
+ catch (error) {
498
+ if (lease.nc.isClosed())
499
+ withdrawn = true;
500
+ throw error;
501
+ }
453
502
  finally {
454
503
  lease.release();
455
504
  }
456
505
  })();
457
506
  renewalTask = task
458
507
  .catch(async (error) => {
459
- if (!signal.aborted && !manager.isClosed()) {
508
+ if (!signal.aborted && !manager.isClosed() && !withdrawn) {
460
509
  await manager.terminate(error instanceof AuthError || error instanceof TransportError
461
510
  ? error
462
511
  : new TransportError({
@@ -473,6 +522,16 @@ export async function connectAdmitted(options) {
473
522
  renewalTask = undefined;
474
523
  renewalAbort = undefined;
475
524
  }
525
+ // One trailing renewal covers every notice received meanwhile.
526
+ if (renewalNoticed &&
527
+ !renewalTask &&
528
+ !manager.isClosed() &&
529
+ !options.signal?.aborted) {
530
+ renewalNoticed = false;
531
+ void refreshAuthority().catch(() => {
532
+ /* typed failure is retained by closed() */
533
+ });
534
+ }
476
535
  });
477
536
  return renewalTask;
478
537
  };
@@ -484,6 +543,7 @@ export async function connectAdmitted(options) {
484
543
  const authOptions = await options.auth.natsConnectOptions({
485
544
  inboxPrefix,
486
545
  admission: credential,
546
+ natsSentinel: options.natsSentinel,
487
547
  });
488
548
  nc = await transport.connect({
489
549
  servers: options.servers,
@@ -2,6 +2,7 @@ import type { StaticDecode } from "typebox";
2
2
  import { Type } from "typebox";
3
3
  import type { GeneratedParticipant } from "../participant_runtime/participant.ts";
4
4
  import { createAuth } from "./session_auth.ts";
5
+ import type { HttpFetch } from "./oauth_core.ts";
5
6
  export declare const DeviceActivationPayloadSchema: Type.TObject<{
6
7
  v: Type.TLiteral<1>;
7
8
  publicIdentityKey: Type.TString;
@@ -51,6 +52,8 @@ export declare function verifyDeviceConfirmationCode(input: {
51
52
  /** Submit one proof-bound device enrollment request. */
52
53
  export declare function requestDeviceEnrollment(args: {
53
54
  trellisUrl: string;
55
+ /** Defaults to `fetch`. */
56
+ fetch?: HttpFetch;
54
57
  publicIdentityKey: string;
55
58
  identitySeed: Uint8Array | string;
56
59
  sessionIdentity: Awaited<ReturnType<typeof createAuth>>;
@@ -73,6 +76,8 @@ export declare function requestDeviceEnrollment(args: {
73
76
  */
74
77
  export declare function waitForDeviceActivation(args: {
75
78
  trellisUrl: string;
79
+ /** Defaults to `fetch`. */
80
+ fetch?: HttpFetch;
76
81
  publicIdentityKey: string;
77
82
  identitySeed: Uint8Array | string;
78
83
  activationKey: Uint8Array | string;
@@ -198,7 +198,7 @@ export async function requestDeviceEnrollment(args) {
198
198
  provisioningSecret: args.provisioningSecret,
199
199
  }),
200
200
  };
201
- const response = await fetch(new URL("/auth/device/enroll", args.trellisUrl), {
201
+ const response = await (args.fetch ?? fetch)(new URL("/auth/device/enroll", args.trellisUrl), {
202
202
  method: "POST",
203
203
  signal: args.signal,
204
204
  headers: { "Content-Type": "application/json" },
@@ -1,3 +1,4 @@
1
+ import type { HttpFetch } from "./oauth_core.ts";
1
2
  import { SessionAuthorityOwner, type RuntimeAuthorizationTrust } from "./authority.ts";
2
3
  /** Authenticate a discovery hint from the credential's existing pin, without consuming OAuth credentials. */
3
- export declare function authenticateIssuerChain(origin: string, anchor: RuntimeAuthorizationTrust, target: RuntimeAuthorizationTrust, signal?: AbortSignal, existingOwner?: SessionAuthorityOwner): Promise<SessionAuthorityOwner>;
4
+ export declare function authenticateIssuerChain(issuer: string, anchor: RuntimeAuthorizationTrust, target: RuntimeAuthorizationTrust, signal?: AbortSignal, existingOwner?: SessionAuthorityOwner, request?: HttpFetch): Promise<SessionAuthorityOwner>;