nextidp 0.1.2 → 0.1.4
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/CHANGELOG.md +39 -0
- package/README.md +116 -6
- package/dist/cjs/config.d.ts +20 -1
- package/dist/cjs/config.js +8 -1
- package/dist/cjs/cookies.d.ts +3 -1
- package/dist/cjs/cookies.js +4 -4
- package/dist/cjs/express.d.ts +1 -1
- package/dist/cjs/hono.d.ts +65 -0
- package/dist/cjs/hono.js +130 -0
- package/dist/cjs/idp.d.ts +14 -2
- package/dist/cjs/idp.js +74 -15
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/next.d.ts +1 -1
- package/dist/cjs/next.js +14 -0
- package/dist/cjs/node.d.ts +1 -1
- package/dist/cjs/session.d.ts +24 -1
- package/dist/cjs/session.js +33 -5
- package/dist/esm/config.d.ts +20 -1
- package/dist/esm/config.js +8 -1
- package/dist/esm/cookies.d.ts +3 -1
- package/dist/esm/cookies.js +4 -4
- package/dist/esm/express.d.ts +1 -1
- package/dist/esm/hono.d.ts +65 -0
- package/dist/esm/hono.js +106 -0
- package/dist/esm/idp.d.ts +14 -2
- package/dist/esm/idp.js +75 -15
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/next.d.ts +1 -1
- package/dist/esm/next.js +14 -0
- package/dist/esm/node.d.ts +1 -1
- package/dist/esm/session.d.ts +24 -1
- package/dist/esm/session.js +32 -5
- package/package.json +24 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.4
|
|
4
|
+
|
|
5
|
+
### Sign-in
|
|
6
|
+
|
|
7
|
+
- `GET <basePath>/login?prompt=…` passes `prompt` on to the auth server: `login`, `consent`
|
|
8
|
+
or `select_account`, or several separated by spaces. Any other value, `none` included, is
|
|
9
|
+
left out, and nothing else in the query is passed on. `signInPath(returnTo, { prompt })`
|
|
10
|
+
builds the link.
|
|
11
|
+
- `reauthenticateAfterSignOut` (default `false`): a sign-out leaves a small marker cookie
|
|
12
|
+
(`<prefix>.signed-out`, `__Secure-` on https, on `basePath` only, 30 days), and the next
|
|
13
|
+
sign-in sends `prompt=login` and clears it, so a shared computer doesn't sign the next person
|
|
14
|
+
in as the last. A link with `reauthenticate=false` (a "Create account" link) opts out and
|
|
15
|
+
leaves the marker; a `prompt` in the link wins over it.
|
|
16
|
+
- `userinfo` (default `false`): the email, `email_verified`, name and picture from the
|
|
17
|
+
userinfo endpoint, merged into `session.user` after sign-in and after a refresh that brings
|
|
18
|
+
a new ID token (kept otherwise), for auth servers that leave them out of the ID token.
|
|
19
|
+
Best effort: a failure, or an answer about another `sub`, goes to `onError` and the
|
|
20
|
+
sign-in goes ahead. `session.claims` stays the ID token's.
|
|
21
|
+
|
|
22
|
+
### Next.js
|
|
23
|
+
|
|
24
|
+
- `routes()` answers a fetch of the login route by Next's client router (a `<Link>`,
|
|
25
|
+
`router.push` or a prefetch: the `rsc` header) with a 200 "Sign-in needs a full page load."
|
|
26
|
+
and no cookie, instead of a redirect it can't follow. The router then loads it as a whole
|
|
27
|
+
page, and a sign-in under way keeps its flow cookie.
|
|
28
|
+
|
|
29
|
+
## 0.1.3
|
|
30
|
+
|
|
31
|
+
### Hono, and edge runtimes
|
|
32
|
+
|
|
33
|
+
- `nextidp/hono`: `routes()`, `middleware()` (the session as `c.get("session")`, refreshed
|
|
34
|
+
before it expires), `requireSession()` and `requireToken()` (the token as
|
|
35
|
+
`c.get("token")`), with the `IdpEnv` type for `new Hono<IdpEnv>()`. A refreshed cookie
|
|
36
|
+
reaches any response the handler makes, its own `Response` included.
|
|
37
|
+
- Runs on edge runtimes (Cloudflare Workers, Vercel Edge, Deno, Bun): the tests bundle the
|
|
38
|
+
core and the Hono adapter for a platform without Node built-ins and run them in Cloudflare's
|
|
39
|
+
`workerd`, with no Node compatibility: sign-in, refresh, sign-out, back-channel logout,
|
|
40
|
+
API tokens and service tokens.
|
|
41
|
+
|
|
3
42
|
## 0.1.2
|
|
4
43
|
|
|
5
44
|
The first release with code in it: sign-in for Next.js, Express and Node, API protection
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# nextidp
|
|
2
2
|
|
|
3
|
-
Sign people in to your Next.js, Express or Node app, and protect your APIs, with
|
|
3
|
+
Sign people in to your Next.js, Express, Hono or Node app, and protect your APIs, with
|
|
4
4
|
[authserver-oidc](https://github.com/sajanv88/authserver-oidc), in one call. It does the
|
|
5
5
|
OpenID Connect work for you:
|
|
6
6
|
|
|
@@ -11,8 +11,8 @@ OpenID Connect work for you:
|
|
|
11
11
|
logout](#sessions-in-a-store-and-back-channel-logout));
|
|
12
12
|
- refreshing tokens before they expire;
|
|
13
13
|
- signing out, of your app or of the auth server too;
|
|
14
|
-
- checking the access tokens your API is called with, and their scopes, in NestJS, Express
|
|
15
|
-
or a Next.js route handler ([below](#protecting-an-api));
|
|
14
|
+
- checking the access tokens your API is called with, and their scopes, in NestJS, Express,
|
|
15
|
+
Hono or a Next.js route handler ([below](#protecting-an-api));
|
|
16
16
|
- tokens for a service to call other APIs as itself ([below](#calling-an-api-as-a-service)).
|
|
17
17
|
|
|
18
18
|
It works with any OpenID Connect provider that supports the code flow with PKCE, but it's
|
|
@@ -22,9 +22,10 @@ made for, and tested against, authserver-oidc.
|
|
|
22
22
|
npm i nextidp
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
ES module and CommonJS builds, with types. Node 24 or later
|
|
25
|
+
ES module and CommonJS builds, with types. Node 24 or later, or an edge runtime
|
|
26
|
+
(Cloudflare Workers, Vercel Edge, Deno, Bun: [below](#edge-runtimes)). Next.js 15 or 16 (App
|
|
26
27
|
Router), Express (tested with 5) or anything else that takes Node middleware, Node's own
|
|
27
|
-
HTTP server, and NestJS 11 or 12 for APIs.
|
|
28
|
+
HTTP server, Hono 4, and NestJS 11 or 12 for APIs.
|
|
28
29
|
|
|
29
30
|
## 1. Register your app on the auth server
|
|
30
31
|
|
|
@@ -98,6 +99,13 @@ export default async function Dashboard() {
|
|
|
98
99
|
</form>
|
|
99
100
|
```
|
|
100
101
|
|
|
102
|
+
Link to `/auth/login` with a plain `<a>`, as above. A `<Link>`, a `router.push` or a prefetch
|
|
103
|
+
makes Next's client router fetch the route itself, and that fetch can't follow the redirect to
|
|
104
|
+
the auth server (another origin). So `auth.routes()` answers such a fetch (it carries the
|
|
105
|
+
`rsc` header) with a plain 200, "Sign-in needs a full page load.", and no cookie: the router
|
|
106
|
+
then loads the address as a whole page, which signs in as usual, and a sign-in already under
|
|
107
|
+
way keeps its cookie.
|
|
108
|
+
|
|
101
109
|
Calling an API as the signed-in person:
|
|
102
110
|
|
|
103
111
|
```ts
|
|
@@ -154,19 +162,111 @@ createServer(async (req, res) => {
|
|
|
154
162
|
Read the session before you start the response: a refresh sets a new cookie. Read twice in
|
|
155
163
|
one request, it's refreshed once.
|
|
156
164
|
|
|
165
|
+
## Hono
|
|
166
|
+
|
|
167
|
+
On any runtime Hono runs on:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
import { Hono } from "hono";
|
|
171
|
+
import { idp, type IdpEnv } from "nextidp/hono";
|
|
172
|
+
|
|
173
|
+
const auth = idp();
|
|
174
|
+
const app = new Hono<IdpEnv>();
|
|
175
|
+
|
|
176
|
+
app.all("/auth/*", auth.routes()); // nextidp's routes
|
|
177
|
+
app.use(auth.middleware()); // the session on every request, refreshed before it expires
|
|
178
|
+
|
|
179
|
+
app.get("/", (c) => {
|
|
180
|
+
const session = c.get("session"); // null if signed out
|
|
181
|
+
return c.text(session ? `Hello, ${session.user.name}` : "Signed out");
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// Signed out, a GET goes to sign in and comes back; anything else gets 401.
|
|
185
|
+
app.get("/dashboard", auth.requireSession(), (c) => c.text(`Hello, ${c.get("session")?.user.name}`));
|
|
186
|
+
|
|
187
|
+
// An API: 401 or 403 with the RFC 6750 challenge, 503 if the token can't be checked.
|
|
188
|
+
app.get("/api/orders", auth.requireToken({ scopes: ["orders:read"] }), (c) =>
|
|
189
|
+
c.json(ordersOf(c.get("token").subject)),
|
|
190
|
+
);
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
A refreshed session's cookie is added to whatever response the handler makes, its own
|
|
194
|
+
`Response` included.
|
|
195
|
+
|
|
196
|
+
## Edge runtimes
|
|
197
|
+
|
|
198
|
+
The core uses only Web APIs (`fetch`, `Request`/`Response`, `crypto.subtle`), so it runs on
|
|
199
|
+
Cloudflare Workers, Vercel Edge, Deno and Bun as well as Node: everything but `nextidp/node`,
|
|
200
|
+
`nextidp/express` and `nextidp/nestjs`, which are for Node. Its tests run it in Cloudflare's
|
|
201
|
+
own runtime, `workerd`, with no Node compatibility turned on.
|
|
202
|
+
|
|
203
|
+
Where there's no `process.env` (Cloudflare Workers), pass the settings from the Worker's
|
|
204
|
+
bindings, read on first use:
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
import { Hono } from "hono";
|
|
208
|
+
import { idp, type IdpEnv } from "nextidp/hono";
|
|
209
|
+
|
|
210
|
+
type Bindings = { IDP_ISSUER: string; IDP_CLIENT_ID: string; IDP_APP_URL: string; IDP_SECRET: string };
|
|
211
|
+
|
|
212
|
+
let bindings: Bindings;
|
|
213
|
+
const auth = idp(() => ({ env: bindings })); // the IDP_* names, from the bindings
|
|
214
|
+
|
|
215
|
+
const app = new Hono<IdpEnv>();
|
|
216
|
+
app.all("/auth/*", auth.routes());
|
|
217
|
+
app.use(auth.middleware());
|
|
218
|
+
|
|
219
|
+
export default {
|
|
220
|
+
fetch(request: Request, env: Bindings) {
|
|
221
|
+
bindings = env;
|
|
222
|
+
return app.fetch(request, env);
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Each isolate has its own memory, so `memoryStore()` there is per isolate. For sessions in a
|
|
228
|
+
store, use one every isolate reaches: a database, or Durable Objects. Cloudflare KV works too,
|
|
229
|
+
but it's eventually consistent: a back-channel logout can take a little while (up to about a
|
|
230
|
+
minute) to reach every location.
|
|
231
|
+
|
|
157
232
|
## The routes
|
|
158
233
|
|
|
159
234
|
All under `basePath` (default `/auth`):
|
|
160
235
|
|
|
161
236
|
| Route | What it does |
|
|
162
237
|
|---|---|
|
|
163
|
-
| `GET /auth/login?returnTo=/path` | Starts a sign-in, and comes back to `returnTo` (paths of this app only). |
|
|
238
|
+
| `GET /auth/login?returnTo=/path` | Starts a sign-in, and comes back to `returnTo` (paths of this app only). Takes `prompt` and `reauthenticate=false` too ([below](#asking-for-the-password-again)). |
|
|
164
239
|
| `GET /auth/callback` | Finishes it: the redirect URI you registered. |
|
|
165
240
|
| `POST /auth/logout` | Revokes the refresh token and ends this app's session. With `signOutOfIdp=true`, the auth server's too. |
|
|
166
241
|
| `POST /auth/refresh` | New tokens now, then back to the form's `returnTo`. |
|
|
167
242
|
|
|
168
243
|
The POST routes accept forms from this app's own pages only (they check `Origin`).
|
|
169
244
|
|
|
245
|
+
### Asking for the password again
|
|
246
|
+
|
|
247
|
+
`GET /auth/login?prompt=login` makes the auth server ask for the password even while its own
|
|
248
|
+
session is still live; `consent` shows the consent screen again; `select_account` asks which
|
|
249
|
+
account. Several go together, separated by spaces (`prompt=login consent`). Any other value
|
|
250
|
+
(`none` included) is left out, and nothing else in the query reaches the auth server.
|
|
251
|
+
|
|
252
|
+
Signing out of the app alone leaves the auth server's session live, so by default the next
|
|
253
|
+
sign-in goes straight through: on a shared computer, as the person before. With
|
|
254
|
+
`reauthenticateAfterSignOut: true`, signing out leaves a small cookie
|
|
255
|
+
(`__Secure-nextidp.signed-out` on https, on `basePath` only, 30 days; its value means
|
|
256
|
+
nothing) and the next sign-in sends `prompt=login`, once.
|
|
257
|
+
|
|
258
|
+
A "Create account" link starts at `/auth/login` too, and `prompt=login` would show the
|
|
259
|
+
sign-in form again once the account exists. Opt it out with `reauthenticate=false`: no
|
|
260
|
+
`prompt`, and the cookie stays for the next real sign-in. A `prompt` in the link wins over the
|
|
261
|
+
cookie.
|
|
262
|
+
|
|
263
|
+
```tsx
|
|
264
|
+
<a href="/auth/login?reauthenticate=false">Create account</a>
|
|
265
|
+
<a href={auth.signInPath("/settings", { prompt: "consent" })}>Review permissions</a>
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
`auth.signInPath(returnTo, { prompt, reauthenticate })` builds these links.
|
|
269
|
+
|
|
170
270
|
## The session
|
|
171
271
|
|
|
172
272
|
```ts
|
|
@@ -183,6 +283,14 @@ type Session = {
|
|
|
183
283
|
The refresh token and the ID token stay inside the encrypted cookie: nothing in the browser
|
|
184
284
|
can read them.
|
|
185
285
|
|
|
286
|
+
`user` comes from the ID token's claims. Some auth servers (authserver-oidc among them) put
|
|
287
|
+
the email and the name in userinfo instead: with `userinfo: true`, nextidp asks userinfo after
|
|
288
|
+
sign-in, and again when a refresh brings a new ID token, and fills `user`'s `email`,
|
|
289
|
+
`emailVerified`, `name` and `picture` from it (only those, so the cookie stays small; an email
|
|
290
|
+
comes with userinfo's own `email_verified` or none). If userinfo fails, or answers for another
|
|
291
|
+
`sub`, the sign-in goes ahead with what the ID token had, and `onError` is told. `claims`
|
|
292
|
+
stays the ID token's.
|
|
293
|
+
|
|
186
294
|
## All the settings
|
|
187
295
|
|
|
188
296
|
Pass them to `idp({...})`, or set the variable in brackets. A function works too,
|
|
@@ -204,6 +312,8 @@ Pass them to `idp({...})`, or set the variable in brackets. A function works too
|
|
|
204
312
|
| `afterSignOut` | `/` | Where sign-out lands: also the post-logout redirect URI. |
|
|
205
313
|
| `errorPath` | `/` | Where a failed sign-in lands, with `?error=<code>`. |
|
|
206
314
|
| `signOutOfIdp` | `false` | Sign out of the auth server too, unless the form says otherwise. |
|
|
315
|
+
| `reauthenticateAfterSignOut` | `false` | After a sign-out, the next sign-in asks for the password again (`prompt=login`), unless its link says `reauthenticate=false` ([above](#asking-for-the-password-again)). |
|
|
316
|
+
| `userinfo` | `false` | Fill the session's email, name and picture from userinfo: one more request at sign-in, and at each refresh that brings a new ID token ([above](#the-session)). |
|
|
207
317
|
| `sessionMaxAge` | 7 days | Renewed at every refresh. |
|
|
208
318
|
| `cookiePrefix` | `nextidp` | Cookies are `__Host-nextidp.session` on https. |
|
|
209
319
|
| `store` | none: sessions live in the cookie | Keep sessions in a store instead ([below](#sessions-in-a-store-and-back-channel-logout)). |
|
package/dist/cjs/config.d.ts
CHANGED
|
@@ -42,6 +42,21 @@ export type IdpOptions = {
|
|
|
42
42
|
errorPath?: string | undefined;
|
|
43
43
|
/** Sign out of the auth server too, by default. A form field can still choose. Default false. */
|
|
44
44
|
signOutOfIdp?: boolean | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* After someone signs out of this app, the next sign-in asks for their password again
|
|
47
|
+
* (`prompt=login`), even while their session at the auth server is still live: on a shared
|
|
48
|
+
* computer, the next person isn't signed in as them. A small cookie remembers the sign-out.
|
|
49
|
+
* A sign-in link opts out with `?reauthenticate=false` (a "Create account" link). Default
|
|
50
|
+
* false.
|
|
51
|
+
*/
|
|
52
|
+
reauthenticateAfterSignOut?: boolean | undefined;
|
|
53
|
+
/**
|
|
54
|
+
* Also read the email, name and picture from the userinfo endpoint after sign-in (and after
|
|
55
|
+
* a refresh that brings a new ID token), for auth servers that leave them out of the ID
|
|
56
|
+
* token. Best effort: if it fails, the sign-in goes ahead with what the ID token had, and
|
|
57
|
+
* `onError` is told. Costs one more request. Default false.
|
|
58
|
+
*/
|
|
59
|
+
userinfo?: boolean | undefined;
|
|
45
60
|
/** How long the session cookie lasts, in seconds, renewed at every refresh. Default 7 days. */
|
|
46
61
|
sessionMaxAge?: number | undefined;
|
|
47
62
|
/** The start of this app's cookie names. Default `nextidp`. */
|
|
@@ -99,12 +114,16 @@ export type IdpConfig = {
|
|
|
99
114
|
postLogoutRedirectUri: string;
|
|
100
115
|
errorPath: string;
|
|
101
116
|
signOutOfIdp: boolean;
|
|
117
|
+
reauthenticateAfterSignOut: boolean;
|
|
118
|
+
userinfo: boolean;
|
|
102
119
|
sessionMaxAge: number;
|
|
103
|
-
/** https: cookies are Secure, with `__Host-` names. */
|
|
120
|
+
/** https: cookies are Secure, with `__Host-` names (`__Secure-` for `signedOut`). */
|
|
104
121
|
secure: boolean;
|
|
122
|
+
/** `signedOut` is the marker `reauthenticateAfterSignOut` sets, on `basePath` only. */
|
|
105
123
|
cookies: {
|
|
106
124
|
session: string;
|
|
107
125
|
flow: string;
|
|
126
|
+
signedOut: string;
|
|
108
127
|
};
|
|
109
128
|
store: SessionStore | undefined;
|
|
110
129
|
/** Where the auth server sends logout tokens, with a store. */
|
package/dist/cjs/config.js
CHANGED
|
@@ -217,9 +217,16 @@ function resolveConfig(options) {
|
|
|
217
217
|
postLogoutRedirectUri: `${appUrl}${afterSignOut}`,
|
|
218
218
|
errorPath,
|
|
219
219
|
signOutOfIdp: options.signOutOfIdp ?? false,
|
|
220
|
+
reauthenticateAfterSignOut: options.reauthenticateAfterSignOut ?? false,
|
|
221
|
+
userinfo: options.userinfo ?? false,
|
|
220
222
|
sessionMaxAge,
|
|
221
223
|
secure,
|
|
222
|
-
cookies: {
|
|
224
|
+
cookies: {
|
|
225
|
+
session: name("session"),
|
|
226
|
+
flow: name("flow"),
|
|
227
|
+
// Path=<basePath>, which a __Host- name doesn't allow: __Secure- keeps it https-only.
|
|
228
|
+
signedOut: `${secure ? "__Secure-" : ""}${prefix}.signed-out`
|
|
229
|
+
},
|
|
223
230
|
store,
|
|
224
231
|
backchannelLogoutUri: `${appUrl}${basePath}/backchannel-logout`
|
|
225
232
|
};
|
package/dist/cjs/cookies.d.ts
CHANGED
|
@@ -3,9 +3,11 @@ export declare const CHUNK_SIZE = 3800;
|
|
|
3
3
|
export type CookieJar = ReadonlyMap<string, string>;
|
|
4
4
|
/** The cookies a request carries. When a name comes twice, the first is kept. */
|
|
5
5
|
export declare function parseCookies(header: string | null | undefined): CookieJar;
|
|
6
|
+
/** `path` defaults to `/`. */
|
|
6
7
|
export type CookieAttributes = {
|
|
7
8
|
secure: boolean;
|
|
8
9
|
maxAge: number;
|
|
10
|
+
path?: string;
|
|
9
11
|
};
|
|
10
12
|
/** A value written by `writeCookie`: the one cookie, or its chunks joined in order. */
|
|
11
13
|
export declare function readCookie(jar: CookieJar, name: string): string | undefined;
|
|
@@ -15,7 +17,7 @@ export declare function readCookie(jar: CookieJar, name: string): string | undef
|
|
|
15
17
|
*/
|
|
16
18
|
export declare function writeCookie(jar: CookieJar, name: string, value: string, attributes: CookieAttributes): string[];
|
|
17
19
|
/** Set-Cookie headers that expire `name` and every chunk of it the request holds. */
|
|
18
|
-
export declare function clearCookie(jar: CookieJar, name: string, secure: boolean): string[];
|
|
20
|
+
export declare function clearCookie(jar: CookieJar, name: string, secure: boolean, path?: string): string[];
|
|
19
21
|
/**
|
|
20
22
|
* The Cookie header the rest of this request should see once `setCookies` apply: what a
|
|
21
23
|
* proxy hands on, so the page renders with the refreshed session and not the old one.
|
package/dist/cjs/cookies.js
CHANGED
|
@@ -41,10 +41,10 @@ function parseCookies(header) {
|
|
|
41
41
|
}
|
|
42
42
|
return jar;
|
|
43
43
|
}
|
|
44
|
-
function serialize(name, value, { secure, maxAge }) {
|
|
44
|
+
function serialize(name, value, { secure, maxAge, path = "/" }) {
|
|
45
45
|
return [
|
|
46
46
|
`${name}=${value}`,
|
|
47
|
-
|
|
47
|
+
`Path=${path}`,
|
|
48
48
|
`Max-Age=${maxAge}`,
|
|
49
49
|
"HttpOnly",
|
|
50
50
|
"SameSite=Lax",
|
|
@@ -90,9 +90,9 @@ function writeCookie(jar, name, value, attributes) {
|
|
|
90
90
|
}
|
|
91
91
|
return headers;
|
|
92
92
|
}
|
|
93
|
-
function clearCookie(jar, name, secure) {
|
|
93
|
+
function clearCookie(jar, name, secure, path = "/") {
|
|
94
94
|
const names = /* @__PURE__ */ new Set([name, ...chunkNames(jar, name)]);
|
|
95
|
-
return [...names].map((stale) => serialize(stale, "", { secure, maxAge: 0 }));
|
|
95
|
+
return [...names].map((stale) => serialize(stale, "", { secure, maxAge: 0, path }));
|
|
96
96
|
}
|
|
97
97
|
function applySetCookies(header, setCookies) {
|
|
98
98
|
const jar = new Map(parseCookies(header));
|
package/dist/cjs/express.d.ts
CHANGED
|
@@ -64,7 +64,7 @@ export declare function idp(options?: IdpOptions | (() => IdpOptions)): ExpressI
|
|
|
64
64
|
export type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
65
65
|
export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
|
|
66
66
|
export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
|
|
67
|
-
export type { Idp, Refreshed } from "./idp.js";
|
|
67
|
+
export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
|
|
68
68
|
export type { SessionOptions } from "./node-adapter.js";
|
|
69
69
|
export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
|
|
70
70
|
export type { IdpUser, Session } from "./session.js";
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
2
|
+
import type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
3
|
+
import type { IdpOptions } from "./config.js";
|
|
4
|
+
import { type Idp } from "./idp.js";
|
|
5
|
+
import type { Session } from "./session.js";
|
|
6
|
+
/**
|
|
7
|
+
* The context variables nextidp sets: `session` (by `middleware()`, null when signed out) and
|
|
8
|
+
* `token` (by `requireToken()`). Give it to your app: `new Hono<IdpEnv>()`.
|
|
9
|
+
*/
|
|
10
|
+
export type IdpEnv = {
|
|
11
|
+
Variables: {
|
|
12
|
+
session: Session | null;
|
|
13
|
+
token: AccessToken;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
export type HonoSessionOptions = {
|
|
17
|
+
/** Refresh the access token when it expires within a minute (default true). */
|
|
18
|
+
refresh?: boolean;
|
|
19
|
+
};
|
|
20
|
+
export type HonoIdp = Idp & {
|
|
21
|
+
/** nextidp's routes, for `app.all("/auth/*", auth.routes())` (under `basePath`). */
|
|
22
|
+
routes(): (c: Context) => Promise<Response>;
|
|
23
|
+
/**
|
|
24
|
+
* Reads the session for every request (refreshing the access token when it's about to
|
|
25
|
+
* expire, with the new cookie on the response) and puts it on the context:
|
|
26
|
+
* `c.get("session")`, null when signed out. `app.use(auth.middleware())`.
|
|
27
|
+
*/
|
|
28
|
+
middleware(options?: HonoSessionOptions): MiddlewareHandler<IdpEnv>;
|
|
29
|
+
/**
|
|
30
|
+
* Lets a request through only with a session. Signed out, a GET or HEAD goes to sign in and
|
|
31
|
+
* comes back after; anything else gets 401.
|
|
32
|
+
*/
|
|
33
|
+
requireSession(): MiddlewareHandler<IdpEnv>;
|
|
34
|
+
/**
|
|
35
|
+
* Lets a request through only with a valid access token that has every scope in
|
|
36
|
+
* `requirements`, put on the context as `c.get("token")`. A refused one gets 401 or 403 with
|
|
37
|
+
* WWW-Authenticate (RFC 6750); one that can't be checked now (the auth server is down) 503.
|
|
38
|
+
*/
|
|
39
|
+
requireToken(requirements?: TokenRequirements): MiddlewareHandler<IdpEnv>;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* The client for a Hono app or API:
|
|
43
|
+
*
|
|
44
|
+
* ```ts
|
|
45
|
+
* import { Hono } from "hono";
|
|
46
|
+
* import { idp, type IdpEnv } from "nextidp/hono";
|
|
47
|
+
*
|
|
48
|
+
* const auth = idp({ issuer: "https://auth.example.com", clientId: "…", appUrl: "…", secret: "…" });
|
|
49
|
+
* const app = new Hono<IdpEnv>();
|
|
50
|
+
* app.all("/auth/*", auth.routes());
|
|
51
|
+
* app.use(auth.middleware());
|
|
52
|
+
* app.get("/dashboard", auth.requireSession(), (c) => c.text(`Hello, ${c.get("session")?.user.name}`));
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* On a runtime without `process.env` (Cloudflare Workers), pass the settings, or `env`:
|
|
56
|
+
* `idp(() => ({ env: workerEnv }))`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function idp(options?: IdpOptions | (() => IdpOptions)): HonoIdp;
|
|
59
|
+
export type { AccessToken, TokenRequirements } from "./access-token.js";
|
|
60
|
+
export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
|
|
61
|
+
export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
|
|
62
|
+
export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
|
|
63
|
+
export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
|
|
64
|
+
export type { IdpUser, Session } from "./session.js";
|
|
65
|
+
export { memoryStore, type SessionStore } from "./store.js";
|
package/dist/cjs/hono.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var hono_exports = {};
|
|
20
|
+
__export(hono_exports, {
|
|
21
|
+
IdpError: () => import_errors2.IdpError,
|
|
22
|
+
SIGN_IN_ERROR_CODES: () => import_errors2.SIGN_IN_ERROR_CODES,
|
|
23
|
+
idp: () => idp,
|
|
24
|
+
isIdpError: () => import_errors2.isIdpError,
|
|
25
|
+
isSignInErrorCode: () => import_errors2.isSignInErrorCode,
|
|
26
|
+
isTokenError: () => import_errors2.isTokenError,
|
|
27
|
+
memoryStore: () => import_store.memoryStore
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(hono_exports);
|
|
30
|
+
var import_errors = require("./errors.js");
|
|
31
|
+
var import_idp = require("./idp.js");
|
|
32
|
+
var import_errors2 = require("./errors.js");
|
|
33
|
+
var import_store = require("./store.js");
|
|
34
|
+
function putCookies(c, cookies) {
|
|
35
|
+
if (cookies.length === 0) return;
|
|
36
|
+
try {
|
|
37
|
+
for (const cookie of cookies) c.res.headers.append("set-cookie", cookie);
|
|
38
|
+
} catch {
|
|
39
|
+
const copy = new Response(c.res.body, c.res);
|
|
40
|
+
for (const cookie of cookies) copy.headers.append("set-cookie", cookie);
|
|
41
|
+
c.res = void 0;
|
|
42
|
+
c.res = copy;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function underBasePath(pathname, basePath) {
|
|
46
|
+
return pathname === basePath || pathname.startsWith(`${basePath}/`);
|
|
47
|
+
}
|
|
48
|
+
function idp(options) {
|
|
49
|
+
const core = (0, import_idp.createIdp)(options);
|
|
50
|
+
const sessionOf = async (c, refresh) => {
|
|
51
|
+
if (!refresh) return { session: await core.getSession(c.req.raw), setCookies: [] };
|
|
52
|
+
const { session, setCookies } = await core.refreshIfNeeded(c.req.raw);
|
|
53
|
+
return { session, setCookies };
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
...core,
|
|
57
|
+
routes: () => (c) => core.handler(c.req.raw),
|
|
58
|
+
middleware({ refresh = true } = {}) {
|
|
59
|
+
return async (c, next) => {
|
|
60
|
+
if (underBasePath(new URL(c.req.url).pathname, core.config().basePath)) {
|
|
61
|
+
await next();
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const { session, setCookies } = await sessionOf(c, refresh);
|
|
65
|
+
c.set("session", session);
|
|
66
|
+
await next();
|
|
67
|
+
putCookies(c, setCookies);
|
|
68
|
+
};
|
|
69
|
+
},
|
|
70
|
+
requireSession() {
|
|
71
|
+
return async (c, next) => {
|
|
72
|
+
const known = c.get("session");
|
|
73
|
+
const { session, setCookies } = known === void 0 ? await sessionOf(c, true) : { session: known, setCookies: [] };
|
|
74
|
+
if (session) {
|
|
75
|
+
c.set("session", session);
|
|
76
|
+
await next();
|
|
77
|
+
putCookies(c, setCookies);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const method = c.req.method.toUpperCase();
|
|
81
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
82
|
+
c.res = c.text("Sign in first.", 401, { "cache-control": "no-store" });
|
|
83
|
+
} else {
|
|
84
|
+
const url = new URL(c.req.url);
|
|
85
|
+
const signIn = new URL(
|
|
86
|
+
core.signInPath(`${url.pathname}${url.search}`),
|
|
87
|
+
core.config().appUrl
|
|
88
|
+
);
|
|
89
|
+
c.res = c.redirect(signIn.toString(), 302);
|
|
90
|
+
c.res.headers.set("cache-control", "no-store");
|
|
91
|
+
}
|
|
92
|
+
putCookies(c, setCookies);
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
requireToken(requirements = {}) {
|
|
96
|
+
return async (c, next) => {
|
|
97
|
+
let token;
|
|
98
|
+
try {
|
|
99
|
+
token = await core.verifyBearer(c.req.header("authorization"), requirements);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if ((0, import_errors.isTokenError)(error)) return core.tokenErrorResponse(error);
|
|
102
|
+
console.error(
|
|
103
|
+
`nextidp: a token couldn't be checked: ${(0, import_errors.isIdpError)(error) ? error.code : "unexpected error"}`
|
|
104
|
+
);
|
|
105
|
+
return c.json(
|
|
106
|
+
{
|
|
107
|
+
error: "temporarily_unavailable",
|
|
108
|
+
error_description: "The token can't be checked now."
|
|
109
|
+
},
|
|
110
|
+
503,
|
|
111
|
+
{ "retry-after": "5", "cache-control": "no-store" }
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
c.set("token", token);
|
|
115
|
+
await next();
|
|
116
|
+
return void 0;
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
122
|
+
0 && (module.exports = {
|
|
123
|
+
IdpError,
|
|
124
|
+
SIGN_IN_ERROR_CODES,
|
|
125
|
+
idp,
|
|
126
|
+
isIdpError,
|
|
127
|
+
isSignInErrorCode,
|
|
128
|
+
isTokenError,
|
|
129
|
+
memoryStore
|
|
130
|
+
});
|
package/dist/cjs/idp.d.ts
CHANGED
|
@@ -34,8 +34,13 @@ export type Idp = {
|
|
|
34
34
|
}): Promise<Refreshed>;
|
|
35
35
|
/** The userinfo endpoint's claims for an access token. */
|
|
36
36
|
userInfo(accessToken: string): Promise<Record<string, unknown>>;
|
|
37
|
-
/**
|
|
38
|
-
|
|
37
|
+
/**
|
|
38
|
+
* The path that starts a sign-in, returning to `returnTo` (a path of this app) after.
|
|
39
|
+
* `prompt` asks the auth server for `login`, `consent` or `select_account` (others are left
|
|
40
|
+
* out); `reauthenticate: false` is for a "Create account" link, which mustn't ask for a
|
|
41
|
+
* password again after a sign-out (see `reauthenticateAfterSignOut`).
|
|
42
|
+
*/
|
|
43
|
+
signInPath(returnTo?: string, options?: SignInPathOptions): string;
|
|
39
44
|
/** For an API: the checked settings it needs (issuer and audience). */
|
|
40
45
|
apiConfig(): ApiConfig;
|
|
41
46
|
/**
|
|
@@ -73,6 +78,13 @@ export type Idp = {
|
|
|
73
78
|
*/
|
|
74
79
|
useServiceToken(client: InterceptableClient, options?: UseServiceTokenOptions): () => void;
|
|
75
80
|
};
|
|
81
|
+
/** What `signInPath` can add to the sign-in link. */
|
|
82
|
+
export type SignInPathOptions = {
|
|
83
|
+
/** `login`, `consent` or `select_account`, or several separated by spaces. */
|
|
84
|
+
prompt?: string | undefined;
|
|
85
|
+
/** false: no `prompt=login` from an earlier sign-out (see `reauthenticateAfterSignOut`). */
|
|
86
|
+
reauthenticate?: boolean | undefined;
|
|
87
|
+
};
|
|
76
88
|
/**
|
|
77
89
|
* The client for one app. Settings are checked on first use, not here, so a module that
|
|
78
90
|
* calls `idp()` can be imported where they aren't set (a build). Pass a function to read
|