@oatscenter/trellis 0.100.0-rc.58 → 0.100.0-rc.59

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 (69) hide show
  1. package/auth/authority.js +177 -91
  2. package/auth/browser/oauth.d.ts +1 -1
  3. package/auth/browser/oauth.js +5 -5
  4. package/auth/connection.d.ts +2 -2
  5. package/auth/connection.js +9 -10
  6. package/auth/issuer_metadata.js +1 -1
  7. package/auth/message_digests.js +1 -1
  8. package/auth/mod.d.ts +1 -1
  9. package/auth/oauth_core.d.ts +2 -2
  10. package/auth/oauth_core.js +2 -2
  11. package/auth/protocol_wasm/client/trellis_protocol_wasm_bg.wasm +0 -0
  12. package/auth/protocol_wasm/provider/trellis_protocol_wasm_bg.wasm +0 -0
  13. package/auth/protocol_wasm.d.ts +42 -21
  14. package/auth/protocol_wasm.js +23 -6
  15. package/backoff.d.ts +20 -0
  16. package/backoff.js +38 -0
  17. package/client_connect.js +4 -4
  18. package/device.js +1 -1
  19. package/errors/index.d.ts +104 -96
  20. package/errors/index.js +9 -1
  21. package/health_transport.d.ts +1 -1
  22. package/health_transport.js +9 -10
  23. package/internal_sdk/generated/_internal/evidence.js +4 -4
  24. package/internal_sdk/generated/apis/auth/mod.d.ts +1 -1
  25. package/internal_sdk/generated/apis/auth/mod.js +4 -4
  26. package/internal_sdk/generated/apis/events/mod.d.ts +3 -5
  27. package/internal_sdk/generated/apis/events/mod.js +7 -11
  28. package/internal_sdk/generated/apis/health/mod.d.ts +1 -1
  29. package/internal_sdk/generated/apis/health/mod.js +2 -2
  30. package/internal_sdk/generated/apis/jobs/mod.d.ts +1 -1
  31. package/internal_sdk/generated/apis/jobs/mod.js +2 -2
  32. package/internal_sdk/generated/apis/state/mod.js +5 -5
  33. package/internal_sdk/generated/apis/webhooks/mod.d.ts +5 -9
  34. package/internal_sdk/generated/apis/webhooks/mod.js +5 -13
  35. package/internal_sdk/generated/package.json +2 -2
  36. package/internal_sdk/generated/participants/eventsRuntime/mod.d.ts +1 -1
  37. package/internal_sdk/generated/participants/eventsRuntime/mod.js +2 -2
  38. package/internal_sdk/generated/participants/healthRuntime/mod.d.ts +1 -1
  39. package/internal_sdk/generated/participants/healthRuntime/mod.js +2 -2
  40. package/internal_sdk/generated/participants/jobsRuntime/mod.d.ts +1 -1
  41. package/internal_sdk/generated/participants/jobsRuntime/mod.js +2 -2
  42. package/internal_sdk/generated/participants/platform/mod.d.ts +1 -1
  43. package/internal_sdk/generated/participants/platform/mod.js +2 -2
  44. package/internal_sdk/generated/types/_internal/p0.d.ts +29 -123
  45. package/internal_sdk/generated/types/_internal/p0.js +8 -35
  46. package/internal_sdk/generated/types/index.d.ts +0 -20
  47. package/internal_sdk/generated/types/index.js +0 -10
  48. package/kv.d.ts +6 -1
  49. package/kv.js +86 -25
  50. package/live/subscription.js +1 -0
  51. package/native/connection.js +4 -4
  52. package/native/discovery.js +5 -5
  53. package/native/oauth.js +2 -1
  54. package/operations.d.ts +6 -1
  55. package/operations.js +53 -9
  56. package/package.json +2 -2
  57. package/portable.d.ts +2 -2
  58. package/service/runtime/core.js +486 -81
  59. package/service/runtime/service.js +38 -5
  60. package/service/runtime/transfer.js +49 -36
  61. package/session/durable_events.js +140 -84
  62. package/session/state.d.ts +6 -18
  63. package/session/state.js +2 -2
  64. package/session.js +12 -4
  65. package/tasks.js +13 -2
  66. package/transfer/session.js +4 -1
  67. package/transfer.d.ts +4 -0
  68. package/transfer.js +39 -24
  69. package/transport/generations.js +12 -0
