Replace NodeJS dict aliases with maps and named field reads
Co-authored-by: Danny Kim <temeddix@gmail.com> Co-committed-by: Danny Kim <temeddix@gmail.com>
This commit was merged in pull request #24.
This commit is contained in:
+91
-32
@@ -1,20 +1,20 @@
|
||||
import { webcrypto } from "node:crypto";
|
||||
|
||||
import { isMapping } from "#common";
|
||||
import { field, isMapping } from "#common";
|
||||
import type { BotProfile } from "#profiles";
|
||||
|
||||
interface DefaultModels {
|
||||
claude: string;
|
||||
codex: string;
|
||||
opencode: string;
|
||||
// The model a profile runs when profiles.json names none.
|
||||
function defaultModel(type: BotProfile["type"]): string {
|
||||
switch (type) {
|
||||
case "CLAUDE":
|
||||
return "claude-sonnet-5";
|
||||
case "CODEX":
|
||||
return "gpt-5.6-terra";
|
||||
case "OPENCODE":
|
||||
return "openrouter/qwen/qwen3.8-27b";
|
||||
}
|
||||
}
|
||||
|
||||
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[];
|
||||
@@ -23,31 +23,61 @@ export interface BotCredentials {
|
||||
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);
|
||||
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 binary = Array.from(value, (byte) => String.fromCodePoint(byte)).join(
|
||||
"",
|
||||
);
|
||||
return btoa(binary)
|
||||
.replaceAll("+", "-")
|
||||
.replaceAll("/", "_")
|
||||
.replaceAll("=", "");
|
||||
}
|
||||
|
||||
const buffer = (value: Uint8Array): ArrayBuffer => Uint8Array.from(value).buffer;
|
||||
const buffer = (value: Uint8Array): ArrayBuffer =>
|
||||
Uint8Array.from(value).buffer;
|
||||
|
||||
function importMasterKey(encoded: string, usage: webcrypto.KeyUsage): Promise<webcrypto.CryptoKey> {
|
||||
async 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]);
|
||||
const key = await webcrypto.subtle.importKey(
|
||||
"raw",
|
||||
buffer(bytes),
|
||||
"AES-GCM",
|
||||
false,
|
||||
[usage],
|
||||
);
|
||||
return key;
|
||||
}
|
||||
|
||||
export async function decryptCredential(encrypted: string, masterKey: string): Promise<string> {
|
||||
const [version, encodedNonce = "", encodedCiphertext = "", extra = ""] = encrypted.split(":");
|
||||
if (version !== "v1" || encodedNonce === "" || encodedCiphertext === "" || extra !== "") {
|
||||
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");
|
||||
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"),
|
||||
@@ -61,7 +91,9 @@ export async function encryptCredential(
|
||||
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");
|
||||
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"),
|
||||
@@ -70,7 +102,22 @@ export async function encryptCredential(
|
||||
return `v1:${encodeBase64Url(nonce)}:${encodeBase64Url(new Uint8Array(ciphertext))}`;
|
||||
}
|
||||
|
||||
async function parseProfile(entry: unknown, index: number, masterKey: string): Promise<BotProfile> {
|
||||
// profiles.json files written before the UPPER_SNAKE switch spell types in lowercase.
|
||||
const OLD_PROFILE_TYPES = new Map<unknown, BotProfile["type"]>([
|
||||
["claude", "CLAUDE"],
|
||||
["codex", "CODEX"],
|
||||
["opencode", "OPENCODE"],
|
||||
]);
|
||||
|
||||
function currentSpelling(type: unknown): unknown {
|
||||
return OLD_PROFILE_TYPES.get(type) ?? type;
|
||||
}
|
||||
|
||||
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`);
|
||||
@@ -80,14 +127,16 @@ async function parseProfile(entry: unknown, index: number, masterKey: string): P
|
||||
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"`);
|
||||
const type = currentSpelling(field(entry, "type"));
|
||||
const model = field(entry, "model");
|
||||
const token = field(entry, "token");
|
||||
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") {
|
||||
if ((type === "CLAUDE" || type === "OPENCODE") && typeof token !== "string") {
|
||||
throw new Error(`${at}.token: expected an encrypted credential`);
|
||||
}
|
||||
if (token !== undefined && typeof token !== "string") {
|
||||
@@ -95,14 +144,17 @@ async function parseProfile(entry: unknown, index: number, masterKey: string): P
|
||||
}
|
||||
return {
|
||||
type,
|
||||
model: model ?? DEFAULT_MODELS[type],
|
||||
model: model ?? defaultModel(type),
|
||||
...(typeof token === "string" && {
|
||||
token: await decryptCredential(token, masterKey),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function parseCredentials(text: string, masterKey: string): Promise<BotCredentials> {
|
||||
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");
|
||||
@@ -112,7 +164,8 @@ export async function parseCredentials(text: string, masterKey: string): Promise
|
||||
throw new Error(`${key}: unknown field`);
|
||||
}
|
||||
}
|
||||
const { "reviewer-token": reviewerToken, profiles } = value;
|
||||
const reviewerToken = field(value, "reviewer-token");
|
||||
const profiles = field(value, "profiles");
|
||||
if (typeof reviewerToken !== "string") {
|
||||
throw new TypeError("reviewer-token: expected an encrypted credential");
|
||||
}
|
||||
@@ -120,7 +173,13 @@ export async function parseCredentials(text: string, masterKey: string): Promise
|
||||
throw new Error("profiles must contain at least one profile");
|
||||
}
|
||||
const parsed = await Promise.all(
|
||||
profiles.map((entry: unknown, index) => parseProfile(entry, index, masterKey)),
|
||||
profiles.map(async (entry: unknown, index) => {
|
||||
const profile = await parseProfile(entry, index, masterKey);
|
||||
return profile;
|
||||
}),
|
||||
);
|
||||
return { reviewerToken: await decryptCredential(reviewerToken, masterKey), profiles: parsed };
|
||||
return {
|
||||
reviewerToken: await decryptCredential(reviewerToken, masterKey),
|
||||
profiles: parsed,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user