@user-hub/auth 0.2.0 → 0.3.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,7 +8,7 @@ Works with Convex apps, React frontends and any server that can check a token.
8
8
 
9
9
  ## How it works
10
10
 
11
- 1. A person scans their badge. The hub sends them to your app with a token in the URL: `https://your-app.com/#token=…`.
11
+ 1. A person scans their badge. The hub sends them to the app that is live, or shows its app list and sends them to the one they pick, with a token in the URL: `https://your-app.com/#token=…`. Your app handles both the same way.
12
12
  2. The provider takes the token out of the address bar and keeps it in the browser, separately for each app.
13
13
  3. Convex (or your server) checks the token with the hub's public key. A token is only accepted by the app it was made for.
14
14
  4. Your app stores its own data under the person's `id`.
@@ -38,22 +38,23 @@ Using a coding agent? The package ships an agent skill. Add it to your agents wi
38
38
  bunx skills experimental_sync
39
39
  ```
40
40
 
41
- ### 2. Register your app with the hub
41
+ ### 2. Sign in and register your app
42
42
 
43
- Ask the hub's admin for its URL and the admin password, and put both in your app's `.env` or `.env.local` (keep it gitignored), or your secret manager:
43
+ Ask the hub's admin for its URL and an account. Then, from your app's folder (with `@user-hub/auth` installed: `bunx hub-user` runs the installed CLI), sign in once:
44
44
 
45
45
  ```sh
46
- HUB_URL=https://hub.example.com
47
- HUB_ADMIN_PASSWORD=…
46
+ bunx hub-user login --hub https://hub.example.com
48
47
  ```
49
48
 
50
- Then, from your app's folder (`bunx` reads `.env` and `.env.local` automatically; with a secret manager, run it through that):
49
+ Paste an API key you created on the hub's **Account** page (`<hub>/account`; it shows as stars), or press Enter to sign in with your browser: it prints a link, you approve the request in the hub, and the CLI makes its own API key. Either way it checks the key with the hub and saves `HUB_URL` and `HUB_API_KEY` to the folder's `.env.local`, readable only by you, keeping the file's other lines. Keep `.env.local` gitignored. Without a terminal (scripts, coding agents), `bunx hub-user login --browser` prints the link for a person to approve, and `bunx hub-user login --api-key-stdin` reads a key from stdin. `bunx hub-user whoami` shows which account the folder is signed in as. Keys do not expire: delete one on `<hub>/account` to revoke it. Outside a folder with the package installed, run it as `bunx -p @user-hub/auth hub-user …`, never a bare `bunx hub-user`: there it fetches an npm package called `hub-user`, which is not ours. Hubs with accounts need `@user-hub/auth` 0.3 or newer. Upgrading from 0.2? Run `bun add @user-hub/auth@latest` (a `^0.2` range never installs 0.3), then `bunx hub-user login`; `HUB_ADMIN_PASSWORD` is no longer used, so delete it from your env files.
50
+
51
+ Then register the app (`bunx` reads `.env` and `.env.local` automatically; if `HUB_URL` and `HUB_API_KEY` live in a secret manager, run it through that):
51
52
 
52
53
  ```sh
53
54
  bunx hub-user register --name "Your App" --new --prod https://your-app.com --dev http://localhost:3000
54
55
  ```
55
56
 
56
- It prints your **app key** (made from the name) and the values to set. Not deployed yet? Leave out `--prod`: you can develop, and badge scans start reaching the app once you add it. Run it again with the same `--name` to update the URLs; a URL left out keeps the registered one. `--new` refuses to touch an app that already has that name, so you never take over someone else's; leave it out when updating your own app later. (A hub admin can do the same under **Apps** in the hub, and copy the values from **Setup**.)
57
+ It prints your **app key** (made from the name) and the values to set. Not deployed yet? Leave out `--prod`: you can develop, and badge scans start reaching the app once you add it. Run it again with the same `--name` to update the URLs; a URL left out keeps the registered one. `--new` refuses to touch an app that already has that name, so you never take over someone else's; leave it out when updating your own app later. New apps are **listed** in the badge app list by default: when the hub shows the app list instead of one live app, listed apps with a production URL appear in it. Pass `--unlisted` to keep one out of it (it can still be scheduled or forced live), or `--listed` to show it again. Pass neither on an update and the hub's current setting stays; the output shows it. Only the account that created an app, or a hub admin, can update it; anyone else gets exit code 4 and is asked to pick another name. Apps registered before the hub had accounts belong to no account, so only a hub admin can change them. (A hub admin can do the same under **Apps** in the hub, and copy the values from **Setup**.)
57
58
 
58
59
  ### 3. Set the values
59
60
 
@@ -114,7 +115,7 @@ export const myVotes = query({
114
115
 
115
116
  ## Working on your app locally
116
117
 
117
- Run your dev server as usual and open it. With no token yet, it sends you to the hub, where you pick who to be (the admin password is asked once per browser), and brings you back signed in. You stay signed in across reloads and restarts until that person's expiration in the hub (4 hours unless set otherwise).
118
+ Run your dev server as usual and open it. With no token yet, it sends you to the hub, where you pick who to be (sign in to the hub with your account once per browser), and brings you back signed in. You stay signed in across reloads and restarts until that person's expiration in the hub (4 hours unless set otherwise).
118
119
 
119
120
  - **Switch person:** open `<hub>/open/<your-app-key>`.
120
121
  - **Different port:** run `hub-user register` again with the new `--dev` URL. The hub only sends tokens to registered URLs.
@@ -181,16 +182,21 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
181
182
  | `@user-hub/auth/react` | `HubAuthProvider` | The same without Convex: `app`, `hubUrl?` |
182
183
  | both | `HubSignedIn` | Shows its children only when signed in. Props: `signedOut?`, `loading?` |
183
184
  | | `useHubUser()`, `useHubToken()`, `useHubSignOut()` | The person (or null), the current token (or null; it changes as it is refreshed), a sign-out function. Also from `/convex-react` |
185
+ | | `useHubSession()` | `undefined` while loading, `null` when signed out, otherwise `{ token, user }`; most apps need only `useHubUser()` or `<HubSignedIn>`. Also from `/convex-react` |
184
186
  | `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app })` | Checks a token anywhere else |
185
- | CLI | `hub-user register --name <name> [--prod <url>] [--dev <url>] [--new] [--hub <url>] [--json]` | Registers or updates the app (at least one URL); `--new` only creates, exit code 3 if the name is taken |
187
+ | CLI | `hub-user login [--hub <url>] [--browser\|--api-key-stdin]` | Signs the folder in: an API key pasted (hidden) or from stdin, or a browser sign-in it prints a link for (it never opens a browser). Saves `HUB_URL` and `HUB_API_KEY` to `./.env.local` (mode 600) |
188
+ | | `hub-user whoami [--json]` | The account `HUB_API_KEY` belongs to; exit code 4 when not signed in |
189
+ | | `hub-user register --name <name> [--prod <url>] [--dev <url>] [--listed\|--unlisted] [--new] [--hub <url>] [--json]` | Registers or updates the app (a new app needs at least one URL; an update may leave both out); `--new` only creates, exit code 3 if the name is taken; `--listed`/`--unlisted` set whether the app shows in the badge app list once it has a production URL (new apps default to listed, omitted keeps the hub's setting) |
190
+ | | Exit codes | 0 done, 1 error, 3 name taken (`register --new`), 4 not signed in (run `hub-user login`) or not allowed (another account's app) |
186
191
 
187
192
  ## Developing this package
188
193
 
189
194
  ```sh
