@user-hub/auth 0.7.3 → 0.8.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 +33 -4
- package/dist/{convex-77ptkyt2.js → convex-e0k41ps8.js} +1 -1
- package/dist/{convex-55v4qaqb.js → convex-jf1p8p1w.js} +1 -1
- package/dist/{convex-zj2n2r92.js → convex-q39rcwdv.js} +152 -9
- package/dist/convex-react.d.ts +2 -1
- package/dist/convex-react.js +13 -5
- package/dist/{convex-c4m6k5st.js → convex-rh6n9pwg.js} +1 -1
- package/dist/{convex-rwq8r0rm.js → convex-vtpnsjbm.js} +2 -2
- package/dist/internal/access-code.d.ts +33 -0
- package/dist/internal/session.d.ts +4 -1
- package/dist/react.d.ts +29 -0
- package/dist/react.js +6 -2
- package/dist/start-convex.js +2 -2
- package/dist/start-middleware.js +2 -2
- package/dist/start.js +2 -2
- package/package.json +1 -1
- package/skills/user-hub-auth/SKILL.md +4 -3
- package/skills/user-hub-auth/references/access-codes.md +63 -0
- package/skills/user-hub-auth/references/connect-an-app.md +2 -2
- package/skills/user-hub-auth/references/dev-and-production.md +2 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> **Private beta.** This package needs a User Hub, which is not public yet. Until then it is only useful to teams already running one.
|
|
4
4
|
|
|
5
|
-
Sign people into your app with their User Hub badge. People scan a printed QR code and arrive in your app already signed in. You get `{ id, name, team, role }` and build no sign-in screens, passwords or sessions.
|
|
5
|
+
Sign people into your app with their User Hub badge. People scan a printed QR code and arrive in your app already signed in, or, on a computer, type the access code printed on the badge. You get `{ id, name, team, role }` and build no sign-in screens, passwords or sessions.
|
|
6
6
|
|
|
7
7
|
Works with Convex apps, React frontends and any server that can check a token.
|
|
8
8
|
|
|
@@ -177,13 +177,41 @@ export const myVotes = query({
|
|
|
177
177
|
});
|
|
178
178
|
```
|
|
179
179
|
|
|
180
|
+
## Access codes
|
|
181
|
+
|
|
182
|
+
Every badge also carries a 5-character access code (letters and digits, such as `K7P3Q`). People who use your app on a computer type it in instead of scanning. Your app draws the screen; the hub checks the code and the person is signed in exactly as after a scan.
|
|
183
|
+
|
|
184
|
+
```tsx
|
|
185
|
+
import { useHubCodeSignIn } from "@user-hub/auth/convex-react"; // or /react
|
|
186
|
+
|
|
187
|
+
function AccessCodeSignIn() {
|
|
188
|
+
const { signIn, pending, error, reset } = useHubCodeSignIn();
|
|
189
|
+
const [code, setCode] = useState("");
|
|
190
|
+
return (
|
|
191
|
+
<form onSubmit={(event) => { event.preventDefault(); void signIn(code); }}>
|
|
192
|
+
<input value={code} onChange={(event) => { setCode(event.target.value); reset(); }} />
|
|
193
|
+
{error && <p>{error.reason}</p>}
|
|
194
|
+
<button disabled={pending}>Sign in</button>
|
|
195
|
+
</form>
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
<HubSignedIn signedOut={<AccessCodeSignIn />}>{children}</HubSignedIn>
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
- `signIn(code)` resolves to `true` once signed in; case, spaces and dashes do not matter.
|
|
203
|
+
- `error.reason` is `invalid` (wrong code, or a person of another event), `ended` (with `eventName`), `rateLimited` (with `retryAfter` in milliseconds: too many wrong codes from this network), `forbidden` (the page's address is not one of the app's URLs in the hub) or `unavailable` (try again).
|
|
204
|
+
- It needs `hubUrl` on the provider. The hub only answers pages served from the app's registered URLs.
|
|
205
|
+
- A code signs the person in to this app whenever their event is running, whatever the schedule says. Regenerating a badge in the hub gives a new code.
|
|
206
|
+
|
|
180
207
|
## Working on your app locally
|
|
181
208
|
|
|
182
209
|
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).
|
|
183
210
|
|
|
184
211
|
- **Switch person:** open `<hub>/open/<your-app-key>`.
|
|
185
212
|
- **Different port:** add it to the app's development URLs: `user-hub dev add http://localhost:<port>` (with `--event` and `--app` outside a starter app). The hub only sends tokens to registered URLs.
|
|
186
|
-
- **Production:** someone without a token sees "Scan your badge to sign in". Pass `signedOut={…}` to `<HubSignedIn>` to style that screen.
|
|
213
|
+
- **Production:** someone without a token sees "Scan your badge to sign in". Pass `signedOut={…}` to `<HubSignedIn>` to style that screen, or make it your access-code screen.
|
|
214
|
+
- **Access-code screen:** pass `devRedirect={false}` to the provider to see the signed-out screen on a dev server instead of going to the hub. Get a test person's code with `user-hub people badge <person>`.
|
|
187
215
|
|
|
188
216
|
## Sign out
|
|
189
217
|
|
|
@@ -245,10 +273,11 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
|
|
|
245
273
|
|---|---|---|
|
|
246
274
|
| `@user-hub/auth/convex` | `hubAuth({ app })` | The Convex auth provider, from `HUB_ISSUER` and `HUB_JWKS` |
|
|
247
275
|
| | `getHubUser(ctx)`, `requireHubUser(ctx)`, `requireFacilitator(ctx)` | The person in Convex functions: or null, or throw |
|
|
248
|
-
| `@user-hub/auth/convex-react` | `ConvexHubAuthProvider` | For Convex apps, in place of `ConvexProvider`, inside `<body>`. Props: `client`, `app`, `hubUrl?`, `initialToken?` |
|
|
249
|
-
| `@user-hub/auth/react` | `HubAuthProvider` | The same without Convex: `app`, `hubUrl?`, `initialToken?` |
|
|
276
|
+
| `@user-hub/auth/convex-react` | `ConvexHubAuthProvider` | For Convex apps, in place of `ConvexProvider`, inside `<body>`. Props: `client`, `app`, `hubUrl?`, `initialToken?`, `devRedirect?` |
|
|
277
|
+
| `@user-hub/auth/react` | `HubAuthProvider` | The same without Convex: `app`, `hubUrl?`, `initialToken?`, `devRedirect?` (default true: a signed-out dev server goes to the hub) |
|
|
250
278
|
| both | `HubSignedIn` | Shows its children only when signed in. Props: `signedOut?`, `loading?` |
|
|
251
279
|
| | `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` |
|
|
280
|
+
| | `useHubCodeSignIn()`, `HUB_ACCESS_CODE_LENGTH` | Access-code sign-in: `{ signIn(code), pending, error, reset }`; the code's length (5). Also from `/convex-react` |
|
|
252
281
|
| | `useHubSession()` | `undefined` while loading, `null` when signed out, otherwise `{ token, user }`; most apps need only `useHubUser()` or `<HubSignedIn>`. Also from `/convex-react` |
|
|
253
282
|
| `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app, hubUrl? })` | Checks a token anywhere else. `hubUrl` is the issuer when `HUB_ISSUER` is not set |
|
|
254
283
|
| `@user-hub/auth/start` | `getHubToken({ app, hubUrl })` | TanStack Start, inside a server function: the request's token for `initialToken`, checked and refreshed, or null |
|
|
@@ -120,4 +120,4 @@ function writeCookie(app, token) {
|
|
|
120
120
|
} catch {}
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
export { hubNow, readClaims, sessionFor, newestSession, refreshInfo, sessionKeyOf, refreshUrlFor, exchange, cookieName, COOKIE_MAX_AGE_S, writeCookie };
|
|
123
|
+
export { hubNow, learnHubClock, readClaims, sessionFor, newestSession, refreshInfo, sessionKeyOf, refreshUrlFor, exchange, cookieName, COOKIE_MAX_AGE_S, writeCookie };
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
registerLiveSession,
|
|
3
3
|
sendableToken
|
|
4
|
-
} from "./convex-
|
|
4
|
+
} from "./convex-rh6n9pwg.js";
|
|
5
5
|
import {
|
|
6
6
|
hubNow,
|
|
7
|
+
learnHubClock,
|
|
7
8
|
readClaims,
|
|
8
9
|
sessionFor,
|
|
9
10
|
newestSession,
|
|
@@ -12,10 +13,10 @@ import {
|
|
|
12
13
|
refreshUrlFor,
|
|
13
14
|
exchange,
|
|
14
15
|
writeCookie
|
|
15
|
-
} from "./convex-
|
|
16
|
+
} from "./convex-jf1p8p1w.js";
|
|
16
17
|
|
|
17
18
|
// src/react.tsx
|
|
18
|
-
import { useMemo as useMemo2 } from "react";
|
|
19
|
+
import { useCallback as useCallback2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
|
|
19
20
|
|
|
20
21
|
// src/internal/session.tsx
|
|
21
22
|
import {
|
|
@@ -30,6 +31,71 @@ import {
|
|
|
30
31
|
useSyncExternalStore
|
|
31
32
|
} from "react";
|
|
32
33
|
|
|
34
|
+
// src/internal/access-code.ts
|
|
35
|
+
var HUB_ACCESS_CODE_LENGTH2 = 5;
|
|
36
|
+
var REQUEST_TIMEOUT_MS = 10 * 1000;
|
|
37
|
+
var failed = (error) => ({
|
|
38
|
+
status: "error",
|
|
39
|
+
error
|
|
40
|
+
});
|
|
41
|
+
function codeUrl(hubUrl) {
|
|
42
|
+
try {
|
|
43
|
+
const url = new URL(hubUrl);
|
|
44
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
45
|
+
return null;
|
|
46
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}/api/code`;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function exchangeCode(hubUrl, app, code) {
|
|
52
|
+
const url = codeUrl(hubUrl);
|
|
53
|
+
if (!url)
|
|
54
|
+
return failed({ reason: "unavailable" });
|
|
55
|
+
const controller = new AbortController;
|
|
56
|
+
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
57
|
+
try {
|
|
58
|
+
const response = await fetch(url, {
|
|
59
|
+
method: "POST",
|
|
60
|
+
headers: { "Content-Type": "application/json" },
|
|
61
|
+
body: JSON.stringify({ code, app }),
|
|
62
|
+
signal: controller.signal
|
|
63
|
+
});
|
|
64
|
+
const body = await response.json().catch(() => null);
|
|
65
|
+
if (response.ok && typeof body?.token === "string") {
|
|
66
|
+
if (readClaims(body.token)?.app !== app) {
|
|
67
|
+
return failed({ reason: "unavailable" });
|
|
68
|
+
}
|
|
69
|
+
const issuedAt = refreshInfo(body.token)?.issuedAt;
|
|
70
|
+
if (issuedAt)
|
|
71
|
+
learnHubClock(issuedAt);
|
|
72
|
+
return { status: "ok", token: body.token };
|
|
73
|
+
}
|
|
74
|
+
switch (body?.error) {
|
|
75
|
+
case "invalid":
|
|
76
|
+
return failed({ reason: "invalid" });
|
|
77
|
+
case "forbidden":
|
|
78
|
+
return failed({ reason: "forbidden" });
|
|
79
|
+
case "ended":
|
|
80
|
+
return failed({
|
|
81
|
+
reason: "ended",
|
|
82
|
+
eventName: String(body.event?.name ?? "")
|
|
83
|
+
});
|
|
84
|
+
case "rateLimited":
|
|
85
|
+
return failed({
|
|
86
|
+
reason: "rateLimited",
|
|
87
|
+
retryAfter: Number(body.retryAfter) || 60000
|
|
88
|
+
});
|
|
89
|
+
default:
|
|
90
|
+
return failed({ reason: "unavailable" });
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
return failed({ reason: "unavailable" });
|
|
94
|
+
} finally {
|
|
95
|
+
clearTimeout(timeout);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
33
99
|
// src/internal/storage.ts
|
|
34
100
|
var storageKey = (app) => `user-hub-token:${app}`;
|
|
35
101
|
function readStorage(key) {
|
|
@@ -127,7 +193,10 @@ var HubContext = createContext({
|
|
|
127
193
|
signOut: () => {},
|
|
128
194
|
suspend: () => {},
|
|
129
195
|
currentToken: () => null,
|
|
130
|
-
refresh: async () => null
|
|
196
|
+
refresh: async () => null,
|
|
197
|
+
signInWithCode: async () => {
|
|
198
|
+
throw new Error("useHubCodeSignIn must be used inside HubAuthProvider or ConvexHubAuthProvider");
|
|
199
|
+
}
|
|
131
200
|
});
|
|
132
201
|
var useHubState = () => useContext(HubContext);
|
|
133
202
|
var openUrl = (hubUrl, app) => `${hubUrl.replace(/\/+$/, "")}/open/${encodeURIComponent(app)}`;
|
|
@@ -135,6 +204,7 @@ function HubSessionProvider({
|
|
|
135
204
|
app,
|
|
136
205
|
hubUrl,
|
|
137
206
|
initialToken,
|
|
207
|
+
devRedirect = true,
|
|
138
208
|
reloadOnSignOut = false,
|
|
139
209
|
children
|
|
140
210
|
}) {
|
|
@@ -157,8 +227,10 @@ function HubSessionProvider({
|
|
|
157
227
|
return { promise, settle };
|
|
158
228
|
});
|
|
159
229
|
const mounted = useRef(false);
|
|
230
|
+
const currentApp = useRef(app);
|
|
231
|
+
const codeAttempt = useRef(0);
|
|
160
232
|
const lastRequest = useRef(0);
|
|
161
|
-
const redirecting = session === null && Boolean(hubUrl) && typeof window !== "undefined" && LOCAL_HOST.test(window.location.hostname);
|
|
233
|
+
const redirecting = session === null && devRedirect && Boolean(hubUrl) && typeof window !== "undefined" && LOCAL_HOST.test(window.location.hostname);
|
|
162
234
|
const show = useCallback((next, token, stalledToken) => {
|
|
163
235
|
held.current = token;
|
|
164
236
|
latest.current = next;
|
|
@@ -171,13 +243,13 @@ function HubSessionProvider({
|
|
|
171
243
|
const leavePage = useCallback(() => {
|
|
172
244
|
if (!reloadOnSignOut || !latest.current)
|
|
173
245
|
return false;
|
|
174
|
-
if (hubUrl && LOCAL_HOST.test(window.location.hostname)) {
|
|
246
|
+
if (devRedirect && hubUrl && LOCAL_HOST.test(window.location.hostname)) {
|
|
175
247
|
window.location.replace(openUrl(hubUrl, app));
|
|
176
248
|
} else {
|
|
177
249
|
window.location.reload();
|
|
178
250
|
}
|
|
179
251
|
return true;
|
|
180
|
-
}, [reloadOnSignOut, hubUrl, app]);
|
|
252
|
+
}, [reloadOnSignOut, devRedirect, hubUrl, app]);
|
|
181
253
|
const end = useCallback(() => {
|
|
182
254
|
writeToken(app, null);
|
|
183
255
|
if (leavePage())
|
|
@@ -240,6 +312,9 @@ function HubSessionProvider({
|
|
|
240
312
|
mounted.current = false;
|
|
241
313
|
};
|
|
242
314
|
}, []);
|
|
315
|
+
useLayoutEffect(() => {
|
|
316
|
+
currentApp.current = app;
|
|
317
|
+
}, [app]);
|
|
243
318
|
useLayoutEffect(() => {
|
|
244
319
|
const unregister = registerLiveSession(app, {
|
|
245
320
|
tokenForRequest: async () => {
|
|
@@ -348,12 +423,49 @@ function HubSessionProvider({
|
|
|
348
423
|
window.location.replace(openUrl(hubUrl, app));
|
|
349
424
|
}
|
|
350
425
|
}, [redirecting, hubUrl, app]);
|
|
426
|
+
const signInWithCode = useCallback(async (code) => {
|
|
427
|
+
if (!hubUrl) {
|
|
428
|
+
throw new Error("useHubCodeSignIn needs hubUrl on HubAuthProvider or ConvexHubAuthProvider");
|
|
429
|
+
}
|
|
430
|
+
const attempt = ++codeAttempt.current;
|
|
431
|
+
const sessionBefore = held.current && sessionKeyOf(held.current);
|
|
432
|
+
const result = await exchangeCode(hubUrl, app, code);
|
|
433
|
+
const sessionNow = held.current && sessionKeyOf(held.current);
|
|
434
|
+
if (!mounted.current || currentApp.current !== app || codeAttempt.current !== attempt || sessionNow !== sessionBefore) {
|
|
435
|
+
return "superseded";
|
|
436
|
+
}
|
|
437
|
+
if (result.status === "error")
|
|
438
|
+
return result.error;
|
|
439
|
+
const next = sessionFor(result.token, app, hubNow());
|
|
440
|
+
if (!next)
|
|
441
|
+
return { reason: "unavailable" };
|
|
442
|
+
signIn(next);
|
|
443
|
+
if (refreshUrlFor(next.token, app, hubUrl))
|
|
444
|
+
trade(next.token);
|
|
445
|
+
return null;
|
|
446
|
+
}, [app, hubUrl, signIn, trade]);
|
|
351
447
|
const signOut = end;
|
|
352
448
|
const suspend = useCallback(() => {
|
|
353
449
|
latest.current = null;
|
|
354
450
|
store.set({ session: null });
|
|
355
451
|
}, [store]);
|
|
356
|
-
const state = useMemo(() => ({
|
|
452
|
+
const state = useMemo(() => ({
|
|
453
|
+
session,
|
|
454
|
+
redirecting,
|
|
455
|
+
signOut,
|
|
456
|
+
suspend,
|
|
457
|
+
currentToken,
|
|
458
|
+
refresh,
|
|
459
|
+
signInWithCode
|
|
460
|
+
}), [
|
|
461
|
+
session,
|
|
462
|
+
redirecting,
|
|
463
|
+
signOut,
|
|
464
|
+
suspend,
|
|
465
|
+
currentToken,
|
|
466
|
+
refresh,
|
|
467
|
+
signInWithCode
|
|
468
|
+
]);
|
|
357
469
|
return /* @__PURE__ */ jsx(HubContext.Provider, {
|
|
358
470
|
value: state,
|
|
359
471
|
children
|
|
@@ -396,5 +508,36 @@ function useHubUser2() {
|
|
|
396
508
|
function useHubToken2() {
|
|
397
509
|
return useHubSession2()?.token ?? null;
|
|
398
510
|
}
|
|
511
|
+
function useHubCodeSignIn2() {
|
|
512
|
+
const { signInWithCode } = useHubState();
|
|
513
|
+
const [pending, setPending] = useState2(false);
|
|
514
|
+
const [error, setError] = useState2(null);
|
|
515
|
+
const inFlight = useRef2(false);
|
|
516
|
+
const attempt = useRef2(0);
|
|
517
|
+
const signIn = useCallback2(async (code) => {
|
|
518
|
+
if (inFlight.current)
|
|
519
|
+
return false;
|
|
520
|
+
inFlight.current = true;
|
|
521
|
+
const mine = ++attempt.current;
|
|
522
|
+
setPending(true);
|
|
523
|
+
setError(null);
|
|
524
|
+
try {
|
|
525
|
+
const failure = await signInWithCode(code);
|
|
526
|
+
if (failure === "superseded")
|
|
527
|
+
return false;
|
|
528
|
+
if (attempt.current === mine)
|
|
529
|
+
setError(failure);
|
|
530
|
+
return failure === null;
|
|
531
|
+
} finally {
|
|
532
|
+
inFlight.current = false;
|
|
533
|
+
setPending(false);
|
|
534
|
+
}
|
|
535
|
+
}, [signInWithCode]);
|
|
536
|
+
const reset = useCallback2(() => {
|
|
537
|
+
attempt.current++;
|
|
538
|
+
setError(null);
|
|
539
|
+
}, []);
|
|
540
|
+
return useMemo2(() => ({ signIn, pending, error, reset }), [signIn, pending, error, reset]);
|
|
541
|
+
}
|
|
399
542
|
|
|
400
|
-
export { useHubState, HubSessionProvider, HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2 };
|
|
543
|
+
export { HUB_ACCESS_CODE_LENGTH2, useHubState, HubSessionProvider, HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2, useHubCodeSignIn2 };
|
package/dist/convex-react.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ConvexReactClient } from "convex/react";
|
|
2
2
|
import { type HubAuthProviderProps } from "./internal/session";
|
|
3
|
-
export { HubSignedIn, useHubSession, useHubSignOut, useHubToken, useHubUser, } from "./react";
|
|
3
|
+
export { HUB_ACCESS_CODE_LENGTH, HubSignedIn, useHubCodeSignIn, useHubSession, useHubSignOut, useHubToken, useHubUser, } from "./react";
|
|
4
|
+
export type { HubCodeError, HubCodeSignIn } from "./react";
|
|
4
5
|
export type { HubRole, HubUser } from "./internal/token";
|
|
5
6
|
/**
|
|
6
7
|
* HubAuthProvider for apps on Convex: the hub token becomes the Convex
|
package/dist/convex-react.js
CHANGED
|
@@ -1,27 +1,33 @@
|
|
|
1
1
|
import {
|
|
2
|
+
HUB_ACCESS_CODE_LENGTH2,
|
|
2
3
|
useHubState,
|
|
3
4
|
HubSessionProvider,
|
|
4
5
|
HubSignedIn2,
|
|
5
6
|
useHubSignOut2,
|
|
6
7
|
useHubSession2,
|
|
7
8
|
useHubUser2,
|
|
8
|
-
useHubToken2
|
|
9
|
-
|
|
9
|
+
useHubToken2,
|
|
10
|
+
useHubCodeSignIn2
|
|
11
|
+
} from "./convex-q39rcwdv.js";
|
|
10
12
|
import {
|
|
11
13
|
sessionKeyOf
|
|
12
|
-
} from "./convex-
|
|
14
|
+
} from "./convex-jf1p8p1w.js";
|
|
13
15
|
|
|
14
16
|
// src/convex-react.tsx
|
|
15
17
|
import {
|
|
16
18
|
ConvexProviderWithAuth,
|
|
17
19
|
useConvexAuth
|
|
18
20
|
} from "convex/react";
|
|
19
|
-
import { useEffect, useMemo } from "react";
|
|
21
|
+
import { useEffect, useMemo, useState } from "react";
|
|
20
22
|
import { jsx } from "react/jsx-runtime";
|
|
21
23
|
function useConvexHubAuth() {
|
|
22
24
|
const { session, currentToken, refresh } = useHubState();
|
|
23
|
-
const isLoading = session === undefined;
|
|
24
25
|
const sessionKey = session ? sessionKeyOf(session.token) : null;
|
|
26
|
+
const [shownKey, setShownKey] = useState(sessionKey);
|
|
27
|
+
const starting = sessionKey !== null && sessionKey !== shownKey;
|
|
28
|
+
if (sessionKey !== shownKey)
|
|
29
|
+
setShownKey(sessionKey);
|
|
30
|
+
const isLoading = session === undefined || starting;
|
|
25
31
|
return useMemo(() => ({
|
|
26
32
|
isLoading,
|
|
27
33
|
isAuthenticated: sessionKey !== null,
|
|
@@ -62,7 +68,9 @@ function ConvexHubAuthProvider({
|
|
|
62
68
|
}
|
|
63
69
|
export {
|
|
64
70
|
ConvexHubAuthProvider,
|
|
71
|
+
HUB_ACCESS_CODE_LENGTH2 as HUB_ACCESS_CODE_LENGTH,
|
|
65
72
|
HubSignedIn2 as HubSignedIn,
|
|
73
|
+
useHubCodeSignIn2 as useHubCodeSignIn,
|
|
66
74
|
useHubSession2 as useHubSession,
|
|
67
75
|
useHubSignOut2 as useHubSignOut,
|
|
68
76
|
useHubToken2 as useHubToken,
|
|
@@ -4,14 +4,14 @@ import {
|
|
|
4
4
|
} from "./convex-ctn06a2f.js";
|
|
5
5
|
import {
|
|
6
6
|
tokenForRequest
|
|
7
|
-
} from "./convex-
|
|
7
|
+
} from "./convex-rh6n9pwg.js";
|
|
8
8
|
import {
|
|
9
9
|
markPrivate,
|
|
10
10
|
RENDER_KEY,
|
|
11
11
|
renderSecret,
|
|
12
12
|
isRender,
|
|
13
13
|
renderToken
|
|
14
|
-
} from "./convex-
|
|
14
|
+
} from "./convex-e0k41ps8.js";
|
|
15
15
|
|
|
16
16
|
// src/internal/start-middleware.ts
|
|
17
17
|
import {
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export declare const HUB_ACCESS_CODE_LENGTH = 5;
|
|
2
|
+
/**
|
|
3
|
+
* Why a code did not sign the person in:
|
|
4
|
+
* - `invalid`: no such code, or not one for this app's event.
|
|
5
|
+
* - `ended`: the person's event has ended.
|
|
6
|
+
* - `rateLimited`: too many wrong codes from this network; try again in
|
|
7
|
+
* `retryAfter` milliseconds.
|
|
8
|
+
* - `forbidden`: the hub does not know this page's address as one of the
|
|
9
|
+
* app's URLs (register it with `user-hub dev` or `user-hub prod`), or
|
|
10
|
+
* `app` is not an app of the hub.
|
|
11
|
+
* - `unavailable`: the hub could not be reached or failed; try again.
|
|
12
|
+
*/
|
|
13
|
+
export type HubCodeError = {
|
|
14
|
+
reason: "invalid";
|
|
15
|
+
} | {
|
|
16
|
+
reason: "ended";
|
|
17
|
+
eventName: string;
|
|
18
|
+
} | {
|
|
19
|
+
reason: "rateLimited";
|
|
20
|
+
retryAfter: number;
|
|
21
|
+
} | {
|
|
22
|
+
reason: "forbidden";
|
|
23
|
+
} | {
|
|
24
|
+
reason: "unavailable";
|
|
25
|
+
};
|
|
26
|
+
export type CodeExchange = {
|
|
27
|
+
status: "ok";
|
|
28
|
+
token: string;
|
|
29
|
+
} | {
|
|
30
|
+
status: "error";
|
|
31
|
+
error: HubCodeError;
|
|
32
|
+
};
|
|
33
|
+
export declare function exchangeCode(hubUrl: string, app: string, code: string): Promise<CodeExchange>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type ReactNode } from "react";
|
|
2
|
+
import { type HubCodeError } from "./access-code";
|
|
2
3
|
import { type HubSession } from "./token";
|
|
3
4
|
type HubState = {
|
|
4
5
|
session: HubSession | null | undefined;
|
|
@@ -7,15 +8,17 @@ type HubState = {
|
|
|
7
8
|
suspend: () => void;
|
|
8
9
|
currentToken: () => string | null;
|
|
9
10
|
refresh: () => Promise<string | null>;
|
|
11
|
+
signInWithCode: (code: string) => Promise<HubCodeError | null | "superseded">;
|
|
10
12
|
};
|
|
11
13
|
export declare const useHubState: () => HubState;
|
|
12
14
|
export type HubAuthProviderProps = {
|
|
13
15
|
app: string;
|
|
14
16
|
hubUrl?: string;
|
|
15
17
|
initialToken?: string | null;
|
|
18
|
+
devRedirect?: boolean;
|
|
16
19
|
children: ReactNode;
|
|
17
20
|
};
|
|
18
|
-
export declare function HubSessionProvider({ app, hubUrl, initialToken, reloadOnSignOut, children, }: HubAuthProviderProps & {
|
|
21
|
+
export declare function HubSessionProvider({ app, hubUrl, initialToken, devRedirect, reloadOnSignOut, children, }: HubAuthProviderProps & {
|
|
19
22
|
reloadOnSignOut?: boolean;
|
|
20
23
|
}): import("react").JSX.Element;
|
|
21
24
|
export {};
|
package/dist/react.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type ReactNode } from "react";
|
|
2
|
+
import type { HubCodeError } from "./internal/access-code";
|
|
2
3
|
import { type HubAuthProviderProps } from "./internal/session";
|
|
3
4
|
import type { HubSession, HubUser } from "./internal/token";
|
|
5
|
+
export { HUB_ACCESS_CODE_LENGTH, type HubCodeError, } from "./internal/access-code";
|
|
4
6
|
export type { HubAuthProviderProps } from "./internal/session";
|
|
5
7
|
export type { HubRole, HubUser } from "./internal/token";
|
|
6
8
|
/**
|
|
@@ -37,3 +39,30 @@ export declare function useHubUser(): HubUser | null;
|
|
|
37
39
|
* it is refreshed, so read it for each request.
|
|
38
40
|
*/
|
|
39
41
|
export declare function useHubToken(): string | null;
|
|
42
|
+
export type HubCodeSignIn = {
|
|
43
|
+
/**
|
|
44
|
+
* Trades the code the person typed (case, spaces and dashes do not matter)
|
|
45
|
+
* for a session. Resolves to true once signed in: <HubSignedIn> then shows
|
|
46
|
+
* the app. A call while another code is being checked does nothing and
|
|
47
|
+
* resolves to false.
|
|
48
|
+
*/
|
|
49
|
+
signIn: (code: string) => Promise<boolean>;
|
|
50
|
+
/** True while the hub checks the code. */
|
|
51
|
+
pending: boolean;
|
|
52
|
+
/** Why the last code did not sign in, or null. */
|
|
53
|
+
error: HubCodeError | null;
|
|
54
|
+
/**
|
|
55
|
+
* Clears `error`, say when the person edits the code. An answer still on
|
|
56
|
+
* its way then shows no error either.
|
|
57
|
+
*/
|
|
58
|
+
reset: () => void;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Sign-in with the access code printed on a person's badge, for apps used on
|
|
62
|
+
* a computer that cannot scan it. The app draws its own screen (pass it as
|
|
63
|
+
* <HubSignedIn signedOut>) and calls `signIn` with what was typed. Needs
|
|
64
|
+
* `hubUrl` on the provider, and the page's address registered as one of the
|
|
65
|
+
* app's URLs in the hub. Set `devRedirect={false}` on the provider to see the
|
|
66
|
+
* screen on a local dev server.
|
|
67
|
+
*/
|
|
68
|
+
export declare function useHubCodeSignIn(): HubCodeSignIn;
|
package/dist/react.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
+
HUB_ACCESS_CODE_LENGTH2,
|
|
2
3
|
HubAuthProvider2,
|
|
3
4
|
HubSignedIn2,
|
|
4
5
|
useHubSignOut2,
|
|
5
6
|
useHubSession2,
|
|
6
7
|
useHubUser2,
|
|
7
|
-
useHubToken2
|
|
8
|
-
|
|
8
|
+
useHubToken2,
|
|
9
|
+
useHubCodeSignIn2
|
|
10
|
+
} from "./convex-q39rcwdv.js";
|
|
9
11
|
export {
|
|
12
|
+
HUB_ACCESS_CODE_LENGTH2 as HUB_ACCESS_CODE_LENGTH,
|
|
10
13
|
HubAuthProvider2 as HubAuthProvider,
|
|
11
14
|
HubSignedIn2 as HubSignedIn,
|
|
15
|
+
useHubCodeSignIn2 as useHubCodeSignIn,
|
|
12
16
|
useHubSession2 as useHubSession,
|
|
13
17
|
useHubSignOut2 as useHubSignOut,
|
|
14
18
|
useHubToken2 as useHubToken,
|
package/dist/start-convex.js
CHANGED
package/dist/start-middleware.js
CHANGED
|
@@ -2,8 +2,8 @@ import"./convex-ctn06a2f.js";
|
|
|
2
2
|
import {
|
|
3
3
|
hubRequestMiddleware,
|
|
4
4
|
hubServerFnMiddleware
|
|
5
|
-
} from "./convex-
|
|
6
|
-
import"./convex-
|
|
5
|
+
} from "./convex-vtpnsjbm.js";
|
|
6
|
+
import"./convex-e0k41ps8.js";
|
|
7
7
|
|
|
8
8
|
// src/start-middleware.ts
|
|
9
9
|
function hubMiddleware(options) {
|
package/dist/start.js
CHANGED
|
@@ -4,11 +4,11 @@ import {
|
|
|
4
4
|
resolveHubToken,
|
|
5
5
|
existingRenderToken,
|
|
6
6
|
rememberRenderToken
|
|
7
|
-
} from "./convex-
|
|
7
|
+
} from "./convex-e0k41ps8.js";
|
|
8
8
|
import {
|
|
9
9
|
cookieName,
|
|
10
10
|
COOKIE_MAX_AGE_S
|
|
11
|
-
} from "./convex-
|
|
11
|
+
} from "./convex-jf1p8p1w.js";
|
|
12
12
|
|
|
13
13
|
// src/start.ts
|
|
14
14
|
import {
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: user-hub-auth
|
|
3
|
-
description: Sign people into an app from their printed User Hub badge with @user-hub/auth. Use when connecting an app to a User Hub, adding badge or
|
|
3
|
+
description: Sign people into an app from their printed User Hub badge with @user-hub/auth, by scanning its QR code or typing its access code. Use when connecting an app to a User Hub, adding badge, QR or access-code sign-in (people on laptops or desktops who cannot scan, "a code instead of the badge", useHubCodeSignIn), wiring hubAuth, ConvexHubAuthProvider, HubAuthProvider, HubSignedIn, useHubUser or verifyHubToken, protecting TanStack Start server functions or server routes (hubConvexMiddleware, hubMiddleware), building facilitator-only pages, or moving an app to a new hub URL or to production. Use it even when the user only says "connect this to the hub" or "add sign-in for the workshop". Never hand-roll login, passwords or token checks for these apps.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# User Hub auth
|
|
7
7
|
|
|
8
|
-
People at a workshop scan a printed QR badge. One hub runs many workshops, called **events**; every person and every app belongs to one. The scan sends the person, signed in, to the app that is live in their event (or to the event's app list), with a token in the URL fragment (`#token=…`) that only that app accepts. `@user-hub/auth` turns that token into a signed-in person: `{ id, name, team, role }`. The app keeps its own data, keyed on the person's hub id.
|
|
8
|
+
People at a workshop scan a printed QR badge, or type the access code printed on it when they use an app on a computer. One hub runs many workshops, called **events**; every person and every app belongs to one. The scan sends the person, signed in, to the app that is live in their event (or to the event's app list), with a token in the URL fragment (`#token=…`) that only that app accepts. `@user-hub/auth` turns that token into a signed-in person: `{ id, name, team, role }`. The app keeps its own data, keyed on the person's hub id.
|
|
9
9
|
|
|
10
10
|
Registering apps, signing a folder in to the hub and managing people is done with the `user-hub` CLI: follow the **user-hub-cli** skill for any `user-hub …` command.
|
|
11
11
|
|
|
@@ -17,6 +17,7 @@ Registering apps, signing a folder in to the hub and managing people is done wit
|
|
|
17
17
|
| Existing app, not connected | Follow [references/connect-an-app.md](references/connect-an-app.md): install, register, set the values, wire the provider, use the person |
|
|
18
18
|
| Server functions or server routes that act as the person (TanStack Start) | [references/server-functions.md](references/server-functions.md) |
|
|
19
19
|
| An app that checks tokens itself in server code (a header-adding hook, `verifyHubToken` plus `ConvexHttpClient`) | Replace it: "Moving from a hand-rolled version" in [references/server-functions.md](references/server-functions.md) |
|
|
20
|
+
| People use the app on a computer, or the human wants an access code / PIN instead of scanning | [references/access-codes.md](references/access-codes.md): the app's own code screen with `useHubCodeSignIn` |
|
|
20
21
|
| Facilitator-only pages or actions | [references/roles.md](references/roles.md) |
|
|
21
22
|
| Running it locally, going to production, or the hub moved | [references/dev-and-production.md](references/dev-and-production.md) |
|
|
22
23
|
|
|
@@ -40,5 +41,5 @@ The hub's URL also comes from the human. It goes in three places with the same v
|
|
|
40
41
|
- **Mount the provider inside `<body>`**, around the page content, never outside `<html>` or in the router's `Wrap`. It always renders its children; `<HubSignedIn>` does the gating.
|
|
41
42
|
- **Server rendering (TanStack Start):** pass `getHubToken()` from `@user-hub/auth/start` to the provider as `initialToken` from the root route's `beforeLoad` ([references/connect-an-app.md](references/connect-an-app.md)), so a page load renders the person instead of `loading`. Everything inside `<HubSignedIn>` then renders on the server: keep `window` and `document` inside effects. With Convex, create the client with `expectAuth: true` and `initialAuthTokenReuse: true`.
|
|
42
43
|
- **Let the provider own the token.** It refreshes it with the hub while the app is open and signs the person out when the hub ends the session. Do not store, refresh or extend tokens yourself. Server functions behind `hub.serverFn` get it by themselves (no headers, no wrapper hook); for anything else read `useHubToken()` for each request.
|
|
43
|
-
- **No other sign-in.** No login screens, passwords or sessions. If something is missing, it belongs in `@user-hub/auth`.
|
|
44
|
+
- **No other sign-in.** No login screens, passwords or sessions. The only sign-in screen an app builds is the access-code screen, through `useHubCodeSignIn` ([references/access-codes.md](references/access-codes.md)). If something is missing, it belongs in `@user-hub/auth`.
|
|
44
45
|
- **Secrets stay out of chat and files you write.** The API key lives only in `.env.local`, saved by `user-hub login`.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# Access codes: sign in by typing a code
|
|
2
|
+
|
|
3
|
+
Every badge also carries an **access code**: 5 letters and digits (such as `K7P3Q`, printed as is), unique to the person. People type it into the app when they use it on a computer that cannot scan the badge. It signs them in exactly as a scan would: same person, same token, same session rules. Use it when the human says the app runs on laptops or desktops, people cannot scan, or they want "an access code", "a PIN" or "a code instead of the badge".
|
|
4
|
+
|
|
5
|
+
The app draws its own branded screen; the hub only checks the code. Never build a code check, a code list or a session yourself.
|
|
6
|
+
|
|
7
|
+
## How it works
|
|
8
|
+
|
|
9
|
+
1. The app's signed-out screen has a code input. It calls `signIn(code)` from `useHubCodeSignIn()`.
|
|
10
|
+
2. The package sends the code and the app key to `<hub>/api/code`. The hub checks it: the code exists, its person is in this app's event, the event has not ended, the request comes from one of the app's registered URLs, and this network has not tried too many wrong codes.
|
|
11
|
+
3. The hub returns a token; the provider signs the person in and keeps them signed in, as after a scan. `<HubSignedIn>` then shows the app.
|
|
12
|
+
|
|
13
|
+
The schedule does not matter here: a code signs the person in to this app whenever their event is running. A badge scan still works and lands the person signed in.
|
|
14
|
+
|
|
15
|
+
## Starter apps
|
|
16
|
+
|
|
17
|
+
Already built in: `src/components/access-code-sign-in.tsx` is the signed-out screen in `src/routes/__root.tsx` (`<HubSignedIn signedOut={<AccessCodeSignIn />}>`). Restyle that component with the app's own components and tokens; keep the hook.
|
|
18
|
+
|
|
19
|
+
## Add it to an app
|
|
20
|
+
|
|
21
|
+
Needs `@user-hub/auth` 0.8 or later and `hubUrl` on the provider (`VITE_HUB_URL`).
|
|
22
|
+
|
|
23
|
+
```tsx
|
|
24
|
+
import {
|
|
25
|
+
HUB_ACCESS_CODE_LENGTH,
|
|
26
|
+
type HubCodeError,
|
|
27
|
+
useHubCodeSignIn,
|
|
28
|
+
} from "@user-hub/auth/convex-react"; // or "@user-hub/auth/react" without Convex
|
|
29
|
+
|
|
30
|
+
function AccessCodeSignIn() {
|
|
31
|
+
const { signIn, pending, error, reset } = useHubCodeSignIn();
|
|
32
|
+
const [code, setCode] = useState("");
|
|
33
|
+
return (
|
|
34
|
+
<form onSubmit={(event) => { event.preventDefault(); void signIn(code); }}>
|
|
35
|
+
{/* The app's own input: a one-time-code input with HUB_ACCESS_CODE_LENGTH slots
|
|
36
|
+
(shadcn: `bunx --bun shadcn@latest add input-otp`), or a plain text field. */}
|
|
37
|
+
<input value={code} onChange={(event) => { setCode(event.target.value); reset(); }} />
|
|
38
|
+
{error && <p>{messageFor(error)}</p>}
|
|
39
|
+
<button type="submit" disabled={pending}>Sign in</button>
|
|
40
|
+
</form>
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Mount it as the signed-out screen:
|
|
45
|
+
<HubSignedIn signedOut={<AccessCodeSignIn />} loading={…}>{children}</HubSignedIn>
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
- `signIn(code)` resolves to `true` once signed in. Case, spaces and dashes in the code do not matter.
|
|
49
|
+
- `error` (`HubCodeError`) says why not; write the app's own message for each `reason`:
|
|
50
|
+
- `invalid`: wrong code, or a person of another event.
|
|
51
|
+
- `ended` (`eventName`): their event has ended.
|
|
52
|
+
- `rateLimited` (`retryAfter`, milliseconds): too many wrong codes from this network.
|
|
53
|
+
- `forbidden`: the hub does not know this page's address as one of the app's URLs. Register it (`user-hub dev add` / `user-hub prod set`); never work around it.
|
|
54
|
+
- `unavailable`: the hub could not be reached; try again.
|
|
55
|
+
- `pending` is true while the hub checks.
|
|
56
|
+
|
|
57
|
+
## Locally
|
|
58
|
+
|
|
59
|
+
On a local dev server, a signed-out person is sent to the hub to pick who to be, so the code screen never shows. To see and test it, pass `devRedirect={false}` to the provider while working on it (or keep it if the app should always show its code screen). Get a test person's code with `bunx user-hub people badge "<name>"` (user-hub-cli skill) or from the person's badge on the hub's People page.
|
|
60
|
+
|
|
61
|
+
## Printing the codes
|
|
62
|
+
|
|
63
|
+
The code is on each person's badge in the hub (People, then Badge) and in the CLI: `people badge <person>`, `people list --badges` and `people badges`, whose `badges.csv` has an `accessCode` column for the print layout. Like the badge link, a code is a lasting sign-in: give each only to its owner. Regenerating a person's badge also gives them a new code.
|
|
@@ -51,7 +51,7 @@ import { ConvexHubAuthProvider, HubSignedIn } from "@user-hub/auth/convex-react"
|
|
|
51
51
|
</body>
|
|
52
52
|
```
|
|
53
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.
|
|
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={…}`. For people on computers, make `signedOut` the app's access-code screen ([access-codes.md](access-codes.md)). Anything outside it (a public landing page) shows to everyone.
|
|
55
55
|
|
|
56
56
|
**Without Convex:** `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth/react`, same place, same props minus `client`.
|
|
57
57
|
|
|
@@ -87,4 +87,4 @@ With Convex, create the client so queries wait for the person's token and keep i
|
|
|
87
87
|
| Other servers | Send `useHubToken()` as `Authorization: Bearer <token>`; check it with `await verifyHubToken(request, { app: "<key>", hubUrl })` from `@user-hub/auth/server` (`hubUrl` is the issuer when the server has no `HUB_ISSUER`) |
|
|
88
88
|
| Sign out | `const signOut = useHubSignOut()` from the provider's entry point. It forgets this app's token only |
|
|
89
89
|
|
|
90
|
-
If the app sets a Content Security Policy, allow the hub in `connect-src`: the provider calls `<hub>/api/token/refresh
|
|
90
|
+
If the app sets a Content Security Policy, allow the hub in `connect-src`: the provider calls `<hub>/api/token/refresh` (and `<hub>/api/code` for access codes).
|
|
@@ -7,7 +7,8 @@ Run the app on one of the development URLs registered with the hub (an app has a
|
|
|
7
7
|
- **Switch person:** open `<hub>/open/<key>`.
|
|
8
8
|
- **Another port:** the hub only sends tokens to registered URLs. Starter apps: `bunx user-hub dev add http://localhost:<port>` and change the port in the `dev` script too. Others: the same with `--event <slug> --app "<the app's name>"`. `bunx user-hub dev list` shows them, `dev remove <url>` drops an old one.
|
|
9
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".
|
|
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 the `signedOut` screen ("Scan your badge to sign in" by default, the access-code screen in starter apps).
|
|
11
|
+
- **Working on the access-code screen:** pass `devRedirect={false}` to the provider so a signed-out dev server shows it instead of going to the hub ([access-codes.md](access-codes.md)).
|
|
11
12
|
|
|
12
13
|
## Production URL
|
|
13
14
|
|