Merge pull request #2697 from ruvnet/feat/meta-proxy-integration

feat(proxy): Cognitum auth and signed Meta-Proxy lifecycle
This commit is contained in:
rUv authored and GitHub committed 2026-07-17 14:31:59 -04:00
commit 7541bf962a
44 files changed
+3891 -8

No files matched your search

@@ -0,0 +1,171 @@
/**
* ADR-306 demand-driven access-token refresh. These tests use an isolated
* state directory and an in-memory keychain double; no real credential store
* or Cognitum endpoint is touched.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const secrets = new Map<string, string>();
const events: string[] = [];
const refreshTokenMock = vi.fn();
const setSecretMock = vi.fn(async (_service: string, account: string, value: string) => {
events.push('persist-refresh-token');
secrets.set(account, value);
});
class MockOAuthError extends Error {
constructor(message: string, public readonly code: 'network' | 'protocol' | 'unexpected_shape') {
super(message);
}
}
vi.mock('../src/auth/security-bridge.js', () => ({
loadSecurityOAuth: async () => ({
refreshToken: refreshTokenMock,
createKeychainAdapter: async () => ({
isAvailable: async () => true,
getSecret: async (_service: string, account: string) => secrets.get(account) ?? null,
setSecret: setSecretMock,
deleteSecret: async () => {},
}),
OAuthError: MockOAuthError,
}),
}));
import { setProfile, getProfile } from '../src/auth/state.js';
import { getSessionToken, setSessionToken, clearSessionToken } from '../src/auth/session.js';
import {
ACCESS_TOKEN_REFRESH_WINDOW_MS,
getValidAccessToken,
NotLoggedInError,
SessionOnlyExpiredError,
} from '../src/auth/client.js';
import { recordConsent } from '../src/funnel/index.js';
import type { CommandContext } from '../src/types.js';
let stateDir: string;
let serial = 0;
function profileName(label: string): string {
serial += 1;
return `${label}-${serial}`;
}
function writeProfile(name: string, keychainRef: string | null): void {
setProfile(name, {
accountId: 'before@example.test',
scopes: ['account.create'],
accessTokenExpiresAt: new Date(Date.now() - 1_000).toISOString(),
keychainRef,
profile: name,
loginMethod: 'pkce',
linkedAt: new Date(Date.now() - 60_000).toISOString(),
});
recordConsent('account', true, 'auth-token-refresh-test');
}
beforeEach(() => {
stateDir = mkdtempSync(join(tmpdir(), 'ruflo-auth-refresh-'));
process.env.RUFLO_STATE_DIR = stateDir;
secrets.clear();
events.length = 0;
refreshTokenMock.mockReset();
setSecretMock.mockClear();
});
afterEach(() => {
delete process.env.RUFLO_STATE_DIR;
rmSync(stateDir, { recursive: true, force: true });
});
describe('getValidAccessToken', () => {
it('returns a cached token without touching the keychain or network', async () => {
const name = profileName('cached');
writeProfile(name, name);
setSessionToken(name, 'cached-access', Date.now() + ACCESS_TOKEN_REFRESH_WINDOW_MS + 10_000);
await expect(getValidAccessToken(name)).resolves.toBe('cached-access');
expect(refreshTokenMock).not.toHaveBeenCalled();
expect(setSecretMock).not.toHaveBeenCalled();
clearSessionToken(name);
});
it('rejects an unknown profile with an actionable login error', async () => {
const name = profileName('missing');
await expect(getValidAccessToken(name)).rejects.toBeInstanceOf(NotLoggedInError);
});
it('fails cleanly when an expired session-only profile cannot refresh', async () => {
const name = profileName('session-only');
writeProfile(name, null);
await expect(getValidAccessToken(name)).rejects.toBeInstanceOf(SessionOnlyExpiredError);
expect(refreshTokenMock).not.toHaveBeenCalled();
});
it('persists a rotated refresh token before publishing the new access token', async () => {
const name = profileName('rotate');
writeProfile(name, name);
secrets.set(name, 'old-refresh');
refreshTokenMock.mockImplementation(async (value: string) => {
expect(value).toBe('old-refresh');
events.push('refresh-response');
return {
access_token: 'new-access',
refresh_token: 'new-refresh',
token_type: 'Bearer',
expires_in: 900,
account_email: 'after@example.test',
};
});
await expect(getValidAccessToken(name)).resolves.toBe('new-access');
expect(events).toEqual(['refresh-response', 'persist-refresh-token']);
expect(secrets.get(name)).toBe('new-refresh');
expect(getSessionToken(name)).toBe('new-access');
expect(getProfile(name)?.accountId).toBe('after@example.test');
clearSessionToken(name);
});
it('does not cache the access token when rotated-token persistence fails', async () => {
const name = profileName('rotation-failure');
writeProfile(name, name);
secrets.set(name, 'old-refresh');
refreshTokenMock.mockResolvedValue({
access_token: 'must-not-escape',
refresh_token: 'new-refresh',
token_type: 'Bearer',
expires_in: 900,
});
setSecretMock.mockRejectedValueOnce(new Error('keychain write failed'));
await expect(getValidAccessToken(name)).rejects.toThrow('keychain write failed');
expect(getSessionToken(name)).toBeNull();
});
});
describe('auth status --check consumer', () => {
it('uses the demand-driven accessor without exposing the token', async () => {
const name = profileName('status-check');
writeProfile(name, null);
setSessionToken(name, 'never-return-this-token', Date.now() + ACCESS_TOKEN_REFRESH_WINDOW_MS + 10_000);
const { authCommand } = await import('../src/commands/auth.js');
const status = authCommand.subcommands?.find((command) => command.name === 'status');
if (!status?.action) throw new Error('auth status subcommand not found');
const ctx: CommandContext = {
args: [],
flags: { _: [], profile: name, check: true, json: true },
cwd: process.cwd(),
interactive: false,
};
const result = await status.action(ctx);
const profiles = (result?.data as { profiles?: Array<Record<string, unknown>> })?.profiles ?? [];
expect(profiles[0]?.credentialStatus).toBe('valid');
expect(JSON.stringify(result?.data)).not.toContain('never-return-this-token');
clearSessionToken(name);
});
});
@@ -0,0 +1,128 @@
/**
* doctor's checkProxyProcess (ADR-307) — the /status-endpoint wiring added
* after finding the original implementation only did PID liveness (its own
* doc comment claimed it hit /status but never actually did). The real
* response shape (`{version, data_plane, bind, sponsored_available,
* proxy_token_valid}`) was confirmed against the real v0.1.0 binary; this
* file mocks `fetch` to cover the comparison/parsing logic without spawning
* a real process per test.
*
* Result shape: `doctorCommand.action(ctx)` -> `{success, data: {results: HealthCheck[]}}`.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { doctorCommand } from '../src/commands/doctor.js';
let stateDir: string;
let savedEnv: NodeJS.ProcessEnv;
let fetchSpy: ReturnType<typeof vi.spyOn> | null = null;
beforeEach(() => {
stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'doctor-proxy-status-test-'));
savedEnv = { ...process.env };
process.env.RUFLO_STATE_DIR = stateDir;
});
afterEach(() => {
process.env = savedEnv;
fs.rmSync(stateDir, { recursive: true, force: true });
fetchSpy?.mockRestore();
fetchSpy = null;
});
function ctxFor(component: string) {
return {
flags: { component },
args: [],
config: {} as Record<string, unknown>,
} as unknown as Parameters<NonNullable<typeof doctorCommand.action>>[0];
}
async function findProxyProcessCheck() {
const result = await doctorCommand.action!(ctxFor('proxy'));
const checks = (result?.data as { results?: Array<{ name: string; status: string; message: string; fix?: string }> })?.results ?? [];
const check = checks.find((c) => c.name.startsWith('Meta LLM Proxy process'));
if (!check) throw new Error('proxy process check not found in results');
return check;
}
/** A PID guaranteed to pass process.kill(pid, 0) — this test's own process. */
function writeLivePidFile() {
fs.writeFileSync(path.join(stateDir, 'proxy.pid'), String(process.pid));
}
describe('checkProxyProcess — /status wiring', () => {
it('reports data_plane from a real-shaped /status response', async () => {
writeLivePidFile();
fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(
JSON.stringify({ version: '0.1.0', data_plane: 'passthrough:anthropic', bind: '127.0.0.1:11435', sponsored_available: false, proxy_token_valid: true }),
{ status: 200 },
),
);
fs.writeFileSync(path.join(stateDir, 'proxy-token'), 'fake-token');
const check = await findProxyProcessCheck();
expect(check.status).toBe('pass');
expect(check.message).toContain('data plane: passthrough:anthropic');
});
it('warns when the running process reports a different version than the install manifest', async () => {
writeLivePidFile();
fs.writeFileSync(path.join(stateDir, 'proxy-token'), 'fake-token');
fs.mkdirSync(path.join(stateDir, 'proxy'), { recursive: true });
fs.writeFileSync(
path.join(stateDir, 'proxy', 'install-manifest.json'),
JSON.stringify({ version: '9.9.9', sha256: 'x', verifiedAt: 'x', pubkeyFingerprint: 'x' }),
);
fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(JSON.stringify({ version: '0.1.0', data_plane: 'local' }), { status: 200 }),
);
const check = await findProxyProcessCheck();
expect(check.status).toBe('warn');
expect(check.message).toContain('reports v0.1.0');
expect(check.message).toContain('installed binary is v9.9.9');
});
it('passes on a live process with no proxy-token, skipping the /status call', async () => {
writeLivePidFile();
fetchSpy = vi.spyOn(globalThis, 'fetch');
const check = await findProxyProcessCheck();
expect(check.status).toBe('pass');
expect(check.message).toContain('no proxy-token to query /status');
expect(fetchSpy).not.toHaveBeenCalled();
});
it('still passes (not fails) when /status is unreachable — PID liveness already succeeded', async () => {
writeLivePidFile();
fs.writeFileSync(path.join(stateDir, 'proxy-token'), 'fake-token');
fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('ECONNREFUSED'));
const check = await findProxyProcessCheck();
expect(check.status).toBe('pass');
expect(check.message).toContain('/status unreachable');
});
it('warns (not fails) on a non-2xx /status response', async () => {
writeLivePidFile();
fs.writeFileSync(path.join(stateDir, 'proxy-token'), 'fake-token');
fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('', { status: 500 }));
const check = await findProxyProcessCheck();
expect(check.status).toBe('warn');
expect(check.message).toContain('HTTP 500');
});
it('never spawns the binary or calls fetch when nothing is running', async () => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
const check = await findProxyProcessCheck();
expect(check.status).toBe('warn');
expect(check.message).toContain('not running');
expect(fetchSpy).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,5 @@
eb98f846288c66e38d7a0bbbc62d02fe53907ad80bcfe900f2d210af17c466a3 meta-proxy-0.1.0-aarch64-apple-darwin.tar.gz
e7ed195320130fee2822d1bc36d18a2c06a8c25adf2f601103dbe3dc7e6b741a meta-proxy-0.1.0-aarch64-unknown-linux-gnu.tar.gz
3b7bb33ca349921c92cee5440e99dfcb03fdba543338f5d45f2c50536610b4a5 meta-proxy-0.1.0-x86_64-apple-darwin.tar.gz
52761dde32a4c32b1725ac01a5409694848f4d1bd7bece212b3a5f0743e5b95d meta-proxy-0.1.0-x86_64-pc-windows-msvc.zip
830b0d47cd9272119039f94433f9b3c60a3b336020101120f69278fef5553682 meta-proxy-0.1.0-x86_64-unknown-linux-gnu.tar.gz
@@ -0,0 +1 @@
iWHkR82XIpESZ3gnfJ0J6VHJzb6Ju9ZsvhR1QfGqrImWJNIJUaaEvQEpenPccbv1fAwCxtg9e2qhT3DRAb9IAw==
@@ -0,0 +1,111 @@
/**
* `proxy config --cloud/--local-only` (ADR-304). The `default_data_plane`
* TOML values written here ("local"/"cloud") were confirmed against
* meta-proxy's actual `DataPlane` enum (`src/config.rs`,
* `#[serde(rename_all = "snake_case")]`) both by reading the source directly
* and by a live behavioral test against the real v0.1.0 binary.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import type { CommandContext } from '../src/types.js';
let stateDir: string;
let savedEnv: NodeJS.ProcessEnv;
beforeEach(() => {
stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'proxy-config-cmd-test-'));
savedEnv = { ...process.env };
process.env.RUFLO_STATE_DIR = stateDir;
});
afterEach(() => {
process.env = savedEnv;
fs.rmSync(stateDir, { recursive: true, force: true });
});
function ctxWithFlags(flags: Record<string, unknown>): CommandContext {
return { args: [], flags: { _: [], ...flags }, cwd: process.cwd(), interactive: false };
}
async function getConfigSub() {
const { proxyCommand } = await import('../src/commands/proxy.js');
const sub = proxyCommand.subcommands?.find((c) => c.name === 'config');
if (!sub) throw new Error('config subcommand not found');
return sub;
}
describe('proxy config', () => {
it('with no flags, reports the default plane (passthrough) when no config file exists', async () => {
const configSub = await getConfigSub();
const result = await configSub.action!(ctxWithFlags({}));
expect(result?.success).toBe(true);
expect((result?.data as { plane?: string })?.plane).toBe('passthrough');
});
it('rejects --cloud and --local-only together', async () => {
const configSub = await getConfigSub();
const result = await configSub.action!(ctxWithFlags({ cloud: true, localOnly: true }));
expect(result?.success).toBe(false);
});
it('--cloud without --yes shows the disclosure and writes nothing', async () => {
const configSub = await getConfigSub();
const result = await configSub.action!(ctxWithFlags({ cloud: true }));
expect(result?.success).toBe(true);
expect((result?.data as { confirmed?: boolean })?.confirmed).toBe(false);
expect(fs.existsSync(path.join(stateDir, 'proxy-config.toml'))).toBe(false);
const { hasConsent } = await import('../src/funnel/index.js');
expect(hasConsent('cloud-routing')).toBe(false);
});
it('--cloud --yes writes default_data_plane = "cloud" and grants consent', async () => {
const configSub = await getConfigSub();
const result = await configSub.action!(ctxWithFlags({ cloud: true, yes: true }));
expect(result?.success).toBe(true);
const raw = fs.readFileSync(path.join(stateDir, 'proxy-config.toml'), 'utf-8');
expect(raw).toContain('default_data_plane = "cloud"');
const { hasConsent } = await import('../src/funnel/index.js');
expect(hasConsent('cloud-routing')).toBe(true);
});
it('--local-only writes default_data_plane = "local" and revokes consent', async () => {
const configSub = await getConfigSub();
await configSub.action!(ctxWithFlags({ cloud: true, yes: true }));
await configSub.action!(ctxWithFlags({ localOnly: true }));
const raw = fs.readFileSync(path.join(stateDir, 'proxy-config.toml'), 'utf-8');
expect(raw).toContain('default_data_plane = "local"');
const { hasConsent } = await import('../src/funnel/index.js');
expect(hasConsent('cloud-routing')).toBe(false);
});
it('revoking via --local-only means a later --cloud (no --yes) re-shows the disclosure', async () => {
const configSub = await getConfigSub();
await configSub.action!(ctxWithFlags({ cloud: true, yes: true }));
await configSub.action!(ctxWithFlags({ localOnly: true }));
const result = await configSub.action!(ctxWithFlags({ cloud: true }));
expect((result?.data as { confirmed?: boolean })?.confirmed).toBe(false);
});
it('preserves unrelated lines already in proxy-config.toml (read-modify-write, not overwrite)', async () => {
fs.writeFileSync(
path.join(stateDir, 'proxy-config.toml'),
'bind = "127.0.0.1:11435"\ndefault_data_plane = "local"\nsponsored_daily_cap_usd = 5.0\n',
);
const configSub = await getConfigSub();
await configSub.action!(ctxWithFlags({ cloud: true, yes: true }));
const raw = fs.readFileSync(path.join(stateDir, 'proxy-config.toml'), 'utf-8');
expect(raw).toContain('bind = "127.0.0.1:11435"');
expect(raw).toContain('sponsored_daily_cap_usd = 5.0');
expect(raw).toContain('default_data_plane = "cloud"');
});
});
@@ -0,0 +1,80 @@
/**
* `proxy install`'s Command.action logic — isolated via RUFLO_STATE_DIR,
* install itself mocked out (real downloads belong in manual/E2E testing,
* already verified against the real meta-proxy v0.1.0 release).
*
* Regression coverage for a real bug found during E2E testing: the
* proxy-install consent grant must never happen before required flags are
* validated. The original implementation checked consent (and, on --yes,
* recorded it) BEFORE checking for --release — so `proxy install --yes`
* with no --release recorded consent even though the command then failed,
* which meant a LATER, parameter-complete `proxy install --release x.y.z`
* silently skipped the disclosure the user should have seen once with real
* information. Fixed by validating --release first.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import type { CommandContext } from '../src/types.js';
let stateDir: string;
let savedEnv: NodeJS.ProcessEnv;
beforeEach(() => {
stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'proxy-install-cmd-test-'));
savedEnv = { ...process.env };
process.env.RUFLO_STATE_DIR = stateDir;
vi.resetModules();
});
afterEach(() => {
process.env = savedEnv;
fs.rmSync(stateDir, { recursive: true, force: true });
vi.restoreAllMocks();
});
function ctxWithFlags(flags: Record<string, unknown>): CommandContext {
return { args: [], flags: { _: [], ...flags }, cwd: process.cwd(), interactive: false };
}
async function getInstallSub() {
const { proxyLifecycleSubcommands } = await import('../src/commands/proxy-lifecycle.js');
const sub = proxyLifecycleSubcommands.find((c) => c.name === 'install');
if (!sub) throw new Error('install subcommand not found');
return sub;
}
describe('proxy install — parameter validation happens before any consent side-effect', () => {
it('--yes with no --release fails WITHOUT recording proxy-install consent', async () => {
const installSub = await getInstallSub();
const result = await installSub.action!(ctxWithFlags({ yes: true }));
expect(result?.success).toBe(false);
const { hasConsent } = await import('../src/funnel/index.js');
expect(hasConsent('proxy-install')).toBe(false);
});
it('a later, parameter-complete call still shows the disclosure (consent was never silently granted)', async () => {
const installSub = await getInstallSub();
// First call: --yes but no --release — must fail, must not grant consent (asserted above).
await installSub.action!(ctxWithFlags({ yes: true }));
// Second call: --release present, but NO --yes this time — must show the
// disclosure and refuse (not silently proceed as if already consented).
const second = await installSub.action!(ctxWithFlags({ release: '0.1.0' }));
expect(second?.success).toBe(true);
expect((second?.data as { confirmed?: boolean } | undefined)?.confirmed).toBe(false);
});
it('missing --release is rejected even when consent already exists from a prior install', async () => {
const { recordConsent } = await import('../src/funnel/consent.js');
recordConsent('proxy-install', true, 'test-seed');
const installSub = await getInstallSub();
const result = await installSub.action!(ctxWithFlags({ yes: true }));
expect(result?.success).toBe(false);
});
});
@@ -0,0 +1,117 @@
/**
* proxy/lifecycle.ts — PID-file/status logic, isolated via RUFLO_STATE_DIR.
* The actual process spawn/stop/log-redirect round trip against the real
* meta-proxy v0.1.0 binary was verified manually during implementation
* (start -> status -> real log content -> stop; double-start correctly
* rejected; a stale PID file correctly recovered from) — not re-asserted
* here since spawning a real 5MB binary per test run is not something CI
* should depend on. This file covers the deterministic logic around it.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
let stateDir: string;
let savedEnv: NodeJS.ProcessEnv;
beforeEach(() => {
stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'proxy-lifecycle-test-'));
savedEnv = { ...process.env };
process.env.RUFLO_STATE_DIR = stateDir;
});
afterEach(() => {
process.env = savedEnv;
fs.rmSync(stateDir, { recursive: true, force: true });
});
describe('getProxyStatus', () => {
it('reports not-installed and not-running on a fresh state dir', async () => {
const { getProxyStatus } = await import('../src/proxy/lifecycle.js');
expect(getProxyStatus()).toEqual({ installed: false, running: false, pid: null, stalePidFile: false });
});
it('reports installed once a binary file exists at the expected path', async () => {
const { proxyBinaryPath } = await import('../src/proxy/paths.js');
fs.mkdirSync(path.dirname(proxyBinaryPath()), { recursive: true });
fs.writeFileSync(proxyBinaryPath(), 'not a real binary, just a marker file');
const { getProxyStatus } = await import('../src/proxy/lifecycle.js');
expect(getProxyStatus().installed).toBe(true);
});
it('reports a stale PID file as not-running (using a PID from a dead process)', async () => {
const { proxyPidFilePath } = await import('../src/proxy/paths.js');
// A PID essentially guaranteed not to be alive on any real system.
fs.writeFileSync(proxyPidFilePath(), '999999999');
const { getProxyStatus } = await import('../src/proxy/lifecycle.js');
const status = getProxyStatus();
expect(status.running).toBe(false);
expect(status.pid).toBeNull();
expect(status.stalePidFile).toBe(true);
});
it('reports running when the PID file points at the current process (a real, live PID)', async () => {
const { proxyPidFilePath } = await import('../src/proxy/paths.js');
fs.writeFileSync(proxyPidFilePath(), String(process.pid));
const { getProxyStatus } = await import('../src/proxy/lifecycle.js');
const status = getProxyStatus();
expect(status.running).toBe(true);
expect(status.pid).toBe(process.pid);
});
it('treats a malformed PID file as a stale PID file, not a crash', async () => {
const { proxyPidFilePath } = await import('../src/proxy/paths.js');
fs.writeFileSync(proxyPidFilePath(), 'not-a-number');
const { getProxyStatus } = await import('../src/proxy/lifecycle.js');
const status = getProxyStatus();
expect(status.running).toBe(false);
expect(status.stalePidFile).toBe(true);
});
});
describe('stopProxy', () => {
it('is a harmless no-op when nothing is running', async () => {
const { stopProxy } = await import('../src/proxy/lifecycle.js');
const result = await stopProxy();
expect(result).toEqual({ wasRunning: false, pid: null });
});
});
describe('readProxyLogTail', () => {
it('returns an empty string when no log file exists yet', async () => {
const { readProxyLogTail } = await import('../src/proxy/lifecycle.js');
expect(readProxyLogTail()).toBe('');
});
it('returns the full content when under the tail-size bound', async () => {
const { proxyLogFilePath } = await import('../src/proxy/paths.js');
fs.writeFileSync(proxyLogFilePath(), 'line one\nline two\n');
const { readProxyLogTail } = await import('../src/proxy/lifecycle.js');
expect(readProxyLogTail()).toBe('line one\nline two\n');
});
it('bounds reads to the last N bytes on a large log file', async () => {
const { proxyLogFilePath } = await import('../src/proxy/paths.js');
const big = 'x'.repeat(200) + 'TAIL-MARKER';
fs.writeFileSync(proxyLogFilePath(), big);
const { readProxyLogTail } = await import('../src/proxy/lifecycle.js');
const tail = readProxyLogTail(50);
expect(tail.length).toBe(50);
expect(tail.endsWith('TAIL-MARKER')).toBe(true);
});
});
describe('watchProxyLog', () => {
it('throws a clear error when no log file exists yet, rather than a raw ENOENT', async () => {
const { watchProxyLog } = await import('../src/proxy/lifecycle.js');
expect(() => watchProxyLog(() => {})).toThrow(/no log file yet/);
});
});
@@ -0,0 +1,37 @@
/**
* isLoopbackBind — the exact bug class meta-proxy's own Rust
* `is_loopback_bind` was written to fix (a naive `startsWith('127.0.0.1')`
* check misclassifies `[::1]` as network-exposed). This TS port must not
* repeat that mistake.
*/
import { describe, it, expect } from 'vitest';
import { isLoopbackBind } from '../src/proxy/paths.js';
describe('isLoopbackBind', () => {
it('recognizes the whole IPv4 127.0.0.0/8 block, not just .0.0.1', () => {
expect(isLoopbackBind('127.0.0.1:11435')).toBe(true);
expect(isLoopbackBind('127.0.0.5:11435')).toBe(true);
expect(isLoopbackBind('127.255.255.255:11435')).toBe(true);
});
it('recognizes the localhost hostname, case-insensitively', () => {
expect(isLoopbackBind('localhost:11435')).toBe(true);
expect(isLoopbackBind('LOCALHOST:11435')).toBe(true);
});
it('recognizes IPv6 loopback — the exact case a naive prefix check misclassifies', () => {
expect(isLoopbackBind('[::1]:11435')).toBe(true);
});
it('recognizes IPv4-mapped IPv6 loopback', () => {
expect(isLoopbackBind('[::ffff:127.0.0.1]:11435')).toBe(true);
});
it('treats all-interfaces and routable binds as NOT loopback', () => {
expect(isLoopbackBind('0.0.0.0:11435')).toBe(false);
expect(isLoopbackBind('[::]:11435')).toBe(false);
expect(isLoopbackBind('192.168.1.10:11435')).toBe(false);
expect(isLoopbackBind('example.com:11435')).toBe(false);
});
});
@@ -0,0 +1,65 @@
/**
* proxy/release.ts — pure, offline tests for target-triple detection and
* asset-filename construction. Matches the 5 triples and the exact
* `meta-proxy-<version>-<triple>.<ext>` naming confirmed against the real
* v0.1.0 GitHub release during planning.
*/
import { describe, it, expect } from 'vitest';
import {
detectTargetTriple,
releaseAssetFilename,
releaseArchiveExtension,
UnsupportedPlatformError,
TARGET_TRIPLES,
} from '../src/proxy/release.js';
describe('detectTargetTriple', () => {
it('maps darwin/arm64 to aarch64-apple-darwin', () => {
expect(detectTargetTriple('darwin', 'arm64')).toBe('aarch64-apple-darwin');
});
it('maps darwin/x64 to x86_64-apple-darwin', () => {
expect(detectTargetTriple('darwin', 'x64')).toBe('x86_64-apple-darwin');
});
it('maps linux/arm64 to aarch64-unknown-linux-gnu', () => {
expect(detectTargetTriple('linux', 'arm64')).toBe('aarch64-unknown-linux-gnu');
});
it('maps linux/x64 to x86_64-unknown-linux-gnu', () => {
expect(detectTargetTriple('linux', 'x64')).toBe('x86_64-unknown-linux-gnu');
});
it('maps win32/x64 to x86_64-pc-windows-msvc', () => {
expect(detectTargetTriple('win32', 'x64')).toBe('x86_64-pc-windows-msvc');
});
it('throws UnsupportedPlatformError for win32/arm64 — meta-proxy publishes no such triple', () => {
expect(() => detectTargetTriple('win32', 'arm64')).toThrow(UnsupportedPlatformError);
});
it('throws UnsupportedPlatformError for an unrecognized platform', () => {
expect(() => detectTargetTriple('freebsd', 'x64')).toThrow(UnsupportedPlatformError);
});
});
describe('releaseArchiveExtension', () => {
it('is zip for the windows triple', () => {
expect(releaseArchiveExtension('x86_64-pc-windows-msvc')).toBe('zip');
});
it('is tar.gz for every other triple', () => {
for (const triple of TARGET_TRIPLES) {
if (triple === 'x86_64-pc-windows-msvc') continue;
expect(releaseArchiveExtension(triple)).toBe('tar.gz');
}
});
});
describe('releaseAssetFilename', () => {
it('matches the exact real asset name confirmed against v0.1.0', () => {
expect(releaseAssetFilename('0.1.0', 'x86_64-pc-windows-msvc')).toBe('meta-proxy-0.1.0-x86_64-pc-windows-msvc.zip');
expect(releaseAssetFilename('0.1.0', 'aarch64-apple-darwin')).toBe('meta-proxy-0.1.0-aarch64-apple-darwin.tar.gz');
});
});
@@ -0,0 +1,46 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setProfile } from '../src/auth/state.js';
import { setSessionToken, clearSessionToken } from '../src/auth/session.js';
import { recordConsent } from '../src/funnel/index.js';
import { refreshInjectedToken, removeInjectedToken } from '../src/proxy/token-bridge.js';
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'ruflo-token-bridge-'));
process.env.RUFLO_STATE_DIR = dir;
});
afterEach(() => {
clearSessionToken('default');
delete process.env.RUFLO_STATE_DIR;
rmSync(dir, { recursive: true, force: true });
});
describe('proxy injected-token bridge', () => {
it('atomically writes an access-token-only envelope and config path', async () => {
const expiresAt = Date.now() + 10 * 60_000;
setProfile('default', {
accountId: 'test@example.com', scopes: ['account.create'],
accessTokenExpiresAt: new Date(expiresAt).toISOString(), keychainRef: null,
profile: 'default', loginMethod: 'pkce', linkedAt: new Date().toISOString(),
});
recordConsent('account', true, 'test');
setSessionToken('default', 'access-only-secret', expiresAt);
await expect(refreshInjectedToken()).resolves.toBe(true);
const envelope = JSON.parse(readFileSync(join(dir, 'proxy-injected-token.json'), 'utf8'));
expect(envelope).toEqual({ schemaVersion: 1, accessToken: 'access-only-secret', expiresAt: new Date(expiresAt).toISOString() });
expect(readFileSync(join(dir, 'proxy-config.toml'), 'utf8')).toContain('ruflo_injected_token_path');
expect(readFileSync(join(dir, 'proxy-config.toml'), 'utf8')).not.toContain('access-only-secret');
if (process.platform !== 'win32') expect(statSync(join(dir, 'proxy-injected-token.json')).mode & 0o077).toBe(0);
});
it('removes the handoff when no authenticated profile is available', async () => {
removeInjectedToken();
await expect(refreshInjectedToken()).resolves.toBe(false);
});
});
@@ -0,0 +1,122 @@
/**
* proxy/verify.ts tests. `real-signature.test.ts`-style fixtures
* (__tests__/fixtures/proxy-release/) are the ACTUAL SHA256SUMS +
* SHA256SUMS.sig downloaded from meta-proxy's real v0.1.0 GitHub release
* (2026-07-16) — this is the same signature-verification result confirmed
* manually during planning (crypto.verify -> true against the pinned key),
* now pinned as a regression test rather than a one-off manual check.
*/
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import {
verifySha256SumsSignature,
parseSha256Sums,
sha256Hex,
verifyRelease,
ReleaseVerificationError,
PROXY_RELEASE_PUBKEY_PEM,
} from '../src/proxy/verify.js';
const FIXTURES_DIR = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'proxy-release');
const REAL_SUMS = readFileSync(join(FIXTURES_DIR, 'SHA256SUMS'));
const REAL_SIG = readFileSync(join(FIXTURES_DIR, 'SHA256SUMS.sig'), 'utf-8').trim();
describe('verifySha256SumsSignature — against a real meta-proxy v0.1.0 release', () => {
it('verifies the real SHA256SUMS.sig against the pinned public key', () => {
expect(verifySha256SumsSignature(REAL_SUMS, REAL_SIG)).toBe(true);
});
it('rejects a tampered SHA256SUMS (one byte flipped)', () => {
const tampered = Buffer.from(REAL_SUMS);
tampered[0] = tampered[0] ^ 0xff;
expect(verifySha256SumsSignature(tampered, REAL_SIG)).toBe(false);
});
it('rejects a corrupted signature', () => {
const badSig = Buffer.from(REAL_SIG, 'base64');
badSig[0] = badSig[0] ^ 0xff;
expect(verifySha256SumsSignature(REAL_SUMS, badSig.toString('base64'))).toBe(false);
});
it('rejects against the wrong public key', () => {
// A different, genuinely-generated Ed25519 SPKI key — not meta-proxy's.
const wrongKey = `-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAXpS1dWHqkPwH+HIpXTVujYsV+jm385xxiKSZfGdEfkY=
-----END PUBLIC KEY-----`;
expect(verifySha256SumsSignature(REAL_SUMS, REAL_SIG, wrongKey)).toBe(false);
});
});
describe('parseSha256Sums', () => {
it('parses every real release asset line', () => {
const parsed = parseSha256Sums(REAL_SUMS.toString('utf-8'));
expect(Object.keys(parsed)).toHaveLength(5);
expect(parsed['meta-proxy-0.1.0-x86_64-pc-windows-msvc.zip']).toBe(
'52761dde32a4c32b1725ac01a5409694848f4d1bd7bece212b3a5f0743e5b95d',
);
});
it('ignores blank lines and malformed entries', () => {
const parsed = parseSha256Sums('\n\nnot a valid line\nabc123 short-hash\n');
expect(Object.keys(parsed)).toHaveLength(0);
});
});
describe('verifyRelease — full pipeline', () => {
it('succeeds when the signature is valid and the asset hash matches', () => {
const assetBytes = Buffer.from('a fake but internally-consistent asset');
const filename = 'fake-asset.tar.gz';
const hash = sha256Hex(assetBytes);
const sumsWithFake = Buffer.concat([REAL_SUMS, Buffer.from(`${hash} ${filename}\n`)]);
// Re-sign isn't possible without the private key, so this test instead
// verifies the two INDEPENDENT failure-free branches together using the
// real signature (over the real, unmodified REAL_SUMS) for the
// signature check, and a synthetic sums blob (whose signature we do NOT
// check here) purely to exercise parseSha256Sums + the hash-match branch.
const parsed = parseSha256Sums(sumsWithFake.toString('utf-8'));
expect(parsed[filename]).toBe(hash);
});
it('throws ReleaseVerificationError when the signature is invalid', () => {
const tampered = Buffer.from(REAL_SUMS);
tampered[0] = tampered[0] ^ 0xff;
expect(() =>
verifyRelease({
sumsBytes: tampered,
sigBase64: REAL_SIG,
assetBytes: Buffer.from('irrelevant'),
assetFilename: 'meta-proxy-0.1.0-x86_64-pc-windows-msvc.zip',
}),
).toThrow(ReleaseVerificationError);
});
it('throws when SHA256SUMS has no entry for the requested asset', () => {
expect(() =>
verifyRelease({
sumsBytes: REAL_SUMS,
sigBase64: REAL_SIG,
assetBytes: Buffer.from('irrelevant'),
assetFilename: 'meta-proxy-0.1.0-does-not-exist.tar.gz',
}),
).toThrow(/no entry/);
});
it('throws when the asset bytes do not match the recorded checksum', () => {
expect(() =>
verifyRelease({
sumsBytes: REAL_SUMS,
sigBase64: REAL_SIG,
assetBytes: Buffer.from('these are definitely not the real 2.3MB windows zip bytes'),
assetFilename: 'meta-proxy-0.1.0-x86_64-pc-windows-msvc.zip',
}),
).toThrow(/sha256 mismatch/);
});
it('is exported for install.ts to pin', () => {
expect(PROXY_RELEASE_PUBKEY_PEM).toContain('BEGIN PUBLIC KEY');
});
});
+277
View File
@@ -0,0 +1,277 @@
/**
* `ruflo auth login` flow orchestration (ADR-306) — composes
* `@claude-flow/security`'s ported OAuth primitives (loopback PKCE, OOB
* manual-paste, refresh) the same way meta-proxy's `oauth/login.rs`
* orchestrates its own Rust primitives. See security-bridge.ts for why the
* package is loaded lazily, and oauth/client.ts (in @claude-flow/security)
* for why this targets the live `auth.cognitum.one` surface rather than
* ADR-308's unconfirmed `/v1/auth/*` spec.
*
* @module auth/client
*/
import * as readline from 'node:readline/promises';
import { existsSync } from 'node:fs';
import { loadSecurityOAuth, type OAuthTokenResponse } from './security-bridge.js';
import { KEYCHAIN_SERVICE } from './constants.js';
import { getProfile, setProfile } from './state.js';
import { getSessionToken, setSessionToken } from './session.js';
import { hasConsent } from '../funnel/index.js';
import { domainForScope } from './scopes.js';
/** Refresh before there is less than one minute left on the access token. */
export const ACCESS_TOKEN_REFRESH_WINDOW_MS = 60_000;
export interface LoginResult {
tokens: OAuthTokenResponse;
method: 'pkce' | 'device' | 'token-stdin';
}
/**
* Best-effort headlessness signal — a false negative just means the browser
* flow is attempted and a real browser opens fine anyway; a false positive
* means the user falls back to the manual OOB flow, which always works
* regardless. Mirrors meta-proxy's `login.rs::is_probably_headless()`.
*/
export function isProbablyHeadless(): boolean {
return Boolean(
process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.CONTAINER || existsDockerEnv(),
);
}
function existsDockerEnv(): boolean {
try {
return existsSync('/.dockerenv');
} catch {
return false;
}
}
/**
* Validates the OAuth callback params against the request that started the
* flow — the CSRF-critical step, extracted so it's independently testable.
* Order matters: an explicit `error` (user denied) and a missing code are
* reported as their own reasons; a missing or mismatched `state` is always
* a state-mismatch, even when a code is present.
*/
export function validateCallback(
error: string | null,
code: string | null,
returnedState: string | null,
expectedState: string,
): { ok: true; code: string } | { ok: false; reason: 'denied' | 'state-mismatch'; detail?: string } {
if (error) return { ok: false, reason: 'denied', detail: error };
if (!code) return { ok: false, reason: 'denied', detail: 'no authorization code received' };
if (!returnedState || returnedState !== expectedState) return { ok: false, reason: 'state-mismatch' };
return { ok: true, code };
}
export class LoginCancelledError extends Error {
constructor() {
super('login cancelled: no code was entered');
this.name = 'LoginCancelledError';
}
}
export class LoginDeniedError extends Error {
constructor(detail: string) {
super(`authorization was denied or failed: ${detail}`);
this.name = 'LoginDeniedError';
}
}
export class StateMismatchError extends Error {
constructor() {
super('state mismatch — the OAuth callback did not match the request this CLI sent');
this.name = 'StateMismatchError';
}
}
export class NotLoggedInError extends Error {
constructor(profile: string) {
super(`not logged in for profile "${profile}" — run: ruflo auth login --profile ${profile}`);
this.name = 'NotLoggedInError';
}
}
export class SessionOnlyExpiredError extends Error {
constructor(profile: string) {
super(
`profile "${profile}" has no persisted refresh token and its in-memory access token is ` +
`absent or expiring — run: ruflo auth login --profile ${profile}`,
);
this.name = 'SessionOnlyExpiredError';
}
}
export class ScopeConsentMismatchError extends Error {
constructor(profile: string, scopes: string[]) {
super(
`profile "${profile}" has scope(s) without matching local consent: ${scopes.join(', ')} — ` +
'authenticated capability denied',
);
this.name = 'ScopeConsentMismatchError';
}
}
/** Browser-based loopback PKCE login — the ADR-306 default for an interactive desktop. */
export async function browserLogin(print: (line: string) => void): Promise<LoginResult> {
const sec = await loadSecurityOAuth();
const server = await sec.CallbackServer.bind();
const pkce = sec.generatePkce();
const url = sec.authorizeUrl(server.redirectUri, pkce.state, pkce.codeChallenge);
print('Opening your browser to sign in to Cognitum...');
print(`If it doesn't open automatically, visit:\n\n ${url}\n`);
await sec.openBrowser(url).catch(() => {}); // best-effort — the URL above is always the fallback
print('Waiting for you to finish signing in...');
const result = await server.awaitCallback();
const validated = validateCallback(result.error, result.code, result.state, pkce.state);
if (!validated.ok) {
if (validated.reason === 'state-mismatch') throw new StateMismatchError();
throw new LoginDeniedError(validated.detail ?? 'unknown');
}
const tokens = await sec.exchangeCode(validated.code, pkce.codeVerifier, server.redirectUri);
return { tokens, method: 'pkce' };
}
/** Headless fallback: prints the authorize URL with the OOB redirect, prompts for the pasted code. */
export async function manualLogin(
print: (line: string) => void,
input: NodeJS.ReadableStream = process.stdin,
): Promise<LoginResult> {
const sec = await loadSecurityOAuth();
print('Browser-based callback unavailable (SSH/container detected, or --no-browser).\n');
const pkce = sec.generatePkce();
const url = sec.authorizeUrl(sec.OOB_REDIRECT_URI, pkce.state, pkce.codeChallenge);
print(`Open this URL in a browser and authorize:\n\n ${url}\n`);
// `rl.question()` resolves on a newline-terminated 'line' event — if `input`
// ends without ever emitting one (e.g. stdin closed early, or piped input
// with no trailing newline), it hangs forever rather than treating EOF as
// a cancellation. Race it against the interface's own 'close' event so an
// early EOF resolves to "" (-> LoginCancelledError below) instead of hanging.
const rl = readline.createInterface({ input, terminal: false });
let code: string;
try {
const closed = new Promise<string>((resolve) => rl.once('close', () => resolve('')));
code = (await Promise.race([rl.question('Paste the code shown after authorizing: '), closed])).trim();
} finally {
rl.close();
}
if (!code) throw new LoginCancelledError();
const tokens = await sec.exchangeManualCode(code, pkce.codeVerifier);
return { tokens, method: 'device' };
}
/**
* `--token-stdin`: reads one JSON object from stdin,
* `{access_token, refresh_token?, expires_in, scope}`. Wire format is not
* specified by ADR-306 — defined here as typed JSON rather than a bare
* token string, so scope/expiry are explicit rather than inferred.
*/
export async function tokenStdinLogin(input: NodeJS.ReadableStream = process.stdin): Promise<LoginResult> {
const chunks: Buffer[] = [];
for await (const chunk of input) chunks.push(chunk as Buffer);
const raw = Buffer.concat(chunks).toString('utf-8').trim();
if (!raw) throw new Error('--token-stdin: no input received on stdin');
let parsed: { access_token?: string; refresh_token?: string; expires_in?: number; scope?: string };
try {
parsed = JSON.parse(raw);
} catch {
throw new Error(
'--token-stdin expects a single JSON object: {"access_token","refresh_token"?,"expires_in","scope"}',
);
}
if (!parsed.access_token) throw new Error('--token-stdin: JSON is missing required field "access_token"');
const tokens: OAuthTokenResponse = {
access_token: parsed.access_token,
token_type: 'Bearer',
refresh_token: parsed.refresh_token,
expires_in: parsed.expires_in,
};
return { tokens, method: 'token-stdin' };
}
/**
* Refreshes an access token. Classifies failure into network-unreachable
* vs. a reachable-but-erroring server so callers can print an honest
* message instead of collapsing both into "offline" (ADR-308 failure
* policy: local ruflo functionality is never affected by auth being
* unavailable, but the diagnostic should say WHY it's unavailable).
*/
export async function refreshAccessToken(refreshTokenValue: string): Promise<OAuthTokenResponse> {
const sec = await loadSecurityOAuth();
try {
return await sec.refreshToken(refreshTokenValue);
} catch (e) {
if (e instanceof sec.OAuthError) {
if (e.code === 'network') {
throw new Error(
'Could not reach the Cognitum auth service. ruflo core functionality is unaffected — ' +
'sign-in is not required for local use.',
);
}
throw new Error(`Cognitum auth service returned an unexpected response: ${e.message}`);
}
throw e;
}
}
/**
* Returns an access token suitable for an authenticated call.
*
* Fast path: a process-memory token with more than one minute remaining.
* Slow path: load the profile's refresh token from the OS keychain, perform
* one refresh, persist a rotated refresh token BEFORE exposing the new access
* token, then update metadata and the process cache. Refresh is deliberately
* demand-driven: offline-safe commands such as plain `auth status` never call
* this function and therefore never create background traffic or retry loops.
*/
export async function getValidAccessToken(profileName = 'default'): Promise<string> {
const profile = getProfile(profileName);
if (!profile) throw new NotLoggedInError(profileName);
const scopesWithoutConsent = profile.scopes.filter((scope) => {
const domain = domainForScope(scope);
return domain !== undefined && !hasConsent(domain);
});
if (scopesWithoutConsent.length > 0) {
throw new ScopeConsentMismatchError(profileName, scopesWithoutConsent);
}
const cached = getSessionToken(profileName, ACCESS_TOKEN_REFRESH_WINDOW_MS);
if (cached) return cached;
if (!profile.keychainRef) throw new SessionOnlyExpiredError(profileName);
const sec = await loadSecurityOAuth();
const keychain = await sec.createKeychainAdapter();
const refreshTokenValue = await keychain.getSecret(KEYCHAIN_SERVICE, profile.keychainRef);
if (!refreshTokenValue) throw new SessionOnlyExpiredError(profileName);
const refreshed = await refreshAccessToken(refreshTokenValue);
if (!refreshed.access_token) throw new Error('Cognitum refresh response did not contain an access token');
// Cognitum rotates refresh tokens with reuse detection. Commit the rotated
// credential first; if this write fails, do not publish/cache the access
// token and do not retry the already-spent old refresh token here.
if (refreshed.refresh_token) {
await keychain.setSecret(KEYCHAIN_SERVICE, profile.keychainRef, refreshed.refresh_token);
}
const expiresAtMs = Date.now() + Math.max(0, refreshed.expires_in ?? 0) * 1000;
setSessionToken(profileName, refreshed.access_token, expiresAtMs);
setProfile(profileName, {
...profile,
accountId: refreshed.account_email ?? profile.accountId,
accessTokenExpiresAt: new Date(expiresAtMs).toISOString(),
linkedAt: new Date().toISOString(),
});
return refreshed.access_token;
}
@@ -0,0 +1,7 @@
/**
* Shared ADR-306 constants — split out so `commands/auth.ts` and
* `auth/client.ts` reference the same keychain service name rather than two
* independently-typed string literals that could silently drift apart.
*/
export const KEYCHAIN_SERVICE = 'ruflo-cognitum-auth';
+25
View File
@@ -0,0 +1,25 @@
/**
* ADR-306 scope <-> ADR-302 consent-domain mapping.
*
* The 5 ADR-306 scopes map 1:1 onto 5 `ConsentDomain` values that already
* exist in src/funnel/types.ts (pre-provisioned for exactly this purpose —
* see that file's own comments). No new consent machinery is needed; this
* module is just the lookup table ADR-306 describes but never names in code.
*/
import type { ConsentDomain } from '../funnel/index.js';
export const SCOPE_TO_DOMAIN: Record<string, ConsentDomain> = {
'account.create': 'account',
'proxy.use': 'proxy-install',
'cloud.route': 'cloud-routing',
'telemetry.write': 'telemetry',
'hosted.memory.use': 'hosted-memory',
};
export function domainForScope(scope: string): ConsentDomain | undefined {
return SCOPE_TO_DOMAIN[scope];
}
/** `login` always requests this scope only, on first run — ADR-306. */
export const INITIAL_SCOPE = 'account.create';
@@ -0,0 +1,77 @@
/**
* Lazy loader for `@claude-flow/security`'s OAuth + keychain surface
* (ADR-306). `@claude-flow/security` is an `optionalDependency` of this
* package (see package.json) — `ruflo auth` is the one capability that
* genuinely cannot function without it, so this module's job is turning "the
* optional package failed to install" into one clear, actionable error
* instead of a raw `ERR_MODULE_NOT_FOUND` stack trace. Mirrors the
* lazy-`require`-in-try/catch idiom already used for this same package in
* src/mcp-client.ts's `applyContentBoundaryGuardrail`, but as an async
* dynamic `import()` (the security package is itself `"type": "module"`).
*
* Only `import type` is used for the package's real types below — type-only
* imports are fully erased at compile time and never touch the runtime
* module resolver, so this file type-checks whether or not the optional
* dependency happens to be installed in a given consumer's node_modules.
*/
import type {
authorizeUrl as AuthorizeUrlFn,
exchangeCode as ExchangeCodeFn,
refreshToken as RefreshTokenFn,
exchangeManualCode as ExchangeManualCodeFn,
generatePkce as GeneratePkceFn,
OAuthTokenResponse,
PkceRequest,
CallbackServer as CallbackServerClass,
CallbackResult,
openBrowser as OpenBrowserFn,
createKeychainAdapter as CreateKeychainAdapterFn,
KeychainAdapter,
OAuthError as OAuthErrorClass,
} from '@claude-flow/security';
export interface SecurityOAuthModule {
authorizeUrl: typeof AuthorizeUrlFn;
exchangeCode: typeof ExchangeCodeFn;
refreshToken: typeof RefreshTokenFn;
exchangeManualCode: typeof ExchangeManualCodeFn;
generatePkce: typeof GeneratePkceFn;
CallbackServer: typeof CallbackServerClass;
openBrowser: typeof OpenBrowserFn;
createKeychainAdapter: typeof CreateKeychainAdapterFn;
OAuthError: typeof OAuthErrorClass;
OOB_REDIRECT_URI: string;
}
export type { OAuthTokenResponse, PkceRequest, CallbackResult, KeychainAdapter };
export class SecurityPackageMissingError extends Error {
constructor(cause: unknown) {
super(
"ruflo auth needs the '@claude-flow/security' package, which isn't installed " +
"(it's an optional dependency — install/reinstall failed or was skipped for this " +
`platform). Try: npm install @claude-flow/security. Underlying error: ${
cause instanceof Error ? cause.message : String(cause)
}`,
);
this.name = 'SecurityPackageMissingError';
}
}
let cached: SecurityOAuthModule | null = null;
/** Loads `@claude-flow/security`'s OAuth surface, throwing a clear error if it's absent. */
export async function loadSecurityOAuth(): Promise<SecurityOAuthModule> {
if (cached) return cached;
try {
const mod = (await import('@claude-flow/security')) as unknown as SecurityOAuthModule;
if (!mod.authorizeUrl || !mod.createKeychainAdapter) {
throw new Error('module loaded but is missing expected OAuth exports');
}
cached = mod;
return mod;
} catch (e) {
throw new SecurityPackageMissingError(e);
}
}
+39
View File
@@ -0,0 +1,39 @@
/**
* Process-lifetime in-memory access-token cache (ADR-306).
*
* The access token is never written to `auth.json` or any other disk file —
* only the refresh token (via the OS keychain, or nowhere in session-only
* mode) survives a process exit. Every fresh `ruflo` invocation starts with
* an empty cache and re-derives an access token from the refresh token (or
* asks the user to log in again, in session-only mode). This is a deliberate
* ADR-306 usability cost, not something to "fix" by persisting the access
* token — see auth/types.ts's doc comment.
*/
interface SessionEntry {
accessToken: string;
/** epoch ms */
expiresAt: number;
}
const sessions = new Map<string, SessionEntry>();
export function setSessionToken(profile: string, accessToken: string, expiresAtMs: number): void {
sessions.set(profile, { accessToken, expiresAt: expiresAtMs });
}
/**
* Returns the cached access token when it remains valid for at least
* `minValidityMs`. Authenticated callers use a small refresh window so a
* token cannot expire while an outbound request is in flight.
*/
export function getSessionToken(profile: string, minValidityMs = 0): string | null {
const entry = sessions.get(profile);
if (!entry) return null;
if (Date.now() + Math.max(0, minValidityMs) >= entry.expiresAt) return null;
return entry.accessToken;
}
export function clearSessionToken(profile: string): void {
sessions.delete(profile);
}
+61
View File
@@ -0,0 +1,61 @@
/**
* `auth.json` persistence — atomic tmp+rename, 0600, under ~/.ruflo (ADR-306).
* Reuses the exact same primitives `proxy-config.toml`'s consent mirror and
* every other funnel state file already use (src/funnel/state.ts).
*/
import { readStateJson, writeStateJson, deleteStateFile } from '../funnel/state.js';
import type { AuthFile, ProfileAuthState } from './types.js';
const AUTH_FILE = 'auth.json';
export const DEFAULT_PROFILE = 'default';
function emptyAuthFile(): AuthFile {
return { schemaVersion: 1, defaultProfile: DEFAULT_PROFILE, profiles: {} };
}
export function readAuthFile(): AuthFile {
const file = readStateJson<AuthFile>(AUTH_FILE);
return file ?? emptyAuthFile();
}
function writeAuthFile(file: AuthFile): void {
writeStateJson(AUTH_FILE, file);
}
export function getProfile(name?: string): ProfileAuthState | null {
const file = readAuthFile();
const key = name ?? file.defaultProfile;
return file.profiles[key] ?? null;
}
export function listProfiles(): { defaultProfile: string; profiles: ProfileAuthState[] } {
const file = readAuthFile();
return { defaultProfile: file.defaultProfile, profiles: Object.values(file.profiles) };
}
/** Writes/overwrites a profile. The first profile ever written becomes the default. */
export function setProfile(name: string, state: ProfileAuthState, makeDefault = false): void {
const file = readAuthFile();
const isFirst = Object.keys(file.profiles).length === 0;
file.profiles[name] = state;
if (makeDefault || isFirst) file.defaultProfile = name;
writeAuthFile(file);
}
export function removeProfile(name: string): boolean {
const file = readAuthFile();
if (!(name in file.profiles)) return false;
delete file.profiles[name];
if (file.defaultProfile === name) {
const remaining = Object.keys(file.profiles);
file.defaultProfile = remaining[0] ?? DEFAULT_PROFILE;
}
writeAuthFile(file);
return true;
}
/** `auth logout --all` — forgets every profile. */
export function clearAllProfiles(): void {
deleteStateFile(AUTH_FILE);
}
+28
View File
@@ -0,0 +1,28 @@
/**
* `ruflo auth` state shapes (ADR-306).
*
* `auth.json` holds identity metadata ONLY — never token material. The
* access token lives exclusively in a process-lifetime in-memory singleton
* (session.ts); the refresh token goes to the OS keychain (keychainRef set)
* or nowhere at all when no keychain backend is reachable (keychainRef:
* null — session-only mode, ADR-306's accepted usability cost, not a bug).
*/
export interface ProfileAuthState {
accountId: string;
scopes: string[];
/** ISO timestamp — the access token's own expiry, not tracked beyond this. */
accessTokenExpiresAt: string;
/** OS-keychain account identifier for this profile's refresh token, or null if session-only. */
keychainRef: string | null;
profile: string;
loginMethod: 'pkce' | 'device' | 'token-stdin';
/** ISO timestamp of the login that created/last-refreshed this profile. */
linkedAt: string;
}
export interface AuthFile {
schemaVersion: 1;
defaultProfile: string;
profiles: Record<string, ProfileAuthState>;
}
+283
View File
@@ -0,0 +1,283 @@
/**
* `ruflo auth` — Cognitum identity (ADR-306).
*
* `login` obtains OAuth tokens via the loopback PKCE flow (default,
* interactive desktop), the OOB manual-paste flow (`--no-browser`, or
* auto-detected headless environments), or `--token-stdin` (CI/enterprise
* automation — refuses interactively otherwise, per ADR-306). The refresh
* token goes to the OS keychain when reachable, or nowhere (session-only —
* a deliberate usability cost, not a bug) when it isn't. The access token
* itself is NEVER written to disk; see src/auth/session.ts.
*/
import type { Command, CommandResult } from '../types.js';
import { output } from '../output.js';
import { isCI, isInteractive, hasConsent, recordConsent, revokeConsent } from '../funnel/index.js';
import {
browserLogin,
manualLogin,
tokenStdinLogin,
isProbablyHeadless,
LoginCancelledError,
LoginDeniedError,
StateMismatchError,
} from '../auth/client.js';
import { loadSecurityOAuth, SecurityPackageMissingError, type OAuthTokenResponse } from '../auth/security-bridge.js';
import { getProfile, setProfile, removeProfile, listProfiles, clearAllProfiles, DEFAULT_PROFILE } from '../auth/state.js';
import { setSessionToken, clearSessionToken } from '../auth/session.js';
import { INITIAL_SCOPE, domainForScope } from '../auth/scopes.js';
import type { ProfileAuthState } from '../auth/types.js';
import { KEYCHAIN_SERVICE } from '../auth/constants.js';
import { getValidAccessToken, NotLoggedInError, SessionOnlyExpiredError } from '../auth/client.js';
import { removeInjectedToken } from '../proxy/token-bridge.js';
function nowIso(): string {
return new Date().toISOString();
}
async function persistLogin(
profileName: string,
tokens: OAuthTokenResponse,
method: ProfileAuthState['loginMethod'],
): Promise<ProfileAuthState> {
const expiresInSec = tokens.expires_in ?? 0;
const expiresAtMs = Date.now() + expiresInSec * 1000;
setSessionToken(profileName, tokens.access_token, expiresAtMs);
let keychainRef: string | null = null;
if (tokens.refresh_token) {
const sec = await loadSecurityOAuth();
const keychain = await sec.createKeychainAdapter();
if (await keychain.isAvailable()) {
await keychain.setSecret(KEYCHAIN_SERVICE, profileName, tokens.refresh_token);
keychainRef = profileName;
}
// else: session-only — the refresh token is simply not persisted anywhere.
}
const state: ProfileAuthState = {
accountId: tokens.account_email ?? 'unknown',
scopes: [INITIAL_SCOPE],
accessTokenExpiresAt: new Date(expiresAtMs).toISOString(),
keychainRef,
profile: profileName,
loginMethod: method,
linkedAt: nowIso(),
};
setProfile(profileName, state);
recordConsent('account', true, 'auth-login');
return state;
}
function refuseNonInteractive(hasTokenStdin: boolean): CommandResult | null {
if (hasTokenStdin) return null;
if (isInteractive() && !isCI()) return null;
// The CLI harness only acts on exitCode — it never auto-prints
// CommandResult.message, so this path must print for itself.
const message =
'ruflo auth login refuses to run interactively in a non-TTY/CI environment. ' +
'Use --token-stdin for automation (reads {"access_token",...} JSON from stdin).';
output.printError(message);
return { success: false, message, exitCode: 1 };
}
const loginCommand: Command = {
name: 'login',
description: 'Sign in to Cognitum (PKCE browser flow, OOB manual flow, or --token-stdin)',
options: [
{ name: 'profile', description: 'Named profile to store this login under', type: 'string', default: DEFAULT_PROFILE },
{ name: 'no-browser', description: 'Force the headless OOB copy-paste flow', type: 'boolean', default: false },
{ name: 'token-stdin', description: 'Read a pre-obtained token as JSON from stdin (CI/automation)', type: 'boolean', default: false },
],
action: async (ctx): Promise<CommandResult> => {
const profileName = typeof ctx.flags.profile === 'string' ? ctx.flags.profile : DEFAULT_PROFILE;
// Parser camelCases kebab-case flag names — read via tokenStdin/noBrowser,
// not ['token-stdin']/['no-browser'] (see doctor.ts's fixHandles comment).
const tokenStdin = Boolean(ctx.flags.tokenStdin ?? ctx.flags['token-stdin']);
const noBrowser = Boolean(ctx.flags.noBrowser ?? ctx.flags['no-browser']);
const refusal = refuseNonInteractive(tokenStdin);
if (refusal) return refusal;
try {
const result = tokenStdin
? await tokenStdinLogin()
: noBrowser || isProbablyHeadless()
? await manualLogin((line) => output.writeln(line))
: await browserLogin((line) => output.writeln(line));
const state = await persistLogin(profileName, result.tokens, result.method);
output.printSuccess(`Logged in as ${state.accountId} (profile: ${profileName})`);
output.writeln(
state.keychainRef
? ' refresh token: stored in the OS keychain'
: ' refresh token: NOT stored (no keychain backend reachable) — session-only, you will need to log in again next time',
);
return { success: true, data: { profile: profileName, accountId: state.accountId } };
} catch (e) {
if (e instanceof SecurityPackageMissingError || e instanceof LoginCancelledError || e instanceof LoginDeniedError || e instanceof StateMismatchError) {
output.printError(e.message);
return { success: false, message: e.message, exitCode: 1 };
}
const message = e instanceof Error ? e.message : String(e);
output.printError('Sign-in failed', message);
return { success: false, message, exitCode: 1 };
}
},
};
const logoutCommand: Command = {
name: 'logout',
description: 'Sign out — clears the local session, keychain entry, and account consent',
options: [
{ name: 'profile', description: 'Profile to log out of', type: 'string', default: DEFAULT_PROFILE },
{ name: 'all', description: 'Log out of every profile', type: 'boolean', default: false },
],
action: async (ctx): Promise<CommandResult> => {
removeInjectedToken();
const all = ctx.flags.all === true;
const profileName = typeof ctx.flags.profile === 'string' ? ctx.flags.profile : DEFAULT_PROFILE;
const { profiles } = listProfiles();
if (profiles.length === 0) {
output.writeln('Nothing to log out of — no profile is signed in.');
return { success: true, data: { hadSession: false } };
}
const toClear = all ? profiles : profiles.filter((p) => p.profile === profileName);
if (toClear.length === 0) {
output.writeln(`No such profile: ${profileName}`);
return { success: false, exitCode: 1 };
}
let sec;
try {
sec = await loadSecurityOAuth();
} catch {
sec = null; // best-effort keychain cleanup — logout must still succeed locally
}
for (const p of toClear) {
clearSessionToken(p.profile);
if (p.keychainRef && sec) {
const keychain = await sec.createKeychainAdapter();
await keychain.deleteSecret(KEYCHAIN_SERVICE, p.keychainRef).catch(() => {});
}
removeProfile(p.profile);
}
if (all) {
clearAllProfiles();
revokeConsent('account', 'auth-logout');
} else if (listProfiles().profiles.length === 0) {
revokeConsent('account', 'auth-logout');
}
output.printSuccess(all ? 'Logged out of all profiles.' : `Logged out of profile "${profileName}".`);
output.writeln(
' Note: this only forgets the local copy. Cognitum does not currently expose a token ' +
'revocation endpoint for this flow, matching the same known limitation meta-proxy documents ' +
'for its own logout — revoke server-side access from the Cognitum dashboard if needed.',
);
return { success: true, data: { hadSession: true } };
},
};
const statusCommand: Command = {
name: 'status',
description: 'Show signed-in profile(s), scopes, and expiry',
options: [
{ name: 'profile', description: 'Show only this profile', type: 'string' },
{ name: 'json', description: 'Machine-readable output', type: 'boolean', default: false },
{
name: 'check',
description: 'Validate credentials now; silently refresh from the OS keychain when needed',
type: 'boolean',
default: false,
},
],
action: async (ctx): Promise<CommandResult> => {
const { defaultProfile, profiles } = listProfiles();
const filterName = typeof ctx.flags.profile === 'string' ? ctx.flags.profile : undefined;
const shown = filterName ? profiles.filter((p) => p.profile === filterName) : profiles;
if (shown.length === 0) {
const message = filterName ? `No such profile: ${filterName}` : 'Not logged in. Run: ruflo auth login';
if (ctx.flags.json) {
output.printJson({ profiles: [] });
} else {
output.writeln(message);
}
return { success: true, data: { profiles: [] } };
}
const withConsistency = shown.map((p) => {
const missingConsent = p.scopes.filter((scope) => {
const domain = domainForScope(scope);
return domain !== undefined && !hasConsent(domain);
});
return { ...p, isDefault: p.profile === defaultProfile, missingConsent };
});
const checked = await Promise.all(
withConsistency.map(async (p) => {
if (!ctx.flags.check) return { ...p, credentialStatus: 'not-checked' as const };
try {
await getValidAccessToken(p.profile);
return { ...p, credentialStatus: 'valid' as const };
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
return {
...p,
credentialStatus:
e instanceof NotLoggedInError || e instanceof SessionOnlyExpiredError
? ('login-required' as const)
: ('unavailable' as const),
credentialError: message,
};
}
}),
);
if (ctx.flags.json) {
output.printJson({ profiles: checked });
return { success: true, data: { profiles: checked } };
}
for (const p of checked) {
output.writeln(`Profile: ${p.profile}${p.isDefault ? ' (default)' : ''}`);
output.writeln(` account: ${p.accountId}`);
output.writeln(` scopes: ${p.scopes.join(', ')}`);
output.writeln(` access token expires: ${p.accessTokenExpiresAt}`);
output.writeln(` refresh token: ${p.keychainRef ? 'in OS keychain' : 'session-only (not persisted)'}`);
if (ctx.flags.check) {
output.writeln(` credential check: ${p.credentialStatus}`);
if ('credentialError' in p && p.credentialError) output.writeln(` ${p.credentialError}`);
}
if (p.missingConsent.length > 0) {
output.printError(
` scope-vs-consent mismatch: ${p.missingConsent.join(', ')} granted without a matching consent receipt`,
);
}
output.writeln('');
}
return { success: true, data: { profiles: checked } };
},
};
export const authCommand: Command = {
name: 'auth',
description: 'Cognitum identity — login, logout, status (ADR-306)',
subcommands: [loginCommand, logoutCommand, statusCommand],
examples: [
{ command: 'ruflo auth login', description: 'Sign in via the browser PKCE flow' },
{ command: 'ruflo auth login --no-browser', description: 'Sign in via the headless OOB copy-paste flow' },
{ command: 'ruflo auth status', description: 'Show signed-in profile(s)' },
{ command: 'ruflo auth status --check', description: 'Validate or silently refresh credentials now' },
{ command: 'ruflo auth logout', description: 'Sign out of the default profile' },
],
action: statusCommand.action,
};
export default authCommand;
+226 -4
View File
@@ -999,7 +999,7 @@ async function checkFunnel(): Promise<HealthCheck> {
}
/** Meta LLM Proxy — sponsored-downtime health (ADR-313). */
async function checkProxy(): Promise<HealthCheck> {
async function checkProxySponsoredConsent(): Promise<HealthCheck> {
try {
const { funnelStateDir, hasConsent, readRateLimitStatus, lastRecordedEvent } = await import('../funnel/index.js');
const dir = funnelStateDir();
@@ -1043,6 +1043,223 @@ async function checkProxy(): Promise<HealthCheck> {
}
}
/**
* Binary presence + tamper check (ADR-307). Deliberately NEVER spawns the
* binary to probe a version — confirmed empirically (2026-07-16) that
* `meta-proxy` has no `--version`/`--help` flag and starts the live server
* as a side effect of ANY invocation, which a doctor health check must never
* do. Version info instead comes from install-manifest.json (written at
* install time) and, once running, the proxy's own `/status` endpoint via
* checkProxyProcess below.
*/
async function checkProxyBinary(): Promise<HealthCheck> {
const NAME = 'Meta LLM Proxy binary (ADR-307)';
try {
const { proxyBinaryPath, proxyInstallManifestPath } = await import('../proxy/paths.js');
const binPath = proxyBinaryPath();
if (!existsSync(binPath)) {
return { name: NAME, status: 'warn', message: 'not installed', fix: 'ruflo proxy install' };
}
const manifestPath = proxyInstallManifestPath();
if (!existsSync(manifestPath)) {
return {
name: NAME,
status: 'warn',
message: 'binary present but no install-manifest.json — provenance unknown (installed outside `ruflo proxy install`?)',
fix: 'ruflo proxy update --release <x.y.z>',
};
}
const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as {
version: string;
sha256: string;
verifiedAt: string;
};
const liveSha = createHash('sha256').update(readFileSync(binPath)).digest('hex');
if (liveSha !== manifest.sha256) {
return {
name: NAME,
status: 'fail',
message: `binary sha256 does not match the recorded install manifest — possible tampering or a manual overwrite (expected ${manifest.sha256.slice(0, 12)}…, got ${liveSha.slice(0, 12)}…)`,
fix: 'ruflo proxy update --release <x.y.z>',
};
}
return { name: NAME, status: 'pass', message: `v${manifest.version}, signature-verified at install (${manifest.verifiedAt})` };
} catch (err) {
return { name: NAME, status: 'warn', message: `check failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
/** PID-file liveness (ADR-307) — mirrors daemon.ts's signal-0 probe pattern. */
async function checkProxyProcess(): Promise<HealthCheck> {
const NAME = 'Meta LLM Proxy process (ADR-307)';
try {
const { proxyPidFilePath } = await import('../proxy/paths.js');
const pidPath = proxyPidFilePath();
if (!existsSync(pidPath)) {
return { name: NAME, status: 'warn', message: 'not running (no PID file)', fix: 'ruflo proxy start' };
}
const pidRaw = readFileSync(pidPath, 'utf-8').trim();
const pid = parseInt(pidRaw, 10);
if (!Number.isFinite(pid)) {
return { name: NAME, status: 'warn', message: `PID file is malformed: ${JSON.stringify(pidRaw)}`, fix: 'ruflo proxy stop && ruflo proxy start' };
}
try {
process.kill(pid, 0); // signal-0 liveness probe — throws if the process is dead
} catch {
return { name: NAME, status: 'warn', message: `PID file points at ${pid}, which is not running — stale PID file`, fix: 'ruflo proxy start' };
}
// Live version-compat + data-plane info, ONLY once PID liveness already
// confirmed a process is running (never spawns anything — see
// checkProxyBinary's comment on why probing via process launch is unsafe).
// GET /status shape confirmed against the real v0.1.0 binary:
// {"version","data_plane","bind","sponsored_available","proxy_token_valid"}.
const { proxyConfigPath, proxyTokenPath, proxyInstallManifestPath } = await import('../proxy/paths.js');
const bindMatch = existsSync(proxyConfigPath())
? readFileSync(proxyConfigPath(), 'utf-8').match(/^bind\s*=\s*"([^"]*)"/m)
: null;
const bind = bindMatch ? bindMatch[1] : '127.0.0.1:11435';
let token: string;
try {
token = readFileSync(proxyTokenPath(), 'utf-8').trim();
} catch {
return { name: NAME, status: 'pass', message: `running (pid ${pid}); no proxy-token to query /status` };
}
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 2000);
const resp = await fetch(`http://${bind}/status`, {
headers: { authorization: `Bearer ${token}` },
signal: controller.signal,
});
clearTimeout(timer);
if (!resp.ok) {
return { name: NAME, status: 'warn', message: `running (pid ${pid}); /status returned HTTP ${resp.status}` };
}
const body = (await resp.json()) as { version?: string; data_plane?: string };
let versionNote = '';
if (existsSync(proxyInstallManifestPath())) {
const manifest = JSON.parse(readFileSync(proxyInstallManifestPath(), 'utf-8')) as { version?: string };
if (manifest.version && body.version && manifest.version !== body.version) {
return {
name: NAME,
status: 'warn',
message: `running (pid ${pid}) reports v${body.version}, but the installed binary is v${manifest.version} — a stale process from a previous version?`,
fix: 'ruflo proxy stop && ruflo proxy start',
};
}
versionNote = body.version ? ` v${body.version}` : '';
}
return {
name: NAME,
status: 'pass',
message: `running (pid ${pid})${versionNote}; data plane: ${body.data_plane ?? 'unknown'}`,
};
} catch (err) {
// Live process but /status unreachable (still starting up, or a
// network hiccup) — not a failure, PID liveness already passed.
return {
name: NAME,
status: 'pass',
message: `running (pid ${pid}); /status unreachable (${err instanceof Error ? err.message : String(err)})`,
};
}
} catch (err) {
return { name: NAME, status: 'warn', message: `check failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
/** Non-loopback bind exposure warning (ADR-307's mandated startup warning, surfaced in doctor too). */
async function checkProxyBindAddress(): Promise<HealthCheck> {
const NAME = 'Meta LLM Proxy bind address (ADR-307)';
try {
const { proxyConfigPath, isLoopbackBind } = await import('../proxy/paths.js');
const cfgPath = proxyConfigPath();
if (!existsSync(cfgPath)) {
return { name: NAME, status: 'pass', message: 'no config file yet — defaults to loopback-only (127.0.0.1:11435)' };
}
const raw = readFileSync(cfgPath, 'utf-8');
const match = raw.match(/^bind\s*=\s*"([^"]*)"/m);
const bind = match ? match[1] : '127.0.0.1:11435';
if (!isLoopbackBind(bind)) {
return {
name: NAME,
status: 'warn',
message: `bound to non-loopback address ${bind} — this exposes the proxy to your network`,
fix: 'Set bind back to 127.0.0.1:<port> in proxy-config.toml unless external exposure is intended',
};
}
return { name: NAME, status: 'pass', message: `loopback-only (${bind})` };
} catch (err) {
return { name: NAME, status: 'warn', message: `check failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
/** `ruflo auth` health (ADR-306). Warn (never fail) on absence — auth is never required for core functionality. */
async function checkAuth(): Promise<HealthCheck> {
const NAME = 'Cognitum identity (ADR-306)';
try {
const { listProfiles } = await import('../auth/state.js');
const { domainForScope } = await import('../auth/scopes.js');
const { hasConsent } = await import('../funnel/index.js');
const { profiles } = listProfiles();
if (profiles.length === 0) {
return { name: NAME, status: 'warn', message: 'not logged in', fix: 'ruflo auth login' };
}
let keychainAvailable: boolean | 'unknown' = 'unknown';
try {
const sec = await import('@claude-flow/security');
keychainAvailable = await (await sec.createKeychainAdapter()).isAvailable();
} catch {
keychainAvailable = 'unknown'; // security package unavailable — surfaced by checkProxyBinary's sibling concerns, not duplicated here
}
// Scope-vs-receipt consistency check (ADR-306: "fail-closed... reports").
// Unlike every other check in this file, a violation here is a FAIL, not
// a warn — a scope present without a matching consent receipt is exactly
// the condition ADR-306 says must never silently pass.
const violations: string[] = [];
for (const p of profiles) {
for (const scope of p.scopes) {
const domain = domainForScope(scope);
if (domain && !hasConsent(domain)) violations.push(`${p.profile}: ${scope}`);
}
}
if (violations.length > 0) {
return {
name: NAME,
status: 'fail',
message: `scope granted without a matching consent receipt: ${violations.join(', ')}`,
fix: 'ruflo auth logout && ruflo auth login',
};
}
const names = profiles.map((p) => p.profile).join(', ');
const sessionOnly = profiles.filter((p) => !p.keychainRef).map((p) => p.profile);
const parts = [`profiles: ${names}`];
if (keychainAvailable === false) parts.push('keychain backend unreachable — falling back to session-only tokens');
if (sessionOnly.length > 0) parts.push(`session-only (no persisted refresh token): ${sessionOnly.join(', ')}`);
return { name: NAME, status: 'pass', message: parts.join('; ') };
} catch (err) {
return { name: NAME, status: 'warn', message: `check failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
async function checkMetaharnessIntegration(): Promise<HealthCheck> {
// Locate plugins dir.
//
@@ -1427,7 +1644,7 @@ export const doctorCommand: Command = {
{
name: 'component',
short: 'c',
description: 'Check specific component (version, node, npm, config, daemon, memory, api, git, mcp, claude, disk, typescript, agentic-flow, encryption, federation, funnel, proxy, metaharness)',
description: 'Check specific component (version, node, npm, config, daemon, memory, api, git, mcp, claude, disk, typescript, agentic-flow, encryption, federation, funnel, proxy, auth, metaharness)',
type: 'string'
},
{
@@ -1565,7 +1782,8 @@ export const doctorCommand: Command = {
checkMetaharness, // ADR-150 — MetaHarness upstream package
checkMetaharnessIntegration, // iter 45 — ruflo-side integration layer
checkFunnel, // ADR-305 — effective funnel state + deciding precedence source
checkProxy, // ADR-313 — Meta LLM Proxy sponsored-downtime health
checkProxySponsoredConsent, // ADR-313 — Meta LLM Proxy sponsored-downtime health
checkAuth, // ADR-306 — Cognitum identity (warn-only; never fails bare `ruflo doctor`)
];
// #2677: `--component memory` now runs the whole memory-health suite,
@@ -1604,7 +1822,11 @@ export const doctorCommand: Command = {
'metaharness': checkMetaharness, // ADR-150 — upstream package
'metaharness-integration': checkMetaharnessIntegration, // iter 45 — ruflo-side
'funnel': checkFunnel, // ADR-305
'proxy': checkProxy, // ADR-313
// ADR-307 — deep-dive array, same pattern as 'memory' above: the cheap
// sponsored-consent check first, then binary/process/bind in the order
// a user would actually debug them (is it installed? running? exposed?).
'proxy': [checkProxySponsoredConsent, checkProxyBinary, checkProxyProcess, checkProxyBindAddress],
'auth': checkAuth, // ADR-306
};
let checksToRun = allChecks;
@@ -88,6 +88,8 @@ const commandLoaders: Record<string, CommandLoader> = {
// User-facing preferences wrapper (ADR-311 copy discipline — no "funnel" in
// the user surface). Forwards to the funnel primitives internally.
settings: () => import('./settings.js'),
// Cognitum identity — login/logout/status (ADR-306)
auth: () => import('./auth.js'),
// Meta LLM Proxy — sponsored downtime capacity (ADR-304/307/313)
proxy: () => import('./proxy.js'),
// Fable co-pilot advisor tip in the statusline insight ticker (ADR-316)
@@ -0,0 +1,248 @@
/**
* `ruflo proxy install|start|stop|status|logs|update|uninstall` (ADR-307) —
* the full lifecycle command set, kept in its own file so
* src/commands/proxy.ts (the ADR-313/314/315 consent subcommands) stays
* under the repo's 500-line-per-file convention. Merged into one
* `proxyCommand` in proxy.ts.
*/
import type { Command, CommandResult } from '../types.js';
import { output } from '../output.js';
import { hasConsent, recordConsent, revokeConsent } from '../funnel/index.js';
import { installProxy, uninstallProxy } from '../proxy/install.js';
import {
startForeground,
startBackground,
stopProxy,
getProxyStatus,
readProxyLogTail,
watchProxyLog,
ProxyNotInstalledError,
ProxyAlreadyRunningError,
} from '../proxy/lifecycle.js';
import { proxyTokenPath } from '../proxy/paths.js';
import { removeInjectedToken, startTokenRefreshPump } from '../proxy/token-bridge.js';
const INSTALL_DISCLOSURE = [
'Installing the Meta LLM Proxy (ADR-304/307).',
'',
'This downloads a separately-released Rust binary (Ed25519-signature and',
'checksum verified before anything is written to disk) and runs it as a',
'local process bound to 127.0.0.1 only. The proxy routes to LOCAL',
'backends by default — no prompt leaves this machine. Cloud routing is a',
'separate, explicit opt-in (`ruflo proxy config --cloud`), never enabled',
'by install alone.',
'',
'Uninstall anytime: ruflo proxy uninstall',
].join('\n');
const installSub: Command = {
name: 'install',
description: 'Download, verify, and install the meta-proxy binary (ADR-307)',
options: [
// NOT named 'version' — index.ts:107 globally intercepts any --version/-v
// anywhere in argv (`if (flags.version || flags.V) { showVersion(); return; }`)
// BEFORE subcommand dispatch, regardless of which command defines it. A
// subcommand-local --version is silently swallowed by the CLI's own
// `ruflo --version` handling — confirmed the hard way in E2E testing.
{ name: 'release', description: 'Release version to install', type: 'string' },
{ name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
],
action: async (ctx): Promise<CommandResult> => {
// Validate required parameters BEFORE any consent side-effect — granting
// proxy-install consent on a call that was going to fail anyway (e.g.
// --yes with no --release) would permanently skip the disclosure on the
// next, parameter-complete attempt. Confirmed as a real bug in E2E testing.
const version = typeof ctx.flags.release === 'string' ? ctx.flags.release : undefined;
if (!version) {
output.printError(
'ruflo proxy install requires --release <x.y.z> — there is no version-discovery ' +
'endpoint yet (see the plan doc for the tracked follow-up). Find the latest at ' +
'the release channel and pass it explicitly.',
);
return { success: false, exitCode: 1 };
}
if (!hasConsent('proxy-install')) {
output.writeln(INSTALL_DISCLOSURE);
output.writeln('');
const confirmed = Boolean(ctx.flags.yes);
if (!confirmed) {
output.writeln(`Re-run with --yes to confirm: ruflo proxy install --release ${version} --yes`);
return { success: true, data: { confirmed: false } };
}
recordConsent('proxy-install', true, 'proxy-install');
}
try {
const spinner = output.createSpinner({ text: `Installing meta-proxy ${version}...`, spinner: 'dots' });
spinner.start();
const result = await installProxy({ version, log: (line) => spinner.setText(line) });
spinner.succeed(`meta-proxy ${version} installed`);
output.writeln(` binary: ${result.binaryPath}`);
output.writeln(` sha256: ${result.sha256}`);
return { success: true, data: result };
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
output.printError('Install failed', message);
return { success: false, message, exitCode: 1 };
}
},
};
const updateSub: Command = {
name: 'update',
description: 'Re-verify and replace the installed binary with a specific version (never automatic)',
options: [{ name: 'release', description: 'Release version to install', type: 'string', required: true }],
action: async (ctx): Promise<CommandResult> => {
const version = typeof ctx.flags.release === 'string' ? ctx.flags.release : undefined;
if (!version) {
output.printError('ruflo proxy update requires --release <x.y.z>');
return { success: false, exitCode: 1 };
}
try {
const spinner = output.createSpinner({ text: `Updating meta-proxy to ${version}...`, spinner: 'dots' });
spinner.start();
const result = await installProxy({ version, log: (line) => spinner.setText(line) });
spinner.succeed(`meta-proxy updated to ${version}`);
output.writeln(` binary: ${result.binaryPath}`);
return { success: true, data: result };
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
output.printError('Update failed', message);
return { success: false, message, exitCode: 1 };
}
},
};
const startSub: Command = {
name: 'start',
description: 'Start meta-proxy (foreground by default; --service to detach)',
options: [
{ name: 'service', description: 'Run detached (background), survives terminal close but not a reboot — full OS-service registration is not yet implemented', type: 'boolean', default: false },
],
action: async (ctx): Promise<CommandResult> => {
const service = Boolean(ctx.flags.service);
try {
if (service) {
const { pid } = await startBackground();
output.printSuccess(`meta-proxy started in the background (pid ${pid})`);
output.writeln(' Note: survives this terminal closing, but not a reboot — OS-service registration is not yet implemented.');
output.writeln(' Logs: ruflo proxy logs');
return { success: true, data: { pid } };
}
output.writeln('Starting meta-proxy in the foreground — press Ctrl+C to stop.');
await startTokenRefreshPump();
await startForeground(); // never returns normally
return { success: true };
} catch (e) {
if (e instanceof ProxyNotInstalledError || e instanceof ProxyAlreadyRunningError) {
output.printError(e.message);
return { success: false, message: e.message, exitCode: 1 };
}
const message = e instanceof Error ? e.message : String(e);
output.printError('Failed to start meta-proxy', message);
return { success: false, message, exitCode: 1 };
}
},
};
const superviseSub: Command = {
name: 'supervise',
description: 'Internal detached supervisor for token refresh and meta-proxy lifecycle',
action: async (): Promise<CommandResult> => {
await startTokenRefreshPump();
await startForeground(true);
return { success: true };
},
};
const stopSub: Command = {
name: 'stop',
description: 'Stop a running meta-proxy process',
action: async (): Promise<CommandResult> => {
const result = await stopProxy();
removeInjectedToken();
if (!result.wasRunning) {
output.writeln('meta-proxy was not running.');
return { success: true, data: result };
}
output.printSuccess(`meta-proxy stopped (was pid ${result.pid})`);
return { success: true, data: result };
},
};
const statusSub: Command = {
name: 'status',
description: 'Show meta-proxy install + process status',
options: [{ name: 'json', description: 'Machine-readable output', type: 'boolean', default: false }],
action: async (ctx): Promise<CommandResult> => {
const status = getProxyStatus();
if (ctx.flags.json) {
output.printJson(status);
return { success: true, data: status };
}
output.writeln(`Installed: ${status.installed ? 'yes' : 'no'}`);
output.writeln(`Running: ${status.running ? `yes (pid ${status.pid})` : 'no'}`);
if (status.stalePidFile) output.writeln(' (a stale PID file was found and will be cleared on next start)');
if (!status.installed) output.writeln('Run: ruflo proxy install --release <x.y.z>');
else if (!status.running) output.writeln('Run: ruflo proxy start');
return { success: true, data: status };
},
};
const logsSub: Command = {
name: 'logs',
description: 'Show meta-proxy --service logs',
options: [
{ name: 'follow', short: 'f', description: 'Stream new log lines as they arrive', type: 'boolean', default: false },
],
action: async (ctx): Promise<CommandResult> => {
if (ctx.flags.follow) {
output.writeln('Following meta-proxy logs — press Ctrl+C to stop.');
try {
const watcher = watchProxyLog((line) => output.writeln(line));
await new Promise<void>((resolve) => {
process.on('SIGINT', () => {
watcher.close();
resolve();
});
});
return { success: true };
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
output.printError(message);
return { success: false, message, exitCode: 1 };
}
}
const tail = readProxyLogTail();
if (!tail) {
output.writeln('No log content yet — meta-proxy has never been started in --service mode.');
return { success: true, data: { empty: true } };
}
output.writeln(tail);
return { success: true };
},
};
const uninstallSub: Command = {
name: 'uninstall',
description: 'Stop the proxy (if running), remove the binary, token, and consent receipt',
action: async (): Promise<CommandResult> => {
const status = getProxyStatus();
if (status.running) {
await stopProxy();
output.writeln('Stopped the running meta-proxy process.');
}
const removed = await uninstallProxy();
const { existsSync, unlinkSync } = await import('node:fs');
const tokenPath = proxyTokenPath();
if (existsSync(tokenPath)) unlinkSync(tokenPath);
removeInjectedToken();
revokeConsent('proxy-install', 'proxy-uninstall');
output.printSuccess(removed ? 'meta-proxy uninstalled.' : 'Nothing was installed — cleaned up any leftover state.');
return { success: true, data: { removed } };
},
};
export const proxyLifecycleSubcommands: Command[] = [installSub, updateSub, startSub, superviseSub, stopSub, statusSub, logsSub, uninstallSub];
+103 -4
View File
@@ -25,6 +25,7 @@ import { clearRateLimitStatus, readRateLimitStatus } from '../funnel/rate-limit-
import { clearQuotaLowStatus, readQuotaLowStatus } from '../funnel/power-saver-notifier.js';
import { getInstalledCliVersion } from '../init/helper-refresh.js';
import * as path from 'path';
import { proxyLifecycleSubcommands } from './proxy-lifecycle.js';
const PROXY_CONFIG_FILE = 'proxy-config.toml';
@@ -44,12 +45,12 @@ function readProxyConfigRaw(): string {
}
}
function writeConsentMirrorLine(field: string, value: boolean): void {
function writeConfigLine(field: string, rawValue: string): void {
const dir = funnelStateDir();
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
const target = path.join(dir, PROXY_CONFIG_FILE);
const raw = readProxyConfigRaw();
const line = `${field} = ${value}`;
const line = `${field} = ${rawValue}`;
const pattern = new RegExp(`^${field}\\s*=.*$`, 'm');
let next: string;
if (pattern.test(raw)) {
@@ -62,6 +63,10 @@ function writeConsentMirrorLine(field: string, value: boolean): void {
fs.renameSync(tmp, target);
}
function writeConsentMirrorLine(field: string, value: boolean): void {
writeConfigLine(field, String(value));
}
function writeSponsoredConsentMirror(granted: boolean): void {
writeConsentMirrorLine('sponsored_consent_granted', granted);
}
@@ -74,6 +79,88 @@ function writeTrainingShareConsentMirror(granted: boolean): void {
writeConsentMirrorLine('training_share_consent_granted', granted);
}
/**
* `default_data_plane` — the ADR-304 cloud-routing toggle. Values confirmed
* against meta-proxy's actual `DataPlane` enum (`src/config.rs`,
* `#[serde(rename_all = "snake_case")]`): "local" | "cloud" | "sponsored" |
* "passthrough" (the last two are not written by this command — sponsored
* is ADR-313's own consent flag, passthrough is the proxy's own default).
*/
function readDataPlane(): string {
const raw = readProxyConfigRaw();
const match = raw.match(/^default_data_plane\s*=\s*"([^"]*)"/m);
return match ? match[1] : 'passthrough'; // matches the Rust struct's own default
}
function writeDataPlane(plane: 'local' | 'cloud'): void {
writeConfigLine('default_data_plane', `"${plane}"`);
}
const CLOUD_ROUTING_DISCLOSURE = [
'Enabling cloud routing.',
'',
'With cloud routing ON, prompts for cloud-tier requests are sent to',
'api.cognitum.one and forwarded to the selected provider',
'(Claude / GPT / Gemini / DeepSeek / OpenRouter).',
'',
'Requests routed to local backends never leave this machine.',
'',
'Disable anytime: ruflo proxy config --local-only',
].join('\n');
const configSub: Command = {
name: 'config',
description: 'Toggle cloud routing (ADR-304) — local backends only by default',
options: [
{ name: 'cloud', description: 'Enable cloud routing (requires cloud-routing consent)', type: 'boolean', default: false },
{ name: 'local-only', description: 'Disable cloud routing, revert to local-only routing', type: 'boolean', default: false },
{ name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
],
action: async (ctx): Promise<CommandResult> => {
const wantCloud = Boolean(ctx.flags.cloud);
const wantLocalOnly = Boolean(ctx.flags.localOnly ?? ctx.flags['local-only']);
if (wantCloud && wantLocalOnly) {
output.printError('Pass either --cloud or --local-only, not both.');
return { success: false, exitCode: 1 };
}
if (!wantCloud && !wantLocalOnly) {
const plane = readDataPlane();
output.writeln(`Current data plane: ${plane}`);
output.writeln(
plane === 'cloud'
? 'Cloud routing is ON — cloud-tier requests go to api.cognitum.one.'
: 'Cloud routing is OFF — requests never leave this machine (or use your own Claude subscription on Passthrough).',
);
return { success: true, data: { plane } };
}
if (wantLocalOnly) {
writeDataPlane('local');
revokeConsent('cloud-routing', 'proxy-config-local-only');
output.printSuccess('Cloud routing disabled — reverted to local-only routing.');
return { success: true, data: { plane: 'local' } };
}
// wantCloud
if (!hasConsent('cloud-routing')) {
output.writeln(CLOUD_ROUTING_DISCLOSURE);
output.writeln('');
if (!ctx.flags.yes) {
output.writeln('Re-run with --yes to confirm: ruflo proxy config --cloud --yes');
return { success: true, data: { confirmed: false } };
}
recordConsent('cloud-routing', true, 'proxy-config-cloud');
}
writeDataPlane('cloud');
output.printSuccess('Cloud routing enabled.');
output.writeln(' Requests routed to local backends still never leave this machine.');
output.writeln(' Disable anytime: ruflo proxy config --local-only');
return { success: true, data: { plane: 'cloud' } };
},
};
const SPONSOR_DISCLOSURE = [
'Enabling sponsored downtime mode.',
'',
@@ -313,19 +400,31 @@ const trainingShareStatusSub: Command = {
export const proxyCommand: Command = {
name: 'proxy',
description: 'Meta LLM Proxy — sponsored downtime + power saver + training-data sharing (ADR-304/307/313/314/315)',
description: 'Meta LLM Proxy — install/lifecycle + sponsored downtime + power saver + training-data sharing (ADR-304/307/313/314/315)',
subcommands: [
...proxyLifecycleSubcommands,
configSub,
sponsorEnableSub, sponsorDisableSub, sponsorStatusSub, sponsorClearSub,
powerSaverEnableSub, powerSaverDisableSub, powerSaverStatusSub, powerSaverClearSub,
trainingShareEnableSub, trainingShareDisableSub, trainingShareStatusSub,
],
examples: [
{ command: 'ruflo proxy install --release 0.1.0 --yes', description: 'Install the meta-proxy binary' },
{ command: 'ruflo proxy start', description: 'Start meta-proxy in the foreground' },
{ command: 'ruflo proxy status', description: 'Show install + process status' },
{ command: 'ruflo proxy config --cloud --yes', description: 'Enable cloud routing (ADR-304)' },
{ command: 'ruflo proxy config --local-only', description: 'Revert to local-only routing' },
{ command: 'ruflo proxy sponsor-status', description: 'Show current sponsored-mode state' },
{ command: 'ruflo proxy sponsor-enable --yes', description: 'Opt into sponsored downtime capacity' },
{ command: 'ruflo proxy power-saver-enable --yes', description: 'Opt into power saver mode' },
{ command: 'ruflo proxy training-share-enable --yes', description: 'Opt into training-data sharing (ADR-315)' },
],
action: sponsorStatusSub.action,
action: async (ctx) => {
const { getProxyStatus } = await import('../proxy/lifecycle.js');
const status = getProxyStatus();
output.writeln(`Installed: ${status.installed ? 'yes' : 'no'}; Running: ${status.running ? `yes (pid ${status.pid})` : 'no'}`);
return sponsorStatusSub.action!(ctx);
},
};
export default proxyCommand;
+159
View File
@@ -0,0 +1,159 @@
/**
* `ruflo proxy install`/`update` orchestration (ADR-307): download -> verify
* -> extract -> place -> record. The per-user bearer token
* (`~/.ruflo/proxy-token`) is NOT generated here — confirmed empirically
* (2026-07-16) that the meta-proxy binary itself creates it on first launch
* (`load_or_create_token()`), so this module's job ends at a verified binary
* on disk plus an install manifest doctor can check against.
*
* @module proxy/install
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { fetchReleaseAssets, detectTargetTriple, releaseArchiveExtension, releaseAssetFilename, type TargetTriple } from './release.js';
import { verifyRelease, sha256Hex, PROXY_RELEASE_PUBKEY_PEM } from './verify.js';
import { proxyBinaryPath, proxyInstallManifestPath, type InstallManifest } from './paths.js';
export class ExtractionError extends Error {
constructor(message: string) {
super(message);
this.name = 'ExtractionError';
}
}
function binaryNameInArchive(): string {
return process.platform === 'win32' ? 'meta-proxy.exe' : 'meta-proxy';
}
/**
* Extracts the archive via the OS's own tools — `tar` for `.tar.gz`
* (present on macOS/Linux/Windows 10+), PowerShell `Expand-Archive`
* specifically for `.zip` on Windows (not tar's bsdtar zip support — not
* reliable enough to lean on). Zero new archive-parsing dependency, matching
* this repo's existing taste for shelling out over adding a parser dep.
*/
async function extractArchive(archivePath: string, extractDir: string, ext: 'zip' | 'tar.gz'): Promise<void> {
const { SafeExecutor } = await import('@claude-flow/security');
fs.mkdirSync(extractDir, { recursive: true });
if (ext === 'tar.gz') {
const exec = new SafeExecutor({ allowedCommands: ['tar'], timeout: 60_000 });
const result = await exec.execute('tar', ['xzf', archivePath, '-C', extractDir]);
if (result.exitCode !== 0) {
throw new ExtractionError(`tar extraction failed (exit ${result.exitCode}): ${result.stderr || result.stdout}`);
}
return;
}
// .zip — PowerShell Expand-Archive, single-quoted literal paths (doubling
// any embedded single quote per PowerShell string-literal escaping) passed
// as ONE argv element to -Command. shell:false means no OS shell ever
// tokenizes this string — only powershell.exe's own parser does.
const escape = (p: string) => p.replace(/'/g, "''");
const command = `Expand-Archive -LiteralPath '${escape(archivePath)}' -DestinationPath '${escape(extractDir)}' -Force`;
const exec = new SafeExecutor({ allowedCommands: ['powershell', 'powershell.exe'], timeout: 60_000 });
const result = await exec.execute('powershell', ['-NoProfile', '-NonInteractive', '-Command', command]);
if (result.exitCode !== 0) {
throw new ExtractionError(`Expand-Archive failed (exit ${result.exitCode}): ${result.stderr || result.stdout}`);
}
}
export interface InstallOptions {
version: string;
log?: (line: string) => void;
}
export interface InstallResult {
version: string;
binaryPath: string;
sha256: string;
}
/**
* Full install pipeline. Refuses (throws) on any verification failure —
* never writes a partially-verified binary into the live install path.
*/
export async function installProxy(opts: InstallOptions): Promise<InstallResult> {
const log = opts.log ?? (() => {});
const triple: TargetTriple = detectTargetTriple();
const archiveFilename = releaseAssetFilename(opts.version, triple);
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruflo-proxy-install-'));
try {
log(`Fetching meta-proxy ${opts.version} (${triple})...`);
const assets = await fetchReleaseAssets(opts.version, triple, workDir, log);
log('Verifying release signature and checksum...');
const { sha256 } = verifyRelease({
sumsBytes: assets.sumsBytes,
sigBase64: assets.sigBase64,
assetBytes: assets.archiveBytes,
assetFilename: assets.archiveFilename,
});
log(`Verified — sha256 ${sha256.slice(0, 16)}…`);
// fetchReleaseAssets's dev (gh) path already wrote the archive to workDir
// under archiveFilename; ensure it's there regardless of source so
// extraction always has a real file to operate on.
const archivePath = path.join(workDir, archiveFilename);
if (!fs.existsSync(archivePath)) {
fs.writeFileSync(archivePath, assets.archiveBytes);
}
const extractDir = path.join(workDir, 'extracted');
await extractArchive(archivePath, extractDir, releaseArchiveExtension(triple));
const extractedBinaryPath = path.join(extractDir, binaryNameInArchive());
if (!fs.existsSync(extractedBinaryPath)) {
throw new ExtractionError(`archive did not contain the expected binary at its root: ${binaryNameInArchive()}`);
}
// Defense in depth: confirm the extracted binary genuinely resolves
// inside extractDir (catches a symlink swap or similar), even though
// we only ever read one specific expected relative path, never an
// archive-listed one (so "zip slip" via arbitrary archive paths isn't
// reachable here in the first place).
const { PathValidator } = await import('@claude-flow/security');
const validator = new PathValidator({ allowedPrefixes: [extractDir] });
const validation = await validator.validate(extractedBinaryPath);
if (!validation.isValid) {
throw new ExtractionError(`extracted binary path failed validation: ${validation.errors.join('; ') || 'unknown'}`);
}
const finalPath = proxyBinaryPath();
fs.mkdirSync(path.dirname(finalPath), { recursive: true, mode: 0o700 });
const tmp = `${finalPath}.tmp`;
fs.copyFileSync(extractedBinaryPath, tmp);
fs.chmodSync(tmp, 0o755);
fs.renameSync(tmp, finalPath);
const liveSha = sha256Hex(fs.readFileSync(finalPath));
const manifest: InstallManifest = {
version: opts.version,
sha256: liveSha,
verifiedAt: new Date().toISOString(),
pubkeyFingerprint: sha256Hex(Buffer.from(PROXY_RELEASE_PUBKEY_PEM)).slice(0, 16),
};
fs.mkdirSync(path.dirname(proxyInstallManifestPath()), { recursive: true });
fs.writeFileSync(proxyInstallManifestPath(), JSON.stringify(manifest, null, 2), { mode: 0o600 });
log(`meta-proxy ${opts.version} installed at ${finalPath}`);
return { version: opts.version, binaryPath: finalPath, sha256: liveSha };
} finally {
fs.rmSync(workDir, { recursive: true, force: true });
}
}
export async function uninstallProxy(): Promise<boolean> {
const binPath = proxyBinaryPath();
const existed = fs.existsSync(binPath);
if (existed) fs.unlinkSync(binPath);
try {
fs.unlinkSync(proxyInstallManifestPath());
} catch {
/* absent — fine */
}
return existed;
}
+257
View File
@@ -0,0 +1,257 @@
/**
* meta-proxy process lifecycle (ADR-307) — start/stop/status/logs.
*
* Adapts daemon.ts's proven pattern (PID file, O_EXCL lockfile for atomic
* check-then-start, signal-0 liveness, SIGTERM->1000ms->SIGKILL) to a
* native binary instead of a forked Node process. The binary itself takes
* no CLI flags — confirmed empirically (2026-07-16): `meta-proxy.exe` has
* no `--version`/`--help`, and any invocation just starts the server reading
* its own config file — so `spawn()` here passes zero arguments, always.
*
* Foreground `start` (the ADR-307 default) uses `stdio: 'inherit'` and
* blocks directly — simplest and safest, no log-file redirection needed.
* `start --service` needs REAL file-descriptor redirection
* (`stdio: ['ignore', fd, fd]`) + `detached: true` + `unref()` via
* `child_process.spawn()` directly — `SafeExecutor.executeStreaming()`
* buffers output in-process, which is wrong for a process meant to outlive
* the `ruflo` invocation that started it.
*
* @module proxy/lifecycle
*/
import { spawn } from 'node:child_process';
import * as fs from 'node:fs';
import { proxyBinaryPath, proxyPidFilePath, proxyLockFilePath, proxyLogFilePath } from './paths.js';
export class ProxyNotInstalledError extends Error {
constructor() {
super('meta-proxy is not installed. Run: ruflo proxy install');
this.name = 'ProxyNotInstalledError';
}
}
export class ProxyAlreadyRunningError extends Error {
constructor(public readonly pid: number) {
super(`meta-proxy is already running (pid ${pid}). Stop it first with: ruflo proxy stop`);
this.name = 'ProxyAlreadyRunningError';
}
}
function requireBinary(): string {
const bin = proxyBinaryPath();
if (!fs.existsSync(bin)) throw new ProxyNotInstalledError();
return bin;
}
/** Signal-0 liveness probe — cross-platform in Node, throws if the process is dead. */
function isProcessRunning(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
export interface ProxyStatus {
installed: boolean;
running: boolean;
pid: number | null;
stalePidFile: boolean;
}
export function getProxyStatus(): ProxyStatus {
const installed = fs.existsSync(proxyBinaryPath());
const pidPath = proxyPidFilePath();
if (!fs.existsSync(pidPath)) {
return { installed, running: false, pid: null, stalePidFile: false };
}
const raw = fs.readFileSync(pidPath, 'utf-8').trim();
const pid = parseInt(raw, 10);
if (!Number.isFinite(pid)) {
return { installed, running: false, pid: null, stalePidFile: true };
}
const running = isProcessRunning(pid);
return { installed, running, pid: running ? pid : null, stalePidFile: !running };
}
function writePidFile(pid: number): void {
fs.writeFileSync(proxyPidFilePath(), String(pid), 'utf-8');
}
function clearStalePidFile(): void {
try {
fs.unlinkSync(proxyPidFilePath());
} catch {
// already absent
}
}
/**
* Atomic check-then-start via an O_EXCL lockfile — the same fix daemon.ts
* applies for the identical race (#2407/#2484: without this, N concurrent
* `start` calls all see "not running" and all spawn their own process).
* Returns the lock fd to release once the PID file has been written (or on
* any early-return/throw), never before.
*/
function acquireStartLock(): number | null {
const lockFile = proxyLockFilePath();
try {
return fs.openSync(lockFile, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'EEXIST') return null; // another start is mid-spawn
throw e;
}
}
function releaseStartLock(fd: number | null): void {
if (fd === null) return;
try {
fs.closeSync(fd);
} catch {
/* ignore */
}
try {
fs.unlinkSync(proxyLockFilePath());
} catch {
/* ignore */
}
}
/**
* Foreground start (ADR-307 default) — blocks the caller until the process
* exits or is interrupted. `stdio: 'inherit'` passes the proxy's own output
* straight through to the terminal; signals (Ctrl+C) propagate naturally to
* the child, no manual forwarding needed.
*/
export async function startForeground(supervised = false): Promise<never> {
const bin = requireBinary();
const status = getProxyStatus();
// In service mode startBackground has already written this supervisor's
// PID. Treating it as a competing proxy makes the supervisor immediately
// exit before it can spawn meta-proxy.
if (!supervised && status.running && status.pid) throw new ProxyAlreadyRunningError(status.pid);
if (status.stalePidFile) clearStalePidFile();
const child = spawn(bin, [], { stdio: 'inherit', windowsHide: false });
if (!supervised && child.pid) writePidFile(child.pid);
const cleanup = () => clearStalePidFile();
process.on('exit', cleanup);
if (supervised) {
const forwardSignal = (signal: NodeJS.Signals) => {
if (!child.killed) child.kill(signal);
};
process.once('SIGTERM', () => forwardSignal('SIGTERM'));
process.once('SIGINT', () => forwardSignal('SIGINT'));
}
await new Promise<void>((resolve) => {
child.on('exit', () => {
cleanup();
resolve();
});
});
process.exit(0);
}
/**
* Background/`--service` start — detaches so the process outlives this
* `ruflo` invocation, redirecting stdout/stderr to a real log file (not
* buffered in-process). Returns once the child's PID is confirmed written,
* without waiting for the process to exit.
*/
export async function startBackground(): Promise<{ pid: number }> {
requireBinary();
const status = getProxyStatus();
if (status.running && status.pid) throw new ProxyAlreadyRunningError(status.pid);
const lockFd = acquireStartLock();
try {
// Re-check under the lock — the dedup above raced a concurrent starter.
const rechecked = getProxyStatus();
if (rechecked.running && rechecked.pid) throw new ProxyAlreadyRunningError(rechecked.pid);
if (rechecked.stalePidFile) clearStalePidFile();
const logFd = fs.openSync(proxyLogFilePath(), 'a');
const cliEntry = process.argv[1];
if (!cliEntry) throw new Error('cannot locate the ruflo CLI entrypoint for supervised service mode');
const child = spawn(process.execPath, [cliEntry, 'proxy', 'supervise'], {
stdio: ['ignore', logFd, logFd],
detached: true,
windowsHide: true,
});
fs.closeSync(logFd); // the child holds its own duplicated fd; safe to close ours
if (!child.pid) throw new Error('ruflo proxy supervisor failed to spawn — no PID returned');
writePidFile(child.pid);
child.unref();
return { pid: child.pid };
} finally {
releaseStartLock(lockFd);
}
}
export interface StopResult {
wasRunning: boolean;
pid: number | null;
}
/** SIGTERM -> 1000ms -> SIGKILL if still alive, mirroring daemon.ts's killBackgroundDaemon. */
export async function stopProxy(): Promise<StopResult> {
const status = getProxyStatus();
if (!status.running || !status.pid) {
if (status.stalePidFile) clearStalePidFile();
return { wasRunning: false, pid: null };
}
const pid = status.pid;
process.kill(pid, 'SIGTERM');
await new Promise((r) => setTimeout(r, 1000));
if (isProcessRunning(pid)) {
process.kill(pid, 'SIGKILL');
}
clearStalePidFile();
return { wasRunning: true, pid };
}
const TAIL_BYTES = 64 * 1024; // bounded read — a long-running proxy's log grows over weeks
export function readProxyLogTail(maxBytes: number = TAIL_BYTES): string {
const logPath = proxyLogFilePath();
if (!fs.existsSync(logPath)) return '';
const { size } = fs.statSync(logPath);
const start = Math.max(0, size - maxBytes);
const fd = fs.openSync(logPath, 'r');
try {
const buf = Buffer.alloc(size - start);
fs.readSync(fd, buf, 0, buf.length, start);
return buf.toString('utf-8');
} finally {
fs.closeSync(fd);
}
}
/** Streams new log lines as they're appended, starting from the current end of file. */
export function watchProxyLog(onLine: (line: string) => void): fs.FSWatcher {
const logPath = proxyLogFilePath();
if (!fs.existsSync(logPath)) {
throw new Error('no log file yet — meta-proxy has never been started in --service mode');
}
let offset = fs.statSync(logPath).size;
return fs.watch(logPath, () => {
const { size } = fs.statSync(logPath);
if (size <= offset) return;
const fd = fs.openSync(logPath, 'r');
try {
const buf = Buffer.alloc(size - offset);
fs.readSync(fd, buf, 0, buf.length, offset);
offset = size;
for (const line of buf.toString('utf-8').split('\n')) {
if (line.length > 0) onLine(line);
}
} finally {
fs.closeSync(fd);
}
});
}
+84
View File
@@ -0,0 +1,84 @@
/**
* Filesystem layout for the managed meta-proxy binary (ADR-307), all under
* the same `~/.ruflo` state dir every other funnel/proxy/auth file uses
* (src/funnel/state.ts's `funnelStateDir()` — respects RUFLO_STATE_DIR for
* tests). Centralized here so doctor.ts, install.ts, and lifecycle.ts share
* one definition instead of three copies drifting apart.
*/
import { join } from 'node:path';
import { funnelStateDir } from '../funnel/index.js';
const BINARY_NAME = process.platform === 'win32' ? 'meta-proxy.exe' : 'meta-proxy';
export function proxyBinaryPath(): string {
return join(funnelStateDir(), 'bin', BINARY_NAME);
}
export function proxyPidFilePath(): string {
return join(funnelStateDir(), 'proxy.pid');
}
export function proxyLockFilePath(): string {
return join(funnelStateDir(), 'proxy.lock');
}
export function proxyLogFilePath(): string {
return join(funnelStateDir(), 'proxy.log');
}
export function proxyInstallManifestPath(): string {
return join(funnelStateDir(), 'proxy', 'install-manifest.json');
}
export function proxyConfigPath(): string {
return join(funnelStateDir(), 'proxy-config.toml');
}
export function proxyTokenPath(): string {
return join(funnelStateDir(), 'proxy-token');
}
export function proxyInjectedTokenPath(): string {
return join(funnelStateDir(), 'proxy-injected-token.json');
}
export interface InstallManifest {
version: string;
sha256: string;
verifiedAt: string;
pubkeyFingerprint: string;
}
/**
* True if `bind` (a `host:port` string from proxy-config.toml) targets a
* loopback address — decides whether the non-loopback exposure warning
* fires (ADR-307). Recognizes the whole IPv4 127.0.0.0/8 block, IPv6 `::1`,
* IPv4-mapped IPv6 loopback, and the `localhost` hostname.
*
* A plain `bind.startsWith('127.0.0.1')` check (the obvious first draft)
* misclassifies `[::1]:port` as non-loopback — a real bug meta-proxy's own
* Rust `is_loopback_bind` fixed for the identical reason; this mirrors that
* fix rather than repeating the mistake on the TypeScript side.
*/
export function isLoopbackBind(bind: string): boolean {
const hostPart = (host: string): boolean => {
const stripped = host.replace(/^\[/, '').replace(/\]$/, '');
if (stripped.toLowerCase() === 'localhost') return true;
if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(stripped)) return true; // 127.0.0.0/8
if (stripped === '::1') return true;
if (/^::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i.test(stripped)) return true; // IPv4-mapped loopback
return false;
};
// IPv6 bracketed form: [::1]:11435
const bracketed = bind.match(/^\[([^\]]+)\]:\d+$/);
if (bracketed) return hostPart(bracketed[1]);
// host:port (IPv4 or hostname) — split on the LAST colon so a bare IPv6
// address without brackets (ambiguous, shouldn't occur in practice) isn't
// misparsed as host:port.
const lastColon = bind.lastIndexOf(':');
const host = lastColon === -1 ? bind : bind.slice(0, lastColon);
return hostPart(host);
}
+168
View File
@@ -0,0 +1,168 @@
/**
* meta-proxy release resolution + download (ADR-307).
*
* Two download paths, deliberately not conflated:
* - **Production** (`downloadReleaseAsset`): public, signed assets from
* cognitum-one/meta-proxy-dist. Source remains private; normal users need
* neither GitHub authentication nor access to the source repository.
* - **Dev-only** (`downloadViaGhCli`): shells out to `gh release download`,
* gated behind `RUFLO_DEV_PROXY_INSTALL=1` so it is never reachable by
* accident, and always logs loudly that it is a developer path.
*
* @module proxy/release
*/
export const TARGET_TRIPLES = [
'aarch64-apple-darwin',
'x86_64-apple-darwin',
'x86_64-unknown-linux-gnu',
'aarch64-unknown-linux-gnu',
'x86_64-pc-windows-msvc',
] as const;
export type TargetTriple = (typeof TARGET_TRIPLES)[number];
export class UnsupportedPlatformError extends Error {
constructor(platform: string, arch: string) {
super(`meta-proxy has no published release for ${platform}/${arch}`);
this.name = 'UnsupportedPlatformError';
}
}
/** Maps the running Node process's platform/arch onto one of meta-proxy's 5 published triples. */
export function detectTargetTriple(platform: string = process.platform, arch: string = process.arch): TargetTriple {
if (platform === 'darwin') return arch === 'arm64' ? 'aarch64-apple-darwin' : 'x86_64-apple-darwin';
if (platform === 'linux') return arch === 'arm64' ? 'aarch64-unknown-linux-gnu' : 'x86_64-unknown-linux-gnu';
if (platform === 'win32') {
if (arch !== 'x64') throw new UnsupportedPlatformError(platform, arch);
return 'x86_64-pc-windows-msvc';
}
throw new UnsupportedPlatformError(platform, arch);
}
export function releaseArchiveExtension(triple: TargetTriple): 'zip' | 'tar.gz' {
return triple.endsWith('windows-msvc') ? 'zip' : 'tar.gz';
}
export function releaseAssetFilename(version: string, triple: TargetTriple): string {
return `meta-proxy-${version}-${triple}.${releaseArchiveExtension(triple)}`;
}
export interface ReleaseAssets {
archiveBytes: Buffer;
archiveFilename: string;
sumsBytes: Buffer;
sigBase64: string;
}
const DEV_INSTALL_ENV = 'RUFLO_DEV_PROXY_INSTALL';
const RELEASE_SOURCE_ENV = 'RUFLO_PROXY_RELEASE_SOURCE';
const GH_REPO = 'cognitum-one/meta-proxy';
const PUBLIC_DIST_BASE = 'https://github.com/cognitum-one/meta-proxy-dist/releases/download';
const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024;
async function downloadPublicAsset(url: string, maxBytes: number): Promise<Buffer> {
const response = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(120_000) });
if (!response.ok) throw new Error(`release download failed: HTTP ${response.status} for ${url}`);
const declared = Number(response.headers.get('content-length') ?? 0);
if (declared > maxBytes) throw new Error(`release asset exceeds ${maxBytes} byte limit`);
const bytes = Buffer.from(await response.arrayBuffer());
if (bytes.length > maxBytes) throw new Error(`release asset exceeds ${maxBytes} byte limit`);
return bytes;
}
async function ghExecutor() {
// Dynamic import, not a static one: @claude-flow/security is only an
// optionalDependency of this package (see auth/security-bridge.ts for the
// same reasoning) — a static top-level import would crash module load for
// any consumer that doesn't have it installed, even ones that never touch
// this dev-only download path.
const { SafeExecutor } = await import('@claude-flow/security');
return new SafeExecutor({ allowedCommands: ['gh'], timeout: 120_000 });
}
/**
* Dev-only fallback: `gh release download` via SafeExecutor into `destDir`.
* Requires the caller's environment to already have `gh` authenticated
* against a GitHub account with access to the private meta-proxy repo — this
* is NOT something a normal ruflo end user has, which is exactly why this
* path is gated and logged, not the default.
*/
export async function downloadViaGhCli(
destDir: string,
version: string,
triple: TargetTriple,
log: (line: string) => void = () => {},
): Promise<ReleaseAssets> {
const archiveFilename = releaseAssetFilename(version, triple);
log(
`[dev-only] Downloading meta-proxy ${version} (${triple}) via \`gh release download\` — ` +
'this path is NOT how production installs work; it exists for local development only ' +
`(gated behind ${DEV_INSTALL_ENV}=1).`,
);
const exec = await ghExecutor();
const result = await exec.execute('gh', [
'release',
'download',
`v${version}`,
'--repo',
GH_REPO,
'--dir',
destDir,
'--pattern',
archiveFilename,
'--pattern',
'SHA256SUMS',
'--pattern',
'SHA256SUMS.sig',
'--clobber',
]);
if (result.exitCode !== 0) {
throw new Error(`gh release download failed (exit ${result.exitCode}): ${result.stderr || result.stdout}`);
}
const { readFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const [archiveBytes, sumsBytes, sigRaw] = await Promise.all([
readFile(join(destDir, archiveFilename)),
readFile(join(destDir, 'SHA256SUMS')),
readFile(join(destDir, 'SHA256SUMS.sig'), 'utf-8'),
]);
return { archiveBytes, archiveFilename, sumsBytes, sigBase64: sigRaw.trim() };
}
/**
* Production download path — a Cognitum-owned, auth-mediated release-proxy
* endpoint. Not implemented: no such endpoint exists in the confirmed
* OpenAPI contract today. Throws a clear, specific error rather than
* silently falling back to the dev path, so a real user hitting this isn't
* left guessing whether it's their environment or a genuine gap.
*/
export async function downloadReleaseAsset(
version: string,
triple: TargetTriple,
_destDir: string,
): Promise<ReleaseAssets> {
const archiveFilename = releaseAssetFilename(version, triple);
const base = (process.env[RELEASE_SOURCE_ENV] || PUBLIC_DIST_BASE).replace(/\/$/, '');
const release = `${base}/v${encodeURIComponent(version)}`;
const [archiveBytes, sumsBytes, sigBytes] = await Promise.all([
downloadPublicAsset(`${release}/${archiveFilename}`, MAX_ARCHIVE_BYTES),
downloadPublicAsset(`${release}/SHA256SUMS`, 128 * 1024),
downloadPublicAsset(`${release}/SHA256SUMS.sig`, 16 * 1024),
]);
return { archiveBytes, archiveFilename, sumsBytes, sigBase64: sigBytes.toString('utf8').trim() };
}
/** Entry point install.ts calls — routes to the dev path when explicitly enabled, else fails clearly. */
export async function fetchReleaseAssets(
version: string,
triple: TargetTriple,
destDir: string,
log?: (line: string) => void,
): Promise<ReleaseAssets> {
if (process.env[DEV_INSTALL_ENV] === '1') {
return downloadViaGhCli(destDir, version, triple, log);
}
return downloadReleaseAsset(version, triple, destDir);
}
@@ -0,0 +1,61 @@
/** ADR-318 access-token-only bridge from ruflo auth to meta-proxy. */
import * as fs from 'node:fs';
import { dirname } from 'node:path';
import { getValidAccessToken } from '../auth/client.js';
import { getProfile, listProfiles } from '../auth/state.js';
import { proxyConfigPath, proxyInjectedTokenPath } from './paths.js';
const REFRESH_POLL_MS = 30_000;
function configureInjectedTokenPath(): void {
const target = proxyConfigPath();
fs.mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
const raw = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : '';
const line = `ruflo_injected_token_path = ${JSON.stringify(proxyInjectedTokenPath())}`;
const pattern = /^ruflo_injected_token_path\s*=.*$/m;
const next = pattern.test(raw) ? raw.replace(pattern, line) : `${raw}${raw && !raw.endsWith('\n') ? '\n' : ''}${line}\n`;
const tmp = `${target}.tmp-${process.pid}`;
fs.writeFileSync(tmp, next, { encoding: 'utf8', mode: 0o600 });
fs.renameSync(tmp, target);
}
export function removeInjectedToken(): void {
try { fs.unlinkSync(proxyInjectedTokenPath()); } catch { /* absent */ }
}
export async function refreshInjectedToken(): Promise<boolean> {
const { defaultProfile } = listProfiles();
const profile = getProfile(defaultProfile);
if (!profile) {
removeInjectedToken();
return false;
}
try {
const accessToken = await getValidAccessToken(defaultProfile);
const current = getProfile(defaultProfile);
if (!current) return false;
const body = JSON.stringify({ schemaVersion: 1, accessToken, expiresAt: current.accessTokenExpiresAt });
configureInjectedTokenPath();
const target = proxyInjectedTokenPath();
const tmp = `${target}.tmp-${process.pid}`;
fs.writeFileSync(tmp, body, { encoding: 'utf8', mode: 0o600 });
fs.chmodSync(tmp, 0o600);
fs.renameSync(tmp, target);
return true;
} catch {
removeInjectedToken();
return false;
}
}
export async function startTokenRefreshPump(): Promise<() => void> {
await refreshInjectedToken();
const timer = setInterval(() => void refreshInjectedToken(), REFRESH_POLL_MS);
const stop = () => {
clearInterval(timer);
removeInjectedToken();
};
process.once('exit', removeInjectedToken);
return stop;
}
+96
View File
@@ -0,0 +1,96 @@
/**
* meta-proxy release verification (ADR-307) — mirrors src/init/helper-signing.ts's
* raw-EdDSA `crypto.verify(null, ...)` pattern almost exactly, and matches the
* exact scheme confirmed live 2026-07-16 against a real v0.1.0 release: ONE
* combined `SHA256SUMS.sig` (raw Ed25519 over the `SHA256SUMS` file's bytes,
* base64-encoded — not a per-binary signature), then a per-asset SHA-256
* check against the matching `SHA256SUMS` line. Refuse-all-or-nothing on any
* mismatch, same discipline as `writeCriticalHelpers()`.
*
* @module proxy/verify
*/
import { createHash, createPublicKey, verify as cryptoVerify } from 'node:crypto';
/**
* meta-proxy's committed release-signing public key (SPKI PEM), confirmed
* live 2026-07-16 by verifying a real `SHA256SUMS.sig` from the v0.1.0
* release against it (crypto.verify -> true).
*/
export const PROXY_RELEASE_PUBKEY_PEM = `-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAjhLDomjIGdcltYC7j+aiESQFD4LWoHaULietG1PuDjw=
-----END PUBLIC KEY-----`;
export class ReleaseVerificationError extends Error {
constructor(message: string) {
super(message);
this.name = 'ReleaseVerificationError';
}
}
/** Raw EdDSA verify of `SHA256SUMS.sig` (base64) over `SHA256SUMS`'s exact bytes. */
export function verifySha256SumsSignature(
sumsBytes: Buffer,
sigBase64: string,
pubkeyPem: string = PROXY_RELEASE_PUBKEY_PEM,
): boolean {
const pubkey = createPublicKey(pubkeyPem);
const sig = Buffer.from(sigBase64.trim(), 'base64');
return cryptoVerify(null, sumsBytes, pubkey, sig);
}
export type ParsedChecksums = Record<string, string>; // filename -> lowercase hex sha256
/** Parses `<sha256> <filename>` lines (sha256sum's own output format). */
export function parseSha256Sums(sumsText: string): ParsedChecksums {
const result: ParsedChecksums = {};
for (const line of sumsText.split(/\r?\n/)) {
const match = line.match(/^([0-9a-f]{64})\s+(.+)$/i);
if (!match) continue;
result[match[2]] = match[1].toLowerCase();
}
return result;
}
export function sha256Hex(bytes: Buffer): string {
return createHash('sha256').update(bytes).digest('hex');
}
export interface VerifyReleaseInput {
sumsBytes: Buffer;
sigBase64: string;
assetBytes: Buffer;
assetFilename: string;
pubkeyPem?: string;
}
export interface VerifyReleaseResult {
sha256: string;
}
/**
* Full verification: signature over SHA256SUMS, then the asset's own hash
* against the matching line. Throws `ReleaseVerificationError` on ANY
* failure — there is no partial-trust outcome, matching ADR-307's "refuses
* on any mismatch" requirement.
*/
export function verifyRelease(input: VerifyReleaseInput): VerifyReleaseResult {
if (!verifySha256SumsSignature(input.sumsBytes, input.sigBase64, input.pubkeyPem)) {
throw new ReleaseVerificationError('SHA256SUMS.sig failed Ed25519 verification — refusing to install');
}
const sums = parseSha256Sums(input.sumsBytes.toString('utf-8'));
const expected = sums[input.assetFilename];
if (!expected) {
throw new ReleaseVerificationError(`SHA256SUMS has no entry for ${input.assetFilename}`);
}
const actual = sha256Hex(input.assetBytes);
if (actual !== expected) {
throw new ReleaseVerificationError(
`sha256 mismatch for ${input.assetFilename}: expected ${expected.slice(0, 12)}…, got ${actual.slice(0, 12)}…`,
);
}
return { sha256: actual };
}
@@ -0,0 +1,60 @@
/**
* Keychain adapter tests. `SessionOnlyKeychainAdapter` is fully covered
* offline (no native backend needed). `createKeychainAdapter()`'s native
* path is exercised only behind a real `isAvailable()` canary probe — CI
* environments with no reachable keychain backend skip gracefully rather
* than faking success, per ADR-306's degrade-to-session-only contract.
*/
import { describe, it, expect } from 'vitest';
import { createKeychainAdapter, SessionOnlyKeychainAdapter } from '../src/keychain-adapter.js';
describe('SessionOnlyKeychainAdapter', () => {
it('round-trips a secret in memory', async () => {
const adapter = new SessionOnlyKeychainAdapter();
await adapter.setSecret('svc', 'acct', 'topsecret');
expect(await adapter.getSecret('svc', 'acct')).toBe('topsecret');
});
it('returns null for a secret that was never set', async () => {
const adapter = new SessionOnlyKeychainAdapter();
expect(await adapter.getSecret('svc', 'nobody')).toBeNull();
});
it('deletes a secret', async () => {
const adapter = new SessionOnlyKeychainAdapter();
await adapter.setSecret('svc', 'acct', 'topsecret');
await adapter.deleteSecret('svc', 'acct');
expect(await adapter.getSecret('svc', 'acct')).toBeNull();
});
it('is always available', async () => {
expect(await new SessionOnlyKeychainAdapter().isAvailable()).toBe(true);
});
it('keeps distinct (service, account) pairs isolated', async () => {
const adapter = new SessionOnlyKeychainAdapter();
await adapter.setSecret('svc-a', 'acct', 'secret-a');
await adapter.setSecret('svc-b', 'acct', 'secret-b');
expect(await adapter.getSecret('svc-a', 'acct')).toBe('secret-a');
expect(await adapter.getSecret('svc-b', 'acct')).toBe('secret-b');
});
});
describe('createKeychainAdapter', () => {
it('resolves to an adapter that is always available (native or session-only fallback)', async () => {
const adapter = await createKeychainAdapter();
expect(await adapter.isAvailable()).toBe(true);
});
it('round-trips a canary secret through whatever backend was selected', async () => {
const adapter = await createKeychainAdapter();
const account = `ruflo-test-${Date.now()}`;
await adapter.setSecret('ruflo-security-test', account, 'round-trip-value');
try {
expect(await adapter.getSecret('ruflo-security-test', account)).toBe('round-trip-value');
} finally {
await adapter.deleteSecret('ruflo-security-test', account);
}
});
});
@@ -0,0 +1,13 @@
import { describe, expect, it } from 'vitest';
import { browserCommand } from '../src/oauth/browser.js';
describe('OAuth browser launcher', () => {
it('preserves the complete OAuth query string on Windows without cmd.exe', () => {
const url = 'https://auth.cognitum.one/oauth/authorize?response_type=code&client_id=meta-proxy&state=test';
const launch = browserCommand(url, 'win32');
expect(launch.cmd).toBe('rundll32.exe');
expect(launch.args).toEqual(['url.dll,FileProtocolHandler', url]);
expect(launch.args[1]).toContain('&client_id=meta-proxy&');
});
});
@@ -0,0 +1,37 @@
/**
* PKCE (RFC 7636) generation tests — the port's correctness check against
* the same values meta-proxy's Rust `pkce.rs` test suite verifies.
*/
import { describe, it, expect } from 'vitest';
import { generate, challengeFromVerifier } from '../src/oauth/pkce.js';
describe('oauth/pkce', () => {
it('generates a verifier within RFC 7636 length bounds (43-128 chars)', () => {
const req = generate();
expect(req.codeVerifier.length).toBeGreaterThanOrEqual(43);
expect(req.codeVerifier.length).toBeLessThanOrEqual(128);
});
it('produces a deterministic challenge for a given verifier', () => {
const req = generate();
expect(challengeFromVerifier(req.codeVerifier)).toBe(req.codeChallenge);
});
it('never collides across two generations', () => {
const a = generate();
const b = generate();
expect(a.state).not.toBe(b.state);
expect(a.codeVerifier).not.toBe(b.codeVerifier);
expect(a.codeChallenge).not.toBe(b.codeChallenge);
});
it('matches the RFC 7636 Appendix B worked example', () => {
// The exact vector meta-proxy's pkce.rs test suite uses — confirms this
// port's encoding (base64url, no padding) and hash (SHA-256) match byte
// for byte, since a verifier generated here must validate against the
// same identity server meta-proxy already talks to successfully.
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
expect(challengeFromVerifier(verifier)).toBe('E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM');
});
});
+3
View File
@@ -18,6 +18,9 @@
"bcryptjs": "^3.0.3",
"zod": "^3.22.0"
},
"optionalDependencies": {
"@napi-rs/keyring": "1.3.0"
},
"devDependencies": {
"vitest": "^4.1.0"
},
+26
View File
@@ -134,6 +134,32 @@ export {
type ToolCallDecision,
} from './authorization/propagator.js';
// OAuth 2.0 + PKCE + OS Keychain (ADR-306)
// A TypeScript port of meta-proxy's proven oauth/{client,pkce,browser,
// callback_server}.rs — see src/oauth/client.ts for why this targets the
// live auth.cognitum.one surface rather than ADR-308's unconfirmed spec.
export {
CLIENT_ID as OAUTH_CLIENT_ID,
SCOPE as OAUTH_SCOPE,
OOB_REDIRECT_URI,
OAuthError,
authorizeUrl,
exchangeCode,
refreshToken,
exchangeManualCode,
type TokenResponse as OAuthTokenResponse,
} from './oauth/client.js';
export { generate as generatePkce, challengeFromVerifier, type PkceRequest } from './oauth/pkce.js';
export { CallbackServer, CallbackTimeoutError, type CallbackResult } from './oauth/callback-server.js';
export { openBrowser } from './oauth/browser.js';
// OS Keychain Adapter (ADR-306)
export {
createKeychainAdapter,
SessionOnlyKeychainAdapter,
type KeychainAdapter,
} from './keychain-adapter.js';
// Plugin Integrity Verifier (ADR-145 P1 — ruvnet/ruflo#2254)
// Install-layer: Ed25519 signature verification + trust-anchor allowlist.
// Stage-2 semantic-intent scan (SCH defence) lands in P2.
Binary file not shown.
@@ -0,0 +1,58 @@
/**
* Opens the system default browser for the `ruflo auth login` flow. A
* TypeScript port of meta-proxy's `src/oauth/browser.rs`.
*
* Deliberately does NOT go through `SafeExecutor.execute()`: `SafeExecutor`'s
* blocked-argument patterns (`safe-executor.ts`'s `DEFAULT_BLOCKED_PATTERNS`)
* include a bare `&`, which is meant to catch shell-metacharacter injection in
* command-line-style arguments — but it also appears in every real OAuth
* authorize URL's query string (`?a=1&b=2&...`), so passing one through would
* false-positive-reject on every real invocation. That blocklist is the wrong
* tool for a URL argument: with `shell: false` (used here, same as
* `SafeExecutor`), a single argv element containing `&` is inert — there's no
* shell to interpret it. The actual safety property that matters is "the URL
* was constructed by us from validated components, never from raw external
* input" (this module's `authorizeUrl()` in `client.ts` is the only caller),
* which `assertSafeUrl` below checks directly instead.
*
* @module v3/security/oauth/browser
*/
import { execFile } from 'node:child_process';
/** Throws if `url` isn't a well-formed https/http URL — the one check that matters here. */
function assertSafeUrl(url: string): void {
const parsed = new URL(url); // throws on malformed input
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
throw new Error(`refusing to open non-http(s) URL scheme: ${parsed.protocol}`);
}
}
/**
* Attempts to open `url` in the system default browser. Resolves whether or
* not a browser window actually appeared — this cannot be confirmed in
* general, which is why the caller always also prints the URL as a fallback.
*/
export function openBrowser(url: string): Promise<void> {
assertSafeUrl(url);
const { cmd, args } = browserCommand(url);
return new Promise((resolve) => {
execFile(cmd, args, { shell: false, windowsHide: true }, () => resolve());
});
}
/** Pure command selection, exported for platform regression tests. */
export function browserCommand(url: string, platform: NodeJS.Platform = process.platform): { cmd: string; args: string[] } {
assertSafeUrl(url);
if (platform === 'darwin') {
return { cmd: 'open', args: [url] };
} else if (platform === 'win32') {
// cmd.exe treats OAuth query-string `&` separators as command operators,
// truncating the URL before client_id. Use the URL handler without a shell.
return { cmd: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] };
} else {
return { cmd: 'xdg-open', args: [url] };
}
}
@@ -0,0 +1,97 @@
/**
* Ephemeral-port localhost callback server for the browser-based OAuth flow
* (ADR-306). A minimal single-request HTTP server — deliberately not a full
* framework for one GET route that lives for one request and then shuts
* down. A TypeScript port of meta-proxy's `src/oauth/callback_server.rs`.
*
* @module v3/security/oauth/callback-server
*/
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
export interface CallbackResult {
code: string | null;
state: string | null;
error: string | null;
}
const SUCCESS_PAGE = `<html>
<body style="background:#0a0a0a; color:#f5f5f5; font-family:sans-serif;
display:flex; align-items:center; justify-content:center;
height:100vh; margin:0;">
<div style="text-align:center;">
<h1>&#10003; ruflo login successful</h1>
<p>You can close this tab and return to your terminal.</p>
</div>
</body>
</html>`;
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes, matches meta-proxy's CALLBACK_TIMEOUT
export class CallbackTimeoutError extends Error {
constructor() {
super('timed out waiting for OAuth callback');
this.name = 'CallbackTimeoutError';
}
}
export class CallbackServer {
private constructor(
private readonly server: Server,
public readonly redirectUri: string,
public readonly port: number,
) {}
/**
* Binds `127.0.0.1:0` (OS-assigned ephemeral port) and returns the server
* plus the exact `redirect_uri` to send in the authorize request — must be
* the `http://127.0.0.1:<port>/oauth/callback` shape identity's
* `validate_redirect_uri` accepts.
*/
static async bind(): Promise<CallbackServer> {
return new Promise((resolve, reject) => {
const server = createServer();
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
const addr = server.address() as AddressInfo;
const redirectUri = `http://127.0.0.1:${addr.port}/oauth/callback`;
resolve(new CallbackServer(server, redirectUri, addr.port));
});
});
}
/**
* Waits for exactly one `GET /oauth/callback?...` request, replies with the
* browser success page, closes the server, and returns the parsed query
* parameters. Times out after `waitForMs` so a login attempt the user
* abandons in the browser doesn't hang the CLI forever.
*/
async awaitCallback(waitForMs = DEFAULT_TIMEOUT_MS): Promise<CallbackResult> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.server.close();
reject(new CallbackTimeoutError());
}, waitForMs);
this.server.once('request', (req, res) => {
clearTimeout(timer);
const url = new URL(req.url ?? '/oauth/callback', 'http://127.0.0.1');
const result: CallbackResult = {
code: url.searchParams.get('code'),
state: url.searchParams.get('state'),
error: url.searchParams.get('error'),
};
res.writeHead(200, {
'content-type': 'text/html; charset=utf-8',
connection: 'close',
});
res.end(SUCCESS_PAGE, () => {
this.server.close();
resolve(result);
});
});
});
}
}
@@ -0,0 +1,153 @@
/**
* HTTP client for `auth.cognitum.one`'s OAuth surface (ADR-306): authorize
* URL construction, `POST /oauth/token` (`authorization_code` and
* `refresh_token` grants), and `POST /v1/oauth/code-exchange` (OOB fallback).
*
* A TypeScript port of meta-proxy's `src/oauth/client.rs`
* (cognitum-one/meta-proxy) — same base URL, same endpoints, same
* form/query parameter names, confirmed live 2026-07-16 (a real
* `GET /oauth/authorize?...&client_id=meta-proxy&redirect_uri=<ruflo-controlled
* loopback>` returns a working consent page, not a redirect_uri-mismatch
* error — so this client reuses meta-proxy's registered `client_id` rather
* than requiring a new one).
*
* Deliberately NOT `api.cognitum.one/v1/auth/*` — that's what ruflo's own
* checked-in OpenAPI spec (v3/docs/api/cognitum-v1.openapi.yaml, ADR-308)
* describes, but it does not match what the real identity server serves.
* This client targets the proven, live surface instead.
*
* @module v3/security/oauth/client
*/
export const CLIENT_ID = 'meta-proxy';
export const SCOPE = 'inference';
/** RFC 8252 out-of-band sentinel — the OOB/manual-paste flow's `redirect_uri`. */
export const OOB_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob';
function authBaseUrl(): string {
const override = process.env.COGNITUM_AUTH_URL;
return override && override.trim() ? override : 'https://auth.cognitum.one';
}
export interface TokenResponse {
access_token: string;
token_type: string;
account_email?: string;
refresh_token?: string;
expires_in?: number;
}
interface OAuthErrorBody {
error: string;
error_description: string;
}
export class OAuthError extends Error {
constructor(
message: string,
public readonly code: 'network' | 'protocol' | 'unexpected_shape',
public readonly oauthError?: string,
public readonly oauthDescription?: string,
) {
super(message);
this.name = 'OAuthError';
}
}
/** Builds the `/oauth/authorize` URL for the standard loopback-redirect flow. */
export function authorizeUrl(redirectUri: string, state: string, codeChallenge: string): string {
const url = new URL(`${authBaseUrl()}/oauth/authorize`);
url.searchParams.set('response_type', 'code');
url.searchParams.set('client_id', CLIENT_ID);
url.searchParams.set('redirect_uri', redirectUri);
url.searchParams.set('scope', SCOPE);
url.searchParams.set('state', state);
url.searchParams.set('code_challenge', codeChallenge);
url.searchParams.set('code_challenge_method', 'S256');
return url.toString();
}
async function parseTokenResponse(resp: Response): Promise<TokenResponse> {
if (resp.ok) {
try {
return (await resp.json()) as TokenResponse;
} catch {
throw new OAuthError('unexpected response shape from the server', 'unexpected_shape');
}
}
try {
const body = (await resp.json()) as OAuthErrorBody;
throw new OAuthError(
`oauth error: ${body.error} — ${body.error_description}`,
'protocol',
body.error,
body.error_description,
);
} catch (e) {
if (e instanceof OAuthError) throw e;
throw new OAuthError('unexpected response shape from the server', 'unexpected_shape');
}
}
async function postForm(path: string, form: Record<string, string>, base = authBaseUrl()): Promise<TokenResponse> {
let resp: Response;
try {
resp = await fetch(`${base}${path}`, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(form).toString(),
});
} catch (e) {
throw new OAuthError(`network error: ${e instanceof Error ? e.message : String(e)}`, 'network');
}
return parseTokenResponse(resp);
}
/** `POST /oauth/token` with `grant_type=authorization_code`. */
export async function exchangeCode(
code: string,
codeVerifier: string,
redirectUri: string,
base = authBaseUrl(),
): Promise<TokenResponse> {
return postForm(
'/oauth/token',
{ grant_type: 'authorization_code', code, code_verifier: codeVerifier, client_id: CLIENT_ID, redirect_uri: redirectUri },
base,
);
}
/**
* `POST /oauth/token` with `grant_type=refresh_token`. identity rotates
* refresh tokens with reuse detection: presenting a refresh token returns a
* NEW refresh token and revokes the old one, and re-presenting a spent one
* revokes the whole session family. Callers MUST persist the returned
* `refresh_token` atomically before using the new access token, and must
* never retry a failed refresh with the same token.
*/
export async function refreshToken(refreshTokenValue: string, base = authBaseUrl()): Promise<TokenResponse> {
return postForm('/oauth/token', { grant_type: 'refresh_token', refresh_token: refreshTokenValue, client_id: CLIENT_ID }, base);
}
/**
* `POST /v1/oauth/code-exchange` — the OOB manual-entry fallback for
* headless/SSH/container environments where no browser round-trip to
* `127.0.0.1` is reachable.
*/
export async function exchangeManualCode(
code: string,
codeVerifier: string,
base = authBaseUrl(),
): Promise<TokenResponse> {
let resp: Response;
try {
resp = await fetch(`${base}/v1/oauth/code-exchange`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ code, code_verifier: codeVerifier, client_id: CLIENT_ID }),
});
} catch (e) {
throw new OAuthError(`network error: ${e instanceof Error ? e.message : String(e)}`, 'network');
}
return parseTokenResponse(resp);
}
@@ -0,0 +1,45 @@
/**
* OAuth 2.0 + PKCE (RFC 7636) client-side generation (ADR-306).
*
* A TypeScript port of meta-proxy's `src/oauth/pkce.rs` (cognitum-one/meta-proxy,
* itself ported from `dashboard/apps/cli/src/pkce.rs`) so a verifier generated
* here validates against the same `services/identity` authorization server
* meta-proxy already talks to successfully — same byte lengths, same encoding,
* same hash. Intentionally duplicated rather than imported from
* `@claude-flow/mcp/src/oauth.ts` (a different, unrelated OAuth client in this
* monorepo) — ADR-306 assigns PKCE ownership to this package specifically.
*
* @module v3/security/oauth/pkce
*/
import { randomBytes, createHash } from 'crypto';
export interface PkceRequest {
state: string;
codeVerifier: string;
codeChallenge: string;
}
/**
* 32 random bytes, base64url-encoded (no padding) — comfortably within RFC
* 7636's 43-128 character verifier length requirement (32 bytes -> 43 chars).
* Matches the Rust port's `random_url_safe_token(32)` exactly.
*/
function randomUrlSafeToken(byteLen: number): string {
return randomBytes(byteLen).toString('base64url');
}
export function challengeFromVerifier(verifier: string): string {
return createHash('sha256').update(verifier).digest('base64url');
}
/**
* Generates a fresh `state` + PKCE verifier/challenge pair for one login
* attempt.
*/
export function generate(): PkceRequest {
const state = randomUrlSafeToken(32);
const codeVerifier = randomUrlSafeToken(32);
const codeChallenge = challengeFromVerifier(codeVerifier);
return { state, codeVerifier, codeChallenge };
}
@@ -105,3 +105,27 @@ The repository already carries an internal meta-llm gateway surface (`metallm_as
- New CLI surface: `ruflo proxy …` — full lifecycle command set (`install|start|stop|status|logs|update|uninstall`) specified in ADR-307, plus `proxy config` for routing mode.
- `ruflo doctor` gains a proxy health check component (details in ADR-307).
- This is the conversion product the ADR-301/302/303 touchpoints funnel toward; activation rate is a North Star metric in ADR-305.
## Addendum (2026-07-16) — `ruflo proxy config` implemented; real TOML wire values confirmed
`ruflo proxy config --cloud [--yes] | --local-only` is implemented in
`v3/@claude-flow/cli/src/commands/proxy.ts` (`configSub`), reusing the same consent-gated
disclosure pattern the ADR-313/314/315 subcommands in that file already use
(`hasConsent`/`recordConsent`/`revokeConsent` against the `cloud-routing` consent domain, plus a
TOML mirror write to `proxy-config.toml`).
**The exact wire value was confirmed two ways, not assumed**: reading meta-proxy's actual
`DataPlane` enum (`src/config.rs`) showed `#[derive(Serialize, Deserialize)]` +
`#[serde(rename_all = "snake_case")]` — so the TOML field is `default_data_plane = "<value>"`
with `"local"` / `"cloud"` / `"sponsored"` / `"passthrough"` (lowercase; snake_case has no effect
on these single-word variant names beyond lowercasing). This was cross-checked behaviorally
against the real v0.1.0 binary: `default_data_plane = "Local"` (PascalCase, the wrong guess)
silently fell back to the default plane (Passthrough) rather than erroring — consistent with this
ADR's own "a malformed config must never crash the proxy" design, but a real trap for anyone
guessing the casing from the Rust variant names alone. `"local"` (lowercase) took a visibly
different code path in the same test. Only `"local"`/`"cloud"` are written by this command;
`"sponsored"` stays owned by ADR-313's own `sponsor-enable`/`sponsor-disable`, and `"passthrough"`
is never written (the proxy's own untouched default).
`ruflo proxy config` (no flags) reports the current plane by reading the same file, defaulting to
`"passthrough"` (matching the Rust struct's own default) when no config file exists yet.
@@ -54,3 +54,57 @@ hosted.memory.use ← consent domain: hosted-memory (new; same receipt rules
- `@claude-flow/security` owns token handling primitives (keychain adapters, PKCE verifier generation); no other package touches token material.
- `ruflo doctor` gains an auth component (keychain availability, token expiry, scope-vs-receipt consistency check).
- The scope-vs-receipt consistency check is enforced client-side on every authenticated call: a scope with no receipt drops the capability and reports, fail-closed.
## Addendum (2026-07-16) — implemented against the proven surface, not the ADR-308 spec
`ruflo auth login|logout|status` is implemented in `v3/@claude-flow/cli/src/auth/` +
`src/commands/auth.ts`, backed by a new OAuth+PKCE+keychain module in `@claude-flow/security`
(`src/oauth/{client,pkce,browser,callback-server}.ts`, `src/keychain-adapter.ts`). Two decisions
made during implementation, differing from this ADR's original text:
- **Targets `auth.cognitum.one/oauth/{authorize,token}` + `/v1/oauth/code-exchange`, NOT
`api.cognitum.one/v1/auth/{device,token,revoke}`.** The latter is what ADR-308's checked-in
OpenAPI spec describes, but reading meta-proxy's actual, currently-shipping OAuth client
(`oauth/client.rs`) showed it hits a different host and a different path scheme entirely — and
meta-proxy's flow is real, tested, and working in production. Building against ADR-308's spec
would have meant shipping a client for endpoints nobody has confirmed exist. This is a genuine
drift between what was specified and what the identity server actually serves — see the
ADR-308 addendum.
- **Reuses meta-proxy's registered `client_id=meta-proxy`, not a new `ruflo`-specific
registration.** Confirmed live 2026-07-16: `GET /oauth/authorize` with `client_id=meta-proxy`
and an arbitrary ruflo-controlled loopback `redirect_uri` returns a working consent page, not a
redirect_uri-mismatch error — so `services/identity`'s `validate_redirect_uri` does not enforce
a per-client exact-URI allowlist for this client, at least today. This is empirical behavior,
not a documented contract, and could tighten later; if it ever does, `ruflo auth` needs its own
registered client as a follow-up, not a silent breakage.
- **Device flow (RFC 8628) was not built as a separate mechanism.** The OOB/manual-paste flow
meta-proxy already implements (`--no-browser`: print an authorize URL with the
`urn:ietf:wg:oauth:2.0:oob` redirect, prompt for a pasted code, exchange it via
`/v1/oauth/code-exchange`) serves the same headless use case this ADR's "device authorization
flow" row describes, and is what was ported. A true RFC 8628 device-code polling flow is not
implemented and is not currently known to exist on the identity server.
`@claude-flow/security` is only an `optionalDependency` of the CLI — `ruflo auth` degrades to a
clear, specific error (not a raw `ERR_MODULE_NOT_FOUND`) when it's absent, via
`auth/security-bridge.ts`'s lazy-load wrapper.
### Addendum (2026-07-16) — demand-driven silent refresh is wired
`src/auth/client.ts::getValidAccessToken(profile)` is now the single consumer-facing token
accessor. It returns an in-process token only when more than 60 seconds of validity remain;
otherwise it loads the profile's refresh token from the OS keychain and performs exactly one
refresh. Cognitum rotates refresh tokens with reuse detection, so the returned refresh token is
written to the keychain **before** the new access token is placed in process memory or returned.
If that keychain write fails, the access token is not published and the spent refresh token is
not retried by this layer.
The accessor also enforces the scope-to-consent invariant before returning any token. Profiles
without a persisted refresh token fail with an explicit session-only/login-required error rather
than persisting token material elsewhere.
Refresh remains demand-driven, not timer-driven: plain `ruflo auth status` reads cached identity
metadata and performs no network request, preserving this ADR's offline behavior. `ruflo auth
status --check` is the first explicit consumer; it validates the selected profile(s), silently
refreshes when necessary, and reports only credential state (`valid`, `login-required`, or
`unavailable`) — never token material. Future authenticated Cognitum API calls must use this same
accessor rather than reading the keychain or session cache directly.
@@ -65,3 +65,89 @@ Default state after install is local-only routing; cloud routing activates only
- A new repository/workspace for the Rust proxy with its own release pipeline; ruflo pins compatible proxy versions per release.
- `ruflo doctor --component proxy` checks: binary signature, version compatibility, bind address, token file permissions, service unit state.
- Failure isolation holds (ADR-304): proxy down → normal connection error; the proxy never silently reroutes local-only traffic to cloud (ADR-308 failure policy).
## Addendum (2026-07-16) — implementation reality check + injected-token bridge design
The lifecycle command set (`install|start|stop|status|logs|update|uninstall`) is now implemented
in `v3/@claude-flow/cli/src/proxy/{paths,release,verify,install,lifecycle}.ts` +
`src/commands/proxy-lifecycle.ts`, verified end-to-end against the real `cognitum-one/meta-proxy`
v0.1.0 release on Windows (install → Ed25519+checksum verify → extract → place → start → real
HTTP request against the running server, enforcing its bearer token → stop). Findings that
correct or firm up this ADR's assumptions:
- **Release signing, confirmed exactly as specified**: ONE combined `SHA256SUMS.sig`
(raw Ed25519, base64, over the exact bytes of `SHA256SUMS`) per release, not a per-binary
signature — `crypto.verify(null, sumsBytes, pubkey, sigBuffer)` against the pinned SPKI key
committed in meta-proxy's `signing-key.pub.pem`. Asset naming:
`meta-proxy-<version>-<target-triple>.<tar.gz|zip>`, 5 published triples (macOS arm64/x64,
Linux x64/arm64 gnu, Windows x64 msvc).
- **`meta-proxy` has no `--version`/`--help` flag** — any invocation starts the live server as a
side effect. `ruflo doctor`'s binary check must never spawn the binary to probe a version;
version comes from the install manifest ruflo writes at install time plus, once running, the
proxy's own `/status` endpoint. **Now implemented**: `checkProxyProcess` calls
`GET /status` (bearer-token-authed with the local `proxy-token`, 2s timeout) only after PID
signal-0 liveness already confirmed a process is running. Confirmed response shape against the
real v0.1.0 binary:
```json
{"version":"0.1.0","data_plane":"passthrough:anthropic","bind":"127.0.0.1:11435","sponsored_available":false,"proxy_token_valid":true}
```
A version mismatch against the install manifest is a `warn` ("a stale process from a previous
version?"), not a `fail` — the process is genuinely running, just possibly stale.
`/status` being unreachable (still starting up, or a network hiccup) does not downgrade an
already-passed PID-liveness check to a warning; it's reported inline on the `pass` result.
- **Production release distribution is implemented.** Signed artifacts are published to the
public `cognitum-one/meta-proxy-dist` repository while source remains private. `ruflo proxy
install` performs bounded unauthenticated downloads, then verifies the pinned Ed25519 signature
over `SHA256SUMS` and the selected archive checksum before extraction. The dev-only private-repo
`gh` path remains available behind `RUFLO_DEV_PROXY_INSTALL=1` for maintainers.
- **OS service-manager registration (launchd/systemd/Windows Service) is deliberately deferred.**
`start --service` ships as a detached background process + PID file + log file for v1 — "survives
terminal close, not a reboot" — with an honest status line rather than three divergent,
hard-to-test OS integrations, one of which (a real Windows Service) typically needs elevation
and would contradict this ADR's own "never requires elevation" line.
### Injected-token bridge (draft design for meta-proxy, NOT implemented in meta-proxy — ruflo side only)
ADR-306 gives `ruflo auth` its own OAuth implementation (a TypeScript port of meta-proxy's proven
`oauth/{client,pkce,browser,callback_server}.rs`, reusing meta-proxy's registered `client_id` —
confirmed live 2026-07-16 that `auth.cognitum.one` accepts an arbitrary ruflo-controlled loopback
`redirect_uri` for that client without a new registration). `ruflo`'s access token is deliberately
process-memory-only (never written to disk), while meta-proxy is a long-running daemon needing a
durable credential — so a bridge has to be `ruflo` *actively pushing* a token, not meta-proxy
reading a file that already holds one.
**Sketch, not implemented**: `ruflo proxy start` (once logged in with `proxy.use` scope) writes
`~/.ruflo/proxy-injected-token` (0600, deliberately separate from `auth.json`) containing the
bearer string + expiry, refreshed on an interval (~every 8 min, given the 15-minute access-token
lifetime) by ruflo's own refresh loop while it supervises the process. Meta-proxy's
`oauth::cloud_auth::resolve()` would gain ONE new highest-priority branch (checked before its
existing two — own OAuth token, own `cog_` key): read `~/.ruflo/proxy-injected-token` (path
overridable via a new, additive `ruflo_injected_token_path: Option<PathBuf>` field, meta-proxy
`ProxyConfig`'s 13th field, none of the current 12 touched); if present/parseable/unexpired, use
it as Bearer; on any failure, fall through silently to the existing two branches. `meta-proxy
login` would keep working completely unchanged for existing users.
**Explicitly unresolved, not hand-waved**: who runs the refresh pump in `--service`/background
mode, since `ruflo` itself is not resident once `start --service` detaches. This needs its own
design pass — most likely the refresh loop has to live inside the same detached background
process `ruflo` spawns for itself, which is a larger change than this addendum's scope — before
any Rust is written or a PR opened against `cognitum-one/meta-proxy`. Not implemented in this
branch; parked here as the design starting point for that follow-up.
### Ruflo-side gap closure (2026-07-16)
The three client-side gaps found during the implementation review are closed:
1. `ruflo proxy config --cloud [--yes] | --local-only` now writes the confirmed lowercase
`default_data_plane` wire values and maintains the `cloud-routing` consent receipt (ADR-304
addendum).
2. `ruflo doctor --component proxy` now authenticates to the live process's `/status` endpoint
after PID liveness succeeds, reporting the data plane and warning on a running-vs-installed
version mismatch.
3. ADR-306's refresh implementation now has a demand-driven consumer through `getValidAccessToken`
and `ruflo auth status --check`, including refresh-token rotation ordering and fail-closed
scope/consent checks.
The bridge is implemented by meta-proxy v0.2.0 and ruflo's resident supervisor: only the short-lived
access token crosses the process boundary, while ruflo retains the rotating refresh token in the OS
keychain. Production installation is implemented through the signed public distribution channel.
@@ -52,3 +52,22 @@ GET /v1/credits # credit balances (the single credit auth
- The OpenAPI spec is the review artifact for any server change that touches the CLI; PRs to either repo that change the boundary must update the shared spec first.
- Contract tests run in ruflo CI against a mock server generated from the spec — the funnel surfaces are testable with zero network and no Cognitum dependency.
- `GET /v1/funnel-policy` responses are Ed25519-signed with the same key-management discipline as the helper channel; the CLI validates signature + policy schema before honoring anything (ADR-305 freshness kill switch is inert otherwise).
## Addendum (2026-07-16) — the `/v1/auth/*` contract does not match the live identity server
While implementing ADR-306, reading meta-proxy's actual, currently-shipping OAuth client
(`oauth/client.rs` in `cognitum-one/meta-proxy`, real integration tests passing against
production) showed it targets `auth.cognitum.one/oauth/{authorize,token}` +
`auth.cognitum.one/v1/oauth/code-exchange` — a different host AND a different path scheme than
this ADR's `/v1/auth/{device,token,revoke}` on `api.cognitum.one`. No open issue or PR in either
`meta-proxy` or `dashboard` (which has its own separate, third, already-production OAuth+keychain
CLI — `apps/cli`, per dashboard's ADR-005 — with its own endpoint usage not yet cross-checked
against this spec either) discusses reconciling this.
This is real drift between a checked-in contract and production reality, not a hypothetical
future risk: `ruflo auth` (ADR-306) was implemented against the proven `auth.cognitum.one`
surface instead of this ADR's `/v1/auth/*` shape, specifically to avoid shipping a client for
endpoints nobody has confirmed exist. The `v3/docs/api/cognitum-v1.openapi.yaml` spec checked
into this repo is consequently aspirational for the auth endpoints, not authoritative — flagged
here rather than silently left to mislead the next person who builds against it. Reconciling the
spec with reality (or vice versa) needs the API/identity owners, not a unilateral client-side fix.
+132
View File
@@ -512,6 +512,10 @@ importers:
zod:
specifier: ^3.22.0
version: 3.25.76
optionalDependencies:
'@napi-rs/keyring':
specifier: 1.3.0
version: 1.3.0
devDependencies:
vitest:
specifier: '>=4.1.0'
@@ -1695,6 +1699,134 @@ packages:
transitivePeerDependencies:
- supports-color
/@napi-rs/keyring-darwin-arm64@1.3.0:
resolution: {integrity: sha512-pl76hJvdYUBn6I24bXiOBMA9nbDapo3I5B+f3OorjDU4dUMSypXeKbOVehJe8fhgTiH24flMyTS3aAIy43xegQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-darwin-x64@1.3.0:
resolution: {integrity: sha512-YcJtEV5LA3cvA4z3BurgxH5IhTsW1JfIvcAAcqcecwk06Si9F9NqkxbZVIfDwQ8oRHgaBmT3zZJnLAotCrVahw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-freebsd-x64@1.3.0:
resolution: {integrity: sha512-vlLf31TGhfRAaxLDBhg8b89ss0HHD/lyNmL5F3UjSaz5CUXElsJmKYq9fqA/B+cZKUEUcLHHGhF0I/CqcFdaVw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [freebsd]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-linux-arm-gnueabihf@1.3.0:
resolution: {integrity: sha512-KiWdMMu/Inz/bHHIAGrnF7r54FZDYXuHO6UFF/rhIrshUsxbMG1Rl9lEymNtqqsVo927G0VYcb02FzWQ3iBQRQ==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-linux-arm64-gnu@1.3.0:
resolution: {integrity: sha512-eyKGpY40lm9Jvs1aD294XRH4y7+TlJM0YVAryZeXA6TX0mb4gMkxVXwSQv7MCwgah7raeUd0dKUb4BPAYIgcMg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-linux-arm64-musl@1.3.0:
resolution: {integrity: sha512-iIK6JWHXAJqDrEyLY3TmswwloVyt2vj+04TZnew+uSJ9gnDO8EwRbp3/iw3LpWaXiDO7VomGO6y8I0Id8uBZSw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-linux-riscv64-gnu@1.3.0:
resolution: {integrity: sha512-/PGqrwn6EwgtK6vccASSXJRfOSP4vN1F4ASsIQ+7MdrK6hNvAJ1FZPrIuD5gGGdxezo3F++To2Wq7DbuGIeuNQ==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-linux-x64-gnu@1.3.0:
resolution: {integrity: sha512-2PDK1WKWTu9lBGq9VvNEkSlQD3O7YwVpmnyN2M3cy4v7NJ/8gDMd9GXv3G+FVXN13uhp4gnnPBS+ScefmEeD2A==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-linux-x64-musl@1.3.0:
resolution: {integrity: sha512-oJ2HkX8YUo46QBkn0pG+HuIKQNqr523q6vBobCn+P95s4C4K6/kLBqHY/1bg5J4ap31DzsznhnFKcfBNBsjCnw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-win32-arm64-msvc@1.3.0:
resolution: {integrity: sha512-tOd3c/uAaeoE4ycVlmAdSvygz0Zt3zdca6Y7gokBeIbaRDWpjDIUOpU3MvML59XAaqyuKGsVVu0F/DZb1lHPmw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-win32-ia32-msvc@1.3.0:
resolution: {integrity: sha512-sPSqeAFZMGqP1R++M2JTza7GQJJ/TpCo6JU6Vcd4jnebvOaEDs9b7eipakU1PJdSvhpC2yXMCNRk9gXfrhuwHQ==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring-win32-x64-msvc@1.3.0:
resolution: {integrity: sha512-4DnCWXwDc0HRKwyRlG5y0VhKZW2tNRQfKKfyj6IX/KWfDNyq9hn4n+GL1auyDcOO/v8PwnhmYo2+rOOqCkvvOg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
requiresBuild: true
dev: false
optional: true
/@napi-rs/keyring@1.3.0:
resolution: {integrity: sha512-WrOw/bcXm0f9qHkumlT1QlArXSTWqaY9sunsDpOk+yCCorCKMxvWT/a3xko4EYHVdeZoh00yI2TydXn6eyICDA==}
engines: {node: '>= 10'}
requiresBuild: true
optionalDependencies:
'@napi-rs/keyring-darwin-arm64': 1.3.0
'@napi-rs/keyring-darwin-x64': 1.3.0
'@napi-rs/keyring-freebsd-x64': 1.3.0
'@napi-rs/keyring-linux-arm-gnueabihf': 1.3.0
'@napi-rs/keyring-linux-arm64-gnu': 1.3.0
'@napi-rs/keyring-linux-arm64-musl': 1.3.0
'@napi-rs/keyring-linux-riscv64-gnu': 1.3.0
'@napi-rs/keyring-linux-x64-gnu': 1.3.0
'@napi-rs/keyring-linux-x64-musl': 1.3.0
'@napi-rs/keyring-win32-arm64-msvc': 1.3.0
'@napi-rs/keyring-win32-ia32-msvc': 1.3.0
'@napi-rs/keyring-win32-x64-msvc': 1.3.0
dev: false
optional: true
/@noble/ed25519@2.3.0:
resolution: {integrity: sha512-M7dvXL2B92/M7dw9+gzuydL8qn/jiqNHaoR3Q+cb1q1GHV7uwE17WCyFMG+Y+TZb5izcaXk5TdJRrDUxHXL78A==}
dev: false