@davoodmehraban89 / Factor-easy / commits / d13498f
Fork 0

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

Requests: close F-412 and harden Wave 3 replay

* State: record remediation continuation request * Requests: close F-412 and harden Wave 3 replay

davoodmehraban89 committed Oct 2, 2026 at 09:59 UTC d13498f3af03f544c05168727b440f053de1d733
6 files changed +360
.github/workflows/quality.yml
+8
@@ -178,6 +178,10 @@ jobs:
178 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261001224500_request_workflow_d2_fk_indexes.sql
179 - name: Execute D2 legacy cutover assertions
180 run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_d2_legacy_behavior.sql
181 + - name: Apply F-412 deterministic duplicate-code guard
182 + run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002070000_request_wave2_duplicate_code_guard.sql
183 + - name: Execute F-412 duplicate-code adversarial assertion
184 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_wave2_duplicate_code_guard.sql
185 - name: Apply D3a step runtime
186 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261001230000_request_workflow_d3a_step_runtime.sql
187 - name: Execute D3a sequential and parallel workflow assertions
@@ -200,6 +204,10 @@ jobs:
204 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002000500_request_workflow_d3c_escalation_conflict_fix.sql
205 - name: Execute D3c operational assertions
206 run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_d3c_operations.sql
207 + - name: Apply Wave 3 decision replay hardening
208 + run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002071000_request_wave3_decision_idempotency.sql
209 + - name: Execute Wave 3 replay authorization and stability assertions
210 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_wave3_decision_idempotency.sql
211 - name: Apply D4a authorized work queue
212 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002033000_request_workflow_d4a_work_queue.sql
213 - name: Execute D4a work queue assertions
PROJECT_STATE.md
+1
@@ -14,6 +14,7 @@ This is high-assurance accounting/ERP software. Posted financial history, tenant
14 ## Current change ledger
15 | Date | Request / decision | Status | Evidence / next action |
16 |---|---|---|---|
17 +| 2026-10-02 | Owner supplied the current remediation/audit package plus manual GitHub QA workflow and directed continuation of both roadmap execution and defect remediation. | **IMPLEMENTED ON REMEDIATION BRANCH / NOT YET VERIFIED** | Live production preflight found zero same-org duplicate legacy request-type codes. Added F-412 explicit duplicate-code abort/report guard plus adversarial two-owner/same-org test; added Wave 3 F-415/F-416 decision replay hardening that reauthorizes and actor-binds replay and reconstructs the original immutable response from event evidence. Quality DB job now applies both migrations/tests. CI, merge and production application are still NOT VERIFIED. Next: open PR, pass protected CI, then apply/reconcile migrations before closing findings. |
18 | 2026-10-02 | Owner directed immediate continuation after observing execution delay. | **D4A IMPLEMENTED / PRODUCTION + DISPOSABLE-DB + REAL-DOM + ACCOUNTING + SECURITY VERIFIED** | PR #21 merged as `4583703396a7ddb00bdad76b52c22932d634cbef`. Main Quality `36961361891` SUCCESS (38/38 real-DOM, accounting phases 2–6 + Golden, D1/C8 DB); Security `36961361897` SUCCESS; Release gate `36961459328` SUCCESS; gated Pages `36961492170` SUCCESS. Production migration `20261002034311 request_workflow_d4a_work_queue` reconciled. Evidence: `docs/REQUEST_WORKFLOW_D4A_VERIFICATION.md`. |\n| 2026-10-02 | Owner switched GitHub Pages source to **GitHub Actions** after the gated Pages workflow was installed. | **WAVE 0 COMPLETED / POSITIVE + NEGATIVE CONTROLS VERIFIED** | Negative control: failing SHA `03561a3369130a7aaba689474d92aa3e93137404` on PR #15 failed required `static-quality`, could not merge, and produced no Release gate / gated Pages deployment. Positive control: protected-main SHA `150ff54d938a45b9a9b476f3a4a8fdabbb45d065` passed Quality `36932956964`, Security `36932956877`, exact-SHA Release gate `36933115365`, then gated Pages deploy `36933151878`; no legacy dynamic branch Pages deployment appeared. F-402/F-403/F-406/F-407/F-423/F-424 are closed at the verified GitHub/repository boundary. |
19 | 2026-10-02 | Wave 2 request integrity remediation F-411/F-413/F-414/F-417/F-418. | **IMPLEMENTED / PRODUCTION + DISPOSABLE-DB + REAL-DOM + ACCOUNTING + SECURITY VERIFIED** | Squash merge `7346910638b6ef9555d4adb5952dd62c8f4c130d` from PR #19. PR Quality `36937247798`: DB jobs SUCCESS and 37/37 real-DOM tests passed; accounting phases + Golden journey passed. PR Security `36937247803`: required Release/QA invariants + CodeQL SUCCESS (Dependency review remains the documented external graph boundary). Main Quality `36937448157` SUCCESS; Security `36937448101` SUCCESS; exact-SHA Release gate `36937598497` SUCCESS; gated Pages `36937616201` SUCCESS. Production migration recorded as `20261001225044 request_wave2_integrity_hardening`; live validator negative controls and function-contract checks passed. |
20 | 2026-10-02 | Live Supabase target `hcsixhqbyuhpshfwqpjx` became available to the connector; owner directed immediate continuation. | **WAVE 1 PRODUCTION RECONCILED / WAVE 2 STARTED** | Production migration history and live `request_transition_instance` definitions were inspected read-only. F-409/F-410 guard is present in production; next slice is F-411/F-413/F-414/F-417/F-418 with server validation, form-runtime fidelity, idempotency binding, active/latest-version enforcement and schema-bound conditions. |
supabase/migrations/20261002070000_request_wave2_duplicate_code_guard.sql new
+38
@@ -0,0 +1,38 @@
1 +-- Wave 2 remainder / F-412: deterministic legacy request-type collision guard.
2 +-- The historical D2 cutover is preserved. This guard makes any ambiguous same-org
3 +-- legacy code fail explicitly instead of allowing the full migration chain to
4 +-- complete after ON CONFLICT DO NOTHING has collapsed business identities.
5 +
6 +create or replace function private.assert_legacy_request_type_code_uniqueness()
7 +returns void
8 +language plpgsql
9 +security invoker
10 +set search_path=''
11 +as $$
12 +declare
13 + v_collision record;
14 +begin
15 + select
16 + r.organization_id,
17 + upper(trim(r.data->>'code')) as normalized_code,
18 + array_agg(r.id order by r.id) as record_ids
19 + into v_collision
20 + from public.records r
21 + where r.collection='requestTypes'
22 + and nullif(trim(r.data->>'code'),'') is not null
23 + and nullif(trim(r.data->>'title'),'') is not null
24 + group by r.organization_id,upper(trim(r.data->>'code'))
25 + having count(*)>1
26 + order by r.organization_id,upper(trim(r.data->>'code'))
27 + limit 1;
28 +
29 + if found then
30 + raise exception 'legacy request type duplicate-code collision: organization %, code %, records %',
31 + v_collision.organization_id,v_collision.normalized_code,v_collision.record_ids
32 + using errcode='23505';
33 + end if;
34 +end $$;
35 +
36 +revoke all on function private.assert_legacy_request_type_code_uniqueness() from public,anon,authenticated;
37 +
38 +select private.assert_legacy_request_type_code_uniqueness();
supabase/migrations/20261002071000_request_wave3_decision_idempotency.sql new
+171
@@ -0,0 +1,171 @@
1 +-- Wave 3 / F-415 + F-416: re-authorize decision replay and return the
2 +-- original immutable command outcome rather than the request's later current state.
3 +
4 +create or replace function private.request_step_decide(
5 + p_request_instance_id uuid,
6 + p_decision text,
7 + p_expected_revision bigint,
8 + p_idempotency_key text,
9 + p_note text default null
10 +)
11 +returns table(
12 + request_instance_id uuid,
13 + status text,
14 + revision bigint,
15 + step_key text,
16 + step_state text,
17 + approvals_received integer,
18 + approvals_required integer
19 +)
20 +language plpgsql
21 +security definer
22 +set search_path=''
23 +as $$
24 +declare
25 + v_row public.request_instances%rowtype;
26 + v_step private.request_step_instances%rowtype;
27 + v_vote private.request_step_votes%rowtype;
28 + v_next private.request_step_instances%rowtype;
29 + v_event public.request_instance_events%rowtype;
30 + v_decision text;
31 + v_approvals integer;
32 + v_status text;
33 + v_replay_step_state text;
34 + v_delegated_from uuid;
35 + v_schema jsonb;
36 +begin
37 + if auth.uid() is null then raise exception 'authentication required' using errcode='28000'; end if;
38 + if char_length(trim(coalesce(p_idempotency_key,'')))<8 then raise exception 'idempotency_key is required'; end if;
39 +
40 + v_decision:=lower(trim(coalesce(p_decision,'')));
41 + if v_decision not in('approve','reject') then raise exception 'unsupported step decision'; end if;
42 +
43 + select * into v_row from public.request_instances r where r.id=p_request_instance_id;
44 + if not found then raise exception 'request instance not found'; end if;
45 + if v_row.organization_id not in(select private.current_organization_ids()) then raise exception 'organization access denied' using errcode='42501'; end if;
46 + if not private.organization_has_module_entitlement(v_row.organization_id,'requests_workflow',true) then raise exception 'active requests_workflow entitlement required' using errcode='42501'; end if;
47 +
48 + select * into v_vote
49 + from private.request_step_votes v
50 + where v.request_instance_id=p_request_instance_id and v.idempotency_key=p_idempotency_key;
51 +
52 + if found then
53 + select * into v_step from private.request_step_instances s where s.id=v_vote.step_instance_id;
54 + if not found then raise exception 'decision replay step evidence missing' using errcode='55000'; end if;
55 +
56 + if v_vote.actor_user_id<>auth.uid() or v_vote.decision<>v_decision then
57 + raise exception 'idempotency key already used by another actor or decision' using errcode='42501';
58 + end if;
59 +
60 + if not private.has_org_capability(v_row.organization_id,'requests_workflow',v_step.required_capability) then
61 + v_delegated_from:=private.request_valid_delegator(v_row.organization_id,auth.uid(),v_step.required_capability,now());
62 + if v_delegated_from is null then raise exception 'active step capability or valid delegation required' using errcode='42501'; end if;
63 + end if;
64 +
65 + select * into v_event
66 + from public.request_instance_events e
67 + where e.request_instance_id=v_row.id
68 + and e.organization_id=v_row.organization_id
69 + and e.actor_user_id=auth.uid()
70 + and e.idempotency_key=p_idempotency_key
71 + and e.action='step_'||v_decision||':'||v_step.step_key;
72 + if not found then raise exception 'decision replay event evidence missing' using errcode='55000'; end if;
73 +
74 + select count(*)::integer into v_approvals
75 + from public.request_instance_events e
76 + where e.request_instance_id=v_row.id
77 + and e.action='step_approve:'||v_step.step_key
78 + and e.revision<=v_event.revision;
79 +
80 + v_replay_step_state:=case
81 + when v_decision='reject' then 'rejected'
82 + when v_approvals>=v_step.required_approvals then 'completed'
83 + else 'active'
84 + end;
85 +
86 + return query select v_row.id,v_event.to_status,v_event.revision,v_step.step_key,
87 + v_replay_step_state,v_approvals,v_step.required_approvals;
88 + return;
89 + end if;
90 +
91 + select * into v_row from public.request_instances r where r.id=p_request_instance_id for update;
92 + if p_expected_revision is null or p_expected_revision<>v_row.revision then raise exception 'stale revision'; end if;
93 + if v_row.status in('approved','rejected','cancelled') then raise exception 'terminal request cannot transition'; end if;
94 +
95 + select * into v_step
96 + from private.request_step_instances s
97 + where s.request_instance_id=v_row.id and s.state='active'
98 + order by s.step_index limit 1 for update;
99 + if not found then raise exception 'active workflow step not found'; end if;
100 +
101 + v_delegated_from:=null;
102 + if not private.has_org_capability(v_row.organization_id,'requests_workflow',v_step.required_capability) then
103 + v_delegated_from:=private.request_valid_delegator(v_row.organization_id,auth.uid(),v_step.required_capability,now());
104 + if v_delegated_from is null then raise exception 'active step capability or valid delegation required' using errcode='42501'; end if;
105 + end if;
106 +
107 + begin
108 + insert into private.request_step_votes(
109 + organization_id,request_instance_id,step_instance_id,actor_user_id,
110 + decision,note,idempotency_key,delegated_from_user_id
111 + ) values(
112 + v_row.organization_id,v_row.id,v_step.id,auth.uid(),
113 + v_decision,p_note,p_idempotency_key,v_delegated_from
114 + ) returning * into v_vote;
115 + exception when unique_violation then
116 + if exists(select 1 from private.request_step_votes x where x.step_instance_id=v_step.id and x.actor_user_id=auth.uid()) then
117 + raise exception 'actor already decided this step';
118 + end if;
119 + raise;
120 + end;
121 +
122 + if v_decision='reject' then
123 + update private.request_step_instances set state='rejected',completed_at=now() where id=v_step.id returning * into v_step;
124 + v_status:='rejected';
125 + else
126 + select count(*)::integer into v_approvals from private.request_step_votes x where x.step_instance_id=v_step.id and x.decision='approve';
127 + if v_approvals>=v_step.required_approvals then
128 + update private.request_step_instances set state='completed',completed_at=now() where id=v_step.id returning * into v_step;
129 + select * into v_next
130 + from private.request_step_instances s
131 + where s.request_instance_id=v_row.id and s.state='pending' and s.step_index>v_step.step_index
132 + order by s.step_index limit 1 for update;
133 + if found then
134 + update private.request_step_instances
135 + set state='active',activated_at=now(),due_at=case when sla_hours is null then null else now()+make_interval(hours=>sla_hours) end
136 + where id=v_next.id;
137 + v_status:='submitted';
138 + else
139 + v_status:='approved';
140 + end if;
141 + else
142 + v_status:='submitted';
143 + end if;
144 + end if;
145 +
146 + update public.request_instances as ri
147 + set status=v_status,revision=ri.revision+1,updated_at=now()
148 + where ri.id=v_row.id returning ri.* into v_row;
149 +
150 + insert into public.request_instance_events(
151 + organization_id,request_instance_id,actor_user_id,action,from_status,to_status,revision,note,idempotency_key
152 + ) values(
153 + v_row.organization_id,v_row.id,auth.uid(),'step_'||v_decision||':'||v_step.step_key,
154 + 'submitted',v_status,v_row.revision,p_note,p_idempotency_key
155 + );
156 +
157 + if v_status='approved' then
158 + select workflow_schema into v_schema from public.request_workflow_versions where id=v_row.workflow_version_id;
159 + perform private.enqueue_request_outbox(v_row.id,coalesce(v_schema,'{}'::jsonb),v_row.revision);
160 + end if;
161 +
162 + select count(*)::integer into v_approvals
163 + from private.request_step_votes x
164 + where x.step_instance_id=v_step.id and x.decision='approve';
165 +
166 + return query select v_row.id,v_row.status,v_row.revision,v_step.step_key,
167 + v_step.state,v_approvals,v_step.required_approvals;
168 +end $$;
169 +
170 +revoke all on function private.request_step_decide(uuid,text,bigint,text,text) from public,anon;
171 +grant execute on function private.request_step_decide(uuid,text,bigint,text,text) to authenticated;
supabase/tests/request_wave2_duplicate_code_guard.sql new
+31
@@ -0,0 +1,31 @@
1 +\set ON_ERROR_STOP on
2 +
3 +insert into public.profiles(id) values
4 + ('44444444-4444-4444-4444-444444444444')
5 +on conflict do nothing;
6 +
7 +insert into public.records(owner_id,organization_id,collection,id,data) values
8 + ('44444444-4444-4444-4444-444444444444','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','requestTypes','AUDIT-TEST-F412-DUP',
9 + jsonb_build_object('id','AUDIT-TEST-F412-DUP','code',' purchase ','title','Duplicate purchase type','active',true,'fields','[]'::jsonb,'workflow',jsonb_build_object('mode','single_owner','steps','[]'::jsonb),'createdAt','2026-10-02T00:00:00Z'));
10 +
11 +do $$
12 +begin
13 + begin
14 + perform private.assert_legacy_request_type_code_uniqueness();
15 + raise exception 'F-412 duplicate legacy code unexpectedly passed preflight';
16 + exception
17 + when unique_violation then
18 + if position('legacy request type duplicate-code collision' in sqlerrm)=0
19 + or position('PURCHASE' in sqlerrm)=0
20 + or position('AUDIT-TEST-F412-DUP' in sqlerrm)=0 then
21 + raise;
22 + end if;
23 + end;
24 +end $$;
25 +
26 +delete from public.records
27 +where owner_id='44444444-4444-4444-4444-444444444444'
28 + and collection='requestTypes'
29 + and id='AUDIT-TEST-F412-DUP';
30 +
31 +select private.assert_legacy_request_type_code_uniqueness();
supabase/tests/request_wave3_decision_idempotency.sql new
+111
@@ -0,0 +1,111 @@
1 +\set ON_ERROR_STOP on
2 +
3 +insert into public.profiles(id) values
4 + ('66666666-6666-6666-6666-666666666666'),
5 + ('77777777-7777-7777-7777-777777777777')
6 +on conflict do nothing;
7 +
8 +set role authenticated;
9 +select set_config('request.jwt.claim.sub','11111111-1111-1111-1111-111111111111',false);
10 +select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
11 +select set_config('request.jwt.claim.member_active','true',false);
12 +select set_config('request.jwt.claim.entitled','true',false);
13 +select set_config('request.jwt.claim.write','true',false);
14 +select set_config('request.jwt.claim.capabilities','read,configure,create,edit,approve',false);
15 +
16 +create temporary table wave3_ids(k text primary key,v uuid);
17 +insert into wave3_ids
18 +select 'type',request_type_version_id from public.request_publish_type_version(
19 + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','W3_REPLAY','Wave 3 replay','Workflow',
20 + '{"schemaVersion":1,"fields":[{"key":"subject","label":"Subject","type":"text","required":true}]}'::jsonb,
21 + '{"schemaVersion":2,"steps":[{"key":"approval","title":"Approval","mode":"parallel","requiredApprovals":2,"requiredCapability":"approve"}]}'::jsonb,0
22 +);
23 +insert into wave3_ids values('instance',public.request_create_instance(
24 + 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from wave3_ids where k='type'),
25 + '{"subject":"stable replay"}'::jsonb,'wave3-create-0001'
26 +));
27 +reset role;
28 +
29 +set role authenticated;
30 +select set_config('request.jwt.claim.sub','66666666-6666-6666-6666-666666666666',false);
31 +select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
32 +select set_config('request.jwt.claim.member_active','true',false);
33 +select set_config('request.jwt.claim.entitled','true',false);
34 +select set_config('request.jwt.claim.capabilities','read,approve',false);
35 +create temporary table wave3_first_response as
36 +select * from public.request_step_decide((select v from wave3_ids where k='instance'),'approve',1,'wave3-vote-0001','first vote');
37 +reset role;
38 +
39 +do $$ begin
40 + if not exists(select 1 from wave3_first_response where status='submitted' and revision=2 and step_key='approval' and step_state='active' and approvals_received=1 and approvals_required=2) then
41 + raise exception 'F-416 baseline first response is not the expected immutable outcome';
42 + end if;
43 +end $$;
44 +
45 +set role authenticated;
46 +select set_config('request.jwt.claim.sub','77777777-7777-7777-7777-777777777777',false);
47 +select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
48 +select set_config('request.jwt.claim.member_active','true',false);
49 +select set_config('request.jwt.claim.entitled','true',false);
50 +select set_config('request.jwt.claim.capabilities','read,approve',false);
51 +create temporary table wave3_second_response as
52 +select * from public.request_step_decide((select v from wave3_ids where k='instance'),'approve',2,'wave3-vote-0002','second vote');
53 +reset role;
54 +
55 +do $$ begin
56 + if not exists(select 1 from wave3_second_response where status='approved' and revision=3 and step_key='approval' and step_state='completed' and approvals_received=2 and approvals_required=2) then
57 + raise exception 'parallel quorum did not reach the expected terminal outcome';
58 + end if;
59 +end $$;
60 +
61 +set role authenticated;
62 +select set_config('request.jwt.claim.sub','66666666-6666-6666-6666-666666666666',false);
63 +select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
64 +select set_config('request.jwt.claim.member_active','true',false);
65 +select set_config('request.jwt.claim.entitled','true',false);
66 +select set_config('request.jwt.claim.capabilities','read',false);
67 +do $$ begin
68 + begin
69 + perform * from public.request_step_decide((select v from wave3_ids where k='instance'),'approve',1,'wave3-vote-0001','retry');
70 + raise exception 'F-415 unauthorized decision replay unexpectedly succeeded';
71 + exception when insufficient_privilege then null;
72 + end;
73 +end $$;
74 +reset role;
75 +
76 +set role authenticated;
77 +select set_config('request.jwt.claim.sub','77777777-7777-7777-7777-777777777777',false);
78 +select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
79 +select set_config('request.jwt.claim.member_active','true',false);
80 +select set_config('request.jwt.claim.entitled','true',false);
81 +select set_config('request.jwt.claim.capabilities','read,approve',false);
82 +do $$ begin
83 + begin
84 + perform * from public.request_step_decide((select v from wave3_ids where k='instance'),'approve',1,'wave3-vote-0001','foreign retry');
85 + raise exception 'actor-bound decision replay unexpectedly succeeded for another actor';
86 + exception when insufficient_privilege then null;
87 + end;
88 +end $$;
89 +reset role;
90 +
91 +set role authenticated;
92 +select set_config('request.jwt.claim.sub','66666666-6666-6666-6666-666666666666',false);
93 +select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
94 +select set_config('request.jwt.claim.member_active','true',false);
95 +select set_config('request.jwt.claim.entitled','true',false);
96 +select set_config('request.jwt.claim.capabilities','read,approve',false);
97 +create temporary table wave3_replay_response as
98 +select * from public.request_step_decide((select v from wave3_ids where k='instance'),'approve',1,'wave3-vote-0001','retry');
99 +reset role;
100 +
101 +do $$ begin
102 + if (select row_to_json(x)::text from wave3_first_response x) is distinct from (select row_to_json(x)::text from wave3_replay_response x) then
103 + raise exception 'F-416 replay response drifted from original command outcome';
104 + end if;
105 + if (select status from public.request_instances where id=(select v from wave3_ids where k='instance'))<>'approved' then
106 + raise exception 'replay mutated the already-approved request';
107 + end if;
108 + if (select revision from public.request_instances where id=(select v from wave3_ids where k='instance'))<>3 then
109 + raise exception 'replay changed request revision';
110 + end if;
111 +end $$;