@huaweidevtools/aishell-dsh-credentials-store 0.0.2 → 0.0.4

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
@@ -8,12 +8,20 @@ This is a **tool library**, not a DSH plugin — no `dsh.client`, no `cordis.pat
8
8
 
9
9
  | Priority | Backend | Durable? | Requirement |
10
10
  |---|---|---|---|
11
- | 1 | `KeyringBackend` | Yes (cross-process, survives reboot) | OS keyring reachable (macOS Keychain / Linux libsecret / Windows Credential Manager) |
11
+ | 1 | `KeyringBackend` | Yes (cross-process, survives reboot) | OS keyring reachable (macOS Keychain / Linux Secret Service / Windows Credential Manager) |
12
12
  | 2 | `FingerprintBackend` | Yes (same-machine, survives reboot) | `node-machine-id` can resolve a machine UUID |
13
13
  | 3 | `MemoryBackend` | No (process-scoped) | None — always available, last resort |
14
14
 
15
15
  When the OS keyring is unavailable (headless Linux without D-Bus, keychain locked, container), the factory falls back to the fingerprint backend — a machine-fingerprint-bound AES-256-GCM encrypted file at `~/.<service>/credentials.enc`. The encryption key is derived from the machine UUID via scrypt; the ciphertext is useless on a different machine. If the machine UUID is also unavailable, the factory falls back to the in-memory backend so a single DSH session still works.
16
16
 
17
+ ### Linux: the store is required, not preferred
18
+
19
+ `@napi-rs/keyring` picks its own Linux store when none is named: the Secret Service first, then — silently — the **kernel keyutils keyring**. That fallback is wrong for credentials, as the binding's own README states: the kernel keyring is "completely in-memory and will not persist across reboots". A container or CI job would accept credentials, report them stored, and lose them at the next reboot.
20
+
21
+ `KeyringBackend` therefore passes `{ linux: { store: 'secret-service' } }`, which makes an unavailable Secret Service **throw** from the construction probe instead of falling back — so the factory's next backend is the fingerprint encrypted file, which is durable. Without the pin the absent-service case does not throw; see the module comment in `src/backends/keyring.ts`.
22
+
23
+ Note that this is the D-Bus Secret Service protocol (`org.freedesktop.secrets`), not `libsecret` — the binding does not link libsecret, and the platform binary is prebuilt, so no development headers are needed.
24
+
17
25
  ## Write failover
18
26
 
19
27
  The construction probe can only detect a keyring that cannot be *read*. A GNOME login keyring whose collection is locked passes the probe — reads answer `null` rather than throwing — and then rejects every write (`Secret Service: no result found`, or a system unlock prompt that blocks until dismissed). So a keyring that passes the probe is wrapped in a `FailoverStore`, which covers the write side:
@@ -46,17 +54,18 @@ const store = createCredentialsStore({ service: 'my-app' })
46
54
  ## Security properties
47
55
 
48
56
  - **No plaintext files**: nothing on disk is readable with `cat`.
49
- - **OS-encrypted at rest**: Keychain (AES), libsecret (DPAPI/GNOME keyring), Credential Manager (DPAPI).
57
+ - **OS-encrypted at rest**: Keychain, Secret Service (GNOME keyring / KWallet — the OS owns the encryption), Credential Manager.
50
58
  - **Machine-bound encryption (FingerprintBackend)**: AES-256-GCM with a scrypt-derived key from the machine UUID. The ciphertext is useless on a different machine; the key never touches disk.
51
59
  - **Per-operation read**: no cache; a credential removed from the keyring is immediately absent on the next `get`.
52
- - **Graceful degradation**: a missing keyring reads as empty, not as an error — the caller's auth flow fails the same way whether the credential is absent or the store is unreachable.
60
+ - **A reachable store that lacks the credential reads as absent, not as an error** — `get` answers `undefined`, so the caller's auth flow fails the same way whether the credential was never stored or was cleared.
61
+ - **An unreachable store is a construction failure, not a read failure.** With the Linux store required (above), no `KeyringBackend` is built at all when the Secret Service cannot be reached: the constructor throws and the factory moves to a durable backend. Once constructed, a store that later becomes unreachable has `get`/`has` answer `undefined`/`false` (reads degrade) while `set`/`delete` throw (writes cannot be silently lost).
53
62
 
54
63
  ## Platform support (KeyringBackend)
55
64
 
56
65
  | Platform | Backend | Requirement |
57
66
  |---|---|---|
58
67
  | macOS | Keychain | None (built in) |
59
- | Linux | libsecret | `gnome-keyring` or `kwallet` running, plus `libsecret-1-dev` at build time |
68
+ | Linux | Secret Service over D-Bus | `gnome-keyring`, `kwalletd`, or KeePassXC running on the session bus (no libsecret, no build headers — the platform binary ships prebuilt) |
60
69
  | Windows | Credential Manager | None (built in) |
61
70
 
62
71
  ## License
package/lib/index.d.ts CHANGED
@@ -5,21 +5,31 @@ type KeyringEntry = {
5
5
  setPassword: (value: string) => void;
6
6
  deletePassword: () => void;
7
7
  };
8
+ /** Entry options bag; only the Linux store pin is used (see the module note). */
9
+ type KeyringEntryOptions = {
10
+ linux?: {
11
+ store?: 'secret-service' | 'keyutils';
12
+ };
13
+ };
8
14
  type KeyringModule = {
9
- Entry: new (service: string, account: string) => KeyringEntry;
15
+ Entry: new (service: string, account: string, options?: KeyringEntryOptions) => KeyringEntry;
10
16
  };
11
17
  /** @internal Test hook: inject a mock keyring module (vi.mock cannot intercept createRequire). */
12
18
  declare function __setKeyringModule(mock: KeyringModule | undefined): void;
13
19
  /**
14
20
  * OS-keyring {@link CredentialsStore}. Constructed with a shared service name;
15
- * every entry is stored under `new Entry(service, account)`.
21
+ * every entry is stored under `new Entry(service, account, { linux: { store:
22
+ * 'secret-service' } })`.
16
23
  *
17
24
  * Construction probes the keyring once — if the native module cannot be loaded
18
- * (no prebuilt binding for this platform) or cannot reach a secret service it
19
- * throws, and {@link createCredentialsStore} falls back to the next backend.
25
+ * (no prebuilt binding for this platform), or the Linux Secret Service is
26
+ * unavailable, it throws and {@link createCredentialsStore} falls back to the
27
+ * next backend. Without the pin the absent-service case does not throw; see
28
+ * the module note.
20
29
  */
21
30
  declare class KeyringBackend implements CredentialsStore {
22
31
  private readonly serviceName;
32
+ private readonly options;
23
33
  private readonly Entry;
24
34
  constructor(config?: CredentialsStoreConfig);
25
35
  get(account: string): string | undefined;
@@ -28,7 +38,6 @@ declare class KeyringBackend implements CredentialsStore {
28
38
  has(account: string): boolean;
29
39
  } //#endregion
30
40
  //#region src/backends/fingerprint.d.ts
31
-
32
41
  /**
33
42
  * Encrypted-file {@link CredentialsStore}. Each account is one entry in a
34
43
  * single JSON map, encrypted as one file under the resolved credentials
@@ -55,9 +64,10 @@ declare class FingerprintBackend implements CredentialsStore {
55
64
  set(account: string, value: string): void;
56
65
  delete(account: string): void;
57
66
  has(account: string): boolean;
58
- } //#endregion
59
- //#region src/backends/memory.d.ts
67
+ }
60
68
 
69
+ //#endregion
70
+ //#region src/backends/memory.d.ts
61
71
  //# sourceMappingURL=fingerprint.d.ts.map
62
72
  /** Process-scoped {@link CredentialsStore}; entries vanish on exit. */
63
73
  declare class MemoryBackend implements CredentialsStore {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/backends/keyring.ts","../../src/backends/fingerprint.ts","../../src/backends/memory.ts","../../src/failover.ts","../../src/index.ts"],"sourcesContent":null,"mappings":";;AA+CA,KA1BK,YAAA,GA0BQ;EAAe,WAAA,EAAA,GAAA,GAAA,MAAA,GAAA,IAAA;EAAA,WAIN,EAAA,CAAA,KAAA,EAAA,MAAA,EAAA,GAAA,IAAA;EAA2B,cAJV,EAAA,GAAA,GAAA,IAAA;AAAgB,CAAA;KArBlD,aAAA;mDAAmE;;;iBAIxD,kBAAA,OAAyB;;;;;;;;AC2DzC;AAAgC,cD1CnB,cAAA,YAA0B,gBC0CP,CAAA;EAAA,iBAIV,WAAA;EAA2B,iBAJN,KAAA;EAAgB,WAAA,CAAA,MAAA,CAAA,EDtCrC,sBCsCqC;;;;;AC1E3D,CAAA;;;;;AFgCuD;;;;;;;cC0C1C,kBAAA,YAA8B;;;uBAIrB;;;AAJtB;;;;EAA2D,QAAA,IAAA;;;;;EC1E9C,MAAA,CAAA,OAAA,EAAc,MAAA,CAAA,EAAA,IAAA;EAAA,GAAA,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,OAAA;CAAA;;;;;AFgCd,cEhCA,aAAA,YAAyB,gBFgCV,CAAA;EAAA,iBAAA,OAAA;EAAA,WAIN,CAAA,OAAA,CAAA,EEjCC,sBFiCD;EAA2B,GAJV,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAgB,GAAA,CAAA,OAAA,EAAA,MAAA,EAAA,KAAA,EAAA,MAAA,CAAA,EAAA,IAAA;;;;;;;;;;UGqDtC,oBAAA;;;;;;;iCAOgB;;;ACnFjC;;;;;;;;AAuBA;;;;;;cD8Ea,aAAA,YAAyB;;;;;;uBAOf,2BAA2B;;;;;;;;;ACtDlD;EAAsC,QAAA,cAAA;EAAA,GAAS,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAA2B,GAAG,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,OAAA;EAAgB,GAAA,CAAA,OAAA,EAAA,MAAA,EAAA,KAAA,EAAA,MAAA,CAAA,EAAA,IAAA;;;;;;;;;;;;;;;AJhElB;AAO1D;;AASjB;;;;;;;;;AAiBA;;;;AAAuD;UIvBtC,sBAAA;;;;;;;;;;;;AHiEjB;EAAgC,SAAA,cAAA,CAAA,EAAA,MAAA;;;AAA2B;;;;;AC1E3D;AAA2B,UEgCV,gBAAA,CFhCU;EAAA;EAGuB,GAHZ,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAgB;;;;;ECqFrC,GAAA,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,OAAoB;;;;;;;;;;;;;;;;AAyBrC;;;;;AAAsD;iBC/CtC,sBAAA,UAA+B,yBAA8B"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/backends/keyring.ts","../../src/backends/fingerprint.ts","../../src/backends/memory.ts","../../src/failover.ts","../../src/index.ts"],"sourcesContent":null,"mappings":";;KAsCK,YAAA;;;;;;KAMA,mBAAA;;IC6CQ,KAAA,CAAA,EAAA,gBAAmB,GAAA,UAAA;EAAA,CAAA;CAAA;KD5C3B,aAAA,GC4CsC;EAAgB,KAAA,EAAA,KAAA,OAAA,EAAA,MAAA,EAAA,OAAA,EAAA,MAAA,EAAA,OAAA,CAAA,ED3CD,mBC2CC,EAAA,GD3CuB,YC2CvB;;;iBDtC3C,kBAAA,OAAyB;;AEpCzC;;;;AAAsD;;;;;ACqFtD;cH7Ba,cAAA,YAA0B;;;;uBAKjB;;;;;;;;;;;;;AALtB;;;AAAuC,cCkB1B,kBAAA,YAA8B,gBDlBJ,CAAA;EAAgB,iBAAA,QAAA;;uBCsBjC;;;;;;;;;;;EAJT,GAAA,CAAA,OAAA,EAAA,MAAA,EAAmB,KAAA,EAAA,MAAA,CAAA,EAAA,IAAA;EAAA,MAAA,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,IAAA;EAAA,GAIV,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,OAAA;;;;;AAJqC;;cC1E9C,aAAA,YAAyB;;wBAGf;;;;;;;;;AFqDvB;;;UG6BiB,oBAAA;;;;;;;iCAOgB;;;;;;;;;;;ACnFjC;;;;;;cDqGa,aAAA,YAAyB;;EC9ErB,iBAAA,cAAgB;;;;uBDqFV,2BAA2B;;;;;;;;;;;;;;;;;ACtDlD;;;;AAA6F;;;;;;;AJ/ClB;AAO1D;AAMO;;;;AAEsE;;AAK9F;;;;;;;;;UI3BiB,sBAAA;;;AJ+CjB;;;EAKiD,SALV,OAAA,CAAA,EAAA,MAAA;EAAgB;;;;;;;;;;;;;ACkBvD;;AAIsB,UG9CL,gBAAA,CH8CK;EAA2B;EAJU,GAAA,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;;;;;EC1E9C;EAAc,GAAA,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,OAAA;;;AAA2B;;;;;ACqFtD;;;;;;;;;;;;;;iBCtBgB,sBAAA,UAA+B,yBAA8B"}
package/lib/index.js CHANGED
@@ -18,21 +18,25 @@ function loadKeyring() {
18
18
  }
19
19
  /**
20
20
  * OS-keyring {@link CredentialsStore}. Constructed with a shared service name;
21
- * every entry is stored under `new Entry(service, account)`.
21
+ * every entry is stored under `new Entry(service, account, { linux: { store:
22
+ * 'secret-service' } })`.
22
23
  *
23
24
  * Construction probes the keyring once — if the native module cannot be loaded
24
- * (no prebuilt binding for this platform) or cannot reach a secret service it
25
- * throws, and {@link createCredentialsStore} falls back to the next backend.
25
+ * (no prebuilt binding for this platform), or the Linux Secret Service is
26
+ * unavailable, it throws and {@link createCredentialsStore} falls back to the
27
+ * next backend. Without the pin the absent-service case does not throw; see
28
+ * the module note.
26
29
  */
27
30
  var KeyringBackend = class {
28
31
  constructor(config = {}) {
29
32
  this.serviceName = config.service ?? "aishell-dsh";
33
+ this.options = { linux: { store: "secret-service" } };
30
34
  this.Entry = loadKeyring().Entry;
31
- new this.Entry(this.serviceName, "__probe__").getPassword();
35
+ new this.Entry(this.serviceName, "__probe__", this.options).getPassword();
32
36
  }
33
37
  get(account) {
34
38
  try {
35
- const value = new this.Entry(this.serviceName, account).getPassword();
39
+ const value = new this.Entry(this.serviceName, account, this.options).getPassword();
36
40
  return value ?? void 0;
37
41
  } catch {
38
42
  return void 0;
@@ -40,18 +44,18 @@ var KeyringBackend = class {
40
44
  }
41
45
  set(account, value) {
42
46
  if (value.length === 0) throw new Error("credential value must be non-empty");
43
- new this.Entry(this.serviceName, account).setPassword(value);
47
+ new this.Entry(this.serviceName, account, this.options).setPassword(value);
44
48
  }
45
49
  delete(account) {
46
50
  try {
47
- new this.Entry(this.serviceName, account).deletePassword();
51
+ new this.Entry(this.serviceName, account, this.options).deletePassword();
48
52
  } catch (error) {
49
53
  if (!String(error).includes("not found") && !String(error).includes("no entry")) throw error;
50
54
  }
51
55
  }
52
56
  has(account) {
53
57
  try {
54
- return new this.Entry(this.serviceName, account).getPassword() !== null;
58
+ return new this.Entry(this.serviceName, account, this.options).getPassword() !== null;
55
59
  } catch {
56
60
  return false;
57
61
  }
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["keyringModule: KeyringModule | undefined","mock: KeyringModule | undefined","config: CredentialsStoreConfig","account: string","value: string","error: unknown","machineIdSync: () => string","plaintext: string","data: Buffer","config: CredentialsStoreConfig","entries: Map<string, string>","account: string","value: string","_config: CredentialsStoreConfig","account: string","value: string","account: string","primary: CredentialsStore","options: FailoverStoreOptions","value: string","error: unknown","fallbackError: unknown","config: CredentialsStoreConfig","keyring: CredentialsStore | undefined"],"sources":["../src/backends/keyring.ts","../src/backends/fingerprint.ts","../src/backends/memory.ts","../src/failover.ts","../src/index.ts"],"sourcesContent":["/**\n * OS-keyring backend — the durable, cross-process credential store.\n *\n * Wraps `@napi-rs/keyring` (macOS Keychain / Linux libsecret / Windows\n * Credential Manager). Values persist across process restarts and reboots\n * because the OS owns the store.\n *\n * Native keyring errors (e.g. no D-Bus secret service running on Linux) are\n * caught: `get`/`has` return `undefined`/`false` so callers degrade\n * gracefully; `set`/`delete` throw a descriptive error so the caller knows\n * the store is unavailable.\n */\n\nimport { createRequire } from 'node:module'\nimport type { CredentialsStore, CredentialsStoreConfig } from '../index.ts'\n\n// Lazily resolved so a missing native binding (the known @napi-rs optional-deps\n// bug, or a platform with no prebuilt binary) throws inside the constructor\n// probe — where createCredentialsStore's try/catch catches it and falls back\n// to FingerprintBackend — instead of crashing at module-load time.\nconst require = createRequire(import.meta.url)\ntype KeyringEntry = {\n getPassword: () => string | null\n setPassword: (value: string) => void\n deletePassword: () => void\n}\ntype KeyringModule = { Entry: new (service: string, account: string) => KeyringEntry }\nlet keyringModule: KeyringModule | undefined\n\n/** @internal Test hook: inject a mock keyring module (vi.mock cannot intercept createRequire). */\nexport function __setKeyringModule(mock: KeyringModule | undefined): void {\n keyringModule = mock\n}\n\nfunction loadKeyring(): KeyringModule {\n if (keyringModule === undefined) keyringModule = require('@napi-rs/keyring') as KeyringModule\n return keyringModule\n}\n\n/**\n * OS-keyring {@link CredentialsStore}. Constructed with a shared service name;\n * every entry is stored under `new Entry(service, account)`.\n *\n * Construction probes the keyring once — if the native module cannot be loaded\n * (no prebuilt binding for this platform) or cannot reach a secret service it\n * throws, and {@link createCredentialsStore} falls back to the next backend.\n */\nexport class KeyringBackend implements CredentialsStore {\n private readonly serviceName: string\n private readonly Entry: new (service: string, account: string) => KeyringEntry\n\n constructor(config: CredentialsStoreConfig = {}) {\n this.serviceName = config.service ?? 'aishell-dsh'\n this.Entry = loadKeyring().Entry\n // Probe: a getPassword on a throwaway account exercises the native path.\n // If the secret service is absent this throws (D-Bus error, etc.), which\n // the factory catches to fall back to the fingerprint backend.\n new this.Entry(this.serviceName, '__probe__').getPassword()\n }\n\n get(account: string): string | undefined {\n try {\n const value = new this.Entry(this.serviceName, account).getPassword()\n return value ?? undefined\n } catch {\n return undefined\n }\n }\n\n set(account: string, value: string): void {\n if (value.length === 0) throw new Error('credential value must be non-empty')\n new this.Entry(this.serviceName, account).setPassword(value)\n }\n\n delete(account: string): void {\n try {\n new this.Entry(this.serviceName, account).deletePassword()\n } catch (error: unknown) {\n // deletePassword on an absent entry may throw on some backends;\n // treat that as a no-op rather than an error.\n if (!String(error).includes('not found') && !String(error).includes('no entry')) {\n throw error\n }\n }\n }\n\n has(account: string): boolean {\n try {\n return new this.Entry(this.serviceName, account).getPassword() !== null\n } catch {\n return false\n }\n }\n}\n","/**\n * Machine-fingerprint-bound encrypted file backend.\n *\n * When the OS keyring is unavailable (headless Linux, Docker, no keyring\n * daemon), credentials are encrypted with a key derived from the machine UUID\n * (node-machine-id) via scrypt, then AES-256-GCM. File format:\n * [12B nonce][16B tag][ciphertext...].\n *\n * The key never touches disk; the ciphertext is useless on a different machine.\n * Same-user-same-machine is trusted. VM cloning copies the machine UUID — a\n * known limitation, not a security hole.\n *\n * Ported from mcp-huaweicloud-ops-deploy/src/auth/fingerprint.ts.\n */\n\nimport { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto'\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport machineIdModule from 'node-machine-id'\nimport type { CredentialsStore, CredentialsStoreConfig } from '../index.ts'\n\nconst machineIdSync: () => string = machineIdModule.machineIdSync\n\nconst SALT = 'aishell-dsh/credentials/v1'\nconst KEY_LEN = 32 // AES-256\nconst NONCE_LEN = 12 // GCM standard (96-bit nonce)\nconst TAG_LEN = 16 // 128-bit auth tag\n\n/** Derive a 32-byte key from the machine UUID via scrypt. */\nfunction deriveKey(): Buffer {\n const machineId = machineIdSync()\n return scryptSync(machineId, SALT, KEY_LEN)\n}\n\n/** Encrypt plaintext → [nonce][tag][ciphertext] as a Buffer. */\nfunction fingerprintEncrypt(plaintext: string): Buffer {\n const key = deriveKey()\n const nonce = randomBytes(NONCE_LEN)\n const cipher = createCipheriv('aes-256-gcm', key, nonce)\n const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n return Buffer.concat([nonce, tag, ciphertext])\n}\n\n/** Decrypt [nonce][tag][ciphertext] → plaintext. Throws on tamper/wrong machine. */\nfunction fingerprintDecrypt(data: Buffer): string {\n if (data.length < NONCE_LEN + TAG_LEN) {\n throw new Error('credentials file corrupted (too short)')\n }\n const key = deriveKey()\n const nonce = data.subarray(0, NONCE_LEN)\n const tag = data.subarray(NONCE_LEN, NONCE_LEN + TAG_LEN)\n const ciphertext = data.subarray(NONCE_LEN + TAG_LEN)\n const decipher = createDecipheriv('aes-256-gcm', key, nonce)\n decipher.setAuthTag(tag)\n const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()])\n return plaintext.toString('utf8')\n}\n\n/**\n * Resolve the directory holding the encrypted credentials file.\n *\n * Priority: an explicit `config.credentialsDir` override → the host's\n * `DSH_HOME` (so credentials live alongside the rest of that host's data —\n * `~/.aishell/credentials` for the desktop app, `~/.dsh/credentials` for the\n * dsh CLI) → a standalone `~/.aishell-dsh` fallback for headless / library\n * use where no DSH host is involved.\n *\n * The `service` config still names the keyring service (and the fallback\n * directory name when neither `credentialsDir` nor `DSH_HOME` is set).\n */\nfunction resolveCredentialsDir(config: CredentialsStoreConfig): string {\n if (config.credentialsDir !== undefined) return config.credentialsDir\n const dshHome = process.env.DSH_HOME\n if (dshHome !== undefined && dshHome.trim() !== '') return join(dshHome, 'credentials')\n const dirName = config.service ?? 'aishell-dsh'\n return join(homedir(), `.${dirName}`)\n}\n\n/**\n * Encrypted-file {@link CredentialsStore}. Each account is one entry in a\n * single JSON map, encrypted as one file under the resolved credentials\n * directory (`$DSH_HOME/credentials/credentials.enc` by default).\n *\n * Construction probes the machine ID + crypto — if `node-machine-id` cannot\n * resolve a UUID, construction throws and the factory falls back to\n * {@link MemoryBackend}.\n */\nexport class FingerprintBackend implements CredentialsStore {\n private readonly filePath: string\n private readonly fileDir: string\n\n constructor(config: CredentialsStoreConfig = {}) {\n this.fileDir = resolveCredentialsDir(config)\n this.filePath = join(this.fileDir, 'credentials.enc')\n // Probe: deriveKey exercises node-machine-id. If it throws, the factory\n // falls back to MemoryBackend.\n deriveKey()\n }\n\n /**\n * Load + decrypt the file into a fresh map. Not cached — credentials are\n * read, used, and dropped so plaintext does not linger in memory between\n * operations. The file I/O + scrypt decrypt per call is acceptable: this is\n * not a hot path (once per chat request, not per token).\n */\n private load(): Map<string, string> {\n if (!existsSync(this.filePath)) return new Map()\n try {\n const encrypted = readFileSync(this.filePath)\n const plaintext = fingerprintDecrypt(encrypted)\n return new Map(Object.entries(JSON.parse(plaintext) as Record<string, string>))\n } catch {\n // Corrupted or wrong machine — treat as empty.\n return new Map()\n }\n }\n\n /** Encrypt + write the map to disk with owner-only permissions. */\n private persist(entries: Map<string, string>): void {\n const plaintext = JSON.stringify(Object.fromEntries(entries))\n mkdirSync(this.fileDir, { recursive: true, mode: 0o700 })\n // Write owner-only (0600); on platforms that ignore the mode (Windows)\n // the file is still encrypted, and ACLs inherit from the profile dir.\n writeFileSync(this.filePath, fingerprintEncrypt(plaintext), { mode: 0o600 })\n }\n\n get(account: string): string | undefined {\n return this.load().get(account)\n }\n\n set(account: string, value: string): void {\n if (value.length === 0) throw new Error('credential value must be non-empty')\n const entries = this.load()\n entries.set(account, value)\n this.persist(entries)\n }\n\n delete(account: string): void {\n const entries = this.load()\n if (entries.delete(account)) {\n this.persist(entries)\n }\n }\n\n has(account: string): boolean {\n return this.load().has(account)\n }\n}\n","/**\n * In-memory backend — the volatile last-resort credential store.\n *\n * Used when the OS keyring is unavailable (no secret service, keychain\n * locked, headless box without D-Bus). Entries live in a process-scoped\n * `Map` and are lost when the process exits — durable enough for a single\n * DSH session, not for persistence.\n *\n * Callers never select this directly; {@link createCredentialsStore} falls\n * back to it when {@link KeyringBackend} cannot initialize.\n */\n\nimport type { CredentialsStore, CredentialsStoreConfig } from '../index.ts'\n\n/** Process-scoped {@link CredentialsStore}; entries vanish on exit. */\nexport class MemoryBackend implements CredentialsStore {\n private readonly entries = new Map<string, string>()\n\n constructor(_config: CredentialsStoreConfig = {}) {\n // Service name is accepted for API symmetry with KeyringBackend but not\n // used: the in-process Map is keyed by account alone, and the factory\n // guarantees only one MemoryBackend is live per credential concern.\n }\n\n get(account: string): string | undefined {\n return this.entries.get(account)\n }\n\n set(account: string, value: string): void {\n if (value.length === 0) throw new Error('credential value must be non-empty')\n this.entries.set(account, value)\n }\n\n delete(account: string): void {\n this.entries.delete(account)\n }\n\n has(account: string): boolean {\n return this.entries.has(account)\n }\n}\n","/**\n * Write-failover wrapper — covers the failure class the construction-time\n * probe chain cannot see.\n *\n * {@link createCredentialsStore} picks a backend by probing at construction\n * time, but the highest-priority backend (the OS keyring) can pass that probe\n * and still reject every real write: a locked GNOME keyring collection reads\n * as `null` (the probe's getPassword does not throw) while setPassword fails.\n * Measured on an isolated D-Bus session:\n *\n * - locked collection, no default alias — read 5 ms → null; write 5 ms →\n * \"Couldn't access platform storage: Secret Service: no result found\"\n * - locked collection, default alias set (the real-desktop shape) — read\n * still null; write blocks on the system unlock prompter and rejects with\n * \"Secret Service: unlock prompt was dismissed\" when canceled\n *\n * So the write path needs its own fallback chain, and it must be sticky: a\n * locked keyring fails every write, so retrying it per call would surface the\n * same error (or the same prompt) once per account a save writes. Deletes trip\n * the same failover: a locked collection rejects them with the same error, and\n * the save route (delete old set → write new set) deletes first — without\n * this, a locked keyring would fail the save before the write failover ever\n * engages.\n *\n * ## Which copy wins\n *\n * A locked collection answers `null` for entries that are really there, so the\n * primary's copy of an account can be arbitrarily out of date while still\n * reading as authoritative. Once it unlocks, that copy would outrank the value\n * the user saved in the meantime — resurrecting a credential the user rotated\n * or cleared, with every later signature using the superseded key.\n *\n * The two backends cannot be compared by recency (neither records one), so the\n * fallback is treated as authoritative for any account it has an opinion\n * about, and the primary answers only when the fallback has none:\n *\n * - **A value in the fallback wins.** It is there because a failover write\n * put it there, and that write is by definition newer than whatever the\n * primary holds. No bookkeeping is needed — the value shadows the primary\n * simply by existing.\n * - **A tombstone means deleted.** A clear whose primary delete failed has\n * nothing to shadow with, so it writes an explicit marker; without one, the\n * stale primary copy would read back as present.\n * - **Otherwise the primary answers**, which is the ordinary healthy path.\n *\n * A successful primary write or delete clears both the fallback value and the\n * tombstone, handing authority back to the keyring.\n *\n * Recording deletion this way — rather than marking accounts \"stale\" on every\n * failover write — keeps the value and its shadow in one place. A mark set by a\n * write would have to be cleared in lockstep with the value, and a mark left\n * behind after its value was gone would make a perfect keyring credential read\n * as *absent* rather than merely stale.\n *\n * ## Why the record is persisted, not held in memory\n *\n * The state it describes outlives the store: the failure is \"the keyring is\n * locked now\", and the read that would resurrect the credential happens in a\n * later session, after it has unlocked. It is therefore stored in the fallback\n * backend itself — the encrypted file in practice, and merely the process in\n * the memory-backed last resort, where the failover is no more durable either.\n * Keys carry a NUL prefix, which no real credential account can collide with.\n *\n * ## Cost on the healthy path\n *\n * The fallback is consulted on every read (once for a value, once for a\n * tombstone). On a machine whose keyring has never failed the fallback has\n * written nothing, so its file does not exist and both lookups are\n * sub-millisecond `existsSync` misses (measured 0.02-0.4 ms). Where a fallback\n * file does exist, each lookup decrypts it — the read-through this replaced\n * already paid one decrypt per miss.\n *\n * The fallback is built on the first read rather than the first failed write,\n * which a machine with a working keyring pays once per store: ~97 ms, almost\n * all of it the fingerprint backend's scrypt probe (measured). It is lazy and\n * cached, so later reads are unaffected.\n *\n * @module\n */\n\nimport type { CredentialsStore } from './index.ts'\n\n/**\n * Account-name prefix marking an account as deleted while the primary was\n * unreachable.\n *\n * The NUL byte cannot appear in a real account name (`HW_ACCESS_KEY`,\n * `HW_SECRET_KEY`, `HW_SECURITY_TOKEN`), so a tombstone can never be confused\n * with a credential. Tombstones are only ever written to the fallback, never\n * to the keyring.\n */\nconst TOMBSTONE_PREFIX = '\\u0000aishell:tombstone:'\n\n/** The fallback key recording that `account` was deleted. */\nconst tombstoneKey = (account: string): string => TOMBSTONE_PREFIX + account\n\n/** Tombstone value; never read, only tested for presence. */\nconst TOMBSTONE_VALUE = '1'\n\n/** Options for {@link FailoverStore}. */\nexport interface FailoverStoreOptions {\n /**\n * Builds the store that takes over when the primary fails a write. Called\n * at most once, lazily, on first need — a read miss or the first failed\n * write — so a healthy keyring never pays for constructing it. Must not\n * throw: the factory's closure ends in MemoryBackend.\n */\n readonly createFallback: () => CredentialsStore\n}\n\n/**\n * A {@link CredentialsStore} that delegates to a primary until the primary\n * fails a write, then fails over — for the life of this store — to a\n * fallback supplied by {@link FailoverStoreOptions.createFallback}.\n *\n * Stickiness is per instance, not per process: each plugin that consumes\n * credentials builds its own store, so one instance failing over does not stop\n * another from trying the primary. That is intended — the flag only exists to\n * avoid re-hitting a primary already known to be unwritable from *this* store,\n * and a second instance's attempt is one probe rather than a policy decision.\n * Correctness across instances comes from the persisted record, not the flag.\n *\n * Constructed by {@link createCredentialsStore} around a KeyringBackend whose\n * construction probe passed; not meant for direct use by upper layers.\n */\nexport class FailoverStore implements CredentialsStore {\n private readonly primary: CredentialsStore\n private readonly createFallback: () => CredentialsStore\n private fallback: CredentialsStore | undefined\n /** Set by the first failed primary write; routes writes thereafter. */\n private failedOver = false\n\n constructor(primary: CredentialsStore, options: FailoverStoreOptions) {\n this.primary = primary\n this.createFallback = options.createFallback\n }\n\n /** The lazily built fallback; constructed at most once per store. */\n private get fallbackStore(): CredentialsStore {\n if (this.fallback === undefined) this.fallback = this.createFallback()\n return this.fallback\n }\n\n /**\n * Drop the tombstone for `account`, if any.\n *\n * Paired with the value purge on every path that hands authority back to the\n * primary. Best-effort: a tombstone that outlives its purpose costs one extra\n * fallback lookup, which must never fail a write the keyring has accepted.\n */\n private clearTombstone(account: string): void {\n try {\n this.fallbackStore.delete(tombstoneKey(account))\n } catch {\n // Best-effort only.\n }\n }\n\n get(account: string): string | undefined {\n // Fallback value first: it is authoritative for any account a failover\n // write touched, and reading the primary first would let the keyring's\n // out-of-date copy win the moment it unlocked.\n const failedOverValue = this.fallbackStore.get(account)\n if (failedOverValue !== undefined) return failedOverValue\n if (this.fallbackStore.has(tombstoneKey(account))) return undefined\n return this.primary.get(account)\n }\n\n has(account: string): boolean {\n if (this.fallbackStore.has(account)) return true\n if (this.fallbackStore.has(tombstoneKey(account))) return false\n return this.primary.has(account)\n }\n\n set(account: string, value: string): void {\n if (value.length === 0) throw new Error('credential value must be non-empty')\n if (this.failedOver) {\n // The primary has already proved it cannot be written, so the fallback\n // is the only destination left.\n this.fallbackStore.set(account, value)\n this.clearTombstone(account)\n return\n }\n try {\n this.primary.set(account, value)\n } catch (error: unknown) {\n // The primary answered its construction probe but cannot take writes\n // (locked collection, vanished secret service). Fail over — sticky, so\n // the remaining accounts of this save do not each hit the same error (or\n // the same unlock prompt) again — and put the value somewhere durable.\n this.failedOver = true\n try {\n this.fallbackStore.set(account, value)\n this.clearTombstone(account)\n } catch (fallbackError: unknown) {\n throw new Error(\n 'credential write failed over, but the fallback store rejected it too: '\n + `${String(fallbackError)} (primary error: ${String(error)})`,\n )\n }\n return\n }\n // The keyring took the write, so it is authoritative for this account\n // again: drop whatever an earlier failed-over session left in the fallback\n // — a value, which would otherwise be read in preference to this write, or\n // a tombstone, which would hide it. Best-effort: failing this cleanup must\n // not fail a save that already succeeded.\n try {\n this.fallbackStore.delete(account)\n } catch {\n // Best-effort purge only.\n }\n this.clearTombstone(account)\n }\n\n delete(account: string): void {\n // The value goes first: it is what a read would serve, and clearing it is\n // required regardless of what the primary does.\n try {\n this.fallbackStore.delete(account)\n } catch {\n // Best-effort; the tombstone below still masks the primary's copy.\n }\n if (this.failedOver) {\n // The primary cannot be written, so its copy cannot be removed now. Leave\n // a tombstone: with no value left in the fallback to shadow it, this\n // marker is the only record that the account is gone, and a later read\n // would otherwise serve the very credential being cleared.\n this.writeTombstone(account)\n return\n }\n try {\n this.primary.delete(account)\n this.clearTombstone(account)\n } catch {\n // A locked collection fails deletes as well as writes (\"no result found\"\n // — wording KeyringBackend's absent-entry no-op filter does not match),\n // and the save route deletes before it writes, so this must trip the\n // same sticky failover a failed write would. The copy we could not remove\n // is masked rather than left readable.\n this.failedOver = true\n this.writeTombstone(account)\n }\n }\n\n /**\n * Record the deletion, or report its failure.\n *\n * Unlike the best-effort cleanups above, a tombstone that cannot be written\n * means the delete silently did not happen and the credential will read back\n * later. That is a failed clear, so it throws rather than being swallowed.\n */\n private writeTombstone(account: string): void {\n this.fallbackStore.set(tombstoneKey(account), TOMBSTONE_VALUE)\n }\n}\n","/**\n * Credential storage abstraction for aishell DSH plugins.\n *\n * Upper layers (aishell-llm's adapter, aishell-credentials' host half)\n * call {@link createCredentialsStore} and get a {@link CredentialsStore} —\n * they never learn which backend is serving. The factory probes backends in\n * priority order (OS keyring first, process memory last) and returns the\n * first that answers. New backends (fingerprint + encrypted file, etc.) slot\n * into the chain without touching callers. A keyring that answers the probe\n * but later rejects writes fails over to the next backend on first failure.\n *\n * This is a tool library, not a DSH plugin — no `dsh.client`, no\n * `cordis.patch.yml`, no `apply`. DSH's own `ctx.credentials` is untouched;\n * user-configured models and `.credentials.yaml` keep working.\n *\n * @module @huaweidevtools/aishell-dsh-credentials-store\n */\n\nimport { KeyringBackend } from './backends/keyring.ts'\nimport { FingerprintBackend } from './backends/fingerprint.ts'\nimport { MemoryBackend } from './backends/memory.ts'\nimport { FailoverStore } from './failover.ts'\n\n/** Options shared by every backend / the factory. */\nexport interface CredentialsStoreConfig {\n /**\n * Backend-scoped identity. For the OS-keyring backend this is the keyring\n * service name; every entry is stored under `new Entry(service, account)`.\n * Defaults to `'aishell-dsh'`.\n */\n readonly service?: string\n /**\n * Explicit directory for the fingerprint encrypted-file backend. When set,\n * overrides the default `$DSH_HOME/credentials` resolution. Callers rarely\n * need this — the host's `DSH_HOME` already places credentials alongside\n * its other data.\n */\n readonly credentialsDir?: string\n}\n\n/**\n * Read/write a named credential. Backends are synchronous and per-call — no\n * cache, so a credential changed from outside is visible on the next `get`.\n * Absent credentials read as `undefined` / `has === false`; a backend that\n * cannot serve (e.g. no D-Bus secret service) degrades the same way rather\n * than throwing on read.\n */\nexport interface CredentialsStore {\n /** Read one credential; `undefined` when absent or backend unavailable. */\n get(account: string): string | undefined\n /** Store one credential. Rejects an empty value; throws on backend errors. */\n set(account: string, value: string): void\n /** Remove one credential; absent is a no-op. Throws on backend errors. */\n delete(account: string): void\n /** Whether a credential is currently stored; `false` when absent or backend unavailable. */\n has(account: string): boolean\n}\n\n/**\n * Probe backends in priority order and return the first that answers.\n *\n * Priority: OS keyring (durable, cross-process) → machine-fingerprint\n * encrypted file (durable, same-machine) → process memory (volatile,\n * last resort). A backend that cannot initialize — no D-Bus secret service\n * on a headless Linux box, keychain locked, etc. — is skipped, not fatal.\n *\n * A keyring that passes the construction probe but is later found unwritable\n * (GNOME login keyring locked: reads come back null, writes fail — the probe\n * cannot see this) is wrapped in a {@link FailoverStore}: its first failed\n * write fails the whole process over to the fingerprint backend, so saving\n * credentials works instead of erroring. The wrapper also records which\n * accounts the keyring must not answer for, so a credential saved while the\n * collection was locked is not shadowed by the keyring's stale copy once it\n * unlocks.\n *\n * @param config - optional service name override.\n * @returns the highest-priority backend that could initialize.\n */\nexport function createCredentialsStore(config: CredentialsStoreConfig = {}): CredentialsStore {\n const keyring: CredentialsStore | undefined = (() => {\n try {\n return new KeyringBackend(config)\n } catch {\n // OS keyring unavailable — try the fingerprint file backend.\n return undefined\n }\n })()\n if (keyring !== undefined) {\n // FingerprintBackend construction probes machine-id (deriveKey); if that\n // fails, MemoryBackend closes the chain — createFallback never throws.\n return new FailoverStore(keyring, { createFallback: () => createFallbackStore(config) })\n }\n return createFallbackStore(config)\n}\n\n/** Probe the durable-file and memory backends behind the keyring. */\nfunction createFallbackStore(config: CredentialsStoreConfig): CredentialsStore {\n try {\n return new FingerprintBackend(config)\n } catch {\n // Machine fingerprint unavailable (no machine ID) — fall back to memory.\n }\n return new MemoryBackend(config)\n}\n\nexport { KeyringBackend, __setKeyringModule } from './backends/keyring.ts'\nexport { FingerprintBackend } from './backends/fingerprint.ts'\nexport { MemoryBackend } from './backends/memory.ts'\nexport { FailoverStore } from './failover.ts'\n"],"mappings":";;;;;;;;AAoBA,MAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAO9C,IAAIA;;AAGJ,SAAgB,mBAAmBC,MAAuC;AACxE,iBAAgB;AACjB;AAED,SAAS,cAA6B;AACpC,KAAI,yBAA6B,iBAAgB,QAAQ,mBAAmB;AAC5E,QAAO;AACR;;;;;;;;;AAUD,IAAa,iBAAb,MAAwD;CAItD,YAAYC,SAAiC,CAAE,GAAE;AAC/C,OAAK,cAAc,OAAO,WAAW;AACrC,OAAK,QAAQ,aAAa,CAAC;AAI3B,MAAI,KAAK,MAAM,KAAK,aAAa,aAAa,aAAa;CAC5D;CAED,IAAIC,SAAqC;AACvC,MAAI;GACF,MAAM,QAAQ,IAAI,KAAK,MAAM,KAAK,aAAa,SAAS,aAAa;AACrE,UAAO;EACR,QAAO;AACN;EACD;CACF;CAED,IAAIA,SAAiBC,OAAqB;AACxC,MAAI,MAAM,WAAW,EAAG,OAAM,IAAI,MAAM;AACxC,MAAI,KAAK,MAAM,KAAK,aAAa,SAAS,YAAY,MAAM;CAC7D;CAED,OAAOD,SAAuB;AAC5B,MAAI;AACF,OAAI,KAAK,MAAM,KAAK,aAAa,SAAS,gBAAgB;EAC3D,SAAQE,OAAgB;AAGvB,QAAK,OAAO,MAAM,CAAC,SAAS,YAAY,KAAK,OAAO,MAAM,CAAC,SAAS,WAAW,CAC7E,OAAM;EAET;CACF;CAED,IAAIF,SAA0B;AAC5B,MAAI;AACF,UAAO,I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+ {"version":3,"file":"index.js","names":["keyringModule: KeyringModule | undefined","mock: KeyringModule | undefined","config: CredentialsStoreConfig","account: string","value: string","error: unknown","machineIdSync: () => string","plaintext: string","data: Buffer","config: CredentialsStoreConfig","entries: Map<string, string>","account: string","value: string","_config: CredentialsStoreConfig","account: string","value: string","account: string","primary: CredentialsStore","options: FailoverStoreOptions","value: string","error: unknown","fallbackError: unknown","config: CredentialsStoreConfig","keyring: CredentialsStore | undefined"],"sources":["../src/backends/keyring.ts","../src/backends/fingerprint.ts","../src/backends/memory.ts","../src/failover.ts","../src/index.ts"],"sourcesContent":["/**\n * OS-keyring backend — the durable, cross-process credential store.\n *\n * Wraps `@napi-rs/keyring` (macOS Keychain / Linux Secret Service / Windows\n * Credential Manager). Values persist across process restarts and reboots\n * because the OS owns the store.\n *\n * ## Why Linux pins the Secret Service store\n *\n * On Linux the binding picks a store itself: Secret Service (gnome-keyring,\n * KWallet, KeePassXC) first, then — silently — the kernel keyutils keyring.\n * That fallback is wrong for credentials, and the binding's README says so:\n * the kernel keyring is \"completely in-memory and will not persist across\n * reboots\". A machine with no Secret Service (a container, CI, a systemd unit\n * with no session bus) would therefore accept credentials, report them stored,\n * and lose them at the next reboot — with `credentialsStored: true` left in\n * the profile pointing at nothing.\n *\n * Pinning `{ linux: { store: 'secret-service' } }` makes an unavailable\n * service throw from the constructor probe instead, so\n * {@link createCredentialsStore} falls through to the machine-fingerprint\n * encrypted file: durable, and honest about where the value lives. Requiring\n * the store is the only way to get that throw — the default selection reports\n * success either way.\n *\n * Native keyring errors are caught: `get`/`has` return `undefined`/`false` so\n * callers degrade gracefully; `set`/`delete` throw a descriptive error so the\n * caller knows the store is unavailable.\n */\n\nimport { createRequire } from 'node:module'\nimport type { CredentialsStore, CredentialsStoreConfig } from '../index.ts'\n\n// Lazily resolved so a missing native binding (the known @napi-rs optional-deps\n// bug, or a platform with no prebuilt binary) throws inside the constructor\n// probe — where createCredentialsStore's try/catch catches it and falls back\n// to FingerprintBackend — instead of crashing at module-load time.\nconst require = createRequire(import.meta.url)\ntype KeyringEntry = {\n getPassword: () => string | null\n setPassword: (value: string) => void\n deletePassword: () => void\n}\n/** Entry options bag; only the Linux store pin is used (see the module note). */\ntype KeyringEntryOptions = { linux?: { store?: 'secret-service' | 'keyutils' } }\ntype KeyringModule = {\n Entry: new (service: string, account: string, options?: KeyringEntryOptions) => KeyringEntry\n}\nlet keyringModule: KeyringModule | undefined\n\n/** @internal Test hook: inject a mock keyring module (vi.mock cannot intercept createRequire). */\nexport function __setKeyringModule(mock: KeyringModule | undefined): void {\n keyringModule = mock\n}\n\nfunction loadKeyring(): KeyringModule {\n if (keyringModule === undefined) keyringModule = require('@napi-rs/keyring') as KeyringModule\n return keyringModule\n}\n\n/**\n * OS-keyring {@link CredentialsStore}. Constructed with a shared service name;\n * every entry is stored under `new Entry(service, account, { linux: { store:\n * 'secret-service' } })`.\n *\n * Construction probes the keyring once — if the native module cannot be loaded\n * (no prebuilt binding for this platform), or the Linux Secret Service is\n * unavailable, it throws and {@link createCredentialsStore} falls back to the\n * next backend. Without the pin the absent-service case does not throw; see\n * the module note.\n */\nexport class KeyringBackend implements CredentialsStore {\n private readonly serviceName: string\n private readonly options: KeyringEntryOptions\n private readonly Entry: KeyringModule['Entry']\n\n constructor(config: CredentialsStoreConfig = {}) {\n this.serviceName = config.service ?? 'aishell-dsh'\n // Required, not preferred: an unavailable Secret Service must throw here so\n // the factory can fall through to a durable backend, rather than silently\n // landing in the kernel keyring's reboot-volatile store.\n this.options = { linux: { store: 'secret-service' } }\n this.Entry = loadKeyring().Entry\n // Probe: a getPassword on a throwaway account exercises the native path.\n new this.Entry(this.serviceName, '__probe__', this.options).getPassword()\n }\n\n get(account: string): string | undefined {\n try {\n const value = new this.Entry(this.serviceName, account, this.options).getPassword()\n return value ?? undefined\n } catch {\n return undefined\n }\n }\n\n set(account: string, value: string): void {\n if (value.length === 0) throw new Error('credential value must be non-empty')\n new this.Entry(this.serviceName, account, this.options).setPassword(value)\n }\n\n delete(account: string): void {\n try {\n new this.Entry(this.serviceName, account, this.options).deletePassword()\n } catch (error: unknown) {\n // deletePassword on an absent entry may throw on some backends;\n // treat that as a no-op rather than an error.\n if (!String(error).includes('not found') && !String(error).includes('no entry')) {\n throw error\n }\n }\n }\n\n has(account: string): boolean {\n try {\n return new this.Entry(this.serviceName, account, this.options).getPassword() !== null\n } catch {\n return false\n }\n }\n}\n","/**\n * Machine-fingerprint-bound encrypted file backend.\n *\n * When the OS keyring is unavailable (headless Linux, Docker, no keyring\n * daemon), credentials are encrypted with a key derived from the machine UUID\n * (node-machine-id) via scrypt, then AES-256-GCM. File format:\n * [12B nonce][16B tag][ciphertext...].\n *\n * The key never touches disk; the ciphertext is useless on a different machine.\n * Same-user-same-machine is trusted. VM cloning copies the machine UUID — a\n * known limitation, not a security hole.\n *\n * Ported from mcp-huaweicloud-ops-deploy/src/auth/fingerprint.ts.\n */\n\nimport { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto'\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport machineIdModule from 'node-machine-id'\nimport type { CredentialsStore, CredentialsStoreConfig } from '../index.ts'\n\nconst machineIdSync: () => string = machineIdModule.machineIdSync\n\nconst SALT = 'aishell-dsh/credentials/v1'\nconst KEY_LEN = 32 // AES-256\nconst NONCE_LEN = 12 // GCM standard (96-bit nonce)\nconst TAG_LEN = 16 // 128-bit auth tag\n\n/** Derive a 32-byte key from the machine UUID via scrypt. */\nfunction deriveKey(): Buffer {\n const machineId = machineIdSync()\n return scryptSync(machineId, SALT, KEY_LEN)\n}\n\n/** Encrypt plaintext → [nonce][tag][ciphertext] as a Buffer. */\nfunction fingerprintEncrypt(plaintext: string): Buffer {\n const key = deriveKey()\n const nonce = randomBytes(NONCE_LEN)\n const cipher = createCipheriv('aes-256-gcm', key, nonce)\n const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n return Buffer.concat([nonce, tag, ciphertext])\n}\n\n/** Decrypt [nonce][tag][ciphertext] → plaintext. Throws on tamper/wrong machine. */\nfunction fingerprintDecrypt(data: Buffer): string {\n if (data.length < NONCE_LEN + TAG_LEN) {\n throw new Error('credentials file corrupted (too short)')\n }\n const key = deriveKey()\n const nonce = data.subarray(0, NONCE_LEN)\n const tag = data.subarray(NONCE_LEN, NONCE_LEN + TAG_LEN)\n const ciphertext = data.subarray(NONCE_LEN + TAG_LEN)\n const decipher = createDecipheriv('aes-256-gcm', key, nonce)\n decipher.setAuthTag(tag)\n const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()])\n return plaintext.toString('utf8')\n}\n\n/**\n * Resolve the directory holding the encrypted credentials file.\n *\n * Priority: an explicit `config.credentialsDir` override → the host's\n * `DSH_HOME` (so credentials live alongside the rest of that host's data —\n * `~/.aishell/credentials` for the desktop app, `~/.dsh/credentials` for the\n * dsh CLI) → a standalone `~/.aishell-dsh` fallback for headless / library\n * use where no DSH host is involved.\n *\n * The `service` config still names the keyring service (and the fallback\n * directory name when neither `credentialsDir` nor `DSH_HOME` is set).\n */\nfunction resolveCredentialsDir(config: CredentialsStoreConfig): string {\n if (config.credentialsDir !== undefined) return config.credentialsDir\n const dshHome = process.env.DSH_HOME\n if (dshHome !== undefined && dshHome.trim() !== '') return join(dshHome, 'credentials')\n const dirName = config.service ?? 'aishell-dsh'\n return join(homedir(), `.${dirName}`)\n}\n\n/**\n * Encrypted-file {@link CredentialsStore}. Each account is one entry in a\n * single JSON map, encrypted as one file under the resolved credentials\n * directory (`$DSH_HOME/credentials/credentials.enc` by default).\n *\n * Construction probes the machine ID + crypto — if `node-machine-id` cannot\n * resolve a UUID, construction throws and the factory falls back to\n * {@link MemoryBackend}.\n */\nexport class FingerprintBackend implements CredentialsStore {\n private readonly filePath: string\n private readonly fileDir: string\n\n constructor(config: CredentialsStoreConfig = {}) {\n this.fileDir = resolveCredentialsDir(config)\n this.filePath = join(this.fileDir, 'credentials.enc')\n // Probe: deriveKey exercises node-machine-id. If it throws, the factory\n // falls back to MemoryBackend.\n deriveKey()\n }\n\n /**\n * Load + decrypt the file into a fresh map. Not cached — credentials are\n * read, used, and dropped so plaintext does not linger in memory between\n * operations. The file I/O + scrypt decrypt per call is acceptable: this is\n * not a hot path (once per chat request, not per token).\n */\n private load(): Map<string, string> {\n if (!existsSync(this.filePath)) return new Map()\n try {\n const encrypted = readFileSync(this.filePath)\n const plaintext = fingerprintDecrypt(encrypted)\n return new Map(Object.entries(JSON.parse(plaintext) as Record<string, string>))\n } catch {\n // Corrupted or wrong machine — treat as empty.\n return new Map()\n }\n }\n\n /** Encrypt + write the map to disk with owner-only permissions. */\n private persist(entries: Map<string, string>): void {\n const plaintext = JSON.stringify(Object.fromEntries(entries))\n mkdirSync(this.fileDir, { recursive: true, mode: 0o700 })\n // Write owner-only (0600); on platforms that ignore the mode (Windows)\n // the file is still encrypted, and ACLs inherit from the profile dir.\n writeFileSync(this.filePath, fingerprintEncrypt(plaintext), { mode: 0o600 })\n }\n\n get(account: string): string | undefined {\n return this.load().get(account)\n }\n\n set(account: string, value: string): void {\n if (value.length === 0) throw new Error('credential value must be non-empty')\n const entries = this.load()\n entries.set(account, value)\n this.persist(entries)\n }\n\n delete(account: string): void {\n const entries = this.load()\n if (entries.delete(account)) {\n this.persist(entries)\n }\n }\n\n has(account: string): boolean {\n return this.load().has(account)\n }\n}\n","/**\n * In-memory backend — the volatile last-resort credential store.\n *\n * Used when the OS keyring is unavailable (no secret service, keychain\n * locked, headless box without D-Bus). Entries live in a process-scoped\n * `Map` and are lost when the process exits — durable enough for a single\n * DSH session, not for persistence.\n *\n * Callers never select this directly; {@link createCredentialsStore} falls\n * back to it when {@link KeyringBackend} cannot initialize.\n */\n\nimport type { CredentialsStore, CredentialsStoreConfig } from '../index.ts'\n\n/** Process-scoped {@link CredentialsStore}; entries vanish on exit. */\nexport class MemoryBackend implements CredentialsStore {\n private readonly entries = new Map<string, string>()\n\n constructor(_config: CredentialsStoreConfig = {}) {\n // Service name is accepted for API symmetry with KeyringBackend but not\n // used: the in-process Map is keyed by account alone, and the factory\n // guarantees only one MemoryBackend is live per credential concern.\n }\n\n get(account: string): string | undefined {\n return this.entries.get(account)\n }\n\n set(account: string, value: string): void {\n if (value.length === 0) throw new Error('credential value must be non-empty')\n this.entries.set(account, value)\n }\n\n delete(account: string): void {\n this.entries.delete(account)\n }\n\n has(account: string): boolean {\n return this.entries.has(account)\n }\n}\n","/**\n * Write-failover wrapper — covers the failure class the construction-time\n * probe chain cannot see.\n *\n * {@link createCredentialsStore} picks a backend by probing at construction\n * time, but the highest-priority backend (the OS keyring) can pass that probe\n * and still reject every real write: a locked GNOME keyring collection reads\n * as `null` (the probe's getPassword does not throw) while setPassword fails.\n * Measured on an isolated D-Bus session:\n *\n * - locked collection, no default alias — read 5 ms → null; write 5 ms →\n * \"Couldn't access platform storage: Secret Service: no result found\"\n * - locked collection, default alias set (the real-desktop shape) — read\n * still null; write blocks on the system unlock prompter and rejects with\n * \"Secret Service: unlock prompt was dismissed\" when canceled\n *\n * So the write path needs its own fallback chain, and it must be sticky: a\n * locked keyring fails every write, so retrying it per call would surface the\n * same error (or the same prompt) once per account a save writes. Deletes trip\n * the same failover: a locked collection rejects them with the same error, and\n * the save route (delete old set → write new set) deletes first — without\n * this, a locked keyring would fail the save before the write failover ever\n * engages.\n *\n * ## Which copy wins\n *\n * A locked collection answers `null` for entries that are really there, so the\n * primary's copy of an account can be arbitrarily out of date while still\n * reading as authoritative. Once it unlocks, that copy would outrank the value\n * the user saved in the meantime — resurrecting a credential the user rotated\n * or cleared, with every later signature using the superseded key.\n *\n * The two backends cannot be compared by recency (neither records one), so the\n * fallback is treated as authoritative for any account it has an opinion\n * about, and the primary answers only when the fallback has none:\n *\n * - **A value in the fallback wins.** It is there because a failover write\n * put it there, and that write is by definition newer than whatever the\n * primary holds. No bookkeeping is needed — the value shadows the primary\n * simply by existing.\n * - **A tombstone means deleted.** A clear whose primary delete failed has\n * nothing to shadow with, so it writes an explicit marker; without one, the\n * stale primary copy would read back as present.\n * - **Otherwise the primary answers**, which is the ordinary healthy path.\n *\n * A successful primary write or delete clears both the fallback value and the\n * tombstone, handing authority back to the keyring.\n *\n * Recording deletion this way — rather than marking accounts \"stale\" on every\n * failover write — keeps the value and its shadow in one place. A mark set by a\n * write would have to be cleared in lockstep with the value, and a mark left\n * behind after its value was gone would make a perfect keyring credential read\n * as *absent* rather than merely stale.\n *\n * ## Why the record is persisted, not held in memory\n *\n * The state it describes outlives the store: the failure is \"the keyring is\n * locked now\", and the read that would resurrect the credential happens in a\n * later session, after it has unlocked. It is therefore stored in the fallback\n * backend itself — the encrypted file in practice, and merely the process in\n * the memory-backed last resort, where the failover is no more durable either.\n * Keys carry a NUL prefix, which no real credential account can collide with.\n *\n * ## Cost on the healthy path\n *\n * The fallback is consulted on every read (once for a value, once for a\n * tombstone). On a machine whose keyring has never failed the fallback has\n * written nothing, so its file does not exist and both lookups are\n * sub-millisecond `existsSync` misses (measured 0.02-0.4 ms). Where a fallback\n * file does exist, each lookup decrypts it — the read-through this replaced\n * already paid one decrypt per miss.\n *\n * The fallback is built on the first read rather than the first failed write,\n * which a machine with a working keyring pays once per store: ~97 ms, almost\n * all of it the fingerprint backend's scrypt probe (measured). It is lazy and\n * cached, so later reads are unaffected.\n *\n * @module\n */\n\nimport type { CredentialsStore } from './index.ts'\n\n/**\n * Account-name prefix marking an account as deleted while the primary was\n * unreachable.\n *\n * The NUL byte cannot appear in a real account name (`HW_ACCESS_KEY`,\n * `HW_SECRET_KEY`, `HW_SECURITY_TOKEN`), so a tombstone can never be confused\n * with a credential. Tombstones are only ever written to the fallback, never\n * to the keyring.\n */\nconst TOMBSTONE_PREFIX = '\\u0000aishell:tombstone:'\n\n/** The fallback key recording that `account` was deleted. */\nconst tombstoneKey = (account: string): string => TOMBSTONE_PREFIX + account\n\n/** Tombstone value; never read, only tested for presence. */\nconst TOMBSTONE_VALUE = '1'\n\n/** Options for {@link FailoverStore}. */\nexport interface FailoverStoreOptions {\n /**\n * Builds the store that takes over when the primary fails a write. Called\n * at most once, lazily, on first need — a read miss or the first failed\n * write — so a healthy keyring never pays for constructing it. Must not\n * throw: the factory's closure ends in MemoryBackend.\n */\n readonly createFallback: () => CredentialsStore\n}\n\n/**\n * A {@link CredentialsStore} that delegates to a primary until the primary\n * fails a write, then fails over — for the life of this store — to a\n * fallback supplied by {@link FailoverStoreOptions.createFallback}.\n *\n * Stickiness is per instance, not per process: each plugin that consumes\n * credentials builds its own store, so one instance failing over does not stop\n * another from trying the primary. That is intended — the flag only exists to\n * avoid re-hitting a primary already known to be unwritable from *this* store,\n * and a second instance's attempt is one probe rather than a policy decision.\n * Correctness across instances comes from the persisted record, not the flag.\n *\n * Constructed by {@link createCredentialsStore} around a KeyringBackend whose\n * construction probe passed; not meant for direct use by upper layers.\n */\nexport class FailoverStore implements CredentialsStore {\n private readonly primary: CredentialsStore\n private readonly createFallback: () => CredentialsStore\n private fallback: CredentialsStore | undefined\n /** Set by the first failed primary write; routes writes thereafter. */\n private failedOver = false\n\n constructor(primary: CredentialsStore, options: FailoverStoreOptions) {\n this.primary = primary\n this.createFallback = options.createFallback\n }\n\n /** The lazily built fallback; constructed at most once per store. */\n private get fallbackStore(): CredentialsStore {\n if (this.fallback === undefined) this.fallback = this.createFallback()\n return this.fallback\n }\n\n /**\n * Drop the tombstone for `account`, if any.\n *\n * Paired with the value purge on every path that hands authority back to the\n * primary. Best-effort: a tombstone that outlives its purpose costs one extra\n * fallback lookup, which must never fail a write the keyring has accepted.\n */\n private clearTombstone(account: string): void {\n try {\n this.fallbackStore.delete(tombstoneKey(account))\n } catch {\n // Best-effort only.\n }\n }\n\n get(account: string): string | undefined {\n // Fallback value first: it is authoritative for any account a failover\n // write touched, and reading the primary first would let the keyring's\n // out-of-date copy win the moment it unlocked.\n const failedOverValue = this.fallbackStore.get(account)\n if (failedOverValue !== undefined) return failedOverValue\n if (this.fallbackStore.has(tombstoneKey(account))) return undefined\n return this.primary.get(account)\n }\n\n has(account: string): boolean {\n if (this.fallbackStore.has(account)) return true\n if (this.fallbackStore.has(tombstoneKey(account))) return false\n return this.primary.has(account)\n }\n\n set(account: string, value: string): void {\n if (value.length === 0) throw new Error('credential value must be non-empty')\n if (this.failedOver) {\n // The primary has already proved it cannot be written, so the fallback\n // is the only destination left.\n this.fallbackStore.set(account, value)\n this.clearTombstone(account)\n return\n }\n try {\n this.primary.set(account, value)\n } catch (error: unknown) {\n // The primary answered its construction probe but cannot take writes\n // (locked collection, vanished secret service). Fail over — sticky, so\n // the remaining accounts of this save do not each hit the same error (or\n // the same unlock prompt) again — and put the value somewhere durable.\n this.failedOver = true\n try {\n this.fallbackStore.set(account, value)\n this.clearTombstone(account)\n } catch (fallbackError: unknown) {\n throw new Error(\n 'credential write failed over, but the fallback store rejected it too: '\n + `${String(fallbackError)} (primary error: ${String(error)})`,\n )\n }\n return\n }\n // The keyring took the write, so it is authoritative for this account\n // again: drop whatever an earlier failed-over session left in the fallback\n // — a value, which would otherwise be read in preference to this write, or\n // a tombstone, which would hide it. Best-effort: failing this cleanup must\n // not fail a save that already succeeded.\n try {\n this.fallbackStore.delete(account)\n } catch {\n // Best-effort purge only.\n }\n this.clearTombstone(account)\n }\n\n delete(account: string): void {\n // The value goes first: it is what a read would serve, and clearing it is\n // required regardless of what the primary does.\n try {\n this.fallbackStore.delete(account)\n } catch {\n // Best-effort; the tombstone below still masks the primary's copy.\n }\n if (this.failedOver) {\n // The primary cannot be written, so its copy cannot be removed now. Leave\n // a tombstone: with no value left in the fallback to shadow it, this\n // marker is the only record that the account is gone, and a later read\n // would otherwise serve the very credential being cleared.\n this.writeTombstone(account)\n return\n }\n try {\n this.primary.delete(account)\n this.clearTombstone(account)\n } catch {\n // A locked collection fails deletes as well as writes (\"no result found\"\n // — wording KeyringBackend's absent-entry no-op filter does not match),\n // and the save route deletes before it writes, so this must trip the\n // same sticky failover a failed write would. The copy we could not remove\n // is masked rather than left readable.\n this.failedOver = true\n this.writeTombstone(account)\n }\n }\n\n /**\n * Record the deletion, or report its failure.\n *\n * Unlike the best-effort cleanups above, a tombstone that cannot be written\n * means the delete silently did not happen and the credential will read back\n * later. That is a failed clear, so it throws rather than being swallowed.\n */\n private writeTombstone(account: string): void {\n this.fallbackStore.set(tombstoneKey(account), TOMBSTONE_VALUE)\n }\n}\n","/**\n * Credential storage abstraction for aishell DSH plugins.\n *\n * Upper layers (aishell-llm's adapter, aishell-credentials' host half)\n * call {@link createCredentialsStore} and get a {@link CredentialsStore} —\n * they never learn which backend is serving. The factory probes backends in\n * priority order (OS keyring first, process memory last) and returns the\n * first that answers. New backends (fingerprint + encrypted file, etc.) slot\n * into the chain without touching callers. A keyring that answers the probe\n * but later rejects writes fails over to the next backend on first failure.\n *\n * This is a tool library, not a DSH plugin — no `dsh.client`, no\n * `cordis.patch.yml`, no `apply`. DSH's own `ctx.credentials` is untouched;\n * user-configured models and `.credentials.yaml` keep working.\n *\n * @module @huaweidevtools/aishell-dsh-credentials-store\n */\n\nimport { KeyringBackend } from './backends/keyring.ts'\nimport { FingerprintBackend } from './backends/fingerprint.ts'\nimport { MemoryBackend } from './backends/memory.ts'\nimport { FailoverStore } from './failover.ts'\n\n/** Options shared by every backend / the factory. */\nexport interface CredentialsStoreConfig {\n /**\n * Backend-scoped identity. For the OS-keyring backend this is the keyring\n * service name; every entry is stored under `new Entry(service, account)`.\n * Defaults to `'aishell-dsh'`.\n */\n readonly service?: string\n /**\n * Explicit directory for the fingerprint encrypted-file backend. When set,\n * overrides the default `$DSH_HOME/credentials` resolution. Callers rarely\n * need this — the host's `DSH_HOME` already places credentials alongside\n * its other data.\n */\n readonly credentialsDir?: string\n}\n\n/**\n * Read/write a named credential. Backends are synchronous and per-call — no\n * cache, so a credential changed from outside is visible on the next `get`.\n * Absent credentials read as `undefined` / `has === false`; a backend that\n * cannot serve (e.g. no D-Bus secret service) degrades the same way rather\n * than throwing on read.\n */\nexport interface CredentialsStore {\n /** Read one credential; `undefined` when absent or backend unavailable. */\n get(account: string): string | undefined\n /** Store one credential. Rejects an empty value; throws on backend errors. */\n set(account: string, value: string): void\n /** Remove one credential; absent is a no-op. Throws on backend errors. */\n delete(account: string): void\n /** Whether a credential is currently stored; `false` when absent or backend unavailable. */\n has(account: string): boolean\n}\n\n/**\n * Probe backends in priority order and return the first that answers.\n *\n * Priority: OS keyring (durable, cross-process) → machine-fingerprint\n * encrypted file (durable, same-machine) → process memory (volatile,\n * last resort). A backend that cannot initialize — no D-Bus secret service\n * on a headless Linux box, keychain locked, etc. — is skipped, not fatal.\n *\n * A keyring that passes the construction probe but is later found unwritable\n * (GNOME login keyring locked: reads come back null, writes fail — the probe\n * cannot see this) is wrapped in a {@link FailoverStore}: its first failed\n * write fails the whole process over to the fingerprint backend, so saving\n * credentials works instead of erroring. The wrapper also records which\n * accounts the keyring must not answer for, so a credential saved while the\n * collection was locked is not shadowed by the keyring's stale copy once it\n * unlocks.\n *\n * @param config - optional service name override.\n * @returns the highest-priority backend that could initialize.\n */\nexport function createCredentialsStore(config: CredentialsStoreConfig = {}): CredentialsStore {\n const keyring: CredentialsStore | undefined = (() => {\n try {\n return new KeyringBackend(config)\n } catch {\n // OS keyring unavailable — try the fingerprint file backend.\n return undefined\n }\n })()\n if (keyring !== undefined) {\n // FingerprintBackend construction probes machine-id (deriveKey); if that\n // fails, MemoryBackend closes the chain — createFallback never throws.\n return new FailoverStore(keyring, { createFallback: () => createFallbackStore(config) })\n }\n return createFallbackStore(config)\n}\n\n/** Probe the durable-file and memory backends behind the keyring. */\nfunction createFallbackStore(config: CredentialsStoreConfig): CredentialsStore {\n try {\n return new FingerprintBackend(config)\n } catch {\n // Machine fingerprint unavailable (no machine ID) — fall back to memory.\n }\n return new MemoryBackend(config)\n}\n\nexport { KeyringBackend, __setKeyringModule } from './backends/keyring.ts'\nexport { FingerprintBackend } from './backends/fingerprint.ts'\nexport { MemoryBackend } from './backends/memory.ts'\n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I;AACF,SAAK,cAAc,IAAI,SAAS,MAAM;AACtC,SAAK,eAAe,QAAQ;GAC7B,SAAQC,eAAwB;AAC/B,UAAM,IAAI,OAEL,wEAAE,OAAO,cAAc,CAAC,mBAAmB,OAAO,MAAM,CAAC;GAE/D;AACD;EACD;AAMD,MAAI;AACF,QAAK,cAAc,OAAO,QAAQ;EACnC,QAAO,CAEP;AACD,OAAK,eAAe,QAAQ;CAC7B;CAED,OAAOL,SAAuB;AAG5B,MAAI;AACF,QAAK,cAAc,OAAO,QAAQ;EACnC,QAAO,CAEP;AACD,MAAI,KAAK,YAAY;AAKnB,QAAK,eAAe,QAAQ;AAC5B;EACD;AACD,MAAI;AACF,QAAK,QAAQ,OAAO,QAAQ;AAC5B,QAAK,eAAe,QAAQ;EAC7B,QAAO;AAMN,QAAK,aAAa;AAClB,QAAK,eAAe,QAAQ;EAC7B;CACF;;;;;;;;CASD,eAAuBA,SAAuB;AAC5C,OAAK,cAAc,IAAI,aAAa,QAAQ,EAAE,gBAAgB;CAC/D;AACF;;;;;;;;;;;;;;;;;;;;;;;;ACjLD,SAAgB,uBAAuBM,SAAiC,CAAE,GAAoB;CAC5F,MAAMC,UAAwC,CAAC,MAAM;AACnD,MAAI;AACF,UAAO,IAAI,eAAe;EAC3B,QAAO;AAEN;EACD;CACF,IAAG;AACJ,KAAI,mBAGF,QAAO,IAAI,cAAc,SAAS,EAAE,gBAAgB,MAAM,oBAAoB,OAAO,CAAE;AAEzF,QAAO,oBAAoB,OAAO;AACnC;;AAGD,SAAS,oBAAoBD,QAAkD;AAC7E,KAAI;AACF,SAAO,IAAI,mBAAmB;CAC/B,QAAO,CAEP;AACD,QAAO,IAAI,cAAc;AAC1B"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@huaweidevtools/aishell-dsh-credentials-store",
3
3
  "description": "Credential storage + SDK-HMAC-SHA256 signing for aishell DSH plugins",
4
- "version": "0.0.2",
4
+ "version": "0.0.4",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -33,7 +33,7 @@
33
33
  ],
34
34
  "license": "Apache-2.0",
35
35
  "dependencies": {
36
- "@napi-rs/keyring": "^2.0.0",
36
+ "@napi-rs/keyring": "^2.1.1",
37
37
  "node-machine-id": "^1.1.12"
38
38
  },
39
39
  "scripts": {