سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 20:45 UTC
Add recovery-only password assistance for users and managers
davoodmehraban89 committed
Oct 25, 2026 at 20:44 UTC
6d521a79fb012a0838f477acec2415793e19e555
18 files changed
+1307
-94
.github/workflows/quality.yml
+3
-1
@@ -116,6 +116,8 @@ 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
120
+ run: node --test scripts/admin-recovery-handler.spec.mjs
121
- name: Install browser smoke-test runtime
122
run: |
123
npm install --no-save @playwright/test@1.55.0 pdf-lib@1.17.1
@@ -123,7 +125,7 @@ jobs:
125
- name: Real DOM smoke
126
run: |
127
python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
126
- npx playwright test scripts/login-auth-transport.spec.js scripts/login-startup-readiness.spec.js scripts/phase0-startup-performance.spec.js scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/login-connectivity.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/ux-keyboard-f2.spec.js scripts/phase0-dark-theme-contrast.spec.js scripts/phase0-selector-stress.spec.js scripts/phase0-invoice-persistence.spec.js scripts/phase0-modal-dashboard.spec.js scripts/accounting-document-workflow.spec.js scripts/admin-provisioning.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
128
+ npx playwright test scripts/password-recovery.spec.js scripts/password-admin-ui.spec.js scripts/login-auth-transport.spec.js scripts/login-startup-readiness.spec.js scripts/phase0-startup-performance.spec.js scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/login-connectivity.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/ux-keyboard-f2.spec.js scripts/phase0-dark-theme-contrast.spec.js scripts/phase0-selector-stress.spec.js scripts/phase0-invoice-persistence.spec.js scripts/phase0-modal-dashboard.spec.js scripts/accounting-document-workflow.spec.js scripts/admin-provisioning.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
129
130
identity-wave5a-database:
131
runs-on: ubuntu-latest
PROJECT_STATE.md
+11
@@ -83,3 +83,14 @@
83
- Fresh unauthenticated real-public Playwright measurement from the cloud/proxy: form/session-check ready **543ms**, extensions/authChecked **817ms**; email/password/login enabled, auth gate visible, no required-script request/HTTP failure, no page error and zero failed extensions. No credentials were submitted and no Supabase request or financial read/write was observed. These timings establish this cloud run only, not the owner's ISP or authenticated account acceptance.
84
- Fresh actual test-profile run `3de24f55-7824-4f76-b909-8688017e4c72` reached the visible login gate and reported no vault credentials; it stopped after four steps/17 seconds without changing preferences. No authenticated workspace was observed in that run; it does not independently establish session expiry or exclude a delayed restore. Appearance true/false/theme reload, restoration, Excel/defaults and real logout/re-entry were **NOT EXECUTED**. Earlier reported UI access does not prove a reusable authenticated session. The owner was given another secure setup handoff; no password/token/cookie was requested in chat or copied into this repository.
85
- No production SQL/migration/schema/RLS/Auth-policy/role/grant, financial posting/history, dependency or frozen-module business change was performed. Navigation174 remains unmerged; PhaseB is not started. Issue106 stays open for affected-device/ISP acceptance. Remaining work: run controlled real-account preferences and exit/re-entry once authenticated access is actually available, restoring effective originals (including the previously reported baseline Ctrl+Enter enabled). Physical printing and production two-user behavior remain NOT VERIFIED. This follow-up changes only continuity/release documentation; its own exact-head CI is maintained in its PR description.
86
+
87
+### 2026-10-25 — Owner-requested password recovery (links only)
88
+- Owner requests password assistance from user/license/access administration and a Forgot Password entry on login. After the cross-company identity consequence was explained, owner explicitly selected **all authorized managers send recovery links only**; the recipient chooses the new password. No administrator password-entry UI, password disclosure, new role, schema/RLS/grant change or direct production password reset is authorized.
89
+- Remote main independently remains `ce32b0b52d974c2316b45b64a8166936f5a8d01e`. Isolated branch/worktree `feat/password-recovery-admin-reset-20261025` / `/workspace/Factor-easy-password-recovery`. Production management metadata reports ACTIVE_HEALTHY and existing `admin-user-management` ACTIVE version3; only metadata/source inspection is allowed at this stage, no deployment/configuration/real mail or password change.
90
+- Existing differences reported before implementation: server already has a global-admin-only `set_password` action but no UI caller; it only writes unenforced `user_metadata.force_password_change`. Login has neither `resetPasswordForEmail` nor recovery-callback handling. Org managers differ from global `profiles.admin`, and a user can belong to several orgs; joining an existing account to an org cannot authorize taking over its global password. Owner's link-only choice replaces direct-reset wiring.
91
+- Plan: reuse fresh server authorization and exact active core/full_suite configure/owner capability algorithm; restrict tenant manager targets to active same-org Auth identities; resolve confirmed email on server, send fixed-callback recovery mail, return no secret. Preserve admin-only account creation and reject legacy direct-set action. Add client Forgot Password, account-neutral send result and a dedicated required new-password callback panel. Preserve ordinary PKCE/OTP/login and prior financial behavior. Tests use isolated mocks only, including wrong-account cached-session/callback isolation, duplicate requests, tenant escalation, errors and strict-CSP Pages.
92
+- Design/plan: `docs/superpowers/specs/2026-10-25-password-recovery-design.md`, `docs/superpowers/plans/2026-10-25-password-recovery.md`. Complete implementation/negative tests/review/PR before any production Auth-function/configuration activation; prepare exact callback/template settings for owner review. Earlier actual-account checkbox/logout QA remains NOT VERIFIED in draft178; no acceptance claim is inherited from synthetic tests.
93
+- **Implemented and independently reviewed:** `js/password-recovery.js` owns the early recovery callback, neutral Forgot Password request and required new-password panel, with minimal `core.js` hooks and versioned HTML/extension delivery. Main PKCE/OTP/Google behavior remains unchanged; the explicit Auth storage key matches the SDK's previous default. Recovery mutations and local logout use a nonpersistent SDK instance bound to the verified user/session, preventing persistent-account swaps from targeting another account. Fresh unsupported callbacks discard old proof and scrub credentials. No private SDK field is changed. Manager link-only buttons reuse `finoraSendUserRecovery` in central users/licenses and active organization member rows, including delegated core configure managers; pending/cooldown and bounded Persian errors prevent duplicate/false-success behavior.
94
+- **Server and actual RED evidence:** extracted `handler.mjs` is called by the existing Deno entrypoint and tested with injected SDK/environment. Fresh active owner/direct/assigned core/full_suite configure authorization matches existing SQL, targets use Auth UUID/confirmed server email and canonical callback; old `set_password` rejects. Original inline handler failed the new recovery cases; additional observed RED cases included malformed organization scope, missing manager UI, raw thrown transport-error disclosure, wrong-account password/logout races and unsupported fresh callback proof reuse. Each was corrected before the final verification; no expectation was relaxed to hide application failures.
95
+- **Executed on the final implementation tree:** complete existing Quality browser command **175/175 PASS (3.3m)** = baseline150 +17 recovery +8 manager cases, including existing settings/logout synthetic regressions, A4/A5 print and financial/tenant tests. Focused recovery **17/17 source and17/17 generated strict-CSP Pages PASS**; manager UI **8/8 source and8/8 generated Pages PASS**. All **50 Quality pre-browser static/behavioral/backup/server commands PASS**, including **45/45 negative/compatibility server tests** and Golden Accounting; separate release-safety PASS; `git diff --check` PASS. Local process-only FONTCONFIG_FILE workaround remained outside the repository. A supplemental generated-manager attempt first failed solely because its local HTTP server had ended after a steered message; an explicitly scoped server/test process then passed8/8 without application/test-assertion changes. Independent whole-diff security review has no remaining blocker.
96
+- **Activation and next work:** concrete backend-first deployment, exact redirect allowlist and standard ConfirmationURL email-template requirements are in `docs/PASSWORD_RECOVERY_ACTIVATION_2026-10-25.md`. Publish this scoped branch/PR and verify its exact remote head Quality, Security and three disposable-DB jobs; maintain SHA/job evidence in the PR description. Production Edge deployment/Auth settings and merge/Pages activation remain pending the separate owner approval required by the boundary above. No real mail/password/financial write, SQL/migration, new dependency, RLS/role/grant change or production deployment occurred. **NOT VERIFIED:** current SMTP/template/redirect settings, real email delivery/password acceptance, owner-ISP/login, physical printing and production two-user behavior. Earlier actual-account settings QA stays inconclusive in draft178 (its exact-head Quality40158541584/Security40158541530 passed); navigation174 and PhaseB remain separate/unstarted.
docs/PASSWORD_RECOVERY_ACTIVATION_2026-10-25.md
new
+67
@@ -0,0 +1,67 @@
1
+# فعالسازی بازیابی رمز فینورا
2
+
3
+این تغییر طبق انتخاب مالک فقط **ارسال پیوند بازیابی** را به مدیران میدهد.
4
+هیچ مدیری رمز جدید کاربر را وارد یا مشاهده نمیکند. کاربر از پیوند ایمیل، رمز
5
+جدید و تکرارش را وارد میکند. حساب Auth میان شرکتهای کاربر مشترک است.
6
+
7
+## نتیجهٔ قابل بازبینی
8
+
9
+- در ورود: «فراموشی رمز عبور» برای ایمیل واردشده؛ پاسخ ارسال، وجود حساب را افشا نمیکند.
10
+- در کاربران/لایسنس: «ارسال پیوند بازیابی» برای مدیر سراسری.
11
+- در دسترسیهای سازمان: همین عمل برای مدیر مجاز و عضو فعال همان سازمان.
12
+- سمت سرور: نشست و مجوز فعلی بررسی میشود؛ مقصد فقط ایمیل تأییدشدهٔ Auth است.
13
+ مرورگر نمیتواند مقصد، پیوند بازگشت یا رمز را تعیین کند. عمل قدیمی `set_password`
14
+ رد میشود؛ ساخت حساب عادی توسط مدیر سراسری حفظ میشود.
15
+- پیوند نامعتبر یا منقضی، داشتن یک نشست دیگر در مرورگر را مجوز تغییر رمز نمیکند.
16
+
17
+## تغییرات Production که هنوز اجرا نشدهاند
18
+
19
+مرز `PROJECT_STATE.md` میگوید: «تغییر schema/RLS/Auth/role/grants، … یا … ارسال بیرونی
20
+نیازمند اجازه صریح جداگانه است.» اجرای موارد زیر پس از اجازهٔ مشخص مالک است.
21
+هیچ migration، SQL یا تغییر نقش/RLS برای این قابلیت لازم نیست.
22
+
23
+1. تنظیمات Auth فعلی را بدون نمایش رازها ثبت و پیوند مجاز زیر را بررسی کنید:
24
+ `https://factoreasy.ir/?finora_recovery=1`.
25
+ اگر وجود ندارد فقط همین نشانی دقیق به Redirect URLs اضافه شود؛ نشانیهای قبلی
26
+ ورود و گوگل حفظ شوند، wildcard جدید لازم نیست.
27
+2. الگوی ایمیل **Reset Password** باید پیوند تأیید Auth را با
28
+ `{{ .ConfirmationURL }}` داشته باشد. پیوند مستقیم به سایت، تأیید بازیابی را
29
+ انجام نمیدهد. قالب/SMTP واقعی فعلی هنوز از این محیط تأیید نشده است؛ بدون بررسی
30
+ آنها ادعای تحویل ایمیل نکنید. تغییر SMTP یا الگوی موجود فقط به اندازهٔ نیاز
31
+ تأییدشده انجام شود؛ سرویس/هزینهٔ جدید در این PR لازم نیست.
32
+3. نسخهٔ جدید `admin-user-management` از هر دو فایل واقعی
33
+ `supabase/functions/admin-user-management/index.ts` و `handler.mjs` منتشر شود.
34
+ متغیرهای محیطی موجود سمت سرور و تنظیم اعتبارسنجی JWT فعلی حفظ شوند؛ هیچ کلید
35
+ سرویس وارد مرورگر، گزارش یا PR نشود. نسخهٔ بررسیشدهٔ قبلی ACTIVE **3** بود.
36
+4. تنها بعد از تأیید backend و تنظیمات بازگشت، PR کلاینت با مسیر عادی شاخهٔ
37
+ محافظتشده ادغام و همان SHA از Release Gate و Pages منتشر شود. قبل از این ترتیب،
38
+ دکمهٔ مدیر با backend قدیمی به خطای «سرویس بازیابی هنوز فعال نیست» میرسد.
39
+
40
+## پذیرش واقعی پس از اجازه
41
+
42
+فقط یک حساب آزمایشی تعیینشده با ایمیل تحت کنترل مالک استفاده شود. اجرای این بخش
43
+ایمیل واقعی میفرستد و رمز همان حساب را عوض میکند؛ تستهای خودکار این PR آن را
44
+انجام نمیدهند. رمز/توکن/پیوند کامل در چت یا لاگ ثبت نشود.
45
+
46
+- درخواست فراموشی رمز، دریافت ایمیل و بازکردن پیوند در مرورگر دیگر؛ رمز جدید فقط در
47
+ فرم امن سایت وارد شود، سپس خروج و ورود با رمز جدید بررسی شود.
48
+- درخواست مدیر سراسری و مدیر سازمان مجاز؛ تأیید رسیدن پیوند فقط به صاحب حساب.
49
+- مدیر سازمان دیگر/عضو عادی/عضو معلق اجازهٔ ارسال نداشته باشد.
50
+- بازکردن پیوند منقضی در مرورگری که حساب دیگری دارد، رمز آن حساب را تغییر ندهد.
51
+- ورود معمول با رمز، ورود با کد ایمیل و گوگل جداگانه بررسی شوند. آزمون اینترنت
52
+ دستگاه مالک و تیکهای تنظیمات همچنان پذیرش مستقل دارند.
53
+
54
+## برگشت
55
+
56
+اگر پذیرش واقعی ناموفق بود، انتشار کلاینت را متوقف یا PR کلاینت را با مسیر عادی
57
+revert کنید؛ خطا را با کد طبقهبندیشده و زمان ثبت کنید، نه اطلاعات حساب. بازگردانی
58
+نسخهٔ Edge یا تنظیمات Auth نیازمند همان مجوز عملیاتی و ثبت نسخه/تنظیم قبلی است.
59
+تاریخچهٔ مالی، رمزهای کاربران و دادههای شرکت برای rollback دستکاری نشوند.
60
+
61
+## حدود شواهد
62
+
63
+تستهای Node و مرورگر، سرویس Auth/ایمیل را شبیهسازی میکنند و پاسخهای ناموفق،
64
+مجوزها و پیوندهای خراب را میآزمایند. نتیجهٔ exact-head CI و شمارش تستهای اجراشده
65
+در PR و `PROJECT_STATE.md` ثبت میشود. **NOT VERIFIED:** تنظیمات واقعی SMTP و allowlist،
66
+تحویل/پوشهٔ هرزنامه، تغییر رمز واقعی، ورود روی اینترنت مالک، چاپ فیزیکی و رفتار دو
67
+کاربر روی Production. هیچ ارسال ایمیل یا تغییر رمز واقعی در مرحلهٔ پیادهسازی نیست.
docs/superpowers/plans/2026-10-25-password-recovery.md
new
+70
@@ -0,0 +1,70 @@
1
+# Password recovery implementation plan
2
+
3
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans task by task.
4
+
5
+**Goal:** Users reset their own password through emailed recovery links, including links initiated by authorized managers.
6
+
7
+**Architecture:** Reuse the existing Auth SDK/Edge entrypoint and authorization model. A small early IIFE owns public recovery state; a mockable Edge handler verifies manager scope and sends only to the server-resolved confirmed identity.
8
+
9
+**Tech Stack:** Existing classic JS, Supabase JS, Deno Edge entrypoint, Node tests, Playwright; no new dependency.
10
+
11
+**Spec:** `docs/superpowers/specs/2026-10-25-password-recovery-design.md`.
12
+
13
+## Global constraints
14
+
15
+- Links only for every manager, per owner's explicit choice.
16
+- Preserve normal PKCE, OTP signup, financial behavior, RLS/roles/grants.
17
+- Canonical callback: `https://factoreasy.ir/?finora_recovery=1`.
18
+- No production mail/password/configuration writes during implementation/testing.
19
+
20
+## Review focus
21
+
22
+- Invalid callback with another user's cached session must not change that user.
23
+- Organization membership cannot authorize a global password takeover.
24
+- Inactive or foreign roles/targets and failed lookups fail closed.
25
+- Pending duplicate clicks and delivery failures cannot report false success.
26
+- Strict-CSP early login readiness and normal onboarding remain intact.
27
+
28
+### 1. Server recovery authorization
29
+
30
+Files: `supabase/functions/admin-user-management/{index.ts,handler.mjs}`,
31
+`scripts/admin-recovery-handler.spec.mjs`, existing provisioning contract.
32
+Interface: `send_recovery` body carries `user_id` plus optional `organization_id`;
33
+success returns `{ok:true}`, failure returns a bounded error code.
34
+
35
+- [x] Write behavioral tests against the old handler and observe recovery RED.
36
+- [x] Extract dependency-injected handler; preserve global-admin creation.
37
+- [x] Implement scoped recovery-only action and reject legacy direct set.
38
+- [x] Run all negative/compatibility tests GREEN; inspect secret-free responses/logs.
39
+
40
+### 2. Public recovery and validated callback
41
+
42
+Files: `js/password-recovery.js`, minimal `js/core.js` hooks, public `index.html`
43
+controls, necessary cache/build assertions, `scripts/password-recovery.spec.js`.
44
+
45
+- [x] Write failing request, callback-isolation and update-state tests.
46
+- [x] Add early capture/session validation, neutral send UI and required new-password panel.
47
+- [x] Keep recovery intent separate from readiness; handle reload and cancellation safely.
48
+- [x] Pass focused tests against source and generated strict-CSP Pages.
49
+
50
+### 3. Manager buttons and complete verification
51
+
52
+Files: `js/admin.js`, `js/organization-rbac.js`,
53
+`scripts/password-admin-ui.spec.js`, `.github/workflows/quality.yml`, continuity docs.
54
+Interface: `finoraSendUserRecovery(userId, organizationId='')` invokes the Edge
55
+action once, with existing client role guards plus fresh server authorization.
56
+
57
+- [x] Add failing global/tenant UI tests for Auth UUID, role guards, duplicate sends and errors.
58
+- [x] Add link-only buttons and shared localized sender with confirmation/pending/cooldown.
59
+- [x] Integrate Node and browser suites into existing CI; preserve prior checks.
60
+- [ ] Run static/Golden/browser, review full diff and exact remote CI; open scoped PR.
61
+- [x] Record files/tests/NOT VERIFIED and concrete activation settings before production approval.
62
+
63
+## Verified implementation checkpoint
64
+
65
+- Full Quality browser command: **175/175 PASS** (150 existing +17 recovery +8 manager).
66
+- Focused recovery:17/17 source and17/17 generated strict-CSP Pages; manager:8/8 source and8/8 generated Pages.
67
+- 50 Quality pre-browser commands including45/45 server cases and Golden PASS; additional release-safety PASS.
68
+- Independent current-diff security review: no remaining blocker; actual invalid-callback/account-switch/logout race RED cases were corrected.
69
+- Runtime code is complete. Exact remote CI remains the publication checkbox above; no production activation or actual email/password acceptance has occurred.
70
+- Activation instructions: `docs/PASSWORD_RECOVERY_ACTIVATION_2026-10-25.md`.
docs/superpowers/specs/2026-10-25-password-recovery-design.md
new
+69
@@ -0,0 +1,69 @@
1
+# Password recovery through user-owned links
2
+
3
+The owner requested Forgot Password on login and assistance from user, license
4
+and access administration. They explicitly chose **recovery links for every
5
+authorized manager**: only the recipient enters the new password.
6
+
7
+## Approaches and decision
8
+
9
+Direct administrator password entry uses an existing global-admin Edge action,
10
+but extending it to organization managers would permit taking over a global
11
+identity shared by multiple companies. Global-admin direct reset plus company
12
+manager links was offered; the owner instead selected links for all managers.
13
+The unused direct-set action will reject requests; existing account creation
14
+retains its existing global-admin-only contract.
15
+
16
+## Scope and authorization
17
+
18
+Add a link button in central users/licenses and in eligible active organization
19
+member rows. The browser passes Auth user UUID and, for tenant administration,
20
+organization UUID; membership UUID and company-record ID are different values.
21
+Fresh server verification authorizes global profiles.admin, or an active actor
22
+membership with is_owner or active core/full_suite configure grants. Assigned
23
+roles and permissions must belong to that same organization and be active.
24
+Tenant targets must be active members of that organization. Email is resolved
25
+from the current confirmed Auth identity, never browser input or stale profile.
26
+No role, grant, database policy, financial record or schema changes are needed.
27
+
28
+Recovery sends through Supabase Auth's existing email delivery. The callback is
29
+fixed at `https://factoreasy.ir/?finora_recovery=1`; no arbitrary recipient or
30
+redirect input is accepted. Responses and audit logs contain no token, link,
31
+password or email address. Existing Auth/provider limits remain authoritative;
32
+browser pending/cooldown checks suppress accidental repeated sends.
33
+
34
+## Login and callback behavior
35
+
36
+Forgot Password validates email and presents an account-neutral result. Delivery
37
+errors/rate limits use bounded Persian messages. The recipient gets a dedicated
38
+new-password/confirmation panel with existing password-strength rules and no
39
+optional password-skip action. Ordinary OTP onboarding stays separate.
40
+
41
+The pinned browser SDK uses PKCE for normal authentication and rejects implicit
42
+callback fragments in that mode. Preserve normal PKCE: the small early recovery
43
+module captures genuine recovery fragments before createClient, scrubs them,
44
+then calls the public setSession API after SDK initialization. Only a validated
45
+recovery session enables password editing. A marker or an unrelated cached
46
+session does not authorize recovery. A tab-local, nonsecret proof bound to the
47
+verified user/session and a deadline may resume a consumed callback after reload;
48
+fresh invalid callbacks discard that proof. No passwords or tokens are persisted
49
+by the helper or logged. Successful update clears fields/proof and enters that
50
+same verified account once. No tenant records load before password completion.
51
+
52
+The request-only email sender uses an ephemeral implicit client with persistence,
53
+refresh and URL detection disabled; this supports links opened in another browser
54
+without changing normal OAuth PKCE. SDK requests use the existing bounded Auth
55
+transport. Generated Pages retains local scripts and strict CSP.
56
+
57
+## Verification and activation
58
+
59
+Use meaningful offline handler tests and Playwright with production transport
60
+blocked: permission spoofing, foreign/inactive membership/roles, recipient and
61
+redirect injection, failed lookups, legacy direct reset rejection, ordinary
62
+creation regression, callback races, invalid link with another cached account,
63
+validation, duplicate submits, update failure and generated Pages.
64
+
65
+Run existing static, Golden, browser, security and disposable-DB checks without
66
+weakening expectations. Production Edge deployment, callback allowlist/SMTP and
67
+actual mail delivery/password changes are separate activation/acceptance steps;
68
+prepare concrete files/tests/settings first. No real mail or password change is
69
+part of synthetic verification. Previous owner-ISP/real settings QA remains open.
index.html
+14
-4
@@ -13,7 +13,7 @@
13
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; font-src 'self' https://cdn.jsdelivr.net data:; img-src 'self' data: blob:; connect-src 'self' https://hcsixhqbyuhpshfwqpjx.supabase.co; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests" />
14
<meta name="apple-mobile-web-app-capable" content="yes" />
15
<meta name="theme-color" content="#071a48" />
16
-<link rel="preload" as="script" href="js/core.js?v=20261024-login-readiness-v1" />
16
+<link rel="preload" as="script" href="js/core.js?v=20261025-password-recovery-v1" />
17
<link rel="preload" as="script" href="js/login-connectivity.js?v=20261024-independent-probes-v4" />
18
<script src="vendor/supabase.js"></script>
19
<script async src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
@@ -234,6 +234,7 @@ body{background:#f6f9fc}
234
<div class="auth-divider">یا با ایمیل</div>
235
<div class="form-group"><label>ایمیل</label><input type="email" id="auth-email" class="form-control" placeholder="name@example.com" autocomplete="email" autocapitalize="none" dir="ltr" /></div>
236
<div class="form-group"><label>رمز عبور</label><input type="password" id="auth-password" class="form-control" placeholder="رمز عبور" autocomplete="current-password" dir="ltr" /></div>
237
+ <button disabled type="button" id="auth-forgot-password" class="btn btn-secondary" style="width:100%;margin-bottom:10px" onclick="finoraRequestPasswordRecovery()">فراموشی رمز عبور</button>
238
<div class="auth-actions">
239
<button id="auth-login-button" class="btn btn-primary" onclick="handleLogin()" disabled>ورود با رمز</button>
240
<button disabled class="btn btn-secondary" onclick="startEmailOtp(false,false)">ورود با کد ایمیل</button>
@@ -257,6 +258,14 @@ body{background:#f6f9fc}
258
<button disabled class="btn btn-primary" style="width:100%;margin-top:16px" onclick="saveNewPassword()">ذخیره رمز و ورود</button>
259
<button disabled class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="skipSetPassword()">فعلاً بدون رمز ادامه بده</button>
260
</div>
261
+ <div id="auth-recovery-container" style="display:none">
262
+ <h2 style="font-size:18px;margin-bottom:12px">تعیین رمز عبور جدید</h2>
263
+ <p id="auth-recovery-status" aria-live="polite" data-state="loading" style="font-size:13px;line-height:1.9;margin-bottom:12px">در حال بررسی پیوند بازیابی...</p>
264
+ <div class="form-group"><label for="auth-recovery-password">رمز عبور جدید</label><input disabled type="password" id="auth-recovery-password" class="form-control" autocomplete="new-password" dir="ltr" /></div>
265
+ <div class="form-group"><label for="auth-recovery-confirm">تکرار رمز عبور جدید</label><input disabled type="password" id="auth-recovery-confirm" class="form-control" autocomplete="new-password" dir="ltr" /></div>
266
+ <button disabled id="auth-recovery-submit" class="btn btn-primary" style="width:100%" onclick="finoraSaveRecoveredPassword()">ذخیره رمز جدید و ورود</button>
267
+ <button disabled id="auth-recovery-cancel" class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="finoraCancelPasswordRecovery()">بازگشت به ورود</button>
268
+ </div>
269
</div>
270
<aside class="auth-visual" aria-label="معرفی فینورا">
271
<div class="auth-hero">
@@ -893,8 +902,9 @@ body{background:#f6f9fc}
902
<!-- The credential-free connectivity action must be loaded before core declares
903
login actions interactive. Hardened Pages binds static handlers just before core. -->
904
<script src="js/login-connectivity.js?v=20261024-independent-probes-v4"></script>
896
-<script src="js/core.js?v=20261024-login-readiness-v1"></script>
897
-<script src="js/admin.js?v=20261012-provision-error-v1"></script>
905
+<script src="js/password-recovery.js?v=20261025-password-recovery-v1"></script>
906
+<script src="js/core.js?v=20261025-password-recovery-v1"></script>
907
+<script src="js/admin.js?v=20261025-password-recovery-v1"></script>
908
<script src="js/sync.js?v=20261012-login-read-cancel-v1"></script>
909
<script src="js/ui.js?v=20261002-shell-scroll-ownership-v2"></script>
910
<script src="js/invoices.js?v=20261024-settings-zero-vat-v1"></script>
@@ -906,7 +916,7 @@ body{background:#f6f9fc}
916
<script src="js/companies.js?v=20260928-integrity-v4"></script>
917
<script src="js/backup.js?v=20260928-data-v3"></script>
918
<script src="js/words.js"></script>
909
-<script src="js/bootstrap.js?v=20261014-org-license-readiness-v1"></script>
919
+<script src="js/bootstrap.js?v=20261025-password-recovery-v1"></script>
920
921
<style>
922
.form-control, textarea, select { direction: rtl; }
js/admin.js
+48
-1
@@ -23,10 +23,57 @@ 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" 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" 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();}
30
+(function(){
31
+ const pending=new Set(),cooldowns=new Map();
32
+ async function recoveryError(data,error){
33
+ let code=data?.error;
34
+ if(!code&&typeof error?.context?.json==='function'){
35
+ try{code=(await error.context.clone().json())?.error}catch(_ignored){}
36
+ }
37
+ return {
38
+ unauthorized:'نشست ورود معتبر نیست؛ دوباره وارد حساب مدیر شوید.',
39
+ forbidden:'مجوز ارسال پیوند بازیابی را ندارید.',
40
+ organization_access_denied:'برای این کاربر در سازمان فعال مجوز بازیابی ندارید.',
41
+ authorization_unavailable:'بررسی مجوزها انجام نشد؛ کمی بعد دوباره تلاش کنید.',
42
+ invalid_recovery_request:'شناسهٔ کاربر یا سازمان معتبر نیست.',
43
+ recovery_target_unavailable:'ایمیل تأییدشدهٔ این کاربر برای بازیابی در دسترس نیست.',
44
+ recovery_rate_limited:'برای ارسال دوبارهٔ پیوند کمی صبر کنید.',
45
+ recovery_failed:'سرویس ایمیل درخواست بازیابی را نپذیرفت؛ کمی بعد دوباره تلاش کنید.',
46
+ unsupported_action:'سرویس بازیابی هنوز فعال نیست؛ با پشتیبانی تماس بگیرید.'
47
+ }[code]||'ارسال پیوند تأیید نشد؛ پیش از تلاش دوباره، ایمیل کاربر را بررسی کنید.';
48
+ }
49
+ window.finoraSendUserRecovery=async function(userId,organizationId=''){
50
+ const uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
51
+ if(!currentUser||!uuid.test(userId)||organizationId&&!uuid.test(organizationId))return;
52
+ if(organizationId){
53
+ if(organizationId!==currentUser.organizationId||!(currentUser.role==='admin'||window.finoraCanManageOrganization?.()))return;
54
+ }else if(currentUser.role!=='admin')return;
55
+ if(pending.has(userId))return;
56
+ if((cooldowns.get(userId)||0)>Date.now())return alert('پیش از درخواست دوباره، یک دقیقه صبر کنید و ایمیل کاربر را بررسی کنید.');
57
+ if(!confirm('پیوند بازیابی به ایمیل تأییدشدهٔ کاربر فرستاده شود؟ کاربر خودش رمز جدید را تعیین میکند.'))return;
58
+ pending.add(userId);cooldowns.set(userId,Date.now()+60000);
59
+ const buttons=[...document.querySelectorAll('[data-recovery-user="'+userId+'"]')].map(el=>({el,disabled:el.disabled}));
60
+ buttons.forEach(({el})=>{el.disabled=true});
61
+ let timer;
62
+ try{
63
+ const send=async()=>{
64
+ const body={action:'send_recovery',user_id:userId};
65
+ if(organizationId)body.organization_id=organizationId;
66
+ const {data,error}=await sb.functions.invoke('admin-user-management',{body});
67
+ if(error||!data?.ok)return recoveryError(data,error);
68
+ return null;
69
+ };
70
+ const reason=await Promise.race([send(),new Promise(resolve=>{timer=setTimeout(()=>resolve('نتیجهٔ درخواست مشخص نیست؛ ایمیل کاربر را بررسی کنید و پیش از ارسال دوباره یک دقیقه صبر کنید.'),20000)})]);
71
+ if(reason)return alert(reason);
72
+ alert('درخواست ارسال پیوند بازیابی ثبت شد؛ کاربر ایمیل و پوشهٔ هرزنامه را بررسی کند.');
73
+ }catch(_error){alert('نتیجهٔ درخواست مشخص نیست؛ ایمیل کاربر را بررسی کنید و پیش از ارسال دوباره یک دقیقه صبر کنید.')}
74
+ finally{clearTimeout(timer);pending.delete(userId);buttons.forEach(({el,disabled})=>{el.disabled=disabled})}
75
+ };
76
+})();
77
async function adminRpc(name,args,okMsg){
78
const {error}=await sb.rpc(name,args);
79
if(error){alert('خطا: '+(error.message||'عملیات ناموفق بود.'));return false;}
js/bootstrap.js
+1
-1
@@ -3,7 +3,7 @@
3
// browsers may download in parallel but preserve script execution/dependencies.
4
// Auth starts only once all extensions have finished loading or failed.
5
const FINORA_EXTENSION_SCRIPTS=[
6
- "js/organization-rbac.js?v=20261014-org-license-readiness-v1",
6
+ "js/organization-rbac.js?v=20261025-password-recovery-v1",
7
"js/organization-invitations.js?v=20260930-eli3-v1",
8
"js/organization-enterprise-ux.js?v=20260930-eli4-v1",
9
"js/platform-modules.js?v=20261001-platform-c6-v1",
js/core.js
+17
-4
@@ -54,7 +54,8 @@ async function finoraBoundedAuthFetch(input,init={},timeoutMs=12000){
54
if(upstream)upstream.removeEventListener('abort',abortFromUpstream);
55
}
56
}
57
-const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{global:{fetch:finoraBoundedAuthFetch},auth:{persistSession:true,autoRefreshToken:true,detectSessionInUrl:true,flowType:'pkce'}});
57
+const FINORA_AUTH_STORAGE_KEY='sb-'+new URL(SUPABASE_URL).hostname.split('.')[0]+'-auth-token';
58
+const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{global:{fetch:finoraBoundedAuthFetch},auth:{storageKey:FINORA_AUTH_STORAGE_KEY,persistSession:true,autoRefreshToken:true,detectSessionInUrl:true,flowType:'pkce'}});
59
const ID_RE=/^[A-Za-z0-9_-]{1,64}$/;
60
const COLLS=['companies','contacts','products','invoices','purchases','cheques','expenses','payments','settings','fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks','postingProfiles','journalVouchers','journalLines','journalLineDimensions','contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit','warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit','employees','employmentContracts','employeeLeave','cashboxes','pettyCashFunds','complianceRules','payrollRuns','payrollLines','employeeBenefitAccruals','pettyCashTransactions','budgets','costDrivers','costAllocations','intercompanyTransactions','enterpriseAudit'];
61
@@ -183,11 +184,12 @@ function authMsg(err){
184
return 'خطا: '+m;
185
}
186
function showAuthPanel(name){
186
- const ids={main:'auth-form-container',otp:'auth-otp-container',setpass:'auth-setpass-container'};
187
+ const ids={main:'auth-form-container',otp:'auth-otp-container',setpass:'auth-setpass-container',recovery:'auth-recovery-container'};
188
Object.keys(ids).forEach(k=>{const el=document.getElementById(ids[k]);if(el)el.style.display=(k===name)?'block':'none';});
189
}
190
function backToAuthMain(){pendingAuthUser=null;otpCreateUser=false;showAuthPanel('main');}
191
function reportOAuthReturnError(){
192
+ if(window.FinoraPasswordRecovery?.active)return;
193
try{
194
const q=new URLSearchParams(window.location.search);
195
const h=new URLSearchParams((window.location.hash||'').replace(/^#/,''));
@@ -205,22 +207,24 @@ async function initAuthSystem(){
207
finoraAuthInitStarted=true;
208
const screen=document.getElementById('auth-screen');
209
if(screen)screen.style.display='flex';
208
- showAuthPanel('main');
210
+ showAuthPanel(window.FinoraPasswordRecovery?.active?'recovery':'main');
211
// Production externalizes onclick attributes under strict CSP. Do not mark
212
// the controls ready until those actual click listeners are registered.
213
const builtHandlers=!!screen?.querySelector('[data-finora-handler-0]');
214
const canUseActions=typeof checkAuthConnectivity==='function'&&(!builtHandlers||window.FinoraLoginActionsBound===true);
215
if(canUseActions&&screen)screen.querySelectorAll('button').forEach(button=>{button.disabled=false;});
216
+ window.FinoraPasswordRecovery?.render();
217
window.FinoraStartupStatus.authFormReady=canUseActions;
218
setAuthLoginStatus(canUseActions?'فرم ورود و دکمهها آماده هستند.':'عملکرد دکمههای ورود بارگذاری نشده است؛ صفحه را دوباره بارگذاری کنید.',canUseActions?'ready':'error');
219
// Remove the legacy plaintext user database that older versions kept in this browser.
220
try{localStorage.removeItem(AUTH_KEY);}catch(e){}
221
try{sessionStorage.removeItem('easy_factor_session_v4_7');}catch(e){}
222
reportOAuthReturnError();
220
- sb.auth.onAuthStateChange(ev=>{if(ev==='SIGNED_OUT'&¤tUser){window.location.reload();}});
223
+ sb.auth.onAuthStateChange((ev,session)=>{window.FinoraPasswordRecovery?.handleEvent(ev,session);if(ev==='SIGNED_OUT'&¤tUser){window.location.reload();}});
224
try{
225
finoraInitialSessionCheck=sb.auth.getSession();
226
const {data}=await finoraInitialSessionCheck;
227
+ if(window.FinoraPasswordRecovery?.active){await window.FinoraPasswordRecovery.resume(sb,data?.session);return;}
228
if(data&&data.session&&!authBusy){
229
authBusy=true;
230
try{await enterApp(data.session.user);}finally{authBusy=false;}
@@ -233,6 +237,7 @@ async function initAuthSystem(){
237
}
238
}
239
async function handleLogin(){
240
+ if(window.FinoraPasswordRecovery?.active)return;
241
if(authBusy){
242
setAuthLoginStatus('درخواست ورود قبلی هنوز در حال انجام است؛ لطفاً منتظر نتیجه بمانید.','busy');
243
return;
@@ -266,6 +271,7 @@ async function handleLogin(){
271
}
272
}
273
async function signInWithGoogle(){
274
+ if(window.FinoraPasswordRecovery?.active)return;
275
if(authBusy)return;
276
authBusy=true;
277
try{
@@ -274,6 +280,7 @@ async function signInWithGoogle(){
280
}catch(err){authBusy=false;alert(authMsg(err));}
281
}
282
async function startEmailOtp(isResend,createUser){
283
+ if(window.FinoraPasswordRecovery?.active)return;
284
if(authBusy)return;
285
const email=normalizeEmail(isResend===true?otpEmail:document.getElementById('auth-email').value);
286
if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
@@ -291,6 +298,7 @@ async function startEmailOtp(isResend,createUser){
298
finally{authBusy=false;}
299
}
300
async function verifyEmailOtp(){
301
+ if(window.FinoraPasswordRecovery?.active)return;
302
if(authBusy)return;
303
const token=toEnDigits(document.getElementById('auth-otp').value).replace(/\s/g,'');
304
if(!OTP_RE.test(token)){alert('کد را فقط با عدد و کامل وارد کنید.');return;}
@@ -312,6 +320,7 @@ async function verifyEmailOtp(){
320
finally{authBusy=false;}
321
}
322
async function saveNewPassword(){
323
+ if(window.FinoraPasswordRecovery?.active)return;
324
if(authBusy)return;
325
const p1=document.getElementById('auth-newpass').value;
326
const p2=document.getElementById('auth-newpass2').value;
@@ -329,12 +338,14 @@ async function saveNewPassword(){
338
finally{authBusy=false;}
339
}
340
async function skipSetPassword(){
341
+ if(window.FinoraPasswordRecovery?.active)return;
342
if(authBusy||!pendingAuthUser)return;
343
const u=pendingAuthUser;pendingAuthUser=null;
344
authBusy=true;
345
try{await enterApp(u);}finally{authBusy=false;}
346
}
347
async function enterApp(authUser,{timeoutMs=25000}={}){
348
+ if(window.FinoraPasswordRecovery?.active)return;
349
const controller=new AbortController();
350
let timeoutStageCodes=[];
351
const abortLogin=()=>{
@@ -351,6 +362,7 @@ async function enterApp(authUser,{timeoutMs=25000}={}){
362
]),controller.signal));
363
clearTimeout(timer);
364
if(controller.signal.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
365
+ if(window.FinoraPasswordRecovery?.active)return;
366
timer=setTimeout(abortLogin,timeoutMs);
367
setAuthLoginStatus('در حال دریافت مشخصات و دسترسی حساب...','loading');
368
const organizationAccount=fetchCurrentUser(authUser,{signal:controller.signal});
@@ -383,6 +395,7 @@ async function enterApp(authUser,{timeoutMs=25000}={}){
395
}finally{
396
clearTimeout(timer);
397
}
398
+ if(window.FinoraPasswordRecovery?.active){currentUser=null;return;}
399
// Post-login UI. Every step is null-safe / isolated so that one missing element or one failing
400
// render can never abort the rest and leave the app empty (previous bug: #menu-admin-panel).
401
const authScreen=document.getElementById('auth-screen');
js/organization-rbac.js
+5
-1
@@ -166,7 +166,11 @@ window.showOrganizationAccessManager=async function(){
166
const members=await orgManagerData(),mods=configurableModules(),roleData=canManage?await roleManagerData():{roles:[],permissions:[],assignments:[]};
167
const roleModules=canManage?roleConfigurableModules():[];
168
const activeCount=members.filter(m=>m.status==='active').length,maxUsers=Math.max(1,Number(currentUser.maxUsers||1)),remaining=Math.max(0,maxUsers-activeCount);
169
- const memberRows=members.map(m=>'<tr><td>'+esc(m.profile?.full_name||m.profile?.email||m.user_id)+'</td><td>'+esc(m.position_title||'—')+'</td><td>'+esc(m.status)+'</td><td>'+(m.is_owner?'مالک':(canManage?'<button class="btn btn-secondary btn-inline" onclick="organizationSetMemberStatusFromUi(\''+esc(m.id)+'\',\''+(m.status==='active'?'suspended':'active')+'\')">'+(m.status==='active'?'تعلیق':'فعالسازی')+'</button>':'—'))+'</td></tr>').join('');
169
+ const memberRows=members.map(m=>{
170
+ const status=m.is_owner?'مالک':(canManage?'<button class="btn btn-secondary btn-inline" onclick="organizationSetMemberStatusFromUi(\''+esc(m.id)+'\',\''+(m.status==='active'?'suspended':'active')+'\')">'+(m.status==='active'?'تعلیق':'فعالسازی')+'</button>':'—');
171
+ const recovery=canManage&&m.status==='active'?'<button class="btn btn-secondary btn-inline" data-recovery-user="'+esc(m.user_id)+'" onclick="finoraSendUserRecovery(\''+esc(m.user_id)+'\',\''+esc(currentUser.organizationId)+'\')">ارسال پیوند بازیابی</button>':'';
172
+ return '<tr><td>'+esc(m.profile?.full_name||m.profile?.email||m.user_id)+'</td><td>'+esc(m.position_title||'—')+'</td><td>'+esc(m.status)+'</td><td>'+status+' '+recovery+'</td></tr>';
173
+ }).join('');
174
el.innerHTML='<div class="modal-card" style="max-width:900px"><div style="display:flex;justify-content:space-between;gap:10px"><div><h3>مدیریت دسترسی سازمان</h3><p class="af-hint">'+esc(currentUser.organizationName||'')+' · مجوز تجاری و مجوز عضو مستقل از هم هستند.</p><p id="org-seat-summary" class="af-hint"><strong>'+toPersianDigits(activeCount)+'</strong> کاربر فعال از <strong>'+toPersianDigits(maxUsers)+'</strong> · ظرفیت باقیمانده '+toPersianDigits(remaining)+'</p></div><button class="btn btn-secondary btn-inline" onclick="document.getElementById(\'finora-org-access-modal\').classList.remove(\'active\')">بستن</button></div>'+
175
(canManage?'<div class="card" style="margin-top:14px"><h4>افزودن عضو موجود فینورا</h4><div class="form-row"><div class="form-group"><label>ایمیل</label><input id="org-member-email" class="form-control" type="email"></div><div class="form-group"><label>سمت</label><input id="org-member-position" class="form-control"></div></div><button class="btn btn-primary" onclick="organizationAddMemberFromUi()">افزودن عضو</button><p class="af-hint">دعوت کاربر فاقد حساب در ELI-3 اضافه میشود.</p><div class="table-responsive" style="margin-top:12px"><table><thead><tr><th>عضو</th><th>سمت</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody>'+memberRows+'</tbody></table></div></div>':'')+
176
(canManage?'<div class="card"><h4>نقشهای سازمانی</h4><p class="af-hint">نقشها مجوزهای قابل استفاده مجدد هستند؛ مجوز مستقیم هر کاربر همچنان بهعنوان Override مستقل باقی میماند.</p><div class="form-row"><div class="form-group"><label>کلید نقش سفارشی</label><input id="org-role-key" class="form-control" placeholder="regional_accountant"></div><div class="form-group"><label>عنوان نقش</label><input id="org-role-title" class="form-control" placeholder="حسابدار ناحیه"></div></div><button class="btn btn-primary btn-inline" onclick="organizationCreateRoleFromUi()">ایجاد/بهروزرسانی نقش</button><hr style="margin:14px 0"><div class="form-row"><div class="form-group"><label>عضو</label><select id="org-role-member" class="form-control">'+members.filter(m=>!m.is_owner&&m.status==='active').map(m=>'<option value="'+esc(m.id)+'">'+esc(m.profile?.full_name||m.profile?.email||m.position_title||m.user_id)+'</option>').join('')+'</select></div><div class="form-group"><label>نقش</label><select id="org-role-assign" class="form-control">'+roleData.roles.filter(r=>r.active).map(r=>'<option value="'+esc(r.id)+'">'+esc(r.title)+(r.is_system?' · پیشفرض':'')+'</option>').join('')+'</select></div></div><button class="btn btn-success btn-inline" onclick="organizationAssignRoleFromUi()">تخصیص نقش</button><hr style="margin:14px 0"><div class="form-row"><div class="form-group"><label>نقش</label><select id="org-role-perm-role" class="form-control">'+roleData.roles.filter(r=>r.active).map(r=>'<option value="'+esc(r.id)+'">'+esc(r.title)+'</option>').join('')+'</select></div><div class="form-group"><label>ماژول</label><select id="org-role-perm-module" class="form-control">'+roleModules.map(x=>'<option value="'+esc(x[0])+'">'+esc(x[1])+'</option>').join('')+'</select></div><div class="form-group"><label>سطح محرمانگی</label><select id="org-role-perm-clearance" class="form-control"><option value="0">عادی</option><option value="1">محرمانه</option><option value="2">خیلی محرمانه</option><option value="3">سری</option></select></div></div><div class="form-group"><label>قابلیتهای نقش</label><div id="org-role-perm-caps" style="display:flex;gap:10px;flex-wrap:wrap">'+[['read','مشاهده'],['create','ایجاد'],['edit','ویرایش'],['delete','حذف'],['approve','تأیید'],['register','ثبت دبیرخانه'],['refer','ارجاع'],['archive','بایگانی'],['configure','مدیریت']].map(x=>'<label><input type="checkbox" value="'+x[0]+'" '+(x[0]==='read'?'checked':'')+'> '+x[1]+'</label>').join('')+'</div></div><button class="btn btn-success btn-inline" onclick="organizationSaveRolePermissionFromUi()">ثبت مجوز نقش</button><div class="table-responsive" style="margin-top:12px"><table><thead><tr><th>نقش</th><th>نوع</th><th>مجوزها</th><th>تخصیصها</th></tr></thead><tbody>'+roleData.roles.map(r=>'<tr><td>'+esc(r.title)+'</td><td>'+(r.is_system?'پیشفرض':'سفارشی')+'</td><td>'+roleData.permissions.filter(p=>p.role_id===r.id).map(p=>esc(p.module_key)+' ('+esc((p.capabilities||[]).join(', '))+')').join('<br>')+'</td><td>'+toPersianDigits(roleData.assignments.filter(a=>a.role_id===r.id).length)+'</td></tr>').join('')+'</tbody></table></div></div>':'')+
js/password-recovery.js
new
+160
@@ -0,0 +1,160 @@
1
+(function(){
2
+ 'use strict';
3
+ const marker='finora_recovery',proofKey='finora.password-recovery.v1',proofLifetime=15*60*1000;
4
+ const redirectTo='https://factoreasy.ir/?finora_recovery=1';
5
+ const url=new URL(window.location.href),hash=new URLSearchParams(url.hash.slice(1));
6
+ const implicit=hash.get('type')==='recovery';
7
+ const callbackFields=['type','access_token','refresh_token','token_hash','error','error_code','error_description'];
8
+ const callbackFragment=callbackFields.some(key=>hash.has(key));
9
+ const state={active:url.searchParams.get(marker)==='1'||implicit,ready:null,session:null,client:null,busy:false,requestBusy:false,cooldown:0,epoch:0,completed:false,resolving:null,message:'در حال بررسی پیوند بازیابی...',status:'loading'};
10
+ let incoming=implicit?{access_token:hash.get('access_token'),refresh_token:hash.get('refresh_token')}:null;
11
+ const fresh=state.active&&(callbackFragment||url.searchParams.has('code')||callbackFields.some(key=>url.searchParams.has(key)));
12
+ function forgetProof(){try{sessionStorage.removeItem(proofKey);}catch(_){} }
13
+ if(fresh)forgetProof();
14
+ if(state.active){
15
+ url.searchParams.set(marker,'1');
16
+ if(callbackFragment)url.hash='';
17
+ callbackFields.forEach(key=>url.searchParams.delete(key));
18
+ window.history.replaceState(window.history.state,'',url.toString());
19
+ }
20
+ function field(id){return document.getElementById(id);}
21
+ function sessionId(session){
22
+ try{const raw=session.access_token.split('.')[1].replace(/-/g,'+').replace(/_/g,'/');const value=JSON.parse(atob(raw.padEnd(Math.ceil(raw.length/4)*4,'='))).session_id;return typeof value==='string'?value:'';}catch(_){return '';}
23
+ }
24
+ function readProof(){
25
+ try{const p=JSON.parse(sessionStorage.getItem(proofKey)||'null'),age=Date.now()-p?.at;return p&&typeof p.user==='string'&&Number.isFinite(age)&&age>=0&&age<proofLifetime?p:null;}catch(_){return null;}
26
+ }
27
+ function sameSession(proof,session){return !!proof?.session&&proof.user===session?.user?.id&&proof.session===sessionId(session);}
28
+ function ephemeralClient(storageKey){return window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{global:{fetch:finoraBoundedAuthFetch},auth:{flowType:'implicit',persistSession:false,autoRefreshToken:false,detectSessionInUrl:false,storageKey}});}
29
+ function remember(session,user){try{sessionStorage.setItem(proofKey,JSON.stringify({user:user.id,session:sessionId(session),at:Date.now()}));}catch(_){} }
30
+ function cleanUrl(){
31
+ const clean=new URL(window.location.href);[marker,'code','error','error_code','error_description'].forEach(key=>clean.searchParams.delete(key));clean.hash='';window.history.replaceState(window.history.state,'',clean.toString());
32
+ }
33
+ function clearPasswords(){['auth-recovery-password','auth-recovery-confirm'].forEach(id=>{const el=field(id);if(el)el.value='';});}
34
+ function render(){
35
+ if(!state.active)return;
36
+ const screen=field('auth-screen');if(screen)screen.style.display='flex';
37
+ if(typeof showAuthPanel==='function')showAuthPanel('recovery');
38
+ const message=field('auth-recovery-status');if(message){message.textContent=state.message;message.dataset.state=state.status;}
39
+ ['auth-recovery-password','auth-recovery-confirm','auth-recovery-submit'].forEach(id=>{const el=field(id);if(el)el.disabled=!state.ready||state.busy;});
40
+ const cancel=field('auth-recovery-cancel');if(cancel)cancel.disabled=state.busy||state.status==='loading';
41
+ }
42
+ function message(text,status='error'){state.message=text;state.status=status;render();}
43
+ function invalid(){state.ready=null;state.session=null;forgetProof();clearPasswords();message('پیوند بازیابی معتبر نیست یا منقضی شده است. از صفحه ورود دوباره درخواست بدهید.');}
44
+ async function resume(client,restored){
45
+ state.client=client;if(!state.active||state.completed)return false;
46
+ if(state.resolving)return state.resolving;
47
+ const epoch=state.epoch;
48
+ state.resolving=(async()=>{
49
+ try{
50
+ render();let verified=state.session;
51
+ if(incoming){
52
+ const pair=incoming;incoming=null;
53
+ if(!pair.access_token||!pair.refresh_token){invalid();return false;}
54
+ const {data,error}=await client.auth.setSession(pair);
55
+ if(epoch!==state.epoch)return false;
56
+ if(error||!data?.user||!data?.session){invalid();return false;}
57
+ verified=data.session;
58
+ }
59
+ const proof=readProof();
60
+ if(!verified){
61
+ if(!sameSession(proof,restored)){invalid();return false;}
62
+ verified=restored;
63
+ }
64
+ const {data,error}=await client.auth.getUser(verified.access_token);
65
+ if(epoch!==state.epoch)return false;
66
+ if(error||!data?.user||data.user.id!==verified.user?.id||!sessionId(verified)){invalid();return false;}
67
+ const first=!state.ready;state.ready=data.user;state.session=verified;
68
+ if(!proof)remember(verified,data.user);
69
+ if(first)clearPasswords();
70
+ message('پیوند تأیید شد. رمز عبور جدید و تکرار آن را وارد کنید.','ready');return true;
71
+ }catch(_){if(epoch===state.epoch)invalid();return false;}
72
+ finally{state.resolving=null;}
73
+ })();
74
+ return state.resolving;
75
+ }
76
+ function handleEvent(event,session){
77
+ if(event!=='PASSWORD_RECOVERY'||!session?.user||state.completed)return;
78
+ state.active=true;state.session=session;
79
+ const current=new URL(window.location.href);current.searchParams.set(marker,'1');window.history.replaceState(window.history.state,'',current.toString());
80
+ render();if(state.client)setTimeout(()=>{void resume(state.client,session);},0);
81
+ }
82
+ async function request(){
83
+ if(state.requestBusy||state.active||typeof authBusy!=='undefined'&&authBusy)return;
84
+ if(Date.now()<state.cooldown)return;
85
+ const email=String(field('auth-email')?.value||'').trim().toLowerCase();
86
+ if(email.length>254||!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)){setAuthLoginStatus('ایمیل معتبر وارد کنید.','error');field('auth-email')?.focus();return;}
87
+ state.requestBusy=true;const button=field('auth-forgot-password');if(button)button.disabled=true;
88
+ try{
89
+ const sender=ephemeralClient('finora-recovery-request');
90
+ const {error}=await sender.auth.resetPasswordForEmail(email,{redirectTo});
91
+ if(error&&error.code!=='user_not_found'&&error.code!=='email_not_found')throw error;
92
+ state.cooldown=Date.now()+60000;
93
+ setAuthLoginStatus('اگر حسابی با این ایمیل وجود داشته باشد، پیوند بازیابی ارسال میشود. ایمیل و پوشه هرزنامه را بررسی کنید.','ready');
94
+ }catch(error){
95
+ const code=String(error?.code||'');setAuthLoginStatus(code.includes('rate_limit')?'تعداد درخواستها زیاد است؛ چند دقیقه بعد دوباره تلاش کنید.':'ارسال پیوند بازیابی انجام نشد؛ اتصال را بررسی و دوباره تلاش کنید.','error');
96
+ }finally{state.requestBusy=false;if(button)button.disabled=false;}
97
+ }
98
+ async function save(){
99
+ if(!state.active||!state.ready||!state.client||state.busy)return;
100
+ const password=field('auth-recovery-password')?.value||'',confirm=field('auth-recovery-confirm')?.value||'';
101
+ if(!isStrongPassword(password)){message('رمز عبور باید حداقل ۸ کاراکتر و شامل یک حرف و یک عدد باشد.');return;}
102
+ if(password!==confirm){message('رمز جدید و تکرار آن باید یکسان باشند.');return;}
103
+ state.busy=true;render();
104
+ try{
105
+ const proof=readProof(),expected=state.ready.id;
106
+ const {data:checked,error:checkError}=await state.client.auth.getUser();
107
+ if(!proof||checkError||checked?.user?.id!==expected||proof.user!==expected){invalid();return;}
108
+ const {data:current,error:sessionError}=await state.client.auth.getSession();
109
+ if(sessionError||!sameSession(proof,current?.session)){invalid();return;}
110
+ // Pin the mutation to this recovery identity: another tab can change the
111
+ // persistent SDK session between validation and updateUser's storage read.
112
+ const writer=ephemeralClient('finora-recovery-update');
113
+ const {data:bound,error:bindError}=await writer.auth.setSession(current.session);
114
+ if(bindError||!sameSession(proof,bound?.session)){invalid();return;}
115
+ const {data,error}=await writer.auth.updateUser({password,data:{has_password:true}});
116
+ if(error){message(error.code==='weak_password'?'رمز عبور انتخابشده شرایط امنیتی سرور را ندارد.':'ذخیره رمز عبور انجام نشد؛ دوباره تلاش کنید.');return;}
117
+ if(data?.user?.id!==expected){invalid();return;}
118
+ const {data:after,error:afterError}=await state.client.auth.getSession();
119
+ state.completed=true;state.active=false;state.ready=null;state.session=null;state.epoch++;
120
+ clearPasswords();forgetProof();cleanUrl();
121
+ if(afterError||!sameSession(proof,after?.session)){showAuthPanel('main');setAuthLoginStatus('رمز جدید ذخیره شد. نشست مرورگر تغییر کرده است؛ برای ادامه با حساب موردنظر وارد شوید.','ready');return;}
122
+ await enterApp(data.user);
123
+ }catch(_){message('ذخیره رمز عبور انجام نشد؛ اتصال را بررسی و دوباره تلاش کنید.');}
124
+ finally{state.busy=false;render();}
125
+ }
126
+ async function cancel(){
127
+ if(state.busy||state.resolving||state.status==='loading')return;
128
+ state.epoch++;
129
+ if(state.ready&&state.client){
130
+ state.busy=true;render();
131
+ try{
132
+ const {data,error:sessionError}=await state.client.auth.getSession();if(sessionError)throw sessionError;
133
+ const proof=readProof();
134
+ if(sameSession(proof,data?.session)){
135
+ const writer=ephemeralClient('finora-recovery-cancel');
136
+ const {data:bound,error:bindError}=await writer.auth.setSession(data.session);if(bindError||!sameSession(proof,bound?.session))throw bindError||new Error('recovery_session_changed');
137
+ const {error}=await writer.auth.signOut({scope:'local'});if(error)throw error;
138
+ // The public SDK logout rereads persistent storage. Revoke only the
139
+ // recovery identity and clear our configured cache only if it still matches.
140
+ const cached=JSON.parse(localStorage.getItem(FINORA_AUTH_STORAGE_KEY)||'null');
141
+ if(sameSession(proof,cached))localStorage.removeItem(FINORA_AUTH_STORAGE_KEY);
142
+ }
143
+ }
144
+ catch(_){state.busy=false;message('خروج از نشست بازیابی کامل نشد؛ دوباره تلاش کنید.');return;}
145
+ }
146
+ state.active=false;state.completed=true;state.ready=null;state.session=null;state.busy=false;incoming=null;
147
+ clearPasswords();forgetProof();cleanUrl();showAuthPanel('main');setAuthLoginStatus('فرم ورود آماده است.','ready');
148
+ }
149
+ window.FinoraPasswordRecovery={get active(){return state.active;},resume,handleEvent,render};
150
+ window.finoraRequestPasswordRecovery=request;
151
+ window.finoraSaveRecoveredPassword=save;
152
+ window.finoraCancelPasswordRecovery=cancel;
153
+ window.addEventListener('hashchange',()=>{
154
+ const next=new URL(window.location.href),fragment=new URLSearchParams(next.hash.slice(1));
155
+ if(!callbackFields.some(key=>fragment.has(key))||!state.active&&next.searchParams.get(marker)!=='1'&&fragment.get('type')!=='recovery')return;
156
+ state.active=true;state.ready=null;state.status='loading';state.epoch++;forgetProof();clearPasswords();render();
157
+ window.location.reload();
158
+ });
159
+ render();
160
+})();
scripts/admin-provisioning-contract.mjs
+6
-3
@@ -1,16 +1,19 @@
1
import{readFileSync}from'node:fs';
2
import assert from'node:assert/strict';
3
-const edge=readFileSync('supabase/functions/admin-user-management/index.ts','utf8');
3
+const entry=readFileSync('supabase/functions/admin-user-management/index.ts','utf8');
4
+const edge=readFileSync('supabase/functions/admin-user-management/handler.mjs','utf8');
5
const ui=readFileSync('js/admin.js','utf8');
6
const html=readFileSync('index.html','utf8');
7
assert.match(edge,/auth\.getUser\(token\)/,'Caller bearer token must be verified on server');
7
-assert.match(edge,/profile\?\.role!=="admin"/,'Profile role must be verified via service-side query');
8
+assert.match(entry,/createAdminUserManagementHandler/,'Deployed entry must use the tested request handler');
9
+assert.match(edge,/profile\?\.role\s*!==\s*"admin"/,'Profile role must be verified via service-side query');
10
assert.match(edge,/SUPABASE_SERVICE_ROLE_KEY/,'Service-side admin API must be used');
11
assert.match(edge,/server\.auth\.admin\.createUser/,'Account created only in server Auth admin API');
10
-assert.match(edge,/email_confirm:true/,'Direct provision uses confirmed address');
12
+assert.match(edge,/email_confirm:\s*true/,'Direct provision uses confirmed address');
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');
17
assert.match(ui,/currentUser\.role!=='admin'/,'UI refuses non-admin account creation');
18
assert.match(html,/id="admin-create-user-button"/,'Central admin create button must exist');
19
assert.doesNotMatch(ui,/SUPABASE_SERVICE_ROLE_KEY/,'Service role key never enters browser');
scripts/admin-recovery-handler.spec.mjs
new
+280
@@ -0,0 +1,280 @@
1
+import assert from 'node:assert/strict';
2
+import {existsSync,readFileSync} from 'node:fs';
3
+import test from 'node:test';
4
+
5
+const ACTOR='11111111-1111-4111-8111-111111111111';
6
+const TARGET='22222222-2222-4222-8222-222222222222';
7
+const ACTOR_MEMBER='33333333-3333-4333-8333-333333333333';
8
+const TARGET_MEMBER='44444444-4444-4444-8444-444444444444';
9
+const ROLE='55555555-5555-4555-8555-555555555555';
10
+const FOREIGN_ROLE='66666666-6666-4666-8666-666666666666';
11
+const CREATED='77777777-7777-4777-8777-777777777777';
12
+const ORG='aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
13
+const OTHER_ORG='bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
14
+const CALLBACK='https://factoreasy.ir/?finora_recovery=1';
15
+const handlerPath=new URL('../supabase/functions/admin-user-management/handler.mjs',import.meta.url);
16
+
17
+async function loadHandler(dependencies){
18
+ if(existsSync(handlerPath)){
19
+ const {createAdminUserManagementHandler}=await import(handlerPath.href);
20
+ return createAdminUserManagementHandler(dependencies);
21
+ }
22
+ // Exercise the unchanged inline Deno handler during the RED run, with no SDK/network import.
23
+ let handler;
24
+ const source=readFileSync(new URL('../supabase/functions/admin-user-management/index.ts',import.meta.url),'utf8')
25
+ .replace(/^import .*;\s*$/gm,'')
26
+ .replace(/let body:\s*Record<string,unknown>;/,'let body;')
27
+ .replace(/:\s*string\s*\|\s*null/g,'')
28
+ .replace(/:\s*(?:string|number|unknown|Request)\b/g,'');
29
+ new Function('createClient','Deno','console',source)(dependencies.createClient,{
30
+ env:{get:dependencies.getEnv},serve:value=>{handler=value;}
31
+ },dependencies.logger);
32
+ assert.equal(typeof handler,'function');
33
+ return handler;
34
+}
35
+
36
+async function fixture(options={}){
37
+ const tables={
38
+ profiles:[{id:ACTOR,role:options.admin?'admin':'user'},{id:TARGET,role:'user'}],
39
+ organizations:[{id:ORG,status:'active'},{id:OTHER_ORG,status:'active'}],
40
+ organization_members:[
41
+ {id:ACTOR_MEMBER,organization_id:ORG,user_id:ACTOR,status:'active',is_owner:!!options.owner},
42
+ {id:TARGET_MEMBER,organization_id:ORG,user_id:TARGET,status:'active',is_owner:false}
43
+ ],
44
+ member_module_permissions:[],organization_member_roles:[],organization_roles:[],organization_role_permissions:[]
45
+ };
46
+ const calls={clients:[],queries:[],authLookups:[],targetLookups:[],emails:[],creates:[],updates:[],links:[],logs:[]};
47
+ const failures=new Set();
48
+ const targetUser={id:TARGET,email:'verified@example.invalid',email_confirmed_at:'2026-10-01T00:00:00Z'};
49
+ function query(table){
50
+ const filters=[];
51
+ function result(one=false){
52
+ calls.queries.push({table,filters:filters.slice()});
53
+ if(failures.has(table))return {data:null,error:{message:'PRIVATE_DATABASE_ERROR'}};
54
+ const rows=(tables[table]||[]).filter(row=>filters.every(([kind,key,value])=>kind==='eq'?row[key]===value:value.includes(row[key])));
55
+ return {data:one?(rows[0]||null):rows,error:null};
56
+ }
57
+ return {
58
+ select(){return this;},eq(key,value){filters.push(['eq',key,value]);return this;},
59
+ in(key,values){filters.push(['in',key,values]);return this;},limit(){return this;},
60
+ single(){return Promise.resolve(result(true));},maybeSingle(){return Promise.resolve(result(true));},
61
+ then(resolve,reject){return Promise.resolve(result()).then(resolve,reject);}
62
+ };
63
+ }
64
+ const getEnv=name=>({SUPABASE_URL:'https://fixture.example.invalid',SUPABASE_ANON_KEY:'anon-fixture',SUPABASE_SERVICE_ROLE_KEY:options.missingConfig?undefined:'service-fixture'})[name];
65
+ const createClient=(url,key,config)=>{
66
+ calls.clients.push({url,key,config});
67
+ return {
68
+ from:query,
69
+ auth:{
70
+ getUser:async token=>{calls.authLookups.push(token);return {data:{user:options.authError?null:{id:ACTOR,user_metadata:options.userMetadata||{}}},error:options.authError||null};},
71
+ resetPasswordForEmail:async(email,config)=>{calls.emails.push({email,config,key});if(options.emailThrows)throw new Error('PRIVATE_EMAIL_ERROR');return {data:{},error:options.emailError||null};},
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};},
76
+ generateLink:async(...args)=>{calls.links.push(args);return {data:{properties:{action_link:'PRIVATE_ACTION_LINK'}},error:null};}
77
+ }
78
+ }
79
+ };
80
+ };
81
+ const handler=await loadHandler({createClient,getEnv,logger:{info:(...args)=>calls.logs.push(args),error:(...args)=>calls.logs.push(args)}});
82
+ async function invoke(body={action:'send_recovery',user_id:TARGET,organization_id:ORG},requestOptions={}){
83
+ const method=requestOptions.method||'POST';
84
+ const headers={'Content-Type':'application/json'};
85
+ if(requestOptions.origin!==null)headers.Origin=requestOptions.origin||'https://factoreasy.ir';
86
+ if(requestOptions.authorization!==null)headers.Authorization=requestOptions.authorization||'Bearer fixture-token';
87
+ const request=new Request('https://fixture.example.invalid/functions/v1/admin-user-management',{
88
+ method,headers,...(method==='POST'?{body:requestOptions.rawBody??JSON.stringify(body)}:{})
89
+ });
90
+ const response=await handler(request);
91
+ return {status:response.status,body:response.status===204?null:await response.json(),headers:response.headers};
92
+ }
93
+ return {tables,calls,failures,targetUser,invoke};
94
+}
95
+function managerRole(f){
96
+ f.tables.organization_member_roles.push({organization_id:ORG,member_id:ACTOR_MEMBER,role_id:ROLE,active:true});
97
+ f.tables.organization_roles.push({id:ROLE,organization_id:ORG,active:true,role_key:'system_admin'});
98
+ f.tables.organization_role_permissions.push({organization_id:ORG,role_id:ROLE,module_key:'core',capabilities:['read','configure']});
99
+}
100
+function noPasswordMutation(f){assert.equal(f.calls.updates.length,0);assert.equal(f.calls.links.length,0);}
101
+
102
+test('global administrator requests only the current verified Auth email and fixed callback',async()=>{
103
+ const f=await fixture({admin:true});
104
+ const result=await f.invoke({action:'send_recovery',user_id:TARGET});
105
+ assert.equal(result.status,200);assert.deepEqual(result.body,{ok:true});
106
+ assert.deepEqual(f.calls.targetLookups,[TARGET]);
107
+ assert.deepEqual(f.calls.emails,[{email:f.targetUser.email,config:{redirectTo:CALLBACK},key:'anon-fixture'}]);
108
+ assert.deepEqual(f.calls.authLookups,['fixture-token']);
109
+ for(const {config} of f.calls.clients){
110
+ assert.equal(config.auth.persistSession,false);assert.equal(config.auth.autoRefreshToken,false);
111
+ assert.equal(config.auth.detectSessionInUrl,false);assert.equal(config.auth.flowType,'implicit');
112
+ }
113
+ noPasswordMutation(f);
114
+});
115
+test('active organization owner may request recovery for an active same-organization Auth user',async()=>{
116
+ const f=await fixture({owner:true});assert.equal((await f.invoke()).status,200);
117
+ assert.equal(f.calls.emails.length,1);noPasswordMutation(f);
118
+});
119
+test('ordinary member and forged user metadata never grant recovery management',async()=>{
120
+ const f=await fixture({userMetadata:{role:'admin',is_owner:true,core_configure:true}});
121
+ assert.equal((await f.invoke()).status,403);assert.equal(f.calls.emails.length,0);noPasswordMutation(f);
122
+});
123
+test('direct core configure permission authorizes the active member',async()=>{
124
+ const f=await fixture();f.tables.member_module_permissions.push({organization_id:ORG,member_id:ACTOR_MEMBER,module_key:'core',capabilities:['configure']});
125
+ assert.equal((await f.invoke()).status,200);assert.equal(f.calls.emails.length,1);
126
+});
127
+test('existing full_suite configure permission authorizes the active member',async()=>{
128
+ const f=await fixture();f.tables.member_module_permissions.push({organization_id:ORG,member_id:ACTOR_MEMBER,module_key:'full_suite',capabilities:['configure']});
129
+ assert.equal((await f.invoke()).status,200);
130
+});
131
+test('module-specific configure and malformed capability strings do not manage recovery',async()=>{
132
+ for(const permission of [{module_key:'accounting',capabilities:['configure']},{module_key:'core',capabilities:'configure'}]){
133
+ const f=await fixture();f.tables.member_module_permissions.push({organization_id:ORG,member_id:ACTOR_MEMBER,...permission});
134
+ assert.equal((await f.invoke()).status,403);assert.equal(f.calls.emails.length,0);
135
+ }
136
+});
137
+test('active reusable role permission authorizes recovery without a new global role',async()=>{
138
+ const f=await fixture();managerRole(f);assert.equal((await f.invoke()).status,200);assert.equal(f.calls.emails.length,1);
139
+});
140
+test('system_admin role name without configure permission grants nothing',async()=>{
141
+ const f=await fixture();managerRole(f);f.tables.organization_role_permissions=[];
142
+ assert.equal((await f.invoke()).status,403);assert.equal(f.calls.emails.length,0);
143
+});
144
+for(const mutation of ['inactive assignment','inactive role','foreign assignment','foreign role','foreign permission']){
145
+ test(`${mutation} cannot authorize recovery`,async()=>{
146
+ const f=await fixture();managerRole(f);
147
+ if(mutation==='inactive assignment')f.tables.organization_member_roles[0].active=false;
148
+ if(mutation==='inactive role')f.tables.organization_roles[0].active=false;
149
+ if(mutation==='foreign assignment')f.tables.organization_member_roles[0].organization_id=OTHER_ORG;
150
+ if(mutation==='foreign role')f.tables.organization_roles[0].organization_id=OTHER_ORG;
151
+ if(mutation==='foreign permission')f.tables.organization_role_permissions[0].organization_id=OTHER_ORG;
152
+ assert.equal((await f.invoke()).status,403);assert.equal(f.calls.emails.length,0);noPasswordMutation(f);
153
+ });
154
+}
155
+for(const who of ['actor','target'])for(const status of ['suspended','left']){
156
+ test(`${status} ${who} membership cannot send a recovery email`,async()=>{
157
+ const f=await fixture({owner:true});f.tables.organization_members[who==='actor'?0:1].status=status;
158
+ assert.equal((await f.invoke()).status,403);assert.equal(f.calls.emails.length,0);
159
+ });
160
+}
161
+test('cross-organization target and organization identifiers cannot escape caller scope',async()=>{
162
+ const f=await fixture({owner:true});f.tables.organization_members[1].organization_id=OTHER_ORG;
163
+ assert.equal((await f.invoke()).status,403);
164
+ assert.equal((await f.invoke({action:'send_recovery',user_id:TARGET,organization_id:OTHER_ORG})).status,403);
165
+ assert.equal(f.calls.emails.length,0);
166
+});
167
+test('membership UUID is not an Auth-user UUID and cannot select a recipient',async()=>{
168
+ const f=await fixture({owner:true});
169
+ assert.equal((await f.invoke({action:'send_recovery',user_id:TARGET_MEMBER,organization_id:ORG})).status,403);
170
+ assert.equal(f.calls.emails.length,0);assert.equal(f.calls.targetLookups.length,0);
171
+});
172
+test('suspended organization and missing caller membership fail closed',async()=>{
173
+ for(const missing of [false,true]){
174
+ const f=await fixture({owner:true});
175
+ if(missing)f.tables.organization_members.shift();else f.tables.organizations[0].status='suspended';
176
+ assert.equal((await f.invoke()).status,403);assert.equal(f.calls.emails.length,0);
177
+ }
178
+});
179
+for(const table of ['profiles','organizations','organization_members','member_module_permissions','organization_member_roles','organization_roles','organization_role_permissions']){
180
+ test(`${table} read error fails closed without sending mail`,async()=>{
181
+ const f=await fixture();managerRole(f);f.failures.add(table);
182
+ const result=await f.invoke();assert.equal(result.status,503);assert.equal(f.calls.emails.length,0);
183
+ assert.doesNotMatch(JSON.stringify(result.body),/PRIVATE_DATABASE_ERROR/);
184
+ });
185
+}
186
+test('missing or unconfirmed email cannot be replaced by stale profile information',async()=>{
187
+ for(const variant of ['missing','unconfirmed','invalid']){
188
+ const f=await fixture({admin:true});
189
+ f.tables.profiles[1].email='stale@example.invalid';
190
+ if(variant==='missing')f.targetUser.email=null;
191
+ if(variant==='unconfirmed')f.targetUser.email_confirmed_at=null;
192
+ if(variant==='invalid')f.targetUser.email='not-an-email';
193
+ assert.equal((await f.invoke({action:'send_recovery',user_id:TARGET})).status,400);assert.equal(f.calls.emails.length,0);
194
+ }
195
+});
196
+test('Auth target lookup failure returns no sensitive details and sends no email',async()=>{
197
+ const f=await fixture({admin:true,targetError:{message:'PRIVATE_AUTH_LOOKUP_ERROR'}});
198
+ const result=await f.invoke({action:'send_recovery',user_id:TARGET});
199
+ assert.equal(result.status,400);assert.equal(f.calls.emails.length,0);
200
+ assert.doesNotMatch(JSON.stringify([result.body,f.calls.logs]),/PRIVATE_AUTH_LOOKUP_ERROR/);
201
+});
202
+for(const extra of [{email:'attacker@example.invalid'},{redirectTo:'https://attacker.example.invalid/'},{password:'NeverSet!Secret123'},{role:'admin'},{is_owner:true}]){
203
+ test(`untrusted recovery field ${Object.keys(extra)[0]} is rejected`,async()=>{
204
+ const f=await fixture({admin:true});
205
+ assert.equal((await f.invoke({action:'send_recovery',user_id:TARGET,...extra})).status,400);
206
+ assert.equal(f.calls.emails.length,0);noPasswordMutation(f);
207
+ });
208
+}
209
+test('malformed target and organization identifiers are rejected before Auth target lookup',async()=>{
210
+ for(const body of [{action:'send_recovery',user_id:'-'.repeat(36)},...[false,0,'','company-1',42].map(organization_id=>({action:'send_recovery',user_id:TARGET,organization_id}))]){
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);
217
+});
218
+test('rate limits remain distinguishable without leaking provider error text',async()=>{
219
+ for(const error of [{code:'over_email_send_rate_limit'},{code:'over_request_rate_limit'},{status:429}]){
220
+ const f=await fixture({admin:true,emailError:{...error,message:'PRIVATE_EMAIL_PROVIDER_ERROR'}});
221
+ const result=await f.invoke({action:'send_recovery',user_id:TARGET});
222
+ assert.equal(result.status,429);assert.equal(result.body.error,'recovery_rate_limited');
223
+ assert.doesNotMatch(JSON.stringify([result.body,f.calls.logs]),/PRIVATE_EMAIL_PROVIDER_ERROR|verified@example/);
224
+ }
225
+});
226
+test('email request rejection and network exception cannot claim success or expose a link',async()=>{
227
+ for(const options of [{emailError:{code:'unexpected_failure',message:'PRIVATE_EMAIL_PROVIDER_ERROR'}},{emailThrows:true}]){
228
+ const f=await fixture({admin:true,...options});const result=await f.invoke({action:'send_recovery',user_id:TARGET});
229
+ assert.equal(result.status,502);assert.equal(result.body.error,'recovery_failed');noPasswordMutation(f);
230
+ assert.doesNotMatch(JSON.stringify([result.body,f.calls.logs]),/PRIVATE_|verified@example/);
231
+ }
232
+});
233
+test('recovery response and audit contain only outcome and account identifiers',async()=>{
234
+ const f=await fixture({owner:true});const result=await f.invoke();assert.equal(result.status,200);
235
+ const encoded=JSON.stringify([result.body,f.calls.logs]);
236
+ assert.doesNotMatch(encoded,/verified@example|anon-fixture|service-fixture|fixture-token|action_link|access_token|password/i);
237
+ assert.ok(encoded.includes(ACTOR));assert.ok(encoded.includes(TARGET));assert.ok(encoded.includes(ORG));
238
+ noPasswordMutation(f);
239
+});
240
+test('global-admin account creation contract remains unchanged',async()=>{
241
+ const f=await fixture({admin:true});
242
+ const result=await f.invoke({action:'create',email:'NEW@example.invalid',full_name:'Sample User',username:'sample.user',temporary_password:'Create!Fixture123'});
243
+ assert.equal(result.status,201);assert.deepEqual(result.body,{ok:true,user_id:CREATED});
244
+ assert.deepEqual(f.calls.creates,[{email:'new@example.invalid',email_confirm:true,password:'Create!Fixture123',user_metadata:{full_name:'Sample User',username:'sample.user',temporary_credential:true}}]);
245
+ assert.equal(f.calls.emails.length,0);noPasswordMutation(f);
246
+});
247
+test('organization owner and delegated manager cannot provision a global account',async()=>{
248
+ for(const owner of [true,false]){
249
+ const f=await fixture({owner});if(!owner)managerRole(f);
250
+ assert.equal((await f.invoke({action:'create',email:'new@example.invalid',temporary_password:'Create!Fixture123'})).status,403);
251
+ assert.equal(f.calls.creates.length,0);
252
+ }
253
+});
254
+test('weak initial passwords remain rejected and creation errors stay bounded',async()=>{
255
+ const f=await fixture({admin:true});
256
+ assert.equal((await f.invoke({action:'create',email:'new@example.invalid',temporary_password:'weak'})).body.error,'weak_temporary_password');
257
+ const failed=await fixture({admin:true,createError:{code:'PRIVATE_EMAIL_SECRET',message:'PRIVATE_MESSAGE'}});
258
+ const result=await failed.invoke({action:'create',email:'new@example.invalid',temporary_password:'Create!Fixture123'});
259
+ assert.equal(result.status,400);assert.equal(result.body.error,'provision_failed');
260
+ assert.doesNotMatch(JSON.stringify([result.body,failed.calls.logs]),/PRIVATE_/);
261
+});
262
+test('CORS and HTTP method handling preserve existing restrictions',async()=>{
263
+ const f=await fixture({admin:true});
264
+ assert.equal((await f.invoke(undefined,{origin:'https://attacker.example.invalid'})).status,403);
265
+ const preflight=await f.invoke(undefined,{method:'OPTIONS',authorization:null});
266
+ assert.equal(preflight.status,204);assert.equal(preflight.headers.get('Access-Control-Allow-Origin'),'https://factoreasy.ir');
267
+ assert.equal((await f.invoke(undefined,{method:'GET'})).status,405);assert.equal(f.calls.clients.length,0);
268
+});
269
+test('missing or rejected bearer and missing server configuration never send mail',async()=>{
270
+ const f=await fixture({admin:true});assert.equal((await f.invoke(undefined,{authorization:null})).status,401);
271
+ const rejected=await fixture({authError:{message:'PRIVATE_AUTH_ERROR'}});assert.equal((await rejected.invoke()).status,401);
272
+ const unconfigured=await fixture({missingConfig:true});assert.equal((await unconfigured.invoke()).status,503);
273
+ for(const item of [f,rejected,unconfigured])assert.equal(item.calls.emails.length,0);
274
+});
275
+test('invalid, array and oversized JSON requests cannot trigger recovery',async()=>{
276
+ for(const requestOptions of [{rawBody:'{'},{rawBody:'[]'},{rawBody:'null'},{rawBody:'x'.repeat(8193)}]){
277
+ const f=await fixture({admin:true});const result=await f.invoke(undefined,requestOptions);
278
+ assert.ok([400,413].includes(result.status));assert.equal(f.calls.emails.length,0);
279
+ }
280
+});
scripts/login-connectivity-check.mjs
+3
-3
@@ -7,9 +7,9 @@ assert(html.includes('id="auth-connectivity-check"'),'Missing diagnostic action'
7
assert(html.includes('id="auth-connectivity-result"'),'Missing accessible result');
8
assert(html.includes('id="auth-connectivity-result" aria-live="polite"'),'Diagnostic must announce updates without adding a conflicting global role=status');
9
assert(html.includes('js/login-connectivity.js?v=20261024-independent-probes-v4'),'Missing versioned script');
10
-assert(html.includes('js/core.js?v=20261024-login-readiness-v1'),'Production login controls must use new cache version');
11
-assert(html.indexOf('<script src="js/login-connectivity.js?v=20261024-independent-probes-v4"')<html.indexOf('<script src="js/core.js?v=20261024-login-readiness-v1"'),'Connectivity handler script must execute before core (not just preload)');
12
-assert(html.includes('js/bootstrap.js?v=20261014-org-license-readiness-v1'),'Parallel bootstrap must also be cache-busted');
10
+assert(html.includes('js/core.js?v=20261025-password-recovery-v1'),'Production login controls must use new cache version');
11
+assert(html.indexOf('<script src="js/login-connectivity.js?v=20261024-independent-probes-v4"')<html.indexOf('<script src="js/core.js?v=20261025-password-recovery-v1"'),'Connectivity handler script must execute before core (not just preload)');
12
+assert(html.includes('js/bootstrap.js?v=20261025-password-recovery-v1'),'Parallel bootstrap must also be cache-busted');
13
assert(html.includes('id="auth-login-button"')&&html.includes('id="auth-login-status"'),'Login control requires real readiness/progress feedback');
14
assert(core.includes('window.FinoraAppAssetsReady'),'Authenticated workspace must remain gated until all module scripts settle');
15
assert(core.includes('window.FinoraOrganizationContextReady')&&core.includes('organizationAccount'),'Profile and license lookup must wait for the organization account adapter');
scripts/password-admin-ui.spec.js
new
+116
@@ -0,0 +1,116 @@
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 ACTOR='11111111-1111-4111-8111-111111111111';
4
+const TARGET='22222222-2222-4222-8222-222222222222';
5
+const OTHER='33333333-3333-4333-8333-333333333333';
6
+const ORG='44444444-4444-4444-8444-444444444444';
7
+const MEMBER='55555555-5555-4555-8555-555555555555';
8
+
9
+async function managerFixture(page,kind='global'){
10
+ await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
11
+ await page.goto(BASE,{waitUntil:'domcontentloaded'});
12
+ await page.waitForFunction(()=>window.FinoraStartupStatus?.authChecked===true&&window.FinoraStartupStatus?.extensionsReady===true);
13
+ await page.evaluate(({kind,ACTOR,TARGET,OTHER,ORG,MEMBER})=>{
14
+ document.getElementById('auth-screen').style.display='none';
15
+ window.__recoveryCalls=[];window.__recoveryAlerts=[];
16
+ window.confirm=()=>true;window.alert=message=>window.__recoveryAlerts.push(String(message));
17
+ currentUser={id:ACTOR,role:kind==='global'?'admin':'user',organizationId:ORG,isOrganizationOwner:kind==='owner',modulePermissions:[],commercialModules:['full_suite'],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};
18
+ const profiles=[{id:TARGET,email:'recipient@example.invalid',full_name:'آزمون بازیابی',role:'user',created_at:'2026-01-01'}];
19
+ const tables={profiles,licenses:[],organization_members:[{id:MEMBER,user_id:TARGET,status:'active',is_owner:false},{id:'66666666-6666-4666-8666-666666666666',user_id:OTHER,status:'suspended',is_owner:false}],organization_roles:[],organization_role_permissions:[],organization_member_roles:[]};
20
+ sb.from=table=>({select(){return this},eq(){return this},in(){return this},order(){return this},then(resolve,reject){return Promise.resolve({data:tables[table]||[],error:null}).then(resolve,reject)}});
21
+ Object.defineProperty(sb,'functions',{configurable:true,value:{invoke:async(name,{body})=>{window.__recoveryCalls.push({name,body});return {data:{ok:true},error:null}}}});
22
+ },{kind,ACTOR,TARGET,OTHER,ORG,MEMBER});
23
+}
24
+
25
+test('central user/license row sends only target Auth identity to the recovery endpoint',async({page})=>{
26
+ await managerFixture(page);
27
+ await page.evaluate(async()=>{navigateShell('settings','view-admin');await renderAdminPanel()});
28
+ const button=page.locator('[data-recovery-user="'+TARGET+'"]');
29
+ await expect(button).toHaveCount(1,{timeout:1500});
30
+ await expect(button).toContainText('پیوند بازیابی');
31
+ await button.click();
32
+ await expect.poll(()=>page.evaluate(()=>window.__recoveryCalls)).toEqual([{name:'admin-user-management',body:{action:'send_recovery',user_id:TARGET}}]);
33
+ expect(await page.evaluate(()=>window.__recoveryAlerts.join(' '))).toContain('پیوند');
34
+});
35
+
36
+test('organization owner targets the active Auth user, never the membership UUID or inactive member',async({page})=>{
37
+ await managerFixture(page,'owner');
38
+ await page.evaluate(()=>showOrganizationAccessManager());
39
+ const modal=page.locator('#finora-org-access-modal.active');
40
+ await expect(modal.locator('[data-recovery-user="'+TARGET+'"]')).toHaveCount(1,{timeout:1500});
41
+ await expect(modal.locator('[data-recovery-user="'+OTHER+'"]')).toHaveCount(0);
42
+ await modal.locator('[data-recovery-user="'+TARGET+'"]').click();
43
+ await expect.poll(()=>page.evaluate(()=>window.__recoveryCalls)).toEqual([{name:'admin-user-management',body:{action:'send_recovery',user_id:TARGET,organization_id:ORG}}]);
44
+ expect((await page.evaluate(()=>window.__recoveryCalls))[0].body.user_id).not.toBe(MEMBER);
45
+});
46
+
47
+test('ordinary member and foreign organization calls cannot invoke manager recovery',async({page})=>{
48
+ await managerFixture(page,'member');
49
+ expect(await page.evaluate(()=>typeof window.finoraSendUserRecovery)).toBe('function');
50
+ await page.evaluate(async({TARGET,ORG})=>{await finoraSendUserRecovery(TARGET,ORG);currentUser.isOrganizationOwner=true;await finoraSendUserRecovery(TARGET,'77777777-7777-4777-8777-777777777777')},{TARGET,ORG});
51
+ expect(await page.evaluate(()=>window.__recoveryCalls)).toHaveLength(0);
52
+});
53
+
54
+test('pending repeated sends and the successful-send cooldown invoke the server once',async({page})=>{
55
+ await managerFixture(page);
56
+ expect(await page.evaluate(()=>typeof window.finoraSendUserRecovery)).toBe('function');
57
+ await page.evaluate(({TARGET})=>{
58
+ sb.functions.invoke=(name,{body})=>{window.__recoveryCalls.push({name,body});return new Promise(resolve=>{window.__resolveRecovery=()=>resolve({data:{ok:true},error:null})})};
59
+ window.__firstRecovery=finoraSendUserRecovery(TARGET);void finoraSendUserRecovery(TARGET);
60
+ },{TARGET});
61
+ expect(await page.evaluate(()=>window.__recoveryCalls)).toHaveLength(1);
62
+ await page.evaluate(async({TARGET})=>{window.__resolveRecovery();await window.__firstRecovery;await finoraSendUserRecovery(TARGET)},{TARGET});
63
+ expect(await page.evaluate(()=>window.__recoveryCalls)).toHaveLength(1);
64
+});
65
+
66
+test('server rejection shows a localized reason and never a false success or raw response',async({page})=>{
67
+ await managerFixture(page);
68
+ expect(await page.evaluate(()=>typeof window.finoraSendUserRecovery)).toBe('function');
69
+ await page.evaluate(async({TARGET})=>{
70
+ sb.functions.invoke=async()=>({data:null,error:{message:'raw-secret-token-error',context:new Response(JSON.stringify({error:'recovery_target_unavailable',extra:'raw-secret-token'}),{status:400,headers:{'content-type':'application/json'}})}});
71
+ await finoraSendUserRecovery(TARGET);
72
+ },{TARGET});
73
+ const alerts=await page.evaluate(()=>window.__recoveryAlerts.join(' '));
74
+ expect(alerts).toContain('ایمیل');
75
+ expect(alerts).not.toContain('raw-secret');
76
+ expect(alerts).not.toContain('ارسال شد');
77
+});
78
+
79
+test('a stalled manager request ends with an uncertain-result message and no immediate duplicate',async({page})=>{
80
+ await managerFixture(page);
81
+ expect(await page.evaluate(()=>typeof window.finoraSendUserRecovery)).toBe('function');
82
+ await page.clock.install();
83
+ await page.evaluate(({TARGET})=>{
84
+ sb.functions.invoke=(name,{body})=>{window.__recoveryCalls.push({name,body});return new Promise(()=>{})};
85
+ window.__firstRecovery=finoraSendUserRecovery(TARGET);
86
+ },{TARGET});
87
+ await page.clock.fastForward(21000);
88
+ await expect.poll(()=>page.evaluate(()=>window.__recoveryAlerts.join(' '))).toContain('مشخص نیست');
89
+ await page.evaluate(async({TARGET})=>{await window.__firstRecovery;await finoraSendUserRecovery(TARGET)},{TARGET});
90
+ expect(await page.evaluate(()=>window.__recoveryCalls)).toHaveLength(1);
91
+ expect(await page.evaluate(()=>window.__recoveryAlerts.join(' '))).not.toContain('ارسال شد');
92
+});
93
+
94
+test('a thrown transport error never leaks raw server details',async({page})=>{
95
+ await managerFixture(page);
96
+ await page.evaluate(async({TARGET})=>{
97
+ sb.functions.invoke=async()=>{throw new Error('raw-secret-token-backend')};
98
+ await finoraSendUserRecovery(TARGET);
99
+ },{TARGET});
100
+ const alerts=await page.evaluate(()=>window.__recoveryAlerts.join(' '));
101
+ expect(alerts).not.toContain('raw-secret');
102
+ expect(alerts).toContain('ایمیل');
103
+});
104
+
105
+test('a delegated core manager can assist an active member independently of paid license state',async({page})=>{
106
+ await managerFixture(page,'member');
107
+ await page.evaluate(async()=>{
108
+ currentUser.modulePermissions=[{module_key:'core',capabilities:['configure']}];
109
+ currentUser.subscription={type:'trial',status:'cancelled',endDate:'2020-01-01'};
110
+ await showOrganizationAccessManager();
111
+ });
112
+ const button=page.locator('#finora-org-access-modal.active [data-recovery-user="'+TARGET+'"]');
113
+ await expect(button).toBeVisible();
114
+ await button.click();
115
+ await expect.poll(()=>page.evaluate(()=>window.__recoveryCalls)).toEqual([{name:'admin-user-management',body:{action:'send_recovery',user_id:TARGET,organization_id:ORG}}]);
116
+});
scripts/password-recovery.spec.js
new
+282
@@ -0,0 +1,282 @@
1
+const {test,expect}=require('@playwright/test');
2
+const BASE=process.env.FINORA_PASSWORD_BASE||process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html';
3
+const PAGES=process.env.FINORA_LOGIN_PAGES_BASE||'http://127.0.0.1:4173/_site/index.html';
4
+const BOB='11111111-1111-4111-8111-111111111111',ALICE='22222222-2222-4222-8222-222222222222';
5
+function token(id){const enc=v=>Buffer.from(JSON.stringify(v)).toString('base64url');return enc({alg:'HS256',typ:'JWT'})+'.'+enc({sub:id,exp:4102444800,session_id:'session-'+id,aud:'authenticated'})+'.synthetic-signature';}
6
+function user(id){return {id,email:id===BOB?'recovery@example.test':'existing@example.test',aud:'authenticated',role:'authenticated',created_at:'2026-01-01T00:00:00Z',user_metadata:{has_password:true,full_name:'Synthetic Recovery'}};}
7
+function session(id){return {access_token:token(id),refresh_token:'synthetic-refresh-'+id,token_type:'bearer',expires_in:3600,expires_at:4102444800,user:user(id)};}
8
+function callback(base,access=token(BOB)){return base+'?finora_recovery=1#type=recovery&access_token='+encodeURIComponent(access)+'&refresh_token=synthetic-recovery-refresh&expires_in=3600&token_type=bearer';}
9
+async function fixture(page,{existing=false,invalid=false,updateError=false}={}){
10
+ const calls={recover:[],recoveryRedirects:[],updates:[],logouts:[],profiles:0,records:0,writes:0};
11
+ await page.addInitScript(({existing,saved})=>{if(existing)localStorage.setItem('sb-hcsixhqbyuhpshfwqpjx-auth-token',JSON.stringify(saved));},{existing,saved:session(ALICE)});
12
+ await page.route('https://*.supabase.co/**',async route=>{
13
+ const request=route.request(),url=new URL(request.url()),path=url.pathname,method=request.method();
14
+ const json=(status,data)=>route.fulfill({status,headers:{'x-supabase-api-version':'2024-01-01','access-control-expose-headers':'x-supabase-api-version'},contentType:'application/json',body:JSON.stringify(data)});
15
+ if(path==='/auth/v1/recover'){
16
+ calls.recover.push(request.postDataJSON());calls.recoveryRedirects.push(url.searchParams.get('redirect_to'));return json(200,{});
17
+ }
18
+ if(path==='/auth/v1/user'){
19
+ const uid=request.headers().authorization?.includes(token(ALICE))?ALICE:BOB;
20
+ if(method==='GET')return invalid&&uid===BOB?json(401,{code:'bad_jwt',msg:'unsafe-private-error-value'}):json(200,user(uid));
21
+ if(method==='PUT'){
22
+ calls.updates.push({uid,...request.postDataJSON()});
23
+ if(updateError)return json(422,{code:'weak_password',msg:'unsafe-private-error-value'});
24
+ return json(200,user(uid));
25
+ }
26
+ }
27
+ if(path==='/auth/v1/logout'){calls.logouts.push(request.headers().authorization);return route.fulfill({status:204,body:''});}
28
+ if(path.startsWith('/rest/v1/')){
29
+ const table=path.split('/').pop();
30
+ if(method!=='GET'){calls.writes++;return json(403,{message:'Unexpected synthetic write'});}
31
+ const uid=request.headers().authorization?.includes(token(ALICE))?ALICE:BOB;
32
+ let data=[];
33
+ if(table==='profiles'){calls.profiles++;data=[{id:uid,email:user(uid).email,full_name:'Synthetic Recovery',role:'accountant'}];}
34
+ if(table==='organization_members')data=[{id:'synthetic-member',organization_id:'synthetic-org',user_id:uid,status:'active',is_owner:true}];
35
+ if(table==='organizations')data=[{id:'synthetic-org',name:'Synthetic Company',status:'active'}];
36
+ if(table==='licenses')data=[{organization_id:'synthetic-org',plan:'lifetime',status:'active',starts_at:'2026-01-01',ends_at:'2099-01-01',modules:['full_suite'],max_companies:5,max_users:5}];
37
+ if(table==='records')calls.records++;
38
+ return json(200,request.headers().accept?.includes('vnd.pgrst.object')?data[0]:data);
39
+ }
40
+ return route.abort('blockedbyclient');
41
+ });
42
+ await page.route('https://cdn.jsdelivr.net/**',route=>route.abort('blockedbyclient'));
43
+ await page.route('https://cdnjs.cloudflare.com/**',route=>route.abort('blockedbyclient'));
44
+ page.on('dialog',dialog=>dialog.dismiss());
45
+ return calls;
46
+}
47
+
48
+test('Forgot Password validates email and sends one account-neutral implicit recovery request',async({page})=>{
49
+ const calls=await fixture(page);
50
+ await page.goto(BASE,{waitUntil:'domcontentloaded'});
51
+ await expect(page.locator('#auth-forgot-password')).toBeEnabled();
52
+ await page.locator('#auth-email').fill('invalid');await page.locator('#auth-forgot-password').click();
53
+ await expect(page.locator('#auth-login-status')).toContainText('ایمیل معتبر');expect(calls.recover).toHaveLength(0);
54
+ await page.locator('#auth-email').fill('Unknown@Example.test');
55
+ await page.locator('#auth-forgot-password').click();await page.locator('#auth-forgot-password').click();
56
+ await expect(page.locator('#auth-login-status')).toContainText('اگر حسابی');
57
+ expect(calls.recover).toEqual([{email:'unknown@example.test',code_challenge:null,code_challenge_method:null,gotrue_meta_security:{}}]);
58
+ expect(calls.recoveryRedirects).toEqual(['https://factoreasy.ir/?finora_recovery=1']);
59
+ expect(calls.profiles).toBe(0);expect(calls.writes).toBe(0);
60
+});
61
+
62
+test('A stalled recovery request times out and restores usable login controls',async({page})=>{
63
+ const calls=await fixture(page);
64
+ let release,arrived;const held=new Promise(r=>{release=r}),requested=new Promise(r=>{arrived=r});
65
+ await page.route('https://*.supabase.co/auth/v1/recover*',async route=>{
66
+ arrived();await held;await route.fulfill({status:200,contentType:'application/json',body:'{}'}).catch(()=>{});
67
+ });
68
+ await page.goto(BASE,{waitUntil:'domcontentloaded'});
69
+ await expect(page.locator('#auth-forgot-password')).toBeEnabled();
70
+ await page.clock.install();await page.locator('#auth-email').fill('recovery@example.test');
71
+ await page.locator('#auth-forgot-password').click();await requested;
72
+ await expect(page.locator('#auth-forgot-password')).toBeDisabled();
73
+ await page.clock.fastForward(12100);
74
+ await expect(page.locator('#auth-login-status')).toContainText('انجام نشد');
75
+ await expect(page.locator('#auth-forgot-password')).toBeEnabled();
76
+ await expect(page.locator('#auth-login-button')).toBeEnabled();
77
+ expect(calls.profiles).toBe(0);expect(calls.updates).toHaveLength(0);release();
78
+});
79
+
80
+test('Implicit recovery link opens required password panel without hydrating financial workspace',async({page})=>{
81
+ const calls=await fixture(page);
82
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
83
+ await expect(page.locator('#auth-recovery-container')).toBeVisible();
84
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
85
+ await expect(page.locator('#auth-form-container')).toBeHidden();
86
+ expect(new URL(page.url()).hash).toBe('');
87
+ expect(calls.profiles).toBe(0);expect(calls.records).toBe(0);
88
+ await page.evaluate(()=>enterApp({id:'should-not-hydrate'}));
89
+ expect(calls.profiles).toBe(0);expect(calls.records).toBe(0);
90
+ await expect(page.locator('#auth-screen')).toBeVisible();
91
+});
92
+
93
+test('Invalid recovery link never uses a different cached account to change a password',async({page})=>{
94
+ const calls=await fixture(page,{existing:true,invalid:true});
95
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
96
+ await expect(page.locator('#auth-recovery-status')).toContainText('معتبر نیست');
97
+ await expect(page.locator('#auth-recovery-submit')).toBeDisabled();
98
+ await page.evaluate(()=>finoraSaveRecoveredPassword());
99
+ expect(calls.updates).toHaveLength(0);expect(calls.profiles).toBe(0);expect(calls.records).toBe(0);
100
+ expect(await page.locator('body').innerText()).not.toContain('unsafe-private-error-value');
101
+});
102
+
103
+test('Recovery marker alone cannot turn a cached session into a password reset',async({page})=>{
104
+ const calls=await fixture(page,{existing:true});
105
+ await page.goto(BASE+'?finora_recovery=1',{waitUntil:'domcontentloaded'});
106
+ await expect(page.locator('#auth-recovery-status')).toContainText('معتبر نیست');
107
+ await expect(page.locator('#auth-recovery-submit')).toBeDisabled();
108
+ expect(calls.profiles).toBe(0);expect(calls.updates).toHaveLength(0);
109
+});
110
+
111
+test('Verified recovery survives reload only for the same validated account',async({page})=>{
112
+ const calls=await fixture(page);
113
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
114
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
115
+ await page.reload();
116
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
117
+ expect(calls.profiles).toBe(0);expect(calls.records).toBe(0);
118
+ await page.evaluate(saved=>localStorage.setItem('sb-hcsixhqbyuhpshfwqpjx-auth-token',JSON.stringify(saved)),session(ALICE));
119
+ await page.reload();
120
+ await expect(page.locator('#auth-recovery-submit')).toBeDisabled();
121
+ await expect(page.locator('#auth-recovery-status')).toContainText('معتبر نیست');
122
+ expect(calls.profiles).toBe(0);
123
+});
124
+
125
+test('An unsupported fresh callback discards an earlier valid recovery proof',async({page})=>{
126
+ const calls=await fixture(page);
127
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
128
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
129
+ await page.goto(callback(BASE).replace('type=recovery','type=signup'),{waitUntil:'domcontentloaded'});
130
+ await expect(page.locator('#auth-recovery-status')).toContainText('معتبر نیست');
131
+ await expect(page.locator('#auth-recovery-submit')).toBeDisabled();
132
+ expect(new URL(page.url()).hash).toBe('');
133
+ expect(calls.updates).toHaveLength(0);expect(calls.profiles).toBe(0);
134
+});
135
+
136
+test('Recovery validates password, suppresses double submit and enters the verified account once',async({page})=>{
137
+ const calls=await fixture(page);
138
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
139
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
140
+ await page.locator('#auth-recovery-password').fill('weak');await page.locator('#auth-recovery-confirm').fill('weak');
141
+ await page.locator('#auth-recovery-submit').click();
142
+ await expect(page.locator('#auth-recovery-status')).toContainText('۸ کاراکتر');expect(calls.updates).toHaveLength(0);
143
+ await page.locator('#auth-recovery-password').fill('NewPassword123');await page.locator('#auth-recovery-confirm').fill('Different123');
144
+ await page.locator('#auth-recovery-submit').click();
145
+ await expect(page.locator('#auth-recovery-status')).toContainText('یکسان');expect(calls.updates).toHaveLength(0);
146
+ await page.locator('#auth-recovery-confirm').fill('NewPassword123');
147
+ await page.evaluate(()=>{finoraSaveRecoveredPassword();finoraSaveRecoveredPassword();});
148
+ await expect(page.locator('#auth-screen')).toBeHidden({timeout:15000});
149
+ expect(calls.updates).toEqual([{uid:BOB,password:'NewPassword123',data:{has_password:true},code_challenge:null,code_challenge_method:null}]);
150
+ expect(await page.evaluate(()=>currentUser.id)).toBe(BOB);
151
+ expect(new URL(page.url()).searchParams.has('finora_recovery')).toBe(false);
152
+ await expect(page.locator('#auth-recovery-password')).toHaveValue('');
153
+ await expect(page.locator('#auth-recovery-confirm')).toHaveValue('');
154
+ expect(calls.writes).toBe(0);
155
+});
156
+
157
+test('Rejected password update stays in recovery without exposing raw provider error',async({page})=>{
158
+ const calls=await fixture(page,{updateError:true});
159
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
160
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
161
+ await page.locator('#auth-recovery-password').fill('NewPassword123');await page.locator('#auth-recovery-confirm').fill('NewPassword123');
162
+ await page.locator('#auth-recovery-submit').click();
163
+ await expect(page.locator('#auth-recovery-status')).toContainText('شرایط امنیتی');
164
+ await expect(page.locator('#auth-screen')).toBeVisible();
165
+ expect(calls.updates).toHaveLength(1);expect(calls.profiles).toBe(0);
166
+ expect(await page.locator('body').innerText()).not.toContain('unsafe-private-error-value');
167
+});
168
+
169
+test('Another tab changing the account while recovery is checked cannot update that account',async({page})=>{
170
+ const calls=await fixture(page);
171
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
172
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
173
+ await page.locator('#auth-recovery-password').fill('NewPassword123');await page.locator('#auth-recovery-confirm').fill('NewPassword123');
174
+ await page.evaluate(saved=>{
175
+ const getUser=sb.auth.getUser.bind(sb.auth);
176
+ sb.auth.getUser=async(...args)=>{const result=await getUser(...args);localStorage.setItem('sb-hcsixhqbyuhpshfwqpjx-auth-token',JSON.stringify(saved));return result;};
177
+ },session(ALICE));
178
+ await page.locator('#auth-recovery-submit').click();
179
+ await expect(page.locator('#auth-recovery-status')).toContainText('معتبر نیست');
180
+ await expect(page.locator('#auth-recovery-submit')).toBeDisabled();
181
+ expect(calls.updates).toHaveLength(0);expect(calls.profiles).toBe(0);
182
+});
183
+
184
+test('A session change after the final check cannot redirect the password mutation',async({page})=>{
185
+ const calls=await fixture(page);
186
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
187
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
188
+ await page.locator('#auth-recovery-password').fill('NewPassword123');await page.locator('#auth-recovery-confirm').fill('NewPassword123');
189
+ await page.evaluate(saved=>{
190
+ const getSession=sb.auth.getSession.bind(sb.auth);
191
+ sb.auth.getSession=async()=>{const result=await getSession();localStorage.setItem('sb-hcsixhqbyuhpshfwqpjx-auth-token',JSON.stringify(saved));return result;};
192
+ },session(ALICE));
193
+ await page.locator('#auth-recovery-submit').click();
194
+ await expect(page.locator('#auth-form-container')).toBeVisible();
195
+ await expect(page.locator('#auth-login-status')).toContainText('رمز جدید ذخیره شد');
196
+ expect(calls.updates).toEqual([{uid:BOB,password:'NewPassword123',data:{has_password:true},code_challenge:null,code_challenge_method:null}]);
197
+ expect(calls.profiles).toBe(0);expect(calls.records).toBe(0);
198
+ expect(await page.evaluate(()=>JSON.parse(localStorage.getItem('sb-hcsixhqbyuhpshfwqpjx-auth-token')).user.id)).toBe(ALICE);
199
+});
200
+
201
+test('Recovery proof cannot authorize a later session for the same account',async({page})=>{
202
+ const calls=await fixture(page);
203
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
204
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
205
+ const later=session(BOB),parts=later.access_token.split('.');
206
+ const payload=JSON.parse(Buffer.from(parts[1],'base64url').toString());payload.session_id='later-unrelated-session';
207
+ parts[1]=Buffer.from(JSON.stringify(payload)).toString('base64url');later.access_token=parts.join('.');
208
+ await page.evaluate(saved=>localStorage.setItem('sb-hcsixhqbyuhpshfwqpjx-auth-token',JSON.stringify(saved)),later);
209
+ await page.locator('#auth-recovery-password').fill('NewPassword123');await page.locator('#auth-recovery-confirm').fill('NewPassword123');
210
+ await page.locator('#auth-recovery-submit').click();
211
+ await expect(page.locator('#auth-recovery-status')).toContainText('معتبر نیست');
212
+ await expect(page.locator('#auth-recovery-submit')).toBeDisabled();
213
+ expect(calls.updates).toHaveLength(0);expect(calls.profiles).toBe(0);
214
+});
215
+
216
+test('Cancel recovery preserves another account that signed in in a different tab',async({page})=>{
217
+ const calls=await fixture(page);
218
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
219
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
220
+ await page.evaluate(saved=>localStorage.setItem('sb-hcsixhqbyuhpshfwqpjx-auth-token',JSON.stringify(saved)),session(ALICE));
221
+ await page.locator('#auth-recovery-cancel').click();
222
+ await expect(page.locator('#auth-form-container')).toBeVisible();
223
+ expect(calls.logouts).toHaveLength(0);
224
+ expect(await page.evaluate(()=>JSON.parse(localStorage.getItem('sb-hcsixhqbyuhpshfwqpjx-auth-token')).user.id)).toBe(ALICE);
225
+ expect(calls.updates).toHaveLength(0);expect(calls.profiles).toBe(0);
226
+});
227
+
228
+test('Cancel logout remains pinned to recovery when the persistent account changes after its check',async({page})=>{
229
+ const calls=await fixture(page);
230
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
231
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
232
+ await page.evaluate(saved=>{
233
+ const getSession=sb.auth.getSession.bind(sb.auth);
234
+ sb.auth.getSession=async()=>{const result=await getSession();localStorage.setItem('sb-hcsixhqbyuhpshfwqpjx-auth-token',JSON.stringify(saved));return result;};
235
+ },session(ALICE));
236
+ await page.locator('#auth-recovery-cancel').click();
237
+ await expect(page.locator('#auth-form-container')).toBeVisible();
238
+ expect(calls.logouts).toEqual(['Bearer '+token(BOB)]);
239
+ expect(await page.evaluate(()=>JSON.parse(localStorage.getItem('sb-hcsixhqbyuhpshfwqpjx-auth-token')).user.id)).toBe(ALICE);
240
+ expect(calls.updates).toHaveLength(0);expect(calls.profiles).toBe(0);
241
+});
242
+
243
+test('Cancel stays disabled until a pending recovery exchange has finished',async({page})=>{
244
+ const calls=await fixture(page);
245
+ let release,arrived;const held=new Promise(r=>{release=r}),requested=new Promise(r=>{arrived=r});
246
+ await page.route('https://*.supabase.co/auth/v1/user',async route=>{
247
+ if(route.request().method()!=='GET')return route.fallback();
248
+ arrived();await held;return route.fallback();
249
+ });
250
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});await requested;
251
+ await expect(page.locator('#auth-recovery-cancel')).toBeDisabled();
252
+ await page.evaluate(()=>finoraCancelPasswordRecovery());
253
+ await expect(page.locator('#auth-recovery-container')).toBeVisible();
254
+ release();await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
255
+ await expect(page.locator('#auth-recovery-cancel')).toBeEnabled();
256
+ expect(calls.profiles).toBe(0);expect(calls.updates).toHaveLength(0);
257
+});
258
+
259
+test('Cancel a verified recovery clears only its local session and prevents automatic re-entry',async({page})=>{
260
+ const calls=await fixture(page);
261
+ await page.goto(callback(BASE),{waitUntil:'domcontentloaded'});
262
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
263
+ await page.locator('#auth-recovery-cancel').click();
264
+ await expect(page.locator('#auth-form-container')).toBeVisible();
265
+ expect(calls.logouts).toEqual(['Bearer '+token(BOB)]);
266
+ expect(await page.evaluate(()=>localStorage.getItem('sb-hcsixhqbyuhpshfwqpjx-auth-token'))).toBeNull();
267
+ expect(new URL(page.url()).searchParams.has('finora_recovery')).toBe(false);
268
+ await page.reload();await expect(page.locator('#auth-login-button')).toBeEnabled();
269
+ await expect(page.locator('#auth-screen')).toBeVisible();
270
+ expect(calls.profiles).toBe(0);expect(calls.updates).toHaveLength(0);
271
+});
272
+
273
+test('Strict CSP recovery form is ready while a required business bundle is held',async({page})=>{
274
+ const calls=await fixture(page);
275
+ let release,arrived;const held=new Promise(r=>{release=r}),requested=new Promise(r=>{arrived=r});
276
+ await page.route('**/js/finora-pages-business.js*',async route=>{arrived();await held;await route.continue();});
277
+ await page.goto(callback(PAGES),{waitUntil:'commit'});await requested;
278
+ await expect(page.locator('#auth-recovery-submit')).toBeEnabled();
279
+ await expect(page.locator('#auth-recovery-container')).toBeVisible();
280
+ expect(calls.profiles).toBe(0);expect(calls.records).toBe(0);
281
+ release();await page.waitForLoadState('domcontentloaded');
282
+});
supabase/functions/admin-user-management/handler.mjs
new
+150
@@ -0,0 +1,150 @@
1
+const allowedOrigins = new Set(["https://factoreasy.ir", "https://www.factoreasy.ir"]);
2
+const allowedHeaders = "authorization,apikey,content-type,x-client-info";
3
+const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4
+const recoveryRedirect = "https://factoreasy.ir/?finora_recovery=1";
5
+const recoveryFields = new Set(["action", "user_id", "organization_id"]);
6
+const provisionErrors = new Set(["email_exists", "user_already_exists", "phone_exists", "unexpected_failure", "validation_failed", "weak_password"]);
7
+
8
+function cors(origin) {
9
+ return {
10
+ "Access-Control-Allow-Origin": origin && allowedOrigins.has(origin) ? origin : "https://factoreasy.ir",
11
+ "Access-Control-Allow-Headers": allowedHeaders,
12
+ "Access-Control-Allow-Methods": "POST,OPTIONS",
13
+ "Vary": "Origin",
14
+ "Content-Type": "application/json; charset=utf-8",
15
+ "Cache-Control": "no-store",
16
+ };
17
+}
18
+function reply(status, body, origin) {
19
+ return new Response(JSON.stringify(body), {status, headers: cors(origin)});
20
+}
21
+function validEmail(raw) {
22
+ return typeof raw === "string" && raw.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(raw);
23
+}
24
+function strongPassword(value) {
25
+ return value.length >= 12 && value.length <= 128 && /[A-Z]/.test(value) && /[a-z]/.test(value) && /\d/.test(value) && /[^A-Za-z\d]/.test(value);
26
+}
27
+class AuthorizationReadError extends Error {}
28
+async function readOne(query) {
29
+ try {
30
+ const {data, error} = await query.maybeSingle();
31
+ if (error) throw new AuthorizationReadError();
32
+ return data;
33
+ } catch {
34
+ throw new AuthorizationReadError();
35
+ }
36
+}
37
+async function readRows(query) {
38
+ try {
39
+ const {data, error} = await query;
40
+ if (error || (data !== null && !Array.isArray(data))) throw new AuthorizationReadError();
41
+ return data || [];
42
+ } catch {
43
+ throw new AuthorizationReadError();
44
+ }
45
+}
46
+function permitsManagement(permission) {
47
+ return ["core", "full_suite"].includes(permission.module_key) && Array.isArray(permission.capabilities) && permission.capabilities.includes("configure");
48
+}
49
+async function canRequestOrganizationRecovery(server, actorId, targetId, organizationId) {
50
+ const organization = await readOne(server.from("organizations").select("id,status").eq("id", organizationId).eq("status", "active"));
51
+ if (!organization) return false;
52
+ const [actor, target] = await Promise.all([
53
+ readOne(server.from("organization_members").select("id,is_owner").eq("organization_id", organizationId).eq("user_id", actorId).eq("status", "active")),
54
+ readOne(server.from("organization_members").select("id").eq("organization_id", organizationId).eq("user_id", targetId).eq("status", "active")),
55
+ ]);
56
+ if (!actor || !target) return false;
57
+ if (actor.is_owner === true) return true;
58
+ const direct = await readRows(server.from("member_module_permissions").select("module_key,capabilities").eq("organization_id", organizationId).eq("member_id", actor.id));
59
+ if (direct.some(permitsManagement)) return true;
60
+ const assignments = await readRows(server.from("organization_member_roles").select("role_id").eq("organization_id", organizationId).eq("member_id", actor.id).eq("active", true));
61
+ const assignedIds = assignments.map(row => row.role_id).filter(id => typeof id === "string" && uuid.test(id));
62
+ if (!assignedIds.length) return false;
63
+ const roles = await readRows(server.from("organization_roles").select("id").eq("organization_id", organizationId).in("id", assignedIds).eq("active", true));
64
+ if (!roles.length) return false;
65
+ const permissions = await readRows(server.from("organization_role_permissions").select("module_key,capabilities").eq("organization_id", organizationId).in("role_id", roles.map(row => row.id)));
66
+ return permissions.some(permitsManagement);
67
+}
68
+
69
+export function createAdminUserManagementHandler({createClient, getEnv, logger = console}) {
70
+ return async function handleAdminUserManagement(request) {
71
+ const origin = request.headers.get("Origin");
72
+ if (origin && !allowedOrigins.has(origin)) return reply(403, {error: "origin_not_allowed"}, origin);
73
+ if (request.method === "OPTIONS") return new Response(null, {status: 204, headers: cors(origin)});
74
+ if (request.method !== "POST") return reply(405, {error: "method_not_allowed"}, origin);
75
+ const bearer = request.headers.get("Authorization") || "";
76
+ if (!/^Bearer\s+[^\s]+$/i.test(bearer)) return reply(401, {error: "unauthorized"}, origin);
77
+ const projectUrl = getEnv("SUPABASE_URL");
78
+ const anon = getEnv("SUPABASE_ANON_KEY");
79
+ const service = getEnv("SUPABASE_SERVICE_ROLE_KEY");
80
+ if (!projectUrl || !anon || !service) return reply(503, {error: "server_configuration_missing"}, origin);
81
+ try {
82
+ const authOptions = {auth: {persistSession: false, autoRefreshToken: false, detectSessionInUrl: false, flowType: "implicit"}};
83
+ const caller = createClient(projectUrl, anon, authOptions);
84
+ const token = bearer.replace(/^Bearer\s+/i, "");
85
+ const {data: {user}, error: userError} = await caller.auth.getUser(token);
86
+ if (userError || !user || !uuid.test(user.id)) return reply(401, {error: "unauthorized"}, origin);
87
+ const server = createClient(projectUrl, service, authOptions);
88
+ const profile = await readOne(server.from("profiles").select("id,role").eq("id", user.id));
89
+ if (!profile || profile.id !== user.id) throw new AuthorizationReadError();
90
+ const raw = await request.text();
91
+ if (raw.length > 8192) return reply(413, {error: "payload_too_large"}, origin);
92
+ let body;
93
+ try { body = JSON.parse(raw); } catch { return reply(400, {error: "invalid_json"}, origin); }
94
+ if (!body || typeof body !== "object" || Array.isArray(body)) return reply(400, {error: "invalid_json"}, origin);
95
+ if (body.action === "send_recovery") {
96
+ const target = body.user_id;
97
+ const organizationId = body.organization_id ?? null;
98
+ if (Object.keys(body).some(key => !recoveryFields.has(key)) || typeof target !== "string" || !uuid.test(target) || (organizationId !== null && (typeof organizationId !== "string" || !uuid.test(organizationId)))) {
99
+ return reply(400, {error: "invalid_recovery_request"}, origin);
100
+ }
101
+ // Membership management never grants control of a user's global Auth password.
102
+ if (profile.role !== "admin" && (!organizationId || !await canRequestOrganizationRecovery(server, user.id, target, organizationId))) {
103
+ return reply(403, {error: "organization_access_denied"}, origin);
104
+ }
105
+ const {data, error: targetError} = await server.auth.admin.getUserById(target);
106
+ const targetUser = data?.user;
107
+ if (targetError || targetUser?.id !== target || !validEmail(targetUser.email) || typeof targetUser.email_confirmed_at !== "string" || !Number.isFinite(Date.parse(targetUser.email_confirmed_at))) {
108
+ return reply(400, {error: "recovery_target_unavailable"}, origin);
109
+ }
110
+ let recoveryError;
111
+ try {
112
+ ({error: recoveryError} = await caller.auth.resetPasswordForEmail(targetUser.email, {redirectTo: recoveryRedirect}));
113
+ } catch {
114
+ recoveryError = {code: "request_failed"};
115
+ }
116
+ const audit = {actor: user.id, user_id: target, organization_id: organizationId, outcome: "requested"};
117
+ if (recoveryError) {
118
+ const limited = recoveryError.status === 429 || ["over_email_send_rate_limit", "over_request_rate_limit"].includes(recoveryError.code);
119
+ logger.info("finora_admin_recovery_failed", {...audit, outcome: limited ? "rate_limited" : "failed"});
120
+ return reply(limited ? 429 : 502, {error: limited ? "recovery_rate_limited" : "recovery_failed"}, origin);
121
+ }
122
+ logger.info("finora_admin_recovery_requested", audit);
123
+ return reply(200, {ok: true}, origin);
124
+ }
125
+ if (body.action !== "create") return reply(400, {error: "unsupported_action"}, origin);
126
+ if (profile?.role !== "admin") return reply(403, {error: "admin_required"}, origin);
127
+ const email = String(body.email || "").trim().toLowerCase();
128
+ const phone = String(body.phone || "").trim();
129
+ const fullName = String(body.full_name || "").trim();
130
+ const username = String(body.username || "").trim().toLowerCase();
131
+ const password = String(body.temporary_password || "");
132
+ if ((!email && !phone) || (email && !validEmail(email)) || (phone && !/^\+[1-9][0-9]{7,14}$/.test(phone))) return reply(400, {error: "invalid_email_or_phone"}, origin);
133
+ if (fullName.length > 120 || username && !/^[a-z0-9_.-]{3,40}$/.test(username)) return reply(400, {error: "invalid_profile"}, origin);
134
+ if (!strongPassword(password)) return reply(400, {error: "weak_temporary_password"}, origin);
135
+ const credentials = email ? {email, email_confirm: true} : {phone, phone_confirm: true};
136
+ const {data: created, error: createError} = await server.auth.admin.createUser({
137
+ ...credentials,
138
+ password,
139
+ user_metadata: {full_name: fullName, username: username || (email ? email.split("@")[0] : phone.replace(/[^0-9]/g, "")), temporary_credential: true},
140
+ });
141
+ if (createError || !created?.user?.id) return reply(400, {error: provisionErrors.has(createError?.code) ? createError.code : "provision_failed"}, origin);
142
+ logger.info("finora_admin_user_provisioned", {actor: user.id, user_id: created.user.id});
143
+ return reply(201, {ok: true, user_id: created.user.id}, origin);
144
+ } catch (error) {
145
+ if (error instanceof AuthorizationReadError) return reply(503, {error: "authorization_unavailable"}, origin);
146
+ logger.error("admin_user_management_failed", "internal_error");
147
+ return reply(500, {error: "internal_error"}, origin);
148
+ }
149
+ };
150
+}
supabase/functions/admin-user-management/index.ts
+5
-76
@@ -1,78 +1,7 @@
1
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
2
+import { createAdminUserManagementHandler } from "./handler.mjs";
3
3
-const allowedOrigins = new Set(["https://factoreasy.ir","https://www.factoreasy.ir"]);
4
-const allowedHeaders = "authorization,apikey,content-type,x-client-info";
5
-const cors = (origin: string | null) => ({
6
- "Access-Control-Allow-Origin": origin && allowedOrigins.has(origin) ? origin : "https://factoreasy.ir",
7
- "Access-Control-Allow-Headers": allowedHeaders,
8
- "Access-Control-Allow-Methods": "POST,OPTIONS",
9
- "Vary": "Origin",
10
- "Content-Type": "application/json; charset=utf-8",
11
- "Cache-Control": "no-store",
12
-});
13
-function reply(status: number, body: unknown, origin: string|null) {
14
- return new Response(JSON.stringify(body),{status,headers:cors(origin)});
15
-}
16
-function validEmail(raw: string) {
17
- return raw.length<=254 && /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(raw);
18
-}
19
-function strongPassword(value: string) {
20
- return value.length>=12 && value.length<=128 && /[A-Z]/.test(value) && /[a-z]/.test(value) && /\d/.test(value) && /[^A-Za-z\d]/.test(value);
21
-}
22
-Deno.serve(async (request: Request) => {
23
- const origin=request.headers.get("Origin");
24
- if(origin && !allowedOrigins.has(origin))return reply(403,{error:"origin_not_allowed"},origin);
25
- if(request.method==="OPTIONS")return new Response(null,{status:204,headers:cors(origin)});
26
- if(request.method!=="POST")return reply(405,{error:"method_not_allowed"},origin);
27
- const bearer=request.headers.get("Authorization")||"";
28
- if(!/^Bearer\s+[^\s]+$/i.test(bearer))return reply(401,{error:"unauthorized"},origin);
29
- const projectUrl=Deno.env.get("SUPABASE_URL");
30
- const anon=Deno.env.get("SUPABASE_ANON_KEY");
31
- const service=Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
32
- if(!projectUrl||!anon||!service)return reply(503,{error:"server_configuration_missing"},origin);
33
- try {
34
- const caller=createClient(projectUrl,anon,{auth:{persistSession:false,autoRefreshToken:false}});
35
- const token=bearer.replace(/^Bearer\s+/i,"");
36
- const {data:{user},error:userError}=await caller.auth.getUser(token);
37
- if(userError||!user)return reply(401,{error:"unauthorized"},origin);
38
- const server=createClient(projectUrl,service,{auth:{persistSession:false,autoRefreshToken:false}});
39
- // A server-fetched global admin role is mandatory. Client-side flags never grant access.
40
- const {data:profile,error:profileError}=await server.from("profiles").select("id,role").eq("id",user.id).single();
41
- if(profileError||profile?.role!=="admin")return reply(403,{error:"admin_required"},origin);
42
- const raw=await request.text();
43
- if(raw.length>8192)return reply(413,{error:"payload_too_large"},origin);
44
- let body: Record<string,unknown>;
45
- try {body=JSON.parse(raw)} catch {return reply(400,{error:"invalid_json"},origin)}
46
- if(body?.action==="set_password"){
47
- const target=String(body.user_id||"");
48
- const newPassword=String(body.password||"");
49
- if(!/^[0-9a-f-]{36}$/i.test(target)||!strongPassword(newPassword))return reply(400,{error:"invalid_password_reset_request"},origin);
50
- const {error}=await server.auth.admin.updateUserById(target,{password:newPassword,user_metadata:{force_password_change:true}});
51
- if(error)return reply(400,{error:"password_reset_failed"},origin);
52
- console.info("finora_admin_password_updated",{actor:user.id,user_id:target});
53
- return reply(200,{ok:true},origin);
54
- }
55
- if(body?.action!=="create")return reply(400,{error:"unsupported_action"},origin);
56
- const email=String(body.email||"").trim().toLowerCase();
57
- const phone=String(body.phone||"").trim();
58
- const fullName=String(body.full_name||"").trim();
59
- const username=String(body.username||"").trim().toLowerCase();
60
- const password=String(body.temporary_password||"");
61
- if((!email&&!phone)||(email&&!validEmail(email))||(phone&&!/^\+[1-9][0-9]{7,14}$/.test(phone)))return reply(400,{error:"invalid_email_or_phone"},origin);
62
- if(fullName.length>120||username && !/^[a-z0-9_.-]{3,40}$/.test(username))return reply(400,{error:"invalid_profile"},origin);
63
- if(!strongPassword(password))return reply(400,{error:"weak_temporary_password"},origin);
64
- const credentials=email?{email,email_confirm:true}:{phone,phone_confirm:true};
65
- const {data:created,error:createError}=await server.auth.admin.createUser({
66
- ...credentials,
67
- password,
68
- user_metadata:{full_name:fullName,username:username||(email?email.split("@")[0]:phone.replace(/[^0-9]/g,"")),temporary_credential:true},
69
- });
70
- if(createError||!created?.user?.id)return reply(400,{error:createError?.code||"provision_failed"},origin);
71
- // Existing Auth trigger provisions ordinary profile, organization and trial license.
72
- console.info("finora_admin_user_provisioned",{actor:user.id,user_id:created.user.id});
73
- return reply(201,{ok:true,user_id:created.user.id},origin);
74
- } catch(error) {
75
- console.error("admin_user_management_failed",error instanceof Error?error.name:"unexpected");
76
- return reply(500,{error:"internal_error"},origin);
77
- }
78
-});
4
+Deno.serve(createAdminUserManagementHandler({
5
+ createClient,
6
+ getEnv: (name: string) => Deno.env.get(name),
7
+}));