rizolang 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +399 -2
  3. package/build/src/ast.d.ts +133 -0
  4. package/build/src/ast.js +4 -0
  5. package/build/src/ast.js.map +1 -0
  6. package/build/src/bin.d.ts +2 -0
  7. package/build/src/bin.js +8 -0
  8. package/build/src/bin.js.map +1 -0
  9. package/build/src/check-api.d.ts +97 -0
  10. package/build/src/check-api.js +506 -0
  11. package/build/src/check-api.js.map +1 -0
  12. package/build/src/checker.d.ts +53 -0
  13. package/build/src/checker.js +235 -0
  14. package/build/src/checker.js.map +1 -0
  15. package/build/src/cli.d.ts +11 -0
  16. package/build/src/cli.js +94 -0
  17. package/build/src/cli.js.map +1 -0
  18. package/build/src/compiler.d.ts +36 -0
  19. package/build/src/compiler.js +61 -0
  20. package/build/src/compiler.js.map +1 -0
  21. package/build/src/diagnostics.d.ts +35 -0
  22. package/build/src/diagnostics.js +69 -0
  23. package/build/src/diagnostics.js.map +1 -0
  24. package/build/src/emit/routes.d.ts +20 -0
  25. package/build/src/emit/routes.js +246 -0
  26. package/build/src/emit/routes.js.map +1 -0
  27. package/build/src/emit/sql.d.ts +12 -0
  28. package/build/src/emit/sql.js +83 -0
  29. package/build/src/emit/sql.js.map +1 -0
  30. package/build/src/emit/typescript.d.ts +13 -0
  31. package/build/src/emit/typescript.js +74 -0
  32. package/build/src/emit/typescript.js.map +1 -0
  33. package/build/src/lexer.d.ts +17 -0
  34. package/build/src/lexer.js +124 -0
  35. package/build/src/lexer.js.map +1 -0
  36. package/build/src/parser.d.ts +17 -0
  37. package/build/src/parser.js +399 -0
  38. package/build/src/parser.js.map +1 -0
  39. package/build/src/types.d.ts +42 -0
  40. package/build/src/types.js +77 -0
  41. package/build/src/types.js.map +1 -0
  42. package/build/src/version.d.ts +2 -0
  43. package/build/src/version.js +3 -0
  44. package/build/src/version.js.map +1 -0
  45. package/docs/SPEC-COMPACT.md +148 -0
  46. package/docs/SPEC.md +597 -0
  47. package/package.json +48 -4
  48. package/runtime/password.ts +58 -0
  49. package/runtime/ratelimit.ts +53 -0
  50. package/runtime/server.ts +449 -0
  51. package/runtime/session.ts +48 -0
  52. package/runtime/types.ts +76 -0
  53. package/runtime/validate.ts +133 -0
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Rizo Lang runtime: password hashing with scrypt (built into Node.js).
3
+ *
4
+ * Parameters follow the OWASP Password Storage Cheat Sheet (N=2^15, r=8, p=3,
5
+ * about 32 MiB of memory per hash). Stored format:
6
+ * scrypt$<log2 N>$<r>$<p>$<salt base64url>$<hash base64url>
7
+ */
8
+ import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
9
+
10
+ const LOG_N = 15;
11
+ const R = 8;
12
+ const P = 3;
13
+ const KEY_LENGTH = 64;
14
+ const SALT_BYTES = 16;
15
+
16
+ function derive(password: string, salt: Buffer, logN: number, r: number, p: number): Promise<Buffer> {
17
+ const N = 2 ** logN;
18
+ return new Promise((resolve, reject) => {
19
+ // maxmem must exceed 128 * N * r bytes.
20
+ scrypt(password.normalize("NFC"), salt, KEY_LENGTH, { N, r, p, maxmem: 256 * N * r }, (err, key) => {
21
+ if (err) reject(err);
22
+ else resolve(key);
23
+ });
24
+ });
25
+ }
26
+
27
+ export async function hashPassword(password: string): Promise<string> {
28
+ const salt = randomBytes(SALT_BYTES);
29
+ const key = await derive(password, salt, LOG_N, R, P);
30
+ return `scrypt$${LOG_N}$${R}$${P}$${salt.toString("base64url")}$${key.toString("base64url")}`;
31
+ }
32
+
33
+ /** Constant-time check. Returns false (never throws) for malformed hashes. */
34
+ export async function verifyPassword(password: string, stored: string): Promise<boolean> {
35
+ const parts = stored.split("$");
36
+ if (parts.length !== 6 || parts[0] !== "scrypt") return false;
37
+ const logN = Number(parts[1]);
38
+ const r = Number(parts[2]);
39
+ const p = Number(parts[3]);
40
+ // Bound the parameters so a tampered hash cannot make verification hang or exhaust memory.
41
+ if (!Number.isInteger(logN) || logN < 14 || logN > 20) return false;
42
+ if (!Number.isInteger(r) || r < 1 || r > 16 || !Number.isInteger(p) || p < 1 || p > 16) return false;
43
+ const salt = Buffer.from(parts[4] ?? "", "base64url");
44
+ const expected = Buffer.from(parts[5] ?? "", "base64url");
45
+ if (salt.length < SALT_BYTES || expected.length !== KEY_LENGTH) return false;
46
+ const actual = await derive(password, salt, logN, r, p);
47
+ return timingSafeEqual(actual, expected);
48
+ }
49
+
50
+ let dummy: Promise<string> | undefined;
51
+ /**
52
+ * A hash of a random password, used when a login names an unknown account,
53
+ * so that response time does not reveal whether the account exists.
54
+ */
55
+ export function dummyHash(): Promise<string> {
56
+ dummy ??= hashPassword(randomBytes(32).toString("base64url"));
57
+ return dummy;
58
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Rizo Lang runtime: fixed-window rate limiting for login and signup.
3
+ *
4
+ * Counts are kept in memory, per process. When running several server
5
+ * processes behind a load balancer, each process limits independently.
6
+ */
7
+
8
+ interface Window {
9
+ count: number;
10
+ resetAt: number;
11
+ }
12
+
13
+ /** Entries kept before expired windows are swept, to bound memory use. */
14
+ const SWEEP_AT = 10_000;
15
+
16
+ export class RateLimiter {
17
+ readonly #limit: number;
18
+ readonly #windowMs: number;
19
+ readonly #now: () => number;
20
+ readonly #windows = new Map<string, Window>();
21
+
22
+ constructor(limit: number, windowMs: number, now: () => number = Date.now) {
23
+ this.#limit = limit;
24
+ this.#windowMs = windowMs;
25
+ this.#now = now;
26
+ }
27
+
28
+ /** Seconds until `key` may try again, or 0 if it is not limited. */
29
+ retryAfter(key: string): number {
30
+ const w = this.#windows.get(key);
31
+ const now = this.#now();
32
+ if (w === undefined || w.resetAt <= now) return 0;
33
+ return w.count >= this.#limit ? Math.ceil((w.resetAt - now) / 1000) : 0;
34
+ }
35
+
36
+ /** Record one attempt for `key`. */
37
+ hit(key: string): void {
38
+ const now = this.#now();
39
+ if (this.#windows.size >= SWEEP_AT) {
40
+ for (const [k, w] of this.#windows) if (w.resetAt <= now) this.#windows.delete(k);
41
+ }
42
+ const w = this.#windows.get(key);
43
+ if (w === undefined || w.resetAt <= now) {
44
+ this.#windows.set(key, { count: 1, resetAt: now + this.#windowMs });
45
+ } else {
46
+ w.count++;
47
+ }
48
+ }
49
+
50
+ reset(key: string): void {
51
+ this.#windows.delete(key);
52
+ }
53
+ }
@@ -0,0 +1,449 @@
1
+ /**
2
+ * Rizo Lang runtime: the HTTP server.
3
+ *
4
+ * Request flow: security headers -> route match -> origin check -> session ->
5
+ * path parameters -> body validation -> password hashing -> parameterized
6
+ * query -> response with public fields only -> one log line.
7
+ *
8
+ * Logs contain the method, the route pattern (not the concrete URL), the
9
+ * status, the duration and a request id. Never bodies, cookies or values.
10
+ */
11
+ import { randomUUID } from "node:crypto";
12
+ import { type IncomingMessage, type ServerResponse, createServer } from "node:http";
13
+ import pg from "pg";
14
+ import { hashPassword, dummyHash, verifyPassword } from "./password.ts";
15
+ import { RateLimiter } from "./ratelimit.ts";
16
+ import { SESSION_SECONDS, SQL, clearedCookie, hashToken, newToken, readToken, sessionCookie } from "./session.ts";
17
+ import type { App, FieldSpec, Route, ValueSource } from "./types.ts";
18
+ import { validateBody, validatePathParam, validateValue } from "./validate.ts";
19
+
20
+ export interface QueryResult {
21
+ readonly rows: readonly Record<string, unknown>[];
22
+ readonly rowCount: number | null;
23
+ }
24
+
25
+ /** The database connection. In production this is a `pg.Pool`. */
26
+ export interface Db {
27
+ query(sql: string, values: unknown[]): Promise<QueryResult>;
28
+ }
29
+
30
+ export interface ServerOptions {
31
+ readonly db: Db;
32
+ /** Where log lines go. Defaults to stdout. */
33
+ readonly log?: (line: string) => void;
34
+ /** Extra origins allowed to send state-changing requests, e.g. "https://app.example.com". */
35
+ readonly allowedOrigins?: readonly string[];
36
+ /** Mark the session cookie Secure. Only turn off for local development over http. */
37
+ readonly secureCookies?: boolean;
38
+ /** Use the first X-Forwarded-For address as the client IP (only behind a trusted proxy). */
39
+ readonly trustProxy?: boolean;
40
+ readonly now?: () => number;
41
+ }
42
+
43
+ /** Largest accepted request body. */
44
+ export const MAX_BODY_BYTES = 1024 * 1024;
45
+
46
+ const SECURITY_HEADERS: Readonly<Record<string, string>> = {
47
+ "Content-Type": "application/json; charset=utf-8",
48
+ "Cache-Control": "no-store",
49
+ "X-Content-Type-Options": "nosniff",
50
+ "X-Frame-Options": "DENY",
51
+ "Referrer-Policy": "no-referrer",
52
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
53
+ "Cross-Origin-Resource-Policy": "same-origin",
54
+ };
55
+
56
+ /** An error that becomes an HTTP response. `message` is shown to the client. */
57
+ class HttpError extends Error {
58
+ readonly status: number;
59
+ readonly code: string;
60
+ readonly field: string | undefined;
61
+ readonly headers: Readonly<Record<string, string>>;
62
+ constructor(status: number, code: string, message: string, field?: string, headers: Record<string, string> = {}) {
63
+ super(message);
64
+ this.status = status;
65
+ this.code = code;
66
+ this.field = field;
67
+ this.headers = headers;
68
+ }
69
+ }
70
+
71
+ interface Matched {
72
+ readonly route: Route;
73
+ readonly params: ReadonlyMap<string, unknown>;
74
+ }
75
+
76
+ interface AuthRoutes {
77
+ readonly method: string;
78
+ readonly path: string;
79
+ }
80
+ const AUTH_ROUTES: readonly AuthRoutes[] = [
81
+ { method: "POST", path: "/auth/signup" },
82
+ { method: "POST", path: "/auth/login" },
83
+ { method: "POST", path: "/auth/logout" },
84
+ { method: "GET", path: "/auth/me" },
85
+ ];
86
+
87
+ /** Copy only the listed keys. Responses never rely on the query alone to hide data. */
88
+ function pick(row: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {
89
+ const out: Record<string, unknown> = {};
90
+ for (const k of keys) if (Object.hasOwn(row, k)) out[k] = row[k];
91
+ return out;
92
+ }
93
+
94
+ const article = (word: string): string => (/^[AEIOU]/i.test(word) ? "An" : "A");
95
+ const camel = (snake: string): string => snake.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());
96
+
97
+ export function createRequestHandler(app: App, options: ServerOptions): (req: IncomingMessage, res: ServerResponse) => Promise<void> {
98
+ const { db } = options;
99
+ const log = options.log ?? ((line: string) => process.stdout.write(`${line}\n`));
100
+ const secure = options.secureCookies ?? true;
101
+ const now = options.now ?? Date.now;
102
+ const allowedOrigins = new Set(options.allowedOrigins ?? []);
103
+
104
+ const loginByIp = new RateLimiter(20, 15 * 60_000, now);
105
+ const loginByAccount = new RateLimiter(5, 15 * 60_000, now);
106
+ const signupByIp = new RateLimiter(10, 60 * 60_000, now);
107
+
108
+ return async (req, res) => {
109
+ const started = now();
110
+ const requestId = randomUUID();
111
+ const method = req.method ?? "GET";
112
+ let pattern = "-";
113
+ let status = 500;
114
+ try {
115
+ const url = new URL(req.url ?? "/", "http://localhost");
116
+ const auth = app.auth;
117
+ if (auth !== null && url.pathname.startsWith("/auth/")) {
118
+ pattern = url.pathname;
119
+ status = await handleAuth(req, res, url.pathname, method);
120
+ } else {
121
+ const { route, params } = match(method, url.pathname);
122
+ pattern = route.pattern;
123
+ status = await handleRoute(req, res, route, params);
124
+ }
125
+ } catch (e) {
126
+ if (e instanceof HttpError) {
127
+ status = e.status;
128
+ send(res, e.status, { error: { code: e.code, message: e.message, ...(e.field ? { field: e.field } : {}) } }, e.headers);
129
+ } else {
130
+ status = 500;
131
+ log(`error id=${requestId} ${describeError(e)}`);
132
+ if (!res.headersSent) {
133
+ send(res, 500, { error: { code: "internal_error", message: `Something went wrong. Request id: ${requestId}.` } });
134
+ } else {
135
+ res.destroy();
136
+ }
137
+ }
138
+ } finally {
139
+ log(`${method} ${pattern} ${status} ${now() - started}ms id=${requestId}`);
140
+ }
141
+ };
142
+
143
+ // -------------------------------------------------------------- routing
144
+
145
+ function match(method: string, pathname: string): Matched {
146
+ let parts: string[];
147
+ try {
148
+ parts = pathname === "/" ? [] : pathname.slice(1).split("/").map(decodeURIComponent);
149
+ } catch {
150
+ throw new HttpError(400, "bad_path", "The URL path is not valid.");
151
+ }
152
+ let best: { route: Route; score: number } | undefined;
153
+ const allow = new Set<string>();
154
+ for (const route of app.routes) {
155
+ if (route.path.length !== parts.length) continue;
156
+ let score = 0;
157
+ let ok = true;
158
+ route.path.forEach((p, i) => {
159
+ if ("static" in p) {
160
+ if (p.static === parts[i]) score++;
161
+ else ok = false;
162
+ } else if ((parts[i] ?? "") === "") {
163
+ ok = false;
164
+ }
165
+ });
166
+ if (!ok) continue;
167
+ allow.add(route.method);
168
+ if (route.method === method && (best === undefined || score > best.score)) best = { route, score };
169
+ }
170
+ if (best === undefined) {
171
+ if (allow.size > 0) {
172
+ throw new HttpError(405, "method_not_allowed", `This path does not support ${method}.`, undefined, { Allow: [...allow].join(", ") });
173
+ }
174
+ throw new HttpError(404, "not_found", "No endpoint matches this path.");
175
+ }
176
+ const params = new Map<string, unknown>();
177
+ best.route.path.forEach((p, i) => {
178
+ if ("param" in p) {
179
+ const r = validatePathParam(p, parts[i] ?? "");
180
+ if ("error" in r) throw new HttpError(400, "invalid_parameter", r.error, p.param);
181
+ params.set(p.param, r.value);
182
+ }
183
+ });
184
+ return { route: best.route, params };
185
+ }
186
+
187
+ // ------------------------------------------------------------- requests
188
+
189
+ /** Reject cross-site state-changing requests (defense in depth on top of SameSite cookies). */
190
+ function checkOrigin(req: IncomingMessage, method: string): void {
191
+ if (method === "GET") return;
192
+ const origin = req.headers.origin;
193
+ if (origin === undefined) return;
194
+ if (allowedOrigins.has(origin)) return;
195
+ let host: string;
196
+ try {
197
+ host = new URL(origin).host;
198
+ } catch {
199
+ throw new HttpError(403, "forbidden_origin", "Requests from this origin are not allowed.");
200
+ }
201
+ if (host !== req.headers.host) throw new HttpError(403, "forbidden_origin", "Requests from this origin are not allowed.");
202
+ }
203
+
204
+ async function readJson(req: IncomingMessage): Promise<unknown> {
205
+ const type = (req.headers["content-type"] ?? "").split(";")[0]?.trim().toLowerCase();
206
+ if (type !== "application/json") {
207
+ throw new HttpError(415, "unsupported_media_type", 'Send the body as JSON with "Content-Type: application/json".');
208
+ }
209
+ const declared = Number(req.headers["content-length"] ?? "0");
210
+ if (declared > MAX_BODY_BYTES) throw new HttpError(413, "body_too_large", "The request body is too large.");
211
+ const chunks: Buffer[] = [];
212
+ let size = 0;
213
+ for await (const chunk of req) {
214
+ const buf = chunk as Buffer;
215
+ size += buf.length;
216
+ if (size > MAX_BODY_BYTES) throw new HttpError(413, "body_too_large", "The request body is too large.");
217
+ chunks.push(buf);
218
+ }
219
+ try {
220
+ return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown;
221
+ } catch {
222
+ throw new HttpError(400, "invalid_json", "The request body is not valid JSON.");
223
+ }
224
+ }
225
+
226
+ function hasBody(req: IncomingMessage): boolean {
227
+ return Number(req.headers["content-length"] ?? "0") > 0 || req.headers["transfer-encoding"] !== undefined;
228
+ }
229
+
230
+ async function body(req: IncomingMessage, specs: readonly FieldSpec[]): Promise<Map<string, unknown>> {
231
+ const v = validateBody(specs, await readJson(req));
232
+ if (!v.ok) throw new HttpError(400, "validation_failed", v.message, v.field || undefined);
233
+ const values = new Map(v.values);
234
+ for (const spec of specs) {
235
+ const value = values.get(spec.key);
236
+ if (spec.kind === "Password" && typeof value === "string") values.set(spec.key, await hashPassword(value));
237
+ }
238
+ return values;
239
+ }
240
+
241
+ async function currentUser(req: IncomingMessage): Promise<string | undefined> {
242
+ const token = readToken(req.headers.cookie);
243
+ if (token === undefined) return undefined;
244
+ const r = await db.query(SQL.lookup, [hashToken(token)]);
245
+ const id = r.rows[0]?.["user_id"];
246
+ return typeof id === "string" ? id : undefined;
247
+ }
248
+
249
+ async function startSession(res: ServerResponse, userId: string): Promise<void> {
250
+ const token = newToken();
251
+ await db.query(SQL.deleteExpired, [userId]);
252
+ await db.query(SQL.create, [hashToken(token), userId, SESSION_SECONDS]);
253
+ res.setHeader("Set-Cookie", sessionCookie(token, secure));
254
+ }
255
+
256
+ function clientIp(req: IncomingMessage): string {
257
+ if (options.trustProxy) {
258
+ const fwd = req.headers["x-forwarded-for"];
259
+ const first = (Array.isArray(fwd) ? fwd[0] : fwd)?.split(",")[0]?.trim();
260
+ if (first) return first;
261
+ }
262
+ return req.socket.remoteAddress ?? "unknown";
263
+ }
264
+
265
+ function values(sources: readonly ValueSource[], params: ReadonlyMap<string, unknown>, bodyValues: ReadonlyMap<string, unknown>, me: string | undefined): unknown[] {
266
+ return sources.map((s) => {
267
+ switch (s.from) {
268
+ case "path": return params.get(s.name);
269
+ case "me": return me;
270
+ case "body": return bodyValues.get(s.key) ?? null;
271
+ case "provided": return bodyValues.has(s.key);
272
+ case "const": return s.value;
273
+ }
274
+ });
275
+ }
276
+
277
+ async function run(sql: string, vals: unknown[], model: string): Promise<QueryResult> {
278
+ try {
279
+ return await db.query(sql, vals);
280
+ } catch (e) {
281
+ const err = e as { code?: string; detail?: string };
282
+ const column = /^Key \(([a-z0-9_]+)\)/.exec(err.detail ?? "")?.[1];
283
+ const field = column === undefined ? undefined : camel(column.replace(/_id$/, "").replace(/_hash$/, ""));
284
+ switch (err.code) {
285
+ case "23505":
286
+ throw new HttpError(409, "already_exists", `${article(model)} ${model} with this ${field ?? "value"} already exists.`, field);
287
+ case "23503":
288
+ throw sql.startsWith("DELETE")
289
+ ? new HttpError(409, "in_use", `This ${model} cannot be deleted because other records link to it.`)
290
+ : new HttpError(400, "invalid_link", `${field ?? "A linked record"} refers to a record that does not exist.`, field);
291
+ case "23514":
292
+ case "23502":
293
+ case "22P02":
294
+ case "22001":
295
+ throw new HttpError(400, "validation_failed", "A value is not valid.");
296
+ default:
297
+ throw e;
298
+ }
299
+ }
300
+ }
301
+
302
+ async function handleRoute(req: IncomingMessage, res: ServerResponse, route: Route, params: ReadonlyMap<string, unknown>): Promise<number> {
303
+ checkOrigin(req, route.method);
304
+ let me: string | undefined;
305
+ if (route.access === "login") {
306
+ me = await currentUser(req);
307
+ if (me === undefined) throw new HttpError(401, "login_required", "You need to log in.");
308
+ }
309
+ let bodyValues: ReadonlyMap<string, unknown> = new Map();
310
+ if (route.body === null) {
311
+ if (hasBody(req)) throw new HttpError(400, "unexpected_body", "This endpoint does not accept a request body.");
312
+ } else {
313
+ bodyValues = await body(req, route.body);
314
+ }
315
+ const r = await run(route.sql, values(route.values, params, bodyValues, me), route.model);
316
+ switch (route.result) {
317
+ case "list":
318
+ return send(res, 200, r.rows.map((row) => pick(row, route.publicKeys)));
319
+ case "created":
320
+ return send(res, 201, pick(r.rows[0] ?? {}, route.publicKeys));
321
+ case "one": {
322
+ const row = r.rows[0];
323
+ if (row === undefined) throw new HttpError(404, "not_found", `${route.model} not found.`);
324
+ return send(res, 200, pick(row, route.publicKeys));
325
+ }
326
+ case "none":
327
+ if ((r.rowCount ?? 0) === 0) throw new HttpError(404, "not_found", `${route.model} not found.`);
328
+ res.writeHead(204, SECURITY_HEADERS).end();
329
+ return 204;
330
+ }
331
+ }
332
+
333
+ // ----------------------------------------------------------------- auth
334
+
335
+ async function handleAuth(req: IncomingMessage, res: ServerResponse, path: string, method: string): Promise<number> {
336
+ const auth = app.auth;
337
+ if (auth === null) throw new HttpError(404, "not_found", "No endpoint matches this path.");
338
+ const known = AUTH_ROUTES.find((r) => r.path === path);
339
+ if (known === undefined) throw new HttpError(404, "not_found", "No endpoint matches this path.");
340
+ if (known.method !== method) {
341
+ throw new HttpError(405, "method_not_allowed", `This path does not support ${method}.`, undefined, { Allow: known.method });
342
+ }
343
+ checkOrigin(req, method);
344
+ const ip = clientIp(req);
345
+
346
+ if (path === "/auth/signup") {
347
+ const wait = signupByIp.retryAfter(ip);
348
+ if (wait > 0) throw new HttpError(429, "too_many_requests", "Too many signups. Try again later.", undefined, { "Retry-After": String(wait) });
349
+ signupByIp.hit(ip);
350
+ const bodyValues = await body(req, auth.signup.body);
351
+ const r = await run(auth.signup.sql, values(auth.signup.values, new Map(), bodyValues, undefined), auth.model);
352
+ const row = r.rows[0] ?? {};
353
+ await startSession(res, String(row["id"]));
354
+ return send(res, 201, pick(row, auth.publicKeys));
355
+ }
356
+
357
+ if (path === "/auth/login") {
358
+ const raw = await readJson(req);
359
+ const v = validateBody(
360
+ [
361
+ { key: auth.loginKey, kind: "Text", required: true, nullable: false, max: 254 },
362
+ { key: auth.passwordKey, kind: "Text", required: true, nullable: false, max: 128 },
363
+ ],
364
+ raw,
365
+ );
366
+ if (!v.ok) throw new HttpError(400, "validation_failed", v.message, v.field || undefined);
367
+ const email = validateValue({ key: auth.loginKey, kind: "Email" }, v.values.get(auth.loginKey));
368
+ const password = String(v.values.get(auth.passwordKey));
369
+ const account = "value" in email ? String(email.value) : "";
370
+ const wait = Math.max(loginByIp.retryAfter(ip), loginByAccount.retryAfter(account));
371
+ if (wait > 0) throw new HttpError(429, "too_many_requests", "Too many login attempts. Try again later.", undefined, { "Retry-After": String(wait) });
372
+
373
+ const r = account === "" ? { rows: [], rowCount: 0 } : await db.query(auth.loginSql, [account]);
374
+ const row = r.rows[0];
375
+ const hash = typeof row?.["hash"] === "string" ? row["hash"] : await dummyHash();
376
+ const valid = await verifyPassword(password, hash);
377
+ if (!valid || row === undefined) {
378
+ loginByIp.hit(ip);
379
+ loginByAccount.hit(account);
380
+ throw new HttpError(401, "invalid_credentials", `The ${auth.loginKey} or ${auth.passwordKey} is incorrect.`);
381
+ }
382
+ loginByAccount.reset(account);
383
+ const userId = String(row["id"]);
384
+ await startSession(res, userId);
385
+ const me = await db.query(auth.meSql, [userId]);
386
+ return send(res, 200, pick(me.rows[0] ?? {}, auth.publicKeys));
387
+ }
388
+
389
+ if (path === "/auth/logout") {
390
+ const token = readToken(req.headers.cookie);
391
+ if (token !== undefined) await db.query(SQL.delete, [hashToken(token)]);
392
+ res.setHeader("Set-Cookie", clearedCookie(secure));
393
+ res.writeHead(204, SECURITY_HEADERS).end();
394
+ return 204;
395
+ }
396
+
397
+ // GET /auth/me
398
+ const userId = await currentUser(req);
399
+ if (userId === undefined) throw new HttpError(401, "login_required", "You need to log in.");
400
+ const r = await db.query(auth.meSql, [userId]);
401
+ const row = r.rows[0];
402
+ if (row === undefined) throw new HttpError(401, "login_required", "You need to log in.");
403
+ return send(res, 200, pick(row, auth.publicKeys));
404
+ }
405
+ }
406
+
407
+ /** One line for the log: the error's code or name and message. Never request data. */
408
+ function describeError(e: unknown): string {
409
+ if (!(e instanceof Error)) return "non-error thrown";
410
+ const code = (e as { code?: unknown }).code;
411
+ return `${typeof code === "string" ? `${code} ` : ""}${e.name}: ${e.message}`;
412
+ }
413
+
414
+ function send(res: ServerResponse, status: number, payload: unknown, headers: Readonly<Record<string, string>> = {}): number {
415
+ res.writeHead(status, { ...SECURITY_HEADERS, ...headers });
416
+ res.end(JSON.stringify(payload));
417
+ return status;
418
+ }
419
+
420
+ /** Start the server. Configuration comes from environment variables. */
421
+ export function startServer(app: App): void {
422
+ const url = process.env["DATABASE_URL"];
423
+ if (url === undefined || url === "") {
424
+ process.stderr.write(
425
+ "rizo: DATABASE_URL is not set.\n fix: Start the server with DATABASE_URL=postgres://user:password@localhost:5432/app node server.ts\n",
426
+ );
427
+ process.exit(1);
428
+ }
429
+ const insecure = process.env["RIZO_DEV_INSECURE_COOKIES"] === "1";
430
+ if (insecure) process.stderr.write("rizo: WARNING: session cookies are not marked Secure. Use this only for local development over http.\n");
431
+ const pool = new pg.Pool({ connectionString: url, max: Number(process.env["RIZO_DB_POOL_SIZE"] ?? "10") });
432
+ const handler = createRequestHandler(app, {
433
+ db: { query: (sql, vals) => pool.query(sql, vals) },
434
+ secureCookies: !insecure,
435
+ trustProxy: process.env["RIZO_TRUST_PROXY"] === "1",
436
+ allowedOrigins: (process.env["RIZO_ALLOWED_ORIGINS"] ?? "").split(",").map((s) => s.trim()).filter(Boolean),
437
+ });
438
+ const server = createServer((req, res) => void handler(req, res));
439
+ server.requestTimeout = 30_000;
440
+ server.headersTimeout = 10_000;
441
+ const port = Number(process.env["PORT"] ?? "3000");
442
+ const host = process.env["HOST"] ?? "127.0.0.1";
443
+ server.listen(port, host, () => process.stdout.write(`rizo: listening on http://${host}:${port}\n`));
444
+ const stop = (): void => {
445
+ server.close(() => void pool.end());
446
+ };
447
+ process.on("SIGTERM", stop);
448
+ process.on("SIGINT", stop);
449
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Rizo Lang runtime: login sessions.
3
+ *
4
+ * A session token is 32 random bytes sent to the browser in an HttpOnly,
5
+ * Secure, SameSite=Lax cookie. Only its SHA-256 hash is stored, so a leaked
6
+ * database does not leak usable sessions.
7
+ */
8
+ import { createHash, randomBytes } from "node:crypto";
9
+
10
+ export const COOKIE_NAME = "rizo_session";
11
+ export const SESSION_SECONDS = 7 * 24 * 60 * 60;
12
+ export const SESSIONS_TABLE = '"_rizo_sessions"';
13
+
14
+ export const SQL = {
15
+ create: `INSERT INTO ${SESSIONS_TABLE} ("token_hash", "user_id", "expires_at") VALUES ($1, $2, now() + make_interval(secs => $3))`,
16
+ lookup: `SELECT "user_id" FROM ${SESSIONS_TABLE} WHERE "token_hash" = $1 AND "expires_at" > now()`,
17
+ delete: `DELETE FROM ${SESSIONS_TABLE} WHERE "token_hash" = $1`,
18
+ deleteExpired: `DELETE FROM ${SESSIONS_TABLE} WHERE "user_id" = $1 AND "expires_at" <= now()`,
19
+ } as const;
20
+
21
+ export function newToken(): string {
22
+ return randomBytes(32).toString("base64url");
23
+ }
24
+
25
+ export function hashToken(token: string): string {
26
+ return createHash("sha256").update(token).digest("hex");
27
+ }
28
+
29
+ /** Read the session token from a Cookie header. Returns undefined if absent or malformed. */
30
+ export function readToken(cookieHeader: string | undefined): string | undefined {
31
+ if (cookieHeader === undefined) return undefined;
32
+ for (const part of cookieHeader.split(";")) {
33
+ const eq = part.indexOf("=");
34
+ if (eq === -1) continue;
35
+ if (part.slice(0, eq).trim() !== COOKIE_NAME) continue;
36
+ const value = part.slice(eq + 1).trim();
37
+ return /^[A-Za-z0-9_-]{43}$/.test(value) ? value : undefined;
38
+ }
39
+ return undefined;
40
+ }
41
+
42
+ export function sessionCookie(token: string, secure: boolean): string {
43
+ return `${COOKIE_NAME}=${token}; HttpOnly;${secure ? " Secure;" : ""} SameSite=Lax; Path=/; Max-Age=${SESSION_SECONDS}`;
44
+ }
45
+
46
+ export function clearedCookie(secure: boolean): string {
47
+ return `${COOKIE_NAME}=; HttpOnly;${secure ? " Secure;" : ""} SameSite=Lax; Path=/; Max-Age=0`;
48
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Rizo Lang runtime: shared types.
3
+ *
4
+ * The compiler generates `routes.ts` as plain data of type `App`. All SQL is
5
+ * written by the compiler at build time; the runtime never builds SQL from
6
+ * text. It only supplies values for $1, $2, ... parameters.
7
+ */
8
+
9
+ export type FieldKind = "Text" | "Number" | "Bool" | "Email" | "Password" | "Date" | "ID";
10
+
11
+ /** How to validate one JSON body field. */
12
+ export interface FieldSpec {
13
+ /** JSON key, e.g. "firstName". */
14
+ readonly key: string;
15
+ readonly kind: FieldKind;
16
+ /** The key must be present. */
17
+ readonly required: boolean;
18
+ /** The value may be null. */
19
+ readonly nullable: boolean;
20
+ /** Length in characters (Text, Email, Password) or value (Number). */
21
+ readonly min?: number;
22
+ readonly max?: number;
23
+ }
24
+
25
+ /** Where the value for one SQL parameter comes from. */
26
+ export type ValueSource =
27
+ | { readonly from: "path"; readonly name: string }
28
+ | { readonly from: "me" }
29
+ /** A validated body field. Password values are hashed before use. */
30
+ | { readonly from: "body"; readonly key: string }
31
+ /** true when the body contains `key` (used for partial updates). */
32
+ | { readonly from: "provided"; readonly key: string }
33
+ | { readonly from: "const"; readonly value: number | boolean };
34
+
35
+ export type PathPart =
36
+ | { readonly static: string }
37
+ | { readonly param: string; readonly kind: "ID" | "Number" | "Bool" | "Text" | "Email" };
38
+
39
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
40
+
41
+ export interface Route {
42
+ readonly method: HttpMethod;
43
+ /** Original path, used in logs (never the concrete URL, which may contain values). */
44
+ readonly pattern: string;
45
+ readonly path: readonly PathPart[];
46
+ readonly access: "public" | "login";
47
+ /** Accepted body fields, or null if the request must not have a body. */
48
+ readonly body: readonly FieldSpec[] | null;
49
+ readonly sql: string;
50
+ readonly values: readonly ValueSource[];
51
+ /** one: 200 with an object (404 if no row); list: 200 with an array; created: 201; none: 204 (404 if no row). */
52
+ readonly result: "one" | "list" | "created" | "none";
53
+ /** The only keys ever copied into a response. */
54
+ readonly publicKeys: readonly string[];
55
+ /** Model name, used in error messages such as "Post not found". */
56
+ readonly model: string;
57
+ }
58
+
59
+ export interface AuthSpec {
60
+ /** Name of the auth model, e.g. "User". */
61
+ readonly model: string;
62
+ readonly signup: { readonly body: readonly FieldSpec[]; readonly sql: string; readonly values: readonly ValueSource[] };
63
+ /** JSON keys of the login fields, e.g. "email" and "password". */
64
+ readonly loginKey: string;
65
+ readonly passwordKey: string;
66
+ /** `SELECT id, <hash column> AS hash FROM <users> WHERE <login column> = $1` */
67
+ readonly loginSql: string;
68
+ /** `SELECT <public columns> FROM <users> WHERE id = $1` */
69
+ readonly meSql: string;
70
+ readonly publicKeys: readonly string[];
71
+ }
72
+
73
+ export interface App {
74
+ readonly routes: readonly Route[];
75
+ readonly auth: AuthSpec | null;
76
+ }