@jetcrab/pi-desk-sdk 1.1.18-dev → 1.1.19-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 CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  包名:`@jetcrab/pi-desk-sdk`。公开接口以本版本 `package.json` 的 exports 和对应 TypeScript 声明为准。
4
4
 
5
- Node-only `/config` 只提供当前配置目录、同目标串行读改写与原子文本写入,`/secrets` 提供凭据引用与加密存储;不从根入口或 Browser 导出,不依赖常驻 Global Host。配置只读取当前路径和格式,旧配置需在升级前另行准备,启动和读取不会自动搬迁或回写旧文件。
5
+ Node 与 Session 插件通过绑定身份的 `plugin.config` 使用 `encrypt`、`decrypt`、`set`、`get` 四接口;用户级配置统一保存在 `<AgentDir>/config/pi-desk.yaml`,可按 JSON Pointer 与 `*` 路径选择加解密。密文内联,系统仅托管主密钥。`/config` 提供宿主装配和文件级工具,`/secrets` 保留旧凭据接口供现有项目配置使用。旧全局配置不迁移、不删除、不回退读取;原生 Pi 配置与项目配置位置保持不变。
6
6
 
7
- SDK 的运行依赖为 Zod(协议 Schema)、`proper-lockfile`(Node 跨进程锁)和 `@napi-rs/keyring`(Node 系统持久密钥存储)。协议与 Browser 子入口不加载这些 Node 配置或凭据能力,非 React 使用不要求安装公共 UI 库。
7
+ SDK 的运行依赖为 Zod(协议 Schema)、`yaml`(统一配置)、`proper-lockfile`(Node 跨进程锁)和 `@napi-rs/keyring`(Node 系统持久密钥存储)。协议与 Browser 子入口不加载这些 Node 配置或凭据能力,非 React 使用不要求安装公共 UI 库。
8
8
 
9
9
  本包自有代码使用 Apache-2.0,见 [LICENSE](./LICENSE)。第三方代码继续遵循其原有许可,构建时保留上游法律注释。
package/dist/browser.d.ts CHANGED
@@ -179,7 +179,21 @@ export interface BrowserTunnelHost {
179
179
  remotePort: number;
180
180
  }): BrowserTunnelHandle;
181
181
  }
