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/docs/SPEC.md ADDED
@@ -0,0 +1,685 @@
1
+ # Rizo Lang Specification
2
+
3
+ Version 0.3 (draft) · Milestone 3: roles, pagination, accounts and migrations
4
+
5
+ Rizo Lang is a secure, simple, full-stack web language. Source files end in `.rz`. The compiler, `rizolang`, turns Rizo Lang into existing technology: a PostgreSQL schema, TypeScript types and a Node.js server. HTML and TypeScript frontends come later.
6
+
7
+ This document is the complete language reference. It is written for people and for AI models alike. If something is not described here, it is not part of the language.
8
+
9
+ > **Status:** `model`, `auth` and `api` blocks are available. `page` and other blocks are planned but are **not** available yet. Using them is a compile error (RZ0211).
10
+
11
+ ---
12
+
13
+ ## 1. Design rules
14
+
15
+ 1. **Dangerous mistakes are impossible, not just unlikely.** There is no raw SQL and no way to build a query from text.
16
+ 2. **Strict and clear.** Every value has a static type. Every error says what went wrong, where and how to fix it.
17
+ 3. **Small.** The whole language fits in this document.
18
+ 4. **Secure by default.**
19
+ - Passwords are hashed automatically and can never be returned in an API response or logged.
20
+ - Inputs are validated automatically.
21
+ - Login and ownership checks are part of the syntax.
22
+
23
+ ---
24
+
25
+ ## 2. Files and basic syntax
26
+
27
+ - A source file is UTF-8 text with the extension `.rz`.
28
+ - A file contains `model` blocks, at most one `auth` line, and `api` blocks, in any order.
29
+ - Comments start with `//` and run to the end of the line. A comment after a path needs a space before it.
30
+ - Whitespace separates tokens. Indentation has no meaning, but two spaces are conventional.
31
+ - **One item per line.** Each field, and each statement in an `api` block, goes on its own line. Commas appear only between query arguments.
32
+ - Names contain only ASCII letters and digits and start with a letter. Underscores and hyphens are not allowed in names.
33
+ - Numbers are whole numbers, optionally negative: `100`, `0`, `-5`. Decimals are not allowed.
34
+ - There are no quoted strings.
35
+ - Lines and columns in error messages start at 1. A tab counts as one column.
36
+
37
+ ---
38
+
39
+ ## 3. Models
40
+
41
+ A model describes one kind of record stored in the database.
42
+
43
+ ```rizo
44
+ model User {
45
+ email: Email unique private
46
+ password: Password
47
+ name: Text max 100
48
+ }
49
+
50
+ model Post {
51
+ author: User
52
+ title: Text max 200
53
+ published: Bool
54
+ }
55
+ ```
56
+
57
+ - A model starts with the lowercase keyword `model`, then a PascalCase name, then `{`. It ends with `}`.
58
+ - A model has at least one field. Model names are unique in a file, and field names are unique in a model.
59
+ - A field is written `name: Type` followed by zero or more modifiers, all on one line.
60
+ - Every model automatically gets an `id: ID` field (a UUID generated by the database). **Do not declare `id`.**
61
+
62
+ ### 3.1 Field types
63
+
64
+ | Type | Meaning | PostgreSQL | TypeScript | Modifiers allowed |
65
+ |------------|-----------------------------------------------|---------------|----------------|--------------------------------------|
66
+ | `Text` | Text. At most 10,000 characters by default. | `TEXT` | `string` | unique, optional, private, min, max |
67
+ | `Number` | Whole number, −2147483648 to 2147483647. | `INTEGER` | `number` | unique, optional, private, min, max |
68
+ | `Bool` | `true` or `false`. | `BOOLEAN` | `boolean` | optional, private |
69
+ | `Email` | Email address, 3–254 chars, stored lowercase. | `TEXT` | `string` | unique, optional, private, min, max |
70
+ | `Password` | Stored only as a salted hash. | `TEXT` (`<name>_hash`) | `PasswordHash` | optional, min, max |
71
+ | `Date` | Date and time, in UTC. | `TIMESTAMPTZ` | `Date` | unique, optional, private |
72
+ | `ID` | A UUID. | `UUID` | `string` | unique, optional, private |
73
+ | *Model* | A link to a record of that model. | `UUID` (`<name>_id`) + foreign key | `string` | unique, optional, private |
74
+
75
+ - `Number` is for whole numbers. Store money as cents.
76
+ - `Email` values are trimmed and lowercased. They must look like `name@domain.tld`.
77
+ - `Password`:
78
+ - The plain-text password is never stored. `password` is stored as `password_hash`.
79
+ - `min` and `max` limit the plain-text length. The defaults are 8 and 128, and you can only tighten them.
80
+ - A field named `password`, `passwd`, `pwd`, `passcode` or `passphrase`, or ending in `Password`, `Passwd`, `Passcode` or `Passphrase`, must have the type `Password`.
81
+ - **Links:** a field whose type is another model's name, such as `author: User`.
82
+ - It stores that record's id in the column `<name>_id`, with a foreign key and an index.
83
+ - Models may link in any order, and a model may link to itself.
84
+ - A required link cannot point to a record that doesn't exist. A record that others link to cannot be deleted.
85
+ - When the linked record is deleted, an optional link becomes `null`.
86
+
87
+ ### 3.2 Modifiers
88
+
89
+ Modifiers come after the type, on the same line, in any order, each at most once.
90
+
91
+ | Modifier | Meaning |
92
+ |------------|------------------------------------------------------------------------------------------------|
93
+ | `unique` | No two records may have the same value. |
94
+ | `optional` | The value may be missing (`null`). Without it, the field is required. |
95
+ | `private` | Stored and accepted as input, but **never returned** by any endpoint, and not allowed in filters or ordering. |
96
+ | `min N` | Text, Email, Password: minimum length in characters. Number: minimum value. |
97
+ | `max N` | Text, Email, Password: maximum length in characters. Number: maximum value. |
98
+
99
+ | Type | Default min | Default max | Allowed range for `min`/`max` |
100
+ |------------|-------------|-------------|-------------------------------|
101
+ | `Text` | none | 10000 | 0 to 1000000 (`max` ≥ 1) |
102
+ | `Email` | 3 | 254 | 3 to 254 |
103
+ | `Password` | 8 | 128 | 8 to 128 |
104
+ | `Number` | none | none | −2147483648 to 2147483647 |
105
+
106
+ - `min` must be ≤ `max` after defaults are applied.
107
+ - `unique` is not allowed on `Bool` or `Password`.
108
+ - `min` and `max` are not allowed on `Bool`, `Date`, `ID` or links.
109
+ - `private` is not allowed on `Password`, which is always hidden.
110
+
111
+ ### 3.3 Naming
112
+
113
+ | Thing | Style | Example | In PostgreSQL |
114
+ |------------|------------|---------------------|-----------------------------|
115
+ | Model name | PascalCase | `BlogPost` | table `blog_posts` |
116
+ | Field name | camelCase | `firstName` | column `first_name` |
117
+ | Link field | camelCase | `author: User` | column `author_id` |
118
+
119
+ - **Table names** are the snake_case plural of the model name:
120
+ - `+s` by default,
121
+ - `+es` after `s`, `x`, `z`, `ch` or `sh`,
122
+ - consonant + `y` becomes `ies`.
123
+ - **Reserved names:**
124
+ - Model names: the seven type names, plus `PasswordHash`, `String`, `Boolean`, `Object`, `Array`, `Promise`, `Record`, `Error`, `Map`, `Set`, `Symbol`, `BigInt`, `Function`, `JSON`, `Math`, `Partial` and `Readonly`.
125
+ - Field name: `id`.
126
+ - Two names must never produce the same table, column or TypeScript type. Table and column names must be at most 63 characters.
127
+
128
+ ---
129
+
130
+ ## 4. Login: the `auth` line
131
+
132
+ ```rizo
133
+ auth User by email
134
+ ```
135
+
136
+ This line turns on accounts and sessions. It is written `auth <Model> by <field>`, optionally followed by `roles <name>, <name>, ...`.
137
+
138
+ Rules (error RZ0317):
139
+ - The field must be declared as `Email unique`, and it must not be optional.
140
+ - The model must have exactly one required `Password` field.
141
+ - A link from the model to itself must be optional.
142
+ - There can be at most one `auth` line per file.
143
+ - Roles, if declared, are camelCase names, at most 20 of them, and must include `admin`. The model must not have its own field named `role`.
144
+
145
+ It adds these endpoints. Paths under `/auth` are reserved.
146
+
147
+ | Endpoint | Body | Result |
148
+ |---------------------|-----------------------------------|-----------------------------------------------|
149
+ | `POST /auth/signup` | The model's fields, like `User.input` | 201 with `User.public`, and logs the user in |
150
+ | `POST /auth/login` | `{ "email": ..., "password": ... }` | 200 with `User.public`, or 401 |
151
+ | `POST /auth/logout` | none | 204; the session is deleted |
152
+ | `GET /auth/me` | none | 200 with `User.public`, or 401 |
153
+ | `PATCH /auth/me` | Any profile fields | 200 with `User.public`. Every field is optional. The login email, the password, the role and links to the auth model can't be changed here |
154
+ | `POST /auth/password` | `{ "currentPassword": ..., "newPassword": ... }` | 204. Every other session of the account is logged out |
155
+ | `POST /auth/logout-all` | none | 204. Every session of the account is deleted, including this one |
156
+ | `DELETE /auth/me` | `{ "password": ... }` | 204, and the account and its sessions are deleted. 409 if other records still link to it |
157
+
158
+ **How login works**
159
+ - Passwords are hashed with scrypt (N=2^15, r=8, p=3) and a random salt.
160
+ - A wrong password and an unknown email give the same 401 response, in about the same time.
161
+ - After 5 failed logins for an account, or 20 from one address, within 15 minutes, login answers 429. Signups are limited to 10 per hour per address.
162
+
163
+ ### 4.1 Roles
164
+
165
+ ```rizo
166
+ auth User by email roles admin, editor
167
+ ```
168
+
169
+ Each account has at most one role, or none.
170
+ - **Storage:** the role is kept in a hidden `role` column that only accepts the declared names.
171
+ - **Never from or to clients:** the role is never accepted in a request body and never appears in any response or public type.
172
+ - **Checked on every request:** a role change applies to existing sessions immediately.
173
+
174
+ **Assigning roles.** Admins use a built-in endpoint:
175
+
176
+ | Endpoint | Body | Result |
177
+ |----------|------|--------|
178
+ | `PUT /auth/users/:id/role` | `{ "role": "editor" }` or `{ "role": null }` | 200 `{ "id", "role" }`. Admins only: 401 if not logged in, 403 if not an admin or if it's your own account |
179
+
180
+ **The first admin.** Sign up normally, then start the server with `RIZO_ADMIN_EMAILS=you@example.com`. At startup, accounts that **already exist** with a listed email become admins. Accounts created later are never promoted this way, so nobody can claim admin by signing up with a listed email.
181
+
182
+ **Sensitive changes:**
183
+ - Changing the password and deleting the account need the current password.
184
+ - A wrong password gets 403 and counts toward the same lockout as login.
185
+ - New passwords follow the Password field's `min` and `max`.
186
+ - Changing the login email isn't available yet, because it needs email verification.
187
+
188
+ **How sessions work**
189
+ - The session is a random 256-bit token in the `rizo_session` cookie: `HttpOnly; Secure; SameSite=Lax; Path=/`, lasting 7 days.
190
+ - The database stores only a SHA-256 hash of the token, in the table `_rizo_sessions`.
191
+
192
+ ---
193
+
194
+ ## 5. Endpoints: `api` blocks
195
+
196
+ ```rizo
197
+ api GET /posts/:id -> Post.public {
198
+ public
199
+ return db.Post.find(id)
200
+ }
201
+ ```
202
+
203
+ An endpoint has a header, an access rule, an optional owner rule and one return line:
204
+
205
+ ```
206
+ api <METHOD> <path> [-> <return type>] {
207
+ public | requires login
208
+ [requires role <role>, <role>]
209
+ [requires owner <link field> [or role <role>, <role>]]
210
+ return db.<Model>.<action>(<arguments>)
211
+ }
212
+ ```
213
+
214
+ ### 5.1 Header
215
+
216
+ - **Method:** `GET`, `POST`, `PUT`, `PATCH` or `DELETE`, in uppercase.
217
+ - **Path:** starts with `/`.
218
+ - Static segments use lowercase letters, digits and single hyphens.
219
+ - Parameters are written `:camelCase`, for example `/posts/:id`.
220
+ - No trailing slash, no empty segment, and no parameter may appear twice.
221
+ - `me` and `body` cannot be parameter names.
222
+ - **Return type:**
223
+ - `-> Model.public` for one record.
224
+ - `-> list Model.public` for many records.
225
+ - Nothing at all for `delete`.
226
+ - Endpoints can only return the `.public` view.
227
+
228
+ ### 5.2 Access
229
+
230
+ Every endpoint must contain **exactly one** of these lines (RZ0318):
231
+
232
+ - `public`: anyone may call the endpoint.
233
+ - `requires login`: the caller must have a valid session, otherwise the response is 401.
234
+
235
+ There is no default, so an endpoint can never be left open by accident. `requires login` needs an `auth` line.
236
+
237
+ `requires owner <field>` adds an ownership check (RZ0329):
238
+ - It needs `requires login`.
239
+ - `<field>` must be a link to the auth model, for example `author`.
240
+ - It works with `find`, `update` and `delete`.
241
+ - The check is part of the SQL `WHERE` clause. A record owned by someone else behaves exactly like a missing one (404), so callers can't tell that it exists.
242
+ - It is **required** for `update` and `delete` on a model that links to the auth model (RZ0331), unless the endpoint has `requires role`. That way one user can never change another user's records.
243
+ - `requires owner author or role admin` also lets the listed roles act on records they don't own. This check is part of the `WHERE` clause too.
244
+
245
+ `requires role admin, editor` only lets users with one of the listed roles call the endpoint; anyone else gets 403.
246
+ - It needs `requires login`, and the roles must be declared on the `auth` line (RZ0332).
247
+ - With `update` or `delete`, it lets those roles change any record.
248
+ - A public endpoint can't update or delete such a model either: `requires owner` needs `requires login`.
249
+
250
+ ### 5.3 Queries
251
+
252
+ The return line is `return db.<Model>.<action>(...)`. There are five actions. Each one has exactly one allowed method (RZ0328), so `GET` never changes data.
253
+
254
+ | Action | Method | Arguments | Result |
255
+ |----------|---------------|---------------------------------------------------|-------------------------------------------|
256
+ | `find` | GET | `(id)`: a path parameter | 200 with the record, or 404 |
257
+ | `list` | GET | filters, `order`, `limit` (all optional) | 200 with `{ "items": [...], "next": ... }` (§5.4) |
258
+ | `create` | POST | `(body)` then optional `field = value` | 201 with the new record |
259
+ | `update` | PUT or PATCH | `(id, body)` | 200 with the updated record, or 404 |
260
+ | `delete` | DELETE | `(id)` | 204, or 404 |
261
+
262
+ **`list` arguments**, separated by commas:
263
+ - `field = value`: filters by equality, combined with AND.
264
+ - `order field` or `order field desc`: sorts. The default order is by `id`. You can't order by an `optional` field, because pages need a sort value in every record.
265
+ - `limit N`: the largest page size, from 1 to 100. The default is 50.
266
+
267
+ Hidden fields (Password or `private`) cannot be used in filters or ordering.
268
+
269
+ **Values** on the right of `=`:
270
+ - `me`: the logged-in user. It only works with a link to the auth model, and is not allowed in public endpoints.
271
+ - A path parameter's name, such as `userId`. Its type comes from the field it's compared with.
272
+ - A whole number, for `Number` fields.
273
+ - `true` or `false`, for `Bool` fields.
274
+
275
+ **`body`** is the JSON request body. It is validated before the query runs:
276
+ - Unknown keys are rejected.
277
+ - Required fields must be present.
278
+ - `null` is only allowed for optional fields.
279
+ - Every limit from the model is checked.
280
+ - In `update`, every field is optional, and only the fields that are sent are changed.
281
+
282
+ **Ownership is never taken from the client** (RZ0326):
283
+ - A link to the auth model is never part of `body`.
284
+ - In `create`, it must be assigned `= me`: `db.Post.create(body, author = me)`.
285
+ - `update` can never change it.
286
+
287
+ The auth model itself cannot be created, updated or deleted through `api` blocks (RZ0327). Accounts are created through `/auth/signup`.
288
+
289
+ Every path parameter must be used in the query (RZ0323).
290
+
291
+ ### 5.4 Pages
292
+
293
+ A `list` endpoint returns one page at a time:
294
+
295
+ ```
296
+ GET /posts?limit=10 → { "items": [ ...10 posts... ], "next": "WyJIZWxsbyIs..." }
297
+ GET /posts?limit=10&after=WyJI... → { "items": [ ...the next posts... ], "next": null }
298
+ ```
299
+
300
+ - `limit` is optional. It must be a whole number from 1 to the endpoint's `limit`, which is also the default.
301
+ - `after` is the `next` value from the previous page. `next` is `null` on the last page.
302
+ - Pages continue exactly after the last record of the previous page, ordered by the sort field and then by `id`. Records added between requests can't cause records to be skipped or repeated.
303
+ - Cursors are opaque. Clients must not build or change them. An invalid cursor is rejected with 400.
304
+ - Endpoints accept no other query parameters. Any unknown or repeated parameter gets 400, on every endpoint.
305
+
306
+ ### 5.5 A complete example
307
+
308
+ ```rizo
309
+ auth User by email
310
+
311
+ model User {
312
+ email: Email unique private
313
+ password: Password min 12
314
+ name: Text max 100
315
+ }
316
+
317
+ model Post {
318
+ author: User
319
+ title: Text min 1 max 200
320
+ published: Bool
321
+ }
322
+
323
+ api GET /posts -> list Post.public {
324
+ public
325
+ return db.Post.list(published = true, order title, limit 20)
326
+ }
327
+
328
+ api POST /posts -> Post.public {
329
+ requires login
330
+ return db.Post.create(body, author = me)
331
+ }
332
+
333
+ api PATCH /posts/:id -> Post.public {
334
+ requires login
335
+ requires owner author
336
+ return db.Post.update(id, body)
337
+ }
338
+
339
+ api DELETE /posts/:id {
340
+ requires login
341
+ requires owner author
342
+ return db.Post.delete(id)
343
+ }
344
+ ```
345
+
346
+ ---
347
+
348
+ ## 6. What the compiler generates
349
+
350
+ `rizolang build app.rz` writes everything to `dist/`.
351
+
352
+ | File | Contents |
353
+ |----------------------|------------------------------------------------------------------------------|
354
+ | `schema.sql` | PostgreSQL 13+ tables, constraints, foreign keys and the sessions table, inside one transaction |
355
+ | `types.ts` | `Model`, `ModelPublic` and `ModelInput` types for every model |
356
+ | `routes.ts` | Every endpoint as data, with its SQL written out in full |
357
+ | `migrate.ts`, `migrations/` | Applies the migrations from your project's `migrations/` folder (§6, Migrations) |
358
+ | `server.ts` | The entry point |
359
+ | `runtime/` | The Rizo runtime: validation, sessions, password hashing and the HTTP server |
360
+ | `package.json`, `tsconfig.json` | To install `pg` and type-check the app |
361
+
362
+ `routes.ts`, `server.ts`, `runtime/`, `package.json` and `tsconfig.json` are written only when the file has an `auth` line or `api` blocks.
363
+
364
+ The three types:
365
+ - `User` is the stored record. It is for server use only, and holds a `PasswordHash`.
366
+ - `UserPublic` (`User.public`) leaves out Password and `private` fields.
367
+ - `UserInput` (`User.input`) is what a client sends. Passwords are plain text here, and links to the auth model are left out.
368
+
369
+ ### Migrations
370
+
371
+ Every build compares your models with the last build and records the difference in `migrations/`, next to your `.rz` file. Commit this folder to version control.
372
+
373
+ | File | Contents |
374
+ |------|----------|
375
+ | `migrations/0001_initial.sql` | The first schema |
376
+ | `migrations/0002_add_column_posts_views.sql`, … | One file per build that changed the schema |
377
+ | `migrations/rizo-schema.json` | A snapshot of the schema after the last migration. Don't edit it |
378
+
379
+ **Refused changes.** These changes would delete data, so the build stops (RZ0904) and writes no files, unless you run `rizolang build app.rz --allow-data-loss`:
380
+ - removing a model or field,
381
+ - changing a field's type,
382
+ - removing a role.
383
+
384
+ Renaming looks like removing and adding, so it is refused too. Keep the old name.
385
+
386
+ **Other changes** are generated automatically: adding models, fields and links, and changing limits, `unique`, `optional` and roles.
387
+ - Making a field required, adding a required field, or tightening limits can fail if existing rows don't fit.
388
+ - In that case the migration is rolled back and nothing changes.
389
+
390
+ **Applying migrations.** `node migrate.ts` (in `dist/`) applies pending migrations in order.
391
+ - Each migration runs in one transaction and is recorded in the `_rizo_migrations` table.
392
+ - A lock stops two deploys from migrating at the same time.
393
+ - If an applied migration file was edited or deleted, nothing runs.
394
+
395
+ **Existing databases.** If a database was created from `schema.sql` before you used migrations, run `node migrate.ts --baseline` once. It records `0001_initial.sql` as already applied.
396
+
397
+ ### Running the server
398
+
399
+ Needs Node.js 22.18 or newer.
400
+
401
+ ```sh
402
+ cd dist && npm install
403
+ DATABASE_URL=postgres://user:pass@localhost:5432/app node migrate.ts
404
+ DATABASE_URL=postgres://user:pass@localhost:5432/app node server.ts
405
+ ```
406
+
407
+ To start a brand-new database, `psql "$DATABASE_URL" -f schema.sql` works too. Then run `node migrate.ts --baseline` so later migrations apply on top of it.
408
+
409
+ | Variable | Default | Meaning |
410
+ |-----------------------------|-------------|------------------------------------------------------------|
411
+ | `DATABASE_URL` | (required) | PostgreSQL connection string |
412
+ | `PORT`, `HOST` | `3000`, `127.0.0.1` | Where to listen |
413
+ | `RIZO_ALLOWED_ORIGINS` | none | Comma-separated extra origins allowed to send POST, PUT, PATCH or DELETE requests |
414
+ | `RIZO_TRUST_PROXY` | off | `1` to read the client IP from `X-Forwarded-For` (only behind a trusted proxy) |
415
+ | `RIZO_DEV_INSECURE_COOKIES` | off | `1` to drop the `Secure` cookie flag for local http. **Never in production.** |
416
+ | `RIZO_DB_POOL_SIZE` | `10` | Maximum number of database connections |
417
+ | `RIZO_ADMIN_EMAILS` | none | Comma-separated emails of **existing** accounts to make admins at startup (§4.1) |
418
+
419
+ ### HTTP behaviour
420
+
421
+ - **Requests:**
422
+ - Only `list` endpoints accept query parameters (`limit` and `after`, §5.4). Any other query parameter gets 400.
423
+ - Bodies must be JSON (`Content-Type: application/json`) and at most 1 MB. Endpoints without `body` reject a request body.
424
+ - Path parameters are validated by type. An invalid id gets 400 before any query runs.
425
+ - **Responses** are JSON:
426
+ - Errors look like `{ "error": { "code": "...", "message": "...", "field": "..." } }`.
427
+ - Status codes: 400 invalid input, 401 not logged in, 403 cross-site request or missing role, 404 not found, 405 wrong method, 409 duplicate or still in use, 413 too large, 415 not JSON, 429 too many attempts, 500 internal error (with a request id).
428
+ - Every response carries `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and a `Content-Security-Policy` that allows nothing.
429
+ - **Cross-site requests:** POST, PUT, PATCH and DELETE requests with an `Origin` header from another site are rejected with 403.
430
+ - **Logs:** one line per request: the method, the route pattern (such as `/posts/:id`), the status, the time and a request id. Logs never contain URLs with values, bodies, cookies or passwords.
431
+
432
+ ---
433
+
434
+ ## 7. Security guarantees
435
+
436
+ These are enforced by the compiler and the runtime, and covered by `tests/security.test.ts` and `tests/e2e.test.ts`:
437
+
438
+ 1. A Password or `private` field never appears in a `.public` type or in any response.
439
+ 2. A Password is never stored in plain text.
440
+ 3. All SQL is written at compile time. Request data only fills `$1, $2, …` parameters, and names can't break out of their quotes.
441
+ 4. Every endpoint declares its access, and `requires owner` is enforced inside the query. Records that belong to a user can only be changed or deleted by that user.
442
+ 5. A record's owner is always the logged-in user, and a user's role is only ever set by an admin. Neither is taken from the request body.
443
+ 6. All input is validated against the model before it reaches the database, and unknown fields are rejected.
444
+ 7. `GET` endpoints never change data. Cross-site writes are rejected.
445
+ 8. When there is any compile error, or a change would delete data without `--allow-data-loss`, no output is written.
446
+
447
+ ---
448
+
449
+ ## 8. Errors
450
+
451
+ ```
452
+ app.rz:3:9 error RZ0301: Unknown field type "String" on field "User.name".
453
+ 3 | name: String
454
+ | ^^^^^^
455
+ fix: Use "Text" instead. Valid types: Text, Number, Bool, Email, Password, Date, ID, or a model name (User).
456
+ ```
457
+
458
+ - The first line is always `<file>:<line>:<column> error <code>: <message>`. The `fix:` line says exactly what to change.
459
+ - Syntax errors (RZ01xx, RZ02xx) stop at the first error. Checking errors (RZ03xx) are all reported together.
460
+ - `rizolang` exits with 0 on success and 1 on any error.
461
+
462
+ | Code | Meaning |
463
+ |--------|-------------------------------------------------------------------------|
464
+ | RZ0101 | Unexpected character (semicolon, underscore, quote…) |
465
+ | RZ0102 | Invalid number (decimal, too large, letters attached) |
466
+ | RZ0201 | Expected `model`, `auth` or `api` at the top level |
467
+ | RZ0202 | Missing model name |
468
+ | RZ0203 | Missing `{` |
469
+ | RZ0204 | Expected a field name or `}` |
470
+ | RZ0205 | Missing `:` after a field name |
471
+ | RZ0206 | Missing field type |
472
+ | RZ0207 | Unknown modifier |
473
+ | RZ0208 | Missing number after `min`/`max` |
474
+ | RZ0209 | Field or statement does not start on a new line |
475
+ | RZ0210 | Block missing its closing `}` |
476
+ | RZ0211 | Block type not available yet (e.g. `page`) |
477
+ | RZ0212 | Unexpected token after a field or statement |
478
+ | RZ0213 | Missing or invalid HTTP method |
479
+ | RZ0214 | Missing path |
480
+ | RZ0215 | Invalid return type (must be `Model.public` or `list Model.public`) |
481
+ | RZ0216 | Unknown statement in an `api` block |
482
+ | RZ0217 | Invalid query syntax |
483
+ | RZ0218 | Invalid `auth` line |
484
+ | RZ0219 | Missing role name in a role list |
485
+ | RZ0301 | Unknown field type |
486
+ | RZ0302 | Modifier not allowed on this type |
487
+ | RZ0303 | Modifier repeated |
488
+ | RZ0304 | `min` greater than `max` |
489
+ | RZ0305 | `min`/`max` value out of range |
490
+ | RZ0306 | Duplicate model name |
491
+ | RZ0307 | Duplicate field name |
492
+ | RZ0308 | Field named `id` (it is automatic) |
493
+ | RZ0309 | Model name not PascalCase |
494
+ | RZ0310 | Field name not camelCase |
495
+ | RZ0311 | Reserved model name |
496
+ | RZ0312 | Two names map to the same table, column or TypeScript type |
497
+ | RZ0313 | Model has no fields |
498
+ | RZ0314 | Name too long for PostgreSQL |
499
+ | RZ0315 | Password-like field (e.g. `password`) not using `Password` |
500
+ | RZ0316 | Unknown model |
501
+ | RZ0317 | Invalid `auth` model |
502
+ | RZ0318 | Endpoint access missing, repeated or contradictory |
503
+ | RZ0319 | Login used without an `auth` line |
504
+ | RZ0320 | Missing, repeated or misplaced `return` line |
505
+ | RZ0321 | Return type does not match the query |
506
+ | RZ0322 | Invalid path |
507
+ | RZ0323 | Unknown or unused path parameter |
508
+ | RZ0324 | Duplicate endpoint |
509
+ | RZ0325 | Invalid query action or arguments |
510
+ | RZ0326 | Link to the auth model not set to `me` |
511
+ | RZ0327 | Creating, changing or deleting the auth model through `api` |
512
+ | RZ0328 | HTTP method does not match the query action |
513
+ | RZ0329 | Invalid `requires owner` |
514
+ | RZ0330 | `me` used in a public endpoint |
515
+ | RZ0331 | `update` or `delete` of an owned record without `requires owner` |
516
+ | RZ0332 | Unknown role, or roles used without declaring them |
517
+ | RZ0901 | Cannot read the input file |
518
+ | RZ0902 | Input file does not end in `.rz` |
519
+ | RZ0903 | Wrong command-line usage |
520
+ | RZ0904 | The change would delete data (needs `--allow-data-loss`) |
521
+ | RZ0905 | `migrations/rizo-schema.json` is missing or damaged |
522
+
523
+ ---
524
+
525
+ ## 9. Common mistakes
526
+
527
+ The examples below use the `User` and `Post` models from §3.
528
+
529
+ **Types from other languages.**
530
+
531
+ ```rizo
532
+ // Wrong
533
+ name: String
534
+ age: Int
535
+ active: Boolean
536
+ createdAt: DateTime
537
+
538
+ // Right
539
+ name: Text
540
+ age: Number
541
+ active: Bool
542
+ createdAt: Date
543
+ ```
544
+
545
+ **Commas, semicolons, decorators or arguments in fields.**
546
+
547
+ ```rizo
548
+ // Wrong
549
+ email: Email, name: Text;
550
+ name: Text(100)
551
+ email: Email @unique
552
+ nickname?: Text
553
+
554
+ // Right
555
+ name: Text max 100
556
+ email: Email unique
557
+ nickname: Text optional
558
+ ```
559
+
560
+ **Declaring `id`, or snake_case names.**
561
+
562
+ ```rizo
563
+ // Wrong
564
+ model blog_post {
565
+ id: ID
566
+ first_name: Text
567
+ }
568
+
569
+ // Right
570
+ model BlogPost {
571
+ firstName: Text
572
+ }
573
+ ```
574
+
575
+ **Weak or plain-text passwords.**
576
+
577
+ ```rizo
578
+ // Wrong
579
+ password: Text
580
+ password: Password unique min 4
581
+
582
+ // Right
583
+ password: Password min 12
584
+ ```
585
+
586
+ **Forgetting to say who may call an endpoint.**
587
+
588
+ ```rizo
589
+ // Wrong
590
+ api GET /posts -> list Post.public {
591
+ return db.Post.list()
592
+ }
593
+
594
+ // Right
595
+ api GET /posts -> list Post.public {
596
+ public
597
+ return db.Post.list()
598
+ }
599
+ ```
600
+
601
+ **Letting the client choose the owner.**
602
+
603
+ ```rizo
604
+ // Wrong
605
+ api POST /posts -> Post.public {
606
+ requires login
607
+ return db.Post.create(body)
608
+ }
609
+
610
+ // Right
611
+ api POST /posts -> Post.public {
612
+ requires login
613
+ return db.Post.create(body, author = me)
614
+ }
615
+ ```
616
+
617
+ **Changing data without an ownership check, or with the wrong method.**
618
+
619
+ ```rizo
620
+ // Wrong
621
+ api GET /posts/:id/delete {
622
+ requires login
623
+ return db.Post.delete(id)
624
+ }
625
+
626
+ // Right
627
+ api DELETE /posts/:id {
628
+ requires login
629
+ requires owner author
630
+ return db.Post.delete(id)
631
+ }
632
+ ```
633
+
634
+ **Returning the full record instead of the public view.**
635
+
636
+ ```rizo
637
+ // Wrong
638
+ api GET /users/:id -> User {
639
+ public
640
+ return db.User.find(id)
641
+ }
642
+
643
+ // Right
644
+ api GET /users/:id -> User.public {
645
+ public
646
+ return db.User.find(id)
647
+ }
648
+ ```
649
+
650
+ ---
651
+
652
+ ## 10. Grammar
653
+
654
+ ```ebnf
655
+ file = { model | auth | api } ;
656
+ model = "model" NAME "{" { field } "}" ;
657
+ field = NAME ":" TYPE { modifier } NEWLINE ;
658
+ modifier = "unique" | "optional" | "private" | "min" INT | "max" INT ;
659
+ TYPE = "Text" | "Number" | "Bool" | "Email" | "Password" | "Date" | "ID" | NAME ;
660
+ auth = "auth" NAME "by" NAME [ "roles" NAME { "," NAME } ] NEWLINE ;
661
+ api = "api" METHOD PATH [ "->" rettype ] "{" { statement NEWLINE } "}" ;
662
+ METHOD = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" ;
663
+ PATH = "/" [ segment { "/" segment } ] ;
664
+ segment = LOWER { LOWER | DIGIT | "-" } | ":" NAME ;
665
+ rettype = [ "list" ] NAME "." "public" ;
666
+ statement = "public" | "requires" "login" | "requires" "role" NAME { "," NAME }
667
+ | "requires" "owner" NAME [ "or" "role" NAME { "," NAME } ] | "return" query ;
668
+ query = "db" "." NAME "." ACTION "(" [ arg { "," arg } ] ")" ;
669
+ ACTION = "find" | "list" | "create" | "update" | "delete" ;
670
+ arg = NAME | NAME "=" value | "order" NAME [ "asc" | "desc" ] | "limit" INT ;
671
+ value = NAME | INT | "true" | "false" ;
672
+ NAME = LETTER { LETTER | DIGIT } ;
673
+ INT = [ "-" ] DIGIT { DIGIT } ;
674
+ comment = "//" { any character except newline } ;
675
+ ```
676
+
677
+ ---
678
+
679
+ ## 11. Planned (not available yet)
680
+
681
+ These are **not** part of the language yet. Using them is an error.
682
+
683
+ - Pagination, and filters other than `=`.
684
+ - Changing the login email, and password reset by email (these need email verification).
685
+ - Frontend `page` blocks.