@protobase/cli 0.46.9 → 0.46.11

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.9";
2
+ var version = "0.46.11";
3
3
  //#endregion
4
4
  export { version };
@@ -27,12 +27,14 @@ const reasons = {
27
27
  };
28
28
  const checkDatabase = async (url, projectDir) => {
29
29
  const sql = connect(url, { connectTimeout: 3 });
30
- const failure = await sql`select 1`.then(() => void 0, (error) => {
30
+ const code = await sql`select 1`.then(() => void 0, (error) => {
31
31
  if (!error.code || !(error.code in reasons)) throw error;
32
- return reasons[error.code];
32
+ return error.code;
33
33
  });
34
34
  await sql.end();
35
- if (failure) throw new Error(`Cannot reach the database at ${describeTarget(url)}: ${failure}.${await startHint(projectDir)}`);
35
+ if (!code) return;
36
+ const hint = code === "ECONNREFUSED" ? await startHint(projectDir) : "";
37
+ throw new Error(`Cannot reach the database at ${describeTarget(url)}: ${reasons[code]}.${hint}`);
36
38
  };
37
39
  //#endregion
38
40
  export { checkDatabase };
@@ -1,4 +1,6 @@
1
1
  //#region src/dev/entry.d.ts
2
2
  declare const _default: import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, import("hono/types").BlankSchema | import("hono/types").MergeSchemaPath<import("hono/types").BlankSchema, "/">, "/", "/">;
3
+ /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
4
+ export declare const anyUsers: () => Promise<boolean> | Promise<undefined>;
3
5
  //#endregion
4
6
  export { _default as default };
package/dist/dev/entry.js CHANGED
@@ -49,11 +49,7 @@ const { admin, jobs } = projectAdmin({
49
49
  }, project.exports, db, ui, reporter, upgradeWebSocket);
50
50
  await devJobs(db, jobs);
51
51
  var entry_default = withDevServiceWorker(new Hono(), Boolean(project.notifications)).route("/", admin);
52
- if (project.auth && !store.__protobaseNoUsersShown) {
53
- store.__protobaseNoUsersShown = true;
54
- hasUsers(project.auth).then((any) => {
55
- if (!any) console.log("No users yet. Create the first admin with: protobase users create you@example.com");
56
- }, (error) => console.error(`Could not check for users, is the auth schema migrated? ${error.message}`));
57
- }
52
+ /** Whether the auth store has a user yet, for the banner's sign-in line; undefined without one. */
53
+ const anyUsers = () => project.auth ? hasUsers(project.auth) : Promise.resolve(void 0);
58
54
  //#endregion
59
- export { entry_default as default };
55
+ export { anyUsers, entry_default as default };
@@ -0,0 +1,21 @@
1
+ //#region src/dev/login-line.ts
2
+ const runners = {
3
+ bun: "bun run protobase",
4
+ pnpm: "pnpm protobase",
5
+ yarn: "yarn protobase",
6
+ npm: "npx protobase"
7
+ };
8
+ const protobaseCommand = (userAgent) => runners[userAgent?.split("/")[0] ?? ""] ?? "npx protobase";
9
+ /**
10
+ * The banner's sign-in line: with an empty auth store, the exact command that creates the first admin, since nobody can
11
+ * sign in until it runs. `anyUsers` is undefined when the project has no auth store the users commands manage.
12
+ */
13
+ const loginLine = (anyUsers, userAgent) => {
14
+ if (anyUsers === void 0) return "";
15
+ const protobase = protobaseCommand(userAgent);
16
+ const create = `${protobase} users create you@example.com --generate-password`;
17
+ if (!anyUsers) return ` login no users yet; create the first admin with:\n ${create}\n`;
18
+ return ` login sign in as one of its users (\`${protobase} users list\`), or add one: ${create}\n`;
19
+ };
20
+ //#endregion
21
+ export { loginLine, protobaseCommand };
@@ -0,0 +1,42 @@
1
+ import { createServer } from "node:net";
2
+ //#region src/dev/loopback.ts
3
+ const devHost = "127.0.0.1";
4
+ const loopbacks = [devHost, "::1"];
5
+ const missingFamily = ["EADDRNOTAVAIL", "EAFNOSUPPORT"];
6
+ const listen = (server, port, host) => new Promise((resolve, reject) => {
7
+ server.once("error", reject);
8
+ server.listen(port, host, () => {
9
+ server.off("error", reject);
10
+ resolve();
11
+ });
12
+ });
13
+ const hold = async (server, port, host) => {
14
+ try {
15
+ await listen(server, port, host);
16
+ return true;
17
+ } catch (error) {
18
+ const { code } = error;
19
+ if (code === "EADDRINUSE") throw new Error(`Port ${port} is in use by another server on ${host}, which would answer http://localhost:${port} instead. Stop it, or run on a free port with --port`);
20
+ if (code && missingFamily.includes(code)) return false;
21
+ throw error;
22
+ }
23
+ };
24
+ /** Fails when another process holds `port` on either loopback address, before the dev server starts. */
25
+ const checkPortFree = async (port) => {
26
+ for (const host of loopbacks) {
27
+ const probe = createServer();
28
+ if (await hold(probe, port, host)) await new Promise((resolve) => probe.close(resolve));
29
+ }
30
+ };
31
+ /**
32
+ * Hands each connection to `port` on ::1 to `httpServer`, listening on 127.0.0.1, WebSocket upgrades included, until it
33
+ * closes. Returns the server listening on ::1, undefined when the machine has no IPv6 loopback.
34
+ */
35
+ const alsoOnIpv6 = async (httpServer, port) => {
36
+ const forwarder = createServer((socket) => httpServer.emit("connection", socket));
37
+ if (!await hold(forwarder, port, "::1")) return void 0;
38
+ httpServer.once("close", () => forwarder.close());
39
+ return forwarder;
40
+ };
41
+ //#endregion
42
+ export { alsoOnIpv6, checkPortFree, devHost };
package/dist/dev/run.js CHANGED
@@ -8,6 +8,8 @@ import { layoutCheck } from "../build/layout-check.js";
8
8
  import { faviconLink } from "../project/favicon-link.js";
9
9
  import { themeLink } from "../project/theme-link.js";
10
10
  import { checkDatabase } from "./check-database.js";
11
+ import { alsoOnIpv6, checkPortFree, devHost } from "./loopback.js";
12
+ import { loginLine } from "./login-line.js";
11
13
  import { stopDevJobs } from "./dev-jobs.js";
12
14
  import { isProjectFile } from "./project-files.js";
13
15
  import { apiWebSockets } from "./api-websockets.js";
@@ -58,6 +60,7 @@ const runDev = async (options, out) => {
58
60
  const appDir = options.appDir ?? adminAppDir;
59
61
  requireAppFiles(appDir);
60
62
  await checkDatabase(url, options.projectDir);
63
+ if (options.port !== 0) await checkPortFree(options.port);
61
64
  const extensions = options.extensions ?? [];
62
65
  const projectDirs = [options.projectDir, ...extensions.map((extension) => extension.dir)];
63
66
  process.env.PROTOBASE_PROJECT = options.projectDir;
@@ -73,6 +76,7 @@ const runDev = async (options, out) => {
73
76
  },
74
77
  server: {
75
78
  headers: frameHeaders,
79
+ host: devHost,
76
80
  port: options.port,
77
81
  strictPort: true,
78
82
  ...options.allowedHosts.length > 0 && { allowedHosts: options.allowedHosts },
@@ -103,17 +107,17 @@ const runDev = async (options, out) => {
103
107
  })
104
108
  ]
105
109
  });
