@user-hub/auth 0.5.0 → 0.6.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 CHANGED
@@ -88,6 +88,38 @@ import { ConvexHubAuthProvider, HubSignedIn } from "@user-hub/auth/convex-react"
88
88
 
89
89
  The provider always renders its children. `<HubSignedIn>` shows them only to a signed-in person, and "Scan your badge to sign in" otherwise; anything outside it shows to everyone.
90
90
 
91
+ #### Render signed in on the server (TanStack Start, optional)
92
+
93
+ The browser keeps the token, so by default the server renders the loading state and every page load or refresh shows it until the page hydrates. To render the person on the server instead, read the token from the request in the root route and hand it to the provider. The provider keeps a copy of the token in a cookie for this; `getHubToken` checks it with the hub's key and refreshes it with the hub when it is about to expire:
94
+
95
+ ```tsx
96
+ // src/routes/__root.tsx
97
+ import { createServerFn } from "@tanstack/react-start";
98
+ import { getHubToken } from "@user-hub/auth/start";
99
+
100
+ const fetchHubToken = createServerFn({ method: "GET" }).handler(() =>
101
+ getHubToken({ app: "your-app-key", hubUrl: import.meta.env.VITE_HUB_URL }),
102
+ );
103
+
104
+ export const Route = createRootRoute({
105
+ // On the server only: in the browser the provider already has the token,
106
+ // so client navigations skip the round trip. The result travels to the
107
+ // browser with the page.
108
+ beforeLoad: async () => ({
109
+ hubToken: import.meta.env.SSR ? await fetchHubToken() : null,
110
+ }),
111
+ shellComponent: RootDocument,
112
+ });
113
+
114
+ // In RootDocument:
115
+ const { hubToken } = Route.useRouteContext();
116
+ <ConvexHubAuthProvider client={convex} app="your-app-key" hubUrl={import.meta.env.VITE_HUB_URL} initialToken={hubToken}>
117
+ ```
118
+
119
+ Apps that load Convex queries on the server through TanStack Query (`ConvexQueryClient`) also give it the token in `beforeLoad`, so those queries run as the person: `if (hubToken) context.convexQueryClient.serverHttpClient?.setAuth(hubToken)`.
120
+
121
+ 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.
122
+
91
123
  ### 5. Use the person
92
124
 
