@protobase/cli 0.46.8 → 0.46.10

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.
@@ -1,4 +1,5 @@
1
1
  import { moduleFile } from "../module-file.js";
2
+ import { exportOrder } from "./export-order.js";
2
3
  import { uiDirs } from "../project/convention-files.js";
3
4
  import { functionFiles } from "../project/functions-folder.js";
4
5
  import { existsSync } from "node:fs";
@@ -15,7 +16,7 @@ const bundleEntryCode = (projectDir, extensions = []) => {
15
16
  const lines = hasCustom ? [`import * as custom from ${JSON.stringify(custom)}`, "const project = custom.default ?? {}"] : ["const project = {}"];
16
17
  if (hasIndex) {
17
18
  const dirs = uiDirs(configDir);
18
- lines.push(`import { conventionConfig } from ${JSON.stringify(conventionModule)}`, `import * as index from ${JSON.stringify(index)}`, ...dirs.map((dir, i) => `import * as ui${i} from ${JSON.stringify(path.join(configDir, dir, "ui.ts"))}`), `const convention = conventionConfig(index, [${dirs.map((dir, i) => `[${JSON.stringify(dir)}, ui${i}]`).join(", ")}])`);
19
+ lines.push(`import { conventionConfig } from ${JSON.stringify(conventionModule)}`, `import * as index from ${JSON.stringify(index)}`, ...dirs.map((dir, i) => `import * as ui${i} from ${JSON.stringify(path.join(configDir, dir, "ui.ts"))}`), `const convention = conventionConfig(index, [${dirs.map((dir, i) => `[${JSON.stringify(dir)}, ui${i}]`).join(", ")}], ${JSON.stringify(exportOrder(index))})`);
19
20
  } else lines.push("const convention = undefined");
20
21
  const functions = functionFiles(projectDir);
21
22
  lines.push(...functions.map(({ file }, i) => `import * as function${i} from ${JSON.stringify(file)}`), `const functions = ${functions.length === 0 ? "undefined" : `{ ${functions.map(({ name }, i) => `${JSON.stringify(name)}: function${i}.default`).join(", ")} }`}`);
@@ -0,0 +1,52 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { parseSync } from "vite";
4
+ //#region src/build/export-order.ts
5
+ const extensions = [
6
+ "",
7
+ ".ts",
8
+ ".tsx",
9
+ ".mts",
10
+ ".js",
11
+ ".mjs",
12
+ "/index.ts",
13
+ "/index.js"
14
+ ];
15
+ const resolveRelative = (from, specifier) => {
16
+ const base = path.resolve(path.dirname(from), specifier);
17
+ const bases = /\.m?js$/.test(base) ? [base, base.replace(/\.(m?)js$/, ".$1ts")] : [base];
18
+ for (const candidate of bases.flatMap((each) => extensions.map((extension) => each + extension))) if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
19
+ };
20
+ const exportName = (name) => name.type === "Literal" ? String(name.value) : name.name;
21
+ const declaredNames = (declaration) => {
22
+ if (declaration.type === "VariableDeclaration") return declaration.declarations.flatMap((each) => each.id.type === "Identifier" ? [each.id.name] : []);
23
+ if ((declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") && declaration.id) return [declaration.id.name];
24
+ return [];
25
+ };
26
+ /**
27
+ * The names a module exports, in the order its source declares them, following relative `export * from` into the
28
+ * modules they name. A bundle's `import * as` namespace sorts its names; this is the order `protobase dev` keeps.
29
+ * Names it cannot see, such as those of a package's `export *`, are left out.
30
+ */
31
+ const exportOrder = (file, seen = /* @__PURE__ */ new Set()) => {
32
+ if (seen.has(file)) return [];
33
+ seen.add(file);
34
+ const { program } = parseSync(file, readFileSync(file, "utf8"));
35
+ const names = program.body.flatMap((statement) => {
36
+ if (statement.type === "ExportNamedDeclaration") {
37
+ if (statement.exportKind === "type") return [];
38
+ if (statement.declaration) return declaredNames(statement.declaration);
39
+ return statement.specifiers.filter((specifier) => specifier.exportKind !== "type").map((specifier) => exportName(specifier.exported));
40
+ }
41
+ if (statement.type === "ExportAllDeclaration") {
42
+ if (statement.exportKind === "type") return [];
43
+ if (statement.exported) return [exportName(statement.exported)];
44
+ const target = statement.source.value.startsWith(".") ? resolveRelative(file, statement.source.value) : void 0;
45
+ return target ? exportOrder(target, seen).filter((name) => name !== "default") : [];
46
+ }
47
+ return [];
48
+ });
49
+ return [...new Set(names)];
50
+ };
51
+ //#endregion
52
+ export { exportOrder };
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.46.8";
2
+ var version = "0.46.10";
3
3
  //#endregion
4
4
  export { version };
@@ -1,6 +1,7 @@
1
1
  //#region src/project/convention.ts
2
- const conventionConfig = (index, uiModules) => {
3
- const config = { ...index };
2
+ const conventionConfig = (index, uiModules, order = []) => {
3
+ const config = Object.fromEntries(order.filter((name) => Object.hasOwn(index, name)).map((name) => [name, index[name]]));
4
+ Object.assign(config, index);
4
5
  for (const [dir, exports] of uiModules) for (const [key, value] of Object.entries(exports)) if (!Object.values(config).includes(value)) config[`${dir}:${key}`] = value;
5
6
  return config;
6
7
  };
@@ -8,6 +8,7 @@ import { detectDrift } from "./drift.js";
8
8
  import { ensureExports } from "./index-file.js";
9
9
  import { assignNames } from "./resource-names.js";
10
10
  import { planResource } from "./resource-plan.js";
11
+ import { dependencyOrder } from "./table-order.js";
11
12
  import { isExcluded, matchesTarget } from "./targets.js";
12
13
  import { uiFields } from "./ui-fields.js";
13
14
  import { addUiSections, renderUiFile, viewName } from "./ui-file.js";
@@ -45,7 +46,7 @@ const planScaffold = async (input) => {
45
46
  table,
46
47
  resourceNameOf: (schema, name) => names.get(`${schema}.${name}`) ?? name
47
48
  });
48
- const targets = input.tables.filter((table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table)).sort((a, b) => tableKey(a).localeCompare(tableKey(b)));
49
+ const targets = dependencyOrder(input.tables.filter((table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table)));
49
50
  const changes = [];
50
51
  const drift = [];
51
52
  const warnings = [];
@@ -0,0 +1,26 @@
1
+ import { tableKey } from "../db/model.js";
2
+ //#region src/scaffold/table-order.ts
3
+ /**
4
+ * The tables in the order their resources are registered in config/index.ts, which is the sidebar's and so the table
5
+ * the app opens on: each after the tables its foreign keys point to, otherwise by name. A cycle of foreign keys is
6
+ * broken where the walk by name first meets it.
7
+ */
8
+ const dependencyOrder = (tables) => {
9
+ const byKey = new Map([...tables].sort((a, b) => tableKey(a).localeCompare(tableKey(b))).map((table) => [tableKey(table), table]));
10
+ const ordered = [];
11
+ const visited = /* @__PURE__ */ new Set();
12
+ const visit = (key) => {
13
+ const table = byKey.get(key);
14
+ if (!table || visited.has(key)) return;
15
+ visited.add(key);
16
+ for (const foreignKey of table.foreignKeys) visit(tableKey({
17
+ schema: foreignKey.refSchema,
18
+ name: foreignKey.refTable
19
+ }));
20
+ ordered.push(table);
21
+ };
22
+ for (const key of byKey.keys()) visit(key);
23
+ return ordered;
24
+ };
25
+ //#endregion
26
+ export { dependencyOrder };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.46.8",
3
+ "version": "0.46.10",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -36,11 +36,11 @@
36
36
  "@better-auth/core": "^1.7.12",
37
37
  "@hono/node-server": "^2.1.3",
38
38
  "@hono/vite-dev-server": "^0.26.1",
39
- "@protobase/layout": "0.46.8",
40
- "@protobase/query": "0.46.8",
41
- "@protobase/schema": "0.46.8",
42
- "@protobase/server": "0.46.8",
43
- "@protobase/ui": "0.46.8",
39
+ "@protobase/layout": "0.46.10",
40
+ "@protobase/query": "0.46.10",
41
+ "@protobase/schema": "0.46.10",
42
+ "@protobase/server": "0.46.10",
43
+ "@protobase/ui": "0.46.10",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -16,6 +16,8 @@ Describe the tables of an existing Postgres database as resources, with their fi
16
16
  - [Record validation](../reference/data-config.md#resource): A rule over the whole record runs on every create and update and reports each problem on the field it concerns.
17
17
  - [Rollups and formulas](../reference/data-config.md#rollups-and-formulas) (beta): Fields that hold counts, sums, averages, minimums or maximums of related records, or values calculated from the record's own numbers, kept current by the database.
18
18
  - [Sensitive fields](../reference/data-config.md#sensitive-fields): Values such as bank account numbers are left out of every response and shown masked. A permitted user reveals one value at a time, and each reveal is audited.
19
+ - [Recent strong sign-in](../reference/data-config.md#recent-strong-sign-in): A sensitive field can ask for a passkey or a second step in the last minutes before it is revealed. The record page asks the person to confirm it's them, then shows it.
20
+ - [Computed reveals](../reference/data-config.md#computed-reveals) (beta): A secret kept elsewhere, or built from several values, is revealed like a sensitive field, with the same access, audit and recent sign-in check, but made when it is asked for.
19
21
  - [Encrypted fields](../reference/data-config.md#encrypted-fields): A sensitive text field is encrypted with the app's own key before it is stored, so dumps, backups and SQL readers see only ciphertext. A command encrypts the values a column already holds.
20
22
  - [Encryption key rotation](../reference/data-config.md#the-key): The encryption key can be replaced without downtime. CLI commands re-encrypt stored values and report what is left.
21
23
  - [Schema API reference](../reference/data-config.md#schema-api-reference): Every builder, option and type of `@protobase/schema` has a doc comment, shown in your editor and in the generated API reference, and the types the builders return are exported for helpers of your own.
@@ -114,6 +114,8 @@ Get responses carry `permissions: { update, delete, fields }`, where `fields` ma
114
114
 
115
115
  A field declared [`.sensitive()`](data-config.md#sensitive-fields) is in `/meta` (marked `sensitive: true`), in record `permissions.fields` and in create and update bodies, but in no list, get, `:search`, `:seek`, write or batch response, and `filter`, `order_by`, `fields` and the aggregates refuse it like an unknown field. `POST /{resource}/{key}:reveal` with `{ "field": "<name>" }` returns one record's value. It needs read access to the record and the field: another tenant's record, a row outside the caller's row filter or a key that does not exist is a `404`, a field the caller cannot read or that is not sensitive a `400`. An [encrypted field](data-config.md#encrypted-fields)'s reveal decrypts its value, and an empty one reveals `null`; a value that does not decrypt is a `500` reported to the operator, without an audit event. An update that changes the key of a record with encrypted fields is a `400` `key-change-unsupported`.
116
116
 
117
+ A field with [`.strongSignIn()`](data-config.md#recent-strong-sign-in) is a `403` `strong-sign-in-required`, whose problem carries `minutes`, until the caller's sign-in proved a passkey or a second step that recently. The same request reveals a resource's [computed reveals](data-config.md#computed-reveals) by name, whose value the server makes when asked.
118
+
117
119
  Before answering, the server publishes an audit event to `options.audit`, and when publishing fails the reveal fails (`500`), so no value leaves without its event. The event never holds the value:
118
120
 
119
121
  ```ts
@@ -307,6 +307,14 @@ Turning it on, off, or making new backup codes asks for the account's password w
307
307
 
308
308
  Sign-in with GitHub or another [provider](#sign-in-with-github) is not asked for the second step.
309
309
 
310
+ ## Recent strong sign-in
311
+
312
+ Some values ask for a sign-in that proved a passkey or a second step not long ago, such as a field with [`.strongSignIn()`](data-config.md#recent-strong-sign-in). Better Auth's sessions do not say how they began, so the server notes it: each passkey sign-in (`/passkey/verify-authentication`), and each correct second step (`/two-factor/verify-totp`, `verify-otp` and `verify-backup-code`), whether it finishes a sign-in or confirms the session the browser has, stores the time beside the session, in the `verification` table, until the session expires. It needs no migration. Staff sessions are never noted.
313
+
314
+ `betterAuthAuthenticator` gives a token of the person's own session `signIn.strongAt()`, which reads that time when a request needs it, so other requests do no extra lookup. An app with its own `authenticate` sets `signIn: { staff: false, strongAt }` on the sessions it returns, `strongAt` resolving to a `Date` or `undefined`; without it, such values are refused.
315
+
316
+ Confirming it's them later counts from then: a passkey signs the browser in anew, and a code from the authenticator app, or a backup code, confirms the session it has. `createAuthSession` from `@protobase/client` does both, with `signInWithPasskey()` and `verifyTwoFactor({ method: 'totp', code })`.
317
+
310
318
  ## Sign-in policy
311
319
 
312
320
  Admins set how people sign in on the app's **Sign-in policy** page (the profile menu, under the user). Each method takes a rule:
@@ -67,7 +67,7 @@ Interactively, each new column shows its proposal: accept, edit (name, type) or
67
67
 
68
68
  ### Re-running
69
69
 
70
- Existing `data.ts` files are edited with ts-morph: only columns that are neither declared nor `null` are added, at the end of `.fields({...})`. Nothing else is rewritten, and key, soft delete and tenant calls are only written when a resource is created. `ui.ts` gets only missing sections. `config/index.ts` gets exports for resources created in the run (all resources when it does not exist yet); existing lines are never touched. A run with nothing new changes nothing. `schema.table.column` on an unscaffolded table scaffolds the whole table.
70
+ Existing `data.ts` files are edited with ts-morph: only columns that are neither declared nor `null` are added, at the end of `.fields({...})`. Nothing else is rewritten, and key, soft delete and tenant calls are only written when a resource is created. `ui.ts` gets only missing sections. `config/index.ts` gets exports for resources created in the run (all resources when it does not exist yet), each table after the tables its foreign keys point to and otherwise by name, so the sidebar, and the table the app opens on, start with tables others refer to; existing lines are never touched. A run with nothing new changes nothing. `schema.table.column` on an unscaffolded table scaffolds the whole table.
71
71
 
72
72
  ### Drift report
73
73
 
@@ -110,6 +110,7 @@ Every option returns a new [field](https://docs.protobase.net/api/schema/interfa
110
110
  | `.access({ read, create, update })` | Role rules for this column. See [Access](#access). |
111
111
  | `.sensitive()` | Hidden like a password: no response carries it, and a caller who may read it reveals one record's value at a time. See [Sensitive fields](#sensitive-fields). |
112
112
  | `.encrypted()` | Sensitive, and stored encrypted with the app's own key, so the database only ever holds ciphertext. Text only. See [Encrypted fields](#encrypted-fields). |
113
+ | `.strongSignIn({ minutes })` | Sensitive, and revealed only after a passkey or a second step in the last `minutes` (15 by default). See [Recent strong sign-in](#recent-strong-sign-in). |
113
114
  | `.ai({ prompt })` | A job fills the field from `prompt`, `{field}` replaced by the record's values, after a create and after an update of a field the prompt reads, as the user who wrote. Text or enum, optional. See [AI fields and actions](ai.md). |
114
115
  | `.rollup({ from, via, fn, field })` | The database keeps the field from the records of another resource: their count, sum, average, least or greatest value. Read-only. See [Rollups and formulas](#rollups-and-formulas). |
115
116
  | `.formula(expression)` | The database computes the field from the record's other number fields, as a generated column. Read-only. See [Rollups and formulas](#rollups-and-formulas). |
@@ -218,6 +219,38 @@ A sensitive field cannot be `.filterable()`, `.sortable()`, aliased, searched, o
218
219
 
219
220
  A [webhook subscription](webhooks.md) delivering `as` a role runs that role's access rules on a captured change, which holds no sensitive field. A rule or row filter that reads one there throws, and the change is kept as failed for that subscription instead of delivered, so decide that access on a field that is not sensitive. A rule that reads the field before it checks the role, such as `record.api_secret == null || ctx.user.roles.includes('admin')`, fails even for `as: { roles: ['admin'] }`: check the role first, as in `ctx.user.roles.includes('admin') || ...`.
220
221
 
222
+ ### Recent strong sign-in
223
+
224
+ A field such as a recovery code or an API secret can ask for more than read access: `.strongSignIn()` reveals it only to someone whose sign-in proved a passkey or a second step in the last 15 minutes, or `minutes` you give. It is sensitive too, so all of the above applies, and `/meta` marks it `strongSignIn: { minutes }`.
225
+
226
+ ```ts
227
+ recoveryCode: f.text().encrypted().strongSignIn({ minutes: 10 }),
228
+ ```
229
+
230
+ Without such a sign-in, the reveal is refused with `403` `strong-sign-in-required` and the number of minutes, before anything is decrypted or audited. The record page then asks the person to confirm it's them, with a passkey or the code of their authenticator app, whichever their account has, and shows the value once they did. A passkey sign-in counts, as does a password or emailed code followed by the [second step](auth.md#two-factor-authentication); confirming later counts from then. Staff [signed in as someone](auth.md#staff-sign-in) and an outside app acting as them, such as an MCP client, never count: they proved nothing as the person. See [Recent strong sign-in](auth.md#recent-strong-sign-in) for how the server knows.
231
+
232
+ ### Computed reveals
233
+
234
+ :::caution[Beta]
235
+ The record page does not show computed reveals yet: an app's own component reveals them with the client's `reveal`.
236
+ :::
237
+
238
+ Some secrets are not in the app's database, such as an API key another service keeps, or are built from several values, such as a file of settings. `.reveals()` names values revealed like a sensitive field but made when one is asked for:
239
+
240
+ ```ts
241
+ resource('apps')
242
+ // ...fields, key and tenant
243
+ .reveals({
244
+ env: {
245
+ value: (app, caller) => secrets.envFile(app.id),
246
+ read: roles.is('owner'),
247
+ strongSignIn: { minutes: 15 },
248
+ },
249
+ })
250
+ ```
251
+
252
+ `POST /apps/{key}:reveal` with `{ "field": "env" }` reads the record as a get does, inside the caller's tenant, row filter and record rules, so a record they cannot read is a `404`. `value` gets the record with every field the caller may read but the sensitive ones, and the caller's user and organization; its answer is the value, `null` when it returns nothing. `read` is a role rule like a field's own read rule, and a caller it leaves out gets `400` as for an unknown field. `strongSignIn` asks for a [recent strong sign-in](#recent-strong-sign-in), 15 minutes when it names no minutes. Each reveal publishes the same audit event as a field's, with the reveal's name as `field`, before the value is returned. A reveal cannot have the name of a field of its resource.
253
+
221
254
  ## Encrypted fields
222
255
 
223
256
  An encrypted field is a [sensitive field](#sensitive-fields) whose value the server encrypts before it reaches the database, so a dump, a backup, a replica, a realtime subscriber or anyone running SQL sees only ciphertext. Only its reveal decrypts it, for a caller who may read the record and the field, and every reveal is audited. Every API write encrypts it: the record form, REST, batches, imports, [public forms](forms.md) and `records` in [API functions](../guides/api-functions.md). The [Supabase-compatible REST API](supabase-rest.md#encrypted-fields) refuses to write or filter it.
@@ -4,7 +4,7 @@
4
4
 
5
5
  How sidebar entries are grouped, and how an entry lists recent records with status dots.
6
6
 
7
- The admin's sidebar has one entry per resource view, grouped by `nav.group` (default: the database schema) and sorted by `nav.order`. A view's [named lists](ui-config.md#more-than-one-list) are entries of their own, placed by their own `nav`. `nav({ hidden: true })` leaves a resource out, for line and link tables; a resource in the [user menu](user-menu.md) is left out too. [Composed pages](layouts.md#setup) have entries of their own, and groups that hold pages come first. A [remote resource](remote-resources.md) has its entry where its source's view places it; while its source cannot be reached, it sits under the source's label, marked "Cannot reach" with the source's name.
7
+ The admin's sidebar has one entry per resource view, grouped by `nav.group` (default: the database schema, with no group name for `public`) and sorted by `nav.order`, then by the order `config/index.ts` exports them, in `protobase dev` and in a built bundle alike. The app opens on the first entry. A view's [named lists](ui-config.md#more-than-one-list) are entries of their own, placed by their own `nav`. `nav({ hidden: true })` leaves a resource out, for line and link tables; a resource in the [user menu](user-menu.md) is left out too. [Composed pages](layouts.md#setup) have entries of their own, and groups that hold pages come first. A [remote resource](remote-resources.md) has its entry where its source's view places it; while its source cannot be reached, it sits under the source's label, marked "Cannot reach" with the source's name.
8
8
 
9
9
  ## The current organization
10
10