rizolang 0.2.0 → 0.3.1
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.
- package/README.md +43 -12
- package/build/src/ast.d.ts +17 -2
- package/build/src/ast.js.map +1 -1
- package/build/src/check-api.d.ts +7 -0
- package/build/src/check-api.js +66 -8
- package/build/src/check-api.js.map +1 -1
- package/build/src/cli.d.ts +1 -0
- package/build/src/cli.js +81 -5
- package/build/src/cli.js.map +1 -1
- package/build/src/compiler.d.ts +2 -0
- package/build/src/compiler.js +2 -1
- package/build/src/compiler.js.map +1 -1
- package/build/src/emit/routes.d.ts +2 -0
- package/build/src/emit/routes.js +78 -8
- package/build/src/emit/routes.js.map +1 -1
- package/build/src/emit/sql.d.ts +3 -4
- package/build/src/emit/sql.js +13 -70
- package/build/src/emit/sql.js.map +1 -1
- package/build/src/emit/typescript.js +4 -1
- package/build/src/emit/typescript.js.map +1 -1
- package/build/src/migrations.d.ts +33 -0
- package/build/src/migrations.js +183 -0
- package/build/src/migrations.js.map +1 -0
- package/build/src/parser.js +40 -5
- package/build/src/parser.js.map +1 -1
- package/build/src/schema.d.ts +63 -0
- package/build/src/schema.js +151 -0
- package/build/src/schema.js.map +1 -0
- package/build/src/version.d.ts +1 -1
- package/build/src/version.js +1 -1
- package/docs/SPEC-COMPACT.md +13 -4
- package/docs/SPEC.md +105 -17
- package/package.json +4 -1
- package/runtime/migrate.ts +131 -0
- package/runtime/server.ts +264 -17
- package/runtime/session.ts +2 -0
- package/runtime/types.ts +36 -1
package/runtime/server.ts
CHANGED
|
@@ -14,7 +14,7 @@ import pg from "pg";
|
|
|
14
14
|
import { hashPassword, dummyHash, verifyPassword } from "./password.ts";
|
|
15
15
|
import { RateLimiter } from "./ratelimit.ts";
|
|
16
16
|
import { SESSION_SECONDS, SQL, clearedCookie, hashToken, newToken, readToken, sessionCookie } from "./session.ts";
|
|
17
|
-
import type { App, FieldSpec, Route, ValueSource } from "./types.ts";
|
|
17
|
+
import type { App, FieldKind, FieldSpec, Route, ValueSource } from "./types.ts";
|
|
18
18
|
import { validateBody, validatePathParam, validateValue } from "./validate.ts";
|
|
19
19
|
|
|
20
20
|
export interface QueryResult {
|
|
@@ -73,17 +73,56 @@ interface Matched {
|
|
|
73
73
|
readonly params: ReadonlyMap<string, unknown>;
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
-
interface
|
|
77
|
-
readonly method: string;
|
|
76
|
+
interface AuthRoute {
|
|
78
77
|
readonly path: string;
|
|
78
|
+
readonly methods: readonly string[];
|
|
79
79
|
}
|
|
80
|
-
const AUTH_ROUTES: readonly
|
|
81
|
-
{
|
|
82
|
-
{
|
|
83
|
-
{
|
|
84
|
-
{
|
|
80
|
+
const AUTH_ROUTES: readonly AuthRoute[] = [
|
|
81
|
+
{ path: "/auth/signup", methods: ["POST"] },
|
|
82
|
+
{ path: "/auth/login", methods: ["POST"] },
|
|
83
|
+
{ path: "/auth/logout", methods: ["POST"] },
|
|
84
|
+
{ path: "/auth/logout-all", methods: ["POST"] },
|
|
85
|
+
{ path: "/auth/password", methods: ["POST"] },
|
|
86
|
+
{ path: "/auth/me", methods: ["GET", "PATCH", "DELETE"] },
|
|
85
87
|
];
|
|
86
88
|
|
|
89
|
+
interface Page {
|
|
90
|
+
readonly limit: number;
|
|
91
|
+
readonly cursor?: { readonly value?: string; readonly id: string };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
95
|
+
const MAX_CURSOR = 2048;
|
|
96
|
+
|
|
97
|
+
/** A cursor is base64url(JSON) of [sortValue, id], or [id] when sorted by id. */
|
|
98
|
+
export function encodeCursor(parts: readonly string[]): string {
|
|
99
|
+
return Buffer.from(JSON.stringify(parts), "utf8").toString("base64url");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Decode and check a cursor. Returns undefined for anything malformed. */
|
|
103
|
+
export function decodeCursor(raw: string, order: FieldKind | null): { value?: string; id: string } | undefined {
|
|
104
|
+
if (raw.length === 0 || raw.length > MAX_CURSOR || !/^[A-Za-z0-9_-]+$/.test(raw)) return undefined;
|
|
105
|
+
let parts: unknown;
|
|
106
|
+
try {
|
|
107
|
+
parts = JSON.parse(Buffer.from(raw, "base64url").toString("utf8"));
|
|
108
|
+
} catch {
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
if (!Array.isArray(parts) || !parts.every((x) => typeof x === "string")) return undefined;
|
|
112
|
+
const strings = parts as string[];
|
|
113
|
+
const id = strings[strings.length - 1];
|
|
114
|
+
if (id === undefined || !UUID_RE.test(id)) return undefined;
|
|
115
|
+
if (order === null) return strings.length === 1 ? { id } : undefined;
|
|
116
|
+
const value = strings[0];
|
|
117
|
+
if (strings.length !== 2 || value === undefined || value.includes("\u0000")) return undefined;
|
|
118
|
+
const valid =
|
|
119
|
+
order === "Number" ? /^-?\d{1,10}$/.test(value)
|
|
120
|
+
: order === "Bool" ? value === "true" || value === "false"
|
|
121
|
+
: order === "ID" ? UUID_RE.test(value)
|
|
122
|
+
: true; // Text, Email, Date: PostgreSQL checks the value when it is cast back.
|
|
123
|
+
return valid ? { value, id } : undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
87
126
|
/** Copy only the listed keys. Responses never rely on the query alone to hide data. */
|
|
88
127
|
function pick(row: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {
|
|
89
128
|
const out: Record<string, unknown> = {};
|
|
@@ -120,7 +159,7 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
120
159
|
} else {
|
|
121
160
|
const { route, params } = match(method, url.pathname);
|
|
122
161
|
pattern = route.pattern;
|
|
123
|
-
status = await handleRoute(req, res, route, params);
|
|
162
|
+
status = await handleRoute(req, res, route, params, url.searchParams);
|
|
124
163
|
}
|
|
125
164
|
} catch (e) {
|
|
126
165
|
if (e instanceof HttpError) {
|
|
@@ -238,6 +277,44 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
238
277
|
return values;
|
|
239
278
|
}
|
|
240
279
|
|
|
280
|
+
/**
|
|
281
|
+
* Query string handling. Only list endpoints accept parameters, and only
|
|
282
|
+
* `limit` and `after`; anything else is rejected.
|
|
283
|
+
*/
|
|
284
|
+
function readPage(route: Route, search: URLSearchParams): Page | undefined {
|
|
285
|
+
const allowed = route.page === null ? [] : ["limit", "after"];
|
|
286
|
+
for (const key of new Set(search.keys())) {
|
|
287
|
+
const shown = key.length > 50 ? `${key.slice(0, 50)}…` : key;
|
|
288
|
+
if (!allowed.includes(key)) {
|
|
289
|
+
throw new HttpError(400, "unknown_parameter",
|
|
290
|
+
allowed.length > 0 ? `Unknown query parameter "${shown}". Allowed: limit, after.` : `This endpoint takes no query parameters (got "${shown}").`, shown);
|
|
291
|
+
}
|
|
292
|
+
if (search.getAll(key).length > 1) throw new HttpError(400, "unknown_parameter", `Query parameter "${key}" appears more than once.`, key);
|
|
293
|
+
}
|
|
294
|
+
if (route.page === null) return undefined;
|
|
295
|
+
const max = route.page.max;
|
|
296
|
+
const rawLimit = search.get("limit");
|
|
297
|
+
let limit = max;
|
|
298
|
+
if (rawLimit !== null) {
|
|
299
|
+
limit = /^\d{1,4}$/.test(rawLimit) ? Number(rawLimit) : 0;
|
|
300
|
+
if (limit < 1 || limit > max) throw new HttpError(400, "invalid_parameter", `limit must be a whole number from 1 to ${max}.`, "limit");
|
|
301
|
+
}
|
|
302
|
+
const rawAfter = search.get("after");
|
|
303
|
+
if (rawAfter === null) return { limit };
|
|
304
|
+
const cursor = decodeCursor(rawAfter, route.page.order);
|
|
305
|
+
if (cursor === undefined) throw new HttpError(400, "invalid_parameter", "after is not a valid cursor. Use the next value from the previous page.", "after");
|
|
306
|
+
return { limit, cursor };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The role of a user, or null. Read from the database on every request, so changes apply at once. */
|
|
310
|
+
async function roleOf(userId: string): Promise<string | null> {
|
|
311
|
+
const auth = app.auth;
|
|
312
|
+
if (auth === null || auth.roleSql === "") return null;
|
|
313
|
+
const r = await db.query(auth.roleSql, [userId]);
|
|
314
|
+
const role = r.rows[0]?.["role"];
|
|
315
|
+
return typeof role === "string" && auth.roles.includes(role) ? role : null;
|
|
316
|
+
}
|
|
317
|
+
|
|
241
318
|
async function currentUser(req: IncomingMessage): Promise<string | undefined> {
|
|
242
319
|
const token = readToken(req.headers.cookie);
|
|
243
320
|
if (token === undefined) return undefined;
|
|
@@ -262,7 +339,14 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
262
339
|
return req.socket.remoteAddress ?? "unknown";
|
|
263
340
|
}
|
|
264
341
|
|
|
265
|
-
function values(
|
|
342
|
+
function values(
|
|
343
|
+
sources: readonly ValueSource[],
|
|
344
|
+
params: ReadonlyMap<string, unknown>,
|
|
345
|
+
bodyValues: ReadonlyMap<string, unknown>,
|
|
346
|
+
me: string | undefined,
|
|
347
|
+
role: string | null,
|
|
348
|
+
page?: Page,
|
|
349
|
+
): unknown[] {
|
|
266
350
|
return sources.map((s) => {
|
|
267
351
|
switch (s.from) {
|
|
268
352
|
case "path": return params.get(s.name);
|
|
@@ -270,6 +354,11 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
270
354
|
case "body": return bodyValues.get(s.key) ?? null;
|
|
271
355
|
case "provided": return bodyValues.has(s.key);
|
|
272
356
|
case "const": return s.value;
|
|
357
|
+
case "hasRole": return role !== null && s.roles.includes(role);
|
|
358
|
+
case "cursorSet": return page?.cursor !== undefined;
|
|
359
|
+
case "cursorValue": return page?.cursor?.value ?? null;
|
|
360
|
+
case "cursorId": return page?.cursor?.id ?? null;
|
|
361
|
+
case "pageLimit": return (page?.limit ?? 0) + 1;
|
|
273
362
|
}
|
|
274
363
|
});
|
|
275
364
|
}
|
|
@@ -291,6 +380,8 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
291
380
|
case "23514":
|
|
292
381
|
case "23502":
|
|
293
382
|
case "22P02":
|
|
383
|
+
case "22007":
|
|
384
|
+
case "22008":
|
|
294
385
|
case "22001":
|
|
295
386
|
throw new HttpError(400, "validation_failed", "A value is not valid.");
|
|
296
387
|
default:
|
|
@@ -299,23 +390,42 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
299
390
|
}
|
|
300
391
|
}
|
|
301
392
|
|
|
302
|
-
async function handleRoute(
|
|
393
|
+
async function handleRoute(
|
|
394
|
+
req: IncomingMessage,
|
|
395
|
+
res: ServerResponse,
|
|
396
|
+
route: Route,
|
|
397
|
+
params: ReadonlyMap<string, unknown>,
|
|
398
|
+
search: URLSearchParams,
|
|
399
|
+
): Promise<number> {
|
|
303
400
|
checkOrigin(req, route.method);
|
|
401
|
+
const page = readPage(route, search);
|
|
304
402
|
let me: string | undefined;
|
|
305
403
|
if (route.access === "login") {
|
|
306
404
|
me = await currentUser(req);
|
|
307
405
|
if (me === undefined) throw new HttpError(401, "login_required", "You need to log in.");
|
|
308
406
|
}
|
|
407
|
+
const needsRole = route.roles.length > 0 || route.values.some((v) => v.from === "hasRole");
|
|
408
|
+
const role = needsRole && me !== undefined ? await roleOf(me) : null;
|
|
409
|
+
if (route.roles.length > 0 && (role === null || !route.roles.includes(role))) {
|
|
410
|
+
throw new HttpError(403, "forbidden", "You do not have permission to do this.");
|
|
411
|
+
}
|
|
309
412
|
let bodyValues: ReadonlyMap<string, unknown> = new Map();
|
|
310
413
|
if (route.body === null) {
|
|
311
414
|
if (hasBody(req)) throw new HttpError(400, "unexpected_body", "This endpoint does not accept a request body.");
|
|
312
415
|
} else {
|
|
313
416
|
bodyValues = await body(req, route.body);
|
|
314
417
|
}
|
|
315
|
-
const r = await run(route.sql, values(route.values, params, bodyValues, me), route.model);
|
|
418
|
+
const r = await run(route.sql, values(route.values, params, bodyValues, me, role, page), route.model);
|
|
316
419
|
switch (route.result) {
|
|
317
|
-
case "list":
|
|
318
|
-
|
|
420
|
+
case "list": {
|
|
421
|
+
const limit = page?.limit ?? r.rows.length;
|
|
422
|
+
const rows = r.rows.slice(0, limit);
|
|
423
|
+
const last = rows[rows.length - 1];
|
|
424
|
+
const next = r.rows.length > limit && last !== undefined
|
|
425
|
+
? encodeCursor(route.page?.order ? [String(last["_cursor"]), String(last["id"])] : [String(last["id"])])
|
|
426
|
+
: null;
|
|
427
|
+
return send(res, 200, { items: rows.map((row) => pick(row, route.publicKeys)), next });
|
|
428
|
+
}
|
|
319
429
|
case "created":
|
|
320
430
|
return send(res, 201, pick(r.rows[0] ?? {}, route.publicKeys));
|
|
321
431
|
case "one": {
|
|
@@ -332,13 +442,74 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
332
442
|
|
|
333
443
|
// ----------------------------------------------------------------- auth
|
|
334
444
|
|
|
445
|
+
async function requireUser(req: IncomingMessage): Promise<string> {
|
|
446
|
+
const me = await currentUser(req);
|
|
447
|
+
if (me === undefined) throw new HttpError(401, "login_required", "You need to log in.");
|
|
448
|
+
return me;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Check the logged-in user's password before a sensitive change. Wrong
|
|
453
|
+
* guesses count toward the same per-account lockout as login.
|
|
454
|
+
*/
|
|
455
|
+
async function confirmPassword(userId: string, password: string, field: string): Promise<void> {
|
|
456
|
+
const auth = app.auth;
|
|
457
|
+
if (auth === null) throw new HttpError(404, "not_found", "No endpoint matches this path.");
|
|
458
|
+
const key = `id:${userId}`;
|
|
459
|
+
const wait = loginByAccount.retryAfter(key);
|
|
460
|
+
if (wait > 0) throw new HttpError(429, "too_many_requests", "Too many wrong passwords. Try again later.", undefined, { "Retry-After": String(wait) });
|
|
461
|
+
const r = await db.query(auth.account.hashSql, [userId]);
|
|
462
|
+
const stored = r.rows[0]?.["hash"];
|
|
463
|
+
const valid = await verifyPassword(password, typeof stored === "string" ? stored : await dummyHash());
|
|
464
|
+
if (!valid) {
|
|
465
|
+
loginByAccount.hit(key);
|
|
466
|
+
throw new HttpError(403, "invalid_credentials", "The password is incorrect.", field);
|
|
467
|
+
}
|
|
468
|
+
loginByAccount.reset(key);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** PUT /auth/users/:id/role, admins only. Body: { "role": "<role>" } or { "role": null }. */
|
|
472
|
+
async function setRole(req: IncomingMessage, res: ServerResponse, method: string, rawId: string): Promise<number> {
|
|
473
|
+
const auth = app.auth;
|
|
474
|
+
if (auth === null) throw new HttpError(404, "not_found", "No endpoint matches this path.");
|
|
475
|
+
if (method !== "PUT") throw new HttpError(405, "method_not_allowed", `This path does not support ${method}.`, undefined, { Allow: "PUT" });
|
|
476
|
+
checkOrigin(req, method);
|
|
477
|
+
const me = await currentUser(req);
|
|
478
|
+
if (me === undefined) throw new HttpError(401, "login_required", "You need to log in.");
|
|
479
|
+
if ((await roleOf(me)) !== "admin") throw new HttpError(403, "forbidden", "You do not have permission to do this.");
|
|
480
|
+
let decoded: string;
|
|
481
|
+
try {
|
|
482
|
+
decoded = decodeURIComponent(rawId);
|
|
483
|
+
} catch {
|
|
484
|
+
throw new HttpError(400, "bad_path", "The URL path is not valid.");
|
|
485
|
+
}
|
|
486
|
+
const id = validatePathParam({ param: "id", kind: "ID" }, decoded);
|
|
487
|
+
if ("error" in id) throw new HttpError(400, "invalid_parameter", id.error, "id");
|
|
488
|
+
if (id.value === me) throw new HttpError(403, "forbidden", "You cannot change your own role.");
|
|
489
|
+
const raw = await readJson(req);
|
|
490
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw) || Object.keys(raw).join() !== "role") {
|
|
491
|
+
throw new HttpError(400, "validation_failed", 'Send exactly one field: { "role": "<role>" } or { "role": null }.', "role");
|
|
492
|
+
}
|
|
493
|
+
const role = (raw as { role: unknown }).role;
|
|
494
|
+
if (role !== null && (typeof role !== "string" || !auth.roles.includes(role))) {
|
|
495
|
+
throw new HttpError(400, "validation_failed", `role must be one of: ${auth.roles.join(", ")}, or null.`, "role");
|
|
496
|
+
}
|
|
497
|
+
const r = await db.query(auth.setRoleSql, [id.value, role]);
|
|
498
|
+
const row = r.rows[0];
|
|
499
|
+
if (row === undefined) throw new HttpError(404, "not_found", `${auth.model} not found.`);
|
|
500
|
+
return send(res, 200, { id: row["id"], role: row["role"] });
|
|
501
|
+
}
|
|
502
|
+
|
|
335
503
|
async function handleAuth(req: IncomingMessage, res: ServerResponse, path: string, method: string): Promise<number> {
|
|
336
504
|
const auth = app.auth;
|
|
337
505
|
if (auth === null) throw new HttpError(404, "not_found", "No endpoint matches this path.");
|
|
506
|
+
const roleRoute = /^\/auth\/users\/([^/]+)\/role$/.exec(path);
|
|
507
|
+
if (roleRoute !== null && auth.roles.length > 0) return setRole(req, res, method, roleRoute[1] ?? "");
|
|
338
508
|
const known = AUTH_ROUTES.find((r) => r.path === path);
|
|
339
509
|
if (known === undefined) throw new HttpError(404, "not_found", "No endpoint matches this path.");
|
|
340
|
-
|
|
341
|
-
|
|
510
|
+
const methods = known.methods.filter((m) => !(path === "/auth/me" && m === "PATCH" && auth.account.profile === null));
|
|
511
|
+
if (!methods.includes(method)) {
|
|
512
|
+
throw new HttpError(405, "method_not_allowed", `This path does not support ${method}.`, undefined, { Allow: methods.join(", ") });
|
|
342
513
|
}
|
|
343
514
|
checkOrigin(req, method);
|
|
344
515
|
const ip = clientIp(req);
|
|
@@ -348,7 +519,7 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
348
519
|
if (wait > 0) throw new HttpError(429, "too_many_requests", "Too many signups. Try again later.", undefined, { "Retry-After": String(wait) });
|
|
349
520
|
signupByIp.hit(ip);
|
|
350
521
|
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);
|
|
522
|
+
const r = await run(auth.signup.sql, values(auth.signup.values, new Map(), bodyValues, undefined, null), auth.model);
|
|
352
523
|
const row = r.rows[0] ?? {};
|
|
353
524
|
await startSession(res, String(row["id"]));
|
|
354
525
|
return send(res, 201, pick(row, auth.publicKeys));
|
|
@@ -386,6 +557,57 @@ export function createRequestHandler(app: App, options: ServerOptions): (req: In
|
|
|
386
557
|
return send(res, 200, pick(me.rows[0] ?? {}, auth.publicKeys));
|
|
387
558
|
}
|
|
388
559
|
|
|
560
|
+
if (path === "/auth/password") {
|
|
561
|
+
const me = await requireUser(req);
|
|
562
|
+
const v = validateBody(
|
|
563
|
+
[{ key: "currentPassword", kind: "Text", required: true, nullable: false, max: 128 }, auth.account.password],
|
|
564
|
+
await readJson(req),
|
|
565
|
+
);
|
|
566
|
+
if (!v.ok) throw new HttpError(400, "validation_failed", v.message, v.field || undefined);
|
|
567
|
+
await confirmPassword(me, String(v.values.get("currentPassword")), "currentPassword");
|
|
568
|
+
await db.query(auth.account.setPasswordSql, [me, await hashPassword(String(v.values.get("newPassword")))]);
|
|
569
|
+
// Everyone else using this account is logged out; this session stays.
|
|
570
|
+
await db.query(SQL.deleteOthers, [me, hashToken(readToken(req.headers.cookie) ?? "")]);
|
|
571
|
+
res.writeHead(204, SECURITY_HEADERS).end();
|
|
572
|
+
return 204;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (path === "/auth/logout-all") {
|
|
576
|
+
const me = await requireUser(req);
|
|
577
|
+
await db.query(SQL.deleteAll, [me]);
|
|
578
|
+
res.setHeader("Set-Cookie", clearedCookie(secure));
|
|
579
|
+
res.writeHead(204, SECURITY_HEADERS).end();
|
|
580
|
+
return 204;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
if (path === "/auth/me" && method === "PATCH" && auth.account.profile !== null) {
|
|
584
|
+
const me = await requireUser(req);
|
|
585
|
+
const profile = auth.account.profile;
|
|
586
|
+
const bodyValues = await body(req, profile.body);
|
|
587
|
+
const r = await run(profile.sql, values(profile.values, new Map(), bodyValues, me, null), auth.model);
|
|
588
|
+
const row = r.rows[0];
|
|
589
|
+
if (row === undefined) throw new HttpError(401, "login_required", "You need to log in.");
|
|
590
|
+
return send(res, 200, pick(row, auth.publicKeys));
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (path === "/auth/me" && method === "DELETE") {
|
|
594
|
+
const me = await requireUser(req);
|
|
595
|
+
const v = validateBody([{ key: "password", kind: "Text", required: true, nullable: false, max: 128 }], await readJson(req));
|
|
596
|
+
if (!v.ok) throw new HttpError(400, "validation_failed", v.message, v.field || undefined);
|
|
597
|
+
await confirmPassword(me, String(v.values.get("password")), "password");
|
|
598
|
+
try {
|
|
599
|
+
await run(auth.account.deleteSql, [me], auth.model);
|
|
600
|
+
} catch (e) {
|
|
601
|
+
if (e instanceof HttpError && e.code === "in_use") {
|
|
602
|
+
throw new HttpError(409, "in_use", "This account still owns records. Delete them first, then delete the account.");
|
|
603
|
+
}
|
|
604
|
+
throw e;
|
|
605
|
+
}
|
|
606
|
+
res.setHeader("Set-Cookie", clearedCookie(secure));
|
|
607
|
+
res.writeHead(204, SECURITY_HEADERS).end();
|
|
608
|
+
return 204;
|
|
609
|
+
}
|
|
610
|
+
|
|
389
611
|
if (path === "/auth/logout") {
|
|
390
612
|
const token = readToken(req.headers.cookie);
|
|
391
613
|
if (token !== undefined) await db.query(SQL.delete, [hashToken(token)]);
|
|
@@ -417,6 +639,20 @@ function send(res: ServerResponse, status: number, payload: unknown, headers: Re
|
|
|
417
639
|
return status;
|
|
418
640
|
}
|
|
419
641
|
|
|
642
|
+
/**
|
|
643
|
+
* Give the admin role to existing accounts with these login emails. Accounts
|
|
644
|
+
* created later are not affected, so nobody can claim admin by signing up
|
|
645
|
+
* with a listed email. Returns the number of accounts changed.
|
|
646
|
+
*/
|
|
647
|
+
export async function grantAdmins(app: App, db: Db, emails: readonly string[]): Promise<number> {
|
|
648
|
+
const auth = app.auth;
|
|
649
|
+
if (auth === null || !auth.roles.includes("admin") || auth.grantAdminSql === "") return 0;
|
|
650
|
+
const list = emails.map((e) => e.trim().toLowerCase()).filter(Boolean);
|
|
651
|
+
if (list.length === 0) return 0;
|
|
652
|
+
const r = await db.query(auth.grantAdminSql, [list]);
|
|
653
|
+
return r.rowCount ?? 0;
|
|
654
|
+
}
|
|
655
|
+
|
|
420
656
|
/** Start the server. Configuration comes from environment variables. */
|
|
421
657
|
export function startServer(app: App): void {
|
|
422
658
|
const url = process.env["DATABASE_URL"];
|
|
@@ -440,6 +676,17 @@ export function startServer(app: App): void {
|
|
|
440
676
|
server.headersTimeout = 10_000;
|
|
441
677
|
const port = Number(process.env["PORT"] ?? "3000");
|
|
442
678
|
const host = process.env["HOST"] ?? "127.0.0.1";
|
|
679
|
+
const adminEmails = (process.env["RIZO_ADMIN_EMAILS"] ?? "").split(",");
|
|
680
|
+
if (adminEmails.some((e) => e.trim() !== "")) {
|
|
681
|
+
if (app.auth === null || !app.auth.roles.includes("admin")) {
|
|
682
|
+
process.stderr.write("rizo: RIZO_ADMIN_EMAILS is set, but this app declares no roles. Ignoring it.\n");
|
|
683
|
+
} else {
|
|
684
|
+
grantAdmins(app, { query: (sql, vals) => pool.query(sql, vals) }, adminEmails).then(
|
|
685
|
+
(n) => process.stdout.write(`rizo: RIZO_ADMIN_EMAILS granted admin to ${n} existing account(s)\n`),
|
|
686
|
+
(e: unknown) => process.stderr.write(`rizo: could not apply RIZO_ADMIN_EMAILS: ${describeError(e)}\n`),
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
443
690
|
server.listen(port, host, () => process.stdout.write(`rizo: listening on http://${host}:${port}\n`));
|
|
444
691
|
const stop = (): void => {
|
|
445
692
|
server.close(() => void pool.end());
|
package/runtime/session.ts
CHANGED
|
@@ -16,6 +16,8 @@ export const SQL = {
|
|
|
16
16
|
lookup: `SELECT "user_id" FROM ${SESSIONS_TABLE} WHERE "token_hash" = $1 AND "expires_at" > now()`,
|
|
17
17
|
delete: `DELETE FROM ${SESSIONS_TABLE} WHERE "token_hash" = $1`,
|
|
18
18
|
deleteExpired: `DELETE FROM ${SESSIONS_TABLE} WHERE "user_id" = $1 AND "expires_at" <= now()`,
|
|
19
|
+
deleteOthers: `DELETE FROM ${SESSIONS_TABLE} WHERE "user_id" = $1 AND "token_hash" <> $2`,
|
|
20
|
+
deleteAll: `DELETE FROM ${SESSIONS_TABLE} WHERE "user_id" = $1`,
|
|
19
21
|
} as const;
|
|
20
22
|
|
|
21
23
|
export function newToken(): string {
|
package/runtime/types.ts
CHANGED
|
@@ -30,7 +30,17 @@ export type ValueSource =
|
|
|
30
30
|
| { readonly from: "body"; readonly key: string }
|
|
31
31
|
/** true when the body contains `key` (used for partial updates). */
|
|
32
32
|
| { readonly from: "provided"; readonly key: string }
|
|
33
|
-
| { readonly from: "const"; readonly value: number | boolean }
|
|
33
|
+
| { readonly from: "const"; readonly value: number | boolean }
|
|
34
|
+
/** Pagination: true when the request has a cursor (`?after=`). */
|
|
35
|
+
| { readonly from: "cursorSet" }
|
|
36
|
+
/** Pagination: the sort column value from the cursor, as text. */
|
|
37
|
+
| { readonly from: "cursorValue" }
|
|
38
|
+
/** Pagination: the id from the cursor. */
|
|
39
|
+
| { readonly from: "cursorId" }
|
|
40
|
+
/** Pagination: the page size plus one (the extra row shows whether there is a next page). */
|
|
41
|
+
| { readonly from: "pageLimit" }
|
|
42
|
+
/** true when the logged-in user has one of these roles (`requires owner author or role admin`). */
|
|
43
|
+
| { readonly from: "hasRole"; readonly roles: readonly string[] };
|
|
34
44
|
|
|
35
45
|
export type PathPart =
|
|
36
46
|
| { readonly static: string }
|
|
@@ -44,12 +54,16 @@ export interface Route {
|
|
|
44
54
|
readonly pattern: string;
|
|
45
55
|
readonly path: readonly PathPart[];
|
|
46
56
|
readonly access: "public" | "login";
|
|
57
|
+
/** The caller must have one of these roles; empty for no role check. */
|
|
58
|
+
readonly roles: readonly string[];
|
|
47
59
|
/** Accepted body fields, or null if the request must not have a body. */
|
|
48
60
|
readonly body: readonly FieldSpec[] | null;
|
|
49
61
|
readonly sql: string;
|
|
50
62
|
readonly values: readonly ValueSource[];
|
|
51
63
|
/** one: 200 with an object (404 if no row); list: 200 with an array; created: 201; none: 204 (404 if no row). */
|
|
52
64
|
readonly result: "one" | "list" | "created" | "none";
|
|
65
|
+
/** For list endpoints: the largest page size, and the type of the sort column (null when sorted by id). */
|
|
66
|
+
readonly page: { readonly max: number; readonly order: FieldKind | null } | null;
|
|
53
67
|
/** The only keys ever copied into a response. */
|
|
54
68
|
readonly publicKeys: readonly string[];
|
|
55
69
|
/** Model name, used in error messages such as "Post not found". */
|
|
@@ -68,6 +82,27 @@ export interface AuthSpec {
|
|
|
68
82
|
/** `SELECT <public columns> FROM <users> WHERE id = $1` */
|
|
69
83
|
readonly meSql: string;
|
|
70
84
|
readonly publicKeys: readonly string[];
|
|
85
|
+
/** Declared roles; empty when the app does not use roles. */
|
|
86
|
+
readonly roles: readonly string[];
|
|
87
|
+
/** `SELECT "role" FROM <users> WHERE id = $1` (empty string without roles) */
|
|
88
|
+
readonly roleSql: string;
|
|
89
|
+
/** `UPDATE <users> SET "role" = $2 WHERE id = $1 RETURNING id, "role"` (empty string without roles) */
|
|
90
|
+
readonly setRoleSql: string;
|
|
91
|
+
/** Grants admin to existing accounts whose login email is in $1 (empty string without roles). */
|
|
92
|
+
readonly grantAdminSql: string;
|
|
93
|
+
/** Account management. */
|
|
94
|
+
readonly account: {
|
|
95
|
+
/** Limits for a new password (the Password field's min and max). */
|
|
96
|
+
readonly password: FieldSpec;
|
|
97
|
+
/** `SELECT <hash column> AS hash FROM <users> WHERE id = $1` */
|
|
98
|
+
readonly hashSql: string;
|
|
99
|
+
/** `UPDATE <users> SET <hash column> = $2 WHERE id = $1` */
|
|
100
|
+
readonly setPasswordSql: string;
|
|
101
|
+
/** `DELETE FROM <users> WHERE id = $1` */
|
|
102
|
+
readonly deleteSql: string;
|
|
103
|
+
/** Updating your own profile, or null when there is nothing a user may change. */
|
|
104
|
+
readonly profile: { readonly body: readonly FieldSpec[]; readonly sql: string; readonly values: readonly ValueSource[] } | null;
|
|
105
|
+
};
|
|
71
106
|
}
|
|
72
107
|
|
|
73
108
|
export interface App {
|