59 lines
2.6 KiB
TypeScript
59 lines
2.6 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;
|
|
}
|
|
|
|
const key = (purpose: string) => createHash("sha256").update(`${purpose}:${secret()}`).digest();
|
|
|
|
/** 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");
|
|
}
|
|
|
|
export function decrypt(enc: string): string {
|
|
const buf = Buffer.from(enc, "base64url");
|
|
const d = createDecipheriv("aes-256-gcm", key("enc"), buf.subarray(0, 12));
|
|
d.setAuthTag(buf.subarray(12, 28));
|
|
return Buffer.concat([d.update(buf.subarray(28)), d.final()]).toString("utf8");
|
|
}
|
|
|
|
/** `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 expected = createHmac("sha256", key("sign")).update(body).digest();
|
|
const given = Buffer.from(sig, "base64url");
|
|
if (given.length !== expected.length || !timingSafeEqual(given, expected)) 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");
|
|
|
|
/** 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 expected = createHmac("sha256", projectHookSecret(projectId)).update(body).digest();
|
|
const given = Buffer.from(signature.trim().toLowerCase(), "hex");
|
|
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
}
|