session-peer 0.4.0 → 0.5.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/dist/process.js CHANGED
@@ -1,7 +1,8 @@
1
- import { spawn } from 'node:child_process';
1
+ import childProcess, { spawn } from 'node:child_process';
2
2
  import { accessSync, constants, realpathSync, statSync } from 'node:fs';
3
3
  import { delimiter, isAbsolute, join } from 'node:path';
4
4
  import { StringDecoder } from 'node:string_decoder';
5
+ import timers from 'node:timers/promises';
5
6
  import { Refusal } from './discovery.js';
6
7
  export class UnknownOutcome extends Error {
7
8
  }
@@ -37,7 +38,8 @@ export function executable(name) {
37
38
  // this CLI reaps that group, which includes descendants such as a jump
38
39
  // ProxyCommand, and nothing else; a descendant that calls setsid() itself has
39
40
  // left the group and is out of scope (there is no PID scanning). Windows has no
40
- // equivalent here: only the child is killed and descendants may linger.
41
+ // equivalent here: only the child is killed and descendants may linger; the
42
+ // tree backend below is a candidate that is deliberately not used (#131).
41
43
  const groups = new Set();
42
44
  const posix = process.platform !== 'win32';
43
45
  const reap = (pid) => { if (pid)
@@ -150,3 +152,283 @@ export function run(binary, args, options = {}) {
150
152
  child.stdin.end(options.input);
151
153
  });
152
154
  }
