@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.

Files changed (71) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +178 -0
  3. package/README.md +557 -2
  4. package/SECURITY.md +55 -0
  5. package/dist/src/artifacts/base-certificate.d.ts +336 -0
  6. package/dist/src/artifacts/base-certificate.js +373 -0
  7. package/dist/src/artifacts/base-certificate.js.map +1 -0
  8. package/dist/src/artifacts/capacity-evidence.d.ts +195 -0
  9. package/dist/src/artifacts/capacity-evidence.js +202 -0
  10. package/dist/src/artifacts/capacity-evidence.js.map +1 -0
  11. package/dist/src/artifacts/commitment-inclusion.d.ts +23 -0
  12. package/dist/src/artifacts/commitment-inclusion.js +91 -0
  13. package/dist/src/artifacts/commitment-inclusion.js.map +1 -0
  14. package/dist/src/artifacts/holder-keyset.d.ts +67 -0
  15. package/dist/src/artifacts/holder-keyset.js +149 -0
  16. package/dist/src/artifacts/holder-keyset.js.map +1 -0
  17. package/dist/src/artifacts/rfc3339.d.ts +9 -0
  18. package/dist/src/artifacts/rfc3339.js +39 -0
  19. package/dist/src/artifacts/rfc3339.js.map +1 -0
  20. package/dist/src/client.d.ts +552 -0
  21. package/dist/src/client.js +1347 -0
  22. package/dist/src/client.js.map +1 -0
  23. package/dist/src/crypto/ai-decision.d.ts +73 -0
  24. package/dist/src/crypto/ai-decision.js +94 -0
  25. package/dist/src/crypto/ai-decision.js.map +1 -0
  26. package/dist/src/crypto/canonical-subject.d.ts +33 -0
  27. package/dist/src/crypto/canonical-subject.js +240 -0
  28. package/dist/src/crypto/canonical-subject.js.map +1 -0
  29. package/dist/src/crypto/collection-merkle.d.ts +58 -0
  30. package/dist/src/crypto/collection-merkle.js +164 -0
  31. package/dist/src/crypto/collection-merkle.js.map +1 -0
  32. package/dist/src/crypto/composite.d.ts +53 -0
  33. package/dist/src/crypto/composite.js +69 -0
  34. package/dist/src/crypto/composite.js.map +1 -0
  35. package/dist/src/crypto/digest.d.ts +3 -0
  36. package/dist/src/crypto/digest.js +31 -0
  37. package/dist/src/crypto/digest.js.map +1 -0
  38. package/dist/src/crypto/ecdsa-p256.d.ts +79 -0
  39. package/dist/src/crypto/ecdsa-p256.js +277 -0
  40. package/dist/src/crypto/ecdsa-p256.js.map +1 -0
  41. package/dist/src/crypto/jcs.d.ts +13 -0
  42. package/dist/src/crypto/jcs.js +65 -0
  43. package/dist/src/crypto/jcs.js.map +1 -0
  44. package/dist/src/crypto/merkle.d.ts +18 -0
  45. package/dist/src/crypto/merkle.js +150 -0
  46. package/dist/src/crypto/merkle.js.map +1 -0
  47. package/dist/src/crypto/ml-dsa.d.ts +28 -0
  48. package/dist/src/crypto/ml-dsa.js +60 -0
  49. package/dist/src/crypto/ml-dsa.js.map +1 -0
  50. package/dist/src/crypto/pseudonym.d.ts +8 -0
  51. package/dist/src/crypto/pseudonym.js +50 -0
  52. package/dist/src/crypto/pseudonym.js.map +1 -0
  53. package/dist/src/crypto/strict-json.d.ts +25 -0
  54. package/dist/src/crypto/strict-json.js +180 -0
  55. package/dist/src/crypto/strict-json.js.map +1 -0
  56. package/dist/src/crypto/subject-json-preconditions.d.ts +46 -0
  57. package/dist/src/crypto/subject-json-preconditions.js +381 -0
  58. package/dist/src/crypto/subject-json-preconditions.js.map +1 -0
  59. package/dist/src/index.d.ts +18 -0
  60. package/dist/src/index.js +80 -0
  61. package/dist/src/index.js.map +1 -0
  62. package/dist/src/issuer.d.ts +668 -0
  63. package/dist/src/issuer.js +1066 -0
  64. package/dist/src/issuer.js.map +1 -0
  65. package/dist/src/retry.d.ts +67 -0
  66. package/dist/src/retry.js +78 -0
  67. package/dist/src/retry.js.map +1 -0
  68. package/dist/src/types.d.ts +297 -0
  69. package/dist/src/types.js +15 -0
  70. package/dist/src/types.js.map +1 -0
  71. package/package.json +62 -4
