@davoodmehraban89 / LifeMate / commits / ee9fb36
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(api): persist shared planner and study sessions with tested auth and privacy

Codex committed Oct 8, 2026 at 15:49 UTC ee9fb363f8211cd6839759775f8e62c15b2d3963
33 files changed +5106 -821
backend/migrations/0007_auth_contacts.sql new
+44
@@ -0,0 +1,44 @@
1 +begin;
2 +
3 +alter table app_user alter column email_normalized drop not null;
4 +alter table app_user add column phone_normalized text unique;
5 +alter table app_user add column phone_verified_at timestamptz;
6 +alter table app_user add constraint app_user_phone_format
7 + check (phone_normalized is null or phone_normalized ~ '^\+[1-9][0-9]{7,14}$');
8 +alter table app_user add constraint app_user_contact_required
9 + check (email_normalized is not null or phone_normalized is not null);
10 +
11 +alter table family_invitation alter column invited_email_normalized drop not null;
12 +alter table family_invitation add column invited_phone_normalized text;
13 +alter table family_invitation add constraint family_invitation_contact_required
14 + check (num_nonnulls(invited_email_normalized,invited_phone_normalized)=1);
15 +alter table family_invitation add constraint family_invitation_phone_format
16 + check (invited_phone_normalized is null or invited_phone_normalized ~ '^\+[1-9][0-9]{7,14}$');
17 +
18 +create table auth_delivery_attempt (
19 + id uuid primary key default gen_random_uuid(),
20 + recipient_digest text not null check (recipient_digest ~ '^[a-f0-9]{64}$'),
21 + purpose text not null check (purpose in ('email_verification','password_reset','phone_otp')),
22 + user_id uuid references app_user(id) on delete set null,
23 + status text not null default 'pending'
24 + check (status in ('pending','accepted','failed','unconfigured','not_needed')),
25 + requested_at timestamptz not null default now(),
26 + updated_at timestamptz not null default now()
27 +);
28 +create index auth_delivery_recipient_window_idx
29 + on auth_delivery_attempt(recipient_digest,purpose,requested_at desc);
30 +
31 +create table auth_phone_challenge (
32 + id uuid primary key,
33 + user_id uuid references app_user(id) on delete cascade,
34 + purpose text not null check (purpose in ('verify','login','recovery')),
35 + code_digest text not null check (code_digest ~ '^[a-f0-9]{64}$'),
36 + attempts smallint not null default 0 check (attempts between 0 and 5),
37 + expires_at timestamptz not null,
38 + used_at timestamptz,
39 + created_at timestamptz not null default now(),
40 + check (expires_at > created_at)
41 +);
42 +create index auth_phone_challenge_owner_idx on auth_phone_challenge(user_id,created_at desc);
43 +
44 +commit;
backend/migrations/0008_study_sessions.sql new
+75
@@ -0,0 +1,75 @@
1 +begin;
2 +
3 +-- Reuse the existing planner; its legacy status remains compatible.
4 +alter table plan_item add column activity_version bigint not null default 0;
5 +alter table plan_item add column if not exists version bigint not null default 0;
6 +alter table plan_item add constraint plan_item_id_owner_unique unique(id,owner_user_id);
7 +
8 +create function plan_item_revision() returns trigger language plpgsql as $$
9 +begin
10 + new.version := old.version+1;
11 + return new;
12 +end $$;
13 +create trigger plan_item_revision before update on plan_item
14 +for each row execute function plan_item_revision();
15 +
16 +create table study_session (
17 + id uuid primary key,
18 + child_user_id uuid not null references app_user(id) on delete cascade,
19 + plan_item_id uuid not null,
20 + source text not null check(source in ('timer','self_reported')),
21 + status text not null check(status in ('running','paused','completed','archived')),
22 + started_at timestamptz not null,
23 + ended_at timestamptz,
24 + last_event_at timestamptz not null,
25 + recorded_duration_seconds integer not null default 0 check(recorded_duration_seconds>=0),
26 + version integer not null default 1 check(version>0),
27 + last_sync_at timestamptz not null default now(),
28 + created_at timestamptz not null default now(),
29 + updated_at timestamptz not null default now(),
30 + archived_at timestamptz,
31 + foreign key(plan_item_id,child_user_id) references plan_item(id,owner_user_id) on delete cascade,
32 + check(ended_at is null or ended_at>=started_at),
33 + check(last_event_at>=started_at)
34 +);
35 +create index study_session_owner_idx on study_session(child_user_id,started_at desc);
36 +create index study_session_plan_idx on study_session(plan_item_id) where archived_at is null;
37 +
38 +create table study_interval (
39 + id bigint generated always as identity primary key,
40 + session_id uuid not null references study_session(id) on delete cascade,
41 + starts_at timestamptz not null,
42 + ends_at timestamptz,
43 + check(ends_at is null or ends_at>=starts_at)
44 +);
45 +create index study_interval_session_idx on study_interval(session_id,starts_at);
46 +create unique index study_interval_one_running_idx on study_interval(session_id) where ends_at is null;
47 +
48 +create table activity_state_event (
49 + id bigint generated always as identity primary key,
50 + plan_item_id uuid not null references plan_item(id) on delete cascade,
51 + actor_user_id uuid not null references app_user(id),
52 + state text not null check(state in ('planned','started','paused','completed','verified')),
53 + source text not null check(source in ('client_timer','self_reported','guardian_confirmation')),
54 + occurred_at timestamptz not null,
55 + accepted_at timestamptz not null default now(),
56 + version bigint not null check(version>0),
57 + confirmation text,
58 + unique(plan_item_id,version),
59 + check((state='verified' and source='guardian_confirmation' and char_length(confirmation) between 1 and 1000)
60 + or (state<>'verified' and source<>'guardian_confirmation' and confirmation is null))
61 +);
62 +create index activity_state_latest_idx on activity_state_event(plan_item_id,version desc);
63 +
64 +-- A separate ledger avoids changing existing planner/offline sync protocol.
65 +create table study_mutation (
66 + user_id uuid not null references app_user(id) on delete cascade,
67 + id uuid not null,
68 + request_hash text not null,
69 + response_body jsonb not null,
70 + response_status integer not null,
71 + accepted_at timestamptz not null default now(),
72 + primary key(user_id,id)
73 +);
74 +
75 +commit;
backend/migrations/0009_authorization_privacy.sql new
+94
@@ -0,0 +1,94 @@
1 +begin;
2 +
3 +create or replace function can_view_student_academic(p_viewer uuid, p_student uuid) returns boolean
4 +language sql stable as $$
5 + select p_viewer=p_student or exists(
6 + select 1 from guardian_relationship g
7 + where g.guardian_user_id=p_viewer
8 + and g.minor_user_id=p_student
9 + and is_active_guardian(g.family_id,p_viewer,p_student)
10 + )
11 +$$;
12 +
13 +create or replace function can_view_plan_item(p_viewer uuid, p_item uuid) returns boolean
14 +language sql stable as $$
15 + select exists(
16 + select 1 from plan_item p
17 + where p.id=p_item
18 + and (
19 + p.owner_user_id=p_viewer
20 + or (
21 + p.family_id is not null
22 + and is_active_family_member(p.family_id,p.owner_user_id)
23 + and is_active_family_member(p.family_id,p_viewer)
24 + and (
25 + p.visibility='family'
26 + or (
27 + p.visibility='parent_guardian'
28 + and is_active_guardian(p.family_id,p_viewer,p.owner_user_id)
29 + )
30 + or (
31 + p.visibility='selected_members'
32 + and exists(
33 + select 1 from sharing_grant sg
34 + where sg.resource_type='plan_item'
35 + and sg.resource_id=p.id
36 + and sg.grantee_user_id=p_viewer
37 + and sg.granted_by=p.owner_user_id
38 + )
39 + )
40 + )
41 + )
42 + )
43 + )
44 +$$;
45 +
46 +-- Remove grants that are already invalid; later rejoining must not restore them.
47 +delete from sharing_grant sg
48 + where sg.resource_type='plan_item'
49 + and not exists(
50 + select 1 from plan_item p
51 + where p.id=sg.resource_id
52 + and p.visibility='selected_members'
53 + and p.family_id is not null
54 + and sg.granted_by=p.owner_user_id
55 + and is_active_family_member(p.family_id,p.owner_user_id)
56 + and is_active_family_member(p.family_id,sg.grantee_user_id)
57 + );
58 +
59 +create function revoke_changed_plan_item_grants() returns trigger
60 +language plpgsql as $$
61 +begin
62 + if new.visibility <> 'selected_members'
63 + or new.family_id is distinct from old.family_id
64 + or new.owner_user_id is distinct from old.owner_user_id then
65 + delete from sharing_grant where resource_type='plan_item' and resource_id=new.id;
66 + end if;
67 + return new;
68 +end
69 +$$;
70 +
71 +create trigger plan_item_revoke_changed_grants
72 +after update of visibility,family_id,owner_user_id on plan_item
73 +for each row execute function revoke_changed_plan_item_grants();
74 +
75 +create function revoke_ended_membership_grants() returns trigger
76 +language plpgsql as $$
77 +begin
78 + if tg_op='DELETE' or new.ended_at is not null then
79 + delete from sharing_grant sg
80 + using plan_item p
81 + where sg.resource_type='plan_item'
82 + and sg.resource_id=p.id
83 + and p.family_id=old.family_id
84 + and (p.owner_user_id=old.user_id or sg.grantee_user_id=old.user_id);
85 + end if;
86 + return null;
87 +end
88 +$$;
89 +
90 +create trigger family_membership_revoke_ended_grants
91 +after update of ended_at or delete on family_membership
92 +for each row execute function revoke_ended_membership_grants();
93 +
94 +commit;
backend/migrations/0010_planner_sync.sql new
+55
@@ -0,0 +1,55 @@
1 +begin;
2 +
3 +alter table plan_item add column if not exists version bigint not null default 0;
4 +alter table plan_item alter column version set default 1;
5 +alter table plan_item add column planned_duration_seconds integer
6 + check(planned_duration_seconds is null or planned_duration_seconds between 0 and 86400);
7 +update plan_item set planned_duration_seconds=duration_minutes*60 where duration_minutes is not null;
8 +
9 +alter table sync_mutation drop constraint sync_mutation_pkey;
10 +alter table sync_mutation add primary key(user_id,id);
11 +alter table sync_mutation drop constraint sync_mutation_operation_check;
12 +alter table sync_mutation add constraint sync_mutation_operation_check
13 + check(operation in ('create','update','complete','reschedule','archive'));
14 +alter table sync_mutation add column request_hash text;
15 +alter table sync_mutation add column canonical_item jsonb;
16 +
17 +create or replace function is_active_family_member(p_family uuid,p_user uuid) returns boolean
18 +language sql stable as $$
19 + select exists(select 1 from family_membership m join family_workspace f on f.id=m.family_id
20 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and f.archived_at is null)
21 +$$;
22 +create or replace function is_active_guardian(p_family uuid,p_guardian uuid,p_minor uuid) returns boolean
23 +language sql stable as $$
24 + select exists(select 1 from guardian_relationship g
25 + join family_workspace f on f.id=g.family_id and f.archived_at is null
26 + join family_membership gm on gm.family_id=g.family_id and gm.user_id=g.guardian_user_id
27 + and gm.ended_at is null and gm.role='parent_guardian'
28 + join family_membership mm on mm.family_id=g.family_id and mm.user_id=g.minor_user_id
29 + and mm.ended_at is null and mm.role='teen_minor'
30 + where g.family_id=p_family and g.guardian_user_id=p_guardian and g.minor_user_id=p_minor and g.active)
31 +$$;
32 +create or replace function is_family_admin(p_family uuid,p_user uuid) returns boolean
33 +language sql stable as $$
34 + select exists(select 1 from family_membership m join family_workspace f on f.id=m.family_id
35 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and m.is_admin and f.archived_at is null)
36 +$$;
37 +
38 +-- Legacy planner PATCH/sync writes still record explicit self-reported activity
39 +-- transitions. Dedicated study/activity writes already advance activity_version.
40 +create function plan_item_legacy_activity() returns trigger language plpgsql as $$
41 +begin
42 + if new.status is distinct from old.status and new.activity_version=old.activity_version
43 + and new.status<>'cancelled' then
44 + new.activity_version := old.activity_version+1;
45 + insert into activity_state_event(plan_item_id,actor_user_id,state,source,occurred_at,version)
46 + values(new.id,new.owner_user_id,
47 + case new.status when 'completed' then 'completed' when 'in_progress' then 'started' else 'planned' end,
48 + 'self_reported',coalesce(new.completed_at,new.updated_at),new.activity_version);
49 + end if;
50 + return new;
51 +end $$;
52 +create trigger plan_item_legacy_activity before update on plan_item
53 +for each row execute function plan_item_legacy_activity();
54 +
55 +commit;
backend/migrations/0011_profile_category.sql new
+18
@@ -0,0 +1,18 @@
1 +begin;
2 +
3 +alter table profile add column profile_category text;
4 +
5 +-- Legacy presentation choices are the only migration hint. Family membership
6 +-- and guardian permissions never define a person's independent category.
7 +update profile set profile_category=case theme_preference
8 + when 'girl_pink' then 'girl_minor'
9 + when 'boy_blue' then 'boy_minor'
10 + else 'adult'
11 +end;
12 +
13 +alter table profile alter column profile_category set default 'adult';
14 +alter table profile alter column profile_category set not null;
15 +alter table profile add constraint profile_category_allowed
16 + check(profile_category in ('girl_minor','boy_minor','adult'));
17 +
18 +commit;
backend/package-lock.json new
+1343
@@ -0,0 +1,1343 @@
1 +{
2 + "name": "lifemate-backend",
3 + "version": "0.5.0",
4 + "lockfileVersion": 3,
5 + "requires": true,
6 + "packages": {
7 + "": {
8 + "name": "lifemate-backend",
9 + "version": "0.5.0",
10 + "dependencies": {
11 + "argon2": "^0.44.0",
12 + "cors": "^2.8.5",
13 + "express": "^5.1.0",
14 + "jsonwebtoken": "^9.0.2",
15 + "nodemailer": "^10.0.14",
16 + "pg": "^8.16.3"
17 + },
18 + "engines": {
19 + "node": ">=22"
20 + }
21 + },
22 + "node_modules/@epic-web/invariant": {
23 + "version": "1.0.0",
24 + "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz",
25 + "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==",
26 + "license": "MIT"
27 + },
28 + "node_modules/@phc/format": {
29 + "version": "1.0.0",
30 + "resolved": "https://registry.npmjs.org/@phc/format/-/format-1.0.0.tgz",
31 + "integrity": "sha512-m7X9U6BG2+J+R1lSOdCiITLLrxm+cWlNI3HUFA92oLO77ObGNzaKdh8pMLqdZcshtkKuV84olNNXDfMc4FezBQ==",
32 + "license": "MIT",
33 + "engines": {
34 + "node": ">=10"
35 + }
36 + },
37 + "node_modules/accepts": {
38 + "version": "2.0.0",
39 + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
40 + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
41 + "license": "MIT",
42 + "dependencies": {
43 + "mime-types": "^3.0.0",
44 + "negotiator": "^1.0.0"
45 + },
46 + "engines": {
47 + "node": ">= 0.6"
48 + }
49 + },
50 + "node_modules/argon2": {
51 + "version": "0.44.0",
52 + "resolved": "https://registry.npmjs.org/argon2/-/argon2-0.44.0.tgz",
53 + "integrity": "sha512-zHPGN3S55sihSQo0dBbK0A5qpi2R31z7HZDZnry3ifOyj8bZZnpZND2gpmhnRGO1V/d555RwBqIK5W4Mrmv3ig==",
54 + "hasInstallScript": true,
55 + "license": "MIT",
56 + "dependencies": {
57 + "@phc/format": "^1.0.0",
58 + "cross-env": "^10.0.0",
59 + "node-addon-api": "^8.5.0",
60 + "node-gyp-build": "^4.8.4"
61 + },
62 + "engines": {
63 + "node": ">=16.17.0"
64 + }
65 + },
66 + "node_modules/body-parser": {
67 + "version": "2.3.0",
68 + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
69 + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
70 + "license": "MIT",
71 + "dependencies": {
72 + "bytes": "^3.1.2",
73 + "content-type": "^2.0.0",
74 + "debug": "^4.4.3",
75 + "http-errors": "^2.0.1",
76 + "iconv-lite": "^0.7.2",
77 + "on-finished": "^2.4.1",
78 + "qs": "^6.15.2",
79 + "raw-body": "^3.0.2",
80 + "type-is": "^2.1.0"
81 + },
82 + "engines": {
83 + "node": ">=18"
84 + },
85 + "funding": {
86 + "type": "opencollective",
87 + "url": "https://opencollective.com/express"
88 + }
89 + },
90 + "node_modules/body-parser/node_modules/content-type": {
91 + "version": "2.1.0",
92 + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
93 + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
94 + "license": "MIT",
95 + "engines": {
96 + "node": ">=18"
97 + },
98 + "funding": {
99 + "type": "opencollective",
100 + "url": "https://opencollective.com/express"
101 + }
102 + },
103 + "node_modules/buffer-equal-constant-time": {
104 + "version": "1.0.1",
105 + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
106 + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
107 + "license": "BSD-3-Clause"
108 + },
109 + "node_modules/bytes": {
110 + "version": "3.1.2",
111 + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
112 + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
113 + "license": "MIT",
114 + "engines": {
115 + "node": ">= 0.8"
116 + }
117 + },
118 + "node_modules/call-bind-apply-helpers": {
119 + "version": "1.0.2",
120 + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
121 + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
122 + "license": "MIT",
123 + "dependencies": {
124 + "es-errors": "^1.3.0",
125 + "function-bind": "^1.1.2"
126 + },
127 + "engines": {
128 + "node": ">= 0.4"
129 + }
130 + },
131 + "node_modules/call-bound": {
132 + "version": "1.0.4",
133 + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
134 + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
135 + "license": "MIT",
136 + "dependencies": {
137 + "call-bind-apply-helpers": "^1.0.2",
138 + "get-intrinsic": "^1.3.0"
139 + },
140 + "engines": {
141 + "node": ">= 0.4"
142 + },
143 + "funding": {
144 + "url": "https://github.com/sponsors/ljharb"
145 + }
146 + },
147 + "node_modules/content-disposition": {
148 + "version": "1.1.0",
149 + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
150 + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
151 + "license": "MIT",
152 + "engines": {
153 + "node": ">=18"
154 + },
155 + "funding": {
156 + "type": "opencollective",
157 + "url": "https://opencollective.com/express"
158 + }
159 + },
160 + "node_modules/content-type": {
161 + "version": "1.0.5",
162 + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
163 + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
164 + "license": "MIT",
165 + "engines": {
166 + "node": ">= 0.6"
167 + }
168 + },
169 + "node_modules/cookie": {
170 + "version": "0.7.2",
171 + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
172 + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
173 + "license": "MIT",
174 + "engines": {
175 + "node": ">= 0.6"
176 + }
177 + },
178 + "node_modules/cookie-signature": {
179 + "version": "1.2.2",
180 + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
181 + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
182 + "license": "MIT",
183 + "engines": {
184 + "node": ">=6.6.0"
185 + }
186 + },
187 + "node_modules/cors": {
188 + "version": "2.8.6",
189 + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
190 + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
191 + "license": "MIT",
192 + "dependencies": {
193 + "object-assign": "^4",
194 + "vary": "^1"
195 + },
196 + "engines": {
197 + "node": ">= 0.10"
198 + },
199 + "funding": {
200 + "type": "opencollective",
201 + "url": "https://opencollective.com/express"
202 + }
203 + },
204 + "node_modules/cross-env": {
205 + "version": "10.1.0",
206 + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz",
207 + "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==",
208 + "license": "MIT",
209 + "dependencies": {
210 + "@epic-web/invariant": "^1.0.0",
211 + "cross-spawn": "^7.0.6"
212 + },
213 + "bin": {
214 + "cross-env": "dist/bin/cross-env.js",
215 + "cross-env-shell": "dist/bin/cross-env-shell.js"
216 + },
217 + "engines": {
218 + "node": ">=20"
219 + }
220 + },
221 + "node_modules/cross-spawn": {
222 + "version": "7.0.6",
223 + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
224 + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
225 + "license": "MIT",
226 + "dependencies": {
227 + "path-key": "^3.1.0",
228 + "shebang-command": "^2.0.0",
229 + "which": "^2.0.1"
230 + },
231 + "engines": {
232 + "node": ">= 8"
233 + }
234 + },
235 + "node_modules/debug": {
236 + "version": "4.4.3",
237 + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
238 + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
239 + "license": "MIT",
240 + "dependencies": {
241 + "ms": "^2.1.3"
242 + },
243 + "engines": {
244 + "node": ">=6.0"
245 + },
246 + "peerDependenciesMeta": {
247 + "supports-color": {
248 + "optional": true
249 + }
250 + }
251 + },
252 + "node_modules/depd": {
253 + "version": "2.0.0",
254 + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
255 + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
256 + "license": "MIT",
257 + "engines": {
258 + "node": ">= 0.8"
259 + }
260 + },
261 + "node_modules/dunder-proto": {
262 + "version": "1.0.1",
263 + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
264 + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
265 + "license": "MIT",
266 + "dependencies": {
267 + "call-bind-apply-helpers": "^1.0.1",
268 + "es-errors": "^1.3.0",
269 + "gopd": "^1.2.0"
270 + },
271 + "engines": {
272 + "node": ">= 0.4"
273 + }
274 + },
275 + "node_modules/ecdsa-sig-formatter": {
276 + "version": "1.0.11",
277 + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
278 + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
279 + "license": "Apache-2.0",
280 + "dependencies": {
281 + "safe-buffer": "^5.0.1"
282 + }
283 + },
284 + "node_modules/ee-first": {
285 + "version": "1.1.1",
286 + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
287 + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
288 + "license": "MIT"
289 + },
290 + "node_modules/encodeurl": {
291 + "version": "2.0.0",
292 + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
293 + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
294 + "license": "MIT",
295 + "engines": {
296 + "node": ">= 0.8"
297 + }
298 + },
299 + "node_modules/es-define-property": {
300 + "version": "1.0.1",
301 + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
302 + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
303 + "license": "MIT",
304 + "engines": {
305 + "node": ">= 0.4"
306 + }
307 + },
308 + "node_modules/es-errors": {
309 + "version": "1.3.0",
310 + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
311 + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
312 + "license": "MIT",
313 + "engines": {
314 + "node": ">= 0.4"
315 + }
316 + },
317 + "node_modules/es-object-atoms": {
318 + "version": "1.1.2",
319 + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
320 + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
321 + "license": "MIT",
322 + "dependencies": {
323 + "es-errors": "^1.3.0"
324 + },
325 + "engines": {
326 + "node": ">= 0.4"
327 + }
328 + },
329 + "node_modules/escape-html": {
330 + "version": "1.0.3",
331 + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
332 + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
333 + "license": "MIT"
334 + },
335 + "node_modules/etag": {
336 + "version": "1.8.1",
337 + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
338 + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
339 + "license": "MIT",
340 + "engines": {
341 + "node": ">= 0.6"
342 + }
343 + },
344 + "node_modules/express": {
345 + "version": "5.2.1",
346 + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
347 + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
348 + "license": "MIT",
349 + "dependencies": {
350 + "accepts": "^2.0.0",
351 + "body-parser": "^2.2.1",
352 + "content-disposition": "^1.0.0",
353 + "content-type": "^1.0.5",
354 + "cookie": "^0.7.1",
355 + "cookie-signature": "^1.2.1",
356 + "debug": "^4.4.0",
357 + "depd": "^2.0.0",
358 + "encodeurl": "^2.0.0",
359 + "escape-html": "^1.0.3",
360 + "etag": "^1.8.1",
361 + "finalhandler": "^2.1.0",
362 + "fresh": "^2.0.0",
363 + "http-errors": "^2.0.0",
364 + "merge-descriptors": "^2.0.0",
365 + "mime-types": "^3.0.0",
366 + "on-finished": "^2.4.1",
367 + "once": "^1.4.0",
368 + "parseurl": "^1.3.3",
369 + "proxy-addr": "^2.0.7",
370 + "qs": "^6.14.0",
371 + "range-parser": "^1.2.1",
372 + "router": "^2.2.0",
373 + "send": "^1.1.0",
374 + "serve-static": "^2.2.0",
375 + "statuses": "^2.0.1",
376 + "type-is": "^2.0.1",
377 + "vary": "^1.1.2"
378 + },
379 + "engines": {
380 + "node": ">= 18"
381 + },
382 + "funding": {
383 + "type": "opencollective",
384 + "url": "https://opencollective.com/express"
385 + }
386 + },
387 + "node_modules/finalhandler": {
388 + "version": "2.1.1",
389 + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
390 + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
391 + "license": "MIT",
392 + "dependencies": {
393 + "debug": "^4.4.0",
394 + "encodeurl": "^2.0.0",
395 + "escape-html": "^1.0.3",
396 + "on-finished": "^2.4.1",
397 + "parseurl": "^1.3.3",
398 + "statuses": "^2.0.1"
399 + },
400 + "engines": {
401 + "node": ">= 18.0.0"
402 + },
403 + "funding": {
404 + "type": "opencollective",
405 + "url": "https://opencollective.com/express"
406 + }
407 + },
408 + "node_modules/forwarded": {
409 + "version": "0.2.0",
410 + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
411 + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
412 + "license": "MIT",
413 + "engines": {
414 + "node": ">= 0.6"
415 + }
416 + },
417 + "node_modules/fresh": {
418 + "version": "2.0.0",
419 + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
420 + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
421 + "license": "MIT",
422 + "engines": {
423 + "node": ">= 0.8"
424 + }
425 + },
426 + "node_modules/function-bind": {
427 + "version": "1.1.2",
428 + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
429 + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
430 + "license": "MIT",
431 + "funding": {
432 + "url": "https://github.com/sponsors/ljharb"
433 + }
434 + },
435 + "node_modules/get-intrinsic": {
436 + "version": "1.3.0",
437 + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
438 + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
439 + "license": "MIT",
440 + "dependencies": {
441 + "call-bind-apply-helpers": "^1.0.2",
442 + "es-define-property": "^1.0.1",
443 + "es-errors": "^1.3.0",
444 + "es-object-atoms": "^1.1.1",
445 + "function-bind": "^1.1.2",
446 + "get-proto": "^1.0.1",
447 + "gopd": "^1.2.0",
448 + "has-symbols": "^1.1.0",
449 + "hasown": "^2.0.2",
450 + "math-intrinsics": "^1.1.0"
451 + },
452 + "engines": {
453 + "node": ">= 0.4"
454 + },
455 + "funding": {
456 + "url": "https://github.com/sponsors/ljharb"
457 + }
458 + },
459 + "node_modules/get-proto": {
460 + "version": "1.0.1",
461 + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
462 + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
463 + "license": "MIT",
464 + "dependencies": {
465 + "dunder-proto": "^1.0.1",
466 + "es-object-atoms": "^1.0.0"
467 + },
468 + "engines": {
469 + "node": ">= 0.4"
470 + }
471 + },
472 + "node_modules/gopd": {
473 + "version": "1.2.0",
474 + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
475 + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
476 + "license": "MIT",
477 + "engines": {
478 + "node": ">= 0.4"
479 + },
480 + "funding": {
481 + "url": "https://github.com/sponsors/ljharb"
482 + }
483 + },
484 + "node_modules/has-symbols": {
485 + "version": "1.1.0",
486 + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
487 + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
488 + "license": "MIT",
489 + "engines": {
490 + "node": ">= 0.4"
491 + },
492 + "funding": {
493 + "url": "https://github.com/sponsors/ljharb"
494 + }
495 + },
496 + "node_modules/hasown": {
497 + "version": "2.0.4",
498 + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
499 + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
500 + "license": "MIT",
501 + "dependencies": {
502 + "function-bind": "^1.1.2"
503 + },
504 + "engines": {
505 + "node": ">= 0.4"
506 + }
507 + },
508 + "node_modules/http-errors": {
509 + "version": "2.0.1",
510 + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
511 + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
512 + "license": "MIT",
513 + "dependencies": {
514 + "depd": "~2.0.0",
515 + "inherits": "~2.0.4",
516 + "setprototypeof": "~1.2.0",
517 + "statuses": "~2.0.2",
518 + "toidentifier": "~1.0.1"
519 + },
520 + "engines": {
521 + "node": ">= 0.8"
522 + },
523 + "funding": {
524 + "type": "opencollective",
525 + "url": "https://opencollective.com/express"
526 + }
527 + },
528 + "node_modules/iconv-lite": {
529 + "version": "0.7.3",
530 + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
531 + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
532 + "license": "MIT",
533 + "dependencies": {
534 + "safer-buffer": ">= 2.1.2 < 3.0.0"
535 + },
536 + "engines": {
537 + "node": ">=0.10.0"
538 + },
539 + "funding": {
540 + "type": "opencollective",
541 + "url": "https://opencollective.com/express"
542 + }
543 + },
544 + "node_modules/inherits": {
545 + "version": "2.0.4",
546 + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
547 + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
548 + "license": "ISC"
549 + },
550 + "node_modules/ipaddr.js": {
551 + "version": "1.9.1",
552 + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
553 + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
554 + "license": "MIT",
555 + "engines": {
556 + "node": ">= 0.10"
557 + }
558 + },
559 + "node_modules/is-promise": {
560 + "version": "4.0.0",
561 + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
562 + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
563 + "license": "MIT"
564 + },
565 + "node_modules/isexe": {
566 + "version": "2.0.0",
567 + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
568 + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
569 + "license": "ISC"
570 + },
571 + "node_modules/jsonwebtoken": {
572 + "version": "9.0.3",
573 + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
574 + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
575 + "license": "MIT",
576 + "dependencies": {
577 + "jws": "^4.0.1",
578 + "lodash.includes": "^4.3.0",
579 + "lodash.isboolean": "^3.0.3",
580 + "lodash.isinteger": "^4.0.4",
581 + "lodash.isnumber": "^3.0.3",
582 + "lodash.isplainobject": "^4.0.6",
583 + "lodash.isstring": "^4.0.1",
584 + "lodash.once": "^4.0.0",
585 + "ms": "^2.1.1",
586 + "semver": "^7.5.4"
587 + },
588 + "engines": {
589 + "node": ">=12",
590 + "npm": ">=6"
591 + }
592 + },
593 + "node_modules/jwa": {
594 + "version": "2.0.1",
595 + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
596 + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
597 + "license": "MIT",
598 + "dependencies": {
599 + "buffer-equal-constant-time": "^1.0.1",
600 + "ecdsa-sig-formatter": "1.0.11",
601 + "safe-buffer": "^5.0.1"
602 + }
603 + },
604 + "node_modules/jws": {
605 + "version": "4.0.1",
606 + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
607 + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
608 + "license": "MIT",
609 + "dependencies": {
610 + "jwa": "^2.0.1",
611 + "safe-buffer": "^5.0.1"
612 + }
613 + },
614 + "node_modules/lodash.includes": {
615 + "version": "4.3.0",
616 + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
617 + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
618 + "license": "MIT"
619 + },
620 + "node_modules/lodash.isboolean": {
621 + "version": "3.0.3",
622 + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
623 + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
624 + "license": "MIT"
625 + },
626 + "node_modules/lodash.isinteger": {
627 + "version": "4.0.4",
628 + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
629 + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
630 + "license": "MIT"
631 + },
632 + "node_modules/lodash.isnumber": {
633 + "version": "3.0.3",
634 + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
635 + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
636 + "license": "MIT"
637 + },
638 + "node_modules/lodash.isplainobject": {
639 + "version": "4.0.6",
640 + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
641 + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
642 + "license": "MIT"
643 + },
644 + "node_modules/lodash.isstring": {
645 + "version": "4.0.1",
646 + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
647 + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
648 + "license": "MIT"
649 + },
650 + "node_modules/lodash.once": {
651 + "version": "4.1.1",
652 + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
653 + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
654 + "license": "MIT"
655 + },
656 + "node_modules/math-intrinsics": {
657 + "version": "1.1.0",
658 + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
659 + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
660 + "license": "MIT",
661 + "engines": {
662 + "node": ">= 0.4"
663 + }
664 + },
665 + "node_modules/media-typer": {
666 + "version": "1.1.1",
667 + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz",
668 + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==",
669 + "license": "MIT",
670 + "engines": {
671 + "node": ">= 0.8"
672 + },
673 + "funding": {
674 + "type": "opencollective",
675 + "url": "https://opencollective.com/express"
676 + }
677 + },
678 + "node_modules/merge-descriptors": {
679 + "version": "2.0.0",
680 + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
681 + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
682 + "license": "MIT",
683 + "engines": {
684 + "node": ">=18"
685 + },
686 + "funding": {
687 + "url": "https://github.com/sponsors/sindresorhus"
688 + }
689 + },
690 + "node_modules/mime-db": {
691 + "version": "1.54.0",
692 + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
693 + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
694 + "license": "MIT",
695 + "engines": {
696 + "node": ">= 0.6"
697 + }
698 + },
699 + "node_modules/mime-types": {
700 + "version": "3.0.2",
701 + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
702 + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
703 + "license": "MIT",
704 + "dependencies": {
705 + "mime-db": "^1.54.0"
706 + },
707 + "engines": {
708 + "node": ">=18"
709 + },
710 + "funding": {
711 + "type": "opencollective",
712 + "url": "https://opencollective.com/express"
713 + }
714 + },
715 + "node_modules/ms": {
716 + "version": "2.1.3",
717 + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
718 + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
719 + "license": "MIT"
720 + },
721 + "node_modules/negotiator": {
722 + "version": "1.1.0",
723 + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz",
724 + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==",
725 + "license": "MIT",
726 + "dependencies": {
727 + "content-type": "^2.1.0"
728 + },
729 + "engines": {
730 + "node": ">=18"
731 + },
732 + "funding": {
733 + "type": "opencollective",
734 + "url": "https://opencollective.com/express"
735 + }
736 + },
737 + "node_modules/negotiator/node_modules/content-type": {
738 + "version": "2.1.0",
739 + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
740 + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
741 + "license": "MIT",
742 + "engines": {
743 + "node": ">=18"
744 + },
745 + "funding": {
746 + "type": "opencollective",
747 + "url": "https://opencollective.com/express"
748 + }
749 + },
750 + "node_modules/node-addon-api": {
751 + "version": "8.9.2",
752 + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz",
753 + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==",
754 + "license": "MIT",
755 + "engines": {
756 + "node": "^18 || ^20 || >= 21"
757 + }
758 + },
759 + "node_modules/node-gyp-build": {
760 + "version": "4.8.4",
761 + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
762 + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
763 + "license": "MIT",
764 + "bin": {
765 + "node-gyp-build": "bin.js",
766 + "node-gyp-build-optional": "optional.js",
767 + "node-gyp-build-test": "build-test.js"
768 + }
769 + },
770 + "node_modules/nodemailer": {
771 + "version": "10.0.16",
772 + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.16.tgz",
773 + "integrity": "sha512-VL9xKErxN+el77o8eBOuYKUPMyEx7F9hfnDCuiUKJRp9v3wnWMOudYgP/SWbwSHy8rUL4cylobuXtki1LpQS7A==",
774 + "license": "MIT-0",
775 + "engines": {
776 + "node": ">=20.0.0"
777 + }
778 + },
779 + "node_modules/object-assign": {
780 + "version": "4.1.1",
781 + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
782 + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
783 + "license": "MIT",
784 + "engines": {
785 + "node": ">=0.10.0"
786 + }
787 + },
788 + "node_modules/object-inspect": {
789 + "version": "1.13.4",
790 + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
791 + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
792 + "license": "MIT",
793 + "engines": {
794 + "node": ">= 0.4"
795 + },
796 + "funding": {
797 + "url": "https://github.com/sponsors/ljharb"
798 + }
799 + },
800 + "node_modules/on-finished": {
801 + "version": "2.4.1",
802 + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
803 + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
804 + "license": "MIT",
805 + "dependencies": {
806 + "ee-first": "1.1.1"
807 + },
808 + "engines": {
809 + "node": ">= 0.8"
810 + }
811 + },
812 + "node_modules/once": {
813 + "version": "1.4.0",
814 + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
815 + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
816 + "license": "ISC",
817 + "dependencies": {
818 + "wrappy": "1"
819 + }
820 + },
821 + "node_modules/parseurl": {
822 + "version": "1.3.3",
823 + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
824 + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
825 + "license": "MIT",
826 + "engines": {
827 + "node": ">= 0.8"
828 + }
829 + },
830 + "node_modules/path-key": {
831 + "version": "3.1.1",
832 + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
833 + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
834 + "license": "MIT",
835 + "engines": {
836 + "node": ">=8"
837 + }
838 + },
839 + "node_modules/path-to-regexp": {
840 + "version": "8.4.2",
841 + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
842 + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
843 + "license": "MIT",
844 + "funding": {
845 + "type": "opencollective",
846 + "url": "https://opencollective.com/express"
847 + }
848 + },
849 + "node_modules/pg": {
850 + "version": "8.23.1",
851 + "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
852 + "integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
853 + "license": "MIT",
854 + "dependencies": {
855 + "pg-connection-string": "^2.14.1",
856 + "pg-pool": "^3.14.0",
857 + "pg-protocol": "^1.16.1",
858 + "pg-types": "2.2.0",
859 + "pgpass": "1.0.5"
860 + },
861 + "engines": {
862 + "node": ">= 16.0.0"
863 + },
864 + "optionalDependencies": {
865 + "pg-cloudflare": "^1.4.1"
866 + },
867 + "peerDependencies": {
868 + "pg-native": ">=3.0.1"
869 + },
870 + "peerDependenciesMeta": {
871 + "pg-native": {
872 + "optional": true
873 + }
874 + }
875 + },
876 + "node_modules/pg-cloudflare": {
877 + "version": "1.4.1",
878 + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
879 + "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
880 + "license": "MIT",
881 + "optional": true
882 + },
883 + "node_modules/pg-connection-string": {
884 + "version": "2.14.1",
885 + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
886 + "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
887 + "license": "MIT"
888 + },
889 + "node_modules/pg-int8": {
890 + "version": "1.0.1",
891 + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
892 + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
893 + "license": "ISC",
894 + "engines": {
895 + "node": ">=4.0.0"
896 + }
897 + },
898 + "node_modules/pg-pool": {
899 + "version": "3.14.0",
900 + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
901 + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
902 + "license": "MIT",
903 + "peerDependencies": {
904 + "pg": ">=8.0"
905 + }
906 + },
907 + "node_modules/pg-protocol": {
908 + "version": "1.16.1",
909 + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
910 + "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
911 + "license": "MIT"
912 + },
913 + "node_modules/pg-types": {
914 + "version": "2.2.0",
915 + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
916 + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
917 + "license": "MIT",
918 + "dependencies": {
919 + "pg-int8": "1.0.1",
920 + "postgres-array": "~2.0.0",
921 + "postgres-bytea": "~1.0.0",
922 + "postgres-date": "~1.0.4",
923 + "postgres-interval": "^1.1.0"
924 + },
925 + "engines": {
926 + "node": ">=4"
927 + }
928 + },
929 + "node_modules/pgpass": {
930 + "version": "1.0.5",
931 + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
932 + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
933 + "license": "MIT",
934 + "dependencies": {
935 + "split2": "^4.1.0"
936 + }
937 + },
938 + "node_modules/postgres-array": {
939 + "version": "2.0.0",
940 + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
941 + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
942 + "license": "MIT",
943 + "engines": {
944 + "node": ">=4"
945 + }
946 + },
947 + "node_modules/postgres-bytea": {
948 + "version": "1.0.1",
949 + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
950 + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
951 + "license": "MIT",
952 + "engines": {
953 + "node": ">=0.10.0"
954 + }
955 + },
956 + "node_modules/postgres-date": {
957 + "version": "1.0.7",
958 + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
959 + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
960 + "license": "MIT",
961 + "engines": {
962 + "node": ">=0.10.0"
963 + }
964 + },
965 + "node_modules/postgres-interval": {
966 + "version": "1.2.0",
967 + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
968 + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
969 + "license": "MIT",
970 + "dependencies": {
971 + "xtend": "^4.0.0"
972 + },
973 + "engines": {
974 + "node": ">=0.10.0"
975 + }
976 + },
977 + "node_modules/proxy-addr": {
978 + "version": "2.0.8",
979 + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
980 + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
981 + "license": "MIT",
982 + "dependencies": {
983 + "forwarded": "0.2.0",
984 + "ipaddr.js": "1.9.1"
985 + },
986 + "engines": {
987 + "node": ">= 0.10"
988 + },
989 + "funding": {
990 + "type": "opencollective",
991 + "url": "https://opencollective.com/express"
992 + }
993 + },
994 + "node_modules/qs": {
995 + "version": "6.16.0",
996 + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
997 + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
998 + "license": "BSD-3-Clause",
999 + "dependencies": {
1000 + "es-define-property": "^1.0.1",
1001 + "side-channel": "^1.1.1"
1002 + },
1003 + "engines": {
1004 + "node": ">=0.6"
1005 + },
1006 + "funding": {
1007 + "url": "https://github.com/sponsors/ljharb"
1008 + }
1009 + },
1010 + "node_modules/range-parser": {
1011 + "version": "1.3.0",
1012 + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
1013 + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",
1014 + "license": "MIT",
1015 + "engines": {
1016 + "node": ">= 0.6"
1017 + },
1018 + "funding": {
1019 + "type": "opencollective",
1020 + "url": "https://opencollective.com/express"
1021 + }
1022 + },
1023 + "node_modules/raw-body": {
1024 + "version": "3.0.2",
1025 + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
1026 + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
1027 + "license": "MIT",
1028 + "dependencies": {
1029 + "bytes": "~3.1.2",
1030 + "http-errors": "~2.0.1",
1031 + "iconv-lite": "~0.7.0",
1032 + "unpipe": "~1.0.0"
1033 + },
1034 + "engines": {
1035 + "node": ">= 0.10"
1036 + }
1037 + },
1038 + "node_modules/router": {
1039 + "version": "2.2.0",
1040 + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
1041 + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
1042 + "license": "MIT",
1043 + "dependencies": {
1044 + "debug": "^4.4.0",
1045 + "depd": "^2.0.0",
1046 + "is-promise": "^4.0.0",
1047 + "parseurl": "^1.3.3",
1048 + "path-to-regexp": "^8.0.0"
1049 + },
1050 + "engines": {
1051 + "node": ">= 18"
1052 + }
1053 + },
1054 + "node_modules/safe-buffer": {
1055 + "version": "5.2.1",
1056 + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
1057 + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
1058 + "funding": [
1059 + {
1060 + "type": "github",
1061 + "url": "https://github.com/sponsors/feross"
1062 + },
1063 + {
1064 + "type": "patreon",
1065 + "url": "https://www.patreon.com/feross"
1066 + },
1067 + {
1068 + "type": "consulting",
1069 + "url": "https://feross.org/support"
1070 + }
1071 + ],
1072 + "license": "MIT"
1073 + },
1074 + "node_modules/safer-buffer": {
1075 + "version": "2.1.2",
1076 + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
1077 + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
1078 + "license": "MIT"
1079 + },
1080 + "node_modules/semver": {
1081 + "version": "7.8.5",
1082 + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
1083 + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
1084 + "license": "ISC",
1085 + "bin": {
1086 + "semver": "bin/semver.js"
1087 + },
1088 + "engines": {
1089 + "node": ">=10"
1090 + }
1091 + },
1092 + "node_modules/send": {
1093 + "version": "1.2.1",
1094 + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
1095 + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
1096 + "license": "MIT",
1097 + "dependencies": {
1098 + "debug": "^4.4.3",
1099 + "encodeurl": "^2.0.0",
1100 + "escape-html": "^1.0.3",
1101 + "etag": "^1.8.1",
1102 + "fresh": "^2.0.0",
1103 + "http-errors": "^2.0.1",
1104 + "mime-types": "^3.0.2",
1105 + "ms": "^2.1.3",
1106 + "on-finished": "^2.4.1",
1107 + "range-parser": "^1.2.1",
1108 + "statuses": "^2.0.2"
1109 + },
1110 + "engines": {
1111 + "node": ">= 18"
1112 + },
1113 + "funding": {
1114 + "type": "opencollective",
1115 + "url": "https://opencollective.com/express"
1116 + }
1117 + },
1118 + "node_modules/serve-static": {
1119 + "version": "2.2.1",
1120 + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
1121 + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
1122 + "license": "MIT",
1123 + "dependencies": {
1124 + "encodeurl": "^2.0.0",
1125 + "escape-html": "^1.0.3",
1126 + "parseurl": "^1.3.3",
1127 + "send": "^1.2.0"
1128 + },
1129 + "engines": {
1130 + "node": ">= 18"
1131 + },
1132 + "funding": {
1133 + "type": "opencollective",
1134 + "url": "https://opencollective.com/express"
1135 + }
1136 + },
1137 + "node_modules/setprototypeof": {
1138 + "version": "1.2.0",
1139 + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
1140 + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
1141 + "license": "ISC"
1142 + },
1143 + "node_modules/shebang-command": {
1144 + "version": "2.0.0",
1145 + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
1146 + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
1147 + "license": "MIT",
1148 + "dependencies": {
1149 + "shebang-regex": "^3.0.0"
1150 + },
1151 + "engines": {
1152 + "node": ">=8"
1153 + }
1154 + },
1155 + "node_modules/shebang-regex": {
1156 + "version": "3.0.0",
1157 + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
1158 + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
1159 + "license": "MIT",
1160 + "engines": {
1161 + "node": ">=8"
1162 + }
1163 + },
1164 + "node_modules/side-channel": {
1165 + "version": "1.1.1",
1166 + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
1167 + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
1168 + "license": "MIT",
1169 + "dependencies": {
1170 + "es-errors": "^1.3.0",
1171 + "object-inspect": "^1.13.4",
1172 + "side-channel-list": "^1.0.1",
1173 + "side-channel-map": "^1.0.1",
1174 + "side-channel-weakmap": "^1.0.2"
1175 + },
1176 + "engines": {
1177 + "node": ">= 0.4"
1178 + },
1179 + "funding": {
1180 + "url": "https://github.com/sponsors/ljharb"
1181 + }
1182 + },
1183 + "node_modules/side-channel-list": {
1184 + "version": "1.0.1",
1185 + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
1186 + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
1187 + "license": "MIT",
1188 + "dependencies": {
1189 + "es-errors": "^1.3.0",
1190 + "object-inspect": "^1.13.4"
1191 + },
1192 + "engines": {
1193 + "node": ">= 0.4"
1194 + },
1195 + "funding": {
1196 + "url": "https://github.com/sponsors/ljharb"
1197 + }
1198 + },
1199 + "node_modules/side-channel-map": {
1200 + "version": "1.0.1",
1201 + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
1202 + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
1203 + "license": "MIT",
1204 + "dependencies": {
1205 + "call-bound": "^1.0.2",
1206 + "es-errors": "^1.3.0",
1207 + "get-intrinsic": "^1.2.5",
1208 + "object-inspect": "^1.13.3"
1209 + },
1210 + "engines": {
1211 + "node": ">= 0.4"
1212 + },
1213 + "funding": {
1214 + "url": "https://github.com/sponsors/ljharb"
1215 + }
1216 + },
1217 + "node_modules/side-channel-weakmap": {
1218 + "version": "1.0.2",
1219 + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
1220 + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
1221 + "license": "MIT",
1222 + "dependencies": {
1223 + "call-bound": "^1.0.2",
1224 + "es-errors": "^1.3.0",
1225 + "get-intrinsic": "^1.2.5",
1226 + "object-inspect": "^1.13.3",
1227 + "side-channel-map": "^1.0.1"
1228 + },
1229 + "engines": {
1230 + "node": ">= 0.4"
1231 + },
1232 + "funding": {
1233 + "url": "https://github.com/sponsors/ljharb"
1234 + }
1235 + },
1236 + "node_modules/split2": {
1237 + "version": "4.2.0",
1238 + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
1239 + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
1240 + "license": "ISC",
1241 + "engines": {
1242 + "node": ">= 10.x"
1243 + }
1244 + },
1245 + "node_modules/statuses": {
1246 + "version": "2.0.2",
1247 + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
1248 + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
1249 + "license": "MIT",
1250 + "engines": {
1251 + "node": ">= 0.8"
1252 + }
1253 + },
1254 + "node_modules/toidentifier": {
1255 + "version": "1.0.1",
1256 + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
1257 + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
1258 + "license": "MIT",
1259 + "engines": {
1260 + "node": ">=0.6"
1261 + }
1262 + },
1263 + "node_modules/type-is": {
1264 + "version": "2.1.0",
1265 + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
1266 + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
1267 + "license": "MIT",
1268 + "dependencies": {
1269 + "content-type": "^2.0.0",
1270 + "media-typer": "^1.1.0",
1271 + "mime-types": "^3.0.0"
1272 + },
1273 + "engines": {
1274 + "node": ">= 18"
1275 + },
1276 + "funding": {
1277 + "type": "opencollective",
1278 + "url": "https://opencollective.com/express"
1279 + }
1280 + },
1281 + "node_modules/type-is/node_modules/content-type": {
1282 + "version": "2.1.0",
1283 + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
1284 + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
1285 + "license": "MIT",
1286 + "engines": {
1287 + "node": ">=18"
1288 + },
1289 + "funding": {
1290 + "type": "opencollective",
1291 + "url": "https://opencollective.com/express"
1292 + }
1293 + },
1294 + "node_modules/unpipe": {
1295 + "version": "1.0.0",
1296 + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
1297 + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
1298 + "license": "MIT",
1299 + "engines": {
1300 + "node": ">= 0.8"
1301 + }
1302 + },
1303 + "node_modules/vary": {
1304 + "version": "1.1.2",
1305 + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
1306 + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
1307 + "license": "MIT",
1308 + "engines": {
1309 + "node": ">= 0.8"
1310 + }
1311 + },
1312 + "node_modules/which": {
1313 + "version": "2.0.2",
1314 + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
1315 + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
1316 + "license": "ISC",
1317 + "dependencies": {
1318 + "isexe": "^2.0.0"
1319 + },
1320 + "bin": {
1321 + "node-which": "bin/node-which"
1322 + },
1323 + "engines": {
1324 + "node": ">= 8"
1325 + }
1326 + },
1327 + "node_modules/wrappy": {
1328 + "version": "1.0.2",
1329 + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
1330 + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
1331 + "license": "ISC"
1332 + },
1333 + "node_modules/xtend": {
1334 + "version": "4.0.2",
1335 + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
1336 + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
1337 + "license": "MIT",
1338 + "engines": {
1339 + "node": ">=0.4"
1340 + }
1341 + }
1342 + }
1343 +}
backend/package.json
+7 -5
@@ -1,21 +1,23 @@
1 {
2 "name": "lifemate-backend",
3 "private": true,
4 - "version": "0.4.0",
4 + "version": "0.5.0",
5 "type": "module",
6 "scripts": {
7 "start": "node src/entrypoint.js",
8 "test": "node --test tests/*.test.js",
9 "migrate": "node scripts/migrate.js",
10 - "check": "node --check src/server.js && node --check src/phase3.js && node --check src/phase4.js && node --check src/phase6.js && node --check src/session_auth.js && node --check src/operations.js && node --check src/entrypoint.js"
10 + "check": "node scripts/check-syntax.js"
11 + },
12 + "engines": {
13 + "node": ">=22"
14 },
12 - "engines": {"node": ">=22"},
15 "dependencies": {
16 "argon2": "^0.44.0",
17 + "cors": "^2.8.5",
18 "express": "^5.1.0",
19 "jsonwebtoken": "^9.0.2",
17 - "pg": "^8.16.3",
20 "nodemailer": "^10.0.14",
19 - "cors": "^2.8.5"
21 + "pg": "^8.16.3"
22 }
23 }
backend/scripts/check-syntax.js new
+19
@@ -0,0 +1,19 @@
1 +import fs from 'node:fs';
2 +import path from 'node:path';
3 +import { spawnSync } from 'node:child_process';
4 +let checked = 0;
5 +for (const directory of ['src', 'scripts', 'tests']) {
6 + function walk(folder) {
7 + for (const entry of fs.readdirSync(folder, {withFileTypes: true})) {
8 + const file = path.join(folder, entry.name);
9 + if (entry.isDirectory()) walk(file);
10 + else if (/\.(js|mjs)$/.test(file)) {
11 + const result = spawnSync(process.execPath, ['--check', file], {stdio: 'inherit'});
12 + if (result.status !== 0) process.exit(result.status ?? 1);
13 + checked++;
14 + }
15 + }
16 + }
17 + walk(directory);
18 +}
19 +console.log(`Syntax checked ${checked} source/script/test files.`);
backend/scripts/migrate.js
+20 -5
@@ -1,5 +1,6 @@
1 import fs from 'node:fs/promises';
2 import path from 'node:path';
3 +import crypto from 'node:crypto';
4 import pg from 'pg';
5
6 const { Client } = pg;
@@ -28,12 +29,14 @@ const client = new Client(
29
30 await client.connect();
31 try {
32 + await client.query("select pg_advisory_lock(hashtextextended('lifemate_schema_migration',0))");
33 await client.query(`
34 create table if not exists schema_migration (
35 filename text primary key,
36 applied_at timestamptz not null default now()
37 )
38 `);
39 + await client.query('alter table schema_migration add column if not exists sha256 text');
40
41 const dir = path.resolve('migrations');
42 const files = (await fs.readdir(dir))
@@ -41,19 +44,31 @@ try {
44 .sort();
45
46 for (const filename of files) {
47 + const source = await fs.readFile(path.join(dir, filename), 'utf8');
48 + const checksum = crypto.createHash('sha256').update(source).digest('hex');
49 const exists = await client.query(
45 - 'select 1 from schema_migration where filename=$1',
50 + 'select sha256 from schema_migration where filename=$1',
51 [filename],
52 );
48 - if (exists.rowCount) continue;
53 + if (exists.rowCount) {
54 + const stored = exists.rows[0].sha256;
55 + if (stored && stored !== checksum) throw new Error(`Applied migration changed: ${filename}`);
56 + if (!stored) console.warn(`UNVERIFIED historical migration checksum: ${filename}`);
57 + continue;
58 + }
59
50 - const sql = await fs.readFile(path.join(dir, filename), 'utf8');
60 + // Existing files contain their own outer BEGIN/COMMIT. Keep the schema
61 + // and ledger insert in ONE transaction instead of committing the SQL early.
62 + const trimmed = source.trim();
63 + const sql = /^begin\s*;/i.test(trimmed) && /commit\s*;$/i.test(trimmed)
64 + ? trimmed.replace(/^begin\s*;/i, '').replace(/commit\s*;$/i, '')
65 + : source;
66 await client.query('begin');
67 try {
68 await client.query(sql);
69 await client.query(
55 - 'insert into schema_migration(filename) values($1)',
56 - [filename],
70 + 'insert into schema_migration(filename,sha256) values($1,$2)',
71 + [filename,checksum],
72 );
73 await client.query('commit');
74 console.log('applied', filename);
backend/src/auth_contacts.js new
+13
@@ -0,0 +1,13 @@
1 +export const normalizeEmail = (value) => String(value ?? '').trim().toLowerCase();
2 +export const isEmail = (value) => typeof value === 'string' && value.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
3 +export const validPassword = (value) => typeof value === 'string' && value.length >= 10 && value.length <= 200;
4 +
5 +export function normalizePhone(value) {
6 + let phone = String(value ?? '').trim().replace(/[۰-۹٠-٩]/g, (digit) => {
7 + const code = digit.charCodeAt(0);
8 + return String(code >= 0x6f0 ? code - 0x6f0 : code - 0x660);
9 + }).replace(/[\s()-]/g, '');
10 + if (/^09\d{9}$/.test(phone)) phone = '+98' + phone.slice(1);
11 + if (/^0098\d{10}$/.test(phone)) phone = '+' + phone.slice(2);
12 + return /^\+[1-9]\d{7,14}$/.test(phone) ? phone : null;
13 +}
backend/src/auth_delivery.js new
+75
@@ -0,0 +1,75 @@
1 +import crypto from 'node:crypto';
2 +import nodemailer from 'nodemailer';
3 +
4 +// Provider ports have no authority to create/verify users or issue sessions.
5 +export class SmsProvider {
6 + configured = false;
7 + status = 'UNVERIFIED';
8 + async sendOtp(_message) { return { delivered: false, reason: 'provider_unconfigured' }; }
9 +}
10 +
11 +export function createSmsProvider() {
12 + // No SMS carrier is selected or enabled. A real adapter needs explicit setup.
13 + return new SmsProvider();
14 +}
15 +
16 +export function createEmailProvider({ env = process.env, fetchImpl = fetch, transportFactory = nodemailer.createTransport } = {}) {
17 + const configured = env.NODE_ENV !== 'test' && Boolean(env.EMAIL_FROM && (env.RESEND_API_KEY || (env.SMTP_HOST && Number(env.SMTP_PORT) > 0)));
18 + return {
19 + configured,
20 + status: configured ? 'CONFIGURED_UNVERIFIED' : 'UNVERIFIED',
21 + async send({ to, subject, text, idempotencyKey }) {
22 + if (!configured) return { delivered: false, reason: 'provider_unconfigured' };
23 + if (env.RESEND_API_KEY) {
24 + const response = await fetchImpl('https://api.resend.com/emails', {
25 + method: 'POST', signal: AbortSignal.timeout(10000),
26 + headers: { Authorization: `Bearer ${env.RESEND_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey },
27 + body: JSON.stringify({ from: env.EMAIL_FROM, to: [to], subject, text }),
28 + });
29 + if (!response.ok) {
30 + const error = new Error('email_provider_rejected');
31 + error.retryable = response.status === 429 || response.status >= 500;
32 + throw error;
33 + }
34 + return { delivered: true };
35 + }
36 + const transport = transportFactory({
37 + host: env.SMTP_HOST, port: Number(env.SMTP_PORT), secure: env.SMTP_SECURE === 'true',
38 + connectionTimeout: 10000, greetingTimeout: 10000, socketTimeout: 10000,
39 + logger: false, debug: false,
40 + auth: env.SMTP_USER ? { user: env.SMTP_USER, pass: env.SMTP_PASSWORD } : undefined,
41 + });
42 + try {
43 + await transport.sendMail({ from: env.EMAIL_FROM, to, subject, text, messageId: `<${idempotencyKey}@lifeguide.invalid>` });
44 + return { delivered: true };
45 + } finally { transport.close?.(); }
46 + },
47 + };
48 +}
49 +
50 +export async function safelyDeliver(provider, message, { pool, attemptId, env = process.env } = {}) {
51 + let status = 'unconfigured';
52 + const idempotencyKey = attemptId ?? crypto.randomUUID();
53 + if (provider.configured) {
54 + for (let attempt = 0; attempt < 3; attempt++) {
55 + try {
56 + const result = await provider.send({ ...message, idempotencyKey });
57 + status = result?.delivered === true ? 'accepted' : 'failed';
58 + break;
59 + } catch (error) {
60 + status = 'failed';
61 + if (error?.retryable !== true || attempt === 2) break;
62 + await new Promise((resolve) => setTimeout(resolve, 250 * (2 ** attempt)));
63 + }
64 + }
65 + }
66 + if (pool && attemptId) {
67 + try { await pool.query('update auth_delivery_attempt set status=$2,updated_at=now() where id=$1', [attemptId, status]); }
68 + catch { /* Account/token is already committed; delivery bookkeeping cannot undo it. */ }
69 + }
70 + if (env.NODE_ENV !== 'test') {
71 + // Never serialize provider errors, recipients, tokens, message text or OTPs.
72 + console.log(JSON.stringify({ type: 'auth_delivery', status, attemptId: idempotencyKey }));
73 + }
74 + return { delivered: status === 'accepted', status };
75 +}
backend/src/auth_router.js new
+339
@@ -0,0 +1,339 @@
1 +import crypto from 'node:crypto';
2 +import express from 'express';
3 +import argon2 from 'argon2';
4 +import jwt from 'jsonwebtoken';
5 +import { normalizeEmail, normalizePhone, isEmail, validPassword } from './auth_contacts.js';
6 +import { createEmailProvider, createSmsProvider, safelyDeliver } from './auth_delivery.js';
7 +
8 +const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
9 +const randomToken = () => crypto.randomBytes(32).toString('base64url');
10 +const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
11 +
12 +async function transaction(pool, operation) {
13 + const client = await pool.connect();
14 + try {
15 + await client.query('begin');
16 + const result = await operation(client);
17 + await client.query('commit');
18 + return result;
19 + } catch (error) {
20 + await client.query('rollback').catch(() => {});
21 + throw error;
22 + } finally { client.release(); }
23 +}
24 +
25 +export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
26 + emailProvider = createEmailProvider({ env }), smsProvider = createSmsProvider() }) {
27 + const router = express.Router();
28 + const testMode = env.NODE_ENV === 'test';
29 + const publicApp = env.PUBLIC_APP_URL ?? 'https://app.lifeguide.invalid';
30 + const dummyHash = argon2.hash(randomToken(), { type: argon2.argon2id });
31 + const digest = (value) => crypto.createHmac('sha256', jwtSecret).update(value).digest('hex');
32 +
33 + async function oneTimeToken(client, userId, kind, minutes) {
34 + const raw = randomToken();
35 + await client.query(
36 + "insert into auth_token(user_id,kind,token_digest,expires_at) values($1,$2,$3,now()+($4 || ' minutes')::interval)",
37 + [userId, kind, sha256(raw), String(minutes)],
38 + );
39 + return raw;
40 + }
41 +
42 + async function usableToken(client, raw, kind) {
43 + const tokenDigest = sha256(raw);
44 + const owner = await client.query('select user_id from auth_token where token_digest=$1 and kind=$2', [tokenDigest, kind]);
45 + if (!owner.rowCount) return null;
46 + const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [owner.rows[0].user_id]);
47 + if (!active.rowCount) return null;
48 + const token = await client.query('select user_id from auth_token where token_digest=$1 and kind=$2 and used_at is null and expires_at>now() for update', [tokenDigest, kind]);
49 + return token.rows[0] ?? null;
50 + }
51 +
52 + async function session(client, userId) {
53 + const refreshToken = randomToken();
54 + const result = await client.query(
55 + "insert into auth_session(user_id,refresh_digest,expires_at) values($1,$2,now()+interval '30 days') returning id",
56 + [userId, sha256(refreshToken)],
57 + );
58 + return {
59 + accessToken: jwt.sign({ sub: userId, sid: result.rows[0].id, aud: 'lifemate-api' }, jwtSecret, { expiresIn: '15m', issuer: 'lifemate' }),
60 + refreshToken,
61 + };
62 + }
63 +
64 + async function claimDelivery(client, recipient, purpose, userId = null) {
65 + // The same limit is claimed before account lookup for known and unknown contacts.
66 + const recipientDigest = digest(`delivery:${recipient}`);
67 + await client.query('select pg_advisory_xact_lock(hashtextextended($1,0))', [recipientDigest + ':' + purpose]);
68 + const recent = await client.query(
69 + `select count(*)::int as n,
70 + ceil(extract(epoch from (max(requested_at)+interval '60 seconds'-now()))) as cooldown,
71 + ceil(extract(epoch from (min(requested_at)+interval '1 hour'-now()))) as window_wait
72 + from auth_delivery_attempt where recipient_digest=$1 and purpose=$2
73 + and requested_at>now()-interval '1 hour'`, [recipientDigest, purpose],
74 + );
75 + const row = recent.rows[0];
76 + const wait = row.n >= 3 ? Number(row.window_wait) : Number(row.cooldown);
77 + if (wait > 0) return { retryAfter: Math.max(1, wait) };
78 + const inserted = await client.query(
79 + 'insert into auth_delivery_attempt(recipient_digest,purpose,user_id) values($1,$2,$3) returning id',
80 + [recipientDigest, purpose, userId],
81 + );
82 + return { attemptId: inserted.rows[0].id };
83 + }
84 +
85 + function limited(res, result) {
86 + if (!result.retryAfter) return false;
87 + res.setHeader('Retry-After', String(result.retryAfter));
88 + res.status(429).json({ error: 'rate_limited' });
89 + return true;
90 + }
91 +
92 + async function emailDelivery(userEmail, raw, kind, attemptId) {
93 + const verify = kind === 'email_verification';
94 + return safelyDeliver(emailProvider, {
95 + to: userEmail,
96 + subject: verify ? 'تأیید حساب لایف‌گاید' : 'بازیابی رمز عبور لایف‌گاید',
97 + text: `${verify ? 'برای تأیید حساب LifeGuide / لایف‌گاید' : 'برای ساخت رمز جدید لایف‌گاید'} این لینک را باز کن: ${publicApp}/${verify ? 'verify-email' : 'reset-password'}?token=${encodeURIComponent(raw)}\nاین لینک ${verify ? '۲۴ ساعت' : '۳۰ دقیقه'} اعتبار دارد. اگر این درخواست را نداده‌ای، پیام را نادیده بگیر.`,
98 + }, { pool, attemptId, env });
99 + }
100 +
101 + router.get('/capabilities', (_req, res) => res.json({
102 + emailDeliveryAvailable: Boolean(emailProvider.configured),
103 + emailStatus: emailProvider.status ?? 'UNVERIFIED',
104 + smsAvailable: Boolean(smsProvider.configured),
105 + smsStatus: smsProvider.status ?? 'UNVERIFIED',
106 + }));
107 +
108 + router.post('/register', async (req, res) => {
109 + const email = normalizeEmail(req.body?.email);
110 + const phone = req.body?.phone == null ? null : normalizePhone(req.body.phone);
111 + const name = String(req.body?.displayName ?? '').trim();
112 + if (!name || name.length > 100 || !validPassword(req.body?.password) ||
113 + (email && phone) || (!email && !phone) || (email && !isEmail(email)) ||
114 + (req.body?.phone != null && !phone)) return res.status(400).json({ error: 'invalid_input' });
115 + if (phone && !smsProvider.configured) return res.status(503).json({ error: 'sms_unavailable' });
116 + // Always hash valid registration input, including duplicates; never replace credentials.
117 + const hash = await argon2.hash(req.body.password, { type: argon2.argon2id });
118 + const result = await transaction(pool, async (client) => {
119 + const rate = email ? await claimDelivery(client, email, 'email_verification') : {};
120 + const inserted = await client.query(
121 + 'insert into app_user(identity_subject,email_normalized,phone_normalized) values($1,$2,$3) on conflict do nothing returning id',
122 + [`local:${crypto.randomUUID()}`, email || null, phone],
123 + );
124 + if (!inserted.rowCount) return { ...rate };
125 + const userId = inserted.rows[0].id;
126 + await client.query("insert into profile(user_id,display_name,theme_preference) values($1,$2,'adult_blue')", [userId, name]);
127 + await client.query('insert into auth_credential(user_id,password_hash) values($1,$2)', [userId, hash]);
128 + let verificationToken;
129 + if (email) verificationToken = await oneTimeToken(client, userId, 'email_verification', 1440);
130 + if (rate.attemptId) await client.query('update auth_delivery_attempt set user_id=$2 where id=$1', [rate.attemptId, userId]);
131 + return { ...rate, userId, verificationToken };
132 + });
133 + // The response is sent before provider I/O, which cannot change a committed account response.
134 + res.status(testMode ? 201 : 202).json(testMode
135 + ? { accepted: true, userId: result.userId, verificationToken: result.verificationToken }
136 + : { accepted: true });
137 + if (result.verificationToken && result.attemptId) await emailDelivery(email, result.verificationToken, 'email_verification', result.attemptId);
138 + else if (result.attemptId) await pool.query("update auth_delivery_attempt set status='not_needed' where id=$1", [result.attemptId]).catch(() => {});
139 + });
140 +
141 + router.post('/resend-verification', async (req, res) => {
142 + const email = normalizeEmail(req.body?.email);
143 + if (!isEmail(email)) return res.status(400).json({ error: 'invalid_input' });
144 + const result = await transaction(pool, async (client) => {
145 + const rate = await claimDelivery(client, email, 'email_verification');
146 + if (rate.retryAfter) return rate;
147 + const user = await client.query('select id from app_user where email_normalized=$1 and email_verified_at is null and disabled_at is null for update', [email]);
148 + if (!user.rowCount) return rate;
149 + const token = await oneTimeToken(client, user.rows[0].id, 'email_verification', 1440);
150 + await client.query('update auth_delivery_attempt set user_id=$2 where id=$1', [rate.attemptId, user.rows[0].id]);
151 + return { ...rate, token };
152 + });
153 + if (limited(res, result)) return;
154 + res.status(202).json({ accepted: true });
155 + if (result.token) await emailDelivery(email, result.token, 'email_verification', result.attemptId);
156 + else await pool.query("update auth_delivery_attempt set status='not_needed' where id=$1", [result.attemptId]).catch(() => {});
157 + });
158 +
159 + router.post('/verify-email', async (req, res) => {
160 + if (!validPassword(req.body?.newPassword)) return res.status(400).json({ error: 'invalid_password' });
161 + const ok = await transaction(pool, async (client) => {
162 + const token = await usableToken(client, String(req.body?.token ?? ''), 'email_verification');
163 + if (!token) return false;
164 + const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
165 + await client.query('update auth_credential set password_hash=$2,password_changed_at=now() where user_id=$1', [token.user_id, hash]);
166 + await client.query('update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null', [token.user_id]);
167 + await client.query("update auth_token set used_at=now() where user_id=$1 and kind='email_verification' and used_at is null", [token.user_id]);
168 + await client.query('update app_user set email_verified_at=coalesce(email_verified_at,now()) where id=$1', [token.user_id]);
169 + return true;
170 + });
171 + if (!ok) return res.status(400).json({ error: 'invalid_or_expired_token' });
172 + res.status(204).end();
173 + });
174 +
175 + router.post('/login', async (req, res) => {
176 + const identifier = String(req.body?.identifier ?? req.body?.email ?? req.body?.phone ?? '').trim();
177 + const email = identifier.includes('@') ? normalizeEmail(identifier) : null;
178 + const phone = email ? null : normalizePhone(identifier);
179 + const result = await pool.query(
180 + `select u.id,u.email_verified_at,u.phone_verified_at,c.password_hash from app_user u
181 + join auth_credential c on c.user_id=u.id where u.disabled_at is null
182 + and (($1::text is not null and u.email_normalized=$1) or ($2::text is not null and u.phone_normalized=$2))`, [email, phone],
183 + );
184 + const password = String(req.body?.password ?? '');
185 + const matched = await argon2.verify(result.rows[0]?.password_hash ?? await dummyHash, password.slice(0, 200));
186 + if (!result.rowCount || password.length > 200 || !matched) return res.status(401).json({ error: 'invalid_credentials' });
187 + if (email ? !result.rows[0].email_verified_at : !result.rows[0].phone_verified_at) {
188 + return res.status(403).json({ error: email ? 'email_not_verified' : 'phone_not_verified' });
189 + }
190 + const tokens = await transaction(pool, async (client) => {
191 + const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [result.rows[0].id]);
192 + if (!active.rowCount) return null;
193 + const current = await client.query('select c.password_hash,u.email_verified_at,u.phone_verified_at from auth_credential c join app_user u on u.id=c.user_id where c.user_id=$1', [result.rows[0].id]);
194 + // Recovery may have committed while this request verified a previously read hash.
195 + if (!current.rowCount || current.rows[0].password_hash !== result.rows[0].password_hash ||
196 + (email ? !current.rows[0].email_verified_at : !current.rows[0].phone_verified_at)) return null;
197 + return session(client, result.rows[0].id);
198 + });
199 + if (!tokens) return res.status(401).json({ error: 'invalid_credentials' });
200 + res.json(tokens);
201 + });
202 +
203 + router.post('/refresh', async (req, res) => {
204 + const tokens = await transaction(pool, async (client) => {
205 + const preliminary = await client.query('select user_id from auth_session where refresh_digest=$1', [sha256(String(req.body?.refreshToken ?? ''))]);
206 + if (!preliminary.rowCount) return null;
207 + // Account-first locking is shared with password/OTP recovery.
208 + const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [preliminary.rows[0].user_id]);
209 + if (!active.rowCount) return null;
210 + const current = await client.query('select id,user_id from auth_session where refresh_digest=$1 and revoked_at is null and expires_at>now() for update', [sha256(String(req.body?.refreshToken ?? ''))]);
211 + if (!current.rowCount) return null;
212 + await client.query('update auth_session set revoked_at=now() where id=$1', [current.rows[0].id]);
213 + return session(client, current.rows[0].user_id);
214 + });
215 + if (!tokens) return res.status(401).json({ error: 'invalid_refresh_token' });
216 + res.json(tokens);
217 + });
218 +
219 + router.post('/forgot-password', async (req, res) => {
220 + const email = normalizeEmail(req.body?.email);
221 + if (!isEmail(email)) return res.json({ accepted: true });
222 + const result = await transaction(pool, async (client) => {
223 + const rate = await claimDelivery(client, email, 'password_reset');
224 + if (rate.retryAfter) return rate;
225 + const user = await client.query('select id from app_user where email_normalized=$1 and disabled_at is null for update', [email]);
226 + if (!user.rowCount) return rate;
227 + const token = await oneTimeToken(client, user.rows[0].id, 'password_reset', 30);
228 + await client.query('update auth_delivery_attempt set user_id=$2 where id=$1', [rate.attemptId, user.rows[0].id]);
229 + return { ...rate, token };
230 + });
231 + if (limited(res, result)) return;
232 + res.json(testMode ? { accepted: true, resetToken: result.token } : { accepted: true });
233 + if (result.token) await emailDelivery(email, result.token, 'password_reset', result.attemptId);
234 + else await pool.query("update auth_delivery_attempt set status='not_needed' where id=$1", [result.attemptId]).catch(() => {});
235 + });
236 +
237 + router.post('/reset-password', async (req, res) => {
238 + if (!validPassword(req.body?.newPassword)) return res.status(400).json({ error: 'invalid_password' });
239 + const ok = await transaction(pool, async (client) => {
240 + const token = await usableToken(client, String(req.body?.token ?? ''), 'password_reset');
241 + if (!token) return false;
242 + const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
243 + await client.query('update auth_credential set password_hash=$2,password_changed_at=now() where user_id=$1', [token.user_id, hash]);
244 + await client.query("update auth_token set used_at=now() where user_id=$1 and kind='password_reset' and used_at is null", [token.user_id]);
245 + await client.query('update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null', [token.user_id]);
246 + return true;
247 + });
248 + if (!ok) return res.status(400).json({ error: 'invalid_or_expired_token' });
249 + res.status(204).end();
250 + });
251 +
252 + router.post('/change-password', auth, async (req, res) => {
253 + if (!validPassword(req.body?.newPassword)) return res.status(400).json({ error: 'invalid_password' });
254 + const ok = await transaction(pool, async (client) => {
255 + const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [req.identity.sub]);
256 + if (!active.rowCount) return false;
257 + const credential = await client.query('select password_hash from auth_credential where user_id=$1 for update', [req.identity.sub]);
258 + if (!credential.rowCount || !(await argon2.verify(credential.rows[0].password_hash, String(req.body?.currentPassword ?? '')))) return false;
259 + const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
260 + await client.query('update auth_credential set password_hash=$2,password_changed_at=now() where user_id=$1', [req.identity.sub, hash]);
261 + await client.query('update auth_session set revoked_at=now() where user_id=$1 and id<>$2 and revoked_at is null', [req.identity.sub, req.identity.sid]);
262 + return true;
263 + });
264 + if (!ok) return res.status(403).json({ error: 'invalid_current_password' });
265 + res.status(204).end();
266 + });
267 +
268 + router.post('/logout', async (req, res) => {
269 + const refresh = req.body?.refreshToken;
270 + if (typeof refresh === 'string') {
271 + await pool.query('update auth_session set revoked_at=coalesce(revoked_at,now()) where refresh_digest=$1', [sha256(refresh)]);
272 + } else {
273 + let identity;
274 + try {
275 + identity = jwt.verify(req.headers.authorization?.replace(/^Bearer\s+/i, ''), jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' });
276 + } catch { /* Uniform logout also accepts expired, missing or revoked proof. */ }
277 + if (identity?.sid && identity?.sub) await pool.query('update auth_session set revoked_at=coalesce(revoked_at,now()) where id=$1 and user_id=$2', [identity.sid, identity.sub]);
278 + }
279 + res.status(204).end();
280 + });
281 +
282 + router.post('/phone/request-otp', async (req, res) => {
283 + if (!smsProvider.configured) return res.status(503).json({ error: 'sms_unavailable' });
284 + const phone = normalizePhone(req.body?.phone);
285 + const purpose = req.body?.purpose ?? 'login';
286 + if (!phone || !['verify', 'login', 'recovery'].includes(purpose)) return res.status(400).json({ error: 'invalid_input' });
287 + const result = await transaction(pool, async (client) => {
288 + const rate = await claimDelivery(client, phone, 'phone_otp');
289 + if (rate.retryAfter) return rate;
290 + const user = await client.query('select id from app_user where phone_normalized=$1 and disabled_at is null', [phone]);
291 + const challengeId = crypto.randomUUID();
292 + const code = String(crypto.randomInt(0, 1000000)).padStart(6, '0');
293 + await client.query("insert into auth_phone_challenge(id,user_id,purpose,code_digest,expires_at) values($1,$2,$3,$4,now()+interval '5 minutes')", [challengeId, user.rows[0]?.id ?? null, purpose, digest(`otp:${challengeId}:${code}`)]);
294 + if (user.rowCount) await client.query('update auth_delivery_attempt set user_id=$2 where id=$1', [rate.attemptId, user.rows[0].id]);
295 + return { ...rate, challengeId, code, known: Boolean(user.rowCount) };
296 + });
297 + if (limited(res, result)) return;
298 + res.status(202).json({ accepted: true, challengeId: result.challengeId, expiresIn: 300 });
299 + if (result.known) await safelyDeliver({ configured: true, send: (message) => smsProvider.sendOtp(message) }, { phone, code: result.code, expiresIn: 300 }, { pool, attemptId: result.attemptId, env });
300 + else await pool.query("update auth_delivery_attempt set status='not_needed' where id=$1", [result.attemptId]).catch(() => {});
301 + });
302 +
303 + router.post('/phone/verify-otp', async (req, res) => {
304 + if (!smsProvider.configured) return res.status(503).json({ error: 'sms_unavailable' });
305 + const challengeId = String(req.body?.challengeId ?? '');
306 + const code = String(req.body?.code ?? '');
307 + if (!uuid.test(challengeId) || !/^\d{6}$/.test(code)) return res.status(401).json({ error: 'invalid_or_expired_otp' });
308 + const result = await transaction(pool, async (client) => {
309 + const owner = await client.query('select user_id from auth_phone_challenge where id=$1', [challengeId]);
310 + // Account-first locking also serializes two different challenges for one account.
311 + let user;
312 + if (owner.rows[0]?.user_id) {
313 + user = await client.query('select phone_verified_at from app_user where id=$1 and disabled_at is null for update', [owner.rows[0].user_id]);
314 + if (!user.rowCount) return null;
315 + }
316 + const challenge = await client.query('select * from auth_phone_challenge where id=$1 and used_at is null and expires_at>now() and attempts<5 for update', [challengeId]);
317 + if (!challenge.rowCount) return null;
318 + const row = challenge.rows[0];
319 + await client.query('update auth_phone_challenge set attempts=attempts+1 where id=$1', [challengeId]);
320 + const provided = Buffer.from(digest(`otp:${challengeId}:${code}`), 'hex');
321 + if (!crypto.timingSafeEqual(provided, Buffer.from(row.code_digest, 'hex')) || !row.user_id) return null;
322 + if (!user?.rowCount || (row.purpose === 'login' && !user.rows[0].phone_verified_at)) return null;
323 + if (row.purpose !== 'login') {
324 + if (!validPassword(req.body?.newPassword)) return { passwordRequired: true };
325 + const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
326 + await client.query('update auth_credential set password_hash=$2,password_changed_at=now() where user_id=$1', [row.user_id, hash]);
327 + await client.query('update app_user set phone_verified_at=coalesce(phone_verified_at,now()) where id=$1', [row.user_id]);
328 + await client.query('update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null', [row.user_id]);
329 + }
330 + await client.query('update auth_phone_challenge set used_at=now() where user_id=$1 and used_at is null', [row.user_id]);
331 + return session(client, row.user_id);
332 + });
333 + if (result?.passwordRequired) return res.status(400).json({ error: 'invalid_password' });
334 + if (!result) return res.status(401).json({ error: 'invalid_or_expired_otp' });
335 + res.json(result);
336 + });
337 +
338 + return router;
339 +}
backend/src/entrypoint.js
+2
@@ -2,6 +2,7 @@ const publicPort = Number(process.env.PORT ?? 8080);
2 process.env.NODE_ENV = process.env.NODE_ENV || 'production';
3 import express from 'express';
4 import {
5 + configureTrustedProxy,
6 operationalErrorHandler,
7 rateLimit,
8 requestContext,
@@ -12,6 +13,7 @@ const { app, pool } = await import('./server.js');
13
14 const outer = express();
15 outer.disable('x-powered-by');
16 +configureTrustedProxy(outer);
17 outer.use(requestContext);
18 outer.use(requestTelemetry);
19 outer.use(rateLimit);
backend/src/operations.js
+17 -1
@@ -1,4 +1,5 @@
1 import crypto from 'node:crypto';
2 +import { isIP } from 'node:net';
3
4 const buckets = new Map();
5 const nowSeconds = () => Math.floor(Date.now() / 1000);
@@ -42,7 +43,22 @@ export function requestTelemetry(req, res, next) {
43 }
44
45 function clientKey(req) {
45 - return req.socket?.remoteAddress || 'unknown';
46 + return req.ip || req.socket?.remoteAddress || 'unknown';
47 +}
48 +
49 +// Only an operator-pinned internal gateway may supply forwarding information.
50 +// Standalone API defaults to ignoring all forwarded headers.
51 +export function configureTrustedProxy(app, value = process.env.TRUSTED_PROXY_CIDRS ?? '') {
52 + const entries = value.split(',').map(x => x.trim()).filter(Boolean);
53 + if (entries.length > 8) throw new Error('Invalid trusted proxy allowlist');
54 + for (const entry of entries) {
55 + const [address, prefix, ...extra] = entry.split('/');
56 + const bits = isIP(address) === 4 ? 32 : isIP(address) === 6 ? 128 : 0;
57 + if (!bits || extra.length || (prefix !== undefined && (!/^\d+$/.test(prefix) || Number(prefix) < 1 || Number(prefix) > bits))) {
58 + throw new Error('Invalid trusted proxy address');
59 + }
60 + }
61 + app.set('trust proxy', entries.length ? entries : false);
62 }
63
64 function profileFor(req) {
backend/src/phase3.js
+70 -332
@@ -1,9 +1,8 @@
1 +import crypto from 'node:crypto';
2 import express from 'express';
3 +import { applyPlanMutation, createPlanItem, updatePlanItem, planTransaction, serializePlanItem, validUuid, PlanMutationError } from './plan_mutations.js';
4
5 const allowedKinds = new Set(['task','event','routine','goal','assignment','exam','study_session']);
4 -const allowedStatus = new Set(['planned','in_progress','completed','cancelled']);
5 -const allowedPriority = new Set(['low','normal','high','urgent']);
6 -const allowedVisibility = new Set(['private','selected_members','parent_guardian','family']);
6
7 function asDate(value) {
8 if (value == null || value === '') return null;
@@ -13,22 +12,25 @@ function asDate(value) {
12
13 async function familyMember(pool, familyId, userId) {
14 const r = await pool.query(
16 - 'select role,is_admin from family_membership where family_id=$1 and user_id=$2 and ended_at is null',
15 + 'select m.role,m.is_admin from family_membership m join family_workspace f on f.id=m.family_id where m.family_id=$1 and m.user_id=$2 and m.ended_at is null and f.archived_at is null',
16 [familyId, userId],
17 );
18 return r.rows[0] ?? null;
19 }
20
21 async function assertPlanWrite(pool, itemId, userId) {
22 + if (!validUuid(itemId)) return { error: 'invalid_id', status: 400 };
23 const r = await pool.query('select * from plan_item where id=$1', [itemId]);
24 if (!r.rowCount) return { error: 'not_found', status: 404 };
25 if (r.rows[0].owner_user_id !== userId) {
26 return { error: 'forbidden', status: 403 };
27 }
28 + if (r.rows[0].family_id && !(await familyMember(pool, r.rows[0].family_id, userId))) return { error: 'family_membership_required', status: 403 };
29 return { item: r.rows[0] };
30 }
31
32 async function assertStudentAcademic(pool, studentUserId, viewerUserId) {
33 + if (!validUuid(studentUserId)) return false;
34 const r = await pool.query(
35 'select can_view_student_academic($1,$2) as allowed',
36 [viewerUserId, studentUserId],
@@ -60,14 +62,14 @@ export function createPhase3Router({ pool, auth }) {
62 order by coalesce(p.starts_at,p.due_at,p.created_at), p.priority desc`,
63 [req.identity.sub, from, to],
64 );
63 - res.json({ items: r.rows });
65 + res.json({ items: r.rows.map((item) => serializePlanItem(item, req.identity.sub)), asOf: new Date() });
66 });
67
68 router.get('/plan-items', auth, async (req, res) => {
69 const from = asDate(req.query.from);
70 const to = asDate(req.query.to);
71 const values = [req.identity.sub];
70 - const filters = ['can_view_plan_item($1,p.id)'];
72 + const filters = ["can_view_plan_item($1,p.id)", "p.status<>'cancelled'"];
73 if (from) {
74 values.push(from);
75 filters.push(`coalesce(p.starts_at,p.due_at,p.created_at) >= $${values.length}`);
@@ -87,163 +89,29 @@ export function createPhase3Router({ pool, auth }) {
89 order by coalesce(p.starts_at,p.due_at,p.created_at), p.created_at`,
90 values,
91 );
90 - res.json({ items: r.rows });
92 + res.json({ items: r.rows.map((item) => serializePlanItem(item, req.identity.sub)), asOf: new Date() });
93 });
94
93 - router.post('/plan-items', auth, async (req, res) => {
94 - const kind = String(req.body.kind ?? 'task');
95 - const title = String(req.body.title ?? '').trim();
96 - const priority = String(req.body.priority ?? 'normal');
97 - const visibility = String(req.body.visibility ?? 'private');
98 - const familyId = req.body.familyId || null;
99 - const startsAt = asDate(req.body.startsAt);
100 - const dueAt = asDate(req.body.dueAt);
101 - if (!allowedKinds.has(kind) || !title || !allowedPriority.has(priority) || !allowedVisibility.has(visibility)) {
102 - return res.status(400).json({ error: 'invalid_plan_item' });
103 - }
104 - if (familyId) {
105 - const member = await familyMember(pool, familyId, req.identity.sub);
106 - if (!member) return res.status(403).json({ error: 'family_membership_required' });
107 - }
108 - if ((visibility === 'family' || visibility === 'parent_guardian') && !familyId) {
109 - return res.status(400).json({ error: 'family_required_for_visibility' });
110 - }
111 - if (req.body.subjectId) {
112 - const s = await pool.query('select student_user_id from subject where id=$1', [req.body.subjectId]);
113 - if (!s.rowCount || s.rows[0].student_user_id !== req.identity.sub) {
114 - return res.status(403).json({ error: 'subject_forbidden' });
115 - }
116 - }
117 -
118 - const client = await pool.connect();
119 - try {
120 - await client.query('begin');
121 - const r = await client.query(
122 - `insert into plan_item(
123 - owner_user_id,family_id,subject_id,kind,title,notes,status,priority,visibility,
124 - starts_at,due_at,duration_minutes,recurrence_rule,parent_item_id
125 - ) values($1,$2,$3,$4,$5,$6,'planned',$7,$8,$9,$10,$11,$12,$13)
126 - returning *`,
127 - [
128 - req.identity.sub, familyId, req.body.subjectId || null, kind, title,
129 - req.body.notes || null, priority, visibility, startsAt, dueAt,
130 - req.body.durationMinutes || null, req.body.recurrenceRule || null,
131 - req.body.parentItemId || null,
132 - ],
133 - );
134 - const item = r.rows[0];
135 -
136 - const selected = Array.isArray(req.body.selectedMemberIds)
137 - ? [...new Set(req.body.selectedMemberIds.map(String))]
138 - : [];
139 - if (visibility === 'selected_members') {
140 - if (!familyId || selected.length === 0) {
141 - await client.query('rollback');
142 - return res.status(400).json({ error: 'selected_members_required' });
143 - }
144 - for (const userId of selected) {
145 - const m = await client.query(
146 - 'select 1 from family_membership where family_id=$1 and user_id=$2 and ended_at is null',
147 - [familyId, userId],
148 - );
149 - if (!m.rowCount) {
150 - await client.query('rollback');
151 - return res.status(400).json({ error: 'selected_member_not_in_family' });
152 - }
153 - await client.query(
154 - `insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by)
155 - values('plan_item',$1,$2,$3)
156 - on conflict do nothing`,
157 - [item.id, userId, req.identity.sub],
158 - );
159 - }
160 - }
161 -
162 - const leadTimes = Array.isArray(req.body.reminderMinutesBefore)
163 - ? [...new Set(req.body.reminderMinutesBefore.map(Number))]
164 - : [];
165 - const baseTime = startsAt ?? dueAt;
166 - if (baseTime) {
167 - for (const minutes of leadTimes) {
168 - if (!Number.isInteger(minutes) || minutes < 0 || minutes > 10080) continue;
169 - await client.query(
170 - `insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for)
171 - values($1,$2,$3,$4::timestamptz - make_interval(mins => $3))
172 - on conflict(plan_item_id,owner_user_id,minutes_before)
173 - do update set scheduled_for=excluded.scheduled_for,status='scheduled',claimed_at=null`,
174 - [item.id, req.identity.sub, minutes, baseTime],
175 - );
176 - }
177 - }
95 + router.get('/plan-items/:itemId', auth, async (req, res) => {
96 + if (!validUuid(req.params.itemId)) return res.status(400).json({ error: 'invalid_id' });
97 + const result = await pool.query('select * from plan_item where id=$1 and can_view_plan_item($2,id)', [req.params.itemId, req.identity.sub]);
98 + if (!result.rowCount) return res.status(404).json({ error: 'not_found' });
99 + res.json(serializePlanItem(result.rows[0], req.identity.sub));
100 + });
101
179 - await client.query('commit');
180 - res.status(201).json(item);
181 - } catch (e) {
182 - await client.query('rollback').catch(() => {});
183 - throw e;
184 - } finally {
185 - client.release();
186 - }
102 + router.post('/plan-items', auth, async (req, res) => {
103 + const item = await planTransaction(pool, req.identity.sub, (client) => createPlanItem(client, req.identity.sub, req.body, req.body.id ?? crypto.randomUUID()));
104 + res.status(201).json(serializePlanItem(item, req.identity.sub));
105 });
106
107 router.patch('/plan-items/:itemId', auth, async (req, res) => {
190 - const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub);
191 - if (access.error) return res.status(access.status).json({ error: access.error });
192 -
193 - const fields = [];
194 - const values = [req.params.itemId];
195 - const add = (column, value, cast = '') => {
196 - values.push(value);
197 - fields.push(`${column}=$${values.length}${cast}`);
198 - };
199 - if (req.body.title != null) {
200 - const title = String(req.body.title).trim();
201 - if (!title) return res.status(400).json({ error: 'invalid_title' });
202 - add('title', title);
203 - }
204 - if (req.body.notes !== undefined) add('notes', req.body.notes || null);
205 - if (req.body.status != null) {
206 - const status = String(req.body.status);
207 - if (!allowedStatus.has(status)) return res.status(400).json({ error: 'invalid_status' });
208 - add('status', status);
209 - if (status === 'completed') add('completed_at', new Date());
210 - if (status !== 'completed') add('completed_at', null);
211 - }
212 - if (req.body.priority != null) {
213 - const priority = String(req.body.priority);
214 - if (!allowedPriority.has(priority)) return res.status(400).json({ error: 'invalid_priority' });
215 - add('priority', priority);
216 - }
217 - if (req.body.startsAt !== undefined) add('starts_at', asDate(req.body.startsAt));
218 - if (req.body.dueAt !== undefined) add('due_at', asDate(req.body.dueAt));
219 - if (req.body.durationMinutes !== undefined) add('duration_minutes', req.body.durationMinutes || null);
220 - if (!fields.length) return res.status(400).json({ error: 'no_changes' });
221 - fields.push('updated_at=now()');
108 + const item = await planTransaction(pool, req.identity.sub, (client) => updatePlanItem(client, req.identity.sub, req.params.itemId, req.body, req.body.expectedVersion));
109 + res.json(serializePlanItem(item, req.identity.sub));
110 + });
111
223 - const client = await pool.connect();
224 - try {
225 - await client.query('begin');
226 - const r = await client.query(
227 - `update plan_item set ${fields.join(',')} where id=$1 returning *`,
228 - values,
229 - );
230 - if (r.rows[0].status === 'completed' || r.rows[0].status === 'cancelled') {
231 - await client.query(
232 - `update reminder set status='cancelled'
233 - where plan_item_id=$1 and status in ('scheduled','claimed')`,
234 - [req.params.itemId],
235 - );
236 - } else {
237 - await client.query('select recompute_reminder_schedule($1)', [req.params.itemId]);
238 - }
239 - await client.query('commit');
240 - res.json(r.rows[0]);
241 - } catch (e) {
242 - await client.query('rollback').catch(() => {});
243 - throw e;
244 - } finally {
245 - client.release();
246 - }
112 + router.delete('/plan-items/:itemId', auth, async (req, res) => {
113 + const item = await planTransaction(pool, req.identity.sub, (client) => updatePlanItem(client, req.identity.sub, req.params.itemId, { status: 'cancelled' }, req.body.expectedVersion));
114 + res.json(serializePlanItem(item, req.identity.sub));
115 });
116
117 router.post('/plan-items/:itemId/reminders', auth, async (req, res) => {
@@ -429,39 +297,43 @@ export function createPhase3Router({ pool, auth }) {
297 }
298 const [years, subjects, workload, grades] = await Promise.all([
299 pool.query(
432 - `select * from academic_year where student_user_id=$1 and active order by starts_on desc`,
433 - [studentUserId],
300 + `select y.* from academic_year y where y.student_user_id=$1 and y.active
301 + and ($1=$2 or exists(select 1 from academic_term t join subject s on s.academic_term_id=t.id
302 + join plan_item p on p.subject_id=s.id where t.academic_year_id=y.id and can_view_plan_item($2,p.id)))
303 + order by y.starts_on desc`,
304 + [studentUserId, req.identity.sub],
305 ),
306 pool.query(
307 `select s.*,t.title as term_title,y.title as year_title
308 from subject s join academic_term t on t.id=s.academic_term_id
309 join academic_year y on y.id=t.academic_year_id
439 - where s.student_user_id=$1 order by s.name`,
440 - [studentUserId],
310 + where s.student_user_id=$1 and ($1=$2 or exists(select 1 from plan_item p
311 + where p.subject_id=s.id and can_view_plan_item($2,p.id))) order by s.name`,
312 + [studentUserId, req.identity.sub],
313 ),
314 pool.query(
315 `select *
316 from plan_item
445 - where owner_user_id=$1
317 + where owner_user_id=$1 and can_view_plan_item($2,id)
318 and kind in ('assignment','exam','study_session')
319 and status not in ('completed','cancelled')
320 order by coalesce(due_at,starts_at) nulls last`,
449 - [studentUserId],
321 + [studentUserId, req.identity.sub],
322 ),
323 pool.query(
324 `select id,title,subject_id,grade_points,grade_out_of,due_at
325 from plan_item
454 - where owner_user_id=$1
326 + where owner_user_id=$1 and can_view_plan_item($2,id)
327 and grade_points is not null
328 and grade_out_of is not null
329 order by due_at desc nulls last`,
458 - [studentUserId],
330 + [studentUserId, req.identity.sub],
331 ),
332 ]);
333 res.json({
334 years: years.rows,
335 subjects: subjects.rows,
464 - workload: workload.rows,
336 + workload: workload.rows.map((item) => serializePlanItem(item, req.identity.sub)),
337 grades: grades.rows,
338 });
339 });
@@ -474,9 +346,10 @@ export function createPhase3Router({ pool, auth }) {
346 `select c.*,s.name as subject_name,s.color_key
347 from class_session c
348 join subject s on s.id=c.subject_id
477 - where s.student_user_id=$1
349 + where s.student_user_id=$1 and ($1=$2 or exists(select 1 from plan_item p
350 + where p.subject_id=s.id and can_view_plan_item($2,p.id)))
351 order by c.weekday,c.starts_at`,
479 - [req.params.studentUserId],
352 + [req.params.studentUserId, req.identity.sub],
353 );
354 res.json({ classes: r.rows });
355 });
@@ -492,12 +365,9 @@ export function createPhase3Router({ pool, auth }) {
365 if (!Number.isFinite(points) || !Number.isFinite(outOf) || outOf <= 0 || points < 0 || points > outOf) {
366 return res.status(400).json({ error: 'invalid_grade' });
367 }
495 - const r = await pool.query(
496 - `update plan_item set grade_points=$2,grade_out_of=$3,updated_at=now()
497 - where id=$1 returning *`,
498 - [req.params.itemId, points, outOf],
499 - );
500 - res.json(r.rows[0]);
368 + const item = await planTransaction(pool, req.identity.sub, (client) => updatePlanItem(client,
369 + req.identity.sub, req.params.itemId, { gradePoints: points, gradeOutOf: outOf }, req.body.expectedVersion));
370 + res.json(serializePlanItem(item, req.identity.sub));
371 });
372
373 router.get('/families/:familyId/calendar', auth, async (req, res) => {
@@ -513,15 +383,14 @@ export function createPhase3Router({ pool, auth }) {
383 order by coalesce(p.starts_at,p.due_at,p.created_at)`,
384 [req.params.familyId, req.identity.sub],
385 );
516 - res.json({ items: r.rows });
386 + res.json({ items: r.rows.map((item) => serializePlanItem(item, req.identity.sub)), asOf: new Date() });
387 });
388
389 router.get('/families/:familyId/children/:studentUserId/support-summary', auth, async (req, res) => {
390 const familyId = req.params.familyId;
391 const studentUserId = req.params.studentUserId;
392 const g = await pool.query(
523 - `select 1 from guardian_relationship
524 - where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3 and active`,
393 + `select 1 where is_active_guardian($1,$2,$3)`,
394 [familyId, req.identity.sub, studentUserId],
395 );
396 if (!g.rowCount) return res.status(403).json({ error: 'guardian_required' });
@@ -530,39 +399,40 @@ export function createPhase3Router({ pool, auth }) {
399 pool.query(
400 `select id,kind,title,due_at,starts_at,priority,status
401 from plan_item
533 - where owner_user_id=$1
402 + where owner_user_id=$1 and family_id=$3 and can_view_plan_item($2,id)
403 and kind in ('assignment','exam','study_session')
404 and status not in ('completed','cancelled')
405 and coalesce(due_at,starts_at) >= now()
406 and coalesce(due_at,starts_at) < now()+interval '14 days'
407 order by coalesce(due_at,starts_at) limit 20`,
539 - [studentUserId],
408 + [studentUserId, req.identity.sub, familyId],
409 ),
410 pool.query(
411 `select count(*)::int as n from plan_item
543 - where owner_user_id=$1 and kind in ('assignment','study_session') and status='completed'
412 + where owner_user_id=$1 and family_id=$3 and can_view_plan_item($2,id) and kind in ('assignment','study_session') and status='completed'
413 and completed_at >= now()-interval '7 days'`,
545 - [studentUserId],
414 + [studentUserId, req.identity.sub, familyId],
415 ),
416 pool.query(
417 `select count(*)::int as n from plan_item
549 - where owner_user_id=$1 and kind in ('assignment','study_session')
418 + where owner_user_id=$1 and family_id=$3 and can_view_plan_item($2,id) and kind in ('assignment','study_session')
419 and status not in ('completed','cancelled') and due_at < now()`,
551 - [studentUserId],
420 + [studentUserId, req.identity.sub, familyId],
421 ),
422 pool.query(
554 - `select coalesce(sum(duration_minutes),0)::int as minutes
555 - from plan_item
556 - where owner_user_id=$1 and kind='study_session' and status='completed'
557 - and completed_at >= now()-interval '7 days'`,
558 - [studentUserId],
423 + `select floor(coalesce(sum(greatest(0,extract(epoch from
424 + least(coalesce(i.ends_at,now()),now())-greatest(i.starts_at,now()-interval '7 days')))),0))::int as seconds
425 + from study_session s join study_interval i on i.session_id=s.id join plan_item p on p.id=s.plan_item_id
426 + where s.child_user_id=$1 and s.archived_at is null and p.family_id=$3 and can_view_plan_item($2,p.id)
427 + and i.starts_at<now() and coalesce(i.ends_at,now())>now()-interval '7 days'`,
428 + [studentUserId, req.identity.sub, familyId],
429 ),
430 pool.query(
431 `select
432 case when sum(grade_out_of)>0 then round(sum(grade_points)/sum(grade_out_of)*100,1) end as percent
433 from plan_item
564 - where owner_user_id=$1 and grade_points is not null and grade_out_of is not null`,
565 - [studentUserId],
434 + where owner_user_id=$1 and family_id=$3 and can_view_plan_item($2,id) and grade_points is not null and grade_out_of is not null`,
435 + [studentUserId, req.identity.sub, familyId],
436 ),
437 ]);
438 await audit(pool, req.identity.sub, familyId, 'parent.support_summary.view', 'student', studentUserId);
@@ -571,157 +441,25 @@ export function createPhase3Router({ pool, auth }) {
441 metrics: {
442 completedLast7Days: completed.rows[0].n,
443 overdue: overdue.rows[0].n,
574 - studyMinutesLast7Days: study.rows[0].minutes,
444 + studyMinutesLast7Days: Math.floor(study.rows[0].seconds / 60),
445 + recordedStudySecondsLast7Days: study.rows[0].seconds,
446 + recordedTimeIsProofOfStudy: false,
447 gradePercent: grades.rows[0].percent == null ? null : Number(grades.rows[0].percent),
448 },
449 });
450 });
451
452 router.post('/sync/mutations', auth, async (req, res) => {
581 - const mutations = Array.isArray(req.body.mutations) ? req.body.mutations : [];
582 - if (mutations.length > 100) {
583 - return res.status(400).json({ error: 'too_many_mutations' });
584 - }
585 -
586 - const client = await pool.connect();
453 + const mutations = req.body?.mutations;
454 + if (!Array.isArray(mutations) || mutations.length > 100) return res.status(400).json({ error: 'invalid_mutations' });
455 const results = [];
588 - try {
589 - for (const mutation of mutations) {
590 - const id = String(mutation.id ?? '');
591 - const operation = String(mutation.operation ?? '');
592 - const entityType = String(mutation.entityType ?? 'plan_item');
593 - const entityId = mutation.entityId ? String(mutation.entityId) : null;
594 - const clientUpdatedAt = asDate(mutation.clientUpdatedAt);
595 - const payload = mutation.payload && typeof mutation.payload === 'object'
596 - ? mutation.payload
597 - : {};
598 -
599 - if (
600 - !id ||
601 - entityType !== 'plan_item' ||
602 - !entityId ||
603 - !clientUpdatedAt ||
604 - !['update', 'complete', 'reschedule'].includes(operation)
605 - ) {
606 - results.push({ id, status: 'rejected', error: 'invalid_mutation' });
607 - continue;
608 - }
609 -
610 - await client.query('begin');
611 - try {
612 - const duplicate = await client.query(
613 - 'select accepted_at from sync_mutation where id=$1 and user_id=$2',
614 - [id, req.identity.sub],
615 - );
616 - if (duplicate.rowCount) {
617 - await client.query('rollback');
618 - results.push({
619 - id,
620 - status: 'already_applied',
621 - acceptedAt: duplicate.rows[0].accepted_at,
622 - });
623 - continue;
624 - }
625 -
626 - const current = await client.query(
627 - 'select * from plan_item where id=$1 for update',
628 - [entityId],
629 - );
630 - if (!current.rowCount) {
631 - await client.query('rollback');
632 - results.push({ id, status: 'rejected', error: 'not_found' });
633 - continue;
634 - }
635 - const item = current.rows[0];
636 - if (item.owner_user_id !== req.identity.sub) {
637 - await client.query('rollback');
638 - results.push({ id, status: 'rejected', error: 'forbidden' });
639 - continue;
640 - }
641 -
642 - const serverUpdatedAt = new Date(item.updated_at);
643 - if (serverUpdatedAt.getTime() > clientUpdatedAt.getTime() + 1000) {
644 - await client.query('rollback');
645 - results.push({
646 - id,
647 - status: 'conflict',
648 - serverUpdatedAt: serverUpdatedAt.toISOString(),
649 - });
650 - continue;
651 - }
652 -
653 - if (operation === 'complete') {
654 - await client.query(
655 - `update plan_item
656 - set status='completed',completed_at=now(),updated_at=now()
657 - where id=$1`,
658 - [entityId],
659 - );
660 - await client.query(
661 - `update reminder set status='cancelled'
662 - where plan_item_id=$1 and status in ('scheduled','claimed')`,
663 - [entityId],
664 - );
665 - } else if (operation === 'reschedule') {
666 - const dueAt = asDate(payload.dueAt);
667 - const startsAt = asDate(payload.startsAt);
668 - if (!dueAt && !startsAt) {
669 - await client.query('rollback');
670 - results.push({ id, status: 'rejected', error: 'invalid_reschedule' });
671 - continue;
672 - }
673 - await client.query(
674 - `update plan_item
675 - set due_at=coalesce($2,due_at),
676 - starts_at=coalesce($3,starts_at),
677 - updated_at=now()
678 - where id=$1`,
679 - [entityId, dueAt, startsAt],
680 - );
681 - await client.query('select recompute_reminder_schedule($1)', [entityId]);
682 - } else {
683 - const title = payload.title == null ? null : String(payload.title).trim();
684 - const status = payload.status == null ? null : String(payload.status);
685 - if (status != null && !allowedStatus.has(status)) {
686 - await client.query('rollback');
687 - results.push({ id, status: 'rejected', error: 'invalid_status' });
688 - continue;
689 - }
690 - await client.query(
691 - `update plan_item
692 - set title=coalesce($2,title),
693 - status=coalesce($3::plan_item_status,status),
694 - updated_at=now()
695 - where id=$1`,
696 - [entityId, title || null, status],
697 - );
698 - }
456 + for (const mutation of mutations) results.push(await applyPlanMutation(pool, req.identity.sub, mutation));
457 + res.json({ results, asOf: new Date() });
458 + });
459
700 - await client.query(
701 - `insert into sync_mutation(
702 - id,user_id,entity_type,entity_id,operation,client_updated_at,payload
703 - ) values($1,$2,$3,$4,$5,$6,$7::jsonb)`,
704 - [
705 - id,
706 - req.identity.sub,
707 - entityType,
708 - entityId,
709 - operation,
710 - clientUpdatedAt,
711 - JSON.stringify(payload),
712 - ],
713 - );
714 - await client.query('commit');
715 - results.push({ id, status: 'accepted' });
716 - } catch (error) {
717 - await client.query('rollback').catch(() => {});
718 - throw error;
719 - }
720 - }
721 - res.json({ results });
722 - } finally {
723 - client.release();
724 - }
460 + router.use((error, _req, res, next) => {
461 + if (error instanceof PlanMutationError) return res.status(error.status).json({ error: error.code, ...error.details });
462 + next(error);
463 });
464
465 return router;
backend/src/phase4.js
+105 -63
@@ -2,6 +2,7 @@ import express from 'express';
2
3 const clampText = (value, max = 4000) =>
4 String(value ?? '').trim().slice(0, max);
5 +const isUuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
6
7 function safetyClass(text) {
8 const value = text.toLowerCase();
@@ -28,75 +29,38 @@ function localGuide(kind, text, klass) {
29 }
30
31 async function providerGuide(kind, text, klass) {
31 - if (klass === 'urgent_review') return localGuide(kind, text, klass);
32 -
33 - const apiKey = process.env.AI_API_KEY;
34 - const baseUrl = process.env.AI_BASE_URL;
35 - const model = process.env.AI_MODEL;
36 - if (!apiKey || !baseUrl || !model) {
37 - return localGuide(kind, text, klass);
38 - }
39 -
40 - const system = [
41 - 'You are LifeMate, an age-appropriate Persian companion.',
42 - 'You are advisory, not a doctor, therapist, diagnostician, or emergency service.',
43 - 'For study, guide step-by-step and avoid simply giving final homework answers.',
44 - 'For planning, propose realistic options and preserve user agency.',
45 - 'For wellbeing, be calm, supportive, non-clinical, and encourage trusted human support when appropriate.',
46 - 'Never claim to know hidden mental state. Never expose private content to parents.',
47 - `Guide mode: ${kind}`,
48 - ].join(' ');
49 -
50 - const response = await fetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
51 - method: 'POST',
52 - headers: {
53 - authorization: `Bearer ${apiKey}`,
54 - 'content-type': 'application/json',
55 - },
56 - body: JSON.stringify({
57 - model,
58 - temperature: 0.4,
59 - messages: [
60 - { role: 'system', content: system },
61 - { role: 'user', content: text },
62 - ],
63 - }),
64 - });
65 -
66 - if (!response.ok) return localGuide(kind, text, klass);
67 - const body = await response.json();
68 - const content = body?.choices?.[0]?.message?.content;
69 - return clampText(content, 6000) || localGuide(kind, text, klass);
32 + // External AI/voice is not authorized in this package, even if keys exist.
33 + return localGuide(kind, text, klass);
34 }
35
36 async function guardianRelationship(pool, familyId, guardianUserId, minorUserId) {
37 const result = await pool.query(
74 - `select 1
75 - from guardian_relationship g
76 - join family_membership gm
77 - on gm.family_id=g.family_id
78 - and gm.user_id=g.guardian_user_id
79 - and gm.ended_at is null
80 - join family_membership mm
81 - on mm.family_id=g.family_id
82 - and mm.user_id=g.minor_user_id
83 - and mm.ended_at is null
84 - where g.family_id=$1
85 - and g.guardian_user_id=$2
86 - and g.minor_user_id=$3
87 - and g.active=true`,
38 + 'select is_active_guardian($1,$2,$3) as allowed',
39 [familyId, guardianUserId, minorUserId],
40 );
90 - return result.rowCount > 0;
41 + return result.rows[0]?.allowed === true;
42 }
43
93 -export function createPhase4Router({ pool, auth }) {
44 +export function createPhase4Router({ pool, auth, sensitiveFeaturesEnabled = process.env.ENABLE_SENSITIVE_FEATURES === 'true' }) {
45 const router = express.Router();
46 + const sensitiveEnabled = sensitiveFeaturesEnabled === true;
47 + const requireSensitive = (_req, res, next) => {
48 + if (!sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
49 + return next();
50 + };
51 router.use(auth);
52
53 router.post('/learning/goals', async (req, res) => {
54 const title = clampText(req.body.title, 240);
55 if (!title) return res.status(400).json({ error: 'invalid_input' });
56 + if (req.body.subjectId != null && !isUuid(req.body.subjectId)) return res.status(400).json({ error: 'invalid_subject_id' });
57 + if (req.body.subjectId) {
58 + const subject = await pool.query(
59 + 'select 1 from subject where id=$1 and student_user_id=$2',
60 + [req.body.subjectId, req.identity.sub],
61 + );
62 + if (!subject.rowCount) return res.status(403).json({ error: 'subject_forbidden' });
63 + }
64 const result = await pool.query(
65 'insert into learning_goal(owner_user_id,subject_id,title,target) values($1,$2,$3,$4) returning *',
66 [
@@ -117,6 +81,65 @@ export function createPhase4Router({ pool, auth }) {
81 res.json({ items: result.rows });
82 });
83
84 + router.get('/learning/goals/:id', async (req, res) => {
85 + if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' });
86 + const result = await pool.query('select * from learning_goal where id=$1 and owner_user_id=$2', [req.params.id, req.identity.sub]);
87 + if (!result.rowCount) return res.status(404).json({ error: 'goal_not_found' });
88 + res.json(result.rows[0]);
89 + });
90 +
91 + router.patch('/learning/goals/:id', async (req, res) => {
92 + if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' });
93 + const body = req.body ?? {};
94 + const has = (field) => Object.hasOwn(body, field);
95 + if (has('title') && (typeof body.title !== 'string' || !body.title.trim() || body.title.trim().length > 240)) return res.status(400).json({ error: 'invalid_input' });
96 + if (has('target') && body.target != null && (typeof body.target !== 'string' || body.target.trim().length > 1000)) return res.status(400).json({ error: 'invalid_input' });
97 + if (has('subjectId') && body.subjectId != null && !isUuid(body.subjectId)) return res.status(400).json({ error: 'invalid_subject_id' });
98 + if (has('status') && !['active', 'completed', 'archived'].includes(body.status)) return res.status(400).json({ error: 'invalid_status' });
99 + const client = await pool.connect();
100 + try {
101 + await client.query('begin');
102 + const goal = await client.query('select status from learning_goal where id=$1 and owner_user_id=$2 for update', [req.params.id, req.identity.sub]);
103 + if (!goal.rowCount || goal.rows[0].status === 'archived') {
104 + await client.query('rollback');
105 + return res.status(goal.rowCount ? 409 : 404).json({ error: goal.rowCount ? 'goal_archived' : 'goal_not_found' });
106 + }
107 + if (body.subjectId != null) {
108 + const subject = await client.query('select 1 from subject where id=$1 and student_user_id=$2', [body.subjectId, req.identity.sub]);
109 + if (!subject.rowCount) {
110 + await client.query('rollback');
111 + return res.status(403).json({ error: 'subject_forbidden' });
112 + }
113 + }
114 + const result = await client.query(
115 + `update learning_goal set title=case when $3 then $4 else title end,
116 + target=case when $5 then $6 else target end,
117 + subject_id=case when $7 then $8::uuid else subject_id end,
118 + status=coalesce($9,status),updated_at=now()
119 + where id=$1 and owner_user_id=$2 returning *`,
120 + [req.params.id, req.identity.sub, has('title'), has('title') ? body.title.trim() : null,
121 + has('target'), body.target?.trim() || null, has('subjectId'), body.subjectId ?? null, body.status ?? null],
122 + );
123 + await client.query('commit');
124 + res.json(result.rows[0]);
125 + } catch (error) {
126 + await client.query('rollback').catch(() => {});
127 + throw error;
128 + } finally { client.release(); }
129 + });
130 +
131 + router.delete('/learning/goals/:id', async (req, res) => {
132 + if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' });
133 + const result = await pool.query(
134 + `update learning_goal set status='archived',
135 + updated_at=case when status='archived' then updated_at else now() end
136 + where id=$1 and owner_user_id=$2 returning id`,
137 + [req.params.id, req.identity.sub],
138 + );
139 + if (!result.rowCount) return res.status(404).json({ error: 'goal_not_found' });
140 + res.status(204).end();
141 + });
142 +
143 router.post('/learning/checkins', async (req, res) => {
144 const confidence = Number(req.body.confidence);
145 const difficulty = Number(req.body.difficulty);
@@ -130,6 +153,10 @@ export function createPhase4Router({ pool, auth }) {
153 ) {
154 return res.status(400).json({ error: 'invalid_input' });
155 }
156 + if (req.body.learningGoalId) {
157 + const goal = await pool.query('select 1 from learning_goal where id=$1 and owner_user_id=$2', [req.body.learningGoalId, req.identity.sub]);
158 + if (!goal.rowCount) return res.status(403).json({ error: 'learning_goal_forbidden' });
159 + }
160 const result = await pool.query(
161 'insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note) values($1,$2,$3,$4,$5) returning *',
162 [
@@ -143,7 +170,7 @@ export function createPhase4Router({ pool, auth }) {
170 res.status(201).json(result.rows[0]);
171 });
172
146 - router.post('/wellbeing/checkins', async (req, res) => {
173 + router.post('/wellbeing/checkins', requireSensitive, async (req, res) => {
174 const mood = Number(req.body.mood);
175 const energy = Number(req.body.energy);
176 const stress = Number(req.body.stress);
@@ -166,7 +193,7 @@ export function createPhase4Router({ pool, auth }) {
193 res.status(201).json(result.rows[0]);
194 });
195
169 - router.get('/wellbeing/checkins', async (req, res) => {
196 + router.get('/wellbeing/checkins', requireSensitive, async (req, res) => {
197 const result = await pool.query(
198 'select id,mood,energy,stress,visibility,created_at from wellbeing_checkin where owner_user_id=$1 order by created_at desc limit 30',
199 [req.identity.sub],
@@ -174,7 +201,7 @@ export function createPhase4Router({ pool, auth }) {
201 res.json({ items: result.rows });
202 });
203
177 - router.get('/families/:familyId/children/:minorUserId/wellbeing-summary', async (req, res) => {
204 + router.get('/families/:familyId/children/:minorUserId/wellbeing-summary', requireSensitive, async (req, res) => {
205 const allowed = await guardianRelationship(
206 pool,
207 req.params.familyId,
@@ -212,7 +239,7 @@ export function createPhase4Router({ pool, auth }) {
239 });
240 });
241
215 - router.post('/families/:familyId/children/:minorUserId/family-guidance', async (req, res) => {
242 + router.post('/families/:familyId/children/:minorUserId/family-guidance', requireSensitive, async (req, res) => {
243 const allowed = await guardianRelationship(
244 pool,
245 req.params.familyId,
@@ -254,8 +281,8 @@ export function createPhase4Router({ pool, auth }) {
281 )
282 end as grade_percent
283 from plan_item
257 - where owner_user_id=$1`,
258 - [req.params.minorUserId],
284 + where owner_user_id=$1 and can_view_plan_item($2,id)`,
285 + [req.params.minorUserId, req.identity.sub],
286 ),
287 pool.query(
288 `select
@@ -327,6 +354,7 @@ export function createPhase4Router({ pool, auth }) {
354 ? req.body.kind
355 : null;
356 if (!kind) return res.status(400).json({ error: 'invalid_kind' });
357 + if (kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
358 const result = await pool.query(
359 'insert into ai_guide_session(owner_user_id,guide_kind) values($1,$2) returning *',
360 [req.identity.sub, kind],
@@ -342,13 +370,14 @@ export function createPhase4Router({ pool, auth }) {
370 [req.params.id, req.identity.sub],
371 );
372 if (!session.rowCount) return res.status(404).json({ error: 'session_not_found' });
373 + if (session.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
374
375 const klass = safetyClass(text);
376 await pool.query(
377 "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'user',$2,$3)",
378 [req.params.id, text, klass],
379 );
351 - if (klass === 'urgent_review') {
380 + if (klass === 'urgent_review' && sensitiveEnabled) {
381 await pool.query(
382 "insert into wellbeing_safety_event(owner_user_id,source_session_id,severity) values($1,$2,'urgent_review')",
383 [req.identity.sub, req.params.id],
@@ -365,7 +394,7 @@ export function createPhase4Router({ pool, auth }) {
394 advisory: true,
395 medicalDiagnosis: false,
396 automaticAction: false,
368 - providerMode: process.env.AI_API_KEY ? 'configured' : 'local_fallback',
397 + providerMode: 'local_fallback',
398 });
399 });
400
@@ -374,6 +403,11 @@ export function createPhase4Router({ pool, auth }) {
403 if (!title || !req.body.proposal || typeof req.body.proposal !== 'object') {
404 return res.status(400).json({ error: 'invalid_input' });
405 }
406 + if (req.body.sessionId) {
407 + const session = await pool.query('select guide_kind from ai_guide_session where id=$1 and owner_user_id=$2', [req.body.sessionId, req.identity.sub]);
408 + if (!session.rowCount) return res.status(403).json({ error: 'session_forbidden' });
409 + if (session.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
410 + }
411 const result = await pool.query(
412 'insert into ai_plan_proposal(owner_user_id,session_id,title,proposal) values($1,$2,$3,$4) returning *',
413 [req.identity.sub, req.body.sessionId || null, title, req.body.proposal],
@@ -386,6 +420,14 @@ export function createPhase4Router({ pool, auth }) {
420 ? req.body.status
421 : null;
422 if (!status) return res.status(400).json({ error: 'invalid_status' });
423 + const proposal = await pool.query(
424 + `select s.guide_kind from ai_plan_proposal p
425 + left join ai_guide_session s on s.id=p.session_id
426 + where p.id=$1 and p.owner_user_id=$2 and p.status='proposed'`,
427 + [req.params.id, req.identity.sub],
428 + );
429 + if (!proposal.rowCount) return res.status(404).json({ error: 'proposal_not_found' });
430 + if (proposal.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
431 const result = await pool.query(
432 "update ai_plan_proposal set status=$3,decided_at=now() where id=$1 and owner_user_id=$2 and status='proposed' returning *",
433 [req.params.id, req.identity.sub, status],
backend/src/phase6.js
+7 -5
@@ -1,24 +1,26 @@
1 import express from 'express';
2 import { createSessionAuth } from './session_auth.js';
3 +import { validBirthDate } from './profile_router.js';
4
5 const stages = { primary_1:[1,3,0], primary_2:[4,6,3], secondary_1:[7,9,6], secondary_2:[10,12,9] };
6 function educationForGrade(grade){ const n=Number(grade); for(const [stage,[min,max,offset]] of Object.entries(stages)){ if(Number.isInteger(n)&&n>=min&&n<=max)return{stage,nationalGrade:n,localYear:n-offset}; } return null; }
7 function validPersona(value){ return ['mother','father','child','adult'].includes(value); }
8 function trustedTextbookUrl(value){ try{ const url=new URL(value); return url.protocol==='https:'&&['chap.sch.ir','medu.gov.ir'].includes(url.hostname); }catch{return false;} }
9
9 -export function createPhase6Router({pool,auth}){
10 +export function createPhase6Router({pool,auth,sensitiveFeaturesEnabled=process.env.ENABLE_SENSITIVE_FEATURES==='true'}){
11 const router=express.Router(); const requireAuth=auth??createSessionAuth({pool,jwtSecret:process.env.JWT_SECRET});
12 + const requireSensitive=(_req,res,next)=>sensitiveFeaturesEnabled===true?next():res.status(503).json({error:'sensitive_features_disabled'});
13 router.get('/me/iran-profile',requireAuth,async(req,res)=>{ const r=await pool.query(`select p.user_id,p.display_name,p.birth_date,p.household_persona,p.sex,e.stage,e.national_grade,e.local_year,e.school_name,e.school_year from profile p left join education_profile e on e.user_id=p.user_id where p.user_id=$1`,[req.identity.sub]); res.json(r.rows[0]??{}); });
12 - router.patch('/me/iran-profile',requireAuth,async(req,res)=>{ const persona=req.body.householdPersona,sex=req.body.sex; if(persona!=null&&!validPersona(persona))return res.status(400).json({error:'invalid_persona'}); if(sex!=null&&!['female','male','unspecified'].includes(sex))return res.status(400).json({error:'invalid_sex'}); await pool.query(`update profile set household_persona=coalesce($2,household_persona),sex=coalesce($3,sex),birth_date=coalesce($4::date,birth_date),updated_at=now() where user_id=$1`,[req.identity.sub,persona??null,sex??null,req.body.birthDate??null]); res.status(204).end(); });
14 + router.patch('/me/iran-profile',requireAuth,async(req,res)=>{ const persona=req.body.householdPersona,sex=req.body.sex,birthDate=req.body.birthDate; if(persona!=null&&!validPersona(persona))return res.status(400).json({error:'invalid_persona'}); if(sex!=null&&!['female','male','unspecified'].includes(sex))return res.status(400).json({error:'invalid_sex'}); if(birthDate!=null&&!validBirthDate(birthDate))return res.status(400).json({error:'invalid_birth_date'}); await pool.query(`update profile set household_persona=coalesce($2,household_persona),sex=coalesce($3,sex),birth_date=coalesce($4::date,birth_date),updated_at=now() where user_id=$1`,[req.identity.sub,persona??null,sex??null,birthDate??null]); res.status(204).end(); });
15 router.put('/me/education',requireAuth,async(req,res)=>{ const mapped=educationForGrade(req.body.nationalGrade); if(!mapped||(req.body.stage&&req.body.stage!==mapped.stage))return res.status(400).json({error:'invalid_grade_stage'}); const schoolYear=String(req.body.schoolYear??'1405-1406'); const r=await pool.query(`insert into education_profile(user_id,stage,national_grade,local_year,school_name,school_year) values($1,$2,$3,$4,$5,$6) on conflict(user_id) do update set stage=excluded.stage,national_grade=excluded.national_grade,local_year=excluded.local_year,school_name=excluded.school_name,school_year=excluded.school_year,updated_at=now() returning *`,[req.identity.sub,mapped.stage,mapped.nationalGrade,mapped.localYear,req.body.schoolName??null,schoolYear]); res.json(r.rows[0]); });
16 router.get('/education/catalog',requireAuth,async(req,res)=>{ const grade=Number(req.query.grade??7),schoolYear=String(req.query.schoolYear??'1405-1406'); if(!educationForGrade(grade))return res.status(400).json({error:'invalid_grade'}); const r=await pool.query(`select s.id,s.code,s.name_fa,s.national_grade,s.school_year,t.title_fa,t.publisher,t.source_url,t.redistribution_status from curriculum_subject s left join textbook_catalog t on t.curriculum_subject_id=s.id where s.country_code='IR' and s.national_grade=$1 and s.school_year=$2 order by s.sort_order,s.name_fa`,[grade,schoolYear]); res.json({grade,mapping:educationForGrade(grade),subjects:r.rows.map(row=>({...row,source_url:trustedTextbookUrl(row.source_url)?row.source_url:null}))}); });
17 router.get('/calendar/iran',requireAuth,async(req,res)=>{ const year=Number(req.query.year??1405); if(!Number.isInteger(year)||year<1300||year>1600)return res.status(400).json({error:'invalid_jalali_year'}); const r=await pool.query(`select jalali_year,jalali_month,jalali_day,title_fa,is_official_holiday,source_name,source_url from iran_calendar_event where jalali_year=$1 order by jalali_month,jalali_day,title_fa`,[year]); res.json({year,weekStartsOn:'saturday',weekendDays:['thursday','friday'],statutoryWeeklyHoliday:'friday',events:r.rows}); });
18 router.get('/me/notification-preferences',requireAuth,async(req,res)=>{ await pool.query('insert into notification_preference(user_id) values($1) on conflict do nothing',[req.identity.sub]); const r=await pool.query('select * from notification_preference where user_id=$1',[req.identity.sub]); res.json(r.rows[0]); });
19 router.patch('/me/notification-preferences',requireAuth,async(req,res)=>{ await pool.query('insert into notification_preference(user_id) values($1) on conflict do nothing',[req.identity.sub]); const fields={inAppBanner:'in_app_banner',pushEnabled:'push_enabled',plannerReminders:'planner_reminders',schoolReminders:'school_reminders',calendarReminders:'calendar_reminders',cycleReminders:'cycle_reminders',sensitivePreview:'sensitive_preview'}; for(const [input,column] of Object.entries(fields)){if(typeof req.body[input]==='boolean')await pool.query(`update notification_preference set ${column}=$2,updated_at=now() where user_id=$1`,[req.identity.sub,req.body[input]]);} const r=await pool.query('select * from notification_preference where user_id=$1',[req.identity.sub]); res.json(r.rows[0]); });
20 // Owner-private wellness records; no relationship-based read path is exposed.
19 - router.get('/me/menstrual-cycles',requireAuth,async(req,res)=>{ const r=await pool.query('select id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled,created_at,updated_at from menstrual_cycle_entry where owner_user_id=$1 order by starts_on desc limit 36',[req.identity.sub]); res.json({entries:r.rows}); });
20 - router.post('/me/menstrual-cycles',requireAuth,async(req,res)=>{ if(!req.body.startsOn)return res.status(400).json({error:'starts_on_required'}); const symptoms=Array.isArray(req.body.symptoms)?req.body.symptoms.slice(0,20).map(String):[]; const r=await pool.query(`insert into menstrual_cycle_entry(owner_user_id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled) values($1,$2::date,$3::date,$4::date,$5::text[],$6,$7) returning id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled`,[req.identity.sub,req.body.startsOn,req.body.endsOn??null,req.body.predictedNextOn??null,symptoms,req.body.notes??null,req.body.reminderEnabled===true]); res.status(201).json(r.rows[0]); });
21 - router.delete('/me/menstrual-cycles/:id',requireAuth,async(req,res)=>{ await pool.query('delete from menstrual_cycle_entry where id=$1 and owner_user_id=$2',[req.params.id,req.identity.sub]); res.status(204).end(); });
21 + router.get('/me/menstrual-cycles',requireAuth,requireSensitive,async(req,res)=>{ const r=await pool.query('select id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled,created_at,updated_at from menstrual_cycle_entry where owner_user_id=$1 order by starts_on desc limit 36',[req.identity.sub]); res.json({entries:r.rows}); });
22 + router.post('/me/menstrual-cycles',requireAuth,requireSensitive,async(req,res)=>{ if(!req.body.startsOn)return res.status(400).json({error:'starts_on_required'}); const symptoms=Array.isArray(req.body.symptoms)?req.body.symptoms.slice(0,20).map(String):[]; const r=await pool.query(`insert into menstrual_cycle_entry(owner_user_id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled) values($1,$2::date,$3::date,$4::date,$5::text[],$6,$7) returning id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled`,[req.identity.sub,req.body.startsOn,req.body.endsOn??null,req.body.predictedNextOn??null,symptoms,req.body.notes??null,req.body.reminderEnabled===true]); res.status(201).json(r.rows[0]); });
23 + router.delete('/me/menstrual-cycles/:id',requireAuth,requireSensitive,async(req,res)=>{ await pool.query('delete from menstrual_cycle_entry where id=$1 and owner_user_id=$2',[req.params.id,req.identity.sub]); res.status(204).end(); });
24 return router;
25 }
26 export {educationForGrade,trustedTextbookUrl};
backend/src/plan_mutations.js new
+199
@@ -0,0 +1,199 @@
1 +import crypto from 'node:crypto';
2 +
3 +const kinds = new Set(['task', 'event', 'routine', 'goal', 'assignment', 'exam', 'study_session']);
4 +const statuses = new Set(['planned', 'in_progress', 'completed', 'cancelled']);
5 +const priorities = new Set(['low', 'normal', 'high', 'urgent']);
6 +const scopes = new Set(['private', 'selected_members', 'parent_guardian', 'family']);
7 +export const validUuid = (x) => typeof x === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(x);
8 +export class PlanMutationError extends Error {
9 + constructor(status, code, details = {}) { super(code); this.status = status; this.code = code; this.details = details; }
10 +}
11 +const fail = (status, code, details) => { throw new PlanMutationError(status, code, details); };
12 +export function serializePlanItem(item, viewer) {
13 + const result = { ...item, version: Number(item.version), activity_version: Number(item.activity_version) };
14 + if (item.owner_user_id !== viewer) delete result.notes;
15 + return result;
16 +}
17 +function canonical(value) {
18 + if (Array.isArray(value)) return value.map(canonical);
19 + if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
20 + return value;
21 +}
22 +function date(value, field) {
23 + if (value === null) return null;
24 + if (typeof value !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,6})?(?:Z|[+-]\d\d:\d\d)$/.test(value)) fail(400, `invalid_${field}`);
25 + const parsed = new Date(value);
26 + if (!Number.isFinite(parsed.getTime())) fail(400, `invalid_${field}`);
27 + return parsed;
28 +}
29 +function text(value, field, max, nullable = false) {
30 + if (nullable && value === null) return null;
31 + if (typeof value !== 'string' || value.length > max || (!nullable && !value.trim())) fail(400, `invalid_${field}`);
32 + return nullable ? value : value.trim();
33 +}
34 +function id(value, field) {
35 + if (value === null) return null;
36 + if (!validUuid(value)) fail(400, `invalid_${field}`);
37 + return value;
38 +}
39 +function integer(value, field, min, max) {
40 + if (value === null) return null;
41 + if (!Number.isSafeInteger(value) || value < min || value > max) fail(400, `invalid_${field}`);
42 + return value;
43 +}
44 +function normalize(payload, existing = null) {
45 + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) fail(400, 'invalid_plan_item');
46 + for (const key of ['ownerUserId', 'owner_user_id', 'version', 'activity_version', 'created_at', 'updated_at', 'completed_at']) if (key in payload) fail(400, 'server_owned_field');
47 + const fields = {};
48 + const isCreate = !existing;
49 + const defaults = { kind: 'task', title: '', priority: 'normal', visibility: 'private', familyId: null, subjectId: null,
50 + notes: null, startsAt: null, dueAt: null, durationMinutes: null, plannedDurationSeconds: null,
51 + recurrenceRule: null, parentItemId: null };
52 + const values = isCreate ? { ...defaults, ...payload } : payload;
53 + const pick = (key, column, validation) => { if (values[key] !== undefined) fields[column] = validation(values[key]); };
54 + pick('kind', 'kind', (x) => { if (!kinds.has(x)) fail(400, 'invalid_kind'); return x; });
55 + pick('title', 'title', (x) => text(x, 'title', 240));
56 + pick('notes', 'notes', (x) => text(x, 'notes', 10000, true));
57 + pick('priority', 'priority', (x) => { if (!priorities.has(x)) fail(400, 'invalid_priority'); return x; });
58 + pick('visibility', 'visibility', (x) => { if (!scopes.has(x)) fail(400, 'invalid_visibility'); return x; });
59 + pick('status', 'status', (x) => { if (!statuses.has(x) || (isCreate && x !== 'planned')) fail(400, 'invalid_status'); return x; });
60 + pick('familyId', 'family_id', (x) => id(x, 'family_id'));
61 + pick('subjectId', 'subject_id', (x) => id(x, 'subject_id'));
62 + pick('parentItemId', 'parent_item_id', (x) => id(x, 'parent_item_id'));
63 + pick('startsAt', 'starts_at', (x) => date(x, 'starts_at'));
64 + pick('dueAt', 'due_at', (x) => date(x, 'due_at'));
65 + pick('recurrenceRule', 'recurrence_rule', (x) => text(x, 'recurrence_rule', 1000, true));
66 + pick('durationMinutes', 'duration_minutes', (x) => integer(x, 'duration_minutes', 1, 1440));
67 + pick('plannedDurationSeconds', 'planned_duration_seconds', (x) => integer(x, 'planned_duration_seconds', 0, 86400));
68 + for (const [key, column] of [['gradePoints', 'grade_points'], ['gradeOutOf', 'grade_out_of']]) pick(key, column, (x) => {
69 + if (x === null) return null;
70 + if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > 999999.99) fail(400, 'invalid_grade');
71 + return x;
72 + });
73 + if (payload.plannedDurationSeconds !== undefined) fields.duration_minutes = payload.plannedDurationSeconds == null || payload.plannedDurationSeconds === 0 ? null : Math.ceil(payload.plannedDurationSeconds / 60);
74 + else if (payload.durationMinutes !== undefined) fields.planned_duration_seconds = payload.durationMinutes == null ? null : payload.durationMinutes * 60;
75 + const merged = { ...existing, ...fields };
76 + if (fields.grade_points !== undefined || fields.grade_out_of !== undefined) {
77 + if (!['assignment', 'exam'].includes(merged.kind)) fail(400, 'grade_not_applicable');
78 + if (!(merged.grade_points == null && merged.grade_out_of == null)
79 + && (merged.grade_points == null || merged.grade_out_of == null || Number(merged.grade_out_of) <= 0 || Number(merged.grade_points) > Number(merged.grade_out_of))) fail(400, 'invalid_grade');
80 + }
81 + if (merged.starts_at && merged.due_at && new Date(merged.due_at) < new Date(merged.starts_at)) fail(400, 'invalid_date_order');
82 + if (['family', 'parent_guardian', 'selected_members'].includes(merged.visibility) && !merged.family_id) fail(400, 'family_required_for_visibility');
83 + return { fields, merged };
84 +}
85 +export async function planOwnerLock(client, userId) {
86 + await client.query('select pg_advisory_xact_lock(hashtextextended($1::text,0))', [userId]);
87 +}
88 +async function authorize(client, userId, item) {
89 + if (!(await client.query('select 1 from app_user where id=$1 and disabled_at is null', [userId])).rowCount) fail(401, 'unauthorized');
90 + if (item && item.owner_user_id !== userId) fail(403, 'forbidden');
91 + if (item?.family_id && !(await client.query('select 1 where is_active_family_member($1,$2)', [item.family_id, userId])).rowCount) fail(403, 'family_membership_required');
92 +}
93 +async function relations(client, userId, item, payload, existing = null) {
94 + await authorize(client, userId, item);
95 + if (item.subject_id && !(await client.query('select 1 from subject where id=$1 and student_user_id=$2', [item.subject_id, userId])).rowCount) fail(403, 'subject_forbidden');
96 + if (item.parent_item_id && !(await client.query('select 1 from plan_item where id=$1 and owner_user_id=$2', [item.parent_item_id, userId])).rowCount) fail(403, 'parent_item_forbidden');
97 + if (payload.selectedMemberIds !== undefined && (!Array.isArray(payload.selectedMemberIds) || payload.selectedMemberIds.length > 100)) fail(400, 'invalid_selected_members');
98 + const selected = payload.selectedMemberIds === undefined ? null : [...new Set(payload.selectedMemberIds)];
99 + if (item.visibility === 'selected_members' && (!existing || existing.visibility !== 'selected_members' || existing.family_id !== item.family_id) && (!selected || !selected.length)) fail(400, 'selected_members_required');
100 + if (selected) for (const member of selected) {
101 + if (!validUuid(member) || !(await client.query('select 1 where is_active_family_member($1,$2)', [item.family_id, member])).rowCount) fail(400, 'selected_member_not_in_family');
102 + }
103 + return selected;
104 +}
105 +async function grants(client, item, selected) {
106 + if (selected !== null || item.visibility !== 'selected_members') await client.query("delete from sharing_grant where resource_type='plan_item' and resource_id=$1", [item.id]);
107 + if (item.visibility === 'selected_members' && selected) for (const member of selected) await client.query(
108 + "insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [item.id, member, item.owner_user_id],
109 + );
110 +}
111 +async function reminders(client, item, payload) {
112 + if (payload.reminderMinutesBefore !== undefined) {
113 + if (!Array.isArray(payload.reminderMinutesBefore) || payload.reminderMinutesBefore.length > 100 || payload.reminderMinutesBefore.some((x) => !Number.isSafeInteger(x) || x < 0 || x > 10080)) fail(400, 'invalid_reminders');
114 + await client.query('delete from reminder where plan_item_id=$1', [item.id]);
115 + const base = item.starts_at ?? item.due_at;
116 + if (base) for (const minutes of new Set(payload.reminderMinutesBefore)) await client.query(
117 + 'insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for) values($1,$2,$3,$4::timestamptz-make_interval(mins=>$3))', [item.id, item.owner_user_id, minutes, base],
118 + );
119 + }
120 + if (['completed', 'cancelled'].includes(item.status)) await client.query("update reminder set status='cancelled' where plan_item_id=$1 and status in ('scheduled','claimed')", [item.id]);
121 + else await client.query('select recompute_reminder_schedule($1)', [item.id]);
122 +}
123 +export async function createPlanItem(client, userId, payload, itemId = crypto.randomUUID()) {
124 + if (!validUuid(itemId)) fail(400, 'invalid_id');
125 + const { fields } = normalize(payload);
126 + const selected = await relations(client, userId, { ...fields, owner_user_id: userId }, payload);
127 + const columns = ['id', 'owner_user_id', ...Object.keys(fields)];
128 + const values = [itemId, userId, ...Object.values(fields)];
129 + const row = (await client.query(`insert into plan_item(${columns.join(',')}) values(${values.map((_, i) => `$${i + 1}`).join(',')}) returning *`, values)).rows[0];
130 + await grants(client, row, selected);
131 + await reminders(client, row, payload);
132 + return row;
133 +}
134 +export async function updatePlanItem(client, userId, itemId, payload, expectedVersion) {
135 + if (!validUuid(itemId)) fail(400, 'invalid_id');
136 + const current = (await client.query('select * from plan_item where id=$1 for update', [itemId])).rows[0];
137 + if (!current) fail(404, 'not_found');
138 + await authorize(client, userId, current);
139 + if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0) fail(400, 'expected_version_required');
140 + if (expectedVersion !== Number(current.version)) fail(409, 'version_conflict', { serverVersion: Number(current.version) });
141 + const { fields, merged } = normalize(payload, current);
142 + if (!Object.keys(fields).length && payload.selectedMemberIds === undefined && payload.reminderMinutesBefore === undefined) fail(400, 'no_changes');
143 + const selected = await relations(client, userId, merged, payload, current);
144 + if (fields.status !== undefined) fields.completed_at = fields.status === 'completed' ? current.completed_at ?? new Date() : null;
145 + const values = [itemId, ...Object.values(fields)];
146 + const update = [...Object.keys(fields).map((key, i) => `${key}=$${i + 2}`), 'updated_at=now()'];
147 + const item = (await client.query(`update plan_item set ${update.join(',')} where id=$1 returning *`, values)).rows[0];
148 + await grants(client, item, selected);
149 + await reminders(client, item, payload);
150 + return item;
151 +}
152 +export async function planTransaction(pool, userId, execute) {
153 + const client = await pool.connect();
154 + try { await client.query('begin'); await planOwnerLock(client, userId); const result = await execute(client); await client.query('commit'); return result; }
155 + catch (error) { await client.query('rollback').catch(() => {}); if (error.code === '23505') fail(409, 'plan_item_exists'); throw error; }
156 + finally { client.release(); }
157 +}
158 +export async function applyPlanMutation(pool, userId, mutation) {
159 + const idValue = mutation?.id;
160 + try {
161 + if (!validUuid(idValue) || mutation.entityType !== 'plan_item' || !validUuid(mutation.entityId)
162 + || !['create', 'update', 'complete', 'reschedule', 'archive'].includes(mutation.operation)
163 + || !mutation.payload || typeof mutation.payload !== 'object' || Array.isArray(mutation.payload)) fail(400, 'invalid_mutation');
164 + const hash = crypto.createHash('sha256').update(JSON.stringify(canonical({ entityType: mutation.entityType, entityId: mutation.entityId, operation: mutation.operation, expectedVersion: mutation.expectedVersion ?? null, payload: mutation.payload }))).digest('hex');
165 + return await planTransaction(pool, userId, async (client) => {
166 + const previous = (await client.query('select * from sync_mutation where user_id=$1 and id=$2', [userId, idValue])).rows[0];
167 + if (previous) {
168 + const current = (await client.query('select * from plan_item where id=$1', [previous.entity_id])).rows[0];
169 + if (!current) fail(404, 'not_found');
170 + await authorize(client, userId, current);
171 + if (previous.request_hash !== hash || !previous.canonical_item) fail(409, 'mutation_id_reused', { serverVersion: Number(current.version) });
172 + return { id: idValue, entityId: previous.entity_id, status: 'already_applied', acceptedAt: previous.accepted_at, item: previous.canonical_item };
173 + }
174 + let item;
175 + if (mutation.operation === 'create') {
176 + if (mutation.expectedVersion !== undefined && mutation.expectedVersion !== 0) fail(400, 'create_expected_version_zero');
177 + if (mutation.payload.id !== undefined && mutation.payload.id !== mutation.entityId) fail(400, 'entity_id_mismatch');
178 + item = await createPlanItem(client, userId, mutation.payload, mutation.entityId);
179 + } else {
180 + const payload = { ...mutation.payload };
181 + if (mutation.operation === 'complete') payload.status = 'completed';
182 + if (mutation.operation === 'archive') payload.status = 'cancelled';
183 + if (mutation.operation === 'reschedule' && payload.dueAt === undefined && payload.startsAt === undefined) fail(400, 'invalid_reschedule');
184 + item = await updatePlanItem(client, userId, mutation.entityId, payload, mutation.expectedVersion);
185 + }
186 + const canonicalItem = serializePlanItem(item, userId);
187 + const accepted = (await client.query(
188 + `insert into sync_mutation(id,user_id,entity_type,entity_id,operation,client_updated_at,payload,request_hash,canonical_item)
189 + values($1,$2,'plan_item',$3,$4,now(),$5::jsonb,$6,$7::jsonb) returning accepted_at`,
190 + [idValue, userId, item.id, mutation.operation, JSON.stringify(mutation.payload), hash, JSON.stringify(canonicalItem)],
191 + )).rows[0].accepted_at;
192 + return { id: idValue, entityId: item.id, status: 'accepted', acceptedAt: accepted, item: canonicalItem };
193 + });
194 + } catch (error) {
195 + if (!(error instanceof PlanMutationError)) throw error;
196 + return { id: idValue ?? null, entityId: mutation?.entityId ?? null,
197 + status: error.status === 409 ? 'conflict' : 'rejected', error: error.code, httpStatus: error.status, ...error.details };
198 + }
199 +}
backend/src/profile_router.js new
+50
@@ -0,0 +1,50 @@
1 +import express from 'express';
2 +
3 +const categories = new Set(['girl_minor', 'boy_minor', 'adult']);
4 +const themes = new Set(['girl_pink', 'boy_blue', 'adult_blue', 'custom']);
5 +
6 +export function validBirthDate(value) {
7 + if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000-')) return false;
8 + const date = new Date(`${value}T00:00:00Z`);
9 + return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
10 +}
11 +
12 +export function createProfileRouter({ pool, auth }) {
13 + const router = express.Router();
14 + router.use(auth);
15 +
16 + router.get('/', async (req, res) => {
17 + const result = await pool.query(
18 + `select u.id as user_id,p.display_name,p.birth_date,p.theme_preference,p.profile_category,
19 + u.email_normalized,u.email_verified_at,u.phone_normalized,u.phone_verified_at
20 + from profile p join app_user u on u.id=p.user_id where p.user_id=$1`,
21 + [req.identity.sub],
22 + );
23 + if (!result.rowCount) return res.status(404).json({ error: 'profile_not_found' });
24 + res.json(result.rows[0]);
25 + });
26 +
27 + router.patch('/', async (req, res) => {
28 + const body = req.body ?? {};
29 + const name = body.displayName == null ? null : String(body.displayName).trim();
30 + const theme = body.themePreference == null ? null : String(body.themePreference);
31 + const category = body.profileCategory;
32 + const birthDate = body.birthDate;
33 + if (name != null && (!name || name.length > 100)) return res.status(400).json({ error: 'invalid_display_name' });
34 + if (theme != null && !themes.has(theme)) return res.status(400).json({ error: 'invalid_theme' });
35 + if (Object.hasOwn(body, 'profileCategory') && !categories.has(category)) return res.status(400).json({ error: 'invalid_profile_category' });
36 + if (birthDate != null && !validBirthDate(birthDate)) return res.status(400).json({ error: 'invalid_birth_date' });
37 + const result = await pool.query(
38 + `update profile set display_name=coalesce($2,display_name),
39 + birth_date=coalesce($3::date,birth_date),
40 + theme_preference=coalesce($4,theme_preference),
41 + profile_category=coalesce($5,profile_category),updated_at=now()
42 + where user_id=$1 returning display_name,birth_date,theme_preference,profile_category`,
43 + [req.identity.sub, name, birthDate ?? null, theme, category ?? null],
44 + );
45 + if (!result.rowCount) return res.status(404).json({ error: 'profile_not_found' });
46 + res.json(result.rows[0]);
47 + });
48 +
49 + return router;
50 +}
backend/src/server.js
+188 -399
@@ -1,19 +1,22 @@
1 import crypto from 'node:crypto';
2 import { pathToFileURL } from 'node:url';
3 import express from 'express';
4 -import argon2 from 'argon2';
5 -import jwt from 'jsonwebtoken';
4 import pg from 'pg';
7 -import nodemailer from 'nodemailer';
5 import cors from 'cors';
6 import { createPhase3Router } from './phase3.js';
7 import { createPhase4Router } from './phase4.js';
8 import { createPhase6Router } from './phase6.js';
12 -import { operationalErrorHandler } from './operations.js';
9 +import { configureTrustedProxy, operationalErrorHandler } from './operations.js';
10 import { createSessionAuth } from './session_auth.js';
11 +import { createAuthRouter } from './auth_router.js';
12 +import { createStudySessionsRouter } from './study_sessions.js';
13 +import { createProfileRouter } from './profile_router.js';
14 +import { normalizeEmail, normalizePhone, isEmail } from './auth_contacts.js';
15 +import { createEmailProvider, safelyDeliver } from './auth_delivery.js';
16
17 const { Pool } = pg;
18 const app = express();
19 +configureTrustedProxy(app);
20 const allowedOrigins = (process.env.CORS_ORIGINS ?? '')
21 .split(',')
22 .map((value) => value.trim())
@@ -41,361 +44,60 @@ if (!jwtSecret || jwtSecret.length < 32) throw new Error('JWT_SECRET must be at
44
45 const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
46 const randomToken = () => crypto.randomBytes(32).toString('base64url');
44 -const normalizeEmail = (email) => String(email ?? '').trim().toLowerCase();
45 -const validPassword = (p) => typeof p === 'string' && p.length >= 10 && p.length <= 200;
46 -const isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
47 const testMode = process.env.NODE_ENV === 'test';
48 -
49 -async function sendTransactionalEmail({ to, subject, text }) {
50 - if (testMode) return { delivered: false, testMode: true };
51 -
52 - const from = process.env.EMAIL_FROM;
53 - if (!from) return { delivered: false, reason: 'provider_not_configured' };
54 -
55 - const apiKey = process.env.RESEND_API_KEY;
56 - if (apiKey) {
57 - const response = await fetch('https://api.resend.com/emails', {
58 - method: 'POST',
59 - headers: {
60 - Authorization: `Bearer ${apiKey}`,
61 - 'Content-Type': 'application/json',
62 - },
63 - body: JSON.stringify({ from, to: [to], subject, text }),
64 - });
65 - if (!response.ok) throw new Error(`email_delivery_failed:${response.status}`);
66 - return { delivered: true, provider: 'resend' };
67 - }
68 -
69 - const smtpHost = process.env.SMTP_HOST;
70 - const smtpPort = Number(process.env.SMTP_PORT ?? 0);
71 - if (smtpHost && smtpPort > 0) {
72 - const transporter = nodemailer.createTransport({
73 - host: smtpHost,
74 - port: smtpPort,
75 - secure: process.env.SMTP_SECURE === 'true',
76 - auth: process.env.SMTP_USER
77 - ? {
78 - user: process.env.SMTP_USER,
79 - pass: process.env.SMTP_PASSWORD,
80 - }
81 - : undefined,
82 - });
83 - await transporter.sendMail({ from, to, subject, text });
84 - return { delivered: true, provider: 'smtp' };
85 - }
86 -
87 - return { delivered: false, reason: 'provider_not_configured' };
88 -}
89 -
90 -const issueAccess = (userId, sessionId) =>
91 - jwt.sign(
92 - { sub: userId, sid: sessionId, aud: 'lifemate-api' },
93 - jwtSecret,
94 - { expiresIn: '15m', issuer: 'lifemate' },
95 - );
96 -
48 +const emailProvider = createEmailProvider();
49 const auth = createSessionAuth({ pool, jwtSecret });
98 -
99 -async function createOneTimeToken(client, userId, kind, minutes) {
100 - const raw = randomToken();
101 - await client.query(
102 - "insert into auth_token(user_id,kind,token_digest,expires_at) values($1,$2,$3,now()+($4 || ' minutes')::interval)",
103 - [userId, kind, sha256(raw), String(minutes)],
104 - );
105 - return raw;
106 -}
107 -
108 -async function createSession(client, userId) {
109 - const refreshToken = randomToken();
110 - const r = await client.query(
111 - "insert into auth_session(user_id,refresh_digest,expires_at) values($1,$2,now()+interval '30 days') returning id",
112 - [userId, sha256(refreshToken)],
113 - );
114 - return {
115 - accessToken: issueAccess(userId, r.rows[0].id),
116 - refreshToken,
117 - };
118 -}
50 +const uuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
51
52 async function familyAccess(familyId, userId, { roles = [], admin = false } = {}) {
53 + if (!uuid(familyId)) return false;
54 const r = await pool.query(
122 - 'select role,is_admin from family_membership where family_id=$1 and user_id=$2 and ended_at is null',
55 + `select m.role,m.is_admin from family_membership m
56 + join family_workspace f on f.id=m.family_id
57 + where m.family_id=$1 and m.user_id=$2 and m.ended_at is null and f.archived_at is null`,
58 [familyId, userId],
59 );
60 if (!r.rowCount) return false;
61 return (admin && r.rows[0].is_admin) || roles.includes(r.rows[0].role);
62 }
63
129 -app.get('/health', async (_req, res) => {
130 - const r = await pool.query('select 1 as ok');
131 - res.json({
132 - status: r.rows[0].ok === 1 ? 'ok' : 'degraded',
133 - emailProviderConfigured: Boolean(process.env.EMAIL_FROM && (process.env.RESEND_API_KEY || (process.env.SMTP_HOST && process.env.SMTP_PORT))),
134 - });
135 -});
136 -
137 -app.post('/v1/auth/register', async (req, res) => {
138 - const email = normalizeEmail(req.body.email);
139 - const password = req.body.password;
140 - const name = String(req.body.displayName ?? '').trim();
141 - if (!isEmail(email) || !validPassword(password) || !name) {
142 - return res.status(400).json({ error: 'invalid_input' });
143 - }
144 -
64 +async function familyAdminTransaction(familyId, userId, operation) {
65 + if (!uuid(familyId)) return { status: 403, body: { error: 'forbidden' } };
66 const client = await pool.connect();
67 try {
68 await client.query('begin');
148 - const hash = await argon2.hash(password, { type: argon2.argon2id });
149 - const u = await client.query(
150 - 'insert into app_user(identity_subject,email_normalized) values($1,$2) returning id',
151 - [`local:${crypto.randomUUID()}`, email],
152 - );
153 - await client.query(
154 - "insert into profile(user_id,display_name,theme_preference) values($1,$2,'adult_blue')",
155 - [u.rows[0].id, name],
156 - );
157 - await client.query(
158 - 'insert into auth_credential(user_id,password_hash) values($1,$2)',
159 - [u.rows[0].id, hash],
160 - );
161 - const verificationToken = await createOneTimeToken(
162 - client,
163 - u.rows[0].id,
164 - 'email_verification',
165 - 60 * 24,
166 - );
69 + const family = await client.query('select id from family_workspace where id=$1 and archived_at is null for update', [familyId]);
70 + const membership = family.rowCount ? await client.query(
71 + `select 1 from family_membership m join app_user u on u.id=m.user_id
72 + where m.family_id=$1 and m.user_id=$2 and m.ended_at is null
73 + and m.is_admin and u.disabled_at is null for update of m,u`, [familyId, userId],
74 + ) : { rowCount: 0 };
75 + const result = membership.rowCount ? await operation(client) : { status: 403, body: { error: 'forbidden' } };
76 await client.query('commit');
168 -
169 - const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid';
170 - const delivery = await sendTransactionalEmail({
171 - to: email,
172 - subject: 'تأیید حساب LifeMate',
173 - text: `برای تأیید حساب LifeMate این لینک را باز کنید: ${baseUrl}/verify-email?token=${encodeURIComponent(verificationToken)}`,
174 - });
175 -
176 - res.status(201).json({
177 - userId: u.rows[0].id,
178 - verificationToken: testMode ? verificationToken : undefined,
179 - emailDelivery: delivery.delivered ? 'sent' : 'pending_configuration',
180 - });
181 - } catch (e) {
77 + return result;
78 + } catch (error) {
79 await client.query('rollback').catch(() => {});
183 - if (e.code === '23505') return res.status(409).json({ error: 'account_exists' });
184 - throw e;
185 - } finally {
186 - client.release();
187 - }
188 -});
189 -
190 -app.post('/v1/auth/verify-email', async (req, res) => {
191 - const digest = sha256(String(req.body.token ?? ''));
192 - const client = await pool.connect();
193 - try {
194 - await client.query('begin');
195 - const r = await client.query(
196 - "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",
197 - [digest],
198 - );
199 - if (!r.rowCount) {
200 - await client.query('rollback');
201 - return res.status(400).json({ error: 'invalid_or_expired_token' });
202 - }
203 - await client.query('update auth_token set used_at=now() where token_digest=$1', [digest]);
204 - await client.query(
205 - 'update app_user set email_verified_at=coalesce(email_verified_at,now()) where id=$1',
206 - [r.rows[0].user_id],
207 - );
208 - await client.query('commit');
209 - res.status(204).end();
210 - } finally {
211 - client.release();
212 - }
213 -});
214 -
215 -app.post('/v1/auth/login', async (req, res) => {
216 - const email = normalizeEmail(req.body.email);
217 - const password = String(req.body.password ?? '');
218 - const r = await pool.query(
219 - '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',
220 - [email],
221 - );
222 - if (!r.rowCount || !(await argon2.verify(r.rows[0].password_hash, password))) {
223 - return res.status(401).json({ error: 'invalid_credentials' });
224 - }
225 - if (!r.rows[0].email_verified_at) {
226 - return res.status(403).json({ error: 'email_not_verified' });
227 - }
228 -
229 - const client = await pool.connect();
230 - try {
231 - const tokens = await createSession(client, r.rows[0].id);
232 - res.json(tokens);
233 - } finally {
234 - client.release();
235 - }
236 -});
237 -
238 -app.post('/v1/auth/refresh', async (req, res) => {
239 - const digest = sha256(String(req.body.refreshToken ?? ''));
240 - const client = await pool.connect();
241 - try {
242 - await client.query('begin');
243 - const r = await client.query(
244 - `select s.id,s.user_id from auth_session s join app_user u on u.id=s.user_id
245 - where s.refresh_digest=$1 and s.revoked_at is null and s.expires_at>now()
246 - and u.disabled_at is null for update of s,u`,
247 - [digest],
248 - );
249 - if (!r.rowCount) {
250 - await client.query('rollback');
251 - return res.status(401).json({ error: 'invalid_refresh_token' });
252 - }
253 -
254 - await client.query('update auth_session set revoked_at=now() where id=$1', [r.rows[0].id]);
255 - const tokens = await createSession(client, r.rows[0].user_id);
256 - await client.query('commit');
257 - res.json(tokens);
258 - } finally {
259 - client.release();
260 - }
261 -});
262 -
263 -app.post('/v1/auth/forgot-password', async (req, res) => {
264 - const email = normalizeEmail(req.body.email);
265 - const r = await pool.query(
266 - 'select id from app_user where email_normalized=$1 and disabled_at is null',
267 - [email],
268 - );
269 -
270 - let resetToken;
271 - if (r.rowCount) {
272 - const c = await pool.connect();
273 - try {
274 - resetToken = await createOneTimeToken(c, r.rows[0].id, 'password_reset', 30);
275 - } finally {
276 - c.release();
277 - }
278 - const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid';
279 - await sendTransactionalEmail({
280 - to: email,
281 - subject: 'بازیابی رمز عبور LifeMate',
282 - text: `برای ساخت رمز جدید این لینک را باز کنید: ${baseUrl}/reset-password?token=${encodeURIComponent(resetToken)}`,
283 - });
284 - }
80 + throw error;
81 + } finally { client.release(); }
82 +}
83 +function familyResponse(res, result) {
84 + return result.body === undefined ? res.status(result.status).end() : res.status(result.status).json(result.body);
85 +}
86 +async function familyAudit(client, familyId, userId, action, targetType, targetId) {
87 + await client.query('insert into access_audit(actor_user_id,family_id,action,target_type,target_id) values($1,$2,$3,$4,$5)', [userId, familyId, action, targetType, targetId]);
88 +}
89
90 +app.get('/health', async (_req, res) => {
91 + const r = await pool.query('select 1 as ok');
92 res.json({
287 - accepted: true,
288 - resetToken: testMode ? resetToken : undefined,
93 + status: r.rows[0].ok === 1 ? 'ok' : 'degraded',
94 + emailProviderConfigured: emailProvider.configured,
95 });
96 });
97
292 -app.post('/v1/auth/reset-password', async (req, res) => {
293 - if (!validPassword(req.body.newPassword)) {
294 - return res.status(400).json({ error: 'invalid_password' });
295 - }
98 +app.use('/v1/auth', createAuthRouter({ pool, jwtSecret, auth, emailProvider }));
99
297 - const digest = sha256(String(req.body.token ?? ''));
298 - const client = await pool.connect();
299 - try {
300 - await client.query('begin');
301 - const r = await client.query(
302 - "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",
303 - [digest],
304 - );
305 - if (!r.rowCount) {
306 - await client.query('rollback');
307 - return res.status(400).json({ error: 'invalid_or_expired_token' });
308 - }
309 -
310 - await client.query('update auth_token set used_at=now() where token_digest=$1', [digest]);
311 - const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
312 - await client.query(
313 - 'update auth_credential set password_hash=$1,password_changed_at=now() where user_id=$2',
314 - [hash, r.rows[0].user_id],
315 - );
316 - await client.query(
317 - 'update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null',
318 - [r.rows[0].user_id],
319 - );
320 - await client.query('commit');
321 - res.status(204).end();
322 - } finally {
323 - client.release();
324 - }
325 -});
326 -
327 -app.post('/v1/auth/change-password', auth, async (req, res) => {
328 - if (!validPassword(req.body.newPassword)) {
329 - return res.status(400).json({ error: 'invalid_password' });
330 - }
331 -
332 - const r = await pool.query(
333 - 'select password_hash from auth_credential where user_id=$1',
334 - [req.identity.sub],
335 - );
336 - if (
337 - !r.rowCount ||
338 - !(await argon2.verify(r.rows[0].password_hash, String(req.body.currentPassword ?? '')))
339 - ) {
340 - return res.status(403).json({ error: 'invalid_current_password' });
341 - }
342 -
343 - const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
344 - const client = await pool.connect();
345 - try {
346 - await client.query('begin');
347 - await client.query(
348 - 'update auth_credential set password_hash=$1,password_changed_at=now() where user_id=$2',
349 - [hash, req.identity.sub],
350 - );
351 - await client.query(
352 - 'update auth_session set revoked_at=now() where user_id=$1 and id<>$2 and revoked_at is null',
353 - [req.identity.sub, req.identity.sid],
354 - );
355 - await client.query('commit');
356 - res.status(204).end();
357 - } finally {
358 - client.release();
359 - }
360 -});
361 -
362 -app.post('/v1/auth/logout', auth, async (req, res) => {
363 - await pool.query('update auth_session set revoked_at=now() where id=$1', [req.identity.sid]);
364 - res.status(204).end();
365 -});
366 -
367 -app.get('/v1/profile', auth, async (req, res) => {
368 - const r = await pool.query(
369 - 'select u.id as user_id,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',
370 - [req.identity.sub],
371 - );
372 - if (!r.rowCount) return res.status(404).json({ error: 'profile_not_found' });
373 - res.json(r.rows[0]);
374 -});
375 -
376 -app.patch('/v1/profile', auth, async (req, res) => {
377 - const name = req.body.displayName == null ? null : String(req.body.displayName).trim();
378 - const theme = req.body.themePreference == null ? null : String(req.body.themePreference);
379 - const allowedThemes = ['girl_pink', 'boy_blue', 'adult_blue', 'custom'];
380 - if (name != null && (!name || name.length > 100)) {
381 - return res.status(400).json({ error: 'invalid_display_name' });
382 - }
383 - if (theme != null && !allowedThemes.includes(theme)) {
384 - return res.status(400).json({ error: 'invalid_theme' });
385 - }
386 -
387 - const r = await pool.query(
388 - `update profile
389 - set display_name=coalesce($2,display_name),
390 - birth_date=coalesce($3::date,birth_date),
391 - theme_preference=coalesce($4,theme_preference),
392 - updated_at=now()
393 - where user_id=$1
394 - returning display_name,birth_date,theme_preference`,
395 - [req.identity.sub, name, req.body.birthDate ?? null, theme],
396 - );
397 - res.json(r.rows[0]);
398 -});
100 +app.use('/v1/profile', createProfileRouter({ pool, auth }));
101
102 app.get('/v1/families', auth, async (req, res) => {
103 const r = await pool.query(
@@ -411,7 +113,7 @@ app.get('/v1/families', auth, async (req, res) => {
113
114 app.post('/v1/families', auth, async (req, res) => {
115 const name = String(req.body.name ?? '').trim();
414 - if (!name) return res.status(400).json({ error: 'invalid_name' });
116 + if (!name || name.length > 120) return res.status(400).json({ error: 'invalid_name' });
117
118 const creatorRole = ['parent_guardian', 'adult_member'].includes(req.body.role)
119 ? req.body.role
@@ -441,6 +143,57 @@ app.post('/v1/families', auth, async (req, res) => {
143 }
144 });
145
146 +app.get('/v1/families/:familyId', auth, async (req, res) => {
147 + if (!await familyAccess(req.params.familyId, req.identity.sub, { roles: ['parent_guardian', 'teen_minor', 'adult_member'] })) return res.status(403).json({ error: 'forbidden' });
148 + const result = await pool.query(`select f.id,f.name,m.role,m.is_admin from family_workspace f
149 + join family_membership m on m.family_id=f.id where f.id=$1 and f.archived_at is null
150 + and m.user_id=$2 and m.ended_at is null`, [req.params.familyId, req.identity.sub]);
151 + if (!result.rowCount) return res.status(403).json({ error: 'forbidden' });
152 + res.json(result.rows[0]);
153 +});
154 +
155 +app.patch('/v1/families/:familyId', auth, async (req, res) => {
156 + const name = String(req.body?.name ?? '').trim();
157 + if (!name || name.length > 120) return res.status(400).json({ error: 'invalid_name' });
158 + const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
159 + const updated = await client.query('update family_workspace set name=$2 where id=$1 returning id,name', [req.params.familyId, name]);
160 + await familyAudit(client, req.params.familyId, req.identity.sub, 'family.rename', 'family', req.params.familyId);
161 + return { status: 200, body: updated.rows[0] };
162 + });
163 + familyResponse(res, result);
164 +});
165 +
166 +app.delete('/v1/families/:familyId', auth, async (req, res) => {
167 + const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
168 + await client.query('update family_workspace set archived_at=now() where id=$1', [req.params.familyId]);
169 + await client.query("update family_invitation set status='revoked' where family_id=$1 and status='pending'", [req.params.familyId]);
170 + await client.query('update guardian_relationship set active=false where family_id=$1', [req.params.familyId]);
171 + await familyAudit(client, req.params.familyId, req.identity.sub, 'family.archive', 'family', req.params.familyId);
172 + return { status: 204 };
173 + });
174 + familyResponse(res, result);
175 +});
176 +
177 +app.delete('/v1/families/:familyId/members/:userId', auth, async (req, res) => {
178 + if (!uuid(req.params.userId)) return res.status(400).json({ error: 'invalid_member' });
179 + const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
180 + const target = await client.query('select m.is_admin,u.disabled_at from family_membership m join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id=$2 and m.ended_at is null for update of m', [req.params.familyId, req.params.userId]);
181 + if (!target.rowCount) return { status: 204 };
182 + if (target.rows[0].is_admin && !target.rows[0].disabled_at) {
183 + const count = await client.query('select count(*)::int as n from family_membership m join app_user u on u.id=m.user_id where m.family_id=$1 and m.ended_at is null and m.is_admin and u.disabled_at is null', [req.params.familyId]);
184 + if (count.rows[0].n <= 1) return { status: 409, body: { error: 'last_admin_required' } };
185 + }
186 + await client.query('update family_membership set ended_at=now(),is_admin=false where family_id=$1 and user_id=$2', [req.params.familyId, req.params.userId]);
187 + await client.query('update guardian_relationship set active=false where family_id=$1 and (guardian_user_id=$2 or minor_user_id=$2)', [req.params.familyId, req.params.userId]);
188 + await client.query(`update family_invitation i set status='revoked' from app_user u where u.id=$2
189 + and i.family_id=$1 and i.status='pending' and (i.invited_by=u.id
190 + or i.invited_email_normalized=u.email_normalized or i.invited_phone_normalized=u.phone_normalized)`, [req.params.familyId, req.params.userId]);
191 + await familyAudit(client, req.params.familyId, req.identity.sub, 'membership.end', 'membership', req.params.userId);
192 + return { status: 204 };
193 + });
194 + familyResponse(res, result);
195 +});
196 +
197 app.get('/v1/families/:familyId/members', auth, async (req, res) => {
198 const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
199 roles: ['parent_guardian', 'teen_minor', 'adult_member'],
@@ -451,9 +204,11 @@ app.get('/v1/families/:familyId/members', auth, async (req, res) => {
204 `select m.user_id,m.role,m.is_admin,p.display_name,p.theme_preference
205 from family_membership m
206 join profile p on p.user_id=m.user_id
454 - where m.family_id=$1 and m.ended_at is null
207 + join family_workspace f on f.id=m.family_id
208 + where m.family_id=$1 and m.ended_at is null and f.archived_at is null
209 + and exists(select 1 from family_membership viewer where viewer.family_id=m.family_id and viewer.user_id=$2 and viewer.ended_at is null)
210 order by m.joined_at`,
456 - [req.params.familyId],
211 + [req.params.familyId, req.identity.sub],
212 );
213 res.json({ members: r.rows });
214 });
@@ -465,6 +220,7 @@ app.post('/v1/families/:familyId/invitations', auth, async (req, res) => {
220 if (!allowed) return res.status(403).json({ error: 'forbidden' });
221
222 const email = normalizeEmail(req.body.email);
223 + const phone = req.body.phone == null ? null : normalizePhone(req.body.phone);
224 const role = String(req.body.role ?? '');
225 const themePreference = String(req.body.themePreference ?? '');
226 const allowedRoles = ['parent_guardian', 'teen_minor', 'adult_member'];
@@ -474,40 +230,49 @@ app.post('/v1/families/:familyId/invitations', auth, async (req, res) => {
230 : role === 'teen_minor'
231 ? 'girl_pink'
232 : 'adult_blue';
477 - if (!isEmail(email) || !allowedRoles.includes(role)) {
233 + if ((email && phone) || (!email && !phone) || (email && !isEmail(email)) ||
234 + (req.body.phone != null && !phone) || !allowedRoles.includes(role)) {
235 return res.status(400).json({ error: 'invalid_invitation' });
236 }
237
481 - const activeMember = await pool.query(
482 - `select 1
483 - from family_membership m
484 - join app_user u on u.id=m.user_id
485 - where m.family_id=$1
486 - and m.ended_at is null
487 - and u.email_normalized=$2`,
488 - [req.params.familyId, email],
489 - );
490 - if (activeMember.rowCount) {
491 - return res.status(409).json({ error: 'member_already_active' });
492 - }
493 -
238 const token = randomToken();
495 - const r = await pool.query(
496 - "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",
497 - [req.params.familyId, email, role, resolvedTheme, sha256(token), req.identity.sub],
498 - );
239 + const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
240 + const activeMember = await client.query(
241 + `select 1
242 + from family_membership m
243 + join app_user u on u.id=m.user_id
244 + where m.family_id=$1
245 + and m.ended_at is null
246 + and ((u.email_normalized=$2 and $2::text is not null)
247 + or (u.phone_normalized=$3 and $3::text is not null))`,
248 + [req.params.familyId, email || null, phone],
249 + );
250 + if (activeMember.rowCount) {
251 + return { status: 409, body: { error: 'member_already_active' } };
252 + }
253
500 - const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifemate.invalid';
501 - await sendTransactionalEmail({
502 - to: email,
503 - subject: 'دعوت به خانواده در LifeMate',
504 - text: `برای پیوستن به خانواده این لینک را باز کنید: ${baseUrl}/accept-invitation?token=${encodeURIComponent(token)}`,
254 + const r = await client.query(
255 + "insert into family_invitation(family_id,invited_email_normalized,invited_phone_normalized,intended_role,intended_theme,token_digest,invited_by,expires_at) values($1,$2,$3,$4,$5,$6,$7,now()+interval '7 days') returning id,expires_at",
256 + [req.params.familyId, email || null, phone, role, resolvedTheme, sha256(token), req.identity.sub],
257 + );
258 + await familyAudit(client, req.params.familyId, req.identity.sub, 'invitation.create', 'invitation', r.rows[0].id);
259 + return { status: 201, body: r.rows[0] };
260 });
261 + if (result.status !== 201) return familyResponse(res, result);
262
263 + const baseUrl = process.env.PUBLIC_APP_URL ?? 'https://app.lifeguide.invalid';
264 + const invitationLink = `${baseUrl}/accept-invitation?token=${encodeURIComponent(token)}`;
265 + // The authenticated family administrator can copy the link even without a provider.
266 res.status(201).json({
508 - ...r.rows[0],
509 - invitationToken: testMode ? token : undefined,
267 + ...result.body,
268 + invitationToken: token,
269 + invitationLink,
270 });
271 + if (email) await safelyDeliver(emailProvider, {
272 + to: email,
273 + subject: 'دعوت به خانواده در لایف‌گاید',
274 + text: `برای پیوستن به خانواده در LifeGuide / لایف‌گاید این لینک را باز کن: ${invitationLink}\nاین لینک ۷ روز اعتبار دارد.`,
275 + }, { attemptId: result.body.id });
276 });
277
278 app.post('/v1/invitations/accept', auth, async (req, res) => {
@@ -515,14 +280,27 @@ app.post('/v1/invitations/accept', auth, async (req, res) => {
280 const client = await pool.connect();
281 try {
282 await client.query('begin');
283 + const preliminary = await client.query('select family_id,invited_by from family_invitation where token_digest=$1', [digest]);
284 + const family = preliminary.rowCount ? await client.query('select 1 from family_workspace where id=$1 and archived_at is null for update', [preliminary.rows[0].family_id]) : { rowCount: 0 };
285 + const inviter = family.rowCount ? await client.query(`select 1 from family_membership m
286 + join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id=$2
287 + and m.ended_at is null and m.is_admin and u.disabled_at is null for update of m`, [preliminary.rows[0].family_id, preliminary.rows[0].invited_by]) : { rowCount: 0 };
288 + if (!inviter.rowCount) {
289 + await client.query('rollback');
290 + return res.status(400).json({ error: 'invalid_or_expired_invitation' });
291 + }
292 + await client.query('select id from app_user where id=$1 for update', [req.identity.sub]);
293 const invitation = await client.query(
519 - `select i.id,i.family_id,i.intended_role,i.intended_theme,i.invited_email_normalized,u.email_normalized
294 + `select i.id,i.family_id,i.intended_role,i.intended_theme,
295 + i.invited_email_normalized,i.invited_phone_normalized,
296 + u.email_normalized,u.email_verified_at,u.phone_normalized,u.phone_verified_at
297 from family_invitation i
298 join app_user u on u.id=$2
299 where i.token_digest=$1
300 and i.status='pending'
301 and i.expires_at>now()
525 - for update`,
302 + and u.disabled_at is null
303 + for update of i`,
304 [digest, req.identity.sub],
305 );
306 if (!invitation.rowCount) {
@@ -530,18 +308,27 @@ app.post('/v1/invitations/accept', auth, async (req, res) => {
308 return res.status(400).json({ error: 'invalid_or_expired_invitation' });
309 }
310 const row = invitation.rows[0];
533 - if (row.invited_email_normalized !== row.email_normalized) {
311 + const matchesEmail = row.invited_email_normalized && row.email_verified_at &&
312 + row.invited_email_normalized === row.email_normalized;
313 + const matchesPhone = row.invited_phone_normalized && row.phone_verified_at &&
314 + row.invited_phone_normalized === row.phone_normalized;
315 + if (!matchesEmail && !matchesPhone) {
316 await client.query('rollback');
535 - return res.status(403).json({ error: 'invitation_email_mismatch' });
317 + return res.status(403).json({ error: 'invitation_contact_mismatch' });
318 }
319
538 - await client.query(
320 + const membership = await client.query(
321 `insert into family_membership(family_id,user_id,role)
322 values($1,$2,$3)
323 on conflict(family_id,user_id)
542 - do update set role=excluded.role,ended_at=null`,
324 + do update set role=excluded.role,ended_at=null,is_admin=false,joined_at=now()
325 + where family_membership.ended_at is not null returning user_id`,
326 [row.family_id, req.identity.sub, row.intended_role],
327 );
328 + if (!membership.rowCount) {
329 + await client.query('rollback');
330 + return res.status(409).json({ error: 'member_already_active' });
331 + }
332 await client.query(
333 "update family_invitation set status='accepted',accepted_by=$2,accepted_at=now() where id=$1",
334 [row.id, req.identity.sub],
@@ -558,53 +345,55 @@ app.post('/v1/invitations/accept', auth, async (req, res) => {
345 );
346 await client.query('commit');
347 res.status(204).end();
348 + } catch (error) {
349 + await client.query('rollback').catch(() => {});
350 + throw error;
351 } finally {
352 client.release();
353 }
354 });
355
356 app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
567 - const allowed = await familyAccess(req.params.familyId, req.identity.sub, {
568 - admin: true,
357 + const guardianUserId = String(req.body?.guardianUserId ?? '');
358 + const minorUserId = String(req.body?.minorUserId ?? '');
359 + if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
360 + const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
361 + const roles = await client.query(`select m.user_id,m.role from family_membership m
362 + join app_user u on u.id=m.user_id where m.family_id=$1 and m.user_id in ($2,$3)
363 + and m.ended_at is null and u.disabled_at is null for update of m`, [req.params.familyId, guardianUserId, minorUserId]);
364 + const map = new Map(roles.rows.map((row) => [row.user_id, row.role]));
365 + if (map.get(guardianUserId) !== 'parent_guardian' || map.get(minorUserId) !== 'teen_minor') return { status: 400, body: { error: 'invalid_guardian_relationship' } };
366 + await client.query(`insert into guardian_relationship(family_id,guardian_user_id,minor_user_id,active)
367 + values($1,$2,$3,true) on conflict(family_id,guardian_user_id,minor_user_id) do update set active=true`, [req.params.familyId, guardianUserId, minorUserId]);
368 + await familyAudit(client, req.params.familyId, req.identity.sub, 'guardian.activate', 'guardian_relationship', guardianUserId);
369 + return { status: 204 };
370 });
570 - if (!allowed) return res.status(403).json({ error: 'forbidden' });
571 -
572 - const guardianUserId = String(req.body.guardianUserId ?? '');
573 - const minorUserId = String(req.body.minorUserId ?? '');
574 -
575 - const roles = await pool.query(
576 - 'select user_id,role from family_membership where family_id=$1 and user_id in ($2,$3) and ended_at is null',
577 - [req.params.familyId, guardianUserId, minorUserId],
578 - );
579 - const map = new Map(roles.rows.map((row) => [row.user_id, row.role]));
580 - if (map.get(guardianUserId) !== 'parent_guardian' || map.get(minorUserId) !== 'teen_minor') {
581 - return res.status(400).json({ error: 'invalid_guardian_relationship' });
582 - }
371 + familyResponse(res, result);
372 +});
373
584 - await pool.query(
585 - `insert into guardian_relationship(family_id,guardian_user_id,minor_user_id,active)
586 - values($1,$2,$3,true)
587 - on conflict(family_id,guardian_user_id,minor_user_id)
588 - do update set active=true`,
589 - [req.params.familyId, guardianUserId, minorUserId],
590 - );
591 - await pool.query(
592 - "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))",
593 - [req.identity.sub, req.params.familyId, guardianUserId, minorUserId],
594 - );
595 - res.status(204).end();
374 +app.delete('/v1/families/:familyId/guardians', auth, async (req, res) => {
375 + const guardianUserId = String(req.body?.guardianUserId ?? '');
376 + const minorUserId = String(req.body?.minorUserId ?? '');
377 + if (!uuid(guardianUserId) || !uuid(minorUserId)) return res.status(400).json({ error: 'invalid_guardian_relationship' });
378 + const result = await familyAdminTransaction(req.params.familyId, req.identity.sub, async (client) => {
379 + await client.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [req.params.familyId, guardianUserId, minorUserId]);
380 + await familyAudit(client, req.params.familyId, req.identity.sub, 'guardian.deactivate', 'guardian_relationship', guardianUserId);
381 + return { status: 204 };
382 + });
383 + familyResponse(res, result);
384 });
385
386 app.use('/v1', createPhase3Router({ pool, auth }));
387 app.use('/v1', createPhase4Router({ pool, auth }));
388 app.use('/v1', createPhase6Router({ pool, auth }));
389 +app.use('/v1', createStudySessionsRouter({ pool, auth }));
390
391 app.use(operationalErrorHandler);
392
393 const port = Number(process.env.PORT ?? 8080);
394 const invokedDirectly = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
395 if (!testMode && invokedDirectly) {
607 - app.listen(port, () => console.log(`LifeMate API listening on ${port}`));
396 + app.listen(port, () => console.log(`LifeGuide API listening on ${port}`));
397 }
398
399 export { app, pool };
backend/src/study_sessions.js new
+384
@@ -0,0 +1,384 @@
1 +import crypto from 'node:crypto';
2 +import express from 'express';
3 +
4 +const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
5 +const states = new Set(['planned', 'started', 'paused', 'completed', 'verified']);
6 +const sources = new Set(['timer', 'self_reported']);
7 +class InputError extends Error {
8 + constructor(status, code, details = {}) { super(code); this.status = status; this.code = code; this.details = details; }
9 +}
10 +const fail = (status, code, details) => { throw new InputError(status, code, details); };
11 +const uuid = (value) => typeof value === 'string' && uuidPattern.test(value);
12 +function instant(value) {
13 + if (typeof value !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,6})?Z$/.test(value)) return null;
14 + const date = new Date(value);
15 + return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 19) === value.slice(0, 19) ? date : null;
16 +}
17 +function eventTime(value) {
18 + const date = instant(value);
19 + if (!date || date.getTime() > Date.now() + 60000 || date.getTime() < Date.now() - 366 * 86400000) fail(400, 'invalid_timestamp');
20 + return date;
21 +}
22 +function canonical(value) {
23 + if (Array.isArray(value)) return value.map(canonical);
24 + if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
25 + return value;
26 +}
27 +function checkVersion(expected, actual) {
28 + if (!Number.isSafeInteger(expected) || expected < 0) fail(400, 'expected_version_required');
29 + if (expected !== Number(actual)) fail(409, 'version_conflict', { serverVersion: Number(actual) });
30 +}
31 +async function ownerLock(client, userId) {
32 + await client.query('select pg_advisory_xact_lock(hashtextextended($1::text,0))', [userId]);
33 +}
34 +async function guardian(client, familyId, viewerId, childId) {
35 + const result = await client.query(
36 + `select 1 from family_workspace f
37 + where f.id=$1 and f.archived_at is null and is_active_guardian($1,$2,$3)`,
38 + [familyId, viewerId, childId],
39 + );
40 + return result.rowCount > 0;
41 +}
42 +// Current sharing and both current memberships are required in addition to the
43 +// relationship. Reports deliberately project no notes or sensitive table data.
44 +const sharedItem = `(p.visibility='parent_guardian' or p.visibility='family'
45 + or (p.visibility='selected_members' and exists(
46 + select 1 from sharing_grant sg where sg.resource_type='plan_item'
47 + and sg.resource_id=p.id and sg.grantee_user_id=$2 and sg.granted_by=p.owner_user_id)))`;
48 +async function planForOwner(client, id, userId) {
49 + const result = await client.query('select * from plan_item where id=$1 for update', [id]);
50 + if (!result.rowCount || result.rows[0].owner_user_id !== userId) fail(404, 'not_found');
51 + if (result.rows[0].status === 'cancelled') fail(409, 'activity_archived');
52 + return result.rows[0];
53 +}
54 +async function sessionForOwner(client, id, userId, lock = false) {
55 + const result = await client.query(`select * from study_session where id=$1 and child_user_id=$2${lock ? ' for update' : ''}`, [id, userId]);
56 + if (!result.rowCount) fail(404, 'not_found');
57 + return result.rows[0];
58 +}
59 +async function activity(client, plan) {
60 + const result = await client.query('select * from activity_state_event where plan_item_id=$1 order by version desc limit 1', [plan.id]);
61 + const row = result.rows[0];
62 + return row ? {
63 + state: row.state, version: Number(row.version), occurredAt: row.occurred_at, acceptedAt: row.accepted_at,
64 + source: row.source, confirmedBy: row.state === 'verified' ? row.actor_user_id : null,
65 + } : { state: plan.status === 'completed' ? 'completed' : plan.status === 'in_progress' ? 'started' : 'planned',
66 + version: Number(plan.activity_version), occurredAt: plan.created_at, acceptedAt: plan.updated_at, source: 'self_reported', confirmedBy: null };
67 +}
68 +async function setActivity(client, plan, actorId, state, source, occurredAt, confirmation = null) {
69 + const current = await activity(client, plan);
70 + if (new Date(current.occurredAt).getTime() > occurredAt.getTime() && current.version > 0) fail(409, 'non_monotonic_activity_time');
71 + const row = (await client.query(
72 + `update plan_item set activity_version=activity_version+1,status=$2::plan_item_status,
73 + completed_at=case when $2::plan_item_status='completed' then coalesce(completed_at,$3) else null end,updated_at=now()
74 + where id=$1 returning *`, [plan.id, ['completed', 'verified'].includes(state) ? 'completed' : state === 'planned' ? 'planned' : 'in_progress', occurredAt],
75 + )).rows[0];
76 + await client.query(
77 + `insert into activity_state_event(plan_item_id,actor_user_id,state,source,occurred_at,version,confirmation)
78 + values($1,$2,$3,$4,$5,$6,$7)`, [plan.id, actorId, state, source, occurredAt, row.activity_version, confirmation],
79 + );
80 + if (row.status === 'completed') await client.query("update reminder set status='cancelled' where plan_item_id=$1 and status in ('scheduled','claimed')", [plan.id]);
81 + return activity(client, row);
82 +}
83 +async function ensureNoOverlap(client, userId, startsAt, endsAt = null, excludedSession = null) {
84 + const result = await client.query(
85 + `select 1 from study_interval i join study_session s on s.id=i.session_id
86 + where s.child_user_id=$1 and s.archived_at is null and ($4::uuid is null or s.id<>$4)
87 + and tstzrange(i.starts_at,i.ends_at,'[)') && tstzrange($2::timestamptz,$3::timestamptz,'[)') limit 1`,
88 + [userId, startsAt, endsAt, excludedSession],
89 + );
90 + if (result.rowCount) fail(409, 'study_time_overlap');
91 +}
92 +async function sessionJson(client, row) {
93 + const result = await client.query('select starts_at,ends_at from study_interval where session_id=$1 order by starts_at,id', [row.id]);
94 + return { id: row.id, childId: row.child_user_id, planItemId: row.plan_item_id, source: row.source, status: row.status,
95 + startedAt: row.started_at, endedAt: row.ended_at, recordedDurationSeconds: row.recorded_duration_seconds,
96 + version: row.version, lastSyncAt: row.last_sync_at, lastEventAt: row.last_event_at,
97 + intervals: result.rows.map((x) => ({ start: x.starts_at, end: x.ends_at })), isEvidenceOfStudy: false };
98 +}
99 +async function readSnapshot(pool, read) {
100 + const client = await pool.connect();
101 + try {
102 + await client.query('begin isolation level repeatable read read only');
103 + const result = await read(client);
104 + await client.query('commit');
105 + return result;
106 + } catch (error) { await client.query('rollback').catch(() => {}); throw error; }
107 + finally { client.release(); }
108 +}
109 +async function mutation(pool, req, res, resource, execute, authorize = null) {
110 + if (!uuid(req.body?.mutationId)) return res.status(400).json({ error: 'mutation_id_required' });
111 + const hash = crypto.createHash('sha256').update(JSON.stringify(canonical({ resource, payload: req.body }))).digest('hex');
112 + const client = await pool.connect();
113 + try {
114 + await client.query('begin');
115 + // Serializes one actor's duplicate retries before touching any data.
116 + await ownerLock(client, req.identity.sub);
117 + // Guardian confirmation retries must not bypass a subsequently revoked
118 + // relation, role, membership or resource grant through the idempotency ledger.
119 + const authorized = authorize ? await authorize(client) : null;
120 + const previous = await client.query('select * from study_mutation where user_id=$1 and id=$2', [req.identity.sub, req.body.mutationId]);
121 + if (previous.rowCount) {
122 + if (previous.rows[0].request_hash !== hash) fail(409, 'mutation_payload_conflict');
123 + const response = previous.rows[0].response_body;
124 + response.acknowledgement.status = 'already_applied';
125 + await client.query('commit');
126 + return res.status(previous.rows[0].response_status).json(response);
127 + }
128 + const { body, status = 200 } = await execute(client, authorized);
129 + const acceptedAt = (await client.query('select clock_timestamp() as ts')).rows[0].ts;
130 + body.acknowledgement = { mutationId: req.body.mutationId, acceptedAt, status: 'accepted' };
131 + await client.query(
132 + 'insert into study_mutation(user_id,id,request_hash,response_body,response_status,accepted_at) values($1,$2,$3,$4::jsonb,$5,$6)',
133 + [req.identity.sub, req.body.mutationId, hash, JSON.stringify(body), status, acceptedAt],
134 + );
135 + await client.query('commit');
136 + return res.status(status).json(body);
137 + } catch (error) {
138 + await client.query('rollback').catch(() => {});
139 + if (error instanceof InputError) return res.status(error.status).json({ error: error.code, ...error.details });
140 + if (error.code === '23505') return res.status(409).json({ error: 'study_session_exists' });
141 + throw error;
142 + } finally { client.release(); }
143 +}
144 +
145 +export function createStudySessionsRouter({ pool, auth }) {
146 + const router = express.Router();
147 + router.use(auth);
148 + router.post('/study/sessions', async (req, res) => mutation(pool, req, res, 'session:create', async (client) => {
149 + const { id, planItemId, source, childId } = req.body;
150 + if (!uuid(id) || !uuid(planItemId) || !sources.has(source) || req.body.recordedDurationSeconds !== undefined) fail(400, 'invalid_study_session');
151 + if (childId !== undefined && childId !== req.identity.sub) fail(403, 'forbidden');
152 + const startedAt = eventTime(req.body.startedAt);
153 + const endedAt = source === 'self_reported' ? eventTime(req.body.endedAt) : null;
154 + if ((endedAt && endedAt <= startedAt) || (source === 'timer' && req.body.endedAt !== undefined)) fail(400, 'invalid_study_interval');
155 + const plan = await planForOwner(client, planItemId, req.identity.sub);
156 + if (plan.status === 'completed') fail(409, 'activity_completed');
157 + await ensureNoOverlap(client, req.identity.sub, startedAt, endedAt);
158 + const seconds = endedAt ? Math.floor((endedAt - startedAt) / 1000) : 0;
159 + const row = (await client.query(
160 + `insert into study_session(id,child_user_id,plan_item_id,source,status,started_at,ended_at,last_event_at,recorded_duration_seconds)
161 + values($1,$2,$3,$4,$5,$6,$7,$8,$9) returning *`,
162 + [id, req.identity.sub, planItemId, source, endedAt ? 'completed' : 'running', startedAt, endedAt, endedAt ?? startedAt, seconds],
163 + )).rows[0];
164 + await client.query('insert into study_interval(session_id,starts_at,ends_at) values($1,$2,$3)', [id, startedAt, endedAt]);
165 + const state = await setActivity(client, plan, req.identity.sub, endedAt ? 'paused' : 'started', source === 'timer' ? 'client_timer' : 'self_reported', endedAt ?? startedAt);
166 + return { status: 201, body: { session: await sessionJson(client, row), activity: state } };
167 + }));
168 + router.get('/study/sessions', async (req, res) => {
169 + if (req.query.planItemId !== undefined && !uuid(req.query.planItemId)) return res.status(400).json({ error: 'invalid_id' });
170 + res.json(await readSnapshot(pool, async (client) => {
171 + const result = await client.query(
172 + 'select * from study_session where child_user_id=$1 and archived_at is null and ($2::uuid is null or plan_item_id=$2) order by started_at desc limit 500',
173 + [req.identity.sub, req.query.planItemId ?? null],
174 + );
175 + return { sessions: await Promise.all(result.rows.map((x) => sessionJson(client, x))), asOf: new Date() };
176 + }));
177 + });
178 + router.get('/study/sessions/:id', async (req, res) => {
179 + if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
180 + try { res.json(await readSnapshot(pool, async (client) => ({ session: await sessionJson(client, await sessionForOwner(client, req.params.id, req.identity.sub)), asOf: new Date() }))); }
181 + catch (error) { if (error instanceof InputError) return res.status(error.status).json({ error: error.code }); throw error; }
182 + });
183 + router.patch('/study/sessions/:id', async (req, res) => {
184 + if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
185 + return mutation(pool, req, res, `session:correct:${req.params.id}`, async (client) => {
186 + const row = await sessionForOwner(client, req.params.id, req.identity.sub, true);
187 + checkVersion(req.body.expectedVersion, row.version);
188 + if (row.source !== 'self_reported' || row.status !== 'completed') fail(409, 'only_completed_self_report_can_be_corrected');
189 + if (req.body.recordedDurationSeconds !== undefined) fail(400, 'duration_is_server_computed');
190 + const startedAt = eventTime(req.body.startedAt);
191 + const endedAt = eventTime(req.body.endedAt);
192 + if (endedAt <= startedAt) fail(400, 'invalid_study_interval');
193 + await ensureNoOverlap(client, req.identity.sub, startedAt, endedAt, row.id);
194 + await client.query('delete from study_interval where session_id=$1', [row.id]);
195 + await client.query('insert into study_interval(session_id,starts_at,ends_at) values($1,$2,$3)', [row.id, startedAt, endedAt]);
196 + const updated = (await client.query(
197 + `update study_session set started_at=$2,ended_at=$3,last_event_at=$3,recorded_duration_seconds=$4,
198 + version=version+1,last_sync_at=now(),updated_at=now() where id=$1 returning *`,
199 + [row.id, startedAt, endedAt, Math.floor((endedAt - startedAt) / 1000)],
200 + )).rows[0];
201 + return { body: { session: await sessionJson(client, updated) } };
202 + });
203 + });
204 + router.post('/study/sessions/:id/events', async (req, res) => {
205 + if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
206 + return mutation(pool, req, res, `session:event:${req.params.id}`, async (client) => {
207 + const row = await sessionForOwner(client, req.params.id, req.identity.sub, true);
208 + checkVersion(req.body.expectedVersion, row.version);
209 + if (row.status === 'completed' || row.status === 'archived') fail(409, 'study_session_closed');
210 + const { action } = req.body;
211 + if (!['pause', 'resume', 'stop'].includes(action)) fail(400, 'invalid_study_action');
212 + const when = eventTime(req.body.occurredAt);
213 + if (when < new Date(row.last_event_at)) fail(409, 'non_monotonic_session_time');
214 + const plan = await planForOwner(client, row.plan_item_id, req.identity.sub);
215 + if (action === 'resume') {
216 + if (row.status !== 'paused') fail(409, 'study_not_paused');
217 + if (plan.status === 'completed') fail(409, 'activity_completed');
218 + await ensureNoOverlap(client, req.identity.sub, when);
219 + await client.query('insert into study_interval(session_id,starts_at) values($1,$2)', [row.id, when]);
220 + } else if (row.status === 'running') {
221 + await client.query('update study_interval set ends_at=$2 where session_id=$1 and ends_at is null', [row.id, when]);
222 + } else if (action === 'pause') fail(409, 'study_not_running');
223 + const updated = (await client.query(
224 + `update study_session set status=$2,ended_at=$3,last_event_at=$4,
225 + recorded_duration_seconds=(select floor(coalesce(sum(extract(epoch from ends_at-starts_at)),0))::int from study_interval where session_id=$1),
226 + version=version+1,last_sync_at=now(),updated_at=now() where id=$1 returning *`,
227 + [row.id, action === 'stop' ? 'completed' : action === 'pause' ? 'paused' : 'running', action === 'stop' ? when : null, when],
228 + )).rows[0];
229 + const current = await activity(client, plan);
230 + const state = plan.status === 'completed' ? current : await setActivity(client, plan, req.identity.sub, action === 'resume' ? 'started' : 'paused', 'client_timer', when);
231 + return { body: { session: await sessionJson(client, updated), activity: state } };
232 + });
233 + });
234 + router.delete('/study/sessions/:id', async (req, res) => {
235 + if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
236 + return mutation(pool, req, res, `session:archive:${req.params.id}`, async (client) => {
237 + const row = await sessionForOwner(client, req.params.id, req.identity.sub, true);
238 + checkVersion(req.body.expectedVersion, row.version);
239 + if (row.status === 'running' || row.status === 'paused') fail(409, 'stop_session_before_archive');
240 + if (row.status === 'archived') fail(409, 'study_session_closed');
241 + const updated = (await client.query("update study_session set status='archived',archived_at=now(),version=version+1,last_sync_at=now(),updated_at=now() where id=$1 returning *", [row.id])).rows[0];
242 + return { body: { session: await sessionJson(client, updated) } };
243 + });
244 + });
245 + router.post('/plan-items/:id/activity-state', async (req, res) => {
246 + if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
247 + const authorize = async (client) => {
248 + const result = await client.query('select * from plan_item where id=$1', [req.params.id]);
249 + if (!result.rowCount) fail(404, 'not_found');
250 + const candidate = result.rows[0];
251 + if (candidate.owner_user_id !== req.identity.sub) await ownerLock(client, candidate.owner_user_id);
252 + const plan = (await client.query('select * from plan_item where id=$1 for update', [req.params.id])).rows[0];
253 + if (!plan) fail(404, 'not_found');
254 + if (req.body.state === 'verified') {
255 + if (!plan.family_id || plan.owner_user_id === req.identity.sub || !await guardian(client, plan.family_id, req.identity.sub, plan.owner_user_id)) fail(403, 'forbidden');
256 + const shared = await client.query(`select 1 from plan_item p where p.id=$1 and ${sharedItem}`, [plan.id, req.identity.sub]);
257 + if (!shared.rowCount) fail(403, 'forbidden');
258 + } else if (plan.owner_user_id !== req.identity.sub) fail(403, 'forbidden');
259 + return plan;
260 + };
261 + return mutation(pool, req, res, `activity:${req.params.id}`, async (client, plan) => {
262 + const verified = req.body.state === 'verified';
263 + if (plan.status === 'cancelled') fail(409, 'activity_archived');
264 + const current = await activity(client, plan);
265 + checkVersion(req.body.expectedVersion, plan.activity_version);
266 + const state = req.body.state;
267 + if (!states.has(state)) fail(400, 'invalid_activity_state');
268 + const source = req.body.source;
269 + const when = eventTime(req.body.occurredAt);
270 + let confirmation = null;
271 + if (verified) {
272 + confirmation = typeof req.body.confirmation === 'string' ? req.body.confirmation.trim() : '';
273 + if (source !== 'guardian_confirmation' || !confirmation || confirmation.length > 1000) fail(400, 'explicit_confirmation_required');
274 + if (current.state !== 'completed') fail(409, 'complete_before_verification');
275 + } else if (!['client_timer', 'self_reported'].includes(source) || req.body.confirmation !== undefined) fail(400, 'invalid_activity_source');
276 + if (state === current.state) fail(409, 'activity_state_unchanged');
277 + if (['completed', 'verified'].includes(current.state) && !['planned', 'verified'].includes(state)) fail(409, 'reopen_activity_first');
278 + const next = await setActivity(client, plan, req.identity.sub, state, source, when, confirmation);
279 + const updated = (await client.query('select version from plan_item where id=$1', [plan.id])).rows[0];
280 + return { body: { activity: next, planItemId: plan.id, planVersion: Number(updated.version) } };
281 + }, authorize);
282 + });
283 + router.get('/plan-items/:id/activity-state', async (req, res) => {
284 + if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
285 + try {
286 + res.json(await readSnapshot(pool, async (client) => {
287 + const plan = (await client.query('select * from plan_item where id=$1', [req.params.id])).rows[0];
288 + if (!plan) fail(404, 'not_found');
289 + if (plan.owner_user_id !== req.identity.sub) {
290 + if (!plan.family_id || !await guardian(client, plan.family_id, req.identity.sub, plan.owner_user_id)) fail(403, 'forbidden');
291 + if (!(await client.query(`select 1 from plan_item p where p.id=$1 and ${sharedItem}`, [plan.id, req.identity.sub])).rowCount) fail(403, 'forbidden');
292 + }
293 + const rows = (await client.query(
294 + 'select state,source,occurred_at,accepted_at,version,actor_user_id from activity_state_event where plan_item_id=$1 order by version desc limit 500', [plan.id],
295 + )).rows.reverse();
296 + return { planItemId: plan.id, planVersion: Number(plan.version), activity: await activity(client, plan),
297 + history: rows.map((x) => ({ state: x.state, source: x.source, occurredAt: x.occurred_at, acceptedAt: x.accepted_at,
298 + version: Number(x.version), confirmedBy: x.state === 'verified' ? x.actor_user_id : null })), asOf: new Date() };
299 + }));
300 + } catch (error) { if (error instanceof InputError) return res.status(error.status).json({ error: error.code }); throw error; }
301 + });
302 + router.get('/families/:familyId/children/:childId/learning-report', async (req, res) => {
303 + if (!uuid(req.params.familyId) || !uuid(req.params.childId)) return res.status(400).json({ error: 'invalid_id' });
304 + const to = req.query.to === undefined ? new Date() : instant(req.query.to);
305 + const from = req.query.from === undefined && to ? new Date(to.getTime() - 30 * 86400000) : instant(req.query.from);
306 + if (!from || !to || to <= from || to - from > 366 * 86400000) return res.status(400).json({ error: 'invalid_report_range' });
307 + const client = await pool.connect();
308 + try {
309 + await client.query('begin isolation level repeatable read read only');
310 + if (!await guardian(client, req.params.familyId, req.identity.sub, req.params.childId)) { await client.query('rollback'); return res.status(403).json({ error: 'forbidden' }); }
311 + const asOf = (await client.query('select clock_timestamp() as ts')).rows[0].ts;
312 + const items = (await client.query(
313 + `select p.id,p.title,p.kind,p.status,p.priority,p.starts_at,p.due_at,p.duration_minutes,p.planned_duration_seconds,p.completed_at,p.updated_at,p.version,
314 + p.activity_version,sub.name as subject_name,p.grade_points,p.grade_out_of,
315 + e.state as activity_state,e.source as activity_source,e.occurred_at as activity_at
316 + from plan_item p left join subject sub on sub.id=p.subject_id
317 + left join lateral(select state,source,occurred_at from activity_state_event where plan_item_id=p.id order by version desc limit 1) e on true
318 + where p.family_id=$1 and p.owner_user_id=$3 and p.status<>'cancelled' and ${sharedItem}
319 + order by coalesce(p.starts_at,p.due_at,p.created_at),p.id`,
320 + [req.params.familyId, req.identity.sub, req.params.childId],
321 + )).rows;
322 + const ids = items.map((x) => x.id);
323 + const intervals = (await client.query(
324 + `select s.id,s.plan_item_id,s.source,s.last_sync_at,s.version,
325 + greatest(i.starts_at,$2::timestamptz) as starts_at,
326 + least(coalesce(i.ends_at,$4::timestamptz),$3::timestamptz,$4::timestamptz) as ends_at
327 + from study_session s join study_interval i on i.session_id=s.id
328 + where s.plan_item_id=any($1::uuid[]) and s.archived_at is null and i.starts_at<$3
329 + and coalesce(i.ends_at,$4)>$2`, [ids, from, to, asOf],
330 + )).rows.filter((x) => x.ends_at > x.starts_at);
331 + const timeByItem = new Map();
332 + const daily = new Map();
333 + let totalMilliseconds = 0;
334 + for (const interval of intervals) {
335 + const milliseconds = interval.ends_at - interval.starts_at;
336 + totalMilliseconds += milliseconds;
337 + timeByItem.set(interval.plan_item_id, (timeByItem.get(interval.plan_item_id) ?? 0) + milliseconds);
338 + // Split at Tehran midnight. Recorded time is never inferred as learning evidence.
339 + let start = interval.starts_at.getTime();
340 + const end = interval.ends_at.getTime();
341 + while (start < end) {
342 + const local = new Date(start + 210 * 60000);
343 + const key = local.toISOString().slice(0, 10);
344 + const next = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate() + 1) - 210 * 60000;
345 + const part = Math.min(end, next) - start;
346 + daily.set(key, (daily.get(key) ?? 0) + part);
347 + start += part;
348 + }
349 + }
350 + const projected = items.map((x) => ({ id: x.id, title: x.title, kind: x.kind, status: x.status, priority: x.priority, version: Number(x.version),
351 + startsAt: x.starts_at, dueAt: x.due_at, plannedDurationSeconds: x.planned_duration_seconds ?? (x.duration_minutes ?? 0) * 60,
352 + recordedDurationSeconds: Math.floor((timeByItem.get(x.id) ?? 0) / 1000), completedAt: x.completed_at,
353 + activityState: x.activity_state ?? (x.status === 'completed' ? 'completed' : x.status === 'in_progress' ? 'started' : 'planned'),
354 + activitySource: x.activity_source ?? 'self_reported', activityAt: x.activity_at ?? x.updated_at,
355 + subjectName: x.subject_name, gradePoints: x.grade_points, gradeOutOf: x.grade_out_of }));
356 + const planned = projected.filter((x) => { const at = x.startsAt ?? x.dueAt; return at && new Date(at) >= from && new Date(at) < to; });
357 + const complete = projected.filter((x) => x.status === 'completed').length;
358 + const latest = [...items.map((x) => x.updated_at), ...intervals.map((x) => x.last_sync_at)].sort((a, b) => b - a)[0] ?? null;
359 + const subjects = new Map();
360 + for (const item of projected) {
361 + const key = item.subjectName ?? 'بدون درس';
362 + const existing = subjects.get(key) ?? { subjectName: key, totalTasks: 0, completedTasks: 0, recordedDurationSeconds: 0 };
363 + existing.totalTasks++;
364 + if (item.status === 'completed') existing.completedTasks++;
365 + existing.recordedDurationSeconds += item.recordedDurationSeconds;
366 + subjects.set(key, existing);
367 + }
368 + const response = { childId: req.params.childId, familyId: req.params.familyId, from, to, asOf, lastSyncAt: latest,
369 + sourceVersion: crypto.createHash('sha256').update(JSON.stringify({ items: items.map((x) => [x.id, x.updated_at, x.activity_version]), intervals: intervals.map((x) => [x.id, x.version, x.last_sync_at]) })).digest('hex'),
370 + timezone: 'Asia/Tehran', recordingDisclaimerKey: 'recorded_time_is_not_proof_of_study', items: projected,
371 + metrics: { totalTasks: projected.length, completedTasks: complete, completionPercent: projected.length ? Math.round(complete * 100 / projected.length) : 0,
372 + overdueTasks: projected.filter((x) => x.status !== 'completed' && x.dueAt && new Date(x.dueAt) < asOf).length,
373 + plannedDurationSeconds: projected.reduce((sum, x) => sum + x.plannedDurationSeconds, 0),
374 + plannedInRangeDurationSeconds: planned.reduce((sum, x) => sum + x.plannedDurationSeconds, 0),
375 + recordedDurationSeconds: Math.floor(totalMilliseconds / 1000) },
376 + daily: [...daily.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([date, ms]) => ({ date, recordedDurationSeconds: Math.floor(ms / 1000) })),
377 + subjects: [...subjects.values()], sources: [...new Set(intervals.map((x) => x.source))], isEvidenceOfStudy: false };
378 + await client.query('commit');
379 + res.json(response);
380 + } catch (error) { await client.query('rollback').catch(() => {}); throw error; }
381 + finally { client.release(); }
382 + });
383 + return router;
384 +}
backend/tests/api.test.js
+3 -3
@@ -48,7 +48,7 @@ test('identity + family vertical slice', async () => {
48
49 const parentVerify = await request('/v1/auth/verify-email', {
50 method: 'POST',
51 - body: { token: parentRegister.body.verificationToken },
51 + body: { token: parentRegister.body.verificationToken, newPassword: initialPassword },
52 });
53 assert.equal(parentVerify.status, 204);
54
@@ -103,7 +103,7 @@ test('identity + family vertical slice', async () => {
103 assert.equal(
104 (await request('/v1/auth/verify-email', {
105 method: 'POST',
106 - body: { token: teenRegister.body.verificationToken },
106 + body: { token: teenRegister.body.verificationToken, newPassword: initialPassword },
107 })).status,
108 204,
109 );
@@ -178,7 +178,7 @@ test('identity + family vertical slice', async () => {
178 (
179 await request('/v1/auth/verify-email', {
180 method: 'POST',
181 - body: { token: supporterRegister.body.verificationToken },
181 + body: { token: supporterRegister.body.verificationToken, newPassword: initialPassword },
182 })
183 ).status,
184 204,
backend/tests/auth_delivery.test.js new
+589
@@ -0,0 +1,589 @@
1 +import test, { after, before } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import { spawn } from 'node:child_process';
5 +import { once } from 'node:events';
6 +import net from 'node:net';
7 +import pg from 'pg';
8 +import express from 'express';
9 +import argon2 from 'argon2';
10 +import jwt from 'jsonwebtoken';
11 +import { createAuthRouter } from '../src/auth_router.js';
12 +import { createSessionAuth } from '../src/session_auth.js';
13 +import { SmsProvider, createEmailProvider, safelyDeliver } from '../src/auth_delivery.js';
14 +import { operationalErrorHandler } from '../src/operations.js';
15 +
16 +assert.ok(process.env.DATABASE_URL, 'Auth delivery tests require a migrated synthetic PostgreSQL database');
17 +assert.ok(process.env.JWT_SECRET?.length >= 32, 'Auth delivery tests require a synthetic JWT secret');
18 +const suffix = crypto.randomUUID();
19 +const applicationName = `auth-fixture-${suffix}`;
20 +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, application_name: applicationName });
21 +const email = `delivery-${suffix}@example.test`;
22 +let child;
23 +let base;
24 +let output = '';
25 +let errors = '';
26 +let smtp;
27 +let providerServer;
28 +let providerBase;
29 +const mail = [];
30 +const smsMessages = [];
31 +const recipients = new Set([email]);
32 +const userIds = new Set();
33 +const familyIds = new Set();
34 +const challengeIds = new Set();
35 +const jwtSecret = process.env.JWT_SECRET;
36 +const recipientDigest = (recipient) => crypto.createHmac('sha256', jwtSecret).update(`delivery:${recipient}`).digest('hex');
37 +const tokenDigest = (token) => crypto.createHash('sha256').update(token).digest('hex');
38 +const password = 'SyntheticPass123!';
39 +const replacement = 'ReplacementSynthetic123!';
40 +
41 +// Only the external delivery ports are fixtures: HTTP, identity, hashes and DB are real.
42 +class CapturingSmsProvider extends SmsProvider {
43 + configured = true;
44 + status = 'TEST_ONLY';
45 + async sendOtp(message) { smsMessages.push(message); return { delivered: true }; }
46 +}
47 +
48 +before(async () => {
49 + // A rejecting local SMTP fixture: no message or credential is transmitted.
50 + smtp = net.createServer((socket) => socket.end('421 synthetic service unavailable\r\n'));
51 + smtp.listen(0, '127.0.0.1');
52 + await once(smtp, 'listening');
53 + const reservation = net.createServer();
54 + reservation.listen(0, '127.0.0.1');
55 + await once(reservation, 'listening');
56 + const port = reservation.address().port;
57 + await new Promise((resolve) => reservation.close(resolve));
58 + base = `http://127.0.0.1:${port}`;
59 + child = spawn(process.execPath, ['src/entrypoint.js'], {
60 + env: {
61 + ...process.env, NODE_ENV: 'production', PORT: String(port),
62 + EMAIL_FROM: 'LifeGuide Test <fixture@example.test>',
63 + SMTP_HOST: '127.0.0.1', SMTP_PORT: String(smtp.address().port),
64 + SMTP_SECURE: 'false', SMTP_USER: '', SMTP_PASSWORD: '', RESEND_API_KEY: '',
65 + PUBLIC_APP_URL: 'https://app.example.test', CORS_ORIGINS: '',
66 + RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '2000',
67 + },
68 + stdio: ['ignore', 'pipe', 'pipe'],
69 + });
70 + child.stdout.on('data', (chunk) => { output += chunk.toString(); });
71 + child.stderr.on('data', (chunk) => { errors += chunk.toString(); });
72 + await new Promise((resolve, reject) => {
73 + const timer = setTimeout(() => reject(new Error('Auth fixture startup timed out')), 10000);
74 + const onData = () => {
75 + if (!output.includes('"type":"startup"')) return;
76 + clearTimeout(timer);
77 + child.stdout.off('data', onData);
78 + resolve();
79 + };
80 + child.stdout.on('data', onData);
81 + child.once('error', (error) => { clearTimeout(timer); reject(error); });
82 + });
83 + const fixtureApp = express();
84 + fixtureApp.use(express.json({ limit: '64kb' }));
85 + fixtureApp.use('/v1/auth', createAuthRouter({
86 + pool, jwtSecret, auth: createSessionAuth({ pool, jwtSecret }),
87 + env: { NODE_ENV: 'production', PUBLIC_APP_URL: 'https://app.example.test' },
88 + emailProvider: { configured: true, status: 'TEST_ONLY', async send(message) { mail.push(message); return { delivered: true }; } },
89 + smsProvider: new CapturingSmsProvider(),
90 + }));
91 + fixtureApp.use(operationalErrorHandler);
92 + providerServer = fixtureApp.listen(0, '127.0.0.1');
93 + await once(providerServer, 'listening');
94 + providerBase = `http://127.0.0.1:${providerServer.address().port}`;
95 +});
96 +
97 +after(async () => {
98 + if (child && child.exitCode === null && child.signalCode === null) {
99 + const closed = once(child, 'close');
100 + child.kill('SIGTERM');
101 + await closed;
102 + }
103 + if (smtp) await new Promise((resolve) => smtp.close(resolve));
104 + if (providerServer) await new Promise((resolve) => providerServer.close(resolve));
105 + await pool.query('delete from access_audit where actor_user_id=any($1::uuid[]) or family_id=any($2::uuid[])', [[...userIds], [...familyIds]]);
106 + await pool.query('delete from family_workspace where id=any($1::uuid[])', [[...familyIds]]);
107 + await pool.query('delete from auth_phone_challenge where id=any($1::uuid[])', [[...challengeIds]]);
108 + await pool.query('delete from auth_delivery_attempt where recipient_digest=any($1::text[])', [[...recipients].map(recipientDigest)]);
109 + await pool.query('delete from app_user where id=any($1::uuid[]) or email_normalized=$2', [[...userIds], email]);
110 + await pool.end();
111 +});
112 +
113 +async function request(path, body, { method = 'POST', token, origin = base } = {}) {
114 + const response = await fetch(origin + path, {
115 + method,
116 + headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
117 + body: body === undefined ? undefined : JSON.stringify(body),
118 + });
119 + const text = await response.text();
120 + return { status: response.status, body: text ? JSON.parse(text) : null, headers: response.headers };
121 +}
122 +
123 +const providerRequest = (path, body, options = {}) => request(path, body, { ...options, origin: providerBase });
124 +async function until(check) {
125 + for (let i = 0; i < 100; i++) {
126 + const value = await check();
127 + if (value) return value;
128 + await new Promise((resolve) => setTimeout(resolve, 20));
129 + }
130 + assert.fail('Synthetic delivery fixture did not complete');
131 +}
132 +async function identify(contact) {
133 + const row = await pool.query('select id from app_user where email_normalized=$1 or phone_normalized=$1', [contact]);
134 + assert.equal(row.rowCount, 1);
135 + userIds.add(row.rows[0].id);
136 + return row.rows[0].id;
137 +}
138 +async function resetCooldown(contact, purpose) {
139 + await pool.query("update auth_delivery_attempt set requested_at=now()-interval '2 hours' where recipient_digest=$1 and purpose=$2", [recipientDigest(contact), purpose]);
140 +}
141 +function freshEmail() { const value = `auth-${crypto.randomUUID()}@example.test`; recipients.add(value); return value; }
142 +function freshPhone() { const value = `+1555${crypto.randomInt(100000000, 999999999)}`; recipients.add(value); return value; }
143 +async function emailAccount() {
144 + const contact = freshEmail();
145 + assert.equal((await providerRequest('/v1/auth/register', { email: contact, displayName: 'Synthetic Email', password })).status, 202);
146 + const id = await identify(contact);
147 + const message = await until(() => mail.find((item) => item.to === contact));
148 + const token = new URL(message.text.match(/https:\/\/\S+/)[0]).searchParams.get('token');
149 + return { contact, id, token };
150 +}
151 +async function otp(contact, purpose = 'verify') {
152 + await resetCooldown(contact, 'phone_otp');
153 + const previous = smsMessages.length;
154 + const response = await providerRequest('/v1/auth/phone/request-otp', { phone: contact, purpose });
155 + assert.equal(response.status, 202);
156 + challengeIds.add(response.body.challengeId);
157 + assert.equal(response.body.expiresIn, 300);
158 + assert.equal(Object.hasOwn(response.body, 'code'), false);
159 + const message = await until(() => smsMessages.slice(previous).find((item) => item.phone === contact));
160 + return { challengeId: response.body.challengeId, code: message.code };
161 +}
162 +async function phoneAccount() {
163 + const contact = freshPhone();
164 + const registered = await providerRequest('/v1/auth/register', { phone: contact, displayName: 'Synthetic Phone', password });
165 + assert.equal(registered.status, 202);
166 + assert.deepEqual(registered.body, { accepted: true });
167 + return { contact, id: await identify(contact) };
168 +}
169 +async function familyFixture() {
170 + const parent = await emailAccount();
171 + assert.equal((await providerRequest('/v1/auth/verify-email', { token: parent.token, newPassword: password })).status, 204);
172 + const login = await request('/v1/auth/login', { email: parent.contact, password });
173 + assert.equal(login.status, 200);
174 + const child = await phoneAccount();
175 + const proof = await otp(child.contact);
176 + const verified = await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password });
177 + assert.equal(verified.status, 200);
178 + const family = await request('/v1/families', { name: 'Synthetic Management Family', role: 'parent_guardian' }, { token: login.body.accessToken });
179 + assert.equal(family.status, 201);
180 + familyIds.add(family.body.id);
181 + return { parent: { ...parent, accessToken: login.body.accessToken }, child: { ...child, accessToken: verified.body.accessToken }, familyId: family.body.id };
182 +}
183 +async function phoneInvitation(fixture, role = 'teen_minor') {
184 + const invitation = await request(`/v1/families/${fixture.familyId}/invitations`, { phone: fixture.child.contact, role }, { token: fixture.parent.accessToken });
185 + assert.equal(invitation.status, 201);
186 + return invitation.body;
187 +}
188 +
189 +test('registration remains recoverable and generic when email delivery fails after commit', async () => {
190 + const body = { email, displayName: 'Synthetic User', password: 'SyntheticPass123!' };
191 + const created = await request('/v1/auth/register', body);
192 + assert.equal(created.status, 202);
193 + assert.deepEqual(created.body, { accepted: true });
194 + const row = await pool.query('select u.id,c.password_hash from app_user u join auth_credential c on c.user_id=u.id where u.email_normalized=$1', [email]);
195 + assert.equal(row.rowCount, 1);
196 + assert.equal(row.rows[0].password_hash.startsWith('$argon2id$'), true);
197 + userIds.add(row.rows[0].id);
198 + await until(async () => (await pool.query("select 1 from auth_delivery_attempt where user_id=$1 and purpose='email_verification' and status='failed'", [row.rows[0].id])).rowCount);
199 + const duplicate = await request('/v1/auth/register', { ...body, displayName: 'Must Not Replace', password: 'OtherSyntheticPass123!' });
200 + assert.equal(duplicate.status, 202);
201 + assert.deepEqual(duplicate.body, created.body);
202 + assert.equal((await pool.query('select display_name from profile where user_id=$1', [row.rows[0].id])).rows[0].display_name, 'Synthetic User');
203 + assert.equal((await pool.query('select password_hash=$2 as unchanged from auth_credential where user_id=$1', [row.rows[0].id, row.rows[0].password_hash])).rows[0].unchanged, true);
204 +});
205 +
206 +test('forgot-password delivery failure keeps the generic response and stored recovery token', async () => {
207 + const known = await request('/v1/auth/forgot-password', { email });
208 + const unknown = await request('/v1/auth/forgot-password', { email: `missing-${suffix}@example.test` });
209 + recipients.add(`missing-${suffix}@example.test`);
210 + assert.equal(known.status, 200);
211 + assert.equal(unknown.status, 200);
212 + assert.deepEqual(known.body, { accepted: true });
213 + assert.deepEqual(unknown.body, known.body);
214 + assert.equal((await pool.query("select count(*)::int as n from auth_token t join app_user u on u.id=t.user_id where u.email_normalized=$1 and t.kind='password_reset'", [email])).rows[0].n, 1);
215 + assert.equal(errors.includes(email), false);
216 + assert.equal(errors.includes('SyntheticPass123!'), false);
217 +});
218 +
219 +test('unconfigured SMS returns the same recoverable failure before account creation or lookup', async () => {
220 + const contact = freshPhone();
221 + const caps = await request('/v1/auth/capabilities', undefined, { method: 'GET' });
222 + assert.equal(caps.status, 200);
223 + assert.equal(caps.body.smsAvailable, false);
224 + assert.equal(caps.body.smsStatus, 'UNVERIFIED');
225 + const rejected = await request('/v1/auth/register', { phone: contact, displayName: 'Synthetic Phone', password });
226 + assert.equal(rejected.status, 503);
227 + assert.deepEqual(rejected.body, { error: 'sms_unavailable' });
228 + assert.equal((await pool.query('select 1 from app_user where phone_normalized=$1', [contact])).rowCount, 0);
229 + const created = await phoneAccount();
230 + const known = await request('/v1/auth/phone/request-otp', { phone: created.contact });
231 + const unknown = await request('/v1/auth/phone/request-otp', { phone: contact });
232 + assert.equal(known.status, 503);
233 + assert.equal(unknown.status, known.status);
234 + assert.deepEqual(unknown.body, known.body);
235 + assert.equal((await pool.query('select 1 from auth_phone_challenge where user_id=$1', [created.id])).rowCount, 0);
236 +});
237 +
238 +test('resend verification is generic, rate limited for known and unknown contacts, and recoverable after provider failure', async () => {
239 + const unknown = freshEmail();
240 + await resetCooldown(email, 'email_verification');
241 + const known = await request('/v1/auth/resend-verification', { email });
242 + const absent = await request('/v1/auth/resend-verification', { email: unknown });
243 + assert.equal(known.status, 202);
244 + assert.equal(absent.status, 202);
245 + assert.deepEqual(known.body, absent.body);
246 + for (const contact of [email, unknown]) {
247 + const blocked = await request('/v1/auth/resend-verification', { email: contact });
248 + assert.equal(blocked.status, 429);
249 + assert.equal(Number(blocked.headers.get('Retry-After')) > 0, true);
250 + await pool.query("update auth_delivery_attempt set requested_at=now()-interval '61 seconds' where recipient_digest=$1 and purpose='email_verification' and requested_at>now()-interval '1 hour'", [recipientDigest(contact)]);
251 + assert.equal((await request('/v1/auth/resend-verification', { email: contact })).status, 202);
252 + await pool.query("update auth_delivery_attempt set requested_at=now()-interval '61 seconds' where recipient_digest=$1 and purpose='email_verification' and requested_at>now()-interval '1 hour'", [recipientDigest(contact)]);
253 + assert.equal((await request('/v1/auth/resend-verification', { email: contact })).status, 202);
254 + const hourlyLimit = await request('/v1/auth/resend-verification', { email: contact });
255 + assert.equal(hourlyLimit.status, 429);
256 + assert.equal(Number(hourlyLimit.headers.get('Retry-After')) > 60, true);
257 + }
258 + const stored = await pool.query("select count(*)::int as n from auth_token t join app_user u on u.id=t.user_id where u.email_normalized=$1 and t.kind='email_verification'", [email]);
259 + assert.equal(stored.rows[0].n >= 4, true);
260 +});
261 +
262 +test('email verification and reset tokens are hashed, expire and can be consumed only once', async () => {
263 + const account = await emailAccount();
264 + const stored = (await pool.query('select token_digest from auth_token where user_id=$1', [account.id])).rows[0].token_digest;
265 + assert.equal(stored === tokenDigest(account.token), true);
266 + assert.equal(stored === account.token, false);
267 + await pool.query("update auth_token set created_at=now()-interval '2 days',expires_at=now()-interval '1 day' where user_id=$1", [account.id]);
268 + assert.equal((await providerRequest('/v1/auth/verify-email', { token: account.token, newPassword: password })).status, 400);
269 + await resetCooldown(account.contact, 'email_verification');
270 + const previous = mail.length;
271 + assert.equal((await providerRequest('/v1/auth/resend-verification', { email: account.contact })).status, 202);
272 + const verification = await until(() => mail.slice(previous).find((item) => item.to === account.contact));
273 + const token = new URL(verification.text.match(/https:\/\/\S+/)[0]).searchParams.get('token');
274 + assert.equal((await providerRequest('/v1/auth/verify-email', { token, newPassword: password })).status, 204);
275 + assert.equal((await providerRequest('/v1/auth/verify-email', { token, newPassword: password })).status, 400);
276 + const login = await providerRequest('/v1/auth/login', { identifier: account.contact, password });
277 + assert.equal(login.status, 200);
278 + const before = mail.length;
279 + assert.equal((await providerRequest('/v1/auth/forgot-password', { email: account.contact })).status, 200);
280 + const resetMessage = await until(() => mail.slice(before).find((item) => item.to === account.contact));
281 + const expiredReset = new URL(resetMessage.text.match(/https:\/\/\S+/)[0]).searchParams.get('token');
282 + await pool.query("update auth_token set created_at=now()-interval '1 hour',expires_at=now()-interval '30 minutes' where token_digest=$1", [tokenDigest(expiredReset)]);
283 + assert.equal((await providerRequest('/v1/auth/reset-password', { token: expiredReset, newPassword: replacement })).status, 400);
284 + await resetCooldown(account.contact, 'password_reset');
285 + const resendStart = mail.length;
286 + assert.equal((await providerRequest('/v1/auth/forgot-password', { email: account.contact })).status, 200);
287 + const resentReset = await until(() => mail.slice(resendStart).find((item) => item.to === account.contact));
288 + const reset = new URL(resentReset.text.match(/https:\/\/\S+/)[0]).searchParams.get('token');
289 + assert.equal((await providerRequest('/v1/auth/reset-password', { token: reset, newPassword: replacement })).status, 204);
290 + assert.equal((await providerRequest('/v1/auth/reset-password', { token: reset, newPassword: password })).status, 400);
291 + assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: login.body.refreshToken })).status, 401);
292 + assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password })).status, 401);
293 + assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password: replacement })).status, 200);
294 +});
295 +
296 +test('phone-only ownership proof replaces pending credentials; OTP is hashed and single-use', async () => {
297 + const account = await phoneAccount();
298 + assert.equal((await providerRequest('/v1/auth/login', { phone: account.contact, password })).status, 403);
299 + const proof = await otp(account.contact);
300 + const stored = (await pool.query('select code_digest,expires_at-created_at as ttl from auth_phone_challenge where id=$1', [proof.challengeId])).rows[0];
301 + assert.equal(stored.code_digest.length, 64);
302 + assert.equal(stored.code_digest === crypto.createHmac('sha256', jwtSecret).update(`otp:${proof.challengeId}:${proof.code}`).digest('hex'), true);
303 + assert.equal(stored.code_digest === proof.code, false);
304 + assert.equal(stored.ttl.minutes, 5);
305 + assert.equal((await providerRequest('/v1/auth/phone/verify-otp', proof)).status, 400);
306 + assert.equal((await pool.query('select phone_verified_at from app_user where id=$1', [account.id])).rows[0].phone_verified_at, null);
307 + const verified = await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: replacement });
308 + assert.equal(verified.status, 200);
309 + assert.ok(verified.body.refreshToken);
310 + assert.equal((await pool.query('select email_normalized,phone_verified_at from app_user where id=$1', [account.id])).rows[0].email_normalized, null);
311 + assert.equal((await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password })).status, 401);
312 + assert.equal((await providerRequest('/v1/auth/login', { identifier: account.contact, password })).status, 401);
313 + assert.equal((await providerRequest('/v1/auth/login', { identifier: account.contact, password: replacement })).status, 200);
314 +});
315 +
316 +test('phone OTP expiry, bounded guessing, unknown accounts and recovery enforce server policy', async () => {
317 + const account = await phoneAccount();
318 + const initial = await otp(account.contact);
319 + assert.equal((await providerRequest('/v1/auth/phone/verify-otp', { ...initial, newPassword: replacement })).status, 200);
320 + const authenticated = await providerRequest('/v1/auth/login', { phone: account.contact, password: replacement });
321 + const expired = await otp(account.contact, 'login');
322 + await pool.query("update auth_phone_challenge set created_at=now()-interval '10 minutes',expires_at=now()-interval '5 minutes' where id=$1", [expired.challengeId]);
323 + assert.equal((await providerRequest('/v1/auth/phone/verify-otp', expired)).status, 401);
324 + const bounded = await otp(account.contact, 'login');
325 + const wrong = bounded.code === '000000' ? '000001' : '000000';
326 + for (let i = 0; i < 5; i++) assert.equal((await providerRequest('/v1/auth/phone/verify-otp', { ...bounded, code: wrong })).status, 401);
327 + assert.equal((await providerRequest('/v1/auth/phone/verify-otp', bounded)).status, 401);
328 + assert.equal((await pool.query('select attempts from auth_phone_challenge where id=$1', [bounded.challengeId])).rows[0].attempts, 5);
329 + const missing = freshPhone();
330 + const before = smsMessages.length;
331 + const absent = await providerRequest('/v1/auth/phone/request-otp', { phone: missing, purpose: 'recovery' });
332 + assert.equal(absent.status, 202);
333 + challengeIds.add(absent.body.challengeId);
334 + assert.equal(smsMessages.length, before);
335 + assert.equal((await providerRequest('/v1/auth/phone/verify-otp', { challengeId: absent.body.challengeId, code: '000000', newPassword: password })).status, 401);
336 + const recovery = await otp(account.contact, 'recovery');
337 + const recovered = await providerRequest('/v1/auth/phone/verify-otp', { ...recovery, newPassword: password });
338 + assert.equal(recovered.status, 200);
339 + assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: authenticated.body.refreshToken })).status, 401);
340 + assert.equal((await providerRequest('/v1/auth/login', { phone: account.contact, password: replacement })).status, 401);
341 + assert.equal((await providerRequest('/v1/auth/login', { phone: account.contact, password })).status, 200);
342 + const disabledProof = await otp(account.contact, 'login');
343 + await pool.query('update app_user set disabled_at=now() where id=$1', [account.id]);
344 + assert.equal((await providerRequest('/v1/auth/phone/verify-otp', disabledProof)).status, 401);
345 + assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: recovered.body.refreshToken })).status, 401);
346 +});
347 +
348 +test('two phone challenges and competing refresh requests serialize without token reuse or deadlock', async () => {
349 + const account = await phoneAccount();
350 + const first = await otp(account.contact);
351 + const second = await otp(account.contact);
352 + const verified = await Promise.all([first, second].map((proof) => providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password })));
353 + assert.deepEqual(verified.map((response) => response.status).sort(), [200, 401]);
354 + const tokens = verified.find((response) => response.status === 200).body;
355 + const refreshed = await Promise.all([1, 2].map(() => providerRequest('/v1/auth/refresh', { refreshToken: tokens.refreshToken })));
356 + assert.deepEqual(refreshed.map((response) => response.status).sort(), [200, 401]);
357 + const active = refreshed.find((response) => response.status === 200).body;
358 + assert.equal((await pool.query('select count(*)::int as n from auth_session where user_id=$1 and revoked_at is null', [account.id])).rows[0].n, 1);
359 + assert.equal((await request('/v1/profile', undefined, { method: 'GET', token: tokens.accessToken })).status, 401);
360 + assert.equal((await request('/v1/profile', undefined, { method: 'GET', token: active.accessToken })).status, 200);
361 + assert.equal((await providerRequest('/v1/auth/logout', { refreshToken: active.refreshToken })).status, 204);
362 + assert.equal((await providerRequest('/v1/auth/logout', { refreshToken: 'invalid-synthetic-proof' })).status, 204);
363 + assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: active.refreshToken })).status, 401);
364 +});
365 +
366 +test('refresh expiry and logout with expired access proof preserve opaque refresh revocation', async () => {
367 + const account = await phoneAccount();
368 + const proof = await otp(account.contact);
369 + const verified = await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password });
370 + assert.equal(verified.status, 200);
371 + const identity = jwt.verify(verified.body.accessToken, jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' });
372 + assert.equal(identity.exp - identity.iat, 900);
373 + await pool.query("update auth_session set created_at=now()-interval '31 days',expires_at=now()-interval '1 day' where id=$1", [identity.sid]);
374 + assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: verified.body.refreshToken })).status, 401);
375 + const login = await providerRequest('/v1/auth/login', { phone: account.contact, password });
376 + assert.equal(login.status, 200);
377 + const active = jwt.verify(login.body.accessToken, jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' });
378 + const expiredAccess = jwt.sign({ sub: active.sub, sid: active.sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: -1 });
379 + assert.equal((await request('/v1/profile', undefined, { method: 'GET', token: expiredAccess })).status, 401);
380 + assert.equal((await request('/v1/auth/logout', { refreshToken: login.body.refreshToken }, { token: expiredAccess })).status, 204);
381 + assert.equal((await pool.query('select revoked_at from auth_session where id=$1', [active.sid])).rows[0].revoked_at instanceof Date, true);
382 + assert.equal((await providerRequest('/v1/auth/refresh', { refreshToken: login.body.refreshToken })).status, 401);
383 +});
384 +
385 +test('phone-only family invites require the matching verified contact and keep the inviter-selected role', async () => {
386 + const parent = await emailAccount();
387 + assert.equal((await providerRequest('/v1/auth/verify-email', { token: parent.token, newPassword: password })).status, 204);
388 + const parentLogin = await request('/v1/auth/login', { email: parent.contact, password });
389 + assert.equal(parentLogin.status, 200);
390 + const phone = await phoneAccount();
391 + const proof = await otp(phone.contact);
392 + const verified = await providerRequest('/v1/auth/phone/verify-otp', { ...proof, newPassword: password });
393 + assert.equal(verified.status, 200);
394 + const family = await request('/v1/families', { name: 'Synthetic Phone Family', role: 'parent_guardian' }, { token: parentLogin.body.accessToken });
395 + assert.equal(family.status, 201);
396 + familyIds.add(family.body.id);
397 + const invitation = await request(`/v1/families/${family.body.id}/invitations`, { phone: phone.contact, role: 'teen_minor' }, { token: parentLogin.body.accessToken });
398 + assert.equal(invitation.status, 201);
399 + assert.ok(invitation.body.invitationToken);
400 + assert.equal(invitation.body.invitationLink.startsWith('https://app.example.test/'), true);
401 + const stored = (await pool.query('select invited_email_normalized,invited_phone_normalized,token_digest from family_invitation where id=$1', [invitation.body.id])).rows[0];
402 + assert.equal(stored.invited_email_normalized, null);
403 + assert.equal(stored.invited_phone_normalized, phone.contact);
404 + assert.equal(stored.token_digest === tokenDigest(invitation.body.invitationToken), true);
405 + assert.equal((await request('/v1/invitations/accept', { token: invitation.body.invitationToken }, { token: parentLogin.body.accessToken })).status, 403);
406 + // Existing session remains active when the fixture removes the verification timestamp.
407 + await pool.query('update app_user set phone_verified_at=null where id=$1', [phone.id]);
408 + assert.equal((await request('/v1/invitations/accept', { token: invitation.body.invitationToken }, { token: verified.body.accessToken })).status, 403);
409 + await pool.query('update app_user set phone_verified_at=now() where id=$1', [phone.id]);
410 + assert.equal((await request('/v1/invitations/accept', { token: invitation.body.invitationToken, role: 'parent_guardian' }, { token: verified.body.accessToken })).status, 204);
411 + const member = (await pool.query('select role,is_admin from family_membership where family_id=$1 and user_id=$2', [family.body.id, phone.id])).rows[0];
412 + assert.equal(member.role, 'teen_minor');
413 + assert.equal(member.is_admin, false);
414 + assert.equal((await request(`/v1/families/${family.body.id}/invitations`, { phone: freshPhone(), role: 'parent_guardian' }, { token: verified.body.accessToken })).status, 403);
415 + const emailInvite = await request(`/v1/families/${family.body.id}/invitations`, { email: freshEmail(), role: 'adult_member' }, { token: parentLogin.body.accessToken });
416 + assert.equal(emailInvite.status, 201);
417 + assert.ok(emailInvite.body.invitationToken);
418 + await until(() => output.split('\n').some((line) => {
419 + try { const event = JSON.parse(line); return event.type === 'auth_delivery' && event.attemptId === emailInvite.body.id && event.status === 'failed'; }
420 + catch { return false; }
421 + }));
422 + assert.equal((await pool.query('select 1 from family_invitation where id=$1 and status=\'pending\'', [emailInvite.body.id])).rowCount, 1);
423 + assert.equal(errors.includes(invitation.body.invitationToken), false);
424 + assert.equal(output.includes(invitation.body.invitationToken), false);
425 + assert.equal(errors.includes(emailInvite.body.invitationToken), false);
426 + assert.equal(output.includes(emailInvite.body.invitationToken), false);
427 +});
428 +
429 +test('provider retry uses one idempotency key and never exposes a rejected provider payload', async () => {
430 + const attempts = [];
431 + const provider = createEmailProvider({
432 + env: { NODE_ENV: 'production', EMAIL_FROM: 'fixture@example.test', RESEND_API_KEY: 'synthetic-local-not-a-real-key' },
433 + async fetchImpl(_url, options) {
434 + attempts.push(options.headers['Idempotency-Key']);
435 + return { ok: attempts.length === 3, status: 503 };
436 + },
437 + });
438 + const result = await safelyDeliver(provider, { to: 'synthetic@example.test', subject: 'Synthetic', text: 'Synthetic fixture' }, { env: { NODE_ENV: 'test' } });
439 + assert.equal(result.delivered, true);
440 + assert.equal(attempts.length, 3);
441 + assert.equal(new Set(attempts).size, 1);
442 +});
443 +
444 +test('email ownership verification cannot enable a pre-registered attacker password', async () => {
445 + const account = await emailAccount();
446 + const duplicate = await providerRequest('/v1/auth/register', { email: account.contact, displayName: 'Real Owner', password: replacement });
447 + assert.equal(duplicate.status, 202);
448 + assert.deepEqual(duplicate.body, { accepted: true });
449 + const oldHash = (await pool.query('select password_hash from auth_credential where user_id=$1', [account.id])).rows[0].password_hash;
450 + assert.equal(await argon2.verify(oldHash, password), true);
451 + assert.equal((await providerRequest('/v1/auth/verify-email', { token: account.token })).status, 400);
452 + assert.equal((await pool.query('select email_verified_at from app_user where id=$1', [account.id])).rows[0].email_verified_at, null);
453 + assert.equal((await providerRequest('/v1/auth/verify-email', { token: account.token, newPassword: replacement })).status, 204);
454 + assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password })).status, 401);
455 + assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password: replacement })).status, 200);
456 +});
457 +
458 +test('login cannot issue a session using a stale password after concurrent recovery commits', async () => {
459 + const account = await emailAccount();
460 + assert.equal((await providerRequest('/v1/auth/verify-email', { token: account.token, newPassword: password })).status, 204);
461 + const before = mail.length;
462 + assert.equal((await providerRequest('/v1/auth/forgot-password', { email: account.contact })).status, 200);
463 + const resetMessage = await until(() => mail.slice(before).find((item) => item.to === account.contact));
464 + const reset = new URL(resetMessage.text.match(/https:\/\/\S+/)[0]).searchParams.get('token');
465 + const barrier = await pool.connect();
466 + let recovery;
467 + let staleLogin;
468 + try {
469 + await barrier.query('begin');
470 + await barrier.query('select id from app_user where id=$1 for update', [account.id]);
471 + const blocked = async (count) => (await pool.query(
472 + "select count(*)::int as n from pg_stat_activity where application_name=$1 and wait_event_type='Lock' and query='select 1 from app_user where id=$1 and disabled_at is null for update'", [applicationName],
473 + )).rows[0].n >= count;
474 + // Queue real recovery first, then let real login verify the old hash before it blocks.
475 + recovery = providerRequest('/v1/auth/reset-password', { token: reset, newPassword: replacement });
476 + await until(() => blocked(1));
477 + staleLogin = providerRequest('/v1/auth/login', { email: account.contact, password });
478 + await until(() => blocked(2));
479 + await barrier.query('commit');
480 + assert.equal((await recovery).status, 204);
481 + assert.equal((await staleLogin).status, 401);
482 + } finally {
483 + await barrier.query('rollback').catch(() => {});
484 + barrier.release();
485 + await Promise.allSettled([recovery, staleLogin].filter(Boolean));
486 + }
487 + assert.equal((await providerRequest('/v1/auth/login', { email: account.contact, password: replacement })).status, 200);
488 +});
489 +
490 +test('disabled SMS gates verification uniformly before reading or consuming a pending proof', async () => {
491 + const account = await phoneAccount();
492 + const proof = await otp(account.contact);
493 + const known = await request('/v1/auth/phone/verify-otp', { ...proof, newPassword: password });
494 + const malformed = await request('/v1/auth/phone/verify-otp', { challengeId: 'synthetic-invalid', code: 'bad' });
495 + assert.equal(known.status, 503);
496 + assert.equal(malformed.status, 503);
497 + assert.deepEqual(known.body, malformed.body);
498 + const stored = (await pool.query('select attempts,used_at from auth_phone_challenge where id=$1', [proof.challengeId])).rows[0];
499 + assert.equal(stored.attempts, 0);
500 + assert.equal(stored.used_at, null);
501 +});
502 +
503 +test('phone OTP cooldown applies equally to known and unknown contacts across purposes', async () => {
504 + const account = await phoneAccount();
505 + const unknown = freshPhone();
506 + for (const contact of [account.contact, unknown]) {
507 + const first = await providerRequest('/v1/auth/phone/request-otp', { phone: contact, purpose: 'verify' });
508 + assert.equal(first.status, 202);
509 + challengeIds.add(first.body.challengeId);
510 + const blocked = await providerRequest('/v1/auth/phone/request-otp', { phone: contact, purpose: 'recovery' });
511 + assert.equal(blocked.status, 429);
512 + assert.equal(Number(blocked.headers.get('Retry-After')) > 0, true);
513 + }
514 +});
515 +
516 +test('Persian and Iranian phone representations normalize consistently without binding a second unverified channel', async () => {
517 + const local = `0900${crypto.randomInt(1000000, 9999999)}`;
518 + const normalized = '+98' + local.slice(1);
519 + recipients.add(normalized);
520 + const persian = local.replace(/\d/g, (digit) => String.fromCharCode(0x6f0 + Number(digit)));
521 + assert.equal((await providerRequest('/v1/auth/register', { phone: persian, password, displayName: 'Synthetic Persian Phone' })).status, 202);
522 + const id = await identify(normalized);
523 + const duplicate = await providerRequest('/v1/auth/register', { phone: `00${normalized.slice(1)}`, password: replacement, displayName: 'Must Not Replace' });
524 + assert.equal(duplicate.status, 202);
525 + assert.equal((await pool.query('select count(*)::int as n from app_user where phone_normalized=$1', [normalized])).rows[0].n, 1);
526 + assert.equal((await providerRequest('/v1/auth/register', { email: freshEmail(), phone: normalized, password, displayName: 'Cannot Bind Second Contact' })).status, 400);
527 + assert.equal((await pool.query('select email_normalized from app_user where id=$1', [id])).rows[0].email_normalized, null);
528 +});
529 +
530 +test('archived families and revoked inviters cannot authorize outstanding invitations', async () => {
531 + for (const revoke of ['archive', 'admin', 'membership']) {
532 + const fixture = await familyFixture();
533 + const invitation = await phoneInvitation(fixture);
534 + if (revoke === 'archive') await pool.query('update family_workspace set archived_at=now() where id=$1', [fixture.familyId]);
535 + if (revoke === 'admin') await pool.query('update family_membership set is_admin=false where family_id=$1 and user_id=$2', [fixture.familyId, fixture.parent.id]);
536 + if (revoke === 'membership') await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [fixture.familyId, fixture.parent.id]);
537 + const accepted = await request('/v1/invitations/accept', { token: invitation.invitationToken }, { token: fixture.child.accessToken });
538 + assert.equal(accepted.status, 400);
539 + assert.equal((await pool.query('select 1 from family_membership where family_id=$1 and user_id=$2', [fixture.familyId, fixture.child.id])).rowCount, 0);
540 + if (revoke === 'archive') {
541 + assert.equal((await request(`/v1/families/${fixture.familyId}/members`, undefined, { method: 'GET', token: fixture.parent.accessToken })).status, 403);
542 + assert.equal((await request(`/v1/families/${fixture.familyId}/invitations`, { phone: freshPhone(), role: 'teen_minor' }, { token: fixture.parent.accessToken })).status, 403);
543 + }
544 + }
545 +});
546 +
547 +test('a former admin rejoining as a child cannot resurrect admin powers or override an active role', async () => {
548 + const fixture = await familyFixture();
549 + await pool.query("insert into family_membership(family_id,user_id,role,is_admin,ended_at) values($1,$2,'adult_member',true,now())", [fixture.familyId, fixture.child.id]);
550 + const invitation = await phoneInvitation(fixture);
551 + assert.equal((await request('/v1/invitations/accept', { token: invitation.invitationToken }, { token: fixture.child.accessToken })).status, 204);
552 + const row = (await pool.query('select role,is_admin from family_membership where family_id=$1 and user_id=$2', [fixture.familyId, fixture.child.id])).rows[0];
553 + assert.equal(row.role, 'teen_minor');
554 + assert.equal(row.is_admin, false);
555 + assert.equal((await request(`/v1/families/${fixture.familyId}/invitations`, { phone: freshPhone(), role: 'parent_guardian' }, { token: fixture.child.accessToken })).status, 403);
556 + // An older pending alternative grant must not change an already-active membership.
557 + const alternateToken = crypto.randomBytes(32).toString('base64url');
558 + await pool.query("insert into family_invitation(family_id,invited_phone_normalized,intended_role,token_digest,invited_by,expires_at) values($1,$2,'parent_guardian',$3,$4,now()+interval '7 days')", [fixture.familyId, fixture.child.contact, tokenDigest(alternateToken), fixture.parent.id]);
559 + assert.equal((await request('/v1/invitations/accept', { token: alternateToken }, { token: fixture.child.accessToken })).status, 409);
560 + assert.equal((await pool.query('select role from family_membership where family_id=$1 and user_id=$2', [fixture.familyId, fixture.child.id])).rows[0].role, 'teen_minor');
561 +});
562 +
563 +test('family management persists edits and securely revokes guardians, membership and archived access', async () => {
564 + const fixture = await familyFixture();
565 + const invitation = await phoneInvitation(fixture);
566 + assert.equal((await request('/v1/invitations/accept', { token: invitation.invitationToken }, { token: fixture.child.accessToken })).status, 204);
567 + const path = `/v1/families/${fixture.familyId}`;
568 + assert.equal((await request(path, { name: 'Unauthorized Rename' }, { method: 'PATCH', token: fixture.child.accessToken })).status, 403);
569 + assert.equal((await request(path, { name: 'Renamed Synthetic Family' }, { method: 'PATCH', token: fixture.parent.accessToken })).status, 200);
570 + const found = await request(path, undefined, { method: 'GET', token: fixture.child.accessToken });
571 + assert.equal(found.status, 200);
572 + assert.equal(found.body.name, 'Renamed Synthetic Family');
573 + const relation = { guardianUserId: fixture.parent.id, minorUserId: fixture.child.id };
574 + assert.equal((await request(`${path}/guardians`, relation, { token: fixture.parent.accessToken })).status, 204);
575 + assert.equal((await request(`${path}/guardians`, relation, { method: 'DELETE', token: fixture.child.accessToken })).status, 403);
576 + assert.equal((await request(`${path}/guardians`, relation, { method: 'DELETE', token: fixture.parent.accessToken })).status, 204);
577 + assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [fixture.familyId, fixture.parent.id, fixture.child.id])).rows[0].active, false);
578 + assert.equal((await request(`${path}/guardians`, relation, { token: fixture.parent.accessToken })).status, 204);
579 + assert.equal((await request(`${path}/members/${fixture.parent.id}`, undefined, { method: 'DELETE', token: fixture.parent.accessToken })).status, 409);
580 + assert.equal((await request(`${path}/members/${fixture.child.id}`, undefined, { method: 'DELETE', token: fixture.parent.accessToken })).status, 204);
581 + assert.equal((await request(path, undefined, { method: 'GET', token: fixture.child.accessToken })).status, 403);
582 + assert.equal((await pool.query('select active from guardian_relationship where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3', [fixture.familyId, fixture.parent.id, fixture.child.id])).rows[0].active, false);
583 + const outstanding = await phoneInvitation(fixture);
584 + assert.equal((await request(path, undefined, { method: 'DELETE', token: fixture.parent.accessToken })).status, 204);
585 + assert.equal((await request(path, undefined, { method: 'GET', token: fixture.parent.accessToken })).status, 403);
586 + assert.equal((await request('/v1/invitations/accept', { token: outstanding.invitationToken }, { token: fixture.child.accessToken })).status, 400);
587 + const archived = (await pool.query('select archived_at from family_workspace where id=$1', [fixture.familyId])).rows[0];
588 + assert.ok(archived.archived_at);
589 +});
backend/tests/migration_atomicity.test.js new
+34
@@ -0,0 +1,34 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
5 +import { tmpdir } from 'node:os';
6 +import path from 'node:path';
7 +import { fileURLToPath } from 'node:url';
8 +import { spawnSync } from 'node:child_process';
9 +import pg from 'pg';
10 +
11 +test('migration schema and ledger remain atomic when ledger insert fails', async () => {
12 + const base = new URL(process.env.DATABASE_URL);
13 + const name = `lifeguide_migration_${crypto.randomUUID().replaceAll('-', '')}`;
14 + const admin = new pg.Client({connectionString: base.toString()});
15 + await admin.connect();
16 + const folder = await mkdtemp(path.join(tmpdir(), 'lifeguide-migration-'));
17 + let database;
18 + try {
19 + await admin.query(`create database ${name}`);
20 + const target = new URL(base); target.pathname = `/${name}`;
21 + database = new pg.Client({connectionString: target.toString()});
22 + await database.connect();
23 + await database.query("create table schema_migration(filename text primary key check(filename <> '9999_atomic.sql'), applied_at timestamptz not null default now())");
24 + await mkdir(path.join(folder, 'migrations'));
25 + await writeFile(path.join(folder, 'migrations', '9999_atomic.sql'), 'begin;\ncreate table atomic_marker(id integer);\ncommit;\n');
26 + const result = spawnSync(process.execPath, [fileURLToPath(new URL('../scripts/migrate.js', import.meta.url))], {cwd: folder, env: {...process.env, DATABASE_URL: target.toString()}, encoding: 'utf8'});
27 + assert.notEqual(result.status, 0, 'deliberate ledger constraint failure must fail');
28 + assert.equal((await database.query("select to_regclass('atomic_marker') as marker")).rows[0].marker, null, 'schema must roll back together with failed ledger');
29 + } finally {
30 + if (database) { await database.end(); await admin.query(`drop database ${name}`); }
31 + await admin.end();
32 + await rm(folder, {recursive: true, force: true});
33 + }
34 +});
backend/tests/online_acceptance.test.js new
+232
@@ -0,0 +1,232 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import net from 'node:net';
5 +import { spawn } from 'node:child_process';
6 +import { once } from 'node:events';
7 +import path from 'node:path';
8 +import { fileURLToPath } from 'node:url';
9 +import pg from 'pg';
10 +
11 +// Real API/DB acceptance substitutes. These do not claim Flutter rendering,
12 +// Android lifecycle, iPhone/Safari installation or reachability from Iran.
13 +const databaseUrl = process.env.DATABASE_URL;
14 +assert.ok(databaseUrl, 'Configure a separate synthetic PostgreSQL database');
15 +const pool = new pg.Pool({ connectionString: databaseUrl });
16 +const backendDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
17 +const secret = 'synthetic-online-acceptance-secret-32-characters';
18 +const uuid = () => crypto.randomUUID();
19 +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
20 +const iso = (ms) => new Date(ms).toISOString();
21 +let apiProcess, base, port, output = '';
22 +
23 +async function startApi() {
24 + const reservation = net.createServer();
25 + await new Promise((resolve, reject) => { reservation.once('error', reject); reservation.listen(0, '127.0.0.1', resolve); });
26 + port = reservation.address().port;
27 + await new Promise((resolve) => reservation.close(resolve));
28 + base = `http://127.0.0.1:${port}`;
29 + output = '';
30 + apiProcess = spawn(process.execPath, ['src/entrypoint.js'], {
31 + cwd: backendDir,
32 + env: { ...process.env, NODE_ENV: 'test', DATABASE_URL: databaseUrl, JWT_SECRET: secret, PORT: String(port),
33 + RATE_LIMIT_GENERAL_MAX: '2000', RATE_LIMIT_AUTH_MAX: '2000', ENABLE_SENSITIVE_FEATURES: 'false',
34 + EMAIL_FROM: '', SMTP_HOST: '', SMTP_PORT: '', RESEND_API_KEY: '',
35 + SMS_PROVIDER: '', SMS_PROVIDER_URL: '', SMS_PROVIDER_TOKEN: '', AI_API_KEY: '', AI_BASE_URL: '', AI_MODEL: '' },
36 + stdio: ['ignore', 'pipe', 'pipe'],
37 + });
38 + apiProcess.stdout.on('data', (chunk) => { output += chunk.toString(); });
39 + apiProcess.stderr.on('data', (chunk) => { output += chunk.toString(); });
40 + for (let attempt = 0; attempt < 100; attempt++) {
41 + if (apiProcess.exitCode !== null) throw new Error(`Synthetic API failed to start: ${output}`);
42 + try {
43 + const ready = await fetch(`${base}/ready`, { signal: AbortSignal.timeout(500) });
44 + if (ready.status === 200) return;
45 + } catch { /* Poll only the loopback test process. */ }
46 + await sleep(50);
47 + }
48 + throw new Error('Synthetic API readiness timed out');
49 +}
50 +async function stopApi() {
51 + if (!apiProcess || apiProcess.exitCode !== null) return;
52 + const current = apiProcess;
53 + const exited = once(current, 'exit');
54 + current.kill('SIGTERM');
55 + const killer = setTimeout(() => current.kill('SIGKILL'), 3000);
56 + await exited;
57 + clearTimeout(killer);
58 + apiProcess = null;
59 +}
60 +async function request(route, { method = 'GET', body, actor, token = actor?.accessToken } = {}) {
61 + const response = await fetch(base + route, { method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
62 + body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(5000) });
63 + const raw = await response.text();
64 + return { status: response.status, body: raw ? JSON.parse(raw) : null };
65 +}
66 +async function register(displayName) {
67 + const email = `acceptance-${uuid()}@example.test`, password = 'SyntheticOnlinePass!123';
68 + const created = await request('/v1/auth/register', { method: 'POST', body: { displayName, email, password } });
69 + // Test-only delivery hook provides proof tokens. Real email/SMS delivery is
70 + // deliberately unconfigured and remains UNVERIFIED by this acceptance test.
71 + assert.equal(created.status, 201);
72 + assert.equal((await request('/v1/auth/verify-email', { method: 'POST', body: { token: created.body.verificationToken, newPassword: password } })).status, 204);
73 + const login = await request('/v1/auth/login', { method: 'POST', body: { email, password } });
74 + assert.equal(login.status, 200);
75 + const profile = await request('/v1/profile', { token: login.body.accessToken });
76 + assert.equal(profile.status, 200);
77 + return { id: profile.body.user_id, email, ...login.body };
78 +}
79 +async function refresh(actor) {
80 + const previous = actor.refreshToken;
81 + const response = await request('/v1/auth/refresh', { method: 'POST', body: { refreshToken: previous } });
82 + assert.equal(response.status, 200);
83 + assert.notEqual(response.body.refreshToken, previous);
84 + Object.assign(actor, response.body);
85 +}
86 +async function invite(mother, member, familyId, role) {
87 + const invitation = await request(`/v1/families/${familyId}/invitations`, { method: 'POST', actor: mother, body: { email: member.email, role } });
88 + assert.equal(invitation.status, 201);
89 + assert.equal((await request('/v1/invitations/accept', { method: 'POST', actor: member, body: { token: invitation.body.invitationToken } })).status, 204);
90 +}
91 +const reportRoute = (familyId, childId) => `/v1/families/${familyId}/children/${childId}/learning-report`;
92 +async function sync(actor, mutation) {
93 + return request('/v1/sync/mutations', { method: 'POST', actor, body: { mutations: [mutation] } });
94 +}
95 +
96 +test('online eight-step family scenario: real entrypoint, independent HTTP clients and PostgreSQL; device/Safari UNVERIFIED', async (t) => {
97 + try {
98 + await startApi();
99 + const [child, mother, father, outsider] = await Promise.all(['فرزند آزمایشی', 'مادر آزمایشی', 'پدر آزمایشی', 'خانواده دیگر آزمایشی'].map(register));
100 + const createdFamily = await request('/v1/families', { method: 'POST', actor: mother, body: { name: 'خانواده مصنوعی پذیرش', role: 'parent_guardian' } });
101 + assert.equal(createdFamily.status, 201);
102 + const familyId = createdFamily.body.id;
103 + await invite(mother, child, familyId, 'teen_minor');
104 + await invite(mother, father, familyId, 'parent_guardian');
105 + for (const parent of [mother, father]) assert.equal((await request(`/v1/families/${familyId}/guardians`, {
106 + method: 'POST', actor: mother, body: { guardianUserId: parent.id, minorUserId: child.id },
107 + })).status, 204);
108 + const otherFamily = await request('/v1/families', { method: 'POST', actor: outsider, body: { name: 'خانواده مستقل مصنوعی', role: 'parent_guardian' } });
109 + assert.equal(otherFamily.status, 201);
110 + const taskId = uuid(), createBody = { id: uuid(), entityType: 'plan_item', entityId: taskId, operation: 'create', expectedVersion: 0, payload: {
111 + kind: 'assignment', title: 'تمرین ریاضی — فقط داده آزمایشی', notes: 'OWNER-PRIVATE-ACCEPTANCE-NOTE',
112 + familyId, visibility: 'parent_guardian', plannedDurationSeconds: 1800, dueAt: iso(Date.now() + 3600000),
113 + } };
114 + const reportPath = reportRoute(familyId, child.id);
115 +
116 + await t.test('A / step 1: child homework creation independently verified by API and PostgreSQL', async () => {
117 + const created = await sync(child, createBody);
118 + assert.equal(created.status, 200);
119 + assert.equal(created.body.results[0].status, 'accepted');
120 + assert.equal(created.body.results[0].item.id, taskId);
121 + const independentRead = await request(`/v1/plan-items/${taskId}`, { actor: child });
122 + assert.equal(independentRead.status, 200);
123 + assert.equal(independentRead.body.notes, 'OWNER-PRIVATE-ACCEPTANCE-NOTE');
124 + const database = await pool.query('select id,owner_user_id,title,version from plan_item where id=$1', [taskId]);
125 + assert.equal(database.rowCount, 1);
126 + assert.equal(database.rows[0].owner_user_id, child.id);
127 + assert.equal(Number(database.rows[0].version), 1);
128 + });
129 + await t.test('B / step 2: mother receives permitted report with freshness; PWA rendering UNVERIFIED', async () => {
130 + const report = await request(reportPath, { actor: mother });
131 + assert.equal(report.status, 200);
132 + assert.ok(report.body.items.some((item) => item.id === taskId));
133 + assert.ok(Number.isFinite(Date.parse(report.body.asOf)));
134 + assert.ok(Number.isFinite(Date.parse(report.body.lastSyncAt)));
135 + assert.ok(report.body.sourceVersion);
136 + assert.ok(!JSON.stringify(report.body).includes('OWNER-PRIVATE-ACCEPTANCE-NOTE'));
137 + });
138 + const t0 = Date.now() - 3600000, startBody = { id: uuid(), mutationId: uuid(), planItemId: taskId, source: 'timer', startedAt: iso(t0) };
139 + let session;
140 + await t.test('G / steps 3–4: timer pause survives full API process restart, resumes and stops without double counting', async () => {
141 + const started = await request('/v1/study/sessions', { method: 'POST', actor: child, body: startBody });
142 + assert.equal(started.status, 201); session = started.body.session;
143 + const overlap = await request('/v1/study/sessions', { method: 'POST', actor: child, body: { ...startBody, id: uuid(), mutationId: uuid(), startedAt: iso(t0 + 1000) } });
144 + assert.equal(overlap.status, 409); assert.equal(overlap.body.error, 'study_time_overlap');
145 + const paused = await request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', actor: child,
146 + body: { mutationId: uuid(), expectedVersion: session.version, action: 'pause', occurredAt: iso(t0 + 5 * 60000) } });
147 + assert.equal(paused.status, 200); session = paused.body.session;
148 + await stopApi(); await startApi();
149 + for (const actor of [child, mother, father]) await refresh(actor);
150 + const restored = await request(`/v1/study/sessions/${session.id}`, { actor: child });
151 + assert.equal(restored.status, 200); assert.equal(restored.body.session.status, 'paused');
152 + assert.equal(restored.body.session.recordedDurationSeconds, 300);
153 + const resumed = await request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', actor: child,
154 + body: { mutationId: uuid(), expectedVersion: restored.body.session.version, action: 'resume', occurredAt: iso(t0 + 15 * 60000) } });
155 + assert.equal(resumed.status, 200);
156 + const stopBody = { mutationId: uuid(), expectedVersion: resumed.body.session.version, action: 'stop', occurredAt: iso(t0 + 35 * 60000) };
157 + const stopped = await request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', actor: child, body: stopBody });
158 + assert.equal(stopped.status, 200); session = stopped.body.session;
159 + assert.equal(session.recordedDurationSeconds, 1500); assert.equal(session.isEvidenceOfStudy, false);
160 + const replay = await request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', actor: child, body: stopBody });
161 + assert.equal(replay.body.acknowledgement.status, 'already_applied');
162 + assert.equal(replay.body.session.recordedDurationSeconds, 1500);
163 + const durations = await pool.query('select count(*)::int n,sum(extract(epoch from ends_at-starts_at))::int seconds from study_interval where session_id=$1', [session.id]);
164 + assert.deepEqual(durations.rows[0], { n: 2, seconds: 1500 });
165 + t.diagnostic('G substitute: actual Node API process restart and timer HTTP replay; Flutter timer app exit/re-sync remains UNVERIFIED.');
166 + });
167 + await t.test('step 5: recorded duration appears only in permitted parent report and is not proof of study', async () => {
168 + const report = await request(reportPath, { actor: mother });
169 + assert.equal(report.status, 200);
170 + assert.equal(report.body.items.find((item) => item.id === taskId).recordedDurationSeconds, 1500);
171 + assert.equal(report.body.items.find((item) => item.id === taskId).plannedDurationSeconds, 1800);
172 + assert.equal(report.body.isEvidenceOfStudy, false);
173 + assert.equal(report.body.recordingDisclaimerKey, 'recorded_time_is_not_proof_of_study');
174 + });
175 + await t.test('C / steps 6–7: child completion is observed by father through an independent authenticated API poll', async () => {
176 + const current = await request(`/v1/plan-items/${taskId}`, { actor: child });
177 + const complete = await sync(child, { id: uuid(), entityType: 'plan_item', entityId: taskId, operation: 'complete', expectedVersion: Number(current.body.version), payload: {} });
178 + assert.equal(complete.body.results[0].status, 'accepted');
179 + const fatherReport = await request(reportPath, { actor: father });
180 + const task = fatherReport.body.items.find((item) => item.id === taskId);
181 + assert.equal(task.status, 'completed'); assert.equal(task.activityState, 'completed');
182 + assert.equal(task.activitySource, 'self_reported');
183 + assert.equal(task.recordedDurationSeconds, 1500);
184 + });
185 + await t.test('D / step 8: API process restart preserves all three accounts, refresh sessions and shared PostgreSQL records', async () => {
186 + await stopApi(); await startApi();
187 + for (const actor of [child, mother, father]) {
188 + await refresh(actor);
189 + assert.equal((await request('/v1/profile', { actor })).status, 200);
190 + const read = await request(`/v1/plan-items/${taskId}`, { actor });
191 + assert.equal(read.status, 200); assert.equal(read.body.status, 'completed');
192 + }
193 + assert.equal((await pool.query('select status,recorded_duration_seconds from study_session where id=$1', [session.id])).rows[0].recorded_duration_seconds, 1500);
194 + t.diagnostic('D substitute: actual API process restart and DB-backed refresh. Closing/reopening Android and installed iPhone PWA remains UNVERIFIED.');
195 + });
196 + await t.test('E: disconnected HTTP request stays queued and later identical replay creates exactly one durable task', async () => {
197 + const offline = { id: uuid(), entityType: 'plan_item', entityId: uuid(), operation: 'create', expectedVersion: 0, payload: {
198 + kind: 'assignment', title: 'تکلیف آفلاین مصنوعی', familyId, visibility: 'parent_guardian', plannedDurationSeconds: 600,
199 + } };
200 + const retainedJournal = JSON.stringify(offline);
201 + await stopApi();
202 + await assert.rejects(sync(child, JSON.parse(retainedJournal)), TypeError);
203 + await startApi();
204 + const first = await sync(child, JSON.parse(retainedJournal)), second = await sync(child, JSON.parse(retainedJournal));
205 + assert.equal(first.body.results[0].status, 'accepted');
206 + assert.equal(second.body.results[0].status, 'already_applied');
207 + assert.deepEqual(second.body.results[0].item, first.body.results[0].item);
208 + assert.equal((await pool.query('select count(*)::int n from plan_item where id=$1', [offline.entityId])).rows[0].n, 1);
209 + t.diagnostic('E substitute: real HTTP disconnection and retained JSON mutation replay; Flutter persistent offline queue requires separate evidence, device offline acceptance UNVERIFIED.');
210 + });
211 + await t.test('F: other-family parent cannot read/write shared child data; private tasks/notes stay owner-only', async () => {
212 + assert.equal((await request(reportPath, { actor: outsider })).status, 403);
213 + assert.equal((await request(`/v1/plan-items/${taskId}`, { actor: outsider })).status, 404);
214 + const current = await request(`/v1/plan-items/${taskId}`, { actor: child });
215 + assert.equal((await request(`/v1/plan-items/${taskId}`, { method: 'PATCH', actor: outsider, body: { title: 'Forbidden', expectedVersion: Number(current.body.version) } })).status, 403);
216 + const privateTask = await request('/v1/plan-items', { method: 'POST', actor: child, body: {
217 + kind: 'task', title: 'PRIVATE-TASK-ACCEPTANCE-TITLE', notes: 'PRIVATE-TASK-ACCEPTANCE-NOTE', visibility: 'private',
218 + } });
219 + assert.equal(privateTask.status, 201);
220 + for (const parent of [mother, father, outsider]) assert.equal((await request(`/v1/plan-items/${privateTask.body.id}`, { actor: parent })).status, 404);
221 + for (const parent of [mother, father]) {
222 + const calendar = await request(`/v1/families/${familyId}/calendar`, { actor: parent });
223 + const content = JSON.stringify(calendar.body);
224 + assert.ok(!content.includes('OWNER-PRIVATE-ACCEPTANCE-NOTE'));
225 + assert.ok(!content.includes('PRIVATE-TASK-ACCEPTANCE'));
226 + }
227 + assert.equal((await request(`/v1/study/sessions/${session.id}`, { actor: mother })).status, 404);
228 + assert.equal((await request(`/v1/study/sessions/${session.id}`)).status, 401);
229 + });
230 + t.diagnostic('H/Safari install, Android devices, PWA UI/session lifecycle, no-VPN Iran reachability, real SMS/email delivery: UNVERIFIED. Only synthetic data and loopback/local PostgreSQL were used.');
231 + } finally { await stopApi(); await pool.end(); }
232 +});
backend/tests/phase3.test.js
+6 -6
@@ -36,7 +36,7 @@ async function registerVerified(email, displayName) {
36 });
37 assert.equal(reg.status,201);
38 assert.equal((await request('/v1/auth/verify-email',{
39 - method:'POST', body:{ token:reg.body.verificationToken },
39 + method:'POST', body:{ token:reg.body.verificationToken, newPassword:password },
40 })).status,204);
41 const login = await request('/v1/auth/login',{
42 method:'POST', body:{ email, password },
@@ -162,7 +162,7 @@ test('phase 3 planner school family vertical slice', async () => {
162 assert.ok(!parentPrivateAttempt.body.items.some((x)=>x.id===privateTask.body.id));
163
164 const grade = await request(`/v1/school/plan-items/${assignment.body.id}/grade`,{
165 - method:'PATCH', token:teen.token, body:{points:18,outOf:20},
165 + method:'PATCH', token:teen.token, body:{points:18,outOf:20,expectedVersion:Number(assignment.body.version)},
166 });
167 assert.equal(grade.status,200);
168
@@ -182,7 +182,7 @@ test('phase 3 planner school family vertical slice', async () => {
182
183 const rescheduled = new Date(Date.now()+2*60*60*1000).toISOString();
184 const update = await request(`/v1/plan-items/${assignment.body.id}`,{
185 - method:'PATCH', token:teen.token, body:{dueAt:rescheduled},
185 + method:'PATCH', token:teen.token, body:{dueAt:rescheduled,expectedVersion:Number(grade.body.version)},
186 });
187 assert.equal(update.status,200);
188
@@ -194,7 +194,7 @@ test('phase 3 planner school family vertical slice', async () => {
194 assert.ok(reminderRows.rows.every((x)=>x.status==='scheduled'));
195
196 const completed = await request(`/v1/plan-items/${assignment.body.id}`,{
197 - method:'PATCH', token:teen.token, body:{status:'completed'},
197 + method:'PATCH', token:teen.token, body:{status:'completed',expectedVersion:Number(update.body.version)},
198 });
199 assert.equal(completed.status,200);
200 const cancelled = await pool.query(
@@ -208,7 +208,7 @@ test('phase 3 planner school family vertical slice', async () => {
208 method:'POST', token:teen.token,
209 body:{mutations:[{
210 id:mutationId, entityType:'plan_item', entityId:privateTask.body.id,
211 - operation:'reschedule', clientUpdatedAt:new Date().toISOString(),
211 + operation:'reschedule', expectedVersion:Number(privateTask.body.version),
212 payload:{dueAt:rescheduled},
213 }]},
214 });
@@ -228,7 +228,7 @@ test('phase 3 planner school family vertical slice', async () => {
228 method:'POST', token:teen.token,
229 body:{mutations:[{
230 id:mutationId, entityType:'plan_item', entityId:privateTask.body.id,
231 - operation:'reschedule', clientUpdatedAt:new Date().toISOString(),
231 + operation:'reschedule', expectedVersion:Number(privateTask.body.version),
232 payload:{dueAt:rescheduled},
233 }]},
234 });
backend/tests/phase4.test.js
+4 -2
@@ -1,6 +1,8 @@
1 import test, { after } from 'node:test';
2 import assert from 'node:assert/strict';
3 -import { app, pool } from '../src/server.js';
3 +// Explicit synthetic opt-in; NODE_ENV=test never enables sensitive APIs itself.
4 +process.env.ENABLE_SENSITIVE_FEATURES = 'true';
5 +const { app, pool } = await import('../src/server.js');
6
7 const server = app.listen(0);
8 const address = server.address();
@@ -38,7 +40,7 @@ async function registerVerified(email, displayName) {
40 (
41 await request('/v1/auth/verify-email', {
42 method: 'POST',
41 - body: { token: registration.body.verificationToken },
43 + body: { token: registration.body.verificationToken, newPassword: password },
44 })
45 ).status,
46 204,
backend/tests/planner_sync.test.js new
+186
@@ -0,0 +1,186 @@
1 +import test, { after } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import express from 'express';
5 +import jwt from 'jsonwebtoken';
6 +import pg from 'pg';
7 +import { createSessionAuth } from '../src/session_auth.js';
8 +import { createPhase3Router } from '../src/phase3.js';
9 +
10 +if (!process.env.DATABASE_URL) throw new Error('planner sync tests require synthetic PostgreSQL');
11 +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
12 +const secret = 'synthetic-planner-sync-secret-32-characters';
13 +const app = express();
14 +app.use(express.json({ limit: '64kb' }));
15 +app.use('/v1', createPhase3Router({ pool, auth: createSessionAuth({ pool, jwtSecret: secret }) }));
16 +app.use((error, _req, res, _next) => { console.error(error); res.status(500).json({ error: 'internal_error' }); });
17 +let server = app.listen(0);
18 +let base = `http://127.0.0.1:${server.address().port}`;
19 +after(async () => { await new Promise((resolve) => server.close(resolve)); await pool.end(); });
20 +const uuid = () => crypto.randomUUID();
21 +async function user() {
22 + const id = uuid(), sid = uuid();
23 + await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `planner-test:${id}`, `${id}@example.test`]);
24 + await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic Planner','adult_blue')", [id]);
25 + await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, uuid()]);
26 + return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) };
27 +}
28 +async function fixture() {
29 + const child = await user(), parent = await user(), outsider = await user(), familyId = uuid();
30 + await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Planner Family',$2)", [familyId, parent.id]);
31 + await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor'),($1,$3,'parent_guardian')", [familyId, child.id, parent.id]);
32 + await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, child.id]);
33 + return { child, parent, outsider, familyId };
34 +}
35 +async function request(path, actor, { method = 'GET', body } = {}) {
36 + const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
37 + const text = await response.text();
38 + return { status: response.status, body: response.headers.get('content-type')?.includes('application/json') ? JSON.parse(text) : text };
39 +}
40 +async function sync(actor, mutations) { return request('/v1/sync/mutations', actor, { method: 'POST', body: { mutations } }); }
41 +const create = (f, payload = {}) => ({ id: uuid(), entityType: 'plan_item', entityId: uuid(), operation: 'create', expectedVersion: 0,
42 + payload: { kind: 'assignment', title: 'تکلیف ریاضی آزمایشی', familyId: f.familyId, visibility: 'parent_guardian', dueAt: new Date(Date.now() + 3600000).toISOString(), plannedDurationSeconds: 1500, ...payload } });
43 +
44 +test('offline stable create/retry/update/complete/archive have canonical acknowledgements and PostgreSQL survives HTTP restart', async () => {
45 + const f = await fixture();
46 + const mutation = create(f);
47 + const created = await sync(f.child, [mutation]);
48 + assert.equal(created.status, 200);
49 + const a = created.body.results[0];
50 + assert.equal(a.status, 'accepted');
51 + assert.equal(a.item.id, mutation.entityId);
52 + assert.equal(Number(a.item.version), 1);
53 + assert.equal(a.item.planned_duration_seconds, 1500);
54 + assert.ok(Number.isFinite(Date.parse(a.acceptedAt)));
55 + const duplicate = await sync(f.child, [mutation]);
56 + assert.equal(duplicate.body.results[0].status, 'already_applied');
57 + assert.deepEqual(duplicate.body.results[0].item, a.item);
58 + assert.equal((await pool.query('select count(*)::int n from plan_item where id=$1', [mutation.entityId])).rows[0].n, 1);
59 + const update = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'update', expectedVersion: 1, payload: { title: 'ویرایش تکلیف', plannedDurationSeconds: 600 } };
60 + const updated = await sync(f.child, [update]);
61 + assert.equal(updated.body.results[0].status, 'accepted');
62 + assert.equal(Number(updated.body.results[0].item.version), 2);
63 + const complete = await sync(f.child, [{ ...update, id: uuid(), operation: 'complete', expectedVersion: 2, payload: {} }]);
64 + assert.equal(complete.body.results[0].item.status, 'completed');
65 + assert.equal(Number(complete.body.results[0].item.version), 3);
66 + const event = (await pool.query('select state,source from activity_state_event where plan_item_id=$1 order by version desc limit 1', [mutation.entityId])).rows[0];
67 + assert.deepEqual(event, { state: 'completed', source: 'self_reported' });
68 + await new Promise((resolve) => server.close(resolve)); server = app.listen(0); base = `http://127.0.0.1:${server.address().port}`;
69 + const read = await request(`/v1/plan-items/${mutation.entityId}`, f.child);
70 + assert.equal(read.status, 200);
71 + assert.equal(read.body.title, 'ویرایش تکلیف');
72 + const archive = await sync(f.child, [{ ...update, id: uuid(), operation: 'archive', expectedVersion: 3, payload: {} }]);
73 + assert.equal(archive.body.results[0].item.status, 'cancelled');
74 + assert.equal((await pool.query('select status from plan_item where id=$1', [mutation.entityId])).rows[0].status, 'cancelled');
75 +});
76 +
77 +test('server versions defeat future client clocks; concurrent updates and changed mutation reuse are explicit conflicts', async () => {
78 + const f = await fixture(), mutation = create(f);
79 + assert.equal((await sync(f.child, [mutation])).body.results[0].status, 'accepted');
80 + const reused = await sync(f.child, [{ ...mutation, payload: { ...mutation.payload, title: 'Changed duplicate' } }]);
81 + assert.equal(reused.body.results[0].status, 'conflict');
82 + assert.equal(reused.body.results[0].error, 'mutation_id_reused');
83 + assert.equal(reused.body.results[0].httpStatus, 409);
84 + const stale = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'update', expectedVersion: 0, clientUpdatedAt: '2999-01-01T00:00:00Z', payload: { title: 'Wrong stale update' } };
85 + assert.equal((await sync(f.child, [stale])).body.results[0].error, 'version_conflict');
86 + const [a, b] = await Promise.all([sync(f.child, [{ ...stale, id: uuid(), expectedVersion: 1 }]), sync(f.child, [{ ...stale, id: uuid(), expectedVersion: 1, payload: { title: 'Other writer' } }])]);
87 + assert.deepEqual([a.body.results[0].status, b.body.results[0].status].sort(), ['accepted', 'conflict']);
88 + assert.equal((await pool.query('select version from plan_item where id=$1', [mutation.entityId])).rows[0].version, '2');
89 +});
90 +
91 +test('direct planner writes require expectedVersion, reject malformed data and return compatible version-one creates', async () => {
92 + const f = await fixture();
93 + const created = await request('/v1/plan-items', f.child, { method: 'POST', body: create(f).payload });
94 + assert.equal(created.status, 201); assert.equal(Number(created.body.version), 1);
95 + assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { title: 'No version' } })).status, 400);
96 + assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { expectedVersion: 0, title: 'Stale' } })).status, 409);
97 + assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { expectedVersion: 1, plannedDurationSeconds: 86401 } })).status, 400);
98 + assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { expectedVersion: 1, dueAt: 'not-a-date' } })).status, 400);
99 + const updated = await request(`/v1/plan-items/${created.body.id}`, f.child, { method: 'PATCH', body: { expectedVersion: 1, plannedDurationSeconds: 0 } });
100 + assert.equal(updated.status, 200); assert.equal(updated.body.planned_duration_seconds, 0);
101 + assert.equal((await request(`/v1/plan-items/${created.body.id}`, f.parent, { method: 'PATCH', body: { expectedVersion: 2, title: 'Parent overwrite' } })).status, 403);
102 +});
103 +
104 +test('duplicate sync mutation rechecks ownership and current family membership; archived families close all helpers and reads', async () => {
105 + const f = await fixture(), mutation = create(f);
106 + assert.equal((await sync(f.child, [mutation])).body.results[0].status, 'accepted');
107 + const forged = await sync(f.outsider, [{ ...mutation, id: uuid(), operation: 'update', expectedVersion: 1, payload: { title: 'Forbidden' } }]);
108 + assert.equal(forged.body.results[0].status, 'rejected');
109 + await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
110 + assert.equal((await sync(f.child, [mutation])).body.results[0].status, 'rejected');
111 + await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
112 + await pool.query('update family_workspace set archived_at=now() where id=$1', [f.familyId]);
113 + assert.equal((await request(`/v1/families/${f.familyId}/calendar`, f.parent)).status, 403);
114 + assert.equal((await request(`/v1/school/${f.child.id}/overview`, f.parent)).status, 403);
115 + assert.deepEqual((await pool.query('select is_active_family_member($1,$2) member,is_active_guardian($1,$3,$2) guardian', [f.familyId, f.child.id, f.parent.id])).rows[0], { member: false, guardian: false });
116 +});
117 +
118 +test('every parent planner read strips owner notes and every school/support aggregate excludes private plans', async () => {
119 + const f = await fixture();
120 + const publicPlan = await request('/v1/plan-items', f.child, { method: 'POST', body: create(f, { notes: 'PRIVATE-NOTES-SECRET' }).payload });
121 + const privatePlan = await request('/v1/plan-items', f.child, { method: 'POST', body: create(f, { visibility: 'private', title: 'PRIVATE-TITLE-SECRET', notes: 'PRIVATE-NOTES-SECRET' }).payload });
122 + await pool.query('update plan_item set grade_points=18,grade_out_of=20 where id=$1', [publicPlan.body.id]);
123 + await pool.query("update plan_item set status='completed',completed_at=now(),grade_points=100,grade_out_of=100 where id=$1", [privatePlan.body.id]);
124 + for (const path of ['/v1/today', '/v1/plan-items', `/v1/plan-items/${publicPlan.body.id}`, `/v1/families/${f.familyId}/calendar`, `/v1/school/${f.child.id}/overview`, `/v1/families/${f.familyId}/children/${f.child.id}/support-summary`]) {
125 + const result = await request(path, f.parent);
126 + assert.equal(result.status, 200, path);
127 + assert.ok(!JSON.stringify(result.body).includes('PRIVATE-NOTES-SECRET'), path);
128 + assert.ok(!JSON.stringify(result.body).includes('PRIVATE-TITLE-SECRET'), path);
129 + }
130 + const owner = await request(`/v1/plan-items/${publicPlan.body.id}`, f.child);
131 + assert.equal(owner.body.notes, 'PRIVATE-NOTES-SECRET');
132 + const support = await request(`/v1/families/${f.familyId}/children/${f.child.id}/support-summary`, f.parent);
133 + assert.equal(support.body.metrics.gradePercent, 90);
134 + assert.equal(support.body.metrics.completedLast7Days, 0);
135 + const overview = await request(`/v1/school/${f.child.id}/overview`, f.parent);
136 + assert.equal(overview.body.grades.length, 1);
137 +});
138 +
139 +test('mutation IDs are scoped to accounts and a malformed/unauthorized mutation never aborts accepted siblings', async () => {
140 + const a = await fixture(), b = await fixture(), first = create(a), second = { ...create(b), id: first.id };
141 + assert.equal((await sync(a.child, [first])).body.results[0].status, 'accepted');
142 + assert.equal((await sync(b.child, [second])).body.results[0].status, 'accepted');
143 + const bad = { ...create(a), entityId: 'not-a-uuid' }, valid = create(a);
144 + const batch = await sync(a.child, [bad, valid]);
145 + assert.equal(batch.status, 200);
146 + assert.deepEqual(batch.body.results.map((x) => x.status), ['rejected', 'accepted']);
147 + assert.equal((await pool.query('select count(*)::int n from sync_mutation where id=$1', [first.id])).rows[0].n, 2);
148 +});
149 +
150 +test('reschedule, selected-member grants and private-note edits share validation without publishing notes', async () => {
151 + const f = await fixture(), mutation = create(f, { visibility: 'selected_members', selectedMemberIds: [f.parent.id], notes: 'OWN-NOTE-SECRET' });
152 + const created = await sync(f.child, [mutation]);
153 + assert.equal(created.body.results[0].status, 'accepted');
154 + assert.equal((await request(`/v1/plan-items/${mutation.entityId}`, f.parent)).status, 200);
155 + const reschedule = { id: uuid(), entityType: 'plan_item', entityId: mutation.entityId, operation: 'reschedule', expectedVersion: 1, payload: { dueAt: new Date(Date.now() + 7200000).toISOString() } };
156 + assert.equal((await sync(f.child, [reschedule])).body.results[0].status, 'accepted');
157 + const madePrivate = await sync(f.child, [{ ...reschedule, id: uuid(), operation: 'update', expectedVersion: 2, payload: { visibility: 'private', notes: 'EDITED-OWN-NOTE-SECRET' } }]);
158 + assert.equal(madePrivate.body.results[0].status, 'accepted');
159 + assert.equal((await request(`/v1/plan-items/${mutation.entityId}`, f.parent)).status, 404);
160 + const owner = await request(`/v1/plan-items/${mutation.entityId}`, f.child);
161 + assert.equal(owner.body.notes, 'EDITED-OWN-NOTE-SECRET');
162 + assert.equal((await pool.query("select count(*)::int n from sharing_grant where resource_type='plan_item' and resource_id=$1", [mutation.entityId])).rows[0].n, 0);
163 +});
164 +
165 +test('grade updates require the latest owner version and support time counts only visible recorded intervals', async () => {
166 + const f = await fixture(), a = create(f), b = create(f, { visibility: 'private' });
167 + const created = await sync(f.child, [a, b]);
168 + assert.ok(created.body.results.every((x) => x.status === 'accepted'));
169 + const path = `/v1/school/plan-items/${a.entityId}/grade`;
170 + assert.equal((await request(path, f.child, { method: 'PATCH', body: { points: 18, outOf: 20 } })).status, 400);
171 + const grade = await request(path, f.child, { method: 'PATCH', body: { points: 18, outOf: 20, expectedVersion: 1 } });
172 + assert.equal(grade.status, 200);
173 + assert.equal(Number(grade.body.version), 2);
174 + assert.equal((await request(path, f.child, { method: 'PATCH', body: { points: 19, outOf: 20, expectedVersion: 1 } })).status, 409);
175 + const t = Date.now() - 3600000;
176 + for (const [planId, offset, seconds] of [[a.entityId, 0, 300], [b.entityId, 600000, 600]]) {
177 + const sessionId = uuid(), start = new Date(t + offset), end = new Date(t + offset + seconds * 1000);
178 + await pool.query("insert into study_session(id,child_user_id,plan_item_id,source,status,started_at,ended_at,last_event_at,recorded_duration_seconds) values($1,$2,$3,'self_reported','completed',$4,$5,$5,$6)", [sessionId, f.child.id, planId, start, end, seconds]);
179 + await pool.query('insert into study_interval(session_id,starts_at,ends_at) values($1,$2,$3)', [sessionId, start, end]);
180 + }
181 + const report = await request(`/v1/families/${f.familyId}/children/${f.child.id}/support-summary`, f.parent);
182 + assert.equal(report.status, 200);
183 + assert.equal(report.body.metrics.recordedStudySecondsLast7Days, 300);
184 + assert.equal(report.body.metrics.studyMinutesLast7Days, 5);
185 + assert.equal(report.body.metrics.recordedTimeIsProofOfStudy, false);
186 +});
backend/tests/privacy_regression.test.js new
+361
@@ -0,0 +1,361 @@
1 +import test, { after, before } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import http from 'node:http';
5 +import express from 'express';
6 +import jwt from 'jsonwebtoken';
7 +import pg from 'pg';
8 +import { createPhase4Router } from '../src/phase4.js';
9 +import { createPhase6Router } from '../src/phase6.js';
10 +import { createSessionAuth } from '../src/session_auth.js';
11 +import { operationalErrorHandler } from '../src/operations.js';
12 +
13 +assert.ok(process.env.DATABASE_URL, 'Configure a separate synthetic PostgreSQL test database');
14 +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
15 +const secret = 'synthetic-privacy-test-secret-at-least-32-characters';
16 +const users = [];
17 +const families = [];
18 +const servers = [];
19 +let defaultBase;
20 +let enabledBase;
21 +
22 +async function serve(options) {
23 + const app = express();
24 + app.use(express.json({ limit: '64kb' }));
25 + const auth = createSessionAuth({ pool, jwtSecret: secret });
26 + app.use('/v1', createPhase4Router({ pool, auth, ...options }));
27 + app.use('/v1', createPhase6Router({ pool, auth, ...options }));
28 + app.use(operationalErrorHandler);
29 + const server = app.listen(0, '127.0.0.1');
30 + await new Promise((resolve) => server.once('listening', resolve));
31 + servers.push(server);
32 + return `http://127.0.0.1:${server.address().port}`;
33 +}
34 +
35 +before(async () => {
36 + delete process.env.ENABLE_SENSITIVE_FEATURES;
37 + defaultBase = await serve({});
38 + enabledBase = await serve({ sensitiveFeaturesEnabled: true });
39 +});
40 +
41 +after(async () => {
42 + for (const server of servers) await new Promise((resolve) => server.close(resolve));
43 + try {
44 + if (families.length) {
45 + await pool.query('delete from access_audit where family_id=any($1::uuid[])', [families]);
46 + await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
47 + }
48 + if (users.length) await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
49 + } finally {
50 + await pool.end();
51 + }
52 +});
53 +
54 +async function user() {
55 + const id = crypto.randomUUID();
56 + const sid = crypto.randomUUID();
57 + await pool.query(
58 + 'insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())',
59 + [id, `privacy-test:${id}`, `privacy-test-${id}@example.test`],
60 + );
61 + users.push(id);
62 + await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic Privacy','adult_blue')", [id]);
63 + await pool.query(
64 + "insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')",
65 + [sid, id, crypto.randomBytes(32).toString('hex')],
66 + );
67 + return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, secret, { issuer: 'lifemate', expiresIn: '15m' }) };
68 +}
69 +
70 +async function fixture() {
71 + const [child, parent, selected, outsider] = await Promise.all([user(), user(), user(), user()]);
72 + const familyId = crypto.randomUUID();
73 + await pool.query('insert into family_workspace(id,name,created_by) values($1,$2,$3)', [familyId, 'Synthetic Privacy Family', parent.id]);
74 + families.push(familyId);
75 + for (const [member, role] of [[child, 'teen_minor'], [parent, 'parent_guardian'], [selected, 'adult_member']]) {
76 + await pool.query('insert into family_membership(family_id,user_id,role) values($1,$2,$3)', [familyId, member.id, role]);
77 + }
78 + await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, child.id]);
79 + return { child, parent, selected, outsider, familyId };
80 +}
81 +
82 +async function plan(f, visibility, { kind = 'assignment', status = 'planned', minutes = null } = {}) {
83 + const row = await pool.query(
84 + `insert into plan_item(owner_user_id,family_id,kind,title,visibility,status,duration_minutes,due_at,completed_at)
85 + values($1,$2,$3,'Synthetic private title',$4,$5::plan_item_status,$6,now()-interval '1 day',case when $5::plan_item_status='completed' then now() end) returning id`,
86 + [f.child.id, f.familyId, kind, visibility, status, minutes],
87 + );
88 + return row.rows[0].id;
89 +}
90 +
91 +async function grant(f, itemId, viewer = f.selected) {
92 + await pool.query("insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [itemId, viewer.id, f.child.id]);
93 +}
94 +
95 +async function canView(viewer, itemId) {
96 + return (await pool.query('select can_view_plan_item($1,$2) as allowed', [viewer.id, itemId])).rows[0].allowed;
97 +}
98 +
99 +async function academic(viewer, student) {
100 + return (await pool.query('select can_view_student_academic($1,$2) as allowed', [viewer.id, student.id])).rows[0].allowed;
101 +}
102 +
103 +async function request(base, path, { method = 'GET', actor, body } = {}) {
104 + const response = await fetch(base + path, {
105 + method,
106 + headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) },
107 + body: body === undefined ? undefined : JSON.stringify(body),
108 + });
109 + const text = await response.text();
110 + return { status: response.status, body: text ? JSON.parse(text) : null };
111 +}
112 +
113 +test('privatizing a selected item revokes its grant and does not resurrect it when selected again', async () => {
114 + const f = await fixture();
115 + const item = await plan(f, 'selected_members');
116 + await grant(f, item);
117 + assert.equal(await canView(f.selected, item), true);
118 + await pool.query("update plan_item set visibility='private' where id=$1", [item]);
119 + assert.equal(await canView(f.selected, item), false);
120 + assert.equal((await pool.query('select 1 from sharing_grant where resource_id=$1', [item])).rowCount, 0);
121 + await pool.query("update plan_item set visibility='selected_members' where id=$1", [item]);
122 + assert.equal(await canView(f.selected, item), false);
123 + assert.equal(await canView(f.child, item), true);
124 +});
125 +
126 +for (const side of ['owner', 'viewer']) {
127 + test(`ending the selected item ${side}'s membership revokes the grant even after rejoining`, async () => {
128 + const f = await fixture();
129 + const item = await plan(f, 'selected_members');
130 + await grant(f, item);
131 + const member = side === 'owner' ? f.child : f.selected;
132 + await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, member.id]);
133 + assert.equal(await canView(f.selected, item), false);
134 + assert.equal((await pool.query('select 1 from sharing_grant where resource_id=$1', [item])).rowCount, 0);
135 + await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, member.id]);
136 + assert.equal(await canView(f.selected, item), false);
137 + });
138 +}
139 +
140 +test('family sharing requires both the item owner and viewer to remain active members', async () => {
141 + const f = await fixture();
142 + const item = await plan(f, 'family');
143 + assert.equal(await canView(f.parent, item), true);
144 + await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
145 + assert.equal(await canView(f.parent, item), false);
146 + assert.equal(await canView(f.child, item), true);
147 +});
148 +
149 +test('a direct selected grant cannot authorize someone outside the current item family', async () => {
150 + const f = await fixture();
151 + const item = await plan(f, 'selected_members');
152 + await grant(f, item, f.outsider);
153 + assert.equal(await canView(f.outsider, item), false);
154 +});
155 +
156 +for (const side of ['guardian', 'minor']) {
157 + test(`academic authorization ends when the ${side}'s current role changes`, async () => {
158 + const f = await fixture();
159 + assert.equal(await academic(f.parent, f.child), true);
160 + const member = side === 'guardian' ? f.parent : f.child;
161 + await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, member.id]);
162 + assert.equal(await academic(f.parent, f.child), false);
163 + assert.equal(await academic(f.child, f.child), true);
164 + });
165 +}
166 +
167 +test('private plan items remain owner-only for both guardians and outsiders', async () => {
168 + const f = await fixture();
169 + const item = await plan(f, 'private');
170 + assert.equal(await canView(f.child, item), true);
171 + assert.equal(await canView(f.parent, item), false);
172 + assert.equal(await canView(f.outsider, item), false);
173 +});
174 +
175 +test('sensitive wellbeing and cycle reads and writes are closed by default, including test mode', async () => {
176 + const f = await fixture();
177 + const paths = [
178 + ['GET', '/v1/wellbeing/checkins'],
179 + ['POST', '/v1/wellbeing/checkins', { mood: 3, energy: 3, stress: 3 }],
180 + ['GET', `/v1/families/${f.familyId}/children/${f.child.id}/wellbeing-summary`],
181 + ['POST', `/v1/families/${f.familyId}/children/${f.child.id}/family-guidance`, { question: 'Synthetic support question' }],
182 + ['GET', '/v1/me/menstrual-cycles'],
183 + ['POST', '/v1/me/menstrual-cycles', { startsOn: '2026-10-01' }],
184 + ['DELETE', `/v1/me/menstrual-cycles/${crypto.randomUUID()}`],
185 + ['POST', '/v1/ai/sessions', { kind: 'wellbeing' }],
186 + ];
187 + for (const [method, path, body] of paths) {
188 + const result = await request(defaultBase, path, { method, actor: f.parent, body });
189 + assert.equal(result.status, 503, `${method} ${path} must stay gated`);
190 + assert.equal(result.body.error, 'sensitive_features_disabled');
191 + }
192 + assert.equal((await pool.query('select 1 from wellbeing_checkin where owner_user_id=$1', [f.parent.id])).rowCount, 0);
193 + assert.equal((await pool.query('select 1 from menstrual_cycle_entry where owner_user_id=$1', [f.parent.id])).rowCount, 0);
194 +});
195 +
196 +test('every Phase 4/6 read and write requires a verified server session before gate or data access', async () => {
197 + const f = await fixture();
198 + const routes = [
199 + ['GET', '/v1/learning/goals'], ['POST', '/v1/learning/goals'], ['POST', '/v1/learning/checkins'],
200 + ['GET', '/v1/wellbeing/checkins'], ['POST', '/v1/wellbeing/checkins'],
201 + ['GET', `/v1/families/${f.familyId}/children/${f.child.id}/wellbeing-summary`],
202 + ['POST', `/v1/families/${f.familyId}/children/${f.child.id}/family-guidance`],
203 + ['POST', '/v1/ai/sessions'], ['POST', `/v1/ai/sessions/${crypto.randomUUID()}/messages`],
204 + ['POST', '/v1/ai/proposals'], ['PATCH', `/v1/ai/proposals/${crypto.randomUUID()}`],
205 + ['GET', '/v1/me/iran-profile'], ['PATCH', '/v1/me/iran-profile'], ['PUT', '/v1/me/education'],
206 + ['GET', '/v1/education/catalog'], ['GET', '/v1/calendar/iran'],
207 + ['GET', '/v1/me/notification-preferences'], ['PATCH', '/v1/me/notification-preferences'],
208 + ['GET', '/v1/me/menstrual-cycles'], ['POST', '/v1/me/menstrual-cycles'],
209 + ['DELETE', `/v1/me/menstrual-cycles/${crypto.randomUUID()}`],
210 + ];
211 + for (const [method, path] of routes) {
212 + assert.equal((await request(defaultBase, path, { method, body: method === 'GET' ? undefined : {} })).status, 401, path);
213 + }
214 +});
215 +
216 +test('explicit synthetic opt-in preserves owner-only cycle records', async () => {
217 + const f = await fixture();
218 + const written = await request(enabledBase, '/v1/me/menstrual-cycles', { method: 'POST', actor: f.child, body: { startsOn: '2026-10-01', notes: 'Synthetic private cycle' } });
219 + assert.equal(written.status, 201);
220 + const item = written.body.id;
221 + assert.equal((await request(enabledBase, '/v1/me/menstrual-cycles', { actor: f.parent })).body.entries.length, 0);
222 + assert.equal((await request(enabledBase, `/v1/me/menstrual-cycles/${item}`, { method: 'DELETE', actor: f.parent })).status, 204);
223 + assert.equal((await pool.query('select 1 from menstrual_cycle_entry where id=$1', [item])).rowCount, 1);
224 + assert.equal((await request(enabledBase, '/v1/me/menstrual-cycles', { actor: f.child })).body.entries[0].notes, 'Synthetic private cycle');
225 + assert.equal((await request(enabledBase, `/v1/me/menstrual-cycles/${item}`, { method: 'DELETE', actor: f.child })).status, 204);
226 +});
227 +
228 +test('Phase 4 guardian summaries reject a stale guardian role after synthetic opt-in', async () => {
229 + const f = await fixture();
230 + const path = `/v1/families/${f.familyId}/children/${f.child.id}/wellbeing-summary`;
231 + assert.equal((await request(enabledBase, path, { actor: f.parent })).status, 200);
232 + await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, f.parent.id]);
233 + assert.equal((await request(enabledBase, path, { actor: f.parent })).status, 403);
234 +});
235 +
236 +test('family guidance academic aggregates include only plan items visible to that guardian', async () => {
237 + const f = await fixture();
238 + await plan(f, 'private', { kind: 'study_session', status: 'completed', minutes: 90 });
239 + await plan(f, 'parent_guardian', { kind: 'study_session', status: 'completed', minutes: 15 });
240 + const result = await request(enabledBase, `/v1/families/${f.familyId}/children/${f.child.id}/family-guidance`, { method: 'POST', actor: f.parent, body: { question: 'Synthetic guidance' } });
241 + assert.equal(result.status, 200);
242 + assert.equal(result.body.summary.academic.completed_last_7_days, 1);
243 + assert.equal(result.body.summary.academic.study_minutes_last_7_days, 15);
244 +});
245 +
246 +test('configured AI credentials cannot trigger a provider request in this work package', async () => {
247 + const f = await fixture();
248 + let calls = 0;
249 + const provider = http.createServer((_req, res) => {
250 + calls += 1;
251 + res.setHeader('content-type', 'application/json');
252 + res.end(JSON.stringify({ choices: [{ message: { content: 'Synthetic provider reply' } }] }));
253 + });
254 + provider.listen(0, '127.0.0.1');
255 + await new Promise((resolve) => provider.once('listening', resolve));
256 + const previous = Object.fromEntries(['AI_API_KEY', 'AI_BASE_URL', 'AI_MODEL'].map((key) => [key, process.env[key]]));
257 + Object.assign(process.env, { AI_API_KEY: 'synthetic-disabled-key', AI_BASE_URL: `http://127.0.0.1:${provider.address().port}`, AI_MODEL: 'synthetic-disabled-model' });
258 + try {
259 + const session = await request(defaultBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'study' } });
260 + assert.equal(session.status, 201);
261 + const reply = await request(defaultBase, `/v1/ai/sessions/${session.body.id}/messages`, { method: 'POST', actor: f.child, body: { message: 'Synthetic math question' } });
262 + assert.equal(reply.status, 200);
263 + assert.equal(calls, 0);
264 + assert.equal(reply.body.providerMode, 'local_fallback');
265 + assert.notEqual(reply.body.body, 'Synthetic provider reply');
266 + } finally {
267 + for (const [key, value] of Object.entries(previous)) {
268 + if (value === undefined) delete process.env[key]; else process.env[key] = value;
269 + }
270 + await new Promise((resolve) => provider.close(resolve));
271 + }
272 +});
273 +
274 +test('an existing wellbeing guide cannot receive messages while sensitive features are disabled', async () => {
275 + const f = await fixture();
276 + const session = await request(enabledBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'wellbeing' } });
277 + assert.equal(session.status, 201);
278 + const reply = await request(defaultBase, `/v1/ai/sessions/${session.body.id}/messages`, { method: 'POST', actor: f.child, body: { message: 'Synthetic private reflection' } });
279 + assert.equal(reply.status, 503);
280 + assert.equal((await pool.query('select 1 from ai_guide_message where session_id=$1', [session.body.id])).rowCount, 0);
281 +});
282 +
283 +test('learning checkins cannot reference another owner\'s goal', async () => {
284 + const f = await fixture();
285 + const goal = await request(defaultBase, '/v1/learning/goals', { method: 'POST', actor: f.child, body: { title: 'Synthetic goal' } });
286 + assert.equal(goal.status, 201);
287 + assert.equal((await request(defaultBase, '/v1/learning/checkins', { method: 'POST', actor: f.outsider, body: { learningGoalId: goal.body.id, confidence: 3, difficulty: 3 } })).status, 403);
288 +});
289 +
290 +test('AI proposals cannot reference another owner\'s guide session', async () => {
291 + const f = await fixture();
292 + const session = await request(defaultBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'study' } });
293 + assert.equal(session.status, 201);
294 + assert.equal((await request(defaultBase, '/v1/ai/proposals', { method: 'POST', actor: f.outsider, body: { sessionId: session.body.id, title: 'Synthetic proposal', proposal: { steps: [] } } })).status, 403);
295 +});
296 +
297 +test('changing a selected item to another family revokes the previous grants', async () => {
298 + const f = await fixture();
299 + const other = await fixture();
300 + const item = await plan(f, 'selected_members');
301 + await grant(f, item);
302 + await pool.query('update plan_item set family_id=$2 where id=$1', [item, other.familyId]);
303 + assert.equal(await canView(f.selected, item), false);
304 + assert.equal((await pool.query('select 1 from sharing_grant where resource_id=$1', [item])).rowCount, 0);
305 +});
306 +
307 +test('production with no sensitive flag remains closed', async () => {
308 + const f = await fixture();
309 + const previous = process.env.NODE_ENV;
310 + process.env.NODE_ENV = 'production';
311 + try {
312 + const base = await serve({});
313 + const result = await request(base, '/v1/me/menstrual-cycles', { actor: f.child });
314 + assert.equal(result.status, 503);
315 + assert.equal(result.body.error, 'sensitive_features_disabled');
316 + } finally {
317 + if (previous === undefined) delete process.env.NODE_ENV; else process.env.NODE_ENV = previous;
318 + }
319 +});
320 +
321 +test('deleting and recreating a selected member cannot revive a previous grant', async () => {
322 + const f = await fixture();
323 + const item = await plan(f, 'selected_members');
324 + await grant(f, item);
325 + await pool.query('delete from family_membership where family_id=$1 and user_id=$2', [f.familyId, f.selected.id]);
326 + assert.equal(await canView(f.selected, item), false);
327 + await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'adult_member')", [f.familyId, f.selected.id]);
328 + assert.equal(await canView(f.selected, item), false);
329 +});
330 +
331 +test('learning goals cannot reference another student\'s subject', async () => {
332 + const f = await fixture();
333 + const context = await pool.query("insert into life_context(user_id,kind,title) values($1,'student','Synthetic class') returning id", [f.child.id]);
334 + const year = await pool.query("insert into academic_year(student_user_id,life_context_id,title,starts_on,ends_on) values($1,$2,'Synthetic year','2026-09-01','2027-06-01') returning id", [f.child.id, context.rows[0].id]);
335 + const term = await pool.query("insert into academic_term(academic_year_id,title,starts_on,ends_on) values($1,'Synthetic term','2026-09-01','2026-12-01') returning id", [year.rows[0].id]);
336 + const subject = await pool.query("insert into subject(student_user_id,academic_term_id,name) values($1,$2,'Synthetic math') returning id", [f.child.id, term.rows[0].id]);
337 + const result = await request(defaultBase, '/v1/learning/goals', { method: 'POST', actor: f.outsider, body: { title: 'Synthetic foreign goal', subjectId: subject.rows[0].id } });
338 + assert.equal(result.status, 403);
339 + assert.equal((await pool.query('select 1 from learning_goal where owner_user_id=$1', [f.outsider.id])).rowCount, 0);
340 +});
341 +
342 +test('wellbeing-linked proposals cannot be created or accepted while sensitive features are disabled', async () => {
343 + const f = await fixture();
344 + const session = await request(enabledBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'wellbeing' } });
345 + const body = { sessionId: session.body.id, title: 'Synthetic reflection proposal', proposal: { steps: [] } };
346 + assert.equal((await request(defaultBase, '/v1/ai/proposals', { method: 'POST', actor: f.child, body })).status, 503);
347 + const proposal = await request(enabledBase, '/v1/ai/proposals', { method: 'POST', actor: f.child, body });
348 + assert.equal(proposal.status, 201);
349 + assert.equal((await request(defaultBase, `/v1/ai/proposals/${proposal.body.id}`, { method: 'PATCH', actor: f.child, body: { status: 'accepted' } })).status, 503);
350 + assert.equal((await pool.query('select status from ai_plan_proposal where id=$1', [proposal.body.id])).rows[0].status, 'proposed');
351 +});
352 +
353 +test('study guidance does not create sensitive wellbeing events while the feature is disabled', async () => {
354 + const f = await fixture();
355 + const session = await request(defaultBase, '/v1/ai/sessions', { method: 'POST', actor: f.child, body: { kind: 'study' } });
356 + assert.equal(session.status, 201);
357 + const reply = await request(defaultBase, `/v1/ai/sessions/${session.body.id}/messages`, { method: 'POST', actor: f.child, body: { message: 'Synthetic safety regression: self-harm' } });
358 + assert.equal(reply.status, 200);
359 + assert.match(reply.body.body, /کمک فوری/);
360 + assert.equal((await pool.query('select 1 from wellbeing_safety_event where owner_user_id=$1', [f.child.id])).rowCount, 0);
361 +});
backend/tests/profile_category.test.js new
+187
@@ -0,0 +1,187 @@
1 +import test, { after } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import fs from 'node:fs/promises';
5 +import jwt from 'jsonwebtoken';
6 +import pg from 'pg';
7 +
8 +assert.ok(process.env.DATABASE_URL, 'Use a migrated synthetic PostgreSQL database');
9 +assert.ok(process.env.JWT_SECRET?.length >= 32, 'Use a synthetic JWT secret');
10 +const { app, pool } = await import('../src/server.js');
11 +const users = [];
12 +const families = [];
13 +let server = app.listen(0, '127.0.0.1');
14 +await new Promise((resolve) => server.once('listening', resolve));
15 +let base = `http://127.0.0.1:${server.address().port}`;
16 +
17 +after(async () => {
18 + await new Promise((resolve) => server.close(resolve));
19 + try {
20 + if (families.length) {
21 + await pool.query('delete from access_audit where family_id=any($1::uuid[])', [families]);
22 + await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
23 + }
24 + if (users.length) await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
25 + } finally { await pool.end(); }
26 +});
27 +
28 +async function user() {
29 + const id = crypto.randomUUID(), sid = crypto.randomUUID();
30 + await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `profile-test:${id}`, `profile-${id}@example.test`]);
31 + users.push(id);
32 + await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic Profile','adult_blue')", [id]);
33 + await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, crypto.randomBytes(32).toString('hex')]);
34 + return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: '15m' }) };
35 +}
36 +
37 +async function fixture() {
38 + const [child, parent, outsider] = await Promise.all([user(), user(), user()]);
39 + const familyId = crypto.randomUUID();
40 + await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic Profile Family',$2)", [familyId, parent.id]);
41 + families.push(familyId);
42 + await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor'),($1,$3,'parent_guardian')", [familyId, child.id, parent.id]);
43 + await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, child.id]);
44 + return { child, parent, outsider, familyId };
45 +}
46 +
47 +async function request(path, { method = 'GET', actor, body } = {}) {
48 + const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
49 + const text = await response.text();
50 + return { status: response.status, body: text && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(text) : text };
51 +}
52 +
53 +test('profile category has an explicit adult default and edits never change family roles or theme', async () => {
54 + const f = await fixture();
55 + const initial = await request('/v1/profile', { actor: f.child });
56 + assert.equal(initial.status, 200);
57 + assert.equal(initial.body.profile_category, 'adult');
58 + const updated = await request('/v1/profile', { method: 'PATCH', actor: f.parent, body: { displayName: 'ویرایش ساختگی', profileCategory: 'girl_minor' } });
59 + assert.equal(updated.status, 200);
60 + assert.equal(updated.body.profile_category, 'girl_minor');
61 + assert.equal(updated.body.theme_preference, 'adult_blue');
62 + assert.equal((await pool.query('select role from family_membership where family_id=$1 and user_id=$2', [f.familyId, f.parent.id])).rows[0].role, 'parent_guardian');
63 + const changedTheme = await request('/v1/profile', { method: 'PATCH', actor: f.parent, body: { themePreference: 'boy_blue' } });
64 + assert.equal(changedTheme.body.profile_category, 'girl_minor');
65 + assert.equal(changedTheme.body.display_name, 'ویرایش ساختگی');
66 + await pool.query("update family_membership set role='adult_member',ended_at=now() where family_id=$1 and user_id=$2", [f.familyId, f.parent.id]);
67 + const read = await request('/v1/profile', { actor: f.parent });
68 + assert.equal(read.body.profile_category, 'girl_minor');
69 + assert.equal(read.body.theme_preference, 'boy_blue');
70 +});
71 +
72 +test('profile validation returns 400 for invalid real calendar dates and categories without partial writes', async () => {
73 + const actor = await user();
74 + for (const birthDate of ['not-a-date', '2026-02-30', '2026-13-01', '2008-02-29T00:00:00Z', 20080229]) {
75 + const bad = await request('/v1/profile', { method: 'PATCH', actor, body: { displayName: 'Must Not Save', birthDate } });
76 + assert.equal(bad.status, 400, String(birthDate));
77 + assert.equal(bad.body.error, 'invalid_birth_date');
78 + }
79 + assert.equal((await request('/v1/profile', { method: 'PATCH', actor, body: { profileCategory: 'parent_guardian' } })).status, 400);
80 + assert.equal((await request('/v1/profile', { method: 'PATCH', actor, body: { displayName: '' } })).status, 400);
81 + assert.equal((await request('/v1/profile', { method: 'PATCH', actor, body: { themePreference: 'unknown' } })).status, 400);
82 + assert.equal((await request('/v1/profile', { actor })).body.display_name, 'Synthetic Profile');
83 + const valid = await request('/v1/profile', { method: 'PATCH', actor, body: { birthDate: '2008-02-29', profileCategory: 'boy_minor', themePreference: 'custom' } });
84 + assert.equal(valid.status, 200);
85 + const saved = (await pool.query('select birth_date::text,profile_category,theme_preference from profile where user_id=$1', [actor.id])).rows[0];
86 + assert.deepEqual(saved, { birth_date: '2008-02-29', profile_category: 'boy_minor', theme_preference: 'custom' });
87 +});
88 +
89 +test('both profile date aliases reject invalid dates and retain the previous calendar day', async () => {
90 + const actor = await user();
91 + await pool.query("update profile set birth_date='2008-02-29' where user_id=$1", [actor.id]);
92 + for (const path of ['/v1/profile', '/v1/me/iran-profile']) {
93 + for (const birthDate of ['2026-02-30', 'invalid-private-birthday', '2026-13-01']) {
94 + const result = await request(path, { method: 'PATCH', actor, body: { birthDate } });
95 + assert.equal(result.status, 400, path);
96 + assert.equal(result.body.error, 'invalid_birth_date');
97 + }
98 + }
99 + assert.equal((await pool.query('select birth_date::text from profile where user_id=$1', [actor.id])).rows[0].birth_date, '2008-02-29');
100 +});
101 +
102 +test('profile and learning CRUD reject missing sessions and cannot target another profile', async () => {
103 + const f = await fixture();
104 + const id = crypto.randomUUID();
105 + for (const [method, path] of [['GET', '/v1/profile'], ['PATCH', '/v1/profile'], ['GET', '/v1/learning/goals'], ['POST', '/v1/learning/goals'], ['GET', `/v1/learning/goals/${id}`], ['PATCH', `/v1/learning/goals/${id}`], ['DELETE', `/v1/learning/goals/${id}`]]) {
106 + assert.equal((await request(path, { method, body: method === 'GET' ? undefined : {} })).status, 401, path);
107 + }
108 + const forged = await request('/v1/profile', { method: 'PATCH', actor: f.child, body: { userId: f.parent.id, displayName: 'Owned Change', profileCategory: 'boy_minor' } });
109 + assert.equal(forged.status, 200);
110 + assert.equal((await request('/v1/profile', { actor: f.parent })).body.display_name, 'Synthetic Profile');
111 + assert.equal((await request('/v1/profile', { actor: f.child })).body.display_name, 'Owned Change');
112 +});
113 +
114 +test('learning goals create, read, edit and safely archive under the same owner and stable ID', async () => {
115 + const f = await fixture();
116 + const created = await request('/v1/learning/goals', { method: 'POST', actor: f.child, body: { title: 'هدف ساختگی', target: 'Private synthetic target' } });
117 + assert.equal(created.status, 201);
118 + const path = `/v1/learning/goals/${created.body.id}`;
119 + const read = await request(path, { actor: f.child });
120 + assert.equal(read.status, 200);
121 + assert.equal(read.body.target, 'Private synthetic target');
122 + for (const viewer of [f.parent, f.outsider]) {
123 + assert.equal((await request(path, { actor: viewer })).status, 404);
124 + assert.equal((await request(path, { method: 'PATCH', actor: viewer, body: { title: 'Forbidden' } })).status, 404);
125 + assert.equal((await request(path, { method: 'DELETE', actor: viewer })).status, 404);
126 + assert.equal((await request('/v1/learning/goals', { actor: viewer })).body.items.length, 0);
127 + }
128 + const checkin = await request('/v1/learning/checkins', { method: 'POST', actor: f.child, body: { learningGoalId: created.body.id, confidence: 3, difficulty: 3, note: 'Private synthetic note' } });
129 + assert.equal(checkin.status, 201);
130 + const edited = await request(path, { method: 'PATCH', actor: f.child, body: { title: 'ویرایش هدف', target: null, status: 'completed' } });
131 + assert.equal(edited.status, 200);
132 + assert.equal(edited.body.id, created.body.id);
133 + assert.equal(edited.body.title, 'ویرایش هدف');
134 + assert.equal(edited.body.target, null);
135 + await new Promise((resolve) => server.close(resolve));
136 + server = app.listen(0, '127.0.0.1');
137 + await new Promise((resolve) => server.once('listening', resolve));
138 + base = `http://127.0.0.1:${server.address().port}`;
139 + assert.equal((await request(path, { actor: f.child })).body.status, 'completed');
140 + for (let attempt = 0; attempt < 2; attempt++) assert.equal((await request(path, { method: 'DELETE', actor: f.child })).status, 204);
141 + assert.equal((await request('/v1/learning/goals', { actor: f.child })).body.items.length, 0);
142 + assert.equal((await request(path, { actor: f.child })).body.status, 'archived');
143 + assert.equal((await request(path, { method: 'PATCH', actor: f.child, body: { status: 'active' } })).status, 409);
144 + const retained = (await pool.query('select learning_goal_id,note from learning_checkin where id=$1', [checkin.body.id])).rows[0];
145 + assert.deepEqual(retained, { learning_goal_id: created.body.id, note: 'Private synthetic note' });
146 +});
147 +
148 +test('learning goal edits validate ownership of subjects, IDs and allowed statuses', async () => {
149 + const f = await fixture();
150 + const invalidCreate = await request('/v1/learning/goals', { method: 'POST', actor: f.child, body: { title: 'Synthetic goal', subjectId: 'not-a-uuid' } });
151 + assert.equal(invalidCreate.status, 400);
152 + assert.equal(invalidCreate.body.error, 'invalid_subject_id');
153 + const created = await request('/v1/learning/goals', { method: 'POST', actor: f.child, body: { title: 'Synthetic goal' } });
154 + const path = `/v1/learning/goals/${created.body.id}`;
155 + const context = await pool.query("insert into life_context(user_id,kind,title) values($1,'student','Synthetic class') returning id", [f.outsider.id]);
156 + const year = await pool.query("insert into academic_year(student_user_id,life_context_id,title,starts_on,ends_on) values($1,$2,'Synthetic year','2026-09-01','2027-06-01') returning id", [f.outsider.id, context.rows[0].id]);
157 + const term = await pool.query("insert into academic_term(academic_year_id,title,starts_on,ends_on) values($1,'Synthetic term','2026-09-01','2026-12-01') returning id", [year.rows[0].id]);
158 + const subject = await pool.query("insert into subject(student_user_id,academic_term_id,name) values($1,$2,'Synthetic math') returning id", [f.outsider.id, term.rows[0].id]);
159 + assert.equal((await request(path, { method: 'PATCH', actor: f.child, body: { subjectId: subject.rows[0].id } })).status, 403);
160 + assert.equal((await request(path, { method: 'PATCH', actor: f.child, body: { status: 'achieved' } })).status, 400);
161 + assert.equal((await request(path, { method: 'PATCH', actor: f.child, body: { title: '' } })).status, 400);
162 + assert.equal((await request('/v1/learning/goals/not-a-uuid', { method: 'PATCH', actor: f.child, body: { title: 'Valid' } })).status, 400);
163 + assert.equal((await request(path, { actor: f.child })).body.title, 'Synthetic goal');
164 +});
165 +
166 +test('profile migration derives legacy categories from themes only and new records default to adult', async () => {
167 + // A real PostgreSQL session with a temporary legacy table exercises the exact
168 + // migration without changing the already-migrated shared test schema.
169 + const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
170 + await client.connect();
171 + try {
172 + await client.query('create temporary table profile(user_id uuid primary key,theme_preference text)');
173 + await client.query('create temporary table family_membership(user_id uuid,role text)');
174 + const legacy = [['girl_pink', 'girl_minor', 'adult_member'], ['boy_blue', 'boy_minor', 'parent_guardian'], ['adult_blue', 'adult', 'teen_minor'], ['custom', 'adult', 'teen_minor'], [null, 'adult', 'parent_guardian']];
175 + for (const [theme, , role] of legacy) {
176 + const id = crypto.randomUUID();
177 + await client.query('insert into profile(user_id,theme_preference) values($1,$2)', [id, theme]);
178 + await client.query('insert into family_membership(user_id,role) values($1,$2)', [id, role]);
179 + }
180 + await client.query(await fs.readFile(new URL('../migrations/0011_profile_category.sql', import.meta.url), 'utf8'));
181 + const rows = await client.query('select theme_preference,profile_category from profile');
182 + for (const [theme, expected] of legacy) assert.equal(rows.rows.find((row) => row.theme_preference === theme).profile_category, expected);
183 + const created = await client.query("insert into profile(user_id,theme_preference) values($1,'girl_pink') returning profile_category", [crypto.randomUUID()]);
184 + assert.equal(created.rows[0].profile_category, 'adult');
185 + await assert.rejects(client.query("insert into profile(user_id,profile_category) values($1,'parent_guardian')", [crypto.randomUUID()]), (error) => error.code === '23514');
186 + } finally { await client.end(); }
187 +});
backend/tests/proxy_rate_limit.test.js new
+46
@@ -0,0 +1,46 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import express from 'express';
4 +import { once } from 'node:events';
5 +import { configureTrustedProxy, rateLimit } from '../src/operations.js';
6 +
7 +async function serve(trusted, run) {
8 + const app = express();
9 + configureTrustedProxy(app, trusted);
10 + app.use(rateLimit);
11 + app.get('/v1/auth/proxy-test', (req, res) => res.json({ ip: req.ip }));
12 + const server = app.listen(0, '127.0.0.1');
13 + await once(server, 'listening');
14 + try { await run(`http://127.0.0.1:${server.address().port}/v1/auth/proxy-test`); }
15 + finally { await new Promise(resolve => server.close(resolve)); }
16 +}
17 +
18 +test('untrusted clients cannot forge forwarded addresses', async () => {
19 + await serve('', async url => {
20 + const response = await fetch(url, { headers: {'x-forwarded-for': '192.0.2.1'} });
21 + assert.equal((await response.json()).ip, '127.0.0.1');
22 + });
23 +});
24 +
25 +test('trusted single gateway separates client rate buckets and ignores extra left hops', async () => {
26 + const previous = [process.env.NODE_ENV, process.env.RATE_LIMIT_AUTH_MAX];
27 + process.env.NODE_ENV = 'production';
28 + process.env.RATE_LIMIT_AUTH_MAX = '2';
29 + try {
30 + await serve('127.0.0.1/32', async url => {
31 + const first = {'x-forwarded-for': '192.0.2.100, 192.0.2.2'};
32 + assert.equal((await (await fetch(url, {headers: first})).json()).ip, '192.0.2.2');
33 + assert.equal((await fetch(url, {headers: first})).status, 200);
34 + assert.equal((await fetch(url, {headers: first})).status, 429);
35 + assert.equal((await fetch(url, {headers: {'x-forwarded-for': '192.0.2.3'}})).status, 200);
36 + });
37 + } finally {
38 + for (const [index, key] of ['NODE_ENV', 'RATE_LIMIT_AUTH_MAX'].entries()) {
39 + if (previous[index] === undefined) delete process.env[key]; else process.env[key] = previous[index];
40 + }
41 + }
42 +});
43 +
44 +test('blank defaults distrust proxy and invalid broad wildcard fails closed', () => {
45 + assert.throws(() => configureTrustedProxy(express(), '*'), /Invalid trusted proxy/);
46 +});
backend/tests/request_safety.test.js
+1
@@ -32,6 +32,7 @@ before(async () => {
32 ...process.env,
33 PORT: String(port),
34 NODE_ENV: 'production',
35 + ENABLE_SENSITIVE_FEATURES: 'true', // Explicit synthetic cycle/error fixtures only.
36 CORS_ORIGINS: allowedOrigin,
37 RATE_LIMIT_AUTH_MAX: '2000',
38 RATE_LIMIT_GENERAL_MAX: '2000',
backend/tests/study_sessions.test.js new
+333
@@ -0,0 +1,333 @@
1 +import test, { after } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import express from 'express';
5 +import jwt from 'jsonwebtoken';
6 +import pg from 'pg';
7 +import { createSessionAuth } from '../src/session_auth.js';
8 +import { createPhase3Router } from '../src/phase3.js';
9 +
10 +// A missing router must fail the HTTP acceptance assertion, never skip a gate.
11 +const studyModule = await import('../src/study_sessions.js').catch((error) => {
12 + if (error.code === 'ERR_MODULE_NOT_FOUND') return null;
13 + throw error;
14 +});
15 +if (!process.env.DATABASE_URL) throw new Error('study tests require a synthetic PostgreSQL DATABASE_URL');
16 +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
17 +const jwtSecret = 'synthetic-study-test-secret-32-characters';
18 +const auth = createSessionAuth({ pool, jwtSecret });
19 +const app = express();
20 +app.use(express.json({ limit: '64kb' }));
21 +app.use('/v1', createPhase3Router({ pool, auth }));
22 +if (studyModule) app.use('/v1', studyModule.createStudySessionsRouter({ pool, auth }));
23 +app.use((error, _req, res, _next) => {
24 + console.error(error);
25 + res.status(500).json({ error: 'internal_error' });
26 +});
27 +let server = app.listen(0);
28 +let base = `http://127.0.0.1:${server.address().port}`;
29 +after(async () => {
30 + await new Promise((resolve) => server.close(resolve));
31 + await pool.end();
32 +});
33 +
34 +async function request(path, { method = 'GET', body, user } = {}) {
35 + const response = await fetch(base + path, {
36 + method,
37 + headers: { 'content-type': 'application/json', ...(user ? { authorization: `Bearer ${user.token}` } : {}) },
38 + body: body === undefined ? undefined : JSON.stringify(body),
39 + });
40 + const raw = await response.text();
41 + return { status: response.status, body: raw && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(raw) : raw || null };
42 +}
43 +async function user() {
44 + const id = crypto.randomUUID();
45 + const sid = crypto.randomUUID();
46 + await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())',
47 + [id, `study-test:${id}`, `${id}@example.test`]);
48 + await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic study tester','adult_blue')", [id]);
49 + await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, crypto.randomUUID()]);
50 + return { id, sid, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: '15m' }) };
51 +}
52 +async function fixture() {
53 + const child = await user();
54 + const mother = await user();
55 + const father = await user();
56 + const outsider = await user();
57 + const familyId = crypto.randomUUID();
58 + await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic study family',$2)", [familyId, mother.id]);
59 + for (const [u, role] of [[child, 'teen_minor'], [mother, 'parent_guardian'], [father, 'parent_guardian']]) {
60 + await pool.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4)', [familyId, u.id, role, u === mother]);
61 + }
62 + for (const u of [mother, father]) {
63 + await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, u.id, child.id]);
64 + }
65 + const task = await request('/v1/plan-items', { method: 'POST', user: child, body: {
66 + kind: 'assignment', title: 'تمرین ریاضی آزمایشی', notes: 'PRIVATE-NOTE-DO-NOT-REPORT', familyId,
67 + visibility: 'parent_guardian', durationMinutes: 30, dueAt: new Date(Date.now() + 86400000).toISOString(),
68 + } });
69 + assert.equal(task.status, 201);
70 + return { child, mother, father, outsider, familyId, task: task.body };
71 +}
72 +const iso = (ms) => new Date(ms).toISOString();
73 +const mutationId = () => crypto.randomUUID();
74 +async function createSession(f, overrides = {}) {
75 + return request('/v1/study/sessions', { method: 'POST', user: f.child, body: {
76 + id: crypto.randomUUID(), mutationId: mutationId(), planItemId: f.task.id,
77 + source: 'timer', startedAt: iso(Date.now() - 3600000), ...overrides,
78 + } });
79 +}
80 +async function event(f, session, action, occurredAt, overrides = {}) {
81 + return request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', user: f.child, body: {
82 + mutationId: mutationId(), expectedVersion: session.version, action, occurredAt, ...overrides,
83 + } });
84 +}
85 +const reportPath = (f) => `/v1/families/${f.familyId}/children/${f.child.id}/learning-report`;
86 +
87 +test('real HTTP and independent PostgreSQL prove eight-step homework/study family slice across server restart', async () => {
88 + const f = await fixture();
89 + const taskRow = await pool.query('select owner_user_id,title from plan_item where id=$1', [f.task.id]);
90 + assert.equal(taskRow.rows[0].owner_user_id, f.child.id);
91 + const motherBefore = await request(reportPath(f), { user: f.mother });
92 + assert.equal(motherBefore.status, 200);
93 + assert.ok(motherBefore.body.items.some((x) => x.id === f.task.id));
94 + const startAt = Date.now() - 3600000;
95 + const created = await createSession(f, { startedAt: iso(startAt) });
96 + assert.equal(created.status, 201);
97 + const stopped = await event(f, created.body.session, 'stop', iso(startAt + 20 * 60000));
98 + assert.equal(stopped.status, 200);
99 + assert.equal(stopped.body.session.recordedDurationSeconds, 1200);
100 + assert.equal(stopped.body.session.isEvidenceOfStudy, false);
101 + const report = await request(reportPath(f), { user: f.mother });
102 + assert.equal(report.status, 200);
103 + assert.equal(report.body.metrics.recordedDurationSeconds, 1200);
104 + assert.equal(report.body.metrics.plannedDurationSeconds, 1800);
105 + assert.equal(report.body.recordingDisclaimerKey, 'recorded_time_is_not_proof_of_study');
106 + assert.ok(!JSON.stringify(report.body).includes('PRIVATE-NOTE-DO-NOT-REPORT'));
107 + const complete = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, body: {
108 + mutationId: mutationId(), expectedVersion: stopped.body.activity.version, state: 'completed',
109 + occurredAt: iso(startAt + 21 * 60000), source: 'self_reported',
110 + } });
111 + assert.equal(complete.status, 200);
112 + const father = await request(reportPath(f), { user: f.father });
113 + assert.equal(father.body.items.find((x) => x.id === f.task.id).status, 'completed');
114 + assert.equal(father.body.items.find((x) => x.id === f.task.id).activityState, 'completed');
115 + assert.ok(father.body.asOf && father.body.lastSyncAt && father.body.sourceVersion);
116 + await new Promise((resolve) => server.close(resolve));
117 + server = app.listen(0);
118 + base = `http://127.0.0.1:${server.address().port}`;
119 + for (const u of [f.child, f.mother, f.father]) {
120 + const persisted = u === f.child
121 + ? await request(`/v1/study/sessions/${created.body.session.id}`, { user: u })
122 + : await request(reportPath(f), { user: u });
123 + assert.equal(persisted.status, 200);
124 + }
125 + const rows = await pool.query('select status,recorded_duration_seconds from study_session where id=$1', [created.body.session.id]);
126 + assert.deepEqual(rows.rows[0], { status: 'completed', recorded_duration_seconds: 1200 });
127 +});
128 +
129 +test('pause/resume survives API restart and duration excludes pauses; duplicate offline retries and conflicts never add time twice', async () => {
130 + const f = await fixture();
131 + const t = Date.now() - 3600000;
132 + const createBody = { id: crypto.randomUUID(), mutationId: mutationId(), planItemId: f.task.id, source: 'timer', startedAt: iso(t) };
133 + const created = await request('/v1/study/sessions', { method: 'POST', user: f.child, body: createBody });
134 + assert.equal(created.status, 201);
135 + const replay = await request('/v1/study/sessions', { method: 'POST', user: f.child, body: createBody });
136 + assert.equal(replay.body.acknowledgement.status, 'already_applied');
137 + const changedDuplicate = await request('/v1/study/sessions', { method: 'POST', user: f.child, body: { ...createBody, startedAt: iso(t - 1) } });
138 + assert.equal(changedDuplicate.status, 409);
139 + const paused = await event(f, created.body.session, 'pause', iso(t + 10 * 60000));
140 + assert.equal(paused.status, 200);
141 + assert.equal(paused.body.session.status, 'paused');
142 + const stale = await event(f, created.body.session, 'resume', iso(t + 20 * 60000));
143 + assert.equal(stale.status, 409);
144 + assert.equal(stale.body.error, 'version_conflict');
145 + await new Promise((resolve) => server.close(resolve));
146 + server = app.listen(0);
147 + base = `http://127.0.0.1:${server.address().port}`;
148 + const persisted = await request(`/v1/study/sessions/${created.body.session.id}`, { user: f.child });
149 + assert.equal(persisted.body.session.status, 'paused');
150 + const resumed = await event(f, persisted.body.session, 'resume', iso(t + 20 * 60000));
151 + assert.equal(resumed.status, 200);
152 + const stopBody = { mutationId: mutationId(), expectedVersion: resumed.body.session.version, action: 'stop', occurredAt: iso(t + 35 * 60000) };
153 + const stopped = await request(`/v1/study/sessions/${resumed.body.session.id}/events`, { method: 'POST', user: f.child, body: stopBody });
154 + assert.equal(stopped.body.session.recordedDurationSeconds, 1500);
155 + const stoppedReplay = await request(`/v1/study/sessions/${resumed.body.session.id}/events`, { method: 'POST', user: f.child, body: stopBody });
156 + assert.equal(stoppedReplay.body.acknowledgement.status, 'already_applied');
157 + assert.equal(stoppedReplay.body.session.version, stopped.body.session.version);
158 + const rows = await pool.query('select count(*)::int n,sum(extract(epoch from ends_at-starts_at))::int duration from study_interval where session_id=$1', [created.body.session.id]);
159 + assert.deepEqual(rows.rows[0], { n: 2, duration: 1500 });
160 + const all = await request('/v1/study/sessions', { user: f.child });
161 + assert.equal(all.body.sessions.length, 1);
162 +});
163 +
164 +test('concurrent/overlapping study sessions are rejected and interval boundaries do not double count', async () => {
165 + const f = await fixture();
166 + const t = Date.now() - 3600000;
167 + const [a, b] = await Promise.all([createSession(f, { startedAt: iso(t) }), createSession(f, { startedAt: iso(t + 1000) })]);
168 + assert.deepEqual([a.status, b.status].sort(), [201, 409]);
169 + const running = (a.status === 201 ? a : b).body.session;
170 + const stopped = await event(f, running, 'stop', iso(t + 600000));
171 + assert.equal(stopped.status, 200);
172 + const overlap = await createSession(f, { source: 'self_reported', startedAt: iso(t + 300000), endedAt: iso(t + 900000) });
173 + assert.equal(overlap.status, 409);
174 + assert.equal(overlap.body.error, 'study_time_overlap');
175 + const boundary = await createSession(f, { source: 'self_reported', startedAt: iso(t + 600000), endedAt: iso(t + 900000) });
176 + assert.equal(boundary.status, 201);
177 + assert.equal(boundary.body.session.recordedDurationSeconds, 300);
178 + assert.equal(boundary.body.session.source, 'self_reported');
179 +});
180 +
181 +test('reports enforce current guardian roles, both memberships, family state, relations and sharing on every read', async () => {
182 + const f = await fixture();
183 + assert.equal((await request(reportPath(f))).status, 401);
184 + assert.equal((await request(reportPath(f), { user: f.outsider })).status, 403);
185 + const s = await createSession(f);
186 + assert.equal(s.status, 201);
187 + for (const u of [f.mother, f.father, f.outsider]) {
188 + assert.equal((await request(`/v1/study/sessions/${s.body.session.id}`, { user: u })).status, 404);
189 + assert.equal((await request(`/v1/study/sessions/${s.body.session.id}/events`, { method: 'POST', user: u,
190 + body: { mutationId: mutationId(), expectedVersion: 1, action: 'stop', occurredAt: iso(Date.now()) } })).status, 404);
191 + }
192 + await pool.query("update plan_item set visibility='private' where id=$1", [f.task.id]);
193 + const privateReport = await request(reportPath(f), { user: f.mother });
194 + assert.equal(privateReport.status, 200);
195 + assert.equal(privateReport.body.items.length, 0);
196 + assert.equal(privateReport.body.metrics.recordedDurationSeconds, 0);
197 + await pool.query("update plan_item set visibility='selected_members' where id=$1", [f.task.id]);
198 + await pool.query("insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [f.task.id, f.mother.id, f.child.id]);
199 + assert.equal((await request(reportPath(f), { user: f.mother })).body.items.length, 1);
200 + assert.equal((await request(reportPath(f), { user: f.father })).body.items.length, 0);
201 + await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, f.mother.id]);
202 + assert.equal((await request(reportPath(f), { user: f.mother })).status, 403);
203 + await pool.query("update family_membership set role='parent_guardian',ended_at=now() where family_id=$1 and user_id=$2", [f.familyId, f.mother.id]);
204 + assert.equal((await request(reportPath(f), { user: f.mother })).status, 403);
205 + await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, f.mother.id]);
206 + await pool.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]);
207 + assert.equal((await request(reportPath(f), { user: f.mother })).status, 403);
208 + await pool.query('update guardian_relationship set active=true where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]);
209 + await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
210 + assert.equal((await request(reportPath(f), { user: f.mother })).status, 403);
211 + await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, f.child.id]);
212 + await pool.query('update family_workspace set archived_at=now() where id=$1', [f.familyId]);
213 + assert.equal((await request(reportPath(f), { user: f.mother })).status, 403);
214 +});
215 +
216 +test('activity completion remains self-reported until explicit authorized guardian confirmation; sessions archive safely', async () => {
217 + const f = await fixture();
218 + const created = await createSession(f, { source: 'self_reported', startedAt: iso(Date.now() - 600000), endedAt: iso(Date.now() - 300000) });
219 + assert.equal(created.status, 201);
220 + const complete = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child,
221 + body: { mutationId: mutationId(), expectedVersion: created.body.activity.version, state: 'completed', source: 'self_reported', occurredAt: iso(Date.now() - 200000) } });
222 + assert.equal(complete.status, 200);
223 + assert.equal(complete.body.activity.state, 'completed');
224 + const body = { mutationId: mutationId(), expectedVersion: complete.body.activity.version, state: 'verified', source: 'guardian_confirmation', occurredAt: iso(Date.now() - 100000), confirmation: 'I confirm reviewing this homework.' };
225 + assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, body })).status, 403);
226 + assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.outsider, body })).status, 403);
227 + assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body: { ...body, confirmation: '' } })).status, 400);
228 + const verified = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body });
229 + assert.equal(verified.status, 200);
230 + assert.equal(verified.body.activity.state, 'verified');
231 + assert.equal(verified.body.activity.source, 'guardian_confirmation');
232 + assert.equal(verified.body.activity.confirmedBy, f.mother.id);
233 + const archived = await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'DELETE', user: f.child,
234 + body: { mutationId: mutationId(), expectedVersion: created.body.session.version } });
235 + assert.equal(archived.status, 200);
236 + assert.equal(archived.body.session.status, 'archived');
237 + assert.equal((await request('/v1/study/sessions', { user: f.child })).body.sessions.length, 0);
238 + assert.equal((await request(reportPath(f), { user: f.mother })).body.metrics.recordedDurationSeconds, 0);
239 +});
240 +
241 +test('malformed IDs, forged owner, future/reversed timestamps, unknown source and client claimed duration fail closed', async () => {
242 + const f = await fixture();
243 + assert.equal((await createSession(f, { id: 'broken' })).status, 400);
244 + assert.equal((await createSession(f, { childId: f.outsider.id })).status, 403);
245 + assert.equal((await createSession(f, { startedAt: iso(Date.now() + 3600000) })).status, 400);
246 + assert.equal((await createSession(f, { source: 'proof_of_study' })).status, 400);
247 + assert.equal((await createSession(f, { source: 'self_reported', startedAt: iso(Date.now() - 60000), endedAt: iso(Date.now() - 120000) })).status, 400);
248 + assert.equal((await createSession(f, { recordedDurationSeconds: 999999 })).status, 400);
249 + assert.equal((await request('/v1/study/sessions/not-a-uuid', { user: f.child })).status, 400);
250 + assert.equal((await request(`${reportPath(f)}?from=broken`, { user: f.mother })).status, 400);
251 + const expired = { ...f.child, token: jwt.sign({ sub: f.child.id, sid: f.child.sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: -1 }) };
252 + assert.equal((await request('/v1/study/sessions', { user: expired })).status, 401);
253 +});
254 +
255 +test('guardian verification retries recheck current permission instead of replaying a revoked grant', async () => {
256 + const f = await fixture();
257 + const body = { mutationId: mutationId(), expectedVersion: 0, state: 'completed', source: 'self_reported', occurredAt: iso(Date.now() - 10000) };
258 + const completed = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, body });
259 + assert.equal(completed.status, 200);
260 + const confirmBody = { mutationId: mutationId(), expectedVersion: completed.body.activity.version, state: 'verified', source: 'guardian_confirmation', occurredAt: iso(Date.now()), confirmation: 'Synthetic reviewed homework.' };
261 + const confirmed = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body: confirmBody });
262 + assert.equal(confirmed.status, 200);
263 + await pool.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]);
264 + assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body: confirmBody })).status, 403);
265 +});
266 +
267 +test('report clips intervals at its boundaries and Tehran midnight and excludes outside-range time', async () => {
268 + const f = await fixture();
269 + const day = new Date(Date.now() - 2 * 86400000).toISOString().slice(0, 10);
270 + const t = new Date(`${day}T20:25:00.000Z`).getTime(); // 23:55 in Tehran
271 + const created = await createSession(f, { source: 'self_reported', startedAt: iso(t), endedAt: iso(t + 20 * 60000) });
272 + assert.equal(created.status, 201);
273 + const report = await request(`${reportPath(f)}?from=${encodeURIComponent(iso(t + 60000))}&to=${encodeURIComponent(iso(t + 16 * 60000))}`, { user: f.mother });
274 + assert.equal(report.status, 200);
275 + assert.equal(report.body.metrics.recordedDurationSeconds, 900);
276 + assert.deepEqual(report.body.daily.map((x) => x.recordedDurationSeconds), [240, 660]);
277 + assert.equal(report.body.daily.reduce((total, x) => total + x.recordedDurationSeconds, 0), 900);
278 +});
279 +
280 +test('owner can correct a self-reported session with version checks and overlap validation; parent cannot edit it', async () => {
281 + const f = await fixture();
282 + const t = Date.now() - 3600000;
283 + const created = await createSession(f, { source: 'self_reported', startedAt: iso(t), endedAt: iso(t + 600000) });
284 + assert.equal(created.status, 201);
285 + const body = { mutationId: mutationId(), expectedVersion: 1, startedAt: iso(t + 1000), endedAt: iso(t + 1201000) };
286 + assert.equal((await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'PATCH', user: f.mother, body })).status, 404);
287 + const corrected = await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'PATCH', user: f.child, body });
288 + assert.equal(corrected.status, 200);
289 + assert.equal(corrected.body.session.recordedDurationSeconds, 1200);
290 + assert.equal(corrected.body.session.version, 2);
291 + const stale = await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'PATCH', user: f.child, body: { ...body, mutationId: mutationId() } });
292 + assert.equal(stale.status, 409);
293 + const other = await createSession(f, { source: 'self_reported', startedAt: iso(t + 1800000), endedAt: iso(t + 2100000) });
294 + assert.equal(other.status, 201);
295 + const overlap = await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'PATCH', user: f.child,
296 + body: { ...body, mutationId: mutationId(), expectedVersion: 2, endedAt: iso(t + 1900000) } });
297 + assert.equal(overlap.status, 409);
298 + assert.equal(overlap.body.error, 'study_time_overlap');
299 + assert.equal((await request(`/v1/study/sessions/${created.body.session.id}`, { user: f.child })).body.session.recordedDurationSeconds, 1200);
300 +});
301 +
302 +test('owner and permitted guardian can read activity history but confirmation text and private records remain hidden', async () => {
303 + const f = await fixture();
304 + const completed = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, body: {
305 + mutationId: mutationId(), expectedVersion: 0, state: 'completed', source: 'self_reported', occurredAt: iso(Date.now() - 1000),
306 + } });
307 + assert.equal(completed.status, 200);
308 + const confirmed = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body: {
309 + mutationId: mutationId(), expectedVersion: completed.body.activity.version, state: 'verified', source: 'guardian_confirmation', occurredAt: iso(Date.now()), confirmation: 'PRIVATE-CONFIRMATION-CONTENT',
310 + } });
311 + assert.equal(confirmed.status, 200);
312 + const history = await request(`/v1/plan-items/${f.task.id}/activity-state`, { user: f.father });
313 + assert.equal(history.status, 200);
314 + assert.deepEqual(history.body.history.map((x) => x.state), ['completed', 'verified']);
315 + assert.equal(history.body.activity.state, 'verified');
316 + assert.ok(!JSON.stringify(history.body).includes('PRIVATE-CONFIRMATION-CONTENT'));
317 + assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { user: f.outsider })).status, 403);
318 + await pool.query("update plan_item set visibility='private' where id=$1", [f.task.id]);
319 + assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { user: f.father })).status, 403);
320 + assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { user: f.child })).status, 200);
321 +});
322 +
323 +test('shared report preserves exact planned seconds rather than rounding through the legacy minutes column', async () => {
324 + const f = await fixture();
325 + const precise = await request('/v1/plan-items', { method: 'POST', user: f.child, body: {
326 + kind: 'assignment', title: 'زمان دقیق آزمایشی', familyId: f.familyId, visibility: 'parent_guardian', plannedDurationSeconds: 95,
327 + } });
328 + assert.equal(precise.status, 201);
329 + const report = await request(reportPath(f), { user: f.mother });
330 + assert.equal(report.status, 200);
331 + assert.equal(report.body.items.find((x) => x.id === precise.body.id).plannedDurationSeconds, 95);
332 + assert.equal(report.body.metrics.plannedDurationSeconds, 1895);
333 +});