155
+ // Request: "<hold csv|-> <kill csv|->". Reply: "ok <rows> <held> <errors>"
156
+ // with rows pid:ppid, held pid:start:exit (exit empty while running) and errors
157
+ // pid:gone|denied. Get-CimInstance returns no command lines or arguments here.
158
+ const helperScript = String.raw `
159
+ $ErrorActionPreference = 'Stop'
160
+ $held = @{}
161
+ function Ids([string]$text) {
162
+ if ($text -eq '-') { return @() }
163
+ if ($text -notmatch '^[0-9]{1,10}(,[0-9]{1,10}){0,4095}$') { throw 'invalid_request' }
164
+ return @($text.Split(',') | ForEach-Object { [int]$_ })
165
+ }
166
+ function Field($list) { if ($list.Count) { return ($list -join ',') }; return '-' }
167
+ function Ticks([DateTime]$time) { return $time.ToUniversalTime().ToFileTimeUtc().ToString([Globalization.CultureInfo]::InvariantCulture) }
168
+ while ($null -ne ($line = [Console]::In.ReadLine())) {
169
+ try {
170
+ $parts = $line.Split(' ')
171
+ if ($parts.Count -ne 2) { throw 'invalid_request' }
172
+ $errors = @()
173
+ foreach ($id in (Ids $parts[0])) {
174
+ if ($held.ContainsKey($id)) { continue }
175
+ try {
176
+ $item = [Diagnostics.Process]::GetProcessById($id)
177
+ # Handle opens and caches one handle; StartTime, HasExited and Kill
178
+ # below all use it, so the identity checked is the identity killed.
179
+ $null = $item.Handle
180
+ $held[$id] = $item
181
+ } catch [ComponentModel.Win32Exception] {
182
+ $kind = 'gone'; if ($_.Exception.NativeErrorCode -eq 5) { $kind = 'denied' }
183
+ $errors += "$($id):$kind"
184
+ } catch { $errors += "$($id):gone" }
185
+ }
186
+ # Snapshot right after the holds and before any kill, so every candidate
187
+ # held here that is still running is listed with its own parent.
188
+ $rows = @(Get-CimInstance -ClassName Win32_Process -Property ProcessId,ParentProcessId | ForEach-Object { "$($_.ProcessId):$($_.ParentProcessId)" })
189
+ $kills = @(Ids $parts[1])
190
+ foreach ($id in $kills) { if ($held.ContainsKey($id)) { try { $held[$id].Kill() } catch {} } }
191
+ foreach ($id in $kills) { if ($held.ContainsKey($id)) { try { [void]$held[$id].WaitForExit(250) } catch {} } }
192
+ $states = @()
193
+ foreach ($id in @($held.Keys)) {
194
+ $item = $held[$id]
195
+ $exit = ''; if ($item.HasExited) { $exit = Ticks $item.ExitTime }
196
+ $states += "$($id):$(Ticks $item.StartTime):$exit"
197
+ }
198
+ [Console]::Out.WriteLine("ok $(Field $rows) $(Field $states) $(Field $errors)")
199
+ } catch { [Console]::Out.WriteLine('error') }
200
+ [Console]::Out.Flush()
201
+ }
202
+ `;
203
+ const csv = (values) => values.length ? values.join(',') : '-';
204
+ const ticks = (text) => { if (!/^[1-9][0-9]{0,18}$/.test(text))
205
+ throw new Error('tree_reply'); return BigInt(text); };
206
+ export function parseTreeReply(line) {
207
+ const parts = line.split(' ');
208
+ if (parts.length !== 4 || parts[0] !== 'ok')
209
+ throw new Error('tree_reply');
210
+ const list = (text) => text === '-' ? [] : text.split(',');
211
+ const id = (text) => { if (!/^[0-9]{1,10}$/.test(text))
212
+ throw new Error('tree_reply'); return Number(text); };
213
+ const reply = { rows: new Map(), held: new Map(), errors: new Map() };
214
+ for (const row of list(parts[1])) {
215
+ const [pid, ppid, extra] = row.split(':');
216
+ if (extra !== undefined)
217
+ throw new Error('tree_reply');
218
+ reply.rows.set(id(pid), id(ppid ?? ''));
219
+ }
220
+ for (const row of list(parts[2])) {
221
+ const [pid, start, exit, extra] = row.split(':');
222
+ if (extra !== undefined || exit === undefined)
223
+ throw new Error('tree_reply');
224
+ reply.held.set(id(pid), { start: ticks(start), exit: exit === '' ? null : ticks(exit) });
225
+ }
226
+ for (const row of list(parts[3])) {
227
+ const [pid, error, extra] = row.split(':');
228
+ if (extra !== undefined || (error !== 'gone' && error !== 'denied'))
229
+ throw new Error('tree_reply');
230
+ reply.errors.set(id(pid), error);
231
+ }
232
+ return reply;
233
+ }
234
+ // One helper per cleanup, started only after a stop (so after any Ctrl-C that
235
+ // caused it); it exits on stdin EOF. Not detached: PowerShell started with
236
+ // DETACHED_PROCESS reads EOF from its piped stdin and exits at once (measured
237
+ // on Windows 10 x64 / PowerShell 5.1). A further Ctrl-C during cleanup can end
238
+ // the helper; that cleanup then reports unconfirmed.
239
+ export function windowsTreeHelper() {
240
+ const helper = childProcess.spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand',
241
+ Buffer.from(helperScript, 'utf16le').toString('base64')], { shell: false, windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
242
+ let buffer = '', waiting, failed = false;
243
+ const fail = () => { failed = true; waiting?.reject(new Error('tree_helper')); waiting = undefined; };
244
+ helper.once('error', fail);
245
+ helper.once('exit', fail);
246
+ helper.stdin.on('error', fail);
247
+ helper.stdout.setEncoding('utf8');
248
+ helper.stdout.on('data', (part) => {
249
+ buffer += part;
250
+ if (buffer.length > 4 * 1024 * 1024) {
251
+ fail();
252
+ helper.kill();
253
+ return;
254
+ }
255
+ const end = buffer.indexOf('\n');
256
+ if (end < 0)
257
+ return;
258
+ const line = buffer.slice(0, end).replace(/\r$/, '');
259
+ buffer = buffer.slice(end + 1);
260
+ const pending = waiting;
261
+ waiting = undefined;
262
+ try {
263
+ pending?.resolve(parseTreeReply(line));
264
+ }
265
+ catch {
266
+ pending?.reject(new Error('tree_reply'));
267
+ }
268
+ });
269
+ return {
270
+ pid: helper.pid,
271
+ request(hold, kill) {
272
+ return new Promise((resolve, reject) => {
273
+ if (failed || waiting) {
274
+ reject(new Error('tree_helper'));
275
+ return;
276
+ }
277
+ waiting = { resolve, reject };
278
+ helper.stdin.write(`${csv(hold)} ${csv(kill)}\n`);
279
+ });
280
+ },
281
+ close() { try {
282
+ helper.stdin.destroy();
283
+ helper.stdout.destroy();
284
+ helper.kill();
285
+ }
286
+ catch { /* Already gone. */ } },
287
+ };
288
+ }
289
+ // A provisional classifier, not an ownership proof. It compares creation/exit
290
+ // times read through held handles; those are UTC wall-clock instants, so the
291
+ // ordering is known to be unsound under a clock rollback, which is why no
292
+ // production path selects this backend. The root is identified first: Node
293
+ // holds its handle until Node observes its exit, so a hold that completes
294
+ // before that holds the root itself (the root is terminated only after this
295
+ // and after its listed children are held, or after ROOT_HOLD_GRACE_MS if the
296
+ // helper is slow). A descendant C is accepted when its parent P was accepted
297
+ // and P.start <= C.start <= P.exit by those UTC times, P being held and so
298
+ // stable. Only accepted candidates are killed; anything else is held but not
299
+ // killed. When the root's identity, a candidate's identity or a candidate's
300
+ // parent cannot be established (root exited first, vanished, denied, unlisted),
301
+ // nothing under it is killed and the result is unconfirmed.
302
+ // A descendant whose own parent exited and was released before cleanup began
303
+ // is not linked to the root at all; it is neither killed nor detectable here.
304
+ // close() asks the helper to exit; it does not await its termination.
305
+ export const ROOT_HOLD_GRACE_MS = 2000;
306
+ export async function reapWindowsTree(root, deadline, options = {}) {
307
+ const now = options.now ?? (() => performance.now()), self = options.self ?? process.pid;
308
+ let helper;
309
+ const grace = setTimeout(() => root.kill(), Math.max(0, Math.min(ROOT_HOLD_GRACE_MS, deadline() - now())));
310
+ try {
311
+ helper = (options.helper ?? windowsTreeHelper)();
312
+ }
313
+ catch {
314
+ clearTimeout(grace);
315
+ root.kill();
316
+ return 'unconfirmed';
317
+ }
318
+ const owned = new Map(), foreign = new Set(), unknown = new Set();
319
+ const listed = new Map();
320
+ // An already observed exit means the root PID may be reused: no evidence.
321
+ let hold = root.exited() ? [] : [root.pid], kill = [];
322
+ let doubtful = !hold.length, rootPending = hold.length > 0;
323
+ const parentOwns = (ppid, start) => {
324
+ const parent = owned.get(ppid);
325
+ return !!parent && start >= parent.start && (parent.exit === null || start <= parent.exit);
326
+ };
327
+ const aborted = new Promise(resolve => {
328
+ if (options.signal?.aborted)
329
+ resolve(undefined);
330
+ else
331
+ options.signal?.addEventListener('abort', () => resolve(undefined), { once: true });
332
+ });
333
+ try {
334
+ for (;;) {
335
+ const remaining = deadline() - now();
336
+ if (remaining <= 0 || options.signal?.aborted)
337
+ return 'unconfirmed';
338
+ // A reply can confirm only if its snapshot followed every kill and the
339
+ // root's observed exit (the helper snapshots before a request's kills).
340
+ const settledBefore = !kill.length && root.exited();
341
+ const abort = new AbortController();
342
+ const reply = await Promise.race([helper.request(hold, kill), aborted,
343
+ timers.setTimeout(remaining, undefined, { signal: abort.signal }).catch(() => undefined)]).finally(() => abort.abort());
344
+ if (!reply)
345
+ return 'unconfirmed';
346
+ for (const [pid, state] of reply.held) {
347
+ const node = owned.get(pid);
348
+ if (node)
349
+ node.exit = state.exit;
350
+ }
351
+ for (const pid of hold) {
352
+ const state = reply.held.get(pid);
353
+ if (rootPending && pid === root.pid) {
354
+ // Still unobserved by Node now, so it was the root when opened.
355
+ rootPending = false;
356
+ // An identified root is terminated through the held handle once the
357
+ // visible tree is held (Node's own kill would let a Node child's job
358
+ // end them first, unheld); the grace timer stays as the backstop.
359
+ // An unidentified root is killed now (through Node's handle).
360
+ if (state && !root.exited())
361
+ owned.set(pid, { ...state });
362
+ else {
363
+ doubtful = true;
364
+ unknown.add(pid);
365
+ clearTimeout(grace);
366
+ root.kill();
367
+ }
368
+ continue;
369
+ }
370
+ if (!state) {
371
+ doubtful = true;
372
+ unknown.add(pid);
373
+ continue;
374
+ }
375
+ // Only this snapshot, taken after the hold, describes the held process.
376
+ // An earlier row may belong to a previous holder of the PID, and no
377
+ // wall-clock stamp can show otherwise: an unlisted (already exited)
378
+ // candidate stays unclassified, and nothing under it is killed.
379
+ const ppid = reply.rows.get(pid);
380
+ if (ppid === undefined) {
381
+ doubtful = true;
382
+ unknown.add(pid);
383
+ }
384
+ else if (ppid !== pid && parentOwns(ppid, state.start))
385
+ owned.set(pid, { ...state });
386
+ else {
387
+ // A changed parent means the listed process was replaced before the
388
+ // hold; whatever it started is no longer visible: doubtful.
389
+ if (ppid !== listed.get(pid))
390
+ doubtful = true;
391
+ foreign.add(pid);
392
+ }
393
+ }
394
+ hold = [];
395
+ kill = [];
396
+ for (const [pid, node] of owned)
397
+ if (node.exit === null)
398
+ kill.push(pid);
399
+ // An unidentified root already made the result doubtful; its PID is in unknown.
400
+ for (const [pid, ppid] of reply.rows) {
401
+ if (unknown.has(ppid))
402
+ doubtful = true;
403
+ if (pid <= 4 || pid === ppid || pid === self || pid === helper.pid || owned.has(pid) || foreign.has(pid) || unknown.has(pid))
404
+ continue;
405
+ if (owned.has(ppid)) {
406
+ hold.push(pid);
407
+ listed.set(pid, ppid);
408
+ }
409
+ }
410
+ // Hold the whole visible tree before killing anything: a dying Node
411
+ // parent's job ends its children, and an unheld one would then vanish
412
+ // unattributed. A tree that keeps growing is bounded by the deadline
413
+ // (the root by ROOT_HOLD_GRACE_MS).
414
+ if (hold.length)
415
+ kill = [];
416
+ if (!hold.length && !kill.length) {
417
+ if (root.exited() && settledBefore)
418
+ return doubtful ? 'unconfirmed' : 'confirmed';
419
+ if (root.exited())
420
+ continue;
421
+ // The root was asked to terminate; give Node a moment to observe it.
422
+ await Promise.race([timers.setTimeout(Math.max(0, Math.min(25, deadline() - now()))), aborted]);
423
+ }
424
+ }
425
+ }
426
+ catch {
427
+ return 'unconfirmed';
428
+ }
429
+ finally {
430
+ clearTimeout(grace);
431
+ root.kill();
432
+ helper.close();
433
+ }
434
+ }
@@ -1,5 +1,5 @@
1
- export declare const VERSION = "0.4.0";
2
- export declare const VERSION_LINE = "session-peer 0.4.0 (typescript)";
1
+ export declare const VERSION = "0.5.0";
2
+ export declare const VERSION_LINE = "session-peer 0.5.0 (typescript)";
3
3
  export declare function host(value: string): string;
