@mindfulauth/core 2.0.0-beta.5 → 2.0.0-beta.6

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.
@@ -1,108 +0,0 @@
1
- // Global middleware for session validation
2
- // Runs before all route handlers to enforce authentication
3
- //
4
- // ASTRO 6 MIGRATION:
5
- // - Astro v6 removed context.locals.runtime.env. Env vars now import from 'cloudflare:workers'.
6
- // - cloudflare:workers is marked external in astro.config.vite.ssr to avoid esbuild scan errors.
7
- // - Dev mode bypass uses import.meta.env.DEV (build-time constant: true in dev, false in prod).
8
- import { defineMiddleware } from 'astro:middleware';
9
- import { env } from 'cloudflare:workers';
10
- import { PUBLIC_ROUTES, PUBLIC_PREFIXES, GET_SECURITY_HEADERS, GET_SKIP_ASSETS } from './config';
11
- import { sanitizePath } from './security';
12
- import { validateSession, validateMemberIdInUrl } from './auth';
13
- /** Check if a path is a public route (no auth required) */
14
- function isPublicRoute(pathname) {
15
- return PUBLIC_ROUTES.includes(pathname) ||
16
- PUBLIC_PREFIXES.some((prefix) => pathname.startsWith(prefix));
17
- }
18
- /** Add security headers to a response */
19
- // NOTE: In Cloudflare Workers, Response.headers is immutable.
20
- // We must create a new Response with a fresh Headers object instead of mutating.
21
- // CSP for script-src/style-src is handled by Astro 6's native security.csp (via <meta> tag).
22
- function addSecurityHeaders(response) {
23
- const newHeaders = new Headers(response.headers);
24
- Object.entries(GET_SECURITY_HEADERS()).forEach(([key, value]) => {
25
- newHeaders.set(key, value);
26
- });
27
- return new Response(response.body, {
28
- status: response.status,
29
- statusText: response.statusText,
30
- headers: newHeaders,
31
- });
32
- }
33
- // Main middleware function
34
- export const onRequest = defineMiddleware(async (context, next) => {
35
- const { request, url, redirect, locals } = context;
36
- const pathname = url.pathname;
37
- // Redirect HTTP to HTTPS (skip in dev mode and localhost)
38
- if (!import.meta.env.DEV && url.protocol === 'http:' && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') {
39
- const httpsUrl = url.toString().replace('http://', 'https://');
40
- return redirect(httpsUrl, 307);
41
- }
42
- // Skip middleware for static assets FIRST (before dev mode)
43
- if (GET_SKIP_ASSETS().includes(pathname)) {
44
- return next();
45
- }
46
- // DEV MODE: Skip auth
47
- // import.meta.env.DEV is a build-time constant replaced by Vite:
48
- // - true during local dev (never included in prod build)
49
- // - false in production builds (tree-shaken out entirely)
50
- // Localhost auth is skipped because Mindful Auth blocks localhost requests.
51
- if (import.meta.env.DEV) {
52
- // Check if public route first
53
- if (isPublicRoute(pathname)) {
54
- locals.recordId = null;
55
- return next();
56
- }
57
- // For protected routes, extract or create mock recordId
58
- // Match memberid with trailing slash
59
- const match = pathname.match(/^\/([a-zA-Z0-9-]+)(?:\/|$)/);
60
- locals.recordId = match ? match[1] : 'dev-user-123';
61
- return next();
62
- }
63
- // PREVIEW MODE: Skip auth (for testing without Mindful Auth on localhost)
64
- // npm run preview builds the project first, so import.meta.env.DEV is false.
65
- // We need a runtime check for localhost to simulate auth in preview.
66
- if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {
67
- if (isPublicRoute(pathname)) {
68
- locals.recordId = null;
69
- return addSecurityHeaders(await next());
70
- }
71
- const match = pathname.match(/^\/([a-zA-Z0-9-]+)(?:\/|$)/);
72
- locals.recordId = match ? match[1] : 'preview-user-123';
73
- return addSecurityHeaders(await next());
74
- }
75
- // Sanitize path
76
- const safePath = sanitizePath(pathname);
77
- if (!safePath) {
78
- return new Response('Bad Request', { status: 400 });
79
- }
80
- // Public routes - no auth needed
81
- if (isPublicRoute(safePath)) {
82
- locals.recordId = null;
83
- return addSecurityHeaders(await next());
84
- }
85
- // Protected route - validate session
86
- // ASTRO 6 CHANGE: Environment variables are accessed directly from 'cloudflare:workers' env,
87
- // not from context.locals.runtime.env (which was removed).
88
- const internalApiKey = env.INTERNAL_API_KEY || import.meta.env.INTERNAL_API_KEY;
89
- if (!internalApiKey) {
90
- console.error('[middleware] CRITICAL: INTERNAL_API_KEY not configured');
91
- return new Response('Internal Server Error', { status: 500 });
92
- }
93
- // URL must have memberid
94
- if (!validateMemberIdInUrl(safePath, null).valid) {
95
- return new Response('Forbidden: URL must include memberid', { status: 403 });
96
- }
97
- // Validate session
98
- const session = await validateSession(request, url.hostname, safePath, internalApiKey);
99
- if (!session.valid) {
100
- return redirect('/login');
101
- }
102
- // Validate memberid matches session
103
- if (!validateMemberIdInUrl(safePath, session.recordId).valid) {
104
- return new Response('Forbidden: Invalid user ID in URL', { status: 403 });
105
- }
106
- locals.recordId = session.recordId;
107
- return addSecurityHeaders(await next());
108
- });
@@ -1,5 +0,0 @@
1
- /** Sanitize endpoint path (prevents ../ traversal and encoded variants) */
2
- export declare function sanitizeEndpoint(endpoint: string): string | null;
3
- /** Sanitize URL path (prevents ../ traversal and encoded variants) */
4
- export declare function sanitizePath(pathname: string): string | null;
5
- //# sourceMappingURL=security.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"security.d.ts","sourceRoot":"","sources":["../src/security.ts"],"names":[],"mappings":"AAkBA,2EAA2E;AAC3E,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAIhE;AAED,sEAAsE;AACtE,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI5D"}
package/dist/security.js DELETED
@@ -1,31 +0,0 @@
1
- // Security utilities - path traversal prevention
2
- const MAX_PATH_LENGTH = 2048;
3
- /** Decode and check for traversal attacks */
4
- function decodeAndValidate(str) {
5
- if (!str || typeof str !== 'string' || str.length > MAX_PATH_LENGTH)
6
- return null;
7
- try {
8
- let decoded = decodeURIComponent(str);
9
- // Catch double-encoded traversal attempts
10
- if (decoded.includes('%'))
11
- decoded = decodeURIComponent(decoded);
12
- return decoded;
13
- }
14
- catch {
15
- return null;
16
- }
17
- }
18
- /** Sanitize endpoint path (prevents ../ traversal and encoded variants) */
19
- export function sanitizeEndpoint(endpoint) {
20
- const decoded = decodeAndValidate(endpoint);
21
- if (!decoded || decoded.includes('..') || decoded.includes('\\'))
22
- return null;
23
- return decoded;
24
- }
25
- /** Sanitize URL path (prevents ../ traversal and encoded variants) */
26
- export function sanitizePath(pathname) {
27
- const decoded = decodeAndValidate(pathname);
28
- if (!decoded || decoded.includes('..') || decoded.includes('\\'))
29
- return null;
30
- return decoded;
31
- }
package/dist/types.d.ts DELETED
@@ -1,22 +0,0 @@
1
- import type { MiddlewareHandler } from 'astro';
2
- export interface MindfulAuthLocals {
3
- recordId: string | null;
4
- runtime?: {
5
- env?: {
6
- INTERNAL_API_KEY?: string;
7
- };
8
- };
9
- }
10
- declare global {
11
- namespace App {
12
- interface Locals extends MindfulAuthLocals {
13
- }
14
- }
15
- }
16
- export interface SessionValidationResult {
17
- valid: boolean;
18
- reason?: string;
19
- recordId?: string;
20
- }
21
- export type MindfulAuthMiddleware = MiddlewareHandler;
22
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,OAAO,CAAC;AAG/C,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,OAAO,CAAC,EAAE;QACR,GAAG,CAAC,EAAE;YACJ,gBAAgB,CAAC,EAAE,MAAM,CAAC;SAC3B,CAAC;KACH,CAAC;CACH;AAGD,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,GAAG,CAAC;QACZ,UAAU,MAAO,SAAQ,iBAAiB;SAAG;KAC9C;CACF;AAED,MAAM,WAAW,uBAAuB;IACtC,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,MAAM,qBAAqB,GAAG,iBAAiB,CAAC"}
package/dist/types.js DELETED
@@ -1,2 +0,0 @@
1
- // Type definitions for Mindful Auth
2
- export {};