@user-hub/auth 0.1.7 → 0.2.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 +15 -4
- package/dist/convex-qxqkx9zh.js +377 -0
- package/dist/convex-react.d.ts +1 -1
- package/dist/convex-react.js +22 -14
- package/dist/react.d.ts +9 -9
- package/dist/react.js +1 -1
- package/dist/session.d.ts +25 -0
- package/dist/token.d.ts +5 -0
- package/package.json +1 -1
- package/skills/user-hub-auth/SKILL.md +4 -3
- package/dist/convex-zgnvvwvn.js +0 -140
package/README.md
CHANGED
|
@@ -10,9 +10,20 @@ Works with Convex apps, React frontends and any server that can check a token.
|
|
|
10
10
|
|
|
11
11
|
1. A person scans their badge. The hub sends them to your app with a token in the URL: `https://your-app.com/#token=…`.
|
|
12
12
|
2. The provider takes the token out of the address bar and keeps it in the browser, separately for each app.
|
|
13
|
-
3. Convex (or your server) checks the token with the hub's public key. A token is only accepted by the app it was made for
|
|
13
|
+
3. Convex (or your server) checks the token with the hub's public key. A token is only accepted by the app it was made for.
|
|
14
14
|
4. Your app stores its own data under the person's `id`.
|
|
15
15
|
|
|
16
|
+
## Sessions
|
|
17
|
+
|
|
18
|
+
The hub decides how long a scan keeps someone signed in: 1, 2 or 4 hours, or until they are signed out from the hub. Your app needs no setup for this.
|
|
19
|
+
|
|
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
|
+
- Reopening the app later (even the next day) keeps the person signed in while their session lasts.
|
|
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.
|
|
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
|
+
- A Content Security Policy needs the hub in `connect-src`.
|
|
26
|
+
|
|
16
27
|
## Quick start
|
|
17
28
|
|
|
18
29
|
### 1. Install
|
|
@@ -103,7 +114,7 @@ export const myVotes = query({
|
|
|
103
114
|
|
|
104
115
|
## Working on your app locally
|
|
105
116
|
|
|
106
|
-
Run your dev server as usual and open it. With no token yet, it sends you to the hub, where you pick who to be (the admin password is asked once per browser), and brings you back signed in. You stay signed in
|
|
117
|
+
Run your dev server as usual and open it. With no token yet, it sends you to the hub, where you pick who to be (the admin password is asked once per browser), and brings you back signed in. You stay signed in across reloads and restarts until that person's expiration in the hub (4 hours unless set otherwise).
|
|
107
118
|
|
|
108
119
|
- **Switch person:** open `<hub>/open/<your-app-key>`.
|
|
109
120
|
- **Different port:** run `hub-user register` again with the new `--dev` URL. The hub only sends tokens to registered URLs.
|
|
@@ -145,7 +156,7 @@ Hiding a page does not protect it: the server check does.
|
|
|
145
156
|
|
|
146
157
|
## Not using Convex?
|
|
147
158
|
|
|
148
|
-
Send the token to your server and check it there:
|
|
159
|
+
Send the token to your server and check it there. It changes every few minutes as it is refreshed, so read it for each request:
|
|
149
160
|
|
|
150
161
|
```tsx
|
|
151
162
|
const token = useHubToken();
|
|
@@ -169,7 +180,7 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
|
|
|
169
180
|
| `@user-hub/auth/convex-react` | `ConvexHubAuthProvider` | For Convex apps, in place of `ConvexProvider`, inside `<body>`. Props: `client`, `app`, `hubUrl?` |
|
|
170
181
|
| `@user-hub/auth/react` | `HubAuthProvider` | The same without Convex: `app`, `hubUrl?` |
|
|
171
182
|
| both | `HubSignedIn` | Shows its children only when signed in. Props: `signedOut?`, `loading?` |
|
|
172
|
-
| | `useHubUser()`, `useHubToken()`, `useHubSignOut()` | The person (or null), the
|
|
183
|
+
| | `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` |
|
|
173
184
|
| `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app })` | Checks a token anywhere else |
|
|
174
185
|
| CLI | `hub-user register --name <name> [--prod <url>] [--dev <url>] [--new] [--hub <url>] [--json]` | Registers or updates the app (at least one URL); `--new` only creates, exit code 3 if the name is taken |
|
|
175
186
|
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
// src/react.tsx
|
|
2
|
+
import { useMemo as useMemo2 } from "react";
|
|
3
|
+
|
|
4
|
+
// src/session.tsx
|
|
5
|
+
import {
|
|
6
|
+
createContext,
|
|
7
|
+
useCallback,
|
|
8
|
+
useContext,
|
|
9
|
+
useEffect,
|
|
10
|
+
useMemo,
|
|
11
|
+
useRef,
|
|
12
|
+
useState
|
|
13
|
+
} from "react";
|
|
14
|
+
|
|
15
|
+
// src/token.ts
|
|
16
|
+
function decodeSegment(segment) {
|
|
17
|
+
const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
|
|
18
|
+
return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
|
|
19
|
+
}
|
|
20
|
+
function payloadOf(token) {
|
|
21
|
+
try {
|
|
22
|
+
return decodeSegment(token.split(".")[1] ?? "");
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function readClaims(token) {
|
|
28
|
+
const payload = payloadOf(token);
|
|
29
|
+
if (typeof payload?.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string") {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
id: payload.sub,
|
|
34
|
+
name: payload.name,
|
|
35
|
+
team: payload.team,
|
|
36
|
+
role: payload.role === "facilitator" ? "facilitator" : "member",
|
|
37
|
+
app: payload.aud,
|
|
38
|
+
expiresAt: payload.exp * 1000
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function sessionFor(token, app, now = Date.now()) {
|
|
42
|
+
const user = token ? readClaims(token) : null;
|
|
43
|
+
return token && user && user.app === app && user.expiresAt > now ? { token, user } : null;
|
|
44
|
+
}
|
|
45
|
+
function refreshInfo(token) {
|
|
46
|
+
const payload = payloadOf(token);
|
|
47
|
+
if (typeof payload?.iss !== "string" || typeof payload.iat !== "number" || typeof payload.auth_time !== "number") {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
url: `${payload.iss.replace(/\/+$/, "")}/api/token/refresh`,
|
|
52
|
+
issuedAt: payload.iat * 1000
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function sessionKeyOf(token) {
|
|
56
|
+
const payload = payloadOf(token);
|
|
57
|
+
if (typeof payload?.sub !== "string") {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return [
|
|
61
|
+
payload.iss,
|
|
62
|
+
payload.aud,
|
|
63
|
+
payload.sub,
|
|
64
|
+
payload.auth_time ?? payload.iat
|
|
65
|
+
].join("|");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/session.tsx
|
|
69
|
+
import { jsx } from "react/jsx-runtime";
|
|
70
|
+
var MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
71
|
+
var REFRESH_AFTER_MS = 5 * 60 * 1000;
|
|
72
|
+
var REFRESH_BEFORE_EXPIRY_MS = 60 * 1000;
|
|
73
|
+
var RETRY_MS = 30 * 1000;
|
|
74
|
+
var REQUEST_TIMEOUT_MS = 10 * 1000;
|
|
75
|
+
var FRESH_MS = 5 * 1000;
|
|
76
|
+
var clockSkewMs = 0;
|
|
77
|
+
var hubNow = () => Date.now() + clockSkewMs;
|
|
78
|
+
var LOCAL_HOST = /^(localhost|127(\.\d{1,3}){3}|10(\.\d{1,3}){3}|192\.168(\.\d{1,3}){2}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|\[::1\]|[a-z0-9-]+\.local)$/i;
|
|
79
|
+
var HubContext = createContext({
|
|
80
|
+
session: undefined,
|
|
81
|
+
redirecting: false,
|
|
82
|
+
signOut: () => {},
|
|
83
|
+
suspend: () => {},
|
|
84
|
+
currentToken: () => null,
|
|
85
|
+
refresh: async () => null
|
|
86
|
+
});
|
|
87
|
+
var useHubState = () => useContext(HubContext);
|
|
88
|
+
var storageKey = (app) => `user-hub-token:${app}`;
|
|
89
|
+
function readStorage(key) {
|
|
90
|
+
try {
|
|
91
|
+
return window.localStorage.getItem(key);
|
|
92
|
+
} catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function writeStorage(key, token) {
|
|
97
|
+
try {
|
|
98
|
+
if (token)
|
|
99
|
+
window.localStorage.setItem(key, token);
|
|
100
|
+
else
|
|
101
|
+
window.localStorage.removeItem(key);
|
|
102
|
+
} catch {}
|
|
103
|
+
}
|
|
104
|
+
function takeTokenFromUrl() {
|
|
105
|
+
const hash = new URLSearchParams(window.location.hash.slice(1));
|
|
106
|
+
const token = hash.get("token");
|
|
107
|
+
if (token) {
|
|
108
|
+
hash.delete("token");
|
|
109
|
+
const rest = hash.toString();
|
|
110
|
+
window.history.replaceState(window.history.state, "", `${window.location.pathname}${window.location.search}${rest ? `#${rest}` : ""}`);
|
|
111
|
+
}
|
|
112
|
+
return token;
|
|
113
|
+
}
|
|
114
|
+
function originOf(url) {
|
|
115
|
+
try {
|
|
116
|
+
return new URL(url).origin;
|
|
117
|
+
} catch {
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function refreshUrlFor(token, app, hubUrl) {
|
|
122
|
+
const info = readClaims(token)?.app === app ? refreshInfo(token) : null;
|
|
123
|
+
const hub = hubUrl && originOf(hubUrl);
|
|
124
|
+
return info && (!hub || originOf(info.url) === hub) ? info.url : null;
|
|
125
|
+
}
|
|
126
|
+
async function exchange(token, app, hubUrl) {
|
|
127
|
+
const url = refreshUrlFor(token, app, hubUrl);
|
|
128
|
+
if (!url) {
|
|
129
|
+
return { status: "ended" };
|
|
130
|
+
}
|
|
131
|
+
const controller = new AbortController;
|
|
132
|
+
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
133
|
+
try {
|
|
134
|
+
const response = await fetch(url, {
|
|
135
|
+
method: "POST",
|
|
136
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
137
|
+
signal: controller.signal
|
|
138
|
+
});
|
|
139
|
+
if (response.status === 401) {
|
|
140
|
+
return { status: "ended" };
|
|
141
|
+
}
|
|
142
|
+
const next = response.ok ? (await response.json())?.token : null;
|
|
143
|
+
if (typeof next !== "string" || sessionKeyOf(next) !== sessionKeyOf(token)) {
|
|
144
|
+
return { status: "failed" };
|
|
145
|
+
}
|
|
146
|
+
const issuedAt = refreshInfo(next)?.issuedAt;
|
|
147
|
+
if (issuedAt) {
|
|
148
|
+
clockSkewMs = issuedAt - Date.now();
|
|
149
|
+
}
|
|
150
|
+
const session = sessionFor(next, app, hubNow());
|
|
151
|
+
return session ? { status: "refreshed", session } : { status: "failed" };
|
|
152
|
+
} catch {
|
|
153
|
+
return { status: "failed" };
|
|
154
|
+
} finally {
|
|
155
|
+
clearTimeout(timeout);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function HubSessionProvider({
|
|
159
|
+
app,
|
|
160
|
+
hubUrl,
|
|
161
|
+
children
|
|
162
|
+
}) {
|
|
163
|
+
const key = storageKey(app);
|
|
164
|
+
const [session, setSession] = useState();
|
|
165
|
+
const [stalled, setStalled] = useState(null);
|
|
166
|
+
const latest = useRef(undefined);
|
|
167
|
+
const held = useRef(null);
|
|
168
|
+
const inFlight = useRef(null);
|
|
169
|
+
const mounted = useRef(false);
|
|
170
|
+
const lastRequest = useRef(0);
|
|
171
|
+
const redirecting = session === null && Boolean(hubUrl) && typeof window !== "undefined" && LOCAL_HOST.test(window.location.hostname);
|
|
172
|
+
const show = useCallback((next, token, stalledToken) => {
|
|
173
|
+
held.current = token;
|
|
174
|
+
latest.current = next;
|
|
175
|
+
setSession(next);
|
|
176
|
+
setStalled(stalledToken);
|
|
177
|
+
}, []);
|
|
178
|
+
const signIn = useCallback((next) => {
|
|
179
|
+
writeStorage(key, next.token);
|
|
180
|
+
show(next, next.token, null);
|
|
181
|
+
}, [key, show]);
|
|
182
|
+
const end = useCallback(() => {
|
|
183
|
+
writeStorage(key, null);
|
|
184
|
+
show(null, null, null);
|
|
185
|
+
}, [key, show]);
|
|
186
|
+
const stall = useCallback((token) => {
|
|
187
|
+
writeStorage(key, token);
|
|
188
|
+
show(null, token, token);
|
|
189
|
+
}, [key, show]);
|
|
190
|
+
const currentToken = useCallback(() => {
|
|
191
|
+
const current = latest.current;
|
|
192
|
+
return current && current.user.expiresAt > hubNow() ? current.token : null;
|
|
193
|
+
}, []);
|
|
194
|
+
const trade = useCallback((sent) => {
|
|
195
|
+
if (inFlight.current?.token === sent) {
|
|
196
|
+
return inFlight.current.answer;
|
|
197
|
+
}
|
|
198
|
+
const answer = (async () => {
|
|
199
|
+
lastRequest.current = Date.now();
|
|
200
|
+
const result = await exchange(sent, app, hubUrl);
|
|
201
|
+
if (!mounted.current || held.current !== sent) {
|
|
202
|
+
return currentToken();
|
|
203
|
+
}
|
|
204
|
+
if (result.status === "refreshed") {
|
|
205
|
+
signIn(result.session);
|
|
206
|
+
return result.session.token;
|
|
207
|
+
}
|
|
208
|
+
if (result.status === "ended") {
|
|
209
|
+
end();
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
if (sessionFor(sent, app, hubNow())) {
|
|
213
|
+
return sent;
|
|
214
|
+
}
|
|
215
|
+
stall(sent);
|
|
216
|
+
return null;
|
|
217
|
+
})().finally(() => {
|
|
218
|
+
if (inFlight.current?.answer === answer) {
|
|
219
|
+
inFlight.current = null;
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
inFlight.current = { token: sent, answer };
|
|
223
|
+
return answer;
|
|
224
|
+
}, [app, hubUrl, currentToken, signIn, end, stall]);
|
|
225
|
+
const refresh = useCallback(async () => {
|
|
226
|
+
const current = latest.current;
|
|
227
|
+
if (!current || !refreshUrlFor(current.token, app, hubUrl)) {
|
|
228
|
+
return currentToken();
|
|
229
|
+
}
|
|
230
|
+
const issuedAt = refreshInfo(current.token)?.issuedAt ?? 0;
|
|
231
|
+
if (!inFlight.current && hubNow() - issuedAt < FRESH_MS) {
|
|
232
|
+
return current.token;
|
|
233
|
+
}
|
|
234
|
+
return await trade(current.token);
|
|
235
|
+
}, [app, hubUrl, currentToken, trade]);
|
|
236
|
+
useEffect(() => {
|
|
237
|
+
mounted.current = true;
|
|
238
|
+
return () => {
|
|
239
|
+
mounted.current = false;
|
|
240
|
+
};
|
|
241
|
+
}, []);
|
|
242
|
+
useEffect(() => {
|
|
243
|
+
const fromUrl = takeTokenFromUrl();
|
|
244
|
+
const stored = readStorage(key);
|
|
245
|
+
const valid = sessionFor(fromUrl, app, hubNow()) ?? sessionFor(stored, app, hubNow());
|
|
246
|
+
if (valid) {
|
|
247
|
+
signIn(valid);
|
|
248
|
+
if (refreshUrlFor(valid.token, app, hubUrl)) {
|
|
249
|
+
trade(valid.token);
|
|
250
|
+
}
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const expired = [fromUrl, stored].find((token) => Boolean(token && refreshUrlFor(token, app, hubUrl)));
|
|
254
|
+
if (!expired) {
|
|
255
|
+
end();
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
writeStorage(key, expired);
|
|
259
|
+
held.current = expired;
|
|
260
|
+
latest.current = undefined;
|
|
261
|
+
setSession(undefined);
|
|
262
|
+
setStalled(null);
|
|
263
|
+
trade(expired);
|
|
264
|
+
}, [app, hubUrl, key, signIn, end, trade]);
|
|
265
|
+
useEffect(() => {
|
|
266
|
+
if (!stalled)
|
|
267
|
+
return;
|
|
268
|
+
const retry = () => {
|
|
269
|
+
if (document.visibilityState !== "hidden" && !inFlight.current) {
|
|
270
|
+
trade(stalled);
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
const id = setInterval(retry, RETRY_MS);
|
|
274
|
+
window.addEventListener("online", retry);
|
|
275
|
+
document.addEventListener("visibilitychange", retry);
|
|
276
|
+
return () => {
|
|
277
|
+
clearInterval(id);
|
|
278
|
+
window.removeEventListener("online", retry);
|
|
279
|
+
document.removeEventListener("visibilitychange", retry);
|
|
280
|
+
};
|
|
281
|
+
}, [stalled, trade]);
|
|
282
|
+
useEffect(() => {
|
|
283
|
+
const follow = (event) => {
|
|
284
|
+
if (event.key !== key && event.key !== null)
|
|
285
|
+
return;
|
|
286
|
+
const token = event.newValue;
|
|
287
|
+
const next = token ? sessionFor(token, app, hubNow()) : null;
|
|
288
|
+
const refreshable = token && refreshUrlFor(token, app, hubUrl);
|
|
289
|
+
show(next, token, !next && refreshable ? token : null);
|
|
290
|
+
};
|
|
291
|
+
window.addEventListener("storage", follow);
|
|
292
|
+
return () => window.removeEventListener("storage", follow);
|
|
293
|
+
}, [app, hubUrl, key, show]);
|
|
294
|
+
useEffect(() => {
|
|
295
|
+
if (!session)
|
|
296
|
+
return;
|
|
297
|
+
const { token, user } = session;
|
|
298
|
+
let active = true;
|
|
299
|
+
let id;
|
|
300
|
+
const after = (delay, run) => {
|
|
301
|
+
id = setTimeout(run, Math.min(Math.max(delay, 0), MAX_TIMEOUT_MS));
|
|
302
|
+
};
|
|
303
|
+
const expiry = setTimeout(() => stall(token), Math.min(Math.max(user.expiresAt - hubNow(), 0), MAX_TIMEOUT_MS));
|
|
304
|
+
if (!refreshUrlFor(token, app, hubUrl)) {
|
|
305
|
+
clearTimeout(expiry);
|
|
306
|
+
after(user.expiresAt - hubNow(), end);
|
|
307
|
+
} else {
|
|
308
|
+
const issuedAt = refreshInfo(token)?.issuedAt ?? 0;
|
|
309
|
+
const attempt = async () => {
|
|
310
|
+
if (await trade(token) === token && active) {
|
|
311
|
+
after(RETRY_MS, attempt);
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
const due = Math.min(issuedAt + REFRESH_AFTER_MS, user.expiresAt - REFRESH_BEFORE_EXPIRY_MS) - hubNow();
|
|
315
|
+
after(Math.max(due, lastRequest.current + RETRY_MS - Date.now()), attempt);
|
|
316
|
+
}
|
|
317
|
+
return () => {
|
|
318
|
+
active = false;
|
|
319
|
+
clearTimeout(id);
|
|
320
|
+
clearTimeout(expiry);
|
|
321
|
+
};
|
|
322
|
+
}, [session, app, hubUrl, end, stall, trade]);
|
|
323
|
+
useEffect(() => {
|
|
324
|
+
if (redirecting && hubUrl) {
|
|
325
|
+
window.location.replace(`${hubUrl.replace(/\/+$/, "")}/open/${encodeURIComponent(app)}`);
|
|
326
|
+
}
|
|
327
|
+
}, [redirecting, hubUrl, app]);
|
|
328
|
+
const signOut = end;
|
|
329
|
+
const suspend = useCallback(() => {
|
|
330
|
+
latest.current = null;
|
|
331
|
+
setSession(null);
|
|
332
|
+
}, []);
|
|
333
|
+
const state = useMemo(() => ({ session, redirecting, signOut, suspend, currentToken, refresh }), [session, redirecting, signOut, suspend, currentToken, refresh]);
|
|
334
|
+
return /* @__PURE__ */ jsx(HubContext.Provider, {
|
|
335
|
+
value: state,
|
|
336
|
+
children
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// src/react.tsx
|
|
341
|
+
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
342
|
+
function HubAuthProvider2(props) {
|
|
343
|
+
return /* @__PURE__ */ jsx2(HubSessionProvider, {
|
|
344
|
+
...props
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
function DefaultSignedOut() {
|
|
348
|
+
return /* @__PURE__ */ jsx2("p", {
|
|
349
|
+
style: { padding: "2rem", textAlign: "center" },
|
|
350
|
+
children: "Scan your badge to sign in."
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
function HubSignedIn2({
|
|
354
|
+
children,
|
|
355
|
+
signedOut = /* @__PURE__ */ jsx2(DefaultSignedOut, {}),
|
|
356
|
+
loading = null
|
|
357
|
+
}) {
|
|
358
|
+
const { session, redirecting } = useHubState();
|
|
359
|
+
if (session === undefined || redirecting)
|
|
360
|
+
return loading;
|
|
361
|
+
return session ? children : signedOut;
|
|
362
|
+
}
|
|
363
|
+
function useHubSignOut2() {
|
|
364
|
+
return useHubState().signOut;
|
|
365
|
+
}
|
|
366
|
+
function useHubSession2() {
|
|
367
|
+
return useHubState().session;
|
|
368
|
+
}
|
|
369
|
+
function useHubUser2() {
|
|
370
|
+
const user = useHubSession2()?.user;
|
|
371
|
+
return useMemo2(() => user ? { id: user.id, name: user.name, team: user.team, role: user.role } : null, [user]);
|
|
372
|
+
}
|
|
373
|
+
function useHubToken2() {
|
|
374
|
+
return useHubSession2()?.token ?? null;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export { sessionKeyOf, useHubState, HubSessionProvider, HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2 };
|
package/dist/convex-react.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ConvexReactClient } from "convex/react";
|
|
2
|
-
import { type HubAuthProviderProps } from "./
|
|
2
|
+
import { type HubAuthProviderProps } from "./session";
|
|
3
3
|
export { HubSignedIn, useHubSession, useHubSignOut, useHubToken, useHubUser, } from "./react";
|
|
4
4
|
export type { HubRole, HubUser } from "./token";
|
|
5
5
|
/**
|
package/dist/convex-react.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
2
|
+
sessionKeyOf,
|
|
3
|
+
useHubState,
|
|
4
|
+
HubSessionProvider,
|
|
3
5
|
HubSignedIn2,
|
|
4
6
|
useHubSignOut2,
|
|
5
7
|
useHubSession2,
|
|
6
8
|
useHubUser2,
|
|
7
9
|
useHubToken2
|
|
8
|
-
} from "./convex-
|
|
10
|
+
} from "./convex-qxqkx9zh.js";
|
|
9
11
|
|
|
10
12
|
// src/convex-react.tsx
|
|
11
13
|
import {
|
|
@@ -15,22 +17,28 @@ import {
|
|
|
15
17
|
import { useEffect, useMemo } from "react";
|
|
16
18
|
import { jsx } from "react/jsx-runtime";
|
|
17
19
|
function useConvexHubAuth() {
|
|
18
|
-
const session =
|
|
20
|
+
const { session, currentToken, refresh } = useHubState();
|
|
21
|
+
const isLoading = session === undefined;
|
|
22
|
+
const sessionKey = session ? sessionKeyOf(session.token) : null;
|
|
19
23
|
return useMemo(() => ({
|
|
20
|
-
isLoading
|
|
21
|
-
isAuthenticated:
|
|
22
|
-
fetchAccessToken: async (
|
|
23
|
-
|
|
24
|
+
isLoading,
|
|
25
|
+
isAuthenticated: sessionKey !== null,
|
|
26
|
+
fetchAccessToken: async ({
|
|
27
|
+
forceRefreshToken
|
|
28
|
+
}) => {
|
|
29
|
+
const token = forceRefreshToken ? await refresh() : currentToken() ?? await refresh();
|
|
30
|
+
return token && sessionKeyOf(token) === sessionKey ? token : null;
|
|
31
|
+
}
|
|
32
|
+
}), [isLoading, sessionKey, currentToken, refresh]);
|
|
24
33
|
}
|
|
25
|
-
function
|
|
26
|
-
const session =
|
|
27
|
-
const signOut = useHubSignOut2();
|
|
34
|
+
function SuspendWhenRejected({ children }) {
|
|
35
|
+
const { session, suspend } = useHubState();
|
|
28
36
|
const { isLoading, isAuthenticated } = useConvexAuth();
|
|
29
37
|
const rejected = Boolean(session) && !isLoading && !isAuthenticated;
|
|
30
38
|
useEffect(() => {
|
|
31
39
|
if (rejected)
|
|
32
|
-
|
|
33
|
-
}, [rejected,
|
|
40
|
+
suspend();
|
|
41
|
+
}, [rejected, suspend]);
|
|
34
42
|
return children;
|
|
35
43
|
}
|
|
36
44
|
function ConvexHubAuthProvider({
|
|
@@ -38,12 +46,12 @@ function ConvexHubAuthProvider({
|
|
|
38
46
|
children,
|
|
39
47
|
...props
|
|
40
48
|
}) {
|
|
41
|
-
return /* @__PURE__ */ jsx(
|
|
49
|
+
return /* @__PURE__ */ jsx(HubSessionProvider, {
|
|
42
50
|
...props,
|
|
43
51
|
children: /* @__PURE__ */ jsx(ConvexProviderWithAuth, {
|
|
44
52
|
client,
|
|
45
53
|
useAuth: useConvexHubAuth,
|
|
46
|
-
children: /* @__PURE__ */ jsx(
|
|
54
|
+
children: /* @__PURE__ */ jsx(SuspendWhenRejected, {
|
|
47
55
|
children
|
|
48
56
|
})
|
|
49
57
|
})
|
package/dist/react.d.ts
CHANGED
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
import { type ReactNode } from "react";
|
|
2
|
-
import { type
|
|
2
|
+
import { type HubAuthProviderProps } from "./session";
|
|
3
|
+
import type { HubSession, HubUser } from "./token";
|
|
4
|
+
export type { HubAuthProviderProps } from "./session";
|
|
3
5
|
export type { HubRole, HubUser } from "./token";
|
|
4
|
-
export type HubAuthProviderProps = {
|
|
5
|
-
app: string;
|
|
6
|
-
hubUrl?: string;
|
|
7
|
-
children: ReactNode;
|
|
8
|
-
};
|
|
9
6
|
/**
|
|
10
7
|
* Provides the signed-in person to the app. Always renders its children:
|
|
11
8
|
* put it inside the root document's <body>, and use <HubSignedIn> to decide
|
|
12
|
-
* what to show.
|
|
9
|
+
* what to show. Keeps the person signed in by refreshing their token with the
|
|
10
|
+
* hub every few minutes while the app is open, for as long as the hub allows.
|
|
11
|
+
* Apps on Convex use ConvexHubAuthProvider instead.
|
|
13
12
|
*/
|
|
14
|
-
export declare function HubAuthProvider(
|
|
13
|
+
export declare function HubAuthProvider(props: HubAuthProviderProps): import("react").JSX.Element;
|
|
15
14
|
/**
|
|
16
15
|
* Shows its children only to a signed-in person. Otherwise `signedOut`
|
|
17
16
|
* ("Scan your badge to sign in" by default), or `loading` while the session is
|
|
@@ -34,6 +33,7 @@ export declare function useHubSession(): HubSession | null | undefined;
|
|
|
34
33
|
export declare function useHubUser(): HubUser | null;
|
|
35
34
|
/**
|
|
36
35
|
* The raw token, for apps whose own server checks it with verifyHubToken:
|
|
37
|
-
* send it as `Authorization: Bearer <token>`.
|
|
36
|
+
* send it as `Authorization: Bearer <token>`. It changes every few minutes as
|
|
37
|
+
* it is refreshed, so read it for each request.
|
|
38
38
|
*/
|
|
39
39
|
export declare function useHubToken(): string | null;
|
package/dist/react.js
CHANGED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type ReactNode } from "react";
|
|
2
|
+
import { type HubSession } from "./token";
|
|
3
|
+
export declare function resetHubClock(): void;
|
|
4
|
+
type HubState = {
|
|
5
|
+
session: HubSession | null | undefined;
|
|
6
|
+
redirecting: boolean;
|
|
7
|
+
signOut: () => void;
|
|
8
|
+
suspend: () => void;
|
|
9
|
+
currentToken: () => string | null;
|
|
10
|
+
refresh: () => Promise<string | null>;
|
|
11
|
+
};
|
|
12
|
+
export declare const useHubState: () => HubState;
|
|
13
|
+
export type HubAuthProviderProps = {
|
|
14
|
+
app: string;
|
|
15
|
+
hubUrl?: string;
|
|
16
|
+
children: ReactNode;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Keeps the signed-in person for HubAuthProvider and ConvexHubAuthProvider:
|
|
20
|
+
* reads the token from the URL or storage, refreshes it with the hub on a
|
|
21
|
+
* schedule (and whenever Convex asks), follows other tabs of the same app,
|
|
22
|
+
* and signs out when the hub ends the session.
|
|
23
|
+
*/
|
|
24
|
+
export declare function HubSessionProvider({ app, hubUrl, children, }: HubAuthProviderProps): import("react").JSX.Element;
|
|
25
|
+
export {};
|
package/dist/token.d.ts
CHANGED
|
@@ -15,3 +15,8 @@ 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 refreshInfo(token: string): {
|
|
19
|
+
url: string;
|
|
20
|
+
issuedAt: number;
|
|
21
|
+
} | null;
|
|
22
|
+
export declare function sessionKeyOf(token: string): string | null;
|
package/package.json
CHANGED
|
@@ -33,7 +33,7 @@ The hub has one address, for example `https://hub.example.com`. The human gives
|
|
|
33
33
|
|
|
34
34
|
- `HUB_URL` in the app's `.env` or `.env.local`: read by `hub-user register` (**Register the app**). The human puts it there with the admin password.
|
|
35
35
|
- `HUB_ISSUER` on the app's Convex deployment: `hub-user register` prints it for you (**Set the two values**).
|
|
36
|
-
- `VITE_HUB_URL` in the app's frontend env: lets the dev server send you to the hub to sign in (**Wire it up**).
|
|
36
|
+
- `VITE_HUB_URL` in the app's frontend env, for production builds too: lets the dev server send you to the hub to sign in, and limits token refresh to that hub (**Wire it up**).
|
|
37
37
|
|
|
38
38
|
## Before you start: ask the human
|
|
39
39
|
|
|
@@ -110,7 +110,7 @@ You need four things. Ask for them; never guess.
|
|
|
110
110
|
|
|
111
111
|
## Your dev server
|
|
112
112
|
|
|
113
|
-
Run the app as usual (`bun run dev`) on the `--dev` URL you registered. Opening it with no token sends the browser to the hub (admin password once per browser), where you pick who to be; the hub sends you back signed in as them.
|
|
113
|
+
Run the app as usual (`bun run dev`) on the `--dev` URL you registered. Opening it with no token sends the browser to the hub (admin password once per browser), where you pick who to be; the hub sends you back signed in as them. You stay signed in across reloads and restarts until that person's expiration in the hub (4 hours unless set otherwise), then the same thing happens again.
|
|
114
114
|
|
|
115
115
|
- To switch person: open `<hub>/open/<key>` and pick someone else.
|
|
116
116
|
- If the dev server runs on another port, run `hub-user register` again with the same `--name` and the new `--dev` URL: the hub only sends tokens back to registered URLs.
|
|
@@ -181,5 +181,6 @@ People are either `"member"` or `"facilitator"`, set in the hub. To give facilit
|
|
|
181
181
|
|
|
182
182
|
- Key all data on the hub id (`identity.subject` / `useHubUser().id`). Never on the name, and never on the badge token, which the app never sees.
|
|
183
183
|
- Check access on the server: `requireFacilitator(ctx)` / `requireHubUser(ctx)` in Convex, or `verifyHubToken` elsewhere. `useHubUser()` is for display only.
|
|
184
|
-
-
|
|
184
|
+
- The provider refreshes tokens with the hub (`<hub>/api/token/refresh`) while the app is open; the hub decides how long a session lasts and when it ends, and the provider then shows the signed-out screen. Do not refresh, store or extend tokens yourself. Read `useHubToken()` for each request, since it changes. If the app sets a Content Security Policy, allow the hub in `connect-src`.
|
|
185
185
|
- Do not add other sign-in methods, sessions or token handling. If something is missing, change this package instead.
|
|
186
|
+
- An existing app on `@user-hub/auth` 0.1 does not refresh tokens, and a `^0.1` range never installs 0.2: update it with `bun add @user-hub/auth@latest`. No code changes are needed.
|
package/dist/convex-zgnvvwvn.js
DELETED
|
@@ -1,140 +0,0 @@
|
|
|
1
|
-
// src/react.tsx
|
|
2
|
-
import {
|
|
3
|
-
createContext,
|
|
4
|
-
useCallback,
|
|
5
|
-
useContext,
|
|
6
|
-
useEffect,
|
|
7
|
-
useMemo,
|
|
8
|
-
useState
|
|
9
|
-
} from "react";
|
|
10
|
-
|
|
11
|
-
// src/token.ts
|
|
12
|
-
function decodeSegment(segment) {
|
|
13
|
-
const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
|
|
14
|
-
return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
|
|
15
|
-
}
|
|
16
|
-
function readClaims(token) {
|
|
17
|
-
try {
|
|
18
|
-
const payload = decodeSegment(token.split(".")[1] ?? "");
|
|
19
|
-
if (typeof payload.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string") {
|
|
20
|
-
return null;
|
|
21
|
-
}
|
|
22
|
-
return {
|
|
23
|
-
id: payload.sub,
|
|
24
|
-
name: payload.name,
|
|
25
|
-
team: payload.team,
|
|
26
|
-
role: payload.role === "facilitator" ? "facilitator" : "member",
|
|
27
|
-
app: payload.aud,
|
|
28
|
-
expiresAt: payload.exp * 1000
|
|
29
|
-
};
|
|
30
|
-
} catch {
|
|
31
|
-
return null;
|
|
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
|
-
|
|
39
|
-
// src/react.tsx
|
|
40
|
-
import { jsx } from "react/jsx-runtime";
|
|
41
|
-
var MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
42
|
-
var LOCAL_HOST = /^(localhost|127(\.\d{1,3}){3}|10(\.\d{1,3}){3}|192\.168(\.\d{1,3}){2}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|\[::1\]|[a-z0-9-]+\.local)$/i;
|
|
43
|
-
var HubContext = createContext({
|
|
44
|
-
session: undefined,
|
|
45
|
-
redirecting: false,
|
|
46
|
-
signOut: () => {}
|
|
47
|
-
});
|
|
48
|
-
var storageKey = (app) => `user-hub-token:${app}`;
|
|
49
|
-
function readStorage(key) {
|
|
50
|
-
try {
|
|
51
|
-
return window.localStorage.getItem(key);
|
|
52
|
-
} catch {
|
|
53
|
-
return null;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
function writeStorage(key, token) {
|
|
57
|
-
try {
|
|
58
|
-
if (token)
|
|
59
|
-
window.localStorage.setItem(key, token);
|
|
60
|
-
else
|
|
61
|
-
window.localStorage.removeItem(key);
|
|
62
|
-
} catch {}
|
|
63
|
-
}
|
|
64
|
-
function loadSession(app) {
|
|
65
|
-
const hash = new URLSearchParams(window.location.hash.slice(1));
|
|
66
|
-
const fromUrl = hash.get("token");
|
|
67
|
-
if (fromUrl) {
|
|
68
|
-
hash.delete("token");
|
|
69
|
-
const rest = hash.toString();
|
|
70
|
-
window.history.replaceState(window.history.state, "", `${window.location.pathname}${window.location.search}${rest ? `#${rest}` : ""}`);
|
|
71
|
-
}
|
|
72
|
-
const session = sessionFor(fromUrl, app) ?? sessionFor(readStorage(storageKey(app)), app);
|
|
73
|
-
writeStorage(storageKey(app), session?.token ?? null);
|
|
74
|
-
return session;
|
|
75
|
-
}
|
|
76
|
-
function HubAuthProvider2({
|
|
77
|
-
app,
|
|
78
|
-
hubUrl,
|
|
79
|
-
children
|
|
80
|
-
}) {
|
|
81
|
-
const [session, setSession] = useState();
|
|
82
|
-
const redirecting = session === null && Boolean(hubUrl) && typeof window !== "undefined" && LOCAL_HOST.test(window.location.hostname);
|
|
83
|
-
useEffect(() => {
|
|
84
|
-
setSession(loadSession(app));
|
|
85
|
-
}, [app]);
|
|
86
|
-
useEffect(() => {
|
|
87
|
-
if (!session)
|
|
88
|
-
return;
|
|
89
|
-
const id = setTimeout(() => {
|
|
90
|
-
writeStorage(storageKey(app), null);
|
|
91
|
-
setSession(null);
|
|
92
|
-
}, Math.min(session.user.expiresAt - Date.now(), MAX_TIMEOUT_MS));
|
|
93
|
-
return () => clearTimeout(id);
|
|
94
|
-
}, [session, app]);
|
|
95
|
-
useEffect(() => {
|
|
96
|
-
if (redirecting && hubUrl) {
|
|
97
|
-
window.location.replace(`${hubUrl.replace(/\/+$/, "")}/open/${encodeURIComponent(app)}`);
|
|
98
|
-
}
|
|
99
|
-
}, [redirecting, hubUrl, app]);
|
|
100
|
-
const signOut = useCallback(() => {
|
|
101
|
-
writeStorage(storageKey(app), null);
|
|
102
|
-
setSession(null);
|
|
103
|
-
}, [app]);
|
|
104
|
-
const state = useMemo(() => ({ session, redirecting, signOut }), [session, redirecting, signOut]);
|
|
105
|
-
return /* @__PURE__ */ jsx(HubContext.Provider, {
|
|
106
|
-
value: state,
|
|
107
|
-
children
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
function DefaultSignedOut() {
|
|
111
|
-
return /* @__PURE__ */ jsx("p", {
|
|
112
|
-
style: { padding: "2rem", textAlign: "center" },
|
|
113
|
-
children: "Scan your badge to sign in."
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
function HubSignedIn2({
|
|
117
|
-
children,
|
|
118
|
-
signedOut = /* @__PURE__ */ jsx(DefaultSignedOut, {}),
|
|
119
|
-
loading = null
|
|
120
|
-
}) {
|
|
121
|
-
const { session, redirecting } = useContext(HubContext);
|
|
122
|
-
if (session === undefined || redirecting)
|
|
123
|
-
return loading;
|
|
124
|
-
return session ? children : signedOut;
|
|
125
|
-
}
|
|
126
|
-
function useHubSignOut2() {
|
|
127
|
-
return useContext(HubContext).signOut;
|
|
128
|
-
}
|
|
129
|
-
function useHubSession2() {
|
|
130
|
-
return useContext(HubContext).session;
|
|
131
|
-
}
|
|
132
|
-
function useHubUser2() {
|
|
133
|
-
const user = useHubSession2()?.user;
|
|
134
|
-
return useMemo(() => user ? { id: user.id, name: user.name, team: user.team, role: user.role } : null, [user]);
|
|
135
|
-
}
|
|
136
|
-
function useHubToken2() {
|
|
137
|
-
return useHubSession2()?.token ?? null;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export { HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2 };
|