Group the sources into aliased modules and lint with the published plugins
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import { expect, test } from "vite-plus/test";
|
||||
|
||||
import { decryptCredential, encryptCredential, parseCredentials } from "./credentials.ts";
|
||||
|
||||
const MASTER_KEY = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
|
||||
const OTHER_KEY = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE";
|
||||
const NONCE = Uint8Array.from({ length: 12 }, (_, index) => index + 32);
|
||||
const ENCRYPTED = "v1:ICEiIyQlJicoKSor:oV_FAgnsN3p1FyegJxwGVdyjfyPio6qDeSUwbA";
|
||||
|
||||
test("decrypts a known AES-256-GCM credential", async () => {
|
||||
expect(await decryptCredential(ENCRYPTED, MASTER_KEY)).toBe("secret-token");
|
||||
});
|
||||
|
||||
test("encrypts a credential with a fresh supplied nonce", async () => {
|
||||
expect(await encryptCredential("secret-token", MASTER_KEY, NONCE)).toStrictEqual(ENCRYPTED);
|
||||
});
|
||||
|
||||
test("rejects a credential encrypted by another master key", async () => {
|
||||
await expect(() => decryptCredential(ENCRYPTED, OTHER_KEY)).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("rejects a credential with a nonstandard nonce", async () => {
|
||||
await expect(() =>
|
||||
decryptCredential("v1:AA:oV_FAgnsN3p1FyegJxwGVdyjfyPio6qDeSUwbA", MASTER_KEY),
|
||||
).rejects.toThrow("nonce must be 12 bytes");
|
||||
});
|
||||
|
||||
test("decrypts the central reviewer token and ordered profiles", async () => {
|
||||
expect(
|
||||
await parseCredentials(
|
||||
JSON.stringify({
|
||||
"reviewer-token": ENCRYPTED,
|
||||
profiles: [
|
||||
{ type: "codex", model: "gpt-custom" },
|
||||
{ type: "claude", token: ENCRYPTED },
|
||||
{ type: "opencode", token: ENCRYPTED },
|
||||
],
|
||||
}),
|
||||
MASTER_KEY,
|
||||
),
|
||||
).toStrictEqual({
|
||||
reviewerToken: "secret-token",
|
||||
profiles: [
|
||||
{ type: "codex", model: "gpt-custom" },
|
||||
{
|
||||
type: "claude",
|
||||
model: "claude-sonnet-5",
|
||||
token: "secret-token",
|
||||
},
|
||||
{
|
||||
type: "opencode",
|
||||
model: "openrouter/qwen/qwen3.8-27b",
|
||||
token: "secret-token",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects malformed central credentials", async () => {
|
||||
await expect(() => parseCredentials('{"profiles": []}', MASTER_KEY)).rejects.toThrow(
|
||||
"reviewer-token",
|
||||
);
|
||||
await expect(() =>
|
||||
parseCredentials(
|
||||
JSON.stringify({ "reviewer-token": ENCRYPTED, profiles: [{ type: "claude" }] }),
|
||||
MASTER_KEY,
|
||||
),
|
||||
).rejects.toThrow("profiles[0].token");
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { webcrypto } from "node:crypto";
|
||||
|
||||
import { isMapping } from "#common";
|
||||
import type { BotProfile } from "#profiles";
|
||||
|
||||
interface DefaultModels {
|
||||
claude: string;
|
||||
codex: string;
|
||||
opencode: string;
|
||||
}
|
||||
|
||||
const DEFAULT_MODELS: DefaultModels = {
|
||||
claude: "claude-sonnet-5",
|
||||
codex: "gpt-5.6-terra",
|
||||
opencode: "openrouter/qwen/qwen3.8-27b",
|
||||
};
|
||||
|
||||
export interface BotCredentials {
|
||||
reviewerToken: string;
|
||||
profiles: BotProfile[];
|
||||
}
|
||||
|
||||
function decodeBase64Url(value: string): Uint8Array {
|
||||
const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
|
||||
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
|
||||
return Uint8Array.from(atob(padded), (character) => character.codePointAt(0) ?? 0);
|
||||
}
|
||||
|
||||
function encodeBase64Url(value: Uint8Array): string {
|
||||
const binary = Array.from(value, (byte) => String.fromCodePoint(byte)).join("");
|
||||
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
|
||||
}
|
||||
|
||||
const buffer = (value: Uint8Array): ArrayBuffer => Uint8Array.from(value).buffer;
|
||||
|
||||
function importMasterKey(encoded: string, usage: webcrypto.KeyUsage): Promise<webcrypto.CryptoKey> {
|
||||
const bytes = decodeBase64Url(encoded);
|
||||
if (bytes.length !== 32) {
|
||||
throw new Error("master-key must be 32 bytes encoded as base64url");
|
||||
}
|
||||
return webcrypto.subtle.importKey("raw", buffer(bytes), "AES-GCM", false, [usage]);
|
||||
}
|
||||
|
||||
export async function decryptCredential(encrypted: string, masterKey: string): Promise<string> {
|
||||
const [version, encodedNonce = "", encodedCiphertext = "", extra = ""] = encrypted.split(":");
|
||||
if (version !== "v1" || encodedNonce === "" || encodedCiphertext === "" || extra !== "") {
|
||||
throw new Error("credential must use v1:<nonce>:<ciphertext>");
|
||||
}
|
||||
const nonce = decodeBase64Url(encodedNonce);
|
||||
if (nonce.length !== 12) throw new Error("credential nonce must be 12 bytes");
|
||||
const plaintext = await webcrypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: buffer(nonce) },
|
||||
await importMasterKey(masterKey, "decrypt"),
|
||||
buffer(decodeBase64Url(encodedCiphertext)),
|
||||
);
|
||||
return new TextDecoder().decode(plaintext);
|
||||
}
|
||||
|
||||
export async function encryptCredential(
|
||||
plaintext: string,
|
||||
masterKey: string,
|
||||
nonce: Uint8Array = webcrypto.getRandomValues(new Uint8Array(12)),
|
||||
): Promise<string> {
|
||||
if (nonce.length !== 12) throw new Error("AES-GCM nonce must be 12 bytes");
|
||||
const ciphertext = await webcrypto.subtle.encrypt(
|
||||
{ name: "AES-GCM", iv: buffer(nonce) },
|
||||
await importMasterKey(masterKey, "encrypt"),
|
||||
new TextEncoder().encode(plaintext),
|
||||
);
|
||||
return `v1:${encodeBase64Url(nonce)}:${encodeBase64Url(new Uint8Array(ciphertext))}`;
|
||||
}
|
||||
|
||||
async function parseProfile(entry: unknown, index: number, masterKey: string): Promise<BotProfile> {
|
||||
const at = `profiles[${index}]`;
|
||||
if (!isMapping(entry)) {
|
||||
throw new TypeError(`${at}: expected a mapping`);
|
||||
}
|
||||
for (const key of Object.keys(entry)) {
|
||||
if (key !== "type" && key !== "model" && key !== "token") {
|
||||
throw new Error(`${at}.${key}: unknown field`);
|
||||
}
|
||||
}
|
||||
const { type, model, token } = entry;
|
||||
if (type !== "claude" && type !== "codex" && type !== "opencode") {
|
||||
throw new Error(`${at}.type: expected "claude", "codex", or "opencode"`);
|
||||
}
|
||||
if (model !== undefined && (typeof model !== "string" || model === "")) {
|
||||
throw new Error(`${at}.model: expected a model name`);
|
||||
}
|
||||
if ((type === "claude" || type === "opencode") && typeof token !== "string") {
|
||||
throw new Error(`${at}.token: expected an encrypted credential`);
|
||||
}
|
||||
if (token !== undefined && typeof token !== "string") {
|
||||
throw new Error(`${at}.token: expected an encrypted credential`);
|
||||
}
|
||||
return {
|
||||
type,
|
||||
model: model ?? DEFAULT_MODELS[type],
|
||||
...(typeof token === "string" && {
|
||||
token: await decryptCredential(token, masterKey),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function parseCredentials(text: string, masterKey: string): Promise<BotCredentials> {
|
||||
const value: unknown = JSON.parse(text);
|
||||
if (!isMapping(value)) {
|
||||
throw new TypeError("credentials must be a mapping");
|
||||
}
|
||||
for (const key of Object.keys(value)) {
|
||||
if (key !== "reviewer-token" && key !== "profiles") {
|
||||
throw new Error(`${key}: unknown field`);
|
||||
}
|
||||
}
|
||||
const { "reviewer-token": reviewerToken, profiles } = value;
|
||||
if (typeof reviewerToken !== "string") {
|
||||
throw new TypeError("reviewer-token: expected an encrypted credential");
|
||||
}
|
||||
if (!Array.isArray(profiles) || profiles.length === 0) {
|
||||
throw new Error("profiles must contain at least one profile");
|
||||
}
|
||||
const parsed = await Promise.all(
|
||||
profiles.map((entry: unknown, index) => parseProfile(entry, index, masterKey)),
|
||||
);
|
||||
return { reviewerToken: await decryptCredential(reviewerToken, masterKey), profiles: parsed };
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// The runtime the prepare phase writes for the later phases: decrypted
|
||||
// credentials laid out per profile, described by a manifest.
|
||||
export { prepareRuntime, readRuntimeManifest } from "./runtime.ts";
|
||||
export type {
|
||||
RuntimeFailure,
|
||||
RuntimeManifest,
|
||||
RuntimeOutcome,
|
||||
RuntimeProfile,
|
||||
RuntimeSuccess,
|
||||
} from "./runtime.ts";
|
||||
@@ -0,0 +1,101 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { chmod, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import process from "node:process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { assert, expect, test } from "vite-plus/test";
|
||||
|
||||
import { IS_ROOT, makeTempDir } from "#testing";
|
||||
|
||||
import { prepareRuntime, type RuntimeProfile } from "./runtime.ts";
|
||||
|
||||
const MASTER_KEY = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
|
||||
const ENCRYPTED = "v1:ICEiIyQlJicoKSor:oV_FAgnsN3p1FyegJxwGVdyjfyPio6qDeSUwbA";
|
||||
|
||||
// Runs `command` as the profile's user, from the root directory.
|
||||
function runAs(profile: RuntimeProfile, command: string, path: string): boolean {
|
||||
const result = spawnSync(command, [path], { cwd: "/", uid: profile.uid, gid: profile.gid });
|
||||
return result.status === 0;
|
||||
}
|
||||
|
||||
async function expectPrivate(path: string, uid: number, mode: number): Promise<void> {
|
||||
const info = await stat(path);
|
||||
expect(info.uid).toStrictEqual(uid);
|
||||
expect(info.mode & 0o777).toBe(mode);
|
||||
}
|
||||
|
||||
test.skipIf(!IS_ROOT)("prepares root-only reviewer and isolated profile credentials", async () => {
|
||||
const root = await makeTempDir();
|
||||
await chmod(root, 0o711);
|
||||
const action = await makeTempDir();
|
||||
try {
|
||||
await writeFile(
|
||||
`${action}/profiles.json`,
|
||||
JSON.stringify({
|
||||
"reviewer-token": ENCRYPTED,
|
||||
profiles: [{ type: "claude", token: ENCRYPTED }, { type: "codex" }],
|
||||
}),
|
||||
);
|
||||
|
||||
const manifest = await prepareRuntime(action, root, MASTER_KEY);
|
||||
const serialized = await readFile(manifest.manifestPath, "utf8");
|
||||
assert(!serialized.includes("secret-token"));
|
||||
expect(await readFile(manifest.reviewerFile, "utf8")).toBe("secret-token");
|
||||
await expectPrivate(manifest.reviewerFile, 0, 0o600);
|
||||
|
||||
const [claude, codex] = manifest.profiles;
|
||||
assert(claude !== undefined && codex !== undefined);
|
||||
expect(claude.uid).not.toStrictEqual(codex.uid);
|
||||
await expectPrivate(claude.home, claude.uid, 0o700);
|
||||
assert(claude.tokenFile !== null);
|
||||
expect(await readFile(claude.tokenFile, "utf8")).toBe("secret-token");
|
||||
await expectPrivate(claude.tokenFile, claude.uid, 0o600);
|
||||
expect((await stat(codex.home)).uid).toStrictEqual(codex.uid);
|
||||
expect(codex.tokenFile).toBe(null);
|
||||
|
||||
const ownToken = spawnSync("/bin/cat", [claude.tokenFile], {
|
||||
cwd: "/",
|
||||
uid: claude.uid,
|
||||
gid: claude.gid,
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(ownToken.status).toBe(0);
|
||||
expect(ownToken.stdout).toBe("secret-token");
|
||||
expect(runAs(claude, "/bin/cat", manifest.reviewerFile)).toBe(false);
|
||||
expect(runAs(claude, "/bin/ls", codex.home)).toBe(false);
|
||||
} finally {
|
||||
await rm(root, { recursive: true });
|
||||
await rm(action, { recursive: true });
|
||||
}
|
||||
});
|
||||
|
||||
test.skipIf(!IS_ROOT)("removes prepared credentials when output publication fails", async () => {
|
||||
const root = await makeTempDir();
|
||||
const action = await makeTempDir();
|
||||
try {
|
||||
await writeFile(
|
||||
`${action}/profiles.json`,
|
||||
JSON.stringify({
|
||||
"reviewer-token": ENCRYPTED,
|
||||
profiles: [{ type: "claude", token: ENCRYPTED }],
|
||||
}),
|
||||
);
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[fileURLToPath(new URL("../prepare.ts", import.meta.url))],
|
||||
{
|
||||
env: {
|
||||
ACTION_PATH: action,
|
||||
RUNNER_TEMP: root,
|
||||
BOT_AGENTS_MASTER_KEY: MASTER_KEY,
|
||||
GITHUB_OUTPUT: action,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.status).not.toBe(0);
|
||||
expect(await readdir(root)).toStrictEqual([]);
|
||||
} finally {
|
||||
await rm(root, { recursive: true });
|
||||
await rm(action, { recursive: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { chmod, chown, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { isMapping } from "#common";
|
||||
import type { ProfileFailure, ProfileIdentity } from "#profiles";
|
||||
|
||||
import { parseCredentials } from "./credentials.ts";
|
||||
|
||||
const FIRST_PROFILE_UID = 20_000;
|
||||
|
||||
export interface RuntimeProfile extends ProfileIdentity {
|
||||
index: number;
|
||||
uid: number;
|
||||
gid: number;
|
||||
home: string;
|
||||
tokenFile: string | null;
|
||||
}
|
||||
|
||||
export interface RuntimeManifest {
|
||||
runtimeDir: string;
|
||||
manifestPath: string;
|
||||
reviewerFile: string;
|
||||
outcomeFile: string;
|
||||
profiles: RuntimeProfile[];
|
||||
}
|
||||
|
||||
export interface RuntimeSuccess {
|
||||
ok: true;
|
||||
body: string;
|
||||
reviewPath: string;
|
||||
anchorsPath: string;
|
||||
profile: ProfileIdentity;
|
||||
}
|
||||
|
||||
export interface RuntimeFailure {
|
||||
ok: false;
|
||||
failures: ProfileFailure[];
|
||||
}
|
||||
|
||||
export type RuntimeOutcome = RuntimeSuccess | RuntimeFailure;
|
||||
|
||||
async function writePrivate(path: string, value: string, uid: number, gid: number): Promise<void> {
|
||||
await writeFile(path, value, { mode: 0o600 });
|
||||
await chmod(path, 0o600);
|
||||
await chown(path, uid, gid);
|
||||
}
|
||||
|
||||
export async function prepareRuntime(
|
||||
actionPath: string,
|
||||
runtimeRoot: string,
|
||||
masterKey: string,
|
||||
): Promise<RuntimeManifest> {
|
||||
const credentials = await parseCredentials(
|
||||
await readFile(join(actionPath, "profiles.json"), "utf8"),
|
||||
masterKey,
|
||||
);
|
||||
const runtimeDir = await mkdtemp(join(runtimeRoot, "bot-agents-"));
|
||||
try {
|
||||
await chmod(runtimeDir, 0o711);
|
||||
const reviewerFile = join(runtimeDir, "reviewer-token");
|
||||
await writePrivate(reviewerFile, credentials.reviewerToken, 0, 0);
|
||||
|
||||
// One profile at a time, in order, as each claims the next UID.
|
||||
const profiles = await credentials.profiles.reduce<Promise<RuntimeProfile[]>>(
|
||||
async (previous, profile, index) => {
|
||||
const prepared = await previous;
|
||||
const uid = FIRST_PROFILE_UID + index;
|
||||
const home = join(runtimeDir, `profile-${index}`);
|
||||
await mkdir(home, { mode: 0o700 });
|
||||
await chmod(home, 0o700);
|
||||
await chown(home, uid, uid);
|
||||
const tokenFile =
|
||||
profile.token === undefined || profile.token === "" ? null : join(home, "token");
|
||||
if (tokenFile !== null && profile.token !== undefined) {
|
||||
await writePrivate(tokenFile, profile.token, uid, uid);
|
||||
}
|
||||
prepared.push({
|
||||
index,
|
||||
type: profile.type,
|
||||
model: profile.model,
|
||||
uid,
|
||||
gid: uid,
|
||||
home,
|
||||
tokenFile,
|
||||
});
|
||||
return prepared;
|
||||
},
|
||||
Promise.resolve([]),
|
||||
);
|
||||
|
||||
const manifestPath = join(runtimeDir, "manifest.json");
|
||||
const manifest: RuntimeManifest = {
|
||||
runtimeDir,
|
||||
manifestPath,
|
||||
reviewerFile,
|
||||
outcomeFile: join(runtimeDir, "outcome.json"),
|
||||
profiles,
|
||||
};
|
||||
await writePrivate(manifestPath, JSON.stringify(manifest), 0, 0);
|
||||
return manifest;
|
||||
} catch (error) {
|
||||
await rm(runtimeDir, { recursive: true }).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function isRuntimeManifest(value: unknown): value is RuntimeManifest {
|
||||
return (
|
||||
isMapping(value) &&
|
||||
typeof value["runtimeDir"] === "string" &&
|
||||
typeof value["manifestPath"] === "string" &&
|
||||
typeof value["reviewerFile"] === "string" &&
|
||||
typeof value["outcomeFile"] === "string" &&
|
||||
Array.isArray(value["profiles"])
|
||||
);
|
||||
}
|
||||
|
||||
export async function readRuntimeManifest(path: string): Promise<RuntimeManifest> {
|
||||
const value: unknown = JSON.parse(await readFile(path, "utf8"));
|
||||
if (!isRuntimeManifest(value)) {
|
||||
throw new Error(`${path}: invalid runtime manifest`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
Reference in New Issue
Block a user