@protobase/cli 0.46.10 → 0.46.12

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 (74) hide show
  1. package/dist/auth/register.js +1 -2
  2. package/dist/auth/write-migration.js +1 -1
  3. package/dist/build/app-icons.js +1 -1
  4. package/dist/build/config-bundle.js +1 -1
  5. package/dist/build/deploy-bundle.js +2 -2
  6. package/dist/build/entry-code.js +1 -1
  7. package/dist/build/plugin-build.js +3 -3
  8. package/dist/build/plugin-fields.js +1 -1
  9. package/dist/build/service-worker-code.js +1 -1
  10. package/dist/build/shell.js +2 -2
  11. package/dist/build/ui-check.js +2 -2
  12. package/dist/build/vite-bundle.js +1 -1
  13. package/dist/bundle/manifest.js +1 -1
  14. package/dist/cli/package.js +1 -1
  15. package/dist/db/connect.js +8 -5
  16. package/dist/dev/check-database.js +5 -3
  17. package/dist/dev/entry.d.ts +2 -0
  18. package/dist/dev/entry.js +6 -10
  19. package/dist/dev/login-line.js +21 -0
  20. package/dist/dev/loopback.js +42 -0
  21. package/dist/dev/project.js +2 -2
  22. package/dist/dev/run.js +19 -11
  23. package/dist/dev/startup-logger.js +24 -0
  24. package/dist/doctor/run.js +4 -1
  25. package/dist/encryption/register.js +1 -2
  26. package/dist/error-message.js +15 -0
  27. package/dist/files/register.js +1 -2
  28. package/dist/infer/proposal.js +1 -1
  29. package/dist/main.js +34 -26
  30. package/dist/migration/load-project.js +1 -1
  31. package/dist/migration/register.js +7 -4
  32. package/dist/migration/summary.js +15 -0
  33. package/dist/mobile/local-spec.js +1 -1
  34. package/dist/mobile/run.js +1 -1
  35. package/dist/mobile/web-part.js +2 -2
  36. package/dist/mobile/workspace.js +1 -1
  37. package/dist/notifications/register.js +1 -2
  38. package/dist/organizations/api.js +15 -0
  39. package/dist/organizations/register.js +5 -15
  40. package/dist/project/favicon-link.js +1 -1
  41. package/dist/project/load-bundle-project.js +2 -2
  42. package/dist/project/load-data-config.js +2 -2
  43. package/dist/project/placeholder-secret.js +9 -0
  44. package/dist/scaffold/existing-config.js +4 -1
  45. package/dist/scaffold/plan.js +17 -5
  46. package/dist/scaffold/project.js +2 -1
  47. package/dist/scaffold/prompt.js +12 -5
  48. package/dist/scaffold/protobase-tables.js +44 -0
  49. package/dist/scaffold/run.js +3 -1
  50. package/dist/scaffold/ui-fields.js +3 -0
  51. package/dist/scaffold/ui-file.js +42 -5
  52. package/dist/serve/app.js +1 -1
  53. package/dist/serve/bundle-version.js +1 -1
  54. package/dist/serve/create-admin.js +3 -3
  55. package/dist/serve/host-modules.js +5 -5
  56. package/dist/serve/lifecycle.js +3 -3
  57. package/dist/serve/mobile-release.js +1 -1
  58. package/dist/serve/serve-bundle-path.js +1 -1
  59. package/dist/serve/serve-bundle.js +3 -3
  60. package/dist/serve/serve-dir.js +2 -2
  61. package/dist/supabase/dump-phase.js +2 -2
  62. package/dist/supabase/load-phase.js +2 -2
  63. package/dist/supabase/register.js +1 -1
  64. package/dist/supabase/storage-phase.js +1 -1
  65. package/dist/users/commands.js +7 -1
  66. package/dist/users/register.js +17 -11
  67. package/dist/users/users-api.js +2 -1
  68. package/dist/worker/start-worker.js +2 -2
  69. package/package.json +6 -6
  70. package/skills/protobase/SKILL.md +1 -0
  71. package/skills/protobase/references/getting-started.md +5 -1
  72. package/skills/protobase/references/guides/existing-database.md +112 -0
  73. package/skills/protobase/references/reference/auth.md +6 -6
  74. package/skills/protobase/references/reference/cli.md +19 -11