package/auth/authority.js CHANGED
@@ -161,7 +161,7 @@ export class SessionAuthorityOwner {
161
161
  #own;
162
162
  #ownAvailable = false;
163
163
  #stopped = false;
164
- #overloaded = false;
164
+ #revocationOverflowUntil = 0;
165
165
  /** Supply issuer pins from trusted provisioning or selected HTTPS discovery, not peer material. */
166
166
  constructor(options) {
167
167
  if (!options.issuers.length || options.issuers.length > 128)
@@ -265,7 +265,8 @@ export class SessionAuthorityOwner {
265
265
  this.#mirrorPreparationStop === abort &&
266
266
  !this.#mirrorCovered)) {
267
267
  this.#mirrorCovered = false;
268
- this.#mirrorFailed = !transportLost && !nats.isClosed();
268
+ this.#mirrorFailed =
269
+ !transportLost && !nats.isClosed() && !nats.isDraining();
269
270
  for (const listener of this.#listeners) {
270
271
  try {
271
272
  listener();
@@ -285,7 +286,10 @@ export class SessionAuthorityOwner {
285
286
  const abort = () => fail(new Error("authority mirror cancelled"), true);
286
287
  const timer = setTimeout(() => fail(new Error("authority mirror snapshot timeout")), options.timeoutMs ?? 30_000);
287
288
  const check = () => {
288
- if (!current() || nats.isClosed() || options.signal?.aborted)
289
+ if (!current() ||
290
+ nats.isClosed() ||
291
+ nats.isDraining() ||
292
+ options.signal?.aborted)
289
293
  throw new Error("authority mirror superseded");
290
294
  };
291
295
  const cover = () => {
@@ -527,7 +531,17 @@ export class SessionAuthorityOwner {
527
531
  }
528
532
  /** Verified retirement observed by the runtime's single mirror. */
529
533
  isRevoked(sessionId) {
530
- return this.#revocations.has(sessionId);
534
+ return this.#revocation(sessionId) !== undefined;
535
+ }
536
+ #revocation(sessionId) {
537
+ const record = this.#revocations.get(sessionId);
538
+ if (!record)
539
+ return undefined;
540
+ if (record.expiresAt <= this.#now()) {
541
+ this.#revocations.delete(sessionId);
542
+ return undefined;
543
+ }
544
+ return record;
531
545
  }
532
546
  /** Observe promotion and sticky lifecycle changes, without a per-context subscription. */
533
547
  subscribeChanges(callback) {
@@ -679,7 +693,7 @@ export class SessionAuthorityOwner {
679
693
  payloadSha256: await payloadSha256(payload),
680
694
  proof,
681
695
  policy: this.policy(),
682
- knownRevoked: this.#revocations.has(entry.authority.authorizationSessionId),
696
+ knownRevoked: this.isRevoked(entry.authority.authorizationSessionId),
683
697
  });
684
698
  if (!verified.ok)
685
699
  throw new Error(verified.error.code);
@@ -694,8 +708,10 @@ export class SessionAuthorityOwner {
694
708
  /** Verify actual provider result bytes against the still-pending opening, not response-supplied correlation. */
695
709
  async verifyResponse(response, payload, proof, receivedSubject, pending) {
696
710
  const provider = await this.peer(response.providerAuthorityDigest);
711
+ let certificateLease;
697
712
  try {
698
- const certificate = await this.#metadata("provider", response.providerCertificateDigest);
713
+ certificateLease = await this.#metadata("provider", response.providerCertificateDigest);
714
+ const certificate = certificateLease.material;
699
715
  const issuer = await this.#issuer(String(certificate.record.issuerKeyId));
700
716
  await this.#settleMirrorUpdates();
701
717
  const verified = await verifySessionResponseWasm({
@@ -711,7 +727,7 @@ export class SessionAuthorityOwner {
711
727
  expectedDeploymentId: pending.expectedDeploymentId,
712
728
  receivedSubject,
713
729
  policy: this.policy(),
714
- knownRevoked: this.#revocations.has(provider.authority.authorizationSessionId),
730
+ knownRevoked: this.isRevoked(provider.authority.authorizationSessionId),
715
731
  });
716
732
  if (!verified.ok)
717
733
  throw new Error(verified.error.code);
@@ -732,6 +748,7 @@ export class SessionAuthorityOwner {
732
748
  return provider.authority.binding;
733
749
  }
734
750
  finally {
751
+ certificateLease?.release();
735
752
  provider.release();
736
753
  }
737
754
  }
@@ -765,7 +782,7 @@ export class SessionAuthorityOwner {
765
782
  }
766
783
  else if (status.state !== "active")
767
784
  throw new Error("historical cutoff unavailable");
768
- const known = this.#revocations.get(hints.authorizationSessionId);
785
+ const known = this.#revocation(hints.authorizationSessionId);
769
786
  if (known)
770
787
  historicalCutoff = Math.min(historicalCutoff ?? known.cutoff, known.cutoff);
771
788
  historical = await this.#verify(bytes, "historicalEvent", historicalCutoff);
@@ -790,14 +807,14 @@ export class SessionAuthorityOwner {
790
807
  proof,
791
808
  policy: this.policy(),
792
809
  originalPublication,
793
- knownRevoked: this.#revocations.has(entry.authority.authorizationSessionId),
810
+ knownRevoked: this.isRevoked(entry.authority.authorizationSessionId),
794
811
  });
795
812
  if (!verified.ok)
796
813
  throw new Error(verified.error.code);
797
814
  if (!originalPublication)
798
815
  this.assertCurrent(entry);
799
816
  else {
800
- const observed = this.#revocations.get(entry.authority.authorizationSessionId)?.cutoff;
817
+ const observed = this.#revocation(entry.authority.authorizationSessionId)?.cutoff;
801
818
  const cutoff = Math.min(historicalCutoff ?? Infinity, observed ?? Infinity);
802
819
  if (Date.parse(originalPublication.publishedAt) / 1000 >= cutoff)
803
820
  throw new Error("EventRevoked");
@@ -827,17 +844,26 @@ export class SessionAuthorityOwner {
827
844
  (expectedSession !== undefined &&
828
845
  expectedSession !== authorizationSessionId))
829
846
  throw new Error("invalid revocation record");
847
+ const now = this.#now();
830
848
  for (const [id, record] of this.#revocations)
831
- if (record.expiresAt <= this.#now())
849
+ if (record.expiresAt <= now)
832
850
  this.#revocations.delete(id);
833
851
  const current = this.#revocations.get(authorizationSessionId);
834
852
  if (!current &&
835
- latestContextExpiry > this.#now() &&
853
+ latestContextExpiry > now &&
836
854
  this.#revocations.size >= 4096) {
837
- this.#overloaded = true;
855
+ this.#revocationOverflowUntil = Math.max(this.#revocationOverflowUntil, latestContextExpiry);
856
+ for (const listener of this.#listeners) {
857
+ try {
858
+ listener();
859
+ }
860
+ catch {
861
+ /* overflow fence remains active until latestContextExpiry */
862
+ }
863
+ }
838
864
  throw new Error("revocation budget exceeded");
839
865
  }
840
- if (latestContextExpiry > this.#now()) {
866
+ if (latestContextExpiry > now) {
841
867
  this.#revocations.set(authorizationSessionId, {
842
868
  cutoff: Math.min(current?.cutoff ?? effectiveCutoff, effectiveCutoff),
843
869
  expiresAt: Math.max(current?.expiresAt ?? latestContextExpiry, latestContextExpiry),
@@ -864,12 +890,13 @@ export class SessionAuthorityOwner {
864
890
  }
865
891
  /** Recheck observed revocation and expiry after every cold asynchronous boundary. */
866
892
  assertCurrent(entry) {
867
- if (this.#stopped || this.#overloaded)
893
+ const now = this.#now();
894
+ if (this.#stopped || this.#revocationOverflowUntil > now)
868
895
  throw new Error("authority owner unavailable");
869
896
  const issuer = this.#liveIssuer(entry.authority.issuerKeyId);
870
897
  if (issuer?.state !== "active")
871
898
  throw new Error("issuer unavailable for live authority");
872
- assertSessionAuthorityHandleCurrentWasm(entry.handle, this.policy(), this.#revocations.has(entry.authority.authorizationSessionId));
899
+ assertSessionAuthorityHandleCurrentWasm(entry.handle, this.policy(), this.isRevoked(entry.authority.authorizationSessionId));
873
900
  }
874
901
  /** Shared authorization used by RPC, events and long-lived adapters. */
875
902
  async authorize(entry, apiId, action, historical = false, publication) {
@@ -883,32 +910,43 @@ export class SessionAuthorityOwner {
883
910
  const api = entry.authority.apis.find((api) => api.apiId === apiId);
884
911
  if (!api)
885
912
  return false;
886
- const catalog = await this.#metadata("catalog", api.catalogSnapshotDigest);
887
- const issuer = await this.#issuer(String(catalog.record.issuerKeyId));
888
- let allowed = await authorizeCatalogActionWasm(entry.handle, catalog.handle, this.#metadataPolicy(issuer), action);
889
- if (!allowed && action.kind === "event" && action.direction === "publish") {
890
- const binding = entry.authority.providerBindings.find((binding) => binding.apiId === apiId);
891
- if (binding &&
892
- (entry.authority.binding.kind === "service" ||
893
- entry.authority.binding.kind === "device")) {
894
- const at = publication?.at ?? this.#now();
895
- const certificate = await this.#metadata("provider", binding.providerCertificateDigest, at);
896
- const providerIssuer = await this.#issuer(String(certificate.record.issuerKeyId));
897
- allowed = await authorizeProviderEventPublicationWasm(entry.handle, catalog.handle, certificate.handle, {
898
- catalogIssuer: issuer,
899
- certificateIssuer: providerIssuer,
900
- trellisInstanceId: this.instanceId,
901
- audienceNatsAccount: this.account,
902
- at,
903
- ...(publication?.publishedAt !== undefined
904
- ? { publishedAt: publication.publishedAt }
905
- : {}),
906
- }, action);
913
+ const catalogLease = await this.#metadata("catalog", api.catalogSnapshotDigest);
914
+ let certificateLease;
915
+ try {
916
+ const catalog = catalogLease.material;
917
+ const issuer = await this.#issuer(String(catalog.record.issuerKeyId));
918
+ let allowed = await authorizeCatalogActionWasm(entry.handle, catalog.handle, this.#metadataPolicy(issuer), action);
919
+ if (!allowed &&
920
+ action.kind === "event" &&
921
+ action.direction === "publish") {
922
+ const binding = entry.authority.providerBindings.find((binding) => binding.apiId === apiId);
923
+ if (binding &&
924
+ (entry.authority.binding.kind === "service" ||
925
+ entry.authority.binding.kind === "device")) {
926
+ const at = publication?.at ?? this.#now();
927
+ certificateLease = await this.#metadata("provider", binding.providerCertificateDigest, at);
928
+ const certificate = certificateLease.material;
929
+ const providerIssuer = await this.#issuer(String(certificate.record.issuerKeyId));
930
+ allowed = await authorizeProviderEventPublicationWasm(entry.handle, catalog.handle, certificate.handle, {
931
+ catalogIssuer: issuer,
932
+ certificateIssuer: providerIssuer,
933
+ trellisInstanceId: this.instanceId,
934
+ transportAudience: this.account,
935
+ at,
936
+ ...(publication?.publishedAt !== undefined
937
+ ? { publishedAt: publication.publishedAt }
938
+ : {}),
939
+ }, action);
940
+ }
907
941
  }
942
+ if (!historical)
943
+ this.assertCurrent(entry);
944
+ return allowed;
945
+ }
946
+ finally {
947
+ certificateLease?.release();
948
+ catalogLease.release();
908
949
  }
909
- if (!historical)
910
- this.assertCurrent(entry);
911
- return allowed;
912
950
  }
913
951
  /** Resolve immutable catalog evidence for one API bound to a live verified authority. @internal */
914
952
  async authenticatedCatalog(entry, apiId) {
@@ -916,16 +954,21 @@ export class SessionAuthorityOwner {
916
954
  const api = entry.authority.apis.find((api) => api.apiId === apiId);
917
955
  if (!api)
918
956
  return undefined;
919
- const catalog = await this.#metadata("catalog", api.catalogSnapshotDigest);
920
- const record = catalog.record;
921
- await this.#issuer(String(record.issuerKeyId));
922
- if (record.apiId !== apiId ||
923
- record.generation !== api.generation ||
924
- typeof record.acceptedRevision !== "string" ||
925
- BigInt(record.acceptedRevision) < BigInt(api.acceptedRevision))
926
- throw new Error("catalog does not match authority binding");
927
- this.assertCurrent(entry);
928
- return structuredClone(record);
957
+ const catalogLease = await this.#metadata("catalog", api.catalogSnapshotDigest);
958
+ try {
959
+ const record = catalogLease.material.record;
960
+ await this.#issuer(String(record.issuerKeyId));
961
+ if (record.apiId !== apiId ||
962
+ record.generation !== api.generation ||
963
+ typeof record.acceptedRevision !== "string" ||
964
+ BigInt(record.acceptedRevision) < BigInt(api.acceptedRevision))
965
+ throw new Error("catalog does not match authority binding");
966
+ this.assertCurrent(entry);
967
+ return structuredClone(record);
968
+ }
969
+ finally {
970
+ catalogLease.release();
971
+ }
929
972
  }
930
973
  /** Authenticate the provider certificate and exact advertised action for a retained endpoint. */
931
974
  async authorizeProvider(entry, apiId, generation, action) {
@@ -936,27 +979,33 @@ export class SessionAuthorityOwner {
936
979
  (authority.binding.kind !== "service" &&
937
980
  authority.binding.kind !== "device"))
938
981
  throw new Error("PermissionDenied");
939
- const certificate = (await this.#metadata("provider", binding.providerCertificateDigest)).record;
940
- if (certificate.principalId !== authority.principalId ||
941
- certificate.sessionPublicKey !== authority.sessionPublicKey ||
942
- certificate.deploymentId !== authority.binding.deploymentId ||
943
- certificate.instanceId !== authority.binding.instanceId ||
944
- certificate.apiId !== apiId ||
945
- certificate.generation !== generation ||
946
- certificate.implementationDigest !== binding.implementationDigest ||
947
- certificate.deploymentId !== binding.deploymentId ||
948
- typeof certificate.notBefore !== "number" ||
949
- typeof certificate.expiresAt !== "number" ||
950
- certificate.notBefore > this.#now() ||
951
- certificate.expiresAt <= this.#now() ||
952
- !Array.isArray(certificate.implementedActions) ||
953
- !certificate.implementedActions.some((member) => member &&
954
- typeof member === "object" &&
955
- Reflect.get(member, "kind") === action.kind &&
956
- Reflect.get(member, "name") === action.name &&
957
- Reflect.get(member, "direction") === action.direction))
958
- throw new Error("PermissionDenied");
959
- this.assertCurrent(entry);
982
+ const certificateLease = await this.#metadata("provider", binding.providerCertificateDigest);
983
+ const certificate = certificateLease.material.record;
984
+ try {
985
+ if (certificate.principalId !== authority.principalId ||
986
+ certificate.sessionPublicKey !== authority.sessionPublicKey ||
987
+ certificate.deploymentId !== authority.binding.deploymentId ||
988
+ certificate.instanceId !== authority.binding.instanceId ||
989
+ certificate.apiId !== apiId ||
990
+ certificate.generation !== generation ||
991
+ certificate.implementationDigest !== binding.implementationDigest ||
992
+ certificate.deploymentId !== binding.deploymentId ||
993
+ typeof certificate.notBefore !== "number" ||
994
+ typeof certificate.expiresAt !== "number" ||
995
+ certificate.notBefore > this.#now() ||
996
+ certificate.expiresAt <= this.#now() ||
997
+ !Array.isArray(certificate.implementedActions) ||
998
+ !certificate.implementedActions.some((member) => member &&
999
+ typeof member === "object" &&
1000
+ Reflect.get(member, "kind") === action.kind &&
1001
+ Reflect.get(member, "name") === action.name &&
1002
+ Reflect.get(member, "direction") === action.direction))
1003
+ throw new Error("PermissionDenied");
1004
+ this.assertCurrent(entry);
1005
+ }
1006
+ finally {
1007
+ certificateLease.release();
1008
+ }
960
1009
  }
961
1010
  /** Stop owned local work without erasing durable OAuth credentials or published historical material. */
962
1011
  stop() {
@@ -981,6 +1030,11 @@ export class SessionAuthorityOwner {
981
1030
  entry.handle.free();
982
1031
  }
983
1032
  this.#peers.clear();
1033
+ for (const entry of this.#materials.values()) {
1034
+ entry.retired = true;
1035
+ if (!entry.references)
1036
+ entry.handle.free();
1037
+ }
984
1038
  this.#materials.clear();
985
1039
  this.#own = undefined;
986
1040
  for (const listener of this.#listeners) {
@@ -1066,7 +1120,7 @@ export class SessionAuthorityOwner {
1066
1120
  return {
1067
1121
  issuer,
1068
1122
  trellisInstanceId: this.instanceId,
1069
- audienceNatsAccount: this.account,
1123
+ transportAudience: this.account,
1070
1124
  nowUnixSeconds: this.#now(),
1071
1125
  installedSequence: this.#rotationSequence.toString(),
1072
1126
  };
@@ -1226,14 +1280,14 @@ export class SessionAuthorityOwner {
1226
1280
  throw new Error("missing issuer lookup identity");
1227
1281
  const issuer = await this.#issuer(hints.issuerKeyId);
1228
1282
  const revoked = typeof hints.authorizationSessionId === "string"
1229
- ? this.#revocations.get(hints.authorizationSessionId)
1283
+ ? this.#revocation(hints.authorizationSessionId)
1230
1284
  : undefined;
1231
1285
  const verified = await createSessionAuthorityHandleWasm({
1232
1286
  authorityBytes: bytes,
1233
1287
  verification: {
1234
1288
  issuer,
1235
1289
  trellisInstanceId: this.instanceId,
1236
- audienceNatsAccount: this.account,
1290
+ transportAudience: this.account,
1237
1291
  policy: this.policy(),
1238
1292
  purpose,
1239
1293
  revocationCutoff: historicalCutoff === undefined
@@ -1282,7 +1336,6 @@ export class SessionAuthorityOwner {
1282
1336
  bytes: bytes.slice(),
1283
1337
  digest: verified.digest,
1284
1338
  record: verified.record,
1285
- handle: undefined,
1286
1339
  };
1287
1340
  }
1288
1341
  /** Authenticate fetched catalog or certificate bytes once into a handle. */
@@ -1298,7 +1351,27 @@ export class SessionAuthorityOwner {
1298
1351
  const authenticated = kind === "catalog"
1299
1352
  ? await authenticateCatalogWasm(bytes, policy)
1300
1353
  : await authenticateProviderCertificateWasm(bytes, policy);
1301
- return { bytes: bytes.slice(), ...authenticated };
1354
+ return {
1355
+ bytes: bytes.slice(),
1356
+ ...authenticated,
1357
+ references: 0,
1358
+ retired: false,
1359
+ };
1360
+ }
1361
+ #retainMaterial(material) {
1362
+ material.references++;
1363
+ let released = false;
1364
+ return {
1365
+ material,
1366
+ release: () => {
1367
+ if (released)
1368
+ return;
1369
+ released = true;
1370
+ material.references--;
1371
+ if (material.retired && material.references === 0)
1372
+ material.handle.free();
1373
+ },
1374
+ };
1302
1375
  }
1303
1376
  async #metadata(kind, digest, at) {
1304
1377
  const key = `${kind}.${digest}`;
@@ -1306,7 +1379,7 @@ export class SessionAuthorityOwner {
1306
1379
  if (cached) {
1307
1380
  this.#materials.delete(key);
1308
1381
  this.#materials.set(key, cached);
1309
- return cached;
1382
+ return this.#retainMaterial(cached);
1310
1383
  }
1311
1384
  let pending = this.#coldMaterials.get(key);
1312
1385
  if (!pending) {
@@ -1314,27 +1387,40 @@ export class SessionAuthorityOwner {
1314
1387
  throw new Error("metadata resolution budget exceeded");
1315
1388
  pending = (async () => {
1316
1389
  const verified = await this.#authenticateMaterial(kind, await this.#read(kind, digest), at);
1317
- if (verified.digest !== digest)
1318
- throw new Error("metadata digest mismatch");
1319
- if (this.#stopped)
1320
- throw new Error("authority owner stopped");
1321
- let total = [...this.#materials.values()].reduce((size, entry) => size + entry.bytes.length, verified.bytes.length);
1322
- while (this.#materials.size >= 256 || total > 16 * 1024 * 1024) {
1323
- const oldest = this.#materials.keys().next().value;
1324
- if (oldest === undefined)
1325
- throw new Error("metadata byte budget exceeded");
1326
- total -= this.#materials.get(oldest).bytes.length;
1327
- this.#materials.delete(oldest);
1390
+ try {
1391
+ if (verified.digest !== digest)
1392
+ throw new Error("metadata digest mismatch");
1393
+ if (this.#stopped)
1394
+ throw new Error("authority owner stopped");
1395
+ let total = [...this.#materials.values()].reduce((size, entry) => size + entry.bytes.length, verified.bytes.length);
1396
+ while (this.#materials.size >= 256 || total > 16 * 1024 * 1024) {
1397
+ const oldest = this.#materials.keys().next().value;
1398
+ if (oldest === undefined)
1399
+ throw new Error("metadata byte budget exceeded");
1400
+ const evicted = this.#materials.get(oldest);
1401
+ total -= evicted.bytes.length;
1402
+ this.#materials.delete(oldest);
1403
+ evicted.retired = true;
1404
+ if (!evicted.references)
1405
+ evicted.handle.free();
1406
+ }
1407
+ this.#materials.set(key, verified);
1408
+ return verified;
1409
+ }
1410
+ catch (error) {
1411
+ verified.handle.free();
1412
+ throw error;
1328
1413
  }
1329
- this.#materials.set(key, verified);
1330
- return verified;
1331
1414
  })();
1332
1415
  this.#coldMaterials.set(key, pending);
1333
1416
  void pending
1334
1417
  .finally(() => this.#coldMaterials.delete(key))
1335
1418
  .catch(() => undefined);
1336
1419
  }
1337
- return await pending;
1420
+ const material = await pending;
1421
+ if (this.#stopped || material.retired)
1422
+ throw new Error("authority material unavailable");
1423
+ return this.#retainMaterial(material);
1338
1424
  }
1339
1425
  #prunePeers(incomingBytes) {
1340
1426
  let total = [...this.#peers.values()].reduce((size, entry) => size + entry.byteLength, incomingBytes);
@@ -14,7 +14,7 @@ declare const metadataSchema: z.ZodObject<{
14
14
  code_challenge_methods_supported: z.ZodArray<z.ZodString>;
15
15
  trellis: z.ZodObject<{
16
16
  trellisInstanceId: z.ZodString;
17
- audienceNatsAccount: z.ZodString;
17
+ transportAudience: z.ZodString;
18
18
  rotationSequence: z.ZodString;
19
19
  natsEndpoints: z.ZodArray<z.ZodString>;
20
20
  natsSentinel: z.ZodString;
@@ -5,7 +5,7 @@ import { authenticateIssuerChain } from "../issuer_trust.js";
5
5
  import { createAuth } from "../session_auth.js";
6
6
  import { base64urlEncode, sha256, utf8, toArrayBuffer } from "../utils.js";
7
7
  import { BrowserSessionStore } from "./storage.js";
8
- import {} from "../protocol_wasm.js";
8
+ import { nkeyTransportPublicKey, } from "../protocol_wasm.js";
9
9
  import { boundedJson, dpopThumbprint, postWithDpop, usableNonce, verifyAdmission, } from "../oauth_core.js";
10
10
  import { SessionAuthorityOwner, } from "../authority.js";
11
11
  const metadataSchema = z.object({
@@ -17,7 +17,7 @@ const metadataSchema = z.object({
17
17
  code_challenge_methods_supported: z.array(z.string()),
18
18
  trellis: z.object({
19
19
  trellisInstanceId: z.string().min(1),
20
- audienceNatsAccount: z.string().min(1),
20
+ transportAudience: z.string().min(1),
21
21
  rotationSequence: z.string().regex(/^(0|[1-9][0-9]*)$/),
22
22
  natsEndpoints: z.array(z.string().min(1)).min(1),
23
23
  natsSentinel: z.string().min(1),
@@ -112,7 +112,7 @@ export class BrowserOAuthClient {
112
112
  const scope = {
113
113
  issuer: metadata.issuer,
114
114
  instanceId: metadata.trellis.trellisInstanceId,
115
- account: metadata.trellis.audienceNatsAccount,
115
+ account: metadata.trellis.transportAudience,
116
116
  browserOrigin: location.origin,
117
117
  clientId: options.clientId,
118
118
  credentialHandle: options.credentialHandle,
@@ -341,7 +341,7 @@ export class BrowserOAuthClient {
341
341
  throw new AuthError({ reason: "OAuthTrustUnavailable" });
342
342
  const owner = await authenticateIssuerChain(this.scope.issuer, this.#owner?.trustSnapshot ?? this.store.trust, {
343
343
  instanceId: metadata.trellis.trellisInstanceId,
344
- account: metadata.trellis.audienceNatsAccount,
344
+ account: metadata.trellis.transportAudience,
345
345
  issuer: active[0],
346
346
  rotationSequence: metadata.trellis.rotationSequence,
347
347
  }, undefined, this.#owner);
@@ -413,7 +413,7 @@ export class BrowserOAuthClient {
413
413
  await this.store.retainTrust(this.#owner);
414
414
  const verified = await verifyAdmission({
415
415
  admission: token.trellis_admission,
416
- ephemeralNkey: auth.sessionNkey,
416
+ transportPublicKey: nkeyTransportPublicKey(auth.sessionNkey),
417
417
  nowUnixSeconds: () => auth.currentIat(),
418
418
  trust: () => this.store.trust,
419
419
  refreshTrust: async () => await this.#prepareTrust(),
@@ -7,7 +7,7 @@ import { TransportGenerationManager, type TransportGeneration } from "../transpo
7
7
  export type ProvisionedConnectionOptions = {
8
8
  servers: string[];
9
9
  trellisInstanceId: string;
10
- audienceNatsAccount: string;
10
+ transportAudience: string;
11
11
  issuers: readonly AuthorityIssuerKey[];
12
12
  /** Sentinel user JWT from the installation's metadata. */
13
13
  natsSentinel: string;
@@ -31,7 +31,7 @@ export declare function connectProvisioned(options: ProvisionedConnectionOptions
31
31
  export declare function connectAdmitted(options: {
32
32
  servers: string[];
33
33
  trellisInstanceId: string;
34
- audienceNatsAccount: string;
34
+ transportAudience: string;
35
35
  issuers: readonly AuthorityIssuerKey[];
36
36
  rotationSequence?: string;
37
37
  /** Sentinel user JWT from the installation's metadata. */
@@ -6,7 +6,7 @@ import { AuthError } from "../errors/AuthError.js";
6
6
  import { TransportError } from "../errors/TransportError.js";
7
7
  import { createAuth } from "./session_auth.js";
8
8
  import { base64urlDecode, base64urlEncode, sha256, utf8 } from "./utils.js";
9
- import { initializeProtocolWasm, signProvisionedAdmissionWasm, verifyOAuthAdmissionWasm, createSessionAuthorityHandleWasm, assertSessionAuthorityHandleCurrentWasm, transportAuthorizationDigestWasm, classifyTransportAuthorizationWasm, } from "./protocol_wasm.js";
9
+ import { initializeProtocolWasm, nkeyTransportPublicKey, signProvisionedAdmissionWasm, verifyOAuthAdmissionWasm, createSessionAuthorityHandleWasm, assertSessionAuthorityHandleCurrentWasm, transportAuthorizationDigestWasm, classifyTransportAuthorizationWasm, } from "./protocol_wasm.js";
10
10
  import { loadDefaultRuntimeTransport, } from "../runtime_transport.js";
11
11
  import { TransportGenerationManager, } from "../transport/generations.js";
12
12
  import { Backoff } from "../backoff.js";
@@ -63,10 +63,10 @@ export async function connectProvisioned(options, kind, hooks = {}, transport) {
63
63
  return await signProvisionedAdmissionWasm({
64
64
  format: "trellis.provisioned-admission.v1",
65
65
  trellisInstanceId: options.trellisInstanceId,
66
- audienceNatsAccount: options.audienceNatsAccount,
66
+ transportAudience: options.transportAudience,
67
67
  credentialId,
68
68
  runtimeId,
69
- ephemeralNkey: auth.sessionNkey,
69
+ transportPublicKey: nkeyTransportPublicKey(auth.sessionNkey),
70
70
  issuedAt,
71
71
  expiresAt: issuedAt + 60,
72
72
  }, base64urlDecode(options.seed));
@@ -116,7 +116,7 @@ export async function connectAdmitted(options) {
116
116
  await initializeProtocolWasm();
117
117
  const owner = new SessionAuthorityOwner({
118
118
  instanceId: options.trellisInstanceId,
119
- account: options.audienceNatsAccount,
119
+ account: options.transportAudience,
120
120
  issuers: options.issuers,
121
121
  rotationSequence: options.rotationSequence,
122
122
  });
@@ -162,8 +162,8 @@ export async function connectAdmitted(options) {
162
162
  const verified = await verifyOAuthAdmissionWasm(utf8(credential), {
163
163
  issuer: owner.trustSnapshot.issuer,
164
164
  trellisInstanceId: options.trellisInstanceId,
165
- audienceNatsAccount: options.audienceNatsAccount,
166
- ephemeralNkey: options.auth.sessionNkey,
165
+ transportAudience: options.transportAudience,
166
+ transportPublicKey: nkeyTransportPublicKey(options.auth.sessionNkey),
167
167
  nowUnixSeconds: options.auth.currentIat(),
168
168
  maximumLifetimeSeconds: 300,
169
169
  });
@@ -201,10 +201,9 @@ export async function connectAdmitted(options) {
201
201
  const broker = info.json();
202
202
  if (registry.attachmentId !== attachmentId ||
203
203
  broker.data?.user !== `trellis.auth.v1:${registry.attachmentId}` ||
204
- registry.transportAuthorization.account !==
205
- options.audienceNatsAccount ||
204
+ registry.transportAuthorization.account !== options.transportAudience ||
206
205
  registry.admittedTransportAuthorization.account !==
207
- options.audienceNatsAccount)
206
+ options.transportAudience)
208
207
  throw new Error("AdmissionAttachmentMismatch");
209
208
  // Verify against the key that signed this answer. A rotation during the
210
209
  // renewal moves the owner's pin on, but that key stays live through its
@@ -217,7 +216,7 @@ export async function connectAdmitted(options) {
217
216
  verification: {
218
217
  issuer,
219
218
  trellisInstanceId: options.trellisInstanceId,
220
- audienceNatsAccount: options.audienceNatsAccount,
219
+ transportAudience: options.transportAudience,
221
220
  policy: owner.policy(),
222
221
  purpose: "live",
223
222
  revocationCutoff: null,
@@ -8,7 +8,7 @@ export async function requestIssuerMetadata(options) {
8
8
  const nonce = crypto.getRandomValues(new Uint8Array(16));
9
9
  const request = {
10
10
  trellisInstanceId: options.instanceId,
11
- audienceNatsAccount: options.account,
11
+ transportAudience: options.account,
12
12
  requestNonce: btoa(String.fromCharCode(...nonce))
13
13
  .replaceAll("+", "-")
14
14
  .replaceAll("/", "_")
@@ -219,7 +219,7 @@ export async function sessionResponseSigningDigest(response, payload) {
219
219
  concatAll(lengthPrefixed([
220
220
  encoder.encode(MESSAGE_RESPONSE_DOMAIN_V1),
221
221
  encoder.encode(response.trellisInstanceId),
222
- encoder.encode(response.audienceNatsAccount),
222
+ encoder.encode(response.transportAudience),
223
223
  fixed(response.providerAuthorityDigest, 32, "providerAuthorityDigest"),
224
224
  fixed(response.providerCertificateDigest, 32, "providerCertificateDigest"),
225
225
  encoder.encode(response.apiId),
package/auth/mod.d.ts CHANGED
@@ -7,7 +7,7 @@ export { type BrowserAuthRecoveryClassification, type BrowserAuthRecoveryKind, c
7
7
  export { buildDeviceActivationPayload, deriveDeviceConfirmationCode, deriveDeviceIdentity, waitForDeviceActivation, } from "./device_activation.ts";
8
8
  export { SessionAuthorityOwner } from "./authority.ts";
9
9
  export { createEventProof, createProof, createResponseProof, type RequestSignature, } from "./proof.ts";
10
- export { type SessionRequest, type SessionEvent, type SessionResponse, type VerifySessionResponseArgs, type VerifySessionResponseResult, verifySessionRequestWasm, verifySessionResponseWasm, } from "./protocol_wasm.ts";
10
+ export { type SessionRequest, type SessionEvent, type SessionResponse, type TransportPublicKey, type VerifySessionResponseArgs, type VerifySessionResponseResult, verifySessionRequestWasm, verifySessionResponseWasm, } from "./protocol_wasm.ts";
11
11
  export { parseSessionProof, SESSION_PROOF_FORMAT_V1, type SessionProof, type SessionProofInput, type SessionProofPolicy, type SessionProofPurpose, sessionProofRequestDigest, sessionProofSigningDigest, signSessionProof, verifySessionProof, } from "./session_proof.ts";
12
12
  export { classifyTransportAuthorizationWasm, TRANSPORT_AUTHORIZATION_FORMAT_V1, transportAuthorizationDigestWasm, type TransportAuthorizationV1, type TransportPolicyClass, } from "./protocol_wasm.ts";
13
13
  export { createAuth, type NatsConnectOptions, type TrellisAuth, } from "./session_auth.ts";
@@ -1,5 +1,5 @@
1
1
  import type { RuntimeAuthorizationTrust } from "./authority.ts";
2
- import { type SignedOAuthAdmission } from "./protocol_wasm.ts";
2
+ import { type SignedOAuthAdmission, type TransportPublicKey } from "./protocol_wasm.ts";
3
3
  /**
4
4
  * The OAuth steps the browser and native clients share: response bounds, DPoP
5
5
  * proofs, the token request with its nonce challenge, and admission
@@ -60,7 +60,7 @@ export declare function postWithDpop(options: {
60
60
  */
61
61
  export declare function verifyAdmission(options: {
62
62
  admission: string;
63
- ephemeralNkey: string;
63
+ transportPublicKey: TransportPublicKey;
64
64
  nowUnixSeconds: () => number;
65
65
  trust: () => RuntimeAuthorizationTrust;
66
66
  refreshTrust: () => Promise<void>;