@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
114 lines (113 loc) • 5.44 kB
JavaScript
import { mkdir, open, unlink } from "node:fs/promises";
import path from "node:path";
import { detectHost } from "./git-hosts.js";
import { resolveAgentToken } from "./git-host-auth.js";
import { BridgeError } from "./protocol.js";
/**
* The gitboy path's credentials. The Hook's stored `gba_` agent token is the
* only one a keyed dispatch may use: a credential helper in the worktree's own
* config answers git, and the agent environment carries the same token for the
* API. The token never enters argv, a remote URL or a log.
*/
/** Variables a keyed worker may inherit from the Hook's own environment. */
export const KEYED_ENV_ALLOW = ["HOME", "USER", "LOGNAME", "PATH", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR"];
const KEYED_ENV_CONFIG_DIRS = ["CODEX_HOME", "CLAUDE_CONFIG_DIR"];
/**
* The exact environment for a keyed worker: a small allowlist plus the values
* this Hook owns. Nothing else from process.env is copied, so no caller or
* Hook token reaches the harness.
*/
export function keyedExplicitEnv(base = process.env, extra = {}) {
const env = {};
for (const key of [...KEYED_ENV_ALLOW, ...KEYED_ENV_CONFIG_DIRS]) {
const value = base[key];
if (typeof value === "string")
env[key] = value;
}
return { ...env, ...extra };
}
/** The credential-free HTTPS remote for a gitboy host, or a refusal when owner/repo cannot be derived. */
export function credentialFreeRemote(host) {
if (!host.domain || !host.webUrl)
throw new BridgeError(409, "This gitboy checkout has no owner/repository in its remote URL, so a keyed dispatch cannot use it.");
let pathname;
try {
pathname = new URL(host.webUrl).pathname;
}
catch {
throw new BridgeError(409, "This gitboy checkout's remote URL cannot be parsed.");
}
const parts = pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
if (parts.length !== 2 || !parts[0] || !parts[1])
throw new BridgeError(409, "This gitboy checkout has no owner/repository in its remote URL, so a keyed dispatch cannot use it.");
return `https://${host.domain}/${parts[0]}/${parts[1]}.git`;
}
/** Write the agent token to an exact private file path. */
export async function writeAgentTokenFileAt(file, token) {
if (!path.isAbsolute(file) || path.basename(file) !== "phren-agent-token")
throw new BridgeError(409, "The agent token file path is not valid.");
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
const handle = await open(file, "wx", 0o600).catch(error => {
if (error.code === "EEXIST")
throw new BridgeError(409, "An agent token file already exists in this checkout; close the earlier dispatch first.");
throw error;
});
try {
await handle.writeFile(token);
await handle.sync();
}
finally {
await handle.close();
}
return file;
}
/** Remove a token file this Hook wrote; only the expected file name is ever touched. */
export async function removeAgentTokenFile(file) {
if (!file || !path.isAbsolute(file) || path.basename(file) !== "phren-agent-token")
return;
await unlink(file).catch(() => undefined);
}
/**
* A keyed dispatch in a gitboy checkout uses this computer's stored agent token
* and fails closed when there is none. The token goes to a 0600 file; the agent
* gets only GITBOY_TOKEN_FILE (and, for a clone, its managed GIT_CONFIG_GLOBAL).
*/
export async function prepareKeyedGitboy(cwd, options) {
const host = await detectHost(cwd, "");
// Keyed dispatches exist for gitboy's runner. A checkout Phren can't place
// on a gitboy host with an agent token is refused, never launched with
// whatever git credentials the computer happens to have.
const stored = host.domain ? await resolveAgentToken(host.domain) : undefined;
if (!host.domain || !stored) {
const domain = host.domain ?? "this checkout's host";
throw new BridgeError(409, `No gitboy agent token for ${domain}. Run phren bridge git-host set ${domain} gitboy with a gba_ token.`);
}
const tokenFile = await writeAgentTokenFileAt(options.tokenFile, stored.token);
return {
env: {
GITBOY_HOST: host.domain,
GITBOY_TOKEN_FILE: tokenFile,
GIT_TERMINAL_PROMPT: "0",
...(options.gitConfigFile ? { GIT_CONFIG_GLOBAL: options.gitConfigFile, GIT_CONFIG_NOSYSTEM: "1" } : {}),
},
tokenFile,
};
}
/** A git credential request for a host with a stored gitboy token, answered for `get` only. */
export async function gitCredentialAnswer(request) {
const protocol = /(?:^|\n)protocol=(.+)/.exec(request)?.[1]?.trim().toLowerCase();
const host = /(?:^|\n)host=(.+)/.exec(request)?.[1]?.trim().toLowerCase().replace(/\.$/, "").replace(/:\d+$/, "");
if (protocol !== "https" || !host)
return undefined;
const stored = await resolveAgentToken(host);
if (!stored)
return undefined;
return { username: "x-token", password: stored.token };
}
/** The `phren bridge git-credential` helper: get answers, store and erase do nothing. */
export async function gitCredentialCommand(operation, request) {
if (operation !== "get")
return undefined;
const answer = await gitCredentialAnswer(request);
return answer ? `username=${answer.username}\npassword=${answer.password}\n` : undefined;
}