@@ -4,19 +4,56 @@ import { methodCalls } from "./existing-config.js";
4
4
  import { Node, SyntaxKind } from "ts-morph";
5
5
  //#region src/scaffold/ui-file.ts
6
6
  const auditField = /^(created|updated)(At|On|_at|_on)$/;
7
+ const createdField = /^(created|inserted)(At|On|_at|_on)$/;
7
8
  const longText = /^(notes?|description|body|comment|comments)$/;
8
9
  const listSize = 5;
10
+ const secretWords = /* @__PURE__ */ new Set([
11
+ "password",
12
+ "passwd",
13
+ "hash",
14
+ "token",
15
+ "secret",
16
+ "salt",
17
+ "otp"
18
+ ]);
19
+ const secretPairs = ["private key", "api key"];
20
+ const isSecretLike = (name) => {
21
+ const words = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
22
+ const joined = words.join(" ");
23
+ return words.some((word) => secretWords.has(word)) || secretPairs.some((pair) => joined.includes(pair));
24
+ };
25
+ const relationsShown = 2;
26
+ /**
27
+ * The first useful fields: the key, unless it is a uuid nobody reads, then the records a record points at, such as an
28
+ * order line's order, then plain scalars, never a secret-like one. Without any of them, the key after all.
29
+ */
9
30
  const listColumns = (fields) => {
10
- const plain = fields.filter((f) => f.role === "plain" && f.type !== "json" && !auditField.test(f.name));
31
+ const keys = fields.filter((f) => f.role === "key" && f.type !== "uuid");
32
+ const plain = fields.filter((f) => f.role === "plain" && f.type !== "json" && !auditField.test(f.name) && !isSecretLike(f.name));
33
+ const relations = plain.filter((f) => f.type === "relation").slice(0, relationsShown);
11
34
  const scalars = plain.filter((f) => f.type !== "relation" && !longText.test(f.name));
12
- const relations = plain.filter((f) => f.type === "relation");
13
- const picked = [...scalars.slice(0, listSize), ...scalars.length < 3 ? relations : []].slice(0, listSize);
35
+ const picked = [
36
+ ...keys,
37
+ ...relations,
38
+ ...scalars
39
+ ].slice(0, listSize);
14
40
  return (picked.length > 0 ? picked : fields.filter((f) => f.role === "key")).map((f) => f.name);
15
41
  };
42
+ /**
43
+ * The newest records first, by the sortable date the records were created on, else by another sortable date. Without
44
+ * one the list keeps the API's order, by key.
45
+ */
46
+ const listSort = (fields) => {
47
+ const dates = fields.filter((f) => f.sortable && (f.type === "timestamp" || f.type === "date"));
48
+ return (dates.find((f) => createdField.test(f.name)) ?? dates[0])?.name;
49
+ };
16
50
  const viewName = (identifier) => `${identifier}View`;
17
51
  const sectionText = {
18
52
  names: (t) => `.names({ singular: '${humanizeSingular(t.tableName)}', plural: '${humanize(t.tableName)}' })`,
19
- list: (t) => `.list((r) => ({ columns: [${listColumns(t.fields).map((n) => `r.${n}`).join(", ")}] }))`
53
+ list: (t) => {
54
+ const sort = listSort(t.fields);
55
+ return `.list((r) => ({ columns: [${listColumns(t.fields).map((n) => `r.${n}`).join(", ")}]${sort ? `, sort: [[r.${sort}, 'desc']]` : ""} }))`;
56
+ }
20
57
  };
21
58
  const lines = (sections, target) => sections.map((s) => ` ${sectionText[s](target)}`);
22
59
  const renderUiFile = (target, sections) => [
@@ -37,4 +74,4 @@ const addUiSections = (text, target, sections) => {
37
74
  return source.getFullText();
38
75
  };
39
76
  //#endregion
40
- export { addUiSections, listColumns, renderUiFile, viewName };
77
+ export { addUiSections, isSecretLike, listColumns, listSort, renderUiFile, viewName };
package/dist/serve/app.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isApiPath } from "../bundle/manifest.js";
2
2
  import { serveStaticSite } from "./static-site.js";