110
+ const closeAndThrow = async (error) => {
111
+ await server.close();
112
+ throw error;
113
+ };
106
114
  await server.listen();
107
115
  const address = server.httpServer?.address();
108
116
  const port = typeof address === "object" && address ? address.port : options.port;
117
+ if (server.httpServer) await alsoOnIpv6(server.httpServer, port).catch(closeAndThrow);
109
118
  process.env.PROTOBASE_DEV_URL = `http://localhost:${port}`;
110
- await server.ssrLoadModule(entry).catch(async (error) => {
111
- await server.close();
112
- throw error;
113
- });
114
- out(`protobase dev ready at http://localhost:${port}\n`);
115
- out(` project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n`);
116
- out(" login sign in with a user created by `protobase users create`\n");
119
+ const anyUsers = await (await server.ssrLoadModule(entry).catch(closeAndThrow)).anyUsers().catch(closeAndThrow);
120
+ out(`protobase dev ready at http://localhost:${port}\n project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n` + loginLine(anyUsers, process.env.npm_config_user_agent));
117
121
  return server;
118
122
  };
119
123
  //#endregion
@@ -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,8 @@ 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 { protobaseSchemas } from "./protobase-tables.js";
12
+ import { dependencyOrder } from "./table-order.js";
11
13
  import { isExcluded, matchesTarget } from "./targets.js";
