@oatscenter/trellis 0.100.0-rc.3 → 0.100.0-rc.30

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 (156) hide show
  1. package/README.md +17 -11
  2. package/auth/authority.js +62 -23
  3. package/auth/authorization/transport_state.d.ts +0 -80
  4. package/auth/authorization/transport_state.js +0 -136
  5. package/auth/browser/oauth.d.ts +20 -31
  6. package/auth/browser/oauth.js +124 -195
  7. package/auth/connection.d.ts +4 -0
  8. package/auth/connection.js +11 -1
  9. package/auth/device_activation.d.ts +5 -0
  10. package/auth/device_activation.js +1 -1
  11. package/auth/issuer_trust.d.ts +2 -1
  12. package/auth/issuer_trust.js +6 -8
  13. package/auth/message_digests.d.ts +36 -0
  14. package/auth/message_digests.js +236 -0
  15. package/auth/oauth_core.d.ts +73 -0
  16. package/auth/oauth_core.js +128 -0
  17. package/auth/proof.js +5 -4
  18. package/auth/protocol_wasm/client/trellis_protocol_wasm.d.ts +404 -0
  19. package/auth/protocol_wasm/client/trellis_protocol_wasm.js +2152 -0
  20. package/auth/protocol_wasm/client/trellis_protocol_wasm_bg.wasm +0 -0
  21. package/auth/protocol_wasm/{trellis_protocol_wasm.d.ts → provider/trellis_protocol_wasm.d.ts} +156 -114
  22. package/auth/protocol_wasm/provider/trellis_protocol_wasm.js +2441 -0
  23. package/auth/protocol_wasm/provider/trellis_protocol_wasm_bg.wasm +0 -0
  24. package/auth/protocol_wasm.d.ts +124 -31
  25. package/auth/protocol_wasm.js +176 -73
  26. package/auth/protocol_wasm_provider.d.ts +1 -0
  27. package/auth/protocol_wasm_provider.js +11 -0
  28. package/auth/session_auth.d.ts +5 -0
  29. package/auth/session_auth.js +2 -1
  30. package/auth/session_proof.js +5 -7
  31. package/caller.d.ts +26 -7
  32. package/caller.js +76 -32
  33. package/client_connect.d.ts +52 -6
  34. package/client_connect.js +296 -11
  35. package/connection.d.ts +6 -3
  36. package/connection.js +2 -6
  37. package/data_plane/budget.d.ts +16 -0
  38. package/data_plane/budget.js +36 -0
  39. package/device/activation.js +3 -0
  40. package/device.d.ts +1 -0
  41. package/device.js +14 -19
  42. package/errors/index.js +1 -1
  43. package/generated.d.ts +1 -1
  44. package/generated_support.d.ts +28 -2
  45. package/generated_support.js +64 -1
  46. package/internal_sdk/generated/apis/auth/mod.d.ts +193 -94
  47. package/internal_sdk/generated/apis/auth/mod.js +256 -123
  48. package/internal_sdk/generated/apis/core/mod.d.ts +6 -6
  49. package/internal_sdk/generated/apis/core/mod.js +37 -21
  50. package/internal_sdk/generated/apis/events/mod.d.ts +21 -16
  51. package/internal_sdk/generated/apis/events/mod.js +122 -71
  52. package/internal_sdk/generated/apis/health/mod.d.ts +9 -8
  53. package/internal_sdk/generated/apis/health/mod.js +54 -31
  54. package/internal_sdk/generated/apis/jobs/mod.d.ts +9 -8
  55. package/internal_sdk/generated/apis/jobs/mod.js +54 -31
  56. package/internal_sdk/generated/apis/state/mod.d.ts +14 -10
  57. package/internal_sdk/generated/apis/state/mod.js +73 -45
  58. package/internal_sdk/generated/apps/cli/mod.d.ts +165 -120
  59. package/internal_sdk/generated/apps/cli/mod.js +223 -273
  60. package/internal_sdk/generated/apps/console/mod.d.ts +193 -148
  61. package/internal_sdk/generated/apps/console/mod.js +294 -344
  62. package/internal_sdk/generated/package.json +2 -2
  63. package/internal_sdk/generated/participants/eventsRuntime/mod.d.ts +18 -10
  64. package/internal_sdk/generated/participants/eventsRuntime/mod.js +24 -16
  65. package/internal_sdk/generated/participants/healthRuntime/mod.d.ts +1 -1
  66. package/internal_sdk/generated/participants/healthRuntime/mod.js +6 -6
  67. package/internal_sdk/generated/participants/jobsRuntime/mod.d.ts +18 -10
  68. package/internal_sdk/generated/participants/jobsRuntime/mod.js +24 -16
  69. package/internal_sdk/generated/participants/platform/mod.d.ts +18 -10
  70. package/internal_sdk/generated/participants/platform/mod.js +23 -15
  71. package/internal_sdk/generated/types/_internal/p0.d.ts +3730 -3539
  72. package/internal_sdk/generated/types/_internal/p0.js +1891 -1640
  73. package/internal_sdk/generated/types/index.d.ts +996 -940
  74. package/internal_sdk/generated/types/index.js +498 -470
  75. package/live/client_open.js +10 -7
  76. package/live/protocol.d.ts +2 -1
  77. package/live/protocol.js +2 -1
  78. package/live/provider.js +6 -2
  79. package/live/telemetry.d.ts +1 -1
  80. package/live/telemetry.js +2 -1
  81. package/native/certificate_acceptance.d.ts +73 -0
  82. package/native/certificate_acceptance.js +344 -0
  83. package/native/connection.d.ts +2 -0
  84. package/native/connection.js +6 -0
  85. package/native/custody.d.ts +2 -0
  86. package/native/custody.js +10 -1
  87. package/native/discovery.d.ts +5 -1
  88. package/native/discovery.js +64 -47
  89. package/native/oauth.d.ts +6 -6
  90. package/native/oauth.js +126 -128
  91. package/native.d.ts +1 -1
  92. package/native.js +1 -0
  93. package/operations.d.ts +3 -4
  94. package/operations.js +0 -3
  95. package/own_authority.d.ts +0 -1
  96. package/own_authority.js +0 -1
  97. package/package.json +4 -2
  98. package/participant_runtime/api.d.ts +2 -6
  99. package/participant_runtime/participant.d.ts +3 -0
  100. package/participant_runtime/participant.js +9 -1
  101. package/portable.d.ts +3 -1
  102. package/portable.js +1 -0
  103. package/runtime_transport.js +18 -2
  104. package/service/mod.d.ts +2 -1
  105. package/service/runtime/core.d.ts +8 -5
  106. package/service/runtime/core.js +105 -88
  107. package/service/runtime/internal_jobs/key-coordinator.js +7 -6
  108. package/service/runtime/service.d.ts +18 -12
  109. package/service/runtime/service.js +144 -22
  110. package/service/runtime/transfer/queue.js +12 -1
  111. package/service/runtime/transfer.d.ts +33 -5
  112. package/service/runtime/transfer.js +333 -89
  113. package/session/contract_types.d.ts +201 -0
  114. package/session/contract_types.js +7 -0
  115. package/session/durable_events.d.ts +63 -0
  116. package/session/durable_events.js +561 -0
  117. package/session/events.d.ts +77 -0
  118. package/session/events.js +54 -0
  119. package/session/facades.d.ts +133 -0
  120. package/session/facades.js +50 -0
  121. package/session/handler_errors.d.ts +32 -0
  122. package/session/handler_errors.js +64 -0
  123. package/session/helpers.d.ts +20 -0
  124. package/session/helpers.js +71 -0
  125. package/session/local_authorization.d.ts +61 -0
  126. package/session/local_authorization.js +156 -0
  127. package/session/operations.d.ts +270 -0
  128. package/session/operations.js +75 -0
  129. package/session/state.d.ts +120 -0
  130. package/session/state.js +333 -0
  131. package/session/types.d.ts +168 -0
  132. package/session/types.js +13 -0
  133. package/session/wire.d.ts +67 -0
  134. package/session/wire.js +244 -0
  135. package/session.d.ts +38 -861
  136. package/session.js +104 -1535
  137. package/sha256.d.ts +9 -0
  138. package/sha256.js +33 -0
  139. package/store.js +7 -1
  140. package/store_reader.js +40 -40
  141. package/telemetry/metrics.d.ts +2 -2
  142. package/telemetry/metrics.js +3 -0
  143. package/transfer/frames.d.ts +11 -0
  144. package/transfer/frames.js +156 -0
  145. package/transfer/session.d.ts +8 -0
  146. package/transfer/session.js +38 -7
  147. package/transfer.d.ts +18 -9
  148. package/transfer.js +127 -107
  149. package/transport/generations.d.ts +2 -40
  150. package/transport/generations.js +35 -331
  151. package/values.d.ts +33 -0
  152. package/values.js +52 -0
  153. package/auth/protocol_wasm/trellis_protocol_wasm.js +0 -1750
  154. package/auth/protocol_wasm/trellis_protocol_wasm_bg.wasm +0 -0
  155. package/auth/protocol_wasm/trellis_protocol_wasm_bytes.d.ts +0 -1
  156. package/auth/protocol_wasm/trellis_protocol_wasm_bytes.js +0 -2
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
package/auth/authority.js CHANGED
@@ -2,9 +2,9 @@ import { Kvm } from "@nats-io/kv";
2
2
  import { createInbox } from "@nats-io/nats-core";
