File size: 17,323 Bytes
1444c0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5169a81
 
 
 
 
1444c0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import { 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("reports built-in localhost URL defaults as not configured", async () => {
    const { req, login } = boot(); await login();
    const st = (await req("GET", "/api/admin/settings")).json.settings;
    for (const k of ["STRIPE_SUCCESS_URL", "STRIPE_CANCEL_URL"]) expect(st.find((x: any) => x.key === k)).toMatchObject({ configured: false, value: "" });
  });
  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"]);
  });
});