Supabase Edge Functions Reference Architecture
This document is the authoritative engineering specification for Debelu's serverless Edge Functions running on the Supabase Deno runtime. Grounded directly in [supabase/functions/deno.json](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/supabase/functions/deno.json), [paystack-webhook/index.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/supabase/functions/paystack-webhook/index.ts), [deliver-notification/index.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/supabase/functions/deliver-notification/index.ts), and [create-user/index.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/supabase/functions/create-user/index.ts), this specification details the event pipelines, cryptographic webhook validations, multi-channel notification dispatchers, and testing protocols.
1. System Overview & Runtime Architecture
Supabase Edge Functions operate as globally distributed, low-latency Deno serverless functions executing on V8 isolates at the edge. They serve as autonomous event gateways and webhook consumers, offloading external integrations from the primary Node.js Express backend.
graph TD
subgraph ExternalGateways [External Event Sources]
Paystack[Paystack Payment Gateway]
DBTrigger[PostgreSQL Database Trigger / pg_net]
AuthHook[Supabase GoTrue Auth Hook]
end
subgraph SupabaseEdge [Supabase Deno Edge Runtime]
PW["paystack-webhook<br/>HMAC SHA-512 Verification & Escrow Activation"]
DN["deliver-notification<br/>Multi-Channel Dispatch: Email, Push, WhatsApp"]
CU["create-user<br/>Profile Provisioning & Referral Assignment"]
Shared["_shared/: paystackAmount.ts, supabaseClient.ts"]
end
subgraph DestinationServices [Internal Services & Providers]
Postgres[(Supabase PostgreSQL Cluster)]
FCM_APNS[FCM / APNs Native Push Gateways]
MetaWhatsApp[Meta WhatsApp Cloud API]
Termii[Termii SMS Gateway]
end
Paystack -->|POST /paystack-webhook| PW
DBTrigger -->|POST /deliver-notification| DN
AuthHook -->|POST /create-user| CU
PW --> Shared
DN --> Shared
CU --> Shared
PW --> Postgres
DN --> FCM_APNS
DN --> MetaWhatsApp
DN --> Termii
CU --> Postgres1.1 Technical Stack & Invariants
- Runtime: Deno 1.x / V8 Edge Isolate.
- Dependencies & Import Maps: Configured via
supabase/functions/import_map.jsonanddeno.json. External modules load viahttps://esm.sh/@supabase/supabase-js@2andhttps://deno.land/std. - Fail-Closed Security: If cryptographic secrets (
PAYSTACK_SECRET_KEY) or HMAC signatures are missing, functions reject requests immediately with HTTP 401 Unauthorized or 500 Server Error without acknowledging receipts.
2. Function Specifications
2.1 paystack-webhook (supabase/functions/paystack-webhook/index.ts)
The primary serverless ingest point for Paystack financial events.
sequenceDiagram
autonumber
participant Paystack as Paystack Gateway
participant Edge as paystack-webhook (Deno)
participant DB as Supabase PostgreSQL
Paystack->>Edge: POST /functions/v1/paystack-webhook (with x-paystack-signature)
Edge->>Edge: Verify Signature (HMAC SHA-512, 128 hex chars, constant-time)
alt Invalid Signature
Edge-->>Paystack: 401 Unauthorized (Fail-Closed)
else Signature Valid
Edge->>DB: Check deduplication table (processed_webhook_events)
alt Event Already Processed
Edge-->>Paystack: 200 OK (Idempotent ACK)
else Fresh Event
Edge->>Edge: Extract Principal Amount via checkoutPrincipalKobo()
alt event === 'charge.success'
Edge->>DB: Atomically transition order -> paid_escrow
Edge->>DB: Insert double-entry transaction record
Edge->>DB: Record processed_webhook_event
Edge-->>Paystack: 200 OK (Event Processed)
else event === 'transfer.success'
Edge->>DB: Update payout_transfers status -> success
Edge-->>Paystack: 200 OK
else event === 'transfer.failed' / 'reversed'
Edge->>DB: Log payout exception & alert on-call
Edge-->>Paystack: 200 OK
end
end
endCryptographic Verification Invariant
Paystack signs webhook payloads using HMAC SHA-512. The edge function enforces strict length checks prior to constant-time evaluation to prevent timing-attack oracles:
// supabase/functions/paystack-webhook/index.ts:36-55
if (signature.length !== 128) {
return new Response(JSON.stringify({ error: 'Invalid signature' }), { status: 401 });
}
const sigBytes = hexToUint8(signature);
if (sigBytes.length !== 64) {
return new Response(JSON.stringify({ error: 'Invalid signature' }), { status: 401 });
}
const calculatedHmac = await crypto.subtle.sign(
'HMAC',
cryptoKey,
new TextEncoder().encode(rawBody)
);
const isValid = timingSafeEqual(new Uint8Array(calculatedHmac), sigBytes);
if (!isValid) {
return new Response(JSON.stringify({ error: 'Invalid signature' }), { status: 401 });
}Underpayment Protection
Extracts actual gross principal amount using checkoutPrincipalKobo() ([_shared/paystackAmount.ts](file:///c:/Users/frank/OneDrive/Desktop/Chisom/Debelu/New%20Debelu%20Marketplace/supabase/functions/_shared/paystackAmount.ts)). Verifies that the settled amount matches or exceeds orders.total_amount. Transactions settling less than the expected balance are quarantined and flagged for fraud investigation.
2.2 deliver-notification (supabase/functions/deliver-notification/index.ts)
A high-throughput multi-channel messaging dispatcher triggered by PostgreSQL database changes or backend outbox queues.
flowchart TD
Inbound[Inbound Notification Event] --> Router{Delivery Channel}
Router -->|Push| APNS_FCM[Send APNs / FCM Push via WebPush & Native Bridge]
Router -->|WhatsApp| WhatsAppCloud[Meta WhatsApp Cloud API: Transactional Template]
Router -->|SMS| TermiiAPI[Termii SMS Gateway: Delivery PIN & OTP]
Router -->|Email| ResendSMTP[Transactional Email Dispatch]
APNS_FCM --> Result[Log Delivery Status to notification_delivery_logs]
WhatsAppCloud --> Result
TermiiAPI --> Result
ResendSMTP --> ResultMulti-Channel Features
- Push Notifications: Emits Web Push (VAPID) and native mobile notifications to device tokens retrieved from
user_devices. - WhatsApp Business Messaging: Formats automated transactional notifications (e.g., order confirmation, vendor dispatch alerts, return request updates) conforming to Meta pre-approved message templates.
- SMS Fallback: Routes urgent 6-digit delivery confirmation PINs through Termii for student buyers in campus hostels with intermittent data connectivity.
2.3 create-user (supabase/functions/create-user/index.ts)
Triggered automatically upon new account creation via Supabase Auth:
- Provisions the core
public.profilesrow with default buyer roles. - Associates campus affiliation based on university email domains (
@unilag.edu.ng,@unn.edu.ng, etc.). - Evaluates student referral tokens and credits initial reward balances.
3. Shared Utilities (supabase/functions/_shared/)
Common code shared across edge functions:
paystackAmount.ts: Pure function parsing Paystack monetary payloads, extracting fee splits, and converting currency into exact integer Kobo.supabaseClient.ts: Helper initializing a privilegedsupabaseAdminclient utilizingSUPABASE_SERVICE_ROLE_KEYfor database operations.crypto.ts: Constant-time byte comparison (timingSafeEqual) and hex decoders.
4. Local Development & Testing
4.1 Running Edge Functions Locally
# Serve edge functions locally using the Supabase CLI
supabase functions serve --env-file ./debelu-backend/.env
# Test local invocation of paystack-webhook
curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/paystack-webhook' \
--header 'Content-Type: application/json' \
--header 'x-paystack-signature: <valid_128_hex_hash>' \
--data '{"event":"charge.success","data":{"reference":"ord_test_123","amount":500000}}'4.2 Automated Edge Function Tests
Edge functions are tested using Vitest against the functions directory:
# Execute automated edge function test suites
npm run test:functions5. Deployment & Secret Provisioning
sequenceDiagram
autonumber
participant Dev as DevOps Engineer
participant CLI as Supabase CLI
participant Cloud as Supabase Managed Edge Infrastructure
Dev->>CLI: supabase secrets set PAYSTACK_SECRET_KEY=sk_live_...
CLI->>Cloud: Encrypts & sets environment secrets
Dev->>CLI: supabase functions deploy paystack-webhook
Dev->>CLI: supabase functions deploy deliver-notification
CLI->>Cloud: Bundles Deno code & deploys globally to edge workers
Cloud-->>Dev: Functions active at https://xyzproject.supabase.co/functions/v1/*5.1 Deployment Commands
# Deploy all edge functions to production
supabase functions deploy paystack-webhook --project-ref <project_ref>
supabase functions deploy deliver-notification --project-ref <project_ref>
supabase functions deploy create-user --project-ref <project_ref>
# Set edge function secrets
supabase secrets set --project-ref <project_ref> \
PAYSTACK_SECRET_KEY="sk_live_..." \
META_WHATSAPP_TOKEN="..." \
TERMII_API_KEY="..." \
VAPID_PRIVATE_KEY="..."6. Document Revision History
| Revision | Date | Lead Author | Scope of Changes | Status |
|---|---|---|---|---|
1.0.0 | 2026-10-05 | Principal Cloud Architect | Initial enterprise edge functions reference detailing Deno runtime, HMAC SHA-512 verification, multi-channel notifications, and deployment protocols. | Active Living Standard |