@signsealer/sdk 1.10.0 → 1.13.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.
package/CHANGELOG.md CHANGED
@@ -1,9 +1,154 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 1.13.0
4
4
 
5
5
  ### Added
6
6
 
7
+ - `textingNumberInvitation(prefill)`: a link that takes a business's owner to
8
+ apply for its own texting number, with what your software already knows
9
+ filled in (`TextingNumberPrefill`, in the application's own field names).
10
+ For a platform serving many businesses, each its own account: ask with that
11
+ business's key or token when `account().texting.why_not` is `number`, and
12
+ show the link on your own screen. It files nothing; the owner reads every
13
+ answer, ticks that it is true and applies. Fourteen days, used up when the
14
+ business applies, twenty a day; a test key is refused. It is sent once and
15
+ never retried, because a retry would spend one of the twenty on a link
16
+ nobody was handed.
17
+ - `Account.texting.number`, the business's own verified number, and
18
+ `Account.texting.application` (`TextingApplication`): where its
19
+ application has got to, or null when it has not applied.
20
+ - The `texting.number_updated` webhook: one delivery per step of the
21
+ application, carrying `number` with `status`, `kind`, `phone` once it is
22
+ the business's, `area_code`, `reason` when the carriers asked for a change
23
+ and `brought`.
24
+
25
+ ## 1.12.0
26
+
27
+ ### Added
28
+
29
+ - A question's `show_if` can say more (`ShowIf`, `ShowIfRule`,
30
+ `ConditionRule`). One rule is written as before, `{ field, ticked: true }`;
31
+ several are `{ match: "all" | "any", rules: [...] }`, up to ten, so a
32
+ question can be asked when every rule is met or when any one is. A rule
33
+ can now also be `not_equals` (answered, and none of these), `contains`
34
+ (words in the answer), `gt` or `lt` (a number above or below, for a
35
+ `number` question), or `age_under` or `age_at_least` (whole years from a
36
+ date of birth, for a `birthdate`, `date` or `datetime` question). The
37
+ server decides, as it did; `SigningField.visible` is still its answer. A
38
+ rule about a question that was itself not asked is not met, and
39
+ `not_equals` needs an answer.
40
+ - A paragraph of the text can depend on the first signer's answers, written
41
+ between `[[show if ...]]` and `[[end]]` lines. `SigningLink.paragraphs`
42
+ says how many there are, which apply (`sections`), whose answers decide
43
+ them and whether that is settled; `body` has only the ones that apply.
44
+ The first signer is also given `source` and `conditions`, to show them as
45
+ the answers come in; anybody else waits until the first signer has
46
+ signed. `sign` takes the paragraphs your page drew as a fifth argument,
47
+ which the first signer's signature needs while they are undecided (422
48
+ without it), and is refused with 409 `paragraphs_changed` when the
49
+ answers call for others. `WorkflowBundle.template.sections` carries the conditions for a
50
+ tablet with no network.
51
+ - A workflow's fixed signer can sign only when the form's answers say so: a
52
+ role in `signer_roles` may have a `show_if` about the workflow's own
53
+ `form_fields`, whose questions now say what they are (`kind`, and
54
+ `options` for a choice), and an answer to one is checked as a template's
55
+ is (422, naming the question). `StartedWorkflow.not_needed` names the
56
+ roles a start's answers did not need; they are not on the document.
57
+ - For a page that decides conditions itself: `SigningLink.condition_zone`
58
+ (and `WorkflowBundle.condition_zone`) is the zone whose calendar day the
59
+ server reads an age on, so "under 18" means the same day to the page as to
60
+ the server. `SigningField.rules_at_start` is the server's answer to each
61
+ rule of a question's `show_if` on its own, and
62
+ `SigningLink.paragraphs.rules_at_start` the same for each paragraph's
63
+ rules, for a rule about a question the page does not ask (one already
64
+ answered, or filled in by whoever sent it).
65
+
66
+ - A condition can do more (00545): `action: "hide"` hides a question, a
67
+ paragraph or a signer when it holds rather than showing it; a part of a
68
+ condition can be a group (`ShowIfGroup`), two or more rules joined by
69
+ their own `"all"` or `"any"`, so `(A and B) or C` can be written, with at
70
+ most ten rules in all; and `not_contains` is a rule, answered and without
71
+ those words. Everything written before means what it meant.
72
+ - `Account.texting.why_not` names every reason the server gives: `number`
73
+ while the business waits for its own verified texting number (00556), and
74
+ `beta` while it is in the beta, which does not text (00564), besides
75
+ `plan` and `test`. Offer no "text me" box for any of them.
76
+
77
+ ## 1.11.1
78
+
79
+ ### Fixed
80
+
81
+ - Writes on Node 18. A write that did not bring its own idempotency key was
82
+ given one with the global `crypto.randomUUID()`, which Node 18 has only
83
+ when started with `--experimental-global-webcrypto`; everywhere else on
84
+ 18 the call threw a `ReferenceError` before anything was sent. The key now
85
+ comes from the global where there is one and from `node:crypto` where
86
+ there is not, as webhook verification already did. Node 19 and later,
87
+ browsers and edge runtimes are unchanged.
88
+
89
+ ## 1.11.0
90
+
91
+ ### Changed
92
+
93
+ - `new SignSealerSigning({ deviceKey })`. Since 2 October the server keeps
94
+ `captured` on a signature only from a paired tablet of the business the
95
+ link belongs to, which sends its own credential as the bearer; from
96
+ anybody else the claim is dropped without an error and the signature is
97
+ dated when it arrives. This client sent no credential at all, so an
98
+ offline signature made through it lost the time it was taken. Given the
99
+ key `pairDevice` answered, `sign()` now sends it with a signature that
100
+ carries `captured`, and with nothing else.
101
+ - A photo refused because the server is reading others is a `429` with
102
+ `code: "busy"` and `Retry-After` (thirty seconds), where it was a `422`
103
+ (3 October). `supplyPhoto` and `captureIdEvidence` throw it as a
104
+ `SignSealerError` whose `retryable` is true and `retryAfter` is the wait;
105
+ nothing was kept, and the same photo can be sent again then. Code that
106
+ treated every refusal of a photo as final now has one it should retry.
107
+
108
+ ### Fixed
109
+
110
+ - `Branding` declares what `GET /v1/branding` answers: `businessName`,
111
+ `primaryColor`, `hasLogo`, `signingHost`, `logoUrl` and the rest, in
112
+ camelCase. It declared `tenant_name`, `colour`, `has_logo`,
113
+ `has_logo_dark` and `signing_host`, which the API has never sent, so each
114
+ read as undefined. Code that compiled against the old names was reading
115
+ nothing; it now fails to compile, which is the point.
116
+ - `SignSealerSigning`'s errors carry `retryAfter`, read from `Retry-After`
117
+ as `SignSealer`'s do. They never did, so a `429` from a signing link --
118
+ a code asked for too soon, a busy photo -- said nothing about how long.
119
+ - `setWebhook`'s doc comment: since 3 October the server checks the
120
+ `events` a change sends as it checks `addWebhook`'s, and refuses a name
121
+ that is not an event with a `422` whose `hint` lists every one (00507).
122
+ This client sends what it is given, so a typo that used to be stored and
123
+ never fire is now an error you can see.
124
+ - `remind`'s doc comment says what 00507 changed: a signer is texted one
125
+ reminder over the life of their link, after which a reminder goes by
126
+ email alone, and one with no email address is refused with a `422`.
127
+ - `setWebhook()` is typed with what turning an endpoint back on answers:
128
+ `resumed`, `waiting` and `dropped_while_paused` (00289).
129
+ - Doc comments that described the API as it was: `templatePdf` (the server
130
+ draws a PDF's pages since 00474, not the uploader's browser), `remind`
131
+ (three a day per signer, twenty-five per document, 00500),
132
+ `recordSmsConsent` (all seven things the wording must say), and
133
+ `verifyWebhookRequest` (a hash of the raw body is a retry-stable key the
134
+ signature covers).
135
+
136
+ ### Added
137
+
138
+ - `workflow_ids` on `setDevice` (00420): every form a tablet runs, in the
139
+ order its kiosk lists them. `PATCH /v1/devices/:id` has taken it since
140
+ 00420 and this client could not send it.
141
+ - `TemplatePdf.drawing_failed` (00474): why the pages could not be drawn
142
+ from the file, when they could not.
143
+ - `StartedWorkflow.template_version` and `party_size`; `PacketSummary.added`
144
+ and `dropped`; the rest of a `DocumentRow` (`integrity_ok`,
145
+ `template_code`, `expires_at` and the others); `Workflow.asked_fields`,
146
+ `sender_fields`, `public_slug`, `time_zone` and the party settings
147
+ (`each_person_signs`, 00484); `Device.workflows` and the queue and version
148
+ fields its heartbeat keeps (00337, 00341, 00420); and every key of
149
+ `SigningLink.party` (`lead_name`, `described`, `minors`, `signing_for`,
150
+ and each added person's `open`, `claimed` and `opened`, 00491). All
151
+ optional: each is what the API already answered.
7
152
  - `SigningField.from_sender` (00437). A box on an uploaded PDF that whoever
8
153
  sent the document filled in: already answered, shown and never asked for.
9
154
  - `SigningField.placed_words` (00438). What a placed box shows: a date or a
@@ -16,6 +161,10 @@
16
161
  - `Account.texting` (00458): whether the business can text people, why
17
162
  not when it cannot (`plan` or `test`), and the opt-in sentence to put
18
163
  beside a "text me" box and record with `recordSmsConsent` when ticked.
164
+ - `time_zone` on `prepareDocument`, and `SigningLink.time_zone` (00476). The
165
+ zone a document's times are in ("America/Denver"): a time blank given as
166
+ `2026-10-03T09:00` is written "October 3, 2026 at 9:00 am MDT". An unknown
167
+ zone is refused with a 422. Without it, values go in as sent.
19
168
  - `PartnerBusiness.source` can be `promotion`: a business that redeemed a
20
169
  promotion code the partner handed out (00421).
21
170
 
package/README.md CHANGED
@@ -94,7 +94,8 @@ try {
94
94
  `SignSealerSigning` takes **no API key**, because on those routes a signing
95
95
  token is the whole credential. It is a separate class on purpose: a client that
96
96
  could send a key alongside a token would be a client that widens somebody's
97
- authority by accident.
97
+ authority by accident. The one credential it carries is a paired tablet's own,
98
+ on an offline signature only (below).
98
99
 
99
100
  ```ts
100
101
  import { SignSealerSigning } from "@signsealer/sdk";
@@ -121,6 +122,23 @@ const asked = await signing.idEvidence(token); // { offered: "id" | "id
121
122
  if (asked?.offered !== "off") await signing.captureIdEvidence(token, "id", { contentType: "image/jpeg", bytes });
122
123
  ```
123
124
 
125
+ A photo the server could not read just then, because it was reading others,
126
+ is refused with a `429` whose `code` is `busy`: nothing was kept, and
127
+ `err.retryAfter` says how many seconds to wait (thirty). Tell the person, and
128
+ send the same photo again then. Any other refusal of a photo (`422`) will be
129
+ the same next time, and its message says why.
130
+
131
+ ```ts
132
+ try {
133
+ await signing.supplyPhoto(token, "boat_condition", { contentType: "image/jpeg", bytes });
134
+ } catch (e) {
135
+ if (e instanceof SignSealerError && e.code === "busy") {
136
+ showNote(e.message); // "Photos are queueing here just now. …"
137
+ setTimeout(() => sendAgain(), (e.retryAfter ?? 30) * 1000);
138
+ } else throw e;
139
+ }
140
+ ```
141
+
124
142
  ### Drawing the questions
125
143
 
126
144
  A template's questions arrive on `link.fields`, and three things about them
@@ -221,18 +239,28 @@ if (pdf.has_pdf && !pdf.ready) {
221
239
  }
222
240
  ```
223
241
 
224
- Uploading the file is a dashboard step, not an API call: the page pictures have
225
- to be drawn by a browser, and a server does not have one — so a route that took
226
- the bytes would leave a template that could never be published.
242
+ Uploading the file is a dashboard step, not an API call: that is where the boxes
243
+ are placed on its pages. SignSealer draws the pictures a signer sees from the
244
+ file itself as it is uploaded, and a template cannot be published until every
245
+ page has one.
227
246
 
228
247
  ### Signing where there is no network
229
248
 
230
- Pass `captured` with what the device thought the time was. The server records
231
- when *it* received the event — that is the part we can attest to — and keeps
232
- your claim beside it, marked as a claim, with the clock difference computed
233
- rather than accepted.
249
+ A paired tablet that took a signature offline passes `captured` with what the
250
+ device thought the time was. The server records when *it* received the event —
251
+ that is the part we can attest to — and keeps the claim beside it, marked as a
252
+ claim, with the clock difference computed rather than accepted.
253
+
254
+ The claim is kept only from a paired tablet of the business the link belongs
255
+ to, because the day it carries is the day written into the document. Give the
256
+ client the tablet's own credential — the `key` that `pairDevice` answered — and
257
+ it is sent with a `sign` that carries `captured`, and with nothing else. Without
258
+ it, `captured` is left out without an error and the signature is dated when it
259
+ arrives.
234
260
 
235
261
  ```ts
262
+ const signing = new SignSealerSigning({ deviceKey: tabletKey });
263
+
236
264
  await signing.sign(token, "drawn", dataUri, {
237
265
  offline: true,
238
266
  at: capturedAt.toISOString(),
@@ -261,6 +289,8 @@ app.post("/hooks/signsealer",
261
289
  if (!ok) return res.status(400).send(reason);
262
290
 
263
291
  // Deliveries are at-least-once: the same event id arrives again on a retry.
292
+ // (A SHA-256 of the raw body is the same on a retry too, and is covered by
293
+ // the signature, which the id is not; see `verifyWebhookRequest`.)
264
294
  if (await alreadyHandled(eventId)) return res.sendStatus(200);
265
295
 
266
296
  await act(JSON.parse(req.body.toString("utf8")));
@@ -337,10 +367,55 @@ fields: [
337
367
  ],
338
368
  ```
339
369
 
370
+ Several rules join with `all` or `any` (1.12.0), and a rule can also be
371
+ `not_equals`, `contains`, `gt` / `lt` for a number, or `age_under` /
372
+ `age_at_least` for a date of birth:
373
+
374
+ ```ts
375
+ { key: "guardian", label: "Parent or guardian's name", kind: "text",
376
+ show_if: { match: "any", rules: [
377
+ { field: "birthday", age_under: 18 },
378
+ { field: "school_trip", ticked: true },
379
+ ] } },
380
+ ```
381
+
382
+ A part of a condition can be a group with its own `all` or `any`, which is
383
+ how `(A and B) or C` is written, and `action: "hide"` hides the question
384
+ when the condition holds instead of showing it. `not_contains` is a rule
385
+ too, answered and without those words:
386
+
387
+ ```ts
388
+ { key: "locker", label: "Locker number", kind: "text",
389
+ show_if: { action: "hide", match: "any", rules: [
390
+ { match: "all", rules: [{ field: "member", unticked: true }, { field: "birthday", age_under: 18 }] },
391
+ { field: "injury", answered: true },
392
+ ] } },
393
+ ```
394
+
340
395
  A condition can only look at a question above it, and a block's heading is
341
396
  given once. The engine checks both and refuses by name, and a refused list
342
397
  leaves no template behind.
343
398
 
399
+ A paragraph of the text can depend on an answer too (1.12.0), written
400
+ between two lines of its own, with the same words a question's line uses:
401
+
402
+ ```text
403
+ [[show if pregnant is: Yes]]
404
+ My doctor has cleared me for this treatment.
405
+ [[end]]
406
+ ```
407
+
408
+ `[[hide if ...]]` hides one instead, and a group is `show if any: a is
409
+ ticked; b is: Yes`, its rules between semicolons.
410
+
411
+ The first signer's answers decide it. `link.body` has only the paragraphs
412
+ that apply, `link.paragraphs` says which, and the first signer's signature
413
+ settles them for everybody else on the document. If your page draws the
414
+ document itself, pass `link.paragraphs.sections` as the fifth argument to
415
+ `sign`: the first signer's signature is refused without it while the
416
+ paragraphs are undecided, and with 409 `paragraphs_changed` when the
417
+ answers have since called for others.
418
+
344
419
  ## Reading what was answered
345
420
 
346
421
  ```ts
@@ -410,6 +485,28 @@ as yours meanwhile, and nothing accrues until `earning` is true, counted from
410
485
  and used, after card fees and the carrier's cost of its texts; credit
411
486
  SignSealer gave away earns nothing.
412
487
 
488
+ ### For platforms: each business's own texting number
489
+
490
+ Each business that texts does so from a number of its own, applied for by its
491
+ owner under the business's legal name; you cannot apply for it. With each
492
+ business's key or token, see which need one and hand the owner a link to the
493
+ application with what you know filled in (1.13.0):
494
+
495
+ ```ts
496
+ const { texting } = await client.account();
497
+ if (texting?.why_not === "number" && !texting.application) {
498
+ const { url } = await client.textingNumberInvitation({
499
+ legal_name: "Dockside Diner LLC", ein: "12-3456789", website: "https://dockside.example",
500
+ address_line1: "1 Pier Rd", city: "Memphis", state: "TN", postal_code: "38103", kind: "toll_free",
501
+ });
502
+ // Show `url` to the owner: it opens their application, signed in, with your answers in it.
503
+ }
504
+ // texting.application: { status: "submitted", kind: "toll_free", phone: null, reason: null, … }
505
+ ```
506
+
507
+ The link files nothing: the owner reads every answer, ticks that it is true
508
+ and applies. Subscribe to `texting.number_updated` to hear each step.
509
+
413
510
  ## Options
414
511
 
415
512
  ```ts
@@ -133,7 +133,6 @@ class SignSealer {
133
133
  this.#fetch = opts.fetch ?? globalThis.fetch;
134
134
  }
135
135
  /* ------------------------------------------------------------- account */
136
- /** Prove the key works, and say whose account it is. */
137
136
  /**
138
137
  * The brand this account shows its signers.
139
138
  *
@@ -145,6 +144,7 @@ class SignSealer {
145
144
  branding() {
146
145
  return this.#call("GET", "/v1/branding");
147
146
  }
147
+ /** Prove the key works, and say whose account it is. */
148
148
  account() {
149
149
  return this.#call("GET", "/v1/account");
150
150
  }
@@ -205,14 +205,6 @@ class SignSealer {
205
205
  setTemplateSettings(id, input) {
206
206
  return this.#call("PATCH", `/v1/templates/${encodeURIComponent(id)}/settings`, input);
207
207
  }
208
- /**
209
- * Whether a template is an uploaded PDF, and whether it is usable yet.
210
- *
211
- * `ready` is the one to check: a PDF template cannot be published until
212
- * every page has a picture a signer can read. Uploading the file is a
213
- * dashboard step — drawing those pictures needs a browser, which a server
214
- * does not have — so this is read-only on purpose.
215
- */
216
208
  /**
217
209
  * Create a template. Version 1, as a draft.
218
210
  *
@@ -229,6 +221,14 @@ class SignSealer {
229
221
  createTemplate(input, idempotencyKey) {
230
222
  return this.#call("POST", "/v1/templates", input, idempotencyKey);
231
223
  }
224
+ /**
225
+ * Whether a template is an uploaded PDF, and whether it is usable yet.
226
+ *
227
+ * `ready` is the one to check: a PDF template cannot be published until
228
+ * SignSealer has drawn a picture of every page from the file itself
229
+ * (00474), which it does as the file is uploaded. Uploading the file is a
230
+ * dashboard step, where the boxes are placed; there is no API route for it.
231
+ */
232
232
  templatePdf(id) {
233
233
  return this.#call("GET", `/v1/templates/${encodeURIComponent(id)}/pdf`);
234
234
  }
@@ -245,9 +245,12 @@ class SignSealer {
245
245
  * `wording` is the field this method exists for. Send the exact words that
246
246
  * were in front of the person, because it is kept verbatim and it is what a
247
247
  * carrier asks for. It has to say that replying STOP opts out, that HELP
248
- * gets help, that message and data rates may apply, and that message
249
- * frequency varies; a disclosure missing any of those is refused with 422
250
- * naming which, and nothing is recorded.
248
+ * gets help, that message and data rates may apply, that message
249
+ * frequency varies, that consent is not a condition of purchase, and that
250
+ * the number is not shared or sold, and link the terms and the privacy
251
+ * policy; a disclosure missing any of those is refused with 422 naming
252
+ * which, and nothing is recorded. `account().texting.wording` is a
253
+ * sentence that passes.
251
254
  *
252
255
  * One call covers the link, the reminder and the confirmation. Somebody who
253
256
  * agreed to those agreed to all three, and an API that made you post three
@@ -274,6 +277,24 @@ class SignSealer {
274
277
  smsConsent(phone) {
275
278
  return this.#call("GET", `/v1/sms-consents?phone=${encodeURIComponent(phone)}`);
276
279
  }
280
+ /**
281
+ * A link that takes the business's owner to apply for its own texting
282
+ * number, with what you know filled in (1.13.0).
283
+ *
284
+ * For when `account().texting.why_not` is `number`. The link opens the
285
+ * business's application on SignSealer after its owner signs in; it files
286
+ * nothing, and only an owner or an admin can apply. Fourteen days, used up
287
+ * when the business applies, twenty a day. Watch `texting.application` on
288
+ * the account, or `texting.number_updated`, for where it has got to. A
289
+ * test key is refused: a sandbox never texts.
290
+ *
291
+ * Sent once, never retried: each link is a new one and counts against the
292
+ * day's twenty, so a retry after a lost answer would spend one on a link
293
+ * nobody was handed. If the answer is lost, ask again when you need one.
294
+ */
295
+ textingNumberInvitation(prefill = {}) {
296
+ return this.#call("POST", "/v1/texting/number/invitations", { prefill }, undefined, { once: true });
297
+ }
277
298
  /* ----------------------------------------------------------- documents */
278
299
  /**
279
300
  * Documents, filtered and paged.
@@ -330,8 +351,13 @@ class SignSealer {
330
351
  }
331
352
  /**
332
353
  * Send one signer a reminder with a fresh link (1.6.0); the one they had
333
- * stops working. Refused inside an hour of their last reminder, and for
354
+ * stops working. Refused (422) inside an hour of their last reminder, past
355
+ * three to one signer or twenty-five for one document in a day, and for
334
356
  * somebody there is no way to reach -- with their link left as it was.
357
+ * A signer is texted one reminder over the life of their link, because
358
+ * that is what they agreed to (00507): after it, a reminder goes by email
359
+ * alone (`by: "email"`), and one with no email address is refused (422).
360
+ * `reminded: true` means it was queued: it is screened before it leaves.
335
361
  */
336
362
  remind(documentId, signerId, idempotencyKey) {
337
363
  return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/remind`, {}, idempotencyKey);
@@ -495,6 +521,14 @@ class SignSealer {
495
521
  addWebhook(input, idempotencyKey) {
496
522
  return this.#call("POST", "/v1/webhooks", input, idempotencyKey);
497
523
  }
524
+ /**
525
+ * Change an endpoint. Turning one back on forgives its failures and sends
526
+ * what it held: `resumed` says it was paused, `waiting` how many are now
527
+ * on their way, and `dropped_while_paused` how many the hold could not
528
+ * keep (00289). `events`, when given, replaces the list and is checked as
529
+ * `addWebhook`'s is: a name that is not an event is refused (422), and the
530
+ * error's `hint` lists every one there is (00507).
531
+ */
498
532
  setWebhook(id, input) {
499
533
  return this.#call("PATCH", `/v1/webhooks/${encodeURIComponent(id)}`, input);
500
534
  }
@@ -641,7 +675,7 @@ class SignSealer {
641
675
  the receiver was still using.
642
676
  */
643
677
  const key = idempotencyKey ??
644
- (method === "GET" || method === "DELETE" || opts.once ? undefined : crypto.randomUUID());
678
+ (method === "GET" || method === "DELETE" || opts.once ? undefined : await randomUuid());
645
679
  let lastError;
646
680
  for (let attempt = 1; attempt <= this.#attempts; attempt++) {
647
681
  let res;
@@ -732,13 +766,26 @@ exports.SignSealer = SignSealer;
732
766
  *
733
767
  * Use this to build your own signing page. If you want ours, send the signer
734
768
  * to `https://api.signsealer.com/s/<token>` and skip all of it.
769
+ *
770
+ * The one exception is a paired tablet's own credential, `deviceKey` (1.11.0),
771
+ * sent on one call only: a signature that carries `captured`. The server keeps
772
+ * an offline signature's claim about when it was taken only from a paired
773
+ * tablet of the business the link belongs to, because that day is the day the
774
+ * document says it was signed, and it asks for the tablet's credential to know
775
+ * it is one. Without it the claim is dropped -- silently, not refused -- and the
776
+ * signature is dated when it arrives. Nothing else here ever sends it.
735
777
  */
736
778
  class SignSealerSigning {
737
779
  #base;
738
780
  #fetch;
781
+ #deviceKey;
739
782
  constructor(opts = {}) {
783
+ if (opts.deviceKey !== undefined && !opts.deviceKey.startsWith("mk_")) {
784
+ throw new Error("a device credential looks like mk_live_… or mk_test_…: the key pairDevice answered");
785
+ }
740
786
  this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
741
787
  this.#fetch = opts.fetch ?? globalThis.fetch;
788
+ this.#deviceKey = opts.deviceKey;
742
789
  }
743
790
  /**
744
791
  * Everything the page needs from one token.
@@ -807,6 +854,12 @@ class SignSealerSigning {
807
854
  * kind `photo`, shrunk on the server, kept encrypted with the document
808
855
  * for as long as the document is kept; the field carries its hash. A
809
856
  * second photograph replaces the first.
857
+ *
858
+ * When the server is reading other photos, or another from this link, it
859
+ * is refused with a 429 `busy` and nothing is kept: the error's
860
+ * `retryable` is true and `retryAfter` says how many seconds to wait
861
+ * (thirty). Show the person its message and send the same photo again
862
+ * then; this client does not wait that long inside a call for you.
810
863
  */
811
864
  supplyPhoto(token, key, image, options = {}) {
812
865
  return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}/fields/${encodeURIComponent(key)}/photo`, {
@@ -851,7 +904,8 @@ class SignSealerSigning {
851
904
  /**
852
905
  * A photo of the ID, or of the person, when the business asked (00339).
853
906
  * Kept encrypted for thirty days, the hash on the trail. Refused when
854
- * the business did not ask.
907
+ * the business did not ask; refused as busy, to be sent again after
908
+ * `retryAfter` seconds, as `supplyPhoto` is.
855
909
  */
856
910
  captureIdEvidence(token, kind, image, captured) {
857
911
  return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}/id-evidence`, {
@@ -860,8 +914,19 @@ class SignSealerSigning {
860
914
  ...(captured ? { captured } : {}),
861
915
  });
862
916
  }
863
- sign(token, method, value, captured) {
864
- return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}`, { method, value, ...(captured ? { captured } : {}) });
917
+ /**
918
+ * Sign. `captured` is for a signature a paired tablet took with no
919
+ * network, and is kept only when the client was built with that tablet's
920
+ * `deviceKey`, which goes with this call and no other; see the class.
921
+ *
922
+ * `paragraphs` (00540) is which of the text's conditional paragraphs your
923
+ * page drew, in order. Required while the first signer's answers still
924
+ * decide them (refused with 422 without it), and refused with 409
925
+ * `paragraphs_changed` when the answers now call for others, so nobody
926
+ * signs a paragraph they were not shown. Kept with the signature.
927
+ */
928
+ sign(token, method, value, captured, paragraphs) {
929
+ return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}`, { method, value, ...(captured ? { captured } : {}), ...(paragraphs ? { paragraphs } : {}) }, captured ? this.#deviceKey : undefined);
865
930
  }
866
931
  decline(token, reason) {
867
932
  return this.#call("POST", `/v1/sign/${encodeURIComponent(token)}/decline`, { reason });
@@ -883,12 +948,16 @@ class SignSealerSigning {
883
948
  second signature the engine correctly declines. Retrying would turn a
884
949
  clear refusal into a confusing one.
885
950
  */
886
- async #call(method, path, body) {
951
+ async #call(method, path, body, deviceKey) {
887
952
  let res;
888
953
  try {
889
954
  res = await this.#fetch(`${this.#base}${path}`, {
890
955
  method,
891
- headers: body === undefined ? {} : { "content-type": "application/json" },
956
+ headers: {
957
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
958
+ /* Only ever `sign` with `captured`, from a client given a tablet's credential. */
959
+ ...(deviceKey ? { authorization: `Bearer ${deviceKey}` } : {}),
960
+ },
892
961
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
893
962
  });
894
963
  }
@@ -901,7 +970,9 @@ class SignSealerSigning {
901
970
  if (res.ok)
902
971
  return parsed;
903
972
  const err = parsed.error;
904
- throw new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId);
973
+ throw new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId,
974
+ /* 1.11.0: how long the server asked for, so a page can say "in half a minute" and try then. */
975
+ waitAsked(res.headers.get("retry-after")));
905
976
  }
906
977
  }
907
978
  exports.SignSealerSigning = SignSealerSigning;
@@ -1127,6 +1198,39 @@ function webCrypto() {
1127
1198
  })();
1128
1199
  return subtlePromise;
1129
1200
  }
1201
+ /**
1202
+ * A fresh idempotency key: a random UUID, from wherever this runtime keeps
1203
+ * one.
1204
+ *
1205
+ * 1.11.1. Every write that did not bring its own key was given one with the
1206
+ * global `crypto.randomUUID()`, which Node 18 does not have unless it was
1207
+ * started with `--experimental-global-webcrypto` -- the same gap
1208
+ * `webCrypto()` above was written for, missed here. So on a plain Node 18,
1209
+ * which this package declares it supports, every such write threw a
1210
+ * `ReferenceError` before it was sent. The global first, then `node:crypto`,
1211
+ * assembled at run time for the reason `webCrypto()` gives.
1212
+ */
1213
+ let uuidPromise = null;
1214
+ function randomUuid() {
1215
+ uuidPromise ??= (async () => {
1216
+ const here = globalThis.crypto;
1217
+ if (typeof here?.randomUUID === "function")
1218
+ return () => here.randomUUID();
1219
+ try {
1220
+ const mod = await Promise.resolve(`${"node:" + "crypto"}`).then(s => __importStar(require(s)));
1221
+ const fallback = mod.randomUUID;
1222
+ if (typeof fallback === "function")
1223
+ return () => fallback();
1224
+ }
1225
+ catch {
1226
+ /* Not Node. The error below is the honest answer. */
1227
+ }
1228
+ throw new Error("no crypto.randomUUID in this runtime, so a write cannot be given an idempotency key"
1229
+ + " — pass your own key, or run where WebCrypto is: every current browser, edge"
1230
+ + " runtime and Node 19 or later has it, and Node 18 reaches it through node:crypto");
1231
+ })();
1232
+ return uuidPromise.then((next) => next());
1233
+ }
1130
1234
  async function hmacSha256(secret, message) {
1131
1235
  const subtle = await webCrypto();
1132
1236
  const enc = new TextEncoder();
@@ -1239,18 +1343,19 @@ function headerOf(headers, name) {
1239
1343
  * signed bytes again with a different id on them, and a receiver keyed on the
1240
1344
  * id will treat the replay as a new event.
1241
1345
  *
1242
- * There is no way to close that from inside this package today, and it is
1243
- * worth saying rather than implying otherwise. A key derived from the signed
1244
- * material — the hash of `timestamp.body` — is authenticated but is *not*
1245
- * stable across retries, because the sender signs a fresh timestamp on every
1246
- * attempt; this SDK briefly returned one, which deduplicated replays and broke
1247
- * ordinary retries, which is the worse failure of the two. The fix is to bring
1248
- * the id inside the signature under a `v2=` scheme, and that is a change to
1249
- * the wire rather than to this file.
1346
+ * A key derived from `timestamp.body` is authenticated but is *not* stable
1347
+ * across retries, because the sender signs a fresh timestamp on every attempt;
1348
+ * this SDK briefly returned one, which deduplicated replays and broke ordinary
1349
+ * retries, which is the worse failure of the two. A SHA-256 of the body alone
1350
+ * is both: the signature covers the body, and a delivery's body is built once
1351
+ * and sent unchanged on every retry. That is what the WordPress plugin keys on
1352
+ * (1.14.4). What it cannot tell apart is a replay a person asked for
1353
+ * (`replayWebhookDelivery`), which sends the same body under a new id. The
1354
+ * whole fix is to bring the id inside the signature under a `v2=` scheme,
1355
+ * and that is a change to the wire rather than to this file.
1250
1356
  *
1251
- * Until then: deduplicate on `eventId`, and if a replay inside a five-minute
1252
- * window would be harmful to your system, check the event's own contents
1253
- * against your records before acting on it.
1357
+ * Until then: deduplicate on `eventId`, or on a hash of the raw body when a
1358
+ * replay inside a five-minute window would be harmful to your system.
1254
1359
  */
1255
1360
  async function verifyWebhookRequest(opts) {
1256
1361
  const result = await verifyWebhook({