diff --git a/apps/cloud/README.md b/apps/cloud/README.md index eec3361..9a72b5c 100644 --- a/apps/cloud/README.md +++ b/apps/cloud/README.md @@ -46,6 +46,7 @@ Lookups on the public path are cached in each isolate for 10 seconds. A deleted | `src/cookie.ts`, `src/headers.ts`, `src/crypto.ts` | Access and notice cookies, forwarded headers, hashing | | `src/pages.ts`, `src/passwords.ts` | The HTML pages (warning, password, errors) and generated passwords | | `scripts/admin.ts` | `pnpm cloud:admin`: bans, takedowns, overrides, billing refreshes, and the duplicate subscriptions to refund | +| `scripts/dashboard.ts`, `scripts/dashboard/` | `pnpm cloud:dashboard`: the read-only overview of every account (see "Dashboard") | ## Run locally @@ -218,3 +219,40 @@ pnpm cloud:admin override teo-goulois 5 10 team --expires 2027-06-30 ``` A duplicate Pro subscription is revoked automatically and logged as an error, but never refunded by the Worker. `pnpm cloud:admin duplicates` lists each one with its orders, read live from Polar: refund the orders it marks in Polar's dashboard (Sales → Orders, reason Duplicate), and run it again later for payments that were still pending. It writes nothing. + +## Dashboard + +`pnpm cloud:dashboard` serves a read-only overview of every account, on this machine: + +- headline numbers: users, new ones in the last 7 and 30 days, active and serving machines, live and serving URLs, accounts per plan status, add-on units that count, bans and takedowns; +- new sign-ups per week; +- what needs attention: banned and `past_due` accounts, overrides ending within 30 days, and accounts at 80% or more of their URL, serving-machine or signed-in-machine limit; +- every account in a table to sort and search, with its plan or override, its machines and live URLs against its limits, and its last activity: the latest sign-in, tunnel start, remote key, URL created or deleted, or billing event, since D1 records no visits; +- each account on its own page, as `cloud:admin show` prints it: ban, override, billing snapshot, entitlement, machines, and each URL with its machine and its serving state. + +Plans, overrides and add-ons go through `src/entitlement.ts`, as in the Worker. It reads the production D1 as `CLOUDFLARE_DEPLOY_TOKEN` from Infisical, in one `wrangler d1 execute` call, when a page loads and the last read is more than 30 seconds old. The refresh button reads again, at most every 5 seconds. A read that takes more than a minute is stopped and the page says it failed, and stopping the dashboard stops a read in progress: wrangler never holds the server. `--local` reads the D1 of `pnpm cloud:dev` instead. + +It only reads. Its database layer ([`scripts/dashboard/db.ts`](scripts/dashboard/db.ts)) refuses before sending anything a statement that is not one plain `SELECT`, no route takes input that reaches SQL, and anything but `GET` and `HEAD` gets `405`. None of its reads selects a token, a password hash, a tunnel or DNS id, a remote key or an ingress port, so none can be served. It has no ban, override, takedown or refresh action: those stay in `pnpm cloud:admin`. + +It needs the `PORT` Localify gives it, so start it through Localify. Once, add `apps/cloud` to the repository's Localify project as a service with a domain of its own: + +```bash +localify project add-service --path apps/cloud --domain cloud-dashboard..localify +``` + +Then, from `apps/cloud`: + +```bash +localify dev cloud -- pnpm cloud:dashboard # production D1 +localify dev cloud -- pnpm cloud:dashboard --local # the D1 of pnpm cloud:dev +``` + +To start it again, run the same command with `--replace`: `localify restart` would run the service's own `dev` script, `wrangler dev`. + +To open it from a phone, give that domain a public URL. It asks for a generated password, which is what guards the data, so keep the URL protected and never run `public-url unprotect` on it: + +```bash +localify public-url create cloud-dashboard..localify +``` + +It answers only for `.localify` hosts and loopback, which a public URL's traffic arrives as. A dedicated D1 token in Infisical, with D1 Read and nothing else, would be safer than the deploy token it reads with today. diff --git a/apps/cloud/package.json b/apps/cloud/package.json index cf87cc8..dd459c1 100644 --- a/apps/cloud/package.json +++ b/apps/cloud/package.json @@ -10,7 +10,8 @@ "deploy": "node scripts/deploy.mjs", "migrate": "node scripts/migrate.mjs", "migrate:local": "wrangler d1 migrations apply localify-cloud --local", - "admin": "node scripts/admin.ts" + "admin": "node scripts/admin.ts", + "dashboard": "node scripts/dashboard.ts" }, "devDependencies": { "@types/node": "^25.6.0", diff --git a/apps/cloud/scripts/dashboard.ts b/apps/cloud/scripts/dashboard.ts new file mode 100644 index 0000000..68a8f42 --- /dev/null +++ b/apps/cloud/scripts/dashboard.ts @@ -0,0 +1,55 @@ +/// +// `pnpm cloud:dashboard [--local]`: a read-only overview of every Localify +// Cloud account, served on this machine. Start it through Localify, which +// gives it a port and a `.localify` URL (apps/cloud/README.md, "Dashboard"). +// It reads the production D1 as `CLOUDFLARE_DEPLOY_TOKEN` from Infisical, +// in one `wrangler d1 execute` call of SELECT statements at most every 30 +// seconds; `--local` reads the D1 of `pnpm cloud:dev` instead. + +import { createServer } from "node:http"; + +import { wranglerReader } from "./dashboard/db.ts"; +import { cachedLoader, createHandler } from "./dashboard/server.ts"; + +const args = process.argv.slice(2).filter((arg) => arg !== "--"); +const unknown = args.filter((arg) => arg !== "--local"); +if (unknown.length > 0) { + console.error(`Unknown argument: ${unknown.join(" ")}. Usage: pnpm cloud:dashboard [--local]`); + process.exit(1); +} +const local = args.includes("--local"); + +const port = Number(process.env.PORT); +if (!Number.isInteger(port) || port <= 0 || port > 65535) { + console.error( + 'PORT is not set: start the dashboard through Localify, which picks its port (apps/cloud/README.md, "Dashboard").', + ); + process.exit(1); +} + +// Stopping kills a read in progress, so a stalled wrangler never holds the exit. +const reads = new AbortController(); +const handler = createHandler(cachedLoader(wranglerReader(local, reads.signal)), { + source: local ? "Local D1" : "Production D1", +}); +const server = createServer((request, response) => { + handler(request, response).catch((error: unknown) => { + console.error(error); + if (!response.headersSent) response.writeHead(500, { "content-type": "text/plain" }); + response.end("Internal error."); + }); +}); +// Loopback only: the Localify proxy is the way in. +server.listen(port, "127.0.0.1", () => { + const url = process.env.LOCALIFY_URL ?? `http://127.0.0.1:${port}`; + console.log( + `Localify Cloud dashboard, read-only, on ${local ? "the local" : "the production"} D1: ${url}`, + ); +}); +for (const signal of ["SIGINT", "SIGTERM"] as const) { + process.on(signal, () => { + reads.abort(); + server.close(() => process.exit(0)); + server.closeAllConnections(); + }); +} diff --git a/apps/cloud/scripts/dashboard/db.ts b/apps/cloud/scripts/dashboard/db.ts new file mode 100644 index 0000000..d40f566 --- /dev/null +++ b/apps/cloud/scripts/dashboard/db.ts @@ -0,0 +1,96 @@ +/// +// The dashboard's only way into D1: plain SELECT statements, refused before +// they leave the process when they are anything else, sent in one +// `wrangler d1 execute` call. Its URL is guarded by a password alone, so a +// leak may show data but never change it. + +import { readCloudValues, wranglerOutputAsync } from "../infisical.mjs"; + +export type Row = Record; +/** Runs SELECT statements, in order, and returns the rows of each one. */ +export type ReadDb = (statements: string[]) => Promise; + +/** How long one read of D1 may take; a production read takes a few seconds. */ +export const READ_TIMEOUT_MS = 60_000; + +/** A statement the dashboard refuses to send. */ +export class NotReadOnlyError extends Error {} + +/** + * Words that change data, the schema or the connection, anywhere outside a + * string literal or a quoted identifier. Column names such as `deleted_at` + * are not words of their own, so they pass. + */ +const FORBIDDEN = + /\b(INSERT|UPDATE|DELETE|REPLACE|UPSERT|MERGE|CREATE|DROP|ALTER|TRUNCATE|ATTACH|DETACH|PRAGMA|VACUUM|REINDEX|ANALYZE|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|RETURNING|TRANSACTION|LOAD_EXTENSION)\b/i; + +/** String literals, quoted identifiers and comments, in the order SQLite reads them. */ +const LEXEMES = /'(?:[^']|'')*'|"(?:[^"]|"")*"|`[^`]*`|\[[^\]]*\]|--[^\n]*|\/\*[\s\S]*?\*\//g; + +/** + * Returns `sql` trimmed when it is one SELECT statement, and throws + * `NotReadOnlyError` otherwise: a statement that starts with anything but + * SELECT (a CTE may hold a write, so WITH is refused too), holds a `;`, an + * unterminated quote or comment, or a forbidden word. + */ +export function assertSelect(sql: string): string { + const trimmed = sql.trim(); + const code = trimmed.replace(LEXEMES, (lexeme) => + lexeme.startsWith("--") || lexeme.startsWith("/*") ? " " : "''", + ); + const refuse = (why: string): never => { + throw new NotReadOnlyError(`The dashboard sends SELECT statements only: ${why}`); + }; + if (!/^SELECT\b/i.test(code)) refuse("this one does not start with SELECT."); + if (code.includes(";")) refuse("one statement at a time, without `;`."); + // What is left of a quote or a comment after the literals are gone is + // an unterminated one, which could hide the rest of the statement. + if (/['"`[]|\/\*|\*\//.test(code.replaceAll("''", ""))) { + refuse("an unterminated quote or comment."); + } + const word = FORBIDDEN.exec(code); + if (word) refuse(`it holds ${word[1]!.toUpperCase()}.`); + return trimmed; +} + +/** `run` behind the guard: every statement is checked before any is sent. */ +export function readOnly(run: ReadDb): ReadDb { + return async (statements) => run(statements.map(assertSelect)); +} + +/** + * Production D1, or with `local` the D1 of `pnpm cloud:dev`, through + * `wrangler d1 execute`: one call for all the statements. Only wrangler's + * identity is kept from Infisical, and it never leaves this process but in + * wrangler's environment. A read that runs past `READ_TIMEOUT_MS`, or that + * `signal` aborts, kills wrangler and fails, without blocking the server. + */ +export function wranglerReader(local: boolean, signal?: AbortSignal): ReadDb { + const identity: Record = {}; + if (!local) { + const { CLOUDFLARE_DEPLOY_TOKEN, CLOUDFLARE_ACCOUNT_ID } = readCloudValues(); + identity.CLOUDFLARE_DEPLOY_TOKEN = CLOUDFLARE_DEPLOY_TOKEN; + identity.CLOUDFLARE_ACCOUNT_ID = CLOUDFLARE_ACCOUNT_ID; + } + return readOnly(async (statements) => { + const output = await wranglerOutputAsync( + identity, + [ + "d1", + "execute", + "localify-cloud", + local ? "--local" : "--remote", + "--yes", + "--json", + "--command", + statements.join(";\n"), + ], + { timeoutMs: READ_TIMEOUT_MS, signal }, + ); + const results = JSON.parse(output) as { results?: Row[] }[]; + if (!Array.isArray(results) || results.length !== statements.length) { + throw new Error(`wrangler returned ${results.length} results for ${statements.length} reads`); + } + return results.map((result) => result.results ?? []); + }); +} diff --git a/apps/cloud/scripts/dashboard/model.ts b/apps/cloud/scripts/dashboard/model.ts new file mode 100644 index 0000000..8e9decf --- /dev/null +++ b/apps/cloud/scripts/dashboard/model.ts @@ -0,0 +1,394 @@ +// What the dashboard reads from D1, and the pure aggregation of those rows +// into what it shows. Plans, overrides and add-ons come from the Worker's own +// rules (`src/entitlement.ts`), never from a copy of them. +// +// No statement selects a token, a password hash or salt, a tunnel or DNS +// id, a remote key or an ingress port: what is not read cannot be served. + +import type { ReadDb, Row } from "./db.ts"; + +import { + EVERY_ACCOUNT_SQL, + accountOf, + servingUrlLimit, + signedInMachineCap, + type AccountRow, + type Entitlement, + type PlanStatus, +} from "../../src/entitlement.ts"; + +/** The reads of one load, sent together. Each is a SELECT without parameters. */ +export const QUERIES = { + accounts: EVERY_ACCOUNT_SQL, + users: `SELECT id, github_id, login, created_at, banned_reason FROM users`, + overrides: `SELECT user_id, reason FROM plan_overrides`, + billing: `SELECT user_id, refreshed_at FROM billing`, + machines: ` + SELECT id, user_id, name, status, tunnel_state, created_at, tunnel_ready_at, remote_key_at + FROM machines WHERE status != 'revoked' OR tunnel_state != 'none' + ORDER BY user_id, created_at, id`, + urls: ` + SELECT p.id, p.user_id, p.slug, p.wildcard, p.protected, m.name AS machine_name, + p.created_at, p.deleted_at, p.taken_down_at, p.taken_down_reason, p.suspended_at + FROM public_urls p LEFT JOIN machines m ON m.id = p.machine_id + WHERE p.deleted_at IS NULL OR p.taken_down_at IS NOT NULL + ORDER BY p.user_id, p.created_at, p.id`, + // D1 records no visits: the latest sign-in, tunnel start, remote key, + // URL created or deleted, and billing event stand in for activity, 0 for + // none. Joins, not a UNION: D1 caps the terms of a compound SELECT. + activity: ` + SELECT u.id AS user_id, MAX(COALESCE(m.at, 0), COALESCE(p.at, 0), COALESCE(w.at, 0)) AS at + FROM users u + LEFT JOIN (SELECT user_id, MAX(MAX(created_at), COALESCE(MAX(tunnel_ready_at), 0), + COALESCE(MAX(remote_key_at), 0)) AS at + FROM machines GROUP BY user_id) m ON m.user_id = u.id + LEFT JOIN (SELECT user_id, MAX(MAX(created_at), COALESCE(MAX(deleted_at), 0)) AS at + FROM public_urls GROUP BY user_id) p ON p.user_id = u.id + LEFT JOIN (SELECT user_id, MAX(received_at) AS at + FROM webhook_events WHERE user_id IS NOT NULL GROUP BY user_id) w ON w.user_id = u.id`, +} as const; + +export type Raw = { [K in keyof typeof QUERIES]: Row[] }; + +/** Every query in one call. */ +export async function readRaw(db: ReadDb): Promise { + const keys = Object.keys(QUERIES) as (keyof typeof QUERIES)[]; + const results = await db(keys.map((key) => QUERIES[key])); + return Object.fromEntries(keys.map((key, index) => [key, results[index] ?? []])) as Raw; +} + +const DAY_MS = 24 * 60 * 60 * 1000; +/** Share of a limit from which an account is listed for attention. */ +export const NEAR_LIMIT = 0.8; +/** How far ahead an expiring override is listed. */ +export const EXPIRY_WINDOW_MS = 30 * DAY_MS; + +export const PLAN_STATUSES: PlanStatus[] = [ + "override", + "trialing", + "active", + "past_due", + "canceling", + "none", +]; + +export type MachineView = { + id: string; + name: string; + status: string; + /** Holds a serving slot: its tunnel state is anything but `none`. */ + serving: boolean; + tunnelState: string; + linked: boolean; + createdAt: number; +}; + +export type UrlState = "serving" | "pending" | "suspended" | "taken_down"; + +export type UrlView = { + slug: string; + state: UrlState; + deleted: boolean; + wildcard: boolean; + protected: boolean; + machineName: string | null; + createdAt: number; + takenDownAt: number | null; + takenDownReason: string | null; +}; + +export type OverrideView = { + servingMachines: number; + publicUrls: number; + remoteAccess: boolean; + reason: string; + expiresAt: number | null; + /** Past its expiry: the plan applies again. */ + expired: boolean; +}; + +export type UserView = { + id: string; + githubId: number; + login: string; + createdAt: number; + bannedAt: number | null; + bannedReason: string | null; + status: PlanStatus; + interval: string | null; + proStatus: string | null; + renewsAt: string | null; + endsAt: string | null; + trialEndsAt: string | null; + billingRefreshedAt: number | null; + override: OverrideView | null; + addons: { machines: number; urlPacks: number }; + entitlement: Entitlement; + /** Machines holding a serving slot, against `entitlement.servingMachines`. */ + servingSlots: number; + /** Active machines, against `signedInCap`. */ + signedIn: number; + signedInCap: number; + /** Neither deleted nor taken down, against `entitlement.publicUrls`. */ + liveUrls: number; + servingUrls: number; + lastActivityAt: number | null; + machines: MachineView[]; + urls: UrlView[]; +}; + +export type AttentionKind = "banned" | "past_due" | "override_expiring" | "urls" | "machines"; + +export type Attention = { userId: string; login: string; kind: AttentionKind; detail: string }; + +export type Dashboard = { + readAt: number; + totals: { + users: number; + newLast7Days: number; + newLast30Days: number; + activeMachines: number; + servingMachines: number; + liveUrls: number; + servingUrls: number; + banned: number; + takedowns: number; + }; + statuses: Record; + /** Add-on units that count right now, across accounts. */ + addonUnits: { machines: number; urlPacks: number }; + /** New sign-ups per week, oldest first, from the first sign-up's week to now's. */ + signupsByWeek: { weekStart: number; count: number }[]; + attention: Attention[]; + /** Newest sign-up first. */ + users: UserView[]; +}; + +function num(value: unknown): number { + return Number(value); +} + +function numOrNull(value: unknown): number | null { + return value === null || value === undefined ? null : Number(value); +} + +function strOrNull(value: unknown): string | null { + return value === null || value === undefined ? null : String(value); +} + +function groupBy(rows: Row[]): Map { + const groups = new Map(); + for (const row of rows) { + const key = String(row.user_id); + const group = groups.get(key); + if (group) group.push(row); + else groups.set(key, [row]); + } + return groups; +} + +function byUser(rows: Row[]): Map { + return new Map(rows.map((row) => [String(row.user_id), row])); +} + +/** Monday 00:00 UTC of the week holding `ms`. */ +export function weekStart(ms: number): number { + const day = Math.floor(ms / DAY_MS); + // 1970-01-01 was a Thursday: day 0 is 3 days after a Monday. + return (day - ((day + 3) % 7)) * DAY_MS; +} + +/** + * The URLs of one owner with their state, as `cloud:admin show` gives it: + * the oldest live URLs within the limit serve unless `suspended_at` is set, + * which a reconcile clears ("pending"); the rest are suspended. + */ +function urlViews(urls: Row[], entitlement: Entitlement): UrlView[] { + const limit = servingUrlLimit(entitlement); + let rank = 0; + return urls.map((url) => { + const deleted = url.deleted_at !== null; + const takenDown = url.taken_down_at !== null; + if (!deleted && !takenDown) rank++; + const state: UrlState = takenDown + ? "taken_down" + : rank <= limit && url.suspended_at === null + ? "serving" + : rank <= limit + ? "pending" + : "suspended"; + return { + slug: String(url.slug), + state, + deleted, + wildcard: num(url.wildcard) === 1, + protected: num(url.protected) === 1, + machineName: strOrNull(url.machine_name), + createdAt: num(url.created_at), + takenDownAt: numOrNull(url.taken_down_at), + takenDownReason: strOrNull(url.taken_down_reason), + }; + }); +} + +/** Whether `used` reaches `NEAR_LIMIT` of a non-zero `limit`. */ +export function nearLimit(used: number, limit: number): boolean { + return limit > 0 && used >= NEAR_LIMIT * limit; +} + +/** The dashboard of the rows of one load, as of `now`. */ +export function buildDashboard(raw: Raw, now: number): Dashboard { + const accounts = byUser(raw.accounts); + const overrides = byUser(raw.overrides); + const billing = byUser(raw.billing); + const activity = byUser(raw.activity); + const machines = groupBy(raw.machines); + const urls = groupBy(raw.urls); + + const users: UserView[] = raw.users.map((user) => { + const id = String(user.id); + const row = accounts.get(id) as AccountRow | undefined; + if (!row) throw new Error(`User ${id} has no account row`); + const account = accountOf(row, now); + const overrideRow = overrides.get(id); + const override: OverrideView | null = + row.override_machines === null || row.override_urls === null + ? null + : { + servingMachines: num(row.override_machines), + publicUrls: num(row.override_urls), + remoteAccess: num(row.override_remote_access) === 1, + reason: String(overrideRow?.reason ?? ""), + expiresAt: numOrNull(row.override_expires_at), + expired: row.override_expires_at !== null && num(row.override_expires_at) <= now, + }; + const machineViews: MachineView[] = (machines.get(id) ?? []).map((machine) => ({ + id: String(machine.id), + name: String(machine.name), + status: String(machine.status), + serving: machine.tunnel_state !== "none", + tunnelState: String(machine.tunnel_state), + linked: machine.remote_key_at !== null, + createdAt: num(machine.created_at), + })); + const views = urlViews(urls.get(id) ?? [], account.entitlement); + return { + id, + githubId: num(user.github_id), + login: String(user.login), + createdAt: num(user.created_at), + bannedAt: numOrNull(row.banned_at), + bannedReason: strOrNull(user.banned_reason), + status: account.plan.status, + interval: account.plan.interval, + proStatus: row.pro_status, + renewsAt: account.plan.renewsAt, + endsAt: account.plan.endsAt, + trialEndsAt: account.plan.trialEndsAt, + billingRefreshedAt: numOrNull(billing.get(id)?.refreshed_at), + override, + addons: account.plan.addons, + entitlement: account.entitlement, + servingSlots: machineViews.filter((machine) => machine.serving).length, + signedIn: machineViews.filter((machine) => machine.status === "active").length, + signedInCap: signedInMachineCap(account.entitlement), + liveUrls: views.filter((url) => !url.deleted && url.state !== "taken_down").length, + servingUrls: views.filter((url) => url.state === "serving").length, + lastActivityAt: num(activity.get(id)?.at ?? 0) || null, + machines: machineViews, + urls: views, + }; + }); + users.sort((a, b) => b.createdAt - a.createdAt || a.login.localeCompare(b.login)); + + const statuses = Object.fromEntries(PLAN_STATUSES.map((status) => [status, 0])) as Record< + PlanStatus, + number + >; + for (const user of users) statuses[user.status]++; + + const sum = (pick: (user: UserView) => number) => + users.reduce((total, user) => total + pick(user), 0); + + return { + readAt: now, + totals: { + users: users.length, + newLast7Days: users.filter((user) => user.createdAt > now - 7 * DAY_MS).length, + newLast30Days: users.filter((user) => user.createdAt > now - 30 * DAY_MS).length, + activeMachines: sum((user) => user.signedIn), + servingMachines: sum((user) => user.servingSlots), + liveUrls: sum((user) => user.liveUrls), + servingUrls: sum((user) => user.servingUrls), + banned: users.filter((user) => user.bannedAt !== null).length, + takedowns: sum((user) => user.urls.filter((url) => url.state === "taken_down").length), + }, + statuses, + addonUnits: { + machines: sum((user) => user.addons.machines), + urlPacks: sum((user) => user.addons.urlPacks), + }, + signupsByWeek: signupsByWeek(users, now), + attention: attentionList(users, now), + users, + }; +} + +function signupsByWeek(users: UserView[], now: number): Dashboard["signupsByWeek"] { + if (users.length === 0) return []; + const first = weekStart(Math.min(...users.map((user) => user.createdAt))); + const last = weekStart(now); + const weeks: Dashboard["signupsByWeek"] = []; + for (let start = first; start <= last; start += 7 * DAY_MS) { + weeks.push({ weekStart: start, count: 0 }); + } + for (const user of users) { + const index = Math.round((weekStart(user.createdAt) - first) / (7 * DAY_MS)); + const week = weeks[index]; + if (week) week.count++; + } + return weeks; +} + +/** Banned and past_due accounts, overrides ending within 30 days, and accounts near a limit. */ +function attentionList(users: UserView[], now: number): Attention[] { + const list: Attention[] = []; + const add = (user: UserView, kind: AttentionKind, detail: string) => + list.push({ userId: user.id, login: user.login, kind, detail }); + for (const user of users) { + if (user.bannedAt !== null) add(user, "banned", user.bannedReason ?? "(no reason)"); + // Under an override too: the card still fails. + if (user.proStatus === "past_due") { + add( + user, + "past_due", + user.status === "override" ? "Pro past_due, under an override" : "Pro past_due", + ); + } + const expiresAt = user.override?.expiresAt ?? null; + if (expiresAt !== null && expiresAt > now && expiresAt <= now + EXPIRY_WINDOW_MS) { + const days = Math.ceil((expiresAt - now) / DAY_MS); + add( + user, + "override_expiring", + `override "${user.override!.reason}" ends in ${days} ${days === 1 ? "day" : "days"}`, + ); + } + if (user.bannedAt !== null) continue; + if (nearLimit(user.liveUrls, user.entitlement.publicUrls)) { + add(user, "urls", `${user.liveUrls} of ${user.entitlement.publicUrls} URLs`); + } + if (nearLimit(user.servingSlots, user.entitlement.servingMachines)) { + add( + user, + "machines", + `${user.servingSlots} of ${user.entitlement.servingMachines} serving machines`, + ); + } + if (nearLimit(user.signedIn, user.signedInCap)) { + add(user, "machines", `${user.signedIn} of ${user.signedInCap} signed-in machines`); + } + } + const order: AttentionKind[] = ["banned", "past_due", "override_expiring", "urls", "machines"]; + return list.sort((a, b) => order.indexOf(a.kind) - order.indexOf(b.kind)); +} diff --git a/apps/cloud/scripts/dashboard/page.ts b/apps/cloud/scripts/dashboard/page.ts new file mode 100644 index 0000000..2c1c89b --- /dev/null +++ b/apps/cloud/scripts/dashboard/page.ts @@ -0,0 +1,549 @@ +// The dashboard's HTML, rendered on the server from a `Dashboard`. Every +// value from D1 goes through `esc`; the only script is inline, behind the +// page's nonce, and sorts, filters and switches the theme in the browser. +// Nothing here links to an action: the dashboard only reads. + +import type { PlanStatus } from "../../src/entitlement.ts"; + +import { + PLAN_STATUSES, + nearLimit, + type Attention, + type Dashboard, + type UrlState, + type UserView, +} from "./model.ts"; + +/** What every page shows of the read behind it: `readAt` is null before a first read. */ +export type PageMeta = { + source: "Production D1" | "Local D1"; + readAt: number | null; + now: number; + nonce: string; + path: string; +}; + +export function esc(value: unknown): string { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +function day(ms: number | null): string { + return ms === null ? "—" : new Date(ms).toISOString().slice(0, 10); +} + +function iso(ms: number): string { + return `${new Date(ms).toISOString().slice(0, 19)}Z`; +} + +/** "3 min ago", "2 days ago", "in 5 days". */ +export function relative(ms: number, now: number): string { + const seconds = Math.round((now - ms) / 1000); + const abs = Math.abs(seconds); + const [value, unit] = + abs < 60 + ? [abs, "s"] + : abs < 3600 + ? [Math.floor(abs / 60), "min"] + : abs < 86400 + ? [Math.floor(abs / 3600), "h"] + : [Math.floor(abs / 86400), abs < 2 * 86400 ? "day" : "days"]; + return seconds >= 0 ? `${value} ${unit} ago` : `in ${value} ${unit}`; +} + +function when(ms: number | null, now: number): string { + return ms === null + ? `—` + : ``; +} + +const STATUS_LABELS: Record = { + override: "Override", + trialing: "Trialing", + active: "Active", + past_due: "Past due", + canceling: "Canceling", + none: "No plan", +}; + +function statusChip(status: PlanStatus): string { + return `${esc(STATUS_LABELS[status])}`; +} + +const URL_STATES: Record = { + serving: "Serving", + pending: "Suspended until the next reconcile", + suspended: "Suspended", + taken_down: "Taken down", +}; + +/** + * A bar of `used` against `limit`, with the numbers in text: amber from 80% + * of the limit, red above it, gray when the limit is 0 (nothing serves). + */ +function meter(used: number, limit: number): string { + const share = limit > 0 ? Math.min(used / limit, 1) : used > 0 ? 1 : 0; + const level = + limit === 0 ? "none" : used > limit ? "over" : nearLimit(used, limit) ? "near" : "ok"; + const label = + level === "over" ? " over the limit" : level === "near" ? " near or at the limit" : ""; + return ` + + ${used} / ${limit}`; +} + +function planCell(user: UserView, now: number): string { + if (user.override) { + const o = user.override; + const ends = + o.expiresAt === null + ? "no expiry" + : o.expired + ? `expired ${day(o.expiresAt)}` + : `until ${day(o.expiresAt)}`; + const chip = o.expired ? statusChip(user.status) : statusChip("override"); + return `${chip} ${o.expired ? "override " : ""}${esc(o.reason)} · ${esc(ends)}${ + o.expiresAt !== null && !o.expired ? `${when(o.expiresAt, now)}` : "" + }`; + } + const detail = [user.interval, user.endsAt ? `ends ${user.endsAt.slice(0, 10)}` : null] + .filter(Boolean) + .join(" · "); + return `${statusChip(user.status)}${detail ? ` ${esc(detail)}` : ""}`; +} + +const STYLE = ` +:root { + color-scheme: light; + --bg: #f6f6f4; --surface: #fcfcfb; --surface-2: #f0efec; --border: #e2e1dc; + --text: #0b0b0b; --text-2: #52514e; --muted: #7a7974; + --accent: #2a78d6; --accent-soft: #dce9f9; + --warn: #b26b00; --warn-soft: #fbecd0; --bad: #c8302f; --bad-soft: #f9dcdc; + --good: #11804f; --good-soft: #d6f0e3; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + color-scheme: dark; + --bg: #121211; --surface: #1a1a19; --surface-2: #232321; --border: #33332f; + --text: #f0efec; --text-2: #c3c2b7; --muted: #8f8e86; + --accent: #3987e5; --accent-soft: #1d3450; + --warn: #e0a030; --warn-soft: #3d2f12; --bad: #e66767; --bad-soft: #432222; + --good: #3cc58a; --good-soft: #173528; + } +} +:root[data-theme="dark"] { + color-scheme: dark; + --bg: #121211; --surface: #1a1a19; --surface-2: #232321; --border: #33332f; + --text: #f0efec; --text-2: #c3c2b7; --muted: #8f8e86; + --accent: #3987e5; --accent-soft: #1d3450; + --warn: #e0a030; --warn-soft: #3d2f12; --bad: #e66767; --bad-soft: #432222; + --good: #3cc58a; --good-soft: #173528; +} +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { + margin: 0; background: var(--bg); color: var(--text); + font: 15px/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; +} +main { max-width: 1180px; margin: 0 auto; padding: 16px 16px 48px; } +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +h1 { font-size: 20px; margin: 0; } +h2 { font-size: 15px; margin: 0 0 12px; color: var(--text-2); font-weight: 600; } +header { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; margin-bottom: 16px; } +header .meta { color: var(--text-2); font-size: 13px; flex: 1 1 auto; } +.actions { display: flex; gap: 8px; } +.button { + display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px; + border: 1px solid var(--border); border-radius: 8px; background: var(--surface); + color: var(--text); font: inherit; font-size: 14px; cursor: pointer; +} +.button:hover { background: var(--surface-2); text-decoration: none; } +.badge { font-size: 12px; color: var(--text-2); border: 1px solid var(--border); border-radius: 999px; padding: 1px 8px; } +section { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 16px; margin-bottom: 16px; } +.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 16px; } +.tile { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 12px 14px; } +.tile .label { color: var(--text-2); font-size: 13px; } +.tile .value { font-size: 26px; font-weight: 650; font-variant-numeric: tabular-nums; line-height: 1.2; } +.tile .sub { color: var(--muted); font-size: 12px; } +.row { display: flex; flex-wrap: wrap; gap: 8px; } +.chip { + display: inline-block; border-radius: 999px; padding: 1px 8px; font-size: 12px; font-weight: 600; + background: var(--surface-2); color: var(--text-2); white-space: nowrap; +} +.chip-override { background: var(--accent-soft); color: var(--accent); } +.chip-trialing, .chip-active { background: var(--good-soft); color: var(--good); } +.chip-past_due, .chip-bad { background: var(--bad-soft); color: var(--bad); } +.chip-canceling, .chip-warn { background: var(--warn-soft); color: var(--warn); } +.status-count { display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 8px; } +.status-count b { font-variant-numeric: tabular-nums; } +.sub { display: block; color: var(--muted); font-size: 12px; } +.muted { color: var(--muted); } +.chart svg { display: block; width: 100%; height: auto; max-height: 240px; } +.chart .narrow { display: none; } +.chart .bar { fill: var(--accent); } +.chart .bar:hover { opacity: .8; } +.chart .axis { fill: var(--muted); font-size: 11px; } +.chart .grid { stroke: var(--border); stroke-width: 1; } +.attention { list-style: none; margin: 0; padding: 0; } +.attention li { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; padding: 8px 0; border-top: 1px solid var(--border); } +.attention li:first-child { border-top: 0; } +.toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 12px; } +.toolbar h2 { margin: 0; flex: 1 1 auto; } +input[type=search] { + font: inherit; font-size: 16px; min-height: 36px; padding: 0 10px; width: min(100%, 280px); + border: 1px solid var(--border); border-radius: 8px; background: var(--bg); color: var(--text); +} +.scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0 -16px; padding: 0 16px; } +table { border-collapse: collapse; width: 100%; font-size: 14px; } +th, td { text-align: left; padding: 8px 10px; border-top: 1px solid var(--border); vertical-align: top; } +th { color: var(--text-2); font-weight: 600; font-size: 12px; white-space: nowrap; border-top: 0; } +th button { all: unset; cursor: pointer; } +th button::after { content: " ↕"; color: var(--muted); } +th[aria-sort=ascending] button::after { content: " ↑"; color: var(--text); } +th[aria-sort=descending] button::after { content: " ↓"; color: var(--text); } +td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } +.meter { display: inline-flex; align-items: center; gap: 8px; white-space: nowrap; } +.meter-bar { display: inline-block; width: 64px; height: 6px; border-radius: 3px; background: var(--surface-2); overflow: hidden; } +.meter-bar span { display: block; height: 100%; border-radius: 3px; background: var(--accent); } +.meter-near .meter-bar span { background: var(--warn); } +.meter-over .meter-bar span { background: var(--bad); } +.meter-none .meter-bar span { background: var(--muted); } +.meter-text { font-variant-numeric: tabular-nums; font-size: 13px; } +dl { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0; } +dt { color: var(--text-2); } +dd { margin: 0; overflow-wrap: anywhere; } +.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; } +.grid-2 > section { margin-bottom: 0; } +.items { list-style: none; margin: 0; padding: 0; } +.items li { padding: 10px 0; border-top: 1px solid var(--border); display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px; } +.items li:first-child { border-top: 0; } +.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; overflow-wrap: anywhere; } +@media (max-width: 640px) { + .chart .wide { display: none; } + .chart .narrow { display: block; } + .tile .value { font-size: 22px; } + dl { grid-template-columns: 1fr; gap: 2px; } + dd { margin-bottom: 8px; } +} +`; + +// Applies the saved theme before the first paint, sorts and filters the +// users table, and drops `?reload` from the address bar once served. +const SCRIPT = ` +(() => { + const root = document.documentElement; + const saved = (() => { try { return localStorage.getItem("theme"); } catch { return null; } })(); + if (saved === "light" || saved === "dark") root.dataset.theme = saved; + if (location.search.includes("reload")) history.replaceState(null, "", location.pathname); + addEventListener("DOMContentLoaded", () => { + document.getElementById("theme")?.addEventListener("click", () => { + const dark = root.dataset.theme + ? root.dataset.theme === "dark" + : matchMedia("(prefers-color-scheme: dark)").matches; + root.dataset.theme = dark ? "light" : "dark"; + try { localStorage.setItem("theme", root.dataset.theme); } catch {} + }); + const table = document.getElementById("users"); + if (!table) return; + const body = table.tBodies[0]; + const rows = [...body.rows]; + const search = document.getElementById("search"); + const count = document.getElementById("count"); + const filter = () => { + const q = search.value.trim().toLowerCase(); + let shown = 0; + for (const row of rows) { + const match = !q || row.dataset.search.includes(q); + row.hidden = !match; + if (match) shown++; + } + count.textContent = shown === rows.length ? rows.length + " accounts" : shown + " of " + rows.length; + }; + search.addEventListener("input", filter); + for (const th of table.tHead.rows[0].cells) { + const button = th.querySelector("button"); + if (!button) continue; + button.addEventListener("click", () => { + const key = th.dataset.key; + const type = th.dataset.type; + const dir = th.getAttribute("aria-sort") === "ascending" ? -1 : 1; + for (const other of table.tHead.rows[0].cells) other.removeAttribute("aria-sort"); + th.setAttribute("aria-sort", dir === 1 ? "ascending" : "descending"); + const value = (row) => row.dataset[key] ?? ""; + rows.sort((a, b) => { + const x = value(a), y = value(b); + return dir * (type === "num" ? (Number(x) || 0) - (Number(y) || 0) : x.localeCompare(y)); + }); + body.append(...rows); + }); + } + }); +})(); +`; + +function layout(title: string, meta: PageMeta, content: string): string { + return ` + + + + + + +${esc(title)} + + + + +
+
+

