Open History to see the last commit
1import { handleAuthRequest, parseSetCookies, serializeSetCookie } from '@neon/auth/server';
2import { z } from 'zod';
3import { ApiError, type User } from '@glow/contracts';
4import { transaction } from './database.ts';
5import { config, required } from './config.ts';
6
7const neonUserSchema = z.object({ id: z.string().min(1), email: z.email(), emailVerified: z.literal(true), name: z.string() });
8type NeonUser = z.infer<typeof neonUserSchema>;
9export function allowedEmail(email: string, domains: string[], emails: string[]): boolean {
10 const normalized = email.trim().toLowerCase();
11 if (!z.email().safeParse(normalized).success) return false;
12 return emails.some(value => value.trim().toLowerCase() === normalized)
13 || domains.some(value => value.trim().toLowerCase() === normalized.split('@')[1]);
14}
15
16export async function resolveGlowUser(identity: NeonUser): Promise<User> {
17 const { data } = await transaction(async client => {
18 const email = identity.email.toLowerCase();
19 await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [`identity:${email}`]);
20 const bound = await client.query('SELECT u.id,u.email,u.name FROM glow_auth_identities i JOIN "user" u ON u.id=i.user_id WHERE i.neon_user_id=$1', [identity.id]);
21 if (bound.rows[0]) {
22 if (bound.rows[0].email.toLowerCase() !== email) throw new ApiError(403, 'This account email changed. Contact the app owner.');
23 return bound.rows[0] as User;
24 }
25 const existing = await client.query('SELECT id,email,name FROM "user" WHERE lower(email)=$1', [email]);
26 const user: User = existing.rows[0] ?? { id: identity.id, email, name: identity.name || email.split('@')[0] };
27 const previous = await client.query('SELECT neon_user_id FROM glow_auth_identities WHERE user_id=$1', [user.id]);
28 if (previous.rows[0]) throw new ApiError(403, 'This Glow account is already linked to another identity.');
29 if (!existing.rows[0]) await client.query('INSERT INTO "user"(id,name,email,"emailVerified","createdAt","updatedAt") VALUES($1,$2,$3,true,now(),now())', [user.id, user.name, email]);
30 await client.query('INSERT INTO glow_auth_identities(neon_user_id,user_id) VALUES($1,$2)', [identity.id, user.id]);
31 return user;
32 });
33 return data;
34}
35
36interface AuthGatewayOptions {
37 baseUrl: string; webUrl: string; webOrigins?: string[]; domains: string[]; emails: string[];
38 resolveUser: (user: NeonUser) => Promise<User>;
39 proxy?: (request: Request, path: string) => Promise<Response>;
40}
41export function createAuthGateway(options: AuthGatewayOptions) {
42 const proxy = options.proxy ?? ((request, path) => handleAuthRequest(options.baseUrl, request, path));
43 function verifiedUser(input: unknown) {
44 const result = neonUserSchema.safeParse(input);
45 if (!result.success) throw new ApiError(403, 'Verify your email with a sign-in code to continue.');
46 if (!allowedEmail(result.data.email, options.domains, options.emails)) throw new ApiError(403, 'Use your Databricks email address to sign in.');
47 return result.data;
48 }
49 return {
50 api: { async getSession({ headers }: { headers: Headers }) {
51 const upstreamHeaders = new Headers({ Origin: options.webUrl });
52 if (headers.get('cookie')) upstreamHeaders.set('cookie', headers.get('cookie')!);
53 const response = await proxy(new Request(`${options.webUrl}/api/auth/get-session`, { headers: upstreamHeaders }), 'get-session');
54 if (!response.ok) {
55 if ([401, 403].includes(response.status)) return null;
56 throw new ApiError(503, 'Sign-in is temporarily unavailable. Try again.');
57 }
58 const data = await response.json();
59 if (!data?.user || !data.session) return null;
60 return { ...data, user: await options.resolveUser(verifiedUser(data.user)) };
61 } },
62 async handler(request: Request): Promise<Response> {
63 const path = new URL(request.url).pathname.replace(/^\/api\/auth\//, '');
64 const route = `${request.method} ${path}`;
65 if (!['GET get-session', 'POST sign-out', 'POST email-otp/send-verification-otp', 'POST sign-in/email-otp'].includes(route)) {
66 return Response.json({ message: 'Use an email sign-in code.' }, { status: 404 });
67 }
68 const headers = new Headers(request.headers);
69 const origin = headers.get('origin');
70 if (request.method === 'POST' && origin && !(options.webOrigins ?? [options.webUrl]).includes(origin)) return Response.json({ message: 'Invalid sign-in origin.' }, { status: 403 });
71 headers.set('origin', options.webUrl);
72 let body: string | undefined;
73 if (path === 'email-otp/send-verification-otp' || path === 'sign-in/email-otp') {
74 const input = z.object({ email: z.string().trim().toLowerCase().pipe(z.email()), otp: z.string().regex(/^\d{6}$/).optional(), type: z.literal('sign-in').optional() }).parse(await request.json());
75 if (!allowedEmail(input.email, options.domains, options.emails)) return Response.json({ message: 'Use your Databricks email address to sign in.' }, { status: 403 });
76 if (path === 'sign-in/email-otp' && !input.otp) return Response.json({ message: 'Enter the six-digit code from your email.' }, { status: 400 });
77 body = JSON.stringify(path === 'sign-in/email-otp' ? { email: input.email, otp: input.otp } : { email: input.email, type: 'sign-in' });
78 } else if (request.method === 'POST') body = '{}';
79 const response = await proxy(new Request(request.url, { method: request.method, headers, body }), path);
80 const result = await response.json();
81 if (response.ok && result?.user) {
82 result.user = await options.resolveUser(verifiedUser(result.user));
83 if (result.session) result.session.userId = result.user.id;
84 }
85 const output = new Headers({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
86 for (const name of ['set-auth-jwt', 'retry-after']) {
87 const value = response.headers.get(name); if (value) output.set(name, value);
88 }
89 for (const cookie of response.headers.getSetCookie()) {
90 for (const parsed of parseSetCookies(cookie)) output.append('Set-Cookie', serializeSetCookie({ ...parsed, domain: undefined, partitioned: undefined, path: '/', sameSite: 'lax', httpOnly: true, secure: true }));
91 }
92 return Response.json(result, { status: response.status, headers: output });
93 },
94 };
95}
96
97let instance: ReturnType<typeof createAuthGateway> | undefined;
98export function auth() {
99 return instance ??= createAuthGateway({
100 baseUrl: required('NEON_AUTH_BASE_URL'), webUrl: config().webUrl, webOrigins: config().webOrigins,
101 domains: (process.env.GLOW_SIGNIN_DOMAINS ?? 'databricks.com').split(','),
102 emails: (process.env.GLOW_SIGNUP_ALLOWLIST ?? '').split(','), resolveUser: resolveGlowUser,
103 });
104}