@user-hub/auth 0.4.2 → 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 +43 -30
- package/dist/convex-55v4qaqb.js +123 -0
- package/dist/{convex-bymky2mf.js → convex-kpwbsxky.js} +64 -136
- package/dist/convex-react.d.ts +2 -2
- package/dist/convex-react.js +4 -2
- package/dist/convex-tx5kfb4e.js +56 -0
- package/dist/convex.d.ts +3 -3
- package/dist/convex.js +1 -1
- package/dist/internal/clock.d.ts +3 -0
- package/dist/internal/cookie.d.ts +3 -0
- package/dist/internal/refresh.d.ts +11 -0
- package/dist/internal/server-session.d.ts +19 -0
- package/dist/{session.d.ts → internal/session.d.ts} +2 -2
- package/dist/internal/storage.d.ts +3 -0
- package/dist/internal/store.d.ts +13 -0
- package/dist/{token.d.ts → internal/token.d.ts} +1 -0
- package/dist/internal/url-token.d.ts +2 -0
- package/dist/react.d.ts +4 -4
- package/dist/react.js +2 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.js +3 -51
- package/dist/start.d.ts +13 -0
- package/dist/start.js +83 -0
- package/package.json +14 -7
- package/skills/user-hub-auth/SKILL.md +25 -202
- package/skills/user-hub-auth/references/connect-an-app.md +87 -0
- package/skills/user-hub-auth/references/dev-and-production.md +30 -0
- package/skills/user-hub-auth/references/roles.md +39 -0
- package/dist/cli.d.ts +0 -2
- package/dist/cli.js +0 -521
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ The hub decides how long a scan keeps someone signed in: 1, 2 or 4 hours, or unt
|
|
|
32
32
|
bun add @user-hub/auth
|
|
33
33
|
```
|
|
34
34
|
|
|
35
|
-
Using a coding agent? The package ships
|
|
35
|
+
Using a coding agent? The package ships the `user-hub-auth` skill (and `user-hub` ships `user-hub-cli`, for the commands). Add them to your agents with:
|
|
36
36
|
|
|
37
37
|
```sh
|
|
38
38
|
bunx skills experimental_sync
|
|
@@ -40,30 +40,16 @@ bunx skills experimental_sync
|
|
|
40
40
|
|
|
41
41
|
### 2. Sign in and register your app
|
|
42
42
|
|
|
43
|
-
Ask the hub's admin for its URL and an account
|
|
43
|
+
Register the app with the [`user-hub`](https://www.npmjs.com/package/user-hub) CLI. Ask the hub's admin for its URL and an account, then from your app's folder:
|
|
44
44
|
|
|
45
45
|
```sh
|
|
46
|
-
|
|
46
|
+
bun add -d user-hub
|
|
47
|
+
bunx user-hub login --hub https://hub.example.com
|
|
48
|
+
bunx user-hub events list
|
|
49
|
+
bunx user-hub apps register --event spring-workshop --name "Your App" --new --prod https://your-app.com --dev http://localhost:3000
|
|
47
50
|
```
|
|
48
51
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
A hub runs many **events** (workshops); people, apps and the schedule each belong to one. Find the event your app is for by its slug, or create one (its time zone defaults to your machine's; pass `--time-zone Europe/Berlin` to pick another):
|
|
52
|
-
|
|
53
|
-
```sh
|
|
54
|
-
bunx hub-user events
|
|
55
|
-
bunx hub-user events create --name "Spring Workshop"
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
Hubs with events need `@user-hub/auth` 0.4 or newer. Upgrading from 0.3? Run `bun add @user-hub/auth@latest` first (a `^0.3` range never installs 0.4); no app code changes.
|
|
59
|
-
|
|
60
|
-
Then register the app in that event (`bunx` reads `.env` and `.env.local` automatically; if `HUB_URL` and `HUB_API_KEY` live in a secret manager, run it through that):
|
|
61
|
-
|
|
62
|
-
```sh
|
|
63
|
-
bunx hub-user register --event spring-workshop --name "Your App" --new --prod https://your-app.com --dev http://localhost:3000
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
`--event` is needed on every run; set `HUB_EVENT=<slug>` in `.env.local` to leave it out. An unknown slug exits with code 5. It prints your **app key** (made from the event's slug and the name) and the values to set. Not deployed yet? Leave out `--prod`: you can develop, and badge scans start reaching the app once you add it. Run it again with the same `--event` and `--name` to update the URLs; a URL left out keeps the registered one. `--new` refuses to touch an app that already has that name, so you never take over someone else's; leave it out when updating your own app later. New apps are **listed** in the badge app list by default: when the hub shows the app list instead of one live app, listed apps with a production URL appear in it. Pass `--unlisted` to keep one out of it (it can still be scheduled or forced live), or `--listed` to show it again. Pass neither on an update and the hub's current setting stays; the output shows it. Any hub account can update any app, so register only under your app's own name. (The same can be done under **Apps** in the hub, with the values under **Setup**.) Quote a value with spaces (`--name "Summer Camp"`): an unexpected extra word stops any `hub-user` command with exit code 1 before it sends anything. When you pass `--hub`, the commands the CLI suggests next keep it.
|
|
52
|
+
`login` saves `HUB_URL` and `HUB_API_KEY` to the folder's `.env.local` (keep it gitignored). A hub runs many **events** (workshops), and an app belongs to one. `apps register` prints your **app key** (made from the event's slug and the name) and the values to set. Not deployed yet? Leave out `--prod`; add it later the same way. `--new` refuses a name another app already has. See `bunx user-hub --help` for everything else, including the event's people. (The same can be done under **Apps** in the hub, with the values under **Setup**.) A new app made with `bun create user-hub@latest` does all of this with `bun run setup`.
|
|
67
53
|
|
|
68
54
|
### 3. Set the values
|
|
69
55
|
|
|
@@ -102,6 +88,38 @@ import { ConvexHubAuthProvider, HubSignedIn } from "@user-hub/auth/convex-react"
|
|
|
102
88
|
|
|
103
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.
|
|
104
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
|
+
|
|
105
123
|
### 5. Use the person
|
|
106
124
|
|
|
107
125
|
```tsx
|
|
@@ -127,7 +145,7 @@ export const myVotes = query({
|
|
|
127
145
|
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 (sign in to the hub with your account 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).
|
|
128
146
|
|
|
129
147
|
- **Switch person:** open `<hub>/open/<your-app-key>`.
|
|
130
|
-
- **Different port:** run `hub
|
|
148
|
+
- **Different port:** run `user-hub apps register` again (same `--event` and `--name`) with the new `--dev` URL. The hub only sends tokens to registered URLs.
|
|
131
149
|
- **Production:** someone without a token sees "Scan your badge to sign in". Pass `signedOut={…}` to `<HubSignedIn>` to style that screen.
|
|
132
150
|
|
|
133
151
|
## Sign out
|
|
@@ -187,18 +205,13 @@ Apps without Convex use `HubAuthProvider` and `HubSignedIn` from `@user-hub/auth
|
|
|
187
205
|
|---|---|---|
|
|
188
206
|
| `@user-hub/auth/convex` | `hubAuth({ app })` | The Convex auth provider, from `HUB_ISSUER` and `HUB_JWKS` |
|
|
189
207
|
| | `getHubUser(ctx)`, `requireHubUser(ctx)`, `requireFacilitator(ctx)` | The person in Convex functions: or null, or throw |
|
|
190
|
-
| `@user-hub/auth/convex-react` | `ConvexHubAuthProvider` | For Convex apps, in place of `ConvexProvider`, inside `<body>`. Props: `client`, `app`, `hubUrl?` |
|
|
191
|
-
| `@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?` |
|
|
192
210
|
| both | `HubSignedIn` | Shows its children only when signed in. Props: `signedOut?`, `loading?` |
|
|
193
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` |
|
|
194
212
|
| | `useHubSession()` | `undefined` while loading, `null` when signed out, otherwise `{ token, user }`; most apps need only `useHubUser()` or `<HubSignedIn>`. Also from `/convex-react` |
|
|
195
213
|
| `@user-hub/auth/server` | `verifyHubToken(requestOrToken, { app })` | Checks a token anywhere else |
|
|
196
|
-
|
|
|
197
|
-
| | `hub-user whoami [--json]` | The account `HUB_API_KEY` belongs to; exit code 4 when not signed in |
|
|
198
|
-
| | `hub-user events [--json]` | The hub's events, newest first: slug, name, time zone, ended ones marked. `--json` prints the array of `{ slug, name, status, timeZone }` |
|
|
199
|
-
| | `hub-user events create --name <name> [--time-zone <zone>] [--json]` | Creates an event (the IANA time zone defaults to this machine's); exit code 3 if its slug is taken. `--json` prints the created event |
|
|
200
|
-
| | `hub-user register --event <slug> --name <name> [--prod <url>] [--dev <url>] [--listed\|--unlisted] [--new] [--hub <url>] [--json]` | Registers or updates the app in an event (`--event` falls back to `HUB_EVENT`; exit code 5 when no event has that slug; a new app needs at least one URL; an update may leave both out); `--new` only creates, exit code 3 if the name is taken (also without `--new` when the key belongs to an app of another event); `--json` includes `event: { slug, name }`; `--listed`/`--unlisted` set whether the app shows in the badge app list once it has a production URL (new apps default to listed, omitted keeps the hub's setting) |
|
|
201
|
-
| | Exit codes | 0 done, 1 error (an unexpected extra word, such as an unquoted `--name Summer Camp`, stops before any request), 3 name taken (`register`, `events create`), 4 not signed in (run `hub-user login`), 5 unknown event (`register`) |
|
|
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 |
|
|
202
215
|
|
|
203
216
|
## Developing this package
|
|
204
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,7 +1,18 @@
|
|
|
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
|
|
|
4
|
-
// src/session.tsx
|
|
15
|
+
// src/internal/session.tsx
|
|
5
16
|
import {
|
|
6
17
|
createContext,
|
|
7
18
|
useCallback,
|
|
@@ -13,79 +24,7 @@ import {
|
|
|
13
24
|
useSyncExternalStore
|
|
14
25
|
} from "react";
|
|
15
26
|
|
|
16
|
-
// src/
|
|
17
|
-
function decodeSegment(segment) {
|
|
18
|
-
const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
|
|
19
|
-
return JSON.parse(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")));
|
|
20
|
-
}
|
|
21
|
-
function payloadOf(token) {
|
|
22
|
-
try {
|
|
23
|
-
return decodeSegment(token.split(".")[1] ?? "");
|
|
24
|
-
} catch {
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
function readClaims(token) {
|
|
29
|
-
const payload = payloadOf(token);
|
|
30
|
-
if (typeof payload?.sub !== "string" || typeof payload.exp !== "number" || typeof payload.aud !== "string") {
|
|
31
|
-
return null;
|
|
32
|
-
}
|
|
33
|
-
return {
|
|
34
|
-
id: payload.sub,
|
|
35
|
-
name: payload.name,
|
|
36
|
-
team: payload.team,
|
|
37
|
-
role: payload.role === "facilitator" ? "facilitator" : "member",
|
|
38
|
-
app: payload.aud,
|
|
39
|
-
expiresAt: payload.exp * 1000
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
function sessionFor(token, app, now = Date.now()) {
|
|
43
|
-
const user = token ? readClaims(token) : null;
|
|
44
|
-
return token && user && user.app === app && user.expiresAt > now ? { token, user } : null;
|
|
45
|
-
}
|
|
46
|
-
function refreshInfo(token) {
|
|
47
|
-
const payload = payloadOf(token);
|
|
48
|
-
if (typeof payload?.iss !== "string" || typeof payload.iat !== "number" || typeof payload.auth_time !== "number") {
|
|
49
|
-
return null;
|
|
50
|
-
}
|
|
51
|
-
return {
|
|
52
|
-
url: `${payload.iss.replace(/\/+$/, "")}/api/token/refresh`,
|
|
53
|
-
issuedAt: payload.iat * 1000
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
function sessionKeyOf(token) {
|
|
57
|
-
const payload = payloadOf(token);
|
|
58
|
-
if (typeof payload?.sub !== "string") {
|
|
59
|
-
return null;
|
|
60
|
-
}
|
|
61
|
-
return [
|
|
62
|
-
payload.iss,
|
|
63
|
-
payload.aud,
|
|
64
|
-
payload.sub,
|
|
65
|
-
payload.auth_time ?? payload.iat
|
|
66
|
-
].join("|");
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// src/session.tsx
|
|
70
|
-
import { jsx } from "react/jsx-runtime";
|
|
71
|
-
var MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
72
|
-
var REFRESH_AFTER_MS = 5 * 60 * 1000;
|
|
73
|
-
var REFRESH_BEFORE_EXPIRY_MS = 60 * 1000;
|
|
74
|
-
var RETRY_MS = 30 * 1000;
|
|
75
|
-
var REQUEST_TIMEOUT_MS = 10 * 1000;
|
|
76
|
-
var FRESH_MS = 5 * 1000;
|
|
77
|
-
var clockSkewMs = 0;
|
|
78
|
-
var hubNow = () => Date.now() + clockSkewMs;
|
|
79
|
-
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;
|
|
80
|
-
var HubContext = createContext({
|
|
81
|
-
session: undefined,
|
|
82
|
-
redirecting: false,
|
|
83
|
-
signOut: () => {},
|
|
84
|
-
suspend: () => {},
|
|
85
|
-
currentToken: () => null,
|
|
86
|
-
refresh: async () => null
|
|
87
|
-
});
|
|
88
|
-
var useHubState = () => useContext(HubContext);
|
|
27
|
+
// src/internal/storage.ts
|
|
89
28
|
var storageKey = (app) => `user-hub-token:${app}`;
|
|
90
29
|
function readStorage(key) {
|
|
91
30
|
try {
|
|
@@ -94,14 +33,18 @@ function readStorage(key) {
|
|
|
94
33
|
return null;
|
|
95
34
|
}
|
|
96
35
|
}
|
|
97
|
-
function
|
|
36
|
+
function writeToken(app, token) {
|
|
37
|
+
writeCookie(app, token);
|
|
98
38
|
try {
|
|
39
|
+
const key = storageKey(app);
|
|
99
40
|
if (token)
|
|
100
41
|
window.localStorage.setItem(key, token);
|
|
101
42
|
else
|
|
102
43
|
window.localStorage.removeItem(key);
|
|
103
44
|
} catch {}
|
|
104
45
|
}
|
|
46
|
+
|
|
47
|
+
// src/internal/url-token.ts
|
|
105
48
|
function tokenInUrl() {
|
|
106
49
|
return new URLSearchParams(window.location.hash.slice(1)).get("token");
|
|
107
50
|
}
|
|
@@ -115,59 +58,20 @@ function takeTokenFromUrl() {
|
|
|
115
58
|
}
|
|
116
59
|
return token;
|
|
117
60
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
return new URL(url).origin;
|
|
121
|
-
} catch {
|
|
122
|
-
return null;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
function refreshUrlFor(token, app, hubUrl) {
|
|
126
|
-
const info = readClaims(token)?.app === app ? refreshInfo(token) : null;
|
|
127
|
-
const hub = hubUrl && originOf(hubUrl);
|
|
128
|
-
return info && (!hub || originOf(info.url) === hub) ? info.url : null;
|
|
129
|
-
}
|
|
130
|
-
async function exchange(token, app, hubUrl) {
|
|
131
|
-
const url = refreshUrlFor(token, app, hubUrl);
|
|
132
|
-
if (!url) {
|
|
133
|
-
return { status: "ended" };
|
|
134
|
-
}
|
|
135
|
-
const controller = new AbortController;
|
|
136
|
-
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
137
|
-
try {
|
|
138
|
-
const response = await fetch(url, {
|
|
139
|
-
method: "POST",
|
|
140
|
-
headers: { Authorization: `Bearer ${token}` },
|
|
141
|
-
signal: controller.signal
|
|
142
|
-
});
|
|
143
|
-
if (response.status === 401) {
|
|
144
|
-
return { status: "ended" };
|
|
145
|
-
}
|
|
146
|
-
const next = response.ok ? (await response.json())?.token : null;
|
|
147
|
-
if (typeof next !== "string" || sessionKeyOf(next) !== sessionKeyOf(token)) {
|
|
148
|
-
return { status: "failed" };
|
|
149
|
-
}
|
|
150
|
-
const issuedAt = refreshInfo(next)?.issuedAt;
|
|
151
|
-
if (issuedAt) {
|
|
152
|
-
clockSkewMs = issuedAt - Date.now();
|
|
153
|
-
}
|
|
154
|
-
const session = sessionFor(next, app, hubNow());
|
|
155
|
-
return session ? { status: "refreshed", session } : { status: "failed" };
|
|
156
|
-
} catch {
|
|
157
|
-
return { status: "failed" };
|
|
158
|
-
} finally {
|
|
159
|
-
clearTimeout(timeout);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
61
|
+
|
|
62
|
+
// src/internal/store.ts
|
|
162
63
|
var LOADING = { session: undefined, stalled: null };
|
|
163
|
-
|
|
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
|
+
}
|
|
164
68
|
function sameSession(a, b) {
|
|
165
69
|
return a === b || a != null && b != null && a.token === b.token;
|
|
166
70
|
}
|
|
167
|
-
function firstState(app, key) {
|
|
71
|
+
function firstState(app, key, initialToken) {
|
|
168
72
|
if (typeof window === "undefined")
|
|
169
|
-
return
|
|
170
|
-
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()));
|
|
171
75
|
return session ? { session, stalled: null } : LOADING;
|
|
172
76
|
}
|
|
173
77
|
function createSessionStore(first) {
|
|
@@ -192,14 +96,38 @@ function createSessionStore(first) {
|
|
|
192
96
|
}
|
|
193
97
|
};
|
|
194
98
|
}
|
|
99
|
+
|
|
100
|
+
// src/internal/session.tsx
|
|
101
|
+
import { jsx } from "react/jsx-runtime";
|
|
102
|
+
var MAX_TIMEOUT_MS = 2 ** 31 - 1;
|
|
103
|
+
var REFRESH_AFTER_MS = 5 * 60 * 1000;
|
|
104
|
+
var REFRESH_BEFORE_EXPIRY_MS = 60 * 1000;
|
|
105
|
+
var RETRY_MS = 30 * 1000;
|
|
106
|
+
var FRESH_MS = 5 * 1000;
|
|
107
|
+
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;
|
|
108
|
+
var HubContext = createContext({
|
|
109
|
+
session: undefined,
|
|
110
|
+
redirecting: false,
|
|
111
|
+
signOut: () => {},
|
|
112
|
+
suspend: () => {},
|
|
113
|
+
currentToken: () => null,
|
|
114
|
+
refresh: async () => null
|
|
115
|
+
});
|
|
116
|
+
var useHubState = () => useContext(HubContext);
|
|
195
117
|
function HubSessionProvider({
|
|
196
118
|
app,
|
|
197
119
|
hubUrl,
|
|
120
|
+
initialToken,
|
|
198
121
|
children
|
|
199
122
|
}) {
|
|
200
123
|
const key = storageKey(app);
|
|
201
|
-
const [
|
|
202
|
-
const
|
|
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);
|
|
203
131
|
const latest = useRef(store.get().session);
|
|
204
132
|
const held = useRef(store.get().session?.token ?? null);
|
|
205
133
|
const inFlight = useRef(null);
|
|
@@ -212,17 +140,17 @@ function HubSessionProvider({
|
|
|
212
140
|
store.set({ session: next, stalled: stalledToken });
|
|
213
141
|
}, [store]);
|
|
214
142
|
const signIn = useCallback((next) => {
|
|
215
|
-
|
|
143
|
+
writeToken(app, next.token);
|
|
216
144
|
show(next, next.token, null);
|
|
217
|
-
}, [
|
|
145
|
+
}, [app, show]);
|
|
218
146
|
const end = useCallback(() => {
|
|
219
|
-
|
|
147
|
+
writeToken(app, null);
|
|
220
148
|
show(null, null, null);
|
|
221
|
-
}, [
|
|
149
|
+
}, [app, show]);
|
|
222
150
|
const stall = useCallback((token) => {
|
|
223
|
-
|
|
151
|
+
writeToken(app, token);
|
|
224
152
|
show(null, token, token);
|
|
225
|
-
}, [
|
|
153
|
+
}, [app, show]);
|
|
226
154
|
const currentToken = useCallback(() => {
|
|
227
155
|
const current = latest.current;
|
|
228
156
|
return current && current.user.expiresAt > hubNow() ? current.token : null;
|
|
@@ -278,7 +206,7 @@ function HubSessionProvider({
|
|
|
278
206
|
useEffect(() => {
|
|
279
207
|
const fromUrl = takeTokenFromUrl();
|
|
280
208
|
const stored = readStorage(key);
|
|
281
|
-
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()));
|
|
282
210
|
if (valid) {
|
|
283
211
|
signIn(valid);
|
|
284
212
|
if (refreshUrlFor(valid.token, app, hubUrl)) {
|
|
@@ -286,17 +214,17 @@ function HubSessionProvider({
|
|
|
286
214
|
}
|
|
287
215
|
return;
|
|
288
216
|
}
|
|
289
|
-
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)));
|
|
290
218
|
if (!expired) {
|
|
291
219
|
end();
|
|
292
220
|
return;
|
|
293
221
|
}
|
|
294
|
-
|
|
222
|
+
writeToken(app, expired);
|
|
295
223
|
held.current = expired;
|
|
296
224
|
latest.current = undefined;
|
|
297
225
|
store.set(LOADING);
|
|
298
226
|
trade(expired);
|
|
299
|
-
}, [app, hubUrl, key, store, signIn, end, trade]);
|
|
227
|
+
}, [app, hubUrl, key, initial, store, signIn, end, trade]);
|
|
300
228
|
useEffect(() => {
|
|
301
229
|
if (!stalled)
|
|
302
230
|
return;
|
|
@@ -409,4 +337,4 @@ function useHubToken2() {
|
|
|
409
337
|
return useHubSession2()?.token ?? null;
|
|
410
338
|
}
|
|
411
339
|
|
|
412
|
-
export {
|
|
340
|
+
export { useHubState, HubSessionProvider, HubAuthProvider2, HubSignedIn2, useHubSignOut2, useHubSession2, useHubUser2, useHubToken2 };
|
package/dist/convex-react.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type ConvexReactClient } from "convex/react";
|
|
2
|
-
import { type HubAuthProviderProps } from "./session";
|
|
2
|
+
import { type HubAuthProviderProps } from "./internal/session";
|
|
3
3
|
export { HubSignedIn, useHubSession, useHubSignOut, useHubToken, useHubUser, } from "./react";
|
|
4
|
-
export type { HubRole, HubUser } from "./token";
|
|
4
|
+
export type { HubRole, HubUser } from "./internal/token";
|
|
5
5
|
/**
|
|
6
6
|
* HubAuthProvider for apps on Convex: the hub token becomes the Convex
|
|
7
7
|
* identity. Use it in place of ConvexProvider, with the same client, inside
|
package/dist/convex-react.js
CHANGED
|
@@ -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-
|
|
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 };
|
package/dist/convex.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Auth, AuthConfig } from "convex/server";
|
|
2
|
-
import type { HubUser } from "./token";
|
|
3
|
-
export type { HubRole, HubUser } from "./token";
|
|
2
|
+
import type { HubUser } from "./internal/token";
|
|
3
|
+
export type { HubRole, HubUser } from "./internal/token";
|
|
4
4
|
type Provider = AuthConfig["providers"][number];
|
|
5
5
|
/**
|
|
6
6
|
* The Convex auth provider for hub tokens. In `convex/auth.config.ts`:
|
|
@@ -8,7 +8,7 @@ type Provider = AuthConfig["providers"][number];
|
|
|
8
8
|
* export default { providers: [hubAuth({ app: "voting" })] } satisfies AuthConfig;
|
|
9
9
|
*
|
|
10
10
|
* Reads HUB_ISSUER and HUB_JWKS from the Convex deployment's environment
|
|
11
|
-
* (`bunx hub
|
|
11
|
+
* (`bunx user-hub apps register` prints both). Then `ctx.auth.getUserIdentity()`
|
|
12
12
|
* returns the person: `subject` is their hub id, plus `name`, `team`, `role`.
|
|
13
13
|
*/
|
|
14
14
|
export declare function hubAuth({ app }: {
|
package/dist/convex.js
CHANGED
|
@@ -4,7 +4,7 @@ function hubAuth({ app }) {
|
|
|
4
4
|
const issuer = process.env.HUB_ISSUER;
|
|
5
5
|
const jwks = process.env.HUB_JWKS;
|
|
6
6
|
if (!issuer || !jwks) {
|
|
7
|
-
throw new Error("Set HUB_ISSUER and HUB_JWKS on this Convex deployment: run `bunx hub
|
|
7
|
+
throw new Error("Set HUB_ISSUER and HUB_JWKS on this Convex deployment: run `bunx user-hub apps register`");
|
|
8
8
|
}
|
|
9
9
|
return {
|
|
10
10
|
type: "customJwt",
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type HubSession } from "./token";
|
|
2
|
+
export declare function refreshUrlFor(token: string, app: string, hubUrl?: string): string | null;
|
|
3
|
+
export type Exchange = {
|
|
4
|
+
status: "refreshed";
|
|
5
|
+
session: HubSession;
|
|
6
|
+
} | {
|
|
7
|
+
status: "ended";
|
|
8
|
+
} | {
|
|
9
|
+
status: "failed";
|
|
10
|
+
};
|
|
11
|
+
export declare function exchange(token: string, app: string, hubUrl?: string): Promise<Exchange>;
|