Initial commit
This commit is contained in:
commit
459e93d314
100 files changed
+26594
No files matched your search
@@ -0,0 +1,59 @@
|
||||
// Outils partagés par les fonctions serveur d'AzuuCine (Deno / Supabase Edge Functions).
|
||||
|
||||
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? ''
|
||||
const ANON_KEY = Deno.env.get('SUPABASE_ANON_KEY') ?? ''
|
||||
|
||||
/** Origines autorisées à appeler les fonctions (ton site), séparées par des virgules. */
|
||||
const ALLOWED = (Deno.env.get('ALLOWED_ORIGINS') ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
export function corsHeaders(req: Request): Record<string, string> {
|
||||
const origin = req.headers.get('Origin') ?? ''
|
||||
const ok = ALLOWED.length === 0 ? /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin) : ALLOWED.includes(origin)
|
||||
return {
|
||||
...(ok ? { 'Access-Control-Allow-Origin': origin } : {}),
|
||||
'Access-Control-Allow-Headers': 'authorization, apikey, content-type',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Max-Age': '600',
|
||||
Vary: 'Origin',
|
||||
}
|
||||
}
|
||||
|
||||
export function json(req: Request, status: number, body: unknown, extra: Record<string, string> = {}): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { ...corsHeaders(req), 'Content-Type': 'application/json; charset=utf-8', 'X-Content-Type-Options': 'nosniff', ...extra },
|
||||
})
|
||||
}
|
||||
|
||||
// Petit cache jeton → utilisateur (évite de revérifier le même jeton à chaque requête)
|
||||
const verified = new Map<string, { id: string; until: number }>()
|
||||
|
||||
/** Vérifie le jeton de connexion auprès de Supabase Auth. Renvoie l'id de l'utilisateur, ou null. */
|
||||
export async function getUserId(req: Request): Promise<string | null> {
|
||||
const auth = req.headers.get('Authorization') ?? ''
|
||||
const token = auth.startsWith('Bearer ') ? auth.slice(7).trim() : ''
|
||||
if (!token || token.length > 4096 || token === ANON_KEY) return null
|
||||
const cached = verified.get(token)
|
||||
if (cached && cached.until > Date.now()) return cached.id
|
||||
const res = await fetch(`${SUPABASE_URL}/auth/v1/user`, { headers: { apikey: ANON_KEY, Authorization: `Bearer ${token}` } })
|
||||
if (!res.ok) return null
|
||||
const user = (await res.json()) as { id?: string }
|
||||
if (typeof user.id !== 'string') return null
|
||||
if (verified.size > 5000) verified.clear()
|
||||
verified.set(token, { id: user.id, until: Date.now() + 60_000 })
|
||||
return user.id
|
||||
}
|
||||
|
||||
// Limite de requêtes par compte (fenêtre glissante, par instance)
|
||||
const hits = new Map<string, number[]>()
|
||||
export function rateLimited(userId: string, max: number, windowMs: number): boolean {
|
||||
const now = Date.now()
|
||||
const list = (hits.get(userId) ?? []).filter((t) => now - t < windowMs)
|
||||
list.push(now)
|
||||
hits.set(userId, list)
|
||||
if (hits.size > 10000) hits.clear()
|
||||
return list.length > max
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Suppression définitive du compte connecté (et de toutes ses données, par cascade).
|
||||
// Utilise la clé « service role », disponible uniquement côté serveur.
|
||||
|
||||
import { corsHeaders, getUserId, json, rateLimited } from '../_shared/auth.ts'
|
||||
|
||||
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? ''
|
||||
const SERVICE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(req) })
|
||||
if (req.method !== 'POST') return json(req, 405, { error: 'method' })
|
||||
|
||||
const userId = await getUserId(req)
|
||||
if (!userId) return json(req, 401, { error: 'auth' })
|
||||
if (rateLimited('delete:' + userId, 3, 60_000)) return json(req, 429, { error: 'rate' })
|
||||
|
||||
let body: { confirm?: unknown } = {}
|
||||
try {
|
||||
body = await req.json()
|
||||
} catch {
|
||||
/* corps vide */
|
||||
}
|
||||
if (body.confirm !== 'SUPPRIMER') return json(req, 400, { error: 'confirm' })
|
||||
|
||||
// Photos de profil et bannières (le stockage n'est pas effacé automatiquement avec le compte)
|
||||
try {
|
||||
const admin = { apikey: SERVICE_KEY, Authorization: `Bearer ${SERVICE_KEY}`, 'Content-Type': 'application/json' }
|
||||
const list = await fetch(`${SUPABASE_URL}/storage/v1/object/list/profile-media`, {
|
||||
method: 'POST',
|
||||
headers: admin,
|
||||
body: JSON.stringify({ prefix: userId, limit: 1000 }),
|
||||
})
|
||||
const files = list.ok ? ((await list.json()) as { name?: string }[]) : []
|
||||
const prefixes = files.filter((f) => typeof f.name === 'string').map((f) => `${userId}/${f.name}`)
|
||||
if (prefixes.length) {
|
||||
await fetch(`${SUPABASE_URL}/storage/v1/object/profile-media`, { method: 'DELETE', headers: admin, body: JSON.stringify({ prefixes }) })
|
||||
}
|
||||
} catch {
|
||||
/* on supprime le compte quand même */
|
||||
}
|
||||
|
||||
const res = await fetch(`${SUPABASE_URL}/auth/v1/admin/users/${encodeURIComponent(userId)}`, {
|
||||
method: 'DELETE',
|
||||
headers: { apikey: SERVICE_KEY, Authorization: `Bearer ${SERVICE_KEY}` },
|
||||
})
|
||||
if (!res.ok) return json(req, 500, { error: 'delete' })
|
||||
return json(req, 200, { ok: true })
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
// Proxy TMDB : l'app appelle cette fonction, qui ajoute TA clé TMDB côté serveur.
|
||||
// La clé est un « secret » Supabase (supabase secrets set TMDB_API_KEY=...) : elle n'est
|
||||
// jamais dans le code, jamais envoyée au navigateur, et seuls les comptes connectés peuvent s'en servir.
|
||||
|
||||
import { corsHeaders, getUserId, json, rateLimited } from '../_shared/auth.ts'
|
||||
|
||||
const TMDB_KEY = Deno.env.get('TMDB_API_KEY') ?? ''
|
||||
|
||||
// Mêmes adresses que dans l'app — tout le reste est refusé
|
||||
const PATHS = /^\/(search\/multi|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?)$/
|
||||
|
||||
// Paramètres autorisés et forme de leur valeur
|
||||
const PARAMS: Record<string, RegExp> = {
|
||||
language: /^(fr-FR|en-US|es-ES|it-IT|de-DE|pt-BR|zh-CN|ja-JP|ko-KR)$/,
|
||||
query: /^[^\u0000-\u001f]{1,100}$/,
|
||||
include_adult: /^false$/,
|
||||
page: /^[1-9]\d?$/,
|
||||
append_to_response: /^(watch\/providers|credits|release_dates)$/,
|
||||
region: /^[A-Z]{2}$/,
|
||||
'release_date.gte': /^\d{4}-\d{2}-\d{2}$/,
|
||||
'release_date.lte': /^\d{4}-\d{2}-\d{2}$/,
|
||||
'air_date.gte': /^\d{4}-\d{2}-\d{2}$/,
|
||||
'air_date.lte': /^\d{4}-\d{2}-\d{2}$/,
|
||||
with_release_type: /^[1-6](\|[1-6]){0,5}$/,
|
||||
sort_by: /^popularity\.desc$/,
|
||||
with_origin_country: /^[A-Z]{2}(\|[A-Z]{2}){0,20}$/,
|
||||
without_genres: /^\d{1,6}(\|\d{1,6}){0,10}$/,
|
||||
}
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(req) })
|
||||
if (req.method !== 'GET') return json(req, 405, { error: 'method' })
|
||||
if (!TMDB_KEY) return json(req, 500, { error: 'TMDB_API_KEY manquante' })
|
||||
|
||||
const userId = await getUserId(req)
|
||||
if (!userId) return json(req, 401, { error: 'auth' })
|
||||
if (rateLimited(userId, 600, 10 * 60_000)) return json(req, 429, { error: 'rate' })
|
||||
|
||||
const url = new URL(req.url)
|
||||
const path = url.searchParams.get('path') ?? ''
|
||||
if (!PATHS.test(path)) return json(req, 400, { error: 'path' })
|
||||
|
||||
const target = new URL('https://api.themoviedb.org/3' + path)
|
||||
for (const [k, v] of url.searchParams) {
|
||||
if (k === 'path') continue
|
||||
const rule = PARAMS[k]
|
||||
if (!rule || !rule.test(v)) return json(req, 400, { error: 'param', name: k.slice(0, 40) })
|
||||
target.searchParams.set(k, v)
|
||||
}
|
||||
// Clé v3 (32 caractères) en paramètre, jeton v4 en en-tête
|
||||
const isBearer = TMDB_KEY.length > 40
|
||||
if (!isBearer) target.searchParams.set('api_key', TMDB_KEY)
|
||||
|
||||
const res = await fetch(target, { headers: isBearer ? { Authorization: `Bearer ${TMDB_KEY}` } : {} })
|
||||
if (!res.ok) return json(req, res.status === 404 ? 404 : 502, { error: 'tmdb', status: res.status })
|
||||
const body = await res.text()
|
||||
if (body.length > 2_000_000) return json(req, 502, { error: 'size' })
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
...corsHeaders(req),
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
// Le navigateur garde la réponse 1 h (moins de requêtes vers TMDB)
|
||||
'Cache-Control': 'private, max-age=3600',
|
||||
},
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user