190
195
  bun install
191
- bun test # unit tests
192
- bun run check # Biome
193
- bun run build # dist/: commit it
196
+ bun test # unit tests
197
+ bunx tsc --noEmit -p . # type-check
198
+ bun run check # Biome
199
+ bun run build # dist/: commit it
194
200
  ```
195
201
 
196
202
  Release with `just release patch` (or `minor` / `major`): it bumps the version, publishes to npm and pushes the commit and tag. See the comments in the `justfile`.
package/dist/cli.js CHANGED
@@ -1,84 +1,393 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
3
  // src/cli.ts
4
+ import { spawnSync } from "node:child_process";
5
+ import { chmod, writeFile } from "node:fs/promises";
6
+ import { hostname } from "node:os";
7
+ import { basename } from "node:path";
4
8
  import { parseArgs } from "node:util";
5
- var USAGE = `Usage: hub-user register --name <name> [--prod <url>] [--dev <url>] [--new] [--hub <url>] [--json]
9
+ var USAGE = `Usage:
10
+ hub-user login [--hub <url>] [--browser | --api-key-stdin]
11
+ hub-user whoami [--hub <url>] [--json]
12
+ hub-user register --name <name> [--prod <url>] [--dev <url>] [--listed|--unlisted] [--new] [--hub <url>] [--json]
6
13
 
7
- --name The app's name in the hub; its key comes from it (required)
8
- --prod Where badge scans send people. Leave it out until the app is
9
- deployed: it can be developed, but not scheduled.
10
- --dev Where developers open the app as a person, e.g. http://localhost:3000
11
- --new Only create a new app: if the name is taken, change nothing and
12
- exit with code 3 so you can pick another name
13
- --hub The hub's URL (default: HUB_URL)
14
- --json Print JSON instead of text
14
+ login Signs this folder in to the hub: saves HUB_URL and HUB_API_KEY to
15
+ ./.env.local (mode 600, other lines kept; keep it out of git).
16
+ --hub The hub's URL (default: HUB_URL; asked in a terminal)
17
+ --browser Sign in with your browser: prints a link to open and approve
18
+ (it never opens a browser itself; works without a terminal)
19
+ --api-key-stdin Read an API key from stdin (create one at <hub>/account)
20
+ In a terminal without either flag, it asks you to paste an API key or press
21
+ Enter to sign in with your browser.
15
22
 
16
- At least one of --prod and --dev is needed. A URL left out on a later run keeps
17
- the registered one.
23
+ whoami Shows the hub account HUB_API_KEY belongs to.
18
24
 
19
- Needs HUB_URL and HUB_ADMIN_PASSWORD in the environment (.env and .env.local
20
- are read automatically). Running it again with the same
21
- name updates that app.`;
25
+ register Registers the app, or updates it when the name exists.
26
+ --name The app's name in the hub; its key comes from it (required)
27
+ --prod Where badge scans send people. Leave it out until the app is
28
+ deployed: it can be developed, but not scheduled or shown in
29
+ the badge app list.
30
+ --dev Where developers open the app as a person, e.g. http://localhost:3000
31
+ --listed Show the app in the hub's badge app list once it has a
32
+ production URL (default for new apps)
33
+ --unlisted Keep the app out of the hub's badge app list
34
+ --new Only create a new app: if the name is taken, change nothing and
35
+ exit with code 3 so you can pick another name
36
+ --hub The hub's URL (default: HUB_URL)
37
+ --json Print JSON instead of text
38
+
39
+ At least one of --prod and --dev is needed with --new or when first registering.
40
+ A URL left out on a later run keeps the registered one; both may be omitted on
41
+ an update. Without --listed or --unlisted, re-registering keeps the current
42
+ listing setting. Running it again with the same name updates that app.
43
+
44
+ whoami and register need HUB_URL and HUB_API_KEY in the environment (.env and
45
+ .env.local are read automatically); hub-user login puts them there.
46
+
47
+ Exit codes: 0 done, 1 error, 3 name taken (register --new), 4 not signed in or
48
+ not allowed.`;
49
+ var ENV_FILE = ".env.local";
50
+ var CLIENT_ID = "hub-user";
51
+ var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
52
+ var LOGIN = "bunx -p @user-hub/auth hub-user login";
53
+ var KEY_NAME_LIMIT = 128;
22
54
  function fail(message) {
23
55
  console.error(`hub-user: ${message}`);
24
56
  process.exit(1);
25
57
  }
26
- var { values, positionals } = parseArgs({
27
- args: process.argv.slice(2),
28
- allowPositionals: true,
29
- options: {
30
- prod: { type: "string" },
31
- dev: { type: "string" },
32
- name: { type: "string" },
33
- hub: { type: "string" },
34
- json: { type: "boolean", default: false },
35
- new: { type: "boolean", default: false },
36
- help: { type: "boolean", short: "h", default: false }
37
- }
38
- });
39
- if (values.help || positionals[0] !== "register") {
58
+ function denied(message, json) {
59
+ console.error(`hub-user: ${message}`);
60
+ if (json)
61
+ console.log(JSON.stringify({ error: message, ...json }, null, 2));
62
+ process.exit(4);
63
+ }
64
+ function parse() {
65
+ try {
66
+ return parseArgs({
67
+ args: process.argv.slice(2),
68
+ allowPositionals: true,
69
+ options: {
70
+ prod: { type: "string" },
71
+ dev: { type: "string" },
72
+ name: { type: "string" },
73
+ hub: { type: "string" },
74
+ json: { type: "boolean", default: false },
75
+ new: { type: "boolean", default: false },
76
+ listed: { type: "boolean", default: false },
77
+ unlisted: { type: "boolean", default: false },
78
+ browser: { type: "boolean", default: false },
79
+ "api-key-stdin": { type: "boolean", default: false },
80
+ help: { type: "boolean", short: "h", default: false }
81
+ }
82
+ });
83
+ } catch (error) {
84
+ fail(`${error.message}
85
+
86
+ ${USAGE}`);
87
+ }
88
+ }
89
+ var { values, positionals } = parse();
90
+ var command = positionals[0];
91
+ if (values.help || !command || !["login", "whoami", "register"].includes(command)) {
40
92
  console.log(USAGE);
41
93
  process.exit(values.help ? 0 : 1);
42
94
  }
43
- var hub = (values.hub ?? process.env.HUB_URL)?.replace(/\/+$/, "");
44
- var password = process.env.HUB_ADMIN_PASSWORD;
45
- var name = values.name?.trim();
46
- if (!hub)
47
- fail("set HUB_URL (in .env or .env.local) or pass --hub");
48
- if (!password)
49
- fail("set HUB_ADMIN_PASSWORD (in .env or .env.local)");
50
- if (!values.prod && !values.dev)
51
- fail("pass --prod <url>, --dev <url> or both");
52
- if (!name)
53
- fail("pass --name <name>, the app's name in the hub");
54
- var response = await fetch(`${hub}/api/apps/register`, {
55
- method: "POST",
56
- headers: {
57
- Authorization: `Bearer ${password}`,
58
- "Content-Type": "application/json"
59
- },
60
- body: JSON.stringify({
61
- name,
62
- ...values.prod !== undefined && { url: values.prod },
63
- ...values.dev !== undefined && { devUrl: values.dev },
64
- ...values.new && { createOnly: true }
65
- })
66
- }).catch((error) => fail(`could not reach ${hub}: ${error.message}`));
67
- var result = await response.json().catch(() => ({}));
68
- if (result.taken) {
69
- if (values.json)
70
- console.log(JSON.stringify(result, null, 2));
71
- else
72
- console.error(`hub-user: ${result.error}`);
73
- process.exit(3);
95
+ var oldPassword = Boolean(process.env.HUB_ADMIN_PASSWORD && !process.env.HUB_API_KEY?.trim());
96
+ if (oldPassword && command === "login") {
97
+ console.error("hub-user: HUB_ADMIN_PASSWORD is no longer used; delete it from your env files.");
98
+ }
99
+ var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
100
+ function hubUrl(value) {
101
+ const url = value?.trim().replace(/\/+$/, "");
102
+ if (!url) {
103
+ return;
104
+ }
105
+ const parsed = URL.parse(url);
106
+ const allowed = parsed?.protocol === "https:" || parsed?.protocol === "http:" && LOOPBACK.has(parsed.hostname);
107
+ if (!allowed) {
108
+ fail(`the hub URL must start with https:// (http:// only for localhost) (got "${url}")`);
109
+ }
110
+ return url;
111
+ }
112
+ function reason(body, status) {
113
+ return String(body.message ?? body.error_description ?? body.error ?? status);
114
+ }
115
+ async function call(hub, path, init = {}) {
116
+ const response = await fetch(`${hub}${path}`, {
117
+ method: init.body === undefined ? "GET" : "POST",
118
+ headers: {
119
+ ...init.token && { Authorization: `Bearer ${init.token}` },
120
+ ...init.body !== undefined && { "Content-Type": "application/json" }
121
+ },
122
+ ...init.body !== undefined && { body: JSON.stringify(init.body) }
123
+ }).catch((error) => fail(`could not reach ${hub}: ${error.message}`));
124
+ const body = await response.json().catch(() => ({}));
125
+ return { status: response.status, ok: response.ok, body };
126
+ }
127
+ async function account(hub, key) {
128
+ const { status, ok, body } = await call(hub, "/api/account", { token: key });
129
+ if (status === 401)
130
+ return null;
131
+ if (status === 404) {
132
+ fail(`${hub} has no accounts: the hub needs updating`);
133
+ }
134
+ if (!ok || typeof body.username !== "string") {
135
+ fail(typeof body.error === "string" ? body.error : `the hub answered ${status}`);
136
+ }
137
+ return body;
138
+ }
139
+ function signedIn(hub, me) {
140
+ return `Signed in to ${hub} as ${me.username} (${me.role})`;
141
+ }
142
+ function credentials(json) {
143
+ const hub = hubUrl(values.hub ?? process.env.HUB_URL);
144
+ const key = process.env.HUB_API_KEY?.trim();
145
+ if (!hub || !key) {
146
+ denied(`not signed in to a hub${oldPassword ? " (HUB_ADMIN_PASSWORD is no longer used)" : ""}: run \`${LOGIN}\` in the app's folder`, json ? { status: 401 } : undefined);
147
+ }
148
+ return { hub, key };
149
+ }
150
+ function secret(question) {
151
+ process.stdout.write(question);
152
+ process.stdin.setRawMode(true);
153
+ process.stdin.resume();
154
+ process.stdin.setEncoding("utf8");
155
+ return new Promise((done) => {
156
+ let value = "";
157
+ const finish = () => {
158
+ process.stdin.off("data", onData);
159
+ process.stdin.setRawMode(false);
160
+ process.stdin.pause();
161
+ process.stdout.write(`
162
+ `);
163
+ done(value.trim());
164
+ };
165
+ const onData = (chunk) => {
166
+ for (const char of chunk) {
167
+ if (char === "\r" || char === `
168
+ `)
169
+ return finish();
170
+ if (char === "\x03") {
171
+ process.stdout.write(`
172
+ `);
173
+ process.exit(130);
174
+ }
175
+ if (char === "" || char === "\b") {
176
+ if (value) {
177
+ value = value.slice(0, -1);
178
+ process.stdout.write("\b \b");
179
+ }
180
+ } else if (char >= " ") {
181
+ value += char;
182
+ process.stdout.write("*");
183
+ }
184
+ }
185
+ };
186
+ process.stdin.on("data", onData);
187
+ });
188
+ }
189
+ async function saveEnv(entries) {
190
+ const file = Bun.file(ENV_FILE);
191
+ const exists = await file.exists();
192
+ if (exists)
193
+ await chmod(ENV_FILE, 384);
194
+ const lines = exists ? (await file.text()).split(`
195
+ `) : [];
196
+ if (lines.at(-1) === "")
197
+ lines.pop();
198
+ for (const [key, value] of Object.entries(entries)) {
199
+ const pattern = new RegExp(`^\\s*(export\\s+)?${key}\\s*=`);
200
+ const at = lines.findIndex((line) => pattern.test(line));
201
+ const line = `${key}=${value}`;
202
+ if (at === -1) {
203
+ lines.push(line);
204
+ continue;
205
+ }
206
+ lines[at] = line;
207
+ for (let i = lines.length - 1;i > at; i--) {
208
+ if (pattern.test(lines[i]))
209
+ lines.splice(i, 1);
210
+ }
211
+ }
212
+ await writeFile(ENV_FILE, `${lines.join(`
213
+ `)}
214
+ `, { mode: 384 });
215
+ await chmod(ENV_FILE, 384);
216
+ }
217
+ function gitignored() {
218
+ const result = spawnSync("git", ["check-ignore", "-q", ENV_FILE]);
219
+ return result.status !== 1;
74
220
  }
