@govcore/middleware 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,26 @@
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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rob Allred
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,32 @@
1
+ import { NextResponse, type NextRequest } from 'next/server';
2
+ export interface CreateMiddlewareOptions {
3
+ /** Path prefixes reachable without a session. */
4
+ publicPaths?: string[];
5
+ /** Path prefixes that require an instance-level role. */
6
+ instanceOnlyPaths?: string[];
7
+ /** The `instanceRole` value that satisfies instanceOnlyPaths. Default 'instance_admin'. */
8
+ instanceRole?: string;
9
+ /** When true, only `maintenanceBypassRole` may pass; everyone else → maintenancePath. */
10
+ maintenanceMode?: boolean;
11
+ /** Role allowed through during maintenance. Default 'admin'. */
12
+ maintenanceBypassRole?: string;
13
+ loginPath?: string;
14
+ maintenancePath?: string;
15
+ /** Where instance-only violations are sent. Default '/'. */
16
+ homePath?: string;
17
+ /** Auth.js secret. Defaults to process.env.AUTH_SECRET. */
18
+ authSecret?: string;
19
+ }
20
+ /**
21
+ * Matcher that excludes static assets and the Auth.js endpoints (they manage
22
+ * their own cookies). Provided as the canonical reference value.
23
+ *
24
+ * NOTE: do NOT use this directly in `export const config = { matcher }` — Next.js
25
+ * statically parses the middleware `config` export at build time and rejects any
26
+ * value it can't resolve to a literal (it reports "Unknown identifier" /
27
+ * "Invalid segment configuration export"). Copy the literal inline instead.
28
+ */
29
+ export declare const defaultMatcher: string[];
30
+ /** Build a Next.js middleware function from GovCore's route-protection rules. */
31
+ export declare function createMiddleware(opts?: CreateMiddlewareOptions): (req: NextRequest) => Promise<NextResponse>;
32
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
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/dist/index.js ADDED
@@ -0,0 +1,99 @@
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
+ 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
+ */
29
+ function redirectTo(req, path) {
30
+ const target = new URL(path, req.nextUrl.origin);
31
+ if (target.hostname === '0.0.0.0') {
32
+ const fwdHost = req.headers.get('x-forwarded-host')?.split(',')[0].trim();
33
+ const fwdProto = req.headers.get('x-forwarded-proto')?.split(',')[0].trim();
34
+ const base = (fwdHost && !fwdHost.startsWith('0.0.0.0') && `${fwdProto || 'https'}://${fwdHost}`) ||
35
+ process.env.NEXT_PUBLIC_APP_URL ||
36
+ null;
37
+ if (base) {
38
+ try {
39
+ return NextResponse.redirect(new URL(path, base));
40
+ }
41
+ catch {
42
+ /* malformed base — fall through */
43
+ }
44
+ }
45
+ }
46
+ return NextResponse.redirect(target);
47
+ }
48
+ /** Read-only session decode — checks both secure and plain cookie salts. */
49
+ async function decodeSession(req, secret) {
50
+ return ((await getToken({ req, secret, secureCookie: true, salt: '__Secure-authjs.session-token' })) ??
51
+ (await getToken({ req, secret, secureCookie: false, salt: 'authjs.session-token' })));
52
+ }
53
+ /** Build a Next.js middleware function from GovCore's route-protection rules. */
54
+ export function createMiddleware(opts = {}) {
55
+ const publicPaths = opts.publicPaths ?? DEFAULT_PUBLIC_PATHS;
56
+ const instanceOnlyPaths = opts.instanceOnlyPaths ?? ['/instance'];
57
+ const instanceRole = opts.instanceRole ?? 'instance_admin';
58
+ const maintenanceBypassRole = opts.maintenanceBypassRole ?? 'admin';
59
+ const loginPath = opts.loginPath ?? '/login';
60
+ const maintenancePath = opts.maintenancePath ?? '/maintenance';
61
+ const homePath = opts.homePath ?? '/';
62
+ return async function middleware(req) {
63
+ const { pathname } = req.nextUrl;
64
+ const isPublic = publicPaths.some((p) => pathname.startsWith(p));
65
+ const isStatic = pathname.startsWith('/_next') || pathname === '/favicon.ico';
66
+ if (isPublic || isStatic)
67
+ return NextResponse.next();
68
+ const secret = opts.authSecret ?? process.env.AUTH_SECRET;
69
+ const token = await decodeSession(req, secret);
70
+ // #782 — post-logout resurrection guard. Reject (and actively delete) any
71
+ // session token issued before the logged-out marker (plus the guard window).
72
+ const loggedOutMarker = req.cookies.get(LOGGED_OUT_MARKER_COOKIE)?.value;
73
+ if (token && isResurrectedSession(loggedOutMarker, token.iat)) {
74
+ const res = redirectTo(req, loginPath);
75
+ for (const cookie of req.cookies.getAll()) {
76
+ if (cookie.name.includes('authjs.session-token')) {
77
+ res.cookies.set(cookie.name, '', {
78
+ maxAge: 0,
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);
96
+ }
97
+ return NextResponse.next();
98
+ };
99
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@govcore/middleware",
3
+ "version": "0.1.0",
4
+ "description": "Edge-safe Next.js middleware factory: read-only session decode, resurrection guard, instance/maintenance gating",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.ts",
11
+ "default": "./src/index.ts"
12
+ }
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "dependencies": {
18
+ "next-auth": "^5.0.0-beta.25",
19
+ "@govcore/auth": "0.1.0"
20
+ },
21
+ "peerDependencies": {
22
+ "next": "^15.0.0"
23
+ },
24
+ "devDependencies": {
25
+ "next": "^15.5.0",
26
+ "typescript": "^5.5.0"
27
+ },
28
+ "scripts": {
29
+ "build": "tsc -p tsconfig.json",
30
+ "dev": "tsc -p tsconfig.json --watch"
31
+ }
32
+ }
package/src/index.ts ADDED
@@ -0,0 +1,134 @@
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
+ }