Implement Auth0 migration

This commit is contained in:
gpt-engineer-app[bot]
2025-11-01 01:08:11 +00:00
parent 858320cd03
commit b2bf9a6e20
17 changed files with 1430 additions and 7 deletions

View File

@@ -0,0 +1,71 @@
/**
* Auth0 JWT Verification Utility
*
* Provides JWT verification using Auth0 JWKS
*/
import { jwtVerify, createRemoteJWKSet, JWTPayload } from 'jose';
const AUTH0_DOMAIN = Deno.env.get('AUTH0_DOMAIN') || '';
const AUTH0_CLIENT_ID = Deno.env.get('AUTH0_CLIENT_ID') || '';
/**
* Extended JWT payload with Auth0-specific claims
*/
export interface Auth0JWTPayload extends JWTPayload {
sub: string;
email?: string;
email_verified?: boolean;
name?: string;
picture?: string;
'https://thrillwiki.com/roles'?: string[];
amr?: string[]; // Authentication Methods Reference (includes 'mfa' if MFA verified)
}
/**
* Verify Auth0 JWT token using JWKS
*/
export async function verifyAuth0Token(token: string): Promise<Auth0JWTPayload> {
try {
if (!AUTH0_DOMAIN || !AUTH0_CLIENT_ID) {
throw new Error('Auth0 configuration missing');
}
// Create JWKS fetcher
const JWKS = createRemoteJWKSet(
new URL(`https://${AUTH0_DOMAIN}/.well-known/jwks.json`)
);
// Verify token
const { payload } = await jwtVerify(token, JWKS, {
issuer: `https://${AUTH0_DOMAIN}/`,
audience: AUTH0_CLIENT_ID,
});
return payload as Auth0JWTPayload;
} catch (error) {
console.error('[Auth0JWT] Verification failed:', error);
throw new Error('Invalid Auth0 token');
}
}
/**
* Extract roles from Auth0 JWT payload
*/
export function extractRoles(payload: Auth0JWTPayload): string[] {
return payload['https://thrillwiki.com/roles'] || [];
}
/**
* Check if user has verified MFA
*/
export function hasMFA(payload: Auth0JWTPayload): boolean {
return payload.amr?.includes('mfa') || false;
}
/**
* Extract user ID (sub) from payload
*/
export function getUserId(payload: Auth0JWTPayload): string {
return payload.sub;
}

View File

