@signsealer/sdk 1.22.0 → 1.26.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,163 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.26.0
4
+
5
+ Everything that worked in 1.25.0 still compiles and works, with three
6
+ exceptions the API made for security (Changed, below): two on a retry with
7
+ the same idempotency key, and what an app a business connected is told about
8
+ its texting number. One of them narrows a type: `addWebhook`'s `secret` is
9
+ now `string | null`.
10
+
11
+ ### Added
12
+
13
+ - More screens in `embedSession(id, { user, components })`: `components` may
14
+ name `send` (00789), the Send screen, to send from one of the business's
15
+ templates or hand the signing links back to your page; `templates` (00791),
16
+ the business's templates, written and edited in the dashboard's editor
17
+ inside your page and published by an `admin`; and `settings` and `texting`
18
+ (00792), the business's brand, delivery and reminders, and its texting
19
+ number, set and applied for by an `admin`. 1.25.0 took `documents` only.
20
+ The browser package `@signsealer/embed` mounts any of them on your page.
21
+ - `settings()` and `updateSettings(changes)` (00792): a business's brand (the
22
+ name, colours, sender name, reply-to address and logo its signers see), who
23
+ sends its signing links, and its reminders; changed only by a partner for a
24
+ business it manages, through `partner.business(id)`. Typed as `Settings`
25
+ and `SettingsChanges`.
26
+ - `textingNumber()` and `applyForTextingNumber(application)` (00792): the
27
+ business's own texting number, where its application has got to and the
28
+ carriers' wording, as data; and, for a business a partner manages, its
29
+ application for a toll-free or a local number, filed by the partner. Typed
30
+ as `TextingNumberState` and `TextingNumberApplication`.
31
+ - `body_format` on `createTemplate()` (`TemplateInput`, 00791): `markdown`
32
+ writes a template with formatting from its first version, rather than
33
+ switching it after.
34
+ - PDF templates through the API (14 November 2026): `createPdfTemplate({
35
+ name, filename, pdf, kind?, code? })` makes a draft from the file, as the
36
+ dashboard's upload does -- read, sanitised and drawn, its signature, date
37
+ and other boxes put where the file asks for them -- and answers with the
38
+ template, its pages and what was found (`PdfTemplate`). `templateFields(id)`
39
+ lists a draft's questions and boxes with its pages (`TemplateFields`,
40
+ `TemplatePage`), `setTemplateFields(id, fields, { fieldsVersion? })`
41
+ replaces them whole, and `templatePage(id, n)` is a page's picture as PNG
42
+ bytes. `fields_version` on `TemplateFields` names the list; given back as
43
+ `fieldsVersion`, a save made after the list changed (a box SignSealer
44
+ placed on a scan, another person's save) is refused with 409 `stale`
45
+ instead of undoing it.
46
+ - `warnings` on what `publishTemplate` answers: `nothing_placed`, a PDF
47
+ template nobody can sign where it is.
48
+ - `redacted` on `SignerLink`, `links_redacted` on `send`'s answer and on
49
+ `StartedWorkflow`, and `AddedWebhook` (`redacted`, `secrets_redacted`) for
50
+ what `addWebhook` answers: the types of the two security changes below.
51
+ - The client refuses a secret key in a web page: a `SignSealer` built with an
52
+ API key or a partner key, or any `SignSealerPartner`, throws in a browser
53
+ page and says to keep the key on your server and use `@signsealer/embed`
54
+ to show SignSealer's screens in a page. Node, Deno, Bun, edge runtimes and
55
+ workers are unaffected, and so are `SignaturePad`, `verifyWebhook` and a
56
+ client with no key (`pairDevice`).
57
+
58
+ ### Changed (security)
59
+
60
+ - A retry of `send`, `startWorkflow` or `startPacketItem` with the same
61
+ idempotency key -- the client's own, after a connection dropped, or yours --
62
+ still sends and starts nothing twice, and now answers without the signing
63
+ links: each `token` and `url` is null, the link is marked `redacted: true`
64
+ and the answer `links_redacted: true` (the API, 14 November 2026). The API
65
+ keeps a link only as its hash, and the copy of an answer it keeps for a
66
+ retry used to hold them whole. To show a signer whose link was lost, mint a
67
+ fresh one with `embedLink`. This is the API's behaviour, whichever version
68
+ of the client asks.
69
+ - A retry of `addWebhook` with the same idempotency key still adds nothing,
70
+ and now answers without the endpoint's signing secret: `secret` is null,
71
+ with `redacted: true` and `secrets_redacted: true` (the API, 14 November
72
+ 2026). The copy of an answer the API kept for a retry used to hold the
73
+ secret whole, and whoever holds it can forge deliveries. `addWebhook` now
74
+ answers `AddedWebhook`, whose `secret` is `string | null`: code that
75
+ assigned it to a `string` needs a check. Keep the secret from the first
76
+ answer; if it was lost, `rotateWebhookSecret`.
77
+ - A connected app no longer sees a business's texting number or the
78
+ carriers' reason (the API, 16 November 2026). `account().texting.number`,
79
+ and `texting.application`'s `phone` and `reason`, are null to an app the
80
+ business connected and to a tablet; it is told the application's `status`
81
+ and `kind`. The business's own API key, and a partner for a business it
82
+ manages, see them as before, as `textingNumber()` already decided. The
83
+ `texting.number_updated` webhook is told the same way: `phone` and
84
+ `reason` are null at a partner's endpoint on a business that only
85
+ connected its app. The types were already `string | null`. This is the API's behaviour, whichever
86
+ version of the client asks.
87
+
88
+ ## 1.25.0
89
+
90
+ Nothing that worked before changes.
91
+
92
+ ### Added
93
+
94
+ - The client says what it is: `User-Agent: signsealer-sdk/<version> (node)` on
95
+ every call a `SignSealer` or `SignSealerPartner` client makes from a server,
96
+ so a request can be traced to the library and version that sent it.
97
+ `userAgent` in the client's options names your own integration instead, and
98
+ `""` sends none. Nothing is sent from a browser, which sets its own.
99
+ `SDK_VERSION` is exported.
100
+
101
+ - For a partner on a Platform agreement (00751), on `SignSealerPartner`:
102
+ `createBusiness()` makes a business of your own (its terms acceptance as
103
+ you took it is required; with an `external_id` it is safe to retry, and one
104
+ already made comes back with `existing: true`), `managedBusinesses()`,
105
+ `managedBusiness(id)` and `updateBusiness(id, changes)`.
106
+ - `partnerKey` on `SignSealerPartner`, a key from your partner dashboard
107
+ (`ss_partner_…`), in place of the client id and secret.
108
+ - `SignSealerPartner.business(id)`: a `SignSealer` client that acts for one of
109
+ your businesses, by its id or your `external_id`, with your partner key.
110
+ The same as `new SignSealer({ apiKey: partnerKey, business: id })`.
111
+ - `balance()` on `SignSealerPartner` (00752): the prepaid balance your
112
+ businesses draw on, its grace period, this month by business, and the
113
+ latest entries. `membership` on `createBusiness()`; `status`, `membership`
114
+ and `spend_cap_cents` on `updateBusiness()`; `membership`,
115
+ `spend_cap_cents` and `month_to_date_cents` on a `ManagedBusiness`.
116
+ - `terms_version` and `terms_url` on `profile()`, `terms` on a
117
+ `ManagedBusiness` (what it accepted, and a newer version due), and `terms`
118
+ on `updateBusiness()` to record its acceptance of a newer version (00756).
119
+ - Your prices to your businesses (00759): `prices()` and `setPrices()` for
120
+ your default, `prices` on `updateBusiness()` for one business; gift credit
121
+ with `giveCredit(id, { cents, expires_at, note, idempotencyKey })`, and
122
+ `gift_credit` and `prices` on a `ManagedBusiness`; `usage(month)`, a month
123
+ per business in your prices with what is left to bill.
124
+ - One webhook endpoint for every business you made (00760): `webhooks()`,
125
+ `addWebhook()` (its secret, once), `updateWebhook()`, `deleteWebhook()`,
126
+ `webhookDeliveries()` and `replayWebhookDelivery()` on `SignSealerPartner`;
127
+ each delivery carries `business_id` and your `external_id`.
128
+ - A test partner key (`ss_partner_test_…`, 00761) as `partnerKey`: everything
129
+ happens in your sandbox, whose businesses send nothing and are not billed;
130
+ `sandbox` on a `ManagedBusiness`.
131
+ - `embedSession(id, { user, components })` on `SignSealerPartner` (00763): a
132
+ start link to a business's Documents screen inside your own product, for one
133
+ of your users, to load in an iframe on your page.
134
+
135
+ ## 1.24.0
136
+
137
+ Nothing that worked before changes, except where a text goes.
138
+
139
+ ### Added
140
+
141
+ - `countries` on `account().texting` (00732): where a text goes, `["US", "CA"]`,
142
+ with `"GB"` while texting UK mobiles is on. Texts go only to US and Canadian
143
+ numbers for now: not every +1 number (the Caribbean, the US territories,
144
+ toll-free and premium codes are not texted) and nowhere else. A mobile
145
+ outside those is kept and not texted; the link goes to the signer's email.
146
+ A signer with only such a mobile is refused by `send()` with 422, naming them.
147
+ - `country` as `why_not` on `smsConsent()`: a number outside the US and
148
+ Canada, which is not texted whatever the consent.
149
+
150
+ ## 1.23.0
151
+
152
+ Nothing that worked before changes.
153
+
154
+ ### Added
155
+
156
+ - `signed` on what `voidPacket()` answers (00724): the documents the void kept
157
+ because they were executed, each by `document_id` and `title`. A document
158
+ whose closing signature was being written while the void ran is waited
159
+ for, then kept and named; before, the void of the whole packet failed.
160
+
3
161
  ## 1.22.0
4
162
 
5
163
  Nothing that worked before changes.
package/README.md CHANGED
@@ -1,12 +1,26 @@
1
1
  # @signsealer/sdk
2
2
 
3
- The client for [SignSealer](https://signsealer.com) — signatures with the
4
- evidence behind them.
3
+ **For your server.** [SignSealer](https://signsealer.com)'s server library: it
4
+ holds your secret key (an API key, or a partner key) and makes the calls that
5
+ send, read and manage. To show SignSealer's screens in your web page, use
6
+ [`@signsealer/embed`](https://www.npmjs.com/package/@signsealer/embed): your
7
+ server gets the session link with this package, and the page mounts it with
8
+ that one.
9
+
10
+ | Package | Where it runs | What it does | Holds a key? |
11
+ |---|---|---|---|
12
+ | `@signsealer/sdk` (this one) | Your server: Node 18+, edge runtimes | Sends documents, reads their evidence, manages the businesses you serve, verifies webhooks | Yes, your secret key |
13
+ | `@signsealer/embed` | Your web page, in the browser | Mounts SignSealer's screens in an iframe on your page | No |
14
+
15
+ Since 1.26.0 a `SignSealer` built with a key, or any `SignSealerPartner`, throws
16
+ in a web page rather than put the key where anybody who opens the page can read
17
+ it. What holds no secret key still works in a browser: `SignSealerSigning` (the
18
+ signer's side), the `SignaturePad` in `@signsealer/sdk/react`, and
19
+ `verifyWebhook`.
5
20
 
6
21
  **No dependencies.** `fetch` is in the runtime, and a signing SDK that drags a
7
22
  HTTP library into somebody's build is a signing SDK that gets declined at
8
- review. It runs anywhere `fetch` does: Node 18+, every edge runtime, and the
9
- browser — though an API key belongs on a server.
23
+ review.
10
24
 
11
25
  ```
12
26
  npm install @signsealer/sdk
@@ -239,10 +253,24 @@ if (pdf.has_pdf && !pdf.ready) {
239
253
  }
240
254
  ```
241
255
 
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.
256
+ The file goes up in the dashboard, or from your server with
257
+ `createPdfTemplate` (1.26.0): read, sanitised and drawn as an upload is, with
258
+ its signature, date and other boxes put where the file asks for them. Check
259
+ and move them with `templateFields` and `setTemplateFields`, then publish.
260
+ SignSealer draws the pictures a signer sees from the file itself as it is
261
+ uploaded, and a template cannot be published until every page has one.
262
+ Publishing one with nothing placed on its pages answers with
263
+ `warnings: [{ code: "nothing_placed" }]`: nobody can sign it where it is.
264
+
265
+ ```ts
266
+ const made = await client.createPdfTemplate({
267
+ name: "Boat rental", filename: "boat-rental.pdf", pdf: await readFile("boat-rental.pdf"),
268
+ });
269
+ const { fields } = await client.templateFields(made.template_id);
270
+ await client.setTemplateFields(made.template_id, fields.map((f) =>
271
+ f.key === "signature" ? { ...f, place: { page: 2, x: 0.1, y: 0.7, w: 0.35, h: 0.05 } } : f));
272
+ await client.publishTemplate(made.template_id);
273
+ ```
246
274
 
247
275
  ### Signing where there is no network
248
276
 
@@ -5,7 +5,9 @@
5
5
  * Deliberately dependency-free: `fetch` is in the runtime, and a signing SDK
6
6
  * that drags a HTTP library into somebody's build is a signing SDK that gets
7
7
  * declined at review. It runs anywhere `fetch` does, which is every Node since
8
- * 18, every edge runtime and the browser — though a key belongs on a server.
8
+ * 18 and every edge runtime. It is the server's half: a client given a secret
9
+ * key in a web page throws (1.26.0), and the page's half, which holds no key,
10
+ * is `@signsealer/embed`.
9
11
  *
10
12
  * Three things it does that a hand-rolled client usually does not:
11
13
  *
@@ -49,7 +51,7 @@ var __importStar = (this && this.__importStar) || (function () {
49
51
  };
50
52
  })();
51
53
  Object.defineProperty(exports, "__esModule", { value: true });
52
- exports.WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_SIGNATURE_HEADER = exports.WEBHOOK_TIMESTAMP_HEADER = exports.WEBHOOK_EVENT_HEADER = exports.SignSealerOAuth = exports.SignSealerOAuthError = exports.SignSealerPartner = exports.SignSealerSigning = exports.SignSealer = exports.SignSealerError = void 0;
54
+ exports.WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_SIGNATURE_HEADER = exports.WEBHOOK_TIMESTAMP_HEADER = exports.WEBHOOK_EVENT_HEADER = exports.SignSealerOAuth = exports.SignSealerOAuthError = exports.SignSealerPartner = exports.SignSealerSigning = exports.SignSealer = exports.KEY_IN_PAGE_MESSAGE = exports.SDK_VERSION = exports.SignSealerError = void 0;
53
55
  exports.createPkce = createPkce;
54
56
  exports.pkceChallenge = pkceChallenge;
55
57
  exports.verifyWebhook = verifyWebhook;
@@ -93,6 +95,37 @@ class SignSealerError extends Error {
93
95
  }
94
96
  }
95
97
  exports.SignSealerError = SignSealerError;
98
+ /** This package's version, as `package.json` has it; `tests/sdk.ts` holds the two together. */
99
+ exports.SDK_VERSION = "1.26.0";
100
+ /** The `User-Agent` header for a server-side client, or none in a browser or when switched off. */
101
+ function agentHeader(given) {
102
+ if (typeof globalThis.window !== "undefined")
103
+ return {};
104
+ const agent = given === undefined ? `signsealer-sdk/${exports.SDK_VERSION} (node)` : given.trim();
105
+ return agent ? { "user-agent": agent.slice(0, 200) } : {};
106
+ }
107
+ /**
108
+ * Whether this is a web page (1.26.0): a `window` and a `document`, and none
109
+ * of the server-like runtimes that can have them too -- jsdom in a Node test,
110
+ * Electron, Deno, Bun. Workers and edge runtimes have no `document`.
111
+ *
112
+ * This library's secret keys (an API key, a partner key, a partner's client
113
+ * secret) act for a business, and anybody who opens a page can read whatever
114
+ * the page holds. What takes no such key is still fine in a page and the
115
+ * guard is not about it: `SignSealerSigning` (a signer's link, and at most a
116
+ * paired tablet's own credential), a `SignSealer` with no key (`pairDevice`),
117
+ * `SignaturePad` and `verifyWebhook`.
118
+ */
119
+ function inWebPage() {
120
+ const g = globalThis;
121
+ if (typeof g.window === "undefined" || typeof g.document === "undefined")
122
+ return false;
123
+ const v = g.process?.versions;
124
+ return typeof v?.node !== "string" && typeof v?.electron !== "string" && typeof g.Deno === "undefined" && typeof g.Bun === "undefined";
125
+ }
126
+ /** What a client built with a secret key in a web page throws (1.26.0). */
127
+ exports.KEY_IN_PAGE_MESSAGE = "This is SignSealer's server library and you gave it a secret key in a web page. "
128
+ + "Keep the key on your server; to show SignSealer's screens in a page, use @signsealer/embed.";
96
129
  /* ------------------------------------------------------------------ client */
97
130
  /**
98
131
  * Strip trailing slashes without a regular expression.
@@ -113,10 +146,12 @@ function withoutTrailingSlashes(url) {
113
146
  }
114
147
  class SignSealer {
115
148
  #key;
149
+ #business;
116
150
  #base;
117
151
  #attempts;
118
152
  #maxWaitMs;
119
153
  #fetch;
154
+ #agent;
120
155
  /**
121
156
  * Agreements left in this billing period, as of the last call that said
122
157
  * (00271), or null on a plan that counts nothing down.
@@ -127,14 +162,25 @@ class SignSealer {
127
162
  */
128
163
  agreementsRemaining = null;
129
164
  constructor(opts = {}) {
130
- if (opts.apiKey !== undefined && !opts.apiKey.startsWith("mk_")) {
165
+ if (opts.apiKey && inWebPage())
166
+ throw new Error(exports.KEY_IN_PAGE_MESSAGE);
167
+ const partnerKey = opts.apiKey?.startsWith("ss_partner_") ?? false;
168
+ if (opts.apiKey !== undefined && !opts.apiKey.startsWith("mk_") && !partnerKey) {
131
169
  throw new Error("a SignSealer API key looks like mk_live_… or mk_test_…");
132
170
  }
171
+ if (partnerKey && !opts.business?.trim()) {
172
+ throw new Error("a partner key acts for one of your businesses: name it with `business`");
173
+ }
174
+ if (opts.business !== undefined && !partnerKey) {
175
+ throw new Error("`business` is for a partner key (ss_partner_…); a business's own key already names its business");
176
+ }
133
177
  this.#key = opts.apiKey ?? "";
178
+ this.#business = opts.business?.trim() ?? "";
134
179
  this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
135
180
  this.#attempts = Math.max(1, opts.maxAttempts ?? 3);
136
181
  this.#maxWaitMs = Math.max(0, opts.maxWaitMs ?? 5_000);
137
182
  this.#fetch = opts.fetch ?? globalThis.fetch;
183
+ this.#agent = agentHeader(opts.userAgent);
138
184
  }
139
185
  /* ------------------------------------------------------------- account */
140
186
  /**
@@ -148,6 +194,38 @@ class SignSealer {
148
194
  branding() {
149
195
  return this.#call("GET", "/v1/branding");
150
196
  }
197
+ /**
198
+ * The business's brand, how its signing links go, and its reminders
199
+ * (00792). `editable` says whether this key may change them: true only for
200
+ * a partner acting for a business it manages.
201
+ */
202
+ settings() {
203
+ return this.#call("GET", "/v1/settings");
204
+ }
205
+ /**
206
+ * Set a managed business's brand, delivery and reminders, as its partner
207
+ * (00792; with `partner.business(id)`). Only what is named changes; null
208
+ * clears it. Any other key is refused with 403: a business that owns its
209
+ * account sets these in its dashboard. A PATCH of the same values, so a
210
+ * retry after a lost answer sets the same thing again.
211
+ */
212
+ updateSettings(changes) {
213
+ return this.#call("PATCH", "/v1/settings", changes);
214
+ }
215
+ /**
216
+ * Apply for a managed business's texting number, as its partner (00792;
217
+ * with `partner.business(id)`), for a toll-free or a local number. Checked
218
+ * as the carriers would check it; a local number's setup is drawn from
219
+ * your balance now. Sent once, never retried: a second answer would file
220
+ * the application again.
221
+ */
222
+ applyForTextingNumber(application) {
223
+ return this.#call("POST", "/v1/texting/number", application, undefined, { once: true });
224
+ }
225
+ /** The business's own texting number, its application's steps, and the carriers' wording (00792). */
226
+ textingNumber() {
227
+ return this.#call("GET", "/v1/texting/number");
228
+ }
151
229
  /** Prove the key works, and say whose account it is. */
152
230
  account() {
153
231
  return this.#call("GET", "/v1/account");
@@ -230,12 +308,55 @@ class SignSealer {
230
308
  *
231
309
  * `ready` is the one to check: a PDF template cannot be published until
232
310
  * SignSealer has drawn a picture of every page from the file itself
233
- * (00474), which it does as the file is uploaded. Uploading the file is a
234
- * dashboard step, where the boxes are placed; there is no API route for it.
311
+ * (00474), which it does as the file is uploaded, in the dashboard or with
312
+ * `createPdfTemplate`.
235
313
  */
236
314
  templatePdf(id) {
237
315
  return this.#call("GET", `/v1/templates/${encodeURIComponent(id)}/pdf`);
238
316
  }
317
+ /**
318
+ * A PDF template, as a draft, from the file (1.26.0): what the dashboard's
319
+ * upload makes. The file is read, sanitised and drawn exactly as an upload
320
+ * is -- up to 12 MB and 60 pages, refused in the dashboard's words past
321
+ * either, or when it is not a PDF or is password-protected -- and the
322
+ * signature and date every PDF starts with are put where the file asks for
323
+ * them, with initials, a printed name and a fillable form's questions each
324
+ * on its box. Check them with `templateFields`, move them with
325
+ * `setTemplateFields`, then `publishTemplate`. `pdf` is the file's bytes
326
+ * or its base64. Needs `signing:templates`.
327
+ */
328
+ createPdfTemplate(input, idempotencyKey) {
329
+ const { pdf, filename, ...rest } = input;
330
+ const content_base64 = typeof pdf === "string" ? pdf : bytesToBase64(pdf);
331
+ return this.#call("POST", "/v1/templates/pdf", { ...rest, pdf: { filename, content_base64 } }, idempotencyKey);
332
+ }
333
+ /**
334
+ * The questions and boxes a template asks for (1.26.0), with a PDF's pages
335
+ * and the address of each page's picture, for a screen to draw them on.
336
+ */
337
+ templateFields(id) {
338
+ return this.#call("GET", `/v1/templates/${encodeURIComponent(id)}/fields`);
339
+ }
340
+ /**
341
+ * Replace a draft's questions and boxes (1.26.0): the whole list, as the
342
+ * dashboard's Place step saves it. A box's `place` is its page and
343
+ * fractions of the page from its top-left. Refused, naming the question,
344
+ * for a page the file does not have, a box off its page, a kind that is
345
+ * not one, and a published version (revise it first).
346
+ *
347
+ * `fieldsVersion`, optional, is the `fields_version` of the list these
348
+ * replace, as `templateFields` answered it: given, a save made after the
349
+ * list changed (a box SignSealer placed on a scan, another person's save)
350
+ * is refused with 409 `stale` rather than undoing it.
351
+ */
352
+ setTemplateFields(id, fields, opts = {}) {
353
+ return this.#call("PUT", `/v1/templates/${encodeURIComponent(id)}/fields`, { fields, ...(opts.fieldsVersion !== undefined ? { fields_version: opts.fieldsVersion } : {}) });
354
+ }
355
+ /** One page of a PDF template as PNG bytes (1.26.0), the picture a signer is shown. 404 until it is drawn. */
356
+ async templatePage(id, page) {
357
+ const out = await this.#call("GET", `/v1/templates/${encodeURIComponent(id)}/pages/${page}`);
358
+ return { page: out.page, width: out.width, height: out.height, contentType: out.content_type, bytes: base64ToBytes(out.bytes_base64) };
359
+ }
239
360
  /* ------------------------------------------------------ texting consent */
240
361
  /**
241
362
  * Record that you have consent to text a number.
@@ -381,6 +502,16 @@ class SignSealer {
381
502
  remind(documentId, signerId, idempotencyKey) {
382
503
  return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/remind`, {}, idempotencyKey);
383
504
  }
505
+ /**
506
+ * The sandbox plays a signer (00719): for a test key only, `signed` (their
507
+ * consent and a typed signature, through every check the signing page
508
+ * makes), `declined` (with `reason`) or `expired`, so each outcome and its
509
+ * webhooks can be driven from your tests. Refused (403) for a live key.
510
+ * Sent once: a second call for a signer who has signed is refused anyway.
511
+ */
512
+ simulateSigning(documentId, signerId, outcome, reason) {
513
+ return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/simulate`, { outcome, ...(reason ? { reason } : {}) }, undefined, { once: true });
514
+ }
384
515
  /**
385
516
  * A fresh signing link to put in an `<iframe>` (1.6.0), with the sites it
386
517
  * may be framed on. Call it when the page is about to be shown rather than
@@ -412,6 +543,11 @@ class SignSealer {
412
543
  /**
413
544
  * Send, and take the links back once.
414
545
  *
546
+ * Once means once: a retry with the same idempotency key (the client's own,
547
+ * after a dropped connection, or yours) sends nothing again and answers with
548
+ * every link's `token` and `url` null, `redacted: true` on each and
549
+ * `links_redacted: true` on the answer. Mint a fresh link with `embedLink`.
550
+ *
415
551
  * Each signer needs an `email`, a `phone`, or both; a `cc` may have neither.
416
552
  * Given both, the same link goes out twice — by mail and by text — because a
417
553
  * person who does not check one inbox checks the other. The text goes only
@@ -419,6 +555,7 @@ class SignSealer {
419
555
  * not, the email still goes and the reason is on the evidence trail.
420
556
  */
421
557
  send(documentId, signers, idempotencyKey) {
558
+ /* `links_redacted` (1.26.0): the answer to a retry with the same key, whose links went in the first answer only. */
422
559
  return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/send`, { signers }, idempotencyKey);
423
560
  }
424
561
  void(documentId, reason, idempotencyKey) {
@@ -563,6 +700,13 @@ class SignSealer {
563
700
  ensureWebhook(input) {
564
701
  return this.#call("PUT", "/v1/webhooks", input);
565
702
  }
703
+ /**
704
+ * Add an endpoint. Its signing `secret` is in the first answer only: a
705
+ * retry with the same idempotency key -- the client's own, after a
706
+ * connection dropped, or yours -- adds nothing and answers with the same
707
+ * `id`, `secret` null and `secrets_redacted: true` (1.26.0). Keep the
708
+ * secret from the first answer; if it was lost, `rotateWebhookSecret`.
709
+ */
566
710
  addWebhook(input, idempotencyKey) {
567
711
  return this.#call("POST", "/v1/webhooks", input, idempotencyKey);
568
712
  }
@@ -788,7 +932,9 @@ class SignSealer {
788
932
  method,
789
933
  headers: {
790
934
  ...(this.#key ? { authorization: `Bearer ${this.#key}` } : {}),
935
+ ...(this.#business ? { "signsealer-business": this.#business } : {}),
791
936
  "content-type": "application/json",
937
+ ...this.#agent,
792
938
  ...(key ? { "idempotency-key": key } : {}),
793
939
  },
794
940
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
@@ -1118,18 +1264,32 @@ exports.SignSealerSigning = SignSealerSigning;
1118
1264
  */
1119
1265
  class SignSealerPartner {
1120
1266
  #auth;
1267
+ #partnerKey;
1121
1268
  #base;
1122
1269
  #attempts;
1123
1270
  #fetch;
1124
1271
  constructor(opts) {
1125
- if (!opts?.clientId || !opts?.clientSecret) {
1126
- throw new Error("a partner client needs its clientId and clientSecret");
1272
+ /* Every partner client holds a secret: its client secret or its partner key. */
1273
+ if (inWebPage())
1274
+ throw new Error(exports.KEY_IN_PAGE_MESSAGE);
1275
+ if ([opts?.clientId, opts?.clientSecret, opts?.partnerKey].some((v) => v?.startsWith("mk_"))) {
1276
+ throw new Error("that is a business's API key; the partner API takes your OAuth client id and secret, or a partner key");
1127
1277
  }
1128
- if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
1129
- throw new Error("that is a business's API key; the partner API takes your OAuth client id and secret");
1278
+ if (opts?.partnerKey) {
1279
+ if (!/^ss_partner_(test_)?[0-9a-f]{48}$/.test(opts.partnerKey)) {
1280
+ throw new Error("a partner key looks like ss_partner_ (or ss_partner_test_) and 48 hex digits");
1281
+ }
1282
+ this.#partnerKey = opts.partnerKey;
1283
+ this.#auth = `Bearer ${opts.partnerKey}`;
1284
+ }
1285
+ else {
1286
+ if (!opts?.clientId || !opts?.clientSecret) {
1287
+ throw new Error("a partner client needs its clientId and clientSecret, or a partnerKey");
1288
+ }
1289
+ this.#partnerKey = null;
1290
+ const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1291
+ this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1130
1292
  }
1131
- const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1132
- this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1133
1293
  this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
1134
1294
  this.#attempts = Math.max(1, opts.maxAttempts ?? 3);
1135
1295
  this.#fetch = opts.fetch ?? globalThis.fetch;
@@ -1160,6 +1320,139 @@ class SignSealerPartner {
1160
1320
  const out = await this.#get("/v1/partner/statements");
1161
1321
  return out.data;
1162
1322
  }
1323
+ /**
1324
+ * 00751: make a business of your own (a Platform agreement). With an
1325
+ * `external_id` it is safe to retry: one already made comes back, with
1326
+ * `existing: true`. Without one it is sent once.
1327
+ */
1328
+ createBusiness(input) {
1329
+ return this.#send("POST", "/v1/partner/businesses", input, Boolean(input.external_id));
1330
+ }
1331
+ /** 00751: the businesses you made, newest first, with how many your agreement allows. `limit` is 1 to 100. */
1332
+ managedBusinesses(opts = {}) {
1333
+ const q = new URLSearchParams({ managed: "true" });
1334
+ if (opts.limit !== undefined)
1335
+ q.set("limit", String(opts.limit));
1336
+ if (opts.offset !== undefined)
1337
+ q.set("offset", String(opts.offset));
1338
+ return this.#get(`/v1/partner/businesses?${q.toString()}`);
1339
+ }
1340
+ /** 00752: the prepaid balance your businesses draw on, this month by business, and the latest entries. */
1341
+ balance() {
1342
+ return this.#get("/v1/partner/balance");
1343
+ }
1344
+ /** 00751: one business you made, by its id or your own `external_id`. */
1345
+ managedBusiness(id) {
1346
+ return this.#get(`/v1/partner/businesses/${encodeURIComponent(id)}`);
1347
+ }
1348
+ /**
1349
+ * 00751: change its `name`, `timezone` or `profile`; only what you send changes. Safe to retry.
1350
+ * 00752: `status` suspends or resumes it, `membership` is month or year from its next renewal,
1351
+ * `spend_cap_cents` its monthly spending limit (null for none).
1352
+ */
1353
+ updateBusiness(id, changes) {
1354
+ return this.#send("PATCH", `/v1/partner/businesses/${encodeURIComponent(id)}`, changes, true);
1355
+ }
1356
+ /** 00759: your default prices to your businesses, and what each unit is. */
1357
+ prices() {
1358
+ return this.#get("/v1/partner/prices");
1359
+ }
1360
+ /** 00759: replace your default prices; `{}` takes them all away. Safe to retry. */
1361
+ setPrices(prices) {
1362
+ return this.#send("PUT", "/v1/partner/prices", { prices }, true);
1363
+ }
1364
+ /**
1365
+ * 00759: give one of your businesses credit (`cents` above zero), or take
1366
+ * back what is left (below zero), in your prices. With an `idempotencyKey`
1367
+ * it is safe to retry; without one it is sent once.
1368
+ */
1369
+ giveCredit(id, gift) {
1370
+ const { idempotencyKey, ...body } = gift;
1371
+ return this.#send("POST", `/v1/partner/businesses/${encodeURIComponent(id)}/gift-credit`, body, Boolean(idempotencyKey), idempotencyKey ? { "idempotency-key": idempotencyKey } : {});
1372
+ }
1373
+ /**
1374
+ * 00760: your webhook endpoints, each hearing every business you made;
1375
+ * with a test key, your sandbox's.
1376
+ */
1377
+ async webhooks() {
1378
+ return (await this.#get("/v1/partner/webhooks")).data;
1379
+ }
1380
+ /** 00760: add an endpoint for every business you made. Its signing `secret` is in this answer only. Sent once. */
1381
+ addWebhook(endpoint) {
1382
+ return this.#send("POST", "/v1/partner/webhooks", endpoint, false);
1383
+ }
1384
+ /** 00760: change an endpoint on every business at once; `active: true` turns back on every copy that paused. */
1385
+ updateWebhook(id, changes) {
1386
+ return this.#send("PATCH", `/v1/partner/webhooks/${encodeURIComponent(id)}`, changes, true);
1387
+ }
1388
+ /** 00760: remove an endpoint from every business. */
1389
+ async deleteWebhook(id) {
1390
+ await this.#send("DELETE", `/v1/partner/webhooks/${encodeURIComponent(id)}`, undefined, true);
1391
+ }
1392
+ /** 00760: an endpoint's latest deliveries across every business, newest first. */
1393
+ async webhookDeliveries(id, opts = {}) {
1394
+ const q = opts.limit !== undefined ? `?limit=${opts.limit}` : "";
1395
+ return (await this.#get(`/v1/partner/webhooks/${encodeURIComponent(id)}/deliveries${q}`)).data;
1396
+ }
1397
+ /** 00760: deliver one again. */
1398
+ replayWebhookDelivery(id, delivery) {
1399
+ return this.#send("POST", `/v1/partner/webhooks/${encodeURIComponent(id)}/deliveries/${encodeURIComponent(delivery)}/replay`, {}, false);
1400
+ }
1401
+ /**
1402
+ * 00763: a start link to one of your businesses' screens inside your product,
1403
+ * for one of your users. It opens once, within five minutes: ask for it as
1404
+ * the page that frames it loads. Sent once. `components` are the screens:
1405
+ * `documents` (the default), `send` (00789), `templates` (00791), and
1406
+ * `settings` and `texting` (00792). Mount it with `@signsealer/embed`.
1407
+ */
1408
+ embedSession(id, session) {
1409
+ return this.#send("POST", `/v1/partner/businesses/${encodeURIComponent(id)}/sessions`, session, false);
1410
+ }
1411
+ /** 00759: a calendar month (YYYY-MM, this one when left out) per business, in your prices, with what to bill. */
1412
+ usage(month) {
1413
+ return this.#get(`/v1/partner/usage${month ? `?month=${encodeURIComponent(month)}` : ""}`);
1414
+ }
1415
+ /**
1416
+ * 00751: a client that acts for one of your businesses -- one you made,
1417
+ * or one that connected your app -- by its id or your own `external_id`.
1418
+ * Every `SignSealer` method then works for that business. Needs a partner key.
1419
+ */
1420
+ business(id) {
1421
+ if (!this.#partnerKey)
1422
+ throw new Error("acting for a business needs a partner key: build this client with partnerKey");
1423
+ return new SignSealer({ apiKey: this.#partnerKey, business: id, baseUrl: this.#base, maxAttempts: this.#attempts, fetch: this.#fetch });
1424
+ }
1425
+ /* A write: retried on a transient failure only when `safe` says asking twice makes nothing twice. */
1426
+ async #send(method, path, body, safe, extra = {}) {
1427
+ for (let attempt = 1;; attempt += 1) {
1428
+ let res;
1429
+ try {
1430
+ res = await this.#fetch(`${this.#base}${path}`, {
1431
+ method,
1432
+ headers: { ...extra, ...agentHeader(undefined), authorization: this.#auth, accept: "application/json",
1433
+ ...(body === undefined ? {} : { "content-type": "application/json" }) },
1434
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
1435
+ });
1436
+ }
1437
+ catch (cause) {
1438
+ if (safe && attempt < this.#attempts) {
1439
+ await sleep(backoff(attempt));
1440
+ continue;
1441
+ }
1442
+ throw new SignSealerError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer", undefined, undefined);
1443
+ }
1444
+ const requestId = res.headers.get("x-request-id") ?? undefined;
1445
+ const text = await res.text();
1446
+ const parsed = text ? safeJson(text) : {};
1447
+ if (res.ok)
1448
+ return parsed;
1449
+ const err = parsed.error;
1450
+ const failure = new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId, waitAsked(res.headers.get("retry-after")));
1451
+ if (!safe || !failure.retryable || attempt >= this.#attempts)
1452
+ throw failure;
1453
+ await sleep(backoff(attempt));
1454
+ }
1455
+ }
1163
1456
  /*
1164
1457
  Every call only reads, so a transient failure is retried as it is: there
1165
1458
  is nothing a second GET could do twice.
@@ -1170,7 +1463,7 @@ class SignSealerPartner {
1170
1463
  try {
1171
1464
  res = await this.#fetch(`${this.#base}${path}`, {
1172
1465
  method: "GET",
1173
- headers: { authorization: this.#auth, accept: "application/json" },
1466
+ headers: { ...agentHeader(undefined), authorization: this.#auth, accept: "application/json" },
1174
1467
  });
1175
1468
  }
1176
1469
  catch (cause) {