93
125
  ```tsx
@@ -173,12 +205,13 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
173
205
  |---|---|---|
174
206
  | `@user-hub/auth/convex` | `hubAuth({ app })` | The Convex auth provider, from `HUB_ISSUER` and `HUB_JWKS` |
175
207
  | | `getHubUser(ctx)`, `requireHubUser(ctx)`, `requireFacilitator(ctx)` | The person in Convex functions: or null, or throw |
176
- | `@user-hub/auth/convex-react` | `ConvexHubAuthProvider` | For Convex apps, in place of `ConvexProvider`, inside `<body>`. Props: `client`, `app`, `hubUrl?` |
177
- | `@user-hub/auth/react` | `HubAuthProvider` | The same without Convex: `app`, `hubUrl?` |
208
+ | `@user-hub/auth/convex-react` | `ConvexHubAuthProvider` | For Convex apps, in place of `ConvexProvider`, inside `<body>`. Props: `client`, `app`, `hubUrl?`, `initialToken?` |
209
+ | `@user-hub/auth/react` | `HubAuthProvider` | The same without Convex: `app`, `hubUrl?`, `initialToken?` |
178
210
  | both | `HubSignedIn` | Shows its children only when signed in. Props: `signedOut?`, `loading?` |
179
211
  | | `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` |
180
212
  | | `useHubSession()` | `undefined` while loading, `null` when signed out, otherwise `{ token, user }`; most apps need only `useHubUser()` or `<HubSignedIn>`. Also from `/convex-react` |
181
213
  | `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app })` | Checks a token anywhere else |
214
+ | `@user-hub/auth/start` | `getHubToken({ app, hubUrl })` | TanStack Start, inside a server function: the request's token for `initialToken`, checked and refreshed, or null |
182
215
 
183
216
  ## Developing this package
184
217
 
@@ -0,0 +1,123 @@
1
+ // src/internal/clock.ts
2
+ var clockSkewMs = 0;
3
+ var hubNow = () => Date.now() + clockSkewMs;
4
+ function learnHubClock(issuedAt) {
5
+ clockSkewMs = issuedAt - Date.now();
6
+ }
7
+
8
+ // src/internal/token.ts
9
+ function decodeSegment(segment) {
10
+ const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
11
+ return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
12
+ }
13
+ function payloadOf(token) {
14
+ try {
15
+ return decodeSegment(token.split(".")[1] ?? "");
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+ function readClaims(token) {
21
+ const payload = payloadOf(token);
22
+ if (typeof payload?.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string" || typeof payload.auth_time !== "number") {
23
+ return null;
24
+ }
25
+ return {
26
+ id: payload.sub,
27
+ name: payload.name,
28
+ team: payload.team,
29
+ role: payload.role === "facilitator" ? "facilitator" : "member",
30
+ app: payload.aud,
31
+ expiresAt: payload.exp * 1000
32
+ };
33
+ }
34
+ function sessionFor(token, app, now = Date.now()) {
35
+ const user = token ? readClaims(token) : null;
36
+ return token && user && user.app === app && user.expiresAt > now ? { token, user } : null;
37
+ }
38
+ function newestSession(...sessions) {
39
+ const issued = (s) => refreshInfo(s.token)?.issuedAt ?? 0;
40
+ return sessions.reduce((best, s) => s && (!best || issued(s) > issued(best)) ? s : best, null);
41
+ }
42
+ function refreshInfo(token) {
43
+ const payload = payloadOf(token);
44
+ if (typeof payload?.iss !== "string" || typeof payload.iat !== "number") {
45
+ return null;
46
+ }
47
+ return {
48
+ url: `${payload.iss.replace(/\/+$/, "")}/api/token/refresh`,
49
+ issuedAt: payload.iat * 1000
50
+ };
51
+ }
52
+ function sessionKeyOf(token) {
53
+ const payload = payloadOf(token);
54
+ if (typeof payload?.sub !== "string" || typeof payload.auth_time !== "number") {
55
+ return null;
56
+ }
57
+ return [payload.iss, payload.aud, payload.sub, payload.auth_time].join("|");
58
+ }
59
+
60
+ // src/internal/refresh.ts
61
+ var REQUEST_TIMEOUT_MS = 10 * 1000;
62
+ function originOf(url) {
63
+ try {
64
+ return new URL(url).origin;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+ function refreshUrlFor(token, app, hubUrl) {
70
+ const info = readClaims(token)?.app === app ? refreshInfo(token) : null;
71
+ if (!info)
72
+ return null;
73
+ if (hubUrl === undefined || hubUrl === "")
74
+ return info.url;
75
+ const hub = originOf(hubUrl);
76
+ return hub && originOf(info.url) === hub ? info.url : null;
77
+ }
78
+ async function exchange(token, app, hubUrl) {
79
+ const url = refreshUrlFor(token, app, hubUrl);
80
+ if (!url) {
81
+ return { status: "ended" };
82
+ }
83
+ const controller = new AbortController;
84
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
85
+ try {
86
+ const response = await fetch(url, {
87
+ method: "POST",
88
+ headers: { Authorization: `Bearer ${token}` },
89
+ signal: controller.signal
90
+ });
91
+ if (response.status === 401) {
92
+ return { status: "ended" };
93
+ }
94
+ const next = response.ok ? (await response.json())?.token : null;
95
+ if (typeof next !== "string" || sessionKeyOf(next) !== sessionKeyOf(token)) {
96
+ return { status: "failed" };
97
+ }
98
+ const issuedAt = refreshInfo(next)?.issuedAt;
99
+ if (issuedAt) {
100
+ learnHubClock(issuedAt);
101
+ }
102
+ const session = sessionFor(next, app, hubNow());
103
+ return session ? { status: "refreshed", session } : { status: "failed" };
104
+ } catch {
105
+ return { status: "failed" };
106
+ } finally {
107
+ clearTimeout(timeout);
108
+ }
109
+ }
110
+
111
+ // src/internal/cookie.ts
112
+ var cookieName = (app) => `user-hub-token.${encodeURIComponent(app)}`;
113
+ var COOKIE_MAX_AGE_S = 400 * 24 * 60 * 60;
114
+ var JWT = /^[\w-]+\.[\w-]+\.[\w-]+$/;
115
+ function writeCookie(app, token) {
116
+ try {
117
+ const value = token && JWT.test(token) ? token : null;
118
+ const secure = window.location.protocol === "https:" ? "; Secure" : "";
119
+ document.cookie = `${cookieName(app)}=${value ?? ""}; Path=/; Max-Age=${value ? COOKIE_MAX_AGE_S : 0}; SameSite=Lax${secure}`;
120
+ } catch {}
121
+ }
122
+
123
+ export { hubNow, readClaims, sessionFor, newestSession, refreshInfo, sessionKeyOf, refreshUrlFor, exchange, cookieName, COOKIE_MAX_AGE_S, writeCookie };
@@ -1,3 +1,14 @@
1
+ import {
2
+ hubNow,
3
+ readClaims,
4
+ sessionFor,
5
+ newestSession,
6
+ refreshInfo,
7
+ refreshUrlFor,
8
+ exchange,
9
+ writeCookie
10
+ } from "./convex-55v4qaqb.js";
11
+
1
12
  // src/react.tsx
2
13
  import { useMemo as useMemo2 } from "react";
3
14
 
@@ -13,112 +24,6 @@ import {
13
24
  useSyncExternalStore
14
25
  } from "react";
15
26
 
16
- // src/internal/clock.ts
17
- var clockSkewMs = 0;
18
- var hubNow = () => Date.now() + clockSkewMs;
19
- function learnHubClock(issuedAt) {
20
- clockSkewMs = issuedAt - Date.now();
21
- }
22
-
23
- // src/internal/token.ts
24
- function decodeSegment(segment) {
25
- const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
26
- return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
27
- }
28
- function payloadOf(token) {
29
- try {
30
- return decodeSegment(token.split(".")[1] ?? "");
31
- } catch {
32
- return null;
33
- }
34
- }
35
- function readClaims(token) {
36
- const payload = payloadOf(token);
37
- if (typeof payload?.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string" || typeof payload.auth_time !== "number") {
38
- return null;
39
- }
40
- return {
41
- id: payload.sub,
42
- name: payload.name,
43
- team: payload.team,
44
- role: payload.role === "facilitator" ? "facilitator" : "member",
45
- app: payload.aud,
46
- expiresAt: payload.exp * 1000
47
- };
48
- }
49
- function sessionFor(token, app, now = Date.now()) {
50
- const user = token ? readClaims(token) : null;
51
- return token && user && user.app === app && user.expiresAt > now ? { token, user } : null;
52
- }
53
- function refreshInfo(token) {
54
- const payload = payloadOf(token);
55
- if (typeof payload?.iss !== "string" || typeof payload.iat !== "number") {
56
- return null;
57
- }
58
- return {
59
- url: `${payload.iss.replace(/\/+$/, "")}/api/token/refresh`,
60
- issuedAt: payload.iat * 1000
61
- };
62
- }
63
- function sessionKeyOf(token) {
64
- const payload = payloadOf(token);
65
- if (typeof payload?.sub !== "string" || typeof payload.auth_time !== "number") {
66
- return null;
67
- }
68
- return [payload.iss, payload.aud, payload.sub, payload.auth_time].join("|");
69
- }
70
-
71
- // src/internal/refresh.ts
72
- var REQUEST_TIMEOUT_MS = 10 * 1000;
73
- function originOf(url) {
74
- try {
75
- return new URL(url).origin;
76
- } catch {
77
- return null;
78
- }
79
- }
80
- function refreshUrlFor(token, app, hubUrl) {
81
- const info = readClaims(token)?.app === app ? refreshInfo(token) : null;
82
- if (!info)
83
- return null;
84
- if (hubUrl === undefined || hubUrl === "")
85
- return info.url;
86
- const hub = originOf(hubUrl);
87
- return hub && originOf(info.url) === hub ? info.url : null;
88
- }
89
- async function exchange(token, app, hubUrl) {
90
- const url = refreshUrlFor(token, app, hubUrl);
91
- if (!url) {
92
- return { status: "ended" };
93
- }
94
- const controller = new AbortController;
95
- const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
96
- try {
97
- const response = await fetch(url, {
98
- method: "POST",
99
- headers: { Authorization: `Bearer ${token}` },
100
- signal: controller.signal
101
- });
102
- if (response.status === 401) {
103
- return { status: "ended" };
104
- }
105
- const next = response.ok ? (await response.json())?.token : null;
106
- if (typeof next !== "string" || sessionKeyOf(next) !== sessionKeyOf(token)) {
107
- return { status: "failed" };
108
- }
109
- const issuedAt = refreshInfo(next)?.issuedAt;
110
- if (issuedAt) {
111
- learnHubClock(issuedAt);
112
- }
113
- const session = sessionFor(next, app, hubNow());
114
- return session ? { status: "refreshed", session } : { status: "failed" };
115
- } catch {
116
- return { status: "failed" };
117
- } finally {
118
- clearTimeout(timeout);
119
- }
120
- }
121
-
122
27
  // src/internal/storage.ts
123
28
  var storageKey = (app) => `user-hub-token:${app}`;
124
29
  function readStorage(key) {
@@ -128,8 +33,10 @@ function readStorage(key) {
128
33
  return null;
129
34
  }
130
35
  }
131
- function writeStorage(key, token) {
36
+ function writeToken(app, token) {
37
+ writeCookie(app, token);
132
38
  try {
39
+ const key = storageKey(app);
133
40
  if (token)
134
41
  window.localStorage.setItem(key, token);
135
42
  else
@@ -154,14 +61,17 @@ function takeTokenFromUrl() {
154
61
 
155
62
  // src/internal/store.ts
156
63
  var LOADING = { session: undefined, stalled: null };
157
- var loadingState = () => LOADING;
64
+ function serverState(app, token) {
65
+ const user = token ? readClaims(token) : null;
66
+ return token && user?.app === app ? { session: { token, user }, stalled: null } : LOADING;
67
+ }
158
68
  function sameSession(a, b) {
159
69
  return a === b || a != null && b != null && a.token === b.token;
160
70
  }
161
- function firstState(app, key) {
71
+ function firstState(app, key, initialToken) {
162
72
  if (typeof window === "undefined")
163
- return LOADING;
164
- const session = sessionFor(tokenInUrl(), app, hubNow()) ?? sessionFor(readStorage(key), app, hubNow());
73
+ return serverState(app, initialToken);
74
+ const session = sessionFor(tokenInUrl(), app, hubNow()) ?? newestSession(sessionFor(initialToken ?? null, app, hubNow()), sessionFor(readStorage(key), app, hubNow()));
165
75
  return session ? { session, stalled: null } : LOADING;
166
76
  }
167
77
  function createSessionStore(first) {
@@ -207,11 +117,17 @@ var useHubState = () => useContext(HubContext);
207
117
  function HubSessionProvider({
208
118
  app,
209
119
  hubUrl,
120
+ initialToken,
210
121
  children
211
122
  }) {
212
123
  const key = storageKey(app);
213
- const [store] = useState(() => createSessionStore(firstState(app, key)));
214
- const { session, stalled } = useSyncExternalStore(store.subscribe, store.get, loadingState);
124
+ const [initial] = useState(() => initialToken ?? null);
125
+ const [rendered] = useState(() => serverState(app, initial));
126
+ const [store] = useState(() => {
127
+ const first = firstState(app, key, initial);
128
+ return createSessionStore(first.session?.token === rendered.session?.token ? rendered : first);
129
+ });
130
+ const { session, stalled } = useSyncExternalStore(store.subscribe, store.get, () => rendered);
215
131
  const latest = useRef(store.get().session);
216
132
  const held = useRef(store.get().session?.token ?? null);
217
133
  const inFlight = useRef(null);
@@ -224,17 +140,17 @@ function HubSessionProvider({
224
140
  store.set({ session: next, stalled: stalledToken });
225
141
  }, [store]);
226
142
  const signIn = useCallback((next) => {
227
- writeStorage(key, next.token);
143
+ writeToken(app, next.token);
228
144
  show(next, next.token, null);
229
- }, [key, show]);
145
+ }, [app, show]);
230
146
  const end = useCallback(() => {
231
- writeStorage(key, null);
147
+ writeToken(app, null);
232
148
  show(null, null, null);
233
- }, [key, show]);
149
+ }, [app, show]);
234
150
  const stall = useCallback((token) => {
235
- writeStorage(key, token);
151
+ writeToken(app, token);
236
152
  show(null, token, token);
237
- }, [key, show]);
153
+ }, [app, show]);
238
154
  const currentToken = useCallback(() => {
239
155
  const current = latest.current;
240
156
  return current && current.user.expiresAt > hubNow() ? current.token : null;
@@ -290,7 +206,7 @@ function HubSessionProvider({
290
206
  useEffect(() => {
291
207
  const fromUrl = takeTokenFromUrl();
292
208
  const stored = readStorage(key);
293
- const valid = sessionFor(fromUrl, app, hubNow()) ?? sessionFor(stored, app, hubNow());
209
+ const valid = sessionFor(fromUrl, app, hubNow()) ?? newestSession(sessionFor(initial, app, hubNow()), sessionFor(stored, app, hubNow()));
294
210
  if (valid) {
295
211
  signIn(valid);
296
212
  if (refreshUrlFor(valid.token, app, hubUrl)) {
@@ -298,17 +214,17 @@ function HubSessionProvider({
298
214
  }
299
215
  return;
300
216
  }
301
- const expired = [fromUrl, stored].find((token) => Boolean(token && refreshUrlFor(token, app, hubUrl)));
217
+ const expired = [fromUrl, stored, initial].find((token) => Boolean(token && refreshUrlFor(token, app, hubUrl)));
302
218
  if (!expired) {
303
219
  end();
304
220
  return;
305
221
  }
306
- writeStorage(key, expired);
222
+ writeToken(app, expired);
307
223
  held.current = expired;
308
224
  latest.current = undefined;
309
225
  store.set(LOADING);
310
226
  trade(expired);
311
- }, [app, hubUrl, key, store, signIn, end, trade]);
227
+ }, [app, hubUrl, key, initial, store, signIn, end, trade]);
312
228
  useEffect(() => {
313
229
  if (!stalled)
314
230
  return;
@@ -421,4 +337,4 @@ function useHubToken2() {
421
337
  return useHubSession2()?.token ?? null;
422
338
  }
423
339
 
424
- export { sessionKeyOf, useHubState, HubSessionProvider, HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2 };
340
+ export { useHubState, HubSessionProvider, HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2 };
@@ -1,5 +1,7 @@
1
1
  import {
2
- sessionKeyOf,
2
+ sessionKeyOf
3
+ } from "./convex-55v4qaqb.js";
4
+ import {
3
5
  useHubState,
4
6
  HubSessionProvider,
5
7
  HubSignedIn2,
@@ -7,7 +9,7 @@ import {
7
9
  useHubSession2,
8
10
  useHubUser2,
9
11
  useHubToken2
10
- } from "./convex-89hjtnwh.js";
12
+ } from "./convex-kpwbsxky.js";
11
13
 
12
14
  // src/convex-react.tsx
13
15
  import {
@@ -0,0 +1,56 @@
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 };
@@ -0,0 +1,3 @@
1
+ export declare const cookieName: (app: string) => string;
2
+ export declare const COOKIE_MAX_AGE_S: number;
3
+ export declare function writeCookie(app: string, token: string | null): void;
@@ -0,0 +1,19 @@
1
+ export declare const MIN_LIFETIME_MS: number;
2
+ export type TokenCookie = {
3
+ get(): string | undefined;
4
+ set(token: string): void;
5
+ clear(): void;
6
+ };
7
+ export type HubTokenOptions = {
8
+ app: string;
9
+ hubUrl?: string;
10
+ issuer?: string;
11
+ jwks?: string;
12
+ };
13
+ /**
14
+ * The cookie's token when it is genuine and has minutes left, refreshed with
15
+ * the hub first when it has not; null when there is nothing to render the
16
+ * person from. Null never means signed out: the browser still decides that,
17
+ * so the cookie is only cleared when the hub has ended the session.
18
+ */
19
+ export declare function resolveHubToken(cookie: TokenCookie, { app, hubUrl, issuer, jwks, }: HubTokenOptions): Promise<string | null>;
@@ -12,6 +12,7 @@ export declare const useHubState: () => HubState;
12
12
  export type HubAuthProviderProps = {
13
13
  app: string;
14
14
  hubUrl?: string;
15
+ initialToken?: string | null;
15
16
  children: ReactNode;
16
17
  };
17
18
  /**
@@ -20,5 +21,5 @@ export type HubAuthProviderProps = {
20
21
  * schedule (and whenever Convex asks), follows other tabs of the same app,
21
22
  * and signs out when the hub ends the session.
22
23
  */
23
- export declare function HubSessionProvider({ app, hubUrl, children, }: HubAuthProviderProps): import("react").JSX.Element;
24
+ export declare function HubSessionProvider({ app, hubUrl, initialToken, children, }: HubAuthProviderProps): import("react").JSX.Element;
24
25
  export {};
@@ -1,3 +1,3 @@
1
1
  export declare const storageKey: (app: string) => string;
2
2
  export declare function readStorage(key: string): string | null;
3
- export declare function writeStorage(key: string, token: string | null): void;
3
+ export declare function writeToken(app: string, token: string | null): void;
@@ -4,8 +4,8 @@ export type SessionState = {
4
4
  stalled: string | null;
5
5
  };
6
6
  export declare const LOADING: SessionState;
7
- export declare const loadingState: () => SessionState;
8
- export declare function firstState(app: string, key: string): SessionState;
7
+ export declare function serverState(app: string, token?: string | null): SessionState;
8
+ export declare function firstState(app: string, key: string, initialToken?: string | null): SessionState;
9
9
  export declare function createSessionStore(first: SessionState): {
10
10
  get: () => SessionState;
11
11
  set: (next: Partial<SessionState>) => void;
@@ -15,6 +15,7 @@ export type HubSession = {
15
15
  user: HubClaims;
16
16
  };
17
17
  export declare function sessionFor(token: string | null, app: string, now?: number): HubSession | null;
18
+ export declare function newestSession(...sessions: (HubSession | null)[]): HubSession | null;
18
19
  export declare function refreshInfo(token: string): {
19
20
  url: string;
20
21
  issuedAt: number;
package/dist/react.js CHANGED
@@ -5,7 +5,8 @@ import {
5
5
  useHubSession2,
6
6
  useHubUser2,
7
7
  useHubToken2
8
- } from "./convex-89hjtnwh.js";
8
+ } from "./convex-kpwbsxky.js";
9
+ import"./convex-55v4qaqb.js";
9
10
  export {
10
11
  HubAuthProvider2 as HubAuthProvider,
11
12
  HubSignedIn2 as HubSignedIn,
package/dist/server.js CHANGED
@@ -1,57 +1,6 @@
1
- // src/server.ts
2
1
  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 verifyHubToken(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
- }
2
+ verifyHubToken2
3
+ } from "./convex-tx5kfb4e.js";
55
4
  export {
56
- verifyHubToken
5
+ verifyHubToken2 as verifyHubToken
57
6
  };
@@ -0,0 +1,13 @@
1
+ import { type HubTokenOptions } from "./internal/server-session";
2
+ export type { HubTokenOptions } from "./internal/server-session";
3
+ /**
4
+ * For TanStack Start: the signed-in person's token from this request's
5
+ * cookie, so the server renders the page signed in instead of the loading
6
+ * state. Call it inside a server function (it reads the request) and pass the
7
+ * result to the provider's `initialToken`. Checks the token with the hub's
8
+ * key, and refreshes it with the hub when it is about to expire. Returns null
9
+ * when it cannot vouch for one; the page then renders as loading and the
10
+ * browser settles it, as without it. A response it returns a token for is
11
+ * marked private and never stored, since the page then carries the token.
12
+ */
13
+ export declare function getHubToken(options: HubTokenOptions): Promise<string | null>;
package/dist/start.js ADDED
@@ -0,0 +1,83 @@
1
+ import {
2
+ hubNow,
3
+ readClaims,
4
+ exchange,
5
+ cookieName,
6
+ COOKIE_MAX_AGE_S
7
+ } from "./convex-55v4qaqb.js";
8
+ import {
9
+ verifyHubToken2
10
+ } from "./convex-tx5kfb4e.js";
11
+
12
+ // src/start.ts
13
+ import {
14
+ appendResponseHeader,
15
+ deleteCookie,
16
+ getCookie,
17
+ getRequestProtocol,
18
+ setCookie,
19
+ setResponseHeader
20
+ } 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
+ async function getHubToken(options) {
63
+ const name = cookieName(options.app);
64
+ const secure = getRequestProtocol({ xForwardedProto: true }) === "https";
65
+ const token = await resolveHubToken({
66
+ get: () => getCookie(name),
67
+ set: (token) => setCookie(name, token, {
68
+ path: "/",
69
+ maxAge: COOKIE_MAX_AGE_S,
70
+ sameSite: "lax",
71
+ secure
72
+ }),
73
+ clear: () => deleteCookie(name, { path: "/" })
74
+ }, options);
75
+ if (token) {
76
+ setResponseHeader("Cache-Control", "private, no-store");
77
+ appendResponseHeader("Vary", "Cookie");
78
+ }
79
+ return token;
80
+ }
81
+ export {
82
+ getHubToken
83
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@user-hub/auth",
3
- "version": "0.5.0",
3
+ "version": "0.6.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",
@@ -8,6 +8,7 @@
8
8
  "convex",
9
9
  "qr",
10
10
  "react",
11
+ "tanstack-start",
11
12
  "user-hub"
12
13
  ],
13
14
  "files": [
@@ -31,13 +32,17 @@
31
32
  "./convex-react": {
32
33
  "types": "./dist/convex-react.d.ts",
33
34
  "default": "./dist/convex-react.js"
35
+ },
36
+ "./start": {
37
+ "types": "./dist/start.d.ts",
38
+ "default": "./dist/start.js"
34
39
  }
35
40
  },
36
41
  "publishConfig": {
37
42
  "access": "public"
38
43
  },
39
44
  "scripts": {
40
- "build": "rm -rf dist && bun build src/convex.ts src/react.tsx src/convex-react.tsx src/server.ts --outdir dist --target node --format esm --splitting --packages external && tsc -p tsconfig.build.json",
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",
41
46
  "check": "vp check",
42
47
  "fix": "vp check --fix",
43
48
  "lint": "vp lint",
@@ -50,6 +55,7 @@
50
55
  },
51
56
  "devDependencies": {
52
57
  "@happy-dom/global-registrator": "^21.0.4",
58
+ "@tanstack/react-start": "^1.169.5",
53
59
  "@types/bun": "^1.4.4",
54
60
  "@types/react": "^19.3.0",
55
61
  "@types/react-dom": "^19.3.0",
@@ -60,6 +66,7 @@
60
66
  "vite-plus": "1.7.0"
61
67
  },
62
68
  "peerDependencies": {
69
+ "@tanstack/react-start": ">=1.169.0",
63
70
  "convex": ">=1.25.0",
64
71
  "react": ">=19"
65
72
  },
@@ -69,6 +76,9 @@
69
76
  },
70
77
  "react": {
71
78
  "optional": true
79
+ },
80
+ "@tanstack/react-start": {
81
+ "optional": true
72
82
  }
73
83
  }
74
84
  }
@@ -36,6 +36,7 @@ The hub's URL also comes from the human. It goes in three places with the same v
36
36
  - **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
37
  - **Check access on the server**: `requireHubUser(ctx)` / `requireFacilitator(ctx)` in Convex, `verifyHubToken` elsewhere. `useHubUser()` is for display; hiding a page protects nothing.
38
38
  - **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
+ - **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.
39
40
  - **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.
40
41
  - **No other sign-in.** No login screens, passwords or sessions. If something is missing, it belongs in `@user-hub/auth`.
41
42
  - **Secrets stay out of chat and files you write.** The API key lives only in `.env.local`, saved by `user-hub login`.
@@ -55,6 +55,26 @@ import { ConvexHubAuthProvider, HubSignedIn } from "@user-hub/auth/convex-react"
55
55
 
56
56
  **Without Convex:** `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth/react`, same place, same props minus `client`.
57
57
 
58
+ **Render signed in on the server (TanStack Start).** Without this, every page load or refresh shows `loading` until the page hydrates. Read the token in the root route and pass it as `initialToken`:
59
+
60
+ ```tsx
61
+ import { createServerFn } from "@tanstack/react-start";
62
+ import { getHubToken } from "@user-hub/auth/start";
63
+
64
+ const fetchHubToken = createServerFn({ method: "GET" }).handler(() =>
65
+ getHubToken({ app: "<key>", hubUrl: import.meta.env.VITE_HUB_URL }),
66
+ );
67
+
68
+ // In createRootRoute / createRootRouteWithContext (server only: the browser already has the token):
69
+ beforeLoad: async () => ({ hubToken: import.meta.env.SSR ? await fetchHubToken() : null }),
70
+
71
+ // In the shell component:
72
+ const { hubToken } = Route.useRouteContext();
73
+ <ConvexHubAuthProvider client={convex} app="<key>" hubUrl={import.meta.env.VITE_HUB_URL} initialToken={hubToken}>
74
+ ```
75
+
76
+ With `ConvexQueryClient` (Convex through TanStack Query), also call `context.convexQueryClient.serverHttpClient?.setAuth(hubToken)` in `beforeLoad` when there is a token, so server-side queries run as the person. Never read or set the `user-hub-token.<key>` cookie yourself: the provider writes it and `getHubToken` reads it.
77
+
58
78
  ## 5. Use the person
59
79
 
60
80
  | Where | How |