@hmharness/lsp 0.23.24 → 0.23.26

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/src/trust.ts CHANGED
@@ -1,108 +1,108 @@
1
- /**
2
- * @hmharness/lsp - source trust (Capability OS first slice, 03 方案 supply-chain guard)
3
- *
4
- * Running a language server means executing a binary we discovered on the
5
- * machine. The 03 plan's supply-chain rule: 来源白名单 + hash. This module
6
- * is that guard:
7
- *
8
- * - every server binary gets a sha256 PIN at trust time
9
- * - DevEco-local servers (official IDE install layout) are auto-trusted
10
- * ONCE — the pin still applies, so a modified binary is caught
11
- * - PATH servers require explicit one-time user trust (hmh lsp trust <id>)
12
- * - a trusted binary whose hash CHANGED is refused (tamper detection),
13
- * with the old and new hash both shown for audit
14
- *
15
- * The trust store lives in HMH_HOME/cognitive/lsp-trust.json — plain JSON,
16
- * user-inspectable, no telemetry.
17
- */
18
- import { createHash } from 'node:crypto';
19
- import { readFile, writeFile, mkdir } from 'node:fs/promises';
20
- import { join } from 'node:path';
21
-
22
- export interface TrustEntry {
23
- id: string;
24
- command: string;
25
- sha256: string;
26
- origin: string;
27
- trustedAt: string;
28
- autoTrusted: boolean;
29
- }
30
-
31
- export interface TrustStore {
32
- kind: 'hmharness-lsp-trust';
33
- version: 1;
34
- entries: Record<string, TrustEntry>;
35
- }
36
-
37
- export function trustPath(home: string): string {
38
- return join(home, 'cognitive', 'lsp-trust.json');
39
- }
40
-
41
- async function loadTrust(home: string): Promise<TrustStore> {
42
- try {
43
- const j = JSON.parse(await readFile(trustPath(home), 'utf8')) as TrustStore;
44
- if (j && j.kind === 'hmharness-lsp-trust' && j.entries && typeof j.entries === 'object') return j;
45
- } catch { /* absent/corrupt = empty store */ }
46
- return { kind: 'hmharness-lsp-trust', version: 1, entries: {} };
47
- }
48
-
49
- /** sha256 of the server binary (the executable file itself). */
50
- export async function serverHash(command: string): Promise<string> {
51
- const buf = await readFile(command);
52
- return createHash('sha256').update(buf).digest('hex');
53
- }
54
-
55
- export interface TrustVerdict {
56
- trusted: boolean;
57
- reason: string;
58
- /** set when the id is trusted but the BINARY changed (tamper case) */
59
- tampered?: { pinned: string; actual: string };
60
- }
61
-
62
- /** Check whether a discovered server may be executed. */
63
- export async function checkTrust(home: string, server: { id: string; command: string; origin: string }): Promise<TrustVerdict> {
64
- const store = await loadTrust(home);
65
- const entry = store.entries[server.id];
66
- const actual = await serverHash(server.command).catch(() => '');
67
- if (!entry) {
68
- if (server.origin.includes('DevEco-local')) {
69
- // official IDE install layout: auto-trust once, pin the hash now
70
- const pinned: TrustEntry = { id: server.id, command: server.command, sha256: actual, origin: server.origin, trustedAt: new Date().toISOString(), autoTrusted: true };
71
- const next = { ...store, entries: { ...store.entries, [server.id]: pinned } };
72
- await mkdir(join(home, 'cognitive'), { recursive: true });
73
- await writeFile(trustPath(home), JSON.stringify(next, null, 1), 'utf8');
74
- return { trusted: true, reason: `auto-trusted (official DevEco-local layout), sha256 pinned ${actual.slice(0, 12)}…` };
75
- }
76
- return { trusted: false, reason: `PATH server not trusted yet — run: hmh lsp trust ${server.id}` };
77
- }
78
- if (entry.sha256 && actual && entry.sha256 !== actual) {
79
- return { trusted: false, reason: `binary CHANGED since trust (tamper?) — pinned ${entry.sha256.slice(0, 12)}…, actual ${actual.slice(0, 12)}…; re-trust only if you know why it changed`, tampered: { pinned: entry.sha256, actual } };
80
- }
81
- return { trusted: true, reason: `trusted since ${entry.trustedAt.slice(0, 10)} (${entry.autoTrusted ? 'auto, DevEco-local' : 'user'}), hash matches` };
82
- }
83
-
84
- /** Explicit user trust: pins the CURRENT hash. */
85
- export async function trustServer(home: string, server: { id: string; command: string; origin: string }): Promise<{ ok: boolean; error?: string; sha256?: string }> {
86
- const sha = await serverHash(server.command).catch(() => '');
87
- if (!sha) return { ok: false, error: 'cannot hash the server binary (unreadable?)' };
88
- const store = await loadTrust(home);
89
- store.entries[server.id] = { id: server.id, command: server.command, sha256: sha, origin: server.origin, trustedAt: new Date().toISOString(), autoTrusted: false };
90
- await mkdir(join(home, 'cognitive'), { recursive: true });
91
- await writeFile(trustPath(home), JSON.stringify(store, null, 1), 'utf8');
92
- return { ok: true, sha256: sha };
93
- }
94
-
95
- /** Revoke trust for a server id. */
96
- export async function untrustServer(home: string, id: string): Promise<boolean> {
97
- const store = await loadTrust(home);
98
- if (!store.entries[id]) return false;
99
- delete store.entries[id];
100
- await writeFile(trustPath(home), JSON.stringify(store, null, 1), 'utf8');
101
- return true;
102
- }
103
-
104
- /** Read-only view for `hmh lsp list`. */
105
- export async function listTrust(home: string): Promise<TrustEntry[]> {
106
- const store = await loadTrust(home);
107
- return Object.values(store.entries);
108
- }
1
+ /**
2
+ * @hmharness/lsp - source trust (Capability OS first slice, 03 方案 supply-chain guard)
3
+ *
4
+ * Running a language server means executing a binary we discovered on the
5
+ * machine. The 03 plan's supply-chain rule: 来源白名单 + hash. This module
6
+ * is that guard:
7
+ *
8
+ * - every server binary gets a sha256 PIN at trust time
9
+ * - DevEco-local servers (official IDE install layout) are auto-trusted
10
+ * ONCE — the pin still applies, so a modified binary is caught
11
+ * - PATH servers require explicit one-time user trust (hmh lsp trust <id>)
12
+ * - a trusted binary whose hash CHANGED is refused (tamper detection),
13
+ * with the old and new hash both shown for audit
14
+ *
15
+ * The trust store lives in HMH_HOME/cognitive/lsp-trust.json — plain JSON,
16
+ * user-inspectable, no telemetry.
17
+ */
18
+ import { createHash } from 'node:crypto';
19
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
20
+ import { join } from 'node:path';
21
+
22
+ export interface TrustEntry {
23
+ id: string;
24
+ command: string;
25
+ sha256: string;
26
+ origin: string;
27
+ trustedAt: string;
28
+ autoTrusted: boolean;
29
+ }
30
+
31
+ export interface TrustStore {
32
+ kind: 'hmharness-lsp-trust';
33
+ version: 1;
34
+ entries: Record<string, TrustEntry>;
35
+ }
36
+
37
+ export function trustPath(home: string): string {
38
+ return join(home, 'cognitive', 'lsp-trust.json');
39
+ }
40
+
41
+ async function loadTrust(home: string): Promise<TrustStore> {
42
+ try {
43
+ const j = JSON.parse(await readFile(trustPath(home), 'utf8')) as TrustStore;
44
+ if (j && j.kind === 'hmharness-lsp-trust' && j.entries && typeof j.entries === 'object') return j;
45
+ } catch { /* absent/corrupt = empty store */ }
46
+ return { kind: 'hmharness-lsp-trust', version: 1, entries: {} };
47
+ }
48
+
49
+ /** sha256 of the server binary (the executable file itself). */
50
+ export async function serverHash(command: string): Promise<string> {
51
+ const buf = await readFile(command);
52
+ return createHash('sha256').update(buf).digest('hex');
53
+ }
54
+
55
+ export interface TrustVerdict {
56
+ trusted: boolean;
57
+ reason: string;
58
+ /** set when the id is trusted but the BINARY changed (tamper case) */
59
+ tampered?: { pinned: string; actual: string };
60
+ }
61
+
62
+ /** Check whether a discovered server may be executed. */
63
+ export async function checkTrust(home: string, server: { id: string; command: string; origin: string }): Promise<TrustVerdict> {
64
+ const store = await loadTrust(home);
65
+ const entry = store.entries[server.id];
66
+ const actual = await serverHash(server.command).catch(() => '');
67
+ if (!entry) {
68
+ if (server.origin.includes('DevEco-local')) {
69
+ // official IDE install layout: auto-trust once, pin the hash now
70
+ const pinned: TrustEntry = { id: server.id, command: server.command, sha256: actual, origin: server.origin, trustedAt: new Date().toISOString(), autoTrusted: true };
71
+ const next = { ...store, entries: { ...store.entries, [server.id]: pinned } };
72
+ await mkdir(join(home, 'cognitive'), { recursive: true });
73
+ await writeFile(trustPath(home), JSON.stringify(next, null, 1), 'utf8');
74
+ return { trusted: true, reason: `auto-trusted (official DevEco-local layout), sha256 pinned ${actual.slice(0, 12)}…` };
75
+ }
76
+ return { trusted: false, reason: `PATH server not trusted yet — run: hmh lsp trust ${server.id}` };
77
+ }
78
+ if (entry.sha256 && actual && entry.sha256 !== actual) {
79
+ return { trusted: false, reason: `binary CHANGED since trust (tamper?) — pinned ${entry.sha256.slice(0, 12)}…, actual ${actual.slice(0, 12)}…; re-trust only if you know why it changed`, tampered: { pinned: entry.sha256, actual } };
80
+ }
81
+ return { trusted: true, reason: `trusted since ${entry.trustedAt.slice(0, 10)} (${entry.autoTrusted ? 'auto, DevEco-local' : 'user'}), hash matches` };
82
+ }
83
+
84
+ /** Explicit user trust: pins the CURRENT hash. */
85
+ export async function trustServer(home: string, server: { id: string; command: string; origin: string }): Promise<{ ok: boolean; error?: string; sha256?: string }> {
86
+ const sha = await serverHash(server.command).catch(() => '');
87
+ if (!sha) return { ok: false, error: 'cannot hash the server binary (unreadable?)' };
88
+ const store = await loadTrust(home);
89
+ store.entries[server.id] = { id: server.id, command: server.command, sha256: sha, origin: server.origin, trustedAt: new Date().toISOString(), autoTrusted: false };
90
+ await mkdir(join(home, 'cognitive'), { recursive: true });
91
+ await writeFile(trustPath(home), JSON.stringify(store, null, 1), 'utf8');
92
+ return { ok: true, sha256: sha };
93
+ }
94
+
95
+ /** Revoke trust for a server id. */
96
+ export async function untrustServer(home: string, id: string): Promise<boolean> {
97
+ const store = await loadTrust(home);
98
+ if (!store.entries[id]) return false;
99
+ delete store.entries[id];
100
+ await writeFile(trustPath(home), JSON.stringify(store, null, 1), 'utf8');
101
+ return true;
102
+ }
103
+
104
+ /** Read-only view for `hmh lsp list`. */
105
+ export async function listTrust(home: string): Promise<TrustEntry[]> {
106
+ const store = await loadTrust(home);
107
+ return Object.values(store.entries);
108
+ }
@@ -1,18 +1,18 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "compilerOptions": {
4
- "noEmit": false,
5
- "allowImportingTsExtensions": false,
6
- "rewriteRelativeImportExtensions": true,
7
- "declaration": true,
8
- "outDir": "dist",
9
- "rootDir": "src",
10
- "paths": {}
11
- },
12
- "include": [
13
- "src/**/*.ts"
14
- ],
15
- "exclude": [
16
- "src/__tests__"
17
- ]
18
- }
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": false,
5
+ "allowImportingTsExtensions": false,
6
+ "rewriteRelativeImportExtensions": true,
7
+ "declaration": true,
8
+ "outDir": "dist",
9
+ "rootDir": "src",
10
+ "paths": {}
11
+ },
12
+ "include": [
13
+ "src/**/*.ts"
14
+ ],
15
+ "exclude": [
16
+ "src/__tests__"
17
+ ]
18
+ }
package/verify-clangd.mts CHANGED
@@ -1,40 +1,40 @@
1
- // REAL-server full-chain verification against DevEco's bundled clangd
2
- // (the previously NOT VERIFIED item: no healthy language server existed)
3
- import { ProcessManager, LspClient, discoverServers, fileToUri } from './src/index.ts';
4
-
5
- const clangd = discoverServers(true).find((s) => s.id === 'clangd' && s.origin === 'DevEco-local');
6
- if (!clangd || !clangd.healthy) {
7
- console.log('DevEco clangd not discovered/healthy:', clangd?.unhealthyReason ?? 'absent');
8
- process.exit(0);
9
- }
10
- console.log('server:', clangd.command, '| origin:', clangd.origin, '| official:', clangd.official);
11
-
12
- import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
13
- import { tmpdir } from 'node:os';
14
- import { join } from 'node:path';
15
- const ws = mkdtempSync(join(tmpdir(), 'clangd-ws-'));
16
- // a C file with a REAL syntax error (missing semicolon)
17
- writeFileSync(join(ws, 'probe.c'), 'int main(void) {\n int x = 1\n return x;\n}\n');
18
-
19
- const mgr = new ProcessManager(clangd, ws);
20
- const diags: Array<{ uri: string; n: number; msgs: string[] }> = [];
21
- const client = new LspClient(mgr.start(), {
22
- requestTimeoutMs: 30_000,
23
- onDiagnostics: (uri, d) => diags.push({ uri, n: d.length, msgs: d.map((x) => x.message.slice(0, 60)) }),
24
- });
25
- const init = await client.initialize(fileToUri(ws));
26
- console.log('initialize OK:', JSON.stringify(init.serverInfo), '| hoverProvider:', Boolean((init.capabilities as Record<string, unknown>).hoverProvider));
27
- const uri = fileToUri(join(ws, 'probe.c'));
28
- client.openDoc(uri, 'c', 'int main(void) {\n int x = 1\n return x;\n}\n');
29
- // clangd needs a moment to parse and publish
30
- await new Promise((r) => setTimeout(r, 4_000));
31
- const got = diags.filter((d) => d.uri === uri);
32
- console.log('diagnostics pushes:', got.length, '| total diags:', got.reduce((s, d) => s + d.n, 0));
33
- if (got.length > 0 && got[0]!.n > 0) console.log('first diag:', got[0]!.msgs[0]);
34
- const hover = await client.hover({ uri }, { line: 0, character: 5 }).catch((e: Error) => ({ error: e.message }));
35
- console.log('hover:', hover && 'contents' in (hover as object) ? 'returned' : JSON.stringify(hover).slice(0, 120));
36
- await client.shutdown();
37
- await mgr.stop();
38
- console.log('stopped cleanly:', mgr.running === false);
39
- rmSync(ws, { recursive: true, force: true });
40
- console.log('REAL-SERVER (DevEco clangd) FULL CHAIN:', diags.length > 0 ? 'VERIFIED' : 'handshake verified, no diagnostics pushed');
1
+ // REAL-server full-chain verification against DevEco's bundled clangd
2
+ // (the previously NOT VERIFIED item: no healthy language server existed)
3
+ import { ProcessManager, LspClient, discoverServers, fileToUri } from './src/index.ts';
4
+
5
+ const clangd = discoverServers(true).find((s) => s.id === 'clangd' && s.origin === 'DevEco-local');
6
+ if (!clangd || !clangd.healthy) {
7
+ console.log('DevEco clangd not discovered/healthy:', clangd?.unhealthyReason ?? 'absent');
8
+ process.exit(0);
9
+ }
10
+ console.log('server:', clangd.command, '| origin:', clangd.origin, '| official:', clangd.official);
11
+
12
+ import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
13
+ import { tmpdir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ const ws = mkdtempSync(join(tmpdir(), 'clangd-ws-'));
16
+ // a C file with a REAL syntax error (missing semicolon)
17
+ writeFileSync(join(ws, 'probe.c'), 'int main(void) {\n int x = 1\n return x;\n}\n');
18
+
19
+ const mgr = new ProcessManager(clangd, ws);
20
+ const diags: Array<{ uri: string; n: number; msgs: string[] }> = [];
21
+ const client = new LspClient(mgr.start(), {
22
+ requestTimeoutMs: 30_000,
23
+ onDiagnostics: (uri, d) => diags.push({ uri, n: d.length, msgs: d.map((x) => x.message.slice(0, 60)) }),
24
+ });
25
+ const init = await client.initialize(fileToUri(ws));
26
+ console.log('initialize OK:', JSON.stringify(init.serverInfo), '| hoverProvider:', Boolean((init.capabilities as Record<string, unknown>).hoverProvider));
27
+ const uri = fileToUri(join(ws, 'probe.c'));
28
+ client.openDoc(uri, 'c', 'int main(void) {\n int x = 1\n return x;\n}\n');
29
+ // clangd needs a moment to parse and publish
30
+ await new Promise((r) => setTimeout(r, 4_000));
31
+ const got = diags.filter((d) => d.uri === uri);
32
+ console.log('diagnostics pushes:', got.length, '| total diags:', got.reduce((s, d) => s + d.n, 0));
33
+ if (got.length > 0 && got[0]!.n > 0) console.log('first diag:', got[0]!.msgs[0]);
34
+ const hover = await client.hover({ uri }, { line: 0, character: 5 }).catch((e: Error) => ({ error: e.message }));
35
+ console.log('hover:', hover && 'contents' in (hover as object) ? 'returned' : JSON.stringify(hover).slice(0, 120));
36
+ await client.shutdown();
37
+ await mgr.stop();
38
+ console.log('stopped cleanly:', mgr.running === false);
39
+ rmSync(ws, { recursive: true, force: true });
40
+ console.log('REAL-SERVER (DevEco clangd) FULL CHAIN:', diags.length > 0 ? 'VERIFIED' : 'handshake verified, no diagnostics pushed');
package/verify-live.mts CHANGED
@@ -1,27 +1,27 @@
1
- // Real-machine LSP verification against the fake server via the public surface
2
- import { shutdownLsp, discoverServers, ProcessManager, LspClient, fileToUri } from './src/index.ts';
3
- import { writeFileSync, mkdirSync, rmSync } from 'node:fs';
4
-
5
- const ws = 'G:/hmharness/.tmp-lsp-ws';
6
- rmSync(ws, { recursive: true, force: true });
7
- mkdirSync(ws, { recursive: true });
8
- writeFileSync(ws + '/demo.ts', 'const x: number = 1;\nconsole.log(x);\n');
9
-
10
- console.log('discovered real servers:', discoverServers().map((s) => s.id).join(', ') || '(none)');
11
-
12
- const mgr = new ProcessManager({ id: 'fake', command: process.execPath, args: ['src/__tests__/fixtures/fake-server.cjs'], source: 'explicit' }, process.cwd());
13
- const client = new LspClient(mgr.start(), { requestTimeoutMs: 10_000 });
14
- const info = await client.initialize(fileToUri(ws));
15
- console.log('initialized:', info.serverInfo?.name, info.serverInfo?.version);
16
- const uri = fileToUri(ws + '/demo.ts');
17
- client.openDoc(uri, 'typescript', 'const y = DELBERATE_ERROR_MARKER;\n');
18
- await new Promise((r) => setTimeout(r, 400));
19
- const hover = await client.hover({ uri }, { line: 0, character: 6 });
20
- console.log('hover:', JSON.stringify(hover?.contents).slice(0, 80));
21
- const def = await client.definition({ uri }, { line: 0, character: 6 });
22
- console.log('definition:', Array.isArray(def) ? def[0]?.uri : def?.uri);
23
- await client.shutdown();
24
- await mgr.stop();
25
- console.log('stopped:', mgr.running === false);
26
- await shutdownLsp();
27
- console.log('REAL-MACHINE (fake-server) LIFECYCLE OK — real typescript-language-server: NOT ON PATH (NOT VERIFIED against a real server this round)');
1
+ // Real-machine LSP verification against the fake server via the public surface
2
+ import { shutdownLsp, discoverServers, ProcessManager, LspClient, fileToUri } from './src/index.ts';
3
+ import { writeFileSync, mkdirSync, rmSync } from 'node:fs';
4
+
5
+ const ws = 'G:/hmharness/.tmp-lsp-ws';
6
+ rmSync(ws, { recursive: true, force: true });
7
+ mkdirSync(ws, { recursive: true });
8
+ writeFileSync(ws + '/demo.ts', 'const x: number = 1;\nconsole.log(x);\n');
9
+
10
+ console.log('discovered real servers:', discoverServers().map((s) => s.id).join(', ') || '(none)');
11
+
12
+ const mgr = new ProcessManager({ id: 'fake', command: process.execPath, args: ['src/__tests__/fixtures/fake-server.cjs'], source: 'explicit' }, process.cwd());
13
+ const client = new LspClient(mgr.start(), { requestTimeoutMs: 10_000 });
14
+ const info = await client.initialize(fileToUri(ws));
15
+ console.log('initialized:', info.serverInfo?.name, info.serverInfo?.version);
16
+ const uri = fileToUri(ws + '/demo.ts');
17
+ client.openDoc(uri, 'typescript', 'const y = DELBERATE_ERROR_MARKER;\n');
18
+ await new Promise((r) => setTimeout(r, 400));
19
+ const hover = await client.hover({ uri }, { line: 0, character: 6 });
20
+ console.log('hover:', JSON.stringify(hover?.contents).slice(0, 80));
21
+ const def = await client.definition({ uri }, { line: 0, character: 6 });
22
+ console.log('definition:', Array.isArray(def) ? def[0]?.uri : def?.uri);
23
+ await client.shutdown();
24
+ await mgr.stop();
25
+ console.log('stopped:', mgr.running === false);
26
+ await shutdownLsp();
27
+ console.log('REAL-MACHINE (fake-server) LIFECYCLE OK — real typescript-language-server: NOT ON PATH (NOT VERIFIED against a real server this round)');