Localify Cloud

+ Read-only + ${esc(meta.source)}${ + meta.readAt === null + ? ", not read yet" + : `, read ${when(meta.readAt, meta.now)} · ${esc(iso(meta.readAt).slice(11, 19))} UTC` + } + + ↻ Refresh + + +
+${content} +
+ +`; +} + +function tile(label: string, value: number, sub = ""): string { + return `
${esc(label)}
${value}
${ + sub ? `
${sub}
` : "" + }
`; +} + +/** + * Sign-ups per week as SVG bars, one series: no legend, a tooltip per bar. + * The last `count` weeks, drawn `width` units wide; text keeps its size + * when the SVG is drawn about that many pixels wide. + */ +export function signupChart(weeks: Dashboard["signupsByWeek"], count = 26, width = 720): string { + if (weeks.length === 0) return `

No sign-ups yet.

`; + const shown = weeks.slice(-count); + const height = 180; + const left = 28; + const bottom = 22; + const top = 8; + const max = Math.max(1, ...shown.map((week) => week.count)); + const ticks = max <= 4 ? max : 4; + const plotHeight = height - top - bottom; + const step = (width - left) / shown.length; + const barWidth = Math.max(2, Math.min(16, step - 4)); + const grid = Array.from({ length: ticks + 1 }, (_, i) => { + const value = Math.round((max * i) / ticks); + const y = top + plotHeight - (value / max) * plotHeight; + return ` + ${value}`; + }).join(""); + const labelEvery = Math.ceil(shown.length / 6); + const bars = shown + .map((week, i) => { + const h = (week.count / max) * plotHeight; + const x = left + i * step + (step - barWidth) / 2; + const y = top + plotHeight - h; + const label = `Week of ${day(week.weekStart)}: ${week.count} ${week.count === 1 ? "sign-up" : "sign-ups"}`; + // A hit target as tall as the plot, so an empty week can be hovered too. + return `${esc(label)} + + ${week.count > 0 ? `` : ""} + ${i % labelEvery === 0 ? `${esc(day(week.weekStart).slice(5))}` : ""}`; + }) + .join(""); + return `${grid}${bars}`; +} + +const ATTENTION_LABELS: Record = { + banned: ["Banned", "chip-bad"], + past_due: ["Past due", "chip-bad"], + override_expiring: ["Override ending", "chip-warn"], + urls: ["URLs near limit", "chip-warn"], + machines: ["Machines near limit", "chip-warn"], +}; + +function attentionList(items: Attention[]): string { + if (items.length === 0) return `

