@protobase/cli 0.129.1 → 0.130.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 (99) hide show
  1. package/dist/auth/config-organizations.js +15 -0
  2. package/dist/auth/register.js +8 -2
  3. package/dist/auth/write-migration.js +34 -12
  4. package/dist/cli/package.js +1 -1
  5. package/dist/config/build-project.js +1 -0
  6. package/dist/config/project-modules.js +64 -0
  7. package/dist/config/read-only-queries.js +9 -0
  8. package/dist/config/user-tables-config.js +1 -1
  9. package/dist/dev/dev-jobs.js +12 -6
  10. package/dist/dev/entry.js +12 -19
  11. package/dist/doctor/capture-files.js +3 -3
  12. package/dist/doctor/startup.js +2 -4
  13. package/dist/migration/apply-migrations.js +9 -6
  14. package/dist/migration/baseline/read-live-modules.js +31 -0
  15. package/dist/migration/baseline/read-live-store.js +18 -4
  16. package/dist/migration/baseline/write-baseline.js +50 -17
  17. package/dist/migration/migrate-project.js +3 -3
  18. package/dist/migration/migration-project.js +29 -15
  19. package/dist/migration/older-code/catalog.js +34 -0
  20. package/dist/migration/older-code/contractions.js +86 -0
  21. package/dist/migration/older-code/lint-files.js +55 -0
  22. package/dist/migration/older-code/refusal.js +9 -0
  23. package/dist/migration/older-code/trial.js +58 -0
  24. package/dist/migration/parts.js +8 -104
  25. package/dist/migration/record/after-file.js +20 -2
  26. package/dist/migration/register.js +67 -19
  27. package/dist/migration/release/release-record.js +9 -7
  28. package/dist/migration/release/release-steps.js +15 -3
  29. package/dist/migration/sign-off/contract.js +65 -0
  30. package/dist/migration/sign-off/delete.js +50 -0
  31. package/dist/migration/sign-off/signed-off-file.js +19 -0
  32. package/dist/migration/snapshot/auth-difference.js +135 -15
  33. package/dist/migration/snapshot/auth-target.js +9 -3
  34. package/dist/migration/snapshot/check.js +24 -5
  35. package/dist/migration/snapshot/custom.js +6 -3
  36. package/dist/migration/snapshot/drop.js +7 -2
  37. package/dist/migration/snapshot/header.js +11 -4
  38. package/dist/migration/snapshot/module-changes.js +22 -0
  39. package/dist/migration/snapshot/module-prompts.js +42 -0
  40. package/dist/migration/snapshot/module-sections.js +38 -0
  41. package/dist/migration/snapshot/next-snapshot.js +13 -7
  42. package/dist/migration/snapshot/off-choice.js +11 -0
  43. package/dist/migration/snapshot/organizations-off-facts.js +49 -0
  44. package/dist/migration/snapshot/revival-rows.js +34 -0
  45. package/dist/migration/snapshot/run-migration.js +82 -15
  46. package/dist/migration/snapshot/snapshot-file.js +7 -0
  47. package/dist/migration/snapshot/terminal-prompts.js +21 -0
  48. package/dist/migration/snapshot/write-file.js +1 -1
  49. package/dist/migration/summary.js +3 -2
  50. package/dist/organizations/api.js +4 -2
  51. package/dist/organizations/commands.js +27 -10
  52. package/dist/organizations/pin-source.js +20 -0
  53. package/dist/organizations/pin.js +40 -0
  54. package/dist/organizations/register.js +20 -12
  55. package/dist/scaffold/protobase-tables.js +2 -2
  56. package/dist/serve/create-admin.js +6 -3
  57. package/dist/serve/lifecycle.js +2 -2
  58. package/dist/serve/migrate-release.js +1 -1
  59. package/dist/serve/relay-check.js +7 -8
  60. package/dist/serve/startup-checks.js +12 -22
  61. package/dist/supabase/load-phase.js +3 -1
  62. package/dist/supabase/project-users.js +4 -1
  63. package/dist/users/commands.js +44 -6
  64. package/dist/users/load-auth.js +9 -3
  65. package/dist/users/manage.js +16 -1
  66. package/dist/users/register.js +28 -25
  67. package/dist/users/set-disabled.js +3 -2
  68. package/dist/users/users-api.js +9 -3
  69. package/dist/worker/start-worker.js +7 -4
  70. package/package.json +8 -8
  71. package/skills/protobase/references/features/api-functions.md +1 -0
  72. package/skills/protobase/references/features/build-and-run.md +4 -2
  73. package/skills/protobase/references/features/sign-in-and-accounts.md +2 -1
  74. package/skills/protobase/references/guides/api-functions.md +27 -2
  75. package/skills/protobase/references/guides/deploy.md +2 -2
  76. package/skills/protobase/references/reference/assistant.md +1 -1
  77. package/skills/protobase/references/reference/auth.md +52 -17
  78. package/skills/protobase/references/reference/calls.md +1 -1
  79. package/skills/protobase/references/reference/cli.md +48 -28
  80. package/skills/protobase/references/reference/comments.md +1 -1
  81. package/skills/protobase/references/reference/config/api.md +1 -1
  82. package/skills/protobase/references/reference/config/jobs-and-events.md +1 -1
  83. package/skills/protobase/references/reference/config/sign-in.md +22 -4
  84. package/skills/protobase/references/reference/config.md +1 -1
  85. package/skills/protobase/references/reference/data-config.md +9 -9
  86. package/skills/protobase/references/reference/derived.md +1 -1
  87. package/skills/protobase/references/reference/email.md +2 -2
  88. package/skills/protobase/references/reference/events.md +2 -2
  89. package/skills/protobase/references/reference/history.md +1 -1
  90. package/skills/protobase/references/reference/jobs.md +5 -5
  91. package/skills/protobase/references/reference/live.md +2 -2
  92. package/skills/protobase/references/reference/notifications.md +4 -4
  93. package/skills/protobase/references/reference/personal-access-tokens.md +2 -2
  94. package/skills/protobase/references/reference/realtime-relay.md +1 -1
  95. package/skills/protobase/references/reference/status.md +2 -2
  96. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  97. package/skills/protobase/references/reference/user-tables.md +1 -1
  98. package/skills/protobase/references/reference/webhooks.md +1 -1
  99. package/dist/migration/snapshot/lint-custom.js +0 -23
