LifeMate — Personal, Family & Learning Companion
Phase 2: Product Foundation & Identity
Complete the LifeMate product foundation and identity vertical slice, including Flutter Android/Web-PWA scaffold, provider-neutral backend, PostgreSQL identity/family model, auth and recovery flows, role-aware Persian RTL shells, CI/security gates, and staging verification.
davoodmehraban89 committed
Oct 5, 2026 at 13:28 UTC
51da2aab9ae68734b13f0938ce41c831f9240aaf
50 files changed
+3382
-78
.github/workflows/ci.yml
new
+88
@@ -0,0 +1,88 @@
1
+name: Phase 2 CI
2
+
3
+on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+permissions:
9
+ contents: read
10
+
11
+jobs:
12
+ security:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - name: Reject committed environment files
17
+ run: |
18
+ bad_files=$(find . -type f \( -name '.env' -o -name '.env.*' \) ! -name '.env.example' ! -path './.git/*')
19
+ if [ -n "$bad_files" ]; then
20
+ echo "Committed environment files detected:"
21
+ echo "$bad_files"
22
+ exit 1
23
+ fi
24
+ - name: Scan high-confidence secret patterns
25
+ run: |
26
+ if git grep -I -n -E '(-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9_]{30,}|sk_live_[A-Za-z0-9]{20,})' -- .; then
27
+ echo "Potential committed secret detected."
28
+ exit 1
29
+ fi
30
+
31
+ flutter:
32
+ runs-on: ubuntu-latest
33
+ defaults:
34
+ run:
35
+ working-directory: apps/lifemate
36
+ steps:
37
+ - uses: actions/checkout@v4
38
+ - uses: subosito/flutter-action@v2
39
+ with:
40
+ channel: stable
41
+ cache: true
42
+ - run: flutter pub get
43
+ - run: dart format lib test
44
+ - run: flutter analyze
45
+ - run: flutter test
46
+ - run: flutter build web --release
47
+ - run: flutter build apk --debug
48
+
49
+ backend:
50
+ runs-on: ubuntu-latest
51
+ services:
52
+ postgres:
53
+ image: postgres:17
54
+ env:
55
+ POSTGRES_PASSWORD: lifemate_ci
56
+ POSTGRES_DB: lifemate_ci
57
+ ports: ['5432:5432']
58
+ options: >-
59
+ --health-cmd "pg_isready -U postgres -d lifemate_ci"
60
+ --health-interval 5s --health-timeout 5s --health-retries 10
61
+ env:
62
+ PGPASSWORD: lifemate_ci
63
+ DATABASE_URL: postgresql://postgres:lifemate_ci@localhost:5432/lifemate_ci
64
+ JWT_SECRET: ci-only-secret-ci-only-secret-ci-only-secret
65
+ NODE_ENV: test
66
+ steps:
67
+ - uses: actions/checkout@v4
68
+ - uses: actions/setup-node@v4
69
+ with:
70
+ node-version: 22
71
+ - name: Apply migrations
72
+ run: |
73
+ psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/migrations/0001_identity_family.sql
74
+ psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/migrations/0002_auth.sql
75
+ - name: Database authorization tests
76
+ run: psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/tests/schema_test.sql
77
+ - name: Install backend
78
+ working-directory: backend
79
+ run: npm install
80
+ - name: Backend dependency audit
81
+ working-directory: backend
82
+ run: npm audit --audit-level=high
83
+ - name: Backend tests
84
+ working-directory: backend
85
+ run: npm test
86
+ - name: Verify schema objects
87
+ run: |
88
+ test "$(psql -h localhost -U postgres -d lifemate_ci -Atc "select count(*) from information_schema.tables where table_schema='public' and table_name in ('app_user','profile','family_workspace','family_membership','guardian_relationship','family_invitation','access_audit','auth_credential','auth_token','auth_session');")" = "10"
.gitignore
new
+22
@@ -0,0 +1,22 @@
1
+# Flutter/Dart
2
+.dart_tool/
3
+.packages
4
+.pub-cache/
5
+build/
6
+.flutter-plugins
7
+.flutter-plugins-dependencies
8
+
9
+# IDE/OS
10
+.idea/
11
+.vscode/
12
+.DS_Store
13
+
14
+# Secrets
15
+.env
16
+.env.*
17
+!.env.example
18
+*.pem
19
+*.key
20
+
21
+# Android local
22
+**/android/local.properties
PROJECT_STATE.md
+26
-28
@@ -1,57 +1,55 @@
1
# LifeMate — Project State
2
3
**Last updated:** 2026-10-05
4
-**Phase:** Phase 1 COMPLETE — Phase 2 READY
4
+**Phase:** Phase 2 — Product Foundation & Identity — COMPLETE
5
**Repository:** `davoodmehraban89/LifeMate`
6
**Working product name:** LifeMate — approved
7
8
## Transfer checkpoint
9
-Phase 1 (Foundation, Product Contract & UX Direction) has passed its exit gate on branch `phase-1/foundation-completion`. Product scope, roles/visibility, UX information architecture, visual direction, conceptual domain model, frontend/backend baselines, PWA constraints, safety/privacy risks and Phase 2 quality gates are documented. No application scaffold has been generated yet.
9
+Phase 1 and Phase 2 are complete. The implementation branch `phase-2/product-foundation-identity` now contains the real Flutter Android/Web-PWA scaffold, provider-neutral Node API, PostgreSQL identity/family schema, auth/recovery/change-password flows, profile/family/invitation/guardian foundations, Persian RTL role-aware Teen/Parent shells, security gates and CI. Railway staging is live with PostgreSQL, API and transactional-email test infrastructure. The Phase 2 CI run for head `9c8a813d4673f9f320d804c91a347a14a51d26db` passed backend, Flutter/Web/Android and security jobs.
10
11
## Five-phase roadmap
12
1. **Foundation, Product Contract & UX Direction** — COMPLETE
13
-2. **Product Foundation & Identity** — READY
14
-3. **Planner, School & Family Core**
13
+2. **Product Foundation & Identity** — COMPLETE
14
+3. **Planner, School & Family Core** — NEXT
15
4. **AI Guides, Learning & Wellbeing**
16
5. **Hardening, Observability & Release**
17
18
## Accepted architecture baseline
19
- Client: Flutter for Android + app-centric responsive Web/PWA.
20
- iPhone/iPad initial distribution: Home Screen PWA; future packaged/native iOS path preserved.
21
-- Backend: Supabase PostgreSQL + Auth + RLS; privileged workflows/AI/server secrets in server-side functions/services.
21
+- Backend: provider-neutral Node API + standard PostgreSQL. Railway is the current staging host; managed database/provider can be replaced without changing domain contracts.
22
+- Identity: LifeMate-owned email/password/session adapter with Argon2id, verification/reset tokens, rotating refresh sessions and server-side authorization.
23
- Offline: explicit custom web service-worker/cache strategy; browser storage is non-authoritative.
24
- Authorization: relationship-aware and server-enforced; family admin is not blanket private-content access.
25
26
## Product/UX baseline
26
-- Teen navigation: Today, Planner, School, AI, Me.
27
-- Parent/adult navigation: Today, Planner, Family, Guide, Me.
27
+- Student navigation uses MyStudyLife as the primary IA benchmark: Today, Weekly Schedule, Calendar, Tasks, Exams/Grades, Focus, AI; LifeMate Family/Wellbeing extensions are additive.
28
+- Parent/adult experiences share the platform while emphasizing Family, authorized progress/support information and guidance.
29
- Parent support focuses on authorized schedule/academic/support summaries, not routine private transcript surveillance.
29
-- Visual language: warm, modern, calm, graphical, teen-friendly but non-childish; Persian RTL first-class.
30
+- Visual language: warm, modern, calm, graphical, teen-friendly but non-childish; Persian RTL first-class. Default profile themes: daughter/teen girl = white + soft pink; son/teen boy = white + calm blue; parents/adults = white + calm blue.
31
- Figma artifact exists: `LifeMate — Product UX & Brand v1` with initial editable direction frames.
32
- Canva is supporting visual/illustration exploration; Figma remains UI source of truth.
33
- Notion Project Hub exists as management mirror; GitHub remains technical source of truth.
34
34
-## Phase 1 deliverables
35
-- `docs/ROADMAP.md`
36
-- `docs/product/PRODUCT_SPEC_V1.md`
37
-- `docs/product/FEATURE_PRIORITIES_V1.md`
38
-- `docs/product/PERMISSION_MATRIX_V0.md`
39
-- `docs/product/PHASE_1_EXECUTION.md`
40
-- `docs/ux/IA_AND_JOURNEYS_V1.md`
41
-- `docs/ux/BRAND_BRIEF_V1.md`
42
-- `docs/architecture/DOMAIN_MODEL_V1.md`
43
-- `docs/architecture/PWA_PLATFORM_CONSTRAINTS_V1.md`
44
-- `docs/architecture/PHASE_2_BLUEPRINT.md`
45
-- `docs/quality/PHASE_2_QUALITY_GATES.md`
46
-- `docs/quality/ANALYTICS_POLICY_V1.md`
47
-- `docs/safety/SAFETY_PRIVACY_RISK_V1.md`
48
-- ADR-0001 through ADR-0005.
49
-
50
-## Phase 2 first vertical slice
51
-Auth → verified email/recovery/change password → Profile → Family Workspace → invitation/membership → Guardian Relationship → RLS/permission tests → Teen/Parent authenticated shells → CI/staging smoke.
35
+## Phase 2 completed vertical slice
36
+Auth → verified email/recovery/change password → Profile → Family Workspace → invitation/membership → Guardian Relationship → server-side permission tests → Persian RTL Teen/Parent shells → CI → persistent staging infrastructure and smoke verification.
37
+
38
+### Verified Phase 2 gates
39
+- PostgreSQL migrations and authorization helper tests pass.
40
+- Backend API tests pass, including unauthenticated, teen/non-admin denial and active-member role-escalation protection.
41
+- Backend dependency audit reports no high-severity blocking vulnerability.
42
+- Secret/environment-file CI gates pass.
43
+- Flutter formatting, static analysis and widget tests pass.
44
+- Flutter Web release build passes.
45
+- Android debug APK build passes.
46
+- Railway staging PostgreSQL, API and Mailpit are online; API health and staging transactional-email probe passed.
47
+
48
+## Phase 3 entry point
49
+Implement Planner, School & Family Core on top of the completed identity/family contracts. Preserve role-aware navigation, relationship-aware permissions, Persian RTL, provider-neutral backend boundaries and the existing CI/security gates.
50
51
## Production-gate items intentionally deferred
54
-These do not block Phase 2 engineering foundation but do block public production of wellbeing/minor-sensitive AI features: jurisdiction-specific legal/guardian consent review; safety severity taxonomy; emergency resource localization; AI provider privacy/retention review; wellbeing retention/export/deletion policy.
52
+These do not block the engineering foundation but do block public production of wellbeing/minor-sensitive AI features: jurisdiction-specific legal/guardian consent review; safety severity taxonomy; emergency resource localization; AI provider privacy/retention review; wellbeing retention/export/deletion policy.
53
54
## Guardrail
57
-AI/wellbeing production exposure stays disabled until its dedicated safety/legal/provider gates pass. Production deploys, destructive migrations and sensitive access changes still require explicit action-specific approval.
\ No newline at end of file
55
+AI/wellbeing production exposure stays disabled until its dedicated safety/legal/provider gates pass. Production deploys, destructive migrations and sensitive access changes still require explicit action-specific approval.
apps/lifemate/.metadata
new
+33
@@ -0,0 +1,33 @@
1
+# This file tracks properties of this Flutter project.
2
+# Used by Flutter tool to assess capabilities and perform upgrades etc.
3
+#
4
+# This file should be version controlled and should not be manually edited.
5
+
6
+version:
7
+ revision: "5fc346839b5d0eef006ed8404392afb4dfae428d"
8
+ channel: "stable"
9
+
10
+project_type: app
11
+
12
+# Tracks metadata for the flutter migrate command
13
+migration:
14
+ platforms:
15
+ - platform: root
16
+ create_revision: 5fc346839b5d0eef006ed8404392afb4dfae428d
17
+ base_revision: 5fc346839b5d0eef006ed8404392afb4dfae428d
18
+ - platform: android
19
+ create_revision: 5fc346839b5d0eef006ed8404392afb4dfae428d
20
+ base_revision: 5fc346839b5d0eef006ed8404392afb4dfae428d
21
+ - platform: web
22
+ create_revision: 5fc346839b5d0eef006ed8404392afb4dfae428d
23
+ base_revision: 5fc346839b5d0eef006ed8404392afb4dfae428d
24
+
25
+ # User provided section
26
+
27
+ # List of Local paths (relative to this file) that should be
28
+ # ignored by the migrate tool.
29
+ #
30
+ # Files that are not part of the templates will be ignored by default.
31
+ unmanaged_files:
32
+ - 'lib/main.dart'
33
+ - 'ios/Runner.xcodeproj/project.pbxproj'
apps/lifemate/analysis_options.yaml
new
+5
@@ -0,0 +1,5 @@
1
+include: package:flutter_lints/flutter.yaml
2
+linter:
3
+ rules:
4
+ prefer_single_quotes: true
5
+ use_super_parameters: true
apps/lifemate/android/.gitignore
new
+14
@@ -0,0 +1,14 @@
1
+gradle-wrapper.jar
2
+/.gradle
3
+/captures/
4
+/gradlew
5
+/gradlew.bat
6
+/local.properties
7
+GeneratedPluginRegistrant.java
8
+.cxx/
9
+
10
+# Remember to never publicly share your keystore.
11
+# See https://flutter.dev/to/reference-keystore
12
+key.properties
13
+**/*.keystore
14
+**/*.jks
apps/lifemate/android/app/build.gradle.kts
new
+49
@@ -0,0 +1,49 @@
1
+plugins {
2
+ id("com.android.application")
3
+ // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
4
+ id("dev.flutter.flutter-gradle-plugin")
5
+}
6
+
7
+android {
8
+ namespace = "com.example.lifemate"
9
+ compileSdk = flutter.compileSdkVersion
10
+ ndkVersion = flutter.ndkVersion
11
+
12
+ compileOptions {
13
+ sourceCompatibility = JavaVersion.VERSION_17
14
+ targetCompatibility = JavaVersion.VERSION_17
15
+ }
16
+
17
+ defaultConfig {
18
+ // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
19
+ applicationId = "com.example.lifemate"
20
+ // You can update the following values to match your application needs.
21
+ // For more information, see: https://flutter.dev/to/review-gradle-config.
22
+ minSdk = flutter.minSdkVersion
23
+ targetSdk = flutter.targetSdkVersion
24
+ // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
25
+ // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
26
+ // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
27
+ // flag during build.
28
+ versionCode = flutter.versionCode
29
+ versionName = flutter.versionName
30
+ }
31
+
32
+ buildTypes {
33
+ release {
34
+ // TODO: Add your own signing config for the release build.
35
+ // Signing with the debug keys for now, so `flutter run --release` works.
36
+ signingConfig = signingConfigs.getByName("debug")
37
+ }
38
+ }
39
+}
40
+
41
+kotlin {
42
+ compilerOptions {
43
+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
44
+ }
45
+}
46
+
47
+flutter {
48
+ source = "../.."
49
+}
apps/lifemate/android/app/src/debug/AndroidManifest.xml
new
+7
@@ -0,0 +1,7 @@
1
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <!-- The INTERNET permission is required for development. Specifically,
3
+ the Flutter tool needs it to communicate with the running application
4
+ to allow setting breakpoints, to provide hot reload, etc.
5
+ -->
6
+ <uses-permission android:name="android.permission.INTERNET"/>
7
+</manifest>
apps/lifemate/android/app/src/main/AndroidManifest.xml
new
+45
@@ -0,0 +1,45 @@
1
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <application
3
+ android:label="LifeMate"
4
+ android:name="${applicationName}"
5
+ android:icon="@drawable/lifemate_logo">
6
+ <activity
7
+ android:name=".MainActivity"
8
+ android:exported="true"
9
+ android:launchMode="singleTop"
10
+ android:taskAffinity=""
11
+ android:theme="@style/LaunchTheme"
12
+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
13
+ android:hardwareAccelerated="true"
14
+ android:windowSoftInputMode="adjustResize">
15
+ <!-- Specifies an Android theme to apply to this Activity as soon as
16
+ the Android process has started. This theme is visible to the user
17
+ while the Flutter UI initializes. After that, this theme continues
18
+ to determine the Window background behind the Flutter UI. -->
19
+ <meta-data
20
+ android:name="io.flutter.embedding.android.NormalTheme"
21
+ android:resource="@style/NormalTheme"
22
+ />
23
+ <intent-filter>
24
+ <action android:name="android.intent.action.MAIN"/>
25
+ <category android:name="android.intent.category.LAUNCHER"/>
26
+ </intent-filter>
27
+ </activity>
28
+ <!-- Don't delete the meta-data below.
29
+ This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
30
+ <meta-data
31
+ android:name="flutterEmbedding"
32
+ android:value="2" />
33
+ </application>
34
+ <!-- Required to query activities that can process text, see:
35
+ https://developer.android.com/training/package-visibility and
36
+ https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
37
+
38
+ In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
39
+ <queries>
40
+ <intent>
41
+ <action android:name="android.intent.action.PROCESS_TEXT"/>
42
+ <data android:mimeType="text/plain"/>
43
+ </intent>
44
+ </queries>
45
+</manifest>
apps/lifemate/android/app/src/main/kotlin/com/example/lifemate/MainActivity.kt
new
+5
@@ -0,0 +1,5 @@
1
+package com.example.lifemate
2
+
3
+import io.flutter.embedding.android.FlutterActivity
4
+
5
+class MainActivity : FlutterActivity()
apps/lifemate/android/app/src/main/res/drawable-v21/launch_background.xml
new
+12
@@ -0,0 +1,12 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<!-- Modify this file to customize your launch splash screen -->
3
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
4
+ <item android:drawable="?android:colorBackground" />
5
+
6
+ <!-- You can insert your own image assets here -->
7
+ <!-- <item>
8
+ <bitmap
9
+ android:gravity="center"
10
+ android:src="@mipmap/launch_image" />
11
+ </item> -->
12
+</layer-list>
apps/lifemate/android/app/src/main/res/drawable/launch_background.xml
new
+12
@@ -0,0 +1,12 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<!-- Modify this file to customize your launch splash screen -->
3
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
4
+ <item android:drawable="@android:color/white" />
5
+
6
+ <!-- You can insert your own image assets here -->
7
+ <!-- <item>
8
+ <bitmap
9
+ android:gravity="center"
10
+ android:src="@mipmap/launch_image" />
11
+ </item> -->
12
+</layer-list>
apps/lifemate/android/app/src/main/res/drawable/lifemate_logo.xml
new
+15
@@ -0,0 +1,15 @@
1
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
2
+ android:width="108dp"
3
+ android:height="108dp"
4
+ android:viewportWidth="108"
5
+ android:viewportHeight="108">
6
+ <path
7
+ android:fillColor="#4D86E8"
8
+ android:pathData="M54,4A50,50 0,1 1,54 104A50,50 0,1 1,54 4" />
9
+ <path
10
+ android:fillColor="#FFFFFF"
11
+ android:pathData="M30,69C38,48 46,38 59,34C69,31 78,35 82,43C75,42 68,44 62,49C55,55 52,63 51,74L42,67C39,75 36,81 31,85Z" />
12
+ <path
13
+ android:fillColor="#FFFFFF"
14
+ android:pathData="M70,28A7,7 0,1 1,70 42A7,7 0,1 1,70 28" />
15
+</vector>
apps/lifemate/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
Binary files /dev/null and b/apps/lifemate/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
apps/lifemate/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
Binary files /dev/null and b/apps/lifemate/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
apps/lifemate/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
Binary files /dev/null and b/apps/lifemate/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
apps/lifemate/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Binary files /dev/null and b/apps/lifemate/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
apps/lifemate/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Binary files /dev/null and b/apps/lifemate/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
apps/lifemate/android/app/src/main/res/values-night/styles.xml
new
+18
@@ -0,0 +1,18 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<resources>
3
+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
4
+ <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
5
+ <!-- Show a splash screen on the activity. Automatically removed when
6
+ the Flutter engine draws its first frame -->
7
+ <item name="android:windowBackground">@drawable/launch_background</item>
8
+ </style>
9
+ <!-- Theme applied to the Android Window as soon as the process has started.
10
+ This theme determines the color of the Android Window while your
11
+ Flutter UI initializes, as well as behind your Flutter UI while its
12
+ running.
13
+
14
+ This Theme is only used starting with V2 of Flutter's Android embedding. -->
15
+ <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
16
+ <item name="android:windowBackground">?android:colorBackground</item>
17
+ </style>
18
+</resources>
apps/lifemate/android/app/src/main/res/values/styles.xml
new
+18
@@ -0,0 +1,18 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<resources>
3
+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
4
+ <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
5
+ <!-- Show a splash screen on the activity. Automatically removed when
6
+ the Flutter engine draws its first frame -->
7
+ <item name="android:windowBackground">@drawable/launch_background</item>
8
+ </style>
9
+ <!-- Theme applied to the Android Window as soon as the process has started.
10
+ This theme determines the color of the Android Window while your
11
+ Flutter UI initializes, as well as behind your Flutter UI while its
12
+ running.
13
+
14
+ This Theme is only used starting with V2 of Flutter's Android embedding. -->
15
+ <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
16
+ <item name="android:windowBackground">?android:colorBackground</item>
17
+ </style>
18
+</resources>
apps/lifemate/android/app/src/profile/AndroidManifest.xml
new
+7
@@ -0,0 +1,7 @@
1
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <!-- The INTERNET permission is required for development. Specifically,
3
+ the Flutter tool needs it to communicate with the running application
4
+ to allow setting breakpoints, to provide hot reload, etc.
5
+ -->
6
+ <uses-permission android:name="android.permission.INTERNET"/>
7
+</manifest>
apps/lifemate/android/build.gradle.kts
new
+24
@@ -0,0 +1,24 @@
1
+allprojects {
2
+ repositories {
3
+ google()
4
+ mavenCentral()
5
+ }
6
+}
7
+
8
+val newBuildDir: Directory =
9
+ rootProject.layout.buildDirectory
10
+ .dir("../../build")
11
+ .get()
12
+rootProject.layout.buildDirectory.value(newBuildDir)
13
+
14
+subprojects {
15
+ val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
16
+ project.layout.buildDirectory.value(newSubprojectBuildDir)
17
+}
18
+subprojects {
19
+ project.evaluationDependsOn(":app")
20
+}
21
+
22
+tasks.register<Delete>("clean") {
23
+ delete(rootProject.layout.buildDirectory)
24
+}
apps/lifemate/android/gradle.properties
new
+6
@@ -0,0 +1,6 @@
1
+org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
2
+android.useAndroidX=true
3
+# This newDsl flag was added by the Flutter template
4
+android.newDsl=false
5
+# This builtInKotlin flag was added by the Flutter template
6
+android.builtInKotlin=false
apps/lifemate/android/gradle/wrapper/gradle-wrapper.properties
new
+5
@@ -0,0 +1,5 @@
1
+distributionBase=GRADLE_USER_HOME
2
+distributionPath=wrapper/dists
3
+zipStoreBase=GRADLE_USER_HOME
4
+zipStorePath=wrapper/dists
5
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
apps/lifemate/android/settings.gradle.kts
new
+26
@@ -0,0 +1,26 @@
1
+pluginManagement {
2
+ val flutterSdkPath =
3
+ run {
4
+ val properties = java.util.Properties()
5
+ file("local.properties").inputStream().use { properties.load(it) }
6
+ val flutterSdkPath = properties.getProperty("flutter.sdk")
7
+ require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
8
+ flutterSdkPath
9
+ }
10
+
11
+ includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
12
+
13
+ repositories {
14
+ google()
15
+ mavenCentral()
16
+ gradlePluginPortal()
17
+ }
18
+}
19
+
20
+plugins {
21
+ id("dev.flutter.flutter-plugin-loader") version "1.0.0"
22
+ id("com.android.application") version "9.1.0" apply false
23
+ id("org.jetbrains.kotlin.android") version "2.4.0" apply false
24
+}
25
+
26
+include(":app")
apps/lifemate/lib/api.dart
new
+269
@@ -0,0 +1,269 @@
1
+import 'dart:convert';
2
+
3
+import 'package:http/http.dart' as http;
4
+
5
+abstract class IdentityApi {
6
+ String? get accessToken;
7
+
8
+ Future<void> register({
9
+ required String displayName,
10
+ required String email,
11
+ required String password,
12
+ });
13
+
14
+ Future<void> verifyEmail(String token);
15
+ Future<void> login(String email, String password);
16
+ Future<void> forgotPassword(String email);
17
+ Future<void> resetPassword(String token, String newPassword);
18
+ Future<void> changePassword(String currentPassword, String newPassword);
19
+ Future<Map<String, dynamic>> getProfile();
20
+ Future<Map<String, dynamic>> updateProfile({
21
+ String? displayName,
22
+ String? birthDate,
23
+ String? themePreference,
24
+ });
25
+ Future<List<Map<String, dynamic>>> listFamilies();
26
+ Future<List<Map<String, dynamic>>> listFamilyMembers(String familyId);
27
+ Future<Map<String, dynamic>> createFamily(String name, {String? role});
28
+ Future<void> inviteMember({
29
+ required String familyId,
30
+ required String email,
31
+ required String role,
32
+ String? themePreference,
33
+ });
34
+ Future<void> acceptInvitation(String token);
35
+ Future<void> setGuardian({
36
+ required String familyId,
37
+ required String guardianUserId,
38
+ required String minorUserId,
39
+ });
40
+}
41
+
42
+class ApiException implements Exception {
43
+ const ApiException(this.statusCode, this.code);
44
+ final int statusCode;
45
+ final String code;
46
+
47
+ @override
48
+ String toString() => 'ApiException($statusCode, $code)';
49
+}
50
+
51
+class HttpIdentityApi implements IdentityApi {
52
+ HttpIdentityApi({
53
+ String? baseUrl,
54
+ http.Client? client,
55
+ }) : baseUrl = baseUrl ??
56
+ const String.fromEnvironment(
57
+ 'LIFEMATE_API_URL',
58
+ defaultValue: 'http://localhost:8080',
59
+ ),
60
+ _client = client ?? http.Client();
61
+
62
+ final String baseUrl;
63
+ final http.Client _client;
64
+
65
+ @override
66
+ String? accessToken;
67
+ String? _refreshToken;
68
+
69
+ Uri _uri(String path) => Uri.parse('$baseUrl$path');
70
+
71
+ Map<String, String> _headers({bool auth = false}) => {
72
+ 'content-type': 'application/json',
73
+ if (auth && accessToken != null) 'authorization': 'Bearer $accessToken',
74
+ };
75
+
76
+ Future<Map<String, dynamic>> _json(
77
+ String method,
78
+ String path, {
79
+ Map<String, dynamic>? body,
80
+ bool auth = false,
81
+ bool retry = true,
82
+ }) async {
83
+ final request = http.Request(method, _uri(path))
84
+ ..headers.addAll(_headers(auth: auth));
85
+ if (body != null) request.body = jsonEncode(body);
86
+
87
+ final streamed = await _client.send(request);
88
+ final response = await http.Response.fromStream(streamed);
89
+
90
+ if (response.statusCode == 401 && auth && retry && _refreshToken != null) {
91
+ await _refresh();
92
+ return _json(method, path, body: body, auth: auth, retry: false);
93
+ }
94
+
95
+ if (response.statusCode < 200 || response.statusCode >= 300) {
96
+ var code = 'request_failed';
97
+ if (response.body.isNotEmpty) {
98
+ try {
99
+ code = (jsonDecode(response.body) as Map<String, dynamic>)['error']
100
+ ?.toString() ??
101
+ code;
102
+ } catch (_) {}
103
+ }
104
+ throw ApiException(response.statusCode, code);
105
+ }
106
+
107
+ if (response.body.isEmpty) return <String, dynamic>{};
108
+ return jsonDecode(response.body) as Map<String, dynamic>;
109
+ }
110
+
111
+ Future<void> _refresh() async {
112
+ final token = _refreshToken;
113
+ if (token == null) throw const ApiException(401, 'session_expired');
114
+ final result = await _json(
115
+ 'POST',
116
+ '/v1/auth/refresh',
117
+ body: {'refreshToken': token},
118
+ retry: false,
119
+ );
120
+ accessToken = result['accessToken']?.toString();
121
+ _refreshToken = result['refreshToken']?.toString();
122
+ }
123
+
124
+ @override
125
+ Future<void> register({
126
+ required String displayName,
127
+ required String email,
128
+ required String password,
129
+ }) async {
130
+ await _json('POST', '/v1/auth/register', body: {
131
+ 'displayName': displayName,
132
+ 'email': email,
133
+ 'password': password,
134
+ });
135
+ }
136
+
137
+ @override
138
+ Future<void> verifyEmail(String token) async {
139
+ await _json('POST', '/v1/auth/verify-email', body: {'token': token});
140
+ }
141
+
142
+ @override
143
+ Future<void> login(String email, String password) async {
144
+ final result = await _json('POST', '/v1/auth/login', body: {
145
+ 'email': email,
146
+ 'password': password,
147
+ });
148
+ accessToken = result['accessToken']?.toString();
149
+ _refreshToken = result['refreshToken']?.toString();
150
+ }
151
+
152
+ @override
153
+ Future<void> forgotPassword(String email) async {
154
+ await _json('POST', '/v1/auth/forgot-password', body: {'email': email});
155
+ }
156
+
157
+ @override
158
+ Future<void> resetPassword(String token, String newPassword) async {
159
+ await _json('POST', '/v1/auth/reset-password', body: {
160
+ 'token': token,
161
+ 'newPassword': newPassword,
162
+ });
163
+ }
164
+
165
+ @override
166
+ Future<void> changePassword(
167
+ String currentPassword,
168
+ String newPassword,
169
+ ) async {
170
+ await _json('POST', '/v1/auth/change-password', auth: true, body: {
171
+ 'currentPassword': currentPassword,
172
+ 'newPassword': newPassword,
173
+ });
174
+ }
175
+
176
+ @override
177
+ Future<Map<String, dynamic>> getProfile() =>
178
+ _json('GET', '/v1/profile', auth: true);
179
+
180
+ @override
181
+ Future<Map<String, dynamic>> updateProfile({
182
+ String? displayName,
183
+ String? birthDate,
184
+ String? themePreference,
185
+ }) =>
186
+ _json('PATCH', '/v1/profile', auth: true, body: {
187
+ if (displayName != null) 'displayName': displayName,
188
+ if (birthDate != null) 'birthDate': birthDate,
189
+ if (themePreference != null) 'themePreference': themePreference,
190
+ });
191
+
192
+ @override
193
+ Future<List<Map<String, dynamic>>> listFamilies() async {
194
+ final result = await _json('GET', '/v1/families', auth: true);
195
+ final families = (result['families'] as List<dynamic>? ?? const []);
196
+ return families
197
+ .map((item) => Map<String, dynamic>.from(item as Map))
198
+ .toList();
199
+ }
200
+
201
+ @override
202
+ Future<List<Map<String, dynamic>>> listFamilyMembers(String familyId) async {
203
+ final result = await _json(
204
+ 'GET',
205
+ '/v1/families/$familyId/members',
206
+ auth: true,
207
+ );
208
+ final members = (result['members'] as List<dynamic>? ?? const []);
209
+ return members
210
+ .map((item) => Map<String, dynamic>.from(item as Map))
211
+ .toList();
212
+ }
213
+
214
+ @override
215
+ Future<Map<String, dynamic>> createFamily(
216
+ String name, {
217
+ String? role,
218
+ }) =>
219
+ _json('POST', '/v1/families', auth: true, body: {
220
+ 'name': name,
221
+ if (role != null) 'role': role,
222
+ });
223
+
224
+ @override
225
+ Future<void> inviteMember({
226
+ required String familyId,
227
+ required String email,
228
+ required String role,
229
+ String? themePreference,
230
+ }) async {
231
+ await _json(
232
+ 'POST',
233
+ '/v1/families/$familyId/invitations',
234
+ auth: true,
235
+ body: {
236
+ 'email': email,
237
+ 'role': role,
238
+ if (themePreference != null) 'themePreference': themePreference,
239
+ },
240
+ );
241
+ }
242
+
243
+ @override
244
+ Future<void> acceptInvitation(String token) async {
245
+ await _json(
246
+ 'POST',
247
+ '/v1/invitations/accept',
248
+ auth: true,
249
+ body: {'token': token},
250
+ );
251
+ }
252
+
253
+ @override
254
+ Future<void> setGuardian({
255
+ required String familyId,
256
+ required String guardianUserId,
257
+ required String minorUserId,
258
+ }) async {
259
+ await _json(
260
+ 'POST',
261
+ '/v1/families/$familyId/guardians',
262
+ auth: true,
263
+ body: {
264
+ 'guardianUserId': guardianUserId,
265
+ 'minorUserId': minorUserId,
266
+ },
267
+ );
268
+ }
269
+}
apps/lifemate/lib/main.dart
new
+1067
@@ -0,0 +1,1067 @@
1
+import 'package:flutter/material.dart';
2
+import 'package:flutter_localizations/flutter_localizations.dart';
3
+
4
+import 'api.dart';
5
+
6
+void main() => runApp(LifeMateApp());
7
+
8
+class LifeMateApp extends StatelessWidget {
9
+ LifeMateApp({super.key, IdentityApi? api}) : api = api ?? HttpIdentityApi();
10
+ final IdentityApi api;
11
+
12
+ @override
13
+ Widget build(BuildContext context) {
14
+ final uri = Uri.base;
15
+ final token = uri.queryParameters['token'];
16
+ Widget entry = SignInPage(
17
+ api: api,
18
+ invitationToken:
19
+ token != null && uri.path.contains('accept-invitation') ? token : null,
20
+ );
21
+ if (token != null && uri.path.contains('verify-email')) {
22
+ entry = VerifyEmailPage(api: api, token: token);
23
+ } else if (token != null && uri.path.contains('reset-password')) {
24
+ entry = ResetPasswordPage(api: api, token: token);
25
+ }
26
+ return MaterialApp(
27
+ debugShowCheckedModeBanner: false,
28
+ locale: const Locale('fa'),
29
+ supportedLocales: const [Locale('fa'), Locale('en')],
30
+ localizationsDelegates: const [
31
+ GlobalMaterialLocalizations.delegate,
32
+ GlobalWidgetsLocalizations.delegate,
33
+ GlobalCupertinoLocalizations.delegate,
34
+ ],
35
+ theme: ThemeData(
36
+ colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF4D86E8)),
37
+ scaffoldBackgroundColor: const Color(0xFFF8FAFD),
38
+ inputDecorationTheme:
39
+ const InputDecorationTheme(border: OutlineInputBorder()),
40
+ useMaterial3: true,
41
+ ),
42
+ home: Directionality(textDirection: TextDirection.rtl, child: entry),
43
+ );
44
+ }
45
+}
46
+
47
+String errorText(Object error) {
48
+ if (error is ApiException) {
49
+ switch (error.code) {
50
+ case 'invalid_credentials':
51
+ return 'ایمیل یا رمز عبور صحیح نیست.';
52
+ case 'email_not_verified':
53
+ return 'ابتدا ایمیل حساب را تأیید کن.';
54
+ case 'account_exists':
55
+ return 'برای این ایمیل قبلاً حساب ساخته شده است.';
56
+ case 'invalid_password':
57
+ return 'رمز عبور باید حداقل ۱۰ کاراکتر باشد.';
58
+ case 'invalid_current_password':
59
+ return 'رمز فعلی صحیح نیست.';
60
+ case 'invalid_or_expired_token':
61
+ return 'لینک منقضی شده یا معتبر نیست.';
62
+ case 'forbidden':
63
+ return 'برای این عملیات دسترسی نداری.';
64
+ }
65
+ }
66
+ return 'عملیات انجام نشد. دوباره تلاش کن.';
67
+}
68
+
69
+class SignInPage extends StatefulWidget {
70
+ const SignInPage({super.key, required this.api, this.invitationToken});
71
+ final IdentityApi api;
72
+ final String? invitationToken;
73
+ @override
74
+ State<SignInPage> createState() => _SignInPageState();
75
+}
76
+
77
+class _SignInPageState extends State<SignInPage> {
78
+ final email = TextEditingController();
79
+ final password = TextEditingController();
80
+ bool busy = false;
81
+ String? error;
82
+
83
+ Future<void> submit() async {
84
+ setState(() {
85
+ busy = true;
86
+ error = null;
87
+ });
88
+ try {
89
+ await widget.api.login(email.text, password.text);
90
+ if (widget.invitationToken != null) {
91
+ await widget.api.acceptInvitation(widget.invitationToken!);
92
+ }
93
+ if (!mounted) return;
94
+ Navigator.of(context).pushReplacement(
95
+ MaterialPageRoute(builder: (_) => HomeShell(api: widget.api)),
96
+ );
97
+ } catch (e) {
98
+ if (mounted) setState(() => error = errorText(e));
99
+ } finally {
100
+ if (mounted) setState(() => busy = false);
101
+ }
102
+ }
103
+
104
+ @override
105
+ Widget build(BuildContext context) => Scaffold(
106
+ body: SafeArea(
107
+ child: Center(
108
+ child: ConstrainedBox(
109
+ constraints: const BoxConstraints(maxWidth: 440),
110
+ child: ListView(
111
+ padding: const EdgeInsets.all(28),
112
+ shrinkWrap: true,
113
+ children: [
114
+ const Icon(Icons.route_rounded, size: 64),
115
+ const SizedBox(height: 16),
116
+ const Text('LifeMate',
117
+ textAlign: TextAlign.center,
118
+ style:
119
+ TextStyle(fontSize: 32, fontWeight: FontWeight.w700)),
120
+ const Text('همراه شخصی، تحصیلی و خانوادگی',
121
+ textAlign: TextAlign.center),
122
+ const SizedBox(height: 28),
123
+ if (widget.invitationToken != null) ...[
124
+ const Card(
125
+ child: Padding(
126
+ padding: EdgeInsets.all(12),
127
+ child: Text(
128
+ 'برای قبول دعوت خانواده، با همان ایمیل دعوتشده وارد شو.'),
129
+ ),
130
+ ),
131
+ const SizedBox(height: 12),
132
+ ],
133
+ TextField(
134
+ controller: email,
135
+ keyboardType: TextInputType.emailAddress,
136
+ decoration: const InputDecoration(labelText: 'ایمیل'),
137
+ ),
138
+ const SizedBox(height: 12),
139
+ TextField(
140
+ controller: password,
141
+ obscureText: true,
142
+ decoration: const InputDecoration(labelText: 'رمز عبور'),
143
+ ),
144
+ if (error != null) ...[
145
+ const SizedBox(height: 12),
146
+ Text(error!,
147
+ style: TextStyle(
148
+ color: Theme.of(context).colorScheme.error)),
149
+ ],
150
+ const SizedBox(height: 16),
151
+ FilledButton(
152
+ onPressed: busy ? null : submit,
153
+ child: Text(busy ? 'در حال ورود...' : 'ورود'),
154
+ ),
155
+ TextButton(
156
+ onPressed: busy
157
+ ? null
158
+ : () => Navigator.of(context).push(MaterialPageRoute(
159
+ builder: (_) => RecoveryPage(api: widget.api))),
160
+ child: const Text('رمز عبور را فراموش کردهام'),
161
+ ),
162
+ TextButton(
163
+ onPressed: busy
164
+ ? null
165
+ : () => Navigator.of(context).push(MaterialPageRoute(
166
+ builder: (_) => RegistrationPage(api: widget.api))),
167
+ child: const Text('ساخت حساب جدید'),
168
+ ),
169
+ ],
170
+ ),
171
+ ),
172
+ ),
173
+ ),
174
+ );
175
+}
176
+
177
+class RegistrationPage extends StatefulWidget {
178
+ const RegistrationPage({super.key, required this.api});
179
+ final IdentityApi api;
180
+ @override
181
+ State<RegistrationPage> createState() => _RegistrationPageState();
182
+}
183
+
184
+class _RegistrationPageState extends State<RegistrationPage> {
185
+ final name = TextEditingController();
186
+ final email = TextEditingController();
187
+ final password = TextEditingController();
188
+ final confirm = TextEditingController();
189
+ bool busy = false;
190
+ String? error;
191
+
192
+ Future<void> submit() async {
193
+ if (password.text != confirm.text) {
194
+ setState(() => error = 'تکرار رمز عبور یکسان نیست.');
195
+ return;
196
+ }
197
+ setState(() {
198
+ busy = true;
199
+ error = null;
200
+ });
201
+ try {
202
+ await widget.api.register(
203
+ displayName: name.text, email: email.text, password: password.text);
204
+ if (!mounted) return;
205
+ ScaffoldMessenger.of(context).showSnackBar(
206
+ const SnackBar(content: Text('حساب ساخته شد. ایمیل تأیید را بررسی کن.')),
207
+ );
208
+ Navigator.pop(context);
209
+ } catch (e) {
210
+ if (mounted) setState(() => error = errorText(e));
211
+ } finally {
212
+ if (mounted) setState(() => busy = false);
213
+ }
214
+ }
215
+
216
+ @override
217
+ Widget build(BuildContext context) => SimpleFormPage(
218
+ title: 'ساخت حساب',
219
+ busy: busy,
220
+ error: error,
221
+ action: 'ثبتنام و ارسال ایمیل تأیید',
222
+ onPressed: submit,
223
+ fields: [
224
+ TextField(
225
+ controller: name,
226
+ decoration: const InputDecoration(labelText: 'نام')),
227
+ TextField(
228
+ controller: email,
229
+ keyboardType: TextInputType.emailAddress,
230
+ decoration: const InputDecoration(labelText: 'ایمیل')),
231
+ TextField(
232
+ controller: password,
233
+ obscureText: true,
234
+ decoration: const InputDecoration(labelText: 'رمز عبور')),
235
+ TextField(
236
+ controller: confirm,
237
+ obscureText: true,
238
+ decoration: const InputDecoration(labelText: 'تکرار رمز عبور')),
239
+ ],
240
+ );
241
+}
242
+
243
+class RecoveryPage extends StatefulWidget {
244
+ const RecoveryPage({super.key, required this.api});
245
+ final IdentityApi api;
246
+ @override
247
+ State<RecoveryPage> createState() => _RecoveryPageState();
248
+}
249
+
250
+class _RecoveryPageState extends State<RecoveryPage> {
251
+ final email = TextEditingController();
252
+ bool busy = false;
253
+ bool sent = false;
254
+ String? error;
255
+
256
+ Future<void> submit() async {
257
+ setState(() {
258
+ busy = true;
259
+ error = null;
260
+ });
261
+ try {
262
+ await widget.api.forgotPassword(email.text);
263
+ if (mounted) setState(() => sent = true);
264
+ } catch (e) {
265
+ if (mounted) setState(() => error = errorText(e));
266
+ } finally {
267
+ if (mounted) setState(() => busy = false);
268
+ }
269
+ }
270
+
271
+ @override
272
+ Widget build(BuildContext context) => SimpleFormPage(
273
+ title: 'بازیابی رمز عبور',
274
+ busy: busy,
275
+ error: error,
276
+ action: sent ? 'لینک ارسال شد' : 'ارسال لینک بازیابی',
277
+ onPressed: sent ? null : submit,
278
+ fields: [
279
+ TextField(
280
+ controller: email,
281
+ keyboardType: TextInputType.emailAddress,
282
+ decoration: const InputDecoration(labelText: 'ایمیل تأییدشده')),
283
+ if (sent)
284
+ const Text(
285
+ 'اگر حسابی با این ایمیل وجود داشته باشد، لینک بازیابی ارسال میشود.'),
286
+ ],
287
+ );
288
+}
289
+
290
+class VerifyEmailPage extends StatefulWidget {
291
+ const VerifyEmailPage({super.key, required this.api, required this.token});
292
+ final IdentityApi api;
293
+ final String token;
294
+ @override
295
+ State<VerifyEmailPage> createState() => _VerifyEmailPageState();
296
+}
297
+
298
+class _VerifyEmailPageState extends State<VerifyEmailPage> {
299
+ String message = 'در حال تأیید ایمیل...';
300
+ @override
301
+ void initState() {
302
+ super.initState();
303
+ verify();
304
+ }
305
+
306
+ Future<void> verify() async {
307
+ try {
308
+ await widget.api.verifyEmail(widget.token);
309
+ if (mounted) setState(() => message = 'ایمیل با موفقیت تأیید شد.');
310
+ } catch (e) {
311
+ if (mounted) setState(() => message = errorText(e));
312
+ }
313
+ }
314
+
315
+ @override
316
+ Widget build(BuildContext context) =>
317
+ Scaffold(body: Center(child: Text(message)));
318
+}
319
+
320
+class ResetPasswordPage extends StatefulWidget {
321
+ const ResetPasswordPage({super.key, required this.api, required this.token});
322
+ final IdentityApi api;
323
+ final String token;
324
+ @override
325
+ State<ResetPasswordPage> createState() => _ResetPasswordPageState();
326
+}
327
+
328
+class _ResetPasswordPageState extends State<ResetPasswordPage> {
329
+ final password = TextEditingController();
330
+ final confirm = TextEditingController();
331
+ bool busy = false;
332
+ bool done = false;
333
+ String? error;
334
+
335
+ Future<void> submit() async {
336
+ if (password.text != confirm.text) {
337
+ setState(() => error = 'تکرار رمز عبور یکسان نیست.');
338
+ return;
339
+ }
340
+ setState(() {
341
+ busy = true;
342
+ error = null;
343
+ });
344
+ try {
345
+ await widget.api.resetPassword(widget.token, password.text);
346
+ if (mounted) setState(() => done = true);
347
+ } catch (e) {
348
+ if (mounted) setState(() => error = errorText(e));
349
+ } finally {
350
+ if (mounted) setState(() => busy = false);
351
+ }
352
+ }
353
+
354
+ @override
355
+ Widget build(BuildContext context) => SimpleFormPage(
356
+ title: 'ساخت رمز جدید',
357
+ busy: busy,
358
+ error: error,
359
+ action: done ? 'رمز تغییر کرد' : 'ذخیره رمز جدید',
360
+ onPressed: done ? null : submit,
361
+ fields: [
362
+ TextField(
363
+ controller: password,
364
+ obscureText: true,
365
+ decoration: const InputDecoration(labelText: 'رمز جدید')),
366
+ TextField(
367
+ controller: confirm,
368
+ obscureText: true,
369
+ decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
370
+ ],
371
+ );
372
+}
373
+
374
+class ChangePasswordPage extends StatefulWidget {
375
+ const ChangePasswordPage({super.key, required this.api});
376
+ final IdentityApi api;
377
+ @override
378
+ State<ChangePasswordPage> createState() => _ChangePasswordPageState();
379
+}
380
+
381
+class _ChangePasswordPageState extends State<ChangePasswordPage> {
382
+ final current = TextEditingController();
383
+ final next = TextEditingController();
384
+ final confirm = TextEditingController();
385
+ bool busy = false;
386
+ String? error;
387
+
388
+ Future<void> submit() async {
389
+ if (next.text != confirm.text) {
390
+ setState(() => error = 'تکرار رمز عبور یکسان نیست.');
391
+ return;
392
+ }
393
+ setState(() {
394
+ busy = true;
395
+ error = null;
396
+ });
397
+ try {
398
+ await widget.api.changePassword(current.text, next.text);
399
+ if (!mounted) return;
400
+ ScaffoldMessenger.of(context)
401
+ .showSnackBar(const SnackBar(content: Text('رمز عبور تغییر کرد.')));
402
+ Navigator.pop(context);
403
+ } catch (e) {
404
+ if (mounted) setState(() => error = errorText(e));
405
+ } finally {
406
+ if (mounted) setState(() => busy = false);
407
+ }
408
+ }
409
+
410
+ @override
411
+ Widget build(BuildContext context) => SimpleFormPage(
412
+ title: 'تغییر رمز عبور',
413
+ busy: busy,
414
+ error: error,
415
+ action: 'ذخیره رمز جدید',
416
+ onPressed: submit,
417
+ fields: [
418
+ TextField(
419
+ controller: current,
420
+ obscureText: true,
421
+ decoration: const InputDecoration(labelText: 'رمز فعلی')),
422
+ TextField(
423
+ controller: next,
424
+ obscureText: true,
425
+ decoration: const InputDecoration(labelText: 'رمز جدید')),
426
+ TextField(
427
+ controller: confirm,
428
+ obscureText: true,
429
+ decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
430
+ ],
431
+ );
432
+}
433
+
434
+class SimpleFormPage extends StatelessWidget {
435
+ const SimpleFormPage({
436
+ super.key,
437
+ required this.title,
438
+ required this.fields,
439
+ required this.action,
440
+ required this.onPressed,
441
+ this.busy = false,
442
+ this.error,
443
+ });
444
+ final String title;
445
+ final List<Widget> fields;
446
+ final String action;
447
+ final VoidCallback? onPressed;
448
+ final bool busy;
449
+ final String? error;
450
+
451
+ @override
452
+ Widget build(BuildContext context) => Scaffold(
453
+ appBar: AppBar(title: Text(title)),
454
+ body: Center(
455
+ child: ConstrainedBox(
456
+ constraints: const BoxConstraints(maxWidth: 520),
457
+ child: ListView(
458
+ padding: const EdgeInsets.all(24),
459
+ children: [
460
+ for (final field in fields)
461
+ Padding(
462
+ padding: const EdgeInsets.only(bottom: 12), child: field),
463
+ if (error != null)
464
+ Padding(
465
+ padding: const EdgeInsets.only(bottom: 12),
466
+ child: Text(error!,
467
+ style: TextStyle(
468
+ color: Theme.of(context).colorScheme.error)),
469
+ ),
470
+ FilledButton(
471
+ onPressed: busy ? null : onPressed,
472
+ child: Text(busy ? 'لطفاً صبر کن...' : action)),
473
+ ],
474
+ ),
475
+ ),
476
+ ),
477
+ );
478
+}
479
+
480
+class HomeShell extends StatefulWidget {
481
+ const HomeShell({super.key, required this.api});
482
+ final IdentityApi api;
483
+
484
+ @override
485
+ State<HomeShell> createState() => _HomeShellState();
486
+}
487
+
488
+class _HomeShellState extends State<HomeShell> {
489
+ int index = 0;
490
+ String themePreference = 'adult_blue';
491
+ bool adultShell = false;
492
+
493
+ static const studentPages = [
494
+ 'امروز',
495
+ 'برنامه هفتگی',
496
+ 'تقویم',
497
+ 'تکالیف و کارها',
498
+ 'امتحانها و نمرات',
499
+ 'تمرکز',
500
+ 'همراه هوشمند',
501
+ ];
502
+
503
+ static const adultPages = [
504
+ 'امروز',
505
+ 'برنامهریز',
506
+ 'خانواده',
507
+ 'راهنما',
508
+ 'من',
509
+ ];
510
+
511
+ @override
512
+ void initState() {
513
+ super.initState();
514
+ loadContext();
515
+ }
516
+
517
+ Future<void> loadContext() async {
518
+ try {
519
+ final profile = await widget.api.getProfile();
520
+ final families = await widget.api.listFamilies();
521
+ final hasAdultRole = families.any(
522
+ (family) =>
523
+ family['role'] == 'parent_guardian' ||
524
+ family['role'] == 'adult_member',
525
+ );
526
+ if (mounted) {
527
+ setState(() {
528
+ themePreference =
529
+ profile['theme_preference']?.toString() ?? 'adult_blue';
530
+ adultShell = hasAdultRole;
531
+ index = 0;
532
+ });
533
+ }
534
+ } catch (_) {}
535
+ }
536
+
537
+ List<String> get pages => adultShell ? adultPages : studentPages;
538
+
539
+ Color get accent => themePreference == 'girl_pink'
540
+ ? const Color(0xFFE58FB0)
541
+ : const Color(0xFF4D86E8);
542
+
543
+ List<NavigationDestination> get destinations => adultShell
544
+ ? const [
545
+ NavigationDestination(
546
+ icon: Icon(Icons.home_outlined),
547
+ label: 'امروز',
548
+ ),
549
+ NavigationDestination(
550
+ icon: Icon(Icons.event_note_outlined),
551
+ label: 'برنامهریز',
552
+ ),
553
+ NavigationDestination(
554
+ icon: Icon(Icons.family_restroom_outlined),
555
+ label: 'خانواده',
556
+ ),
557
+ NavigationDestination(
558
+ icon: Icon(Icons.assistant_outlined),
559
+ label: 'راهنما',
560
+ ),
561
+ NavigationDestination(
562
+ icon: Icon(Icons.person_outline),
563
+ label: 'من',
564
+ ),
565
+ ]
566
+ : const [
567
+ NavigationDestination(
568
+ icon: Icon(Icons.home_outlined),
569
+ label: 'امروز',
570
+ ),
571
+ NavigationDestination(
572
+ icon: Icon(Icons.schedule_outlined),
573
+ label: 'برنامه',
574
+ ),
575
+ NavigationDestination(
576
+ icon: Icon(Icons.calendar_month_outlined),
577
+ label: 'تقویم',
578
+ ),
579
+ NavigationDestination(
580
+ icon: Icon(Icons.task_alt_outlined),
581
+ label: 'کارها',
582
+ ),
583
+ NavigationDestination(
584
+ icon: Icon(Icons.school_outlined),
585
+ label: 'امتحانها',
586
+ ),
587
+ ];
588
+
589
+ void selectPage(int next) {
590
+ setState(() => index = next);
591
+ }
592
+
593
+ @override
594
+ Widget build(BuildContext context) => Theme(
595
+ data: Theme.of(context).copyWith(
596
+ colorScheme: ColorScheme.fromSeed(seedColor: accent),
597
+ scaffoldBackgroundColor: Colors.white,
598
+ ),
599
+ child: Scaffold(
600
+ appBar: AppBar(
601
+ title: Text(pages[index]),
602
+ actions: [
603
+ IconButton(
604
+ onPressed: () => Navigator.of(context).push(
605
+ MaterialPageRoute(
606
+ builder: (_) => ProfileFamilyPage(api: widget.api),
607
+ ),
608
+ ),
609
+ icon: const Icon(Icons.person_outline),
610
+ ),
611
+ ],
612
+ ),
613
+ body: Center(
614
+ child: Text(
615
+ pages[index],
616
+ style: Theme.of(context).textTheme.headlineMedium,
617
+ ),
618
+ ),
619
+ bottomNavigationBar: NavigationBar(
620
+ selectedIndex: index > 4 ? 0 : index,
621
+ onDestinationSelected: selectPage,
622
+ destinations: destinations,
623
+ ),
624
+ drawer: Drawer(
625
+ child: SafeArea(
626
+ child: ListView(
627
+ children: [
628
+ const ListTile(
629
+ title: Text('LifeMate'),
630
+ subtitle: Text('منوی اصلی'),
631
+ ),
632
+ ...pages.asMap().entries.map(
633
+ (entry) => ListTile(
634
+ title: Text(entry.value),
635
+ onTap: () {
636
+ selectPage(entry.key);
637
+ Navigator.pop(context);
638
+ },
639
+ ),
640
+ ),
641
+ if (!adultShell) ...[
642
+ const Divider(),
643
+ ListTile(
644
+ leading: const Icon(Icons.family_restroom),
645
+ title: const Text('خانواده'),
646
+ onTap: () => Navigator.of(context).push(
647
+ MaterialPageRoute(
648
+ builder: (_) => ProfileFamilyPage(api: widget.api),
649
+ ),
650
+ ),
651
+ ),
652
+ ],
653
+ ],
654
+ ),
655
+ ),
656
+ ),
657
+ ),
658
+ );
659
+}
660
+
661
+class ProfileFamilyPage extends StatefulWidget {
662
+ const ProfileFamilyPage({super.key, required this.api});
663
+ final IdentityApi api;
664
+ @override
665
+ State<ProfileFamilyPage> createState() => _ProfileFamilyPageState();
666
+}
667
+
668
+class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
669
+ late Future<List<dynamic>> data;
670
+ @override
671
+ void initState() {
672
+ super.initState();
673
+ data = load();
674
+ }
675
+
676
+ Future<List<dynamic>> load() async =>
677
+ [await widget.api.getProfile(), await widget.api.listFamilies()];
678
+
679
+ Future<void> editProfile(Map<String, dynamic> profile) async {
680
+ final name = TextEditingController(
681
+ text: profile['display_name']?.toString() ?? '');
682
+ final theme = ValueNotifier<String>(
683
+ profile['theme_preference']?.toString() ?? 'adult_blue');
684
+ final saved = await showDialog<bool>(
685
+ context: context,
686
+ builder: (dialogContext) => AlertDialog(
687
+ title: const Text('ویرایش پروفایل'),
688
+ content: Column(mainAxisSize: MainAxisSize.min, children: [
689
+ TextField(
690
+ controller: name,
691
+ decoration: const InputDecoration(labelText: 'نام')),
692
+ const SizedBox(height: 12),
693
+ ValueListenableBuilder<String>(
694
+ valueListenable: theme,
695
+ builder: (_, value, __) => DropdownButtonFormField<String>(
696
+ initialValue: value,
697
+ decoration: const InputDecoration(labelText: 'تم'),
698
+ items: const [
699
+ DropdownMenuItem(
700
+ value: 'girl_pink', child: Text('سفید / صورتی')),
701
+ DropdownMenuItem(
702
+ value: 'boy_blue', child: Text('سفید / آبی نوجوان')),
703
+ DropdownMenuItem(
704
+ value: 'adult_blue', child: Text('سفید / آبی بزرگسال')),
705
+ ],
706
+ onChanged: (v) {
707
+ if (v != null) theme.value = v;
708
+ },
709
+ ),
710
+ ),
711
+ ]),
712
+ actions: [
713
+ TextButton(
714
+ onPressed: () => Navigator.pop(dialogContext, false),
715
+ child: const Text('انصراف')),
716
+ FilledButton(
717
+ onPressed: () async {
718
+ await widget.api.updateProfile(
719
+ displayName: name.text.trim(),
720
+ themePreference: theme.value);
721
+ if (dialogContext.mounted) Navigator.pop(dialogContext, true);
722
+ },
723
+ child: const Text('ذخیره'),
724
+ ),
725
+ ],
726
+ ),
727
+ );
728
+ name.dispose();
729
+ theme.dispose();
730
+ if (saved == true && mounted) setState(() => data = load());
731
+ }
732
+
733
+ Future<void> createFamily() async {
734
+ final name = TextEditingController();
735
+ final created = await showDialog<bool>(
736
+ context: context,
737
+ builder: (dialogContext) => AlertDialog(
738
+ title: const Text('ساخت فضای خانواده'),
739
+ content: TextField(
740
+ controller: name,
741
+ decoration: const InputDecoration(labelText: 'نام خانواده')),
742
+ actions: [
743
+ TextButton(
744
+ onPressed: () => Navigator.pop(dialogContext, false),
745
+ child: const Text('انصراف')),
746
+ FilledButton(
747
+ onPressed: () async {
748
+ if (name.text.trim().isEmpty) return;
749
+ await widget.api
750
+ .createFamily(name.text.trim(), role: 'parent_guardian');
751
+ if (dialogContext.mounted) Navigator.pop(dialogContext, true);
752
+ },
753
+ child: const Text('ساخت'),
754
+ ),
755
+ ],
756
+ ),
757
+ );
758
+ name.dispose();
759
+ if (created == true && mounted) setState(() => data = load());
760
+ }
761
+
762
+ Future<void> invite(String familyId) async {
763
+ final email = TextEditingController();
764
+ final choice = ValueNotifier<String>('daughter');
765
+ final sent = await showDialog<bool>(
766
+ context: context,
767
+ builder: (dialogContext) => AlertDialog(
768
+ title: const Text('دعوت فرزند / عضو'),
769
+ content: Column(mainAxisSize: MainAxisSize.min, children: [
770
+ TextField(
771
+ controller: email,
772
+ keyboardType: TextInputType.emailAddress,
773
+ decoration: const InputDecoration(labelText: 'ایمیل')),
774
+ const SizedBox(height: 12),
775
+ ValueListenableBuilder<String>(
776
+ valueListenable: choice,
777
+ builder: (_, value, __) => DropdownButtonFormField<String>(
778
+ initialValue: value,
779
+ decoration: const InputDecoration(labelText: 'نوع عضو'),
780
+ items: const [
781
+ DropdownMenuItem(
782
+ value: 'daughter', child: Text('فرزند دختر — سفید / صورتی')),
783
+ DropdownMenuItem(
784
+ value: 'son', child: Text('فرزند پسر — سفید / آبی')),
785
+ DropdownMenuItem(
786
+ value: 'parent', child: Text('والد / سرپرست — سفید / آبی')),
787
+ DropdownMenuItem(
788
+ value: 'adult', child: Text('عضو بزرگسال — سفید / آبی')),
789
+ ],
790
+ onChanged: (v) {
791
+ if (v != null) choice.value = v;
792
+ },
793
+ ),
794
+ ),
795
+ ]),
796
+ actions: [
797
+ TextButton(
798
+ onPressed: () => Navigator.pop(dialogContext, false),
799
+ child: const Text('انصراف')),
800
+ FilledButton(
801
+ onPressed: () async {
802
+ final selected = choice.value;
803
+ final role = selected == 'parent'
804
+ ? 'parent_guardian'
805
+ : selected == 'adult'
806
+ ? 'adult_member'
807
+ : 'teen_minor';
808
+ final theme = selected == 'daughter'
809
+ ? 'girl_pink'
810
+ : selected == 'son'
811
+ ? 'boy_blue'
812
+ : 'adult_blue';
813
+ await widget.api.inviteMember(
814
+ familyId: familyId,
815
+ email: email.text,
816
+ role: role,
817
+ themePreference: theme);
818
+ if (dialogContext.mounted) Navigator.pop(dialogContext, true);
819
+ },
820
+ child: const Text('ارسال دعوت'),
821
+ ),
822
+ ],
823
+ ),
824
+ );
825
+ email.dispose();
826
+ choice.dispose();
827
+ if (sent == true && mounted) {
828
+ ScaffoldMessenger.of(context)
829
+ .showSnackBar(const SnackBar(content: Text('دعوت ارسال شد.')));
830
+ }
831
+ }
832
+
833
+ @override
834
+ Widget build(BuildContext context) => Scaffold(
835
+ appBar: AppBar(title: const Text('پروفایل و خانواده')),
836
+ body: FutureBuilder<List<dynamic>>(
837
+ future: data,
838
+ builder: (context, snapshot) {
839
+ if (snapshot.hasError) {
840
+ return Center(child: Text(errorText(snapshot.error!)));
841
+ }
842
+ if (!snapshot.hasData) {
843
+ return const Center(child: CircularProgressIndicator());
844
+ }
845
+ final profile = snapshot.data![0] as Map<String, dynamic>;
846
+ final families = snapshot.data![1] as List<Map<String, dynamic>>;
847
+ return ListView(
848
+ padding: const EdgeInsets.all(20),
849
+ children: [
850
+ Card(
851
+ child: ListTile(
852
+ leading: const CircleAvatar(child: Icon(Icons.person)),
853
+ title: Text(
854
+ profile['display_name']?.toString() ?? 'پروفایل من'),
855
+ subtitle:
856
+ Text(profile['email_normalized']?.toString() ?? ''),
857
+ trailing: IconButton(
858
+ onPressed: () => editProfile(profile),
859
+ icon: const Icon(Icons.edit_outlined)),
860
+ ),
861
+ ),
862
+ const SizedBox(height: 12),
863
+ if (families.isEmpty)
864
+ Card(
865
+ child: ListTile(
866
+ leading: const Icon(Icons.family_restroom),
867
+ title: const Text('هنوز فضای خانواده ساخته نشده'),
868
+ trailing: IconButton(
869
+ onPressed: createFamily,
870
+ icon: const Icon(Icons.add)),
871
+ ),
872
+ )
873
+ else
874
+ ...families.map((family) => Card(
875
+ child: ListTile(
876
+ leading: const Icon(Icons.family_restroom),
877
+ title:
878
+ Text(family['name']?.toString() ?? 'خانواده'),
879
+ subtitle: Text(
880
+ '${family['is_admin'] == true ? 'مدیر خانواده · ' : ''}${family['role'] ?? ''}'),
881
+ onTap: () => Navigator.of(context).push(
882
+ MaterialPageRoute(
883
+ builder: (_) => FamilyMembersPage(
884
+ api: widget.api,
885
+ familyId: family['id'].toString(),
886
+ familyName:
887
+ family['name']?.toString() ?? 'خانواده',
888
+ isAdmin: family['is_admin'] == true,
889
+ ),
890
+ ),
891
+ ),
892
+ trailing: IconButton(
893
+ onPressed: () => invite(family['id'].toString()),
894
+ icon: const Icon(Icons.person_add_alt)),
895
+ ),
896
+ )),
897
+ ListTile(
898
+ leading: const Icon(Icons.password),
899
+ title: const Text('تغییر رمز عبور'),
900
+ onTap: () => Navigator.of(context).push(MaterialPageRoute(
901
+ builder: (_) => ChangePasswordPage(api: widget.api))),
902
+ ),
903
+ const ListTile(
904
+ leading: Icon(Icons.privacy_tip_outlined),
905
+ title: Text('حریم خصوصی و دسترسیها'),
906
+ subtitle:
907
+ Text('خصوصی، اعضای منتخب، والد/سرپرست، خانواده، ایمنی'),
908
+ ),
909
+ ],
910
+ );
911
+ },
912
+ ),
913
+ floatingActionButton: FloatingActionButton.extended(
914
+ onPressed: createFamily,
915
+ icon: const Icon(Icons.add),
916
+ label: const Text('خانواده')),
917
+ );
918
+}
919
+
920
+class FamilyMembersPage extends StatefulWidget {
921
+ const FamilyMembersPage({
922
+ super.key,
923
+ required this.api,
924
+ required this.familyId,
925
+ required this.familyName,
926
+ required this.isAdmin,
927
+ });
928
+ final IdentityApi api;
929
+ final String familyId;
930
+ final String familyName;
931
+ final bool isAdmin;
932
+ @override
933
+ State<FamilyMembersPage> createState() => _FamilyMembersPageState();
934
+}
935
+
936
+class _FamilyMembersPageState extends State<FamilyMembersPage> {
937
+ late Future<List<Map<String, dynamic>>> members;
938
+ @override
939
+ void initState() {
940
+ super.initState();
941
+ members = widget.api.listFamilyMembers(widget.familyId);
942
+ }
943
+
944
+ String roleLabel(String role) => switch (role) {
945
+ 'parent_guardian' => 'والد / سرپرست',
946
+ 'teen_minor' => 'فرزند / نوجوان',
947
+ 'adult_member' => 'عضو بزرگسال',
948
+ _ => role,
949
+ };
950
+
951
+ Future<void> configureGuardian(List<Map<String, dynamic>> items) async {
952
+ final guardians =
953
+ items.where((m) => m['role'] == 'parent_guardian').toList();
954
+ final minors = items.where((m) => m['role'] == 'teen_minor').toList();
955
+ if (guardians.isEmpty || minors.isEmpty) {
956
+ ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
957
+ content: Text('برای ثبت سرپرستی، حداقل یک والد و یک فرزند لازم است.')));
958
+ return;
959
+ }
960
+ final guardianId =
961
+ ValueNotifier<String>(guardians.first['user_id'].toString());
962
+ final minorId = ValueNotifier<String>(minors.first['user_id'].toString());
963
+ final saved = await showDialog<bool>(
964
+ context: context,
965
+ builder: (dialogContext) => AlertDialog(
966
+ title: const Text('رابطه والد و فرزند'),
967
+ content: Column(mainAxisSize: MainAxisSize.min, children: [
968
+ ValueListenableBuilder<String>(
969
+ valueListenable: guardianId,
970
+ builder: (_, value, __) => DropdownButtonFormField<String>(
971
+ initialValue: value,
972
+ decoration: const InputDecoration(labelText: 'والد / سرپرست'),
973
+ items: guardians
974
+ .map((m) => DropdownMenuItem(
975
+ value: m['user_id'].toString(),
976
+ child: Text(m['display_name']?.toString() ?? 'والد')))
977
+ .toList(),
978
+ onChanged: (v) {
979
+ if (v != null) guardianId.value = v;
980
+ },
981
+ ),
982
+ ),
983
+ const SizedBox(height: 12),
984
+ ValueListenableBuilder<String>(
985
+ valueListenable: minorId,
986
+ builder: (_, value, __) => DropdownButtonFormField<String>(
987
+ initialValue: value,
988
+ decoration: const InputDecoration(labelText: 'فرزند'),
989
+ items: minors
990
+ .map((m) => DropdownMenuItem(
991
+ value: m['user_id'].toString(),
992
+ child: Text(m['display_name']?.toString() ?? 'فرزند')))
993
+ .toList(),
994
+ onChanged: (v) {
995
+ if (v != null) minorId.value = v;
996
+ },
997
+ ),
998
+ ),
999
+ ]),
1000
+ actions: [
1001
+ TextButton(
1002
+ onPressed: () => Navigator.pop(dialogContext, false),
1003
+ child: const Text('انصراف')),
1004
+ FilledButton(
1005
+ onPressed: () async {
1006
+ await widget.api.setGuardian(
1007
+ familyId: widget.familyId,
1008
+ guardianUserId: guardianId.value,
1009
+ minorUserId: minorId.value);
1010
+ if (dialogContext.mounted) Navigator.pop(dialogContext, true);
1011
+ },
1012
+ child: const Text('ثبت رابطه'),
1013
+ ),
1014
+ ],
1015
+ ),
1016
+ );
1017
+ guardianId.dispose();
1018
+ minorId.dispose();
1019
+ if (saved == true && mounted) {
1020
+ ScaffoldMessenger.of(context).showSnackBar(
1021
+ const SnackBar(content: Text('رابطه سرپرستی ثبت شد.')));
1022
+ }
1023
+ }
1024
+
1025
+ @override
1026
+ Widget build(BuildContext context) => Scaffold(
1027
+ appBar: AppBar(title: Text(widget.familyName)),
1028
+ body: FutureBuilder<List<Map<String, dynamic>>>(
1029
+ future: members,
1030
+ builder: (context, snapshot) {
1031
+ if (snapshot.hasError) {
1032
+ return Center(child: Text(errorText(snapshot.error!)));
1033
+ }
1034
+ if (!snapshot.hasData) {
1035
+ return const Center(child: CircularProgressIndicator());
1036
+ }
1037
+ final items = snapshot.data!;
1038
+ return ListView(
1039
+ padding: const EdgeInsets.all(20),
1040
+ children: [
1041
+ for (final member in items)
1042
+ Card(
1043
+ child: ListTile(
1044
+ leading: const CircleAvatar(child: Icon(Icons.person)),
1045
+ title:
1046
+ Text(member['display_name']?.toString() ?? 'عضو'),
1047
+ subtitle:
1048
+ Text(roleLabel(member['role']?.toString() ?? '')),
1049
+ trailing: member['is_admin'] == true
1050
+ ? const Chip(label: Text('مدیر'))
1051
+ : null,
1052
+ ),
1053
+ ),
1054
+ if (widget.isAdmin) ...[
1055
+ const SizedBox(height: 12),
1056
+ FilledButton.icon(
1057
+ onPressed: () => configureGuardian(items),
1058
+ icon: const Icon(Icons.supervisor_account_outlined),
1059
+ label: const Text('تنظیم رابطه والد و فرزند'),
1060
+ ),
1061
+ ],
1062
+ ],
1063
+ );
1064
+ },
1065
+ ),
1066
+ );
1067
+}
apps/lifemate/pubspec.yaml
new
+19
@@ -0,0 +1,19 @@
1
+name: lifemate
2
+version: 0.1.0+1
3
+publish_to: none
4
+description: LifeMate personal, family and learning companion.
5
+environment:
6
+ sdk: '>=3.4.0 <4.0.0'
7
+dependencies:
8
+ flutter:
9
+ sdk: flutter
10
+ flutter_localizations:
11
+ sdk: flutter
12
+ intl: ^0.20.2
13
+ http: ^1.5.0
14
+dev_dependencies:
15
+ flutter_test:
16
+ sdk: flutter
17
+ flutter_lints: ^6.0.0
18
+flutter:
19
+ uses-material-design: true
apps/lifemate/test/app_test.dart
new
+180
@@ -0,0 +1,180 @@
1
+import 'package:flutter/material.dart';
2
+import 'package:flutter_test/flutter_test.dart';
3
+import 'package:lifemate/api.dart';
4
+import 'package:lifemate/main.dart';
5
+
6
+class FakeApi implements IdentityApi {
7
+ FakeApi({
8
+ this.role = 'teen_minor',
9
+ this.themePreference = 'girl_pink',
10
+ });
11
+
12
+ final String role;
13
+ final String themePreference;
14
+
15
+ @override
16
+ String? accessToken;
17
+
18
+ @override
19
+ Future<void> login(String email, String password) async {
20
+ accessToken = 'test-token';
21
+ }
22
+
23
+ @override
24
+ Future<void> register({
25
+ required String displayName,
26
+ required String email,
27
+ required String password,
28
+ }) async {}
29
+
30
+ @override
31
+ Future<void> verifyEmail(String token) async {}
32
+
33
+ @override
34
+ Future<void> forgotPassword(String email) async {}
35
+
36
+ @override
37
+ Future<void> resetPassword(String token, String newPassword) async {}
38
+
39
+ @override
40
+ Future<void> changePassword(
41
+ String currentPassword,
42
+ String newPassword,
43
+ ) async {}
44
+
45
+ @override
46
+ Future<Map<String, dynamic>> getProfile() async => {
47
+ 'display_name': role == 'teen_minor' ? 'آرام' : 'والد',
48
+ 'email_normalized': 'user@example.test',
49
+ 'theme_preference': themePreference,
50
+ };
51
+
52
+ @override
53
+ Future<Map<String, dynamic>> updateProfile({
54
+ String? displayName,
55
+ String? birthDate,
56
+ String? themePreference,
57
+ }) async =>
58
+ {
59
+ 'display_name': displayName ?? 'والد',
60
+ 'theme_preference': themePreference ?? 'adult_blue',
61
+ };
62
+
63
+ @override
64
+ Future<List<Map<String, dynamic>>> listFamilies() async => [
65
+ {
66
+ 'id': 'family-1',
67
+ 'name': 'خانواده',
68
+ 'role': role,
69
+ 'is_admin': role == 'parent_guardian',
70
+ }
71
+ ];
72
+
73
+ @override
74
+ Future<List<Map<String, dynamic>>> listFamilyMembers(String familyId) async =>
75
+ [];
76
+
77
+ @override
78
+ Future<Map<String, dynamic>> createFamily(
79
+ String name, {
80
+ String? role,
81
+ }) async =>
82
+ {'id': 'family-1', 'name': name};
83
+
84
+ @override
85
+ Future<void> inviteMember({
86
+ required String familyId,
87
+ required String email,
88
+ required String role,
89
+ String? themePreference,
90
+ }) async {}
91
+
92
+ @override
93
+ Future<void> acceptInvitation(String token) async {}
94
+
95
+ @override
96
+ Future<void> setGuardian({
97
+ required String familyId,
98
+ required String guardianUserId,
99
+ required String minorUserId,
100
+ }) async {}
101
+}
102
+
103
+void main() {
104
+ testWidgets('starts in Persian RTL with identity actions', (tester) async {
105
+ await tester.pumpWidget(LifeMateApp(api: FakeApi()));
106
+
107
+ expect(find.text('LifeMate'), findsOneWidget);
108
+ expect(find.text('ورود'), findsOneWidget);
109
+ expect(find.text('رمز عبور را فراموش کردهام'), findsOneWidget);
110
+
111
+ final directionality =
112
+ tester.widget<Directionality>(find.byType(Directionality).last);
113
+ expect(directionality.textDirection, TextDirection.rtl);
114
+ });
115
+
116
+ testWidgets('opens recovery flow', (tester) async {
117
+ await tester.pumpWidget(LifeMateApp(api: FakeApi()));
118
+
119
+ await tester.tap(find.text('رمز عبور را فراموش کردهام'));
120
+ await tester.pumpAndSettle();
121
+
122
+ expect(find.text('بازیابی رمز عبور'), findsOneWidget);
123
+ expect(find.text('ارسال لینک بازیابی'), findsOneWidget);
124
+ });
125
+
126
+ testWidgets('teen login opens MyStudyLife-inspired student shell',
127
+ (tester) async {
128
+ await tester.pumpWidget(
129
+ LifeMateApp(
130
+ api: FakeApi(role: 'teen_minor', themePreference: 'girl_pink'),
131
+ ),
132
+ );
133
+
134
+ await tester.enterText(
135
+ find.widgetWithText(TextField, 'ایمیل'),
136
+ 'parent@example.test',
137
+ );
138
+ await tester.enterText(
139
+ find.widgetWithText(TextField, 'رمز عبور'),
140
+ 'StrongPass!123',
141
+ );
142
+ await tester.tap(find.text('ورود'));
143
+ await tester.pumpAndSettle();
144
+
145
+ expect(find.text('امروز'), findsWidgets);
146
+ expect(find.text('برنامه'), findsOneWidget);
147
+ expect(find.text('تقویم'), findsOneWidget);
148
+ expect(find.text('کارها'), findsOneWidget);
149
+ expect(find.text('امتحانها'), findsOneWidget);
150
+ });
151
+
152
+ testWidgets('parent login opens parent-focused family shell', (tester) async {
153
+ await tester.pumpWidget(
154
+ LifeMateApp(
155
+ api: FakeApi(
156
+ role: 'parent_guardian',
157
+ themePreference: 'adult_blue',
158
+ ),
159
+ ),
160
+ );
161
+
162
+ await tester.enterText(
163
+ find.widgetWithText(TextField, 'ایمیل'),
164
+ 'parent@example.test',
165
+ );
166
+ await tester.enterText(
167
+ find.widgetWithText(TextField, 'رمز عبور'),
168
+ 'StrongPass!123',
169
+ );
170
+ await tester.tap(find.text('ورود'));
171
+ await tester.pumpAndSettle();
172
+
173
+ expect(find.text('امروز'), findsWidgets);
174
+ expect(find.text('برنامهریز'), findsOneWidget);
175
+ expect(find.text('خانواده'), findsOneWidget);
176
+ expect(find.text('راهنما'), findsOneWidget);
177
+ expect(find.text('من'), findsOneWidget);
178
+ expect(find.text('امتحانها'), findsNothing);
179
+ });
180
+}
apps/lifemate/web/favicon.png
Binary files /dev/null and b/apps/lifemate/web/favicon.png differ
apps/lifemate/web/icons/Icon-192.png
Binary files /dev/null and b/apps/lifemate/web/icons/Icon-192.png differ
apps/lifemate/web/icons/Icon-512.png
Binary files /dev/null and b/apps/lifemate/web/icons/Icon-512.png differ
apps/lifemate/web/icons/Icon-maskable-192.png
Binary files /dev/null and b/apps/lifemate/web/icons/Icon-maskable-192.png differ
apps/lifemate/web/icons/Icon-maskable-512.png
Binary files /dev/null and b/apps/lifemate/web/icons/Icon-maskable-512.png differ
apps/lifemate/web/index.html
new
+46
@@ -0,0 +1,46 @@
1
+<!DOCTYPE html>
2
+<html>
3
+<head>
4
+ <!--
5
+ If you are serving your web app in a path other than the root, change the
6
+ href value below to reflect the base path you are serving from.
7
+
8
+ The path provided below has to start and end with a slash "/" in order for
9
+ it to work correctly.
10
+
11
+ For more details:
12
+ * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
13
+
14
+ This is a placeholder for base href that will be replaced by the value of
15
+ the `--base-href` argument provided to `flutter build`.
16
+ -->
17
+ <base href="$FLUTTER_BASE_HREF">
18
+
19
+ <meta charset="UTF-8">
20
+ <meta content="IE=Edge" http-equiv="X-UA-Compatible">
21
+ <meta name="description" content="LifeMate — همراه شخصی، تحصیلی و خانوادگی">
22
+
23
+ <!-- iOS meta tags & icons -->
24
+ <meta name="mobile-web-app-capable" content="yes">
25
+ <meta name="apple-mobile-web-app-status-bar-style" content="default">
26
+ <meta name="apple-mobile-web-app-title" content="LifeMate">
27
+ <link rel="apple-touch-icon" href="icons/Icon-192.png">
28
+
29
+ <!-- Favicon -->
30
+ <link rel="icon" type="image/png" href="favicon.png"/>
31
+
32
+ <title>LifeMate</title>
33
+ <link rel="manifest" href="manifest.json">
34
+</head>
35
+<body>
36
+ <!--
37
+ You can customize the "flutter_bootstrap.js" script.
38
+ This is useful to provide a custom configuration to the Flutter loader
39
+ or to give the user feedback during the initialization process.
40
+
41
+ For more details:
42
+ * https://docs.flutter.dev/platform-integration/web/initialization
43
+ -->
44
+ <script src="flutter_bootstrap.js" async></script>
45
+</body>
46
+</html>
apps/lifemate/web/manifest.json
new
+38
@@ -0,0 +1,38 @@
1
+{
2
+ "name": "LifeMate",
3
+ "short_name": "LifeMate",
4
+ "start_url": "/",
5
+ "scope": "/",
6
+ "display": "standalone",
7
+ "background_color": "#F8FAFD",
8
+ "theme_color": "#4D86E8",
9
+ "description": "همراه شخصی، تحصیلی و خانوادگی",
10
+ "orientation": "portrait-primary",
11
+ "dir": "rtl",
12
+ "lang": "fa",
13
+ "prefer_related_applications": false,
14
+ "icons": [
15
+ {
16
+ "src": "icons/Icon-192.png",
17
+ "sizes": "192x192",
18
+ "type": "image/png"
19
+ },
20
+ {
21
+ "src": "icons/Icon-512.png",
22
+ "sizes": "512x512",
23
+ "type": "image/png"
24
+ },
25
+ {
26
+ "src": "icons/Icon-maskable-192.png",
27
+ "sizes": "192x192",
28
+ "type": "image/png",
29
+ "purpose": "maskable"
30
+ },
31
+ {
32
+ "src": "icons/Icon-maskable-512.png",
33
+ "sizes": "512x512",
34
+ "type": "image/png",
35
+ "purpose": "maskable"
36
+ }
37
+ ]
38
+}
backend/README.md
new
+20
@@ -0,0 +1,20 @@
1
+# LifeMate backend contract
2
+
3
+Phase 2 keeps infrastructure provider-neutral.
4
+
5
+## IdentityProvider
6
+Required operations: register(email,password), verifyEmail(token), signIn(email,password), requestPasswordReset(email), resetPassword(token,newPassword), changePassword(session,currentPassword,newPassword), revokeSession(session).
7
+
8
+Security requirements: normalized email; non-enumerating recovery response; single-use/time-limited verification and reset tokens stored as digests; modern password hashing in the identity adapter; session rotation/revocation; rate limiting; audit sensitive changes.
9
+
10
+## LifeMate API authorization
11
+Every request resolves an authenticated `app_user`. Family operations evaluate active membership and explicit guardian relationships server-side. `owner_admin` is administrative authority and never grants blanket access to private teen content. Safety-controlled access is a separate audited policy path.
12
+
13
+## Invitation
14
+Invitation token is random, time-limited and stored only as a digest. Acceptance requires authenticated email match (or an explicitly audited admin correction flow), active pending status and expiry validation. Membership is created transactionally with invitation acceptance.
15
+
16
+## PostgreSQL
17
+`migrations/` contains portable schema migrations. Database helper functions/constraints are defense in depth. Clients never connect with database-owner credentials.
18
+
19
+## Staging
20
+CI exercises migrations/tests against an isolated PostgreSQL service. Persistent managed staging is attached separately and must use its own credentials/data before Phase 2 is declared complete.
backend/migrations/0001_identity_family.sql
new
+125
@@ -0,0 +1,125 @@
1
+begin;
2
+
3
+create extension if not exists pgcrypto;
4
+
5
+create type member_role as enum ('parent_guardian','teen_minor','adult_member');
6
+create type invitation_status as enum ('pending','accepted','revoked','expired');
7
+create type visibility_scope as enum ('private','selected_members','parent_guardian','family','safety_controlled');
8
+
9
+create table app_user (
10
+ id uuid primary key default gen_random_uuid(),
11
+ identity_subject text not null unique,
12
+ email_normalized text not null unique check (email_normalized = lower(email_normalized)),
13
+ email_verified_at timestamptz,
14
+ created_at timestamptz not null default now(),
15
+ disabled_at timestamptz
16
+);
17
+
18
+create table profile (
19
+ user_id uuid primary key references app_user(id) on delete cascade,
20
+ display_name text not null check (char_length(display_name) between 1 and 100),
21
+ birth_date date,
22
+ theme_preference text check (theme_preference in ('girl_pink','boy_blue','adult_blue','custom')),
23
+ updated_at timestamptz not null default now()
24
+);
25
+
26
+create table family_workspace (
27
+ id uuid primary key default gen_random_uuid(),
28
+ name text not null check (char_length(name) between 1 and 120),
29
+ created_by uuid not null references app_user(id),
30
+ created_at timestamptz not null default now(),
31
+ archived_at timestamptz
32
+);
33
+
34
+create table family_membership (
35
+ family_id uuid not null references family_workspace(id) on delete cascade,
36
+ user_id uuid not null references app_user(id) on delete cascade,
37
+ role member_role not null,
38
+ is_admin boolean not null default false,
39
+ joined_at timestamptz not null default now(),
40
+ ended_at timestamptz,
41
+ primary key (family_id, user_id)
42
+);
43
+
44
+create table guardian_relationship (
45
+ family_id uuid not null,
46
+ guardian_user_id uuid not null,
47
+ minor_user_id uuid not null,
48
+ active boolean not null default true,
49
+ created_at timestamptz not null default now(),
50
+ primary key (family_id, guardian_user_id, minor_user_id),
51
+ foreign key (family_id, guardian_user_id) references family_membership(family_id, user_id) on delete cascade,
52
+ foreign key (family_id, minor_user_id) references family_membership(family_id, user_id) on delete cascade,
53
+ check (guardian_user_id <> minor_user_id)
54
+);
55
+
56
+create table family_invitation (
57
+ id uuid primary key default gen_random_uuid(),
58
+ family_id uuid not null references family_workspace(id) on delete cascade,
59
+ invited_email_normalized text not null check (invited_email_normalized = lower(invited_email_normalized)),
60
+ intended_role member_role not null,
61
+ intended_theme text check (intended_theme in ('girl_pink','boy_blue','adult_blue','custom')),
62
+ token_digest text not null unique,
63
+ status invitation_status not null default 'pending',
64
+ invited_by uuid not null references app_user(id),
65
+ expires_at timestamptz not null,
66
+ accepted_by uuid references app_user(id),
67
+ created_at timestamptz not null default now(),
68
+ accepted_at timestamptz,
69
+ check (expires_at > created_at)
70
+);
71
+
72
+create table access_audit (
73
+ id bigint generated always as identity primary key,
74
+ actor_user_id uuid references app_user(id),
75
+ family_id uuid references family_workspace(id),
76
+ action text not null,
77
+ target_type text not null,
78
+ target_id text,
79
+ occurred_at timestamptz not null default now(),
80
+ metadata jsonb not null default '{}'::jsonb
81
+);
82
+
83
+create index family_membership_user_idx on family_membership(user_id) where ended_at is null;
84
+create index family_membership_admin_idx on family_membership(family_id, is_admin) where ended_at is null and is_admin;
85
+create index family_invitation_pending_idx on family_invitation(family_id, invited_email_normalized) where status = 'pending';
86
+create index access_audit_family_time_idx on access_audit(family_id, occurred_at desc);
87
+
88
+create function is_active_family_member(p_family uuid, p_user uuid) returns boolean
89
+language sql stable as $$
90
+ select exists(
91
+ select 1 from family_membership m
92
+ where m.family_id=p_family and m.user_id=p_user and m.ended_at is null
93
+ )
94
+$$;
95
+
96
+create function is_family_admin(p_family uuid, p_user uuid) returns boolean
97
+language sql stable as $$
98
+ select exists(
99
+ select 1 from family_membership m
100
+ where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and m.is_admin
101
+ )
102
+$$;
103
+
104
+create function is_active_guardian(p_family uuid, p_guardian uuid, p_minor uuid) returns boolean
105
+language sql stable as $$
106
+ select exists(
107
+ select 1 from guardian_relationship g
108
+ join family_membership gm
109
+ on gm.family_id=g.family_id
110
+ and gm.user_id=g.guardian_user_id
111
+ and gm.ended_at is null
112
+ and gm.role='parent_guardian'
113
+ join family_membership mm
114
+ on mm.family_id=g.family_id
115
+ and mm.user_id=g.minor_user_id
116
+ and mm.ended_at is null
117
+ and mm.role='teen_minor'
118
+ where g.family_id=p_family
119
+ and g.guardian_user_id=p_guardian
120
+ and g.minor_user_id=p_minor
121
+ and g.active
122
+ )
123
+$$;
124
+
125
+commit;
backend/migrations/0002_auth.sql
new
+35
@@ -0,0 +1,35 @@
1
+begin;
2
+
3
+create table auth_credential (
4
+ user_id uuid primary key references app_user(id) on delete cascade,
5
+ password_hash text not null,
6
+ password_changed_at timestamptz not null default now(),
7
+ failed_attempts integer not null default 0 check (failed_attempts >= 0),
8
+ locked_until timestamptz
9
+);
10
+
11
+create type auth_token_kind as enum ('email_verification','password_reset');
12
+create table auth_token (
13
+ id uuid primary key default gen_random_uuid(),
14
+ user_id uuid not null references app_user(id) on delete cascade,
15
+ kind auth_token_kind not null,
16
+ token_digest text not null unique,
17
+ expires_at timestamptz not null,
18
+ used_at timestamptz,
19
+ created_at timestamptz not null default now(),
20
+ check (expires_at > created_at)
21
+);
22
+create index auth_token_active_idx on auth_token(user_id, kind, expires_at) where used_at is null;
23
+
24
+create table auth_session (
25
+ id uuid primary key default gen_random_uuid(),
26
+ user_id uuid not null references app_user(id) on delete cascade,
27
+ refresh_digest text not null unique,
28
+ expires_at timestamptz not null,
29
+ revoked_at timestamptz,
30
+ created_at timestamptz not null default now(),
31
+ last_seen_at timestamptz not null default now()
32
+);
33
+create index auth_session_user_active_idx on auth_session(user_id, expires_at) where revoked_at is null;
34
+
35
+commit;
backend/package.json
new
+23
@@ -0,0 +1,23 @@
1
+{
2
+ "name": "lifemate-backend",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "start": "node src/server.js",
8
+ "test": "node --test tests/*.test.js",
9
+ "migrate": "node scripts/migrate.js",
10
+ "check": "node --check src/server.js"
11
+ },
12
+ "engines": {
13
+ "node": ">=22"
14
+ },
15
+ "dependencies": {
16
+ "argon2": "^0.44.0",
17
+ "express": "^5.1.0",
18
+ "jsonwebtoken": "^9.0.2",
19
+ "pg": "^8.16.3",
20
+ "nodemailer": "^10.0.14",
21
+ "cors": "^2.8.5"
22
+ }
23
+}
backend/scripts/migrate.js
new
+52
@@ -0,0 +1,52 @@
1
+import fs from 'node:fs/promises';
2
+import path from 'node:path';
3
+import pg from 'pg';
4
+
5
+const { Client } = pg;
6
+const databaseUrl = process.env.DATABASE_URL;
7
+if (!databaseUrl) throw new Error('DATABASE_URL is required');
8
+
9
+const client = new Client({
10
+ connectionString: databaseUrl,
11
+ ssl: databaseUrl.includes('localhost') ? false : { rejectUnauthorized: false },
12
+});
13
+
14
+await client.connect();
15
+try {
16
+ await client.query(`
17
+ create table if not exists schema_migration (
18
+ filename text primary key,
19
+ applied_at timestamptz not null default now()
20
+ )
21
+ `);
22
+
23
+ const dir = path.resolve('migrations');
24
+ const files = (await fs.readdir(dir))
25
+ .filter((name) => /^\d+_.*\.sql$/.test(name))
26
+ .sort();
27
+
28
+ for (const filename of files) {
29
+ const exists = await client.query(
30
+ 'select 1 from schema_migration where filename=$1',
31
+ [filename],
32
+ );
33
+ if (exists.rowCount) continue;
34
+
35
+ const sql = await fs.readFile(path.join(dir, filename), 'utf8');
36
+ await client.query('begin');
37
+ try {
38
+ await client.query(sql);
39
+ await client.query(
40
+ 'insert into schema_migration(filename) values($1)',
41
+ [filename],
42
+ );
43
+ await client.query('commit');
44
+ console.log('applied', filename);
45
+ } catch (error) {
46
+ await client.query('rollback');
47
+ throw error;
48
+ }
49
+ }
50
+} finally {
51
+ await client.end();
52
+}
backend/src/server.js
new
+616
@@ -0,0 +1,616 @@
1
+import crypto from 'node:crypto';
2
+import express from 'express';
3
+import argon2 from 'argon2';
4
+import jwt from 'jsonwebtoken';
5
+import pg from 'pg';
6
+import nodemailer from 'nodemailer';
7
+import cors from 'cors';
8
+
9
+const { Pool } = pg;
10
+const app = express();
11
+const allowedOrigins = (process.env.CORS_ORIGINS ?? '')
12
+ .split(',')
13
+ .map((value) => value.trim())
14
+ .filter(Boolean);
15
+app.use(
16
+ cors({
17
+ origin(origin, callback) {
18
+ if (!origin || testMode || allowedOrigins.includes(origin)) {
19
+ return callback(null, true);
20
+ }
21
+ return callback(new Error('cors_origin_denied'));
22
+ },
23
+ methods: ['GET', 'POST', 'PATCH', 'OPTIONS'],
24
+ allowedHeaders: ['Content-Type', 'Authorization'],
25
+ maxAge: 86400,
26
+ }),
27
+);
28
+app.use(express.json({ limit: '64kb' }));
29
+
30
+const pool = new Pool({ connectionString: process.env.DATABASE_URL });
31
+const jwtSecret = process.env.JWT_SECRET;
32
+if (!jwtSecret || jwtSecret.length < 32) throw new Error('JWT_SECRET must be at least 32 characters');
33
+
34
+const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
35
+const randomToken = () => crypto.randomBytes(32).toString('base64url');
36
+const normalizeEmail = (email) => String(email ?? '').trim().toLowerCase();
37
+const validPassword = (p) => typeof p === 'string' && p.length >= 10 && p.length <= 200;
38
+const isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
39
+const testMode = process.env.NODE_ENV === 'test';
40
+
41
+async function sendTransactionalEmail({ to, subject, text }) {
42
+ if (testMode) return { delivered: false, testMode: true };
43
+
44
+ const from = process.env.EMAIL_FROM;
45
+ if (!from) return { delivered: false, reason: 'provider_not_configured' };
46
+
47
+ const apiKey = process.env.RESEND_API_KEY;
48
+ if (apiKey) {
49
+ const response = await fetch('https://api.resend.com/emails', {
50
+ method: 'POST',
51
+ headers: {
52
+ Authorization: `Bearer ${apiKey}`,
53
+ 'Content-Type': 'application/json',
54
+ },
55
+ body: JSON.stringify({ from, to: [to], subject, text }),
56
+ });
57
+ if (!response.ok) throw new Error(`email_delivery_failed:${response.status}`);
58
+ return { delivered: true, provider: 'resend' };
59
+ }
60
+
61
+ const smtpHost = process.env.SMTP_HOST;
62
+ const smtpPort = Number(process.env.SMTP_PORT ?? 0);
63
+ if (smtpHost && smtpPort > 0) {
64
+ const transporter = nodemailer.createTransport({
65
+ host: smtpHost,
66
+ port: smtpPort,
67
+ secure: process.env.SMTP_SECURE === 'true',
68
+ auth: process.env.SMTP_USER
69
+ ? {
70
+ user: process.env.SMTP_USER,
71
+ pass: process.env.SMTP_PASSWORD,
72
+ }
73
+ : undefined,
74
+ });
75
+ await transporter.sendMail({ from, to, subject, text });
76
+ return { delivered: true, provider: 'smtp' };
77
+ }
78
+
79
+ return { delivered: false, reason: 'provider_not_configured' };
80
+}
81
+
82
+const issueAccess = (userId, sessionId) =>
83
+ jwt.sign(
84
+ { sub: userId, sid: sessionId, aud: 'lifemate-api' },
85
+ jwtSecret,
86
+ { expiresIn: '15m', issuer: 'lifemate' },
87
+ );
88
+
89
+async function auth(req, res, next) {
90
+ const raw = req.headers.authorization?.replace(/^Bearer\s+/i, '');
91
+ try {
92
+ const identity = jwt.verify(raw, jwtSecret, {
93
+ audience: 'lifemate-api',
94
+ issuer: 'lifemate',
95
+ });
96
+ const session = await pool.query(
97
+ 'select 1 from auth_session where id=$1 and user_id=$2 and revoked_at is null and expires_at>now()',
98
+ [identity.sid, identity.sub],
99
+ );
100
+ if (!session.rowCount) return res.status(401).json({ error: 'session_invalid' });
101
+ req.identity = identity;
102
+ next();
103
+ } catch {
104
+ res.status(401).json({ error: 'unauthorized' });
105
+ }
106
+}
107
+
108
+async function createOneTimeToken(client, userId, kind, minutes) {
109
+ const raw = randomToken();
110
+ await client.query(
111
+ "insert into auth_token(user_id,kind,token_digest,expires_at) values($1,$2,$3,now()+($4 || ' minutes')::interval)",
112
+ [userId, kind, sha256(raw), String(minutes)],
113
+ );
114
+ return raw;
115
+}
116
+
117
+async function createSession(client, userId) {
118
+ const refreshToken = randomToken();
119
+ const r = await client.query(
120
+ "insert into auth_session(user_id,refresh_digest,expires_at) values($1,$2,now()+interval '30 days') returning id",
121
+ [userId, sha256(refreshToken)],
122
+ );
123
+ return {
124
+ accessToken: issueAccess(userId, r.rows[0].id),
125
+ refreshToken,
126
+ };
127
+}
128
+
129
+async function familyAccess(familyId, userId, { roles = [], admin = false } = {}) {
130
+ const r = await pool.query(
131
+ 'select role,is_admin from family_membership where family_id=$1 and user_id=$2 and ended_at is null',
132
+ [familyId, userId],
133
+ );
134
+ if (!r.rowCount) return false;
135
+ return (admin && r.rows[0].is_admin) || roles.includes(r.rows[0].role);
136
+}
137
+
138
+app.get('/health', async (_req, res) => {
139
+ const r = await pool.query('select 1 as ok');
140
+ res.json({
141
+ status: r.rows[0].ok === 1 ? 'ok' : 'degraded',
142
+ emailProviderConfigured: Boolean(process.env.EMAIL_FROM && (process.env.RESEND_API_KEY || (process.env.SMTP_HOST && process.env.SMTP_PORT))),
143
+ });
144
+});
145
+
146
+app.post('/v1/auth/register', async (req, res) => {
147
+ const email = normalizeEmail(req.body.email);
148
+ const password = req.body.password;
149
+ const name = String(req.body.displayName ?? '').trim();
150
+ if (!isEmail(email) || !validPassword(password) || !name) {
151
+ return res.status(400).json({ error: 'invalid_input' });
152
+ }
153
+
154
+ const client = await pool.connect();
155
+ try {
156
+ await client.query('begin');
157
+ const hash = await argon2.hash(password, { type: argon2.argon2id });
158
+ const u = await client.query(
159
+ 'insert into app_user(identity_subject,email_normalized) values($1,$2) returning id',
160
+ [`local:${crypto.randomUUID()}`, email],
161
+ );
162
+ await client.query(
163
+ "insert into profile(user_id,display_name,theme_preference) values($1,$2,'adult_blue')",
164
+ [u.rows[0].id, name],
165
+ );
166
+ await client.query(
167
+ 'insert into auth_credential(user_id,password_hash) values($1,$2)',
168
+ [u.rows[0].id, hash],
169
+ );
170
+ const verificationToken = await createOneTimeToken(
171
+ client,
172
+ u.rows[0].id,
173
+ 'email_verification',
174
+ 60 * 24,
175
+ );
176
+ await client.query('commit');
177
+
178
+ const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid';
179
+ const delivery = await sendTransactionalEmail({
180
+ to: email,
181
+ subject: 'تأیید حساب LifeMate',
182
+ text: `برای تأیید حساب LifeMate این لینک را باز کنید: ${baseUrl}/verify-email?token=${encodeURIComponent(verificationToken)}`,
183
+ });
184
+
185
+ res.status(201).json({
186
+ userId: u.rows[0].id,
187
+ verificationToken: testMode ? verificationToken : undefined,
188
+ emailDelivery: delivery.delivered ? 'sent' : 'pending_configuration',
189
+ });
190
+ } catch (e) {
191
+ await client.query('rollback').catch(() => {});
192
+ if (e.code === '23505') return res.status(409).json({ error: 'account_exists' });
193
+ throw e;
194
+ } finally {
195
+ client.release();
196
+ }
197
+});
198
+
199
+app.post('/v1/auth/verify-email', async (req, res) => {
200
+ const digest = sha256(String(req.body.token ?? ''));
201
+ const client = await pool.connect();
202
+ try {
203
+ await client.query('begin');
204
+ const r = await client.query(
205
+ "select user_id from auth_token where kind='email_verification' and token_digest=$1 and used_at is null and expires_at>now() for update",
206
+ [digest],
207
+ );
208
+ if (!r.rowCount) {
209
+ await client.query('rollback');
210
+ return res.status(400).json({ error: 'invalid_or_expired_token' });
211
+ }
212
+ await client.query('update auth_token set used_at=now() where token_digest=$1', [digest]);
213
+ await client.query(
214
+ 'update app_user set email_verified_at=coalesce(email_verified_at,now()) where id=$1',
215
+ [r.rows[0].user_id],
216
+ );
217
+ await client.query('commit');
218
+ res.status(204).end();
219
+ } finally {
220
+ client.release();
221
+ }
222
+});
223
+
224
+app.post('/v1/auth/login', async (req, res) => {
225
+ const email = normalizeEmail(req.body.email);
226
+ const password = String(req.body.password ?? '');
227
+ const r = await pool.query(
228
+ 'select u.id,u.email_verified_at,c.password_hash from app_user u join auth_credential c on c.user_id=u.id where u.email_normalized=$1 and u.disabled_at is null',
229
+ [email],
230
+ );
231
+ if (!r.rowCount || !(await argon2.verify(r.rows[0].password_hash, password))) {
232
+ return res.status(401).json({ error: 'invalid_credentials' });
233
+ }
234
+ if (!r.rows[0].email_verified_at) {
235
+ return res.status(403).json({ error: 'email_not_verified' });
236
+ }
237
+
238
+ const client = await pool.connect();
239
+ try {
240
+ const tokens = await createSession(client, r.rows[0].id);
241
+ res.json(tokens);
242
+ } finally {
243
+ client.release();
244
+ }
245
+});
246
+
247
+app.post('/v1/auth/refresh', async (req, res) => {
248
+ const digest = sha256(String(req.body.refreshToken ?? ''));
249
+ const client = await pool.connect();
250
+ try {
251
+ await client.query('begin');
252
+ const r = await client.query(
253
+ 'select id,user_id from auth_session where refresh_digest=$1 and revoked_at is null and expires_at>now() for update',
254
+ [digest],
255
+ );
256
+ if (!r.rowCount) {
257
+ await client.query('rollback');
258
+ return res.status(401).json({ error: 'invalid_refresh_token' });
259
+ }
260
+
261
+ await client.query('update auth_session set revoked_at=now() where id=$1', [r.rows[0].id]);
262
+ const tokens = await createSession(client, r.rows[0].user_id);
263
+ await client.query('commit');
264
+ res.json(tokens);
265
+ } finally {
266
+ client.release();
267
+ }
268
+});
269
+
270
+app.post('/v1/auth/forgot-password', async (req, res) => {
271
+ const email = normalizeEmail(req.body.email);
272
+ const r = await pool.query(
273
+ 'select id from app_user where email_normalized=$1 and disabled_at is null',
274
+ [email],
275
+ );
276
+
277
+ let resetToken;
278
+ if (r.rowCount) {
279
+ const c = await pool.connect();
280
+ try {
281
+ resetToken = await createOneTimeToken(c, r.rows[0].id, 'password_reset', 30);
282
+ } finally {
283
+ c.release();
284
+ }
285
+ const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid';
286
+ await sendTransactionalEmail({
287
+ to: email,
288
+ subject: 'بازیابی رمز عبور LifeMate',
289
+ text: `برای ساخت رمز جدید این لینک را باز کنید: ${baseUrl}/reset-password?token=${encodeURIComponent(resetToken)}`,
290
+ });
291
+ }
292
+
293
+ res.json({
294
+ accepted: true,
295
+ resetToken: testMode ? resetToken : undefined,
296
+ });
297
+});
298
+
299
+app.post('/v1/auth/reset-password', async (req, res) => {
300
+ if (!validPassword(req.body.newPassword)) {
301
+ return res.status(400).json({ error: 'invalid_password' });
302
+ }
303
+
304
+ const digest = sha256(String(req.body.token ?? ''));
305
+ const client = await pool.connect();
306
+ try {
307
+ await client.query('begin');
308
+ const r = await client.query(
309
+ "select user_id from auth_token where kind='password_reset' and token_digest=$1 and used_at is null and expires_at>now() for update",
310
+ [digest],
311
+ );
312
+ if (!r.rowCount) {
313
+ await client.query('rollback');
314
+ return res.status(400).json({ error: 'invalid_or_expired_token' });
315
+ }
316
+
317
+ await client.query('update auth_token set used_at=now() where token_digest=$1', [digest]);
318
+ const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
319
+ await client.query(
320
+ 'update auth_credential set password_hash=$1,password_changed_at=now() where user_id=$2',
321
+ [hash, r.rows[0].user_id],
322
+ );
323
+ await client.query(
324
+ 'update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null',
325
+ [r.rows[0].user_id],
326
+ );
327
+ await client.query('commit');
328
+ res.status(204).end();
329
+ } finally {
330
+ client.release();
331
+ }
332
+});
333
+
334
+app.post('/v1/auth/change-password', auth, async (req, res) => {
335
+ if (!validPassword(req.body.newPassword)) {
336
+ return res.status(400).json({ error: 'invalid_password' });
337
+ }
338
+
339
+ const r = await pool.query(
340
+ 'select password_hash from auth_credential where user_id=$1',
341
+ [req.identity.sub],
342
+ );
343
+ if (
344
+ !r.rowCount ||
345
+ !(await argon2.verify(r.rows[0].password_hash, String(req.body.currentPassword ?? '')))
346
+ ) {
347
+ return res.status(403).json({ error: 'invalid_current_password' });
348
+ }
349
+
350
+ const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
351
+ const client = await pool.connect();
352
+ try {
353
+ await client.query('begin');
354
+ await client.query(
355
+ 'update auth_credential set password_hash=$1,password_changed_at=now() where user_id=$2',
356
+ [hash, req.identity.sub],
357
+ );
358
+ await client.query(
359
+ 'update auth_session set revoked_at=now() where user_id=$1 and id<>$2 and revoked_at is null',
360
+ [req.identity.sub, req.identity.sid],
361
+ );
362
+ await client.query('commit');
363
+ res.status(204).end();
364
+ } finally {
365
+ client.release();
366
+ }
367
+});
368
+
369
+app.post('/v1/auth/logout', auth, async (req, res) => {
370
+ await pool.query('update auth_session set revoked_at=now() where id=$1', [req.identity.sid]);
371
+ res.status(204).end();
372
+});
373
+
374
+app.get('/v1/profile', auth, async (req, res) => {
375
+ const r = await pool.query(
376
+ 'select p.display_name,p.birth_date,p.theme_preference,u.email_normalized,u.email_verified_at from profile p join app_user u on u.id=p.user_id where p.user_id=$1',
377
+ [req.identity.sub],
378
+ );
379
+ if (!r.rowCount) return res.status(404).json({ error: 'profile_not_found' });
380
+ res.json(r.rows[0]);
381
+});
382
+
383
+app.patch('/v1/profile', auth, async (req, res) => {
384
+ const name = req.body.displayName == null ? null : String(req.body.displayName).trim();
385
+ const theme = req.body.themePreference == null ? null : String(req.body.themePreference);
386
+ const allowedThemes = ['girl_pink', 'boy_blue', 'adult_blue', 'custom'];
387
+ if (name != null && (!name || name.length > 100)) {
388
+ return res.status(400).json({ error: 'invalid_display_name' });
389
+ }
390
+ if (theme != null && !allowedThemes.includes(theme)) {
391
+ return res.status(400).json({ error: 'invalid_theme' });
392
+ }
393
+
394
+ const r = await pool.query(
395
+ `update profile
396
+ set display_name=coalesce($2,display_name),
397
+ birth_date=coalesce($3::date,birth_date),
398
+ theme_preference=coalesce($4,theme_preference),
399
+ updated_at=now()
400
+ where user_id=$1
401
+ returning display_name,birth_date,theme_preference`,
402
+ [req.identity.sub, name, req.body.birthDate ?? null, theme],
403
+ );
404
+ res.json(r.rows[0]);
405
+});
406
+
407
+app.get('/v1/families', auth, async (req, res) => {
408
+ const r = await pool.query(
409
+ `select f.id,f.name,m.role,m.is_admin
410
+ from family_membership m
411
+ join family_workspace f on f.id=m.family_id
412
+ where m.user_id=$1 and m.ended_at is null and f.archived_at is null
413
+ order by f.created_at`,
414
+ [req.identity.sub],
415
+ );
416
+ res.json({ families: r.rows });
417
+});
418
+
419
+app.post('/v1/families', auth, async (req, res) => {
420
+ const name = String(req.body.name ?? '').trim();
421
+ if (!name) return res.status(400).json({ error: 'invalid_name' });
422
+
423
+ const creatorRole = ['parent_guardian', 'adult_member'].includes(req.body.role)
424
+ ? req.body.role
425
+ : 'adult_member';
426
+ const c = await pool.connect();
427
+ try {
428
+ await c.query('begin');
429
+ const f = await c.query(
430
+ 'insert into family_workspace(name,created_by) values($1,$2) returning id,name',
431
+ [name, req.identity.sub],
432
+ );
433
+ await c.query(
434
+ 'insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,true)',
435
+ [f.rows[0].id, req.identity.sub, creatorRole],
436
+ );
437
+ await c.query(
438
+ "insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'family.create','family',$3)",
439
+ [req.identity.sub, f.rows[0].id, String(f.rows[0].id)],
440
+ );
441
+ await c.query('commit');
442
+ res.status(201).json(f.rows[0]);
443
+ } catch (e) {
444
+ await c.query('rollback');
445
+ throw e;
446
+ } finally {
447
+ c.release();
448
+ }
449
+});
450
+
451
+app.get('/v1/families/:familyId/members', auth, async (req, res) => {
452
+ const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
453
+ roles: ['parent_guardian', 'teen_minor', 'adult_member'],
454
+ });
455
+ if (!allowed) return res.status(403).json({ error: 'forbidden' });
456
+
457
+ const r = await pool.query(
458
+ `select m.user_id,m.role,m.is_admin,p.display_name,p.theme_preference
459
+ from family_membership m
460
+ join profile p on p.user_id=m.user_id
461
+ where m.family_id=$1 and m.ended_at is null
462
+ order by m.joined_at`,
463
+ [req.params.familyId],
464
+ );
465
+ res.json({ members: r.rows });
466
+});
467
+
468
+app.post('/v1/families/:familyId/invitations', auth, async (req, res) => {
469
+ const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
470
+ admin: true,
471
+ });
472
+ if (!allowed) return res.status(403).json({ error: 'forbidden' });
473
+
474
+ const email = normalizeEmail(req.body.email);
475
+ const role = String(req.body.role ?? '');
476
+ const themePreference = String(req.body.themePreference ?? '');
477
+ const allowedRoles = ['parent_guardian', 'teen_minor', 'adult_member'];
478
+ const allowedThemes = ['girl_pink', 'boy_blue', 'adult_blue', 'custom'];
479
+ const resolvedTheme = allowedThemes.includes(themePreference)
480
+ ? themePreference
481
+ : role === 'teen_minor'
482
+ ? 'girl_pink'
483
+ : 'adult_blue';
484
+ if (!isEmail(email) || !allowedRoles.includes(role)) {
485
+ return res.status(400).json({ error: 'invalid_invitation' });
486
+ }
487
+
488
+ const activeMember = await pool.query(
489
+ `select 1
490
+ from family_membership m
491
+ join app_user u on u.id=m.user_id
492
+ where m.family_id=$1
493
+ and m.ended_at is null
494
+ and u.email_normalized=$2`,
495
+ [req.params.familyId, email],
496
+ );
497
+ if (activeMember.rowCount) {
498
+ return res.status(409).json({ error: 'member_already_active' });
499
+ }
500
+
501
+ const token = randomToken();
502
+ const r = await pool.query(
503
+ "insert into family_invitation(family_id,invited_email_normalized,intended_role,intended_theme,token_digest,invited_by,expires_at) values($1,$2,$3,$4,$5,$6,now()+interval '7 days') returning id,expires_at",
504
+ [req.params.familyId, email, role, resolvedTheme, sha256(token), req.identity.sub],
505
+ );
506
+
507
+ const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid';
508
+ await sendTransactionalEmail({
509
+ to: email,
510
+ subject: 'دعوت به خانواده در LifeMate',
511
+ text: `برای پیوستن به خانواده این لینک را باز کنید: ${baseUrl}/accept-invitation?token=${encodeURIComponent(token)}`,
512
+ });
513
+
514
+ res.status(201).json({
515
+ ...r.rows[0],
516
+ invitationToken: testMode ? token : undefined,
517
+ });
518
+});
519
+
520
+app.post('/v1/invitations/accept', auth, async (req, res) => {
521
+ const digest = sha256(String(req.body.token ?? ''));
522
+ const client = await pool.connect();
523
+ try {
524
+ await client.query('begin');
525
+ const invitation = await client.query(
526
+ `select i.id,i.family_id,i.intended_role,i.intended_theme,i.invited_email_normalized,u.email_normalized
527
+ from family_invitation i
528
+ join app_user u on u.id=$2
529
+ where i.token_digest=$1
530
+ and i.status='pending'
531
+ and i.expires_at>now()
532
+ for update`,
533
+ [digest, req.identity.sub],
534
+ );
535
+ if (!invitation.rowCount) {
536
+ await client.query('rollback');
537
+ return res.status(400).json({ error: 'invalid_or_expired_invitation' });
538
+ }
539
+ const row = invitation.rows[0];
540
+ if (row.invited_email_normalized !== row.email_normalized) {
541
+ await client.query('rollback');
542
+ return res.status(403).json({ error: 'invitation_email_mismatch' });
543
+ }
544
+
545
+ await client.query(
546
+ `insert into family_membership(family_id,user_id,role)
547
+ values($1,$2,$3)
548
+ on conflict(family_id,user_id)
549
+ do update set role=excluded.role,ended_at=null`,
550
+ [row.family_id, req.identity.sub, row.intended_role],
551
+ );
552
+ await client.query(
553
+ "update family_invitation set status='accepted',accepted_by=$2,accepted_at=now() where id=$1",
554
+ [row.id, req.identity.sub],
555
+ );
556
+ if (row.intended_theme) {
557
+ await client.query(
558
+ 'update profile set theme_preference=$2,updated_at=now() where user_id=$1',
559
+ [req.identity.sub, row.intended_theme],
560
+ );
561
+ }
562
+ await client.query(
563
+ "insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,'invitation.accept','membership',$3)",
564
+ [req.identity.sub, row.family_id, String(req.identity.sub)],
565
+ );
566
+ await client.query('commit');
567
+ res.status(204).end();
568
+ } finally {
569
+ client.release();
570
+ }
571
+});
572
+
573
+app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
574
+ const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
575
+ admin: true,
576
+ });
577
+ if (!allowed) return res.status(403).json({ error: 'forbidden' });
578
+
579
+ const guardianUserId = String(req.body.guardianUserId ?? '');
580
+ const minorUserId = String(req.body.minorUserId ?? '');
581
+
582
+ const roles = await pool.query(
583
+ 'select user_id,role from family_membership where family_id=$1 and user_id in ($2,$3) and ended_at is null',
584
+ [req.params.familyId, guardianUserId, minorUserId],
585
+ );
586
+ const map = new Map(roles.rows.map((row) => [row.user_id, row.role]));
587
+ if (map.get(guardianUserId) !== 'parent_guardian' || map.get(minorUserId) !== 'teen_minor') {
588
+ return res.status(400).json({ error: 'invalid_guardian_relationship' });
589
+ }
590
+
591
+ await pool.query(
592
+ `insert into guardian_relationship(family_id,guardian_user_id,minor_user_id,active)
593
+ values($1,$2,$3,true)
594
+ on conflict(family_id,guardian_user_id,minor_user_id)
595
+ do update set active=true`,
596
+ [req.params.familyId, guardianUserId, minorUserId],
597
+ );
598
+ await pool.query(
599
+ "insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata) values($1,$2,'guardian.activate','guardian_relationship',$3,jsonb_build_object('minorUserId',$4::text))",
600
+ [req.identity.sub, req.params.familyId, guardianUserId, minorUserId],
601
+ );
602
+ res.status(204).end();
603
+});
604
+
605
+app.use((err, _req, res, _next) => {
606
+ console.error(err);
607
+ res.status(500).json({ error: 'internal_error' });
608
+});
609
+
610
+const port = Number(process.env.PORT ?? 8080);
611
+if (!testMode) {
612
+ app.listen(port, () => console.log(`LifeMate API listening on ${port}`));
613
+}
614
+
615
+export { app, pool };
616
+export default app;
backend/tests/api.test.js
new
+294
@@ -0,0 +1,294 @@
1
+import test, { after } from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { app, pool } from '../src/server.js';
4
+
5
+const server = app.listen(0);
6
+const address = server.address();
7
+const base = `http://127.0.0.1:${address.port}`;
8
+
9
+after(async () => {
10
+ await new Promise((resolve) => server.close(resolve));
11
+ await pool.end();
12
+});
13
+
14
+async function request(path, { method = 'GET', body, token } = {}) {
15
+ const response = await fetch(base + path, {
16
+ method,
17
+ headers: {
18
+ 'content-type': 'application/json',
19
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
20
+ },
21
+ body: body === undefined ? undefined : JSON.stringify(body),
22
+ });
23
+ const text = await response.text();
24
+ return {
25
+ status: response.status,
26
+ body: text ? JSON.parse(text) : null,
27
+ };
28
+}
29
+
30
+test('identity + family vertical slice', async () => {
31
+ const suffix = Date.now().toString(36);
32
+ const parentEmail = `parent-${suffix}@example.test`;
33
+ const teenEmail = `teen-${suffix}@example.test`;
34
+ const supporterEmail = `supporter-${suffix}@example.test`;
35
+ const initialPassword = 'StrongPass!123';
36
+ const changedPassword = 'StrongerPass!456';
37
+
38
+ const parentRegister = await request('/v1/auth/register', {
39
+ method: 'POST',
40
+ body: {
41
+ displayName: 'Parent',
42
+ email: parentEmail,
43
+ password: initialPassword,
44
+ },
45
+ });
46
+ assert.equal(parentRegister.status, 201);
47
+ assert.ok(parentRegister.body.verificationToken);
48
+
49
+ const parentVerify = await request('/v1/auth/verify-email', {
50
+ method: 'POST',
51
+ body: { token: parentRegister.body.verificationToken },
52
+ });
53
+ assert.equal(parentVerify.status, 204);
54
+
55
+ const parentLogin = await request('/v1/auth/login', {
56
+ method: 'POST',
57
+ body: { email: parentEmail, password: initialPassword },
58
+ });
59
+ assert.equal(parentLogin.status, 200);
60
+ assert.ok(parentLogin.body.accessToken);
61
+ assert.ok(parentLogin.body.refreshToken);
62
+
63
+ const refreshed = await request('/v1/auth/refresh', {
64
+ method: 'POST',
65
+ body: { refreshToken: parentLogin.body.refreshToken },
66
+ });
67
+ assert.equal(refreshed.status, 200);
68
+ assert.ok(refreshed.body.accessToken);
69
+ assert.notEqual(refreshed.body.refreshToken, parentLogin.body.refreshToken);
70
+
71
+ const profile = await request('/v1/profile', {
72
+ token: refreshed.body.accessToken,
73
+ });
74
+ assert.equal(profile.status, 200);
75
+ assert.equal(profile.body.display_name, 'Parent');
76
+
77
+ const profileUpdate = await request('/v1/profile', {
78
+ method: 'PATCH',
79
+ token: refreshed.body.accessToken,
80
+ body: { themePreference: 'adult_blue' },
81
+ });
82
+ assert.equal(profileUpdate.status, 200);
83
+ assert.equal(profileUpdate.body.theme_preference, 'adult_blue');
84
+
85
+ const family = await request('/v1/families', {
86
+ method: 'POST',
87
+ token: refreshed.body.accessToken,
88
+ body: { name: 'Test Family', role: 'parent_guardian' },
89
+ });
90
+ assert.equal(family.status, 201);
91
+ assert.ok(family.body.id);
92
+
93
+ const teenRegister = await request('/v1/auth/register', {
94
+ method: 'POST',
95
+ body: {
96
+ displayName: 'Teen',
97
+ email: teenEmail,
98
+ password: initialPassword,
99
+ },
100
+ });
101
+ assert.equal(teenRegister.status, 201);
102
+
103
+ assert.equal(
104
+ (await request('/v1/auth/verify-email', {
105
+ method: 'POST',
106
+ body: { token: teenRegister.body.verificationToken },
107
+ })).status,
108
+ 204,
109
+ );
110
+
111
+ const teenLogin = await request('/v1/auth/login', {
112
+ method: 'POST',
113
+ body: { email: teenEmail, password: initialPassword },
114
+ });
115
+ assert.equal(teenLogin.status, 200);
116
+
117
+ const unauthenticatedMembers = await request(`/v1/families/${family.body.id}/members`);
118
+ assert.equal(unauthenticatedMembers.status, 401);
119
+
120
+ const invite = await request(`/v1/families/${family.body.id}/invitations`, {
121
+ method: 'POST',
122
+ token: refreshed.body.accessToken,
123
+ body: { email: teenEmail, role: 'teen_minor' },
124
+ });
125
+ assert.equal(invite.status, 201);
126
+ assert.ok(invite.body.invitationToken);
127
+
128
+ const accept = await request('/v1/invitations/accept', {
129
+ method: 'POST',
130
+ token: teenLogin.body.accessToken,
131
+ body: { token: invite.body.invitationToken },
132
+ });
133
+ assert.equal(accept.status, 204);
134
+
135
+ const members = await request(`/v1/families/${family.body.id}/members`, {
136
+ token: refreshed.body.accessToken,
137
+ });
138
+ assert.equal(members.status, 200);
139
+ assert.equal(members.body.members.length, 2);
140
+ const parentMember = members.body.members.find((m) => m.display_name === 'Parent');
141
+ const teenMember = members.body.members.find((m) => m.display_name === 'Teen');
142
+ assert.equal(parentMember.role, 'parent_guardian');
143
+ assert.equal(parentMember.is_admin, true);
144
+ assert.equal(teenMember.role, 'teen_minor');
145
+ assert.equal(teenMember.is_admin, false);
146
+
147
+ const teenInviteAttempt = await request(`/v1/families/${family.body.id}/invitations`, {
148
+ method: 'POST',
149
+ token: teenLogin.body.accessToken,
150
+ body: { email: 'blocked@example.test', role: 'adult_member' },
151
+ });
152
+ assert.equal(teenInviteAttempt.status, 403);
153
+
154
+ const reinviteActiveTeen = await request(
155
+ `/v1/families/${family.body.id}/invitations`,
156
+ {
157
+ method: 'POST',
158
+ token: refreshed.body.accessToken,
159
+ body: {
160
+ email: teenEmail,
161
+ role: 'parent_guardian',
162
+ themePreference: 'adult_blue',
163
+ },
164
+ },
165
+ );
166
+ assert.equal(reinviteActiveTeen.status, 409);
167
+
168
+ const supporterRegister = await request('/v1/auth/register', {
169
+ method: 'POST',
170
+ body: {
171
+ displayName: 'Supporter',
172
+ email: supporterEmail,
173
+ password: initialPassword,
174
+ },
175
+ });
176
+ assert.equal(supporterRegister.status, 201);
177
+ assert.equal(
178
+ (
179
+ await request('/v1/auth/verify-email', {
180
+ method: 'POST',
181
+ body: { token: supporterRegister.body.verificationToken },
182
+ })
183
+ ).status,
184
+ 204,
185
+ );
186
+ const supporterLogin = await request('/v1/auth/login', {
187
+ method: 'POST',
188
+ body: { email: supporterEmail, password: initialPassword },
189
+ });
190
+ assert.equal(supporterLogin.status, 200);
191
+
192
+ const supporterInvite = await request(
193
+ `/v1/families/${family.body.id}/invitations`,
194
+ {
195
+ method: 'POST',
196
+ token: refreshed.body.accessToken,
197
+ body: { email: supporterEmail, role: 'parent_guardian' },
198
+ },
199
+ );
200
+ assert.equal(supporterInvite.status, 201);
201
+ assert.equal(
202
+ (
203
+ await request('/v1/invitations/accept', {
204
+ method: 'POST',
205
+ token: supporterLogin.body.accessToken,
206
+ body: { token: supporterInvite.body.invitationToken },
207
+ })
208
+ ).status,
209
+ 204,
210
+ );
211
+
212
+ const nonAdminParentInviteAttempt = await request(
213
+ `/v1/families/${family.body.id}/invitations`,
214
+ {
215
+ method: 'POST',
216
+ token: supporterLogin.body.accessToken,
217
+ body: { email: 'blocked-by-policy@example.test', role: 'adult_member' },
218
+ },
219
+ );
220
+ assert.equal(nonAdminParentInviteAttempt.status, 403);
221
+
222
+ const guardian = await request(`/v1/families/${family.body.id}/guardians`, {
223
+ method: 'POST',
224
+ token: refreshed.body.accessToken,
225
+ body: {
226
+ guardianUserId: parentMember.user_id,
227
+ minorUserId: teenMember.user_id,
228
+ },
229
+ });
230
+ assert.equal(guardian.status, 204);
231
+
232
+ const teenGuardianAttempt = await request(`/v1/families/${family.body.id}/guardians`, {
233
+ method: 'POST',
234
+ token: teenLogin.body.accessToken,
235
+ body: {
236
+ guardianUserId: parentMember.user_id,
237
+ minorUserId: teenMember.user_id,
238
+ },
239
+ });
240
+ assert.equal(teenGuardianAttempt.status, 403);
241
+
242
+ const forgot = await request('/v1/auth/forgot-password', {
243
+ method: 'POST',
244
+ body: { email: teenEmail },
245
+ });
246
+ assert.equal(forgot.status, 200);
247
+ assert.equal(forgot.body.accepted, true);
248
+ assert.ok(forgot.body.resetToken);
249
+
250
+ const reset = await request('/v1/auth/reset-password', {
251
+ method: 'POST',
252
+ body: { token: forgot.body.resetToken, newPassword: changedPassword },
253
+ });
254
+ assert.equal(reset.status, 204);
255
+
256
+ const oldLogin = await request('/v1/auth/login', {
257
+ method: 'POST',
258
+ body: { email: teenEmail, password: initialPassword },
259
+ });
260
+ assert.equal(oldLogin.status, 401);
261
+
262
+ const newLogin = await request('/v1/auth/login', {
263
+ method: 'POST',
264
+ body: { email: teenEmail, password: changedPassword },
265
+ });
266
+ assert.equal(newLogin.status, 200);
267
+
268
+ const changedAgain = await request('/v1/auth/change-password', {
269
+ method: 'POST',
270
+ token: newLogin.body.accessToken,
271
+ body: { currentPassword: changedPassword, newPassword: initialPassword },
272
+ });
273
+ assert.equal(changedAgain.status, 204);
274
+
275
+ const logout = await request('/v1/auth/logout', {
276
+ method: 'POST',
277
+ token: newLogin.body.accessToken,
278
+ });
279
+ assert.equal(logout.status, 204);
280
+
281
+ const afterLogout = await request('/v1/profile', {
282
+ token: newLogin.body.accessToken,
283
+ });
284
+ assert.equal(afterLogout.status, 401);
285
+});
286
+
287
+test('forgot-password response does not enumerate accounts', async () => {
288
+ const response = await request('/v1/auth/forgot-password', {
289
+ method: 'POST',
290
+ body: { email: `missing-${Date.now()}@example.test` },
291
+ });
292
+ assert.equal(response.status, 200);
293
+ assert.deepEqual(response.body, { accepted: true });
294
+});
backend/tests/schema_test.sql
new
+41
@@ -0,0 +1,41 @@
1
+\set ON_ERROR_STOP on
2
+
3
+begin;
4
+
5
+insert into app_user(id, identity_subject, email_normalized) values
6
+('00000000-0000-0000-0000-000000000001','parent-1','parent@example.test'),
7
+('00000000-0000-0000-0000-000000000002','teen-1','teen@example.test'),
8
+('00000000-0000-0000-0000-000000000003','other-1','other@example.test');
9
+
10
+insert into family_workspace(id,name,created_by) values
11
+('10000000-0000-0000-0000-000000000001','Test Family','00000000-0000-0000-0000-000000000001');
12
+
13
+insert into family_membership(family_id,user_id,role,is_admin) values
14
+('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000001','parent_guardian',true),
15
+('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002','teen_minor',false);
16
+
17
+insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values
18
+('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002');
19
+
20
+do $$
21
+begin
22
+ if not is_active_family_member('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002') then raise exception 'teen must be active family member'; end if;
23
+ if is_active_family_member('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000003') then raise exception 'outsider must not be family member'; end if;
24
+ if not is_family_admin('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000001') then raise exception 'parent admin capability missing'; end if;
25
+ if is_family_admin('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002') then raise exception 'teen must not inherit admin capability'; end if;
26
+ if not is_active_guardian('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002') then raise exception 'guardian relation missing'; end if;
27
+ if is_active_guardian('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000003','00000000-0000-0000-0000-000000000002') then raise exception 'outsider must not become guardian'; end if;
28
+end $$;
29
+
30
+update family_membership
31
+set ended_at=now()
32
+where family_id='10000000-0000-0000-0000-000000000001'
33
+ and user_id='00000000-0000-0000-0000-000000000002';
34
+
35
+do $$
36
+begin
37
+ if is_active_family_member('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002') then raise exception 'removed teen must not remain active member'; end if;
38
+ if is_active_guardian('10000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002') then raise exception 'guardian relationship must deactivate when minor membership ends'; end if;
39
+end $$;
40
+
41
+rollback;
docs/architecture/PHASE_2_BLUEPRINT.md
+21
-20
@@ -1,6 +1,6 @@
1
# LifeMate — Phase 2 Implementation Blueprint
2
3
-## Proposed repository structure
3
+## Repository structure
4
```text
5
apps/lifemate/ Flutter application (Android + Web/PWA)
6
lib/
@@ -8,39 +8,40 @@ apps/lifemate/ Flutter application (Android + Web/PWA)
8
features/auth/
9
features/profile/
10
features/family/
11
- shared/ reusable UI/domain utilities with strict scope
12
- web/ manifest, icons, bootstrap, custom SW/web integration
11
+ shared/
12
+ web/ manifest, icons, PWA integration
13
test/
14
-supabase/
15
- migrations/ versioned schema + grants + RLS
16
- functions/ privileged server workflows; no client secrets
17
- tests/ database/RLS allow+deny tests
14
+backend/
15
+ migrations/ standard PostgreSQL schema + constraints/policies
16
+ tests/ authorization/database tests
17
+ README.md API/identity adapter contract
18
docs/ product, UX, architecture, safety, quality, decisions
19
-.github/workflows/ CI after scaffold
19
+.github/workflows/ CI and staging verification
20
```
21
22
## Architecture style
23
-Feature-oriented Flutter modules with domain/service boundaries; avoid a giant shared layer. UI may validate and cache, but backend policies are authoritative for permissions. Supabase is accessed through repository/service interfaces so AI/provider logic and complex privileged workflows remain server-side.
23
+Feature-oriented Flutter modules behind application repositories. Flutter never receives privileged database credentials. A server/API boundary owns identity-session validation and relationship-aware authorization. PostgreSQL is the durable relational source of truth. Managed database, identity, email, storage and realtime providers are adapters rather than domain dependencies.
24
25
## Environments
26
-At minimum: **local**, **staging**, **production**. Staging and production use separate Supabase projects/secrets/data. Environment-specific public configuration is injected at build/deploy; secrets/service-role/provider keys exist only in server secret stores. `.env` with real credentials is never committed.
26
+At minimum: **local**, **staging**, **production**. Staging and production use separate database credentials/data. Environment-specific public API configuration is injected at build/deploy; privileged credentials exist only in server/CI secret stores. Real `.env` files are never committed.
27
28
-## Phase 2 first vertical slice
29
-1. App shell + localization/RTL + theme.
30
-2. Email/password auth + verification/recovery/change-password.
31
-3. Profile creation.
28
+## Phase 2 vertical slice
29
+1. App shell + Persian RTL + role/profile-aware theme.
30
+2. Email/password auth contract + verification/recovery/change-password UX.
31
+3. Profile creation/editing.
32
4. Family Workspace + invitation + membership.
33
-5. Guardian relationship and baseline permission enforcement.
33
+5. Guardian relationship and baseline server authorization contract.
34
6. Teen/Parent authenticated home shells.
35
-7. CI and staging smoke.
35
+7. CI and isolated PostgreSQL staging smoke.
36
37
-This slice deliberately proves identity and authorization before planner/school data expands the schema.
37
+## Student navigation baseline
38
+MyStudyLife is the primary information-architecture benchmark for the student surface. Direct destinations remain visible for Today, Schedule, Calendar, Tasks, Exams/Grades, Focus and AI; LifeMate Family/Wellbeing extensions are additive rather than hiding these core destinations behind a generic School layer.
39
40
## PWA integration
40
-Own `manifest.json`, icons/apple-touch-icon, standalone metadata, install guidance and custom service-worker strategy. Push subscription is capability-detected and implemented only after the core auth/family slice is stable.
41
+Own `manifest.json`, branded icons/apple-touch-icon, standalone metadata, install guidance and explicit service-worker strategy. Push is capability-detected and is not required for Phase 2 identity acceptance.
42
43
## Configuration rule
43
-Public client identifiers are separated from secrets. Any credential that bypasses RLS or accesses AI/email/push provider privileged APIs is server-only.
44
+Any credential that can read another user's private data, administer identity, send privileged email, or bypass authorization is server-only.
45
46
## Migration rule
46
-Schema/grant/RLS changes travel together in versioned migrations and include database tests. Destructive migrations require explicit approval and rollback/backup consideration.
\ No newline at end of file
47
+Schema, constraints and authorization-relevant database changes travel together in versioned PostgreSQL migrations and tests. Destructive migrations require explicit approval and rollback/backup consideration.
docs/decisions/0005-backend-supabase.md
+3
-20
@@ -1,24 +1,7 @@
1
# ADR-0005 — Backend/Auth Baseline: Supabase
2
3
-- **Status:** Accepted for Phase 2 baseline
3
+- **Status:** Superseded
4
- **Date:** 2026-10-05
5
+- **Superseded by:** `0006-provider-neutral-postgresql-backend.md`
6
6
-## Decision
7
-Use **Supabase** as the initial backend platform: PostgreSQL + Supabase Auth + Row Level Security, with Edge Functions/server-side code for privileged workflows, AI orchestration and secrets.
8
-
9
-## Why
10
-LifeMate needs relational family/guardian/resource relationships, granular authorization and email/password recovery. Supabase Auth integrates JWT identity with PostgreSQL RLS, allowing authorization to remain consistent across Android and Web/PWA clients.
11
-
12
-## Security contract
13
-- Enable RLS on every exposed application table.
14
-- Explicitly set grants and separate policies by operation; do not assume RLS alone removes broad grants.
15
-- Test allow and deny paths for authorization policies.
16
-- Publishable client key may exist in clients; service-role/secret keys never do.
17
-- Privileged AI/provider calls, invitation administration and sensitive safety workflows execute server-side.
18
-- Views/functions must be reviewed for RLS/security-definer behavior before exposure.
19
-
20
-## Auth baseline
21
-Email/password with email verification, non-enumerating forgot-password response, time-limited recovery flow, authenticated password change and controlled redirect URLs. Custom SMTP/provider selection is an operational Phase 2 task, not a reason to build custom authentication.
22
-
23
-## Alternatives considered
24
-Custom API/Postgres would provide full control but adds auth/security/operations work before core product value. Firebase simplifies some mobile flows but the relational authorization model is a less direct fit for family/guardian/resource policy. Supabase remains replaceable behind domain/service boundaries if later scale or compliance requirements justify migration.
\ No newline at end of file
7
+Supabase was initially selected as the Phase 2 combined PostgreSQL/Auth/RLS platform. The project subsequently moved to a provider-neutral PostgreSQL architecture with explicit identity/API/email/storage adapters. This file remains only as decision history and must not be used as current implementation guidance.
docs/decisions/0006-provider-neutral-postgresql-backend.md
new
+41
@@ -0,0 +1,41 @@
1
+# ADR-0006 — Provider-neutral PostgreSQL Backend
2
+
3
+- **Status:** Accepted
4
+- **Date:** 2026-10-05
5
+- **Supersedes:** any Phase 2 assumption that Supabase is a mandatory backend platform
6
+
7
+## Context
8
+Phase 2 originally treated Supabase as the likely combined database/auth/backend provider. Creation of an isolated LifeMate staging project was blocked by account-level project limits. More importantly, tying identity, authorization, storage, realtime and database behavior to one BaaS creates unnecessary platform coupling for a long-lived family product.
9
+
10
+## Decision
11
+LifeMate will use PostgreSQL as its durable relational source of truth while exposing infrastructure through explicit application ports/adapters.
12
+
13
+The managed PostgreSQL host is replaceable. Neon is the preferred current target when available, but no domain entity, authorization rule, migration or client contract may require Neon-specific semantics.
14
+
15
+Required ports:
16
+- `IdentityProvider`: registration, email verification, login/session, password recovery/change.
17
+- `LifeMateApi`: authenticated application boundary; clients do not receive privileged database credentials.
18
+- `TransactionalEmail`: verification, password recovery and family invitation messages.
19
+- `ObjectStorage`: future profile/media assets.
20
+- `RealtimeTransport`: optional event delivery; business correctness cannot depend on it.
21
+
22
+PostgreSQL owns profiles, family workspaces, memberships, guardian relationships, invitations and authorization-relevant state. Authorization is enforced server-side. Database constraints and, where operationally suitable, RLS are defense-in-depth rather than the only authorization boundary.
23
+
24
+## Consequences
25
+### Positive
26
+- Staging/production can move between managed PostgreSQL providers.
27
+- Auth can change without rewriting family/profile domain tables.
28
+- Flutter clients stay independent of database vendor SDKs.
29
+- Testing authorization through API/service contracts becomes straightforward.
30
+- LifeMate is no longer blocked by Supabase project quotas.
31
+
32
+### Cost
33
+- We own a small backend/API layer instead of relying entirely on generated BaaS APIs.
34
+- Email verification/recovery and session handling need an explicit identity adapter.
35
+- Realtime/storage require separate adapters if/when introduced.
36
+
37
+## Guardrails
38
+- Never place database owner/service credentials in Flutter/Web clients.
39
+- Never use client-side role checks as the security boundary.
40
+- Never let Family Owner/Admin imply automatic access to private teen content.
41
+- Migrations remain standard PostgreSQL SQL wherever practical.
docs/plans/PHASE_2_IMPLEMENTATION_PLAN.md
new
+38
@@ -0,0 +1,38 @@
1
+# Phase 2 — Product Foundation & Identity Implementation Plan
2
+
3
+Status: IN PROGRESS
4
+
5
+## Acceptance contract
6
+Phase 2 is complete only when a real Flutter Android/Web-PWA scaffold exists; email/password auth supports verification, recovery and password change; profiles and family workspaces exist; invitations and guardian relationships are server-authorized; RTL/theme shells exist for teen/parent; CI builds/tests Android and Web; and a separate staging PostgreSQL backend has been exercised.
7
+
8
+## Architecture revision
9
+Supabase is no longer a required platform dependency. LifeMate uses provider-neutral backend ports with PostgreSQL as the durable relational core. Neon is the preferred managed PostgreSQL target when its connector is operational, but application/domain code must not depend on Neon-specific APIs.
10
+
11
+Provider boundaries:
12
+- Database: PostgreSQL 17-compatible SQL; managed target may be Neon.
13
+- Authorization: server-side policy/service layer backed by relational membership/guardian grants; PostgreSQL RLS may provide defense in depth where supported.
14
+- Authentication: `IdentityProvider` port; provider implementation can be changed without altering domain entities.
15
+- Object storage: `ObjectStorage` port; not required for Phase 2 identity acceptance.
16
+- Email: `TransactionalEmail` port for verification/recovery/invitations.
17
+- Realtime: optional adapter; no Phase 2 domain rule depends on realtime delivery.
18
+
19
+## Execution order
20
+1. Scaffold Flutter app and platform assets.
21
+2. RED tests for role/theme/auth/family domain behavior, then minimal GREEN implementation.
22
+3. Add provider-neutral client repositories for auth/profile/family flows.
23
+4. Add versioned PostgreSQL schema, constraints, authorization policy tests and optional RLS defense-in-depth policies.
24
+5. Add authentication UI: sign-in/up, verification state, forgot/reset/change password.
25
+6. Add profile + family workspace + invitation + membership/guardian UI.
26
+7. Add Persian RTL authenticated Teen/Parent shells and MyStudyLife-inspired direct student navigation.
27
+8. Add CI: format, analyze, tests, Android debug build, Web build, secret scan.
28
+9. Attach an isolated staging PostgreSQL environment, apply migrations, run authorization/smoke tests.
29
+10. Verify branch, update PROJECT_STATE, PR review and merge only after green evidence.
30
+
31
+## Product rulings carried into implementation
32
+- Student IA uses MyStudyLife as benchmark: direct access to Today, Schedule, Calendar, Tasks, Exams/Grades, Focus and AI; LifeMate family/wellbeing extensions remain additive.
33
+- Theme defaults: girl/teen profile white + soft pink; boy/teen white + blue; parent/adult white + blue. Theme remains user-overridable later.
34
+- Admin ownership never implies blanket access to private teen content.
35
+- No wellbeing/AI production exposure in Phase 2.
36
+
37
+## Environment rule
38
+Local, staging and production are distinct. Staging must not reuse Finora/EasyFactor infrastructure. The codebase must remain deployable to standard PostgreSQL even if a managed-provider connector is temporarily unavailable.
docs/quality/PHASE_2_QUALITY_GATES.md
+3
-3
@@ -5,13 +5,13 @@ Once application code exists, every implementation PR must run:
5
1. formatting check;
6
2. Flutter/Dart static analysis;
7
3. unit/widget tests relevant to changed domain/UI;
8
-4. authorization/database tests when schema/RLS changes;
8
+4. authorization/database tests when schema or access-policy changes;
9
5. Android debug build smoke;
10
6. Web release/debug build smoke as appropriate;
11
-7. secret scanning/dependency review available in the repository plan/tooling.
11
+7. secret scanning and backend dependency audit in CI.
12
13
## Security tests required for identity/family
14
-For each protected resource, test allowed and denied access for: owner profile, related guardian, unrelated family member, removed member, unauthenticated user and privileged server path where applicable. RLS tests must cover SELECT/INSERT/UPDATE/DELETE rather than only happy-path reads.
14
+For each protected resource, test allowed and denied access for: owner profile, related guardian, unrelated family member, removed member, unauthenticated user and privileged server path where applicable. LifeMate's primary authorization boundary is the server/API layer; database constraints and helper-policy tests provide defense in depth. If RLS is enabled for a deployment, its SELECT/INSERT/UPDATE/DELETE policies must be tested as an additional gate.
15
16
## Staging rule
17
All deployable changes land in staging before production. Staging uses separate environment/secrets/data from production. No production deploy, destructive migration or sensitive access change is implied by merge alone.
docs/ux/BRAND_BRIEF_V1.md
+14
-7
@@ -4,14 +4,22 @@
4
**LifeMate = همراه رشد، نه ناظر.** The visual language combines calm, momentum, independence and connection.
5
6
## Audience behavior
7
-The initial teen experience must feel attractive to a 13-year-old without using preschool/childish motifs. The same identity must remain credible at 16, 20 and adulthood. Parent surfaces share the brand but prioritize clarity and actionability.
7
+The initial teen experience must feel attractive to a 13-year-old without preschool/childish motifs. The same identity must remain credible at 16, 20 and adulthood. Parent surfaces share the brand but prioritize clarity and actionability.
8
+
9
+## Profile-aware theme defaults
10
+LifeMate uses a white/light neutral foundation and applies a profile-aware accent as a **default, not an irreversible identity lock**:
11
+- Girl/teen default: white + soft modern pink.
12
+- Boy/teen default: white + calm blue.
13
+- Parent/adult default: white + calm blue with a more restrained information density.
14
+
15
+The component system, navigation and semantics remain identical across themes. A future Settings control may override the accent without changing role, gender or permissions. Never communicate state using color alone.
16
17
## Visual direction
18
- Soft geometric forms, rounded but not toy-like.
11
-- Controlled illustration: meaningful empty states, learning moments and onboarding; avoid decorative overload.
12
-- Primary direction: deep plum/indigo anchor + lavender support + mint success/calm + restrained peach warmth + light neutral cloud surfaces.
19
+- Controlled illustration for meaningful empty states, learning moments and onboarding; avoid decorative overload.
20
+- Use restrained success/calm/warning semantic colors independent from the profile accent.
21
- Dark mode must be designed, not mechanically inverted.
14
-- Typography direction: **Vazirmatn** for Persian UI where licensing/package validation passes; Latin companion chosen for metric harmony.
22
+- Typography direction: **Vazirmatn** for Persian UI where package/license validation passes; Latin companion chosen for metric harmony.
23
- Iconography: rounded, consistent stroke; no cartoon school clichés as the core brand mark.
24
25
## Logo/app icon principles
@@ -24,11 +32,10 @@ Teen: encouraging, calm, graphical, choice-oriented. Parent: concise, trustworth
32
Use short purposeful transitions to explain hierarchy/status. No attention-hijacking animation, reward explosions or endless streak pressure. Respect reduced motion.
33
34
## Figma artifact
27
-Phase 1 design file: `LifeMate — Product UX & Brand v1`.
28
-Initial editable board includes color direction and concept frames for Teen Today, Parent Overview and Login/Welcome. This is a direction board, not a final UI kit.
35
+Phase 1 design file: `LifeMate — Product UX & Brand v1`. Initial editable board is directional, not a final UI kit.
36
37
## Canva role
38
Canva is approved for supporting illustration/educational visual asset exploration. Final UI layout, tokens, components and interaction specifications remain controlled in Figma so implementation does not depend on flattened artwork.
39
40
## Acceptance
34
-A future screen should be rejected if it feels like a generic school ERP, a surveillance dashboard, or a small-child game. It should feel like a polished personal companion that happens to understand school and family.
\ No newline at end of file
41
+Reject screens that feel like a generic school ERP, a surveillance dashboard, or a small-child game. LifeMate should feel like a polished personal companion that understands school and family.