ProjectOS / services /wallet /src /runtime.ts
Watchtower
Deploy GitHub main 30390bd (PR #3: default URL fix)
5169a81
Raw History Blame Contribute Delete
14.4 kB
import type Stripe from "stripe";
import type { Config } from "./config.js";
import { Ledger } from "./ledger.js";
import { MemoryStore } from "./memoryStore.js";
import { SupabaseStore } from "./supabaseStore.js";
import { makeStripe } from "./stripe.js";
import { MemoryDeviceStore, SupabaseDeviceStore, SwitchableDeviceStore, type DeviceStore } from "./devices.js";
import type { Account, AccountKind, LedgerStore, Transaction } from "./types.js";
export const SETTING_KEYS = [
"STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET", "STRIPE_SUCCESS_URL", "STRIPE_CANCEL_URL",
"SUPABASE_URL", "SUPABASE_SERVICE_ROLE_KEY", "WALLET_STORE",
] as const;
export type SettingKey = (typeof SETTING_KEYS)[number];
export const SETTING_META: Record<SettingKey, { label: string; secret: boolean; hint: string }> = {
STRIPE_SECRET_KEY: { label: "Stripe secret key (TEST)", secret: true, hint: "sk_test_… or rk_test_… from Stripe Dashboard → Developers → API keys (test mode). Live keys are refused." },
STRIPE_WEBHOOK_SECRET: { label: "Stripe webhook signing secret", secret: true, hint: "whsec_… from the test-mode webhook endpoint you point at /webhooks/stripe (event: payment_intent.succeeded)." },
STRIPE_SUCCESS_URL: { label: "Checkout success URL", secret: false, hint: "Optional. Defaults to this app's /funding/success page." },
STRIPE_CANCEL_URL: { label: "Checkout cancel URL", secret: false, hint: "Optional. Defaults to this app's /funding/cancel page." },
SUPABASE_URL: { label: "Supabase project URL", secret: false, hint: "https://<project-ref>.supabase.co" },
SUPABASE_SERVICE_ROLE_KEY: { label: "Supabase service role key", secret: true, hint: "Project Settings → API → service_role (server-side only; never shown again)." },
WALLET_STORE: { label: "Storage backend", secret: false, hint: "memory (resets on restart) or supabase (durable; run the SQL migrations first)." },
};
export function validateSetting(key: SettingKey, value: string): string | null {
const v = value.trim();
switch (key) {
case "STRIPE_SECRET_KEY":
if (/^(sk|rk)_live_/.test(v)) return "Live Stripe keys are refused. This wallet is TEST mode only.";
if (!/^(sk|rk)_test_[A-Za-z0-9]{8,}$/.test(v)) return "Must be a Stripe TEST key starting with sk_test_ or rk_test_.";
return null;
case "STRIPE_WEBHOOK_SECRET":
return /^whsec_[A-Za-z0-9+/=_-]{8,}$/.test(v) ? null : "Must be a webhook signing secret starting with whsec_.";
case "STRIPE_SUCCESS_URL": case "STRIPE_CANCEL_URL":
try { const u = new URL(v); return /^https?:$/.test(u.protocol) ? null : "URL must be http(s)."; } catch { return "Not a valid URL."; }
case "SUPABASE_URL":
return /^https:\/\/[a-z0-9-]{4,}\.supabase\.(co|in|net)\/?$/i.test(v) ? null : "Must look like https://<project-ref>.supabase.co";
case "SUPABASE_SERVICE_ROLE_KEY":
return /^(eyJ[\w-]+\.[\w-]+\.[\w-]+|sb_secret_[\w-]{8,})$/.test(v) ? null : "Must be the service_role key (JWT starting eyJ… or sb_secret_…).";
case "WALLET_STORE":
return v === "memory" || v === "supabase" ? null : "Must be memory or supabase.";
}
}
/** Where saved settings go so they survive restarts. */
export interface Persister {
available: boolean;
describe: string;
persist(set: Partial<Record<SettingKey, string>>, clear: SettingKey[]): Promise<void>;
}
export class SwitchableLedgerStore implements LedgerStore {
constructor(public target: LedgerStore) {}
getOrCreateAccount(u: string, k: AccountKind, c: string): Promise<Account> { return this.target.getOrCreateAccount(u, k, c); }
findTransactionByKey(u: string, k: string): Promise<Transaction | null> { return this.target.findTransactionByKey(u, k); }
insertTransaction(tx: Transaction) { return this.target.insertTransaction(tx); }
balance(id: string) { return this.target.balance(id); }
listTransactions(u: string, l?: number) { return this.target.listTransactions(u, l); }
}
export class SettingsError extends Error { constructor(public fields: Partial<Record<SettingKey, string>>, msg = "invalid settings") { super(msg); } }
export interface RuntimeOptions {
stripe?: Stripe | null;
ledger?: Ledger; // supply to disable hot-swapping storage (tests)
devices?: DeviceStore;
persister?: Persister;
}
/** Mutable, server-side-only runtime state: current settings, Stripe client, storage backend. */
export class Runtime {
private values = new Map<SettingKey, string>();
private persisted = new Set<SettingKey>();
stripe: Stripe | null;
readonly ledger: Ledger;
readonly devices: DeviceStore;
readonly canSwitchStore: boolean;
persister?: Persister;
private ledgerSwitch?: SwitchableLedgerStore;
private deviceSwitch?: SwitchableDeviceStore;
private memLedger = new MemoryStore();
private memDevices = new MemoryDeviceStore();
constructor(cfg: Config, opts: RuntimeOptions = {}) {
for (const k of SETTING_KEYS) { const v = (cfg as Record<string, unknown>)[k]; if (typeof v === "string" && v && !(k.endsWith("_URL") && /^http:\/\/localhost[:/]/.test(v))) { this.values.set(k, v); } } // localhost defaults count as "not set"
this.persister = opts.persister;
this.stripe = opts.stripe !== undefined ? opts.stripe : (cfg.STRIPE_SECRET_KEY ? makeStripe(cfg.STRIPE_SECRET_KEY) : null);
if (opts.ledger) {
this.ledger = opts.ledger; this.devices = opts.devices ?? this.memDevices; this.canSwitchStore = false;
} else {
this.ledgerSwitch = new SwitchableLedgerStore(this.memLedger);
this.deviceSwitch = new SwitchableDeviceStore(this.memDevices);
this.ledger = new Ledger(this.ledgerSwitch); this.devices = this.deviceSwitch; this.canSwitchStore = true;
if (cfg.WALLET_STORE === "supabase") this.applyStore();
}
}
get(key: SettingKey): string | undefined { return this.values.get(key); }
get storeMode(): "memory" | "supabase" { return this.get("WALLET_STORE") === "supabase" ? "supabase" : "memory"; }
get webhookSecret() { return this.get("STRIPE_WEBHOOK_SECRET"); }
private applyStore() {
if (!this.ledgerSwitch || !this.deviceSwitch) return;
if (this.storeMode === "supabase") {
const url = this.get("SUPABASE_URL")!, key = this.get("SUPABASE_SERVICE_ROLE_KEY")!;
this.ledgerSwitch.target = new SupabaseStore(url, key);
this.deviceSwitch.target = new SupabaseDeviceStore(url, key);
} else { this.ledgerSwitch.target = this.memLedger; this.deviceSwitch.target = this.memDevices; }
}
/** Origin of the request as seen by the browser (behind the HF proxy). */
static origin(req: { protocol: string; get(h: string): string | undefined }): string {
const proto = req.get("x-forwarded-proto")?.split(",")[0]?.trim() || req.protocol;
return `${proto}://${req.get("x-forwarded-host") ?? req.get("host")}`;
}
checkoutUrls(origin: string) {
const pick = (k: SettingKey, dflt: string) => { const v = this.get(k); return v && !/^https?:\/\/localhost[:/]/.test(v) ? v : dflt; };
return {
success: pick("STRIPE_SUCCESS_URL", `${origin}/funding/success?session_id={CHECKOUT_SESSION_ID}`),
cancel: pick("STRIPE_CANCEL_URL", `${origin}/funding/cancel`),
};
}
status() {
const settings = SETTING_KEYS.map((key) => {
const v = this.get(key); const meta = SETTING_META[key];
return { key, label: meta.label, hint: meta.hint, secret: meta.secret, configured: Boolean(v),
persisted: this.persisted.has(key), value: !meta.secret ? (v ?? "") : undefined, masked: meta.secret && v ? mask(v) : undefined };
});
return { settings, storeMode: this.storeMode, canSwitchStore: this.canSwitchStore, stripeReady: Boolean(this.stripe),
persistence: { available: Boolean(this.persister?.available), describe: this.persister?.describe ?? "Not available: no server-side Hugging Face token configured." } };
}
/** Remove any known secret value from text before it leaves the server. */
redact(text: string): string {
let out = text;
for (const k of SETTING_KEYS) { const v = this.get(k); if (v && v.length >= 8 && SETTING_META[k].secret) out = out.split(v).join("[redacted]"); }
return out
.replace(/\b(?:sk|rk|pk)_(?:test|live)_[A-Za-z0-9*]+/g, "[redacted]")
.replace(/\bwhsec_[A-Za-z0-9+/=_*-]+/g, "[redacted]")
.replace(/\bsb_secret_[\w-]+/g, "[redacted]")
.replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g, "[redacted]");
}
async update(patch: Partial<Record<SettingKey, string>>, clear: SettingKey[] = [], persist = false) {
const errors: Partial<Record<SettingKey, string>> = {};
const set: Partial<Record<SettingKey, string>> = {};
for (const k of SETTING_KEYS) {
const raw = patch[k];
if (typeof raw !== "string" || raw.trim() === "") continue; // blank = leave unchanged
const err = validateSetting(k, raw);
if (err) errors[k] = err; else set[k] = raw.trim();
}
for (const k of clear) if (!SETTING_KEYS.includes(k)) errors[k] = "unknown setting";
if (Object.keys(errors).length) throw new SettingsError(errors);
const next = new Map(this.values);
for (const [k, v] of Object.entries(set)) next.set(k as SettingKey, v);
for (const k of clear) next.delete(k);
if (next.get("WALLET_STORE") === "supabase") {
if (!this.canSwitchStore) throw new SettingsError({ WALLET_STORE: "Storage cannot be switched in this build." });
if (!next.get("SUPABASE_URL")) errors.SUPABASE_URL = "Required to use Supabase storage.";
if (!next.get("SUPABASE_SERVICE_ROLE_KEY")) errors.SUPABASE_SERVICE_ROLE_KEY = "Required to use Supabase storage.";
if (Object.keys(errors).length) throw new SettingsError(errors);
}
let newStripe = this.stripe;
if (set.STRIPE_SECRET_KEY) newStripe = makeStripe(set.STRIPE_SECRET_KEY);
if (clear.includes("STRIPE_SECRET_KEY")) newStripe = null;
this.values = next; this.stripe = newStripe;
const touchedStore = ["WALLET_STORE", "SUPABASE_URL", "SUPABASE_SERVICE_ROLE_KEY"].some((k) => k in set || clear.includes(k as SettingKey));
if (touchedStore) {
if (clear.some((k) => k === "SUPABASE_URL" || k === "SUPABASE_SERVICE_ROLE_KEY") && this.storeMode === "supabase") this.values.set("WALLET_STORE", "memory");
this.applyStore();
}
for (const k of clear) this.persisted.delete(k);
let persisted = false; let persistError: string | undefined;
const effective: Partial<Record<SettingKey, string>> = { ...set };
if (clear.includes("SUPABASE_SERVICE_ROLE_KEY") || clear.includes("SUPABASE_URL")) effective.WALLET_STORE = "memory";
if (persist) {
if (!this.persister?.available) persistError = "No server-side Hugging Face token is configured, so settings were kept in memory only.";
else {
try { await this.persister.persist(effective, clear); persisted = true; for (const k of Object.keys(effective)) this.persisted.add(k as SettingKey); }
catch (e) { persistError = this.redact((e as Error).message); }
}
}
return { changed: Object.keys(set) as SettingKey[], cleared: clear, persisted, persistError };
}
async testStripe(): Promise<{ ok: boolean; message: string }> {
if (!this.stripe) return { ok: false, message: "No Stripe key configured." };
try {
const bal = await this.stripe.balance.retrieve();
if (bal.livemode) return { ok: false, message: "Key is LIVE mode. Refusing." };
const wh = this.webhookSecret ? "Webhook signing secret is set." : "Webhook signing secret not set yet (needed to credit the wallet after payment).";
return { ok: true, message: `Connected to Stripe in test mode. ${wh}` };
} catch (e) { return { ok: false, message: this.redact((e as Error).message) }; }
}
async testSupabase(): Promise<{ ok: boolean; message: string }> {
const url = this.get("SUPABASE_URL"), key = this.get("SUPABASE_SERVICE_ROLE_KEY");
if (!url || !key) return { ok: false, message: "Supabase URL and service role key are both required." };
try {
const r = await fetch(`${url.replace(/\/$/, "")}/rest/v1/wallet_accounts?select=id&limit=1`, { headers: { apikey: key, authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(10_000) });
if (r.ok) return { ok: true, message: "Connected to Supabase; wallet tables found." };
const body = await r.text();
if (r.status === 401 || r.status === 403) return { ok: false, message: "Supabase rejected the service role key." };
if (r.status === 404 || /PGRST205|does not exist|schema cache/i.test(body)) return { ok: true, message: "Connected to Supabase, but the wallet tables are missing. Run the SQL migrations (download below), then test again." };
return { ok: false, message: this.redact(`Supabase responded ${r.status}: ${body.slice(0, 200)}`) };
} catch (e) { return { ok: false, message: this.redact(`Could not reach Supabase: ${(e as Error).message}`) }; }
}
}
export function mask(v: string): string {
const prefix = /^(sk_test_|rk_test_|whsec_|sb_secret_)/.exec(v)?.[1] ?? "";
return `${prefix}••••••••${v.slice(-4)}`;
}
/** Persists settings as Hugging Face Space secrets (server-side token; never sent to the browser). */
export class HfSecretsPersister implements Persister {
available: boolean;
describe: string;
constructor(private spaceId: string | undefined, private token: string | undefined, private base = "https://huggingface.co") {
this.available = Boolean(spaceId && token);
this.describe = this.available ? `Saved as Hugging Face Space secrets on ${spaceId} (the Space restarts after saving).` : "Not available: HF_SPACE_TOKEN / SPACE_ID not set.";
}
private async call(method: "POST" | "DELETE", body: Record<string, string>) {
const r = await fetch(`${this.base}/api/spaces/${this.spaceId}/secrets`, { method, headers: { authorization: `Bearer ${this.token}`, "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000) });
if (!r.ok) throw new Error(`Hugging Face API ${method} secret failed (${r.status})`);
}
async persist(set: Partial<Record<SettingKey, string>>, clear: SettingKey[]) {
await Promise.all([
...Object.entries(set).map(([key, value]) => this.call("POST", { key, value: value! })),
...clear.map((key) => this.call("DELETE", { key })),
]);
}
}