Nothing needs attention.

`; + return `
    ${items + .map((item) => { + const [label, chip] = ATTENTION_LABELS[item.kind]; + return `
  • ${esc(label)} + ${esc(item.login)} + ${esc(item.detail)}
  • `; + }) + .join("")}
`; +} + +function userRow(user: UserView, now: number): string { + const search = [user.login, user.githubId, user.status, user.override?.reason ?? ""] + .join(" ") + .toLowerCase(); + return ` + ${esc(user.login)} + ${esc(day(user.createdAt))} + ${planCell(user, now)} + ${meter(user.servingSlots, user.entitlement.servingMachines)}${user.signedIn} signed in of ${user.signedInCap} + ${meter(user.liveUrls, user.entitlement.publicUrls)}${user.servingUrls} serving + ${when(user.lastActivityAt, now)} + ${user.bannedAt === null ? "" : `Banned`} + `; +} + +export function overviewPage(dashboard: Dashboard, meta: PageMeta): string { + const t = dashboard.totals; + const statuses = PLAN_STATUSES.map( + (status) => + `${statusChip(status)} ${dashboard.statuses[status]}`, + ).join(""); + const headers: [string, string, "num" | "text", string][] = [ + ["login", "GitHub login", "text", ""], + ["created", "Signed up", "num", ""], + ["plan", "Plan or override", "text", ""], + ["machines", "Serving machines", "num", ""], + ["urls", "Live URLs", "num", ""], + [ + "activity", + "Last activity", + "num", + "Latest sign-in, tunnel start, URL change or billing event: D1 records no visits", + ], + ["banned", "Banned", "num", ""], + ]; + const content = ` +
+ ${tile("Users", t.users, `+${t.newLast7Days} in 7 days · +${t.newLast30Days} in 30`)} + ${tile("Active machines", t.activeMachines, `${t.servingMachines} holding a serving slot`)} + ${tile("Live URLs", t.liveUrls, `${t.servingUrls} serving`)} + ${tile("Add-on units", dashboard.addonUnits.machines + dashboard.addonUnits.urlPacks, `${dashboard.addonUnits.machines} machine · ${dashboard.addonUnits.urlPacks} URL packs`)} + ${tile("Banned", t.banned)} + ${tile("Takedowns", t.takedowns)} +
+