3
- import { jobsDrainApp, mobileReleaseApp, webauthnPath } from "@protobase/server";
4
3
  import { Hono } from "hono";
4
+ import { jobsDrainApp, mobileReleaseApp, webauthnPath } from "@protobase/server";
5
5
  import { logger } from "hono/logger";
6
6
  //#region src/serve/app.ts
7
7
  const createServeApp = ({ admin, requestLog, site, jobs, drainToken, mobile }) => {
@@ -1,5 +1,5 @@
1
- import { manifestFile } from "../bundle/manifest.js";
2
1
  import { protobaseVersion } from "../version/version.js";
2
+ import { manifestFile } from "../bundle/manifest.js";
3
3
  import { bundleVersionProblem } from "../version/compatibility.js";
4
4
  import { existsSync } from "node:fs";
5
5
  import path from "node:path";
@@ -1,9 +1,9 @@
1
- import { checkBundleVersion } from "./bundle-version.js";
2
- import { loadBundle } from "./load-bundle.js";
3
- import { bundleConfigFile } from "../worker/start-worker.js";
4
1
  import { readHidden } from "../users/password.js";
5
2
  import { createUserCommand } from "../users/commands.js";
6
3
  import { usersApi } from "../users/users-api.js";
4
+ import { checkBundleVersion } from "./bundle-version.js";
5
+ import { loadBundle } from "./load-bundle.js";
6
+ import { bundleConfigFile } from "../worker/start-worker.js";
7
7
  import { checkAuthSchema } from "@protobase/server";
8
8
  //#region src/serve/create-admin.ts
9
9
  const createAdminInBundle = async (bundle, email, options, out) => {
@@ -1,12 +1,9 @@
1
- import * as server from "@protobase/server";
2
1
  import * as postgres$1 from "postgres";
3
2
  import * as nodeServer from "@hono/node-server";
4
- import * as query from "@protobase/query";
3
+ import * as hono from "hono";
4
+ import * as server from "@protobase/server";
5
5
  import * as kysely from "kysely";
6
6
  import * as pg$1 from "pg";
7
- import * as schema from "@protobase/schema";
8
- import * as layout from "@protobase/layout";
9
- import * as hono from "hono";
10
7
  import * as reactEmailRender from "@react-email/render";
11
8
  import * as apiReference from "@scalar/hono-api-reference";
12
9
  import * as aipParsers from "aip-parsers";
@@ -19,6 +16,9 @@ import * as kyselyPostgres from "kysely/helpers/postgres";
19
16
  import * as react from "react";
20
17
  import * as reactJsxRuntime from "react/jsx-runtime";
21
18
  import * as zod from "zod";
19
+ import * as layout from "@protobase/layout";
20
+ import * as query from "@protobase/query";
21
+ import * as schema from "@protobase/schema";
22
22
  //#region src/serve/host-modules.ts
23
23
  const hostModules = {
24
24
  "@protobase/schema": schema,
@@ -1,14 +1,14 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
- import { apiWebSocketServer } from "../project/api-websocket-server.js";
3
- import { withClientAddress } from "./client-address.js";
4
2
  import { projectAdmin } from "../project/project-admin.js";
5
3
  import { createPgDb } from "../project/pg-db.js";
4
+ import { withClientAddress } from "./client-address.js";
5
+ import { apiWebSocketServer } from "../project/api-websocket-server.js";
6
6
  import { createServeApp } from "./app.js";
7
7
  import { startCleanupTimer } from "./cleanup-timer.js";
8
8
  import { closeSockets } from "./close-sockets.js";
9
9
  import { servedRelease } from "./mobile-release.js";
10
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
11
10
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
11
+ import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
12
12
  import pg from "pg";
13
13
  //#region src/serve/lifecycle.ts
14
14
  const listen = (server, port) => new Promise((resolve, reject) => {
@@ -1,8 +1,8 @@
1
1
  import { nativeFingerprint } from "../mobile/fingerprint.js";
2
2
  import { withApiOrigin } from "../mobile/api-origin-page.js";
3
3
  import { siteFiles } from "./site-files.js";
4
- import { composeRelease } from "@protobase/server";
5
4
  import { readFile } from "node:fs/promises";
5
+ import { composeRelease } from "@protobase/server";
6
6
  //#region src/serve/mobile-release.ts
7
7
  const loopback = [
8
8
  "localhost",
@@ -1,6 +1,6 @@
1
1
  import { readManifest } from "../bundle/manifest.js";
2
- import { serveBundle } from "./serve-bundle.js";
3
2
  import { bundleSite } from "./bundle-site.js";
3
+ import { serveBundle } from "./serve-bundle.js";
4
4
  import { statSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  //#region src/serve/serve-bundle-path.ts
@@ -1,11 +1,11 @@
1
- import { readManifest } from "../bundle/manifest.js";
2
1
  import { projectErrorReporter } from "../project/error-reporter.js";
3
- import { bundleUi } from "./bundle-ui.js";
2
+ import { readManifest } from "../bundle/manifest.js";
4
3
  import { checkBundleVersion } from "./bundle-version.js";
4
+ import { loadBundle } from "./load-bundle.js";
5
+ import { bundleUi } from "./bundle-ui.js";
5
6
  import { reportCrashes } from "./crash-reports.js";
6
7
  import { readServeEnv } from "./env.js";
7
8
  import { startServe } from "./lifecycle.js";
8
- import { loadBundle } from "./load-bundle.js";
9
9
  import { closeOnSignals } from "./signals.js";
10
10
  import path from "node:path";
11
11
  //#region src/serve/serve-bundle.ts
@@ -1,8 +1,8 @@
1
1
  import { readManifest } from "../bundle/manifest.js";
2
+ import { bundleSite } from "./bundle-site.js";
3
+ import { serveBundle } from "./serve-bundle.js";
2
4
  import { installedShellDir } from "../build/shell.js";
3
5
  import { pinnedNative } from "../mobile/pinned-packages.js";
4
- import { serveBundle } from "./serve-bundle.js";
5
- import { bundleSite } from "./bundle-site.js";
6
6
  import { servedShell, shellVariable } from "./served-shell.js";
7
7
  import path from "node:path";
8
8
  //#region src/serve/serve-dir.ts
@@ -17,9 +17,9 @@ import { ensureApiRoles, existingSchemas, existingTables } from "./target-checks
17
17
  import { creatableExtensions } from "./target-extensions.js";
18
18
  import { usersColumnsMigration } from "./users-migrations.js";
19
19
  import path from "node:path";
20
- import { isSchedule } from "@protobase/server";
21
- import { mkdir, readFile, rm } from "node:fs/promises";
22
20
  import postgres from "postgres";
21
+ import { mkdir, readFile, rm } from "node:fs/promises";
22
+ import { isSchedule } from "@protobase/server";
23
23
  //#region src/supabase/dump-phase.ts
24
24
  /** Fails unless the database at `sql` is Supabase's: its auth and storage schemas, and its own admin role. */
25
25
  const checkSupabase = async (sql) => {
@@ -1,6 +1,5 @@
1
- import { loadProjectAuth } from "../users/load-auth.js";
2
- import { writeAuthMigration } from "../auth/write-migration.js";
3
1
  import { connect } from "../db/connect.js";
2
+ import { writeAuthMigration } from "../auth/write-migration.js";
4
3
  import { runDoctor } from "../doctor/run.js";
5
4
  import { runScaffold } from "../scaffold/run.js";
6
5
  import { convertedCronJobs } from "./cron-plan.js";
@@ -11,6 +10,7 @@ import { loadScript, qualified } from "./load-script.js";
11
10
  import { existingTables, filledTables, otherTables } from "./target-checks.js";
12
11
  import { providerCounts } from "./identity-providers.js";
13
12
  import { accountsMigration } from "./users-migrations.js";
13
+ import { loadProjectAuth } from "../users/load-auth.js";
14
14
  import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
15
15
  import { importReport } from "./report.js";
16
16
  import { existsSync } from "node:fs";
@@ -1,5 +1,4 @@
1
1
  import { loadNearestEnvFile } from "../dev/env.js";
2
- import { runSupabaseImport } from "./run.js";
3
2
  import path from "node:path";
4
3
  //#region src/supabase/register.ts
5
4
  const out = (text) => process.stdout.write(text);
@@ -19,6 +18,7 @@ const registerImport = (program) => {
19
18
  if (source && opts.sourceEnv) throw new Error("Pass either a connection string or --source-env, not both");
20
19
  const projectDir = process.cwd();
21
20
  loadNearestEnvFile(projectDir);
21
+ const { runSupabaseImport } = await import("./run.js");
22
22
  await runSupabaseImport({
23
23
  sourceUrl: source ?? (opts.sourceEnv ? variable(opts.sourceEnv) : void 0),
24
24
  targetUrl: variable(opts.env),
@@ -9,8 +9,8 @@ import { storageObjects } from "./storage-objects.js";
9
9
  import { bucketLines, megabytes, objectCount, overQuota, totalBytes } from "./storage-sizes.js";
10
10
  import { storageReport } from "./storage-report.js";
11
11
  import path from "node:path";
12
- import { objectKey, storageProvider, storeUsage } from "@protobase/server";
13
12
  import { writeFile } from "node:fs/promises";
13
+ import { objectKey, storageProvider, storeUsage } from "@protobase/server";
14
14
  //#region src/supabase/storage-phase.ts
15
15
  /** Objects copied at once: enough to keep a connection busy, few enough for any host. */
16
16
  const parallel = 4;
@@ -1,6 +1,11 @@
1
1
  import { resolvePassword } from "./password.js";
2
2
  //#region src/users/commands.ts
3
3
  const githubId = /^[1-9][0-9]*$/;
4
+ const shownAs = (role, labels) => {
5
+ const names = role.split(",");
6
+ const shown = names.map((name) => labels[name] ?? name);
7
+ return shown.some((label, index) => label.toLowerCase() !== names[index].toLowerCase()) ? `, shown in the app as ${shown.join(", ")}` : "";
8
+ };
4
9
  const createUserCommand = async (api, options, deps, out) => {
5
10
  if (!options.email.includes("@")) throw new Error(`"${options.email}" is not an email address`);
6
11
  if (options.githubId !== void 0 && !githubId.test(options.githubId)) throw new Error(`"${options.githubId}" is not a GitHub user id, a number such as 583231`);
@@ -16,7 +21,8 @@ const createUserCommand = async (api, options, deps, out) => {
16
21
  accountId: options.githubId
17
22
  }] }
18
23
  });
19
- out(`Created ${user.role} ${user.email}${options.githubId ? `, linked to GitHub user ${options.githubId}` : ""}\n`);
24
+ const { labels } = await api.roles();
25
+ out(`Created ${user.role} ${user.email}${shownAs(user.role, labels)}${options.githubId ? `, linked to GitHub user ${options.githubId}` : ""}\n`);
20
26
  if (generated) out(`Password (shown once): ${password}\n`);
21
27
  };
22
28
  const listUsersCommand = async (api, out) => {
@@ -1,18 +1,15 @@
1
- import { loadProjectAuth } from "./load-auth.js";
2
1
  import { addMemberCommand } from "../organizations/commands.js";
3
- import { organizationsApi } from "../organizations/register.js";
4
- import { readHidden, rejectPasswordArgument } from "./password.js";
5
- import { createUserCommand, listRolesCommand, listUsersCommand } from "./commands.js";
6
2
  import { deleteUserCommand, setRoleCommand } from "./manage.js";
7
- import { usersApi } from "./users-api.js";
8
- import { setDisabledInProject } from "./set-disabled.js";
9
3
  import { parseTtl } from "./ttl.js";
10
4
  import { Option } from "commander";
11
- import { issueToken } from "@protobase/server";
12
5
  import { createInterface } from "node:readline/promises";
13
6
  //#region src/users/register.ts
14
7
  const out = (text) => process.stdout.write(text);
15
- const projectApi = async () => usersApi(await loadProjectAuth(process.cwd()));
8
+ const loadAuth = async () => (await import("./load-auth.js")).loadProjectAuth(process.cwd());
9
+ const projectApi = async () => {
10
+ const [{ usersApi }, auth] = await Promise.all([import("./users-api.js"), loadAuth()]);
11
+ return usersApi(auth);
12
+ };
16
13
  const ask = async (question) => {
17
14
  if (!process.stdin.isTTY) throw new Error("Confirmation needs a terminal; pass --yes to skip it");
18
15
  const rl = createInterface({
@@ -27,8 +24,14 @@ const finish = (code) => process.exit(code);
27
24
  const registerUsers = (program) => {
28
25
  const users = program.command("users").description("Manage the admin users of the project in the current directory");
29
26
  users.command("create").description("Create a user; the first user is always an admin").argument("<email>").option("--name <name>", "display name").option("--role <role>", "role for users after the first (default: the project's default role; see `users roles`)").option("--password-stdin", "read the password from stdin", false).option("--generate-password", "generate a strong password and print it once", false).option("--no-password", "no password: the user signs in by emailed code, passkey or a sign-in provider").option("--github-id <id>", "link the user to this GitHub user id, so signing in with GitHub finds them whatever their address").option("--organization <organization>", "with organizations: add the user to this one (its slug or id)").option("--org-role <role>", "with --organization: owner, admin or member (default member)").option("--app-roles <roles>", "with --organization: app roles there, comma separated").addOption(new Option("--password <value>").hideHelp()).action(async (email, opts) => {
27
+ const { readHidden, rejectPasswordArgument } = await import("./password.js");
30
28
  rejectPasswordArgument(opts.password);
31
- const auth = await loadProjectAuth(process.cwd());
29
+ const [{ createUserCommand }, { usersApi }, { organizationsApi }, auth] = await Promise.all([
30
+ import("./commands.js"),
31
+ import("./users-api.js"),
32
+ import("../organizations/api.js"),
33
+ loadAuth()
34
+ ]);
32
35
  await createUserCommand(usersApi(auth), {
33
36
  email,
34
37
  name: opts.name,
@@ -64,17 +67,20 @@ const registerUsers = (program) => {
64
67
  finish(0);
65
68
  });
66
69
  for (const disabled of [true, false]) users.command(disabled ? "disable" : "enable").description(disabled ? "Ban a user and revoke their sessions" : "Lift a ban").argument("<email>").action(async (email) => {
67
- await setDisabledInProject(await loadProjectAuth(process.cwd()), {
70
+ const { setDisabledInProject } = await import("./set-disabled.js");
71
+ await setDisabledInProject(await loadAuth(), {
68
72
  email,
69
73
  disabled
70
74
  }, out);
71
75
  finish(0);
72
76
  });
73
77
  users.command("roles").description("List the roles of the project (the first is admin)").action(async () => {
78
+ const { listRolesCommand } = await import("./commands.js");
74
79
  await listRolesCommand(await projectApi(), out);
75
80
  finish(0);
76
81
  });
77
82
  users.command("list").description("List users: email, role, creation date").action(async () => {
83
+ const { listUsersCommand } = await import("./commands.js");
78
84
  await listUsersCommand(await projectApi(), out);
79
85
  finish(0);
80
86
  });
@@ -82,7 +88,7 @@ const registerUsers = (program) => {
82
88
  const registerToken = (program) => {
83
89
  program.command("token").description("Print a bearer token (JWT) for an existing user").argument("<email>").option("--ttl <duration>", "lifetime: 30s, 15m, up to 24h", "15m").action(async (email, opts) => {
84
90
  const ttlSeconds = parseTtl(opts.ttl);
85
- const auth = await loadProjectAuth(process.cwd());
91
+ const [{ issueToken }, auth] = await Promise.all([import("@protobase/server"), loadAuth()]);
86
92
  const { token } = await issueToken(auth, {
87
93
  email,
88
94
  ttlSeconds
@@ -4,7 +4,8 @@ const usersApi = (auth) => ({
4
4
  hasUsers: () => hasUsers(auth),
5
5
  roles: async () => ({
6
6
  roles: roleChoices(auth),
7
- defaultRole: auth.defaultRole
7
+ defaultRole: auth.defaultRole,
8
+ labels: auth.roleDefinitions.labels
8
9
  }),
9
10
  createUser: (input) => createUser(auth, input),
10
11
  listUsers: () => listUsers(auth),
@@ -1,7 +1,7 @@
1
- import { readManifest } from "../bundle/manifest.js";
2
- import { checkBundleVersion } from "../serve/bundle-version.js";
3
1
  import { projectAdmin } from "../project/project-admin.js";
4
2
  import { createPgDb } from "../project/pg-db.js";
3
+ import { readManifest } from "../bundle/manifest.js";
4
+ import { checkBundleVersion } from "../serve/bundle-version.js";
5
5
  import { loadBundle } from "../serve/load-bundle.js";
6
6
  import { statSync } from "node:fs";
7
7
  import path from "node:path";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.46.10",
3
+ "version": "0.46.12",
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.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",
39
+ "@protobase/layout": "0.46.12",
40
+ "@protobase/query": "0.46.12",
41
+ "@protobase/schema": "0.46.12",
42
+ "@protobase/server": "0.46.12",
43
+ "@protobase/ui": "0.46.12",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -43,6 +43,7 @@ Guides:
43
43
  - When setting up or running a project for the first time → read [Getting started](references/getting-started.md)
44
44
  - When you need to know whether Protobase has a feature, what it is called or how stable it is → read [Features](references/features.md), which links a page per area
45
45
  - When shipping a project as a bundle and running it with the serve runtime → read [Deploy](references/guides/deploy.md)
46
+ - When putting an admin on a Postgres database that already exists, from install to the first sign-in → read [Admin over an existing database](references/guides/existing-database.md)
46
47
  - When turning a table into an admin with fields, views and filters → read [From a table to an admin](references/guides/table-to-admin.md)
47
48
  - When building a page from layouts and blocks → read [Your first composed page](references/guides/first-composed-page.md)
48
49
  - When giving customers a page for their plan, cards and invoices → read [A billing page](references/guides/billing-page.md)
@@ -17,6 +17,10 @@ npm create protobase my-app
17
17
  npm create protobase my-app -- --preset real-estate
18
18
  ```
19
19
 
20
+ ## Admin over an existing database
21
+
22
+ For a Postgres database you already have, [Admin over an existing database](guides/existing-database.md) goes from an empty folder to signing in: install the packages, scaffold the config from the tables, check it with `doctor`, add sign-in and its tables, create the first admin and run `protobase dev`.
23
+
20
24
  ## Docs as Markdown
21
25
 
22
26
  Every page of these docs is also Markdown at its address plus `.md`: `https://docs.protobase.net/reference/cli/` is also `https://docs.protobase.net/reference/cli.md`. The code a page shows from example files is written out in it, and its live demos are left out, so a coding agent or a chat assistant reads the page whole. In a project, [`protobase skill install`](reference/cli.md#skill) gives coding agents the docs of the installed version.
@@ -41,7 +45,7 @@ bun run --cwd examples/erp protobase users create you@example.com --generate-pas
41
45
  bun run --cwd examples/erp dev # http://localhost:5173
42
46
  ```
43
47
 
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)).
48
+ `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
49
 
46
50
  ## Run the real estate example
47
51
 
@@ -0,0 +1,112 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/guides/existing-database.md: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Admin over an existing database
4
+
5
+ Put an admin on a Postgres database you already have, in six steps, from install to signing in, with every file sign-in needs.
6
+
7
+ You have a Postgres database and want an admin over its tables, without moving the data. This guide goes from an empty folder to signing in to that admin. It takes about fifteen minutes and needs Node 22.12 or later.
8
+
9
+ Protobase never changes your tables. Sign-in is the one thing it adds to the database: an `auth` schema with its own tables for users, sessions and signing keys. `protobase migration` writes them as a SQL file you apply yourself, like any other migration, and the app never changes the schema while it runs.
10
+
11
+ ## 1. Install
12
+
13
+ In a new folder, next to the database's own code or anywhere else:
14
+
15
+ ```sh
16
+ npm install @protobase/cli @protobase/schema @protobase/layout @protobase/server @protobase/ui pg kysely
17
+ ```
18
+
19
+ Then a `.env` beside it, which every `protobase` command reads:
20
+
21
+ ```sh
22
+ DATABASE_URL=postgres://user:password@localhost:5432/shop
23
+ # Signs session cookies: generate your own with openssl rand -base64 32
24
+ BETTER_AUTH_SECRET=
25
+ BETTER_AUTH_URL=http://localhost:5173
26
+ ```
27
+
28
+ Keep `.env` out of version control.
29
+
30
+ ## 2. Scaffold the config
31
+
32
+ ```sh
33
+ npx protobase scaffold --ui
34
+ ```
35
+
36
+ It reads the tables, read-only, and writes `config/<resource>/data.ts` and `ui.ts` for each one, and `config/index.ts`. In a terminal it asks about each column: press Enter to accept one, `l` to accept it and every one after it. `--yes` accepts them all without asking, and `--dry-run` shows the files without writing them. A table without a primary key, or a unique index on columns that are never null, is skipped with a warning, and so is a view. What it infers is in the [CLI reference](../reference/cli.md#scaffold).
37
+
38
+ ## 3. Check it
39
+
40
+ ```sh
41
+ npx protobase doctor
42
+ ```
43
+
44
+ It checks the config against the database: each table and column exists, each type fits, and an index serves every filter and sort the admin makes. Each error names the index to add, such as `create index on "public"."orders" ("total");`. Add those with your own migrations, or drop the `.filterable()` or `.sortable()` that needs it.
45
+
46
+ ## 4. Add sign-in
47
+
48
+ Two files. `protobase.config.ts` is the project:
49
+
50
+ ```ts
51
+ import * as config from './config'
52
+ import { auth, authenticate } from './auth/auth'
53
+
54
+ export default { config, auth, authenticate }
55
+ ```
56
+
57
+ `auth/auth.ts` sets up sign-in with [Better Auth](../reference/auth.md), with its tables in the `auth` schema:
58
+
59
+ ```ts
60
+ import { PostgresDialect } from 'kysely'
61
+ import pg from 'pg'
62
+ import { appPool, betterAuthAuthenticator, createAuth } from '@protobase/server'
63
+
64
+ const secret = process.env.BETTER_AUTH_SECRET
65
+ if (!secret) throw new Error('BETTER_AUTH_SECRET is not set: put the output of `openssl rand -base64 32` in .env')
66
+
67
+ // The app's one pool on DATABASE_URL, which `protobase dev` and `serve` share.
68
+ const pool = appPool(pg, process.env.DATABASE_URL!)
69
+
70
+ export const auth = createAuth({
71
+ // Users, sessions and signing keys live in a schema of their own, next to your tables.
72
+ database: { dialect: new PostgresDialect({ pool }), type: 'postgres', schemaName: 'auth', transaction: true },
73
+ baseURL: process.env.BETTER_AUTH_URL ?? 'http://localhost:5173',
74
+ secret,
75
+ })
76
+
77
+ export const authenticate = betterAuthAuthenticator({ auth, tenant: 1 })
78
+ ```
79
+
80
+ The [auth reference](../reference/auth.md) has the rest: emailed codes, passkeys, two-factor, roles, and a users table the database already has.
81
+
82
+ ## 5. Write and apply the auth tables
83
+
84
+ ```sh
85
+ npx protobase migration
86
+ ```
87
+
88
+ It compares the database with what sign-in needs and writes `db/migrations/001_auth.sql`: the `auth` schema and its tables. It only adds; it never drops or changes your tables. Read it, then apply it with your migration tool, or with `psql`:
89
+
90
+ ```sh
91
+ psql "$DATABASE_URL" -1 -f db/migrations/001_auth.sql
92
+ ```
93
+
94
+ After a Protobase upgrade, run `npx protobase migration` again: it writes only what the new version adds, as the next file.
95
+
96
+ ## 6. Create the first admin and sign in
97
+
98
+ ```sh
99
+ npx protobase users create you@example.com --generate-password
100
+ npx protobase dev
101
+ ```
102
+
103
+ The first user is always an admin. The password is printed once. `protobase dev` serves the admin and its API at `http://localhost:5173` (`--port` picks another port); sign in there with that email and password.
104
+
105
+ ## Running scaffold again
106
+
107
+ When the database gets a new table or column, run `npx protobase scaffold --ui` again. It adds only what is new, and leaves your edits as they are. It leaves out the `auth` schema of step 5 on its own, and says so, as the sign-in tables are no admin pages. It also reports drift: a declared field whose column has gone, or whose type no longer fits.
108
+
109
+ ## Next
110
+
111
+ - [From a table to an admin](table-to-admin.md): names, columns, filters and record pages for the resources you scaffolded.
112
+ - [Deploy](deploy.md): build the app and run it on your own server.
@@ -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