sideby 0.24.0 → 0.26.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/README.md +3 -1
- package/ai-tasks.json +17 -0
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +14 -0
- package/dist/src/cli/commands.js +120 -12
- package/dist/src/cli/json-schemas.js +47 -0
- package/dist/src/cli/main.js +41 -6
- package/dist/src/core/ask.d.ts +10 -6
- package/dist/src/core/ask.js +52 -9
- package/dist/src/core/config.d.ts +16 -0
- package/dist/src/core/config.js +16 -0
- package/dist/src/core/egress.d.ts +103 -0
- package/dist/src/core/egress.js +333 -0
- package/dist/src/core/handoff-run.d.ts +4 -2
- package/dist/src/core/handoff-run.js +18 -11
- package/dist/src/core/launch.d.ts +5 -1
- package/dist/src/core/launch.js +5 -0
- package/dist/src/core/network.d.ts +131 -0
- package/dist/src/core/network.js +317 -0
- package/dist/src/families/agy/index.js +4 -1
- package/dist/src/families/claude/index.js +4 -1
- package/dist/src/families/codex/index.js +8 -1
- package/dist/src/families/grok/index.js +4 -1
- package/dist/src/families/pi/index.js +4 -1
- package/dist/src/network/hook.d.ts +15 -0
- package/dist/src/network/hook.js +69 -0
- package/dist/src/panel/handler.d.ts +3 -0
- package/dist/src/panel/handler.js +33 -1
- package/dist/src/panel/i18n.d.ts +51 -0
- package/dist/src/panel/i18n.js +102 -0
- package/dist/src/panel/page-logic.d.ts +23 -1
- package/dist/src/panel/page-logic.js +33 -0
- package/dist/src/panel/page-script.js +130 -2
- package/dist/src/panel/page-styles.js +11 -3
- package/dist/src/runtime.d.ts +18 -1
- package/dist/src/runtime.js +78 -7
- package/dist/src/types.d.ts +7 -0
- package/package.json +2 -2
- package/schemas/config.json +20 -0
- package/schemas/network-set.json +129 -0
- package/schemas/network.json +199 -0
- package/schemas/try.json +4 -0
- package/skills/sideby/SKILL.md +3 -2
- package/skills/sideby/references/ai-tasks.md +2 -1
- package/skills/sideby/references/network.md +37 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { Account, Env } from '../types.ts';
|
|
2
|
+
import type { Config } from './config.ts';
|
|
3
|
+
import { type EgressStatus, type TraceFetcher, type Verdict } from './egress.ts';
|
|
4
|
+
/** Families Network Guard covers in v1. */
|
|
5
|
+
export declare const GUARDED_FAMILIES: readonly ['claude', 'codex'];
|
|
6
|
+
export declare const TRACE: {
|
|
7
|
+
readonly anthropic: 'https://api.anthropic.com/cdn-cgi/trace';
|
|
8
|
+
readonly chatgpt: 'https://chatgpt.com/cdn-cgi/trace';
|
|
9
|
+
readonly openai: 'https://api.openai.com/cdn-cgi/trace';
|
|
10
|
+
};
|
|
11
|
+
/** Where an Account's Egress is checked, or why it is not. */
|
|
12
|
+
export type NetworkTarget = {
|
|
13
|
+
url: string;
|
|
14
|
+
} | {
|
|
15
|
+
skip: 'not-covered' | 'third-party';
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* The trace address that takes the same route as the Account's model requests: the vendor's own API domain for
|
|
19
|
+
* a Subscription Account or an API Account on the official endpoint; none for a third-party endpoint.
|
|
20
|
+
* `env` is the Launch environment (the Secret File already merged).
|
|
21
|
+
*/
|
|
22
|
+
export declare function networkTarget(account: Pick<Account, 'family' | 'kind'>, env: Env): NetworkTarget;
|
|
23
|
+
export declare const networkDir: (stateDir: string) => string;
|
|
24
|
+
/** Network Guard is on: the switch, a non-empty list, and not in CI (where it makes no request). */
|
|
25
|
+
export declare function guardOn(config: Pick<Config, 'network'>, env: Env): boolean;
|
|
26
|
+
export interface LaunchGuardResult {
|
|
27
|
+
/** Variables `network-hook` reads, to add to the Host's environment. */
|
|
28
|
+
env: Record<string, string>;
|
|
29
|
+
verdict: Verdict;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The check before a Launch (spec §3.35): throws a UserError that says what to do when the Egress is outside the
|
|
33
|
+
* list or cannot be told; returns what the session's hooks need, or null when this Launch is not guarded.
|
|
34
|
+
*/
|
|
35
|
+
export declare function guardLaunch(opts: {
|
|
36
|
+
account: Account;
|
|
37
|
+
env: Env;
|
|
38
|
+
config: Pick<Config, 'network'>;
|
|
39
|
+
stateDir: string;
|
|
40
|
+
label?: string;
|
|
41
|
+
fetcher?: TraceFetcher;
|
|
42
|
+
now?: () => Date;
|
|
43
|
+
print?: string;
|
|
44
|
+
}): Promise<LaunchGuardResult | null>;
|
|
45
|
+
/** The line a Launch prints when the check saw the address change (a notice, never a block). */
|
|
46
|
+
export declare function ipChangedLine(v: Verdict, env: Env): string | undefined;
|
|
47
|
+
/** Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). */
|
|
48
|
+
export declare function claudeNetworkHooks(): Record<string, unknown[]>;
|
|
49
|
+
/** The file holding Network Guard's Claude hooks alone. */
|
|
50
|
+
export declare const claudeNetworkSettings: (stateDir: string) => string;
|
|
51
|
+
/**
|
|
52
|
+
* Host arguments that add Network Guard's hooks to a session: Claude through a `--settings` file sideby writes,
|
|
53
|
+
* Codex through `-c hooks.*`. Nothing is written into a Host directory.
|
|
54
|
+
*/
|
|
55
|
+
export declare function networkHookArgs(family: string, stateDir: string): Promise<string[]>;
|
|
56
|
+
/** The line a Claude Launch prints when the user's own `--settings` leaves no room for the session hooks. */
|
|
57
|
+
export declare function networkSettingsLine(env: Env): string;
|
|
58
|
+
/** Once per Codex Account: Codex runs the hooks only after the user trusts them in `/hooks`. */
|
|
59
|
+
export declare function codexNetworkTrustLine(stateDir: string, ref: string, env: Env): Promise<string | undefined>;
|
|
60
|
+
/**
|
|
61
|
+
* Auto Handoff's Claude hook arguments with Network Guard's hooks added to its `--settings` file, written as a new
|
|
62
|
+
* file next to Network Guard's own (Claude Code takes one `--settings`).
|
|
63
|
+
*/
|
|
64
|
+
export declare function withClaudeNetworkHooks(hookArgs: readonly string[], stateDir: string): Promise<string[]>;
|
|
65
|
+
/** `args` without the Network Guard arguments `networkHookArgs` added (Auto Handoff merges them into its own). */
|
|
66
|
+
export declare function withoutArgs(args: readonly string[], drop: readonly string[]): string[];
|
|
67
|
+
/** Where one Account is checked, or why not: a third-party endpoint, or an API Account decided at Launch. */
|
|
68
|
+
export interface NetworkAccountRow {
|
|
69
|
+
ref: string;
|
|
70
|
+
url?: string;
|
|
71
|
+
skip?: 'not-covered' | 'third-party' | 'at-launch';
|
|
72
|
+
}
|
|
73
|
+
export interface NetworkTargetStatus {
|
|
74
|
+
url: string;
|
|
75
|
+
/** Accounts checked at this address. */
|
|
76
|
+
accounts: string[];
|
|
77
|
+
status: EgressStatus | 'not-checked';
|
|
78
|
+
loc?: string;
|
|
79
|
+
checkedAt?: string;
|
|
80
|
+
error?: string;
|
|
81
|
+
/** The address changed in the last day. */
|
|
82
|
+
ipChanged: boolean;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* What `sideby network` and the Panel show (spec §3.35): per address, the newest cached result, and per Account
|
|
86
|
+
* where it is checked or why not. Reads only the cache; `check` asks every address now.
|
|
87
|
+
*/
|
|
88
|
+
export declare function networkOverview(opts: {
|
|
89
|
+
accounts: readonly Account[];
|
|
90
|
+
config: Pick<Config, 'network'>;
|
|
91
|
+
stateDir: string;
|
|
92
|
+
env: Env;
|
|
93
|
+
envFor: (account: Account) => Promise<Env>;
|
|
94
|
+
check?: boolean;
|
|
95
|
+
fetcher?: TraceFetcher;
|
|
96
|
+
now?: () => Date;
|
|
97
|
+
print?: string;
|
|
98
|
+
}): Promise<{
|
|
99
|
+
guard: boolean;
|
|
100
|
+
allow: string[];
|
|
101
|
+
active: boolean;
|
|
102
|
+
ci: boolean;
|
|
103
|
+
targets: NetworkTargetStatus[];
|
|
104
|
+
accounts: NetworkAccountRow[];
|
|
105
|
+
}>;
|
|
106
|
+
export type NetworkOverview = Awaited<ReturnType<typeof networkOverview>>;
|
|
107
|
+
export interface NetworkChange {
|
|
108
|
+
guard?: boolean;
|
|
109
|
+
allow?: string[];
|
|
110
|
+
}
|
|
111
|
+
/** Country codes as config keeps them: upper case, two letters, each once, in the order given. */
|
|
112
|
+
export declare function normalizeAllow(codes: readonly string[]): string[];
|
|
113
|
+
/**
|
|
114
|
+
* `sideby network on|off|allow` and the Panel's network check (spec §3.35): changes config `network`, shown first
|
|
115
|
+
* (`apply: false`) and written with `apply`. Turning it on with no allowed country is refused.
|
|
116
|
+
*/
|
|
117
|
+
export declare function setNetwork(configFile: string, change: NetworkChange, opts: {
|
|
118
|
+
apply: boolean;
|
|
119
|
+
}): Promise<{
|
|
120
|
+
changed: boolean;
|
|
121
|
+
applied: boolean;
|
|
122
|
+
file: string;
|
|
123
|
+
before: {
|
|
124
|
+
guard: boolean;
|
|
125
|
+
allow: string[];
|
|
126
|
+
};
|
|
127
|
+
after: {
|
|
128
|
+
guard: boolean;
|
|
129
|
+
allow: string[];
|
|
130
|
+
};
|
|
131
|
+
}>;
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// Network Guard (spec §3.35, ADR-0053): which address each Account's Egress is checked at, the check before a
|
|
2
|
+
// Launch, and the hooks that keep checking inside a session sideby starts. The check itself is core/egress.ts.
|
|
3
|
+
import { mkdir, readFile } from 'node:fs/promises';
|
|
4
|
+
import { extname, join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { blockMessage, cacheKey, judge, NETWORK_ENV, prefersChinese, readEntry, refresh, verdict, } from './egress.js';
|
|
7
|
+
import { UserError } from './errors.js';
|
|
8
|
+
import { writeFileAtomic } from './fs-safe.js';
|
|
9
|
+
import { inCi } from './update.js';
|
|
10
|
+
/** Families Network Guard covers in v1. */
|
|
11
|
+
export const GUARDED_FAMILIES = ['claude', 'codex'];
|
|
12
|
+
export const TRACE = {
|
|
13
|
+
anthropic: 'https://api.anthropic.com/cdn-cgi/trace',
|
|
14
|
+
chatgpt: 'https://chatgpt.com/cdn-cgi/trace',
|
|
15
|
+
openai: 'https://api.openai.com/cdn-cgi/trace',
|
|
16
|
+
};
|
|
17
|
+
function officialHost(value, host) {
|
|
18
|
+
if (!value)
|
|
19
|
+
return true;
|
|
20
|
+
try {
|
|
21
|
+
return new URL(value).hostname.toLowerCase() === host;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The trace address that takes the same route as the Account's model requests: the vendor's own API domain for
|
|
29
|
+
* a Subscription Account or an API Account on the official endpoint; none for a third-party endpoint.
|
|
30
|
+
* `env` is the Launch environment (the Secret File already merged).
|
|
31
|
+
*/
|
|
32
|
+
export function networkTarget(account, env) {
|
|
33
|
+
if (account.family === 'claude') {
|
|
34
|
+
return officialHost(env.ANTHROPIC_BASE_URL, 'api.anthropic.com')
|
|
35
|
+
? { url: TRACE.anthropic }
|
|
36
|
+
: { skip: 'third-party' };
|
|
37
|
+
}
|
|
38
|
+
if (account.family === 'codex') {
|
|
39
|
+
if (account.kind === 'subscription')
|
|
40
|
+
return { url: TRACE.chatgpt };
|
|
41
|
+
const base = env.OPENAI_BASE_URL || env.CODEX_API_BASE_URL;
|
|
42
|
+
return officialHost(base, 'api.openai.com') ? { url: TRACE.openai } : { skip: 'third-party' };
|
|
43
|
+
}
|
|
44
|
+
return { skip: 'not-covered' };
|
|
45
|
+
}
|
|
46
|
+
export const networkDir = (stateDir) => join(stateDir, 'network');
|
|
47
|
+
/** Network Guard is on: the switch, a non-empty list, and not in CI (where it makes no request). */
|
|
48
|
+
export function guardOn(config, env) {
|
|
49
|
+
return Boolean(config.network?.guard && config.network.allow?.length && !inCi(env));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The check before a Launch (spec §3.35): throws a UserError that says what to do when the Egress is outside the
|
|
53
|
+
* list or cannot be told; returns what the session's hooks need, or null when this Launch is not guarded.
|
|
54
|
+
*/
|
|
55
|
+
export async function guardLaunch(opts) {
|
|
56
|
+
if (!guardOn(opts.config, opts.env))
|
|
57
|
+
return null;
|
|
58
|
+
const target = networkTarget(opts.account, opts.env);
|
|
59
|
+
if (!('url' in target))
|
|
60
|
+
return null;
|
|
61
|
+
const allow = opts.config.network?.allow ?? [];
|
|
62
|
+
const dir = networkDir(opts.stateDir);
|
|
63
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
64
|
+
const v = await verdict({
|
|
65
|
+
url: target.url,
|
|
66
|
+
env: opts.env,
|
|
67
|
+
allow,
|
|
68
|
+
dir,
|
|
69
|
+
moment: 'launch',
|
|
70
|
+
...(opts.fetcher ? { fetcher: opts.fetcher } : {}),
|
|
71
|
+
...(opts.now ? { now: opts.now } : {}),
|
|
72
|
+
...(opts.print ? { print: opts.print } : {}),
|
|
73
|
+
});
|
|
74
|
+
if (v.status !== 'ok')
|
|
75
|
+
throw new UserError(blockMessage(v, allow, {
|
|
76
|
+
ref: opts.label || opts.account.ref,
|
|
77
|
+
at: 'launch',
|
|
78
|
+
zh: prefersChinese(opts.env),
|
|
79
|
+
}), { code: v.status === 'blocked' ? 'network-blocked' : 'network-unknown' });
|
|
80
|
+
return {
|
|
81
|
+
env: { [NETWORK_ENV.url]: target.url, [NETWORK_ENV.allow]: allow.join(','), [NETWORK_ENV.dir]: dir },
|
|
82
|
+
verdict: v,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** The line a Launch prints when the check saw the address change (a notice, never a block). */
|
|
86
|
+
export function ipChangedLine(v, env) {
|
|
87
|
+
if (!v.ipChanged)
|
|
88
|
+
return undefined;
|
|
89
|
+
return prefersChinese(env)
|
|
90
|
+
? 'sideby:网络出口 IP 和上次不同(国家没变,没有拦截)。'
|
|
91
|
+
: 'sideby: the network exit address changed since the last check (same country, nothing blocked).';
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The command a Host runs for the hook: this Node and this sideby by absolute path, never `sideby` by name. A
|
|
95
|
+
* missing or older `sideby` on PATH would fail the hook, and a failing hook lets the Host go on.
|
|
96
|
+
*/
|
|
97
|
+
function hookCommand(family, event) {
|
|
98
|
+
const main = fileURLToPath(new URL(`../cli/main${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
|
|
99
|
+
const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
|
|
100
|
+
const safe = (s) => !/["\\\n]/.test(s);
|
|
101
|
+
const bin = safe(process.execPath) && safe(main) ? `${q(process.execPath)} ${q(main)}` : 'sideby';
|
|
102
|
+
return `${bin} network-hook ${family} ${event}`;
|
|
103
|
+
}
|
|
104
|
+
const HOOK_EVENTS = ['UserPromptSubmit', 'PreToolUse'];
|
|
105
|
+
/** Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). */
|
|
106
|
+
export function claudeNetworkHooks() {
|
|
107
|
+
const out = {};
|
|
108
|
+
for (const e of HOOK_EVENTS)
|
|
109
|
+
out[e] = [{ hooks: [{ type: 'command', command: hookCommand('claude', e) }] }];
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
/** The file holding Network Guard's Claude hooks alone. */
|
|
113
|
+
export const claudeNetworkSettings = (stateDir) => join(networkDir(stateDir), 'claude-settings.json');
|
|
114
|
+
/**
|
|
115
|
+
* Host arguments that add Network Guard's hooks to a session: Claude through a `--settings` file sideby writes,
|
|
116
|
+
* Codex through `-c hooks.*`. Nothing is written into a Host directory.
|
|
117
|
+
*/
|
|
118
|
+
export async function networkHookArgs(family, stateDir) {
|
|
119
|
+
if (family === 'claude') {
|
|
120
|
+
const file = claudeNetworkSettings(stateDir);
|
|
121
|
+
await mkdir(networkDir(stateDir), { recursive: true, mode: 0o700 });
|
|
122
|
+
await writeFileAtomic(file, `${JSON.stringify({ hooks: claudeNetworkHooks() }, null, 2)}\n`, 0o600);
|
|
123
|
+
return ['--settings', file];
|
|
124
|
+
}
|
|
125
|
+
if (family === 'codex')
|
|
126
|
+
return HOOK_EVENTS.flatMap((e) => [
|
|
127
|
+
'-c',
|
|
128
|
+
`hooks.${e}=[{hooks=[{type="command",command="${hookCommand('codex', e)}"}]}]`,
|
|
129
|
+
]);
|
|
130
|
+
return [];
|
|
131
|
+
}
|
|
132
|
+
/** The line a Claude Launch prints when the user's own `--settings` leaves no room for the session hooks. */
|
|
133
|
+
export function networkSettingsLine(env) {
|
|
134
|
+
return prefersChinese(env)
|
|
135
|
+
? 'sideby:已经给了 `--settings`,这个会话里不会每条消息前检查网络(启动前已检查)。'
|
|
136
|
+
: 'sideby: `--settings` is already given, so this session is not checked before each prompt (it was checked before starting).';
|
|
137
|
+
}
|
|
138
|
+
/** Once per Codex Account: Codex runs the hooks only after the user trusts them in `/hooks`. */
|
|
139
|
+
export async function codexNetworkTrustLine(stateDir, ref, env) {
|
|
140
|
+
const file = join(networkDir(stateDir), 'codex-trust-notices.json');
|
|
141
|
+
let seen = [];
|
|
142
|
+
try {
|
|
143
|
+
const v = JSON.parse(await readFile(file, 'utf8'));
|
|
144
|
+
if (Array.isArray(v.refs))
|
|
145
|
+
seen = v.refs.filter((r) => typeof r === 'string');
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// first notice
|
|
149
|
+
}
|
|
150
|
+
if (seen.includes(ref))
|
|
151
|
+
return undefined;
|
|
152
|
+
try {
|
|
153
|
+
await writeFileAtomic(file, `${JSON.stringify({ refs: [...seen, ref] })}\n`, 0o600);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
// shown again next time
|
|
157
|
+
}
|
|
158
|
+
return prefersChinese(env)
|
|
159
|
+
? `sideby:Codex 要先信任 hook 才会在会话中检查网络:在 ${ref} 里输入 /hooks,信任 \`network-hook\`。之前只在启动前检查。`
|
|
160
|
+
: `sideby: Codex checks the network inside a session only after you trust the hook: in ${ref}, type /hooks and trust \`network-hook\`. Until then it is checked only before starting.`;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Auto Handoff's Claude hook arguments with Network Guard's hooks added to its `--settings` file, written as a new
|
|
164
|
+
* file next to Network Guard's own (Claude Code takes one `--settings`).
|
|
165
|
+
*/
|
|
166
|
+
export async function withClaudeNetworkHooks(hookArgs, stateDir) {
|
|
167
|
+
const at = hookArgs.indexOf('--settings');
|
|
168
|
+
const file = at === -1 ? undefined : hookArgs[at + 1];
|
|
169
|
+
let settings = {};
|
|
170
|
+
if (file) {
|
|
171
|
+
try {
|
|
172
|
+
settings = JSON.parse(await readFile(file, 'utf8'));
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
settings = {};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const hooks = { ...(settings.hooks ?? {}) };
|
|
179
|
+
for (const [e, list] of Object.entries(claudeNetworkHooks()))
|
|
180
|
+
hooks[e] = [...(hooks[e] ?? []), ...list];
|
|
181
|
+
const out = join(networkDir(stateDir), 'claude-settings-handoff.json');
|
|
182
|
+
await mkdir(networkDir(stateDir), { recursive: true, mode: 0o700 });
|
|
183
|
+
await writeFileAtomic(out, `${JSON.stringify({ ...settings, hooks }, null, 2)}\n`, 0o600);
|
|
184
|
+
return at === -1 ? [...hookArgs, '--settings', out] : hookArgs.map((a, i) => (i === at + 1 ? out : a));
|
|
185
|
+
}
|
|
186
|
+
/** `args` without the Network Guard arguments `networkHookArgs` added (Auto Handoff merges them into its own). */
|
|
187
|
+
export function withoutArgs(args, drop) {
|
|
188
|
+
if (!drop.length)
|
|
189
|
+
return [...args];
|
|
190
|
+
for (let i = 0; i + drop.length <= args.length; i++) {
|
|
191
|
+
if (drop.every((d, j) => args[i + j] === d))
|
|
192
|
+
return [...args.slice(0, i), ...args.slice(i + drop.length)];
|
|
193
|
+
}
|
|
194
|
+
return [...args];
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* What `sideby network` and the Panel show (spec §3.35): per address, the newest cached result, and per Account
|
|
198
|
+
* where it is checked or why not. Reads only the cache; `check` asks every address now.
|
|
199
|
+
*/
|
|
200
|
+
export async function networkOverview(opts) {
|
|
201
|
+
const allow = opts.config.network?.allow ?? [];
|
|
202
|
+
const dir = networkDir(opts.stateDir);
|
|
203
|
+
const byUrl = new Map();
|
|
204
|
+
const accounts = [];
|
|
205
|
+
for (const a of opts.accounts) {
|
|
206
|
+
if (!GUARDED_FAMILIES.includes(a.family))
|
|
207
|
+
continue;
|
|
208
|
+
// An API Account's endpoint and proxy live in its Secret File, which sideby reads only at Launch.
|
|
209
|
+
if (a.kind === 'api') {
|
|
210
|
+
accounts.push({ ref: a.ref, skip: 'at-launch' });
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
let env;
|
|
214
|
+
try {
|
|
215
|
+
env = await opts.envFor(a);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
env = opts.env;
|
|
219
|
+
}
|
|
220
|
+
const t = networkTarget(a, env);
|
|
221
|
+
if ('url' in t) {
|
|
222
|
+
const got = byUrl.get(t.url) ?? { accounts: [], env };
|
|
223
|
+
got.accounts.push(a.ref);
|
|
224
|
+
byUrl.set(t.url, got);
|
|
225
|
+
accounts.push({ ref: a.ref, url: t.url });
|
|
226
|
+
}
|
|
227
|
+
else
|
|
228
|
+
accounts.push({ ref: a.ref, skip: t.skip });
|
|
229
|
+
}
|
|
230
|
+
const now = (opts.now?.() ?? new Date()).getTime();
|
|
231
|
+
const targets = [];
|
|
232
|
+
if (opts.check)
|
|
233
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
234
|
+
for (const [url, { accounts: refs, env }] of byUrl) {
|
|
235
|
+
let entry;
|
|
236
|
+
if (opts.check) {
|
|
237
|
+
entry = (await refresh({
|
|
238
|
+
url,
|
|
239
|
+
env,
|
|
240
|
+
dir,
|
|
241
|
+
...(opts.fetcher ? { fetcher: opts.fetcher } : {}),
|
|
242
|
+
...(opts.now ? { now: opts.now } : {}),
|
|
243
|
+
...(opts.print ? { print: opts.print } : {}),
|
|
244
|
+
})).entry;
|
|
245
|
+
}
|
|
246
|
+
else
|
|
247
|
+
entry = await readEntry(dir, cacheKey(url, env));
|
|
248
|
+
const changed = entry?.ipChangedAt ? now - Date.parse(entry.ipChangedAt) < 24 * 3600_000 : false;
|
|
249
|
+
targets.push({
|
|
250
|
+
url,
|
|
251
|
+
accounts: refs,
|
|
252
|
+
status: entry ? judge(entry, allow) : 'not-checked',
|
|
253
|
+
...(entry?.loc ? { loc: entry.loc } : {}),
|
|
254
|
+
...(entry ? { checkedAt: entry.checkedAt } : {}),
|
|
255
|
+
...(entry?.error ? { error: entry.error } : {}),
|
|
256
|
+
ipChanged: changed,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
guard: Boolean(opts.config.network?.guard),
|
|
261
|
+
allow,
|
|
262
|
+
active: guardOn(opts.config, opts.env),
|
|
263
|
+
ci: inCi(opts.env),
|
|
264
|
+
targets,
|
|
265
|
+
accounts,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/** Country codes as config keeps them: upper case, two letters, each once, in the order given. */
|
|
269
|
+
export function normalizeAllow(codes) {
|
|
270
|
+
const out = [];
|
|
271
|
+
for (const raw of codes) {
|
|
272
|
+
const c = raw.trim().toUpperCase();
|
|
273
|
+
if (!/^[A-Z]{2}$/.test(c))
|
|
274
|
+
throw new UserError(`"${raw}" is not a country code; use two letters such as US or JP (ISO 3166-1 alpha-2).`, { code: 'network-bad-country' });
|
|
275
|
+
if (!out.includes(c))
|
|
276
|
+
out.push(c);
|
|
277
|
+
}
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* `sideby network on|off|allow` and the Panel's network check (spec §3.35): changes config `network`, shown first
|
|
282
|
+
* (`apply: false`) and written with `apply`. Turning it on with no allowed country is refused.
|
|
283
|
+
*/
|
|
284
|
+
export async function setNetwork(configFile, change, opts) {
|
|
285
|
+
const { editConfigNetwork } = await import('./config.js');
|
|
286
|
+
const allow = change.allow ? normalizeAllow(change.allow) : undefined;
|
|
287
|
+
const r = await editConfigNetwork(configFile, (cur) => {
|
|
288
|
+
const next = { ...cur };
|
|
289
|
+
if (allow) {
|
|
290
|
+
if (allow.length)
|
|
291
|
+
next.allow = allow;
|
|
292
|
+
else
|
|
293
|
+
delete next.allow;
|
|
294
|
+
}
|
|
295
|
+
if (change.guard === true)
|
|
296
|
+
next.guard = true;
|
|
297
|
+
if (change.guard === false)
|
|
298
|
+
delete next.guard;
|
|
299
|
+
// Refused before anything is written.
|
|
300
|
+
if (next.guard && !next.allow?.length)
|
|
301
|
+
throw new UserError(change.guard
|
|
302
|
+
? 'Choose the countries first: `sideby network allow US JP` (the countries your requests may leave from), then `sideby network on`.'
|
|
303
|
+
: 'Network checking is on, so at least one country must stay allowed; turn it off first with `sideby network off`.', { code: 'network-allow-empty' });
|
|
304
|
+
return next;
|
|
305
|
+
}, { dryRun: !opts.apply });
|
|
306
|
+
const view = (c) => ({
|
|
307
|
+
guard: Boolean(c?.guard),
|
|
308
|
+
allow: c?.allow ?? [],
|
|
309
|
+
});
|
|
310
|
+
return {
|
|
311
|
+
changed: r.changed,
|
|
312
|
+
applied: opts.apply && r.changed,
|
|
313
|
+
file: configFile,
|
|
314
|
+
before: view(r.before),
|
|
315
|
+
after: view(r.after),
|
|
316
|
+
};
|
|
317
|
+
}
|
|
@@ -28,7 +28,10 @@ export const agyFamily = {
|
|
|
28
28
|
],
|
|
29
29
|
apiVars: [],
|
|
30
30
|
// `-p` is one non-interactive prompt (agy 1.4.4 --help, 2026-10-21).
|
|
31
|
-
probe: {
|
|
31
|
+
probe: {
|
|
32
|
+
args: ['-p', 'Reply with OK'],
|
|
33
|
+
model: { flags: ['--model'], args: (m) => ['--model', m, '-p', 'Reply with OK'] },
|
|
34
|
+
},
|
|
32
35
|
// agy reads a prompt only from -p, -i or stdin: "unexpected argument" otherwise (agy 1.4.4, 2026-10-21).
|
|
33
36
|
promptArg: '--prompt-interactive',
|
|
34
37
|
aiTaskArgs: (args) => args.includes(SKIP_PERMISSIONS) ? args.filter((a) => a !== SKIP_PERMISSIONS) : [...args],
|
|
@@ -108,7 +108,10 @@ export const claudeFamily = {
|
|
|
108
108
|
apiVars: ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL'],
|
|
109
109
|
secretVar: 'ANTHROPIC_AUTH_TOKEN',
|
|
110
110
|
// `-p` is one non-interactive prompt (Claude Code 2.1.301 --help, 2026-10-17).
|
|
111
|
-
probe: {
|
|
111
|
+
probe: {
|
|
112
|
+
args: ['-p', 'Reply with OK'],
|
|
113
|
+
model: { flags: ['--model'], args: (m) => ['--model', m, '-p', 'Reply with OK'] },
|
|
114
|
+
},
|
|
112
115
|
aiTaskArgs: claudeAiTaskArgs,
|
|
113
116
|
settingsFile: 'settings.json',
|
|
114
117
|
sharedItems: [
|
|
@@ -36,7 +36,14 @@ export const codexFamily = {
|
|
|
36
36
|
secretVar: 'OPENAI_API_KEY',
|
|
37
37
|
// `exec` refuses to run outside a git repo unless this flag is set (Codex 0.163.0 --help:
|
|
38
38
|
// allow running outside a Git repository). The probe's cwd is a temp directory.
|
|
39
|
-
probe: {
|
|
39
|
+
probe: {
|
|
40
|
+
args: ['exec', '--skip-git-repo-check', 'Reply with OK'],
|
|
41
|
+
// `exec` reads its own `-m`; a `-m` before the subcommand does not reach it.
|
|
42
|
+
model: {
|
|
43
|
+
flags: ['-m', '--model'],
|
|
44
|
+
args: (m) => ['exec', '--skip-git-repo-check', '-m', m, 'Reply with OK'],
|
|
45
|
+
},
|
|
46
|
+
},
|
|
40
47
|
// `-i, --image <FILE>...` takes several values (Codex 0.163.0 --help); AI Tasks pass `--image=<path>`, one value
|
|
41
48
|
// per flag, so the prompt after it stays a positional argument.
|
|
42
49
|
imageArg: '--image',
|
|
@@ -51,7 +51,10 @@ export const grokFamily = {
|
|
|
51
51
|
apiVars: ['GROK_MODELS_BASE_URL', 'XAI_API_KEY'],
|
|
52
52
|
secretVar: 'XAI_API_KEY',
|
|
53
53
|
// `-p` is one non-interactive prompt (Grok Build 1.0.60 --help, 2026-10-17).
|
|
54
|
-
probe: {
|
|
54
|
+
probe: {
|
|
55
|
+
args: ['-p', 'Reply with OK'],
|
|
56
|
+
model: { flags: ['-m', '--model'], args: (m) => ['--model', m, '-p', 'Reply with OK'] },
|
|
57
|
+
},
|
|
55
58
|
settingsFile: 'config.toml',
|
|
56
59
|
sharedItems: [
|
|
57
60
|
{ path: 'skills', mode: 'link' },
|
|
@@ -44,7 +44,10 @@ export const piFamily = {
|
|
|
44
44
|
// First key in the proxy.env template `new --api` writes. The OpenAI key is still set with `--var`.
|
|
45
45
|
secretVar: 'ANTHROPIC_API_KEY',
|
|
46
46
|
// `-p` is one non-interactive prompt (pi 1.3.0 --help, 2026-10-17).
|
|
47
|
-
probe: {
|
|
47
|
+
probe: {
|
|
48
|
+
args: ['-p', 'Reply with OK'],
|
|
49
|
+
model: { flags: ['--model'], args: (m) => ['--model', m, '-p', 'Reply with OK'] },
|
|
50
|
+
},
|
|
48
51
|
settingsFile: 'settings.json',
|
|
49
52
|
sharedItems: [
|
|
50
53
|
{ path: 'AGENTS.md', mode: 'link' },
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type TraceFetcher } from '../core/egress.ts';
|
|
2
|
+
export declare const NETWORK_HOOK_COMMAND = "sideby network-hook";
|
|
3
|
+
type Env = Record<string, string | undefined>;
|
|
4
|
+
export interface NetworkHookDeps {
|
|
5
|
+
fetcher?: TraceFetcher;
|
|
6
|
+
now?: () => Date;
|
|
7
|
+
print?: string;
|
|
8
|
+
/** Starts the detached refresh; tests replace it. */
|
|
9
|
+
background?: (family: string, env: Env) => void;
|
|
10
|
+
}
|
|
11
|
+
/** Returns the exit code: 0 lets the Host go on, 2 blocks (the reason is written to `err`). */
|
|
12
|
+
export declare function runNetworkHook(argv: readonly string[], env: Env, err: {
|
|
13
|
+
write(s: string): unknown;
|
|
14
|
+
}, deps?: NetworkHookDeps): Promise<number>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Entry for `sideby network-hook <family> <event>` (spec §3.35, ADR-0053). A Host runs it before every prompt and tool
|
|
2
|
+
// call in a session sideby started with Network Guard on, so it imports only Node built-ins and leaf modules: never
|
|
3
|
+
// the Runtime, a Family index or core/accounts.ts. Unlike `handoff-hook` it exists to stop the Host: exit 2 with the
|
|
4
|
+
// reason on stderr blocks the prompt or the tool call; anything it cannot tell blocks too.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { blockMessage, NETWORK_ENV, prefersChinese, refresh, verdict, } from '../core/egress.js';
|
|
7
|
+
export const NETWORK_HOOK_COMMAND = 'sideby network-hook';
|
|
8
|
+
/** The Host events this entry answers, and when each happens; `Refresh` is its own detached refresh. */
|
|
9
|
+
const MOMENTS = { UserPromptSubmit: 'prompt', PreToolUse: 'tool' };
|
|
10
|
+
function startRefresh(family, env) {
|
|
11
|
+
try {
|
|
12
|
+
const entry = process.argv[1];
|
|
13
|
+
if (!entry)
|
|
14
|
+
return;
|
|
15
|
+
const child = spawn(process.execPath, [...process.execArgv, entry, 'network-hook', family, 'Refresh'], {
|
|
16
|
+
detached: true,
|
|
17
|
+
stdio: 'ignore',
|
|
18
|
+
env: env,
|
|
19
|
+
});
|
|
20
|
+
child.on('error', () => { });
|
|
21
|
+
child.unref();
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// the next call checks itself
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Returns the exit code: 0 lets the Host go on, 2 blocks (the reason is written to `err`). */
|
|
28
|
+
export async function runNetworkHook(argv, env, err, deps = {}) {
|
|
29
|
+
const [family = '', event = ''] = argv;
|
|
30
|
+
const url = env[NETWORK_ENV.url];
|
|
31
|
+
const dir = env[NETWORK_ENV.dir];
|
|
32
|
+
const allow = (env[NETWORK_ENV.allow] ?? '').split(',').filter(Boolean);
|
|
33
|
+
// Not a session sideby started with Network Guard (the hook was copied somewhere): nothing to guard.
|
|
34
|
+
if (!url || !dir)
|
|
35
|
+
return 0;
|
|
36
|
+
const common = {
|
|
37
|
+
url,
|
|
38
|
+
env,
|
|
39
|
+
dir,
|
|
40
|
+
...(deps.fetcher ? { fetcher: deps.fetcher } : {}),
|
|
41
|
+
...(deps.now ? { now: deps.now } : {}),
|
|
42
|
+
...(deps.print ? { print: deps.print } : {}),
|
|
43
|
+
};
|
|
44
|
+
if (event === 'Refresh') {
|
|
45
|
+
await refresh(common);
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
const moment = MOMENTS[event];
|
|
49
|
+
if (!moment)
|
|
50
|
+
return 0;
|
|
51
|
+
try {
|
|
52
|
+
const v = await verdict({
|
|
53
|
+
...common,
|
|
54
|
+
allow,
|
|
55
|
+
moment,
|
|
56
|
+
background: () => (deps.background ?? startRefresh)(family, env),
|
|
57
|
+
});
|
|
58
|
+
if (v.status === 'ok')
|
|
59
|
+
return 0;
|
|
60
|
+
err.write(`${blockMessage(v, allow, { ref: env.SIDEBY_LABEL || env.SIDEBY_ACCOUNT, at: moment, zh: prefersChinese(env) })}\n`);
|
|
61
|
+
return 2;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
err.write(`${prefersChinese(env)
|
|
65
|
+
? '已拦截:sideby 的网络检查出错,没能确认网络出口。重新发送试试;一直出错就运行 `sideby network check`。'
|
|
66
|
+
: "Blocked: sideby's network check failed and could not tell this network's exit. Try again; if it keeps failing, run `sideby network check`."}\n`);
|
|
67
|
+
return 2;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -7,6 +7,7 @@ import { type InboundGroup } from '../core/inbound.ts';
|
|
|
7
7
|
import { type LiveSession, type LiveSessionsResult, sessionCopyText } from '../core/live-sessions.ts';
|
|
8
8
|
import { listMessages, type MessageReceipt, sendMessage } from '../core/messages.ts';
|
|
9
9
|
import { type AccountModel } from '../core/model-choice.ts';
|
|
10
|
+
import { type NetworkOverview } from '../core/network.ts';
|
|
10
11
|
import { type RemoteControlGroup } from '../core/remote-control.ts';
|
|
11
12
|
import * as update from '../core/update.ts';
|
|
12
13
|
import type { AccountStatus, DoctorHistory, FamilyInfo, QuotaCheckInfo, Runtime } from '../runtime.ts';
|
|
@@ -256,6 +257,8 @@ export interface PanelState {
|
|
|
256
257
|
quotaChecks?: QuotaCheckInfo[];
|
|
257
258
|
/** Config `panel` (spec §3.29): the theme and language the Panel shows; absent when neither is set. */
|
|
258
259
|
panel?: PanelConfig;
|
|
260
|
+
/** Network Guard (spec §3.35): the setting and the cached result per address; absent without Claude or Codex Accounts. */
|
|
261
|
+
network?: NetworkOverview;
|
|
259
262
|
}
|
|
260
263
|
/**
|
|
261
264
|
* Internal, for tests: replaces parts of the machine the Panel's start-at-login switch uses (platform, launcher,
|