@@ -0,0 +1,114 @@
/**
* Auth0 Get Management Token Edge Function
*
* Obtains Auth0 Management API access tokens for admin operations
*/
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { verifyAuth0Token, extractRoles } from '../_shared/auth0Jwt.ts';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
// In-memory cache for management token
let cachedToken: string | null = null;
let tokenExpiry: number = 0;
serve(async (req) => {
// Handle CORS preflight
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
try {
// Verify user is authenticated
const authHeader = req.headers.get('authorization');
if (!authHeader) {
throw new Error('Missing authorization header');
}
const token = authHeader.replace('Bearer ', '');
const payload = await verifyAuth0Token(token);
// Check if user has admin/moderator role
const roles = extractRoles(payload);
const isAuthorized = roles.some(role =>
['admin', 'moderator', 'superuser'].includes(role)
);
if (!isAuthorized) {
return new Response(
JSON.stringify({ error: 'Unauthorized - admin role required' }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 403,
}
);
}
// Check if cached token is still valid (5 min buffer)
const now = Date.now() / 1000;
if (cachedToken && tokenExpiry > now + 300) {
return new Response(
JSON.stringify({
access_token: cachedToken,
token_type: 'Bearer',
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
}
// Get new management token
const AUTH0_DOMAIN = Deno.env.get('AUTH0_DOMAIN')!;
const M2M_CLIENT_ID = Deno.env.get('AUTH0_M2M_CLIENT_ID')!;
const M2M_CLIENT_SECRET = Deno.env.get('AUTH0_M2M_CLIENT_SECRET')!;
const response = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: M2M_CLIENT_ID,
client_secret: M2M_CLIENT_SECRET,
audience: `https://${AUTH0_DOMAIN}/api/v2/`,
grant_type: 'client_credentials',
}),
});
if (!response.ok) {
throw new Error('Failed to get management token');
}
const data = await response.json();
// Cache the token
cachedToken = data.access_token;
tokenExpiry = now + data.expires_in;
return new Response(
JSON.stringify({
access_token: data.access_token,
token_type: data.token_type,
expires_in: data.expires_in,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error) {
console.error('[Auth0ManagementToken] Error:', error);
return new Response(
JSON.stringify({ error: error.message }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
}
);
}
});

View File

@@ -0,0 +1,105 @@
/**
* Auth0 Get Roles Edge Function
*
* Fetches user roles for authorization checks
*/
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { verifyAuth0Token, getUserId, extractRoles } from '../_shared/auth0Jwt.ts';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
// Handle CORS preflight
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
try {
// Get Auth0 token from Authorization header
const authHeader = req.headers.get('authorization');
if (!authHeader) {
throw new Error('Missing authorization header');
}
const token = authHeader.replace('Bearer ', '');
const payload = await verifyAuth0Token(token);
const auth0Sub = getUserId(payload);
// Try to get roles from JWT first
const jwtRoles = extractRoles(payload);
// Create Supabase client
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);
// Get profile by auth0_sub
const { data: profile, error: profileError } = await supabase
.from('profiles')
.select('id')
.eq('auth0_sub', auth0Sub)
.single();
if (profileError || !profile) {
// Return JWT roles if profile not found
return new Response(
JSON.stringify({
success: true,
roles: jwtRoles,
source: 'jwt',
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
}
// Fetch roles from database
const { data: dbRoles, error: rolesError } = await supabase
.from('user_roles')
.select('role')
.eq('user_id', profile.id);
if (rolesError) {
throw rolesError;
}
const roles = dbRoles?.map(r => r.role) || [];
// Also fetch permissions
const { data: permissions } = await supabase
.rpc('get_user_management_permissions', { _user_id: profile.id });
return new Response(
JSON.stringify({
success: true,
roles,
permissions,
source: 'database',
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error) {
console.error('[Auth0GetRoles] Error:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
}
);
}
});

View File

@@ -0,0 +1,158 @@
/**
* Auth0 User Sync Edge Function
*
* Syncs Auth0 user data to Supabase profiles table after authentication
*/
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { verifyAuth0Token, getUserId } from '../_shared/auth0Jwt.ts';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
serve(async (req) => {
// Handle CORS preflight
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
try {
// Get Auth0 token from Authorization header
const authHeader = req.headers.get('authorization');
if (!authHeader) {
throw new Error('Missing authorization header');
}
const token = authHeader.replace('Bearer ', '');
const payload = await verifyAuth0Token(token);
const auth0Sub = getUserId(payload);
// Parse request body
const { email, name, picture, email_verified } = await req.json();
// Create Supabase admin client
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);
// Check if profile exists by auth0_sub
const { data: existingProfile } = await supabase
.from('profiles')
.select('id, username, email, auth0_sub')
.eq('auth0_sub', auth0Sub)
.single();
let profile;
if (existingProfile) {
// Update existing profile
const { data, error } = await supabase
.from('profiles')
.update({
email: email || existingProfile.email,
avatar_url: picture || existingProfile.avatar_url,
updated_at: new Date().toISOString(),
})
.eq('auth0_sub', auth0Sub)
.select()
.single();
if (error) throw error;
profile = data;
} else {
// Check if profile exists by email (migration case)
const { data: emailProfile } = await supabase
.from('profiles')
.select('id, username, email')
.eq('email', email)
.is('auth0_sub', null)
.single();
if (emailProfile) {
// Link existing Supabase account to Auth0
const { data, error } = await supabase
.from('profiles')
.update({
auth0_sub: auth0Sub,
avatar_url: picture || emailProfile.avatar_url,
updated_at: new Date().toISOString(),
})
.eq('id', emailProfile.id)
.select()
.single();
if (error) throw error;
profile = data;
} else {
// Create new profile
const username = email.split('@')[0] + '_' + Math.random().toString(36).substring(7);
const { data, error } = await supabase
.from('profiles')
.insert({
auth0_sub: auth0Sub,
email: email,
username: username,
display_name: name || username,
avatar_url: picture,
email_verified: email_verified || false,
})
.select()
.single();
if (error) throw error;
profile = data;
}
}
// Log sync to auth0_sync_log
await supabase
.from('auth0_sync_log')
.insert({
auth0_sub: auth0Sub,
user_id: profile.id,
sync_status: 'success',
user_data: { email, name, picture },
});
// Fetch user roles
const { data: roles } = await supabase
.from('user_roles')
.select('role')
.eq('user_id', profile.id);
return new Response(
JSON.stringify({
success: true,
profile: {
id: profile.id,
auth0_sub: profile.auth0_sub,
username: profile.username,
email: profile.email,
avatar_url: profile.avatar_url,
roles: roles?.map(r => r.role) || [],
},
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error) {
console.error('[Auth0Sync] Error:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
}
);
}
});

View File

@@ -0,0 +1,154 @@
/**
* Auth0 Webhook Edge Function
*
* Handles Auth0 webhook events for real-time sync
*/
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { createHmac } from 'https://deno.land/std@0.168.0/node/crypto.ts';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, x-auth0-signature',
};
/**
* Verify Auth0 webhook signature
*/
function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean {
const hmac = createHmac('sha256', secret);
hmac.update(payload);
const expectedSignature = hmac.digest('hex');
return signature === expectedSignature;
}
serve(async (req) => {
// Handle CORS preflight
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
try {
// Get webhook secret
const WEBHOOK_SECRET = Deno.env.get('AUTH0_WEBHOOK_SECRET');
if (!WEBHOOK_SECRET) {
throw new Error('Webhook secret not configured');
}
// Verify signature
const signature = req.headers.get('x-auth0-signature');
const body = await req.text();
if (signature && !verifyWebhookSignature(body, signature, WEBHOOK_SECRET)) {
return new Response(
JSON.stringify({ error: 'Invalid signature' }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 401,
}
);
}
const event = JSON.parse(body);
const { type, data } = event;
// Create Supabase admin client
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);
// Handle different event types
switch (type) {
case 'post-login': {
// Update last login timestamp
const auth0Sub = data.user?.user_id;
if (auth0Sub) {
await supabase
.from('profiles')
.update({ updated_at: new Date().toISOString() })
.eq('auth0_sub', auth0Sub);
// Log to audit log
await supabase.rpc('log_admin_action', {
p_user_id: null,
p_action: 'auth0_login',
p_details: { auth0_sub: auth0Sub, event_type: 'post-login' },
});
}
break;
}
case 'post-change-password': {
// Log password change
const auth0Sub = data.user?.user_id;
if (auth0Sub) {
await supabase.rpc('log_admin_action', {
p_user_id: null,
p_action: 'password_changed',
p_details: { auth0_sub: auth0Sub, event_type: 'post-change-password' },
});
}
break;
}
case 'post-user-registration': {
// Create initial profile if doesn't exist
const auth0Sub = data.user?.user_id;
const email = data.user?.email;
if (auth0Sub && email) {
const { data: existing } = await supabase
.from('profiles')
.select('id')
.eq('auth0_sub', auth0Sub)
.single();
if (!existing) {
const username = email.split('@')[0] + '_' + Math.random().toString(36).substring(7);
await supabase
.from('profiles')
.insert({
auth0_sub: auth0Sub,
email: email,
username: username,
display_name: data.user?.name || username,
});
}
}
break;
}
default:
console.log('[Auth0Webhook] Unhandled event type:', type);
}
// Log webhook event
await supabase
.from('auth0_sync_log')
.insert({
auth0_sub: data.user?.user_id || 'unknown',
sync_status: 'success',
user_data: { event_type: type, data },
});
return new Response(
JSON.stringify({ success: true }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error) {
console.error('[Auth0Webhook] Error:', error);
return new Response(
JSON.stringify({ error: error.message }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
);
}
});