@oatscenter/trellis 0.100.0-rc.46 → 0.100.0-rc.48

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 (44) hide show
  1. package/auth/authority.d.ts +6 -0
  2. package/auth/authority.js +19 -5
  3. package/auth/browser/oauth.js +29 -4
  4. package/auth/connection.js +51 -19
  5. package/auth/protocol_wasm/client/trellis_protocol_wasm_bg.wasm +0 -0
  6. package/auth/protocol_wasm/provider/trellis_protocol_wasm_bg.wasm +0 -0
  7. package/client_connect.js +11 -6
  8. package/generated_support.js +57 -36
  9. package/internal_sdk/generated/_internal/evidence.d.ts +12 -0
  10. package/internal_sdk/generated/_internal/evidence.js +13 -0
  11. package/internal_sdk/generated/apis/auth/mod.d.ts +900 -2
  12. package/internal_sdk/generated/apis/auth/mod.js +7 -12
  13. package/internal_sdk/generated/apis/core/mod.d.ts +35 -1
  14. package/internal_sdk/generated/apis/core/mod.js +6 -11
  15. package/internal_sdk/generated/apis/events/mod.d.ts +96 -2
  16. package/internal_sdk/generated/apis/events/mod.js +7 -12
  17. package/internal_sdk/generated/apis/health/mod.d.ts +70 -2
  18. package/internal_sdk/generated/apis/health/mod.js +17 -12
  19. package/internal_sdk/generated/apis/jobs/mod.d.ts +100 -1
  20. package/internal_sdk/generated/apis/jobs/mod.js +6 -11
  21. package/internal_sdk/generated/apis/state/mod.d.ts +38 -1
  22. package/internal_sdk/generated/apis/state/mod.js +6 -11
  23. package/internal_sdk/generated/apps/console/mod.d.ts +5 -0
  24. package/internal_sdk/generated/apps/console/mod.js +6 -0
  25. package/internal_sdk/generated/package.json +63 -11
  26. package/internal_sdk/generated/participants/eventsRuntime/mod.d.ts +1 -1
  27. package/internal_sdk/generated/participants/eventsRuntime/mod.js +5 -13
  28. package/internal_sdk/generated/participants/healthRuntime/mod.d.ts +2 -1
  29. package/internal_sdk/generated/participants/healthRuntime/mod.js +6 -13
  30. package/internal_sdk/generated/participants/jobsRuntime/mod.js +3 -11
  31. package/internal_sdk/generated/participants/platform/mod.d.ts +1 -1
  32. package/internal_sdk/generated/participants/platform/mod.js +5 -13
  33. package/internal_sdk/generated/types/_internal/p0.d.ts +6618 -1
  34. package/internal_sdk/generated/types/_internal/p0.js +1144 -1111
  35. package/internal_sdk/generated/types/index.d.ts +10 -0
  36. package/internal_sdk/generated/types/index.js +5 -0
  37. package/live/client_open.js +38 -14
  38. package/package.json +11 -11
  39. package/service/config.js +1 -10
  40. package/session/local_authorization.js +45 -4
  41. package/session.d.ts +1 -1
  42. package/session.js +57 -28
  43. package/transport/generations.d.ts +17 -12
  44. package/transport/generations.js +68 -102
