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
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "rizolang",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.1",
4
+ "description": "Rizo Lang: a secure, simple, full-stack web language for the AI era. Compiles to PostgreSQL and TypeScript.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://rizobot.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/chaitanyaaggarwal9/rizolang.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/chaitanyaaggarwal9/rizolang/issues"
13
+ },
14
+ "keywords": [
15
+ "rizo",
16
+ "rizolang",
17
+ "programming-language",
18
+ "compiler",
19
+ "postgresql",
20
+ "typescript",
21
+ "secure-by-default"
22
+ ],
23
+ "type": "module",
24
+ "bin": {
25
+ "rizolang": "build/src/bin.js"
26
+ },
27
+ "files": [
28
+ "build/src",
29
+ "runtime",
30
+ "docs",
31
+ "LICENSE",
32
+ "README.md"
33
+ ],
34
+ "engines": {
35
+ "node": ">=22.12.0"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.build.json",
39
+ "typecheck": "tsc -p tsconfig.json",
40
+ "test": "vitest run",
41
+ "test:watch": "vitest"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "26.6.6",
45
+ "@types/pg": "8.23.1",
46
+ "pg": "8.23.1",
47
+ "typescript": "7.0.2",
48
+ "vitest": "5.1.0"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Rizo Lang runtime: applies the SQL files in migrations/ to the database.
3
+ *
4
+ * - Each migration runs in its own transaction and is recorded in
5
+ * "_rizo_migrations" with a checksum, so it is applied exactly once.
6
+ * - A PostgreSQL advisory lock stops two deploys from migrating at once.
7
+ * - If an applied migration file was changed or deleted, nothing runs.
8
+ */
9
+ import { createHash } from "node:crypto";
10
+ import { readFileSync, readdirSync } from "node:fs";
11
+ import { fileURLToPath } from "node:url";
12
+ import pg from "pg";
13
+
14
+ export const MIGRATIONS_TABLE = '"_rizo_migrations"';
15
+ const MIGRATION_FILE = /^\d{4}_[a-z0-9_]+\.sql$/;
16
+ /** Arbitrary constant identifying the rizolang migration lock. */
17
+ const LOCK_ID = 727_201_401;
18
+
19
+ export interface Migration {
20
+ readonly name: string;
21
+ readonly sql: string;
22
+ readonly checksum: string;
23
+ }
24
+
25
+ export interface MigrateResult {
26
+ readonly applied: readonly string[];
27
+ readonly baselined: string | undefined;
28
+ }
29
+
30
+ /** Read the migration files of a directory, in order. */
31
+ export function readMigrations(dir: string): Migration[] {
32
+ return readdirSync(dir)
33
+ .filter((f) => MIGRATION_FILE.test(f))
34
+ .sort()
35
+ .map((name) => {
36
+ const sql = readFileSync(`${dir}/${name}`, "utf8");
37
+ return { name, sql, checksum: createHash("sha256").update(sql).digest("hex") };
38
+ });
39
+ }
40
+
41
+ export class MigrationError extends Error {}
42
+
43
+ /** A connected client, e.g. a `pg.Client` or a client from a pool. */
44
+ export interface MigrationClient {
45
+ query(sql: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
46
+ }
47
+
48
+ /**
49
+ * Apply pending migrations. With `baseline`, the first migration is recorded
50
+ * as applied without running it (for databases created from schema.sql).
51
+ */
52
+ export async function migrate(client: MigrationClient, migrations: readonly Migration[], options: { baseline?: boolean } = {}): Promise<MigrateResult> {
53
+ await client.query("SELECT pg_advisory_lock($1)", [LOCK_ID]);
54
+ try {
55
+ await client.query(
56
+ `CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} ("name" TEXT PRIMARY KEY, "checksum" TEXT NOT NULL, "applied_at" TIMESTAMPTZ NOT NULL DEFAULT now())`,
57
+ );
58
+ const done = new Map(
59
+ (await client.query(`SELECT "name", "checksum" FROM ${MIGRATIONS_TABLE}`)).rows.map((r) => [String(r["name"]), String(r["checksum"])]),
60
+ );
61
+ for (const [name, checksum] of done) {
62
+ const file = migrations.find((m) => m.name === name);
63
+ if (file === undefined) throw new MigrationError(`Migration ${name} was applied to this database but its file is missing. Restore it from version control.`);
64
+ if (file.checksum !== checksum) {
65
+ throw new MigrationError(`Migration ${name} was changed after it was applied. Restore the original file and put new changes in a new migration.`);
66
+ }
67
+ }
68
+
69
+ let baselined: string | undefined;
70
+ if (options.baseline) {
71
+ const first = migrations[0];
72
+ if (done.size > 0) throw new MigrationError("--baseline is only for a database that has no migrations recorded yet.");
73
+ if (first === undefined) throw new MigrationError("There are no migrations to baseline.");
74
+ await client.query(`INSERT INTO ${MIGRATIONS_TABLE} ("name", "checksum") VALUES ($1, $2)`, [first.name, first.checksum]);
75
+ done.set(first.name, first.checksum);
76
+ baselined = first.name;
77
+ }
78
+
79
+ const applied: string[] = [];
80
+ for (const m of migrations) {
81
+ if (done.has(m.name)) continue;
82
+ await client.query("BEGIN");
83
+ try {
84
+ await client.query(m.sql);
85
+ await client.query(`INSERT INTO ${MIGRATIONS_TABLE} ("name", "checksum") VALUES ($1, $2)`, [m.name, m.checksum]);
86
+ await client.query("COMMIT");
87
+ } catch (e) {
88
+ await client.query("ROLLBACK");
89
+ const reason = e instanceof Error ? e.message : String(e);
90
+ throw new MigrationError(
91
+ `Migration ${m.name} failed and was rolled back: ${reason}` +
92
+ (/null values|violates check|could not create unique/.test(reason)
93
+ ? "\nExisting rows do not fit the new rules. Fix or remove those rows, or make the field optional, then run again."
94
+ : ""),
95
+ );
96
+ }
97
+ applied.push(m.name);
98
+ }
99
+ return { applied, baselined };
100
+ } finally {
101
+ await client.query("SELECT pg_advisory_unlock($1)", [LOCK_ID]);
102
+ }
103
+ }
104
+
105
+ /** Entry point used by the generated migrate.ts. */
106
+ export async function runMigrations(dirUrl: URL): Promise<void> {
107
+ const url = process.env["DATABASE_URL"];
108
+ if (url === undefined || url === "") {
109
+ process.stderr.write("rizo: DATABASE_URL is not set.\n fix: Run DATABASE_URL=postgres://user:password@localhost:5432/app node migrate.ts\n");
110
+ process.exit(1);
111
+ }
112
+ const args = process.argv.slice(2);
113
+ const unknown = args.find((a) => a !== "--baseline");
114
+ if (unknown !== undefined) {
115
+ process.stderr.write(`rizo: unknown option "${unknown}". The only option is --baseline.\n`);
116
+ process.exit(1);
117
+ }
118
+ const client = new pg.Client({ connectionString: url });
119
+ await client.connect();
120
+ try {
121
+ const r = await migrate(client, readMigrations(fileURLToPath(dirUrl)), { baseline: args.includes("--baseline") });
122
+ if (r.baselined !== undefined) process.stdout.write(`rizo: recorded ${r.baselined} as already applied (baseline)\n`);
123
+ for (const name of r.applied) process.stdout.write(`rizo: applied ${name}\n`);
124
+ if (r.applied.length === 0) process.stdout.write("rizo: database is up to date\n");
125
+ } catch (e) {
126
+ process.stderr.write(`rizo: ${e instanceof Error ? e.message : String(e)}\n`);
127
+ process.exitCode = 1;
128
+ } finally {
129
+ await client.end();
130
+ }
131
+ }
@@ -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
+ }