4
4
  export declare function reply(value: string): {
5
5
  to: string;
package/dist/protocol.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isIPv6 } from 'node:net';
2
2
  import { Refusal } from './discovery.js';
3
3
  import { uuid } from './writer.js';
4
- export const VERSION = '0.4.0';
4
+ export const VERSION = '0.5.0';
5
5
  export const VERSION_LINE = `session-peer ${VERSION} (typescript)`;
6
6
  // Return the OpenSSH destination: [user@]name, or an IPv6 literal with any
7
7
  // brackets removed (`ssh` does not strip `[...]` outside ssh:// URIs). Zone IDs
@@ -9,14 +9,15 @@ const verdict = (compatible) => ({ status: compatible ? 'compatible' : 'incompat
9
9
  code: compatible ? 'skill_contract_compatible' : 'skill_contract_mismatch', verification: 'metadata_only' });
10
10
  export const SKILL_METADATA_LIMIT = 65536;
11
11
  const keys = ['version', 'runtime-implementation', 'runtime-min-version', 'runtime-full-version', 'runtime-capability-policy'];
12
- // Preserve each published runtime/profile result. The 0.4.0 release candidate
13
- // preserves the three published profiles and adds one exact reviewed successor.
12
+ // Preserve each published runtime/profile result. The 0.5.0 release candidate
13
+ // carries forward only the four exact profiles accepted by public 0.4.0.
14
14
  // Metadata compatibility does not authenticate content or publish/install a skill.