12
14
  import { uiFields } from "./ui-fields.js";
13
15
  import { addUiSections, renderUiFile, viewName } from "./ui-file.js";
@@ -39,13 +41,15 @@ const change = (file, before, after) => before === after ? [] : [{
39
41
  }];
40
42
  const planScaffold = async (input) => {
41
43
  const { configDir, existing, ui } = input;
42
- const names = assignNames(input.tables, existing);
44
+ const skipped = protobaseSchemas(input.tables.filter((table) => matchesTarget(input.target, table)), input.target);
45
+ const isProtobase = (table) => skipped.some((schema) => schema.tables.includes(table));
46
+ const names = assignNames(input.tables.filter((table) => !isProtobase(table)), existing);
43
47
  const byTable = new Map(existing.map((resource) => [resource.table, resource]));
44
48
  const context = (table) => ({
45
49
  table,
46
50
  resourceNameOf: (schema, name) => names.get(`${schema}.${name}`) ?? name
47
51
  });
48
- const targets = input.tables.filter((table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table)).sort((a, b) => tableKey(a).localeCompare(tableKey(b)));
52
+ const targets = dependencyOrder(input.tables.filter((table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table) && !isProtobase(table)));
49
53
  const changes = [];
50
54
  const drift = [];
51
55
  const warnings = [];
@@ -68,6 +72,10 @@ const planScaffold = async (input) => {
68
72
  names: [viewName(identifier)]
69
73
  });
70
74
  };
75
+ for (const resource of existing) {
76
+ const table = input.tables.find((each) => tableKey(each) === resource.table);
77
+ if (table && isProtobase(table)) warnings.push(`${resource.table}: one of Protobase's own tables, which ${resource.dir}/data.ts declares; remove that resource`);
78
+ }
71
79
  for (const table of targets) {
72
80
  const key = tableKey(table);
73
81
  const current = byTable.get(key);
@@ -115,6 +123,7 @@ const planScaffold = async (input) => {
115
123
  changes,
116
124
  drift,
117
125
  warnings,
126
+ skipped,
118
127
  live
119
128
  };
120
129
  };
@@ -0,0 +1,44 @@
1
+ //#region src/scaffold/protobase-tables.ts
2
+ const storeCore = [
3
+ "user",
4
+ "session",
5
+ "account",
6
+ "verification"
7
+ ];
8
+ const storeTables = /* @__PURE__ */ new Set([
9
+ ...storeCore,
10
+ "jwks",
11
+ "passkey",
12
+ "two_factor",
13
+ "sign_in_policy",
14
+ "staff_sign_in"
15
+ ]);
16
+ const isStoreTable = (name) => storeTables.has(name) || name.startsWith("oauth_");
17
+ const bySchema = (tables) => {
18
+ const groups = /* @__PURE__ */ new Map();
19
+ for (const table of tables) groups.set(table.schema, [...groups.get(table.schema) ?? [], table]);
20
+ return groups;
21
+ };
22
+ const authStore = (schema, tables) => {
23
+ if (schema === "auth") return tables;
24
+ if (!storeCore.every((name) => tables.some((table) => table.name === name))) return [];
25
+ return schema === "public" ? tables.filter((table) => isStoreTable(table.name)) : tables;
26
+ };
27
+ const jobQueue = (schema, tables) => schema === "jobs" && ["job", "version"].every((name) => tables.some((table) => table.name === name)) ? tables : [];
28
+ const protobaseSchemas = (tables, target) => [...bySchema(tables)].flatMap(([schema, own]) => {
29
+ if (target.schema === schema) return [];
30
+ const store = authStore(schema, own);
31
+ if (store.length > 0) return [{
32
+ schema,
33
+ what: "auth store",
34
+ tables: store
35
+ }];
36
+ const queue = jobQueue(schema, own);
37
+ return queue.length > 0 ? [{
38
+ schema,
39
+ what: "job queue",
40
+ tables: queue
41
+ }] : [];
42
+ });
43
+ //#endregion
44
+ export { protobaseSchemas };
@@ -12,6 +12,7 @@ const readText = (file) => readFile(file, "utf8").catch((error) => {
12
12
  if (error.code === "ENOENT") return void 0;
13
13
  throw error;
14
14
  });
