session-peer 0.3.2 → 0.3.4
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/PARITY.md +125 -21
- package/README.ja.md +12 -6
- package/README.ko.md +77 -54
- package/README.md +12 -6
- package/README.zh-CN.md +12 -6
- package/RELEASING.md +119 -4
- package/SECURITY.md +1 -1
- package/VALIDATION.md +200 -4
- package/dist/cli.js +15 -34
- package/dist/diagnostics.js +3 -32
- package/dist/output.js +6 -0
- package/dist/process.d.ts +4 -0
- package/dist/process.js +34 -16
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +1 -1
- package/dist/skill-metadata.d.ts +10 -0
- package/dist/skill-metadata.js +144 -0
- package/dist/ssh-response.d.ts +18 -0
- package/dist/ssh-response.js +201 -0
- package/docs/api.md +7 -4
- package/docs/design/ordinary-ssh-responses.md +37 -0
- package/docs/design/typescript-skill-compatibility.md +84 -0
- package/docs/guide.ja.md +39 -14
- package/docs/guide.ko.md +251 -152
- package/docs/guide.md +70 -15
- package/docs/guide.zh-CN.md +39 -14
- package/docs/shorthand.md +1 -1
- package/package.json +2 -2
package/dist/process.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { 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
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
4
5
|
import { Refusal } from './discovery.js';
|
|
5
6
|
export class UnknownOutcome extends Error {
|
|
6
7
|
}
|
|
@@ -57,7 +58,9 @@ function forward(signal) {
|
|
|
57
58
|
}
|
|
58
59
|
export function run(binary, args, options = {}) {
|
|
59
60
|
return new Promise(resolve => {
|
|
60
|
-
let stdout = '', stderr = '', bytes = 0, spawned = false, interrupted = false, finished = false, stopped = false;
|
|
61
|
+
let stdout = '', stderr = '', bytes = 0, stderrBytes = 0, spawned = false, interrupted = false, finished = false, stopped = false;
|
|
62
|
+
let stopReason;
|
|
63
|
+
const chunks = [], outputDecoder = new StringDecoder('utf8'), diagnosticDecoder = new StringDecoder('utf8');
|
|
61
64
|
const child = spawn(binary, args, { shell: false, env: options.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'], detached: posix });
|
|
62
65
|
const release = () => {
|
|
63
66
|
if (child.pid === undefined || !groups.delete(child.pid) || groups.size)
|
|
@@ -71,12 +74,16 @@ export function run(binary, args, options = {}) {
|
|
|
71
74
|
finished = true;
|
|
72
75
|
clearTimeout(timer);
|
|
73
76
|
release();
|
|
74
|
-
|
|
77
|
+
stdout += outputDecoder.end();
|
|
78
|
+
stderr += diagnosticDecoder.end();
|
|
79
|
+
resolve({ code, stdout, stderr, spawned, interrupted,
|
|
80
|
+
...(options.rawStdout ? { stdoutBytes: Buffer.concat(chunks, bytes) } : {}), ...(stopReason ? { stopReason } : {}) });
|
|
75
81
|
};
|
|
76
|
-
const stop = () => {
|
|
82
|
+
const stop = (reason) => {
|
|
77
83
|
if (stopped || finished)
|
|
78
84
|
return;
|
|
79
85
|
stopped = interrupted = true;
|
|
86
|
+
stopReason = reason;
|
|
80
87
|
if (posix)
|
|
81
88
|
reap(child.pid);
|
|
82
89
|
else
|
|
@@ -90,9 +97,9 @@ export function run(binary, args, options = {}) {
|
|
|
90
97
|
if (child.exitCode !== null || child.signalCode !== null)
|
|
91
98
|
setTimeout(() => finish(child.exitCode), 100);
|
|
92
99
|
};
|
|
93
|
-
const timer = setTimeout(stop, options.timeout ?? 3000);
|
|
100
|
+
const timer = setTimeout(() => stop('timeout'), options.timeout ?? 3000);
|
|
94
101
|
const register = () => {
|
|
95
|
-
if (!posix || child.pid === undefined || groups.has(child.pid))
|
|
102
|
+
if (finished || stopped || !posix || child.pid === undefined || groups.has(child.pid))
|
|
96
103
|
return;
|
|
97
104
|
if (!groups.size)
|
|
98
105
|
for (const name of signals)
|
|
@@ -104,24 +111,35 @@ export function run(binary, args, options = {}) {
|
|
|
104
111
|
register();
|
|
105
112
|
child.once('spawn', () => { spawned = true; register(); });
|
|
106
113
|
child.stdin.on('error', () => { });
|
|
107
|
-
child.stdout.setEncoding('utf8');
|
|
108
114
|
child.stdout.on('data', (part) => {
|
|
109
|
-
bytes
|
|
110
|
-
|
|
111
|
-
|
|
115
|
+
if (bytes + part.length > (options.limit ?? 1024 * 1024)) {
|
|
116
|
+
stop('output_limit');
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
bytes += part.length;
|
|
120
|
+
if (options.rawStdout)
|
|
121
|
+
chunks.push(part);
|
|
112
122
|
else
|
|
113
|
-
stdout += part;
|
|
123
|
+
stdout += outputDecoder.write(part);
|
|
114
124
|
});
|
|
115
125
|
// Drain but never report native stderr (it may contain message text/credentials).
|
|
116
126
|
// Retain stderr only for allowlisted error classification. Never include it in CLI output.
|
|
117
127
|
child.stderr.on('data', (part) => {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
128
|
+
// Protocol mode has an independent 4096-byte diagnostic budget. Excess
|
|
129
|
+
// diagnostics are drained without retaining them or invalidating stdout.
|
|
130
|
+
if (stderrBytes < 4096) {
|
|
131
|
+
const kept = part.subarray(0, 4096 - stderrBytes);
|
|
132
|
+
stderrBytes += kept.length;
|
|
133
|
+
stderr += diagnosticDecoder.write(kept);
|
|
134
|
+
}
|
|
135
|
+
if (!options.rawStdout) {
|
|
136
|
+
if (bytes + part.length > (options.limit ?? 1024 * 1024))
|
|
137
|
+
stop('output_limit');
|
|
138
|
+
else
|
|
139
|
+
bytes += part.length;
|
|
140
|
+
}
|
|
123
141
|
});
|
|
124
|
-
child.once('error', () => { interrupted = true; });
|
|
142
|
+
child.once('error', () => { interrupted = true; stopReason = 'process_error'; });
|
|
125
143
|
// After a kill, the exit plus a short fixed grace bounds completion even if
|
|
126
144
|
// a pipe never closes; otherwise 'close' (all output read) completes it.
|
|
127
145
|
// A descendant that keeps the pipes open after the child exits runs into
|
package/dist/protocol.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export declare const VERSION = "0.3.
|
|
2
|
-
export declare const VERSION_LINE = "session-peer 0.3.
|
|
1
|
+
export declare const VERSION = "0.3.4";
|
|
2
|
+
export declare const VERSION_LINE = "session-peer 0.3.4 (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.3.
|
|
4
|
+
export const VERSION = '0.3.4';
|
|
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
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type SkillCheck = {
|
|
2
|
+
status: string;
|
|
3
|
+
code: string;
|
|
4
|
+
verification?: 'metadata_only';
|
|
5
|
+
};
|
|
6
|
+
export declare const SKILL_METADATA_LIMIT = 65536;
|
|
7
|
+
export declare function validateSkillMetadata(text: string, runtime?: unknown): SkillCheck;
|
|
8
|
+
export declare function inspectSkill(original: string): SkillCheck & {
|
|
9
|
+
path: string;
|
|
10
|
+
};
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// A local, bounded string-map inspection. No instructions, references, tools or
|
|
2
|
+
// network are executed. Body bytes are read, but never interpreted as commands.
|
|
3
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
|
|
4
|
+
import { TextDecoder } from 'node:util';
|
|
5
|
+
import { canonical } from './discovery.js';
|
|
6
|
+
import { VERSION } from './protocol.js';
|
|
7
|
+
const unknown = (code = 'skill_metadata_missing') => ({ status: 'unknown', code });
|
|
8
|
+
const verdict = (compatible) => ({ status: compatible ? 'compatible' : 'incompatible',
|
|
9
|
+
code: compatible ? 'skill_contract_compatible' : 'skill_contract_mismatch', verification: 'metadata_only' });
|
|
10
|
+
export const SKILL_METADATA_LIMIT = 65536;
|
|
11
|
+
const keys = ['version', 'runtime-implementation', 'runtime-min-version', 'runtime-full-version', 'runtime-capability-policy'];
|
|
12
|
+
// Finite reviewed profiles: public 0.3.2 is legacy-only; public 0.3.3 accepts
|
|
13
|
+
// both profiles. The explicit 0.3.4 row is an unreleased patch proposal, not
|
|
14
|
+
// generic future-version support. Compiled VERSION is 0.3.4 in this candidate.
|
|
15
|
+
const matrix = {
|
|
16
|
+
'0.3.2': ['0.1.0'], '0.3.3': ['0.1.0', '0.2.0'], '0.3.4': ['0.1.0', '0.2.0']
|
|
17
|
+
};
|
|
18
|
+
const profiles = {
|
|
19
|
+
'0.1.0': ['0.1.0', 'typescript', '0.1.0', '0.1.0', 'probe-help'],
|
|
20
|
+
'0.2.0': ['0.2.0', 'typescript', '0.1.0', '0.3.2', 'probe-help']
|
|
21
|
+
};
|
|
22
|
+
// Deliberately not general YAML: plain ASCII tokens or unescaped quoted strings,
|
|
23
|
+
// followed by an optional comment. YAML tags, aliases, maps and sequences fail.
|
|
24
|
+
function scalar(value) {
|
|
25
|
+
const match = /^(?:"([^"\\\r\n]*)"|'([^'\\\r\n]*)'|([A-Za-z0-9][A-Za-z0-9._/-]*))(?:[ ]+(?:#.*)?)?$/.exec(value);
|
|
26
|
+
const result = match ? match[1] ?? match[2] ?? match[3] : undefined;
|
|
27
|
+
return result?.length ? result : undefined;
|
|
28
|
+
}
|
|
29
|
+
export function validateSkillMetadata(text, runtime = VERSION) {
|
|
30
|
+
if (text.length > SKILL_METADATA_LIMIT || Buffer.byteLength(text, 'utf8') > SKILL_METADATA_LIMIT)
|
|
31
|
+
return unknown('skill_metadata_unreadable');
|
|
32
|
+
if (typeof runtime !== 'string' || !/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$/.test(runtime))
|
|
33
|
+
return unknown();
|
|
34
|
+
// BOM and controls are rejected explicitly; whole-file fatal UTF-8 happens in
|
|
35
|
+
// the reader. LF/CRLF and body tabs are supported; lone CR is not.
|
|
36
|
+
// Map indentation and value separators use spaces rather than tabs.
|
|
37
|
+
if (text.startsWith('\uFEFF') || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]|\r(?!\n)/.test(text))
|
|
38
|
+
return unknown();
|
|
39
|
+
const front = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1];
|
|
40
|
+
if (!front)
|
|
41
|
+
return unknown();
|
|
42
|
+
const lines = front.split(/\r?\n/), names = [], sections = [];
|
|
43
|
+
let rootOwner;
|
|
44
|
+
for (let i = 0; i < lines.length; i++) {
|
|
45
|
+
const line = lines[i];
|
|
46
|
+
if (/^[ ]*(?:#.*)?$/.test(line))
|
|
47
|
+
continue;
|
|
48
|
+
if (line.startsWith(' ')) {
|
|
49
|
+
// Comments/blank lines do not end a root scalar. Only metadata and
|
|
50
|
+
// ignored unrelated fields can own indented content; name cannot.
|
|
51
|
+
if (rootOwner === undefined || rootOwner === 'name')
|
|
52
|
+
return unknown();
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
const root = /^([a-z][a-z0-9-]*):/.exec(line);
|
|
56
|
+
if (!root)
|
|
57
|
+
return unknown();
|
|
58
|
+
rootOwner = root[1];
|
|
59
|
+
if (/^name:/.test(line)) {
|
|
60
|
+
if (!/^name:[ ]+/.test(line))
|
|
61
|
+
return unknown();
|
|
62
|
+
const name = scalar(line.slice(5).trimStart());
|
|
63
|
+
if (name === undefined)
|
|
64
|
+
return unknown();
|
|
65
|
+
names.push(name);
|
|
66
|
+
}
|
|
67
|
+
if (/^metadata:/.test(line)) {
|
|
68
|
+
if (!/^metadata:(?:[ ]+(?:#.*)?)?$/.test(line))
|
|
69
|
+
return unknown();
|
|
70
|
+
sections.push(i);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (names.length !== 1 || sections.length !== 1)
|
|
74
|
+
return unknown();
|
|
75
|
+
const fields = new Map();
|
|
76
|
+
for (let i = sections[0] + 1; i < lines.length; i++) {
|
|
77
|
+
const line = lines[i];
|
|
78
|
+
if (/^[ ]*(?:#.*)?$/.test(line))
|
|
79
|
+
continue;
|
|
80
|
+
if (!line.startsWith(' '))
|
|
81
|
+
break;
|
|
82
|
+
const match = /^ ([a-z][a-z0-9-]*):[ ]+(.*)$/.exec(line);
|
|
83
|
+
if (!match || fields.has(match[1]))
|
|
84
|
+
return unknown();
|
|
85
|
+
const value = scalar(match[2]);
|
|
86
|
+
if (value === undefined)
|
|
87
|
+
return unknown();
|
|
88
|
+
fields.set(match[1], value);
|
|
89
|
+
}
|
|
90
|
+
if (keys.some(key => !fields.has(key)))
|
|
91
|
+
return unknown();
|
|
92
|
+
const values = keys.map(key => fields.get(key));
|
|
93
|
+
const profile = Object.hasOwn(profiles, values[0]) ? profiles[values[0]] : undefined;
|
|
94
|
+
return verdict(names[0] === 'session-peer-ts' && !!profile && profile.every((value, i) => value === values[i]) &&
|
|
95
|
+
!!matrix[runtime]?.includes(values[0]));
|
|
96
|
+
}
|
|
97
|
+
function stable(a, b) {
|
|
98
|
+
return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
|
|
99
|
+
}
|
|
100
|
+
export function inspectSkill(original) {
|
|
101
|
+
let path = original, established = false;
|
|
102
|
+
try {
|
|
103
|
+
path = canonical(original); // Preserve separately managed symlink installations.
|
|
104
|
+
const before = lstatSync(path, { bigint: true });
|
|
105
|
+
if (!before.isFile() || before.size > BigInt(SKILL_METADATA_LIMIT))
|
|
106
|
+
return { path, ...unknown('skill_metadata_unreadable') };
|
|
107
|
+
established = true;
|
|
108
|
+
const flags = constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
109
|
+
const fd = openSync(path, flags);
|
|
110
|
+
try {
|
|
111
|
+
const opened = fstatSync(fd, { bigint: true });
|
|
112
|
+
if (!opened.isFile() || !stable(before, opened))
|
|
113
|
+
return { path, ...unknown('skill_metadata_unreadable') };
|
|
114
|
+
const bytes = Buffer.alloc(SKILL_METADATA_LIMIT + 1);
|
|
115
|
+
let length = 0;
|
|
116
|
+
while (length < bytes.length) {
|
|
117
|
+
const count = readSync(fd, bytes, length, bytes.length - length, length);
|
|
118
|
+
if (!count)
|
|
119
|
+
break;
|
|
120
|
+
length += count;
|
|
121
|
+
}
|
|
122
|
+
const after = fstatSync(fd, { bigint: true }), current = lstatSync(path, { bigint: true });
|
|
123
|
+
if (length > SKILL_METADATA_LIMIT || BigInt(length) !== before.size || !after.isFile() || !current.isFile() ||
|
|
124
|
+
!stable(before, after) || !stable(before, current) || canonical(original) !== path)
|
|
125
|
+
return { path, ...unknown('skill_metadata_unreadable') };
|
|
126
|
+
let text;
|
|
127
|
+
try {
|
|
128
|
+
text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length));
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return { path, ...unknown('skill_metadata_unreadable') };
|
|
132
|
+
}
|
|
133
|
+
return { path, ...validateSkillMetadata(text) };
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
closeSync(fd);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
const code = error.code;
|
|
141
|
+
return { path, ...(!established && (code === 'ENOENT' || code === 'ENOTDIR') ? { status: 'missing', code: 'skill_missing' } :
|
|
142
|
+
code === 'EACCES' || code === 'EPERM' ? { status: 'permission_denied', code: 'permission_denied' } : unknown('skill_metadata_unreadable')) };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Done } from './process.js';
|
|
2
|
+
export declare const RESPONSE_BYTES: number;
|
|
3
|
+
export declare const RESPONSE_DEPTH = 64;
|
|
4
|
+
export declare const RESPONSE_NODES = 65536;
|
|
5
|
+
export declare function parseResponse(bytes: Uint8Array): Record<string, unknown>;
|
|
6
|
+
export type ResponseRequest = {
|
|
7
|
+
command: string;
|
|
8
|
+
to?: string;
|
|
9
|
+
dryRun?: boolean;
|
|
10
|
+
returnTo?: string;
|
|
11
|
+
home?: string;
|
|
12
|
+
allowInactive?: boolean;
|
|
13
|
+
};
|
|
14
|
+
export declare function validateResponse(value: Record<string, unknown>, request: ResponseRequest): void;
|
|
15
|
+
export declare function responseOutcome(done: Done, request: ResponseRequest): {
|
|
16
|
+
value: Record<string, unknown>;
|
|
17
|
+
exitCode: number;
|
|
18
|
+
};
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Ordinary SSH response protocol. Internal helpers, not a package-root API.
|
|
2
|
+
import { casefold } from './casefold.js';
|
|
3
|
+
import { uuid } from './writer.js';
|
|
4
|
+
export const RESPONSE_BYTES = 1024 * 1024;
|
|
5
|
+
export const RESPONSE_DEPTH = 64;
|
|
6
|
+
export const RESPONSE_NODES = 65536;
|
|
7
|
+
function invalid() { throw new Error('remote_response_unverified'); }
|
|
8
|
+
// A finite-depth scanner validates the whole frame and decoded object keys
|
|
9
|
+
// before JSON.parse can overwrite duplicates. Each key/value consumes a node;
|
|
10
|
+
// both allocations and recursion are bounded independently of field semantics.
|
|
11
|
+
export function parseResponse(bytes) {
|
|
12
|
+
if (bytes.byteLength > RESPONSE_BYTES)
|
|
13
|
+
return invalid();
|
|
14
|
+
let text;
|
|
15
|
+
try {
|
|
16
|
+
text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return invalid();
|
|
20
|
+
}
|
|
21
|
+
let at = 0, nodes = 0;
|
|
22
|
+
const number = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
|
|
23
|
+
const space = () => { while (at < text.length && /[\x20\t\r\n]/.test(text[at]))
|
|
24
|
+
at++; };
|
|
25
|
+
const count = () => { if (++nodes > RESPONSE_NODES)
|
|
26
|
+
invalid(); };
|
|
27
|
+
const string = () => {
|
|
28
|
+
const start = at++;
|
|
29
|
+
while (at < text.length) {
|
|
30
|
+
const char = text[at++];
|
|
31
|
+
if (char === '\\') {
|
|
32
|
+
at++;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (char === '"') {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(text.slice(start, at));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return invalid();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return invalid();
|
|
45
|
+
};
|
|
46
|
+
const value = (depth) => {
|
|
47
|
+
count();
|
|
48
|
+
space();
|
|
49
|
+
const char = text[at];
|
|
50
|
+
if (char === '{' || char === '[') {
|
|
51
|
+
if (depth >= RESPONSE_DEPTH)
|
|
52
|
+
invalid();
|
|
53
|
+
const object = char === '{', close = object ? '}' : ']';
|
|
54
|
+
const keys = new Set();
|
|
55
|
+
at++;
|
|
56
|
+
space();
|
|
57
|
+
if (text[at] === close) {
|
|
58
|
+
at++;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
while (true) {
|
|
62
|
+
if (object) {
|
|
63
|
+
space();
|
|
64
|
+
if (text[at] !== '"')
|
|
65
|
+
invalid();
|
|
66
|
+
count();
|
|
67
|
+
const key = string();
|
|
68
|
+
if (keys.has(key))
|
|
69
|
+
invalid();
|
|
70
|
+
keys.add(key);
|
|
71
|
+
space();
|
|
72
|
+
if (text[at++] !== ':')
|
|
73
|
+
invalid();
|
|
74
|
+
}
|
|
75
|
+
value(depth + 1);
|
|
76
|
+
space();
|
|
77
|
+
if (text[at] === close) {
|
|
78
|
+
at++;
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (text[at++] !== ',')
|
|
82
|
+
invalid();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (char === '"') {
|
|
86
|
+
string();
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
for (const literal of ['true', 'false', 'null']) {
|
|
90
|
+
if (text.startsWith(literal, at)) {
|
|
91
|
+
at += literal.length;
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
number.lastIndex = at;
|
|
96
|
+
const matched = number.exec(text);
|
|
97
|
+
if (!matched)
|
|
98
|
+
invalid();
|
|
99
|
+
at = number.lastIndex;
|
|
100
|
+
};
|
|
101
|
+
space();
|
|
102
|
+
if (text[at] !== '{')
|
|
103
|
+
return invalid();
|
|
104
|
+
value(0);
|
|
105
|
+
space();
|
|
106
|
+
if (at !== text.length)
|
|
107
|
+
return invalid();
|
|
108
|
+
try {
|
|
109
|
+
return JSON.parse(text);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return invalid();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
116
|
+
// Bind supported native facts to the original command, dry-run and exact
|
|
117
|
+
// target. Home aliases are resolved on the destination; this does not resolve
|
|
118
|
+
// remote paths on the caller or authenticate a remote process/incarnation.
|
|
119
|
+
export function validateResponse(value, request) {
|
|
120
|
+
if (value.schemaVersion !== 1 || value.command !== request.command || typeof value.ok !== 'boolean' ||
|
|
121
|
+
typeof value.host !== 'string' || !value.host || ('error' in value && (value.ok || typeof value.error !== 'string')))
|
|
122
|
+
invalid();
|
|
123
|
+
if (request.command === 'list' && value.ok && !Array.isArray(value.sessions))
|
|
124
|
+
invalid();
|
|
125
|
+
if (request.command === 'doctor' && value.ok && (value.diagnosticCompleted !== true || typeof value.ready !== 'boolean' ||
|
|
126
|
+
value.implementation !== 'typescript' || !record(value.agents)))
|
|
127
|
+
invalid();
|
|
128
|
+
if (request.command === 'doctor' && value.ok && request.returnTo && (!record(value.returnRoute) ||
|
|
129
|
+
!['verified', 'failed'].includes(value.returnRoute.status) || value.returnRoute.transport !== 'ssh' ||
|
|
130
|
+
value.returnRoute.host !== request.returnTo))
|
|
131
|
+
invalid();
|
|
132
|
+
if (request.command !== 'send')
|
|
133
|
+
return;
|
|
134
|
+
if (!value.ok && typeof value.error !== 'string')
|
|
135
|
+
invalid();
|
|
136
|
+
const codex = request.to?.startsWith('codex:') === true;
|
|
137
|
+
const expected = request.dryRun ? 'validated' : codex ? 'queued' : 'posted';
|
|
138
|
+
if (value.consumptionConfirmed !== false ||
|
|
139
|
+
(value.ok && (value.submitted !== !request.dryRun || value.status !== expected)) ||
|
|
140
|
+
(!value.ok && !((value.submitted === false && value.status === 'refused') ||
|
|
141
|
+
(!request.dryRun && value.submitted === null && value.status === 'unknown'))) ||
|
|
142
|
+
('dryRun' in value && value.dryRun !== !!request.dryRun) || ('retryAllowed' in value && value.retryAllowed !== false))
|
|
143
|
+
invalid();
|
|
144
|
+
if (!value.ok) {
|
|
145
|
+
if ('queueId' in value)
|
|
146
|
+
invalid();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const target = value.target;
|
|
150
|
+
if (!record(target) || (target.agent !== undefined && target.agent !== (codex ? 'codex' : 'claude')))
|
|
151
|
+
invalid();
|
|
152
|
+
if (codex) {
|
|
153
|
+
if (typeof target.id !== 'string' || !uuid(target.id) || target.id.toLowerCase() !== request.to.slice(6).toLowerCase())
|
|
154
|
+
invalid();
|
|
155
|
+
if ('queueId' in value && (request.dryRun || typeof value.queueId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.queueId)))
|
|
156
|
+
invalid();
|
|
157
|
+
if (typeof value.codexHome !== 'string' || !/^(?:\/|[A-Za-z]:[\\/]|[\\/]{2})/.test(value.codexHome))
|
|
158
|
+
invalid();
|
|
159
|
+
// A receiver can canonicalize a remote alias. It echoes the explicit home
|
|
160
|
+
// it actually parsed, rather than asking the caller to resolve remote paths.
|
|
161
|
+
if ('requestedCodexHome' in value && (request.home === undefined || value.requestedCodexHome !== request.home))
|
|
162
|
+
invalid();
|
|
163
|
+
if (request.home !== undefined && value.codexHome !== request.home && value.requestedCodexHome !== request.home)
|
|
164
|
+
invalid();
|
|
165
|
+
if ('codexHomeResolution' in value && (!record(value.codexHomeResolution) || value.codexHomeResolution.schemaVersion !== 1 ||
|
|
166
|
+
value.codexHomeResolution.status !== (request.home === undefined ? 'selected' : 'explicit') ||
|
|
167
|
+
value.codexHomeResolution.selected !== value.codexHome ||
|
|
168
|
+
(value.codexHomeResolution.reason === 'explicit_inactive_opt_in' && !request.allowInactive)))
|
|
169
|
+
invalid();
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
if (!Number.isSafeInteger(target.pid) || target.pid <= 0 || !(typeof target.name === 'string' || target.name === null) || 'queueId' in value)
|
|
173
|
+
invalid();
|
|
174
|
+
const requested = request.to.replace(/^claude:/, '');
|
|
175
|
+
if (/^\d+$/.test(requested) ? target.pid !== Number(requested) :
|
|
176
|
+
typeof target.name !== 'string' || casefold(target.name) !== casefold(requested))
|
|
177
|
+
invalid();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// Transport failure is not a second submission. A fully validated response
|
|
181
|
+
// keeps native ok/status/submitted unchanged; local exit 1 reports transport
|
|
182
|
+
// failure. Overflow never establishes a complete frame, even with a prefix.
|
|
183
|
+
export function responseOutcome(done, request) {
|
|
184
|
+
if (!done.spawned || done.stopReason === 'output_limit' || !done.stdoutBytes)
|
|
185
|
+
return invalid();
|
|
186
|
+
const value = parseResponse(done.stdoutBytes);
|
|
187
|
+
validateResponse(value, request);
|
|
188
|
+
// Reserved client-owned diagnosis; retain unrelated additive native fields.
|
|
189
|
+
delete value.sshTransport;
|
|
190
|
+
delete value.requestedCodexHome;
|
|
191
|
+
const ordinary = !done.interrupted && [0, 1, 2].includes(done.code ?? -1);
|
|
192
|
+
if (ordinary) {
|
|
193
|
+
if (value.ok !== (done.code === 0))
|
|
194
|
+
return invalid();
|
|
195
|
+
return { value, exitCode: done.code };
|
|
196
|
+
}
|
|
197
|
+
return { value: { ...value, ...(request.command === 'send' ? { retryAllowed: false } : {}),
|
|
198
|
+
sshTransport: { status: done.stopReason === 'timeout' ? 'timed_out' : 'failed',
|
|
199
|
+
reason: done.stopReason === 'timeout' ? 'ssh_timeout' : done.stopReason === 'process_error' ? 'ssh_process_error' : 'ssh_exit_nonzero',
|
|
200
|
+
exitCode: done.code } }, exitCode: 1 };
|
|
201
|
+
}
|
package/docs/api.md
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
# API reference
|
|
2
2
|
|
|
3
|
-
This reference describes source/package version **0.3.
|
|
3
|
+
This reference describes source/package version **0.3.4**. 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.3.
|
|
8
|
+
locally with `npm install --ignore-scripts session-peer@0.3.4` 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.3.
|
|
15
|
-
console.log(VERSION_LINE); // session-peer 0.3.
|
|
14
|
+
console.log(VERSION); // 0.3.4
|
|
15
|
+
console.log(VERSION_LINE); // session-peer 0.3.4 (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));
|
|
@@ -30,3 +30,6 @@ not verify a live writer, establish a return route, or confirm consumption.
|
|
|
30
30
|
Only the exports above form the public package API; internal `dist` modules are
|
|
31
31
|
not package subpath exports. Use the [CLI guide](guide.md#use) for sending and
|
|
32
32
|
[CONTRIBUTING.md](../CONTRIBUTING.md) for development and test setup.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
The ordinary SSH response correction is documented separately as the [0.3.3 ordinary SSH response correction](design/ordinary-ssh-responses.md); its internal parser is not a package-root export.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
<a id="ordinary-ssh-response-validation--033-release-candidate"></a>
|
|
2
|
+
|
|
3
|
+
# Ordinary SSH response validation — 0.3.3
|
|
4
|
+
|
|
5
|
+
This describes the source correction for [#116](https://github.com/abruption/session-peer-ts/issues/116) and [#115](https://github.com/abruption/session-peer-ts/issues/115). It is not a claim that the immutable npm 0.3.2 artifact contains it. Both endpoints still require the same TypeScript client version. The Python 1.0.2 development oracle and the separate 0.4.0 handoff proposals are unchanged.
|
|
6
|
+
|
|
7
|
+
## Bounded protocol
|
|
8
|
+
|
|
9
|
+
- Request stdout is collected as raw bytes, with a **1,048,576-byte** limit including whitespace and line endings. An overflow invalidates the entire response; a retained valid prefix is not accepted.
|
|
10
|
+
- UTF-8 decoding is fatal, including sequences split across process chunks. An actual UTF-8 U+FFFD character is legal; invalid bytes are not repaired into one.
|
|
11
|
+
- The frame contains exactly one top-level JSON object, surrounded only by JSON space, tab, CR and LF. BOM, banners, trailing material, multiple frames and non-JSON constants are rejected.
|
|
12
|
+
- A pre-parse scanner rejects duplicate decoded keys in every object, including escaped-equivalent keys. Containers have a maximum depth of **64**, and values plus object keys have a combined budget of **65,536 nodes**. The scanner's recursion and allocations are bounded by these limits and the byte limit; it does not evaluate input. Legacy JSON number spellings are not replaced with the separate handoff proposal's integer grammar.
|
|
13
|
+
- Diagnostic stderr is independent of protocol stdout: at most **4,096 raw bytes** are retained and replacement decoded. Excess is drained, and raw diagnostics are never printed in the result. Malformed stderr alone does not invalidate a complete stdout response.
|
|
14
|
+
- Version preflight and other non-protocol tool consumers keep their text interfaces and existing timeouts. The SSH request deadline remains 90 seconds. POSIX cleanup kills only the owned process group; escaped descendants and Windows descendant cleanup retain their documented limits.
|
|
15
|
+
|
|
16
|
+
## Native facts and transport completion
|
|
17
|
+
|
|
18
|
+
The same parser and command/request validator apply to normal and abnormal transport completion. Send responses must match the requested agent, Codex UUID or Claude PID/casefolded name, dry-run/status/submitted facts, and `consumptionConfirmed:false`. Claude `name:null`, an omitted target agent, and an omitted Codex queue ID remain supported. A present queue ID must match the native bounded identifier grammar. Returned Codex home and selected-home metadata must agree, the selected/explicit mode must match the request, and an inactive opt-in reason requires the caller's opt-in. If a canonical returned home differs from the explicit input, the receiver must echo its parsed `requestedCodexHome`; the caller validates and removes this wire-only scalar. Legacy same-path results do not need the scalar. Home aliases and canonicalization belong to the destination, not the caller's local filesystem. This check does not authenticate the remote native process or prove an independent mapping of a remote path alias.
|
|
19
|
+
|
|
20
|
+
| Transport / frame | Local result |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| Verified ordinary exit 0/1/2 | Preserve native fields and the existing exit/`ok` consistency contract. |
|
|
23
|
+
| Complete independently validated response followed by SSH 255, shutdown or collection timeout | Preserve native `ok`, `status`, `submitted`, target and optional queue ID; return **exit 1** and an additive `sshTransport` diagnostic. |
|
|
24
|
+
| Missing, partial, malformed, polluted, overflowed or mismatched response after a possible send effect | `outcome_unknown`, `submitted:null`, `retryAllowed:false`, exit 1. |
|
|
25
|
+
| Unverified dry-run or non-send response | `remote_response_unverified`, exit 1; no native submission is performed by those commands. |
|
|
26
|
+
|
|
27
|
+
`sshTransport` is client-owned and contains `status` (`failed` or `timed_out`), `reason` (`ssh_exit_nonzero`, `ssh_timeout` or `ssh_process_error`) and the observed `exitCode` (integer or null). A peer cannot supply this client diagnosis. It is omitted for ordinary verified exits. An abnormal transport send adds `retryAllowed:false` and never resubmits, falls back or fails over.
|
|
28
|
+
|
|
29
|
+
Consequently **native `ok:true` can coexist with local exit 1**. Consumers must inspect native submission facts and the transport diagnostic rather than assume a nonzero exit means nothing was submitted. Text output keeps the native result and adds the transport warning. Definite remote refusal facts are retained when a complete verified response establishes them. Missing native fields are not synthesized as false or null.
|
|
30
|
+
|
|
31
|
+
Ordered fanout preserves each destination's result and has exit 1 if any destination has a nonzero local exit. `posted`/`queued` and `submitted:true` remain submission evidence only: no injection, receipt ACK, task completion or retry authority is established.
|
|
32
|
+
|
|
33
|
+
## Validation boundaries
|
|
34
|
+
|
|
35
|
+
The fixtures use synthetic response objects and owned fake processes/SSH endpoints, not live agent delivery. They cover complete versus partial output, exit 0/255, actual process collection timeout, invalid diagnostic bytes, byte/depth/node limits, escaped duplicate keys, nullable Claude names, request mismatches, ordered mixed-host results and one request per host. A test-only import shortens the production request timer in the POSIX CLI fixture; production has no new timeout setting. The portable parser/process tests run in the Windows suite; the native Windows fixture exercises a complete Codex response followed by SSH 255 through encoded PowerShell. CI results and exact commits are recorded in the PR, not inferred from fixture names.
|
|
36
|
+
|
|
37
|
+
At dependency [PR #127](https://github.com/abruption/session-peer-ts/pull/127) head `8c882fa`, 13 portable parser/process fixtures passed. POSIX fake SSH exercised complete/partial frames with exits 0/255 and a real shortened collection timeout, plus ordered fanout and one attempt per host. The encoded PowerShell Windows fixture retained a complete `queued` native stand-in result (`ok:true`, `submitted:true`) after SSH 255 and invalid diagnostic stderr, while returning local exit 1 with `sshTransport`; it made exactly one queue stand-in call. [CI run 37863835806](https://github.com/abruption/session-peer-ts/actions/runs/37863835806) passed 12/12 checks including macOS/Ubuntu Node 22/24 and Windows native Node 22/24; [CodeQL run 37863832399](https://github.com/abruption/session-peer-ts/actions/runs/37863832399) also passed. This qualifies that dependency head's bounded fixtures, not a future merged main release SHA. It adds no actual agent ACK, real SSH-host, delivery/crash or fleet verification. Final combined candidate checks and exact artifact evidence belong in [VALIDATION.md](../../VALIDATION.md).
|