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

qa/finora-phase5-posted-insert-jwt-red-20261123
audit-remediation-wave3-4-20261002 audit-remediation-wave3-verify-20261002 audit-remediation-wave4-20261002 audit-remediation-wave4b-20261002 audit-remediation-wave5a-identity-20261002 audit-remediation-wave5b-offboarding-20261002 audit-remediation-wave5c-authorization-20261002 audit-security-intent-review-20261002 audit/finora-financial-core-20261115 audit/finora-master-prompt-phase0-20261016 audit/finora-stage3-legacy-source-readonly-20261023 audit/full-controls-20261030 audit/owner-live-state-reconcile-20261012 audit/owner-review-20261007 audit/phase1-live-permissions-readonly-20261013 audit/reconcile-live-state-20261006 audit/reconcile-state-20261002 audit/wp0-hardening-baseline-20261102 branding-login-favicon-20261002 c8-workflow-task1 c8-workflow-task2 c8-workflow-task3 chore/wave0-pages-gate-closeout claude-code-plugins-setup design/finora-c01-authoritative-source-draft-20261124 docs-wave4b-verified-20261002 docs/active-company-invoice-release-evidence-20261014 docs/agent-operating-model-20261114 docs/chart-taxpayer-release-evidence-20261004 docs/cloud-only-agent-orchestration-20261115 docs/confirm-finora-product-charter-20261115 docs/continuation-20261030 docs/d4a-verified docs/external-work-review-20261121 docs/finora-audit-continuity-20261014 docs/finora-backup-merge-evidence-20261014 docs/finora-ci-reconciliation-20261122 docs/finora-codex-master-prompt docs/finora-eight-phase-plan-20261011 docs/finora-f002-live-buyer-filter-verified-20261015 docs/finora-license-race-release-evidence-20261014 docs/finora-license-rollout-acceptance-20261015 docs/finora-phase0-repeat-and-pages-nav-verified-20261015 docs/finora-phase0-repeat-evidence-20261015 docs/finora-selectors-release-and-fixture-qa-20261015 docs/finora-stagea-pr240-ci-triage-20261123 docs/finora-test-license-live-pass-20261015 docs/finora-v2-m01-coverage-20261124 docs/handoff-charter-v2-20261124 docs/invoice-product-search-release-20261011 docs/invoice-workspace-release-20261007 docs/phase-status-20261031 docs/phase0-acceptance-release-evidence-20261012 docs/phase0-admin-provision-release-evidence-20261012 docs/phase0-core-bundle-owner-login-open-20261013 docs/phase0-duplicate-js-release-20261016 docs/phase0-f001-auth-rest-shared-timeout-20261013 docs/phase0-f001-owner-login-observed-20261013 docs/phase0-f001-second-device-fail-40s-20261013 docs/phase0-f003-release-verification-20261011 docs/phase0-f004-print-release-evidence-20261012 docs/phase0-f004-watermark-release-evidence-20261012 docs/phase0-f005-large-selector-release-20261012 docs/phase0-f005-release-evidence-20261012 docs/phase0-f006-dark-release-evidence-20261012 docs/phase0-f008-final-pr-closure-evidence-20261012 docs/phase0-f008-reconcile-stale-prs-20261012 docs/phase0-f107-production-evidence-20261012 docs/phase0-kavenegar-otp-preflight-release-20261012 docs/phase0-login-release-evidence-20261012 docs/phase0-login-rest-bootstrap-stage-release-20261012 docs/phase0-owner-app-assets-bundle-release-20261013 docs/phase0-owner-login-csp-release-20261012 docs/phase0-reconcile-postmerge-evidence-20261012 docs/phase0-site-probe-release-evidence-20261012 docs/phase0-startup-release-evidence-20261012 docs/phase3-treasury-release-evidence-20261014 docs/pilot-posted-correction-release-evidence-20261014 docs/pilot-purchase-correction-release-evidence-20261014 docs/print-persian-release-verification-20261011 docs/qa-ci-triage-218-20261122 docs/real-account-qa-20261030 docs/release-state-20261007 docs/seamless-amendment-release-20261014 docs/seamless-document-correction-release-20261014 docs/settings-login-release-20261025 docs/stripe-qa-deployment-evidence-20261011 docs/ux-f2-release-evidence-20261011 docs/ux-f2-release-verification-20261011 docs/wave0-closeout docs/wave2-closeout exec-phase1-architecture exec-phase1-implementation exec-phase1-qa exec-phase1-security-release exec-phase1-ux feat/accounting-document-draft-approval-20261011 feat/accounting-document-release-candidate-20261011 feat/active-company-strict-isolation-20261014 feat/admin-provisioning-reconciled-20261011 feat/admin-secure-user-provisioning-20261011 feat/admin-user-provisioning-merged-20261011 feat/d4a-request-work-queue feat/document-lifecycle-atf-20261118 feat/document-lifecycle-temp-permanent-atef feat/draft-first-attachment-lifecycle-216 feat/finora-offline-encrypted-backup-20261014 feat/finora-phase-a-navigation-20261023 feat/finora-stripe-sandbox-edge-gate feat/immutable-attachment-temporary-vouchers feat/iran-accounting-design-audit feat/journal-document-lifecycle-20261118 feat/journal-rpc-repository-adapter-20261117 feat/office-c7-fulltext-ocr-provenance feat/password-recovery-admin-reset-20261025 feat/pilot-expense-income-inplace-amendment-20261014 feat/pilot-journal-invoice-correction-20261014 feat/pilot-purchase-correction-20261014 feat/pilot-treasury-unallocated-correction-20261014 feat/retain-document-editor-after-save-20261014 feat/seamless-financial-document-correction-20261014 feat/slice-b-tenant-rbac feat/stripe-sandbox-invoice-probe feature/accounting-core-p0 feature/accounting-product-guidance feature/admin-identity-phone-auth feature/commercial-rnd feature/finora-phase1a-supabase-cli-20261016 feature/finora-stage2-manual-canary-20261017 feature/finora-stage3-commercial-payload-20261023 feature/finora-stage3-enforce-invoice-rpc-20261023 feature/finora-stage3-enforce-purchase-red-20261023 feature/invoice-workspace-cleanup feature/phase0-kavenegar-otp-preflight-20261012 feature/ux-commerce-settings-r2 fix-shell-scroll-live-cache-20261002 fix-shell-scrollbar-explicit-ownership-20261002 fix-shell-scrollbar-ownership-20261002 fix-shell-scrollbar-right-edge-20261002 fix/about-bug-report-20261114 fix/active-company-invoice-scope-20261014 fix/active-company-isolation-reconcile-20261014 fix/admin-central-password-reset-20261028 fix/auth-network-diagnostics fix/chart-taxpayer-reference-20261003 fix/combobox-enter-reliability fix/combobox-live-search fix/combobox-production-cache fix/combobox-release-asset-v2 fix/company-edit-action-20261028 fix/company-edit-pilot-delete-20261014 fix/company-form-action-state-20261014 fix/company-form-action-state-rebased-20261014 fix/contact-operational-balance-20261111 fix/dark-theme-contrast fix/financial-lifecycle-recovery-20261124 fix/finora-accounting-test-organization-readiness-20261015 fix/finora-b01-safe-org-switch-20261124 fix/finora-b02-sync-recovery-20261124 fix/finora-b03-conflict-review-20261124 fix/finora-org-license-bootstrap-race-20261014 fix/finora-stage3-posted-source-immutable-20261023 fix/finora-v2-b03-r2-qa-20261124 fix/finora-v2-b03-r3-readonly-20261124 fix/g01-asof-financial-position-20261128 fix/invoice-product-search-rehydrate-20261011 fix/invoice-search-cache-bust fix/issue229-linked-draft-status-20261122 fix/login-assets-retry-20261014 fix/login-inert-startup-20261110 fix/login-member-access-20261101 fix/login-resilience-20261017 fix/login-short-viewport-20261028 fix/login-startup-readiness-20261024 fix/navigation-utilities-placement-20261105 fix/office-c7-source-ref-binding fix/office-c7-source-ref-binding-v2 fix/owner-login-network-20261026 fix/password-recovery-invalid-cancel-20261026 fix/payment-amount-format-20261111 fix/phase0-admin-provision-seat-bootstrap-20261012 fix/phase0-auth-bundled-assets-for-unstable-isp-20261013 fix/phase0-auth-handler-binding-stalled-session-20261012 fix/phase0-login-context-stage-visibility-20261012 fix/phase0-login-single-local-bundle-20261013 fix/phase0-login-site-probe-clarity-20261012 fix/phase0-login-ui-ready-20261012 fix/phase0-modal-dashboard-drill-20261011 fix/phase0-pages-blocking-core-bundles-20261013 fix/phase0-print-no-draft-watermark-20261012 fix/phase0-startup-parallel-asset-load-20261012 fix/phase3-behavioral-verification fix/preserve-pending-edits-20261121 fix/print-persian-digit-consistency-20261011 fix/recovery-login-startup-20261027 fix/report-opening-balance-release-20261130 fix/settings-checkbox-persistence-20261024 fix/taxpayer-arithmetic-20261004 fix/ux-keyboard-search-f2-20261011 fix/wave2-request-input-integrity hardening/c01-source-draft-20261129 hardening/global-draft-conversion-20261113 hardening/wp1-ledger-integrity-20261102 integration/finora-execution-20261124 integration/issue229-ui-qa-20261122 integration/wp1-ledger-core-20261115 integration/wp2-manual-journal-rpc-20261116 main ops-heartbeat-v2-20261002 ops-progress-heartbeat-rule-20261002 ops/wave4-production-20261003 plan/financial-core-phase1-approval-20261016 qa/attachment-allocator-two-session-20261122 qa/draft-first-save-red-evidence-20261122 qa/finora-autopost-retry-identity-red-20261122 qa/finora-identity-rpc-security-tripwire-20261122 qa/finora-issue223-manual-kardex-browser-red-20261123 qa/finora-issue223-stock-real-jwt-20261123 qa/finora-issue238-inventory-count-browser-red-20261123 qa/finora-issue238-save-browser-red-20261122 qa/finora-login-cors-header-preflight-20261025 qa/finora-phase0-saved-session-repeat-20261015 qa/finora-phase5-posted-insert-jwt-red-20261123 qa/finora-stage3-ui-jwt-autopost-20261023 qa/finora-v2-g01-report-reconciliation-20261125 qa/free-supabase-local-wp2-20261116 qa/issue229-approval-boundary-jwt-20261122 qa/issue229-sale-save-linked-draft-red-20261122 qa/phase0-acceptance-start-20261012 qa/phase0-f005-account-project-contract-stress-20261012 qa/phase0-f005-selector-stress-20261012 qa/phase0-f006-dark-contrast-20261012 qa/post-wave4-verification-20261003 qa/posted-source-immutable-jwt-20261122 qa/pr219-wp1-disposable-dburl-proof-20261123 qa/purchase-source-jwt-20261122 qa/real-settings-acceptance-20261025 qa/recovery-mail-acceptance-20261026 qa/source-autopost-jwt-atomicity-20261122 qa/wave0-negative-gate-proof qa/wp2-auth-tenant-e2e-20261117 qa/wp2-authorized-journal-write-20261122 qa/wp2-financial-paths-reconciliation-20261122 qa/wp3-financial-tenant-isolation-20261117 remediation/wave0-liveqa-wave1 remediation/wave2-request-integrity staging/finora-stage22-free-20261022 state-scroll-verified-20261002 state-wave4b-production-20261002 state-wave5a-production-20261002 test/finora-accounting-boot-readiness-20261015 test/finora-f0-02-production-selectors-20261015 test/finora-pages-commerce-event-wiring-20261015 test/finora-pages-invoice-selectors-readonly-20261015 test/finora-stage3-jwt-source-post-20261023 test/phase0-invoice-fixture-bootstrap-20261016 test/phase0-invoice-persistence-20261011 test/phase0-pages-delayed-dispatcher-20261016 ux-scroll-ownership-20261002 work/finora-stage3-enforce-purchase-green-20261023 work/finora-stage3-enforce-sale-green-20261023 work/finora-stage3-payload-green-20261023
mjs 230 lines 14 KB
Raw
1 import assert from 'node:assert/strict';
2 import {spawnSync} from 'node:child_process';
3
4 // Issue223: real Auth-issued JWT / PostgREST against disposable local WP2 ONLY.
5 // Proves organization/company row scopes and posted-source immutability;
6 // NOT the active-company UI read model, stock approval, valuation, or live-host security.
7 const api=String(process.env.API_URL||'').replace(/\/$/,'');
8 const anon=process.env.ANON_KEY,service=process.env.SERVICE_ROLE_KEY,db=process.env.DB_URL;
9 for(const [key,value] of Object.entries({API_URL:api,ANON_KEY:anon,SERVICE_ROLE_KEY:service,DB_URL:db}))
10 assert.ok(value,'missing disposable WP2 environment setting: '+key);
11 for(const [name,url] of [['API_URL',api],['DB_URL',db]]){
12 const host=new URL(url).hostname.toLowerCase();
13 assert.ok(['localhost','127.0.0.1','::1','[::1]'].includes(host),
14 'FINORA_ISSUE223_NONLOCAL_BLOCK: '+name+' must be local');
15 }
16 const suffix=Date.now()+'-'+crypto.randomUUID().slice(0,8);
17 const quote=value=>"'"+String(value).replaceAll("'","''")+"'";
18 function sql(statement){
19 const p=spawnSync('psql',[db,'-X','-v','ON_ERROR_STOP=1','-c',statement],{encoding:'utf8'});
20 assert.equal(p.status,0,'disposable fixture SQL error: '+(p.stderr||p.stdout).slice(-700));
21 }
22 async function createUser(label){
23 const email='finora-qa223-'+label+'-'+suffix+'@example.test';
24 const password='QA-'+crypto.randomUUID()+'-Aa9!';
25 const response=await fetch(api+'/auth/v1/admin/users',{
26 method:'POST',headers:{apikey:service,Authorization:'Bearer '+service,'Content-Type':'application/json'},
27 body:JSON.stringify({email,password,email_confirm:true,user_metadata:{username:'q223'+label+Date.now()}})
28 });
29 const data=await response.json();
30 assert.equal(response.status,200,'disposable test-user fixture '+label+' failed');
31 assert.ok(data.id,'Auth missing fixture user ID');
32 return {id:data.id,email,password};
33 }
34 async function login(user){
35 const r=await fetch(api+'/auth/v1/token?grant_type=password',{
36 method:'POST',headers:{apikey:anon,'Content-Type':'application/json'},
37 body:JSON.stringify({email:user.email,password:user.password})
38 });
39 const data=await r.json();
40 assert.equal(r.status,200,'disposable Auth login failed');
41 assert.equal(data.user?.id,user.id,'Auth JWT user ID mismatch');
42 assert.ok(data.access_token,'missing genuine Auth JWT');
43 return data.access_token;
44 }
45 async function rest(path,jwt,init={}){
46 return fetch(api+'/rest/v1/'+path,{
47 ...init,headers:{apikey:anon,Authorization:'Bearer '+jwt,...(init.headers||{})}
48 });
49 }
50 function record(organizationId,ownerId,collection,id,data){
51 return '('+[quote(organizationId),quote(ownerId),quote(collection),quote(id),
52 quote(JSON.stringify(data))+'::jsonb'].join(',')+')';
53 }
54 const path=(collection,id)=>'records?select=id,collection,organization_id,data,version&collection=eq.'+
55 encodeURIComponent(collection)+'&id=eq.'+encodeURIComponent(id);
56 async function rows(collection,id,jwt){
57 const r=await rest(path(collection,id),jwt);
58 assert.equal(r.status,200,'readback must return status 200: '+collection);
59 return r.json();
60 }
61 async function attemptForeignDelete(collection,id,organizationId,jwt){
62 const r=await rest('records?organization_id=eq.'+organizationId+
63 '&collection=eq.'+collection+'&id=eq.'+encodeURIComponent(id),jwt,{
64 method:'DELETE',headers:{Prefer:'return=representation'}
65 });
66 assert.ok([200,204].includes(r.status),'foreign delete unexpected HTTP '+r.status);
67 assert.deepEqual(await r.json().catch(()=>[]),[],'cross-tenant DELETE returned a modified row');
68 }
69 async function attemptForeignPatch(collection,id,organizationId,jwt){
70 const r=await rest('records?organization_id=eq.'+organizationId+
71 '&collection=eq.'+collection+'&id=eq.'+encodeURIComponent(id),jwt,{
72 method:'PATCH',headers:{'Content-Type':'application/json',Prefer:'return=representation'},
73 body:JSON.stringify({data:{status:'draft',companyId:'QA_FORGED',qty:999}})
74 });
75 assert.ok([200,204].includes(r.status),'foreign update unexpected HTTP '+r.status);
76 assert.deepEqual(await r.json().catch(()=>[]),[],'cross-tenant UPDATE returned a modified row');
77 }
78 async function attemptOwnPostedMutation(collection,id,jwt,oldData){
79 const target='records?collection=eq.'+collection+'&id=eq.'+encodeURIComponent(id);
80 const patched={...oldData,status:'draft',qty:999,actualQty:999};
81 const update=await rest(target,jwt,{method:'PATCH',
82 headers:{'Content-Type':'application/json',Prefer:'return=representation'},
83 body:JSON.stringify({data:patched})});
84 assert.ok(!update.ok,'FINORA_ISSUE223_POSTED_UPDATE_ALLOWED: '+collection+' HTTP '+update.status);
85 const deletion=await rest(target,jwt,{method:'DELETE',
86 headers:{Prefer:'return=representation'}});
87 assert.ok(!deletion.ok,'FINORA_ISSUE223_POSTED_DELETE_ALLOWED: '+collection+' HTTP '+deletion.status);
88 }
89 const users=[];
90 try{
91 const [a,b,c]=await Promise.all([createUser('a'),createUser('b'),createUser('c')]);
92 users.push(a,b,c);
93 const orgA=crypto.randomUUID(),orgB=crypto.randomUUID(),memberA=crypto.randomUUID();
94 const ca1='QA223_CO_A1_'+suffix,ca2='QA223_CO_A2_'+suffix,cb='QA223_CO_B_'+suffix;
95 const whA1='QA223_WH_A1_'+suffix,whA2='QA223_WH_A2_'+suffix,whB='QA223_WH_B_'+suffix;
96 const product='QA223_PRODUCT_'+suffix;
97 const movementA1='QA223_MOV_A1_'+suffix,movementA2='QA223_MOV_A2_'+suffix;
98 const movementB='QA223_MOV_B_'+suffix,countA='QA223_COUNT_A_'+suffix,countA2='QA223_COUNT_A2_'+suffix,countB='QA223_COUNT_B_'+suffix;
99 const movementData=(uid,companyId,warehouseId,qty)=>({
100 ownerUserId:uid,companyId,warehouseId,productId:product,qty,unitCost:50,
101 kind:'adjustment_in',status:'posted',date:'1405/07/21',
102 postedAt:'2026-11-20T08:00:00.000Z'
103 });
104 const countData=(uid,companyId,warehouseId,qty)=>({
105 ownerUserId:uid,companyId,warehouseId,productId:product,
106 expectedQty:qty,actualQty:qty,diff:0,status:'posted',
107 date:'1405/07/21',postedAt:'2026-11-20T08:00:00.000Z'
108 });
109 const mvA1=movementData(a.id,ca1,whA1,5),mvA2=movementData(a.id,ca2,whA2,3);
110 const mvB=movementData(b.id,cb,whB,7);
111 const coA=countData(a.id,ca1,whA1,5),coA2=countData(a.id,ca2,whA2,3),coB=countData(b.id,cb,whB,7);
112 sql('insert into public.organizations(id,owner_user_id,name) values '+
113 '('+quote(orgA)+','+quote(a.id)+','+quote('QA223 org A')+'),'+
114 '('+quote(orgB)+','+quote(b.id)+','+quote('QA223 org B')+');'+
115 'update public.licenses set organization_id='+quote(orgA)+',max_companies=2,max_users=2 where user_id='+quote(a.id)+';'+
116 'update public.licenses set organization_id='+quote(orgB)+' where user_id='+quote(b.id)+';'+
117 'insert into public.organization_members(organization_id,user_id,status,is_owner) values '+
118 '('+quote(orgA)+','+quote(a.id)+','+quote('active')+',true),'+
119 '('+quote(orgB)+','+quote(b.id)+','+quote('active')+',true);');
120 // A real non-owner member receives only inventory:read for company A1.
121 // The disposable organization license permits exactly owner A + member C.
122 sql('insert into public.organization_members(id,organization_id,user_id,status,is_owner) values ('+
123 quote(memberA)+','+quote(orgA)+','+quote(c.id)+','+quote('active')+',false);');
124 sql('insert into public.member_module_permissions(organization_id,member_id,module_key,capabilities,scope_type,scope_id,confidentiality_level) values ('+
125 quote(orgA)+','+quote(memberA)+','+quote('inventory')+",array['read']::text[],"+quote('company')+','+quote(ca1)+',0);');
126 // The disposable fixture needs A's two companies: default license capacity is 1.
127 // Raise only A's local test license to 2, without bypassing its DB trigger.
128 const seed=[
129 [orgA,a.id,'companies',ca1,{name:'Company A1'}],
130 [orgA,a.id,'companies',ca2,{name:'Company A2'}],
131 [orgB,b.id,'companies',cb,{name:'Company B'}],
132 [orgA,a.id,'warehouses',whA1,{companyId:ca1,code:'WA1',name:'Warehouse A1',active:true}],
133 [orgA,a.id,'warehouses',whA2,{companyId:ca2,code:'WA2',name:'Warehouse A2',active:true}],
134 [orgB,b.id,'warehouses',whB,{companyId:cb,code:'WB1',name:'Warehouse B',active:true}],
135 [orgA,a.id,'products',product,{name:'QA223 product',code:'QA223'}],
136 [orgB,b.id,'products',product,{name:'QA223 product',code:'QA223'}],
137 [orgA,a.id,'stockMovements',movementA1,mvA1],
138 [orgA,a.id,'stockMovements',movementA2,mvA2],
139 [orgB,b.id,'stockMovements',movementB,mvB],
140 [orgA,a.id,'inventoryCounts',countA,coA],
141 [orgA,a.id,'inventoryCounts',countA2,coA2],
142 [orgB,b.id,'inventoryCounts',countB,coB]
143 ];
144 sql('insert into public.records(organization_id,owner_id,collection,id,data) values '+
145 seed.map(row=>record(...row)).join(',')+';');
146 const [jwtA,jwtB,jwtC]=await Promise.all([login(a),login(b),login(c)]);
147 for(const [collection,aid,a2id,bid,oldData,oldData2] of [
148 ['stockMovements',movementA1,movementA2,movementB,mvA1,mvA2],
149 ['inventoryCounts',countA,countA2,countB,coA,coA2]
150 ]){
151 const own=await rows(collection,aid,jwtA);
152 assert.equal(own.length,1,'A JWT cannot see own '+collection);
153 assert.deepEqual(own[0].data,oldData,'own posted '+collection+' fixture mismatch');
154 const ownerA2=await rows(collection,a2id,jwtA);
155 assert.equal(ownerA2.length,1,'organization owner cannot see company A2 '+collection);
156 assert.deepEqual(ownerA2[0].data,oldData2,'owner A2 '+collection+' fixture mismatch');
157 assert.deepEqual(await rows(collection,aid,jwtB),[],
158 'FINORA_ISSUE223_CROSS_ORG_READ_BYPASS: B JWT read A '+collection);
159 assert.equal((await rows(collection,bid,jwtB)).length,1,
160 'B JWT cannot see own '+collection);
161 assert.deepEqual(await rows(collection,bid,jwtA),[],
162 'FINORA_ISSUE223_CROSS_ORG_READ_BYPASS: A JWT read B '+collection);
163 const scopedA1=await rows(collection,aid,jwtC);
164 assert.equal(scopedA1.length,1,'company-scoped C cannot read A1 '+collection);
165 assert.deepEqual(scopedA1[0].data,oldData,'C read unexpected A1 '+collection+' data');
166 assert.deepEqual(await rows(collection,a2id,jwtC),[],
167 'FINORA_ISSUE223_COMPANY_SCOPE_BYPASS: C read same-org company A2 '+collection);
168 assert.deepEqual(await rows(collection,bid,jwtC),[],
169 'FINORA_ISSUE223_COMPANY_SCOPE_CROSS_ORG_BYPASS: C read foreign org '+collection);
170 const injected=await rest('records?select=id',jwtB,{
171 method:'POST',headers:{'Content-Type':'application/json',Prefer:'return=representation'},
172 body:JSON.stringify({organization_id:orgA,owner_id:b.id,collection,
173 id:'QA223_INJECT_'+collection+'_'+suffix,data:{...oldData,status:'draft'}})
174 });
175 assert.ok([401,403].includes(injected.status),
176 'FINORA_ISSUE223_FOREIGN_INSERT_ALLOWED: '+collection+' HTTP '+injected.status);
177 await attemptForeignPatch(collection,aid,orgA,jwtB);
178 await attemptForeignDelete(collection,aid,orgA,jwtB);
179 await attemptForeignPatch(collection,aid,orgA,jwtC);
180 await attemptForeignDelete(collection,aid,orgA,jwtC);
181 await attemptForeignPatch(collection,a2id,orgA,jwtC);
182 await attemptForeignDelete(collection,a2id,orgA,jwtC);
183 assert.deepEqual((await rows(collection,aid,jwtA))[0].data,oldData,
184 'foreign JWT changed or removed posted '+collection);
185 await attemptOwnPostedMutation(collection,aid,jwtA,oldData);
186 assert.deepEqual((await rows(collection,aid,jwtA))[0].data,oldData,
187 'FINORA_ISSUE223_POSTED_IMMUTABILITY_BYPASS: '+collection);
188 }
189 // Read-only must not create either supported stock source collection.
190 for(const [collection,data] of [
191 ['stockMovements',movementData(c.id,ca1,whA1,1)],
192 ['inventoryCounts',countData(c.id,ca1,whA1,1)]
193 ]){
194 const readOnlyCreateId='QA223_READONLY_CREATE_'+collection+'_'+suffix;
195 const readOnlyCreate=await rest('records?select=id',jwtC,{
196 method:'POST',headers:{'Content-Type':'application/json',Prefer:'return=representation'},
197 body:JSON.stringify({organization_id:orgA,owner_id:c.id,collection,id:readOnlyCreateId,data})
198 });
199 assert.ok([401,403].includes(readOnlyCreate.status),
200 'FINORA_ISSUE223_READONLY_CREATE_ALLOWED: '+collection+' inventory:read member HTTP '+readOnlyCreate.status);
201 assert.deepEqual(await rows(collection,readOnlyCreateId,jwtA),[],
202 'read-only inventory member created '+collection);
203 }
204 // Owners have organization-wide scope and legitimately see A1/A2. A delegated
205 // member with company scope A1 sees A1 only; neither result is the UI selector.
206 // Client active-company Kardex filtering remains a separate product acceptance gate.
207 const sameOrg=await rows('stockMovements',movementA2,jwtA);
208 assert.equal(sameOrg.length,1,'authorized same-org owner must see company A2');
209 assert.equal(sameOrg[0].data.companyId,ca2);
210 assert.equal((await rows('inventoryCounts',countA2,jwtA)).length,1,
211 'organization owner must see company A2 inventory count');
212 assert.deepEqual(await rows('stockMovements',movementA2,jwtB),[],
213 'foreign organization can see A2 stock movement');
214 const crossOrg=await rest('records?select=id,data&collection=eq.stockMovements',jwtA);
215 assert.equal(crossOrg.status,200);
216 const orgRows=await crossOrg.json();
217 assert.deepEqual(orgRows.map(x=>x.id).sort(),[movementA1,movementA2].sort(),
218 'A JWT stock records must include authorized A1/A2 and exclude B');
219 const scopedRows=await rest('records?select=id&collection=eq.stockMovements',jwtC);
220 assert.equal(scopedRows.status,200);
221 assert.deepEqual((await scopedRows.json()).map(x=>x.id),[movementA1],
222 'company-scoped inventory:read JWT must return only A1 rows');
223 console.log('WP2_PHASE5_STOCK_JWT_ISOLATION_PASS: Auth-issued JWT A/B read, forbidden cross-org insert/update/delete, readback unchanged for posted stockMovements/inventoryCounts; owner A sees A1/A2.');
224 console.log('WP2_PHASE5_POSTED_IMMUTABILITY_PASS: posted stockMovements and inventoryCounts reject same-owner JWT data PATCH and DELETE; original rows intact.');
225 console.log('WP2_PHASE5_COMPANY_SCOPE_JWT_PASS: real Auth-issued non-owner C with inventory:read scoped to company A1 reads A1 stock/count rows and cannot read same-org A2 or foreign-org B.');
226 console.log('WP2_PHASE5_READ_ONLY_MEMBER_CAPABILITY_PASS: scoped inventory:read member cannot create, patch or delete stock/count records; source readback unchanged.');
227 console.log('WP2_PHASE5_ACTIVE_COMPANY_NOT_RLS_SCOPE: owner A legitimately sees A1/A2; delegated company-scoped C sees A1 only. PR242 active-company Kardex/UI filter remains a separate product P0.');
228 }finally{
229 console.log('WP2_PHASE5_QA_DISPOSABLE: '+users.length+' temporary Auth fixture users; disposable local Supabase workflow handles teardown.');
230 }