Watchtower commited on
Commit ·
1444c0a
1
Parent(s): 8341c00
Deploy GitHub main 67e6ec2 (PR #2: wallet UI, devices, settings)
Browse filesFiles changed (25)
- Dockerfile+1
- services/wallet/.env.exampleAdded+11
- services/wallet/README.md+21
- services/wallet/public/404.htmlAdded+11
- services/wallet/public/app.css+12
- services/wallet/public/app.js+17-19
- services/wallet/public/common.jsAdded+42
- services/wallet/public/devices.htmlAdded+22
- services/wallet/public/devices.jsAdded+29
- services/wallet/public/favicon.svgAdded
- services/wallet/public/funding/cancel.htmlAdded+11
- services/wallet/public/funding/success.htmlAdded+11
- services/wallet/public/index.html+10-5
- services/wallet/public/links.json+51-7
- services/wallet/public/settings.htmlAdded+24
- services/wallet/public/settings.jsAdded+66
- services/wallet/src/admin.tsAdded+104
- services/wallet/src/app.ts+58-17
- services/wallet/src/devices.tsAdded+94
- services/wallet/src/index.ts+12-8
- services/wallet/src/ledger.ts+11
- services/wallet/src/runtime.tsAdded+239
- services/wallet/supabase/migrations/20261202000000_wallet_devices.sqlAdded+15
- services/wallet/test/admin.test.tsAdded+249
- services/wallet/test/app.test.ts+1-1
15 unmodified lines16171819202115 unmodified linesCOPY --from=build --chown=node /app/services/wallet/dist ./distCOPY --chown=node services/wallet/package.json ./COPY --chown=node services/wallet/public ./publicENV NODE_ENV=production PORT=7860EXPOSE 7860CMD ["node", "dist/index.js"]15 unmodified lines1617181920212215 unmodified linesCOPY --from=build --chown=node /app/services/wallet/dist ./distCOPY --chown=node services/wallet/package.json ./COPY --chown=node services/wallet/public ./publicCOPY --chown=node services/wallet/supabase ./supabaseENV NODE_ENV=production PORT=7860EXPOSE 7860CMD ["node", "dist/index.js"]
1234567891011# Wallet service — copy to .env and fill with TEST values only. Never commit real values.PORT=7860WALLET_USER_ID=00000000-0000-0000-0000-000000000001STRIPE_SECRET_KEY=sk_test_REPLACE_MESTRIPE_WEBHOOK_SECRET=whsec_REPLACE_MESTRIPE_SUCCESS_URL=http://localhost:7860/funding/successSTRIPE_CANCEL_URL=http://localhost:7860/funding/cancelSUPABASE_URL=https://YOUR_PROJECT.supabase.coSUPABASE_SERVICE_ROLE_KEY=REPLACE_ME# Set to "memory" to run without Supabase (dev/tests)WALLET_STORE=supabase2 unmodified lines3452 unmodified linesPersonal-use wallet backend (TEST mode only): double-entry ledger, Stripe test funding(Checkout / PaymentIntents + signature-verified webhooks), QR-invoice payment routing,Supabase persistence. See root README "Wallet service" section.2 unmodified lines345678910111213141516171819202122232425262 unmodified linesPersonal-use wallet backend (TEST mode only): double-entry ledger, Stripe test funding(Checkout / PaymentIntents + signature-verified webhooks), QR-invoice payment routing,Supabase persistence. See root README "Wallet service" section.## Web UI| Page | Purpose ||---|---|| `/` | Wallet: balance, add funds (Stripe Checkout), pay invoice by QR payload, transactions, app links || `/devices` | Add / remove phones and devices (phone numbers normalised to E.164). Requires sign-in || `/settings` | Enter Stripe **test** keys and Supabase URL + service role key, test each connection, switch storage. Requires sign-in || `/funding/success`, `/funding/cancel` | Stripe Checkout return pages |### Admin passcode and secrets* Set `ADMIN_PASSCODE` (env / Space secret). Without it `/settings` and `/devices` are disabled.* Secrets typed on `/settings` are held server-side only. They are never returned to the browser (only a masked tail),never logged, and error text is redacted. Live Stripe keys (`sk_live_`/`rk_live_`) are refused.* To survive restarts the server writes them as Hugging Face **Space secrets** using `HF_SPACE_TOKEN` + theSpace-provided `SPACE_ID` (the Space restarts after a save). Without a token they stay in memory only.Prefer a fine-grained token limited to this Space.* With `WALLET_STORE=memory` balances and devices reset on restart. Run the SQL in `supabase/migrations/`(downloadable from `/settings`), then switch storage to `supabase` for durable data.* `/wallet/test-credit` (signed in) adds simulated test credit so the wallet can be exercised before Stripe is configured.
1234567891011<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Page not found — ProjectOS</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><link rel="stylesheet" href="/app.css"></head><body><header class="top" id="top"></header><main class="wrap"><p class="eyebrow">404</p><h1>Page not <span>found</span></h1><div class="card"><p>That page doesn't exist. Try one of these:</p><div class="row"><a class="btn" href="/">Wallet</a><a class="btn" href="/devices">Devices</a><a class="btn" href="/settings">Settings</a></div></div></main><footer id="status" class="foot">Checking status…</footer><script src="/common.js"></script></body></html>22 unmodified lines23242522 unmodified lines.app.disabled{opacity:.55;cursor:not-allowed;background:#f7f6f9}.foot{text-align:center;color:var(--muted);font-size:12px;padding:16px;border-top:1px solid var(--line);background:#fff}@media(max-width:760px){.grid2{grid-template-columns:1fr}.wrap{padding:22px 16px 60px}.top{padding:0 16px}h1{font-size:24px}}22 unmodified lines23242526272829303132333435363722 unmodified lines.app.disabled{opacity:.55;cursor:not-allowed;background:#f7f6f9}.foot{text-align:center;color:var(--muted);font-size:12px;padding:16px;border-top:1px solid var(--line);background:#fff}@media(max-width:760px){.grid2{grid-template-columns:1fr}.wrap{padding:22px 16px 60px}.top{padding:0 16px}h1{font-size:24px}}.top .nav{display:flex;gap:4px;margin-left:28px;flex:1}.top .nav a{color:var(--muted);text-decoration:none;padding:8px 12px;border-radius:7px;font-weight:600}.top .nav a:hover{background:#f4f2fb;color:var(--ink)}.top .nav a.active{background:#f0edff;color:var(--purple)}.top .brand{text-decoration:none;color:var(--ink)}.top .right{display:flex;gap:14px;align-items:center}.signin,.link{color:var(--purple);font-weight:600;text-decoration:none;background:none;border:0;cursor:pointer;font:inherit;font-weight:600;padding:0}.stack>*{margin-bottom:10px}label{display:block;font-weight:600;font-size:12px;margin:12px 0 5px}select{font:inherit;border:1px solid var(--line);border-radius:7px;padding:9px;background:#fdfdfe}input.wide,select.wide{width:100%;max-width:520px}.btn{border:1px solid var(--line);background:#fff;padding:9px 14px;border-radius:7px;cursor:pointer;font:inherit;font-weight:600}.btn:hover{border-color:#d9d4f5}.btn.danger{color:var(--red)}.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.pill{display:inline-block;padding:2px 8px;border-radius:99px;font-size:11px;font-weight:700}.pill.on{background:#e8f6ef;color:var(--green)}.pill.off{background:#f3f2f6;color:var(--muted)}.hint{color:var(--muted);font-size:12px;margin:4px 0 0}.field{padding:14px 0;border-top:1px solid #f1f0f3}.field:first-of-type{border-top:0}code,.mono{font-family:ui-monospace,monospace;font-size:12px;background:#f6f5f9;padding:2px 6px;border-radius:5px}.app .priv{display:inline-block;margin-left:6px;font-size:10px;color:#b5813b;background:#fff8ed;border:1px solid #f3e8d6;border-radius:99px;padding:1px 7px;font-weight:700;vertical-align:middle}.devs{list-style:none;margin:0;padding:0}.devs li{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:12px 0;border-top:1px solid #f1f0f3}.devs li:first-child{border-top:0}.devs small{display:block;color:var(--muted);margin-top:3px}.grid3{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}
123456789104 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849const $ = (id) => document.getElementById(id);const fmt = (minor, cur = "usd") => new Intl.NumberFormat(undefined, { style: "currency", currency: cur.toUpperCase() }).format(minor / 100);const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));async function api(path, opts) {const r = await fetch(path, opts); let body = {}; try { body = await r.json(); } catch {}return { ok: r.ok, status: r.status, body };}async function loadBalance() { const r = await api("/wallet/balance?currency=usd"); $("balance").textContent = r.ok ? fmt(r.body.balance, r.body.currency) : "Unavailable"; }async function loadTxs() {const r = await api("/wallet/transactions"); const ul = $("txs");4 unmodified linesreturn `<li><div><strong>${esc(t.memo || t.kind)}</strong><small>${esc(t.kind)} · ${new Date(t.created_at).toLocaleString()}</small></div><span class="amt ${pos ? "pos" : "neg"}">${pos ? "+" : "−"}${fmt(amt)}</span></li>`;}).join("");}function msg(el, cls, text) { el.className = "msg " + cls; el.textContent = text; }$("payForm").addEventListener("submit", async (e) => {e.preventDefault(); const qr = $("qr").value.trim(); const m = $("payMsg");if (!qr) return msg(m, "err", "Paste an invoice QR payload first.");const r = await api("/invoices/pay", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ qr }) });if (r.ok) { msg(m, "ok", r.body.status === "already_paid" ? "This invoice was already paid." : `Paid ✓ — new balance ${fmt(r.body.balance)}`); $("qr").value = ""; refresh(); }else msg(m, "err", r.body.error || `Payment failed (${r.status})`);});$("fund").addEventListener("click", async () => {const m = $("fundMsg"); const amount = Math.round(Number($("fundAmt").value) * 100);$("fund").disabled = true;const r = await api("/funding/checkout", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ amount, currency: "usd" }) });$("fund").disabled = false;if (r.status === 503) return msg(m, "warn", "Stripe not configured yet — add Stripe TEST keys as Space secrets to enable top-ups.");if (r.ok && r.body.url) { location.href = r.body.url; return; }msg(m, "err", r.body.error || `Could not start checkout (${r.status})`);});async function loadApps() {const r = await api("/links.json"); const el = $("apps"); if (!r.ok) { el.innerHTML = '<p class="muted">No apps configured.</p>'; return; }el.innerHTML = r.body.apps.map((a) => {const ic = esc(a.name.slice(0, 1));if (!a.url) return `<div class="app disabled" aria-disabled="true"><div class="ic">${ic}</div><strong>${esc(a.name)}</strong><small>Coming soon</small></div>`;const sec = a.secondary ? `<a class="sec" href="${esc(a.secondary.url)}" target="_blank" rel="noopener">${esc(a.secondary.label)} ↗</a>` : "";return `<div class="app"><a href="${esc(a.url)}" target="_blank" rel="noopener" style="text-decoration:none;color:inherit;display:block"><div class="ic">${ic}</div><strong>${esc(a.name)} ↗</strong><small>${esc(a.description || "")}</small></a>${sec}</div>`;}).join("");}async function loadStatus() {const r = await api("/healthz");$("status").textContent = r.ok ? `● Service OK · mode: ${r.body.mode} · Stripe: ${r.body.stripe ? "configured" : "not configured"} · ${new Date().toLocaleTimeString()}` : "Service unreachable";}function refresh() { loadBalance(); loadTxs(); loadStatus(); }refresh(); loadApps();1234 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647async function loadBalance() { const r = await api("/wallet/balance?currency=usd"); $("balance").textContent = r.ok ? fmt(r.body.balance, r.body.currency) : "Unavailable"; }async function loadTxs() {const r = await api("/wallet/transactions"); const ul = $("txs");4 unmodified linesreturn `<li><div><strong>${esc(t.memo || t.kind)}</strong><small>${esc(t.kind)} · ${new Date(t.created_at).toLocaleString()}</small></div><span class="amt ${pos ? "pos" : "neg"}">${pos ? "+" : "−"}${fmt(amt)}</span></li>`;}).join("");}$("example").addEventListener("click", () => { $("qr").value = JSON.stringify({ v: 1, invoice_id: "INV-" + Date.now().toString(36), merchant_id: "demo-merchant", merchant_name: "Demo Merchant", amount: 500, currency: "usd" }); });$("payForm").addEventListener("submit", async (e) => {e.preventDefault(); const qr = $("qr").value.trim(); const m = $("payMsg");if (!qr) return msg(m, "err", "Paste an invoice QR payload first (or click “Fill example”).");const r = await api("/invoices/pay", { method: "POST", body: { qr } });if (r.ok) { msg(m, "ok", r.body.status === "already_paid" ? "This invoice was already paid." : `Paid ✓ — new balance ${fmt(r.body.balance)}`); $("qr").value = ""; refresh(); }else msg(m, "err", r.body.error || `Payment failed (${r.status})`);});$("fund").addEventListener("click", async () => {const m = $("fundMsg"); const amount = Math.round(Number($("fundAmt").value) * 100);if (!(amount >= 50)) return msg(m, "err", "Enter an amount of at least $0.50.");$("fund").disabled = true;const r = await api("/funding/checkout", { method: "POST", body: { amount, currency: "usd" } });$("fund").disabled = false;if (r.status === 503) { $("testCredit").hidden = false; return msg(m, "warn", "Stripe isn't configured yet."); }if (r.ok && r.body.url) { location.href = r.body.url; return; }msg(m, "err", r.body.error || `Could not start checkout (${r.status})`);});$("testCreditBtn").addEventListener("click", async () => {const m = $("fundMsg"); const amount = Math.round(Number($("fundAmt").value) * 100);const r = await api("/wallet/test-credit", { method: "POST", body: { amount } });if (r.status === 401 || r.status === 503) return msg(m, "warn", "Sign in first (Settings page) to add simulated credit.");if (r.ok) { msg(m, "ok", `Added simulated credit ✓ — balance ${fmt(r.body.balance)}`); refresh(); } else msg(m, "err", r.body.error || `Failed (${r.status})`);});async function loadApps() {const r = await api("/links.json"); const el = $("apps"); if (!r.ok) { el.innerHTML = '<p class="muted">No apps configured.</p>'; return; }el.innerHTML = r.body.apps.map((a) => {const ic = esc(a.name.slice(0, 1));if (!a.url) return `<div class="app disabled" aria-disabled="true"><div class="ic">${ic}</div><strong>${esc(a.name)}</strong><small>Coming soon</small></div>`;const priv = (u) => (u.private ? '<span class="priv" title="Private — opens only when you are signed in to the owning account">private</span>' : "");const sec = a.secondary ? `<a class="sec" href="${esc(a.secondary.url)}" target="_blank" rel="noopener">${esc(a.secondary.label)} ↗</a>${priv(a.secondary)}` : "";return `<div class="app"><a href="${esc(a.url)}" target="_blank" rel="noopener" style="text-decoration:none;color:inherit;display:block"><div class="ic">${ic}</div><strong>${esc(a.name)} ↗${priv(a)}</strong><small>${esc(a.description || "")}</small></a>${sec}</div>`;}).join("");}async function loadTestCreditHint() { const r = await api("/healthz"); if (r.ok && !r.body.stripe) $("testCredit").hidden = false; }function refresh() { loadBalance(); loadTxs(); loadStatus(); }refresh(); loadApps(); loadTestCreditHint();
123456789101112131415161718192021222324252627282930313233343536373839404142/* Shared helpers + header/nav for every ProjectOS wallet page. */const $ = (id) => document.getElementById(id);const fmt = (minor, cur = "usd") => new Intl.NumberFormat(undefined, { style: "currency", currency: cur.toUpperCase() }).format(minor / 100);const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));async function api(path, opts = {}) { const o = { credentials: "same-origin", ...opts }; if (o.body && typeof o.body !== "string") { o.body = JSON.stringify(o.body); o.headers = { "content-type": "application/json", ...(o.headers || {}) }; } let r; try { r = await fetch(path, o); } catch { return { ok: false, status: 0, body: { error: "Network error: could not reach the server." } }; } let body = {}; try { body = await r.json(); } catch {} return { ok: r.ok, status: r.status, body };}function msg(el, cls, text) { el.className = "msg " + cls; el.textContent = text; }
const NAV = [["/", "Wallet"], ["/devices", "Devices"], ["/settings", "Settings"]];function renderHeader() { const here = location.pathname.replace(/\/$/, "") || "/"; const links = NAV.map(([h, t]) => `<a href="${h}"${(here === h || here === h + ".html") ? ' class="active" aria-current="page"' : ""}>${t}</a>`).join(""); $("top").innerHTML = `<a class="brand" href="/"><span class="mark">◆</span>Project<span class="light">OS</span></a> <nav class="nav" aria-label="Main">${links}</nav> <div class="right"><span class="badge">TEST MODE</span><span id="who"></span></div>`; api("/api/admin/session").then((r) => { const authed = r.ok && r.body.authenticated; $("who").innerHTML = authed ? '<button class="link" id="logout" type="button">Sign out</button>' : '<a class="signin" href="/settings">Sign in</a>'; if (authed) $("logout").addEventListener("click", async () => { await api("/api/admin/logout", { method: "POST", body: {} }); location.href = "/"; }); });}async function loadStatus() { const r = await api("/healthz"); const el = $("status"); if (!el) return; el.textContent = r.ok ? `● Service OK · TEST mode · Stripe: ${r.body.stripe ? "configured" : "not configured"} · storage: ${r.body.store} · ${new Date().toLocaleTimeString()}` : "Service unreachable";}/** Shows an inline sign-in form inside `host`; calls onDone() after success. */function signInForm(host, onDone, note) { host.innerHTML = `<form id="loginForm" class="stack"><div class="label">SIGN IN</div>${note ? `<p class="muted">${esc(note)}</p>` : ""} <label for="passcode">Admin passcode</label><input id="passcode" type="password" autocomplete="current-password" required style="width:100%;max-width:340px"> <div><button class="primary" type="submit">Sign in</button></div><div id="loginMsg" class="msg" role="status"></div></form>`; $("loginForm").addEventListener("submit", async (e) => { e.preventDefault(); const r = await api("/api/admin/login", { method: "POST", body: { passcode: $("passcode").value } }); if (r.ok) { $("passcode").value = ""; onDone(); } else msg($("loginMsg"), "err", r.body.error || `Sign-in failed (${r.status})`); });}renderHeader(); loadStatus();12345678910111213141516171819202122<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Devices — ProjectOS</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><link rel="stylesheet" href="/app.css"></head><body><header class="top" id="top"></header><main class="wrap"><p class="eyebrow">DEVICES <span class="rule"></span> PHONES</p><h1>Phones & <span>devices</span></h1><div id="gate" class="card" hidden></div><div id="content" hidden><section class="card"><div class="label">ADD A PHONE OR DEVICE</div><form id="devForm" class="stack" novalidate> <label for="label">Name</label><input class="wide" id="label" maxlength="60" placeholder="e.g. Pixel 9, Work iPhone" required style="width:100%"> <div class="row"><div><label for="kind">Type</label><select id="kind"><option value="phone">Phone</option><option value="tablet">Tablet</option><option value="watch">Watch</option><option value="other">Other</option></select></div> <div><label for="platform">Platform</label><select id="platform"><option value="ios">iOS</option><option value="android">Android</option><option value="other">Other</option></select></div></div> <label for="phone">Phone number (optional)</label><input class="wide" id="phone" type="tel" placeholder="+1 415 555 0123" style="width:100%"> <p class="hint">International format, or a 10-digit US number. Stored as +E.164.</p> <div><button class="primary" type="submit">Add device</button></div><div id="devMsg" class="msg" role="status"></div></form></section><section class="card" style="margin-top:14px"><div class="label">YOUR DEVICES</div><ul id="devs" class="devs"><li class="muted">Loading…</li></ul></section></div></main><footer id="status" class="foot">Checking status…</footer><script src="/common.js"></script><script src="/devices.js"></script></body></html>1234567891011121314151617181920212223242526272829const ICON = { phone: "📱", tablet: "▭", watch: "⌚", other: "◻" };async function loadDevices() { const r = await api("/api/devices"); const ul = $("devs"); if (r.status === 401 || r.status === 503) return showGate(r); if (!r.ok) { ul.innerHTML = `<li class="err">${esc(r.body.error || "Could not load devices")}</li>`; return; } $("gate").hidden = true; $("content").hidden = false; if (!r.body.length) { ul.innerHTML = '<li class="muted">No devices yet. Add your first phone above.</li>'; return; } ul.innerHTML = r.body.map((d) => `<li><div><strong>${ICON[d.kind] || ""} ${esc(d.label)}</strong><small>${esc(d.kind)} · ${esc(d.platform)}${d.phone ? " · " + esc(d.phone) : ""} · added ${new Date(d.created_at).toLocaleDateString()}</small></div><button class="btn danger" data-id="${esc(d.id)}" type="button">Remove</button></li>`).join(""); ul.querySelectorAll("button[data-id]").forEach((b) => b.addEventListener("click", async () => { if (!confirm("Remove this device?")) return; const x = await api("/api/devices/" + encodeURIComponent(b.dataset.id), { method: "DELETE" }); if (x.ok) loadDevices(); else msg($("devMsg"), "err", x.body.error || "Could not remove device"); }));}function showGate(r) { $("content").hidden = true; $("gate").hidden = false; if (r.status === 503) { $("gate").innerHTML = '<div class="label">NOT AVAILABLE</div><p>The admin passcode is not configured on the server, so devices (which hold phone numbers) are locked. Set <code>ADMIN_PASSCODE</code> as a Space secret.</p>'; return; } signInForm($("gate"), loadDevices, "Devices hold phone numbers, so this page needs the admin passcode.");}$("devForm").addEventListener("submit", async (e) => { e.preventDefault(); const m = $("devMsg"); const label = $("label").value.trim(); if (!label) return msg(m, "err", "Give the device a name."); const body = { label, kind: $("kind").value, platform: $("platform").value }; const phone = $("phone").value.trim(); if (phone) body.phone = phone; const r = await api("/api/devices", { method: "POST", body }); if (r.status === 401) return showGate(r); if (r.ok) { msg(m, "ok", `Added ${r.body.label}${r.body.phone ? " (" + r.body.phone + ")" : ""} ✓`); $("devForm").reset(); loadDevices(); } else msg(m, "err", r.body.error || `Could not add device (${r.status})`);});loadDevices();1234567891011<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Checkout cancelled — ProjectOS</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><link rel="stylesheet" href="/app.css"></head><body><header class="top" id="top"></header><main class="wrap"><p class="eyebrow">FUNDING</p><h1>Checkout <span>cancelled</span></h1><div class="card"><p>No money moved and your balance is unchanged.</p><div class="row"><a class="primary" style="text-decoration:none" href="/">Back to wallet</a></div></div></main><footer id="status" class="foot">Checking status…</footer><script src="/common.js"></script></body></html>1234567891011<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Payment received — ProjectOS</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><link rel="stylesheet" href="/app.css"></head><body><header class="top" id="top"></header><main class="wrap"><p class="eyebrow">FUNDING</p><h1>Payment <span>submitted</span></h1><div class="card"><p>Thanks — Stripe (test mode) reported a successful checkout. Your balance updates as soon as Stripe's webhook reaches this app (usually a few seconds).</p><p class="hint">If the balance does not change, check that the webhook signing secret is saved on the Settings page.</p><div class="row"><a class="primary" style="text-decoration:none" href="/">Back to wallet</a><a class="btn" href="/settings">Settings</a></div></div></main><footer id="status" class="foot">Checking status…</footer><script src="/common.js"></script></body></html>12345678910111213141516171819202122<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>ProjectOS — Wallet</title><link rel="stylesheet" href="/app.css"></head><body><header class="top"><div class="brand"><span class="mark">◆</span>Project<span class="light">OS</span></div><span class="badge">TEST MODE</span></header><main class="wrap"><p class="eyebrow">WALLET <span class="rule"></span> PERSONAL</p><h1>Welcome back, <span>Architect</span></h1><section class="grid2"><div class="card balance"><div class="label">WALLET BALANCE</div><div id="balance" class="big">—</div><div class="row"><button id="fund" class="primary">+ Add funds</button><input id="fundAmt" type="number" min="0.5" step="0.01" value="25" aria-label="Amount (USD)"></div><div id="fundMsg" class="msg"></div></div><div class="card"><div class="label">PAY INVOICE</div><form id="payForm"><textarea id="qr" rows="4" placeholder='Paste QR payload: {"v":1,"invoice_id":"INV-1","merchant_id":"m1","amount":1200,"currency":"usd"} or projectos-invoice:?v=1&...'></textarea><button class="primary" type="submit">Pay from balance</button></form><div id="payMsg" class="msg"></div></div></section><section class="card"><div class="label">RECENT TRANSACTIONS</div><ul id="txs" class="txs"><li class="muted">Loading…</li></ul></section><h2>Apps</h2><section id="apps" class="apps"></section></main><footer id="status" class="foot">Checking status…</footer><script src="/app.js"></script></body></html>123456789101112131415161718192021222324252627<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>ProjectOS — Wallet</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><link rel="stylesheet" href="/app.css"></head><body><header class="top" id="top"></header><main class="wrap"><p class="eyebrow">WALLET <span class="rule"></span> PERSONAL</p><h1>Welcome back, <span>Architect</span></h1><section class="grid2"><div class="card balance"><div class="label">WALLET BALANCE</div><div id="balance" class="big">—</div><div class="row"><button id="fund" class="primary">+ Add funds</button><input id="fundAmt" type="number" min="0.5" step="0.01" value="25" aria-label="Amount (USD)"></div><div id="fundMsg" class="msg" role="status"></div><div id="testCredit" class="hint" hidden>Stripe isn't set up yet. <button class="link" id="testCreditBtn" type="button">Add simulated test credit</button> (sign-in required) to try the wallet, or <a href="/settings">enter Stripe test keys</a>.</div></div><div class="card"><div class="label">PAY INVOICE</div><form id="payForm"><textarea id="qr" rows="4" placeholder='Paste QR payload: {"v":1,"invoice_id":"INV-1","merchant_id":"m1","amount":1200,"currency":"usd"} or projectos-invoice:?v=1&...'></textarea><div class="row"><button class="primary" type="submit">Pay from balance</button><button class="btn" id="example" type="button">Fill example ($5.00)</button></div></form><div id="payMsg" class="msg" role="status"></div></div></section><section class="grid3" style="margin-bottom:14px"><a class="card app" href="/devices" style="text-decoration:none;color:inherit"><strong>Phones & devices</strong><small>Add or remove the phones linked to this wallet.</small></a><a class="card app" href="/settings" style="text-decoration:none;color:inherit"><strong>Settings & keys</strong><small>Enter Stripe test keys and Supabase credentials.</small></a></section><section class="card"><div class="label">RECENT TRANSACTIONS</div><ul id="txs" class="txs"><li class="muted">Loading…</li></ul></section><h2>Apps</h2><section id="apps" class="apps"></section></main><footer id="status" class="foot">Checking status…</footer><script src="/common.js"></script><script src="/app.js"></script></body></html>
1234567891011{"apps": [{ "name": "KlawChat", "description": "Retrieval chat", "url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/klawchat-retrieval", "secondary": { "label": "GitHub", "url": "https://github.com/mindtdilly/klaw-chat" } },{ "name": "Klaw Command", "description": "Workbench", "url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/klaw-workbench" },{ "name": "OpenKlaw", "description": "Modules", "url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/openclaw-modules" },{ "name": "ProcureNet", "description": "Procurement atlas", "url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/procure-atlas", "secondary": { "label": "GitHub", "url": "https://github.com/mindtdilly/Procurenet" } },{ "name": "KlawPay", "description": "Wallet atlas", "url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/wallet-atlas", "secondary": { "label": "GitHub", "url": "https://github.com/mindtdilly/Omnipay" } },{ "name": "ProcureMe", "description": "Coming soon", "url": null },{ "name": "ChargeMe", "description": "Coming soon", "url": null }]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{"apps": [{"name": "KlawChat","description": "Retrieval chat","url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/klawchat-retrieval","secondary": {"label": "GitHub","url": "https://github.com/mindtdilly/klaw-chat"},"private": true},{"name": "Klaw Command","description": "Workbench","url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/klaw-workbench","private": true},{"name": "OpenKlaw","description": "Modules","url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/openclaw-modules","private": true},{"name": "ProcureNet","description": "Procurement atlas","url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/procure-atlas","secondary": {"label": "GitHub","url": "https://github.com/mindtdilly/Procurenet","private": true}},{"name": "KlawPay","description": "Wallet atlas","url": "https://huggingface.co/spaces/AnthropicallyHuggingFaces/wallet-atlas","secondary": {"label": "GitHub","url": "https://github.com/mindtdilly/Omnipay"}},{"name": "ProcureMe","description": "Coming soon","url": null},{"name": "ChargeMe","description": "Coming soon","url": null}]}
123456789101112131415161718192021222324<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Settings — ProjectOS</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><link rel="stylesheet" href="/app.css"></head><body><header class="top" id="top"></header><main class="wrap"><p class="eyebrow">SETTINGS <span class="rule"></span> KEYS</p><h1>Keys & <span>setup</span></h1><div id="gate" class="card" hidden></div><div id="content" hidden><section class="card"><div class="label">STATUS</div><div id="summary" class="stack"></div></section><form id="setForm" class="card" style="margin-top:14px" autocomplete="off" novalidate> <div class="label">STRIPE (TEST MODE ONLY)</div><div id="stripeFields"></div> <p class="hint">Webhook endpoint to add in Stripe (test mode): <code id="whUrl"></code></p> <div class="row"><button class="btn" type="button" id="testStripe">Test Stripe connection</button></div><div id="stripeMsg" class="msg" role="status"></div> <div class="label" style="margin-top:22px">SUPABASE</div><div id="supaFields"></div> <div class="row"><button class="btn" type="button" id="testSupa">Test Supabase connection</button><a class="btn" href="/api/admin/migrations.sql" download>Download SQL migrations</a></div><div id="supaMsg" class="msg" role="status"></div> <div class="field"><label class="row" style="font-weight:500"><input type="checkbox" id="persist" style="width:auto"> <span id="persistLabel">Also save as Space secrets so they survive restarts</span></label></div> <div class="row"><button class="primary" type="submit">Save settings</button></div><div id="saveMsg" class="msg" role="status"></div> <p class="hint">Secret values are written to the server only and are never shown again — fields stay blank and only a masked tail is displayed. Leave a field blank to keep its current value.</p></form></div></main><footer id="status" class="foot">Checking status…</footer><script src="/common.js"></script><script src="/settings.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566let state = null;const STRIPE = ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET", "STRIPE_SUCCESS_URL", "STRIPE_CANCEL_URL"];const SUPA = ["SUPABASE_URL", "SUPABASE_SERVICE_ROLE_KEY", "WALLET_STORE"];function fieldHtml(s) { const pill = s.configured ? '<span class="pill on">configured</span>' : '<span class="pill off">not set</span>'; const kept = s.persisted ? ' <span class="pill on">saved as Space secret</span>' : ""; let input; if (s.key === "WALLET_STORE") input = `<select class="wide" id="f_${s.key}"><option value="memory"${s.value !== "supabase" ? " selected" : ""}>memory (resets on restart)</option><option value="supabase"${s.value === "supabase" ? " selected" : ""}>supabase (durable)</option></select>`; else if (s.secret) input = `<input class="wide" id="f_${s.key}" type="password" autocomplete="new-password" spellcheck="false" placeholder="${s.configured ? "Current: " + esc(s.masked) + " — type to replace" : "Not set"}">`; else input = `<input class="wide" id="f_${s.key}" type="url" spellcheck="false" value="${esc(s.value)}" placeholder="${s.key.startsWith("STRIPE") ? "Default: this app" : ""}">`; const clr = s.configured && s.key !== "WALLET_STORE" ? `<label class="row" style="font-weight:400;margin:6px 0 0"><input type="checkbox" id="c_${s.key}" style="width:auto"> Remove this value</label>` : ""; return `<div class="field"><div class="row"><strong>${esc(s.label)}</strong>${pill}${kept}</div><div>${input}</div><p class="hint">${esc(s.hint)}</p><div class="msg err" id="e_${s.key}"></div>${clr}</div>`;}function render(st) { state = st; const by = Object.fromEntries(st.settings.map((s) => [s.key, s])); $("stripeFields").innerHTML = STRIPE.map((k) => fieldHtml(by[k])).join(""); $("supaFields").innerHTML = SUPA.map((k) => fieldHtml(by[k])).join(""); if (!st.canSwitchStore) $("f_WALLET_STORE").disabled = true; $("whUrl").textContent = st.webhookUrl; $("summary").innerHTML = `<div class="row"><span>Stripe:</span> ${by.STRIPE_SECRET_KEY.configured && by.STRIPE_WEBHOOK_SECRET.configured ? '<span class="pill on">ready</span>' : '<span class="pill off">incomplete</span>'} <span>Storage:</span> <span class="pill ${st.storeMode === "supabase" ? "on" : "off"}">${esc(st.storeMode)}</span></div> <p class="hint">${st.storeMode === "memory" ? "Running in memory: balances and devices reset when the Space restarts. Add Supabase and switch storage to supabase to keep them." : "Balances and devices are stored in Supabase."}</p> <p class="hint">${esc(st.persistence.describe)}</p>`; const p = $("persist"); p.disabled = !st.persistence.available; if (!st.persistence.available) p.checked = false; else if (p.dataset.init !== "1") { p.checked = true; p.dataset.init = "1"; } $("persistLabel").textContent = st.persistence.available ? "Also save as Space secrets so they survive restarts (the Space restarts, which resets memory-mode data)" : "Space-secret persistence unavailable — values are kept in memory only until restart";}async function load() { const s = await api("/api/admin/session"); if (s.ok && !s.body.configured) { $("content").hidden = true; $("gate").hidden = false; $("gate").innerHTML = '<div class="label">NOT AVAILABLE</div><p>The admin passcode is not configured on the server. Set <code>ADMIN_PASSCODE</code> as a Space secret, then reload.</p>'; return; } if (!(s.ok && s.body.authenticated)) { $("content").hidden = true; $("gate").hidden = false; return signInForm($("gate"), load, "Enter the admin passcode to manage Stripe and Supabase keys."); } const r = await api("/api/admin/settings"); if (!r.ok) { $("gate").hidden = false; $("gate").textContent = r.body.error || "Could not load settings"; return; } $("gate").hidden = true; $("content").hidden = false; render(r.body);}$("setForm").addEventListener("submit", async (e) => { e.preventDefault(); const m = $("saveMsg"); document.querySelectorAll('[id^="e_"]').forEach((el) => (el.textContent = "")); const values = {}; const clear = []; for (const s of state.settings) { const el = $("f_" + s.key); if (!el) continue; const c = $("c_" + s.key); if (c && c.checked) { clear.push(s.key); continue; } const v = el.value.trim(); if (s.key === "WALLET_STORE") { if (v !== state.storeMode) values[s.key] = v; } else if (s.secret) { if (v) values[s.key] = v; } else if (v !== (s.value || "")) { if (v) values[s.key] = v; else if (s.configured) clear.push(s.key); } } if (!Object.keys(values).length && !clear.length) return msg(m, "warn", "Nothing to save — no fields changed."); const r = await api("/api/admin/settings", { method: "PUT", body: { values, clear, persist: $("persist").checked } }); for (const k of STRIPE.concat(SUPA)) if ($("f_" + k) && $("f_" + k).type === "password") $("f_" + k).value = ""; // never keep secrets in the page if (r.status === 401) return load(); if (!r.ok) { for (const [k, v] of Object.entries(r.body.fields || {})) if ($("e_" + k)) $("e_" + k).textContent = v; return msg(m, "err", r.body.error || `Save failed (${r.status})`); } render(r.body); const bits = ["Saved ✓"]; if (r.body.persisted) bits.push("Stored as Hugging Face Space secrets; the Space is restarting and this page will reconnect in about a minute."); else if ($("persist").checked) bits.push("Not persisted: " + (r.body.persistError || "unknown error") + " Active in memory until the next restart."); else bits.push("Active now (in memory only; lost on restart)."); msg(m, r.body.persistError ? "warn" : "ok", bits.join(" "));});async function runTest(path, el, btn) { btn.disabled = true; msg(el, "", "Testing…"); const r = await api(path, { method: "POST", body: {} }); btn.disabled = false; if (r.status === 401) return load(); msg(el, r.ok && r.body.ok ? "ok" : "err", r.body.message || r.body.error || `Test failed (${r.status})`);}$("testStripe").addEventListener("click", () => runTest("/api/admin/test/stripe", $("stripeMsg"), $("testStripe")));$("testSupa").addEventListener("click", () => runTest("/api/admin/test/supabase", $("supaMsg"), $("testSupa")));load();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import { createHash, randomBytes, timingSafeEqual } from "node:crypto";import express from "express";import { Runtime, SETTING_KEYS, SettingsError, type SettingKey } from "./runtime.js";import { readFileSync } from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";
const COOKIE = "pos_admin";const SESSION_MS = 12 * 3600_000;const MAX_FAILS = 5, FAIL_WINDOW_MS = 10 * 60_000;
function digest(s: string) { return createHash("sha256").update(s).digest(); }export function passcodeMatches(given: string, expected: string): boolean { return timingSafeEqual(digest(given), digest(expected)); }
function parseCookies(h: string | undefined): Record<string, string> { const out: Record<string, string> = {}; for (const part of (h ?? "").split(";")) { const i = part.indexOf("="); if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim()); } return out;}
export class AdminAuth { private sessions = new Map<string, number>(); private fails = new Map<string, { n: number; first: number }>(); constructor(private passcode: string | undefined) {} get configured() { return Boolean(this.passcode); }
private prune(now = Date.now()) { for (const [t, exp] of this.sessions) if (exp < now) this.sessions.delete(t); } isAuthed(req: express.Request): boolean { const t = parseCookies(req.headers.cookie)[COOKIE]; if (!t) return false; const exp = this.sessions.get(t); if (!exp) return false; if (exp < Date.now()) { this.sessions.delete(t); return false; } return true; } login(req: express.Request, res: express.Response, given: unknown): { ok: boolean; status: number; error?: string } { if (!this.passcode) return { ok: false, status: 503, error: "Admin passcode is not configured on the server (set ADMIN_PASSCODE)." }; const ip = req.ip ?? "unknown"; const now = Date.now(); const f = this.fails.get(ip); if (f && now - f.first < FAIL_WINDOW_MS && f.n >= MAX_FAILS) return { ok: false, status: 429, error: "Too many attempts. Try again in a few minutes." }; if (typeof given !== "string" || !given || !passcodeMatches(given, this.passcode)) { this.fails.set(ip, f && now - f.first < FAIL_WINDOW_MS ? { n: f.n + 1, first: f.first } : { n: 1, first: now }); return { ok: false, status: 401, error: "Incorrect passcode." }; } this.fails.delete(ip); this.prune(now); const token = randomBytes(32).toString("hex"); this.sessions.set(token, now + SESSION_MS); const secure = (req.get("x-forwarded-proto") ?? req.protocol).startsWith("https"); res.setHeader("Set-Cookie", `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_MS / 1000}${secure ? "; Secure" : ""}`); return { ok: true, status: 200 }; } logout(req: express.Request, res: express.Response) { const t = parseCookies(req.headers.cookie)[COOKIE]; if (t) this.sessions.delete(t); res.setHeader("Set-Cookie", `${COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`); } require = (req: express.Request, res: express.Response, next: express.NextFunction) => { if (!this.passcode) return void res.status(503).json({ error: "Admin passcode is not configured on the server (set ADMIN_PASSCODE)." }); if (!this.isAuthed(req)) return void res.status(401).json({ error: "Sign in required." }); next(); };}
/** State-changing requests must be JSON (forces a CORS preflight for cross-site callers). */const jsonOnly: express.RequestHandler = (req, res, next) => { if (["GET", "HEAD", "OPTIONS"].includes(req.method)) return next(); if (!req.is("application/json")) return void res.status(415).json({ error: "Content-Type must be application/json" }); next();};
export function adminRouter(rt: Runtime, auth: AdminAuth): express.Router { const r = express.Router(); r.use(jsonOnly); r.get("/session", (req, res) => res.json({ authenticated: auth.isAuthed(req), configured: auth.configured })); r.post("/login", (req, res) => { const out = auth.login(req, res, req.body?.passcode); res.status(out.status).json(out.ok ? { ok: true } : { error: out.error }); }); r.post("/logout", (req, res) => { auth.logout(req, res); res.json({ ok: true }); });
r.get("/settings", auth.require, (req, res) => { const origin = Runtime.origin(req); res.json({ ...rt.status(), webhookUrl: `${origin}/webhooks/stripe`, defaultUrls: rt.checkoutUrls(origin) }); }); r.put("/settings", auth.require, async (req, res) => { const body = (req.body ?? {}) as { values?: Record<string, unknown>; clear?: unknown; persist?: unknown }; const patch: Partial<Record<SettingKey, string>> = {}; for (const k of SETTING_KEYS) { const v = body.values?.[k]; if (typeof v === "string") patch[k] = v; } const clear = Array.isArray(body.clear) ? (body.clear.filter((k) => typeof k === "string") as SettingKey[]) : []; try { const out = await rt.update(patch, clear, body.persist === true); const origin = Runtime.origin(req); res.json({ ...out, ...rt.status(), webhookUrl: `${origin}/webhooks/stripe`, defaultUrls: rt.checkoutUrls(origin) }); } catch (e) { if (e instanceof SettingsError) return void res.status(422).json({ error: "Some settings were rejected; nothing was saved.", fields: e.fields }); res.status(500).json({ error: rt.redact((e as Error).message) }); } }); r.post("/test/stripe", auth.require, async (_req, res) => res.json(await rt.testStripe())); r.post("/test/supabase", auth.require, async (_req, res) => res.json(await rt.testSupabase())); r.get("/migrations.sql", auth.require, (_req, res) => { const dir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "supabase", "migrations"); const files = ["20261031000000_wallet_ledger.sql", "20261202000000_wallet_devices.sql"]; try { const sql = files.map((f) => `-- ===== ${f} =====\n${readFileSync(path.join(dir, f), "utf8")}`).join("\n\n"); res.type("text/plain").set("Content-Disposition", 'attachment; filename="projectos-wallet.sql"').send(sql); } catch { res.status(404).json({ error: "Migration files are not bundled in this build." }); } }); return r;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import express from "express";import { fileURLToPath } from "node:url";import path from "node:path";const publicDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "public");import type Stripe from "stripe";import type { Config } from "./config.js";import { Ledger, LedgerError } from "./ledger.js";import { parseInvoiceQr, payInvoice, InvoiceSchema } from "./routing.js";import { createFundingCheckout, createFundingPaymentIntent, handleWebhook } from "./stripe.js";export function buildApp(cfg: Config, ledger: Ledger, stripe: Stripe | null): express.Application {const app = express();const stripeReady = (needWebhook = false): Stripe | null =>stripe && (!needWebhook || cfg.STRIPE_WEBHOOK_SECRET) ? stripe : null;const notConfigured = (res: express.Response) => res.status(503).json({ error: "Stripe not configured" });const userId = cfg.WALLET_USER_ID; // single-user now; replace with auth-derived id for multi-userapp.post("/webhooks/stripe", express.raw({ type: "application/json" }), async (req, res) => {const s = stripeReady(true); if (!s) return notConfigured(res);try { const ev = await handleWebhook(s, ledger, req.body, req.header("stripe-signature"), cfg.STRIPE_WEBHOOK_SECRET!); res.json({ received: true, type: ev.type }); }catch (e) { res.status(400).json({ error: (e as Error).message }); }});app.use(express.json({ limit: "32kb" }));app.use(express.static(publicDir, { index: "index.html" }));app.get("/healthz", (_req, res) => res.json({ ok: true, mode: "test", stripe: Boolean(stripeReady(true)) }));app.get("/wallet/balance", async (req, res, next) => {try { const currency = String(req.query.currency ?? "usd"); res.json({ currency, balance: await ledger.walletBalance(userId, currency) }); } catch (e) { next(e); }});app.get("/wallet/transactions", async (_req, res, next) => { try { res.json(await ledger.list(userId)); } catch (e) { next(e); } });app.post("/funding/checkout", async (req, res, next) => {const st = stripeReady(); if (!st) return notConfigured(res);try { const s = await createFundingCheckout(st, userId, Number(req.body.amount), String(req.body.currency ?? "usd"), cfg.STRIPE_SUCCESS_URL, cfg.STRIPE_CANCEL_URL); res.json({ id: s.id, url: s.url }); } catch (e) { next(e); }});app.post("/funding/payment-intent", async (req, res, next) => {const st = stripeReady(); if (!st) return notConfigured(res);try { const pi = await createFundingPaymentIntent(st, userId, Number(req.body.amount), String(req.body.currency ?? "usd")); res.json({ id: pi.id, client_secret: pi.client_secret }); } catch (e) { next(e); }});app.post("/invoices/pay", async (req, res, next) => {try {const invoice = typeof req.body.qr === "string" ? parseInvoiceQr(req.body.qr) : InvoiceSchema.parse(req.body.invoice);res.json(await payInvoice(ledger, userId, invoice));} catch (e) { next(e); }});app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {res.status(err instanceof LedgerError || err.name === "ZodError" ? 422 : 500).json({ error: err.message });});return app;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import express from "express";import { fileURLToPath } from "node:url";import path from "node:path";import type Stripe from "stripe";import type { Config } from "./config.js";import { Ledger, LedgerError } from "./ledger.js";import { parseInvoiceQr, payInvoice, InvoiceSchema } from "./routing.js";import { createFundingCheckout, createFundingPaymentIntent, handleWebhook } from "./stripe.js";import { Runtime } from "./runtime.js";import { AdminAuth, adminRouter } from "./admin.js";import { DeviceError, addDevice } from "./devices.js";const publicDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "public");export interface AppOptions { runtime?: Runtime; adminPasscode?: string }export function buildApp(cfg: Config, ledger: Ledger | null, stripe: Stripe | null, opts: AppOptions = {}): express.Application {const rt = opts.runtime ?? new Runtime(cfg, { stripe, ...(ledger ? { ledger } : {}) });const L = rt.ledger;const auth = new AdminAuth(opts.adminPasscode);const app = express();app.set("trust proxy", true);app.disable("x-powered-by");const notConfigured = (res: express.Response) => res.status(503).json({ error: "Stripe not configured" });const userId = cfg.WALLET_USER_ID; // single-user now; replace with auth-derived id for multi-userapp.use((_req, res, next) => {res.setHeader("X-Content-Type-Options", "nosniff");res.setHeader("Referrer-Policy", "same-origin");next();});app.post("/webhooks/stripe", express.raw({ type: "application/json" }), async (req, res) => {const s = rt.stripe; const secret = rt.webhookSecret;if (!s || !secret) return notConfigured(res);try { const ev = await handleWebhook(s, L, req.body, req.header("stripe-signature"), secret); res.json({ received: true, type: ev.type }); }catch (e) { res.status(400).json({ error: rt.redact((e as Error).message) }); }});app.use(express.json({ limit: "32kb" }));app.use(express.static(publicDir, { index: "index.html", extensions: ["html"] }));app.get("/favicon.ico", (_req, res) => res.redirect(301, "/favicon.svg"));app.get("/healthz", (_req, res) => res.json({ ok: true, mode: "test", stripe: Boolean(rt.stripe && rt.webhookSecret), store: rt.storeMode, admin: auth.configured }));app.use("/api/admin", adminRouter(rt, auth));// --- devices / phones (sign-in required: they hold phone numbers) ---app.get("/api/devices", auth.require, async (_req, res, next) => { try { res.json(await rt.devices.list(userId)); } catch (e) { next(e); } });app.post("/api/devices", auth.require, async (req, res, next) => { try { res.status(201).json(await addDevice(rt.devices, userId, req.body)); } catch (e) { next(e); } });app.delete("/api/devices/:id", auth.require, async (req, res, next) => {try { const ok = await rt.devices.remove(userId, req.params.id); res.status(ok ? 200 : 404).json(ok ? { ok: true } : { error: "device not found" }); } catch (e) { next(e); }});// --- wallet ---app.get("/wallet/balance", async (req, res, next) => {try { const currency = String(req.query.currency ?? "usd"); res.json({ currency, balance: await L.walletBalance(userId, currency) }); } catch (e) { next(e); }});app.get("/wallet/transactions", async (_req, res, next) => { try { res.json(await L.list(userId)); } catch (e) { next(e); } });app.post("/wallet/test-credit", auth.require, async (req, res, next) => {try { const amount = Math.round(Number(req.body?.amount)); const tx = await L.recordTestCredit(userId, amount); res.json({ transaction: tx, balance: await L.walletBalance(userId) }); } catch (e) { next(e); }});app.post("/funding/checkout", async (req, res, next) => {const st = rt.stripe; if (!st) return notConfigured(res);try {const urls = rt.checkoutUrls(Runtime.origin(req));const s = await createFundingCheckout(st, userId, Number(req.body.amount), String(req.body.currency ?? "usd"), urls.success, urls.cancel);res.json({ id: s.id, url: s.url });} catch (e) { next(e); }});app.post("/funding/payment-intent", async (req, res, next) => {const st = rt.stripe; if (!st) return notConfigured(res);try { const pi = await createFundingPaymentIntent(st, userId, Number(req.body.amount), String(req.body.currency ?? "usd")); res.json({ id: pi.id, client_secret: pi.client_secret }); } catch (e) { next(e); }});app.post("/invoices/pay", async (req, res, next) => {try {const invoice = typeof req.body.qr === "string" ? parseInvoiceQr(req.body.qr) : InvoiceSchema.parse(req.body.invoice);res.json(await payInvoice(L, userId, invoice));} catch (e) { next(e); }});// Unknown API-ish paths get JSON; anything else gets the friendly 404 page.app.use((req, res) => {if (req.method === "GET" && !/^\/(api|wallet|funding|invoices|webhooks)\b/.test(req.path)) return void res.status(404).sendFile(path.join(publicDir, "404.html"));res.status(404).json({ error: "not found" });});app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {const status = err instanceof LedgerError || err instanceof DeviceError || err.name === "ZodError" ? 422 : (err as { type?: string }).type === "entity.parse.failed" ? 400 : 500;res.status(status).json({ error: rt.redact(err.message) });});return app;}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import { randomUUID } from "node:crypto";import { createClient, type SupabaseClient } from "@supabase/supabase-js";import { z } from "zod";
export const MAX_DEVICES = 20;
export interface Device { id: string; user_id: string; label: string; kind: "phone" | "tablet" | "watch" | "other"; platform: "ios" | "android" | "other"; phone?: string; // E.164 created_at: string;}
export interface DeviceStore { list(userId: string): Promise<Device[]>; add(device: Device): Promise<void>; remove(userId: string, id: string): Promise<boolean>;}
export class DeviceError extends Error {}
/** Normalises user-entered numbers to E.164. 10-digit numbers are treated as US/Canada (+1). */export function normalizePhone(raw: string): string { const s = raw.trim(); if (!s) throw new DeviceError("phone number is empty"); if (/[^\d+\-().\s]/.test(s)) throw new DeviceError("phone number may only contain digits, spaces, + - ( )"); const digits = s.replace(/\D/g, ""); let e164: string; if (s.startsWith("+")) e164 = `+${digits}`; else if (digits.length === 10) e164 = `+1${digits}`; else if (digits.length === 11 && digits.startsWith("1")) e164 = `+${digits}`; else throw new DeviceError("use international format, e.g. +14155550123 (or a 10-digit US number)"); if (!/^\+[1-9]\d{6,14}$/.test(e164)) throw new DeviceError("phone number must be 7-15 digits in international format"); return e164;}
export const DeviceInput = z.object({ label: z.string().trim().min(1, "name is required").max(60), kind: z.enum(["phone", "tablet", "watch", "other"]).default("phone"), platform: z.enum(["ios", "android", "other"]).default("other"), phone: z.string().max(40).optional(),});
export async function addDevice(store: DeviceStore, userId: string, input: unknown): Promise<Device> { const parsed = DeviceInput.safeParse(input); if (!parsed.success) throw new DeviceError(parsed.error.issues.map((i) => i.message).join("; ")); const existing = await store.list(userId); if (existing.length >= MAX_DEVICES) throw new DeviceError(`device limit reached (${MAX_DEVICES}); remove one first`); const phone = parsed.data.phone?.trim() ? normalizePhone(parsed.data.phone) : undefined; if (phone && existing.some((d) => d.phone === phone)) throw new DeviceError("that phone number is already added"); const d: Device = { id: randomUUID(), user_id: userId, label: parsed.data.label, kind: parsed.data.kind, platform: parsed.data.platform, phone, created_at: new Date().toISOString() }; await store.add(d); return d;}
export class MemoryDeviceStore implements DeviceStore { items: Device[] = []; async list(userId: string) { return this.items.filter((d) => d.user_id === userId).sort((a, b) => b.created_at.localeCompare(a.created_at)); } async add(d: Device) { this.items.push(structuredClone(d)); } async remove(userId: string, id: string) { const n = this.items.length; this.items = this.items.filter((d) => !(d.user_id === userId && d.id === id)); return this.items.length < n; }}
export class SupabaseDeviceStore implements DeviceStore { private db: SupabaseClient; constructor(url: string, serviceKey: string) { this.db = createClient(url, serviceKey, { auth: { persistSession: false } }); } async list(userId: string): Promise<Device[]> { const { data, error } = await this.db.from("wallet_devices").select("*").eq("user_id", userId).order("created_at", { ascending: false }); if (error) throw new Error(error.message); return (data ?? []).map((r) => ({ ...r, phone: r.phone ?? undefined }) as Device); } async add(d: Device) { const { error } = await this.db.from("wallet_devices").insert({ ...d, phone: d.phone ?? null }); if (error) throw new Error(error.message); } async remove(userId: string, id: string) { const { data, error } = await this.db.from("wallet_devices").delete().eq("user_id", userId).eq("id", id).select("id"); if (error) throw new Error(error.message); return (data ?? []).length > 0; }}
/** Lets the settings page hot-swap memory <-> Supabase without restarting. */export class SwitchableDeviceStore implements DeviceStore { constructor(public target: DeviceStore) {} list(u: string) { return this.target.list(u); } add(d: Device) { return this.target.add(d); } remove(u: string, id: string) { return this.target.remove(u, id); }}123456789101112import { loadConfig } from "./config.js";import { Ledger } from "./ledger.js";import { MemoryStore } from "./memoryStore.js";import { SupabaseStore } from "./supabaseStore.js";import { makeStripe } from "./stripe.js";import { buildApp } from "./app.js";const cfg = loadConfig(); // throws on sk_live_ / Apple Pay credsconst store = cfg.WALLET_STORE === "memory" ? new MemoryStore() : new SupabaseStore(cfg.SUPABASE_URL!, cfg.SUPABASE_SERVICE_ROLE_KEY!);const app = buildApp(cfg, new Ledger(store), cfg.STRIPE_SECRET_KEY ? makeStripe(cfg.STRIPE_SECRET_KEY) : null);if (!cfg.STRIPE_SECRET_KEY || !cfg.STRIPE_WEBHOOK_SECRET) console.warn("Stripe not configured: funding/webhook routes return 503");app.listen(cfg.PORT, "0.0.0.0", () => console.log(`wallet (TEST mode) listening on :${cfg.PORT}`));12345678910111213141516import { loadConfig } from "./config.js";import { buildApp } from "./app.js";import { HfSecretsPersister, Runtime } from "./runtime.js";// If WALLET_STORE=supabase is set but the keys are missing/removed, run in memory mode instead of crash-looping.if (process.env.WALLET_STORE === "supabase" && (!process.env.SUPABASE_URL || !process.env.SUPABASE_SERVICE_ROLE_KEY)) {console.warn("WALLET_STORE=supabase but Supabase URL/key missing: falling back to memory store");process.env.WALLET_STORE = "memory";}const cfg = loadConfig(); // throws on sk_live_ / Apple Pay credsconst persister = new HfSecretsPersister(process.env.SPACE_ID, process.env.HF_SPACE_TOKEN);const runtime = new Runtime(cfg, { persister });const app = buildApp(cfg, null, null, { runtime, adminPasscode: process.env.ADMIN_PASSCODE });if (!cfg.STRIPE_SECRET_KEY || !cfg.STRIPE_WEBHOOK_SECRET) console.warn("Stripe not configured: funding/webhook routes return 503 until keys are added on /settings");if (!process.env.ADMIN_PASSCODE) console.warn("ADMIN_PASSCODE not set: /settings and /devices sign-in are disabled");app.listen(cfg.PORT, "0.0.0.0", () => console.log(`wallet (TEST mode, store=${runtime.storeMode}) listening on :${cfg.PORT}`));
47 unmodified lines484950515247 unmodified lines});}list(userId: string, limit = 50) { return this.store.listTransactions(userId, limit); }}47 unmodified lines4849505152535455565758596061626347 unmodified lines});}/** TEST-mode only: simulated deposit so the wallet is usable before Stripe keys exist. */async recordTestCredit(userId: string, amount: number, currency = "usd") {if (!Number.isSafeInteger(amount) || amount < 1 || amount > 100_000) throw new LedgerError("test credit must be 1..100000 minor units");const clearing = await this.account(userId, "stripe_clearing", currency);const wallet = await this.account(userId, "user_wallet", currency);return this.post({user_id: userId, kind: "funding", idempotency_key: `test-credit:${randomUUID()}`, memo: "Test credit (simulated, no Stripe)",postings: [{ account_id: clearing.id, amount }, { account_id: wallet.id, amount: -amount }],});}list(userId: string, limit = 50) { return this.store.listTransactions(userId, limit); }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239import 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) { this.values.set(k, v); } } 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 })), ]); }}123456789101112131415-- ProjectOS wallet: registered phones / devices (added from the Devices page).create table if not exists wallet_devices ( id uuid primary key, user_id uuid not null, label text not null check (char_length(label) between 1 and 60), kind text not null default 'phone' check (kind in ('phone','tablet','watch','other')), platform text not null default 'other' check (platform in ('ios','android','other')), phone text check (phone is null or phone ~ '^\+[1-9][0-9]{6,14}$'), created_at timestamptz not null default now(), unique (user_id, phone));alter table wallet_devices enable row level security;-- Service role bypasses RLS. Future multi-user: add policies on auth.uid() = user_id.drop policy if exists wallet_devices_owner on wallet_devices;create policy wallet_devices_owner on wallet_devices for select using (auth.uid() = user_id);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249import { describe, it, expect, afterEach, vi } from "vitest";import http from "node:http";import fs from "node:fs";import path from "node:path";import type { AddressInfo } from "node:net";import { buildApp } from "../src/app.js";import { loadConfig } from "../src/config.js";import { Runtime, HfSecretsPersister, validateSetting, mask, type Persister } from "../src/runtime.js";import { normalizePhone } from "../src/devices.js";
const base = { WALLET_STORE: "memory", WALLET_USER_ID: "u1" };const PASS = "correct-horse-battery";const SK = "sk_test_51ABCDEFGHIJKLMNOP1234";const WH = "whsec_abcdefghijklmnop1234";const servers: http.Server[] = [];afterEach(() => { while (servers.length) servers.pop()!.close(); vi.restoreAllMocks(); });
function boot(opts: { passcode?: string | null; persister?: Persister; env?: Record<string, string> } = {}) { const cfg = loadConfig({ ...base, ...(opts.env ?? {}) }); const rt = new Runtime(cfg, { persister: opts.persister }); const app = buildApp(cfg, null, null, { runtime: rt, adminPasscode: opts.passcode === null ? undefined : opts.passcode ?? PASS }); const srv = app.listen(0); servers.push(srv); const url = `http://127.0.0.1:${(srv.address() as AddressInfo).port}`; let cookie = ""; const req = async (method: string, p: string, body?: unknown, headers: Record<string, string> = {}) => { const r = await fetch(url + p, { method, redirect: "manual", headers: { ...(body !== undefined ? { "content-type": "application/json" } : {}), ...(cookie ? { cookie } : {}), ...headers }, body: body !== undefined ? JSON.stringify(body) : undefined }); const sc = r.headers.get("set-cookie"); if (sc && !sc.includes("Max-Age=0")) cookie = sc.split(";")[0]; const text = await r.text(); let json: any = null; try { json = JSON.parse(text); } catch {} return { status: r.status, json, text, headers: r.headers }; }; const login = () => req("POST", "/api/admin/login", { passcode: PASS }); return { rt, url, req, login };}
describe("admin sign-in", () => { it("503s when ADMIN_PASSCODE is not configured", async () => { const { req } = boot({ passcode: null }); expect((await req("POST", "/api/admin/login", { passcode: "x" })).status).toBe(503); expect((await req("GET", "/api/admin/settings")).status).toBe(503); expect((await req("GET", "/api/admin/session")).json).toEqual({ authenticated: false, configured: false }); }); it("rejects wrong passcode, protects routes, accepts correct one with HttpOnly cookie", async () => { const { req } = boot(); expect((await req("GET", "/api/admin/settings")).status).toBe(401); expect((await req("GET", "/api/devices")).status).toBe(401); expect((await req("POST", "/wallet/test-credit", { amount: 100 })).status).toBe(401); expect((await req("POST", "/api/admin/login", { passcode: "nope" })).status).toBe(401); const ok = await req("POST", "/api/admin/login", { passcode: PASS }); expect(ok.status).toBe(200); expect(ok.headers.get("set-cookie")).toMatch(/HttpOnly/); expect(ok.headers.get("set-cookie")).not.toContain(PASS); expect((await req("GET", "/api/admin/settings")).status).toBe(200); await req("POST", "/api/admin/logout", {}); expect((await req("GET", "/api/admin/settings")).status).toBe(401); }); it("rate-limits repeated failures (even for the right passcode afterwards)", async () => { const { req } = boot(); for (let i = 0; i < 5; i++) expect((await req("POST", "/api/admin/login", { passcode: "bad" + i })).status).toBe(401); expect((await req("POST", "/api/admin/login", { passcode: "bad" })).status).toBe(429); expect((await req("POST", "/api/admin/login", { passcode: PASS })).status).toBe(429); }); it("requires JSON content type for state changes (CSRF guard)", async () => { const { url } = boot(); const r = await fetch(url + "/api/admin/login", { method: "POST", headers: { "content-type": "text/plain" }, body: JSON.stringify({ passcode: PASS }) }); expect(r.status).toBe(415); });});
describe("settings", () => { it("validates, masks, never echoes secrets, and activates Stripe", async () => { const { req, login, rt } = boot(); await login(); const bad = await req("PUT", "/api/admin/settings", { values: { STRIPE_SECRET_KEY: "sk_live_abcdefghijklmnop" } }); expect(bad.status).toBe(422); expect(bad.json.fields.STRIPE_SECRET_KEY).toMatch(/Live/); expect(rt.get("STRIPE_SECRET_KEY")).toBeUndefined(); const put = await req("PUT", "/api/admin/settings", { values: { STRIPE_SECRET_KEY: SK, STRIPE_WEBHOOK_SECRET: WH }, persist: false }); expect(put.status).toBe(200); const get = await req("GET", "/api/admin/settings"); for (const body of [put.text, get.text]) { expect(body).not.toContain(SK); expect(body).not.toContain(WH); expect(body).not.toContain("51ABCDEFGHIJKLMNOP"); } const s = get.json.settings.find((x: any) => x.key === "STRIPE_SECRET_KEY"); expect(s).toMatchObject({ configured: true, secret: true, masked: "sk_test_••••••••1234" }); expect(s.value).toBeUndefined(); expect(get.json.stripeReady).toBe(true); expect((await req("GET", "/healthz")).json.stripe).toBe(true); // blank = unchanged await req("PUT", "/api/admin/settings", { values: { STRIPE_SECRET_KEY: "" } }); expect(rt.get("STRIPE_SECRET_KEY")).toBe(SK); // clear await req("PUT", "/api/admin/settings", { clear: ["STRIPE_SECRET_KEY"] }); expect((await req("GET", "/healthz")).json.stripe).toBe(false); }); it("requires Supabase URL+key before switching storage, then switches and tests", async () => { const { req, login } = boot(); await login(); const r = await req("PUT", "/api/admin/settings", { values: { WALLET_STORE: "supabase" } }); expect(r.status).toBe(422); expect(Object.keys(r.json.fields)).toEqual(["SUPABASE_URL", "SUPABASE_SERVICE_ROLE_KEY"]); expect((await req("PUT", "/api/admin/settings", { values: { SUPABASE_URL: "http://evil.example" } })).status).toBe(422); }); it("persists via the persister and reports failures without leaking values", async () => { const calls: unknown[] = []; const good: Persister = { available: true, describe: "fake", persist: async (set, clear) => { calls.push({ set, clear }); } }; const a = boot({ persister: good }); await a.login(); const r = await a.req("PUT", "/api/admin/settings", { values: { STRIPE_SECRET_KEY: SK }, persist: true }); expect(r.json.persisted).toBe(true); expect(calls).toEqual([{ set: { STRIPE_SECRET_KEY: SK }, clear: [] }]); expect(r.json.settings.find((s: any) => s.key === "STRIPE_SECRET_KEY").persisted).toBe(true); const bad: Persister = { available: true, describe: "fake", persist: async () => { throw new Error(`boom ${SK}`); } }; const b = boot({ persister: bad }); await b.login(); const r2 = await b.req("PUT", "/api/admin/settings", { values: { STRIPE_SECRET_KEY: SK }, persist: true }); expect(r2.status).toBe(200); expect(r2.json.persisted).toBe(false); expect(r2.text).not.toContain(SK); expect(r2.json.persistError).toContain("[redacted]"); const c = boot(); await c.login(); const r3 = await c.req("PUT", "/api/admin/settings", { values: { STRIPE_SECRET_KEY: SK }, persist: true }); expect(r3.json.persisted).toBe(false); expect(r3.json.persistError).toMatch(/memory only/); }); it("never logs secrets", async () => { const spies = (["log", "warn", "error", "info"] as const).map((m) => vi.spyOn(console, m).mockImplementation(() => {})); const { req, login } = boot(); await login(); await req("PUT", "/api/admin/settings", { values: { STRIPE_SECRET_KEY: SK, STRIPE_WEBHOOK_SECRET: WH } }); await req("POST", "/api/admin/test/stripe", {}); const logged = JSON.stringify(spies.flatMap((s) => s.mock.calls)); expect(logged).not.toContain(SK); expect(logged).not.toContain(WH); expect(logged).not.toContain(PASS); }); it("tests the Stripe connection (live-mode keys and errors are reported safely)", async () => { const { req, login, rt } = boot(); await login(); expect((await req("POST", "/api/admin/test/stripe", {})).json.ok).toBe(false); rt.stripe = { balance: { retrieve: async () => ({ livemode: false }) } } as never; expect((await req("POST", "/api/admin/test/stripe", {})).json.message).toMatch(/test mode/); rt.stripe = { balance: { retrieve: async () => { throw new Error(`Invalid API Key provided: ${SK}`); } } } as never; const r = await req("POST", "/api/admin/test/stripe", {}); expect(r.json.ok).toBe(false); expect(r.text).not.toContain(SK); }); it("tests the Supabase connection against a stub REST endpoint", async () => { let seenKey = ""; const stub = http.createServer((q, s) => { seenKey = String(q.headers.apikey); if (seenKey === "good") { s.setHeader("content-type", "application/json"); return void s.end("[]"); } if (seenKey === "nowallet") { s.statusCode = 404; return void s.end('{"code":"PGRST205"}'); } s.statusCode = 401; s.end("{}"); }).listen(0); servers.push(stub); const u = `http://127.0.0.1:${(stub.address() as AddressInfo).port}`; for (const [key, ok, re] of [["good", true, /wallet tables found/], ["nowallet", true, /missing/], ["bad", false, /rejected/]] as const) { const { req, login } = boot({ env: { SUPABASE_URL: u, SUPABASE_SERVICE_ROLE_KEY: key } }); await login(); const r = await req("POST", "/api/admin/test/supabase", {}); expect(r.json.ok).toBe(ok); expect(r.json.message).toMatch(re); } const { req, login } = boot(); await login(); expect((await req("POST", "/api/admin/test/supabase", {})).json.ok).toBe(false); }); it("serves the SQL migrations to signed-in admins only", async () => { const { req, login } = boot(); expect((await req("GET", "/api/admin/migrations.sql")).status).toBe(401); await login(); const r = await req("GET", "/api/admin/migrations.sql"); expect(r.status).toBe(200); expect(r.text).toContain("wallet_devices"); expect(r.text).toContain("wallet_post_transaction"); }); it("validators + mask", () => { expect(validateSetting("STRIPE_SECRET_KEY", "rk_test_abcdefghij")).toBeNull(); expect(validateSetting("STRIPE_SECRET_KEY", "pk_test_abcdefghij")).toMatch(/TEST key/); expect(validateSetting("STRIPE_WEBHOOK_SECRET", "nope")).toMatch(/whsec_/); expect(validateSetting("SUPABASE_URL", "https://abcd1234.supabase.co")).toBeNull(); expect(validateSetting("SUPABASE_SERVICE_ROLE_KEY", "eyJhbGciOi.eyJyb2xl.sig_nature")).toBeNull(); expect(mask("sb_secret_abcdef123456")).toBe("sb_secret_••••••••3456"); }); it("HfSecretsPersister calls the Hugging Face secrets API with a bearer token", async () => { const seen: { method?: string; url?: string; auth?: string; body?: string }[] = []; const hf = http.createServer((q, s) => { let b = ""; q.on("data", (c) => (b += c)); q.on("end", () => { seen.push({ method: q.method, url: q.url, auth: q.headers.authorization, body: b }); s.end("{}"); }); }).listen(0); servers.push(hf); const p = new HfSecretsPersister("me/space", "hf_tok", `http://127.0.0.1:${(hf.address() as AddressInfo).port}`); await p.persist({ STRIPE_SECRET_KEY: SK }, ["SUPABASE_URL"]); expect(seen.map((s) => `${s.method} ${s.url}`).sort()).toEqual(["DELETE /api/spaces/me/space/secrets", "POST /api/spaces/me/space/secrets"]); expect(seen.every((s) => s.auth === "Bearer hf_tok")).toBe(true); expect(new HfSecretsPersister(undefined, "x").available).toBe(false); });});
describe("devices (add phone)", () => { it("adds, lists, dedupes, validates, and removes", async () => { const { req, login } = boot(); await login(); const add = await req("POST", "/api/devices", { label: "Pixel 9", kind: "phone", platform: "android", phone: "(415) 555-0123" }); expect(add.status).toBe(201); expect(add.json.phone).toBe("+14155550123"); expect((await req("POST", "/api/devices", { label: "Dup", phone: "+1 415 555 0123" })).status).toBe(422); expect((await req("POST", "/api/devices", { label: "", phone: "" })).status).toBe(422); expect((await req("POST", "/api/devices", { label: "x", phone: "abc" })).status).toBe(422); expect((await req("POST", "/api/devices", { label: "No number", kind: "tablet" })).status).toBe(201); const list = await req("GET", "/api/devices"); expect(list.json).toHaveLength(2); expect((await req("DELETE", "/api/devices/" + add.json.id)).status).toBe(200); expect((await req("DELETE", "/api/devices/" + add.json.id)).status).toBe(404); expect((await req("GET", "/api/devices")).json).toHaveLength(1); }); it("caps the number of devices", async () => { const { req, login } = boot(); await login(); for (let i = 0; i < 20; i++) expect((await req("POST", "/api/devices", { label: "d" + i })).status).toBe(201); expect((await req("POST", "/api/devices", { label: "one too many" })).status).toBe(422); }); it("normalizes phone numbers", () => { expect(normalizePhone("+44 20 7946 0958")).toBe("+442079460958"); expect(normalizePhone("1-415-555-0123")).toBe("+14155550123"); expect(() => normalizePhone("12345")).toThrow(); });});
describe("wallet actions in test mode without Stripe", () => { it("simulated credit then invoice payment works; checkout 503s", async () => { const { req, login } = boot(); await login(); expect((await req("POST", "/funding/checkout", { amount: 500 })).status).toBe(503); const c = await req("POST", "/wallet/test-credit", { amount: 2500 }); expect(c.status).toBe(200); expect(c.json.balance).toBe(2500); const pay = await req("POST", "/invoices/pay", { qr: JSON.stringify({ v: 1, invoice_id: "A1", merchant_id: "m", amount: 500, currency: "usd" }) }); expect(pay.json.balance).toBe(2000); expect((await req("POST", "/wallet/test-credit", { amount: -5 })).status).toBe(422); expect((await req("GET", "/wallet/transactions")).json).toHaveLength(2); }); it("derives checkout URLs from the public origin (not localhost) when none configured", () => { const rt = new Runtime(loadConfig(base)); expect(rt.checkoutUrls("https://x.hf.space")).toEqual({ success: "https://x.hf.space/funding/success?session_id={CHECKOUT_SESSION_ID}", cancel: "https://x.hf.space/funding/cancel" }); const custom = new Runtime(loadConfig({ ...base, STRIPE_SUCCESS_URL: "https://ex.com/ok", STRIPE_CANCEL_URL: "https://ex.com/no" })); expect(custom.checkoutUrls("https://x.hf.space")).toEqual({ success: "https://ex.com/ok", cancel: "https://ex.com/no" }); expect(Runtime.origin({ protocol: "http", get: (h) => ({ "x-forwarded-proto": "https", host: "a.hf.space" } as Record<string, string>)[h] })).toBe("https://a.hf.space"); });});
describe("pages and links", () => { const publicDir = path.resolve(import.meta.dirname, "..", "public"); it("every internal href/src in every page resolves (no dead links)", async () => { const { url, req, login } = boot(); await login(); // signed in so protected downloads resolve too const pages = ["/", "/devices", "/settings", "/funding/success", "/funding/cancel", "/404.html"]; const targets = new Set<string>(); for (const p of pages) { const r = await fetch(url + p); expect(r.status, p).toBe(200); const html = await r.text(); for (const m of html.matchAll(/(?:href|src)="([^"#]+)"/g)) if (m[1].startsWith("/")) targets.add(m[1]); } // links injected by common.js for (const p of ["/", "/devices", "/settings", "/favicon.ico", "/links.json"]) targets.add(p); for (const t of targets) { const r = await req("GET", t); expect(r.status, t).toBe(t === "/favicon.ico" ? 301 : 200); } expect(targets.has("/common.js") && targets.has("/devices.js") && targets.has("/settings.js") && targets.has("/app.js")).toBe(true); // every static file referenced by script tags exists on disk for (const f of fs.readdirSync(publicDir)) { const st = fs.statSync(path.join(publicDir, f)); if (st.isFile()) expect(st.size, f).toBeGreaterThan(0); } }); it("unknown pages get the friendly 404; unknown API paths get JSON 404", async () => { const { url } = boot(); const a = await fetch(url + "/nope"); expect(a.status).toBe(404); expect(await a.text()).toContain("Page not"); const b = await fetch(url + "/api/nope"); expect(b.status).toBe(404); expect((await b.json()).error).toBe("not found"); }); it("links.json: external links are https and private ones are flagged", async () => { const { url } = boot(); const { apps } = await (await fetch(url + "/links.json")).json(); for (const a of apps) for (const l of [a, a.secondary].filter(Boolean)) if (l.url) expect(l.url).toMatch(/^https:\/\//); expect(apps.filter((a: any) => a.private).map((a: any) => a.name)).toEqual(["KlawChat", "Klaw Command", "OpenKlaw"]); });});24 unmodified lines2526272829303124 unmodified linesconst root = await fetch(url + "/");expect(root.status).toBe(200);const html = await root.text();expect(html).toContain("TEST MODE");expect(html).toContain('id="payForm"');const links = await (await fetch(url + "/links.json")).json();expect(links.apps.map((a: { name: string }) => a.name)).toEqual(["KlawChat","Klaw Command","OpenKlaw","ProcureNet","KlawPay","ProcureMe","ChargeMe"]);24 unmodified lines2526272829303124 unmodified linesconst root = await fetch(url + "/");expect(root.status).toBe(200);const html = await root.text();expect(await (await fetch(url + "/common.js")).text()).toContain("TEST MODE");expect(html).toContain('id="payForm"');const links = await (await fetch(url + "/links.json")).json();expect(links.apps.map((a: { name: string }) => a.name)).toEqual(["KlawChat","Klaw Command","OpenKlaw","ProcureNet","KlawPay","ProcureMe","ChargeMe"]);
Dockerfile+1
services/wallet/.env.exampleAdded+11
services/wallet/README.md+21
services/wallet/public/404.htmlAdded+11
services/wallet/public/app.css+12
services/wallet/public/app.js+17-19
services/wallet/public/common.jsAdded+42
services/wallet/public/devices.htmlAdded+22
services/wallet/public/devices.jsAdded+29
services/wallet/public/favicon.svgAdded
services/wallet/public/funding/cancel.htmlAdded+11
services/wallet/public/funding/success.htmlAdded+11
services/wallet/public/index.html+10-5
services/wallet/public/links.json+51-7
services/wallet/public/settings.htmlAdded+24
services/wallet/public/settings.jsAdded+66
services/wallet/src/admin.tsAdded+104
services/wallet/src/app.ts+58-17
services/wallet/src/devices.tsAdded+94
services/wallet/src/index.ts+12-8
services/wallet/src/ledger.ts+11
services/wallet/src/runtime.tsAdded+239
services/wallet/supabase/migrations/20261202000000_wallet_devices.sqlAdded+15
services/wallet/test/admin.test.tsAdded+249
services/wallet/test/app.test.ts+1-1