session-peer 0.2.0 → 0.3.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/send.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { casefold } from './casefold.js';
2
2
  import { createConnection } from 'node:net';
3
- import { claude, Refusal } from './discovery.js';
3
+ import { claude, Refusal, sqliteHome } from './discovery.js';
4
4
  import { executable, run, UnknownOutcome } from './process.js';
5
5
  import { HomeRefusal, resolveWriter, revalidateWriter, uuid } from './writer.js';
6
6
  import { postWindowsPipe } from './windows.js';
@@ -62,12 +62,19 @@ export async function send(options) {
62
62
  const binary = executable(options.codexBin ?? 'codex');
63
63
  const selection = await resolveWriter(options.home, id, options.allowInactive);
64
64
  const { home } = selection;
65
+ const storage = sqliteHome(home);
66
+ if (storage !== 'default')
67
+ throw new HomeRefusal(storage === 'configured' ? 'unsupported_codex_sqlite_home' : 'codex_config_unreadable', selection.resolution);
65
68
  const result = { ...base, target: { agent: 'codex', id }, codexHome: home,
66
69
  status: options.dryRun ? 'validated' : 'queued', codexHomeResolution: selection.resolution };
67
70
  if (options.dryRun)
68
71
  return result;
69
72
  await revalidateWriter(selection, options.home, id, options.allowInactive);
70
- const done = await run(binary, ['queue', '--thread', id, '--message', options.message], { env: { ...process.env, CODEX_HOME: home }, timeout: 30000 });
73
+ // `--message=` keeps a body starting with `-` from being parsed as an option.
74
+ // An inherited CODEX_SQLITE_HOME would queue outside the validated home.
75
+ // Windows environment names are case-insensitive.
76
+ const inherited = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase() !== 'CODEX_SQLITE_HOME'));
77
+ const done = await run(binary, ['queue', '--thread', id, `--message=${options.message}`], { env: { ...inherited, CODEX_HOME: home }, timeout: 30000 });
71
78
  if (!done.spawned)
72
79
  throw new HomeRefusal('native_spawn_failed', selection.resolution);
73
80
  if (done.interrupted || done.code !== 0)
