askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
15 hours, 50 minutes ago
History
ai-config.ts · 7.8 KB · 189 lines
| 1 | /** |
| 2 | * Where the AI Reader's API keys come from — and, just as important, where they never do. |
| 3 | * |
| 4 | * Keys are NEVER in the repository. They are read at runtime from, in order: |
| 5 | * 1. the process environment (ANTHROPIC_API_KEY / OPENAI_API_KEY) |
| 6 | * 2. the file named by DBB_ENV_FILE, if set |
| 7 | * 3. ~/.dbbasic/env |
| 8 | * Files are plain `NAME=value` lines (the usual .env shape). |
| 9 | * |
| 10 | * Only a FIXED allow-list of variable names is ever read out of a file. An env file may hold |
| 11 | * unrelated secrets (database URLs, wallet keys, other services' tokens); they are skipped |
| 12 | * at parse time, so this module cannot leak what it never loads. |
| 13 | * |
| 14 | * Key values never leave the main process: the chrome UI gets `describeAi()` (provider, model, |
| 15 | * which providers are usable, and the file a key came from — never a value), and any error text |
| 16 | * is passed through `redact()` before it can reach a log or the UI. |
| 17 | */ |
| 18 | |
| 19 | import { readFileSync } from "node:fs"; |
| 20 | import { homedir } from "node:os"; |
| 21 | import { join } from "node:path"; |
| 22 | |
| 23 | export type Provider = "anthropic" | "openai"; |
| 24 | |
| 25 | /** The ONLY names read from env files. */ |
| 26 | const ALLOWED_NAMES = [ |
| 27 | "ANTHROPIC_API_KEY", |
| 28 | "OPENAI_API_KEY", |
| 29 | "DBB_AI_PROVIDER", |
| 30 | "DBB_AI_MODEL", // overrides the model for whichever provider is selected |
| 31 | "DBB_AI_MODEL_ANTHROPIC", |
| 32 | "DBB_AI_MODEL_OPENAI", |
| 33 | "DBB_AI_BASE_URL", // an OpenAI-compatible endpoint: a model on this machine or on your network |
| 34 | ] as const; |
| 35 | const ALLOWED = new Set<string>(ALLOWED_NAMES); |
| 36 | |
| 37 | /** |
| 38 | * Default models: small and fast, because a TL;DR is a once-per-click, latency-sensitive job. Measured on |
| 39 | * a real 26k-character page, claude-haiku-5-5 wrote an equally accurate summary in 2.6 s for $0.0015, versus |
| 40 | * 5.0 s and $0.0585 for claude-opus-5-5 (about 40x the cost). For richer summaries set |
| 41 | * DBB_AI_MODEL_ANTHROPIC=claude-opus-5-5 (or claude-sonnet-5-5). |
| 42 | */ |
| 43 | export const DEFAULT_MODELS: Record<Provider, string> = { |
| 44 | anthropic: "claude-haiku-5-5", |
| 45 | openai: "gpt-5.4-mini", |
| 46 | }; |
| 47 | |
| 48 | /** Parse `NAME=value` lines, keeping ONLY allow-listed names. Handles `export`, quotes, comments, CRLF. */ |
| 49 | export function parseEnvFile(text: string): Record<string, string> { |
| 50 | const out: Record<string, string> = {}; |
| 51 | for (const raw of text.split(/\r?\n/)) { |
| 52 | const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(raw); |
| 53 | if (!m || m[1] === undefined || !ALLOWED.has(m[1])) continue; |
| 54 | let v = m[2] ?? ""; |
| 55 | if (v.length >= 2 && (v[0] === '"' || v[0] === "'") && v[v.length - 1] === v[0]) v = v.slice(1, -1); |
| 56 | else v = v.replace(/\s+#.*$/, ""); // trailing comment on an unquoted value |
| 57 | if (v) out[m[1]] = v; |
| 58 | } |
| 59 | return out; |
| 60 | } |
| 61 | |
| 62 | export interface Loaded { |
| 63 | values: Record<string, string>; |
| 64 | /** For each allowed name that was found: "env" or the file it came from. Never a value. */ |
| 65 | sources: Record<string, string>; |
| 66 | } |
| 67 | |
| 68 | export interface LoadOptions { |
| 69 | env?: Record<string, string | undefined>; |
| 70 | files?: string[]; |
| 71 | readFile?: (path: string) => string; |
| 72 | } |
| 73 | |
| 74 | export function defaultEnvFiles(env: Record<string, string | undefined> = process.env): string[] { |
| 75 | return [...(env.DBB_ENV_FILE ? [env.DBB_ENV_FILE] : []), join(homedir(), ".dbbasic", "env")]; |
| 76 | } |
| 77 | |
| 78 | /** Collect allow-listed values; earlier sources win (environment, then each file in order). */ |
| 79 | export function loadAiEnv(opts: LoadOptions = {}): Loaded { |
| 80 | const env = opts.env ?? process.env; |
| 81 | const read = opts.readFile ?? ((p: string) => readFileSync(p, "utf8")); |
| 82 | const values: Record<string, string> = {}; |
| 83 | const sources: Record<string, string> = {}; |
| 84 | for (const name of ALLOWED_NAMES) { |
| 85 | const v = env[name]; |
| 86 | if (v) { |
| 87 | values[name] = v; |
| 88 | sources[name] = "env"; |
| 89 | } |
| 90 | } |
| 91 | for (const file of opts.files ?? defaultEnvFiles(env)) { |
| 92 | let parsed: Record<string, string>; |
| 93 | try { |
| 94 | parsed = parseEnvFile(read(file)); |
| 95 | } catch { |
| 96 | continue; // missing/unreadable file is normal |
| 97 | } |
| 98 | for (const [k, v] of Object.entries(parsed)) { |
| 99 | if (!(k in values)) { |
| 100 | values[k] = v; |
| 101 | sources[k] = file; |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | return { values, sources }; |
| 106 | } |
| 107 | |
| 108 | export interface AiConfig { |
| 109 | provider: Provider; |
| 110 | model: string; |
| 111 | /** Provider -> key. Main process only; never serialize this. */ |
| 112 | keys: Partial<Record<Provider, string>>; |
| 113 | available: Provider[]; |
| 114 | sources: Record<string, string>; |
| 115 | /** An OpenAI-compatible endpoint (a local or network model) used instead of api.openai.com. */ |
| 116 | baseUrl?: string; |
| 117 | /** The env file named the model (rather than the default being used). */ |
| 118 | modelExplicit?: boolean; |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * A model endpoint must be https, or plain http only to this machine or a private network (where "a model on my own |
| 123 | * hardware" lives). Anything else is ignored, so page text never goes over plain http across the internet. |
| 124 | */ |
| 125 | export function parseBaseUrl(v: string | undefined): string | null { |
| 126 | if (!v) return null; |
| 127 | let u: URL; |
| 128 | try { |
| 129 | u = new URL(v); |
| 130 | } catch { |
| 131 | return null; |
| 132 | } |
| 133 | if (u.username || u.password) return null; |
| 134 | if (u.protocol === "https:") return u.href.replace(/\/$/, ""); |
| 135 | if (u.protocol !== "http:") return null; |
| 136 | const h = u.hostname.replace(/^\[|\]$/g, ""); |
| 137 | const priv = |
| 138 | h === "localhost" || h === "::1" || h.endsWith(".local") || /^127\./.test(h) || /^10\./.test(h) || /^192\.168\./.test(h) || /^172\.(1[6-9]|2\d|3[01])\./.test(h); |
| 139 | return priv ? u.href.replace(/\/$/, "") : null; |
| 140 | } |
| 141 | |
| 142 | /** Pick the provider (Anthropic by default) and model. Returns null when no usable key exists. */ |
| 143 | export function resolveAi(loaded: Loaded): AiConfig | null { |
| 144 | const { values, sources } = loaded; |
| 145 | const keys: Partial<Record<Provider, string>> = {}; |
| 146 | if (values.ANTHROPIC_API_KEY) keys.anthropic = values.ANTHROPIC_API_KEY; |
| 147 | if (values.OPENAI_API_KEY) keys.openai = values.OPENAI_API_KEY; |
| 148 | const baseUrl = parseBaseUrl(values.DBB_AI_BASE_URL); |
| 149 | const names = new Set<Provider>(Object.keys(keys) as Provider[]); |
| 150 | if (baseUrl) names.add("openai"); // a local or network endpoint needs no key |
| 151 | const available = [...names].sort((a, b) => (a === "anthropic" ? -1 : b === "anthropic" ? 1 : 0)); |
| 152 | if (available.length === 0) return null; |
| 153 | |
| 154 | const wanted = values.DBB_AI_PROVIDER as Provider | undefined; |
| 155 | const provider: Provider = wanted && available.includes(wanted) ? wanted : (available[0] as Provider); |
| 156 | const named = (provider === "anthropic" ? values.DBB_AI_MODEL_ANTHROPIC : values.DBB_AI_MODEL_OPENAI) || values.DBB_AI_MODEL; |
| 157 | const model = named || DEFAULT_MODELS[provider]; |
| 158 | return { provider, model, keys, available, sources, ...(baseUrl ? { baseUrl } : {}), ...(named ? { modelExplicit: true } : {}) }; |
| 159 | } |
| 160 | |
| 161 | /** Everything the UI may know: no key material. */ |
| 162 | export interface AiDescription { |
| 163 | configured: boolean; |
| 164 | provider?: Provider; |
| 165 | model?: string; |
| 166 | available: Provider[]; |
| 167 | keySources: Partial<Record<Provider, string>>; |
| 168 | /** Host (and port) of a local or network endpoint, when one is in use. Never a key. */ |
| 169 | endpoint?: string; |
| 170 | } |
| 171 | |
| 172 | export function describeAi(cfg: AiConfig | null): AiDescription { |
| 173 | if (!cfg) return { configured: false, available: [], keySources: {} }; |
| 174 | const keySources: Partial<Record<Provider, string>> = {}; |
| 175 | if (cfg.sources.ANTHROPIC_API_KEY) keySources.anthropic = cfg.sources.ANTHROPIC_API_KEY; |
| 176 | if (cfg.sources.OPENAI_API_KEY) keySources.openai = cfg.sources.OPENAI_API_KEY; |
| 177 | const endpoint = cfg.baseUrl && cfg.provider === "openai" ? new URL(cfg.baseUrl).host : undefined; |
| 178 | return { configured: true, provider: cfg.provider, model: cfg.model, available: cfg.available, keySources, ...(endpoint ? { endpoint } : {}) }; |
| 179 | } |
| 180 | |
| 181 | /** Remove any key (or a recognisable fragment of one) from text before it is logged or shown. */ |
| 182 | export function redact(text: string, cfg: AiConfig | null): string { |
| 183 | let out = text; |
| 184 | for (const k of Object.values(cfg?.keys ?? {})) { |
| 185 | if (k) out = out.split(k).join("[redacted-key]"); |
| 186 | } |
| 187 | // Belt and braces for keys we don't hold: the common provider shapes. |
| 188 | return out.replace(/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}/g, "[redacted-key]"); |
| 189 | } |