@dakota-xyz/ts-sdk 3.0.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.
@@ -0,0 +1,379 @@
1
+ 'use strict';
2
+
3
+ // src/agentic/canonicalize.ts
4
+ function canonicalJSON(value) {
5
+ return canonicalize(value);
6
+ }
7
+ function canonicalize(value) {
8
+ if (value === null || value === void 0) {
9
+ return "null";
10
+ }
11
+ if (typeof value === "boolean") {
12
+ return value ? "true" : "false";
13
+ }
14
+ if (typeof value === "number") {
15
+ if (!Number.isFinite(value)) {
16
+ throw new TypeError(`canonical JSON: non-finite number ${value}`);
17
+ }
18
+ return JSON.stringify(value);
19
+ }
20
+ if (typeof value === "string") {
21
+ return JSON.stringify(value);
22
+ }
23
+ if (typeof value === "bigint") {
24
+ throw new TypeError("canonical JSON: bigint values are not supported");
25
+ }
26
+ if (Array.isArray(value)) {
27
+ const parts = value.map((item) => canonicalize(item));
28
+ return `[${parts.join(",")}]`;
29
+ }
30
+ if (typeof value === "object") {
31
+ const obj = value;
32
+ const keys = Object.keys(obj).sort();
33
+ const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);
34
+ return `{${parts.join(",")}}`;
35
+ }
36
+ throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);
37
+ }
38
+
39
+ // src/governance/encoding.ts
40
+ var B64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
41
+ function bytesToBase64(bytes) {
42
+ let out = "";
43
+ let i = 0;
44
+ for (; i + 2 < bytes.length; i += 3) {
45
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
46
+ out += B64_ALPHABET[n >> 18 & 63] + B64_ALPHABET[n >> 12 & 63] + B64_ALPHABET[n >> 6 & 63] + B64_ALPHABET[n & 63];
47
+ }
48
+ const rest = bytes.length - i;
49
+ if (rest === 1) {
50
+ const n = bytes[i] << 16;
51
+ out += B64_ALPHABET[n >> 18 & 63] + B64_ALPHABET[n >> 12 & 63] + "==";
52
+ } else if (rest === 2) {
53
+ const n = bytes[i] << 16 | bytes[i + 1] << 8;
54
+ out += B64_ALPHABET[n >> 18 & 63] + B64_ALPHABET[n >> 12 & 63] + B64_ALPHABET[n >> 6 & 63] + "=";
55
+ }
56
+ return out;
57
+ }
58
+ function bytesToBase64url(bytes) {
59
+ return stripPadding(bytesToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_"));
60
+ }
61
+ function stripPadding(s) {
62
+ let end = s.length;
63
+ while (end > 0 && s.charCodeAt(end - 1) === 61) end--;
64
+ return s.slice(0, end);
65
+ }
66
+ function base64ToBytes(input) {
67
+ const s = stripPadding(input.replace(/-/g, "+").replace(/_/g, "/"));
68
+ if (!/^[A-Za-z0-9+/]*$/.test(s) || s.length % 4 === 1) {
69
+ throw new TypeError("invalid base64 or base64url string");
70
+ }
71
+ const out = new Uint8Array(Math.floor(s.length * 3 / 4));
72
+ let o = 0;
73
+ for (let i = 0; i < s.length; i += 4) {
74
+ const a = B64_ALPHABET.indexOf(s[i]);
75
+ const b = B64_ALPHABET.indexOf(s[i + 1]);
76
+ const c = i + 2 < s.length ? B64_ALPHABET.indexOf(s[i + 2]) : 0;
77
+ const d = i + 3 < s.length ? B64_ALPHABET.indexOf(s[i + 3]) : 0;
78
+ const n = a << 18 | b << 12 | c << 6 | d;
79
+ out[o++] = n >> 16 & 255;
80
+ if (i + 2 < s.length) out[o++] = n >> 8 & 255;
81
+ if (i + 3 < s.length) out[o++] = n & 255;
82
+ }
83
+ return out;
84
+ }
85
+ function utf8(s) {
86
+ return new TextEncoder().encode(s);
87
+ }
88
+ function toBytes(source) {
89
+ if (ArrayBuffer.isView(source)) {
90
+ return new Uint8Array(source.buffer, source.byteOffset, source.byteLength).slice();
91
+ }
92
+ if (Object.prototype.toString.call(source) === "[object ArrayBuffer]") {
93
+ return new Uint8Array(source.slice(0));
94
+ }
95
+ throw new TypeError("expected an ArrayBuffer or a typed array");
96
+ }
97
+
98
+ // src/governance/intents.ts
99
+ var LOWERCASE_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
100
+ function assertIdempotencyKey(key) {
101
+ if (typeof key !== "string" || !LOWERCASE_UUID.test(key)) {
102
+ throw new TypeError(
103
+ `idempotency key must be a lowercase UUID (got ${JSON.stringify(key)}); the platform refuses any other form`
104
+ );
105
+ }
106
+ }
107
+ function newIdempotencyKey() {
108
+ const c = globalThis.crypto;
109
+ if (c && typeof c.randomUUID === "function") {
110
+ return c.randomUUID().toLowerCase();
111
+ }
112
+ if (!c || typeof c.getRandomValues !== "function") {
113
+ throw new Error("no cryptographic random source: pass an idempotency key explicitly");
114
+ }
115
+ const b = c.getRandomValues(new Uint8Array(16));
116
+ b[6] = b[6] & 15 | 64;
117
+ b[8] = b[8] & 63 | 128;
118
+ const hex = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
119
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
120
+ }
121
+ function nonEmpty(name, value) {
122
+ if (typeof value !== "string" || value === "") {
123
+ throw new TypeError(`${name} is required`);
124
+ }
125
+ return value;
126
+ }
127
+ function keyList(name, keys) {
128
+ if (!Array.isArray(keys) || keys.length === 0) {
129
+ throw new TypeError(`${name} must list at least one public key`);
130
+ }
131
+ return keys.map((k, i) => {
132
+ const key = nonEmpty(`${name}[${i}]`, k);
133
+ if (key.trim() !== key) {
134
+ throw new TypeError(`${name}[${i}] has leading or trailing whitespace; trim it first`);
135
+ }
136
+ return key;
137
+ });
138
+ }
139
+ function version(v) {
140
+ if (!Number.isSafeInteger(v) || v < 0) {
141
+ throw new TypeError(
142
+ `signer_group_version must be a non-negative integer (got ${String(v)}); read it from the group's \`version\``
143
+ );
144
+ }
145
+ return v;
146
+ }
147
+ function finish(intent) {
148
+ const canonical = canonicalJSON(intent);
149
+ return { intent, canonical, bytes: utf8(canonical) };
150
+ }
151
+ function addSignersToGroupIntent(params) {
152
+ assertIdempotencyKey(params.idempotencyKey);
153
+ return finish({
154
+ type: "add_signers_to_group",
155
+ signer_group_id: nonEmpty("signerGroupId", params.signerGroupId),
156
+ new_member_keys: keyList("newMemberKeys", params.newMemberKeys),
157
+ signer_group_version: version(params.signerGroupVersion),
158
+ idempotency_key: params.idempotencyKey
159
+ });
160
+ }
161
+ function removeSignersFromGroupIntent(params) {
162
+ assertIdempotencyKey(params.idempotencyKey);
163
+ return finish({
164
+ type: "remove_signers_from_group",
165
+ group_id: nonEmpty("signerGroupId", params.signerGroupId),
166
+ members_to_remove: keyList("membersToRemove", params.membersToRemove),
167
+ signer_group_version: version(params.signerGroupVersion),
168
+ idempotency_key: params.idempotencyKey
169
+ });
170
+ }
171
+ function updateSignerGroupGovernanceIntent(params) {
172
+ assertIdempotencyKey(params.idempotencyKey);
173
+ const intent = {
174
+ type: "update_signer_group_governance",
175
+ signer_group_id: nonEmpty("signerGroupId", params.signerGroupId),
176
+ signer_group_version: version(params.signerGroupVersion),
177
+ idempotency_key: params.idempotencyKey
178
+ };
179
+ if (params.governanceThreshold !== void 0 && params.governanceThreshold !== null) {
180
+ const t = params.governanceThreshold;
181
+ if (!Number.isSafeInteger(t) || t < 1 || t > 2147483647) {
182
+ throw new TypeError(
183
+ "governanceThreshold must be an integer from 1 to 2^31-1, or null to clear it"
184
+ );
185
+ }
186
+ intent.governance_threshold = params.governanceThreshold;
187
+ }
188
+ if (params.governanceSignerGroupId !== void 0 && params.governanceSignerGroupId !== null) {
189
+ intent.governance_signer_group_id = nonEmpty(
190
+ "governanceSignerGroupId",
191
+ params.governanceSignerGroupId
192
+ );
193
+ }
194
+ return finish(intent);
195
+ }
196
+ function createCryptoDestinationIntent(params) {
197
+ assertIdempotencyKey(params.idempotencyKey);
198
+ return finish({
199
+ type: "create_crypto_destination",
200
+ recipient_id: nonEmpty("recipientId", params.recipientId),
201
+ network_id: nonEmpty("networkId", params.networkId),
202
+ address: nonEmpty("address", params.address),
203
+ signer_group_id: nonEmpty("signerGroupId", params.signerGroupId),
204
+ idempotency_key: params.idempotencyKey
205
+ });
206
+ }
207
+
208
+ // src/governance/webauthn.ts
209
+ function buildChallenge(intent) {
210
+ const bytes = challengeBytes(intent);
211
+ const out = new ArrayBuffer(bytes.length);
212
+ new Uint8Array(out).set(bytes);
213
+ return out;
214
+ }
215
+ function challengeBytes(intent) {
216
+ if (typeof intent === "string") {
217
+ return utf8(intent);
218
+ }
219
+ if (isBinary(intent)) {
220
+ return toBytes(intent);
221
+ }
222
+ if (intent && typeof intent === "object") {
223
+ const canonical = intent.canonical;
224
+ if (typeof canonical === "string") {
225
+ return utf8(canonical);
226
+ }
227
+ }
228
+ throw new TypeError(
229
+ "expected a built intent, a prepared change, its canonical string, or its bytes"
230
+ );
231
+ }
232
+ function isBinary(v) {
233
+ return ArrayBuffer.isView(v) || Object.prototype.toString.call(v) === "[object ArrayBuffer]";
234
+ }
235
+ function b64urlField(name, value) {
236
+ if (value === void 0 || value === null || value === "") {
237
+ throw new TypeError(`passkey assertion is missing ${name}`);
238
+ }
239
+ if (typeof value === "string") {
240
+ return bytesToBase64url(base64ToBytes(value));
241
+ }
242
+ return bytesToBase64url(toBytes(value));
243
+ }
244
+ function packAssertion(credential) {
245
+ if (!credential || credential.type !== "public-key") {
246
+ throw new TypeError('expected a WebAuthn assertion with type "public-key"');
247
+ }
248
+ if (typeof credential.id !== "string" || credential.id === "") {
249
+ throw new TypeError("passkey assertion is missing id");
250
+ }
251
+ const r = credential.response;
252
+ if (!r) {
253
+ throw new TypeError("passkey assertion is missing response");
254
+ }
255
+ const response = {
256
+ clientDataJSON: b64urlField("clientDataJSON", r.clientDataJSON),
257
+ authenticatorData: b64urlField("authenticatorData", r.authenticatorData),
258
+ signature: b64urlField("signature", r.signature)
259
+ };
260
+ if (r.userHandle !== void 0 && r.userHandle !== null && r.userHandle !== "") {
261
+ response.userHandle = b64urlField("userHandle", r.userHandle);
262
+ }
263
+ const envelope = {
264
+ // The verifier requires `id` to be base64url; some mobile libraries hand
265
+ // out standard base64, so normalize it like the binary fields.
266
+ id: b64urlField("id", credential.id),
267
+ rawId: b64urlField("rawId", credential.rawId),
268
+ type: "public-key",
269
+ clientExtensionResults: {},
270
+ response
271
+ };
272
+ if (credential.authenticatorAttachment) {
273
+ envelope.authenticatorAttachment = credential.authenticatorAttachment;
274
+ }
275
+ return bytesToBase64url(utf8(JSON.stringify(envelope)));
276
+ }
277
+ var MAX_PACKED_ASSERTION_LENGTH = 64 * 1024;
278
+ function assertionChallengeMatches(packed, intent) {
279
+ if (typeof packed !== "string" || packed.length > MAX_PACKED_ASSERTION_LENGTH) {
280
+ return false;
281
+ }
282
+ try {
283
+ const envelope = JSON.parse(new TextDecoder().decode(base64ToBytes(packed)));
284
+ const clientDataB64 = envelope.response?.clientDataJSON;
285
+ if (typeof clientDataB64 !== "string") {
286
+ return false;
287
+ }
288
+ const clientData = JSON.parse(new TextDecoder().decode(base64ToBytes(clientDataB64)));
289
+ if (typeof clientData.challenge !== "string") {
290
+ return false;
291
+ }
292
+ const got = base64ToBytes(clientData.challenge);
293
+ const want = new Uint8Array(buildChallenge(intent));
294
+ return got.length === want.length && got.every((b, i) => b === want[i]);
295
+ } catch {
296
+ return false;
297
+ }
298
+ }
299
+ function webauthnSigner(getAssertion) {
300
+ return {
301
+ async sign(payload) {
302
+ const credential = await getAssertion(buildChallenge(payload));
303
+ return packAssertion(credential);
304
+ }
305
+ };
306
+ }
307
+
308
+ // src/governance/signer.ts
309
+ async function signGovernanceIntent(intent, signers) {
310
+ if (!Array.isArray(signers) || signers.length === 0) {
311
+ throw new TypeError("a governance change needs at least one signer");
312
+ }
313
+ const bytes = ArrayBuffer.isView(intent) ? toBytes(intent) : intent.bytes;
314
+ const out = [];
315
+ for (const s of signers) {
316
+ const sig = typeof s === "function" ? await s(bytes.slice()) : await s.sign(bytes.slice());
317
+ if (typeof sig !== "string" || sig === "") {
318
+ throw new Error("a governance signer returned an empty signature");
319
+ }
320
+ out.push(sig);
321
+ }
322
+ return out;
323
+ }
324
+ function webCryptoES256Signer(privateKey, subtle) {
325
+ return {
326
+ async sign(payload) {
327
+ const s = subtle ?? globalThis.crypto?.subtle;
328
+ if (!s) {
329
+ throw new Error(
330
+ "WebCrypto is not available: pass a SubtleCrypto or use ES256Signer on Node"
331
+ );
332
+ }
333
+ const raw = new Uint8Array(
334
+ await s.sign(
335
+ { name: "ECDSA", hash: "SHA-256" },
336
+ privateKey,
337
+ toArrayBuffer(payload)
338
+ )
339
+ );
340
+ return bytesToBase64(p1363ToDer(raw));
341
+ }
342
+ };
343
+ }
344
+ function toArrayBuffer(bytes) {
345
+ const out = new ArrayBuffer(bytes.length);
346
+ new Uint8Array(out).set(bytes);
347
+ return out;
348
+ }
349
+ function p1363ToDer(sig) {
350
+ if (sig.length !== 64) {
351
+ throw new Error(`expected a 64-byte P-256 signature, got ${sig.length} bytes`);
352
+ }
353
+ const int = (bytes) => {
354
+ let i = 0;
355
+ while (i < bytes.length - 1 && bytes[i] === 0) i++;
356
+ const trimmed = bytes.slice(i);
357
+ const body = trimmed[0] & 128 ? Uint8Array.of(0, ...trimmed) : trimmed;
358
+ return Uint8Array.of(2, body.length, ...body);
359
+ };
360
+ const r = int(sig.slice(0, 32));
361
+ const s = int(sig.slice(32));
362
+ return Uint8Array.of(48, r.length + s.length, ...r, ...s);
363
+ }
364
+
365
+ exports.addSignersToGroupIntent = addSignersToGroupIntent;
366
+ exports.assertIdempotencyKey = assertIdempotencyKey;
367
+ exports.assertionChallengeMatches = assertionChallengeMatches;
368
+ exports.buildChallenge = buildChallenge;
369
+ exports.canonicalJSON = canonicalJSON;
370
+ exports.createCryptoDestinationIntent = createCryptoDestinationIntent;
371
+ exports.newIdempotencyKey = newIdempotencyKey;
372
+ exports.packAssertion = packAssertion;
373
+ exports.removeSignersFromGroupIntent = removeSignersFromGroupIntent;
374
+ exports.signGovernanceIntent = signGovernanceIntent;
375
+ exports.updateSignerGroupGovernanceIntent = updateSignerGroupGovernanceIntent;
376
+ exports.webCryptoES256Signer = webCryptoES256Signer;
377
+ exports.webauthnSigner = webauthnSigner;
378
+ //# sourceMappingURL=index.js.map
379
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/agentic/canonicalize.ts","../../src/governance/encoding.ts","../../src/governance/intents.ts","../../src/governance/webauthn.ts","../../src/governance/signer.ts"],"names":[],"mappings":";;;AAsBO,SAAS,cAAc,KAAA,EAAwB;AACpD,EAAA,OAAO,aAAa,KAAK,CAAA;AAC3B;AAEA,SAAS,aAAa,KAAA,EAAwB;AAC5C,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW;AACzC,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,IAAI,OAAO,UAAU,SAAA,EAAW;AAC9B,IAAA,OAAO,QAAQ,MAAA,GAAS,OAAA;AAAA,EAC1B;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,EAAG;AAC3B,MAAA,MAAM,IAAI,SAAA,CAAU,CAAA,kCAAA,EAAqC,KAAK,CAAA,CAAE,CAAA;AAAA,IAClE;AAGA,IAAA,OAAO,IAAA,CAAK,UAAU,KAAK,CAAA;AAAA,EAC7B;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAG7B,IAAA,OAAO,IAAA,CAAK,UAAU,KAAK,CAAA;AAAA,EAC7B;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAG7B,IAAA,MAAM,IAAI,UAAU,iDAAiD,CAAA;AAAA,EACvE;AACA,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxB,IAAA,MAAM,QAAQ,KAAA,CAAM,GAAA,CAAI,C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,CAAA;AACxC,EAAA,IAAI,UAAA,CAAW,GAAG,CAAA,CAAE,GAAA,CAAI,KAAK,CAAA;AAC7B,EAAA,OAAO,GAAA;AACT;AAGA,SAAS,WAAW,GAAA,EAA6B;AAC/C,EAAA,IAAI,GAAA,CAAI,WAAW,EAAA,EAAI;AACrB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,wCAAA,EAA2C,GAAA,CAAI,MAAM,CAAA,MAAA,CAAQ,CAAA;AAAA,EAC/E;AACA,EAAA,MAAM,GAAA,GAAM,CAAC,KAAA,KAAkC;AAC7C,IAAA,IAAI,CAAA,GAAI,CAAA;AACR,IAAA,OAAO,IAAI,KAAA,CAAM,MAAA,GAAS,KAAK,KAAA,CAAM,CAAC,MAAM,CAAA,EAAG,CAAA,EAAA;AAC/C,IAAA,MAAM,OAAA,GAAU,KAAA,CAAM,KAAA,CAAM,CAAC,CAAA;AAE7B,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,CAAC,CAAA,GAAK,GAAA,GAAO,WAAW,EAAA,CAAG,CAAA,EAAG,GAAG,OAAO,CAAA,GAAI,OAAA;AACjE,IAAA,OAAO,WAAW,EAAA,CAAG,CAAA,EAAM,IAAA,CAAK,MAAA,EAAQ,GAAG,IAAI,CAAA;AAAA,EACjD,CAAA;AACA,EAAA,MAAM,IAAI,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA;AAC9B,EAAA,MAAM,CAAA,GAAI,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,EAAE,CAAC,CAAA;AAC3B,EAAA,OAAO,UAAA,CAAW,EAAA,CAAG,EAAA,EAAM,CAAA,CAAE,MAAA,GAAS,EAAE,MAAA,EAAQ,GAAG,CAAA,EAAG,GAAG,CAAC,CAAA;AAC5D","file":"index.js","sourcesContent":["/**\n * RFC 8785 (JCS) canonical JSON — the exact bytes the platform signs.\n *\n * A payload canonicalized here matches the platform's `enc.C14nJSON`\n * (json.Marshal + jsoncanonicalizer.Transform) byte-for-byte, so a\n * signature produced from the result verifies server-side.\n *\n * This implementation covers the value shapes the SDK ever puts into a\n * signed payload: nulls, booleans, finite integers/floats, strings,\n * arrays, and plain object maps. It intentionally does NOT handle\n * non-integer numbers with fractional parts differently from\n * JSON.stringify, because every mandate/endorsement payload the SDK\n * produces uses only integers, strings, arrays, and object maps — decimal\n * amounts are always sent as strings.\n */\n\n/**\n * RFC 8785 (JCS) canonicalize `value` and return its bytes as a UTF-8 string.\n *\n * @throws if `value` contains a non-finite number, a Symbol, a bigint, or a\n * circular reference — any of which cannot be encoded to canonical JSON.\n */\nexport function canonicalJSON(value: unknown): string {\n return canonicalize(value);\n}\n\nfunction canonicalize(value: unknown): string {\n if (value === null || value === undefined) {\n return 'null';\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError(`canonical JSON: non-finite number ${value}`);\n }\n // JSON.stringify already emits ES6 Number.prototype.toString() for\n // finite numbers, which is exactly what RFC 8785 § 3.2.2.3 mandates.\n return JSON.stringify(value);\n }\n if (typeof value === 'string') {\n // JSON.stringify handles JSON escape sequences per RFC 8259, matching\n // JCS's string-escape rules (§ 3.2.2.2).\n return JSON.stringify(value);\n }\n if (typeof value === 'bigint') {\n // BigInts have no unambiguous number representation for JSON;\n // fail loudly rather than produce bytes that won't verify.\n throw new TypeError('canonical JSON: bigint values are not supported');\n }\n if (Array.isArray(value)) {\n const parts = value.map((item) => canonicalize(item));\n return `[${parts.join(',')}]`;\n }\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // JCS sorts object member keys by their UTF-16 code-unit order,\n // which is exactly what a JavaScript `Array.prototype.sort()` on\n // strings produces (§ 3.2.3).\n const keys = Object.keys(obj).sort();\n const parts = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(obj[key])}`);\n return `{${parts.join(',')}}`;\n }\n throw new TypeError(`canonical JSON: unsupported value type ${typeof value}`);\n}\n","/**\n * Byte helpers that work the same in browsers, React Native and Node, with\n * no `Buffer` and no `node:` import, so the governance entry point stays\n * bundle-safe.\n */\n\nconst B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/** Standard base64 (RFC 4648 §4), padded. */\nexport function bytesToBase64(bytes: Uint8Array): string {\n let out = '';\n let i = 0;\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!;\n out +=\n B64_ALPHABET[(n >> 18) & 63]! +\n B64_ALPHABET[(n >> 12) & 63]! +\n B64_ALPHABET[(n >> 6) & 63]! +\n B64_ALPHABET[n & 63]!;\n }\n const rest = bytes.length - i;\n if (rest === 1) {\n const n = bytes[i]! << 16;\n out += B64_ALPHABET[(n >> 18) & 63]! + B64_ALPHABET[(n >> 12) & 63]! + '==';\n } else if (rest === 2) {\n const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8);\n out +=\n B64_ALPHABET[(n >> 18) & 63]! +\n B64_ALPHABET[(n >> 12) & 63]! +\n B64_ALPHABET[(n >> 6) & 63]! +\n '=';\n }\n return out;\n}\n\n/** base64url (RFC 4648 §5), unpadded — the encoding WebAuthn uses. */\nexport function bytesToBase64url(bytes: Uint8Array): string {\n return stripPadding(bytesToBase64(bytes).replace(/\\+/g, '-').replace(/\\//g, '_'));\n}\n\n// Trailing '=' removal without a regex: an unanchored /=+$/ backtracks\n// quadratically on a long run of '=' that is not at the end.\nfunction stripPadding(s: string): string {\n let end = s.length;\n while (end > 0 && s.charCodeAt(end - 1) === 61 /* '=' */) end--;\n return s.slice(0, end);\n}\n\n/**\n * Decode base64 in either alphabet, padded or not.\n *\n * @throws on characters outside both alphabets or an impossible length.\n */\nexport function base64ToBytes(input: string): Uint8Array {\n const s = stripPadding(input.replace(/-/g, '+').replace(/_/g, '/'));\n if (!/^[A-Za-z0-9+/]*$/.test(s) || s.length % 4 === 1) {\n throw new TypeError('invalid base64 or base64url string');\n }\n const out = new Uint8Array(Math.floor((s.length * 3) / 4));\n let o = 0;\n for (let i = 0; i < s.length; i += 4) {\n const a = B64_ALPHABET.indexOf(s[i]!);\n const b = B64_ALPHABET.indexOf(s[i + 1]!);\n const c = i + 2 < s.length ? B64_ALPHABET.indexOf(s[i + 2]!) : 0;\n const d = i + 3 < s.length ? B64_ALPHABET.indexOf(s[i + 3]!) : 0;\n const n = (a << 18) | (b << 12) | (c << 6) | d;\n out[o++] = (n >> 16) & 255;\n if (i + 2 < s.length) out[o++] = (n >> 8) & 255;\n if (i + 3 < s.length) out[o++] = n & 255;\n }\n return out;\n}\n\n/** UTF-8 bytes of a string. */\nexport function utf8(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n/** A copy of any BufferSource as a plain Uint8Array. */\nexport function toBytes(source: ArrayBuffer | ArrayBufferView): Uint8Array {\n // isView / toString instead of instanceof: buffers from another realm\n // (an iframe, jsdom, some React Native bridges) fail `instanceof`.\n if (ArrayBuffer.isView(source)) {\n return new Uint8Array(source.buffer, source.byteOffset, source.byteLength).slice();\n }\n if (Object.prototype.toString.call(source) === '[object ArrayBuffer]') {\n return new Uint8Array((source as ArrayBuffer).slice(0));\n }\n throw new TypeError('expected an ArrayBuffer or a typed array');\n}\n","/**\n * Canonical intents for signer-group governance changes.\n *\n * A change to a governed signer group (adding or removing members, changing\n * who governs it) needs signatures from the group's governing members. Each\n * signature covers the RFC 8785 (JCS) canonical JSON of an \"intent\" that the\n * policy engine rebuilds from the request and checks byte-for-byte. A wrong\n * key, a missing `signer_group_version`, or an idempotency key that differs\n * from the `X-Idempotency-Key` header gives a signature that never verifies,\n * so build the intent here rather than by hand.\n *\n * The builders are pure (no I/O, no `node:` import), so they run in a\n * browser or mobile app as well as on a server. The byte equality with the\n * policy engine is pinned by golden vectors in the test suite.\n */\n\nimport { canonicalJSON } from '../agentic/canonicalize.js';\nimport { utf8 } from './encoding.js';\n\n/** `add_signers_to_group`: endorses adding members to a signer group. */\nexport interface AddSignersToGroupIntent {\n readonly type: 'add_signers_to_group';\n readonly signer_group_id: string;\n readonly new_member_keys: readonly string[];\n readonly signer_group_version: number;\n readonly idempotency_key: string;\n}\n\n/**\n * `remove_signers_from_group`: endorses removing members. Note the group id\n * key is `group_id` here, not `signer_group_id`.\n */\nexport interface RemoveSignersFromGroupIntent {\n readonly type: 'remove_signers_from_group';\n readonly group_id: string;\n readonly members_to_remove: readonly string[];\n readonly signer_group_version: number;\n readonly idempotency_key: string;\n}\n\n/**\n * `update_signer_group_governance`: endorses replacing a group's governance\n * settings. An optional setting is ABSENT when not set (never null), and an\n * absent setting is cleared by the change.\n */\nexport interface UpdateSignerGroupGovernanceIntent {\n readonly type: 'update_signer_group_governance';\n readonly signer_group_id: string;\n readonly signer_group_version: number;\n readonly idempotency_key: string;\n readonly governance_threshold?: number;\n readonly governance_signer_group_id?: string;\n}\n\n/** `create_crypto_destination`: endorses creating a crypto destination. */\nexport interface CreateCryptoDestinationIntent {\n readonly type: 'create_crypto_destination';\n readonly recipient_id: string;\n readonly network_id: string;\n readonly address: string;\n readonly signer_group_id: string;\n readonly idempotency_key: string;\n}\n\n/** Any intent this module builds. */\nexport type GovernanceIntent =\n | AddSignersToGroupIntent\n | RemoveSignersFromGroupIntent\n | UpdateSignerGroupGovernanceIntent\n | CreateCryptoDestinationIntent;\n\n/**\n * An intent together with the exact bytes its signatures cover.\n *\n * - `canonical` is the canonical JSON as a string (handy to store or log).\n * - `bytes` is its UTF-8 encoding: what an ES256 signer signs, and what a\n * WebAuthn `navigator.credentials.get()` call takes as its `challenge`.\n */\nexport interface CanonicalIntent<T extends GovernanceIntent = GovernanceIntent> {\n readonly intent: T;\n readonly canonical: string;\n readonly bytes: Uint8Array;\n}\n\nconst LOWERCASE_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\n/**\n * Check that `key` is a lowercase UUID, the only idempotency key the platform\n * accepts on these endpoints. The same key goes into the intent and the\n * `X-Idempotency-Key` header, so an uppercase key would be refused even\n * though its signature is otherwise valid.\n *\n * @throws TypeError when it is not.\n */\nexport function assertIdempotencyKey(key: string): void {\n if (typeof key !== 'string' || !LOWERCASE_UUID.test(key)) {\n throw new TypeError(\n `idempotency key must be a lowercase UUID (got ${JSON.stringify(key)}); the platform refuses any other form`\n );\n }\n}\n\n/**\n * A fresh lowercase v4 UUID for a governance change, from the platform's\n * cryptographic random source (`crypto.randomUUID`, else\n * `crypto.getRandomValues`).\n */\nexport function newIdempotencyKey(): string {\n const c = (\n globalThis as {\n crypto?: { randomUUID?: () => string; getRandomValues?: (a: Uint8Array) => Uint8Array };\n }\n ).crypto;\n if (c && typeof c.randomUUID === 'function') {\n return c.randomUUID().toLowerCase();\n }\n if (!c || typeof c.getRandomValues !== 'function') {\n throw new Error('no cryptographic random source: pass an idempotency key explicitly');\n }\n const b = c.getRandomValues(new Uint8Array(16));\n b[6] = (b[6]! & 0x0f) | 0x40;\n b[8] = (b[8]! & 0x3f) | 0x80;\n const hex = Array.from(b, (x: number) => x.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction nonEmpty(name: string, value: string): string {\n if (typeof value !== 'string' || value === '') {\n throw new TypeError(`${name} is required`);\n }\n return value;\n}\n\nfunction keyList(name: string, keys: readonly string[]): string[] {\n if (!Array.isArray(keys) || keys.length === 0) {\n throw new TypeError(`${name} must list at least one public key`);\n }\n return keys.map((k, i) => {\n const key = nonEmpty(`${name}[${i}]`, k);\n // The platform trims an added member key before it rebuilds the intent it\n // verifies, so a key signed with surrounding whitespace can never verify.\n // Refuse it rather than guess which form the caller meant to sign.\n if (key.trim() !== key) {\n throw new TypeError(`${name}[${i}] has leading or trailing whitespace; trim it first`);\n }\n return key;\n });\n}\n\nfunction version(v: number): number {\n if (!Number.isSafeInteger(v) || v < 0) {\n throw new TypeError(\n `signer_group_version must be a non-negative integer (got ${String(v)}); read it from the group's \\`version\\``\n );\n }\n return v;\n}\n\nfunction finish<T extends GovernanceIntent>(intent: T): CanonicalIntent<T> {\n const canonical = canonicalJSON(intent);\n return { intent, canonical, bytes: utf8(canonical) };\n}\n\n/**\n * Intent for adding members to a signer group\n * (`POST /signer-groups/{id}/signers`). That endpoint adds one `member_key`\n * per request, so pass `[memberKey]`.\n *\n * @param params.signerGroupVersion - the group's current `version` (0 is valid\n * and is signed as 0)\n * @param params.idempotencyKey - a lowercase UUID; send the SAME value as the\n * request's `X-Idempotency-Key`\n */\nexport function addSignersToGroupIntent(params: {\n signerGroupId: string;\n newMemberKeys: readonly string[];\n signerGroupVersion: number;\n idempotencyKey: string;\n}): CanonicalIntent<AddSignersToGroupIntent> {\n assertIdempotencyKey(params.idempotencyKey);\n return finish({\n type: 'add_signers_to_group',\n signer_group_id: nonEmpty('signerGroupId', params.signerGroupId),\n new_member_keys: keyList('newMemberKeys', params.newMemberKeys),\n signer_group_version: version(params.signerGroupVersion),\n idempotency_key: params.idempotencyKey,\n });\n}\n\n/**\n * Intent for removing members from a signer group\n * (`POST /signer-groups/{id}/signer-removals`). `membersToRemove` is signed\n * in the order given, which must be the order sent.\n */\nexport function removeSignersFromGroupIntent(params: {\n signerGroupId: string;\n membersToRemove: readonly string[];\n signerGroupVersion: number;\n idempotencyKey: string;\n}): CanonicalIntent<RemoveSignersFromGroupIntent> {\n assertIdempotencyKey(params.idempotencyKey);\n return finish({\n type: 'remove_signers_from_group',\n group_id: nonEmpty('signerGroupId', params.signerGroupId),\n members_to_remove: keyList('membersToRemove', params.membersToRemove),\n signer_group_version: version(params.signerGroupVersion),\n idempotency_key: params.idempotencyKey,\n });\n}\n\n/**\n * Intent for replacing a signer group's governance settings\n * (`PATCH /signer-groups/{id}/governance`).\n *\n * The change replaces the WHOLE governance state: leave a setting out (or\n * pass null) to clear it, which the intent expresses by omitting the key.\n * No `governanceThreshold` means the default quorum; no\n * `governanceSignerGroupId` means the group governs itself.\n */\nexport function updateSignerGroupGovernanceIntent(params: {\n signerGroupId: string;\n signerGroupVersion: number;\n idempotencyKey: string;\n governanceThreshold?: number | null;\n governanceSignerGroupId?: string | null;\n}): CanonicalIntent<UpdateSignerGroupGovernanceIntent> {\n assertIdempotencyKey(params.idempotencyKey);\n const intent: {\n -readonly [K in keyof UpdateSignerGroupGovernanceIntent]: UpdateSignerGroupGovernanceIntent[K];\n } = {\n type: 'update_signer_group_governance',\n signer_group_id: nonEmpty('signerGroupId', params.signerGroupId),\n signer_group_version: version(params.signerGroupVersion),\n idempotency_key: params.idempotencyKey,\n };\n if (params.governanceThreshold !== undefined && params.governanceThreshold !== null) {\n // The platform stores it as an int32.\n const t = params.governanceThreshold;\n if (!Number.isSafeInteger(t) || t < 1 || t > 2147483647) {\n throw new TypeError(\n 'governanceThreshold must be an integer from 1 to 2^31-1, or null to clear it'\n );\n }\n intent.governance_threshold = params.governanceThreshold;\n }\n if (params.governanceSignerGroupId !== undefined && params.governanceSignerGroupId !== null) {\n intent.governance_signer_group_id = nonEmpty(\n 'governanceSignerGroupId',\n params.governanceSignerGroupId\n );\n }\n return finish(intent);\n}\n\n/**\n * Intent for creating a crypto destination endorsed by a signer group's\n * governance (`POST /recipients/{recipient_id}/destinations` with\n * `destination_type: 'crypto'`, `signatures` and `signer_group_id`). Send\n * `crypto_address` = `address` and the same `network_id`.\n */\nexport function createCryptoDestinationIntent(params: {\n recipientId: string;\n networkId: string;\n address: string;\n signerGroupId: string;\n idempotencyKey: string;\n}): CanonicalIntent<CreateCryptoDestinationIntent> {\n assertIdempotencyKey(params.idempotencyKey);\n return finish({\n type: 'create_crypto_destination',\n recipient_id: nonEmpty('recipientId', params.recipientId),\n network_id: nonEmpty('networkId', params.networkId),\n address: nonEmpty('address', params.address),\n signer_group_id: nonEmpty('signerGroupId', params.signerGroupId),\n idempotency_key: params.idempotencyKey,\n });\n}\n","/**\n * Passkey (WebAuthn) signatures for governance intents.\n *\n * The platform verifies a passkey signature like this: the assertion's\n * `clientDataJSON.challenge` must decode to the intent's canonical JSON\n * itself (NOT a hash of it), and the authenticator's signature over\n * `authenticatorData || SHA-256(clientDataJSON)` must verify against the\n * signer's registered COSE key. The `signatures[]` entry is base64url of the\n * `CredentialAssertionResponse` JSON.\n *\n * So the SDK does two small things and never touches the credential:\n * - {@link buildChallenge} gives you the bytes to pass as\n * `navigator.credentials.get({ publicKey: { challenge } })`.\n * - {@link packAssertion} turns the returned credential into the\n * `signatures[]` entry.\n */\n\nimport { base64ToBytes, bytesToBase64url, toBytes, utf8 } from './encoding.js';\nimport type { CanonicalIntent } from './intents.js';\nimport type { GovernanceSigner } from './signer.js';\n\n/**\n * Binary data as WebAuthn APIs hand it out: an ArrayBuffer or typed array\n * (browsers), or a base64 / base64url string (most React Native passkey\n * libraries, and `PublicKeyCredential.toJSON()`).\n */\nexport type BinaryOrBase64 = ArrayBuffer | ArrayBufferView | string;\n\n/**\n * The parts of a `PublicKeyCredential` (with an `AuthenticatorAssertionResponse`)\n * that the platform reads. A browser's `navigator.credentials.get()` result\n * satisfies it as-is: the DOM types its `response` as the base\n * `AuthenticatorResponse`, so `authenticatorData` and `signature` are\n * optional here and checked at run time by {@link packAssertion}.\n */\nexport interface AssertionCredential {\n readonly id: string;\n readonly rawId: BinaryOrBase64;\n readonly type: string;\n readonly authenticatorAttachment?: string | null;\n readonly response: {\n readonly clientDataJSON: BinaryOrBase64;\n readonly authenticatorData?: BinaryOrBase64;\n readonly signature?: BinaryOrBase64;\n readonly userHandle?: BinaryOrBase64 | null;\n };\n}\n\n/**\n * What a challenge can be built from: a built intent, anything else that\n * carries the `canonical` string (such as a `PreparedSignerGroupChange`),\n * the `canonical` string itself (what a server would send to the browser),\n * or its bytes.\n */\nexport type ChallengeSource =\n | CanonicalIntent\n | { readonly canonical: string }\n | string\n | Uint8Array\n | ArrayBuffer;\n\n/**\n * The WebAuthn challenge for an intent: its raw canonical JSON bytes, as a\n * fresh `ArrayBuffer`. Pass it as `publicKey.challenge`; the browser\n * base64url-encodes it into `clientDataJSON`, which is exactly what the\n * platform expects. (An `ArrayBuffer` is a `BufferSource` under every\n * TypeScript version, unlike a `Uint8Array` on TypeScript 5.7+.)\n *\n * @throws TypeError when `intent` is none of the {@link ChallengeSource} forms\n */\nexport function buildChallenge(intent: ChallengeSource): ArrayBuffer {\n const bytes = challengeBytes(intent);\n const out = new ArrayBuffer(bytes.length);\n new Uint8Array(out).set(bytes);\n return out;\n}\n\nfunction challengeBytes(intent: ChallengeSource): Uint8Array {\n if (typeof intent === 'string') {\n return utf8(intent);\n }\n if (isBinary(intent)) {\n return toBytes(intent);\n }\n if (intent && typeof intent === 'object') {\n // `canonical` first: it is the one field every source carries, and a\n // built intent's `bytes` are its UTF-8 encoding anyway.\n const canonical = (intent as { canonical?: unknown }).canonical;\n if (typeof canonical === 'string') {\n return utf8(canonical);\n }\n }\n throw new TypeError(\n 'expected a built intent, a prepared change, its canonical string, or its bytes'\n );\n}\n\nfunction isBinary(v: unknown): v is ArrayBuffer | ArrayBufferView {\n return ArrayBuffer.isView(v) || Object.prototype.toString.call(v) === '[object ArrayBuffer]';\n}\n\nfunction b64urlField(name: string, value: BinaryOrBase64 | null | undefined): string {\n if (value === undefined || value === null || value === '') {\n throw new TypeError(`passkey assertion is missing ${name}`);\n }\n if (typeof value === 'string') {\n // Normalize either base64 alphabet to unpadded base64url.\n return bytesToBase64url(base64ToBytes(value));\n }\n return bytesToBase64url(toBytes(value));\n}\n\n/**\n * Package a passkey assertion as a `signatures[]` entry: base64url of the\n * `CredentialAssertionResponse` JSON\n * (`{id, rawId, type, authenticatorAttachment?, clientExtensionResults, response: {clientDataJSON, authenticatorData, signature, userHandle?}}`,\n * every binary field base64url).\n *\n * @param credential - what `navigator.credentials.get()` returned (or a\n * mobile passkey library's equivalent)\n * @throws TypeError when it is not a public-key assertion or a field is\n * missing\n */\nexport function packAssertion(credential: AssertionCredential): string {\n if (!credential || credential.type !== 'public-key') {\n throw new TypeError('expected a WebAuthn assertion with type \"public-key\"');\n }\n if (typeof credential.id !== 'string' || credential.id === '') {\n throw new TypeError('passkey assertion is missing id');\n }\n const r = credential.response;\n if (!r) {\n throw new TypeError('passkey assertion is missing response');\n }\n const response: Record<string, string> = {\n clientDataJSON: b64urlField('clientDataJSON', r.clientDataJSON),\n authenticatorData: b64urlField('authenticatorData', r.authenticatorData),\n signature: b64urlField('signature', r.signature),\n };\n if (r.userHandle !== undefined && r.userHandle !== null && r.userHandle !== '') {\n response.userHandle = b64urlField('userHandle', r.userHandle);\n }\n const envelope: Record<string, unknown> = {\n // The verifier requires `id` to be base64url; some mobile libraries hand\n // out standard base64, so normalize it like the binary fields.\n id: b64urlField('id', credential.id),\n rawId: b64urlField('rawId', credential.rawId),\n type: 'public-key',\n clientExtensionResults: {},\n response,\n };\n if (credential.authenticatorAttachment) {\n envelope.authenticatorAttachment = credential.authenticatorAttachment;\n }\n return bytesToBase64url(utf8(JSON.stringify(envelope)));\n}\n\n/** Longest packed assertion {@link assertionChallengeMatches} will decode. */\nconst MAX_PACKED_ASSERTION_LENGTH = 64 * 1024;\n\n/**\n * Whether a packed passkey signature was made over `intent` — its challenge\n * equals the intent's canonical bytes. A cheap server-side check of what a\n * browser sent back before you submit it. It does NOT verify the signature\n * itself; the platform does that. Returns false for anything that is not a\n * packed assertion, including one longer than 64 KiB.\n */\nexport function assertionChallengeMatches(packed: string, intent: ChallengeSource): boolean {\n // `packed` usually comes from a browser, so bound the work it can cause\n // before decoding it. A real assertion is a few kilobytes.\n if (typeof packed !== 'string' || packed.length > MAX_PACKED_ASSERTION_LENGTH) {\n return false;\n }\n try {\n const envelope = JSON.parse(new TextDecoder().decode(base64ToBytes(packed))) as {\n response?: { clientDataJSON?: string };\n };\n const clientDataB64 = envelope.response?.clientDataJSON;\n if (typeof clientDataB64 !== 'string') {\n return false;\n }\n const clientData = JSON.parse(new TextDecoder().decode(base64ToBytes(clientDataB64))) as {\n challenge?: string;\n };\n if (typeof clientData.challenge !== 'string') {\n return false;\n }\n const got = base64ToBytes(clientData.challenge);\n const want = new Uint8Array(buildChallenge(intent));\n return got.length === want.length && got.every((b, i) => b === want[i]);\n } catch {\n return false;\n }\n}\n\n/**\n * A {@link GovernanceSigner} backed by a passkey. `getAssertion` receives\n * the challenge and returns the credential; in a browser:\n *\n * ```typescript\n * const signer = webauthnSigner((challenge) =>\n * navigator.credentials.get({\n * publicKey: { challenge, rpId: 'app.example.com', userVerification: 'required' },\n * }) as Promise<PublicKeyCredential>\n * );\n * ```\n *\n * Every call prompts the user, so do not use it with automatic stale-version\n * retries unless a second prompt is acceptable.\n */\nexport function webauthnSigner(\n getAssertion: (challenge: ArrayBuffer) => Promise<AssertionCredential> | AssertionCredential\n): GovernanceSigner {\n return {\n async sign(payload: Uint8Array): Promise<string> {\n const credential = await getAssertion(buildChallenge(payload));\n return packAssertion(credential);\n },\n };\n}\n","/**\n * Pluggable signers for governance intents.\n *\n * A signer turns the intent's canonical bytes into one `signatures[]` entry.\n * The SDK ships three:\n * - ES256 on a server: `ES256Signer` (also exported as `P256MandateSigner`) in the\n * main entry, or your own HSM/KMS behind this interface.\n * - ES256 in a browser: {@link webCryptoES256Signer} over a WebCrypto key.\n * - Passkey: `webauthnSigner` from this entry point.\n */\n\nimport { bytesToBase64, toBytes } from './encoding.js';\nimport type { CanonicalIntent } from './intents.js';\n\n/**\n * Produces one `signatures[]` entry over a governance intent's canonical\n * bytes. For ES256 that is base64 of the ASN.1 DER ECDSA signature over\n * SHA-256(payload); for a passkey it is the packed assertion.\n */\nexport interface GovernanceSigner {\n sign(payload: Uint8Array): Promise<string> | string;\n}\n\n/** A {@link GovernanceSigner} or a bare signing function. */\nexport type GovernanceSignerLike =\n | GovernanceSigner\n | ((payload: Uint8Array) => Promise<string> | string);\n\n/**\n * Sign an intent with each signer, one after another (passkey prompts must\n * not overlap), and return the signatures in signer order.\n *\n * @throws when `signers` is empty or a signer returns an empty signature\n */\nexport async function signGovernanceIntent(\n intent: CanonicalIntent | Uint8Array,\n signers: readonly GovernanceSignerLike[]\n): Promise<string[]> {\n if (!Array.isArray(signers) || signers.length === 0) {\n throw new TypeError('a governance change needs at least one signer');\n }\n const bytes = ArrayBuffer.isView(intent) ? toBytes(intent) : intent.bytes;\n const out: string[] = [];\n for (const s of signers) {\n // Each signer gets its own copy, so one cannot alter what the next signs.\n const sig = typeof s === 'function' ? await s(bytes.slice()) : await s.sign(bytes.slice());\n if (typeof sig !== 'string' || sig === '') {\n throw new Error('a governance signer returned an empty signature');\n }\n out.push(sig);\n }\n return out;\n}\n\n/**\n * The part of WebCrypto's `SubtleCrypto` the ES256 signer uses. Declared\n * structurally so the SDK does not need the DOM type library; a real\n * `crypto.subtle` (browser, Deno, Node's `webcrypto.subtle`) satisfies it.\n */\nexport interface SubtleCryptoLike {\n sign(\n algorithm: { name: 'ECDSA'; hash: 'SHA-256' },\n key: never,\n data: ArrayBuffer\n ): Promise<ArrayBuffer>;\n}\n\n/**\n * An ES256 {@link GovernanceSigner} over a WebCrypto P-256 private key, for\n * browsers and other runtimes without `node:crypto`. The key can be\n * non-extractable. WebCrypto returns raw `r || s`; this converts it to the\n * ASN.1 DER form the platform verifies.\n *\n * @param privateKey - an ECDSA P-256 `CryptoKey` with the `sign` usage\n * (typed loosely so the SDK does not require the DOM type library)\n * @param subtle - the SubtleCrypto to use (defaults to `globalThis.crypto.subtle`)\n */\nexport function webCryptoES256Signer(\n privateKey: object,\n subtle?: SubtleCryptoLike\n): GovernanceSigner {\n return {\n async sign(payload: Uint8Array): Promise<string> {\n const s = subtle ?? (globalThis as { crypto?: { subtle?: SubtleCryptoLike } }).crypto?.subtle;\n if (!s) {\n throw new Error(\n 'WebCrypto is not available: pass a SubtleCrypto or use ES256Signer on Node'\n );\n }\n const raw = new Uint8Array(\n await s.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n privateKey as never,\n toArrayBuffer(payload)\n )\n );\n return bytesToBase64(p1363ToDer(raw));\n },\n };\n}\n\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const out = new ArrayBuffer(bytes.length);\n new Uint8Array(out).set(bytes);\n return out;\n}\n\n/** IEEE P1363 `r || s` (64 bytes for P-256) to an ASN.1 DER ECDSA signature. */\nfunction p1363ToDer(sig: Uint8Array): Uint8Array {\n if (sig.length !== 64) {\n throw new Error(`expected a 64-byte P-256 signature, got ${sig.length} bytes`);\n }\n const int = (bytes: Uint8Array): Uint8Array => {\n let i = 0;\n while (i < bytes.length - 1 && bytes[i] === 0) i++;\n const trimmed = bytes.slice(i);\n // A leading 1 bit would make the INTEGER negative: prefix a zero byte.\n const body = trimmed[0]! & 0x80 ? Uint8Array.of(0, ...trimmed) : trimmed;\n return Uint8Array.of(0x02, body.length, ...body);\n };\n const r = int(sig.slice(0, 32));\n const s = int(sig.slice(32));\n return Uint8Array.of(0x30, r.length + s.length, ...r, ...s);\n}\n"]}