@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
147 lines (146 loc) • 8.39 kB
JavaScript
/** Machine-local credential failures shared by session hooks, polling and doctor. */
import * as fs from "fs";
import { createHash } from "node:crypto";
import { atomicWriteText, runtimeFile } from "../phren-paths.js";
import { tryFileLock, withFileLock } from "../governance/locks.js";
import { runGit } from "../utils-helpers.js";
import { healStoreAuth } from "./auth-heal.js";
import { gitAuthEnvironment, gitAuthErrorText, scrubGitAuthText } from "./auth-diagnostics.js";
import { appendSyncLog } from "./outcome.js";
export const AUTH_BACKOFF_INITIAL_MS = 60 * 60 * 1000;
export const AUTH_BACKOFF_MAX_MS = AUTH_BACKOFF_INITIAL_MS;
export const AUTH_UNREGISTER_AFTER_MS = 7 * 24 * 60 * 60 * 1000;
function remoteIdentity(remote) {
const safe = scrubGitAuthText(remote);
return safe === remote ? { remote } : { remote: safe, remoteFingerprint: createHash("sha256").update(remote).digest("hex") };
}
function matchesRemote(state, current) {
const identity = remoteIdentity(current.remote);
return state.remoteName === current.remoteName && state.remote === identity.remote && state.remoteFingerprint === identity.remoteFingerprint;
}
export function isGitAuthFailure(error) {
const value = error;
const message = [typeof error === "string" ? error : value?.message, value?.stderr, value?.error].filter(Boolean).join("\n");
return /could not read (?:Username|Password)|authentication failed|terminal prompts disabled|permission denied \(publickey\)|could not (?:read|get) (?:a )?password/i.test(message)
|| /\b(?:HTTP(?:\/[\d.]+)?|(?:returned )?error|status(?: code)?)[:\s]+(?:401|403)\b|\b(?:401 Unauthorized|403 Forbidden)\b|^(?:401|403)$/im.test(message);
}
export function readStoreAuthFailure(cwd) {
try {
const state = JSON.parse(fs.readFileSync(runtimeFile(cwd, "sync-auth.json"), "utf8"));
if (typeof state?.remote !== "string" || !state.remote || typeof state.remoteName !== "string" || !state.remoteName)
return;
if (![state.firstFailedAt, state.lastFailedAt, state.retryAt, state.failures].every(Number.isFinite))
return;
if (state.firstFailedAt < 0 || state.lastFailedAt < state.firstFailedAt || state.retryAt < state.lastFailedAt || state.failures < 1)
return;
return {
...state,
...remoteIdentity(state.remote),
retryAt: Math.min(state.retryAt, state.lastFailedAt + AUTH_BACKOFF_MAX_MS),
firstError: typeof state.firstError === "string" ? gitAuthErrorText(state.firstError) : undefined,
environment: typeof state.environment === "string" ? state.environment : undefined,
};
}
catch {
return;
}
}
export function clearStoreAuthFailure(cwd) {
fs.rmSync(runtimeFile(cwd, "sync-auth.json"), { force: true });
}
/** Read Git's effective URL, including insteadOf rewrites, without contacting it. */
export function storeSyncRemote(cwd, name, push = false) {
const git = (args) => runGit(cwd, args, 5000);
const branch = name ? null : git(["symbolic-ref", "--quiet", "--short", "HEAD"]);
const pushRemote = push && ((branch && git(["config", "--get", `branch.${branch}.pushRemote`])) || git(["config", "--get", "remote.pushDefault"]));
const remoteName = name || pushRemote || (branch && git(["config", "--get", `branch.${branch}.remote`])) || "origin";
if (remoteName === ".")
return;
const remote = git(["remote", "get-url", ...(push ? ["--push"] : []), "--", remoteName]);
return remote ? { remoteName, remote } : undefined;
}
/** Changing the configured remote immediately releases the old credential block. */
export function activeStoreAuthFailure(cwd, state = readStoreAuthFailure(cwd)) {
if (!state)
return;
const current = storeSyncRemote(cwd);
return current && matchesRemote(state, current) ? state : undefined;
}
export function authBackoffActive(state, now = Date.now()) {
return Boolean(state && now < state.retryAt);
}
export function storeAuthDetail(state) {
return `needs credentials: ${state.remote}; next retry ${new Date(state.retryAt).toISOString()}`;
}
export function storeAuthDoctorDetail(state) {
return [storeAuthDetail(state), state.environment, state.firstError].filter(Boolean).join("\n");
}
export function recordStoreAuthFailure(cwd, remoteName, remote, now = Date.now(), error) {
return withFileLock(runtimeFile(cwd, "sync-auth-state"), () => {
const previous = readStoreAuthFailure(cwd);
const sameRemote = previous && matchesRemote(previous, { remoteName, remote });
const failures = sameRemote ? Math.min(previous.failures + 1, 32) : 1;
const firstError = (sameRemote ? previous.firstError : undefined) ?? gitAuthErrorText(error);
const environment = (sameRemote ? previous.environment : undefined) ?? gitAuthEnvironment(cwd);
const state = {
...remoteIdentity(remote), remoteName, failures, firstError, environment,
firstFailedAt: sameRemote ? previous.firstFailedAt : now,
lastFailedAt: now,
retryAt: now + AUTH_BACKOFF_MAX_MS,
};
atomicWriteText(runtimeFile(cwd, "sync-auth.json"), JSON.stringify(state) + "\n");
if (firstError && (!sameRemote || !previous.firstError)) {
appendSyncLog(cwd, "auth", `${storeAuthDetail(state)} (${environment})\n${firstError}`);
}
return state;
});
}
/** Only transport failures affect credentials; local merge errors never do. */
export function withStoreAuthBackoff(git, now = Date.now) {
return async (cwd, args) => {
if (!["fetch", "pull", "push", "ls-remote"].includes(args[0]))
return git(cwd, args);
const separator = args.indexOf("--");
const remote = storeSyncRemote(cwd, separator >= 0 ? args[separator + 1] : undefined, args[0] === "push");
if (!remote)
return git(cwd, args);
// Serialize transport probes across processes so startup and polling share one retry.
const release = tryFileLock(runtimeFile(cwd, "sync-auth-probe"));
if (!release)
return { ok: false, output: "", error: "Store remote check deferred: another sync is running." };
try {
const previous = readStoreAuthFailure(cwd);
const block = previous && matchesRemote(previous, remote) ? previous : undefined;
if (block && authBackoffActive(block, now())) {
return { ok: false, output: "", error: storeAuthDetail(block) };
}
// An existing ls-remote is already cheap and its caller needs the requested refs.
const probe = Boolean(block) && args[0] !== "ls-remote";
const checked = await git(cwd, probe ? ["ls-remote", "--quiet", "--", remote.remoteName, "HEAD"] : args);
const authFailed = !checked.ok && isGitAuthFailure(checked);
const healed = authFailed ? await healStoreAuth(cwd, remote.remoteName, remote.remote, git, now()) : undefined;
const resume = healed?.healed || (probe && checked.ok);
// A non-auth failure also stops the block from aging toward unregister.
if (block && (resume || !authFailed))
clearStoreAuthFailure(cwd);
const result = resume ? await git(cwd, args) : checked;
if (result.ok)
return result;
if (!isGitAuthFailure(result)) {
return probe ? { ok: false, output: "", error: gitAuthErrorText(result) } : result;
}
const healDetail = healed?.detail;
// A push-only permission failure must not disable otherwise readable stores.
if (args[0] === "push" && (!probe || resume)) {
const error = gitAuthErrorText(result) ?? "push failed";
return { ok: false, output: result.output, error: healDetail ? `${error}\n${healDetail}` : error };
}
const current = storeSyncRemote(cwd, remote.remoteName) ?? remote;
const state = recordStoreAuthFailure(cwd, current.remoteName, current.remote, now(), authFailed ? checked : result);
return { ok: false, output: "", error: `${storeAuthDetail(state)}${healDetail ? `. ${healDetail}` : ""}` };
}
finally {
release();
}
};
}