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

Add global admin password reset action

Quinn White committed Oct 28, 2026 at 20:58 UTC 0615dea67ac109de9104f370b602dc3198a8c7ed
8 files changed +231 -13
.github/workflows/quality.yml
+1 -1
@@ -116,7 +116,7 @@ jobs:
116 run: node scripts/posting-idempotency-check.mjs
117 - name: Secure admin provisioning contract
118 run: node scripts/admin-provisioning-contract.mjs
119 - - name: Recovery-only manager authorization and delivery contract
119 + - name: Central admin credential and organization recovery controls
120 run: node --test scripts/admin-recovery-handler.spec.mjs
121 - name: Install browser smoke-test runtime
122 run: |
PROJECT_STATE.md
+5
@@ -165,3 +165,8 @@
165 ### 2026-10-28 — Company Edit button repair
166 - Owner reports that company selection works but the company-table Edit action does not open the editor; requests actual button verification. Separate branch `fix/company-edit-action-20261028` is now based on protected main `c95da47bca863be5b8ead47d49a5a6a8ff30d382`; login layout and central-admin password feature remain separate.
167 - **Root cause confirmed and local verification complete:** the hardened Pages dispatcher does not support `this.dataset.companyId`, so the rendered Edit button could not call `editCompany`. A narrow `editCompanyFromButton(this)` adapter reads the existing data attribute in application code; the generated button now escapes its ID. Expanded real-DOM tests click Edit, Cancel, Edit, Save, select the default company, log out/reload/edit again, and verify an expired license prevents a save. Source and generated Pages tests **5/5 PASS**; `git diff --check` PASS. No production company record was touched. Protected PR and post-deployment Pages verification are pending.
168 +
169 +### 2026-10-28 — Central software-admin password assignment
170 +- Owner requests direct assignment of a forgotten password from the central users/licenses panel. This isolated branch `fix/admin-central-password-reset-20261028` is based on protected main `c19a3590674a65a0857576c1093ef17ab3119df8`. The existing global platform role `profiles.role='admin'` is the sole direct-reset authority; company managers remain recovery-link-only because a user's password applies across organizations.
171 +- **Implemented and verified locally:** handler tests **49/49 PASS**, central reset UI and existing office/Pages browser suite **28/28 PASS**, admin provisioning contract, JavaScript syntax checks, and `git diff --check` PASS. Synthetic tests click the central row button, validate strong matching values, call the server once, clear both fields, reject organization owners, and verify provider errors never become false success or leak details. No real password/account was changed. Upstream Supabase documents the server-side `auth.admin.updateUserById(..., { password })` operation at https://supabase.com/docs/reference/javascript/auth-admin-updateuserbyid; the changelog scan found no applicable Auth breaking change.
172 +- **NOT VERIFIED / release gate:** production still runs the prior `admin-user-management` function. Do not deploy the function or dependent UI until the owner separately approves production Auth activation. Real account reset and post-deployment production UI are NOT VERIFIED.
index.html
+15 -2
@@ -770,7 +770,7 @@ body{background:#f6f9fc}
770 <div><h2 style="font-size:18px;color:var(--danger)">👑 پنل مدیریت مرکزی کاربران و لایسنس‌ها</h2><p style="color:var(--text-muted);font-size:13px;margin-top:4px">تعریف کاربران، تخصیص طرح‌های لایسنس، تمدید، تغییر مدت و لغو اشتراک.</p></div>
771 <div style="display:flex;gap:8px;flex-wrap:wrap"><button id="admin-create-user-button" class="btn btn-success btn-inline" type="button" onclick="adminOpenCreateUser()">+ ایجاد کاربر جدید</button><button class="btn btn-primary btn-inline" onclick="refreshAdminPanel()">🔄 تازه‌سازی لیست</button></div>
772 </div>
773 -<div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:20px;font-size:13px;line-height:1.9">مدیر سیستم می‌تواند حساب کاربری عادی را با ایمیل و رمز اولیه بدون ثبت‌نام قبلی بسازد. رمز را فقط از مسیر امن در اختیار کاربر قرار دهید. مدیریت اشتراک از جدول انجام می‌شود.</div>
773 +<div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:20px;font-size:13px;line-height:1.9">مدیر سیستم سراسری می‌تواند حساب عادی بسازد، لایسنس را مدیریت کند و در صورت درخواست کاربر رمز تازه تعیین کند. مدیر هر شرکت فقط پیوند بازیابی می‌فرستد. تغییر رمز حسابی که در چند شرکت عضو است بر همهٔ آن شرکت‌ها اثر می‌گذارد؛ رمز را فقط از مسیر امن در اختیار کاربر بگذارید.</div>
774 <div class="table-responsive">
775 <table><thead><tr><th>کاربر</th><th>وضعیت حساب</th><th>نوع اشتراک</th><th>ظرفیت شرکت</th><th>ظرفیت کاربران</th><th>تاریخ شروع</th><th>تاریخ پایان</th><th>روزهای باقیمانده</th><th>عملیات مدیریت لایسنس</th></tr></thead><tbody id="admin-users-table-body"><tr><td colspan="9" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr></tbody></table>
776 </div>
@@ -842,6 +842,19 @@ body{background:#f6f9fc}
842 <button class="btn btn-secondary" type="button" onclick="adminCloseCreateUser()">بستن</button>
843 </div>
844 </div></div>
845 +<div class="modal-backdrop" id="modal-admin-reset-password">
846 +<div class="modal-card" style="max-width:520px" role="dialog" aria-modal="true" aria-labelledby="admin-password-reset-title">
847 +<h3 id="admin-password-reset-title">تعیین رمز جدید کاربر</h3>
848 +<p class="af-hint">حساب انتخاب‌شده: <strong id="admin-password-reset-user"></strong></p>
849 +<p class="af-hint">این عملیات رمز مشترک حساب کاربر را در همهٔ شرکت‌هایش عوض می‌کند. رمز باید حداقل ۱۲ نویسه و شامل حرف بزرگ، حرف کوچک، عدد و نماد باشد.</p>
850 +<div class="form-group"><label for="admin-reset-password">رمز جدید</label><input id="admin-reset-password" class="form-control" type="password" minlength="12" maxlength="128" autocomplete="new-password" dir="ltr"></div>
851 +<div class="form-group"><label for="admin-reset-password-confirm">تکرار رمز جدید</label><input id="admin-reset-password-confirm" class="form-control" type="password" minlength="12" maxlength="128" autocomplete="new-password" dir="ltr"></div>
852 +<p id="admin-password-reset-status" class="af-hint" aria-live="polite"></p>
853 +<div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:15px">
854 +<button id="admin-reset-password-submit" class="btn btn-primary" type="button" onclick="adminSetPassword()">ثبت رمز جدید</button>
855 +<button class="btn btn-secondary" type="button" onclick="adminClosePasswordReset()">بستن</button>
856 +</div>
857 +</div></div>
858 <div class="modal-backdrop" id="modal-admin-license-edit">
859 <div class="modal-card">
860 <h3 style="font-size:16px;margin-bottom:12px" id="modal-license-user-title">تغییر مدت و لایسنس کاربر</h3>
@@ -911,7 +924,7 @@ body{background:#f6f9fc}
924 <script src="js/login-connectivity.js?v=20261026-preflight-compare-v5"></script>
925 <script src="js/password-recovery.js?v=20261026-recovery-cancel-v2"></script>
926 <script src="js/core.js?v=20261025-password-recovery-v1"></script>
914 -<script src="js/admin.js?v=20261025-password-recovery-v1"></script>
927 +<script src="js/admin.js?v=20261028-central-password-reset-v1"></script>
928 <script src="js/sync.js?v=20261012-login-read-cancel-v1"></script>
929 <script src="js/ui.js?v=20261002-shell-scroll-ownership-v2"></script>
930 <script src="js/invoices.js?v=20261024-settings-zero-vat-v1"></script>
js/admin.js
+59 -2
@@ -12,7 +12,7 @@ async function renderAdminPanel(){
12 adminUsersCache=(p.data||[]).map(u=>Object.assign({},u,{lic:lic.get(u.id)||null}));
13 if(adminUsersCache.length===0){tbody.innerHTML='<tr><td colspan="9" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>';return;}
14 const planLabels={monthly:'طرح ۱ ماهه',three_months:'طرح ۳ ماهه',annual:'طرح ۱ ساله',lifetime:'دائمی (Lifetime)',trial:'آزمایشی (Trial)'};
15 - tbody.innerHTML=adminUsersCache.map(u=>{
15 + tbody.innerHTML=adminUsersCache.map(u=>{
16 const sub=u.lic?{type:u.lic.plan,startDate:u.lic.starts_at,endDate:u.lic.ends_at,status:u.lic.status}:{type:'trial',startDate:'',endDate:'',status:'cancelled'};
17 const remDays=getRemainingDays(sub.endDate);
18 const isExp=remDays<=0&&sub.type!=='lifetime';
@@ -23,7 +23,7 @@ async function renderAdminPanel(){
23 const endJalali=sub.type==='lifetime'?'نامحدود':formatToJalali(sub.endDate);
24 const remDaysText=sub.type==='lifetime'?'نامحدود':toPersianDigits(Math.max(0,remDays))+' روز';
25 const uid=esc(u.id);
26 - const capacity=Math.max(1,Number(u.lic?.max_companies||1)),userCapacity=Math.max(1,Number(u.lic?.max_users||1));return `<tr><td><strong>${esc(u.full_name||u.email||u.username||'—')}</strong><small style="display:block;color:var(--text-muted)">${esc(u.email||'')}</small> ${u.role==='admin'?'<span class="badge badge-info">مدیر سیستم</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</td><td><strong>${toPersianDigits(capacity)}</strong> شرکت</td><td><strong>${toPersianDigits(userCapacity)}</strong> کاربر</td><td>${formatToJalali(sub.startDate)}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${uid}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${uid}')">اصلاح لایسنس</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" data-recovery-user="${uid}" onclick="finoraSendUserRecovery('${uid}')">ارسال پیوند بازیابی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${uid}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${uid}')">لغو اشتراک</button>`:''}</td></tr>`;
26 + const capacity=Math.max(1,Number(u.lic?.max_companies||1)),userCapacity=Math.max(1,Number(u.lic?.max_users||1));return `<tr><td><strong>${esc(u.full_name||u.email||u.username||'—')}</strong><small style="display:block;color:var(--text-muted)">${esc(u.email||'')}</small> ${u.role==='admin'?'<span class="badge badge-info">مدیر سیستم</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</td><td><strong>${toPersianDigits(capacity)}</strong> شرکت</td><td><strong>${toPersianDigits(userCapacity)}</strong> کاربر</td><td>${formatToJalali(sub.startDate)}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${uid}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${uid}')">اصلاح لایسنس</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" data-recovery-user="${uid}" onclick="finoraSendUserRecovery('${uid}')">ارسال پیوند بازیابی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" data-reset-user="${uid}" onclick="adminOpenPasswordReset('${uid}')">تعیین رمز جدید</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${uid}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${uid}')">لغو اشتراک</button>`:''}</td></tr>`;
27 }).join('');
28 }
29 function refreshAdminPanel(){renderAdminPanel();}
@@ -74,6 +74,63 @@ function refreshAdminPanel(){renderAdminPanel();}
74 finally{clearTimeout(timer);pending.delete(userId);buttons.forEach(({el,disabled})=>{el.disabled=disabled})}
75 };
76 })();
77 +let adminPasswordResetTarget='';
78 +function adminOpenPasswordReset(userId){
79 + if(!currentUser||currentUser.role!=='admin')return;
80 + const uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
81 + const target=adminUsersCache.find(user=>user.id===userId);
82 + if(!target||!uuid.test(userId))return;
83 + adminPasswordResetTarget=userId;
84 + document.getElementById('admin-password-reset-user').textContent=target.email||target.full_name||'کاربر انتخاب‌شده';
85 + document.getElementById('admin-reset-password').value='';
86 + document.getElementById('admin-reset-password-confirm').value='';
87 + document.getElementById('admin-password-reset-status').textContent='';
88 + document.getElementById('modal-admin-reset-password').classList.add('active');
89 + document.getElementById('admin-reset-password').focus();
90 +}
91 +function adminClosePasswordReset(){
92 + document.getElementById('admin-reset-password').value='';
93 + document.getElementById('admin-reset-password-confirm').value='';
94 + document.getElementById('admin-password-reset-status').textContent='';
95 + document.getElementById('modal-admin-reset-password').classList.remove('active');
96 + adminPasswordResetTarget='';
97 +}
98 +async function adminSetPassword(){
99 + if(!currentUser||currentUser.role!=='admin'||!adminPasswordResetTarget)return;
100 + const targetId=adminPasswordResetTarget;
101 + const passwordInput=document.getElementById('admin-reset-password');
102 + const confirmInput=document.getElementById('admin-reset-password-confirm');
103 + const status=document.getElementById('admin-password-reset-status');
104 + const button=document.getElementById('admin-reset-password-submit');
105 + const password=String(passwordInput.value||''),confirmation=String(confirmInput.value||'');
106 + if(password.length<12||password.length>128||!/[a-z]/.test(password)||!/[A-Z]/.test(password)||!/[0-9]/.test(password)||!/[^A-Za-z0-9]/.test(password)){
107 + status.textContent='رمز جدید حداقل ۱۲ نویسه و شامل حرف بزرگ، حرف کوچک، عدد و نماد باشد.';return;
108 + }
109 + if(password!==confirmation){status.textContent='تکرار رمز با رمز جدید یکسان نیست.';return;}
110 + const target=adminUsersCache.find(user=>user.id===adminPasswordResetTarget);
111 + if(!target)return;
112 + if(!confirm('رمز ورود '+(target.email||target.full_name||'این کاربر')+' با رمز جدید جایگزین شود؟'))return;
113 + button.disabled=true;status.textContent='در حال ثبت امن رمز جدید...';
114 + passwordInput.value='';confirmInput.value='';
115 + try{
116 + const {data,error}=await sb.functions.invoke('admin-user-management',{body:{action:'set_password',user_id:targetId,password}});
117 + if(error||!data?.ok){status.textContent=await adminPasswordResetErrorMessage(data,error);return;}
118 + status.textContent='رمز جدید برای این کاربر ثبت شد؛ آن را فقط از مسیر امن در اختیارش بگذارید.';
119 + }catch(_error){status.textContent='نتیجهٔ تغییر رمز مشخص نیست؛ پیش از تلاش دوباره وضعیت حساب را بررسی کنید.';}
120 + finally{button.disabled=false;passwordInput.value='';confirmInput.value='';}
121 +}
122 +async function adminPasswordResetErrorMessage(data,error){
123 + let code=String(data?.error||'');
124 + if(!code&&typeof error?.context?.json==='function')try{code=(await error.context.clone().json())?.error||'';}catch(_ignored){}
125 + return ({
126 + unauthorized:'نشست معتبر نیست؛ دوباره وارد حساب مدیر سیستم شوید.',
127 + admin_required:'تعیین رمز فقط برای مدیر سیستم مجاز است.',
128 + invalid_password_reset:'درخواست تعیین رمز معتبر نیست.',
129 + weak_password_assignment:'رمز شرایط امنیتی لازم را ندارد.',
130 + password_target_unavailable:'حساب انتخاب‌شده در سرور پیدا نشد.',
131 + password_assignment_failed:'سرور نتوانست رمز جدید را ثبت کند؛ وضعیت حساب را بررسی کنید.'
132 + })[code]||'نتیجهٔ ثبت رمز از سرور تأیید نشد؛ وضعیت حساب را بررسی کنید.';
133 +}
134 async function adminRpc(name,args,okMsg){
135 const {error}=await sb.rpc(name,args);
136 if(error){alert('خطا: '+(error.message||'عملیات ناموفق بود.'));return false;}
scripts/admin-provisioning-contract.mjs
+6 -2
@@ -13,8 +13,12 @@ assert.match(edge,/email_confirm:\s*true/,'Direct provision uses confirmed addre
13 assert.doesNotMatch(edge,/\b(?:app_metadata|role)\s*:\s*["']admin["']/i,'Client must not elevate a new account');
14 assert.match(edge,/strongPassword\(password\)/,'Server enforces strong initial credential');
15 assert.match(edge,/allowedOrigins\.has\(origin\)/,'Browser origins are restricted');
16 -assert.doesNotMatch(edge,/updateUserById|generateLink/,'Recovery only sends an email; managers never receive credential control');
16 +assert.match(edge,/if\s*\(profile\.role\s*!==\s*"admin"\)\s*return\s+reply\(403,\s*\{error:\s*"admin_required"\}/,'Direct password assignment must require global platform-admin role');
17 +assert.match(edge,/auth\.admin\.updateUserById\(targetId,\s*\{password:/,'Password changes must use the server-side Auth Admin API');
18 +assert.doesNotMatch(edge,/generateLink/,'The password reset path must not generate or expose provider links');
19 assert.match(ui,/currentUser\.role!=='admin'/,'UI refuses non-admin account creation');
20 +assert.match(ui,/currentUser\.role!=='admin'\|\|!adminPasswordResetTarget/,'UI refuses non-admin direct password changes');
21 +assert.match(ui,/action:'set_password'/,'Central admin reset must invoke the guarded server action');
22 assert.match(html,/id="admin-create-user-button"/,'Central admin create button must exist');
23 assert.doesNotMatch(ui,/SUPABASE_SERVICE_ROLE_KEY/,'Service role key never enters browser');
20 -console.log('Admin server-only provisioning contract PASS');
24 +console.log('Admin server-only provisioning and credential reset contract PASS');
scripts/admin-recovery-handler.spec.mjs
+45 -4
@@ -72,7 +72,7 @@ async function fixture(options={}){
72 admin:{
73 getUserById:async id=>{calls.targetLookups.push(id);return {data:{user:id===TARGET&&!options.targetError?targetUser:null},error:options.targetError||null};},
74 createUser:async body=>{calls.creates.push(body);return {data:{user:options.createError?null:{id:CREATED}},error:options.createError||null};},
75 - updateUserById:async(...args)=>{calls.updates.push(args);return {data:{user:{id:TARGET}},error:null};},
75 + updateUserById:async(...args)=>{calls.updates.push(args);if(options.updateThrows)throw new Error('PRIVATE_AUTH_EXCEPTION');return {data:options.updateError?null:{user:{id:TARGET}},error:options.updateError||null};},
76 generateLink:async(...args)=>{calls.links.push(args);return {data:{properties:{action_link:'PRIVATE_ACTION_LINK'}},error:null};}
77 }
78 }
@@ -211,9 +211,50 @@ test('malformed target and organization identifiers are rejected before Auth tar
211 const f=await fixture({admin:true});assert.equal((await f.invoke(body)).status,400);assert.equal(f.calls.targetLookups.length,0);
212 }
213 });
214 -test('legacy direct password-setting action is removed even for the global admin',async()=>{
215 - const f=await fixture({admin:true});const result=await f.invoke({action:'set_password',user_id:TARGET,password:'NeverSet!Secret123'});
216 - assert.equal(result.status,400);assert.equal(result.body.error,'unsupported_action');noPasswordMutation(f);
214 +test('global platform admin can set a password through Auth Admin and receives only an outcome',async()=>{
215 + const secret='NeverSet!Secret123';const f=await fixture({admin:true});
216 + const result=await f.invoke({action:'set_password',user_id:TARGET,password:secret});
217 + assert.equal(result.status,200);assert.deepEqual(result.body,{ok:true});
218 + assert.deepEqual(f.calls.updates,[[TARGET,{password:secret}]]);
219 + assert.deepEqual(f.calls.logs,[['finora_admin_password_set',{actor:ACTOR,user_id:TARGET,outcome:'success'}]]);
220 + assert.doesNotMatch(JSON.stringify([result.body,f.calls.logs]),new RegExp(secret));
221 + assert.equal(f.calls.emails.length,0);assert.equal(f.calls.creates.length,0);
222 +});
223 +test('organization owner and delegated managers cannot assign any global Auth password',async()=>{
224 + for(const options of [{owner:true},{}]){
225 + const f=await fixture(options);if(!options.owner)managerRole(f);
226 + const result=await f.invoke({action:'set_password',user_id:TARGET,password:'NeverSet!Secret123'});
227 + assert.equal(result.status,403);assert.equal(result.body.error,'admin_required');
228 + assert.equal(f.calls.targetLookups.length,0);noPasswordMutation(f);
229 + }
230 +});
231 +test('malformed direct reset identifiers and unexpected fields are rejected without Auth lookup',async()=>{
232 + for(const body of [
233 + {action:'set_password',user_id:'-'.repeat(36),password:'NeverSet!Secret123'},
234 + {action:'set_password',user_id:TARGET,password:'NeverSet!Secret123',organization_id:ORG},
235 + {action:'set_password',user_id:TARGET,password:'NeverSet!Secret123',email:'attacker@example.invalid'},
236 + {action:'set_password',user_id:TARGET,password:'NeverSet!Secret123',role:'admin'}
237 + ]){
238 + const f=await fixture({admin:true});const result=await f.invoke(body);
239 + assert.equal(result.status,400);assert.equal(result.body.error,'invalid_password_reset');
240 + assert.equal(f.calls.targetLookups.length,0);noPasswordMutation(f);
241 + }
242 +});
243 +test('weak assigned passwords fail server policy without Auth mutation',async()=>{
244 + for(const password of ['short','NeverSet!NoDigits','ONLYUPPER!123','NeverSet!abcdef','a'.repeat(129)]){
245 + const f=await fixture({admin:true});const result=await f.invoke({action:'set_password',user_id:TARGET,password});
246 + assert.equal(result.status,400);assert.equal(result.body.error,'weak_password_assignment');noPasswordMutation(f);
247 + }
248 +});
249 +test('Auth password update failures are bounded and never log the submitted secret',async()=>{
250 + const secret='NeverSet!Secret123';
251 + for(const options of [{updateError:{code:'PRIVATE_AUTH_ERROR',message:'PRIVATE_AUTH_MESSAGE'}},{updateThrows:true}]){
252 + const f=await fixture({admin:true,...options});
253 + const result=await f.invoke({action:'set_password',user_id:TARGET,password:secret});
254 + assert.equal(result.status,502);assert.equal(result.body.error,'password_assignment_failed');
255 + assert.doesNotMatch(JSON.stringify([result.body,f.calls.logs]),/PRIVATE_|NeverSet!Secret123/);
256 + assert.equal(f.calls.emails.length,0);
257 + }
258 });
259 test('rate limits remain distinguishable without leaking provider error text',async()=>{
260 for(const error of [{code:'over_email_send_rate_limit'},{code:'over_request_rate_limit'},{status:429}]){
scripts/password-admin-ui.spec.js
+76 -2
@@ -1,14 +1,15 @@
1 const {test,expect}=require('@playwright/test');
2 const BASE=process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html';
3 +const PAGES_BASE=process.env.FINORA_TEST_PAGES_BASE||new URL('/_site/index.html',BASE).href;
4 const ACTOR='11111111-1111-4111-8111-111111111111';
5 const TARGET='22222222-2222-4222-8222-222222222222';
6 const OTHER='33333333-3333-4333-8333-333333333333';
7 const ORG='44444444-4444-4444-8444-444444444444';
8 const MEMBER='55555555-5555-4555-8555-555555555555';
9
9 -async function managerFixture(page,kind='global'){
10 +async function managerFixture(page,kind='global',url=BASE){
11 await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
11 - await page.goto(BASE,{waitUntil:'domcontentloaded'});
12 + await page.goto(url,{waitUntil:'domcontentloaded'});
13 await page.waitForFunction(()=>window.FinoraStartupStatus?.authChecked===true&&window.FinoraStartupStatus?.extensionsReady===true);
14 await page.evaluate(({kind,ACTOR,TARGET,OTHER,ORG,MEMBER})=>{
15 document.getElementById('auth-screen').style.display='none';
@@ -33,6 +34,79 @@ test('central user/license row sends only target Auth identity to the recovery e
34 expect(await page.evaluate(()=>window.__recoveryAlerts.join(' '))).toContain('پیوند');
35 });
36
37 +test('global software admin assigns a new password from the central user row and secrets are cleared',async({page})=>{
38 + await managerFixture(page);
39 + await page.evaluate(async()=>{navigateShell('settings','view-admin');await renderAdminPanel()});
40 + const row=page.locator('#admin-users-table-body tr').filter({hasText:'recipient@example.invalid'});
41 + const button=row.locator('[data-reset-user="'+TARGET+'"]');
42 + await expect(button).toBeVisible();await button.click();
43 + await expect(page.locator('#modal-admin-reset-password')).toHaveClass(/active/);
44 + const secret='VeryStrong!NewPass123';
45 + await page.locator('#admin-reset-password').fill(secret);
46 + await page.locator('#admin-reset-password-confirm').fill(secret);
47 + await page.locator('#admin-reset-password-submit').click();
48 + await expect.poll(()=>page.evaluate(()=>window.__recoveryCalls)).toEqual([{name:'admin-user-management',body:{action:'set_password',user_id:TARGET,password:secret}}]);
49 + await expect(page.locator('#admin-password-reset-status')).toContainText('ثبت شد');
50 + await expect(page.locator('#admin-reset-password')).toHaveValue('');
51 + await expect(page.locator('#admin-reset-password-confirm')).toHaveValue('');
52 +});
53 +
54 +test('generated strict-CSP Pages central reset button opens and invokes the server action',async({page})=>{
55 + await managerFixture(page,'global',PAGES_BASE);
56 + await page.evaluate(async()=>{navigateShell('settings','view-admin');await renderAdminPanel()});
57 + const button=page.locator('[data-reset-user="'+TARGET+'"]');
58 + await expect(button).toBeVisible();await button.click();
59 + await expect(page.locator('#modal-admin-reset-password')).toHaveClass(/active/);
60 + const secret='VeryStrong!NewPass123';
61 + await page.locator('#admin-reset-password').fill(secret);
62 + await page.locator('#admin-reset-password-confirm').fill(secret);
63 + await page.locator('#admin-reset-password-submit').click();
64 + await expect.poll(()=>page.evaluate(()=>window.__recoveryCalls)).toEqual([{name:'admin-user-management',body:{action:'set_password',user_id:TARGET,password:secret}}]);
65 + await expect(page.locator('#admin-password-reset-status')).toContainText('ثبت شد');
66 +});
67 +
68 +test('central password form rejects mismatched and weak passwords before calling the server',async({page})=>{
69 + await managerFixture(page);
70 + await page.evaluate(async()=>{navigateShell('settings','view-admin');await renderAdminPanel()});
71 + await page.locator('[data-reset-user="'+TARGET+'"]').click();
72 + await page.locator('#admin-reset-password').fill('weak');
73 + await page.locator('#admin-reset-password-confirm').fill('different');
74 + await page.locator('#admin-reset-password-submit').click();
75 + await expect(page.locator('#admin-password-reset-status')).toContainText('حداقل ۱۲');
76 + await expect.poll(()=>page.evaluate(()=>window.__recoveryCalls)).toHaveLength(0);
77 + await page.locator('#admin-reset-password').fill('VeryStrong!NewPass123');
78 + await page.locator('#admin-reset-password-confirm').fill('VeryStrong!Other456');
79 + await page.locator('#admin-reset-password-submit').click();
80 + await expect(page.locator('#admin-password-reset-status')).toContainText('یکسان نیست');
81 + await expect.poll(()=>page.evaluate(()=>window.__recoveryCalls)).toHaveLength(0);
82 +});
83 +
84 +test('organization owner cannot render or invoke the central direct-password form',async({page})=>{
85 + await managerFixture(page,'owner');
86 + await expect(page.locator('#admin-users-table-body [data-reset-user]')).toHaveCount(0);
87 + await page.evaluate(async({TARGET})=>{await adminSetPassword();await adminOpenPasswordReset(TARGET);},{TARGET});
88 + expect(await page.evaluate(()=>window.__recoveryCalls)).toHaveLength(0);
89 + await expect(page.locator('#modal-admin-reset-password')).not.toHaveClass(/active/);
90 +});
91 +
92 +test('failed central password assignment shows no success and never echoes server details',async({page})=>{
93 + await managerFixture(page);
94 + await page.evaluate(async()=>{navigateShell('settings','view-admin');await renderAdminPanel()});
95 + await page.locator('[data-reset-user="'+TARGET+'"]').click();
96 + const secret='VeryStrong!NewPass123';
97 + await page.locator('#admin-reset-password').fill(secret);
98 + await page.locator('#admin-reset-password-confirm').fill(secret);
99 + await page.evaluate(()=>{sb.functions.invoke=async(name,{body})=>{window.__recoveryCalls.push({name,body});return {data:null,error:{message:'PRIVATE_PROVIDER_DETAIL',context:new Response(JSON.stringify({error:'password_assignment_failed',detail:'PRIVATE_SECRET'}),{status:502})}}};});
100 + await page.locator('#admin-reset-password-submit').click();
101 + await expect(page.locator('#admin-password-reset-status')).toContainText('نتوانست');
102 + const status=await page.locator('#admin-password-reset-status').innerText();
103 + expect(status).not.toContain('ثبت شد');
104 + expect(status).not.toContain('PRIVATE');
105 + expect(status).not.toContain(secret);
106 + await expect(page.locator('#admin-reset-password')).toHaveValue('');
107 + expect(await page.evaluate(()=>window.__recoveryCalls)).toHaveLength(1);
108 +});
109 +
110 test('organization owner targets the active Auth user, never the membership UUID or inactive member',async({page})=>{
111 await managerFixture(page,'owner');
112 await page.evaluate(()=>showOrganizationAccessManager());
supabase/functions/admin-user-management/handler.mjs
+24
@@ -122,6 +122,30 @@ export function createAdminUserManagementHandler({createClient, getEnv, logger =
122 logger.info("finora_admin_recovery_requested", audit);
123 return reply(200, {ok: true}, origin);
124 }
125 + if (body.action === "set_password") {
126 + if (Object.keys(body).some(key => !["action", "user_id", "password"].includes(key)) || typeof body.user_id !== "string" || !uuid.test(body.user_id) || typeof body.password !== "string") {
127 + return reply(400, {error: "invalid_password_reset"}, origin);
128 + }
129 + if (profile.role !== "admin") return reply(403, {error: "admin_required"}, origin);
130 + if (!strongPassword(body.password)) return reply(400, {error: "weak_password_assignment"}, origin);
131 + const targetId = body.user_id;
132 + const {data, error: targetError} = await server.auth.admin.getUserById(targetId);
133 + if (targetError || data?.user?.id !== targetId) return reply(404, {error: "password_target_unavailable"}, origin);
134 + let updateError;
135 + let updatedUser;
136 + try {
137 + ({data: {user: updatedUser} = {}, error: updateError} = await server.auth.admin.updateUserById(targetId, {password: body.password}));
138 + } catch {
139 + updateError = {code: "request_failed"};
140 + }
141 + const audit = {actor: user.id, user_id: targetId, outcome: "success"};
142 + if (updateError || updatedUser?.id !== targetId) {
143 + logger.info("finora_admin_password_set_failed", {...audit, outcome: "failed"});
144 + return reply(502, {error: "password_assignment_failed"}, origin);
145 + }
146 + logger.info("finora_admin_password_set", audit);
147 + return reply(200, {ok: true}, origin);
148 + }
149 if (body.action !== "create") return reply(400, {error: "unsupported_action"}, origin);
150 if (profile?.role !== "admin") return reply(403, {error: "admin_required"}, origin);
151 const email = String(body.email || "").trim().toLowerCase();