@certcrypt/sdk 0.0.0-stage → 1.0.1
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.
Potentially problematic release.
This version of @certcrypt/sdk might be problematic. Click here for more details.
- package/CHANGELOG.md +74 -0
- package/LICENSE +178 -0
- package/README.md +557 -2
- package/SECURITY.md +55 -0
- package/dist/src/artifacts/base-certificate.d.ts +336 -0
- package/dist/src/artifacts/base-certificate.js +373 -0
- package/dist/src/artifacts/base-certificate.js.map +1 -0
- package/dist/src/artifacts/capacity-evidence.d.ts +195 -0
- package/dist/src/artifacts/capacity-evidence.js +202 -0
- package/dist/src/artifacts/capacity-evidence.js.map +1 -0
- package/dist/src/artifacts/commitment-inclusion.d.ts +23 -0
- package/dist/src/artifacts/commitment-inclusion.js +91 -0
- package/dist/src/artifacts/commitment-inclusion.js.map +1 -0
- package/dist/src/artifacts/holder-keyset.d.ts +67 -0
- package/dist/src/artifacts/holder-keyset.js +149 -0
- package/dist/src/artifacts/holder-keyset.js.map +1 -0
- package/dist/src/artifacts/rfc3339.d.ts +9 -0
- package/dist/src/artifacts/rfc3339.js +39 -0
- package/dist/src/artifacts/rfc3339.js.map +1 -0
- package/dist/src/client.d.ts +552 -0
- package/dist/src/client.js +1347 -0
- package/dist/src/client.js.map +1 -0
- package/dist/src/crypto/ai-decision.d.ts +73 -0
- package/dist/src/crypto/ai-decision.js +94 -0
- package/dist/src/crypto/ai-decision.js.map +1 -0
- package/dist/src/crypto/canonical-subject.d.ts +33 -0
- package/dist/src/crypto/canonical-subject.js +240 -0
- package/dist/src/crypto/canonical-subject.js.map +1 -0
- package/dist/src/crypto/collection-merkle.d.ts +58 -0
- package/dist/src/crypto/collection-merkle.js +164 -0
- package/dist/src/crypto/collection-merkle.js.map +1 -0
- package/dist/src/crypto/composite.d.ts +53 -0
- package/dist/src/crypto/composite.js +69 -0
- package/dist/src/crypto/composite.js.map +1 -0
- package/dist/src/crypto/digest.d.ts +3 -0
- package/dist/src/crypto/digest.js +31 -0
- package/dist/src/crypto/digest.js.map +1 -0
- package/dist/src/crypto/ecdsa-p256.d.ts +79 -0
- package/dist/src/crypto/ecdsa-p256.js +277 -0
- package/dist/src/crypto/ecdsa-p256.js.map +1 -0
- package/dist/src/crypto/jcs.d.ts +13 -0
- package/dist/src/crypto/jcs.js +65 -0
- package/dist/src/crypto/jcs.js.map +1 -0
- package/dist/src/crypto/merkle.d.ts +18 -0
- package/dist/src/crypto/merkle.js +150 -0
- package/dist/src/crypto/merkle.js.map +1 -0
- package/dist/src/crypto/ml-dsa.d.ts +28 -0
- package/dist/src/crypto/ml-dsa.js +60 -0
- package/dist/src/crypto/ml-dsa.js.map +1 -0
- package/dist/src/crypto/pseudonym.d.ts +8 -0
- package/dist/src/crypto/pseudonym.js +50 -0
- package/dist/src/crypto/pseudonym.js.map +1 -0
- package/dist/src/crypto/strict-json.d.ts +25 -0
- package/dist/src/crypto/strict-json.js +180 -0
- package/dist/src/crypto/strict-json.js.map +1 -0
- package/dist/src/crypto/subject-json-preconditions.d.ts +46 -0
- package/dist/src/crypto/subject-json-preconditions.js +381 -0
- package/dist/src/crypto/subject-json-preconditions.js.map +1 -0
- package/dist/src/index.d.ts +18 -0
- package/dist/src/index.js +80 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/issuer.d.ts +668 -0
- package/dist/src/issuer.js +1066 -0
- package/dist/src/issuer.js.map +1 -0
- package/dist/src/retry.d.ts +67 -0
- package/dist/src/retry.js +78 -0
- package/dist/src/retry.js.map +1 -0
- package/dist/src/types.d.ts +297 -0
- package/dist/src/types.js +15 -0
- package/dist/src/types.js.map +1 -0
- package/package.json +62 -4
|
@@ -0,0 +1,1347 @@
|
|
|
1
|
+
// Copyright © 2025-2026 CERTCRYPT, Inc., its affiliates or licensors. All rights reserved.
|
|
2
|
+
//
|
|
3
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
// you may not use this file except in compliance with the License.
|
|
5
|
+
// You may obtain a copy of the License at
|
|
6
|
+
//
|
|
7
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
//
|
|
9
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
// See the License for the specific language governing permissions and
|
|
13
|
+
// limitations under the License.
|
|
14
|
+
/**
|
|
15
|
+
* Client for a CERTCRYPT node — the issuer-side HTTP surface this SDK talks to.
|
|
16
|
+
*
|
|
17
|
+
* Scope: an HTTP client over the node's issuer routes — `POST /v1/issue` and
|
|
18
|
+
* `GET /v1/operations/{id}`, plus activation, emission recovery and dead
|
|
19
|
+
* letters. The node wraps the submitted commitments into the
|
|
20
|
+
* closed submission set and tracks the resulting operation.
|
|
21
|
+
*
|
|
22
|
+
* NO CUSTODY: the issuer produces a zero-data `capacity.evidence/1` (projected,
|
|
23
|
+
* unlinkable) — signing only the Level-3 projected commitment with a non-reused
|
|
24
|
+
* operation-key leaf — and submits it as a loose commitment (see
|
|
25
|
+
* `mintVerifiableCertificate`). `issue(request)` sends commitments a caller has
|
|
26
|
+
* already signed.
|
|
27
|
+
*/
|
|
28
|
+
import { decideRetry, drawBackoffMs, parseRetryAfter, RETRY_AFTER_MAX_MS, RETRY_AFTER_MIN_MS, RETRY_DEFAULTS, } from "./retry.js";
|
|
29
|
+
import { assembleEvidence, assertSubmissionSetWithinBound, } from "./artifacts/capacity-evidence.js";
|
|
30
|
+
import { sha3_256 } from "@noble/hashes/sha3.js";
|
|
31
|
+
import { assembleBaseCertificate, } from "./artifacts/base-certificate.js";
|
|
32
|
+
import { buildCommitmentInclusionProof, } from "./artifacts/commitment-inclusion.js";
|
|
33
|
+
export class CertcryptNodeError extends Error {
|
|
34
|
+
status;
|
|
35
|
+
body;
|
|
36
|
+
/**
|
|
37
|
+
* The wait the node asked for, in ms, when it refused with 503 or 429 and a
|
|
38
|
+
* usable `Retry-After` — a restart, an outbox it could not write. `null`
|
|
39
|
+
* otherwise. Read by the retry policy; surfaced so a caller that gives up can
|
|
40
|
+
* still tell "come back in 10 s" from "broken".
|
|
41
|
+
*/
|
|
42
|
+
retryAfterMs;
|
|
43
|
+
/**
|
|
44
|
+
* The machine-readable reason the node gave, when its body carries one: the
|
|
45
|
+
* `error` code of a `{error, message, request_id}` answer (a request the node
|
|
46
|
+
* refused before submitting it), or the whole-request `state` of an
|
|
47
|
+
* `IssueResponse` (e.g. `submission_failed`). `null` otherwise.
|
|
48
|
+
*
|
|
49
|
+
* `integration_key_replaced` (HTTP 409, on activation): the integration key
|
|
50
|
+
* in this configuration was replaced by a newer one — regenerating the key in
|
|
51
|
+
* the console invalidates every previous key at once. Not retryable: update
|
|
52
|
+
* the configuration with the latest integration key and start again.
|
|
53
|
+
*/
|
|
54
|
+
code;
|
|
55
|
+
/**
|
|
56
|
+
* For a `submission_failed` the node answered with HTTP 422: the HTTP status
|
|
57
|
+
* with which the CERTCRYPT service definitively refused the request. Nothing
|
|
58
|
+
* was queued; resending the same request gets the same answer, so fix the
|
|
59
|
+
* cause before submitting anew. `null` otherwise.
|
|
60
|
+
*/
|
|
61
|
+
upstreamStatus;
|
|
62
|
+
constructor(message, status, body, retryAfterMs = null) {
|
|
63
|
+
super(message);
|
|
64
|
+
this.name = "CertcryptNodeError";
|
|
65
|
+
this.status = status;
|
|
66
|
+
this.body = body;
|
|
67
|
+
this.retryAfterMs = retryAfterMs;
|
|
68
|
+
const detail = body ? nodeErrorDetail(body) : null;
|
|
69
|
+
this.code = detail?.code ?? null;
|
|
70
|
+
this.upstreamStatus = detail?.upstreamStatus ?? null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* True for a response field that carries nothing: absent, `null`, `false`, `0`,
|
|
75
|
+
* `""`, `{}` or `[]` — the set the activation answer counts as missing.
|
|
76
|
+
*/
|
|
77
|
+
function isEmptyField(v) {
|
|
78
|
+
if (v === undefined || v === null || v === false || v === 0 || v === "")
|
|
79
|
+
return true;
|
|
80
|
+
if (Array.isArray(v))
|
|
81
|
+
return v.length === 0;
|
|
82
|
+
if (typeof v === "object")
|
|
83
|
+
return Object.keys(v).length === 0;
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The two statuses a successful `POST /v1/activate` carries: `redeemed` on the
|
|
88
|
+
* first activation, `already_consumed_same_root` on an idempotent replay with the
|
|
89
|
+
* same key-set root. Any other value is not an activation.
|
|
90
|
+
*/
|
|
91
|
+
const ACTIVATION_STATUSES = ["redeemed", "already_consumed_same_root"];
|
|
92
|
+
/** The fields an activation answer cannot do without, in the order a refusal
|
|
93
|
+
* names them. */
|
|
94
|
+
const ACTIVATION_REQUIRED = [
|
|
95
|
+
"level1_binding",
|
|
96
|
+
"level1_signature",
|
|
97
|
+
"holder_id",
|
|
98
|
+
"pool_id",
|
|
99
|
+
];
|
|
100
|
+
/** The required fields that must be strings, in the order a refusal names them. */
|
|
101
|
+
const ACTIVATION_STRINGS = ["holder_id", "pool_id"];
|
|
102
|
+
function isPlainObject(v) {
|
|
103
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
104
|
+
}
|
|
105
|
+
function isNonEmptyString(v) {
|
|
106
|
+
return typeof v === "string" && v.length > 0;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The composite signature wire shape `level1_signature` must have: the shape the
|
|
110
|
+
* binding's verifier later reads (`alg`, `mode`, and one or more component
|
|
111
|
+
* signatures, each with its `alg` and `sig_b64`). The SDK carries the signature
|
|
112
|
+
* verbatim into every proof it presents, so a value of any other shape would
|
|
113
|
+
* only fail later, far from its cause.
|
|
114
|
+
*/
|
|
115
|
+
function isCompositeSignature(v) {
|
|
116
|
+
if (!isPlainObject(v))
|
|
117
|
+
return false;
|
|
118
|
+
if (!isNonEmptyString(v.alg) || !isNonEmptyString(v.mode))
|
|
119
|
+
return false;
|
|
120
|
+
const components = v.signatures;
|
|
121
|
+
if (!Array.isArray(components) || components.length === 0)
|
|
122
|
+
return false;
|
|
123
|
+
for (const c of components) {
|
|
124
|
+
if (!isPlainObject(c))
|
|
125
|
+
return false;
|
|
126
|
+
if (!isNonEmptyString(c.alg) || !isNonEmptyString(c.sig_b64))
|
|
127
|
+
return false;
|
|
128
|
+
if ("encoding" in c && typeof c.encoding !== "string")
|
|
129
|
+
return false;
|
|
130
|
+
if ("low_s" in c && typeof c.low_s !== "boolean")
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Read a `POST /v1/activate` answer, failing closed.
|
|
137
|
+
*
|
|
138
|
+
* Four refusals, checked in this order, each throwing `CertcryptNodeError` with
|
|
139
|
+
* no HTTP status (the request itself succeeded):
|
|
140
|
+
*
|
|
141
|
+
* 1. the body is not a JSON object: `activate returned no JSON object`;
|
|
142
|
+
* 2. a required field is absent or empty (`null`, `""`, `0`, `false`, `{}`,
|
|
143
|
+
* `[]`): `activate returned no <fields>`;
|
|
144
|
+
* 3. a field has the wrong type (`level1_binding` not an object,
|
|
145
|
+
* `level1_signature` not a composite signature, `holder_id` or `pool_id`
|
|
146
|
+
* not a string):
|
|
147
|
+
* `activate returned a malformed <fields>`;
|
|
148
|
+
* 4. `status` is neither `redeemed` nor `already_consumed_same_root`:
|
|
149
|
+
* `activate returned an unrecognized status`.
|
|
150
|
+
*
|
|
151
|
+
* The checks and their order are part of the activation contract of the
|
|
152
|
+
* issuance service. Nothing is cached or persisted on a refusal: the caller adopts
|
|
153
|
+
* nothing until this returns.
|
|
154
|
+
*/
|
|
155
|
+
function parseActivation(parsed) {
|
|
156
|
+
if (!isPlainObject(parsed)) {
|
|
157
|
+
throw new CertcryptNodeError("activate returned no JSON object", null, null);
|
|
158
|
+
}
|
|
159
|
+
const body = parsed;
|
|
160
|
+
const raw = JSON.stringify(body);
|
|
161
|
+
const missing = ACTIVATION_REQUIRED.filter((k) => isEmptyField(body[k]));
|
|
162
|
+
if (missing.length > 0) {
|
|
163
|
+
throw new CertcryptNodeError(`activate returned no ${missing.join(", ")}`, null, raw);
|
|
164
|
+
}
|
|
165
|
+
const malformed = [];
|
|
166
|
+
if (!isPlainObject(body.level1_binding))
|
|
167
|
+
malformed.push("level1_binding");
|
|
168
|
+
if (!isCompositeSignature(body.level1_signature))
|
|
169
|
+
malformed.push("level1_signature");
|
|
170
|
+
for (const k of ACTIVATION_STRINGS) {
|
|
171
|
+
if (typeof body[k] !== "string")
|
|
172
|
+
malformed.push(k);
|
|
173
|
+
}
|
|
174
|
+
if (malformed.length > 0) {
|
|
175
|
+
throw new CertcryptNodeError(`activate returned a malformed ${malformed.join(", ")}`, null, raw);
|
|
176
|
+
}
|
|
177
|
+
const status = body.status;
|
|
178
|
+
if (typeof status !== "string" || !ACTIVATION_STATUSES.includes(status)) {
|
|
179
|
+
throw new CertcryptNodeError("activate returned an unrecognized status", null, raw);
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
signedLevel1: {
|
|
183
|
+
level1_binding: body.level1_binding,
|
|
184
|
+
level1_signature: body.level1_signature,
|
|
185
|
+
},
|
|
186
|
+
poolId: body.pool_id,
|
|
187
|
+
holderId: body.holder_id,
|
|
188
|
+
status,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Parse a node error body: an `IssueResponse` with a whole-request `state`
|
|
193
|
+
* (`{state: {state, error?, upstream_status?}}`), or the node's plain
|
|
194
|
+
* `{error, message, request_id}`. `null` for anything else.
|
|
195
|
+
*/
|
|
196
|
+
function nodeErrorDetail(text) {
|
|
197
|
+
let b;
|
|
198
|
+
try {
|
|
199
|
+
b = JSON.parse(text);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return null; // not JSON: the status says it all
|
|
203
|
+
}
|
|
204
|
+
if (typeof b !== "object" || b === null)
|
|
205
|
+
return null;
|
|
206
|
+
const o = b;
|
|
207
|
+
if (o.state && typeof o.state.state === "string") {
|
|
208
|
+
const msg = typeof o.state.error === "string"
|
|
209
|
+
? o.state.error
|
|
210
|
+
: typeof o.state.message === "string"
|
|
211
|
+
? o.state.message
|
|
212
|
+
: "";
|
|
213
|
+
const up = o.state.upstream_status;
|
|
214
|
+
return {
|
|
215
|
+
code: o.state.state,
|
|
216
|
+
message: msg,
|
|
217
|
+
upstreamStatus: typeof up === "number" && Number.isInteger(up) ? up : null,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
if (typeof o.error === "string") {
|
|
221
|
+
return {
|
|
222
|
+
code: o.error,
|
|
223
|
+
message: typeof o.message === "string" ? o.message : "",
|
|
224
|
+
upstreamStatus: null,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
/** The node's `Retry-After`, honored only on 503 and 429. */
|
|
230
|
+
function retryAfterOf(resp) {
|
|
231
|
+
// Defensive: test doubles and some fetch polyfills omit `headers`.
|
|
232
|
+
const raw = resp.headers?.get?.("retry-after") ?? null;
|
|
233
|
+
const honored = resp.status === 503 || resp.status === 429;
|
|
234
|
+
return { raw, ms: honored ? parseRetryAfter(raw) : null };
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* ` — <code>[ (upstream HTTP <n>)]: <message>` from a node error body, when it
|
|
238
|
+
* carries one, so the caller sees WHY the node refused, not just the status.
|
|
239
|
+
*/
|
|
240
|
+
function describeState(text) {
|
|
241
|
+
const d = nodeErrorDetail(text);
|
|
242
|
+
if (!d)
|
|
243
|
+
return "";
|
|
244
|
+
const up = d.upstreamStatus !== null ? ` (upstream HTTP ${d.upstreamStatus})` : "";
|
|
245
|
+
return ` — ${d.code}${up}${d.message ? `: ${d.message}` : ""}`;
|
|
246
|
+
}
|
|
247
|
+
/** Signing domain of the issuer's per-request proof to a node. */
|
|
248
|
+
export const ISSUER_AUTH_DOMAIN = "certcrypt:issuer-auth:1";
|
|
249
|
+
/**
|
|
250
|
+
* The bytes the issuer's leaf signs for `challenge` on `request`:
|
|
251
|
+
* `certcrypt:issuer-auth:1|<challenge>|<host>|<METHOD> <path?query>|<sha3-256
|
|
252
|
+
* hex of the body>`. The node rebuilds it from the request it receives, so a
|
|
253
|
+
* proof captured in transit is good only for repeating that very request — not
|
|
254
|
+
* another route, body or node. `host` is the URL's host with a non-default port.
|
|
255
|
+
*/
|
|
256
|
+
export function issuerAuthMessage(challenge, request) {
|
|
257
|
+
const u = new URL(request.url);
|
|
258
|
+
const digest = Buffer.from(sha3_256(new TextEncoder().encode(request.body ?? ""))).toString("hex");
|
|
259
|
+
return `${ISSUER_AUTH_DOMAIN}|${challenge}|${u.host}|${request.method.toUpperCase()} ${u.pathname}${u.search}|${digest}`;
|
|
260
|
+
}
|
|
261
|
+
/** Render the human-readable line carried by {@link WaitProgress.message}. */
|
|
262
|
+
function describeWait(p) {
|
|
263
|
+
const secs = (ms) => `${Math.max(1, Math.round(ms / 1000))}s`;
|
|
264
|
+
const head = `still ${p.nodeState} after ${secs(p.elapsedMs)}`;
|
|
265
|
+
// Once settlement is on the substrate the window is no longer what the wait is
|
|
266
|
+
// about: it is the substrate's irreversibility, which no amount of window scheduling shortens.
|
|
267
|
+
// Saying so is the difference between "this looks hung" and "this is nearly done".
|
|
268
|
+
if (p.settlement?.phase === "finality_pending") {
|
|
269
|
+
const pct = p.settlement.progress_ppm === undefined
|
|
270
|
+
? ""
|
|
271
|
+
: ` (~${Math.floor(p.settlement.progress_ppm / 10_000)}%)`;
|
|
272
|
+
return (`${head} — settled on chain, waiting for irreversibility${pct}; ` +
|
|
273
|
+
`next check in ${secs(p.nextCheckInMs)}`);
|
|
274
|
+
}
|
|
275
|
+
if (p.overdue && p.window?.expected_settled_by) {
|
|
276
|
+
return (`${head} — OVERDUE: settlement is past the operator's expected instant ` +
|
|
277
|
+
`${p.window.expected_settled_by} (window ${p.window.window_profile}); ` +
|
|
278
|
+
`retrying in ${secs(p.nextCheckInMs)}`);
|
|
279
|
+
}
|
|
280
|
+
if (p.window?.expected_settled_by) {
|
|
281
|
+
const close = p.window.target_close_by ? ` to close (~${p.window.target_close_by})` : "";
|
|
282
|
+
return (`${head} — waiting for settlement window ${p.window.window_profile}${close}, ` +
|
|
283
|
+
`settlement expected by ~${p.window.expected_settled_by}; next check in ${secs(p.nextCheckInMs)}`);
|
|
284
|
+
}
|
|
285
|
+
if (p.overdue && p.window?.target_close_by) {
|
|
286
|
+
return (`${head} — OVERDUE: window ${p.window.window_profile} was due to close by ` +
|
|
287
|
+
`${p.window.target_close_by}; retrying in ${secs(p.nextCheckInMs)}`);
|
|
288
|
+
}
|
|
289
|
+
if (p.window?.target_close_by) {
|
|
290
|
+
return (`${head} — waiting for settlement window ${p.window.window_profile} to close ` +
|
|
291
|
+
`(~${p.window.target_close_by}); next check in ${secs(p.nextCheckInMs)}`);
|
|
292
|
+
}
|
|
293
|
+
if (p.window) {
|
|
294
|
+
return (`${head} — window ${p.window.window_profile} assigned, no close estimate yet; ` +
|
|
295
|
+
`next check in ${secs(p.nextCheckInMs)}`);
|
|
296
|
+
}
|
|
297
|
+
return `${head} — no window estimate from the node; next check in ${secs(p.nextCheckInMs)}`;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Extra delay after `target_close_by` before checking, when the node reports no
|
|
301
|
+
* `expected_settled_by`. The target is the window's CLOSE, but the package only
|
|
302
|
+
* exists once the settlement is anchored and finality has advanced — checking at
|
|
303
|
+
* the exact target reliably observes `processing` and wastes the trip.
|
|
304
|
+
*/
|
|
305
|
+
const WINDOW_SETTLING_MARGIN_MS = 3_000;
|
|
306
|
+
/**
|
|
307
|
+
* Extra delay after `expected_settled_by` before the last scheduled check. That
|
|
308
|
+
* instant already accounts for anchoring and finality, so the margin only absorbs
|
|
309
|
+
* clock skew between this host and the operator.
|
|
310
|
+
*/
|
|
311
|
+
const EXPECTED_SETTLED_MARGIN_MS = 1_000;
|
|
312
|
+
/**
|
|
313
|
+
* Where the early check sits between the close and `expected_settled_by`, as a
|
|
314
|
+
* fraction of that span. The operator sets `expected_settled_by` with headroom
|
|
315
|
+
* so that "overdue" means something; most settlements land well before it, and
|
|
316
|
+
* one check inside the span finds them without waiting out the headroom.
|
|
317
|
+
*/
|
|
318
|
+
const SETTLEMENT_CHECKPOINT_FRACTION = 0.6;
|
|
319
|
+
/**
|
|
320
|
+
* Every operation in a window shares its close, so their checks would otherwise
|
|
321
|
+
* reach the node — and through it the operator — at the same instant. Each
|
|
322
|
+
* scheduled check is pushed back by a random 0..this many ms. Only ever later,
|
|
323
|
+
* never earlier, so no check lands before the instant it is aimed at.
|
|
324
|
+
*/
|
|
325
|
+
const CHECKPOINT_SPREAD_MS = 1_000;
|
|
326
|
+
/**
|
|
327
|
+
* Upper bound on ONE sleep towards a scheduled check. The backoff cap is far too
|
|
328
|
+
* short for this: a window that closes in three minutes would otherwise be polled
|
|
329
|
+
* every 30 s while it is still open, for nothing. This bound only exists so that a
|
|
330
|
+
* mis-set instant cannot park the poller indefinitely; the whole wait is still
|
|
331
|
+
* bounded by `maxWaitMs`.
|
|
332
|
+
*/
|
|
333
|
+
const SCHEDULED_SLEEP_CAP_MS = 10 * 60_000;
|
|
334
|
+
/**
|
|
335
|
+
* The checks a wait schedules for a window, in order, and the instant after which
|
|
336
|
+
* a still-pending operation is overdue.
|
|
337
|
+
*
|
|
338
|
+
* With `expected_settled_by` (E) and `target_close_by` (T): one check at
|
|
339
|
+
* T + 60 % of (E − T), one at E + 1 s; overdue past E. With only T: one check at
|
|
340
|
+
* T + 3 s; overdue past T. With only E: one check at E + 1 s. Neither (or neither
|
|
341
|
+
* parses): no checks, `dueMs` NaN.
|
|
342
|
+
*/
|
|
343
|
+
function windowCheckpoints(window) {
|
|
344
|
+
const target = window?.target_close_by ? Date.parse(window.target_close_by) : NaN;
|
|
345
|
+
const expected = window?.expected_settled_by ? Date.parse(window.expected_settled_by) : NaN;
|
|
346
|
+
if (Number.isFinite(expected)) {
|
|
347
|
+
// The operator never reports settlement before the close; if it did, the
|
|
348
|
+
// close is still the earlier bound on a terminal state.
|
|
349
|
+
const dueMs = Number.isFinite(target) ? Math.max(expected, target) : expected;
|
|
350
|
+
const checkpoints = [];
|
|
351
|
+
if (Number.isFinite(target) && dueMs > target) {
|
|
352
|
+
checkpoints.push(target + Math.round((dueMs - target) * SETTLEMENT_CHECKPOINT_FRACTION));
|
|
353
|
+
}
|
|
354
|
+
checkpoints.push(dueMs + EXPECTED_SETTLED_MARGIN_MS);
|
|
355
|
+
return { checkpoints, dueMs };
|
|
356
|
+
}
|
|
357
|
+
if (Number.isFinite(target)) {
|
|
358
|
+
return { checkpoints: [target + WINDOW_SETTLING_MARGIN_MS], dueMs: target };
|
|
359
|
+
}
|
|
360
|
+
return { checkpoints: [], dueMs: NaN };
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* True when the operation is running late at `now`: the operator's
|
|
364
|
+
* `expected_settled_by` has passed, or — when the node reports no such instant —
|
|
365
|
+
* the window's `target_close_by` has. False when the window names neither.
|
|
366
|
+
*/
|
|
367
|
+
export function isSettlementOverdue(window, now) {
|
|
368
|
+
const { dueMs } = windowCheckpoints(window);
|
|
369
|
+
return Number.isFinite(dueMs) && now > dueMs;
|
|
370
|
+
}
|
|
371
|
+
/** Default wall-clock bound for `auto` mode. */
|
|
372
|
+
const DEFAULT_MAX_WAIT_MS = 15 * 60_000;
|
|
373
|
+
/**
|
|
374
|
+
* When no `onProgress` was supplied, a sleep at least this long is announced on
|
|
375
|
+
* the console. Below it the wait is short enough to read as "working"; above it,
|
|
376
|
+
* silence reads as a hang.
|
|
377
|
+
*/
|
|
378
|
+
const QUIET_WAIT_WARN_MS = 10_000;
|
|
379
|
+
/**
|
|
380
|
+
* Choose how long to sleep before the next poll.
|
|
381
|
+
*
|
|
382
|
+
* Exported for testing: the scheduling decision is the whole point of the
|
|
383
|
+
* until-window mode, and it is far easier to pin as a pure function than through
|
|
384
|
+
* a live poll loop.
|
|
385
|
+
*/
|
|
386
|
+
export function nextPollDelayMs(args) {
|
|
387
|
+
const { attempt, now, window, backoffBaseMs, backoffCapMs } = args;
|
|
388
|
+
const random = args.random ?? Math.random;
|
|
389
|
+
const { checkpoints } = windowCheckpoints(window);
|
|
390
|
+
if (checkpoints.length > 0) {
|
|
391
|
+
// The next scheduled check still ahead of us: sleep straight until it (plus
|
|
392
|
+
// the spread) instead of polling a window that is still open. Capped only so
|
|
393
|
+
// a mis-set instant cannot park the poller indefinitely.
|
|
394
|
+
const next = checkpoints.find((p) => p > now);
|
|
395
|
+
if (next !== undefined) {
|
|
396
|
+
const spread = Math.floor(Math.min(Math.max(random(), 0), 1) * CHECKPOINT_SPREAD_MS);
|
|
397
|
+
return {
|
|
398
|
+
delayMs: Math.min(next - now + spread, Math.max(SCHEDULED_SLEEP_CAP_MS, backoffCapMs)),
|
|
399
|
+
overdue: false,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
// Every scheduled check has run and we are still not terminal: the operation
|
|
403
|
+
// is running late. Fall through to backoff and SAY it is overdue.
|
|
404
|
+
const backoff = Math.min(backoffBaseMs * 2 ** Math.max(0, attempt - 1), backoffCapMs);
|
|
405
|
+
return { delayMs: backoff, overdue: true };
|
|
406
|
+
}
|
|
407
|
+
// No estimate → exponential backoff with a cap.
|
|
408
|
+
const backoff = Math.min(backoffBaseMs * 2 ** Math.max(0, attempt - 1), backoffCapMs);
|
|
409
|
+
return { delayMs: backoff, overdue: false };
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Verdicts the client must NOT re-POST. Everything else transient (timeout,
|
|
413
|
+
* transport error, `submission_failed`) is retryable.
|
|
414
|
+
*
|
|
415
|
+
* `accepted_for_retry` is here on purpose: the submission did not get through on
|
|
416
|
+
* this attempt, but the node has taken durable custody of it and will deliver it.
|
|
417
|
+
* Re-POSTing would be wasted work, and worse, it invites a duplicate. The eventual
|
|
418
|
+
* outcome is observed by polling the operation, not by re-issuing.
|
|
419
|
+
*/
|
|
420
|
+
function isNonRetryableState(state) {
|
|
421
|
+
return (state === "independent_ready" ||
|
|
422
|
+
state === "accepted" ||
|
|
423
|
+
state === "accepted_for_retry" ||
|
|
424
|
+
state === "rejected" ||
|
|
425
|
+
state === "expired" ||
|
|
426
|
+
state === "insufficient_capacity" ||
|
|
427
|
+
state === "replay_detected" ||
|
|
428
|
+
// The node sends a rejection before per-member evaluation with HTTP 200;
|
|
429
|
+
// resending the same set gets the same answer.
|
|
430
|
+
state === "pre_evaluation_rejected");
|
|
431
|
+
}
|
|
432
|
+
/** Sleep helper. */
|
|
433
|
+
function sleep(ms) {
|
|
434
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Generate a 26-char ULID (Crockford base32): 48-bit millisecond timestamp +
|
|
438
|
+
* 80-bit randomness. The server's idempotency key MUST be a ULID (26 chars), NOT a
|
|
439
|
+
* UUID (36 chars) — `crypto.randomUUID()` would be rejected with HTTP 400.
|
|
440
|
+
*/
|
|
441
|
+
const ULID_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // Crockford base32 (no I,L,O,U)
|
|
442
|
+
function newUlid() {
|
|
443
|
+
let ts = Date.now();
|
|
444
|
+
const time = new Array(10);
|
|
445
|
+
for (let i = 9; i >= 0; i--) {
|
|
446
|
+
time[i] = ULID_ALPHABET[ts % 32];
|
|
447
|
+
ts = Math.floor(ts / 32);
|
|
448
|
+
}
|
|
449
|
+
const rand = new Uint8Array(16);
|
|
450
|
+
globalThis.crypto.getRandomValues(rand);
|
|
451
|
+
let out = time.join("");
|
|
452
|
+
for (let i = 0; i < 16; i++)
|
|
453
|
+
out += ULID_ALPHABET[rand[i] % 32];
|
|
454
|
+
return out; // 10 (time) + 16 (rand) = 26 chars
|
|
455
|
+
}
|
|
456
|
+
/** Exponential backoff with full jitter for attempt `n` (1-based). */
|
|
457
|
+
function backoffMs(n, baseMs, capMs) {
|
|
458
|
+
// Polling backoff (waitForOperation). Submit retries use `decideRetry`.
|
|
459
|
+
const exp = Math.min(capMs, baseMs * 2 ** (n - 1));
|
|
460
|
+
// Full jitter: a uniform draw over the WHOLE window, not `exp/2 + rand(exp/2)`.
|
|
461
|
+
// Under a thundering herd the halved variant leaves every client's retries clustered in
|
|
462
|
+
// the back half of the window and they collide again; drawing over the full window is
|
|
463
|
+
// what actually spreads them.
|
|
464
|
+
return Math.floor(Math.random() * exp);
|
|
465
|
+
}
|
|
466
|
+
/** The states from which an operation will not move on its own. */
|
|
467
|
+
const TERMINAL_STATES = new Set([
|
|
468
|
+
"independent_ready",
|
|
469
|
+
"rejected",
|
|
470
|
+
"expired",
|
|
471
|
+
"replay_detected",
|
|
472
|
+
"insufficient_capacity",
|
|
473
|
+
"pre_evaluation_rejected",
|
|
474
|
+
"submission_failed",
|
|
475
|
+
]);
|
|
476
|
+
/**
|
|
477
|
+
* True for a terminal state name: polling stops there. `accepted_for_retry` and
|
|
478
|
+
* `accepted` are not terminal — the first means the node holds the set and will
|
|
479
|
+
* deliver it, the second that a member was accepted for processing, not settled.
|
|
480
|
+
*/
|
|
481
|
+
export function isTerminalState(state) {
|
|
482
|
+
return TERMINAL_STATES.has(state);
|
|
483
|
+
}
|
|
484
|
+
function isTerminal(state) {
|
|
485
|
+
return isTerminalState(state.state);
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Normalize the two shapes `GET /v1/operations/{id}` can return into one
|
|
489
|
+
* OperationRecord (see the type doc). A local node record already carries
|
|
490
|
+
* `state`; the server body forwarded on reconciliation carries `status` (string)
|
|
491
|
+
* plus the base64 proof artifacts and no `state`/`request_id`. We map that
|
|
492
|
+
* `status` to a `state` discriminant and surface the proof fields.
|
|
493
|
+
*/
|
|
494
|
+
function normalizeOperationRecord(body) {
|
|
495
|
+
const operation_id = String(body.operation_id ?? "");
|
|
496
|
+
const independence_proof = typeof body.independence_proof === "string" ? body.independence_proof : undefined;
|
|
497
|
+
const settlement_material = typeof body.settlement_material === "string" ? body.settlement_material : undefined;
|
|
498
|
+
// The scheduling hint, present while the operation is being settled. Read defensively:
|
|
499
|
+
// a node that does not send it is fully supported, and the poller simply falls
|
|
500
|
+
// back to backoff. We copy ONLY the known scheduling
|
|
501
|
+
// fields — never spread the object — so that if the wire ever grew a cost-like
|
|
502
|
+
// field it could not silently reach an SDK consumer or its logs.
|
|
503
|
+
const sw = body.settlement_window;
|
|
504
|
+
let settlement_window;
|
|
505
|
+
if (sw && typeof sw === "object") {
|
|
506
|
+
const w = sw;
|
|
507
|
+
if (typeof w.window_profile === "string" && typeof w.window_profile_version === "string") {
|
|
508
|
+
settlement_window = {
|
|
509
|
+
window_profile: w.window_profile,
|
|
510
|
+
window_profile_version: w.window_profile_version,
|
|
511
|
+
...(typeof w.target_close_by === "string"
|
|
512
|
+
? { target_close_by: w.target_close_by }
|
|
513
|
+
: {}),
|
|
514
|
+
...(typeof w.expected_settled_by === "string"
|
|
515
|
+
? { expected_settled_by: w.expected_settled_by }
|
|
516
|
+
: {}),
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
// The progress indicator, same defensive discipline as the window above and for
|
|
521
|
+
// the same reason: copy ONLY the three known fields, never spread. The wire could
|
|
522
|
+
// grow a substrate-revealing field (a block height, a finality lag) and spreading would
|
|
523
|
+
// hand it to an SDK consumer and its logs without anyone deciding to.
|
|
524
|
+
const sp = body.settlement_progress;
|
|
525
|
+
let settlement_progress;
|
|
526
|
+
if (sp && typeof sp === "object") {
|
|
527
|
+
const g = sp;
|
|
528
|
+
if (typeof g.phase === "string") {
|
|
529
|
+
settlement_progress = {
|
|
530
|
+
phase: g.phase,
|
|
531
|
+
...(typeof g.progress_ppm === "number" ? { progress_ppm: g.progress_ppm } : {}),
|
|
532
|
+
...(typeof g.observed_at === "string" ? { observed_at: g.observed_at } : {}),
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
// Already in node-record shape (has a structured `state`): pass through.
|
|
537
|
+
if (body.state && typeof body.state === "object") {
|
|
538
|
+
return {
|
|
539
|
+
operation_id,
|
|
540
|
+
request_id: typeof body.request_id === "string" ? body.request_id : undefined,
|
|
541
|
+
state: body.state,
|
|
542
|
+
...(independence_proof ? { independence_proof } : {}),
|
|
543
|
+
...(settlement_material ? { settlement_material } : {}),
|
|
544
|
+
...(settlement_window ? { settlement_window } : {}),
|
|
545
|
+
...(settlement_progress ? { settlement_progress } : {}),
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
// Server body shape: `status` string → map to a state discriminant.
|
|
549
|
+
//
|
|
550
|
+
// AN ACCEPTED OPERATION CAN STILL END WITHOUT A PROOF. The CERTCRYPT service
|
|
551
|
+
// answers one of five statuses — processing, independent_ready, rejected,
|
|
552
|
+
// insufficient_capacity, expired. An operation can be rejected after it was
|
|
553
|
+
// accepted (e.g. a window whose settlement could not be proven), or expire: its
|
|
554
|
+
// authorization ran out before it could settle, nothing was consumed
|
|
555
|
+
// (submission-set/1 §11.1). Folding either into `processing` would leave
|
|
556
|
+
// `waitForOperation` polling indefinitely, so every known terminal status is
|
|
557
|
+
// mapped explicitly.
|
|
558
|
+
//
|
|
559
|
+
// Only an unrecognized status falls back to `processing`, so the poller keeps
|
|
560
|
+
// going rather than inventing a terminal state.
|
|
561
|
+
const status = String(body.status ?? "processing");
|
|
562
|
+
const reasonCode = typeof body.reason_code === "string" ? body.reason_code : status;
|
|
563
|
+
const message = typeof body.message === "string" ? body.message : "";
|
|
564
|
+
const state = status === "independent_ready"
|
|
565
|
+
? { state: "independent_ready", upstream_operation_id: operation_id }
|
|
566
|
+
: status === "rejected"
|
|
567
|
+
? { state: "rejected", reason_code: reasonCode, message }
|
|
568
|
+
: status === "insufficient_capacity"
|
|
569
|
+
? { state: "insufficient_capacity" }
|
|
570
|
+
: status === "expired"
|
|
571
|
+
? { state: "expired", reason_code: reasonCode, message }
|
|
572
|
+
: { state: "processing", upstream_operation_id: operation_id };
|
|
573
|
+
return {
|
|
574
|
+
operation_id,
|
|
575
|
+
state,
|
|
576
|
+
...(independence_proof ? { independence_proof } : {}),
|
|
577
|
+
...(settlement_material ? { settlement_material } : {}),
|
|
578
|
+
...(settlement_window ? { settlement_window } : {}),
|
|
579
|
+
...(settlement_progress ? { settlement_progress } : {}),
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* How long every request (issue, activate, reads, health) waits for the
|
|
584
|
+
* node before giving up on that attempt, in ms: 30 s. An attempt that times out
|
|
585
|
+
* is a transport failure, retried under the transport-retry policy where the
|
|
586
|
+
* request is retried at all.
|
|
587
|
+
*/
|
|
588
|
+
export const REQUEST_TIMEOUT_MS = 30_000;
|
|
589
|
+
/** The body of a 2xx `/v1/issue` answer that is not a JSON object. */
|
|
590
|
+
class UnparseableIssueResponse extends Error {
|
|
591
|
+
status;
|
|
592
|
+
text;
|
|
593
|
+
constructor(status, text) {
|
|
594
|
+
super("issue failed: unparseable node response");
|
|
595
|
+
this.status = status;
|
|
596
|
+
this.text = text;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
export class CertcryptNodeClient {
|
|
600
|
+
/** The node base URL every request goes to, without a trailing slash. */
|
|
601
|
+
baseUrl;
|
|
602
|
+
poolId;
|
|
603
|
+
fetchImpl;
|
|
604
|
+
retryPolicy;
|
|
605
|
+
now;
|
|
606
|
+
sleepMs;
|
|
607
|
+
random;
|
|
608
|
+
issuerAuthProof;
|
|
609
|
+
issuerReadProof;
|
|
610
|
+
onUpstreamOperationId;
|
|
611
|
+
constructor(opts) {
|
|
612
|
+
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
|
613
|
+
this.poolId = opts.pool_id ?? null;
|
|
614
|
+
this.retryPolicy = {
|
|
615
|
+
maxElapsedMs: opts.retry?.maxElapsedMs ?? RETRY_DEFAULTS.maxElapsedMs,
|
|
616
|
+
maxAttempts: opts.retry?.maxAttempts !== undefined
|
|
617
|
+
? Math.max(1, opts.retry.maxAttempts)
|
|
618
|
+
: RETRY_DEFAULTS.maxAttempts,
|
|
619
|
+
backoffBaseMs: opts.retry?.baseMs ?? RETRY_DEFAULTS.backoffBaseMs,
|
|
620
|
+
backoffCapMs: opts.retry?.capMs ?? RETRY_DEFAULTS.backoffCapMs,
|
|
621
|
+
};
|
|
622
|
+
this.now = opts.clock?.now ?? (() => Date.now());
|
|
623
|
+
this.sleepMs = opts.clock?.sleep ?? sleep;
|
|
624
|
+
this.random = opts.clock?.random ?? Math.random;
|
|
625
|
+
this.issuerAuthProof = opts.issuerAuthProof ?? null;
|
|
626
|
+
this.issuerReadProof = opts.issuerReadProof ?? null;
|
|
627
|
+
this.onUpstreamOperationId = opts.onUpstreamOperationId ?? null;
|
|
628
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
629
|
+
if (!f) {
|
|
630
|
+
throw new CertcryptNodeError("no fetch implementation available; pass opts.fetch on older runtimes", null, null);
|
|
631
|
+
}
|
|
632
|
+
this.fetchImpl = f;
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Headers for authenticated requests (issue, operations, emission lookups,
|
|
636
|
+
* dead letters). `/health` and `/v1/activate` need
|
|
637
|
+
* no issuer proof.
|
|
638
|
+
*
|
|
639
|
+
* Zero-trust auth: the node authenticates an issuer ONLY by the self-verifying
|
|
640
|
+
* proof in `x-certcrypt-issuer-auth` — the system-domain-signed binding over the
|
|
641
|
+
* holder_key_set_root + a leaf disclosure + a possession signature over a fresh
|
|
642
|
+
* challenge, built anew for every request. The node verifies it offline, with
|
|
643
|
+
* no token lookup. No `Authorization` header is sent: the node would ignore it,
|
|
644
|
+
* and a bearer credential handed to a node buys nothing but exposure. Your scope
|
|
645
|
+
* derives from the proof, never from the request body.
|
|
646
|
+
*/
|
|
647
|
+
authHeaders(request, extra) {
|
|
648
|
+
const h = { ...extra };
|
|
649
|
+
if (this.issuerAuthProof) {
|
|
650
|
+
const proof = this.issuerAuthProof(request);
|
|
651
|
+
if (proof)
|
|
652
|
+
h["x-certcrypt-issuer-auth"] = proof;
|
|
653
|
+
}
|
|
654
|
+
return h;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* One fetch bounded by {@link REQUEST_TIMEOUT_MS}: a node that accepts the
|
|
658
|
+
* connection and never answers must not hold the caller forever. The timeout
|
|
659
|
+
* surfaces as a rejected promise, which every caller treats as a transport
|
|
660
|
+
* failure.
|
|
661
|
+
*/
|
|
662
|
+
async fetchWithTimeout(url, init = {}) {
|
|
663
|
+
const controller = new AbortController();
|
|
664
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
665
|
+
try {
|
|
666
|
+
return await this.fetchImpl(url, { ...init, signal: controller.signal });
|
|
667
|
+
}
|
|
668
|
+
finally {
|
|
669
|
+
clearTimeout(timer);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
/** The issuer's half of a read chain over `resource`, minted anew on every call
|
|
673
|
+
* (its challenge is single-use). Empty before activation. */
|
|
674
|
+
issuerReadHeaders(resource) {
|
|
675
|
+
const proof = this.issuerReadProof ? this.issuerReadProof(resource) : null;
|
|
676
|
+
return proof ? { "x-certcrypt-issuer-read": proof } : {};
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* A GET under the transport-retry policy, the same decisions `issue()` makes:
|
|
680
|
+
* a transport failure or a retryable status (408, 425, 429, 5xx) is retried
|
|
681
|
+
* until the time budget runs out, a `Retry-After` on 503/429 is honored
|
|
682
|
+
* without counting as an attempt, and any other answer is returned for the
|
|
683
|
+
* caller to read. Safe because a read changes nothing.
|
|
684
|
+
*
|
|
685
|
+
* Returns the response's status, body and `Retry-After`; throws only when it
|
|
686
|
+
* gives up, naming `label` and how long it tried.
|
|
687
|
+
*/
|
|
688
|
+
async readWithRetry(url, extraHeaders, label) {
|
|
689
|
+
const startedAt = this.now();
|
|
690
|
+
let counted = 0;
|
|
691
|
+
for (;;) {
|
|
692
|
+
let outcome;
|
|
693
|
+
let last;
|
|
694
|
+
try {
|
|
695
|
+
// Fresh proofs per ATTEMPT: the node accepts an auth challenge once and
|
|
696
|
+
// the issuance service a read challenge once, so reusing the first
|
|
697
|
+
// attempt's headers would turn every retry that got through into a 401.
|
|
698
|
+
const headers = this.authHeaders({ method: "GET", url }, extraHeaders());
|
|
699
|
+
const resp = await this.fetchWithTimeout(url, { headers });
|
|
700
|
+
const text = await resp.text();
|
|
701
|
+
const retryAfter = retryAfterOf(resp);
|
|
702
|
+
if (resp.ok)
|
|
703
|
+
return { status: resp.status, ok: true, text, retryAfterMs: null };
|
|
704
|
+
outcome = { kind: "http", status: resp.status, retryAfter: retryAfter.raw };
|
|
705
|
+
last = new CertcryptNodeError(`${label} failed: HTTP ${resp.status}`, resp.status, text, retryAfter.ms);
|
|
706
|
+
}
|
|
707
|
+
catch (e) {
|
|
708
|
+
outcome = { kind: "transport" };
|
|
709
|
+
last = new CertcryptNodeError(`${label} failed: ${String(e)}`, null, null);
|
|
710
|
+
}
|
|
711
|
+
const d = decideRetry(this.retryPolicy, outcome, counted, this.now() - startedAt);
|
|
712
|
+
if (d.action === "return") {
|
|
713
|
+
// About the request, not the transport: hand the answer back as it came.
|
|
714
|
+
return { status: last.status ?? 0, ok: false, text: last.body ?? "", retryAfterMs: last.retryAfterMs };
|
|
715
|
+
}
|
|
716
|
+
if (d.action === "give_up") {
|
|
717
|
+
throw new CertcryptNodeError(`${last.message} — gave up after ${Math.round((this.now() - startedAt) / 1000)}s ` +
|
|
718
|
+
`and ${counted + 1} attempt(s)`, last.status, last.body, last.retryAfterMs);
|
|
719
|
+
}
|
|
720
|
+
if (d.countsAttempt) {
|
|
721
|
+
counted += 1;
|
|
722
|
+
await this.sleepMs(drawBackoffMs(d.waitMsMax));
|
|
723
|
+
}
|
|
724
|
+
else {
|
|
725
|
+
await this.sleepMs(d.waitMs);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Liveness check. True when the node answers /health with a 2xx.
|
|
731
|
+
*
|
|
732
|
+
* One request, never retried, bounded at 30 s, and it never throws: a
|
|
733
|
+
* transport failure (refused, reset, no answer in time) and an error status
|
|
734
|
+
* both report false. A liveness probe that waited out a restart would report
|
|
735
|
+
* the node alive minutes late instead of reporting it down.
|
|
736
|
+
*/
|
|
737
|
+
async health() {
|
|
738
|
+
try {
|
|
739
|
+
const resp = await this.fetchWithTimeout(`${this.baseUrl}/health`);
|
|
740
|
+
return resp.ok;
|
|
741
|
+
}
|
|
742
|
+
catch {
|
|
743
|
+
return false;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Submit a closed submission set for issuance. Returns the node-local
|
|
748
|
+
* operation and its initial state. The happy path is `processing`
|
|
749
|
+
* (finalization is asynchronous); poll [`getOperation`] /
|
|
750
|
+
* [`waitForOperation`].
|
|
751
|
+
*
|
|
752
|
+
* More than `MAX_SUBMISSION_SET_MEMBERS` (64) commitments throw
|
|
753
|
+
* `SubmissionSetTooLargeError` before anything is sent (submission-set/1 §8.1).
|
|
754
|
+
*/
|
|
755
|
+
async issue(req) {
|
|
756
|
+
// The producer refuses to build an over-bound set (submission-set/1 §8.1):
|
|
757
|
+
// fail fast, before the request leaves the process. The node and the
|
|
758
|
+
// submit endpoint reject one independently.
|
|
759
|
+
assertSubmissionSetWithinBound(req.commitments?.length ?? 0);
|
|
760
|
+
// Stable idempotency key: generate ONCE here if the caller didn't, and reuse
|
|
761
|
+
// the SAME id across every retry. The server deduplicates on it (a
|
|
762
|
+
// replay returns the original outcome), so a retry never double-submits. If we let the node generate it
|
|
763
|
+
// (its fallback), each retry would get a NEW id → not idempotent. The signed
|
|
764
|
+
// evidence inside `req` is built once and reused verbatim on every attempt —
|
|
765
|
+
// a retry is transport-only, it NEVER re-signs: a leaf must not be reused.
|
|
766
|
+
const idemReq = {
|
|
767
|
+
...req,
|
|
768
|
+
request_id: req.request_id ?? newUlid(),
|
|
769
|
+
};
|
|
770
|
+
const startedAt = this.now();
|
|
771
|
+
let counted = 0;
|
|
772
|
+
for (;;) {
|
|
773
|
+
let outcome;
|
|
774
|
+
let last;
|
|
775
|
+
try {
|
|
776
|
+
const attempt = await this.issueOnce(idemReq);
|
|
777
|
+
if (attempt.ok) {
|
|
778
|
+
// Decide retryable vs final from the per-member results (or whole-request
|
|
779
|
+
// state). A response with any non-final member is retryable; otherwise
|
|
780
|
+
// return it — `accepted_for_retry` included: the node holds the set.
|
|
781
|
+
if (this.isResponseFinal(attempt.body))
|
|
782
|
+
return attempt.body;
|
|
783
|
+
outcome = { kind: "transport" };
|
|
784
|
+
last = new CertcryptNodeError(`issue not final (retryable): ${JSON.stringify(attempt.body.state ?? attempt.body.results)}`, attempt.status, attempt.text);
|
|
785
|
+
}
|
|
786
|
+
else {
|
|
787
|
+
outcome = { kind: "http", status: attempt.status, retryAfter: attempt.retryAfter.raw };
|
|
788
|
+
last = new CertcryptNodeError(`issue failed: HTTP ${attempt.status}${describeState(attempt.text)}`, attempt.status, attempt.text, attempt.retryAfter.ms);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
catch (e) {
|
|
792
|
+
if (e instanceof UnparseableIssueResponse) {
|
|
793
|
+
// A 2xx whose body is not a JSON object: the answer was lost on the
|
|
794
|
+
// way, not given. Retrying is safe — the request is idempotent on its
|
|
795
|
+
// request_id, so the node answers the same set the same way.
|
|
796
|
+
outcome = { kind: "transport" };
|
|
797
|
+
last = new CertcryptNodeError(e.message, e.status, e.text);
|
|
798
|
+
}
|
|
799
|
+
else {
|
|
800
|
+
// No HTTP answer at all: refused, reset, timed out — the node restarting.
|
|
801
|
+
outcome = { kind: "transport" };
|
|
802
|
+
last = new CertcryptNodeError(`issue failed: ${String(e)}`, null, null);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
const d = decideRetry(this.retryPolicy, outcome, counted, this.now() - startedAt);
|
|
806
|
+
if (d.action === "return")
|
|
807
|
+
throw last; // about the request, not the transport
|
|
808
|
+
if (d.action === "give_up") {
|
|
809
|
+
throw new CertcryptNodeError(`${last.message} — gave up after ${Math.round((this.now() - startedAt) / 1000)}s ` +
|
|
810
|
+
`and ${counted + 1} attempt(s)`, last.status, last.body, last.retryAfterMs);
|
|
811
|
+
}
|
|
812
|
+
if (d.countsAttempt) {
|
|
813
|
+
counted += 1;
|
|
814
|
+
await this.sleepMs(drawBackoffMs(d.waitMsMax));
|
|
815
|
+
}
|
|
816
|
+
else {
|
|
817
|
+
await this.sleepMs(d.waitMs);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
/** One POST attempt. Throws on transport error; returns status, body and the
|
|
822
|
+
* node's `Retry-After`. */
|
|
823
|
+
async issueOnce(req) {
|
|
824
|
+
const url = `${this.baseUrl}/v1/issue`;
|
|
825
|
+
const payload = JSON.stringify(req);
|
|
826
|
+
const resp = await this.fetchWithTimeout(url, {
|
|
827
|
+
method: "POST",
|
|
828
|
+
headers: this.authHeaders({ method: "POST", url, body: payload }, { "content-type": "application/json" }),
|
|
829
|
+
body: payload,
|
|
830
|
+
});
|
|
831
|
+
const text = await resp.text();
|
|
832
|
+
let parsed;
|
|
833
|
+
try {
|
|
834
|
+
parsed = JSON.parse(text);
|
|
835
|
+
}
|
|
836
|
+
catch {
|
|
837
|
+
parsed = undefined;
|
|
838
|
+
}
|
|
839
|
+
const isObject = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
|
|
840
|
+
if (resp.ok && !isObject)
|
|
841
|
+
throw new UnparseableIssueResponse(resp.status, text);
|
|
842
|
+
const body = (isObject ? parsed : {});
|
|
843
|
+
return { ok: resp.ok, status: resp.status, text, body, retryAfter: retryAfterOf(resp) };
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* A response is FINAL (stop retrying) when every member reached a terminal
|
|
847
|
+
* verdict and there is no whole-request transient failure. A whole-request
|
|
848
|
+
* `submission_failed` (the node could not reach the server) is retryable.
|
|
849
|
+
*/
|
|
850
|
+
isResponseFinal(res) {
|
|
851
|
+
if (res.state && res.state.state === "submission_failed")
|
|
852
|
+
return false;
|
|
853
|
+
if (res.state)
|
|
854
|
+
return isNonRetryableState(res.state.state);
|
|
855
|
+
if (res.results && res.results.length > 0) {
|
|
856
|
+
return res.results.every((m) => isNonRetryableState(m.state.state));
|
|
857
|
+
}
|
|
858
|
+
// No state and no results: treat as retryable (incomplete).
|
|
859
|
+
return false;
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Convenience: issue 1..N already-built loose commitments in one call, under a
|
|
863
|
+
* request_id this client generates. The node wraps them into one submission-set. All
|
|
864
|
+
* commitments MUST share issuer + authorization. Use for a batch the
|
|
865
|
+
* caller already has signed on hand (e.g. a nightly import).
|
|
866
|
+
*/
|
|
867
|
+
async issueCommitments(commitments) {
|
|
868
|
+
return this.issue({ commitments });
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Activate an integration by redeeming a one-time activation code (OTP, TOFU).
|
|
872
|
+
* The node forwards this to the server's `POST /v1/activate`; the server redeems the
|
|
873
|
+
* code, mints the Level-1 authorization over `holderKeySetRoot`, and returns
|
|
874
|
+
* the signed binding INLINE. The caller (usually `Certcrypt`) caches the
|
|
875
|
+
* returned binding as its `signedLevel1` and stops presenting the code.
|
|
876
|
+
*
|
|
877
|
+
* The SDK talks ONLY to the node; this is the node route, not the server.
|
|
878
|
+
* `rulesVersion` and `systemRootFingerprint` come from the issuer's onboarding
|
|
879
|
+
* config (the server validates the fingerprint matches its own domain).
|
|
880
|
+
*/
|
|
881
|
+
async activate(params) {
|
|
882
|
+
const url = `${this.baseUrl}/v1/activate`;
|
|
883
|
+
const body = JSON.stringify({
|
|
884
|
+
code: params.code,
|
|
885
|
+
holder_key_set_root: params.holderKeySetRoot,
|
|
886
|
+
key_set_disclosure: params.keySetDisclosure,
|
|
887
|
+
key_set_possession_b64: params.keySetPossessionB64,
|
|
888
|
+
rules_version: params.rulesVersion,
|
|
889
|
+
system_root_fingerprint: params.systemRootFingerprint,
|
|
890
|
+
valid_until: params.validUntil,
|
|
891
|
+
});
|
|
892
|
+
const resp = await this.fetchWithTimeout(url, {
|
|
893
|
+
method: "POST",
|
|
894
|
+
headers: this.authHeaders({ method: "POST", url, body }, { "content-type": "application/json" }),
|
|
895
|
+
body,
|
|
896
|
+
});
|
|
897
|
+
if (!resp.ok) {
|
|
898
|
+
const text = await resp.text();
|
|
899
|
+
throw new CertcryptNodeError(`activate failed: HTTP ${resp.status}${describeState(text)}`, resp.status, text, retryAfterOf(resp).ms);
|
|
900
|
+
}
|
|
901
|
+
// The server binds the integration's canonical (holder_id, pool_id) at
|
|
902
|
+
// activation and echoes both here (relayed verbatim by the node). The caller
|
|
903
|
+
// MUST emit under this holder_id: it is the identity the activation bound, and
|
|
904
|
+
// emitting under a self-chosen one would not be accounted for against this
|
|
905
|
+
// integration at all.
|
|
906
|
+
//
|
|
907
|
+
// Fail closed: a 200 that is not an activation (not an object, a field
|
|
908
|
+
// missing or of the wrong type, a status other than the two successes) is
|
|
909
|
+
// refused before anything is returned, so nothing is cached or persisted.
|
|
910
|
+
const text = await resp.text();
|
|
911
|
+
let parsed;
|
|
912
|
+
try {
|
|
913
|
+
parsed = JSON.parse(text);
|
|
914
|
+
}
|
|
915
|
+
catch {
|
|
916
|
+
parsed = undefined;
|
|
917
|
+
}
|
|
918
|
+
return parseActivation(parsed);
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Mint + sign one verifiable certificate and its loose commitment WITHOUT
|
|
922
|
+
* sending anything: the ONE place a certificate is minted and signed.
|
|
923
|
+
*
|
|
924
|
+
* Exists so N certificates can be prepared and then submitted in ONE `issue()`
|
|
925
|
+
* request (grouping amortizes the per-submission overhead across all N).
|
|
926
|
+
* Synchronous: no request is made, nothing is awaited.
|
|
927
|
+
*
|
|
928
|
+
* Everything irreversible happens HERE — the base_certificate is signed and
|
|
929
|
+
* `leafIndex`/`operationSalt` are spent. A commitment that is minted and never
|
|
930
|
+
* sent leaves its leaf spent; a retry re-sends this exact commitment rather than
|
|
931
|
+
* minting a new one.
|
|
932
|
+
*/
|
|
933
|
+
mintVerifiableCertificate(params) {
|
|
934
|
+
// 1. Mint + sign the base_certificate from the subjects' original material.
|
|
935
|
+
// The target choice decides whether the anchor carries root_id (the signed
|
|
936
|
+
// participation reference). issued-only omits it consciously; independent-
|
|
937
|
+
// capable requires it — a defaulted omission can never be repaired later.
|
|
938
|
+
const rootIdField = params.target.mode === "independent-capable"
|
|
939
|
+
? { root_id: params.target.root_id }
|
|
940
|
+
: {};
|
|
941
|
+
const minted = assembleBaseCertificate({
|
|
942
|
+
subjects: params.subjects,
|
|
943
|
+
nonce_hex: params.anchor.nonce_hex,
|
|
944
|
+
issued_at: params.anchor.issued_at,
|
|
945
|
+
...rootIdField,
|
|
946
|
+
system_id: params.anchor.system_id,
|
|
947
|
+
rules_version: params.anchor.rules_version,
|
|
948
|
+
issuerKey: params.issuerKey,
|
|
949
|
+
});
|
|
950
|
+
// 2. Sign the zero-data evidence over the REAL cert digest (never an opaque
|
|
951
|
+
// string of unknown origin). The holder signs only the Level-3 projected
|
|
952
|
+
// commitment with a non-reused leaf of its operation-key tree; the Level-1
|
|
953
|
+
// anchor (`signedLevel1`) comes from the holder-authorization endpoint and
|
|
954
|
+
// is carried verbatim.
|
|
955
|
+
if (this.poolId && params.poolId && params.poolId !== this.poolId) {
|
|
956
|
+
throw new CertcryptNodeError(`mintVerifiableCertificate: pool "${params.poolId}" is not this client's ` +
|
|
957
|
+
`pool "${this.poolId}" (one integration = one pool)`, null, null);
|
|
958
|
+
}
|
|
959
|
+
const poolId = params.poolId ?? this.poolId;
|
|
960
|
+
if (!poolId) {
|
|
961
|
+
throw new CertcryptNodeError("mintVerifiableCertificate requires a pool_id, in NodeClientOptions or as " +
|
|
962
|
+
"poolId (the integration's pool; one integration = one pool)", null, null);
|
|
963
|
+
}
|
|
964
|
+
const evidence = assembleEvidence({
|
|
965
|
+
signedLevel1: params.signedLevel1,
|
|
966
|
+
certificate_commitment_digest: minted.certificate_commitment_digest,
|
|
967
|
+
consumed_quantity: params.evidenceFields.consumed_quantity,
|
|
968
|
+
declared_effective_units: params.evidenceFields.declared_effective_units,
|
|
969
|
+
issued_at: params.evidenceFields.issued_at,
|
|
970
|
+
expires_at: params.evidenceFields.expires_at,
|
|
971
|
+
// `pool_id` is the instance's configured pool, stamped into both the
|
|
972
|
+
// operative context and the projected pool pseudonym — never chosen per call.
|
|
973
|
+
stable: {
|
|
974
|
+
holder_id: params.holderId,
|
|
975
|
+
pool_id: poolId,
|
|
976
|
+
authorization_id: params.authorizationId,
|
|
977
|
+
},
|
|
978
|
+
keySet: params.keySet,
|
|
979
|
+
leafIndex: params.leafIndex,
|
|
980
|
+
operationSalt: params.operationSalt,
|
|
981
|
+
});
|
|
982
|
+
// The SDK is thin: ship the signed evidence as ONE loose commitment. The node
|
|
983
|
+
// is the builder that wraps it into the submission-set.
|
|
984
|
+
const commitment = {
|
|
985
|
+
capacity_evidence: evidence,
|
|
986
|
+
operative: { holder_id: params.holderId, pool_id: poolId },
|
|
987
|
+
};
|
|
988
|
+
return { commitment, minted };
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Read one emission by the digest of the capacity evidence that produced it.
|
|
992
|
+
*
|
|
993
|
+
* The lookup that outlives the node. A node's operation id lives in THAT node's
|
|
994
|
+
* journal, so a restart with an in-memory journal — or moving to another node,
|
|
995
|
+
* which the model treats as changing a URL — leaves the issuer unable to ask
|
|
996
|
+
* about an emission the issuance service still holds. The digest has no such
|
|
997
|
+
* problem: the issuer recomputes it from evidence it signed itself.
|
|
998
|
+
*
|
|
999
|
+
* The read chain is unchanged, and the signed resource is the digest. That is
|
|
1000
|
+
* stronger than signing an id the node handed over: the issuer can check what
|
|
1001
|
+
* the digest means, because it produced it.
|
|
1002
|
+
*/
|
|
1003
|
+
async getEmissionByCommitment(independenceRef) {
|
|
1004
|
+
// No id translation here, unlike getOperation: the digest IS the resource
|
|
1005
|
+
// the issuance service routes and verifies on.
|
|
1006
|
+
const resp = await this.readWithRetry(`${this.baseUrl}/v1/emissions/by-commitment/${encodeURIComponent(independenceRef)}`, () => this.issuerReadHeaders(independenceRef), "getEmissionByCommitment");
|
|
1007
|
+
if (resp.status === 404) {
|
|
1008
|
+
throw new CertcryptNodeError(`no emission for capacity-evidence digest ${independenceRef}`, 404, null);
|
|
1009
|
+
}
|
|
1010
|
+
if (!resp.ok) {
|
|
1011
|
+
throw new CertcryptNodeError(`getEmissionByCommitment failed: HTTP ${resp.status}`, resp.status, resp.text, resp.retryAfterMs);
|
|
1012
|
+
}
|
|
1013
|
+
return JSON.parse(resp.text);
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* This integration's submissions the node gave up delivering (dead-lettered).
|
|
1017
|
+
*
|
|
1018
|
+
* A node keeps retrying an unreachable or unavailable server for as long as
|
|
1019
|
+
* it takes; what lands here is a refusal about the request or the node's own
|
|
1020
|
+
* credentials, which retrying unchanged cannot fix. Empty is the healthy
|
|
1021
|
+
* answer. Delivery metadata only — never the stored set.
|
|
1022
|
+
*/
|
|
1023
|
+
async listDeadLetters() {
|
|
1024
|
+
const resp = await this.readWithRetry(`${this.baseUrl}/v1/outbox/dead`, () => ({}), "listDeadLetters");
|
|
1025
|
+
if (!resp.ok) {
|
|
1026
|
+
throw new CertcryptNodeError(`listDeadLetters failed: HTTP ${resp.status}`, resp.status, resp.text, resp.retryAfterMs);
|
|
1027
|
+
}
|
|
1028
|
+
const body = JSON.parse(resp.text);
|
|
1029
|
+
return (body.dead ?? []).map((d) => ({
|
|
1030
|
+
requestId: String(d.request_id ?? ""),
|
|
1031
|
+
attempts: Number(d.attempts ?? 0),
|
|
1032
|
+
createdAtMs: Number(d.created_at_ms ?? 0),
|
|
1033
|
+
lastError: typeof d.last_error === "string" ? d.last_error : null,
|
|
1034
|
+
}));
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Put one dead-lettered submission back in the node's delivery queue, once
|
|
1038
|
+
* whatever refused it has been fixed. The node resends the SAME signed set
|
|
1039
|
+
* under the same `request_id` — nothing is re-signed, and the server
|
|
1040
|
+
* deduplicates. Throws 404 for an id this integration does not own.
|
|
1041
|
+
*/
|
|
1042
|
+
async redriveDeadLetter(requestId) {
|
|
1043
|
+
const url = `${this.baseUrl}/v1/outbox/dead/${encodeURIComponent(requestId)}/redrive`;
|
|
1044
|
+
const resp = await this.fetchWithTimeout(url, {
|
|
1045
|
+
method: "POST",
|
|
1046
|
+
headers: this.authHeaders({ method: "POST", url }),
|
|
1047
|
+
});
|
|
1048
|
+
if (!resp.ok) {
|
|
1049
|
+
throw new CertcryptNodeError(`redriveDeadLetter failed: HTTP ${resp.status}`, resp.status, await resp.text(), retryAfterOf(resp).ms);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Fetch the current state of a node-local operation. Retried under the
|
|
1054
|
+
* transport-retry policy, like every read; a 404 (unknown id) is not.
|
|
1055
|
+
*/
|
|
1056
|
+
async getOperation(operationId) {
|
|
1057
|
+
return this.readOperation(operationId, true);
|
|
1058
|
+
}
|
|
1059
|
+
/** One operation read; `retry` false sends exactly one request (the wait loop
|
|
1060
|
+
* owns its own retrying). */
|
|
1061
|
+
async readOperation(operationId, retry) {
|
|
1062
|
+
// The issuer's half of the read chain, bound to THIS operation id. The node
|
|
1063
|
+
// adds its own half and forwards both; the server verifies the pair. Binding the
|
|
1064
|
+
// resource is what stops a signature captured for one read from being
|
|
1065
|
+
// replayed against another operation.
|
|
1066
|
+
const url = `${this.baseUrl}/v1/operations/${encodeURIComponent(operationId)}`;
|
|
1067
|
+
let resp;
|
|
1068
|
+
if (retry) {
|
|
1069
|
+
resp = await this.readWithRetry(url, () => this.issuerReadHeaders(operationId), "getOperation");
|
|
1070
|
+
}
|
|
1071
|
+
else {
|
|
1072
|
+
const headers = this.authHeaders({ method: "GET", url }, this.issuerReadHeaders(operationId));
|
|
1073
|
+
const r = await this.fetchWithTimeout(url, { headers });
|
|
1074
|
+
resp = { status: r.status, ok: r.ok, text: await r.text(), retryAfterMs: retryAfterOf(r).ms };
|
|
1075
|
+
}
|
|
1076
|
+
if (resp.status === 404) {
|
|
1077
|
+
throw new CertcryptNodeError(`operation not found: ${operationId}`, 404, null);
|
|
1078
|
+
}
|
|
1079
|
+
if (!resp.ok) {
|
|
1080
|
+
throw new CertcryptNodeError(`getOperation failed: HTTP ${resp.status}`, resp.status, resp.text, resp.retryAfterMs);
|
|
1081
|
+
}
|
|
1082
|
+
const body = JSON.parse(resp.text);
|
|
1083
|
+
const record = normalizeOperationRecord(body);
|
|
1084
|
+
// A member the node delivered LATE (it answered `accepted_for_retry` at
|
|
1085
|
+
// submit) reaches `accepted` with an upstream id the issuer was never told.
|
|
1086
|
+
// The node's local record carries it; hand it over so the next read signs
|
|
1087
|
+
// the id the server routes on. Until then the node serves its local record,
|
|
1088
|
+
// so the cost is one poll, not a stuck operation.
|
|
1089
|
+
if (this.onUpstreamOperationId && record.state.state === "accepted") {
|
|
1090
|
+
const up = record.state.upstream_operation_id;
|
|
1091
|
+
if (up)
|
|
1092
|
+
this.onUpstreamOperationId(operationId, up);
|
|
1093
|
+
}
|
|
1094
|
+
return record;
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* List the emissions this integration has in flight — neither independently
|
|
1098
|
+
* verifiable yet nor terminally refused.
|
|
1099
|
+
*
|
|
1100
|
+
* `getOperation` requires an id, and an issuer that lost its handles lost the
|
|
1101
|
+
* ids with them: they travel only in the emission response. This endpoint lets
|
|
1102
|
+
* such an issuer enumerate its in-flight emissions instead of re-emitting,
|
|
1103
|
+
* which would open a second node operation for the same certificate — the
|
|
1104
|
+
* outcome the handle exists to prevent.
|
|
1105
|
+
*
|
|
1106
|
+
* Scope is this integration, resolved upstream from the key-set root proven by
|
|
1107
|
+
* the read chain, not from any credential of the node that relays it.
|
|
1108
|
+
*
|
|
1109
|
+
* The response carries no handle material. Each entry states what exists and
|
|
1110
|
+
* when to poll again; fetch the recoverable half one emission at a time.
|
|
1111
|
+
*
|
|
1112
|
+
* `truncated` means the page hit the server cap: narrow `since` rather than
|
|
1113
|
+
* treat the list as complete. A reconciler needs to distinguish a full listing
|
|
1114
|
+
* from a first page.
|
|
1115
|
+
*/
|
|
1116
|
+
async listUnresolvedEmissions(since, limit) {
|
|
1117
|
+
// The signed resource is the QUERY, not an id — a caller that lost its
|
|
1118
|
+
// handles has none. `since` is signed and sent as the SAME string: the node
|
|
1119
|
+
// relays it verbatim and the issuance service verifies both halves over identical bytes,
|
|
1120
|
+
// so reformatting it anywhere breaks the chain silently.
|
|
1121
|
+
const qs = new URLSearchParams({ since });
|
|
1122
|
+
if (limit !== undefined)
|
|
1123
|
+
qs.set("limit", String(limit));
|
|
1124
|
+
const resp = await this.readWithRetry(`${this.baseUrl}/v1/emissions/unresolved?${qs.toString()}`, () => this.issuerReadHeaders(`emissions:unresolved:${since}`), "listUnresolvedEmissions");
|
|
1125
|
+
if (!resp.ok) {
|
|
1126
|
+
// No empty-list fallback on failure: a reconciler would read that as
|
|
1127
|
+
// "nothing pending" and act on it by re-emitting.
|
|
1128
|
+
throw new CertcryptNodeError(`listUnresolvedEmissions failed: HTTP ${resp.status}`, resp.status, resp.text, resp.retryAfterMs);
|
|
1129
|
+
}
|
|
1130
|
+
const body = JSON.parse(resp.text);
|
|
1131
|
+
const raw = Array.isArray(body.emissions) ? body.emissions : [];
|
|
1132
|
+
return {
|
|
1133
|
+
emissions: raw.map((e) => {
|
|
1134
|
+
const r = e;
|
|
1135
|
+
return {
|
|
1136
|
+
operationId: String(r.operation_id ?? ""),
|
|
1137
|
+
status: String(r.status ?? ""),
|
|
1138
|
+
reasonCode: r.reason_code ?? null,
|
|
1139
|
+
updatedAt: String(r.updated_at ?? ""),
|
|
1140
|
+
targetCloseBy: r.target_close_by ?? null,
|
|
1141
|
+
expectedSettledBy: r.expected_settled_by ?? null,
|
|
1142
|
+
settledAt: r.settled_at ?? null,
|
|
1143
|
+
commitmentCount: Number(r.commitment_count ?? 0),
|
|
1144
|
+
};
|
|
1145
|
+
}),
|
|
1146
|
+
truncated: body.truncated === true,
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
/**
|
|
1150
|
+
* Poll an operation until it reaches a terminal state (independent_ready,
|
|
1151
|
+
* rejected, expired, replay_detected, insufficient_capacity,
|
|
1152
|
+
* pre_evaluation_rejected, submission_failed), or throw.
|
|
1153
|
+
*
|
|
1154
|
+
* When the wait ends without one — attempts or `maxWaitMs` exhausted — this
|
|
1155
|
+
* throws `CertcryptNodeError` ("did not reach a terminal state"): the
|
|
1156
|
+
* operation is still progressing and the caller's handle stays valid, so poll
|
|
1157
|
+
* again later. A transient poll failure does not abort the wait; five
|
|
1158
|
+
* consecutive ones do, and a 404 (unknown id) surfaces at once. A node that
|
|
1159
|
+
* asks for a pause (503 or 429 with `Retry-After`) is waited out without
|
|
1160
|
+
* counting it as a failure. Each poll is one request, and time is read from
|
|
1161
|
+
* the client's clock.
|
|
1162
|
+
*/
|
|
1163
|
+
async waitForOperation(operationId, opts = {}) {
|
|
1164
|
+
// A caller that passes intervalMs/maxAttempts gets fixed-interval polling.
|
|
1165
|
+
// Only a caller that passes neither (or asks for it) gets the window-aware
|
|
1166
|
+
// scheduling.
|
|
1167
|
+
const explicitlyFixed = opts.intervalMs !== undefined || opts.maxAttempts !== undefined;
|
|
1168
|
+
const strategy = opts.strategy ?? (explicitlyFixed ? "fixed" : "auto");
|
|
1169
|
+
const intervalMs = opts.intervalMs ?? 1000;
|
|
1170
|
+
const backoffBaseMs = opts.backoffBaseMs ?? 1000;
|
|
1171
|
+
const backoffCapMs = opts.backoffCapMs ?? 30_000;
|
|
1172
|
+
// In fixed mode the attempt cap defaults to 60; in auto mode the wall
|
|
1173
|
+
// clock is the real bound and attempts are effectively unlimited.
|
|
1174
|
+
const maxAttempts = opts.maxAttempts ?? (strategy === "fixed" ? 60 : Number.MAX_SAFE_INTEGER);
|
|
1175
|
+
const maxWaitMs = opts.maxWaitMs ?? (strategy === "fixed" ? Number.POSITIVE_INFINITY : DEFAULT_MAX_WAIT_MS);
|
|
1176
|
+
const startedAt = this.now();
|
|
1177
|
+
let last = null;
|
|
1178
|
+
let pollErrors = 0; // consecutive transient poll failures
|
|
1179
|
+
let lastWindow;
|
|
1180
|
+
// Sticky like `lastWindow`: a tick whose response omitted it should keep
|
|
1181
|
+
// reporting the last thing we actually knew rather than silently regressing.
|
|
1182
|
+
let lastSettlement;
|
|
1183
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1184
|
+
try {
|
|
1185
|
+
// One request per tick: this loop owns the retrying, so a blip is
|
|
1186
|
+
// counted here and a requested pause is bounded by `maxWaitMs`.
|
|
1187
|
+
last = await this.readOperation(operationId, false);
|
|
1188
|
+
pollErrors = 0;
|
|
1189
|
+
// Remember the last window the node reported: once the operation goes
|
|
1190
|
+
// terminal the field is gone, and a transient blip should not lose the
|
|
1191
|
+
// schedule we were waiting on.
|
|
1192
|
+
if (last.settlement_window)
|
|
1193
|
+
lastWindow = last.settlement_window;
|
|
1194
|
+
if (last.settlement_progress)
|
|
1195
|
+
lastSettlement = last.settlement_progress;
|
|
1196
|
+
if (isTerminal(last.state))
|
|
1197
|
+
return last;
|
|
1198
|
+
}
|
|
1199
|
+
catch (e) {
|
|
1200
|
+
// A transient blip during polling (network, 5xx) must NOT abort the
|
|
1201
|
+
// wait — keep polling. A 404 is different (the op id is wrong); surface
|
|
1202
|
+
// it. Give up only after several consecutive transient failures.
|
|
1203
|
+
if (e instanceof CertcryptNodeError && e.status === 404)
|
|
1204
|
+
throw e;
|
|
1205
|
+
// The node asked for a pause (a restart): wait it out without counting
|
|
1206
|
+
// it as a failure — the same rule the submit path follows.
|
|
1207
|
+
if (e instanceof CertcryptNodeError && e.retryAfterMs !== null) {
|
|
1208
|
+
const asked = Math.min(Math.max(e.retryAfterMs, RETRY_AFTER_MIN_MS), RETRY_AFTER_MAX_MS);
|
|
1209
|
+
const left = maxWaitMs - (this.now() - startedAt);
|
|
1210
|
+
if (left <= 0)
|
|
1211
|
+
break;
|
|
1212
|
+
await this.sleepMs(Math.min(asked, left));
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
pollErrors += 1;
|
|
1216
|
+
if (pollErrors >= 5)
|
|
1217
|
+
throw e;
|
|
1218
|
+
}
|
|
1219
|
+
const now = this.now();
|
|
1220
|
+
const elapsedMs = now - startedAt;
|
|
1221
|
+
const { delayMs, overdue } = strategy === "fixed"
|
|
1222
|
+
? { delayMs: intervalMs, overdue: false }
|
|
1223
|
+
: nextPollDelayMs({
|
|
1224
|
+
attempt: attempt + 1,
|
|
1225
|
+
now,
|
|
1226
|
+
window: lastWindow,
|
|
1227
|
+
backoffBaseMs,
|
|
1228
|
+
backoffCapMs,
|
|
1229
|
+
random: this.random,
|
|
1230
|
+
});
|
|
1231
|
+
// Stop at the wall-clock bound rather than sleeping past it.
|
|
1232
|
+
const remaining = maxWaitMs - elapsedMs;
|
|
1233
|
+
if (remaining <= 0)
|
|
1234
|
+
break;
|
|
1235
|
+
const sleepMs = Math.min(delayMs, remaining);
|
|
1236
|
+
const progress = {
|
|
1237
|
+
attempt: attempt + 1,
|
|
1238
|
+
nodeState: last?.state.state ?? "unknown",
|
|
1239
|
+
nextCheckInMs: sleepMs,
|
|
1240
|
+
elapsedMs,
|
|
1241
|
+
...(lastWindow ? { window: lastWindow } : {}),
|
|
1242
|
+
...(lastSettlement ? { settlement: lastSettlement } : {}),
|
|
1243
|
+
overdue,
|
|
1244
|
+
};
|
|
1245
|
+
const message = describeWait(progress);
|
|
1246
|
+
if (opts.onProgress) {
|
|
1247
|
+
try {
|
|
1248
|
+
opts.onProgress({ ...progress, message });
|
|
1249
|
+
}
|
|
1250
|
+
catch {
|
|
1251
|
+
// A reporting callback must never break the wait.
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
else if (sleepMs >= QUIET_WAIT_WARN_MS || overdue) {
|
|
1255
|
+
// NOBODY is listening and we are about to sleep for a long time (or the
|
|
1256
|
+
// operation is already late). An unannounced multi-minute sleep is
|
|
1257
|
+
// indistinguishable from a hang, and the issuer would reasonably kill the
|
|
1258
|
+
// process. Say it once per tick on the console; a caller that wants
|
|
1259
|
+
// structured reporting passes onProgress and this never fires.
|
|
1260
|
+
// eslint-disable-next-line no-console
|
|
1261
|
+
console.info(`[certcrypt] operation ${operationId}: ${message}`);
|
|
1262
|
+
}
|
|
1263
|
+
await this.sleepMs(sleepMs);
|
|
1264
|
+
}
|
|
1265
|
+
const waited = this.now() - startedAt;
|
|
1266
|
+
throw new CertcryptNodeError(`operation ${operationId} did not reach a terminal state after ${Math.round(waited / 1000)}s` +
|
|
1267
|
+
(last ? ` (last state: ${last.state.state})` : "") +
|
|
1268
|
+
(lastWindow?.expected_settled_by
|
|
1269
|
+
? `; operator expected window ${lastWindow.window_profile} to be settled by ` +
|
|
1270
|
+
`${lastWindow.expected_settled_by}` +
|
|
1271
|
+
(isSettlementOverdue(lastWindow, this.now())
|
|
1272
|
+
? ` — it is OVERDUE: settlement is past the operator's expected instant`
|
|
1273
|
+
: "")
|
|
1274
|
+
: lastWindow?.target_close_by
|
|
1275
|
+
? `; node expected window ${lastWindow.window_profile} to close by ${lastWindow.target_close_by}` +
|
|
1276
|
+
` — it is OVERDUE: settlement is taking longer than the window allows`
|
|
1277
|
+
: ""), null, null);
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Assemble the full `verification-package/1` for one operation so the issuer
|
|
1281
|
+
* can verify its OWN Proof of Independence OFFLINE (dogfooding). No new node
|
|
1282
|
+
* surface: the node is a non-custodian and never returns base_certificate /
|
|
1283
|
+
* capacity_evidence / the commitment inclusion proof. This gathers:
|
|
1284
|
+
* - base_certificate + capacity_evidence — client-held (passed in);
|
|
1285
|
+
* - independence_proof + settlement_material — from GET /v1/operations/{id}
|
|
1286
|
+
* once independent_ready (base64 → parsed JSON);
|
|
1287
|
+
* - commitment_inclusion_proof — DERIVED locally from the proof's
|
|
1288
|
+
* `consumed_commitment_ids` + this commitment's index (same Merkle
|
|
1289
|
+
* primitive the verifier recomputes).
|
|
1290
|
+
*
|
|
1291
|
+
* Throws if the operation is not `independent_ready`, if the server artifacts are
|
|
1292
|
+
* missing, or if the proof lacks `consumed_commitment_ids`.
|
|
1293
|
+
*/
|
|
1294
|
+
async buildVerificationPackage(operationId, opts) {
|
|
1295
|
+
const rec = await this.waitForOperation(operationId, opts.wait);
|
|
1296
|
+
if (rec.state.state !== "independent_ready") {
|
|
1297
|
+
throw new CertcryptNodeError(`operation ${operationId} is not independent_ready (state: ${rec.state.state}) — no proof to package`, null, null);
|
|
1298
|
+
}
|
|
1299
|
+
if (!rec.independence_proof || !rec.settlement_material) {
|
|
1300
|
+
throw new CertcryptNodeError(`operation ${operationId} reached independent_ready but the node returned no proof/settlement material`, null, null);
|
|
1301
|
+
}
|
|
1302
|
+
const independenceProof = JSON.parse(Buffer.from(rec.independence_proof, "base64").toString("utf8"));
|
|
1303
|
+
const settlementMaterial = JSON.parse(Buffer.from(rec.settlement_material, "base64").toString("utf8"));
|
|
1304
|
+
const consumedIds = independenceProof.consumed_commitment_ids;
|
|
1305
|
+
if (!Array.isArray(consumedIds) || consumedIds.length === 0) {
|
|
1306
|
+
throw new CertcryptNodeError(`independence_proof for ${operationId} has no consumed_commitment_ids — cannot derive the inclusion proof`, null, null);
|
|
1307
|
+
}
|
|
1308
|
+
const commitmentInclusionProof = buildCommitmentInclusionProof(consumedIds, opts.commitmentIndex);
|
|
1309
|
+
return {
|
|
1310
|
+
base_certificate: opts.baseCertificate,
|
|
1311
|
+
independence_proof: independenceProof,
|
|
1312
|
+
verification_context: opts.verificationContext,
|
|
1313
|
+
capacity_evidence: opts.capacityEvidence,
|
|
1314
|
+
commitment_inclusion_proof: commitmentInclusionProof,
|
|
1315
|
+
settlement_material: settlementMaterial,
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Assemble a `verification_package` from artifacts already in hand.
|
|
1320
|
+
*
|
|
1321
|
+
* Same shaping as `buildVerificationPackage`, without the polling: the caller
|
|
1322
|
+
* recovered the proof and the settlement material some other way — by the
|
|
1323
|
+
* capacity-evidence digest, typically, when the node that emitted no longer has
|
|
1324
|
+
* the operation.
|
|
1325
|
+
*
|
|
1326
|
+
* The package is identical either way. Nothing here is node-supplied: the
|
|
1327
|
+
* inclusion proof is derived from the proof's own `consumed_commitment_ids`, and
|
|
1328
|
+
* the rest comes from the handle the issuer kept.
|
|
1329
|
+
*/
|
|
1330
|
+
assembleVerificationPackageFromProof(opts) {
|
|
1331
|
+
const independenceProof = JSON.parse(Buffer.from(opts.independenceProofB64, "base64").toString("utf8"));
|
|
1332
|
+
const settlementMaterial = JSON.parse(Buffer.from(opts.settlementMaterialB64, "base64").toString("utf8"));
|
|
1333
|
+
const consumedIds = independenceProof.consumed_commitment_ids;
|
|
1334
|
+
if (!Array.isArray(consumedIds) || consumedIds.length === 0) {
|
|
1335
|
+
throw new CertcryptNodeError("independence_proof has no consumed_commitment_ids — cannot derive the inclusion proof", null, null);
|
|
1336
|
+
}
|
|
1337
|
+
return {
|
|
1338
|
+
base_certificate: opts.baseCertificate,
|
|
1339
|
+
independence_proof: independenceProof,
|
|
1340
|
+
verification_context: opts.verificationContext,
|
|
1341
|
+
capacity_evidence: opts.capacityEvidence,
|
|
1342
|
+
commitment_inclusion_proof: buildCommitmentInclusionProof(consumedIds, opts.commitmentIndex),
|
|
1343
|
+
settlement_material: settlementMaterial,
|
|
1344
|
+
};
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
//# sourceMappingURL=client.js.map
|