@davoodmehraban89 / LifeMate / commits / e253696
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(sms): add isolated Kavenegar VerifyLookup adapter with secret-safe errors

davoodmehraban89 committed Oct 15, 2026 at 00:56 UTC e25369655490a3d019a5bf1e721bb560822f163a
1 file changed +86
backend/src/kavenegar_sms.js new
+86
@@ -0,0 +1,86 @@
1 +// Dedicated Kavenegar VerifyLookup provider. Only call from a trusted backend.
2 +// The provider's v1 API puts the API key in the HTTPS URL path; never log request URLs.
3 +const iranPhone = /^\+989\d{9}$/;
4 +const sixDigits = /^\d{6}$/;
5 +const uuid = /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
6 +const keyPattern = /^[a-zA-Z0-9]{16,256}$/;
7 +const templatePattern = /^[a-zA-Z][a-zA-Z0-9]{1,63}$/;
8 +
9 +function providerError(code) {
10 + const error = new Error(code); // Never include provider response, key, phone or token.
11 + error.retryable = false; // VerifyLookup has no idempotency key: retry risks duplicate SMS.
12 + return error;
13 +}
14 +
15 +export function createKavenegarSmsProvider({ env = process.env, fetchImpl = fetch, timeoutMs = 10000 } = {}) {
16 + const apiKey = env.KAVENEGAR_API_KEY;
17 + const template = env.KAVENEGAR_TEMPLATE;
18 + if (typeof apiKey !== 'string' || !keyPattern.test(apiKey)) throw providerError('sms_provider_token_invalid');
19 + if (typeof template !== 'string' || !templatePattern.test(template)) throw providerError('sms_provider_template_invalid');
20 + const timeout = Number.isInteger(timeoutMs) && timeoutMs > 0 && timeoutMs <= 10000 ? timeoutMs : 10000;
21 + return new KavenegarSmsProvider({ apiKey, template, fetchImpl, timeout });
22 +}
23 +
24 +class KavenegarSmsProvider {
25 + configured = true;
26 + status = 'CONFIGURED_UNVERIFIED';
27 + #apiKey; #template; #fetch; #timeout;
28 + constructor({ apiKey, template, fetchImpl, timeout }) {
29 + this.#apiKey = apiKey;
30 + this.#template = template;
31 + this.#fetch = fetchImpl;
32 + this.#timeout = timeout;
33 + }
34 +
35 + async sendOtp({ phone, code, expiresIn, idempotencyKey }) {
36 + if (typeof phone !== 'string' || !iranPhone.test(phone) ||
37 + typeof code !== 'string' || !sixDigits.test(code) ||
38 + !Number.isInteger(expiresIn) || expiresIn < 1 || expiresIn > 300 ||
39 + typeof idempotencyKey !== 'string' || !uuid.test(idempotencyKey)) {
40 + throw providerError('sms_provider_input_invalid');
41 + }
42 +
43 + // Fixed official host: no user-controlled URL, HTTP fallback or redirects.
44 + // The +98XXXXXXXXXX identity is converted to Kavenegar's Iranian 09XXXXXXXXX.
45 + const url = new URL(`https://api.kavenegar.com/v1/${this.#apiKey}/verify/lookup.json`);
46 + url.search = new URLSearchParams({
47 + receptor: '0' + phone.slice(3),
48 + token: code,
49 + template: this.#template,
50 + type: 'sms',
51 + }).toString();
52 +
53 + const signal = AbortSignal.timeout(this.#timeout);
54 + let response;
55 + try {
56 + response = await this.#fetch(url.href, {
57 + method: 'GET',
58 + redirect: 'error',
59 + signal,
60 + headers: { Accept: 'application/json' },
61 + });
62 + } catch {
63 + throw providerError(signal.aborted ? 'sms_provider_timeout' : 'sms_provider_unavailable');
64 + }
65 + if (response?.status !== 200) {
66 + try { await response?.body?.cancel?.(); } catch { /* no body logging */ }
67 + throw providerError('sms_provider_rejected');
68 + }
69 +
70 + let payload;
71 + try {
72 + const raw = await response.text();
73 + if (raw.length > 8192) throw new Error('oversized_provider_response');
74 + payload = JSON.parse(raw);
75 + } catch {
76 + throw providerError('sms_provider_malformed_response');
77 + }
78 + if (payload?.return?.status !== 200 ||
79 + !payload.entries ||
80 + (Array.isArray(payload.entries) && !payload.entries.length)) {
81 + throw providerError('sms_provider_rejected');
82 + }
83 + // HTTP 200 and provider 200 only prove provider acceptance, not handset delivery.
84 + return { delivered: true };
85 + }
86 +}