feat(release): prepare 1.1.0 candidate
This commit is contained in:
parent
5a34f66981
commit
5205dcdfa9
736 changed files with 115667 additions and 12203 deletions
|
|
@ -1,171 +1,238 @@
|
|||
// server/supabase/functions/team-invite/index.ts
|
||||
// 팀 초대 생성 — 이메일 기반 초대 토큰 발급.
|
||||
// 초대 링크는 클라이언트가 이메일로 공유 (추후 Edge Function에서 SMTP/Resend 연동).
|
||||
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { requireUser } from '../_shared/auth.ts'
|
||||
import { corsHeaders, handleCorsPreflightRequest } from '../_shared/cors.ts'
|
||||
import { requireUser, authErrorResponse, type AuthError } from '../_shared/auth.ts'
|
||||
import { createServiceRoleClient } from '../_shared/quota.ts'
|
||||
import {
|
||||
buildInviteEmailHtml,
|
||||
buildInviteUrl,
|
||||
mapTeamRpcError,
|
||||
normalizeSiteOrigin,
|
||||
parseTeamInviteInput,
|
||||
TeamContractError,
|
||||
validateEmailSender,
|
||||
} from '../_shared/team-contract.ts'
|
||||
|
||||
interface InviteRequest {
|
||||
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
|
||||
role?: 'admin' | 'member'
|
||||
token: string
|
||||
role: 'admin' | 'member'
|
||||
expires_at: string
|
||||
duplicate: boolean
|
||||
}
|
||||
|
||||
// @ts-expect-error — Deno 런타임 전역
|
||||
Deno.serve(async (req: Request) => {
|
||||
const preflight = handleCorsPreflightRequest(req)
|
||||
if (preflight) return preflight
|
||||
function jsonResponse(body: Record<string, unknown>, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: JSON_HEADERS })
|
||||
}
|
||||
|
||||
if (req.method !== 'POST') {
|
||||
return new Response(JSON.stringify({ error: 'Method not allowed' }), {
|
||||
status: 405,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||
})
|
||||
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 user = await requireUser(req)
|
||||
const body = (await req.json()) as InviteRequest
|
||||
|
||||
if (!body.team_id || !body.email) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'team_id and email are required' }),
|
||||
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
const serviceClient = createServiceRoleClient()
|
||||
|
||||
// 권한 확인: 요청자가 해당 팀의 owner/admin 인가?
|
||||
const { data: membership } = await serviceClient
|
||||
.from('team_members')
|
||||
.select('role')
|
||||
.eq('team_id', body.team_id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
|
||||
const role = (membership?.role as string | undefined) ?? null
|
||||
if (role !== 'owner' && role !== 'admin') {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'forbidden', message: '팀 owner/admin만 초대할 수 있습니다.' }),
|
||||
{ status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
}
|
||||
|
||||
// 토큰 생성 (service_role RPC)
|
||||
const { data: tokenData, error: tokenErr } = await serviceClient.rpc('generate_invite_token')
|
||||
if (tokenErr || !tokenData) {
|
||||
throw new Error(`토큰 생성 실패: ${tokenErr?.message ?? 'unknown'}`)
|
||||
}
|
||||
const token = tokenData as string
|
||||
|
||||
// 초대 INSERT
|
||||
const { data: invite, error: insertErr } = await serviceClient
|
||||
.from('team_invites')
|
||||
.insert({
|
||||
team_id: body.team_id,
|
||||
invited_by: user.id,
|
||||
email: body.email.toLowerCase().trim(),
|
||||
role: body.role ?? 'member',
|
||||
token
|
||||
})
|
||||
.select('id, token, expires_at')
|
||||
.single()
|
||||
|
||||
if (insertErr || !invite) {
|
||||
throw new Error(`초대 생성 실패: ${insertErr?.message ?? 'unknown'}`)
|
||||
}
|
||||
|
||||
// 초대 링크 구성 (클라이언트에서 이메일로 공유)
|
||||
// @ts-expect-error — Deno.env
|
||||
const siteUrl = Deno.env.get('SITE_URL') ?? 'https://d3ro.dev'
|
||||
const inviteUrl = `${siteUrl}/accept-invite?token=${encodeURIComponent(token)}`
|
||||
|
||||
// Resend API로 이메일 발송 (옵션 — RESEND_API_KEY 설정 시에만)
|
||||
// @ts-expect-error — Deno.env
|
||||
const resendKey = Deno.env.get('RESEND_API_KEY') ?? ''
|
||||
// @ts-expect-error — Deno.env
|
||||
const fromAddress = Deno.env.get('RESEND_FROM') ?? 'D3RO Voice <noreply@d3ro.dev>'
|
||||
let emailSent = false
|
||||
let emailError: string | null = null
|
||||
|
||||
if (resendKey) {
|
||||
try {
|
||||
// 팀 이름 조회 (이메일 본문용)
|
||||
const { data: teamRow } = await serviceClient
|
||||
.from('teams')
|
||||
.select('name')
|
||||
.eq('id', body.team_id)
|
||||
.maybeSingle()
|
||||
const teamName = (teamRow?.name as string | undefined) ?? '팀'
|
||||
|
||||
const inviterEmail = user.email ?? '(알 수 없음)'
|
||||
|
||||
const resendResp = await fetch('https://api.resend.com/emails', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${resendKey}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
from: fromAddress,
|
||||
to: [body.email.toLowerCase().trim()],
|
||||
subject: `${teamName} 팀에 초대되었습니다 — D3RO Voice`,
|
||||
html: `
|
||||
<div style="font-family: system-ui, sans-serif; max-width: 560px; margin: 0 auto; padding: 24px; color: #1a1a1c;">
|
||||
<h1 style="color: #f25b29; font-weight: 300; letter-spacing: -1px;">D3RO VOICE</h1>
|
||||
<p>안녕하세요.</p>
|
||||
<p><strong>${inviterEmail}</strong> 님이 당신을 <strong>${teamName}</strong> 팀(${body.role ?? 'member'})에 초대했습니다.</p>
|
||||
<p style="margin: 32px 0;">
|
||||
<a href="${inviteUrl}"
|
||||
style="display: inline-block; padding: 14px 32px; background: #f25b29; color: #ffffff; text-decoration: none; border-radius: 8px; font-weight: 600;">
|
||||
초대 수락하기
|
||||
</a>
|
||||
</p>
|
||||
<p style="color: #8e8e93; font-size: 13px;">
|
||||
이 초대는 7일 후 만료됩니다. 직접 링크를 복사하려면:
|
||||
</p>
|
||||
<p style="background: #f5f5f7; padding: 12px; border-radius: 6px; font-family: monospace; font-size: 11px; word-break: break-all;">
|
||||
${inviteUrl}
|
||||
</p>
|
||||
<hr style="margin: 32px 0; border: 0; border-top: 1px solid #eee;" />
|
||||
<p style="color: #8e8e93; font-size: 11px;">
|
||||
D3RO Voice — 로컬+클라우드 하이브리드 AI 음성 어시스턴트
|
||||
</p>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
})
|
||||
|
||||
if (resendResp.ok) {
|
||||
emailSent = true
|
||||
} else {
|
||||
emailError = `Resend ${resendResp.status}: ${await resendResp.text()}`
|
||||
}
|
||||
} catch (e) {
|
||||
emailError = e instanceof Error ? e.message : String(e)
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
id: invite.id,
|
||||
url: inviteUrl,
|
||||
expires_at: invite.expires_at,
|
||||
email_sent: emailSent,
|
||||
email_error: emailError
|
||||
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),
|
||||
}),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
)
|
||||
} catch (err) {
|
||||
if (err && typeof err === 'object' && 'status' in err && 'message' in err) {
|
||||
return authErrorResponse(err as AuthError, corsHeaders)
|
||||
}
|
||||
const message = err instanceof Error ? err.message : 'Unknown error'
|
||||
return new Response(JSON.stringify({ error: message }), {
|
||||
status: 500,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue