@signsealer/sdk 1.4.0 → 1.10.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,5 +1,169 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ### Added
6
+
7
+ - `SigningField.from_sender` (00437). A box on an uploaded PDF that whoever
8
+ sent the document filled in: already answered, shown and never asked for.
9
+ - `SigningField.placed_words` (00438). What a placed box shows: a date or a
10
+ time in words, beside `placed_value`, which stays the answer.
11
+ - `PartnerProfile.review`, `PartnerProfile.earning` and
12
+ `PartnerProfile.earning_since` (00451). A partner account that enrolled
13
+ itself is reviewed by a person before its share starts: `review` is
14
+ `pending` until then, businesses are attributed meanwhile, and nothing
15
+ accrues until `earning` is true, counted from `earning_since`.
16
+ - `Account.texting` (00458): whether the business can text people, why
17
+ not when it cannot (`plan` or `test`), and the opt-in sentence to put
18
+ beside a "text me" box and record with `recordSmsConsent` when ticked.
19
+ - `PartnerBusiness.source` can be `promotion`: a business that redeemed a
20
+ promotion code the partner handed out (00421).
21
+
22
+ ## 1.10.0
23
+
24
+ ### Added
25
+
26
+ - `SigningField.at_signing` and `SigningField.placed_value` (00427). A
27
+ signature box or a signing-date box placed on an uploaded PDF is filled by
28
+ signing itself -- the signature as typed, and the day it was signed in the
29
+ business's timezone -- so a signing page draws those boxes rather than
30
+ asking for them, and `sign()` no longer refuses for them.
31
+ `placed_value` is what a box on the page carries, for showing the
32
+ document as it will be sealed.
33
+ - `TemplateSettings.photos_in_copy`, and `photos_in_copy` on
34
+ `setTemplateSettings` (00428). The photographs a signer takes as answers
35
+ are printed on pages after the certificate in the signed PDF, each with
36
+ its question, when it was taken and its SHA-256, under the same seal. On
37
+ unless turned off; the certificate keeps every hash either way.
38
+
39
+ ## 1.9.0
40
+
41
+ ### Added
42
+
43
+ - `startPacket(packetId)` (00424): starts everything a packet still owes.
44
+ Items already started are left alone, so it is safe on every booking
45
+ update; one that cannot be started comes back under `skipped` with the
46
+ reason. Type `PacketStart`.
47
+ - `voidPacket(packetId, reason)`: the booking was cancelled. What nobody has
48
+ finished is voided; what somebody signed is kept and counted.
49
+ - `integrations()` and `integrationEvents(connectionId)`: the booking systems
50
+ this business can connect and its connections, and what arrived from one
51
+ and what became of it. Credentials and a connection's address are never
52
+ returned. Types `IntegrationProvider`, `IntegrationConnection`,
53
+ `IntegrationEvent`.
54
+ - `integrations()` also answers `needs_membership`, true on Free, because
55
+ connecting a booking system comes with the membership (00425); and each
56
+ connection carries `paused_reason`, `membership` when it was paused because
57
+ the membership ended. Such a connection resumes by itself when the
58
+ membership starts again.
59
+
60
+ ## 1.8.0
61
+
62
+ ### Added
63
+
64
+ - `SignSealerPartner` (00418): a partner reading its own revenue share, with
65
+ its OAuth client id and secret by HTTP Basic. `profile()` (the share,
66
+ custom branding and its monthly fee, businesses brought, this month so far,
67
+ and `signup_url`), `businesses({ limit, offset })` and `statements()`.
68
+ Read-only; every call is retried on a transient failure. A business's API
69
+ key is refused by the constructor.
70
+ - `SignSealerPartner.signupUrl(code)`: the partner's signup link, built
71
+ without a call.
72
+ - Types `PartnerProfile`, `PartnerMonthToDate`, `PartnerBusiness`,
73
+ `PartnerStatement` and `PartnerOptions`.
74
+
75
+ ## 1.7.0
76
+
77
+ ### Added
78
+
79
+ - `DocumentSigners.link_allowed` (00409): whether `gateLink` will mint a link
80
+ for this caller. Always true for a key; for a paired tablet, only on a
81
+ document it or its form started, unless the business let that tablet show
82
+ links for every open document.
83
+ - `Device.hand_off` and `Device.gate`, and `setDevice(id, { hand_off, gate })`.
84
+ `gate` is `own` (the default) or `account`.
85
+ - `Account.mode` (00413): `test` for a test key (`mk_test_`), which acts on
86
+ the business's sandbox, where nothing is sent to anybody and nothing is
87
+ billed. Nothing changes in how the client is used: a test key is a key.
88
+ - `restoreTemplate(id, { change_note })` (00412): an older published version
89
+ back as a new draft at the top, with its text, questions, consent wording
90
+ and file.
91
+ - `change_note` on `editTemplate` and `reviseTemplate`, and on
92
+ `TemplateDetail` and each of its `versions`, with each version's `name`,
93
+ `created_at`, `has_pdf` and `documents`.
94
+
95
+ ### Changed
96
+
97
+ - A tablet added from now on starts with `gate: "own"`: `gateLink` from it is
98
+ refused with 403 for a document it did not start and its form did not
99
+ start, until the business sets `gate: "account"`. Tablets paired before
100
+ keep `account`, so nothing that worked stops working. A link a tablet
101
+ shows is one whoever holds it could open.
102
+
103
+ ## 1.6.0
104
+
105
+ ### Added
106
+
107
+ Templates, all the way through (00408). Until now the client could create a
108
+ draft and nothing else, so a template made from your own software could not
109
+ be sent until somebody published it in the dashboard.
110
+
111
+ - `template(id)` -- one version whole: `body`, `body_format`, `variables`,
112
+ `consent_text`, `fields`, `settings`, and `versions`, every version of its
113
+ code newest first.
114
+ - `templates({ code })` -- one template's versions.
115
+ - `editTemplate(id, …)` -- change a draft. A published version refuses.
116
+ - `publishTemplate(id)` -- publish a draft.
117
+ - `reviseTemplate(id, …)` -- the next version of a published template, as a
118
+ draft. `id` must be the newest version; an older one is a 409 naming it.
119
+ - `discardTemplate(id)` -- throw away a draft nothing was made from.
120
+ - `setTemplateSettings(id, …)` -- `one_time`, `show_address`,
121
+ `valid_months`, `remind_days`, and `resign`.
122
+
123
+ Documents:
124
+
125
+ - `prepareDocument` takes `external_ref`, `metadata` and `return_url`.
126
+ Webhooks carry the reference back as `document.metadata.external_ref`, and
127
+ `documents({ external_ref })` finds it.
128
+ - `documents()` answers `has_more`, `limit` and `offset` beside `total`.
129
+ - `send` takes `delivery: "embedded"` for a signer you show the page to
130
+ yourself: nothing is emailed or texted to them, and the automatic
131
+ reminders leave them alone. Each link now carries `url`.
132
+ - `remind(documentId, signerId)` sends a signer a fresh link.
133
+ - `embedLink(documentId, signerId)` mints a fresh link to put in an
134
+ `<iframe>`, with `frame_origins`, the sites it may be framed on. The page
135
+ posts an `EmbedEvent` to its parent: `ready`, `signed`, `declined`.
136
+ - `Account.frame_origins`.
137
+
138
+ ### Fixed
139
+
140
+ Retries. The client minted an idempotency key for every write and retried
141
+ every one after a lost response or a 5xx, but the server only honours keys
142
+ on the writes that create things. On the others a retry did the work twice.
143
+ The worst case was `rotateWebhookSecret`: two rotations drop the secret your
144
+ receiver is still using. `rotateWebhookSecret`, `replayWebhookDelivery`,
145
+ `pairDevice`, `addDevice`, `reportProblem` and `gateLink` are now sent once
146
+ after an ambiguous failure. A 429, which says nothing happened, is still
147
+ waited out.
148
+
149
+ ## 1.5.0
150
+
151
+ ### Added
152
+
153
+ `standing({ template, email?, phone? })` asks `GET /v1/standing` (00406)
154
+ whether a person's signature on a template is still good: their newest
155
+ completed signature on any version of it, with `standing` -- `current`,
156
+ `expired`, `resign` (signed on a version the business has since asked
157
+ everybody to sign again) or `on_file` (the template has no period) -- and
158
+ `valid_until`. `found: false` means they have never signed it.
159
+
160
+ `DocumentRow`, `DocumentSigners` and `DocumentDetail` declare `standing`
161
+ and `valid_until`, which the server now sends on a signed document, and
162
+ `DocumentDetail` declares `renewed_by`: the newer signing by the same
163
+ person that replaced it. `Template` declares `valid_months`,
164
+ `remind_days` and `resign_from_version`. The `Standing` and
165
+ `PersonStanding` types name them.
166
+
3
167
  ## 1.4.0
4
168
 
5
169
  Types and documentation; no request the client sends changed. 1.3.0 was
@@ -49,10 +213,10 @@ existed.
49
213
 
50
214
  ## 1.3.0
51
215
 
52
- The first version on npm since 1.0.0. 1.0.1 and 1.2.0 were tagged while
53
- the publish workflow was not running, so the entries below this one
54
- describe changes that never reached the registry; installing 1.3.0 gets
55
- all of them.
216
+ Meant as the first version on npm since 1.0.0, and never published: its tag,
217
+ like 1.0.1's and 1.2.0's, was pushed while the publish workflow was not
218
+ running, so this entry and the ones below it describe changes that first
219
+ reached the registry in 1.4.0, which carries all of them.
56
220
 
57
221
  ### Added
58
222
 
package/README.md CHANGED
@@ -72,6 +72,12 @@ back when the billing period turns, and no amount of backing off will reach it.
72
72
  Subscribe to `billing.quota_approaching` if you would rather hear about it
73
73
  before the call that fails.
74
74
 
75
+ On the membership, which is paid from prepaid credit, the count is the
76
+ month's free signings left plus the signings the balance still covers, and a
77
+ `402` there clears as soon as credit is added or an automatic reload lands,
78
+ not only when the month turns; on Free, starting the membership clears it
79
+ too. `error.hint` says which case it is.
80
+
75
81
  ```ts
76
82
  try {
77
83
  await signsealer.send(documentId, signers);
@@ -313,9 +319,10 @@ const { template_id } = await client.createTemplate({
313
319
  ```
