@oatscenter/trellis 0.100.0-rc.20 → 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.
- package/auth/device_activation.d.ts +3 -0
- package/auth/device_activation.js +1 -1
- package/auth/issuer_trust.d.ts +2 -1
- package/auth/issuer_trust.js +2 -2
- package/auth/oauth_core.d.ts +13 -0
- package/auth/oauth_core.js +1 -1
- package/device/activation.js +2 -1
- package/device.js +4 -2
- package/internal_sdk/generated/package.json +1 -1
- package/native/certificate_acceptance.d.ts +39 -13
- package/native/certificate_acceptance.js +138 -33
- package/native/discovery.js +5 -1
- package/native/oauth.js +3 -1
- package/package.json +3 -2
- package/runtime_transport.js +11 -2
- package/service/runtime/core.js +17 -4
|
@@ -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>>;
|
|
@@ -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" },
|
package/auth/issuer_trust.d.ts
CHANGED
|
@@ -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>;
|
package/auth/issuer_trust.js
CHANGED
|
@@ -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
|
|
24
|
+
const response = await request(url, {
|
|
25
25
|
credentials: "omit",
|
|
26
26
|
redirect: "error",
|
|
27
27
|
signal: AbortSignal.any([
|
package/auth/oauth_core.d.ts
CHANGED
|
@@ -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
|
package/auth/oauth_core.js
CHANGED
|
@@ -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 },
|
package/device/activation.js
CHANGED
|
@@ -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";
|
|
@@ -169,6 +169,7 @@ function createActivationSession(args) {
|
|
|
169
169
|
});
|
|
170
170
|
}
|
|
171
171
|
const enrollment = await requestDeviceEnrollment({
|
|
172
|
+
fetch: installationFetch,
|
|
172
173
|
trellisUrl: args.trellisUrl,
|
|
173
174
|
publicIdentityKey: args.identity.publicIdentityKey,
|
|
174
175
|
identitySeed: args.identity.identitySeed,
|
|
@@ -207,6 +208,7 @@ export async function startDeviceActivationWithDeps(args, deps) {
|
|
|
207
208
|
});
|
|
208
209
|
const connectionId = ulid();
|
|
209
210
|
const activation = await requestDeviceEnrollment({
|
|
211
|
+
fetch: installationFetch,
|
|
210
212
|
trellisUrl: args.trellisUrl,
|
|
211
213
|
publicIdentityKey: identity.publicIdentityKey,
|
|
212
214
|
identitySeed: identity.identitySeed,
|
|
@@ -284,7 +286,7 @@ export async function resumeDeviceActivationWithDeps(args, deps) {
|
|
|
284
286
|
* `TrellisDevice.connect`.
|
|
285
287
|
*/
|
|
286
288
|
export async function connectDeviceWithDeps(args, deps) {
|
|
287
|
-
await trustAcceptedCertificatesFor(args.participant.identity);
|
|
289
|
+
await trustAcceptedCertificatesFor(args.participant.identity, [args.servers].flat());
|
|
288
290
|
const connected = await connectProvisioned(args, "device", {}, await deps.loadTransport());
|
|
289
291
|
let companion;
|
|
290
292
|
try {
|
|
@@ -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
|
-
*
|
|
23
|
-
*
|
|
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
|
|
26
|
-
*
|
|
27
|
-
* is
|
|
28
|
-
* `acceptance.fingerprint`
|
|
29
|
-
* `
|
|
30
|
-
*
|
|
31
|
-
* this
|
|
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
|
|
42
|
-
* that only reaches the broker. Activation, which reaches the
|
|
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 {
|
|
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
|
-
*
|
|
26
|
-
*
|
|
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
|
|
29
|
-
*
|
|
30
|
-
* is
|
|
31
|
-
* `acceptance.fingerprint`
|
|
32
|
-
* `
|
|
33
|
-
*
|
|
34
|
-
* this
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
102
|
-
|
|
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
|
-
|
|
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
|
|
119
|
-
* that only reaches the broker. Activation, which reaches the
|
|
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
|
-
|
|
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.
|
package/native/discovery.js
CHANGED
|
@@ -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) =>
|
|
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.
|
|
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.
|
|
74
|
+
"version": "0.100.0-rc.21",
|
|
74
75
|
"type": "module",
|
|
75
76
|
"license": "Apache-2.0",
|
|
76
77
|
"publishConfig": {
|
package/runtime_transport.js
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
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
|
}
|
package/service/runtime/core.js
CHANGED
|
@@ -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
|
|
2704
|
-
// renewal, matching the owner-continues-renewing
|
|
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
|
-
|
|
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
|
-
|
|
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) {
|