15
+ const skippedLine = ({ schema, what, tables }) => `skipped ${schema === "public" ? tables.map((table) => `public.${table.name}`).join(", ") : `schema ${schema}`}, Protobase's ${what}; pass "${schema}" as the target to scaffold it anyway\n`;
15
16
  const write = async ({ path: file, after }) => {
16
17
  await mkdir(path.dirname(file), { recursive: true });
17
18
  await writeFile(file, after);
@@ -43,6 +44,7 @@ const runScaffold = async (options, out) => {
43
44
  for (const change of plan.changes) if (!options.dryRun) out(`${change.before === void 0 ? "created" : "updated"} ${change.path}\n`);
44
45
  if (plan.changes.length === 0) out("Nothing to do, config is up to date.\n");
45
46
  else if (options.dryRun) out(`${plan.changes.length} file(s) would change; nothing was written (--dry-run).\n`);
47
+ for (const schema of plan.skipped) out(skippedLine(schema));
46
48
  for (const warning of plan.warnings) out(`warning: ${warning}\n`);
47
49
  if (plan.drift.length > 0) {
48
50
  out("\nDrift:\n");
@@ -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 };
@@ -6,8 +6,23 @@ import { Node, SyntaxKind } from "ts-morph";
6
6
  const auditField = /^(created|updated)(At|On|_at|_on)$/;
7
7
  const longText = /^(notes?|description|body|comment|comments)$/;
8
8
  const listSize = 5;
9
+ const secretWords = /* @__PURE__ */ new Set([
10
+ "password",
11
+ "passwd",
12
+ "hash",
13
+ "token",
14
+ "secret",
15
+ "salt",
16
+ "otp"
17
+ ]);
18
+ const secretPairs = ["private key", "api key"];
19
+ const isSecretLike = (name) => {
20
+ const words = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
21
+ const joined = words.join(" ");
22
+ return words.some((word) => secretWords.has(word)) || secretPairs.some((pair) => joined.includes(pair));
23
+ };
9
24
  const listColumns = (fields) => {
10
- const plain = fields.filter((f) => f.role === "plain" && f.type !== "json" && !auditField.test(f.name));
25
+ const plain = fields.filter((f) => f.role === "plain" && f.type !== "json" && !auditField.test(f.name) && !isSecretLike(f.name));
11
26
  const scalars = plain.filter((f) => f.type !== "relation" && !longText.test(f.name));
12
27
  const relations = plain.filter((f) => f.type === "relation");
13
28
  const picked = [...scalars.slice(0, listSize), ...scalars.length < 3 ? relations : []].slice(0, listSize);
@@ -37,4 +52,4 @@ const addUiSections = (text, target, sections) => {
37
52
  return source.getFullText();
38
53
  };
39
54
  //#endregion
40
- export { addUiSections, listColumns, renderUiFile, viewName };
55
+ export { addUiSections, isSecretLike, listColumns, renderUiFile, viewName };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.46.9",
3
+ "version": "0.46.11",
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.9",
40
- "@protobase/query": "0.46.9",
41
- "@protobase/schema": "0.46.9",
42
- "@protobase/server": "0.46.9",
43
- "@protobase/ui": "0.46.9",
39
+ "@protobase/layout": "0.46.11",
40
+ "@protobase/query": "0.46.11",
41
+ "@protobase/schema": "0.46.11",
42
+ "@protobase/server": "0.46.11",
43
+ "@protobase/ui": "0.46.11",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -41,7 +41,7 @@ bun run --cwd examples/erp protobase users create you@example.com --generate-pas
41
41
  bun run --cwd examples/erp dev # http://localhost:5173
42
42
  ```
43
43
 
44
- `BETTER_AUTH_SECRET` in `examples/erp/.env` signs the session cookies; see [Login with Better Auth](reference/auth.md). `protobase dev` serves the admin app and the API on one port and reloads both on every change ([CLI](reference/cli.md#dev)).
44
+ `BETTER_AUTH_SECRET` in `examples/erp/.env` signs the session cookies; see [Login with Better Auth](reference/auth.md). `protobase dev` serves the admin app and the API on one port and reloads both on every change ([CLI](reference/cli.md#dev)). Its startup message says how to sign in: while the database has no users, it prints the exact `users create` command for the first admin. It stops with a clear message when another server holds its port; pass `--port 5174` to run a second app beside it.
45
45
 
46
46
  ## Run the real estate example
47
47
 
@@ -82,7 +82,7 @@ The columns Better Auth needs that the table lacks come first, from a migration
82
82
  | `PROTOBASE_OPERATOR_ISSUER`, `PROTOBASE_OPERATOR_CLIENT_ID`, `PROTOBASE_OPERATOR_CLIENT_SECRET` | the [operator provider](#operator-provider) its staff sign in with to sign in as people, passed by the platform; staff sign-in is off without them. `PROTOBASE_OPERATOR_NAME` and `PROTOBASE_OPERATOR_GROUP` are optional |
83
83
  | `PROTOBASE_TRUSTED_PROXIES` | the proxies in front of `protobase serve`, addresses or CIDR ranges, comma separated, such as `172.30.87.1`, the Docker network's gateway in the [compose template](../guides/deploy.md#compose-template); see [Client addresses](#client-addresses) |
84
84
 
85
- - Cookies are `SameSite=Lax`, and `Secure` when `BETTER_AUTH_URL` is https.
85
+ - Cookies are `SameSite=Lax`, and `Secure` when `BETTER_AUTH_URL` is https. When it is http with a port, their names carry it (`better-auth-5173.session_token`), because a browser shares cookies across the ports of a host: two apps on `localhost` then keep their own sign-ins.
86
86
  - Sign-in is rate limited (5 password attempts per minute and client by default, `signInPerMinute`, which also limits [sign-up](#open-sign-up) requests; 3 per minute for emailed codes); [Client addresses](#client-addresses) says how a client is known.
87
87
  - New passwords need at least 12 characters.
88
88
  - `appName` is the app's name: authenticator apps and passkey prompts show it, the admin app's sidebar shows it at the top beside the app's [icon](app-identity.md#the-icons), else Protobase's mark (Protobase's wordmark when it is `Protobase`), every browser tab of the admin app ends its title with it, the [installed app](installable-app.md) is called by it, the [auth emails](email.md#protobases-own-mail) name the app with it, and the platform's mailer sends them as it (the sender's display name). `PROTOBASE_APP_NAME`, when set, overrides it; without either it is `Protobase`, then without a display name. See [App identity](app-identity.md).
@@ -249,7 +249,7 @@ With mail configured, the account page's Profile tab offers "Change email": the
249
249
  | `requestEmailChange(newEmail)` | `POST /api/auth/email-otp/request-email-change` with `{ newEmail }`: mails the code to the new address |
250
250
  | `changeEmail(newEmail, code)` | `POST /api/auth/email-otp/change-email` with `{ newEmail, otp }`: moves the account once the code is right (a wrong one is `INVALID_OTP`, an old one `OTP_EXPIRED`) |
251
251
 
252
- - A code works for 5 minutes, once, and three wrong tries end it. Codes are stored hashed.
252
+ - A code works for 10 minutes, once, and three wrong tries end it. Codes are stored hashed.
253
253
  - An address another account has gets no code, and the answer is the same, so it does not tell who has an account.
254
254
  - Each endpoint is limited to 3 requests per minute and client. Without mail both answer `404`.
255
255
  - A [staff session](#staff-sign-in) cannot change the address (`STAFF_CANNOT_CHANGE_SIGN_IN`), and neither can an [MCP client](#oauth-for-mcp-clients)'s token (`401`).
@@ -258,7 +258,7 @@ With mail configured, the account page's Profile tab offers "Change email": the
258
258
 
259
259
  With mail configured, the sign-in page offers "Email me a sign-in code": the person enters their address, gets a 6-digit code, and signs in with it instead of a password. It is Better Auth's [email OTP](https://www.better-auth.com/docs/plugins/email-otp) plugin: `POST /api/auth/email-otp/send-verification-otp` with `{ email, type: "sign-in" }`, then `POST /api/auth/sign-in/email-otp` with `{ email, otp }`.
260
260
 
261
- - A code works for 5 minutes, once, and three wrong tries end it; asking again sends a new one and the old one stops working. Codes are stored hashed.
261
+ - A code works for 10 minutes, once, and three wrong tries end it; asking again sends a new one and the old one stops working. Codes are stored hashed.
262
262
  - It never creates an account: an address no account uses gets no code but an email saying so, which suggests signing in with the address the person signed up with. The answer is the same either way, so it does not tell who has an account.
263
263
  - Only sign-in codes are mailed this way. The plugin's own email verification and password reset endpoints are off (`404`), and asking for another type of code answers `400`. Its address change is on, as [Changing the address](#changing-the-address) describes.
264
264
  - An account with [two-factor authentication](#two-factor-authentication) is asked for its second step after the code too, as after a password.
@@ -277,7 +277,7 @@ The sign-in page then offers "Create an account", and so do [sign-in prompts](ui
277
277
  - `role` is one of `roles`, and never `admin`: `createAuth` stops with an error otherwise. Give it the least a stranger may hold; a request that names another role, or sets `role` through Better Auth's own endpoints, does not get it.
278
278
  - It needs mail: without a mailer it is not offered, `GET /api/auth/status` has no `signUp`, and its endpoints answer `404`. Not with [organizations](#organizations), whose people join by invitation.
279
279
  - `POST /api/auth/sign-up/send-code` with `{ email }` mails the code. It answers the same whether the address has an account or not; an address that has one is mailed a note saying so instead of a code, with a link to the sign-in page, so nobody can tell from the answer, and no second account is made.
280
- - `POST /api/auth/sign-up/verify-code` with `{ email, code }` checks the code on its own and answers `{ ticket }`. A code works for 5 minutes, once, and three wrong tries end it; asking again sends a new one. Codes are stored hashed.
280
+ - `POST /api/auth/sign-up/verify-code` with `{ email, code }` checks the code on its own and answers `{ ticket }`. A code works for 10 minutes, once, and three wrong tries end it; asking again sends a new one. Codes are stored hashed.
281
281
  - `POST /api/auth/sign-up/create` with `{ ticket, name, password? }` makes the account for the address whose code was right, and signs in. A ticket works for 30 minutes, once, and is stored hashed; a password the policy refuses leaves it for another try. A used or expired one answers `SIGN_UP_TICKET_INVALID`, and the sign-up starts again with the address.
282
282
  - The password follows the [sign-in policy](#sign-in-policy) as for an invitation: none while passwords are off, optional while emailed codes are on, 12 characters or more. What the policy requires, such as two-factor authentication, is set up after the first sign-in, as for every account.
283
283
  - The three requests are limited per minute and client like sign-in (`signInPerMinute`, default 5), and refused (`NO_ADMIN_YET`) while the store has no user.
@@ -301,7 +301,7 @@ People add passkeys (Face ID, Touch ID, Windows Hello, a phone or a security key
301
301
  On their account page, people turn on a second step after a password or an emailed sign-in code, with Better Auth's [two-factor](https://www.better-auth.com/docs/plugins/2fa) plugin:
302
302
 
303
303
  - **Authenticator app:** the page shows a QR code (and the key, to type in), the person confirms it with a code from the app, and gets ten backup codes that each work once instead of a code. New backup codes replace the old ones.
304
- - **Emailed code:** with mail configured, a 6-digit code mailed at each sign-in, valid for 5 minutes. An account with an app can also choose an emailed code at sign-in. Backup codes come with the app only.
304
+ - **Emailed code:** with mail configured, a 6-digit code mailed at each sign-in, valid for 10 minutes. An account with an app can also choose an emailed code at sign-in. Backup codes come with the app only.
305
305
 
306
306
  Turning it on, off, or making new backup codes asks for the account's password when it has one. At sign-in, a correct password or code answers `{ "twoFactorRedirect": true, "twoFactorMethods": ["totp", "otp"] }` instead of a session, and `POST /api/auth/two-factor/verify-totp`, `verify-otp` or `verify-backup-code` with `{ code, trustDevice? }` finishes it; `trustDevice` skips the step in that browser for 30 days. Ten wrong codes in a row lock the account's second step for 15 minutes.
307
307
 
@@ -548,7 +548,7 @@ It is Better Auth's organization plugin, with its tables named in snake_case (`o
548
548
 
549
549
  **Ids.** `generateId` 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 `onCreated`, as the ERP example does (`examples/erp/auth/auth.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.
550
550
 
551
- The app's own pages are under the profile menu: the switcher, "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`, ...).
551
+ 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`, ...).
552
552
 
553
553
  ## Tokens and roles
554
554
 
@@ -32,12 +32,14 @@ protobase scaffold <connection string | --env DATABASE_URL> [target] [options]
32
32
 
33
33
  `target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended.
34
34
 
35
+ Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the `auth` schema, another schema holding Better Auth's `user`, `session`, `account` and `verification` tables (in `public`, only the auth store's tables), and pg-boss's `jobs` schema. A line names each one skipped; a target naming the schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it.
36
+
35
37
  | Option | Effect |
36
38
  | --- | --- |
37
39
  | `--config <dir>` | config folder, default `config` |
38
40
  | `--yes` | accept every proposal, no prompts (required without a TTY) |
39
41
  | `--dry-run` | print a diff, write nothing |
40
- | `--ui` | also write `ui.ts` (`.names()` and `.list()`) |
42
+ | `--ui` | also write `ui.ts` (`.names()` and `.list()`); the list never shows a secret-like column (`password`, `hash`, `token`, `secret`, `salt`, `otp`, `private_key`, `api_key` in its name) |
41
43
  | `--ui-list`, `--ui-section <names\|list>` | write only those `ui.ts` sections |
42
44
  | `--exclude <schema[.table]>` | skip tables, repeatable |
43
45
 
@@ -67,7 +69,7 @@ Interactively, each new column shows its proposal: accept, edit (name, type) or
67
69
 
68
70
  ### Re-running
69
71
 
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.
72
+ 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
73
 
72
74
  ### Drift report
73
75
 
@@ -103,9 +105,10 @@ protobase dev [--port 5173] [--env DATABASE_URL] [--cache-dir <dir>] [--allowed-
103
105
 
104
106
  One process, one port: Vite serves the admin app from `@protobase/ui`'s `src/app/` (`dist/app/` when installed; `index.html` and `main.tsx`, or `main.js`; the command fails with a clear message when they are missing) and `@hono/vite-dev-server` mounts the Hono app from `createAdmin` under `/api`, supabase-js's `/api/sb` included. Open `http://localhost:<port>`; the API reference is at `/api/docs`.
105
107
 
106
- - **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and points to its `db:up` script when it has one). The project needs `pg` installed, because the API connects with Kysely over the project's own `pg`.
108
+ - **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and, when nothing listens there, points to its `db:up` script when it has one). The project needs `pg` installed, because the API connects with Kysely over the project's own `pg`.
109
+ - **Port:** the app listens on `--port` at both `127.0.0.1` and `::1`, since `localhost` is either one depending on the runtime and the browser. When another process holds the port on either address the command stops before it starts and names that address; stop the other server or pass another `--port`.
107
110
  - **Cache:** Vite's dependency cache is `node_modules/.vite`; two dev servers sharing it can disturb each other's optimisation, so pass `--cache-dir` for a second one (the integration test does).
108
- - **Login:** real sign-in only, with the `authenticate` and `auth` exported by `protobase.config.ts` (see [Login with Better Auth](auth.md)). A project without an authenticator fails at startup with a message pointing there, one whose auth schema is behind with the tables and columns it lacks (see [`auth migration`](#auth-migration)), and one with a resource whose [events](events.md) or [history](history.md) lack their triggers, or whose [comments](comments.md) lack their table, or whose [rollup and formula fields](data-config.md#rollups-and-formulas) lack their columns or triggers, which it checks again on every reload (see [`migration`](#migration)), and one with an [AI field or action](ai.md#the-model) and no model key; there is no development login. Create the first admin with `protobase users create`.
111
+ - **Login:** real sign-in only, with the `authenticate` and `auth` exported by `protobase.config.ts` (see [Login with Better Auth](auth.md)). A project without an authenticator fails at startup with a message pointing there, one whose auth schema is behind with the tables and columns it lacks (see [`auth migration`](#auth-migration)), and one with a resource whose [events](events.md) or [history](history.md) lack their triggers, or whose [comments](comments.md) lack their table, or whose [rollup and formula fields](data-config.md#rollups-and-formulas) lack their columns or triggers, which it checks again on every reload (see [`migration`](#migration)), and one with an [AI field or action](ai.md#the-model) and no model key; there is no development login. The `login` line of the startup message says how to sign in: while the auth store has no users, it prints the exact command that creates the first admin, such as `bun run protobase users create you@example.com --generate-password` (the package manager that started `dev`, `npx` otherwise). Against a database that has users already, such as an app's hosted one, sign in as one of them or add one with a new email; its own password is set there.
109
112
  - **Mobile releases:** see [below](#mobile-releases).
110
113
  - **Jobs:** with [jobs](jobs.md) in the config it runs them in its process, once the jobs schema checks out (see [`migration`](#migration)); an edited job runs its new code from the next job on.
111
114
  - **Tunnels and other hosts:** Vite only answers `localhost` by default. `--allowed-hosts .trycloudflare.com,app.example.com` adds Host headers (a leading dot matches all subdomains). Hot reload needs no extra setting: the Vite client takes protocol, host and port from the page, so behind an HTTPS tunnel it connects over `wss` on 443 as long as the tunnel forwards WebSockets.
@@ -483,7 +486,7 @@ Run inside a project whose `protobase.config.ts` exports `auth` (Better Auth). T
483
486
 
484
487
  The password is typed at a hidden prompt with confirmation, read from stdin with `--password-stdin` (for scripts, e.g. `pass show erp | protobase users create me@example.com --password-stdin`), or generated with `--generate-password` and printed once; it must be 12 to 128 characters, the length the app requires of every new password. `--no-password` makes an account without one, which signs in by [emailed code](auth.md#emailed-sign-in-codes), passkey or a sign-in provider, as with an app whose [sign-in policy](auth.md#sign-in-policy) turns passwords off. A password is never accepted as an argument, since it would end up in shell history. `users list` prints email, role and creation date (and `disabled` for banned users), never credentials.
485
488
 
486
- `delete` asks you to type the email back (or pass `--yes`), and needs a terminal otherwise. `delete`, `set-role` and `disable` refuse to touch the last admin, so the project cannot lock itself out. `disable` bans the user and revokes their sessions; tokens already issued stop working on their next request, and `protobase token` refuses disabled users. With [MCP](auth.md#oauth-for-mcp-clients) on, it also disconnects their MCP clients. `enable` lifts the ban; the clients have to be allowed again. `protobase dev` prints "No users yet. Create the first admin with: protobase users create you@example.com" at startup while the user table is empty.
489
+ `delete` asks you to type the email back (or pass `--yes`), and needs a terminal otherwise. `delete`, `set-role` and `disable` refuse to touch the last admin, so the project cannot lock itself out. `disable` bans the user and revokes their sessions; tokens already issued stop working on their next request, and `protobase token` refuses disabled users. With [MCP](auth.md#oauth-for-mcp-clients) on, it also disconnects their MCP clients. `enable` lifts the ban; the clients have to be allowed again. `protobase dev` prints the command that creates the first admin at startup while the user table is empty (see [`dev`](#dev)).
487
490
 
488
491
  With [organizations](auth.md#organizations), `--role` is the user's global role (none by default) and `--organization` adds the new user to an organization, with `--org-role` (`owner`, `admin`, or `member`, the default) and `--app-roles` there.
489
492
 
@@ -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