session-peer 0.4.0 → 0.5.1

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.
@@ -0,0 +1,150 @@
1
+ // Linux procfs evidence for exact native profiles. These readers inspect only
2
+ // a supplied PID (an owned app-server child or the single lsof-reported lock
3
+ // owner) and the kernel lock table; they never scan /proc/<pid> inventories.
4
+ // All parsing is closed: an unrecognized row that names the inspected inode, a
5
+ // changed start time, a foreign UID or an unexpected executable refuses.
6
+ // Exact profile rows select this machinery (see native-profiles.ts); it is
7
+ // unit-tested with injected readers. Synchronous reads here run in the owned
8
+ // linux-native-probe worker under the caller's original deadline, or inside
9
+ // the already deadline-bounded writer-probe process.
10
+ import { readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs';
11
+ export const procfs = {
12
+ readFile: path => readFileSync(path, 'utf8'),
13
+ readdir: path => readdirSync(path),
14
+ readlink: path => readlinkSync(path),
15
+ stat: path => { const s = statSync(path, { bigint: true }); return { dev: s.dev, ino: s.ino }; },
16
+ };
17
+ export class ProcRefusal extends Error {
18
+ }
19
+ const refuse = () => { throw new ProcRefusal('procfs_evidence_unverified'); };
20
+ const gone = (error) => ['ENOENT', 'ESRCH'].includes(error.code ?? '');
21
+ const decimal = (value) => /^(?:0|[1-9]\d{0,18})$/.test(value ?? '') ? BigInt(value) : refuse();
22
+ // /proc/<pid>/stat: comm may contain spaces and ')' so split after the LAST ')'.
23
+ // Fields after comm start at field 3 (state); starttime is field 22.
24
+ export function parseProcStat(text) {
25
+ const end = text.lastIndexOf(')');
26
+ if (end < 0 || text[end + 1] !== ' ')
27
+ refuse();
28
+ const fields = text.slice(end + 2).replace(/\n$/, '').split(' ');
29
+ if (fields.length < 20 || !/^[A-Za-z]$/.test(fields[0]))
30
+ refuse();
31
+ return { state: fields[0], ppid: Number(decimal(fields[1])), pgrp: Number(decimal(fields[2])), starttime: decimal(fields[19]).toString() };
32
+ }
33
+ // Real, effective, saved and filesystem UIDs must all be the caller's UID.
34
+ export function parseProcStatusUid(text) {
35
+ const rows = text.split('\n').filter(line => line.startsWith('Uid:'));
36
+ const match = rows.length === 1 ? /^Uid:\t(\d+)\t(\d+)\t(\d+)\t(\d+)$/.exec(rows[0]) : null;
37
+ if (!match || new Set(match.slice(1)).size !== 1)
38
+ refuse();
39
+ return Number(decimal(match[1]));
40
+ }
41
+ // glibc gnu_dev_major/minor, matching libuv's makedev() for statx results.
42
+ export function devParts(dev) {
43
+ return { major: ((dev >> 8n) & 0xfffn) | ((dev >> 32n) & ~0xfffn), minor: (dev & 0xffn) | ((dev >> 12n) & ~0xffn) };
44
+ }
45
+ // fs/locks.c lock_get_status: "<id>: [-> ]<KIND> <MODE> <ACCESS> <pid> <maj>:<min>:<ino> <start> <end|EOF>".
46
+ // Rows for other inodes may use unknown kinds and are ignored only when they
47
+ // cannot name the inspected inode.
48
+ export function procLockHolders(text, target) {
49
+ const { major, minor } = devParts(target.dev), rows = [];
50
+ for (const line of text.split('\n')) {
51
+ if (!line)
52
+ continue;
53
+ const match = /^\d+: (?:\s*(->)\s+)?(\S+)\s+(\S+)\s+(\S+)\s+(-?\d+) ([0-9a-f]+):([0-9a-f]+):(\d+) \d+ (?:\d+|EOF)$/.exec(line);
54
+ if (!match) {
55
+ if (line.includes(':' + target.ino.toString() + ' '))
56
+ refuse();
57
+ continue;
58
+ }
59
+ const row = { blocked: match[1] === '->', kind: match[2], access: match[4], pid: Number(match[5]),
60
+ major: BigInt('0x' + match[6]), minor: BigInt('0x' + match[7]), ino: decimal(match[8]) };
61
+ if (row.ino === target.ino && row.major === major && row.minor === minor)
62
+ rows.push(row);
63
+ }
64
+ return rows;
65
+ }
66
+ // Exactly one granted exclusive flock(2) holder, as Rust std File::try_lock
67
+ // takes on Unix; POSIX/OFD/shared/lease rows or another holder are ambiguous.
68
+ export function procFlockOwner(path, reader = procfs) {
69
+ const target = reader.stat(path), rows = procLockHolders(reader.readFile('/proc/locks'), target);
70
+ const granted = rows.filter(row => !row.blocked);
71
+ if (rows.some(row => row.kind !== 'FLOCK') || granted.length !== 1 || granted[0].access !== 'WRITE' ||
72
+ !Number.isSafeInteger(granted[0].pid) || granted[0].pid <= 1)
73
+ refuse();
74
+ return granted[0].pid;
75
+ }
76
+ export function procOwner(pid, reader = procfs, executable = false) {
77
+ if (!Number.isSafeInteger(pid) || pid <= 1)
78
+ refuse();
79
+ try {
80
+ const stat = parseProcStat(reader.readFile(`/proc/${pid}/stat`)), uid = parseProcStatusUid(reader.readFile(`/proc/${pid}/status`));
81
+ if (['Z', 'X', 'x'].includes(stat.state))
82
+ refuse();
83
+ return { pid, ...stat, uid, ...(executable ? { exe: reader.stat(`/proc/${pid}/exe`) } : {}) };
84
+ }
85
+ catch (error) {
86
+ if (error instanceof ProcRefusal)
87
+ throw error;
88
+ return refuse();
89
+ }
90
+ }
91
+ export const sameOwner = (left, right) => left.pid === right.pid && left.ppid === right.ppid &&
92
+ left.pgrp === right.pgrp && left.starttime === right.starttime && left.uid === right.uid &&
93
+ left.exe?.dev === right.exe?.dev && left.exe?.ino === right.exe?.ino;
94
+ // Only regular absolute paths are retained; sockets, pipes and anon inodes are
95
+ // not storage. A descriptor closed during the walk is not opened state.
96
+ export function procOpenedFiles(pid, reader = procfs, limit = 4096) {
97
+ let entries;
98
+ try {
99
+ entries = reader.readdir(`/proc/${pid}/fd`);
100
+ }
101
+ catch {
102
+ return refuse();
103
+ }
104
+ if (entries.length > limit || entries.some(entry => !/^(?:0|[1-9]\d{0,9})$/.test(entry)))
105
+ refuse();
106
+ const files = [];
107
+ for (const fd of entries) {
108
+ let name, stat;
109
+ try {
110
+ name = reader.readlink(`/proc/${pid}/fd/${fd}`);
111
+ if (!name.startsWith('/'))
112
+ continue;
113
+ stat = reader.stat(`/proc/${pid}/fd/${fd}`);
114
+ }
115
+ catch (error) {
116
+ if (gone(error))
117
+ continue;
118
+ return refuse();
119
+ }
120
+ const deleted = name.endsWith(' (deleted)');
121
+ files.push({ name: deleted ? name.slice(0, -' (deleted)'.length) : name, dev: stat.dev, ino: stat.ino, deleted });
122
+ }
123
+ return files;
124
+ }
125
+ // Owned app-server binding: this process's direct child, its own detached
126
+ // group leader, same UID in all four slots, executing exactly the selected
127
+ // executable inode, unchanged (PID reuse/exec) across the descriptor walk.
128
+ export function procOwnedFiles(pid, parentPid, uid, executable, reader = procfs) {
129
+ const before = procOwner(pid, reader, true);
130
+ if (before.ppid !== parentPid || before.pgrp !== pid || before.uid !== uid ||
131
+ before.exe.dev !== executable.dev || before.exe.ino !== executable.ino)
132
+ refuse();
133
+ const files = procOpenedFiles(pid, reader);
134
+ if (!sameOwner(before, procOwner(pid, reader, true)))
135
+ refuse();
136
+ return files;
137
+ }
138
+ // Host-native 64-bit little-endian executable header: ELF on Linux, thin
139
+ // Mach-O on Darwin. The complete byte digest is the artifact identity.
140
+ const machines = { arm64: [183, 0x0100000c], x64: [62, 0x01000007] };
141
+ export function nativeExecutable(header, platform, arch) {
142
+ const machine = machines[arch];
143
+ if (!machine || header.length < 20)
144
+ return false;
145
+ if (platform === 'linux')
146
+ return header.readUInt32BE(0) === 0x7f454c46 && header[4] === 2 && header[5] === 1 &&
147
+ [2, 3].includes(header.readUInt16LE(16)) && header.readUInt16LE(18) === machine[0];
148
+ return platform === 'darwin' && header.readUInt32LE(0) === 0xfeedfacf && header.readUInt32LE(4) === machine[1] &&
149
+ header.readUInt32LE(12) === 2;
150
+ }
@@ -1,3 +1,4 @@
1
+ import { type NativeProfile } from './native-profiles.js';
1
2
  export declare const METADATA_SOURCE: Readonly<{
2
3
  version: "0.160.1";
3
4
  commit: "d27764b82f7118f674371e6d6e76271d9d606edb";
@@ -21,7 +22,7 @@ export type MetadataQualification = Readonly<{
21
22
  commit: string;
22
23
  platform: string;
23
24
  }>;
24
- export declare function metadataQualification(version: string): MetadataQualification | undefined;
25
+ export declare function metadataQualification(version: string, platform?: string): MetadataQualification | undefined;
25
26
  export type MetadataBudget = {
26
27
  observationRemainingMs(): number;
27
28
  };
@@ -39,7 +40,7 @@ export type MetadataObservation = MetadataCapability & {
39
40
  status: 'running' | 'completed' | 'failed' | 'interrupted' | 'unknown';
40
41
  };
41
42
  };
42
- export declare function metadataCapability(scope: MetadataScope, version: string, budget: MetadataBudget | undefined, verifyOwner: VerifyMetadataOwner): Promise<MetadataCapability>;
43
+ export declare function metadataCapability(scope: MetadataScope, version: string, budget: MetadataBudget | undefined, verifyOwner: VerifyMetadataOwner, profiles?: readonly NativeProfile[]): Promise<MetadataCapability>;
43
44
  export declare function observeMetadata(scope: MetadataScope & {
44
45
  clientUserMessageId: string;
45
46
  }, budget: MetadataBudget, verifyOwner: VerifyMetadataOwner): Promise<MetadataObservation>;
@@ -3,6 +3,7 @@
3
3
  import childProcess from 'node:child_process';
4
4
  import { isAbsolute, join, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { NATIVE_PROFILES, validateNativeProfiles } from './native-profiles.js';
6
7
  export const METADATA_SOURCE = Object.freeze({ version: '0.160.1',
7
8
  commit: 'd27764b82f7118f674371e6d6e76271d9d606edb',
8
9
  database: 'thread_history_1.sqlite', recentUsers: 256, maxCellBytes: 256 * 1024, childMs: 1000 });
@@ -14,15 +15,18 @@ export const METADATA_RESUME_QUALIFICATION = Object.freeze({ version: METADATA_S
14
15
  commit: METADATA_SOURCE.commit, platform: 'darwin-arm64' });
15
16
  // Exact native qualification is separate from POSIX structural-store fixtures.
16
17
  // No version range, current PATH inference or schema-only upgrade is permitted.
17
- const metadataQualifications = Object.freeze([
18
- METADATA_RESUME_QUALIFICATION,
19
- Object.freeze({ version: '0.162.1', commit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d', platform: 'darwin-arm64' }),
20
- ]);
21
- export function metadataQualification(version) {
22
- if (typeof version !== 'string')
18
+ // Rows are projected from the exact platform-aware native profile table.
19
+ const metadataQualifications = Object.freeze(NATIVE_PROFILES.map(row => row.platform === METADATA_RESUME_QUALIFICATION.platform && row.version === METADATA_RESUME_QUALIFICATION.version &&
20
+ row.commit === METADATA_RESUME_QUALIFICATION.commit ? METADATA_RESUME_QUALIFICATION :
21
+ Object.freeze({ version: row.version, commit: row.commit, platform: row.platform })));
22
+ // With a platform, selection is the exact (platform, version) row. Without one
23
+ // (structural store checks only) a version must name exactly one platform's row.
24
+ export function metadataQualification(version, platform) {
25
+ if (typeof version !== 'string' || (platform !== undefined && typeof platform !== 'string'))
23
26
  return undefined;
24
27
  const exact = version.startsWith('codex-cli ') ? version.slice('codex-cli '.length) : version;
25
- return metadataQualifications.find(profile => profile.version === exact);
28
+ const rows = metadataQualifications.filter(profile => profile.version === exact && (platform === undefined || profile.platform === platform));
29
+ return rows.length === 1 ? rows[0] : undefined;
26
30
  }
27
31
  const reasons = ['metadata_version_unsupported', 'metadata_platform_unsupported',
28
32
  'metadata_scope_invalid', 'metadata_storage_untrusted', 'metadata_history_unavailable', 'metadata_schema_unsupported',
@@ -200,8 +204,12 @@ async function inspect(scope, mode, budget, verify, clientUserMessageId) {
200
204
  const { storageStamp: _privateStamp, ...publicResult } = result;
201
205
  return publicResult;
202
206
  }
203
- export async function metadataCapability(scope, version, budget, verifyOwner) {
204
- if (!metadataQualification(version))
207
+ // `profiles` is a hermetic test hook (validated synthetic tables only).
208
+ export async function metadataCapability(scope, version, budget, verifyOwner, profiles = NATIVE_PROFILES) {
209
+ // Structural store check: any exact row's version. Platform selection is the
210
+ // caller's exact metadataQualification(version, platform), never inferred here.
211
+ const exact = typeof version === 'string' && version.startsWith('codex-cli ') ? version.slice('codex-cli '.length) : version;
212
+ if (!validateNativeProfiles(profiles).some(row => row.version === exact))
205
213
  return { supported: false, reason: 'metadata_version_unsupported' };
206
214
  const result = await inspect(scope, 'capability', budget, verifyOwner);
207
215
  return { supported: result.supported, ...(result.reason === undefined ? {} : { reason: result.reason }) };
@@ -219,15 +227,18 @@ export function resumeMetadataObservation(scope, qualification, budget, verifyOw
219
227
  Object.keys(qualification).some(key => !['version', 'commit', 'platform'].includes(key))) {
220
228
  return Promise.resolve(unsupported('metadata_scope_invalid'));
221
229
  }
222
- const expected = metadataQualification(qualification.version);
223
- // Retained records use the canonical native version, not a CLI banner.
224
- if (!expected || qualification.version !== expected.version) {
230
+ // Retained records use the canonical native version, not a CLI banner. The
231
+ // exact retained (version, commit, platform) row is required; a same-version
232
+ // row for another platform is not inherited.
233
+ const versions = metadataQualifications.filter(row => row.version === qualification.version);
234
+ if (!versions.length) {
225
235
  return Promise.resolve(unsupported('metadata_version_unsupported'));
226
236
  }
227
- if (qualification.commit !== expected.commit) {
237
+ const commits = versions.filter(row => row.commit === qualification.commit);
238
+ if (!commits.length) {
228
239
  return Promise.resolve(unsupported('metadata_schema_unsupported'));
229
240
  }
230
- if (qualification.platform !== expected.platform ||
241
+ if (!commits.some(row => row.platform === qualification.platform) ||
231
242
  qualification.platform !== `${process.platform}-${process.arch}`) {
232
243
  return Promise.resolve(unsupported('metadata_platform_unsupported'));
233
244
  }
@@ -0,0 +1,25 @@
1
+ export type NativeProfile = Readonly<{
2
+ platform: string;
3
+ version: string;
4
+ commit: string;
5
+ platformOs: 'macos' | 'linux';
6
+ storageBinding: 'darwin_lsof' | 'linux_procfs';
7
+ ownerInspection: 'lsof_ps' | 'lsof_ps_procfs_locks';
8
+ sshDestination: boolean;
9
+ artifact: Readonly<{
10
+ target: string;
11
+ sha256: string;
12
+ }> | null;
13
+ }>;
14
+ export type NativeProfileQuery = Readonly<{
15
+ platform: string;
16
+ version: string;
17
+ }>;
18
+ export type NativeProfileRefusal = 'version_unsupported' | 'platform_unsupported';
19
+ export declare function validateNativeProfiles(table: readonly NativeProfile[]): readonly NativeProfile[];
20
+ export declare const NATIVE_PROFILES: readonly NativeProfile[];
21
+ export declare const CANDIDATE_PROFILES: readonly NativeProfile[];
22
+ export declare const currentPlatform: () => string;
23
+ export declare function selectNativeProfile(query: NativeProfileQuery, table?: readonly NativeProfile[]): NativeProfile | undefined;
24
+ export declare function nativeProfileRefusal(query: NativeProfileQuery, table?: readonly NativeProfile[]): NativeProfileRefusal | undefined;
25
+ export declare const platformProfiled: (platform: string, table?: readonly NativeProfile[]) => boolean;
@@ -0,0 +1,62 @@
1
+ const kinds = {
2
+ darwin: { platformOs: 'macos', storageBinding: 'darwin_lsof', ownerInspection: 'lsof_ps', targets: { arm64: 'aarch64-apple-darwin' } },
3
+ linux: { platformOs: 'linux', storageBinding: 'linux_procfs', ownerInspection: 'lsof_ps_procfs_locks',
4
+ targets: { arm64: 'aarch64-unknown-linux-musl', x64: 'x86_64-unknown-linux-musl' } },
5
+ };
6
+ const historical = new Set(['darwin-arm64/0.160.1', 'darwin-arm64/0.162.1']);
7
+ // Validates the whole table, including test-supplied synthetic tables, so a
8
+ // malformed or ambiguous row cannot be selected by a looser comparison.
9
+ export function validateNativeProfiles(table) {
10
+ const keys = new Set();
11
+ for (const row of table) {
12
+ if (!row || typeof row !== 'object' || Object.keys(row).sort().join() !==
13
+ 'artifact,commit,ownerInspection,platform,platformOs,sshDestination,storageBinding,version')
14
+ throw new Error('invalid native profile');
15
+ const [os, arch, extra] = row.platform.split('-'), kind = kinds[os];
16
+ const target = kind?.targets[arch];
17
+ if (!kind || !target || extra !== undefined || !/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(row.version) ||
18
+ !/^[0-9a-f]{40}$/.test(row.commit) || row.platformOs !== kind.platformOs || row.storageBinding !== kind.storageBinding ||
19
+ row.ownerInspection !== kind.ownerInspection || typeof row.sshDestination !== 'boolean' ||
20
+ (os === 'linux' && row.sshDestination))
21
+ throw new Error('invalid native profile');
22
+ const key = row.platform + '/' + row.version;
23
+ if (keys.has(key))
24
+ throw new Error('ambiguous native profile');
25
+ keys.add(key);
26
+ if (row.artifact === null ? !historical.has(key) : Object.keys(row.artifact).sort().join() !== 'sha256,target' ||
27
+ row.artifact.target !== target || !/^[0-9a-f]{64}$/.test(row.artifact.sha256))
28
+ throw new Error('invalid native artifact');
29
+ }
30
+ return Object.freeze(table.map(row => Object.freeze({ ...row, artifact: row.artifact && Object.freeze({ ...row.artifact }) })));
31
+ }
32
+ export const NATIVE_PROFILES = validateNativeProfiles([
33
+ { platform: 'darwin-arm64', version: '0.160.1', commit: 'd27764b82f7118f674371e6d6e76271d9d606edb',
34
+ platformOs: 'macos', storageBinding: 'darwin_lsof', ownerInspection: 'lsof_ps', sshDestination: true, artifact: null },
35
+ { platform: 'darwin-arm64', version: '0.162.1', commit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d',
36
+ platformOs: 'macos', storageBinding: 'darwin_lsof', ownerInspection: 'lsof_ps', sshDestination: true, artifact: null },
37
+ ]);
38
+ // Recorded but NOT selectable. Linux arm64 test host, 2026-10-20: upstream
39
+ // rust-v0.162.1 musl artifact digest, Linux-generated schema/opt-out evidence
40
+ // and one dedicated-thread client-ID injection (linux-observation-native-
41
+ // evidence.json). Activation is withheld until the original TUI writer's
42
+ // executable is bound to this artifact and the writer's kernel identity is
43
+ // retained across send and independent wait (PARITY.md follow-up design).
44
+ export const CANDIDATE_PROFILES = validateNativeProfiles([
45
+ { platform: 'linux-arm64', version: '0.162.1', commit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d',
46
+ platformOs: 'linux', storageBinding: 'linux_procfs', ownerInspection: 'lsof_ps_procfs_locks', sshDestination: false,
47
+ artifact: { target: 'aarch64-unknown-linux-musl', sha256: '071cbe8d821cf1b02b6d8ba6c8b7991b228fcb8519dcb68a37d31222bb8cabe5' } },
48
+ ]);
49
+ export const currentPlatform = () => `${process.platform}-${process.arch}`;
50
+ export function selectNativeProfile(query, table = NATIVE_PROFILES) {
51
+ if (!query || typeof query.platform !== 'string' || typeof query.version !== 'string')
52
+ return undefined;
53
+ return table.find(row => row.platform === query.platform && row.version === query.version);
54
+ }
55
+ // Version absence is reported before platform absence; neither is downgraded
56
+ // to a nearby row. An exact version on another platform is still unsupported.
57
+ export function nativeProfileRefusal(query, table = NATIVE_PROFILES) {
58
+ if (selectNativeProfile(query, table))
59
+ return undefined;
60
+ return table.some(row => row.version === query?.version) ? 'platform_unsupported' : 'version_unsupported';
61
+ }
62
+ export const platformProfiled = (platform, table = NATIVE_PROFILES) => table.some(row => row.platform === platform);
package/dist/process.d.ts CHANGED
@@ -19,3 +19,31 @@ export declare function run(binary: string, args: string[], options?: {
19
19
  limit?: number;
20
20
  rawStdout?: boolean;
21
21
  }): Promise<Done>;
22
+ export type TreeCleanup = 'confirmed' | 'unconfirmed';
23
+ export type TreeReply = {
24
+ rows: Map<number, number>;
25
+ held: Map<number, {
26
+ start: bigint;
27
+ exit: bigint | null;
28
+ }>;
29
+ errors: Map<number, 'gone' | 'denied'>;
30
+ };
31
+ export type TreeHelper = {
32
+ pid?: number;
33
+ request(hold: number[], kill: number[]): Promise<TreeReply>;
34
+ close(): void;
35
+ };
36
+ export type TreeRoot = {
37
+ pid: number;
38
+ exited: () => boolean;
39
+ kill: () => void;
40
+ };
41
+ export declare function parseTreeReply(line: string): TreeReply;
42
+ export declare function windowsTreeHelper(): TreeHelper;
43
+ export declare const ROOT_HOLD_GRACE_MS = 2000;
44
+ export declare function reapWindowsTree(root: TreeRoot, deadline: () => number, options?: {
45
+ helper?: () => TreeHelper;
46
+ now?: () => number;
47
+ self?: number;
48
+ signal?: AbortSignal;
49
+ }): Promise<TreeCleanup>;