15
15
  // Every later runtime/profile requires separate review; no version ranges.
16
16
  const matrix = {
17
17
  '0.3.2': ['0.1.0'], '0.3.3': ['0.1.0', '0.2.0'], '0.3.4': ['0.1.0', '0.2.0'],
18
18
  '0.3.5': ['0.1.0', '0.2.0', '0.2.1'], '0.3.6': ['0.1.0', '0.2.0', '0.2.1'],
19
- '0.4.0': ['0.1.0', '0.2.0', '0.2.1', '0.3.0']
19
+ '0.4.0': ['0.1.0', '0.2.0', '0.2.1', '0.3.0'],
20
+ '0.5.0': ['0.1.0', '0.2.0', '0.2.1', '0.3.0']
20
21
  };
21
22
  const profiles = {
22
23
  '0.1.0': ['0.1.0', 'typescript', '0.1.0', '0.1.0', 'probe-help'],
package/dist/ssh.d.ts CHANGED
@@ -15,7 +15,8 @@ export type SshJump = {
15
15
  };
16
16
  export declare function sshJump(value: string): SshJump;
17
17
  export declare function proxyCommand(ssh: string, jump: SshJump): string;
18
- export declare function jumpOptions(ssh: string, jump: SshJump): string[];
18
+ export declare function windowsProxyCommand(ssh: string, jump: SshJump, env?: NodeJS.ProcessEnv): string;
19
+ export declare function jumpOptions(ssh: string, jump: SshJump, platform?: NodeJS.Platform): string[];
19
20
  export declare function sshConfig(ssh: string, destination: string, options: SshOptions, force?: boolean): Promise<{
20
21
  user: SshUser;
21
22
  read: boolean;
package/dist/ssh.js CHANGED
@@ -81,11 +81,46 @@ export function proxyCommand(ssh, jump) {
81
81
  '-o', 'ClearAllForwardings=yes', '-o', 'PermitLocalCommand=no', ...(jump.port ? ['-p', jump.port] : []), '-l', jump.user,
82
82
  '-W', "'[%h]:%p'", '--', jump.host].join(' ');
83
83
  }
84
+ // Win32-OpenSSH has no shell step (PowerShell/openssh-portable source; the spawn
85
+ // path reads the same in the four inspected revisions v8.1.0.0, v9.5.0.0,
86
+ // v10.0.0.0 and latestw_all d0c65f2, which is source provenance, not a test of
87
+ // them): readconf.c keeps the raw value and, except in v8.1.0.0, argv_split()s
88
+ // it first and rejects unbalanced quotes; sshconnect.c
89
+ // percent-expands "exec %s", skips "exec " and posix_spawnp()s the whole string
90
+ // as argv[0] with no arguments; misc.c build_commandline_string() passes a string
91
+ // that starts with '"' unchanged to CreateProcessW(NULL, ...) (w32fd.c, which
92
+ // then also skips its unquoted-name retry). No cmd.exe runs, so %VAR%, ^, & and |
93
+ // are inert; the ssh.exe UCRT splits the line once more. Only an absolute drive
94
+ // path ending in \ssh.exe without '"', ':' or wildcard characters is accepted:
95
+ // it is the quoted program name (read up to the next '"', no escapes), and every
96
+ // other argument is a fixed or validated token without spaces, quotes or
97
+ // backslashes, so no MSVCRT escaping is needed. "[%h]:%p" is double-quoted where
98
+ // POSIX single-quotes it; %h from a configured HostName stays the same trusted
99
+ // ssh_config boundary. SSH_TEST_ENVIRONMENT makes Win32-OpenSSH rewrite the
100
+ // path (bash_to_win_path): upstream checks atoi(value). This builder refuses
101
+ // when Number.parseInt(value, 10) is truthy; that is not a general emulation of
102
+ // C atoi, and non-ASCII, locale and overflow behavior is unqualified.
103
+ // An isolated no-connection probe with the real Win32-OpenSSH 9.5p1 ssh.exe and
104
+ // an argv-dump hop matched this exactly (VALIDATION). Not enabled: a connected
105
+ // hop and owned-process-tree cleanup of the hop grandchild are unqualified (#20,
106
+ // #131; see cli.ts).
107
+ export function windowsProxyCommand(ssh, jump, env = process.env) {
108
+ if (ssh.length > 4096 || /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(ssh) ||
109
+ !/^[A-Za-z]:\\(?:[^\x00-\x1f\x7f"*:<>?|/\\]+\\)*ssh\.exe$/i.test(ssh))
110
+ throw new Refusal('ssh_jump_unsupported_ssh_path');
111
+ if (Number.parseInt(env.SSH_TEST_ENVIRONMENT ?? '', 10))
112
+ throw new Refusal('ssh_jump_unsupported_environment');
113
+ return [`"${ssh.replace(/%/g, '%%')}"`, '-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'UpdateHostKeys=no', '-o', 'ConnectTimeout=10',
114
+ '-o', 'ConnectionAttempts=1', '-o', 'ProxyCommand=none', '-o', 'ProxyJump=none', '-o', 'ControlPath=none', '-o', 'ForwardAgent=no',
115
+ '-o', 'ClearAllForwardings=yes', '-o', 'PermitLocalCommand=no', ...(jump.port ? ['-p', jump.port] : []), '-l', jump.user,
116
+ '-W', '"[%h]:%p"', '--', jump.host].join(' ');
117
+ }
84
118
  // Outer options for a jump: a configured ControlMaster/ControlPath could reuse
85
119
  // an existing master and bypass the hop, and ProxyUseFdpass would change how the
86
120
  // proxy hands over its connection, so all three are fixed before user options.
87
- export function jumpOptions(ssh, jump) {
88
- return ['-o', 'ControlMaster=no', '-o', 'ControlPath=none', '-o', 'ProxyUseFdpass=no', '-o', `ProxyCommand=${proxyCommand(ssh, jump)}`];
121
+ export function jumpOptions(ssh, jump, platform = process.platform) {
122
+ const command = platform === 'win32' ? windowsProxyCommand(ssh, jump) : proxyCommand(ssh, jump);
123
+ return ['-o', 'ControlMaster=no', '-o', 'ControlPath=none', '-o', 'ProxyUseFdpass=no', '-o', `ProxyCommand=${command}`];
89
124
  }
90
125
  // Like Python, ask OpenSSH which login user applies without connecting. With
91
126
  // `force`, `ssh -G` also runs for an explicit user so the caller can see a
package/dist/windows.d.ts CHANGED
@@ -9,3 +9,31 @@ export declare const START_PROBE_TIMEOUT_MS = 15000;
9
9
  export declare function inspectWindows(mode: 'identity' | 'openers', value: string): WindowsProcess[];
10
10
  export declare function windowsProcessStart(pid: number): bigint | undefined;
11
11
  export declare function postWindowsPipe(pipe: string, pid: number, text: string): Promise<void>;
12
+ export type WindowsAce = {
13
+ sid: string;
14
+ allow: boolean;
15
+ rights: number;
16
+ inherited: boolean;
17
+ inherits: boolean;
18
+ };
19
+ export type WindowsStorageEntry = {
20
+ path: string;
21
+ exists: boolean;
22
+ directory?: boolean;
23
+ reparse?: boolean;
24
+ owner?: string;
25
+ protected?: boolean;
26
+ nullDacl?: boolean;
27
+ rules?: WindowsAce[];
28
+ };
29
+ export type WindowsStorageReport = {
30
+ user: string;
31
+ tokenOwner: string;
32
+ entries: WindowsStorageEntry[];
33
+ };
34
+ export type WindowsStorageFailure = 'path_unsupported' | 'inspection_failed' | 'missing' | 'reparse_point' | 'not_directory' | 'not_file' | 'owner_mismatch' | 'acl_missing' | 'acl_inherited' | 'acl_broad';
35
+ export declare function windowsAncestors(path: string): string[] | undefined;
36
+ export declare function windowsStorageFailure(report: WindowsStorageReport, kind: 'directory' | 'file'): WindowsStorageFailure | undefined;
37
+ export declare function inspectWindowsStorage(path: string): WindowsStorageReport;
38
+ export declare function verifyWindowsPrivate(path: string, kind: 'directory' | 'file', inspect?: typeof inspectWindowsStorage): void;
39
+ export declare function createWindowsPrivateDirectory(path: string, inspect?: typeof inspectWindowsStorage): void;
package/dist/windows.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readdirSync, readFileSync, lstatSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { join, win32 } from 'node:path';
3
3
  import { createConnection } from 'node:net';
4
4
  import { spawnSync } from 'node:child_process';
5
5
  import { Refusal } from './discovery.js';
@@ -197,3 +197,151 @@ export async function postWindowsPipe(pipe, pid, text) {
197
197
  });
198
198
  });
199
199
  }
200
+ const storageScript = String.raw `
201
+ $ErrorActionPreference = 'Stop'
202
+ $sid = [Security.Principal.SecurityIdentifier]
203
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
204
+ $user = $identity.User.Value; $tokenOwner = $identity.Owner.Value
205
+ $entries = @()
206
+ foreach ($path in $paths) {
207
+ $item = Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue
208
+ if (!$item) { $entries += @{path=$path; exists=$false}; continue }
209
+ $entry = @{path=$path; exists=$true; directory=[bool]$item.PSIsContainer; reparse=[bool]($item.Attributes -band [IO.FileAttributes]::ReparsePoint)}
210
+ if (!$entry.reparse -and $path -eq $paths[-1]) {
211
+ $acl = $item.GetAccessControl([Security.AccessControl.AccessControlSections]'Owner, Access')
212
+ $entry.owner = $acl.GetOwner($sid).Value
213
+ $entry.protected = [bool]$acl.AreAccessRulesProtected
214
+ $entry.nullDacl = [bool]($acl.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access) -match 'D:NO_ACCESS_CONTROL')
215
+ $entry.rules = @($acl.GetAccessRules($true, $true, $sid) | ForEach-Object { @{sid=$_.IdentityReference.Value;
216
+ allow=($_.AccessControlType -eq 'Allow'); rights=[int64]$_.FileSystemRights; inherited=[bool]$_.IsInherited;
217
+ inherits=($_.InheritanceFlags -ne [Security.AccessControl.InheritanceFlags]::None)} })
218
+ }
219
+ $entries += $entry
220
+ }
221
+ [Console]::Out.Write((ConvertTo-Json -InputObject @{user=$user; tokenOwner=$tokenOwner; entries=@($entries)} -Compress -Depth 5))
222
+ `;
223
+ // Every component from the drive root to the leaf, for reparse checks. UNC,
224
+ // device (\\?\, \\.\) and relative paths are not private-storage candidates.
225
+ export function windowsAncestors(path) {
226
+ if (!/^[A-Za-z]:\\/.test(path) || /[\0\r\n]/.test(path) || path.split(/[\\/]/).some(part => part === '..' || part === '.'))
227
+ return undefined;
228
+ const parts = win32.normalize(path).replace(/\\+$/, '').split('\\');
229
+ return parts.map((_, index) => index ? parts.slice(0, index + 1).join('\\') : parts[0] + '\\');
230
+ }
231
+ const sidPattern = /^S-1-[0-9]+(?:-[0-9]+){1,14}$/;
232
+ function storageReport(value, paths) {
233
+ const report = value;
234
+ if (!report || typeof report !== 'object' || typeof report.user !== 'string' || !sidPattern.test(report.user) ||
235
+ typeof report.tokenOwner !== 'string' || !sidPattern.test(report.tokenOwner) ||
236
+ !Array.isArray(report.entries) || report.entries.length !== paths.length)
237
+ return undefined;
238
+ for (const [index, entry] of report.entries.entries()) {
239
+ if (!entry || entry.path !== paths[index] || typeof entry.exists !== 'boolean')
240
+ return undefined;
241
+ if (!entry.exists)
242
+ continue;
243
+ if (typeof entry.directory !== 'boolean' || typeof entry.reparse !== 'boolean')
244
+ return undefined;
245
+ if (entry.reparse || index !== paths.length - 1)
246
+ continue;
247
+ if (typeof entry.owner !== 'string' || !sidPattern.test(entry.owner) || typeof entry.protected !== 'boolean' ||
248
+ typeof entry.nullDacl !== 'boolean' || !Array.isArray(entry.rules) || entry.rules.length > 256 ||
249
+ entry.rules.some(rule => !rule || typeof rule.sid !== 'string' || !sidPattern.test(rule.sid) || typeof rule.allow !== 'boolean' ||
250
+ !Number.isSafeInteger(rule.rights) || typeof rule.inherited !== 'boolean' || typeof rule.inherits !== 'boolean'))
251
+ return undefined;
252
+ }
253
+ return report;
254
+ }
255
+ // The leaf must be owned by the current user SID or the token's default owner
256
+ // (an elevated administrator's new files are owned by Administrators; measured
257
+ // on Windows 10 x64). A group owner is a weaker boundary: every member of that
258
+ // group may rewrite the DACL, so this is not an owner-only guarantee for an
259
+ // elevated administrator, and the non-administrator cell is unverified. Every
260
+ // allow ACE, inherited
261
+ // or inheritable included, must name that SID; a directory's DACL must be
262
+ // protected from its parent. No component may be a reparse point (symlink,
263
+ // junction, mount point or other tag), checked by attribute, not lstat.
264
+ export function windowsStorageFailure(report, kind) {
265
+ const entries = report.entries, leaf = entries.at(-1);
266
+ if (!leaf)
267
+ return 'inspection_failed';
268
+ if (entries.some(entry => entry.exists && entry.reparse))
269
+ return 'reparse_point';
270
+ if (!leaf.exists || entries.some(entry => !entry.exists))
271
+ return 'missing';
272
+ if (kind === 'directory' ? !leaf.directory : leaf.directory)
273
+ return kind === 'directory' ? 'not_directory' : 'not_file';
274
+ if (leaf.owner !== report.user && leaf.owner !== report.tokenOwner)
275
+ return 'owner_mismatch';
276
+ if (leaf.nullDacl)
277
+ return 'acl_missing';
278
+ if (leaf.rules.some(rule => rule.allow && rule.sid !== report.user))
279
+ return 'acl_broad';
280
+ if (kind === 'directory' && (!leaf.protected || leaf.rules.some(rule => rule.inherited)))
281
+ return 'acl_inherited';
282
+ return undefined;
283
+ }
284
+ export function inspectWindowsStorage(path) {
285
+ if (process.platform !== 'win32')
286
+ throw new Refusal('windows_inspection_unavailable', 1);
287
+ const paths = windowsAncestors(path);
288
+ if (!paths)
289
+ throw new Refusal('handoff_storage_untrusted', 1);
290
+ const encoded = Buffer.from(JSON.stringify(paths), 'utf8').toString('base64');
291
+ // PowerShell 5.1 emits a JSON array as one object; cast, do not wrap in @().
292
+ const code = `$paths = [string[]](ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}'))))\ntry {\n${storageScript}\n} catch { exit 1 }`;
293
+ const done = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
294
+ '$script = [Console]::In.ReadToEnd(); Invoke-Expression $script'], { input: code, encoding: 'utf8', timeout: START_PROBE_TIMEOUT_MS, maxBuffer: 1024 * 1024, windowsHide: true });
295
+ if (done.status !== 0 || done.error)
296
+ throw new Refusal('windows_owner_inspection_failed', 1);
297
+ let report;
298
+ try {
299
+ report = storageReport(JSON.parse(done.stdout), paths);
300
+ }
301
+ catch { /* Rejected below. */ }
302
+ if (!report)
303
+ throw new Refusal('windows_owner_inspection_failed', 1);
304
+ return report;
305
+ }
306
+ // Fails closed with handoff_storage_untrusted; the specific failure is not
307
+ // surfaced because it would describe local ACL layout.
308
+ export function verifyWindowsPrivate(path, kind, inspect = inspectWindowsStorage) {
309
+ if (windowsStorageFailure(inspect(path), kind))
310
+ throw new Refusal('handoff_storage_untrusted', 1);
311
+ }
312
+ // Creates only a new leaf under an existing reparse-free parent, owned by the
313
+ // current user with a protected DACL granting that user alone, inherited by its
314
+ // contents; the whole chain is inspected again afterwards. Precheck, creation
315
+ // and postcheck are separate steps, not one atomic operation: someone able to
316
+ // write the parent can race them, and only the postcheck can reject the result.
317
+ export function createWindowsPrivateDirectory(path, inspect = inspectWindowsStorage) {
318
+ if (process.platform !== 'win32')
319
+ throw new Refusal('handoff_storage_unsupported', 1);
320
+ const paths = windowsAncestors(path);
321
+ if (!paths || paths.length < 2)
322
+ throw new Refusal('handoff_storage_untrusted', 1);
323
+ if (inspect(paths.at(-2)).entries.some(entry => !entry.exists || entry.reparse))
324
+ throw new Refusal('handoff_storage_untrusted', 1);
325
+ const encoded = Buffer.from(paths.at(-1), 'utf8').toString('base64');
326
+ const code = `
327
+ $ErrorActionPreference = 'Stop'
328
+ try {
329
+ $path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}'))
330
+ if (Test-Path -LiteralPath $path) { exit 3 }
331
+ if (!(Test-Path -LiteralPath ([IO.Path]::GetDirectoryName($path)) -PathType Container)) { exit 4 }
332
+ $user = [Security.Principal.WindowsIdentity]::GetCurrent().User
333
+ $security = New-Object Security.AccessControl.DirectorySecurity
334
+ $security.SetOwner($user)
335
+ $security.SetAccessRuleProtection($true, $false)
336
+ $security.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($user, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow')))
337
+ [void][IO.Directory]::CreateDirectory($path, $security)
338
+ } catch { exit 1 }
339
+ `;
340
+ const done = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
341
+ '$script = [Console]::In.ReadToEnd(); Invoke-Expression $script'], { input: code, encoding: 'utf8', timeout: START_PROBE_TIMEOUT_MS, maxBuffer: 65536, windowsHide: true });
342
+ if (done.status === 3)
343
+ throw new Refusal('handoff_ledger_exists', 1);
344
+ if (done.status !== 0 || done.error)
345
+ throw new Refusal('handoff_storage_untrusted', 1);
346
+ verifyWindowsPrivate(paths.at(-1), 'directory', inspect);
347
+ }
package/docs/api.md CHANGED
@@ -1,18 +1,18 @@
1
1
  # API reference
