سامانه صدور فاکتور و حسابداری

test: verify Stripe sandbox invoice roundtrip and guard read-only adapter

Davood Mehraban committed Oct 11, 2026 at 09:19 UTC e57c77b98999313319825c95fb9af522d7ba1c13
6 files changed +204
.github/workflows/quality.yml
+2
@@ -24,6 +24,8 @@ jobs:
24 run: node scripts/quality-check.mjs
25 - name: Independent accounting integrity fixture
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: Commercial workspace and factory-reset invariants
30 run: node scripts/commercial-rnd-check.mjs
31 - name: UX commerce/settings R2 invariants
PROJECT_STATE.md
+7
@@ -153,3 +153,10 @@ Owner approved Iranian accounting standards as primary, with future internationa
153
154 2026-10-11 follow-up: GitHub PR #64 Quality and Security workflows succeeded. New accounting audit fixture added to quality workflow. Isolated public invoice-save debug blocked by null currentUser fixture, so save/reload remains unverified (not a confirmed application defect).
155
156 +
157 +## 2026-10-11 Stripe sandbox integration probe (requested)
158 +Owner confirmed connected Stripe plugin and requested completion of sandbox invoice create/read and safe Finora integration probe. Scope: Stripe test/sandbox only, read-only production boundaries, no payments, no actual customer contact, no exposed API keys, no Supabase schema/auth/data mutations. Decision: implement and verify bounded standalone integration/tests; record actual API results and connection blockers before claiming completion.
159 +
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 +
docs/STRIPE_SANDBOX_INTEGRATION_2026-10-11.md new
+41
@@ -0,0 +1,41 @@
1 +# Stripe sandbox invoice integration probe — 2026-10-11
2 +
3 +## Verified with the connected Stripe plugin (actual API operations)
4 +- Account: **Finora ERP sandbox**, `livemode=false`.
5 +- Created synthetic customer without an email address or payment method.
6 +- Created a **draft**, `auto_advance=false`, USD invoice; did not finalize, send, or charge.
7 +- Added one synthetic line for **USD 12.50 (1,250 cents)**.
8 +- Read invoice back by ID and through list endpoint. Stripe returned `status=draft`, `subtotal=total=amount_due=1250`, one line, `livemode=false`.
9 +- Verified Stripe invoice ID `in_1UPFYbGnbcoujdbeXnuN3Jf0` and marker `FINORA-QA-20261011-A`.
10 +- Initial attempt to create `send_invoice` without a customer email was **rejected by Stripe**; used `charge_automatically` plus `auto_advance=false`, with **no attached payment method**. No attempt to finalize or take payment.
11 +- Stripe ChatGPT plugin succeeded; this does **not** grant Finora's static Pages client or Supabase backend an API key.
12 +
13 +## Delivered repository-side acceptance gate
14 +- `scripts/stripe-sandbox-readonly.mjs`: server-side only, read-only GET adapter that rejects live keys, non-sandbox/non-draft/non-marked invoices, mismatched currency/amount/lines, and incomplete line pagination. It cannot create invoices or post accounting entries.
15 +- `scripts/stripe-sandbox-readonly-test.mjs`: deterministic positive and adversarial tests; uses a deliberately synthetic reconstruction of the observed sandbox invoice.
16 +- `scripts/fixtures/stripe-sandbox-invoice-synthetic.json`: **synthetic QA snapshot**, not a production/customer export.
17 +- CI invokes the tests; no secret or credential is stored in the repository.
18 +
19 +## Test locally without credentials
20 +```sh
21 +node scripts/stripe-sandbox-readonly-test.mjs
22 +node scripts/stripe-sandbox-readonly.mjs --fixture scripts/fixtures/stripe-sandbox-invoice-synthetic.json
23 +```
24 +
25 +## Optional DIRECT API connectivity test — still NOT VERIFIED
26 +The installed ChatGPT Stripe connection cannot be reused as a server credential. To test direct access from the Finora execution environment, an owner-controlled **restricted Stripe sandbox key** with only invoice-read scope must be provided via environment variable on a trusted server (never in Git, chat, GitHub Pages, or browser JS).
27 +```sh
28 +# Set the environment variable privately in the trusted server shell:
29 +node scripts/stripe-sandbox-readonly.mjs --live in_1UPFYbGnbcoujdbeXnuN3Jf0
30 +```
31 +Variable name: `STRIPE_SANDBOX_RESTRICTED_KEY`. The adapter accepts only `rk_test_` keys. The test cannot run until this server-only key is configured.
32 +
33 +## Full Finora integration boundaries (NOT IMPLEMENTED)
34 +- Require authenticated, authorized company-to-Stripe-account mapping stored **server-side**, with tenant-scoped verification and an auditable least-privilege role.
35 +- Enforce idempotent external invoice identifiers, reconciliation, event replay protection, signed webhooks, and controlled error/retry handling.
36 +- Never convert USD cents directly into IRR/toman journal rows. Apply explicit currency/exchange-rate policy and Iranian tax rules subject to accounting review.
37 +- Production Stripe financial writes, posting, Supabase schema/auth changes, protected key provisioning, and public release require separately reviewed scopes and safety checks.
38 +- ERPNext/Odoo/Beancount are **not** installed/connected by this Stripe test.
39 +
40 +## Acceptance
41 +Sandbox draft create/line append/read verified via plugin. Repository read-only adapter + fixture tests are separately checked by CI. A full production financial integration or authenticated tenant E2E **must not be claimed**.
scripts/fixtures/stripe-sandbox-invoice-synthetic.json new
+30
@@ -0,0 +1,30 @@
1 +{
2 + "id": "in_1UPFYbGnbcoujdbeXnuN3Jf0",
3 + "object": "invoice",
4 + "livemode": false,
5 + "status": "draft",
6 + "auto_advance": false,
7 + "currency": "usd",
8 + "customer": "cus_VQ5jO0GvKcuiQd",
9 + "subtotal": 1250,
10 + "total": 1250,
11 + "amount_due": 1250,
12 + "metadata": {
13 + "environment": "sandbox",
14 + "finora_qa": "true",
15 + "finora_test_ref": "FINORA-QA-20261011-A",
16 + "integration_test": "stripe_draft_roundtrip"
17 + },
18 + "lines": {
19 + "object": "list",
20 + "has_more": false,
21 + "data": [
22 + {
23 + "id": "il_1UPFYkGnbcoujdbe1RC94LS2",
24 + "amount": 1250,
25 + "currency": "usd",
26 + "description": "Synthetic QA service item"
27 + }
28 + ]
29 + }
30 +}
scripts/stripe-sandbox-readonly-test.mjs new
+47
@@ -0,0 +1,47 @@
1 +import assert from 'node:assert/strict';
2 +import fs from 'node:fs';
3 +import { normalizeStripeSandboxInvoice, readStripeSandboxInvoice } from './stripe-sandbox-readonly.mjs';
4 +
5 +const fixture = JSON.parse(fs.readFileSync('scripts/fixtures/stripe-sandbox-invoice-synthetic.json', 'utf8'));
6 +const valid = normalizeStripeSandboxInvoice(fixture);
7 +assert.equal(valid.totalMinor, 1250);
8 +assert.equal(valid.lineCount, 1);
9 +assert.equal(valid.sandbox, true);
10 +assert.equal(valid.safeForLedgerPosting, false);
11 +
12 +const bad = (change, message) => {
13 + const copy = structuredClone(fixture);
14 + change(copy);
15 + assert.throws(() => normalizeStripeSandboxInvoice(copy), new RegExp(message));
16 +};
17 +bad(v => v.livemode = true, 'LIVE_MODE_FORBIDDEN');
18 +bad(v => v.status = 'open', 'NON_DRAFT_OR_AUTOMATIC_INVOICE');
19 +bad(v => v.auto_advance = true, 'NON_DRAFT_OR_AUTOMATIC_INVOICE');
20 +bad(v => v.metadata.finora_test_ref = 'OTHER', 'REFERENCE_MISMATCH');
21 +bad(v => v.metadata.finora_qa = 'false', 'NOT_A_FINORA_SANDBOX_FIXTURE');
22 +bad(v => v.currency = 'irr', 'CURRENCY_MISMATCH');
23 +bad(v => v.total = 1200, 'INVOICE_TOTAL_MISMATCH');
24 +bad(v => v.amount_due = 1251, 'INVOICE_TOTAL_MISMATCH');
25 +bad(v => v.subtotal = 500, 'INVOICE_TOTAL_MISMATCH');
26 +bad(v => v.lines.data[0].amount = 1249, 'LINE_SUM_MISMATCH');
27 +bad(v => v.lines.has_more = true, 'LINES_NOT_FULLY_RETRIEVED');
28 +bad(v => v.lines.data.push({ ...v.lines.data[0] }), 'DUPLICATE_OR_INVALID_LINE');
29 +bad(v => v.lines.data = [], 'EMPTY_INVOICE_LINES');
30 +bad(v => v.lines.data[0].currency = 'eur', 'LINE_CURRENCY_MISMATCH');
31 +bad(v => v.total = -1, 'NEGATIVE_AMOUNT');
32 +
33 +await assert.rejects(readStripeSandboxInvoice('https://evil.test', 'rk_test_qa', () => { throw Error('network must not be used'); }), /INVALID_INVOICE_ID/);
34 +await assert.rejects(readStripeSandboxInvoice(fixture.id, 'sk_live_private', () => { throw Error('network must not be used'); }), /RESTRICTED_SANDBOX_KEY_REQUIRED/);
35 +await assert.rejects(readStripeSandboxInvoice(fixture.id, undefined, () => { throw Error('network must not be used'); }), /RESTRICTED_SANDBOX_KEY_REQUIRED/);
36 +let calls = 0;
37 +const data = await readStripeSandboxInvoice(fixture.id, 'rk_test_dummyonly', async (url, opts) => {
38 + calls++;
39 + assert.equal(url, `https://api.stripe.com/v1/invoices/${fixture.id}`);
40 + assert.equal(opts.method, 'GET');
41 + assert.equal(opts.headers.Authorization, 'Bearer rk_test_dummyonly');
42 + return { ok: true, status: 200, json: async () => fixture };
43 +});
44 +assert.equal(calls, 1);
45 +assert.deepEqual(data, valid);
46 +await assert.rejects(readStripeSandboxInvoice(fixture.id, 'rk_test_dummyonly', async () => ({ ok: false, status: 403 })), /STRIPE_HTTP_403/);
47 +console.log('PASS: sandbox-only read adapter + positive and adversarial checks; no writes or live credentials');
scripts/stripe-sandbox-readonly.mjs new
+77
@@ -0,0 +1,77 @@
1 +// Server-side, read-only Stripe sandbox evidence adapter. Never import in the public Finora UI.
2 +import fs from 'node:fs';
3 +import { fileURLToPath } from 'node:url';
4 +
5 +const STRIPE_API = 'https://api.stripe.com';
6 +const EXPECTED_REF = 'FINORA-QA-20261011-A';
7 +const requireValue = (condition, code) => { if (!condition) throw new Error(code); };
8 +
9 +export function normalizeStripeSandboxInvoice(raw, options = {}) {
10 + const expectedRef = options.expectedRef ?? EXPECTED_REF;
11 + const expectedAmount = options.expectedAmount ?? 1250;
12 + requireValue(raw && typeof raw === 'object', 'INVALID_INVOICE_OBJECT');
13 + requireValue(/^in_[a-zA-Z0-9]+$/.test(raw.id || ''), 'INVALID_INVOICE_ID');
14 + requireValue(raw.livemode === false, 'LIVE_MODE_FORBIDDEN');
15 + requireValue(raw.status === 'draft' && raw.auto_advance === false, 'NON_DRAFT_OR_AUTOMATIC_INVOICE');
16 + requireValue(raw.metadata?.finora_qa === 'true' && raw.metadata?.environment === 'sandbox', 'NOT_A_FINORA_SANDBOX_FIXTURE');
17 + requireValue(raw.metadata?.finora_test_ref === expectedRef, 'REFERENCE_MISMATCH');
18 + requireValue(raw.currency === 'usd', 'CURRENCY_MISMATCH');
19 + requireValue(Number.isSafeInteger(raw.amount_due) && Number.isSafeInteger(raw.subtotal) && Number.isSafeInteger(raw.total), 'INVALID_AMOUNT');
20 + requireValue(raw.amount_due >= 0 && raw.subtotal >= 0 && raw.total >= 0, 'NEGATIVE_AMOUNT');
21 + requireValue(raw.amount_due === raw.total && raw.total === raw.subtotal, 'INVOICE_TOTAL_MISMATCH');
22 + requireValue(raw.total === expectedAmount, 'UNEXPECTED_TEST_AMOUNT');
23 + requireValue(raw.lines?.has_more === false && Array.isArray(raw.lines.data), 'LINES_NOT_FULLY_RETRIEVED');
24 + requireValue(raw.lines.data.length > 0, 'EMPTY_INVOICE_LINES');
25 + const lineIds = new Set();
26 + const lines = raw.lines.data.map(line => {
27 + requireValue(typeof line.id === 'string' && !lineIds.has(line.id), 'DUPLICATE_OR_INVALID_LINE');
28 + lineIds.add(line.id);
29 + requireValue(Number.isSafeInteger(line.amount) && line.amount >= 0, 'INVALID_LINE_AMOUNT');
30 + requireValue(!line.currency || line.currency === raw.currency, 'LINE_CURRENCY_MISMATCH');
31 + return { id: line.id, amountMinor: line.amount, currency: raw.currency };
32 + });
33 + requireValue(lines.reduce((sum, line) => sum + line.amountMinor, 0) === raw.subtotal, 'LINE_SUM_MISMATCH');
34 + return {
35 + provider: 'stripe',
36 + sandbox: true,
37 + id: raw.id,
38 + reference: expectedRef,
39 + customerId: raw.customer,
40 + status: raw.status,
41 + currency: raw.currency,
42 + subtotalMinor: raw.subtotal,
43 + totalMinor: raw.total,
44 + lineCount: lines.length,
45 + lines,
46 + safeForLedgerPosting: false,
47 + note: 'Sandbox evidence only. Requires verified company mapping, exchange-rate policy and posting authorization.'
48 + };
49 +}
50 +
51 +export async function readStripeSandboxInvoice(id, key, fetchImpl = fetch) {
52 + requireValue(/^in_[a-zA-Z0-9]+$/.test(id || ''), 'INVALID_INVOICE_ID');
53 + // Restricted sandbox-only key; never pass in query strings, logs, or a public UI.
54 + requireValue(/^rk_test_[a-zA-Z0-9]+$/.test(key || ''), 'RESTRICTED_SANDBOX_KEY_REQUIRED');
55 + const response = await fetchImpl(`${STRIPE_API}/v1/invoices/${id}`, {
56 + method: 'GET',
57 + headers: { Authorization: `Bearer ${key}`, Accept: 'application/json' },
58 + signal: AbortSignal.timeout(15000)
59 + });
60 + requireValue(response && response.ok, `STRIPE_HTTP_${response?.status || 'FAILED'}`);
61 + return normalizeStripeSandboxInvoice(await response.json());
62 +}
63 +
64 +async function runCli() {
65 + const [mode, arg] = process.argv.slice(2);
66 + if (mode === '--fixture' && arg) {
67 + console.log(JSON.stringify(normalizeStripeSandboxInvoice(JSON.parse(fs.readFileSync(arg, 'utf8'))), null, 2));
68 + } else if (mode === '--live' && arg) {
69 + console.log(JSON.stringify(await readStripeSandboxInvoice(arg, process.env.STRIPE_SANDBOX_RESTRICTED_KEY), null, 2));
70 + } else {
71 + throw new Error('Usage: node scripts/stripe-sandbox-readonly.mjs --fixture file.json OR --live in_... (requires STRIPE_SANDBOX_RESTRICTED_KEY)');
72 + }
73 +}
74 +
75 +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
76 + runCli().catch(error => { console.error('Stripe sandbox probe failed:', error.message); process.exitCode = 1; });
77 +}