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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,53 @@
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
+ ## Usage
18
+
19
+ ```typescript
20
+ import { createCredentialsStore } from '@huaweidevtools/aishell-dsh-credentials-store'
21
+
22
+ const store = createCredentialsStore() // probes keyring → fingerprint → memory
23
+ store.set('HW_ACCESS_KEY', 'LTAIxxxx') // durable if keyring or fingerprint is up
24
+ const ak = store.get('HW_ACCESS_KEY') // 'LTAIxxxx'
25
+ store.has('HW_ACCESS_KEY') // true
26
+ store.delete('HW_ACCESS_KEY')
27
+ ```
28
+
29
+ A custom service name isolates entries from other applications sharing the same keyring:
30
+
31
+ ```typescript
32
+ const store = createCredentialsStore({ service: 'my-app' })
33
+ ```
34
+
35
+ ## Security properties
36
+
37
+ - **No plaintext files**: nothing on disk is readable with `cat`.
38
+ - **OS-encrypted at rest**: Keychain (AES), libsecret (DPAPI/GNOME keyring), Credential Manager (DPAPI).
39
+ - **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.
40
+ - **Per-operation read**: no cache; a credential removed from the keyring is immediately absent on the next `get`.
41
+ - **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.
42
+
43
+ ## Platform support (KeyringBackend)
44
+
45
+ | Platform | Backend | Requirement |
46
+ |---|---|---|
47
+ | macOS | Keychain | None (built in) |
48
+ | Linux | libsecret | `gnome-keyring` or `kwallet` running, plus `libsecret-1-dev` at build time |
49
+ | Windows | Credential Manager | None (built in) |
50
+
51
+ ## License
52
+
53
+ Apache License 2.0. See [LICENSE](../../LICENSE).
package/lib/index.d.ts ADDED
@@ -0,0 +1,139 @@
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/index.d.ts
74
+ //# sourceMappingURL=memory.d.ts.map
75
+ /**
76
+ * Credential storage abstraction for aishell DSH plugins.
77
+ *
78
+ * Upper layers (aishell-llm's adapter, aishell-credentials' host half)
79
+ * call {@link createCredentialsStore} and get a {@link CredentialsStore} —
80
+ * they never learn which backend is serving. The factory probes backends in
81
+ * priority order (OS keyring first, process memory last) and returns the
82
+ * first that answers. New backends (fingerprint + encrypted file, etc.) slot
83
+ * into the chain without touching callers.
84
+ *
85
+ * This is a tool library, not a DSH plugin — no `dsh.client`, no
86
+ * `cordis.patch.yml`, no `apply`. DSH's own `ctx.credentials` is untouched;
87
+ * user-configured models and `.credentials.yaml` keep working.
88
+ *
89
+ * @module @huaweidevtools/aishell-dsh-credentials-store
90
+ */
91
+ /** Options shared by every backend / the factory. */
92
+ interface CredentialsStoreConfig {
93
+ /**
94
+ * Backend-scoped identity. For the OS-keyring backend this is the keyring
95
+ * service name; every entry is stored under `new Entry(service, account)`.
96
+ * Defaults to `'aishell-dsh'`.
97
+ */
98
+ readonly service?: string;
99
+ /**
100
+ * Explicit directory for the fingerprint encrypted-file backend. When set,
101
+ * overrides the default `$DSH_HOME/credentials` resolution. Callers rarely
102
+ * need this — the host's `DSH_HOME` already places credentials alongside
103
+ * its other data.
104
+ */
105
+ readonly credentialsDir?: string;
106
+ }
107
+ /**
108
+ * Read/write a named credential. Backends are synchronous and per-call — no
109
+ * cache, so a credential changed from outside is visible on the next `get`.
110
+ * Absent credentials read as `undefined` / `has === false`; a backend that
111
+ * cannot serve (e.g. no D-Bus secret service) degrades the same way rather
112
+ * than throwing on read.
113
+ */
114
+ interface CredentialsStore {
115
+ /** Read one credential; `undefined` when absent or backend unavailable. */
116
+ get(account: string): string | undefined;
117
+ /** Store one credential. Rejects an empty value; throws on backend errors. */
118
+ set(account: string, value: string): void;
119
+ /** Remove one credential; absent is a no-op. Throws on backend errors. */
120
+ delete(account: string): void;
121
+ /** Whether a credential is currently stored; `false` when absent or backend unavailable. */
122
+ has(account: string): boolean;
123
+ }
124
+ /**
125
+ * Probe backends in priority order and return the first that answers.
126
+ *
127
+ * Priority: OS keyring (durable, cross-process) → machine-fingerprint
128
+ * encrypted file (durable, same-machine) → process memory (volatile,
129
+ * last resort). A backend that cannot initialize — no D-Bus secret service
130
+ * on a headless Linux box, keychain locked, etc. — is skipped, not fatal.
131
+ *
132
+ * @param config - optional service name override.
133
+ * @returns the highest-priority backend that could initialize.
134
+ */
135
+ declare function createCredentialsStore(config?: CredentialsStoreConfig): CredentialsStore;
136
+
137
+ //#endregion
138
+ export { CredentialsStore, CredentialsStoreConfig, FingerprintBackend, KeyringBackend, MemoryBackend, __setKeyringModule, createCredentialsStore };
139
+ //# 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/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;;;;;;;;;AAjCoB;AAO1D;;AASjB;;;;;;;;;AAiBA;;;;AAAuD,UGzBtC,sBAAA,CHyBsC;;;;;;;;;;;;;EC0C1C,SAAA,cAAmB,CAAA,EAAA,MAAA;;;;AAA2B;;;;;AC1E9C,UC8BI,gBAAA,CD9BU;EAAA;EAAA,GAGJ,CAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAA2B;EAHI,GAAA,CAAA,OAAA,EAAA,MAAA,EAAA,KAAA,EAAA,MAAA,CAAA,EAAA,IAAA;;;;;;;;;;;;;;;;;iBCoDtC,sBAAA,UAA+B,yBAA8B"}
package/lib/index.js ADDED
@@ -0,0 +1,222 @@
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/index.ts
199
+ /**
200
+ * Probe backends in priority order and return the first that answers.
201
+ *
202
+ * Priority: OS keyring (durable, cross-process) → machine-fingerprint
203
+ * encrypted file (durable, same-machine) → process memory (volatile,
204
+ * last resort). A backend that cannot initialize — no D-Bus secret service
205
+ * on a headless Linux box, keychain locked, etc. — is skipped, not fatal.
206
+ *
207
+ * @param config - optional service name override.
208
+ * @returns the highest-priority backend that could initialize.
209
+ */
210
+ function createCredentialsStore(config = {}) {
211
+ try {
212
+ return new KeyringBackend(config);
213
+ } catch {}
214
+ try {
215
+ return new FingerprintBackend(config);
216
+ } catch {}
217
+ return new MemoryBackend(config);
218
+ }
219
+
220
+ //#endregion
221
+ export { FingerprintBackend, KeyringBackend, MemoryBackend, __setKeyringModule, createCredentialsStore };
222
+ //# 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","config: CredentialsStoreConfig"],"sources":["../src/backends/keyring.ts","../src/backends/fingerprint.ts","../src/backends/memory.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 * 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.\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'\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 * @param config - optional service name override.\n * @returns the highest-priority backend that could initialize.\n */\nexport function createCredentialsStore(config: CredentialsStoreConfig = {}): CredentialsStore {\n try {\n return new KeyringBackend(config)\n } catch {\n // OS keyring unavailable — try the fingerprint file backend.\n }\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"],"mappings":"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"}
@@ -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.0",
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
  }