182
+ export interface BrowserFloatingHandle {
183
+ close(): void;
184
+ }
185
+ export interface BrowserFloatingImplementation {
186
+ mount: BrowserMount<BrowserFloatingHandle>;
187
+ }
188
+ export interface BrowserFloatingOpenInput {
189
+ id: string;
190
+ load(): Promise<BrowserFloatingImplementation>;
191
+ }
192
+ export interface BrowserFloatingHost {
193
+ open(input: BrowserFloatingOpenInput): BrowserFloatingHandle;
194
+ }
182
195
  export interface BrowserPluginHost {
196
+ readonly floating: BrowserFloatingHost;
183
197
  readonly events: HostEvents<BrowserHostEventMap>;
184
198
  readonly settings: HostSettings;
185
199
  /** 映射当前工作台后端的已发布 TCP 端口;旧宿主或无原生能力时不可用。 */
@@ -0,0 +1,8 @@
1
+ import type { PluginJsonObject, PluginJsonValue } from './shared.js';
2
+ /** 宿主按插件身份绑定;不暴露文件位置或密钥。 */
3
+ export interface PluginConfig {
4
+ encrypt(value: PluginJsonValue): Promise<string>;
5
+ decrypt(value: string): Promise<PluginJsonValue>;
6
+ set(conf: PluginJsonObject, encryptPaths?: readonly string[]): Promise<void>;
7
+ get(decryptPaths?: readonly string[]): Promise<PluginJsonObject>;
8
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { PluginJsonValue } from './shared.js';
2
+ export interface ConfigKeyOptions {
3
+ /** 仅由宿主或隔离测试注入,不属于插件配置接口。 */
4
+ keyProvider?: () => Promise<Uint8Array>;
5
+ }
6
+ export declare function isEncryptedConfigValue(value: unknown): value is string;
7
+ export declare function hasEncryptedConfigValue(value: PluginJsonValue): boolean;
8
+ export declare function loadConfigKey(path: string, encryptedExists: boolean, options: ConfigKeyOptions, assertActive: () => void): Promise<Buffer>;
9
+ export declare function encryptConfigValue(value: PluginJsonValue, key: Buffer): string;
10
+ export declare function decryptConfigValue(value: string, key: Buffer): PluginJsonValue;
@@ -0,0 +1,114 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
2
+ import { realpathSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { readStorageFile } from "./config-storage.js";
6
+ const prefix = 'enc:v1:';
7
+ const aad = Buffer.from('pi-desk/config/v1');
8
+ export function isEncryptedConfigValue(value) {
9
+ return typeof value === 'string' && value.startsWith(prefix);
10
+ }
11
+ export function hasEncryptedConfigValue(value) {
12
+ if (isEncryptedConfigValue(value))
13
+ return true;
14
+ return value !== null && typeof value === 'object'
15
+ ? Object.values(value).some(hasEncryptedConfigValue)
16
+ : false;
17
+ }
18
+ function keyBytes(value) {
19
+ if (!(value instanceof Uint8Array) || value.byteLength !== 32) {
20
+ throw new Error('配置主密钥必须是原始 32 字节');
21
+ }
22
+ return Buffer.from(value);
23
+ }
24
+ export async function loadConfigKey(path, encryptedExists, options, assertActive) {
25
+ if (options.keyProvider)
26
+ return keyBytes(await options.keyProvider());
27
+ const file = process.env.PI_DESK_SECRET_KEY_FILE;
28
+ if (file !== undefined) {
29
+ if (!file)
30
+ throw new Error('PI_DESK_SECRET_KEY_FILE 必须指定外部密钥文件');
31
+ const bytes = readStorageFile(resolve(file));
32
+ if (bytes === null)
33
+ throw new Error('配置外部密钥文件不存在');
34
+ try {
35
+ return keyBytes(bytes);
36
+ }
37
+ finally {
38
+ bytes.fill(0);
39
+ }
40
+ }
41
+ try {
42
+ const { Entry } = await import('@napi-rs/keyring');
43
+ const directory = realpathSync(dirname(path));
44
+ const identity = process.platform === 'win32' ? directory.toLowerCase() : directory;
45
+ const account = createHash('sha256').update(identity).digest('hex');
46
+ const entry = new Entry('pi-desk.config', account, { linux: { store: 'secret-service' } });
47
+ const stored = entry.getPassword();
48
+ if (stored !== null) {
49
+ const key = Buffer.from(stored, 'base64');
50
+ if (key.length !== 32 || key.toString('base64') !== stored) {
51
+ key.fill(0);
52
+ throw new Error('配置主密钥格式无效');
53
+ }
54
+ return key;
55
+ }
56
+ if (encryptedExists)
57
+ throw new Error('配置密文已存在但主密钥缺失,拒绝生成替代密钥');
58
+ assertActive();
59
+ const key = randomBytes(32);
60
+ try {
61
+ entry.setPassword(key.toString('base64'));
62
+ if (entry.getPassword() !== key.toString('base64'))
63
+ throw new Error('主密钥回读失败');
64
+ return key;
65
+ }
66
+ catch {
67
+ key.fill(0);
68
+ throw new Error('保存配置主密钥失败');
69
+ }
70
+ }
71
+ catch (cause) {
72
+ // 系统原生错误可能带凭据正文,不向插件转发。
73
+ const message = cause instanceof Error && /^配置(密文|主密钥)/u.test(cause.message)
74
+ ? cause.message
75
+ : '系统钥匙串不可用,无法取得配置主密钥';
76
+ throw new Error(message);
77
+ }
78
+ }
79
+ export function encryptConfigValue(value, key) {
80
+ const nonce = randomBytes(12);
81
+ const cipher = createCipheriv('aes-256-gcm', key, nonce);
82
+ cipher.setAAD(aad);
83
+ const plaintext = Buffer.from(JSON.stringify(z.json().parse(value)));
84
+ try {
85
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
86
+ return prefix + Buffer.concat([nonce, cipher.getAuthTag(), encrypted]).toString('base64');
87
+ }
88
+ finally {
89
+ plaintext.fill(0);
90
+ }
91
+ }
92
+ export function decryptConfigValue(value, key) {
93
+ try {
94
+ if (!isEncryptedConfigValue(value))
95
+ throw new Error();
96
+ const encoded = value.slice(prefix.length);
97
+ const bytes = Buffer.from(encoded, 'base64');
98
+ if (bytes.length < 29 || bytes.toString('base64') !== encoded)
99
+ throw new Error();
100
+ const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12));
101
+ decipher.setAAD(aad);
102
+ decipher.setAuthTag(bytes.subarray(12, 28));
103
+ const plaintext = Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]);
104
+ try {
105
+ return z.json().parse(JSON.parse(plaintext.toString('utf8')));
106
+ }
107
+ finally {
108
+ plaintext.fill(0);
109
+ }
110
+ }
111
+ catch {
112
+ throw new Error('配置密文认证失败或格式无效');
113
+ }
114
+ }
@@ -0,0 +1,9 @@
1
+ import type { PluginJsonObject, PluginJsonValue } from './shared.js';
2
+ export interface ConfigValueLocation {
3
+ parent: PluginJsonObject | PluginJsonValue[];
4
+ key: string;
5
+ parts: string[];
6
+ }
7
+ export declare function configValueLocations(conf: PluginJsonObject, paths: readonly string[]): ConfigValueLocation[];
8
+ export declare function getConfigLocation(location: ConfigValueLocation): PluginJsonValue;
9
+ export declare function setConfigLocation(location: ConfigValueLocation, value: PluginJsonValue): void;
@@ -0,0 +1,50 @@
1
+ export function configValueLocations(conf, paths) {
2
+ const found = new Map();
3
+ for (const path of paths) {
4
+ if (typeof path !== 'string' || !path.startsWith('/') || /~(?![01])/u.test(path)) {
5
+ throw new Error('配置路径必须是非根 JSON Pointer,可用 * 匹配当前层所有成员');
6
+ }
7
+ const parts = path
8
+ .slice(1)
9
+ .split('/')
10
+ .map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~'));
11
+ function visit(value, index, prefix) {
12
+ if (value === null || typeof value !== 'object')
13
+ return;
14
+ const part = parts[index];
15
+ for (const key of part === '*' ? Object.keys(value) : [part]) {
16
+ if (!Object.prototype.propertyIsEnumerable.call(value, key))
17
+ continue;
18
+ const location = [...prefix, key];
19
+ if (index === parts.length - 1) {
20
+ found.set(JSON.stringify(location), { parent: value, key, parts: location });
21
+ }
22
+ else {
23
+ const child = Array.isArray(value) ? value[Number(key)] : value[key];
24
+ visit(child, index + 1, location);
25
+ }
26
+ }
27
+ }
28
+ visit(conf, 0, []);
29
+ }
30
+ const locations = [...found.values()];
31
+ for (const current of locations) {
32
+ for (let length = 1; length < current.parts.length; length += 1) {
33
+ if (found.has(JSON.stringify(current.parts.slice(0, length)))) {
34
+ throw new Error('配置加解密路径不能同时包含父节点和子节点');
35
+ }
36
+ }
37
+ }
38
+ return locations;
39
+ }
40
+ export function getConfigLocation(location) {
41
+ return Array.isArray(location.parent)
42
+ ? location.parent[Number(location.key)]
43
+ : location.parent[location.key];
44
+ }
45
+ export function setConfigLocation(location, value) {
46
+ if (Array.isArray(location.parent))
47
+ location.parent[Number(location.key)] = value;
48
+ else
49
+ location.parent[location.key] = value;
50
+ }
@@ -1,4 +1,4 @@
1
1
  export declare function ensureStorageDirectory(path: string): void;
