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