@oatscenter/trellis 0.100.0-rc.5 → 0.100.0-rc.50

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 (126) hide show
  1. package/README.md +17 -11
  2. package/auth/authority.d.ts +17 -0
  3. package/auth/authority.js +98 -15
  4. package/auth/browser/oauth.d.ts +17 -3
  5. package/auth/browser/oauth.js +73 -15
  6. package/auth/browser.d.ts +1 -0
  7. package/auth/browser.js +1 -0
  8. package/auth/connection.d.ts +4 -0
  9. package/auth/connection.js +128 -18
  10. package/auth/device_activation.d.ts +5 -0
  11. package/auth/device_activation.js +1 -1
  12. package/auth/issuer_trust.d.ts +2 -1
  13. package/auth/issuer_trust.js +24 -5
  14. package/auth/oauth_core.d.ts +15 -0
  15. package/auth/oauth_core.js +7 -2
  16. package/auth/protocol_wasm/client/trellis_protocol_wasm.d.ts +28 -24
  17. package/auth/protocol_wasm/client/trellis_protocol_wasm.js +557 -359
  18. package/auth/protocol_wasm/client/trellis_protocol_wasm_bg.wasm +0 -0
  19. package/auth/protocol_wasm/provider/trellis_protocol_wasm.d.ts +33 -29
  20. package/auth/protocol_wasm/provider/trellis_protocol_wasm.js +628 -407
  21. package/auth/protocol_wasm/provider/trellis_protocol_wasm_bg.wasm +0 -0
  22. package/auth/protocol_wasm.d.ts +17 -0
  23. package/auth/session_auth.d.ts +5 -0
  24. package/auth/session_auth.js +38 -2
  25. package/caller.d.ts +41 -8
  26. package/caller.js +68 -31
  27. package/client_connect.d.ts +55 -3
  28. package/client_connect.js +314 -15
  29. package/connection.d.ts +6 -1
  30. package/connection.js +2 -0
  31. package/data_plane/budget.js +1 -1
  32. package/device/activation.js +3 -0
  33. package/device.d.ts +4 -0
  34. package/device.js +32 -0
  35. package/generated.d.ts +1 -1
  36. package/generated_support.d.ts +41 -2
  37. package/generated_support.js +107 -36
  38. package/index.d.ts +1 -0
  39. package/internal_sdk/generated/_internal/evidence.d.ts +12 -0
  40. package/internal_sdk/generated/_internal/evidence.js +13 -0
  41. package/internal_sdk/generated/apis/auth/mod.d.ts +1330 -33
  42. package/internal_sdk/generated/apis/auth/mod.js +513 -70
  43. package/internal_sdk/generated/apis/core/mod.d.ts +40 -6
  44. package/internal_sdk/generated/apis/core/mod.js +38 -27
  45. package/internal_sdk/generated/apis/events/mod.d.ts +116 -17
  46. package/internal_sdk/generated/apis/events/mod.js +124 -78
  47. package/internal_sdk/generated/apis/health/mod.d.ts +78 -9
  48. package/internal_sdk/generated/apis/health/mod.js +66 -38
  49. package/internal_sdk/generated/apis/jobs/mod.d.ts +108 -8
  50. package/internal_sdk/generated/apis/jobs/mod.js +55 -37
  51. package/internal_sdk/generated/apis/state/mod.d.ts +51 -10
  52. package/internal_sdk/generated/apis/state/mod.js +74 -51
  53. package/internal_sdk/generated/apps/cli/mod.d.ts +1220 -18
  54. package/internal_sdk/generated/apps/cli/mod.js +199 -18
  55. package/internal_sdk/generated/apps/console/mod.d.ts +1427 -17
  56. package/internal_sdk/generated/apps/console/mod.js +197 -18
  57. package/internal_sdk/generated/package.json +63 -11
  58. package/internal_sdk/generated/participants/eventsRuntime/mod.d.ts +155 -3
  59. package/internal_sdk/generated/participants/eventsRuntime/mod.js +39 -15
  60. package/internal_sdk/generated/participants/healthRuntime/mod.d.ts +81 -1
  61. package/internal_sdk/generated/participants/healthRuntime/mod.js +7 -13
  62. package/internal_sdk/generated/participants/jobsRuntime/mod.d.ts +160 -2
  63. package/internal_sdk/generated/participants/jobsRuntime/mod.js +37 -13
  64. package/internal_sdk/generated/participants/platform/mod.d.ts +1198 -3
  65. package/internal_sdk/generated/participants/platform/mod.js +39 -15
  66. package/internal_sdk/generated/types/_internal/p0.d.ts +7604 -59
  67. package/internal_sdk/generated/types/_internal/p0.js +1689 -1064
  68. package/internal_sdk/generated/types/index.d.ts +182 -10
  69. package/internal_sdk/generated/types/index.js +91 -5
  70. package/kv.js +4 -4
  71. package/live/client_open.js +67 -24
  72. package/native/certificate_acceptance.d.ts +73 -0
  73. package/native/certificate_acceptance.js +344 -0
  74. package/native/connection.d.ts +5 -0
  75. package/native/connection.js +23 -1
  76. package/native/custody.d.ts +2 -0
  77. package/native/custody.js +47 -10
  78. package/native/discovery.d.ts +5 -0
  79. package/native/discovery.js +61 -21
  80. package/native/oauth.js +69 -28
  81. package/native.d.ts +1 -0
  82. package/native.js +1 -0
  83. package/operations.d.ts +4 -0
  84. package/own_authority.js +2 -2
  85. package/package.json +12 -10
  86. package/pagination.d.ts +1 -1
  87. package/pagination.js +1 -1
  88. package/participant_runtime/participant.d.ts +3 -1
  89. package/participant_runtime/participant.js +1 -0
  90. package/portable.d.ts +3 -1
  91. package/portable.js +1 -0
  92. package/provider.d.ts +10 -3
  93. package/provider.js +7 -0
  94. package/runtime_transport.js +18 -2
  95. package/service/config.d.ts +134 -0
  96. package/service/config.js +291 -0
  97. package/service/mod.d.ts +3 -1
  98. package/service/outbox_inbox.d.ts +2 -2
  99. package/service/outbox_inbox.js +2 -2
  100. package/service/runtime/core.js +52 -9
  101. package/service/runtime/internal_jobs/job-manager.d.ts +2 -0
  102. package/service/runtime/internal_jobs/job-manager.js +112 -67
  103. package/service/runtime/internal_jobs/key-coordinator.js +7 -6
  104. package/service/runtime/internal_jobs/runtime-worker.js +13 -1
  105. package/service/runtime/service.d.ts +20 -12
  106. package/service/runtime/service.js +203 -19
  107. package/service/runtime/transfer/queue.js +5 -5
  108. package/service/runtime/transfer.js +1 -1
  109. package/session/handler_errors.d.ts +7 -1
  110. package/session/handler_errors.js +13 -1
  111. package/session/local_authorization.js +45 -4
  112. package/session/operations.d.ts +5 -0
  113. package/session/state.d.ts +1 -1
  114. package/session/state.js +1 -1
  115. package/session/wire.d.ts +2 -0
  116. package/session/wire.js +21 -2
  117. package/session.d.ts +24 -3
  118. package/session.js +148 -33
  119. package/transfer/session.d.ts +4 -4
  120. package/transfer/session.js +6 -6
  121. package/transfer.d.ts +3 -3
  122. package/transfer.js +3 -3
  123. package/transport/generations.d.ts +23 -12
  124. package/transport/generations.js +71 -89
  125. package/values.d.ts +33 -0
  126. 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
