@oatscenter/trellis 0.100.0-rc.20 → 0.100.0-rc.22

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.
@@ -2,6 +2,7 @@ import type { StaticDecode } from "typebox";
2
2
  import { Type } from "typebox";
3
3
  import type { GeneratedParticipant } from "../participant_runtime/participant.ts";
4
4
  import { createAuth } from "./session_auth.ts";
5
+ import type { HttpFetch } from "./oauth_core.ts";
5
6
  export declare const DeviceActivationPayloadSchema: Type.TObject<{
6
7
  v: Type.TLiteral<1>;
7
8
  publicIdentityKey: Type.TString;
@@ -51,6 +52,8 @@ export declare function verifyDeviceConfirmationCode(input: {
51
52
  /** Submit one proof-bound device enrollment request. */
52
53
  export declare function requestDeviceEnrollment(args: {
53
54
  trellisUrl: string;
55
+ /** Defaults to `fetch`. */
56
+ fetch?: HttpFetch;
54
57
  publicIdentityKey: string;
55
58
  identitySeed: Uint8Array | string;
56
59
  sessionIdentity: Awaited<ReturnType<typeof createAuth>>;
@@ -73,6 +76,8 @@ export declare function requestDeviceEnrollment(args: {
73
76
  */
74
77
  export declare function waitForDeviceActivation(args: {
75
78
  trellisUrl: string;
79
+ /** Defaults to `fetch`. */
80
+ fetch?: HttpFetch;
76
81
  publicIdentityKey: string;
77
82
  identitySeed: Uint8Array | string;
78
83
  activationKey: Uint8Array | string;
@@ -198,7 +198,7 @@ export async function requestDeviceEnrollment(args) {
198
198
  provisioningSecret: args.provisioningSecret,
199
199
  }),
200
200
  };
201
- const response = await fetch(new URL("/auth/device/enroll", args.trellisUrl), {
201
+ const response = await (args.fetch ?? fetch)(new URL("/auth/device/enroll", args.trellisUrl), {
202
202
  method: "POST",
203
203
  signal: args.signal,
204
204
  headers: { "Content-Type": "application/json" },
@@ -1,3 +1,4 @@
1
+ import type { HttpFetch } from "./oauth_core.ts";
1
2
  import { SessionAuthorityOwner, type RuntimeAuthorizationTrust } from "./authority.ts";
2
3
  /** Authenticate a discovery hint from the credential's existing pin, without consuming OAuth credentials. */
3
- export declare function authenticateIssuerChain(issuer: string, anchor: RuntimeAuthorizationTrust, target: RuntimeAuthorizationTrust, signal?: AbortSignal, existingOwner?: SessionAuthorityOwner): Promise<SessionAuthorityOwner>;
4
+ export declare function authenticateIssuerChain(issuer: string, anchor: RuntimeAuthorizationTrust, target: RuntimeAuthorizationTrust, signal?: AbortSignal, existingOwner?: SessionAuthorityOwner, request?: HttpFetch): Promise<SessionAuthorityOwner>;
@@ -2,7 +2,7 @@ import { AuthError } from "../errors/AuthError.js";
2
2
  import { issuerChainSchema, signedBytes } from "./protocol_wasm.js";
3
3
  import { SessionAuthorityOwner, } from "./authority.js";
4
4
  /** Authenticate a discovery hint from the credential's existing pin, without consuming OAuth credentials. */
5
- export async function authenticateIssuerChain(issuer, anchor, target, signal, existingOwner) {
5
+ export async function authenticateIssuerChain(issuer, anchor, target, signal, existingOwner, request = fetch) {
6
6
  const owner = existingOwner ??
7
7
  new SessionAuthorityOwner({
8
8
  instanceId: anchor.instanceId,
@@ -21,7 +21,7 @@ export async function authenticateIssuerChain(issuer, anchor, target, signal, ex
21
21
  pinnedKeyId: anchor.issuer.keyId,
22
22
  targetKeyId: target.issuer.keyId,
23
23
  }).toString();
24
- const response = await fetch(url, {
24
+ const response = await request(url, {
25
25
  credentials: "omit",
26
26
  redirect: "error",
27
27
  signal: AbortSignal.any([
@@ -26,6 +26,17 @@ export type TokenResponse = Readonly<{
26
26
  }>;
27
27
  /** One bounded `DPoP-Nonce` value, or undefined. @internal */
28
28
  export declare function usableNonce(value: string | null): string | undefined;
29
+ /** The request options Trellis's own HTTPS requests use. @internal */
30
+ export type HttpRequest = {
31
+ method?: string;
32
+ headers?: Record<string, string>;
33
+ body?: string | URLSearchParams;
34
+ signal?: AbortSignal;
35
+ redirect?: RequestRedirect;
36
+ credentials?: RequestCredentials;
37
+ };
38
+ /** The part of `fetch` Trellis's own HTTPS requests use. @internal */
39
+ export type HttpFetch = (input: string | URL, init?: HttpRequest) => Promise<Response>;
29
40
  /**
30
41
  * POST a DPoP-bound form, answering a `use_dpop_nonce` challenge. Each attempt
31
42
  * signs a fresh proof; a challenge precedes any artifact consumption, so the
@@ -39,6 +50,8 @@ export declare function postWithDpop(options: {
39
50
  sessionPublicKey: string;
40
51
  nonce?: string;
41
52
  signal: AbortSignal;
53
+ /** Defaults to `fetch`. */
54
+ fetch?: HttpFetch;
42
55
  }): Promise<TokenResponse>;
43
56
  /**
44
57
  * Verify a signed OAuth admission against current trust. If it does not
@@ -75,7 +75,7 @@ export async function postWithDpop(options) {
75
75
  let nonce = options.nonce;
76
76
  for (let attempt = 0; attempt < 3; attempt++) {
77
77
  const proof = await createDpopProof(options.key, options.endpoint, options.runtimeId, options.sessionPublicKey, nonce);
78
- const response = await fetch(options.endpoint, {
78
+ const response = await (options.fetch ?? fetch)(options.endpoint, {
79
79
  method: "POST",
80
80
  body: options.form,
81
81
  headers: { DPoP: proof },
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
- import { acceptServerCertificateFor } from "../native/certificate_acceptance.js";
2
+ import { acceptServerCertificateFor, installationFetch, } from "../native/certificate_acceptance.js";
3
3
  import { dirname, join } from "node:path";
4
4
  import { env, platform } from "node:process";
5
5
  import { Type } from "typebox";
@@ -301,6 +301,7 @@ export async function checkDeviceActivation(args) {
301
301
  if (localState?.status === "activated") {
302
302
  const identity = await deriveDeviceIdentity(normalizeRootSecret(args.rootSecret));
303
303
  const enrollment = await requestDeviceEnrollment({
304
+ fetch: installationFetch,
304
305
  trellisUrl: args.trellisUrl,
305
306
  publicIdentityKey: identity.publicIdentityKey,
306
307
  identitySeed: identity.identitySeed,
package/device.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Request-serving participants load the provider protocol build.
2
- import { acceptServerCertificateFor, trustAcceptedCertificatesFor, } from "./native/certificate_acceptance.js";
2
+ import { acceptServerCertificateFor, installationFetch, trustAcceptedCertificatesFor, } from "./native/certificate_acceptance.js";
3
3
  import "./auth/protocol_wasm_provider.js";
4
4
  export { checkDeviceActivation } from "./device/activation.js";
5
5
  import { AsyncResult, Result, UnexpectedError } from "@oatscenter/result";
@@ -137,6 +137,7 @@ function createActivationSession(args) {
137
137
  return activatedState;
138
138
  }
139
139
  await waitForDeviceActivation({
140
+ fetch: installationFetch,
140
141
  trellisUrl: args.trellisUrl,
141
142
  publicIdentityKey: args.identity.publicIdentityKey,
142
143
  identitySeed: args.identity.identitySeed,
@@ -169,6 +170,7 @@ function createActivationSession(args) {
169
170
  });
170
171
  }
171
172
  const enrollment = await requestDeviceEnrollment({
173
+ fetch: installationFetch,
172
174
  trellisUrl: args.trellisUrl,
173
175
  publicIdentityKey: args.identity.publicIdentityKey,
174
176
  identitySeed: args.identity.identitySeed,
@@ -207,6 +209,7 @@ export async function startDeviceActivationWithDeps(args, deps) {
207
209
  });
208
210
  const connectionId = ulid();
209
211
  const activation = await requestDeviceEnrollment({
212
+ fetch: installationFetch,
210
213
  trellisUrl: args.trellisUrl,
211
214
  publicIdentityKey: identity.publicIdentityKey,
212
215
  identitySeed: identity.identitySeed,
@@ -284,7 +287,7 @@ export async function resumeDeviceActivationWithDeps(args, deps) {
284
287
  * `TrellisDevice.connect`.
285
288
  */
286
289
  export async function connectDeviceWithDeps(args, deps) {
287
- await trustAcceptedCertificatesFor(args.participant.identity);
290
+ await trustAcceptedCertificatesFor(args.participant.identity, [args.servers].flat());
288
291
  const connected = await connectProvisioned(args, "device", {}, await deps.loadTransport());
289
292
  let companion;
290
293
  try {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "dependencies": {
3
- "@oatscenter/trellis": "^0.100.0-rc.20"
3
+ "@oatscenter/trellis": "^0.100.0-rc.22"
4
4
  },
5
5
  "description": "Generated Trellis APIs and participants.",
6
6
  "exports": {
@@ -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,42 @@ 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 installation at `endpoints` too,
24
+ * which that installation named itself. Refuses an endpoint another
25
+ * installation this process connects to already trusts differently.
26
+ * @internal
27
+ */
28
+ export declare function trustNamedEndpoints(named: string, endpoints: readonly string[]): Promise<void>;
29
+ /**
30
+ * The issuers accepted for `servers`' installation, for a connection to them.
31
+ * @internal
32
+ */
33
+ export declare function acceptedIssuersFor(servers: readonly string[]): string[] | undefined;
34
+ /**
35
+ * `fetch`, trusting the issuer accepted for `input`'s endpoint when there is
36
+ * one.
37
+ * @internal
38
+ */
39
+ export declare function installationFetch(input: string | URL, init?: HttpRequest): Promise<Response>;
40
+ /**
41
+ * A WebSocket to `url`, trusting the issuer accepted for its endpoint when
42
+ * there is one.
43
+ * @internal
44
+ */
45
+ export declare function installationWebSocket(url: string): WebSocket;
46
+ /**
47
+ * Makes Trellis's connections to the Trellis at `url` trust the certificate
48
+ * it presents, accepting one nothing vouches for the way a browser would.
24
49
  *
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.
50
+ * A server the system trust store vouches for needs nothing, unless it fails
51
+ * an explicitly requested fingerprint. Otherwise the certificate accepted
52
+ * earlier for this server is trusted, and a different one is refused. On first
53
+ * contact the issuer's SHA-256 fingerprint must match `acceptance.fingerprint`
54
+ * (or `TRELLIS_CERTIFICATE_FINGERPRINT`), or `TRELLIS_ACCEPT_SELF_SIGNED` must
55
+ * be `1`, or the operator accepts it on the terminal. The accepted issuer is
56
+ * saved in `acceptance.directory`. Only this installation's endpoints trust
57
+ * it, through `discoverNativeOAuth` and the connections Trellis opens to
58
+ * them; the rest of the process, including `fetch`, does not.
32
59
  */
33
60
  export declare function acceptServerCertificate(url: string, acceptance: CertificateAcceptance): Promise<Result<void, AuthError>>;
34
61
  /**
@@ -38,8 +65,9 @@ export declare function acceptServerCertificate(url: string, acceptance: Certifi
38
65
  */
39
66
  export declare function acceptServerCertificateFor(url: string, participant: string): Promise<void>;
40
67
  /**
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.
68
+ * Trusts the certificates `participant` already accepted at the `servers`
69
+ * their installations named, for a connection that only reaches the broker.
70
+ * Activation and discovery, which reach the server's HTTPS address, accept
71
+ * them and record what each installation names.
44
72
  */
45
- export declare function trustAcceptedCertificatesFor(participant: string): Promise<void>;
73
+ export declare function trustAcceptedCertificatesFor(participant: string, servers: readonly string[]): Promise<void>;
@@ -2,9 +2,12 @@ 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";
10
+ import { z } from "zod";
8
11
  import { AuthError } from "../errors/AuthError.js";
9
12
  /** Accepts only a certificate whose issuer has this SHA-256 fingerprint. */
10
13
  export const CERTIFICATE_FINGERPRINT_ENV = "TRELLIS_CERTIFICATE_FINGERPRINT";
@@ -21,17 +24,173 @@ export function certificateAcceptanceFor(program) {
21
24
  : join(homedir(), ".local", "state");
22
25
  return { directory: join(state, "trellis", program, "servers") };
23
26
  }
27
+ /** By the endpoint each was accepted at. */
28
+ const installations = new Map();
29
+ const defaultPorts = {
30
+ "https:": "443",
31
+ "wss:": "443",
32
+ "http:": "80",
33
+ "ws:": "80",
34
+ "tls:": "4222",
35
+ "nats:": "4222",
36
+ };
37
+ function endpointOf(url) {
38
+ const parsed = new URL(url);
39
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
40
+ return `${host}:${parsed.port || defaultPorts[parsed.protocol] || ""}`;
41
+ }
42
+ function installationAt(endpoint) {
43
+ for (const installation of installations.values())
44
+ if (installation.endpoints.has(endpoint))
45
+ return installation;
46
+ return undefined;
47
+ }
48
+ function sameIssuers(a, b) {
49
+ return a?.join("\n") === b?.join("\n");
50
+ }
51
+ function remember(endpoint, issuers, file) {
52
+ const previous = installations.get(endpoint);
53
+ const installation = {
54
+ at: endpoint,
55
+ issuers,
56
+ endpoints: previous && sameIssuers(previous.issuers, issuers)
57
+ ? previous.endpoints
58
+ : new Set([endpoint]),
59
+ file,
60
+ };
61
+ // What an endpoint presents itself outranks what another installation
62
+ // named it.
63
+ for (const other of installations.values())
64
+ if (other !== previous)
65
+ other.endpoints.delete(endpoint);
66
+ installations.set(endpoint, installation);
67
+ return installation;
68
+ }
69
+ function namedFile(file) {
70
+ return file.replace(/\.pem$/, ".endpoints.json");
71
+ }
24
72
  /**
25
- * Makes this process trust the certificate a Trellis at `url` presents,
26
- * accepting one nothing vouches for the way a browser would.
73
+ * Trusts the issuer accepted for `named`'s installation at `endpoints` too,
74
+ * which that installation named itself. Refuses an endpoint another
75
+ * installation this process connects to already trusts differently.
76
+ * @internal
77
+ */
78
+ export async function trustNamedEndpoints(named, endpoints) {
79
+ const at = endpointOf(named);
80
+ await name(installationAt(at) ?? remember(at, undefined), endpoints.map(endpointOf));
81
+ }
82
+ async function name(installation, endpoints) {
83
+ for (const endpoint of endpoints) {
84
+ const other = installationAt(endpoint);
85
+ if (other &&
86
+ other !== installation &&
87
+ !sameIssuers(other.issuers, installation.issuers))
88
+ throw new AuthError({
89
+ reason: "CertificateConflict",
90
+ message: `${installation.at} names ${endpoint}, which another Trellis this program connects to trusts with a different certificate`,
91
+ });
92
+ }
93
+ for (const endpoint of endpoints)
94
+ installation.endpoints.add(endpoint);
95
+ if (!installation.file)
96
+ return;
97
+ // Saved even when it names only itself, as an installation that offers
98
+ // only its WebSocket on its own port does.
99
+ const file = namedFile(installation.file);
100
+ const saved = JSON.stringify({
101
+ endpoint: installation.at,
102
+ endpoints: [...installation.endpoints],
103
+ });
104
+ if ((await readFile(file, "utf8").catch(() => undefined)) === saved)
105
+ return;
106
+ const staged = `${file}.${randomUUID()}`;
107
+ await writeFile(staged, saved, { mode: 0o600, flag: "wx" });
108
+ await rename(staged, file);
109
+ }
110
+ /**
111
+ * The issuers accepted for `servers`' installation, for a connection to them.
112
+ * @internal
113
+ */
114
+ export function acceptedIssuersFor(servers) {
115
+ const issuers = new Set(servers.flatMap((server) => installationAt(endpointOf(server))?.issuers ?? []));
116
+ return issuers.size ? [...issuers] : undefined;
117
+ }
118
+ /** One connection pool per set of accepted issuers. */
119
+ const agents = new WeakMap();
120
+ function agentFor(url) {
121
+ const issuers = installationAt(endpointOf(url))?.issuers;
122
+ if (!issuers)
123
+ return undefined;
124
+ let agent = agents.get(issuers);
125
+ if (!agent) {
126
+ agent = new Agent({ connect: { ca: [...issuers] } });
127
+ agents.set(issuers, agent);
128
+ }
129
+ return agent;
130
+ }
131
+ /**
132
+ * `fetch`, trusting the issuer accepted for `input`'s endpoint when there is
133
+ * one.
134
+ * @internal
135
+ */
136
+ export async function installationFetch(input, init = {}) {
137
+ const dispatcher = agentFor(input);
138
+ if (!dispatcher)
139
+ return await fetch(input, init);
140
+ const headers = { ...init.headers };
141
+ if (init.body instanceof URLSearchParams)
142
+ headers["content-type"] ??=
143
+ "application/x-www-form-urlencoded;charset=UTF-8";
144
+ const received = await request(input, {
145
+ dispatcher,
146
+ method: init.method ?? "GET",
147
+ headers,
148
+ body: init.body?.toString(),
149
+ signal: init.signal,
150
+ });
151
+ // Like fetch with `redirect: "error"`; undici follows none by default.
152
+ if (received.statusCode >= 300 &&
153
+ received.statusCode < 400 &&
154
+ init.redirect === "error") {
155
+ received.body.destroy();
156
+ throw new TypeError("fetch failed: redirect");
157
+ }
158
+ const responseHeaders = new Headers();
159
+ for (const [name, value] of Object.entries(received.headers))
160
+ for (const item of [value ?? []].flat())
161
+ responseHeaders.append(name, item);
162
+ const empty = [101, 204, 205, 304].includes(received.statusCode);
163
+ if (empty)
164
+ received.body.destroy();
165
+ return new Response(empty
166
+ ? null
167
+ : Readable.toWeb(received.body), { status: received.statusCode, headers: responseHeaders });
168
+ }
169
+ /**
170
+ * A WebSocket to `url`, trusting the issuer accepted for its endpoint when
171
+ * there is one.
172
+ * @internal
173
+ */
174
+ export function installationWebSocket(url) {
175
+ const dispatcher = agentFor(url);
176
+ // Node's own WebSocket is this class, from its bundled copy of undici.
177
+ return dispatcher
178
+ ? new AgentWebSocket(url, { dispatcher })
179
+ : new WebSocket(url);
180
+ }
181
+ /**
182
+ * Makes Trellis's connections to the Trellis at `url` trust the certificate
183
+ * it presents, accepting one nothing vouches for the way a browser would.
27
184
  *
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.
185
+ * A server the system trust store vouches for needs nothing, unless it fails
186
+ * an explicitly requested fingerprint. Otherwise the certificate accepted
187
+ * earlier for this server is trusted, and a different one is refused. On first
188
+ * contact the issuer's SHA-256 fingerprint must match `acceptance.fingerprint`
189
+ * (or `TRELLIS_CERTIFICATE_FINGERPRINT`), or `TRELLIS_ACCEPT_SELF_SIGNED` must
190
+ * be `1`, or the operator accepts it on the terminal. The accepted issuer is
191
+ * saved in `acceptance.directory`. Only this installation's endpoints trust
192
+ * it, through `discoverNativeOAuth` and the connections Trellis opens to
193
+ * them; the rest of the process, including `fetch`, does not.
35
194
  */
36
195
  export async function acceptServerCertificate(url, acceptance) {
37
196
  let target;
@@ -50,8 +209,17 @@ export async function acceptServerCertificate(url, acceptance) {
50
209
  const presented = await presentedIssuer(host, port);
51
210
  if (!presented)
52
211
  return err(new AuthError({ reason: "OAuthUnavailable" }));
53
- if (presented.authorized)
212
+ const expected = (acceptance.fingerprint ?? process.env[CERTIFICATE_FINGERPRINT_ENV])?.trim();
213
+ const normalize = (value) => value.replaceAll(":", "").toUpperCase();
214
+ if (expected && normalize(expected) !== normalize(presented.fingerprint))
215
+ return err(new AuthError({
216
+ reason: "CertificateMismatch",
217
+ message: `${server} presents issuer fingerprint ${presented.fingerprint}, not the expected ${expected}`,
218
+ }));
219
+ if (presented.authorized) {
220
+ remember(server, undefined);
54
221
  return ok(undefined);
222
+ }
55
223
  const accepted = await readFile(file, "utf8").catch(() => undefined);
56
224
  if (accepted !== undefined) {
57
225
  const fingerprint = new X509Certificate(accepted).fingerprint256;
@@ -60,17 +228,11 @@ export async function acceptServerCertificate(url, acceptance) {
60
228
  reason: "CertificateChanged",
61
229
  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
230
  }));
63
- trust(accepted);
231
+ remember(server, [accepted], file);
64
232
  return ok(undefined);
65
233
  }
66
- const expected = (acceptance.fingerprint ?? process.env[CERTIFICATE_FINGERPRINT_ENV])?.trim();
67
- const normalize = (value) => value.replaceAll(":", "").toUpperCase();
68
234
  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
- }));
235
+ // Matched above.
74
236
  }
75
237
  else if (process.env[ACCEPT_SELF_SIGNED_ENV]?.trim() === "1") {
76
238
  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 +260,12 @@ export async function acceptServerCertificate(url, acceptance) {
98
260
  }
99
261
  await mkdir(acceptance.directory, { recursive: true, mode: 0o700 });
100
262
  await chmod(acceptance.directory, 0o700);
101
- const staged = `${file}.${process.pid}`;
102
- await writeFile(staged, presented.pem, { mode: 0o600 });
263
+ // Unique to this attempt: another one in this process may be staging the
264
+ // same certificate.
265
+ const staged = `${file}.${randomUUID()}`;
266
+ await writeFile(staged, presented.pem, { mode: 0o600, flag: "wx" });
103
267
  await rename(staged, file);
104
- trust(presented.pem);
268
+ remember(server, [presented.pem], file);
105
269
  return ok(undefined);
106
270
  }
107
271
  /**
@@ -115,25 +279,34 @@ export async function acceptServerCertificateFor(url, participant) {
115
279
  throw accepted.error;
116
280
  }
117
281
  /**
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.
282
+ * Trusts the certificates `participant` already accepted at the `servers`
283
+ * their installations named, for a connection that only reaches the broker.
284
+ * Activation and discovery, which reach the server's HTTPS address, accept
285
+ * them and record what each installation names.
121
286
  */
122
- export async function trustAcceptedCertificatesFor(participant) {
287
+ export async function trustAcceptedCertificatesFor(participant, servers) {
123
288
  const { directory } = certificateAcceptanceFor(participantProgram(participant));
124
- for (const name of await readdir(directory).catch(() => []))
125
- if (name.endsWith(".pem"))
126
- trust(await readFile(join(directory, name), "utf8"));
289
+ const wanted = new Set(servers.map(endpointOf));
290
+ for (const entry of await readdir(directory).catch(() => [])) {
291
+ if (!entry.endsWith(".pem"))
292
+ continue;
293
+ const file = join(directory, entry);
294
+ const named = await readFile(namedFile(file), "utf8")
295
+ .then((text) => z
296
+ .object({ endpoint: z.string(), endpoints: z.array(z.string()) })
297
+ .parse(JSON.parse(text)))
298
+ .catch(() => undefined);
299
+ if (!named ||
300
+ installations.has(named.endpoint) ||
301
+ !named.endpoints.some((endpoint) => wanted.has(endpoint)))
302
+ continue;
303
+ // Already saved: only trusted again.
304
+ await name(remember(named.endpoint, [await readFile(file, "utf8")]), named.endpoints);
305
+ }
127
306
  }
128
307
  function participantProgram(participant) {
129
308
  return participant.replace(/[^A-Za-z0-9._-]/g, "_");
130
309
  }
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
310
  /**
138
311
  * The issuer that ends the chain the server presents, without trusting it,
139
312
  * 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
+ await 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
+ await 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.20",
54
+ "@oatscenter/result": "0.100.0-rc.22",
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.20",
74
+ "version": "0.100.0-rc.22",
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,22 @@ export class TrellisServiceRuntime extends Trellis {
2697
2699
  return next;
2698
2700
  };
2699
2701
  const startLeaseHeartbeat = (runtime, fence) => {
2702
+ // A recovery still in flight when the service stopped must not
2703
+ // renew, or keep the process alive to try.
2704
+ if (this.#operationRecoveryAbort.signal.aborted)
2705
+ return;
2706
+ const stopHeartbeat = () => {
2707
+ clearInterval(leaseHeartbeat);
2708
+ this.#operationLeaseHeartbeats.delete(leaseHeartbeat);
2709
+ };
2700
2710
  const leaseHeartbeat = setInterval(() => {
2701
2711
  // Cancellation aborts the handler signal so cleanup can observe it,
2702
2712
  // 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.
2713
+ // a terminal operation, lost ownership (handled below) or stopping
2714
+ // the service ends renewal, matching the owner-continues-renewing
2715
+ // contract.
2705
2716
  if (runtime.terminal) {
2706
- clearInterval(leaseHeartbeat);
2717
+ stopHeartbeat();
2707
2718
  return;
2708
2719
  }
2709
2720
  void this.#queueOperationFrame(runtime, async () => {
@@ -2752,11 +2763,14 @@ export class TrellisServiceRuntime extends Trellis {
2752
2763
  this.#operations.delete(runtime.id);
2753
2764
  }
2754
2765
  this.#releaseOperationFence(runtime.id, fence);
2755
- clearInterval(leaseHeartbeat);
2766
+ stopHeartbeat();
2756
2767
  });
2757
2768
  }, 10_000);
2769
+ this.#operationLeaseHeartbeats.add(leaseHeartbeat);
2758
2770
  };
2759
2771
  const watchCancellation = (runtime, fence) => {
2772
+ if (this.#operationRecoveryAbort.signal.aborted)
2773
+ return;
2760
2774
  let reading = false;
2761
2775
  let cleanupScheduled = !!runtime.cancelRequestedAt;
2762
2776
  const cancellationWatch = setInterval(() => {
@@ -2844,6 +2858,8 @@ export class TrellisServiceRuntime extends Trellis {
2844
2858
  .take();
2845
2859
  if (isErr(staged))
2846
2860
  return;
2861
+ if (this.#operationRecoveryAbort.signal.aborted)
2862
+ return;
2847
2863
  startLeaseHeartbeat(runtime, fence);
2848
2864
  watchCancellation(runtime, fence);
2849
2865
  const transferSession = {
@@ -2889,12 +2905,16 @@ export class TrellisServiceRuntime extends Trellis {
2889
2905
  runtime.snapshot.revision++;
2890
2906
  runtime.snapshot.updatedAt = now();
2891
2907
  await this.saveOperationRecord(runtime);
2908
+ if (this.#operationRecoveryAbort.signal.aborted)
2909
+ return;
2892
2910
  startLeaseHeartbeat(runtime, fence);
2893
2911
  watchCancellation(runtime, fence);
2894
2912
  this.#operationTransferSessions.set(runtime.id, reopened);
2895
2913
  void scheduleHandler(runtime, fence, runtime.caller, reopened, {}, true);
2896
2914
  return;
2897
2915
  }
2916
+ if (this.#operationRecoveryAbort.signal.aborted)
2917
+ return;
2898
2918
  startLeaseHeartbeat(runtime, fence);
2899
2919
  watchCancellation(runtime, fence);
2900
2920
  void scheduleHandler(runtime, fence, runtime.caller, undefined, {}, true);
@@ -3416,6 +3436,11 @@ export class TrellisServiceRuntime extends Trellis {
3416
3436
  }
3417
3437
  this.#operationRecoverers.clear();
3418
3438
  this.#operationRecoveryIndexes.clear();
3439
+ // A stopped process renews nothing; its leases expire for recovery.
3440
+ for (const heartbeat of this.#operationLeaseHeartbeats) {
3441
+ clearInterval(heartbeat);
3442
+ }
3443
+ this.#operationLeaseHeartbeats.clear();
3419
3444
  for (const close of this.#operationIntakeClosers)
3420
3445
  close();
3421
3446
  for (const drain of this.#operationIntakeDrains) {