@oatscenter/trellis 0.100.0-rc.19 → 0.100.0-rc.21

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 (31) hide show
  1. package/auth/device_activation.d.ts +3 -0
  2. package/auth/device_activation.js +1 -1
  3. package/auth/issuer_trust.d.ts +2 -1
  4. package/auth/issuer_trust.js +2 -2
  5. package/auth/oauth_core.d.ts +13 -0
  6. package/auth/oauth_core.js +1 -1
  7. package/device/activation.js +2 -1
  8. package/device.js +4 -2
  9. package/internal_sdk/generated/apis/auth/mod.d.ts +1 -1
  10. package/internal_sdk/generated/apis/auth/mod.js +5 -5
  11. package/internal_sdk/generated/apis/core/mod.js +4 -4
  12. package/internal_sdk/generated/apis/events/mod.js +4 -4
  13. package/internal_sdk/generated/apis/health/mod.js +4 -4
  14. package/internal_sdk/generated/apis/jobs/mod.js +4 -4
  15. package/internal_sdk/generated/apis/state/mod.js +4 -4
  16. package/internal_sdk/generated/package.json +2 -2
  17. package/internal_sdk/generated/participants/eventsRuntime/mod.js +4 -4
  18. package/internal_sdk/generated/participants/healthRuntime/mod.js +4 -4
  19. package/internal_sdk/generated/participants/jobsRuntime/mod.js +4 -4
  20. package/internal_sdk/generated/participants/platform/mod.d.ts +1 -1
  21. package/internal_sdk/generated/participants/platform/mod.js +6 -6
  22. package/internal_sdk/generated/types/_internal/p0.d.ts +1 -1
  23. package/internal_sdk/generated/types/_internal/p0.js +1 -1
  24. package/native/certificate_acceptance.d.ts +39 -13
  25. package/native/certificate_acceptance.js +138 -33
  26. package/native/discovery.js +5 -1
  27. package/native/oauth.js +3 -1
  28. package/package.json +3 -2
  29. package/runtime_transport.js +11 -2
  30. package/service/runtime/core.js +17 -4
  31. package/service/runtime/service.js +37 -33