@@ -0,0 +1,1066 @@
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
+ * Certcrypt — high-level issuer client.
16
+ *
17
+ * Wraps the low-level CertcryptNodeClient and hides all the plumbing an app
18
+ * would otherwise reimplement: keyset derivation, activation (TOFU),
19
+ * caching the minted Level-1 binding, per-operation salt, and — in the
20
+ * unlinkable mode — never-reused leaf bookkeeping. An integrating app does:
21
+ *
22
+ * const certcrypt = new Certcrypt({ nodeBaseUrl, keysetSeed,
23
+ * integrationKey, mode: "stable",
24
+ * rulesVersion, systemRootFingerprint, systemId });
25
+ *
26
+ * THE SAME CODE ON EVERY START — there is no "first run" branch. `keysetSeed` and
27
+ * `integrationKey` are two halves of one boot credential: provision both from config
28
+ * (env / secret manager) and keep them. Nothing else has to be persisted for the
29
+ * issuer to survive a restart.
30
+ *
31
+ * Why that works: the keyset root is re-derived from the seed, so re-presenting the
32
+ * same `integrationKey` is an idempotent replay the server answers with the same binding.
33
+ * The key is "one-time" only in that its FIRST use permanently TOFU-binds it to this
34
+ * seed's root; presenting it with a DIFFERENT root is refused (409). That protects
35
+ * against hijack, not against your own restart. (One caveat before that first use: an
36
+ * UNREDEEMED key expires. The window is stated in your onboarding materials — activate
37
+ * promptly, or request a new key.)
38
+ *
39
+ * Optional: pass a `bindingStore` to cache the binding and skip the activation
40
+ * round-trip on start. It is a CACHE — omitting it is fully supported and costs one
41
+ * request per start.
42
+ * const res = await certcrypt.issue({
43
+ * subjects: [{ profile: "subject.text/1", material: myTextBytes }],
44
+ * });
45
+ *
46
+ * `issue()` certifies the MATERIAL (subject.text/1, subject.binary/1, …): it mints
47
+ * a signed base_certificate whose commitment is derived from the material and
48
+ * submits it toward Independent, so a third party can verify the binding OFFLINE.
49
+ * A certificate commits to an ORDERED SET of subjects: pass one for a single-subject
50
+ * cert, or several (dual-cert etc.) — one leaf/signature binds the whole set. The
51
+ * order is significant; consumers may rely on subjects[0] being the primary face.
52
+ * The issuer supplies only the material — the SDK derives the signing key from the
53
+ * seed and does the rest. Persist `res.handle`; call `resolveEmission(handle)` to
54
+ * get the verification-package once it settles.
55
+ *
56
+ * TWO KEY MODES:
57
+ * - "stable" (DEFAULT): a tiny key set (size 1), the key is REUSED. No counter,
58
+ * no exhaustion, no leaf store. The issuer's certs
59
+ * are linkable to each other, and therefore RECOGNIZABLE as its own — usually
60
+ * the point for an institutional or server issuer. Leaf-reuse is a PRIVACY
61
+ * choice, not a protocol mandate: reusing a leaf leaves the cert VALID, only
62
+ * correlatable.
63
+ * - "unlinkable" (OPT-IN): a large key set + a DISTINCT leaf per cert + no reuse,
64
+ * so the capacity layer never repeats a key. Every certificate is still
65
+ * signed with the same issuer key, so a party holding two of them can tell they
66
+ * share an issuer; what stays unlinkable is the protocol surface. Needs a `leafStore` (persistent
67
+ * nextLeaf()). The SDK enforces the no-reuse because a verifier cannot detect a
68
+ * repeat: nothing in the artifacts reveals that a leaf was used twice, so the
69
+ * property is lost silently if the issuer does not hold the line.
70
+ */
71
+ import { randomBytes } from "node:crypto";
72
+ import { CertcryptNodeClient, CertcryptNodeError, isSettlementOverdue, isTerminalState, issuerAuthMessage, } from "./client.js";
73
+ import { HolderKeySet } from "./artifacts/holder-keyset.js";
74
+ import { assertSubmissionSetWithinBound, evidenceDigestHex, } from "./artifacts/capacity-evidence.js";
75
+ import { deriveIssuerKey, generateNonceHex, computeExpiresAt, resolveCollectionSubjects, } from "./artifacts/base-certificate.js";
76
+ import { SUBJECT_COLLECTION } from "./crypto/canonical-subject.js";
77
+ import { strictJsonParse } from "./crypto/strict-json.js";
78
+ /**
79
+ * Σ of the certificate's per-subject effective units, as the capacity evidence
80
+ * declares it (`submission-set/1`). Each subject contributes:
81
+ * - a `subject.collection/1` → its `declared_cardinality` (a batch of N items), and
82
+ * - any other subject → 1.
83
+ * So a 3-subject certificate declares "3", a single-subject one "1", and one with a
84
+ * 500-item collection subject declares 500 (plus its siblings). Returned as the
85
+ * canonical decimal string the evidence uses.
86
+ *
87
+ * The server re-derives the same sum from the minted base_certificate and rejects a
88
+ * mismatch fail-closed, so the declaration cannot understate what the certificate
89
+ * actually carries.
90
+ */
91
+ function sumEffectiveUnits(subjects) {
92
+ let total = 0n;
93
+ for (const s of subjects) {
94
+ if (s.profile === SUBJECT_COLLECTION) {
95
+ // Declared by leaves: the cardinality IS the leaf count, and no descriptor
96
+ // exists yet (its root needs the anchor nonce).
97
+ if (s.leaves) {
98
+ const n = BigInt(s.leaves.length);
99
+ total += n > 0n ? n : 1n;
100
+ continue;
101
+ }
102
+ // Otherwise the declared_cardinality lives in its JSON material.
103
+ try {
104
+ const obj = strictJsonParse(Buffer.from(s.material).toString("utf8"));
105
+ const dc = BigInt(String(obj?.declared_cardinality ?? "0"));
106
+ total += dc > 0n ? dc : 1n;
107
+ }
108
+ catch {
109
+ total += 1n; // malformed collection: count as 1 (the node re-derives + rejects).
110
+ }
111
+ }
112
+ else {
113
+ total += 1n;
114
+ }
115
+ }
116
+ return total.toString();
117
+ }
118
+ /** A trivial in-memory leaf store — NOT persistent. Only for tests / single-run
119
+ * scripts; a real unlinkable deployment must supply a durable store: this one
120
+ * restarts at zero, which silently reuses every leaf it already handed out. The
121
+ * SDK never picks it for you — `mode: "unlinkable"` without a `leafStore` is
122
+ * refused at construction. */
123
+ export class InMemoryLeafStore {
124
+ cursor = 0;
125
+ async nextLeaf() {
126
+ return this.cursor++;
127
+ }
128
+ }
129
+ /**
130
+ * Rebuild an `EmissionHandle` from a recovered fragment plus the issuer-held
131
+ * material.
132
+ *
133
+ * WHY THIS EXISTS RATHER THAN A PLAIN OBJECT LITERAL. The one dangerous mistake
134
+ * in recovery is supplying a `commitmentIndex` when the fragment has none —
135
+ * defaulting it to 0, say, because the type demands a number. That produces a
136
+ * handle that looks complete and yields an inclusion proof that verifies against
137
+ * NOTHING: the index is a position in the Merkle leaf order, and the wrong
138
+ * position is not a near miss. So a partial fragment is refused here, loudly,
139
+ * instead of becoming an artifact that fails far away.
140
+ *
141
+ * Call it only for fragments whose emission has settled. For the rest, keep
142
+ * polling: the endpoint says when.
143
+ */
144
+ export function emissionHandleFromRecovery(fragment, issuerHeld) {
145
+ if (fragment.commitmentIndex === null || fragment.commitmentIndex === undefined) {
146
+ throw new Error("cannot rebuild an EmissionHandle from a partial fragment: commitmentIndex " +
147
+ "is null, which means the emission has not settled and its Merkle position " +
148
+ "does not exist yet. Poll until it settles, then recover again — never " +
149
+ "substitute a placeholder index: the inclusion proof it produces verifies " +
150
+ "against nothing.");
151
+ }
152
+ return {
153
+ operationId: fragment.operationId,
154
+ upstreamOperationId: issuerHeld.upstreamOperationId,
155
+ independenceRef: fragment.independenceRef,
156
+ commitmentIndex: fragment.commitmentIndex,
157
+ capacityEvidence: fragment.capacityEvidence,
158
+ baseCertificate: issuerHeld.baseCertificate,
159
+ collections: issuerHeld.collections,
160
+ };
161
+ }
162
+ /**
163
+ * The default `valid_until` an activation asks for: a far-future bound for the LEVEL-1 BINDING's validity window —
164
+ * not for a commitment.
165
+ *
166
+ * These are different clocks and only one is rate-limited by the rules-domain: an
167
+ * authorization binding legitimately outlives any single issuance (re-minting it
168
+ * per emission would produce a new authorization_id every restart), while a
169
+ * capacity commitment must expire at exactly `issued_at + domain TTL`. Using this
170
+ * value for a commitment produces certificates the verifier rejects; see
171
+ * COMMITMENT_TTL_SECONDS below.
172
+ */
173
+ export const FAR_FUTURE = "2100-01-01T00:00:00Z";
174
+ /**
175
+ * Capacity-commitment TTL, in seconds, per rules-domain.
176
+ *
177
+ * A PUBLIC RULE of the domain, not an issuer setting. The verifier requires
178
+ * `expires_at === issued_at + ttl` (COMMITMENT_TTL_VALID) precisely so an issuer
179
+ * cannot widen its own window, and the issuance service enforces the same equality at
180
+ * submit — so a wrong value is refused at issuance instead of surfacing months
181
+ * later, in someone else's hands, on a certificate the issuer believed was good.
182
+ *
183
+ * Mirrors `commitment_ttl_seconds` in the verifier toolkit's per-environment
184
+ * config. An unknown rules_version returns undefined and issuance FAILS: there is
185
+ * no defensible default, and a far-future fallback (year 2100) would be
186
+ * exactly the self-inflated window the rule exists to block.
187
+ */
188
+ const COMMITMENT_TTL_SECONDS = Object.freeze({
189
+ "rules/2026-01": 86_400,
190
+ "rules/conformance": 2_592_000,
191
+ });
192
+ /**
193
+ * The rules domains this SDK implements.
194
+ *
195
+ * Not configuration. `rules_version` is carried in every artifact this SDK emits
196
+ * and covered by its signatures, and what it asserts is that the artifact was
197
+ * produced under that exact normative body — its subject-profile
198
+ * canonicalizations, its commitment constructions with their exact preimages, its
199
+ * signature algorithms, its settlement contract. This SDK does not read those
200
+ * from anywhere: they are compiled in (see crypto/canonical-subject.ts,
201
+ * crypto/collection-merkle.ts). So it implements one normative body, and the
202
+ * honest thing is to say which.
203
+ *
204
+ * Emitting under a rules domain this SDK does not implement is the failure mode
205
+ * nothing downstream catches: the artifact verifies perfectly — signatures valid,
206
+ * digests matching, settlement real — while attesting to behavior that never
207
+ * happened. A verifier cannot detect it, because there is nothing malformed to
208
+ * detect. Hence the refusal is here, at emission, where it is still possible
209
+ * (`rules-domain/1` §14.2).
210
+ *
211
+ * Adding an entry means having implemented that rules domain, not having decided
212
+ * to support it.
213
+ */
214
+ export const SUPPORTED_RULES_VERSIONS = Object.freeze([
215
+ "rules/2026-01",
216
+ "rules/conformance",
217
+ ]);
218
+ /**
219
+ * Rules domains registered at runtime, on top of the published ones.
220
+ *
221
+ * A deployment may run under a rules domain it registers at runtime instead of
222
+ * one from the published list. The domain then comes from whoever runs the SDK,
223
+ * never from this package: the shape is public, a deployment's values are its
224
+ * own.
225
+ *
226
+ * This does NOT relax the gate. Registering a domain asserts the same thing
227
+ * `SUPPORTED_RULES_VERSIONS` asserts — that this SDK implements that normative
228
+ * body — and the assertion is then made by whoever registers it. An unregistered
229
+ * domain is still refused, which is what `rules-domain/1` §14.2 requires.
230
+ */
231
+ const runtimeRulesVersions = new Set();
232
+ /**
233
+ * Register a rules domain this SDK implements but does not publish.
234
+ *
235
+ * For a deployment that runs under its own rules domain. Call it before constructing
236
+ * `Certcrypt`: the gate runs at construction.
237
+ *
238
+ * Only accepts a domain whose canonicalization and settlement semantics this SDK
239
+ * already implements — i.e. one that differs from a published domain in WHERE it
240
+ * settles, not in HOW artifacts are formed. Registering anything else produces
241
+ * artifacts that verify correctly and attest to behavior that never happened,
242
+ * which is precisely what the gate exists to prevent.
243
+ */
244
+ export function registerRulesDomain(rulesVersion) {
245
+ if (typeof rulesVersion !== "string" || rulesVersion.length === 0) {
246
+ throw new Error("Certcrypt: registerRulesDomain requires a non-empty rules_version");
247
+ }
248
+ if (!rulesVersion.startsWith("rules/")) {
249
+ throw new Error(`Certcrypt: rules_version must start with "rules/", got "${rulesVersion}"`);
250
+ }
251
+ runtimeRulesVersions.add(rulesVersion);
252
+ }
253
+ /** Every rules domain this SDK will emit under: published + registered. */
254
+ function implementedRulesVersions() {
255
+ return [...SUPPORTED_RULES_VERSIONS, ...runtimeRulesVersions];
256
+ }
257
+ /**
258
+ * The subject profiles this SDK can canonicalize, mirroring
259
+ * crypto/canonical-subject.ts.
260
+ *
261
+ * Mirrors crypto/canonical-subject.ts, which is the only place that turns a
262
+ * subject into committed bytes: a profile absent there cannot be emitted,
263
+ * whatever else in this package mentions it. A rules domain may admit profiles an
264
+ * SDK does not implement, and passing one is refused rather than approximated —
265
+ * canonicalizing a subject under the wrong profile yields a commitment that is
266
+ * well-formed and wrong, which is exactly the class of error §14.2 exists to
267
+ * prevent.
268
+ */
269
+ const IMPLEMENTED_SUBJECT_PROFILES = Object.freeze([
270
+ "subject.binary/1",
271
+ "subject.text/1",
272
+ "subject.email/1",
273
+ "subject.collection/1",
274
+ "subject.ai-decision/1",
275
+ "subject.context-snapshot/1",
276
+ ]);
277
+ /**
278
+ * Fail closed unless this SDK implements the rules domain it is asked to emit
279
+ * under. Called at construction, so the refusal lands before any signing key or
280
+ * capacity is touched.
281
+ */
282
+ function assertRulesDomainImplemented(rulesVersion) {
283
+ if (implementedRulesVersions().includes(rulesVersion))
284
+ return;
285
+ throw new Error(`Certcrypt: this SDK does not implement rules_version "${rulesVersion}". ` +
286
+ `It implements: ${implementedRulesVersions().join(", ")}. ` +
287
+ "rules_version is not a parameter: it asserts, in every artifact emitted " +
288
+ "and under its signatures, that the artifact was produced under that exact " +
289
+ "normative body. Emitting under rules this SDK does not implement would " +
290
+ "produce artifacts that verify correctly and attest to behavior that never " +
291
+ "happened, which no verifier can detect (rules-domain/1 §14.2). Use a " +
292
+ "rules_version this SDK implements, or an SDK that implements that one.");
293
+ }
294
+ /**
295
+ * PRIVATE signing-domain separators for the issuer↔node↔issuance-service channel.
296
+ *
297
+ * These are NOT public protocol identifiers. No normative spec defines them, no
298
+ * verifier evaluates them, and a conforming third-party implementation never has
299
+ * to reproduce them: they are a bilateral contract between an issuer and the
300
+ * issuance service it talks to. What they buy is domain separation — a read signature must never be
301
+ * valid as an activation, or as a commitment, with the same key.
302
+ *
303
+ * The `:` form is deliberate. The normative artifacts are all shaped
304
+ * `name.thing/<version>` (`capacity.commitment/1`, `subject.text/1`,
305
+ * `independence.proof/1`), so a separator in that same shape would read as a spec
306
+ * identifier to anyone scanning this file — and someone evaluating an
307
+ * implementation could reasonably conclude they had to reproduce it. The colon
308
+ * form cannot be mistaken for one.
309
+ *
310
+ * They stay versioned even though nothing parses the `:1`: the whole string is
311
+ * compared as opaque bytes, so the suffix is free today and gives a clean exit if
312
+ * a message ever changes shape — a `:2` domain makes old and new signatures
313
+ * mutually invalid by construction rather than silently sharing a domain.
314
+ *
315
+ * The CERTCRYPT service verifies these exact strings, so both sides MUST stay in
316
+ * step: changing one alone turns every read into a 401 and every activation into a
317
+ * rejected possession proof.
318
+ */
319
+ const PRIVATE_SIGNING_DOMAIN_READ = "certcrypt:read:2";
320
+ const PRIVATE_SIGNING_DOMAIN_ACTIVATE = "certcrypt:activate:1";
321
+ /** The bytes both halves of a read chain sign: domain, the issuer's per-read
322
+ * challenge, and the resource. Exported for tests. */
323
+ export function readMessage(challenge, resource) {
324
+ return `${PRIVATE_SIGNING_DOMAIN_READ}|${challenge}|${resource}`;
325
+ }
326
+ function toRfc3339Seconds(d) {
327
+ return d.toISOString().replace(/\.\d{3}Z$/, "Z");
328
+ }
329
+ /** Derive a stable authorization id from the binding: `auth:` followed by the
330
+ * first 32 hex characters of its authorized root. Kept opaque; the evidence
331
+ * carries it only as an operation-scoped pseudonym. */
332
+ function deriveAuthorizationId(binding) {
333
+ const root = binding.level1_binding.holder_key_set_root ?? "";
334
+ return `auth:${root.slice(0, 32)}`;
335
+ }
336
+ export class Certcrypt {
337
+ client;
338
+ keySet;
339
+ opts;
340
+ mode;
341
+ leafStore;
342
+ /** Optional cache for the Level-1 binding (see BindingStore). null = no caching,
343
+ * which is fully supported: the SDK re-activates from `integrationKey` instead. */
344
+ bindingStore;
345
+ signedLevel1;
346
+ poolId;
347
+ /** The canonical holder_id the ACTIVATION bound to this integration. The
348
+ * emission is attributed to it, so emission MUST use it (not a
349
+ * caller-configured value). Learned from activate(); falls back to
350
+ * opts.holderId only when a pre-obtained signedLevel1 skips activation. */
351
+ holderId;
352
+ /** Composite cert-signing key for verifiable issuance. Either injected
353
+ * (opts.issuerKey) or derived lazily from the master seed on first issue(). */
354
+ issuerKeyCached;
355
+ constructor(opts) {
356
+ // Before anything else: this SDK implements one normative body, and refusing
357
+ // here means the refusal lands before a key is derived, capacity is touched or
358
+ // an artifact exists to be mistaken for a valid one.
359
+ assertRulesDomainImplemented(opts.rulesVersion);
360
+ this.opts = opts;
361
+ this.mode = opts.mode ?? "stable";
362
+ const treeSize = opts.treeSize ?? (this.mode === "stable" ? 1 : 4096);
363
+ if (this.mode === "unlinkable" && treeSize < 2) {
364
+ throw new Error("unlinkable mode needs a treeSize >= 2 (a distinct leaf per cert)");
365
+ }
366
+ if (opts.commitmentTtlSeconds !== undefined &&
367
+ !(Number.isInteger(opts.commitmentTtlSeconds) && opts.commitmentTtlSeconds > 0)) {
368
+ throw new Error("commitmentTtlSeconds must be a positive whole number of seconds: the verifier " +
369
+ "requires expires_at === issued_at + ttl, and a TTL of zero or less yields a " +
370
+ "commitment that is already expired");
371
+ }
372
+ // No default store. The leaf bookkeeping has to survive restarts, and an
373
+ // in-memory default would restart at zero and reuse every leaf it handed out
374
+ // — the one failure no verifier can detect.
375
+ if (this.mode === "unlinkable" && !opts.leafStore) {
376
+ throw new Error('mode "unlinkable" requires a leafStore: each commitment must be signed with a ' +
377
+ "leaf never used before, and that bookkeeping has to survive restarts");
378
+ }
379
+ this.keySet = HolderKeySet.fromMasterSeed(opts.keysetSeed, treeSize);
380
+ this.leafStore = this.mode === "unlinkable" ? opts.leafStore : null;
381
+ // No default store: unlike the leaf counter, an absent binding cache costs only
382
+ // one request per start (the SDK re-activates), so silently picking a location
383
+ // for the integrator would trade a real deployment decision for nothing.
384
+ this.bindingStore = opts.bindingStore ?? null;
385
+ this.signedLevel1 = opts.signedLevel1 ?? null;
386
+ this.poolId = opts.poolId;
387
+ this.holderId = opts.holderId;
388
+ this.issuerKeyCached = opts.issuerKey ?? null;
389
+ const clientOpts = {
390
+ baseUrl: opts.nodeBaseUrl,
391
+ pool_id: opts.poolId,
392
+ // Self-verifying issuer-auth: each request to the node carries a fresh proof
393
+ // the node verifies OFFLINE (no token lookup, no call to the issuance service). Built from the
394
+ // cached Level-1 binding + a leaf disclosure + a possession signature over a
395
+ // fresh challenge. Null until activated (the binding is minted on first emit).
396
+ issuerAuthProof: (request) => this.buildIssuerAuthProof(request),
397
+ // The client polls by node-local id; the proof must cover the id the
398
+ // issuance service routes on. The issuer knows both because the node reported the upstream id
399
+ // at submit, so it translates here — nobody has to declare the mapping over
400
+ // the wire, and nobody has to trust one.
401
+ issuerReadProof: (resource) => this.buildIssuerReadProof(this.upstreamIds.get(resource) ?? resource),
402
+ // Learns the upstream id of a member the node delivered late, so the
403
+ // next read signs the id the server routes on.
404
+ onUpstreamOperationId: (operationId, upstream) => {
405
+ if (!this.upstreamIds.has(operationId))
406
+ this.upstreamIds.set(operationId, upstream);
407
+ },
408
+ };
409
+ if (opts.fetch)
410
+ clientOpts.fetch = opts.fetch;
411
+ if (opts.retry)
412
+ clientOpts.retry = opts.retry;
413
+ this.client = new CertcryptNodeClient(clientOpts);
414
+ }
415
+ /**
416
+ * Build the `x-certcrypt-issuer-auth` header value: base64(JSON) of
417
+ * { signed_level1, disclosure, challenge, possession_b64 }. Returns null if not
418
+ * yet activated (no binding to present). The challenge is fresh per call
419
+ * (timestamp + random), binding the possession signature to this request; the
420
+ * node accepts it once and downstream request_id idempotency neutralizes replay.
421
+ */
422
+ buildIssuerAuthProof(request) {
423
+ if (!this.signedLevel1)
424
+ return null;
425
+ // Leaf 0 in either mode: this proof goes to the node with the request and
426
+ // never into an artifact.
427
+ const leafIndex = 0;
428
+ const challenge = `${Date.now()}.${Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(16))).toString("base64")}`;
429
+ // Signed together with the request it is for (see issuerAuthMessage).
430
+ const possession = this.keySet.sign(leafIndex, Buffer.from(issuerAuthMessage(challenge, request), "utf8"));
431
+ const proof = {
432
+ signed_level1: this.signedLevel1,
433
+ disclosure: this.keySet.disclosure(leafIndex),
434
+ challenge,
435
+ possession_b64: Buffer.from(possession).toString("base64"),
436
+ };
437
+ return Buffer.from(JSON.stringify(proof), "utf8").toString("base64");
438
+ }
439
+ /** node-local operation id → the server's id for it, learned at submit. Only ever
440
+ * holds emissions THIS process made; a handle restored from storage carries its
441
+ * `upstreamOperationId` and is registered on use. */
442
+ upstreamIds = new Map();
443
+ /**
444
+ * Build the `x-certcrypt-issuer-read` header value: base64(JSON) of
445
+ * { signed_level1, disclosure, challenge, possession_b64 }, where the possession
446
+ * signature covers `certcrypt:read:2|<challenge>|<resource>` (a PRIVATE signing
447
+ * domain, not a spec id). The challenge is fresh per call and the issuance
448
+ * service spends it: the node that relays this half cannot replay it later to
449
+ * read on its own initiative.
450
+ *
451
+ * WHY A READ NEEDS THIS. A submit proves who its issuer is from the inside —
452
+ * every certificate carries `capacity_evidence` this key set signed. A read
453
+ * carries no such artifact, so the scope has to come from somewhere else, and
454
+ * the only sound answer is a signature: the issuer signs the exact resource it
455
+ * is asking for, so the server derives the scope from WHO SIGNED rather than from
456
+ * whoever transported the request. A node therefore cannot read anything unless
457
+ * its issuer actually asked for it.
458
+ *
459
+ * Returns null before activation (no binding to present yet).
460
+ */
461
+ buildIssuerReadProof(resource) {
462
+ if (!this.signedLevel1)
463
+ return null;
464
+ const leafIndex = 0;
465
+ const challenge = `${Date.now()}.${Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(16))).toString("base64")}`;
466
+ const message = readMessage(challenge, resource);
467
+ const possession = this.keySet.sign(leafIndex, Buffer.from(message, "utf8"));
468
+ const proof = {
469
+ signed_level1: this.signedLevel1,
470
+ disclosure: this.keySet.disclosure(leafIndex),
471
+ challenge,
472
+ possession_b64: Buffer.from(possession).toString("base64"),
473
+ };
474
+ return Buffer.from(JSON.stringify(proof), "utf8").toString("base64");
475
+ }
476
+ /** The holder_key_set_root to supply at onboarding (or that the
477
+ * activation binds via TOFU). Public value derived from the secret seed. */
478
+ keysetRoot() {
479
+ return this.keySet.root;
480
+ }
481
+ /** The cached Level-1 binding (present after activation), or null before it.
482
+ * Public (no secret). Persisting it is an OPTIMIZATION, not a requirement — a
483
+ * restart re-activates from `integrationKey`. To cache it, prefer a `bindingStore`
484
+ * (it also carries `holderId`/`poolId`, which a bare binding does not). */
485
+ binding() {
486
+ return this.signedLevel1;
487
+ }
488
+ /**
489
+ * Activate the integration WITHOUT issuing anything.
490
+ *
491
+ * Activation is normally invisible: the first `issue()` does it on the way past,
492
+ * so a first issuance is an ordinary issuance that also happens to activate.
493
+ * Call this to redeem the integration key and confirm the credentials at deploy
494
+ * time, before any certificate exists. Reaching `Independent` is a separate,
495
+ * later event.
496
+ *
497
+ * It redeems the key against the server and caches the binding. It does NOT create
498
+ * a certificate, does NOT anchor anything, and consumes NO capacity: issuance is
499
+ * a separate request. Idempotent — safe to call on every start, and a no-op once
500
+ * bound. Typical use is a startup or readiness hook:
501
+ *
502
+ * await certcrypt.activate(); // deploy time: claim the key
503
+ * …
504
+ * await certcrypt.issue({ … }); // later: the real certificate
505
+ */
506
+ async activate() {
507
+ return this.ensureActivated();
508
+ }
509
+ /**
510
+ * Ensure we hold a Level-1 binding. Resolution order, each step a fallback of the
511
+ * previous: (1) already in memory, (2) the `bindingStore` cache, (3) activate from
512
+ * `integrationKey`. Idempotent — a second call is a no-op once bound.
513
+ *
514
+ * Step 3 is what makes a COLD RESTART work with nothing persisted: the keyset root
515
+ * is re-derived from `keysetSeed`, so re-presenting the same `integrationKey` is an
516
+ * idempotent replay the server answers with the same binding. The store only saves the
517
+ * round-trip; it is never required for correctness, so a load failure is swallowed.
518
+ */
519
+ async ensureActivated() {
520
+ if (this.signedLevel1)
521
+ return this.signedLevel1;
522
+ // (2) Cache hit: adopt the binding AND the two identifiers activation bound to
523
+ // it. A store that returned a binding without them would leave issue() throwing.
524
+ if (this.bindingStore) {
525
+ try {
526
+ const cached = await this.bindingStore.load();
527
+ if (cached?.binding) {
528
+ this.signedLevel1 = cached.binding;
529
+ this.holderId = cached.holderId;
530
+ if (!this.poolId)
531
+ this.poolId = cached.poolId;
532
+ return this.signedLevel1;
533
+ }
534
+ }
535
+ catch {
536
+ // A cache is never fatal: fall through and re-activate from the key.
537
+ }
538
+ }
539
+ if (!this.opts.integrationKey) {
540
+ throw new Error("not activated: provide `integrationKey`. Keep it in config alongside " +
541
+ "`keysetSeed` and supply it on every start — it is not consumed by use. " +
542
+ "Issue one at https://console.certcrypt.com. A pre-obtained " +
543
+ "`signedLevel1` also works, but then `holderId` must be set.");
544
+ }
545
+ // Prove we own the root we are asking the server to bind. Activation travels
546
+ // THROUGH A NODE, so an unsigned root would be just a body field in transit:
547
+ // binding it has to require proof that the presenter actually holds the key
548
+ // set. Signing `certcrypt:activate:1|<code>|<root>` with a leaf of that very
549
+ // key set is something only the holder of the seed can do, which is what ties
550
+ // the one-time code to THIS issuer's identity and no other.
551
+ const activationLeafIndex = 0;
552
+ const activationMessage = `${PRIVATE_SIGNING_DOMAIN_ACTIVATE}|${this.opts.integrationKey}|${this.keySet.root}`;
553
+ const activationPossession = this.keySet.sign(activationLeafIndex, Buffer.from(activationMessage, "utf8"));
554
+ const res = await this.client.activate({
555
+ code: this.opts.integrationKey,
556
+ holderKeySetRoot: this.keySet.root,
557
+ keySetDisclosure: this.keySet.disclosure(activationLeafIndex),
558
+ keySetPossessionB64: Buffer.from(activationPossession).toString("base64"),
559
+ rulesVersion: this.opts.rulesVersion,
560
+ systemRootFingerprint: this.opts.systemRootFingerprint,
561
+ // No valid_from: the issuance service fixes it, and a same-root replay
562
+ // answers with the authorization bound at first activation, so restarts
563
+ // reuse one authorization without the SDK choosing any date.
564
+ validUntil: this.opts.validUntil ?? FAR_FUTURE,
565
+ });
566
+ this.signedLevel1 = res.signedLevel1;
567
+ if (!this.poolId)
568
+ this.poolId = res.poolId;
569
+ // The activation is authoritative for the (holder_id, pool_id) emission is
570
+ // attributed to — always adopt the returned holder_id, overriding any configured
571
+ // one, so emission is attributed to the identity the activation bound.
572
+ this.holderId = res.holderId;
573
+ if (this.bindingStore) {
574
+ try {
575
+ await this.bindingStore.save({
576
+ binding: res.signedLevel1,
577
+ holderId: res.holderId,
578
+ poolId: res.poolId,
579
+ });
580
+ }
581
+ catch {
582
+ // Persisting is an optimization; a failure only costs a round-trip next start.
583
+ }
584
+ }
585
+ return this.signedLevel1;
586
+ }
587
+ /** The composite cert-signing key: injected (opts.issuerKey) or derived once
588
+ * from the master seed, domain-separated from the operation-key tree. The
589
+ * issuer never handles it; it is reconstructed from the seed it already gave. */
590
+ resolveIssuerKey() {
591
+ if (!this.issuerKeyCached) {
592
+ const id = this.opts.issuerKeyId ?? `issuer:${this.keySet.root.slice(0, 32)}`;
593
+ this.issuerKeyCached = deriveIssuerKey(this.opts.keysetSeed, id);
594
+ }
595
+ return this.issuerKeyCached;
596
+ }
597
+ /**
598
+ * Issue a certificate over `input.subjects` — the ONE issuance surface, verifiable
599
+ * by construction. Activates on first use, then: derives the composite signing
600
+ * key from the seed, canonicalizes each subject byte-identically to the verifier,
601
+ * mints a SIGNED base_certificate whose commitment is derived FROM the material(s)
602
+ * (never an opaque caller digest), and submits it toward Independent. A third
603
+ * party holding the original material + the returned proof can verify the binding
604
+ * OFFLINE. In "stable" mode reuses leaf 0; in "unlinkable" mode pulls a fresh leaf.
605
+ *
606
+ * The returned `IssueResult.handle` (with `baseCertificate`) is the serializable
607
+ * operation handle: persist it and call `resolveEmission(handle)` later to poll THIS one
608
+ * operation and build the verification-package — never re-emitting.
609
+ */
610
+ async issue(input) {
611
+ // issue() is prepare() + submit() for N=1, and stays the surface almost every
612
+ // integration should use: one certificate, one request, nothing to persist
613
+ // between the two halves and no leaf left in limbo if the send fails.
614
+ const prepared = await this.prepare(input);
615
+ const { response, handles } = await this.submit([prepared], {
616
+ ...(input.settlementPreferences
617
+ ? { settlementPreferences: input.settlementPreferences }
618
+ : {}),
619
+ });
620
+ return {
621
+ response,
622
+ commitment: prepared.commitment,
623
+ authorizationId: prepared.authorizationId,
624
+ handle: handles[0],
625
+ collections: prepared.collections,
626
+ };
627
+ }
628
+ /**
629
+ * Sign ONE certificate and return its commitment WITHOUT sending it, so several
630
+ * can be submitted together with `submit()`.
631
+ *
632
+ * WHY IT EXISTS. N unrelated certificates sent one at a time carry the
633
+ * per-submission overhead N times; the same N prepared and submitted in a single
634
+ * request carry it once. For a batch that is the whole saving: the node accepts
635
+ * N members in one request, and this is the step before the send.
636
+ *
637
+ * WHAT IT COSTS. This is where everything irreversible happens: the
638
+ * base_certificate is signed and the leaf and operation salt are spent. Sending
639
+ * is not what consumes them. In "unlinkable" mode a prepared commitment that is
640
+ * never submitted leaves its leaf spent for good — the allocator is monotone on
641
+ * purpose (`LeafStore` has no `release()`), because recycling would reintroduce a
642
+ * reuse no verifier can detect. Losing a leaf costs one slot in a large key set;
643
+ * reusing one silently destroys the unlinkability the mode exists for. In
644
+ * "stable" mode leaf 0 is reused by design and nothing is lost.
645
+ *
646
+ * So: to retry a failed send, call `submit()` again with the commitment you
647
+ * already hold. Never re-`prepare()` the same material — that signs a second
648
+ * commitment for one certificate.
649
+ *
650
+ * Validation is identical to `issue()` (same non-empty subjects, implemented
651
+ * profiles, system_id, root_id, pool/holder, TTL) because both run this method.
652
+ *
653
+ * All members of one submission set must share issuer and authorization; every
654
+ * commitment from the same instance does, so prepared commitments can be mixed
655
+ * freely — `submit()` rejects a mismatch before spending a request.
656
+ */
657
+ async prepare(input) {
658
+ const signedLevel1 = await this.ensureActivated();
659
+ const poolId = this.poolId;
660
+ if (!poolId)
661
+ throw new Error("no pool_id (set poolId or obtain it from activation)");
662
+ const holderId = this.holderId;
663
+ if (!holderId) {
664
+ throw new Error("no holder_id: it is learned from activation; provide an integrationKey, " +
665
+ "or set holderId in options when supplying a pre-obtained signedLevel1");
666
+ }
667
+ const rootId = this.opts.systemRootFingerprint;
668
+ if (!rootId) {
669
+ throw new Error("issue() requires systemRootFingerprint (the Independent root_id)");
670
+ }
671
+ // An empty system_id signs fine and is REJECTED by every conformant verifier
672
+ // (BASE_CERTIFICATE_STRUCTURE_VALID). Catch it at issuance, not at verification.
673
+ if (!this.opts.systemId) {
674
+ throw new Error('issue() requires systemId (the system domain id, e.g. "certcrypt"). ' +
675
+ "Without it the certificate carries an empty payload.system_id and every " +
676
+ "conformant verifier REJECTS it.");
677
+ }
678
+ if (!Array.isArray(input.subjects) || input.subjects.length === 0) {
679
+ throw new Error("issue() requires a non-empty subjects[] set");
680
+ }
681
+ // A rules domain may admit subject profiles this SDK does not implement.
682
+ // Canonicalizing under the wrong profile produces a commitment that is
683
+ // well-formed and wrong, so an unimplemented profile is refused rather than
684
+ // approximated (rules-domain/1 §14.2).
685
+ for (const [index, subject] of input.subjects.entries()) {
686
+ const profile = subject.profile;
687
+ if (profile !== undefined && !IMPLEMENTED_SUBJECT_PROFILES.includes(profile)) {
688
+ throw new Error(`issue(): subject[${index}] declares profile "${profile}", which this SDK ` +
689
+ `does not implement. It implements: ${IMPLEMENTED_SUBJECT_PROFILES.join(", ")}. ` +
690
+ "The profile fixes how the subject is canonicalized and committed to, so " +
691
+ "emitting under one this SDK cannot canonicalize would bind the certificate " +
692
+ "to a commitment no conforming verifier reproduces.");
693
+ }
694
+ }
695
+ const issuedAt = input.issuedAt ?? toRfc3339Seconds(new Date());
696
+ // The verifier requires expires_at == issued_at + rules-domain TTL. An explicit
697
+ // input.expiresAt still wins (advanced callers), then an explicit TTL, then the
698
+ // domain's published one. There is no far-future fallback: it would produce a
699
+ // certificate the verifier rejects, silently, and the issuer would only find out
700
+ // when a third party tried to verify it.
701
+ // `??`, not `||`: only an absent value falls back. A zero TTL is refused at
702
+ // construction, so nothing here has to tell 0 apart from "unset".
703
+ const ttlSeconds = this.opts.commitmentTtlSeconds ?? COMMITMENT_TTL_SECONDS[this.opts.rulesVersion];
704
+ if (input.expiresAt === undefined && ttlSeconds === undefined) {
705
+ throw new Error(`issue(): no commitment TTL for rules_version "${this.opts.rulesVersion}". ` +
706
+ "The TTL is a public rule of the rules-domain and the verifier requires " +
707
+ "expires_at === issued_at + ttl, so it cannot be guessed. Pass " +
708
+ "commitmentTtlSeconds explicitly, or use a rules_version this SDK knows.");
709
+ }
710
+ const expiresAt = input.expiresAt ?? computeExpiresAt(issuedAt, ttlSeconds);
711
+ const authorizationId = deriveAuthorizationId(signedLevel1);
712
+ // Generated up front: it is the collection salt, so it must exist before the
713
+ // subjects are resolved (subject.collection/1 §8).
714
+ const nonceHex = generateNonceHex();
715
+ const { subjects: resolvedSubjects, collections } = resolveCollectionSubjects(input.subjects, nonceHex);
716
+ // Spent HERE, at signing: in unlinkable mode this leaf never comes back.
717
+ const leafIndex = this.mode === "stable" ? 0 : await this.leafStore.nextLeaf();
718
+ const operationSalt = randomBytes(32);
719
+ const { commitment, minted } = this.client.mintVerifiableCertificate({
720
+ subjects: resolvedSubjects,
721
+ issuerKey: this.resolveIssuerKey(),
722
+ target: { mode: "independent-capable", root_id: rootId },
723
+ anchor: {
724
+ issued_at: issuedAt,
725
+ nonce_hex: nonceHex,
726
+ system_id: this.opts.systemId,
727
+ rules_version: this.opts.rulesVersion,
728
+ },
729
+ signedLevel1,
730
+ holderId,
731
+ // The pool resolved for THIS issuer: configured, or learned at activation.
732
+ // The client was built before activation, so its own pool may be unset.
733
+ poolId,
734
+ authorizationId,
735
+ evidenceFields: {
736
+ // Defaults to "0" on purpose, and that is NOT a placeholder to fill in
737
+ // later: an issuer cannot know what an issuance will consume. The value is
738
+ // resolved server-side and is not final until the operation crystallizes,
739
+ // so asking the caller for a number here would be asking for one it does
740
+ // not have.
741
+ //
742
+ // Nothing reads this field: it is carried into the submission set and
743
+ // persisted, but no gate or verifier check depends on it.
744
+ //
745
+ // The quantity the issuance really consumed comes back in the
746
+ // `settlement_material` that the `independence_proof` binds — after
747
+ // crystallization, when it is a fact rather than a forecast.
748
+ consumed_quantity: input.consumedQuantity ?? "0",
749
+ // Σ over the certificate's subjects of each subject's effective units (a
750
+ // normal subject = 1; a subject.collection/1 = its declared_cardinality).
751
+ // A multi-subject certificate therefore declares its TRUE subject count,
752
+ // not 1 — a single-subject cert still declares "1". The node re-derives
753
+ // this from the base_certificate and rejects a mismatch (fail-closed), so
754
+ // the declaration cannot understate what the certificate actually carries.
755
+ // An explicit override wins only for advanced callers that pre-computed it.
756
+ declared_effective_units: input.declaredEffectiveUnits ?? sumEffectiveUnits(input.subjects),
757
+ issued_at: issuedAt,
758
+ expires_at: expiresAt,
759
+ },
760
+ keySet: this.keySet,
761
+ leafIndex,
762
+ operationSalt,
763
+ });
764
+ return {
765
+ commitment,
766
+ baseCertificate: minted.base_certificate,
767
+ collections,
768
+ authorizationId,
769
+ leafIndex,
770
+ };
771
+ }
772
+ /**
773
+ * Submit prepared commitments as ONE submission set and return a handle for each.
774
+ *
775
+ * This is the request `prepare()` exists to fill: N members travel together and
776
+ * amortize the per-submission overhead across all of them. It is
777
+ * N-in-one-request, synchronous — not a time-window accumulation, so nothing is buffered and nothing is deferred.
778
+ *
779
+ * Handles come back in the SAME order as the input, each already correlated with
780
+ * its member of the response, so a batch of N is as persistable as a single
781
+ * emission: keep each handle and call `resolveEmission()` on it later.
782
+ *
783
+ * A retry re-sends these same commitments — the SDK never re-signs, because a
784
+ * leaf must not be reused. If the send fails after signing, the leaves are
785
+ * already spent (see `prepare()`); calling `submit()` again with the same array
786
+ * is the correct move, and the node deduplicates on the request id.
787
+ *
788
+ * At most `MAX_SUBMISSION_SET_MEMBERS` (64) commitments make one set; more
789
+ * throw `SubmissionSetTooLargeError` before anything is sent
790
+ * (submission-set/1 §8.1). Split a larger batch into several `submit()` calls.
791
+ */
792
+ async submit(prepared, opts = {}) {
793
+ if (!Array.isArray(prepared) || prepared.length === 0) {
794
+ throw new Error("submit() requires a non-empty prepared[] array");
795
+ }
796
+ // The producer refuses to build an over-bound set (submission-set/1 §8.1).
797
+ assertSubmissionSetWithinBound(prepared.length);
798
+ // Every member of one set must answer to the same issuer and authorization, or
799
+ // the node refuses the whole request. Caught here so a mixed batch costs an
800
+ // error rather than a round-trip — the commitments are already signed either
801
+ // way, but the request is not spent.
802
+ const authorizationId = prepared[0].authorizationId;
803
+ for (const [index, item] of prepared.entries()) {
804
+ if (item.authorizationId !== authorizationId) {
805
+ throw new Error(`submit(): prepared[${index}] carries authorization_id ` +
806
+ `"${item.authorizationId}" but prepared[0] carries "${authorizationId}". ` +
807
+ "One submission set is one issuer under one authorization; the node " +
808
+ "refuses a mixed set. Submit them as separate requests.");
809
+ }
810
+ }
811
+ const response = await this.client.issue({
812
+ commitments: prepared.map((p) => p.commitment),
813
+ ...(opts.requestId ? { request_id: opts.requestId } : {}),
814
+ ...(opts.settlementPreferences
815
+ ? {
816
+ settlement_preferences: {
817
+ window_profile: opts.settlementPreferences.windowProfile,
818
+ fallback_policy: opts.settlementPreferences.fallbackPolicy ?? "reject",
819
+ },
820
+ }
821
+ : {}),
822
+ });
823
+ // Correlate by commitment_index when the node reports one (a set of N comes
824
+ // back indexed), falling back to positional order for a single member.
825
+ const handles = prepared.map((item, position) => {
826
+ const member = response.results?.find((r) => r.commitment_index === position) ??
827
+ response.results?.[position];
828
+ const operationId = member?.operation_id ?? "";
829
+ if (!operationId) {
830
+ // A whole-request failure — a transport error reaching the issuance service, or a
831
+ // rejection before per-member evaluation — comes back with `results`
832
+ // EMPTY and the reason in the top-level `state`. Reporting "no
833
+ // operation_id" here hides that reason behind a symptom, which is how a
834
+ // transient upstream failure ends up looking like a protocol bug —
835
+ // typically under concurrency, where one request of several fails this way.
836
+ const whole = response.state;
837
+ if (whole?.state) {
838
+ throw new CertcryptNodeError(`submit failed: ${whole.state}${whole.error ? ` — ${whole.error}` : ""}`, null, JSON.stringify(whole));
839
+ }
840
+ throw new Error(`submit: node returned no operation_id for prepared[${position}] ` +
841
+ `(results had ${response.results?.length ?? 0} entries and no top-level state)`);
842
+ }
843
+ const upstreamOperationId = member?.state?.state === "accepted"
844
+ ? member.state.upstream_operation_id
845
+ : undefined;
846
+ if (upstreamOperationId)
847
+ this.upstreamIds.set(operationId, upstreamOperationId);
848
+ return {
849
+ operationId,
850
+ ...(upstreamOperationId ? { upstreamOperationId } : {}),
851
+ independenceRef: evidenceDigestHex(item.commitment.capacity_evidence),
852
+ commitmentIndex: member?.commitment_index ?? position,
853
+ ...(item.collections.length > 0 ? { collections: item.collections } : {}),
854
+ capacityEvidence: item.commitment.capacity_evidence,
855
+ // The signed base_certificate — this is what makes the emission verifiable
856
+ // against the original material. resolveEmission threads it into the package.
857
+ baseCertificate: item.baseCertificate,
858
+ };
859
+ });
860
+ return { response, handles };
861
+ }
862
+ /**
863
+ * List the emissions this integration has in flight — neither independently
864
+ * verifiable yet nor terminally refused.
865
+ *
866
+ * `resolveEmission` requires a handle and `getOperation` requires an id. An
867
+ * issuer that lost both can still enumerate its in-flight emissions here: the
868
+ * request is authenticated by the caller's own key, the read chain proves the
869
+ * key-set root, and the server answers for that root's integration.
870
+ *
871
+ * Persisting the handle at emission remains the supported path; this method
872
+ * makes a lost handle recoverable instead of a reason to re-emit.
873
+ *
874
+ * `since` is required and bounded server-side; check `truncated` before
875
+ * treating the list as complete.
876
+ */
877
+ async listUnresolvedEmissions(since, limit) {
878
+ // A process that only RECOVERS (it did not emit) has no binding yet, so the
879
+ // read would carry no issuer half and be refused. Activating first is
880
+ // idempotent and a no-op once bound.
881
+ await this.ensureActivated();
882
+ return this.client.listUnresolvedEmissions(since, limit);
883
+ }
884
+ /**
885
+ * Resolve an emission by the digest of the capacity evidence that produced it.
886
+ *
887
+ * The fallback when the node no longer knows the operation — it restarted with
888
+ * an in-memory journal, or the issuer moved to another node. The digest is the
889
+ * one identifier the issuer can always produce, because it recomputes it from
890
+ * evidence it signed; the attempt id was never the issuer's and the node's
891
+ * operation id belongs to a journal it may no longer be talking to.
892
+ *
893
+ * Not a weaker path: the read still carries both halves of the chain, and the
894
+ * resource signed is the digest itself — which is stronger than signing an id
895
+ * the node handed over, because the issuer can check what it means.
896
+ *
897
+ * Returns `pending` while the emission has not settled. Once it has, the full
898
+ * `verification_package` is assembled from the proof and the settlement
899
+ * material this read returns plus the handle the issuer kept
900
+ * (`baseCertificate`, `capacityEvidence`, `commitmentIndex`); the inclusion
901
+ * proof is derived from the proof's `consumed_commitment_ids`.
902
+ */
903
+ async resolveByCommitment(handle, verificationContext) {
904
+ const rec = await this.client.getEmissionByCommitment(handle.independenceRef);
905
+ if (rec.status === "expired") {
906
+ return { state: "expired", nodeState: rec.status, reasonCode: rec.reason_code ?? "expired" };
907
+ }
908
+ // Every other terminal status that is not independent_ready ends the
909
+ // emission without a proof (insufficient_capacity, for one).
910
+ if (rec.status !== "independent_ready" && isTerminalState(rec.status)) {
911
+ return { state: "rejected", nodeState: rec.status };
912
+ }
913
+ // BOTH artifacts or nothing: a package missing the settlement material does
914
+ // not verify, and returning a half-built one would fail later and further
915
+ // away, where the cause is no longer visible.
916
+ if (rec.status !== "independent_ready" ||
917
+ !rec.independence_proof ||
918
+ !rec.settlement_material) {
919
+ return { state: "pending", nodeState: rec.status };
920
+ }
921
+ // Everything the package needs is either in the handle the issuer kept
922
+ // (`baseCertificate`, `capacityEvidence`, `commitmentIndex`) or derivable from
923
+ // the proof itself (the inclusion proof comes from its
924
+ // `consumed_commitment_ids`). The node contributed none of it — which is why
925
+ // this path can return the same verdict, not a weaker one.
926
+ const verificationPackage = this.client.assembleVerificationPackageFromProof({
927
+ independenceProofB64: rec.independence_proof,
928
+ settlementMaterialB64: rec.settlement_material,
929
+ baseCertificate: handle.baseCertificate,
930
+ capacityEvidence: handle.capacityEvidence,
931
+ verificationContext,
932
+ commitmentIndex: handle.commitmentIndex,
933
+ });
934
+ return {
935
+ state: "independent",
936
+ verificationPackage,
937
+ independenceRef: handle.independenceRef,
938
+ };
939
+ }
940
+ /**
941
+ * Resolve a previously-emitted certificate from its handle: poll the ONE operation's
942
+ * state (never re-emits) and, once independent_ready, build the full
943
+ * verification-package/1 from the handle's own capacity_evidence + the node's
944
+ * proof/settlement material. Returns:
945
+ * - { state: "independent", verificationPackage, independenceRef } once settled,
946
+ * - { state: "pending", nodeState } while it is still being settled (retry later),
947
+ * - { state: "expired", nodeState, reasonCode } when it can no longer settle,
948
+ * - { state: "rejected", nodeState } on any other terminal state
949
+ * (rejected, insufficient_capacity, replay_detected, pre_evaluation_rejected,
950
+ * submission_failed).
951
+ *
952
+ * `opts.wait` bounds the poll (default: a SINGLE status check — a reconciler
953
+ * wants a quick "is it ready yet?", not a long block). Pass `maxAttempts` above
954
+ * 1, `maxWaitMs`, or `strategy: "auto"` to wait inline; a wait that ends
955
+ * without a terminal state reports `pending`, it does not throw.
956
+ * `opts.verificationContext` supplies the published profile values
957
+ * (rules_version + system_id) the package records; it defaults to this
958
+ * instance's `rulesVersion` and `systemId`.
959
+ */
960
+ async resolveEmission(handle, opts = {}) {
961
+ const verificationContext = opts.verificationContext ?? {
962
+ rules_version: this.opts.rulesVersion,
963
+ system_id: this.opts.systemId ?? "",
964
+ };
965
+ // Ensure the issuer is activated BEFORE polling: the node's operation reads
966
+ // are issuer-authenticated (x-certcrypt-issuer-auth), and that header is built
967
+ // from the cached Level-1 binding. A process that only RESOLVES a handle (e.g.
968
+ // a separate process that did not emit in-process) has no binding yet → the
969
+ // proof provider returns null → the node answers 401. Activating first (idempotent;
970
+ // a no-op once bound) makes resolveEmission self-sufficient, exactly like issue().
971
+ await this.ensureActivated();
972
+ // A handle restored from storage (another process, a restart) carries the
973
+ // upstream id but was never registered in-process. Register it before any read
974
+ // so the proof signs the id the server routes on.
975
+ if (handle.upstreamOperationId) {
976
+ this.upstreamIds.set(handle.operationId, handle.upstreamOperationId);
977
+ }
978
+ // The node's operation id lives in THAT node's journal. A node restarted with
979
+ // an in-memory journal, or a different node entirely (the model treats moving
980
+ // as changing a URL, not migrating), answers 404 for an emission the issuance
981
+ // service still holds.
982
+ //
983
+ // The capacity-evidence digest does not have that problem: the issuer
984
+ // recomputes it from evidence it signed itself, and it identifies the emission
985
+ // at the issuance service. So a 404 here is not the end of the road — it is the signal to
986
+ // ask by the identifier that outlives the node.
987
+ let rec;
988
+ try {
989
+ rec = await this.client.getOperation(handle.operationId);
990
+ }
991
+ catch (e) {
992
+ if (!(e instanceof CertcryptNodeError && e.status === 404) || !handle.independenceRef) {
993
+ throw e;
994
+ }
995
+ return await this.resolveByCommitment(handle, verificationContext);
996
+ }
997
+ let nodeState = rec.state.state;
998
+ let expiredReason = rec.state.state === "expired" ? rec.state.reason_code : "expired";
999
+ // The node's scheduling hint, carried through the optional wait below so the
1000
+ // pending result can report which window we are waiting on.
1001
+ let window = rec.settlement_window;
1002
+ // Optional bounded wait. Default: just the one check we already did — a
1003
+ // reconciler wants "is it ready yet?", not a block. When the caller DOES ask
1004
+ // to wait, its WaitOptions are passed through untouched, so the window-aware
1005
+ // scheduling (and `onProgress`) apply here exactly as on the client.
1006
+ const wantsWait = opts.wait !== undefined &&
1007
+ ((opts.wait.maxAttempts ?? 1) > 1 ||
1008
+ opts.wait.maxWaitMs !== undefined ||
1009
+ opts.wait.strategy === "auto");
1010
+ if (wantsWait && !isTerminalState(nodeState)) {
1011
+ try {
1012
+ const settled = await this.client.waitForOperation(handle.operationId, opts.wait);
1013
+ nodeState = settled.state.state;
1014
+ if (settled.state.state === "expired")
1015
+ expiredReason = settled.state.reason_code;
1016
+ if (settled.settlement_window)
1017
+ window = settled.settlement_window;
1018
+ }
1019
+ catch (e) {
1020
+ // The wait timed out without a terminal state. That is NOT an error for
1021
+ // resolveEmission: the operation is still being settled and the handle is still
1022
+ // good. Fall through and report `pending` (with the window, so the caller
1023
+ // knows when to come back) rather than making the issuer handle a throw for
1024
+ // the ordinary "not ready yet" case. A 404 (wrong id) still propagates.
1025
+ if (e instanceof CertcryptNodeError && e.status === 404)
1026
+ throw e;
1027
+ }
1028
+ }
1029
+ if (nodeState === "expired")
1030
+ return { state: "expired", nodeState, reasonCode: expiredReason };
1031
+ // Every other terminal state that is not independent_ready ends the
1032
+ // emission without a proof: rejected, insufficient_capacity,
1033
+ // replay_detected, pre_evaluation_rejected, submission_failed.
1034
+ if (nodeState !== "independent_ready" && isTerminalState(nodeState)) {
1035
+ return { state: "rejected", nodeState };
1036
+ }
1037
+ if (nodeState !== "independent_ready") {
1038
+ // Hand back the node's own schedule so the caller can time its next check
1039
+ // instead of polling blindly — and can tell "settling normally" apart from
1040
+ // "late", which is what a stuck settlement actually looks like from here.
1041
+ const settlementWindow = window ?? rec.settlement_window;
1042
+ const overdue = isSettlementOverdue(settlementWindow, Date.now());
1043
+ return {
1044
+ state: "pending",
1045
+ nodeState,
1046
+ ...(settlementWindow ? { settlementWindow } : {}),
1047
+ ...(overdue ? { overdue: true } : {}),
1048
+ };
1049
+ }
1050
+ const verificationPackage = await this.client.buildVerificationPackage(handle.operationId, {
1051
+ // Client-held artifacts the server never returns: without them the package
1052
+ // cannot reach INDEPENDENT_VALID or bind to the original material.
1053
+ baseCertificate: handle.baseCertificate,
1054
+ capacityEvidence: handle.capacityEvidence,
1055
+ verificationContext,
1056
+ commitmentIndex: handle.commitmentIndex,
1057
+ });
1058
+ return { state: "independent", verificationPackage, independenceRef: handle.independenceRef };
1059
+ }
1060
+ /** Access the underlying low-level client (advanced: buildVerificationPackage,
1061
+ * waitForOperation, etc.). */
1062
+ nodeClient() {
1063
+ return this.client;
1064
+ }
1065
+ }
1066
+ //# sourceMappingURL=issuer.js.map