@govcore/middleware 0.1.0 → 0.1.3
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/dist/index.d.ts +7 -5
- package/dist/index.js +63 -92
- package/dist/index.js.map +1 -0
- package/package.json +25 -9
- package/CHANGELOG.md +0 -26
- package/dist/index.d.ts.map +0 -1
- package/src/index.ts +0 -134
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
+
|
|
3
|
+
interface CreateMiddlewareOptions {
|
|
3
4
|
/** Path prefixes reachable without a session. */
|
|
4
5
|
publicPaths?: string[];
|
|
5
6
|
/** Path prefixes that require an instance-level role. */
|
|
@@ -26,7 +27,8 @@ export interface CreateMiddlewareOptions {
|
|
|
26
27
|
* value it can't resolve to a literal (it reports "Unknown identifier" /
|
|
27
28
|
* "Invalid segment configuration export"). Copy the literal inline instead.
|
|
28
29
|
*/
|
|
29
|
-
|
|
30
|
+
declare const defaultMatcher: string[];
|
|
30
31
|
/** Build a Next.js middleware function from GovCore's route-protection rules. */
|
|
31
|
-
|
|
32
|
-
|
|
32
|
+
declare function createMiddleware(opts?: CreateMiddlewareOptions): (req: NextRequest) => Promise<NextResponse>;
|
|
33
|
+
|
|
34
|
+
export { type CreateMiddlewareOptions, createMiddleware, defaultMatcher };
|
package/dist/index.js
CHANGED
|
@@ -1,99 +1,70 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
// pure arithmetic, no DB. The only cross-package import is @govcore/auth's pure
|
|
8
|
-
// `logout-marker` subpath (no next-auth/db pulled in).
|
|
9
|
-
import { getToken } from 'next-auth/jwt';
|
|
10
|
-
import { NextResponse } from 'next/server';
|
|
11
|
-
import { LOGGED_OUT_MARKER_COOKIE, isResurrectedSession } from '@govcore/auth/logout-marker';
|
|
12
|
-
const DEFAULT_PUBLIC_PATHS = ['/login', '/setup', '/error', '/api/auth', '/maintenance'];
|
|
13
|
-
/**
|
|
14
|
-
* Matcher that excludes static assets and the Auth.js endpoints (they manage
|
|
15
|
-
* their own cookies). Provided as the canonical reference value.
|
|
16
|
-
*
|
|
17
|
-
* NOTE: do NOT use this directly in `export const config = { matcher }` — Next.js
|
|
18
|
-
* statically parses the middleware `config` export at build time and rejects any
|
|
19
|
-
* value it can't resolve to a literal (it reports "Unknown identifier" /
|
|
20
|
-
* "Invalid segment configuration export"). Copy the literal inline instead.
|
|
21
|
-
*/
|
|
22
|
-
export const defaultMatcher = ['/((?!_next/static|_next/image|favicon.ico|api/auth).*)'];
|
|
23
|
-
/**
|
|
24
|
-
* Absolute redirect that never echoes the container bind address (#807). Next
|
|
25
|
-
* middleware requires an absolute Location; behind a TLS-terminating proxy the
|
|
26
|
-
* request origin can be `0.0.0.0:3000`, which we rebuild from the forwarded host
|
|
27
|
-
* or NEXT_PUBLIC_APP_URL.
|
|
28
|
-
*/
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { getToken } from "next-auth/jwt";
|
|
3
|
+
import { NextResponse } from "next/server";
|
|
4
|
+
import { LOGGED_OUT_MARKER_COOKIE, isResurrectedSession } from "@govcore/auth/logout-marker";
|
|
5
|
+
var DEFAULT_PUBLIC_PATHS = ["/login", "/setup", "/error", "/api/auth", "/maintenance"];
|
|
6
|
+
var defaultMatcher = ["/((?!_next/static|_next/image|favicon.ico|api/auth).*)"];
|
|
29
7
|
function redirectTo(req, path) {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
}
|
|
41
|
-
catch {
|
|
42
|
-
/* malformed base — fall through */
|
|
43
|
-
}
|
|
44
|
-
}
|
|
8
|
+
const target = new URL(path, req.nextUrl.origin);
|
|
9
|
+
if (target.hostname === "0.0.0.0") {
|
|
10
|
+
const fwdHost = req.headers.get("x-forwarded-host")?.split(",")[0].trim();
|
|
11
|
+
const fwdProto = req.headers.get("x-forwarded-proto")?.split(",")[0].trim();
|
|
12
|
+
const base = fwdHost && !fwdHost.startsWith("0.0.0.0") && `${fwdProto || "https"}://${fwdHost}` || process.env.NEXT_PUBLIC_APP_URL || null;
|
|
13
|
+
if (base) {
|
|
14
|
+
try {
|
|
15
|
+
return NextResponse.redirect(new URL(path, base));
|
|
16
|
+
} catch {
|
|
17
|
+
}
|
|
45
18
|
}
|
|
46
|
-
|
|
19
|
+
}
|
|
20
|
+
return NextResponse.redirect(target);
|
|
47
21
|
}
|
|
48
|
-
/** Read-only session decode — checks both secure and plain cookie salts. */
|
|
49
22
|
async function decodeSession(req, secret) {
|
|
50
|
-
|
|
51
|
-
(await getToken({ req, secret, secureCookie: false, salt: 'authjs.session-token' })));
|
|
23
|
+
return await getToken({ req, secret, secureCookie: true, salt: "__Secure-authjs.session-token" }) ?? await getToken({ req, secret, secureCookie: false, salt: "authjs.session-token" });
|
|
52
24
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
expires: new Date(0),
|
|
80
|
-
path: '/',
|
|
81
|
-
secure: cookie.name.startsWith('__Secure-'),
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
return res;
|
|
86
|
-
}
|
|
87
|
-
if (!token)
|
|
88
|
-
return redirectTo(req, loginPath);
|
|
89
|
-
const maintenanceMode = opts.maintenanceMode ?? process.env.MAINTENANCE_MODE === 'true';
|
|
90
|
-
if (maintenanceMode && token.role !== maintenanceBypassRole) {
|
|
91
|
-
return redirectTo(req, maintenancePath);
|
|
92
|
-
}
|
|
93
|
-
if (instanceOnlyPaths.some((p) => pathname.startsWith(p)) &&
|
|
94
|
-
token.instanceRole !== instanceRole) {
|
|
95
|
-
return redirectTo(req, homePath);
|
|
25
|
+
function createMiddleware(opts = {}) {
|
|
26
|
+
const publicPaths = opts.publicPaths ?? DEFAULT_PUBLIC_PATHS;
|
|
27
|
+
const instanceOnlyPaths = opts.instanceOnlyPaths ?? ["/instance"];
|
|
28
|
+
const instanceRole = opts.instanceRole ?? "instance_admin";
|
|
29
|
+
const maintenanceBypassRole = opts.maintenanceBypassRole ?? "admin";
|
|
30
|
+
const loginPath = opts.loginPath ?? "/login";
|
|
31
|
+
const maintenancePath = opts.maintenancePath ?? "/maintenance";
|
|
32
|
+
const homePath = opts.homePath ?? "/";
|
|
33
|
+
return async function middleware(req) {
|
|
34
|
+
const { pathname } = req.nextUrl;
|
|
35
|
+
const isPublic = publicPaths.some((p) => pathname.startsWith(p));
|
|
36
|
+
const isStatic = pathname.startsWith("/_next") || pathname === "/favicon.ico";
|
|
37
|
+
if (isPublic || isStatic) return NextResponse.next();
|
|
38
|
+
const secret = opts.authSecret ?? process.env.AUTH_SECRET;
|
|
39
|
+
const token = await decodeSession(req, secret);
|
|
40
|
+
const loggedOutMarker = req.cookies.get(LOGGED_OUT_MARKER_COOKIE)?.value;
|
|
41
|
+
if (token && isResurrectedSession(loggedOutMarker, token.iat)) {
|
|
42
|
+
const res = redirectTo(req, loginPath);
|
|
43
|
+
for (const cookie of req.cookies.getAll()) {
|
|
44
|
+
if (cookie.name.includes("authjs.session-token")) {
|
|
45
|
+
res.cookies.set(cookie.name, "", {
|
|
46
|
+
maxAge: 0,
|
|
47
|
+
expires: /* @__PURE__ */ new Date(0),
|
|
48
|
+
path: "/",
|
|
49
|
+
secure: cookie.name.startsWith("__Secure-")
|
|
50
|
+
});
|
|
96
51
|
}
|
|
97
|
-
|
|
98
|
-
|
|
52
|
+
}
|
|
53
|
+
return res;
|
|
54
|
+
}
|
|
55
|
+
if (!token) return redirectTo(req, loginPath);
|
|
56
|
+
const maintenanceMode = opts.maintenanceMode ?? process.env.MAINTENANCE_MODE === "true";
|
|
57
|
+
if (maintenanceMode && token.role !== maintenanceBypassRole) {
|
|
58
|
+
return redirectTo(req, maintenancePath);
|
|
59
|
+
}
|
|
60
|
+
if (instanceOnlyPaths.some((p) => pathname.startsWith(p)) && token.instanceRole !== instanceRole) {
|
|
61
|
+
return redirectTo(req, homePath);
|
|
62
|
+
}
|
|
63
|
+
return NextResponse.next();
|
|
64
|
+
};
|
|
99
65
|
}
|
|
66
|
+
export {
|
|
67
|
+
createMiddleware,
|
|
68
|
+
defaultMatcher
|
|
69
|
+
};
|
|
70
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @govcore/middleware — the edge-safe Next.js route-protection factory.\n//\n// Deliberately NOT next-auth's `auth()` wrapper: that re-issues (rolls) the\n// session cookie on its responses, making the middleware itself a resurrection\n// emitter that fights the #782 guard. `getToken` is a read-only decode — this\n// middleware never writes session cookies (ADR-0003). Edge-safe: token decode +\n// pure arithmetic, no DB. The only cross-package import is @govcore/auth's pure\n// `logout-marker` subpath (no next-auth/db pulled in).\n\nimport { getToken, type JWT } from 'next-auth/jwt'\nimport { NextResponse, type NextRequest } from 'next/server'\nimport { LOGGED_OUT_MARKER_COOKIE, isResurrectedSession } from '@govcore/auth/logout-marker'\n\nexport interface CreateMiddlewareOptions {\n /** Path prefixes reachable without a session. */\n publicPaths?: string[]\n /** Path prefixes that require an instance-level role. */\n instanceOnlyPaths?: string[]\n /** The `instanceRole` value that satisfies instanceOnlyPaths. Default 'instance_admin'. */\n instanceRole?: string\n /** When true, only `maintenanceBypassRole` may pass; everyone else → maintenancePath. */\n maintenanceMode?: boolean\n /** Role allowed through during maintenance. Default 'admin'. */\n maintenanceBypassRole?: string\n loginPath?: string\n maintenancePath?: string\n /** Where instance-only violations are sent. Default '/'. */\n homePath?: string\n /** Auth.js secret. Defaults to process.env.AUTH_SECRET. */\n authSecret?: string\n}\n\nconst DEFAULT_PUBLIC_PATHS = ['/login', '/setup', '/error', '/api/auth', '/maintenance']\n\n/**\n * Matcher that excludes static assets and the Auth.js endpoints (they manage\n * their own cookies). Provided as the canonical reference value.\n *\n * NOTE: do NOT use this directly in `export const config = { matcher }` — Next.js\n * statically parses the middleware `config` export at build time and rejects any\n * value it can't resolve to a literal (it reports \"Unknown identifier\" /\n * \"Invalid segment configuration export\"). Copy the literal inline instead.\n */\nexport const defaultMatcher = ['/((?!_next/static|_next/image|favicon.ico|api/auth).*)']\n\n/**\n * Absolute redirect that never echoes the container bind address (#807). Next\n * middleware requires an absolute Location; behind a TLS-terminating proxy the\n * request origin can be `0.0.0.0:3000`, which we rebuild from the forwarded host\n * or NEXT_PUBLIC_APP_URL.\n */\nfunction redirectTo(req: NextRequest, path: string): NextResponse {\n const target = new URL(path, req.nextUrl.origin)\n if (target.hostname === '0.0.0.0') {\n const fwdHost = req.headers.get('x-forwarded-host')?.split(',')[0].trim()\n const fwdProto = req.headers.get('x-forwarded-proto')?.split(',')[0].trim()\n const base =\n (fwdHost && !fwdHost.startsWith('0.0.0.0') && `${fwdProto || 'https'}://${fwdHost}`) ||\n process.env.NEXT_PUBLIC_APP_URL ||\n null\n if (base) {\n try {\n return NextResponse.redirect(new URL(path, base))\n } catch {\n /* malformed base — fall through */\n }\n }\n }\n return NextResponse.redirect(target)\n}\n\n/** Read-only session decode — checks both secure and plain cookie salts. */\nasync function decodeSession(req: NextRequest, secret: string | undefined): Promise<JWT | null> {\n return (\n (await getToken({ req, secret, secureCookie: true, salt: '__Secure-authjs.session-token' })) ??\n (await getToken({ req, secret, secureCookie: false, salt: 'authjs.session-token' }))\n )\n}\n\n/** Build a Next.js middleware function from GovCore's route-protection rules. */\nexport function createMiddleware(opts: CreateMiddlewareOptions = {}) {\n const publicPaths = opts.publicPaths ?? DEFAULT_PUBLIC_PATHS\n const instanceOnlyPaths = opts.instanceOnlyPaths ?? ['/instance']\n const instanceRole = opts.instanceRole ?? 'instance_admin'\n const maintenanceBypassRole = opts.maintenanceBypassRole ?? 'admin'\n const loginPath = opts.loginPath ?? '/login'\n const maintenancePath = opts.maintenancePath ?? '/maintenance'\n const homePath = opts.homePath ?? '/'\n\n return async function middleware(req: NextRequest): Promise<NextResponse> {\n const { pathname } = req.nextUrl\n\n const isPublic = publicPaths.some((p) => pathname.startsWith(p))\n const isStatic = pathname.startsWith('/_next') || pathname === '/favicon.ico'\n if (isPublic || isStatic) return NextResponse.next()\n\n const secret = opts.authSecret ?? process.env.AUTH_SECRET\n const token = await decodeSession(req, secret)\n\n // #782 — post-logout resurrection guard. Reject (and actively delete) any\n // session token issued before the logged-out marker (plus the guard window).\n const loggedOutMarker = req.cookies.get(LOGGED_OUT_MARKER_COOKIE)?.value\n if (token && isResurrectedSession(loggedOutMarker, token.iat as number | undefined)) {\n const res = redirectTo(req, loginPath)\n for (const cookie of req.cookies.getAll()) {\n if (cookie.name.includes('authjs.session-token')) {\n res.cookies.set(cookie.name, '', {\n maxAge: 0,\n expires: new Date(0),\n path: '/',\n secure: cookie.name.startsWith('__Secure-'),\n })\n }\n }\n return res\n }\n\n if (!token) return redirectTo(req, loginPath)\n\n const maintenanceMode = opts.maintenanceMode ?? process.env.MAINTENANCE_MODE === 'true'\n if (maintenanceMode && token.role !== maintenanceBypassRole) {\n return redirectTo(req, maintenancePath)\n }\n\n if (\n instanceOnlyPaths.some((p) => pathname.startsWith(p)) &&\n token.instanceRole !== instanceRole\n ) {\n return redirectTo(req, homePath)\n }\n\n return NextResponse.next()\n }\n}\n"],"mappings":";AASA,SAAS,gBAA0B;AACnC,SAAS,oBAAsC;AAC/C,SAAS,0BAA0B,4BAA4B;AAqB/D,IAAM,uBAAuB,CAAC,UAAU,UAAU,UAAU,aAAa,cAAc;AAWhF,IAAM,iBAAiB,CAAC,wDAAwD;AAQvF,SAAS,WAAW,KAAkB,MAA4B;AAChE,QAAM,SAAS,IAAI,IAAI,MAAM,IAAI,QAAQ,MAAM;AAC/C,MAAI,OAAO,aAAa,WAAW;AACjC,UAAM,UAAU,IAAI,QAAQ,IAAI,kBAAkB,GAAG,MAAM,GAAG,EAAE,CAAC,EAAE,KAAK;AACxE,UAAM,WAAW,IAAI,QAAQ,IAAI,mBAAmB,GAAG,MAAM,GAAG,EAAE,CAAC,EAAE,KAAK;AAC1E,UAAM,OACH,WAAW,CAAC,QAAQ,WAAW,SAAS,KAAK,GAAG,YAAY,OAAO,MAAM,OAAO,MACjF,QAAQ,IAAI,uBACZ;AACF,QAAI,MAAM;AACR,UAAI;AACF,eAAO,aAAa,SAAS,IAAI,IAAI,MAAM,IAAI,CAAC;AAAA,MAClD,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACA,SAAO,aAAa,SAAS,MAAM;AACrC;AAGA,eAAe,cAAc,KAAkB,QAAiD;AAC9F,SACG,MAAM,SAAS,EAAE,KAAK,QAAQ,cAAc,MAAM,MAAM,gCAAgC,CAAC,KACzF,MAAM,SAAS,EAAE,KAAK,QAAQ,cAAc,OAAO,MAAM,uBAAuB,CAAC;AAEtF;AAGO,SAAS,iBAAiB,OAAgC,CAAC,GAAG;AACnE,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,oBAAoB,KAAK,qBAAqB,CAAC,WAAW;AAChE,QAAM,eAAe,KAAK,gBAAgB;AAC1C,QAAM,wBAAwB,KAAK,yBAAyB;AAC5D,QAAM,YAAY,KAAK,aAAa;AACpC,QAAM,kBAAkB,KAAK,mBAAmB;AAChD,QAAM,WAAW,KAAK,YAAY;AAElC,SAAO,eAAe,WAAW,KAAyC;AACxE,UAAM,EAAE,SAAS,IAAI,IAAI;AAEzB,UAAM,WAAW,YAAY,KAAK,CAAC,MAAM,SAAS,WAAW,CAAC,CAAC;AAC/D,UAAM,WAAW,SAAS,WAAW,QAAQ,KAAK,aAAa;AAC/D,QAAI,YAAY,SAAU,QAAO,aAAa,KAAK;AAEnD,UAAM,SAAS,KAAK,cAAc,QAAQ,IAAI;AAC9C,UAAM,QAAQ,MAAM,cAAc,KAAK,MAAM;AAI7C,UAAM,kBAAkB,IAAI,QAAQ,IAAI,wBAAwB,GAAG;AACnE,QAAI,SAAS,qBAAqB,iBAAiB,MAAM,GAAyB,GAAG;AACnF,YAAM,MAAM,WAAW,KAAK,SAAS;AACrC,iBAAW,UAAU,IAAI,QAAQ,OAAO,GAAG;AACzC,YAAI,OAAO,KAAK,SAAS,sBAAsB,GAAG;AAChD,cAAI,QAAQ,IAAI,OAAO,MAAM,IAAI;AAAA,YAC/B,QAAQ;AAAA,YACR,SAAS,oBAAI,KAAK,CAAC;AAAA,YACnB,MAAM;AAAA,YACN,QAAQ,OAAO,KAAK,WAAW,WAAW;AAAA,UAC5C,CAAC;AAAA,QACH;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,MAAO,QAAO,WAAW,KAAK,SAAS;AAE5C,UAAM,kBAAkB,KAAK,mBAAmB,QAAQ,IAAI,qBAAqB;AACjF,QAAI,mBAAmB,MAAM,SAAS,uBAAuB;AAC3D,aAAO,WAAW,KAAK,eAAe;AAAA,IACxC;AAEA,QACE,kBAAkB,KAAK,CAAC,MAAM,SAAS,WAAW,CAAC,CAAC,KACpD,MAAM,iBAAiB,cACvB;AACA,aAAO,WAAW,KAAK,QAAQ;AAAA,IACjC;AAEA,WAAO,aAAa,KAAK;AAAA,EAC3B;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@govcore/middleware",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Edge-safe Next.js middleware factory: read-only session decode, resurrection guard, instance/maintenance gating",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"main": "./
|
|
7
|
-
"types": "./
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
|
-
"types": "./
|
|
11
|
-
"default": "./
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
12
|
}
|
|
13
13
|
},
|
|
14
14
|
"publishConfig": {
|
|
@@ -16,17 +16,33 @@
|
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"next-auth": "^5.0.0-beta.25",
|
|
19
|
-
"@govcore/auth": "0.1
|
|
19
|
+
"@govcore/auth": "0.3.1"
|
|
20
20
|
},
|
|
21
21
|
"peerDependencies": {
|
|
22
22
|
"next": "^15.0.0"
|
|
23
23
|
},
|
|
24
24
|
"devDependencies": {
|
|
25
25
|
"next": "^15.5.0",
|
|
26
|
-
"typescript": "^5.5.0"
|
|
26
|
+
"typescript": "^5.5.0",
|
|
27
|
+
"tsup": "^8.3.0"
|
|
28
|
+
},
|
|
29
|
+
"module": "./dist/index.js",
|
|
30
|
+
"files": [
|
|
31
|
+
"dist"
|
|
32
|
+
],
|
|
33
|
+
"tsup": {
|
|
34
|
+
"entry": [
|
|
35
|
+
"src/index.ts"
|
|
36
|
+
],
|
|
37
|
+
"format": [
|
|
38
|
+
"esm"
|
|
39
|
+
],
|
|
40
|
+
"dts": true,
|
|
41
|
+
"clean": true,
|
|
42
|
+
"sourcemap": true
|
|
27
43
|
},
|
|
28
44
|
"scripts": {
|
|
29
|
-
"build": "
|
|
30
|
-
"dev": "
|
|
45
|
+
"build": "tsup",
|
|
46
|
+
"dev": "tsup --watch"
|
|
31
47
|
}
|
|
32
48
|
}
|
package/CHANGELOG.md
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
# @govcore/middleware
|
|
2
|
-
|
|
3
|
-
## 0.1.0
|
|
4
|
-
|
|
5
|
-
### Minor Changes
|
|
6
|
-
|
|
7
|
-
- ca7cadb: Phase 3 — route protection and identity.
|
|
8
|
-
|
|
9
|
-
`@govcore/auth`: `createAuth` factory wrapping Auth.js (NextAuth v5) — injected
|
|
10
|
-
OIDC providers + local credentials (bcrypt), the Drizzle adapter over
|
|
11
|
-
`@govcore/schema`, the invite-based SSO provisioning guard, JWT/session callbacks
|
|
12
|
-
that stamp the active org/role from the membership model, login/logout audit, and
|
|
13
|
-
the resurrection-guard marker. Plus `hashPassword`/`verifyPassword`/`validatePassword`
|
|
14
|
-
and an edge-safe `./logout-marker` subpath. GovEA's product-specific per-org
|
|
15
|
-
policy (lockout/session-timeout/password-expiry) is intentionally not included.
|
|
16
|
-
|
|
17
|
-
`@govcore/middleware`: edge-safe `createMiddleware` factory — read-only `getToken`
|
|
18
|
-
decode (never writes cookies, ADR-0003), the #782 post-logout resurrection guard,
|
|
19
|
-
the #807 bind-address-safe redirect, and configurable public/instance-only/
|
|
20
|
-
maintenance gating, plus `defaultMatcher`.
|
|
21
|
-
|
|
22
|
-
### Patch Changes
|
|
23
|
-
|
|
24
|
-
- Updated dependencies [ca7cadb]
|
|
25
|
-
- Updated dependencies [18bed9e]
|
|
26
|
-
- @govcore/auth@0.1.0
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAG5D,MAAM,WAAW,uBAAuB;IACtC,iDAAiD;IACjD,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;IACtB,yDAAyD;IACzD,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAA;IAC5B,2FAA2F;IAC3F,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,yFAAyF;IACzF,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,gEAAgE;IAChE,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,2DAA2D;IAC3D,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAID;;;;;;;;GAQG;AACH,eAAO,MAAM,cAAc,UAA6D,CAAA;AAoCxF,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,IAAI,GAAE,uBAA4B,IAShC,KAAK,WAAW,KAAG,OAAO,CAAC,YAAY,CAAC,CA4C1E"}
|
package/src/index.ts
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
// @govcore/middleware — the edge-safe Next.js route-protection factory.
|
|
2
|
-
//
|
|
3
|
-
// Deliberately NOT next-auth's `auth()` wrapper: that re-issues (rolls) the
|
|
4
|
-
// session cookie on its responses, making the middleware itself a resurrection
|
|
5
|
-
// emitter that fights the #782 guard. `getToken` is a read-only decode — this
|
|
6
|
-
// middleware never writes session cookies (ADR-0003). Edge-safe: token decode +
|
|
7
|
-
// pure arithmetic, no DB. The only cross-package import is @govcore/auth's pure
|
|
8
|
-
// `logout-marker` subpath (no next-auth/db pulled in).
|
|
9
|
-
|
|
10
|
-
import { getToken, type JWT } from 'next-auth/jwt'
|
|
11
|
-
import { NextResponse, type NextRequest } from 'next/server'
|
|
12
|
-
import { LOGGED_OUT_MARKER_COOKIE, isResurrectedSession } from '@govcore/auth/logout-marker'
|
|
13
|
-
|
|
14
|
-
export interface CreateMiddlewareOptions {
|
|
15
|
-
/** Path prefixes reachable without a session. */
|
|
16
|
-
publicPaths?: string[]
|
|
17
|
-
/** Path prefixes that require an instance-level role. */
|
|
18
|
-
instanceOnlyPaths?: string[]
|
|
19
|
-
/** The `instanceRole` value that satisfies instanceOnlyPaths. Default 'instance_admin'. */
|
|
20
|
-
instanceRole?: string
|
|
21
|
-
/** When true, only `maintenanceBypassRole` may pass; everyone else → maintenancePath. */
|
|
22
|
-
maintenanceMode?: boolean
|
|
23
|
-
/** Role allowed through during maintenance. Default 'admin'. */
|
|
24
|
-
maintenanceBypassRole?: string
|
|
25
|
-
loginPath?: string
|
|
26
|
-
maintenancePath?: string
|
|
27
|
-
/** Where instance-only violations are sent. Default '/'. */
|
|
28
|
-
homePath?: string
|
|
29
|
-
/** Auth.js secret. Defaults to process.env.AUTH_SECRET. */
|
|
30
|
-
authSecret?: string
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const DEFAULT_PUBLIC_PATHS = ['/login', '/setup', '/error', '/api/auth', '/maintenance']
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Matcher that excludes static assets and the Auth.js endpoints (they manage
|
|
37
|
-
* their own cookies). Provided as the canonical reference value.
|
|
38
|
-
*
|
|
39
|
-
* NOTE: do NOT use this directly in `export const config = { matcher }` — Next.js
|
|
40
|
-
* statically parses the middleware `config` export at build time and rejects any
|
|
41
|
-
* value it can't resolve to a literal (it reports "Unknown identifier" /
|
|
42
|
-
* "Invalid segment configuration export"). Copy the literal inline instead.
|
|
43
|
-
*/
|
|
44
|
-
export const defaultMatcher = ['/((?!_next/static|_next/image|favicon.ico|api/auth).*)']
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Absolute redirect that never echoes the container bind address (#807). Next
|
|
48
|
-
* middleware requires an absolute Location; behind a TLS-terminating proxy the
|
|
49
|
-
* request origin can be `0.0.0.0:3000`, which we rebuild from the forwarded host
|
|
50
|
-
* or NEXT_PUBLIC_APP_URL.
|
|
51
|
-
*/
|
|
52
|
-
function redirectTo(req: NextRequest, path: string): NextResponse {
|
|
53
|
-
const target = new URL(path, req.nextUrl.origin)
|
|
54
|
-
if (target.hostname === '0.0.0.0') {
|
|
55
|
-
const fwdHost = req.headers.get('x-forwarded-host')?.split(',')[0].trim()
|
|
56
|
-
const fwdProto = req.headers.get('x-forwarded-proto')?.split(',')[0].trim()
|
|
57
|
-
const base =
|
|
58
|
-
(fwdHost && !fwdHost.startsWith('0.0.0.0') && `${fwdProto || 'https'}://${fwdHost}`) ||
|
|
59
|
-
process.env.NEXT_PUBLIC_APP_URL ||
|
|
60
|
-
null
|
|
61
|
-
if (base) {
|
|
62
|
-
try {
|
|
63
|
-
return NextResponse.redirect(new URL(path, base))
|
|
64
|
-
} catch {
|
|
65
|
-
/* malformed base — fall through */
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return NextResponse.redirect(target)
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Read-only session decode — checks both secure and plain cookie salts. */
|
|
73
|
-
async function decodeSession(req: NextRequest, secret: string | undefined): Promise<JWT | null> {
|
|
74
|
-
return (
|
|
75
|
-
(await getToken({ req, secret, secureCookie: true, salt: '__Secure-authjs.session-token' })) ??
|
|
76
|
-
(await getToken({ req, secret, secureCookie: false, salt: 'authjs.session-token' }))
|
|
77
|
-
)
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** Build a Next.js middleware function from GovCore's route-protection rules. */
|
|
81
|
-
export function createMiddleware(opts: CreateMiddlewareOptions = {}) {
|
|
82
|
-
const publicPaths = opts.publicPaths ?? DEFAULT_PUBLIC_PATHS
|
|
83
|
-
const instanceOnlyPaths = opts.instanceOnlyPaths ?? ['/instance']
|
|
84
|
-
const instanceRole = opts.instanceRole ?? 'instance_admin'
|
|
85
|
-
const maintenanceBypassRole = opts.maintenanceBypassRole ?? 'admin'
|
|
86
|
-
const loginPath = opts.loginPath ?? '/login'
|
|
87
|
-
const maintenancePath = opts.maintenancePath ?? '/maintenance'
|
|
88
|
-
const homePath = opts.homePath ?? '/'
|
|
89
|
-
|
|
90
|
-
return async function middleware(req: NextRequest): Promise<NextResponse> {
|
|
91
|
-
const { pathname } = req.nextUrl
|
|
92
|
-
|
|
93
|
-
const isPublic = publicPaths.some((p) => pathname.startsWith(p))
|
|
94
|
-
const isStatic = pathname.startsWith('/_next') || pathname === '/favicon.ico'
|
|
95
|
-
if (isPublic || isStatic) return NextResponse.next()
|
|
96
|
-
|
|
97
|
-
const secret = opts.authSecret ?? process.env.AUTH_SECRET
|
|
98
|
-
const token = await decodeSession(req, secret)
|
|
99
|
-
|
|
100
|
-
// #782 — post-logout resurrection guard. Reject (and actively delete) any
|
|
101
|
-
// session token issued before the logged-out marker (plus the guard window).
|
|
102
|
-
const loggedOutMarker = req.cookies.get(LOGGED_OUT_MARKER_COOKIE)?.value
|
|
103
|
-
if (token && isResurrectedSession(loggedOutMarker, token.iat as number | undefined)) {
|
|
104
|
-
const res = redirectTo(req, loginPath)
|
|
105
|
-
for (const cookie of req.cookies.getAll()) {
|
|
106
|
-
if (cookie.name.includes('authjs.session-token')) {
|
|
107
|
-
res.cookies.set(cookie.name, '', {
|
|
108
|
-
maxAge: 0,
|
|
109
|
-
expires: new Date(0),
|
|
110
|
-
path: '/',
|
|
111
|
-
secure: cookie.name.startsWith('__Secure-'),
|
|
112
|
-
})
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
return res
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
if (!token) return redirectTo(req, loginPath)
|
|
119
|
-
|
|
120
|
-
const maintenanceMode = opts.maintenanceMode ?? process.env.MAINTENANCE_MODE === 'true'
|
|
121
|
-
if (maintenanceMode && token.role !== maintenanceBypassRole) {
|
|
122
|
-
return redirectTo(req, maintenancePath)
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
if (
|
|
126
|
-
instanceOnlyPaths.some((p) => pathname.startsWith(p)) &&
|
|
127
|
-
token.instanceRole !== instanceRole
|
|
128
|
-
) {
|
|
129
|
-
return redirectTo(req, homePath)
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
return NextResponse.next()
|
|
133
|
-
}
|
|
134
|
-
}
|