rizolang 0.0.0-stage → 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.
Files changed (60) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +430 -2
  3. package/build/src/ast.d.ts +148 -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 +104 -0
  10. package/build/src/check-api.js +564 -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 +12 -0
  16. package/build/src/cli.js +170 -0
  17. package/build/src/cli.js.map +1 -0
  18. package/build/src/compiler.d.ts +38 -0
  19. package/build/src/compiler.js +62 -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 +22 -0
  25. package/build/src/emit/routes.js +316 -0
  26. package/build/src/emit/routes.js.map +1 -0
  27. package/build/src/emit/sql.d.ts +11 -0
  28. package/build/src/emit/sql.js +26 -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 +77 -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/migrations.d.ts +33 -0
  37. package/build/src/migrations.js +183 -0
  38. package/build/src/migrations.js.map +1 -0
  39. package/build/src/parser.d.ts +17 -0
  40. package/build/src/parser.js +434 -0
  41. package/build/src/parser.js.map +1 -0
  42. package/build/src/schema.d.ts +63 -0
  43. package/build/src/schema.js +151 -0
  44. package/build/src/schema.js.map +1 -0
  45. package/build/src/types.d.ts +42 -0
  46. package/build/src/types.js +77 -0
  47. package/build/src/types.js.map +1 -0
  48. package/build/src/version.d.ts +2 -0
  49. package/build/src/version.js +3 -0
  50. package/build/src/version.js.map +1 -0
  51. package/docs/SPEC-COMPACT.md +157 -0
  52. package/docs/SPEC.md +685 -0
  53. package/package.json +51 -4
  54. package/runtime/migrate.ts +131 -0
  55. package/runtime/password.ts +58 -0
  56. package/runtime/ratelimit.ts +53 -0
  57. package/runtime/server.ts +696 -0
  58. package/runtime/session.ts +50 -0
  59. package/runtime/types.ts +111 -0
  60. package/runtime/validate.ts +133 -0