75
- if (!response.ok) {
76
- fail(result.error ?? `the hub answered ${response.status}`);
221
+ var wait = (seconds) => new Promise((done) => setTimeout(done, seconds * 1000));
222
+ async function browserKey(hub) {
223
+ const start = await call(hub, "/api/auth/device/code", {
224
+ body: { client_id: CLIENT_ID }
225
+ });
226
+ if (!start.ok || typeof start.body.device_code !== "string") {
227
+ fail(start.status === 404 ? `${hub} has no browser sign-in: the hub needs updating` : `the hub refused to start a browser sign-in (${reason(start.body, start.status)})`);
228
+ }
229
+ const code = start.body;
230
+ console.log(`To sign in, open this link and approve the request:
231
+
232
+ ${code.verification_uri_complete ?? code.verification_uri}
233
+
234
+ Check that the page shows the code ${code.user_code}.
235
+ Waiting for approval…`);
236
+ let interval = code.interval ?? 5;
237
+ const deadline = Date.now() + code.expires_in * 1000;
238
+ let session;
239
+ while (!session) {
240
+ await wait(interval);
241
+ if (Date.now() > deadline) {
242
+ fail(`the sign-in link expired: run \`${LOGIN}\` again`);
243
+ }
244
+ const poll = await fetch(`${hub}/api/auth/device/token`, {
245
+ method: "POST",
246
+ headers: { "Content-Type": "application/json" },
247
+ body: JSON.stringify({
248
+ grant_type: DEVICE_GRANT,
249
+ device_code: code.device_code,
250
+ client_id: CLIENT_ID
251
+ })
252
+ }).catch(() => null);
253
+ if (!poll)
254
+ continue;
255
+ const body = await poll.json().catch(() => ({}));
256
+ if (poll.ok && typeof body.access_token === "string") {
257
+ session = body.access_token;
258
+ } else if (body.error === "authorization_pending") {} else if (body.error === "slow_down") {
259
+ interval += 5;
260
+ } else if (body.error === "access_denied") {
261
+ fail("the sign-in was denied in the browser");
262
+ } else if (body.error === "expired_token") {
263
+ fail(`the sign-in link expired: run \`${LOGIN}\` again`);
264
+ } else {
265
+ fail(`the browser sign-in failed (${reason(body, poll.status)}): run \`${LOGIN}\` again`);
266
+ }
267
+ }
268
+ const created = await call(hub, "/api/auth/api-key/create", {
269
+ token: session,
270
+ body: {
271
+ name: `hub-user on ${hostname()} (${basename(process.cwd())})`.slice(0, KEY_NAME_LIMIT)
272
+ }
273
+ });
274
+ const signOut = await call(hub, "/api/auth/sign-out", {
275
+ token: session,
276
+ body: {}
277
+ });
278
+ if (!signOut.ok) {
279
+ console.error(`hub-user: could not end the temporary browser sign-in session (${reason(signOut.body, signOut.status)}); it expires on its own`);
280
+ }
281
+ if (!created.ok || typeof created.body.key !== "string") {
282
+ fail(`the hub did not create an API key (${reason(created.body, created.status)})`);
283
+ }
284
+ return created.body.key;
285
+ }
286
+ async function login() {
287
+ if (values.browser && values["api-key-stdin"]) {
288
+ fail("pass --browser or --api-key-stdin, not both");
289
+ }
290
+ const interactive = Boolean(process.stdin.isTTY);
291
+ let hub = hubUrl(values.hub ?? process.env.HUB_URL);
292
+ if (!hub && interactive) {
293
+ hub = hubUrl(prompt("Hub URL (from your hub's admin):") ?? "");
294
+ }
295
+ if (!hub)
296
+ fail("pass --hub <url> or set HUB_URL");
297
+ let key;
298
+ if (values["api-key-stdin"]) {
299
+ key = (await Bun.stdin.text()).trim();
300
+ if (!key)
301
+ fail("no API key on stdin");
302
+ } else if (values.browser) {
303
+ key = await browserKey(hub);
304
+ } else if (interactive) {
305
+ key = await secret(`Paste an API key from ${hub}/account, or press Enter to sign in with your browser: `);
306
+ if (!key)
307
+ key = await browserKey(hub);
308
+ } else {
309
+ fail("pass --browser to sign in with your browser, or --api-key-stdin to read an API key");
310
+ }
311
+ if (!key.startsWith("uhk_")) {
312
+ fail(`that is not an API key (they start with uhk_): create one at ${hub}/account`);
313
+ }
314
+ const me = await account(hub, key);
315
+ if (!me) {
316
+ denied(`${hub} did not accept that API key: create a new one at ${hub}/account and run \`${LOGIN}\` again`);
317
+ }
318
+ await saveEnv({ HUB_URL: hub, HUB_API_KEY: key });
319
+ console.log(`${signedIn(hub, me)}
320
+ Saved HUB_URL and HUB_API_KEY to ${ENV_FILE}.`);
321
+ if (!gitignored()) {
322
+ console.error(`hub-user: ${ENV_FILE} is not gitignored: add it to .gitignore so the key is never committed`);
323
+ }
324
+ }
325
+ async function whoami() {
326
+ const { hub, key } = credentials(values.json);
327
+ const me = await account(hub, key);
328
+ if (!me) {
329
+ denied(`${hub} did not accept HUB_API_KEY (deleted, or for another hub): run \`${LOGIN}\``, values.json ? { status: 401 } : undefined);
330
+ }
331
+ console.log(values.json ? JSON.stringify({ hub, ...me }, null, 2) : `${signedIn(hub, me)}${me.name && me.name !== me.username ? `
332
+ Name: ${me.name}` : ""}`);
77
333
  }
78
- if (values.json) {
79
- console.log(JSON.stringify(result, null, 2));
80
- } else {
81
- console.log(`Registered "${name}" with key: ${result.key}
334
+ function forbidden(error = "This account may not change that app.") {
335
+ const why = error.split(/(?<=\.)\s+/).filter((sentence) => !/\badmin\b|another name/i.test(sentence)).join(" ").replace(/\.?$/, ".");
336
+ return `${why === "." ? "This account may not change that app." : why} Ask a hub admin, or pick another name.`;
337
+ }
338
+ async function register() {
339
+ const name = values.name?.trim();
340
+ for (const flag of ["prod", "dev"]) {
341
+ if (values[flag] !== undefined && !values[flag].trim()) {
342
+ fail(`--${flag} needs a URL: leave --${flag} out to keep the registered one`);
343
+ }
344
+ }
345
+ if (values.new && !values.prod && !values.dev)
346
+ fail("pass --prod <url>, --dev <url> or both when creating an app");
347
+ if (!name)
348
+ fail("pass --name <name>, the app's name in the hub");
349
+ if (values.listed && values.unlisted)
350
+ fail("pass --listed or --unlisted, not both");
351
+ const { hub, key } = credentials(values.json);
352
+ const { status, ok, body } = await call(hub, "/api/apps/register", {
353
+ token: key,
354
+ body: {
355
+ name,
356
+ ...values.prod !== undefined && { url: values.prod },
357
+ ...values.dev !== undefined && { devUrl: values.dev },
358
+ ...values.new && { createOnly: true },
359
+ ...values.listed && { listed: true },
360
+ ...values.unlisted && { listed: false }
361
+ }
362
+ });
363
+ const result = body;
364
+ if (result.taken) {
365
+ if (values.json)
366
+ console.log(JSON.stringify(result, null, 2));
367
+ else
368
+ console.error(`hub-user: ${result.error}`);
369
+ process.exit(3);
370
+ }
371
+ if (status === 401) {
372
+ denied(`${hub} did not accept HUB_API_KEY (deleted, or for another hub): run \`${LOGIN}\``, values.json ? { status: 401 } : undefined);
373
+ }
374
+ if (status === 403) {
375
+ denied(forbidden(result.error), values.json ? { status: 403, forbidden: true } : undefined);
376
+ }
377
+ if (!ok) {
378
+ fail(result.error ?? `the hub answered ${status}`);
379
+ }
380
+ const wanted = values.listed ? true : values.unlisted ? false : undefined;
381
+ if (wanted !== undefined && result.listed !== wanted) {
382
+ fail(`"${name}" was registered, but the hub did not apply --${wanted ? "listed" : "unlisted"}: it needs updating to support the app list`);
383
+ }
384
+ if (values.json) {
385
+ console.log(JSON.stringify(result, null, 2));
386
+ return;
387
+ }
388
+ const listing = typeof result.listed === "boolean" ? `
389
+ Listed in the badge app list: ${result.listed ? values.prod ? "yes" : "yes, once it has a production URL" : "no"}` : "";
390
+ console.log(`Registered "${name}" with key: ${result.key}${listing}
82
391
 
83
392
  Environment (Convex deployment, or the app's server):
84
393
  HUB_ISSUER=${result.env.HUB_ISSUER}
@@ -93,3 +402,9 @@ VITE_HUB_URL=${result.hubUrl}
93
402
 
94
403
  Then use the key in code: hubAuth({ app: "${result.key}" }) and <ConvexHubAuthProvider app="${result.key}" hubUrl={import.meta.env.VITE_HUB_URL} client={convex}>`);
95
404
  }
