@user-hub/auth 0.6.2 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -2
- package/dist/convex-77ptkyt2.js +108 -0
- package/dist/convex-c4m6k5st.js +53 -0
- package/dist/convex-ctn06a2f.js +72 -0
- package/dist/convex-react.js +4 -4
- package/dist/convex-rwq8r0rm.js +90 -0
- package/dist/{convex-nqc41e3r.js → convex-zj2n2r92.js} +51 -20
- package/dist/internal/keys.d.ts +24 -0
- package/dist/internal/live-session.d.ts +20 -0
- package/dist/internal/private-response.d.ts +7 -0
- package/dist/internal/render-token.d.ts +22 -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 +24 -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 +31 -0
- package/dist/start-convex.js +29 -0
- package/dist/start-middleware.d.ts +27 -0
- package/dist/start-middleware.js +15 -0
- package/dist/start.js +35 -56
- 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 +75 -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, 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
|
+
- `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` (type `HubConvexContext`) |
|
|
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
|
|
|
@@ -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 };
|
|
@@ -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 };
|
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-zj2n2r92.js";
|
|
10
|
+
import {
|
|
11
|
+
sessionKeyOf
|
|
12
|
+
} from "./convex-55v4qaqb.js";
|
|
13
13
|
|
|
14
14
|
// src/convex-react.tsx
|
|
15
15
|
import {
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hubKeys,
|
|
3
|
+
verifyHubToken2
|
|
4
|
+
} from "./convex-ctn06a2f.js";
|
|
5
|
+
import {
|
|
6
|
+
tokenForRequest
|
|
7
|
+
} from "./convex-c4m6k5st.js";
|
|
8
|
+
import {
|
|
9
|
+
markPrivate,
|
|
10
|
+
RENDER_KEY,
|
|
11
|
+
renderSecret,
|
|
12
|
+
isRender,
|
|
13
|
+
renderToken
|
|
14
|
+
} from "./convex-77ptkyt2.js";
|
|
15
|
+
|
|
16
|
+
// src/internal/start-middleware.ts
|
|
17
|
+
import {
|
|
18
|
+
createMiddleware
|
|
19
|
+
} from "@tanstack/react-start";
|
|
20
|
+
|
|
21
|
+
// src/internal/request-auth.ts
|
|
22
|
+
var SIGN_IN_MESSAGE = "Scan your badge to sign in.";
|
|
23
|
+
var BEARER = /^Bearer\s+(\S+)$/i;
|
|
24
|
+
var REJECTED_TOKEN = new Set([
|
|
25
|
+
"ERR_JWT_EXPIRED",
|
|
26
|
+
"ERR_JWT_CLAIM_VALIDATION_FAILED",
|
|
27
|
+
"ERR_JWT_INVALID",
|
|
28
|
+
"ERR_JWS_INVALID",
|
|
29
|
+
"ERR_JWS_SIGNATURE_VERIFICATION_FAILED",
|
|
30
|
+
"ERR_JWKS_NO_MATCHING_KEY",
|
|
31
|
+
"ERR_JWKS_MULTIPLE_MATCHING_KEYS",
|
|
32
|
+
"ERR_JOSE_ALG_NOT_ALLOWED",
|
|
33
|
+
"ERR_JOSE_NOT_SUPPORTED"
|
|
34
|
+
]);
|
|
35
|
+
var rejectedToken = (error) => REJECTED_TOKEN.has(error?.code);
|
|
36
|
+
async function authenticate(request, options) {
|
|
37
|
+
hubKeys(options);
|
|
38
|
+
const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
|
|
39
|
+
if (!token)
|
|
40
|
+
return null;
|
|
41
|
+
try {
|
|
42
|
+
return { hub: await verifyHubToken2(token, options), hubToken: token };
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (rejectedToken(error))
|
|
45
|
+
return null;
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/internal/start-middleware.ts
|
|
51
|
+
function hubRequestMiddleware(options) {
|
|
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
|
+
}
|
|
60
|
+
if (!auth) {
|
|
61
|
+
if (handlerType === "router" && !serverFnMeta) {
|
|
62
|
+
return new Response(SIGN_IN_MESSAGE, { status: 401 });
|
|
63
|
+
}
|
|
64
|
+
throw new Error(SIGN_IN_MESSAGE);
|
|
65
|
+
}
|
|
66
|
+
return next({ context: auth });
|
|
67
|
+
});
|
|
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
|
+
}
|
|
76
|
+
function hubServerFnMiddleware(app, request) {
|
|
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
|
+
}
|
|
82
|
+
const token = await tokenForRequest(app);
|
|
83
|
+
return next({
|
|
84
|
+
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
85
|
+
sendContext: {}
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export { hubRequestMiddleware, hubServerFnMiddleware };
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
registerLiveSession,
|
|
3
|
+
sendableToken
|
|
4
|
+
} from "./convex-c4m6k5st.js";
|
|
1
5
|
import {
|
|
2
6
|
hubNow,
|
|
3
7
|
readClaims,
|
|
@@ -19,6 +23,7 @@ import {
|
|
|
19
23
|
useCallback,
|
|
20
24
|
useContext,
|
|
21
25
|
useEffect,
|
|
26
|
+
useLayoutEffect,
|
|
22
27
|
useMemo,
|
|
23
28
|
useRef,
|
|
24
29
|
useState,
|
|
@@ -144,6 +149,13 @@ function HubSessionProvider({
|
|
|
144
149
|
const latest = useRef(store.get().session);
|
|
145
150
|
const held = useRef(store.get().session?.token ?? null);
|
|
146
151
|
const inFlight = useRef(null);
|
|
152
|
+
const [loaded] = useState(() => {
|
|
153
|
+
let settle = () => {};
|
|
154
|
+
const promise = new Promise((resolve) => {
|
|
155
|
+
settle = resolve;
|
|
156
|
+
});
|
|
157
|
+
return { promise, settle };
|
|
158
|
+
});
|
|
147
159
|
const mounted = useRef(false);
|
|
148
160
|
const lastRequest = useRef(0);
|
|
149
161
|
const redirecting = session === null && Boolean(hubUrl) && typeof window !== "undefined" && LOCAL_HOST.test(window.location.hostname);
|
|
@@ -222,34 +234,53 @@ function HubSessionProvider({
|
|
|
222
234
|
}
|
|
223
235
|
return await trade(current.token);
|
|
224
236
|
}, [app, hubUrl, currentToken, trade]);
|
|
225
|
-
|
|
237
|
+
useLayoutEffect(() => {
|
|
226
238
|
mounted.current = true;
|
|
227
239
|
return () => {
|
|
228
240
|
mounted.current = false;
|
|
229
241
|
};
|
|
230
242
|
}, []);
|
|
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]);
|
|
231
258
|
useEffect(() => {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
259
|
+
try {
|
|
260
|
+
const fromUrl = takeTokenFromUrl();
|
|
261
|
+
const stored = readStorage(key);
|
|
262
|
+
const valid = sessionFor(fromUrl, app, hubNow()) ?? newestSession(sessionFor(initial, app, hubNow()), sessionFor(stored, app, hubNow()));
|
|
263
|
+
if (valid) {
|
|
264
|
+
signIn(valid);
|
|
265
|
+
if (refreshUrlFor(valid.token, app, hubUrl) && (valid.token === fromUrl || !recentlyRefreshed(valid.token))) {
|
|
266
|
+
trade(valid.token);
|
|
267
|
+
}
|
|
268
|
+
return;
|
|
239
269
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
270
|
+
const expired = [fromUrl, stored, initial].find((token) => Boolean(token && refreshUrlFor(token, app, hubUrl)));
|
|
271
|
+
if (!expired) {
|
|
272
|
+
end();
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
writeToken(app, expired);
|
|
276
|
+
held.current = expired;
|
|
277
|
+
latest.current = undefined;
|
|
278
|
+
store.set(LOADING);
|
|
279
|
+
trade(expired);
|
|
280
|
+
} finally {
|
|
281
|
+
loaded.settle();
|
|
246
282
|
}
|
|
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]);
|
|
283
|
+
}, [app, hubUrl, key, initial, store, signIn, end, trade, loaded]);
|
|
253
284
|
useEffect(() => {
|
|
254
285
|
if (!stalled)
|
|
255
286
|
return;
|
|
@@ -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,20 @@
|
|
|
1
|
+
export type LiveSession = {
|
|
2
|
+
tokenForRequest: () => Promise<string | null>;
|
|
3
|
+
};
|
|
4
|
+
export declare const PROVIDER_WAIT_MS: number;
|
|
5
|
+
export declare const MIN_SEND_LIFETIME_MS: number;
|
|
6
|
+
/** Registers the provider's session; returns the unregister function. */
|
|
7
|
+
export declare function registerLiveSession(app: string, session: LiveSession): () => void;
|
|
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
|
+
*/
|
|
13
|
+
export declare function tokenForRequest(app: string): Promise<string | null>;
|
|
14
|
+
/**
|
|
15
|
+
* The provider's side: the current token while it has over a minute left,
|
|
16
|
+
* else the next one from the hub (refresh keeps a still-valid token when the
|
|
17
|
+
* hub cannot be reached, and gives null once signed out). `now` is the
|
|
18
|
+
* provider's hub clock.
|
|
19
|
+
*/
|
|
20
|
+
export declare function sendableToken(currentToken: string | null, refresh: () => Promise<string | null>, now: number): Promise<string | null>;
|
|
@@ -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>;
|
|
@@ -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,24 @@
|
|
|
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>;
|
|
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. 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.
|
|
18
|
+
*/
|
|
19
|
+
export declare function hubRequestMiddleware(options: HubMiddlewareOptions): HubRequestMiddleware;
|
|
20
|
+
/**
|
|
21
|
+
* Server functions: the browser sends the provider's current token (refreshed
|
|
22
|
+
* first when it is about to expire), then `request` checks it on the server.
|
|
23
|
+
*/
|
|
24
|
+
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,31 @@
|
|
|
1
|
+
import { type RequestMiddlewareAfterServer } from "@tanstack/react-start";
|
|
2
|
+
import { ConvexHttpClient } from "convex/browser";
|
|
3
|
+
import type { HubAuthContext, 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
|
+
/** What hubConvexMiddleware adds to the handler's context. */
|
|
9
|
+
export type HubConvexContext = HubAuthContext & {
|
|
10
|
+
convex: ConvexHttpClient;
|
|
11
|
+
};
|
|
12
|
+
/** hubConvexMiddleware's request middleware: the person, then Convex. */
|
|
13
|
+
export type HubConvexRequestMiddleware = RequestMiddlewareAfterServer<{}, readonly [HubRequestMiddleware], {
|
|
14
|
+
convex: ConvexHttpClient;
|
|
15
|
+
}>;
|
|
16
|
+
/**
|
|
17
|
+
* hubMiddleware (`@user-hub/auth/start-middleware`) for apps on Convex: the
|
|
18
|
+
* handler also gets `context.convex`, a ConvexHttpClient acting as the
|
|
19
|
+
* person, so Convex checks them again (requireHubUser) for every call.
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* export const hub = hubConvexMiddleware({
|
|
23
|
+
* app: APP_KEY,
|
|
24
|
+
* hubUrl: import.meta.env.VITE_HUB_URL,
|
|
25
|
+
* convexUrl: import.meta.env.VITE_CONVEX_URL,
|
|
26
|
+
* });
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare function hubConvexMiddleware({ convexUrl, ...options }: HubMiddlewareOptions & {
|
|
30
|
+
convexUrl: string | undefined;
|
|
31
|
+
}): HubMiddleware<HubConvexRequestMiddleware>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import"./convex-ctn06a2f.js";
|
|
2
|
+
import {
|
|
3
|
+
hubRequestMiddleware,
|
|
4
|
+
hubServerFnMiddleware
|
|
5
|
+
} from "./convex-rwq8r0rm.js";
|
|
6
|
+
import"./convex-77ptkyt2.js";
|
|
7
|
+
|
|
8
|
+
// src/start-convex.ts
|
|
9
|
+
import {
|
|
10
|
+
createMiddleware
|
|
11
|
+
} from "@tanstack/react-start";
|
|
12
|
+
import { ConvexHttpClient } from "convex/browser";
|
|
13
|
+
function hubConvexMiddleware({
|
|
14
|
+
convexUrl,
|
|
15
|
+
...options
|
|
16
|
+
}) {
|
|
17
|
+
if (!convexUrl) {
|
|
18
|
+
throw new Error("hubConvexMiddleware needs convexUrl (VITE_CONVEX_URL)");
|
|
19
|
+
}
|
|
20
|
+
const request = createMiddleware().middleware([hubRequestMiddleware(options)]).server(({ next, context }) => {
|
|
21
|
+
const convex = new ConvexHttpClient(convexUrl);
|
|
22
|
+
convex.setAuth(context.hubToken);
|
|
23
|
+
return next({ context: { convex } });
|
|
24
|
+
});
|
|
25
|
+
return { request, serverFn: hubServerFnMiddleware(options.app, request) };
|
|
26
|
+
}
|
|
27
|
+
export {
|
|
28
|
+
hubConvexMiddleware
|
|
29
|
+
};
|
|
@@ -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,15 @@
|
|
|
1
|
+
import"./convex-ctn06a2f.js";
|
|
2
|
+
import {
|
|
3
|
+
hubRequestMiddleware,
|
|
4
|
+
hubServerFnMiddleware
|
|
5
|
+
} from "./convex-rwq8r0rm.js";
|
|
6
|
+
import"./convex-77ptkyt2.js";
|
|
7
|
+
|
|
8
|
+
// src/start-middleware.ts
|
|
9
|
+
function hubMiddleware(options) {
|
|
10
|
+
const request = hubRequestMiddleware(options);
|
|
11
|
+
return { request, serverFn: hubServerFnMiddleware(options.app, request) };
|
|
12
|
+
}
|
|
13
|
+
export {
|
|
14
|
+
hubMiddleware
|
|
15
|
+
};
|
package/dist/start.js
CHANGED
|
@@ -1,80 +1,59 @@
|
|
|
1
|
+
import"./convex-ctn06a2f.js";
|
|
2
|
+
import {
|
|
3
|
+
markPrivate,
|
|
4
|
+
resolveHubToken,
|
|
5
|
+
existingRenderToken,
|
|
6
|
+
rememberRenderToken
|
|
7
|
+
} from "./convex-77ptkyt2.js";
|
|
1
8
|
import {
|
|
2
|
-
hubNow,
|
|
3
|
-
readClaims,
|
|
4
|
-
exchange,
|
|
5
9
|
cookieName,
|
|
6
10
|
COOKIE_MAX_AGE_S
|
|
7
11
|
} from "./convex-55v4qaqb.js";
|
|
8
|
-
import {
|
|
9
|
-
verifyHubToken2
|
|
10
|
-
} from "./convex-tx5kfb4e.js";
|
|
11
12
|
|
|
12
13
|
// src/start.ts
|
|
13
14
|
import {
|
|
14
15
|
appendResponseHeader,
|
|
15
16
|
deleteCookie,
|
|
16
17
|
getCookie,
|
|
18
|
+
getRequest,
|
|
17
19
|
getRequestProtocol,
|
|
20
|
+
getResponseHeader,
|
|
18
21
|
setCookie,
|
|
19
22
|
setResponseHeader
|
|
20
23
|
} from "@tanstack/react-start/server";
|
|
21
|
-
|
|
22
|
-
// src/internal/server-session.ts
|
|
23
|
-
var MIN_LIFETIME_MS = 2 * 60 * 1000;
|
|
24
|
-
async function verified(token, app, issuer, jwks) {
|
|
25
|
-
try {
|
|
26
|
-
await verifyHubToken2(token, { app, issuer, jwks });
|
|
27
|
-
return true;
|
|
28
|
-
} catch {
|
|
29
|
-
return false;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
async function resolveHubToken(cookie, {
|
|
33
|
-
app,
|
|
34
|
-
hubUrl,
|
|
35
|
-
issuer = process.env.HUB_ISSUER || hubUrl?.replace(/\/+$/, ""),
|
|
36
|
-
jwks = process.env.HUB_JWKS || undefined
|
|
37
|
-
}) {
|
|
38
|
-
const token = cookie.get();
|
|
39
|
-
const user = token ? readClaims(token) : null;
|
|
40
|
-
if (!token || !issuer || user?.app !== app)
|
|
41
|
-
return null;
|
|
42
|
-
if (user.expiresAt - hubNow() > MIN_LIFETIME_MS) {
|
|
43
|
-
return await verified(token, app, issuer, jwks) ? token : null;
|
|
44
|
-
}
|
|
45
|
-
if (!hubUrl)
|
|
46
|
-
return null;
|
|
47
|
-
const result = await exchange(token, app, hubUrl);
|
|
48
|
-
if (result.status === "ended") {
|
|
49
|
-
cookie.clear();
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
if (result.status === "failed")
|
|
53
|
-
return null;
|
|
54
|
-
const next = result.session.token;
|
|
55
|
-
if (!await verified(next, app, issuer, jwks))
|
|
56
|
-
return null;
|
|
57
|
-
cookie.set(next);
|
|
58
|
-
return next;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// src/start.ts
|
|
62
24
|
async function getHubToken(options) {
|
|
63
25
|
const name = cookieName(options.app);
|
|
64
26
|
const secure = getRequestProtocol({ xForwardedProto: true }) === "https";
|
|
65
|
-
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({
|
|
66
49
|
get: () => getCookie(name),
|
|
67
|
-
set:
|
|
68
|
-
path: "/",
|
|
69
|
-
maxAge: COOKIE_MAX_AGE_S,
|
|
70
|
-
sameSite: "lax",
|
|
71
|
-
secure
|
|
72
|
-
}),
|
|
50
|
+
set: writeCookie,
|
|
73
51
|
clear: () => deleteCookie(name, { path: "/" })
|
|
74
52
|
}, options);
|
|
53
|
+
rememberRenderToken(request, options.app, resolving);
|
|
54
|
+
const token = await resolving;
|
|
75
55
|
if (token) {
|
|
76
|
-
|
|
77
|
-
appendResponseHeader("Vary", "Cookie");
|
|
56
|
+
markPrivate({ getResponseHeader, setResponseHeader, appendResponseHeader });
|
|
78
57
|
}
|
|
79
58
|
return token;
|
|
80
59
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@user-hub/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
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,75 @@
|
|
|
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: 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
|
+
|
|
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
|
+
- **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.
|
|
74
|
+
- **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.
|
|
75
|
+
- **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 };
|