@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.
package/dist/esm/index.js CHANGED
@@ -256,6 +256,21 @@ export class SignSealer {
256
256
  textingNumberInvitation(prefill = {}) {
257
257
  return this.#call("POST", "/v1/texting/number/invitations", { prefill }, undefined, { once: true });
258
258
  }
259
+ /**
260
+ * Who texts the signers of documents sent through a partner's app, for a
261
+ * partner whose dashboard leaves it to each business (1.21.0).
262
+ *
263
+ * As the partner, with the business's access token, leave `clientId` out:
264
+ * the choice is yours for that business. With the business's own key, name
265
+ * the app by its `ss_client_…` id (the key needs `signing:webhooks`). With
266
+ * `partner` or `none`, SignSealer sends no texts for those documents -- no
267
+ * link, no reminder, no confirmation -- while email and webhooks go on as
268
+ * before; a one-time code a signer asks for is still sent. A PUT, so a
269
+ * retry after a lost answer sets the same thing again.
270
+ */
271
+ setTextingSender(sender, clientId) {
272
+ return this.#call("PUT", "/v1/texting/sender", clientId ? { sender, client_id: clientId } : { sender });
273
+ }
259
274
  /* ----------------------------------------------------------- documents */
260
275
  /**
261
276
  * Documents, filtered and paged.
@@ -335,6 +350,22 @@ export class SignSealer {
335
350
  prepareDocument(input, idempotencyKey) {
336
351
  return this.#call("POST", "/v1/documents", input, idempotencyKey);
337
352
  }
353
+ /**
354
+ * A document from a PDF and the places to sign it, in one call (1.19.0,
355
+ * 00685): the file is read, sanitised and drawn as a dashboard upload is,
356
+ * kept as a one-time template, and the document prepared as a draft.
357
+ * Each box is one `recipient`'s -- the `sign_order` you give that signer
358
+ * on `send()` -- given in `fields` (fractions of the page, from its
359
+ * top-left) or found from text tags in the file's words with
360
+ * `text_tags: true` (`{{signature:1}}`, `{{date:1}}`, `{{initials:2}}`,
361
+ * `{{text:1:Job number}}`, `{{checkbox:2:Label}}`). Needs `signing:templates`
362
+ * and `signing:send` on the key. `pdf` is the file's bytes or its base64.
363
+ */
364
+ documentFromPdf(input, idempotencyKey) {
365
+ const { pdf, ...rest } = input;
366
+ const pdf_base64 = typeof pdf === "string" ? pdf : bytesToBase64(pdf);
367
+ return this.#call("POST", "/v1/documents/from-pdf", { ...rest, pdf_base64 }, idempotencyKey);
368
+ }
338
369
  /**
339
370
  * Send, and take the links back once.
340
371
  *
@@ -479,6 +510,16 @@ export class SignSealer {
479
510
  webhooks() {
480
511
  return this.#call("GET", "/v1/webhooks");
481
512
  }
513
+ /**
514
+ * Make sure an endpoint is registered for an address (1.19.0, 00685): the
515
+ * business's endpoint for `url`, its events and label set to these, or a
516
+ * new one when it has none -- so calling it on every start-up never makes
517
+ * a second. `created` says which; `secret` is there only when it is new.
518
+ * An endpoint the business turned off stays off (`active`, `paused`).
519
+ */
520
+ ensureWebhook(input) {
521
+ return this.#call("PUT", "/v1/webhooks", input);
522
+ }
482
523
  addWebhook(input, idempotencyKey) {
483
524
  return this.#call("POST", "/v1/webhooks", input, idempotencyKey);
484
525
  }
@@ -613,6 +654,65 @@ export class SignSealer {
613
654
  reportProblem(input) {
614
655
  return this.#call("POST", "/v1/devices/report", input, undefined, { once: true });
615
656
  }
657
+ /* --------------------------------------- trusted applications (1.18.0) */
658
+ /**
659
+ * The business's own applications whose servers vouch for their people's
660
+ * approvals, each with its public keys (00684). Needs `signing:applications`.
661
+ */
662
+ async signingApplications() {
663
+ const out = await this.#call("GET", "/v1/signing-applications");
664
+ return out.applications;
665
+ }
666
+ /** Register an application. Then register the public key it signs approvals with. */
667
+ addSigningApplication(name, idempotencyKey) {
668
+ return this.#call("POST", "/v1/signing-applications", { name }, idempotencyKey);
669
+ }
670
+ /**
671
+ * Register a public key, as a JWK: EC P-256 for ES256, OKP Ed25519 for
672
+ * EdDSA. Only the public half; one with `d` is refused. `kid` defaults to
673
+ * the key's RFC 7638 thumbprint.
674
+ */
675
+ addSigningApplicationKey(applicationId, input, idempotencyKey) {
676
+ return this.#call("POST", `/v1/signing-applications/${encodeURIComponent(applicationId)}/keys`, input, idempotencyKey);
677
+ }
678
+ /** Revoke a key: every approval it signed and has not sent is refused from now on. */
679
+ revokeSigningApplicationKey(applicationId, keyId, reason) {
680
+ return this.#call("DELETE", `/v1/signing-applications/${encodeURIComponent(applicationId)}/keys/${encodeURIComponent(keyId)}?reason=${encodeURIComponent(reason)}`);
681
+ }
682
+ /** Disable an application: every approval from it is refused from now on. */
683
+ disableSigningApplication(applicationId, reason) {
684
+ return this.#call("POST", `/v1/signing-applications/${encodeURIComponent(applicationId)}/disable`, { reason }, undefined, { once: true });
685
+ }
686
+ /**
687
+ * Hand over one person's saved signature for one signing, server to
688
+ * server (00684). The reference is single-use, short-lived and bound to
689
+ * the application and the person; the image is never served back.
690
+ * Possession of the reference authorises nothing on its own: only an
691
+ * approval from the same application naming the same person, with
692
+ * `signature.sha256` equal to `sha256` here, spends it. Needs
693
+ * `signing:assert`.
694
+ */
695
+ addSignatureReference(input) {
696
+ return this.#call("POST", "/v1/signature-references", input, undefined, { once: true });
697
+ }
698
+ /**
699
+ * Sign with an approval your application's server signed (`createApproval`).
700
+ * Recorded as authenticated by your application, never as an identity
701
+ * SignSealer checked. The same approval sent again answers with the
702
+ * signing it made (`replayed: true`); retried with the same idempotency
703
+ * key, the stored answer. Needs `signing:assert`.
704
+ */
705
+ signWithApproval(input, idempotencyKey) {
706
+ return this.#call("POST", "/v1/signing-transactions", input, idempotencyKey);
707
+ }
708
+ /** One signing an approval made. */
709
+ signingTransaction(id) {
710
+ return this.#call("GET", `/v1/signing-transactions/${encodeURIComponent(id)}`);
711
+ }
712
+ /** The signing an approval made, by your application's id and the approval's `jti`: for a client that lost the answer. */
713
+ signingTransactionByApproval(applicationId, approvalId) {
714
+ return this.#call("GET", `/v1/signing-transactions?application_id=${encodeURIComponent(applicationId)}&approval_id=${encodeURIComponent(approvalId)}`);
715
+ }
616
716
  /* ------------------------------------------------------------ the wire */
617
717
  async #call(method, path, body, idempotencyKey,
618
718
  /**
@@ -1101,6 +1201,297 @@ function safeJson(text) {
1101
1201
  return {};
1102
1202
  }
1103
1203
  }
1204
+ /**
1205
+ * A refusal from the OAuth endpoints, or from the consent screen's answer.
1206
+ *
1207
+ * `code` is RFC 6749's `error` and `message` its `error_description` (both
1208
+ * also under their RFC names). Two questions decide what to do:
1209
+ *
1210
+ * - `reconnect`: the grant is over, or the code is spent. `invalid_grant`
1211
+ * -- the business disconnected you, the person who connected you can no
1212
+ * longer give what you hold, a token or code was used twice, or it
1213
+ * expired. Send the business through `authorizeUrl` again; nothing else
1214
+ * will bring it back.
1215
+ * - `transient`: the network or SignSealer, not your request. The grant may
1216
+ * well still be good. On a refresh, **whether the token was spent is
1217
+ * unknown**: read `refresh()` before deciding to send it again.
1218
+ *
1219
+ * `invalid_client` is neither: your client id or secret did not
1220
+ * authenticate, which is your configuration, for every business at once.
1221
+ *
1222
+ * `retryable` is always false. SignSealerError's "worth trying again
1223
+ * unchanged" is exactly the advice that turns a lost answer into a revoked
1224
+ * grant here.
1225
+ */
1226
+ export class SignSealerOAuthError extends SignSealerError {
1227
+ constructor(status, code, message, requestId, retryAfter) {
1228
+ super(status, code, message, undefined, requestId, retryAfter);
1229
+ this.name = "SignSealerOAuthError";
1230
+ }
1231
+ /** RFC 6749's name for `code`. */
1232
+ get error() {
1233
+ return this.code;
1234
+ }
1235
+ /** RFC 6749's name for `message`. */
1236
+ get errorDescription() {
1237
+ return this.message;
1238
+ }
1239
+ get retryable() {
1240
+ return false;
1241
+ }
1242
+ /** The grant is over or the code spent: send the business to connect again. */
1243
+ get reconnect() {
1244
+ return this.code === "invalid_grant";
1245
+ }
1246
+ /** The network or SignSealer failed, not the request. On a refresh, the token may or may not have been spent. */
1247
+ get transient() {
1248
+ return this.status === 0 || this.status === 429 || this.status >= 500;
1249
+ }
1250
+ }
1251
+ /** The characters RFC 7636 allows in a verifier, 43 to 128 of them. */
1252
+ const VERIFIER = /^[A-Za-z0-9\-._~]{43,128}$/;
1253
+ /**
1254
+ * Random bytes from wherever this runtime keeps them: the global WebCrypto,
1255
+ * then `node:crypto` for Node 18, assembled at run time for the reason
1256
+ * `webCrypto()` gives.
1257
+ */
1258
+ let randomPromise = null;
1259
+ async function randomBytes(n) {
1260
+ randomPromise ??= (async () => {
1261
+ const here = globalThis.crypto;
1262
+ if (typeof here?.getRandomValues === "function")
1263
+ return (k) => here.getRandomValues(new Uint8Array(k));
1264
+ try {
1265
+ const mod = await import(/* webpackIgnore: true */ /* @vite-ignore */ "node:" + "crypto");
1266
+ const web = mod.webcrypto;
1267
+ if (typeof web?.getRandomValues === "function")
1268
+ return (k) => web.getRandomValues(new Uint8Array(k));
1269
+ }
1270
+ catch {
1271
+ /* Not Node. The error below is the honest answer. */
1272
+ }
1273
+ throw new Error("no crypto.getRandomValues in this runtime, so a PKCE verifier cannot be made"
1274
+ + " — every current browser, edge runtime and Node 19 or later has it,"
1275
+ + " and Node 18 reaches it through node:crypto");
1276
+ })();
1277
+ return (await randomPromise)(n);
1278
+ }
1279
+ /**
1280
+ * A fresh PKCE pair, one per authorise request: 32 random bytes as a
1281
+ * 43-character verifier, and its S256 challenge.
1282
+ *
1283
+ * Keep the verifier on your server, against the `state` you send (a
1284
+ * session, or a short-lived row), and give it to `exchangeCode`. Never put
1285
+ * it in the authorise address: the challenge goes there, and the verifier
1286
+ * is what proves the code came back to the same party that asked.
1287
+ */
1288
+ export async function createPkce() {
1289
+ const verifier = base64url(await randomBytes(32));
1290
+ return { verifier, challenge: await pkceChallenge(verifier), method: "S256" };
1291
+ }
1292
+ /** The S256 challenge for a verifier: base64url of its SHA-256, without padding (RFC 7636, section 4.2). */
1293
+ export async function pkceChallenge(verifier) {
1294
+ if (!VERIFIER.test(verifier)) {
1295
+ throw new Error("a PKCE verifier is 43 to 128 of A-Z, a-z, 0-9 and - . _ ~");
1296
+ }
1297
+ const digest = await (await webCrypto()).digest("SHA-256", new TextEncoder().encode(verifier));
1298
+ return base64url(new Uint8Array(digest));
1299
+ }
1300
+ /**
1301
+ * "Connect with SignSealer", for a partner's server (1.20.0).
1302
+ *
1303
+ * ```ts
1304
+ * const oauth = new SignSealerOAuth({ clientId, clientSecret });
1305
+ * const { verifier, challenge } = await createPkce();
1306
+ * redirect(oauth.authorizeUrl({ redirectUri, scopes: ["signing:read", "signing:write"], state, codeChallenge: challenge }));
1307
+ * // …and on the way back:
1308
+ * const { code } = oauth.callback(request.url, savedState);
1309
+ * const tokens = await oauth.exchangeCode({ code, redirectUri, codeVerifier: verifier });
1310
+ * const client = new SignSealer({ apiKey: tokens.access_token });
1311
+ * ```
1312
+ *
1313
+ * The client is authenticated to `/oauth/token` by HTTP Basic, which RFC
1314
+ * 6749 prefers and the server reads first. Every token request is sent
1315
+ * exactly once: see `refresh()` for why that is the whole point.
1316
+ */
1317
+ export class SignSealerOAuth {
1318
+ #auth;
1319
+ #base;
1320
+ #clientId;
1321
+ #fetch;
1322
+ constructor(opts) {
1323
+ if (!opts?.clientId || !opts?.clientSecret) {
1324
+ throw new Error("an OAuth client needs its clientId and clientSecret");
1325
+ }
1326
+ if (opts.clientId.startsWith("mk_") || opts.clientSecret.startsWith("mk_")) {
1327
+ throw new Error("that is a business's API key; OAuth takes your client id and secret");
1328
+ }
1329
+ this.#clientId = opts.clientId;
1330
+ /* Each half form-encoded before joining (RFC 6749, 2.3.1), which is how the server decodes them. */
1331
+ const pair = `${encodeURIComponent(opts.clientId)}:${encodeURIComponent(opts.clientSecret)}`;
1332
+ this.#auth = `Basic ${bytesToBase64(new TextEncoder().encode(pair))}`;
1333
+ this.#base = withoutTrailingSlashes(opts.baseUrl ?? "https://api.signsealer.com");
1334
+ this.#fetch = opts.fetch ?? globalThis.fetch;
1335
+ }
1336
+ /**
1337
+ * Where to send the business's browser. SignSealer signs them in (or lets
1338
+ * them make an account and name their business on the way), shows your
1339
+ * registered name and what each scope allows, and sends them back to
1340
+ * `redirectUri` with `code` and your `state`, or with `error`.
1341
+ *
1342
+ * `redirectUri` must be one you registered, byte for byte, and the same
1343
+ * string you give `exchangeCode`. `state` is yours, returned untouched:
1344
+ * make it unguessable, keep it with the verifier, and check it in
1345
+ * `callback`. Ask for the fewest scopes that do the job; a scope your
1346
+ * client was not registered with is refused as `invalid_scope`.
1347
+ */
1348
+ authorizeUrl(opts) {
1349
+ if (!opts?.redirectUri)
1350
+ throw new Error("authorizeUrl needs the redirectUri you registered");
1351
+ if (!opts.scopes?.length)
1352
+ throw new Error("authorizeUrl needs at least one scope");
1353
+ if (!opts.state)
1354
+ throw new Error("authorizeUrl needs a state, to check on the way back");
1355
+ if (!opts.codeChallenge || opts.codeChallenge.length < 43) {
1356
+ throw new Error("authorizeUrl needs the codeChallenge from createPkce(); PKCE is required");
1357
+ }
1358
+ const q = new URLSearchParams({
1359
+ response_type: "code",
1360
+ client_id: this.#clientId,
1361
+ redirect_uri: opts.redirectUri,
1362
+ scope: opts.scopes.join(" "),
1363
+ state: opts.state,
1364
+ code_challenge: opts.codeChallenge,
1365
+ code_challenge_method: "S256",
1366
+ });
1367
+ return `${this.#base}/oauth/authorize?${q}`;
1368
+ }
1369
+ /**
1370
+ * Read the consent screen's answer from your redirect's query: the code,
1371
+ * once `state` matches the one you kept. A business that pressed Not now
1372
+ * comes back as `access_denied`, and a request the screen could not
1373
+ * answer as its RFC 6749 error; both are thrown as SignSealerOAuthError,
1374
+ * with `status` 400. A `state` that does not match is `state_mismatch`:
1375
+ * do not exchange that code.
1376
+ */
1377
+ callback(query, expectedState) {
1378
+ const q = query instanceof URLSearchParams ? query
1379
+ : query instanceof URL ? query.searchParams
1380
+ : new URLSearchParams(query.includes("?") ? query.slice(query.indexOf("?") + 1) : query);
1381
+ const state = q.get("state") ?? "";
1382
+ if (!expectedState || !sameBytes(new TextEncoder().encode(state), new TextEncoder().encode(expectedState))) {
1383
+ throw new SignSealerOAuthError(400, "state_mismatch", "the state that came back is not the one this browser was sent with");
1384
+ }
1385
+ const error = q.get("error");
1386
+ if (error)
1387
+ throw new SignSealerOAuthError(400, error, q.get("error_description") ?? error);
1388
+ const code = q.get("code");
1389
+ if (!code)
1390
+ throw new SignSealerOAuthError(400, "invalid_request", "the answer carried neither a code nor an error");
1391
+ return { code };
1392
+ }
1393
+ /**
1394
+ * Exchange the code from `callback` for the business's tokens. Do it at
1395
+ * once: a code lives sixty seconds and is good once.
1396
+ *
1397
+ * Sent once and never again. A code presented twice is a replay, and the
1398
+ * server revokes the grant it made, so a retry after a lost answer would
1399
+ * disconnect the business it just connected. If this throws `transient`,
1400
+ * send the business through `authorizeUrl` again.
1401
+ */
1402
+ exchangeCode(opts) {
1403
+ if (!opts?.code || !opts.redirectUri || !opts.codeVerifier) {
1404
+ throw new Error("exchangeCode needs the code, the same redirectUri and the PKCE codeVerifier");
1405
+ }
1406
+ return this.#token({
1407
+ grant_type: "authorization_code",
1408
+ code: opts.code,
1409
+ redirect_uri: opts.redirectUri,
1410
+ code_verifier: opts.codeVerifier,
1411
+ });
1412
+ }
1413
+ /**
1414
+ * Swap a refresh token for a new access token **and a new refresh token**.
1415
+ *
1416
+ * **THIS IS NEVER RETRIED, AND YOU MUST NOT RETRY IT EITHER WITHOUT
1417
+ * THINKING.** The refresh token you send is spent the moment SignSealer
1418
+ * reads it. Presenting a spent one is treated as theft: the whole family
1419
+ * is revoked -- every refresh token from that connection, the grant, and
1420
+ * every access token issued under it -- and the business has to connect
1421
+ * again. From the server's side a buggy retry and a stolen token look the
1422
+ * same.
1423
+ *
1424
+ * So:
1425
+ *
1426
+ * 1. **Serialise refreshes per grant.** One at a time for each business
1427
+ * (a row lock, an advisory lock, a queue). Two workers refreshing the
1428
+ * same grant at once will end it.
1429
+ * 2. **Store the new refresh token before you use the access token**,
1430
+ * atomically, while still holding the lock. A new refresh token you
1431
+ * lose cannot be got back.
1432
+ * 3. **A `transient` failure leaves the token's state unknown.** If the
1433
+ * request reached SignSealer and the answer was lost, the token you
1434
+ * hold is spent and its successor lost with the answer; if it never
1435
+ * arrived, it is still good. Sending it again either works or ends
1436
+ * the connection (`reconnect`), which losing the successor had
1437
+ * already made inevitable. That is your decision, made under the
1438
+ * lock, never a loop.
1439
+ * 4. **`reconnect` means reconnect.** Mark the business disconnected and
1440
+ * ask them to connect again; do not try the token again.
1441
+ */
1442
+ refresh(refreshToken) {
1443
+ if (!refreshToken)
1444
+ throw new Error("refresh needs the refresh token you stored last");
1445
+ return this.#token({ grant_type: "refresh_token", refresh_token: refreshToken });
1446
+ }
1447
+ /*
1448
+ One request, one answer, no loop. Every other call in this package
1449
+ retries what is worth retrying; this one has nothing worth retrying,
1450
+ because both of its grants are spent by being read.
1451
+ */
1452
+ async #token(form) {
1453
+ const sentAt = Date.now();
1454
+ let res;
1455
+ try {
1456
+ res = await this.#fetch(`${this.#base}/oauth/token`, {
1457
+ method: "POST",
1458
+ headers: {
1459
+ authorization: this.#auth,
1460
+ "content-type": "application/x-www-form-urlencoded",
1461
+ accept: "application/json",
1462
+ },
1463
+ body: new URLSearchParams(form).toString(),
1464
+ });
1465
+ }
1466
+ catch (cause) {
1467
+ throw new SignSealerOAuthError(0, "network", cause instanceof Error ? cause.message : "the request did not reach SignSealer");
1468
+ }
1469
+ const requestId = res.headers.get("x-request-id") ?? undefined;
1470
+ const text = await res.text();
1471
+ const parsed = (text ? safeJson(text) : {});
1472
+ if (res.ok && typeof parsed.access_token === "string") {
1473
+ const expiresIn = typeof parsed.expires_in === "number" ? parsed.expires_in : 3600;
1474
+ const scope = typeof parsed.scope === "string" ? parsed.scope : "";
1475
+ return {
1476
+ access_token: parsed.access_token,
1477
+ token_type: "Bearer",
1478
+ expires_in: expiresIn,
1479
+ expires_at: new Date(sentAt + expiresIn * 1000).toISOString(),
1480
+ scope,
1481
+ scopes: scope.split(" ").filter(Boolean),
1482
+ refresh_token: typeof parsed.refresh_token === "string" ? parsed.refresh_token : null,
1483
+ };
1484
+ }
1485
+ const code = typeof parsed.error === "string" ? parsed.error
1486
+ : res.status >= 500 ? "server_error"
1487
+ : res.status === 429 ? "temporarily_unavailable"
1488
+ : res.ok ? "server_error" : "invalid_request";
1489
+ const description = typeof parsed.error_description === "string" ? parsed.error_description
1490
+ : res.ok ? "SignSealer answered without an access token" : `SignSealer returned ${res.status}`;
1491
+ /* A 200 with no token is SignSealer's fault, and as unknown in its outcome as a 500. */
1492
+ throw new SignSealerOAuthError(res.ok ? 502 : res.status, code, description, requestId, waitAsked(res.headers.get("retry-after")));
1493
+ }
1494
+ }
1104
1495
  /* ------------------------------------------------------- verifying a webhook
1105
1496
 
1106
1497
  The SDK could create a webhook endpoint and could not check a delivery from
@@ -1352,4 +1743,84 @@ export async function verifyWebhookRequest(opts) {
1352
1743
  });
1353
1744
  return { ...result, eventId: headerOf(opts.headers, WEBHOOK_EVENT_HEADER) };
1354
1745
  }
1746
+ const APPROVAL_TYP = "signsealer-approval+jwt";
1747
+ function base64url(bytes) {
1748
+ let bin = "";
1749
+ for (let i = 0; i < bytes.length; i++)
1750
+ bin += String.fromCharCode(bytes[i]);
1751
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1752
+ }
1753
+ const seconds = (t) => Math.floor((t instanceof Date ? t.getTime() : t) / 1000);
1754
+ /** 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. */
1755
+ function trimSpaces(s) {
1756
+ let start = 0;
1757
+ let end = s.length;
1758
+ while (start < end && s.charCodeAt(start) === 32)
1759
+ start++;
1760
+ while (end > start && s.charCodeAt(end - 1) === 32)
1761
+ end--;
1762
+ return s.slice(start, end);
1763
+ }
1764
+ /** SHA-256 of a string's UTF-8, as lowercase hex: a signature's, or a document's text. */
1765
+ export async function sha256Hex(text) {
1766
+ const digest = await (await webCrypto()).digest("SHA-256", new TextEncoder().encode(text));
1767
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
1768
+ }
1769
+ /**
1770
+ * Sign one approval with your application's private key: a compact JWS
1771
+ * that `signWithApproval` sends. `privateKey` is a WebCrypto key or a
1772
+ * private JWK -- ECDSA P-256 (ES256) or Ed25519 (EdDSA) -- and `kid` the
1773
+ * name you registered its public half under.
1774
+ *
1775
+ * Make one per approval, when the person approves, and send it at once: it
1776
+ * lives two minutes by default and five at most, and its `jti` is spent by
1777
+ * the signing it makes.
1778
+ */
1779
+ export async function createApproval(opts) {
1780
+ const subtle = await webCrypto();
1781
+ const a = opts.approval;
1782
+ let key = opts.privateKey;
1783
+ if (!(typeof opts.privateKey.type === "string" && opts.privateKey.algorithm)) {
1784
+ const jwk = opts.privateKey;
1785
+ const params = jwk.kty === "OKP" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: "P-256" };
1786
+ key = await subtle.importKey("jwk", jwk, params, false, ["sign"]);
1787
+ }
1788
+ const ed = key.algorithm.name === "Ed25519";
1789
+ if (!ed && !(key.algorithm.name === "ECDSA" && key.algorithm.namedCurve === "P-256")) {
1790
+ throw new Error("an approval is signed with an ECDSA P-256 (ES256) or an Ed25519 (EdDSA) key");
1791
+ }
1792
+ const ttl = Math.min(Math.max(a.ttlSeconds ?? 120, 1), 300);
1793
+ const iat = seconds(opts.now ?? Date.now());
1794
+ const approvalId = a.approvalId ?? `apr_${(await randomUuid()).replace(/-/g, "")}`;
1795
+ const signatureSha = a.signature.method === "saved" ? a.signature.sha256
1796
+ /* Spaces trimmed as the server trims a typed signature, so the hash is of what it keeps. */
1797
+ : await sha256Hex(a.signature.method === "drawn" ? a.signature.image : trimSpaces(a.signature.text));
1798
+ const claims = {
1799
+ iss: a.applicationId,
1800
+ aud: "signsealer",
1801
+ tenant_id: a.tenantId,
1802
+ sub: a.person.subject,
1803
+ name: a.person.name,
1804
+ amr: a.auth.methods,
1805
+ ...(a.auth.level ? { acr: a.auth.level } : {}),
1806
+ auth_time: seconds(a.auth.at),
1807
+ approved_at: seconds(a.approvedAt),
1808
+ iat,
1809
+ exp: iat + ttl,
1810
+ jti: approvalId,
1811
+ document_id: a.documentId,
1812
+ document_sha256: a.documentSha256.toLowerCase(),
1813
+ ...(a.signerId ? { signer_id: a.signerId } : {}),
1814
+ signature: { method: a.signature.method, sha256: signatureSha },
1815
+ consent: true,
1816
+ origin: a.origin ?? "online",
1817
+ ...(a.ip ? { ip: a.ip } : {}),
1818
+ ...(a.device ? { device: a.device } : {}),
1819
+ };
1820
+ const enc = new TextEncoder();
1821
+ const input = `${base64url(enc.encode(JSON.stringify({ alg: ed ? "EdDSA" : "ES256", typ: APPROVAL_TYP, kid: opts.kid })))}.${base64url(enc.encode(JSON.stringify(claims)))}`;
1822
+ /* WebCrypto's ECDSA signature is r||s, which is what JWS wants. */
1823
+ const sig = await subtle.sign(ed ? { name: "Ed25519" } : { name: "ECDSA", hash: "SHA-256" }, key, enc.encode(input));
1824
+ return { assertion: `${input}.${base64url(new Uint8Array(sig))}`, approvalId, claims };
1825
+ }
1355
1826
  //# sourceMappingURL=index.js.map