Files
OpenMAIC/middleware.ts
T
c071e02d83 feat: ACCESS_CODE site-level authentication (#407) (#411)
* feat(access-code): add status API endpoint

Returns whether ACCESS_CODE is enabled and whether the current user is
authenticated via cookie, to support the frontend access gate.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(access-code): add verify API endpoint

Creates POST /api/access-code/verify that validates ACCESS_CODE env var
and sets an HttpOnly 7-day cookie on success.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(access-code): add Next.js middleware to gate API routes

Intercepts all requests when ACCESS_CODE env var is set. API routes
return 401 without the openmaic_access cookie; page requests pass
through so the frontend can render the access-code modal.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(i18n): add accessCode translations for all 4 locales

Add accessCode top-level key to en-US, zh-CN, ja-JP, and ru-RU locale
files with title, placeholder, submit, and error strings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: add ACCESS_CODE documentation to .env.example

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: add AccessCodeGuard component and integrate into root layout

Wraps page children with an access-code gate that checks /api/access-code/status on mount and renders AccessCodeModal when authentication is required.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(access-code): add AccessCodeModal component

Adds the modal dialog component that prompts users for an access code,
using existing Dialog/Button/Input UI components and i18n translation keys.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(access-code): fix lint error and format files

- Fix useEffect setState pattern in access-code-guard.tsx
- Format middleware.ts and layout.tsx with Prettier

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* style(access-code): redesign modal as full-screen gate

Replace generic Radix Dialog with a custom full-screen gate:
- Mesh gradient background with noise texture
- Frosted glass card with backdrop-blur
- Staggered motion animations on mount
- Inline submit button inside input field
- Success state animation before dismissal
- Proper dark mode support

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(access-code): address code review findings

Critical:
- Middleware now validates HMAC-signed cookie tokens, not just existence
- Verify endpoint uses timingSafeEqual for constant-time comparison
- Cookie value is now `timestamp.HMAC(ACCESS_CODE, timestamp)` instead of UUID

Important:
- Middleware 401 response includes `errorCode` matching apiError shape
- Status endpoint uses apiSuccess wrapper for consistency
- Remove unused `accessCode.submit` i18n key from all 4 locales

Suggestions:
- Guard renders children during loading (overlay on top, not blocking)
- Network error defaults to enabled=true (safer than silently disabling)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(access-code): use Web Crypto API in middleware for Edge Runtime

Node.js crypto module is not available in Next.js Edge Runtime.
Replace createHmac/timingSafeEqual with crypto.subtle HMAC and
manual constant-length XOR comparison.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com>
2026-04-12 22:14:14 +08:00

78 lines
2.3 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
/** Convert string to Uint8Array */
function encode(str: string): Uint8Array {
return new TextEncoder().encode(str);
}
/** Convert ArrayBuffer to hex string */
function bufToHex(buf: ArrayBuffer): string {
return Array.from(new Uint8Array(buf))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
/** Verify an HMAC-signed token using Web Crypto API (Edge-compatible) */
async function verifyToken(token: string, accessCode: string): Promise<boolean> {
const dotIndex = token.indexOf('.');
if (dotIndex === -1) return false;
const timestamp = token.substring(0, dotIndex);
const signature = token.substring(dotIndex + 1);
const keyData = encode(accessCode);
const key = await crypto.subtle.importKey(
'raw',
keyData.buffer as ArrayBuffer,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign'],
);
const data = encode(timestamp);
const expected = bufToHex(await crypto.subtle.sign('HMAC', key, data.buffer as ArrayBuffer));
// Constant-length comparison (not truly constant-time in JS, but sufficient here)
if (signature.length !== expected.length) return false;
let mismatch = 0;
for (let i = 0; i < signature.length; i++) {
mismatch |= signature.charCodeAt(i) ^ expected.charCodeAt(i);
}
return mismatch === 0;
}
export async function middleware(request: NextRequest) {
const accessCode = process.env.ACCESS_CODE;
if (!accessCode) {
return NextResponse.next();
}
const { pathname } = request.nextUrl;
// Whitelist: access-code endpoints, health check
if (pathname.startsWith('/api/access-code/') || pathname === '/api/health') {
return NextResponse.next();
}
// Check cookie — validate HMAC signature, not just existence
const cookie = request.cookies.get('openmaic_access');
if (cookie?.value && (await verifyToken(cookie.value, accessCode))) {
return NextResponse.next();
}
// API requests without valid cookie → 401
if (pathname.startsWith('/api/')) {
return NextResponse.json(
{ success: false, errorCode: 'INVALID_REQUEST', error: 'Access code required' },
{ status: 401 },
);
}
// Page requests → let through, frontend shows modal
return NextResponse.next();
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|logos/).*)'],
};