314
320
 
315
321
  Version 1, as a **draft**. A template is not usable until it is published, and
316
- publishing is what freezes the text people will have signed — so there is no
317
- `publish` method here on purpose. That is a decision somebody makes looking at
318
- the words.
322
+ publishing is what freezes the text people will have signed. That is a decision
323
+ somebody makes looking at the words: `editTemplate(template_id, …)` changes the
324
+ draft until then, `publishTemplate(template_id)` publishes it, and
325
+ `reviseTemplate` makes the next version as a draft afterwards.
319
326
 
320
327
  Questions can be grouped, asked only when an earlier answer says so, and
321
328
  flagged for a person to read:
@@ -366,6 +373,43 @@ changed since it was issued. That is reported and never corrected — a
366
373
  verification service that quietly re-derived could not answer the one question
367
374
  it exists for.
368
375
 
376
+ ## For partners: what you have earned
377
+
378
+ A platform SignSealer has enrolled as a partner shares in the revenue of every
379
+ business it brings, for as long as that business pays. A business is yours
380
+ when it signs up through your link, installs your app in its first weeks, or
381
+ redeems a promotion code made for you; a business your own people own is not.
382
+ `SignSealerPartner` reads it, with your OAuth client's id and secret, never a
383
+ business's key:
384
+
385
+ ```ts
386
+ import { SignSealerPartner } from "@signsealer/sdk";
387
+
388
+ const partner = new SignSealerPartner({
389
+ clientId: process.env.SIGNSEALER_CLIENT_ID!,
390
+ clientSecret: process.env.SIGNSEALER_CLIENT_SECRET!,
391
+ });
392
+
393
+ const me = await partner.profile();
394
+ // { referral_code: "deckpos", businesses: 12,
395
+ // month_to_date: { revenue_cents: 41250, share_cents: …, … },
396
+ // signup_url: "https://app.signsealer.com/signup?partner=deckpos" }
397
+
398
+ const { data, has_more } = await partner.businesses({ limit: 100 });
399
+ const months = await partner.statements(); // every closed month, newest first
400
+
401
+ SignSealerPartner.signupUrl("deckpos"); // the same link, without a call
402
+ ```
403
+
404
+ It only reads. Your share and programme come from your partner agreement, and
405
+ a month's statement is written once, when the month is over; `paid` turns true
406
+ when the payment is recorded. A partner account that enrolled itself is looked
407
+ at by a person first: `review` is `pending` until then, businesses are recorded
408
+ as yours meanwhile, and nothing accrues until `earning` is true, counted from
409
+ `earning_since`. The revenue shared is what a business paid for
410
+ and used, after card fees and the carrier's cost of its texts; credit
411
+ SignSealer gave away earns nothing.
412
+
369
413
  ## Options
