|
| 1 | +import { createApiError, getAuthLookupForEmail } from '@inkeep/agents-core'; |
| 2 | +import { Hono } from 'hono'; |
| 3 | +import { HTTPException } from 'hono/http-exception'; |
| 4 | +import runDbClient from '../../../data/db/runDbClient'; |
| 5 | +import { getLogger } from '../../../logger'; |
| 6 | +import type { ManageAppVariables } from '../../../types/app'; |
| 7 | + |
| 8 | +const logger = getLogger('auth-lookup'); |
| 9 | + |
| 10 | +const RATE_LIMIT_WINDOW_MS = 60_000; |
| 11 | +const RATE_LIMIT_MAX_REQUESTS = 20; |
| 12 | +const ipRequestTimestamps = new Map<string, number[]>(); |
| 13 | + |
| 14 | +setInterval(() => { |
| 15 | + const cutoff = Date.now() - RATE_LIMIT_WINDOW_MS; |
| 16 | + for (const [ip, timestamps] of ipRequestTimestamps) { |
| 17 | + const recent = timestamps.filter((t) => t > cutoff); |
| 18 | + if (recent.length === 0) { |
| 19 | + ipRequestTimestamps.delete(ip); |
| 20 | + } else { |
| 21 | + ipRequestTimestamps.set(ip, recent); |
| 22 | + } |
| 23 | + } |
| 24 | +}, RATE_LIMIT_WINDOW_MS); |
| 25 | + |
| 26 | +function getClientIp(c: { req: { header: (name: string) => string | undefined } }): string { |
| 27 | + return ( |
| 28 | + c.req.header('x-forwarded-for')?.split(',')[0]?.trim() || c.req.header('x-real-ip') || 'unknown' |
| 29 | + ); |
| 30 | +} |
| 31 | + |
| 32 | +const authLookupRoutes = new Hono<{ Variables: ManageAppVariables }>(); |
| 33 | + |
| 34 | +/** |
| 35 | + * GET /api/auth-lookup?email=user@example.com |
| 36 | + * |
| 37 | + * Unauthenticated endpoint for the email-first login flow. |
| 38 | + * Returns org-aware auth methods: |
| 39 | + * 1. Checks SSO providers by email domain -> resolves org -> returns org's allowed methods (SSO filtered to domain-matched providers) |
| 40 | + * 2. Checks existing user account -> resolves org membership -> returns org's allowed methods (SSO filtered to domain-matched providers) |
| 41 | + * |
| 42 | + * Returns empty organizations array if no match is found. |
| 43 | + * |
| 44 | + * Rate-limited per IP to mitigate email/org enumeration. |
| 45 | + * organizationSlug is intentionally omitted from the response to minimize info disclosure. |
| 46 | + */ |
| 47 | +authLookupRoutes.get('/', async (c) => { |
| 48 | + const clientIp = getClientIp(c); |
| 49 | + const now = Date.now(); |
| 50 | + const timestamps = ipRequestTimestamps.get(clientIp) || []; |
| 51 | + const recent = timestamps.filter((t) => t > now - RATE_LIMIT_WINDOW_MS); |
| 52 | + |
| 53 | + if (recent.length >= RATE_LIMIT_MAX_REQUESTS) { |
| 54 | + logger.warn({ clientIp, count: recent.length }, 'auth-lookup rate limit exceeded'); |
| 55 | + throw createApiError({ |
| 56 | + code: 'too_many_requests', |
| 57 | + message: 'Too many requests. Please try again later.', |
| 58 | + }); |
| 59 | + } |
| 60 | + |
| 61 | + recent.push(now); |
| 62 | + ipRequestTimestamps.set(clientIp, recent); |
| 63 | + |
| 64 | + const email = c.req.query('email'); |
| 65 | + |
| 66 | + if (!email) { |
| 67 | + throw createApiError({ |
| 68 | + code: 'bad_request', |
| 69 | + message: 'Email parameter is required', |
| 70 | + }); |
| 71 | + } |
| 72 | + |
| 73 | + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; |
| 74 | + if (!emailRegex.test(email)) { |
| 75 | + throw createApiError({ |
| 76 | + code: 'bad_request', |
| 77 | + message: 'Invalid email format', |
| 78 | + }); |
| 79 | + } |
| 80 | + |
| 81 | + try { |
| 82 | + const organizations = await getAuthLookupForEmail(runDbClient)(email); |
| 83 | + |
| 84 | + const sanitized = organizations.map(({ organizationSlug: _slug, ...rest }) => rest); |
| 85 | + |
| 86 | + logger.info( |
| 87 | + { clientIp, emailDomain: email.split('@')[1], orgCount: organizations.length }, |
| 88 | + 'auth-lookup completed' |
| 89 | + ); |
| 90 | + |
| 91 | + return c.json({ organizations: sanitized }); |
| 92 | + } catch (error) { |
| 93 | + if (error instanceof HTTPException) { |
| 94 | + throw error; |
| 95 | + } |
| 96 | + |
| 97 | + logger.error({ clientIp, error }, 'auth-lookup failed'); |
| 98 | + throw createApiError({ |
| 99 | + code: 'internal_server_error', |
| 100 | + message: 'Failed to look up authentication method', |
| 101 | + }); |
| 102 | + } |
| 103 | +}); |
| 104 | + |
| 105 | +export default authLookupRoutes; |
0 commit comments