@@ -0,0 +1,50 @@
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
+ deleteOthers: `DELETE FROM ${SESSIONS_TABLE} WHERE "user_id" = $1 AND "token_hash" <> $2`,
20
+ deleteAll: `DELETE FROM ${SESSIONS_TABLE} WHERE "user_id" = $1`,
21
+ } as const;
22
+
23
+ export function newToken(): string {
24
+ return randomBytes(32).toString("base64url");
25
+ }
26
+
27
+ export function hashToken(token: string): string {
28
+ return createHash("sha256").update(token).digest("hex");
29
+ }
30
+
31
+ /** Read the session token from a Cookie header. Returns undefined if absent or malformed. */
32
+ export function readToken(cookieHeader: string | undefined): string | undefined {
33
+ if (cookieHeader === undefined) return undefined;
34
+ for (const part of cookieHeader.split(";")) {
35
+ const eq = part.indexOf("=");
36
+ if (eq === -1) continue;
37
+ if (part.slice(0, eq).trim() !== COOKIE_NAME) continue;
38
+ const value = part.slice(eq + 1).trim();
39
+ return /^[A-Za-z0-9_-]{43}$/.test(value) ? value : undefined;
40
+ }
41
+ return undefined;
42
+ }
43
+
44
+ export function sessionCookie(token: string, secure: boolean): string {
45
+ return `${COOKIE_NAME}=${token}; HttpOnly;${secure ? " Secure;" : ""} SameSite=Lax; Path=/; Max-Age=${SESSION_SECONDS}`;
46
+ }
47
+
48
+ export function clearedCookie(secure: boolean): string {
49
+ return `${COOKIE_NAME}=; HttpOnly;${secure ? " Secure;" : ""} SameSite=Lax; Path=/; Max-Age=0`;
50
+ }
@@ -0,0 +1,111 @@
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
+ /** 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[] };
44
+
45
+ export type PathPart =
46
+ | { readonly static: string }
47
+ | { readonly param: string; readonly kind: "ID" | "Number" | "Bool" | "Text" | "Email" };
48
+
49
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
50
+
51
+ export interface Route {
52
+ readonly method: HttpMethod;
53
+ /** Original path, used in logs (never the concrete URL, which may contain values). */
54
+ readonly pattern: string;
55
+ readonly path: readonly PathPart[];
56
+ readonly access: "public" | "login";
57
+ /** The caller must have one of these roles; empty for no role check. */
58
+ readonly roles: readonly string[];
59
+ /** Accepted body fields, or null if the request must not have a body. */
60
+ readonly body: readonly FieldSpec[] | null;
61
+ readonly sql: string;
62
+ readonly values: readonly ValueSource[];
63
+ /** one: 200 with an object (404 if no row); list: 200 with an array; created: 201; none: 204 (404 if no row). */
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;
67
+ /** The only keys ever copied into a response. */
68
+ readonly publicKeys: readonly string[];
69
+ /** Model name, used in error messages such as "Post not found". */
70
+ readonly model: string;
71
+ }
72
+
73
+ export interface AuthSpec {
74
+ /** Name of the auth model, e.g. "User". */
75
+ readonly model: string;
76
+ readonly signup: { readonly body: readonly FieldSpec[]; readonly sql: string; readonly values: readonly ValueSource[] };
77
+ /** JSON keys of the login fields, e.g. "email" and "password". */
78
+ readonly loginKey: string;
79
+ readonly passwordKey: string;
80
+ /** `SELECT id, <hash column> AS hash FROM <users> WHERE <login column> = $1` */
81
+ readonly loginSql: string;
82
+ /** `SELECT <public columns> FROM <users> WHERE id = $1` */
83
+ readonly meSql: string;
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
+ };
106
+ }
107
+
108
+ export interface App {
109
+ readonly routes: readonly Route[];
110
+ readonly auth: AuthSpec | null;
111
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Rizo Lang runtime: input validation.
3
+ *
4
+ * Every value from a request (body fields and path parameters) passes through
5
+ * here before it reaches a query. Anything unexpected is rejected with a
6
+ * message that names the field; values are never echoed back.
7
+ */
8
+ import type { FieldKind, FieldSpec, PathPart } from "./types.ts";
9
+
10
+ export type Validated =
11
+ | { readonly ok: true; readonly values: ReadonlyMap<string, unknown> }
12
+ | { readonly ok: false; readonly field: string; readonly message: string };
13
+
14
+ const INT32_MIN = -2147483648;
15
+ const INT32_MAX = 2147483647;
16
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
+ const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
18
+ /** Date, or date and time with a required time zone. */
19
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,6})?)?(Z|[+-]\d{2}:\d{2}))?$/;
20
+ /** Path parameters of type Text are capped so URLs cannot carry huge values. */
21
+ const MAX_PATH_TEXT = 1000;
22
+
23
+ /** Length in Unicode code points, matching PostgreSQL's char_length(). */
24
+ const length = (s: string): number => [...s].length;
25
+
26
+ function describeKind(kind: FieldKind): string {
27
+ switch (kind) {
28
+ case "Text": return "text";
29
+ case "Password": return "text";
30
+ case "Email": return "an email address";
31
+ case "Number": return "a whole number";
32
+ case "Bool": return "true or false";
33
+ case "Date": return "an ISO 8601 date such as 2026-01-31T12:00:00Z";
34
+ case "ID": return "an ID (UUID)";
35
+ }
36
+ }
37
+
38
+ /** Validate one value. Returns the value to store, or an error message. */
39
+ export function validateValue(spec: Omit<FieldSpec, "required" | "nullable">, raw: unknown): { value: unknown } | { error: string } {
40
+ const { key, kind } = spec;
41
+ const bad = (): { error: string } => ({ error: `${key} must be ${describeKind(kind)}.` });
42
+ switch (kind) {
43
+ case "Text":
44
+ case "Password": {
45
+ if (typeof raw !== "string") return bad();
46
+ if (raw.includes("\u0000")) return { error: `${key} contains a character that is not allowed.` };
47
+ const n = length(raw);
48
+ if (spec.min !== undefined && n < spec.min) return { error: `${key} must be at least ${spec.min} characters.` };
49
+ if (spec.max !== undefined && n > spec.max) return { error: `${key} must be at most ${spec.max} characters.` };
50
+ return { value: raw };
51
+ }
52
+ case "Email": {
53
+ if (typeof raw !== "string") return bad();
54
+ const email = raw.trim().toLowerCase();
55
+ const n = length(email);
56
+ if (!EMAIL.test(email)) return bad();
57
+ if (spec.min !== undefined && n < spec.min) return { error: `${key} must be at least ${spec.min} characters.` };
58
+ if (spec.max !== undefined && n > spec.max) return { error: `${key} must be at most ${spec.max} characters.` };
59
+ return { value: email };
60
+ }
61
+ case "Number": {
62
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < INT32_MIN || raw > INT32_MAX) return bad();
63
+ if (spec.min !== undefined && raw < spec.min) return { error: `${key} must be at least ${spec.min}.` };
64
+ if (spec.max !== undefined && raw > spec.max) return { error: `${key} must be at most ${spec.max}.` };
65
+ return { value: raw };
66
+ }
67
+ case "Bool":
68
+ return typeof raw === "boolean" ? { value: raw } : bad();
69
+ case "Date": {
70
+ if (typeof raw !== "string" || !ISO_DATE.test(raw)) return bad();
71
+ const d = new Date(raw);
72
+ return Number.isNaN(d.getTime()) ? bad() : { value: d };
73
+ }
74
+ case "ID":
75
+ return typeof raw === "string" && UUID.test(raw) ? { value: raw.toLowerCase() } : bad();
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Validate a JSON request body against the endpoint's fields.
81
+ * `partial` is used for updates: every field is optional.
82
+ */
83
+ export function validateBody(specs: readonly FieldSpec[], body: unknown): Validated {
84
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
85
+ return { ok: false, field: "", message: "The request body must be a JSON object." };
86
+ }
87
+ const allowed = new Set(specs.map((s) => s.key));
88
+ for (const key of Object.keys(body)) {
89
+ if (!allowed.has(key)) {
90
+ const shown = key.length > 50 ? `${key.slice(0, 50)}…` : key;
91
+ return {
92
+ ok: false,
93
+ field: shown,
94
+ message: `Unknown field "${shown}". Allowed fields: ${[...allowed].join(", ") || "none"}.`,
95
+ };
96
+ }
97
+ }
98
+ const values = new Map<string, unknown>();
99
+ const record = body as Record<string, unknown>;
100
+ for (const spec of specs) {
101
+ if (!Object.hasOwn(record, spec.key)) {
102
+ if (spec.required) return { ok: false, field: spec.key, message: `${spec.key} is required.` };
103
+ continue;
104
+ }
105
+ const raw = record[spec.key];
106
+ if (raw === null) {
107
+ if (!spec.nullable) return { ok: false, field: spec.key, message: `${spec.key} cannot be null.` };
108
+ values.set(spec.key, null);
109
+ continue;
110
+ }
111
+ const r = validateValue(spec, raw);
112
+ if ("error" in r) return { ok: false, field: spec.key, message: r.error };
113
+ values.set(spec.key, r.value);
114
+ }
115
+ return { ok: true, values };
116
+ }
117
+
118
+ /** Validate a decoded path parameter. */
119
+ export function validatePathParam(part: Extract<PathPart, { param: string }>, raw: string): { value: unknown } | { error: string } {
120
+ const key = part.param;
121
+ switch (part.kind) {
122
+ case "Number":
123
+ if (!/^-?\d{1,10}$/.test(raw)) return { error: `${key} must be a whole number.` };
124
+ return validateValue({ key, kind: "Number" }, Number(raw));
125
+ case "Bool":
126
+ if (raw !== "true" && raw !== "false") return { error: `${key} must be true or false.` };
127
+ return { value: raw === "true" };
128
+ case "Text":
129
+ return validateValue({ key, kind: "Text", min: 1, max: MAX_PATH_TEXT }, raw);
130
+ default:
131
+ return validateValue({ key, kind: part.kind }, raw);
132
+ }
133
+ }