@jetcrab/pi-desk-sdk 1.1.16-dev → 1.1.18-dev
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/browser.d.ts +3 -0
- package/dist/config-storage.d.ts +4 -0
- package/dist/config-storage.js +157 -0
- package/dist/config.d.ts +6 -0
- package/dist/config.js +27 -0
- package/dist/entry.d.ts +3 -0
- package/dist/events.d.ts +35 -0
- package/dist/events.js +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/secrets.d.ts +15 -0
- package/dist/secrets.js +245 -0
- package/package.json +19 -1
package/README.md
CHANGED
|
@@ -2,4 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
包名:`@jetcrab/pi-desk-sdk`。公开接口以本版本 `package.json` 的 exports 和对应 TypeScript 声明为准。
|
|
4
4
|
|
|
5
|
+
Node-only `/config` 只提供当前配置目录、同目标串行读改写与原子文本写入,`/secrets` 提供凭据引用与加密存储;不从根入口或 Browser 导出,不依赖常驻 Global Host。配置只读取当前路径和格式,旧配置需在升级前另行准备,启动和读取不会自动搬迁或回写旧文件。
|
|
6
|
+
|
|
7
|
+
SDK 的运行依赖为 Zod(协议 Schema)、`proper-lockfile`(Node 跨进程锁)和 `@napi-rs/keyring`(Node 系统持久密钥存储)。协议与 Browser 子入口不加载这些 Node 配置或凭据能力,非 React 使用不要求安装公共 UI 库。
|
|
8
|
+
|
|
5
9
|
本包自有代码使用 Apache-2.0,见 [LICENSE](./LICENSE)。第三方代码继续遵循其原有许可,构建时保留上游法律注释。
|
package/dist/browser.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { BrowserApplicationContext, PluginDisposer, PluginJsonObject, PluginNotificationLevel, PluginSource, PluginWorkSession } from './shared.js';
|
|
2
2
|
import type { PluginPushMessage } from './entry.js';
|
|
3
3
|
import type { HostSettings } from './settings.js';
|
|
4
|
+
import type { BrowserHostEventMap, HostEvents } from './events.js';
|
|
4
5
|
export type { HostRegion, HostSettings, HostSettingsSnapshot } from './settings.js';
|
|
6
|
+
export type { BrowserHostEventMap, ChatSubmitResult, HostEventListener, HostEvents, WorkbenchContext } from './events.js';
|
|
5
7
|
export type { BrowserApplicationContext, BrowserBuiltinIconName, BrowserContributionIcon, PluginDisposer, PluginJsonObject, PluginJsonValue, PluginNotificationLevel, PluginSource, PluginWorkSession } from './shared.js';
|
|
6
8
|
export type { PluginPushMessage, PluginPushTarget } from './entry.js';
|
|
7
9
|
export type BrowserContributionKind = 'application' | 'composer-panel' | 'settings-page' | 'message-view' | 'session-sidebar-tab';
|
|
@@ -178,6 +180,7 @@ export interface BrowserTunnelHost {
|
|
|
178
180
|
}): BrowserTunnelHandle;
|
|
179
181
|
}
|
|
180
182
|
export interface BrowserPluginHost {
|
|
183
|
+
readonly events: HostEvents<BrowserHostEventMap>;
|
|
181
184
|
readonly settings: HostSettings;
|
|
182
185
|
/** 映射当前工作台后端的已发布 TCP 端口;旧宿主或无原生能力时不可用。 */
|
|
183
186
|
readonly tunnels?: BrowserTunnelHost;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function ensureStorageDirectory(path: string): void;
|
|
2
|
+
export declare function readStorageFile(path: string): Buffer | null;
|
|
3
|
+
export declare function writeStorageFile(path: string, content: Buffer, expected: Buffer | null): void;
|
|
4
|
+
export declare function withStorageLock<T>(path: string, action: (assertLocked: () => void) => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
import lockfile from 'proper-lockfile';
|
|
5
|
+
function errorCode(error) {
|
|
6
|
+
return error.code ?? 'UNKNOWN';
|
|
7
|
+
}
|
|
8
|
+
function storageError(operation, path, error) {
|
|
9
|
+
return new Error(`${operation}失败:${path}(${errorCode(error)})`);
|
|
10
|
+
}
|
|
11
|
+
// 只创建目标文件需要的目录;AgentDir 及其他已有目录仍由调用方管理。
|
|
12
|
+
export function ensureStorageDirectory(path) {
|
|
13
|
+
assertDirectories(path);
|
|
14
|
+
try {
|
|
15
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
throw storageError('创建配置目录', path, error);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function assertDirectories(path) {
|
|
22
|
+
const parent = dirname(path);
|
|
23
|
+
if (parent !== path)
|
|
24
|
+
assertDirectories(parent);
|
|
25
|
+
try {
|
|
26
|
+
if (!lstatSync(path).isDirectory())
|
|
27
|
+
throw new Error(`配置目录不是普通目录:${path}`);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (errorCode(error) === 'ENOENT')
|
|
31
|
+
return;
|
|
32
|
+
if (error instanceof Error && error.message.startsWith('配置目录'))
|
|
33
|
+
throw error;
|
|
34
|
+
throw storageError('检查配置目录', path, error);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function readStorageFile(path) {
|
|
38
|
+
assertDirectories(dirname(path));
|
|
39
|
+
let descriptor;
|
|
40
|
+
try {
|
|
41
|
+
const stat = lstatSync(path);
|
|
42
|
+
if (!stat.isFile())
|
|
43
|
+
throw new Error(`拒绝读取非普通配置文件或符号链接:${path}`);
|
|
44
|
+
descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
45
|
+
const opened = fstatSync(descriptor);
|
|
46
|
+
if (!opened.isFile() || opened.ino !== stat.ino || opened.dev !== stat.dev) {
|
|
47
|
+
throw new Error(`读取期间配置文件已变化:${path}`);
|
|
48
|
+
}
|
|
49
|
+
return readFileSync(descriptor);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (errorCode(error) === 'ENOENT')
|
|
53
|
+
return null;
|
|
54
|
+
if (error instanceof Error && /^(拒绝读取|读取期间)/u.test(error.message))
|
|
55
|
+
throw error;
|
|
56
|
+
throw storageError('读取配置文件', path, error);
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
if (descriptor !== undefined)
|
|
60
|
+
closeSync(descriptor);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function assertFileUnchanged(path, expected) {
|
|
64
|
+
const actual = readStorageFile(path);
|
|
65
|
+
if (expected === null ? actual !== null : actual === null || !actual.equals(expected)) {
|
|
66
|
+
throw new Error(`配置文件已变化,拒绝覆盖:${path}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function syncDirectory(path) {
|
|
70
|
+
// Windows 不支持以普通文件描述符 fsync 目录;文件本身始终先 fsync。
|
|
71
|
+
if (process.platform === 'win32')
|
|
72
|
+
return;
|
|
73
|
+
const descriptor = openSync(path, constants.O_RDONLY);
|
|
74
|
+
try {
|
|
75
|
+
fsyncSync(descriptor);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
closeSync(descriptor);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export function writeStorageFile(path, content, expected) {
|
|
82
|
+
const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
|
|
83
|
+
let descriptor;
|
|
84
|
+
let committed = false;
|
|
85
|
+
try {
|
|
86
|
+
descriptor = openSync(temporary, 'wx', 0o600);
|
|
87
|
+
writeFileSync(descriptor, content);
|
|
88
|
+
fsyncSync(descriptor);
|
|
89
|
+
closeSync(descriptor);
|
|
90
|
+
descriptor = undefined;
|
|
91
|
+
assertFileUnchanged(path, expected);
|
|
92
|
+
if (expected === null) {
|
|
93
|
+
// 硬链接发布保证目标在锁外被创建时也不会被覆盖。
|
|
94
|
+
linkSync(temporary, path);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
renameSync(temporary, path);
|
|
98
|
+
}
|
|
99
|
+
syncDirectory(dirname(path));
|
|
100
|
+
const actual = readStorageFile(path);
|
|
101
|
+
if (!actual?.equals(content))
|
|
102
|
+
throw new Error(`配置文件写入校验失败:${path}`);
|
|
103
|
+
committed = true;
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error instanceof Error && error.message.startsWith('配置文件'))
|
|
107
|
+
throw error;
|
|
108
|
+
throw storageError('原子写入配置文件', path, error);
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
if (descriptor !== undefined)
|
|
112
|
+
closeSync(descriptor);
|
|
113
|
+
try {
|
|
114
|
+
unlinkSync(temporary);
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
if (errorCode(error) !== 'ENOENT') {
|
|
118
|
+
const status = committed ? '配置已提交,不应回收其引用的凭据' : '配置写入失败,保留原始错误';
|
|
119
|
+
console.warn(`${storageError('清理配置临时文件', temporary, error).message};${status},请清理该临时文件`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const lockOptions = { realpath: false, stale: 120_000, update: 10_000 };
|
|
125
|
+
export async function withStorageLock(path, action) {
|
|
126
|
+
let compromised = false;
|
|
127
|
+
let release;
|
|
128
|
+
try {
|
|
129
|
+
release = await lockfile.lock(path, {
|
|
130
|
+
...lockOptions,
|
|
131
|
+
retries: { retries: 150, minTimeout: 100, maxTimeout: 100, randomize: false },
|
|
132
|
+
onCompromised() {
|
|
133
|
+
compromised = true;
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
throw storageError('获取配置文件锁', path, error);
|
|
139
|
+
}
|
|
140
|
+
const assertLocked = () => {
|
|
141
|
+
if (compromised)
|
|
142
|
+
throw new Error(`配置文件锁已失效:${path}`);
|
|
143
|
+
};
|
|
144
|
+
try {
|
|
145
|
+
const result = await action(assertLocked);
|
|
146
|
+
assertLocked();
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
try {
|
|
151
|
+
await release();
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
console.warn(`${storageError('释放配置文件锁', path, error).message};操作结果不回滚,请检查锁目录`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare function getConfigDirectory(agentDir?: string): string;
|
|
2
|
+
export declare function getConfigPath(filename: string, agentDir?: string): string;
|
|
3
|
+
/** 串行保护同一目标的完整读改写;操作内不能嵌套获取同一目标锁。 */
|
|
4
|
+
export declare function withConfigTransaction<T>(targetPath: string, operation: () => Promise<T>): Promise<T>;
|
|
5
|
+
/** 原子发布 UTF-8 配置;读改写应置于 withConfigTransaction 内,本方法不重复加锁。 */
|
|
6
|
+
export declare function writeConfigTextAtomic(path: string, content: string): void;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { ensureStorageDirectory, readStorageFile, withStorageLock, writeStorageFile } from "./config-storage.js";
|
|
4
|
+
export function getConfigDirectory(agentDir) {
|
|
5
|
+
return join(agentDir ?? getAgentDir(), 'config');
|
|
6
|
+
}
|
|
7
|
+
export function getConfigPath(filename, agentDir) {
|
|
8
|
+
if (!filename || filename === '.' || filename === '..' || /[/\\:\x00-\x1f]/u.test(filename)) {
|
|
9
|
+
throw new Error('配置文件名必须是单个文件名');
|
|
10
|
+
}
|
|
11
|
+
return join(getConfigDirectory(agentDir), filename);
|
|
12
|
+
}
|
|
13
|
+
/** 串行保护同一目标的完整读改写;操作内不能嵌套获取同一目标锁。 */
|
|
14
|
+
export async function withConfigTransaction(targetPath, operation) {
|
|
15
|
+
const target = resolve(targetPath);
|
|
16
|
+
ensureStorageDirectory(dirname(target));
|
|
17
|
+
return withStorageLock(target, async () => {
|
|
18
|
+
readStorageFile(target);
|
|
19
|
+
return operation();
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/** 原子发布 UTF-8 配置;读改写应置于 withConfigTransaction 内,本方法不重复加锁。 */
|
|
23
|
+
export function writeConfigTextAtomic(path, content) {
|
|
24
|
+
const target = resolve(path);
|
|
25
|
+
ensureStorageDirectory(dirname(target));
|
|
26
|
+
writeStorageFile(target, Buffer.from(content, 'utf8'), readStorageFile(target));
|
|
27
|
+
}
|
package/dist/entry.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { CapabilityDeclarations } from './capabilities.js';
|
|
2
2
|
import type { HostSettings } from './settings.js';
|
|
3
|
+
import type { HostEvents, NodeHostEventMap } from './events.js';
|
|
3
4
|
export type { HostRegion, HostSettings, HostSettingsSnapshot } from './settings.js';
|
|
5
|
+
export type { ChatInputAccepted, HostEventListener, HostEvents, NodeHostEventMap } from './events.js';
|
|
4
6
|
import { type PluginDisposer, type PluginJsonObject, type PluginJsonValue, type PluginNotificationLevel, type PluginSource, type PluginWorkSession } from './shared.ts';
|
|
5
7
|
export type { BrowserBuiltinIconName, BrowserContributionIcon, PluginDisposer, PluginJsonObject, PluginJsonValue, PluginNotificationLevel, PluginSource, PluginWorkSession } from './shared.js';
|
|
6
8
|
export interface GlobalPluginMethodContext {
|
|
@@ -33,6 +35,7 @@ export interface PiDeskWorkSessionCapability {
|
|
|
33
35
|
listWorkSessions(): Promise<readonly PluginWorkSession[]>;
|
|
34
36
|
}
|
|
35
37
|
export interface PiDeskPluginHost {
|
|
38
|
+
readonly events: HostEvents<NodeHostEventMap>;
|
|
36
39
|
readonly settings: HostSettings;
|
|
37
40
|
readonly workSessions: PiDeskWorkSessionCapability;
|
|
38
41
|
}
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { BrowserConnectionSnapshot, BrowserThemeSnapshot } from './browser.js';
|
|
2
|
+
import type { HostSettingsSnapshot } from './settings.js';
|
|
3
|
+
import type { BrowserApplicationContext, PluginJsonObject, PluginSource, PluginWorkSession } from './shared.js';
|
|
4
|
+
export type HostEventListener<T> = (data: Readonly<T>) => void | Promise<void>;
|
|
5
|
+
export interface HostEvents<Events> {
|
|
6
|
+
on<K extends keyof Events & string>(name: K, handler: HostEventListener<Events[K]>): () => void;
|
|
7
|
+
onPlugin(pluginName: string, name: string, handler: HostEventListener<PluginJsonObject>): () => void;
|
|
8
|
+
emit(name: string, data: PluginJsonObject): void;
|
|
9
|
+
}
|
|
10
|
+
export type WorkbenchContext = BrowserApplicationContext | null;
|
|
11
|
+
export interface ChatInputAccepted {
|
|
12
|
+
source: PluginSource;
|
|
13
|
+
tempId: string;
|
|
14
|
+
}
|
|
15
|
+
export type ChatSubmitResult = (ChatInputAccepted & {
|
|
16
|
+
status: 'accepted';
|
|
17
|
+
}) | {
|
|
18
|
+
source: PluginSource;
|
|
19
|
+
status: 'failed' | 'unknown';
|
|
20
|
+
message: string;
|
|
21
|
+
};
|
|
22
|
+
export interface BrowserHostEventMap {
|
|
23
|
+
'workbench-context': WorkbenchContext;
|
|
24
|
+
'work-sessions': readonly PluginWorkSession[];
|
|
25
|
+
connection: BrowserConnectionSnapshot;
|
|
26
|
+
settings: HostSettingsSnapshot;
|
|
27
|
+
theme: BrowserThemeSnapshot;
|
|
28
|
+
'plugin-state': PluginJsonObject | null;
|
|
29
|
+
'chat-submit-result': ChatSubmitResult;
|
|
30
|
+
}
|
|
31
|
+
export interface NodeHostEventMap {
|
|
32
|
+
'work-sessions': readonly PluginWorkSession[];
|
|
33
|
+
settings: HostSettingsSnapshot;
|
|
34
|
+
'chat-input-accepted': ChatInputAccepted;
|
|
35
|
+
}
|
package/dist/events.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface SecretStoreOptions {
|
|
2
|
+
agentDir?: string;
|
|
3
|
+
/** 仅供隔离测试或受控集成注入;生产默认使用系统钥匙串。 */
|
|
4
|
+
keyProvider?: () => Promise<Uint8Array>;
|
|
5
|
+
}
|
|
6
|
+
export interface SecretStore {
|
|
7
|
+
get(reference: string): Promise<string | null>;
|
|
8
|
+
put(value: string, reference?: string): Promise<string>;
|
|
9
|
+
/** 仅显式删除已确认不再被任何配置引用的凭据;发布过的旧引用不会自动回收。 */
|
|
10
|
+
delete(reference: string): Promise<void>;
|
|
11
|
+
export(references: readonly string[]): Promise<Record<string, string>>;
|
|
12
|
+
import(values: Readonly<Record<string, string>>): Promise<Record<string, string>>;
|
|
13
|
+
}
|
|
14
|
+
export declare function isSecretReference(value: unknown): value is string;
|
|
15
|
+
export declare function createSecretStore(options?: SecretStoreOptions): SecretStore;
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { realpathSync } from 'node:fs';
|
|
4
|
+
import { getConfigPath } from "./config.js";
|
|
5
|
+
import { ensureStorageDirectory, readStorageFile, withStorageLock, writeStorageFile } from "./config-storage.js";
|
|
6
|
+
const header = Buffer.from('PIDSECR1');
|
|
7
|
+
class KeyError extends Error {
|
|
8
|
+
}
|
|
9
|
+
const nonceLength = 12;
|
|
10
|
+
const tagLength = 16;
|
|
11
|
+
const maxVaultBytes = 8 * 1024 * 1024;
|
|
12
|
+
const maxVaultRecords = 4096;
|
|
13
|
+
function assertVaultCapacity(values) {
|
|
14
|
+
const entries = Object.entries(values);
|
|
15
|
+
const guidance = '请先导出需要保留的凭据,并仅显式删除已确认不再被任何配置引用的凭据后重试;不会自动清空保险库';
|
|
16
|
+
if (entries.length > maxVaultRecords) {
|
|
17
|
+
throw new Error(`凭据保险库最多保存 ${maxVaultRecords} 条记录;${guidance}`);
|
|
18
|
+
}
|
|
19
|
+
let bytes = header.length + nonceLength + tagLength + 2 + Math.max(entries.length - 1, 0);
|
|
20
|
+
for (const [reference, value] of entries) {
|
|
21
|
+
if (Buffer.byteLength(value, 'utf8') > maxVaultBytes) {
|
|
22
|
+
throw new Error(`凭据保险库完整密文不能超过 8 MiB;${guidance}`);
|
|
23
|
+
}
|
|
24
|
+
bytes +=
|
|
25
|
+
Buffer.byteLength(JSON.stringify(reference), 'utf8') +
|
|
26
|
+
1 +
|
|
27
|
+
Buffer.byteLength(JSON.stringify(value), 'utf8');
|
|
28
|
+
if (bytes > maxVaultBytes)
|
|
29
|
+
throw new Error(`凭据保险库完整密文不能超过 8 MiB;${guidance}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const referencePattern = /^secret:\/\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/u;
|
|
33
|
+
export function isSecretReference(value) {
|
|
34
|
+
return typeof value === 'string' && referencePattern.test(value);
|
|
35
|
+
}
|
|
36
|
+
function assertReference(reference) {
|
|
37
|
+
if (!isSecretReference(reference))
|
|
38
|
+
throw new Error('凭据引用必须为 secret://UUID');
|
|
39
|
+
}
|
|
40
|
+
function decodeVault(content, key) {
|
|
41
|
+
try {
|
|
42
|
+
if (content.length < header.length + nonceLength + tagLength ||
|
|
43
|
+
!content.subarray(0, header.length).equals(header)) {
|
|
44
|
+
throw new Error();
|
|
45
|
+
}
|
|
46
|
+
const nonceEnd = header.length + nonceLength;
|
|
47
|
+
const decipher = createDecipheriv('aes-256-gcm', key, content.subarray(header.length, nonceEnd));
|
|
48
|
+
decipher.setAAD(header);
|
|
49
|
+
decipher.setAuthTag(content.subarray(nonceEnd, nonceEnd + tagLength));
|
|
50
|
+
const plaintext = Buffer.concat([
|
|
51
|
+
decipher.update(content.subarray(nonceEnd + tagLength)),
|
|
52
|
+
decipher.final()
|
|
53
|
+
]);
|
|
54
|
+
try {
|
|
55
|
+
const values = JSON.parse(plaintext.toString('utf8'));
|
|
56
|
+
if (typeof values !== 'object' || values === null || Array.isArray(values))
|
|
57
|
+
throw new Error();
|
|
58
|
+
for (const [reference, value] of Object.entries(values)) {
|
|
59
|
+
if (!isSecretReference(reference) || typeof value !== 'string')
|
|
60
|
+
throw new Error();
|
|
61
|
+
}
|
|
62
|
+
return values;
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
plaintext.fill(0);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw new Error('凭据保险库认证失败或格式无效,请确认密钥与文件完整性');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function encodeVault(values, key) {
|
|
73
|
+
const nonce = randomBytes(nonceLength);
|
|
74
|
+
const cipher = createCipheriv('aes-256-gcm', key, nonce);
|
|
75
|
+
cipher.setAAD(header);
|
|
76
|
+
const plaintext = Buffer.from(JSON.stringify(values));
|
|
77
|
+
try {
|
|
78
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
79
|
+
return Buffer.concat([header, nonce, cipher.getAuthTag(), ciphertext]);
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
plaintext.fill(0);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function validateKey(key) {
|
|
86
|
+
if (!(key instanceof Uint8Array) || key.byteLength !== 32) {
|
|
87
|
+
throw new Error('凭据主密钥必须是 32 字节');
|
|
88
|
+
}
|
|
89
|
+
return Buffer.from(key);
|
|
90
|
+
}
|
|
91
|
+
async function loadKey(path, vaultExists, keyProvider, assertLocked) {
|
|
92
|
+
if (keyProvider) {
|
|
93
|
+
try {
|
|
94
|
+
return validateKey(await keyProvider());
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw new Error('注入的凭据密钥提供器失败或未返回 32 字节密钥');
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const keyFile = process.env.PI_DESK_SECRET_KEY_FILE;
|
|
101
|
+
if (keyFile !== undefined) {
|
|
102
|
+
if (!keyFile)
|
|
103
|
+
throw new Error('PI_DESK_SECRET_KEY_FILE 必须指定外部密钥文件');
|
|
104
|
+
const content = readStorageFile(resolve(keyFile));
|
|
105
|
+
if (content === null)
|
|
106
|
+
throw new Error('外部凭据密钥文件不存在,拒绝生成或替换密钥');
|
|
107
|
+
try {
|
|
108
|
+
// 外部文件由部署方持有;SDK 只读原始 32 字节,从不创建或改写它。
|
|
109
|
+
return validateKey(content);
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
content.fill(0);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
// 延迟加载原生模块,注入测试及外部密钥文件模式不访问系统钥匙串。
|
|
117
|
+
const { Entry } = await import('@napi-rs/keyring');
|
|
118
|
+
const directory = realpathSync(dirname(path));
|
|
119
|
+
const identity = process.platform === 'win32' ? directory.toLowerCase() : directory;
|
|
120
|
+
const account = createHash('sha256').update(identity).digest('hex');
|
|
121
|
+
const entry = new Entry('pi-desk.credentials', account, { linux: { store: 'secret-service' } });
|
|
122
|
+
const password = entry.getPassword();
|
|
123
|
+
if (password !== null) {
|
|
124
|
+
if (!/^[A-Za-z0-9+/]{43}=$/u.test(password))
|
|
125
|
+
throw new KeyError('凭据主密钥格式无效');
|
|
126
|
+
const key = Buffer.from(password, 'base64');
|
|
127
|
+
if (key.length !== 32 || key.toString('base64') !== password)
|
|
128
|
+
throw new KeyError('凭据主密钥格式无效');
|
|
129
|
+
return key;
|
|
130
|
+
}
|
|
131
|
+
if (vaultExists)
|
|
132
|
+
throw new KeyError('凭据保险库已存在,但系统钥匙串中的主密钥缺失,拒绝重建');
|
|
133
|
+
assertLocked();
|
|
134
|
+
const key = randomBytes(32);
|
|
135
|
+
try {
|
|
136
|
+
entry.setPassword(key.toString('base64'));
|
|
137
|
+
if (entry.getPassword() !== key.toString('base64'))
|
|
138
|
+
throw new Error('凭据主密钥写入校验失败');
|
|
139
|
+
return key;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
key.fill(0);
|
|
143
|
+
throw new KeyError('凭据主密钥写入失败,请检查系统钥匙串');
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
if (error instanceof KeyError)
|
|
148
|
+
throw error;
|
|
149
|
+
// 原生错误正文可能包含凭据;仅给出可定位且不泄漏秘密的操作原因。
|
|
150
|
+
throw new Error('系统钥匙串不可用,无法解锁凭据;Linux 需要 Secret Service,也可设置 PI_DESK_SECRET_KEY_FILE');
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
export function createSecretStore(options = {}) {
|
|
154
|
+
const path = resolve(getConfigPath('credentials.enc', options.agentDir));
|
|
155
|
+
const keyProvider = options.keyProvider;
|
|
156
|
+
async function access(action) {
|
|
157
|
+
ensureStorageDirectory(dirname(path));
|
|
158
|
+
return withStorageLock(path, async (assertLocked) => {
|
|
159
|
+
const existing = readStorageFile(path);
|
|
160
|
+
let key;
|
|
161
|
+
try {
|
|
162
|
+
let values = {};
|
|
163
|
+
if (existing !== null) {
|
|
164
|
+
key = await loadKey(path, true, keyProvider, assertLocked);
|
|
165
|
+
values = decodeVault(existing, key);
|
|
166
|
+
}
|
|
167
|
+
assertLocked();
|
|
168
|
+
const { result, changed } = action(values);
|
|
169
|
+
if (changed) {
|
|
170
|
+
assertVaultCapacity(values);
|
|
171
|
+
key ??= await loadKey(path, false, keyProvider, assertLocked);
|
|
172
|
+
const content = encodeVault(values, key);
|
|
173
|
+
// 写前先用同一解密路径验证完整格式,再原子发布并逐字节回读校验。
|
|
174
|
+
decodeVault(content, key);
|
|
175
|
+
assertLocked();
|
|
176
|
+
writeStorageFile(path, content, existing);
|
|
177
|
+
}
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
key?.fill(0);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
async get(reference) {
|
|
187
|
+
assertReference(reference);
|
|
188
|
+
return access((values) => ({ result: values[reference] ?? null, changed: false }));
|
|
189
|
+
},
|
|
190
|
+
async put(value, reference) {
|
|
191
|
+
if (typeof value !== 'string')
|
|
192
|
+
throw new Error('凭据值必须是字符串');
|
|
193
|
+
if (reference !== undefined)
|
|
194
|
+
assertReference(reference);
|
|
195
|
+
return access((values) => {
|
|
196
|
+
let next = reference ?? `secret://${randomUUID()}`;
|
|
197
|
+
while (reference === undefined && Object.hasOwn(values, next))
|
|
198
|
+
next = `secret://${randomUUID()}`;
|
|
199
|
+
values[next] = value;
|
|
200
|
+
return { result: next, changed: true };
|
|
201
|
+
});
|
|
202
|
+
},
|
|
203
|
+
async delete(reference) {
|
|
204
|
+
assertReference(reference);
|
|
205
|
+
return access((values) => {
|
|
206
|
+
const changed = Object.hasOwn(values, reference);
|
|
207
|
+
delete values[reference];
|
|
208
|
+
return { result: undefined, changed };
|
|
209
|
+
});
|
|
210
|
+
},
|
|
211
|
+
async export(references) {
|
|
212
|
+
for (const reference of references)
|
|
213
|
+
assertReference(reference);
|
|
214
|
+
return access((values) => {
|
|
215
|
+
const exported = {};
|
|
216
|
+
for (const reference of references) {
|
|
217
|
+
if (!Object.hasOwn(values, reference))
|
|
218
|
+
throw new Error('导出的凭据引用不存在');
|
|
219
|
+
exported[reference] = values[reference];
|
|
220
|
+
}
|
|
221
|
+
return { result: exported, changed: false };
|
|
222
|
+
});
|
|
223
|
+
},
|
|
224
|
+
async import(values) {
|
|
225
|
+
const entries = Object.entries(values);
|
|
226
|
+
for (const [reference, value] of entries) {
|
|
227
|
+
assertReference(reference);
|
|
228
|
+
if (typeof value !== 'string')
|
|
229
|
+
throw new Error('导入的凭据值必须是字符串');
|
|
230
|
+
}
|
|
231
|
+
return access((stored) => {
|
|
232
|
+
const mapping = {};
|
|
233
|
+
for (const [oldReference, value] of entries) {
|
|
234
|
+
let next;
|
|
235
|
+
do {
|
|
236
|
+
next = `secret://${randomUUID()}`;
|
|
237
|
+
} while (Object.hasOwn(stored, next) || Object.hasOwn(values, next));
|
|
238
|
+
stored[next] = value;
|
|
239
|
+
mapping[oldReference] = next;
|
|
240
|
+
}
|
|
241
|
+
return { result: mapping, changed: entries.length > 0 };
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"url": "git+https://github.com/JetCrab/pi-desk.git",
|
|
6
6
|
"directory": "plugins/pi-desk-sdk"
|
|
7
7
|
},
|
|
8
|
-
"version": "1.1.
|
|
8
|
+
"version": "1.1.18-dev",
|
|
9
9
|
"license": "Apache-2.0",
|
|
10
10
|
"publishConfig": {
|
|
11
11
|
"registry": "https://registry.npmjs.org",
|
|
@@ -18,6 +18,20 @@
|
|
|
18
18
|
"import": "./dist/index.js",
|
|
19
19
|
"default": "./dist/index.js"
|
|
20
20
|
},
|
|
21
|
+
"./config": {
|
|
22
|
+
"types": "./dist/config.d.ts",
|
|
23
|
+
"node": {
|
|
24
|
+
"import": "./dist/config.js",
|
|
25
|
+
"default": "./dist/config.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"./secrets": {
|
|
29
|
+
"types": "./dist/secrets.d.ts",
|
|
30
|
+
"node": {
|
|
31
|
+
"import": "./dist/secrets.js",
|
|
32
|
+
"default": "./dist/secrets.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
21
35
|
"./settings": {
|
|
22
36
|
"types": "./dist/settings.d.ts",
|
|
23
37
|
"import": "./dist/settings.js",
|
|
@@ -71,6 +85,8 @@
|
|
|
71
85
|
"README.md"
|
|
72
86
|
],
|
|
73
87
|
"dependencies": {
|
|
88
|
+
"@napi-rs/keyring": "2.1.2",
|
|
89
|
+
"proper-lockfile": "^4.1.2",
|
|
74
90
|
"zod": "^4.4.3"
|
|
75
91
|
},
|
|
76
92
|
"peerDependencies": {
|
|
@@ -110,6 +126,7 @@
|
|
|
110
126
|
}
|
|
111
127
|
},
|
|
112
128
|
"devDependencies": {
|
|
129
|
+
"@types/proper-lockfile": "^4.1.4",
|
|
113
130
|
"@base-ui/react": "^1.7.0",
|
|
114
131
|
"@streamdown/cjk": "^1.0.3",
|
|
115
132
|
"@streamdown/code": "^1.1.1",
|
|
@@ -121,6 +138,7 @@
|
|
|
121
138
|
},
|
|
122
139
|
"scripts": {
|
|
123
140
|
"build": "tsc -p tsconfig.json && node scripts/build-host-runtime.mjs",
|
|
141
|
+
"typecheck:isolated": "tsc -p tsconfig.json --noEmit --isolatedModules",
|
|
124
142
|
"test": "pnpm run build && node --test tests/*.test.mjs"
|
|
125
143
|
}
|
|
126
144
|
}
|