@user-hub/auth 0.1.7 → 0.2.1

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,11 +8,22 @@ 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
- 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, and lasts 4 hours.
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`.
15
15
 
16
+ ## Sessions
17
+
18
+ The hub decides how long a scan keeps someone signed in: 1, 2 or 4 hours, or until they are signed out from the hub. Your app needs no setup for this.
19
+
20
+ - When the app opens, and then every 5 minutes while it is open, the provider trades the token for a fresh one with the hub (`POST <hub>/api/token/refresh`); each fresh token lasts 10 minutes. With `hubUrl` set, it only ever asks that hub. The schedule follows the hub's clock, so a device whose clock is off still refreshes on time.
21
+ - Reopening the app later (even the next day) keeps the person signed in while their session lasts.
22
+ - When the hub ends a session (the person is deleted, signed out of all apps, or gets a new badge), the app signs them out within about 10 minutes. Name, team and role changes arrive the same way. Other tabs of the app follow a sign-out.
23
+ - A server checking tokens with `verifyHubToken` still accepts a token until it expires: up to 10 minutes after the hub ends the session, or up to 4 hours for the token a scan hands over.
24
+ - If the hub cannot be reached, the person stays signed in until their token runs out, then sees the signed-out screen; the app tries again when the device is back online, every 30 seconds, and on reload.
25
+ - A Content Security Policy needs the hub in `connect-src`.
26
+
16
27
  ## Quick start
17
28
 
18
29
  ### 1. Install
@@ -42,7 +53,7 @@ Then, from your app's folder (`bunx` reads `.env` and `.env.local` automatically
42
53
  bunx hub-user register --name "Your App" --new --prod https://your-app.com --dev http://localhost:3000
43
54
  ```
44
55
 
45
- 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**.)
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. `--listed`, `--unlisted` and updates without a URL need @user-hub/auth 0.2.1 or newer (`bun add @user-hub/auth@latest`). (A hub admin can do the same under **Apps** in the hub, and copy the values from **Setup**.)
46
57
 
47
58
  ### 3. Set the values
48
59
 
