@canton-network/core-signing-dfns 0.2.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 ADDED
@@ -0,0 +1,114 @@
1
+ # @canton-network/core-signing-dfns
2
+
3
+ This package provides a signing driver for integrating the Wallet Gateway with [Dfns](https://www.dfns.co/). It implements the `SigningDriverInterface` defined in `@canton-network/core-signing-lib`, allowing the Wallet Gateway to manage keys and sign transactions using Dfns's infrastructure.
4
+
5
+ ## Installation
6
+
7
+ This package is part of the Splice Wallet Kernel monorepo and is typically installed as a workspace dependency.
8
+
9
+ ```bash
10
+ yarn add @canton-network/core-signing-dfns
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ The `DfnsSigningDriver` is designed to be used within the Wallet Gateway's signing architecture. It requires a configuration object containing Dfns organization details and credentials.
16
+
17
+ ### Initialization
18
+
19
+ ```typescript
20
+ import DfnsSigningDriver, {
21
+ DfnsConfig,
22
+ DfnsCredentials,
23
+ } from '@canton-network/core-signing-dfns'
24
+
25
+ const credentials: DfnsCredentials = {
26
+ credId: 'your-credential-id',
27
+ privateKey: 'your-private-key',
28
+ authToken: 'your-auth-token',
29
+ }
30
+
31
+ const config: DfnsConfig = {
32
+ orgId: 'your-dfns-org-id',
33
+ baseUrl: 'https://api.dfns.io', // Dfns API URL
34
+ credentials,
35
+ }
36
+
37
+ const driver = new DfnsSigningDriver(config)
38
+ ```
39
+
40
+ ### Features
41
+
42
+ Dfns is used as a sign-only provider: the driver creates ed25519 keys and produces hash signatures, while topology submission and ledger interaction happen on the Wallet Gateway against its configured validator (bring-your-own-validator).
43
+
44
+ - **Key Management**:
45
+ - `createKey`: Creates a new ed25519 key in Dfns.
46
+ - `getKeys`: Lists active Canton-compatible (`EdDSA` / `ed25519`) keys.
47
+ - **Signing**:
48
+ - `signTransaction`: Submits a hash signing request to Dfns for the resolved key. Returns immediately with a signature id; signature bytes are fetched via `getTransaction` once Dfns reports the request as `Signed`.
49
+ - **Signature Status**:
50
+ - `getTransaction`: Retrieves the status and signature for a previously submitted signing request.
51
+ - `getTransactions`: Retrieves multiple signatures filtered by id or public key.
52
+ - **Configuration**:
53
+ - `getConfiguration` / `setConfiguration`.
54
+
55
+ ### Integration
56
+
57
+ This driver is intended to be registered with the `SigningController` in the Wallet Gateway, which manages multiple signing providers.
58
+
59
+ ```typescript
60
+ // Example integration (conceptual)
61
+ import { SigningController } from '@canton-network/core-signing-internal' // or similar
62
+
63
+ const signingController = new SigningController()
64
+ signingController.registerDriver(driver)
65
+ ```
66
+
67
+ ## Configuration
68
+
69
+ The driver accepts a `DfnsConfig` object:
70
+
71
+ | Property | Type | Required | Description |
72
+ | :------------ | :---------------- | :------- | :----------------------------------------------------------- |
73
+ | `orgId` | `string` | Yes | Your Dfns organization ID. |
74
+ | `baseUrl` | `string` | Yes | The base URL for the Dfns API (e.g., `https://api.dfns.io`). |
75
+ | `credentials` | `DfnsCredentials` | Yes | Credentials used to authenticate with Dfns. |
76
+
77
+ ### DfnsCredentials
78
+
79
+ Dfns uses two-layer authentication: a long-lived service account JWT plus per-request signing with a private key.
80
+
81
+ | Property | Type | Description |
82
+ | :----------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
83
+ | `credId` | `string` | ID of the Dfns credential registered against the service account. |
84
+ | `privateKey` | `string` | PEM-encoded private key paired with `credId`. Signs every sensitive Dfns API request as a U2F-style second factor. Configured once; not derived from `authToken`. |
85
+ | `authToken` | `string` | Long-lived service account bearer JWT issued by the Dfns dashboard. Does not auto-expire and is not regenerated from `privateKey`/`credId`; rotate by issuing a new token in the dashboard. |
86
+
87
+ ### Wallet Gateway Configuration
88
+
89
+ When running the Wallet Gateway (Remote), the Dfns signing driver is configured using the following environment variables:
90
+
91
+ - `DFNS_ORG_ID`: Your Dfns organization ID.
92
+ - `DFNS_BASE_URL`: The base URL for the Dfns API. Defaults to `https://api.dfns.io` if not set.
93
+ - `DFNS_CRED_ID`: The default credential ID for Dfns API authentication.
94
+ - `DFNS_PRIVATE_KEY`: The private key for signing Dfns API requests.
95
+ - `DFNS_AUTH_TOKEN`: The authentication token for the Dfns API.
96
+
97
+ Example usage:
98
+
99
+ ```bash
100
+ DFNS_ORG_ID="your-org-id" \
101
+ DFNS_BASE_URL="https://api.dfns.io" \
102
+ DFNS_CRED_ID="your-cred-id" \
103
+ DFNS_PRIVATE_KEY="your-private-key" \
104
+ DFNS_AUTH_TOKEN="your-auth-token" \
105
+ yarn start
106
+ ```
107
+
108
+ ## Canton Network Support
109
+
110
+ Keys are created with `scheme: EdDSA` and `curve: ed25519`. The driver lists and resolves only `Active` ed25519 keys. The Wallet Gateway is responsible for binding keys to a specific Canton network via its own party allocation flow.
111
+
112
+ ## License
113
+
114
+ Apache-2.0
package/dist/dfns.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { SigningStatus } from '@canton-network/core-signing-lib';
2
+ /**
3
+ * Credentials for a Dfns service account. Dfns uses two-layer auth: a
4
+ * long-lived bearer token plus per-request signing with a private key.
5
+ */
6
+ export interface DfnsCredentials {
7
+ /** ID of the Dfns credential (key) registered against the service account. */
8
+ credId: string;
9
+ /**
10
+ * PEM-encoded private key paired with `credId`. Used to sign every
11
+ * sensitive Dfns API request as a U2F-style second factor. Configured
12
+ * once per deployment; not derived from `authToken`.
13
+ */
14
+ privateKey: string;
15
+ /**
16
+ * Long-lived service account bearer JWT issued by the Dfns dashboard.
17
+ * Does not auto-expire and is not regenerated from `privateKey`/`credId`.
18
+ * Rotate by issuing a new token in the Dfns dashboard.
19
+ */
20
+ authToken: string;
21
+ }
22
+ export interface DfnsKey {
23
+ /** Dfns key id (e.g. `key-...`). */
24
+ id: string;
25
+ /** Human-readable name configured on the Dfns key. */
26
+ name: string;
27
+ /** ed25519 public key, base64-encoded (Canton format). */
28
+ publicKey: string;
29
+ }
30
+ export interface DfnsSignature {
31
+ /** Dfns signature id (used as the txId returned to the gateway). */
32
+ id: string;
33
+ /** Dfns key id the signature was produced with. */
34
+ keyId: string;
35
+ status: SigningStatus;
36
+ /** ed25519 signature, base64-encoded (Canton SIGNATURE_FORMAT_CONCAT). */
37
+ signature?: string;
38
+ }
39
+ export declare class DfnsHandler {
40
+ private client;
41
+ private orgId;
42
+ private baseUrl;
43
+ constructor(orgId: string, baseUrl: string, credentials: DfnsCredentials);
44
+ private createClient;
45
+ /**
46
+ * Create a raw ed25519 key in Dfns suitable for signing Canton topology
47
+ * and ledger transactions. The key is not bound to a network — chain
48
+ * activation happens on the gateway against its configured validator.
49
+ */
50
+ createKey(name: string): Promise<DfnsKey>;
51
+ iterateKeys(): AsyncGenerator<DfnsKey>;
52
+ listKeys(): Promise<DfnsKey[]>;
53
+ getKey(keyId: string): Promise<DfnsKey | undefined>;
54
+ /**
55
+ * Resolve a key by base64 ed25519 public key. Iterates Dfns keys —
56
+ * acceptable for first iteration since most deployments hold a single
57
+ * Canton key per credential.
58
+ */
59
+ findKeyByPublicKey(publicKeyBase64: string): Promise<DfnsKey | undefined>;
60
+ /**
61
+ * Submit a hash signing request to Dfns. Returns immediately with the
62
+ * signature id and current status; signature bytes are fetched via
63
+ * {@link getSignature} once the request reaches `signed` status.
64
+ *
65
+ * The hash is reused as the Dfns idempotency key — re-signing the same
66
+ * hash returns the existing signature rather than producing a duplicate,
67
+ * which is safe because Canton's command deduplication handles repeats
68
+ * at the ledger level.
69
+ *
70
+ * @param keyId Dfns key id resolved from the gateway's key identifier.
71
+ * @param hashBase64 32-byte hash, base64-encoded (Canton TxHash format).
72
+ */
73
+ signHash(keyId: string, hashBase64: string): Promise<DfnsSignature>;
74
+ getSignature(keyId: string, signatureId: string): Promise<DfnsSignature | undefined>;
75
+ /**
76
+ * Locate a signature across all Canton keys. Used when the gateway
77
+ * polls by signature id without knowing the originating key id.
78
+ */
79
+ findSignature(signatureId: string): Promise<DfnsSignature | undefined>;
80
+ listSignatures(keyId: string): AsyncGenerator<DfnsSignature>;
81
+ private extractSignature;
82
+ private mapStatus;
83
+ }
84
+ //# sour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AAO,CAAC,OAAO,GAAG,SAAS,CAAC;IAS/B;;;;;;;;;;;;OAYG;IACU,QAAQ,CACjB,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,MAAM,GACnB,OAAO,CAAC,aAAa,CAAC;IAuBZ,YAAY,CACrB,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,MAAM,GACpB,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;IAkBrC;;;OAGG;IACU,aAAa,CACtB,WAAW,EAAE,MAAM,GACpB,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;IAQvB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,CAAC,aAAa,CAAC;IAwB1E,OAAO,CAAC,gBAAgB;IAYxB,OAAO,CAAC,SAAS;CAiBpB"}
package/dist/index.cjs ADDED
@@ -0,0 +1,421 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var coreSigningLib = require('@canton-network/core-signing-lib');
6
+ var sdk = require('@dfns/sdk');
7
+ var sdkKeysigner = require('@dfns/sdk-keysigner');
8
+ var pino = require('pino');
9
+ var _ = require('lodash');
10
+ var zod = require('zod');
11
+
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var ___default = /*#__PURE__*/_interopDefault(_);
15
+
16
+ var __defProp = Object.defineProperty;
17
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
18
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
19
+ var logger = pino.pino({ name: "dfns-handler", level: "debug" });
20
+ var DFNS_LIST_PAGE_SIZE = 50;
21
+ function hexToBase64(hex) {
22
+ return Buffer.from(hex, "hex").toString("base64");
23
+ }
24
+ function base64ToHex(base64) {
25
+ return Buffer.from(base64, "base64").toString("hex");
26
+ }
27
+ function isCantonKey(scheme, curve) {
28
+ return scheme === "EdDSA" && curve === "ed25519";
29
+ }
30
+ var DfnsHandler = class {
31
+ constructor(orgId, baseUrl, credentials) {
32
+ __publicField(this, "client");
33
+ __publicField(this, "orgId");
34
+ __publicField(this, "baseUrl");
35
+ this.orgId = orgId;
36
+ this.baseUrl = baseUrl;
37
+ this.client = this.createClient(credentials);
38
+ }
39
+ createClient(credentials) {
40
+ const signer = new sdkKeysigner.AsymmetricKeySigner({
41
+ credId: credentials.credId,
42
+ privateKey: credentials.privateKey
43
+ });
44
+ return new sdk.DfnsApiClient({
45
+ orgId: this.orgId,
46
+ authToken: credentials.authToken,
47
+ baseUrl: this.baseUrl,
48
+ signer
49
+ });
50
+ }
51
+ /**
52
+ * Create a raw ed25519 key in Dfns suitable for signing Canton topology
53
+ * and ledger transactions. The key is not bound to a network — chain
54
+ * activation happens on the gateway against its configured validator.
55
+ */
56
+ async createKey(name) {
57
+ try {
58
+ const key = await this.client.keys.createKey({
59
+ body: {
60
+ scheme: "EdDSA",
61
+ curve: "ed25519",
62
+ name
63
+ }
64
+ });
65
+ return {
66
+ id: key.id,
67
+ name: key.name || key.id,
68
+ publicKey: hexToBase64(key.publicKey)
69
+ };
70
+ } catch (error) {
71
+ logger.error(error, "Error creating Dfns key");
72
+ throw error;
73
+ }
74
+ }
75
+ async *iterateKeys() {
76
+ let paginationToken;
77
+ do {
78
+ const response = await this.client.keys.listKeys({
79
+ query: {
80
+ limit: DFNS_LIST_PAGE_SIZE,
81
+ ...paginationToken ? { paginationToken } : {}
82
+ }
83
+ });
84
+ for (const key of response.items) {
85
+ if (key.status !== "Active" || !isCantonKey(key.scheme, key.curve)) {
86
+ continue;
87
+ }
88
+ yield {
89
+ id: key.id,
90
+ name: key.name || key.id,
91
+ publicKey: hexToBase64(key.publicKey)
92
+ };
93
+ }
94
+ paginationToken = response.nextPageToken;
95
+ } while (paginationToken);
96
+ }
97
+ async listKeys() {
98
+ const keys = [];
99
+ try {
100
+ for await (const key of this.iterateKeys()) {
101
+ keys.push(key);
102
+ }
103
+ } catch (error) {
104
+ logger.error(error, "Error listing Dfns keys");
105
+ throw error;
106
+ }
107
+ return keys;
108
+ }
109
+ async getKey(keyId) {
110
+ try {
111
+ const key = await this.client.keys.getKey({ keyId });
112
+ if (key.status !== "Active" || !isCantonKey(key.scheme, key.curve)) {
113
+ return void 0;
114
+ }
115
+ return {
116
+ id: key.id,
117
+ name: key.name || key.id,
118
+ publicKey: hexToBase64(key.publicKey)
119
+ };
120
+ } catch (error) {
121
+ logger.debug(error, `Key ${keyId} not found`);
122
+ return void 0;
123
+ }
124
+ }
125
+ /**
126
+ * Resolve a key by base64 ed25519 public key. Iterates Dfns keys —
127
+ * acceptable for first iteration since most deployments hold a single
128
+ * Canton key per credential.
129
+ */
130
+ async findKeyByPublicKey(publicKeyBase64) {
131
+ for await (const key of this.iterateKeys()) {
132
+ if (key.publicKey === publicKeyBase64) {
133
+ return key;
134
+ }
135
+ }
136
+ return void 0;
137
+ }
138
+ /**
139
+ * Submit a hash signing request to Dfns. Returns immediately with the
140
+ * signature id and current status; signature bytes are fetched via
141
+ * {@link getSignature} once the request reaches `signed` status.
142
+ *
143
+ * The hash is reused as the Dfns idempotency key — re-signing the same
144
+ * hash returns the existing signature rather than producing a duplicate,
145
+ * which is safe because Canton's command deduplication handles repeats
146
+ * at the ledger level.
147
+ *
148
+ * @param keyId Dfns key id resolved from the gateway's key identifier.
149
+ * @param hashBase64 32-byte hash, base64-encoded (Canton TxHash format).
150
+ */
151
+ async signHash(keyId, hashBase64) {
152
+ try {
153
+ const result = await this.client.keys.generateSignature({
154
+ keyId,
155
+ body: {
156
+ kind: "Hash",
157
+ hash: base64ToHex(hashBase64),
158
+ blockchainKind: "Canton",
159
+ externalId: base64ToHex(hashBase64)
160
+ }
161
+ });
162
+ return {
163
+ id: result.id,
164
+ keyId,
165
+ status: this.mapStatus(result.status),
166
+ signature: this.extractSignature(result.signature)
167
+ };
168
+ } catch (error) {
169
+ logger.error(error, "Error signing hash with Dfns");
170
+ throw error;
171
+ }
172
+ }
173
+ async getSignature(keyId, signatureId) {
174
+ try {
175
+ const result = await this.client.keys.getSignature({
176
+ keyId,
177
+ signatureId
178
+ });
179
+ return {
180
+ id: result.id,
181
+ keyId,
182
+ status: this.mapStatus(result.status),
183
+ signature: this.extractSignature(result.signature)
184
+ };
185
+ } catch (error) {
186
+ logger.debug(error, `Signature ${signatureId} not found`);
187
+ return void 0;
188
+ }
189
+ }
190
+ /**
191
+ * Locate a signature across all Canton keys. Used when the gateway
192
+ * polls by signature id without knowing the originating key id.
193
+ */
194
+ async findSignature(signatureId) {
195
+ for await (const key of this.iterateKeys()) {
196
+ const sig = await this.getSignature(key.id, signatureId);
197
+ if (sig) return sig;
198
+ }
199
+ return void 0;
200
+ }
201
+ async *listSignatures(keyId) {
202
+ let paginationToken;
203
+ do {
204
+ const response = await this.client.keys.listSignatures({
205
+ keyId,
206
+ query: {
207
+ limit: DFNS_LIST_PAGE_SIZE,
208
+ ...paginationToken ? { paginationToken } : {}
209
+ }
210
+ });
211
+ for (const sig of response.items) {
212
+ yield {
213
+ id: sig.id,
214
+ keyId,
215
+ status: this.mapStatus(sig.status),
216
+ signature: this.extractSignature(sig.signature)
217
+ };
218
+ }
219
+ paginationToken = response.nextPageToken;
220
+ } while (paginationToken);
221
+ }
222
+ extractSignature(signature) {
223
+ if (!signature) return void 0;
224
+ const hex = signature.encoded ?? `${signature.r}${signature.s}`;
225
+ return hexToBase64(hex);
226
+ }
227
+ mapStatus(dfnsStatus) {
228
+ switch (dfnsStatus) {
229
+ case "Signed":
230
+ case "Confirmed":
231
+ return "signed";
232
+ case "Pending":
233
+ case "Executing":
234
+ return "pending";
235
+ case "Rejected":
236
+ return "rejected";
237
+ case "Failed":
238
+ return "failed";
239
+ default:
240
+ logger.warn(`Unknown Dfns signature status: ${dfnsStatus}`);
241
+ return "pending";
242
+ }
243
+ }
244
+ };
245
+ var DfnsCredentialsSchema = zod.z.object({
246
+ credId: zod.z.string().min(1),
247
+ privateKey: zod.z.string().min(1),
248
+ authToken: zod.z.string().min(1)
249
+ });
250
+ var DfnsConfigSchema = zod.z.object({
251
+ orgId: zod.z.string().min(1),
252
+ baseUrl: zod.z.string().url(),
253
+ credentials: DfnsCredentialsSchema
254
+ });
255
+ var createDfnsHandler = (config) => new DfnsHandler(config.orgId, config.baseUrl, config.credentials);
256
+ function toTransaction(sig, publicKey) {
257
+ const tx = {
258
+ txId: sig.id,
259
+ status: sig.status
260
+ };
261
+ if (sig.signature) tx.signature = sig.signature;
262
+ if (publicKey) tx.publicKey = publicKey;
263
+ return tx;
264
+ }
265
+ var DfnsSigningDriver = class {
266
+ constructor(config) {
267
+ __publicField(this, "dfns");
268
+ __publicField(this, "config");
269
+ __publicField(this, "partyMode", coreSigningLib.PartyMode.EXTERNAL);
270
+ __publicField(this, "signingProvider", coreSigningLib.SigningProvider.DFNS);
271
+ __publicField(this, "controller", (_userId) => coreSigningLib.buildController({
272
+ signTransaction: async (params) => {
273
+ try {
274
+ const keyId = await this.resolveKeyId(params.keyIdentifier);
275
+ if (!keyId) {
276
+ return {
277
+ error: "key_not_found",
278
+ error_description: "No Dfns key found for the provided key identifier."
279
+ };
280
+ }
281
+ if (!params.txHash) {
282
+ return {
283
+ error: "bad_arguments",
284
+ error_description: "txHash is required to sign with Dfns."
285
+ };
286
+ }
287
+ const sig = await this.dfns.signHash(keyId, params.txHash);
288
+ return toTransaction(sig, params.keyIdentifier.publicKey);
289
+ } catch (error) {
290
+ return {
291
+ error: "signing_error",
292
+ error_description: error.message
293
+ };
294
+ }
295
+ },
296
+ getTransaction: async (params) => {
297
+ try {
298
+ const sig = await this.dfns.findSignature(params.txId);
299
+ if (!sig) {
300
+ return {
301
+ error: "transaction_not_found",
302
+ error_description: "The requested signature does not exist."
303
+ };
304
+ }
305
+ const key = await this.dfns.getKey(sig.keyId);
306
+ return toTransaction(sig, key?.publicKey);
307
+ } catch (error) {
308
+ return {
309
+ error: "fetch_error",
310
+ error_description: error.message
311
+ };
312
+ }
313
+ },
314
+ getTransactions: async (params) => {
315
+ if (!params.publicKeys && !params.txIds) {
316
+ return {
317
+ error: "bad_arguments",
318
+ error_description: "Either publicKeys or txIds must be provided."
319
+ };
320
+ }
321
+ try {
322
+ const txIds = new Set(params.txIds || []);
323
+ const publicKeys = new Set(params.publicKeys || []);
324
+ const transactions = [];
325
+ for await (const key of this.dfns.iterateKeys()) {
326
+ if (params.publicKeys && !publicKeys.has(key.publicKey)) {
327
+ continue;
328
+ }
329
+ for await (const sig of this.dfns.listSignatures(
330
+ key.id
331
+ )) {
332
+ if (params.txIds && !txIds.has(sig.id)) continue;
333
+ transactions.push(toTransaction(sig, key.publicKey));
334
+ if (params.txIds && !params.publicKeys && transactions.length === txIds.size) {
335
+ return { transactions };
336
+ }
337
+ }
338
+ }
339
+ return { transactions };
340
+ } catch (error) {
341
+ return {
342
+ error: "fetch_error",
343
+ error_description: error.message
344
+ };
345
+ }
346
+ },
347
+ getKeys: async () => {
348
+ try {
349
+ const keys = await this.dfns.listKeys();
350
+ return {
351
+ keys: keys.map((k) => ({
352
+ id: k.id,
353
+ name: k.name,
354
+ publicKey: k.publicKey
355
+ }))
356
+ };
357
+ } catch (error) {
358
+ return {
359
+ error: "fetch_error",
360
+ error_description: error.message
361
+ };
362
+ }
363
+ },
364
+ createKey: async (params) => {
365
+ try {
366
+ const key = await this.dfns.createKey(params.name);
367
+ return {
368
+ id: key.id,
369
+ name: key.name,
370
+ publicKey: key.publicKey
371
+ };
372
+ } catch (error) {
373
+ return {
374
+ error: "creation_error",
375
+ error_description: error.message
376
+ };
377
+ }
378
+ },
379
+ getConfiguration: async () => ({
380
+ orgId: this.config.orgId,
381
+ baseUrl: this.config.baseUrl,
382
+ credentials: this.config.credentials
383
+ }),
384
+ setConfiguration: async (params) => {
385
+ const validated = DfnsConfigSchema.safeParse(params);
386
+ if (!validated.success) {
387
+ return {
388
+ error: "bad_arguments",
389
+ error_description: validated.error.message
390
+ };
391
+ }
392
+ const newConfig = {
393
+ orgId: validated.data.orgId,
394
+ baseUrl: validated.data.baseUrl,
395
+ credentials: validated.data.credentials
396
+ };
397
+ if (!___default.default.isEqual(newConfig, this.config)) {
398
+ this.config = newConfig;
399
+ this.dfns = createDfnsHandler(this.config);
400
+ }
401
+ return params;
402
+ },
403
+ subscribeTransactions: async (_params) => {
404
+ return Promise.resolve({});
405
+ }
406
+ }));
407
+ this.config = config;
408
+ this.dfns = createDfnsHandler(config);
409
+ }
410
+ async resolveKeyId(keyIdentifier) {
411
+ if (keyIdentifier.id) return keyIdentifier.id;
412
+ if (!keyIdentifier.publicKey) return void 0;
413
+ const key = await this.dfns.findKeyByPublicKey(keyIdentifier.publicKey);
414
+ return key?.id;
415
+ }
416
+ };
417
+
418
+ exports.DfnsHandler = DfnsHandler;
419
+ exports.default = DfnsSigningDriver;
420
+ //# sourceMappingURL=index.cjs.map
421
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/dfns.ts","../src/index.ts"],"names":["pino","AsymmetricKeySigner","DfnsApiClient","z","PartyMode","SigningProvider","buildController","_"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,IAAM,SAASA,SAAA,CAAK,EAAE,MAAM,cAAA,EAAgB,KAAA,EAAO,SAAS,CAAA;AAE5D,IAAM,mBAAA,GAAsB,EAAA;AA0C5B,SAAS,YAAY,GAAA,EAAqB;AACtC,EAAA,OAAO,OAAO,IAAA,CAAK,GAAA,EAAK,KAAK,CAAA,CAAE,SAAS,QAAQ,CAAA;AACpD;AAEA,SAAS,YAAY,MAAA,EAAwB;AACzC,EAAA,OAAO,OAAO,IAAA,CAAK,MAAA,EAAQ,QAAQ,CAAA,CAAE,SAAS,KAAK,CAAA;AACvD;AAEA,SAAS,WAAA,CAAY,QAAgB,KAAA,EAAwB;AACzD,EAAA,OAAO,MAAA,KAAW,WAAW,KAAA,KAAU,SAAA;AAC3C;AAEO,IAAM,cAAN,MAAkB;AAAA,EAKrB,WAAA,CAAY,KAAA,EAAe,OAAA,EAAiB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aAAA,CAAc,EAAA,EAAI,OAAO,aAAA,CAAc,EAAA;AAC3C,IAAA,IAAI,CAAC,aAAA,CAAc,SAAA,EAAW,OAAO,MAAA;AAErC,IAAA,MAAM,MAAM,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAA,CAAmB,cAAc,SAAS,CAAA;AACtE,IAAA,OAAO,GAAA,EAAK,EAAA;AAAA,EAChB;AAwLJ","file":"index.cjs","sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { DfnsApiClient } from '@dfns/sdk'\nimport { AsymmetricKeySigner } from '@dfns/sdk-keysigner'\nimport { SigningStatus } from '@canton-network/core-signing-lib'\nimport { pino } from 'pino'\n\nconst logger = pino({ name: 'dfns-handler', level: 'debug' })\n\nconst DFNS_LIST_PAGE_SIZE = 50\n\n/**\n * Credentials for a Dfns service account. Dfns uses two-layer auth: a\n * long-lived bearer token plus per-request signing with a private key.\n */\nexport interface DfnsCredentials {\n /** ID of the Dfns credential (key) registered against the service account. */\n credId: string\n /**\n * PEM-encoded private key paired with `credId`. Used to sign every\n * sensitive Dfns API request as a U2F-style second factor. Configured\n * once per deployment; not derived from `authToken`.\n */\n privateKey: string\n /**\n * Long-lived service account bearer JWT issued by the Dfns dashboard.\n * Does not auto-expire and is not regenerated from `privateKey`/`credId`.\n * Rotate by issuing a new token in the Dfns dashboard.\n */\n authToken: string\n}\n\nexport interface DfnsKey {\n /** Dfns key id (e.g. `key-...`). */\n id: string\n /** Human-readable name configured on the Dfns key. */\n name: string\n /** ed25519 public key, base64-encoded (Canton format). */\n publicKey: string\n}\n\nexport interface DfnsSignature {\n /** Dfns signature id (used as the txId returned to the gateway). */\n id: string\n /** Dfns key id the signature was produced with. */\n keyId: string\n status: SigningStatus\n /** ed25519 signature, base64-encoded (Canton SIGNATURE_FORMAT_CONCAT). */\n signature?: string\n}\n\nfunction hexToBase64(hex: string): string {\n return Buffer.from(hex, 'hex').toString('base64')\n}\n\nfunction base64ToHex(base64: string): string {\n return Buffer.from(base64, 'base64').toString('hex')\n}\n\nfunction isCantonKey(scheme: string, curve: string): boolean {\n return scheme === 'EdDSA' && curve === 'ed25519'\n}\n\nexport class DfnsHandler {\n private client: DfnsApiClient\n private orgId: string\n private baseUrl: string\n\n constructor(orgId: string, baseUrl: string, credentials: DfnsCredentials) {\n this.orgId = orgId\n this.baseUrl = baseUrl\n this.client = this.createClient(credentials)\n }\n\n private createClient(credentials: DfnsCredentials): DfnsApiClient {\n const signer = new AsymmetricKeySigner({\n credId: credentials.credId,\n privateKey: credentials.privateKey,\n })\n\n return new DfnsApiClient({\n orgId: this.orgId,\n authToken: credentials.authToken,\n baseUrl: this.baseUrl,\n signer,\n })\n }\n\n /**\n * Create a raw ed25519 key in Dfns suitable for signing Canton topology\n * and ledger transactions. The key is not bound to a network — chain\n * activation happens on the gateway against its configured validator.\n */\n public async createKey(name: string): Promise<DfnsKey> {\n try {\n const key = await this.client.keys.createKey({\n body: {\n scheme: 'EdDSA',\n curve: 'ed25519',\n name,\n },\n })\n return {\n id: key.id,\n name: key.name || key.id,\n publicKey: hexToBase64(key.publicKey),\n }\n } catch (error) {\n logger.error(error, 'Error creating Dfns key')\n throw error\n }\n }\n\n public async *iterateKeys(): AsyncGenerator<DfnsKey> {\n let paginationToken: string | undefined\n do {\n const response = await this.client.keys.listKeys({\n query: {\n limit: DFNS_LIST_PAGE_SIZE,\n ...(paginationToken ? { paginationToken } : {}),\n },\n })\n\n for (const key of response.items) {\n if (\n key.status !== 'Active' ||\n !isCantonKey(key.scheme, key.curve)\n ) {\n continue\n }\n yield {\n id: key.id,\n name: key.name || key.id,\n publicKey: hexToBase64(key.publicKey),\n }\n }\n\n paginationToken = response.nextPageToken\n } while (paginationToken)\n }\n\n public async listKeys(): Promise<DfnsKey[]> {\n const keys: DfnsKey[] = []\n try {\n for await (const key of this.iterateKeys()) {\n keys.push(key)\n }\n } catch (error) {\n logger.error(error, 'Error listing Dfns keys')\n throw error\n }\n return keys\n }\n\n public async getKey(keyId: string): Promise<DfnsKey | undefined> {\n try {\n const key = await this.client.keys.getKey({ keyId })\n if (\n key.status !== 'Active' ||\n !isCantonKey(key.scheme, key.curve)\n ) {\n return undefined\n }\n return {\n id: key.id,\n name: key.name || key.id,\n publicKey: hexToBase64(key.publicKey),\n }\n } catch (error) {\n logger.debug(error, `Key ${keyId} not found`)\n return undefined\n }\n }\n\n /**\n * Resolve a key by base64 ed25519 public key. Iterates Dfns keys —\n * acceptable for first iteration since most deployments hold a single\n * Canton key per credential.\n */\n public async findKeyByPublicKey(\n publicKeyBase64: string\n ): Promise<DfnsKey | undefined> {\n for await (const key of this.iterateKeys()) {\n if (key.publicKey === publicKeyBase64) {\n return key\n }\n }\n return undefined\n }\n\n /**\n * Submit a hash signing request to Dfns. Returns immediately with the\n * signature id and current status; signature bytes are fetched via\n * {@link getSignature} once the request reaches `signed` status.\n *\n * The hash is reused as the Dfns idempotency key — re-signing the same\n * hash returns the existing signature rather than producing a duplicate,\n * which is safe because Canton's command deduplication handles repeats\n * at the ledger level.\n *\n * @param keyId Dfns key id resolved from the gateway's key identifier.\n * @param hashBase64 32-byte hash, base64-encoded (Canton TxHash format).\n */\n public async signHash(\n keyId: string,\n hashBase64: string\n ): Promise<DfnsSignature> {\n try {\n const result = await this.client.keys.generateSignature({\n keyId,\n body: {\n kind: 'Hash',\n hash: base64ToHex(hashBase64),\n blockchainKind: 'Canton',\n externalId: base64ToHex(hashBase64),\n },\n })\n return {\n id: result.id,\n keyId,\n status: this.mapStatus(result.status),\n signature: this.extractSignature(result.signature),\n }\n } catch (error) {\n logger.error(error, 'Error signing hash with Dfns')\n throw error\n }\n }\n\n public async getSignature(\n keyId: string,\n signatureId: string\n ): Promise<DfnsSignature | undefined> {\n try {\n const result = await this.client.keys.getSignature({\n keyId,\n signatureId,\n })\n return {\n id: result.id,\n keyId,\n status: this.mapStatus(result.status),\n signature: this.extractSignature(result.signature),\n }\n } catch (error) {\n logger.debug(error, `Signature ${signatureId} not found`)\n return undefined\n }\n }\n\n /**\n * Locate a signature across all Canton keys. Used when the gateway\n * polls by signature id without knowing the originating key id.\n */\n public async findSignature(\n signatureId: string\n ): Promise<DfnsSignature | undefined> {\n for await (const key of this.iterateKeys()) {\n const sig = await this.getSignature(key.id, signatureId)\n if (sig) return sig\n }\n return undefined\n }\n\n public async *listSignatures(keyId: string): AsyncGenerator<DfnsSignature> {\n let paginationToken: string | undefined\n do {\n const response = await this.client.keys.listSignatures({\n keyId,\n query: {\n limit: DFNS_LIST_PAGE_SIZE,\n ...(paginationToken ? { paginationToken } : {}),\n },\n })\n\n for (const sig of response.items) {\n yield {\n id: sig.id,\n keyId,\n status: this.mapStatus(sig.status),\n signature: this.extractSignature(sig.signature),\n }\n }\n\n paginationToken = response.nextPageToken\n } while (paginationToken)\n }\n\n private extractSignature(signature?: {\n encoded?: string\n r: string\n s: string\n }): string | undefined {\n if (!signature) return undefined\n // For ed25519, `encoded` is the 64-byte r||s concat in hex; fall back\n // to assembling it from r/s if `encoded` is not populated.\n const hex = signature.encoded ?? `${signature.r}${signature.s}`\n return hexToBase64(hex)\n }\n\n private mapStatus(dfnsStatus: string): SigningStatus {\n switch (dfnsStatus) {\n case 'Signed':\n case 'Confirmed':\n return 'signed'\n case 'Pending':\n case 'Executing':\n return 'pending'\n case 'Rejected':\n return 'rejected'\n case 'Failed':\n return 'failed'\n default:\n logger.warn(`Unknown Dfns signature status: ${dfnsStatus}`)\n return 'pending'\n }\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n buildController,\n PartyMode,\n SigningDriverInterface,\n SigningProvider,\n} from '@canton-network/core-signing-lib'\n\nimport {\n SignTransactionParams,\n SignTransactionResult,\n GetTransactionParams,\n GetTransactionResult,\n GetTransactionsResult,\n GetTransactionsParams,\n GetKeysResult,\n CreateKeyParams,\n CreateKeyResult,\n GetConfigurationResult,\n SetConfigurationParams,\n SubscribeTransactionsParams,\n SubscribeTransactionsResult,\n SetConfigurationResult,\n Transaction,\n} from '@canton-network/core-signing-lib'\nimport { DfnsHandler, DfnsCredentials, DfnsSignature } from './dfns.js'\nimport { AuthContext } from '@canton-network/core-wallet-auth'\nimport _ from 'lodash'\nimport { z } from 'zod'\n\nexport type { DfnsCredentials, DfnsKey, DfnsSignature } from './dfns.js'\nexport { DfnsHandler } from './dfns.js'\n\nexport interface DfnsConfig {\n orgId: string\n baseUrl: string\n credentials: DfnsCredentials\n}\n\nconst DfnsCredentialsSchema = z.object({\n credId: z.string().min(1),\n privateKey: z.string().min(1),\n authToken: z.string().min(1),\n})\n\nconst DfnsConfigSchema = z.object({\n orgId: z.string().min(1),\n baseUrl: z.string().url(),\n credentials: DfnsCredentialsSchema,\n})\n\nconst createDfnsHandler = (config: DfnsConfig): DfnsHandler =>\n new DfnsHandler(config.orgId, config.baseUrl, config.credentials)\n\nfunction toTransaction(sig: DfnsSignature, publicKey?: string): Transaction {\n const tx: Transaction = {\n txId: sig.id,\n status: sig.status,\n }\n if (sig.signature) tx.signature = sig.signature\n if (publicKey) tx.publicKey = publicKey\n return tx\n}\n\nexport default class DfnsSigningDriver implements SigningDriverInterface {\n private dfns: DfnsHandler\n private config: DfnsConfig\n\n constructor(config: DfnsConfig) {\n this.config = config\n this.dfns = createDfnsHandler(config)\n }\n\n public partyMode = PartyMode.EXTERNAL\n public signingProvider = SigningProvider.DFNS\n\n private async resolveKeyId(keyIdentifier: {\n id?: string\n publicKey?: string\n }): Promise<string | undefined> {\n if (keyIdentifier.id) return keyIdentifier.id\n if (!keyIdentifier.publicKey) return undefined\n\n const key = await this.dfns.findKeyByPublicKey(keyIdentifier.publicKey)\n return key?.id\n }\n\n public controller = (\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _userId: AuthContext['userId'] | undefined\n ) =>\n buildController({\n signTransaction: async (\n params: SignTransactionParams\n ): Promise<SignTransactionResult> => {\n try {\n const keyId = await this.resolveKeyId(params.keyIdentifier)\n if (!keyId) {\n return {\n error: 'key_not_found',\n error_description:\n 'No Dfns key found for the provided key identifier.',\n }\n }\n\n if (!params.txHash) {\n return {\n error: 'bad_arguments',\n error_description:\n 'txHash is required to sign with Dfns.',\n }\n }\n\n const sig = await this.dfns.signHash(keyId, params.txHash)\n\n return toTransaction(sig, params.keyIdentifier.publicKey)\n } catch (error) {\n return {\n error: 'signing_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n getTransaction: async (\n params: GetTransactionParams\n ): Promise<GetTransactionResult> => {\n try {\n const sig = await this.dfns.findSignature(params.txId)\n if (!sig) {\n return {\n error: 'transaction_not_found',\n error_description:\n 'The requested signature does not exist.',\n }\n }\n const key = await this.dfns.getKey(sig.keyId)\n return toTransaction(sig, key?.publicKey)\n } catch (error) {\n return {\n error: 'fetch_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n getTransactions: async (\n params: GetTransactionsParams\n ): Promise<GetTransactionsResult> => {\n if (!params.publicKeys && !params.txIds) {\n return {\n error: 'bad_arguments',\n error_description:\n 'Either publicKeys or txIds must be provided.',\n }\n }\n\n try {\n const txIds = new Set(params.txIds || [])\n const publicKeys = new Set(params.publicKeys || [])\n const transactions: Transaction[] = []\n\n for await (const key of this.dfns.iterateKeys()) {\n if (\n params.publicKeys &&\n !publicKeys.has(key.publicKey)\n ) {\n continue\n }\n\n for await (const sig of this.dfns.listSignatures(\n key.id\n )) {\n if (params.txIds && !txIds.has(sig.id)) continue\n transactions.push(toTransaction(sig, key.publicKey))\n\n if (\n params.txIds &&\n !params.publicKeys &&\n transactions.length === txIds.size\n ) {\n return { transactions }\n }\n }\n }\n\n return { transactions }\n } catch (error) {\n return {\n error: 'fetch_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n getKeys: async (): Promise<GetKeysResult> => {\n try {\n const keys = await this.dfns.listKeys()\n return {\n keys: keys.map((k) => ({\n id: k.id,\n name: k.name,\n publicKey: k.publicKey,\n })),\n }\n } catch (error) {\n return {\n error: 'fetch_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n createKey: async (\n params: CreateKeyParams\n ): Promise<CreateKeyResult> => {\n try {\n const key = await this.dfns.createKey(params.name)\n return {\n id: key.id,\n name: key.name,\n publicKey: key.publicKey,\n }\n } catch (error) {\n return {\n error: 'creation_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n getConfiguration: async (): Promise<GetConfigurationResult> => ({\n orgId: this.config.orgId,\n baseUrl: this.config.baseUrl,\n credentials: this.config.credentials,\n }),\n\n setConfiguration: async (\n params: SetConfigurationParams\n ): Promise<SetConfigurationResult> => {\n const validated = DfnsConfigSchema.safeParse(params)\n if (!validated.success) {\n return {\n error: 'bad_arguments',\n error_description: validated.error.message,\n }\n }\n\n const newConfig: DfnsConfig = {\n orgId: validated.data.orgId,\n baseUrl: validated.data.baseUrl,\n credentials: validated.data.credentials,\n }\n\n if (!_.isEqual(newConfig, this.config)) {\n this.config = newConfig\n this.dfns = createDfnsHandler(this.config)\n }\n\n return params\n },\n\n subscribeTransactions: async (\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _params: SubscribeTransactionsParams\n ): Promise<SubscribeTransactionsResult> => {\n return Promise.resolve({} as SubscribeTransactionsResult)\n },\n })\n}\n"]}
@@ -0,0 +1,29 @@
1
+ import { PartyMode, SigningDriverInterface, SigningProvider } from '@canton-network/core-signing-lib';
2
+ import { DfnsCredentials } from './dfns.js';
3
+ import { AuthContext } from '@canton-network/core-wallet-auth';
4
+ export type { DfnsCredentials, DfnsKey, DfnsSignature } from './dfns.js';
5
+ export { DfnsHandler } from './dfns.js';
6
+ export interface DfnsConfig {
7
+ orgId: string;
8
+ baseUrl: string;
9
+ credentials: DfnsCredentials;
10
+ }
11
+ export default class DfnsSigningDriver implements SigningDriverInterface {
12
+ private dfns;
13
+ private config;
14
+ constructor(config: DfnsConfig);
15
+ partyMode: PartyMode;
16
+ signingProvider: SigningProvider;
17
+ private resolveKeyId;
18
+ controller: (_userId: AuthContext["userId"] | undefined) => {
19
+ signTransaction: import("@canton-network/core-signing-lib").SignTransaction;
20
+ getTransaction: import("@canton-network/core-signing-lib").GetTransaction;
21
+ getTransactions: import("@canton-network/core-signing-lib").GetTransactions;
22
+ getKeys: import("@canton-network/core-signing-lib").GetKeys;
23
+ createKey: import("@canton-network/core-signing-lib").CreateKey;
24
+ getConfiguration: import("@canton-network/core-signing-lib").GetConfiguration;
25
+ setConfiguration: import("@canton-network/core-signing-lib").SetConfiguration;
26
+ subscribeTransactions: import("@canton-network/core-signing-lib").SubscribeTransactions;
27
+ };
28
+ }
29
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAEH,SAAS,EACT,sBAAsB,EACtB,eAAe,EAClB,MAAM,kCAAkC,CAAA;AAmBzC,OAAO,EAAe,eAAe,EAAiB,MAAM,WAAW,CAAA;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAA;AAI9D,YAAY,EAAE,eAAe,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC,MAAM,WAAW,UAAU;IACvB,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,EAAE,eAAe,CAAA;CAC/B;AA2BD,MAAM,CAAC,OAAO,OAAO,iBAAkB,YAAW,sBAAsB;IACpE,OAAO,CAAC,IAAI,CAAa;IACzB,OAAO,CAAC,MAAM,CAAY;gBAEd,MAAM,EAAE,UAAU;IAKvB,SAAS,YAAqB;IAC9B,eAAe,kBAAuB;YAE/B,YAAY;IAWnB,UAAU,GAEb,SAAS,WAAW,CAAC,QAAQ,CAAC,GAAG,SAAS;;;;;;;;;MAmLxC;CACT"}
package/dist/index.js ADDED
@@ -0,0 +1,412 @@
1
+ import { PartyMode, SigningProvider, buildController } from '@canton-network/core-signing-lib';
2
+ import { DfnsApiClient } from '@dfns/sdk';
3
+ import { AsymmetricKeySigner } from '@dfns/sdk-keysigner';
4
+ import { pino } from 'pino';
5
+ import _ from 'lodash';
6
+ import { z } from 'zod';
7
+
8
+ var __defProp = Object.defineProperty;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
11
+ var logger = pino({ name: "dfns-handler", level: "debug" });
12
+ var DFNS_LIST_PAGE_SIZE = 50;
13
+ function hexToBase64(hex) {
14
+ return Buffer.from(hex, "hex").toString("base64");
15
+ }
16
+ function base64ToHex(base64) {
17
+ return Buffer.from(base64, "base64").toString("hex");
18
+ }
19
+ function isCantonKey(scheme, curve) {
20
+ return scheme === "EdDSA" && curve === "ed25519";
21
+ }
22
+ var DfnsHandler = class {
23
+ constructor(orgId, baseUrl, credentials) {
24
+ __publicField(this, "client");
25
+ __publicField(this, "orgId");
26
+ __publicField(this, "baseUrl");
27
+ this.orgId = orgId;
28
+ this.baseUrl = baseUrl;
29
+ this.client = this.createClient(credentials);
30
+ }
31
+ createClient(credentials) {
32
+ const signer = new AsymmetricKeySigner({
33
+ credId: credentials.credId,
34
+ privateKey: credentials.privateKey
35
+ });
36
+ return new DfnsApiClient({
37
+ orgId: this.orgId,
38
+ authToken: credentials.authToken,
39
+ baseUrl: this.baseUrl,
40
+ signer
41
+ });
42
+ }
43
+ /**
44
+ * Create a raw ed25519 key in Dfns suitable for signing Canton topology
45
+ * and ledger transactions. The key is not bound to a network — chain
46
+ * activation happens on the gateway against its configured validator.
47
+ */
48
+ async createKey(name) {
49
+ try {
50
+ const key = await this.client.keys.createKey({
51
+ body: {
52
+ scheme: "EdDSA",
53
+ curve: "ed25519",
54
+ name
55
+ }
56
+ });
57
+ return {
58
+ id: key.id,
59
+ name: key.name || key.id,
60
+ publicKey: hexToBase64(key.publicKey)
61
+ };
62
+ } catch (error) {
63
+ logger.error(error, "Error creating Dfns key");
64
+ throw error;
65
+ }
66
+ }
67
+ async *iterateKeys() {
68
+ let paginationToken;
69
+ do {
70
+ const response = await this.client.keys.listKeys({
71
+ query: {
72
+ limit: DFNS_LIST_PAGE_SIZE,
73
+ ...paginationToken ? { paginationToken } : {}
74
+ }
75
+ });
76
+ for (const key of response.items) {
77
+ if (key.status !== "Active" || !isCantonKey(key.scheme, key.curve)) {
78
+ continue;
79
+ }
80
+ yield {
81
+ id: key.id,
82
+ name: key.name || key.id,
83
+ publicKey: hexToBase64(key.publicKey)
84
+ };
85
+ }
86
+ paginationToken = response.nextPageToken;
87
+ } while (paginationToken);
88
+ }
89
+ async listKeys() {
90
+ const keys = [];
91
+ try {
92
+ for await (const key of this.iterateKeys()) {
93
+ keys.push(key);
94
+ }
95
+ } catch (error) {
96
+ logger.error(error, "Error listing Dfns keys");
97
+ throw error;
98
+ }
99
+ return keys;
100
+ }
101
+ async getKey(keyId) {
102
+ try {
103
+ const key = await this.client.keys.getKey({ keyId });
104
+ if (key.status !== "Active" || !isCantonKey(key.scheme, key.curve)) {
105
+ return void 0;
106
+ }
107
+ return {
108
+ id: key.id,
109
+ name: key.name || key.id,
110
+ publicKey: hexToBase64(key.publicKey)
111
+ };
112
+ } catch (error) {
113
+ logger.debug(error, `Key ${keyId} not found`);
114
+ return void 0;
115
+ }
116
+ }
117
+ /**
118
+ * Resolve a key by base64 ed25519 public key. Iterates Dfns keys —
119
+ * acceptable for first iteration since most deployments hold a single
120
+ * Canton key per credential.
121
+ */
122
+ async findKeyByPublicKey(publicKeyBase64) {
123
+ for await (const key of this.iterateKeys()) {
124
+ if (key.publicKey === publicKeyBase64) {
125
+ return key;
126
+ }
127
+ }
128
+ return void 0;
129
+ }
130
+ /**
131
+ * Submit a hash signing request to Dfns. Returns immediately with the
132
+ * signature id and current status; signature bytes are fetched via
133
+ * {@link getSignature} once the request reaches `signed` status.
134
+ *
135
+ * The hash is reused as the Dfns idempotency key — re-signing the same
136
+ * hash returns the existing signature rather than producing a duplicate,
137
+ * which is safe because Canton's command deduplication handles repeats
138
+ * at the ledger level.
139
+ *
140
+ * @param keyId Dfns key id resolved from the gateway's key identifier.
141
+ * @param hashBase64 32-byte hash, base64-encoded (Canton TxHash format).
142
+ */
143
+ async signHash(keyId, hashBase64) {
144
+ try {
145
+ const result = await this.client.keys.generateSignature({
146
+ keyId,
147
+ body: {
148
+ kind: "Hash",
149
+ hash: base64ToHex(hashBase64),
150
+ blockchainKind: "Canton",
151
+ externalId: base64ToHex(hashBase64)
152
+ }
153
+ });
154
+ return {
155
+ id: result.id,
156
+ keyId,
157
+ status: this.mapStatus(result.status),
158
+ signature: this.extractSignature(result.signature)
159
+ };
160
+ } catch (error) {
161
+ logger.error(error, "Error signing hash with Dfns");
162
+ throw error;
163
+ }
164
+ }
165
+ async getSignature(keyId, signatureId) {
166
+ try {
167
+ const result = await this.client.keys.getSignature({
168
+ keyId,
169
+ signatureId
170
+ });
171
+ return {
172
+ id: result.id,
173
+ keyId,
174
+ status: this.mapStatus(result.status),
175
+ signature: this.extractSignature(result.signature)
176
+ };
177
+ } catch (error) {
178
+ logger.debug(error, `Signature ${signatureId} not found`);
179
+ return void 0;
180
+ }
181
+ }
182
+ /**
183
+ * Locate a signature across all Canton keys. Used when the gateway
184
+ * polls by signature id without knowing the originating key id.
185
+ */
186
+ async findSignature(signatureId) {
187
+ for await (const key of this.iterateKeys()) {
188
+ const sig = await this.getSignature(key.id, signatureId);
189
+ if (sig) return sig;
190
+ }
191
+ return void 0;
192
+ }
193
+ async *listSignatures(keyId) {
194
+ let paginationToken;
195
+ do {
196
+ const response = await this.client.keys.listSignatures({
197
+ keyId,
198
+ query: {
199
+ limit: DFNS_LIST_PAGE_SIZE,
200
+ ...paginationToken ? { paginationToken } : {}
201
+ }
202
+ });
203
+ for (const sig of response.items) {
204
+ yield {
205
+ id: sig.id,
206
+ keyId,
207
+ status: this.mapStatus(sig.status),
208
+ signature: this.extractSignature(sig.signature)
209
+ };
210
+ }
211
+ paginationToken = response.nextPageToken;
212
+ } while (paginationToken);
213
+ }
214
+ extractSignature(signature) {
215
+ if (!signature) return void 0;
216
+ const hex = signature.encoded ?? `${signature.r}${signature.s}`;
217
+ return hexToBase64(hex);
218
+ }
219
+ mapStatus(dfnsStatus) {
220
+ switch (dfnsStatus) {
221
+ case "Signed":
222
+ case "Confirmed":
223
+ return "signed";
224
+ case "Pending":
225
+ case "Executing":
226
+ return "pending";
227
+ case "Rejected":
228
+ return "rejected";
229
+ case "Failed":
230
+ return "failed";
231
+ default:
232
+ logger.warn(`Unknown Dfns signature status: ${dfnsStatus}`);
233
+ return "pending";
234
+ }
235
+ }
236
+ };
237
+ var DfnsCredentialsSchema = z.object({
238
+ credId: z.string().min(1),
239
+ privateKey: z.string().min(1),
240
+ authToken: z.string().min(1)
241
+ });
242
+ var DfnsConfigSchema = z.object({
243
+ orgId: z.string().min(1),
244
+ baseUrl: z.string().url(),
245
+ credentials: DfnsCredentialsSchema
246
+ });
247
+ var createDfnsHandler = (config) => new DfnsHandler(config.orgId, config.baseUrl, config.credentials);
248
+ function toTransaction(sig, publicKey) {
249
+ const tx = {
250
+ txId: sig.id,
251
+ status: sig.status
252
+ };
253
+ if (sig.signature) tx.signature = sig.signature;
254
+ if (publicKey) tx.publicKey = publicKey;
255
+ return tx;
256
+ }
257
+ var DfnsSigningDriver = class {
258
+ constructor(config) {
259
+ __publicField(this, "dfns");
260
+ __publicField(this, "config");
261
+ __publicField(this, "partyMode", PartyMode.EXTERNAL);
262
+ __publicField(this, "signingProvider", SigningProvider.DFNS);
263
+ __publicField(this, "controller", (_userId) => buildController({
264
+ signTransaction: async (params) => {
265
+ try {
266
+ const keyId = await this.resolveKeyId(params.keyIdentifier);
267
+ if (!keyId) {
268
+ return {
269
+ error: "key_not_found",
270
+ error_description: "No Dfns key found for the provided key identifier."
271
+ };
272
+ }
273
+ if (!params.txHash) {
274
+ return {
275
+ error: "bad_arguments",
276
+ error_description: "txHash is required to sign with Dfns."
277
+ };
278
+ }
279
+ const sig = await this.dfns.signHash(keyId, params.txHash);
280
+ return toTransaction(sig, params.keyIdentifier.publicKey);
281
+ } catch (error) {
282
+ return {
283
+ error: "signing_error",
284
+ error_description: error.message
285
+ };
286
+ }
287
+ },
288
+ getTransaction: async (params) => {
289
+ try {
290
+ const sig = await this.dfns.findSignature(params.txId);
291
+ if (!sig) {
292
+ return {
293
+ error: "transaction_not_found",
294
+ error_description: "The requested signature does not exist."
295
+ };
296
+ }
297
+ const key = await this.dfns.getKey(sig.keyId);
298
+ return toTransaction(sig, key?.publicKey);
299
+ } catch (error) {
300
+ return {
301
+ error: "fetch_error",
302
+ error_description: error.message
303
+ };
304
+ }
305
+ },
306
+ getTransactions: async (params) => {
307
+ if (!params.publicKeys && !params.txIds) {
308
+ return {
309
+ error: "bad_arguments",
310
+ error_description: "Either publicKeys or txIds must be provided."
311
+ };
312
+ }
313
+ try {
314
+ const txIds = new Set(params.txIds || []);
315
+ const publicKeys = new Set(params.publicKeys || []);
316
+ const transactions = [];
317
+ for await (const key of this.dfns.iterateKeys()) {
318
+ if (params.publicKeys && !publicKeys.has(key.publicKey)) {
319
+ continue;
320
+ }
321
+ for await (const sig of this.dfns.listSignatures(
322
+ key.id
323
+ )) {
324
+ if (params.txIds && !txIds.has(sig.id)) continue;
325
+ transactions.push(toTransaction(sig, key.publicKey));
326
+ if (params.txIds && !params.publicKeys && transactions.length === txIds.size) {
327
+ return { transactions };
328
+ }
329
+ }
330
+ }
331
+ return { transactions };
332
+ } catch (error) {
333
+ return {
334
+ error: "fetch_error",
335
+ error_description: error.message
336
+ };
337
+ }
338
+ },
339
+ getKeys: async () => {
340
+ try {
341
+ const keys = await this.dfns.listKeys();
342
+ return {
343
+ keys: keys.map((k) => ({
344
+ id: k.id,
345
+ name: k.name,
346
+ publicKey: k.publicKey
347
+ }))
348
+ };
349
+ } catch (error) {
350
+ return {
351
+ error: "fetch_error",
352
+ error_description: error.message
353
+ };
354
+ }
355
+ },
356
+ createKey: async (params) => {
357
+ try {
358
+ const key = await this.dfns.createKey(params.name);
359
+ return {
360
+ id: key.id,
361
+ name: key.name,
362
+ publicKey: key.publicKey
363
+ };
364
+ } catch (error) {
365
+ return {
366
+ error: "creation_error",
367
+ error_description: error.message
368
+ };
369
+ }
370
+ },
371
+ getConfiguration: async () => ({
372
+ orgId: this.config.orgId,
373
+ baseUrl: this.config.baseUrl,
374
+ credentials: this.config.credentials
375
+ }),
376
+ setConfiguration: async (params) => {
377
+ const validated = DfnsConfigSchema.safeParse(params);
378
+ if (!validated.success) {
379
+ return {
380
+ error: "bad_arguments",
381
+ error_description: validated.error.message
382
+ };
383
+ }
384
+ const newConfig = {
385
+ orgId: validated.data.orgId,
386
+ baseUrl: validated.data.baseUrl,
387
+ credentials: validated.data.credentials
388
+ };
389
+ if (!_.isEqual(newConfig, this.config)) {
390
+ this.config = newConfig;
391
+ this.dfns = createDfnsHandler(this.config);
392
+ }
393
+ return params;
394
+ },
395
+ subscribeTransactions: async (_params) => {
396
+ return Promise.resolve({});
397
+ }
398
+ }));
399
+ this.config = config;
400
+ this.dfns = createDfnsHandler(config);
401
+ }
402
+ async resolveKeyId(keyIdentifier) {
403
+ if (keyIdentifier.id) return keyIdentifier.id;
404
+ if (!keyIdentifier.publicKey) return void 0;
405
+ const key = await this.dfns.findKeyByPublicKey(keyIdentifier.publicKey);
406
+ return key?.id;
407
+ }
408
+ };
409
+
410
+ export { DfnsHandler, DfnsSigningDriver as default };
411
+ //# sourceMappingURL=index.js.map
412
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/dfns.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;AAQA,IAAM,SAAS,IAAA,CAAK,EAAE,MAAM,cAAA,EAAgB,KAAA,EAAO,SAAS,CAAA;AAE5D,IAAM,mBAAA,G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,IAAA,CAAK,IAAA,GAAO,iBAAA,CAAkB,IAAA,CAAK,MAAM,CAAA;AAAA,QAC7C;AAEA,QAAA,OAAO,MAAA;AAAA,MACX,CAAA;AAAA,MAEA,qBAAA,EAAuB,OAEnB,OAAA,KACuC;AACvC,QAAA,OAAO,OAAA,CAAQ,OAAA,CAAQ,EAAiC,CAAA;AAAA,MAC5D;AAAA,KACH,CAAA,CAAA;AAvMD,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAkB,MAAM,CAAA;AAAA,EACxC;AAAA,EAKA,MAAc,aAAa,aAAA,EAGK;AAC5B,IAAA,IAAI,aAAA,CAAc,EAAA,EAAI,OAAO,aAAA,CAAc,EAAA;AAC3C,IAAA,IAAI,CAAC,aAAA,CAAc,SAAA,EAAW,OAAO,MAAA;AAErC,IAAA,MAAM,MAAM,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAA,CAAmB,cAAc,SAAS,CAAA;AACtE,IAAA,OAAO,GAAA,EAAK,EAAA;AAAA,EAChB;AAwLJ","file":"index.js","sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { DfnsApiClient } from '@dfns/sdk'\nimport { AsymmetricKeySigner } from '@dfns/sdk-keysigner'\nimport { SigningStatus } from '@canton-network/core-signing-lib'\nimport { pino } from 'pino'\n\nconst logger = pino({ name: 'dfns-handler', level: 'debug' })\n\nconst DFNS_LIST_PAGE_SIZE = 50\n\n/**\n * Credentials for a Dfns service account. Dfns uses two-layer auth: a\n * long-lived bearer token plus per-request signing with a private key.\n */\nexport interface DfnsCredentials {\n /** ID of the Dfns credential (key) registered against the service account. */\n credId: string\n /**\n * PEM-encoded private key paired with `credId`. Used to sign every\n * sensitive Dfns API request as a U2F-style second factor. Configured\n * once per deployment; not derived from `authToken`.\n */\n privateKey: string\n /**\n * Long-lived service account bearer JWT issued by the Dfns dashboard.\n * Does not auto-expire and is not regenerated from `privateKey`/`credId`.\n * Rotate by issuing a new token in the Dfns dashboard.\n */\n authToken: string\n}\n\nexport interface DfnsKey {\n /** Dfns key id (e.g. `key-...`). */\n id: string\n /** Human-readable name configured on the Dfns key. */\n name: string\n /** ed25519 public key, base64-encoded (Canton format). */\n publicKey: string\n}\n\nexport interface DfnsSignature {\n /** Dfns signature id (used as the txId returned to the gateway). */\n id: string\n /** Dfns key id the signature was produced with. */\n keyId: string\n status: SigningStatus\n /** ed25519 signature, base64-encoded (Canton SIGNATURE_FORMAT_CONCAT). */\n signature?: string\n}\n\nfunction hexToBase64(hex: string): string {\n return Buffer.from(hex, 'hex').toString('base64')\n}\n\nfunction base64ToHex(base64: string): string {\n return Buffer.from(base64, 'base64').toString('hex')\n}\n\nfunction isCantonKey(scheme: string, curve: string): boolean {\n return scheme === 'EdDSA' && curve === 'ed25519'\n}\n\nexport class DfnsHandler {\n private client: DfnsApiClient\n private orgId: string\n private baseUrl: string\n\n constructor(orgId: string, baseUrl: string, credentials: DfnsCredentials) {\n this.orgId = orgId\n this.baseUrl = baseUrl\n this.client = this.createClient(credentials)\n }\n\n private createClient(credentials: DfnsCredentials): DfnsApiClient {\n const signer = new AsymmetricKeySigner({\n credId: credentials.credId,\n privateKey: credentials.privateKey,\n })\n\n return new DfnsApiClient({\n orgId: this.orgId,\n authToken: credentials.authToken,\n baseUrl: this.baseUrl,\n signer,\n })\n }\n\n /**\n * Create a raw ed25519 key in Dfns suitable for signing Canton topology\n * and ledger transactions. The key is not bound to a network — chain\n * activation happens on the gateway against its configured validator.\n */\n public async createKey(name: string): Promise<DfnsKey> {\n try {\n const key = await this.client.keys.createKey({\n body: {\n scheme: 'EdDSA',\n curve: 'ed25519',\n name,\n },\n })\n return {\n id: key.id,\n name: key.name || key.id,\n publicKey: hexToBase64(key.publicKey),\n }\n } catch (error) {\n logger.error(error, 'Error creating Dfns key')\n throw error\n }\n }\n\n public async *iterateKeys(): AsyncGenerator<DfnsKey> {\n let paginationToken: string | undefined\n do {\n const response = await this.client.keys.listKeys({\n query: {\n limit: DFNS_LIST_PAGE_SIZE,\n ...(paginationToken ? { paginationToken } : {}),\n },\n })\n\n for (const key of response.items) {\n if (\n key.status !== 'Active' ||\n !isCantonKey(key.scheme, key.curve)\n ) {\n continue\n }\n yield {\n id: key.id,\n name: key.name || key.id,\n publicKey: hexToBase64(key.publicKey),\n }\n }\n\n paginationToken = response.nextPageToken\n } while (paginationToken)\n }\n\n public async listKeys(): Promise<DfnsKey[]> {\n const keys: DfnsKey[] = []\n try {\n for await (const key of this.iterateKeys()) {\n keys.push(key)\n }\n } catch (error) {\n logger.error(error, 'Error listing Dfns keys')\n throw error\n }\n return keys\n }\n\n public async getKey(keyId: string): Promise<DfnsKey | undefined> {\n try {\n const key = await this.client.keys.getKey({ keyId })\n if (\n key.status !== 'Active' ||\n !isCantonKey(key.scheme, key.curve)\n ) {\n return undefined\n }\n return {\n id: key.id,\n name: key.name || key.id,\n publicKey: hexToBase64(key.publicKey),\n }\n } catch (error) {\n logger.debug(error, `Key ${keyId} not found`)\n return undefined\n }\n }\n\n /**\n * Resolve a key by base64 ed25519 public key. Iterates Dfns keys —\n * acceptable for first iteration since most deployments hold a single\n * Canton key per credential.\n */\n public async findKeyByPublicKey(\n publicKeyBase64: string\n ): Promise<DfnsKey | undefined> {\n for await (const key of this.iterateKeys()) {\n if (key.publicKey === publicKeyBase64) {\n return key\n }\n }\n return undefined\n }\n\n /**\n * Submit a hash signing request to Dfns. Returns immediately with the\n * signature id and current status; signature bytes are fetched via\n * {@link getSignature} once the request reaches `signed` status.\n *\n * The hash is reused as the Dfns idempotency key — re-signing the same\n * hash returns the existing signature rather than producing a duplicate,\n * which is safe because Canton's command deduplication handles repeats\n * at the ledger level.\n *\n * @param keyId Dfns key id resolved from the gateway's key identifier.\n * @param hashBase64 32-byte hash, base64-encoded (Canton TxHash format).\n */\n public async signHash(\n keyId: string,\n hashBase64: string\n ): Promise<DfnsSignature> {\n try {\n const result = await this.client.keys.generateSignature({\n keyId,\n body: {\n kind: 'Hash',\n hash: base64ToHex(hashBase64),\n blockchainKind: 'Canton',\n externalId: base64ToHex(hashBase64),\n },\n })\n return {\n id: result.id,\n keyId,\n status: this.mapStatus(result.status),\n signature: this.extractSignature(result.signature),\n }\n } catch (error) {\n logger.error(error, 'Error signing hash with Dfns')\n throw error\n }\n }\n\n public async getSignature(\n keyId: string,\n signatureId: string\n ): Promise<DfnsSignature | undefined> {\n try {\n const result = await this.client.keys.getSignature({\n keyId,\n signatureId,\n })\n return {\n id: result.id,\n keyId,\n status: this.mapStatus(result.status),\n signature: this.extractSignature(result.signature),\n }\n } catch (error) {\n logger.debug(error, `Signature ${signatureId} not found`)\n return undefined\n }\n }\n\n /**\n * Locate a signature across all Canton keys. Used when the gateway\n * polls by signature id without knowing the originating key id.\n */\n public async findSignature(\n signatureId: string\n ): Promise<DfnsSignature | undefined> {\n for await (const key of this.iterateKeys()) {\n const sig = await this.getSignature(key.id, signatureId)\n if (sig) return sig\n }\n return undefined\n }\n\n public async *listSignatures(keyId: string): AsyncGenerator<DfnsSignature> {\n let paginationToken: string | undefined\n do {\n const response = await this.client.keys.listSignatures({\n keyId,\n query: {\n limit: DFNS_LIST_PAGE_SIZE,\n ...(paginationToken ? { paginationToken } : {}),\n },\n })\n\n for (const sig of response.items) {\n yield {\n id: sig.id,\n keyId,\n status: this.mapStatus(sig.status),\n signature: this.extractSignature(sig.signature),\n }\n }\n\n paginationToken = response.nextPageToken\n } while (paginationToken)\n }\n\n private extractSignature(signature?: {\n encoded?: string\n r: string\n s: string\n }): string | undefined {\n if (!signature) return undefined\n // For ed25519, `encoded` is the 64-byte r||s concat in hex; fall back\n // to assembling it from r/s if `encoded` is not populated.\n const hex = signature.encoded ?? `${signature.r}${signature.s}`\n return hexToBase64(hex)\n }\n\n private mapStatus(dfnsStatus: string): SigningStatus {\n switch (dfnsStatus) {\n case 'Signed':\n case 'Confirmed':\n return 'signed'\n case 'Pending':\n case 'Executing':\n return 'pending'\n case 'Rejected':\n return 'rejected'\n case 'Failed':\n return 'failed'\n default:\n logger.warn(`Unknown Dfns signature status: ${dfnsStatus}`)\n return 'pending'\n }\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n buildController,\n PartyMode,\n SigningDriverInterface,\n SigningProvider,\n} from '@canton-network/core-signing-lib'\n\nimport {\n SignTransactionParams,\n SignTransactionResult,\n GetTransactionParams,\n GetTransactionResult,\n GetTransactionsResult,\n GetTransactionsParams,\n GetKeysResult,\n CreateKeyParams,\n CreateKeyResult,\n GetConfigurationResult,\n SetConfigurationParams,\n SubscribeTransactionsParams,\n SubscribeTransactionsResult,\n SetConfigurationResult,\n Transaction,\n} from '@canton-network/core-signing-lib'\nimport { DfnsHandler, DfnsCredentials, DfnsSignature } from './dfns.js'\nimport { AuthContext } from '@canton-network/core-wallet-auth'\nimport _ from 'lodash'\nimport { z } from 'zod'\n\nexport type { DfnsCredentials, DfnsKey, DfnsSignature } from './dfns.js'\nexport { DfnsHandler } from './dfns.js'\n\nexport interface DfnsConfig {\n orgId: string\n baseUrl: string\n credentials: DfnsCredentials\n}\n\nconst DfnsCredentialsSchema = z.object({\n credId: z.string().min(1),\n privateKey: z.string().min(1),\n authToken: z.string().min(1),\n})\n\nconst DfnsConfigSchema = z.object({\n orgId: z.string().min(1),\n baseUrl: z.string().url(),\n credentials: DfnsCredentialsSchema,\n})\n\nconst createDfnsHandler = (config: DfnsConfig): DfnsHandler =>\n new DfnsHandler(config.orgId, config.baseUrl, config.credentials)\n\nfunction toTransaction(sig: DfnsSignature, publicKey?: string): Transaction {\n const tx: Transaction = {\n txId: sig.id,\n status: sig.status,\n }\n if (sig.signature) tx.signature = sig.signature\n if (publicKey) tx.publicKey = publicKey\n return tx\n}\n\nexport default class DfnsSigningDriver implements SigningDriverInterface {\n private dfns: DfnsHandler\n private config: DfnsConfig\n\n constructor(config: DfnsConfig) {\n this.config = config\n this.dfns = createDfnsHandler(config)\n }\n\n public partyMode = PartyMode.EXTERNAL\n public signingProvider = SigningProvider.DFNS\n\n private async resolveKeyId(keyIdentifier: {\n id?: string\n publicKey?: string\n }): Promise<string | undefined> {\n if (keyIdentifier.id) return keyIdentifier.id\n if (!keyIdentifier.publicKey) return undefined\n\n const key = await this.dfns.findKeyByPublicKey(keyIdentifier.publicKey)\n return key?.id\n }\n\n public controller = (\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _userId: AuthContext['userId'] | undefined\n ) =>\n buildController({\n signTransaction: async (\n params: SignTransactionParams\n ): Promise<SignTransactionResult> => {\n try {\n const keyId = await this.resolveKeyId(params.keyIdentifier)\n if (!keyId) {\n return {\n error: 'key_not_found',\n error_description:\n 'No Dfns key found for the provided key identifier.',\n }\n }\n\n if (!params.txHash) {\n return {\n error: 'bad_arguments',\n error_description:\n 'txHash is required to sign with Dfns.',\n }\n }\n\n const sig = await this.dfns.signHash(keyId, params.txHash)\n\n return toTransaction(sig, params.keyIdentifier.publicKey)\n } catch (error) {\n return {\n error: 'signing_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n getTransaction: async (\n params: GetTransactionParams\n ): Promise<GetTransactionResult> => {\n try {\n const sig = await this.dfns.findSignature(params.txId)\n if (!sig) {\n return {\n error: 'transaction_not_found',\n error_description:\n 'The requested signature does not exist.',\n }\n }\n const key = await this.dfns.getKey(sig.keyId)\n return toTransaction(sig, key?.publicKey)\n } catch (error) {\n return {\n error: 'fetch_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n getTransactions: async (\n params: GetTransactionsParams\n ): Promise<GetTransactionsResult> => {\n if (!params.publicKeys && !params.txIds) {\n return {\n error: 'bad_arguments',\n error_description:\n 'Either publicKeys or txIds must be provided.',\n }\n }\n\n try {\n const txIds = new Set(params.txIds || [])\n const publicKeys = new Set(params.publicKeys || [])\n const transactions: Transaction[] = []\n\n for await (const key of this.dfns.iterateKeys()) {\n if (\n params.publicKeys &&\n !publicKeys.has(key.publicKey)\n ) {\n continue\n }\n\n for await (const sig of this.dfns.listSignatures(\n key.id\n )) {\n if (params.txIds && !txIds.has(sig.id)) continue\n transactions.push(toTransaction(sig, key.publicKey))\n\n if (\n params.txIds &&\n !params.publicKeys &&\n transactions.length === txIds.size\n ) {\n return { transactions }\n }\n }\n }\n\n return { transactions }\n } catch (error) {\n return {\n error: 'fetch_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n getKeys: async (): Promise<GetKeysResult> => {\n try {\n const keys = await this.dfns.listKeys()\n return {\n keys: keys.map((k) => ({\n id: k.id,\n name: k.name,\n publicKey: k.publicKey,\n })),\n }\n } catch (error) {\n return {\n error: 'fetch_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n createKey: async (\n params: CreateKeyParams\n ): Promise<CreateKeyResult> => {\n try {\n const key = await this.dfns.createKey(params.name)\n return {\n id: key.id,\n name: key.name,\n publicKey: key.publicKey,\n }\n } catch (error) {\n return {\n error: 'creation_error',\n error_description: (error as Error).message,\n }\n }\n },\n\n getConfiguration: async (): Promise<GetConfigurationResult> => ({\n orgId: this.config.orgId,\n baseUrl: this.config.baseUrl,\n credentials: this.config.credentials,\n }),\n\n setConfiguration: async (\n params: SetConfigurationParams\n ): Promise<SetConfigurationResult> => {\n const validated = DfnsConfigSchema.safeParse(params)\n if (!validated.success) {\n return {\n error: 'bad_arguments',\n error_description: validated.error.message,\n }\n }\n\n const newConfig: DfnsConfig = {\n orgId: validated.data.orgId,\n baseUrl: validated.data.baseUrl,\n credentials: validated.data.credentials,\n }\n\n if (!_.isEqual(newConfig, this.config)) {\n this.config = newConfig\n this.dfns = createDfnsHandler(this.config)\n }\n\n return params\n },\n\n subscribeTransactions: async (\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _params: SubscribeTransactionsParams\n ): Promise<SubscribeTransactionsResult> => {\n return Promise.resolve({} as SubscribeTransactionsResult)\n },\n })\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@canton-network/core-signing-dfns",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Dfns signing driver for Canton Network Wallet Gateway",
6
+ "license": "Apache-2.0",
7
+ "packageManager": "yarn@4.9.4",
8
+ "main": "dist/index.cjs",
9
+ "module": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.cjs",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "scripts": {
20
+ "build": "tsup && tsc -p tsconfig.types.json",
21
+ "dev": "tsup --watch --onSuccess \"tsc -p tsconfig.types.json\"",
22
+ "clean": "tsc -b --clean; rm -rf dist",
23
+ "flatpack": "yarn pack --out \"$FLATPACK_OUTDIR\"",
24
+ "test": "jest"
25
+ },
26
+ "dependencies": {
27
+ "@canton-network/core-signing-lib": "^1.2.0",
28
+ "@canton-network/core-wallet-auth": "^1.2.0",
29
+ "@dfns/sdk": "^0.8.9",
30
+ "@dfns/sdk-keysigner": "^0.8.9",
31
+ "lodash": "^4.17.21",
32
+ "pino": "^10.2.1",
33
+ "zod": "^4.3.5"
34
+ },
35
+ "devDependencies": {
36
+ "@jest/globals": "^30.2.0",
37
+ "@swc/core": "^1.15.10",
38
+ "@swc/jest": "^0.2.39",
39
+ "@types/jest": "^30.0.0",
40
+ "@types/lodash": "^4.17.16",
41
+ "@types/node": "^25.0.10",
42
+ "jest": "^30.2.0",
43
+ "ts-jest-resolver": "^2.0.1",
44
+ "tsup": "^8.5.1",
45
+ "typescript": "^5.9.3"
46
+ },
47
+ "files": [
48
+ "dist/**"
49
+ ],
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "git+https://github.com/hyperledger-labs/splice-wallet-kernel.git",
56
+ "directory": "core/signing-dfns"
57
+ }
58
+ }