@@ -48,7 +48,7 @@ The second argument of a handler (`c.env` in a [Hono app](#hono-apps)):
48
48
  | --- | --- |
49
49
  | `session` | The caller: `{ user: { id, roles }, tenant? }`, from the app's `authenticate`. |
50
50
  | `records` | The app's resources, acting as the caller: `list`, `get`, `create`, `update`, `delete`, `softDeleteField`. |
51
- | `db` | The Kysely instance itself. It skips every access rule, row filter and tenant scope. |
51
+ | `db` | The Kysely instance itself. It skips every access rule, row filter and the tenant scope of `.tenant` resources, but keeps the [organization's tables](#the-organizations-tables) to the caller's organization. |
52
52
  | `caller()` | Resolves to `{ session, records }`. Public functions use it to ask for a caller when they need one. |
53
53
  | `decryptField(resource, key, field)` | An [encrypted field](../reference/data-config.md#reading-in-jobs-and-functions)'s value, skipping access rules like `db`; each read is audited, naming the function and the caller. |
54
54
  | `acceptWebSocket(events)` | Answers a WebSocket upgrade with a socket; return its response. See [WebSockets](#websockets). |
@@ -58,6 +58,31 @@ The second argument of a handler (`c.env` in a [Hono app](#hono-apps)):
58
58
 
59
59
  A [public function](#public-functions-and-webhooks) has only `db`, `caller()`, `acceptWebSocket`, `calls`, `channels` and `name`.
60
60
 
61
+ ### The organization's tables
62
+
63
+ :::caution[Beta]
64
+ The host commands read every organization, and no check in CI finds raw SQL that names these tables as plain text. Sign-in's own queries keep to one organization (see [the reference](../reference/auth.md#organizations)).
65
+ :::
66
+
67
+ With [organizations](../reference/auth.md#organizations) on, the tables of the auth store whose rows each belong to one organization, `member`, `invitation` and `personal_access_token` under the names the app gives them, show `db` only the caller's organization, the one their session works in. While organizations are off after being on, the tables they left show `db` only [the default organization](../reference/auth.md#the-default-organization), for a session of it, whose tenant is its id; a session of another tenant, or of none, sees none of their rows. A read, update or delete of one gets `organization_id = <the organization>` in the select, update or delete that reads the table: in its `where`, or for a joined table in the join's `on`, so a `left join` keeps its other rows. Subqueries, common table expressions and `exists` filter their own tables, and a name a common table expression takes is not the table. An insert writes the organization, and one naming another organization, or an update moving a row to one, is refused with a `ScopeRefused` error before it reaches the database; so is an upsert's update of a row of another organization, which it leaves as it is. A table of the project's own with the same name in another schema is never taken for the store's. A right or full join, or a `merge`, of one of these tables throws, as the scope cannot keep it to the organization.
68
+
69
+ A [job](../reference/jobs.md) works in the organization of the `db` that enqueued it, such as a function's. A public function, a function called at `/api/sb/functions/v1`, a webhook's call of a function, a recurring job, and a job enqueued with `db.unscoped(...)`, a plain database or from SQL work in no organization: their `db` reads no row of these tables and writes none. Work that means every organization's rows says so, with a reason for whoever reviews it:
70
+
71
+ ```ts
72
+ const everyone = await db.unscoped('the nightly report counts members of every organization').selectFrom('auth.member').select(({ fn }) => fn.countAll().as('members')).executeTakeFirstOrThrow()
73
+ ```
74
+
75
+ Raw SQL names these tables through `scoped(table)` for the organization's rows, or `unscoped(reason, table)` for every organization's, both from `@protobase/query`. Naming one with `sql.table` or `sql.id` is refused, and `db.withoutPlugins()` too, as it would drop the scope without a reason:
76
+
77
+ ```ts
78
+ import { scoped } from '@protobase/query'
79
+ import { sql } from 'kysely'
80
+
81
+ const { rows } = await sql`select count(*) as members from ${scoped('auth.member')} as m`.execute(db)
82
+ ```
83
+
84
+ `scoped(table)` runs only on a database that keeps the scope: elsewhere Postgres refuses it as an unknown function. SQL written as plain text, `sql.raw`, a database view, or Kysely's `CompiledQuery.raw` is not seen, so name these tables through the helpers. The `.tenant` resources of the app's own tables are not kept to the organization in `db`: their API and `records` are.
85
+
61
86
  ## Reading and writing records as the caller
62
87
 
63
88
  ```ts title="functions/ready-for-pickup.ts"
@@ -131,7 +156,7 @@ export default defineFunction({ public: true }, async (request, { db }) => {
131
156
  - `verifyStandardWebhook(request, { secret })` checks [Standard Webhooks](https://www.standardwebhooks.com) signatures, as Supabase Auth hooks, Svix and Resend send them, including the timestamp (5 minutes of tolerance by default).
132
157
  - Stripe ships its own check: `stripe.webhooks.constructEventAsync(await request.text(), request.headers.get('stripe-signature'), secret)`.
133
158
 
134
- A public function has no caller, so it has no `records`. Its `db` skips the tenant scope too, so filter by tenant yourself where it matters. When a function should serve anyone but treat a signed-in caller differently, `await context.caller()` resolves the caller from the request, or rejects with the `401` problem.
159
+ A public function has no caller, so it has no `records`. Its `db` skips the tenant scope too, so filter by tenant yourself where it matters, and it sees no row of the [organization's tables](#the-organizations-tables). When a function should serve anyone but treat a signed-in caller differently, `await context.caller()` resolves the caller from the request, or rejects with the `401` problem.
135
160
 
136
161
  ## WebSockets
137
162
 
@@ -40,13 +40,13 @@ Every migration Protobase writes ends with the statement that records it in `mig
40
40
 
41
41
  A file may have an `.after.sql` beside it, such as `007_indexes.after.sql` beside `007_indexes.sql`, for statements that cannot run in a transaction, such as `create index concurrently if not exists`. `migrate` runs it once the file's batch commits, one statement at a time, each ending with a semicolon at the end of a line, then marks the file complete. A run that stops before then, killed or failing, leaves the file applied but not complete, and the next `migrate` finishes it first; an index it left invalid is dropped and built again. A project's own runner skips `.after.sql` files.
42
42
 
43
- The server reads the newest row once at startup, with the model it builds from the config and its code, and starts when the hashes are equal, or when the database is ahead of it only by additive migrations, as when a deploy is rolled back to the version before. It refuses when the database lacks something it reads or has it at an older step, naming the sign-in module and step, the version the database matches and its own, and the two ways out: `protobase migrate --plan` and `protobase migrate`, or running the version the database matches:
43
+ The server reads the record once at startup, with the model it builds from the config and its code: the sign-in store with sign-in on, and each built-in schema that is a module with numbered steps, such as the [jobs schema](../reference/jobs.md#the-jobs-schema), when the app needs it. It compares each part on its own, leaving out a part of the record it does not read, such as a schema a newer version needs, and starts when a row records every part as it reads it and no migration after that row is not additive, as when a deploy is rolled back to the version before. It refuses when the database lacks something it reads or has it at an older step, naming the sign-in module or the schema and its step, the version the database matches and its own, and the two ways out: `protobase migrate --plan` and `protobase migrate`, or running the version the database matches:
44
44
 
45
45
  ```
46
46
  The database is behind Protobase 0.128.0, so the server will not start: the auth store's passkeys module is at step 1 (passkeys), and this version needs step 2 (rp_id_index). To bring the database up to 0.128.0, run `protobase migrate --plan` to see the migrations it will apply, then `protobase migrate`. Or run Protobase 0.127.5, the version the database matches.
47
47
  ```
48
48
 
49
- It refuses as well on a database ahead of it by a migration that is not additive, while a unique index of an `.after.sql` is still building, and on a database with sign-in that records no migration, such as one migrated before this record: `protobase auth migration` then writes the file that records the store. An unfinished plain index does not keep it from starting. The server never migrates the database itself, and never turns a feature off because its tables are missing. <gap>The record's model cannot hold the jobs, change capture, rollup and other feature schemas because recording their models is not implemented, so the server still checks those schemas at startup one by one.</gap>
49
+ It refuses as well on a database ahead of it by a migration that is not additive after the newest one recording the model it reads, saying that rolling back to it is blocked and naming the version the database matches, while a unique index of an `.after.sql` is still building, and on a database that records no migration while the app reads the sign-in store or a schema module, such as one migrated before this record: `protobase auth migration` then writes the file that records the store, and [`protobase migration baseline`](../reference/cli.md#migration) the one that records a schema an earlier version's migration made. An unfinished plain index does not keep it from starting. The server never migrates the database itself, and never turns a feature off because its tables are missing. Besides the record, with the built-in assistant it checks what the database has given the [query role](../reference/assistant.md#the-built-in-backend), which a migration cannot promise. <gap>A migration that breaks older code without changing the model the record holds, such as a hand-written rename of a resource's column, cannot stop the version before from starting because recording the app's own release in `migrations.history` is not implemented.</gap> <gap>An app's CI cannot run its previous release's tests against the new schema because the older-code test is not implemented.</gap>
50
50
 
51
51
  ## Images
52
52
 
@@ -66,7 +66,7 @@ It lives at `/api/assistant` on the app's own origin and answers with the user's
66
66
 
67
67
  Both run **outside Protobase's access rules and tenant scoping**: whoever has the `admin` or `ai` role can read every resource's table, and with approval change everything the app's database role can, since `propose_write_query` still runs as that role. Give the app a database role without superuser rights, and those roles only to people who may see all of the data.
68
68
 
69
- Making the query role needs `CREATEROLE` once, for the role that applies the migrations; that role becomes a member of it and may run the function. The query role bypasses row-level security only when the migrating role may grant that, a superuser or, on Postgres 16 and later, a role with `BYPASSRLS`; otherwise it reads what the tables' policies give it. When the app serves as another database role than the one that migrates, grant that role `usage on schema query` and `execute on function query.run_read_only(text, integer)`. `protobase migration` writes the role only when it finds the built-in assistant's key, `PROTOBASE_ASSISTANT_API_KEY` in the `.env` it reads or `assistant.apiKey` of the config, so run it with the key set even when only production has the real one. The server does not start while the role or its function is missing, while the role can read an auth table, or while it may call a `SECURITY DEFINER` function, other than a trigger function, whose owner can read one: the statement would read the auth store through it, so revoke `execute` on such a function from `PUBLIC`, or keep it in a schema without a resource. A resource added since the last migration is refused by Postgres until the next one grants its table.
69
+ Making the query role needs `CREATEROLE` once, for the role that applies the migrations; that role becomes a member of it and may run the function. The query role bypasses row-level security only when the migrating role may grant that, a superuser or, on Postgres 16 and later, a role with `BYPASSRLS`; otherwise it reads what the tables' policies give it. When the app serves as another database role than the one that migrates, grant that role `usage on schema query` and `execute on function query.run_read_only(text, integer)`. `protobase migration` writes the role only when it finds the built-in assistant's key, `PROTOBASE_ASSISTANT_API_KEY` in the `.env` it reads or `assistant.apiKey` of the config, so run it with the key set even when only production has the real one. The server does not start while the [record of migrations](../guides/deploy.md#the-record-of-migrations) lacks the role, its function or a resource's grants, while the role can read an auth table, or while it may call a `SECURITY DEFINER` function, other than a trigger function, whose owner can read one: the statement would read the auth store through it, so revoke `execute` on such a function from `PUBLIC`, or keep it in a schema without a resource. Adding a resource writes its grants into the next migration, and removing one takes them back.
70
70
 
71
71
  ### The app's own tools
72
72
 
@@ -26,31 +26,37 @@ Users, sessions and signing keys stay apart from the application's tables, in a
26
26
 
27
27
  ### Migrations
28
28
 
29
- The store's tables come from steps that ship with Protobase, and are part of the project's migrations, committed in the repository like the application's own: the examples carry them as `db/migrations/*_auth.sql`, and their `db:migrate` applies both. Each module of sign-in has its own numbered chain of steps, the only source of its tables: `auth` (users, sessions, accounts, codes and signing keys), `two_factor`, `passkeys`, `sign_in_policy`, `staff_sign_in`, `organizations`, `mcp`, `personal_access_tokens`, `mail_senders` and `platform_devices`. A step is written against the store's [names](#table-and-column-names), so it makes the tables and columns under the names the app configures, and a step that adds columns to another module's table, such as `organizations` adding the organization of each user, session and personal access token, adds them only while that module is on. The store records the versions of its steps it applied in its `auth_migrations` table, one row per version, the numbers of the single chain the store had before its modules had chains of their own. When an upgrade of Protobase brings new steps, write them as the project's next migration:
29
+ The store's tables come from steps that ship with Protobase, and are part of the project's migrations, committed in the repository like the application's own: the examples carry them as `db/migrations/*_auth.sql`, and their `db:migrate` applies both. Each module of sign-in has its own numbered chain of steps, the only source of its tables: `auth` (users, sessions, accounts, codes and signing keys), `two_factor`, `passkeys`, `sign_in_policy`, `staff_sign_in`, `organizations`, `mcp`, `personal_access_tokens`, `mail_senders` and `platform_devices`. A step is written against the store's [names](#table-and-column-names), so it makes the tables and columns under the names the app configures, and a step that adds columns to another module's table, such as `organizations` adding the organization of each user, session and personal access token, adds them only while that module is on. The store records each step it applied in its `auth_steps` table, one row per module, step and the module whose tables it changes, so the columns one module adds to another's tables are recorded apart from the step's own tables. A store an earlier Protobase made recorded versions instead, in `auth_migrations`, the numbers of the single chain the store had before its modules had chains of their own: the next file makes `auth_steps` from them, each version as the steps that shared it, such as version 13 as `auth` 4, `passkeys` 2, `staff_sign_in` 2 and `organizations` 2, and `auth_migrations` is read no more. When an upgrade of Protobase brings new steps, write them as the project's next migration:
30
30
 
31
31
  ```sh
32
32
  bun run db:migrate # the database at the project's current schema
33
- bun run protobase auth migration # reads auth_migrations; writes the steps not applied as db/migrations/NNN_auth.sql
33
+ bun run protobase auth migration # reads auth_steps; writes the steps not applied as db/migrations/NNN_auth.sql
34
34
  bun run db:migrate # applies them
35
35
  ```
36
36
 
37
- Each step's statements come under a comment naming its module, number and name, such as `-- auth 2 account_keys: ...`, and the last step of a version is followed by its row in `auth_migrations`. The file only adds tables, nullable columns, columns with a default, and indexes, and the `pg_trgm` extension that the index of the users' names needs, never drops, retypes or tightens anything, so it is safe to apply unattended; Protobase's tests lint every step it ships for this. A step that assumes something of the rows already there starts with a check that refuses before it changes anything: `auth` step 2, which makes one account per provider and account id, stops when two accounts share both, naming them, so you keep one of each in a migration of your own written before it, then apply again. The file is plain SQL to review, edit or leave out where the project handles the auth schema itself. `--dir` and `--name` choose the folder and the name after the number. [`protobase migration`](cli.md#migration) writes the same steps from the project's `protobase.snapshot.json` instead of the database, so it needs no database, along with what the config's other features need, such as [jobs](jobs.md). The file `auth migration` writes starts with Protobase's lines and brings the store to every step of this version, so it also starts the project's snapshot, or moves it on, and `protobase migration` goes on from there.
37
+ Each step's statements come under a comment naming its module, number and name, such as `-- auth 2 account_keys: ...`, and each is followed by its row in `auth_steps`. The file only adds tables, nullable columns, columns with a default, and indexes, and the `pg_trgm` extension that the index of the users' names needs, never drops, retypes or tightens anything, so it is safe to apply unattended; Protobase's tests lint every step it ships for this. A step that assumes something of the rows already there starts with a check that refuses before it changes anything: `auth` step 2, which makes one account per provider and account id, stops when two accounts share both, naming them, so you keep one of each in a migration of your own written before it, then apply again. The file is plain SQL to review, edit or leave out where the project handles the auth schema itself. `--dir` and `--name` choose the folder and the name after the number. [`protobase migration`](cli.md#migration) writes the same steps from the project's `protobase.snapshot.json` instead of the database, so it needs no database, along with what the config's other features need, such as [jobs](jobs.md). The file `auth migration` writes starts with Protobase's lines and brings the store to every step of this version, so it also starts the project's snapshot, or moves it on, and `protobase migration` goes on from there.
38
38
 
39
- Every store has the tables of every module, whether the app turns the feature on or not: [passkeys](#passkeys), [two-factor authentication](#two-factor-authentication), [organizations](#organizations), the [OAuth provider for MCP](#oauth-for-mcp-clients) and [personal access tokens](personal-access-tokens.md). Turning a feature on or off needs no migration and drops nothing; the columns a feature adds to the user and session tables are empty until it is on. SAML providers and open sign-up keep nothing in the store. <gap>A store cannot leave out the tables of a feature the app does not use because recording the steps a store has, rather than versions, is not implemented.</gap>
39
+ A store has the tables of the modules the config turns on, and no table, column or index of the others. A module is on while its feature is: `organizations` with [`auth.organizations`](#organizations), `mcp` with [`auth.mcp`](#oauth-for-mcp-clients) or `openIdProvider`, which share its tables, `personal_access_tokens` with [`auth.personalAccessTokens`](personal-access-tokens.md), and `mail_senders` with [`auth.personalMail`](config/sign-in.md#authpersonalmail), and `platform_devices` with [device sign-in](#device-accounts): a provider of `auth.signInProviders` with `devices: true`, or [`auth.signInDevices`](config/sign-in.md#authsignindevices) for the platform's providers from the environment, as a migration is written from the config alone. `auth`, `two_factor`, `passkeys`, `sign_in_policy` and `staff_sign_in` are always on: those features have no switch. Turning a feature on is a migration: the next `protobase migration` or `protobase auth migration` writes its module's steps, and the statements the modules already on add to its tables, and the server refuses to start with the feature on until that file is applied. The columns a module adds to another's table, such as `user.last_organization_id`, are made with that module. SAML providers and open sign-up keep nothing in the store.
40
+
41
+ #### Turning a module off
42
+
43
+ Taking a feature out of the config turns its module off, and the next [`protobase migration`](cli.md#migration) asks what becomes of its tables and rows, keep, archive or delete; without a terminal, `--off` answers. The answer is recorded in `protobase.snapshot.json`, under `decisions.modules.kept`, with the step the module had and its tables' names. `keep`, the default, applies at once: the tables and rows stay as they are, the module stays at its step, and each column it adds to the tables of the modules still on loses `not null`, so the code that no longer writes it still inserts rows, and is watched for the code that still does, such as the version before once rolled back: a trigger on each counts the rows written with it set, by hour, in `retired.writes` (`table_name`, `column_name`, `hour`, `writes`), the schema `retired` made by the first file that retires a column. Turning the module on again stops the watch, and the column is in use again under its name with the values it kept. A personal access token's `organization_id` stays required, as tokens made while organizations are off are made in [the default organization](#the-default-organization). For personal access tokens the question says they stay valid unless deleted. `archive` and `delete` keep it the same way, and record the choice, the file that turned it off and the columns it retired, until [`protobase migration contract`](cli.md#signing-off-an-update) signs the update off: that file moves the module's tables to the schema `protobase_archive_<n>`, which the app's roles cannot use, with no foreign key between them and the tables still on, and renames each column it retired to `<column>_archive`; the module moves to `decisions.modules.archived`. [`protobase migration delete <module>`](cli.md#signing-off-an-update) then removes the archive for good, once it was applied a stated period ago and nothing wrote it within it. A module turned on again after its archive starts afresh from its first step, and the archive stays until deleted. `protobase auth migration` refuses a config that turns a module off or on again since the snapshot, and says to run `protobase migration`.
44
+
45
+ Turning a kept module on again writes the rest of its steps after the one it was kept at, and refuses a table or column name the config changed meanwhile, as for a module that stays on; and again what the modules on add to its tables, which their guard skips where the database has it. Its rows come back into use, such as personal access tokens, which act for their users again, so the file starts with a check that refuses while its tables hold rows, naming each table with its count, unless it is applied with [`protobase migrate --force`](cli.md#migrate). With `DATABASE_URL` set, `protobase migration` counts them first and refuses the same way, asking on a terminal whether to bring them back, or taking `--force`; with empty tables it neither asks nor refuses.
40
46
 
41
47
  The names the app configures, the store's schema ([`auth.schema`](config/sign-in.md#authschema)), its [tables and columns](#table-and-column-names), and uuid ids (`generateUserId: 'uuid'`), are the ones in effect when the file is written. Changing one later is a migration of the project's own, such as a rename. <gap>`protobase auth migration` cannot rename a table or column the store has already because writing a rename from a changed name is not implemented.</gap>
42
48
 
43
- The server never changes the schema, and never compares it with what Better Auth needs. `protobase serve` and `protobase dev` read the database's [record of migrations](../guides/deploy.md#the-record-of-migrations), `migrations.history`, at startup and refuse to start while it lacks a step of this Protobase, naming the module and step, or while the database is ahead of this Protobase by a migration that is not additive. Each migration records itself there; `auth_migrations` stays the steps' own record, which each step's file reads to skip a step the database has. The examples' `db:migrate` applies all pending files in one transaction, so a migration that fails leaves the database as the running version expects it. The host must guarantee the rest: nothing but the migrations writes while they run, and the new version serves only after they succeeded. Only [`protobase dev`](cli.md#dev), on the developer's machine, compares the store's tables with what the app's Better Auth needs, and warns at startup about each table, column or index that drifted, such as one changed by hand.
49
+ The server never changes the schema, and never compares it with what Better Auth needs. `protobase serve` and `protobase dev` read the database's [record of migrations](../guides/deploy.md#the-record-of-migrations), `migrations.history`, at startup and refuse to start while it lacks a step of this Protobase, naming the module and step, or while the database is ahead of this Protobase by a migration that is not additive. Each migration records itself there; `auth_steps` stays the steps' own record, which each step's file reads to skip a step the database has. The examples' `db:migrate` applies all pending files in one transaction, so a migration that fails leaves the database as the running version expects it. The host must guarantee the rest: nothing but the migrations writes while they run, and the new version serves only after they succeeded. Only [`protobase dev`](cli.md#dev), on the developer's machine, compares the store's tables with what the app's Better Auth needs, and warns at startup about each table, column or index that drifted, such as one changed by hand.
44
50
 
45
51
  No resource may be over a table of the store, which holds password hashes, sessions, tokens and signing keys: `protobase serve` and `protobase dev` refuse to start with one, naming it, whatever the table is called, and [`protobase scaffold`](cli.md#scaffold) never writes one. The API, the Supabase-compatible endpoints, live updates and MCP read the app's resources only, so none of them reads the store.
46
52
 
47
- A store made before 0.48, when `protobase auth migration` compared the database with Better Auth's tables, has no `auth_migrations`. For it, `protobase auth migration` writes the step that adopts it, once: it runs every step in a scratch schema, in a transaction it rolls back, to find the tables and columns each version makes, records each version whose tables and columns the store has, with their types, as applied, and writes the steps of the versions whose tables it has none of, such as MCP's for an app that never turned MCP on. The file checks again, when it is applied, that the store has every table and column it adopts, and stops otherwise, naming them. A store that has only some of a version's tables and columns, or has them with other types, is refused, naming what differs: bring it to the schema of Protobase 0.47 first, with that version's `protobase auth migration`. A store set up by Protobase 0.6, with Better Auth's camelCase names, or by `auth:migrate` before it, goes through 0.47 the same way.
53
+ A store made before 0.48, when `protobase auth migration` compared the database with Better Auth's tables, has no record of its steps. For it, `protobase auth migration` writes the step that adopts it, once: it runs every step in a scratch schema, in a transaction it rolls back, to find the tables and columns each version makes, records the steps of each version whose tables and columns the store has, with their types, as applied, and writes the steps of the versions whose tables it has none of, such as MCP's for an app that never turned MCP on. The file checks again, when it is applied, that the store has every table and column it adopts, and stops otherwise, naming them. A store that has only some of a version's tables and columns, or has them with other types, is refused, naming what differs: bring it to the schema of Protobase 0.47 first, with that version's `protobase auth migration`. A store set up by Protobase 0.6, with Better Auth's camelCase names, or by `auth:migrate` before it, goes through 0.47 the same way.
48
54
 
49
55
  ### Table and column names
50
56
 
51
57
  Each module of the store declares its tables and columns once, under built-in names, snake_case like the app's (`sign_in_policy.platform_sign_in`, `session.user_id`); the code and the API keep Better Auth's camelCase names. The modules and their tables:
52
58
 
53
- - `auth`: `user`, `session`, `account`, `verification`, `jwks` and `auth_migrations`.
59
+ - `auth`: `user`, `session`, `account`, `verification`, `jwks`, `auth_steps` and `auth_migrations`.
54
60
  - `two_factor`: `two_factor`, and the user's `two_factor_enabled`.
55
61
  - `passkeys`: `passkey`.
56
62
  - `sign_in_policy`: `sign_in_policy`.
@@ -136,7 +142,7 @@ The store's migrations then make nothing of the user table, which a migration of
136
142
 
137
143
  ### Hooks
138
144
 
139
- Sign-in runs the project's own code from `auth/hooks.ts`, which Protobase finds by that path and loads when it builds sign-in. Each hook is a named export, typed with `AuthHooks` from `@protobase/server`, and gets the app's database, `{ db }` (Kysely), as its last argument:
145
+ Sign-in runs the project's own code from `auth/hooks.ts`, which Protobase finds by that path and loads when it builds sign-in. Each hook is a named export, typed with `AuthHooks` from `@protobase/server`, and gets the app's database, `{ db }` (Kysely), as its last argument, which keeps the [organization's tables](../guides/api-functions.md#the-organizations-tables) to the organization the hook is about, and to none for a hook about none, such as `onUserCreated`:
140
146
 
141
147
  ```ts
142
148
  // auth/hooks.ts
@@ -154,9 +160,9 @@ export const generateUserId: AuthHooks['generateUserId'] = async ({ db }) => {
154
160
  | `generateUserId` | the id of a new user, by any route; see [User ids](#roles-and-access-in-the-api) |
155
161
  | `onUserCreated` | `(user, context, { db })`, after a user is created by any route: `protobase users create`, an admin, [open sign-up](#open-sign-up) or a [sign-in provider](#sign-in-with-github) |
156
162
  | `generateOrganizationId` | the id of a new [organization](#organizations); default a random UUID |
157
- | `onOrganizationCreated` | `({ organization, member }, { db })`, after an organization is created, with its owner's membership |
158
- | `beforeOrganizationDeleted` | `(organization, { db })`, before an organization is deleted; throwing refuses it |
159
- | `organizationHooks` | Better Auth's organization hooks by name, each with `{ db }` last, run after Protobase's own |
163
+ | `onOrganizationCreated` | `({ organization, member }, { db })`, after an organization is created, with its owner's membership; `db` works in the new organization |
164
+ | `beforeOrganizationDeleted` | `(organization, { db })`, before an organization is deleted; throwing refuses it; `db` works in that organization |
165
+ | `organizationHooks` | Better Auth's organization hooks by name, each with `{ db }` last, run after Protobase's own; `db` works in the organization the hook's input names |
160
166
  | `senderVerifiers` | `(add_verifier)`, once as the app starts: adds the app's ways to prove a From address; see [Verifying a From address](email.md#verifying-a-from-address) |
161
167
 
162
168
  A mailer of the project's own, for sign-in's mail, is the default export of `auth/mailer.ts` (see [Password reset](#password-reset)). An authenticator of its own, in place of the one `authenticate` describes, is the default export of `auth/authenticate.ts` (see [Tokens and roles](#tokens-and-roles)).
@@ -668,6 +674,14 @@ PROTOBASE_SIGN_IN_PHONE_TOKENS=true
668
674
 
669
675
  A provider that gives each device a subject of its own, such as one that signs in a phone app, can have every device be an account of its own: `PROTOBASE_SIGN_IN_DEVICES=true` (`devices: true`), with [token sign-in](#token-sign-in) alone, without a client secret.
670
676
 
677
+ Device sign-in keeps its own tables, `refused_account` and `device_session`, which a migration makes. A provider of `auth.signInProviders` with `devices: true` turns them on. For the platform's providers from the environment, turn on `auth.signInDevices` in the config, then write the migration with `protobase migration` and apply it:
678
+
679
+ ```ts
680
+ auth: { signInDevices: true }
681
+ ```
682
+
683
+ Without it, a provider of the environment with `PROTOBASE_SIGN_IN_DEVICES=true`, or `PROTOBASE_SIGN_IN_<ID>_DEVICES=true`, stops the server at startup with an error naming `auth.signInDevices`.
684
+
671
685
  - **Linked by address:** a device's first sign-in links it to the account with the address the provider vouches for, as for any provider, both addresses verified. A person holds as many of the provider's accounts as they have devices.
672
686
  - **Its sessions:** each session a device's token sign-in starts is kept as the device's in the store's `device_session` table (the `platform_devices` module's step 1), which goes with the session, so it lasts as long as the session however often it is renewed. A sign-in that waits for the [second step](#two-factor-authentication) is the device's once the step is taken.
673
687
  - **On the account page:** the **Devices** tab lists each device as the provider's name with the device's own name, which the device's ID token carries in the `device_name` claim (a string), with when it was linked, and the sessions it began under it rather than among the others. The connected accounts do not list them. `GET /api/auth/account/device-links` answers `{ links: [{ id, provider, name, device, linkedAt, sessions }] }`, `sessions` being the tokens of the sessions it began; `GET /api/auth/status` says `deviceLinks: true`.
@@ -750,11 +764,11 @@ auth: {
750
764
  sales: 'Sales',
751
765
  accountant: 'Accountant',
752
766
  },
753
- organizations: { create: 'everyone' },
767
+ organizations: { enabled: true, default: { id: 'main', name: 'Main', slug: 'main' }, existingUsersRole: 'sales', create: 'everyone' },
754
768
  }
755
769
  ```
756
770
 
757
- It is Better Auth's organization plugin, with its tables named in snake_case (`organization`, `member`, `invitation`, `session.active_organization_id`); every store has them, and `user.last_organization_id`, with organizations on or off (see [migrations](#migrations)).
771
+ It is Better Auth's organization plugin, with its tables named in snake_case (`organization`, `member`, `invitation`, `session.active_organization_id`, `user.last_organization_id`), which the store has while organizations are on, and keeps once they are turned off (see [migrations](#migrations)).
758
772
 
759
773
  **Two kinds of role.** Every membership has an organization role, Better Auth's `owner`, `admin` or `member`, which decides who manages the organization: owners and admins invite, remove and change members and edit its details; only owners hand it over, delete it or make owners. App roles, the project's `roles`, decide what the app shows and allows. A user holds them **globally** (the admin plugin's `role` column, as without organizations), which applies in every organization, or **per membership** (`member.app_roles`), which applies there only. A request's role, `ctx.user.roles`, is the session's [active role](#active-role), of either kind; access rules see the organization role as `ctx.organization.role`, read from the membership on each request, absent for someone who is no member there, such as a superuser who entered it. `admin` is the superuser: global only, it holds every role. With organizations every role needs a label; `owner` and `member` cannot be app role names, and `user` stands for an account without a global role.
760
774
 
@@ -770,21 +784,42 @@ It is Better Auth's organization plugin, with its tables named in snake_case (`o
770
784
 
771
785
  **Ids.** The `generateOrganizationId` [hook](#hooks) makes a new organization's id, by default a UUID; `.tenant` columns hold it, so `text` or `uuid`. An app whose tenant columns are integers takes the next value of its own organizations sequence instead, and adds its own row in `onOrganizationCreated`, as the ERP example does (`tests/apps/erp/auth/hooks.ts`). An app that ran as one organization keeps its tenant value: `protobase organizations create "Acme" --owner you@example.com --id 1 --members all` makes that organization, with every user in it: superusers as owners, everyone else as a member, their global roles moved onto the membership. The first user `createUser` makes also becomes the owner of every organization without members, such as those a seed made before anyone could own them.
772
786
 
773
- **On the host.** The [`protobase organizations`](cli.md#organizations) commands call these functions of `@protobase/server`, which a script of the project's own, such as a seed, calls with the sign-in of [`loadProjectAuth`](#first-run). The host acts as a superuser, so it may give any role; `organization` is a slug or an id:
787
+ **On the host.** The [`protobase organizations`](cli.md#organizations) commands call these functions of `@protobase/server`, which a script of the project's own, such as a seed, calls with the sign-in of [`loadProjectAuth`](#first-run). The host acts as a superuser, so it may give any role; `organization` is a slug or an id. `scope` is the organization a call works in, by its id, or every organization with `everyOrganization('<why>')` from `@protobase/query`, whose reason says why the call reads every organization's rows:
774
788
 
775
789
  ```ts
776
- import { addAppRoleToOwners, addMember, createOrganization, listOrganizations, removeMember, setMemberRoles } from '@protobase/server'
790
+ import { addAppRoleToOwners, addMember, createOrganization, isMemberByEmail, listOrganizations, listUsers, organizationByKey, removeMember, setMemberRoles } from '@protobase/server'
777
791
 
778
792
  await createOrganization(auth, { name, slug, owner: email, id? }) // the owner holds every app role
779
793
  await addMember(auth, { organization, email, role?, appRoles? }) // role: owner, admin or member (default)
780
794
  await setMemberRoles(auth, { organization, email, role?, appRoles? })
781
795
  await removeMember(auth, { organization, email }) // refuses the last owner
782
- await listOrganizations(auth, { after?, size? }) // a page, oldest first: { organizations: [{ id, name, slug, members }], next? }
783
- await addAppRoleToOwners(auth, appRole) // a role the project added later, to every owner
796
+ await listOrganizations(auth, scope, { after?, size? }) // a page, oldest first: { organizations: [{ id, name, slug, members }], next? }
797
+ await addAppRoleToOwners(auth, scope, appRole) // a role the project added later, to the owners in scope
798
+ await listUsers(auth, { scope?, after?, size? }) // the members of scope; every user without it
799
+ await organizationByKey(auth, organization) // the organization, or null
800
+ await isMemberByEmail(auth, organizationId, email)
784
801
  ```
785
802
 
786
803
  The app's own pages are under the profile menu: the switcher, "Manage organizations" (theirs, a new one, and for global roles any one), "Organization" (details, leaving, handing over, deleting), and for owners and admins "Members" and "Invitations". The client has them as `session.organizations` (`list`, `current`, `switchTo`, `members`, `invite`, ...). `session.organizations.create({ name })` makes one from its name alone: the server makes the slug from the name, and when another organization has that slug, adds a dash and six random letters and digits, such as `acme-k3x9q2`. The organization page changes the slug afterwards.
787
804
 
805
+ ### The default organization
806
+
807
+ Every table of the store is either the whole app's or an organization's. `member`, `invitation` and `personal_access_token` hold an organization's rows, each with its `organization_id`; the others, users, sessions, accounts, verifications, two-factor secrets, passkeys, the sign-in policy and the signing keys among them, are the app's. Each index of an organization's table serves one organization, leading with `organization_id`, or the whole app, such as a lookup by a person or an address; a key looked up from outside, such as a token's hash, stays unique across the app. The `db` the app's functions, jobs and hooks get shows them one organization's rows only, unless `db.unscoped('<reason>')` (see [The organization's tables](../guides/api-functions.md#the-organizations-tables)). Sign-in's own queries keep to one organization too, work Better Auth finishes after the response included: an `/api/auth/organization/*` request works in the organization it names as `organizationId`, in a GET's query or a POST's body, else in the session's active one, and a POST naming another in its query is refused with `400` (`CONFLICTING_ORGANIZATIONS`); a membership or token is read in the organization it belongs to; and what is a person's own in every organization, such as their organizations, the invitations to their address, their personal access tokens and a token looked up by its hash, is read across them. A request elsewhere in `/api/auth` works in none. <gap>An `/api/auth/organization/*` request that names its organization by slug alone cannot reach one other than the session's active organization because finding the organization of a slug before the request runs is not implemented.</gap> While organizations are off after being on, the `db` keeps the tables they left to [the default organization](#the-default-organization): a function's for a session of it, a job's enqueued in it, and a hook's, which is about it; a public function and `/api/sb/functions/v1` see none of their rows.
808
+
809
+ The default organization, `organizations.default`, is the one that stands in for every organization while they are off. [`protobase migration`](cli.md#migration) refuses without it once organizations are on or were ever on, and records it in `protobase.snapshot.json`. Turning organizations off sets `enabled: false` and keeps `default`; the store keeps their tables and columns, as [for any module](#turning-a-module-off).
810
+
811
+ Turning organizations on for the first time makes the default organization under its id, and each user there already becomes its member, with the organization role `member` and the app role `existingUsersRole`; `protobase migration` refuses without that role, unless the store is new and holds no users. Each personal access token made before then works in the default organization: the migration's `.after.sql` fills them in batches, then makes their `organization_id` required, checked first without a long lock, and builds their index per organization concurrently. Turning organizations on again later fills nothing: a token made while they were off was made in the default organization. One made while they were off on an earlier version has no organization, so the migration refuses, naming it, as below. On a store whose organizations were on before, such as one [`migration baseline`](cli.md#migration) started, the default organization is made when the store lacks it, no one becomes its member, and a token without an organization is not given the default one, which would guess where it works: the migration refuses, naming each such token, so you delete them, or set the organization each works in, in a migration of your own written before it. With organizations on, a personal access token is made in the session's active organization, and refused without one.
812
+
813
+ When organizations are off while the store still holds organizations, as after they were on, the default organization stands in for all of them, and only its members have access:
814
+
815
+ - At startup, the server refuses to start unless `authenticate.tenant` is the default organization's id, and its error message shows both values. A store with no organization, such as one whose organization tables were made while organizations were off, starts as before.
816
+ - A non-member who signs in gets the same answer as for a wrong password, and no session is created. This applies to every sign-in method, including staff sign-in and impersonation.
817
+ - Anyone added while organizations are off, by open sign-up, an admin or a sign-in provider, becomes a member of the default organization. They get the organization role `member` and the app role set in `existingUsersRole`, or no app role if that is not set.
818
+ - A non-member's session, API token or OAuth access token is refused with `401`. A non-member's session gets no token from `/api/auth/token` and no personal access token, and an admin who is not a member cannot manage people, the sign-in policy or registered clients, so they cannot add someone to the default organization. <gap>A non-member's session from before organizations were turned off still answers `/api/auth/get-session` because refusing it in sign-in's own session read is not implemented.</gap>
819
+ - New personal access tokens are created in the default organization, and only tokens created there work. A token created in another organization, or in none, is refused like an unknown token.
820
+
821
+ When `DATABASE_URL` is set, the question `protobase migration` asks as organizations are turned off says how many people are not members of the default organization. It also says how many personal access tokens were created outside it. If the store's only organization is not the default, `protobase migration` offers to make it the default. If you answer yes, it prints the `default` entry for your config and stops without writing anything. Add the entry and run it again.
822
+
788
823
  ### First organization and start address
789
824
 
790
825
  :::caution[Beta]
@@ -31,7 +31,7 @@ Or, with no media server, `backend: { kind: 'peer' }`: see [Peer to peer](#peer-
31
31
  - `maxMinutes`: how long a call lasts at most, 240 by default. Then it ends, whoever is still in it.
32
32
  - `processes`: `'many'` when several processes serve the app behind one address, so members that different processes serve meet in one call; `'one'`, the default, otherwise.
33
33
 
34
- Without `calls`, an app has none of it: the server loads no calls code, and only a page that imports `@protobase/client/calls` bundles the browser side. With `calls`, [`protobase migration`](cli.md#migration) adds the `calls` schema, where calls and their members are kept; apply it with the project's other migrations. `protobase dev` and `protobase serve` do not start while it is missing.
34
+ Without `calls`, an app has none of it: the server loads no calls code, and only a page that imports `@protobase/client/calls` bundles the browser side. With `calls`, [`protobase migration`](cli.md#migration) adds the `calls` schema, where calls and their members are kept, and the notices table rings reach open pages through; apply it with the project's other migrations. `protobase dev` and `protobase serve` do not start while the [record of migrations](../guides/deploy.md#the-record-of-migrations) lacks them.
35
35
 
36
36
  Running LiveKit on your own machine: `bun run calls:up` in the Protobase repository starts one from `docker-compose.yml`, at `ws://127.0.0.1:7880` with the key `devkey` and the secret `secretsecretsecretsecretsecretsecret`.
37
37