@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/README.md CHANGED
@@ -241,6 +241,88 @@ const portfolio = await client.insights.getClientReport({ severity: 'critical,wa
241
241
 
242
242
  The full agentic surface is reachable via `client.paymentAgents`, `client.mandates`, `client.instructions`, `client.scheduledPayments`, and `client.insights`.
243
243
 
244
+ ## Signer-group governance (ES256 and passkeys)
245
+
246
+ When a client has governance enforcement on, or a signer group has
247
+ governance settings, adding or removing members and changing who governs the
248
+ group need signatures from the group's governing members. Each signature
249
+ covers a canonical "intent" that includes the group's current `version` and
250
+ the request's idempotency key, so the SDK builds it for you.
251
+
252
+ **On a server, with ES256 keys:**
253
+
254
+ ```typescript
255
+ import { ES256Signer, StaleSignerGroupVersionError } from '@dakota-xyz/ts-sdk';
256
+
257
+ const admin = ES256Signer.fromPrivateKey(process.env.ADMIN_KEY_PEM!); // or your KMS behind GovernanceSigner
258
+ const group = await client.signerGroups.addSignerSigned(groupId, newMemberPublicKey, [admin]);
259
+ await client.signerGroups.removeSignersSigned(groupId, [oldMemberPublicKey], [admin]);
260
+ await client.signerGroups.updateGovernanceSigned(groupId, { governance_threshold: 2 }, [admin]);
261
+ ```
262
+
263
+ Pass as many signers as the group's `effective_governance_threshold` needs.
264
+ The helper reads the group's `version`, generates a lowercase UUID idempotency
265
+ key, signs, and sends the same key as `X-Idempotency-Key`. Pass
266
+ `{ staleRetries: n }` (0 to 5) to the add and remove helpers to re-read and
267
+ re-sign after a concurrent change; each retry asks every signer again. The
268
+ governance update refuses it, since re-signing a whole-state change after
269
+ someone else's would undo theirs.
270
+
271
+ **With passkeys, signed in the user's browser or app:** the API key stays on
272
+ your server, so the change is prepared there, signed in the browser, and sent
273
+ from the server.
274
+
275
+ ```typescript
276
+ // server: build the change and keep it (it is plain JSON)
277
+ const change = await client.signerGroups.prepareAddSigner(groupId, newMemberPublicKey);
278
+ session.pendingChange = change;
279
+ return { challenge: change.canonical };
280
+
281
+ // browser: the browser-safe entry point has no Node dependencies
282
+ import { buildChallenge, packAssertion } from '@dakota-xyz/ts-sdk/governance';
283
+ const credential = await navigator.credentials.get({
284
+ publicKey: { challenge: buildChallenge(challenge), rpId: 'app.example.com', userVerification: 'required' },
285
+ });
286
+ const signature = packAssertion(credential as PublicKeyCredential);
287
+
288
+ // server: check it, then send it
289
+ import { assertionChallengeMatches } from '@dakota-xyz/ts-sdk';
290
+ if (!assertionChallengeMatches(signature, session.pendingChange)) throw new Error('wrong change');
291
+ const group = await client.signerGroups.submitSignedChange(session.pendingChange, [signature]);
292
+ ```
293
+
294
+ The challenge is the canonical intent itself, not a hash of it. Passkey and
295
+ ES256 signatures can be combined toward one quorum. In a browser with a
296
+ WebCrypto key, use `webCryptoES256Signer(cryptoKey)`.
297
+
298
+ **When governance refuses**, the error says why (each is an `APIError`):
299
+
300
+ | Error | Meaning | What to do |
301
+ |---|---|---|
302
+ | `EndorsementRequiredError` (400) | The change was sent unsigned | Use the signed helpers |
303
+ | `InsufficientEndorsementsError` (403) | Too few governing signatures (`have`, `need`) | Prepare again (a new idempotency key) and collect every signature again |
304
+ | `StaleSignerGroupVersionError` (409) | The group changed after signing | Prepare and sign again (or pass `staleRetries`) |
305
+ | `BelowThresholdError` (422) | The removal would leave the group too small | Add members first, or remove fewer |
306
+ | `InvalidGoverningGroupError` (409) | The governing group is gone or invalid | Fix the group's governance |
307
+
308
+ The idempotency key is part of what is signed, and the platform remembers the
309
+ outcome per key. So a governance refusal (stale version, too few or bad
310
+ signatures) is final for that intent: prepare and sign again. Resending the
311
+ same key with more signatures is refused as a different request.
312
+
313
+ If a submit may fail without any response (a timeout or a dropped
314
+ connection), use the `prepare*` + `submitSignedChange` pair and keep the
315
+ prepared change and its signatures: after such a failure, resubmit exactly
316
+ those with `submitSignedChange`. The `*Signed` helpers do not return what
317
+ they signed, so there is nothing to resubmit, and calling one again prepares
318
+ a new intent (under a new key, unless you pass `idempotencyKey`).
319
+
320
+ To build intents yourself (for example a governed crypto destination), use
321
+ `addSignersToGroupIntent`, `removeSignersFromGroupIntent`,
322
+ `updateSignerGroupGovernanceIntent` and `createCryptoDestinationIntent`. See
323
+ `examples/governance-es256.ts` and `examples/governance-passkey.ts` for
324
+ complete runs against sandbox.
325
+
244
326
  ## Handling Webhooks
245
327
 
246
328
  Dakota sends webhooks for all status changes. Set up a handler:
@@ -728,11 +810,19 @@ Manage multi-party authorization.
728
810
  | `signerGroups.create(data)` | Create signer group |
729
811
  | `signerGroups.list(params?)` | List signer groups |
730
812
  | `signerGroups.get(id, params?)` | Get signer group by ID (`{ include_removed: true }` adds `removed_members`) |
731
- | `signerGroups.addSigner(groupId, data)` | Add signer to group |
732
- | `signerGroups.removeSigner(groupId, signerId)` | Remove signer (by KSUID `signer_id`, not public key) |
813
+ | `signerGroups.addSigner(groupId, data)` | Add signer to group (unsigned; a governed group refuses it) |
814
+ | `signerGroups.removeSigner(groupId, signerId)` | Remove signer (by KSUID `signer_id`, not public key; unsigned) |
815
+ | `signerGroups.addSignerSigned(groupId, memberKey, signers, opts?)` | Add a member with governance signatures, in one call |
816
+ | `signerGroups.removeSignersSigned(groupId, memberKeys, signers, opts?)` | Remove members with governance signatures, in one call |
817
+ | `signerGroups.updateGovernanceSigned(groupId, settings, signers, opts?)` | Replace the group's governance settings, signed |
818
+ | `signerGroups.prepareAddSigner` / `prepareRemoveSigners` / `prepareGovernanceUpdate` | Build a change to sign elsewhere (passkey in a browser) |
819
+ | `signerGroups.submitSignedChange(change, signatures)` | Send a prepared change with its signatures |
820
+ | `signerGroups.removeSigners(groupId, body)` / `updateGovernance(groupId, body)` | Low level: send a body you signed yourself |
733
821
  | `signerGroups.attachToWallet(walletId, groupId)` | Attach to wallet |
734
822
  | `signerGroups.detachFromWallet(walletId, groupId)` | Detach from wallet |
735
823
 
824
+ See [Signer-group governance](#signer-group-governance-es256-and-passkeys) for signing.
825
+
736
826
  ### Signers
737
827
 
738
828
  Manage individual signers.
@@ -749,8 +839,9 @@ Manage API key credentials.
749
839
 
750
840
  | Method | Description |
751
841
  |--------|-------------|
752
- | `apiKeys.create(data)` | Create API key (secret shown once) |
753
- | `apiKeys.list(params?)` | List API keys |
842
+ | `apiKeys.create(data)` | Create API key with an optional name and scope (key shown once) |
843
+ | `apiKeys.list(params?)` | List API keys, with name, scope and last-used time |
844
+ | `apiKeys.update(id, data)` | Change the name, the scope, or both |
754
845
  | `apiKeys.delete(id)` | Delete API key |
755
846
 
756
847
  ### Users
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Canonical intents for signer-group governance changes.
3
+ *
4
+ * A change to a governed signer group (adding or removing members, changing
5
+ * who governs it) needs signatures from the group's governing members. Each
6
+ * signature covers the RFC 8785 (JCS) canonical JSON of an "intent" that the
7
+ * policy engine rebuilds from the request and checks byte-for-byte. A wrong
8
+ * key, a missing `signer_group_version`, or an idempotency key that differs
9
+ * from the `X-Idempotency-Key` header gives a signature that never verifies,
10
+ * so build the intent here rather than by hand.
11
+ *
12
+ * The builders are pure (no I/O, no `node:` import), so they run in a
13
+ * browser or mobile app as well as on a server. The byte equality with the
14
+ * policy engine is pinned by golden vectors in the test suite.
15
+ */
16
+ /** `add_signers_to_group`: endorses adding members to a signer group. */
17
+ interface AddSignersToGroupIntent {
18
+ readonly type: 'add_signers_to_group';
19
+ readonly signer_group_id: string;
20
+ readonly new_member_keys: readonly string[];
21
+ readonly signer_group_version: number;
22
+ readonly idempotency_key: string;
23
+ }
24
+ /**
25
+ * `remove_signers_from_group`: endorses removing members. Note the group id
26
+ * key is `group_id` here, not `signer_group_id`.
27
+ */
28
+ interface RemoveSignersFromGroupIntent {
29
+ readonly type: 'remove_signers_from_group';
30
+ readonly group_id: string;
31
+ readonly members_to_remove: readonly string[];
32
+ readonly signer_group_version: number;
33
+ readonly idempotency_key: string;
34
+ }
35
+ /**
36
+ * `update_signer_group_governance`: endorses replacing a group's governance
37
+ * settings. An optional setting is ABSENT when not set (never null), and an
38
+ * absent setting is cleared by the change.
39
+ */
40
+ interface UpdateSignerGroupGovernanceIntent {
41
+ readonly type: 'update_signer_group_governance';
42
+ readonly signer_group_id: string;
43
+ readonly signer_group_version: number;
44
+ readonly idempotency_key: string;
45
+ readonly governance_threshold?: number;
46
+ readonly governance_signer_group_id?: string;
47
+ }
48
+ /** `create_crypto_destination`: endorses creating a crypto destination. */
49
+ interface CreateCryptoDestinationIntent {
50
+ readonly type: 'create_crypto_destination';
51
+ readonly recipient_id: string;
52
+ readonly network_id: string;
53
+ readonly address: string;
54
+ readonly signer_group_id: string;
55
+ readonly idempotency_key: string;
56
+ }
57
+ /** Any intent this module builds. */
58
+ type GovernanceIntent = AddSignersToGroupIntent | RemoveSignersFromGroupIntent | UpdateSignerGroupGovernanceIntent | CreateCryptoDestinationIntent;
59
+ /**
60
+ * An intent together with the exact bytes its signatures cover.
61
+ *
62
+ * - `canonical` is the canonical JSON as a string (handy to store or log).
63
+ * - `bytes` is its UTF-8 encoding: what an ES256 signer signs, and what a
64
+ * WebAuthn `navigator.credentials.get()` call takes as its `challenge`.
65
+ */
66
+ interface CanonicalIntent<T extends GovernanceIntent = GovernanceIntent> {
67
+ readonly intent: T;
68
+ readonly canonical: string;
69
+ readonly bytes: Uint8Array;
70
+ }
71
+ /**
72
+ * Check that `key` is a lowercase UUID, the only idempotency key the platform
73
+ * accepts on these endpoints. The same key goes into the intent and the
74
+ * `X-Idempotency-Key` header, so an uppercase key would be refused even
75
+ * though its signature is otherwise valid.
76
+ *
77
+ * @throws TypeError when it is not.
78
+ */
79
+ declare function assertIdempotencyKey(key: string): void;
80
+ /**
81
+ * A fresh lowercase v4 UUID for a governance change, from the platform's
82
+ * cryptographic random source (`crypto.randomUUID`, else
83
+ * `crypto.getRandomValues`).
84
+ */
85
+ declare function newIdempotencyKey(): string;
86
+ /**
87
+ * Intent for adding members to a signer group
88
+ * (`POST /signer-groups/{id}/signers`). That endpoint adds one `member_key`
89
+ * per request, so pass `[memberKey]`.
90
+ *
91
+ * @param params.signerGroupVersion - the group's current `version` (0 is valid
92
+ * and is signed as 0)
93
+ * @param params.idempotencyKey - a lowercase UUID; send the SAME value as the
94
+ * request's `X-Idempotency-Key`
95
+ */
96
+ declare function addSignersToGroupIntent(params: {
97
+ signerGroupId: string;
98
+ newMemberKeys: readonly string[];
99
+ signerGroupVersion: number;
100
+ idempotencyKey: string;
101
+ }): CanonicalIntent<AddSignersToGroupIntent>;
102
+ /**
103
+ * Intent for removing members from a signer group
104
+ * (`POST /signer-groups/{id}/signer-removals`). `membersToRemove` is signed
105
+ * in the order given, which must be the order sent.
106
+ */
107
+ declare function removeSignersFromGroupIntent(params: {
108
+ signerGroupId: string;
109
+ membersToRemove: readonly string[];
110
+ signerGroupVersion: number;
111
+ idempotencyKey: string;
112
+ }): CanonicalIntent<RemoveSignersFromGroupIntent>;
113
+ /**
114
+ * Intent for replacing a signer group's governance settings
115
+ * (`PATCH /signer-groups/{id}/governance`).
116
+ *
117
+ * The change replaces the WHOLE governance state: leave a setting out (or
118
+ * pass null) to clear it, which the intent expresses by omitting the key.
119
+ * No `governanceThreshold` means the default quorum; no
120
+ * `governanceSignerGroupId` means the group governs itself.
121
+ */
122
+ declare function updateSignerGroupGovernanceIntent(params: {
123
+ signerGroupId: string;
124
+ signerGroupVersion: number;
125
+ idempotencyKey: string;
126
+ governanceThreshold?: number | null;
127
+ governanceSignerGroupId?: string | null;
128
+ }): CanonicalIntent<UpdateSignerGroupGovernanceIntent>;
129
+ /**
130
+ * Intent for creating a crypto destination endorsed by a signer group's
131
+ * governance (`POST /recipients/{recipient_id}/destinations` with
132
+ * `destination_type: 'crypto'`, `signatures` and `signer_group_id`). Send
133
+ * `crypto_address` = `address` and the same `network_id`.
134
+ */
135
+ declare function createCryptoDestinationIntent(params: {
136
+ recipientId: string;
137
+ networkId: string;
138
+ address: string;
139
+ signerGroupId: string;
140
+ idempotencyKey: string;
141
+ }): CanonicalIntent<CreateCryptoDestinationIntent>;
142
+
143
+ /**
144
+ * Pluggable signers for governance intents.
145
+ *
146
+ * A signer turns the intent's canonical bytes into one `signatures[]` entry.
147
+ * The SDK ships three:
148
+ * - ES256 on a server: `ES256Signer` (also exported as `P256MandateSigner`) in the
149
+ * main entry, or your own HSM/KMS behind this interface.
150
+ * - ES256 in a browser: {@link webCryptoES256Signer} over a WebCrypto key.
151
+ * - Passkey: `webauthnSigner` from this entry point.
152
+ */
153
+
154
+ /**
155
+ * Produces one `signatures[]` entry over a governance intent's canonical
156
+ * bytes. For ES256 that is base64 of the ASN.1 DER ECDSA signature over
157
+ * SHA-256(payload); for a passkey it is the packed assertion.
158
+ */
159
+ interface GovernanceSigner {
160
+ sign(payload: Uint8Array): Promise<string> | string;
161
+ }
162
+ /** A {@link GovernanceSigner} or a bare signing function. */
163
+ type GovernanceSignerLike = GovernanceSigner | ((payload: Uint8Array) => Promise<string> | string);
164
+ /**
165
+ * Sign an intent with each signer, one after another (passkey prompts must
166
+ * not overlap), and return the signatures in signer order.
167
+ *
168
+ * @throws when `signers` is empty or a signer returns an empty signature
169
+ */
170
+ declare function signGovernanceIntent(intent: CanonicalIntent | Uint8Array, signers: readonly GovernanceSignerLike[]): Promise<string[]>;
171
+ /**
172
+ * The part of WebCrypto's `SubtleCrypto` the ES256 signer uses. Declared
173
+ * structurally so the SDK does not need the DOM type library; a real
174
+ * `crypto.subtle` (browser, Deno, Node's `webcrypto.subtle`) satisfies it.
175
+ */
176
+ interface SubtleCryptoLike {
177
+ sign(algorithm: {
178
+ name: 'ECDSA';
179
+ hash: 'SHA-256';
180
+ }, key: never, data: ArrayBuffer): Promise<ArrayBuffer>;
181
+ }
182
+ /**
183
+ * An ES256 {@link GovernanceSigner} over a WebCrypto P-256 private key, for
184
+ * browsers and other runtimes without `node:crypto`. The key can be
185
+ * non-extractable. WebCrypto returns raw `r || s`; this converts it to the
186
+ * ASN.1 DER form the platform verifies.
187
+ *
188
+ * @param privateKey - an ECDSA P-256 `CryptoKey` with the `sign` usage
189
+ * (typed loosely so the SDK does not require the DOM type library)
190
+ * @param subtle - the SubtleCrypto to use (defaults to `globalThis.crypto.subtle`)
191
+ */
192
+ declare function webCryptoES256Signer(privateKey: object, subtle?: SubtleCryptoLike): GovernanceSigner;
193
+
194
+ /**
195
+ * RFC 8785 (JCS) canonical JSON — the exact bytes the platform signs.
196
+ *
197
+ * A payload canonicalized here matches the platform's `enc.C14nJSON`
198
+ * (json.Marshal + jsoncanonicalizer.Transform) byte-for-byte, so a
199
+ * signature produced from the result verifies server-side.
200
+ *
201
+ * This implementation covers the value shapes the SDK ever puts into a
202
+ * signed payload: nulls, booleans, finite integers/floats, strings,
203
+ * arrays, and plain object maps. It intentionally does NOT handle
204
+ * non-integer numbers with fractional parts differently from
205
+ * JSON.stringify, because every mandate/endorsement payload the SDK
206
+ * produces uses only integers, strings, arrays, and object maps — decimal
207
+ * amounts are always sent as strings.
208
+ */
209
+ /**
210
+ * RFC 8785 (JCS) canonicalize `value` and return its bytes as a UTF-8 string.
211
+ *
212
+ * @throws if `value` contains a non-finite number, a Symbol, a bigint, or a
213
+ * circular reference — any of which cannot be encoded to canonical JSON.
214
+ */
215
+ declare function canonicalJSON(value: unknown): string;
216
+
217
+ /**
218
+ * Passkey (WebAuthn) signatures for governance intents.
219
+ *
220
+ * The platform verifies a passkey signature like this: the assertion's
221
+ * `clientDataJSON.challenge` must decode to the intent's canonical JSON
222
+ * itself (NOT a hash of it), and the authenticator's signature over
223
+ * `authenticatorData || SHA-256(clientDataJSON)` must verify against the
224
+ * signer's registered COSE key. The `signatures[]` entry is base64url of the
225
+ * `CredentialAssertionResponse` JSON.
226
+ *
227
+ * So the SDK does two small things and never touches the credential:
228
+ * - {@link buildChallenge} gives you the bytes to pass as
229
+ * `navigator.credentials.get({ publicKey: { challenge } })`.
230
+ * - {@link packAssertion} turns the returned credential into the
231
+ * `signatures[]` entry.
232
+ */
233
+
234
+ /**
235
+ * Binary data as WebAuthn APIs hand it out: an ArrayBuffer or typed array
236
+ * (browsers), or a base64 / base64url string (most React Native passkey
237
+ * libraries, and `PublicKeyCredential.toJSON()`).
238
+ */
239
+ type BinaryOrBase64 = ArrayBuffer | ArrayBufferView | string;
240
+ /**
241
+ * The parts of a `PublicKeyCredential` (with an `AuthenticatorAssertionResponse`)
242
+ * that the platform reads. A browser's `navigator.credentials.get()` result
243
+ * satisfies it as-is: the DOM types its `response` as the base
244
+ * `AuthenticatorResponse`, so `authenticatorData` and `signature` are
245
+ * optional here and checked at run time by {@link packAssertion}.
246
+ */
247
+ interface AssertionCredential {
248
+ readonly id: string;
249
+ readonly rawId: BinaryOrBase64;
250
+ readonly type: string;
251
+ readonly authenticatorAttachment?: string | null;
252
+ readonly response: {
253
+ readonly clientDataJSON: BinaryOrBase64;
254
+ readonly authenticatorData?: BinaryOrBase64;
255
+ readonly signature?: BinaryOrBase64;
256
+ readonly userHandle?: BinaryOrBase64 | null;
257
+ };
258
+ }
259
+ /**
260
+ * What a challenge can be built from: a built intent, anything else that
261
+ * carries the `canonical` string (such as a `PreparedSignerGroupChange`),
262
+ * the `canonical` string itself (what a server would send to the browser),
263
+ * or its bytes.
264
+ */
265
+ type ChallengeSource = CanonicalIntent | {
266
+ readonly canonical: string;
267
+ } | string | Uint8Array | ArrayBuffer;
268
+ /**
269
+ * The WebAuthn challenge for an intent: its raw canonical JSON bytes, as a
270
+ * fresh `ArrayBuffer`. Pass it as `publicKey.challenge`; the browser
271
+ * base64url-encodes it into `clientDataJSON`, which is exactly what the
272
+ * platform expects. (An `ArrayBuffer` is a `BufferSource` under every
273
+ * TypeScript version, unlike a `Uint8Array` on TypeScript 5.7+.)
274
+ *
275
+ * @throws TypeError when `intent` is none of the {@link ChallengeSource} forms
276
+ */
277
+ declare function buildChallenge(intent: ChallengeSource): ArrayBuffer;
278
+ /**
279
+ * Package a passkey assertion as a `signatures[]` entry: base64url of the
280
+ * `CredentialAssertionResponse` JSON
281
+ * (`{id, rawId, type, authenticatorAttachment?, clientExtensionResults, response: {clientDataJSON, authenticatorData, signature, userHandle?}}`,
282
+ * every binary field base64url).
283
+ *
284
+ * @param credential - what `navigator.credentials.get()` returned (or a
285
+ * mobile passkey library's equivalent)
286
+ * @throws TypeError when it is not a public-key assertion or a field is
287
+ * missing
288
+ */
289
+ declare function packAssertion(credential: AssertionCredential): string;
290
+ /**
291
+ * Whether a packed passkey signature was made over `intent` — its challenge
292
+ * equals the intent's canonical bytes. A cheap server-side check of what a
293
+ * browser sent back before you submit it. It does NOT verify the signature
294
+ * itself; the platform does that. Returns false for anything that is not a
295
+ * packed assertion, including one longer than 64 KiB.
296
+ */
297
+ declare function assertionChallengeMatches(packed: string, intent: ChallengeSource): boolean;
298
+ /**
299
+ * A {@link GovernanceSigner} backed by a passkey. `getAssertion` receives
300
+ * the challenge and returns the credential; in a browser:
301
+ *
302
+ * ```typescript
303
+ * const signer = webauthnSigner((challenge) =>
304
+ * navigator.credentials.get({
305
+ * publicKey: { challenge, rpId: 'app.example.com', userVerification: 'required' },
306
+ * }) as Promise<PublicKeyCredential>
307
+ * );
308
+ * ```
309
+ *
310
+ * Every call prompts the user, so do not use it with automatic stale-version
311
+ * retries unless a second prompt is acceptable.
312
+ */
313
+ declare function webauthnSigner(getAssertion: (challenge: ArrayBuffer) => Promise<AssertionCredential> | AssertionCredential): GovernanceSigner;
314
+
315
+ export { type AddSignersToGroupIntent, type AssertionCredential, type BinaryOrBase64, type CanonicalIntent, type ChallengeSource, type CreateCryptoDestinationIntent, type GovernanceIntent, type GovernanceSigner, type GovernanceSignerLike, type RemoveSignersFromGroupIntent, type SubtleCryptoLike, type UpdateSignerGroupGovernanceIntent, addSignersToGroupIntent, assertIdempotencyKey, assertionChallengeMatches, buildChallenge, canonicalJSON, createCryptoDestinationIntent, newIdempotencyKey, packAssertion, removeSignersFromGroupIntent, signGovernanceIntent, updateSignerGroupGovernanceIntent, webCryptoES256Signer, webauthnSigner };