package/dist/ssh.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ export type SshOptions = {
2
+ args: string[];
3
+ user?: string;
4
+ };
5
+ export type SshUser = {
6
+ sshUser: string | null;
7
+ sshUserSource: 'explicit' | 'ssh_config_or_local_default' | 'unknown';
8
+ };
9
+ export declare function sshOptions(tokens: string[]): SshOptions;
10
+ export type SshJump = {
11
+ user: string;
12
+ host: string;
13
+ port?: string;
14
+ spec: string;
15
+ };
16
+ export declare function sshJump(value: string): SshJump;
17
+ export declare function proxyCommand(ssh: string, jump: SshJump): string;
18
+ export declare function jumpOptions(ssh: string, jump: SshJump): string[];
19
+ export declare function sshConfig(ssh: string, destination: string, options: SshOptions, force?: boolean): Promise<{
20
+ user: SshUser;
21
+ read: boolean;
22
+ hostKeyAlias?: string;
23
+ }>;
24
+ export declare function sshUser(ssh: string, destination: string, options: SshOptions): Promise<SshUser>;
package/dist/ssh.js ADDED
@@ -0,0 +1,114 @@
1
+ import { isIPv6 } from 'node:net';
2
+ import { Refusal } from './discovery.js';
3
+ import { run } from './process.js';
4
+ // An allowlist, not a blocklist: OpenSSH has many spellings that run local
5
+ // commands (ProxyCommand, LocalCommand, KnownHostsCommand, Match exec, Include,
6
+ // -F, PKCS11Provider...). Only these connection settings are accepted, and they
7
+ // are re-emitted in one canonical argv form. ProxyJump is excluded because the
8
+ // jump hop does not inherit BatchMode/StrictHostKeyChecking from the command line.
9
+ const FLAGS = { p: 'port', l: 'user', i: 'identityfile' };
10
+ const KEYS = ['port', 'user', 'identityfile', 'identitiesonly'];
11
+ const valid = {
12
+ port: value => /^[1-9]\d{0,4}$/.test(value) && Number(value) <= 65535,
13
+ user: value => value.length <= 255 && /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(value),
14
+ // OpenSSH expands %tokens and ${ENV} in identity paths; refuse both.
15
+ identityfile: value => value.length <= 4096 && !value.startsWith('-') && !/[\x00-\x1f\x7f%$]/.test(value),
16
+ identitiesonly: value => value === 'yes' || value === 'no',
17
+ family: () => true
18
+ };
19
+ export function sshOptions(tokens) {
20
+ const seen = new Map();
21
+ for (let i = 0; i < tokens.length; i++) {
22
+ const token = tokens[i];
23
+ let key, value;
24
+ if (token === '-4' || token === '-6') {
25
+ key = 'family';
26
+ value = token;
27
+ }
28
+ else {
29
+ const match = /^-([plio])(.*)$/s.exec(token);
30
+ if (!match)
31
+ throw new Refusal('unsupported_ssh_option');
32
+ value = match[2] || tokens[++i];
33
+ if (value === undefined || value.startsWith('-'))
34
+ throw new Refusal('invalid_ssh_option');
35
+ if (match[1] === 'o') {
36
+ // Only Key=Value; OpenSSH would re-tokenize spaces and quotes in -o.
37
+ const pair = /^([A-Za-z]+)=(.*)$/s.exec(value);
38
+ if (!pair || !KEYS.includes(pair[1].toLowerCase()))
39
+ throw new Refusal('unsupported_ssh_option');
40
+ key = pair[1].toLowerCase();
41
+ value = pair[2];
42
+ }
43
+ else
44
+ key = FLAGS[match[1]];
45
+ }
46
+ if (seen.has(key) || !valid[key](value))
47
+ throw new Refusal('invalid_ssh_option');
48
+ seen.set(key, value);
49
+ }
50
+ const args = [];
51
+ if (seen.has('port'))
52
+ args.push('-p', seen.get('port'));
53
+ if (seen.has('user'))
54
+ args.push('-l', seen.get('user'));
55
+ if (seen.has('identityfile'))
56
+ args.push('-i', seen.get('identityfile'));
57
+ if (seen.has('identitiesonly'))
58
+ args.push('-o', `IdentitiesOnly=${seen.get('identitiesonly')}`);
59
+ if (seen.has('family'))
60
+ args.push(seen.get('family'));
61
+ return { args, ...(seen.has('user') ? { user: seen.get('user') } : {}) };
62
+ }
63
+ // --ssh-jump USER@HOST[:PORT]: one hop with an explicit user. IPv6 needs
64
+ // brackets. Every part is limited to characters that are inert in a POSIX
65
+ // shell and in OpenSSH % tokens, because the hop runs inside ProxyCommand.
66
+ export function sshJump(value) {
67
+ const match = value.length <= 255 ? /^([A-Za-z0-9_][A-Za-z0-9_.-]*)@(?:\[([0-9A-Fa-f:.]+)\]|([A-Za-z0-9][A-Za-z0-9_.-]*))(?::([1-9]\d{0,4}))?$/.exec(value) : null;
68
+ if (!match || (match[2] !== undefined && !isIPv6(match[2])) || (match[4] !== undefined && Number(match[4]) > 65535))
69
+ throw new Refusal('invalid_ssh_jump');
70
+ return { user: match[1], host: match[2] ?? match[3], ...(match[4] ? { port: match[4] } : {}), spec: value };
71
+ }
72
+ // A fixed ProxyCommand instead of -J: OpenSSH's -J does not pass BatchMode or
73
+ // StrictHostKeyChecking to the hop. The hop's own ssh_config may not add a
74
+ // further proxy, control socket, forwarding or local command. OpenSSH runs
75
+ // ProxyCommand through the user's shell after %-token expansion (ssh_config(5)),
76
+ // so the executable path is shell-quoted and every % in it is doubled.
77
+ export function proxyCommand(ssh, jump) {
78
+ const path = `'${ssh.replace(/'/g, "'\\''")}'`.replace(/%/g, '%%');
79
+ return [path, '-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'UpdateHostKeys=no', '-o', 'ConnectTimeout=10',
80
+ '-o', 'ConnectionAttempts=1', '-o', 'ProxyCommand=none', '-o', 'ProxyJump=none', '-o', 'ControlPath=none', '-o', 'ForwardAgent=no',
81
+ '-o', 'ClearAllForwardings=yes', '-o', 'PermitLocalCommand=no', ...(jump.port ? ['-p', jump.port] : []), '-l', jump.user,
82
+ '-W', "'[%h]:%p'", '--', jump.host].join(' ');
83
+ }
84
+ // Outer options for a jump: a configured ControlMaster/ControlPath could reuse
85
+ // an existing master and bypass the hop, and ProxyUseFdpass would change how the
86
+ // 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)}`];
89
+ }
90
+ // Like Python, ask OpenSSH which login user applies without connecting. With
91
+ // `force`, `ssh -G` also runs for an explicit user so the caller can see a
92
+ // configured HostKeyAlias (`read` says whether the configuration was read).
93
+ export async function sshConfig(ssh, destination, options, force = false) {
94
+ const at = destination.lastIndexOf('@');
95
+ const explicit = at > 0 ? { sshUser: destination.slice(0, at), sshUserSource: 'explicit' } :
96
+ options.user ? { sshUser: options.user, sshUserSource: 'explicit' } : undefined;
97
+ if (explicit && !force)
98
+ return { user: explicit, read: false };
99
+ const done = await run(ssh, ['-G', ...options.args, '--', destination], { timeout: 5000 });
100
+ let user = explicit ?? { sshUser: null, sshUserSource: 'unknown' }, hostKeyAlias;
101
+ if (done.interrupted || done.code !== 0)
102
+ return { user, read: false };
103
+ for (const line of done.stdout.split(/\r?\n/)) {
104
+ const match = /^(user|hostkeyalias) (\S[^\x00-\x1f\x7f]{0,254})$/i.exec(line);
105
+ if (match?.[1].toLowerCase() === 'hostkeyalias')
106
+ hostKeyAlias = match[2].trim();
107
+ else if (match && !explicit)
108
+ user = { sshUser: match[2].trim(), sshUserSource: 'ssh_config_or_local_default' };
109
+ }
110
+ return { user, read: true, ...(hostKeyAlias ? { hostKeyAlias } : {}) };
111
+ }
112
+ export async function sshUser(ssh, destination, options) {
113
+ return (await sshConfig(ssh, destination, options)).user;
114
+ }
@@ -0,0 +1,37 @@
1
+ import { Refusal } from './discovery.js';
2
+ export declare const PACKAGE = "session-peer";
3
+ export declare const REFRESH_ARG = "--_refresh-update-cache";
4
+ export declare const CHANNELS: string[];
5
+ export declare class UpdateRefusal extends Refusal {
6
+ readonly guidance: Record<string, unknown>;
7
+ constructor(code: string, guidance: Record<string, unknown>);
8
+ }
9
+ export declare const validVersion: (text: unknown, stable?: boolean) => boolean;
10
+ export declare function compareVersions(a: string, b: string): number;
11
+ export type Manager = 'npm' | 'npm_project' | 'pnpm' | 'pnpm_project' | 'yarn' | 'bun' | 'volta' | 'npx' | 'source' | 'unknown';
12
+ export type Probe = {
13
+ read: (path: string) => string;
14
+ real: (path: string) => string;
15
+ };
16
+ export declare function manager(path?: string, platform?: NodeJS.Platform, probe?: Probe): Manager;
17
+ export declare const upgradeCommand: (owner: Manager, target: string) => string | null;
18
+ export declare const upgradeGuidance: (owner: Manager) => string;
19
+ export declare function registryUrl(env?: NodeJS.ProcessEnv): URL;
20
+ export declare function distTags(env?: NodeJS.ProcessEnv): Promise<Record<string, unknown>>;
21
+ export declare function cacheDirectory(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
22
+ type CacheState = {
23
+ status: 'missing' | 'invalid' | 'fresh' | 'expired';
24
+ latest?: string | null;
25
+ checkedAt?: number;
26
+ };
27
+ export declare function readCache(env?: NodeJS.ProcessEnv, now?: number): CacheState;
28
+ export declare function acquireLock(env?: NodeJS.ProcessEnv): string | undefined;
29
+ export declare function lockState(env?: NodeJS.ProcessEnv, now?: number): 'free' | 'held' | 'stale';
30
+ export declare function releaseLock(token: string | undefined, env?: NodeJS.ProcessEnv): boolean;
31
+ export declare function refreshCache(env?: NodeJS.ProcessEnv): Promise<void>;
32
+ export declare const noticesEnabled: (optOut: boolean, env?: NodeJS.ProcessEnv) => boolean;
33
+ export declare function updateNotice(optOut: boolean, env?: NodeJS.ProcessEnv, now?: number): Record<string, unknown> | undefined;
34
+ export declare const noticeText: (notice: Record<string, unknown>) => string;
35
+ export declare function checkUpdate(channel?: string, env?: NodeJS.ProcessEnv): Promise<Record<string, unknown>>;
36
+ export declare function refuseSelfUpdate(channel?: string): never;
37
+ export {};
@@ -0,0 +1,444 @@
1
+ // Update checks read only public npm dist-tags. They never install packages,
2
+ // replace npm-owned files, or touch Python installs, remote hosts or skills.
3
+ import { spawn } from 'node:child_process';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { chmodSync, closeSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { isAbsolute, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { inspectSkills } from './diagnostics.js';
10
+ import { Refusal } from './discovery.js';
11
+ import { VERSION } from './protocol.js';
12
+ export const PACKAGE = 'session-peer';
13
+ export const REFRESH_ARG = '--_refresh-update-cache';
14
+ const LOCK_TOKEN = 'SESSION_PEER_UPDATE_LOCK_TOKEN';
15
+ export const CHANNELS = ['latest', 'preview'];
16
+ const TIMEOUT = 3000, RESPONSE_LIMIT = 65536, CACHE_LIMIT = 4096;
17
+ const TTL = 24 * 3600_000, FAILURE_TTL = 3600_000, LOCK_STALE = 60_000;
18
+ // Distinct from Python's update.json: npm and Python versions are separate streams.
19
+ const CACHE = 'npm-update.json', LOCK = 'npm-update.lock';
20
+ export class UpdateRefusal extends Refusal {
21
+ guidance;
22
+ constructor(code, guidance) {
23
+ super(code);
24
+ this.guidance = guidance;
25
+ }
26
+ }
27
+ const IDENTIFIER = '(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)';
28
+ const SEMVER = new RegExp(`^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-(${IDENTIFIER}(?:\\.${IDENTIFIER})*))?$`);
29
+ // npm versions without build metadata; no `v` prefix, partial or Python-style tags.
30
+ function parseVersion(text) {
31
+ if (typeof text !== 'string' || text.length > 64)
32
+ return undefined;
33
+ const match = SEMVER.exec(text);
34
+ return match ? { core: [match[1], match[2], match[3]].map(part => BigInt(part)), pre: match[4]?.split('.') ?? [] } : undefined;
35
+ }
36
+ function order(a, b) {
37
+ for (let i = 0; i < 3; i++)
38
+ if (a.core[i] !== b.core[i])
39
+ return a.core[i] < b.core[i] ? -1 : 1;
40
+ if (!a.pre.length || !b.pre.length)
41
+ return Math.sign(b.pre.length - a.pre.length);
42
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
43
+ const x = a.pre[i], y = b.pre[i];
44
+ if (x === undefined || y === undefined)
45
+ return x === undefined ? -1 : 1;
46
+ if (x === y)
47
+ continue;
48
+ const nx = /^\d+$/.test(x), ny = /^\d+$/.test(y);
49
+ if (nx && ny)
50
+ return BigInt(x) < BigInt(y) ? -1 : 1;
51
+ if (nx !== ny)
52
+ return nx ? -1 : 1;
53
+ return x < y ? -1 : 1;
54
+ }
55
+ return 0;
56
+ }
57
+ export const validVersion = (text, stable = false) => { const parsed = parseVersion(text); return !!parsed && (!stable || !parsed.pre.length); };
58
+ export function compareVersions(a, b) {
59
+ const x = parseVersion(a), y = parseVersion(b);
60
+ if (!x || !y)
61
+ throw new Refusal('invalid_version', 1);
62
+ return order(x, y);
63
+ }
64
+ const disk = {
65
+ read: path => { if (statSync(path).size > 1_048_576)
66
+ throw new Error('too_large'); return readFileSync(path, 'utf8'); },
67
+ real: path => realpathSync(path).replace(/\\/g, '/')
68
+ };
69
+ const declares = (root, probe) => {
70
+ try {
71
+ const value = JSON.parse(probe.read(`${root}/package.json`));
72
+ return ['dependencies', 'devDependencies', 'optionalDependencies'].some(key => {
73
+ const group = value?.[key];
74
+ return !!group && typeof group === 'object' && Object.hasOwn(group, PACKAGE);
75
+ });
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ };
81
+ const attempt = (check) => { try {
82
+ return check();
83
+ }
84
+ catch {
85
+ return false;
86
+ } };
87
+ // Guidance follows the resolved CLI file, and only a positively identified owner
88
+ // gets a command: an npm global prefix whose own launcher points at this package
89
+ // (default, Homebrew, nvm, nvm-windows, fnm), a manager-specific global store
90
+ // whose manifest declares session-peer, or Volta/npx stores. Anything else is
91
+ // `unknown` (no command), never a guess that could modify the current project.
92
+ export function manager(path = fileURLToPath(import.meta.url), platform = process.platform, probe = disk) {
93
+ const file = path.replace(/\\/g, '/');
94
+ const match = /^(.*)\/node_modules\/session-peer\/dist\/[^/]+$/.exec(file);
95
+ if (!match) {
96
+ const root = /^(.*)\/dist\/[^/]+$/.exec(file)?.[1];
97
+ return root && !/\/node_modules\//.test(file) && attempt(() => JSON.parse(probe.read(`${root}/package.json`)).name === PACKAGE) ? 'source' : 'unknown';
98
+ }
99
+ const parent = match[1], lower = parent.toLowerCase();
100
+ if (/\/_npx\/[0-9a-f]+$/.test(lower))
101
+ return 'npx';
102
+ if (/\/\.?volta\/tools\/image\/packages\/session-peer(?:\/lib)?$/.test(lower))
103
+ return 'volta';
104
+ const store = lower.lastIndexOf('/node_modules/.pnpm/');
105
+ if (store >= 0) {
106
+ const root = parent.slice(0, store);
107
+ if (!declares(root, probe))
108
+ return 'unknown';
109
+ return /\/pnpm\/global\/\d+$/.test(root.toLowerCase()) ? 'pnpm' : 'pnpm_project';
110
+ }
111
+ if (/\/yarn\/(?:data\/)?global$/.test(lower))
112
+ return declares(parent, probe) ? 'yarn' : 'unknown';
113
+ if (/\/\.bun\/install\/global$/.test(lower))
114
+ return declares(parent, probe) ? 'bun' : 'unknown';
115
+ const cli = `${parent}/node_modules/session-peer/dist/cli.js`;
116
+ if (platform === 'win32') {
117
+ if (attempt(() => probe.read(`${parent}/session-peer.cmd`).replace(/\\/g, '/').toLowerCase().includes('/node_modules/session-peer/dist/cli.js')))
118
+ return 'npm';
119
+ }
120
+ else if (lower.endsWith('/lib') && attempt(() => probe.real(`${parent.slice(0, -4)}/bin/session-peer`) === probe.real(cli)))
121
+ return 'npm';
122
+ return declares(parent, probe) ? 'npm_project' : 'unknown';
123
+ }
124
+ const COMMANDS = {
125
+ npm: spec => `npm install --global --ignore-scripts ${spec}`,
126
+ pnpm: spec => `pnpm add --global --ignore-scripts ${spec}`,
127
+ yarn: spec => `yarn global add --ignore-scripts ${spec}`,
128
+ bun: spec => `bun add --global --ignore-scripts ${spec}`,
129
+ volta: spec => `volta install ${spec}`,
130
+ npx: spec => `npx --yes --ignore-scripts ${spec} --version`
131
+ };
132
+ export const upgradeCommand = (owner, target) => COMMANDS[owner]?.(`${PACKAGE}@${target}`) ?? null;
133
+ export const upgradeGuidance = (owner) => owner === 'source' ? 'This is a source checkout; update it with git and rebuild.' :
134
+ owner === 'npm_project' || owner === 'pnpm_project' ? 'Update the session-peer dependency in the project that installed it.' :
135
+ owner === 'unknown' ? 'The installing package manager could not be identified; update session-peer with the tool that installed it.' :
136
+ `Run updateCommand with ${owner}, which manages this installation.`;
137
+ export function registryUrl(env = process.env) {
138
+ let url;
139
+ try {
140
+ url = new URL(env.SESSION_PEER_UPDATE_REGISTRY || 'https://registry.npmjs.org/');
141
+ }
142
+ catch {
143
+ throw new Refusal('invalid_update_registry');
144
+ }
145
+ // Plain HTTP only for loopback mirrors/fixtures; never embedded credentials.
146
+ const loopback = ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname);
147
+ if (!(url.protocol === 'https:' || (url.protocol === 'http:' && loopback)) || url.username || url.password || url.search || url.hash)
148
+ throw new Refusal('invalid_update_registry');
149
+ return new URL(`-/package/${PACKAGE}/dist-tags`, url.href.endsWith('/') ? url.href : url.href + '/');
150
+ }
151
+ const networkFailure = (error) => new Refusal(error?.name === 'TimeoutError' ? 'registry_timeout' : 'registry_unreachable', 1);
152
+ // One bounded request, no retries. Response bodies are never reported.
153
+ export async function distTags(env = process.env) {
154
+ const url = registryUrl(env);
155
+ const signal = AbortSignal.timeout(TIMEOUT);
156
+ let response;
157
+ try {
158
+ response = await fetch(url, { headers: { accept: 'application/json' }, redirect: 'error', signal });
159
+ }
160
+ catch (error) {
161
+ throw networkFailure(error);
162
+ }
163
+ if (response.status !== 200) {
164
+ await response.body?.cancel().catch(() => { });
165
+ throw new Refusal('registry_http_error', 1);
166
+ }
167
+ const chunks = [];
168
+ let bytes = 0;
169
+ try {
170
+ for await (const chunk of (response.body ?? [])) {
171
+ bytes += chunk.length;
172
+ if (bytes > RESPONSE_LIMIT)
173
+ throw new Refusal('registry_response_invalid', 1);
174
+ chunks.push(chunk);
175
+ }
176
+ }
177
+ catch (error) {
178
+ throw error instanceof Refusal ? error : networkFailure(error);
179
+ }
180
+ let value;
181
+ try {
182
+ value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
183
+ }
184
+ catch {
185
+ throw new Refusal('registry_response_invalid', 1);
186
+ }
187
+ if (!value || typeof value !== 'object' || Array.isArray(value))
188
+ throw new Refusal('registry_response_invalid', 1);
189
+ return value;
190
+ }
191
+ export function cacheDirectory(env = process.env, platform = process.platform) {
192
+ const configured = env.SESSION_PEER_CACHE_DIR;
193
+ if (configured) {
194
+ if (!isAbsolute(configured))
195
+ throw new Error('relative_cache_directory');
196
+ return configured;
197
+ }
198
+ if (platform === 'win32')
199
+ return join(env.LOCALAPPDATA && isAbsolute(env.LOCALAPPDATA) ? env.LOCALAPPDATA : join(homedir(), 'AppData', 'Local'), 'session-peer', 'Cache');
200
+ if (env.XDG_CACHE_HOME && isAbsolute(env.XDG_CACHE_HOME))
201
+ return join(env.XDG_CACHE_HOME, 'session-peer');
202
+ return join(homedir(), platform === 'darwin' ? 'Library/Caches' : '.cache', 'session-peer');
203
+ }
204
+ function privateDirectory(env) {
205
+ const directory = cacheDirectory(env);
206
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
207
+ const info = lstatSync(directory);
208
+ if (!info.isDirectory())
209
+ throw new Error('cache_not_directory');
210
+ if (process.platform !== 'win32') {
211
+ if (info.uid !== process.getuid())
212
+ throw new Error('cache_not_owned');
213
+ if (info.mode & 0o077)
214
+ chmodSync(directory, 0o700);
215
+ }
216
+ return directory;
217
+ }
218
+ export function readCache(env = process.env, now = Date.now()) {
219
+ let value;
220
+ try {
221
+ const path = join(cacheDirectory(env), CACHE), info = lstatSync(path);
222
+ if (!info.isFile() || info.size > CACHE_LIMIT)
223
+ return { status: 'invalid' };
224
+ value = JSON.parse(readFileSync(path, 'utf8'));
225
+ }
226
+ catch (error) {
227
+ return { status: error.code === 'ENOENT' ? 'missing' : 'invalid' };
228
+ }
229
+ const record = value;
230
+ if (!record || typeof record !== 'object' || Array.isArray(record) || record.schemaVersion !== 1 || record.package !== PACKAGE ||
231
+ record.source !== 'npm_registry' || record.channel !== 'latest')
232
+ return { status: 'invalid' };
233
+ const { latest, checkedAt } = record;
234
+ if (typeof checkedAt !== 'number' || !Number.isSafeInteger(checkedAt) || checkedAt > now + 300_000 ||
235
+ (latest !== null && !validVersion(latest, true)))
236
+ return { status: 'invalid' };
237
+ // A failed refresh (latest:null) only backs off further attempts.
238
+ return { status: now - checkedAt < (latest === null ? FAILURE_TTL : TTL) ? 'fresh' : 'expired', latest: latest, checkedAt };
239
+ }
240
+ // Internal helper: callers must hold the refresh lock (see publish). dist/updates.js is
241
+ // not a package export, so none of these functions are public API.
242
+ function writeCache(latest, env, now = Date.now()) {
243
+ const directory = privateDirectory(env);
244
+ const temporary = join(directory, `.${CACHE}.${process.pid}.${randomUUID()}.tmp`);
245
+ try {
246
+ const fd = openSync(temporary, 'wx', 0o600);
247
+ try {
248
+ writeSync(fd, JSON.stringify({ schemaVersion: 1, package: PACKAGE, source: 'npm_registry', channel: 'latest', latest, checkedAt: now }));
249
+ fsyncSync(fd);
250
+ }
251
+ finally {
252
+ closeSync(fd);
253
+ }
254
+ renameSync(temporary, join(directory, CACHE));
255
+ }
256
+ finally {
257
+ rmSync(temporary, { force: true });
258
+ }
259
+ }
260
+ // Single flight, fail closed. Every cache write (background refresh or explicit
261
+ // check) happens only while holding `npm-update.lock`, created with O_EXCL and a
262
+ // random token. Nothing ever takes over, moves or deletes a lock it did not
263
+ // create: an existing lock of any age makes the background refresh skip and
264
+ // the explicit check skip its cache write. A lock left by a crashed refresh
265
+ // stays until the user removes it (see PARITY.md).
266
+ const TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
267
+ const readLock = (lock) => { try {
268
+ return readFileSync(lock, 'utf8');
269
+ }
270
+ catch {
271
+ return undefined;
272
+ } };
273
+ export function acquireLock(env = process.env) {
274
+ const lock = join(privateDirectory(env), LOCK), token = randomUUID();
275
+ let fd;
276
+ try {
277
+ fd = openSync(lock, 'wx', 0o600);
278
+ }
279
+ catch (error) {
280
+ if (error.code === 'EEXIST')
281
+ return undefined;
282
+ throw error;
283
+ }
284
+ let created;
285
+ try {
286
+ created = fstatSync(fd, { bigint: true });
287
+ writeSync(fd, token);
288
+ }
289
+ catch (error) {
290
+ try {
291
+ closeSync(fd);
292
+ }
293
+ catch { }
294
+ // Remove only the file this call just created (same inode); never another lock.
295
+ try {
296
+ const info = lstatSync(lock, { bigint: true });
297
+ if (created && info.dev === created.dev && info.ino === created.ino)
298
+ rmSync(lock, { force: true });
299
+ }
300
+ catch { }
301
+ throw error;
302
+ }
303
+ closeSync(fd);
304
+ return token;
305
+ }
306
+ export function lockState(env = process.env, now = Date.now()) {
307
+ try {
308
+ return now - lstatSync(join(cacheDirectory(env), LOCK)).mtimeMs >= LOCK_STALE ? 'stale' : 'held';
309
+ }
310
+ catch (error) {
311
+ return error.code === 'ENOENT' ? 'free' : 'held';
312
+ }
313
+ }
314
+ // Only the creator removes its lock; nobody else changes the lock path.
315
+ export function releaseLock(token, env = process.env) {
316
+ try {
317
+ if (!token || !TOKEN.test(token))
318
+ return false;
319
+ const lock = join(cacheDirectory(env), LOCK);
320
+ if (readLock(lock) !== token)
321
+ return false;
322
+ rmSync(lock, { force: true });
323
+ return true;
324
+ }
325
+ catch {
326
+ return false;
327
+ }
328
+ }
329
+ // Writes as the lock holder, and only over an older record.
330
+ function publish(token, latest, started, env) {
331
+ try {
332
+ if (readLock(join(cacheDirectory(env), LOCK)) !== token)
333
+ return 'not_owner';
334
+ const current = readCache(env);
335
+ if (current.checkedAt !== undefined && current.checkedAt >= started)
336
+ return 'skipped_newer';
337
+ writeCache(latest, env);
338
+ return 'written';
339
+ }
340
+ catch {
341
+ return 'failed';
342
+ }
343
+ }
344
+ function scheduleRefresh(env) {
345
+ let token;
346
+ try {
347
+ token = acquireLock(env);
348
+ if (!token)
349
+ return false;
350
+ const owned = token;
351
+ const child = spawn(process.execPath, [fileURLToPath(new URL('./cli.js', import.meta.url)), REFRESH_ARG], { detached: true, stdio: 'ignore', windowsHide: true, env: { ...env, [LOCK_TOKEN]: owned } });
352
+ child.once('error', () => releaseLock(owned, env));
353
+ child.unref();
354
+ return true;
355
+ }
356
+ catch {
357
+ releaseLock(token, env);
358
+ return false;
359
+ }
360
+ }
361
+ // Background refresh by the inherited lock holder; without its token, nothing happens.
362
+ export async function refreshCache(env = process.env) {
363
+ const token = env[LOCK_TOKEN], started = Date.now();
364
+ if (!token || !TOKEN.test(token) || readLock(join(cacheDirectory(env), LOCK)) !== token)
365
+ return;
366
+ try {
367
+ let latest = null;
368
+ try {
369
+ const tags = await distTags(env);
370
+ if (validVersion(tags.latest, true))
371
+ latest = tags.latest;
372
+ }
373
+ catch { }
374
+ publish(token, latest, started, env);
375
+ }
376
+ finally {
377
+ releaseLock(token, env);
378
+ }
379
+ }
380
+ const truthy = (value) => ['1', 'true', 'yes', 'on'].includes((value ?? '').trim().toLowerCase());
381
+ export const noticesEnabled = (optOut, env = process.env) => !optOut && !truthy(env.SESSION_PEER_NO_UPDATE_NOTICE) && truthy(env.SESSION_PEER_UPDATE_NOTICE);
382
+ // Advisory and client-side only: reads the local cache, at most schedules one
383
+ // detached refresh, and never throws into or delays the requested command.
384
+ export function updateNotice(optOut, env = process.env, now = Date.now()) {
385
+ try {
386
+ if (!noticesEnabled(optOut, env))
387
+ return undefined;
388
+ const state = readCache(env, now);
389
+ if (state.status !== 'fresh') {
390
+ scheduleRefresh(env);
391
+ return undefined;
392
+ }
393
+ if (!state.latest || compareVersions(VERSION, state.latest) >= 0)
394
+ return undefined;
395
+ const owner = manager();
396
+ return { schemaVersion: 1, status: 'available', current: VERSION, latest: state.latest, channel: 'latest',
397
+ checkedAt: new Date(state.checkedAt).toISOString().replace(/\.\d{3}Z$/, 'Z'), source: 'npm_registry_cache',
398
+ managedBy: owner, command: upgradeCommand(owner, state.latest), guidance: upgradeGuidance(owner) };
399
+ }
400
+ catch {
401
+ return undefined;
402
+ }
403
+ }
404
+ export const noticeText = (notice) => `Update available: session-peer ${notice.current} -> ${notice.latest} (npm dist-tag latest). ` +
405
+ (notice.command ? `Run: ${notice.command}` : String(notice.guidance));
406
+ export async function checkUpdate(channel = 'latest', env = process.env) {
407
+ const started = Date.now();
408
+ const tags = await distTags(env);
409
+ if (tags[channel] === undefined)
410
+ throw new Refusal('dist_tag_missing', 1);
411
+ const latest = tags[channel];
412
+ if (!validVersion(latest, channel === 'latest'))
413
+ throw new Refusal('registry_response_invalid', 1);
414
+ // An intended request refreshes the shared cache under the same lock, or reports why it did not.
415
+ let cache = 'not_applicable';
416
+ if (channel === 'latest') {
417
+ try {
418
+ const token = acquireLock(env);
419
+ // Keep the documented enum: an unverifiable lock (not_owner) is reported as failed.
420
+ if (token) {
421
+ const outcome = publish(token, latest, started, env);
422
+ cache = outcome === 'not_owner' ? 'failed' : outcome;
423
+ releaseLock(token, env);
424
+ }
425
+ else
426
+ cache = lockState(env) === 'stale' ? 'skipped_stale_lock' : 'skipped_locked';
427
+ }
428
+ catch {
429
+ cache = 'failed';
430
+ }
431
+ }
432
+ const position = compareVersions(VERSION, latest), owner = manager();
433
+ return { ok: true, package: PACKAGE, current: VERSION, latest, channel, distTag: channel, source: 'npm_registry',
434
+ status: position < 0 ? 'update_available' : position === 0 ? 'up_to_date' : 'ahead', outdated: position < 0,
435
+ updated: false, managedBy: owner, updateCommand: position < 0 ? upgradeCommand(owner, latest) : null,
436
+ guidance: position < 0 ? upgradeGuidance(owner) : `No update is needed for the ${channel} dist-tag.`,
437
+ cache, skills: inspectSkills(), skillsManagedBy: 'separate' };
438
+ }
439
+ // npm-owned files are never replaced in place; the owning manager installs updates.
440
+ export function refuseSelfUpdate(channel = 'latest') {
441
+ const owner = manager();
442
+ throw new UpdateRefusal('self_update_unsupported', { updated: false, managedBy: owner,
443
+ updateCommand: upgradeCommand(owner, channel), guidance: upgradeGuidance(owner), checkCommand: `session-peer update --check${channel === 'latest' ? '' : ` --channel ${channel}`} --json` });
444
+ }
package/dist/windows.d.ts CHANGED
@@ -4,6 +4,8 @@ export type WindowsProcess = {
4
4
  command: string;
5
5
  start: string;
6
6
  };
7
+ export declare const COMPILED_INSPECTION_TIMEOUT_MS = 20000;
8
+ export declare const START_PROBE_TIMEOUT_MS = 15000;
7
9
  export declare function inspectWindows(mode: 'identity' | 'openers', value: string): WindowsProcess[];
8
10
  export declare function windowsProcessStart(pid: number): bigint | undefined;
9
11
  export declare function postWindowsPipe(pipe: string, pid: number, text: string): Promise<void>;