238 lines
8 KiB
TypeScript
238 lines
8 KiB
TypeScript
import { createClient } from '@supabase/supabase-js'
|
|
import { requireUser } from '../_shared/auth.ts'
|
|
import { corsHeaders, handleCorsPreflightRequest } from '../_shared/cors.ts'
|
|
import { createServiceRoleClient } from '../_shared/quota.ts'
|
|
import {
|
|
buildInviteEmailHtml,
|
|
buildInviteUrl,
|
|
mapTeamRpcError,
|
|
normalizeSiteOrigin,
|
|
parseTeamInviteInput,
|
|
TeamContractError,
|
|
validateEmailSender,
|
|
} from '../_shared/team-contract.ts'
|
|
|
|
const JSON_HEADERS = {
|
|
...corsHeaders,
|
|
'Content-Type': 'application/json',
|
|
'Cache-Control': 'no-store',
|
|
Pragma: 'no-cache',
|
|
}
|
|
const REQUEST_LIMIT_BYTES = 8 * 1024
|
|
const RESEND_TIMEOUT_MS = 10_000
|
|
const PUSH_TIMEOUT_MS = 12_000
|
|
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
|
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,128}$/
|
|
|
|
interface InviteRpcResult {
|
|
id: string
|
|
team_id: string
|
|
email: string
|
|
token: string
|
|
role: 'admin' | 'member'
|
|
expires_at: string
|
|
duplicate: boolean
|
|
}
|
|
|
|
function jsonResponse(body: Record<string, unknown>, status = 200): Response {
|
|
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS })
|
|
}
|
|
|
|
async function readJson(req: Request): Promise<unknown> {
|
|
if (req.headers.get('Content-Type')?.split(';', 1)[0].trim().toLowerCase() !== 'application/json') {
|
|
throw new TeamContractError('unsupported_media_type', 415)
|
|
}
|
|
const declaredLength = Number(req.headers.get('Content-Length') ?? '0')
|
|
if (Number.isFinite(declaredLength) && declaredLength > REQUEST_LIMIT_BYTES) {
|
|
throw new TeamContractError('request_too_large', 413)
|
|
}
|
|
const text = await req.text()
|
|
if (new TextEncoder().encode(text).byteLength > REQUEST_LIMIT_BYTES) {
|
|
throw new TeamContractError('request_too_large', 413)
|
|
}
|
|
try {
|
|
return JSON.parse(text)
|
|
} catch {
|
|
throw new TeamContractError('invalid_json', 400)
|
|
}
|
|
}
|
|
|
|
function createUserClient(req: Request) {
|
|
const url = Deno.env.get('SUPABASE_URL') ?? ''
|
|
const anonKey = Deno.env.get('SUPABASE_ANON_KEY') ?? ''
|
|
const authorization = req.headers.get('Authorization') ?? ''
|
|
return createClient(url, anonKey, {
|
|
auth: { persistSession: false, autoRefreshToken: false },
|
|
global: { headers: { Authorization: authorization } },
|
|
})
|
|
}
|
|
|
|
function normalizeInviteResult(value: unknown): InviteRpcResult {
|
|
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
throw new TeamContractError('invalid_invite_response', 502)
|
|
}
|
|
const row = value as Record<string, unknown>
|
|
if (
|
|
typeof row.id !== 'string'
|
|
|| !UUID_PATTERN.test(row.id)
|
|
|| typeof row.team_id !== 'string'
|
|
|| !UUID_PATTERN.test(row.team_id)
|
|
|| typeof row.email !== 'string'
|
|
|| typeof row.token !== 'string'
|
|
|| !TOKEN_PATTERN.test(row.token)
|
|
|| (row.role !== 'admin' && row.role !== 'member')
|
|
|| typeof row.expires_at !== 'string'
|
|
|| !Number.isFinite(Date.parse(row.expires_at))
|
|
|| typeof row.duplicate !== 'boolean'
|
|
) {
|
|
throw new TeamContractError('invalid_invite_response', 502)
|
|
}
|
|
return row as unknown as InviteRpcResult
|
|
}
|
|
|
|
async function sendInviteEmail(input: {
|
|
recipient: string
|
|
inviterEmail: string
|
|
teamName: string
|
|
role: 'admin' | 'member'
|
|
inviteUrl: string
|
|
}): Promise<{ sent: boolean; error: string | null }> {
|
|
const apiKey = Deno.env.get('RESEND_API_KEY')?.trim() ?? ''
|
|
if (!apiKey) return { sent: false, error: 'email_not_configured' }
|
|
|
|
let from: string
|
|
try {
|
|
from = validateEmailSender(Deno.env.get('RESEND_FROM') ?? '')
|
|
} catch {
|
|
return { sent: false, error: 'email_configuration_invalid' }
|
|
}
|
|
|
|
try {
|
|
const response = await fetch('https://api.resend.com/emails', {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${apiKey}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
from,
|
|
to: [input.recipient],
|
|
subject: 'You were invited to a D3RO Voice team',
|
|
html: buildInviteEmailHtml(input),
|
|
}),
|
|
signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),
|
|
})
|
|
return response.ok
|
|
? { sent: true, error: null }
|
|
: { sent: false, error: 'email_provider_rejected' }
|
|
} catch {
|
|
return { sent: false, error: 'email_provider_unavailable' }
|
|
}
|
|
}
|
|
|
|
async function dispatchInvitePush(req: Request, inviteId: string): Promise<string> {
|
|
const supabaseUrl = Deno.env.get('SUPABASE_URL')?.trim() ?? ''
|
|
const anonKey = Deno.env.get('SUPABASE_ANON_KEY')?.trim() ?? ''
|
|
const authorization = req.headers.get('Authorization') ?? ''
|
|
if (!supabaseUrl || !anonKey || !authorization) return 'push_not_configured'
|
|
|
|
try {
|
|
const endpoint = new URL('/functions/v1/send-push', supabaseUrl)
|
|
if (endpoint.protocol !== 'https:' && endpoint.protocol !== 'http:') {
|
|
return 'push_not_configured'
|
|
}
|
|
const response = await fetch(endpoint, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: authorization,
|
|
apikey: anonKey,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
event_type: 'team.invite.created',
|
|
resource_id: inviteId,
|
|
}),
|
|
signal: AbortSignal.timeout(PUSH_TIMEOUT_MS),
|
|
})
|
|
if (!response.ok) return 'push_unavailable'
|
|
const result = await response.json() as Record<string, unknown>
|
|
if (result.duplicate === true) return 'push_duplicate'
|
|
return typeof result.sent === 'number' && result.sent > 0
|
|
? 'push_sent'
|
|
: 'push_no_registration'
|
|
} catch {
|
|
return 'push_unavailable'
|
|
}
|
|
}
|
|
|
|
Deno.serve(async (req: Request) => {
|
|
const preflight = handleCorsPreflightRequest(req)
|
|
if (preflight) return preflight
|
|
if (req.method !== 'POST') return jsonResponse({ error: 'method_not_allowed' }, 405)
|
|
|
|
try {
|
|
const user = await requireUser(req)
|
|
const input = parseTeamInviteInput(await readJson(req))
|
|
// Validate deployment configuration before the RPC mutates invitation
|
|
// state, otherwise a bad SITE_URL would create an unusable bearer token.
|
|
const siteOrigin = normalizeSiteOrigin(Deno.env.get('SITE_URL'))
|
|
if (!siteOrigin.startsWith('https://')) {
|
|
throw new TeamContractError('site_url_https_required', 503)
|
|
}
|
|
const userClient = createUserClient(req)
|
|
const { data, error } = await userClient.rpc('create_team_invite', {
|
|
target_team_id: input.teamId,
|
|
invited_email: input.email,
|
|
invited_role: input.role,
|
|
})
|
|
if (error) throw mapTeamRpcError('invite', error)
|
|
const invite = normalizeInviteResult(data)
|
|
if (
|
|
invite.team_id !== input.teamId
|
|
|| invite.email.toLowerCase() !== input.email
|
|
|| invite.role !== input.role
|
|
) {
|
|
throw new TeamContractError('invalid_invite_response', 502)
|
|
}
|
|
|
|
const inviteUrl = buildInviteUrl(siteOrigin, invite.token)
|
|
|
|
let email = { sent: false, error: 'duplicate_invite' as string | null }
|
|
let pushStatus = 'push_duplicate'
|
|
if (!invite.duplicate) {
|
|
const serviceClient = createServiceRoleClient()
|
|
const { data: team, error: teamError } = await serviceClient
|
|
.from('teams')
|
|
.select('name')
|
|
.eq('id', invite.team_id)
|
|
.maybeSingle()
|
|
const teamName = !teamError && typeof team?.name === 'string' ? team.name : 'D3RO Voice team'
|
|
email = await sendInviteEmail({
|
|
recipient: input.email,
|
|
inviterEmail: user.email ?? 'A D3RO Voice user',
|
|
teamName,
|
|
role: invite.role,
|
|
inviteUrl,
|
|
})
|
|
pushStatus = await dispatchInvitePush(req, invite.id)
|
|
}
|
|
|
|
return jsonResponse({
|
|
id: invite.id,
|
|
url: inviteUrl,
|
|
expires_at: invite.expires_at,
|
|
email_sent: email.sent,
|
|
email_error: email.error,
|
|
duplicate: invite.duplicate,
|
|
push_status: pushStatus,
|
|
})
|
|
} catch (error) {
|
|
if (error instanceof TeamContractError) {
|
|
return jsonResponse({ error: error.code, message: error.code }, error.status)
|
|
}
|
|
if (error && typeof error === 'object' && 'status' in error && 'message' in error) {
|
|
return jsonResponse({ error: 'unauthorized', message: 'unauthorized' }, 401)
|
|
}
|
|
return jsonResponse({ error: 'team_invite_failed', message: 'team_invite_failed' }, 500)
|
|
}
|
|
})
|