2
2
 
3
- This reference describes source/package version **0.4.0**. Check registry availability and review the selected release before installation. Dated release evidence is recorded in [VALIDATION.md](../VALIDATION.md); before publication use a reviewed source artifact.
3
+ This reference describes source/package version **0.5.0**. Check registry availability and review the selected release before installation. Dated release evidence is recorded in [VALIDATION.md](../VALIDATION.md); before publication use a reviewed source artifact.
4
4
 
5
5
  [Back to README](../README.md) · [User guide](guide.md)
6
6
 
7
7
  The package exposes a small ESM API with TypeScript declarations. Install it
8
- locally with `npm install --ignore-scripts session-peer@0.4.0` before importing it.
8
+ locally with `npm install --ignore-scripts session-peer@0.5.0` before importing it.
9
9
  Importing the package does not execute the CLI or submit a message.
10
10
 
11
11
  ```js
12
12
  import { VERSION, VERSION_LINE, reply, envelope } from 'session-peer';
13
13
 
14
- console.log(VERSION); // 0.4.0
15
- console.log(VERSION_LINE); // session-peer 0.4.0 (typescript)
14
+ console.log(VERSION); // 0.5.0
15
+ console.log(VERSION_LINE); // session-peer 0.5.0 (typescript)
16
16
  const address = 'session-peer://v1/reply?agent=claude&session=12345&transport=local';
17
17
  console.log(reply(address)); // { to: '12345' }
18
18
  console.log(envelope('Please review and reply.', true, address));
@@ -91,8 +91,8 @@ message/transcript scan manufactures ACK. Ordinary generated Reply-To stays v1.
91
91
 
92
92
  POSIX opt-in `send --host HOST` performs an exact-version preflight and a
93
93
  no-effect preparation before one destination-side send. Both ends must contain
94
- the same reviewed 0.4.0 implementation: a 0.3.x banner does not establish new
95
- capability. Initialize the destination's private ledger explicitly; no command
94
+ the same reviewed 0.5.0 implementation. This workflow was introduced in
95
+ 0.4.0; a 0.3.x banner does not establish the capability. Initialize the destination's private ledger explicitly; no command
96
96
  auto-installs a handler or initializes missing history. The origin does not
97
97
  create a local receipt collector. Reconcile with `handoff status`/`wait` on the
98
98
  destination that owns the retained intent, without another send.
@@ -192,6 +192,13 @@ false` even when the explicit wait fails. The separate handoff describes the
192
192
  requested evidence goal. After any possible RPC write, no legacy fallback or
