|
| 1 | +import { Logger } from '@pgpmjs/logger'; |
| 2 | +import type { NextFunction, Request, RequestHandler, Response } from 'express'; |
| 3 | +import type { AuthSettings } from '../types'; |
| 4 | +import './types'; // for Request type |
| 5 | + |
| 6 | +const log = new Logger('cookie'); |
| 7 | + |
| 8 | +/** Default cookie name for session tokens (matches auth.ts). */ |
| 9 | +const SESSION_COOKIE_NAME = 'constructive_session'; |
| 10 | + |
| 11 | +/** Default cookie name for device tokens (long-lived trusted device). */ |
| 12 | +const DEVICE_COOKIE_NAME = 'constructive_device_token'; |
| 13 | + |
| 14 | +/** |
| 15 | + * GraphQL mutation names that return an access_token on success. |
| 16 | + * When cookie auth is enabled, the server sets an HttpOnly session cookie |
| 17 | + * from the access_token in the response payload. |
| 18 | + */ |
| 19 | +const AUTH_MUTATIONS_SIGN_IN = new Set([ |
| 20 | + 'signIn', |
| 21 | + 'signUp', |
| 22 | + 'signInSso', |
| 23 | + 'signUpSso', |
| 24 | + 'signInMagicLink', |
| 25 | + 'signInEmailOtp', |
| 26 | + 'signInSmsOtp', |
| 27 | + 'signInOneTimeToken', |
| 28 | + 'signInCrossOrigin', |
| 29 | + 'completeMfaChallenge', |
| 30 | +]); |
| 31 | + |
| 32 | +/** |
| 33 | + * GraphQL mutation names that should clear the session cookie. |
| 34 | + */ |
| 35 | +const AUTH_MUTATIONS_SIGN_OUT = new Set([ |
| 36 | + 'signOut', |
| 37 | + 'revokeSession', |
| 38 | +]); |
| 39 | + |
| 40 | +/** |
| 41 | + * Attempt to extract the GraphQL operation name from the request body. |
| 42 | + * Works for both JSON and already-parsed bodies. |
| 43 | + */ |
| 44 | +const getOperationName = (req: Request): string | undefined => { |
| 45 | + const body = (req as any).body; |
| 46 | + if (!body) return undefined; |
| 47 | + if (typeof body === 'object' && body.operationName) { |
| 48 | + return body.operationName; |
| 49 | + } |
| 50 | + return undefined; |
| 51 | +}; |
| 52 | + |
| 53 | +/** |
| 54 | + * Build cookie options from AuthSettings. |
| 55 | + * Falls back to secure defaults when settings are missing. |
| 56 | + */ |
| 57 | +const buildCookieOptions = ( |
| 58 | + settings: AuthSettings | undefined, |
| 59 | +): Record<string, unknown> => { |
| 60 | + const secure = settings?.cookieSecure ?? (process.env.NODE_ENV === 'production'); |
| 61 | + const sameSite = (settings?.cookieSamesite ?? 'lax') as 'strict' | 'lax' | 'none'; |
| 62 | + const httpOnly = settings?.cookieHttponly ?? true; |
| 63 | + const path = settings?.cookiePath ?? '/'; |
| 64 | + const domain = settings?.cookieDomain ?? undefined; |
| 65 | + |
| 66 | + const opts: Record<string, unknown> = { |
| 67 | + httpOnly, |
| 68 | + secure, |
| 69 | + sameSite, |
| 70 | + path, |
| 71 | + }; |
| 72 | + if (domain) { |
| 73 | + opts.domain = domain; |
| 74 | + } |
| 75 | + |
| 76 | + // maxAge from settings is an interval string (e.g. "7 days"). |
| 77 | + // Express cookie maxAge is in milliseconds. We parse common interval formats. |
| 78 | + const maxAgeStr = settings?.cookieMaxAge; |
| 79 | + if (maxAgeStr) { |
| 80 | + const ms = parseIntervalToMs(maxAgeStr); |
| 81 | + if (ms > 0) { |
| 82 | + opts.maxAge = ms; |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + return opts; |
| 87 | +}; |
| 88 | + |
| 89 | +/** |
| 90 | + * Parse a PostgreSQL interval string (e.g. "7 days", "24 hours", "30 minutes") |
| 91 | + * into milliseconds. Supports common auth-relevant durations. |
| 92 | + */ |
| 93 | +const parseIntervalToMs = (interval: string): number => { |
| 94 | + const normalized = interval.trim().toLowerCase(); |
| 95 | + |
| 96 | + // Try numeric-only (assume seconds) |
| 97 | + const numOnly = Number(normalized); |
| 98 | + if (!isNaN(numOnly) && numOnly > 0) { |
| 99 | + return numOnly * 1000; |
| 100 | + } |
| 101 | + |
| 102 | + // Match patterns like "7 days", "24 hours", "30 minutes", "1 year" |
| 103 | + const match = normalized.match(/^(\d+)\s*(second|minute|hour|day|week|month|year)s?$/); |
| 104 | + if (!match) return 0; |
| 105 | + |
| 106 | + const value = parseInt(match[1], 10); |
| 107 | + const unit = match[2]; |
| 108 | + |
| 109 | + const multipliers: Record<string, number> = { |
| 110 | + second: 1000, |
| 111 | + minute: 60 * 1000, |
| 112 | + hour: 60 * 60 * 1000, |
| 113 | + day: 24 * 60 * 60 * 1000, |
| 114 | + week: 7 * 24 * 60 * 60 * 1000, |
| 115 | + month: 30 * 24 * 60 * 60 * 1000, |
| 116 | + year: 365 * 24 * 60 * 60 * 1000, |
| 117 | + }; |
| 118 | + |
| 119 | + return value * (multipliers[unit] || 0); |
| 120 | +}; |
| 121 | + |
| 122 | +/** |
| 123 | + * Extract the access_token from a GraphQL JSON response body. |
| 124 | + * Auth mutations return { data: { mutationName: { accessToken: "..." } } } |
| 125 | + * PostGraphile camelCases the output columns, so we look for accessToken. |
| 126 | + */ |
| 127 | +const extractAccessToken = (body: any, operationName: string): string | undefined => { |
| 128 | + if (!body?.data) return undefined; |
| 129 | + |
| 130 | + // The mutation result is nested under the camelCase mutation name |
| 131 | + const mutationResult = body.data[operationName]; |
| 132 | + if (!mutationResult) return undefined; |
| 133 | + |
| 134 | + // PostGraphile wraps in { result: { ... } } for function mutations |
| 135 | + const result = mutationResult.result ?? mutationResult; |
| 136 | + |
| 137 | + // Look for access_token or accessToken in the result |
| 138 | + return result?.accessToken ?? result?.access_token ?? undefined; |
| 139 | +}; |
| 140 | + |
| 141 | +/** |
| 142 | + * Extract device_id from a GraphQL JSON response body. |
| 143 | + * Sign-in mutations may return a device_id when device tracking is enabled. |
| 144 | + */ |
| 145 | +const extractDeviceId = (body: any, operationName: string): string | undefined => { |
| 146 | + if (!body?.data) return undefined; |
| 147 | + const mutationResult = body.data[operationName]; |
| 148 | + if (!mutationResult) return undefined; |
| 149 | + const result = mutationResult.result ?? mutationResult; |
| 150 | + return result?.deviceId ?? result?.device_id ?? undefined; |
| 151 | +}; |
| 152 | + |
| 153 | +/** |
| 154 | + * Creates the cookie lifecycle middleware. |
| 155 | + * |
| 156 | + * When `enable_cookie_auth` is true in app_auth_settings: |
| 157 | + * - On sign-in/sign-up mutations: intercepts the response and sets an HttpOnly |
| 158 | + * session cookie from the returned access_token. |
| 159 | + * - On sign-out/revoke mutations: clears the session cookie. |
| 160 | + * - On sign-in with device tracking: sets a long-lived device token cookie. |
| 161 | + * |
| 162 | + * When `enable_cookie_auth` is false (default): this middleware is a no-op. |
| 163 | + * Bearer token authentication continues to work regardless of this setting. |
| 164 | + */ |
| 165 | +export const createCookieMiddleware = (): RequestHandler => { |
| 166 | + return (req: Request, res: Response, next: NextFunction): void => { |
| 167 | + const authSettings = req.api?.authSettings; |
| 168 | + |
| 169 | + // Skip if cookie auth is not enabled |
| 170 | + if (!authSettings?.enableCookieAuth) { |
| 171 | + return next(); |
| 172 | + } |
| 173 | + |
| 174 | + const opName = getOperationName(req); |
| 175 | + if (!opName) { |
| 176 | + return next(); |
| 177 | + } |
| 178 | + |
| 179 | + // Sign-out: clear session cookie before passing through |
| 180 | + if (AUTH_MUTATIONS_SIGN_OUT.has(opName)) { |
| 181 | + const cookieOpts = buildCookieOptions(authSettings); |
| 182 | + res.clearCookie(SESSION_COOKIE_NAME, cookieOpts); |
| 183 | + log.info(`[cookie] Cleared session cookie for operation=${opName}`); |
| 184 | + return next(); |
| 185 | + } |
| 186 | + |
| 187 | + // Sign-in: intercept the response to set session cookie |
| 188 | + if (AUTH_MUTATIONS_SIGN_IN.has(opName)) { |
| 189 | + // Monkey-patch res.json to intercept the GraphQL response |
| 190 | + const originalJson = res.json.bind(res); |
| 191 | + res.json = (body: any) => { |
| 192 | + try { |
| 193 | + const accessToken = extractAccessToken(body, opName); |
| 194 | + if (accessToken) { |
| 195 | + const cookieOpts = buildCookieOptions(authSettings); |
| 196 | + res.cookie(SESSION_COOKIE_NAME, accessToken, cookieOpts); |
| 197 | + log.info(`[cookie] Set session cookie for operation=${opName}`); |
| 198 | + } |
| 199 | + |
| 200 | + // Also handle device token cookie |
| 201 | + const deviceId = extractDeviceId(body, opName); |
| 202 | + if (deviceId) { |
| 203 | + const deviceCookieOpts = buildCookieOptions(authSettings); |
| 204 | + // Device tokens are long-lived (90 days default) |
| 205 | + deviceCookieOpts.maxAge = 90 * 24 * 60 * 60 * 1000; |
| 206 | + res.cookie(DEVICE_COOKIE_NAME, deviceId, deviceCookieOpts); |
| 207 | + log.info(`[cookie] Set device token cookie for operation=${opName}`); |
| 208 | + } |
| 209 | + } catch (e: any) { |
| 210 | + log.error(`[cookie] Error processing response for ${opName}:`, e.message); |
| 211 | + } |
| 212 | + |
| 213 | + return originalJson(body); |
| 214 | + }; |
| 215 | + } |
| 216 | + |
| 217 | + next(); |
| 218 | + }; |
| 219 | +}; |
0 commit comments