@@ -29,6 +29,12 @@ export type PendingSessionRequest = {
29
29
  action: CatalogActionIdentity;
30
30
  expectedDeploymentId: string | null;
31
31
  };
32
+ /**
33
+ * Verification evidence that is only briefly unavailable, such as a revocation
34
+ * mirror catching up. A change notification from the owner may make it current.
35
+ */
36
+ export declare class AuthorityUnavailableError extends Error {
37
+ }
32
38
  /** Short-lived typed identity lease; cannot be constructed from unverified JSON. */
33
39
  export declare class VerifiedAuthority {
34
40
  #private;
@@ -160,6 +166,17 @@ export declare class SessionAuthorityOwner {
160
166
  stop(): void;
161
167
  /** Read public verification material using a fresh, pinned-issuer authenticated exchange. */
162
168
  readIssuerMetadata(query: IssuerMetadataQuery): Promise<IssuerMetadataResponse>;
169
+ /**
170
+ * Re-read each rotated-out key still inside its live overlap. Auth sends
171
+ * the issuer notice on revocation too, and a revoked key then stops
172
+ * authorizing live use at once instead of at its signed deadline.
173
+ */
174
+ recheckRetiringIssuers(): Promise<void>;
175
+ /**
176
+ * The issuer key with this id while it authorizes live use: the current key,
177
+ * or a rotated-out key inside its signed overlap that is not revoked.
178
+ */
179
+ liveIssuer(keyId: string): AuthorityIssuerKey | undefined;
163
180
  /** Authenticate one signed successor from this owner's existing durable pin. */
164
181
  acceptIssuerRotation(bytes: Uint8Array): Promise<void>;
165
182
  }
package/auth/authority.js CHANGED
@@ -7,6 +7,12 @@ import { payloadSha256 } from "./message_digests.js";
7
7
  import {} from "./utils.js";
8
8
  import { requestIssuerMetadata } from "./issuer_metadata.js";
9
9
  const authorityLeaseToken = Symbol("verified authority lease");
10
+ /**
11
+ * Verification evidence that is only briefly unavailable, such as a revocation
12
+ * mirror catching up. A change notification from the owner may make it current.
13
+ */
14
+ export class AuthorityUnavailableError extends Error {
15
+ }
10
16
  /** Short-lived typed identity lease; cannot be constructed from unverified JSON. */
11
17
  export class VerifiedAuthority {
12
18
  #owner;
@@ -44,6 +50,30 @@ export class VerifiedAuthority {
44
50
  /** Verified logical caller identity usable by all SDK adapters. */
45
51
  get caller() {
46
52
  const authority = this.#entry.authority;
53
+ // Auth signs the user's own profile into a user principal's authority.
54
+ const profile = authority.principalKind === "user"
55
+ ? authority.extensions["trellis.user.v1"]
56
+ : undefined;
57
+ const text = (value) => typeof value === "string" ? value : undefined;
58
+ const user = profile !== null &&
59
+ typeof profile === "object" &&
60
+ !Array.isArray(profile) &&
61
+ typeof profile.displayName === "string"
62
+ ? {
63
+ displayName: profile.displayName,
64
+ ...(text(profile.givenName) && {
65
+ givenName: text(profile.givenName),
66
+ }),
67
+ ...(text(profile.familyName) && {
68
+ familyName: text(profile.familyName),
69
+ }),
70
+ ...(text(profile.email) && { email: text(profile.email) }),
71
+ emailVerified: profile.emailVerified === true,
72
+ ...(text(profile.avatarUrl) && {
73
+ avatarUrl: text(profile.avatarUrl),
74
+ }),
75
+ }
76
+ : undefined;
47
77
  return {
48
78
  authorityDigest: this.digest,
49
79
  principalId: authority.principalId,
@@ -57,6 +87,7 @@ export class VerifiedAuthority {
57
87
  oauthGrantId: authority.oauthGrantId,
58
88
  capabilities: authority.capabilities,
59
89
  apis: authority.apis,
90
+ ...(user && { user }),
60
91
  };
61
92
  }
62
93
  /** Time and observed retirement are checked again immediately before authorized work. */
@@ -103,6 +134,7 @@ export class SessionAuthorityOwner {
103
134
  instanceId;
104
135
  account;
105
136
  #keys = new Map();
137
+ #liveUntil = new Map();
106
138
  #peers = new Map();
107
139
  #materials = new Map();
108
140
  #pending = new Map();
@@ -443,7 +475,7 @@ export class SessionAuthorityOwner {
443
475
  const issuer = await this.#issuer(keyId);
444
476
  const verified = await verifyAdmissionContextWasm(bytes, issuer, request, subject, reply, this.account, this.#now());
445
477
  if (this.#stopped ||
446
- this.#keys.get(issuer.keyId)?.state !== "active" ||
478
+ this.#liveIssuer(issuer.keyId)?.state !== "active" ||
447
479
  verified.expiresAt <= this.#now())
448
480
  throw new Error("Unavailable");
449
481
  return verified;
@@ -452,7 +484,9 @@ export class SessionAuthorityOwner {
452
484
  policy() {
453
485
  return {
454
486
  nowUnixSeconds: this.#now(),
455
- allowedClockSkewSeconds: 5,
487
+ // The Rust SDK accepts the same window, so a request that waited in a
488
+ // provider's queue or a resend is judged alike by either provider.
489
+ allowedClockSkewSeconds: 30,
456
490
  maximumAuthorityLifetimeSeconds: 300,
457
491
  maximumAuthorityBytes: 512 * 1024,
458
492
  maximumEntries: 4096,
@@ -555,8 +589,10 @@ export class SessionAuthorityOwner {
555
589
  }
556
590
  /** Borrow the current own authority, which peer-cache pressure can never evict. */
557
591
  own() {
558
- if (!this.#own || !this.#ownAvailable)
592
+ if (!this.#own)
559
593
  throw new Error("own authority unavailable");
594
+ if (!this.#ownAvailable)
595
+ throw new AuthorityUnavailableError("own authority unavailable");
560
596
  this.assertCurrent(this.#own);
561
597
  return VerifiedAuthority.acquire(authorityLeaseToken, this, this.#own);
562
598
  }
@@ -806,16 +842,18 @@ export class SessionAuthorityOwner {
806
842
  updates = this.#mirrorUpdates;
807
843
  await updates;
808
844
  if (epoch !== this.#mirrorEpoch)
809
- throw new Error("authority mirror superseded");
845
+ throw new AuthorityUnavailableError("authority mirror superseded");
810
846
  } while (updates !== this.#mirrorUpdates);
811
847
  // This waits only for updates already received, never for lost coverage or
812
848
  // a replacement mirror. Callers still perform their normal live checks.
813
849
  }
814
850
  /** Recheck observed revocation and expiry after every cold asynchronous boundary. */
815
851
  assertCurrent(entry) {
816
- if (this.#stopped || this.#overloaded || !this.#mirrorCovered)
852
+ if (this.#stopped || this.#overloaded)
817
853
  throw new Error("authority owner unavailable");
818
- const issuer = this.#keys.get(entry.authority.issuerKeyId);
854
+ if (!this.#mirrorCovered)
855
+ throw new AuthorityUnavailableError("revocation mirror is not current");
856
+ const issuer = this.#liveIssuer(entry.authority.issuerKeyId);
819
857
  if (issuer?.state !== "active")
820
858
  throw new Error("issuer unavailable for live authority");
821
859
  assertSessionAuthorityHandleCurrentWasm(entry.handle, this.policy(), this.#revocations.has(entry.authority.authorizationSessionId));
@@ -978,8 +1016,10 @@ export class SessionAuthorityOwner {
978
1016
  assertCurrent,
979
1017
  });
980
1018
  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);
1019
+ // The shared verifier checked the exact requested key, its non-live
1020
+ // state, and that only a retired key carries a live deadline.
1021
+ const answer = JSON.parse(response.result.payload);
1022
+ const historical = answer.key;
983
1023
  const previous = this.#keys.get(historical.keyId);
984
1024
  if (previous && previous.publicKey !== historical.publicKey)
985
1025
  throw new Error("historical issuer conflict");
@@ -987,8 +1027,15 @@ export class SessionAuthorityOwner {
987
1027
  throw new Error("historical issuer is a live pin");
988
1028
  if (!previous && this.#keys.size >= 128)
989
1029
  throw new Error("issuer history budget exceeded");
990
- if (previous?.state !== "revoked")
1030
+ if (previous?.state !== "revoked") {
991
1031
  this.#keys.set(historical.keyId, historical);
1032
+ // A key Auth reports inside its overlap is live until the signed
1033
+ // deadline, as if this owner had followed the chain.
1034
+ if (!previous &&
1035
+ answer.liveUntil !== undefined &&
1036
+ answer.liveUntil > this.#now())
1037
+ this.#liveUntil.set(historical.keyId, answer.liveUntil);
1038
+ }
992
1039
  }
993
1040
  if (query.kind === "authorityStatus" &&
994
1041
  response.result.kind === "value") {
@@ -1017,8 +1064,10 @@ export class SessionAuthorityOwner {
1017
1064
  };
1018
1065
  }
1019
1066
  async #read(kind, key) {
1020
- if (!this.#material || this.#stopped)
1067
+ if (this.#stopped)
1021
1068
  throw new Error("authority material unavailable");
1069
+ if (!this.#material)
1070
+ throw new AuthorityUnavailableError("authority material unavailable");
1022
1071
  if (!/^[A-Za-z0-9_-]{1,128}$/.test(key))
1023
1072
  throw new Error("invalid material lookup key");
1024
1073
  const prefix = kind === "authority" ? "context" : kind === "catalog" ? "api" : kind;
@@ -1027,16 +1076,46 @@ export class SessionAuthorityOwner {
1027
1076
  throw new Error("authority material unavailable");
1028
1077
  return entry.value;
1029
1078
  }
1030
- async #issuer(keyId) {
1031
- let issuer = this.#keys.get(keyId);
1032
- if (!issuer) {
1033
- issuer = await this.#forwardIssuer(keyId);
1079
+ /**
1080
+ * Re-read each rotated-out key still inside its live overlap. Auth sends
1081
+ * the issuer notice on revocation too, and a revoked key then stops
1082
+ * authorizing live use at once instead of at its signed deadline.
1083
+ */
1084
+ async recheckRetiringIssuers() {
1085
+ for (const [keyId, until] of this.#liveUntil) {
1086
+ if (until <= this.#now()) {
1087
+ this.#liveUntil.delete(keyId);
1088
+ continue;
1089
+ }
1090
+ // A failed read leaves the key to its signed deadline.
1091
+ await this.#readIssuerMetadata({ kind: "issuerKey", keyId }, false).catch(() => undefined);
1034
1092
  }
1093
+ }
1094
+ /**
1095
+ * The issuer key with this id while it authorizes live use: the current key,
1096
+ * or a rotated-out key inside its signed overlap that is not revoked.
1097
+ */
1098
+ liveIssuer(keyId) {
1099
+ const issuer = this.#liveIssuer(keyId);
1100
+ return issuer?.state === "active" ? issuer : undefined;
1101
+ }
1102
+ /** A rotated-out key stays live until its signed deadline, as in the Rust owner. */
1103
+ #liveIssuer(keyId) {
1104
+ const issuer = this.#keys.get(keyId);
1105
+ return issuer?.state === "retired" &&
1106
+ (this.#liveUntil.get(keyId) ?? 0) > this.#now()
1107
+ ? { ...issuer, state: "active" }
1108
+ : issuer;
1109
+ }
1110
+ async #issuer(keyId) {
1111
+ let issuer = this.#liveIssuer(keyId);
1112
+ if (!issuer && (await this.#forwardIssuer(keyId)))
1113
+ issuer = this.#liveIssuer(keyId);
1035
1114
  if (!issuer) {
1036
1115
  const response = await this.#readIssuerMetadata({ kind: "issuerKey", keyId }, false);
1037
1116
  if (response.result.kind !== "value")
1038
1117
  throw new Error("historical authority issuer unavailable");
1039
- issuer = this.#keys.get(keyId);
1118
+ issuer = this.#liveIssuer(keyId);
1040
1119
  }
1041
1120
  if (!issuer || issuer.state === "revoked")
1042
1121
  throw new Error("untrusted authority issuer");
@@ -1085,7 +1164,11 @@ export class SessionAuthorityOwner {
1085
1164
  const existing = this.#keys.get(verified.successor.keyId);
1086
1165
  if (existing)
1087
1166
  throw new Error("issuer rotation conflict");
1167
+ const retiredAt = verified.record.previousRetiredAt;
1168
+ if (typeof retiredAt !== "number")
1169
+ throw new Error("invalid rotation");
1088
1170
  this.#keys.set(previous.keyId, { ...previous, state: "retired" });
1171
+ this.#liveUntil.set(previous.keyId, retiredAt);
1089
1172
  this.#keys.set(verified.successor.keyId, verified.successor);
1090
1173
  this.#rotationSequence++;
1091
1174
  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. */
@@ -6,19 +6,21 @@ import { createAuth } from "../session_auth.js";
6
6
  import { base64urlEncode, sha256, utf8, toArrayBuffer } from "../utils.js";
7
7
  import { BrowserSessionStore } from "./storage.js";
8
8
  import {} from "../protocol_wasm.js";
9
- import { boundedJson, dpopThumbprint, postWithDpop, verifyAdmission, } from "../oauth_core.js";
9
+ import { boundedJson, dpopThumbprint, postWithDpop, usableNonce, verifyAdmission, } from "../oauth_core.js";
10
10
  import { SessionAuthorityOwner, } from "../authority.js";
11
11
  const metadataSchema = z.object({
12
12
  issuer: z.string().url(),
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
  });
@@ -59,33 +63,39 @@ export class BrowserOAuthClient {
59
63
  #nonce;
60
64
  #runtime;
61
65
  #owner;
62
- constructor(metadata, scope, store) {
66
+ // Discovery read while opening. The refresh a page load starts with
67
+ // authenticates it instead of reading the same document again.
68
+ #discovered;
69
+ constructor(metadata, scope, store, nonce) {
63
70
  this.metadata = metadata;
64
71
  this.scope = scope;
65
72
  this.store = store;
73
+ this.#nonce = nonce;
74
+ this.#discovered = { metadata, at: Date.now() };
66
75
  }
67
76
  /** Discover the selected issuer and reopen the exact app's credential custody. */
68
77
  static async open(options) {
69
78
  try {
70
79
  const issuer = new URL(options.issuer);
80
+ // Plain HTTP only reaches this machine, which browsers already trust.
71
81
  const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(issuer.hostname);
72
82
  if (issuer.username ||
73
83
  issuer.password ||
74
84
  issuer.hash ||
75
85
  issuer.search ||
76
- issuer.pathname !== "/" ||
77
86
  (issuer.protocol !== "https:" &&
78
- !(options.loopbackDevelopment &&
79
- loopback &&
80
- issuer.protocol === "http:")))
87
+ !(loopback && issuer.protocol === "http:")))
81
88
  return err(new AuthError({ reason: "InvalidIssuer" }));
82
- const response = await fetch(new URL("/.well-known/oauth-authorization-server", issuer), {
89
+ const response = await fetch(`${issuer.href.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`, {
83
90
  redirect: "error",
84
91
  credentials: "omit",
85
92
  signal: AbortSignal.timeout(30_000),
86
93
  });
87
94
  if (!response.ok)
88
95
  return err(new AuthError({ reason: "OAuthUnavailable" }));
96
+ // Discovery offers the token endpoint's current DPoP nonce, so the
97
+ // first token request needs no challenge and retry.
98
+ const nonce = usableNonce(response.headers.get("DPoP-Nonce"));
89
99
  const metadata = metadataSchema.parse(await boundedJson(response));
90
100
  if (new URL(metadata.issuer).href !== issuer.href ||
91
101
  !metadata.code_challenge_methods_supported.includes("S256") ||
@@ -93,6 +103,7 @@ export class BrowserOAuthClient {
93
103
  metadata.authorization_endpoint,
94
104
  metadata.token_endpoint,
95
105
  metadata.revocation_endpoint,
106
+ metadata.end_session_endpoint,
96
107
  ].some((endpoint) => new URL(endpoint).origin !== issuer.origin))
97
108
  return err(new AuthError({ reason: "InvalidIssuer" }));
98
109
  const scope = {
@@ -114,7 +125,7 @@ export class BrowserOAuthClient {
114
125
  })).take();
115
126
  if (isErr(opened))
116
127
  return err(opened.error);
117
- return ok(new BrowserOAuthClient(metadata, scope, opened));
128
+ return ok(new BrowserOAuthClient(metadata, scope, opened, nonce));
118
129
  }
119
130
  catch {
120
131
  return err(new AuthError({ reason: "OAuthUnavailable" }));
@@ -144,8 +155,12 @@ export class BrowserOAuthClient {
144
155
  }
145
156
  });
146
157
  }
147
- /** Build a PKCE authorization URL and retain only this tab's continuation. */
148
- async authorize(redirectUri, capabilities) {
158
+ /**
159
+ * Build a PKCE authorization URL and retain only this tab's continuation.
160
+ * With `extendGrant`, approval widens that grant of this app instead of
161
+ * creating another, so its live session gains what the user approves.
162
+ */
163
+ async authorize(redirectUri, capabilities, options = {}) {
149
164
  try {
150
165
  const redirect = new URL(redirectUri);
151
166
  if (redirect.origin !== location.origin ||
@@ -184,6 +199,7 @@ export class BrowserOAuthClient {
184
199
  optional: capabilities.optional,
185
200
  },
186
201
  ]),
202
+ ...(options.extendGrant ? { trellis_grant: options.extendGrant } : {}),
187
203
  }).toString();
188
204
  return ok(url.href);
189
205
  }
@@ -193,6 +209,9 @@ export class BrowserOAuthClient {
193
209
  }
194
210
  /** Consume this tab's exact callback once; install signed authority before remembering its grant. */
195
211
  async complete(callback = location.href) {
212
+ // A later refresh renews a session, perhaps after the signer changed, so
213
+ // it discovers afresh.
214
+ this.#discovered = undefined;
196
215
  try {
197
216
  const raw = sessionStorage.getItem(this.#pendingKey());
198
217
  if (!raw)
@@ -231,6 +250,32 @@ export class BrowserOAuthClient {
231
250
  return err(new AuthError({ reason: "OAuthRecoveryRequired" }));
232
251
  }
233
252
  }
253
+ /**
254
+ * Whether the user approved an extension whose callback reached another
255
+ * window, checked against this tab's continuation like {@link complete}.
256
+ * The code is not exchanged: the extended grant already holds the approval.
257
+ */
258
+ approvalOutcome(callback) {
259
+ try {
260
+ const raw = sessionStorage.getItem(this.#pendingKey());
261
+ if (!raw)
262
+ return err(new AuthError({ reason: "OAuthRecoveryRequired" }));
263
+ const pending = pendingSchema.parse(JSON.parse(raw));
264
+ const url = new URL(callback);
265
+ const redirect = new URL(pending.redirectUri);
266
+ if (Date.now() - pending.createdAt > 600_000 ||
267
+ url.origin !== redirect.origin ||
268
+ url.pathname !== redirect.pathname ||
269
+ url.searchParams.getAll("state").length !== 1 ||
270
+ url.searchParams.get("state") !== pending.state)
271
+ return err(new AuthError({ reason: "InvalidOAuthCallback" }));
272
+ sessionStorage.removeItem(this.#pendingKey());
273
+ return ok(url.searchParams.has("code") && !url.searchParams.has("error"));
274
+ }
275
+ catch {
276
+ return err(new AuthError({ reason: "InvalidOAuthCallback" }));
277
+ }
278
+ }
234
279
  /** Serialize refresh across tabs and atomically commit rotation; reload makes a fresh runtime key. */
235
280
  async resume(install) {
236
281
  if (!install && !this.#owner)
@@ -244,7 +289,21 @@ export class BrowserOAuthClient {
244
289
  else if (!this.#owner)
245
290
  throw new AuthError({ reason: "OAuthRecoveryRequired" });
246
291
  }, async () => {
247
- await this.#prepareTrust();
292
+ // Only a document read moments ago stands in for a fresh one, and
293
+ // only while it still authenticates: if the signer changed since,
294
+ // discovery is read again before anything is spent.
295
+ const discovered = this.#discovered;
296
+ this.#discovered = undefined;
297
+ if (discovered && Date.now() - discovered.at < 30_000) {
298
+ try {
299
+ await this.#prepareTrust(discovered.metadata);
300
+ return;
301
+ }
302
+ catch {
303
+ // Stale; fall through to a fresh read.
304
+ }
305
+ }
306
+ await this.#prepareTrust(undefined);
248
307
  });
249
308
  }
250
309
  /** Bind the authenticated connection to the retained credential trust root. */
@@ -257,7 +316,7 @@ export class BrowserOAuthClient {
257
316
  }
258
317
  async #prepareTrust(metadata) {
259
318
  if (!metadata) {
260
- const response = await fetch(new URL("/.well-known/oauth-authorization-server", this.scope.issuer), {
319
+ const response = await fetch(`${this.scope.issuer.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`, {
261
320
  redirect: "error",
262
321
  credentials: "omit",
263
322
  signal: AbortSignal.timeout(30000),
@@ -267,8 +326,7 @@ export class BrowserOAuthClient {
267
326
  metadata = metadataSchema.parse(await boundedJson(response));
268
327
  }
269
328
  const active = metadata.trellis.issuers.filter((key) => key.state === "active");
270
- if (new URL(metadata.issuer).origin !== this.scope.issuer ||
271
- active.length !== 1)
329
+ if (metadata.issuer !== this.scope.issuer || active.length !== 1)
272
330
  throw new AuthError({ reason: "OAuthTrustUnavailable" });
273
331
  const owner = await authenticateIssuerChain(this.scope.issuer, this.#owner?.trustSnapshot ?? this.store.trust, {
274
332
  instanceId: metadata.trellis.trellisInstanceId,
@@ -318,7 +376,7 @@ export class BrowserOAuthClient {
318
376
  // Neither unsigned NATS errors nor transient HTTP failures delete the durable grant/key.
319
377
  if (!response.ok)
320
378
  return err(new AuthError({
321
- reason: response.status >= 500
379
+ reason: response.status >= 500 || response.status === 429
322
380
  ? "OAuthUnavailable"
323
381
  : "OAuthRecoveryRequired",
324
382
  }));
package/auth/browser.d.ts CHANGED
@@ -8,4 +8,5 @@ export { BrowserOAuthClient, type BrowserOAuthAdmission, type BrowserOAuthMetada
8
8
  export { classifyBrowserAuthError, isRecoverableBrowserAuthError, } from "./browser_recovery.ts";
9
9
  export type { BrowserAuthRecoveryClassification, BrowserAuthRecoveryKind, } from "./browser_recovery.ts";
10
10
  export { decodeTrellisHttpError, TrellisHttpError } from "./http_error.ts";
11
+ export { publicKeyBase64urlFromSeed } from "./keys.ts";
11
12
  export { base64urlDecode, base64urlEncode, sha256, toArrayBuffer, utf8, } from "./utils.ts";
package/auth/browser.js CHANGED
@@ -7,4 +7,5 @@ export { BrowserSessionStore, } from "./browser/storage.js";
7
7
  export { BrowserOAuthClient, } from "./browser/oauth.js";
8
8
  export { classifyBrowserAuthError, isRecoverableBrowserAuthError, } from "./browser_recovery.js";
9
9
  export { decodeTrellisHttpError, TrellisHttpError } from "./http_error.js";
10
+ export { publicKeyBase64urlFromSeed } from "./keys.js";
10
11
  export { base64urlDecode, base64urlEncode, sha256, toArrayBuffer, utf8, } from "./utils.js";
@@ -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";