129 lines
5.4 KiB
TypeScript
129 lines
5.4 KiB
TypeScript
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
import { loadEnv } from "@peppa/shared";
|
|
|
|
function secret(): string {
|
|
const s = loadEnv().PEPPA_SECRET;
|
|
if (!s) throw new Error("PEPPA_SECRET is not set");
|
|
return s;
|
|
}
|
|
|
|
/** PEP-19: the key being rotated out — still accepted for reading, never used for writing. */
|
|
function previousSecret(): string | null {
|
|
const p = loadEnv().PEPPA_SECRET_PREVIOUS;
|
|
return p && p !== secret() ? p : null;
|
|
}
|
|
|
|
const derive = (purpose: string, s: string) => createHash("sha256").update(`${purpose}:${s}`).digest();
|
|
const key = (purpose: string) => derive(purpose, secret());
|
|
/** Current key first, then the previous one (two-key rotation of PEPPA_SECRET). */
|
|
const keys = (purpose: string) => {
|
|
const prev = previousSecret();
|
|
return prev ? [key(purpose), derive(purpose, prev)] : [key(purpose)];
|
|
};
|
|
|
|
/** Whether PEPPA_SECRET_PREVIOUS is set (a rotation is in progress). */
|
|
export const rotatingSecret = () => previousSecret() !== null;
|
|
|
|
/** AES-256-GCM; output is base64url(iv | tag | ciphertext). */
|
|
export function encrypt(plain: string): string {
|
|
const iv = randomBytes(12);
|
|
const c = createCipheriv("aes-256-gcm", key("enc"), iv);
|
|
const data = Buffer.concat([c.update(plain, "utf8"), c.final()]);
|
|
return Buffer.concat([iv, c.getAuthTag(), data]).toString("base64url");
|
|
}
|
|
|
|
function decryptWith(k: Buffer, buf: Buffer): string {
|
|
const d = createDecipheriv("aes-256-gcm", k, buf.subarray(0, 12));
|
|
d.setAuthTag(buf.subarray(12, 28));
|
|
return Buffer.concat([d.update(buf.subarray(28)), d.final()]).toString("utf8");
|
|
}
|
|
|
|
/** Decrypts with the current key, falling back to PEPPA_SECRET_PREVIOUS during a rotation. */
|
|
export function decrypt(enc: string): string {
|
|
const buf = Buffer.from(enc, "base64url");
|
|
const [cur, prev] = keys("enc");
|
|
try {
|
|
return decryptWith(cur!, buf);
|
|
} catch (e) {
|
|
if (!prev) throw e;
|
|
return decryptWith(prev, buf);
|
|
}
|
|
}
|
|
|
|
/** Which key an encrypted value opens with (PEP-19: what still waits for `reencrypt`). */
|
|
export function encryptedWith(enc: string): "current" | "previous" | "unknown" {
|
|
const buf = Buffer.from(enc, "base64url");
|
|
const [cur, prev] = keys("enc");
|
|
for (const [k, label] of [[cur, "current"], [prev, "previous"]] as const) {
|
|
if (!k) continue;
|
|
try {
|
|
decryptWith(k, buf);
|
|
return label;
|
|
} catch {
|
|
// next key
|
|
}
|
|
}
|
|
return "unknown";
|
|
}
|
|
|
|
/** `payload.signature` token (HMAC-SHA256), used for web session cookies. */
|
|
export function sign(payload: object): string {
|
|
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
return `${body}.${createHmac("sha256", key("sign")).update(body).digest("base64url")}`;
|
|
}
|
|
|
|
export function verify<T>(token: string | undefined): T | null {
|
|
if (!token) return null;
|
|
const [body, sig] = token.split(".");
|
|
if (!body || !sig) return null;
|
|
const given = Buffer.from(sig, "base64url");
|
|
const ok = keys("sign").some((k) => {
|
|
const expected = createHmac("sha256", k).update(body).digest();
|
|
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
});
|
|
if (!ok) return null;
|
|
try {
|
|
return JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as T;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export const hashToken = (s: string) => createHmac("sha256", key("hash")).update(s).digest("hex");
|
|
|
|
/** Hashes of a token under the current and the previous key (lookups during a rotation). */
|
|
export const hashTokenCandidates = (s: string) => keys("hash").map((k) => createHmac("sha256", k).update(s).digest("hex"));
|
|
|
|
/** Per-project secret for Gitea webhooks and CI reports (Actions secret PEPPA_CI_SECRET). */
|
|
export const projectHookSecret = (projectId: number) => createHmac("sha256", key("ci")).update(String(projectId)).digest("hex");
|
|
|
|
/** Checks `X-Gitea-Signature` (hex HMAC-SHA256 of the raw body) against the project's secret. */
|
|
export function verifyHookSignature(projectId: number, body: string, signature: string | null | undefined): boolean {
|
|
if (!signature) return false;
|
|
const given = Buffer.from(signature.trim().toLowerCase(), "hex");
|
|
// During a rotation Gitea still signs with the old project secret until `peppa ci connect`.
|
|
return keys("ci").some((k) => {
|
|
const secret = createHmac("sha256", k).update(String(projectId)).digest("hex");
|
|
const expected = createHmac("sha256", secret).update(body).digest();
|
|
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* PEP-17: token of one agent run for the agent relay (/api/agent/*): `s<id>.<generation>.<hmac>`.
|
|
* Only checks the signature — the caller also checks the generation is current and the session alive.
|
|
*/
|
|
export function agentRelayToken(sessionId: number, generation: number): string {
|
|
const body = `s${sessionId}.${generation}`;
|
|
return `${body}.${createHmac("sha256", key("agent")).update(body).digest("base64url")}`;
|
|
}
|
|
|
|
export function parseAgentRelayToken(token: string | null | undefined): { sessionId: number; generation: number } | null {
|
|
const m = token?.trim().match(/^s(\d+)\.(\d+)\.([A-Za-z0-9_-]+)$/);
|
|
if (!m) return null;
|
|
const expected = createHmac("sha256", key("agent")).update(`s${m[1]}.${m[2]}`).digest();
|
|
const given = Buffer.from(m[3]!, "base64url");
|
|
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
|
|
return { sessionId: Number(m[1]), generation: Number(m[2]) };
|
|
}
|