سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 10:30 UTC
feat(otp): stage fail-closed signed Supabase SMS Hook Kavenegar adapter
davoodmehraban89 committed
Oct 12, 2026 at 22:41 UTC
b10ab78466a5d29f92a9a0a2de811ad54eacdcd2
1 file changed
+87
supabase/functions/finora-kavenegar-send-sms/handler.mjs
new
+87
@@ -0,0 +1,87 @@
1
+// Finora Supabase Auth Send SMS Hook -> Kavenegar verification templates.
2
+// Staged/offline only. No production deployment or Auth configuration is implied.
3
+// Exact signed-body verification protects this endpoint even with verify_jwt=false.
4
+export const KAVENEGAR_TEMPLATE = 'FinoraLogin';
5
+const REPLAY_WINDOW_SECONDS = 300;
6
+const MAX_BODY_BYTES = 8192;
7
+const HEADERS = {'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'};
8
+
9
+function reply(status, error) {
10
+ return new Response(error ? JSON.stringify({error}) : '{}', {status,headers:HEADERS});
11
+}
12
+function safeBase64Decode(raw) {
13
+ const binary = atob(raw);
14
+ return Uint8Array.from(binary, char => char.charCodeAt(0));
15
+}
16
+export function iranianSmsReceptor(phone) {
17
+ // Supabase Auth uses E.164. Never infer identity from an arbitrary profile field.
18
+ if (typeof phone !== 'string' || !/^\+989[0-9]{9}$/.test(phone)) return null;
19
+ return '0' + phone.slice(3);
20
+}
21
+export async function verifyAuthSmsSignature(request, rawBody, rawSecret, nowMs = Date.now(), cryptoImpl = globalThis.crypto) {
22
+ const webhookId = request.headers.get('webhook-id') || '';
23
+ const timestampText = request.headers.get('webhook-timestamp') || '';
24
+ const signatureText = request.headers.get('webhook-signature') || '';
25
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(webhookId) || !/^[0-9]{10,11}$/.test(timestampText)) return false;
26
+ const timestamp = Number(timestampText);
27
+ if (!Number.isSafeInteger(timestamp) || Math.abs(Math.floor(nowMs / 1000) - timestamp) > REPLAY_WINDOW_SECONDS) return false;
28
+ if (!signatureText || signatureText.length > 1024 || !cryptoImpl?.subtle) return false;
29
+ // The Supabase hook secret is typically v1,whsec_BASE64. Allow a rotated
30
+ // set separated by |; never treat the displayed secret as a raw HMAC key.
31
+ const secrets = String(rawSecret || '').split('|').slice(0,3);
32
+ const signatures = signatureText.split(/\s+/).filter(s => s.startsWith('v1,')).slice(0,6);
33
+ if (!signatures.length) return false;
34
+ const signed = new TextEncoder().encode(webhookId + '.' + timestampText + '.' + rawBody);
35
+ for (const entry of secrets) {
36
+ const match = /^(?:v1,)?whsec_([A-Za-z0-9+/=]{32,})$/.exec(entry.trim());
37
+ if (!match) continue;
38
+ let keyBytes;
39
+ try { keyBytes = safeBase64Decode(match[1]); } catch { continue; }
40
+ if (keyBytes.length < 24 || keyBytes.length > 64) continue;
41
+ const key = await cryptoImpl.subtle.importKey('raw', keyBytes, {name:'HMAC',hash:'SHA-256'}, false, ['verify']);
42
+ for (const signature of signatures) {
43
+ try {
44
+ const bytes = safeBase64Decode(signature.slice(3));
45
+ if (bytes.length !== 32) continue;
46
+ if (await cryptoImpl.subtle.verify('HMAC', key, bytes, signed)) return true;
47
+ } catch { /* malformed signature */ }
48
+ }
49
+ }
50
+ return false;
51
+}
52
+export async function handleFinoraKavenegarSms(request, {env = () => '', fetchImpl = fetch, nowMs = Date.now(), cryptoImpl = globalThis.crypto} = {}) {
53
+ if (request.method !== 'POST') return reply(405, 'method_not_allowed');
54
+ // Feature flag is mandatory, rather than silently treating an unconfigured hook as delivered.
55
+ if (env('FINORA_KAVENEGAR_OTP_ENABLED') !== 'true') return reply(503, 'otp_not_enabled');
56
+ const apiKey = String(env('KAVENEGAR_API_KEY') || '').trim();
57
+ const hookSecret = String(env('SEND_SMS_HOOK_SECRET') || '').trim();
58
+ if (!/^[A-Za-z0-9]{16,128}$/.test(apiKey) || !hookSecret) return reply(503, 'otp_secrets_not_configured');
59
+ const raw = await request.text();
60
+ if (new TextEncoder().encode(raw).length > MAX_BODY_BYTES) return reply(413, 'payload_too_large');
61
+ if (!(await verifyAuthSmsSignature(request, raw, hookSecret, nowMs, cryptoImpl))) return reply(401, 'invalid_hook_signature');
62
+ let event;
63
+ try { event = JSON.parse(raw); } catch { return reply(400, 'invalid_hook_payload'); }
64
+ const receptor = iranianSmsReceptor(event?.user?.phone);
65
+ const token = event?.sms?.otp;
66
+ if (!receptor || typeof token !== 'string' || !/^[0-9]{6,10}$/.test(token)) return reply(422, 'unsupported_phone_or_token');
67
+ const body = new URLSearchParams({receptor,token,template:KAVENEGAR_TEMPLATE});
68
+ // The provider requires the API key in its URL; never print URLs or response bodies.
69
+ const providerUrl = 'https://api.kavenegar.com/v1/' + encodeURIComponent(apiKey) + '/verify/lookup.json';
70
+ const controller = new AbortController();
71
+ const timeout = setTimeout(() => controller.abort(), 3500);
72
+ try {
73
+ const response = await fetchImpl(providerUrl,{
74
+ method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','Accept':'application/json'},
75
+ body:body.toString(),signal:controller.signal
76
+ });
77
+ if (!response.ok) return reply(502, 'sms_provider_failed');
78
+ const receipt = await response.json();
79
+ if (Number(receipt?.return?.status) !== 200) return reply(502, 'sms_provider_failed');
80
+ return reply(200);
81
+ } catch {
82
+ // Never log OTP, mobile, user info, API key or provider request URL.
83
+ return reply(502, 'sms_provider_unreachable');
84
+ } finally {
85
+ clearTimeout(timeout);
86
+ }
87
+}