@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,668 @@
1
+ import { CertcryptNodeClient, type RetryOptions, type VerificationPackage, type WaitOptions } from "./client.js";
2
+ import type { SignedLevel1Binding } from "./artifacts/capacity-evidence.js";
3
+ import { type IssuerKey, type ResolvedCollection, type SubjectInput } from "./artifacts/base-certificate.js";
4
+ import type { IssueResponse, LooseCommitment, SettlementWindowEstimate, UnresolvedEmissions } from "./types.js";
5
+ /** Persistent, monotone leaf allocator for the unlinkable mode. Each call MUST
6
+ * return a fresh index never handed out before (survives restarts). */
7
+ export interface LeafStore {
8
+ nextLeaf(): Promise<number>;
9
+ }
10
+ /** A trivial in-memory leaf store — NOT persistent. Only for tests / single-run
11
+ * scripts; a real unlinkable deployment must supply a durable store: this one
12
+ * restarts at zero, which silently reuses every leaf it already handed out. The
13
+ * SDK never picks it for you — `mode: "unlinkable"` without a `leafStore` is
14
+ * refused at construction. */
15
+ export declare class InMemoryLeafStore implements LeafStore {
16
+ private cursor;
17
+ nextLeaf(): Promise<number>;
18
+ }
19
+ /**
20
+ * Optional persistence for the Level-1 binding — a CACHE that saves the activation
21
+ * round-trip on start, never a requirement for correctness. With only `integrationKey`
22
+ * + `keysetSeed` the SDK re-activates by itself (the key replays idempotently against
23
+ * the same root), so an empty or failing store degrades to "one extra request".
24
+ *
25
+ * `save()` receives `holderId`/`poolId` alongside the binding and `load()` MUST return
26
+ * them: both are LEARNED from activation and authoritative for emission (emission is
27
+ * attributed to `holder_id`). A store that persisted only the binding would
28
+ * leave `holderId` unresolved and `issue()` would throw — which is exactly the trap of
29
+ * supplying a bare `signedLevel1` by hand.
30
+ *
31
+ * No default implementation is provided on purpose: the binding carries `holder_id` and
32
+ * `pool_id`, so where it lives is a deployment decision (DB, secret manager, file) the
33
+ * SDK should not make for the integrator.
34
+ */
35
+ export interface BindingStore {
36
+ load(): Promise<BindingStoreEntry | null>;
37
+ save(entry: BindingStoreEntry): Promise<void>;
38
+ }
39
+ /** What a BindingStore round-trips: the binding plus the two identifiers the
40
+ * activation bound to it. All three are public (no secret) — safe to persist. */
41
+ export interface BindingStoreEntry {
42
+ binding: SignedLevel1Binding;
43
+ holderId: string;
44
+ poolId: string;
45
+ }
46
+ export type IssuerMode = "stable" | "unlinkable";
47
+ export interface CertcryptOptions {
48
+ /** Node base URL (the SDK talks only to the node). */
49
+ nodeBaseUrl: string;
50
+ /** 32-byte master seed (64-hex or Uint8Array). Secret; never leaves the app. */
51
+ keysetSeed: string | Uint8Array;
52
+ /** The integration's pool_id (from onboarding). Optional if learned from activate. */
53
+ poolId?: string;
54
+ /** Stable holder id for this integration. Normally LEARNED from activation (the
55
+ * issuance service binds and returns it), so it is optional. Set it only when supplying a
56
+ * pre-obtained `signedLevel1` that skips activation — it MUST then equal the
57
+ * holder the integration was activated under, or the emission is not accounted
58
+ * for against this integration. */
59
+ holderId?: string;
60
+ /** Published system context (from onboarding config). */
61
+ rulesVersion: string;
62
+ systemRootFingerprint: string;
63
+ /** The system domain id (e.g. "certcrypt"), stamped into the verifiable
64
+ * certificate's anchor. From onboarding config. */
65
+ systemId?: string;
66
+ /** The capacity-commitment TTL (seconds) from the ACTIVE rules-domain registry
67
+ * (e.g. 86400 for a one-day TTL). The verifier requires
68
+ * expires_at == issued_at + this TTL, so issue() derives expires_at from it
69
+ * rather than a caller value. Omitting it uses the published TTL of the
70
+ * configured rules domain; a domain registered with `registerRulesDomain` has
71
+ * no published TTL, so it must be set there or issuance fails. */
72
+ commitmentTtlSeconds?: number;
73
+ /** The integration's activation key (from onboarding). KEEP IT: supply it
74
+ * on EVERY start, exactly like `keysetSeed` — it is not consumed by use.
75
+ *
76
+ * It is "one-time" in one specific sense: the FIRST activation TOFU-binds it to
77
+ * this `keysetSeed`'s root, permanently. Re-presenting it with the SAME root is
78
+ * an idempotent replay the server answers with the same binding
79
+ * (`already_consumed_same_root`), which is what makes a cold restart work with no
80
+ * persisted state. Presenting it with a DIFFERENT root is refused (409) — that is
81
+ * the hijack the TOFU closes, not your restart.
82
+ *
83
+ * Caveat before the first activation: an UNREDEEMED key expires. The window is
84
+ * stated in your onboarding materials — activate promptly, or request a new key.
85
+ * Once redeemed it replays indefinitely — the consumed branch is evaluated before
86
+ * the expiry one, by design. */
87
+ integrationKey?: string;
88
+ /** A pre-obtained Level-1 binding. An OPTIMIZATION that skips the activation
89
+ * round-trip on start — NOT a requirement, and NOT a substitute for keeping
90
+ * `integrationKey` (with the key alone the SDK re-activates by itself).
91
+ *
92
+ * Supplying this WITHOUT `integrationKey` means activation never runs, so the
93
+ * canonical `holderId` is never learned — set `holderId` explicitly too, or
94
+ * `issue()` will throw. Prefer a `bindingStore`, which caches all three together. */
95
+ signedLevel1?: SignedLevel1Binding;
96
+ /** Optional cache for the Level-1 binding, so a restart skips the activation
97
+ * round-trip. A CACHE, not a source of truth: on a miss (or a load error) the SDK
98
+ * re-activates from `integrationKey`, so a cold store is never fatal. Omit it and
99
+ * the SDK simply re-activates on every start. */
100
+ bindingStore?: BindingStore;
101
+ /** Key mode. Default "stable". */
102
+ mode?: IssuerMode;
103
+ /** Issuer key id stamped into the base_certificate signer block. Default
104
+ * `"issuer:" + keysetRoot[0:32]`. A label only: the signing key depends on
105
+ * `keysetSeed` alone, so changing the id never changes the key (conformance
106
+ * family `issuer-key-derivation`). Not a secret. */
107
+ issuerKeyId?: string;
108
+ /** A pre-provisioned composite issuer key (e.g. KMS-backed) for verifiable
109
+ * issuance. OPTIONAL: when omitted, `issue()` derives one DETERMINISTICALLY
110
+ * from `keysetSeed` (domain-separated) so the issuer provisions only the seed.
111
+ * Supply this only to harden production custody. */
112
+ issuerKey?: IssuerKey;
113
+ /** Tree size. Default: 1 for stable, 4096 for unlinkable. */
114
+ treeSize?: number;
115
+ /** Leaf allocator for the unlinkable mode. Required when mode="unlinkable":
116
+ * construction throws without one, because a default that restarts at zero
117
+ * would silently reuse leaves. */
118
+ leafStore?: LeafStore;
119
+ /** End of the minted authorization's validity (RFC3339 seconds). Default
120
+ * `FAR_FUTURE`. Only used when activating. Its start is not the issuer's to
121
+ * choose: the issuance service fixes it (the activation instant, never before
122
+ * the Level-1 key that signs it) and the SDK reads it from the answer. */
123
+ validUntil?: string;
124
+ /** Optional custom fetch (tests). */
125
+ fetch?: typeof fetch;
126
+ /**
127
+ * How long a submit or a read keeps retrying while the node is unreachable or
128
+ * asks for a pause (a restart, an outbox it could not write). Default: 120 s,
129
+ * no attempt limit, backoff base 200 ms and cap 30 s. Raise `maxElapsedMs` if
130
+ * your process can wait longer for a node restart; lower it if a caller
131
+ * upstream needs an answer sooner (a mail filter that would rather defer the
132
+ * message, for instance).
133
+ */
134
+ retry?: RetryOptions;
135
+ }
136
+ /** Issuer-elected settlement-window preference: how soon this emission's window
137
+ * closes, and therefore how soon the certificate can reach `Independent`.
138
+ * Optional — omit it to accept the default.
139
+ *
140
+ * Operational only: the window profile is never part of the submission_set, the
141
+ * proof, or anything a verifier evaluates. Choosing a faster window changes when
142
+ * a certificate becomes independently verifiable, never whether it is valid. */
143
+ export interface SettlementPreferences {
144
+ /** Identifier of a published window profile. The available profiles and the
145
+ * current default are documented at https://docs.certcrypt.com — they are
146
+ * resolved at submission rather than pinned here, so a profile added or
147
+ * retired later needs no SDK release.
148
+ *
149
+ * Validated on submit: an unknown or inactive profile is rejected fail-closed
150
+ * unless `fallbackPolicy: "slower_allowed"`. */
151
+ windowProfile: string;
152
+ /** `reject` (default, fail-closed) | `slower_allowed` (record an explicit
153
+ * downgrade to a slower profile if the requested one cannot be accepted). */
154
+ fallbackPolicy?: "reject" | "slower_allowed";
155
+ }
156
+ /**
157
+ * Input to `issue()` — the ONE issuance surface. The issuer supplies only the
158
+ * MATERIAL and its subject profile; the SDK does everything else (derives the
159
+ * signing key from the seed, canonicalizes the subject byte-identically to the
160
+ * verifier, mints a SIGNED base_certificate whose commitment is derived FROM the
161
+ * material, and submits it toward Independent). This is the primary issuance surface:
162
+ *
163
+ * await certcrypt.issue({ subjects: [{ profile: "subject.text/1", material }] });
164
+ *
165
+ * There is no opaque-digest mode: `issue()` always commits to real material, so a
166
+ * third party can bind the Proof of Independence to THIS exact content. (To
167
+ * certify a non-document fact, model it as a subject — e.g. subject.ai-decision/1
168
+ * over a canonical JSON — rather than passing a bare digest.)
169
+ */
170
+ export interface IssueInput {
171
+ /** The ORDERED set of subjects the certificate commits to, each a material +
172
+ * its subject profile (subject.text/1, subject.binary/1, subject.email/1,
173
+ * subject.collection/1, subject.ai-decision/1). Pass ONE for a single-subject
174
+ * certificate, or SEVERAL for a multi-subject one (dual-cert: assertion + PDF,
175
+ * …) — a single leaf/signature binds the whole set. MUST be non-empty; the
176
+ * order is significant (consumers may rely on subjects[0] as the primary face).
177
+ * The SDK canonicalizes each per profile and commits to it in the base_certificate. */
178
+ subjects: SubjectInput[];
179
+ /** Declared effective units. Default: the sum over `subjects` (1 per subject,
180
+ * a collection's `declared_cardinality` for a collection), which the node
181
+ * re-derives and must match. */
182
+ declaredEffectiveUnits?: string;
183
+ /**
184
+ * Consumed quantity (default `"0"`). **Leave it unset.**
185
+ *
186
+ * A caller cannot know this value: it is resolved server-side and is not final
187
+ * until the operation completes. Nothing reads what you put here. The quantity
188
+ * actually consumed comes back in the `settlement_material` that the
189
+ * `independence_proof` binds — that is the authoritative figure, and the only one
190
+ * worth recording.
191
+ */
192
+ consumedQuantity?: string;
193
+ /** issued_at / expires_at (RFC3339 seconds). Default issued=now, expires=issued_at
194
+ * plus the rules domain's commitment TTL, which a verifier requires exactly. */
195
+ issuedAt?: string;
196
+ expiresAt?: string;
197
+ /** Issuer-elected settlement window (see `SettlementPreferences`). Omit for the
198
+ * default. */
199
+ settlementPreferences?: SettlementPreferences;
200
+ }
201
+ /**
202
+ * One certificate SIGNED but not yet sent — what `prepare()` returns and
203
+ * `submit()` consumes.
204
+ *
205
+ * N unrelated certificates sent as N requests carry the per-submission overhead N
206
+ * times, while the same N prepared and submitted together carry it ONCE — the
207
+ * reason this surface exists.
208
+ *
209
+ * TREAT IT AS SPENT THE MOMENT YOU HOLD IT. `prepare()` signs, and signing is what
210
+ * consumes the leaf and the operation salt; sending does not. In "unlinkable" mode a
211
+ * prepared commitment that is never submitted leaves its leaf spent for good: the
212
+ * leaf allocator is monotone by design (`LeafStore` has no `release()`), because
213
+ * recycling a leaf would reintroduce the reuse a verifier cannot detect. Losing a
214
+ * leaf costs one slot in a large key set; reusing one silently destroys the
215
+ * unlinkability the mode exists to provide. In "stable" mode leaf 0 is reused on
216
+ * purpose, so nothing is lost.
217
+ *
218
+ * Serializable: persist it (JSON) if the submit happens in another process. What you
219
+ * must NOT do is re-`prepare()` the same certificate to retry a failed send — that
220
+ * signs a second commitment for the same material. Re-`submit()` the one you hold.
221
+ */
222
+ export interface PreparedCommitment {
223
+ /** The signed loose commitment, exactly as it will travel on the wire. */
224
+ commitment: LooseCommitment;
225
+ /** The signed base_certificate. Needed to build the handle after the submit and
226
+ * to verify the emission offline against the original material. Typed `unknown`
227
+ * to match `EmissionHandle` — it travels as an opaque signed blob. */
228
+ baseCertificate: unknown;
229
+ /** Resolved collection subjects (descriptor + leaf hashes, in leaf order). They
230
+ * also travel signed inside the certificate's collection descriptor and can be
231
+ * read back from it; returned here for convenience. */
232
+ collections: ResolvedCollection[];
233
+ /** Stable authorization id this commitment was signed under. All members of one
234
+ * submission set MUST share it (and the issuer), or the node refuses the mix. */
235
+ authorizationId: string;
236
+ /** Which leaf signed this commitment. Recorded for auditing the no-reuse
237
+ * invariant; `-1` is never returned (leaf 0 is valid, and is the stable mode). */
238
+ leafIndex: number;
239
+ }
240
+ /** What `submit()` returns: the node's response plus one handle per prepared
241
+ * commitment, in the SAME order they were passed in. */
242
+ export interface SubmitResult {
243
+ response: IssueResponse;
244
+ /** One serializable handle per submitted commitment, index-aligned with the
245
+ * input array. Persist each and pass it to `resolveEmission()` later. */
246
+ handles: EmissionHandle[];
247
+ }
248
+ export interface IssueResult {
249
+ response: IssueResponse;
250
+ /**
251
+ * One entry per `leaves`-declared collection subject: its descriptor and its leaf
252
+ * hashes, in leaf order.
253
+ *
254
+ * Returned for convenience: the same descriptor ships signed inside the certificate,
255
+ * ordered, so these values can also be read back from there and an inclusion proof
256
+ * rebuilt from the certificate alone. They are what a `verification-package/1` §11
257
+ * carries. What is NOT recoverable anywhere is the leaf material behind each salted
258
+ * digest — proving a member belongs still requires holding that member.
259
+ */
260
+ collections: ResolvedCollection[];
261
+ commitment: LooseCommitment;
262
+ authorizationId: string;
263
+ /** Serializable handle of THIS emission. Persist it and pass it to
264
+ * `resolveEmission` later to check settlement + build the package without
265
+ * re-emitting (exactly one node operation per certificate). See EmissionHandle. */
266
+ handle: EmissionHandle;
267
+ }
268
+ /**
269
+ * A serializable handle of ONE emission (`emitCertificate`). The issuer persists
270
+ * this as an opaque blob and hands it back to `resolveEmission` later to check the
271
+ * certificate's settlement and build the verification-package — WITHOUT re-emitting.
272
+ *
273
+ * Why the SDK owns this: every issuer whose settlement is asynchronous faces the
274
+ * same need — emit once, then resume. Without a handle, an issuer either blocks a
275
+ * request waiting for settlement, or re-emits on every retry (a duplicate node
276
+ * operation per attempt for the SAME certificate). The handle carries the two
277
+ * pieces the node NEVER returns (independence_ref is derived from the client-held
278
+ * capacity_evidence; the commitment_index positions it in the accepted set) so a
279
+ * later process — even after a restart — can finish the job from the blob alone.
280
+ *
281
+ * Treat it as opaque; its shape may gain fields. It contains no secret (the
282
+ * capacity_evidence is public), so it is safe to store next to the certificate.
283
+ */
284
+ export interface EmissionHandle {
285
+ /** The node operation to poll. The ONE operation for this certificate. */
286
+ operationId: string;
287
+ /**
288
+ * The server's own id for this operation, as the node reported it at submit.
289
+ *
290
+ * The SDK still POLLS `operationId` (it talks only to the node), but a read
291
+ * proof must sign THIS one: the server routes on it, and having both halves of the
292
+ * read chain cover the id the server itself uses removes the only thing that would
293
+ * otherwise have to be trusted — a node-declared mapping between its local alias
294
+ * and the upstream id. With one id there is no mapping to declare and none to
295
+ * believe.
296
+ *
297
+ * Absent for a member that was not accepted upstream (there is no service-side
298
+ * operation to read).
299
+ */
300
+ upstreamOperationId?: string;
301
+ /** Evidence digest bound into independence.proof/1 (the durable proof ref). */
302
+ independenceRef: string;
303
+ /** This commitment's index in the accepted set (for the inclusion proof). */
304
+ commitmentIndex: number;
305
+ /** The public capacity.evidence/1 the node never returns — needed to assemble
306
+ * the package. Public (no secret), safe to persist. */
307
+ capacityEvidence: unknown;
308
+ /** The signed base_certificate. `resolveEmission` puts it into the package so a
309
+ * verifier can reach INDEPENDENT_VALID and bind to the original material. */
310
+ baseCertificate?: unknown;
311
+ /** Descriptor + leaf hashes per collection subject. The descriptor travels
312
+ * signed inside the certificate; these are kept so the issuer can build
313
+ * inclusion proofs, which need the ordered leaf hashes. */
314
+ collections?: ResolvedCollection[];
315
+ }
316
+ /** The half of an `EmissionHandle` CERTCRYPT can hand back, as the recovery
317
+ * endpoint returns it.
318
+ *
319
+ * Four fields. The handle's other three come from the caller; two of them hold
320
+ * what only the issuer's certificate carries:
321
+ *
322
+ * - `baseCertificate` — the issuer minted and signed it; only its digest ever
323
+ * crossed the boundary. Nothing server-side to return.
324
+ * - `collections` — descriptors and leaf hashes travel signed inside that
325
+ * base certificate, which CERTCRYPT never receives. They are read back
326
+ * from the certificate the issuer holds, and from nowhere else.
327
+ *
328
+ * So recovery is a JOIN, not a download: this half plus the certificate the
329
+ * issuer still holds. An issuer that lost BOTH cannot reconstruct the emission
330
+ * from any endpoint. */
331
+ export interface RecoveredHandleFragment {
332
+ operationId: string;
333
+ independenceRef: string;
334
+ /** Null until the emission settles: the index lives in the Proof of
335
+ * Independence, which does not exist before then. */
336
+ commitmentIndex: number | null;
337
+ capacityEvidence: unknown;
338
+ }
339
+ /**
340
+ * Rebuild an `EmissionHandle` from a recovered fragment plus the issuer-held
341
+ * material.
342
+ *
343
+ * WHY THIS EXISTS RATHER THAN A PLAIN OBJECT LITERAL. The one dangerous mistake
344
+ * in recovery is supplying a `commitmentIndex` when the fragment has none —
345
+ * defaulting it to 0, say, because the type demands a number. That produces a
346
+ * handle that looks complete and yields an inclusion proof that verifies against
347
+ * NOTHING: the index is a position in the Merkle leaf order, and the wrong
348
+ * position is not a near miss. So a partial fragment is refused here, loudly,
349
+ * instead of becoming an artifact that fails far away.
350
+ *
351
+ * Call it only for fragments whose emission has settled. For the rest, keep
352
+ * polling: the endpoint says when.
353
+ */
354
+ export declare function emissionHandleFromRecovery(fragment: RecoveredHandleFragment, issuerHeld: {
355
+ baseCertificate: unknown;
356
+ collections?: ResolvedCollection[];
357
+ upstreamOperationId?: string;
358
+ }): EmissionHandle;
359
+ /** Terminal/interim outcome of `resolveEmission`. */
360
+ export type EmissionResolution = {
361
+ state: "independent";
362
+ verificationPackage: VerificationPackage;
363
+ independenceRef: string;
364
+ } | {
365
+ state: "pending";
366
+ nodeState: string;
367
+ /** The settlement window the node expects to settle this operation in, when it
368
+ * reported one. A reconciler should schedule its next call around
369
+ * `settlementWindow.expected_settled_by` (or `target_close_by` when the
370
+ * node reports no expected settlement instant) instead of polling blindly.
371
+ * Operational only — never verifier-evaluated, and it carries no cost figure
372
+ * (see {@link SettlementWindowEstimate}). */
373
+ settlementWindow?: SettlementWindowEstimate;
374
+ /** True when `expected_settled_by` (or, without it, `target_close_by`) has
375
+ * already passed and the operation is still not settled: it is running LATE. Lets an issuer surface "your operation is
376
+ * delayed" instead of an indefinite spinner. */
377
+ overdue?: boolean;
378
+ } | {
379
+ state: "rejected";
380
+ nodeState: string;
381
+ } | {
382
+ state: "expired";
383
+ nodeState: string;
384
+ reasonCode: string;
385
+ };
386
+ /**
387
+ * The default `valid_until` an activation asks for: a far-future bound for the LEVEL-1 BINDING's validity window —
388
+ * not for a commitment.
389
+ *
390
+ * These are different clocks and only one is rate-limited by the rules-domain: an
391
+ * authorization binding legitimately outlives any single issuance (re-minting it
392
+ * per emission would produce a new authorization_id every restart), while a
393
+ * capacity commitment must expire at exactly `issued_at + domain TTL`. Using this
394
+ * value for a commitment produces certificates the verifier rejects; see
395
+ * COMMITMENT_TTL_SECONDS below.
396
+ */
397
+ export declare const FAR_FUTURE = "2100-01-01T00:00:00Z";
398
+ /**
399
+ * The rules domains this SDK implements.
400
+ *
401
+ * Not configuration. `rules_version` is carried in every artifact this SDK emits
402
+ * and covered by its signatures, and what it asserts is that the artifact was
403
+ * produced under that exact normative body — its subject-profile
404
+ * canonicalizations, its commitment constructions with their exact preimages, its
405
+ * signature algorithms, its settlement contract. This SDK does not read those
406
+ * from anywhere: they are compiled in (see crypto/canonical-subject.ts,
407
+ * crypto/collection-merkle.ts). So it implements one normative body, and the
408
+ * honest thing is to say which.
409
+ *
410
+ * Emitting under a rules domain this SDK does not implement is the failure mode
411
+ * nothing downstream catches: the artifact verifies perfectly — signatures valid,
412
+ * digests matching, settlement real — while attesting to behavior that never
413
+ * happened. A verifier cannot detect it, because there is nothing malformed to
414
+ * detect. Hence the refusal is here, at emission, where it is still possible
415
+ * (`rules-domain/1` §14.2).
416
+ *
417
+ * Adding an entry means having implemented that rules domain, not having decided
418
+ * to support it.
419
+ */
420
+ export declare const SUPPORTED_RULES_VERSIONS: readonly string[];
421
+ /**
422
+ * Register a rules domain this SDK implements but does not publish.
423
+ *
424
+ * For a deployment that runs under its own rules domain. Call it before constructing
425
+ * `Certcrypt`: the gate runs at construction.
426
+ *
427
+ * Only accepts a domain whose canonicalization and settlement semantics this SDK
428
+ * already implements — i.e. one that differs from a published domain in WHERE it
429
+ * settles, not in HOW artifacts are formed. Registering anything else produces
430
+ * artifacts that verify correctly and attest to behavior that never happened,
431
+ * which is precisely what the gate exists to prevent.
432
+ */
433
+ export declare function registerRulesDomain(rulesVersion: string): void;
434
+ /** The bytes both halves of a read chain sign: domain, the issuer's per-read
435
+ * challenge, and the resource. Exported for tests. */
436
+ export declare function readMessage(challenge: string, resource: string): string;
437
+ export declare class Certcrypt {
438
+ private readonly client;
439
+ private readonly keySet;
440
+ private readonly opts;
441
+ private readonly mode;
442
+ private readonly leafStore;
443
+ /** Optional cache for the Level-1 binding (see BindingStore). null = no caching,
444
+ * which is fully supported: the SDK re-activates from `integrationKey` instead. */
445
+ private readonly bindingStore;
446
+ private signedLevel1;
447
+ private poolId;
448
+ /** The canonical holder_id the ACTIVATION bound to this integration. The
449
+ * emission is attributed to it, so emission MUST use it (not a
450
+ * caller-configured value). Learned from activate(); falls back to
451
+ * opts.holderId only when a pre-obtained signedLevel1 skips activation. */
452
+ private holderId;
453
+ /** Composite cert-signing key for verifiable issuance. Either injected
454
+ * (opts.issuerKey) or derived lazily from the master seed on first issue(). */
455
+ private issuerKeyCached;
456
+ constructor(opts: CertcryptOptions);
457
+ /**
458
+ * Build the `x-certcrypt-issuer-auth` header value: base64(JSON) of
459
+ * { signed_level1, disclosure, challenge, possession_b64 }. Returns null if not
460
+ * yet activated (no binding to present). The challenge is fresh per call
461
+ * (timestamp + random), binding the possession signature to this request; the
462
+ * node accepts it once and downstream request_id idempotency neutralizes replay.
463
+ */
464
+ private buildIssuerAuthProof;
465
+ /** node-local operation id → the server's id for it, learned at submit. Only ever
466
+ * holds emissions THIS process made; a handle restored from storage carries its
467
+ * `upstreamOperationId` and is registered on use. */
468
+ private readonly upstreamIds;
469
+ /**
470
+ * Build the `x-certcrypt-issuer-read` header value: base64(JSON) of
471
+ * { signed_level1, disclosure, challenge, possession_b64 }, where the possession
472
+ * signature covers `certcrypt:read:2|<challenge>|<resource>` (a PRIVATE signing
473
+ * domain, not a spec id). The challenge is fresh per call and the issuance
474
+ * service spends it: the node that relays this half cannot replay it later to
475
+ * read on its own initiative.
476
+ *
477
+ * WHY A READ NEEDS THIS. A submit proves who its issuer is from the inside —
478
+ * every certificate carries `capacity_evidence` this key set signed. A read
479
+ * carries no such artifact, so the scope has to come from somewhere else, and
480
+ * the only sound answer is a signature: the issuer signs the exact resource it
481
+ * is asking for, so the server derives the scope from WHO SIGNED rather than from
482
+ * whoever transported the request. A node therefore cannot read anything unless
483
+ * its issuer actually asked for it.
484
+ *
485
+ * Returns null before activation (no binding to present yet).
486
+ */
487
+ private buildIssuerReadProof;
488
+ /** The holder_key_set_root to supply at onboarding (or that the
489
+ * activation binds via TOFU). Public value derived from the secret seed. */
490
+ keysetRoot(): string;
491
+ /** The cached Level-1 binding (present after activation), or null before it.
492
+ * Public (no secret). Persisting it is an OPTIMIZATION, not a requirement — a
493
+ * restart re-activates from `integrationKey`. To cache it, prefer a `bindingStore`
494
+ * (it also carries `holderId`/`poolId`, which a bare binding does not). */
495
+ binding(): SignedLevel1Binding | null;
496
+ /**
497
+ * Activate the integration WITHOUT issuing anything.
498
+ *
499
+ * Activation is normally invisible: the first `issue()` does it on the way past,
500
+ * so a first issuance is an ordinary issuance that also happens to activate.
501
+ * Call this to redeem the integration key and confirm the credentials at deploy
502
+ * time, before any certificate exists. Reaching `Independent` is a separate,
503
+ * later event.
504
+ *
505
+ * It redeems the key against the server and caches the binding. It does NOT create
506
+ * a certificate, does NOT anchor anything, and consumes NO capacity: issuance is
507
+ * a separate request. Idempotent — safe to call on every start, and a no-op once
508
+ * bound. Typical use is a startup or readiness hook:
509
+ *
510
+ * await certcrypt.activate(); // deploy time: claim the key
511
+ * …
512
+ * await certcrypt.issue({ … }); // later: the real certificate
513
+ */
514
+ activate(): Promise<SignedLevel1Binding>;
515
+ /**
516
+ * Ensure we hold a Level-1 binding. Resolution order, each step a fallback of the
517
+ * previous: (1) already in memory, (2) the `bindingStore` cache, (3) activate from
518
+ * `integrationKey`. Idempotent — a second call is a no-op once bound.
519
+ *
520
+ * Step 3 is what makes a COLD RESTART work with nothing persisted: the keyset root
521
+ * is re-derived from `keysetSeed`, so re-presenting the same `integrationKey` is an
522
+ * idempotent replay the server answers with the same binding. The store only saves the
523
+ * round-trip; it is never required for correctness, so a load failure is swallowed.
524
+ */
525
+ ensureActivated(): Promise<SignedLevel1Binding>;
526
+ /** The composite cert-signing key: injected (opts.issuerKey) or derived once
527
+ * from the master seed, domain-separated from the operation-key tree. The
528
+ * issuer never handles it; it is reconstructed from the seed it already gave. */
529
+ private resolveIssuerKey;
530
+ /**
531
+ * Issue a certificate over `input.subjects` — the ONE issuance surface, verifiable
532
+ * by construction. Activates on first use, then: derives the composite signing
533
+ * key from the seed, canonicalizes each subject byte-identically to the verifier,
534
+ * mints a SIGNED base_certificate whose commitment is derived FROM the material(s)
535
+ * (never an opaque caller digest), and submits it toward Independent. A third
536
+ * party holding the original material + the returned proof can verify the binding
537
+ * OFFLINE. In "stable" mode reuses leaf 0; in "unlinkable" mode pulls a fresh leaf.
538
+ *
539
+ * The returned `IssueResult.handle` (with `baseCertificate`) is the serializable
540
+ * operation handle: persist it and call `resolveEmission(handle)` later to poll THIS one
541
+ * operation and build the verification-package — never re-emitting.
542
+ */
543
+ issue(input: IssueInput): Promise<IssueResult>;
544
+ /**
545
+ * Sign ONE certificate and return its commitment WITHOUT sending it, so several
546
+ * can be submitted together with `submit()`.
547
+ *
548
+ * WHY IT EXISTS. N unrelated certificates sent one at a time carry the
549
+ * per-submission overhead N times; the same N prepared and submitted in a single
550
+ * request carry it once. For a batch that is the whole saving: the node accepts
551
+ * N members in one request, and this is the step before the send.
552
+ *
553
+ * WHAT IT COSTS. This is where everything irreversible happens: the
554
+ * base_certificate is signed and the leaf and operation salt are spent. Sending
555
+ * is not what consumes them. In "unlinkable" mode a prepared commitment that is
556
+ * never submitted leaves its leaf spent for good — the allocator is monotone on
557
+ * purpose (`LeafStore` has no `release()`), because recycling would reintroduce a
558
+ * reuse no verifier can detect. Losing a leaf costs one slot in a large key set;
559
+ * reusing one silently destroys the unlinkability the mode exists for. In
560
+ * "stable" mode leaf 0 is reused by design and nothing is lost.
561
+ *
562
+ * So: to retry a failed send, call `submit()` again with the commitment you
563
+ * already hold. Never re-`prepare()` the same material — that signs a second
564
+ * commitment for one certificate.
565
+ *
566
+ * Validation is identical to `issue()` (same non-empty subjects, implemented
567
+ * profiles, system_id, root_id, pool/holder, TTL) because both run this method.
568
+ *
569
+ * All members of one submission set must share issuer and authorization; every
570
+ * commitment from the same instance does, so prepared commitments can be mixed
571
+ * freely — `submit()` rejects a mismatch before spending a request.
572
+ */
573
+ prepare(input: IssueInput): Promise<PreparedCommitment>;
574
+ /**
575
+ * Submit prepared commitments as ONE submission set and return a handle for each.
576
+ *
577
+ * This is the request `prepare()` exists to fill: N members travel together and
578
+ * amortize the per-submission overhead across all of them. It is
579
+ * N-in-one-request, synchronous — not a time-window accumulation, so nothing is buffered and nothing is deferred.
580
+ *
581
+ * Handles come back in the SAME order as the input, each already correlated with
582
+ * its member of the response, so a batch of N is as persistable as a single
583
+ * emission: keep each handle and call `resolveEmission()` on it later.
584
+ *
585
+ * A retry re-sends these same commitments — the SDK never re-signs, because a
586
+ * leaf must not be reused. If the send fails after signing, the leaves are
587
+ * already spent (see `prepare()`); calling `submit()` again with the same array
588
+ * is the correct move, and the node deduplicates on the request id.
589
+ *
590
+ * At most `MAX_SUBMISSION_SET_MEMBERS` (64) commitments make one set; more
591
+ * throw `SubmissionSetTooLargeError` before anything is sent
592
+ * (submission-set/1 §8.1). Split a larger batch into several `submit()` calls.
593
+ */
594
+ submit(prepared: PreparedCommitment[], opts?: {
595
+ settlementPreferences?: SettlementPreferences;
596
+ requestId?: string;
597
+ }): Promise<SubmitResult>;
598
+ /**
599
+ * List the emissions this integration has in flight — neither independently
600
+ * verifiable yet nor terminally refused.
601
+ *
602
+ * `resolveEmission` requires a handle and `getOperation` requires an id. An
603
+ * issuer that lost both can still enumerate its in-flight emissions here: the
604
+ * request is authenticated by the caller's own key, the read chain proves the
605
+ * key-set root, and the server answers for that root's integration.
606
+ *
607
+ * Persisting the handle at emission remains the supported path; this method
608
+ * makes a lost handle recoverable instead of a reason to re-emit.
609
+ *
610
+ * `since` is required and bounded server-side; check `truncated` before
611
+ * treating the list as complete.
612
+ */
613
+ listUnresolvedEmissions(since: string, limit?: number): Promise<UnresolvedEmissions>;
614
+ /**
615
+ * Resolve an emission by the digest of the capacity evidence that produced it.
616
+ *
617
+ * The fallback when the node no longer knows the operation — it restarted with
618
+ * an in-memory journal, or the issuer moved to another node. The digest is the
619
+ * one identifier the issuer can always produce, because it recomputes it from
620
+ * evidence it signed; the attempt id was never the issuer's and the node's
621
+ * operation id belongs to a journal it may no longer be talking to.
622
+ *
623
+ * Not a weaker path: the read still carries both halves of the chain, and the
624
+ * resource signed is the digest itself — which is stronger than signing an id
625
+ * the node handed over, because the issuer can check what it means.
626
+ *
627
+ * Returns `pending` while the emission has not settled. Once it has, the full
628
+ * `verification_package` is assembled from the proof and the settlement
629
+ * material this read returns plus the handle the issuer kept
630
+ * (`baseCertificate`, `capacityEvidence`, `commitmentIndex`); the inclusion
631
+ * proof is derived from the proof's `consumed_commitment_ids`.
632
+ */
633
+ private resolveByCommitment;
634
+ /**
635
+ * Resolve a previously-emitted certificate from its handle: poll the ONE operation's
636
+ * state (never re-emits) and, once independent_ready, build the full
637
+ * verification-package/1 from the handle's own capacity_evidence + the node's
638
+ * proof/settlement material. Returns:
639
+ * - { state: "independent", verificationPackage, independenceRef } once settled,
640
+ * - { state: "pending", nodeState } while it is still being settled (retry later),
641
+ * - { state: "expired", nodeState, reasonCode } when it can no longer settle,
642
+ * - { state: "rejected", nodeState } on any other terminal state
643
+ * (rejected, insufficient_capacity, replay_detected, pre_evaluation_rejected,
644
+ * submission_failed).
645
+ *
646
+ * `opts.wait` bounds the poll (default: a SINGLE status check — a reconciler
647
+ * wants a quick "is it ready yet?", not a long block). Pass `maxAttempts` above
648
+ * 1, `maxWaitMs`, or `strategy: "auto"` to wait inline; a wait that ends
649
+ * without a terminal state reports `pending`, it does not throw.
650
+ * `opts.verificationContext` supplies the published profile values
651
+ * (rules_version + system_id) the package records; it defaults to this
652
+ * instance's `rulesVersion` and `systemId`.
653
+ */
654
+ resolveEmission(handle: EmissionHandle, opts?: {
655
+ /** The published profile values the package records. Default: this
656
+ * instance's `rulesVersion` and `systemId`. */
657
+ verificationContext?: {
658
+ rules_version: string;
659
+ system_id: string;
660
+ };
661
+ /** Poll scheduling. Omit for a single status check (the default). Supports the
662
+ * window-aware `auto` strategy, `maxWaitMs` and `onProgress` — see WaitOptions. */
663
+ wait?: WaitOptions;
664
+ }): Promise<EmissionResolution>;
665
+ /** Access the underlying low-level client (advanced: buildVerificationPackage,
666
+ * waitForOperation, etc.). */
667
+ nodeClient(): CertcryptNodeClient;
668
+ }