193
193
  second submission occurs.
194
194
 
195
+ Selection is by the exact host platform/architecture and native version.
196
+ The 0.5.0 source records a Linux arm64 Codex 0.162.1 candidate (pinned musl
197
+ executable, procfs storage binding, `/proc/locks` writer-owner check) but does
198
+ not activate it. Linux and any other unlisted platform/version have no
199
+ profile, so required delivery refuses before effect and best-effort uses the
200
+ ordinary queue.
201
+
195
202
  Before an opted-in native effect, original saved thread/home/writer evidence,
196
203
  default SQLite storage, exact native version and a warm supported metadata
197
204
  schema are checked. Required unsupported observation refuses before effect.
@@ -266,6 +273,9 @@ a completed milestone. Exact evidence and limits are in [VALIDATION](../VALIDATI
266
273
 
267
274
  ## 0.4.0 implementation scope
268
275
 
276
+ The 0.5.0 source preserves this supported handoff scope; its Linux and Windows
277
+ groundwork does not enable additional platform or ACK support.
278
+
269
279
  The 0.4.0 implementation includes the qualified macOS arm64 observer and explicit
270
280
  `operator_confirmed` receipts on supported POSIX ledgers. Other platforms do not
271
281
  inherit that qualification. Linux observation [#130](https://github.com/abruption/session-peer-ts/issues/130),