@lumoauth/nextjs 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +146 -2
- package/dist/index.d.mts +19 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +110 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +72 -0
- package/dist/index.mjs.map +1 -0
- package/dist/server.d.mts +232 -0
- package/dist/server.d.ts +232 -0
- package/dist/server.js +433 -0
- package/dist/server.js.map +1 -0
- package/dist/server.mjs +396 -0
- package/dist/server.mjs.map +1 -0
- package/package.json +67 -4
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { UserInfo } from '@lumoauth/shared';
|
|
2
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
3
|
+
|
|
4
|
+
interface LumoAuthNextConfig {
|
|
5
|
+
/** Base URL of your LumoAuth instance. */
|
|
6
|
+
domain: string;
|
|
7
|
+
/** Organization slug. */
|
|
8
|
+
orgId: string;
|
|
9
|
+
/** OAuth client id. */
|
|
10
|
+
clientId: string;
|
|
11
|
+
/** Client secret, for confidential clients. Public + PKCE clients omit it. */
|
|
12
|
+
clientSecret?: string;
|
|
13
|
+
/** Secret used to seal the session cookie. At least 32 characters. */
|
|
14
|
+
secret: string;
|
|
15
|
+
/** Absolute redirect URI registered with the OAuth client. */
|
|
16
|
+
redirectUri: string;
|
|
17
|
+
/** Where to send a signed-out user. @default '/' */
|
|
18
|
+
afterSignOutUrl?: string;
|
|
19
|
+
/** Where to send a freshly signed-in user. @default '/' */
|
|
20
|
+
afterSignInUrl?: string;
|
|
21
|
+
/** OAuth scopes. @default 'openid profile email' */
|
|
22
|
+
scope?: string;
|
|
23
|
+
/** Session cookie lifetime in seconds. @default 30 days */
|
|
24
|
+
sessionMaxAge?: number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Resolve config from the environment.
|
|
28
|
+
*
|
|
29
|
+
* The public values are read from `NEXT_PUBLIC_*` so the same names work in
|
|
30
|
+
* both the client provider and the server. `LUMOAUTH_SECRET` and
|
|
31
|
+
* `LUMOAUTH_CLIENT_SECRET` are deliberately NOT public — a `NEXT_PUBLIC_`
|
|
32
|
+
* prefix would inline them into the browser bundle.
|
|
33
|
+
*/
|
|
34
|
+
declare function resolveConfig(overrides?: Partial<LumoAuthNextConfig>): LumoAuthNextConfig;
|
|
35
|
+
|
|
36
|
+
interface AuthObject {
|
|
37
|
+
/** OIDC subject of the signed-in user, or null. */
|
|
38
|
+
userId: string | null;
|
|
39
|
+
/**
|
|
40
|
+
* Whether the user has a live SESSION — not whether the access token is
|
|
41
|
+
* currently fresh. A stale access token with a valid refresh token is still
|
|
42
|
+
* a signed-in user.
|
|
43
|
+
*/
|
|
44
|
+
isSignedIn: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* The access token, or null if it is stale and nothing refreshed it.
|
|
47
|
+
*
|
|
48
|
+
* Returns null rather than refreshing, because a server component cannot
|
|
49
|
+
* persist the result: LumoAuth rotates and revokes refresh tokens on use,
|
|
50
|
+
* so an unpersisted refresh would burn the token and break the session on
|
|
51
|
+
* the very next request. Add `lumoAuthMiddleware()` and the token is always
|
|
52
|
+
* fresh by the time this runs.
|
|
53
|
+
*/
|
|
54
|
+
getToken: () => string | null;
|
|
55
|
+
/** Access-token expiry, epoch milliseconds. */
|
|
56
|
+
expiresAt: number | null;
|
|
57
|
+
/**
|
|
58
|
+
* True when the session is live but the access token needs replacing.
|
|
59
|
+
* Only possible when middleware is not installed on this route.
|
|
60
|
+
*/
|
|
61
|
+
isStale: boolean;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Read the session in a server component, route handler, or server action.
|
|
65
|
+
*
|
|
66
|
+
* Because the session lives in an httpOnly cookie the server can read directly,
|
|
67
|
+
* a page can decide what to render *before* it responds — no client round-trip,
|
|
68
|
+
* and therefore none of the signed-out-then-signed-in flash that a purely
|
|
69
|
+
* client-side provider produces on every load.
|
|
70
|
+
*
|
|
71
|
+
* ```tsx
|
|
72
|
+
* export default async function Page() {
|
|
73
|
+
* const { isSignedIn, userId } = await auth();
|
|
74
|
+
* if (!isSignedIn) redirect('/api/auth/login');
|
|
75
|
+
* return <p>Hello {userId}</p>;
|
|
76
|
+
* }
|
|
77
|
+
* ```
|
|
78
|
+
*
|
|
79
|
+
* The session is trusted because it is sealed with AES-256-GCM using
|
|
80
|
+
* `LUMOAUTH_SECRET`: the browser can neither read nor forge it. This does not
|
|
81
|
+
* re-verify the access token's signature against the issuer's JWKS — the token
|
|
82
|
+
* is only ever accepted here because *we* put it in the cookie after a
|
|
83
|
+
* successful exchange.
|
|
84
|
+
*/
|
|
85
|
+
declare function auth(overrides?: Partial<LumoAuthNextConfig>): Promise<AuthObject>;
|
|
86
|
+
/**
|
|
87
|
+
* The signed-in user's profile, or null.
|
|
88
|
+
*
|
|
89
|
+
* This makes a network call to the OIDC `/userinfo` endpoint on every
|
|
90
|
+
* invocation, so prefer `auth()` when the subject is all you need.
|
|
91
|
+
*/
|
|
92
|
+
declare function currentUser(overrides?: Partial<LumoAuthNextConfig>): Promise<UserInfo | null>;
|
|
93
|
+
/**
|
|
94
|
+
* Redirect signed-out visitors to sign in. Call at the top of a protected
|
|
95
|
+
* server component.
|
|
96
|
+
*
|
|
97
|
+
* ```tsx
|
|
98
|
+
* export default async function Page() {
|
|
99
|
+
* await protectPage();
|
|
100
|
+
* ...
|
|
101
|
+
* }
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
declare function protectPage(opts?: {
|
|
105
|
+
returnTo?: string;
|
|
106
|
+
}): Promise<AuthObject>;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Backend-for-frontend route handlers.
|
|
110
|
+
*
|
|
111
|
+
* Mount once, at `app/api/auth/[...lumoauth]/route.ts`:
|
|
112
|
+
*
|
|
113
|
+
* ```ts
|
|
114
|
+
* import { createRouteHandler } from '@lumoauth/nextjs/server';
|
|
115
|
+
* export const { GET, POST } = createRouteHandler();
|
|
116
|
+
* ```
|
|
117
|
+
*
|
|
118
|
+
* The server owns the whole OAuth exchange, so tokens live in an httpOnly
|
|
119
|
+
* cookie and never reach JavaScript. That is what makes `auth()` work in a
|
|
120
|
+
* server component — and therefore what makes a signed-in page render
|
|
121
|
+
* server-side with no loading flash.
|
|
122
|
+
*/
|
|
123
|
+
type Ctx = {
|
|
124
|
+
params: Promise<{
|
|
125
|
+
lumoauth?: string[];
|
|
126
|
+
}>;
|
|
127
|
+
};
|
|
128
|
+
declare function createRouteHandler(overrides?: Partial<LumoAuthNextConfig>): {
|
|
129
|
+
GET: (request: Request, context: Ctx) => Promise<Response>;
|
|
130
|
+
POST: (request: Request, context: Ctx) => Promise<Response>;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
interface MiddlewareOptions extends Partial<LumoAuthNextConfig> {
|
|
134
|
+
/**
|
|
135
|
+
* Paths requiring a session. Accepts globs (`/dashboard/:path*`), regexes,
|
|
136
|
+
* or a predicate. Everything else is public.
|
|
137
|
+
*/
|
|
138
|
+
protect?: Array<string | RegExp> | ((req: NextRequest) => boolean);
|
|
139
|
+
/**
|
|
140
|
+
* Keep the access token fresh automatically. @default true
|
|
141
|
+
*
|
|
142
|
+
* Turning this off means `auth().getToken()` returns null once the token
|
|
143
|
+
* goes stale, because nothing else in the request pipeline is able to
|
|
144
|
+
* persist a refreshed one.
|
|
145
|
+
*/
|
|
146
|
+
refresh?: boolean;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Session refresh and route protection.
|
|
150
|
+
*
|
|
151
|
+
* ```ts
|
|
152
|
+
* // middleware.ts
|
|
153
|
+
* import { lumoAuthMiddleware } from '@lumoauth/nextjs/server';
|
|
154
|
+
*
|
|
155
|
+
* export default lumoAuthMiddleware({ protect: ['/dashboard/:path*'] });
|
|
156
|
+
* export const config = { matcher: ['/((?!_next|.*\\..*).*)'] };
|
|
157
|
+
* ```
|
|
158
|
+
*
|
|
159
|
+
* ## Why refresh belongs here
|
|
160
|
+
*
|
|
161
|
+
* An access token lasts about an hour; a session lasts weeks. Something has to
|
|
162
|
+
* trade the refresh token for a new access token, and in Next.js that can only
|
|
163
|
+
* happen where cookies are writable: middleware, route handlers, and server
|
|
164
|
+
* actions. Server components cannot set cookies, so they can never persist a
|
|
165
|
+
* refresh.
|
|
166
|
+
*
|
|
167
|
+
* That distinction is not cosmetic. LumoAuth rotates refresh tokens and revokes
|
|
168
|
+
* the old one on use, so refreshing somewhere that cannot persist the result
|
|
169
|
+
* would spend the token and break the session on the next request. Middleware
|
|
170
|
+
* runs before the page renders and can write the response cookie, so it is the
|
|
171
|
+
* correct place.
|
|
172
|
+
*
|
|
173
|
+
* Because middleware writes the cookie on the *response* while the page reads
|
|
174
|
+
* the *request*, the fresh session is also forwarded on a request header that
|
|
175
|
+
* `auth()` prefers — otherwise the refresh would not take effect until the
|
|
176
|
+
* following request.
|
|
177
|
+
*/
|
|
178
|
+
declare function lumoAuthMiddleware(options?: MiddlewareOptions): (req: NextRequest) => Promise<NextResponse<unknown>>;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The server-side session, sealed into an httpOnly cookie.
|
|
182
|
+
*
|
|
183
|
+
* This is the trust boundary for everything else in the package: `auth()`
|
|
184
|
+
* believes what is in here, so it must be unforgeable. The cookie is encrypted
|
|
185
|
+
* AND authenticated with AES-256-GCM, so a client can neither read the tokens
|
|
186
|
+
* nor alter the payload without the auth tag failing.
|
|
187
|
+
*
|
|
188
|
+
* Encrypting rather than merely signing matters because the payload holds the
|
|
189
|
+
* refresh token, which must never be readable by the browser.
|
|
190
|
+
*
|
|
191
|
+
* Implemented with Web Crypto rather than `node:crypto` because these helpers
|
|
192
|
+
* run in three different places: route handlers (Node runtime), `auth()` in a
|
|
193
|
+
* server component (Node), and `lumoAuthMiddleware` (edge runtime, where
|
|
194
|
+
* `node:crypto` does not exist). Web Crypto is the one API present in all of
|
|
195
|
+
* them. The cost is that seal/unseal are async.
|
|
196
|
+
*/
|
|
197
|
+
declare const SESSION_COOKIE = "lumo_session";
|
|
198
|
+
/**
|
|
199
|
+
* Two different lifetimes live in here, and conflating them is the classic
|
|
200
|
+
* bug: an access token lasts ~1 hour, a session lasts weeks.
|
|
201
|
+
*
|
|
202
|
+
* `expiresAt` is when the ACCESS TOKEN goes stale — routine, expected, and
|
|
203
|
+
* fixed by a refresh.
|
|
204
|
+
* `sessionExpiresAt` is when the SESSION itself ends and the user must sign in
|
|
205
|
+
* again.
|
|
206
|
+
*
|
|
207
|
+
* A user whose access token expired five minutes ago is still signed in.
|
|
208
|
+
*/
|
|
209
|
+
interface ServerSession {
|
|
210
|
+
accessToken: string;
|
|
211
|
+
refreshToken: string | null;
|
|
212
|
+
idToken: string | null;
|
|
213
|
+
/** Access-token expiry, epoch milliseconds. */
|
|
214
|
+
expiresAt: number;
|
|
215
|
+
/** Session expiry, epoch milliseconds. Absent on cookies written before this field existed. */
|
|
216
|
+
sessionExpiresAt?: number;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Header used to hand a freshly refreshed session from middleware to the
|
|
220
|
+
* server component rendering the same request.
|
|
221
|
+
*
|
|
222
|
+
* Middleware writes the new cookie on the RESPONSE, but the component reads
|
|
223
|
+
* REQUEST cookies — which still hold the stale value. Without this header the
|
|
224
|
+
* refresh would only take effect on the following request.
|
|
225
|
+
*/
|
|
226
|
+
declare const REFRESHED_SESSION_HEADER = "x-lumo-session";
|
|
227
|
+
/** True when the session itself is still valid, regardless of token staleness. */
|
|
228
|
+
declare function isSessionLive(session: ServerSession | null): session is ServerSession;
|
|
229
|
+
/** True when the access token needs replacing before it can be used. */
|
|
230
|
+
declare function isTokenStale(session: ServerSession): boolean;
|
|
231
|
+
|
|
232
|
+
export { type AuthObject, type LumoAuthNextConfig, type MiddlewareOptions, REFRESHED_SESSION_HEADER, SESSION_COOKIE, type ServerSession, auth, createRouteHandler, currentUser, isSessionLive, isTokenStale, lumoAuthMiddleware, protectPage, resolveConfig };
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/server.ts
|
|
31
|
+
var server_exports = {};
|
|
32
|
+
__export(server_exports, {
|
|
33
|
+
REFRESHED_SESSION_HEADER: () => REFRESHED_SESSION_HEADER,
|
|
34
|
+
SESSION_COOKIE: () => SESSION_COOKIE,
|
|
35
|
+
auth: () => auth,
|
|
36
|
+
createRouteHandler: () => createRouteHandler,
|
|
37
|
+
currentUser: () => currentUser,
|
|
38
|
+
isSessionLive: () => isSessionLive,
|
|
39
|
+
isTokenStale: () => isTokenStale,
|
|
40
|
+
lumoAuthMiddleware: () => lumoAuthMiddleware,
|
|
41
|
+
protectPage: () => protectPage,
|
|
42
|
+
resolveConfig: () => resolveConfig
|
|
43
|
+
});
|
|
44
|
+
module.exports = __toCommonJS(server_exports);
|
|
45
|
+
var import_server_only = require("server-only");
|
|
46
|
+
|
|
47
|
+
// src/auth.ts
|
|
48
|
+
var import_headers = require("next/headers");
|
|
49
|
+
var import_shared = require("@lumoauth/shared");
|
|
50
|
+
|
|
51
|
+
// src/config.ts
|
|
52
|
+
function resolveConfig(overrides = {}) {
|
|
53
|
+
const env = process.env;
|
|
54
|
+
const cfg = {
|
|
55
|
+
domain: overrides.domain ?? env.NEXT_PUBLIC_LUMOAUTH_DOMAIN ?? "",
|
|
56
|
+
orgId: overrides.orgId ?? env.NEXT_PUBLIC_LUMOAUTH_ORG_ID ?? "",
|
|
57
|
+
clientId: overrides.clientId ?? env.NEXT_PUBLIC_LUMOAUTH_CLIENT_ID ?? "",
|
|
58
|
+
clientSecret: overrides.clientSecret ?? env.LUMOAUTH_CLIENT_SECRET,
|
|
59
|
+
secret: overrides.secret ?? env.LUMOAUTH_SECRET ?? "",
|
|
60
|
+
redirectUri: overrides.redirectUri ?? env.NEXT_PUBLIC_REDIRECT_URI ?? "",
|
|
61
|
+
afterSignOutUrl: overrides.afterSignOutUrl ?? "/",
|
|
62
|
+
afterSignInUrl: overrides.afterSignInUrl ?? "/",
|
|
63
|
+
scope: overrides.scope ?? "openid profile email",
|
|
64
|
+
sessionMaxAge: overrides.sessionMaxAge ?? 60 * 60 * 24 * 30
|
|
65
|
+
};
|
|
66
|
+
const missing = ["domain", "orgId", "clientId", "secret", "redirectUri"].filter(
|
|
67
|
+
(k) => !cfg[k]
|
|
68
|
+
);
|
|
69
|
+
if (missing.length) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`@lumoauth/nextjs is missing required config: ${missing.join(", ")}. Set NEXT_PUBLIC_LUMOAUTH_DOMAIN, NEXT_PUBLIC_LUMOAUTH_ORG_ID, NEXT_PUBLIC_LUMOAUTH_CLIENT_ID, NEXT_PUBLIC_REDIRECT_URI and LUMOAUTH_SECRET, or pass them to createRouteHandler({ ... }).`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return cfg;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/session-cookie.ts
|
|
78
|
+
var SESSION_COOKIE = "lumo_session";
|
|
79
|
+
var PKCE_COOKIE = "lumo_pkce";
|
|
80
|
+
var REFRESHED_SESSION_HEADER = "x-lumo-session";
|
|
81
|
+
var REFRESH_WINDOW_MS = 6e4;
|
|
82
|
+
function isSessionLive(session) {
|
|
83
|
+
if (!session) return false;
|
|
84
|
+
if (session.sessionExpiresAt && session.sessionExpiresAt <= Date.now()) return false;
|
|
85
|
+
return !!session.refreshToken || session.expiresAt > Date.now();
|
|
86
|
+
}
|
|
87
|
+
function isTokenStale(session) {
|
|
88
|
+
return session.expiresAt - Date.now() < REFRESH_WINDOW_MS;
|
|
89
|
+
}
|
|
90
|
+
var IV_BYTES = 12;
|
|
91
|
+
function buf(u) {
|
|
92
|
+
return u;
|
|
93
|
+
}
|
|
94
|
+
function b64urlEncode(bytes) {
|
|
95
|
+
let s = "";
|
|
96
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
97
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
98
|
+
}
|
|
99
|
+
function b64urlDecode(text) {
|
|
100
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/");
|
|
101
|
+
const bin = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
102
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
103
|
+
}
|
|
104
|
+
async function importKey(secret) {
|
|
105
|
+
if (!secret || secret.length < 32) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
"LUMOAUTH_SECRET must be set to at least 32 characters. Generate one with: openssl rand -hex 32"
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
const digest = await crypto.subtle.digest("SHA-256", buf(new TextEncoder().encode(secret)));
|
|
111
|
+
return crypto.subtle.importKey("raw", digest, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
112
|
+
}
|
|
113
|
+
async function seal(payload, secret) {
|
|
114
|
+
const key = await importKey(secret);
|
|
115
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
116
|
+
const data = new TextEncoder().encode(JSON.stringify(payload));
|
|
117
|
+
const sealed = new Uint8Array(
|
|
118
|
+
await crypto.subtle.encrypt({ name: "AES-GCM", iv: buf(iv) }, key, buf(data))
|
|
119
|
+
);
|
|
120
|
+
return `${b64urlEncode(iv)}.${b64urlEncode(sealed)}`;
|
|
121
|
+
}
|
|
122
|
+
async function unseal(value, secret) {
|
|
123
|
+
if (!value) return null;
|
|
124
|
+
const parts = value.split(".");
|
|
125
|
+
if (parts.length !== 2) return null;
|
|
126
|
+
try {
|
|
127
|
+
const iv = b64urlDecode(parts[0]);
|
|
128
|
+
const body = b64urlDecode(parts[1]);
|
|
129
|
+
const key = await importKey(secret);
|
|
130
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: buf(iv) }, key, buf(body));
|
|
131
|
+
return JSON.parse(new TextDecoder().decode(plain));
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function cookieOptions(maxAgeSeconds, secure) {
|
|
137
|
+
return {
|
|
138
|
+
httpOnly: true,
|
|
139
|
+
// Lax, not Strict: the OAuth callback is a cross-site top-level
|
|
140
|
+
// navigation back from the identity provider, and Strict would withhold
|
|
141
|
+
// the PKCE cookie exactly then.
|
|
142
|
+
sameSite: "lax",
|
|
143
|
+
secure,
|
|
144
|
+
path: "/",
|
|
145
|
+
maxAge: maxAgeSeconds
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/auth.ts
|
|
150
|
+
var SIGNED_OUT = {
|
|
151
|
+
userId: null,
|
|
152
|
+
isSignedIn: false,
|
|
153
|
+
getToken: () => null,
|
|
154
|
+
expiresAt: null,
|
|
155
|
+
isStale: false
|
|
156
|
+
};
|
|
157
|
+
function decodeSub(accessToken) {
|
|
158
|
+
try {
|
|
159
|
+
const [, payload] = accessToken.split(".");
|
|
160
|
+
const json = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
161
|
+
return typeof json.sub === "string" ? json.sub : null;
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
async function auth(overrides = {}) {
|
|
167
|
+
const cfg = resolveConfig(overrides);
|
|
168
|
+
const hdrs = await (0, import_headers.headers)();
|
|
169
|
+
const fromHeader = await unseal(
|
|
170
|
+
hdrs.get(REFRESHED_SESSION_HEADER) ?? void 0,
|
|
171
|
+
cfg.secret
|
|
172
|
+
);
|
|
173
|
+
const jar = await (0, import_headers.cookies)();
|
|
174
|
+
const session = fromHeader ?? await unseal(jar.get(SESSION_COOKIE)?.value, cfg.secret);
|
|
175
|
+
if (!isSessionLive(session)) return SIGNED_OUT;
|
|
176
|
+
const stale = isTokenStale(session);
|
|
177
|
+
return {
|
|
178
|
+
userId: decodeSub(session.accessToken),
|
|
179
|
+
isSignedIn: true,
|
|
180
|
+
getToken: () => stale ? null : session.accessToken,
|
|
181
|
+
expiresAt: session.expiresAt,
|
|
182
|
+
isStale: stale
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
async function currentUser(overrides = {}) {
|
|
186
|
+
const cfg = resolveConfig(overrides);
|
|
187
|
+
const { getToken, isSignedIn } = await auth(overrides);
|
|
188
|
+
if (!isSignedIn) return null;
|
|
189
|
+
const token = getToken();
|
|
190
|
+
if (!token) return null;
|
|
191
|
+
try {
|
|
192
|
+
const mod = new import_shared.AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });
|
|
193
|
+
return await mod.getUserInfo(token);
|
|
194
|
+
} catch {
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
async function protectPage(opts = {}) {
|
|
199
|
+
const result = await auth();
|
|
200
|
+
if (!result.isSignedIn) {
|
|
201
|
+
const { redirect } = await import("next/navigation");
|
|
202
|
+
const qs = opts.returnTo ? `?return_to=${encodeURIComponent(opts.returnTo)}` : "";
|
|
203
|
+
redirect(`/api/auth/login${qs}`);
|
|
204
|
+
}
|
|
205
|
+
return result;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// src/route-handler.ts
|
|
209
|
+
var import_shared2 = require("@lumoauth/shared");
|
|
210
|
+
function authModule(cfg) {
|
|
211
|
+
return new import_shared2.AuthModule({ baseUrl: cfg.domain, orgId: cfg.orgId, clientId: cfg.clientId });
|
|
212
|
+
}
|
|
213
|
+
function safeReturnTo(raw, fallback) {
|
|
214
|
+
if (!raw) return fallback;
|
|
215
|
+
if (!raw.startsWith("/") || raw.startsWith("//")) return fallback;
|
|
216
|
+
return raw;
|
|
217
|
+
}
|
|
218
|
+
function createRouteHandler(overrides = {}) {
|
|
219
|
+
const getCfg = () => resolveConfig(overrides);
|
|
220
|
+
async function segments(context) {
|
|
221
|
+
const p = await context.params;
|
|
222
|
+
return p?.lumoauth ?? [];
|
|
223
|
+
}
|
|
224
|
+
async function GET(request, context) {
|
|
225
|
+
const cfg = getCfg();
|
|
226
|
+
const action = (await segments(context))[0];
|
|
227
|
+
const url = new URL(request.url);
|
|
228
|
+
const secure = url.protocol === "https:";
|
|
229
|
+
if (action === "login") {
|
|
230
|
+
const codeVerifier = (0, import_shared2.generateCodeVerifier)();
|
|
231
|
+
const state = (0, import_shared2.generateState)();
|
|
232
|
+
const codeChallenge = await (0, import_shared2.generateCodeChallenge)(codeVerifier);
|
|
233
|
+
const authorize = new URL(
|
|
234
|
+
`${cfg.domain.replace(/\/+$/, "")}${(0, import_shared2.buildPath)(import_shared2.ROUTES["oauth.authorize"].path, { orgId: cfg.orgId })}`
|
|
235
|
+
);
|
|
236
|
+
authorize.searchParams.set("response_type", "code");
|
|
237
|
+
authorize.searchParams.set("client_id", cfg.clientId);
|
|
238
|
+
authorize.searchParams.set("redirect_uri", cfg.redirectUri);
|
|
239
|
+
authorize.searchParams.set("scope", cfg.scope);
|
|
240
|
+
authorize.searchParams.set("code_challenge", codeChallenge);
|
|
241
|
+
authorize.searchParams.set("code_challenge_method", "S256");
|
|
242
|
+
authorize.searchParams.set("state", state);
|
|
243
|
+
const pkce = {
|
|
244
|
+
codeVerifier,
|
|
245
|
+
state,
|
|
246
|
+
returnTo: safeReturnTo(url.searchParams.get("return_to"), cfg.afterSignInUrl)
|
|
247
|
+
};
|
|
248
|
+
const res = Response.redirect(authorize.toString(), 302);
|
|
249
|
+
return withCookie(
|
|
250
|
+
res,
|
|
251
|
+
`${PKCE_COOKIE}=${await seal(pkce, cfg.secret)}; ${serialize(cookieOptions(600, secure))}`
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
if (action === "callback") {
|
|
255
|
+
const code = url.searchParams.get("code");
|
|
256
|
+
const returnedState = url.searchParams.get("state");
|
|
257
|
+
const pkce = await unseal(readCookie(request, PKCE_COOKIE), cfg.secret);
|
|
258
|
+
if (!code || !returnedState || !pkce) {
|
|
259
|
+
return redirectTo(url.origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
260
|
+
}
|
|
261
|
+
if (returnedState !== pkce.state) {
|
|
262
|
+
return redirectTo(url.origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
const tokens = await authModule(cfg).exchangeCodeForTokens({
|
|
266
|
+
code,
|
|
267
|
+
codeVerifier: pkce.codeVerifier,
|
|
268
|
+
redirectUri: cfg.redirectUri,
|
|
269
|
+
...cfg.clientSecret ? { clientSecret: cfg.clientSecret } : {}
|
|
270
|
+
});
|
|
271
|
+
const session = {
|
|
272
|
+
accessToken: tokens.access_token,
|
|
273
|
+
refreshToken: tokens.refresh_token ?? null,
|
|
274
|
+
idToken: tokens.id_token ?? null,
|
|
275
|
+
// Access-token expiry: short, refreshed in the background.
|
|
276
|
+
expiresAt: Date.now() + tokens.expires_in * 1e3,
|
|
277
|
+
// Session expiry: long. The user stays signed in until this
|
|
278
|
+
// passes, however many access tokens come and go.
|
|
279
|
+
sessionExpiresAt: Date.now() + cfg.sessionMaxAge * 1e3
|
|
280
|
+
};
|
|
281
|
+
return redirectTo(url.origin + pkce.returnTo, [
|
|
282
|
+
`${SESSION_COOKIE}=${await seal(session, cfg.secret)}; ${serialize(cookieOptions(cfg.sessionMaxAge, secure))}`,
|
|
283
|
+
clearCookie(PKCE_COOKIE, secure)
|
|
284
|
+
]);
|
|
285
|
+
} catch {
|
|
286
|
+
return redirectTo(url.origin + cfg.afterSignOutUrl, [clearCookie(PKCE_COOKIE, secure)]);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (action === "session") {
|
|
290
|
+
const session = await unseal(readCookie(request, SESSION_COOKIE), cfg.secret);
|
|
291
|
+
if (!isSessionLive(session)) {
|
|
292
|
+
return Response.json({ accessToken: null, expiresAt: null });
|
|
293
|
+
}
|
|
294
|
+
return Response.json({
|
|
295
|
+
accessToken: session.accessToken,
|
|
296
|
+
idToken: session.idToken,
|
|
297
|
+
expiresAt: session.expiresAt
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (action === "logout") return doLogout(cfg, url, request, secure);
|
|
301
|
+
return new Response("Not found", { status: 404 });
|
|
302
|
+
}
|
|
303
|
+
async function POST(request, context) {
|
|
304
|
+
const cfg = getCfg();
|
|
305
|
+
const action = (await segments(context))[0];
|
|
306
|
+
const url = new URL(request.url);
|
|
307
|
+
if (action === "logout") return doLogout(cfg, url, request, url.protocol === "https:");
|
|
308
|
+
return new Response("Not found", { status: 404 });
|
|
309
|
+
}
|
|
310
|
+
async function doLogout(cfg, url, request, secure) {
|
|
311
|
+
const session = await unseal(readCookie(request, SESSION_COOKIE), cfg.secret);
|
|
312
|
+
if (session?.accessToken) {
|
|
313
|
+
await authModule(cfg).revokeToken(session.accessToken, session.accessToken).catch(() => {
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
const logout = new URL(
|
|
317
|
+
`${cfg.domain.replace(/\/+$/, "")}${(0, import_shared2.buildPath)(import_shared2.ROUTES["oauth.logout"].path, { orgId: cfg.orgId })}`
|
|
318
|
+
);
|
|
319
|
+
logout.searchParams.set("post_logout_redirect_uri", url.origin + cfg.afterSignOutUrl);
|
|
320
|
+
if (session?.idToken) logout.searchParams.set("id_token_hint", session.idToken);
|
|
321
|
+
return redirectTo(logout.toString(), [clearCookie(SESSION_COOKIE, secure)]);
|
|
322
|
+
}
|
|
323
|
+
return { GET, POST };
|
|
324
|
+
}
|
|
325
|
+
function serialize(o) {
|
|
326
|
+
return [
|
|
327
|
+
`Path=${o.path}`,
|
|
328
|
+
`Max-Age=${o.maxAge}`,
|
|
329
|
+
`SameSite=${o.sameSite === "lax" ? "Lax" : o.sameSite}`,
|
|
330
|
+
o.httpOnly ? "HttpOnly" : "",
|
|
331
|
+
o.secure ? "Secure" : ""
|
|
332
|
+
].filter(Boolean).join("; ");
|
|
333
|
+
}
|
|
334
|
+
function clearCookie(name, secure) {
|
|
335
|
+
return `${name}=; Path=/; Max-Age=0; SameSite=Lax; HttpOnly${secure ? "; Secure" : ""}`;
|
|
336
|
+
}
|
|
337
|
+
function readCookie(request, name) {
|
|
338
|
+
const header = request.headers.get("cookie");
|
|
339
|
+
if (!header) return void 0;
|
|
340
|
+
const hit = header.split("; ").find((c) => c.startsWith(`${name}=`));
|
|
341
|
+
return hit?.slice(name.length + 1);
|
|
342
|
+
}
|
|
343
|
+
function redirectTo(location, cookies2) {
|
|
344
|
+
const headers2 = new Headers({ Location: location });
|
|
345
|
+
cookies2.forEach((c) => headers2.append("Set-Cookie", c));
|
|
346
|
+
return new Response(null, { status: 302, headers: headers2 });
|
|
347
|
+
}
|
|
348
|
+
function withCookie(res, cookie) {
|
|
349
|
+
const headers2 = new Headers(res.headers);
|
|
350
|
+
headers2.append("Set-Cookie", cookie);
|
|
351
|
+
return new Response(res.body, { status: res.status, headers: headers2 });
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// src/middleware.ts
|
|
355
|
+
var import_server = require("next/server");
|
|
356
|
+
var import_shared3 = require("@lumoauth/shared");
|
|
357
|
+
function toMatcher(pattern) {
|
|
358
|
+
if (pattern instanceof RegExp) return pattern;
|
|
359
|
+
const source = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\/:path\*/g, "(?:/.*)?").replace(/\*/g, ".*");
|
|
360
|
+
return new RegExp(`^${source}$`);
|
|
361
|
+
}
|
|
362
|
+
function lumoAuthMiddleware(options = {}) {
|
|
363
|
+
const { protect = [], refresh = true, ...configOverrides } = options;
|
|
364
|
+
return async function middleware(req) {
|
|
365
|
+
const isProtected = typeof protect === "function" ? protect(req) : protect.map(toMatcher).some((m) => m.test(req.nextUrl.pathname));
|
|
366
|
+
const cfg = resolveConfig(configOverrides);
|
|
367
|
+
const rawCookie = req.cookies.get(SESSION_COOKIE)?.value;
|
|
368
|
+
const session = await unseal(rawCookie, cfg.secret);
|
|
369
|
+
if (!isSessionLive(session)) {
|
|
370
|
+
if (!isProtected) {
|
|
371
|
+
if (!rawCookie) return import_server.NextResponse.next();
|
|
372
|
+
const res2 = import_server.NextResponse.next();
|
|
373
|
+
res2.cookies.delete(SESSION_COOKIE);
|
|
374
|
+
return res2;
|
|
375
|
+
}
|
|
376
|
+
const login = new URL("/api/auth/login", req.nextUrl.origin);
|
|
377
|
+
login.searchParams.set("return_to", req.nextUrl.pathname + req.nextUrl.search);
|
|
378
|
+
const res = import_server.NextResponse.redirect(login);
|
|
379
|
+
if (rawCookie) res.cookies.delete(SESSION_COOKIE);
|
|
380
|
+
return res;
|
|
381
|
+
}
|
|
382
|
+
if (!refresh || !isTokenStale(session)) return import_server.NextResponse.next();
|
|
383
|
+
if (!session.refreshToken) {
|
|
384
|
+
if (!isProtected) return import_server.NextResponse.next();
|
|
385
|
+
const login = new URL("/api/auth/login", req.nextUrl.origin);
|
|
386
|
+
login.searchParams.set("return_to", req.nextUrl.pathname + req.nextUrl.search);
|
|
387
|
+
return import_server.NextResponse.redirect(login);
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
const mod = new import_shared3.AuthModule({
|
|
391
|
+
baseUrl: cfg.domain,
|
|
392
|
+
orgId: cfg.orgId,
|
|
393
|
+
clientId: cfg.clientId
|
|
394
|
+
});
|
|
395
|
+
const tokens = await mod.refreshToken(session.refreshToken);
|
|
396
|
+
const next = {
|
|
397
|
+
accessToken: tokens.access_token,
|
|
398
|
+
// Keep the existing token when the server does not rotate;
|
|
399
|
+
// losing it here would silently end the session at the next
|
|
400
|
+
// refresh.
|
|
401
|
+
refreshToken: tokens.refresh_token ?? session.refreshToken,
|
|
402
|
+
idToken: tokens.id_token ?? session.idToken,
|
|
403
|
+
expiresAt: Date.now() + tokens.expires_in * 1e3,
|
|
404
|
+
sessionExpiresAt: session.sessionExpiresAt
|
|
405
|
+
};
|
|
406
|
+
const sealed = await seal(next, cfg.secret);
|
|
407
|
+
const headers2 = new Headers(req.headers);
|
|
408
|
+
headers2.set(REFRESHED_SESSION_HEADER, sealed);
|
|
409
|
+
const res = import_server.NextResponse.next({ request: { headers: headers2 } });
|
|
410
|
+
const opts = cookieOptions(cfg.sessionMaxAge, req.nextUrl.protocol === "https:");
|
|
411
|
+
res.cookies.set(SESSION_COOKIE, sealed, opts);
|
|
412
|
+
return res;
|
|
413
|
+
} catch {
|
|
414
|
+
const res = isProtected ? import_server.NextResponse.redirect(new URL("/api/auth/login", req.nextUrl.origin)) : import_server.NextResponse.next();
|
|
415
|
+
res.cookies.delete(SESSION_COOKIE);
|
|
416
|
+
return res;
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
421
|
+
0 && (module.exports = {
|
|
422
|
+
REFRESHED_SESSION_HEADER,
|
|
423
|
+
SESSION_COOKIE,
|
|
424
|
+
auth,
|
|
425
|
+
createRouteHandler,
|
|
426
|
+
currentUser,
|
|
427
|
+
isSessionLive,
|
|
428
|
+
isTokenStale,
|
|
429
|
+
lumoAuthMiddleware,
|
|
430
|
+
protectPage,
|
|
431
|
+
resolveConfig
|
|
432
|
+
});
|
|
433
|
+
//# sourceMappingURL=server.js.map
|