@yourself_id/siwys-api-js 0.36.0 → 0.36.1-SAPP-1200.71.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,253 @@
1
+ # @yourself_id/siwys-api-js
2
+
3
+ Node.js backend SDK for **Sign In With YourSelf (SIWYS)** and the **Multi-Dimensional Identity Protocol (MDIP)**.
4
+
5
+ This package provides the tools required for server-side operations, including:
6
+ - Creating authentication challenges and callbacks for the SELF Mobile Wallet
7
+ - Verifying challenge responses submitted by users
8
+ - Issuing, binding, and publishing Verifiable Credentials
9
+ - Managing wallets and Decentralized Identifiers (DIDs)
10
+ - Communicating with Gatekeeper and Keymaster nodes
11
+
12
+ ---
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @yourself_id/siwys-api-js
18
+ # or
19
+ yarn add @yourself_id/siwys-api-js
20
+ ```
21
+
22
+ ---
23
+
24
+ ## Two Integration Pathways
25
+
26
+ You can use this SDK in one of two modes depending on your architecture:
27
+
28
+ | Pathway | Class | Best For | Architecture |
29
+ |---|---|---|---|
30
+ | **Embedded Keymaster** | `Keymaster` | Node.js / TypeScript backends | Runs Keymaster in-process, saves encrypted wallet state via pluggable DB adapter. |
31
+ | **External Keymaster Client** | `KeymasterExternalClient` | Polyglot / Microservices | Connects over HTTP REST to a standalone Keymaster container (e.g. from `KeychainMDIP/kc`). |
32
+
33
+ ---
34
+
35
+ ## Pathway 1: Embedded Keymaster (`Keymaster`)
36
+
37
+ Runs the Keymaster service in-process within your Node.js application.
38
+
39
+ ### 1. Configure Wallet Persistence
40
+
41
+ Keymaster requires a persistence adapter (`WalletBase`) to store the encrypted wallet. Here is an example filesystem adapter:
42
+
43
+ ```typescript
44
+ // services/wallet.ts
45
+ import fs from "fs";
46
+ import type { StoredWallet } from "@yourself_id/siwys-api-js";
47
+
48
+ const WALLET_FILE = "./data/wallet.json";
49
+
50
+ export async function saveWallet(wallet: StoredWallet, overwrite = false): Promise<boolean> {
51
+ if (fs.existsSync(WALLET_FILE) && !overwrite) return true;
52
+ fs.mkdirSync("./data", { recursive: true });
53
+ fs.writeFileSync(WALLET_FILE, JSON.stringify(wallet, null, 2));
54
+ return true;
55
+ }
56
+
57
+ export async function loadWallet(): Promise<StoredWallet | null> {
58
+ if (fs.existsSync(WALLET_FILE)) {
59
+ return JSON.parse(fs.readFileSync(WALLET_FILE, "utf-8"));
60
+ }
61
+ return null;
62
+ }
63
+
64
+ export async function updateWallet(
65
+ mutator: (wallet: StoredWallet) => void | Promise<void>
66
+ ): Promise<void> {
67
+ const wallet = await loadWallet();
68
+ if (!wallet) throw new Error("No wallet found to update");
69
+ const before = JSON.stringify(wallet);
70
+ await mutator(wallet);
71
+ if (before !== JSON.stringify(wallet)) {
72
+ await saveWallet(wallet, true);
73
+ }
74
+ }
75
+ ```
76
+
77
+ ### 2. Initialize and Start Keymaster
78
+
79
+ ```typescript
80
+ // server.ts
81
+ import { Keymaster } from "@yourself_id/siwys-api-js";
82
+ import { saveWallet, loadWallet, updateWallet } from "./services/wallet.js";
83
+
84
+ async function setupKeymaster() {
85
+ Keymaster.initialize({
86
+ gatekeeperConfig: {
87
+ url: process.env.GATEKEEPER_URL || "http://localhost:4224",
88
+ waitUntilReady: true,
89
+ },
90
+ walletConfig: {
91
+ id: "company-node-id",
92
+ registry: "hyperswarm",
93
+ mnemonic: process.env.WALLET_MNEMONIC, // optional: recovers wallet if initializing fresh
94
+ },
95
+ walletDb: {
96
+ saveWallet,
97
+ loadWallet,
98
+ updateWallet,
99
+ },
100
+ passphrase: process.env.KEYMASTER_PASSPHRASE || "a-secure-passphrase",
101
+ didPrefix: "did:test",
102
+ });
103
+
104
+ await Keymaster.start();
105
+ console.log("Keymaster is ready");
106
+ }
107
+
108
+ setupKeymaster();
109
+ ```
110
+
111
+ ---
112
+
113
+ ## Pathway 2: External Keymaster (`KeymasterExternalClient`)
114
+
115
+ Use this when you are running a standalone Keymaster container (such as the Docker image from [KeychainMDIP/kc](https://github.com/KeychainMDIP/kc)) on port 4226:
116
+
117
+ ```typescript
118
+ import { KeymasterExternalClient } from "@yourself_id/siwys-api-js";
119
+
120
+ const keymasterClient = new KeymasterExternalClient({
121
+ keymasterConfig: {
122
+ url: process.env.KEYMASTER_URL || "http://localhost:4226",
123
+ waitUntilReady: true,
124
+ },
125
+ didPrefix: "did:test",
126
+ });
127
+
128
+ await keymasterClient.start();
129
+ ```
130
+
131
+ `KeymasterExternalClient` provides the same core methods (`createChallenge`, `verifyResponse`, `bindCredential`, `issueCredential`, etc.) via HTTP REST.
132
+
133
+ ---
134
+
135
+ ## Core Use Cases
136
+
137
+ ### 1. Creating Authentication Challenges
138
+
139
+ When a user visits your sign-in page, create a challenge and return the challenge data and QR code URL to the frontend:
140
+
141
+ ```typescript
142
+ import { Keymaster } from "@yourself_id/siwys-api-js";
143
+
144
+ app.post("/challenges", async (req, res) => {
145
+ try {
146
+ const challenge = await Keymaster.createChallenge({
147
+ callback: `${process.env.BACKEND_URL}/login`,
148
+ // Optional: require user to present specific credentials
149
+ // credentials: [{ schema: "did:test:schema-id", issuers: ["did:test:issuer-did"] }]
150
+ });
151
+
152
+ // Returns: { challenge: "did:test:...", challengeUrl: "https://.../login?challenge=did:test:..." }
153
+ res.json(challenge);
154
+ } catch (err) {
155
+ res.status(500).json({ error: "Failed to generate challenge" });
156
+ }
157
+ });
158
+ ```
159
+
160
+ ### 2. Verifying Authentication Responses
161
+
162
+ The SELF mobile wallet signs and submits the challenge response back to your backend callback URL:
163
+
164
+ ```typescript
165
+ app.post("/login", async (req, res) => {
166
+ try {
167
+ const { response } = req.body;
168
+ const verify = await Keymaster.verifyResponse(response);
169
+
170
+ if (verify.match) {
171
+ // Authentication succeeded!
172
+ // verify.responder contains the user's DID
173
+ const userDid = verify.responder;
174
+
175
+ // Issue your application's session cookie or JWT
176
+ const sessionToken = createSessionForUser(userDid);
177
+
178
+ res.json({ authenticated: true, token: sessionToken });
179
+ } else {
180
+ res.status(401).json({ error: "Challenge response verification failed" });
181
+ }
182
+ } catch (err) {
183
+ res.status(500).json({ error: "Exception verifying response" });
184
+ }
185
+ });
186
+ ```
187
+
188
+ ### 3. Issuing Verifiable Credentials to Users
189
+
190
+ Issue a verifiable credential to a user's DID:
191
+
192
+ ```typescript
193
+ // 1. Bind credential to user's DID against a defined schema
194
+ const boundCredential = await Keymaster.bindCredential(schemaDid, userDid, {
195
+ validFrom: new Date().toISOString(),
196
+ validUntil: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(),
197
+ credential: {
198
+ membershipTier: "Gold",
199
+ accountNumber: "A-987654",
200
+ },
201
+ });
202
+
203
+ // 2. Issue the credential
204
+ const credentialDid = await Keymaster.issueCredential(boundCredential);
205
+
206
+ // 3. Publish so the holder or verifiers can resolve it
207
+ await Keymaster.publishCredential(credentialDid);
208
+ ```
209
+
210
+ ---
211
+
212
+ ## API & Configuration Reference
213
+
214
+ ### `KeymasterConfig`
215
+
216
+ | Field | Type | Required | Description |
217
+ |---|---|---|---|
218
+ | `gatekeeperConfig` | `SdkConfig` | Yes (embedded) | Configuration for connecting to the Gatekeeper node. |
219
+ | `walletConfig` | `WalletConfig` | Yes | ID and registry name for the default DID, plus optional mnemonic. |
220
+ | `walletDb` | `WalletBase` | Yes (embedded) | `saveWallet`, `loadWallet`, and `updateWallet` persistence hooks. |
221
+ | `passphrase` | `string` | Yes | Secret passphrase used to encrypt and decrypt the wallet at rest. |
222
+ | `didPrefix` | `string` | Optional | DID method prefix (e.g. `did:test` or `did:mdip`). |
223
+
224
+ ### `WalletConfig`
225
+
226
+ ```typescript
227
+ interface WalletConfig {
228
+ id: string; // Identifier for this node's default DID (e.g. "my-company-id")
229
+ registry: "local" | "hyperswarm" | "TESS" | "TBTC" | "TFTC" | "Signet" | "Signet-Inscription" | "BTC-Inscription";
230
+ mnemonic?: string; // BIP39 mnemonic seed phrase for recovery
231
+ }
232
+ ```
233
+
234
+ ### `SdkConfig`
235
+
236
+ ```typescript
237
+ interface SdkConfig {
238
+ url: string; // Base URL of Gatekeeper or Keymaster service
239
+ waitUntilReady?: boolean; // Wait for upstream service readiness before completing start
240
+ intervalSeconds?: number; // Poll interval when waiting for ready state
241
+ chatty?: boolean; // Enable verbose logging during connection
242
+ token?: string; // Optional bearer authorization token
243
+ }
244
+ ```
245
+
246
+ ---
247
+
248
+ ## Related Documentation
249
+
250
+ - [Keymaster Integration Guide](../../demo/README.md#integrating-keymaster)
251
+ - [React Frontend SDK (`@yourself_id/siwys-react-js`)](../react-js/README.md)
252
+ - [React Native SDK (`@yourself_id/siwys-react-native`)](../react-native/README.md)
253
+ - [Reference Node & Docker Microservices (KeychainMDIP/kc)](https://github.com/KeychainMDIP/kc)
package/dist/index.cjs CHANGED
@@ -41,6 +41,7 @@ module.exports = __toCommonJS(index_exports);
41
41
  var import_client = __toESM(require("@mdip/gatekeeper/client"), 1);
42
42
  var import_node = __toESM(require("@mdip/cipher/node"), 1);
43
43
  var import_keymaster = __toESM(require("@mdip/keymaster"), 1);
44
+ var import_encryption = require("@mdip/keymaster/encryption");
44
45
  var Keymaster = class _Keymaster {
45
46
  static instance = null;
46
47
  config;
@@ -66,6 +67,9 @@ var Keymaster = class _Keymaster {
66
67
  );
67
68
  }
68
69
  }
70
+ static resetInstance() {
71
+ _Keymaster.instance = null;
72
+ }
69
73
  // Ensures the instance is initialized
70
74
  ensureInitialized() {
71
75
  if (!_Keymaster.instance) {
@@ -285,6 +289,10 @@ var Keymaster = class _Keymaster {
285
289
  _Keymaster.getInstance().ensureInitialized();
286
290
  return _Keymaster.getInstance().createIdInternal(name, options);
287
291
  }
292
+ static async createIdOperation(name, account, options) {
293
+ _Keymaster.getInstance().ensureInitialized();
294
+ return _Keymaster.getInstance().createIdOperationInternal(name, account, options);
295
+ }
288
296
  // Remove an ID
289
297
  /**
290
298
  * Removes an existing DID.
@@ -338,6 +346,14 @@ var Keymaster = class _Keymaster {
338
346
  _Keymaster.getInstance().ensureInitialized();
339
347
  return _Keymaster.getInstance().setSchemaInternal(id, schema);
340
348
  }
349
+ static async loadWallet() {
350
+ _Keymaster.getInstance().ensureInitialized();
351
+ return _Keymaster.getInstance().loadWalletInternal();
352
+ }
353
+ static async saveWallet(wallet, overwrite = true) {
354
+ _Keymaster.getInstance().ensureInitialized();
355
+ return _Keymaster.getInstance().saveWalletInternal(wallet, overwrite);
356
+ }
341
357
  // Create a new wallet
342
358
  /**
343
359
  * Creates a new wallet.
@@ -359,6 +375,10 @@ var Keymaster = class _Keymaster {
359
375
  _Keymaster.getInstance().ensureInitialized();
360
376
  return _Keymaster.getInstance().recoverWalletInternal(did);
361
377
  }
378
+ static async recoverWalletWithRepair(did) {
379
+ _Keymaster.getInstance().ensureInitialized();
380
+ return _Keymaster.getInstance().recoverWalletWithRepairInternal(did);
381
+ }
362
382
  // Helper method to retrieve the instance
363
383
  static getInstance() {
364
384
  if (!_Keymaster.instance) {
@@ -414,7 +434,9 @@ var Keymaster = class _Keymaster {
414
434
  passphrase: this.config.passphrase,
415
435
  didPrefix: this.config.didPrefix
416
436
  });
417
- await this.ensureWalletExists();
437
+ if (this.config.autoSetupWallet !== false) {
438
+ await this.ensureWalletExists();
439
+ }
418
440
  } else {
419
441
  return false;
420
442
  }
@@ -500,6 +522,10 @@ var Keymaster = class _Keymaster {
500
522
  await this.ensureServiceIsRunning();
501
523
  return this.keymasterService.createId(...args);
502
524
  }
525
+ async createIdOperationInternal(...args) {
526
+ await this.ensureServiceIsRunning();
527
+ return this.keymasterService.createIdOperation(...args);
528
+ }
503
529
  async removeIdInternal(...args) {
504
530
  await this.ensureServiceIsRunning();
505
531
  return this.keymasterService.removeId(...args);
@@ -520,6 +546,14 @@ var Keymaster = class _Keymaster {
520
546
  await this.ensureServiceIsRunning();
521
547
  return this.keymasterService.setSchema(...args);
522
548
  }
549
+ async loadWalletInternal() {
550
+ await this.ensureServiceIsRunning();
551
+ return this.keymasterService.loadWallet();
552
+ }
553
+ async saveWalletInternal(wallet, overwrite) {
554
+ await this.ensureServiceIsRunning();
555
+ return this.keymasterService.saveWallet(wallet, overwrite);
556
+ }
523
557
  async newWalletInternal(...args) {
524
558
  await this.ensureServiceIsRunning();
525
559
  return this.keymasterService.newWallet(...args);
@@ -528,6 +562,63 @@ var Keymaster = class _Keymaster {
528
562
  await this.ensureServiceIsRunning();
529
563
  return this.keymasterService.recoverWallet(...args);
530
564
  }
565
+ async recoverWalletWithRepairInternal(did) {
566
+ await this.ensureServiceIsRunning();
567
+ const keymaster = this.keymasterService;
568
+ if (!did) {
569
+ const seedBank = await keymaster.resolveSeedBank();
570
+ const data = seedBank.didDocumentData;
571
+ did = data?.wallet;
572
+ }
573
+ if (!did || typeof did !== "string") {
574
+ throw new Error("No backup DID found");
575
+ }
576
+ const asset = await keymaster.resolveAsset(did);
577
+ if (!asset || typeof asset.backup !== "string") {
578
+ throw new Error('Asset "backup" is missing or not a string');
579
+ }
580
+ const cipher = new import_node.default();
581
+ const keypair = await keymaster.hdKeyPair();
582
+ const backup = JSON.parse(cipher.decryptMessage(
583
+ keypair.publicJwk,
584
+ keypair.privateJwk,
585
+ asset.backup
586
+ ));
587
+ if (!backup || typeof backup !== "object" || Array.isArray(backup)) {
588
+ throw new Error("Invalid backup wallet");
589
+ }
590
+ const mnemonic = await keymaster.decryptMnemonic();
591
+ if (backup.version === 1) {
592
+ if (!backup.seed || typeof backup.seed !== "object" || Array.isArray(backup.seed)) {
593
+ throw new Error("Invalid backup wallet seed");
594
+ }
595
+ backup.seed.mnemonicEnc = await (0, import_encryption.encMnemonic)(
596
+ mnemonic,
597
+ this.config.passphrase
598
+ );
599
+ }
600
+ const validator = new import_keymaster.default({
601
+ gatekeeper: this.getGatekeeper(),
602
+ wallet: {
603
+ loadWallet: async () => backup,
604
+ saveWallet: async () => true
605
+ },
606
+ cipher,
607
+ passphrase: this.config.passphrase,
608
+ didPrefix: this.config.didPrefix
609
+ });
610
+ const wallet = await validator.loadWallet();
611
+ if (!Number.isInteger(wallet.counter) || wallet.counter < 0 || !wallet.ids || typeof wallet.ids !== "object" || Array.isArray(wallet.ids)) {
612
+ throw new Error("Invalid backup wallet contents");
613
+ }
614
+ if (await validator.decryptMnemonic() !== mnemonic) {
615
+ throw new Error("Backup mnemonic does not match local wallet");
616
+ }
617
+ if (!await keymaster.saveWallet(wallet, true)) {
618
+ throw new Error("Failed to save recovered wallet");
619
+ }
620
+ return keymaster.loadWallet();
621
+ }
531
622
  async ensureWalletExists() {
532
623
  const existing = await this.config?.walletDb?.loadWallet() || null;
533
624
  const walletConfig = this.config?.walletConfig;
@@ -567,7 +658,7 @@ var Keymaster = class _Keymaster {
567
658
  throw new Error("Missing didPrefix config");
568
659
  }
569
660
  if (config.gatekeeperConfig) {
570
- if (!config.walletConfig) {
661
+ if (config.autoSetupWallet !== false && !config.walletConfig) {
571
662
  throw new Error("Missing wallet config");
572
663
  }
573
664
  if (!config.walletDb?.loadWallet) {