@protobase/cli 0.122.0 → 0.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/auth/migration-file.js +3 -1
  2. package/dist/auth/register.js +1 -0
  3. package/dist/auth/write-migration.js +27 -10
  4. package/dist/cli/package.js +1 -1
  5. package/dist/dev/dev-relay.js +1 -1
  6. package/dist/doctor/startup.js +1 -1
  7. package/dist/main.js +1 -1
  8. package/dist/migration/load-project.js +6 -7
  9. package/dist/migration/migrate-project.js +5 -3
  10. package/dist/migration/parts.js +5 -8
  11. package/dist/migration/plan-migrations.js +25 -0
  12. package/dist/migration/register.js +75 -11
  13. package/dist/migration/snapshot/auth-difference.js +37 -0
  14. package/dist/migration/snapshot/auth-target.js +13 -0
  15. package/dist/migration/snapshot/check.js +26 -0
  16. package/dist/migration/snapshot/consistency.js +29 -0
  17. package/dist/migration/snapshot/custom.js +39 -0
  18. package/dist/migration/snapshot/drop.js +64 -0
  19. package/dist/migration/snapshot/header.js +34 -0
  20. package/dist/migration/snapshot/lint-custom.js +23 -0
  21. package/dist/migration/snapshot/migration-files.js +30 -0
  22. package/dist/migration/snapshot/next-snapshot.js +40 -0
  23. package/dist/migration/snapshot/preconditions.js +25 -0
  24. package/dist/migration/snapshot/run-migration.js +50 -0
  25. package/dist/migration/snapshot/snapshot-file.js +33 -0
  26. package/dist/migration/snapshot/up.js +24 -0
  27. package/dist/migration/snapshot/write-file.js +24 -0
  28. package/dist/migration/summary.js +6 -6
  29. package/dist/supabase/dump-phase.js +3 -2
  30. package/dist/supabase/load-phase.js +5 -0
  31. package/dist/supabase/project-users.js +4 -3
  32. package/dist/supabase/storage-copy.js +1 -1
  33. package/dist/supabase/store-migrations.js +42 -4
  34. package/dist/users/password.js +1 -1
  35. package/package.json +9 -8
  36. package/skills/protobase/references/features/build-and-run.md +2 -1
  37. package/skills/protobase/references/features/data-model.md +1 -0
  38. package/skills/protobase/references/features/email-and-public-forms.md +2 -1
  39. package/skills/protobase/references/reference/api.md +1 -1
  40. package/skills/protobase/references/reference/auth.md +1 -1
  41. package/skills/protobase/references/reference/cli.md +26 -6
  42. package/skills/protobase/references/reference/config/api.md +9 -1
  43. package/skills/protobase/references/reference/data-config.md +36 -0
  44. package/skills/protobase/references/reference/email.md +20 -4
  45. package/dist/migration/write-migrations.js +0 -32
