سامانه صدور فاکتور و حسابداری
feat(otp): stage disabled Kavenegar Send SMS hook with offline tests (#110)
* docs(state): record approved offline Kavenegar OTP preparation and strict no-activation boundary * feat(otp): stage fail-closed signed Supabase SMS Hook Kavenegar adapter * feat(otp): add isolated Supabase Edge entrypoint (not deployed) * test(otp): offline signed hook and provider failure regression matrix * docs(otp): safe staged activation, existing identity linking and external-cost gates * ci(otp): run offline Kavenegar signed hook regression without external SMS * docs(state): record offline OTP QA evidence, provider approval and no-activation gate
davoodmehraban89 committed
Oct 12, 2026 at 22:52 UTC
6d0882810ca66e105f2c80c745daf6bc4dcfb88b
6 files changed
+221
.github/workflows/quality.yml
+2
@@ -28,6 +28,8 @@ jobs:
28
run: node scripts/stripe-sandbox-readonly-test.mjs
29
- name: Finora Stripe sandbox Edge authorization and invariant gates
30
run: node scripts/stripe-edge-sandbox-test.mjs
31
+ - name: Finora Kavenegar OTP offline signed-hook and provider safety checks
32
+ run: node scripts/kavenegar-otp-preflight-test.mjs
33
- name: Commercial workspace and factory-reset invariants
34
run: node scripts/commercial-rnd-check.mjs
35
- name: UX commerce/settings R2 invariants
PROJECT_STATE.md
+12
@@ -63,6 +63,18 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
63
- **Direct live-domain parity, authorized remote Windows read-only GET:** `https://factoreasy.ir/?loginCspProof=20261012` HTML includes `js/generated-event-handlers.js`, `js/core.js?v=20261012-login-wiring-v3` and `js/sync.js?v=20261012-login-read-cancel-v1`; versioned `js/bootstrap.js` points to `organization-rbac.js?v=20261012-login-scoped-read-v1`, and direct retrieved module contains `finoraOrganizationRead`, `FINORA_LOGIN_READ_TIMEOUT` and scoped read references. No owner credentials, session data, backend mutations, accounts or financial history were accessed.
64
- **Acceptance boundary / next step:** CODE_RELEASED / SYNTHETIC_E2E_PASSED / LIVE_ASSET_PARITY_VERIFIED; owner actual affected-ISP behavior remains **NOT VERIFIED**, F0-01 and overall Phase 0 remain **OPEN**. Owner should fully refresh `factoreasy.ir`, click `بررسی اتصال به سرور ورود` with no password and report only code (AUTH_OK/AUTH_TIMEOUT/AUTH_UNREACHABLE/SITE_UNREACHABLE), then test permitted existing account login privately. Distinguish slow restored-session permissions/records from Auth service network. Rollback #107 via guarded Pages, no DB rollback.
65
66
+### 2026-10-12 Kavenegar OTP preparation — OWNER APPROVED OFFLINE PREPARATION ONLY / PENDING
67
+- **Owner intent:** move future Finora primary sign-in from email toward mobile OTP using previously created Kavenegar verification template `FinoraLogin`; correct owner clarification: the owner approved **preparing the technical infrastructure**, not Kavenegar's template. Most recent visible provider status was **UNDER REVIEW**, and provider template approval and SMS delivery are **NOT VERIFIED**. Preserve existing password/email/Google sign-in and all existing Supabase Auth user IDs/organizations. No automatic new accounts or reassignment of an existing identity.
68
+- **Scope/owner:** code preparation on isolated branch only; design server-side Supabase Auth Send SMS Hook -> verified webhook -> Kavenegar `verify/lookup` using template `FinoraLogin`, feature disabled/fail-closed by default, no API key in public GitHub/browser. Add a provider adapter with synthetic offline tests and setup/runbook. No Auth settings, hook, live Edge Function, environment secrets, phone mappings, database or production site modifications under this slice.
69
+- **Verified baseline:** main `833b795b7b0320260b91dcbe621bbce04b23f0c3`; live Supabase `hcsixhqbyuhpshfwqpjx` HEALTHY; `public.profiles.phone` and unique partial index existing, live `phone_identity_profile` migration recorded; no Kavenegar sender Edge Function deployed; historical PR #58 remains open, must not blindly merge/duplicate migration. Windows Desktop Commander `DESKTOP-71SJ63M` ONLINE. Its working copy `C:\Temp\Factor-easy` was observed on stale `main` SHA `b1a35fdc...`, with **0 tracked modifications / 2189 untracked files**, and is read-only for this operation; GitHub branch is canonical source.
70
+- **Acceptance:** offline contract tests cover signed hook body/gate, phone formatting, token/template injection protection, provider status/errors/timeouts and no sensitive logging; source/docs checked on feature-head CI. Activation requires independently verified **approved provider template**, securely configured API/hook secrets, admin owner confirmation before Auth provider setting changes and actual SMS send/test costs, safe linking/verification for existing user phone identities, staged user test without creating duplicate accounts, owner affected-network sign-in acceptance. RLS/tenant isolation and ledger remain unchanged. **Phase 0 F0-01 still OPEN.**
71
+
72
+### 2026-10-12 Kavenegar OTP server-only preparation — PR #110 OFFLINE QA PASS / NOT ACTIVATED
73
+- **Owner clarification upheld:** `FinoraLogin` template **NOT verified approved by Kavenegar**, only owner-approved infrastructure preparation. Provider SDK API documented; **no provider key received**, no live outbound SMS or Auth hook configuration. Keep existing email/password/Google functioning unchanged. Historical phone PR #58 remains pending and was not merged.
74
+- **PR [#110](https://github.com/davoodmehraban89/Factor-easy/pull/110):** isolated `supabase/functions/finora-kavenegar-send-sms/{handler.mjs,index.ts}` stage, `scripts/kavenegar-otp-preflight-test.mjs`, Quality workflow step and detailed `docs/FINORA_KAVENEGAR_OTP_PREPARATION_2026-10-12.md`. Feature disabled unless explicit `FINORA_KAVENEGAR_OTP_ENABLED=true` plus Edge-only `KAVENEGAR_API_KEY` and `SEND_SMS_HOOK_SECRET`. Checks Standard Webhooks HMAC and 5-minute timestamp before parsing, validates `+989...` and 6–10-digit token, uses provider's fixed template `FinoraLogin` and 3.5s timeout. Responds non-200 on disabled/invalid/provider failure; synthetic tests never contact Kavenegar. No account management, DB migrations, RLS, Auth configuration, website login UI, edge deployment, secret creation or cost.
75
+- **Observed Quality head `b6e72973a45bd48f3b2ad28f31a4da54c8094633`:** GitHub [Quality run `38296251394`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38296251394), **attempt 2 SUCCESS**, 96/96 Chromium PASS, Golden accounting PASS, OTP synthetic signed-hook/provider regression PASS, three isolated PostgreSQL suites PASS; [Security `38296251305`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38296251305) SUCCESS. First attempt had 95/96 Chromium with old F0-06 light-theme luminance assertion failing (reported 0.456 < 0.5), but no OTP regression; reran exact code job without weakening or changing the visual assertion and passed 96/96. This *documentation follow-up* commit still requires a new exact-head validation before merge.
76
+- **Acceptance still OPEN:** Kavenegar template approval/real delivery/cost, staging Edge deploy with signature verification and `verify_jwt=false`, protected server secrets, Supabase Auth phone provider & SMS hook configuration and real-account mobile binding must receive separate explicit owner approval and testing. NO automatic signup or newly created unrelated Auth user is allowed during legacy identity migration. Phase 0 F0-01 owner-real-ISP sign-in and Phase 0 as a whole remain OPEN.
77
+
78
## Current change ledger
79
| 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Commercial sale/purchase workspaces now share a stable `صدور سند تجاری` header/actions layout; duplicate purchase sidebar injection removed; the public selector is the single document-type selector and the legacy internal invoice-kind control is hidden. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; protected-branch CI remains pending. |
80
docs/FINORA_KAVENEGAR_OTP_PREPARATION_2026-10-12.md
new
+38
@@ -0,0 +1,38 @@
1
+# Finora — Kavenegar SMS OTP integration preparation (2026-10-12)
2
+
3
+**Status: OFFLINE PREPARATION ONLY; NO LIVE SMS, NO AUTH CONFIG CHANGE, NO LIVE EDGE DEPLOY.**
4
+
5
+## Authority / current factual baseline
6
+Owner has **approved preparation** of mobile OTP integration, **not claimed that Kavenegar approved** the template. Last Kavenegar screenshot of `FinoraLogin` displayed `در حال بررسی`. Do not infer approved from chat shorthand. Sender/real delivery/provider credit have NOT been verified.
7
+
8
+The existing application uses Supabase Auth email OTP / password / Google; `public.profiles.phone` and unique non-null phone index exist; prior live migration `phone_identity_profile` was recorded, but that does **not** prove matching `auth.users.phone` or securely linked identities. Historic phone PR #58 is open/stale; do not merge it or reapply its migration without reconciliation. Supabase currently has **no deployed** `finora-kavenegar-send-sms` Edge Function.
9
+
10
+An authorized Remote Desktop Commander device `DESKTOP-71SJ63M` is online. Local checkout `C:\Temp\Factor-easy` was read-only checked: branch `main`, SHA `b1a35fdc1df71c46c287bec47be54fa6e8641428`, 0 tracked changes and 2189 untracked files. **It is stale and has many untracked files**: do not reset, clean, overwrite or sync it without separate review. This preparation is authored on a GitHub feature branch.
11
+
12
+## Proposed integration
13
+`Supabase Auth` creates and validates OTP; it calls its **Send SMS HTTP Hook** with a signed Standard Webhooks event (`user.phone`, `sms.otp`). Server-side Deno Edge Function verifies **raw-body signature and timestamp**, validates E.164 `+989xxxxxxxxx` phone and 6–10 digit OTP, converts phone to local `09...` and posts `application/x-www-form-urlencoded` to Kavenegar `/v1/<API_KEY>/verify/lookup.json` with fixed `template=FinoraLogin`. Supabase alone issues Auth JWT/session and existing Finora membership/license/RLS rules remain authoritative.
14
+
15
+Function files: `supabase/functions/finora-kavenegar-send-sms/{index.ts,handler.mjs}`. It rejects all requests unless `FINORA_KAVENEGAR_OTP_ENABLED=true`, and even then rejects unsigned, expired, malformed or missing-secret events. It **never** receives a browser call or generates, stores or verifies the OTP. No customer identity search, tenant data access, service-role key, SQL or business record write is required.
16
+
17
+## Activation gates (do not perform in preparation phase)
18
+1. Independently see `FinoraLogin` in Kavenegar state **تأیید شده**. Confirm verify/lookup is allowed on this tariff, short-SMS unit cost/credit and live sender deliverability.
19
+2. Set `KAVENEGAR_API_KEY` and `SEND_SMS_HOOK_SECRET` **only in Supabase server-side encrypted Edge secrets**, not in messages, public GitHub, logs, browser, desktop env files or screenshots. Generate hook signing secret through Supabase Auth Hooks (use actual value, not the sample). Configure Edge Function for `verify_jwt=false` **only at activation**, because incoming signed Auth hook requests have no end-user JWT; the handler enforces signature verification. This setting is sensitive; require owner confirmation.
20
+3. Deploy the Edge Function under owner-approved rollout, while `FINORA_KAVENEGAR_OTP_ENABLED` remains unset/false; configure Auth's `Send SMS Hook` to its HTTPS URL and enable the phone provider only in a controlled window after explicit owner confirmation. **Never** configure a fail-closed disabled hook as the active route for real users.
21
+4. Stage one real SMS to an explicitly approved test number; external messaging **and cost** require owner authorization. A Kavenegar API status 200 means *accepted by provider*, not verified delivery. Verify real handset receipt and OTP expiry/attempt limit, no 1-to-many runaway resends.
22
+5. **Before real login rollout:** authenticated owner must securely link a verified phone to **the existing `auth.users.id`**, reconcile any conflicting existing phone identity and preserve memberships, licenses and all tenant/financial records. The existing profile's phone text is not, by itself, a validated Auth login method. Do not directly mutate Auth or RLS without explicit authorization. Keep `shouldCreateUser:false` for existing-user sign-in; do not auto-create anonymous phone users.
23
+6. Implement the mobile-first login form in a separately gated PR **after** provider, identity linking and server hooks pass. Preserve email/password and Google fallback. Verify browser CSP handlers, retry/rate limiting, CAPTCHA, account lockout, RTL mobile UX, session restore, +98 normalization, masking/error states, and correct org isolation; validate on owner's affected ISP.
24
+7. Merge/release only after full static/Chromium/Golden/3 PostgreSQL/Security checks, gated Pages and owner test. F0-01 and Phase 0 remain open until real acceptance. Rollback via removing SMS entry point and restoring existing Auth settings after coordinated owner approval.
25
+
26
+## Offline acceptance and limitations
27
+- Run `node scripts/kavenegar-otp-preflight-test.mjs` (no internet, no SMS, synthetic token / hook signing secret); CI also executes it.
28
+- No secrets or credential data in repo. Never log the webhook body/provider URL, phone, token or upstream response JSON.
29
+- The hook enforces a 5-minute signed-message timestamp window but does **not** persist event-id replay deduplication. Supabase Auth rate limits and a later approved cost/sending control remain required before production.
30
+- Provider timeout is 3.5 seconds to fit Supabase Auth HTTP hook timeout (~5 seconds). Invalid provider response fails closed and returns non-200; it never falsely acknowledges SMS delivery.
31
+- **Not verified:** Kavenegar approval, actual SMS/charges, Supabase Auth phone setting, provider SMS hook wiring, live sender, actual phone-to-existing-user secure linking, site UI and mobile sign-in. Do not mark any as complete from passing synthetic tests.
32
+
33
+## Public technical references
34
+- Supabase: https://supabase.com/docs/guides/auth/auth-hooks/send-sms-hook
35
+- Supabase Auth Hook security: https://supabase.com/docs/guides/auth/auth-hooks
36
+- Standard Webhooks spec: https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md
37
+- Kavenegar SDK verification example: https://github.com/KaveNegar/kavenegar-node
38
+
scripts/kavenegar-otp-preflight-test.mjs
new
+74
@@ -0,0 +1,74 @@
1
+import assert from 'node:assert/strict';
2
+import {readFileSync} from 'node:fs';
3
+import {KAVENEGAR_TEMPLATE, iranianSmsReceptor, handleFinoraKavenegarSms} from '../supabase/functions/finora-kavenegar-send-sms/handler.mjs';
4
+
5
+const signedSecretBytes = new TextEncoder().encode('synthetic-hook-secret-material-that-is-not-live');
6
+const hookSecret='v1,whsec_'+btoa(String.fromCharCode(...signedSecretBytes));
7
+const config={FINORA_KAVENEGAR_OTP_ENABLED:'true',KAVENEGAR_API_KEY:'SYNTHETICAPIKEY1234567890',SEND_SMS_HOOK_SECRET:hookSecret};
8
+const env=(overrides={})=>(key)=>({...config,...overrides})[key]||'';
9
+const event={user:{id:'00000000-0000-4000-8000-000000000001',phone:'+989123456789'},sms:{otp:'123456'}};
10
+const signed=async (payload=event,{ts=Math.floor(Date.now()/1000),id='test_event_123',secretBytes=signedSecretBytes,signatureTamper=false}={})=>{
11
+ const raw=JSON.stringify(payload);
12
+ const cryptoKey=await crypto.subtle.importKey('raw',secretBytes,{name:'HMAC',hash:'SHA-256'},false,['sign']);
13
+ const bytes=new TextEncoder().encode(id+'.'+ts+'.'+raw);
14
+ const signature=new Uint8Array(await crypto.subtle.sign('HMAC',cryptoKey,bytes));
15
+ const base64=btoa(String.fromCharCode(...signature));
16
+ return new Request('https://functions.invalid/finora-kavenegar-send-sms',{
17
+ method:'POST',
18
+ headers:{'webhook-id':id,'webhook-timestamp':String(ts),'webhook-signature':'v1,'+(signatureTamper?'invalidsignature':base64)},
19
+ body:raw
20
+ });
21
+};
22
+const rejectedNetwork=async()=>{throw new Error('not expected to contact SMS provider');};
23
+let calls=0;
24
+const mockSuccess=async(url,options)=>{
25
+ calls++;
26
+ assert.equal(url,'https://api.kavenegar.com/v1/SYNTHETICAPIKEY1234567890/verify/lookup.json');
27
+ assert.equal(options.method,'POST');
28
+ assert.equal(options.headers['Content-Type'],'application/x-www-form-urlencoded');
29
+ const form=new URLSearchParams(options.body);
30
+ assert.equal(form.get('receptor'),'09123456789');
31
+ assert.equal(form.get('token'),'123456');
32
+ assert.equal(form.get('template'),KAVENEGAR_TEMPLATE);
33
+ assert.equal([...form.keys()].length,3);
34
+ assert.equal(options.signal.aborted,false);
35
+ return Response.json({return:{status:200},entries:{messageid:123}},{status:200});
36
+};
37
+const perform=async(req,{overrides={},fetchImpl=rejectedNetwork}={})=>{
38
+ const response=await handleFinoraKavenegarSms(req,{env:env(overrides),fetchImpl});
39
+ assert.equal(response.headers.get('Cache-Control'),'no-store');
40
+ const raw=await response.text();
41
+ for(const forbidden of ['123456','09123456789',config.KAVENEGAR_API_KEY,hookSecret])assert.ok(!raw.includes(forbidden));
42
+ return {status:response.status,raw};
43
+};
44
+assert.equal(KAVENEGAR_TEMPLATE,'FinoraLogin');
45
+assert.equal(iranianSmsReceptor('+989123456789'),'09123456789');
46
+assert.equal(iranianSmsReceptor('09123456789'),null);
47
+assert.equal(iranianSmsReceptor('+12025550123'),null);
48
+assert.equal((await perform(await signed(),{overrides:{FINORA_KAVENEGAR_OTP_ENABLED:''}})).status,503);
49
+assert.equal((await perform(await signed(),{overrides:{KAVENEGAR_API_KEY:''}})).status,503);
50
+assert.equal((await perform(await signed(),{overrides:{SEND_SMS_HOOK_SECRET:''}})).status,503);
51
+assert.equal((await perform(new Request('https://functions.invalid'),{})).status,405);
52
+const unsigned=new Request('https://functions.invalid',{method:'POST',body:JSON.stringify(event)});
53
+assert.equal((await perform(unsigned)).status,401);
54
+assert.equal((await perform(await signed(event,{signatureTamper:true}))).status,401);
55
+assert.equal((await perform(await signed(event,{ts:Math.floor(Date.now()/1000)-301}))).status,401);
56
+assert.equal((await perform(await signed(event,{ts:Math.floor(Date.now()/1000)+301}))).status,401);
57
+assert.equal((await perform(await signed({user:{phone:'+12025550123'},sms:{otp:'123456'}}))).status,422);
58
+assert.equal((await perform(await signed({user:{phone:'+989123456789'},sms:{otp:'12345'} }))).status,422);
59
+assert.equal((await perform(await signed({user:{phone:'+989123456789'},sms:{otp:'123456%0Aevil'}}))).status,422);
60
+assert.equal((await perform(await signed({user:{phone:'+989123456789'},sms:{otp:123456}}))).status,422);
61
+assert.equal((await perform(await signed(),{fetchImpl:async()=>Response.json({return:{status:411}},{status:200})})).status,502);
62
+assert.equal((await perform(await signed(),{fetchImpl:async()=>Response.json({return:{status:200}},{status:400})})).status,502);
63
+assert.equal((await perform(await signed(),{fetchImpl:async()=>{throw new Error('synthetic network outage')}})).status,502);
64
+assert.equal((await perform(await signed(),{fetchImpl:mockSuccess})).status,200);
65
+assert.equal(calls,1,'real delivery must never occur during preflight tests');
66
+const code=readFileSync('supabase/functions/finora-kavenegar-send-sms/index.ts','utf8');
67
+assert.match(code,/handleFinoraKavenegarSms/);
68
+assert.match(code,/Deno\.serve/);
69
+assert.ok(!code.includes('SERVICE_ROLE_KEY'));
70
+const quality=readFileSync('supabase/functions/finora-kavenegar-send-sms/handler.mjs','utf8');
71
+assert.match(quality,/verifyAuthSmsSignature/);
72
+assert.match(quality,/FINORA_KAVENEGAR_OTP_ENABLED/);
73
+assert.ok(!quality.includes('console.log('));
74
+console.log('PASS: Finora Kavenegar OTP offline preflight: signed request, disabled default, provider errors, phone/token isolation, zero real SMS.');
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
+}
supabase/functions/finora-kavenegar-send-sms/index.ts
new
+8
@@ -0,0 +1,8 @@
1
+// Server-only Supabase Auth Send SMS Hook entrypoint.
2
+// In a later owner-approved activation, deploy this function with verify_jwt=false
3
+// because GoTrue signs HTTP hooks using Standard Webhooks, not a user JWT.
4
+// All requests MUST pass signed-body verification in handler.mjs.
5
+import {handleFinoraKavenegarSms} from './handler.mjs';
6
+Deno.serve((request: Request) => handleFinoraKavenegarSms(request, {
7
+ env: (name: string) => Deno.env.get(name) || ''
8
+}));