@user-hub/auth 0.4.2 → 0.6.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.
@@ -0,0 +1,87 @@
1
+ # Connect an existing app
2
+
3
+ Five steps, in order. The `user-hub …` commands are explained in the **user-hub-cli** skill.
4
+
5
+ ## 1. Install
6
+
7
+ ```sh
8
+ bun add @user-hub/auth
9
+ bun add -d user-hub
10
+ ```
11
+
12
+ ## 2. Register the app
13
+
14
+ From the app's folder, once it is signed in (`bunx user-hub whoami`; if it exits with code 4, sign in as the user-hub-cli skill describes):
15
+
16
+ ```sh
17
+ bunx user-hub apps register --event <slug> --name "<app name>" --new --dev http://localhost:3000 [--prod https://app.example.com]
18
+ ```
19
+
20
+ - `--new` never takes over another app: a taken name exits with code 3 and changes nothing. Ask the human for another name. Drop `--new` only when updating this app's own registration later.
21
+ - Leave out `--prod` until the app is deployed.
22
+ - It prints the app **key** (`<event slug>-<name>`), `HUB_ISSUER`, `HUB_JWKS` and `VITE_HUB_URL`. With `--json`: `key`, `env`, `hubUrl`.
23
+
24
+ ## 3. Set the values
25
+
26
+ - Convex, on every deployment the app uses: `bunx convex env set HUB_ISSUER '…'` and `bunx convex env set HUB_JWKS '…'` (add `--prod` for production).
27
+ - Other servers: the same two names in their environment.
28
+ - Frontend env: `VITE_HUB_URL` (the hub's URL), for production builds too.
29
+
30
+ ## 4. Wire it up
31
+
32
+ `convex/auth.config.ts`:
33
+
34
+ ```ts
35
+ import type { AuthConfig } from "convex/server";
36
+ import { hubAuth } from "@user-hub/auth/convex";
37
+
38
+ export default { providers: [hubAuth({ app: "<key>" })] } satisfies AuthConfig;
39
+ ```
40
+
41
+ The provider replaces `ConvexProvider` (same `ConvexReactClient`), **inside the root document's `<body>`**: in TanStack Start the root route's shell component (`src/routes/__root.tsx`), in a Vite SPA around `<App />`, in Next.js inside `<body>` of the root layout.
42
+
43
+ ```tsx
44
+ import { ConvexHubAuthProvider, HubSignedIn } from "@user-hub/auth/convex-react";
45
+
46
+ <body>
47
+ <ConvexHubAuthProvider client={convex} app="<key>" hubUrl={import.meta.env.VITE_HUB_URL}>
48
+ <HubSignedIn>{children}</HubSignedIn>
49
+ </ConvexHubAuthProvider>
50
+ <Scripts />
51
+ </body>
52
+ ```
53
+
54
+ `<HubSignedIn>` shows its children only to a signed-in person and "Scan your badge to sign in" otherwise; style that with `signedOut={…}` and the first render with `loading={…}`. Anything outside it (a public landing page) shows to everyone.
55
+
56
+ **Without Convex:** `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth/react`, same place, same props minus `client`.
57
+
58
+ **Render signed in on the server (TanStack Start).** Without this, every page load or refresh shows `loading` until the page hydrates. Read the token in the root route and pass it as `initialToken`:
59
+
60
+ ```tsx
61
+ import { createServerFn } from "@tanstack/react-start";
62
+ import { getHubToken } from "@user-hub/auth/start";
63
+
64
+ const fetchHubToken = createServerFn({ method: "GET" }).handler(() =>
65
+ getHubToken({ app: "<key>", hubUrl: import.meta.env.VITE_HUB_URL }),
66
+ );
67
+
68
+ // In createRootRoute / createRootRouteWithContext (server only: the browser already has the token):
69
+ beforeLoad: async () => ({ hubToken: import.meta.env.SSR ? await fetchHubToken() : null }),
70
+
71
+ // In the shell component:
72
+ const { hubToken } = Route.useRouteContext();
73
+ <ConvexHubAuthProvider client={convex} app="<key>" hubUrl={import.meta.env.VITE_HUB_URL} initialToken={hubToken}>
74
+ ```
75
+
76
+ With `ConvexQueryClient` (Convex through TanStack Query), also call `context.convexQueryClient.serverHttpClient?.setAuth(hubToken)` in `beforeLoad` when there is a token, so server-side queries run as the person. Never read or set the `user-hub-token.<key>` cookie yourself: the provider writes it and `getHubToken` reads it.
77
+
78
+ ## 5. Use the person
79
+
80
+ | Where | How |
81
+ |---|---|
82
+ | Components | `const me = useHubUser()` → `{ id, name, team, role }` or `null` |
83
+ | Convex functions | `const me = await requireHubUser(ctx)` (throws when signed out); `getHubUser(ctx)` when signing in is optional |
84
+ | Other servers | Send `useHubToken()` as `Authorization: Bearer <token>`; check it with `await verifyHubToken(request, { app: "<key>" })` from `@user-hub/auth/server` |
85
+ | Sign out | `const signOut = useHubSignOut()` from the provider's entry point. It forgets this app's token only |
86
+
87
+ If the app sets a Content Security Policy, allow the hub in `connect-src`: the provider calls `<hub>/api/token/refresh`.
@@ -0,0 +1,30 @@
1
+ # Local development, production and a moved hub
2
+
3
+ ## Your dev server
4
+
5
+ Run the app on the development URL registered with the hub. With no token, it sends the browser to the hub, where the human (signed in to the hub once per browser) picks who to be, and comes back signed in. That lasts across reloads until the person's session in the hub ends (4 hours unless set otherwise).
6
+
7
+ - **Switch person:** open `<hub>/open/<key>`.
8
+ - **Another port:** the hub only sends tokens to registered URLs. Starter apps: `bun run setup --dev http://localhost:<port>` and change the port in the `dev` script too. Others: `bunx user-hub apps register` again with the same event, `--name` and the new `--dev`.
9
+ - **Test people:** `bunx user-hub people create --name "Test Person" --team Test` (user-hub-cli skill).
10
+ - This redirect only happens on local addresses (localhost, 127.x, 10.x, 172.16-31.x, 192.168.x, *.local). In production a person without a token sees "Scan your badge to sign in".
11
+
12
+ ## Production URL
13
+
14
+ Badge scans reach the app only once the hub knows its production URL. Ask the human for the deployed URL (never guess), then:
15
+
16
+ - **Starter apps:** `bun run setup --prod https://<deployed url>`. It also sets `HUB_ISSUER` and `HUB_JWKS` on the production Convex deployment.
17
+ - **Other apps:** `bunx user-hub apps register --event <slug> --name "<the app's name>" --prod https://<deployed url>` without `--new`, then `bunx convex env set --prod HUB_ISSUER '…'` and `… HUB_JWKS '…'`.
18
+
19
+ Then `bunx convex deploy`, set `VITE_CONVEX_URL` and `VITE_HUB_URL` on the host, and tell the human the app can be scheduled or forced live under **Schedule** of its event. While the event's badges go to the app list, a listed app with a production URL appears there straight away.
20
+
21
+ ## The hub moved to a new URL
22
+
23
+ Hub ids stay the same, so data keyed on the id carries over, but the app rejects every sign-in until it is updated.
24
+
25
+ 1. Sign the folder in to the new hub: `bunx user-hub login --hub <new url>`.
26
+ 2. **Starter apps:** `bun run setup --hub-moved` (it updates the same app on the new hub; add `--event <slug>` if the new hub has no event with the saved slug), then redeploy with `just push`: `VITE_HUB_URL` is built into the frontend.
27
+ 3. **Other apps:**
28
+ - `bunx user-hub apps register --event <slug> --name "<the app's name>"` with no `--new` and no URLs: it keeps the registered URLs and prints the new values. The printed key must equal the `app` key in the code; if it differs, or the hub asks for a URL, stop and ask the human.
29
+ - Set `HUB_ISSUER` and `HUB_JWKS` on every Convex deployment (with and without `--prod`). No deploy needed for that.
30
+ - Set `VITE_HUB_URL` to the new URL, then rebuild and redeploy the frontend.
@@ -0,0 +1,39 @@
1
+ # Facilitator pages
2
+
3
+ People are `"member"` or `"facilitator"`, set in the hub. Protect on the server first, then hide in the UI.
4
+
5
+ ## Server: the real protection
6
+
7
+ ```ts
8
+ import { requireFacilitator, requireHubUser } from "@user-hub/auth/convex";
9
+
10
+ export const closeVoting = mutation({
11
+ args: {},
12
+ handler: async (ctx) => {
13
+ await requireFacilitator(ctx); // throws for members and for nobody signed in
14
+ // …
15
+ },
16
+ });
17
+
18
+ export const myVotes = query({
19
+ args: {},
20
+ handler: async (ctx) => {
21
+ const me = await requireHubUser(ctx); // throws when signed out
22
+ return await ctx.db
23
+ .query("votes")
24
+ .withIndex("by_person", (q) => q.eq("personId", me.id))
25
+ .take(50);
26
+ },
27
+ });
28
+ ```
29
+
30
+ Not Convex: check `(await verifyHubToken(request, { app })).role`.
31
+
32
+ ## UI: only for a clean screen
33
+
34
+ ```tsx
35
+ const me = useHubUser();
36
+ if (me?.role !== "facilitator") return <p>This page is for facilitators.</p>;
37
+ ```
38
+
39
+ Members can still call the functions behind a hidden page, which is why the server check comes first.
package/dist/cli.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env bun
2
- export {};
package/dist/cli.js DELETED
@@ -1,521 +0,0 @@
1
- #!/usr/bin/env bun
2
-
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";
8
- import { parseArgs } from "node:util";
9
- var USAGE = `Usage:
10
- hub-user login [--hub <url>] [--browser | --api-key-stdin]
11
- hub-user whoami [--hub <url>] [--json]
12
- hub-user events [--hub <url>] [--json]
13
- hub-user events create --name <name> [--time-zone <zone>] [--hub <url>] [--json]
14
- hub-user register --event <slug> --name <name> [--prod <url>] [--dev <url>] [--listed|--unlisted] [--new] [--hub <url>] [--json]
15
-
16
- login Signs this folder in to the hub: saves HUB_URL and HUB_API_KEY to
17
- ./.env.local (mode 600, other lines kept; keep it out of git).
18
- --hub The hub's URL (default: HUB_URL; asked in a terminal)
19
- --browser Sign in with your browser: prints a link to open and approve
20
- (it never opens a browser itself; works without a terminal)
21
- --api-key-stdin Read an API key from stdin (create one at <hub>/account)
22
- In a terminal without either flag, it asks you to paste an API key or press
23
- Enter to sign in with your browser.
24
-
25
- whoami Shows the hub account HUB_API_KEY belongs to.
26
-
27
- events Lists the hub's events (workshops), newest first, with the slug
28
- that register takes.
29
- create Creates an event:
30
- --name The event's name; its slug comes from it (required)
31
- --time-zone An IANA time zone such as Europe/Berlin (default: this
32
- machine's)
33
-
34
- register Registers the app in an event, or updates it when the name exists
35
- there.
36
- --event The event's slug (default: HUB_EVENT); see hub-user events
37
- --name The app's name in the hub; its key comes from the event and the
38
- name (required)
39
- --prod Where badge scans send people. Leave it out until the app is
40
- deployed: it can be developed, but not scheduled or shown in
41
- the badge app list.
42
- --dev Where developers open the app as a person, e.g. http://localhost:3000
43
- --listed Show the app in the hub's badge app list once it has a
44
- production URL (default for new apps)
45
- --unlisted Keep the app out of the hub's badge app list
46
- --new Only create a new app: if the name is taken, change nothing and
47
- exit with code 3 so you can pick another name
48
- --hub The hub's URL (default: HUB_URL)
49
- --json Print JSON instead of text
50
-
51
- At least one of --prod and --dev is needed with --new or when first registering.
52
- A URL left out on a later run keeps the registered one; both may be omitted on
53
- an update. Without --listed or --unlisted, re-registering keeps the current
54
- listing setting. Running it again with the same event and name updates that
55
- app.
56
-
57
- whoami, events and register need HUB_URL and HUB_API_KEY in the environment
58
- (.env and .env.local are read automatically); hub-user login puts them there.
59
-
60
- Exit codes: 0 done, 1 error, 3 name taken (register --new, an app of another
61
- event, events create), 4 not signed in, 5 unknown event (register).`;
62
- var ENV_FILE = ".env.local";
63
- var CLIENT_ID = "hub-user";
64
- var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
65
- var CLI = "bunx -p @user-hub/auth hub-user";
66
- var LOGIN = `${CLI} login`;
67
- var KEY_NAME_LIMIT = 128;
68
- function fail(message) {
69
- console.error(`hub-user: ${message}`);
70
- process.exit(1);
71
- }
72
- function denied(message, json) {
73
- console.error(`hub-user: ${message}`);
74
- if (json)
75
- console.log(JSON.stringify({ error: message, ...json }, null, 2));
76
- process.exit(4);
77
- }
78
- function parse() {
79
- try {
80
- return parseArgs({
81
- args: process.argv.slice(2),
82
- allowPositionals: true,
83
- options: {
84
- prod: { type: "string" },
85
- dev: { type: "string" },
86
- name: { type: "string" },
87
- event: { type: "string" },
88
- "time-zone": { type: "string" },
89
- hub: { type: "string" },
90
- json: { type: "boolean", default: false },
91
- new: { type: "boolean", default: false },
92
- listed: { type: "boolean", default: false },
93
- unlisted: { type: "boolean", default: false },
94
- browser: { type: "boolean", default: false },
95
- "api-key-stdin": { type: "boolean", default: false },
96
- help: { type: "boolean", short: "h", default: false }
97
- }
98
- });
99
- } catch (error) {
100
- fail(`${error.message}
101
-
102
- ${USAGE}`);
103
- }
104
- }
105
- var { values, positionals } = parse();
106
- var command = positionals[0];
107
- var subcommand = positionals[1];
108
- if (values.help || !command || !["login", "whoami", "events", "register"].includes(command) || command === "events" && subcommand !== undefined && subcommand !== "create") {
109
- console.log(USAGE);
110
- process.exit(values.help ? 0 : 1);
111
- }
112
- var extra = positionals.slice(command === "events" && subcommand === "create" ? 2 : 1);
113
- if (extra.length > 0) {
114
- fail(`unexpected argument${extra.length > 1 ? "s" : ""} ${extra.map((word) => `"${word}"`).join(" ")}: quote a value with spaces, like --name "Summer Camp"`);
115
- }
116
- function hubFlag() {
117
- const hub = values.hub?.trim().replace(/\/+$/, "");
118
- if (!hub)
119
- return "";
120
- return ` --hub ${/^[\w@%+=:,./-]+$/.test(hub) ? hub : `'${hub.replaceAll("'", "'\\''")}'`}`;
121
- }
122
- var oldPassword = Boolean(process.env.HUB_ADMIN_PASSWORD && !process.env.HUB_API_KEY?.trim());
123
- if (oldPassword && command === "login") {
124
- console.error("hub-user: HUB_ADMIN_PASSWORD is no longer used; delete it from your env files.");
125
- }
126
- var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
127
- function hubUrl(value) {
128
- const url = value?.trim().replace(/\/+$/, "");
129
- if (!url) {
130
- return;
131
- }
132
- const parsed = URL.parse(url);
133
- const allowed = parsed?.protocol === "https:" || parsed?.protocol === "http:" && LOOPBACK.has(parsed.hostname);
134
- if (!allowed) {
135
- fail(`the hub URL must start with https:// (http:// only for localhost) (got "${url}")`);
136
- }
137
- return url;
138
- }
139
- function reason(body, status) {
140
- for (const value of [body.message, body.error_description, body.error]) {
141
- if (typeof value === "string")
142
- return value;
143
- }
144
- return String(status);
145
- }
146
- async function call(hub, path, init = {}) {
147
- const response = await fetch(`${hub}${path}`, {
148
- method: init.body === undefined ? "GET" : "POST",
149
- headers: {
150
- ...init.token && { Authorization: `Bearer ${init.token}` },
151
- ...init.body !== undefined && { "Content-Type": "application/json" }
152
- },
153
- ...init.body !== undefined && { body: JSON.stringify(init.body) }
154
- }).catch((error) => fail(`could not reach ${hub}: ${error.message}`));
155
- const body = await response.json().catch(() => ({}));
156
- return { status: response.status, ok: response.ok, body };
157
- }
158
- async function account(hub, key) {
159
- const { status, ok, body } = await call(hub, "/api/account", { token: key });
160
- if (status === 401)
161
- return null;
162
- if (status === 404) {
163
- fail(`${hub} has no accounts: the hub needs updating`);
164
- }
165
- if (!ok || typeof body.username !== "string") {
166
- fail(typeof body.error === "string" ? body.error : `the hub answered ${status}`);
167
- }
168
- return body;
169
- }
170
- function signedIn(hub, me) {
171
- return `Signed in to ${hub} as ${me.username} (${me.role})`;
172
- }
173
- function credentials(json) {
174
- const hub = hubUrl(values.hub ?? process.env.HUB_URL);
175
- const key = process.env.HUB_API_KEY?.trim();
176
- if (!hub || !key) {
177
- 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);
178
- }
179
- return { hub, key };
180
- }
181
- function secret(question) {
182
- process.stdout.write(question);
183
- process.stdin.setRawMode(true);
184
- process.stdin.resume();
185
- process.stdin.setEncoding("utf8");
186
- return new Promise((done) => {
187
- let value = "";
188
- const finish = () => {
189
- process.stdin.off("data", onData);
190
- process.stdin.setRawMode(false);
191
- process.stdin.pause();
192
- process.stdout.write(`
193
- `);
194
- done(value.trim());
195
- };
196
- const onData = (chunk) => {
197
- for (const char of chunk) {
198
- if (char === "\r" || char === `
199
- `)
200
- return finish();
201
- if (char === "\x03") {
202
- process.stdout.write(`
203
- `);
204
- process.exit(130);
205
- }
206
- if (char === "" || char === "\b") {
207
- if (value) {
208
- value = value.slice(0, -1);
209
- process.stdout.write("\b \b");
210
- }
211
- } else if (char >= " ") {
212
- value += char;
213
- process.stdout.write("*");
214
- }
215
- }
216
- };
217
- process.stdin.on("data", onData);
218
- });
219
- }
220
- async function saveEnv(entries) {
221
- const file = Bun.file(ENV_FILE);
222
- const exists = await file.exists();
223
- if (exists)
224
- await chmod(ENV_FILE, 384);
225
- const lines = exists ? (await file.text()).split(`
226
- `) : [];
227
- if (lines.at(-1) === "")
228
- lines.pop();
229
- for (const [key, value] of Object.entries(entries)) {
230
- const pattern = new RegExp(`^\\s*(export\\s+)?${key}\\s*=`);
231
- const at = lines.findIndex((line) => pattern.test(line));
232
- const line = `${key}=${value}`;
233
- if (at === -1) {
234
- lines.push(line);
235
- continue;
236
- }
237
- lines[at] = line;
238
- for (let i = lines.length - 1;i > at; i--) {
239
- if (pattern.test(lines[i]))
240
- lines.splice(i, 1);
241
- }
242
- }
243
- await writeFile(ENV_FILE, `${lines.join(`
244
- `)}
245
- `, { mode: 384 });
246
- await chmod(ENV_FILE, 384);
247
- }
248
- function gitignored() {
249
- const result = spawnSync("git", ["check-ignore", "-q", ENV_FILE]);
250
- return result.status !== 1;
251
- }
252
- var wait = (seconds) => new Promise((done) => setTimeout(done, seconds * 1000));
253
- async function browserKey(hub) {
254
- const start = await call(hub, "/api/auth/device/code", {
255
- body: { client_id: CLIENT_ID }
256
- });
257
- if (!start.ok || typeof start.body.device_code !== "string") {
258
- 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)})`);
259
- }
260
- const code = start.body;
261
- console.log(`To sign in, open this link and approve the request:
262
-
263
- ${code.verification_uri_complete ?? code.verification_uri}
264
-
265
- Check that the page shows the code ${code.user_code}.
266
- Waiting for approval…`);
267
- let interval = code.interval ?? 5;
268
- const deadline = Date.now() + code.expires_in * 1000;
269
- let session;
270
- while (!session) {
271
- await wait(interval);
272
- if (Date.now() > deadline) {
273
- fail(`the sign-in link expired: run \`${LOGIN}\` again`);
274
- }
275
- const poll = await fetch(`${hub}/api/auth/device/token`, {
276
- method: "POST",
277
- headers: { "Content-Type": "application/json" },
278
- body: JSON.stringify({
279
- grant_type: DEVICE_GRANT,
280
- device_code: code.device_code,
281
- client_id: CLIENT_ID
282
- })
283
- }).catch(() => null);
284
- if (!poll)
285
- continue;
286
- const body = await poll.json().catch(() => ({}));
287
- if (poll.ok && typeof body.access_token === "string") {
288
- session = body.access_token;
289
- } else if (body.error === "authorization_pending") {} else if (body.error === "slow_down") {
290
- interval += 5;
291
- } else if (body.error === "access_denied") {
292
- fail("the sign-in was denied in the browser");
293
- } else if (body.error === "expired_token") {
294
- fail(`the sign-in link expired: run \`${LOGIN}\` again`);
295
- } else {
296
- fail(`the browser sign-in failed (${reason(body, poll.status)}): run \`${LOGIN}\` again`);
297
- }
298
- }
299
- const created = await call(hub, "/api/auth/api-key/create", {
300
- token: session,
301
- body: {
302
- name: `hub-user on ${hostname()} (${basename(process.cwd())})`.slice(0, KEY_NAME_LIMIT)
303
- }
304
- });
305
- const signOut = await call(hub, "/api/auth/sign-out", {
306
- token: session,
307
- body: {}
308
- });
309
- if (!signOut.ok) {
310
- console.error(`hub-user: could not end the temporary browser sign-in session (${reason(signOut.body, signOut.status)}); it expires on its own`);
311
- }
312
- if (!created.ok || typeof created.body.key !== "string") {
313
- fail(`the hub did not create an API key (${reason(created.body, created.status)})`);
314
- }
315
- return created.body.key;
316
- }
317
- async function login() {
318
- if (values.browser && values["api-key-stdin"]) {
319
- fail("pass --browser or --api-key-stdin, not both");
320
- }
321
- const interactive = Boolean(process.stdin.isTTY);
322
- let hub = hubUrl(values.hub ?? process.env.HUB_URL);
323
- if (!hub && interactive) {
324
- hub = hubUrl(prompt("Hub URL (from your hub's admin):") ?? "");
325
- }
326
- if (!hub)
327
- fail("pass --hub <url> or set HUB_URL");
328
- let key;
329
- if (values["api-key-stdin"]) {
330
- key = (await Bun.stdin.text()).trim();
331
- if (!key)
332
- fail("no API key on stdin");
333
- } else if (values.browser) {
334
- key = await browserKey(hub);
335
- } else if (interactive) {
336
- key = await secret(`Paste an API key from ${hub}/account, or press Enter to sign in with your browser: `);
337
- if (!key)
338
- key = await browserKey(hub);
339
- } else {
340
- fail("pass --browser to sign in with your browser, or --api-key-stdin to read an API key");
341
- }
342
- if (!key.startsWith("uhk_")) {
343
- fail(`that is not an API key (they start with uhk_): create one at ${hub}/account`);
344
- }
345
- const me = await account(hub, key);
346
- if (!me) {
347
- denied(`${hub} did not accept that API key: create a new one at ${hub}/account and run \`${LOGIN}\` again`);
348
- }
349
- await saveEnv({ HUB_URL: hub, HUB_API_KEY: key });
350
- console.log(`${signedIn(hub, me)}
351
- Saved HUB_URL and HUB_API_KEY to ${ENV_FILE}.`);
352
- if (!gitignored()) {
353
- console.error(`hub-user: ${ENV_FILE} is not gitignored: add it to .gitignore so the key is never committed`);
354
- }
355
- }
356
- async function whoami() {
357
- const { hub, key } = credentials(values.json);
358
- const me = await account(hub, key);
359
- if (!me)
360
- refused(hub);
361
- console.log(values.json ? JSON.stringify({ hub, ...me }, null, 2) : `${signedIn(hub, me)}${me.name && me.name !== me.username ? `
362
- Name: ${me.name}` : ""}`);
363
- }
364
- function refused(hub) {
365
- denied(`${hub} did not accept HUB_API_KEY (deleted, or for another hub): run \`${LOGIN}\``, values.json ? { status: 401 } : undefined);
366
- }
367
- function noEvents(hub) {
368
- fail(`${hub} has no events: the hub needs updating`);
369
- }
370
- async function listEvents() {
371
- const { hub, key } = credentials(values.json);
372
- const { status, ok, body } = await call(hub, "/api/events", { token: key });
373
- if (status === 401)
374
- refused(hub);
375
- if (status === 404)
376
- noEvents(hub);
377
- if (!ok || !Array.isArray(body.events)) {
378
- fail(typeof body.error === "string" ? body.error : `the hub answered ${status}`);
379
- }
380
- const events = body.events;
381
- if (values.json) {
382
- console.log(JSON.stringify(events, null, 2));
383
- return;
384
- }
385
- if (events.length === 0) {
386
- console.log(`No events yet. Create one with \`${CLI} events create --name <name>${hubFlag()}\`.`);
387
- return;
388
- }
389
- const width = Math.max(...events.map((event) => event.slug.length));
390
- console.log(events.map((event) => `${event.slug.padEnd(width)} ${event.name} (${event.timeZone}${event.status === "ended" ? ", ended" : ""})`).join(`
391
- `));
392
- }
393
- async function createEvent() {
394
- const name = values.name?.trim();
395
- if (!name)
396
- fail("pass --name <name>, the event's name");
397
- if (values["time-zone"] !== undefined && !values["time-zone"].trim()) {
398
- fail("--time-zone needs a zone such as Europe/Berlin: leave it out to use this machine's");
399
- }
400
- const timeZone = values["time-zone"]?.trim() ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
401
- const { hub, key } = credentials(values.json);
402
- const { status, ok, body } = await call(hub, "/api/events", {
403
- token: key,
404
- body: { name, timeZone }
405
- });
406
- if (status === 409 && body.taken) {
407
- if (values.json)
408
- console.log(JSON.stringify(body, null, 2));
409
- else
410
- console.error(`hub-user: ${reason(body, status)}`);
411
- process.exit(3);
412
- }
413
- if (status === 401)
414
- refused(hub);
415
- if (status === 404)
416
- noEvents(hub);
417
- if (!ok || typeof body.slug !== "string") {
418
- fail(typeof body.error === "string" ? body.error : `the hub answered ${status}`);
419
- }
420
- const event = body;
421
- if (values.json) {
422
- console.log(JSON.stringify(event, null, 2));
423
- return;
424
- }
425
- console.log(`Created event "${event.name}" with slug: ${event.slug} (time zone ${event.timeZone})
426
-
427
- Register apps in it with:
428
- ${CLI} register --event ${event.slug} --name <app name>${hubFlag()} …`);
429
- }
430
- async function register() {
431
- const name = values.name?.trim();
432
- for (const flag of ["prod", "dev"]) {
433
- if (values[flag] !== undefined && !values[flag].trim()) {
434
- fail(`--${flag} needs a URL: leave --${flag} out to keep the registered one`);
435
- }
436
- }
437
- if (values.new && !values.prod && !values.dev)
438
- fail("pass --prod <url>, --dev <url> or both when creating an app");
439
- if (!name)
440
- fail("pass --name <name>, the app's name in the hub");
441
- if (values.listed && values.unlisted)
442
- fail("pass --listed or --unlisted, not both");
443
- if (values.event !== undefined && !values.event.trim()) {
444
- fail(`--event needs an event's slug: see \`${CLI} events${hubFlag()}\``);
445
- }
446
- const event = (values.event ?? process.env.HUB_EVENT)?.trim();
447
- if (!event) {
448
- fail(`pass --event <slug> or set HUB_EVENT to choose the hub event the app belongs to: \`${CLI} events${hubFlag()}\` lists them and \`${CLI} events create --name <name>${hubFlag()}\` creates one`);
449
- }
450
- const { hub, key } = credentials(values.json);
451
- const { status, ok, body } = await call(hub, "/api/apps/register", {
452
- token: key,
453
- body: {
454
- event,
455
- name,
456
- ...values.prod !== undefined && { url: values.prod },
457
- ...values.dev !== undefined && { devUrl: values.dev },
458
- ...values.new && { createOnly: true },
459
- ...values.listed && { listed: true },
460
- ...values.unlisted && { listed: false }
461
- }
462
- });
463
- const result = body;
464
- if (result.taken) {
465
- if (values.json)
466
- console.log(JSON.stringify(result, null, 2));
467
- else
468
- console.error(`hub-user: ${result.error}`);
469
- process.exit(3);
470
- }
471
- if (status === 404 && result.unknownEvent) {
472
- if (values.json)
473
- console.log(JSON.stringify(result, null, 2));
474
- else
475
- console.error(`hub-user: ${result.error ?? `no event has the slug "${event}"`} (\`${CLI} events${hubFlag()}\` lists them)`);
476
- process.exit(5);
477
- }
478
- if (status === 401)
479
- refused(hub);
480
- if (!ok) {
481
- fail(result.error ?? `the hub answered ${status}`);
482
- }
483
- if (!result.event) {
484
- fail(`"${name}" was registered, but not in the event "${event}": the hub needs updating to support events`);
485
- }
486
- const wanted = values.listed ? true : values.unlisted ? false : undefined;
487
- if (wanted !== undefined && result.listed !== wanted) {
488
- fail(`"${name}" was registered, but the hub did not apply --${wanted ? "listed" : "unlisted"}: it needs updating to support the app list`);
489
- }
490
- if (values.json) {
491
- console.log(JSON.stringify(result, null, 2));
492
- return;
493
- }
494
- const listing = typeof result.listed === "boolean" ? `
495
- Listed in the badge app list: ${result.listed ? values.prod ? "yes" : "yes, once it has a production URL" : "no"}` : "";
496
- console.log(`Registered "${name}" in the event "${result.event.name}" (${result.event.slug}) with key: ${result.key}${listing}
497
-
498
- Environment (Convex deployment, or the app's server):
499
- HUB_ISSUER=${result.env.HUB_ISSUER}
500
- HUB_JWKS=${result.env.HUB_JWKS}
501
-
502
- For Convex:
503
- bunx convex env set HUB_ISSUER '${result.env.HUB_ISSUER}'
504
- bunx convex env set HUB_JWKS '${result.env.HUB_JWKS}'
505
-
506
- Frontend (the dev server sends you to the hub to pick who to be):
507
- VITE_HUB_URL=${result.hubUrl}
508
-
509
- Then use the key in code: hubAuth({ app: "${result.key}" }) and <ConvexHubAuthProvider app="${result.key}" hubUrl={import.meta.env.VITE_HUB_URL} client={convex}>`);
510
- }
511
- if (command === "login")
512
- await login();
513
- else if (command === "whoami")
514
- await whoami();
515
- else if (command === "events") {
516
- if (subcommand === "create")
517
- await createEvent();
518
- else
519
- await listEvents();
520
- } else
521
- await register();