@signsealer/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,854 @@
1
+ "use strict";
2
+ /**
3
+ * `@signsealer/sdk` — the client an integration actually holds.
4
+ *
5
+ * Deliberately dependency-free: `fetch` is in the runtime, and a signing SDK
6
+ * that drags a HTTP library into somebody's build is a signing SDK that gets
7
+ * declined at review. It runs anywhere `fetch` does, which is every Node since
8
+ * 18, every edge runtime and the browser — though a key belongs on a server.
9
+ *
10
+ * Three things it does that a hand-rolled client usually does not:
11
+ *
12
+ * - retries the failures worth retrying, with an idempotency key, so a
13
+ * network blip does not become a second waiver;
14
+ * - surfaces the API's own sentence rather than "Request failed with 422";
15
+ * - keeps the request id, so a support mail can quote something we can look
16
+ * up.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_SIGNATURE_HEADER = exports.WEBHOOK_TIMESTAMP_HEADER = exports.WEBHOOK_EVENT_HEADER = exports.SignSealerSigning = exports.SignSealer = exports.SignSealerError = void 0;
20
+ exports.verifyWebhook = verifyWebhook;
21
+ exports.verifyWebhookRequest = verifyWebhookRequest;
22
+ /* ------------------------------------------------------------------ errors */
23
+ class SignSealerError extends Error {
24
+ status;
25
+ code;
26
+ message;
27
+ hint;
28
+ requestId;
29
+ retryAfter;
30
+ constructor(status, code, message, hint, requestId,
31
+ /** Seconds the server asked you to wait, from `Retry-After`. */
32
+ retryAfter) {
33
+ super(message);
34
+ this.status = status;
35
+ this.code = code;
36
+ this.message = message;
37
+ this.hint = hint;
38
+ this.requestId = requestId;
39
+ this.retryAfter = retryAfter;
40
+ this.name = "SignSealerError";
41
+ }
42
+ /** Worth trying again unchanged: transient by nature, not by hope. */
43
+ get retryable() {
44
+ return this.status === 429 || this.status >= 500;
45
+ }
46
+ /**
47
+ * The month's allowance is spent, or the business set a spending limit and
48
+ * this period reached it.
49
+ *
50
+ * Deliberately not retryable, and that is the point of it having its own
51
+ * status: a 429 means come back shortly, and this will not be there
52
+ * shortly. Handle it by telling somebody, not by waiting — the plan has to
53
+ * change, or the period has to turn.
54
+ */
55
+ get quotaExceeded() {
56
+ return this.status === 402 || this.code === "quota_exceeded";
57
+ }
58
+ }
59
+ exports.SignSealerError = SignSealerError;
60
+ /* ------------------------------------------------------------------ client */
61
+ /**
62
+ * Strip trailing slashes without a regular expression.
63
+ *
64
+ * `baseUrl.replace(/\/+$/, "")` is what this replaced, in both clients, and
65
+ * CodeQL is right that it is polynomial ReDoS: `\/+$` backtracks across a
66
+ * long run of slashes that is not at the end, so a base URL of one slash
67
+ * repeated is quadratic. The input is a developer's own configuration rather
68
+ * than a stranger's, which makes it unlikely rather than impossible -- and
69
+ * the honest fix is four lines that cannot backtrack at all, not an argument
70
+ * about who supplies the string.
71
+ */
72
+ function withoutTrailingSlashes(url) {
73
+ let end = url.length;
74
+ while (end > 0 && url.charCodeAt(end - 1) === 47 /* "/" */)
75
+ end -= 1;
76
+ return url.slice(0, end);
77
+ }
78
+ class SignSealer {
79
+ #key;
80
+ #base;
81
+ #attempts;
82
+ #maxWaitMs;
83
+ #fetch;
84
+ /**
85
+ * Agreements left in this billing period, as of the last call that said
86
+ * (00271), or null on a plan that counts nothing down.
87
+ *
88
+ * A server with no screen to warn on still gets warned: the count rides on
89
+ * the answer to a send, so an integration can see the wall coming without
90
+ * polling for it.
91
+ */
92
+ agreementsRemaining = null;
93
+ constructor(opts) {
94
+ if (!opts.apiKey?.startsWith("mk_")) {
95
+ throw new Error("a SignSealer API key looks like mk_live_… or mk_test_…");
96
+ }
97
+ this.#key = opts.apiKey;
98
+ this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
99
+ this.#attempts = Math.max(1, opts.maxAttempts ?? 3);
100
+ this.#maxWaitMs = Math.max(0, opts.maxWaitMs ?? 5_000);
101
+ this.#fetch = opts.fetch ?? globalThis.fetch;
102
+ }
103
+ /* ------------------------------------------------------------- account */
104
+ /** Prove the key works, and say whose account it is. */
105
+ /**
106
+ * The brand this account shows its signers.
107
+ *
108
+ * SignSealer's own until the business has the white-label add-on and has
109
+ * set a brand. An embedded platform reads this to match its own chrome to
110
+ * what the signer is about to see, so the two do not disagree at the
111
+ * moment somebody is deciding whether to trust the page.
112
+ */
113
+ branding() {
114
+ return this.#call("GET", "/v1/branding");
115
+ }
116
+ account() {
117
+ return this.#call("GET", "/v1/account");
118
+ }
119
+ /* ----------------------------------------------------------- templates */
120
+ async templates() {
121
+ const { templates } = await this.#call("GET", "/v1/templates");
122
+ return templates;
123
+ }
124
+ /**
125
+ * Whether a template is an uploaded PDF, and whether it is usable yet.
126
+ *
127
+ * `ready` is the one to check: a PDF template cannot be published until
128
+ * every page has a picture a signer can read. Uploading the file is a
129
+ * dashboard step — drawing those pictures needs a browser, which a server
130
+ * does not have — so this is read-only on purpose.
131
+ */
132
+ /**
133
+ * Create a template. Version 1, as a draft.
134
+ *
135
+ * A template is not usable until it is published, and publishing is what
136
+ * freezes the text people will have signed — so this is deliberately the
137
+ * *draft* door and there is no `publish` beside it. Publishing is a
138
+ * decision somebody makes looking at the words, in the dashboard.
139
+ *
140
+ * `fields` says what the document asks for besides a signature, and is
141
+ * set in the same call rather than in a second one: a template that
142
+ * exists for a moment asking for nothing is a template somebody can send
143
+ * in that moment.
144
+ */
145
+ createTemplate(input, idempotencyKey) {
146
+ return this.#call("POST", "/v1/templates", input, idempotencyKey);
147
+ }
148
+ templatePdf(id) {
149
+ return this.#call("GET", `/v1/templates/${encodeURIComponent(id)}/pdf`);
150
+ }
151
+ /* ------------------------------------------------------ texting consent */
152
+ /**
153
+ * Record that you have consent to text a number.
154
+ *
155
+ * For a number you took somewhere SignSealer is not: your booking form, an
156
+ * order, the counter. Until this existed there was no way to tell us, so a
157
+ * business collecting numbers on its own form had every text held and was
158
+ * told nothing -- the document went out by email and the text quietly did
159
+ * not.
160
+ *
161
+ * `wording` is the field this method exists for. Send the exact words that
162
+ * were in front of the person, because it is kept verbatim and it is what a
163
+ * carrier asks for. It has to say that replying STOP opts out, that HELP
164
+ * gets help, that message and data rates may apply, and that message
165
+ * frequency varies; a disclosure missing any of those is refused with 422
166
+ * naming which, and nothing is recorded.
167
+ *
168
+ * One call covers the link, the reminder and the confirmation. Somebody who
169
+ * agreed to those agreed to all three, and an API that made you post three
170
+ * times would get posted to once.
171
+ *
172
+ * A number that has replied STOP cannot be re-consented this way. They have
173
+ * to opt in again themselves, and recording an attestation on their behalf
174
+ * is not that.
175
+ */
176
+ recordSmsConsent(input, idempotencyKey) {
177
+ return this.#call("POST", "/v1/sms-consents", {
178
+ phone: input.phone,
179
+ obtained_via: input.obtainedVia,
180
+ wording: input.wording,
181
+ }, idempotencyKey);
182
+ }
183
+ /**
184
+ * Whether you may text a number, and since when.
185
+ *
186
+ * Ask before putting the tick box in front of somebody again. It answers
187
+ * about the one number you pass and deliberately will not list every mobile
188
+ * on the account.
189
+ */
190
+ smsConsent(phone) {
191
+ return this.#call("GET", `/v1/sms-consents?phone=${encodeURIComponent(phone)}`);
192
+ }
193
+ /* ----------------------------------------------------------- documents */
194
+ documents(filter = {}) {
195
+ const q = new URLSearchParams(Object.entries(filter)
196
+ .filter(([, v]) => v !== undefined)
197
+ .map(([k, v]) => [k, String(v)]));
198
+ return this.#call("GET", `/v1/documents?${q}`);
199
+ }
200
+ document(id) {
201
+ return this.#call("GET", `/v1/documents/${encodeURIComponent(id)}`);
202
+ }
203
+ prepareDocument(input, idempotencyKey) {
204
+ return this.#call("POST", "/v1/documents", input, idempotencyKey);
205
+ }
206
+ send(documentId, signers, idempotencyKey) {
207
+ return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/send`, { signers }, idempotencyKey);
208
+ }
209
+ void(documentId, reason, idempotencyKey) {
210
+ return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/void`, { reason }, idempotencyKey);
211
+ }
212
+ /**
213
+ * The certificate, or null when there is not one yet.
214
+ *
215
+ * Null rather than a throw, because "not finished signing" is an ordinary
216
+ * state a caller polls through, not an exception.
217
+ */
218
+ async certificate(documentId) {
219
+ try {
220
+ return await this.#call("GET", `/v1/documents/${encodeURIComponent(documentId)}/certificate`);
221
+ }
222
+ catch (e) {
223
+ if (e instanceof SignSealerError && e.status === 404)
224
+ return null;
225
+ throw e;
226
+ }
227
+ }
228
+ /**
229
+ * The executed agreement and its certificate, sealed, as bytes.
230
+ *
231
+ * Null when the document has not been executed. A PDF headed "Certificate
232
+ * of Completion" for something nobody finished signing is precisely the
233
+ * artefact this product exists to make impossible, so there is no hopeful
234
+ * version of this to return.
235
+ */
236
+ async pdf(documentId) {
237
+ try {
238
+ const out = await this.#call("GET", `/v1/documents/${encodeURIComponent(documentId)}/pdf`);
239
+ return {
240
+ filename: out.filename,
241
+ bytes: base64ToBytes(out.bytes_base64),
242
+ seal: out.seal,
243
+ };
244
+ }
245
+ catch (e) {
246
+ if (e instanceof SignSealerError && e.status === 404)
247
+ return null;
248
+ throw e;
249
+ }
250
+ }
251
+ /**
252
+ * The evidence bundle: the sealed PDF with the evidence package printed
253
+ * after the audit trail — every message, every webhook, the record's state
254
+ * — as one sealed file. Null before the document is executed, like `pdf`;
255
+ * `evidence` has the JSON before then.
256
+ */
257
+ async bundle(documentId) {
258
+ try {
259
+ const out = await this.#call("GET", `/v1/documents/${encodeURIComponent(documentId)}/bundle`);
260
+ return {
261
+ filename: out.filename,
262
+ bytes: base64ToBytes(out.bytes_base64),
263
+ seal: out.seal,
264
+ };
265
+ }
266
+ catch (e) {
267
+ if (e instanceof SignSealerError && e.status === 404)
268
+ return null;
269
+ throw e;
270
+ }
271
+ }
272
+ /* ----------------------------------------------------------- workflows */
273
+ workflows() {
274
+ return this.#call("GET", "/v1/workflows");
275
+ }
276
+ /** The QR code for a workflow's public form: its address, an SVG, and a 1024px PNG as base64. 404 with no public address. */
277
+ workflowQr(workflowId) {
278
+ return this.#call("GET", `/v1/workflows/${encodeURIComponent(workflowId)}/qr`);
279
+ }
280
+ startWorkflow(workflowId, participant, idempotencyKey) {
281
+ return this.#call("POST", `/v1/workflows/${encodeURIComponent(workflowId)}/start`, participant, idempotencyKey);
282
+ }
283
+ /* ---------------------------------------------------------- reservations */
284
+ /**
285
+ * Import a reservation and its guests, and get back what is now required.
286
+ *
287
+ * One call rather than three. A booking system that has a reservation always
288
+ * wants to know what it needs signed, and splitting that into import, then
289
+ * guests, then build would be two round trips that exist only because we
290
+ * split them.
291
+ */
292
+ upsertReservation(input) {
293
+ return this.#call("PUT", "/v1/subjects", input);
294
+ }
295
+ packet(packetId) {
296
+ return this.#call("GET", `/v1/packets/${encodeURIComponent(packetId)}`);
297
+ }
298
+ startPacketItem(itemId, idempotencyKey) {
299
+ return this.#call("POST", `/v1/packets/items/${encodeURIComponent(itemId)}/start`, undefined, idempotencyKey);
300
+ }
301
+ /* ------------------------------------------------------------ webhooks */
302
+ webhooks() {
303
+ return this.#call("GET", "/v1/webhooks");
304
+ }
305
+ addWebhook(input, idempotencyKey) {
306
+ return this.#call("POST", "/v1/webhooks", input, idempotencyKey);
307
+ }
308
+ setWebhook(id, input) {
309
+ return this.#call("PATCH", `/v1/webhooks/${encodeURIComponent(id)}`, input);
310
+ }
311
+ removeWebhook(id, reason) {
312
+ return this.#call("DELETE", `/v1/webhooks/${encodeURIComponent(id)}?reason=${encodeURIComponent(reason)}`);
313
+ }
314
+ /**
315
+ * A new signing secret for an endpoint, returned **once**.
316
+ *
317
+ * For 24 hours every delivery is signed with both — the signature header
318
+ * carries two comma-separated `v1=` values, the new secret's first — so a
319
+ * receiver can switch over without dropping a delivery. `verifyWebhook`
320
+ * accepts either while both are live, so the safe order is: rotate, store
321
+ * the new secret, pass both to the verifier, then drop the old one.
322
+ *
323
+ * After the window the old secret is forgotten, and a delivery signed
324
+ * with it will not verify.
325
+ */
326
+ rotateWebhookSecret(id) {
327
+ return this.#call("POST", `/v1/webhooks/${encodeURIComponent(id)}/rotate`);
328
+ }
329
+ /**
330
+ * An endpoint's last fifty deliveries, newest first.
331
+ *
332
+ * What each one was, whether it landed, how many attempts it took, when
333
+ * the next is due, and the last error in the words the receiver gave us.
334
+ * A replay names the delivery it repeats in `replay_of`.
335
+ */
336
+ webhookDeliveries(id) {
337
+ return this.#call("GET", `/v1/webhooks/${encodeURIComponent(id)}/deliveries`);
338
+ }
339
+ /**
340
+ * Send one delivery again, as a new delivery marked as its replay.
341
+ *
342
+ * For the afternoon somebody's receiver was down, or deployed a bug that
343
+ * dropped what it was handed. A delivery still in the queue is refused,
344
+ * and so is a second replay while the first is queued — a replay is not a
345
+ * way to send the same event five times.
346
+ */
347
+ replayWebhookDelivery(deliveryId, idempotencyKey) {
348
+ return this.#call("POST", `/v1/webhooks/deliveries/${encodeURIComponent(deliveryId)}/replay`, undefined, idempotencyKey);
349
+ }
350
+ /* ------------------------------------------------------------- devices */
351
+ /**
352
+ * Trade a pairing code for a device credential.
353
+ *
354
+ * **Takes no API key**, and it is the only method here that does not: the
355
+ * pairing code *is* the credential, and requiring a key to exchange a code
356
+ * for a key is the circle the whole feature exists to break. So call it on
357
+ * a `SignSealer` built without one, or on the device itself.
358
+ *
359
+ * The code is shown once on the fleet screen, lives fifteen minutes and is
360
+ * spent on first use. What comes back is a key scoped to this device alone.
361
+ * Every refusal reads identically — wrong, expired, spent and belonging to
362
+ * a stopped device are deliberately indistinguishable, because telling them
363
+ * apart tells a guesser whether they are warm.
364
+ */
365
+ pairDevice(input) {
366
+ return this.#call("POST", "/v1/devices/pair", input);
367
+ }
368
+ /**
369
+ * Say the device is still here, and read back what it should be running.
370
+ *
371
+ * The device does not say *which* device it is — the credential it calls
372
+ * with does. So a tablet cannot report on another's behalf, and a
373
+ * heartbeat from a revoked credential resolves to no device at all. The
374
+ * answer carries the device's name and assigned workflow, so a change made
375
+ * on the fleet screen reaches the tablet without re-pairing.
376
+ */
377
+ deviceHeartbeat(input = {}) {
378
+ return this.#call("POST", "/v1/devices/heartbeat", input);
379
+ }
380
+ /* ------------------------------------------------------------ the wire */
381
+ async #call(method, path, body, idempotencyKey) {
382
+ /*
383
+ A retry without a key can create a second document, so one is minted for
384
+ any write that did not bring its own. That is the difference between a
385
+ client that is safe to retry and a client that is merely willing to.
386
+ */
387
+ const key = idempotencyKey ??
388
+ (method === "GET" || method === "DELETE" ? undefined : crypto.randomUUID());
389
+ let lastError;
390
+ for (let attempt = 1; attempt <= this.#attempts; attempt++) {
391
+ let res;
392
+ try {
393
+ res = await this.#fetch(`${this.#base}${path}`, {
394
+ method,
395
+ headers: {
396
+ authorization: `Bearer ${this.#key}`,
397
+ "content-type": "application/json",
398
+ ...(key ? { "idempotency-key": key } : {}),
399
+ },
400
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
401
+ });
402
+ }
403
+ catch (cause) {
404
+ // A connection that never landed is the case idempotency exists for:
405
+ // we cannot know whether the server did the work, so we retry with
406
+ // the same key and let it tell us.
407
+ lastError = new SignSealerError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer", undefined, undefined);
408
+ if (attempt < this.#attempts) {
409
+ await sleep(backoff(attempt));
410
+ continue;
411
+ }
412
+ throw lastError;
413
+ }
414
+ const requestId = res.headers.get("x-request-id") ?? undefined;
415
+ /*
416
+ How many agreements are left this month, when the server said
417
+ (00271). Kept on the client rather than returned, so reading it is
418
+ never a breaking change to a method's shape — and it is there after
419
+ every call that reports it, which is every successful send on a plan
420
+ that counts them down. Null means this plan counts nothing down.
421
+ */
422
+ const left = res.headers.get("x-agreements-remaining");
423
+ if (left !== null) {
424
+ const n = Number(left);
425
+ if (Number.isFinite(n))
426
+ this.agreementsRemaining = n;
427
+ }
428
+ const text = await res.text();
429
+ const parsed = text ? safeJson(text) : {};
430
+ if (res.ok)
431
+ return parsed;
432
+ const err = parsed
433
+ .error;
434
+ const askedFor = waitAsked(res.headers.get("retry-after"));
435
+ lastError = new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId, askedFor);
436
+ if (lastError.retryable && attempt < this.#attempts) {
437
+ /*
438
+ When the server said how long, wait that long rather than guessing.
439
+
440
+ The guess used to be 250ms, then 500ms, then a second — and the
441
+ rate limiter's window is a minute, so all three attempts landed
442
+ inside the same window, failed identically, and spent two more of
443
+ the caller's budget in the window after it. Worse than one
444
+ failure, and the server had been saying so.
445
+
446
+ A wait longer than `maxWaitMs` is not slept through: parking a
447
+ caller's `await` for a minute inside a library is its own
448
+ surprise. That one is thrown at once, with `retryAfter` on the
449
+ error, so the caller schedules it rather than blocking on it.
450
+ */
451
+ if (askedFor === undefined) {
452
+ await sleep(backoff(attempt));
453
+ continue;
454
+ }
455
+ if (askedFor * 1000 <= this.#maxWaitMs) {
456
+ await sleep(askedFor * 1000);
457
+ continue;
458
+ }
459
+ }
460
+ throw lastError;
461
+ }
462
+ throw lastError ?? new SignSealerError(0, "unknown", "the request failed", undefined, undefined);
463
+ }
464
+ }
465
+ exports.SignSealer = SignSealer;
466
+ /**
467
+ * The signer's side, which takes **no API key at all**.
468
+ *
469
+ * A separate class rather than methods on `SignSealer`, and the separation is
470
+ * the point rather than tidiness. A signing token is the whole credential on
471
+ * these routes; a client that could send a key alongside one would be a client
472
+ * that widens somebody's authority by accident, and the API deliberately
473
+ * ignores a key here for the same reason.
474
+ *
475
+ * Use this to build your own signing page. If you want ours, send the signer
476
+ * to `https://api.signsealer.com/s/<token>` and skip all of it.
477
+ */
478
+ class SignSealerSigning {
479
+ #base;
480
+ #fetch;
481
+ constructor(opts = {}) {
482
+ this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
483
+ this.#fetch = opts.fetch ?? globalThis.fetch;
484
+ }
485
+ /**
486
+ * Everything the page needs from one token.
487
+ *
488
+ * Answers for a token that matches nothing too, with `ok: false` and a
489
+ * reason — a bad link and an expired one are deliberately indistinguishable.
490
+ */
491
+ link(token) {
492
+ return this.#call("GET", `/v1/sign/${encodeURIComponent(token)}`);
493
+ }
494
+ /**
495
+ * Where one page of an uploaded PDF lives, for an `<img>` or an `<Image>`.
496
+ *
497
+ * Not under `/v1`, and it takes **no API key**: the signing token is the
498
+ * whole credential, the same one `link` was called with. That is what lets
499
+ * the browser fetch it directly rather than proxying it through your
500
+ * server with a key attached.
501
+ */
502
+ pageUrl(token, n) {
503
+ return `${this.#base}/s/${encodeURIComponent(token)}/page?n=${n}`;
504
+ }
505
+ /**
506
+ * Send this signer a one-time code, when the business asks for one.
507
+ *
508
+ * Only when the business has switched it on (Settings → Signing) and the
509
+ * link was delivered to this signer. The code goes to the address or
510
+ * number the link went to — never one your page collects — and the answer
511
+ * says where, masked, so you can render "we sent a code to d•••@example.com"
512
+ * without learning the address.
513
+ *
514
+ * **A signing flow that never calls this will simply fail for those
515
+ * businesses**: `sign` is refused while a required code is unconfirmed,
516
+ * and there is nothing in `link()` you could have done about it. Check
517
+ * `SigningLink.verification` and send a code when it says one is wanted.
518
+ *
519
+ * One a minute, five an hour. Not an identity check: it proves control of
520
+ * that inbox or phone at the moment of signing, and the certificate says
521
+ * `email_otp` or `sms_otp` rather than anything about who the person is.
522
+ */
523
+ requestCode(token) {
524
+ return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}/code`);
525
+ }
526
+ /**
527
+ * Confirm the code the signer typed.
528
+ *
529
+ * A wrong code answers `{ ok: false }` with the tries left rather than
530
+ * throwing — it is an answer, not an error, and a client that treated it
531
+ * as one would show a stack trace to somebody who fat-fingered a digit.
532
+ * After five wrong tries the code is dead and a new one has to be sent.
533
+ *
534
+ * A confirmed code is a verified event on the evidence trail.
535
+ */
536
+ confirmCode(token, code) {
537
+ return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}/verify`, { code });
538
+ }
539
+ /** Must happen before signing. The engine refuses a signature without it. */
540
+ consent(token, captured) {
541
+ return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}/consent`, captured ? { captured } : {});
542
+ }
543
+ /** Initials, a checkbox, a date. `about` names the child a field is for. */
544
+ supply(token, key, value, about) {
545
+ return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}/fields`, { key, value, ...(about ? { about } : {}) });
546
+ }
547
+ sign(token, method, value, captured) {
548
+ return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}`, { method, value, ...(captured ? { captured } : {}) });
549
+ }
550
+ decline(token, reason) {
551
+ return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}/decline`, { reason });
552
+ }
553
+ /**
554
+ * Check a certificate by its printed code. No credential of any kind.
555
+ *
556
+ * Supply `documentSha256` to have a file you hold compared with the one
557
+ * recorded — the hash is compared, never the file.
558
+ */
559
+ verify(code, documentSha256) {
560
+ const q = documentSha256 ? `?sha256=${encodeURIComponent(documentSha256)}` : "";
561
+ return this.#call("GET", `/v1/verify/${encodeURIComponent(code)}${q}`);
562
+ }
563
+ /*
564
+ No retries here, and that is deliberate rather than unfinished. These calls
565
+ are made with a person waiting, and the ones that write are refused on a
566
+ repeat by the engine anyway — a second `sign` is not idempotent, it is a
567
+ second signature the engine correctly declines. Retrying would turn a
568
+ clear refusal into a confusing one.
569
+ */
570
+ async #call(method, path, body) {
571
+ let res;
572
+ try {
573
+ res = await this.#fetch(`${this.#base}${path}`, {
574
+ method,
575
+ headers: body === undefined ? {} : { "content-type": "application/json" },
576
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
577
+ });
578
+ }
579
+ catch (cause) {
580
+ throw new SignSealerError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer", undefined, undefined);
581
+ }
582
+ const requestId = res.headers.get("x-request-id") ?? undefined;
583
+ const text = await res.text();
584
+ const parsed = text ? safeJson(text) : {};
585
+ if (res.ok)
586
+ return parsed;
587
+ const err = parsed.error;
588
+ throw new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId);
589
+ }
590
+ }
591
+ exports.SignSealerSigning = SignSealerSigning;
592
+ /**
593
+ * `Retry-After`, as seconds, when it is a number we believe.
594
+ *
595
+ * The header may also be an HTTP date; SignSealer sends seconds, and a date
596
+ * is read too so a proxy in between cannot turn a wait into a guess.
597
+ */
598
+ function waitAsked(header) {
599
+ const raw = (header ?? "").trim();
600
+ if (!raw)
601
+ return undefined;
602
+ if (/^\d+$/.test(raw)) {
603
+ const n = Number(raw);
604
+ return n >= 0 && n <= 86_400 ? n : undefined;
605
+ }
606
+ const at = new Date(raw).getTime();
607
+ if (!Number.isFinite(at))
608
+ return undefined;
609
+ const secs = Math.ceil((at - Date.now()) / 1000);
610
+ return secs >= 0 && secs <= 86_400 ? secs : undefined;
611
+ }
612
+ function backoff(attempt) {
613
+ // Exponential with jitter. Without the jitter, every client that failed
614
+ // together retries together, which is how a recovering service is knocked
615
+ // over by the clients waiting for it.
616
+ const base = Math.min(2 ** (attempt - 1) * 250, 4_000);
617
+ return base + Math.random() * base * 0.3;
618
+ }
619
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
620
+ /** Base64 to bytes, without assuming Node: `atob` is in every runtime that
621
+ * has `fetch`, and `Buffer` is not. */
622
+ function base64ToBytes(b64) {
623
+ const binary = atob(b64);
624
+ const out = new Uint8Array(binary.length);
625
+ for (let i = 0; i < binary.length; i++)
626
+ out[i] = binary.charCodeAt(i);
627
+ return out;
628
+ }
629
+ function safeJson(text) {
630
+ try {
631
+ return JSON.parse(text);
632
+ }
633
+ catch {
634
+ return {};
635
+ }
636
+ }
637
+ /* ------------------------------------------------------- verifying a webhook
638
+
639
+ The SDK could create a webhook endpoint and could not check a delivery from
640
+ it, which is the wrong half to ship: managing endpoints is a thing you do
641
+ once, and verifying a delivery is a thing your server does on every request
642
+ for ever. Everybody who integrated had to write this from the prose, and
643
+ the parts that are easy to get wrong are not the obvious ones.
644
+
645
+ Written against WebCrypto rather than `node:crypto`, because this package
646
+ says it runs in Node, edge runtimes and the browser, and one import of
647
+ `node:crypto` would make two of those false. That is what makes it async.
648
+ */
649
+ exports.WEBHOOK_EVENT_HEADER = "signsealer-event-id";
650
+ exports.WEBHOOK_TIMESTAMP_HEADER = "signsealer-timestamp";
651
+ exports.WEBHOOK_SIGNATURE_HEADER = "signsealer-signature";
652
+ /** Five minutes each way, matching the sender. */
653
+ exports.WEBHOOK_TOLERANCE_SECONDS = 300;
654
+ /** Hex to bytes, for a string already known to be `[0-9a-f]` of even length. */
655
+ function hexToBytes(hex) {
656
+ const out = new Uint8Array(hex.length / 2);
657
+ for (let i = 0; i < out.length; i++)
658
+ out[i] = parseInt(hex.substr(i * 2, 2), 16);
659
+ return out;
660
+ }
661
+ /**
662
+ * Constant time, which is the whole reason this is in the SDK.
663
+ *
664
+ * `a === b` on a hex string returns as soon as it finds a difference, and how
665
+ * long it took says how many characters were right — which recovers a valid
666
+ * signature one character at a time. Every byte is compared here whatever the
667
+ * result.
668
+ */
669
+ function sameBytes(a, b) {
670
+ if (a.length !== b.length)
671
+ return false;
672
+ let diff = 0;
673
+ for (let i = 0; i < a.length; i++)
674
+ diff |= a[i] ^ b[i];
675
+ return diff === 0;
676
+ }
677
+ /**
678
+ * WebCrypto, wherever this is running.
679
+ *
680
+ * `globalThis.crypto` is the one every modern runtime has — browsers, Deno,
681
+ * Bun, Cloudflare Workers, Vercel's edge, and Node from 19. It is **not** on
682
+ * Node 18, which this package still declares support for: 18 ships WebCrypto
683
+ * only as `node:crypto`'s `webcrypto` export unless the process was started
684
+ * with `--experimental-global-webcrypto`. The first version of this threw
685
+ * there, and said in the message that Node 18 had it, which was wrong twice.
686
+ *
687
+ * So the global first, and `node:crypto` only when there is no global. The
688
+ * specifier is assembled at run time on purpose: written out, a bundler
689
+ * targeting the browser follows the static import and fails the build over a
690
+ * branch that browser will never take. The import is inside try/catch for the
691
+ * same reason — a runtime with neither should reach the error below, not a
692
+ * module-resolution failure.
693
+ *
694
+ * Resolved once and kept: this runs per delivery, and an endpoint under load
695
+ * should not re-enter the module loader for each one.
696
+ */
697
+ let subtlePromise = null;
698
+ function webCrypto() {
699
+ subtlePromise ??= (async () => {
700
+ const here = globalThis.crypto?.subtle;
701
+ if (here)
702
+ return here;
703
+ try {
704
+ const mod = await Promise.resolve(`${"node:" + "crypto"}`).then(s => require(s));
705
+ const fallback = mod.webcrypto?.subtle;
706
+ if (fallback)
707
+ return fallback;
708
+ }
709
+ catch {
710
+ /* Not Node. The error below is the honest answer. */
711
+ }
712
+ throw new Error("no WebCrypto in this runtime, so a webhook signature cannot be verified"
713
+ + " — every current browser, edge runtime and Node 19 or later has it,"
714
+ + " and Node 18 reaches it through node:crypto");
715
+ })();
716
+ return subtlePromise;
717
+ }
718
+ async function hmacSha256(secret, message) {
719
+ const subtle = await webCrypto();
720
+ const enc = new TextEncoder();
721
+ const key = await subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
722
+ return new Uint8Array(await subtle.sign("HMAC", key, enc.encode(message)));
723
+ }
724
+ /**
725
+ * Is this delivery really from SignSealer, and recent?
726
+ *
727
+ * ```ts
728
+ * const check = await verifyWebhook({
729
+ * secret: process.env.SIGNSEALER_WEBHOOK_SECRET!,
730
+ * body: rawBody, // the bytes, not the object
731
+ * signature: req.headers["signsealer-signature"],
732
+ * timestamp: req.headers["signsealer-timestamp"],
733
+ * });
734
+ * if (!check.ok) return res.status(400).send(check.reason);
735
+ * ```
736
+ *
737
+ * Three things it does that a hand-written check usually misses.
738
+ *
739
+ * **The timestamp is inside the MAC**, so a captured delivery cannot be
740
+ * replayed tomorrow with a fresh header — and the window is enforced in both
741
+ * directions, because accepting one from the future is how you buy yourself an
742
+ * arbitrarily long replay window.
743
+ *
744
+ * **A rotation carries two signatures.** During a secret rotation's grace
745
+ * window the header is `v1=<new>,v1=<old>`, so a receiver holding either
746
+ * secret still verifies. A check written against a single signature starts
747
+ * rejecting real deliveries the first time the secret is rotated.
748
+ *
749
+ * **Every part is compared**, not the first that matches, and in constant
750
+ * time.
751
+ *
752
+ * Use `signsealer-event-id` for idempotency: a delivery retried six times
753
+ * carries the same id six times, and it is one event.
754
+ */
755
+ async function verifyWebhook(opts) {
756
+ const tolerance = opts.toleranceSeconds ?? exports.WEBHOOK_TOLERANCE_SECONDS;
757
+ const now = Math.floor((opts.now ?? Date.now()) / 1000);
758
+ if (!opts.secret)
759
+ return { ok: false, reason: "no signing secret was given" };
760
+ if (!opts.signature)
761
+ return { ok: false, reason: "no signature header" };
762
+ if (!opts.timestamp)
763
+ return { ok: false, reason: "no timestamp header" };
764
+ const sent = Number(opts.timestamp);
765
+ if (!Number.isFinite(sent))
766
+ return { ok: false, reason: "the timestamp is not a number" };
767
+ if (Math.abs(now - sent) > tolerance) {
768
+ return {
769
+ ok: false,
770
+ reason: `the timestamp is ${Math.abs(now - sent)}s away from now, outside the ${tolerance}s window`,
771
+ };
772
+ }
773
+ /*
774
+ Every part must be well-formed, and one that is not refuses the delivery
775
+ before any comparison — so the header cannot be padded with junk to change
776
+ how long this takes.
777
+ */
778
+ const parts = opts.signature.split(",").map((p) => p.trim()).filter(Boolean);
779
+ const givens = [];
780
+ for (const part of parts) {
781
+ const given = /^v1=([0-9a-f]{64})$/.exec(part)?.[1];
782
+ if (!given)
783
+ return { ok: false, reason: "the signature is not in the v1=<hex> form" };
784
+ givens.push(given);
785
+ }
786
+ if (!givens.length)
787
+ return { ok: false, reason: "the signature is not in the v1=<hex> form" };
788
+ const expected = await hmacSha256(opts.secret, `${sent}.${opts.body}`);
789
+ let matched = false;
790
+ for (const given of givens) {
791
+ /* Not `if (matched) break`: the time taken must say nothing about which
792
+ signature was the right one, or whether an early one matched. */
793
+ if (sameBytes(expected, hexToBytes(given)))
794
+ matched = true;
795
+ }
796
+ return matched ? { ok: true } : { ok: false, reason: "the signature does not match" };
797
+ }
798
+ function headerOf(headers, name) {
799
+ if (typeof headers.get === "function") {
800
+ return headers.get(name) ?? null;
801
+ }
802
+ const bag = headers;
803
+ /* Node lower-cases incoming header names; a hand-built object may not. */
804
+ const raw = bag[name] ?? bag[name.toLowerCase()]
805
+ ?? bag[Object.keys(bag).find((k) => k.toLowerCase() === name.toLowerCase()) ?? ""];
806
+ return Array.isArray(raw) ? raw[0] ?? null : raw ?? null;
807
+ }
808
+ /**
809
+ * The same check, reading the headers for you, and handing back the event id.
810
+ *
811
+ * ```ts
812
+ * const { ok, reason, eventId } = await verifyWebhookRequest({
813
+ * secret, body: rawBody, headers: req.headers,
814
+ * });
815
+ * if (!ok) return res.status(400).send(reason);
816
+ * if (await alreadyHandled(eventId)) return res.status(200).end();
817
+ * ```
818
+ *
819
+ * ## What `eventId` is, and the one thing it does not do
820
+ *
821
+ * It is stable across retries — a delivery attempted six times carries the
822
+ * same id all six — which is what makes it the key to deduplicate on. Use it.
823
+ *
824
+ * What it is **not** is authenticated. The signature covers `timestamp.body`;
825
+ * the id travels beside it in a header, outside the HMAC. So somebody who
826
+ * obtains one valid delivery can, inside the tolerance window, send those same
827
+ * signed bytes again with a different id on them, and a receiver keyed on the
828
+ * id will treat the replay as a new event.
829
+ *
830
+ * There is no way to close that from inside this package today, and it is
831
+ * worth saying rather than implying otherwise. A key derived from the signed
832
+ * material — the hash of `timestamp.body` — is authenticated but is *not*
833
+ * stable across retries, because the sender signs a fresh timestamp on every
834
+ * attempt; this SDK briefly returned one, which deduplicated replays and broke
835
+ * ordinary retries, which is the worse failure of the two. The fix is to bring
836
+ * the id inside the signature under a `v2=` scheme, and that is a change to
837
+ * the wire rather than to this file.
838
+ *
839
+ * Until then: deduplicate on `eventId`, and if a replay inside a five-minute
840
+ * window would be harmful to your system, check the event's own contents
841
+ * against your records before acting on it.
842
+ */
843
+ async function verifyWebhookRequest(opts) {
844
+ const result = await verifyWebhook({
845
+ secret: opts.secret,
846
+ body: opts.body,
847
+ signature: headerOf(opts.headers, exports.WEBHOOK_SIGNATURE_HEADER),
848
+ timestamp: headerOf(opts.headers, exports.WEBHOOK_TIMESTAMP_HEADER),
849
+ toleranceSeconds: opts.toleranceSeconds,
850
+ now: opts.now,
851
+ });
852
+ return { ...result, eventId: headerOf(opts.headers, exports.WEBHOOK_EVENT_HEADER) };
853
+ }
854
+ //# sourceMappingURL=index.cjs.map