@signsealer/sdk 1.16.0 → 1.22.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,9 +49,13 @@ 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.SignSealerError = void 0;
53
+ exports.createPkce = createPkce;
54
+ exports.pkceChallenge = pkceChallenge;
53
55
  exports.verifyWebhook = verifyWebhook;
54
56
  exports.verifyWebhookRequest = verifyWebhookRequest;
57
+ exports.sha256Hex = sha256Hex;
58
+ exports.createApproval = createApproval;
55
59
  class SignSealerError extends Error {
56
60
  status;
57
61
  code;
@@ -295,6 +299,21 @@ class SignSealer {
295
299
  textingNumberInvitation(prefill = {}) {
296
300
  return this.#call("POST", "/v1/texting/number/invitations", { prefill }, undefined, { once: true });
297
301
  }
302
+ /**
303
+ * Who texts the signers of documents sent through a partner's app, for a
304
+ * partner whose dashboard leaves it to each business (1.21.0).
305
+ *
306
+ * As the partner, with the business's access token, leave `clientId` out:
307
+ * the choice is yours for that business. With the business's own key, name
308
+ * the app by its `ss_client_…` id (the key needs `signing:webhooks`). With
309
+ * `partner` or `none`, SignSealer sends no texts for those documents -- no
310
+ * link, no reminder, no confirmation -- while email and webhooks go on as
311
+ * before; a one-time code a signer asks for is still sent. A PUT, so a
312
+ * retry after a lost answer sets the same thing again.
313
+ */
314
+ setTextingSender(sender, clientId) {
315
+ return this.#call("PUT", "/v1/texting/sender", clientId ? { sender, client_id: clientId } : { sender });
316
+ }
298
317
  /* ----------------------------------------------------------- documents */
299
318
  /**
300
319
  * Documents, filtered and paged.
@@ -374,6 +393,22 @@ class SignSealer {
374
393
  prepareDocument(input, idempotencyKey) {
375
394
  return this.#call("POST", "/v1/documents", input, idempotencyKey);
376
395
  }
396
+ /**
397
+ * A document from a PDF and the places to sign it, in one call (1.19.0,
398
+ * 00685): the file is read, sanitised and drawn as a dashboard upload is,
399
+ * kept as a one-time template, and the document prepared as a draft.
400
+ * Each box is one `recipient`'s -- the `sign_order` you give that signer
401
+ * on `send()` -- given in `fields` (fractions of the page, from its
402
+ * top-left) or found from text tags in the file's words with
403
+ * `text_tags: true` (`{{signature:1}}`, `{{date:1}}`, `{{initials:2}}`,
404
+ * `{{text:1:Job number}}`, `{{checkbox:2:Label}}`). Needs `signing:templates`
405
+ * and `signing:send` on the key. `pdf` is the file's bytes or its base64.
406
+ */
407
+ documentFromPdf(input, idempotencyKey) {
408
+ const { pdf, ...rest } = input;
409
+ const pdf_base64 = typeof pdf === "string" ? pdf : bytesToBase64(pdf);
410
+ return this.#call("POST", "/v1/documents/from-pdf", { ...rest, pdf_base64 }, idempotencyKey);
411
+ }
377
412
  /**
378
413
  * Send, and take the links back once.
379
414
  *
@@ -518,6 +553,16 @@ class SignSealer {
518
553
  webhooks() {
519
554
  return this.#call("GET", "/v1/webhooks");
520
555
  }
556
+ /**
557
+ * Make sure an endpoint is registered for an address (1.19.0, 00685): the
558
+ * business's endpoint for `url`, its events and label set to these, or a
559
+ * new one when it has none -- so calling it on every start-up never makes
560
+ * a second. `created` says which; `secret` is there only when it is new.
561
+ * An endpoint the business turned off stays off (`active`, `paused`).
562
+ */
563
+ ensureWebhook(input) {
564
+ return this.#call("PUT", "/v1/webhooks", input);
565
+ }
521
566
  addWebhook(input, idempotencyKey) {
522
567
  return this.#call("POST", "/v1/webhooks", input, idempotencyKey);
523
568
  }
@@ -652,6 +697,65 @@ class SignSealer {
652
697
  reportProblem(input) {
653
698
  return this.#call("POST", "/v1/devices/report", input, undefined, { once: true });
654
699
  }
700
+ /* --------------------------------------- trusted applications (1.18.0) */
701
+ /**
702
+ * The business's own applications whose servers vouch for their people's
703
+ * approvals, each with its public keys (00684). Needs `signing:applications`.
704
+ */
705
+ async signingApplications() {
706
+ const out = await this.#call("GET", "/v1/signing-applications");
707
+ return out.applications;
708
+ }
709
+ /** Register an application. Then register the public key it signs approvals with. */
710
+ addSigningApplication(name, idempotencyKey) {
711
+ return this.#call("POST", "/v1/signing-applications", { name }, idempotencyKey);
712
+ }
713
+ /**
714
+ * Register a public key, as a JWK: EC P-256 for ES256, OKP Ed25519 for
715
+ * EdDSA. Only the public half; one with `d` is refused. `kid` defaults to
716
+ * the key's RFC 7638 thumbprint.
717
+ */
718
+ addSigningApplicationKey(applicationId, input, idempotencyKey) {
719
+ return this.#call("POST", `/v1/signing-applications/${encodeURIComponent(applicationId)}/keys`, input, idempotencyKey);
720
+ }
721
+ /** Revoke a key: every approval it signed and has not sent is refused from now on. */
722
+ revokeSigningApplicationKey(applicationId, keyId, reason) {
723
+ return this.#call("DELETE", `/v1/signing-applications/${encodeURIComponent(applicationId)}/keys/${encodeURIComponent(keyId)}?reason=${encodeURIComponent(reason)}`);
724
+ }
725
+ /** Disable an application: every approval from it is refused from now on. */
726
+ disableSigningApplication(applicationId, reason) {
727
+ return this.#call("POST", `/v1/signing-applications/${encodeURIComponent(applicationId)}/disable`, { reason }, undefined, { once: true });
728
+ }
729
+ /**
730
+ * Hand over one person's saved signature for one signing, server to
731
+ * server (00684). The reference is single-use, short-lived and bound to
732
+ * the application and the person; the image is never served back.
733
+ * Possession of the reference authorises nothing on its own: only an
734
+ * approval from the same application naming the same person, with
735
+ * `signature.sha256` equal to `sha256` here, spends it. Needs
736
+ * `signing:assert`.
737
+ */
738
+ addSignatureReference(input) {
739
+ return this.#call("POST", "/v1/signature-references", input, undefined, { once: true });
740
+ }
741
+ /**
742
+ * Sign with an approval your application's server signed (`createApproval`).
743
+ * Recorded as authenticated by your application, never as an identity
744
+ * SignSealer checked. The same approval sent again answers with the
745
+ * signing it made (`replayed: true`); retried with the same idempotency
746
+ * key, the stored answer. Needs `signing:assert`.
747
+ */
748
+ signWithApproval(input, idempotencyKey) {
749
+ return this.#call("POST", "/v1/signing-transactions", input, idempotencyKey);
750
+ }
751
+ /** One signing an approval made. */
752
+ signingTransaction(id) {
753
+ return this.#call("GET", `/v1/signing-transactions/${encodeURIComponent(id)}`);
754
+ }
755
+ /** The signing an approval made, by your application's id and the approval's `jti`: for a client that lost the answer. */
756
+ signingTransactionByApproval(applicationId, approvalId) {
757
+ return this.#call("GET", `/v1/signing-transactions?application_id=${encodeURIComponent(applicationId)}&approval_id=${encodeURIComponent(approvalId)}`);
758
+ }
655
759
  /* ------------------------------------------------------------ the wire */
656
760
  async #call(method, path, body, idempotencyKey,
657
761
  /**
@@ -1143,6 +1247,299 @@ function safeJson(text) {
1143
1247
  return {};
1144
1248
  }
1145
1249
  }
1250
+ /**
1251
+ * A refusal from the OAuth endpoints, or from the consent screen's answer.
1252
+ *
1253
+ * `code` is RFC 6749's `error` and `message` its `error_description` (both
1254
+ * also under their RFC names). Two questions decide what to do:
1255
+ *
1256
+ * - `reconnect`: the grant is over, or the code is spent. `invalid_grant`
1257
+ * -- the business disconnected you, the person who connected you can no
1258
+ * longer give what you hold, a token or code was used twice, or it
1259
+ * expired. Send the business through `authorizeUrl` again; nothing else
1260
+ * will bring it back.
1261
+ * - `transient`: the network or SignSealer, not your request. The grant may
1262
+ * well still be good. On a refresh, **whether the token was spent is
1263
+ * unknown**: read `refresh()` before deciding to send it again.
1264
+ *
1265
+ * `invalid_client` is neither: your client id or secret did not
1266
+ * authenticate, which is your configuration, for every business at once.
1267
+ *
1268
+ * `retryable` is always false. SignSealerError's "worth trying again
1269
+ * unchanged" is exactly the advice that turns a lost answer into a revoked
1270
+ * grant here.
1271
+ */
1272
+ class SignSealerOAuthError extends SignSealerError {
1273
+ constructor(status, code, message, requestId, retryAfter) {
1274
+ super(status, code, message, undefined, requestId, retryAfter);
1275
+ this.name = "SignSealerOAuthError";
1276
+ }
1277
+ /** RFC 6749's name for `code`. */
1278
+ get error() {
1279
+ return this.code;
1280
+ }
1281
+ /** RFC 6749's name for `message`. */
1282
+ get errorDescription() {
1283
+ return this.message;
1284
+ }
1285
+ get retryable() {
1286
+ return false;
1287
+ }
1288
+ /** The grant is over or the code spent: send the business to connect again. */
1289
+ get reconnect() {
1290
+ return this.code === "invalid_grant";
1291
+ }
1292
+ /** The network or SignSealer failed, not the request. On a refresh, the token may or may not have been spent. */
1293
+ get transient() {
1294
+ return this.status === 0 || this.status === 429 || this.status >= 500;
1295
+ }
1296
+ }
1297
+ exports.SignSealerOAuthError = SignSealerOAuthError;
1298
+ /** The characters RFC 7636 allows in a verifier, 43 to 128 of them. */
1299
+ const VERIFIER = /^[A-Za-z0-9\-._~]{43,128}$/;
1300
+ /**
1301
+ * Random bytes from wherever this runtime keeps them: the global WebCrypto,
1302
+ * then `node:crypto` for Node 18, assembled at run time for the reason
1303
+ * `webCrypto()` gives.
1304
+ */
1305
+ let randomPromise = null;
1306
+ async function randomBytes(n) {
1307
+ randomPromise ??= (async () => {
1308
+ const here = globalThis.crypto;
1309
+ if (typeof here?.getRandomValues === "function")
1310
+ return (k) => here.getRandomValues(new Uint8Array(k));
1311
+ try {
1312
+ const mod = await Promise.resolve(`${"node:" + "crypto"}`).then(s => __importStar(require(s)));
1313
+ const web = mod.webcrypto;
1314
+ if (typeof web?.getRandomValues === "function")
1315
+ return (k) => web.getRandomValues(new Uint8Array(k));
1316
+ }
1317
+ catch {
1318
+ /* Not Node. The error below is the honest answer. */
1319
+ }
1320
+ throw new Error("no crypto.getRandomValues in this runtime, so a PKCE verifier cannot be made"
1321
+ + " — every current browser, edge runtime and Node 19 or later has it,"
1322
+ + " and Node 18 reaches it through node:crypto");
1323
+ })();
1324
+ return (await randomPromise)(n);
1325
+ }
1326
+ /**
1327
+ * A fresh PKCE pair, one per authorise request: 32 random bytes as a
1328
+ * 43-character verifier, and its S256 challenge.
1329
+ *
1330
+ * Keep the verifier on your server, against the `state` you send (a
1331
+ * session, or a short-lived row), and give it to `exchangeCode`. Never put
1332
+ * it in the authorise address: the challenge goes there, and the verifier
1333
+ * is what proves the code came back to the same party that asked.
1334
+ */
1335
+ async function createPkce() {
1336
+ const verifier = base64url(await randomBytes(32));
1337
+ return { verifier, challenge: await pkceChallenge(verifier), method: "S256" };
1338
+ }
1339
+ /** The S256 challenge for a verifier: base64url of its SHA-256, without padding (RFC 7636, section 4.2). */
1340
+ async function pkceChallenge(verifier) {
1341
+ if (!VERIFIER.test(verifier)) {
1342
+ throw new Error("a PKCE verifier is 43 to 128 of A-Z, a-z, 0-9 and - . _ ~");
1343
+ }
1344
+ const digest = await (await webCrypto()).digest("SHA-256", new TextEncoder().encode(verifier));
1345
+ return base64url(new Uint8Array(digest));
1346
+ }
1347
+ /**
1348
+ * "Connect with SignSealer", for a partner's server (1.20.0).
1349
+ *
1350
+ * ```ts
1351
+ * const oauth = new SignSealerOAuth({ clientId, clientSecret });
1352
+ * const { verifier, challenge } = await createPkce();
1353
+ * redirect(oauth.authorizeUrl({ redirectUri, scopes: ["signing:read", "signing:write"], state, codeChallenge: challenge }));
1354
+ * // …and on the way back:
1355
+ * const { code } = oauth.callback(request.url, savedState);
1356
+ * const tokens = await oauth.exchangeCode({ code, redirectUri, codeVerifier: verifier });
1357
+ * const client = new SignSealer({ apiKey: tokens.access_token });
1358
+ * ```
1359
+ *
1360
+ * The client is authenticated to `/oauth/token` by HTTP Basic, which RFC
1361
+ * 6749 prefers and the server reads first. Every token request is sent
1362
+ * exactly once: see `refresh()` for why that is the whole point.
1363
+ */
1364
+ class SignSealerOAuth {
1365
+ #auth;
1366
+ #base;
1367
+ #clientId;
1368
+ #fetch;
1369
+ constructor(opts) {
1370
+ if (!opts?.clientId || !opts?.clientSecret) {
1371
+ throw new Error("an OAuth client needs its clientId and clientSecret");
1372
+ }
1373
+ if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
1374
+ throw new Error("that is a business's API key; OAuth takes your client id and secret");
1375
+ }
1376
+ this.#clientId = opts.clientId;
1377
+ /* Each half form-encoded before joining (RFC 6749, 2.3.1), which is how the server decodes them. */
1378
+ const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1379
+ this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1380
+ this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
1381
+ this.#fetch = opts.fetch ?? globalThis.fetch;
1382
+ }
1383
+ /**
1384
+ * Where to send the business's browser. SignSealer signs them in (or lets
1385
+ * them make an account and name their business on the way), shows your
1386
+ * registered name and what each scope allows, and sends them back to
1387
+ * `redirectUri` with `code` and your `state`, or with `error`.
1388
+ *
1389
+ * `redirectUri` must be one you registered, byte for byte, and the same
1390
+ * string you give `exchangeCode`. `state` is yours, returned untouched:
1391
+ * make it unguessable, keep it with the verifier, and check it in
1392
+ * `callback`. Ask for the fewest scopes that do the job; a scope your
1393
+ * client was not registered with is refused as `invalid_scope`.
1394
+ */
1395
+ authorizeUrl(opts) {
1396
+ if (!opts?.redirectUri)
1397
+ throw new Error("authorizeUrl needs the redirectUri you registered");
1398
+ if (!opts.scopes?.length)
1399
+ throw new Error("authorizeUrl needs at least one scope");
1400
+ if (!opts.state)
1401
+ throw new Error("authorizeUrl needs a state, to check on the way back");
1402
+ if (!opts.codeChallenge || opts.codeChallenge.length < 43) {
1403
+ throw new Error("authorizeUrl needs the codeChallenge from createPkce(); PKCE is required");
1404
+ }
1405
+ const q = new URLSearchParams({
1406
+ response_type: "code",
1407
+ client_id: this.#clientId,
1408
+ redirect_uri: opts.redirectUri,
1409
+ scope: opts.scopes.join(" "),
1410
+ state: opts.state,
1411
+ code_challenge: opts.codeChallenge,
1412
+ code_challenge_method: "S256",
1413
+ });
1414
+ return `${this.#base}/oauth/authorize?${q}`;
1415
+ }
1416
+ /**
1417
+ * Read the consent screen's answer from your redirect's query: the code,
1418
+ * once `state` matches the one you kept. A business that pressed Not now
1419
+ * comes back as `access_denied`, and a request the screen could not
1420
+ * answer as its RFC 6749 error; both are thrown as SignSealerOAuthError,
1421
+ * with `status` 400. A `state` that does not match is `state_mismatch`:
1422
+ * do not exchange that code.
1423
+ */
1424
+ callback(query, expectedState) {
1425
+ const q = query instanceof URLSearchParams ? query
1426
+ : query instanceof URL ? query.searchParams
1427
+ : new URLSearchParams(query.includes("?") ? query.slice(query.indexOf("?") + 1) : query);
1428
+ const state = q.get("state") ?? "";
1429
+ if (!expectedState || !sameBytes(new TextEncoder().encode(state), new TextEncoder().encode(expectedState))) {
1430
+ throw new SignSealerOAuthError(400, "state_mismatch", "the state that came back is not the one this browser was sent with");
1431
+ }
1432
+ const error = q.get("error");
1433
+ if (error)
1434
+ throw new SignSealerOAuthError(400, error, q.get("error_description") ?? error);
1435
+ const code = q.get("code");
1436
+ if (!code)
1437
+ throw new SignSealerOAuthError(400, "invalid_request", "the answer carried neither a code nor an error");
1438
+ return { code };
1439
+ }
1440
+ /**
1441
+ * Exchange the code from `callback` for the business's tokens. Do it at
1442
+ * once: a code lives sixty seconds and is good once.
1443
+ *
1444
+ * Sent once and never again. A code presented twice is a replay, and the
1445
+ * server revokes the grant it made, so a retry after a lost answer would
1446
+ * disconnect the business it just connected. If this throws `transient`,
1447
+ * send the business through `authorizeUrl` again.
1448
+ */
1449
+ exchangeCode(opts) {
1450
+ if (!opts?.code || !opts.redirectUri || !opts.codeVerifier) {
1451
+ throw new Error("exchangeCode needs the code, the same redirectUri and the PKCE codeVerifier");
1452
+ }
1453
+ return this.#token({
1454
+ grant_type: "authorization_code",
1455
+ code: opts.code,
1456
+ redirect_uri: opts.redirectUri,
1457
+ code_verifier: opts.codeVerifier,
1458
+ });
1459
+ }
1460
+ /**
1461
+ * Swap a refresh token for a new access token **and a new refresh token**.
1462
+ *
1463
+ * **THIS IS NEVER RETRIED, AND YOU MUST NOT RETRY IT EITHER WITHOUT
1464
+ * THINKING.** The refresh token you send is spent the moment SignSealer
1465
+ * reads it. Presenting a spent one is treated as theft: the whole family
1466
+ * is revoked -- every refresh token from that connection, the grant, and
1467
+ * every access token issued under it -- and the business has to connect
1468
+ * again. From the server's side a buggy retry and a stolen token look the
1469
+ * same.
1470
+ *
1471
+ * So:
1472
+ *
1473
+ * 1. **Serialise refreshes per grant.** One at a time for each business
1474
+ * (a row lock, an advisory lock, a queue). Two workers refreshing the
1475
+ * same grant at once will end it.
1476
+ * 2. **Store the new refresh token before you use the access token**,
1477
+ * atomically, while still holding the lock. A new refresh token you
1478
+ * lose cannot be got back.
1479
+ * 3. **A `transient` failure leaves the token's state unknown.** If the
1480
+ * request reached SignSealer and the answer was lost, the token you
1481
+ * hold is spent and its successor lost with the answer; if it never
1482
+ * arrived, it is still good. Sending it again either works or ends
1483
+ * the connection (`reconnect`), which losing the successor had
1484
+ * already made inevitable. That is your decision, made under the
1485
+ * lock, never a loop.
1486
+ * 4. **`reconnect` means reconnect.** Mark the business disconnected and
1487
+ * ask them to connect again; do not try the token again.
1488
+ */
1489
+ refresh(refreshToken) {
1490
+ if (!refreshToken)
1491
+ throw new Error("refresh needs the refresh token you stored last");
1492
+ return this.#token({ grant_type: "refresh_token", refresh_token: refreshToken });
1493
+ }
1494
+ /*
1495
+ One request, one answer, no loop. Every other call in this package
1496
+ retries what is worth retrying; this one has nothing worth retrying,
1497
+ because both of its grants are spent by being read.
1498
+ */
1499
+ async #token(form) {
1500
+ const sentAt = Date.now();
1501
+ let res;
1502
+ try {
1503
+ res = await this.#fetch(`${this.#base}/oauth/token`, {
1504
+ method: "POST",
1505
+ headers: {
1506
+ authorization: this.#auth,
1507
+ "content-type": "application/x-www-form-urlencoded",
1508
+ accept: "application/json",
1509
+ },
1510
+ body: new URLSearchParams(form).toString(),
1511
+ });
1512
+ }
1513
+ catch (cause) {
1514
+ throw new SignSealerOAuthError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer");
1515
+ }
1516
+ const requestId = res.headers.get("x-request-id") ?? undefined;
1517
+ const text = await res.text();
1518
+ const parsed = (text ? safeJson(text) : {});
1519
+ if (res.ok && typeof parsed.access_token === "string") {
1520
+ const expiresIn = typeof parsed.expires_in === "number" ? parsed.expires_in : 3600;
1521
+ const scope = typeof parsed.scope === "string" ? parsed.scope : "";
1522
+ return {
1523
+ access_token: parsed.access_token,
1524
+ token_type: "Bearer",
1525
+ expires_in: expiresIn,
1526
+ expires_at: new Date(sentAt + expiresIn * 1000).toISOString(),
1527
+ scope,
1528
+ scopes: scope.split(" ").filter(Boolean),
1529
+ refresh_token: typeof parsed.refresh_token === "string" ? parsed.refresh_token : null,
1530
+ };
1531
+ }
1532
+ const code = typeof parsed.error === "string" ? parsed.error
1533
+ : res.status >= 500 ? "server_error"
1534
+ : res.status === 429 ? "temporarily_unavailable"
1535
+ : res.ok ? "server_error" : "invalid_request";
1536
+ const description = typeof parsed.error_description === "string" ? parsed.error_description
1537
+ : res.ok ? "SignSealer answered without an access token" : `SignSealer returned ${res.status}`;
1538
+ /* A 200 with no token is SignSealer's fault, and as unknown in its outcome as a 500. */
1539
+ throw new SignSealerOAuthError(res.ok ? 502 : res.status, code, description, requestId, waitAsked(res.headers.get("retry-after")));
1540
+ }
1541
+ }
1542
+ exports.SignSealerOAuth = SignSealerOAuth;
1146
1543
  /* ------------------------------------------------------- verifying a webhook
1147
1544
 
1148
1545
  The SDK could create a webhook endpoint and could not check a delivery from
@@ -1394,4 +1791,84 @@ async function verifyWebhookRequest(opts) {
1394
1791
  });
1395
1792
  return { ...result, eventId: headerOf(opts.headers, exports.WEBHOOK_EVENT_HEADER) };
1396
1793
  }
1794
+ const APPROVAL_TYP = "signsealer-approval+jwt";
1795
+ function base64url(bytes) {
1796
+ let bin = "";
1797
+ for (let i = 0; i < bytes.length; i++)
1798
+ bin += String.fromCharCode(bytes[i]);
1799
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1800
+ }
1801
+ const seconds = (t) => Math.floor((t instanceof Date ? t.getTime() : t) / 1000);
1802
+ /** Spaces off both ends, and only spaces, as the server's trim() does; a loop, not /^ +| +$/, which is slow on a long run of them. */
1803
+ function trimSpaces(s) {
1804
+ let start = 0;
1805
+ let end = s.length;
1806
+ while (start < end && s.charCodeAt(start) === 32)
1807
+ start++;
1808
+ while (end > start && s.charCodeAt(end - 1) === 32)
1809
+ end--;
1810
+ return s.slice(start, end);
1811
+ }
1812
+ /** SHA-256 of a string's UTF-8, as lowercase hex: a signature's, or a document's text. */
1813
+ async function sha256Hex(text) {
1814
+ const digest = await (await webCrypto()).digest("SHA-256", new TextEncoder().encode(text));
1815
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
1816
+ }
1817
+ /**
1818
+ * Sign one approval with your application's private key: a compact JWS
1819
+ * that `signWithApproval` sends. `privateKey` is a WebCrypto key or a
1820
+ * private JWK -- ECDSA P-256 (ES256) or Ed25519 (EdDSA) -- and `kid` the
1821
+ * name you registered its public half under.
1822
+ *
1823
+ * Make one per approval, when the person approves, and send it at once: it
1824
+ * lives two minutes by default and five at most, and its `jti` is spent by
1825
+ * the signing it makes.
1826
+ */
1827
+ async function createApproval(opts) {
1828
+ const subtle = await webCrypto();
1829
+ const a = opts.approval;
1830
+ let key = opts.privateKey;
1831
+ if (!(typeof opts.privateKey.type === "string" && opts.privateKey.algorithm)) {
1832
+ const jwk = opts.privateKey;
1833
+ const params = jwk.kty === "OKP" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: "P-256" };
1834
+ key = await subtle.importKey("jwk", jwk, params, false, ["sign"]);
1835
+ }
1836
+ const ed = key.algorithm.name === "Ed25519";
1837
+ if (!ed && !(key.algorithm.name === "ECDSA" && key.algorithm.namedCurve === "P-256")) {
1838
+ throw new Error("an approval is signed with an ECDSA P-256 (ES256) or an Ed25519 (EdDSA) key");
1839
+ }
1840
+ const ttl = Math.min(Math.max(a.ttlSeconds ?? 120, 1), 300);
1841
+ const iat = seconds(opts.now ?? Date.now());
1842
+ const approvalId = a.approvalId ?? `apr_${(await randomUuid()).replace(/-/g, "")}`;
1843
+ const signatureSha = a.signature.method === "saved" ? a.signature.sha256
1844
+ /* Spaces trimmed as the server trims a typed signature, so the hash is of what it keeps. */
1845
+ : await sha256Hex(a.signature.method === "drawn" ? a.signature.image : trimSpaces(a.signature.text));
1846
+ const claims = {
1847
+ iss: a.applicationId,
1848
+ aud: "signsealer",
1849
+ tenant_id: a.tenantId,
1850
+ sub: a.person.subject,
1851
+ name: a.person.name,
1852
+ amr: a.auth.methods,
1853
+ ...(a.auth.level ? { acr: a.auth.level } : {}),
1854
+ auth_time: seconds(a.auth.at),
1855
+ approved_at: seconds(a.approvedAt),
1856
+ iat,
1857
+ exp: iat + ttl,
1858
+ jti: approvalId,
1859
+ document_id: a.documentId,
1860
+ document_sha256: a.documentSha256.toLowerCase(),
1861
+ ...(a.signerId ? { signer_id: a.signerId } : {}),
1862
+ signature: { method: a.signature.method, sha256: signatureSha },
1863
+ consent: true,
1864
+ origin: a.origin ?? "online",
1865
+ ...(a.ip ? { ip: a.ip } : {}),
1866
+ ...(a.device ? { device: a.device } : {}),
1867
+ };
1868
+ const enc = new TextEncoder();
1869
+ const input = `${base64url(enc.encode(JSON.stringify({ alg: ed ? "EdDSA" : "ES256", typ: APPROVAL_TYP, kid: opts.kid })))}.${base64url(enc.encode(JSON.stringify(claims)))}`;
1870
+ /* WebCrypto's ECDSA signature is r||s, which is what JWS wants. */
1871
+ const sig = await subtle.sign(ed ? { name: "Ed25519" } : { name: "ECDSA", hash: "SHA-256" }, key, enc.encode(input));
1872
+ return { assertion: `${input}.${base64url(new Uint8Array(sig))}`, approvalId, claims };
1873
+ }
1397
1874
  //# sourceMappingURL=index.cjs.map