405
+ if (command === "login")
406
+ await login();
407
+ else if (command === "whoami")
408
+ await whoami();
409
+ else
410
+ await register();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@user-hub/auth",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Sign people in from User Hub badges: Convex auth config, React provider, server verification and the hub-user CLI.",
5
5
  "type": "module",
6
6
  "files": [
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: user-hub-auth
3
- description: Sign people into an app from their User Hub badge. Use when an app needs User Hub auth (workshop badges, QR sign-in, hubAuth, ConvexHubAuthProvider, HubAuthProvider, HubSignedIn, useHubUser, verifyHubToken, hub-user register), or when asked to connect an app to the hub. Never hand-roll login, passwords or token checks for these apps.
3
+ description: Sign people into an app from their User Hub badge. Use when an app needs User Hub auth (workshop badges, QR sign-in, hubAuth, ConvexHubAuthProvider, HubAuthProvider, HubSignedIn, useHubUser, verifyHubToken, hub-user login, hub-user register), or when asked to connect an app to the hub. Never hand-roll login, passwords or token checks for these apps.
4
4
  ---
5
5
 
6
6
  # User Hub auth
7
7
 
8
- People at a workshop scan a printed QR badge. The hub sends them to whichever app is live, signed in, with a token in the URL fragment (`#token=…`) that only that app accepts. This package turns that token into a signed-in person. The app keeps its own data, keyed on the person's hub id.
8
+ People at a workshop scan a printed QR badge. The hub sends them, signed in, to whichever app is live (or shows its app list so they pick one), with a token in the URL fragment (`#token=…`) that only that app accepts. The app gets the same token either way and needs nothing extra for the app list. This package turns that token into a signed-in person. The app keeps its own data, keyed on the person's hub id.
9
9
 
10
10
  ## Starting a new app
11
11
 
@@ -15,7 +15,7 @@ If there is no app yet, don't build one by hand: scaffold one with sign-in alrea
15
15
  bun create user-hub@latest my-app
16
16
  ```
17
17
 
18
- In a terminal it asks for the hub's URL and admin password and saves them to the new app's `.env.local`. As an agent you never handle the password, so either ask the human to run it, or run it only when `HUB_URL` and `HUB_ADMIN_PASSWORD` are already in the environment (for example `infisical run -- bun create user-hub@latest my-app`).
18
+ In a terminal it asks for the hub's URL, then signs the new app in (`hub-user login`: paste an API key, or approve a sign-in in the browser) and saves `HUB_URL` and `HUB_API_KEY` to the new app's `.env.local`. As an agent you never handle an API key, so either ask the human to run it, or run it without a terminal with the hub's URL (`bun create user-hub@latest my-app --hub-url https://hub.example.com`) and then sign the new app in from its folder as described in **Signing in** below.
19
19
 
20
20
  Then:
21
21
 
@@ -31,7 +31,7 @@ That covers every step below; read on only to add User Hub to an existing app or
31
31
 
32
32
  The hub has one address, for example `https://hub.example.com`. The human gives it to you; you need it in three places, all with the same value:
33
33
 
34
- - `HUB_URL` in the app's `.env` or `.env.local`: read by `hub-user register` (**Register the app**). The human puts it there with the admin password.
34
+ - `HUB_URL` in the app's `.env.local`: read by `hub-user register` (**Register the app**). `hub-user login` puts it there, next to the API key (**Signing in**).
35
35
  - `HUB_ISSUER` on the app's Convex deployment: `hub-user register` prints it for you (**Set the two values**).
36
36
  - `VITE_HUB_URL` in the app's frontend env, for production builds too: lets the dev server send you to the hub to sign in, and limits token refresh to that hub (**Wire it up**).
37
37
 
@@ -40,13 +40,23 @@ The hub has one address, for example `https://hub.example.com`. The human gives
40
40
  You need four things. Ask for them; never guess.
41
41
 
42
42
  1. **The app's name** in the hub, unique to this app (the same name updates the same app, and apps copied from a template often share a package name).
43
- 2. **Its local URL** (usually `http://localhost:3000`) and **its production URL** if it is deployed. Without a production URL the app can be developed but not scheduled, so badge scans never reach it; add it later by running register again with `--prod`.
44
- 3. **Where `HUB_URL` and `HUB_ADMIN_PASSWORD` are.** You do not have the password, and you must never ask for it in chat, write it into a file yourself, commit it or print it. Ask the human which of these applies:
45
- - **`.env` or `.env.local`** in the app's repo (must be gitignored): the human adds `HUB_URL=…` and `HUB_ADMIN_PASSWORD=…` themselves. `bunx hub-user` reads `.env` and `.env.local` automatically.
46
- - **Infisical** (or another secret manager): run the command through it, for example `infisical run -- bunx hub-user register …`.
47
- - **The human runs the command** and pastes you only the output, which contains no secrets.
43
+ 2. **Its local URL** (usually `http://localhost:3000`) and **its production URL** if it is deployed. Without a production URL the app can be developed but not scheduled or shown in the app list, so badge scans never reach it; add it later by running register again with `--prod`.
44
+ 3. **Whether the app's folder is signed in to the hub.** Check it yourself with `bunx -p @user-hub/auth hub-user whoami` (it prints the account, or exits with code 4 when not signed in). If it is not, see **Signing in**. If the human keeps `HUB_URL` and `HUB_API_KEY` in a secret manager (Infisical, say), run every `hub-user` command through it instead (`infisical run -- bunx -p @user-hub/auth hub-user register …`).
48
45
  4. **Which Convex deployments** the app uses (dev, prod), so the values go on each.
49
46
 
47
+ ## Signing in
48
+
49
+ `hub-user` acts as a hub account through an API key, `HUB_API_KEY`, saved in the app folder's `.env.local` next to `HUB_URL`. You never ask for an API key or password in chat, never write one into a file yourself, never commit one and never print `.env.local`. Always run the CLI as `bunx -p @user-hub/auth hub-user …`: it uses the app's installed `@user-hub/auth`, or fetches that package when the app does not have it yet. Never run a bare `bunx hub-user`: in a folder without the package it fetches an npm package called `hub-user`, which is not ours.
50
+
51
+ Sign the folder in one of two ways, from the app's folder:
52
+
53
+ - **The human runs** `bunx -p @user-hub/auth hub-user login --hub https://<hub url>` in a terminal. It asks them to paste an API key from `<hub>/account` (it shows as stars) or press Enter to sign in with the browser.
54
+ - **You run** `bunx -p @user-hub/auth hub-user login --hub https://<hub url> --browser`. It prints a link and a code, then waits (up to 10 minutes) until the request is approved: run it in the background or with a long timeout, read the link from its output and give it to the human to open, sign in to the hub and approve. Never open or approve the link yourself. When it is approved, the command creates an API key for itself, saves it and prints `Signed in to <hub> as <username> (<role>)`.
55
+
56
+ Hubs with accounts need `@user-hub/auth` 0.3 or newer. If the app already has an older one installed (its `hub-user` has no `login`), run `bun add @user-hub/auth@latest` first.
57
+
58
+ The hub's URL comes from the human (or `HUB_URL` already in `.env.local`, which `--hub` can then be left out for). If login fails because the request was denied or expired, run it again or ask the human. An older `.env.local` with `HUB_ADMIN_PASSWORD` is no longer used: ask the human to delete that line.
59
+
50
60
  ## Steps
51
61
 
52
62
  1. **Install:**
@@ -55,15 +65,17 @@ You need four things. Ask for them; never guess.
55
65
  bun add @user-hub/auth
56
66
  ```
57
67
 
58
- 2. **Register the app** from the app's repo root, with `HUB_URL` and the password supplied the way the human chose in question 3 above:
68
+ 2. **Register the app** from the app's repo root, once the folder is signed in (question 3 above):
59
69
 
60
70
  ```sh
61
- bunx hub-user register --name "<app name>" --new --prod https://app.example.com --dev http://localhost:3000
71
+ bunx -p @user-hub/auth hub-user register --name "<app name>" --new --prod https://app.example.com --dev http://localhost:3000
62
72
  ```
63
73
 
64
74
  `--new` makes sure you never take over another app: if the name is already taken, nothing changes and it exits with code 3 and "already exists". Then ask the human for another name and run it again. Drop `--new` only when updating this app's own registration later.
65
75
 
66
- Leave out `--prod` if the app is not deployed yet. Running it again with the same `--name` updates the URLs; a URL left out keeps the registered one. If it fails with "set HUB_URL", "set HUB_ADMIN_PASSWORD" or a wrong password, stop and ask the human; do not work around it.
76
+ Leave out `--prod` if the app is not deployed yet. Running it again with the same `--name` updates the URLs; a URL left out keeps the registered one, and with no URL flags it keeps the registered URLs and just prints the values. Use the exact name the app has in the hub: the hub finds the app by the key made from the name and saves the name as you typed it. If it exits with code 4, read the message: "not signed in" or "did not accept HUB_API_KEY" means sign in again (**Signing in**); "Ask a hub admin, or pick another name" means the app belongs to another account (apps registered before the hub had accounts belong to none, so only a hub admin can change them): ask the human for another name, or to have a hub admin change it. Do not work around either.
77
+
78
+ New apps are **listed** in the badge app list by default. When the hub admin sets **Badges go to** to the app list, a scan shows the listed apps that have a production URL and the person picks one; a listed app without a production URL does not appear. Pass `--unlisted` to keep one out of it (it can still be scheduled or forced live), or `--listed` to show it again; in a starter app whose `scripts/setup.ts` mentions `--unlisted`, pass it to `bun run setup`. Pass neither when updating and the hub's current setting stays; the output shows it ("Listed in the badge app list: yes", or "yes, once it has a production URL" without `--prod`). If it says the hub "did not apply" the flag, the hub is too old for the app list: tell the human; the rest of the registration went through.
67
79
 
68
80
  It prints the app **key** (made from the name), `HUB_ISSUER` and `HUB_JWKS` (server side) and `VITE_HUB_URL` (frontend). Add `--json` to parse them.
69
81
 
@@ -110,7 +122,7 @@ You need four things. Ask for them; never guess.
110
122
 
111
123
  ## Your dev server
112
124
 
113
- Run the app as usual (`bun run dev`) on the `--dev` URL you registered. Opening it with no token sends the browser to the hub (admin password once per browser), where you pick who to be; the hub sends you back signed in as them. You stay signed in across reloads and restarts until that person's expiration in the hub (4 hours unless set otherwise), then the same thing happens again.
125
+ Run the app as usual (`bun run dev`) on the `--dev` URL you registered. Opening it with no token sends the browser to the hub (the human signs in with their hub account once per browser), where you pick who to be; the hub sends you back signed in as them. You stay signed in across reloads and restarts until that person's expiration in the hub (4 hours unless set otherwise), then the same thing happens again.
114
126
 
115
127
  - To switch person: open `<hub>/open/<key>` and pick someone else.
116
128
  - If the dev server runs on another port, run `hub-user register` again with the same `--name` and the new `--dev` URL: the hub only sends tokens back to registered URLs.
@@ -121,13 +133,24 @@ Run the app as usual (`bun run dev`) on the `--dev` URL you registered. Opening
121
133
  Badge scans only reach an app once the hub knows its production URL. When the human asks to set up the production URL (or says the app is deployed), ask for the deployed URL (never guess), then:
122
134
 
123
135
  - **Starter apps** (they have `scripts/setup.ts`): `bun run setup --prod https://<deployed url>`. It updates the app's own registration and sets `HUB_ISSUER` and `HUB_JWKS` on the production Convex deployment too.
124
- - **Other apps:** `bunx hub-user register --name "<the app's name in the hub>" --prod https://<deployed url>`, without `--new` (this updates the app's own registration; the name is `HUB_APP_NAME` in `.env.local`, or ask the human). Then set the two printed values on production: `bunx convex env set --prod HUB_ISSUER '…'` and `bunx convex env set --prod HUB_JWKS '…'`.
136
+ - **Other apps:** `bunx -p @user-hub/auth hub-user register --name "<the app's name in the hub>" --prod https://<deployed url>`, without `--new` (this updates the app's own registration; the name is `HUB_APP_NAME` in `.env.local`, or ask the human). Then set the two printed values on production: `bunx convex env set --prod HUB_ISSUER '…'` and `bunx convex env set --prod HUB_JWKS '…'`.
125
137
 
126
138
  Then:
127
139
 
128
140
  1. `bunx convex deploy`.
129
141
  2. On the host, set `VITE_CONVEX_URL` (the production deployment's URL) and `VITE_HUB_URL` (the hub's URL).
130
- 3. Tell the human the app is ready for the hub admin to schedule (or force live) under **Schedule**; until then badge scans go to whichever app is live.
142
+ 3. Tell the human the app is ready for the hub admin to schedule (or force live) under **Schedule**; until then badge scans go to whichever app is live. While **Badges go to** shows the app list, a listed app appears there as soon as it has its production URL.
143
+
144
+ ## Hub moved to a new URL
145
+
146
+ When the human says the hub's URL changed, hub ids stay the same, so data keyed on the id carries over. Until the app is updated it rejects every sign-in.
147
+
148
+ - **Starter apps** (they have `scripts/setup.ts`): sign the folder in to the new hub with `hub-user login --hub <new url>` (**Signing in**), then run `bun run setup`. It updates the app's own registration and sets `HUB_ISSUER`, `HUB_JWKS` and `VITE_HUB_URL` again (on the production Convex deployment too, once the app has a production URL). Then redeploy with `just push`: Vite bakes `VITE_HUB_URL` in at build time.
149
+ - **Other apps:**
150
+ 1. Sign the app's folder in to the new hub with `hub-user login --hub <new url>` (**Signing in**); it replaces `HUB_URL` and `HUB_API_KEY` in `.env.local`. If the human keeps them in a secret manager, ask them to change them there.
151
+ 2. Run `bunx -p @user-hub/auth hub-user register --name "<the app's name in the hub>"` without `--new` or any URL flags: it keeps the registered URLs and prints the new values. Use the exact name from the hub's **Apps** page: the CLI finds the app by the key made from the name. The printed key must equal the `app` key already in the code; if it differs, or the hub says to give a URL (no app has that name), stop and ask the human: you found another app, or none.
152
+ 3. Set `HUB_ISSUER` and `HUB_JWKS` on every Convex deployment the app uses (`bunx convex env set …`, and again with `--prod`). Convex re-reads `auth.config.ts` with the new values straight away; no deploy is needed.
153
+ 4. Set `VITE_HUB_URL` to the new URL in the frontend env and on the host, then rebuild and redeploy the frontend: Vite bakes it in at build time.
131
154
 
132
155
  ## Sign out
133
156
 
@@ -179,8 +202,9 @@ People are either `"member"` or `"facilitator"`, set in the hub. To give facilit
179
202
 
180
203
  ## Rules
181
204
 
182
- - Key all data on the hub id (`identity.subject` / `useHubUser().id`). Never on the name, and never on the badge token, which the app never sees.
205
+ - Key all data on the hub id (`identity.subject` / `useHubUser().id`). Never on the name, never on the badge token, which the app never sees, and never on Convex's `identity.tokenIdentifier`, which includes the hub's URL and changes if the hub moves.
183
206
  - Check access on the server: `requireFacilitator(ctx)` / `requireHubUser(ctx)` in Convex, or `verifyHubToken` elsewhere. `useHubUser()` is for display only.
184
207
  - The provider refreshes tokens with the hub (`<hub>/api/token/refresh`) while the app is open; the hub decides how long a session lasts and when it ends, and the provider then shows the signed-out screen. Do not refresh, store or extend tokens yourself. Read `useHubToken()` for each request, since it changes. If the app sets a Content Security Policy, allow the hub in `connect-src`.
185
208
  - Do not add other sign-in methods, sessions or token handling. If something is missing, change this package instead.
209
+ - `@user-hub/auth` 0.3 replaced the hub's admin password with accounts: `hub-user` no longer reads `HUB_ADMIN_PASSWORD` and needs `hub-user login` once per app folder. A `^0.2` range never installs 0.3: `bun add @user-hub/auth@latest`; no app code changes.
186
210
  - An existing app on `@user-hub/auth` 0.1 does not refresh tokens, and a `^0.1` range never installs 0.2: update it with `bun add @user-hub/auth@latest`. No code changes are needed.