سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 00:30 UTC
feat: add fail-closed Stripe QA Edge function with user allowlist
Davood Mehraban committed
Oct 11, 2026 at 09:48 UTC
67081d8c26253c0413bf014213589066b8ad6728
7 files changed
+247
.github/workflows/quality.yml
+2
@@ -26,6 +26,8 @@ jobs:
26
run: node scripts/finance-integrity-audit-test.mjs
27
- name: Stripe sandbox invoice read-only invariants
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: Commercial workspace and factory-reset invariants
32
run: node scripts/commercial-rnd-check.mjs
33
- name: UX commerce/settings R2 invariants
.gitignore
new
+6
@@ -0,0 +1,6 @@
1
+# Never commit backend API credentials or Edge Function secrets.
2
+.env
3
+.env.*
4
+supabase/functions/.env
5
+supabase/functions/.env.*
6
+!supabase/functions/.env.example
PROJECT_STATE.md
+7
@@ -160,3 +160,10 @@ Owner confirmed connected Stripe plugin and requested completion of sandbox invo
160
161
2026-10-11 verification checkpoint: Stripe connected plugin test account 'Finora ERP sandbox' (livemode=false): synthetic customer cus_VQ5jO0GvKcuiQd created without email/payment method; draft in_1UPFYbGnbcoujdbeXnuN3Jf0 created (auto_advance=false), invoice item amount 1250 USD minor units added; GET by ID and list both returned draft, total/subtotal/amount_due=1250, exactly one line. Initial send_invoice attempt without email was rejected, so no email was sent; successful draft uses charge_automatically without finalization. New scripts/stripe-sandbox-readonly.mjs is a server-only read-only sandbox guard with synthetic fixture and adversarial test integrated into Quality CI. Local tests PASS: new sandbox adapter, syntax 53 JS + 48 MJS, finance audit, golden accounting journey, git diff check. NO direct Finora backend Stripe API credentials available; no Finora UI/prod DB/schema/auth integration, no charges/ledger writes. Only ChatGPT plugin API access is live-verified. Next: PR Quality/Security CI, then owner-provided private restricted sandbox API key on trusted server and tenant/auth mapping approval for server deployment if desired.
162
163
+
164
+## 2026-10-11 Stripe actual Finora server connection preparation
165
+Owner requested implementation to continue autonomously and precise owner-only setup instructions if blocked. Verified live Supabase project hcsixhqbyuhpshfwqpjx is ACTIVE_HEALTHY and existing admin-user-management Edge Function requires JWT. Stripe plugin verified a sandbox synthetic draft invoice; it does not supply a Finora backend API key. Design decision: implement a disabled-by-default, server-side-only, fixed sandbox invoice preview Edge Function guarded by verify_jwt, live verified Supabase user identity, exact user allowlist and restricted rk_test_ key; no financial postings/production data writes or RLS/schema/auth changes. Deployment will be independently checked; missing secret/identity remain explicit blockers. User must set the restricted Stripe sandbox key in Supabase Functions secrets privately, never share it in chat or commit it.
166
+
167
+
168
+2026-10-11 implementation checkpoint: Added JWT-required (Supabase platform verify_jwt intended), server-side-only finora-stripe-qa-read Edge Function with locked one-invoice QA scope, Auth /auth/v1/user revalidation, exact allowed user UUID, Stripe restricted rk_test_ only, origin/method restrictions, no customer PII in output, no ledger/production data writes. Added .gitignore for .env secrets, documented Dashboard-only two-secret onboarding. Local PASS: 26 auth/amount/origin adversarial cases, Stripe fixture read, finance integrity, golden accounting journey, syntax 53 JS/49 MJS, git diff check. PENDING: GitHub PR CI, actual Edge deployment verify_jwt=true, unauthorized live 401 probe, owner private sandbox secrets and authenticated read test. Never mark direct Finora-to-Stripe API as verified before private key is configured.
169
+
docs/STRIPE_EDGE_SANDBOX_QA_2026-10-11.md
new
+43
@@ -0,0 +1,43 @@
1
+# Finora — restricted Stripe sandbox Edge gateway (2026-10-11)
2
+
3
+## Purpose / rollout
4
+The only endpoint is a **QA preview** of the previously verified synthetic USD 12.50 Stripe draft invoice. It does not handle actual financial records, payments, subscriptions, document posting, exchange rates, production Stripe keys or Stripe webhooks.
5
+
6
+This code is deliberately **fail-closed by default**. No result is returned without both an explicitly configured restricted **test** Stripe API key and one exact approved Supabase user UUID. The Supabase platform must set `verify_jwt=true` (mandatory), and the handler re-verifies the caller with Supabase Auth before checking the exact user ID.
7
+
8
+Project: `hcsixhqbyuhpshfwqpjx`; function slug: `finora-stripe-qa-read`. No DB migrations, RLS changes, licenses, auth metadata, or financial-history writes.
9
+
10
+## Owner-only secrets — never send to ChatGPT or commit
11
+1. In **Stripe Dashboard**, switch the account picker to the sandbox called **Finora ERP sandbox**. Under **Developers → API keys**, create a **restricted** API key, not a secret/unrestricted key. Set **Invoices: Read**, all other resource permissions **None**. The key must begin with `rk_test_`. If Stripe's interface requires an associated resource for invoice reads, grant read-only access to that resource only, and remove any unnecessary permissions after testing.
12
+2. Open the Finora Supabase project's [Edge Functions → Secrets](https://supabase.com/dashboard/project/hcsixhqbyuhpshfwqpjx/functions/secrets). Add `STRIPE_SANDBOX_RESTRICTED_KEY` with the new sandbox-only key value. It must stay *only* inside Supabase secrets.
13
+3. In the same page, set `FINORA_STRIPE_QA_ALLOWED_USER_ID` to the **Auth → Users → User UID** of the ONE intended authorized Finora tester. Do not paste tokens or keys into chats, browser code, GitHub, or plaintext files.
14
+4. Tell the development assistant only **"دو مقدار امن ثبت شد"** (no key/UID shared). Re-test with an authenticated tester account. Supabase Secrets updates do not require an Edge Function redeploy.
15
+
16
+Official guidance: https://docs.stripe.com/keys/restricted-api-keys and https://supabase.com/docs/guides/functions/secrets
17
+
18
+## Request contract
19
+Requires a current valid Supabase user JWT and the exact allowlisted user. Only POST and OPTIONS. Browsers accept only the actual Finora origins:
20
+- https://factoreasy.ir
21
+- https://davoodmehraban89.github.io
22
+
23
+Endpoint (no query parameters): `https://hcsixhqbyuhpshfwqpjx.supabase.co/functions/v1/finora-stripe-qa-read`.
24
+With an existing signed-in Supabase browser client, a development tester may invoke:
25
+```js
26
+const response = await sb.functions.invoke('finora-stripe-qa-read', { body: {} });
27
+console.log(response.data, response.error);
28
+```
29
+This example MUST NOT be treated as a production UI feature or embedded in normal customer workflows. It never inserts Finora invoices or books journal entries.
30
+
31
+## Reproducible tests
32
+```sh
33
+node scripts/stripe-edge-sandbox-test.mjs
34
+node scripts/stripe-sandbox-readonly-test.mjs
35
+node scripts/golden-accounting-core-check.mjs
36
+```
37
+All mock API traffic stays in process. Tests assert denied origins/verbs/missing config, exact authenticated allowlist, no live Stripe key, fixed invoice ID, sandbox status, amount, currency and line consistency.
38
+
39
+## Approval gates for a future real integration
40
+- Live Stripe account authorization is NOT granted by this sandbox connector.
41
+- Written decision on multi-company/tenant authorization, organization ownership, audit trail, idempotency, exchange rates, tax treatment and accounting posting rules.
42
+- Signed webhook verification, minimal backend permission roles, replay resistance and event-to-ledger reconciliation.
43
+- Review actual costs/eligibility before activating any production payment features.
scripts/stripe-edge-sandbox-test.mjs
new
+89
@@ -0,0 +1,89 @@
1
+import assert from 'node:assert/strict';
2
+import fs from 'node:fs';
3
+import { handleStripeQaPreview, QA_INVOICE_ID } from '../supabase/functions/finora-stripe-qa-read/handler.mjs';
4
+
5
+const sample = JSON.parse(fs.readFileSync('scripts/fixtures/stripe-sandbox-invoice-synthetic.json', 'utf8'));
6
+const allowed = '11111111-1111-4111-8111-111111111111';
7
+const other = '22222222-2222-4222-8222-222222222222';
8
+const envData = {
9
+ FINORA_STRIPE_QA_ALLOWED_USER_ID: allowed,
10
+ STRIPE_SANDBOX_RESTRICTED_KEY: 'rk_test_' + 'X'.repeat(28),
11
+ SUPABASE_URL: 'https://example-project.supabase.co',
12
+ SUPABASE_ANON_KEY: 'public-synthetic-anon-value',
13
+};
14
+const environment = data => name => (data || envData)[name];
15
+const createRequest = (origin = 'https://factoreasy.ir', method = 'POST', token = 'Bearer ' + 'mock-user-jwt-example-very-long') =>
16
+ new Request('https://edge.invalid/functions/v1/finora-stripe-qa-read', { method, headers: { Origin: origin, Authorization: token } });
17
+const mockedFetch = ({ user = allowed, invoice = sample, authStatus = 200, stripeStatus = 200 } = {}) => async (url, opts) => {
18
+ assert.equal(opts.method, 'GET');
19
+ if (url === 'https://example-project.supabase.co/auth/v1/user') {
20
+ assert.equal(opts.headers.apikey, envData.SUPABASE_ANON_KEY);
21
+ assert.equal(opts.headers.Authorization, 'Bearer mock-user-jwt-example-very-long');
22
+ return new Response(JSON.stringify({ id: user }), { status: authStatus });
23
+ }
24
+ assert.equal(url, 'https://api.stripe.com/v1/invoices/' + QA_INVOICE_ID);
25
+ assert.equal(opts.headers.Authorization, 'Bearer ' + envData.STRIPE_SANDBOX_RESTRICTED_KEY);
26
+ return new Response(JSON.stringify(invoice), { status: stripeStatus });
27
+};
28
+async function run(expectedStatus, { req = createRequest(), env = environment(), fetchImpl = mockedFetch() } = {}) {
29
+ const result = await handleStripeQaPreview(req, { env, fetchImpl });
30
+ assert.equal(result.status, expectedStatus);
31
+ assert.equal(result.headers.get('Cache-Control'), 'no-store, max-age=0');
32
+ const body = await result.json();
33
+ return { result, body };
34
+}
35
+let count = 0;
36
+const check = async (code, config) => { await run(code, config); count++; };
37
+const success = await run(200);
38
+assert.deepEqual(success.body.invoice, {
39
+ provider: 'stripe',
40
+ environment: 'sandbox',
41
+ reference: 'FINORA-QA-20261011-A',
42
+ invoiceId: QA_INVOICE_ID,
43
+ invoiceStatus: 'draft',
44
+ currency: 'USD',
45
+ amountMinor: 1250,
46
+ lineCount: 1,
47
+ ledgerPostingAllowed: false,
48
+});
49
+assert.equal(success.result.headers.get('Access-Control-Allow-Origin'), 'https://factoreasy.ir');
50
+assert.ok(!JSON.stringify(success.body).includes('cus_'));
51
+count++;
52
+
53
+const noNetwork = async () => { throw Error('network must not run'); };
54
+await check(503, { env: environment({ ...envData, STRIPE_SANDBOX_RESTRICTED_KEY: '' }), fetchImpl: noNetwork });
55
+await check(503, { env: environment({ ...envData, STRIPE_SANDBOX_RESTRICTED_KEY: 'rk_live_not_allowed' }), fetchImpl: noNetwork });
56
+await check(503, { env: environment({ ...envData, FINORA_STRIPE_QA_ALLOWED_USER_ID: '' }), fetchImpl: noNetwork });
57
+await check(503, { env: environment({ ...envData, FINORA_STRIPE_QA_ALLOWED_USER_ID: 'not-a-uuid' }), fetchImpl: noNetwork });
58
+await check(503, { env: environment({ ...envData, SUPABASE_ANON_KEY: '' }), fetchImpl: noNetwork });
59
+await check(503, { env: environment({ ...envData, SUPABASE_URL: 'https://not-supabase.example' }), fetchImpl: noNetwork });
60
+await check(403, { req: createRequest('https://evil.example'), fetchImpl: noNetwork });
61
+await check(405, { req: createRequest('https://factoreasy.ir', 'GET'), fetchImpl: noNetwork });
62
+await check(401, { req: createRequest('https://factoreasy.ir', 'POST', 'Bearer bad'), fetchImpl: noNetwork });
63
+await check(401, { fetchImpl: mockedFetch({ authStatus: 401 }) });
64
+await check(403, { fetchImpl: mockedFetch({ user: other }) });
65
+await check(502, { fetchImpl: mockedFetch({ stripeStatus: 403 }) });
66
+await check(502, { fetchImpl: async () => { throw Error('secret leak prohibited'); } });
67
+for (const mutate of [
68
+ x => { x.livemode = true; },
69
+ x => { x.status = 'paid'; },
70
+ x => { x.auto_advance = true; },
71
+ x => { x.metadata.finora_test_ref = 'wrong'; },
72
+ x => { x.amount_due = 1300; },
73
+ x => { x.currency = 'irr'; },
74
+ x => { x.lines.has_more = true; },
75
+ x => { x.lines.data[0].amount = 1249; },
76
+ x => { x.lines.data.push({ ...x.lines.data[0] }); },
77
+ x => { x.id = 'in_wrong'; },
78
+]) {
79
+ const copy = structuredClone(sample);
80
+ mutate(copy);
81
+ await check(502, { fetchImpl: mockedFetch({ invoice: copy }) });
82
+}
83
+const options = await run(200, { req: createRequest('https://factoreasy.ir', 'OPTIONS'), fetchImpl: noNetwork });
84
+assert.equal(options.result.headers.get('Access-Control-Allow-Methods'), 'POST, OPTIONS');
85
+count++;
86
+const untrustedOptions = await run(403, { req: createRequest('https://evil.example', 'OPTIONS'), fetchImpl: noNetwork });
87
+assert.equal(untrustedOptions.result.headers.get('Access-Control-Allow-Origin'), null);
88
+count++;
89
+console.log('PASS: Finora Stripe Edge function tested with', count, 'sandbox access and adversarial cases; no production writes');
supabase/functions/finora-stripe-qa-read/handler.mjs
new
+93
@@ -0,0 +1,93 @@
1
+// Fail-closed Finora Stripe QA gateway. ONLY a single synthetic sandbox draft can be read.
2
+// No Stripe write verbs, accounting record writes, service-role key, or customer PII in responses.
3
+export const QA_INVOICE_ID = 'in_1UPFYbGnbcoujdbeXnuN3Jf0';
4
+const QA_REFERENCE = 'FINORA-QA-20261011-A';
5
+const QA_AMOUNT_MINOR = 1250;
6
+const TRUSTED_ORIGINS = new Set(['https://factoreasy.ir', 'https://davoodmehraban89.github.io']);
7
+const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+const restrictedKey = /^rk_test_[a-zA-Z0-9]{12,}$/;
9
+const resourceId = /^in_[a-zA-Z0-9]+$/;
10
+const getEnv = (env, key) => (env(key) || '').trim();
11
+
12
+function respond(status, body, origin) {
13
+ const headers = {
14
+ 'Content-Type': 'application/json; charset=utf-8',
15
+ 'Cache-Control': 'no-store, max-age=0',
16
+ 'X-Content-Type-Options': 'nosniff',
17
+ 'Vary': 'Origin',
18
+ };
19
+ if (TRUSTED_ORIGINS.has(origin)) {
20
+ headers['Access-Control-Allow-Origin'] = origin;
21
+ headers['Access-Control-Allow-Headers'] = 'authorization, apikey, content-type, x-client-info';
22
+ headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS';
23
+ }
24
+ return new Response(JSON.stringify(body), { status, headers });
25
+}
26
+
27
+function safeInvoice(raw) {
28
+ if (!raw || raw.id !== QA_INVOICE_ID || !resourceId.test(raw.id)) throw Error('id');
29
+ if (raw.livemode !== false || raw.status !== 'draft' || raw.auto_advance !== false) throw Error('mode');
30
+ if (raw.metadata?.finora_qa !== 'true' || raw.metadata?.environment !== 'sandbox' || raw.metadata?.finora_test_ref !== QA_REFERENCE) throw Error('marker');
31
+ if (raw.currency !== 'usd' || raw.subtotal !== QA_AMOUNT_MINOR || raw.total !== QA_AMOUNT_MINOR || raw.amount_due !== QA_AMOUNT_MINOR) throw Error('amount');
32
+ if (!raw.lines || raw.lines.has_more !== false || !Array.isArray(raw.lines.data) || raw.lines.data.length !== 1) throw Error('lines');
33
+ const line = raw.lines.data[0];
34
+ if (!line || line.amount !== QA_AMOUNT_MINOR || (line.currency && line.currency !== 'usd')) throw Error('line-amount');
35
+ return {
36
+ provider: 'stripe',
37
+ environment: 'sandbox',
38
+ reference: QA_REFERENCE,
39
+ invoiceId: raw.id,
40
+ invoiceStatus: 'draft',
41
+ currency: 'USD',
42
+ amountMinor: QA_AMOUNT_MINOR,
43
+ lineCount: 1,
44
+ ledgerPostingAllowed: false,
45
+ };
46
+}
47
+
48
+export async function handleStripeQaPreview(request, { env, fetchImpl = fetch } = {}) {
49
+ const origin = request.headers.get('origin');
50
+ if (origin && !TRUSTED_ORIGINS.has(origin)) return respond(403, { error: 'origin_forbidden' }, origin);
51
+ if (request.method === 'OPTIONS') return respond(200, { ok: true }, origin);
52
+ if (request.method !== 'POST') return respond(405, { error: 'method_not_allowed' }, origin);
53
+
54
+ const userId = getEnv(env, 'FINORA_STRIPE_QA_ALLOWED_USER_ID');
55
+ const key = getEnv(env, 'STRIPE_SANDBOX_RESTRICTED_KEY');
56
+ const apiUrl = getEnv(env, 'SUPABASE_URL').replace(/\/+$/, '');
57
+ const supabaseKey = getEnv(env, 'SUPABASE_ANON_KEY');
58
+ // Both user allowlist and restricted sandbox key must be deliberately provisioned.
59
+ if (!uuid.test(userId) || !restrictedKey.test(key) || !apiUrl || !supabaseKey) {
60
+ return respond(503, { error: 'sandbox_gateway_not_configured' }, origin);
61
+ }
62
+ if (!/^https:\/\/[a-z0-9-]+\.supabase\.co$/.test(apiUrl)) {
63
+ return respond(503, { error: 'invalid_server_configuration' }, origin);
64
+ }
65
+ const bearer = request.headers.get('authorization') || '';
66
+ if (!/^Bearer [A-Za-z0-9._~-]{20,}$/.test(bearer)) return respond(401, { error: 'authentication_required' }, origin);
67
+
68
+ try {
69
+ // Live Supabase Auth identity lookup; never trust a client-supplied user ID or JWT claims alone.
70
+ const authResult = await fetchImpl(apiUrl + '/auth/v1/user', {
71
+ method: 'GET',
72
+ headers: { Authorization: bearer, apikey: supabaseKey, Accept: 'application/json' },
73
+ signal: AbortSignal.timeout(12000),
74
+ });
75
+ if (!authResult.ok) return respond(authResult.status === 401 || authResult.status === 403 ? 401 : 502, { error: 'authentication_failed' }, origin);
76
+ const user = await authResult.json();
77
+ if (!uuid.test(user?.id)) return respond(401, { error: 'authentication_failed' }, origin);
78
+ if (user.id.toLowerCase() !== userId.toLowerCase()) return respond(403, { error: 'sandbox_access_denied' }, origin);
79
+
80
+ // The only external financial request is a GET of the fixed, known QA draft.
81
+ const stripeResult = await fetchImpl('https://api.stripe.com/v1/invoices/' + QA_INVOICE_ID, {
82
+ method: 'GET',
83
+ headers: { Authorization: 'Bearer ' + key, Accept: 'application/json' },
84
+ signal: AbortSignal.timeout(12000),
85
+ });
86
+ if (!stripeResult.ok) return respond(502, { error: 'stripe_sandbox_read_failed' }, origin);
87
+ const preview = safeInvoice(await stripeResult.json());
88
+ return respond(200, { ok: true, invoice: preview }, origin);
89
+ } catch {
90
+ // No exception body or API key is ever reflected to the client or logs.
91
+ return respond(502, { error: 'sandbox_gateway_unavailable' }, origin);
92
+ }
93
+}
supabase/functions/finora-stripe-qa-read/index.ts
new
+7
@@ -0,0 +1,7 @@
1
+import { handleStripeQaPreview } from './handler.mjs';
2
+
3
+// Authentication is also enforced by Supabase platform: verify_jwt = true.
4
+Deno.serve((request: Request) => handleStripeQaPreview(request, {
5
+ env: (name: string) => Deno.env.get(name),
6
+ fetchImpl: fetch,
7
+}));