create-user-hub 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,9 +8,9 @@ Start a new app with User Hub sign-in already wired: people scan their badge and
8
8
  bun create user-hub@latest my-app
9
9
  ```
10
10
 
11
- It asks for your hub's URL and admin password (from your hub's admin; the password shows as stars), checks the hub answers and saves both to the app's `.env.local`.
11
+ It asks for your hub's URL (from your hub's admin) and checks the hub answers. Then it signs the new app in to the hub with your account: paste an API key from the hub's account page (it shows as stars), or press Enter and approve the sign-in in your browser. The app's `.env.local` gets `HUB_URL` and `HUB_API_KEY`.
12
12
 
13
- Scripts and coding agents are never asked when `HUB_URL` and `HUB_ADMIN_PASSWORD` are already in the environment (for example through your secret manager). The password is never a command-line flag, so it stays out of shell history.
13
+ Scripts and coding agents are never asked: pass `--hub-url` (or set `HUB_URL`), and set `HUB_API_KEY` in the environment if you have one (for example through your secret manager) to have it checked and saved. Without a key, sign in later from the app's folder (where `@user-hub/auth` is installed: `bunx hub-user` runs the installed CLI) with `bunx hub-user login` (a coding agent runs `bunx hub-user login --browser` and shows you the link to approve). Never run a bare `bunx hub-user` anywhere else: there it fetches an npm package called `hub-user`, which is not ours. The key is never a command-line flag, so it stays out of shell history.
14
14
 
15
15
  You get a TanStack Start + Convex app with Tailwind, shadcn (dark theme) and Vite+ (Oxfmt, Oxlint), plus:
16
16
 
package/index.js CHANGED
@@ -1,14 +1,24 @@
1
1
  #!/usr/bin/env bun
2
2
  // bun create user-hub@latest [my-app] [--hub-url <url>]
3
- // Copies the starter, names it, saves the hub's URL and admin password to
4
- // .env.local, installs it and adds the agent skill.
3
+ // Copies the starter, names it, saves the hub's URL to .env.local, installs
4
+ // it, adds the agent skill and signs the new app in to the hub.
5
5
  //
6
- // People are asked for anything missing (the password is typed as stars).
7
- // Scripts and agents set HUB_URL and HUB_ADMIN_PASSWORD in the environment
8
- // and are never asked. The password is never a command-line flag: that would
9
- // leave it in shell history and process lists.
6
+ // Signing in is `hub-user login` from @user-hub/auth, run inside the new app:
7
+ // it saves HUB_URL and HUB_API_KEY to .env.local. People in a terminal paste
8
+ // an API key or approve the sign-in in their browser. Scripts and agents set
9
+ // HUB_URL (or --hub-url) and, if they have one, HUB_API_KEY in the
10
+ // environment and are never asked. The key is never a command-line flag: that
11
+ // would leave it in shell history and process lists.
10
12
  import { existsSync, readdirSync } from "node:fs";
11
- import { cp, mkdir, readFile, rename, symlink, writeFile } from "node:fs/promises";
13
+ import {
14
+ cp,
15
+ mkdir,
16
+ readFile,
17
+ rename,
18
+ rm,
19
+ symlink,
20
+ writeFile,
21
+ } from "node:fs/promises";
12
22
  import { basename, join, resolve } from "node:path";
13
23
  import { parseArgs } from "node:util";
14
24
 
@@ -29,43 +39,6 @@ function slug(text) {
29
39
  .replace(/^-+|-+$/g, "");
30
40
  }
31
41
 
32
- // Reads a line without echoing it, printing a star per character.
33
- function secret(question) {
34
- process.stdout.write(question);
35
- process.stdin.setRawMode(true);
36
- process.stdin.resume();
37
- process.stdin.setEncoding("utf8");
38
- return new Promise((done) => {
39
- let value = "";
40
- const finish = () => {
41
- process.stdin.off("data", onData);
42
- process.stdin.setRawMode(false);
43
- process.stdin.pause();
44
- process.stdout.write("\n");
45
- done(value);
46
- };
47
- const onData = (chunk) => {
48
- for (const char of chunk) {
49
- if (char === "\r" || char === "\n") return finish();
50
- if (char === "\u0003") {
51
- process.stdout.write("\n");
52
- process.exit(130);
53
- }
54
- if (char === "\u007f" || char === "\b") {
55
- if (value) {
56
- value = value.slice(0, -1);
57
- process.stdout.write("\b \b");
58
- }
59
- } else if (char >= " ") {
60
- value += char;
61
- process.stdout.write("*");
62
- }
63
- }
64
- };
65
- process.stdin.on("data", onData);
66
- });
67
- }
68
-
69
42
  // The hub answers its public key at this path; anything else is a typo or a
70
43
  // hub that is down.
71
44
  async function hubAnswers(url) {
@@ -98,16 +71,22 @@ const dest = resolve(target);
98
71
  if (existsSync(dest) && readdirSync(dest).length > 0) {
99
72
  fail(`${dest} already exists and is not empty.`);
100
73
  }
74
+ // Whether this run makes the folder, or fills one that is there and empty.
75
+ const destCreated = !existsSync(dest);
101
76
 
102
77
  let hubUrl = flags["hub-url"] ?? process.env.HUB_URL;
103
- let adminPassword = process.env.HUB_ADMIN_PASSWORD;
104
- if (interactive && (!hubUrl || !adminPassword)) {
105
- console.log("\nYour hub's URL and admin password (from your hub's admin).");
106
- console.log("Press Enter to skip and add them to .env.local later.\n");
107
- hubUrl ||= prompt("Hub URL:") ?? "";
108
- if (hubUrl) adminPassword ||= await secret("Admin password: ");
78
+ const apiKey = process.env.HUB_API_KEY?.trim();
79
+ if (interactive && !hubUrl) {
80
+ console.log("\nYour hub's URL (from your hub's admin).");
81
+ console.log("Press Enter to skip and sign in to the hub later.\n");
82
+ hubUrl = prompt("Hub URL:") ?? "";
109
83
  }
110
84
  hubUrl = hubUrl?.trim().replace(/\/+$/, "");
85
+ if (apiKey && !hubUrl) {
86
+ fail(
87
+ "HUB_API_KEY is set, but not the hub it belongs to: pass --hub-url or set HUB_URL.",
88
+ );
89
+ }
111
90
  if (hubUrl && !/^https?:\/\//.test(hubUrl)) {
112
91
  fail(`The hub URL must start with https:// (got "${hubUrl}").`);
