Bootstrap Foundry Core with project-scoped Google sign-in

This commit is contained in:
2026-11-04 23:35:52 +08:00
commit e482f88600
7 changed files with 447 additions and 0 deletions
+199
View File
@@ -0,0 +1,199 @@
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { createServer } from 'node:http';
import pg from 'pg';
function required(name) {
if (!process.env[name]) throw new Error(`Missing ${name}`);
return process.env[name];
}
const publicOrigin = new URL(required('PUBLIC_ORIGIN'));
if (publicOrigin.protocol !== 'https:' || publicOrigin.href !== publicOrigin.origin + '/') {
throw new Error('PUBLIC_ORIGIN must be an HTTPS origin');
}
const redirectUri = new URL('/auth/google/callback', publicOrigin).href;
const clientId = required('GOOGLE_CLIENT_ID');
const clientSecret = required('GOOGLE_CLIENT_SECRET');
const db = new pg.Pool({ connectionString: required('DATABASE_URL') });
db.on('error', error => console.error('Database pool error', error.code));
const projects = new Map();
for (const [name, value] of Object.entries(JSON.parse(required('FOUNDRY_PROJECTS')))) {
const callback = new URL(value);
const local = callback.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(callback.hostname);
if (!/^[a-z][a-z0-9-]*$/.test(name) || (!local && callback.protocol !== 'https:') ||
callback.username || callback.password || callback.hash) {
throw new Error(`Invalid project configuration: ${name}`);
}
projects.set(name, callback);
}
const randomToken = () => randomBytes(32).toString('base64url');
const digest = value => createHash('sha256').update(value).digest('base64url');
const isToken = value => typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value);
const cookieName = state => `__Host-foundry-oauth-${state}`;
function reply(res, status, payload) {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(payload === undefined ? undefined : JSON.stringify(payload));
}
function redirect(res, destination) {
res.writeHead(302, { Location: destination });
res.end();
}
async function googleJson(url, options) {
const response = await fetch(url, { ...options, redirect: 'error', signal: AbortSignal.timeout(10000) });
if (!response.ok) throw new Error('Google request failed');
return response.json();
}
async function start(res, url, project) {
const challenge = url.searchParams.get('challenge');
if (!isToken(challenge)) return reply(res, 400, { error: 'invalid_challenge' });
const state = randomToken();
const browser = randomToken();
const verifier = randomToken();
await db.query(`
INSERT INTO oauth_attempts VALUES ($1, $2, $3, $4, $5, now() + interval '10 minutes')
`, [digest(state), digest(browser), project, challenge, verifier]);
const google = new URL('https://accounts.google.com/o/oauth2/v2/auth');
google.search = new URLSearchParams({
client_id: clientId, redirect_uri: redirectUri, response_type: 'code',
scope: 'openid email', state, code_challenge: digest(verifier), code_challenge_method: 'S256',
prompt: 'select_account',
});
res.setHeader('Set-Cookie', `${cookieName(state)}=${browser}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=600`);
redirect(res, google.href);
}
async function callback(req, res, url) {
const state = url.searchParams.get('state');
if (!isToken(state)) return reply(res, 400, { error: 'invalid_state' });
const browserCookie = cookieName(state);
const browser = req.headers.cookie?.split(';').map(part => part.trim())
.find(part => part.startsWith(browserCookie + '='))?.slice(browserCookie.length + 1);
if (!isToken(browser)) return reply(res, 400, { error: 'invalid_state' });
const { rows: [attempt] } = await db.query(`
DELETE FROM oauth_attempts
WHERE state_hash = $1 AND browser_hash = $2 AND expires_at > now()
RETURNING project, frontend_challenge, google_verifier
`, [digest(state), digest(browser)]);
if (!attempt || !projects.has(attempt.project)) return reply(res, 400, { error: 'invalid_state' });
res.setHeader('Set-Cookie', `${browserCookie}=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0`);
const destination = new URL(projects.get(attempt.project));
const code = url.searchParams.get('code');
if (!code || url.searchParams.has('error')) {
destination.hash = 'error=google_login_cancelled';
return redirect(res, destination.href);
}
const tokens = await googleJson('https://oauth2.googleapis.com/token', {
method: 'POST',
body: new URLSearchParams({
code, client_id: clientId, client_secret: clientSecret, redirect_uri: redirectUri,
grant_type: 'authorization_code', code_verifier: attempt.google_verifier,
}),
});
if (typeof tokens.access_token !== 'string') throw new Error('Missing Google access token');
const user = await googleJson('https://openidconnect.googleapis.com/v1/userinfo', {
headers: { Authorization: `Bearer ${tokens.access_token}` },
});
if (typeof user.sub !== 'string' || !user.sub) throw new Error('Missing Google subject');
const grant = randomToken();
await db.query(`
WITH account AS (
INSERT INTO project_accounts (project, id, google_subject, email) VALUES ($1, $2, $3, $4)
ON CONFLICT (project, google_subject) DO UPDATE SET email = EXCLUDED.email
RETURNING id
)
INSERT INTO login_grants
SELECT $5, $1, id, $6, now() + interval '1 minute' FROM account
`, [attempt.project, randomUUID(), user.sub, user.email_verified === true ? user.email : null,
digest(grant), attempt.frontend_challenge]);
destination.hash = new URLSearchParams({ code: grant }).toString();
redirect(res, destination.href);
}
async function exchange(req, res, project) {
const code = req.headers['x-foundry-code'];
const verifier = req.headers['x-foundry-verifier'];
if (!isToken(code) || !isToken(verifier)) return reply(res, 400, { error: 'invalid_exchange' });
const session = randomToken();
const { rowCount } = await db.query(`
WITH grant AS (
DELETE FROM login_grants
WHERE token_hash = $1 AND project = $2 AND frontend_challenge = $3 AND expires_at > now()
RETURNING account_id
)
INSERT INTO project_sessions
SELECT $4, $2, account_id, now() + interval '8 hours' FROM grant
`, [digest(code), project, digest(verifier), digest(session)]);
if (!rowCount) return reply(res, 401, { error: 'invalid_grant' });
reply(res, 200, { access_token: session, token_type: 'Bearer', expires_in: 28800 });
}
async function account(req, res, project, action) {
const token = req.headers.authorization?.match(/^Bearer ([A-Za-z0-9_-]{43})$/)?.[1];
if (!token) return reply(res, 401, { error: 'invalid_session' });
const params = [digest(token), project];
if (action === 'logout') {
await db.query('DELETE FROM project_sessions WHERE token_hash = $1 AND project = $2', params);
return reply(res, 204);
}
const { rows: [user] } = await db.query(`
SELECT a.id, a.email FROM project_sessions s
JOIN project_accounts a ON a.project = s.project AND a.id = s.account_id
WHERE s.token_hash = $1 AND s.project = $2 AND s.expires_at > now()
`, params);
if (!user) return reply(res, 401, { error: 'invalid_session' });
reply(res, 200, { project, ...user });
}
async function handle(req, res) {
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Referrer-Policy', 'no-referrer');
const url = new URL(req.url, publicOrigin);
if (req.method === 'GET' && url.pathname === '/healthz') return reply(res, 200, { status: 'ok' });
if (req.method === 'GET' && url.pathname === '/readyz') {
await db.query('SELECT 1 FROM project_accounts LIMIT 1');
return reply(res, 200, { status: 'ready' });
}
if (req.method === 'GET' && url.pathname === '/auth/google/callback') return callback(req, res, url);
const [, project, action] = url.pathname.match(/^\/projects\/([a-z][a-z0-9-]*)\/auth\/(google|exchange|me|logout)$/) ?? [];
const frontend = projects.get(project);
if (!frontend) return reply(res, 404, { error: 'not_found' });
if (action === 'google' && req.method === 'GET') return start(res, url, project);
const origin = req.headers.origin;
res.setHeader('Vary', 'Origin');
if (origin && origin !== frontend.origin) return reply(res, 403, { error: 'origin_denied' });
if (origin) res.setHeader('Access-Control-Allow-Origin', origin);
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'Authorization, X-Foundry-Code, X-Foundry-Verifier');
return reply(res, 204);
}
if (action === 'exchange' && req.method === 'POST') return exchange(req, res, project);
if (action === 'me' && req.method === 'GET') return account(req, res, project, action);
if (action === 'logout' && req.method === 'POST') return account(req, res, project, action);
reply(res, 405, { error: 'method_not_allowed' });
}
createServer((req, res) => {
handle(req, res).catch(error => {
console.error('Request failed', error.code ?? error.name);
if (res.headersSent) return res.destroy();
reply(res, 503, { error: 'service_unavailable' });
});
}).listen(Number(process.env.PORT ?? 8080), process.env.HOST ?? '127.0.0.1');