@@ -103,7 +114,7 @@ export const myVotes = query({
103
114
 
104
115
  ## Working on your app locally
105
116
 
106
- 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 for 4 hours, across reloads and restarts.
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).
107
118
 
108
119
  - **Switch person:** open `<hub>/open/<your-app-key>`.
109
120
  - **Different port:** run `hub-user register` again with the new `--dev` URL. The hub only sends tokens to registered URLs.
@@ -145,7 +156,7 @@ Hiding a page does not protect it: the server check does.
145
156
 
146
157
  ## Not using Convex?
147
158
 
148
- Send the token to your server and check it there:
159
+ Send the token to your server and check it there. It changes every few minutes as it is refreshed, so read it for each request:
149
160
 
150
161
  ```tsx
151
162
  const token = useHubToken();
@@ -169,17 +180,19 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
169
180
  | `@user-hub/auth/convex-react` | `ConvexHubAuthProvider` | For Convex apps, in place of `ConvexProvider`, inside `<body>`. Props: `client`, `app`, `hubUrl?` |
170
181
  | `@user-hub/auth/react` | `HubAuthProvider` | The same without Convex: `app`, `hubUrl?` |
171
182
  | both | `HubSignedIn` | Shows its children only when signed in. Props: `signedOut?`, `loading?` |
172
- | | `useHubUser()`, `useHubToken()`, `useHubSignOut()` | The person (or null), the raw token (or null), a sign-out function. Also from `/convex-react` |
183
+ | | `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
+ | | `useHubSession()` | `undefined` while loading, `null` when signed out, otherwise `{ token, user }`; most apps need only `useHubUser()` or `<HubSignedIn>`. Also from `/convex-react` |
173
185
  | `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app })` | Checks a token anywhere else |
174
- | 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 |
186
+ | CLI | `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) |
175
187
 
176
188
  ## Developing this package
177
189
 
178
190
  ```sh
179
191
  bun install
180
- bun test # unit tests
181
- bun run check # Biome
182
- bun run build # dist/: commit it
192
+ bun test # unit tests
193
+ bunx tsc --noEmit -p . # type-check
194
+ bun run check # Biome
195
+ bun run build # dist/: commit it
183
196
  ```
184
197
 
185
198
  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
@@ -2,19 +2,25 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { parseArgs } from "node:util";
5
- var USAGE = `Usage: hub-user register --name <name> [--prod <url>] [--dev <url>] [--new] [--hub <url>] [--json]
5
+ var USAGE = `Usage: hub-user register --name <name> [--prod <url>] [--dev <url>] [--listed|--unlisted] [--new] [--hub <url>] [--json]
6
6
 
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
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 or shown in
10
+ the badge app list.
11
+ --dev Where developers open the app as a person, e.g. http://localhost:3000
12
+ --listed Show the app in the hub's badge app list once it has a
13
+ production URL (default for new apps)
14
+ --unlisted Keep the app out of the hub's badge app list
15
+ --new Only create a new app: if the name is taken, change nothing and
16
+ exit with code 3 so you can pick another name
17
+ --hub The hub's URL (default: HUB_URL)
18
+ --json Print JSON instead of text
15
19
 
16
- At least one of --prod and --dev is needed. A URL left out on a later run keeps
17
- the registered one.
20
+ At least one of --prod and --dev is needed with --new or when first registering.
21
+ A URL left out on a later run keeps the registered one; both may be omitted on
22
+ an update. Without --listed or --unlisted, re-registering keeps the current
23
+ listing setting.
18
24
 
19
25
  Needs HUB_URL and HUB_ADMIN_PASSWORD in the environment (.env and .env.local
20
26
  are read automatically). Running it again with the same
@@ -33,6 +39,8 @@ var { values, positionals } = parseArgs({
33
39
  hub: { type: "string" },
34
40
  json: { type: "boolean", default: false },
35
41
  new: { type: "boolean", default: false },
42
+ listed: { type: "boolean", default: false },
43
+ unlisted: { type: "boolean", default: false },
36
44
  help: { type: "boolean", short: "h", default: false }
37
45
  }
38
46
  });
@@ -47,10 +55,12 @@ if (!hub)
47
55
  fail("set HUB_URL (in .env or .env.local) or pass --hub");
48
56
  if (!password)
49
57
  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");
58
+ if (values.new && !values.prod && !values.dev)
59
+ fail("pass --prod <url>, --dev <url> or both when creating an app");
52
60
  if (!name)
53
61
  fail("pass --name <name>, the app's name in the hub");
62
+ if (values.listed && values.unlisted)
63
+ fail("pass --listed or --unlisted, not both");
54
64
  var response = await fetch(`${hub}/api/apps/register`, {
55
65
  method: "POST",
56
66
  headers: {
@@ -61,7 +71,9 @@ var response = await fetch(`${hub}/api/apps/register`, {
61
71
  name,
62
72
  ...values.prod !== undefined && { url: values.prod },
63
73
  ...values.dev !== undefined && { devUrl: values.dev },
64
- ...values.new && { createOnly: true }
74
+ ...values.new && { createOnly: true },
75
+ ...values.listed && { listed: true },
76
+ ...values.unlisted && { listed: false }
65
77
  })
66
78
  }).catch((error) => fail(`could not reach ${hub}: ${error.message}`));
67
79
  var result = await response.json().catch(() => ({}));
@@ -75,10 +87,16 @@ if (result.taken) {
75
87
  if (!response.ok) {
76
88
  fail(result.error ?? `the hub answered ${response.status}`);
77
89
  }
90
+ var wanted = values.listed ? true : values.unlisted ? false : undefined;
91
+ if (wanted !== undefined && result.listed !== wanted) {
92
+ fail(`"${name}" was registered, but the hub did not apply --${wanted ? "listed" : "unlisted"}: it needs updating to support the app list`);
93
+ }
78
94
  if (values.json) {
79
95
  console.log(JSON.stringify(result, null, 2));
80
96
  } else {
81
- console.log(`Registered "${name}" with key: ${result.key}
97
+ const listing = typeof result.listed === "boolean" ? `
98
+ Listed in the badge app list: ${result.listed ? "yes" : "no"}` : "";
99
+ console.log(`Registered "${name}" with key: ${result.key}${listing}
82
100
 
83
101
  Environment (Convex deployment, or the app's server):
84
102
  HUB_ISSUER=${result.env.HUB_ISSUER}
@@ -0,0 +1,377 @@
1
+ // src/react.tsx
2
+ import { useMemo as useMemo2 } from "react";
3
+
4
+ // src/session.tsx
5
+ import {
6
+ createContext,
7
+ useCallback,
8
+ useContext,
9
+ useEffect,
10
+ useMemo,
11
+ useRef,
12
+ useState
13
+ } from "react";
14
+
15
+ // src/token.ts
16
+ function decodeSegment(segment) {
17
+ const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
18
+ return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
19
+ }
20
+ function payloadOf(token) {
21
+ try {
22
+ return decodeSegment(token.split(".")[1] ?? "");
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+ function readClaims(token) {
28
+ const payload = payloadOf(token);
29
+ if (typeof payload?.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string") {
30
+ return null;
31
+ }
32
+ return {
33
+ id: payload.sub,
34
+ name: payload.name,
35
+ team: payload.team,
36
+ role: payload.role === "facilitator" ? "facilitator" : "member",
37
+ app: payload.aud,
38
+ expiresAt: payload.exp * 1000
39
+ };
40
+ }
41
+ function sessionFor(token, app, now = Date.now()) {
42
+ const user = token ? readClaims(token) : null;
43
+ return token && user && user.app === app && user.expiresAt > now ? { token, user } : null;
44
+ }
45
+ function refreshInfo(token) {
46
+ const payload = payloadOf(token);
47
+ if (typeof payload?.iss !== "string" || typeof payload.iat !== "number" || typeof payload.auth_time !== "number") {
48
+ return null;
49
+ }
50
+ return {
51
+ url: `${payload.iss.replace(/\/+$/, "")}/api/token/refresh`,
52
+ issuedAt: payload.iat * 1000
53
+ };
54
+ }
55
+ function sessionKeyOf(token) {
56
+ const payload = payloadOf(token);
57
+ if (typeof payload?.sub !== "string") {
58
+ return null;
59
+ }
60
+ return [
61
+ payload.iss,
62
+ payload.aud,
63
+ payload.sub,
64
+ payload.auth_time ?? payload.iat
65
+ ].join("|");
66
+ }
67
+
68
+ // src/session.tsx
69
+ import { jsx } from "react/jsx-runtime";
70
+ var MAX_TIMEOUT_MS = 2 ** 31 - 1;
71
+ var REFRESH_AFTER_MS = 5 * 60 * 1000;
72
+ var REFRESH_BEFORE_EXPIRY_MS = 60 * 1000;
73
+ var RETRY_MS = 30 * 1000;
74
+ var REQUEST_TIMEOUT_MS = 10 * 1000;
75
+ var FRESH_MS = 5 * 1000;
76
+ var clockSkewMs = 0;
77
+ var hubNow = () => Date.now() + clockSkewMs;
78
+ var LOCAL_HOST = /^(localhost|127(\.\d{1,3}){3}|10(\.\d{1,3}){3}|192\.168(\.\d{1,3}){2}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|\[::1\]|[a-z0-9-]+\.local)$/i;
79
+ var HubContext = createContext({
80
+ session: undefined,
81
+ redirecting: false,
82
+ signOut: () => {},
83
+ suspend: () => {},
84
+ currentToken: () => null,
85
+ refresh: async () => null
86
+ });
87
+ var useHubState = () => useContext(HubContext);
88
+ var storageKey = (app) => `user-hub-token:${app}`;
89
+ function readStorage(key) {
90
+ try {
91
+ return window.localStorage.getItem(key);
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+ function writeStorage(key, token) {
97
+ try {
98
+ if (token)
99
+ window.localStorage.setItem(key, token);
100
+ else
101
+ window.localStorage.removeItem(key);
102
+ } catch {}
103
+ }
104
+ function takeTokenFromUrl() {
105
+ const hash = new URLSearchParams(window.location.hash.slice(1));
106
+ const token = hash.get("token");
107
+ if (token) {
108
+ hash.delete("token");
109
+ const rest = hash.toString();
110
+ window.history.replaceState(window.history.state, "", `${window.location.pathname}${window.location.search}${rest ? `#${rest}` : ""}`);
111
+ }
112
+ return token;
113
+ }
114
+ function originOf(url) {
115
+ try {
116
+ return new URL(url).origin;
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+ function refreshUrlFor(token, app, hubUrl) {
122
+ const info = readClaims(token)?.app === app ? refreshInfo(token) : null;
123
+ const hub = hubUrl && originOf(hubUrl);
124
+ return info && (!hub || originOf(info.url) === hub) ? info.url : null;
125
+ }
126
+ async function exchange(token, app, hubUrl) {
127
+ const url = refreshUrlFor(token, app, hubUrl);
128
+ if (!url) {
129
+ return { status: "ended" };
130
+ }
131
+ const controller = new AbortController;
132
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
133
+ try {
134
+ const response = await fetch(url, {
135
+ method: "POST",
136
+ headers: { Authorization: `Bearer ${token}` },
137
+ signal: controller.signal
138
+ });
139
+ if (response.status === 401) {
140
+ return { status: "ended" };
141
+ }
142
+ const next = response.ok ? (await response.json())?.token : null;
143
+ if (typeof next !== "string" || sessionKeyOf(next) !== sessionKeyOf(token)) {
144
+ return { status: "failed" };
145
+ }
146
+ const issuedAt = refreshInfo(next)?.issuedAt;
147
+ if (issuedAt) {
148
+ clockSkewMs = issuedAt - Date.now();
149
+ }
150
+ const session = sessionFor(next, app, hubNow());
151
+ return session ? { status: "refreshed", session } : { status: "failed" };
152
+ } catch {
153
+ return { status: "failed" };
154
+ } finally {
155
+ clearTimeout(timeout);
156
+ }
157
+ }
158
+ function HubSessionProvider({
159
+ app,
160
+ hubUrl,
161
+ children
162
+ }) {
163
+ const key = storageKey(app);
164
+ const [session, setSession] = useState();
165
+ const [stalled, setStalled] = useState(null);
166
+ const latest = useRef(undefined);
167
+ const held = useRef(null);
168
+ const inFlight = useRef(null);
169
+ const mounted = useRef(false);
170
+ const lastRequest = useRef(0);
171
+ const redirecting = session === null && Boolean(hubUrl) && typeof window !== "undefined" && LOCAL_HOST.test(window.location.hostname);
172
+ const show = useCallback((next, token, stalledToken) => {
173
+ held.current = token;
174
+ latest.current = next;
175
+ setSession(next);
176
+ setStalled(stalledToken);
177
+ }, []);
178
+ const signIn = useCallback((next) => {
179
+ writeStorage(key, next.token);
180
+ show(next, next.token, null);
181
+ }, [key, show]);
182
+ const end = useCallback(() => {
183
+ writeStorage(key, null);
184
+ show(null, null, null);
185
+ }, [key, show]);
186
+ const stall = useCallback((token) => {
187
+ writeStorage(key, token);
188
+ show(null, token, token);
189
+ }, [key, show]);
190
+ const currentToken = useCallback(() => {
191
+ const current = latest.current;
192
+ return current && current.user.expiresAt > hubNow() ? current.token : null;
193
+ }, []);
194
+ const trade = useCallback((sent) => {
195
+ if (inFlight.current?.token === sent) {
196
+ return inFlight.current.answer;
197
+ }
198
+ const answer = (async () => {
199
+ lastRequest.current = Date.now();
200
+ const result = await exchange(sent, app, hubUrl);
201
+ if (!mounted.current || held.current !== sent) {
202
+ return currentToken();
203
+ }
204
+ if (result.status === "refreshed") {
205
+ signIn(result.session);
206
+ return result.session.token;
207
+ }
208
+ if (result.status === "ended") {
209
+ end();
210
+ return null;
211
+ }
212
+ if (sessionFor(sent, app, hubNow())) {
213
+ return sent;
214
+ }
215
+ stall(sent);
216
+ return null;
217
+ })().finally(() => {
218
+ if (inFlight.current?.answer === answer) {
219
+ inFlight.current = null;
220
+ }
221
+ });
222
+ inFlight.current = { token: sent, answer };
223
+ return answer;
224
+ }, [app, hubUrl, currentToken, signIn, end, stall]);
225
+ const refresh = useCallback(async () => {
226
+ const current = latest.current;
227
+ if (!current || !refreshUrlFor(current.token, app, hubUrl)) {
228
+ return currentToken();
229
+ }
230
+ const issuedAt = refreshInfo(current.token)?.issuedAt ?? 0;
231
+ if (!inFlight.current && hubNow() - issuedAt < FRESH_MS) {
232
+ return current.token;
233
+ }
234
+ return await trade(current.token);
235
+ }, [app, hubUrl, currentToken, trade]);
236
+ useEffect(() => {
237
+ mounted.current = true;
238
+ return () => {
239
+ mounted.current = false;
240
+ };
241
+ }, []);
242
+ useEffect(() => {
243
+ const fromUrl = takeTokenFromUrl();
244
+ const stored = readStorage(key);
245
+ const valid = sessionFor(fromUrl, app, hubNow()) ?? sessionFor(stored, app, hubNow());
246
+ if (valid) {
247
+ signIn(valid);
248
+ if (refreshUrlFor(valid.token, app, hubUrl)) {
249
+ trade(valid.token);
250
+ }
251
+ return;
252
+ }
253
+ const expired = [fromUrl, stored].find((token) => Boolean(token && refreshUrlFor(token, app, hubUrl)));
254
+ if (!expired) {
255
+ end();
256
+ return;
257
+ }
258
+ writeStorage(key, expired);
259
+ held.current = expired;
260
+ latest.current = undefined;
261
+ setSession(undefined);
262
+ setStalled(null);
263
+ trade(expired);
264
+ }, [app, hubUrl, key, signIn, end, trade]);
265
+ useEffect(() => {
266
+ if (!stalled)
267
+ return;
268
+ const retry = () => {
269
+ if (document.visibilityState !== "hidden" && !inFlight.current) {
270
+ trade(stalled);
271
+ }
272
+ };
273
+ const id = setInterval(retry, RETRY_MS);
274
+ window.addEventListener("online", retry);
275
+ document.addEventListener("visibilitychange", retry);
276
+ return () => {
277
+ clearInterval(id);
278
+ window.removeEventListener("online", retry);
279
+ document.removeEventListener("visibilitychange", retry);
280
+ };
281
+ }, [stalled, trade]);
282
+ useEffect(() => {
283
+ const follow = (event) => {
284
+ if (event.key !== key && event.key !== null)
285
+ return;
286
+ const token = event.newValue;
287
+ const next = token ? sessionFor(token, app, hubNow()) : null;
288
+ const refreshable = token && refreshUrlFor(token, app, hubUrl);
289
+ show(next, token, !next && refreshable ? token : null);
290
+ };
291
+ window.addEventListener("storage", follow);
292
+ return () => window.removeEventListener("storage", follow);
293
+ }, [app, hubUrl, key, show]);
294
+ useEffect(() => {
295
+ if (!session)
296
+ return;
297
+ const { token, user } = session;
298
+ let active = true;
299
+ let id;
300
+ const after = (delay, run) => {
301
+ id = setTimeout(run, Math.min(Math.max(delay, 0), MAX_TIMEOUT_MS));
302
+ };
303
+ const expiry = setTimeout(() => stall(token), Math.min(Math.max(user.expiresAt - hubNow(), 0), MAX_TIMEOUT_MS));
304
+ if (!refreshUrlFor(token, app, hubUrl)) {
305
+ clearTimeout(expiry);
306
+ after(user.expiresAt - hubNow(), end);
307
+ } else {
308
+ const issuedAt = refreshInfo(token)?.issuedAt ?? 0;
309
+ const attempt = async () => {
310
+ if (await trade(token) === token && active) {
311
+ after(RETRY_MS, attempt);
312
+ }
313
+ };
314
+ const due = Math.min(issuedAt + REFRESH_AFTER_MS, user.expiresAt - REFRESH_BEFORE_EXPIRY_MS) - hubNow();
315
+ after(Math.max(due, lastRequest.current + RETRY_MS - Date.now()), attempt);
316
+ }
317
+ return () => {
318
+ active = false;
319
+ clearTimeout(id);
320
+ clearTimeout(expiry);
321
+ };
322
+ }, [session, app, hubUrl, end, stall, trade]);
323
+ useEffect(() => {
324
+ if (redirecting && hubUrl) {
325
+ window.location.replace(`${hubUrl.replace(/\/+$/, "")}/open/${encodeURIComponent(app)}`);
326
+ }
327
+ }, [redirecting, hubUrl, app]);
328
+ const signOut = end;
329
+ const suspend = useCallback(() => {
330
+ latest.current = null;
331
+ setSession(null);
332
+ }, []);
333
+ const state = useMemo(() => ({ session, redirecting, signOut, suspend, currentToken, refresh }), [session, redirecting, signOut, suspend, currentToken, refresh]);
334
+ return /* @__PURE__ */ jsx(HubContext.Provider, {
335
+ value: state,
336
+ children
337
+ });
338
+ }
339
+
340
+ // src/react.tsx
341
+ import { jsx as jsx2 } from "react/jsx-runtime";
342
+ function HubAuthProvider2(props) {
343
+ return /* @__PURE__ */ jsx2(HubSessionProvider, {
344
+ ...props
345
+ });
346
+ }
347
+ function DefaultSignedOut() {
348
+ return /* @__PURE__ */ jsx2("p", {
349
+ style: { padding: "2rem", textAlign: "center" },
350
+ children: "Scan your badge to sign in."
351
+ });
352
+ }
353
+ function HubSignedIn2({
354
+ children,
355
+ signedOut = /* @__PURE__ */ jsx2(DefaultSignedOut, {}),
356
+ loading = null
357
+ }) {
358
+ const { session, redirecting } = useHubState();
359
+ if (session === undefined || redirecting)
360
+ return loading;
361
+ return session ? children : signedOut;
362
+ }
363
+ function useHubSignOut2() {
364
+ return useHubState().signOut;
365
+ }
366
+ function useHubSession2() {
367
+ return useHubState().session;
368
+ }
369
+ function useHubUser2() {
370
+ const user = useHubSession2()?.user;
371
+ return useMemo2(() => user ? { id: user.id, name: user.name, team: user.team, role: user.role } : null, [user]);
372
+ }
373
+ function useHubToken2() {
374
+ return useHubSession2()?.token ?? null;
375
+ }
376
+
377
+ export { sessionKeyOf, useHubState, HubSessionProvider, HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2 };
@@ -1,5 +1,5 @@
1
1
  import { type ConvexReactClient } from "convex/react";
2
- import { type HubAuthProviderProps } from "./react";
2
+ import { type HubAuthProviderProps } from "./session";
3
3
  export { HubSignedIn, useHubSession, useHubSignOut, useHubToken, useHubUser, } from "./react";
4
4
  export type { HubRole, HubUser } from "./token";
5
5
  /**
@@ -1,11 +1,13 @@
1
1
  import {
2
- HubAuthProvider2,
2
+ sessionKeyOf,
3
+ useHubState,
4
+ HubSessionProvider,
3
5
  HubSignedIn2,
4
6
  useHubSignOut2,
5
7
  useHubSession2,
6
8
  useHubUser2,
7
9
  useHubToken2
8
- } from "./convex-zgnvvwvn.js";
10
+ } from "./convex-qxqkx9zh.js";
9
11
 
10
12
  // src/convex-react.tsx
11
13
  import {
@@ -15,22 +17,28 @@ import {
15
17
  import { useEffect, useMemo } from "react";
16
18
  import { jsx } from "react/jsx-runtime";
17
19
  function useConvexHubAuth() {
18
- const session = useHubSession2();
20
+ const { session, currentToken, refresh } = useHubState();
21
+ const isLoading = session === undefined;
22
+ const sessionKey = session ? sessionKeyOf(session.token) : null;
19
23
  return useMemo(() => ({
20
- isLoading: session === undefined,
21
- isAuthenticated: Boolean(session),
22
- fetchAccessToken: async () => session && session.user.expiresAt > Date.now() ? session.token : null
23
- }), [session]);
24
+ isLoading,
25
+ isAuthenticated: sessionKey !== null,
26
+ fetchAccessToken: async ({
27
+ forceRefreshToken
28
+ }) => {
29
+ const token = forceRefreshToken ? await refresh() : currentToken() ?? await refresh();
30
+ return token && sessionKeyOf(token) === sessionKey ? token : null;
31
+ }
32
+ }), [isLoading, sessionKey, currentToken, refresh]);
24
33
  }
25
- function SignOutWhenRejected({ children }) {
26
- const session = useHubSession2();
27
- const signOut = useHubSignOut2();
34
+ function SuspendWhenRejected({ children }) {
35
+ const { session, suspend } = useHubState();
28
36
  const { isLoading, isAuthenticated } = useConvexAuth();
29
37
  const rejected = Boolean(session) && !isLoading && !isAuthenticated;
30
38
  useEffect(() => {
31
39
  if (rejected)
32
- signOut();
33
- }, [rejected, signOut]);
40
+ suspend();
41
+ }, [rejected, suspend]);
34
42
  return children;
35
43
  }
36
44
  function ConvexHubAuthProvider({
@@ -38,12 +46,12 @@ function ConvexHubAuthProvider({
38
46
  children,
39
47
  ...props
40
48
  }) {
41
- return /* @__PURE__ */ jsx(HubAuthProvider2, {
49
+ return /* @__PURE__ */ jsx(HubSessionProvider, {
42
50
  ...props,
43
51
  children: /* @__PURE__ */ jsx(ConvexProviderWithAuth, {
44
52
  client,
45
53
  useAuth: useConvexHubAuth,
46
- children: /* @__PURE__ */ jsx(SignOutWhenRejected, {
54
+ children: /* @__PURE__ */ jsx(SuspendWhenRejected, {
47
55
  children
48
56
  })
49
57
  })
package/dist/react.d.ts CHANGED
@@ -1,17 +1,16 @@
1
1
  import { type ReactNode } from "react";
2
- import { type HubSession, type HubUser } from "./token";
2
+ import { type HubAuthProviderProps } from "./session";
3
+ import type { HubSession, HubUser } from "./token";
4
+ export type { HubAuthProviderProps } from "./session";
3
5
  export type { HubRole, HubUser } from "./token";
4
- export type HubAuthProviderProps = {
5
- app: string;
6
- hubUrl?: string;
7
- children: ReactNode;
8
- };
9
6
  /**
10
7
  * Provides the signed-in person to the app. Always renders its children:
11
8
  * put it inside the root document's <body>, and use <HubSignedIn> to decide
12
- * what to show. Apps on Convex use ConvexHubAuthProvider instead.
9
+ * what to show. Keeps the person signed in by refreshing their token with the
10
+ * hub every few minutes while the app is open, for as long as the hub allows.
11
+ * Apps on Convex use ConvexHubAuthProvider instead.
13
12
  */
14
- export declare function HubAuthProvider({ app, hubUrl, children, }: HubAuthProviderProps): import("react").JSX.Element;
13
+ export declare function HubAuthProvider(props: HubAuthProviderProps): import("react").JSX.Element;
15
14
  /**
16
15
  * Shows its children only to a signed-in person. Otherwise `signedOut`
17
16
  * ("Scan your badge to sign in" by default), or `loading` while the session is
@@ -34,6 +33,7 @@ export declare function useHubSession(): HubSession | null | undefined;
34
33
  export declare function useHubUser(): HubUser | null;
35
34
  /**
36
35
  * The raw token, for apps whose own server checks it with verifyHubToken:
37
- * send it as `Authorization: Bearer <token>`.
36
+ * send it as `Authorization: Bearer <token>`. It changes every few minutes as
37
+ * it is refreshed, so read it for each request.
38
38
  */
39
39
  export declare function useHubToken(): string | null;
package/dist/react.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  useHubSession2,
6
6
  useHubUser2,
7
7
  useHubToken2
8
- } from "./convex-zgnvvwvn.js";
8
+ } from "./convex-qxqkx9zh.js";
9
9
  export {
10
10
  HubAuthProvider2 as HubAuthProvider,
11
11
  HubSignedIn2 as HubSignedIn,
@@ -0,0 +1,25 @@
1
+ import { type ReactNode } from "react";
2
+ import { type HubSession } from "./token";
3
+ export declare function resetHubClock(): void;
4
+ type HubState = {
5
+ session: HubSession | null | undefined;
6
+ redirecting: boolean;
7
+ signOut: () => void;
8
+ suspend: () => void;
9
+ currentToken: () => string | null;
10
+ refresh: () => Promise<string | null>;
11
+ };
12
+ export declare const useHubState: () => HubState;
13
+ export type HubAuthProviderProps = {
14
+ app: string;
15
+ hubUrl?: string;
16
+ children: ReactNode;
17
+ };
18
+ /**
19
+ * Keeps the signed-in person for HubAuthProvider and ConvexHubAuthProvider:
20
+ * reads the token from the URL or storage, refreshes it with the hub on a
21
+ * schedule (and whenever Convex asks), follows other tabs of the same app,
22
+ * and signs out when the hub ends the session.
23
+ */
24
+ export declare function HubSessionProvider({ app, hubUrl, children, }: HubAuthProviderProps): import("react").JSX.Element;
25
+ export {};
package/dist/token.d.ts CHANGED
@@ -15,3 +15,8 @@ export type HubSession = {
15
15
  user: HubClaims;
16
16
  };
17
17
  export declare function sessionFor(token: string | null, app: string, now?: number): HubSession | null;
18
+ export declare function refreshInfo(token: string): {
19
+ url: string;
20
+ issuedAt: number;
21
+ } | null;
22
+ export declare function sessionKeyOf(token: string): string | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@user-hub/auth",
3
- "version": "0.1.7",
3
+ "version": "0.2.1",
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": [
@@ -5,7 +5,7 @@ description: Sign people into an app from their User Hub badge. Use when an app
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
 
@@ -33,14 +33,14 @@ The hub has one address, for example `https://hub.example.com`. The human gives
33
33
 
34
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.
35
35
  - `HUB_ISSUER` on the app's Convex deployment: `hub-user register` prints it for you (**Set the two values**).
36
- - `VITE_HUB_URL` in the app's frontend env: lets the dev server send you to the hub to sign in (**Wire it up**).
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
 
38
38
  ## Before you start: ask the human
39
39
 
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`.
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
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
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
46
  - **Infisical** (or another secret manager): run the command through it, for example `infisical run -- bunx hub-user register …`.
@@ -63,7 +63,9 @@ You need four things. Ask for them; never guess.
63
63
 
64
64
  `--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
65
 
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.
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. Updating with no URL flags needs `@user-hub/auth` 0.2.1 or newer (`bun add @user-hub/auth@latest`); older versions ask for `--prod` or `--dev`. 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.
67
+
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`. Both flags need `@user-hub/auth` 0.2.1 or newer (`bun add @user-hub/auth@latest`); older versions reject them. Pass neither when updating and the hub's current setting stays; the output shows it ("Listed in the badge app list: yes"). 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
69
 
68
70
  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
71
 
@@ -110,7 +112,7 @@ You need four things. Ask for them; never guess.
110
112
 
111
113
  ## Your dev server
112
114
 
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. The token is kept for 4 hours across reloads and restarts, then the same thing happens again.
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 (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.
114
116
 
115
117
  - To switch person: open `<hub>/open/<key>` and pick someone else.
116
118
  - 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.
@@ -127,7 +129,18 @@ Then:
127
129
 
128
130
  1. `bunx convex deploy`.
129
131
  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.
132
+ 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.
133
+
134
+ ## Hub moved to a new URL
135
+
136
+ 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
+
138
+ - **Starter apps** (they have `scripts/setup.ts`): ask the human to change `HUB_URL` in `.env.local`, 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
+ - **Other apps:**
140
+ 1. Ask the human to change `HUB_URL` where they keep it (see question 3 above).
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. This needs `@user-hub/auth` 0.2.1 or newer: if it asks for `--prod` or `--dev`, run `bun add @user-hub/auth@latest` first. 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
+ 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
+ 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
144
 
132
145
  ## Sign out
133
146
 
@@ -179,7 +192,8 @@ People are either `"member"` or `"facilitator"`, set in the hub. To give facilit
179
192
 
180
193
  ## Rules
181
194
 
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.
195
+ - 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
196
  - Check access on the server: `requireFacilitator(ctx)` / `requireHubUser(ctx)` in Convex, or `verifyHubToken` elsewhere. `useHubUser()` is for display only.
184
- - Tokens last 4 hours; the provider then shows the signed-out screen. Do not try to refresh them: people scan their badge again.
197
+ - 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
198
  - Do not add other sign-in methods, sessions or token handling. If something is missing, change this package instead.
199
+ - 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. The same command updates 0.2.0, whose `hub-user` has no `--listed`/`--unlisted` and needs a URL flag on every run (both need 0.2.1 or newer).
@@ -1,140 +0,0 @@
1
- // src/react.tsx
2
- import {
3
- createContext,
4
- useCallback,
5
- useContext,
6
- useEffect,
7
- useMemo,
8
- useState
9
- } from "react";
10
-
11
- // src/token.ts
12
- function decodeSegment(segment) {
13
- const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
14
- return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
15
- }
16
- function readClaims(token) {
17
- try {
18
- const payload = decodeSegment(token.split(".")[1] ?? "");
19
- if (typeof payload.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string") {
20
- return null;
21
- }
22
- return {
23
- id: payload.sub,
24
- name: payload.name,
25
- team: payload.team,
26
- role: payload.role === "facilitator" ? "facilitator" : "member",
27
- app: payload.aud,
28
- expiresAt: payload.exp * 1000
29
- };
30
- } catch {
31
- return null;
32
- }
33
- }
34
- function sessionFor(token, app, now = Date.now()) {
35
- const user = token ? readClaims(token) : null;
36
- return token && user && user.app === app && user.expiresAt > now ? { token, user } : null;
37
- }
38
-
39
- // src/react.tsx
40
- import { jsx } from "react/jsx-runtime";
41
- var MAX_TIMEOUT_MS = 2 ** 31 - 1;
42
- var LOCAL_HOST = /^(localhost|127(\.\d{1,3}){3}|10(\.\d{1,3}){3}|192\.168(\.\d{1,3}){2}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|\[::1\]|[a-z0-9-]+\.local)$/i;
43
- var HubContext = createContext({
44
- session: undefined,
45
- redirecting: false,
46
- signOut: () => {}
47
- });
48
- var storageKey = (app) => `user-hub-token:${app}`;
49
- function readStorage(key) {
50
- try {
51
- return window.localStorage.getItem(key);
52
- } catch {
53
- return null;
54
- }
55
- }
56
- function writeStorage(key, token) {
57
- try {
58
- if (token)
59
- window.localStorage.setItem(key, token);
60
- else
61
- window.localStorage.removeItem(key);
62
- } catch {}
63
- }
64
- function loadSession(app) {
65
- const hash = new URLSearchParams(window.location.hash.slice(1));
66
- const fromUrl = hash.get("token");
67
- if (fromUrl) {
68
- hash.delete("token");
69
- const rest = hash.toString();
70
- window.history.replaceState(window.history.state, "", `${window.location.pathname}${window.location.search}${rest ? `#${rest}` : ""}`);
71
- }
72
- const session = sessionFor(fromUrl, app) ?? sessionFor(readStorage(storageKey(app)), app);
73
- writeStorage(storageKey(app), session?.token ?? null);
74
- return session;
75
- }
76
- function HubAuthProvider2({
77
- app,
78
- hubUrl,
79
- children
80
- }) {
81
- const [session, setSession] = useState();
82
- const redirecting = session === null && Boolean(hubUrl) && typeof window !== "undefined" && LOCAL_HOST.test(window.location.hostname);
83
- useEffect(() => {
84
- setSession(loadSession(app));
85
- }, [app]);
86
- useEffect(() => {
87
- if (!session)
88
- return;
89
- const id = setTimeout(() => {
90
- writeStorage(storageKey(app), null);
91
- setSession(null);
92
- }, Math.min(session.user.expiresAt - Date.now(), MAX_TIMEOUT_MS));
93
- return () => clearTimeout(id);
94
- }, [session, app]);
95
- useEffect(() => {
96
- if (redirecting && hubUrl) {
97
- window.location.replace(`${hubUrl.replace(/\/+$/, "")}/open/${encodeURIComponent(app)}`);
98
- }
99
- }, [redirecting, hubUrl, app]);
100
- const signOut = useCallback(() => {
101
- writeStorage(storageKey(app), null);
102
- setSession(null);
103
- }, [app]);
104
- const state = useMemo(() => ({ session, redirecting, signOut }), [session, redirecting, signOut]);
105
- return /* @__PURE__ */ jsx(HubContext.Provider, {
106
- value: state,
107
- children
108
- });
109
- }
110
- function DefaultSignedOut() {
111
- return /* @__PURE__ */ jsx("p", {
112
- style: { padding: "2rem", textAlign: "center" },
113
- children: "Scan your badge to sign in."
114
- });
115
- }
116
- function HubSignedIn2({
117
- children,
118
- signedOut = /* @__PURE__ */ jsx(DefaultSignedOut, {}),
119
- loading = null
120
- }) {
121
- const { session, redirecting } = useContext(HubContext);
122
- if (session === undefined || redirecting)
123
- return loading;
124
- return session ? children : signedOut;
125
- }
126
- function useHubSignOut2() {
127
- return useContext(HubContext).signOut;
128
- }
129
- function useHubSession2() {
130
- return useContext(HubContext).session;
131
- }
132
- function useHubUser2() {
133
- const user = useHubSession2()?.user;
134
- return useMemo(() => user ? { id: user.id, name: user.name, team: user.team, role: user.role } : null, [user]);
135
- }
136
- function useHubToken2() {
137
- return useHubSession2()?.token ?? null;
138
- }
139
-
140
- export { HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2 };