@signsealer/sdk 1.19.0 → 1.25.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/dist/esm/index.js CHANGED
@@ -50,6 +50,15 @@ export class SignSealerError extends Error {
50
50
  return this.status === 402 || this.code === "quota_exceeded";
51
51
  }
52
52
  }
53
+ /** This package's version, as `package.json` has it; `tests/sdk.ts` holds the two together. */
54
+ export const SDK_VERSION = "1.25.0";
55
+ /** The `User-Agent` header for a server-side client, or none in a browser or when switched off. */
56
+ function agentHeader(given) {
57
+ if (typeof globalThis.window !== "undefined")
58
+ return {};
59
+ const agent = given === undefined ? `signsealer-sdk/${SDK_VERSION} (node)` : given.trim();
60
+ return agent ? { "user-agent": agent.slice(0, 200) } : {};
61
+ }
53
62
  /* ------------------------------------------------------------------ client */
54
63
  /**
55
64
  * Strip trailing slashes without a regular expression.
@@ -70,10 +79,12 @@ function withoutTrailingSlashes(url) {
70
79
  }
71
80
  export class SignSealer {
72
81
  #key;
82
+ #business;
73
83
  #base;
74
84
  #attempts;
75
85
  #maxWaitMs;
76
86
  #fetch;
87
+ #agent;
77
88
  /**
78
89
  * Agreements left in this billing period, as of the last call that said
79
90
  * (00271), or null on a plan that counts nothing down.
@@ -84,14 +95,23 @@ export class SignSealer {
84
95
  */
85
96
  agreementsRemaining = null;