Accounts per plan

${statuses}
+

New sign-ups per week

${signupChart(dashboard.signupsByWeek)}
${signupChart(dashboard.signupsByWeek, 12, 360)}
+

Needs attention

${attentionList(dashboard.attention)}
+
+

Users ${dashboard.users.length} accounts

+
+
+ ${headers + .map( + ([key, label, type, title]) => + ``, + ) + .join("")} + ${dashboard.users.map((user) => userRow(user, meta.now)).join("")} +
+
`; + return layout("Localify Cloud", meta, content); +} + +export function userPage(user: UserView, meta: PageMeta): string { + const now = meta.now; + const e = user.entitlement; + const override = user.override + ? `${user.override.servingMachines} serving machines, ${user.override.publicUrls} URLs, ${ + user.override.remoteAccess ? "remote access" : "no remote access" + } · "${esc(user.override.reason)}" · ${ + user.override.expiresAt === null + ? "no expiry" + : `${user.override.expired ? "expired" : "expires"} ${esc(iso(user.override.expiresAt))}` + }` + : `None`; + const billing = + user.billingRefreshedAt === null + ? `No billing snapshot` + : `Pro ${esc(user.proStatus ?? "none")}${user.interval ? ` (${esc(user.interval)})` : ""} · snapshot ${when(user.billingRefreshedAt, now)}`; + const dates = [ + user.trialEndsAt ? `trial ends ${user.trialEndsAt.slice(0, 10)}` : null, + user.renewsAt ? `renews ${user.renewsAt.slice(0, 10)}` : null, + user.endsAt ? `ends ${user.endsAt.slice(0, 10)}` : null, + ].filter(Boolean); + const machines = user.machines.length + ? `
    ${user.machines + .map( + (machine) => `
  • ${esc(machine.name)} + signed in ${esc(day(machine.createdAt))}${machine.linked ? " · remote key" : ""} + ${ + machine.status !== "active" + ? `${esc(machine.status)}` + : machine.serving + ? `Serving slot · ${esc(machine.tunnelState)}` + : `No slot` + }
  • `, + ) + .join("")}
