@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.
@@ -49,7 +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.SignSealerPartner = 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.SignSealerOAuth = exports.SignSealerOAuthError = exports.SignSealerPartner = exports.SignSealerSigning = exports.SignSealer = exports.SDK_VERSION = exports.SignSealerError = void 0;
53
+ exports.createPkce = createPkce;
54
+ exports.pkceChallenge = pkceChallenge;
53
55
  exports.verifyWebhook = verifyWebhook;
54
56
  exports.verifyWebhookRequest = verifyWebhookRequest;
55
57
  exports.sha256Hex = sha256Hex;
@@ -91,6 +93,15 @@ class SignSealerError extends Error {
91
93
  }
92
94
  }
93
95
  exports.SignSealerError = SignSealerError;
96
+ /** This package's version, as `package.json` has it; `tests/sdk.ts` holds the two together. */
97
+ exports.SDK_VERSION = "1.25.0";
98
+ /** The `User-Agent` header for a server-side client, or none in a browser or when switched off. */
99
+ function agentHeader(given) {
100
+ if (typeof globalThis.window !== "undefined")
101
+ return {};
102
+ const agent = given === undefined ? `signsealer-sdk/${exports.SDK_VERSION} (node)` : given.trim();
103
+ return agent ? { "user-agent": agent.slice(0, 200) } : {};
104
+ }
94
105
  /* ------------------------------------------------------------------ client */
95
106
  /**
96
107
  * Strip trailing slashes without a regular expression.
@@ -111,10 +122,12 @@ function withoutTrailingSlashes(url) {
111
122
  }
112
123
  class SignSealer {
113
124
  #key;
125
+ #business;
114
126
  #base;
115
127
  #attempts;
116
128
  #maxWaitMs;
117
129
  #fetch;
130
+ #agent;
118
131
  /**
119
132
  * Agreements left in this billing period, as of the last call that said
120
133
  * (00271), or null on a plan that counts nothing down.
@@ -125,14 +138,23 @@ class SignSealer {
125
138
  */
126
139
  agreementsRemaining = null;