86
97
  constructor(opts = {}) {
87
- if (opts.apiKey !== undefined && !opts.apiKey.startsWith("mk_")) {
98
+ const partnerKey = opts.apiKey?.startsWith("ss_partner_") ?? false;
99
+ if (opts.apiKey !== undefined && !opts.apiKey.startsWith("mk_") && !partnerKey) {
88
100
  throw new Error("a SignSealer API key looks like mk_live_… or mk_test_…");
89
101
  }
102
+ if (partnerKey && !opts.business?.trim()) {
103
+ throw new Error("a partner key acts for one of your businesses: name it with `business`");
104
+ }
105
+ if (opts.business !== undefined && !partnerKey) {
106
+ throw new Error("`business` is for a partner key (ss_partner_…); a business's own key already names its business");
107
+ }
90
108
  this.#key = opts.apiKey ?? "";
109
+ this.#business = opts.business?.trim() ?? "";
91
110
  this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
92
111
  this.#attempts = Math.max(1, opts.maxAttempts ?? 3);
93
112
  this.#maxWaitMs = Math.max(0, opts.maxWaitMs ?? 5_000);
94
113
  this.#fetch = opts.fetch ?? globalThis.fetch;
114
+ this.#agent = agentHeader(opts.userAgent);
95
115
  }
96
116
  /* ------------------------------------------------------------- account */
97
117
  /**
@@ -256,6 +276,21 @@ export class SignSealer {
256
276
  textingNumberInvitation(prefill = {}) {
257
277
  return this.#call("POST", "/v1/texting/number/invitations", { prefill }, undefined, { once: true });
258
278
  }
279
+ /**
280
+ * Who texts the signers of documents sent through a partner's app, for a
281
+ * partner whose dashboard leaves it to each business (1.21.0).
282
+ *
283
+ * As the partner, with the business's access token, leave `clientId` out:
284
+ * the choice is yours for that business. With the business's own key, name
285
+ * the app by its `ss_client_…` id (the key needs `signing:webhooks`). With
286
+ * `partner` or `none`, SignSealer sends no texts for those documents -- no
287
+ * link, no reminder, no confirmation -- while email and webhooks go on as
288
+ * before; a one-time code a signer asks for is still sent. A PUT, so a
289
+ * retry after a lost answer sets the same thing again.
290
+ */
291
+ setTextingSender(sender, clientId) {
292
+ return this.#call("PUT", "/v1/texting/sender", clientId ? { sender, client_id: clientId } : { sender });
293
+ }
259
294
  /* ----------------------------------------------------------- documents */
260
295
  /**
261
296
  * Documents, filtered and paged.
@@ -323,6 +358,16 @@ export class SignSealer {
323
358
  remind(documentId, signerId, idempotencyKey) {
324
359
  return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/remind`, {}, idempotencyKey);
325
360
  }
361
+ /**
362
+ * The sandbox plays a signer (00719): for a test key only, `signed` (their
363
+ * consent and a typed signature, through every check the signing page
364
+ * makes), `declined` (with `reason`) or `expired`, so each outcome and its
365
+ * webhooks can be driven from your tests. Refused (403) for a live key.
366
+ * Sent once: a second call for a signer who has signed is refused anyway.
367
+ */
368
+ simulateSigning(documentId, signerId, outcome, reason) {
369
+ return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/simulate`, { outcome, ...(reason ? { reason } : {}) }, undefined, { once: true });
370
+ }
326
371
  /**
327
372
  * A fresh signing link to put in an `<iframe>` (1.6.0), with the sites it
328
373
  * may be framed on. Call it when the page is about to be shown rather than
@@ -730,7 +775,9 @@ export class SignSealer {
730
775
  method,
731
776
  headers: {
732
777
  ...(this.#key ? { authorization: `Bearer ${this.#key}` } : {}),
778
+ ...(this.#business ? { "signsealer-business": this.#business } : {}),
733
779
  "content-type": "application/json",
780
+ ...this.#agent,
734
781
  ...(key ? { "idempotency-key": key } : {}),
735
782
  },
736
783
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
@@ -1058,18 +1105,29 @@ export class SignSealerSigning {
1058
1105
  */
1059
1106
  export class SignSealerPartner {
1060
1107
  #auth;
1108
+ #partnerKey;
1061
1109
  #base;
1062
1110
  #attempts;
1063
1111
  #fetch;
1064
1112
  constructor(opts) {
1065
- if (!opts?.clientId || !opts?.clientSecret) {
1066
- throw new Error("a partner client needs its clientId and clientSecret");
1113
+ if ([opts?.clientId, opts?.clientSecret, opts?.partnerKey].some((v) => v?.startsWith("mk_"))) {
1114
+ throw new Error("that is a business's API key; the partner API takes your OAuth client id and secret, or a partner key");
1067
1115
  }
1068
- if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
1069
- throw new Error("that is a business's API key; the partner API takes your OAuth client id and secret");
1116
+ if (opts?.partnerKey) {
1117
+ if (!/^ss_partner_(test_)?[0-9a-f]{48}$/.test(opts.partnerKey)) {
1118
+ throw new Error("a partner key looks like ss_partner_ (or ss_partner_test_) and 48 hex digits");
1119
+ }
1120
+ this.#partnerKey = opts.partnerKey;
1121
+ this.#auth = `Bearer ${opts.partnerKey}`;
1122
+ }
1123
+ else {
1124
+ if (!opts?.clientId || !opts?.clientSecret) {
1125
+ throw new Error("a partner client needs its clientId and clientSecret, or a partnerKey");
1126
+ }
1127
+ this.#partnerKey = null;
1128
+ const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1129
+ this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1070
1130
  }
1071
- const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1072
- this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1073
1131
  this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
1074
1132
  this.#attempts = Math.max(1, opts.maxAttempts ?? 3);
1075
1133
  this.#fetch = opts.fetch ?? globalThis.fetch;
@@ -1100,6 +1158,137 @@ export class SignSealerPartner {
1100
1158
  const out = await this.#get("/v1/partner/statements");
1101
1159
  return out.data;
1102
1160
  }
1161
+ /**
1162
+ * 00751: make a business of your own (a Platform agreement). With an
1163
+ * `external_id` it is safe to retry: one already made comes back, with
1164
+ * `existing: true`. Without one it is sent once.
1165
+ */
1166
+ createBusiness(input) {
1167
+ return this.#send("POST", "/v1/partner/businesses", input, Boolean(input.external_id));
1168
+ }
1169
+ /** 00751: the businesses you made, newest first, with how many your agreement allows. `limit` is 1 to 100. */
1170
+ managedBusinesses(opts = {}) {
1171
+ const q = new URLSearchParams({ managed: "true" });
1172
+ if (opts.limit !== undefined)
1173
+ q.set("limit", String(opts.limit));
1174
+ if (opts.offset !== undefined)
1175
+ q.set("offset", String(opts.offset));
1176
+ return this.#get(`/v1/partner/businesses?${q.toString()}`);
1177
+ }
1178
+ /** 00752: the prepaid balance your businesses draw on, this month by business, and the latest entries. */
1179
+ balance() {
1180
+ return this.#get("/v1/partner/balance");
1181
+ }
1182
+ /** 00751: one business you made, by its id or your own `external_id`. */
1183
+ managedBusiness(id) {
1184
+ return this.#get(`/v1/partner/businesses/${encodeURIComponent(id)}`);
1185
+ }
1186
+ /**
1187
+ * 00751: change its `name`, `timezone` or `profile`; only what you send changes. Safe to retry.
1188
+ * 00752: `status` suspends or resumes it, `membership` is month or year from its next renewal,
1189
+ * `spend_cap_cents` its monthly spending limit (null for none).
1190
+ */
1191
+ updateBusiness(id, changes) {
1192
+ return this.#send("PATCH", `/v1/partner/businesses/${encodeURIComponent(id)}`, changes, true);
1193
+ }
1194
+ /** 00759: your default prices to your businesses, and what each unit is. */
1195
+ prices() {
1196
+ return this.#get("/v1/partner/prices");
1197
+ }
1198
+ /** 00759: replace your default prices; `{}` takes them all away. Safe to retry. */
1199
+ setPrices(prices) {
1200
+ return this.#send("PUT", "/v1/partner/prices", { prices }, true);
1201
+ }
1202
+ /**
1203
+ * 00759: give one of your businesses credit (`cents` above zero), or take
1204
+ * back what is left (below zero), in your prices. With an `idempotencyKey`
1205
+ * it is safe to retry; without one it is sent once.
1206
+ */
1207
+ giveCredit(id, gift) {
1208
+ const { idempotencyKey, ...body } = gift;
1209
+ return this.#send("POST", `/v1/partner/businesses/${encodeURIComponent(id)}/gift-credit`, body, Boolean(idempotencyKey), idempotencyKey ? { "idempotency-key": idempotencyKey } : {});
1210
+ }
1211
+ /**
1212
+ * 00760: your webhook endpoints, each hearing every business you made;
1213
+ * with a test key, your sandbox's.
1214
+ */
1215
+ async webhooks() {
1216
+ return (await this.#get("/v1/partner/webhooks")).data;
1217
+ }
1218
+ /** 00760: add an endpoint for every business you made. Its signing `secret` is in this answer only. Sent once. */
1219
+ addWebhook(endpoint) {
1220
+ return this.#send("POST", "/v1/partner/webhooks", endpoint, false);
1221
+ }
1222
+ /** 00760: change an endpoint on every business at once; `active: true` turns back on every copy that paused. */
1223
+ updateWebhook(id, changes) {
1224
+ return this.#send("PATCH", `/v1/partner/webhooks/${encodeURIComponent(id)}`, changes, true);
1225
+ }
1226
+ /** 00760: remove an endpoint from every business. */
1227
+ async deleteWebhook(id) {
1228
+ await this.#send("DELETE", `/v1/partner/webhooks/${encodeURIComponent(id)}`, undefined, true);
1229
+ }
1230
+ /** 00760: an endpoint's latest deliveries across every business, newest first. */
1231
+ async webhookDeliveries(id, opts = {}) {
1232
+ const q = opts.limit !== undefined ? `?limit=${opts.limit}` : "";
1233
+ return (await this.#get(`/v1/partner/webhooks/${encodeURIComponent(id)}/deliveries${q}`)).data;
1234
+ }
1235
+ /** 00760: deliver one again. */
1236
+ replayWebhookDelivery(id, delivery) {
1237
+ return this.#send("POST", `/v1/partner/webhooks/${encodeURIComponent(id)}/deliveries/${encodeURIComponent(delivery)}/replay`, {}, false);
1238
+ }
1239
+ /**
1240
+ * 00763: a start link to one of your businesses' screens inside your product,
1241
+ * for one of your users. It opens once, within five minutes: ask for it as
1242
+ * the page that frames it loads. Sent once.
1243
+ */
1244
+ embedSession(id, session) {
1245
+ return this.#send("POST", `/v1/partner/businesses/${encodeURIComponent(id)}/sessions`, session, false);
1246
+ }
1247
+ /** 00759: a calendar month (YYYY-MM, this one when left out) per business, in your prices, with what to bill. */
1248
+ usage(month) {
1249
+ return this.#get(`/v1/partner/usage${month ? `?month=${encodeURIComponent(month)}` : ""}`);
1250
+ }
1251
+ /**
1252
+ * 00751: a client that acts for one of your businesses -- one you made,
1253
+ * or one that connected your app -- by its id or your own `external_id`.
1254
+ * Every `SignSealer` method then works for that business. Needs a partner key.
1255
+ */
1256
+ business(id) {
1257
+ if (!this.#partnerKey)
1258
+ throw new Error("acting for a business needs a partner key: build this client with partnerKey");
1259
+ return new SignSealer({ apiKey: this.#partnerKey, business: id, baseUrl: this.#base, maxAttempts: this.#attempts, fetch: this.#fetch });
1260
+ }
1261
+ /* A write: retried on a transient failure only when `safe` says asking twice makes nothing twice. */
1262
+ async #send(method, path, body, safe, extra = {}) {
1263
+ for (let attempt = 1;; attempt += 1) {
1264
+ let res;
1265
+ try {
1266
+ res = await this.#fetch(`${this.#base}${path}`, {
1267
+ method,
1268
+ headers: { ...extra, ...agentHeader(undefined), authorization: this.#auth, accept: "application/json",
1269
+ ...(body === undefined ? {} : { "content-type": "application/json" }) },
1270
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
1271
+ });
1272
+ }
1273
+ catch (cause) {
1274
+ if (safe && attempt < this.#attempts) {
1275
+ await sleep(backoff(attempt));
1276
+ continue;
1277
+ }
1278
+ throw new SignSealerError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer", undefined, undefined);
1279
+ }
1280
+ const requestId = res.headers.get("x-request-id") ?? undefined;
1281
+ const text = await res.text();
1282
+ const parsed = text ? safeJson(text) : {};
1283
+ if (res.ok)
1284
+ return parsed;
1285
+ const err = parsed.error;
1286
+ const failure = new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId, waitAsked(res.headers.get("retry-after")));
1287
+ if (!safe || !failure.retryable || attempt >= this.#attempts)
1288
+ throw failure;
1289
+ await sleep(backoff(attempt));
1290
+ }
1291
+ }
1103
1292
  /*
1104
1293
  Every call only reads, so a transient failure is retried as it is: there
1105
1294
  is nothing a second GET could do twice.
@@ -1110,7 +1299,7 @@ export class SignSealerPartner {
1110
1299
  try {
1111
1300
  res = await this.#fetch(`${this.#base}${path}`, {
1112
1301
  method: "GET",
1113
- headers: { authorization: this.#auth, accept: "application/json" },
1302
+ headers: { ...agentHeader(undefined), authorization: this.#auth, accept: "application/json" },
1114
1303
  });
1115
1304
  }
1116
1305
  catch (cause) {
@@ -1186,6 +1375,297 @@ function safeJson(text) {
1186
1375
  return {};
1187
1376
  }
1188
1377
  }
1378
+ /**
1379
+ * A refusal from the OAuth endpoints, or from the consent screen's answer.
1380
+ *
1381
+ * `code` is RFC 6749's `error` and `message` its `error_description` (both
1382
+ * also under their RFC names). Two questions decide what to do:
1383
+ *
1384
+ * - `reconnect`: the grant is over, or the code is spent. `invalid_grant`
1385
+ * -- the business disconnected you, the person who connected you can no
1386
+ * longer give what you hold, a token or code was used twice, or it
1387
+ * expired. Send the business through `authorizeUrl` again; nothing else
1388
+ * will bring it back.
1389
+ * - `transient`: the network or SignSealer, not your request. The grant may
1390
+ * well still be good. On a refresh, **whether the token was spent is
1391
+ * unknown**: read `refresh()` before deciding to send it again.
1392
+ *
1393
+ * `invalid_client` is neither: your client id or secret did not
1394
+ * authenticate, which is your configuration, for every business at once.
1395
+ *
1396
+ * `retryable` is always false. SignSealerError's "worth trying again
1397
+ * unchanged" is exactly the advice that turns a lost answer into a revoked
1398
+ * grant here.
1399
+ */
1400
+ export class SignSealerOAuthError extends SignSealerError {
1401
+ constructor(status, code, message, requestId, retryAfter) {
1402
+ super(status, code, message, undefined, requestId, retryAfter);
1403
+ this.name = "SignSealerOAuthError";
1404
+ }
1405
+ /** RFC 6749's name for `code`. */
1406
+ get error() {
1407
+ return this.code;
1408
+ }
1409
+ /** RFC 6749's name for `message`. */
1410
+ get errorDescription() {
1411
+ return this.message;
1412
+ }
1413
+ get retryable() {
1414
+ return false;
1415
+ }
1416
+ /** The grant is over or the code spent: send the business to connect again. */
1417
+ get reconnect() {
1418
+ return this.code === "invalid_grant";
1419
+ }
1420
+ /** The network or SignSealer failed, not the request. On a refresh, the token may or may not have been spent. */
1421
+ get transient() {
1422
+ return this.status === 0 || this.status === 429 || this.status >= 500;
1423
+ }
1424
+ }
1425
+ /** The characters RFC 7636 allows in a verifier, 43 to 128 of them. */
1426
+ const VERIFIER = /^[A-Za-z0-9\-._~]{43,128}$/;
1427
+ /**
1428
+ * Random bytes from wherever this runtime keeps them: the global WebCrypto,
1429
+ * then `node:crypto` for Node 18, assembled at run time for the reason
1430
+ * `webCrypto()` gives.
1431
+ */
1432
+ let randomPromise = null;
1433
+ async function randomBytes(n) {
1434
+ randomPromise ??= (async () => {
1435
+ const here = globalThis.crypto;
1436
+ if (typeof here?.getRandomValues === "function")
1437
+ return (k) => here.getRandomValues(new Uint8Array(k));
1438
+ try {
1439
+ const mod = await import(/* webpackIgnore: true */ /* @vite-ignore */ "node:" + "crypto");
1440
+ const web = mod.webcrypto;
1441
+ if (typeof web?.getRandomValues === "function")
1442
+ return (k) => web.getRandomValues(new Uint8Array(k));
1443
+ }
1444
+ catch {
1445
+ /* Not Node. The error below is the honest answer. */
1446
+ }
1447
+ throw new Error("no crypto.getRandomValues in this runtime, so a PKCE verifier cannot be made"
1448
+ + " — every current browser, edge runtime and Node 19 or later has it,"
1449
+ + " and Node 18 reaches it through node:crypto");
1450
+ })();
1451
+ return (await randomPromise)(n);
1452
+ }
1453
+ /**
1454
+ * A fresh PKCE pair, one per authorise request: 32 random bytes as a
1455
+ * 43-character verifier, and its S256 challenge.
1456
+ *
1457
+ * Keep the verifier on your server, against the `state` you send (a
1458
+ * session, or a short-lived row), and give it to `exchangeCode`. Never put
1459
+ * it in the authorise address: the challenge goes there, and the verifier
1460
+ * is what proves the code came back to the same party that asked.
1461
+ */
1462
+ export async function createPkce() {
1463
+ const verifier = base64url(await randomBytes(32));
1464
+ return { verifier, challenge: await pkceChallenge(verifier), method: "S256" };
1465
+ }
1466
+ /** The S256 challenge for a verifier: base64url of its SHA-256, without padding (RFC 7636, section 4.2). */
1467
+ export async function pkceChallenge(verifier) {
1468
+ if (!VERIFIER.test(verifier)) {
1469
+ throw new Error("a PKCE verifier is 43 to 128 of A-Z, a-z, 0-9 and - . _ ~");
1470
+ }
1471
+ const digest = await (await webCrypto()).digest("SHA-256", new TextEncoder().encode(verifier));
1472
+ return base64url(new Uint8Array(digest));
1473
+ }
1474
+ /**
1475
+ * "Connect with SignSealer", for a partner's server (1.20.0).
1476
+ *
1477
+ * ```ts
1478
+ * const oauth = new SignSealerOAuth({ clientId, clientSecret });
1479
+ * const { verifier, challenge } = await createPkce();
1480
+ * redirect(oauth.authorizeUrl({ redirectUri, scopes: ["signing:read", "signing:write"], state, codeChallenge: challenge }));
1481
+ * // …and on the way back:
1482
+ * const { code } = oauth.callback(request.url, savedState);
1483
+ * const tokens = await oauth.exchangeCode({ code, redirectUri, codeVerifier: verifier });
1484
+ * const client = new SignSealer({ apiKey: tokens.access_token });
1485
+ * ```
1486
+ *
1487
+ * The client is authenticated to `/oauth/token` by HTTP Basic, which RFC
1488
+ * 6749 prefers and the server reads first. Every token request is sent
1489
+ * exactly once: see `refresh()` for why that is the whole point.
1490
+ */
1491
+ export class SignSealerOAuth {
1492
+ #auth;
1493
+ #base;
1494
+ #clientId;
1495
+ #fetch;
1496
+ constructor(opts) {
1497
+ if (!opts?.clientId || !opts?.clientSecret) {
1498
+ throw new Error("an OAuth client needs its clientId and clientSecret");
1499
+ }
1500
+ if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
1501
+ throw new Error("that is a business's API key; OAuth takes your client id and secret");
1502
+ }
1503
+ this.#clientId = opts.clientId;
1504
+ /* Each half form-encoded before joining (RFC 6749, 2.3.1), which is how the server decodes them. */
1505
+ const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1506
+ this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1507
+ this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
1508
+ this.#fetch = opts.fetch ?? globalThis.fetch;
1509
+ }
1510
+ /**
1511
+ * Where to send the business's browser. SignSealer signs them in (or lets
1512
+ * them make an account and name their business on the way), shows your
1513
+ * registered name and what each scope allows, and sends them back to
1514
+ * `redirectUri` with `code` and your `state`, or with `error`.
1515
+ *
1516
+ * `redirectUri` must be one you registered, byte for byte, and the same
1517
+ * string you give `exchangeCode`. `state` is yours, returned untouched:
1518
+ * make it unguessable, keep it with the verifier, and check it in
1519
+ * `callback`. Ask for the fewest scopes that do the job; a scope your
1520
+ * client was not registered with is refused as `invalid_scope`.
1521
+ */
1522
+ authorizeUrl(opts) {
1523
+ if (!opts?.redirectUri)
1524
+ throw new Error("authorizeUrl needs the redirectUri you registered");
1525
+ if (!opts.scopes?.length)
1526
+ throw new Error("authorizeUrl needs at least one scope");
1527
+ if (!opts.state)
1528
+ throw new Error("authorizeUrl needs a state, to check on the way back");
1529
+ if (!opts.codeChallenge || opts.codeChallenge.length < 43) {
1530
+ throw new Error("authorizeUrl needs the codeChallenge from createPkce(); PKCE is required");
1531
+ }
1532
+ const q = new URLSearchParams({
1533
+ response_type: "code",
1534
+ client_id: this.#clientId,
1535
+ redirect_uri: opts.redirectUri,
1536
+ scope: opts.scopes.join(" "),
1537
+ state: opts.state,
1538
+ code_challenge: opts.codeChallenge,
1539
+ code_challenge_method: "S256",
1540
+ });
1541
+ return `${this.#base}/oauth/authorize?${q}`;
1542
+ }
1543
+ /**
1544
+ * Read the consent screen's answer from your redirect's query: the code,
1545
+ * once `state` matches the one you kept. A business that pressed Not now
1546
+ * comes back as `access_denied`, and a request the screen could not
1547
+ * answer as its RFC 6749 error; both are thrown as SignSealerOAuthError,
1548
+ * with `status` 400. A `state` that does not match is `state_mismatch`:
1549
+ * do not exchange that code.
1550
+ */
1551
+ callback(query, expectedState) {
1552
+ const q = query instanceof URLSearchParams ? query
1553
+ : query instanceof URL ? query.searchParams
1554
+ : new URLSearchParams(query.includes("?") ? query.slice(query.indexOf("?") + 1) : query);
1555
+ const state = q.get("state") ?? "";
1556
+ if (!expectedState || !sameBytes(new TextEncoder().encode(state), new TextEncoder().encode(expectedState))) {
1557
+ throw new SignSealerOAuthError(400, "state_mismatch", "the state that came back is not the one this browser was sent with");
1558
+ }
1559
+ const error = q.get("error");
1560
+ if (error)
1561
+ throw new SignSealerOAuthError(400, error, q.get("error_description") ?? error);
1562
+ const code = q.get("code");
1563
+ if (!code)
1564
+ throw new SignSealerOAuthError(400, "invalid_request", "the answer carried neither a code nor an error");
1565
+ return { code };
1566
+ }
1567
+ /**
1568
+ * Exchange the code from `callback` for the business's tokens. Do it at
1569
+ * once: a code lives sixty seconds and is good once.
1570
+ *
1571
+ * Sent once and never again. A code presented twice is a replay, and the
1572
+ * server revokes the grant it made, so a retry after a lost answer would
1573
+ * disconnect the business it just connected. If this throws `transient`,
1574
+ * send the business through `authorizeUrl` again.
1575
+ */
1576
+ exchangeCode(opts) {
1577
+ if (!opts?.code || !opts.redirectUri || !opts.codeVerifier) {
1578
+ throw new Error("exchangeCode needs the code, the same redirectUri and the PKCE codeVerifier");
1579
+ }
1580
+ return this.#token({
1581
+ grant_type: "authorization_code",
1582
+ code: opts.code,
1583
+ redirect_uri: opts.redirectUri,
1584
+ code_verifier: opts.codeVerifier,
1585
+ });
1586
+ }
1587
+ /**
1588
+ * Swap a refresh token for a new access token **and a new refresh token**.
1589
+ *
1590
+ * **THIS IS NEVER RETRIED, AND YOU MUST NOT RETRY IT EITHER WITHOUT
1591
+ * THINKING.** The refresh token you send is spent the moment SignSealer
1592
+ * reads it. Presenting a spent one is treated as theft: the whole family
1593
+ * is revoked -- every refresh token from that connection, the grant, and
1594
+ * every access token issued under it -- and the business has to connect
1595
+ * again. From the server's side a buggy retry and a stolen token look the
1596
+ * same.
1597
+ *
1598
+ * So:
1599
+ *
1600
+ * 1. **Serialise refreshes per grant.** One at a time for each business
1601
+ * (a row lock, an advisory lock, a queue). Two workers refreshing the
1602
+ * same grant at once will end it.
1603
+ * 2. **Store the new refresh token before you use the access token**,
1604
+ * atomically, while still holding the lock. A new refresh token you
1605
+ * lose cannot be got back.
1606
+ * 3. **A `transient` failure leaves the token's state unknown.** If the
1607
+ * request reached SignSealer and the answer was lost, the token you
1608
+ * hold is spent and its successor lost with the answer; if it never
1609
+ * arrived, it is still good. Sending it again either works or ends
1610
+ * the connection (`reconnect`), which losing the successor had
1611
+ * already made inevitable. That is your decision, made under the
1612
+ * lock, never a loop.
1613
+ * 4. **`reconnect` means reconnect.** Mark the business disconnected and
1614
+ * ask them to connect again; do not try the token again.
1615
+ */
1616
+ refresh(refreshToken) {
1617
+ if (!refreshToken)
1618
+ throw new Error("refresh needs the refresh token you stored last");
1619
+ return this.#token({ grant_type: "refresh_token", refresh_token: refreshToken });
1620
+ }
1621
+ /*
1622
+ One request, one answer, no loop. Every other call in this package
1623
+ retries what is worth retrying; this one has nothing worth retrying,
1624
+ because both of its grants are spent by being read.
1625
+ */
1626
+ async #token(form) {
1627
+ const sentAt = Date.now();
1628
+ let res;
1629
+ try {
1630
+ res = await this.#fetch(`${this.#base}/oauth/token`, {
1631
+ method: "POST",
1632
+ headers: {
1633
+ authorization: this.#auth,
1634
+ "content-type": "application/x-www-form-urlencoded",
1635
+ accept: "application/json",
1636
+ },
1637
+ body: new URLSearchParams(form).toString(),
1638
+ });
1639
+ }
1640
+ catch (cause) {
1641
+ throw new SignSealerOAuthError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer");
1642
+ }
1643
+ const requestId = res.headers.get("x-request-id") ?? undefined;
1644
+ const text = await res.text();
1645
+ const parsed = (text ? safeJson(text) : {});
1646
+ if (res.ok && typeof parsed.access_token === "string") {
1647
+ const expiresIn = typeof parsed.expires_in === "number" ? parsed.expires_in : 3600;
1648
+ const scope = typeof parsed.scope === "string" ? parsed.scope : "";
1649
+ return {
1650
+ access_token: parsed.access_token,
1651
+ token_type: "Bearer",
1652
+ expires_in: expiresIn,
1653
+ expires_at: new Date(sentAt + expiresIn * 1000).toISOString(),
1654
+ scope,
1655
+ scopes: scope.split(" ").filter(Boolean),
1656
+ refresh_token: typeof parsed.refresh_token === "string" ? parsed.refresh_token : null,
1657
+ };
1658
+ }
1659
+ const code = typeof parsed.error === "string" ? parsed.error
1660
+ : res.status >= 500 ? "server_error"
1661
+ : res.status === 429 ? "temporarily_unavailable"
1662
+ : res.ok ? "server_error" : "invalid_request";
1663
+ const description = typeof parsed.error_description === "string" ? parsed.error_description
1664
+ : res.ok ? "SignSealer answered without an access token" : `SignSealer returned ${res.status}`;
1665
+ /* A 200 with no token is SignSealer's fault, and as unknown in its outcome as a 500. */
1666
+ throw new SignSealerOAuthError(res.ok ? 502 : res.status, code, description, requestId, waitAsked(res.headers.get("retry-after")));
1667
+ }
1668
+ }
1189
1669
  /* ------------------------------------------------------- verifying a webhook
1190
1670
 
1191
1671
  The SDK could create a webhook endpoint and could not check a delivery from