@@ -69,6 +69,7 @@ export const repairs = resource('repairs')
69
69
  | `.checks({ tasks_parked_by_hand: { label: '{title} waits for a day.' } })` | The database checks whose refusal the API names, each by its constraint name, with the label the app shows. See [Checks the database makes](#checks-the-database-makes). |
70
70
  | `.openExisting((r) => [r.organization_id, r.member_key])` | A unique key of the table whose conflict on create opens the record already holding those values, such as a direct message with the same members. See [Opening an existing record](#opening-an-existing-record). |
71
71
  | `.validate((record) => issues)` | A rule over the whole record, run after the field checks on every create and update. It returns `[{ field, message }]` or `undefined`; issues answer `400` with the field named. |
72
+ | `.prepare((values, context) => values)` | Fills in or rewrites a create's or update's values on the server before they are written, inside the write's transaction, such as a generated key or a normalised name. See [Preparing a record](#preparing-a-record). |
72
73
  | `.access({ ... })` | Rules per operation. See [Access](#access). |
73
74
  | `.events((e, r) => [...])` | What changes of its records mean, such as `orders.created`, captured in the database for every write. See [Events](events.md). |
74
75
  | `.explicitGrants()` | Leaves the resource out of role wildcards such as `*.read`: only `*` and capabilities that name it grant it. For resources whose records hold secrets. See [Resources that need named grants](access.md#resources-that-need-named-grants). |
@@ -506,6 +507,41 @@ What a move leaves behind: webhooks already sent carried the old values to their
506
507
 
507
508
  It protects the values from database dumps, backups, replicas, and readers of raw SQL and realtime changes, who see only ciphertext. It does not protect them from whoever holds the key or the app's environment, or can run code in the server. Someone who can write to the database can change a row's tenant or roles, or put back an older value of the same record and field, from a backup say, which still opens. The ciphertext shows whether a value is empty, its length and when it changed. A key seals at most about 2³² values safely, as each gets a random IV; rotating starts a new key's count.
508
509
 
510
+ ## Preparing a record
511
+
512
+ Some values only the server may make, such as a generated key, a random identifier or a name written the one way the table accepts. `.prepare()` fills them in or rewrites them before the record is written, on every create and update: through the REST API, a [batch write](api.md#batch-writes), the [MCP tools](mcp.md), a public form and the assistant alike. It gets the values as the field checks and `.validate()` rules accepted them, and returns the values to write:
513
+
514
+ ```ts
515
+ import { randomBytes } from 'node:crypto'
516
+ import { domainToASCII } from 'node:url'
517
+ import { f, FieldIssue, resource } from '@protobase/schema'
518
+
519
+ export const api_tokens = resource('api_tokens')
520
+ .table('api_tokens')
521
+ .fields({
522
+ id: f.integer().readOnly().dbDefault(),
523
+ domain: f.text(),
524
+ // not null, and no request may write it
525
+ token: f.text().readOnly(),
526
+ })
527
+ .primaryKey((r) => r.id)
528
+ .prepare((values, { operation }) => {
529
+ // Bücher.de. is stored as xn--bcher-kva.de, as a check (domain = lower(domain)) wants
530
+ const domain = values.domain === undefined ? {} : { domain: domainToASCII(values.domain.replace(/\.$/, '')) }
531
+ if (domain.domain === '') throw new FieldIssue('domain', 'Not a domain name')
532
+ return operation === 'create' ? { ...values, ...domain, token: randomBytes(24).toString('base64url') } : { ...values, ...domain }
533
+ })
534
+ ```
535
+
536
+ - A field it fills stays `.readOnly()`: a request that sends it is refused as read-only, and the hook sets it anyway, so a `not null` column the server makes can be created through the standard `POST`.
537
+ - Its second argument holds the `operation` (`'create'` or `'update'`), the `user`, the `session` and the `tenant` the write works in, `before`, the stored record an update changes, and `trx`, the write's transaction (Kysely): what the hook reads or writes there commits with the record, or not at all.
538
+ - It runs after the field checks and `.validate()` rules, which then check the record it returns again (`400` when one refuses it), and before the access rules decide on the record and the row is written; the [write hooks](config/api.md#writehooks) run after the row is written, in the same transaction.
539
+ - Throwing a `FieldIssue` refuses the write with `422` and `errors: [{ field, code: 'invalid-value', message }]`, the field named when the caller reads or writes it and `_record` otherwise; anything else it throws rolls the write back as a server error.
540
+ - It may not set the tenant column or the `.author()` field, which only the server sets from the caller, nor a name that is not one of the resource's fields: the write then fails as a server error that names it.
541
+ - Each call adds a hook, run in order, each with the values the one before returned.
542
+ - The [PostgREST-compatible API](supabase-rest.md) writes the tables under their own grants and policies rather than through the resources, so the hook does not run there: a table it writes takes such a value from a default or a trigger.
543
+ - It does database and CPU work only, such as generating a key pair. While it waits on anything else, such as an HTTP call, the transaction stays open; work that needs the network belongs in a [job](jobs.md) a write hook enqueues.
544
+
509
545
  ## Opening an existing record
510
546
 
511
547
  A resource whose records are unique by some of their values, such as a direct message by its members, can have a create that repeats those values open the record that holds them instead of failing. `.openExisting()` names the unique key, as its fields:
@@ -317,7 +317,7 @@ await mail.send({ to: member.email, subject: 'News', text: '...', bulk: true, to
317
317
  Amazon SES (through SNS) and Resend report to their own endpoints so far, beside the `protobase` one a platform reports to.
318
318
  :::
319
319
 
320
- A mail provider tells the app when a message bounced or its recipient marked it as spam. With `mailFeedback` on, each report becomes a `mail_feedback` record, one per recipient, with the events `mail_feedback.bounced` and `mail_feedback.complained`, which [workflows](workflows.md), [subscriptions](webhooks.md) and your own code act on, such as marking a contact's address undeliverable. Protobase records and notifies only: it keeps sending to the address, and the app decides what a bounce means.
320
+ A mail provider tells the app when a message bounced or its recipient marked it as spam. With `mailFeedback` on, each report becomes a `mail_feedback` record, one per recipient, or one for a complaint that hides who complained, with the events `mail_feedback.bounced` and `mail_feedback.complained`, which [workflows](workflows.md), [subscriptions](webhooks.md) and your own code act on, such as marking a contact's address undeliverable. Protobase records and notifies only: it keeps sending to the address, and the app decides what a bounce means.
321
321
 
322
322
  Turn it on in the config, then run `protobase migration`, which writes its table, `mail.feedback`, and the capture of its events as migrations of the project's own; apply them with the project's migrations, as `protobase serve` refuses to start while the table is missing:
323
323
 
@@ -336,10 +336,11 @@ Each provider reports to `POST /api/mail/feedback/<provider>` with the default [
336
336
  A value that is not a topic ARN or a signing secret stops startup, naming the variable.
337
337
 
338
338
  - **Signatures:** a report writes nothing unless its signature checks out. `ses` takes SNS's signature, versions 1 and 2, with the signing certificate fetched from an SNS host over HTTPS and kept an hour, and only messages of the named topics, since anyone can sign with a topic of their own. `resend` and `protobase` take [Standard Webhooks](https://www.standardwebhooks.com) signatures, made at most five minutes before. A missing or wrong signature answers `401`, another topic `403`.
339
- - **The record:** `type` is `bounce` or `complaint`; `bounce_type` `hard` (permanent) or `soft` (transient), and empty when the provider could not tell; `recipient`, lower-cased; `message_id`, the `Message-ID` header of the message it is about, when the report states it; `provider_message_id`, the provider's own id of that message; `reason`, as the provider gives it, such as the receiving server's diagnostic, a bounce subtype or a complaint's feedback type; `occurred_at`, when the provider says it happened; `provider`, `event_id`, the provider's id of the report, and `created_at`. A value the report does not state is empty, never guessed. Match it to the mail it answers by the [message id](#message-id) you stored.
339
+ - **The record:** `type` is `bounce` or `complaint`; `bounce_type` `hard` (permanent) or `soft` (transient), and empty when the provider could not tell; `recipient`, lower-cased, which a complaint leaves empty when the report hides who complained, as some mailbox providers' spam reports do, and then names its `message_id`; `message_id`, the `Message-ID` header of the message it is about, when the report states it; `provider_message_id`, the provider's own id of that message; `reason`, as the provider gives it, such as the receiving server's diagnostic, a bounce subtype or a complaint's feedback type; `occurred_at`, when the provider says it happened; `provider`, `event_id`, the provider's id of the report, and `created_at`. A value the report does not state is empty, never guessed. Match it to the mail it answers by the [message id](#message-id) you stored.
340
340
  - **Once:** a provider sends a report again when it got no answer in time; the same report writes nothing new. A report of another kind, such as a delivery, answers `204` and writes nothing.
341
341
  - **Who sees it:** admins see the reports under **Mail feedback** in the admin app, and the app's code reads them as the `mail_feedback` resource, `GET /api/v1/mail_feedback?filter=recipient = "ada@example.com"`, filtered by `recipient`, `type`, `message_id` or `provider_message_id`. Nobody changes them but the endpoints.
342
- - **The `protobase` endpoint:** its body is one record as above, without `provider`, `event_id` and `created_at`, such as `{ "type": "bounce", "bounce_type": "hard", "recipient": "ada@example.com", "message_id": "<...>", "reason": "smtp; 550 5.1.1 user unknown" }`, signed as Standard Webhooks with a key derived from `PROTOBASE_SECRET`, so the secret itself never travels: `mailFeedbackHeaders(secret, id, body)` of `@protobase/server` makes the headers. `webhook-id` names the report, and a retry keeps it.
342
+ - **The `protobase` endpoint:** its body is one record as above, without `provider`, `event_id` and `created_at`, such as `{ "type": "bounce", "bounce_type": "hard", "recipient": "ada@example.com", "message_id": "<...>", "reason": "smtp; 550 5.1.1 user unknown" }`, a bounce with its `recipient` and a complaint with its `recipient`, its `message_id` or both, signed as Standard Webhooks with a key derived from `PROTOBASE_SECRET`, so the secret itself never travels: `mailFeedbackHeaders(secret, id, body)` of `@protobase/server` makes the headers. `webhook-id` names the report, and a retry keeps it.
343
+ - <gap>The generated type of a `mail_feedback` record cannot say that `message_id` is set when `recipient` is empty because field types that depend on another field's value are not implemented.</gap>
343
344
  - <gap>Other mail providers cannot report bounces and complaints because only the `ses`, `resend` and `protobase` endpoints are implemented.</gap>
344
345
 
345
346
  ## Attachments
@@ -432,9 +433,24 @@ export default defineFunction(async (request, { personalMail }) => {
432
433
 
433
434
  - **The mailbox's own address** is the one its provider's ID token names; Google gives it with the `email` scope sign-in asks for.
434
435
  - **The account page's calls:** `GET /api/auth/account/mail-senders` lists the person's addresses with their mailbox's own `address`; `POST .../mail-senders/add { address, name?, signature? }`, `POST .../mail-senders/update { id, name?, signature?, isDefault? }` (`name: null` drops the name, `signature: null` drops its own) and `POST .../mail-senders/remove { id }` change them. Each acts on the signed-in person's own addresses only.
435
- - <gap>An entered address cannot be checked to work before mail goes out from it because the test mail through the mailbox is not implemented.</gap>
436
436
  - <gap>An address cannot be shared with others who send mail because proving that the person owns the address is not implemented.</gap>
437
437
 
438
+ ### Checking a From address
439
+
440
+ :::note[Coming soon]
441
+ The app's side is built; the hosting platform's service that receives the test messages is not live yet.
442
+ :::
443
+
444
+ Gmail sends from the account's own address, without an error, when a From address is not one of its verified send-as addresses. So the account page checks an address by sending one test message from it through the person's mailbox, to a one-time address of a mail check service, and showing the From it arrived with:
445
+
446
+ - **When:** adding an address checks it at once; its dialog, under **Edit**, checks it again with **Check address**, and after a result with **Check again**.
447
+ - **Waiting:** the dialog asks every 3 seconds whether the message arrived, for up to 2 minutes, then says it did not arrive in time. Closing the dialog stops asking.
448
+ - **The result:** a From equal to the address, without regard to case, confirms it; any other shows the address the mailbox used instead, with how to set the address up in Gmail. The message also shows in the person's Sent folder.
449
+ - **The service:** the hosting platform names it in `PROTOBASE_MAIL_CHECK_URL`, a URL the app treats as opaque. The app makes two signed JSON `POST`s under it: `/alias-checks` answers `{ token, address }`, a one-time address and its token, and `/alias-checks/result { token }` answers `{ received: false }`, or `{ received: true, from }` with the address in the message's From header. Each carries [Standard Webhooks](https://www.standardwebhooks.com) headers under a key derived from `PROTOBASE_SECRET` by HKDF (`mailCheckSecret` and `mailCheckHeaders` of `@protobase/server`), which the service checks with `verifyStandardWebhook`. `PROTOBASE_MAIL_CHECK_URL` without `PROTOBASE_SECRET` stops startup.
450
+ - **Unchecked:** without the service, the dialog says the app cannot check From addresses, and how to check one by hand.
451
+ - **The account page's calls:** `GET /api/auth/account/mail-senders` says `checks: true` where the app can check; `POST .../mail-senders/check { id }` sends the test message and answers `{ status: 'waiting', check }`, or `{ status: 'unchecked' }`; `POST .../mail-senders/check-result { id, check }` answers `waiting`, `confirmed` or `mismatch` with `from`. Each acts on the signed-in person's own addresses only, and staff signed in as them cannot send a check.
452
+ - <gap>Self-hosted apps cannot check a From address because no mail check service that receives the test messages is implemented outside Protobase Cloud.</gap>
453
+
438
454
  ### A From address on a record
439
455
 
440
456
  :::caution[Beta]
@@ -1,32 +0,0 @@
1
- import { nextMigrationName } from "../auth/migration-file.js";
2
- import path from "node:path";
3
- import { mkdir, readdir, writeFile } from "node:fs/promises";
4
- //#region src/migration/write-migrations.ts
5
- /** A part's file: what wrote it and why, then its statements. */
6
- const partText = (title, sql) => `-- ${title}, written by \`protobase migration\`.\n-- Applied with the project's other migrations; edit or remove statements the project handles differently.\n\n${sql}\n`;
7
- /**
8
- * Writes what each part still needs as the next migrations in `dir`, one file per part, and returns their paths; none
9
- * when the database is current. Every part is compared with the database before any file is written, so the
10
- * project's earlier migrations must be applied to it first.
11
- */
12
- const writeMigrations = async (parts, dir) => {
13
- const pending = [];
14
- for (const part of parts) {
15
- const sql = await part.sql();
16
- if (sql !== void 0) pending.push({
17
- part,
18
- sql
19
- });
20
- }
21
- if (pending.length === 0) return [];
22
- await mkdir(dir, { recursive: true });
23
- const files = [];
24
- for (const { part, sql } of pending) {
25
- const file = path.join(dir, nextMigrationName(await readdir(dir), part.name));
26
- await writeFile(file, partText(part.title, sql), { flag: "wx" });
27
- files.push(file);
28
- }
29
- return files;
30
- };
31
- //#endregion
32
- export { partText, writeMigrations };