@user-hub/auth 0.7.0 → 0.7.2
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 +8 -3
- package/dist/{convex-10r10q8j.js → convex-55v4qaqb.js} +53 -8
- package/dist/convex-77ptkyt2.js +108 -0
- package/dist/convex-c4m6k5st.js +53 -0
- package/dist/convex-react.js +2 -2
- package/dist/{convex-dt8pvksb.js → convex-rwq8r0rm.js} +29 -4
- package/dist/{convex-mhcxj7fg.js → convex-zj2n2r92.js} +22 -16
- package/dist/internal/live-session.d.ts +6 -1
- package/dist/internal/private-response.d.ts +7 -0
- package/dist/internal/render-token.d.ts +22 -0
- package/dist/internal/start-middleware.d.ts +8 -3
- package/dist/react.js +1 -1
- package/dist/start-convex.d.ts +5 -1
- package/dist/start-convex.js +2 -1
- package/dist/start-middleware.js +2 -1
- package/dist/start.js +35 -57
- package/package.json +1 -1
- package/skills/user-hub-auth/SKILL.md +2 -1
- package/skills/user-hub-auth/references/connect-an-app.md +1 -1
- package/skills/user-hub-auth/references/dev-and-production.md +4 -1
- package/skills/user-hub-auth/references/roles.md +14 -1
- package/skills/user-hub-auth/references/server-functions.md +17 -2
- package/dist/convex-errnd02r.js +0 -28
- package/dist/convex-gj0ap5wv.js +0 -53
package/README.md
CHANGED
|
@@ -148,11 +148,14 @@ export const saveSummary = createServerFn({ method: "POST" })
|
|
|
148
148
|
});
|
|
149
149
|
```
|
|
150
150
|
|
|
151
|
-
- **Server functions:** the browser sends the person's current token by itself (refreshed first when it is about to expire), so call them as usual. Without a valid token the call throws "Scan your badge to sign in.".
|
|
152
|
-
- **Server routes:** the caller sends `Authorization: Bearer <token>` (`useHubToken()`); without a valid token the route answers 401.
|
|
151
|
+
- **Server functions:** the browser sends the person's current token by itself (refreshed first when it is about to expire), so call them as usual, from loaders and queries too, on the first page load as well: a call made before the provider is ready waits for it, and one run while the server renders the page uses the person's cookie, as `getHubToken` does. Without a valid token the call throws "Scan your badge to sign in.".
|
|
152
|
+
- **Server routes:** the caller sends `Authorization: Bearer <token>` (`useHubToken()`); without a valid token the route answers 401. Server routes never accept the cookie.
|
|
153
153
|
- `context.convex` is a `ConvexHttpClient` acting as the person, so Convex functions still check them with `requireHubUser`. Without Convex, use `hubMiddleware({ app, hubUrl })` from `@user-hub/auth/start-middleware`: the same, with `context.hub` and `context.hubToken`.
|
|
154
154
|
- Tokens are checked against `HUB_ISSUER` and `HUB_JWKS` when the server has them, else against `hubUrl` and its published key, so a container with no runtime environment works. Pass both URLs from `import.meta.env`, never `process.env.VITE_*`.
|
|
155
155
|
- Start protects server functions from cross-site calls by default; an app that defines `src/start.ts` adds `createCsrfMiddleware` itself.
|
|
156
|
+
- The browser half needs the provider (`ConvexHubAuthProvider` or `HubAuthProvider`) mounted, as every connected app has; without one, calls wait 10 seconds and then fail.
|
|
157
|
+
- Roles: check `context.hub.role` in the handler (and keep `requireFacilitator` in Convex).
|
|
158
|
+
- Replacing your own version (a hook that adds the header, a middleware calling `verifyHubToken` and `ConvexHttpClient.setAuth`)? See "Moving from a hand-rolled version" in the skill's `references/server-functions.md`.
|
|
156
159
|
|
|
157
160
|
### 5. Use the person
|
|
158
161
|
|
|
@@ -214,6 +217,8 @@ const me = useHubUser();
|
|
|
214
217
|
if (me?.role !== "facilitator") return <p>This page is for facilitators.</p>;
|
|
215
218
|
```
|
|
216
219
|
|
|
220
|
+
In TanStack Start server functions and server routes behind the middleware, check `context.hub.role` the same way.
|
|
221
|
+
|
|
217
222
|
Hiding a page does not protect it: the server check does.
|
|
218
223
|
|
|
219
224
|
## Not using Convex?
|
|
@@ -247,7 +252,7 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
|
|
|
247
252
|
| | `useHubSession()` | `undefined` while loading, `null` when signed out, otherwise `{ token, user }`; most apps need only `useHubUser()` or `<HubSignedIn>`. Also from `/convex-react` |
|
|
248
253
|
| `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app, hubUrl? })` | Checks a token anywhere else. `hubUrl` is the issuer when `HUB_ISSUER` is not set |
|
|
249
254
|
| `@user-hub/auth/start` | `getHubToken({ app, hubUrl })` | TanStack Start, inside a server function: the request's token for `initialToken`, checked and refreshed, or null |
|
|
250
|
-
| `@user-hub/auth/start-convex` | `hubConvexMiddleware({ app, hubUrl, convexUrl })` | TanStack Start middleware: `.serverFn` for server functions (the browser sends the token), `.request` for server routes (Bearer header). Handlers get `context.hub`, `context.hubToken` and `context.convex` |
|
|
255
|
+
| `@user-hub/auth/start-convex` | `hubConvexMiddleware({ app, hubUrl, convexUrl })` | TanStack Start middleware: `.serverFn` for server functions (the browser sends the token), `.request` for server routes (Bearer header). Handlers get `context.hub`, `context.hubToken` and `context.convex` (type `HubConvexContext`) |
|
|
251
256
|
| `@user-hub/auth/start-middleware` | `hubMiddleware({ app, hubUrl })` | The same without Convex: `context.hub` and `context.hubToken` |
|
|
252
257
|
|
|
253
258
|
## Developing this package
|
|
@@ -1,10 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
readClaims,
|
|
3
|
-
sessionFor,
|
|
4
|
-
refreshInfo,
|
|
5
|
-
sessionKeyOf
|
|
6
|
-
} from "./convex-gj0ap5wv.js";
|
|
7
|
-
|
|
8
1
|
// src/internal/clock.ts
|
|
9
2
|
var clockSkewMs = 0;
|
|
10
3
|
var hubNow = () => Date.now() + clockSkewMs;
|
|
@@ -12,6 +5,58 @@ function learnHubClock(issuedAt) {
|
|
|
12
5
|
clockSkewMs = issuedAt - Date.now();
|
|
13
6
|
}
|
|
14
7
|
|
|
8
|
+
// src/internal/token.ts
|
|
9
|
+
function decodeSegment(segment) {
|
|
10
|
+
const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
|
|
11
|
+
return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
|
|
12
|
+
}
|
|
13
|
+
function payloadOf(token) {
|
|
14
|
+
try {
|
|
15
|
+
return decodeSegment(token.split(".")[1] ?? "");
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function readClaims(token) {
|
|
21
|
+
const payload = payloadOf(token);
|
|
22
|
+
if (typeof payload?.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string" || typeof payload.auth_time !== "number") {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
id: payload.sub,
|
|
27
|
+
name: payload.name,
|
|
28
|
+
team: payload.team,
|
|
29
|
+
role: payload.role === "facilitator" ? "facilitator" : "member",
|
|
30
|
+
app: payload.aud,
|
|
31
|
+
expiresAt: payload.exp * 1000
|
|
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
|
+
function newestSession(...sessions) {
|
|
39
|
+
const issued = (s) => refreshInfo(s.token)?.issuedAt ?? 0;
|
|
40
|
+
return sessions.reduce((best, s) => s && (!best || issued(s) > issued(best)) ? s : best, null);
|
|
41
|
+
}
|
|
42
|
+
function refreshInfo(token) {
|
|
43
|
+
const payload = payloadOf(token);
|
|
44
|
+
if (typeof payload?.iss !== "string" || typeof payload.iat !== "number") {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
url: `${payload.iss.replace(/\/+$/, "")}/api/token/refresh`,
|
|
49
|
+
issuedAt: payload.iat * 1000
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function sessionKeyOf(token) {
|
|
53
|
+
const payload = payloadOf(token);
|
|
54
|
+
if (typeof payload?.sub !== "string" || typeof payload.auth_time !== "number") {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
return [payload.iss, payload.aud, payload.sub, payload.auth_time].join("|");
|
|
58
|
+
}
|
|
59
|
+
|
|
15
60
|
// src/internal/refresh.ts
|
|
16
61
|
var REQUEST_TIMEOUT_MS = 10 * 1000;
|
|
17
62
|
function originOf(url) {
|
|
@@ -75,4 +120,4 @@ function writeCookie(app, token) {
|
|
|
75
120
|
} catch {}
|
|
76
121
|
}
|
|
77
122
|
|
|
78
|
-
export { hubNow, refreshUrlFor, exchange, cookieName, COOKIE_MAX_AGE_S, writeCookie };
|
|
123
|
+
export { hubNow, readClaims, sessionFor, newestSession, refreshInfo, sessionKeyOf, refreshUrlFor, exchange, cookieName, COOKIE_MAX_AGE_S, writeCookie };
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hubIssuer,
|
|
3
|
+
hubJwks,
|
|
4
|
+
verifyHubToken2
|
|
5
|
+
} from "./convex-ctn06a2f.js";
|
|
6
|
+
import {
|
|
7
|
+
hubNow,
|
|
8
|
+
readClaims,
|
|
9
|
+
exchange,
|
|
10
|
+
cookieName
|
|
11
|
+
} from "./convex-55v4qaqb.js";
|
|
12
|
+
|
|
13
|
+
// src/internal/private-response.ts
|
|
14
|
+
function markPrivate(helpers) {
|
|
15
|
+
helpers.setResponseHeader("Cache-Control", "private, no-store");
|
|
16
|
+
const raw = helpers.getResponseHeader("Vary");
|
|
17
|
+
const vary = Array.isArray(raw) ? raw.join(",") : typeof raw === "string" ? raw : "";
|
|
18
|
+
if (!/(^|,)\s*cookie\s*(,|$)/i.test(vary)) {
|
|
19
|
+
helpers.appendResponseHeader("Vary", "Cookie");
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/internal/server-session.ts
|
|
24
|
+
var MIN_LIFETIME_MS = 2 * 60 * 1000;
|
|
25
|
+
async function verified(token, app, issuer, jwks) {
|
|
26
|
+
try {
|
|
27
|
+
await verifyHubToken2(token, { app, issuer, jwks });
|
|
28
|
+
return true;
|
|
29
|
+
} catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function resolveHubToken(cookie, { app, hubUrl, ...options }) {
|
|
34
|
+
const issuer = hubIssuer({ hubUrl, issuer: options.issuer });
|
|
35
|
+
const jwks = hubJwks(options.jwks);
|
|
36
|
+
const token = cookie.get();
|
|
37
|
+
const user = token ? readClaims(token) : null;
|
|
38
|
+
if (!token || !issuer || user?.app !== app)
|
|
39
|
+
return null;
|
|
40
|
+
if (user.expiresAt - hubNow() > MIN_LIFETIME_MS) {
|
|
41
|
+
return await verified(token, app, issuer, jwks) ? token : null;
|
|
42
|
+
}
|
|
43
|
+
if (!hubUrl)
|
|
44
|
+
return null;
|
|
45
|
+
const result = await exchange(token, app, hubUrl);
|
|
46
|
+
if (result.status === "ended") {
|
|
47
|
+
cookie.clear();
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
if (result.status === "failed")
|
|
51
|
+
return null;
|
|
52
|
+
const next = result.session.token;
|
|
53
|
+
if (!await verified(next, app, issuer, jwks))
|
|
54
|
+
return null;
|
|
55
|
+
cookie.set(next);
|
|
56
|
+
return next;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// src/internal/render-token.ts
|
|
60
|
+
var RENDER_KEY = "userHubRender";
|
|
61
|
+
var SECRET = Symbol.for("@user-hub/auth/render-secret");
|
|
62
|
+
function renderSecret() {
|
|
63
|
+
const store = globalThis;
|
|
64
|
+
return store[SECRET] ??= crypto.randomUUID();
|
|
65
|
+
}
|
|
66
|
+
function isRender(context) {
|
|
67
|
+
const value = context?.[RENDER_KEY];
|
|
68
|
+
return typeof value === "string" && value === renderSecret();
|
|
69
|
+
}
|
|
70
|
+
var resolved = new WeakMap;
|
|
71
|
+
function forRequest(request) {
|
|
72
|
+
let tokens = resolved.get(request);
|
|
73
|
+
if (!tokens) {
|
|
74
|
+
tokens = new Map;
|
|
75
|
+
resolved.set(request, tokens);
|
|
76
|
+
}
|
|
77
|
+
return tokens;
|
|
78
|
+
}
|
|
79
|
+
function existingRenderToken(request, app) {
|
|
80
|
+
return resolved.get(request)?.get(app);
|
|
81
|
+
}
|
|
82
|
+
function rememberRenderToken(request, app, token) {
|
|
83
|
+
forRequest(request).set(app, token);
|
|
84
|
+
}
|
|
85
|
+
function readCookie(request, name) {
|
|
86
|
+
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
87
|
+
const index = part.indexOf("=");
|
|
88
|
+
if (index > 0 && part.slice(0, index).trim() === name) {
|
|
89
|
+
return part.slice(index + 1).trim() || undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
function renderToken(request, options) {
|
|
95
|
+
const tokens = forRequest(request);
|
|
96
|
+
let token = tokens.get(options.app);
|
|
97
|
+
if (!token) {
|
|
98
|
+
token = resolveHubToken({
|
|
99
|
+
get: () => readCookie(request, cookieName(options.app)),
|
|
100
|
+
set: () => {},
|
|
101
|
+
clear: () => {}
|
|
102
|
+
}, options);
|
|
103
|
+
tokens.set(options.app, token);
|
|
104
|
+
}
|
|
105
|
+
return token;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export { markPrivate, resolveHubToken, RENDER_KEY, renderSecret, isRender, existingRenderToken, rememberRenderToken, renderToken };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {
|
|
2
|
+
readClaims
|
|
3
|
+
} from "./convex-55v4qaqb.js";
|
|
4
|
+
|
|
5
|
+
// src/internal/live-session.ts
|
|
6
|
+
var KEY = Symbol.for("@user-hub/auth/live-sessions");
|
|
7
|
+
var WAITING = Symbol.for("@user-hub/auth/live-sessions-waiting");
|
|
8
|
+
var store = globalThis;
|
|
9
|
+
var live = store[KEY] ??= new Map;
|
|
10
|
+
var waiting = store[WAITING] ??= new Map;
|
|
11
|
+
var PROVIDER_WAIT_MS = 10 * 1000;
|
|
12
|
+
var MIN_SEND_LIFETIME_MS = 60 * 1000;
|
|
13
|
+
function registerLiveSession(app, session) {
|
|
14
|
+
live.set(app, session);
|
|
15
|
+
const waiters = waiting.get(app);
|
|
16
|
+
waiting.delete(app);
|
|
17
|
+
for (const wake of waiters ?? [])
|
|
18
|
+
wake();
|
|
19
|
+
return () => {
|
|
20
|
+
if (live.get(app) === session)
|
|
21
|
+
live.delete(app);
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
async function tokenForRequest(app) {
|
|
25
|
+
if (!live.has(app) && typeof window !== "undefined") {
|
|
26
|
+
await providerRegistered(app);
|
|
27
|
+
}
|
|
28
|
+
return await live.get(app)?.tokenForRequest() ?? null;
|
|
29
|
+
}
|
|
30
|
+
function providerRegistered(app) {
|
|
31
|
+
return new Promise((resolve) => {
|
|
32
|
+
const waiters = waiting.get(app) ?? new Set;
|
|
33
|
+
waiting.set(app, waiters);
|
|
34
|
+
const wake = () => {
|
|
35
|
+
clearTimeout(timer);
|
|
36
|
+
waiters.delete(wake);
|
|
37
|
+
if (!waiters.size && waiting.get(app) === waiters)
|
|
38
|
+
waiting.delete(app);
|
|
39
|
+
resolve();
|
|
40
|
+
};
|
|
41
|
+
const timer = setTimeout(wake, PROVIDER_WAIT_MS);
|
|
42
|
+
waiters.add(wake);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
async function sendableToken(currentToken, refresh, now) {
|
|
46
|
+
const expiresAt = currentToken ? readClaims(currentToken)?.expiresAt : null;
|
|
47
|
+
if (currentToken && expiresAt && expiresAt - now > MIN_SEND_LIFETIME_MS) {
|
|
48
|
+
return currentToken;
|
|
49
|
+
}
|
|
50
|
+
return await refresh();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export { registerLiveSession, tokenForRequest, sendableToken };
|
package/dist/convex-react.js
CHANGED
|
@@ -6,10 +6,10 @@ import {
|
|
|
6
6
|
useHubSession2,
|
|
7
7
|
useHubUser2,
|
|
8
8
|
useHubToken2
|
|
9
|
-
} from "./convex-
|
|
9
|
+
} from "./convex-zj2n2r92.js";
|
|
10
10
|
import {
|
|
11
11
|
sessionKeyOf
|
|
12
|
-
} from "./convex-
|
|
12
|
+
} from "./convex-55v4qaqb.js";
|
|
13
13
|
|
|
14
14
|
// src/convex-react.tsx
|
|
15
15
|
import {
|
|
@@ -4,7 +4,14 @@ import {
|
|
|
4
4
|
} from "./convex-ctn06a2f.js";
|
|
5
5
|
import {
|
|
6
6
|
tokenForRequest
|
|
7
|
-
} from "./convex-
|
|
7
|
+
} from "./convex-c4m6k5st.js";
|
|
8
|
+
import {
|
|
9
|
+
markPrivate,
|
|
10
|
+
RENDER_KEY,
|
|
11
|
+
renderSecret,
|
|
12
|
+
isRender,
|
|
13
|
+
renderToken
|
|
14
|
+
} from "./convex-77ptkyt2.js";
|
|
8
15
|
|
|
9
16
|
// src/internal/start-middleware.ts
|
|
10
17
|
import {
|
|
@@ -42,8 +49,14 @@ async function authenticate(request, options) {
|
|
|
42
49
|
|
|
43
50
|
// src/internal/start-middleware.ts
|
|
44
51
|
function hubRequestMiddleware(options) {
|
|
45
|
-
return createMiddleware().server(async ({ next, request, handlerType, serverFnMeta }) => {
|
|
46
|
-
|
|
52
|
+
return createMiddleware().server(async ({ next, request, handlerType, serverFnMeta, context }) => {
|
|
53
|
+
let auth = await authenticate(request, options);
|
|
54
|
+
if (!auth && serverFnMeta && isRender(context)) {
|
|
55
|
+
auth = await authenticate(withBearer(request, await renderToken(request, options)), options);
|
|
56
|
+
if (auth) {
|
|
57
|
+
markPrivate(await import("@tanstack/react-start/server"));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
47
60
|
if (!auth) {
|
|
48
61
|
if (handlerType === "router" && !serverFnMeta) {
|
|
49
62
|
return new Response(SIGN_IN_MESSAGE, { status: 401 });
|
|
@@ -53,11 +66,23 @@ function hubRequestMiddleware(options) {
|
|
|
53
66
|
return next({ context: auth });
|
|
54
67
|
});
|
|
55
68
|
}
|
|
69
|
+
function withBearer(request, token) {
|
|
70
|
+
if (!token)
|
|
71
|
+
return request;
|
|
72
|
+
const headers = new Headers(request.headers);
|
|
73
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
74
|
+
return new Request(request.url, { method: request.method, headers });
|
|
75
|
+
}
|
|
56
76
|
function hubServerFnMiddleware(app, request) {
|
|
57
77
|
return createMiddleware({ type: "function" }).middleware([request]).client(async ({ next }) => {
|
|
78
|
+
if (typeof window === "undefined") {
|
|
79
|
+
const proof = { [RENDER_KEY]: renderSecret() };
|
|
80
|
+
return next({ sendContext: proof });
|
|
81
|
+
}
|
|
58
82
|
const token = await tokenForRequest(app);
|
|
59
83
|
return next({
|
|
60
|
-
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
|
84
|
+
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
85
|
+
sendContext: {}
|
|
61
86
|
});
|
|
62
87
|
});
|
|
63
88
|
}
|
|
@@ -1,20 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
hubNow,
|
|
3
|
-
refreshUrlFor,
|
|
4
|
-
exchange,
|
|
5
|
-
writeCookie
|
|
6
|
-
} from "./convex-10r10q8j.js";
|
|
7
1
|
import {
|
|
8
2
|
registerLiveSession,
|
|
9
3
|
sendableToken
|
|
10
|
-
} from "./convex-
|
|
4
|
+
} from "./convex-c4m6k5st.js";
|
|
11
5
|
import {
|
|
6
|
+
hubNow,
|
|
12
7
|
readClaims,
|
|
13
8
|
sessionFor,
|
|
14
9
|
newestSession,
|
|
15
10
|
refreshInfo,
|
|
16
|
-
sessionKeyOf
|
|
17
|
-
|
|
11
|
+
sessionKeyOf,
|
|
12
|
+
refreshUrlFor,
|
|
13
|
+
exchange,
|
|
14
|
+
writeCookie
|
|
15
|
+
} from "./convex-55v4qaqb.js";
|
|
18
16
|
|
|
19
17
|
// src/react.tsx
|
|
20
18
|
import { useMemo as useMemo2 } from "react";
|
|
@@ -242,13 +240,21 @@ function HubSessionProvider({
|
|
|
242
240
|
mounted.current = false;
|
|
243
241
|
};
|
|
244
242
|
}, []);
|
|
245
|
-
useLayoutEffect(() =>
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
243
|
+
useLayoutEffect(() => {
|
|
244
|
+
const unregister = registerLiveSession(app, {
|
|
245
|
+
tokenForRequest: async () => {
|
|
246
|
+
await loaded.promise;
|
|
247
|
+
if (!mounted.current)
|
|
248
|
+
return null;
|
|
249
|
+
await inFlight.current?.answer;
|
|
250
|
+
return await sendableToken(currentToken(), refresh, hubNow());
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
return () => {
|
|
254
|
+
unregister();
|
|
255
|
+
loaded.settle();
|
|
256
|
+
};
|
|
257
|
+
}, [app, loaded, currentToken, refresh]);
|
|
252
258
|
useEffect(() => {
|
|
253
259
|
try {
|
|
254
260
|
const fromUrl = takeTokenFromUrl();
|
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
export type LiveSession = {
|
|
2
2
|
tokenForRequest: () => Promise<string | null>;
|
|
3
3
|
};
|
|
4
|
+
export declare const PROVIDER_WAIT_MS: number;
|
|
4
5
|
export declare const MIN_SEND_LIFETIME_MS: number;
|
|
5
6
|
/** Registers the provider's session; returns the unregister function. */
|
|
6
7
|
export declare function registerLiveSession(app: string, session: LiveSession): () => void;
|
|
7
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* The token the app's provider would send now. A call made in the browser
|
|
10
|
+
* before the provider registered (a query run during the first render) waits
|
|
11
|
+
* for it; null without one.
|
|
12
|
+
*/
|
|
8
13
|
export declare function tokenForRequest(app: string): Promise<string | null>;
|
|
9
14
|
/**
|
|
10
15
|
* The provider's side: the current token while it has over a minute left,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
type ResponseHelpers = {
|
|
2
|
+
getResponseHeader: (name: string) => unknown;
|
|
3
|
+
setResponseHeader: (name: string, value: string) => void;
|
|
4
|
+
appendResponseHeader: (name: string, value: string) => void;
|
|
5
|
+
};
|
|
6
|
+
export declare function markPrivate(helpers: ResponseHelpers): void;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type HubTokenOptions } from "./server-session";
|
|
2
|
+
/**
|
|
3
|
+
* The send-context key the server-function middleware's client half sets
|
|
4
|
+
* when it runs on the server (a server function called while a page renders),
|
|
5
|
+
* and its value: a random secret made once per server process. A browser can
|
|
6
|
+
* send any context, but never this secret, so only a render on this server
|
|
7
|
+
* may use the cookie.
|
|
8
|
+
*/
|
|
9
|
+
export declare const RENDER_KEY = "userHubRender";
|
|
10
|
+
export declare function renderSecret(): string;
|
|
11
|
+
/** True when the context carries this server's render secret. */
|
|
12
|
+
export declare function isRender(context: unknown): boolean;
|
|
13
|
+
/** The lookup already made for this request and app, if any. */
|
|
14
|
+
export declare function existingRenderToken(request: Request, app: string): Promise<string | null> | undefined;
|
|
15
|
+
/** getHubToken's answer for this request, for render-time server functions. */
|
|
16
|
+
export declare function rememberRenderToken(request: Request, app: string, token: Promise<string | null>): void;
|
|
17
|
+
/**
|
|
18
|
+
* The request cookie's token for this app, checked with the hub's key and
|
|
19
|
+
* refreshed with the hub when it is about to expire; null when there is none
|
|
20
|
+
* to vouch for. Never writes the cookie: getHubToken (or the browser) does.
|
|
21
|
+
*/
|
|
22
|
+
export declare function renderToken(request: Request, options: HubTokenOptions): Promise<string | null>;
|
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
import { type AnyRequestMiddleware, type FunctionMiddlewareAfterClient, type RequestMiddlewareAfterServer } from "@tanstack/react-start";
|
|
2
2
|
import { type HubAuthContext, type HubMiddlewareOptions } from "./request-auth";
|
|
3
3
|
export type HubRequestMiddleware = RequestMiddlewareAfterServer<{}, undefined, HubAuthContext>;
|
|
4
|
-
export type HubServerFnMiddleware<Request extends AnyRequestMiddleware> = FunctionMiddlewareAfterClient<{}, readonly [Request], undefined,
|
|
4
|
+
export type HubServerFnMiddleware<Request extends AnyRequestMiddleware> = FunctionMiddlewareAfterClient<{}, readonly [Request], undefined, {}, undefined>;
|
|
5
5
|
export type HubMiddleware<Request extends AnyRequestMiddleware = HubRequestMiddleware> = {
|
|
6
6
|
request: Request;
|
|
7
7
|
serverFn: HubServerFnMiddleware<Request>;
|
|
8
8
|
};
|
|
9
9
|
/**
|
|
10
10
|
* Server routes and server functions: the person behind the request's
|
|
11
|
-
* Authorization header.
|
|
12
|
-
* a
|
|
11
|
+
* Authorization header. A server function called while the server renders a
|
|
12
|
+
* page (a loader or query run there) has no browser to send one, so it uses
|
|
13
|
+
* the person's cookie, as getHubToken does for the page itself, and marks the
|
|
14
|
+
* page private. Only such a render may: hubServerFnMiddleware's client half
|
|
15
|
+
* proves it with this server's secret. Without a valid token a server route
|
|
16
|
+
* answers 401 and a server function throws, which its caller receives as the
|
|
17
|
+
* error.
|
|
13
18
|
*/
|
|
14
19
|
export declare function hubRequestMiddleware(options: HubMiddlewareOptions): HubRequestMiddleware;
|
|
15
20
|
/**
|
package/dist/react.js
CHANGED
package/dist/start-convex.d.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import { type RequestMiddlewareAfterServer } from "@tanstack/react-start";
|
|
2
2
|
import { ConvexHttpClient } from "convex/browser";
|
|
3
|
-
import type { HubMiddlewareOptions } from "./internal/request-auth";
|
|
3
|
+
import type { HubAuthContext, HubMiddlewareOptions } from "./internal/request-auth";
|
|
4
4
|
import { type HubMiddleware, type HubRequestMiddleware } from "./internal/start-middleware";
|
|
5
5
|
export type { HubAuthContext, HubMiddlewareOptions, } from "./internal/request-auth";
|
|
6
6
|
export type { HubMiddleware, HubRequestMiddleware, HubServerFnMiddleware, } from "./internal/start-middleware";
|
|
7
7
|
export type { HubRole, HubUser } from "./internal/token";
|
|
8
|
+
/** What hubConvexMiddleware adds to the handler's context. */
|
|
9
|
+
export type HubConvexContext = HubAuthContext & {
|
|
10
|
+
convex: ConvexHttpClient;
|
|
11
|
+
};
|
|
8
12
|
/** hubConvexMiddleware's request middleware: the person, then Convex. */
|
|
9
13
|
export type HubConvexRequestMiddleware = RequestMiddlewareAfterServer<{}, readonly [HubRequestMiddleware], {
|
|
10
14
|
convex: ConvexHttpClient;
|
package/dist/start-convex.js
CHANGED
package/dist/start-middleware.js
CHANGED
package/dist/start.js
CHANGED
|
@@ -1,81 +1,59 @@
|
|
|
1
|
+
import"./convex-ctn06a2f.js";
|
|
1
2
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
markPrivate,
|
|
4
|
+
resolveHubToken,
|
|
5
|
+
existingRenderToken,
|
|
6
|
+
rememberRenderToken
|
|
7
|
+
} from "./convex-77ptkyt2.js";
|
|
6
8
|
import {
|
|
7
|
-
hubNow,
|
|
8
|
-
exchange,
|
|
9
9
|
cookieName,
|
|
10
10
|
COOKIE_MAX_AGE_S
|
|
11
|
-
} from "./convex-
|
|
12
|
-
import {
|
|
13
|
-
readClaims
|
|
14
|
-
} from "./convex-gj0ap5wv.js";
|
|
11
|
+
} from "./convex-55v4qaqb.js";
|
|
15
12
|
|
|
16
13
|
// src/start.ts
|
|
17
14
|
import {
|
|
18
15
|
appendResponseHeader,
|
|
19
16
|
deleteCookie,
|
|
20
17
|
getCookie,
|
|
18
|
+
getRequest,
|
|
21
19
|
getRequestProtocol,
|
|
20
|
+
getResponseHeader,
|
|
22
21
|
setCookie,
|
|
23
22
|
setResponseHeader
|
|
24
23
|
} from "@tanstack/react-start/server";
|
|
25
|
-
|
|
26
|
-
// src/internal/server-session.ts
|
|
27
|
-
var MIN_LIFETIME_MS = 2 * 60 * 1000;
|
|
28
|
-
async function verified(token, app, issuer, jwks) {
|
|
29
|
-
try {
|
|
30
|
-
await verifyHubToken2(token, { app, issuer, jwks });
|
|
31
|
-
return true;
|
|
32
|
-
} catch {
|
|
33
|
-
return false;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
async function resolveHubToken(cookie, { app, hubUrl, ...options }) {
|
|
37
|
-
const issuer = hubIssuer({ hubUrl, issuer: options.issuer });
|
|
38
|
-
const jwks = hubJwks(options.jwks);
|
|
39
|
-
const token = cookie.get();
|
|
40
|
-
const user = token ? readClaims(token) : null;
|
|
41
|
-
if (!token || !issuer || user?.app !== app)
|
|
42
|
-
return null;
|
|
43
|
-
if (user.expiresAt - hubNow() > MIN_LIFETIME_MS) {
|
|
44
|
-
return await verified(token, app, issuer, jwks) ? token : null;
|
|
45
|
-
}
|
|
46
|
-
if (!hubUrl)
|
|
47
|
-
return null;
|
|
48
|
-
const result = await exchange(token, app, hubUrl);
|
|
49
|
-
if (result.status === "ended") {
|
|
50
|
-
cookie.clear();
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
if (result.status === "failed")
|
|
54
|
-
return null;
|
|
55
|
-
const next = result.session.token;
|
|
56
|
-
if (!await verified(next, app, issuer, jwks))
|
|
57
|
-
return null;
|
|
58
|
-
cookie.set(next);
|
|
59
|
-
return next;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// src/start.ts
|
|
63
24
|
async function getHubToken(options) {
|
|
64
25
|
const name = cookieName(options.app);
|
|
65
26
|
const secure = getRequestProtocol({ xForwardedProto: true }) === "https";
|
|
66
|
-
const
|
|
27
|
+
const writeCookie = (token) => setCookie(name, token, {
|
|
28
|
+
path: "/",
|
|
29
|
+
maxAge: COOKIE_MAX_AGE_S,
|
|
30
|
+
sameSite: "lax",
|
|
31
|
+
secure
|
|
32
|
+
});
|
|
33
|
+
const request = getRequest();
|
|
34
|
+
const earlier = existingRenderToken(request, options.app);
|
|
35
|
+
if (earlier) {
|
|
36
|
+
const token = await earlier;
|
|
37
|
+
if (token && token !== getCookie(name))
|
|
38
|
+
writeCookie(token);
|
|
39
|
+
if (token) {
|
|
40
|
+
markPrivate({
|
|
41
|
+
getResponseHeader,
|
|
42
|
+
setResponseHeader,
|
|
43
|
+
appendResponseHeader
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
return token;
|
|
47
|
+
}
|
|
48
|
+
const resolving = resolveHubToken({
|
|
67
49
|
get: () => getCookie(name),
|
|
68
|
-
set:
|
|
69
|
-
path: "/",
|
|
70
|
-
maxAge: COOKIE_MAX_AGE_S,
|
|
71
|
-
sameSite: "lax",
|
|
72
|
-
secure
|
|
73
|
-
}),
|
|
50
|
+
set: writeCookie,
|
|
74
51
|
clear: () => deleteCookie(name, { path: "/" })
|
|
75
52
|
}, options);
|
|
53
|
+
rememberRenderToken(request, options.app, resolving);
|
|
54
|
+
const token = await resolving;
|
|
76
55
|
if (token) {
|
|
77
|
-
|
|
78
|
-
appendResponseHeader("Vary", "Cookie");
|
|
56
|
+
markPrivate({ getResponseHeader, setResponseHeader, appendResponseHeader });
|
|
79
57
|
}
|
|
80
58
|
return token;
|
|
81
59
|
}
|
package/package.json
CHANGED
|
@@ -16,6 +16,7 @@ Registering apps, signing a folder in to the hub and managing people is done wit
|
|
|
16
16
|
| No app yet | Scaffold one: `bun create user-hub@latest my-app`, then `bun run setup` and `bun run dev` in it. It comes wired; read on only to change the wiring |
|
|
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
|
+
| 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) |
|
|
19
20
|
| Facilitator-only pages or actions | [references/roles.md](references/roles.md) |
|
|
20
21
|
| Running it locally, going to production, or the hub moved | [references/dev-and-production.md](references/dev-and-production.md) |
|
|
21
22
|
|
|
@@ -38,6 +39,6 @@ The hub's URL also comes from the human. It goes in three places with the same v
|
|
|
38
39
|
- **Check access on the server**: `requireHubUser(ctx)` / `requireFacilitator(ctx)` in Convex, `hub.serverFn` / `hub.request` middleware on TanStack Start server functions and routes ([references/server-functions.md](references/server-functions.md)), `verifyHubToken` elsewhere. `useHubUser()` is for display; hiding a page protects nothing.
|
|
39
40
|
- **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.
|
|
40
41
|
- **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`.
|
|
41
|
-
- **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; read `useHubToken()` for each request.
|
|
42
|
+
- **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.
|
|
42
43
|
- **No other sign-in.** No login screens, passwords or sessions. If something is missing, it belongs in `@user-hub/auth`.
|
|
43
44
|
- **Secrets stay out of chat and files you write.** The API key lives only in `.env.local`, saved by `user-hub login`.
|
|
@@ -75,7 +75,7 @@ const { hubToken } = Route.useRouteContext();
|
|
|
75
75
|
|
|
76
76
|
With `ConvexQueryClient` (Convex through TanStack Query), also call `context.convexQueryClient.serverHttpClient?.setAuth(hubToken)` in `beforeLoad` when there is a token, so server-side queries run as the person.
|
|
77
77
|
|
|
78
|
-
With Convex, create the client so queries wait for the person's token and keep it, instead of running signed out first and then signing in twice: `new ConvexReactClient(url, { expectAuth: true, initialAuthTokenReuse: true })`, or the same options as the second argument of `new ConvexQueryClient(url, …)`. On Vite, also pre-bundle Convex and this package together, so the browser holds one `convex/react` ("Could not find Convex client" otherwise): `optimizeDeps: { include: ["convex/react", "@user-hub/auth/convex-react"] }`, plus `"@convex-dev/react-query"` when you use it. `ConvexHubAuthProvider` reloads the page when the person signs out (here, in another tab, or by the hub), as Convex recommends with `expectAuth`: the new page starts signed out, so no cached query runs again without the token. Never read or set the `user-hub-token.<key>` cookie yourself: the provider writes it and `getHubToken`
|
|
78
|
+
With Convex, create the client so queries wait for the person's token and keep it, instead of running signed out first and then signing in twice: `new ConvexReactClient(url, { expectAuth: true, initialAuthTokenReuse: true })`, or the same options as the second argument of `new ConvexQueryClient(url, …)`. On Vite, also pre-bundle Convex and this package together, so the browser holds one `convex/react` ("Could not find Convex client" otherwise): `optimizeDeps: { include: ["convex/react", "@user-hub/auth/convex-react"] }`, plus `"@convex-dev/react-query"` when you use it. `ConvexHubAuthProvider` reloads the page when the person signs out (here, in another tab, or by the hub), as Convex recommends with `expectAuth`: the new page starts signed out, so no cached query runs again without the token. Never read or set the `user-hub-token.<key>` cookie yourself: the provider writes it, and `getHubToken` and the server-function middleware read it.
|
|
79
79
|
|
|
80
80
|
## 5. Use the person
|
|
81
81
|
|
|
@@ -16,7 +16,9 @@ Badge scans reach the app only once the hub knows its production URL. Ask the hu
|
|
|
16
16
|
- **Starter apps:** `bun run setup --prod https://<deployed url>`. It also sets `HUB_ISSUER` and `HUB_JWKS` on the production Convex deployment.
|
|
17
17
|
- **Other apps:** `bunx user-hub apps register --event <slug> --name "<the app's name>" --prod https://<deployed url>` without `--new`, then `bunx convex env set --prod HUB_ISSUER '…'` and `… HUB_JWKS '…'`.
|
|
18
18
|
|
|
19
|
-
Then `bunx convex deploy`, set `VITE_CONVEX_URL` and `VITE_HUB_URL` on the host, and tell the human the app can be scheduled or forced live under **Schedule** of its event. While the event's badges go to the app list, a listed app with a production URL appears there straight away.
|
|
19
|
+
Then `bunx convex deploy`, set `VITE_CONVEX_URL` and `VITE_HUB_URL` on the host (at build time: Vite builds them in), and tell the human the app can be scheduled or forced live under **Schedule** of its event. While the event's badges go to the app list, a listed app with a production URL appears there straight away.
|
|
20
|
+
|
|
21
|
+
Server functions and server routes behind `hub.serverFn` / `hub.request` need nothing more on the host: they check tokens against the built-in `VITE_HUB_URL` and the hub's published key. `HUB_ISSUER` and `HUB_JWKS` in the host's runtime environment are optional; when set, they win, so keep them right (see below).
|
|
20
22
|
|
|
21
23
|
## The hub moved to a new URL
|
|
22
24
|
|
|
@@ -28,3 +30,4 @@ Hub ids stay the same, so data keyed on the id carries over, but the app rejects
|
|
|
28
30
|
- `bunx user-hub apps register --event <slug> --name "<the app's name>"` with no `--new` and no URLs: it keeps the registered URLs and prints the new values. The printed key must equal the `app` key in the code; if it differs, or the hub asks for a URL, stop and ask the human.
|
|
29
31
|
- Set `HUB_ISSUER` and `HUB_JWKS` on every Convex deployment (with and without `--prod`). No deploy needed for that.
|
|
30
32
|
- Set `VITE_HUB_URL` to the new URL, then rebuild and redeploy the frontend.
|
|
33
|
+
4. **Any app whose server sets `HUB_ISSUER` or `HUB_JWKS` in its own runtime environment** (for `verifyHubToken` or the server-function middleware): update them there too, or every server call rejects sign-ins. Starter apps set none.
|
|
@@ -27,7 +27,20 @@ export const myVotes = query({
|
|
|
27
27
|
});
|
|
28
28
|
```
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
TanStack Start server functions and server routes (behind `hub.serverFn` / `hub.request`, see [server-functions.md](server-functions.md)): check `context.hub.role`, and keep `requireFacilitator(ctx)` in any Convex function `context.convex` calls:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
export const resetEvent = createServerFn({ method: "POST" })
|
|
34
|
+
.middleware([hub.serverFn])
|
|
35
|
+
.handler(async ({ context }) => {
|
|
36
|
+
if (context.hub.role !== "facilitator") {
|
|
37
|
+
throw new Error("This is for facilitators.");
|
|
38
|
+
}
|
|
39
|
+
// …
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Any other server: check `(await verifyHubToken(request, { app })).role`.
|
|
31
44
|
|
|
32
45
|
## UI: only for a clean screen
|
|
33
46
|
|
|
@@ -40,7 +40,9 @@ export const saveSummary = createServerFn({ method: "POST" })
|
|
|
40
40
|
});
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
The token comes from `ConvexHubAuthProvider` (or `HubAuthProvider`), so the app must mount one, as every connected app does ([connect-an-app.md](connect-an-app.md)). Without it, a call from the browser waits 10 seconds for a provider and then fails with "Scan your badge to sign in.".
|
|
44
|
+
|
|
45
|
+
Call it like any server function (`await saveSummary({ data })`), from anywhere inside the provider: event handlers, effects, route loaders and queries (`useSuspenseQuery` included), on the first page load too. The browser half sends the person's current token, refreshed first when it is about to expire (a call made before the provider is ready, during the page's first render, waits for it): no wrapper hook, no headers at the call site. While the server renders a page (a loader or query run there) there is no browser to send a token, so it uses the person's cookie, as `getHubToken` does. Without a valid token the handler never runs and the call throws "Scan your badge to sign in.".
|
|
44
46
|
|
|
45
47
|
## 3. Server routes
|
|
46
48
|
|
|
@@ -70,5 +72,18 @@ Without a valid token it answers 401 "Scan your badge to sign in.".
|
|
|
70
72
|
- **Convex still checks.** Keep `requireHubUser(ctx)` / `requireFacilitator(ctx)` in every Convex function `context.convex` calls: the middleware proves who is asking, Convex decides what they may do. Check roles on `context.hub.role` for anything outside Convex.
|
|
71
73
|
- **Every server function or route that touches private data** gets `hub.serverFn` or `hub.request`. A route guard (`beforeLoad`) is not protection: server functions are reachable on their own.
|
|
72
74
|
- **CSRF:** Start protects server functions from cross-site calls by default. An app that defines `src/start.ts` must add `createCsrfMiddleware` itself (see TanStack Start's server functions guide).
|
|
73
|
-
- **
|
|
75
|
+
- **Server routes take only the header**, never the cookie: a server route is an API anyone can call. Server functions take the cookie only while the server renders a page; a call from the browser always needs the token the middleware sends.
|
|
76
|
+
- **Types:** `HubConvexContext` (`context.hub`, `context.hubToken`, `context.convex`) from `@user-hub/auth/start-convex`, `HubAuthContext` from `@user-hub/auth/start-middleware`, for helpers that take the handler's context.
|
|
74
77
|
- **Create the middleware once** and import it; do not call `hubConvexMiddleware` per function.
|
|
78
|
+
|
|
79
|
+
## Moving from a hand-rolled version
|
|
80
|
+
|
|
81
|
+
Apps written before `@user-hub/auth` 0.7 may check tokens themselves. Signs: a hook that adds `Authorization: Bearer` to every server-function call (often `useHubServerFn`, wrapping `useHubToken`), and a `createMiddleware().server(...)` that reads the header, calls `verifyHubToken` and builds a `ConvexHttpClient` with `setAuth`. Replace them:
|
|
82
|
+
|
|
83
|
+
1. `bun add @user-hub/auth@latest` (0.7.1 or newer: it also covers server functions called during the first page load).
|
|
84
|
+
2. Create `hub` once, as in step 1 above, and delete the hand-rolled middleware.
|
|
85
|
+
3. Server functions: `.middleware([hub.serverFn])`. Delete the wrapper hook and call the functions directly at every call site.
|
|
86
|
+
4. Server routes: `middleware: [hub.request]`. Their callers keep sending `Authorization: Bearer <token>` from `useHubToken()`; a missing or bad token is now a 401, so check the UI shows it sensibly.
|
|
87
|
+
5. Types: use `HubConvexContext` (or `HubAuthContext`) instead of your own context type.
|
|
88
|
+
6. Keep `getHubToken` in the root route for `initialToken`, and every `requireHubUser` / `requireFacilitator` in Convex.
|
|
89
|
+
7. Run the app's checks, then test every changed path signed in, including a hard reload straight onto a page that calls a server function as it loads.
|
package/dist/convex-errnd02r.js
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
readClaims
|
|
3
|
-
} from "./convex-gj0ap5wv.js";
|
|
4
|
-
|
|
5
|
-
// src/internal/live-session.ts
|
|
6
|
-
var KEY = Symbol.for("@user-hub/auth/live-sessions");
|
|
7
|
-
var store = globalThis;
|
|
8
|
-
var live = store[KEY] ??= new Map;
|
|
9
|
-
var MIN_SEND_LIFETIME_MS = 60 * 1000;
|
|
10
|
-
function registerLiveSession(app, session) {
|
|
11
|
-
live.set(app, session);
|
|
12
|
-
return () => {
|
|
13
|
-
if (live.get(app) === session)
|
|
14
|
-
live.delete(app);
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
async function tokenForRequest(app) {
|
|
18
|
-
return await live.get(app)?.tokenForRequest() ?? null;
|
|
19
|
-
}
|
|
20
|
-
async function sendableToken(currentToken, refresh, now) {
|
|
21
|
-
const expiresAt = currentToken ? readClaims(currentToken)?.expiresAt : null;
|
|
22
|
-
if (currentToken && expiresAt && expiresAt - now > MIN_SEND_LIFETIME_MS) {
|
|
23
|
-
return currentToken;
|
|
24
|
-
}
|
|
25
|
-
return await refresh();
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export { registerLiveSession, tokenForRequest, sendableToken };
|
package/dist/convex-gj0ap5wv.js
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
// src/internal/token.ts
|
|
2
|
-
function decodeSegment(segment) {
|
|
3
|
-
const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
|
|
4
|
-
return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
|
|
5
|
-
}
|
|
6
|
-
function payloadOf(token) {
|
|
7
|
-
try {
|
|
8
|
-
return decodeSegment(token.split(".")[1] ?? "");
|
|
9
|
-
} catch {
|
|
10
|
-
return null;
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
function readClaims(token) {
|
|
14
|
-
const payload = payloadOf(token);
|
|
15
|
-
if (typeof payload?.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string" || typeof payload.auth_time !== "number") {
|
|
16
|
-
return null;
|
|
17
|
-
}
|
|
18
|
-
return {
|
|
19
|
-
id: payload.sub,
|
|
20
|
-
name: payload.name,
|
|
21
|
-
team: payload.team,
|
|
22
|
-
role: payload.role === "facilitator" ? "facilitator" : "member",
|
|
23
|
-
app: payload.aud,
|
|
24
|
-
expiresAt: payload.exp * 1000
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
function sessionFor(token, app, now = Date.now()) {
|
|
28
|
-
const user = token ? readClaims(token) : null;
|
|
29
|
-
return token && user && user.app === app && user.expiresAt > now ? { token, user } : null;
|
|
30
|
-
}
|
|
31
|
-
function newestSession(...sessions) {
|
|
32
|
-
const issued = (s) => refreshInfo(s.token)?.issuedAt ?? 0;
|
|
33
|
-
return sessions.reduce((best, s) => s && (!best || issued(s) > issued(best)) ? s : best, null);
|
|
34
|
-
}
|
|
35
|
-
function refreshInfo(token) {
|
|
36
|
-
const payload = payloadOf(token);
|
|
37
|
-
if (typeof payload?.iss !== "string" || typeof payload.iat !== "number") {
|
|
38
|
-
return null;
|
|
39
|
-
}
|
|
40
|
-
return {
|
|
41
|
-
url: `${payload.iss.replace(/\/+$/, "")}/api/token/refresh`,
|
|
42
|
-
issuedAt: payload.iat * 1000
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
function sessionKeyOf(token) {
|
|
46
|
-
const payload = payloadOf(token);
|
|
47
|
-
if (typeof payload?.sub !== "string" || typeof payload.auth_time !== "number") {
|
|
48
|
-
return null;
|
|
49
|
-
}
|
|
50
|
-
return [payload.iss, payload.aud, payload.sub, payload.auth_time].join("|");
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export { readClaims, sessionFor, newestSession, refreshInfo, sessionKeyOf };
|