@huaweidevtools/aishell-dsh-credentials-store 0.0.0-stage → 0.0.1-beta.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined in Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is derived from (or based upon) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Huawei Cloud AI Shell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,64 @@
1
- # Temporary Holding Version
1
+ # @huaweidevtools/aishell-dsh-credentials-store
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Credential storage abstraction for aishell DSH plugins. Upper layers call `createCredentialsStore()` and receive a `CredentialsStore` — they never learn which backend is serving. The factory probes backends in priority order and returns the first that answers.
4
+
5
+ This is a **tool library**, not a DSH plugin — no `dsh.client`, no `cordis.patch.yml`, no `apply`.
6
+
7
+ ## Backends
8
+
9
+ | Priority | Backend | Durable? | Requirement |
10
+ |---|---|---|---|
11
+ | 1 | `KeyringBackend` | Yes (cross-process, survives reboot) | OS keyring reachable (macOS Keychain / Linux libsecret / Windows Credential Manager) |
12
+ | 2 | `FingerprintBackend` | Yes (same-machine, survives reboot) | `node-machine-id` can resolve a machine UUID |
13
+ | 3 | `MemoryBackend` | No (process-scoped) | None — always available, last resort |
14
+
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
+
17
+ ## Write failover
18
+
19
+ 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:
20
+
21
+ - The first failed `set`/`delete` fails over, **stickily**, to the fingerprint backend for the life of that store instance. Sticky because a locked collection fails every write; retrying per call would surface the same error — or the same unlock prompt — once per account a save writes. `delete` trips it too, because the save route deletes the old set before writing the new one.
22
+ - **Which copy wins.** A locked collection reports `null` for entries that really exist, so its copy can be arbitrarily stale; once it unlocks, that copy would otherwise outrank the value saved in the meantime — resurrecting a credential the user had rotated or cleared. The two backends cannot be compared by recency, so the fallback is authoritative for any account it has an opinion about: a value there wins (it got there by a failover write, which is newer by definition), a tombstone there means deleted, and otherwise the keyring answers. A failed-over clear writes a tombstone because it has no value to shadow the keyring's copy with.
23
+ - A successful keyring write or delete clears the fallback value *and* the tombstone, handing authority back to the keyring — a leftover tombstone would make a good keyring credential read as absent.
24
+ - Reads before any failure fall through to the fallback after a keyring miss, so a credential stored by a previous session's failover stays visible.
25
+
26
+ The record lives in the fallback backend — the encrypted file in practice — so it survives the restart the failure mode requires: the keyring is locked *now*, and the read that would resurrect the credential happens in a later session, after it has unlocked. On a machine whose keyring has never failed the fallback has written nothing, and each read pays a sub-millisecond check against an absent file.
27
+
28
+ ## Usage
29
+
30
+ ```typescript
31
+ import { createCredentialsStore } from '@huaweidevtools/aishell-dsh-credentials-store'
32
+
33
+ const store = createCredentialsStore() // probes keyring → fingerprint → memory
34
+ store.set('HW_ACCESS_KEY', 'LTAIxxxx') // durable if keyring or fingerprint is up
35
+ const ak = store.get('HW_ACCESS_KEY') // 'LTAIxxxx'
36
+ store.has('HW_ACCESS_KEY') // true
37
+ store.delete('HW_ACCESS_KEY')
38
+ ```
39
+
40
+ A custom service name isolates entries from other applications sharing the same keyring:
41
+
42
+ ```typescript
43
+ const store = createCredentialsStore({ service: 'my-app' })
44
+ ```
45
+
46
+ ## Security properties
47
+
48
+ - **No plaintext files**: nothing on disk is readable with `cat`.
49
+ - **OS-encrypted at rest**: Keychain (AES), libsecret (DPAPI/GNOME keyring), Credential Manager (DPAPI).
50
+ - **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
+ - **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.
53
+
54
+ ## Platform support (KeyringBackend)
55
+
56
+ | Platform | Backend | Requirement |
57
+ |---|---|---|
58
+ | macOS | Keychain | None (built in) |
59
+ | Linux | libsecret | `gnome-keyring` or `kwallet` running, plus `libsecret-1-dev` at build time |
60
+ | Windows | Credential Manager | None (built in) |
61
+
62
+ ## License
63
+
64
+ Apache License 2.0. See [LICENSE](../../LICENSE).
package/lib/index.d.ts ADDED
@@ -0,0 +1,208 @@
1
+ //#region src/backends/keyring.d.ts
2
+
3
+ type KeyringEntry = {
4
+ getPassword: () => string | null;
5
+ setPassword: (value: string) => void;
6
+ deletePassword: () => void;
7
+ };
8
+ type KeyringModule = {
9
+ Entry: new (service: string, account: string) => KeyringEntry;
10
+ };
11
+ /** @internal Test hook: inject a mock keyring module (vi.mock cannot intercept createRequire). */
12
+ declare function __setKeyringModule(mock: KeyringModule | undefined): void;
13
+ /**
14
+ * OS-keyring {@link CredentialsStore}. Constructed with a shared service name;
15
+ * every entry is stored under `new Entry(service, account)`.
16
+ *
17
+ * 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.
20
+ */
21
+ declare class KeyringBackend implements CredentialsStore {
22
+ private readonly serviceName;
23
+ private readonly Entry;
24
+ constructor(config?: CredentialsStoreConfig);
25
+ get(account: string): string | undefined;
26
+ set(account: string, value: string): void;
27
+ delete(account: string): void;
28
+ has(account: string): boolean;
29
+ } //#endregion
30
+ //#region src/backends/fingerprint.d.ts
31
+
32
+ /**
33
+ * Encrypted-file {@link CredentialsStore}. Each account is one entry in a
34
+ * single JSON map, encrypted as one file under the resolved credentials
35
+ * directory (`$DSH_HOME/credentials/credentials.enc` by default).
36
+ *
37
+ * Construction probes the machine ID + crypto — if `node-machine-id` cannot
38
+ * resolve a UUID, construction throws and the factory falls back to
39
+ * {@link MemoryBackend}.
40
+ */
41
+ declare class FingerprintBackend implements CredentialsStore {
42
+ private readonly filePath;
43
+ private readonly fileDir;
44
+ constructor(config?: CredentialsStoreConfig);
45
+ /**
46
+ * Load + decrypt the file into a fresh map. Not cached — credentials are
47
+ * read, used, and dropped so plaintext does not linger in memory between
48
+ * operations. The file I/O + scrypt decrypt per call is acceptable: this is
49
+ * not a hot path (once per chat request, not per token).
50
+ */
51
+ private load;
52
+ /** Encrypt + write the map to disk with owner-only permissions. */
53
+ private persist;
54
+ get(account: string): string | undefined;
55
+ set(account: string, value: string): void;
56
+ delete(account: string): void;
57
+ has(account: string): boolean;
58
+ } //#endregion
59
+ //#region src/backends/memory.d.ts
60
+
61
+ //# sourceMappingURL=fingerprint.d.ts.map
62
+ /** Process-scoped {@link CredentialsStore}; entries vanish on exit. */
63
+ declare class MemoryBackend implements CredentialsStore {
64
+ private readonly entries;
65
+ constructor(_config?: CredentialsStoreConfig);
66
+ get(account: string): string | undefined;
67
+ set(account: string, value: string): void;
68
+ delete(account: string): void;
69
+ has(account: string): boolean;
70
+ }
71
+
72
+ //#endregion
73
+ //#region src/failover.d.ts
74
+ //# sourceMappingURL=memory.d.ts.map
75
+
76
+ /** Options for {@link FailoverStore}. */
77
+ interface FailoverStoreOptions {
78
+ /**
79
+ * Builds the store that takes over when the primary fails a write. Called
80
+ * at most once, lazily, on first need — a read miss or the first failed
81
+ * write — so a healthy keyring never pays for constructing it. Must not
82
+ * throw: the factory's closure ends in MemoryBackend.
83
+ */
84
+ readonly createFallback: () => CredentialsStore;
85
+ }
86
+ /**
87
+ * A {@link CredentialsStore} that delegates to a primary until the primary
88
+ * fails a write, then fails over — for the life of this store — to a
89
+ * fallback supplied by {@link FailoverStoreOptions.createFallback}.
90
+ *
91
+ * Stickiness is per instance, not per process: each plugin that consumes
92
+ * credentials builds its own store, so one instance failing over does not stop
93
+ * another from trying the primary. That is intended — the flag only exists to
94
+ * avoid re-hitting a primary already known to be unwritable from *this* store,
95
+ * and a second instance's attempt is one probe rather than a policy decision.
96
+ * Correctness across instances comes from the persisted record, not the flag.
97
+ *
98
+ * Constructed by {@link createCredentialsStore} around a KeyringBackend whose
99
+ * construction probe passed; not meant for direct use by upper layers.
100
+ */
101
+ declare class FailoverStore implements CredentialsStore {
102
+ private readonly primary;
103
+ private readonly createFallback;
104
+ private fallback;
105
+ /** Set by the first failed primary write; routes writes thereafter. */
106
+ private failedOver;
107
+ constructor(primary: CredentialsStore, options: FailoverStoreOptions);
108
+ /** The lazily built fallback; constructed at most once per store. */
109
+ private get fallbackStore();
110
+ /**
111
+ * Drop the tombstone for `account`, if any.
112
+ *
113
+ * Paired with the value purge on every path that hands authority back to the
114
+ * primary. Best-effort: a tombstone that outlives its purpose costs one extra
115
+ * fallback lookup, which must never fail a write the keyring has accepted.
116
+ */
117
+ private clearTombstone;
118
+ get(account: string): string | undefined;
119
+ has(account: string): boolean;
120
+ set(account: string, value: string): void;
121
+ delete(account: string): void;
122
+ /**
123
+ * Record the deletion, or report its failure.
124
+ *
125
+ * Unlike the best-effort cleanups above, a tombstone that cannot be written
126
+ * means the delete silently did not happen and the credential will read back
127
+ * later. That is a failed clear, so it throws rather than being swallowed.
128
+ */
129
+ private writeTombstone;
130
+ } //#endregion
131
+ //#region src/index.d.ts
132
+
133
+ //# sourceMappingURL=failover.d.ts.map
134
+ /**
135
+ * Credential storage abstraction for aishell DSH plugins.
136
+ *
137
+ * Upper layers (aishell-llm's adapter, aishell-credentials' host half)
138
+ * call {@link createCredentialsStore} and get a {@link CredentialsStore} —
139
+ * they never learn which backend is serving. The factory probes backends in
140
+ * priority order (OS keyring first, process memory last) and returns the
141
+ * first that answers. New backends (fingerprint + encrypted file, etc.) slot
142
+ * into the chain without touching callers. A keyring that answers the probe
143
+ * but later rejects writes fails over to the next backend on first failure.
144
+ *
145
+ * This is a tool library, not a DSH plugin — no `dsh.client`, no
146
+ * `cordis.patch.yml`, no `apply`. DSH's own `ctx.credentials` is untouched;
147
+ * user-configured models and `.credentials.yaml` keep working.
148
+ *
149
+ * @module @huaweidevtools/aishell-dsh-credentials-store
150
+ */
151
+ /** Options shared by every backend / the factory. */
152
+ interface CredentialsStoreConfig {
153
+ /**
154
+ * Backend-scoped identity. For the OS-keyring backend this is the keyring
155
+ * service name; every entry is stored under `new Entry(service, account)`.
156
+ * Defaults to `'aishell-dsh'`.
157
+ */
158
+ readonly service?: string;
159
+ /**
160
+ * Explicit directory for the fingerprint encrypted-file backend. When set,
161
+ * overrides the default `$DSH_HOME/credentials` resolution. Callers rarely
162
+ * need this — the host's `DSH_HOME` already places credentials alongside
163
+ * its other data.
164
+ */
165
+ readonly credentialsDir?: string;
166
+ }
167
+ /**
168
+ * Read/write a named credential. Backends are synchronous and per-call — no
169
+ * cache, so a credential changed from outside is visible on the next `get`.
170
+ * Absent credentials read as `undefined` / `has === false`; a backend that
171
+ * cannot serve (e.g. no D-Bus secret service) degrades the same way rather
172
+ * than throwing on read.
173
+ */
174
+ interface CredentialsStore {
175
+ /** Read one credential; `undefined` when absent or backend unavailable. */
176
+ get(account: string): string | undefined;
177
+ /** Store one credential. Rejects an empty value; throws on backend errors. */
178
+ set(account: string, value: string): void;
179
+ /** Remove one credential; absent is a no-op. Throws on backend errors. */
180
+ delete(account: string): void;
181
+ /** Whether a credential is currently stored; `false` when absent or backend unavailable. */
182
+ has(account: string): boolean;
183
+ }
184
+ /**
185
+ * Probe backends in priority order and return the first that answers.
186
+ *
187
+ * Priority: OS keyring (durable, cross-process) → machine-fingerprint
188
+ * encrypted file (durable, same-machine) → process memory (volatile,
189
+ * last resort). A backend that cannot initialize — no D-Bus secret service
190
+ * on a headless Linux box, keychain locked, etc. — is skipped, not fatal.
191
+ *
192
+ * A keyring that passes the construction probe but is later found unwritable
193
+ * (GNOME login keyring locked: reads come back null, writes fail — the probe
194
+ * cannot see this) is wrapped in a {@link FailoverStore}: its first failed
195
+ * write fails the whole process over to the fingerprint backend, so saving
196
+ * credentials works instead of erroring. The wrapper also records which
197
+ * accounts the keyring must not answer for, so a credential saved while the
198
+ * collection was locked is not shadowed by the keyring's stale copy once it
199
+ * unlocks.
200
+ *
201
+ * @param config - optional service name override.
202
+ * @returns the highest-priority backend that could initialize.
203
+ */
204
+ declare function createCredentialsStore(config?: CredentialsStoreConfig): CredentialsStore;
205
+
206
+ //#endregion
207
+ export { CredentialsStore, CredentialsStoreConfig, FailoverStore, FingerprintBackend, KeyringBackend, MemoryBackend, __setKeyringModule, createCredentialsStore };
208
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +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"}
package/lib/index.js ADDED
@@ -0,0 +1,357 @@
1
+ import { createRequire } from "node:module";
2
+ import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import machineIdModule from "node-machine-id";
7
+
8
+ //#region src/backends/keyring.ts
9
+ const require = createRequire(import.meta.url);
10
+ let keyringModule;
11
+ /** @internal Test hook: inject a mock keyring module (vi.mock cannot intercept createRequire). */
12
+ function __setKeyringModule(mock) {
13
+ keyringModule = mock;
14
+ }
15
+ function loadKeyring() {
16
+ if (keyringModule === void 0) keyringModule = require("@napi-rs/keyring");
17
+ return keyringModule;
18
+ }
19
+ /**
20
+ * OS-keyring {@link CredentialsStore}. Constructed with a shared service name;
21
+ * every entry is stored under `new Entry(service, account)`.
22
+ *
23
+ * 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.
26
+ */
27
+ var KeyringBackend = class {
28
+ constructor(config = {}) {
29
+ this.serviceName = config.service ?? "aishell-dsh";
30
+ this.Entry = loadKeyring().Entry;
31
+ new this.Entry(this.serviceName, "__probe__").getPassword();
32
+ }
33
+ get(account) {
34
+ try {
35
+ const value = new this.Entry(this.serviceName, account).getPassword();
36
+ return value ?? void 0;
37
+ } catch {
38
+ return void 0;
39
+ }
40
+ }
41
+ set(account, value) {
42
+ if (value.length === 0) throw new Error("credential value must be non-empty");
43
+ new this.Entry(this.serviceName, account).setPassword(value);
44
+ }
45
+ delete(account) {
46
+ try {
47
+ new this.Entry(this.serviceName, account).deletePassword();
48
+ } catch (error) {
49
+ if (!String(error).includes("not found") && !String(error).includes("no entry")) throw error;
50
+ }
51
+ }
52
+ has(account) {
53
+ try {
54
+ return new this.Entry(this.serviceName, account).getPassword() !== null;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ };
60
+
61
+ //#endregion
62
+ //#region src/backends/fingerprint.ts
63
+ const machineIdSync = machineIdModule.machineIdSync;
64
+ const SALT = "aishell-dsh/credentials/v1";
65
+ const KEY_LEN = 32;
66
+ const NONCE_LEN = 12;
67
+ const TAG_LEN = 16;
68
+ /** Derive a 32-byte key from the machine UUID via scrypt. */
69
+ function deriveKey() {
70
+ const machineId = machineIdSync();
71
+ return scryptSync(machineId, SALT, KEY_LEN);
72
+ }
73
+ /** Encrypt plaintext → [nonce][tag][ciphertext] as a Buffer. */
74
+ function fingerprintEncrypt(plaintext) {
75
+ const key = deriveKey();
76
+ const nonce = randomBytes(NONCE_LEN);
77
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
78
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
79
+ const tag = cipher.getAuthTag();
80
+ return Buffer.concat([
81
+ nonce,
82
+ tag,
83
+ ciphertext
84
+ ]);
85
+ }
86
+ /** Decrypt [nonce][tag][ciphertext] → plaintext. Throws on tamper/wrong machine. */
87
+ function fingerprintDecrypt(data) {
88
+ if (data.length < NONCE_LEN + TAG_LEN) throw new Error("credentials file corrupted (too short)");
89
+ const key = deriveKey();
90
+ const nonce = data.subarray(0, NONCE_LEN);
91
+ const tag = data.subarray(NONCE_LEN, NONCE_LEN + TAG_LEN);
92
+ const ciphertext = data.subarray(NONCE_LEN + TAG_LEN);
93
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce);
94
+ decipher.setAuthTag(tag);
95
+ const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
96
+ return plaintext.toString("utf8");
97
+ }
98
+ /**
99
+ * Resolve the directory holding the encrypted credentials file.
100
+ *
101
+ * Priority: an explicit `config.credentialsDir` override → the host's
102
+ * `DSH_HOME` (so credentials live alongside the rest of that host's data —
103
+ * `~/.aishell/credentials` for the desktop app, `~/.dsh/credentials` for the
104
+ * dsh CLI) → a standalone `~/.aishell-dsh` fallback for headless / library
105
+ * use where no DSH host is involved.
106
+ *
107
+ * The `service` config still names the keyring service (and the fallback
108
+ * directory name when neither `credentialsDir` nor `DSH_HOME` is set).
109
+ */
110
+ function resolveCredentialsDir(config) {
111
+ if (config.credentialsDir !== void 0) return config.credentialsDir;
112
+ const dshHome = process.env.DSH_HOME;
113
+ if (dshHome !== void 0 && dshHome.trim() !== "") return join(dshHome, "credentials");
114
+ const dirName = config.service ?? "aishell-dsh";
115
+ return join(homedir(), `.${dirName}`);
116
+ }
117
+ /**
118
+ * Encrypted-file {@link CredentialsStore}. Each account is one entry in a
119
+ * single JSON map, encrypted as one file under the resolved credentials
120
+ * directory (`$DSH_HOME/credentials/credentials.enc` by default).
121
+ *
122
+ * Construction probes the machine ID + crypto — if `node-machine-id` cannot
123
+ * resolve a UUID, construction throws and the factory falls back to
124
+ * {@link MemoryBackend}.
125
+ */
126
+ var FingerprintBackend = class {
127
+ constructor(config = {}) {
128
+ this.fileDir = resolveCredentialsDir(config);
129
+ this.filePath = join(this.fileDir, "credentials.enc");
130
+ deriveKey();
131
+ }
132
+ /**
133
+ * Load + decrypt the file into a fresh map. Not cached — credentials are
134
+ * read, used, and dropped so plaintext does not linger in memory between
135
+ * operations. The file I/O + scrypt decrypt per call is acceptable: this is
136
+ * not a hot path (once per chat request, not per token).
137
+ */
138
+ load() {
139
+ if (!existsSync(this.filePath)) return new Map();
140
+ try {
141
+ const encrypted = readFileSync(this.filePath);
142
+ const plaintext = fingerprintDecrypt(encrypted);
143
+ return new Map(Object.entries(JSON.parse(plaintext)));
144
+ } catch {
145
+ return new Map();
146
+ }
147
+ }
148
+ /** Encrypt + write the map to disk with owner-only permissions. */
149
+ persist(entries) {
150
+ const plaintext = JSON.stringify(Object.fromEntries(entries));
151
+ mkdirSync(this.fileDir, {
152
+ recursive: true,
153
+ mode: 448
154
+ });
155
+ writeFileSync(this.filePath, fingerprintEncrypt(plaintext), { mode: 384 });
156
+ }
157
+ get(account) {
158
+ return this.load().get(account);
159
+ }
160
+ set(account, value) {
161
+ if (value.length === 0) throw new Error("credential value must be non-empty");
162
+ const entries = this.load();
163
+ entries.set(account, value);
164
+ this.persist(entries);
165
+ }
166
+ delete(account) {
167
+ const entries = this.load();
168
+ if (entries.delete(account)) this.persist(entries);
169
+ }
170
+ has(account) {
171
+ return this.load().has(account);
172
+ }
173
+ };
174
+
175
+ //#endregion
176
+ //#region src/backends/memory.ts
177
+ /** Process-scoped {@link CredentialsStore}; entries vanish on exit. */
178
+ var MemoryBackend = class {
179
+ constructor(_config = {}) {
180
+ this.entries = new Map();
181
+ }
182
+ get(account) {
183
+ return this.entries.get(account);
184
+ }
185
+ set(account, value) {
186
+ if (value.length === 0) throw new Error("credential value must be non-empty");
187
+ this.entries.set(account, value);
188
+ }
189
+ delete(account) {
190
+ this.entries.delete(account);
191
+ }
192
+ has(account) {
193
+ return this.entries.has(account);
194
+ }
195
+ };
196
+
197
+ //#endregion
198
+ //#region src/failover.ts
199
+ /**
200
+ * Account-name prefix marking an account as deleted while the primary was
201
+ * unreachable.
202
+ *
203
+ * The NUL byte cannot appear in a real account name (`HW_ACCESS_KEY`,
204
+ * `HW_SECRET_KEY`, `HW_SECURITY_TOKEN`), so a tombstone can never be confused
205
+ * with a credential. Tombstones are only ever written to the fallback, never
206
+ * to the keyring.
207
+ */
208
+ const TOMBSTONE_PREFIX = "\0aishell:tombstone:";
209
+ /** The fallback key recording that `account` was deleted. */
210
+ const tombstoneKey = (account) => TOMBSTONE_PREFIX + account;
211
+ /** Tombstone value; never read, only tested for presence. */
212
+ const TOMBSTONE_VALUE = "1";
213
+ /**
214
+ * A {@link CredentialsStore} that delegates to a primary until the primary
215
+ * fails a write, then fails over — for the life of this store — to a
216
+ * fallback supplied by {@link FailoverStoreOptions.createFallback}.
217
+ *
218
+ * Stickiness is per instance, not per process: each plugin that consumes
219
+ * credentials builds its own store, so one instance failing over does not stop
220
+ * another from trying the primary. That is intended — the flag only exists to
221
+ * avoid re-hitting a primary already known to be unwritable from *this* store,
222
+ * and a second instance's attempt is one probe rather than a policy decision.
223
+ * Correctness across instances comes from the persisted record, not the flag.
224
+ *
225
+ * Constructed by {@link createCredentialsStore} around a KeyringBackend whose
226
+ * construction probe passed; not meant for direct use by upper layers.
227
+ */
228
+ var FailoverStore = class {
229
+ constructor(primary, options) {
230
+ this.failedOver = false;
231
+ this.primary = primary;
232
+ this.createFallback = options.createFallback;
233
+ }
234
+ /** The lazily built fallback; constructed at most once per store. */
235
+ get fallbackStore() {
236
+ if (this.fallback === void 0) this.fallback = this.createFallback();
237
+ return this.fallback;
238
+ }
239
+ /**
240
+ * Drop the tombstone for `account`, if any.
241
+ *
242
+ * Paired with the value purge on every path that hands authority back to the
243
+ * primary. Best-effort: a tombstone that outlives its purpose costs one extra
244
+ * fallback lookup, which must never fail a write the keyring has accepted.
245
+ */
246
+ clearTombstone(account) {
247
+ try {
248
+ this.fallbackStore.delete(tombstoneKey(account));
249
+ } catch {}
250
+ }
251
+ get(account) {
252
+ const failedOverValue = this.fallbackStore.get(account);
253
+ if (failedOverValue !== void 0) return failedOverValue;
254
+ if (this.fallbackStore.has(tombstoneKey(account))) return void 0;
255
+ return this.primary.get(account);
256
+ }
257
+ has(account) {
258
+ if (this.fallbackStore.has(account)) return true;
259
+ if (this.fallbackStore.has(tombstoneKey(account))) return false;
260
+ return this.primary.has(account);
261
+ }
262
+ set(account, value) {
263
+ if (value.length === 0) throw new Error("credential value must be non-empty");
264
+ if (this.failedOver) {
265
+ this.fallbackStore.set(account, value);
266
+ this.clearTombstone(account);
267
+ return;
268
+ }
269
+ try {
270
+ this.primary.set(account, value);
271
+ } catch (error) {
272
+ this.failedOver = true;
273
+ try {
274
+ this.fallbackStore.set(account, value);
275
+ this.clearTombstone(account);
276
+ } catch (fallbackError) {
277
+ throw new Error(`credential write failed over, but the fallback store rejected it too: ${String(fallbackError)} (primary error: ${String(error)})`);
278
+ }
279
+ return;
280
+ }
281
+ try {
282
+ this.fallbackStore.delete(account);
283
+ } catch {}
284
+ this.clearTombstone(account);
285
+ }
286
+ delete(account) {
287
+ try {
288
+ this.fallbackStore.delete(account);
289
+ } catch {}
290
+ if (this.failedOver) {
291
+ this.writeTombstone(account);
292
+ return;
293
+ }
294
+ try {
295
+ this.primary.delete(account);
296
+ this.clearTombstone(account);
297
+ } catch {
298
+ this.failedOver = true;
299
+ this.writeTombstone(account);
300
+ }
301
+ }
302
+ /**
303
+ * Record the deletion, or report its failure.
304
+ *
305
+ * Unlike the best-effort cleanups above, a tombstone that cannot be written
306
+ * means the delete silently did not happen and the credential will read back
307
+ * later. That is a failed clear, so it throws rather than being swallowed.
308
+ */
309
+ writeTombstone(account) {
310
+ this.fallbackStore.set(tombstoneKey(account), TOMBSTONE_VALUE);
311
+ }
312
+ };
313
+
314
+ //#endregion
315
+ //#region src/index.ts
316
+ /**
317
+ * Probe backends in priority order and return the first that answers.
318
+ *
319
+ * Priority: OS keyring (durable, cross-process) → machine-fingerprint
320
+ * encrypted file (durable, same-machine) → process memory (volatile,
321
+ * last resort). A backend that cannot initialize — no D-Bus secret service
322
+ * on a headless Linux box, keychain locked, etc. — is skipped, not fatal.
323
+ *
324
+ * A keyring that passes the construction probe but is later found unwritable
325
+ * (GNOME login keyring locked: reads come back null, writes fail — the probe
326
+ * cannot see this) is wrapped in a {@link FailoverStore}: its first failed
327
+ * write fails the whole process over to the fingerprint backend, so saving
328
+ * credentials works instead of erroring. The wrapper also records which
329
+ * accounts the keyring must not answer for, so a credential saved while the
330
+ * collection was locked is not shadowed by the keyring's stale copy once it
331
+ * unlocks.
332
+ *
333
+ * @param config - optional service name override.
334
+ * @returns the highest-priority backend that could initialize.
335
+ */
336
+ function createCredentialsStore(config = {}) {
337
+ const keyring = (() => {
338
+ try {
339
+ return new KeyringBackend(config);
340
+ } catch {
341
+ return void 0;
342
+ }
343
+ })();
344
+ if (keyring !== void 0) return new FailoverStore(keyring, { createFallback: () => createFallbackStore(config) });
345
+ return createFallbackStore(config);
346
+ }
347
+ /** Probe the durable-file and memory backends behind the keyring. */
348
+ function createFallbackStore(config) {
349
+ try {
350
+ return new FingerprintBackend(config);
351
+ } catch {}
352
+ return new MemoryBackend(config);
353
+ }
354
+
355
+ //#endregion
356
+ export { FailoverStore, FingerprintBackend, KeyringBackend, MemoryBackend, __setKeyringModule, createCredentialsStore };
357
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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;AA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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"}
@@ -0,0 +1,40 @@
1
+ //#region src/signer.d.ts
2
+ /**
3
+ * Huawei Cloud SDK-HMAC-SHA256 request signing.
4
+ *
5
+ * Signs an HTTP request with AK/SK (and an optional temporary SecurityToken)
6
+ * using the same algorithm as the official Huawei Cloud SDK. Produces the
7
+ * `Authorization`, `x-sdk-date`, and `x-security-token` headers to attach
8
+ * to a `fetch` call.
9
+ *
10
+ * @module @huaweidevtools/aishell-dsh-credentials-store/signer
11
+ */
12
+ /** Credentials for signing. */
13
+ interface SignCredentials {
14
+ readonly ak: string;
15
+ readonly sk: string;
16
+ readonly securityToken?: string;
17
+ }
18
+ /** The headers produced by {@link sign}. */
19
+ interface SignedHeaders {
20
+ readonly host: string;
21
+ readonly 'x-sdk-date': string;
22
+ readonly Authorization: string;
23
+ readonly 'x-security-token'?: string;
24
+ }
25
+ /**
26
+ * Sign an HTTP request with SDK-HMAC-SHA256.
27
+ *
28
+ * @param method - HTTP method (GET, POST, ...).
29
+ * @param host - Host component of the request URL (e.g. `api.aishell.openbuildlab.com`).
30
+ * @param path - Path component of the request URL (e.g. `/chat/completions`).
31
+ * @param query - Query parameters as a key-value map.
32
+ * @param body - Request body (stringified for hashing; empty string for GET).
33
+ * @param credentials - AK/SK and optional SecurityToken.
34
+ * @returns The headers to attach to the fetch call.
35
+ */
36
+ declare function sign(method: string, host: string, path: string, query: Record<string, string>, body: string, credentials: SignCredentials): SignedHeaders; //#endregion
37
+
38
+ //# sourceMappingURL=signer.d.ts.map
39
+ export { SignCredentials, SignedHeaders, sign };
40
+ //# sourceMappingURL=signer.d.ts.map
package/lib/signer.js ADDED
@@ -0,0 +1,66 @@
1
+ import crypto from "node:crypto";
2
+
3
+ //#region src/signer.ts
4
+ function sha256Hex(data) {
5
+ return crypto.createHash("sha256").update(data).digest("hex");
6
+ }
7
+ function hmacSha256(key, data) {
8
+ return crypto.createHmac("sha256", key).update(data).digest("hex");
9
+ }
10
+ /** RFC 3986 URL-encode a string (unreserved chars stay literal). */
11
+ function urlEncode(str) {
12
+ const hex = (c) => "%" + (c < 16 ? "0" : "") + c.toString(16).toUpperCase();
13
+ const noEscape = new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~".split(""));
14
+ let out = "";
15
+ for (const ch of str) {
16
+ const c = ch.codePointAt(0);
17
+ if (c < 128) out += noEscape.has(ch) ? ch : hex(c);
18
+ else out += encodeURIComponent(ch);
19
+ }
20
+ return out;
21
+ }
22
+ /** ISO 8601 timestamp in Huawei Cloud format: `20260912T064552Z`. */
23
+ function sdkTimestamp() {
24
+ return new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+/, "");
25
+ }
26
+ /**
27
+ * Sign an HTTP request with SDK-HMAC-SHA256.
28
+ *
29
+ * @param method - HTTP method (GET, POST, ...).
30
+ * @param host - Host component of the request URL (e.g. `api.aishell.openbuildlab.com`).
31
+ * @param path - Path component of the request URL (e.g. `/chat/completions`).
32
+ * @param query - Query parameters as a key-value map.
33
+ * @param body - Request body (stringified for hashing; empty string for GET).
34
+ * @param credentials - AK/SK and optional SecurityToken.
35
+ * @returns The headers to attach to the fetch call.
36
+ */
37
+ function sign(method, host, path, query, body, credentials) {
38
+ const ts = sdkTimestamp();
39
+ const cqs = Object.entries(query).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${urlEncode(k)}=${urlEncode(v)}`).join("&");
40
+ const curi = "/" + path.split("/").filter(Boolean).map(urlEncode).join("/") + "/";
41
+ const hasToken = credentials.securityToken !== void 0;
42
+ const signedHeaders = hasToken ? "host;x-sdk-date;x-security-token" : "host;x-sdk-date";
43
+ const canonicalHeaders = hasToken ? `host:${host}\nx-sdk-date:${ts}\nx-security-token:${credentials.securityToken}\n` : `host:${host}\nx-sdk-date:${ts}\n`;
44
+ const payloadHash = sha256Hex(body);
45
+ const canonicalRequest = [
46
+ method,
47
+ curi,
48
+ cqs,
49
+ canonicalHeaders,
50
+ signedHeaders,
51
+ payloadHash
52
+ ].join("\n");
53
+ const stringToSign = `SDK-HMAC-SHA256\n${ts}\n${sha256Hex(canonicalRequest)}`;
54
+ const signature = hmacSha256(credentials.sk, stringToSign);
55
+ const headers = {
56
+ host,
57
+ "x-sdk-date": ts,
58
+ Authorization: `SDK-HMAC-SHA256 Access=${credentials.ak}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
59
+ ...hasToken ? { "x-security-token": credentials.securityToken } : {}
60
+ };
61
+ return headers;
62
+ }
63
+
64
+ //#endregion
65
+ export { sign };
66
+ //# sourceMappingURL=signer.js.map
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@huaweidevtools/aishell-dsh-credentials-store",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Credential storage + SDK-HMAC-SHA256 signing for aishell DSH plugins",
4
+ "version": "0.0.1-beta.1",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/yusheng-g/aishell-dsh-plugins.git",
11
+ "directory": "packages/credentials-store"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./signer": {
22
+ "types": "./lib/signer.d.ts",
23
+ "default": "./lib/signer.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "lib/index.js",
28
+ "lib/signer.js",
29
+ "lib/index.d.ts",
30
+ "lib/signer.d.ts",
31
+ "lib/index.js.map",
32
+ "lib/index.d.ts.map"
33
+ ],
34
+ "license": "Apache-2.0",
35
+ "dependencies": {
36
+ "@napi-rs/keyring": "^2.0.0",
37
+ "node-machine-id": "^1.1.12"
38
+ },
39
+ "scripts": {
40
+ "build:bundle": "tsdown"
41
+ }
6
42
  }