370
414
 
371
415
  ```ts
@@ -49,10 +49,9 @@ var __importStar = (this && this.__importStar) || (function () {
49
49
  };
50
50
  })();
51
51
  Object.defineProperty(exports, "__esModule", { value: true });
52
- exports.WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_SIGNATURE_HEADER = exports.WEBHOOK_TIMESTAMP_HEADER = exports.WEBHOOK_EVENT_HEADER = exports.SignSealerSigning = exports.SignSealer = exports.SignSealerError = void 0;
52
+ exports.WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_SIGNATURE_HEADER = exports.WEBHOOK_TIMESTAMP_HEADER = exports.WEBHOOK_EVENT_HEADER = exports.SignSealerPartner = exports.SignSealerSigning = exports.SignSealer = exports.SignSealerError = void 0;
53
53
  exports.verifyWebhook = verifyWebhook;
54
54
  exports.verifyWebhookRequest = verifyWebhookRequest;
55
- /* ------------------------------------------------------------------ errors */
56
55
  class SignSealerError extends Error {
57
56
  status;
58
57
  code;
@@ -150,10 +149,62 @@ class SignSealer {
150
149
  return this.#call("GET", "/v1/account");
151
150
  }
152
151
  /* ----------------------------------------------------------- templates */
153
- async templates() {
154
- const { templates } = await this.#call("GET", "/v1/templates");
152
+ /** Every version of every template, newest first; `code` narrows it to one template's versions. No text: `template(id)` has that. */
153
+ async templates(filter = {}) {
154
+ const { templates } = await this.#call("GET", filter.code ? `/v1/templates?code=${encodeURIComponent(filter.code)}` : "/v1/templates");
155
155
  return templates;
156
156
  }
157
+ /** One template version, whole: text, questions, settings, and every version of its code (1.6.0). */
158
+ template(id) {
159
+ return this.#call("GET", `/v1/templates/${encodeURIComponent(id)}`);
160
+ }
161
+ /**
162
+ * Change a draft (1.6.0). `fields`, when given, replaces the whole list.
163
+ * A published version refuses: what people signed does not change, so
164
+ * make the next version with `reviseTemplate`.
165
+ */
166
+ editTemplate(id, input) {
167
+ return this.#call("PATCH", `/v1/templates/${encodeURIComponent(id)}`, input);
168
+ }
169
+ /**
170
+ * Publish a draft (1.6.0): from now on documents made from its code use
171
+ * this version, and its text can no longer change. Refused, naming what
172
+ * is wrong, for a placeholder the template does not declare or a PDF with
173
+ * pages nobody has drawn.
174
+ */
175
+ publishTemplate(id, idempotencyKey) {
176
+ return this.#call("POST", `/v1/templates/${encodeURIComponent(id)}/publish`, {}, idempotencyKey);
177
+ }
178
+ /**
179
+ * The next version of a published template, as a draft (1.6.0): the
180
+ * newest version copied, with whatever you change. `id` must be the
181
+ * newest version; an older one answers 409 naming the newest. Documents
182
+ * already sent keep the version they were sent on.
183
+ */
184
+ reviseTemplate(id, input = {}, idempotencyKey) {
185
+ return this.#call("POST", `/v1/templates/${encodeURIComponent(id)}/revise`, input, idempotencyKey);
186
+ }
187
+ /**
188
+ * An older published version back as a new draft at the top (1.7.0): its
189
+ * text, questions, consent wording and file. Its `change_note` says
190
+ * "Restored from version N", and yours after it. Refused for the newest
191
+ * version, a draft, and while the template has an open draft.
192
+ */
193
+ restoreTemplate(id, input = {}, idempotencyKey) {
194
+ return this.#call("POST", `/v1/templates/${encodeURIComponent(id)}/restore`, input, idempotencyKey);
195
+ }
196
+ /** Throw away a draft nothing was made from (1.6.0). A published version is never discarded. */
197
+ discardTemplate(id) {
198
+ return this.#call("DELETE", `/v1/templates/${encodeURIComponent(id)}`);
199
+ }
200
+ /**
201
+ * The settings a template's code carries to every version (1.6.0).
202
+ * `resign: true` asks everybody who signed an older version to sign the
203
+ * newest published one; `valid_months: null` clears the period.
204
+ */
205
+ setTemplateSettings(id, input) {
206
+ return this.#call("PATCH", `/v1/templates/${encodeURIComponent(id)}/settings`, input);
207
+ }
157
208
  /**
158
209
  * Whether a template is an uploaded PDF, and whether it is usable yet.
159
210
  *
@@ -166,9 +217,9 @@ class SignSealer {
166
217
  * Create a template. Version 1, as a draft.
167
218
  *
168
219
  * A template is not usable until it is published, and publishing is what
169
- * freezes the text people will have signed — so this is deliberately the
170
- * *draft* door and there is no `publish` beside it. Publishing is a
171
- * decision somebody makes looking at the words, in the dashboard.
220
+ * freezes the text people will have signed. Publish it with
221
+ * `publishTemplate` once the words are right -- in the dashboard, or from
222
+ * here when your own software is where the words are decided (1.6.0).
172
223
  *
173
224
  * `fields` says what the document asks for besides a signature, and is
174
225
  * set in the same call rather than in a second one: a template that
@@ -255,6 +306,19 @@ class SignSealer {
255
306
  documentSigners(id) {
256
307
  return this.#call("GET", `/v1/documents/${encodeURIComponent(id)}/signers`);
257
308
  }
309
+ /**
310
+ * Does this person have a current signature on this template (00406)? By
311
+ * the template's code and the person's email or phone. `found: false` is
312
+ * "send them the form", not an error.
313
+ */
314
+ standing(who) {
315
+ const q = new URLSearchParams({ template: who.template });
316
+ if (who.email)
317
+ q.set("email", who.email);
318
+ if (who.phone)
319
+ q.set("phone", who.phone);
320
+ return this.#call("GET", `/v1/standing?${q}`);
321
+ }
258
322
  /**
259
323
  * A fresh signing link for a signer who has not signed, as a QR code to
260
324
  * hold up (00340). The link they were sent stops working; the trail says
@@ -262,7 +326,24 @@ class SignSealer {
262
326
  * declined, a copied recipient, or a document that is not open.
263
327
  */
264
328
  gateLink(documentId, signerId) {
265
- return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/link`, {});
329
+ return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/link`, {}, undefined, { once: true });
330
+ }
331
+ /**
332
+ * 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
334
+ * somebody there is no way to reach -- with their link left as it was.
335
+ */
336
+ remind(documentId, signerId, idempotencyKey) {
337
+ return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/remind`, {}, idempotencyKey);
338
+ }
339
+ /**
340
+ * A fresh signing link to put in an `<iframe>` (1.6.0), with the sites it
341
+ * may be framed on. Call it when the page is about to be shown rather than
342
+ * keeping a link; the one the signer had stops working. Inside the frame
343
+ * the page posts an `EmbedEvent` to its parent.
344
+ */
345
+ embedLink(documentId, signerId) {
346
+ return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/embed`, {});
266
347
  }
267
348
  prepareDocument(input, idempotencyKey) {
268
349
  return this.#call("POST", "/v1/documents", input, idempotencyKey);
@@ -380,6 +461,33 @@ class SignSealer {
380
461
  startPacketItem(itemId, idempotencyKey) {
381
462
  return this.#call("POST", `/v1/packets/items/${encodeURIComponent(itemId)}/start`, undefined, idempotencyKey);
382
463
  }
464
+ /**
465
+ * Start everything a packet still owes (00424). Items already started are
466
+ * left alone, so this is safe to call on every booking update; an item
467
+ * that cannot be started comes back under `skipped` with the reason.
468
+ */
469
+ startPacket(packetId) {
470
+ return this.#call("POST", `/v1/packets/${encodeURIComponent(packetId)}/start`);
471
+ }
472
+ /**
473
+ * Void a packet because the booking was cancelled (00424): what nobody has
474
+ * finished is voided with the reason, what somebody signed is kept.
475
+ */
476
+ voidPacket(packetId, reason) {
477
+ return this.#call("POST", `/v1/packets/${encodeURIComponent(packetId)}/void`, { reason });
478
+ }
479
+ /* -------------------------------------------------------- integrations */
480
+ /**
481
+ * The booking systems this business can connect, and its connections (00424).
482
+ * `needs_membership` is true on Free: connecting one comes with the membership (00425).
483
+ */
484
+ integrations() {
485
+ return this.#call("GET", "/v1/integrations");
486
+ }
487
+ /** What arrived from one connection and what became of it, newest first. */
488
+ integrationEvents(connectionId) {
489
+ return this.#call("GET", `/v1/integrations/${encodeURIComponent(connectionId)}/events`);
490
+ }
383
491
  /* ------------------------------------------------------------ webhooks */
384
492
  webhooks() {
385
493
  return this.#call("GET", "/v1/webhooks");
@@ -406,7 +514,7 @@ class SignSealer {
406
514
  * with it will not verify.
407
515
  */
408
516
  rotateWebhookSecret(id) {
409
- return this.#call("POST", `/v1/webhooks/${encodeURIComponent(id)}/rotate`);
517
+ return this.#call("POST", `/v1/webhooks/${encodeURIComponent(id)}/rotate`, undefined, undefined, { once: true });
410
518
  }
411
519
  /**
412
520
  * An endpoint's last fifty deliveries, newest first.
@@ -427,7 +535,7 @@ class SignSealer {
427
535
  * way to send the same event five times.
428
536
  */
429
537
  replayWebhookDelivery(deliveryId, idempotencyKey) {
430
- return this.#call("POST", `/v1/webhooks/deliveries/${encodeURIComponent(deliveryId)}/replay`, undefined, idempotencyKey);
538
+ return this.#call("POST", `/v1/webhooks/deliveries/${encodeURIComponent(deliveryId)}/replay`, undefined, idempotencyKey, { once: true });
431
539
  }
432
540
  /* ------------------------------------------------------------- devices */
433
541
  /**
@@ -445,7 +553,7 @@ class SignSealer {
445
553
  * apart tells a guesser whether they are warm.
446
554
  */
447
555
  pairDevice(input) {
448
- return this.#call("POST", "/v1/devices/pair", input);
556
+ return this.#call("POST", "/v1/devices/pair", input, undefined, { once: true });
449
557
  }
450
558
  /**
451
559
  * Tablets, from your own software (00335).
@@ -460,7 +568,7 @@ class SignSealer {
460
568
  }
461
569
  /** Add a tablet. The pairing code comes back once and never again. */
462
570
  addDevice(input) {
463
- return this.#call("POST", "/v1/devices", input);
571
+ return this.#call("POST", "/v1/devices", input, undefined, { once: true });
464
572
  }
465
573
  /** A new code for a tablet; any tablet paired to it stops the moment the code is made. */
466
574
  newDeviceCode(id) {
@@ -508,17 +616,32 @@ class SignSealer {
508
616
  * customer's name ends up. Thirty an hour per tablet.
509
617
  */
510
618
  reportProblem(input) {
511
- return this.#call("POST", "/v1/devices/report", input);
619
+ return this.#call("POST", "/v1/devices/report", input, undefined, { once: true });
512
620
  }
513
621
  /* ------------------------------------------------------------ the wire */
514
- async #call(method, path, body, idempotencyKey) {
622
+ async #call(method, path, body, idempotencyKey,
623
+ /**
624
+ * `once`: a write the server does not de-duplicate and that must not
625
+ * happen twice -- rotating a secret, adding a tablet, pairing, a replay,
626
+ * a report, the gate's link. It is never repeated after an answer that
627
+ * leaves us not knowing whether it happened (no response, or a 5xx); a
628
+ * refusal that says it did not happen (429) is still waited out.
629
+ */
630
+ opts = {}) {
515
631
  /*
516
632
  A retry without a key can create a second document, so one is minted for
517
633
  any write that did not bring its own. That is the difference between a
518
634
  client that is safe to retry and a client that is merely willing to.
635
+
636
+ Not for a `once` write: the server does not keep keys on those routes,
637
+ and sending one would suggest a protection that is not there. That is
638
+ the mistake 1.6.0 fixes -- this client minted a key for every POST and
639
+ retried every one, and on the routes that ignore keys a lost answer to
640
+ "rotate my webhook secret" became two rotations, dropping the secret
641
+ the receiver was still using.
519
642
  */
520
643
  const key = idempotencyKey ??
521
- (method === "GET" || method === "DELETE" ? undefined : crypto.randomUUID());
644
+ (method === "GET" || method === "DELETE" || opts.once ? undefined : crypto.randomUUID());
522
645
  let lastError;
523
646
  for (let attempt = 1; attempt <= this.#attempts; attempt++) {
524
647
  let res;
@@ -538,7 +661,7 @@ class SignSealer {
538
661
  // we cannot know whether the server did the work, so we retry with
539
662
  // the same key and let it tell us.
540
663
  lastError = new SignSealerError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer", undefined, undefined);
541
- if (attempt < this.#attempts) {
664
+ if (attempt < this.#attempts && !opts.once) {
542
665
  await sleep(backoff(attempt));
543
666
  continue;
544
667
  }
@@ -566,7 +689,9 @@ class SignSealer {
566
689
  .error;
567
690
  const askedFor = waitAsked(res.headers.get("retry-after"));
568
691
  lastError = new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId, askedFor);
569
- if (lastError.retryable && attempt < this.#attempts) {
692
+ /* A 5xx on a `once` write may have done the work; only a refusal that says it did not is waited out. */
693
+ const mayRepeat = !opts.once || res.status === 429;
694
+ if (lastError.retryable && mayRepeat && attempt < this.#attempts) {
570
695
  /*
571
696
  When the server said how long, wait that long rather than guessing.
572
697
 
@@ -780,6 +905,94 @@ class SignSealerSigning {
780
905
  }
781
906
  }
782
907
  exports.SignSealerSigning = SignSealerSigning;
908
+ /**
909
+ * A partner reading its own revenue share (1.8.0): the businesses it brought,
910
+ * what they have paid this month, and every closed month's statement.
911
+ *
912
+ * Authenticated with the partner's OAuth client id and secret, by HTTP Basic
913
+ * -- never with a business's API key or access token, which act as one
914
+ * business. Only a partner SignSealer has enrolled can use it, and it only
915
+ * reads: the share and the programme are set by SignSealer, from the signed
916
+ * agreement. Keep the secret on a server.
917
+ */
918
+ class SignSealerPartner {
919
+ #auth;
920
+ #base;
921
+ #attempts;
922
+ #fetch;
923
+ constructor(opts) {
924
+ if (!opts?.clientId || !opts?.clientSecret) {
925
+ throw new Error("a partner client needs its clientId and clientSecret");
926
+ }
927
+ if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
928
+ throw new Error("that is a business's API key; the partner API takes your OAuth client id and secret");
929
+ }
930
+ const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
931
+ this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
932
+ this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
933
+ this.#attempts = Math.max(1, opts.maxAttempts ?? 3);
934
+ this.#fetch = opts.fetch ?? globalThis.fetch;
935
+ }
936
+ /**
937
+ * The link to hand a business, from your referral code, without a call.
938
+ * `profile().signup_url` is the same link.
939
+ */
940
+ static signupUrl(referralCode, appOrigin = "https://app.signsealer.com") {
941
+ return `${withoutTrailingSlashes(appOrigin)}/signup?partner=${encodeURIComponent(referralCode)}`;
942
+ }
943
+ /** Your programme, this month so far, and your signup link. */
944
+ profile() {
945
+ return this.#get("/v1/partner");
946
+ }
947
+ /** The businesses you brought, newest first. `limit` is 1 to 200, 50 when left out. */
948
+ businesses(opts = {}) {
949
+ const q = new URLSearchParams();
950
+ if (opts.limit !== undefined)
951
+ q.set("limit", String(opts.limit));
952
+ if (opts.offset !== undefined)
953
+ q.set("offset", String(opts.offset));
954
+ const qs = q.toString();
955
+ return this.#get(`/v1/partner/businesses${qs ? `?${qs}` : ""}`);
956
+ }
957
+ /** Every closed month, newest first. */
958
+ async statements() {
959
+ const out = await this.#get("/v1/partner/statements");
960
+ return out.data;
961
+ }
962
+ /*
963
+ Every call only reads, so a transient failure is retried as it is: there
964
+ is nothing a second GET could do twice.
965
+ */
966
+ async #get(path) {
967
+ for (let attempt = 1;; attempt += 1) {
968
+ let res;
969
+ try {
970
+ res = await this.#fetch(`${this.#base}${path}`, {
971
+ method: "GET",
972
+ headers: { authorization: this.#auth, accept: "application/json" },
973
+ });
974
+ }
975
+ catch (cause) {
976
+ if (attempt < this.#attempts) {
977
+ await sleep(backoff(attempt));
978
+ continue;
979
+ }
980
+ throw new SignSealerError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer", undefined, undefined);
981
+ }
982
+ const requestId = res.headers.get("x-request-id") ?? undefined;
983
+ const text = await res.text();
984
+ const parsed = text ? safeJson(text) : {};
985
+ if (res.ok)
986
+ return parsed;
987
+ const err = parsed.error;
988
+ const failure = new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId, waitAsked(res.headers.get("retry-after")));
989
+ if (!failure.retryable || attempt >= this.#attempts)
990
+ throw failure;
991
+ await sleep(backoff(attempt));
992
+ }
993
+ }
994
+ }
995
+ exports.SignSealerPartner = SignSealerPartner;
783
996
  /**
784
997
  * `Retry-After`, as seconds, when it is a number we believe.
785
998
  *