@user-hub/auth 0.6.2 → 0.7.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 +37 -2
- package/dist/{convex-55v4qaqb.js → convex-10r10q8j.js} +8 -53
- package/dist/convex-ctn06a2f.js +72 -0
- package/dist/convex-dt8pvksb.js +65 -0
- package/dist/convex-errnd02r.js +28 -0
- package/dist/convex-gj0ap5wv.js +53 -0
- package/dist/{convex-nqc41e3r.js → convex-mhcxj7fg.js} +50 -25
- package/dist/convex-react.js +4 -4
- package/dist/internal/keys.d.ts +24 -0
- package/dist/internal/live-session.d.ts +15 -0
- package/dist/internal/request-auth.d.ts +16 -0
- package/dist/internal/server-session.d.ts +1 -1
- package/dist/internal/start-middleware.d.ts +19 -0
- package/dist/react.js +1 -2
- package/dist/server.d.ts +6 -6
- package/dist/server.js +1 -1
- package/dist/start-convex.d.ts +27 -0
- package/dist/start-convex.js +28 -0
- package/dist/start-middleware.d.ts +27 -0
- package/dist/start-middleware.js +14 -0
- package/dist/start.js +11 -10
- package/package.json +11 -2
- package/skills/user-hub-auth/SKILL.md +3 -2
- package/skills/user-hub-auth/references/connect-an-app.md +2 -1
- package/skills/user-hub-auth/references/server-functions.md +74 -0
- package/dist/convex-tx5kfb4e.js +0 -56
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@ The hub decides how long a scan keeps someone signed in: 1, 2 or 4 hours, or unt
|
|
|
20
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
21
|
- Reopening the app later (even the next day) keeps the person signed in while their session lasts.
|
|
22
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.
|
|
23
|
+
- A server checking tokens with `verifyHubToken` (or the server-function middleware) 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
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
25
|
- A Content Security Policy needs the hub in `connect-src`.
|
|
26
26
|
|
|
@@ -122,6 +122,38 @@ With Convex, create the client so queries wait for the person's token and keep i
|
|
|
122
122
|
|
|
123
123
|
When `getHubToken` cannot vouch for a token (none yet, forged, or the hub unreachable) it returns `null` and the page renders as loading, as without it. When it returns one, the page carries that token, so it marks the response `Cache-Control: private, no-store` and `Vary: Cookie`: never put such pages behind a shared cache.
|
|
124
124
|
|
|
125
|
+
#### Server functions and server routes (TanStack Start)
|
|
126
|
+
|
|
127
|
+
Server code that acts as the person (a server function that calls another service and saves to Convex, a streaming route) gets them from middleware. Create it once:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
// src/lib/hub.ts
|
|
131
|
+
import { hubConvexMiddleware } from "@user-hub/auth/start-convex";
|
|
132
|
+
|
|
133
|
+
export const hub = hubConvexMiddleware({
|
|
134
|
+
app: "your-app-key",
|
|
135
|
+
hubUrl: import.meta.env.VITE_HUB_URL,
|
|
136
|
+
convexUrl: import.meta.env.VITE_CONVEX_URL,
|
|
137
|
+
});
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Then use `hub.serverFn` on server functions and `hub.request` on server routes:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
export const saveSummary = createServerFn({ method: "POST" })
|
|
144
|
+
.middleware([hub.serverFn])
|
|
145
|
+
.handler(async ({ context }) => {
|
|
146
|
+
context.hub; // { id, name, team, role }
|
|
147
|
+
await context.convex.mutation(api.summaries.save, { /* … */ }); // as the person
|
|
148
|
+
});
|
|
149
|
+
```
|
|
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.
|
|
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
|
+
- 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
|
+
- Start protects server functions from cross-site calls by default; an app that defines `src/start.ts` adds `createCsrfMiddleware` itself.
|
|
156
|
+
|
|
125
157
|
### 5. Use the person
|
|
126
158
|
|
|
127
159
|
```tsx
|
|
@@ -197,6 +229,7 @@ fetch("/api/thing", { headers: { Authorization: `Bearer ${token}` } });
|
|
|
197
229
|
import { verifyHubToken } from "@user-hub/auth/server";
|
|
198
230
|
|
|
199
231
|
const me = await verifyHubToken(request, { app: "your-app-key" }); // reads HUB_ISSUER and HUB_JWKS
|
|
232
|
+
// No HUB_ISSUER on the server? Pass the hub's URL: { app, hubUrl }
|
|
200
233
|
```
|
|
201
234
|
|
|
202
235
|
Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth/react`, in the same place, and do not need Convex installed.
|
|
@@ -212,8 +245,10 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
|
|
|
212
245
|
| both | `HubSignedIn` | Shows its children only when signed in. Props: `signedOut?`, `loading?` |
|
|
213
246
|
| | `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` |
|
|
214
247
|
| | `useHubSession()` | `undefined` while loading, `null` when signed out, otherwise `{ token, user }`; most apps need only `useHubUser()` or `<HubSignedIn>`. Also from `/convex-react` |
|
|
215
|
-
| `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app })` | Checks a token anywhere else |
|
|
248
|
+
| `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app, hubUrl? })` | Checks a token anywhere else. `hubUrl` is the issuer when `HUB_ISSUER` is not set |
|
|
216
249
|
| `@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` |
|
|
251
|
+
| `@user-hub/auth/start-middleware` | `hubMiddleware({ app, hubUrl })` | The same without Convex: `context.hub` and `context.hubToken` |
|
|
217
252
|
|
|
218
253
|
## Developing this package
|
|
219
254
|
|
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
import {
|
|
2
|
+
readClaims,
|
|
3
|
+
sessionFor,
|
|
4
|
+
refreshInfo,
|
|
5
|
+
sessionKeyOf
|
|
6
|
+
} from "./convex-gj0ap5wv.js";
|
|
7
|
+
|
|
1
8
|
// src/internal/clock.ts
|
|
2
9
|
var clockSkewMs = 0;
|
|
3
10
|
var hubNow = () => Date.now() + clockSkewMs;
|
|
@@ -5,58 +12,6 @@ function learnHubClock(issuedAt) {
|
|
|
5
12
|
clockSkewMs = issuedAt - Date.now();
|
|
6
13
|
}
|
|
7
14
|
|
|
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
|
-
|
|
60
15
|
// src/internal/refresh.ts
|
|
61
16
|
var REQUEST_TIMEOUT_MS = 10 * 1000;
|
|
62
17
|
function originOf(url) {
|
|
@@ -120,4 +75,4 @@ function writeCookie(app, token) {
|
|
|
120
75
|
} catch {}
|
|
121
76
|
}
|
|
122
77
|
|
|
123
|
-
export { hubNow,
|
|
78
|
+
export { hubNow, refreshUrlFor, exchange, cookieName, COOKIE_MAX_AGE_S, writeCookie };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// src/server.ts
|
|
2
|
+
import { errors, jwtVerify } from "jose";
|
|
3
|
+
|
|
4
|
+
// src/internal/keys.ts
|
|
5
|
+
import {
|
|
6
|
+
createLocalJWKSet,
|
|
7
|
+
createRemoteJWKSet
|
|
8
|
+
} from "jose";
|
|
9
|
+
var env = (name) => (typeof process === "undefined" ? undefined : process.env[name]) || undefined;
|
|
10
|
+
function hubIssuer({ hubUrl, issuer }) {
|
|
11
|
+
return (issuer || env("HUB_ISSUER") || hubUrl)?.replace(/\/+$/, "") || undefined;
|
|
12
|
+
}
|
|
13
|
+
function hubJwks(jwks) {
|
|
14
|
+
return jwks || env("HUB_JWKS");
|
|
15
|
+
}
|
|
16
|
+
var keySets = new Map;
|
|
17
|
+
function keySet(source) {
|
|
18
|
+
let keys = keySets.get(source);
|
|
19
|
+
if (!keys) {
|
|
20
|
+
if (source.startsWith("data:")) {
|
|
21
|
+
const json = Buffer.from(source.split(",")[1] ?? "", "base64").toString();
|
|
22
|
+
keys = createLocalJWKSet(JSON.parse(json));
|
|
23
|
+
} else {
|
|
24
|
+
keys = createRemoteJWKSet(new URL(source));
|
|
25
|
+
}
|
|
26
|
+
keySets.set(source, keys);
|
|
27
|
+
}
|
|
28
|
+
return keys;
|
|
29
|
+
}
|
|
30
|
+
function hubKeys(options) {
|
|
31
|
+
const issuer = hubIssuer(options);
|
|
32
|
+
if (!issuer) {
|
|
33
|
+
throw new Error("Set HUB_ISSUER or pass hubUrl: run `bunx user-hub apps register`");
|
|
34
|
+
}
|
|
35
|
+
const source = hubJwks(options.jwks) || `${issuer}/.well-known/jwks.json`;
|
|
36
|
+
try {
|
|
37
|
+
return { issuer, keys: keySet(source) };
|
|
38
|
+
} catch (error) {
|
|
39
|
+
throw new Error(`The hub's key (HUB_JWKS or ${issuer}) cannot be read: ${String(error)}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/server.ts
|
|
44
|
+
function bearer(input) {
|
|
45
|
+
if (typeof input === "string")
|
|
46
|
+
return input;
|
|
47
|
+
const header = input.headers.get("authorization") ?? "";
|
|
48
|
+
return /^Bearer\s+(\S+)$/i.exec(header)?.[1] ?? "";
|
|
49
|
+
}
|
|
50
|
+
async function verifyHubToken2(input, options) {
|
|
51
|
+
const { issuer, keys } = hubKeys(options);
|
|
52
|
+
const token = bearer(input);
|
|
53
|
+
if (!token) {
|
|
54
|
+
throw new Error("No hub token");
|
|
55
|
+
}
|
|
56
|
+
const { payload } = await jwtVerify(token, keys, {
|
|
57
|
+
issuer,
|
|
58
|
+
audience: options.app,
|
|
59
|
+
algorithms: ["ES256"]
|
|
60
|
+
});
|
|
61
|
+
if (typeof payload.auth_time !== "number") {
|
|
62
|
+
throw new errors.JWTClaimValidationFailed("Not a hub sign-in token: it has no auth_time", payload, "auth_time", "missing");
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
id: payload.sub,
|
|
66
|
+
name: payload.name,
|
|
67
|
+
team: payload.team,
|
|
68
|
+
role: payload.role === "facilitator" ? "facilitator" : "member"
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export { hubIssuer, hubJwks, hubKeys, verifyHubToken2 };
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hubKeys,
|
|
3
|
+
verifyHubToken2
|
|
4
|
+
} from "./convex-ctn06a2f.js";
|
|
5
|
+
import {
|
|
6
|
+
tokenForRequest
|
|
7
|
+
} from "./convex-errnd02r.js";
|
|
8
|
+
|
|
9
|
+
// src/internal/start-middleware.ts
|
|
10
|
+
import {
|
|
11
|
+
createMiddleware
|
|
12
|
+
} from "@tanstack/react-start";
|
|
13
|
+
|
|
14
|
+
// src/internal/request-auth.ts
|
|
15
|
+
var SIGN_IN_MESSAGE = "Scan your badge to sign in.";
|
|
16
|
+
var BEARER = /^Bearer\s+(\S+)$/i;
|
|
17
|
+
var REJECTED_TOKEN = new Set([
|
|
18
|
+
"ERR_JWT_EXPIRED",
|
|
19
|
+
"ERR_JWT_CLAIM_VALIDATION_FAILED",
|
|
20
|
+
"ERR_JWT_INVALID",
|
|
21
|
+
"ERR_JWS_INVALID",
|
|
22
|
+
"ERR_JWS_SIGNATURE_VERIFICATION_FAILED",
|
|
23
|
+
"ERR_JWKS_NO_MATCHING_KEY",
|
|
24
|
+
"ERR_JWKS_MULTIPLE_MATCHING_KEYS",
|
|
25
|
+
"ERR_JOSE_ALG_NOT_ALLOWED",
|
|
26
|
+
"ERR_JOSE_NOT_SUPPORTED"
|
|
27
|
+
]);
|
|
28
|
+
var rejectedToken = (error) => REJECTED_TOKEN.has(error?.code);
|
|
29
|
+
async function authenticate(request, options) {
|
|
30
|
+
hubKeys(options);
|
|
31
|
+
const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
|
|
32
|
+
if (!token)
|
|
33
|
+
return null;
|
|
34
|
+
try {
|
|
35
|
+
return { hub: await verifyHubToken2(token, options), hubToken: token };
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (rejectedToken(error))
|
|
38
|
+
return null;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/internal/start-middleware.ts
|
|
44
|
+
function hubRequestMiddleware(options) {
|
|
45
|
+
return createMiddleware().server(async ({ next, request, handlerType, serverFnMeta }) => {
|
|
46
|
+
const auth = await authenticate(request, options);
|
|
47
|
+
if (!auth) {
|
|
48
|
+
if (handlerType === "router" && !serverFnMeta) {
|
|
49
|
+
return new Response(SIGN_IN_MESSAGE, { status: 401 });
|
|
50
|
+
}
|
|
51
|
+
throw new Error(SIGN_IN_MESSAGE);
|
|
52
|
+
}
|
|
53
|
+
return next({ context: auth });
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function hubServerFnMiddleware(app, request) {
|
|
57
|
+
return createMiddleware({ type: "function" }).middleware([request]).client(async ({ next }) => {
|
|
58
|
+
const token = await tokenForRequest(app);
|
|
59
|
+
return next({
|
|
60
|
+
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export { hubRequestMiddleware, hubServerFnMiddleware };
|
|
@@ -0,0 +1,28 @@
|
|
|
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 };
|
|
@@ -0,0 +1,53 @@
|
|
|
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 };
|
|
@@ -1,14 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
hubNow,
|
|
3
|
+
refreshUrlFor,
|
|
4
|
+
exchange,
|
|
5
|
+
writeCookie
|
|
6
|
+
} from "./convex-10r10q8j.js";
|
|
7
|
+
import {
|
|
8
|
+
registerLiveSession,
|
|
9
|
+
sendableToken
|
|
10
|
+
} from "./convex-errnd02r.js";
|
|
11
|
+
import {
|
|
3
12
|
readClaims,
|
|
4
13
|
sessionFor,
|
|
5
14
|
newestSession,
|
|
6
15
|
refreshInfo,
|
|
7
|
-
sessionKeyOf
|
|
8
|
-
|
|
9
|
-
exchange,
|
|
10
|
-
writeCookie
|
|
11
|
-
} from "./convex-55v4qaqb.js";
|
|
16
|
+
sessionKeyOf
|
|
17
|
+
} from "./convex-gj0ap5wv.js";
|
|
12
18
|
|
|
13
19
|
// src/react.tsx
|
|
14
20
|
import { useMemo as useMemo2 } from "react";
|
|
@@ -19,6 +25,7 @@ import {
|
|
|
19
25
|
useCallback,
|
|
20
26
|
useContext,
|
|
21
27
|
useEffect,
|
|
28
|
+
useLayoutEffect,
|
|
22
29
|
useMemo,
|
|
23
30
|
useRef,
|
|
24
31
|
useState,
|
|
@@ -144,6 +151,13 @@ function HubSessionProvider({
|
|
|
144
151
|
const latest = useRef(store.get().session);
|
|
145
152
|
const held = useRef(store.get().session?.token ?? null);
|
|
146
153
|
const inFlight = useRef(null);
|
|
154
|
+
const [loaded] = useState(() => {
|
|
155
|
+
let settle = () => {};
|
|
156
|
+
const promise = new Promise((resolve) => {
|
|
157
|
+
settle = resolve;
|
|
158
|
+
});
|
|
159
|
+
return { promise, settle };
|
|
160
|
+
});
|
|
147
161
|
const mounted = useRef(false);
|
|
148
162
|
const lastRequest = useRef(0);
|
|
149
163
|
const redirecting = session === null && Boolean(hubUrl) && typeof window !== "undefined" && LOCAL_HOST.test(window.location.hostname);
|
|
@@ -222,34 +236,45 @@ function HubSessionProvider({
|
|
|
222
236
|
}
|
|
223
237
|
return await trade(current.token);
|
|
224
238
|
}, [app, hubUrl, currentToken, trade]);
|
|
225
|
-
|
|
239
|
+
useLayoutEffect(() => {
|
|
226
240
|
mounted.current = true;
|
|
227
241
|
return () => {
|
|
228
242
|
mounted.current = false;
|
|
229
243
|
};
|
|
230
244
|
}, []);
|
|
245
|
+
useLayoutEffect(() => registerLiveSession(app, {
|
|
246
|
+
tokenForRequest: async () => {
|
|
247
|
+
await loaded.promise;
|
|
248
|
+
await inFlight.current?.answer;
|
|
249
|
+
return await sendableToken(currentToken(), refresh, hubNow());
|
|
250
|
+
}
|
|
251
|
+
}), [app, loaded, currentToken, refresh]);
|
|
231
252
|
useEffect(() => {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
253
|
+
try {
|
|
254
|
+
const fromUrl = takeTokenFromUrl();
|
|
255
|
+
const stored = readStorage(key);
|
|
256
|
+
const valid = sessionFor(fromUrl, app, hubNow()) ?? newestSession(sessionFor(initial, app, hubNow()), sessionFor(stored, app, hubNow()));
|
|
257
|
+
if (valid) {
|
|
258
|
+
signIn(valid);
|
|
259
|
+
if (refreshUrlFor(valid.token, app, hubUrl) && (valid.token === fromUrl || !recentlyRefreshed(valid.token))) {
|
|
260
|
+
trade(valid.token);
|
|
261
|
+
}
|
|
262
|
+
return;
|
|
239
263
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
264
|
+
const expired = [fromUrl, stored, initial].find((token) => Boolean(token && refreshUrlFor(token, app, hubUrl)));
|
|
265
|
+
if (!expired) {
|
|
266
|
+
end();
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
writeToken(app, expired);
|
|
270
|
+
held.current = expired;
|
|
271
|
+
latest.current = undefined;
|
|
272
|
+
store.set(LOADING);
|
|
273
|
+
trade(expired);
|
|
274
|
+
} finally {
|
|
275
|
+
loaded.settle();
|
|
246
276
|
}
|
|
247
|
-
|
|
248
|
-
held.current = expired;
|
|
249
|
-
latest.current = undefined;
|
|
250
|
-
store.set(LOADING);
|
|
251
|
-
trade(expired);
|
|
252
|
-
}, [app, hubUrl, key, initial, store, signIn, end, trade]);
|
|
277
|
+
}, [app, hubUrl, key, initial, store, signIn, end, trade, loaded]);
|
|
253
278
|
useEffect(() => {
|
|
254
279
|
if (!stalled)
|
|
255
280
|
return;
|
package/dist/convex-react.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
sessionKeyOf
|
|
3
|
-
} from "./convex-55v4qaqb.js";
|
|
4
1
|
import {
|
|
5
2
|
useHubState,
|
|
6
3
|
HubSessionProvider,
|
|
@@ -9,7 +6,10 @@ import {
|
|
|
9
6
|
useHubSession2,
|
|
10
7
|
useHubUser2,
|
|
11
8
|
useHubToken2
|
|
12
|
-
} from "./convex-
|
|
9
|
+
} from "./convex-mhcxj7fg.js";
|
|
10
|
+
import {
|
|
11
|
+
sessionKeyOf
|
|
12
|
+
} from "./convex-gj0ap5wv.js";
|
|
13
13
|
|
|
14
14
|
// src/convex-react.tsx
|
|
15
15
|
import {
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { createLocalJWKSet, createRemoteJWKSet } from "jose";
|
|
2
|
+
export type HubKeyOptions = {
|
|
3
|
+
hubUrl?: string;
|
|
4
|
+
issuer?: string;
|
|
5
|
+
jwks?: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* The hub's URL its tokens carry as `iss`, without a trailing slash:
|
|
9
|
+
* `issuer`, else HUB_ISSUER, else `hubUrl`. Undefined when none is set.
|
|
10
|
+
*/
|
|
11
|
+
export declare function hubIssuer({ hubUrl, issuer }: HubKeyOptions): string | undefined;
|
|
12
|
+
/** The hub's public key: `jwks`, else HUB_JWKS. */
|
|
13
|
+
export declare function hubJwks(jwks?: string): string | undefined;
|
|
14
|
+
type KeySet = ReturnType<typeof createLocalJWKSet> | ReturnType<typeof createRemoteJWKSet>;
|
|
15
|
+
/**
|
|
16
|
+
* The issuer and key set to check tokens with. Throws when the server is not
|
|
17
|
+
* set up (no issuer, a HUB_JWKS that is not a key set, a hub URL that is not a
|
|
18
|
+
* URL): a setup mistake, never a signed-out person.
|
|
19
|
+
*/
|
|
20
|
+
export declare function hubKeys(options: HubKeyOptions): {
|
|
21
|
+
issuer: string;
|
|
22
|
+
keys: KeySet;
|
|
23
|
+
};
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type LiveSession = {
|
|
2
|
+
tokenForRequest: () => Promise<string | null>;
|
|
3
|
+
};
|
|
4
|
+
export declare const MIN_SEND_LIFETIME_MS: number;
|
|
5
|
+
/** Registers the provider's session; returns the unregister function. */
|
|
6
|
+
export declare function registerLiveSession(app: string, session: LiveSession): () => void;
|
|
7
|
+
/** The token the app's provider would send now; null without a provider. */
|
|
8
|
+
export declare function tokenForRequest(app: string): Promise<string | null>;
|
|
9
|
+
/**
|
|
10
|
+
* The provider's side: the current token while it has over a minute left,
|
|
11
|
+
* else the next one from the hub (refresh keeps a still-valid token when the
|
|
12
|
+
* hub cannot be reached, and gives null once signed out). `now` is the
|
|
13
|
+
* provider's hub clock.
|
|
14
|
+
*/
|
|
15
|
+
export declare function sendableToken(currentToken: string | null, refresh: () => Promise<string | null>, now: number): Promise<string | null>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type VerifyHubTokenOptions } from "../server";
|
|
2
|
+
import type { HubUser } from "./token";
|
|
3
|
+
export type HubMiddlewareOptions = VerifyHubTokenOptions;
|
|
4
|
+
/** What the middleware adds to the handler's context. */
|
|
5
|
+
export type HubAuthContext = {
|
|
6
|
+
hub: HubUser;
|
|
7
|
+
hubToken: string;
|
|
8
|
+
};
|
|
9
|
+
export declare const SIGN_IN_MESSAGE = "Scan your badge to sign in.";
|
|
10
|
+
/**
|
|
11
|
+
* The person behind the request's `Authorization: Bearer` token, or null when
|
|
12
|
+
* there is none or it is not a valid sign-in for this app. A server that is
|
|
13
|
+
* not set up (no issuer, an unreadable key) or cannot reach the hub's key
|
|
14
|
+
* throws instead: that is the server's problem, not a signed-out person.
|
|
15
|
+
*/
|
|
16
|
+
export declare function authenticate(request: Request, options: HubMiddlewareOptions): Promise<HubAuthContext | null>;
|
|
@@ -16,4 +16,4 @@ export type HubTokenOptions = {
|
|
|
16
16
|
* person from. Null never means signed out: the browser still decides that,
|
|
17
17
|
* so the cookie is only cleared when the hub has ended the session.
|
|
18
18
|
*/
|
|
19
|
-
export declare function resolveHubToken(cookie: TokenCookie, { app, hubUrl,
|
|
19
|
+
export declare function resolveHubToken(cookie: TokenCookie, { app, hubUrl, ...options }: HubTokenOptions): Promise<string | null>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type AnyRequestMiddleware, type FunctionMiddlewareAfterClient, type RequestMiddlewareAfterServer } from "@tanstack/react-start";
|
|
2
|
+
import { type HubAuthContext, type HubMiddlewareOptions } from "./request-auth";
|
|
3
|
+
export type HubRequestMiddleware = RequestMiddlewareAfterServer<{}, undefined, HubAuthContext>;
|
|
4
|
+
export type HubServerFnMiddleware<Request extends AnyRequestMiddleware> = FunctionMiddlewareAfterClient<{}, readonly [Request], undefined, undefined, undefined>;
|
|
5
|
+
export type HubMiddleware<Request extends AnyRequestMiddleware = HubRequestMiddleware> = {
|
|
6
|
+
request: Request;
|
|
7
|
+
serverFn: HubServerFnMiddleware<Request>;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Server routes and server functions: the person behind the request's
|
|
11
|
+
* Authorization header. Without a valid token a server route answers 401 and
|
|
12
|
+
* a server function throws, which its caller receives as the error.
|
|
13
|
+
*/
|
|
14
|
+
export declare function hubRequestMiddleware(options: HubMiddlewareOptions): HubRequestMiddleware;
|
|
15
|
+
/**
|
|
16
|
+
* Server functions: the browser sends the provider's current token (refreshed
|
|
17
|
+
* first when it is about to expire), then `request` checks it on the server.
|
|
18
|
+
*/
|
|
19
|
+
export declare function hubServerFnMiddleware<Request extends AnyRequestMiddleware>(app: string, request: Request): HubServerFnMiddleware<Request>;
|
package/dist/react.js
CHANGED
package/dist/server.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
+
import { type HubKeyOptions } from "./internal/keys";
|
|
1
2
|
import type { HubUser } from "./internal/token";
|
|
2
3
|
export type { HubRole, HubUser } from "./internal/token";
|
|
3
|
-
type
|
|
4
|
+
export type VerifyHubTokenOptions = HubKeyOptions & {
|
|
4
5
|
app: string;
|
|
5
|
-
issuer?: string;
|
|
6
|
-
jwks?: string;
|
|
7
6
|
};
|
|
8
7
|
/**
|
|
9
8
|
* For servers that are not Convex. Pass the request (token in an
|
|
10
|
-
* `Authorization: Bearer` header) or the token itself
|
|
11
|
-
*
|
|
9
|
+
* `Authorization: Bearer` header) or the token itself, and `hubUrl` when the
|
|
10
|
+
* server has no HUB_ISSUER. Returns the person, or throws when the token is
|
|
11
|
+
* missing, expired, forged or meant for another app.
|
|
12
12
|
*/
|
|
13
|
-
export declare function verifyHubToken(input: Request | string,
|
|
13
|
+
export declare function verifyHubToken(input: Request | string, options: VerifyHubTokenOptions): Promise<HubUser>;
|
package/dist/server.js
CHANGED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type RequestMiddlewareAfterServer } from "@tanstack/react-start";
|
|
2
|
+
import { ConvexHttpClient } from "convex/browser";
|
|
3
|
+
import type { HubMiddlewareOptions } from "./internal/request-auth";
|
|
4
|
+
import { type HubMiddleware, type HubRequestMiddleware } from "./internal/start-middleware";
|
|
5
|
+
export type { HubAuthContext, HubMiddlewareOptions, } from "./internal/request-auth";
|
|
6
|
+
export type { HubMiddleware, HubRequestMiddleware, HubServerFnMiddleware, } from "./internal/start-middleware";
|
|
7
|
+
export type { HubRole, HubUser } from "./internal/token";
|
|
8
|
+
/** hubConvexMiddleware's request middleware: the person, then Convex. */
|
|
9
|
+
export type HubConvexRequestMiddleware = RequestMiddlewareAfterServer<{}, readonly [HubRequestMiddleware], {
|
|
10
|
+
convex: ConvexHttpClient;
|
|
11
|
+
}>;
|
|
12
|
+
/**
|
|
13
|
+
* hubMiddleware (`@user-hub/auth/start-middleware`) for apps on Convex: the
|
|
14
|
+
* handler also gets `context.convex`, a ConvexHttpClient acting as the
|
|
15
|
+
* person, so Convex checks them again (requireHubUser) for every call.
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* export const hub = hubConvexMiddleware({
|
|
19
|
+
* app: APP_KEY,
|
|
20
|
+
* hubUrl: import.meta.env.VITE_HUB_URL,
|
|
21
|
+
* convexUrl: import.meta.env.VITE_CONVEX_URL,
|
|
22
|
+
* });
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export declare function hubConvexMiddleware({ convexUrl, ...options }: HubMiddlewareOptions & {
|
|
26
|
+
convexUrl: string | undefined;
|
|
27
|
+
}): HubMiddleware<HubConvexRequestMiddleware>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import"./convex-ctn06a2f.js";
|
|
2
|
+
import {
|
|
3
|
+
hubRequestMiddleware,
|
|
4
|
+
hubServerFnMiddleware
|
|
5
|
+
} from "./convex-dt8pvksb.js";
|
|
6
|
+
|
|
7
|
+
// src/start-convex.ts
|
|
8
|
+
import {
|
|
9
|
+
createMiddleware
|
|
10
|
+
} from "@tanstack/react-start";
|
|
11
|
+
import { ConvexHttpClient } from "convex/browser";
|
|
12
|
+
function hubConvexMiddleware({
|
|
13
|
+
convexUrl,
|
|
14
|
+
...options
|
|
15
|
+
}) {
|
|
16
|
+
if (!convexUrl) {
|
|
17
|
+
throw new Error("hubConvexMiddleware needs convexUrl (VITE_CONVEX_URL)");
|
|
18
|
+
}
|
|
19
|
+
const request = createMiddleware().middleware([hubRequestMiddleware(options)]).server(({ next, context }) => {
|
|
20
|
+
const convex = new ConvexHttpClient(convexUrl);
|
|
21
|
+
convex.setAuth(context.hubToken);
|
|
22
|
+
return next({ context: { convex } });
|
|
23
|
+
});
|
|
24
|
+
return { request, serverFn: hubServerFnMiddleware(options.app, request) };
|
|
25
|
+
}
|
|
26
|
+
export {
|
|
27
|
+
hubConvexMiddleware
|
|
28
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { HubMiddlewareOptions } from "./internal/request-auth";
|
|
2
|
+
import { type HubMiddleware } from "./internal/start-middleware";
|
|
3
|
+
export type { HubAuthContext, HubMiddlewareOptions, } from "./internal/request-auth";
|
|
4
|
+
export type { HubMiddleware, HubRequestMiddleware, HubServerFnMiddleware, } from "./internal/start-middleware";
|
|
5
|
+
export type { HubRole, HubUser } from "./internal/token";
|
|
6
|
+
/**
|
|
7
|
+
* TanStack Start middleware for the signed-in person. Create it once and
|
|
8
|
+
* export it:
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* export const hub = hubMiddleware({
|
|
12
|
+
* app: APP_KEY,
|
|
13
|
+
* hubUrl: import.meta.env.VITE_HUB_URL,
|
|
14
|
+
* });
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* - `hub.serverFn` for server functions: the browser sends the person's token
|
|
18
|
+
* (from HubAuthProvider or ConvexHubAuthProvider), the server checks it.
|
|
19
|
+
* - `hub.request` for server routes: the caller sends
|
|
20
|
+
* `Authorization: Bearer <token>` itself (useHubToken).
|
|
21
|
+
*
|
|
22
|
+
* Handlers get `context.hub` (the person) and `context.hubToken`. A request
|
|
23
|
+
* without a valid token never reaches them: a server function throws "Scan
|
|
24
|
+
* your badge to sign in.", a server route answers 401. Apps on Convex use
|
|
25
|
+
* hubConvexMiddleware from `@user-hub/auth/start-convex` instead.
|
|
26
|
+
*/
|
|
27
|
+
export declare function hubMiddleware(options: HubMiddlewareOptions): HubMiddleware;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import"./convex-ctn06a2f.js";
|
|
2
|
+
import {
|
|
3
|
+
hubRequestMiddleware,
|
|
4
|
+
hubServerFnMiddleware
|
|
5
|
+
} from "./convex-dt8pvksb.js";
|
|
6
|
+
|
|
7
|
+
// src/start-middleware.ts
|
|
8
|
+
function hubMiddleware(options) {
|
|
9
|
+
const request = hubRequestMiddleware(options);
|
|
10
|
+
return { request, serverFn: hubServerFnMiddleware(options.app, request) };
|
|
11
|
+
}
|
|
12
|
+
export {
|
|
13
|
+
hubMiddleware
|
|
14
|
+
};
|
package/dist/start.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hubIssuer,
|
|
3
|
+
hubJwks,
|
|
4
|
+
verifyHubToken2
|
|
5
|
+
} from "./convex-ctn06a2f.js";
|
|
1
6
|
import {
|
|
2
7
|
hubNow,
|
|
3
|
-
readClaims,
|
|
4
8
|
exchange,
|
|
5
9
|
cookieName,
|
|
6
10
|
COOKIE_MAX_AGE_S
|
|
7
|
-
} from "./convex-
|
|
11
|
+
} from "./convex-10r10q8j.js";
|
|
8
12
|
import {
|
|
9
|
-
|
|
10
|
-
} from "./convex-
|
|
13
|
+
readClaims
|
|
14
|
+
} from "./convex-gj0ap5wv.js";
|
|
11
15
|
|
|
12
16
|
// src/start.ts
|
|
13
17
|
import {
|
|
@@ -29,12 +33,9 @@ async function verified(token, app, issuer, jwks) {
|
|
|
29
33
|
return false;
|
|
30
34
|
}
|
|
31
35
|
}
|
|
32
|
-
async function resolveHubToken(cookie, {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
issuer = process.env.HUB_ISSUER || hubUrl?.replace(/\/+$/, ""),
|
|
36
|
-
jwks = process.env.HUB_JWKS || undefined
|
|
37
|
-
}) {
|
|
36
|
+
async function resolveHubToken(cookie, { app, hubUrl, ...options }) {
|
|
37
|
+
const issuer = hubIssuer({ hubUrl, issuer: options.issuer });
|
|
38
|
+
const jwks = hubJwks(options.jwks);
|
|
38
39
|
const token = cookie.get();
|
|
39
40
|
const user = token ? readClaims(token) : null;
|
|
40
41
|
if (!token || !issuer || user?.app !== app)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@user-hub/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Sign people in from User Hub badges: Convex auth config, React provider and server verification.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"auth",
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
"skills"
|
|
17
17
|
],
|
|
18
18
|
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
19
20
|
"exports": {
|
|
20
21
|
"./convex": {
|
|
21
22
|
"types": "./dist/convex.d.ts",
|
|
@@ -36,13 +37,21 @@
|
|
|
36
37
|
"./start": {
|
|
37
38
|
"types": "./dist/start.d.ts",
|
|
38
39
|
"default": "./dist/start.js"
|
|
40
|
+
},
|
|
41
|
+
"./start-middleware": {
|
|
42
|
+
"types": "./dist/start-middleware.d.ts",
|
|
43
|
+
"default": "./dist/start-middleware.js"
|
|
44
|
+
},
|
|
45
|
+
"./start-convex": {
|
|
46
|
+
"types": "./dist/start-convex.d.ts",
|
|
47
|
+
"default": "./dist/start-convex.js"
|
|
39
48
|
}
|
|
40
49
|
},
|
|
41
50
|
"publishConfig": {
|
|
42
51
|
"access": "public"
|
|
43
52
|
},
|
|
44
53
|
"scripts": {
|
|
45
|
-
"build": "rm -rf dist && bun build src/convex.ts src/react.tsx src/convex-react.tsx src/server.ts src/start.ts --outdir dist --target node --format esm --splitting --packages external && tsc -p tsconfig.build.json",
|
|
54
|
+
"build": "rm -rf dist && bun build src/convex.ts src/react.tsx src/convex-react.tsx src/server.ts src/start.ts src/start-middleware.ts src/start-convex.ts --outdir dist --target node --format esm --splitting --packages external && tsc -p tsconfig.build.json",
|
|
46
55
|
"check": "vp check",
|
|
47
56
|
"fix": "vp check --fix",
|
|
48
57
|
"lint": "vp lint",
|
|
@@ -1,6 +1,6 @@
|
|
|
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 QR sign-in, wiring hubAuth, ConvexHubAuthProvider, HubAuthProvider, HubSignedIn, useHubUser or verifyHubToken, 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.
|
|
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 QR sign-in, 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
|
|
@@ -15,6 +15,7 @@ Registering apps, signing a folder in to the hub and managing people is done wit
|
|
|
15
15
|
|---|---|
|
|
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
|
+
| Server functions or server routes that act as the person (TanStack Start) | [references/server-functions.md](references/server-functions.md) |
|
|
18
19
|
| Facilitator-only pages or actions | [references/roles.md](references/roles.md) |
|
|
19
20
|
| Running it locally, going to production, or the hub moved | [references/dev-and-production.md](references/dev-and-production.md) |
|
|
20
21
|
|
|
@@ -34,7 +35,7 @@ The hub's URL also comes from the human. It goes in three places with the same v
|
|
|
34
35
|
## Rules
|
|
35
36
|
|
|
36
37
|
- **Key data on the hub id** (`useHubUser().id`, `identity.subject` in Convex). Never on the name, the badge, or Convex's `tokenIdentifier`, which contains the hub's URL and changes if the hub moves.
|
|
37
|
-
- **Check access on the server**: `requireHubUser(ctx)` / `requireFacilitator(ctx)` in Convex, `verifyHubToken` elsewhere. `useHubUser()` is for display; hiding a page protects nothing.
|
|
38
|
+
- **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.
|
|
38
39
|
- **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.
|
|
39
40
|
- **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`.
|
|
40
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.
|
|
@@ -83,7 +83,8 @@ With Convex, create the client so queries wait for the person's token and keep i
|
|
|
83
83
|
|---|---|
|
|
84
84
|
| Components | `const me = useHubUser()` → `{ id, name, team, role }` or `null` |
|
|
85
85
|
| Convex functions | `const me = await requireHubUser(ctx)` (throws when signed out); `getHubUser(ctx)` when signing in is optional |
|
|
86
|
-
|
|
|
86
|
+
| TanStack Start server functions and routes | `hubConvexMiddleware` (or `hubMiddleware`): [server-functions.md](server-functions.md) |
|
|
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`) |
|
|
87
88
|
| Sign out | `const signOut = useHubSignOut()` from the provider's entry point. It forgets this app's token only |
|
|
88
89
|
|
|
89
90
|
If the app sets a Content Security Policy, allow the hub in `connect-src`: the provider calls `<hub>/api/token/refresh`.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Server functions and server routes (TanStack Start)
|
|
2
|
+
|
|
3
|
+
For server code that acts as the signed-in person: a server function that calls another service and saves to Convex, a streaming chat route, an upload. Never hand-roll this (reading the header, `verifyHubToken`, a `ConvexHttpClient`): the middleware below does it, including the production container that has no runtime environment.
|
|
4
|
+
|
|
5
|
+
## 1. Create the middleware once
|
|
6
|
+
|
|
7
|
+
`src/lib/hub.ts`:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { hubConvexMiddleware } from "@user-hub/auth/start-convex";
|
|
11
|
+
|
|
12
|
+
import { APP_KEY } from "../../convex/hub";
|
|
13
|
+
|
|
14
|
+
export const hub = hubConvexMiddleware({
|
|
15
|
+
app: APP_KEY,
|
|
16
|
+
hubUrl: import.meta.env.VITE_HUB_URL,
|
|
17
|
+
convexUrl: import.meta.env.VITE_CONVEX_URL,
|
|
18
|
+
});
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Without Convex: `hubMiddleware({ app, hubUrl })` from `@user-hub/auth/start-middleware`, the same minus `convexUrl` and `context.convex`.
|
|
22
|
+
|
|
23
|
+
Pass `hubUrl` and `convexUrl` from `import.meta.env` as above. Never `process.env.VITE_*`: Vite only builds `import.meta.env` values in, and a production container may have no runtime environment at all. The middleware checks tokens against `HUB_ISSUER` and `HUB_JWKS` when the server has them, else against `hubUrl` and its published key.
|
|
24
|
+
|
|
25
|
+
## 2. Server functions
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { createServerFn } from "@tanstack/react-start";
|
|
29
|
+
|
|
30
|
+
import { hub } from "@/lib/hub";
|
|
31
|
+
import { api } from "../../convex/_generated/api";
|
|
32
|
+
|
|
33
|
+
export const saveSummary = createServerFn({ method: "POST" })
|
|
34
|
+
.middleware([hub.serverFn])
|
|
35
|
+
.validator((data: { text: string }) => data)
|
|
36
|
+
.handler(async ({ context, data }) => {
|
|
37
|
+
// context.hub: { id, name, team, role }; context.hubToken: their token
|
|
38
|
+
// context.convex: a ConvexHttpClient acting as them
|
|
39
|
+
await context.convex.mutation(api.summaries.save, { text: data.text });
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Call it like any server function (`await saveSummary({ data })`), from anywhere inside the provider. The browser half sends the person's current token, refreshed first when it is about to expire: no wrapper hook, no headers at the call site. Without a valid token the handler never runs and the call throws "Scan your badge to sign in.".
|
|
44
|
+
|
|
45
|
+
## 3. Server routes
|
|
46
|
+
|
|
47
|
+
Server routes are plain HTTP, so the caller sends the token itself (`useHubToken()`, read for each request):
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
export const Route = createFileRoute("/api/chat")({
|
|
51
|
+
server: {
|
|
52
|
+
middleware: [hub.request],
|
|
53
|
+
handlers: {
|
|
54
|
+
POST: async ({ context, request }) => {
|
|
55
|
+
// context.hub, context.hubToken, context.convex as above
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
fetch("/api/chat", { method: "POST", headers: { Authorization: `Bearer ${token}` }, body });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Without a valid token it answers 401 "Scan your badge to sign in.".
|
|
67
|
+
|
|
68
|
+
## Rules
|
|
69
|
+
|
|
70
|
+
- **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
|
+
- **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
|
+
- **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
|
+
- **Loaders during server rendering** have no browser to send the token: use `getHubToken` there (see [connect-an-app.md](connect-an-app.md)), not these middleware.
|
|
74
|
+
- **Create the middleware once** and import it; do not call `hubConvexMiddleware` per function.
|
package/dist/convex-tx5kfb4e.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
// src/server.ts
|
|
2
|
-
import {
|
|
3
|
-
createLocalJWKSet,
|
|
4
|
-
createRemoteJWKSet,
|
|
5
|
-
jwtVerify
|
|
6
|
-
} from "jose";
|
|
7
|
-
var keySets = new Map;
|
|
8
|
-
function keySet(jwks, issuer) {
|
|
9
|
-
const source = jwks || `${issuer}/.well-known/jwks.json`;
|
|
10
|
-
let keys = keySets.get(source);
|
|
11
|
-
if (!keys) {
|
|
12
|
-
if (source.startsWith("data:")) {
|
|
13
|
-
const json = Buffer.from(source.split(",")[1] ?? "", "base64").toString();
|
|
14
|
-
keys = createLocalJWKSet(JSON.parse(json));
|
|
15
|
-
} else {
|
|
16
|
-
keys = createRemoteJWKSet(new URL(source));
|
|
17
|
-
}
|
|
18
|
-
keySets.set(source, keys);
|
|
19
|
-
}
|
|
20
|
-
return keys;
|
|
21
|
-
}
|
|
22
|
-
function bearer(input) {
|
|
23
|
-
if (typeof input === "string")
|
|
24
|
-
return input;
|
|
25
|
-
const header = input.headers.get("authorization") ?? "";
|
|
26
|
-
return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : "";
|
|
27
|
-
}
|
|
28
|
-
async function verifyHubToken2(input, {
|
|
29
|
-
app,
|
|
30
|
-
issuer = process.env.HUB_ISSUER,
|
|
31
|
-
jwks = process.env.HUB_JWKS
|
|
32
|
-
}) {
|
|
33
|
-
if (!issuer) {
|
|
34
|
-
throw new Error("Set HUB_ISSUER: run `bunx user-hub apps register`");
|
|
35
|
-
}
|
|
36
|
-
const token = bearer(input);
|
|
37
|
-
if (!token) {
|
|
38
|
-
throw new Error("No hub token");
|
|
39
|
-
}
|
|
40
|
-
const { payload } = await jwtVerify(token, keySet(jwks, issuer), {
|
|
41
|
-
issuer,
|
|
42
|
-
audience: app,
|
|
43
|
-
algorithms: ["ES256"]
|
|
44
|
-
});
|
|
45
|
-
if (typeof payload.auth_time !== "number") {
|
|
46
|
-
throw new Error("Not a hub sign-in token: it has no auth_time");
|
|
47
|
-
}
|
|
48
|
-
return {
|
|
49
|
-
id: payload.sub,
|
|
50
|
-
name: payload.name,
|
|
51
|
-
team: payload.team,
|
|
52
|
-
role: payload.role === "facilitator" ? "facilitator" : "member"
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export { verifyHubToken2 };
|