127
140
  constructor(opts = {}) {
128
- if (opts.apiKey !== undefined && !opts.apiKey.startsWith("mk_")) {
141
+ const partnerKey = opts.apiKey?.startsWith("ss_partner_") ?? false;
142
+ if (opts.apiKey !== undefined && !opts.apiKey.startsWith("mk_") && !partnerKey) {
129
143
  throw new Error("a SignSealer API key looks like mk_live_… or mk_test_…");
130
144
  }
145
+ if (partnerKey && !opts.business?.trim()) {
146
+ throw new Error("a partner key acts for one of your businesses: name it with `business`");
147
+ }
148
+ if (opts.business !== undefined && !partnerKey) {
149
+ throw new Error("`business` is for a partner key (ss_partner_…); a business's own key already names its business");
150
+ }
131
151
  this.#key = opts.apiKey ?? "";
152
+ this.#business = opts.business?.trim() ?? "";
132
153
  this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
133
154
  this.#attempts = Math.max(1, opts.maxAttempts ?? 3);
134
155
  this.#maxWaitMs = Math.max(0, opts.maxWaitMs ?? 5_000);
135
156
  this.#fetch = opts.fetch ?? globalThis.fetch;
157
+ this.#agent = agentHeader(opts.userAgent);
136
158
  }
137
159
  /* ------------------------------------------------------------- account */
138
160
  /**
@@ -297,6 +319,21 @@ class SignSealer {
297
319
  textingNumberInvitation(prefill = {}) {
298
320
  return this.#call("POST", "/v1/texting/number/invitations", { prefill }, undefined, { once: true });
299
321
  }
322
+ /**
323
+ * Who texts the signers of documents sent through a partner's app, for a
324
+ * partner whose dashboard leaves it to each business (1.21.0).
325
+ *
326
+ * As the partner, with the business's access token, leave `clientId` out:
327
+ * the choice is yours for that business. With the business's own key, name
328
+ * the app by its `ss_client_…` id (the key needs `signing:webhooks`). With
329
+ * `partner` or `none`, SignSealer sends no texts for those documents -- no
330
+ * link, no reminder, no confirmation -- while email and webhooks go on as
331
+ * before; a one-time code a signer asks for is still sent. A PUT, so a
332
+ * retry after a lost answer sets the same thing again.
333
+ */
334
+ setTextingSender(sender, clientId) {
335
+ return this.#call("PUT", "/v1/texting/sender", clientId ? { sender, client_id: clientId } : { sender });
336
+ }
300
337
  /* ----------------------------------------------------------- documents */
301
338
  /**
302
339
  * Documents, filtered and paged.
@@ -364,6 +401,16 @@ class SignSealer {
364
401
  remind(documentId, signerId, idempotencyKey) {
365
402
  return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/remind`, {}, idempotencyKey);
366
403
  }
404
+ /**
405
+ * The sandbox plays a signer (00719): for a test key only, `signed` (their
406
+ * consent and a typed signature, through every check the signing page
407
+ * makes), `declined` (with `reason`) or `expired`, so each outcome and its
408
+ * webhooks can be driven from your tests. Refused (403) for a live key.
409
+ * Sent once: a second call for a signer who has signed is refused anyway.
410
+ */
411
+ simulateSigning(documentId, signerId, outcome, reason) {
412
+ return this.#call("POST", `/v1/documents/${encodeURIComponent(documentId)}/signers/${encodeURIComponent(signerId)}/simulate`, { outcome, ...(reason ? { reason } : {}) }, undefined, { once: true });
413
+ }
367
414
  /**
368
415
  * A fresh signing link to put in an `<iframe>` (1.6.0), with the sites it
369
416
  * may be framed on. Call it when the page is about to be shown rather than
@@ -771,7 +818,9 @@ class SignSealer {
771
818
  method,
772
819
  headers: {
773
820
  ...(this.#key ? { authorization: `Bearer ${this.#key}` } : {}),
821
+ ...(this.#business ? { "signsealer-business": this.#business } : {}),
774
822
  "content-type": "application/json",
823
+ ...this.#agent,
775
824
  ...(key ? { "idempotency-key": key } : {}),
776
825
  },
777
826
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
@@ -1101,18 +1150,29 @@ exports.SignSealerSigning = SignSealerSigning;
1101
1150
  */
1102
1151
  class SignSealerPartner {
1103
1152
  #auth;
1153
+ #partnerKey;
1104
1154
  #base;
1105
1155
  #attempts;
1106
1156
  #fetch;
1107
1157
  constructor(opts) {
1108
- if (!opts?.clientId || !opts?.clientSecret) {
1109
- throw new Error("a partner client needs its clientId and clientSecret");
1158
+ if ([opts?.clientId, opts?.clientSecret, opts?.partnerKey].some((v) => v?.startsWith("mk_"))) {
1159
+ throw new Error("that is a business's API key; the partner API takes your OAuth client id and secret, or a partner key");
1110
1160
  }
1111
- if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
1112
- throw new Error("that is a business's API key; the partner API takes your OAuth client id and secret");
1161
+ if (opts?.partnerKey) {
1162
+ if (!/^ss_partner_(test_)?[0-9a-f]{48}$/.test(opts.partnerKey)) {
1163
+ throw new Error("a partner key looks like ss_partner_ (or ss_partner_test_) and 48 hex digits");
1164
+ }
1165
+ this.#partnerKey = opts.partnerKey;
1166
+ this.#auth = `Bearer ${opts.partnerKey}`;
1167
+ }
1168
+ else {
1169
+ if (!opts?.clientId || !opts?.clientSecret) {
1170
+ throw new Error("a partner client needs its clientId and clientSecret, or a partnerKey");
1171
+ }
1172
+ this.#partnerKey = null;
1173
+ const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1174
+ this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1113
1175
  }
1114
- const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1115
- this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1116
1176
  this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
1117
1177
  this.#attempts = Math.max(1, opts.maxAttempts ?? 3);
1118
1178
  this.#fetch = opts.fetch ?? globalThis.fetch;
@@ -1143,6 +1203,137 @@ class SignSealerPartner {
1143
1203
  const out = await this.#get("/v1/partner/statements");
1144
1204
  return out.data;
1145
1205
  }
1206
+ /**
1207
+ * 00751: make a business of your own (a Platform agreement). With an
1208
+ * `external_id` it is safe to retry: one already made comes back, with
1209
+ * `existing: true`. Without one it is sent once.
1210
+ */
1211
+ createBusiness(input) {
1212
+ return this.#send("POST", "/v1/partner/businesses", input, Boolean(input.external_id));
1213
+ }
1214
+ /** 00751: the businesses you made, newest first, with how many your agreement allows. `limit` is 1 to 100. */
1215
+ managedBusinesses(opts = {}) {
1216
+ const q = new URLSearchParams({ managed: "true" });
1217
+ if (opts.limit !== undefined)
1218
+ q.set("limit", String(opts.limit));
1219
+ if (opts.offset !== undefined)
1220
+ q.set("offset", String(opts.offset));
1221
+ return this.#get(`/v1/partner/businesses?${q.toString()}`);
1222
+ }
1223
+ /** 00752: the prepaid balance your businesses draw on, this month by business, and the latest entries. */
1224
+ balance() {
1225
+ return this.#get("/v1/partner/balance");
1226
+ }
1227
+ /** 00751: one business you made, by its id or your own `external_id`. */
1228
+ managedBusiness(id) {
1229
+ return this.#get(`/v1/partner/businesses/${encodeURIComponent(id)}`);
1230
+ }
1231
+ /**
1232
+ * 00751: change its `name`, `timezone` or `profile`; only what you send changes. Safe to retry.
1233
+ * 00752: `status` suspends or resumes it, `membership` is month or year from its next renewal,
1234
+ * `spend_cap_cents` its monthly spending limit (null for none).
1235
+ */
1236
+ updateBusiness(id, changes) {
1237
+ return this.#send("PATCH", `/v1/partner/businesses/${encodeURIComponent(id)}`, changes, true);
1238
+ }
1239
+ /** 00759: your default prices to your businesses, and what each unit is. */
1240
+ prices() {
1241
+ return this.#get("/v1/partner/prices");
1242
+ }
1243
+ /** 00759: replace your default prices; `{}` takes them all away. Safe to retry. */
1244
+ setPrices(prices) {
1245
+ return this.#send("PUT", "/v1/partner/prices", { prices }, true);
1246
+ }
1247
+ /**
1248
+ * 00759: give one of your businesses credit (`cents` above zero), or take
1249
+ * back what is left (below zero), in your prices. With an `idempotencyKey`
1250
+ * it is safe to retry; without one it is sent once.
1251
+ */
1252
+ giveCredit(id, gift) {
1253
+ const { idempotencyKey, ...body } = gift;
1254
+ return this.#send("POST", `/v1/partner/businesses/${encodeURIComponent(id)}/gift-credit`, body, Boolean(idempotencyKey), idempotencyKey ? { "idempotency-key": idempotencyKey } : {});
1255
+ }
1256
+ /**
1257
+ * 00760: your webhook endpoints, each hearing every business you made;
1258
+ * with a test key, your sandbox's.
1259
+ */
1260
+ async webhooks() {
1261
+ return (await this.#get("/v1/partner/webhooks")).data;
1262
+ }
1263
+ /** 00760: add an endpoint for every business you made. Its signing `secret` is in this answer only. Sent once. */
1264
+ addWebhook(endpoint) {
1265
+ return this.#send("POST", "/v1/partner/webhooks", endpoint, false);
1266
+ }
1267
+ /** 00760: change an endpoint on every business at once; `active: true` turns back on every copy that paused. */
1268
+ updateWebhook(id, changes) {
1269
+ return this.#send("PATCH", `/v1/partner/webhooks/${encodeURIComponent(id)}`, changes, true);
1270
+ }
1271
+ /** 00760: remove an endpoint from every business. */
1272
+ async deleteWebhook(id) {
1273
+ await this.#send("DELETE", `/v1/partner/webhooks/${encodeURIComponent(id)}`, undefined, true);
1274
+ }
1275
+ /** 00760: an endpoint's latest deliveries across every business, newest first. */
1276
+ async webhookDeliveries(id, opts = {}) {
1277
+ const q = opts.limit !== undefined ? `?limit=${opts.limit}` : "";
1278
+ return (await this.#get(`/v1/partner/webhooks/${encodeURIComponent(id)}/deliveries${q}`)).data;
1279
+ }
1280
+ /** 00760: deliver one again. */
1281
+ replayWebhookDelivery(id, delivery) {
1282
+ return this.#send("POST", `/v1/partner/webhooks/${encodeURIComponent(id)}/deliveries/${encodeURIComponent(delivery)}/replay`, {}, false);
1283
+ }
1284
+ /**
1285
+ * 00763: a start link to one of your businesses' screens inside your product,
1286
+ * for one of your users. It opens once, within five minutes: ask for it as
1287
+ * the page that frames it loads. Sent once.
1288
+ */
1289
+ embedSession(id, session) {
1290
+ return this.#send("POST", `/v1/partner/businesses/${encodeURIComponent(id)}/sessions`, session, false);
1291
+ }
1292
+ /** 00759: a calendar month (YYYY-MM, this one when left out) per business, in your prices, with what to bill. */
1293
+ usage(month) {
1294
+ return this.#get(`/v1/partner/usage${month ? `?month=${encodeURIComponent(month)}` : ""}`);
1295
+ }
1296
+ /**
1297
+ * 00751: a client that acts for one of your businesses -- one you made,
1298
+ * or one that connected your app -- by its id or your own `external_id`.
1299
+ * Every `SignSealer` method then works for that business. Needs a partner key.
1300
+ */
1301
+ business(id) {
1302
+ if (!this.#partnerKey)
1303
+ throw new Error("acting for a business needs a partner key: build this client with partnerKey");
1304
+ return new SignSealer({ apiKey: this.#partnerKey, business: id, baseUrl: this.#base, maxAttempts: this.#attempts, fetch: this.#fetch });
1305
+ }
1306
+ /* A write: retried on a transient failure only when `safe` says asking twice makes nothing twice. */
1307
+ async #send(method, path, body, safe, extra = {}) {
1308
+ for (let attempt = 1;; attempt += 1) {
1309
+ let res;
1310
+ try {
1311
+ res = await this.#fetch(`${this.#base}${path}`, {
1312
+ method,
1313
+ headers: { ...extra, ...agentHeader(undefined), authorization: this.#auth, accept: "application/json",
1314
+ ...(body === undefined ? {} : { "content-type": "application/json" }) },
1315
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
1316
+ });
1317
+ }
1318
+ catch (cause) {
1319
+ if (safe && attempt < this.#attempts) {
1320
+ await sleep(backoff(attempt));
1321
+ continue;
1322
+ }
1323
+ throw new SignSealerError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer", undefined, undefined);
1324
+ }
1325
+ const requestId = res.headers.get("x-request-id") ?? undefined;
1326
+ const text = await res.text();
1327
+ const parsed = text ? safeJson(text) : {};
1328
+ if (res.ok)
1329
+ return parsed;
1330
+ const err = parsed.error;
1331
+ const failure = new SignSealerError(res.status, err?.code ?? "unknown", err?.message ?? `SignSealer returned ${res.status}`, err?.hint, requestId, waitAsked(res.headers.get("retry-after")));
1332
+ if (!safe || !failure.retryable || attempt >= this.#attempts)
1333
+ throw failure;
1334
+ await sleep(backoff(attempt));
1335
+ }
1336
+ }
1146
1337
  /*
1147
1338
  Every call only reads, so a transient failure is retried as it is: there
1148
1339
  is nothing a second GET could do twice.
@@ -1153,7 +1344,7 @@ class SignSealerPartner {
1153
1344
  try {
1154
1345
  res = await this.#fetch(`${this.#base}${path}`, {
1155
1346
  method: "GET",
1156
- headers: { authorization: this.#auth, accept: "application/json" },
1347
+ headers: { ...agentHeader(undefined), authorization: this.#auth, accept: "application/json" },
1157
1348
  });
1158
1349
  }
1159
1350
  catch (cause) {
@@ -1230,6 +1421,299 @@ function safeJson(text) {
1230
1421
  return {};
1231
1422
  }
1232
1423
  }
1424
+ /**
1425
+ * A refusal from the OAuth endpoints, or from the consent screen's answer.
1426
+ *
1427
+ * `code` is RFC 6749's `error` and `message` its `error_description` (both
1428
+ * also under their RFC names). Two questions decide what to do:
1429
+ *
1430
+ * - `reconnect`: the grant is over, or the code is spent. `invalid_grant`
1431
+ * -- the business disconnected you, the person who connected you can no
1432
+ * longer give what you hold, a token or code was used twice, or it
1433
+ * expired. Send the business through `authorizeUrl` again; nothing else
1434
+ * will bring it back.
1435
+ * - `transient`: the network or SignSealer, not your request. The grant may
1436
+ * well still be good. On a refresh, **whether the token was spent is
1437
+ * unknown**: read `refresh()` before deciding to send it again.
1438
+ *
1439
+ * `invalid_client` is neither: your client id or secret did not
1440
+ * authenticate, which is your configuration, for every business at once.
1441
+ *
1442
+ * `retryable` is always false. SignSealerError's "worth trying again
1443
+ * unchanged" is exactly the advice that turns a lost answer into a revoked
1444
+ * grant here.
1445
+ */
1446
+ class SignSealerOAuthError extends SignSealerError {
1447
+ constructor(status, code, message, requestId, retryAfter) {
1448
+ super(status, code, message, undefined, requestId, retryAfter);
1449
+ this.name = "SignSealerOAuthError";
1450
+ }
1451
+ /** RFC 6749's name for `code`. */
1452
+ get error() {
1453
+ return this.code;
1454
+ }
1455
+ /** RFC 6749's name for `message`. */
1456
+ get errorDescription() {
1457
+ return this.message;
1458
+ }
1459
+ get retryable() {
1460
+ return false;
1461
+ }
1462
+ /** The grant is over or the code spent: send the business to connect again. */
1463
+ get reconnect() {
1464
+ return this.code === "invalid_grant";
1465
+ }
1466
+ /** The network or SignSealer failed, not the request. On a refresh, the token may or may not have been spent. */
1467
+ get transient() {
1468
+ return this.status === 0 || this.status === 429 || this.status >= 500;
1469
+ }
1470
+ }
1471
+ exports.SignSealerOAuthError = SignSealerOAuthError;
1472
+ /** The characters RFC 7636 allows in a verifier, 43 to 128 of them. */
1473
+ const VERIFIER = /^[A-Za-z0-9\-._~]{43,128}$/;
1474
+ /**
1475
+ * Random bytes from wherever this runtime keeps them: the global WebCrypto,
1476
+ * then `node:crypto` for Node 18, assembled at run time for the reason
1477
+ * `webCrypto()` gives.
1478
+ */
1479
+ let randomPromise = null;
1480
+ async function randomBytes(n) {
1481
+ randomPromise ??= (async () => {
1482
+ const here = globalThis.crypto;
1483
+ if (typeof here?.getRandomValues === "function")
1484
+ return (k) => here.getRandomValues(new Uint8Array(k));
1485
+ try {
1486
+ const mod = await Promise.resolve(`${"node:" + "crypto"}`).then(s => __importStar(require(s)));
1487
+ const web = mod.webcrypto;
1488
+ if (typeof web?.getRandomValues === "function")
1489
+ return (k) => web.getRandomValues(new Uint8Array(k));
1490
+ }
1491
+ catch {
1492
+ /* Not Node. The error below is the honest answer. */
1493
+ }
1494
+ throw new Error("no crypto.getRandomValues in this runtime, so a PKCE verifier cannot be made"
1495
+ + " — every current browser, edge runtime and Node 19 or later has it,"
1496
+ + " and Node 18 reaches it through node:crypto");
1497
+ })();
1498
+ return (await randomPromise)(n);
1499
+ }
1500
+ /**
1501
+ * A fresh PKCE pair, one per authorise request: 32 random bytes as a
1502
+ * 43-character verifier, and its S256 challenge.
1503
+ *
1504
+ * Keep the verifier on your server, against the `state` you send (a
1505
+ * session, or a short-lived row), and give it to `exchangeCode`. Never put
1506
+ * it in the authorise address: the challenge goes there, and the verifier
1507
+ * is what proves the code came back to the same party that asked.
1508
+ */
1509
+ async function createPkce() {
1510
+ const verifier = base64url(await randomBytes(32));
1511
+ return { verifier, challenge: await pkceChallenge(verifier), method: "S256" };
1512
+ }
1513
+ /** The S256 challenge for a verifier: base64url of its SHA-256, without padding (RFC 7636, section 4.2). */
1514
+ async function pkceChallenge(verifier) {
1515
+ if (!VERIFIER.test(verifier)) {
1516
+ throw new Error("a PKCE verifier is 43 to 128 of A-Z, a-z, 0-9 and - . _ ~");
1517
+ }
1518
+ const digest = await (await webCrypto()).digest("SHA-256", new TextEncoder().encode(verifier));
1519
+ return base64url(new Uint8Array(digest));
1520
+ }
1521
+ /**
1522
+ * "Connect with SignSealer", for a partner's server (1.20.0).
1523
+ *
1524
+ * ```ts
1525
+ * const oauth = new SignSealerOAuth({ clientId, clientSecret });
1526
+ * const { verifier, challenge } = await createPkce();
1527
+ * redirect(oauth.authorizeUrl({ redirectUri, scopes: ["signing:read", "signing:write"], state, codeChallenge: challenge }));
1528
+ * // …and on the way back:
1529
+ * const { code } = oauth.callback(request.url, savedState);
1530
+ * const tokens = await oauth.exchangeCode({ code, redirectUri, codeVerifier: verifier });
1531
+ * const client = new SignSealer({ apiKey: tokens.access_token });
1532
+ * ```
1533
+ *
1534
+ * The client is authenticated to `/oauth/token` by HTTP Basic, which RFC
1535
+ * 6749 prefers and the server reads first. Every token request is sent
1536
+ * exactly once: see `refresh()` for why that is the whole point.
1537
+ */
1538
+ class SignSealerOAuth {
1539
+ #auth;
1540
+ #base;
1541
+ #clientId;
1542
+ #fetch;
1543
+ constructor(opts) {
1544
+ if (!opts?.clientId || !opts?.clientSecret) {
1545
+ throw new Error("an OAuth client needs its clientId and clientSecret");
1546
+ }
1547
+ if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
1548
+ throw new Error("that is a business's API key; OAuth takes your client id and secret");
1549
+ }
1550
+ this.#clientId = opts.clientId;
1551
+ /* Each half form-encoded before joining (RFC 6749, 2.3.1), which is how the server decodes them. */
1552
+ const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1553
+ this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1554
+ this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
1555
+ this.#fetch = opts.fetch ?? globalThis.fetch;
1556
+ }
1557
+ /**
1558
+ * Where to send the business's browser. SignSealer signs them in (or lets
1559
+ * them make an account and name their business on the way), shows your
1560
+ * registered name and what each scope allows, and sends them back to
1561
+ * `redirectUri` with `code` and your `state`, or with `error`.
1562
+ *
1563
+ * `redirectUri` must be one you registered, byte for byte, and the same
1564
+ * string you give `exchangeCode`. `state` is yours, returned untouched:
1565
+ * make it unguessable, keep it with the verifier, and check it in
1566
+ * `callback`. Ask for the fewest scopes that do the job; a scope your
1567
+ * client was not registered with is refused as `invalid_scope`.
1568
+ */
1569
+ authorizeUrl(opts) {
1570
+ if (!opts?.redirectUri)
1571
+ throw new Error("authorizeUrl needs the redirectUri you registered");
1572
+ if (!opts.scopes?.length)
1573
+ throw new Error("authorizeUrl needs at least one scope");
1574
+ if (!opts.state)
1575
+ throw new Error("authorizeUrl needs a state, to check on the way back");
1576
+ if (!opts.codeChallenge || opts.codeChallenge.length < 43) {
1577
+ throw new Error("authorizeUrl needs the codeChallenge from createPkce(); PKCE is required");
1578
+ }
1579
+ const q = new URLSearchParams({
1580
+ response_type: "code",
1581
+ client_id: this.#clientId,
1582
+ redirect_uri: opts.redirectUri,
1583
+ scope: opts.scopes.join(" "),
1584
+ state: opts.state,
1585
+ code_challenge: opts.codeChallenge,
1586
+ code_challenge_method: "S256",
1587
+ });
1588
+ return `${this.#base}/oauth/authorize?${q}`;
1589
+ }
1590
+ /**
1591
+ * Read the consent screen's answer from your redirect's query: the code,
1592
+ * once `state` matches the one you kept. A business that pressed Not now
1593
+ * comes back as `access_denied`, and a request the screen could not
1594
+ * answer as its RFC 6749 error; both are thrown as SignSealerOAuthError,
1595
+ * with `status` 400. A `state` that does not match is `state_mismatch`:
1596
+ * do not exchange that code.
1597
+ */
1598
+ callback(query, expectedState) {
1599
+ const q = query instanceof URLSearchParams ? query
1600
+ : query instanceof URL ? query.searchParams
1601
+ : new URLSearchParams(query.includes("?") ? query.slice(query.indexOf("?") + 1) : query);
1602
+ const state = q.get("state") ?? "";
1603
+ if (!expectedState || !sameBytes(new TextEncoder().encode(state), new TextEncoder().encode(expectedState))) {
1604
+ throw new SignSealerOAuthError(400, "state_mismatch", "the state that came back is not the one this browser was sent with");
1605
+ }
1606
+ const error = q.get("error");
1607
+ if (error)
1608
+ throw new SignSealerOAuthError(400, error, q.get("error_description") ?? error);
1609
+ const code = q.get("code");
1610
+ if (!code)
1611
+ throw new SignSealerOAuthError(400, "invalid_request", "the answer carried neither a code nor an error");
1612
+ return { code };
1613
+ }
1614
+ /**
1615
+ * Exchange the code from `callback` for the business's tokens. Do it at
1616
+ * once: a code lives sixty seconds and is good once.
1617
+ *
1618
+ * Sent once and never again. A code presented twice is a replay, and the
1619
+ * server revokes the grant it made, so a retry after a lost answer would
1620
+ * disconnect the business it just connected. If this throws `transient`,
1621
+ * send the business through `authorizeUrl` again.
1622
+ */
1623
+ exchangeCode(opts) {
1624
+ if (!opts?.code || !opts.redirectUri || !opts.codeVerifier) {
1625
+ throw new Error("exchangeCode needs the code, the same redirectUri and the PKCE codeVerifier");
1626
+ }
1627
+ return this.#token({
1628
+ grant_type: "authorization_code",
1629
+ code: opts.code,
1630
+ redirect_uri: opts.redirectUri,
1631
+ code_verifier: opts.codeVerifier,
1632
+ });
1633
+ }
1634
+ /**
1635
+ * Swap a refresh token for a new access token **and a new refresh token**.
1636
+ *
1637
+ * **THIS IS NEVER RETRIED, AND YOU MUST NOT RETRY IT EITHER WITHOUT
1638
+ * THINKING.** The refresh token you send is spent the moment SignSealer
1639
+ * reads it. Presenting a spent one is treated as theft: the whole family
1640
+ * is revoked -- every refresh token from that connection, the grant, and
1641
+ * every access token issued under it -- and the business has to connect
1642
+ * again. From the server's side a buggy retry and a stolen token look the
1643
+ * same.
1644
+ *
1645
+ * So:
1646
+ *
1647
+ * 1. **Serialise refreshes per grant.** One at a time for each business
1648
+ * (a row lock, an advisory lock, a queue). Two workers refreshing the
1649
+ * same grant at once will end it.
1650
+ * 2. **Store the new refresh token before you use the access token**,
1651
+ * atomically, while still holding the lock. A new refresh token you
1652
+ * lose cannot be got back.
1653
+ * 3. **A `transient` failure leaves the token's state unknown.** If the
1654
+ * request reached SignSealer and the answer was lost, the token you
1655
+ * hold is spent and its successor lost with the answer; if it never
1656
+ * arrived, it is still good. Sending it again either works or ends
1657
+ * the connection (`reconnect`), which losing the successor had
1658
+ * already made inevitable. That is your decision, made under the
1659
+ * lock, never a loop.
1660
+ * 4. **`reconnect` means reconnect.** Mark the business disconnected and
1661
+ * ask them to connect again; do not try the token again.
1662
+ */
1663
+ refresh(refreshToken) {
1664
+ if (!refreshToken)
1665
+ throw new Error("refresh needs the refresh token you stored last");
1666
+ return this.#token({ grant_type: "refresh_token", refresh_token: refreshToken });
1667
+ }
1668
+ /*
1669
+ One request, one answer, no loop. Every other call in this package
1670
+ retries what is worth retrying; this one has nothing worth retrying,
1671
+ because both of its grants are spent by being read.
1672
+ */
1673
+ async #token(form) {
1674
+ const sentAt = Date.now();
1675
+ let res;
1676
+ try {
1677
+ res = await this.#fetch(`${this.#base}/oauth/token`, {
1678
+ method: "POST",
1679
+ headers: {
1680
+ authorization: this.#auth,
1681
+ "content-type": "application/x-www-form-urlencoded",
1682
+ accept: "application/json",
1683
+ },
1684
+ body: new URLSearchParams(form).toString(),
1685
+ });
1686
+ }
1687
+ catch (cause) {
1688
+ throw new SignSealerOAuthError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer");
1689
+ }
1690
+ const requestId = res.headers.get("x-request-id") ?? undefined;
1691
+ const text = await res.text();
1692
+ const parsed = (text ? safeJson(text) : {});
1693
+ if (res.ok && typeof parsed.access_token === "string") {
1694
+ const expiresIn = typeof parsed.expires_in === "number" ? parsed.expires_in : 3600;
1695
+ const scope = typeof parsed.scope === "string" ? parsed.scope : "";
1696
+ return {
1697
+ access_token: parsed.access_token,
1698
+ token_type: "Bearer",
1699
+ expires_in: expiresIn,
1700
+ expires_at: new Date(sentAt + expiresIn * 1000).toISOString(),
1701
+ scope,
1702
+ scopes: scope.split(" ").filter(Boolean),
1703
+ refresh_token: typeof parsed.refresh_token === "string" ? parsed.refresh_token : null,
1704
+ };
1705
+ }
1706
+ const code = typeof parsed.error === "string" ? parsed.error
1707
+ : res.status >= 500 ? "server_error"
1708
+ : res.status === 429 ? "temporarily_unavailable"
1709
+ : res.ok ? "server_error" : "invalid_request";
1710
+ const description = typeof parsed.error_description === "string" ? parsed.error_description
1711
+ : res.ok ? "SignSealer answered without an access token" : `SignSealer returned ${res.status}`;
1712
+ /* A 200 with no token is SignSealer's fault, and as unknown in its outcome as a 500. */
1713
+ throw new SignSealerOAuthError(res.ok ? 502 : res.status, code, description, requestId, waitAsked(res.headers.get("retry-after")));
1714
+ }
1715
+ }
1716
+ exports.SignSealerOAuth = SignSealerOAuth;
1233
1717
  /* ------------------------------------------------------- verifying a webhook
1234
1718
 
1235
1719
  The SDK could create a webhook endpoint and could not check a delivery from