@dakota-xyz/ts-sdk 3.2.0 → 3.4.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/index.js CHANGED
@@ -118,7 +118,15 @@ var APIError = class _APIError extends Error {
118
118
  }
119
119
  } catch {
120
120
  }
121
- return new _APIError(response.status, code, message, {
121
+ if (typeof code !== "string") {
122
+ code = `http_${response.status}`;
123
+ }
124
+ const governanceCode = code.replace(/-/g, "_");
125
+ const Typed = GOVERNANCE_ERRORS.get(governanceCode);
126
+ if (Typed) {
127
+ code = governanceCode;
128
+ }
129
+ return new (Typed ?? _APIError)(response.status, code, message, {
122
130
  details,
123
131
  requestId,
124
132
  rawBody,
@@ -133,6 +141,50 @@ var APIError = class _APIError extends Error {
133
141
  return `APIError [${this.statusCode}]: ${this.message}`;
134
142
  }
135
143
  };
144
+ var EndorsementRequiredError = class extends APIError {
145
+ constructor(statusCode, code, message, options) {
146
+ super(statusCode, code, message, options);
147
+ this.name = "EndorsementRequiredError";
148
+ }
149
+ };
150
+ var InsufficientEndorsementsError = class extends APIError {
151
+ /** Signatures the platform counted, when it said so. */
152
+ have;
153
+ /** Signatures the quorum needs, when it said so. */
154
+ need;
155
+ constructor(statusCode, code, message, options) {
156
+ super(statusCode, code, message, options);
157
+ this.name = "InsufficientEndorsementsError";
158
+ const m = /have (\d+), need (\d+)/.exec(message);
159
+ this.have = m ? Number(m[1]) : null;
160
+ this.need = m ? Number(m[2]) : null;
161
+ }
162
+ };
163
+ var StaleSignerGroupVersionError = class extends APIError {
164
+ constructor(statusCode, code, message, options) {
165
+ super(statusCode, code, message, options);
166
+ this.name = "StaleSignerGroupVersionError";
167
+ }
168
+ };
169
+ var BelowThresholdError = class extends APIError {
170
+ constructor(statusCode, code, message, options) {
171
+ super(statusCode, code, message, options);
172
+ this.name = "BelowThresholdError";
173
+ }
174
+ };
175
+ var InvalidGoverningGroupError = class extends APIError {
176
+ constructor(statusCode, code, message, options) {
177
+ super(statusCode, code, message, options);
178
+ this.name = "InvalidGoverningGroupError";
179
+ }
180
+ };
181
+ var GOVERNANCE_ERRORS = /* @__PURE__ */ new Map([
182
+ ["endorsement_required", EndorsementRequiredError],
183
+ ["insufficient_endorsements", InsufficientEndorsementsError],
184
+ ["stale_signer_group_version", StaleSignerGroupVersionError],
185
+ ["below_threshold", BelowThresholdError],
186
+ ["invalid_governing_group", InvalidGoverningGroupError]
187
+ ]);
136
188
  var TransportError = class _TransportError extends Error {
137
189
  /** The underlying error that caused this transport error */
138
190
  cause;
@@ -1102,6 +1154,7 @@ var RecipientsResource = class extends BaseResource {
1102
1154
  * ```typescript
1103
1155
  * const recipient = await client.recipients.create(customerId, {
1104
1156
  * name: 'Treasury Account',
1157
+ * external_id: 'vendor-1177', // optional: your own label, not unique
1105
1158
  * });
1106
1159
  * ```
1107
1160
  */
@@ -1118,7 +1171,7 @@ var RecipientsResource = class extends BaseResource {
1118
1171
  * List recipients for a customer.
1119
1172
  *
1120
1173
  * @param customerId - Customer ID
1121
- * @param params - Pagination parameters
1174
+ * @param params - Pagination parameters and an optional `external_id` filter
1122
1175
  * @returns Async iterator of recipients
1123
1176
  *
1124
1177
  * @example
@@ -1126,6 +1179,11 @@ var RecipientsResource = class extends BaseResource {
1126
1179
  * for await (const recipient of client.recipients.list(customerId)) {
1127
1180
  * console.log(recipient.name);
1128
1181
  * }
1182
+ *
1183
+ * // Look up recipients by your own label
1184
+ * const matches = await client.recipients
1185
+ * .list(customerId, { external_id: 'vendor-1177' })
1186
+ * .toArray();
1129
1187
  * ```
1130
1188
  */
1131
1189
  list(customerId, params) {
@@ -1189,6 +1247,211 @@ var RecipientsResource = class extends BaseResource {
1189
1247
  }
1190
1248
  };
1191
1249
 
1250
+ // src/agentic/canonicalize.ts
1251
+ function canonicalJSON(value) {
1252
+ return canonicalize(value);
1253
+ }
1254
+ function canonicalize(value) {
1255
+ if (value === null || value === void 0) {
1256
+ return "null";
1257
+ }
1258
+ if (typeof value === "boolean") {
1259
+ return value ? "true" : "false";
1260
+ }
1261
+ if (typeof value === "number") {
1262
+ if (!Number.isFinite(value)) {
1263
+ throw new TypeError(`canonical JSON: non-finite number ${value}`);
1264
+ }
1265
+ return JSON.stringify(value);
1266
+ }
1267
+ if (typeof value === "string") {
1268
+ return JSON.stringify(value);
1269
+ }
1270
+ if (typeof value === "bigint") {
1271
+ throw new TypeError("canonical JSON: bigint values are not supported");
1272
+ }
1273
+ if (Array.isArray(value)) {
1274
+ const parts = value.map((item) => canonicalize(item));
1275
+ return `[${parts.join(",")}]`;
1276
+ }
1277
+ if (typeof value === "object") {
1278
+ const obj = value;
1279
+ const keys = Object.keys(obj).sort();
1280
+ const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);
1281
+ return `{${parts.join(",")}}`;
1282
+ }
1283
+ throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);
1284
+ }
1285
+
1286
+ // src/governance/encoding.ts
1287
+ var B64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1288
+ function bytesToBase64(bytes) {
1289
+ let out = "";
1290
+ let i = 0;
1291
+ for (; i + 2 < bytes.length; i += 3) {
1292
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
1293
+ out += B64_ALPHABET[n >> 18 & 63] + B64_ALPHABET[n >> 12 & 63] + B64_ALPHABET[n >> 6 & 63] + B64_ALPHABET[n & 63];
1294
+ }
1295
+ const rest = bytes.length - i;
1296
+ if (rest === 1) {
1297
+ const n = bytes[i] << 16;
1298
+ out += B64_ALPHABET[n >> 18 & 63] + B64_ALPHABET[n >> 12 & 63] + "==";
1299
+ } else if (rest === 2) {
1300
+ const n = bytes[i] << 16 | bytes[i + 1] << 8;
1301
+ out += B64_ALPHABET[n >> 18 & 63] + B64_ALPHABET[n >> 12 & 63] + B64_ALPHABET[n >> 6 & 63] + "=";
1302
+ }
1303
+ return out;
1304
+ }
1305
+ function bytesToBase64url(bytes) {
1306
+ return stripPadding(bytesToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_"));
1307
+ }
1308
+ function stripPadding(s) {
1309
+ let end = s.length;
1310
+ while (end > 0 && s.charCodeAt(end - 1) === 61) end--;
1311
+ return s.slice(0, end);
1312
+ }
1313
+ function base64ToBytes(input) {
1314
+ const s = stripPadding(input.replace(/-/g, "+").replace(/_/g, "/"));
1315
+ if (!/^[A-Za-z0-9+/]*$/.test(s) || s.length % 4 === 1) {
1316
+ throw new TypeError("invalid base64 or base64url string");
1317
+ }
1318
+ const out = new Uint8Array(Math.floor(s.length * 3 / 4));
1319
+ let o = 0;
1320
+ for (let i = 0; i < s.length; i += 4) {
1321
+ const a = B64_ALPHABET.indexOf(s[i]);
1322
+ const b = B64_ALPHABET.indexOf(s[i + 1]);
1323
+ const c = i + 2 < s.length ? B64_ALPHABET.indexOf(s[i + 2]) : 0;
1324
+ const d = i + 3 < s.length ? B64_ALPHABET.indexOf(s[i + 3]) : 0;
1325
+ const n = a << 18 | b << 12 | c << 6 | d;
1326
+ out[o++] = n >> 16 & 255;
1327
+ if (i + 2 < s.length) out[o++] = n >> 8 & 255;
1328
+ if (i + 3 < s.length) out[o++] = n & 255;
1329
+ }
1330
+ return out;
1331
+ }
1332
+ function utf8(s) {
1333
+ return new TextEncoder().encode(s);
1334
+ }
1335
+ function toBytes(source) {
1336
+ if (ArrayBuffer.isView(source)) {
1337
+ return new Uint8Array(source.buffer, source.byteOffset, source.byteLength).slice();
1338
+ }
1339
+ if (Object.prototype.toString.call(source) === "[object ArrayBuffer]") {
1340
+ return new Uint8Array(source.slice(0));
1341
+ }
1342
+ throw new TypeError("expected an ArrayBuffer or a typed array");
1343
+ }
1344
+
1345
+ // src/governance/intents.ts
1346
+ var LOWERCASE_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1347
+ function assertIdempotencyKey(key) {
1348
+ if (typeof key !== "string" || !LOWERCASE_UUID.test(key)) {
1349
+ throw new TypeError(
1350
+ `idempotency key must be a lowercase UUID (got ${JSON.stringify(key)}); the platform refuses any other form`
1351
+ );
1352
+ }
1353
+ }
1354
+ function newIdempotencyKey() {
1355
+ const c = globalThis.crypto;
1356
+ if (c && typeof c.randomUUID === "function") {
1357
+ return c.randomUUID().toLowerCase();
1358
+ }
1359
+ if (!c || typeof c.getRandomValues !== "function") {
1360
+ throw new Error("no cryptographic random source: pass an idempotency key explicitly");
1361
+ }
1362
+ const b = c.getRandomValues(new Uint8Array(16));
1363
+ b[6] = b[6] & 15 | 64;
1364
+ b[8] = b[8] & 63 | 128;
1365
+ const hex = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
1366
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1367
+ }
1368
+ function nonEmpty(name, value) {
1369
+ if (typeof value !== "string" || value === "") {
1370
+ throw new TypeError(`${name} is required`);
1371
+ }
1372
+ return value;
1373
+ }
1374
+ function keyList(name, keys) {
1375
+ if (!Array.isArray(keys) || keys.length === 0) {
1376
+ throw new TypeError(`${name} must list at least one public key`);
1377
+ }
1378
+ return keys.map((k, i) => {
1379
+ const key = nonEmpty(`${name}[${i}]`, k);
1380
+ if (key.trim() !== key) {
1381
+ throw new TypeError(`${name}[${i}] has leading or trailing whitespace; trim it first`);
1382
+ }
1383
+ return key;
1384
+ });
1385
+ }
1386
+ function version(v) {
1387
+ if (!Number.isSafeInteger(v) || v < 0) {
1388
+ throw new TypeError(
1389
+ `signer_group_version must be a non-negative integer (got ${String(v)}); read it from the group's \`version\``
1390
+ );
1391
+ }
1392
+ return v;
1393
+ }
1394
+ function finish(intent) {
1395
+ const canonical = canonicalJSON(intent);
1396
+ return { intent, canonical, bytes: utf8(canonical) };
1397
+ }
1398
+ function addSignersToGroupIntent(params) {
1399
+ assertIdempotencyKey(params.idempotencyKey);
1400
+ return finish({
1401
+ type: "add_signers_to_group",
1402
+ signer_group_id: nonEmpty("signerGroupId", params.signerGroupId),
1403
+ new_member_keys: keyList("newMemberKeys", params.newMemberKeys),
1404
+ signer_group_version: version(params.signerGroupVersion),
1405
+ idempotency_key: params.idempotencyKey
1406
+ });
1407
+ }
1408
+ function removeSignersFromGroupIntent(params) {
1409
+ assertIdempotencyKey(params.idempotencyKey);
1410
+ return finish({
1411
+ type: "remove_signers_from_group",
1412
+ group_id: nonEmpty("signerGroupId", params.signerGroupId),
1413
+ members_to_remove: keyList("membersToRemove", params.membersToRemove),
1414
+ signer_group_version: version(params.signerGroupVersion),
1415
+ idempotency_key: params.idempotencyKey
1416
+ });
1417
+ }
1418
+ function updateSignerGroupGovernanceIntent(params) {
1419
+ assertIdempotencyKey(params.idempotencyKey);
1420
+ const intent = {
1421
+ type: "update_signer_group_governance",
1422
+ signer_group_id: nonEmpty("signerGroupId", params.signerGroupId),
1423
+ signer_group_version: version(params.signerGroupVersion),
1424
+ idempotency_key: params.idempotencyKey
1425
+ };
1426
+ if (params.governanceThreshold !== void 0 && params.governanceThreshold !== null) {
1427
+ const t = params.governanceThreshold;
1428
+ if (!Number.isSafeInteger(t) || t < 1 || t > 2147483647) {
1429
+ throw new TypeError(
1430
+ "governanceThreshold must be an integer from 1 to 2^31-1, or null to clear it"
1431
+ );
1432
+ }
1433
+ intent.governance_threshold = params.governanceThreshold;
1434
+ }
1435
+ if (params.governanceSignerGroupId !== void 0 && params.governanceSignerGroupId !== null) {
1436
+ intent.governance_signer_group_id = nonEmpty(
1437
+ "governanceSignerGroupId",
1438
+ params.governanceSignerGroupId
1439
+ );
1440
+ }
1441
+ return finish(intent);
1442
+ }
1443
+ function createCryptoDestinationIntent(params) {
1444
+ assertIdempotencyKey(params.idempotencyKey);
1445
+ return finish({
1446
+ type: "create_crypto_destination",
1447
+ recipient_id: nonEmpty("recipientId", params.recipientId),
1448
+ network_id: nonEmpty("networkId", params.networkId),
1449
+ address: nonEmpty("address", params.address),
1450
+ signer_group_id: nonEmpty("signerGroupId", params.signerGroupId),
1451
+ idempotency_key: params.idempotencyKey
1452
+ });
1453
+ }
1454
+
1192
1455
  // src/client/resources/destinations.ts
1193
1456
  var DestinationsResource = class extends BaseResource {
1194
1457
  /**
@@ -1230,6 +1493,15 @@ var DestinationsResource = class extends BaseResource {
1230
1493
  * ```
1231
1494
  */
1232
1495
  async create(recipientId, data, options) {
1496
+ const signatures = data.signatures;
1497
+ if (signatures !== void 0 && signatures.length > 0) {
1498
+ if (!options?.idempotencyKey) {
1499
+ throw new TypeError(
1500
+ "destinations.create with signatures needs options.idempotencyKey: the idempotency_key inside the signed intent (a generated one could never match)"
1501
+ );
1502
+ }
1503
+ assertIdempotencyKey(options.idempotencyKey);
1504
+ }
1233
1505
  return this.transport.request({
1234
1506
  method: "POST",
1235
1507
  path: `/recipients/${recipientId}/destinations`,
@@ -1729,13 +2001,19 @@ var WalletsResource = class extends BaseResource {
1729
2001
  * with the wallet's signer-group ECDSA P-256 key, base64-encode the
1730
2002
  * DER signature, then post the envelope.
1731
2003
  *
2004
+ * Use the SDK's `canonicalJSON`: it matches the platform's canonical form
2005
+ * byte for byte. Write `amount` in its shortest decimal form (`'100'`, not
2006
+ * `'100.00'`; `'0.5'`, not `'0.50'`). The platform parses the amount as a
2007
+ * decimal and re-serializes it before it checks the signature, so trailing
2008
+ * zeros change the signed bytes and the signature fails.
2009
+ *
1732
2010
  * @param walletId - Wallet ID
1733
2011
  * @param data - Endorsed wallet transaction request: `{ signatures, intent }`
1734
2012
  * @returns Created transaction
1735
2013
  *
1736
2014
  * @example
1737
2015
  * ```typescript
1738
- * import canonicalize from 'canonicalize';
2016
+ * import { canonicalJSON } from '@dakota-xyz/ts-sdk';
1739
2017
  * import { createSign, createPrivateKey, randomUUID } from 'node:crypto';
1740
2018
  *
1741
2019
  * const intent = {
@@ -1745,12 +2023,12 @@ var WalletsResource = class extends BaseResource {
1745
2023
  * kind: 'transfer',
1746
2024
  * from: wallet.address,
1747
2025
  * to: '0x...',
1748
- * amount: '100.00',
2026
+ * amount: '100', // shortest decimal form, see below
1749
2027
  * asset_id: 'USDC',
1750
2028
  * },
1751
2029
  * idempotency_key: randomUUID(),
1752
2030
  * };
1753
- * const canonical = canonicalize(intent)!;
2031
+ * const canonical = canonicalJSON(intent);
1754
2032
  * const sig = createSign('SHA256').update(canonical).sign({
1755
2033
  * key: createPrivateKey({ key: privateKeyDer, format: 'der', type: 'pkcs8' }),
1756
2034
  * dsaEncoding: 'der',
@@ -2369,6 +2647,63 @@ var PoliciesResource = class extends BaseResource {
2369
2647
  }
2370
2648
  };
2371
2649
 
2650
+ // src/governance/signer.ts
2651
+ async function signGovernanceIntent(intent, signers) {
2652
+ if (!Array.isArray(signers) || signers.length === 0) {
2653
+ throw new TypeError("a governance change needs at least one signer");
2654
+ }
2655
+ const bytes = ArrayBuffer.isView(intent) ? toBytes(intent) : intent.bytes;
2656
+ const out = [];
2657
+ for (const s of signers) {
2658
+ const sig = typeof s === "function" ? await s(bytes.slice()) : await s.sign(bytes.slice());
2659
+ if (typeof sig !== "string" || sig === "") {
2660
+ throw new Error("a governance signer returned an empty signature");
2661
+ }
2662
+ out.push(sig);
2663
+ }
2664
+ return out;
2665
+ }
2666
+ function webCryptoES256Signer(privateKey, subtle) {
2667
+ return {
2668
+ async sign(payload) {
2669
+ const s = subtle ?? globalThis.crypto?.subtle;
2670
+ if (!s) {
2671
+ throw new Error(
2672
+ "WebCrypto is not available: pass a SubtleCrypto or use ES256Signer on Node"
2673
+ );
2674
+ }
2675
+ const raw = new Uint8Array(
2676
+ await s.sign(
2677
+ { name: "ECDSA", hash: "SHA-256" },
2678
+ privateKey,
2679
+ toArrayBuffer(payload)
2680
+ )
2681
+ );
2682
+ return bytesToBase64(p1363ToDer(raw));
2683
+ }
2684
+ };
2685
+ }
2686
+ function toArrayBuffer(bytes) {
2687
+ const out = new ArrayBuffer(bytes.length);
2688
+ new Uint8Array(out).set(bytes);
2689
+ return out;
2690
+ }
2691
+ function p1363ToDer(sig) {
2692
+ if (sig.length !== 64) {
2693
+ throw new Error(`expected a 64-byte P-256 signature, got ${sig.length} bytes`);
2694
+ }
2695
+ const int = (bytes) => {
2696
+ let i = 0;
2697
+ while (i < bytes.length - 1 && bytes[i] === 0) i++;
2698
+ const trimmed = bytes.slice(i);
2699
+ const body = trimmed[0] & 128 ? Uint8Array.of(0, ...trimmed) : trimmed;
2700
+ return Uint8Array.of(2, body.length, ...body);
2701
+ };
2702
+ const r = int(sig.slice(0, 32));
2703
+ const s = int(sig.slice(32));
2704
+ return Uint8Array.of(48, r.length + s.length, ...r, ...s);
2705
+ }
2706
+
2372
2707
  // src/client/resources/signer-groups.ts
2373
2708
  var SignerGroupsResource = class extends BaseResource {
2374
2709
  /**
@@ -2417,7 +2752,7 @@ var SignerGroupsResource = class extends BaseResource {
2417
2752
  async get(signerGroupId, params) {
2418
2753
  return this.transport.request({
2419
2754
  method: "GET",
2420
- path: `/signer-groups/${signerGroupId}`,
2755
+ path: `/signer-groups/${seg(signerGroupId)}`,
2421
2756
  query: { ...params }
2422
2757
  });
2423
2758
  }
@@ -2428,21 +2763,35 @@ var SignerGroupsResource = class extends BaseResource {
2428
2763
  * key of an existing signer resource — not a fresh signer definition.
2429
2764
  * Returns the updated group (with the new member included).
2430
2765
  *
2766
+ * A governed group (governance settings, or a client with governance
2767
+ * enforcement on) refuses an unsigned add with
2768
+ * `EndorsementRequiredError`; use {@link addSignerSigned} instead, or pass
2769
+ * `signatures` + `signer_group_version` yourself with the SAME idempotency
2770
+ * key that is inside the signed intent.
2771
+ *
2431
2772
  * @param signerGroupId - Signer group ID
2432
2773
  * @param data - `{ member_key }` (the signer's base64 PKIX public key)
2433
2774
  * @returns The updated signer group
2434
2775
  */
2435
2776
  async addSigner(signerGroupId, data, options) {
2777
+ if (data.signatures !== void 0) {
2778
+ requireSignedKey("addSigner", options);
2779
+ }
2436
2780
  return this.transport.request({
2437
2781
  method: "POST",
2438
- path: `/signer-groups/${signerGroupId}/signers`,
2782
+ path: `/signer-groups/${seg(signerGroupId)}/signers`,
2439
2783
  body: data,
2440
2784
  idempotencyKey: options?.idempotencyKey,
2441
2785
  timeout: options?.timeout
2442
2786
  });
2443
2787
  }
2444
2788
  /**
2445
- * Remove a signer from a group.
2789
+ * Remove ONE signer from a group, unsigned, by its KSUID `signer_id`
2790
+ * (`DELETE /signer-groups/{id}/signers/{signer_id}`).
2791
+ *
2792
+ * A governed group refuses this with `EndorsementRequiredError`; use
2793
+ * {@link removeSignersSigned} instead. Not to be confused with
2794
+ * {@link removeSigners} (plural), the signed removal by PUBLIC KEY.
2446
2795
  *
2447
2796
  * @param signerGroupId - Signer group ID
2448
2797
  * @param signerId - The signer's KSUID `signer_id` — NOT its public key.
@@ -2453,11 +2802,257 @@ var SignerGroupsResource = class extends BaseResource {
2453
2802
  async removeSigner(signerGroupId, signerId, options) {
2454
2803
  await this.transport.request({
2455
2804
  method: "DELETE",
2456
- path: `/signer-groups/${signerGroupId}/signers/${signerId}`,
2805
+ path: `/signer-groups/${seg(signerGroupId)}/signers/${seg(signerId)}`,
2806
+ idempotencyKey: options?.idempotencyKey,
2807
+ timeout: options?.timeout
2808
+ });
2809
+ }
2810
+ // --------------------------------------------------------------------------
2811
+ // Signed (governed) membership and governance changes
2812
+ // --------------------------------------------------------------------------
2813
+ /**
2814
+ * Remove members by PUBLIC KEY, with signatures from the group's governance
2815
+ * (`POST /signer-groups/{id}/signer-removals`). Low level: you supply the
2816
+ * signed body, and `options.idempotencyKey` is required and MUST be the key
2817
+ * inside the signed intent. Prefer {@link removeSignersSigned}. (The
2818
+ * singular {@link removeSigner} is the unsigned removal by `signer_id`.)
2819
+ */
2820
+ async removeSigners(signerGroupId, data, options) {
2821
+ requireSignedKey("removeSigners", options);
2822
+ return this.transport.request({
2823
+ method: "POST",
2824
+ path: `/signer-groups/${seg(signerGroupId)}/signer-removals`,
2825
+ body: data,
2457
2826
  idempotencyKey: options?.idempotencyKey,
2458
2827
  timeout: options?.timeout
2459
2828
  });
2460
2829
  }
2830
+ /**
2831
+ * Replace a group's governance settings with signatures from its current
2832
+ * governance (`PATCH /signer-groups/{id}/governance`). The body is the
2833
+ * WHOLE state: a setting left out is cleared. Low level: you supply the
2834
+ * signed body, and `options.idempotencyKey` is required and MUST be the key
2835
+ * inside the signed intent. Prefer {@link updateGovernanceSigned}.
2836
+ */
2837
+ async updateGovernance(signerGroupId, data, options) {
2838
+ requireSignedKey("updateGovernance", options);
2839
+ return this.transport.request({
2840
+ method: "PATCH",
2841
+ path: `/signer-groups/${seg(signerGroupId)}/governance`,
2842
+ body: data,
2843
+ idempotencyKey: options?.idempotencyKey,
2844
+ timeout: options?.timeout
2845
+ });
2846
+ }
2847
+ /**
2848
+ * Build (but do not sign or send) the change that adds `memberKey` to the
2849
+ * group. Reads the group's current `version` unless
2850
+ * `options.signerGroupVersion` is given, and generates a lowercase UUID
2851
+ * idempotency key unless one is given.
2852
+ *
2853
+ * Use it when the signatures are collected elsewhere — for example a
2854
+ * passkey in the user's browser: send `change.canonical` there, pass it to
2855
+ * `buildChallenge`, then give the packed assertions to
2856
+ * {@link submitSignedChange}.
2857
+ */
2858
+ async prepareAddSigner(signerGroupId, memberKey, options) {
2859
+ return this.prepareChange(
2860
+ "add_signers_to_group",
2861
+ signerGroupId,
2862
+ { memberKeys: [memberKey] },
2863
+ options
2864
+ );
2865
+ }
2866
+ /**
2867
+ * Build (but do not sign or send) the change that removes `memberKeys`
2868
+ * (public keys, as the group lists them; signed in this order).
2869
+ */
2870
+ async prepareRemoveSigners(signerGroupId, memberKeys, options) {
2871
+ return this.prepareChange(
2872
+ "remove_signers_from_group",
2873
+ signerGroupId,
2874
+ { memberKeys: [...memberKeys] },
2875
+ options
2876
+ );
2877
+ }
2878
+ /**
2879
+ * Build (but do not sign or send) the change that sets the group's
2880
+ * governance to `settings`. It replaces the whole state: a setting left
2881
+ * out or null is cleared.
2882
+ */
2883
+ async prepareGovernanceUpdate(signerGroupId, settings, options) {
2884
+ const governance = {};
2885
+ if (settings.governance_threshold !== void 0 && settings.governance_threshold !== null) {
2886
+ governance.governance_threshold = settings.governance_threshold;
2887
+ }
2888
+ if (settings.governance_signer_group_id !== void 0 && settings.governance_signer_group_id !== null) {
2889
+ governance.governance_signer_group_id = settings.governance_signer_group_id;
2890
+ }
2891
+ return this.prepareChange(
2892
+ "update_signer_group_governance",
2893
+ signerGroupId,
2894
+ { governance },
2895
+ options
2896
+ );
2897
+ }
2898
+ /**
2899
+ * Send a prepared change with its signatures (ES256 DER base64, or packed
2900
+ * passkey assertions), using the change's idempotency key as
2901
+ * `X-Idempotency-Key`. Re-checks that the change still matches the intent
2902
+ * that was signed and refuses it otherwise, without sending anything.
2903
+ *
2904
+ * @throws EndorsementRequiredError, InsufficientEndorsementsError,
2905
+ * StaleSignerGroupVersionError, BelowThresholdError (all APIError)
2906
+ */
2907
+ async submitSignedChange(change, signatures, options) {
2908
+ if (!Array.isArray(signatures) || signatures.length === 0 || signatures.some((s) => typeof s !== "string" || s === "")) {
2909
+ throw new TypeError("a signed change needs at least one non-empty signature");
2910
+ }
2911
+ const built = buildChangeIntent(change);
2912
+ if (built.canonical !== change.canonical) {
2913
+ throw new Error(
2914
+ "the prepared change does not match the intent that was signed (it was altered after it was prepared); prepare it again"
2915
+ );
2916
+ }
2917
+ const i = built.intent;
2918
+ const requestOptions = { idempotencyKey: i.idempotency_key, timeout: options?.timeout };
2919
+ const sigs = [...signatures];
2920
+ switch (i.type) {
2921
+ case "add_signers_to_group":
2922
+ return this.addSigner(
2923
+ i.signer_group_id,
2924
+ {
2925
+ member_key: i.new_member_keys[0],
2926
+ signer_group_version: i.signer_group_version,
2927
+ signatures: sigs
2928
+ },
2929
+ requestOptions
2930
+ );
2931
+ case "remove_signers_from_group":
2932
+ return this.removeSigners(
2933
+ i.group_id,
2934
+ {
2935
+ members_to_remove: [...i.members_to_remove],
2936
+ signer_group_version: i.signer_group_version,
2937
+ signatures: sigs
2938
+ },
2939
+ requestOptions
2940
+ );
2941
+ case "update_signer_group_governance": {
2942
+ const body = {
2943
+ ...i.governance_threshold !== void 0 && {
2944
+ governance_threshold: i.governance_threshold
2945
+ },
2946
+ ...i.governance_signer_group_id !== void 0 && {
2947
+ governance_signer_group_id: i.governance_signer_group_id
2948
+ },
2949
+ signer_group_version: i.signer_group_version,
2950
+ signatures: sigs
2951
+ };
2952
+ return this.updateGovernance(i.signer_group_id, body, requestOptions);
2953
+ }
2954
+ default:
2955
+ throw new TypeError(`cannot submit a ${i.type} change from signerGroups`);
2956
+ }
2957
+ }
2958
+ /**
2959
+ * Add `memberKey` to a governed group in one call: read the version, build
2960
+ * the `add_signers_to_group` intent, sign it with each signer (in order),
2961
+ * and send it with the same idempotency key in the intent and the header.
2962
+ *
2963
+ * @param signers - ES256 signers (`ES256Signer`, your KMS) or plain
2964
+ * `(bytes) => signature` functions; together they must meet the group's
2965
+ * `effective_governance_threshold`. For a passkey in the user's browser
2966
+ * or app, use {@link prepareAddSigner} + {@link submitSignedChange}
2967
+ * instead, so the API key stays on your server; `webauthnSigner` fits
2968
+ * here only when the passkey prompt runs in the same process as this
2969
+ * client. Each stale retry calls every signer again.
2970
+ * @example
2971
+ * ```typescript
2972
+ * const group = await client.signerGroups.addSignerSigned(groupId, newKey, [
2973
+ * ES256Signer.fromPrivateKey(adminKeyPem),
2974
+ * ]);
2975
+ * ```
2976
+ */
2977
+ async addSignerSigned(signerGroupId, memberKey, signers, options) {
2978
+ return this.signAndSubmit(
2979
+ () => this.prepareAddSigner(signerGroupId, memberKey, options),
2980
+ signers,
2981
+ options
2982
+ );
2983
+ }
2984
+ /** Remove `memberKeys` from a governed group in one call; see {@link addSignerSigned}. */
2985
+ async removeSignersSigned(signerGroupId, memberKeys, signers, options) {
2986
+ return this.signAndSubmit(
2987
+ () => this.prepareRemoveSigners(signerGroupId, memberKeys, options),
2988
+ signers,
2989
+ options
2990
+ );
2991
+ }
2992
+ /**
2993
+ * Replace a group's governance settings in one call; see
2994
+ * {@link addSignerSigned}. Signed by the group's CURRENT governance.
2995
+ *
2996
+ * `staleRetries` is refused here: the change replaces the WHOLE governance
2997
+ * state, so re-signing it after someone else changed the group would
2998
+ * silently undo their change. On `StaleSignerGroupVersionError`, re-read
2999
+ * the group, decide, and call again.
3000
+ */
3001
+ async updateGovernanceSigned(signerGroupId, settings, signers, options) {
3002
+ if (options?.staleRetries) {
3003
+ throw new TypeError(
3004
+ "staleRetries is not supported on updateGovernanceSigned: a re-sign after a concurrent change would undo it"
3005
+ );
3006
+ }
3007
+ return this.signAndSubmit(
3008
+ () => this.prepareGovernanceUpdate(signerGroupId, settings, options),
3009
+ signers,
3010
+ options
3011
+ );
3012
+ }
3013
+ async prepareChange(kind, signerGroupId, fields, options) {
3014
+ if (options?.idempotencyKey !== void 0) {
3015
+ assertIdempotencyKey(options.idempotencyKey);
3016
+ }
3017
+ const signerGroupVersion = options?.signerGroupVersion ?? await this.currentVersion(signerGroupId);
3018
+ const draft = {
3019
+ kind,
3020
+ signerGroupId,
3021
+ signerGroupVersion,
3022
+ idempotencyKey: options?.idempotencyKey ?? governanceIdempotencyKey(),
3023
+ ...fields,
3024
+ canonical: ""
3025
+ };
3026
+ return { ...draft, canonical: buildChangeIntent(draft).canonical };
3027
+ }
3028
+ async currentVersion(signerGroupId) {
3029
+ const group = await this.get(signerGroupId);
3030
+ if (typeof group.version !== "number") {
3031
+ throw new Error(
3032
+ `signer group ${signerGroupId} has no version in the response, so a signed change cannot be built; pass signerGroupVersion if you know it`
3033
+ );
3034
+ }
3035
+ return group.version;
3036
+ }
3037
+ async signAndSubmit(prepare, signers, options) {
3038
+ if (!Array.isArray(signers) || signers.length === 0) {
3039
+ throw new TypeError("a governance change needs at least one signer");
3040
+ }
3041
+ let retries = staleRetryBudget(options);
3042
+ for (; ; ) {
3043
+ const change = await prepare();
3044
+ const signatures = await signGovernanceIntent(utf8(change.canonical), signers);
3045
+ try {
3046
+ return await this.submitSignedChange(change, signatures, { timeout: options?.timeout });
3047
+ } catch (err) {
3048
+ if (err instanceof StaleSignerGroupVersionError && retries > 0) {
3049
+ retries--;
3050
+ continue;
3051
+ }
3052
+ throw err;
3053
+ }
3054
+ }
3055
+ }
2461
3056
  /**
2462
3057
  * Get wallets attached to a signer group.
2463
3058
  *
@@ -2469,7 +3064,7 @@ var SignerGroupsResource = class extends BaseResource {
2469
3064
  async getWallets(signerGroupId) {
2470
3065
  return this.transport.request({
2471
3066
  method: "GET",
2472
- path: `/signer-groups/${signerGroupId}/wallets`
3067
+ path: `/signer-groups/${seg(signerGroupId)}/wallets`
2473
3068
  });
2474
3069
  }
2475
3070
  /**
@@ -2486,7 +3081,7 @@ var SignerGroupsResource = class extends BaseResource {
2486
3081
  async attachToWallet(walletId, signerGroupId, options) {
2487
3082
  await this.transport.request({
2488
3083
  method: "PUT",
2489
- path: `/wallets/${walletId}/signer-groups/${signerGroupId}`,
3084
+ path: `/wallets/${seg(walletId)}/signer-groups/${seg(signerGroupId)}`,
2490
3085
  body: options?.endorsement,
2491
3086
  idempotencyKey: options?.idempotencyKey,
2492
3087
  timeout: options?.timeout
@@ -2506,7 +3101,7 @@ var SignerGroupsResource = class extends BaseResource {
2506
3101
  async detachFromWallet(walletId, signerGroupId, options) {
2507
3102
  await this.transport.request({
2508
3103
  method: "DELETE",
2509
- path: `/wallets/${walletId}/signer-groups/${signerGroupId}`,
3104
+ path: `/wallets/${seg(walletId)}/signer-groups/${seg(signerGroupId)}`,
2510
3105
  body: options?.endorsement,
2511
3106
  idempotencyKey: options?.idempotencyKey,
2512
3107
  timeout: options?.timeout
@@ -2523,6 +3118,65 @@ var SignerGroupsResource = class extends BaseResource {
2523
3118
  return this.paginate(`/wallets/${walletId}/signer-groups`, params);
2524
3119
  }
2525
3120
  };
3121
+ function seg(id) {
3122
+ if (typeof id !== "string" || id === "" || id === "." || id === "..") {
3123
+ throw new TypeError(`invalid id for a request path: ${JSON.stringify(id)}`);
3124
+ }
3125
+ return encodeURIComponent(id);
3126
+ }
3127
+ var MAX_STALE_RETRIES = 5;
3128
+ function staleRetryBudget(options) {
3129
+ const n = options?.staleRetries ?? 0;
3130
+ if (!Number.isInteger(n) || n < 0 || n > MAX_STALE_RETRIES) {
3131
+ throw new TypeError(`staleRetries must be an integer from 0 to ${MAX_STALE_RETRIES}`);
3132
+ }
3133
+ if (n > 0 && (options?.signerGroupVersion !== void 0 || options?.idempotencyKey !== void 0)) {
3134
+ throw new TypeError(
3135
+ "staleRetries cannot be combined with a fixed signerGroupVersion or idempotencyKey: a retry needs a fresh read and a fresh key"
3136
+ );
3137
+ }
3138
+ return n;
3139
+ }
3140
+ function governanceIdempotencyKey() {
3141
+ const c = globalThis.crypto;
3142
+ return typeof c?.randomUUID === "function" ? newIdempotencyKey() : crypto.randomUUID().toLowerCase();
3143
+ }
3144
+ function requireSignedKey(method, options) {
3145
+ if (!options?.idempotencyKey) {
3146
+ throw new TypeError(
3147
+ `${method} with signatures needs options.idempotencyKey: the idempotency_key inside the signed intent (a generated one could never match)`
3148
+ );
3149
+ }
3150
+ assertIdempotencyKey(options.idempotencyKey);
3151
+ }
3152
+ function buildChangeIntent(change) {
3153
+ const common = {
3154
+ signerGroupId: change.signerGroupId,
3155
+ signerGroupVersion: change.signerGroupVersion,
3156
+ idempotencyKey: change.idempotencyKey
3157
+ };
3158
+ switch (change.kind) {
3159
+ case "add_signers_to_group":
3160
+ if (!change.memberKeys || change.memberKeys.length !== 1) {
3161
+ throw new TypeError(
3162
+ "an add change carries exactly one member key (the endpoint adds one per request)"
3163
+ );
3164
+ }
3165
+ return addSignersToGroupIntent({ ...common, newMemberKeys: change.memberKeys });
3166
+ case "remove_signers_from_group":
3167
+ return removeSignersFromGroupIntent({ ...common, membersToRemove: change.memberKeys ?? [] });
3168
+ case "update_signer_group_governance":
3169
+ return updateSignerGroupGovernanceIntent({
3170
+ ...common,
3171
+ governanceThreshold: change.governance?.governance_threshold,
3172
+ governanceSignerGroupId: change.governance?.governance_signer_group_id
3173
+ });
3174
+ default:
3175
+ throw new TypeError(
3176
+ `unknown signer-group change kind ${JSON.stringify(change.kind)}`
3177
+ );
3178
+ }
3179
+ }
2526
3180
  var SignersResource = class extends BaseResource {
2527
3181
  /**
2528
3182
  * Create a new signer.
@@ -2581,6 +3235,23 @@ var ApiKeysResource = class extends BaseResource {
2581
3235
  list(params) {
2582
3236
  return this.paginate("/api-keys", params);
2583
3237
  }
3238
+ /**
3239
+ * Change the name, the scope, or both, of an API key. A new scope applies
3240
+ * from the next request made with the key. The key value does not change.
3241
+ *
3242
+ * @param apiKeyId - API key ID
3243
+ * @param data - The new name, the new scope, or both
3244
+ * @returns The updated API key
3245
+ */
3246
+ async update(apiKeyId, data, options) {
3247
+ return this.transport.request({
3248
+ method: "PATCH",
3249
+ path: `/api-keys/${apiKeyId}`,
3250
+ body: data,
3251
+ idempotencyKey: options?.idempotencyKey,
3252
+ timeout: options?.timeout
3253
+ });
3254
+ }
2584
3255
  /**
2585
3256
  * Delete an API key.
2586
3257
  *
@@ -2905,11 +3576,11 @@ var LegalResource = class extends BaseResource {
2905
3576
  * });
2906
3577
  * ```
2907
3578
  */
2908
- async get(documentKey, version) {
3579
+ async get(documentKey, version2) {
2909
3580
  return this.transport.request({
2910
3581
  method: "GET",
2911
3582
  path: `/legal/documents/${documentKey}`,
2912
- query: version !== void 0 ? { version } : void 0
3583
+ query: version2 !== void 0 ? { version: version2 } : void 0
2913
3584
  });
2914
3585
  }
2915
3586
  };
@@ -3127,21 +3798,16 @@ var SandboxResource = class extends BaseResource {
3127
3798
  * @param data - Simulation request data
3128
3799
  * @returns Simulation response with previous and new state
3129
3800
  *
3130
- * @example Approve KYB and activate applicant
3801
+ * `applicant_activate` runs the same code path as `kyb_approve`. One call
3802
+ * is enough: do not send `applicant_activate` after `kyb_approve`.
3803
+ *
3804
+ * @example Approve an application
3131
3805
  * ```typescript
3132
- * // Step 1: Approve the KYB application
3133
3806
  * await client.sandbox.simulateOnboarding({
3134
3807
  * type: 'kyb_approve',
3135
3808
  * applicant_id: customer.application_id,
3136
3809
  * simulation_id: `sim_kyb_${Date.now()}`,
3137
3810
  * });
3138
- *
3139
- * // Step 2: Activate the applicant (triggers provisioning)
3140
- * await client.sandbox.simulateOnboarding({
3141
- * type: 'applicant_activate',
3142
- * applicant_id: customer.application_id,
3143
- * simulation_id: `sim_activate_${Date.now()}`,
3144
- * });
3145
3811
  * ```
3146
3812
  *
3147
3813
  * @example Reject a KYB application
@@ -4365,41 +5031,84 @@ var DakotaClient = class {
4365
5031
  return this.config.baseURL;
4366
5032
  }
4367
5033
  };
4368
-
4369
- // src/agentic/canonicalize.ts
4370
- function canonicalJSON(value) {
4371
- return canonicalize(value);
4372
- }
4373
- function canonicalize(value) {
4374
- if (value === null || value === void 0) {
4375
- return "null";
5034
+ var ES256Signer = class _ES256Signer {
5035
+ privateKey;
5036
+ publicKey;
5037
+ constructor(privateKey, publicKey) {
5038
+ this.privateKey = privateKey;
5039
+ this.publicKey = publicKey;
4376
5040
  }
4377
- if (typeof value === "boolean") {
4378
- return value ? "true" : "false";
5041
+ /**
5042
+ * Generate a fresh P-256 keypair.
5043
+ */
5044
+ static generate() {
5045
+ const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" });
5046
+ return new _ES256Signer(privateKey, publicKey);
4379
5047
  }
4380
- if (typeof value === "number") {
4381
- if (!Number.isFinite(value)) {
4382
- throw new TypeError(`canonical JSON: non-finite number ${value}`);
5048
+ /**
5049
+ * Adopt an existing P-256 private key. Accepts a PKCS#8 PEM string, a
5050
+ * DER-encoded PKCS#8 buffer, or a Node {@link KeyObject}.
5051
+ */
5052
+ static fromPrivateKey(key) {
5053
+ const privateKey = typeof key === "string" || key instanceof Uint8Array ? crypto.createPrivateKey({
5054
+ key,
5055
+ format: typeof key === "string" ? "pem" : "der",
5056
+ type: "pkcs8"
5057
+ }) : key;
5058
+ if (privateKey.asymmetricKeyType !== "ec") {
5059
+ throw new Error("a P-256 private key is required (ES256)");
4383
5060
  }
4384
- return JSON.stringify(value);
5061
+ const details = privateKey.asymmetricKeyDetails;
5062
+ if (details?.namedCurve !== "prime256v1") {
5063
+ throw new Error("a P-256 private key is required (ES256)");
5064
+ }
5065
+ const publicKey = crypto.createPublicKey(privateKey);
5066
+ return new _ES256Signer(privateKey, publicKey);
4385
5067
  }
4386
- if (typeof value === "string") {
4387
- return JSON.stringify(value);
5068
+ /**
5069
+ * base64 PKIX (SPKI) public key — pass this as the signer's registered
5070
+ * public key at agent creation / mandate approval.
5071
+ */
5072
+ publicKeyBase64() {
5073
+ const der = this.publicKey.export({ format: "der", type: "spki" });
5074
+ return Buffer.from(der).toString("base64");
4388
5075
  }
4389
- if (typeof value === "bigint") {
4390
- throw new TypeError("canonical JSON: bigint values are not supported");
5076
+ /**
5077
+ * Returns base64( ASN.1 ECDSA signature over SHA-256(payload) ).
5078
+ */
5079
+ sign(payload) {
5080
+ const signer = crypto.createSign("SHA256");
5081
+ signer.update(payload);
5082
+ const sig = signer.sign({ key: this.privateKey, dsaEncoding: "der" });
5083
+ return Buffer.from(sig).toString("base64");
4391
5084
  }
4392
- if (Array.isArray(value)) {
4393
- const parts = value.map((item) => canonicalize(item));
4394
- return `[${parts.join(",")}]`;
5085
+ };
5086
+ function verifyES256Signature(publicKeyBase64, payload, signatureBase64) {
5087
+ let publicKey;
5088
+ try {
5089
+ publicKey = crypto.createPublicKey({
5090
+ key: Buffer.from(publicKeyBase64, "base64"),
5091
+ format: "der",
5092
+ type: "spki"
5093
+ });
5094
+ } catch (err) {
5095
+ throw new Error(`parse public key: ${err.message}`);
4395
5096
  }
4396
- if (typeof value === "object") {
4397
- const obj = value;
4398
- const keys = Object.keys(obj).sort();
4399
- const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);
4400
- return `{${parts.join(",")}}`;
5097
+ if (publicKey.asymmetricKeyType !== "ec") {
5098
+ throw new Error("not a P-256 public key (ES256 requires P-256)");
5099
+ }
5100
+ if (publicKey.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
5101
+ throw new Error("not a P-256 public key (ES256 requires P-256)");
5102
+ }
5103
+ const verifier = crypto.createVerify("SHA256");
5104
+ verifier.update(payload);
5105
+ const ok = verifier.verify(
5106
+ { key: publicKey, dsaEncoding: "der" },
5107
+ Buffer.from(signatureBase64, "base64")
5108
+ );
5109
+ if (!ok) {
5110
+ throw new Error("signature verification failed");
4401
5111
  }
4402
- throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);
4403
5112
  }
4404
5113
 
4405
5114
  // src/agentic/sign.ts
@@ -4423,14 +5132,14 @@ function mandateSignPayload(mandate, action) {
4423
5132
  });
4424
5133
  return new TextEncoder().encode(encoded);
4425
5134
  }
4426
- function mandateAmendSignPayload(mandate, version, rule) {
5135
+ function mandateAmendSignPayload(mandate, version2, rule) {
4427
5136
  if (!mandate.id) {
4428
5137
  throw new Error("mandate has no id");
4429
5138
  }
4430
5139
  if (!mandate.bound_signer_id) {
4431
5140
  throw new Error("mandate has no bound_signer_id");
4432
5141
  }
4433
- if (!Number.isInteger(version) || version < 2) {
5142
+ if (!Number.isInteger(version2) || version2 < 2) {
4434
5143
  throw new Error("amend version must be an integer >= 2 (the version being created)");
4435
5144
  }
4436
5145
  const encoded = canonicalJSON({
@@ -4440,7 +5149,7 @@ function mandateAmendSignPayload(mandate, version, rule) {
4440
5149
  rule,
4441
5150
  valid_from: mandate.valid_from ?? 0,
4442
5151
  valid_until: mandate.valid_until ?? 0,
4443
- version
5152
+ version: version2
4444
5153
  });
4445
5154
  return new TextEncoder().encode(encoded);
4446
5155
  }
@@ -4529,84 +5238,105 @@ function addPolicyRulePayload(policyId, action, ruleType, definition, idempotenc
4529
5238
  function textBytes(s) {
4530
5239
  return new TextEncoder().encode(s);
4531
5240
  }
4532
- var P256MandateSigner = class _P256MandateSigner {
4533
- privateKey;
4534
- publicKey;
4535
- constructor(privateKey, publicKey) {
4536
- this.privateKey = privateKey;
4537
- this.publicKey = publicKey;
5241
+
5242
+ // src/governance/webauthn.ts
5243
+ function buildChallenge(intent) {
5244
+ const bytes = challengeBytes(intent);
5245
+ const out = new ArrayBuffer(bytes.length);
5246
+ new Uint8Array(out).set(bytes);
5247
+ return out;
5248
+ }
5249
+ function challengeBytes(intent) {
5250
+ if (typeof intent === "string") {
5251
+ return utf8(intent);
4538
5252
  }
4539
- /**
4540
- * Generate a fresh P-256 keypair.
4541
- */
4542
- static generate() {
4543
- const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" });
4544
- return new _P256MandateSigner(privateKey, publicKey);
5253
+ if (isBinary(intent)) {
5254
+ return toBytes(intent);
4545
5255
  }
4546
- /**
4547
- * Adopt an existing P-256 private key. Accepts a PKCS#8 PEM string, a
4548
- * DER-encoded PKCS#8 buffer, or a Node {@link KeyObject}.
4549
- */
4550
- static fromPrivateKey(key) {
4551
- const privateKey = typeof key === "string" || key instanceof Uint8Array ? crypto.createPrivateKey({
4552
- key,
4553
- format: typeof key === "string" ? "pem" : "der",
4554
- type: "pkcs8"
4555
- }) : key;
4556
- if (privateKey.asymmetricKeyType !== "ec") {
4557
- throw new Error("a P-256 private key is required (ES256)");
5256
+ if (intent && typeof intent === "object") {
5257
+ const canonical = intent.canonical;
5258
+ if (typeof canonical === "string") {
5259
+ return utf8(canonical);
4558
5260
  }
4559
- const details = privateKey.asymmetricKeyDetails;
4560
- if (details?.namedCurve !== "prime256v1") {
4561
- throw new Error("a P-256 private key is required (ES256)");
4562
- }
4563
- const publicKey = crypto.createPublicKey(privateKey);
4564
- return new _P256MandateSigner(privateKey, publicKey);
4565
5261
  }
4566
- /**
4567
- * base64 PKIX (SPKI) public key — pass this as the signer's registered
4568
- * public key at agent creation / mandate approval.
4569
- */
4570
- publicKeyBase64() {
4571
- const der = this.publicKey.export({ format: "der", type: "spki" });
4572
- return Buffer.from(der).toString("base64");
5262
+ throw new TypeError(
5263
+ "expected a built intent, a prepared change, its canonical string, or its bytes"
5264
+ );
5265
+ }
5266
+ function isBinary(v) {
5267
+ return ArrayBuffer.isView(v) || Object.prototype.toString.call(v) === "[object ArrayBuffer]";
5268
+ }
5269
+ function b64urlField(name, value) {
5270
+ if (value === void 0 || value === null || value === "") {
5271
+ throw new TypeError(`passkey assertion is missing ${name}`);
4573
5272
  }
4574
- /**
4575
- * Returns base64( ASN.1 ECDSA signature over SHA-256(payload) ).
4576
- */
4577
- sign(payload) {
4578
- const signer = crypto.createSign("SHA256");
4579
- signer.update(payload);
4580
- const sig = signer.sign({ key: this.privateKey, dsaEncoding: "der" });
4581
- return Buffer.from(sig).toString("base64");
5273
+ if (typeof value === "string") {
5274
+ return bytesToBase64url(base64ToBytes(value));
4582
5275
  }
4583
- };
4584
- function verifyMandateSignature(publicKeyBase64, payload, signatureBase64) {
4585
- let publicKey;
4586
- try {
4587
- publicKey = crypto.createPublicKey({
4588
- key: Buffer.from(publicKeyBase64, "base64"),
4589
- format: "der",
4590
- type: "spki"
4591
- });
4592
- } catch (err) {
4593
- throw new Error(`parse public key: ${err.message}`);
5276
+ return bytesToBase64url(toBytes(value));
5277
+ }
5278
+ function packAssertion(credential) {
5279
+ if (!credential || credential.type !== "public-key") {
5280
+ throw new TypeError('expected a WebAuthn assertion with type "public-key"');
4594
5281
  }
4595
- if (publicKey.asymmetricKeyType !== "ec") {
4596
- throw new Error("not a P-256 public key (ES256 requires P-256)");
5282
+ if (typeof credential.id !== "string" || credential.id === "") {
5283
+ throw new TypeError("passkey assertion is missing id");
4597
5284
  }
4598
- if (publicKey.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
4599
- throw new Error("not a P-256 public key (ES256 requires P-256)");
5285
+ const r = credential.response;
5286
+ if (!r) {
5287
+ throw new TypeError("passkey assertion is missing response");
4600
5288
  }
4601
- const verifier = crypto.createVerify("SHA256");
4602
- verifier.update(payload);
4603
- const ok = verifier.verify(
4604
- { key: publicKey, dsaEncoding: "der" },
4605
- Buffer.from(signatureBase64, "base64")
4606
- );
4607
- if (!ok) {
4608
- throw new Error("signature verification failed");
5289
+ const response = {
5290
+ clientDataJSON: b64urlField("clientDataJSON", r.clientDataJSON),
5291
+ authenticatorData: b64urlField("authenticatorData", r.authenticatorData),
5292
+ signature: b64urlField("signature", r.signature)
5293
+ };
5294
+ if (r.userHandle !== void 0 && r.userHandle !== null && r.userHandle !== "") {
5295
+ response.userHandle = b64urlField("userHandle", r.userHandle);
5296
+ }
5297
+ const envelope = {
5298
+ // The verifier requires `id` to be base64url; some mobile libraries hand
5299
+ // out standard base64, so normalize it like the binary fields.
5300
+ id: b64urlField("id", credential.id),
5301
+ rawId: b64urlField("rawId", credential.rawId),
5302
+ type: "public-key",
5303
+ clientExtensionResults: {},
5304
+ response
5305
+ };
5306
+ if (credential.authenticatorAttachment) {
5307
+ envelope.authenticatorAttachment = credential.authenticatorAttachment;
4609
5308
  }
5309
+ return bytesToBase64url(utf8(JSON.stringify(envelope)));
5310
+ }
5311
+ var MAX_PACKED_ASSERTION_LENGTH = 64 * 1024;
5312
+ function assertionChallengeMatches(packed, intent) {
5313
+ if (typeof packed !== "string" || packed.length > MAX_PACKED_ASSERTION_LENGTH) {
5314
+ return false;
5315
+ }
5316
+ try {
5317
+ const envelope = JSON.parse(new TextDecoder().decode(base64ToBytes(packed)));
5318
+ const clientDataB64 = envelope.response?.clientDataJSON;
5319
+ if (typeof clientDataB64 !== "string") {
5320
+ return false;
5321
+ }
5322
+ const clientData = JSON.parse(new TextDecoder().decode(base64ToBytes(clientDataB64)));
5323
+ if (typeof clientData.challenge !== "string") {
5324
+ return false;
5325
+ }
5326
+ const got = base64ToBytes(clientData.challenge);
5327
+ const want = new Uint8Array(buildChallenge(intent));
5328
+ return got.length === want.length && got.every((b, i) => b === want[i]);
5329
+ } catch {
5330
+ return false;
5331
+ }
5332
+ }
5333
+ function webauthnSigner(getAssertion) {
5334
+ return {
5335
+ async sign(payload) {
5336
+ const credential = await getAssertion(buildChallenge(payload));
5337
+ return packAssertion(credential);
5338
+ }
5339
+ };
4610
5340
  }
4611
5341
 
4612
5342
  exports.APIError = APIError;
@@ -4617,19 +5347,24 @@ exports.ApiKeysResource = ApiKeysResource;
4617
5347
  exports.ApplicationsResource = ApplicationsResource;
4618
5348
  exports.AuthMode = AuthMode;
4619
5349
  exports.AutoTransactionsResource = AutoTransactionsResource;
5350
+ exports.BelowThresholdError = BelowThresholdError;
4620
5351
  exports.ConfigurationError = ConfigurationError;
4621
5352
  exports.CustomersResource = CustomersResource;
4622
5353
  exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY;
4623
5354
  exports.DakotaClient = DakotaClient;
4624
5355
  exports.DestinationsResource = DestinationsResource;
5356
+ exports.ES256Signer = ES256Signer;
5357
+ exports.EndorsementRequiredError = EndorsementRequiredError;
4625
5358
  exports.Environment = Environment;
4626
5359
  exports.EventsResource = EventsResource;
4627
5360
  exports.FeePayoutDestinationResource = FeePayoutDestinationResource;
4628
5361
  exports.InfoResource = InfoResource;
4629
5362
  exports.InsightsResource = InsightsResource;
4630
5363
  exports.InstructionsResource = InstructionsResource;
5364
+ exports.InsufficientEndorsementsError = InsufficientEndorsementsError;
5365
+ exports.InvalidGoverningGroupError = InvalidGoverningGroupError;
4631
5366
  exports.MandatesResource = MandatesResource;
4632
- exports.P256MandateSigner = P256MandateSigner;
5367
+ exports.P256MandateSigner = ES256Signer;
4633
5368
  exports.PaginatedIterator = PaginatedIterator;
4634
5369
  exports.PaymentAgentsResource = PaymentAgentsResource;
4635
5370
  exports.PoliciesResource = PoliciesResource;
@@ -4639,17 +5374,23 @@ exports.ScheduledPaymentsResource = ScheduledPaymentsResource;
4639
5374
  exports.SelfServeResource = SelfServeResource;
4640
5375
  exports.SignerGroupsResource = SignerGroupsResource;
4641
5376
  exports.SignersResource = SignersResource;
5377
+ exports.StaleSignerGroupVersionError = StaleSignerGroupVersionError;
4642
5378
  exports.TransactionsResource = TransactionsResource;
4643
5379
  exports.TransportError = TransportError;
4644
5380
  exports.UsersResource = UsersResource;
4645
5381
  exports.WalletsResource = WalletsResource;
4646
5382
  exports.WebhooksResource = WebhooksResource;
4647
5383
  exports.addPolicyRulePayload = addPolicyRulePayload;
5384
+ exports.addSignersToGroupIntent = addSignersToGroupIntent;
5385
+ exports.assertIdempotencyKey = assertIdempotencyKey;
5386
+ exports.assertionChallengeMatches = assertionChallengeMatches;
4648
5387
  exports.attachGroupPayload = attachGroupPayload;
4649
5388
  exports.attachPolicyPayload = attachPolicyPayload;
4650
5389
  exports.attachUserToWallet = attachUserToWallet;
5390
+ exports.buildChallenge = buildChallenge;
4651
5391
  exports.canonicalJSON = canonicalJSON;
4652
5392
  exports.consoleLogger = consoleLogger;
5393
+ exports.createCryptoDestinationIntent = createCryptoDestinationIntent;
4653
5394
  exports.deletePolicyPayload = deletePolicyPayload;
4654
5395
  exports.detachGroupPayload = detachGroupPayload;
4655
5396
  exports.detachPolicyPayload = detachPolicyPayload;
@@ -4657,10 +5398,18 @@ exports.detachUserFromWallet = detachUserFromWallet;
4657
5398
  exports.getEnvironmentURL = getEnvironmentURL;
4658
5399
  exports.mandateAmendSignPayload = mandateAmendSignPayload;
4659
5400
  exports.mandateSignPayload = mandateSignPayload;
5401
+ exports.newIdempotencyKey = newIdempotencyKey;
4660
5402
  exports.noopLogger = noopLogger;
5403
+ exports.packAssertion = packAssertion;
4661
5404
  exports.paginate = paginate;
4662
5405
  exports.removePolicyRulePayload = removePolicyRulePayload;
5406
+ exports.removeSignersFromGroupIntent = removeSignersFromGroupIntent;
5407
+ exports.signGovernanceIntent = signGovernanceIntent;
4663
5408
  exports.updatePolicyRulePayload = updatePolicyRulePayload;
4664
- exports.verifyMandateSignature = verifyMandateSignature;
5409
+ exports.updateSignerGroupGovernanceIntent = updateSignerGroupGovernanceIntent;
5410
+ exports.verifyES256Signature = verifyES256Signature;
5411
+ exports.verifyMandateSignature = verifyES256Signature;
5412
+ exports.webCryptoES256Signer = webCryptoES256Signer;
5413
+ exports.webauthnSigner = webauthnSigner;
4665
5414
  //# sourceMappingURL=index.js.map
4666
5415
  //# sourceMappingURL=index.js.map