2
- export declare function readStorageFile(path: string): Buffer | null;
2
+ export declare function readStorageFile(path: string, maximumBytes?: number): Buffer | null;
3
3
  export declare function writeStorageFile(path: string, content: Buffer, expected: Buffer | null): void;
4
4
  export declare function withStorageLock<T>(path: string, action: (assertLocked: () => void) => Promise<T>): Promise<T>;
@@ -34,13 +34,16 @@ function assertDirectories(path) {
34
34
  throw storageError('检查配置目录', path, error);
35
35
  }
36
36
  }
37
- export function readStorageFile(path) {
37
+ export function readStorageFile(path, maximumBytes) {
38
38
  assertDirectories(dirname(path));
39
39
  let descriptor;
40
40
  try {
41
41
  const stat = lstatSync(path);
42
42
  if (!stat.isFile())
43
43
  throw new Error(`拒绝读取非普通配置文件或符号链接:${path}`);
44
+ if (maximumBytes !== undefined && stat.size > maximumBytes) {
45
+ throw new Error(`拒绝读取超过容量限制的配置文件:${path}`);
46
+ }
44
47
  descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
45
48
  const opened = fstatSync(descriptor);
46
49
  if (!opened.isFile() || opened.ino !== stat.ino || opened.dev !== stat.dev) {
@@ -83,7 +86,8 @@ export function writeStorageFile(path, content, expected) {
83
86
  let descriptor;
84
87
  let committed = false;
85
88
  try {
86
- descriptor = openSync(temporary, 'wx', 0o600);
89
+ const mode = expected !== null && process.platform !== 'win32' ? lstatSync(path).mode & 0o600 : 0o600;
90
+ descriptor = openSync(temporary, 'wx', mode);
87
91
  writeFileSync(descriptor, content);
88
92
  fsyncSync(descriptor);
89
93
  closeSync(descriptor);
@@ -0,0 +1,13 @@
1
+ import type { PluginConfig } from './config-api.js';
2
+ import { type ConfigKeyOptions } from './config-encryption.ts';
3
+ import { type PluginJsonObject } from './shared.ts';
4
+ export interface ConfigStoreOptions extends ConfigKeyOptions {
5
+ agentDir?: string;
6
+ /** 宿主 Owner 失效后禁止新操作及尚未发布的写入。 */
7
+ assertActive?: () => void;
8
+ }
9
+ export declare function getUnifiedConfigPath(agentDir?: string): string;
10
+ /** 宿主同步启动读取普通配置;插件业务使用四接口,不从这里解密。 */
11
+ export declare function readConfigSection(namespace: 'pi-desk' | 'plugins', name: string, agentDir?: string): PluginJsonObject;
12
+ /** 供宿主装配与原生绑定使用,业务插件直接使用绑定后的 plugin.config。 */
13
+ export declare function bindConfigStore(namespace: 'pi-desk' | 'plugins', name: string, options?: ConfigStoreOptions): PluginConfig;
@@ -0,0 +1,98 @@
1
+ import { dirname } from 'node:path';
2
+ import { parseDocument } from 'yaml';
3
+ import { z } from 'zod';
4
+ import { getConfigPath } from "./config.js";
5
+ import { ensureStorageDirectory, readStorageFile, withStorageLock, writeStorageFile } from "./config-storage.js";
6
+ import { configValueLocations, getConfigLocation, setConfigLocation } from "./config-paths.js";
7
+ import { decryptConfigValue, encryptConfigValue, hasEncryptedConfigValue, isEncryptedConfigValue, loadConfigKey } from "./config-encryption.js";
8
+ import { normalizePluginIdentifier } from "./shared.js";
9
+ const dictionary = z.record(z.string(), z.json());
10
+ const maxConfigBytes = 8 * 1024 * 1024;
11
+ export function getUnifiedConfigPath(agentDir) {
12
+ return getConfigPath('pi-desk.yaml', agentDir);
13
+ }
14
+ function readDocument(path) {
15
+ const previous = readStorageFile(path, maxConfigBytes);
16
+ const document = parseDocument(previous?.toString('utf8') ?? '{}\n', {
17
+ uniqueKeys: true,
18
+ schema: 'core'
19
+ });
20
+ if (document.errors.length)
21
+ throw new Error(`统一配置 YAML 无法解析:${path}`);
22
+ const root = dictionary.parse(document.toJS({ maxAliasCount: 100 }) ?? {});
23
+ for (const namespace of ['pi-desk', 'plugins']) {
24
+ if (Object.hasOwn(root, namespace))
25
+ dictionary.parse(root[namespace]);
26
+ }
27
+ return { previous, document, root };
28
+ }
29
+ /** 宿主同步启动读取普通配置;插件业务使用四接口,不从这里解密。 */
30
+ export function readConfigSection(namespace, name, agentDir) {
31
+ const { root } = readDocument(getUnifiedConfigPath(agentDir));
32
+ return dictionary.parse(dictionary.parse(root[namespace] ?? {})[name] ?? {});
33
+ }
34
+ /** 供宿主装配与原生绑定使用,业务插件直接使用绑定后的 plugin.config。 */
35
+ export function bindConfigStore(namespace, name, options = {}) {
36
+ name = normalizePluginIdentifier(name, 'pluginName');
37
+ const path = getUnifiedConfigPath(options.agentDir);
38
+ const assertActive = () => options.assertActive?.();
39
+ async function access(action) {
40
+ assertActive();
41
+ ensureStorageDirectory(dirname(path));
42
+ return withStorageLock(path, async (assertLocked) => {
43
+ const assertCurrent = () => {
44
+ assertLocked();
45
+ assertActive();
46
+ };
47
+ assertCurrent();
48
+ const state = readDocument(path);
49
+ let loadedKey;
50
+ try {
51
+ return await action(state, async (required) => {
52
+ loadedKey ??= await loadConfigKey(path, required || hasEncryptedConfigValue(state.root), options, assertCurrent);
53
+ assertCurrent();
54
+ return loadedKey;
55
+ }, assertCurrent);
56
+ }
57
+ finally {
58
+ loadedKey?.fill(0);
59
+ }
60
+ });
61
+ }
62
+ return {
63
+ async encrypt(value) {
64
+ return access(async (_state, key) => encryptConfigValue(value, await key(false)));
65
+ },
66
+ async decrypt(value) {
67
+ return access(async (_state, key) => decryptConfigValue(value, await key(true)));
68
+ },
69
+ async set(conf, encryptPaths = []) {
70
+ const next = dictionary.parse(conf);
71
+ const locations = configValueLocations(next, encryptPaths);
72
+ await access(async (state, key, assertCurrent) => {
73
+ for (const location of locations) {
74
+ setConfigLocation(location, encryptConfigValue(getConfigLocation(location), await key(false)));
75
+ }
76
+ state.document.setIn([namespace, name], next);
77
+ const content = Buffer.from(state.document.toString());
78
+ if (content.byteLength > maxConfigBytes)
79
+ throw new Error('统一配置文件不能超过 8 MiB');
80
+ assertCurrent();
81
+ writeStorageFile(path, content, state.previous);
82
+ });
83
+ },
84
+ async get(decryptPaths = []) {
85
+ return access(async ({ root }, key) => {
86
+ const section = dictionary.parse(root[namespace] ?? {});
87
+ const conf = dictionary.parse(section[name] ?? {});
88
+ for (const location of configValueLocations(conf, decryptPaths)) {
89
+ const value = getConfigLocation(location);
90
+ if (isEncryptedConfigValue(value)) {
91
+ setConfigLocation(location, decryptConfigValue(value, await key(true)));
92
+ }
93
+ }
94
+ return conf;
95
+ });
96
+ }
97
+ };
98
+ }
package/dist/config.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export type { PluginConfig } from './config-api.js';
2
+ export { bindConfigStore, getUnifiedConfigPath, readConfigSection, type ConfigStoreOptions } from './config-store.ts';
1
3
  export declare function getConfigDirectory(agentDir?: string): string;
2
4
  export declare function getConfigPath(filename: string, agentDir?: string): string;
3
5
  /** 串行保护同一目标的完整读改写;操作内不能嵌套获取同一目标锁。 */
package/dist/config.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { bindConfigStore, getUnifiedConfigPath, readConfigSection } from "./config-store.js";
1
2
  import { getAgentDir } from '@earendil-works/pi-coding-agent';
2
3
  import { dirname, join, resolve } from 'node:path';
3
4
  import { ensureStorageDirectory, readStorageFile, withStorageLock, writeStorageFile } from "./config-storage.js";
package/dist/entry.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { PluginConfig } from './config-api.js';
2
+ export type { PluginConfig } from './config-api.js';
1
3
  import type { CapabilityDeclarations } from './capabilities.js';
2
4
  import type { HostSettings } from './settings.js';
3
5
  import type { HostEvents, NodeHostEventMap } from './events.js';
@@ -116,6 +118,7 @@ export interface PluginMessageDeclaration {
116
118
  }
117
119
  export interface PiDeskPluginFacade {
118
120
  readonly name: string;
121
+ readonly config: PluginConfig;
119
122
  readonly host: PiDeskPluginHost;
120
123
  readonly notifications: PiDeskPluginNotifications;
121
124
  setState(state: PluginJsonObject | null): void;