@@ -2120,7 +2120,7 @@ export type AuthServiceUpdate = {
2120
2120
  readonly participantDigest: AuthDigest;
2121
2121
  readonly participantId: string;
2122
2122
  readonly requestedAt: ReturnType<typeof codecs.timestamp.decode>;
2123
- readonly reviewUrl: string;
2123
+ readonly reviewUrl?: string;
2124
2124
  readonly revision: AuthRevision;
2125
2125
  readonly state: AuthServiceUpdateState;
2126
2126
  readonly updateId: ReturnType<typeof codecs.ulid.decode>;
@@ -1110,7 +1110,7 @@ export const AuthServiceUpdateCodec = codecs.recursive(() => codecs.named("trell
1110
1110
  participantDigest: codecs.ref(() => AuthDigestCodec),
1111
1111
  participantId: codecs.string,
1112
1112
  requestedAt: codecs.timestamp,
1113
- reviewUrl: codecs.string,
1113
+ reviewUrl: codecs.optional(codecs.string),
1114
1114
  revision: codecs.ref(() => AuthRevisionCodec),
1115
1115
  state: codecs.ref(() => AuthServiceUpdateStateCodec),
1116
1116
  updateId: codecs.ulid
@@ -1,4 +1,5 @@
1
1
  import { type Result } from "@oatscenter/result";
2
+ import type { HttpRequest } from "../auth/oauth_core.ts";
2
3
  import { AuthError } from "../errors/AuthError.ts";
3
4
  /** Accepts only a certificate whose issuer has this SHA-256 fingerprint. */
4
5
  export declare const CERTIFICATE_FINGERPRINT_ENV = "TRELLIS_CERTIFICATE_FINGERPRINT";
@@ -19,16 +20,41 @@ export interface CertificateAcceptance {
19
20
  */
20
21
  export declare function certificateAcceptanceFor(program: string): CertificateAcceptance;
21
22
  /**
22
- * Makes this process trust the certificate a Trellis at `url` presents,
23
- * accepting one nothing vouches for the way a browser would.
23
+ * Trusts the issuer accepted for `named`'s endpoint at `endpoints` too, which
24
+ * that installation named itself, such as its sign-in and its NATS servers.
25
+ * @internal
26
+ */
27
+ export declare function trustNamedEndpoints(named: string, endpoints: readonly string[]): void;
28
+ /**
29
+ * The issuers accepted for any of `servers`, for a connection to them.
30
+ * @internal
31
+ */
32
+ export declare function acceptedIssuersFor(servers: readonly string[]): string[] | undefined;
33
+ /**
34
+ * `fetch`, trusting the issuer accepted for `input`'s endpoint when there is
35
+ * one.
36
+ * @internal
37
+ */
38
+ export declare function installationFetch(input: string | URL, init?: HttpRequest): Promise<Response>;
39
+ /**
40
+ * A WebSocket to `url`, trusting the issuer accepted for its endpoint when
41
+ * there is one.
42
+ * @internal
43
+ */
44
+ export declare function installationWebSocket(url: string): WebSocket;
45
+ /**
46
+ * Makes Trellis's connections to the Trellis at `url` trust the certificate
47
+ * it presents, accepting one nothing vouches for the way a browser would.
24
48
  *
25
- * A server the system trust store vouches for needs nothing. Otherwise the
26
- * certificate accepted earlier for this server is trusted, and a different one
27
- * is refused. On first contact the issuer's SHA-256 fingerprint must match
28
- * `acceptance.fingerprint` (or `TRELLIS_CERTIFICATE_FINGERPRINT`), or
29
- * `TRELLIS_ACCEPT_SELF_SIGNED` must be `1`, or the operator accepts it on the
30
- * terminal. The accepted issuer is saved in `acceptance.directory` and added to
31
- * this process's TLS trust, which `fetch` and NATS connections use.
49
+ * A server the system trust store vouches for needs nothing, unless it fails
50
+ * an explicitly requested fingerprint. Otherwise the certificate accepted
51
+ * earlier for this server is trusted, and a different one is refused. On first
52
+ * contact the issuer's SHA-256 fingerprint must match `acceptance.fingerprint`
53
+ * (or `TRELLIS_CERTIFICATE_FINGERPRINT`), or `TRELLIS_ACCEPT_SELF_SIGNED` must
54
+ * be `1`, or the operator accepts it on the terminal. The accepted issuer is
55
+ * saved in `acceptance.directory`. Only this installation's endpoints trust
56
+ * it, through `discoverNativeOAuth` and the connections Trellis opens to
57
+ * them; the rest of the process, including `fetch`, does not.
32
58
  */
33
59
  export declare function acceptServerCertificate(url: string, acceptance: CertificateAcceptance): Promise<Result<void, AuthError>>;
34
60
  /**
@@ -38,8 +64,8 @@ export declare function acceptServerCertificate(url: string, acceptance: Certifi
38
64
  */
39
65
  export declare function acceptServerCertificateFor(url: string, participant: string): Promise<void>;
40
66
  /**
41
- * Trusts the certificates `participant` already accepted, for a connection
42
- * that only reaches the broker. Activation, which reaches the server's HTTPS
43
- * address, accepts them first.
67
+ * Trusts the certificates `participant` already accepted at `servers`, for a
68
+ * connection that only reaches the broker. Activation, which reaches the
69
+ * server's HTTPS address, accepts them first.
44
70
  */
45
- export declare function trustAcceptedCertificatesFor(participant: string): Promise<void>;
71
+ export declare function trustAcceptedCertificatesFor(participant: string, servers: readonly string[]): Promise<void>;
@@ -2,8 +2,10 @@ import { chmod, mkdir, readdir, readFile, rename, writeFile, } from "node:fs/pro
2
2
  import { homedir } from "node:os";
3
3
  import { isAbsolute, join } from "node:path";
4
4
  import { createInterface } from "node:readline/promises";
5
- import { X509Certificate } from "node:crypto";
6
- import { connect, getCACertificates, setDefaultCACertificates, } from "node:tls";
5
+ import { randomUUID, X509Certificate } from "node:crypto";
6
+ import { Readable } from "node:stream";
7
+ import { connect } from "node:tls";
8
+ import { Agent, request, WebSocket as AgentWebSocket } from "undici";
7
9
  import { err, ok } from "@oatscenter/result";
8
10
  import { AuthError } from "../errors/AuthError.js";
9
11
  /** Accepts only a certificate whose issuer has this SHA-256 fingerprint. */
@@ -22,16 +24,118 @@ export function certificateAcceptanceFor(program) {
22
24
  return { directory: join(state, "trellis", program, "servers") };
23
25
  }
24
26
  /**
25
- * Makes this process trust the certificate a Trellis at `url` presents,
26
- * accepting one nothing vouches for the way a browser would.
27
+ * The issuers accepted for each endpoint (`host:port`), which only Trellis's
28
+ * own connections to that endpoint trust. Nothing else in the process does.
29
+ */
30
+ const acceptedIssuers = new Map();
31
+ const defaultPorts = {
32
+ "https:": "443",
33
+ "wss:": "443",
34
+ "http:": "80",
35
+ "ws:": "80",
36
+ "tls:": "4222",
37
+ "nats:": "4222",
38
+ };
39
+ function endpointOf(url) {
40
+ const parsed = new URL(url);
41
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
42
+ return `${host}:${parsed.port || defaultPorts[parsed.protocol] || ""}`;
43
+ }
44
+ /**
45
+ * Trusts the issuer accepted for `named`'s endpoint at `endpoints` too, which
46
+ * that installation named itself, such as its sign-in and its NATS servers.
47
+ * @internal
48
+ */
49
+ export function trustNamedEndpoints(named, endpoints) {
50
+ const issuers = acceptedIssuers.get(endpointOf(named));
51
+ if (issuers)
52
+ for (const endpoint of endpoints)
53
+ acceptedIssuers.set(endpointOf(endpoint), issuers);
54
+ }
55
+ /**
56
+ * The issuers accepted for any of `servers`, for a connection to them.
57
+ * @internal
58
+ */
59
+ export function acceptedIssuersFor(servers) {
60
+ const issuers = new Set(servers.flatMap((server) => acceptedIssuers.get(endpointOf(server)) ?? []));
61
+ return issuers.size ? [...issuers] : undefined;
62
+ }
63
+ /** One connection pool per set of accepted issuers. */
64
+ const agents = new WeakMap();
65
+ function agentFor(url) {
66
+ const issuers = acceptedIssuers.get(endpointOf(url));
67
+ if (!issuers)
68
+ return undefined;
69
+ let agent = agents.get(issuers);
70
+ if (!agent) {
71
+ agent = new Agent({ connect: { ca: [...issuers] } });
72
+ agents.set(issuers, agent);
73
+ }
74
+ return agent;
75
+ }
76
+ /**
77
+ * `fetch`, trusting the issuer accepted for `input`'s endpoint when there is
78
+ * one.
79
+ * @internal
80
+ */
81
+ export async function installationFetch(input, init = {}) {
82
+ const dispatcher = agentFor(input);
83
+ if (!dispatcher)
84
+ return await fetch(input, init);
85
+ const headers = { ...init.headers };
86
+ if (init.body instanceof URLSearchParams)
87
+ headers["content-type"] ??=
88
+ "application/x-www-form-urlencoded;charset=UTF-8";
89
+ const received = await request(input, {
90
+ dispatcher,
91
+ method: init.method ?? "GET",
92
+ headers,
93
+ body: init.body?.toString(),
94
+ signal: init.signal,
95
+ });
96
+ // Like fetch with `redirect: "error"`; undici follows none by default.
97
+ if (received.statusCode >= 300 &&
98
+ received.statusCode < 400 &&
99
+ init.redirect === "error") {
100
+ received.body.destroy();
101
+ throw new TypeError("fetch failed: redirect");
102
+ }
103
+ const responseHeaders = new Headers();
104
+ for (const [name, value] of Object.entries(received.headers))
105
+ for (const item of [value ?? []].flat())
106
+ responseHeaders.append(name, item);
107
+ const empty = [101, 204, 205, 304].includes(received.statusCode);
108
+ if (empty)
109
+ received.body.destroy();
110
+ return new Response(empty
111
+ ? null
112
+ : Readable.toWeb(received.body), { status: received.statusCode, headers: responseHeaders });
113
+ }
114
+ /**
115
+ * A WebSocket to `url`, trusting the issuer accepted for its endpoint when
116
+ * there is one.
117
+ * @internal
118
+ */
119
+ export function installationWebSocket(url) {
120
+ const dispatcher = agentFor(url);
121
+ // Node's own WebSocket is this class, from its bundled copy of undici.
122
+ return dispatcher
123
+ ? new AgentWebSocket(url, { dispatcher })
124
+ : new WebSocket(url);
125
+ }
126
+ /**
127
+ * Makes Trellis's connections to the Trellis at `url` trust the certificate
128
+ * it presents, accepting one nothing vouches for the way a browser would.
27
129
  *
28
- * A server the system trust store vouches for needs nothing. Otherwise the
29
- * certificate accepted earlier for this server is trusted, and a different one
30
- * is refused. On first contact the issuer's SHA-256 fingerprint must match
31
- * `acceptance.fingerprint` (or `TRELLIS_CERTIFICATE_FINGERPRINT`), or
32
- * `TRELLIS_ACCEPT_SELF_SIGNED` must be `1`, or the operator accepts it on the
33
- * terminal. The accepted issuer is saved in `acceptance.directory` and added to
34
- * this process's TLS trust, which `fetch` and NATS connections use.
130
+ * A server the system trust store vouches for needs nothing, unless it fails
131
+ * an explicitly requested fingerprint. Otherwise the certificate accepted
132
+ * earlier for this server is trusted, and a different one is refused. On first
133
+ * contact the issuer's SHA-256 fingerprint must match `acceptance.fingerprint`
134
+ * (or `TRELLIS_CERTIFICATE_FINGERPRINT`), or `TRELLIS_ACCEPT_SELF_SIGNED` must
135
+ * be `1`, or the operator accepts it on the terminal. The accepted issuer is
136
+ * saved in `acceptance.directory`. Only this installation's endpoints trust
137
+ * it, through `discoverNativeOAuth` and the connections Trellis opens to
138
+ * them; the rest of the process, including `fetch`, does not.
35
139
  */
36
140
  export async function acceptServerCertificate(url, acceptance) {
37
141
  let target;
@@ -50,6 +154,13 @@ export async function acceptServerCertificate(url, acceptance) {
50
154
  const presented = await presentedIssuer(host, port);
51
155
  if (!presented)
52
156
  return err(new AuthError({ reason: "OAuthUnavailable" }));
157
+ const expected = (acceptance.fingerprint ?? process.env[CERTIFICATE_FINGERPRINT_ENV])?.trim();
158
+ const normalize = (value) => value.replaceAll(":", "").toUpperCase();
159
+ if (expected && normalize(expected) !== normalize(presented.fingerprint))
160
+ return err(new AuthError({
161
+ reason: "CertificateMismatch",
162
+ message: `${server} presents issuer fingerprint ${presented.fingerprint}, not the expected ${expected}`,
163
+ }));
53
164
  if (presented.authorized)
54
165
  return ok(undefined);
55
166
  const accepted = await readFile(file, "utf8").catch(() => undefined);
@@ -60,17 +171,11 @@ export async function acceptServerCertificate(url, acceptance) {
60
171
  reason: "CertificateChanged",
61
172
  message: `${server} presents a different certificate than the one accepted for it (accepted ${fingerprint}, presented ${presented.fingerprint}); someone may be intercepting the connection. If the operator replaced it, delete ${file} and connect again`,
62
173
  }));
63
- trust(accepted);
174
+ acceptedIssuers.set(server, [accepted]);
64
175
  return ok(undefined);
65
176
  }
66
- const expected = (acceptance.fingerprint ?? process.env[CERTIFICATE_FINGERPRINT_ENV])?.trim();
67
- const normalize = (value) => value.replaceAll(":", "").toUpperCase();
68
177
  if (expected) {
69
- if (normalize(expected) !== normalize(presented.fingerprint))
70
- return err(new AuthError({
71
- reason: "CertificateMismatch",
72
- message: `${server} presents issuer fingerprint ${presented.fingerprint}, not the expected ${expected}`,
73
- }));
178
+ // Matched above.
74
179
  }
75
180
  else if (process.env[ACCEPT_SELF_SIGNED_ENV]?.trim() === "1") {
76
181
  process.stderr.write(`Accepting ${server}'s certificate because ${ACCEPT_SELF_SIGNED_ENV}=1; its issuer's SHA-256 fingerprint is\n ${presented.fingerprint}\n`);
@@ -98,10 +203,12 @@ export async function acceptServerCertificate(url, acceptance) {
98
203
  }
99
204
  await mkdir(acceptance.directory, { recursive: true, mode: 0o700 });
100
205
  await chmod(acceptance.directory, 0o700);
101
- const staged = `${file}.${process.pid}`;
102
- await writeFile(staged, presented.pem, { mode: 0o600 });
206
+ // Unique to this attempt: another one in this process may be staging the
207
+ // same certificate.
208
+ const staged = `${file}.${randomUUID()}`;
209
+ await writeFile(staged, presented.pem, { mode: 0o600, flag: "wx" });
103
210
  await rename(staged, file);
104
- trust(presented.pem);
211
+ acceptedIssuers.set(server, [presented.pem]);
105
212
  return ok(undefined);
106
213
  }
107
214
  /**
@@ -115,25 +222,23 @@ export async function acceptServerCertificateFor(url, participant) {
115
222
  throw accepted.error;
116
223
  }
117
224
  /**
118
- * Trusts the certificates `participant` already accepted, for a connection
119
- * that only reaches the broker. Activation, which reaches the server's HTTPS
120
- * address, accepts them first.
225
+ * Trusts the certificates `participant` already accepted at `servers`, for a
226
+ * connection that only reaches the broker. Activation, which reaches the
227
+ * server's HTTPS address, accepts them first.
121
228
  */
122
- export async function trustAcceptedCertificatesFor(participant) {
229
+ export async function trustAcceptedCertificatesFor(participant, servers) {
123
230
  const { directory } = certificateAcceptanceFor(participantProgram(participant));
231
+ const issuers = [];
124
232
  for (const name of await readdir(directory).catch(() => []))
125
233
  if (name.endsWith(".pem"))
126
- trust(await readFile(join(directory, name), "utf8"));
234
+ issuers.push(await readFile(join(directory, name), "utf8"));
235
+ if (issuers.length)
236
+ for (const server of servers)
237
+ acceptedIssuers.set(endpointOf(server), issuers);
127
238
  }
128
239
  function participantProgram(participant) {
129
240
  return participant.replace(/[^A-Za-z0-9._-]/g, "_");
130
241
  }
131
- /** Adds `pem` to the CAs this process's TLS connections trust. */
132
- function trust(pem) {
133
- const current = getCACertificates("default");
134
- if (!current.includes(pem))
135
- setDefaultCACertificates([...current, pem]);
136
- }
137
242
  /**
138
243
  * The issuer that ends the chain the server presents, without trusting it,
139
244
  * and whether the system trust store already vouches for the server.
@@ -6,6 +6,7 @@ import { base64urlDecode, base64urlEncode, sha256 } from "../auth/utils.js";
6
6
  import { codecs } from "../generated_support.js";
7
7
  import { AuthError } from "../errors/AuthError.js";
8
8
  import { boundedJson, usableNonce } from "../auth/oauth_core.js";
9
+ import { installationFetch, trustNamedEndpoints, } from "./certificate_acceptance.js";
9
10
  const metadataSchema = z.object({
10
11
  issuer: z.string(),
11
12
  trellis: z.object({
@@ -54,7 +55,7 @@ function issuerOf(address) {
54
55
  /** Discover only the selected HTTPS origin (literal loopback HTTP is allowed), without redirects. Retained custody never repins from discovery. */
55
56
  export async function discoverNativeOAuth(origin, options = {}) {
56
57
  try {
57
- const get = (url) => fetch(url, {
58
+ const get = (url) => installationFetch(url, {
58
59
  redirect: "error",
59
60
  credentials: "omit",
60
61
  signal: AbortSignal.any([
@@ -76,7 +77,9 @@ export async function discoverNativeOAuth(origin, options = {}) {
76
77
  const resource = resourceSchema.parse(await boundedJson(named));
77
78
  if (issuerOf(resource.resource) !== issuer)
78
79
  throw new AuthError({ reason: "InvalidIssuer" });
80
+ const address = issuer;
79
81
  issuer = issuerOf(resource.authorization_servers[0]);
82
+ trustNamedEndpoints(address, [issuer]);
80
83
  response = await get(`${issuer}/.well-known/oauth-authorization-server`);
81
84
  if (response.status === 429)
82
85
  throw new AuthError({ reason: "OAuthBusy" });
@@ -120,6 +123,7 @@ export async function discoverNativeOAuth(origin, options = {}) {
120
123
  }
121
124
  // Native NATS is preferred; a Trellis that keeps it private advertises
122
125
  // only its WebSocket. One connection can't mix the two.
126
+ trustNamedEndpoints(issuer, metadata.trellis.natsEndpoints);
123
127
  const native = metadata.trellis.natsEndpoints.filter((server) => /^(nats|tls):/.test(server));
124
128
  const nativeServers = native.length > 0 ? native : [...metadata.trellis.natsEndpoints];
125
129
  if (nativeServers.length === 0)
package/native/oauth.js CHANGED
@@ -7,6 +7,7 @@ import { dpopThumbprint, postWithDpop, verifyAdmission, } from "../auth/oauth_co
7
7
  import { base64urlEncode } from "../auth/utils.js";
8
8
  import { AuthError } from "../errors/AuthError.js";
9
9
  import { authenticateIssuerChain } from "../auth/issuer_trust.js";
10
+ import { installationFetch } from "./certificate_acceptance.js";
10
11
  import { MemoryNativeOAuthCustody, validateNativeScope, validateNativeTrust, } from "./custody.js";
11
12
  import { discoverNativeOAuth } from "./discovery.js";
12
13
  const tokenSchema = z.object({
@@ -246,6 +247,7 @@ export class NativeOAuthClient {
246
247
  },
247
248
  runtimeId: this.runtimeId,
248
249
  sessionPublicKey: this.auth.sessionKey,
250
+ fetch: installationFetch,
249
251
  signal: AbortSignal.any([
250
252
  AbortSignal.timeout(30000),
251
253
  ...(signal ? [signal] : []),
@@ -280,7 +282,7 @@ export class NativeOAuthClient {
280
282
  ? discovered.error
281
283
  : new AuthError({ reason: "OAuthTrustUnavailable" });
282
284
  this.#dpopNonce = discovered.orThrow().dpopNonce;
283
- const owner = await authenticateIssuerChain(this.scope.issuer, this.trust, discovered.orThrow().trust, signal, this.#owner);
285
+ const owner = await authenticateIssuerChain(this.scope.issuer, this.trust, discovered.orThrow().trust, signal, this.#owner, installationFetch);
284
286
  try {
285
287
  await this.#retainTrust(owner);
286
288
  if (!this.#connected)
package/package.json CHANGED
@@ -51,7 +51,7 @@
51
51
  "@nats-io/obj": "^3.4.0",
52
52
  "@nats-io/transport-node": "^3.4.0",
53
53
  "@noble/hashes": "1.8.0",
54
- "@oatscenter/result": "0.100.0-rc.19",
54
+ "@oatscenter/result": "0.100.0-rc.21",
55
55
  "@opentelemetry/api": "^1.9.1",
56
56
  "@opentelemetry/context-async-hooks": "~2.11.0",
57
57
  "@opentelemetry/core": "~2.11.0",
@@ -67,10 +67,11 @@
67
67
  "tweetnacl": "^1.0.3",
68
68
  "typebox": "^1.1.33",
69
69
  "ulid": "^3.0.2",
70
+ "undici": "^8.12.3",
70
71
  "uqr": "0.1.3",
71
72
  "zod": "^4.3.6"
72
73
  },
73
- "version": "0.100.0-rc.19",
74
+ "version": "0.100.0-rc.21",
74
75
  "type": "module",
75
76
  "license": "Apache-2.0",
76
77
  "publishConfig": {
@@ -45,11 +45,20 @@ export async function loadDefaultRuntimeTransport() {
45
45
  }
46
46
  return {
47
47
  connect: async (options) => {
48
+ // The issuer accepted for these servers' installation, and only it.
49
+ const { acceptedIssuersFor, installationWebSocket } = await import("./native/certificate_acceptance.js");
48
50
  if (usesWebSocketTransport(options.servers)) {
49
- return await wsconnect(options);
51
+ return await wsconnect({
52
+ ...options,
53
+ wsFactory: async (url) => ({
54
+ socket: installationWebSocket(url),
55
+ encrypted: url.startsWith("wss://"),
56
+ }),
57
+ });
50
58
  }
51
59
  const { connect } = await import("@nats-io/transport-node");
52
- return await connect(options);
60
+ const ca = acceptedIssuersFor(Array.isArray(options.servers) ? options.servers : [options.servers]);
61
+ return await connect(ca ? { ...options, tls: { ca: ca.join("\n") } } : options);
53
62
  },
54
63
  };
55
64
  }
@@ -255,6 +255,8 @@ export class TrellisServiceRuntime extends Trellis {
255
255
  #operationTransport = new Map();
256
256
  /** Closes shared operation intake queues, releasing any queued delivery pins. */
257
257
  #operationIntakeClosers = new Set();
258
+ /** Lease renewal timers of executions this process owns; stopping ends them. */
259
+ #operationLeaseHeartbeats = new Set();
258
260
  #operationRecoverers = new Map();
259
261
  #operationRecoveryIndexes = new Set();
260
262
  #operationRecoveryAbort = new AbortController();
@@ -2697,13 +2699,18 @@ export class TrellisServiceRuntime extends Trellis {
2697
2699
  return next;
2698
2700
  };
2699
2701
  const startLeaseHeartbeat = (runtime, fence) => {
2702
+ const stopHeartbeat = () => {
2703
+ clearInterval(leaseHeartbeat);
2704
+ this.#operationLeaseHeartbeats.delete(leaseHeartbeat);
2705
+ };
2700
2706
  const leaseHeartbeat = setInterval(() => {
2701
2707
  // Cancellation aborts the handler signal so cleanup can observe it,
2702
2708
  // but cleanup must keep renewing the lease until it finalizes. Only
2703
- // a terminal operation (or lost ownership, handled below) stops
2704
- // renewal, matching the owner-continues-renewing contract.
2709
+ // a terminal operation, lost ownership (handled below) or stopping
2710
+ // the service ends renewal, matching the owner-continues-renewing
2711
+ // contract.
2705
2712
  if (runtime.terminal) {
2706
- clearInterval(leaseHeartbeat);
2713
+ stopHeartbeat();
2707
2714
  return;
2708
2715
  }
2709
2716
  void this.#queueOperationFrame(runtime, async () => {
@@ -2752,9 +2759,10 @@ export class TrellisServiceRuntime extends Trellis {
2752
2759
  this.#operations.delete(runtime.id);
2753
2760
  }
2754
2761
  this.#releaseOperationFence(runtime.id, fence);
2755
- clearInterval(leaseHeartbeat);
2762
+ stopHeartbeat();
2756
2763
  });
2757
2764
  }, 10_000);
2765
+ this.#operationLeaseHeartbeats.add(leaseHeartbeat);
2758
2766
  };
2759
2767
  const watchCancellation = (runtime, fence) => {
2760
2768
  let reading = false;
@@ -3416,6 +3424,11 @@ export class TrellisServiceRuntime extends Trellis {
3416
3424
  }
3417
3425
  this.#operationRecoverers.clear();
3418
3426
  this.#operationRecoveryIndexes.clear();
3427
+ // A stopped process renews nothing; its leases expire for recovery.
3428
+ for (const heartbeat of this.#operationLeaseHeartbeats) {
3429
+ clearInterval(heartbeat);
3430
+ }
3431
+ this.#operationLeaseHeartbeats.clear();
3419
3432
  for (const close of this.#operationIntakeClosers)
3420
3433
  close();
3421
3434
  for (const drain of this.#operationIntakeDrains) {
@@ -1675,43 +1675,47 @@ async function awaitServiceUpdate(connected, participant, log, signal) {
1675
1675
  participantId: participant.identity,
1676
1676
  packageEvidence: participant.packageEvidence,
1677
1677
  })).update;
1678
- let update = await submit();
1679
- let shown;
1680
- let delay = 1_000;
1681
- for (;;) {
1682
- if (update.state === "applied")
1683
- return;
1684
- if (update.state === "rejected")
1685
- throw new Error(`An administrator rejected this build's update (${update.reviewUrl})`);
1686
- if (update.state === "superseded") {
1687
- update = await submit();
1688
- continue;
1689
- }
1690
- if (shown !== update.reviewUrl) {
1691
- shown = update.reviewUrl;
1692
- log.warn({ participant: participant.identity, reviewUrl: shown }, "This build asks for new access; waiting for an administrator to approve it");
1693
- console.error(`\n${participant.identity} needs an administrator to approve its update.\nOpen ${shown}\nor scan:\n${renderUnicodeCompact(shown)}`);
1694
- }
1695
- await new Promise((resolve, reject) => {
1696
- const timer = setTimeout(resolve, delay);
1697
- signal?.addEventListener("abort", () => {
1698
- clearTimeout(timer);
1699
- reject(signal.reason);
1700
- }, { once: true });
1701
- });
1702
- delay = Math.min(delay * 2, 15_000);
1703
- try {
1678
+ try {
1679
+ let update = await submit();
1680
+ let shown;
1681
+ let delay = 1_000;
1682
+ for (;;) {
1683
+ if (update.state === "applied")
1684
+ return;
1685
+ if (update.state === "rejected")
1686
+ throw new Error(`An administrator rejected this build's update (${update.reviewUrl ?? `trellis svc ${update.deploymentId} updates`})`);
1687
+ if (update.state === "superseded") {
1688
+ update = await submit();
1689
+ continue;
1690
+ }
1691
+ if (shown !== update.updateId) {
1692
+ shown = update.updateId;
1693
+ const reviewUrl = update.reviewUrl;
1694
+ log.warn({ participant: participant.identity, reviewUrl }, "This build asks for new access; waiting for an administrator to approve it");
1695
+ console.error(reviewUrl === undefined
1696
+ ? `\n${participant.identity} needs an administrator to approve its update with\n trellis svc ${update.deploymentId} approve`
1697
+ : `\n${participant.identity} needs an administrator to approve its update.\nOpen ${reviewUrl}\nor scan:\n${renderUnicodeCompact(reviewUrl)}`);
1698
+ }
1699
+ await new Promise((resolve, reject) => {
1700
+ const timer = setTimeout(resolve, delay);
1701
+ signal?.addEventListener("abort", () => {
1702
+ clearTimeout(timer);
1703
+ reject(signal.reason);
1704
+ }, { once: true });
1705
+ });
1706
+ delay = Math.min(delay * 2, 15_000);
1704
1707
  update = (await client.requestServiceUpdate("ServiceUpdates.Status", {
1705
1708
  updateId: update.updateId,
1706
1709
  })).update;
1707
1710
  }
1708
- catch (cause) {
1709
- // Approval retires this session. Connecting again shows whether the
1710
- // update installed; if not, Submit returns the same update.
1711
- if (cause instanceof TransportError)
1712
- return;
1713
- throw cause;
1714
- }
1711
+ }
1712
+ catch (cause) {
1713
+ // Approval retires this session, sometimes before Submit's reply arrives.
1714
+ // Connecting again shows whether the update installed; if not, Submit
1715
+ // returns the same update.
1716
+ if (cause instanceof TransportError)
1717
+ return;
1718
+ throw cause;
1715
1719
  }
1716
1720
  }
1717
1721
  /**