@stav-ai/cli 0.1.6 → 0.1.9
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/README.md +14 -4
- package/dist/adapters/index.js +91 -29
- package/dist/adapters/pi-stav-provider.js +2 -1
- package/dist/agent/index.js +626 -0
- package/dist/agent/pairings.js +83 -0
- package/dist/agent/passkey.js +86 -0
- package/dist/agent/questions.js +232 -0
- package/dist/agent/relay.js +224 -0
- package/dist/agent/steps.js +131 -0
- package/dist/agent/wire.js +41 -0
- package/dist/cli.js +30 -4
- package/dist/config.js +1 -0
- package/dist/http.js +2 -1
- package/dist/launch.js +26 -8
- package/dist/noise.js +225 -0
- package/dist/prompt.js +119 -0
- package/dist/stav.js +3 -3
- package/dist/store/index.js +10 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The steps of a task as lines in the terminal.
|
|
3
|
+
*
|
|
4
|
+
* The text of a step comes from an agent that reads other people's text, so
|
|
5
|
+
* none of it may look like a line of ours. Every line of it starts with
|
|
6
|
+
* `MARK`: control characters are gone (terminalText), a line feed starts a new
|
|
7
|
+
* marked line, and a long line is broken here, because a line the terminal
|
|
8
|
+
* breaks itself would go on at the left edge. Only our own fixed words start
|
|
9
|
+
* a line without the mark.
|
|
10
|
+
*/
|
|
11
|
+
import { terminalText } from '../terminal-text.js';
|
|
12
|
+
export const MARK = '│ ';
|
|
13
|
+
/** At most this many columns: only ASCII is sure to take one, a terminal may show § or ø in two. */
|
|
14
|
+
const width = (char) => (char.codePointAt(0) < 0x7f ? 1 : 2);
|
|
15
|
+
const isNumber = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
|
16
|
+
const isText = (v) => typeof v === 'string';
|
|
17
|
+
/** A code the connector or the relay sent, or `unknown`. It goes on lines of ours. */
|
|
18
|
+
export const word = (v) => (isText(v) && /^[a-z0-9_]{1,64}$/.test(v) ? v : 'unknown');
|
|
19
|
+
const QUESTIONS = {
|
|
20
|
+
needs_approval: '● The agent asks for your approval',
|
|
21
|
+
needs_login: '● The agent asks you to sign in where its data is',
|
|
22
|
+
needs_access: '● The agent asks for access',
|
|
23
|
+
};
|
|
24
|
+
const END_STATES = { done: 'done', cannot: 'the agent could not do it', failed: 'failed' };
|
|
25
|
+
export class StepPrinter {
|
|
26
|
+
columns;
|
|
27
|
+
/** The text that goes on: which one, and how many columns its last line has. Null at the start of a line. */
|
|
28
|
+
open = null;
|
|
29
|
+
constructor(columns) {
|
|
30
|
+
this.columns = columns;
|
|
31
|
+
}
|
|
32
|
+
/** What to write before a line of ours. */
|
|
33
|
+
close() {
|
|
34
|
+
const out = this.open?.column ? '\n' : '';
|
|
35
|
+
this.open = null;
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
line(text) {
|
|
39
|
+
return `${this.close()}${text}\n`;
|
|
40
|
+
}
|
|
41
|
+
/** `first` and then `rest` start the lines. */
|
|
42
|
+
marked(text, first = MARK, rest = MARK) {
|
|
43
|
+
const limit = Math.max(8, this.columns() - 1);
|
|
44
|
+
let mark = first;
|
|
45
|
+
let out = '';
|
|
46
|
+
for (const char of terminalText(text.replace(/\r\n/g, '\n')).replace(/\t/g, ' ')) {
|
|
47
|
+
if (char === '\n') {
|
|
48
|
+
out += this.open.column ? '\n' : `${MARK}\n`;
|
|
49
|
+
this.open.column = 0;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (this.open.column + width(char) > limit && this.open.column > mark.length) {
|
|
53
|
+
out += '\n';
|
|
54
|
+
this.open.column = 0;
|
|
55
|
+
}
|
|
56
|
+
if (!this.open.column) {
|
|
57
|
+
out += mark;
|
|
58
|
+
this.open.column = mark.length;
|
|
59
|
+
mark = rest;
|
|
60
|
+
}
|
|
61
|
+
out += char;
|
|
62
|
+
this.open.column += width(char);
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
/** A text under a heading of ours. With `more` the next step of the same text goes on where it ended. */
|
|
67
|
+
text(key, heading, text, more) {
|
|
68
|
+
let out = '';
|
|
69
|
+
if (this.open?.key !== key) {
|
|
70
|
+
out = this.line(heading);
|
|
71
|
+
this.open = { key, column: 0 };
|
|
72
|
+
}
|
|
73
|
+
out += this.marked(text);
|
|
74
|
+
return more ? out : out + this.close();
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* A question. A choice's number stands left of the mark, where no text of
|
|
78
|
+
* the agent can come: not from the question, not from a long choice.
|
|
79
|
+
*/
|
|
80
|
+
question(reason, text, choices) {
|
|
81
|
+
let out = this.text('question', QUESTIONS[reason] ?? '● The agent has a question', text, false);
|
|
82
|
+
if (choices.length)
|
|
83
|
+
out += this.line('● You can answer');
|
|
84
|
+
for (const [i, choice] of choices.entries()) {
|
|
85
|
+
this.open = { key: 'choice', column: 0 };
|
|
86
|
+
out += this.marked(terminalText(choice).replace(/\s+/g, ' ').trim() || ' ', `${i + 1} ${MARK}`, ` ${MARK}`) + this.close();
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/** The step as it goes to the terminal. Empty for a kind this version does not know. */
|
|
91
|
+
step(f) {
|
|
92
|
+
const key = [f.task, f.call, f.kind, f.id, f.reasoning].join(' ');
|
|
93
|
+
const text = isText(f.text) ? f.text : '';
|
|
94
|
+
const more = f.more === true;
|
|
95
|
+
switch (f.kind) {
|
|
96
|
+
case 'start':
|
|
97
|
+
return this.line(`● A task started at ${isNumber(f.at) ? clock(f.at) : 'an unknown time'}.`);
|
|
98
|
+
case 'prompt':
|
|
99
|
+
return this.text(key, '● To the model', text, more);
|
|
100
|
+
case 'text':
|
|
101
|
+
return this.text(key, f.reasoning === true ? '● The model thinks' : '● The model', text, more);
|
|
102
|
+
case 'tool_call':
|
|
103
|
+
// The name comes from the agent too: it gets a marked line of its own.
|
|
104
|
+
return this.text(key, '● The model calls a tool', this.open?.key === key ? text : `${isText(f.name) ? f.name : ''}\n${text}`, more);
|
|
105
|
+
case 'tool_result':
|
|
106
|
+
return this.text(key, f.error === true ? '● The tool gave an error' : '● The tool gave', text, more);
|
|
107
|
+
case 'refused':
|
|
108
|
+
return this.text(key, '● A model call was refused', text, more);
|
|
109
|
+
case 'usage': {
|
|
110
|
+
const parts = [];
|
|
111
|
+
if (isNumber(f.input_tokens))
|
|
112
|
+
parts.push(`${f.input_tokens} tokens in`);
|
|
113
|
+
if (isNumber(f.output_tokens))
|
|
114
|
+
parts.push(`${f.output_tokens} tokens out`);
|
|
115
|
+
if (isText(f.cost) && /^\d{1,12}(\.\d{1,12})?$/.test(f.cost))
|
|
116
|
+
parts.push(`cost ${f.cost}${isText(f.currency) && /^[A-Z]{3}$/.test(f.currency) ? ` ${f.currency}` : ''}`);
|
|
117
|
+
return parts.length ? this.line(`● Used: ${parts.join(', ')}.`) : '';
|
|
118
|
+
}
|
|
119
|
+
case 'end':
|
|
120
|
+
return this.line(`● The task ended: ${END_STATES[word(f.state)] ?? word(f.state)}${f.reason ? ` (${word(f.reason)})` : ''}.`);
|
|
121
|
+
case 'gap':
|
|
122
|
+
return this.line(`● ${isNumber(f.lines) ? f.lines : 'Some'} steps were left out here: they came faster than this terminal could show them.`);
|
|
123
|
+
default:
|
|
124
|
+
return '';
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Epoch seconds as a local time. */
|
|
129
|
+
export function clock(at) {
|
|
130
|
+
return new Date(at * 1000).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
|
|
131
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** The small parts of WATCH.md that the CLI, the connector and the page must all make the same way. */
|
|
2
|
+
import { createHash, hkdfSync } from 'node:crypto';
|
|
3
|
+
const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
4
|
+
const CODE_LENGTH = 26;
|
|
5
|
+
const FINGERPRINT_LENGTH = 10;
|
|
6
|
+
/** What a person typed, in the alphabet of § 3: case, spaces and dashes do not matter. */
|
|
7
|
+
function readTyped(typed, length) {
|
|
8
|
+
const text = typed.replace(/[\s-]/g, '').replace(/[a-z]/g, (c) => c.toUpperCase()).replace(/[IL]/g, '1').replace(/O/g, '0');
|
|
9
|
+
return text.length === length && [...text].every((c) => ALPHABET.includes(c)) ? text : null;
|
|
10
|
+
}
|
|
11
|
+
/** The pairing code, or null when it is not one. */
|
|
12
|
+
export const readCode = (typed) => readTyped(typed, CODE_LENGTH);
|
|
13
|
+
/** A typed passkey fingerprint, or null when it is not one. */
|
|
14
|
+
export const readFingerprint = (typed) => readTyped(typed, FINGERPRINT_LENGTH);
|
|
15
|
+
export function pskOf(code) {
|
|
16
|
+
return Buffer.from(hkdfSync('sha256', Buffer.from(code), Buffer.alloc(0), 'stav-agent-watch-v1 pair', 32));
|
|
17
|
+
}
|
|
18
|
+
export function prologue(kind, n) {
|
|
19
|
+
return Buffer.concat(['stav-agent-watch', '1', kind, n.agent_id, n.team_id, n.user_id, n.device_id].flatMap((s) => {
|
|
20
|
+
const bytes = Buffer.from(s);
|
|
21
|
+
const length = Buffer.alloc(2);
|
|
22
|
+
length.writeUInt16BE(bytes.length);
|
|
23
|
+
return [length, bytes];
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
/** The bytes the passkey signs. `number` is for `watch` only. */
|
|
27
|
+
export function challenge(mode, h, number = '') {
|
|
28
|
+
return createHash('sha256').update(`stav-agent-passkey-${mode}-v1\0`).update(h).update(mode === 'watch' ? number : '').digest();
|
|
29
|
+
}
|
|
30
|
+
/** The first 10 characters of the SHA-256 of the passkey's public key (SPKI DER). */
|
|
31
|
+
export function fingerprint(spki) {
|
|
32
|
+
const bits = [...createHash('sha256').update(spki).digest()].map((b) => b.toString(2).padStart(8, '0')).join('');
|
|
33
|
+
return Array.from({ length: FINGERPRINT_LENGTH }, (_, i) => ALPHABET[parseInt(bits.slice(i * 5, i * 5 + 5), 2)]).join('');
|
|
34
|
+
}
|
|
35
|
+
/** The bytes, or null when the text is not in the one canonical form. */
|
|
36
|
+
export function decode(text, encoding, length) {
|
|
37
|
+
if (typeof text !== 'string' || text === '')
|
|
38
|
+
return null;
|
|
39
|
+
const bytes = Buffer.from(text, encoding);
|
|
40
|
+
return bytes.toString(encoding) === text && (length === undefined || bytes.length === length) ? bytes : null;
|
|
41
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -5,17 +5,18 @@
|
|
|
5
5
|
* stav login | logout | whoami
|
|
6
6
|
* stav workspace [<slug>]
|
|
7
7
|
* stav apps
|
|
8
|
-
* stav launch <app> [--model <id>] [--workspace <slug>] [--yes] [-- <app arguments>]
|
|
8
|
+
* stav launch <app> [--model <id>] [--workspace <slug>] [--yes] [--verbose] [-- <app arguments>]
|
|
9
9
|
*
|
|
10
10
|
* No telemetry (spec B.9).
|
|
11
11
|
*/
|
|
12
12
|
import { parseArgs } from 'node:util';
|
|
13
13
|
import { ADAPTERS } from './adapters/index.js';
|
|
14
|
+
import { agentCommand, TIMES } from './agent/index.js';
|
|
14
15
|
import { accessToken, defaultIO, login, logout } from './auth/session.js';
|
|
15
16
|
import { loadConfig } from './config.js';
|
|
16
17
|
import { StavError } from './errors.js';
|
|
17
18
|
import { launch, runChild, which } from './launch.js';
|
|
18
|
-
import { terminal } from './prompt.js';
|
|
19
|
+
import { askHere, terminal } from './prompt.js';
|
|
19
20
|
import { terminalText } from './terminal-text.js';
|
|
20
21
|
import { Stav } from './stav.js';
|
|
21
22
|
import { forgetAppKeys, openStore, readSettings, writeSetting } from './store/index.js';
|
|
@@ -35,6 +36,7 @@ Launch options:
|
|
|
35
36
|
--model <id> The model, e.g. zai-org/glm-5-2 (default: the app's Stav default)
|
|
36
37
|
--workspace <slug> The workspace to use for this run
|
|
37
38
|
--yes Do not ask before making the key
|
|
39
|
+
--verbose Show the key's access, every setting and the app's warnings
|
|
38
40
|
|
|
39
41
|
Environment:
|
|
40
42
|
STAV_API_KEY Use this key; no sign-in and no key is made
|
|
@@ -62,6 +64,7 @@ async function main(argv) {
|
|
|
62
64
|
model: { type: 'string' },
|
|
63
65
|
workspace: { type: 'string' },
|
|
64
66
|
yes: { type: 'boolean', short: 'y' },
|
|
67
|
+
verbose: { type: 'boolean' },
|
|
65
68
|
'forget-keys': { type: 'boolean' },
|
|
66
69
|
help: { type: 'boolean', short: 'h' },
|
|
67
70
|
version: { type: 'boolean', short: 'v' },
|
|
@@ -77,8 +80,31 @@ async function main(argv) {
|
|
|
77
80
|
return command || values.help ? 0 : 1;
|
|
78
81
|
}
|
|
79
82
|
const cfg = loadConfig();
|
|
80
|
-
const store = await openStore();
|
|
81
83
|
const fetchFn = fetch;
|
|
84
|
+
if (command === 'agent') {
|
|
85
|
+
// Before the store is opened: pair and watch refuse first.
|
|
86
|
+
return agentCommand([...rest, ...appArgs], {
|
|
87
|
+
cfg, fetchFn, openStore, env: process.env, times: TIMES,
|
|
88
|
+
isTerminal: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
89
|
+
token: (s) => accessToken(fetchFn, cfg, s),
|
|
90
|
+
workspace: async (s) => {
|
|
91
|
+
const stored = (await readSettings()).workspace;
|
|
92
|
+
if (!values.workspace)
|
|
93
|
+
return stored;
|
|
94
|
+
const t = await accessToken(fetchFn, cfg, s);
|
|
95
|
+
return t ? (await chooseWorkspace(await new Stav(cfg, fetchFn).workspaces(t), values.workspace, stored, terminal)).id : stored;
|
|
96
|
+
},
|
|
97
|
+
ask: askHere,
|
|
98
|
+
openBrowser: defaultIO.open,
|
|
99
|
+
write: (text) => new Promise((resolve, reject) => process.stdout.write(text, (e) => (e ? reject(e) : resolve()))),
|
|
100
|
+
columns: () => process.stdout.columns || 80,
|
|
101
|
+
onInterrupt: (fn) => {
|
|
102
|
+
process.on('SIGINT', fn);
|
|
103
|
+
return () => process.off('SIGINT', fn);
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const store = await openStore();
|
|
82
108
|
const stav = new Stav(cfg, fetchFn);
|
|
83
109
|
const token = () => accessToken(fetchFn, cfg, store);
|
|
84
110
|
switch (command) {
|
|
@@ -192,7 +218,7 @@ async function main(argv) {
|
|
|
192
218
|
platform: process.platform,
|
|
193
219
|
cwd: process.cwd(),
|
|
194
220
|
};
|
|
195
|
-
return launch({ app, model: values.model, workspace: values.workspace, yes: values.yes, appArgs }, deps);
|
|
221
|
+
return launch({ app, model: values.model, workspace: values.workspace, yes: values.yes, verbose: values.verbose, appArgs }, deps);
|
|
196
222
|
}
|
|
197
223
|
default:
|
|
198
224
|
err(`Unknown command "${command}".\n`);
|
package/dist/config.js
CHANGED
|
@@ -13,6 +13,7 @@ export function loadConfig(env = process.env) {
|
|
|
13
13
|
return {
|
|
14
14
|
apiUrl: trim(env.STAV_API_URL, 'https://stav.ai'),
|
|
15
15
|
gatewayUrl: trim(env.STAV_GATEWAY_URL, 'https://api.stav.ai'),
|
|
16
|
+
relayUrl: trim(env.STAV_RELAY_URL, 'wss://relay.stav.ai'),
|
|
16
17
|
auth0Domain: trim(env.STAV_AUTH0_DOMAIN, 'auth.stav.ai'),
|
|
17
18
|
auth0ClientId: trim(env.STAV_AUTH0_CLIENT_ID, PROD_AUTH0_CLIENT_ID),
|
|
18
19
|
auth0Audience: trim(env.STAV_AUTH0_AUDIENCE, 'https://api.stav.ai') + '/',
|
package/dist/http.js
CHANGED
|
@@ -15,6 +15,7 @@ export async function request(fetchFn, url, opts = {}) {
|
|
|
15
15
|
if (opts.body !== undefined)
|
|
16
16
|
headers['Content-Type'] = 'application/json';
|
|
17
17
|
let res;
|
|
18
|
+
let text;
|
|
18
19
|
try {
|
|
19
20
|
res = await fetchFn(url, {
|
|
20
21
|
method: opts.method ?? (opts.body !== undefined ? 'POST' : 'GET'),
|
|
@@ -22,11 +23,11 @@ export async function request(fetchFn, url, opts = {}) {
|
|
|
22
23
|
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
|
23
24
|
signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
|
|
24
25
|
});
|
|
26
|
+
text = await res.text();
|
|
25
27
|
}
|
|
26
28
|
catch (err) {
|
|
27
29
|
throw new StavError(`Could not reach ${new URL(url).host}: ${err instanceof Error ? err.message : String(err)}`, 'network');
|
|
28
30
|
}
|
|
29
|
-
const text = await res.text();
|
|
30
31
|
let body = text;
|
|
31
32
|
try {
|
|
32
33
|
body = text ? JSON.parse(text) : null;
|
package/dist/launch.js
CHANGED
|
@@ -53,7 +53,7 @@ async function checkLaunch(opts, d) {
|
|
|
53
53
|
checkLaunchable(app, adapter, slug);
|
|
54
54
|
const model = opts.model ?? app.launch_recipe.default_model ?? null;
|
|
55
55
|
if (model !== null && !MODEL_RE.test(model)) {
|
|
56
|
-
throw new StavError(`"${model}" is not a model id. Use one like zai-org/glm-5-2.`, 'bad_model');
|
|
56
|
+
throw new StavError(`"${model}" is not a model id. Use one like zai-org/glm-5-2 or auto:eu.`, 'bad_model');
|
|
57
57
|
}
|
|
58
58
|
const programPath = d.which(adapter.program);
|
|
59
59
|
const conflict = adapter.conflicts ? await adapter.conflicts(d.env.HOME, d.cwd, d.env, opts.appArgs ?? []) : null;
|
|
@@ -217,20 +217,38 @@ export async function settleKey(plan, d) {
|
|
|
217
217
|
}
|
|
218
218
|
return made.full_key;
|
|
219
219
|
}
|
|
220
|
-
export function describePlan(plan, launch, appArgs, storeKind = 'keychain') {
|
|
220
|
+
export function describePlan(plan, launch, appArgs, storeKind = 'keychain', verbose = false) {
|
|
221
221
|
const lines = [];
|
|
222
222
|
if (plan.workspace)
|
|
223
223
|
lines.push(`Workspace: ${plan.workspace.name}`);
|
|
224
|
+
if (!verbose) {
|
|
225
|
+
const name = plan.adapter.displayName;
|
|
226
|
+
if ('create' in plan.key) {
|
|
227
|
+
// The key's access, and the workspace key an owner or admin may get
|
|
228
|
+
// instead, are said before the question; the rest is --verbose.
|
|
229
|
+
const fallback = plan.key.orWorkspaceKey ? '; a workspace key if personal keys are off' : '';
|
|
230
|
+
lines.push(`Make an API key for ${name} (${plan.adapter.scopes.join(', ')}${fallback}) and start it with ${launch.summary}.`);
|
|
231
|
+
}
|
|
232
|
+
else
|
|
233
|
+
lines.push(`Start ${name} with ${launch.summary}, using ${plan.key.source === 'env' ? 'the key in STAV_API_KEY' : 'your saved key'}.`);
|
|
234
|
+
if (launch.warning)
|
|
235
|
+
lines.push(launch.warning);
|
|
236
|
+
if (appArgs.length)
|
|
237
|
+
lines.push(`Your arguments: ${appArgs.join(' ')}`);
|
|
238
|
+
lines.push('Add --verbose to see the details.');
|
|
239
|
+
return lines;
|
|
240
|
+
}
|
|
241
|
+
const keep = storeKind === 'keychain'
|
|
242
|
+
? 'keep it in your keychain (never in this folder)'
|
|
243
|
+
: 'keep it in a file only you can read (no keychain here; never in this folder)';
|
|
224
244
|
if ('create' in plan.key) {
|
|
225
245
|
// A Stav that does not yet limit personal keys makes this key with
|
|
226
|
-
// full access
|
|
227
|
-
|
|
246
|
+
// full access. The short plan leaves that out; settleKey says so once
|
|
247
|
+
// the key is made.
|
|
248
|
+
lines.push(`Make a personal API key "${plan.key.name}" with access to ${plan.adapter.scopes.join(', ')} only, and ${keep} for next time. If Stav cannot limit personal keys yet, the key has full access to your workspace.`);
|
|
228
249
|
if (plan.key.orWorkspaceKey) {
|
|
229
250
|
lines.push(`If ${plan.workspace.name} does not allow personal keys, make a workspace API key with the same name and access instead.`);
|
|
230
251
|
}
|
|
231
|
-
lines.push(storeKind === 'keychain'
|
|
232
|
-
? 'Keep it in your keychain (never in this folder), and use it next time.'
|
|
233
|
-
: 'Keep it in a file only you can read (no keychain here; never in this folder), and use it next time.');
|
|
234
252
|
}
|
|
235
253
|
else {
|
|
236
254
|
lines.push(plan.key.source === 'env' ? 'Use the key in STAV_API_KEY.' : `Use your saved ${plan.adapter.displayName} key.`);
|
|
@@ -245,7 +263,7 @@ export function describePlan(plan, launch, appArgs, storeKind = 'keychain') {
|
|
|
245
263
|
export async function launch(opts, d) {
|
|
246
264
|
const plan = await planLaunch(opts, d);
|
|
247
265
|
const preview = plan.adapter.plan({ gatewayUrl: d.cfg.gatewayUrl, key: '<key>', model: plan.model });
|
|
248
|
-
for (const line of describePlan(plan, preview, opts.appArgs, d.store.kind))
|
|
266
|
+
for (const line of describePlan(plan, preview, opts.appArgs, d.store.kind, opts.verbose))
|
|
249
267
|
d.log(line);
|
|
250
268
|
const changes = 'create' in plan.key;
|
|
251
269
|
if (!opts.yes) {
|
package/dist/noise.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two Noise handshakes of WATCH.md § 2 (revision 34) on node:crypto:
|
|
3
|
+
* Noise_XXpsk0_25519_AESGCM_SHA256 and Noise_KK_25519_AESGCM_SHA256.
|
|
4
|
+
*
|
|
5
|
+
* Both roles are here: the CLI is always the initiator, the tests answer as
|
|
6
|
+
* the connector. Every handshake message has an empty payload.
|
|
7
|
+
*/
|
|
8
|
+
import { createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, createPublicKey, diffieHellman, randomBytes } from 'node:crypto';
|
|
9
|
+
const DH_LEN = 32;
|
|
10
|
+
const TAG_LEN = 16;
|
|
11
|
+
export const MAX_MESSAGE = 65_535;
|
|
12
|
+
const EMPTY = Buffer.alloc(0);
|
|
13
|
+
// The DER heads in front of a raw X25519 private and public key.
|
|
14
|
+
const PKCS8 = Buffer.from('302e020100300506032b656e04220420', 'hex');
|
|
15
|
+
const SPKI = Buffer.from('302a300506032b656e032100', 'hex');
|
|
16
|
+
export class NoiseError extends Error {
|
|
17
|
+
}
|
|
18
|
+
function privateKey(raw) {
|
|
19
|
+
return createPrivateKey({ key: Buffer.concat([PKCS8, raw]), format: 'der', type: 'pkcs8' });
|
|
20
|
+
}
|
|
21
|
+
export function keyPair(raw = randomBytes(DH_LEN)) {
|
|
22
|
+
if (raw.length !== DH_LEN)
|
|
23
|
+
throw new NoiseError('wrong key length');
|
|
24
|
+
return { private: raw, public: createPublicKey(privateKey(raw)).export({ format: 'der', type: 'spki' }).subarray(SPKI.length) };
|
|
25
|
+
}
|
|
26
|
+
/** X25519. A public key that gives the all-zero result is refused. */
|
|
27
|
+
export function dh(priv, pub) {
|
|
28
|
+
let out;
|
|
29
|
+
try {
|
|
30
|
+
out = diffieHellman({
|
|
31
|
+
privateKey: privateKey(priv),
|
|
32
|
+
publicKey: createPublicKey({ key: Buffer.concat([SPKI, pub]), format: 'der', type: 'spki' }),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new NoiseError('bad public key');
|
|
37
|
+
}
|
|
38
|
+
if (out.length !== DH_LEN || out.every((b) => b === 0))
|
|
39
|
+
throw new NoiseError('bad public key');
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
const sha256 = (...parts) => createHash('sha256').update(Buffer.concat(parts)).digest();
|
|
43
|
+
const hmac = (key, ...parts) => createHmac('sha256', key).update(Buffer.concat(parts)).digest();
|
|
44
|
+
function hkdf(ck, input, n) {
|
|
45
|
+
const temp = hmac(ck, input);
|
|
46
|
+
const out = [];
|
|
47
|
+
let last = EMPTY;
|
|
48
|
+
for (let i = 1; i <= n; i++) {
|
|
49
|
+
last = hmac(temp, last, Buffer.from([i]));
|
|
50
|
+
out.push(last);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
/** One key and its counter. */
|
|
55
|
+
export class CipherState {
|
|
56
|
+
key;
|
|
57
|
+
n = 0;
|
|
58
|
+
constructor(key) {
|
|
59
|
+
this.key = key;
|
|
60
|
+
}
|
|
61
|
+
nonce() {
|
|
62
|
+
const b = Buffer.alloc(12);
|
|
63
|
+
b.writeBigUInt64BE(BigInt(this.n), 4);
|
|
64
|
+
return b;
|
|
65
|
+
}
|
|
66
|
+
encrypt(plain, ad = EMPTY) {
|
|
67
|
+
if (plain.length + TAG_LEN > MAX_MESSAGE)
|
|
68
|
+
throw new NoiseError('message too long');
|
|
69
|
+
const c = createCipheriv('aes-256-gcm', this.key, this.nonce(), { authTagLength: TAG_LEN });
|
|
70
|
+
c.setAAD(ad);
|
|
71
|
+
const out = Buffer.concat([c.update(plain), c.final(), c.getAuthTag()]);
|
|
72
|
+
this.n++;
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
decrypt(message, ad = EMPTY) {
|
|
76
|
+
if (message.length < TAG_LEN || message.length > MAX_MESSAGE)
|
|
77
|
+
throw new NoiseError('wrong message length');
|
|
78
|
+
const d = createDecipheriv('aes-256-gcm', this.key, this.nonce(), { authTagLength: TAG_LEN });
|
|
79
|
+
d.setAAD(ad);
|
|
80
|
+
d.setAuthTag(message.subarray(message.length - TAG_LEN));
|
|
81
|
+
try {
|
|
82
|
+
const out = Buffer.concat([d.update(message.subarray(0, message.length - TAG_LEN)), d.final()]);
|
|
83
|
+
this.n++;
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
throw new NoiseError('message does not decrypt');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const PATTERNS = {
|
|
92
|
+
pair: { name: 'Noise_XXpsk0_25519_AESGCM_SHA256', known: false, messages: [['psk', 'e'], ['e', 'ee', 's', 'es'], ['s', 'se']] },
|
|
93
|
+
watch: { name: 'Noise_KK_25519_AESGCM_SHA256', known: true, messages: [['e', 'es', 'ss'], ['e', 'ee', 'se']] },
|
|
94
|
+
};
|
|
95
|
+
export class Handshake {
|
|
96
|
+
o;
|
|
97
|
+
ck;
|
|
98
|
+
h;
|
|
99
|
+
cipher = null;
|
|
100
|
+
step = 0;
|
|
101
|
+
e;
|
|
102
|
+
re = null;
|
|
103
|
+
rs;
|
|
104
|
+
constructor(o) {
|
|
105
|
+
this.o = o;
|
|
106
|
+
const p = PATTERNS[o.kind];
|
|
107
|
+
this.e = o.ephemeral ?? keyPair();
|
|
108
|
+
this.rs = o.remoteStatic ?? null;
|
|
109
|
+
if (p.known !== (this.rs !== null) || (o.kind === 'pair') !== (o.psk?.length === 32))
|
|
110
|
+
throw new NoiseError('wrong keys for this handshake');
|
|
111
|
+
// A name of at most 32 bytes is padded with zeros, a longer one is hashed.
|
|
112
|
+
const name = Buffer.from(p.name);
|
|
113
|
+
this.h = name.length <= 32 ? Buffer.concat([name, Buffer.alloc(32 - name.length)]) : sha256(name);
|
|
114
|
+
this.ck = this.h;
|
|
115
|
+
this.mixHash(o.prologue);
|
|
116
|
+
if (p.known) {
|
|
117
|
+
this.mixHash(o.initiator ? o.static.public : this.rs);
|
|
118
|
+
this.mixHash(o.initiator ? this.rs : o.static.public);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
get done() {
|
|
122
|
+
return this.step === PATTERNS[this.o.kind].messages.length;
|
|
123
|
+
}
|
|
124
|
+
/** The handshake hash, after the last message. */
|
|
125
|
+
get hash() {
|
|
126
|
+
if (!this.done)
|
|
127
|
+
throw new NoiseError('the handshake is not finished');
|
|
128
|
+
return this.h;
|
|
129
|
+
}
|
|
130
|
+
get remoteStatic() {
|
|
131
|
+
if (!this.done || !this.rs)
|
|
132
|
+
throw new NoiseError('the handshake is not finished');
|
|
133
|
+
return this.rs;
|
|
134
|
+
}
|
|
135
|
+
mixHash(data) {
|
|
136
|
+
this.h = sha256(this.h, data);
|
|
137
|
+
}
|
|
138
|
+
mixKey(input) {
|
|
139
|
+
const [ck, k] = hkdf(this.ck, input, 2);
|
|
140
|
+
this.ck = ck;
|
|
141
|
+
this.cipher = new CipherState(k);
|
|
142
|
+
}
|
|
143
|
+
mixPsk() {
|
|
144
|
+
const [ck, h, k] = hkdf(this.ck, this.o.psk, 3);
|
|
145
|
+
this.ck = ck;
|
|
146
|
+
this.mixHash(h);
|
|
147
|
+
this.cipher = new CipherState(k);
|
|
148
|
+
}
|
|
149
|
+
seal(plain) {
|
|
150
|
+
const out = this.cipher ? this.cipher.encrypt(plain, this.h) : plain;
|
|
151
|
+
this.mixHash(out);
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
unseal(data) {
|
|
155
|
+
const out = this.cipher ? this.cipher.decrypt(data, this.h) : data;
|
|
156
|
+
this.mixHash(data);
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
/** The DH of a two-letter token: the first letter is the initiator's key. */
|
|
160
|
+
mixDh(token) {
|
|
161
|
+
const [mine, theirs] = this.o.initiator ? [token[0], token[1]] : [token[1], token[0]];
|
|
162
|
+
this.mixKey(dh((mine === 'e' ? this.e : this.o.static).private, (theirs === 'e' ? this.re : this.rs)));
|
|
163
|
+
}
|
|
164
|
+
tokens(writing) {
|
|
165
|
+
if (this.done || (this.step % 2 === 0) !== (writing === this.o.initiator))
|
|
166
|
+
throw new NoiseError('not this side\'s turn');
|
|
167
|
+
return PATTERNS[this.o.kind].messages[this.step];
|
|
168
|
+
}
|
|
169
|
+
write() {
|
|
170
|
+
const out = [];
|
|
171
|
+
for (const t of this.tokens(true)) {
|
|
172
|
+
if (t === 'psk')
|
|
173
|
+
this.mixPsk();
|
|
174
|
+
else if (t === 'e') {
|
|
175
|
+
out.push(this.e.public);
|
|
176
|
+
this.mixHash(this.e.public);
|
|
177
|
+
if (this.o.psk)
|
|
178
|
+
this.mixKey(this.e.public);
|
|
179
|
+
}
|
|
180
|
+
else if (t === 's')
|
|
181
|
+
out.push(this.seal(this.o.static.public));
|
|
182
|
+
else
|
|
183
|
+
this.mixDh(t);
|
|
184
|
+
}
|
|
185
|
+
out.push(this.seal(EMPTY));
|
|
186
|
+
this.step++;
|
|
187
|
+
return Buffer.concat(out);
|
|
188
|
+
}
|
|
189
|
+
/** A message that fails leaves the handshake useless: drop it. */
|
|
190
|
+
read(message) {
|
|
191
|
+
let rest = message;
|
|
192
|
+
const take = (n) => {
|
|
193
|
+
if (rest.length < n)
|
|
194
|
+
throw new NoiseError('message too short');
|
|
195
|
+
const part = rest.subarray(0, n);
|
|
196
|
+
rest = rest.subarray(n);
|
|
197
|
+
return part;
|
|
198
|
+
};
|
|
199
|
+
for (const t of this.tokens(false)) {
|
|
200
|
+
if (t === 'psk')
|
|
201
|
+
this.mixPsk();
|
|
202
|
+
else if (t === 'e') {
|
|
203
|
+
this.re = Buffer.from(take(DH_LEN));
|
|
204
|
+
this.mixHash(this.re);
|
|
205
|
+
if (this.o.psk)
|
|
206
|
+
this.mixKey(this.re);
|
|
207
|
+
}
|
|
208
|
+
else if (t === 's')
|
|
209
|
+
this.rs = this.unseal(take(DH_LEN + TAG_LEN));
|
|
210
|
+
else
|
|
211
|
+
this.mixDh(t);
|
|
212
|
+
}
|
|
213
|
+
if (rest.length !== TAG_LEN)
|
|
214
|
+
throw new NoiseError('wrong message length');
|
|
215
|
+
this.unseal(rest);
|
|
216
|
+
this.step++;
|
|
217
|
+
}
|
|
218
|
+
/** The two keys after the handshake, for this side. */
|
|
219
|
+
split() {
|
|
220
|
+
if (!this.done)
|
|
221
|
+
throw new NoiseError('the handshake is not finished');
|
|
222
|
+
const [first, second] = hkdf(this.ck, EMPTY, 2).map((k) => new CipherState(k));
|
|
223
|
+
return this.o.initiator ? { send: first, receive: second } : { send: second, receive: first };
|
|
224
|
+
}
|
|
225
|
+
}
|