113
92
  }
@@ -122,6 +101,16 @@ await cp(TEMPLATE, dest, { recursive: true });
122
101
  await rename(join(dest, "gitignore"), join(dest, ".gitignore"));
123
102
  await rename(join(dest, "dockerignore"), join(dest, ".dockerignore"));
124
103
 
104
+ // Testing unreleased @user-hub/auth: CREATE_USER_HUB_AUTH_SPEC (for example
105
+ // file:/path/to/user-hub-auth) replaces its version range before installing.
106
+ const authSpec = process.env.CREATE_USER_HUB_AUTH_SPEC;
107
+ if (authSpec) {
108
+ const path = join(dest, "package.json");
109
+ const pkg = JSON.parse(await readFile(path, "utf8"));
110
+ pkg.dependencies["@user-hub/auth"] = authSpec;
111
+ await writeFile(path, `${JSON.stringify(pkg, null, 2)}\n`);
112
+ }
113
+
125
114
  for (const file of [
126
115
  "package.json",
127
116
  "README.md",
@@ -139,23 +128,42 @@ for (const file of [
139
128
  }
140
129
  await symlink("CLAUDE.md", join(dest, "AGENTS.md"));
141
130
 
142
- // .env.local is gitignored; the password never goes anywhere else.
143
- const env = [
144
- hubUrl && `HUB_URL=${hubUrl}`,
145
- adminPassword && `HUB_ADMIN_PASSWORD=${adminPassword}`,
146
- ].filter(Boolean);
147
- if (env.length > 0) {
148
- await writeFile(join(dest, ".env.local"), `${env.join("\n")}\n`, {
131
+ // .env.local is gitignored. hub-user login adds HUB_API_KEY next to the URL.
132
+ if (hubUrl) {
133
+ await writeFile(join(dest, ".env.local"), `HUB_URL=${hubUrl}\n`, {
149
134
  mode: 0o600,
150
135
  });
151
136
  }
152
137
 
153
- const run = (command) =>
154
- Bun.spawn(command, { cwd: dest, stdio: ["inherit", "inherit", "inherit"] })
138
+ const run = (command, stdin = "inherit") =>
139
+ Bun.spawn(command, { cwd: dest, stdio: [stdin, "inherit", "inherit"] })
155
140
  .exited;
156
141
 
142
+ // A half-made app would block running the same command again ("already
143
+ // exists"), so a failed or interrupted install takes back what this run
144
+ // wrote: the folder when this run made it, else only what it put inside.
157
145
  console.log("\nInstalling dependencies");
158
- if ((await run(["bun", "install"])) !== 0) fail("bun install failed.");
146
+ let interrupted = false;
147
+ const onInterrupt = () => {
148
+ interrupted = true;
149
+ };
150
+ // Ctrl-C reaches bun install too; wait for it to stop before cleaning up.
151
+ process.on("SIGINT", onInterrupt);
152
+ const installed = (await run(["bun", "install"])) === 0;
153
+ process.off("SIGINT", onInterrupt);
154
+ if (!installed || interrupted) {
155
+ if (destCreated) {
156
+ await rm(dest, { recursive: true, force: true });
157
+ } else {
158
+ for (const entry of readdirSync(dest)) {
159
+ await rm(join(dest, entry), { recursive: true, force: true });
160
+ }
161
+ }
162
+ console.error(
163
+ `\n✗ ${interrupted ? "Stopped while installing" : "bun install failed"}, so ${destCreated ? `${dest} was removed` : `what was copied into ${dest} was removed`}. Run the same command again.`,
164
+ );
165
+ process.exit(interrupted ? 130 : 1);
166
+ }
159
167
 
160
168
  // The skill ships inside @user-hub/auth: one copy for every agent, linked
161
169
  // for Claude Code.
@@ -169,22 +177,45 @@ await symlink("../.agents/skills", join(dest, ".claude/skills"));
169
177
 
170
178
  await run(["git", "init", "-q"]);
171
179
 
172
- const ready = Boolean(hubUrl && adminPassword);
180
+ // Sign the new app in: a key from the environment is checked with the hub and
181
+ // saved; in a terminal, hub-user asks for a key or a browser sign-in.
182
+ let signedIn = false;
183
+ if (hubUrl && (apiKey || interactive)) {
184
+ // --no-install: the CLI installed above, never an npm package of that name.
185
+ const login = [
186
+ "bun",
187
+ "x",
188
+ "--no-install",
189
+ "hub-user",
190
+ "login",
191
+ "--hub",
192
+ hubUrl,
193
+ ];
194
+ console.log("\nSigning in to the hub");
195
+ // Ctrl-C belongs to hub-user; the app exists either way, so still say what
196
+ // is next.
197
+ const ignore = () => {};
198
+ process.on("SIGINT", ignore);
199
+ signedIn = apiKey
200
+ ? (await run([...login, "--api-key-stdin"], new Blob([apiKey]))) === 0
201
+ : (await run(login)) === 0;
202
+ process.off("SIGINT", ignore);
203
+ }
204
+
173
205
  console.log(`
174
- ✓ Created ${name}
206
+ ✓ Created ${name}${hubUrl && !signedIn ? ", not signed in to the hub yet" : ""}
175
207
 
176
208
  Next:
177
209
 
178
210
  cd ${target}
179
211
  ${
180
- ready
212
+ signedIn
181
213
  ? ""
182
214
  : `
183
- 0. Put your hub's URL and admin password in .env.local
184
- (from your hub's admin):
185
-
186
- HUB_URL=https://hub.example.com
187
- HUB_ADMIN_PASSWORD=…
215
+ 0. bunx hub-user login signs this app in to the hub${hubUrl ? "" : "\n (its URL comes from your hub's admin)"}
216
+ Paste an API key from the hub's account page, or press
217
+ Enter to approve the sign-in in your browser. A coding
218
+ agent runs it with --browser and shows you the link.
188
219
  `
189
220
  }
190
221
  1. bun run setup connects Convex and the hub, once
@@ -193,3 +224,6 @@ ${
193
224
  Using a coding agent? It reads CLAUDE.md (AGENTS.md) and the
194
225
  user-hub-auth skill in .claude/skills.
195
226
  `);
227
+
228
+ // A key passed in by a script that the hub refused is an error for it to see.
229
+ if (apiKey && !signedIn) process.exit(1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-user-hub",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "Start a TanStack Start + Convex app with User Hub sign-in: bun create user-hub@latest my-app",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,7 +1,9 @@
1
- # From your hub's admin. bun run setup reads them; never commit them.
1
+ # Saved by bunx hub-user login (bun run setup runs it when they are missing).
2
+ # Never commit them; never share the API key.
2
3
  HUB_URL=https://hub.example.com
3
- HUB_ADMIN_PASSWORD=
4
+ HUB_API_KEY=
4
5
 
5
6
  # Written by bun run setup and the Convex CLI:
6
7
  # CONVEX_DEPLOYMENT, VITE_CONVEX_URL, VITE_HUB_URL, HUB_APP_NAME (this app's
7
- # name in the hub, once registered), HUB_APP_PROD_URL (once given)
8
+ # name in the hub, once registered), HUB_APP_DEV_URL (its development URL),
9
+ # HUB_APP_PROD_URL (once given)
@@ -14,8 +14,9 @@ A TanStack Start + Convex app whose sign-in comes from User Hub: people scan the
14
14
 
15
15
  - **Bun only:** `bun` and `bunx`; never `npm`, `npx`, `pnpm` or `yarn`.
16
16
  - **Never hand-roll auth:** no login screens, passwords, sessions or token handling. If something is missing, it belongs in `@user-hub/auth`.
17
- - **Secrets:** `HUB_ADMIN_PASSWORD` lives only in `.env.local`, set by the human. Never print, copy or commit it.
17
+ - **Secrets:** `HUB_API_KEY` lives only in `.env.local`, saved by `hub-user login`. Never ask for it (or a password) in chat, write it yourself, print it, copy it, commit it, or print `.env.local`. When the folder is not signed in (`bunx hub-user whoami` exits with code 4), ask the human to run `bunx hub-user login`, or run `bunx hub-user login --browser` and give them the link it prints (the skill's "Signing in"). Run `bunx hub-user` only in this folder with the dependencies installed (`bun install`): it runs the CLI from `@user-hub/auth`; anywhere else it fetches an npm package called `hub-user`, which is not ours.
18
18
  - **Convex:** public functions are thin wrappers (validators, an auth check, one call into `convex/model/`); every function has `args` and `returns` validators; reads use indexes and are bounded.
19
+ - **Convex AI files** are off (`"aiFiles": { "enabled": false }` in `convex.json`), so `convex dev` never asks to add them: they would append a block telling agents to use `npx` to this file and add its own skills. To add them anyway, run `bunx convex ai-files enable`.
19
20
  - **UI:** shadcn components only (`bunx --bun shadcn@latest add …`), dark theme, works on mobile. Lists are `Item`s in an `ItemGroup` with actions in a `ButtonGroup`, never tables; forms use `Field`.
20
21
  - **Imports:** the `@/` alias for `src/`.
21
22
  - **Generated files:** never edit `src/routeTree.gen.ts`, `convex/_generated/*` or `src/components/ui/*` by hand.
@@ -23,6 +24,6 @@ A TanStack Start + Convex app whose sign-in comes from User Hub: people scan the
23
24
 
24
25
  ## Commands
25
26
 
26
- `bun run setup` (once), `bun run setup --prod <url>` (once deployed: registers the production URL so badge scans can reach the app; see the skill's "Production URL"), `bun run setup --unlisted` / `--listed` (keep the app out of the hub's badge app list, or put it back; new apps are listed), `bun run dev`, `bun run check` (`vp check`: format, lint and type-check), `bun run fix` (`vp check --fix`), `bun run typecheck`, `bun run build`, `just build` / `just push` (deploy Convex to production and build the Docker image against it; `IMAGE` sets the registry path; the container needs no env). Lint and format rules live in `vite.config.ts` (Vite+); `vp` is project-local, so run it through the scripts or `bunx vp`.
27
+ `bun run setup` (once; signs the folder in first when run in a terminal and it is not), `bun run setup --prod <url>` (once deployed: registers the production URL so badge scans can reach the app; see the skill's "Production URL"), `bun run setup --dev <url>` (change where the hub opens the app for developers; first registered as `http://localhost:` plus the port in the `dev` script, kept on later runs; change the port in the `dev` script too), `bun run setup --unlisted` / `--listed` (keep the app out of the hub's badge app list, or put it back; new apps are listed), `bun run dev`, `bun run check` (`vp check`: format, lint and type-check), `bun run fix` (`vp check --fix`), `bun run typecheck`, `bun run build`, `just build` / `just push` (deploy Convex to production and build the Docker image against it; `IMAGE` sets the registry path; the container needs no env). Lint and format rules live in `vite.config.ts` (Vite+); `vp` is project-local, so run it through the scripts or `bunx vp`.
27
28
 
28
- **Hub moved:** change `HUB_URL` in `.env.local`, run `bun run setup` (it updates this app's registration and sets `HUB_ISSUER`/`HUB_JWKS` on Convex, production included once a production URL is known, and `VITE_HUB_URL`), then `just push`, because `VITE_HUB_URL` is built into the frontend.
29
+ **Hub moved:** sign the folder in to the new hub (`bunx hub-user login --hub <new url>`, replacing `HUB_URL` and `HUB_API_KEY`), run `bun run setup` (it updates this app's registration and sets `HUB_ISSUER`/`HUB_JWKS` on Convex, production included once a production URL is known, and `VITE_HUB_URL`), then `just push`, because `VITE_HUB_URL` is built into the frontend.
@@ -4,15 +4,16 @@ A TanStack Start + Convex app with User Hub sign-in: people scan their badge and
4
4
 
5
5
  ## Get started
6
6
 
7
- 1. Ask your hub's admin for the hub URL and admin password, and put them in `.env.local`:
7
+ 1. Sign this folder in to your hub (your hub's admin gives you its URL and an account):
8
8
 
9
9
  ```sh
10
- HUB_URL=https://hub.example.com
11
- HUB_ADMIN_PASSWORD=…
10
+ bunx hub-user login --hub https://hub.example.com
12
11
  ```
13
12
 
14
- 2. `bun run setup`: creates your Convex project, registers the app with the hub and sets everything up. If another app already has this name in the hub, it asks you for a new one (or run `bun run setup --name <name>`). New apps show in the hub's badge app list once they have a production URL; `bun run setup --unlisted` keeps this one out and `--listed` puts it back. Safe to run again.
15
- 3. `bun run dev`, then open http://localhost:3000. You are sent to the hub to pick who to be, then back signed in.
13
+ Run it in this folder with the dependencies installed (`bun install` first in a fresh clone): `bunx hub-user` runs the CLI that comes with `@user-hub/auth`. Anywhere else it fetches an npm package called `hub-user`, which is not ours. Paste an API key from the hub's account page, or press Enter and approve the sign-in in your browser. It saves `HUB_URL` and `HUB_API_KEY` to `.env.local`. Skip this if you signed in when the app was created; `bun run setup` also asks when this folder is not signed in.
14
+
15
+ 2. `bun run setup`: creates your Convex project, registers the app with the hub and sets everything up. If another app already has this name in the hub, it asks you for a new one (or run `bun run setup --name <name>`). New apps show in the hub's badge app list once they have a production URL; `bun run setup --unlisted` keeps this one out and `--listed` puts it back. Safe to run again. If the hub later says your account may not change this app (it belongs to another account), ask a hub admin, or register it under a new name: delete `HUB_APP_NAME` from `.env.local` and run `bun run setup --name <new name>`.
16
+ 3. `bun run dev`, then open http://localhost:3000. You are sent to the hub to pick who to be, then back signed in. To use another port, change it in `package.json`'s `dev` script and run `bun run setup --dev http://localhost:<port>`; later runs of setup keep the development URL.
16
17
  4. Once the app is deployed: `bun run setup --prod https://your-app.example.com`, so badge scans can reach it. Setup asks for this the first time; press Enter to skip until you deploy.
17
18
 
18
19
  ## Deploy
@@ -26,7 +27,7 @@ Then serve the container (port 3000) at your production URL and make sure the hu
26
27
 
27
28
  ### Hub moved
28
29
 
29
- Change `HUB_URL` in `.env.local` and run `bun run setup`: it updates this app's registration with the new hub and sets `HUB_ISSUER`, `HUB_JWKS` (on the production Convex deployment too, once it has a production URL) and `VITE_HUB_URL`. Then `just push`, because `VITE_HUB_URL` is built into the frontend.
30
+ Sign this folder in to the new hub (`bunx hub-user login --hub <new url>`, which replaces `HUB_URL` and `HUB_API_KEY` in `.env.local`) and run `bun run setup`: it updates this app's registration with the new hub and sets `HUB_ISSUER`, `HUB_JWKS` (on the production Convex deployment too, once it has a production URL) and `VITE_HUB_URL`. Then `just push`, because `VITE_HUB_URL` is built into the frontend.
30
31
 
31
32
  ## What's inside
32
33
 
@@ -5,5 +5,8 @@
5
5
  },
6
6
  "codegen": {
7
7
  "fileType": "ts"
8
+ },
9
+ "aiFiles": {
10
+ "enabled": false
8
11
  }
9
12
  }
@@ -19,7 +19,7 @@
19
19
  "@tailwindcss/vite": "^4.3.3",
20
20
  "@tanstack/react-router": "^1.170.46",
21
21
  "@tanstack/react-start": "^1.169.4",
22
- "@user-hub/auth": "^0.2.1",
22
+ "@user-hub/auth": "^0.3.0",
23
23
  "class-variance-authority": "^0.7.1",
24
24
  "cn": "^0.5.0",
25
25
  "convex": "^1.48.0",
@@ -1,18 +1,21 @@
1
1
  // Setup: creates the Convex project, registers this app with User Hub and
2
2
  // sets the values that make Convex trust the hub's tokens.
3
- // Run: bun run setup [--name <name>] [--prod <url>] [--listed|--unlisted].
4
- // Safe to run again; run it with --prod once the app is deployed so badge
5
- // scans can reach it. --unlisted keeps the app out of the hub's badge app list
6
- // (new apps are listed), --listed puts it back; without either, the hub keeps
7
- // the current setting.
8
- // Needs HUB_URL and HUB_ADMIN_PASSWORD in .env.local (Bun loads it).
3
+ // Run: bun run setup [--name <name>] [--prod <url>] [--dev <url>]
4
+ // [--listed|--unlisted]. Safe to run again; run it with --prod once the app
5
+ // is deployed so badge scans can reach it. --dev changes where the hub opens
6
+ // the app for developers (first registered as http://localhost:<the port in
7
+ // package.json's dev script>); later runs keep it. --unlisted keeps the app
8
+ // out of the hub's badge app list (new apps are listed), --listed puts it
9
+ // back; without either, the hub keeps the current setting.
10
+ // Needs HUB_URL and HUB_API_KEY in .env.local (Bun loads it), which
11
+ // `bunx hub-user login` saves; in a terminal, setup runs it when they are
12
+ // missing or the hub refuses the key.
9
13
 
10
14
  import { existsSync, renameSync } from "node:fs";
11
15
  import { rename } from "node:fs/promises";
12
16
 
13
17
  const ENV_FILE = ".env.local";
14
18
  const HUB_FILE = "convex/hub.ts";
15
- const DEV_URL = "http://localhost:3000";
16
19
  const AUTH_CONFIG = "convex/auth.config.ts";
17
20
  const AUTH_CONFIG_ASIDE = "convex/auth.config.ts.setup";
18
21
 
@@ -31,16 +34,34 @@ function fail(message: string): never {
31
34
  process.exit(1);
32
35
  }
33
36
 
34
- async function run(command: string[], { capture = false } = {}) {
37
+ // capture keeps stdout; hub-user also keeps stderr, so its "run `bunx
38
+ // hub-user login`" hint can give way to setup's own message (setup runs the
39
+ // login itself) and other errors are printed as they are.
40
+ async function run(
41
+ command: string[],
42
+ { capture = false, hubUser = false } = {},
43
+ ) {
35
44
  const child = Bun.spawn(command, {
36
45
  stdin: "inherit",
37
46
  stdout: capture ? "pipe" : "inherit",
38
- stderr: "inherit",
47
+ stderr: hubUser ? "pipe" : "inherit",
39
48
  env: process.env,
40
49
  });
41
- const output = capture ? await new Response(child.stdout).text() : "";
50
+ const [output, errors] = await Promise.all([
51
+ capture ? new Response(child.stdout).text() : "",
52
+ hubUser ? new Response(child.stderr).text() : "",
53
+ ]);
42
54
  const code = await child.exited;
43
- return { ok: code === 0, code, output };
55
+ return { ok: code === 0, code, output, errors };
56
+ }
57
+
58
+ // hub-user from this app's node_modules; --no-install never fetches a package
59
+ // of that name from npm.
60
+ function hubUser(...args: string[]) {
61
+ return run(["bunx", "--no-install", "hub-user", ...args], {
62
+ capture: true,
63
+ hubUser: true,
64
+ });
44
65
  }
45
66
 
46
67
  async function readEnv() {
@@ -56,15 +77,81 @@ async function writeEnv(key: string, value: string) {
56
77
  await Bun.write(ENV_FILE, `${[...lines, `${key}=${value}`].join("\n")}\n`);
57
78
  }
58
79
 
80
+ // Signs this folder in to the hub with `hub-user login` (an API key or the
81
+ // browser), then picks up the HUB_URL and HUB_API_KEY it saved, which this
82
+ // process read from .env.local before they were there.
83
+ async function signIn() {
84
+ step("Signing this folder in to User Hub");
85
+ const hub = process.env.HUB_URL;
86
+ const login = await run([
87
+ "bunx",
88
+ "--no-install",
89
+ "hub-user",
90
+ "login",
91
+ ...(hub ? ["--hub", hub] : []),
92
+ ]);
93
+ if (!login.ok) fail("Not signed in to the hub. Run bun run setup again.");
94
+ const saved = await readEnv();
95
+ for (const key of ["HUB_URL", "HUB_API_KEY"]) {
96
+ const value = new RegExp(`^${key}=(.*)$`, "m").exec(saved)?.[1];
97
+ if (value) process.env[key] = value;
98
+ }
99
+ }
100
+
101
+ // What to run when this folder is not signed in and nobody can be asked.
102
+ function loginHelp(problem: string) {
103
+ const hub = process.env.HUB_URL ? "" : " --hub https://<your hub>";
104
+ return `${problem} Sign the folder in, then run bun run setup again:
105
+
106
+ bunx hub-user login${hub}
107
+
108
+ It asks you to paste an API key from the hub's account page, or to approve
109
+ the sign-in in your browser. A coding agent runs it with --browser and shows
110
+ you the link to open.`;
111
+ }
112
+
113
+ // hub-user register --json prints { error, status, forbidden } with exit code
114
+ // 4; forbidden means a 403 (not this account's app), not a login problem.
115
+ function forbidden(output: string) {
116
+ try {
117
+ return (JSON.parse(output) as { forbidden?: boolean }).forbidden === true;
118
+ } catch {
119
+ return false;
120
+ }
121
+ }
122
+
59
123
  // Put back an auth config left aside by an interrupted run.
60
124
  if (existsSync(AUTH_CONFIG_ASIDE) && !existsSync(AUTH_CONFIG)) {
61
125
  renameSync(AUTH_CONFIG_ASIDE, AUTH_CONFIG);
62
126
  }
63
127
 
64
- if (!process.env.HUB_URL || !process.env.HUB_ADMIN_PASSWORD) {
65
- fail(
66
- `Add HUB_URL and HUB_ADMIN_PASSWORD to ${ENV_FILE} (ask your hub's admin), then run bun run setup again.`,
67
- );
128
+ // hub-user comes with @user-hub/auth.
129
+ if (!existsSync("node_modules/@user-hub/auth")) {
130
+ fail("Install the dependencies first: bun install");
131
+ }
132
+
133
+ // Sign-in first: nothing below works without it, and a refused key is better
134
+ // found before the Convex project and the questions.
135
+ if (!process.env.HUB_URL || !process.env.HUB_API_KEY) {
136
+ if (!process.stdin.isTTY) {
137
+ fail(loginHelp("This folder is not signed in to the hub."));
138
+ }
139
+ await signIn();
140
+ } else {
141
+ // hub-user whoami exits with 4 when the hub refuses the key.
142
+ const whoami = await hubUser("whoami", "--json");
143
+ if (whoami.code === 4) {
144
+ if (!process.stdin.isTTY) {
145
+ fail(loginHelp("The hub did not accept this folder's API key."));
146
+ }
147
+ console.log("\n The hub did not accept this folder's API key.");
148
+ await signIn();
149
+ } else if (!whoami.ok) {
150
+ process.stderr.write(whoami.errors);
151
+ fail(
152
+ `Could not check this folder's sign-in with ${process.env.HUB_URL}; see the error above.`,
153
+ );
154
+ }
68
155
  }
69
156
 
70
157
  // 1. Convex project. Its first push happens before the hub values exist, so
@@ -98,9 +185,11 @@ if (!/^CONVEX_DEPLOYMENT=/m.test(await readEnv())) {
98
185
  // another one. Once registered, the name is kept in .env.local
99
186
  // (HUB_APP_NAME) and later runs update this app's own registration.
100
187
  step("Registering this app with User Hub");
101
- const packageName = (
102
- (await Bun.file("package.json").json()) as { name: string }
103
- ).name;
188
+ const packageJson = (await Bun.file("package.json").json()) as {
189
+ name: string;
190
+ scripts: { dev?: string };
191
+ };
192
+ const packageName = packageJson.name;
104
193
  // HUB_APP_NAME is written only after a successful registration, so it marks
105
194
  // this app's own entry. `bun run setup --name <name>` picks a new name.
106
195
  const alreadyRegistered = Boolean(process.env.HUB_APP_NAME);
@@ -115,29 +204,52 @@ if (!prodUrl && !process.env.HUB_APP_PROD_URL && process.stdin.isTTY) {
115
204
  " Production URL, where badge scans send people (Enter to skip until you deploy):",
116
205
  )?.trim() || undefined;
117
206
  }
207
+ // Where the hub opens the app for developers. Sent the first time and with
208
+ // --dev; otherwise the hub keeps the registered one, which HUB_APP_DEV_URL
209
+ // remembers (set by hand with hub-user register, it is not known here).
210
+ const devPort =
211
+ /--port (\d+)/.exec(packageJson.scripts.dev ?? "")?.[1] ?? "3000";
212
+ const devFlag = flag("dev");
213
+ const sendDev = Boolean(devFlag) || !alreadyRegistered;
214
+ const devUrl: string | undefined =
215
+ devFlag ??
216
+ process.env.HUB_APP_DEV_URL ??
217
+ (sendDev ? `http://localhost:${devPort}` : undefined);
118
218
  // Passed on to hub-user as is; without either the hub keeps its setting.
119
219
  const listing = ["--listed", "--unlisted"].filter((arg) =>
120
220
  process.argv.includes(arg),
121
221
  );
122
222
  if (listing.length > 1) fail("Pass --listed or --unlisted, not both.");
123
223
  let registered: Awaited<ReturnType<typeof run>>;
224
+ let signedInAgain = false;
124
225
  for (;;) {
125
- registered = await run(
126
- [
127
- "bunx",
128
- "hub-user",
129
- "register",
130
- "--name",
131
- appName,
132
- "--dev",
133
- DEV_URL,
134
- ...(prodUrl ? ["--prod", prodUrl] : []),
135
- ...listing,
136
- "--json",
137
- ...(alreadyRegistered ? [] : ["--new"]),
138
- ],
139
- { capture: true },
226
+ registered = await hubUser(
227
+ "register",
228
+ "--name",
229
+ appName,
230
+ ...(sendDev && devUrl ? ["--dev", devUrl] : []),
231
+ ...(prodUrl ? ["--prod", prodUrl] : []),
232
+ ...listing,
233
+ "--json",
234
+ ...(alreadyRegistered ? [] : ["--new"]),
140
235
  );
236
+ // hub-user exits with 4 when the hub refuses the API key (401) or this
237
+ // account may not change the app (403); its JSON says which.
238
+ if (registered.code === 4) {
239
+ if (forbidden(registered.output)) {
240
+ fail(`The hub says your account may not change the app "${appName}": it belongs to
241
+ another account, or was registered before accounts and only a hub admin can
242
+ change it. Signing in again does not help. Ask a hub admin, or register this
243
+ app under a new name: ${alreadyRegistered ? `delete HUB_APP_NAME from ${ENV_FILE}, then run ` : ""}bun run setup --name <new name>`);
244
+ }
245
+ if (!process.stdin.isTTY || signedInAgain) {
246
+ fail(loginHelp("The hub did not accept this folder's API key."));
247
+ }
248
+ console.log("\n The hub did not accept this folder's API key.");
249
+ await signIn();
250
+ signedInAgain = true;
251
+ continue;
252
+ }
141
253
  // hub-user exits with 3 when --new finds the name taken.
142
254
  if (registered.code !== 3) break;
143
255
  console.log(`\n An app called "${appName}" already exists in the hub.`);
@@ -148,10 +260,11 @@ for (;;) {
148
260
  if (!appName) fail("No name given. Run bun run setup again.");
149
261
  }
150
262
  if (!registered.ok) {
263
+ process.stderr.write(registered.errors);
151
264
  fail(
152
265
  prodUrl
153
- ? "The hub refused the registration; see the error above. Check HUB_URL, HUB_ADMIN_PASSWORD and that the production URL is a full https:// address."
154
- : "The hub refused the registration; see the error above. Check HUB_URL and HUB_ADMIN_PASSWORD.",
266
+ ? "The hub refused the registration; see the error above. Check HUB_URL and that the production URL is a full https:// address."
267
+ : "The hub refused the registration; see the error above. Check HUB_URL.",
155
268
  );
156
269
  }
157
270
  const { key, hubUrl, env, listed } = JSON.parse(registered.output) as {
@@ -163,8 +276,19 @@ const { key, hubUrl, env, listed } = JSON.parse(registered.output) as {
163
276
  };
164
277
  await writeEnv("HUB_APP_NAME", appName);
165
278
  if (prodUrl) await writeEnv("HUB_APP_PROD_URL", prodUrl);
279
+ if (sendDev && devUrl) await writeEnv("HUB_APP_DEV_URL", devUrl);
166
280
  const production = prodUrl ?? process.env.HUB_APP_PROD_URL;
167
281
  console.log(` Registered as "${appName}", app key: ${key}`);
282
+ console.log(
283
+ ` Development URL: ${devUrl ?? "the one registered in the hub"}${sendDev ? "" : " (kept; bun run setup --dev <url> changes it)"}`,
284
+ );
285
+ // bun run dev must serve where the hub sends developers back to.
286
+ const devUrlPort = devUrl ? URL.parse(devUrl)?.port : undefined;
287
+ if (devUrlPort && devUrlPort !== devPort) {
288
+ console.log(
289
+ ` Note: bun run dev serves port ${devPort} (package.json), not ${devUrlPort}. Change one so they match.`,
290
+ );
291
+ }
168
292
  if (listed !== undefined) {
169
293
  console.log(
170
294
  listed
@@ -230,6 +354,6 @@ console.log(`
230
354
 
231
355
  bun run dev
232
356
 
233
- Open ${DEV_URL}: you are sent to the hub to pick who to be, then back signed in.
357
+ Open ${devUrl ?? "the development URL registered in the hub"}: you are sent to the hub to pick who to be, then back signed in.
234
358
 
235
359
  ${productionNote}`);