3
3
  import { QueuedIteratorImpl } from "@nats-io/nats-core/internal";
4
4
  import { AckPolicy, DeliverPolicy, jetstream, } from "@nats-io/jetstream";
5
- import { assertSessionAuthorityHandleCurrentWasm, verifyAdmissionContextWasm, authorizeCatalogActionWasm, createSessionAuthorityHandleWasm, verifyAuthorityMetadataWasm, verifySessionEventWasm, verifySessionRequestWasm, verifySessionResponseWasm, } from "./protocol_wasm.js";
5
+ import { assertSessionAuthorityHandleCurrentWasm, verifyAdmissionContextWasm, authenticateCatalogWasm, authenticateProviderCertificateWasm, authorizeCatalogActionWasm, authorizeProviderEventPublicationWasm, createSessionAuthorityHandleWasm, verifyAuthorityMetadataWasm, verifySessionEventWasm, verifySessionRequestWasm, verifySessionResponseWasm, authorizationSessionStatusSchema, signedBytes, } from "./protocol_wasm.js";
6
+ import { payloadSha256 } from "./message_digests.js";
6
7
  import {} from "./utils.js";
7
- import { AuthAuthorityStatusResponseCodec } from "../internal_sdk/generated/types/_internal/p0.js";
8
8
  import { requestIssuerMetadata } from "./issuer_metadata.js";
