@user-hub/auth 0.2.1 → 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 +12 -8
- package/dist/cli.js +362 -65
- package/package.json +1 -1
- package/skills/user-hub-auth/SKILL.md +28 -17
package/README.md
CHANGED
|
@@ -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.
|
|
41
|
+
### 2. Sign in and register your app
|
|
42
42
|
|
|
43
|
-
Ask the hub's admin for its URL and
|
|
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
|
-
|
|
47
|
-
HUB_ADMIN_PASSWORD=…
|
|
46
|
+
bunx hub-user login --hub https://hub.example.com
|
|
48
47
|
```
|
|
49
48
|
|
|
50
|
-
|
|
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. 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.
|
|
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
|
|
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.
|
|
@@ -183,7 +184,10 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
|
|
|
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` |
|
|
184
185
|
| | `useHubSession()` | `undefined` while loading, `null` when signed out, otherwise `{ token, user }`; most apps need only `useHubUser()` or `<HubSignedIn>`. Also from `/convex-react` |
|
|
185
186
|
| `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app })` | Checks a token anywhere else |
|
|
186
|
-
| CLI | `hub-user
|
|
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) |
|
|
187
191
|
|
|
188
192
|
## Developing this package
|
|
189
193
|
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
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:
|
|
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
|
|
|
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.
|
|
22
|
+
|
|
23
|
+
whoami Shows the hub account HUB_API_KEY belongs to.
|
|
24
|
+
|
|
25
|
+
register Registers the app, or updates it when the name exists.
|
|
7
26
|
--name The app's name in the hub; its key comes from it (required)
|
|
8
27
|
--prod Where badge scans send people. Leave it out until the app is
|
|
9
28
|
deployed: it can be developed, but not scheduled or shown in
|
|
@@ -20,82 +39,354 @@ var USAGE = `Usage: hub-user register --name <name> [--prod <url>] [--dev <url>]
|
|
|
20
39
|
At least one of --prod and --dev is needed with --new or when first registering.
|
|
21
40
|
A URL left out on a later run keeps the registered one; both may be omitted on
|
|
22
41
|
an update. Without --listed or --unlisted, re-registering keeps the current
|
|
23
|
-
listing setting.
|
|
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.
|
|
24
46
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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;
|
|
28
54
|
function fail(message) {
|
|
29
55
|
console.error(`hub-user: ${message}`);
|
|
30
56
|
process.exit(1);
|
|
31
57
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
|
|
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)) {
|
|
48
92
|
console.log(USAGE);
|
|
49
93
|
process.exit(values.help ? 0 : 1);
|
|
50
94
|
}
|
|
51
|
-
var
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
if (
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
Authorization: `Bearer ${password}`,
|
|
68
|
-
"Content-Type": "application/json"
|
|
69
|
-
},
|
|
70
|
-
body: JSON.stringify({
|
|
71
|
-
name,
|
|
72
|
-
...values.prod !== undefined && { url: values.prod },
|
|
73
|
-
...values.dev !== undefined && { devUrl: values.dev },
|
|
74
|
-
...values.new && { createOnly: true },
|
|
75
|
-
...values.listed && { listed: true },
|
|
76
|
-
...values.unlisted && { listed: false }
|
|
77
|
-
})
|
|
78
|
-
}).catch((error) => fail(`could not reach ${hub}: ${error.message}`));
|
|
79
|
-
var result = await response.json().catch(() => ({}));
|
|
80
|
-
if (result.taken) {
|
|
81
|
-
if (values.json)
|
|
82
|
-
console.log(JSON.stringify(result, null, 2));
|
|
83
|
-
else
|
|
84
|
-
console.error(`hub-user: ${result.error}`);
|
|
85
|
-
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;
|
|
86
111
|
}
|
|
87
|
-
|
|
88
|
-
|
|
112
|
+
function reason(body, status) {
|
|
113
|
+
return String(body.message ?? body.error_description ?? body.error ?? status);
|
|
89
114
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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 };
|
|
93
126
|
}
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
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;
|
|
220
|
+
}
|
|
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}` : ""}`);
|
|
333
|
+
}
|
|
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
|
+
}
|
|
97
388
|
const listing = typeof result.listed === "boolean" ? `
|
|
98
|
-
Listed in the badge app list: ${result.listed ? "yes" : "no"}` : "";
|
|
389
|
+
Listed in the badge app list: ${result.listed ? values.prod ? "yes" : "yes, once it has a production URL" : "no"}` : "";
|
|
99
390
|
console.log(`Registered "${name}" with key: ${result.key}${listing}
|
|
100
391
|
|
|
101
392
|
Environment (Convex deployment, or the app's server):
|
|
@@ -111,3 +402,9 @@ VITE_HUB_URL=${result.hubUrl}
|
|
|
111
402
|
|
|
112
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}>`);
|
|
113
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
|
-
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
|
|
@@ -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
|
|
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
|
|
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
|
|
|
@@ -41,12 +41,22 @@ 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
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. **
|
|
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.
|
|
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,17 +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,
|
|
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, 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.
|
|
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.
|
|
67
77
|
|
|
68
|
-
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`.
|
|
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.
|
|
69
79
|
|
|
70
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.
|
|
71
81
|
|
|
@@ -112,7 +122,7 @@ You need four things. Ask for them; never guess.
|
|
|
112
122
|
|
|
113
123
|
## Your dev server
|
|
114
124
|
|
|
115
|
-
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 (
|
|
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.
|
|
116
126
|
|
|
117
127
|
- To switch person: open `<hub>/open/<key>` and pick someone else.
|
|
118
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.
|
|
@@ -123,7 +133,7 @@ Run the app as usual (`bun run dev`) on the `--dev` URL you registered. Opening
|
|
|
123
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:
|
|
124
134
|
|
|
125
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.
|
|
126
|
-
- **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 '…'`.
|
|
127
137
|
|
|
128
138
|
Then:
|
|
129
139
|
|
|
@@ -135,10 +145,10 @@ Then:
|
|
|
135
145
|
|
|
136
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.
|
|
137
147
|
|
|
138
|
-
- **Starter apps** (they have `scripts/setup.ts`):
|
|
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.
|
|
139
149
|
- **Other apps:**
|
|
140
|
-
1.
|
|
141
|
-
2. Run `bunx 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.
|
|
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.
|
|
142
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.
|
|
143
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.
|
|
144
154
|
|
|
@@ -196,4 +206,5 @@ People are either `"member"` or `"facilitator"`, set in the hub. To give facilit
|
|
|
196
206
|
- Check access on the server: `requireFacilitator(ctx)` / `requireHubUser(ctx)` in Convex, or `verifyHubToken` elsewhere. `useHubUser()` is for display only.
|
|
197
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`.
|
|
198
208
|
- Do not add other sign-in methods, sessions or token handling. If something is missing, change this package instead.
|
|
199
|
-
-
|
|
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.
|
|
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.
|