@@ -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;
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;
@@ -478,7 +484,9 @@ export class SessionAuthorityOwner {
478
484
  policy() {
479
485
  return {
480
486
  nowUnixSeconds: this.#now(),
481
- 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,
482
490
  maximumAuthorityLifetimeSeconds: 300,
483
491
  maximumAuthorityBytes: 512 * 1024,
484
492
  maximumEntries: 4096,
@@ -581,8 +589,10 @@ export class SessionAuthorityOwner {
581
589
  }
582
590
  /** Borrow the current own authority, which peer-cache pressure can never evict. */
583
591
  own() {
584
- if (!this.#own || !this.#ownAvailable)
592
+ if (!this.#own)
585
593
  throw new Error("own authority unavailable");
594
+ if (!this.#ownAvailable)
595
+ throw new AuthorityUnavailableError("own authority unavailable");
586
596
  this.assertCurrent(this.#own);
587
597
  return VerifiedAuthority.acquire(authorityLeaseToken, this, this.#own);
588
598
  }
@@ -832,15 +842,17 @@ export class SessionAuthorityOwner {
832
842
  updates = this.#mirrorUpdates;
833
843
  await updates;
834
844
  if (epoch !== this.#mirrorEpoch)
835
- throw new Error("authority mirror superseded");
845
+ throw new AuthorityUnavailableError("authority mirror superseded");
836
846
  } while (updates !== this.#mirrorUpdates);
837
847
  // This waits only for updates already received, never for lost coverage or
838
848
  // a replacement mirror. Callers still perform their normal live checks.
839
849
  }
840
850
  /** Recheck observed revocation and expiry after every cold asynchronous boundary. */
841
851
  assertCurrent(entry) {
842
- if (this.#stopped || this.#overloaded || !this.#mirrorCovered)
852
+ if (this.#stopped || this.#overloaded)
843
853
  throw new Error("authority owner unavailable");
854
+ if (!this.#mirrorCovered)
855
+ throw new AuthorityUnavailableError("revocation mirror is not current");
844
856
  const issuer = this.#liveIssuer(entry.authority.issuerKeyId);
845
857
  if (issuer?.state !== "active")
846
858
  throw new Error("issuer unavailable for live authority");
@@ -1052,8 +1064,10 @@ export class SessionAuthorityOwner {
1052
1064
  };
1053
1065
  }
1054
1066
  async #read(kind, key) {
1055
- if (!this.#material || this.#stopped)
1067
+ if (this.#stopped)
1056
1068
  throw new Error("authority material unavailable");
1069
+ if (!this.#material)
1070
+ throw new AuthorityUnavailableError("authority material unavailable");
1057
1071
  if (!/^[A-Za-z0-9_-]{1,128}$/.test(key))
1058
1072
  throw new Error("invalid material lookup key");
1059
1073
  const prefix = kind === "authority" ? "context" : kind === "catalog" ? "api" : kind;
@@ -6,7 +6,7 @@ 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(),
@@ -63,10 +63,15 @@ export class BrowserOAuthClient {
63
63
  #nonce;
64
64
  #runtime;
65
65
  #owner;
66
- 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) {
67
70
  this.metadata = metadata;
68
71
  this.scope = scope;
69
72
  this.store = store;
73
+ this.#nonce = nonce;
74
+ this.#discovered = { metadata, at: Date.now() };
70
75
  }
71
76
  /** Discover the selected issuer and reopen the exact app's credential custody. */
72
77
  static async open(options) {
@@ -88,6 +93,9 @@ export class BrowserOAuthClient {
88
93
  });
89
94
  if (!response.ok)
90
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"));
91
99
  const metadata = metadataSchema.parse(await boundedJson(response));
92
100
  if (new URL(metadata.issuer).href !== issuer.href ||
93
101
  !metadata.code_challenge_methods_supported.includes("S256") ||
@@ -117,7 +125,7 @@ export class BrowserOAuthClient {
117
125
  })).take();
118
126
  if (isErr(opened))
119
127
  return err(opened.error);
120
- return ok(new BrowserOAuthClient(metadata, scope, opened));
128
+ return ok(new BrowserOAuthClient(metadata, scope, opened, nonce));
121
129
  }
122
130
  catch {
123
131
  return err(new AuthError({ reason: "OAuthUnavailable" }));
@@ -201,6 +209,9 @@ export class BrowserOAuthClient {
201
209
  }
202
210
  /** Consume this tab's exact callback once; install signed authority before remembering its grant. */
203
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;
204
215
  try {
205
216
  const raw = sessionStorage.getItem(this.#pendingKey());
206
217
  if (!raw)
@@ -278,7 +289,21 @@ export class BrowserOAuthClient {
278
289
  else if (!this.#owner)
279
290
  throw new AuthError({ reason: "OAuthRecoveryRequired" });
280
291
  }, async () => {
281
- 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);
282
307
  });
283
308
  }
284
309
  /** Bind the authenticated connection to the retained credential trust root. */
@@ -1,3 +1,4 @@
1
+ import { ClosedConnectionError } from "@nats-io/nats-core";
1
2
  import { z } from "zod";
2
3
  import { SessionAuthorityOwner } from "./authority.js";
3
4
  import { requestOwnAdmission } from "./admission.js";
@@ -11,6 +12,8 @@ import { TransportGenerationManager, } from "../transport/generations.js";
11
12
  /** Subjects on which Auth announces a new provider of an API the session calls. */
12
13
  const PROVIDERS_NOTICE_SUBJECT_PREFIX = "trellis.auth.providers.";
13
14
  const ISSUER_NOTICE_SUBJECT = "trellis.auth.issuers";
15
+ /** Pause before renewing again after a renewal Auth did not answer. */
16
+ const RENEWAL_RETRY_MS = 1_000;
14
17
  const policySchema = z.object({
15
18
  format: z.literal("trellis.transport-authorization.v1"),
16
19
  account: z.string(),
@@ -69,6 +72,23 @@ export async function connectProvisioned(options, kind, hooks = {}, transport) {
69
72
  owner = connected.owner;
70
73
  return connected;
71
74
  }
75
+ /**
76
+ * Make a generation's flush settle when its connection closes.
77
+ *
78
+ * nats.js fails a pending flush only when it redials in place. A generation
79
+ * never does, so without this a flush awaiting a lost connection's `PONG`
80
+ * would wait forever instead of failing with the loss.
81
+ */
82
+ function settleFlushOnClose(nc) {
83
+ const flush = nc.flush.bind(nc);
84
+ nc.flush = () => Promise.race([
85
+ flush(),
86
+ nc.closed().then((error) => {
87
+ throw error ?? new ClosedConnectionError();
88
+ }),
89
+ ]);
90
+ return nc;
91
+ }
72
92
  /** One signed-admission connection path for OAuth and provisioned runtimes. */
73
93
  export async function connectAdmitted(options) {
74
94
  // Browsers cannot load the protocol build synchronously: load it once here.
@@ -285,7 +305,6 @@ export async function connectAdmitted(options) {
285
305
  ? connect.authenticator
286
306
  : [connect.authenticator],
287
307
  inboxPrefix,
288
- maxReconnectAttempts: 0,
289
308
  timeoutMs: options.timeout ?? 30_000,
290
309
  },
291
310
  };
@@ -308,14 +327,13 @@ export async function connectAdmitted(options) {
308
327
  prepare,
309
328
  readAdmission,
310
329
  open: async (connect) => {
311
- const nc = await transport.connect({
330
+ const nc = settleFlushOnClose(await transport.connect({
312
331
  servers: connect.servers,
313
332
  authenticator: connect.authenticators,
314
333
  inboxPrefix,
315
- maxReconnectAttempts: 0,
316
334
  reconnect: false,
317
335
  timeout: connect.timeoutMs,
318
- });
336
+ }));
319
337
  const credential = preparedCredentials.get(connect);
320
338
  if (!credential) {
321
339
  await nc.close();
@@ -436,6 +454,8 @@ export async function connectAdmitted(options) {
436
454
  // Set when the attachment this renewal leased closed under it: ordinary
437
455
  // transport recovery then owns readmission, and this failure ends nothing.
438
456
  let withdrawn = false;
457
+ // Set when the renewal failed without Auth refusing it, so another runs.
458
+ let retry = false;
439
459
  const task = (async () => {
440
460
  // A reduction can withdraw the attachment while the existing admission
441
461
  // pipeline is preparing its replacement. Explicit renewal must join that
@@ -506,14 +526,15 @@ export async function connectAdmitted(options) {
506
526
  renewalTask = task
507
527
  .catch(async (error) => {
508
528
  if (!signal.aborted && !manager.isClosed() && !withdrawn) {
509
- await manager.terminate(error instanceof AuthError || error instanceof TransportError
510
- ? error
511
- : new TransportError({
512
- code: "trellis.transport.unavailable",
513
- message: "Authority renewal is unavailable.",
514
- hint: "Reconnect when the runtime is available.",
515
- cause: error,
516
- }));
529
+ // Only a verified answer that retires or reduces this session ends
530
+ // it. Auth sends no unsigned refusal: when it is overloaded or slow,
531
+ // the admission reply never comes and the renewal times out. That is
532
+ // unavailability, so renewal runs again; once the installed
533
+ // authority expires, it no longer authorizes application work.
534
+ if (error instanceof AuthError)
535
+ await manager.terminate(error);
536
+ else
537
+ retry = true;
517
538
  }
518
539
  throw error;
519
540
  })
@@ -522,16 +543,25 @@ export async function connectAdmitted(options) {
522
543
  renewalTask = undefined;
523
544
  renewalAbort = undefined;
524
545
  }
546
+ if (renewalTask || manager.isClosed() || options.signal?.aborted)
547
+ return;
525
548
  // One trailing renewal covers every notice received meanwhile.
526
- if (renewalNoticed &&
527
- !renewalTask &&
528
- !manager.isClosed() &&
529
- !options.signal?.aborted) {
549
+ if (renewalNoticed) {
530
550
  renewalNoticed = false;
531
551
  void refreshAuthority().catch(() => {
532
552
  /* typed failure is retained by closed() */
533
553
  });
534
554
  }
555
+ else if (retry) {
556
+ if (renewalTimer !== undefined)
557
+ clearTimeout(renewalTimer);
558
+ renewalTimer = setTimeout(() => {
559
+ renewalTimer = undefined;
560
+ void refreshAuthority().catch(() => {
561
+ /* each failure schedules its own retry */
562
+ });
563
+ }, RENEWAL_RETRY_MS);
564
+ }
535
565
  });
536
566
  return renewalTask;
537
567
  };
@@ -545,12 +575,14 @@ export async function connectAdmitted(options) {
545
575
  admission: credential,
546
576
  natsSentinel: options.natsSentinel,
547
577
  });
548
- nc = await transport.connect({
578
+ nc = settleFlushOnClose(await transport.connect({
549
579
  servers: options.servers,
550
580
  ...authOptions,
551
- maxReconnectAttempts: 0,
581
+ // Like every later generation, the first never reconnects in place: a
582
+ // lost connection is replaced by a freshly admitted generation.
583
+ reconnect: false,
552
584
  timeout: options.timeout ?? 30_000,
553
- });
585
+ }));
554
586
  credentials.set(nc, credential);
555
587
  const admission = await readAdmission(nc);
556
588
  const prepared = {
package/client_connect.js CHANGED
@@ -31,12 +31,17 @@ export function connectClientWithDeps(args, deps) {
31
31
  window.opener.postMessage({ type: APPROVAL_MESSAGE, href: landed.href }, location.origin);
32
32
  return Result.err(new AuthError({ reason: "OAuthApprovalWindow" }));
33
33
  }
34
- await initializeProtocolWasm();
35
- const opened = (await BrowserOAuthClient.open({
36
- issuer: args.trellisUrl,
37
- clientId: args.auth.clientId,
38
- credentialHandle: args.auth.credentialHandle ?? args.auth.clientId,
39
- })).take();
34
+ // Discovery and custody need no protocol module, so they load
35
+ // alongside it.
36
+ const [, discovered] = await Promise.all([
37
+ initializeProtocolWasm(),
38
+ BrowserOAuthClient.open({
39
+ issuer: args.trellisUrl,
40
+ clientId: args.auth.clientId,
41
+ credentialHandle: args.auth.credentialHandle ?? args.auth.clientId,
42
+ }),
43
+ ]);
44
+ const opened = discovered.take();
40
45
  if (isErr(opened))
41
46
  return Result.err(opened.error);
42
47
  const oauth = opened;
@@ -90,7 +90,7 @@ const ulidPattern = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
90
90
  */
91
91
  function checkLimits(value, limits) {
92
92
  const count = typeof value === "string"
93
- ? [...value].length
93
+ ? codePointCount(value, limits)
94
94
  : Array.isArray(value)
95
95
  ? value.length
96
96
  : undefined;
@@ -107,6 +107,28 @@ function checkLimits(value, limits) {
107
107
  fail(`a value of at most ${limits.max}`);
108
108
  }
109
109
  }
110
+ /**
111
+ * Count a string's code points as string iteration does: a surrogate pair is
112
+ * one, a lone surrogate is one. A string has between half its UTF-16 length
113
+ * and its UTF-16 length in code points, so when that whole range satisfies
114
+ * the limits the exact count cannot change the outcome and is skipped.
115
+ */
116
+ function codePointCount(value, limits) {
117
+ const units = value.length;
118
+ if ((limits.maxCount === undefined || units <= limits.maxCount) &&
119
+ (limits.minCount === undefined || Math.ceil(units / 2) >= limits.minCount))
120
+ return units;
121
+ let count = 0;
122
+ for (let index = 0; index < units; index++, count++) {
123
+ const unit = value.charCodeAt(index);
124
+ if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < units) {
125
+ const next = value.charCodeAt(index + 1);
126
+ if (next >= 0xdc00 && next <= 0xdfff)
127
+ index++;
128
+ }
129
+ }
130
+ return count;
131
+ }
110
132
  /** Accept only values JSON can represent, so `json` round-trips exactly. */
111
133
  function jsonValue(value) {
112
134
  if (value === null || typeof value === "boolean" || typeof value === "string")
@@ -169,50 +191,49 @@ export const codecs = Object.freeze({
169
191
  });
170
192
  },
171
193
  model(fields) {
172
- const known = new Set(Object.keys(fields));
173
- const preserveUnknown = (source, target) => {
174
- for (const [name, value] of Object.entries(source)) {
194
+ // Resolve the field table once, not on every value.
195
+ const names = Object.keys(fields);
196
+ const known = new Set(names);
197
+ const optional = names.map((name) => "optional" in fields[name]);
198
+ const decoders = names.map((name) => fields[name].decode);
199
+ const encoders = names.map((name) => fields[name].encode);
200
+ const isEnumerable = Object.prototype.propertyIsEnumerable;
201
+ const transform = (value, convert) => {
202
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
203
+ return fail("object");
204
+ }
205
+ const source = value;
206
+ const target = {};
207
+ let ownKnown = 0;
208
+ for (let index = 0; index < names.length; index++) {
209
+ const name = names[index];
210
+ if (isEnumerable.call(source, name))
211
+ ownKnown++;
212
+ const fieldValue = source[name];
213
+ if (fieldValue === undefined && optional[index])
214
+ continue;
215
+ target[name] = convert[index](fieldValue);
216
+ }
217
+ // Carry fields this contract version does not know through unchanged.
218
+ // When every own key is a known field there is nothing to copy.
219
+ const keys = Object.keys(source);
220
+ if (keys.length === ownKnown)
221
+ return target;
222
+ for (const name of keys) {
175
223
  if (known.has(name))
176
224
  continue;
225
+ // Define rather than assign: assigning `__proto__` would invoke the
226
+ // inherited setter instead of keeping it as an ordinary key.
177
227
  Object.defineProperty(target, name, {
178
- value,
228
+ value: source[name],
179
229
  enumerable: true,
180
230
  writable: true,
181
231
  configurable: true,
182
232
  });
183
233
  }
234
+ return target;
184
235
  };
185
- return codec((value) => {
186
- if (value === null ||
187
- typeof value !== "object" ||
188
- Array.isArray(value)) {
189
- return fail("object");
190
- }
191
- const source = value;
192
- const decoded = {};
193
- for (const [name, field] of Object.entries(fields)) {
194
- if (source[name] === undefined && "optional" in field)
195
- continue;
196
- decoded[name] = field.decode(source[name]);
197
- }
198
- preserveUnknown(source, decoded);
199
- return decoded;
200
- }, (value) => {
201
- if (value === null ||
202
- typeof value !== "object" ||
203
- Array.isArray(value)) {
204
- return fail("object");
205
- }
206
- const encoded = {};
207
- for (const [name, field] of Object.entries(fields)) {
208
- const fieldValue = value[name];
209
- if (fieldValue === undefined && "optional" in field)
210
- continue;
211
- encoded[name] = field.encode(fieldValue);
212
- }
213
- preserveUnknown(value, encoded);
214
- return encoded;
215
- });
236
+ return codec((value) => transform(value, decoders), (value) => transform(value, encoders));
216
237
  },
217
238
  named(_name, value) {
218
239
  return codec((input) => value.decode(input), (input) => value.encode(input));
@@ -0,0 +1,12 @@
1
+ // Generated by Trellis. Do not edit.
2
+ /** This build's package evidence, submitted to Auth to install it. */
3
+ export declare const packageEvidence: {
4
+ readonly rootPackage: string;
5
+ readonly rootDigest: string;
6
+ readonly packages: readonly {
7
+ readonly name: string;
8
+ readonly version: string;
9
+ readonly digest: string;
10
+ readonly source: string;
11
+ }[];
12
+ };