Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions apps/cloud/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.<project-id>.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.<project-id>.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.
3 changes: 2 additions & 1 deletion apps/cloud/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
55 changes: 55 additions & 0 deletions apps/cloud/scripts/dashboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/// <reference types="node" />
// `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();
});
}
96 changes: 96 additions & 0 deletions apps/cloud/scripts/dashboard/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/// <reference types="node" />
// 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<string, unknown>;
/** Runs SELECT statements, in order, and returns the rows of each one. */
export type ReadDb = (statements: string[]) => Promise<Row[][]>;

/** 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<string, string | undefined> = {};
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 ?? []);
});
}
Loading
Loading