@calimero-network/mero-js 35.2.1 → 35.3.0
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/README.md +5 -5
- package/dist/client/approvals.d.ts +2 -0
- package/dist/client/approvals.js +8 -1
- package/dist/client/calimero-client.d.ts +13 -2
- package/dist/client/calimero-client.js +16 -0
- package/dist/client/index.d.ts +4 -3
- package/dist/client/index.js +2 -2
- package/dist/client/package-capabilities.d.ts +42 -0
- package/dist/client/package-capabilities.js +2 -0
- package/dist/index.browser.mjs +4 -4
- package/dist/index.browser.mjs.map +3 -3
- package/dist/index.cjs +202 -27
- package/dist/index.cjs.map +3 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +202 -27
- package/dist/index.mjs.map +3 -3
- package/dist/runtime/attestation.d.ts +28 -1
- package/dist/runtime/attestation.js +95 -20
- package/dist/runtime/index.d.ts +3 -3
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/transport.d.ts +39 -2
- package/dist/runtime/transport.js +97 -8
- package/dist/runtime.browser.mjs +1 -0
- package/dist/runtime.cjs +1 -0
- package/dist/runtime.mjs +1 -0
- package/package.json +1 -1
|
@@ -81,7 +81,9 @@ export interface NodePolicy {
|
|
|
81
81
|
* pinned measurements). Takes precedence over `release`.
|
|
82
82
|
*/
|
|
83
83
|
verifyQuote?: VerifyTransportQuote;
|
|
84
|
-
/** The app
|
|
84
|
+
/** The app whose code the node must attest: it binds its own record of the bundle hash, which the record carries. */
|
|
85
|
+
app?: string;
|
|
86
|
+
/** With `app`: the hash the node must bind. Alone: sent and bound, but only echoed, so never recorded. */
|
|
85
87
|
appHash?: string;
|
|
86
88
|
}
|
|
87
89
|
export interface AttestationDoc {
|
|
@@ -97,12 +99,37 @@ export interface AttestationDoc {
|
|
|
97
99
|
node: number;
|
|
98
100
|
mock: boolean;
|
|
99
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Only what the check verified. Sealed means `profile === 'locked-read-only'`; no profile or a mock is not
|
|
104
|
+
* sealed, and no release means no verifier link. `appHash` is the one the node bound for `policy.app`.
|
|
105
|
+
*/
|
|
106
|
+
export interface NodeVerification {
|
|
107
|
+
url: string;
|
|
108
|
+
mock: boolean;
|
|
109
|
+
release?: string;
|
|
110
|
+
profile?: string;
|
|
111
|
+
appHash?: string;
|
|
112
|
+
/** When the check passed (ms since the epoch). */
|
|
113
|
+
checkedAt: number;
|
|
114
|
+
}
|
|
100
115
|
/**
|
|
101
116
|
* The release a node names, checked against the floor before anything is
|
|
102
117
|
* fetched. Accepts `2.3.109` and the tag form `mero-tee-v2.3.109`.
|
|
103
118
|
*/
|
|
104
119
|
export declare function claimedRelease(doc: Pick<AttestationDoc, 'release'>, minReleaseVersion: string): string;
|
|
120
|
+
/** `host` gave no answer: its fetch rejected (`cause`) or it answered a 5xx `status`. Says nothing about the quote. */
|
|
121
|
+
export declare class Unanswered extends Error {
|
|
122
|
+
readonly host: string;
|
|
123
|
+
readonly status?: number;
|
|
124
|
+
readonly cause?: unknown;
|
|
125
|
+
constructor(host: string, status?: number, cause?: unknown);
|
|
126
|
+
}
|
|
105
127
|
/** `fetch`, refusing collateral older than `policy.maxCollateralAgeDays` (by its TCB info's `issueDate`). */
|
|
106
128
|
export declare function freshCollateral(fetch: (quote: Uint8Array) => Promise<DcapCollateral>, policy: Pick<NodeReleasePolicy, 'maxCollateralAgeDays' | 'now'>): (quote: Uint8Array) => Promise<DcapCollateral>;
|
|
107
129
|
/** Fetch the node's attestation and return its transport key once it checks out. */
|
|
108
130
|
export declare function fetchAttestedKey(baseUrl: string, policy: NodePolicy, fetchImpl?: typeof fetch): Promise<Uint8Array>;
|
|
131
|
+
/** {@link fetchAttestedKey}, with the record of what the check verified. */
|
|
132
|
+
export declare function verifyNode(baseUrl: string, policy: NodePolicy, fetchImpl?: typeof fetch): Promise<{
|
|
133
|
+
key: Uint8Array;
|
|
134
|
+
verification: NodeVerification;
|
|
135
|
+
}>;
|
|
@@ -62,21 +62,63 @@ export function claimedRelease(doc, minReleaseVersion) {
|
|
|
62
62
|
}
|
|
63
63
|
return version;
|
|
64
64
|
}
|
|
65
|
+
/** `host` gave no answer: its fetch rejected (`cause`) or it answered a 5xx `status`. Says nothing about the quote. */
|
|
66
|
+
export class Unanswered extends Error {
|
|
67
|
+
constructor(host, status, cause) {
|
|
68
|
+
super(status ? `${host} answered HTTP ${status}` : `${host} could not be reached: ${cause?.message}`);
|
|
69
|
+
this.host = host;
|
|
70
|
+
this.status = status;
|
|
71
|
+
this.cause = cause;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** `error` as {@link Unanswered} from `host` when it is a fetch's `TypeError`: no connection, or one dropped mid-body. */
|
|
75
|
+
function unanswered(host, error) {
|
|
76
|
+
return error instanceof TypeError ? new Unanswered(host, undefined, error) : error;
|
|
77
|
+
}
|
|
78
|
+
/** A status that is no answer yet: the host is overloaded or failing, not judging the request. */
|
|
79
|
+
const unansweredStatus = (status) => status === 429 || status >= 500;
|
|
80
|
+
/** `fetchImpl`, throwing {@link Unanswered} for `host` instead of a rejection, a dropped body or a 429/5xx. */
|
|
81
|
+
function answered(fetchImpl, host) {
|
|
82
|
+
return async (input, init) => {
|
|
83
|
+
const response = await fetchImpl(input, init).catch((error) => {
|
|
84
|
+
throw unanswered(host, error);
|
|
85
|
+
});
|
|
86
|
+
if (unansweredStatus(response.status))
|
|
87
|
+
throw new Unanswered(host, response.status);
|
|
88
|
+
const body = await response.arrayBuffer().catch((error) => {
|
|
89
|
+
throw unanswered(host, error);
|
|
90
|
+
});
|
|
91
|
+
return new Response(body, response);
|
|
92
|
+
};
|
|
93
|
+
}
|
|
65
94
|
async function releaseFor(version, policy, fetchImpl) {
|
|
66
95
|
const source = policy.releaseSource;
|
|
67
96
|
if (typeof source === 'function')
|
|
68
97
|
return source(version);
|
|
98
|
+
const fetchMirror = answered(fetchImpl, 'the release mirror');
|
|
69
99
|
if (source === 'github')
|
|
70
|
-
return fetchGithubNodeRelease(version, { fetch:
|
|
71
|
-
return fetchNodeRelease(cloudNodeReleaseUrl(source ?? DEFAULT_RELEASE_MIRROR, version), { fetch:
|
|
100
|
+
return fetchGithubNodeRelease(version, { fetch: fetchMirror });
|
|
101
|
+
return fetchNodeRelease(cloudNodeReleaseUrl(source ?? DEFAULT_RELEASE_MIRROR, version), { fetch: fetchMirror });
|
|
72
102
|
}
|
|
73
103
|
/** The collateral fetch a policy gets unless it brings its own: `@phala/dcap-qvl` against `collateralSource`. */
|
|
74
104
|
function defaultCollateral(policy) {
|
|
75
105
|
const source = policy.collateralSource ?? DEFAULT_COLLATERAL_MIRROR;
|
|
106
|
+
// dcap-qvl fetches with its own `fetch`: only its call's `TypeError` is no answer, never a bad URL or bundle.
|
|
76
107
|
if (source === 'intel') {
|
|
77
|
-
return async (quote) =>
|
|
108
|
+
return async (quote) => {
|
|
109
|
+
const get = await dcap('getCollateralFromPcs');
|
|
110
|
+
return get(quote).catch((error) => {
|
|
111
|
+
throw unanswered('Intel PCS', error);
|
|
112
|
+
});
|
|
113
|
+
};
|
|
78
114
|
}
|
|
79
|
-
|
|
115
|
+
new URL(source);
|
|
116
|
+
return async (quote) => {
|
|
117
|
+
const get = await dcap('getCollateral');
|
|
118
|
+
return get(source, quote).catch((error) => {
|
|
119
|
+
throw unanswered(source, error);
|
|
120
|
+
});
|
|
121
|
+
};
|
|
80
122
|
}
|
|
81
123
|
/** `fetch`, refusing collateral older than `policy.maxCollateralAgeDays` (by its TCB info's `issueDate`). */
|
|
82
124
|
export function freshCollateral(fetch, policy) {
|
|
@@ -105,9 +147,14 @@ export function freshCollateral(fetch, policy) {
|
|
|
105
147
|
async function verifyRelease(doc, args, policy, fetchImpl) {
|
|
106
148
|
// Refuse what no release could admit before reaching for the network.
|
|
107
149
|
const version = claimedRelease(doc, policy.minReleaseVersion);
|
|
150
|
+
const profile = policy.profile ?? PRODUCTION_PROFILE;
|
|
151
|
+
const release = await releaseFor(version, policy, fetchImpl);
|
|
152
|
+
if (release.version !== version) {
|
|
153
|
+
throw new Error(`The node names mero-tee release ${version}, but the release served is ${release.version}`);
|
|
154
|
+
}
|
|
108
155
|
const trusted = await trustSignedRelease({
|
|
109
|
-
release
|
|
110
|
-
profile
|
|
156
|
+
release,
|
|
157
|
+
profile,
|
|
111
158
|
allowDebugProfile: policy.allowDebugProfile,
|
|
112
159
|
minReleaseVersion: policy.minReleaseVersion,
|
|
113
160
|
identity: policy.identity,
|
|
@@ -120,24 +167,52 @@ async function verifyRelease(doc, args, policy, fetchImpl) {
|
|
|
120
167
|
now: policy.now,
|
|
121
168
|
...trusted,
|
|
122
169
|
});
|
|
123
|
-
return verifier(args);
|
|
170
|
+
return (await verifier(args)) ? { release: version, profile } : undefined;
|
|
124
171
|
}
|
|
125
172
|
/** Fetch the node's attestation and return its transport key once it checks out. */
|
|
126
173
|
export async function fetchAttestedKey(baseUrl, policy, fetchImpl = (input, init) => fetch(input, init)) {
|
|
174
|
+
return (await verifyNode(baseUrl, policy, fetchImpl)).key;
|
|
175
|
+
}
|
|
176
|
+
/** The app hash the node chose for `policy.app`, which must be real and the pinned one if any. */
|
|
177
|
+
function nodeBoundAppHash(doc, policy) {
|
|
178
|
+
const bound = fromHex(doc.appHash, 'appHash', 32);
|
|
179
|
+
if (bound.every((byte) => byte === 0))
|
|
180
|
+
throw new Error('The node bound no app: its app hash is all zero');
|
|
181
|
+
if (policy.appHash && hex(bound) !== policy.appHash.toLowerCase()) {
|
|
182
|
+
throw new Error(`The node's app hash ${hex(bound)} is not the pinned ${policy.appHash}`);
|
|
183
|
+
}
|
|
184
|
+
return bound;
|
|
185
|
+
}
|
|
186
|
+
/** {@link fetchAttestedKey}, with the record of what the check verified. */
|
|
187
|
+
export async function verifyNode(baseUrl, policy, fetchImpl = (input, init) => fetch(input, init)) {
|
|
188
|
+
const url = baseUrl.replace(/\/+$/, '');
|
|
127
189
|
const nonce = hex(crypto.getRandomValues(new Uint8Array(32)));
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
if (policy.
|
|
131
|
-
|
|
132
|
-
|
|
190
|
+
const attestation = new URL(`${url}/attestation`);
|
|
191
|
+
attestation.searchParams.set('nonce', nonce);
|
|
192
|
+
if (policy.app)
|
|
193
|
+
attestation.searchParams.set('app', policy.app);
|
|
194
|
+
else if (policy.appHash)
|
|
195
|
+
attestation.searchParams.set('appHash', policy.appHash);
|
|
196
|
+
const response = await fetchImpl(attestation.toString());
|
|
197
|
+
if (unansweredStatus(response.status))
|
|
198
|
+
throw new Unanswered('the node', response.status);
|
|
133
199
|
if (!response.ok)
|
|
134
200
|
throw new Error(`The node refused to attest: HTTP ${response.status}`);
|
|
135
|
-
const doc = (await response.json())
|
|
201
|
+
const doc = (await response.json().catch((error) => {
|
|
202
|
+
throw unanswered('the node', error);
|
|
203
|
+
}));
|
|
136
204
|
const transportKey = fromHex(doc.transportKey, 'transportKey', 32);
|
|
137
|
-
const
|
|
205
|
+
const boundApp = policy.app ? nodeBoundAppHash(doc, policy) : undefined;
|
|
206
|
+
const inner = boundApp ?? (policy.appHash ? fromHex(policy.appHash, 'appHash', 32) : new Uint8Array(32));
|
|
138
207
|
const suffix = await transportKeyBinding(inner, transportKey);
|
|
139
208
|
const quote = base64ToBytes(doc.quote);
|
|
140
209
|
const header = new TextEncoder().encode(MOCK_QUOTE_HEADER);
|
|
210
|
+
const verification = (facts) => ({
|
|
211
|
+
url,
|
|
212
|
+
...facts,
|
|
213
|
+
...(boundApp ? { appHash: hex(boundApp) } : {}),
|
|
214
|
+
checkedAt: Date.now(),
|
|
215
|
+
});
|
|
141
216
|
if (equal(quote.slice(0, header.length), header)) {
|
|
142
217
|
if (!policy.allowMock) {
|
|
143
218
|
throw new Error('mock quote refused: this client only trusts real TEEs');
|
|
@@ -146,20 +221,20 @@ export async function fetchAttestedKey(baseUrl, policy, fetchImpl = (input, init
|
|
|
146
221
|
if (!equal(report.slice(0, 32), fromHex(nonce, 'nonce', 32)) || !equal(report.slice(32), suffix)) {
|
|
147
222
|
throw new Error('the quote does not bind this transport key, app and nonce');
|
|
148
223
|
}
|
|
149
|
-
return transportKey;
|
|
224
|
+
return { key: transportKey, verification: verification({ mock: true }) };
|
|
150
225
|
}
|
|
151
226
|
const args = { quoteB64: doc.quote, nonce, reportDataSuffix: hex(suffix) };
|
|
152
|
-
let
|
|
227
|
+
let facts;
|
|
153
228
|
if (policy.verifyQuote) {
|
|
154
|
-
|
|
229
|
+
facts = (await policy.verifyQuote(args)) ? {} : undefined;
|
|
155
230
|
}
|
|
156
231
|
else if (policy.release) {
|
|
157
|
-
|
|
232
|
+
facts = await verifyRelease(doc, args, policy.release, fetchImpl);
|
|
158
233
|
}
|
|
159
234
|
else {
|
|
160
235
|
throw new Error('real quote refused: this client trusts no TD image (set policy.release)');
|
|
161
236
|
}
|
|
162
|
-
if (!
|
|
237
|
+
if (!facts)
|
|
163
238
|
throw new Error('The attestation did not verify, so its transport key is not trusted');
|
|
164
|
-
return transportKey;
|
|
239
|
+
return { key: transportKey, verification: verification({ mock: false, ...facts }) };
|
|
165
240
|
}
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { DEFAULT_RETRY, NodeTransport, directoryTransport, newIdempotencyKey, queryString, refusal, retryDelayMs, routePath, sseFrames, } from './transport.js';
|
|
2
|
-
export type { CalimeroSession, NodeEvent, RetryOptions, DirectorySource, HttpMethod, NodeTransportOptions, QueryValue, RequestOptions, Transport, } from './transport.js';
|
|
3
|
-
export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from './attestation.js';
|
|
4
|
-
export type { AttestationDoc, NodePolicy, NodeReleasePolicy } from './attestation.js';
|
|
2
|
+
export type { CalimeroSession, NodeEvent, RetryOptions, DirectorySource, HttpMethod, NodeTransportOptions, NodeVerificationState, QueryValue, RequestOptions, Transport, } from './transport.js';
|
|
3
|
+
export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER, verifyNode } from './attestation.js';
|
|
4
|
+
export type { AttestationDoc, NodePolicy, NodeReleasePolicy, NodeVerification } from './attestation.js';
|
|
5
5
|
export { DEFAULT_DIRECTORY, DirectoryError } from './directory.js';
|
|
6
6
|
export type { DirectoryFailure } from './directory.js';
|
|
7
7
|
export { browserPasskey, b64url, fromB64url, passkeyConfirm } from './passkey.js';
|
package/dist/runtime/index.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// `NodeTransport.exchange`; `client.transport` is a `CalimeroClient`'s runtime.
|
|
14
14
|
export { DEFAULT_RETRY, NodeTransport, directoryTransport, newIdempotencyKey, queryString, refusal, retryDelayMs, routePath, sseFrames, } from './transport.js';
|
|
15
15
|
// Attestation: what a node must prove before anything is sealed to it.
|
|
16
|
-
export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER } from './attestation.js';
|
|
16
|
+
export { claimedRelease, fetchAttestedKey, freshCollateral, MOCK_QUOTE_HEADER, verifyNode } from './attestation.js';
|
|
17
17
|
// The node directory a cluster's node list is read from.
|
|
18
18
|
export { DEFAULT_DIRECTORY, DirectoryError } from './directory.js';
|
|
19
19
|
// Passkeys (WebAuthn) for the step-up and the ceremonies.
|
|
@@ -21,12 +21,27 @@
|
|
|
21
21
|
* Paths are relative to the node (`apps/{app}/intents`, a leading `/` is
|
|
22
22
|
* dropped); {@link routePath} fills a path template with encoded segments.
|
|
23
23
|
*/
|
|
24
|
-
import { type NodePolicy } from './attestation.js';
|
|
24
|
+
import { type NodePolicy, type NodeVerification } from './attestation.js';
|
|
25
25
|
import { CalimeroError } from './errors.js';
|
|
26
26
|
import { type PasskeyProvider, type PasskeyUserVerification } from './passkey.js';
|
|
27
27
|
import type { components } from '../generated/api.js';
|
|
28
28
|
/** A signed-in session: what sign-up, sign-in and a refresh answer. */
|
|
29
29
|
export type CalimeroSession = components['schemas']['Session'];
|
|
30
|
+
/**
|
|
31
|
+
* Where a node stands with the client's check: `refused` failed verification, `unreachable`
|
|
32
|
+
* gave no answer (retried on next use).
|
|
33
|
+
*/
|
|
34
|
+
export type NodeVerificationState = {
|
|
35
|
+
status: 'checking';
|
|
36
|
+
url: string;
|
|
37
|
+
} | ({
|
|
38
|
+
status: 'verified';
|
|
39
|
+
} & NodeVerification) | {
|
|
40
|
+
status: 'refused' | 'unreachable';
|
|
41
|
+
url: string;
|
|
42
|
+
reason: string;
|
|
43
|
+
checkedAt: number;
|
|
44
|
+
};
|
|
30
45
|
/** One server-sent event: `data` parsed as JSON when it is. */
|
|
31
46
|
export interface NodeEvent {
|
|
32
47
|
id: string;
|
|
@@ -165,6 +180,11 @@ export declare class NodeTransport implements Transport {
|
|
|
165
180
|
private at;
|
|
166
181
|
/** A sealed fetch per node, each attesting its own node on first use. */
|
|
167
182
|
private readonly channels;
|
|
183
|
+
/** The latest attestation check of each node, and the attempt it came from. */
|
|
184
|
+
private readonly checks;
|
|
185
|
+
private readonly attempts;
|
|
186
|
+
/** The transport key each node's channel was attested to. */
|
|
187
|
+
private readonly keys;
|
|
168
188
|
private readonly policy;
|
|
169
189
|
/** The unsealed fetch, for the one route served in the clear (`/attestation`). */
|
|
170
190
|
readonly raw: typeof fetch;
|
|
@@ -179,7 +199,7 @@ export declare class NodeTransport implements Transport {
|
|
|
179
199
|
/** The directory the node list came from, if it came from one. */
|
|
180
200
|
private source;
|
|
181
201
|
constructor(options: NodeTransportOptions);
|
|
182
|
-
/** Whether `error` is a
|
|
202
|
+
/** Whether `error` is a host that gave no answer: a `fetch` that failed, or an attestation input left {@link Unanswered}. */
|
|
183
203
|
isNetworkFailure(error: unknown): boolean;
|
|
184
204
|
/** Re-read the node list from `source` when it is due, and after a failover. */
|
|
185
205
|
useDirectory(source: DirectorySource): void;
|
|
@@ -196,6 +216,23 @@ export declare class NodeTransport implements Transport {
|
|
|
196
216
|
get session(): CalimeroSession | undefined;
|
|
197
217
|
/** The sealed channel to `url`, attested under the policy before its first request. */
|
|
198
218
|
private channel;
|
|
219
|
+
/** Attest node `url` for the channel `live` tells is in use, keeping what the check verified or why it failed. */
|
|
220
|
+
private attest;
|
|
221
|
+
/** What the client's check of node `url` (a URL from `nodes`; default: the one in use) established; `undefined` before it is first used. */
|
|
222
|
+
verification(url?: string): NodeVerificationState | undefined;
|
|
223
|
+
/**
|
|
224
|
+
* Attest `app` on node `url` (a URL from `nodes`; default: the one in use): the record's
|
|
225
|
+
* `appHash` is the one the node bound. Throws on refusal, or when the quote's key is not the channel's.
|
|
226
|
+
*/
|
|
227
|
+
attestApp(app: string, url?: string): Promise<NodeVerification>;
|
|
228
|
+
/** The settled check of node `url`; throws the reason when it failed. */
|
|
229
|
+
private settled;
|
|
230
|
+
private sameKey;
|
|
231
|
+
/**
|
|
232
|
+
* Start the check of node `url` if none runs and answer its settled outcome, without a request or a repeat.
|
|
233
|
+
* `checkedAt` is when that check ran; a failure is answered, not thrown.
|
|
234
|
+
*/
|
|
235
|
+
verify(url?: string): Promise<NodeVerificationState>;
|
|
199
236
|
/**
|
|
200
237
|
* Move on from node `from` (the one that answered `421 WRONG_NODE`) to the
|
|
201
238
|
* next one. False when there is no other. A request that saw the same node
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
* dropped); {@link routePath} fills a path template with encoded segments.
|
|
23
23
|
*/
|
|
24
24
|
import { SealedTransportError, createSealedFetch } from '../sealed/sealed.js';
|
|
25
|
-
import {
|
|
25
|
+
import { hex } from '../crypto/internal.js';
|
|
26
|
+
import { Unanswered, verifyNode } from './attestation.js';
|
|
26
27
|
import { orderNodes, readDirectory } from './directory.js';
|
|
27
28
|
import { CalimeroError, ConfirmRequired, LoginRequired, UnavailableError, WrongNode, errorFrom, } from './errors.js';
|
|
28
29
|
import { b64url } from './passkey.js';
|
|
@@ -162,6 +163,11 @@ export class NodeTransport {
|
|
|
162
163
|
this.at = 0;
|
|
163
164
|
/** A sealed fetch per node, each attesting its own node on first use. */
|
|
164
165
|
this.channels = new Map();
|
|
166
|
+
/** The latest attestation check of each node, and the attempt it came from. */
|
|
167
|
+
this.checks = new Map();
|
|
168
|
+
this.attempts = new Map();
|
|
169
|
+
/** The transport key each node's channel was attested to. */
|
|
170
|
+
this.keys = new Map();
|
|
165
171
|
/** Rejections of the underlying `fetch` itself: the node could not be reached or dropped the connection. */
|
|
166
172
|
this.networkFailures = new WeakSet();
|
|
167
173
|
const trim = (url) => url.replace(/\/+$/, '');
|
|
@@ -185,9 +191,9 @@ export class NodeTransport {
|
|
|
185
191
|
};
|
|
186
192
|
this.raw = raw;
|
|
187
193
|
}
|
|
188
|
-
/** Whether `error` is a
|
|
194
|
+
/** Whether `error` is a host that gave no answer: a `fetch` that failed, or an attestation input left {@link Unanswered}. */
|
|
189
195
|
isNetworkFailure(error) {
|
|
190
|
-
return error instanceof TypeError && this.networkFailures.has(error);
|
|
196
|
+
return (error instanceof TypeError && this.networkFailures.has(error)) || error instanceof Unanswered;
|
|
191
197
|
}
|
|
192
198
|
/** Re-read the node list from `source` when it is due, and after a failover. */
|
|
193
199
|
useDirectory(source) {
|
|
@@ -221,16 +227,99 @@ export class NodeTransport {
|
|
|
221
227
|
}
|
|
222
228
|
/** The sealed channel to `url`, attested under the policy before its first request. */
|
|
223
229
|
channel(url) {
|
|
224
|
-
let
|
|
225
|
-
if (!
|
|
226
|
-
|
|
230
|
+
let channel = this.channels.get(url);
|
|
231
|
+
if (!channel) {
|
|
232
|
+
// A channel that has been dropped records nothing: only the one in use speaks for the node.
|
|
233
|
+
const live = () => this.channels.get(url) === sealed;
|
|
234
|
+
let first;
|
|
235
|
+
const sealed = createSealedFetch({
|
|
227
236
|
baseUrl: url,
|
|
228
|
-
transportPublicKey: () =>
|
|
237
|
+
transportPublicKey: () => {
|
|
238
|
+
const key = first ?? this.attest(url, live);
|
|
239
|
+
first = undefined;
|
|
240
|
+
return key;
|
|
241
|
+
},
|
|
229
242
|
fetch: this.raw,
|
|
230
243
|
});
|
|
231
244
|
this.channels.set(url, sealed);
|
|
245
|
+
first = this.attest(url, live);
|
|
246
|
+
channel = sealed;
|
|
247
|
+
}
|
|
248
|
+
return channel;
|
|
249
|
+
}
|
|
250
|
+
/** Attest node `url` for the channel `live` tells is in use, keeping what the check verified or why it failed. */
|
|
251
|
+
attest(url, live) {
|
|
252
|
+
if (!live())
|
|
253
|
+
return verifyNode(url, this.policy, this.raw).then(({ key }) => key);
|
|
254
|
+
this.checks.set(url, { status: 'checking', url });
|
|
255
|
+
const attempt = verifyNode(url, this.policy, this.raw).then(({ key, verification }) => {
|
|
256
|
+
if (live()) {
|
|
257
|
+
this.checks.set(url, { status: 'verified', ...verification });
|
|
258
|
+
this.keys.set(url, key);
|
|
259
|
+
}
|
|
260
|
+
return key;
|
|
261
|
+
}, (error) => {
|
|
262
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
263
|
+
const unreachable = this.isNetworkFailure(error);
|
|
264
|
+
if (live()) {
|
|
265
|
+
this.checks.set(url, { status: unreachable ? 'unreachable' : 'refused', url, reason, checkedAt: Date.now() });
|
|
266
|
+
// No answer says nothing about the node: the next use attests on a new channel.
|
|
267
|
+
if (unreachable)
|
|
268
|
+
this.channels.delete(url);
|
|
269
|
+
}
|
|
270
|
+
throw error;
|
|
271
|
+
});
|
|
272
|
+
// A failure surfaces on the request that needed the key, not as an unhandled rejection.
|
|
273
|
+
attempt.catch(() => undefined);
|
|
274
|
+
this.attempts.set(url, attempt);
|
|
275
|
+
return attempt;
|
|
276
|
+
}
|
|
277
|
+
/** What the client's check of node `url` (a URL from `nodes`; default: the one in use) established; `undefined` before it is first used. */
|
|
278
|
+
verification(url = this.nodeUrl) {
|
|
279
|
+
return this.checks.get(url);
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Attest `app` on node `url` (a URL from `nodes`; default: the one in use): the record's
|
|
283
|
+
* `appHash` is the one the node bound. Throws on refusal, or when the quote's key is not the channel's.
|
|
284
|
+
*/
|
|
285
|
+
async attestApp(app, url = this.nodeUrl) {
|
|
286
|
+
const pinned = this.policy.app === app ? this.policy.appHash : undefined;
|
|
287
|
+
const policy = { ...this.policy, app, appHash: pinned };
|
|
288
|
+
await this.settled(url);
|
|
289
|
+
let attested = await verifyNode(url, policy, this.raw);
|
|
290
|
+
if (!this.sameKey(url, attested.key)) {
|
|
291
|
+
// The node may have restarted: the channel's own check, on a new channel, decides which key requests use.
|
|
292
|
+
this.channels.delete(url);
|
|
293
|
+
await this.settled(url);
|
|
294
|
+
attested = await verifyNode(url, policy, this.raw);
|
|
295
|
+
if (!this.sameKey(url, attested.key)) {
|
|
296
|
+
throw new Error('The node attested the app under another transport key than its channel');
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return attested.verification;
|
|
300
|
+
}
|
|
301
|
+
/** The settled check of node `url`; throws the reason when it failed. */
|
|
302
|
+
async settled(url) {
|
|
303
|
+
const state = await this.verify(url);
|
|
304
|
+
if (state.status === 'refused' || state.status === 'unreachable')
|
|
305
|
+
throw new Error(state.reason);
|
|
306
|
+
}
|
|
307
|
+
sameKey(url, key) {
|
|
308
|
+
const channelKey = this.keys.get(url);
|
|
309
|
+
return channelKey !== undefined && hex(channelKey) === hex(key);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Start the check of node `url` if none runs and answer its settled outcome, without a request or a repeat.
|
|
313
|
+
* `checkedAt` is when that check ran; a failure is answered, not thrown.
|
|
314
|
+
*/
|
|
315
|
+
async verify(url = this.nodeUrl) {
|
|
316
|
+
this.channel(url);
|
|
317
|
+
for (;;) {
|
|
318
|
+
const attempt = this.attempts.get(url);
|
|
319
|
+
await attempt?.catch(() => undefined);
|
|
320
|
+
if (this.attempts.get(url) === attempt)
|
|
321
|
+
return this.checks.get(url);
|
|
232
322
|
}
|
|
233
|
-
return sealed;
|
|
234
323
|
}
|
|
235
324
|
/**
|
|
236
325
|
* Move on from node `from` (the one that answered `421 WRONG_NODE`) to the
|
package/dist/runtime.browser.mjs
CHANGED
package/dist/runtime.cjs
CHANGED
|
@@ -66,4 +66,5 @@ Object.defineProperty(exports, "sseFrames", { enumerable: true, get: () => m["ss
|
|
|
66
66
|
Object.defineProperty(exports, "transportKeyBinding", { enumerable: true, get: () => m["transportKeyBinding"] });
|
|
67
67
|
Object.defineProperty(exports, "trustSignedRelease", { enumerable: true, get: () => m["trustSignedRelease"] });
|
|
68
68
|
Object.defineProperty(exports, "trustedMeasurementsFromReleases", { enumerable: true, get: () => m["trustedMeasurementsFromReleases"] });
|
|
69
|
+
Object.defineProperty(exports, "verifyNode", { enumerable: true, get: () => m["verifyNode"] });
|
|
69
70
|
Object.defineProperty(exports, "verifySignedNodeRelease", { enumerable: true, get: () => m["verifySignedNodeRelease"] });
|
package/dist/runtime.mjs
CHANGED