` + : `

No signed-in machine.

`; + const urlChip: Record = { + serving: "chip-active", + pending: "chip-warn", + suspended: "chip-warn", + taken_down: "chip-bad", + }; + const urls = user.urls.length + ? `
    ${user.urls + .map( + ( + url, + ) => `
  • ${esc(url.slug)}${url.wildcard ? ` wildcard` : ""}${url.protected ? "" : ` open`} + ${url.machineName ? `on ${esc(url.machineName)}` : "no machine"} · created ${esc(day(url.createdAt))}${ + url.takenDownAt !== null + ? ` · taken down ${esc(day(url.takenDownAt))}: ${esc(url.takenDownReason ?? "(no reason)")}` + : "" + }${url.deleted ? " · deleted" : ""} + ${esc(URL_STATES[url.state])}
  • `, + ) + .join("")}
` + : `

No public URL.

`; + const content = ` +

← All accounts

+
+

${esc(user.login)}

${statusChip(user.status)}${ + user.bannedAt !== null ? ` Banned` : "" + }
+
+
GitHub id
${user.githubId}
+
User id
${esc(user.id)}
+
Signed up
${esc(iso(user.createdAt))} · ${when(user.createdAt, now)}
+
Last activity
${when(user.lastActivityAt, now)}
+
Ban
${user.bannedAt === null ? `Not banned` : `${esc(iso(user.bannedAt))}: ${esc(user.bannedReason ?? "(no reason)")}`}
+
Override
${override}
+
Billing
${billing}${dates.length ? `${esc(dates.join(" · "))}` : ""}
+
Add-ons counting
${user.addons.machines} machine units, ${user.addons.urlPacks} URL packs
+
Entitlement
${ + e.servingMachines === 0 && e.publicUrls === 0 && !e.remoteAccess + ? "none" + : `${e.servingMachines} serving machines, ${e.publicUrls} URLs, ${e.remoteAccess ? "remote access" : "no remote access"}` + }
+
Serving machines
${meter(user.servingSlots, e.servingMachines)}
+
Signed-in machines
${meter(user.signedIn, user.signedInCap)}
+
Live URLs
${meter(user.liveUrls, e.publicUrls)} ${user.servingUrls} serving
+
+
+
+

Machines

${machines}
+

Public URLs

${urls}
+
`; + return layout(`${user.login} · Localify Cloud`, meta, content); +} + +export function messagePage(title: string, message: string, meta: PageMeta): string { + return layout( + `${title} · Localify Cloud`, + meta, + `

${esc(title)}

${esc(message)}

