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