@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / e664e8f
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 17:00 UTC

fix(auth): repair organization license ordering in admin-created user bootstrap (#94)

* docs(phase0): register observed admin signup trigger-order failure before implementing fix * fix(auth): seed trial license before guarded owner membership on user creation * test(auth): mirror existing phone columns in disposable identity fixture * test(auth): preserve email-or-phone identity validation on updated bootstrap * test(auth): reproduce live missing-licence seat failure in disposable PostgreSQL * test(auth): assert seeded license, seat cap, ordinary role and phone bootstrap * test(auth): require failing pre-fix repro and repaired bootstrap/seat PG regression in CI * fix(admin): decode safe server error codes into Persian instead of opaque HTTP error * fix(admin): version admin UI for reliable error display after deploy * test(admin): verify redacted Persian server rejection and cleared temporary password

davoodmehraban89 committed Oct 12, 2026 at 11:22 UTC e664e8fdbc77b660dfc1fedff580b206279899f3
10 files changed +220 -6
.github/workflows/quality.yml
+6
@@ -149,8 +149,14 @@ jobs:
149 run: psql -v ON_ERROR_STOP=1 -f supabase/tests/identity_wave5a_bootstrap.sql
150 - name: Apply Wave 5a identity bootstrap migration
151 run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002080000_identity_wave5a_bootstrap.sql
152 + - name: Reproduce missing-license pre-fix user creation failure under real seat guard
153 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/identity_bootstrap_seat_guard_repro.sql
154 + - name: Apply F0 admin signup license-before-membership fix
155 + run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261012080000_fix_identity_bootstrap_license_before_membership.sql
156 - name: Execute Wave 5a identity bootstrap assertions
157 run: psql -v ON_ERROR_STOP=1 -f supabase/tests/identity_wave5a_behavior.sql
158 + - name: Verify owner capacity, second-user rejection and phone signup after fix
159 + run: psql -v ON_ERROR_STOP=1 -f supabase/tests/identity_bootstrap_seat_guard_behavior.sql
160
161 c8-policy-database:
162 runs-on: ubuntu-latest
PROJECT_STATE.md
+9
@@ -324,3 +324,12 @@ Owner reports login blocked with generic 'check internet/VPN' network error on l
324 - PR #92 merged by squash to protected `main` exact SHA **`745bdc847a3c2db22048d1d545da0fad0ae5cc67`**. On that SAME SHA: Quality **`38218505600` SUCCESS**, static job `114708817767` Chromium **85/85 PASS (51.1s)** + Golden/draft-posted safety and three disposable DB jobs; Security **`38218505535` SUCCESS**, Release gate **`38218679192` SUCCESS**, gated Pages **`38218725537` SUCCESS**. Concurrent duplicate Release `38218648536` CANCELLED and Pages `38218713325` SKIPPED, neither counted as success.
325 - Independent read-only remote proof: authorized Windows desktop `DESKTOP-71SJ63M` GET to `https://factoreasy.ir/?phase0dark=20261012` includes `20261012-phase0-dark-contrast-v1` (**True**); fetched live `js/ux-hardening-r2.js?v=20261012-phase0-dark-contrast-v1` contains dark shell and secondary-button selectors (**True / True**). This proves deployed asset parity, **not** customer-authenticated visual experience.
326 - **Acceptance:** F0-06 targeted contrast **RELEASED / CONTROLLED-QA-PASSED**; broader modal/RTL keyboard/import/export/dark-light owner UI and physical-device acceptance remains **UNVERIFIED**. F0-01/02/03/04/07 and F0-08 outstanding gates remain; **PHASE 0 OPEN / NOT OWNER ACCEPTED**. No customer data, ledger, Auth, RLS, roles, schema, Supabase migration, financial posting or paid-service changes. Rollback: revert PR #92, run gated Pages deploy, refresh cached bundle.
327 +
328 +
329 +## 2026-10-12 F0-01/F0-07 admin provisioning 400 — OWNER REPORTED / ROOT CAUSE VERIFIED / FIX STARTED
330 +- **Owner request:** Screenshot of real Central Admin > New User form reporting `Edge Function returned a non-2xx status code` despite fields entered; fix the issue *before* resuming Phase 0 work. Do **not** record name, email, password, tokens, IP or request metadata from owner screenshot in project logs. Do not create a live user or change an existing password during diagnosis.
331 +- **Verified live source evidence:** protected `main` `487471fe9154ff7b94fab56335ffeb000494c72a`; live Supabase project `hcsixhqbyuhpshfwqpjx`, Edge `admin-user-management` ACTIVE v3 with `verify_jwt=true`. Request log on 2026-10-12 07:13:44Z: authenticated POST to Edge returned HTTP 400; corresponding Auth Admin `/auth/v1/admin/users` returned HTTP 500, with Auth error `ERROR: organization license not found (SQLSTATE 23503)` / `unexpected_failure`. These are exact live logs, **not** guessed password, email, network or unauthorized-role failure.
332 +- **Root cause:** live `public.handle_new_user()` inserts `public.organization_members` active owner BEFORE `public.licenses`; `private.enforce_organization_member_seat()` BEFORE INSERT requires license row and raises SQLSTATE 23503 if absent. Existing migrations lack the function's post-phone-identity live definition in main. Transaction fails during Auth user creation and rolls back. Actual constraints reviewed: licenses FK to profile/organization only, no membership FK; license-first ordering is valid and satisfies unmodified seat trigger.
333 +- **Bounded intended correction:** add reviewed, idempotent one-function migration to reorder fresh-user bootstrap as `profiles → organizations → licenses → owner membership`, preserving all current live email/phone signup support, default `role='user'`, trial entitlements, security-definer fixed search_path and seat enforcement. Reproduce 23503 in disposable PostgreSQL fixture, then verify successful bootstrap and existing seat-limit rejection. Add safe UI parsing of Edge structured error codes and regression test so admin form no longer displays opaque non-2xx errors. Run static/Chromium, disposable DB, Security; gate on exact SHA. Production migration only after independent tests and confirmed source/version equivalence; no changes to existing user/license rows, RLS, Auth JWT verification, or financial data. Rollback: approved previous function definition (do not mutate accounts/data). No live account creation without separately approved isolated identity.
334 +- **Dependent continuation:** PR #92 dark-mode work already merged into latest main; verify its exact protected-main gates before further F0-06 work. Phase 0 remains OPEN; do not claim owner E2E pass from synthetic tests or read-only diagnostics.
335 +- **Current status:** ROOT_CAUSE_VERIFIED / REPRODUCE_AND_FIX_IN_PROGRESS.
index.html
+1 -1
@@ -889,7 +889,7 @@ body{background:#f6f9fc}
889
890 <script src="js/core.js?v=20261011-login-triage-v1"></script>
891 <script src="js/login-connectivity.js?v=20261011-login-triage-v1"></script>
892 -<script src="js/admin.js?v=20261011-provision-v2"></script>
892 +<script src="js/admin.js?v=20261012-provision-error-v1"></script>
893 <script src="js/sync.js?v=20260928-data-v4"></script>
894 <script src="js/ui.js?v=20261002-shell-scroll-ownership-v2"></script>
895 <script src="js/invoices.js?v=20261011-doc-draft-v1"></script>
js/admin.js
+29 -2
@@ -77,6 +77,33 @@ function adminCloseCreateUser(){
77 if(modal){modal.classList.remove('active');modal.setAttribute('aria-hidden','true');}
78 const pw=document.getElementById('admin-new-password');if(pw)pw.value='';
79 }
80 +// Only show a bounded, localized error classification. Do not display raw backend
81 +// error messages, response bodies or any credentials in the admin panel.
82 +async function adminProvisioningErrorMessage(data,error){
83 + let code=String(data?.error||'').trim();
84 + if(!code&&error?.context&&typeof error.context.json==='function'){
85 + try{
86 + const response=typeof error.context.clone==='function'?error.context.clone():error.context;
87 + const body=await response.json();
88 + code=String(body?.error||'').trim();
89 + }catch(_ignored){}
90 + }
91 + const descriptions={
92 + invalid_email_or_phone:'نشانی ایمیل یا شماره تماس نامعتبر است.',
93 + invalid_profile:'نام یا نام کاربری شرایط مجاز را ندارد.',
94 + weak_temporary_password:'رمز اولیه باید حداقل ۱۲ کاراکتر و شامل حرف بزرگ و کوچک لاتین، عدد و نماد باشد.',
95 + unauthorized:'نشست ورود معتبر نیست؛ دوباره وارد حساب مدیر شوید.',
96 + admin_required:'این عملیات فقط با نقش مدیر سیستم تأییدشده مجاز است.',
97 + origin_not_allowed:'دامنه فعلی برای عملیات مدیریتی مجاز نیست.',
98 + server_configuration_missing:'تنظیمات امن سرویس ساخت حساب ناقص است؛ با پشتیبانی فنی تماس بگیرید.',
99 + email_exists:'این نشانی ایمیل قبلاً ثبت شده است؛ ابتدا فهرست کاربران را بررسی کنید.',
100 + user_already_exists:'این حساب قبلاً ایجاد شده است؛ ابتدا فهرست کاربران را بررسی کنید.',
101 + unexpected_failure:'پایگاه داده ساخت حساب را رد کرده است؛ ابتدا فهرست کاربران را بررسی کنید و موضوع را به پشتیبانی فنی گزارش دهید.',
102 + provision_failed:'ساخت حساب در سامانه احراز هویت ناموفق بود؛ ابتدا فهرست کاربران را بررسی کنید.',
103 + internal_error:'سرویس ساخت حساب خطای داخلی دارد؛ موضوع را به پشتیبانی فنی گزارش دهید.'
104 + };
105 + return descriptions[code]||'پاسخ موفق از سرویس دریافت نشد. پیش از تلاش مجدد، فهرست کاربران را بررسی کنید و در صورت نیاز با پشتیبانی تماس بگیرید.';
106 +}
107 async function adminCreateUser(){
108 if(!currentUser||currentUser.role!=='admin')return;
109 const email=String(document.getElementById('admin-new-email')?.value||'').trim().toLowerCase();
@@ -95,8 +122,8 @@ async function adminCreateUser(){
122 try{
123 const {data,error}=await sb.functions.invoke('admin-user-management',{body:{action:'create',email,full_name,username,temporary_password}});
124 if(error||!data?.ok){
98 - const reason=data?.error||error?.message||'unknown_error';
99 - fail('ایجاد حساب تأیید نشد: '+String(reason));return;
125 + const reason=await adminProvisioningErrorMessage(data,error);
126 + fail('ایجاد حساب تأیید نشد: '+reason);return;
127 }
128 adminCloseCreateUser();
129 alert('حساب ساخته شد. رمز اولیه را فقط از مسیر امن در اختیار کاربر قرار دهید و سپس لایسنس را از جدول مدیریت کنید.');
scripts/admin-provisioning.spec.js
+23
@@ -48,3 +48,26 @@ test('invalid email/weak password are rejected client-side without invoking serv
48 await page.locator('#modal-admin-create-user button').filter({hasText:'بستن'}).click();
49 await expect(page.locator('#modal-admin-create-user')).not.toHaveClass(/active/);
50 });
51 +
52 +test('server-side provisioning 400 shows actionable safe Persian reason without leaking raw HTTP error',async({page})=>{
53 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
54 + await page.evaluate(()=>{
55 + currentUser={id:'OWNER_QA',role:'admin'};
56 + document.getElementById('auth-screen').style.display='none';
57 + window.__calls=0;
58 + window.confirm=()=>true;
59 + Object.defineProperty(sb,'functions',{configurable:true,value:{invoke:async()=>{
60 + window.__calls++;
61 + return {data:null,error:{message:'Edge Function returned a non-2xx status code',context:new Response(JSON.stringify({error:'unexpected_failure'}),{status:400,headers:{'content-type':'application/json'}})}};
62 + }}});
63 + adminOpenCreateUser();
64 + });
65 + await page.locator('#admin-new-email').fill('test@example.invalid');
66 + await page.locator('#admin-new-password').fill('Temp!Password1234');
67 + await page.locator('#admin-create-submit').click();
68 + await expect(page.locator('#admin-create-status')).toContainText('پایگاه داده ساخت حساب را رد کرده است');
69 + await expect(page.locator('#admin-create-status')).not.toContainText('non-2xx');
70 + await expect(page.locator('#admin-new-password')).toHaveValue('');
71 + expect(await page.evaluate(()=>window.__calls)).toBe(1);
72 + await expect(page.locator('#modal-admin-create-user.active')).toBeVisible();
73 +});
supabase/migrations/20261012080000_fix_identity_bootstrap_license_before_membership.sql new
+53
@@ -0,0 +1,53 @@
1 +-- F0-01/F0-07: Repair Auth bootstrap order after organization member-seat guard.
2 +-- Verified live error (2026-10-12): 'organization license not found' (23503).
3 +-- Minimal semantics: profiles -> organization -> trial license -> owner membership.
4 +-- Preserve existing email/phone identities, ordinary role and unmodified seat policy.
5 +-- This CREATE OR REPLACE does not rewrite any existing users, organizations, or licenses.
6 +create or replace function public.handle_new_user()
7 +returns trigger
8 +language plpgsql security definer set search_path=''
9 +as $function$
10 +declare v_username text; v_org_name text; v_org_id uuid; v_identity text;
11 +begin
12 + v_identity:=coalesce(nullif(lower(new.email),''),nullif(new.phone,''));
13 + if v_identity is null then
14 + raise exception 'Finora requires an email or phone identity for signup';
15 + end if;
16 + v_username:=lower(coalesce(
17 + nullif(new.raw_user_meta_data->>'username',''),
18 + case when new.email is not null then split_part(new.email,'@',1)
19 + else regexp_replace(new.phone,'[^0-9+]','','g') end
20 + ));
21 + v_org_name:=left(
22 + coalesce(
23 + nullif(trim(new.raw_user_meta_data->>'full_name'),''),
24 + nullif(trim(new.raw_user_meta_data->>'name'),''),
25 + nullif(v_username,''),
26 + 'Finora'
27 + )||' - شخصی',
28 + 160
29 + );
30 + insert into public.profiles(id,email,phone,username,role,full_name)
31 + values(
32 + new.id,
33 + case when new.email is null then null else lower(new.email) end,
34 + new.phone,
35 + v_username,
36 + 'user',
37 + nullif(trim(coalesce(new.raw_user_meta_data->>'full_name',new.raw_user_meta_data->>'name','')),'')
38 + );
39 + insert into public.organizations(owner_user_id,name,status)
40 + values(new.id,v_org_name,'active') returning id into v_org_id;
41 +
42 + -- The BEFORE INSERT seat guard on organization_members checks this row.
43 + -- Seed the trial license FIRST, without weakening or disabling that guard.
44 + insert into public.licenses(user_id,organization_id,plan,status,starts_at,ends_at,max_companies,max_users,modules,limits)
45 + values(new.id,v_org_id,'trial','trial',current_date,current_date+15,1,1,array['full_suite']::text[],'{}'::jsonb);
46 +
47 + insert into public.organization_members(organization_id,user_id,status,is_owner)
48 + values(v_org_id,new.id,'active',true);
49 + return new;
50 +end $function$;
51 +
52 +-- Keep direct calls unavailable to browser-level roles.
53 +revoke all on function public.handle_new_user() from public, anon, authenticated;
supabase/tests/identity_bootstrap_seat_guard_behavior.sql new
+56
@@ -0,0 +1,56 @@
1 +\set ON_ERROR_STOP on
2 +-- Wave5a behavior confirms the owner is provisioned with the trial license.
3 +-- The additional checks ensure user-creation fix did not relax seat limits or privileges.
4 +do $$
5 +declare v_org uuid;v_member_count integer;
6 +begin
7 + select id into strict v_org from public.organizations
8 + where owner_user_id='11111111-1111-1111-1111-111111111111';
9 + select count(*) into v_member_count from public.organization_members
10 + where organization_id=v_org and status='active';
11 + if v_member_count<>1 then raise exception 'unexpected initial owner count'; end if;
12 + if not exists(select 1 from public.licenses where organization_id=v_org and max_users=1) then
13 + raise exception 'license was not seeded before member enforcement';
14 + end if;
15 + if not exists(select 1 from public.profiles where id='11111111-1111-1111-1111-111111111111' and role='user') then
16 + raise exception 'initial account was elevated to admin';
17 + end if;
18 +end $$;
19 +
20 +-- A second identity receives its own one-seat trial; it must never join
21 +-- the first organization as a second active named user.
22 +insert into auth.users(id,email,raw_user_meta_data)
23 +values('33333333-3333-3333-3333-333333333333','second@example.invalid','{"full_name":"Second QA"}'::jsonb);
24 +do $$
25 +declare v_org uuid;
26 +begin
27 + select id into strict v_org from public.organizations
28 + where owner_user_id='11111111-1111-1111-1111-111111111111';
29 + begin
30 + insert into public.organization_members(organization_id,user_id,status,is_owner)
31 + values(v_org,'33333333-3333-3333-3333-333333333333','active',false);
32 + raise exception 'second active user illegally bypassed named seat limit';
33 + exception when sqlstate '23514' then
34 + if position('named-user seat limit exceeded' in sqlerrm)=0 then raise;end if;
35 + end;
36 + if exists(select 1 from public.organization_members where organization_id=v_org
37 + and user_id='33333333-3333-3333-3333-333333333333') then
38 + raise exception 'failed extra membership was inserted';
39 + end if;
40 +end $$;
41 +
42 +-- The currently deployed bootstrap permits authenticated phone-only identities.
43 +insert into auth.users(id,email,phone,raw_user_meta_data)
44 +values('44444444-4444-4444-4444-444444444444',null,'+989123456789','{"full_name":"Phone QA"}'::jsonb);
45 +do $$
46 +declare v_org uuid;
47 +begin
48 + select id into strict v_org from public.organizations
49 + where owner_user_id='44444444-4444-4444-4444-444444444444';
50 + if not exists(select 1 from public.profiles where id='44444444-4444-4444-4444-444444444444' and phone='+989123456789' and role='user')
51 + or not exists(select 1 from public.licenses where organization_id=v_org and max_users=1 and status='trial')
52 + or not exists(select 1 from public.organization_members where organization_id=v_org
53 + and user_id='44444444-4444-4444-4444-444444444444' and status='active' and is_owner) then
54 + raise exception 'phone bootstrap regressed';
55 + end if;
56 +end $$;
supabase/tests/identity_bootstrap_seat_guard_repro.sql new
+40
@@ -0,0 +1,40 @@
1 +-- Disposable-DB reconstruction of the LIVE seat limiter (no production data).
2 +create schema if not exists private;
3 +create or replace function private.enforce_organization_member_seat()
4 +returns trigger language plpgsql security definer set search_path='' as $$
5 +declare v_limit integer;v_active integer;
6 +begin
7 + if new.status<>'active' then return new; end if;
8 + if tg_op='UPDATE' and old.status='active' and old.organization_id=new.organization_id then return new; end if;
9 + select l.max_users into v_limit
10 + from public.licenses l
11 + where l.organization_id=new.organization_id
12 + for update;
13 + if v_limit is null then raise exception 'organization license not found' using errcode='23503';end if;
14 + select count(*)::integer into v_active
15 + from public.organization_members m
16 + where m.organization_id=new.organization_id
17 + and m.status='active'
18 + and (tg_op='INSERT' or m.id<>new.id);
19 + if v_active>=v_limit then raise exception 'named-user seat limit exceeded' using errcode='23514';end if;
20 + return new;
21 +end $$;
22 +create trigger trg_organization_member_seat before insert or update of status,organization_id
23 +on public.organization_members for each row execute function private.enforce_organization_member_seat();
24 +
25 +-- Reproduce the exact initial failure while original Wave5a function is installed.
26 +-- Nested exception scope rolls back every synthetic Auth/profile/org write.
27 +do $$
28 +begin
29 + begin
30 + insert into auth.users(id,email,raw_user_meta_data)
31 + values ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','before-fix@example.invalid','{"full_name":"Before Fix QA"}'::jsonb);
32 + raise exception 'expected pre-fix bootstrap to fail on missing license';
33 + exception when sqlstate '23503' then
34 + if position('organization license not found' in sqlerrm)=0 then raise;end if;
35 + end;
36 + if exists(select 1 from auth.users where id='aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
37 + or exists(select 1 from public.profiles where id='aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa') then
38 + raise exception 'failed transaction left partial identity';
39 + end if;
40 +end $$;
supabase/tests/identity_wave5a_behavior.sql
+1 -1
@@ -14,6 +14,6 @@ begin
14 begin
15 insert into auth.users(id,email,raw_user_meta_data) values('22222222-2222-2222-2222-222222222222',null,'{}'::jsonb);
16 raise exception 'email-less signup unexpectedly succeeded';
17 - exception when others then if position('requires an email identity' in sqlerrm)=0 then raise;end if;end;
17 + exception when others then if position('requires an email or phone identity' in sqlerrm)=0 then raise;end if;end;
18 if exists(select 1 from public.profiles where id='22222222-2222-2222-2222-222222222222') then raise exception 'failed signup left partial profile state';end if;
19 end $$;
supabase/tests/identity_wave5a_bootstrap.sql
+2 -2
@@ -4,8 +4,8 @@ do $$ begin
4 if not exists(select 1 from pg_roles where rolname='authenticated') then create role authenticated nologin; end if;
5 end $$;
6 create schema if not exists auth;
7 -create table auth.users(id uuid primary key,email text,raw_user_meta_data jsonb not null default '{}'::jsonb);
8 -create table public.profiles(id uuid primary key references auth.users(id) on delete cascade,username text,role text not null default 'user',created_at timestamptz not null default now(),email text not null,full_name text);
7 +create table auth.users(id uuid primary key,email text,phone text,raw_user_meta_data jsonb not null default '{}'::jsonb);
8 +create table public.profiles(id uuid primary key references auth.users(id) on delete cascade,username text,role text not null default 'user',created_at timestamptz not null default now(),email text,phone text,full_name text);
9 create table public.organizations(id uuid primary key default gen_random_uuid(),owner_user_id uuid not null references public.profiles(id) on delete restrict,name text not null check(char_length(trim(name)) between 1 and 160),status text not null default 'active' check(status in('active','suspended')),created_at timestamptz not null default now(),updated_at timestamptz not null default now());
10 create table public.organization_members(id uuid primary key default gen_random_uuid(),organization_id uuid not null references public.organizations(id) on delete cascade,user_id uuid not null references public.profiles(id) on delete cascade,unit_id uuid,position_title text,status text not null default 'active' check(status in('active','suspended','left')),is_owner boolean not null default false,created_at timestamptz not null default now(),updated_at timestamptz not null default now(),unique(organization_id,user_id));
11 create table public.licenses(user_id uuid primary key references public.profiles(id) on delete cascade,plan text not null check(plan in('trial','monthly','three_months','annual','lifetime')),status text not null check(status in('trial','active','cancelled')),starts_at date not null default current_date,ends_at date not null,updated_at timestamptz not null default now(),max_companies integer not null default 1 check(max_companies between 1 and 1000),modules text[] not null default array['full_suite']::text[],organization_id uuid not null references public.organizations(id) on delete restrict,max_users integer not null default 1 check(max_users between 1 and 100000),limits jsonb not null default '{}'::jsonb check(jsonb_typeof(limits)='object'));