`, + ); +} diff --git a/apps/cloud/scripts/dashboard/server.ts b/apps/cloud/scripts/dashboard/server.ts new file mode 100644 index 0000000..6d9d247 --- /dev/null +++ b/apps/cloud/scripts/dashboard/server.ts @@ -0,0 +1,143 @@ +/// +// The dashboard's HTTP side: a cache of one read of D1, and the routes. GET +// and HEAD only, no route takes input that reaches SQL, and nothing served +// carries a secret: the reads never select one (`model.ts`). + +import type { IncomingMessage, ServerResponse } from "node:http"; + +import { randomBytes } from "node:crypto"; + +import type { ReadDb } from "./db.ts"; + +import { buildDashboard, readRaw, type Dashboard } from "./model.ts"; +import { messagePage, overviewPage, userPage, type PageMeta } from "./page.ts"; + +/** How long a read serves before the next page load reads D1 again. */ +export const CACHE_MS = 30_000; +/** The refresh button reads again at most this often, whoever presses it. */ +export const MIN_RELOAD_MS = 5_000; + +export type Loader = (fresh: boolean) => Promise; + +/** + * One read shared by every request while it runs, kept `CACHE_MS`. A + * failed read is not kept: the next request tries again. + */ +export function cachedLoader(db: ReadDb, clock: () => number = Date.now): Loader { + let cached: Dashboard | null = null; + let running: Promise | null = null; + return (fresh) => { + const now = clock(); + const age = cached ? now - cached.readAt : Infinity; + if (cached && age < (fresh ? MIN_RELOAD_MS : CACHE_MS)) return Promise.resolve(cached); + running ??= readRaw(db) + .then((raw) => (cached = buildDashboard(raw, clock()))) + .finally(() => (running = null)); + return running; + }; +} + +/** + * Loopback, and `.localify` names: the Localify proxy, and a public URL, + * whose daemon forwards the local host. Any other `Host` is a page that + * resolved its own name to this machine, and gets nothing. + */ +export function allowedHost(host: string | undefined): boolean { + if (!host) return false; + const name = host.replace(/:\d+$/, "").toLowerCase(); + return ( + name === "localhost" || + name === "127.0.0.1" || + name === "[::1]" || + name === "localify" || + name.endsWith(".localify") + ); +} + +function headers(nonce: string): Record { + return { + "content-type": "text/html; charset=utf-8", + "cache-control": "no-store", + "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`, + "x-content-type-options": "nosniff", + "x-frame-options": "DENY", + "referrer-policy": "no-referrer", + "x-robots-tag": "noindex, nofollow", + }; +} + +export type Options = { source: PageMeta["source"]; clock?: () => number }; + +/** The request handler over a loader. Errors are logged here, never served. */ +export function createHandler(load: Loader, { source, clock = Date.now }: Options) { + let lastReadAt: number | null = null; + return async (request: IncomingMessage, response: ServerResponse): Promise => { + const nonce = randomBytes(16).toString("base64"); + const url = new URL(request.url ?? "/", "http://dashboard"); + const send = (status: number, html: string, extra: Record = {}) => { + response.writeHead(status, { ...headers(nonce), ...extra }); + response.end(request.method === "HEAD" ? undefined : html); + }; + const meta = (): PageMeta => ({ + source, + readAt: lastReadAt, + now: clock(), + nonce, + path: url.pathname, + }); + + if (!allowedHost(request.headers.host)) { + send(421, "Unknown host.", { "content-type": "text/plain; charset=utf-8" }); + return; + } + if (request.method !== "GET" && request.method !== "HEAD") { + send(405, messagePage("Read-only", "This dashboard only reads.", meta()), { + allow: "GET, HEAD", + }); + return; + } + if (url.pathname === "/favicon.ico") { + response.writeHead(204, { "cache-control": "max-age=86400" }); + response.end(); + return; + } + const userMatch = /^\/users\/([^/]+)$/.exec(url.pathname); + if (url.pathname !== "/" && !userMatch) { + send(404, messagePage("Not found", "No such page.", meta())); + return; + } + + let dashboard: Dashboard; + try { + dashboard = await load(url.searchParams.has("reload")); + lastReadAt = dashboard.readAt; + } catch (error) { + console.error("Reading D1 failed:", error); + send( + 503, + messagePage( + "D1 could not be read", + "The terminal running the dashboard has the error. Try again in a moment.", + meta(), + ), + ); + return; + } + if (!userMatch) { + send(200, overviewPage(dashboard, meta())); + return; + } + let id: string; + try { + id = decodeURIComponent(userMatch[1]!); + } catch { + id = ""; + } + const user = dashboard.users.find((candidate) => candidate.id === id); + if (!user) { + send(404, messagePage("Not found", "No account has this id.", meta())); + return; + } + send(200, userPage(user, meta())); + }; +} diff --git a/apps/cloud/scripts/infisical.mjs b/apps/cloud/scripts/infisical.mjs index 07c23aa..4046077 100644 --- a/apps/cloud/scripts/infisical.mjs +++ b/apps/cloud/scripts/infisical.mjs @@ -7,7 +7,7 @@ // CLOUDFLARE_API_TOKEN (Tunnel and DNS rights) never becomes wrangler's // identity: it is a secret of the Worker only. -import { execFileSync, spawnSync } from "node:child_process"; +import { execFileSync, spawn, spawnSync } from "node:child_process"; /** The `/cloud` values for an Infisical environment, `prod` by default, by key. */ export function readCloudValues(environment = "prod") { @@ -82,6 +82,37 @@ export function wranglerOutput(values, args) { return result.stdout; } +/** + * `wranglerOutput` without blocking: for a server, which must keep answering + * and stopping while wrangler runs. Wrangler is killed past `timeoutMs`, or + * when `signal` aborts, and the promise then rejects. + */ +export function wranglerOutputAsync(values, args, { timeoutMs, signal } = {}) { + return new Promise((resolve, reject) => { + const child = spawn("wrangler", args, { + stdio: ["ignore", "pipe", "inherit"], + env: wranglerEnv(values), + timeout: timeoutMs, + signal, + killSignal: "SIGKILL", + }); + let stdout = ""; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk) => { + stdout += chunk; + if (stdout.length > 64 * 1024 * 1024) child.kill("SIGKILL"); + }); + child.on("error", reject); + child.on("close", (status, killedBy) => { + if (status === 0) resolve(stdout); + else { + const how = killedBy ? `was stopped by ${killedBy}` : `failed with status ${status}`; + reject(new Error(`wrangler ${args[0] ?? ""} ${how}:\n${stdout}`)); + } + }); + }); +} + // `node scripts/infisical.mjs `, for the migration scripts. if (import.meta.url === `file://${process.argv[1]}`) { process.exitCode = runWrangler(readCloudValues(), process.argv.slice(2)); diff --git a/apps/cloud/src/entitlement.ts b/apps/cloud/src/entitlement.ts index 6862eca..62e23ae 100644 --- a/apps/cloud/src/entitlement.ts +++ b/apps/cloud/src/entitlement.ts @@ -61,6 +61,8 @@ const SELECT_ACCOUNTS = ` /** `?1` is the user id. No row for an unknown user. */ export const ACCOUNT_SQL = `${SELECT_ACCOUNTS} WHERE u.id = ?1`; +/** Every account, for the operator's dashboard (`scripts/dashboard.ts`). */ +export const EVERY_ACCOUNT_SQL = SELECT_ACCOUNTS; /** The row `REMOTE_CHECK_SQL` returns: the account, and a JSON array of machine ids. */ export type RemoteCheckRow = AccountRow & { active_machines: string }; diff --git a/apps/cloud/test/dashboard.test.ts b/apps/cloud/test/dashboard.test.ts new file mode 100644 index 0000000..457d321 --- /dev/null +++ b/apps/cloud/test/dashboard.test.ts @@ -0,0 +1,571 @@ +// `pnpm cloud:dashboard`: its SELECT-only guard, its reads against the real +// migrations with fixture rows, the aggregation, the cache, and what its +// routes serve. Every row here is made up. + +import type { AddressInfo } from "node:net"; +import type { DatabaseSync, SQLInputValue } from "node:sqlite"; + +import { createServer, request as httpRequest, type Server } from "node:http"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { NotReadOnlyError, assertSelect, readOnly, type ReadDb } from "../scripts/dashboard/db"; +import { + QUERIES, + buildDashboard, + readRaw, + weekStart, + type Dashboard, +} from "../scripts/dashboard/model"; +import { esc, signupChart } from "../scripts/dashboard/page"; +import { + CACHE_MS, + MIN_RELOAD_MS, + allowedHost, + cachedLoader, + createHandler, +} from "../scripts/dashboard/server"; +import { createTestDb } from "./support"; + +const DAY = 24 * 60 * 60 * 1000; +const NOW = Date.UTC(2026, 10, 23, 12, 0, 0); + +describe("assertSelect", () => { + it("lets one SELECT through", () => { + expect(assertSelect(" SELECT id FROM users ")).toBe("SELECT id FROM users"); + expect(assertSelect("select deleted_at, updated FROM public_urls")).toContain("deleted_at"); + expect(assertSelect("SELECT 'DELETE FROM users' AS words")).toContain("DELETE"); + expect(assertSelect(`SELECT "update" FROM t -- a DROP in a comment`)).toContain("SELECT"); + }); + + it.each([ + ["INSERT INTO users (id) VALUES ('x')"], + ["UPDATE users SET login = 'x'"], + ["DELETE FROM users"], + ["DROP TABLE users"], + ["ALTER TABLE users ADD COLUMN x"], + ["CREATE TABLE x (y)"], + ["REPLACE INTO users (id) VALUES ('x')"], + ["PRAGMA table_info(users)"], + ["ATTACH DATABASE 'x' AS y"], + ["VACUUM"], + ["WITH x AS (SELECT 1) DELETE FROM users"], + ["WITH x AS (SELECT 1) SELECT * FROM x"], + ["SELECT 1; DELETE FROM users"], + ["SELECT 1;"], + [ + "SELECT * FROM users WHERE id IN (SELECT user_id FROM (DELETE FROM tokens RETURNING user_id))", + ], + ["SELECT 'unterminated"], + ["SELECT 1 /* DELETE FROM users"], + ['SELECT "x FROM users'], + [" insert into users (id) values ('x')"], + [""], + ])("refuses %j", (sql) => { + expect(() => assertSelect(sql)).toThrow(NotReadOnlyError); + }); + + it("refuses the whole call before anything is sent", async () => { + const run = vi.fn(async () => [[]]); + const db = readOnly(run); + await expect(db(["SELECT 1", "UPDATE users SET banned_at = 1"])).rejects.toThrow( + NotReadOnlyError, + ); + expect(run).not.toHaveBeenCalled(); + await expect(db(["SELECT 1 AS one"])).resolves.toEqual([[]]); + expect(run).toHaveBeenCalledWith(["SELECT 1 AS one"]); + }); + + it("lets every query of the dashboard through", () => { + for (const sql of Object.values(QUERIES)) expect(() => assertSelect(sql)).not.toThrow(); + }); +}); + +// --- Fixtures --- + +type Values = Record; + +function insert(sqlite: DatabaseSync, table: string, values: Values): void { + const keys = Object.keys(values); + sqlite + .prepare(`INSERT INTO ${table} (${keys.join(", ")}) VALUES (${keys.map(() => "?").join(", ")})`) + .run(...keys.map((key) => values[key]!)); +} + +const SECRETS = [ + "PASSWORD-HASH-1", + "PASSWORD-SALT-1", + "TOKEN-HASH-1", + "TUNNEL-ID-1", + "DNS-ID-1", + "REMOTE-KEY-1", + "48123", +]; + +function user( + sqlite: DatabaseSync, + id: string, + login: string, + ageDays: number, + extra: Values = {}, +) { + insert(sqlite, "users", { + id, + github_id: 1000 + Number(id.slice(1)), + login, + created_at: NOW - ageDays * DAY, + ...extra, + }); +} + +function machine(sqlite: DatabaseSync, id: string, userId: string, extra: Values = {}) { + insert(sqlite, "machines", { + id, + user_id: userId, + name: `${id}-laptop`, + status: "active", + ingress_port: 48123, + created_at: NOW - 30 * DAY, + ...extra, + }); +} + +let urlCount = 0; +function url(sqlite: DatabaseSync, userId: string, extra: Values = {}) { + urlCount++; + insert(sqlite, "public_urls", { + id: `url-${String(urlCount).padStart(3, "0")}`, + user_id: userId, + slug: `slug-${urlCount}`, + local_domain: `app${urlCount}.localify`, + wildcard: 0, + protected: 1, + password_hash: "PASSWORD-HASH-1", + password_salt: "PASSWORD-SALT-1", + password_version: 1, + created_at: NOW - 20 * DAY + urlCount, + ...extra, + }); +} + +function billing(sqlite: DatabaseSync, userId: string, extra: Values) { + insert(sqlite, "billing", { user_id: userId, revision: 1, refreshed_at: NOW - DAY, ...extra }); +} + +/** + * alice: team override, 8 of 10 URLs (one awaiting its reconcile); + * bob: Pro active, both serving slots used, a takedown; carol: an override + * ending in 10 days; dave: banned, and past_due; erin: trialing with + * add-ons; frank: no plan, one suspended URL, a revoked machine. + */ +function seed(sqlite: DatabaseSync): void { + urlCount = 0; + user(sqlite, "u1", "alice", 100); + user(sqlite, "u2", "bob", 3); + user(sqlite, "u3", "carol", 10); + user(sqlite, "u4", "dave", 40, { banned_at: NOW - 2 * DAY, banned_reason: "phishing" }); + user(sqlite, "u5", "erin", 20); + user(sqlite, "u6", "frank", 5); + + insert(sqlite, "plan_overrides", { + user_id: "u1", + serving_machines: 5, + public_urls: 10, + remote_access: 1, + reason: "team", + expires_at: null, + created_at: NOW - 90 * DAY, + }); + insert(sqlite, "plan_overrides", { + user_id: "u3", + serving_machines: 1, + public_urls: 5, + remote_access: 0, + reason: "beta", + expires_at: NOW + 10 * DAY, + created_at: NOW - 9 * DAY, + }); + billing(sqlite, "u2", { + pro_status: "active", + pro_interval: "month", + current_period_end: NOW + 20 * DAY, + }); + billing(sqlite, "u4", { pro_status: "past_due", pro_interval: "year", past_due_at: NOW - DAY }); + const grant = (id: string, kind: string, units: number) => ({ + id, + kind, + units, + status: "active", + cancel_at_period_end: false, + current_period_end: NOW + 20 * DAY, + trial_end: null, + ends_at: null, + ended_at: null, + past_due_at: null, + }); + billing(sqlite, "u5", { + pro_status: "trialing", + pro_interval: "month", + trial_end: NOW + 4 * DAY, + current_period_end: NOW + 4 * DAY, + addon_grants: JSON.stringify([grant("sub-a", "machine", 2), grant("sub-b", "urls", 1)]), + }); + + machine(sqlite, "m1", "u1", { + tunnel_state: "ready", + tunnel_id: "TUNNEL-ID-1", + dns_record_id: "DNS-ID-1", + tunnel_ready_at: NOW - 2 * 60 * 60 * 1000, + remote_key: "REMOTE-KEY-1", + remote_key_at: NOW - 3 * DAY, + }); + machine(sqlite, "m2", "u1", { name: `` }); + machine(sqlite, "m3", "u2", { tunnel_state: "ready" }); + machine(sqlite, "m4", "u2", { tunnel_state: "provisioning" }); + machine(sqlite, "m5", "u6", { status: "revoked", revoked_at: NOW - DAY }); + insert(sqlite, "tokens", { + hash: "TOKEN-HASH-1", + user_id: "u1", + machine_id: "m1", + created_at: NOW - DAY, + }); + + for (let i = 0; i < 8; i++) + url(sqlite, "u1", { machine_id: "m1", suspended_at: i === 7 ? NOW - DAY : null }); + url(sqlite, "u1", { deleted_at: NOW - DAY }); + url(sqlite, "u2", { machine_id: "m3", wildcard: 1 }); + url(sqlite, "u2", { taken_down_at: NOW - DAY, taken_down_reason: "malware" }); + url(sqlite, "u6", { machine_id: "m5" }); + + insert(sqlite, "webhook_events", { + id: "evt-1", + type: "subscription.active", + user_id: "u2", + received_at: NOW - 60 * 60 * 1000, + }); +} + +function sqliteDb(sqlite: DatabaseSync): ReadDb { + return readOnly(async (statements) => + statements.map((sql) => + sqlite + .prepare(sql) + .all() + .map((row) => ({ ...row })), + ), + ); +} + +let sqlite: DatabaseSync; +let db: ReadDb; + +beforeEach(() => { + sqlite = createTestDb().sqlite; + seed(sqlite); + db = sqliteDb(sqlite); +}); + +async function dashboard(): Promise { + return buildDashboard(await readRaw(db), NOW); +} + +describe("buildDashboard", () => { + it("counts the headline numbers", async () => { + const d = await dashboard(); + expect(d.totals).toEqual({ + users: 6, + newLast7Days: 2, + newLast30Days: 4, + activeMachines: 4, + servingMachines: 3, + liveUrls: 10, + servingUrls: 8, + banned: 1, + takedowns: 1, + }); + expect(d.statuses).toEqual({ + override: 2, + trialing: 1, + active: 1, + past_due: 1, + canceling: 0, + none: 1, + }); + expect(d.addonUnits).toEqual({ machines: 2, urlPacks: 1 }); + }); + + it("counts sign-ups per week up to now's week", async () => { + const d = await dashboard(); + expect(d.signupsByWeek.reduce((sum, week) => sum + week.count, 0)).toBe(6); + expect(d.signupsByWeek[0]!.weekStart).toBe(weekStart(NOW - 100 * DAY)); + expect(d.signupsByWeek.at(-1)!.weekStart).toBe(weekStart(NOW)); + expect(new Date(weekStart(NOW)).getUTCDay()).toBe(1); + }); + + it("lists what needs attention, most urgent first", async () => { + const d = await dashboard(); + expect(d.attention.map(({ login, kind, detail }) => [login, kind, detail])).toEqual([ + ["dave", "banned", "phishing"], + ["dave", "past_due", "Pro past_due"], + ["carol", "override_expiring", `override "beta" ends in 10 days`], + ["alice", "urls", "8 of 10 URLs"], + ["bob", "machines", "2 of 2 serving machines"], + ]); + }); + + it("gives each account its plan, limits and URLs, through the Worker's rules", async () => { + const d = await dashboard(); + const byLogin = Object.fromEntries(d.users.map((u) => [u.login, u])); + expect(d.users.map((u) => u.login)).toEqual(["bob", "frank", "carol", "erin", "dave", "alice"]); + + const alice = byLogin.alice!; + expect(alice.status).toBe("override"); + expect(alice.override).toMatchObject({ reason: "team", expiresAt: null, expired: false }); + expect(alice.entitlement).toEqual({ servingMachines: 5, publicUrls: 10, remoteAccess: true }); + expect([alice.servingSlots, alice.signedIn, alice.signedInCap]).toEqual([1, 2, 13]); + expect(alice.urls.map((u) => u.state)).toEqual([...Array(7).fill("serving"), "pending"]); + expect(alice.machines[0]).toMatchObject({ name: "m1-laptop", serving: true, linked: true }); + expect(alice.lastActivityAt).toBe(NOW - 2 * 60 * 60 * 1000); + + const bob = byLogin.bob!; + expect(bob.status).toBe("active"); + expect(bob.entitlement.servingMachines).toBe(2); + expect(bob.urls.map((u) => [u.state, u.machineName])).toEqual([ + ["serving", "m3-laptop"], + ["taken_down", null], + ]); + expect(bob.lastActivityAt).toBe(NOW - 60 * 60 * 1000); + + const dave = byLogin.dave!; + expect(dave.status).toBe("past_due"); + expect(dave.entitlement).toEqual({ servingMachines: 0, publicUrls: 0, remoteAccess: false }); + + expect(byLogin.erin!.entitlement).toEqual({ + servingMachines: 4, + publicUrls: 20, + remoteAccess: true, + }); + expect(byLogin.frank!.urls.map((u) => [u.state, u.machineName])).toEqual([ + ["suspended", "m5-laptop"], + ]); + expect(byLogin.frank!.signedIn).toBe(0); + }); + + it("shows an expired override as such, with the plan behind it", () => { + const later = NOW + 11 * DAY; + return readRaw(db).then((raw) => { + const carol = buildDashboard(raw, later).users.find((u) => u.login === "carol")!; + expect(carol.status).toBe("none"); + expect(carol.override).toMatchObject({ reason: "beta", expired: true }); + }); + }); + + it("handles an empty database", () => { + const empty = buildDashboard( + { accounts: [], users: [], overrides: [], billing: [], machines: [], urls: [], activity: [] }, + NOW, + ); + expect(empty.totals.users).toBe(0); + expect(empty.signupsByWeek).toEqual([]); + expect(signupChart(empty.signupsByWeek)).toContain("No sign-ups yet"); + }); +}); + +describe("cachedLoader", () => { + it("reads once per 30 seconds, and again on a refresh after 5", async () => { + let now = NOW; + const run = vi.fn(db); + const load = cachedLoader(run, () => now); + await Promise.all([load(false), load(false)]); + expect(run).toHaveBeenCalledTimes(1); + now += MIN_RELOAD_MS - 1; + await load(true); + expect(run).toHaveBeenCalledTimes(1); + now += 1; + await load(true); + expect(run).toHaveBeenCalledTimes(2); + now += CACHE_MS - 1; + await load(false); + expect(run).toHaveBeenCalledTimes(2); + now += 1; + await load(false); + expect(run).toHaveBeenCalledTimes(3); + }); + + it("keeps no failed read", async () => { + const run = vi.fn().mockRejectedValueOnce(new Error("D1 down")).mockImplementation(db); + const load = cachedLoader(run, () => NOW); + await expect(load(false)).rejects.toThrow("D1 down"); + await expect(load(false)).resolves.toMatchObject({ totals: { users: 6 } }); + }); +}); + +describe("allowedHost", () => { + it.each([ + ["dashboard.cloud.localify", true], + ["dashboard.cloud.localify:443", true], + ["127.0.0.1:41234", true], + ["localhost", true], + ["evil.example", false], + ["localify.evil.example", false], + ["dashboard.localify.fyi", false], + [undefined, false], + ])("%s: %s", (host, allowed) => { + expect(allowedHost(host)).toBe(allowed); + }); +}); + +describe("routes", () => { + let server: Server; + let port: number; + const log = vi.spyOn(console, "error"); + + beforeEach(async () => { + log.mockImplementation(() => {}); + const handler = createHandler( + cachedLoader(db, () => NOW), + { source: "Local D1", clock: () => NOW }, + ); + server = createServer((req, res) => void handler(req, res)); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + port = (server.address() as AddressInfo).port; + }); + + afterEach(async () => { + await new Promise((resolve) => server.close(resolve)); + log.mockReset(); + }); + + function get( + path: string, + { method = "GET", host = "dashboard.cloud.localify" } = {}, + ): Promise<{ status: number; headers: Record; body: string }> { + return new Promise((resolve, reject) => { + const req = httpRequest( + { host: "127.0.0.1", port, path, method, headers: { host } }, + (res) => { + let body = ""; + res.setEncoding("utf8"); + res.on("data", (chunk) => (body += chunk)); + res.on("end", () => resolve({ status: res.statusCode!, headers: res.headers, body })); + }, + ); + req.on("error", reject); + req.end(); + }); + } + + it("serves the overview, with no secret in it", async () => { + const response = await get("/"); + expect(response.status).toBe(200); + expect(response.headers["cache-control"]).toBe("no-store"); + expect(response.headers["content-security-policy"]).toContain("default-src 'none'"); + for (const login of ["alice", "bob", "carol", "dave", "erin", "frank"]) { + expect(response.body).toContain(login); + } + expect(response.body).toContain("Needs attention"); + expect(response.body).toContain(" { + const response = await get("/users/u1"); + expect(response.status).toBe(200); + expect(response.body).toContain("slug-1"); + expect(response.body).toContain("m1-laptop"); + expect(response.body).toContain("Suspended until the next reconcile"); + expect(response.body).not.toContain("")); + for (const secret of SECRETS) expect(response.body).not.toContain(secret); + }); + + it("answers an unknown account or page with 404", async () => { + expect((await get("/users/nobody")).status).toBe(404); + expect((await get("/users/%E0%A4%A")).status).toBe(404); + expect((await get("/admin")).status).toBe(404); + }); + + it("refuses anything but GET and HEAD", async () => { + for (const method of ["POST", "PUT", "DELETE", "PATCH"]) { + const response = await get("/", { method }); + expect(response.status).toBe(405); + expect(response.headers.allow).toBe("GET, HEAD"); + } + expect((await get("/", { method: "HEAD" })).status).toBe(200); + }); + + it("refuses a host that is not Localify's or loopback", async () => { + const response = await get("/", { host: "evil.example" }); + expect(response.status).toBe(421); + expect(response.body).not.toContain("alice"); + }); + + it("serves a failed read as 503 without its error", async () => { + const handler = createHandler( + async () => { + throw new Error("wrangler failed: TOKEN-HASH-1"); + }, + { source: "Production D1", clock: () => NOW }, + ); + const failing = createServer((req, res) => void handler(req, res)); + await new Promise((resolve) => failing.listen(0, "127.0.0.1", resolve)); + const previous = port; + port = (failing.address() as AddressInfo).port; + const response = await get("/"); + port = previous; + await new Promise((resolve) => failing.close(resolve)); + expect(response.status).toBe(503); + expect(response.body).not.toContain("TOKEN-HASH-1"); + expect(log).toHaveBeenCalled(); + }); +}); + +describe("wranglerOutputAsync", () => { + const original = process.env.PATH; + let dir: string; + + beforeEach(async () => { + const { mkdtempSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + dir = mkdtempSync(join(tmpdir(), "fake-wrangler-")); + // A wrangler that prints its first argument, or stalls when it is `stall`. + writeFileSync( + join(dir, "wrangler"), + '#!/bin/sh\nif [ "$1" = stall ]; then exec sleep 30; fi\necho "$1"\n', + { mode: 0o755 }, + ); + process.env.PATH = `${dir}:${original}`; + }); + + afterEach(async () => { + process.env.PATH = original; + const { rmSync } = await import("node:fs"); + rmSync(dir, { recursive: true, force: true }); + }); + + it("returns what wrangler printed", async () => { + const { wranglerOutputAsync } = await import("../scripts/infisical.mjs"); + expect(await wranglerOutputAsync({}, ["hello"])).toBe("hello\n"); + }); + + it("kills a stalled wrangler past its deadline, without blocking the event loop", async () => { + const { wranglerOutputAsync } = await import("../scripts/infisical.mjs"); + let ticks = 0; + const timer = setInterval(() => ticks++, 20); + const started = Date.now(); + await expect(wranglerOutputAsync({}, ["stall"], { timeoutMs: 300 })).rejects.toThrow( + /stopped by SIGKILL/, + ); + clearInterval(timer); + expect(Date.now() - started).toBeLessThan(5_000); + expect(ticks).toBeGreaterThan(3); + }); + + it("kills wrangler when the signal aborts", async () => { + const { wranglerOutputAsync } = await import("../scripts/infisical.mjs"); + const controller = new AbortController(); + const read = wranglerOutputAsync({}, ["stall"], { signal: controller.signal }); + setTimeout(() => controller.abort(), 100); + await expect(read).rejects.toThrow(); + }); +}); diff --git a/apps/cloud/tsconfig.json b/apps/cloud/tsconfig.json index 558e33e..e8d264c 100644 --- a/apps/cloud/tsconfig.json +++ b/apps/cloud/tsconfig.json @@ -13,5 +13,5 @@ "skipLibCheck": true, "types": [] }, - "include": ["src", "test", "scripts/admin.ts", "worker-configuration.d.ts", "vitest.config.ts"] + "include": ["src", "test", "scripts/admin.ts", "scripts/dashboard.ts", "scripts/dashboard", "worker-configuration.d.ts", "vitest.config.ts"] } diff --git a/docs/public-urls.md b/docs/public-urls.md index 63383d6..72b0ea9 100644 --- a/docs/public-urls.md +++ b/docs/public-urls.md @@ -481,6 +481,8 @@ Refunds are not automated. A duplicate takes a checkout opened from an old link, A login is the one GitHub gave at the last sign-in, so two accounts can share one; `id:` names either of them. +`pnpm cloud:dashboard` shows every account at once, served on the operator's machine. It only reads: its database layer sends nothing but `SELECT` statements, and it has no action to take ([apps/cloud/README.md](../apps/cloud/README.md), "Dashboard"). + Reports arrive at `abuse@localify.dev`, linked from every page the Worker serves. ### Public traffic diff --git a/package.json b/package.json index ceb4f90..4e31a75 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "cloud:migrate:local": "pnpm --filter @localify/cloud run migrate:local", "cloud:deploy": "pnpm --filter @localify/cloud run deploy", "cloud:admin": "pnpm --filter @localify/cloud run admin", + "cloud:dashboard": "pnpm --filter @localify/cloud run dashboard", "desktop:prepare-sidecar": "node scripts/prepare-tauri-sidecar.mjs --release", "check-version-sync": "node scripts/check-version-sync.mjs", "desktop:postprocess-macos-bundles": "bash scripts/postprocess-macos-bundles.sh",