File size: 6,189 Bytes
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
import { 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;
}