9
9
  const authorityLeaseToken = Symbol("verified authority lease");
10
10
  /** Short-lived typed identity lease; cannot be constructed from unverified JSON. */
@@ -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,7 +81,7 @@ export class VerifiedAuthority {
57
81
  oauthGrantId: authority.oauthGrantId,
58
82
  capabilities: authority.capabilities,
59
83
  apis: authority.apis,
60
- platformPrivileges: authority.platformPrivileges,
84
+ ...(user && { user }),
61
85
  };
62
86
  }
63
87
  /** Time and observed retirement are checked again immediately before authorized work. */
@@ -624,7 +648,7 @@ export class SessionAuthorityOwner {
624
648
  const verified = await verifySessionRequestWasm({
625
649
  authorityHandle: entry.handle,
626
650
  request,
627
- payload,
651
+ payloadSha256: await payloadSha256(payload),
628
652
  proof,
629
653
  policy: this.policy(),
630
654
  knownRevoked: this.#revocations.has(entry.authority.authorizationSessionId),
@@ -649,9 +673,9 @@ export class SessionAuthorityOwner {
649
673
  const verified = await verifySessionResponseWasm({
650
674
  providerHandle: provider.entry(authorityLeaseToken).handle,
651
675
  response,
652
- payload,
676
+ payloadSha256: await payloadSha256(payload),
653
677
  proof,
654
- certificate: certificate.record,
678
+ certificate: certificate.handle,
655
679
  certificateIssuer: issuer,
656
680
  pendingRequest: pending.request,
657
681
  pendingRequestDigest: pending.proofDigest,
@@ -700,11 +724,11 @@ export class SessionAuthorityOwner {
700
724
  });
701
725
  if (metadata.result.kind !== "value")
702
726
  throw new Error("historical revocation resolution unavailable");
703
- const status = AuthAuthorityStatusResponseCodec.decode(JSON.parse(metadata.result.payload));
727
+ const status = authorizationSessionStatusSchema.parse(JSON.parse(metadata.result.payload));
704
728
  if (status.authorizationSessionId !== hints.authorizationSessionId)
705
729
  throw new Error("historical status mismatch");
706
730
  if (status.revocation) {
707
- const revocation = await this.#verifyMetadata("revocation", status.revocation);
731
+ const revocation = await this.#verifyMetadata("revocation", signedBytes(status.revocation));
708
732
  if (revocation.record.authorizationSessionId !==
709
733
  hints.authorizationSessionId ||
710
734
  typeof revocation.record.effectiveCutoff !== "number")
@@ -734,7 +758,7 @@ export class SessionAuthorityOwner {
734
758
  const verified = await verifySessionEventWasm({
735
759
  authorityHandle: entry.handle,
736
760
  event,
737
- payload,
761
+ payloadSha256: await payloadSha256(payload),
738
762
  proof,
739
763
  policy: this.policy(),
740
764
  originalPublication,
@@ -835,7 +859,7 @@ export class SessionAuthorityOwner {
835
859
  return false;
836
860
  const catalog = await this.#metadata("catalog", api.catalogSnapshotDigest);
837
861
  const issuer = await this.#issuer(String(catalog.record.issuerKeyId));
838
- let allowed = await authorizeCatalogActionWasm(entry.handle, catalog.bytes, this.#metadataPolicy(issuer), action);
862
+ let allowed = await authorizeCatalogActionWasm(entry.handle, catalog.handle, this.#metadataPolicy(issuer), action);
839
863
  if (!allowed && action.kind === "event" && action.direction === "publish") {
840
864
  const binding = entry.authority.providerBindings.find((binding) => binding.apiId === apiId);
841
865
  if (binding &&
@@ -844,16 +868,15 @@ export class SessionAuthorityOwner {
844
868
  const at = publication?.at ?? this.#now();
845
869
  const certificate = await this.#metadata("provider", binding.providerCertificateDigest, at);
846
870
  const providerIssuer = await this.#issuer(String(certificate.record.issuerKeyId));
847
- allowed = await authorizeCatalogActionWasm(entry.handle, catalog.bytes, {
848
- ...this.#metadataPolicy(issuer),
849
- providerPublication: {
850
- certificate: certificate.record,
851
- issuer: providerIssuer,
852
- at,
853
- ...(publication?.publishedAt !== undefined
854
- ? { publishedAt: publication.publishedAt }
855
- : {}),
856
- },
871
+ allowed = await authorizeProviderEventPublicationWasm(entry.handle, catalog.handle, certificate.handle, {
872
+ catalogIssuer: issuer,
873
+ certificateIssuer: providerIssuer,
874
+ trellisInstanceId: this.instanceId,
875
+ audienceNatsAccount: this.account,
876
+ at,
877
+ ...(publication?.publishedAt !== undefined
878
+ ? { publishedAt: publication.publishedAt }
879
+ : {}),
857
880
  }, action);
858
881
  }
859
882
  }
@@ -994,11 +1017,11 @@ export class SessionAuthorityOwner {
994
1017
  }
995
1018
  if (query.kind === "authorityStatus" &&
996
1019
  response.result.kind === "value") {
997
- const status = AuthAuthorityStatusResponseCodec.decode(JSON.parse(response.result.payload));
1020
+ const status = authorizationSessionStatusSchema.parse(JSON.parse(response.result.payload));
998
1021
  if (status.authorizationSessionId !== query.authorizationSessionId)
999
1022
  throw new Error("issuer metadata status identity mismatch");
1000
1023
  if (status.revocation)
1001
- await this.observeRevocation(status.revocation, query.authorizationSessionId, () => epoch === this.#mirrorEpoch &&
1024
+ await this.observeRevocation(signedBytes(status.revocation), query.authorizationSessionId, () => epoch === this.#mirrorEpoch &&
1002
1025
  this.#mirrorCovered &&
1003
1026
  !this.#stopped);
1004
1027
  assertCurrent();
@@ -1193,7 +1216,23 @@ export class SessionAuthorityOwner {
1193
1216
  bytes: bytes.slice(),
1194
1217
  digest: verified.digest,
1195
1218
  record: verified.record,
1219
+ handle: undefined,
1220
+ };
1221
+ }
1222
+ /** Authenticate fetched catalog or certificate bytes once into a handle. */
1223
+ async #authenticateMaterial(kind, bytes, at) {
1224
+ const hints = this.#hints(bytes);
1225
+ if (typeof hints.issuerKeyId !== "string")
1226
+ throw new Error("missing issuer lookup identity");
1227
+ const issuer = await this.#issuer(hints.issuerKeyId);
1228
+ const policy = {
1229
+ ...this.#metadataPolicy(issuer),
1230
+ ...(at !== undefined ? { nowUnixSeconds: at } : {}),
1196
1231
  };
1232
+ const authenticated = kind === "catalog"
1233
+ ? await authenticateCatalogWasm(bytes, policy)
1234
+ : await authenticateProviderCertificateWasm(bytes, policy);
1235
+ return { bytes: bytes.slice(), ...authenticated };
1197
1236
  }
1198
1237
  async #metadata(kind, digest, at) {
1199
1238
  const key = `${kind}.${digest}`;
@@ -1208,7 +1247,7 @@ export class SessionAuthorityOwner {
1208
1247
  if (this.#coldMaterials.size >= 32)
1209
1248
  throw new Error("metadata resolution budget exceeded");
1210
1249
  pending = (async () => {
1211
- const verified = await this.#verifyMetadata(kind, await this.#read(kind, digest), at);
1250
+ const verified = await this.#authenticateMaterial(kind, await this.#read(kind, digest), at);
1212
1251
  if (verified.digest !== digest)
1213
1252
  throw new Error("metadata digest mismatch");
1214
1253
  if (this.#stopped)
@@ -1,84 +1,4 @@
1
1
  import { type TransportAuthorizationV1 } from "../protocol_wasm.ts";
2
- /**
3
- * Retained transport-authorization status for one logical connection.
4
- *
5
- * `unavailable` covers a real disconnect and a socket whose own authority no
6
- * longer covers its admitted policy; it never means "application authorization
7
- * is revoked", which is a separate observation.
8
- */
9
- export type TransportAuthorizationStatus = "unavailable" | "current" | "upgrade_available";
10
- /**
11
- * Parse the signed-context digest out of an authenticated admission name.
12
- *
13
- * Returns `undefined` for any name that is not a well-formed Trellis admission
14
- * marker, so a foreign or malformed name is never mistaken for admitted
15
- * authority.
16
- * The complete marker requires nonempty opaque digest and server fields,
17
- * no whitespace, and a canonical positive decimal u64 client ID.
18
- */
19
- export declare function admissionContextDigest(authenticatedUser: string): string | undefined;
20
- /** Result of one bounded own-user-information read. */
21
- export type OwnAdmission = {
22
- authenticatedUser: string;
23
- contextDigest?: string;
24
- };
25
- /** Minimal NATS request surface used for the own-user-information read. */
26
- export type OwnUserInfoRequester = {
27
- request(subject: string, payload?: Uint8Array, opts?: {
28
- timeout?: number;
29
- }): Promise<{
30
- json<T>(): T;
31
- }>;
32
- };
33
- /**
34
- * Read this attachment's authenticated identity from the broker.
35
- *
36
- * Best effort by design: notification is triggered by a hint or a refresh, and
37
- * a missing or malformed reply must never install authority or lose
38
- * enforcement, so any failure yields `undefined` instead of throwing.
39
- */
40
- export declare function readOwnAdmission(nc: OwnUserInfoRequester, timeoutMs: number): Promise<OwnAdmission | undefined>;
41
- /**
42
- * Retained admitted-transport state for one logical connection.
43
- *
44
- * Holds the exact signed policy actually admitted on the current physical
45
- * attachment (`A`) and recomputes the retained upgrade status against the
46
- * newest valid application policy (`D`). It installs no authority: a change
47
- * here only records a passive upgrade notice or marks transport unavailable.
48
- */
49
- export declare class TransportAuthorizationState {
50
- #private;
51
- /** Register the retained status observer; it receives semantic changes and the current value. */
52
- onStatusChanged(callback: (status: TransportAuthorizationStatus) => void): void;
53
- status(): TransportAuthorizationStatus;
54
- admittedDigest(): string | undefined;
55
- admittedPolicy(): TransportAuthorizationV1 | undefined;
56
- /** Newest valid application policy D used for the last comparison. */
57
- allowedPolicy(): TransportAuthorizationV1 | undefined;
58
- /**
59
- * Record the policy actually admitted on the current physical generation and
60
- * recompute the status against the newest valid application policy.
61
- *
62
- * Called only after an actual admission read, never as a side effect of an
63
- * ordinary context promotion, so an in-place renewal does not pretend the
64
- * socket adopted the newer policy.
65
- */
66
- recordAdmission(args: {
67
- contextDigest: string;
68
- policy: TransportAuthorizationV1;
69
- allowed?: TransportAuthorizationV1;
70
- nowUnixSeconds: number;
71
- }): Promise<void>;
72
- /**
73
- * Recompute against the newest valid application policy without a new read.
74
- *
75
- * A duplicate renewal that changes only the context digest does not change
76
- * the semantic status, so no repeated transition is published.
77
- */
78
- recompute(allowed: TransportAuthorizationV1 | undefined, nowUnixSeconds: number): Promise<void>;
79
- /** Record a real physical loss; the next admission recomputes from scratch. */
80
- markDisconnected(): void;
81
- }
82
2
  /**
83
3
  * Whether the admitted policy covers the exact subjects an operation needs.
84
4
  *
@@ -1,140 +1,4 @@
1
1
  import { classifyTransportAuthorizationWasm, TRANSPORT_AUTHORIZATION_FORMAT_V1, } from "../protocol_wasm.js";
2
- /**
3
- * Prefix the runtime sets on every callout-owned attachment's authenticated
4
- * name: `trellis.auth.v1:<contextDigest>:<serverId>:<clientId>`.
5
- */
6
- const ADMISSION_NAME_PREFIX = "trellis.auth.v1:";
7
- /**
8
- * Parse the signed-context digest out of an authenticated admission name.
9
- *
10
- * Returns `undefined` for any name that is not a well-formed Trellis admission
11
- * marker, so a foreign or malformed name is never mistaken for admitted
12
- * authority.
13
- * The complete marker requires nonempty opaque digest and server fields,
14
- * no whitespace, and a canonical positive decimal u64 client ID.
15
- */
16
- export function admissionContextDigest(authenticatedUser) {
17
- if (!authenticatedUser.startsWith(ADMISSION_NAME_PREFIX))
18
- return undefined;
19
- const remainder = authenticatedUser.slice(ADMISSION_NAME_PREFIX.length);
20
- const fields = remainder.split(":");
21
- const [digest, serverId, clientId] = fields;
22
- if (fields.length !== 3 ||
23
- !digest ||
24
- !serverId ||
25
- /[\p{White_Space}\uFEFF]/u.test(remainder) ||
26
- !/^[1-9][0-9]*$/u.test(clientId) ||
27
- BigInt(clientId) > 18446744073709551615n)
28
- return undefined;
29
- return digest;
30
- }
31
- /**
32
- * Read this attachment's authenticated identity from the broker.
33
- *
34
- * Best effort by design: notification is triggered by a hint or a refresh, and
35
- * a missing or malformed reply must never install authority or lose
36
- * enforcement, so any failure yields `undefined` instead of throwing.
37
- */
38
- export async function readOwnAdmission(nc, timeoutMs) {
39
- try {
40
- const reply = await nc.request("$SYS.REQ.USER.INFO", undefined, {
41
- timeout: timeoutMs,
42
- });
43
- const info = reply.json();
44
- const user = info?.data?.user;
45
- if (typeof user !== "string" || user.length === 0)
46
- return undefined;
47
- return {
48
- authenticatedUser: user,
49
- contextDigest: admissionContextDigest(user),
50
- };
51
- }
52
- catch {
53
- return undefined;
54
- }
55
- }
56
- /**
57
- * Retained admitted-transport state for one logical connection.
58
- *
59
- * Holds the exact signed policy actually admitted on the current physical
60
- * attachment (`A`) and recomputes the retained upgrade status against the
61
- * newest valid application policy (`D`). It installs no authority: a change
62
- * here only records a passive upgrade notice or marks transport unavailable.
63
- */
64
- export class TransportAuthorizationState {
65
- #admittedDigest;
66
- #admitted;
67
- #allowed;
68
- #status = "unavailable";
69
- #onStatusChanged;
70
- /** Register the retained status observer; it receives semantic changes and the current value. */
71
- onStatusChanged(callback) {
72
- this.#onStatusChanged = callback;
73
- callback(this.#status);
74
- }
75
- status() {
76
- return this.#status;
77
- }
78
- admittedDigest() {
79
- return this.#admittedDigest;
80
- }
81
- admittedPolicy() {
82
- return this.#admitted;
83
- }
84
- /** Newest valid application policy D used for the last comparison. */
85
- allowedPolicy() {
86
- return this.#allowed;
87
- }
88
- /**
89
- * Record the policy actually admitted on the current physical generation and
90
- * recompute the status against the newest valid application policy.
91
- *
92
- * Called only after an actual admission read, never as a side effect of an
93
- * ordinary context promotion, so an in-place renewal does not pretend the
94
- * socket adopted the newer policy.
95
- */
96
- async recordAdmission(args) {
97
- this.#admittedDigest = args.contextDigest;
98
- this.#admitted = args.policy;
99
- await this.recompute(args.allowed, args.nowUnixSeconds);
100
- }
101
- /**
102
- * Recompute against the newest valid application policy without a new read.
103
- *
104
- * A duplicate renewal that changes only the context digest does not change
105
- * the semantic status, so no repeated transition is published.
106
- */
107
- async recompute(allowed, nowUnixSeconds) {
108
- this.#allowed = allowed;
109
- const admitted = this.#admitted;
110
- if (!admitted) {
111
- this.#setStatus("unavailable");
112
- return;
113
- }
114
- if (!allowed) {
115
- this.#setStatus("current");
116
- return;
117
- }
118
- const relation = await classifyTransportAuthorizationWasm(admitted, allowed, nowUnixSeconds);
119
- this.#setStatus(relation === "current"
120
- ? "current"
121
- : relation === "upgrade_available"
122
- ? "upgrade_available"
123
- : "unavailable");
124
- }
125
- /** Record a real physical loss; the next admission recomputes from scratch. */
126
- markDisconnected() {
127
- this.#admittedDigest = undefined;
128
- this.#admitted = undefined;
129
- this.#setStatus("unavailable");
130
- }
131
- #setStatus(next) {
132
- if (next === this.#status)
133
- return;
134
- this.#status = next;
135
- this.#onStatusChanged?.(next);
136
- }
137
- }
138
2
  /**
139
3
  * Whether the admitted policy covers the exact subjects an operation needs.
140
4
  *
@@ -3,19 +3,21 @@ import { z } from "zod";
3
3
  import { AuthError } from "../../errors/AuthError.ts";
4
4
  import { type TrellisAuth } from "../session_auth.ts";
5
5
  import { BrowserSessionStore, type BrowserOAuthScope } from "./storage.ts";
6
- import { type PlatformPrivilege, type SignedOAuthAdmission } from "../protocol_wasm.ts";
6
+ import { type SignedOAuthAdmission } from "../protocol_wasm.ts";
7
7
  import { SessionAuthorityOwner, type RuntimeAuthorizationTrust } from "../authority.ts";
8
8
  declare const metadataSchema: z.ZodObject<{
9
9
  issuer: z.ZodString;
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;
@@ -33,29 +35,12 @@ declare const tokenSchema: z.ZodObject<{
33
35
  refresh_token: z.ZodString;
34
36
  expires_in: z.ZodNumber;
35
37
  trellis_admission: z.ZodString;
36
- authorization_details: z.ZodOptional<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
38
+ authorization_details: z.ZodOptional<z.ZodArray<z.ZodObject<{
37
39
  type: z.ZodLiteral<"trellis_capabilities">;
38
40
  required: z.ZodArray<z.ZodString>;
39
41
  optional: z.ZodArray<z.ZodString>;
40
- }, z.core.$strip>, z.ZodObject<{
41
- type: z.ZodLiteral<"trellis_platform_privileges">;
42
- required: z.ZodArray<z.ZodEnum<{
43
- "principals.manage": "principals.manage";
44
- "roles.manage": "roles.manage";
45
- "apis.accept": "apis.accept";
46
- "apis.forceReplace": "apis.forceReplace";
47
- "clients.manage": "clients.manage";
48
- "privileges.manage": "privileges.manage";
49
- }>>;
50
- optional: z.ZodArray<z.ZodEnum<{
51
- "principals.manage": "principals.manage";
52
- "roles.manage": "roles.manage";
53
- "apis.accept": "apis.accept";
54
- "apis.forceReplace": "apis.forceReplace";
55
- "clients.manage": "clients.manage";
56
- "privileges.manage": "privileges.manage";
57
- }>>;
58
- }, z.core.$strip>], "type">>>;
42
+ requested_optional: z.ZodOptional<z.ZodArray<z.ZodString>>;
43
+ }, z.core.$strip>>>;
59
44
  }, z.core.$strip>;
60
45
  /** HTTPS-authenticated discovery scoped to the user's selected server. */
61
46
  export type BrowserOAuthMetadata = z.infer<typeof metadataSchema>;
@@ -75,11 +60,6 @@ export type BrowserOAuthAdmission = {
75
60
  export type BrowserCapabilityRequest = {
76
61
  readonly required: readonly string[];
77
62
  readonly optional: readonly string[];
78
- /** Finite RAR requests; the server still enforces client eligibility, administrator authority, and consent. */
79
- readonly platformPrivileges?: {
80
- readonly required: readonly PlatformPrivilege[];
81
- readonly optional: readonly PlatformPrivilege[];
82
- };
83
63
  };
84
64
  /** Registered and CIMD public OAuth clients share this flow and durable custody. */
85
65
  export declare class BrowserOAuthClient {
@@ -93,22 +73,31 @@ export declare class BrowserOAuthClient {
93
73
  issuer: string;
94
74
  clientId: string;
95
75
  credentialHandle: string;
96
- loopbackDevelopment?: boolean;
97
76
  }): Promise<Result<BrowserOAuthClient, AuthError>>;
98
77
  /** Revoke this app's refresh family and clear custody; does not log out of the Portal. */
99
78
  revoke(): Promise<Result<void, AuthError>>;
100
- /** Build a PKCE authorization URL and retain only this tab's continuation. */
101
- 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>>;
102
87
  /** Consume this tab's exact callback once; install signed authority before remembering its grant. */
103
88
  complete(callback?: string): Promise<Result<{
104
89
  value: BrowserOAuthAdmission;
105
90
  refreshToken: string;
106
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>;
107
98
  /** Serialize refresh across tabs and atomically commit rotation; reload makes a fresh runtime key. */
108
99
  resume(install?: (admission: BrowserOAuthAdmission) => Promise<void>): Promise<Result<BrowserOAuthAdmission, AuthError>>;
109
100
  /** Bind the authenticated connection to the retained credential trust root. */
110
101
  bindOwner(owner: SessionAuthorityOwner): Promise<void>;
111
102
  }
112
- /** RFC 9449 proof and the authenticated Trellis runtime/NKey extension, signed without exporting the private key. */
113
- export declare function createBrowserDpopProof(key: Readonly<CryptoKeyPair>, tokenEndpoint: string, runtimeId: string, sessionPublicKey: string, nonce?: string): Promise<string>;
114
103
  export {};