diff --git a/local/README.md b/local/README.md index 7dbd489..84e04ca 100644 --- a/local/README.md +++ b/local/README.md @@ -25,7 +25,7 @@ Then check it: local/smoke.sh ``` -It prints `smoke: OK` when admin login, a service-counter read and a public mobile-api call all succeed. +It prints `smoke: OK` when admin login, `/api/admin/me`, the users list, a service-counter read and a public mobile-api call all succeed. | What | Where | |---|---| @@ -34,6 +34,23 @@ It prints `smoke: OK` when admin login, a service-counter read and a public mobi | MySQL | localhost:3307, user `root`, password `colite-dev` | | Admin login | `admin` / `colite-dev-admin` | +## Admin portal + +The portal runs outside Docker with `npm run dev` and talks to `mobile-api` on port 8080. With the stack up: + +```sh +cd solvway-admin-portal +cat > .env.local <<'EOF' +MOBILE_API_BASE_URL=http://localhost:8080 +MOBILE_API_KEY=colite-local-app-key +SESSION_SECRET=colite-local-session-secret-0123456789abcdef +EOF +npm ci +npm run dev +``` + +Open http://localhost:3001 and log in as `admin` / `colite-dev-admin`. `.env.local` is git-ignored. The portal declares Node 24; Node 22 also runs it. + ## Reset Deletes the database volume; the next start reseeds from `local/seed/`: diff --git a/local/seed/02-reference.sql b/local/seed/02-reference.sql index 07378b5..1c81b24 100644 --- a/local/seed/02-reference.sql +++ b/local/seed/02-reference.sql @@ -163,7 +163,7 @@ UNLOCK TABLES; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'ROLE_SUPER_ADMIN',NULL,1,'ROLE_SUPER_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(2,'ROLE_ADMIN',1,2,'ROLE_SUPER_ADMIN/ROLE_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(3,'ROLE_MEMBER',NULL,1,'ROLE_MEMBER','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(4,'ROLE_HQ',1,3,'ROLE_SUPER_ADMIN/ROLE_ADMIN/ROLE_HQ','admin','2020-01-01 00:00:00','admin','2021-03-18 01:46:43'),(31,'ROLE_KYC',42,3,'ROLE_SUPER_ADMIN/ROLE_TEMP_DELETE/ROLE_KYC','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(32,'ROLE_MERCHANT',NULL,1,'ROLE_MERCHANT','admin','2020-01-01 00:00:00','admin','2023-05-12 02:26:10'),(71,'ROLE_MERCHANT_ADMIN',32,2,'ROLE_MERCHANT/ROLE_MERCHANT_ADMIN','admin','2020-01-01 00:00:00','admin','2023-05-12 02:26:10'),(91,'ROLE_MERCHANT_BASIC',71,3,'ROLE_MERCHANT/ROLE_MERCHANT_ADMIN/ROLE_MERCHANT_BASIC','admin','2021-10-21 11:00:00','admin','2023-05-12 02:26:10'),(99,'ROLE_IT',1,2,'ROLE_SUPER_ADMIN/ROLE_IT','solvwayadm','2022-04-05 12:57:42','solvwayadm','2022-04-05 04:57:41'),(110,'ROLE_TASTEFULLY',1,2,'ROLE_SUPER_ADMIN/ROLE_TASTEFULLY','bryanlee','2023-06-01 17:44:58','bryanlee','2024-08-20 05:40:39'),(111,'ROLE_STAFF',1,2,'ROLE_SUPER_ADMIN/ROLE_STAFF','admin','2024-08-20 11:40:29','admin','2024-08-20 05:31:41'),(112,'ROLE_MERC',1,2,'ROLE_SUPER_ADMIN/ROLE_MERC','admin','2024-08-20 14:25:16','admin','2024-08-20 06:25:15'),(113,'ROLE_REGISTEREXHIBITOR (cancel) ',99,3,'ROLE_SUPER_ADMIN/ROLE_IT/ROLE_REGISTEREXHIBITOR (cancel) ','admin','2024-08-23 16:00:19','admin','2024-08-28 02:26:29'),(114,'ROLE_KAYZ',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_KAYZ','Staff','2024-08-23 16:14:23','Staff1','2024-09-26 08:52:44'),(115,'ROLE_TESTING REGISTER',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_TESTING REGISTER','Staff1','2024-08-28 11:36:14','Staff1','2024-08-28 03:36:14'),(116,'ROLE_GWP',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_GWP','Staff1','2024-09-26 13:38:05','Staff1','2024-09-26 05:38:04'),(117,'ROLE_LUCKYDRAW',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_LUCKYDRAW','Staff1','2024-09-26 15:16:59','Staff1','2024-09-26 07:16:59'),(118,'ROLE_EVENT OPERATION',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_EVENT OPERATION','Staff1','2024-09-26 16:52:09','Staff1','2026-04-29 09:03:25'),(119,'ROLE_TSC MEMBER REDEMPTION',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_TSC MEMBER REDEMPTION','Staff1','2025-06-24 18:45:54','Staff1','2025-06-25 14:35:48'),(120,'ROLE_MAIN_DASHBOARD',1,2,'ROLE_SUPER_ADMIN/ROLE_MAIN_DASHBOARD','bryanlee','2023-06-01 17:44:58','bryanlee','2024-08-20 05:40:39'); +INSERT INTO `role` VALUES (1,'ROLE_SUPER_ADMIN',NULL,1,'ROLE_SUPER_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(2,'ROLE_ADMIN',1,2,'ROLE_SUPER_ADMIN/ROLE_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(3,'ROLE_MEMBER',NULL,1,'ROLE_MEMBER','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -272,7 +272,7 @@ UNLOCK TABLES; LOCK TABLES `user_group_roles` WRITE; /*!40000 ALTER TABLE `user_group_roles` DISABLE KEYS */; -INSERT INTO `user_group_roles` VALUES (4,2),(8,32),(4,110),(9,110),(5,111),(7,111),(6,112),(7,114); +INSERT INTO `user_group_roles` VALUES (4,2); /*!40000 ALTER TABLE `user_group_roles` ENABLE KEYS */; UNLOCK TABLES; @@ -282,7 +282,7 @@ UNLOCK TABLES; LOCK TABLES `modules_roles` WRITE; /*!40000 ALTER TABLE `modules_roles` DISABLE KEYS */; -INSERT INTO `modules_roles` VALUES (12010010,99),(12010010,100),(12010010,101),(12010010,110),(12010100,99),(12010100,100),(12010100,101),(12010100,110),(12010100,111),(12010100,114),(12010100,118),(12010100,119),(12010110,99),(12010110,100),(12010110,101),(12010110,110),(12010110,111),(12010120,99),(12010120,100),(12010120,101),(12010120,110),(12010120,111),(12010400,99),(12010400,100),(12010400,101),(12010500,99),(12010500,100),(12010500,101),(12010500,110),(12010790,110),(12010800,99),(12010800,100),(12010800,101),(12010800,110),(12010900,99),(12010900,100),(12010900,101),(12010900,110),(12011200,99),(12011200,100),(12011200,101),(12011200,110),(12011300,99),(12011300,100),(12011300,101),(12011400,99),(12011400,100),(12011400,101),(12011400,110),(12011901,99),(12011901,100),(12011901,101),(12011901,110),(12020100,99),(12020100,100),(12020100,101),(12020100,110),(12020200,99),(12020200,100),(12020200,101),(12020300,99),(12020300,100),(12020300,101),(12020300,110),(12020400,99),(12020400,100),(12020400,101),(12020400,110),(12020500,99),(12020500,100),(12020500,101),(12020500,110),(12610100,99),(12610100,100),(12610100,101),(12610100,109),(12610100,111),(12610100,113),(12610100,115),(12610200,99),(12610200,100),(12610200,101),(12610200,109),(12610200,111),(12610200,113),(12610200,115),(12610210,99),(12610210,100),(12610210,101),(12610210,109),(12610210,111),(12610210,113),(12610210,115),(12610300,99),(12610300,100),(12610300,101),(12610300,109),(12610300,111),(12610300,113),(12610300,115),(12610400,99),(12610400,100),(12610400,101),(12610400,109),(12610400,111),(12610400,113),(12610400,115),(12610405,109),(12610500,99),(12610500,100),(12610500,101),(12610500,109),(12610500,111),(12610500,113),(12610500,115),(12610540,111),(12610550,111),(12610600,99),(12620100,99),(12620200,99),(12620300,99),(12620400,99),(12630006,99),(12630006,100),(12630006,101),(12700100,111),(12700100,114),(12700100,117),(12700100,118),(12700200,111),(12700200,114),(12700200,117),(12700200,118),(12700300,111),(12700300,114),(12700300,117),(12700300,118),(12700400,111),(12700400,114),(12700400,117),(12700400,118),(12700500,111),(12700500,114),(12700500,117),(12700500,118),(12700505,111),(12700510,111),(12700510,114),(12700510,117),(12700510,118),(12700520,111),(12700520,114),(12700520,117),(12700520,118),(12700530,111),(12700530,114),(12700530,116),(12700530,117),(12700530,118),(12700600,111),(12700600,114),(12700600,118),(12700600,119),(12700700,111),(12700700,114),(12700700,118),(12700700,119),(12700800,111),(12700800,114),(12700800,118),(12700800,119),(13000010,110),(13010200,99),(13010200,100),(13010200,101),(13010200,110),(13010220,110),(13010400,99),(13010400,100),(13010400,101),(13010400,109),(13010400,110),(13010994,110),(13015100,101),(13015100,109),(13015100,110),(13015200,99),(13015200,100),(13015200,101),(13015200,110),(13015360,110),(13015370,110),(14010100,99),(14010100,100),(14010100,101),(14020100,99),(14020100,100),(14020100,101),(14020200,99),(14020200,100),(14020200,101),(14020300,99),(14020300,100),(14020300,101),(14020350,99),(14020350,100),(14020350,101),(14020400,99),(14020400,100),(14020400,101),(14020450,99),(14020450,100),(14020450,101),(14020500,99),(14020500,100),(14020500,101),(14020510,99),(14020510,100),(14020510,101),(14080100,99),(14080100,100),(14080100,101),(14090100,99),(14090100,100),(14090100,101),(14090200,99),(14090200,100),(14090200,101),(15010100,99),(15010100,100),(15010100,109),(15010100,110),(15010200,99),(15010200,100),(15010200,109),(15010200,110),(15010300,99),(15010300,100),(15010300,109),(15010300,110),(15010400,99),(15010400,100),(15010400,110),(15020100,99),(15020100,100),(15020100,101),(15020100,110),(15030100,110),(15030200,110),(15030300,110),(15030400,110),(15031500,110),(15031600,110),(15031700,110),(15031800,110),(15031910,110),(15032100,110),(15032200,110),(15032300,110),(15032400,110),(15041000,111),(15041000,112),(15041000,114),(15042000,111),(15042000,112),(15043000,111),(15043000,112),(15043000,114),(15043000,119),(15600200,99),(15600200,100),(15600200,101),(15600410,99),(15600410,100),(15600410,101),(15600415,99),(15600415,100),(15600415,101),(15600610,99),(15600610,100),(15600610,101),(15600620,99),(15600620,100),(15600620,101),(16010100,101),(16010200,101),(16030100,110),(16030200,110),(16030300,110),(19010100,99),(19010100,100),(19010100,101),(19010100,110),(19010200,99),(19010200,100),(19010200,101),(19010200,110),(19010200,111),(19010310,99),(19010310,100),(19010310,101),(19010310,110),(19010310,111),(19010315,99),(19010315,100),(19010315,101),(19010315,110),(19010315,111),(19010320,99),(19010320,100),(19010320,101),(19010320,110),(19010320,111),(19010321,99),(19010321,100),(19010321,101),(19010321,110),(19010321,111),(19020100,99),(19020100,100),(19020100,101),(19020100,110),(19020100,111),(19020200,99),(19020200,100),(19020200,101),(19020200,110),(19020200,111),(19020300,99),(19020300,100),(19020300,101),(19020300,110),(19020300,111),(19035100,99),(19035100,100),(19035100,101),(19035200,99),(19035200,100),(19035200,101),(19035300,99),(19035300,100),(19035300,101),(19035400,99),(19035400,100),(19035400,101),(19035510,99),(19035510,100),(19035510,101),(19035520,99),(19035520,100),(19035520,101),(19040100,99),(19040100,100),(19040100,101),(19050100,99),(19050100,100),(19050100,101),(19050200,99),(19050200,100),(19050200,101),(19050300,99),(19050300,100),(19050300,101),(19050400,99),(19050400,100),(19050400,101),(19050500,99),(19050500,100),(19050500,101),(19055110,99),(19055110,100),(19055110,101),(19055110,109),(19055210,99),(19055210,100),(19055210,101),(19055210,109),(19055210,110),(19055220,99),(19055220,100),(19055220,101),(19055220,109),(19055220,110),(19055310,99),(19055310,100),(19055310,101),(19055310,109),(19055310,110),(19055320,99),(19055320,100),(19055320,101),(19055320,109),(19055320,110),(19055410,99),(19055410,100),(19055410,101),(19055410,110),(19055420,99),(19055420,100),(19055420,101),(19055420,110),(19055430,99),(19055430,100),(19055430,101),(19055430,109),(19055430,110),(19055440,99),(19055440,100),(19055440,101),(19055440,109),(19055440,110),(19056100,110),(19057100,110),(19058100,110),(19058200,110),(19060100,99),(19060100,100),(19060100,101),(19060100,111),(19060110,99),(19060110,100),(19060110,101),(19060110,111),(19060120,99),(19060120,100),(19060120,101),(19060120,111),(19060200,99),(19060200,100),(19060200,101),(19060200,111),(19060300,99),(19060300,100),(19060300,101),(19070110,99),(19070110,100),(19070110,101),(19070110,109),(19070110,110),(19070120,99),(19070120,100),(19070120,101),(19070120,109),(19070120,110),(19090100,99),(19090100,100),(19090100,101),(19090100,109),(19090100,110),(19090110,99),(19090110,100),(19090110,101),(19090110,109),(19090110,110),(19090120,99),(19090120,100),(19090120,101),(19090120,109),(19090120,110),(19090320,99),(19090320,100),(19090320,101),(19090320,109),(19090320,110),(19090330,99),(19090330,100),(19090330,101),(19090330,109),(19090330,110),(19090720,99),(19090720,100),(19090720,101),(19090720,109),(19090720,110),(19090730,99),(19090730,100),(19090730,101),(19090730,109),(19090730,110),(19090843,110),(19090843,111),(19090851,99),(19090851,100),(19090851,101),(19090851,111),(19090852,31),(19090852,99),(19090852,100),(19090852,101),(19090852,111),(19090871,99),(19090871,100),(19090871,101),(19090872,99),(19090872,100),(19090872,101),(19090873,99),(19090873,100),(19090873,101),(19090874,99),(19090874,100),(19090874,101),(19090875,99),(19090875,100),(19090875,101),(19090881,110),(19090881,111),(19090881,114),(19090881,118),(19090910,99),(19090910,100),(19090910,101),(19091010,99),(19091010,100),(19091010,101),(19091021,99),(19091021,100),(19091021,101),(19091022,99),(19091022,100),(19091022,101),(19091110,109),(19091110,110),(19091110,111),(19091120,109),(19091120,110),(19091120,111),(19091610,111),(19091620,111),(19091630,111),(19091710,111),(19091720,111),(19091730,111),(19999998,99),(19999999,99),(19999999,100),(19999999,101),(20090000,3),(20100100,3),(20100200,3),(20100300,3),(20100400,3),(20200100,3),(20300400,3),(20401100,3),(20401200,3),(20500200,3),(20600000,3),(20610000,3),(20620000,3),(20700100,3),(20700200,3),(20700300,3),(20700600,3),(20800100,3),(20800200,3),(20800300,3),(30700000,91),(36000000,91),(36010000,91),(38000000,91),(38000100,91); +INSERT INTO `modules_roles` VALUES (20090000,3),(20100100,3),(20100200,3),(20100300,3),(20100400,3),(20200100,3),(20300400,3),(20401100,3),(20401200,3),(20500200,3),(20600000,3),(20610000,3),(20620000,3),(20700100,3),(20700200,3),(20700300,3),(20700600,3),(20800100,3),(20800200,3),(20800300,3); /*!40000 ALTER TABLE `modules_roles` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 57af24a..400988b 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -1,17 +1,27 @@ --- Local dev only. One company and one admin login. +-- Local dev only. Applies the change SQL (company, BO modules) and creates one admin login. -- Admin login: admin / colite-dev-admin (dev password, documented in local/README.md). --- The company table and user.company_id for real environments are added by the admin-auth change (change 2). +-- Keep the statements below in step with openspec/changes/*/sql/ (and the archive once archived). USE `service-system`; -CREATE TABLE IF NOT EXISTS `company` ( + +-- add-admin-auth-users-roles/sql/01-company.sql +CREATE TABLE `company` ( `id` bigint NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `company` (`id`, `name`) VALUES (1, 'Co-Lite'); +ALTER TABLE `user` ADD COLUMN `company_id` bigint NULL; +-- add-admin-auth-users-roles/sql/02-bo-modules.sql +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40000000, 'BO_ROOT', 'Back Office', 'BO', 'R', 0, NULL, NULL), + (40700000, 'BO_USERS', 'Users', 'BO', 'M', 40000000, '/users', 'UserCog'), + (40800000, 'BO_ROLES', 'Roles', 'BO', 'M', 40000000, '/roles', 'ShieldCheck'); + +-- Dev admin: super admin, company 1, password already set (login 'Y', no first-login change). INSERT INTO `user` (`id`, `email`, `enabled`, `name`, `password`, `username`, `groupid`, `branchid`, - `login`, `status`, `type`, `create_by`, `create_date`, `done_by`) -VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 0, - 'N', 'Y', 'A', 'seed', NOW(), 'seed'); + `login`, `status`, `type`, `create_by`, `create_date`, `done_by`, `company_id`) +VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 1, + 'Y', 'Y', 'A', 'seed', NOW(), 'seed', 1); INSERT INTO `users_roles` (`user_id`, `role_id`) VALUES (1, 1); diff --git a/local/smoke.sh b/local/smoke.sh index 8f91376..e252a8f 100755 --- a/local/smoke.sh +++ b/local/smoke.sh @@ -8,19 +8,27 @@ APP_KEY=colite-local-app-key fail() { echo "FAIL: $1"; exit 1; } -# 1. Admin login: gateway -> service-auth -> service-system -> MySQL -token=$(curl -sf -X POST "$GW/auth/authenticate" -H "api-key: $GW_KEY" -H 'Content-Type: application/json' \ - -d '{"username":"admin","password":"colite-dev-admin"}') || fail "POST $GW/auth/authenticate" -[ -n "$token" ] || fail "POST $GW/auth/authenticate returned no token" -echo "auth/authenticate: 200" +# 1. Admin login: mobile-api -> service-auth -> service-system -> MySQL +token=$(curl -sf -X POST "$MOBILE/api/admin/auth/login" -H "api-key: $APP_KEY" -H 'Content-Type: application/json' \ + -d '{"username":"admin","password":"colite-dev-admin"}' \ + | sed -n 's/.*"token":"\([^"]*\)".*/\1/p') || fail "POST $MOBILE/api/admin/auth/login" +[ -n "$token" ] || fail "POST $MOBILE/api/admin/auth/login returned no token" +echo "api/admin/auth/login: 200" -# 2. gateway -> service-counter -> MySQL +# 2. Admin guard and session lookup, then the users list (service-system) +for path in /api/admin/me /api/admin/users; do + code=$(curl -s -o /dev/null -w '%{http_code}' "$MOBILE$path" -H "api-key: $APP_KEY" -H "Authorization: Bearer $token") + [ "$code" = 200 ] || fail "GET $MOBILE$path returned $code" + echo "${path#/}: $code" +done + +# 3. gateway -> service-counter -> MySQL code=$(curl -s -o /dev/null -w '%{http_code}' "$GW/counter/event/findCurrentEvent" \ -H "api-key: $GW_KEY" -H "Authorization: Bearer $token") [ "$code" = 200 ] || fail "GET $GW/counter/event/findCurrentEvent returned $code" echo "counter/event/findCurrentEvent: $code" -# 3. mobile-api -> gateway -> service-system -> MySQL +# 4. mobile-api -> gateway -> service-system -> MySQL, no login code=$(curl -s -o /dev/null -w '%{http_code}' "$MOBILE/api/public/messages/en_US" -H "api-key: $APP_KEY") [ "$code" = 200 ] || fail "GET $MOBILE/api/public/messages/en_US returned $code" echo "api/public/messages/en_US: $code" diff --git a/openspec/changes/add-admin-auth-users-roles/.openspec.yaml b/openspec/changes/add-admin-auth-users-roles/.openspec.yaml new file mode 100644 index 0000000..7ed429c --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-26 diff --git a/openspec/changes/add-admin-auth-users-roles/design.md b/openspec/changes/add-admin-auth-users-roles/design.md new file mode 100644 index 0000000..88d5d05 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/design.md @@ -0,0 +1,85 @@ +# Design + +## Context + +- The admin portal in `solvway-admin-portal` is babyboo's full back office. Its kept screens call portal route handlers (`app/api/**`), which call `mobile-api` `/api/admin/**` through `callMobileApi` with the `api-key` header and the JWT as a Bearer token. The session is a sealed cookie (`bb_admin` by default). +- Co-Lite's `mobile-api` has no `/api/admin/**` controllers. `AppAccessAspect` checks the api-key and JWT signature and expiry only, so any valid token (member or admin) passes. +- Babyboo's `mobile-api` already solves this: `AdminAuthController`, `AdminUserController`, `AdminRoleController`, their services, `@AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin checks in its `AppAccessAspect`, with unit tests. Babyboo and Co-Lite share the Solvway base, and Co-Lite's `services-system` and `services-auth` already expose every downstream endpoint those services call except the module-management and group endpoints we drop. +- `services-auth` `POST /auth/authenticate` issues admin (type A) tokens and answers 200 with an empty body on failure. `/auth/findUserByToken/BO/{token}` returns the admin user with roles and ACL menu, and returns nothing for a token stored as logged out by `/auth/logoutToken/{token}` (Redis). +- `services-system` `/user/resetAdminPassword` takes username and email, checks they match an admin, sets a random 8-character password with login status N (change required), and emails it. +- Tastefully's module rows use area `A`; babyboo's portal reads area `BO` with names like `BO_USERS`. + +## Goals / Non-Goals + +**Goals:** +- Port, not rewrite: take babyboo's admin classes and tests, then cut what depends on dropped features. +- Every rule in the specs is pinned by a test before it is implemented (porting rule in `CLAUDE.md`). + +**Non-Goals:** +- Login throttling or lockout, session-policy timeouts, Google sign-in, user groups, module management, audit log, country scope. +- Changing member (customer-portal) auth. + +## Decisions + +### 1. Port babyboo's admin layer into `mobile-api`, trimmed + +Copy `AdminAuthController`, `AdminUserController`, `AdminRoleController`, their services and DTOs, `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard`, and the admin branch of babyboo's `AppAccessAspect` (`isAdminPath`, `isAdminToken`, revocation, session guard, `requireAdminModule`). Remove country scope, audit annotations, login-security and lockout handling, and anything that calls a dropped endpoint. Port the matching babyboo unit tests and adapt them; a dropped feature's tests go with it. + +Alternative: write admin controllers fresh against Tastefully's backoffice controllers. Rejected: the portal already speaks babyboo's contract, and babyboo's version has the guard and tests we need. + +### 2. Admin token check uses `findUserByToken/BO` + +On an `/api/admin/**` path the aspect first reads the token's `USERTYPE` claim: anything but `A` is a 403. It then loads the user with `/auth/findUserByToken/BO/{token}`; no user (unknown or logged out) is a 401. `findUserByToken` did not check the logout list, so this change makes it return no user for a logged-out token, and adds `BO` to the `Area` enums in core-libs and services-system. `findUserByToken` also adds `ROLE_ADMIN` (id 2) to every admin, so the module check ignores role 2. The pending-reset 403 carries `code: PASSWORD_RESET_REQUIRED`, which the portal uses to redirect. The same lookup gives the roles for the module check and the enabled and login-status flags for the session guard (deactivated means 401; pending password change allows only first-login and logout, otherwise 403). This is one downstream call per admin request. + +`ponytail:` no cache on this lookup; add a short-TTL cache keyed by token if admin latency matters. + +Alternative: a JWT claim for user type. Rejected: needs a `services-auth` change and still needs the lookup for revocation and deactivation. + +### 3. Wrong password becomes 401 in `mobile-api` + +`AdminAuthController.login` maps an empty token from `/auth/authenticate` to 401. `services-auth` stays as is, so other callers (customer portal) are unaffected. + +### 4. Forgot password reuses `/user/resetAdminPassword` + +New public endpoint `POST /api/admin/auth/forgot-password` (`@AppAuth(skipValidate=true)`) with `{username, email}`. It calls `/user/resetAdminPassword` and always answers 200 with no body detail. The admin-triggered reset (`POST /api/admin/users/{id}/resetPassword`) looks up the user and calls the same endpoint with that user's username and email. The portal gets a `/forgot-password` page (added to `PUBLIC_PATHS`) linked from the login page. + +The emailed password is plain text in the email body. That is Tastefully's existing behaviour, accepted for phase 1 because the user must change it at next login. + +### 5. Company + +`service-system` gets `company (id, name, create_date)` and `user.company_id BIGINT NULL` (nullable because member rows share the table). `services-system` `User` gains `companyId`. `AdminUserService.create` sets `companyId` from the logged-in admin, ignoring any value in the request. The seed sets company 1 on the dev admin. + +### 6. Co-Lite back-office modules + +Area `BO`, babyboo's id scheme: `40000000 BO_ROOT` (type R), `40700000 BO_USERS` (`/users`), `40800000 BO_ROLES` (`/roles`). Tastefully's area-`A` rows stay in the table and never show, because the portal reads area `BO`. The portal's `FIXED_PROTECTED_MODULE_NAMES` and `routeModules` are cut to the names that exist. + +### 7. Roles shown + +The role list hides `ROLE_MEMBER` and `ROLE_ADMIN` (id 2, attached to every admin by `findUserByToken` and ignored by the module check). The local seed drops Tastefully's business roles (KYC, merchant, staff and the rest) and keeps `ROLE_SUPER_ADMIN` (1), `ROLE_ADMIN` (2) and `ROLE_MEMBER` (3). + +### 8. Portal cut-down + +Delete by directory: every `app/` route, `app/api/` family, `app/components/` folder and test not used by the kept screens (list in proposal). Then remove `package.json` dependencies with no remaining import. Rename the cookie default to `colite_admin` and replace babyboo branding strings. The kept-screen tests and the shell and middleware tests must stay green; i18n keys for removed screens go with them. + +### 9. Smoke check + +`local/smoke.sh` logs in through `POST :8080/api/admin/auth/login` and then calls `GET :8080/api/admin/me` and `GET :8080/api/admin/users`, replacing the gateway login. The service-counter read and the public call stay. + +## Risks / Trade-offs + +- [Anyone who knows a username and its email can reset that password, locking the user out until they read the email] → Accepted for phase 1 (staff-only, small team). The response never reveals a match. Throttling comes back with babyboo's login-security later. +- [The ported aspect is security code copied across codebases] → Each guard rule has a ported or new test, and the reviewer reads the whole aspect diff. +- [Deleting most of the portal breaks shared imports in ways tests miss] → `npm run build` and `npm run lint` must pass, not only `vitest`. +- [Forgot-password takes longer when the details match (bcrypt plus an email), so timing can hint at a match] → Accepted for phase 1; the body is identical either way. +- [services-auth issues a token to a deactivated admin] → The admin login checks `enabled` and revokes that token before answering 401; `/user/resetAdminPassword` now refuses deactivated users. +- [A non-super admin with `BO_USERS` or `BO_ROLES` could use one module to gain the other] → A non-super admin cannot change their own roles or the grants of a role they hold, and nobody can assign `ROLE_ADMIN` or `ROLE_MEMBER`. They can still give a colleague any visible role; a subset rule (assign only what you hold) is deferred. +- [The gateway token bypass for `/user/resetAdminPassword` returns the updated-row count (1 or 0) to anyone with a gateway api-key allowed on `/user/`] → Gateway keys stay internal (mobile-api only); the public endpoint in mobile-api always answers the same. +- [Plain-text temporary password in email] → Forced change at next login; revisit with real SMTP in change 5. + +## Migration Plan + +Additive SQL in `sql/` of this change, run against `service-system`: +1. `01-company.sql`: create `company`, add `user.company_id`, insert company 1. +2. `02-bo-modules.sql`: insert the three BO module rows. + +Nothing is deployed, so there is no live data. The same statements are mirrored into `local/seed/`. Rollback: drop the column, the table and the rows (`sql/99-rollback.sql`). diff --git a/openspec/changes/add-admin-auth-users-roles/proposal.md b/openspec/changes/add-admin-auth-users-roles/proposal.md new file mode 100644 index 0000000..91d7d28 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/proposal.md @@ -0,0 +1,37 @@ +# Proposal + +## Why + +Lead capture (change 4) needs staff to log in to the admin portal and needs Sales users to exist. Today the copied admin portal is babyboo's full back office, and `mobile-api` has no `/api/admin/**` endpoints, so nobody can log in. This change gives Co-Lite a working staff login, user management and role permissions: the base every later admin screen builds on. See `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md` (Admin portal, Access, Company id). + +## What Changes + +- **Admin portal cut down** to: login, first-login password change, forgot password, Users (list, create, edit, deactivate, assign roles, reset password), Roles (list, create, edit, edit permissions), the app shell with role-based menus, and the not-authorised page. Every other babyboo screen, API route, component and test is removed, along with dependencies only they used. +- **New forgot-password page** in the portal. It uses Tastefully's existing reset: username plus email, a temporary password is emailed, and the user must change it at next login. +- **`mobile-api` gains `/api/admin/**`**: auth (login, first-login, forgot password, logout, refresh), `me`, users, roles and role permissions. Ported from babyboo's AdminAuth, AdminUser and AdminRole controllers onto Co-Lite's existing `services-auth` and `services-system` endpoints. +- **Admin access enforcement** in `mobile-api`: on `/api/admin/**`, a non-admin token is rejected, a logged-out token is rejected, a pending first-login reset confines the token to the first-login endpoint, and each handler declares the modules it needs (`@AdminModule`), checked against the caller's roles. Super admin passes every module check. +- **Wrong-password login returns 401** at `/api/admin/auth/login` (today `services-auth` answers 200 with an empty body). +- **Company**: a `company` table and a `company_id` column on the admin `user` in `service-system`. New users get the creating admin's company. +- **Back-office modules**: Co-Lite's own BO module rows (root, Users, Roles) in `service-system`.`module`. SQL lives in this change folder and is mirrored in `local/seed/`. + +Not in this change: login lockout, session-policy and login-security screens, the module-management screen, user groups, audit log, Google sign-in (all babyboo features Co-Lite drops in phase 1). + +## Capabilities + +### New Capabilities +- `admin-access`: staff login, first-login password change, forgot password, logout, session, menus, and the rules that guard every `/api/admin/**` endpoint and admin portal page. +- `admin-users`: managing staff users (list, search, create, edit, deactivate, assign roles, reset password) and the company they belong to. +- `admin-roles`: managing roles and the back-office modules each role grants. + +### Modified Capabilities +None. + +## Impact + +- `solvway-admin-portal`: most of the tree is deleted; kept screens are adapted to Co-Lite (cookie name, module names, branding text). +- `solvway-mobile-api`: new admin controllers, services, `@AdminModule`, and admin checks in `AppAccessAspect`. +- `solvway-services-system`: `Company` entity, `User.companyId`, user save sets company. No new endpoints expected (the needed ones exist); any gap found is added in the task that needs it. +- `solvway-services-auth`: unchanged unless the admin token check needs it (see design). +- Database `service-system`: new table `company`, new column `user.company_id`, new `module` and `modules_roles` rows. Additive only. +- `local/seed/`: mirrors the SQL; `03-colite.sql` keeps creating the dev admin. +- `local/smoke.sh`: the admin login call moves to `/api/admin/auth/login` on mobile-api. diff --git a/openspec/changes/add-admin-auth-users-roles/specs/admin-access/spec.md b/openspec/changes/add-admin-auth-users-roles/specs/admin-access/spec.md new file mode 100644 index 0000000..e46c8d3 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/specs/admin-access/spec.md @@ -0,0 +1,121 @@ +# Spec Delta + +## Purpose + +Staff log in to the Co-Lite admin portal, and every admin page and `/api/admin/**` endpoint admits only active staff holding the module it needs. + +## ADDED Requirements + +### Requirement: Staff login + +The system SHALL let an active admin user log in with username and password through the admin portal, and SHALL return the user's name, roles, menu and whether a password change is required. + +#### Scenario: Correct credentials + +- **GIVEN** an active admin user `admin` with password `colite-dev-admin` +- **WHEN** they submit those credentials on the login page +- **THEN** they are signed in and land on the portal home +- **AND** the sidebar shows only the menu entries their roles grant + +#### Scenario: Wrong password + +- **WHEN** a user submits a wrong password +- **THEN** `/api/admin/auth/login` responds 401 +- **AND** the login page shows an invalid-credentials message without saying whether the username exists + +#### Scenario: Deactivated user + +- **GIVEN** an admin user whose account is deactivated +- **WHEN** they submit their correct password +- **THEN** login is refused with a 401 and the page shows the same invalid-credentials message + +#### Scenario: Member account + +- **WHEN** a member (non-admin) account submits its correct credentials to the admin login +- **THEN** login is refused with a 401 + +### Requirement: First-login password change + +The system SHALL require a user whose password is temporary (new user or reset) to set a new password before using any other admin page or endpoint. + +#### Scenario: Pending change confines the session + +- **GIVEN** a user logged in with a temporary password +- **WHEN** they open any portal page other than the password-change page +- **THEN** they are sent to the password-change page +- **AND** any `/api/admin/**` call other than first-login and logout responds 403 + +#### Scenario: Password changed + +- **GIVEN** a user on the password-change page +- **WHEN** they submit a new password that meets the password rules +- **THEN** the password is saved, the temporary flag clears, and they can use the portal + +### Requirement: Forgot password + +The system SHALL let a user request a temporary password by entering their username and email on a public forgot-password page. The response SHALL be the same whether or not the username and email match an active admin user. + +#### Scenario: Matching username and email + +- **GIVEN** an active admin user with username `sales1` and email `sales1@example.com` +- **WHEN** someone submits `sales1` and `sales1@example.com` +- **THEN** a temporary password is emailed to `sales1@example.com` +- **AND** the user must change it at next login +- **AND** the page shows "If the details match an account, we have emailed a temporary password." + +#### Scenario: Non-matching details + +- **WHEN** someone submits a username and email that do not match an active admin user +- **THEN** no password changes and no email is sent +- **AND** the page shows the same message as for a match + +### Requirement: Logout + +The system SHALL end the session on logout, and SHALL reject the logged-out token on every later `/api/admin/**` call even before it expires. + +#### Scenario: Token used after logout + +- **GIVEN** a user who logged out +- **WHEN** a request reuses their old token on `/api/admin/me` +- **THEN** it responds 401 + +### Requirement: Admin endpoint guard + +Every `/api/admin/**` endpoint except login and forgot password SHALL require a valid admin token, and SHALL require at least one of the back-office modules the endpoint declares, granted to one of the caller's roles. A user with the super admin role SHALL pass every module check. An endpoint that declares no module SHALL be denied to everyone except super admin. + +#### Scenario: No token + +- **WHEN** `/api/admin/users` is called without a token +- **THEN** it responds 401 + +#### Scenario: Member token on an admin path + +- **WHEN** a valid member token calls `/api/admin/me` +- **THEN** it responds 403 + +#### Scenario: Missing module + +- **GIVEN** an admin user whose roles do not grant `BO_USERS` +- **WHEN** they call `GET /api/admin/users` +- **THEN** it responds 403 + +#### Scenario: Granted module + +- **GIVEN** an admin user whose role grants `BO_USERS` +- **WHEN** they call `GET /api/admin/users` +- **THEN** it responds 200 + +### Requirement: Page guard + +The admin portal SHALL show a not-authorised page when a signed-in user opens a page whose module their roles do not grant, and SHALL send a signed-out visitor to the login page for every page except login and forgot password. + +#### Scenario: Signed-out visitor + +- **WHEN** a signed-out visitor opens `/users` +- **THEN** they are sent to the login page and return to `/users` after logging in + +#### Scenario: Page without the module + +- **GIVEN** a signed-in user without `BO_ROLES` +- **WHEN** they open `/roles` +- **THEN** the not-authorised page is shown and no role data is loaded diff --git a/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md b/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md new file mode 100644 index 0000000..9c881fc --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md @@ -0,0 +1,48 @@ +# Spec Delta + +## Purpose + +Admins with the Roles module define roles and choose which back-office modules each role grants, which controls the menus and endpoints its users reach. + +## ADDED Requirements + +### Requirement: Role list and edit + +The system SHALL let an admin with `BO_ROLES` list, create and rename admin roles. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules). + +#### Scenario: Create role + +- **WHEN** an admin with `BO_ROLES` creates role `ROLE_SALES` +- **THEN** it appears in the role list and can be assigned to users + +#### Scenario: Duplicate name + +- **GIVEN** role `ROLE_SALES` exists +- **WHEN** an admin creates another role named `ROLE_SALES` +- **THEN** the save is refused with a message + +### Requirement: Role permissions + +The system SHALL let an admin with `BO_ROLES` choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. An admin who is not super admin SHALL NOT change the grants of a role they hold. + +#### Scenario: Grant Users module + +- **GIVEN** role `ROLE_SALES` without `BO_USERS` +- **WHEN** an admin grants `BO_USERS` to `ROLE_SALES` and saves +- **THEN** users with `ROLE_SALES` see Users in the sidebar after their next login or session refresh +- **AND** `GET /api/admin/users` responds 200 for them + +#### Scenario: Own role + +- **GIVEN** an admin who is not super admin and holds `ROLE_SALES` +- **WHEN** they change the module grants of `ROLE_SALES` and save +- **THEN** the save is refused with a message, so no admin can widen their own access or lock themselves out of role management + +### Requirement: Back-office module set + +The system SHALL hold Co-Lite's back-office modules in the module table, with a root entry and one entry per admin screen. This change SHALL add `BO_USERS` (Users) and `BO_ROLES` (Roles). Later changes add their own modules. + +#### Scenario: Seeded modules + +- **WHEN** the local stack starts from an empty database +- **THEN** the super admin's sidebar shows Users and Roles and no Tastefully back-office entries diff --git a/openspec/changes/add-admin-auth-users-roles/specs/admin-users/spec.md b/openspec/changes/add-admin-auth-users-roles/specs/admin-users/spec.md new file mode 100644 index 0000000..277f370 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/specs/admin-users/spec.md @@ -0,0 +1,85 @@ +# Spec Delta + +## Purpose + +Admins with the Users module manage staff accounts: who can log in, which roles they hold, and which company they belong to. + +## ADDED Requirements + +### Requirement: User list + +The system SHALL list admin users only (never members), paginated on the server, searchable by name, username or email, filterable by active state, and sortable by column. + +#### Scenario: Search + +- **GIVEN** admin users `sales1` and `sales2` and a member `m100` +- **WHEN** an admin with `BO_USERS` searches for `sales` +- **THEN** the list shows `sales1` and `sales2` and not `m100` + +### Requirement: Create user + +The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email and one or more roles. Username and email SHALL be unique. The new user SHALL receive a temporary password by email and SHALL belong to the creating admin's company. + +#### Scenario: New user + +- **WHEN** an admin creates user `sales1` with email `sales1@example.com` and role Sales +- **THEN** the user is saved as active with a pending password change +- **AND** a temporary password is emailed to `sales1@example.com` +- **AND** the user's company is the creating admin's company + +#### Scenario: Duplicate username + +- **GIVEN** a user `sales1` exists +- **WHEN** an admin creates another user with username `sales1` +- **THEN** the save is refused and the form shows that the username is taken + +### Requirement: Edit and deactivate user + +The system SHALL let an admin with `BO_USERS` change a user's name, email, roles and active state. A deactivated user SHALL NOT be able to log in, and a session they already hold SHALL be refused on its next `/api/admin/**` call. An admin SHALL NOT be able to deactivate their own account. An admin who is not super admin SHALL NOT change the roles on their own account. No admin SHALL assign `ROLE_ADMIN` or `ROLE_MEMBER` when creating or editing a user. + +#### Scenario: Deactivate + +- **GIVEN** user `sales1` is signed in +- **WHEN** an admin deactivates `sales1` +- **THEN** `sales1`'s next `/api/admin/**` call responds 401 +- **AND** `sales1` can no longer log in + +#### Scenario: Self-deactivation + +- **WHEN** an admin tries to deactivate their own account +- **THEN** the save is refused with a message + +#### Scenario: Own roles + +- **GIVEN** an admin who is not super admin and holds `ROLE_SALES` +- **WHEN** they save their own account with a different set of roles +- **THEN** the save is refused with a message and their roles are unchanged + +#### Scenario: Hidden roles + +- **WHEN** an admin creates or edits a user with `ROLE_ADMIN` or `ROLE_MEMBER` in the roles +- **THEN** the save is refused with a message + +### Requirement: Admin-triggered password reset + +The system SHALL let an admin with `BO_USERS` reset another user's password, which emails the user a temporary password and requires a change at next login. The system SHALL NOT let an admin set another user's password to a value the admin chooses. + +#### Scenario: Reset + +- **WHEN** an admin resets `sales1`'s password +- **THEN** `sales1`'s old password stops working +- **AND** a temporary password is emailed to `sales1`'s email address + +#### Scenario: No direct password set + +- **WHEN** an admin calls `POST /api/admin/users/{id}/changePassword` +- **THEN** the endpoint does not exist and no password changes + +### Requirement: Company membership + +Every admin user SHALL belong to exactly one company. The company SHALL be set by the system from the creating admin, never from the request. + +#### Scenario: Company in the request is ignored + +- **WHEN** a create-user request carries a company id different from the admin's own +- **THEN** the new user gets the admin's company diff --git a/openspec/changes/add-admin-auth-users-roles/sql/01-company.sql b/openspec/changes/add-admin-auth-users-roles/sql/01-company.sql new file mode 100644 index 0000000..4c0bd00 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/sql/01-company.sql @@ -0,0 +1,17 @@ +-- Co-Lite change 2: company and user.company_id. Target: `service-system`. Additive only. Run once. +USE `service-system`; + +CREATE TABLE `company` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +INSERT INTO `company` (`id`, `name`) VALUES (1, 'Co-Lite'); + +-- Nullable: member rows share the `user` table and have no company. +ALTER TABLE `user` ADD COLUMN `company_id` bigint NULL; + +-- Every existing admin belongs to the one company. +UPDATE `user` SET `company_id` = 1 WHERE `type` = 'A'; diff --git a/openspec/changes/add-admin-auth-users-roles/sql/02-bo-modules.sql b/openspec/changes/add-admin-auth-users-roles/sql/02-bo-modules.sql new file mode 100644 index 0000000..2c0b197 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/sql/02-bo-modules.sql @@ -0,0 +1,9 @@ +-- Co-Lite change 2: back-office modules read by the admin portal (area BO). +-- Target: `service-system`.`module`. Additive only. Run once. +-- ROLE_SUPER_ADMIN (id 1) passes every module check and needs no modules_roles rows. +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40000000, 'BO_ROOT', 'Back Office', 'BO', 'R', 0, NULL, NULL), + (40700000, 'BO_USERS', 'Users', 'BO', 'M', 40000000, '/users', 'UserCog'), + (40800000, 'BO_ROLES', 'Roles', 'BO', 'M', 40000000, '/roles', 'ShieldCheck'); diff --git a/openspec/changes/add-admin-auth-users-roles/sql/99-rollback.sql b/openspec/changes/add-admin-auth-users-roles/sql/99-rollback.sql new file mode 100644 index 0000000..81368a2 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/sql/99-rollback.sql @@ -0,0 +1,6 @@ +-- Rollback for 01-company.sql and 02-bo-modules.sql. +USE `service-system`; +DELETE FROM `modules_roles` WHERE `module_id` IN (40000000, 40700000, 40800000); +DELETE FROM `module` WHERE `id` IN (40000000, 40700000, 40800000); +ALTER TABLE `user` DROP COLUMN `company_id`; +DROP TABLE `company`; diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md new file mode 100644 index 0000000..4be15f7 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -0,0 +1,55 @@ +# Tasks + +Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most touch shared security code or build files. + +## 1. Database + +- [x] 1.1 Write `sql/01-company.sql` (create `company`, add nullable `user.company_id`, insert company 1 'Co-Lite'), `sql/02-bo-modules.sql` (`40000000 BO_ROOT` R, `40700000 BO_USERS` `/users`, `40800000 BO_ROLES` `/roles`, area `BO`) and `sql/99-rollback.sql` in this change folder. Mirror them into `local/seed/` (`03-colite.sql` sets `company_id = 1` on the dev admin; `02-reference.sql` keeps only roles 1, 2, 3 and their `modules_roles` rows). Verify: `docker compose -f local/docker-compose.yml down -v && local/up.sh` exits 0, and a read-only SELECT shows the admin with company 1, the three BO modules and three roles. + - Scope: `openspec/changes/add-admin-auth-users-roles/sql/**`, `local/seed/**` + +## 2. services-system + +- [x] 2.1 Add `companyId` to `services-system` `User` (column `company_id`) and make `/user/save` keep it. Test first: saving a user with `companyId` 1 and reading it back returns 1; saving an existing user without `companyId` does not clear it. Verify: `mvn -T 1C -pl solvway-services-system -am verify`. + - Scope: `solvway-services-system/src/**` + +## 3. mobile-api admin guard + +- [x] 3.1 Port `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin branch of babyboo's `AppAccessAspect` (admin-path detection, admin-token check via `/auth/findUserByToken/BO/{token}`, revocation, deactivated and pending-reset handling, `requireAdminModule` with super-admin bypass, fail closed) into Co-Lite's `AppAccessAspect`, without country scope or audit. Port babyboo's tests for these classes and add tests for every `admin-access` "Admin endpoint guard" and "Logout" scenario plus: deactivated token gives 401, pending reset gives 403 except first-login and logout, undeclared handler denied to non-super admin. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. + - Scope: `solvway-mobile-api/src/main/java/**/useraccess/**`, `solvway-mobile-api/src/test/java/**/useraccess/**`, `solvway-mobile-api/src/main/resources/application*.yml` + +## 4. mobile-api admin auth + +- [x] 4.1 Port babyboo's `AdminAuthController` and `AdminAuthenticationService` (login, first-login, logout, refresh, me) onto Co-Lite endpoints, and add `POST /api/admin/auth/forgot-password` calling `/user/resetAdminPassword`. Login answers 401 for an empty token, a deactivated user or a non-admin account; forgot-password always answers 200. Port babyboo's tests for these classes and add one per `admin-access` login, first-login and forgot-password scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. + - Scope: `solvway-mobile-api/src/**/controller/admin/**`, `solvway-mobile-api/src/**/service/admin/**`, `solvway-mobile-api/src/**/dto/admin/**` (or babyboo's equivalent packages) + +## 5. mobile-api users and roles + +- [x] 5.1 Port `AdminUserController` and `AdminUserService`: admin-only list with search, filter and sort; create with temporary password, email and company from the logged-in admin; edit; deactivate with self-deactivation refused; admin-triggered reset via `/user/resetAdminPassword`. Tests first for each `admin-users` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. + - Scope: as 4.1 +- [x] 5.2 Port `AdminRoleController`, `AdminRoleService` and `AdminAclService` (role list hiding `ROLE_MEMBER`, create and rename with unique names, `GET/PUT /roles/{id}/modules` replacing grants, self lock-out refused, super admin grants not editable). Tests first for each `admin-roles` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. + - Scope: as 4.1 + +## 6. Admin portal + +- [x] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0. + - Scope: `solvway-admin-portal/**` +- [x] 6.2 Add the `/forgot-password` page (public, linked from login) and its route handler calling `/api/admin/auth/forgot-password`, showing the fixed message for any outcome; make the users form refuse self-deactivation and show duplicate-username and lock-out errors from the API. Tests first (vitest) for each portal-visible scenario in the specs. Verify: `npm run lint && npm run build && npm test` exit 0. + - Scope: `solvway-admin-portal/**` + +## 7. Local stack and end-to-end check + +- [x] 7.1 Update `local/smoke.sh` to log in via `POST :8080/api/admin/auth/login` and call `/api/admin/me` and `/api/admin/users` (keep the counter read and the public call); add the portal to the README run steps (`npm run dev` with `MOBILE_API_BASE_URL=http://localhost:8080` and the app key). Verify: fresh `local/up.sh` then `local/smoke.sh` prints `smoke: OK`. + - Scope: `local/smoke.sh`, `local/README.md`, `local/.env.example` +- [x] 7.2 Drive the portal in a browser with Playwright against the local stack: login (correct and wrong password), first-login change for a new user, users list/create/edit/deactivate, roles create and grant `BO_USERS`, not-authorised page for a user without `BO_ROLES`, forgot-password message. Screenshots in the change folder's `verification/`. Only local dev data is created. Verify: each scenario observed as specified. + - Scope: `openspec/changes/add-admin-auth-users-roles/verification/**` + +## 8. Review follow-up: close self-escalation + +- [x] 8.1 In `mobile-api`: delete `POST /api/admin/users/{id}/changePassword` and `AdminUserService.changePassword`; in `AdminUserService` refuse (403, `OWN_ROLES`) a non-super caller whose update changes the role set on their own account, and refuse (400, `UNKNOWN_ROLE`) `ROLE_ADMIN` or `ROLE_MEMBER` on create and update; in `AdminAclService.updateGrants` refuse (403, `OWN_ROLE`) a non-super caller editing a role they hold, and delete `requireNoLockout`, which that rule makes unreachable. Tests first for each new scenario. Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify` exits 0. + - Scope: `solvway-mobile-api/src/**/admin/**`, `solvway-mobile-api/src/**/service/Admin*` +- [x] 8.2 In the portal: delete the change-password route, `ChangePasswordDialog`, `changeAdminUserPassword` and the button on the edit-user page; the emailed reset stays. Verify: `npm run lint && npx tsc --noEmit && npx vitest run` exit 0. + - Scope: `solvway-admin-portal/**` + +## Workflow follow-up + +- Code review, PR to `main`, merge, then archive this change. diff --git a/openspec/changes/add-admin-auth-users-roles/verification/01-login-wrong-password.png b/openspec/changes/add-admin-auth-users-roles/verification/01-login-wrong-password.png new file mode 100644 index 0000000..f7273b5 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/01-login-wrong-password.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/02-users-list.png b/openspec/changes/add-admin-auth-users-roles/verification/02-users-list.png new file mode 100644 index 0000000..ebcbab0 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/02-users-list.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/03-role-create.png b/openspec/changes/add-admin-auth-users-roles/verification/03-role-create.png new file mode 100644 index 0000000..1a9e6f5 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/03-role-create.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/04-role-duplicate.png b/openspec/changes/add-admin-auth-users-roles/verification/04-role-duplicate.png new file mode 100644 index 0000000..00a98f0 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/04-role-duplicate.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/05-role-grant-users.png b/openspec/changes/add-admin-auth-users-roles/verification/05-role-grant-users.png new file mode 100644 index 0000000..70eca42 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/05-role-grant-users.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/06-user-created.png b/openspec/changes/add-admin-auth-users-roles/verification/06-user-created.png new file mode 100644 index 0000000..51c7e71 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/06-user-created.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/07-own-account-locked.png b/openspec/changes/add-admin-auth-users-roles/verification/07-own-account-locked.png new file mode 100644 index 0000000..5fd034b Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/07-own-account-locked.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/08-first-login-weak.png b/openspec/changes/add-admin-auth-users-roles/verification/08-first-login-weak.png new file mode 100644 index 0000000..e27f36f Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/08-first-login-weak.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/09-sales-home.png b/openspec/changes/add-admin-auth-users-roles/verification/09-sales-home.png new file mode 100644 index 0000000..2ea3f87 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/09-sales-home.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/10-not-authorised.png b/openspec/changes/add-admin-auth-users-roles/verification/10-not-authorised.png new file mode 100644 index 0000000..ca2bd3b Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/10-not-authorised.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/11-deactivated-signed-out.png b/openspec/changes/add-admin-auth-users-roles/verification/11-deactivated-signed-out.png new file mode 100644 index 0000000..aa8c3fd Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/11-deactivated-signed-out.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/12-forgot-password.png b/openspec/changes/add-admin-auth-users-roles/verification/12-forgot-password.png new file mode 100644 index 0000000..3932395 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/12-forgot-password.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/13-login-copy.png b/openspec/changes/add-admin-auth-users-roles/verification/13-login-copy.png new file mode 100644 index 0000000..4c5506e Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/13-login-copy.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/14-role-duplicate.png b/openspec/changes/add-admin-auth-users-roles/verification/14-role-duplicate.png new file mode 100644 index 0000000..94b5b37 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/14-role-duplicate.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/15-user-created-banner.png b/openspec/changes/add-admin-auth-users-roles/verification/15-user-created-banner.png new file mode 100644 index 0000000..92cc97a Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/15-user-created-banner.png differ diff --git a/openspec/changes/add-admin-auth-users-roles/verification/16-reset-password-hint.png b/openspec/changes/add-admin-auth-users-roles/verification/16-reset-password-hint.png new file mode 100644 index 0000000..9224f05 Binary files /dev/null and b/openspec/changes/add-admin-auth-users-roles/verification/16-reset-password-hint.png differ diff --git a/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md b/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md index 1f1e5a0..5485b6d 100644 --- a/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md +++ b/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md @@ -1,6 +1,6 @@ --- name: run-solvway-admin-portal -description: Build, run, and drive solvway-admin-portal (babyboo Back Office). Use when asked to start the app, run its dev server or tests, or take a screenshot of / interact with the running UI. +description: Build, run, and drive solvway-admin-portal (Co-Lite Back Office). Use when asked to start the app, run its dev server or tests, or take a screenshot of / interact with the running UI. --- All paths below are relative to `solvway-admin-portal/`. diff --git a/solvway-admin-portal/.env.example b/solvway-admin-portal/.env.example index 9041ce4..2cd469a 100644 --- a/solvway-admin-portal/.env.example +++ b/solvway-admin-portal/.env.example @@ -1,5 +1,5 @@ # ── Mobile API (BFF target) ─────────────────────────────────────────── -# Base URL of babyboo's solvway-mobile-api, no trailing slash. +# Base URL of solvway-mobile-api, no trailing slash. # Supplied per environment; there is no sensible default. MOBILE_API_BASE_URL= @@ -10,4 +10,4 @@ MOBILE_API_KEY= # ── Session ─────────────────────────────────────────────────────────── # Name of the httpOnly cookie that stores the admin JWT. -SESSION_COOKIE_NAME=bb_admin +SESSION_COOKIE_NAME=colite_admin diff --git a/solvway-admin-portal/Dockerfile b/solvway-admin-portal/Dockerfile index d5ecf6d..b17ac1f 100644 --- a/solvway-admin-portal/Dockerfile +++ b/solvway-admin-portal/Dockerfile @@ -5,7 +5,6 @@ FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ -COPY vendor/ ./vendor/ RUN npm ci # A High or Critical advisory in a runtime dependency fails the image (F45). Dev tooling is not shipped, # so it is excluded. Moderate advisories do not block; review them with a full `npm audit`. diff --git a/solvway-admin-portal/README.md b/solvway-admin-portal/README.md index ec781e0..9eeb3f1 100644 --- a/solvway-admin-portal/README.md +++ b/solvway-admin-portal/README.md @@ -1,206 +1,26 @@ -# Back-Office Template — babyboo.my +# Co-Lite Admin Portal -> **Migration in progress.** This module is being converted from a Vite SPA to a Next.js App -> Router project (see `openspec/changes/add-admin-portal-auth`). `app/` currently holds only a -> placeholder shell; the real pages, components and services below still live under `src/` — -> specifically `src/legacy-pages/` (renamed from `src/pages/` because Next.js reserves that name -> for its own Pages Router) — pending a later change that ports them into `app/*/page.tsx` with -> `react-router` calls rewired to `next/navigation`. Everything in this README describing routes, -> the mock-data architecture and theming still describes that `src/` tree. +Next.js 16 admin portal for Co-Lite. Screens call the JSON admin APIs (`/api/admin/**`) in `mobile-api` through server-side route handlers. -A reusable admin/back-office front end for MLM (multi-level marketing) clients. It ships -against mock data behind an API-shaped service layer, so a client project can swap in a real -backend without touching any page or component code. +## Run -**Currently skinned for babyboo.my** — baby & maternity retail, competing with Medela, Momcozy, -Kinderkraft and Hamilton. The audience is sleep-deprived, time-poor, highly selective parents, so -decisions are ranked clarity → speed → trust. The look is deliberately warm and soft-edged rather -than clinical: cream page, warm neutrals, brand brown `#6E3E17` with a gold `#F2BC57` accent, and a -1rem radius so nothing has a sharp corner. - -## Stack - -- [Next.js 16](https://nextjs.org/) (App Router, `output: "standalone"`) — build tool and server -- [React 19](https://react.dev/) + TypeScript (strict mode) -- [Tailwind CSS 3](https://tailwindcss.com/) via PostCSS + `tailwind.config.ts` — matches - `solvway-customer-portal`'s wiring -- [Sass](https://sass-lang.com/) — token maps and mixins in `src/styles/` (pending port into - `app/globals.css`, which currently carries a plain-CSS transliteration of the same tokens) -- [shadcn/ui](https://ui.shadcn.com/) — owned component source, themed with CSS variables -- [Recharts](https://recharts.org/) via shadcn's `chart` wrapper — dashboard charts -- [TanStack Table](https://tanstack.com/table) — data tables -- [lucide-react](https://lucide.dev/) — icons -- [react-router-dom v7](https://reactrouter.com/) — still a dependency for the not-yet-ported - `src/legacy-pages/` tree; removed once that tree is rewired to `next/navigation` -- [Vitest](https://vitest.dev/) + [React Testing Library](https://testing-library.com/react) — tests - -## Getting Started +Needs Node 24 (see `.nvmrc`). ```bash -npm install -npm run dev # next dev --port 3001 -npm test # run the full test suite (Vitest, run once) -npm run test:watch # run tests in watch mode -npm run build # next build (type-checks + production build) -npm start # next start --port 3001, after a build - -python3 scripts/check-contrast.py # verify token contrast in both themes +cp .env.example .env.local # then fill in the values below +npm ci +npm run dev # http://localhost:3001 ``` -### Auth +| Variable | Purpose | +| --- | --- | +| `MOBILE_API_BASE_URL` | Base URL of `mobile-api` | +| `MOBILE_API_KEY` | API key sent to `mobile-api` | +| `SESSION_SECRET` | Secret used to seal the session cookie | +| `SESSION_COOKIE_NAME` | Session cookie base name (default `colite_admin`) | -Login is no longer mocked. `/login` posts to the same-origin `/api/auth/login` route handler, -which proxies `solvway-mobile-api` (`app/lib/server/mobileApi.ts`) and sets an httpOnly session -cookie server-side. Signing in requires: - -- `MOBILE_API_BASE_URL` and `MOBILE_API_KEY` set (see `.env.example`), pointing at a reachable - `solvway-mobile-api` instance. -- A real `UserType.A` account in that instance's services-system. - -Without a configured Mobile API, `/login` still renders, but submitting the form reports "Mobile -API is not configured" — there is no local/offline demo login anymore. - -Visiting any other route while unauthenticated redirects back to `/login`; logging out clears the -session and returns you there as well. - -## Screen Inventory - -| Route | Page | Notes | -|---|---|---| -| `/login` | Login | Email/password with a password-reveal toggle; inline error on invalid credentials | -| `/` | Dashboard | Live KPI tiles (members, settled revenue/orders, rewards; Malaysia-time month), 12-month revenue and member-growth charts, revenue by channel, rank/status mix, rewards by type, top-earner leaderboard | -| `/members` | Members | Sortable, faceted, URL-synced member table with column visibility and CSV export | -| `/members/:id` | Member Detail | Identity header, performance strip, tabs for Sales · Commissions · Downline | -| `/reports` | Reports | Live Sales (settled orders) and Rewards tabs, Malaysia-time period presets + date range, paged, period totals, full-result-set CSV export | -| `/network` | Network | Genealogy as an indented tree or a top-down chart, with search that expands ancestors and highlights matches | - -Navigation is a **collapsible sidebar with up to three levels**: it collapses to an icon rail on -desktop (persisted per browser) and becomes an overlay drawer below `lg`. Every leaf resolves to a -real view — `Members → By rank → Diamond` applies `?rank=Diamond`, the Reports children select -`?tab=` — so none of them are decorative. - -[`src/components/app/nav-config.ts`](src/components/app/nav-config.ts) is the **contract a backend -menu endpoint would return**: plain `label` / `to` / `children` / `isDefault` data, with the icon as -the only client-side concern. `nav-config.test.ts` encodes the invariants such an endpoint must -satisfy (leaf-xor-group, depth cap, real routes, unique targets, one default per group), so a -backend implementation can be validated against the same rules the UI relies on. - -## Design Standard - -**[`docs/design/DASHBOARD-STANDARD.md`](docs/design/DASHBOARD-STANDARD.md) is authoritative.** It -defines the tokens, layout grid, KPI and chart specs, required data states, accessibility floor -(WCAG 2.1 AA) and the anti-patterns. Read it before adding a screen. Where it and a component -disagree, the component is wrong. - -## Mock-Data Architecture - -Everything under `src/services/*` is written to look and behave like a real API client: every -function is `async`, returns plain data (no framework types leak out), and pagination, filtering -and **sorting** happen the same way a backend would do them. The Dashboard and Reports are live -(`app/lib/services/adminDashboard.ts` -> BFF -> mobile-api aggregate reads); `src/services/api.ts` holds shared helpers (pagination, sorting, an -artificial network delay). - -**Pages only call functions from the other -`src/services/*` modules. This is the intended swap point: to connect a real backend, replace the -bodies of these service functions with `fetch` calls that return the same shapes (see -`src/types/index.ts`), and no page or component needs to change. - -``` -src/ - components/ - app/ # two-level sidebar + nav config - ui/ # shadcn primitives + DataTable, states, chart skeletons - dashboard/ # KPI tile, chart card (chart + its accessible table) - genealogy/ # tree view and org chart - styles/ - _variables.scss # $palettes (light + dark), breakpoints, layout, z-index - _mixins.scss # respond-to, focus-ring, tap-target, brand gradient - index.scss # emits the token blocks from the maps + base layer - tailwind.css # Tailwind entry + @theme (kept as CSS on purpose) - lib/ - theme.tsx # light/dark provider, persists to localStorage - utils.ts # cn() - services/ - api.ts # shared mock helpers (pagination, sorting, delay) - period.ts # month labels - auth.ts # login/logout/session — swap point - members.ts # list/detail/facets/stats — swap point - network.ts # genealogy tree — swap point -``` - -## Theming - -Colour lives in Sass maps in [`src/styles/_variables.scss`](src/styles/_variables.scss), emitted as -CSS custom properties by `index.scss` and exposed to Tailwind via `@theme inline` in `tailwind.css`. -**No component contains a colour literal.** - -The babyboo palette is brand brown `#6E3E17` with a gold `#F2BC57` accent on a cream page, plus warm -neutrals and a warm-espresso dark mode (not slate). - -**One thing to know about the gold:** `#F2BC57` is 1.73:1 against white, so it can only ever be a -*filled surface* carrying `--accent-foreground` text — never text, a thin indicator, or a chart -series, all of which would be invisible in light mode. Anything in the accent family that must carry -meaning uses `--accent-strong` (`#9A6212`, 5.08:1). That is why the accent is absent from the chart -ramp. - -Both themes live in the same map, so a token cannot be added to light and forgotten in dark. - -To re-skin for a client: - -1. Edit `$palettes` in `src/styles/_variables.scss` — primary, accent, chart ramp, radius. -2. Swap the font `` (was `index.html`, now belongs in `app/layout.tsx` — see the Migration - note above) and the `--font-*` tokens (now in `app/globals.css`, ported from - `src/styles/tailwind.css`). -3. Replace the wordmark in `src/components/app/app-sidebar.tsx`. -4. Run `python3 scripts/check-contrast.py`. - -### Fonts - -Headings are **Google Sans**, body and numerals are **Inter** — two families, no monospace. Numerals -use Inter's own tabular figures (`.tabular`), so columns still align while avoiding the technical -register of monospace digits, and it saves a font request. - -Fonts were linked from `index.html`'s `` tags before the Next.js conversion; the placeholder -`app/layout.tsx` does not yet re-add them (Task 6 restores the font ``s or switches to -`next/font`). If Google Sans must be self-hosted (offline builds, or a licensed -variant), `src/styles/index.scss` has a commented `@font-face` block — drop the `woff2` files into -`public/fonts/` and uncomment; the heading stack already requests the family first. DM Sans is the -fallback if it fails to load. - -Light is the default; dark is opt-in via the header toggle and persisted per browser. Note that -`--border` (dividers, decorative) and `--input` (form-control boundaries, must clear 3:1) are -deliberately different values — see the standard's §2. - -`scripts/check-contrast.py` verifies all of the above (both themes, exits non-zero on regression). -Run it after any palette edit. - -## Testing - -143 tests across 29 files (`npx vitest run`), covering the ported Next.js app under `app/`. Server-only -modules (`app/lib/server/mobileApi.ts`, the `/api/auth/*` route handlers) run under jsdom because -`vitest.config.ts` aliases `server-only` to `test/stub-empty.ts`. Client components mock -`apiGet`/`apiPost` (`app/lib/clientApi.ts`) rather than hitting a network, so UI tests don't depend -on `solvway-mobile-api` being reachable. - -Charts are asserted through the accessible data table that every chart is required to ship -(standard §6) rather than by measuring SVG — so no chart library gets stubbed, and the assertions -check real figures. - -`vitest.setup.ts` (repo root) stubs `matchMedia`, `ResizeObserver`, and the Pointer Events APIs -that Radix needs and jsdom lacks. - -## Known Issues - -- The production bundle is a single ~958 kB (288 kB gzip) chunk. That is down from 2.62 MB - (797 kB gzip) under antd, but a client project with stricter budgets should still code-split - with dynamic `import()`. -- **`sass-embedded` is pinned to 1.77.8 via an `overrides` entry in `package.json`, and removing it - will hang the build on macOS 13.** Vite auto-installs `sass-embedded` as an optional peer; from - roughly 1.83 its bundled Dart VM requires macOS 14+ and aborts with - `VM initialization failed`. Because that happens during the compiler handshake, the build hangs - rather than failing, which makes it look like an infinite loop. On macOS 14+ the pin is harmless - and can be dropped. -- In-browser visual verification across all breakpoints has not been automated. The contrast - floor is checked by script; layout at 375/768/1024/1440px still needs a human or a - browser-driver pass. +## Scripts +- `npm run build` / `npm start` production build and server (port 3001) +- `npm run lint` +- `npm test` diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts deleted file mode 100644 index 6217054..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq() { - return new Request("http://localhost/api/admin/company-accounts/MY/MYHQ00002/deactivate", { - method: "POST", - }) as unknown as Parameters[0]; -} -function ctx(prefix: string, memberCode: string) { - return { params: Promise.resolve({ prefix, memberCode }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts/[prefix]/[memberCode]/deactivate", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards to POST /api/admin/company-accounts/{prefix}/{memberCode}/deactivate", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { prefix: "MY", memberCode: "MYHQ00002", active: "N" } }); - - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/company-accounts/MY/MYHQ00002/deactivate", - { method: "POST", token: "jwt-abc" }, - ); - expect(res.status).toBe(200); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "not found", status: 404 }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(404); - }); - - // deactivate returns an empty 200 downstream (void controller). NextResponse.json(undefined) - // would 500 — the route must return a safe ok body. (Caught in live Part D verification.) - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts deleted file mode 100644 index 85c2c61..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; - -// POST -> /api/admin/company-accounts/{prefix}/{memberCode}/deactivate -// (add-admin-company-account-crud, Part C). Drops the account from the weighted split; the -// member, its network_tree row and any existing downline are left untouched — there is no hard -// delete. A mutation, so always POST, never a GET. - -export async function POST( - _req: NextRequest, - ctx: { params: Promise<{ prefix: string; memberCode: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix, memberCode } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}/${encodeURIComponent(memberCode)}/deactivate`, - { method: "POST", token }, - ); - if (!result.ok) return errorResponse(result); - // deactivate returns an empty 200 downstream (void); avoid NextResponse.json(undefined) (500). - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts deleted file mode 100644 index 519230d..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq() { - return new Request("http://localhost/api/admin/company-accounts/MY/MYHQ00002/reactivate", { - method: "POST", - }) as unknown as Parameters[0]; -} -function ctx(prefix: string, memberCode: string) { - return { params: Promise.resolve({ prefix, memberCode }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts/[prefix]/[memberCode]/reactivate", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards to POST /api/admin/company-accounts/{prefix}/{memberCode}/reactivate", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { prefix: "MY", memberCode: "MYHQ00002", active: "Y" } }); - - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/company-accounts/MY/MYHQ00002/reactivate", - { method: "POST", token: "jwt-abc" }, - ); - expect(res.status).toBe(200); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "not found", status: 404 }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(404); - }); - - // reactivate returns an empty 200 downstream (void controller); the route must not 500 on it. - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts deleted file mode 100644 index 38b6198..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; - -// POST -> /api/admin/company-accounts/{prefix}/{memberCode}/reactivate -// (add-admin-company-account-crud, Part C). Restores the account to the weighted split. A -// mutation, so always POST, never a GET. - -export async function POST( - _req: NextRequest, - ctx: { params: Promise<{ prefix: string; memberCode: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix, memberCode } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}/${encodeURIComponent(memberCode)}/reactivate`, - { method: "POST", token }, - ); - if (!result.ok) return errorResponse(result); - // reactivate returns an empty 200 downstream (void); avoid NextResponse.json(undefined) (500). - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts deleted file mode 100644 index 54eeab8..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq() { - return new Request("http://localhost/api/admin/company-accounts/MY") as unknown as Parameters< - typeof GET - >[0]; -} -function ctx(prefix: string) { - return { params: Promise.resolve({ prefix }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/company-accounts/[prefix]", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq(), ctx("MY")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT to GET /api/admin/company-accounts/{prefix} and returns the rows", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const rows = [ - { - prefix: "MY", - memberCode: "MYHQ00002", - name: "HQ Two", - weight: 50, - active: "Y", - configVersion: 3, - directDownline: 2, - allocatedCount: 10, - }, - ]; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: rows }); - - const res = await GET(getReq(), ctx("MY")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts/MY", { - token: "jwt-abc", - }); - expect(res.status).toBe(200); - expect(await res.json()).toEqual(rows); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "boom", status: 400 }); - const res = await GET(getReq(), ctx("MY")); - expect(res.status).toBe(400); - expect((await res.json()).error).toBe("boom"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts deleted file mode 100644 index dbe6507..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { CompanyAccountRow } from "@/app/lib/types"; - -// GET -> /api/admin/company-accounts/{prefix} (add-admin-company-account-crud, Part C): the -// company accounts configured for one registration country. Read-only — no side effect on GET -// (Next.js prefetch-safe). - -export async function GET(_req: NextRequest, ctx: { params: Promise<{ prefix: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts deleted file mode 100644 index e1d0fc0..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST, PUT } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/company-accounts", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -function putReq(body: unknown) { - return new Request("http://localhost/api/admin/company-accounts", { - method: "PUT", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("requires prefix, memberCode, name and a weight", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const body of [ - { memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }, - { prefix: "MY", name: "HQ Two", weight: 50 }, - { prefix: "MY", memberCode: "MYHQ00002", weight: 50 }, - { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two" }, - {}, - ]) { - const res = await POST(postReq(body)); - expect(res.status).toBe(400); - } - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects an email without a password (and vice versa) without forwarding", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const base = { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }; - const res1 = await POST(postReq({ ...base, email: "hq2@babyboo.my" })); - expect(res1.status).toBe(400); - const res2 = await POST(postReq({ ...base, password: "Qweqwe123" })); - expect(res2.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT and full body to POST /api/admin/company-accounts", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const body = { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }; - mocks.callMobileApi.mockResolvedValue({ - ok: true, - data: { memberId: "1", loginRequested: false, credentialCreated: false }, - }); - - const res = await POST(postReq(body)); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts", { - method: "POST", - body, - token: "jwt-abc", - }); - expect(res.status).toBe(200); - expect((await res.json()).loginRequested).toBe(false); - }); - - it("forwards a duplicate-code 4xx as-is with the downstream message", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ - ok: false, - error: "member_code already in use", - status: 409, - }); - - const res = await POST( - postReq({ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }), - ); - - expect(res.status).toBe(409); - expect((await res.json()).error).toBe("member_code already in use"); - }); -}); - -describe("PUT /api/admin/company-accounts", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await PUT(putReq({ prefix: "MY", memberCode: "MYHQ00002", weight: 75 })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("requires prefix and memberCode to locate the row", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const body of [{ memberCode: "MYHQ00002", weight: 75 }, { prefix: "MY", weight: 75 }, {}]) { - const res = await PUT(putReq(body)); - expect(res.status).toBe(400); - } - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT and full body to PUT /api/admin/company-accounts", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const body = { prefix: "MY", memberCode: "MYHQ00002", weight: 75, active: "Y" }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ...body, name: "HQ Two", configVersion: 4 } }); - - const res = await PUT(putReq(body)); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts", { - method: "PUT", - body, - token: "jwt-abc", - }); - expect(res.status).toBe(200); - }); - - // update returns an empty 200 downstream (void controller). NextResponse.json(undefined) would - // 500 — the route must return a safe ok body. (Caught in live Part D verification.) - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await PUT(putReq({ prefix: "MY", memberCode: "MYHQ00002", weight: 5 })); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/route.ts deleted file mode 100644 index 5a1b547..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/route.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { CompanyAccountCreatePayload, CompanyAccountUpdatePayload } from "@/app/lib/types"; - -// POST/PUT -> /api/admin/company-accounts (add-admin-company-account-crud, Part C). Both are -// mutations and never go out on GET (Next.js prefetch rule). Create writes the member + tree -// placement + allocation config (+ optional login) as one action; edit changes weight/active/ -// name only — memberCode/prefix locate the row and are never themselves edited. - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const body = await req.json().catch(() => ({})); - const { prefix, memberCode, name, weight, email, password } = body as Partial; - if (!prefix || !memberCode || !name || typeof weight !== "number") { - return badRequest("prefix, memberCode, name and weight are required."); - } - // The optional login travels as a pair (the anchor pattern) — one without the other is a - // malformed request, never forwarded upstream. - if (Boolean(email) !== Boolean(password)) { - return badRequest("email and password must be supplied together, or neither."); - } - - const result = await callMobileApi("/api/admin/company-accounts", { - method: "POST", - body, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} - -export async function PUT(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const body = await req.json().catch(() => ({})); - const { prefix, memberCode } = body as Partial; - if (!prefix || !memberCode) { - return badRequest("prefix and memberCode are required to locate the account."); - } - - const result = await callMobileApi("/api/admin/company-accounts", { - method: "PUT", - body, - token, - }); - if (!result.ok) return errorResponse(result); - // update returns an empty 200 downstream (void); NextResponse.json(undefined) would 500, so - // fall back to a small ok body. - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts b/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts deleted file mode 100644 index 4a5f1c7..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(search = "") { - return new Request(`http://localhost/api/admin/dashboard/event${search}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/dashboard/event", () => { - it("forwards only the event id and the admin JWT (never an operator)", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { pendingOrders: 1 } }); - const res = await GET(getReq("?eventId=7&operator=Ben")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ pendingOrders: 1 }); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/event?eventId=7", { token: "jwt-abc" }); - }); - - it("is 401 without a session and never calls mobile-api", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq("?eventId=7")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("is 400 for a missing or non-numeric event id", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - expect((await GET(getReq())).status).toBe(400); - expect((await GET(getReq("?eventId=7;drop"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes a downstream 403 through", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_DASHBOARD_EVENT module is required." }); - const res = await GET(getReq("?eventId=7")); - expect(res.status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/event/route.ts b/solvway-admin-portal/app/api/admin/dashboard/event/route.ts deleted file mode 100644 index a78d5ff..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/event/route.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; -import { badRequest } from "@/app/lib/server/apiRoute"; - -// GET -> mobile-api GET /api/admin/dashboard/event (BO_DASHBOARD_EVENT, gated upstream). Read-only, prefetch-safe. -// Only the event id is forwarded: mobile-api resolves the operator from the session, never from the client. -export function GET(req: NextRequest) { - const eventId = new URL(req.url).searchParams.get("eventId") ?? ""; - if (!/^\d+$/.test(eventId)) return badRequest("Invalid eventId parameter."); - return forwardAdminGet(req, "/api/admin/dashboard/event", ["eventId"]); -} diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts b/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts deleted file mode 100644 index f80779d..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }); - mocks.getToken.mockReset().mockResolvedValue("jwt-abc"); -}); - -describe("GET /api/admin/dashboard country", () => { - it("forwards country to mobile-api", async () => { - await GET(new Request("http://localhost/api/admin/dashboard?country=SG&evil=1") as unknown as Parameters[0]); - const url = mocks.callMobileApi.mock.calls[0][0] as string; - expect(new URL(url, "http://x").searchParams.get("country")).toBe("SG"); - expect(url).not.toContain("evil"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.test.ts b/solvway-admin-portal/app/api/admin/dashboard/route.test.ts deleted file mode 100644 index 9028c2f..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(search = "") { - return new Request(`http://localhost/api/admin/dashboard${search}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/dashboard", () => { - it("forwards only the documented params and the admin JWT", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } }); - const res = await GET(getReq("?from=2026-09-01&to=2026-09-29&evil=1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: 1 }); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard?from=2026-09-01&to=2026-09-29", { token: "jwt-abc" }); - }); - - it("is 401 without a session and never calls mobile-api", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("is 400 for a malformed date", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await GET(getReq("?from=yesterday")); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream refusal through", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "forbidden", status: 403 }); - const res = await GET(getReq()); - expect(res.status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.ts b/solvway-admin-portal/app/api/admin/dashboard/route.ts deleted file mode 100644 index e6f4edf..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; - -// GET -> mobile-api GET /api/admin/dashboard (BO_DASHBOARD). Read-only; module-gated upstream. -export const GET = (req: NextRequest) => forwardAdminGet(req, "/api/admin/dashboard", ["from", "to", "country"]); diff --git a/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts b/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts deleted file mode 100644 index c0a732a..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; -import { badRequest } from "@/app/lib/server/apiRoute"; - -// GET -> mobile-api GET /api/admin/event-summary/{eventId}?from=&to= (BO_EVENT_SUMMARY, gated upstream). Read-only. -// date is the older one-day form, still forwarded; forwardAdminGet validates from/to, date is checked here. -export async function GET(req: NextRequest, { params }: { params: Promise<{ eventId: string }> }) { - const { eventId } = await params; - if (!/^\d+$/.test(eventId)) return badRequest("Invalid eventId parameter."); - const date = new URL(req.url).searchParams.get("date"); - if (date && !/^\d{4}-\d{2}-\d{2}$/.test(date)) return badRequest("Invalid date parameter."); - return forwardAdminGet(req, `/api/admin/event-summary/${encodeURIComponent(eventId)}`, ["date", "from", "to"]); -} diff --git a/solvway-admin-portal/app/api/admin/event-summary/events/route.ts b/solvway-admin-portal/app/api/admin/event-summary/events/route.ts deleted file mode 100644 index 57ac2d6..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/events/route.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; - -// GET -> mobile-api GET /api/admin/event-summary/events (BO_EVENT_SUMMARY, gated upstream). Read-only, prefetch-safe. -export function GET(req: NextRequest) { - return forwardAdminGet(req, "/api/admin/event-summary/events", []); -} diff --git a/solvway-admin-portal/app/api/admin/event-summary/route.test.ts b/solvway-admin-portal/app/api/admin/event-summary/route.test.ts deleted file mode 100644 index 07f6218..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/route.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -// add-event-summary: the two Event Summary BFF routes are read-only pass-throughs to mobile-api. -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET as getEvents } from "./events/route"; -import { GET as getSummary } from "./[eventId]/route"; - -const req = (path: string) => new Request(`http://localhost${path}`) as unknown as Parameters[0]; -const ctx = (eventId: string) => ({ params: Promise.resolve({ eventId }) }); - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset().mockResolvedValue("jwt-abc"); -}); - -describe("GET /api/admin/event-summary/events", () => { - it("forwards to mobile-api with the admin JWT", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: [{ id: "5" }] }); - const res = await getEvents(req("/api/admin/event-summary/events")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual([{ id: "5" }]); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/events", { token: "jwt-abc" }); - }); - - it("is 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await getEvents(req("/api/admin/event-summary/events"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); - -describe("GET /api/admin/event-summary/[eventId]", () => { - it("forwards the event id and the day", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { orders: 3 } }); - const res = await getSummary(req("/api/admin/event-summary/5?date=2026-10-06&x=1"), ctx("5")); - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?date=2026-10-06", { token: "jwt-abc" }); - }); - - it("forwards without a day when none is given", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5", { token: "jwt-abc" }); - }); - - it("is 400 for a non-numeric id or a malformed day, without calling mobile-api", async () => { - expect((await getSummary(req("/api/admin/event-summary/5;x"), ctx("5;x"))).status).toBe(400); - expect((await getSummary(req("/api/admin/event-summary/5?date=06-10-2026"), ctx("5"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards a Date From / Date To range", async () => { // BABYBOO-39 - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5?from=2026-10-14&to=2026-10-16&x=1"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?from=2026-10-14&to=2026-10-16", { token: "jwt-abc" }); - }); - - it("forwards from, to and the older date together", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5?to=2026-10-16&date=2026-10-14&from=2026-10-14"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?date=2026-10-14&from=2026-10-14&to=2026-10-16", { token: "jwt-abc" }); - }); - - it("is 400 for a malformed from or to, without calling mobile-api", async () => { - expect((await getSummary(req("/api/admin/event-summary/5?from=14-10-2026"), ctx("5"))).status).toBe(400); - expect((await getSummary(req("/api/admin/event-summary/5?from=2026-10-14&to=2026-10"), ctx("5"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes a downstream 403 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_EVENT_SUMMARY module is required." }); - expect((await getSummary(req("/api/admin/event-summary/5"), ctx("5"))).status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts deleted file mode 100644 index e42f954..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -const ctx = () => ({ params: Promise.resolve({ uuid: "12345" }) }); - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/12345/action", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/[uuid]/action", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ action: "approve", remarks: "" }), ctx()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a non-numeric uuid (path traversal) with 400 before calling upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "approve", remarks: "" }), { params: Promise.resolve({ uuid: "../../member/x" }) }); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects action=delete with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "delete", remarks: "test" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects action=pending with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "pending", remarks: "test" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects reject action with blank remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "reject", remarks: "" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects reject action with whitespace-only remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "reject", remarks: " " }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects revoke action with blank remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "revoke", remarks: "" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("accepts approve with empty remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "A" } }); - - const res = await POST(postReq({ action: "approve", remarks: "" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/approve", { - method: "POST", - body: { action: "approve", remarks: "" }, - token: "jwt-abc", - }); - }); - - it("accepts reject with non-blank remarks (≤500 chars)", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "R" } }); - - const res = await POST(postReq({ action: "reject", remarks: "Document expired on 2025-01-01" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/reject", { - method: "POST", - body: { action: "reject", remarks: "Document expired on 2025-01-01" }, - token: "jwt-abc", - }); - }); - - it("accepts revoke with remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "V" } }); - - const res = await POST(postReq({ action: "revoke", remarks: "Admin correction" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/revoke", { - method: "POST", - body: { action: "revoke", remarks: "Admin correction" }, - token: "jwt-abc", - }); - }); - - it("rejects remarks > 500 chars", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const longRemarks = "x".repeat(501); - const res = await POST(postReq({ action: "reject", remarks: longRemarks }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts deleted file mode 100644 index 8769a47..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { AdminKycRow } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/{uuid}/action { action, remarks } (BO_KYC gated upstream; a mutation, -// never a GET). action ∈ { approve, reject, revoke }. reject/revoke require non-blank remarks ≤ 500 chars. - -const ALLOWED_ACTIONS = new Set(["approve", "reject", "revoke"]); - -export async function POST(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { uuid } = await ctx.params; - // uuid is a Snowflake id carried as a string; anything else never reaches the upstream path. - if (!/^\d+$/.test(uuid)) return badRequest("Parameter \"uuid\" is invalid"); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { action, remarks } = (body ?? {}) as { action?: unknown; remarks?: unknown }; - - if (typeof action !== "string" || !ALLOWED_ACTIONS.has(action)) { - return badRequest("Parameter \"action\" must be one of: approve, reject, revoke"); - } - - const remarksStr = typeof remarks === "string" ? remarks : ""; - - // reject/revoke require non-blank remarks, max 500 chars. - if ((action === "reject" || action === "revoke") && !remarksStr.trim()) { - return badRequest("Remarks are required for this action"); - } - if (remarksStr.length > 500) { - return badRequest("Remarks must not exceed 500 characters"); - } - - const result = await callMobileApi(`/api/admin/kyc/${encodeURIComponent(uuid)}/${action}`, { - method: "POST", - body: { action, remarks: remarksStr }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts deleted file mode 100644 index 99972bf..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ getToken: vi.fn() })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function req(url = "http://localhost/api/admin/kyc/12345/doc/ID_FRONT") { - const u = new URL(url); - return { nextUrl: u } as unknown as Parameters[0]; -} -const ctx = (uuid = "12345", docType = "ID_FRONT") => ({ params: Promise.resolve({ uuid, docType }) }); - -const originalFetch = global.fetch; - -beforeEach(() => { - mocks.getToken.mockReset(); - process.env.MOBILE_API_BASE_URL = "http://gateway"; - process.env.MOBILE_API_KEY = "secret-key"; -}); -afterEach(() => { - global.fetch = originalFetch; -}); - -describe("GET /api/admin/kyc/[uuid]/doc/[docType]", () => { - it("returns 401 without a session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx()); - expect(res.status).toBe(401); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("rejects docType=PASSPORT with 400 and never calls upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "PASSPORT")); - - expect(res.status).toBe(400); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("rejects docType=DRIVING_LICENSE with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "DRIVING_LICENSE")); - - expect(res.status).toBe(400); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("returns upstream bytes with no-store for allowed docTypes", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const imgBytes = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0]); // JPEG marker - const upstream = new Response(imgBytes, { - status: 200, - headers: { "content-type": "image/jpeg" }, - }); - const fetchSpy = vi.fn().mockResolvedValue(upstream); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "ID_FRONT")); - - expect(res.status).toBe(200); - expect(res.headers.get("Cache-Control")).toBe("no-store"); - expect(res.headers.get("content-type")).toBe("image/jpeg"); - const body = new Uint8Array(await res.arrayBuffer()); - expect(Array.from(body)).toEqual([0xFF, 0xD8, 0xFF, 0xE0]); - }); - - it("returns upstream bytes for SELFIE", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const pngBytes = new Uint8Array([0x89, 0x50, 0x4E, 0x47]); - const upstream = new Response(pngBytes, { - status: 200, - headers: { "content-type": "image/png" }, - }); - const fetchSpy = vi.fn().mockResolvedValue(upstream); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("67890", "SELFIE")); - - expect(res.status).toBe(200); - const body = new Uint8Array(await res.arrayBuffer()); - expect(Array.from(body)).toEqual([0x89, 0x50, 0x4E, 0x47]); - }); - - // F20: the proxy is served from the admin origin with the admin's cookie; a stored non-image type must never render - it("never passes a non-image upstream type through, and forbids sniffing", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const type of ["text/html", "image/svg+xml", "application/xhtml+xml", "text/html; charset=utf-8"]) { - global.fetch = vi.fn().mockResolvedValue( - new Response("", { status: 200, headers: { "content-type": type } }), - ) as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "SELFIE")); - - expect(res.headers.get("content-type")).toBe("application/octet-stream"); - expect(res.headers.get("x-content-type-options")).toBe("nosniff"); - } - }); - - it("keeps an image type and forbids sniffing", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - global.fetch = vi.fn().mockResolvedValue( - new Response(new Uint8Array([1]), { status: 200, headers: { "content-type": "Image/PNG; foo=bar" } }), - ) as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "ID_BACK")); - - expect(res.headers.get("content-type")).toBe("image/png"); - expect(res.headers.get("x-content-type-options")).toBe("nosniff"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts deleted file mode 100644 index 67324f7..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { SAFE_BINARY_HEADERS, safeContentType } from "@/app/lib/server/binaryProxy"; -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { unauthorized } from "@/app/lib/server/apiRoute"; -import { isTraversalPath } from "@/app/lib/server/upstreamPathGuard"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// GET -> mobile-api GET /api/admin/kyc/{uuid}/doc/{docType} — streams KYC document image bytes. -// A binary proxy: callMobileApi normalizes JSON, so this route does a raw fetch and passes the -// image bytes + Content-Type through. Authorization is the BO_KYC module grant, enforced -// server-side by mobile-api. Read-only — no side effect on GET (Next.js prefetch-safe). -// Allowed docTypes: ID_FRONT, ID_BACK, SELFIE. - -const TIMEOUT_MS = 30_000; - -const ALLOWED_DOC_TYPES = new Set(["ID_FRONT", "ID_BACK", "SELFIE"]); - -function jsonError(message: string, status: number) { - return NextResponse.json({ error: message }, { status }); -} - -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string; docType: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { docType, uuid } = await ctx.params; - - // Only allow known doc types — never call upstream with an arbitrary path segment. - if (!/^\d+$/.test(uuid)) return jsonError("Invalid uuid", 400); - if (!ALLOWED_DOC_TYPES.has(docType)) { - return jsonError(`Unsupported doc type: ${encodeURIComponent(docType)}`, 400); - } - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return jsonError("Mobile API is not configured", 500); - - // Fetched directly, so callMobileApi's dot-segment guard is applied here too. - const path = `/api/admin/kyc/${encodeURIComponent(uuid)}/doc/${encodeURIComponent(docType)}`; - if (isTraversalPath(path)) return jsonError("Invalid uuid", 400); - const forwardedIp = await forwardedClientIpHeaders(); - const url = `${base}${path}`; - - let res: Response; - try { - res = await fetch(url, { - method: "GET", - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return jsonError("Couldn't reach the KYC service", 502); - } - - if (!res.ok) { - if (res.status === 401) return unauthorized(); - if (res.status === 404) return jsonError("Document not found.", 404); - if (res.status === 403) return jsonError("Not authorized.", 403); - if (res.status >= 500) return jsonError("The KYC service failed.", 502); - return jsonError("Couldn't download the document.", 400); - } - - const body = await res.arrayBuffer(); - const headers = new Headers({ - // KYC documents are JPEG or PNG only (mobile-api KycUploadRules); F20: nothing else renders on this origin - "Content-Type": safeContentType(res.headers.get("content-type"), ["image/jpeg", "image/png"]), - "Cache-Control": "no-store", - ...SAFE_BINARY_HEADERS, - }); - const disposition = res.headers.get("content-disposition"); - if (disposition) headers.set("Content-Disposition", disposition); - return new NextResponse(body, { status: 200, headers }); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts deleted file mode 100644 index 4b68b17..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/12345") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/[uuid]", () => { - it("rejects a non-numeric uuid with 400 before calling upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await GET(getReq(), { params: Promise.resolve({ uuid: "abc" }) }); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq(), { params: Promise.resolve({ uuid: "12345" }) }); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards uuid to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ - ok: true, - data: { record: {}, docTypes: [], member: {}, history: [], warnings: [] }, - }); - - await GET(getReq(), { params: Promise.resolve({ uuid: "12345" }) }); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345", { token: "jwt-abc" }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts deleted file mode 100644 index 3ec4a60..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute"; -import type { AdminKycDetail } from "@/app/lib/types"; - -// GET -> /api/admin/kyc/{uuid} (read-only; BO_KYC gated upstream). - -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { uuid } = await ctx.params; - // uuid is a Snowflake id carried as a string; anything else never reaches the upstream path. - if (!/^\d+$/.test(uuid)) return badRequest("Parameter \"uuid\" is invalid"); - const result = await callMobileApi(`/api/admin/kyc/${encodeURIComponent(uuid)}`, { - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts deleted file mode 100644 index 3e4f78f..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/counts") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/counts", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - }); - - it("forwards to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { P: 1, A: 2, R: 0, V: 0, ALL: 3 } }); - - const res = await GET(getReq()); - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/counts", { token: "jwt-abc" }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/counts/route.ts b/solvway-admin-portal/app/api/admin/kyc/counts/route.ts deleted file mode 100644 index 3b7e1f7..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/counts/route.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { AdminKycCounts } from "@/app/lib/types"; - -// GET -> /api/admin/kyc/counts (read-only; BO_KYC gated upstream). - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const result = await callMobileApi("/api/admin/kyc/counts", { token }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts deleted file mode 100644 index 08d66ce..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/export") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/export", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - }); - - it("forwards query params (minus page/size) to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] }); - - await GET(getReq("http://localhost/api/admin/kyc/export?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=10")); - - // page/size should be absent from the export call - const [path] = mocks.callMobileApi.mock.calls[0]; - expect(path).toContain("status=P"); - expect(path).toContain("q=ahmad"); - expect(path).not.toContain("page="); - expect(path).not.toContain("size="); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/export/route.ts b/solvway-admin-portal/app/api/admin/kyc/export/route.ts deleted file mode 100644 index 77b89c0..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/export/route.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import { TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; - -// GET -> /api/admin/kyc/export?status=&q=&from=&to=&channel= (same filters as list but no page/size; read-only; BO_KYC gated upstream). - -const QUERY = { - status: TEXT, - q: TEXT, - from: TEXT, - to: TEXT, - channel: TEXT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - // Export does NOT carry page/size, so they are not in its allow-list. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/kyc/export${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/route.test.ts deleted file mode 100644 index 531b063..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/route.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards query params to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0, page: 0, size: 10 } }); - - await GET(getReq("http://localhost/api/admin/kyc?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=20")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/kyc?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=20", - { token: "jwt-abc" }, - ); - }); - - it("omits absent query params", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0, page: 0, size: 10 } }); - - await GET(getReq()); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc", { token: "jwt-abc" }); - }); - - it("returns 200 on success", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const payload = { content: [], totalElements: 0, page: 0, size: 10 }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: payload }); - - const res = await GET(getReq()); - expect(res.status).toBe(200); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/route.ts b/solvway-admin-portal/app/api/admin/kyc/route.ts deleted file mode 100644 index 9fe50da..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/route.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; -import type { AdminKycPage } from "@/app/lib/types"; - -// GET -> /api/admin/kyc?status=&q=&from=&to=&channel=&page=&size= (read-only; BO_KYC gated upstream). - -const QUERY = { - status: TEXT, - q: TEXT, - from: TEXT, - to: TEXT, - channel: TEXT, - ...paging(500), - ...SORT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/kyc${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts deleted file mode 100644 index d35a14a..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/submit", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/submit", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST( - postReq({ - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }), - ); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the submit body to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "999", status: "P" } }); - - const res = await POST( - postReq({ - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }), - ); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/submit", { - method: "POST", - body: { - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }, - token: "jwt-abc", - }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/submit/route.ts b/solvway-admin-portal/app/api/admin/kyc/submit/route.ts deleted file mode 100644 index 0b242bd..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/submit/route.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { AdminKycRow } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/submit { memberCode, submitName, identityType, identityNo, docs } -// (BO_KYC gated upstream; a mutation, never a GET). - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { memberCode, submitName, identityType, identityNo, docs } = (body ?? {}) as { - memberCode?: unknown; - submitName?: unknown; - identityType?: unknown; - identityNo?: unknown; - docs?: unknown; - }; - - if (typeof memberCode !== "string" || !memberCode) { - return badRequest("Parameter \"memberCode\" is required"); - } - if (typeof submitName !== "string" || !submitName) { - return badRequest("Parameter \"submitName\" is required"); - } - if (typeof identityType !== "string" || !identityType) { - return badRequest("Parameter \"identityType\" is required"); - } - if (typeof identityNo !== "string" || !identityNo) { - return badRequest("Parameter \"identityNo\" is required"); - } - - const result = await callMobileApi("/api/admin/kyc/submit", { - method: "POST", - body: { memberCode, submitName, identityType, identityNo, docs }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts deleted file mode 100644 index b638417..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/upload", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/upload", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "data" })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the upload body to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { reference: "ref-123" } }); - - const res = await POST( - postReq({ memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "base64data" }), - ); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/upload", { - method: "POST", - body: { memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "base64data" }, - token: "jwt-abc", - }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/upload/route.ts b/solvway-admin-portal/app/api/admin/kyc/upload/route.ts deleted file mode 100644 index aa362db..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/upload/route.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { KycUploadResult } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/upload { memberCode, docType, fileType, base } (BO_KYC gated upstream; -// a mutation, never a GET). - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { memberCode, docType, fileType, base } = (body ?? {}) as { - memberCode?: unknown; - docType?: unknown; - fileType?: unknown; - base?: unknown; - }; - - if (typeof memberCode !== "string" || !memberCode) { - return badRequest("Parameter \"memberCode\" is required"); - } - - const result = await callMobileApi("/api/admin/kyc/upload", { - method: "POST", - body: { memberCode, docType, fileType, base }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts b/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts deleted file mode 100644 index aea8e9e..0000000 --- a/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(qs: string) { - return new Request(`http://localhost/api/admin/member-corrections${qs}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/member-corrections", () => { - it("forwards the query string with the admin JWT and returns the page", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const page = { content: [], totalElements: 0 }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: page }); - - const res = await GET(getReq("?type=RANK&memberCode=MY1&page=1&size=20")); - - expect(res.status).toBe(200); - expect(await res.json()).toEqual(page); - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/member-corrections?type=RANK&memberCode=MY1&page=1&size=20", - { token: "jwt-abc" }, - ); - }); - - it("forwards no query string when there is none", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } }); - - await GET(getReq("")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/member-corrections", { token: "jwt-abc" }); - }); - - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - - const res = await GET(getReq("")); - - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/member-corrections/route.ts b/solvway-admin-portal/app/api/admin/member-corrections/route.ts deleted file mode 100644 index 955d6b7..0000000 --- a/solvway-admin-portal/app/api/admin/member-corrections/route.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; -import type { AdminMemberCorrectionPage } from "@/app/lib/types"; - -// GET -> /api/admin/member-corrections (BABYBOO-43): admin rank and referral corrections, newest -// first. Forwards the query string (type, memberCode, from, to, page, size) with the bb_admin JWT. Read-only — -// no side effect on GET (Next.js prefetch-safe). BO_RANK_REFERRAL is enforced upstream. - -const QUERY = { - type: TEXT, - memberCode: TEXT, - from: TEXT, - to: TEXT, - ...paging(500), - ...SORT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/member-corrections${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts deleted file mode 100644 index f1ce24c..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { unauthorized } from "@/app/lib/server/apiRoute"; -import { expiredSignal, isId } from "@/app/lib/server/messagesProxy"; -import { isTraversalPath } from "@/app/lib/server/upstreamPathGuard"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// GET -> mobile-api GET /api/admin/member-messages/{uuid}/messages/{messageUuid}/images/{index}: streams a -// private message image. Raw fetch (callMobileApi normalises JSON). Side-effect free, so prefetch-safe. -const TIMEOUT_MS = 120_000; // covers the piped body too, so a slow link can finish a 5 MB image -const IMAGE_TYPES = new Set(["image/jpeg", "image/png"]); -const err = (message: string, status: number) => NextResponse.json({ error: message }, { status }); - -export async function GET( - _req: NextRequest, - ctx: { params: Promise<{ uuid: string; messageUuid: string; index: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - const { uuid, messageUuid, index } = await ctx.params; - if (!isId(uuid) || !isId(messageUuid) || !/^\d{1,2}$/.test(index)) return err("Invalid image reference", 400); - // Fetched directly, so callMobileApi's dot-segment guard is applied here too. - const path = `/api/admin/member-messages/${encodeURIComponent(uuid)}/messages/${encodeURIComponent(messageUuid)}/images/${encodeURIComponent(index)}`; - if (isTraversalPath(path)) return err("Invalid image reference", 400); - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return err("Mobile API is not configured", 500); - - const forwardedIp = await forwardedClientIpHeaders(); - - let res: Response; - try { - res = await fetch(`${base}${path}`, { - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return err("Couldn't reach the messaging service", 502); - } - if (!res.ok) { - if (expiredSignal(res.status, await res.text().catch(() => ""))) return unauthorized(); - if (res.status === 404) return err("Image not found.", 404); - if (res.status === 403) return err("Not authorized.", 403); - return err("Couldn't load the image.", res.status >= 500 ? 502 : 400); - } - // Served from the origin that holds the admin session: never pass an upstream type through unchecked. - const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase(); - return new NextResponse(res.body, { - status: 200, - headers: { - "Content-Type": IMAGE_TYPES.has(type) ? type : "application/octet-stream", - "Cache-Control": "private, no-store", - "X-Content-Type-Options": "nosniff", - }, - }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts deleted file mode 100644 index af48bf8..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -type Ctx = { params: Promise<{ uuid: string }> }; - -// GET -> /api/admin/member-messages/{uuid}/messages?before=&size= POST -> same path { body, imageRefs }. -export async function GET(req: NextRequest, ctx: Ctx) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/messages`, "GET", { query: ["before", "size"] }); -} - -export async function POST(req: NextRequest, ctx: Ctx) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/messages`, "POST", { body: true }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts deleted file mode 100644 index 3ed8a98..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// POST -> mobile-api POST /api/admin/member-messages/{uuid}/read (a mutation, never a GET). -export async function POST(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/read`, "POST"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts deleted file mode 100644 index 265e8e2..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/{uuid}. -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}`, "GET"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts deleted file mode 100644 index bfbdc56..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts/{broadcastUuid}/recipients?unreadOnly=&page=&size=. -export async function GET(req: NextRequest, ctx: { params: Promise<{ broadcastUuid: string }> }) { - const { broadcastUuid } = await ctx.params; - if (!isId(broadcastUuid)) return badRequest('Parameter "broadcastUuid" is invalid'); - return relay(req, `/broadcasts/${encodeURIComponent(broadcastUuid)}/recipients`, "GET", { query: ["unreadOnly", "page", "size", "sortBy", "sortDir"] }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts deleted file mode 100644 index f4e5302..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts/{broadcastUuid}. -export async function GET(req: NextRequest, ctx: { params: Promise<{ broadcastUuid: string }> }) { - const { broadcastUuid } = await ctx.params; - if (!isId(broadcastUuid)) return badRequest('Parameter "broadcastUuid" is invalid'); - return relay(req, `/broadcasts/${encodeURIComponent(broadcastUuid)}`, "GET"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts deleted file mode 100644 index cb162c6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// POST -> mobile-api POST /api/admin/member-messages/broadcasts/preview { target }. -export const POST = (req: NextRequest) => relay(req, "/broadcasts/preview", "POST", { body: true }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts deleted file mode 100644 index b2c5fc6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts (q, sortBy, sortDir, page, size): one summary row per broadcast. -export const GET = (req: NextRequest) => - relay(req, "/broadcasts", "GET", { query: ["q", "sortBy", "sortDir", "page", "size"] }); - -// POST -> mobile-api POST /api/admin/member-messages/broadcasts { target, subject, body, imageRefs }. -export const POST = (req: NextRequest) => relay(req, "/broadcasts", "POST", { body: true }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts b/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts deleted file mode 100644 index bf17bc6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/by-key (query forwarded: member). -export const GET = (req: NextRequest) => relay(req, "/by-key", "GET", { query: ["member"] }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/images/route.ts b/solvway-admin-portal/app/api/admin/member-messages/images/route.ts deleted file mode 100644 index 78db3b4..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/images/route.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, unauthorized } from "@/app/lib/server/apiRoute"; -import { codeOf, codeResponse, expiredSignal } from "@/app/lib/server/messagesProxy"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// POST multipart { file } -> mobile-api POST /api/admin/member-messages/images -> { ref }. TWO-STEP upload: -// the ref is committed by mobile-api when the message is sent (abandoned uploads are reaped, intended). -const ALLOWED = new Set(["image/jpeg", "image/png"]); -const MAX_BYTES = 5 * 1024 * 1024; -const TIMEOUT_MS = 30_000; - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - // Refuse an oversized declared body before buffering it (formData() reads everything into memory). - if (Number(req.headers?.get("content-length") ?? 0) > MAX_BYTES + 64 * 1024) { - return badRequest("Image must be 5 MB or smaller", { code: "MESSAGE_INVALID" }); - } - - let file: unknown; - try { - file = (await req.formData()).get("file"); - } catch { - return badRequest("Invalid request body"); - } - if (!(file instanceof File)) return badRequest('Parameter "file" is required'); - if (!ALLOWED.has(file.type)) return badRequest("Only JPEG or PNG images are allowed", { code: "MESSAGE_INVALID" }); - if (file.size > MAX_BYTES) return badRequest("Image must be 5 MB or smaller", { code: "MESSAGE_INVALID" }); - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return NextResponse.json({ error: "Mobile API is not configured" }, { status: 500 }); - - const forwardedIp = await forwardedClientIpHeaders(); - - const form = new FormData(); - form.set("file", file, file.name); - let res: Response; - try { - res = await fetch(`${base}/api/admin/member-messages/images`, { - method: "POST", - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, // no Content-Type: fetch sets the boundary - body: form, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return NextResponse.json({ error: "Couldn't reach the messaging service" }, { status: 502 }); - } - const text = await res.text(); - let data: Record = {}; - try { - data = text ? JSON.parse(text) : {}; - } catch { - /* non-JSON upstream body: fall through to the generic message */ - } - if (!res.ok) { - if (expiredSignal(res.status, text)) return unauthorized(); - const code = codeOf(text); // matches the code field or a reason text that carries it - if (code) return codeResponse(code); - const message = (data.detail as string) || (data.message as string) || (data.error as string) || "Upload failed"; - const status = res.status >= 400 && res.status < 500 ? res.status : 502; - return NextResponse.json({ error: message }, { status }); - } - // A 200 without a ref would let the UI send a message pointing at nothing. - if (typeof data.ref !== "string") return NextResponse.json({ error: "Upload failed" }, { status: 502 }); - return NextResponse.json({ ref: data.ref }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/route.ts b/solvway-admin-portal/app/api/admin/member-messages/route.ts deleted file mode 100644 index 77ae2d5..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages (query forwarded: types, unreadOnly, q, page, size). -export const GET = (req: NextRequest) => relay(req, "", "GET", { query: ["types", "unreadOnly", "q", "page", "size", "sortBy", "sortDir"] }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts b/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts deleted file mode 100644 index a5406d1..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import type { NextRequest } from "next/server"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET as listBroadcasts } from "./broadcasts/route"; -import { GET as summary } from "./broadcasts/[broadcastUuid]/route"; -import { GET as recipients } from "./broadcasts/[broadcastUuid]/recipients/route"; - -// BABYBOO-56 broadcast read count: read-only BFF relays. -const B = "http://localhost/api/admin/member-messages"; -const req = (url: string) => new Request(url, { method: "GET" }) as unknown as NextRequest; -const ctx = (broadcastUuid: string) => ({ params: Promise.resolve({ broadcastUuid }) }); -const lastCall = () => { - const [url, opts] = mocks.callMobileApi.mock.calls.at(-1)!; - const [path, qs = ""] = String(url).split("?"); - return { path, sp: new URLSearchParams(qs), opts }; -}; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { fine: 1 } }); - mocks.getToken.mockReset().mockResolvedValue("jwt"); - process.env.MOBILE_API_BASE_URL = "http://up"; - process.env.MOBILE_API_KEY = "k"; -}); - -describe("GET broadcasts summaries relay", () => { - it("forwards q, page and size to mobile-api with the session token", async () => { - const res = await listBroadcasts(req(`${B}/broadcasts?q=raya&page=1&size=20`)); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, sp, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts"); - expect([sp.get("q"), sp.get("page"), sp.get("size")]).toEqual(["raya", "1", "20"]); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await listBroadcasts(req(`${B}/broadcasts?page=0&size=20`))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Something odd", status: 500 }); - expect((await listBroadcasts(req(`${B}/broadcasts?page=0&size=20`))).status).toBeGreaterThanOrEqual(400); - }); -}); - -describe("GET broadcast recipients relay", () => { - it("forwards the uuid, unreadOnly, page and size", async () => { - const res = await recipients(req(`${B}/broadcasts/b1/recipients?unreadOnly=true&page=2&size=20`), ctx("b1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, sp, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts/b1/recipients"); - expect([sp.get("unreadOnly"), sp.get("page"), sp.get("size")]).toEqual(["true", "2", "20"]); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await recipients(req(`${B}/broadcasts/b1/recipients`), ctx("b1"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a path-like broadcast id before any upstream call", async () => { - const res = await recipients(req(`${B}/broadcasts/x/recipients`), ctx("../admin")); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream 404 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Broadcast not found", status: 404 }); - expect((await recipients(req(`${B}/broadcasts/b1/recipients`), ctx("b1"))).status).toBe(404); - }); -}); - -describe("GET single broadcast summary relay", () => { - it("forwards the uuid to mobile-api with the session token", async () => { - const res = await summary(req(`${B}/broadcasts/b1`), ctx("b1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts/b1"); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await summary(req(`${B}/broadcasts/b1`), ctx("b1"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a path-like broadcast id with 400 before any upstream call", async () => { - expect((await summary(req(`${B}/broadcasts/x`), ctx("../admin"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream 404 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Broadcast not found", status: 404 }); - expect((await summary(req(`${B}/broadcasts/b1`), ctx("b1"))).status).toBe(404); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts b/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts deleted file mode 100644 index 8c2e4cd..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import type { NextRequest } from "next/server"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET as list } from "./route"; -import { GET as byKey } from "./by-key/route"; -import { GET as messages } from "./[uuid]/messages/route"; -import { POST as upload } from "./images/route"; -import { GET as image } from "./[uuid]/messages/[messageUuid]/images/[index]/route"; - -const B = "http://localhost/api/admin/member-messages"; -const get = (url: string) => new Request(url) as unknown as NextRequest; -const img = (messageUuid = "m1") => ({ params: Promise.resolve({ uuid: "c1", messageUuid, index: "0" }) }); -const formReq = (fd: FormData, headers: Record = {}) => - ({ headers: new Headers(headers), formData: async () => fd }) as unknown as NextRequest; -const pngForm = () => { - const fd = new FormData(); - fd.append("file", new File(["abc"], "a.png", { type: "image/png" })); - return fd; -}; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }); - mocks.getToken.mockReset().mockResolvedValue("jwt"); - process.env.MOBILE_API_BASE_URL = "http://up"; - process.env.MOBILE_API_KEY = "k"; -}); -afterEach(() => vi.unstubAllGlobals()); - -describe("query whitelist", () => { - it("forwards only the documented query keys", async () => { - await list(get(`${B}?types=S&q=x&page=1&size=20&unreadOnly=true&reader=M:MY3&adminUsername=eve`)); - await byKey(get(`${B}/by-key?member=MY5&reader=M:MY3`)); - await messages(get(`${B}/c1/messages?before=m9&size=30&reader=M:MY3`), { params: Promise.resolve({ uuid: "c1" }) }); - const urls = mocks.callMobileApi.mock.calls.map((c) => c[0] as string); - expect(urls[0]).toBe("/api/admin/member-messages?types=S&unreadOnly=true&q=x&page=1&size=20"); - expect(urls[1]).toBe("/api/admin/member-messages/by-key?member=MY5"); - expect(urls[2]).toBe("/api/admin/member-messages/c1/messages?before=m9&size=30"); - }); - - it("passes a module-denied 403 through for the blocked state", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_MEMBER_MESSAGES module is required." }); - const res = await list(get(B)); - expect(res.status).toBe(403); - }); -}); - -describe("upload", () => { - it("refuses a declared body far over 5 MB before reading it", async () => { - const formData = vi.fn(); - const fetchMock = vi.fn(); - vi.stubGlobal("fetch", fetchMock); - const res = await upload({ headers: new Headers({ "content-length": String(7 * 1024 * 1024) }), formData } as unknown as NextRequest); - expect(res.status).toBe(400); - expect(formData).not.toHaveBeenCalled(); - expect(fetchMock).not.toHaveBeenCalled(); - }); - - it("forwards the file under the `file` field", async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ref: "messages/admin/1.png" }), { status: 200 })); - vi.stubGlobal("fetch", fetchMock); - const res = await upload(formReq(pngForm())); - expect(await res.json()).toEqual({ ref: "messages/admin/1.png" }); - expect((fetchMock.mock.calls[0][1].body as FormData).get("file")).toBeInstanceOf(File); - }); - - it("answers 502 when a 200 reply has no ref", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("", { status: 200 }))); - expect((await upload(formReq(pngForm()))).status).toBe(502); - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", { status: 200 }))); - expect((await upload(formReq(pngForm()))).status).toBe(502); - }); - - it("maps mobile-api's expired-token 500 to 401", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("JWT expired token", { status: 500 }))); - expect((await upload(formReq(pngForm()))).status).toBe(401); - }); -}); - -describe("image stream", () => { - it("never serves a non-image type as-is and sets nosniff", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("" } }); - fireEvent.click(screen.getByRole("button", { name: "Show editor" })); - const last = onChange.mock.calls.at(-1)?.[0] as string; - expect(last).toContain("

Pasted

"); - expect(last).not.toContain("script"); - }); - - it("passes HTML typed in Show HTML to the form before switching back", async () => { - const { onChange } = await mount("

x

"); - fireEvent.click(screen.getByRole("button", { name: "Show HTML" })); - fireEvent.change(screen.getByLabelText("HTML source"), { target: { value: "

Pasted

" } }); - expect(onChange).toHaveBeenLastCalledWith("

Pasted

"); - }); - - it("refuses a non-https YouTube link", async () => { - const { onChange } = await mount("

x

"); - const prompt = vi.spyOn(window, "prompt").mockReturnValueOnce("http://www.youtube.com/watch?v=dQw4w9WgXcQ"); - fireEvent.click(screen.getByRole("button", { name: "YouTube video" })); - expect(onChange).not.toHaveBeenCalled(); - prompt.mockRestore(); - }); - - it("emits an empty string when the text is cleared", async () => { - const { container, onChange } = await mount("

x

"); - act(() => { editorOf(container).commands.clearContent(true); }); - expect(onChange).toHaveBeenLastCalledWith(""); - }); - - it("keeps an image-only document", async () => { - const { container, onChange } = await mount("

x

"); - act(() => { editorOf(container).commands.setContent('', { emitUpdate: true }); }); - expect(onChange.mock.calls.at(-1)?.[0]).toContain(' { - const { container } = await mount("## Head\n\n- one"); - expect(container.querySelector(".ProseMirror h2")?.textContent).toBe("Head"); - expect(container.querySelector(".ProseMirror li")?.textContent).toBe("one"); - }); - - it("loads a value that arrives after mount", async () => { - const onChange = vi.fn(); - const { container, rerender } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - rerender(); - await waitFor(() => expect(container.querySelector(".ProseMirror")?.textContent).toBe("Loaded")); - expect(onChange).not.toHaveBeenCalled(); - }); - - it("disables editing when disabled", async () => { - const { container } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - expect(container.querySelector(".ProseMirror")?.getAttribute("contenteditable")).toBe("false"); - expect(screen.getByRole("button", { name: "Bold" })).toBeDisabled(); - }); - it("uploads a picked image and inserts it", async () => { - const onChange = vi.fn(); - const onUploadImage = vi.fn().mockResolvedValue("https://s3.test/bucket/product/1.png"); - const { container } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - const file = new File(["png"], "a.png", { type: "image/png" }); - fireEvent.change(screen.getByLabelText("Upload image"), { target: { files: [file] } }); - await waitFor(() => expect(onChange.mock.calls.at(-1)?.[0]).toContain('src="https://s3.test/bucket/product/1.png"')); - expect(onUploadImage).toHaveBeenCalledWith(file); - }); - - it("shows an upload error and inserts nothing when the upload fails", async () => { - const onChange = vi.fn(); - const onUploadImage = vi.fn().mockRejectedValue(new Error("Upload failed")); - const { container } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - fireEvent.change(screen.getByLabelText("Upload image"), { target: { files: [new File(["x"], "a.png", { type: "image/png" })] } }); - expect(await screen.findByText("Upload failed")).toBeInTheDocument(); - expect(onChange).not.toHaveBeenCalled(); - }); - - it("flags an off-site image and leaves trusted ones alone", async () => { - render( -

'} - onChange={vi.fn()} - onUploadImage={vi.fn()} - trustedImageHosts={["s3.test"]} - />, - ); - expect(await screen.findByText(/cdn\.shopify\.com\/a\.png/)).toBeInTheDocument(); - expect(screen.queryByText(/s3\.test\/bucket\/b\.png/)).not.toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Re-upload to Babyboo" })).toBeInTheDocument(); - }); - - it("re-uploads an off-site image and swaps its src", async () => { - const onChange = vi.fn(); - const onUploadImage = vi.fn().mockResolvedValue("https://s3.test/bucket/product/9.png"); - // jsdom's Response cannot wrap a Blob, so stub only what the editor reads. - const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({ - ok: true, - blob: async () => new Blob(["png"], { type: "image/png" }), - } as Response); - render( -

'} onChange={onChange} - onUploadImage={onUploadImage} trustedImageHosts={["s3.test"]} />, - ); - fireEvent.click(await screen.findByRole("button", { name: "Re-upload to Babyboo" })); - await waitFor(() => expect(onChange.mock.calls.at(-1)?.[0]).toContain('src="https://s3.test/bucket/product/9.png"')); - expect(onChange.mock.calls.at(-1)?.[0]).not.toContain("cdn.shopify.com"); - expect((onUploadImage.mock.calls[0][0] as File).type).toBe("image/png"); - await waitFor(() => expect(screen.queryByRole("button", { name: "Re-upload to Babyboo" })).not.toBeInTheDocument()); - fetchMock.mockRestore(); - }); - - it("shows the manual fallback when the fetch fails", async () => { - const onChange = vi.fn(); - const fetchMock = vi.spyOn(globalThis, "fetch").mockRejectedValue(new TypeError("Failed to fetch")); - render( -

'} onChange={onChange} - onUploadImage={vi.fn()} trustedImageHosts={["s3.test"]} />, - ); - fireEvent.click(await screen.findByRole("button", { name: "Re-upload to Babyboo" })); - expect(await screen.findByText(/Couldn't copy this image/)).toBeInTheDocument(); - expect(onChange).not.toHaveBeenCalled(); - fetchMock.mockRestore(); - }); - - it("hides the image button when no upload function is given", async () => { - await mount("

x

"); - expect(screen.queryByLabelText("Upload image")).not.toBeInTheDocument(); - }); - - it("places Image between Link and YouTube when uploads are enabled", async () => { - const { container } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - const names = screen.getAllByRole("button").map((b) => b.getAttribute("aria-label")); - expect(names.slice(names.indexOf("Link"), names.indexOf("Link") + 3)).toEqual(["Link", "Image", "YouTube video"]); - }); - it("inserts a picked emoji at the cursor", async () => { - const { container, onChange } = await mount("

Hi

"); - act(() => { editorOf(container).commands.focus("end"); }); - fireEvent.click(screen.getByRole("button", { name: "Emoji" })); - fireEvent.click(await screen.findByText("pick-bottle")); - expect(onChange).toHaveBeenLastCalledWith("

Hi🍼

"); - }); - it("shows a size counter near the limit", async () => { - await mount(`

${"a".repeat(58000)}

`); - expect(screen.getByText(/KB of 64 KB/)).toBeInTheDocument(); - }); - - it("shows no counter for a normal description", async () => { - await mount("

short

"); - expect(screen.queryByText(/KB of 64 KB/)).not.toBeInTheDocument(); - }); - - it("gives every toolbar control a hover title equal to its label", async () => { - render(); - await waitFor(() => expect(document.querySelector(".ProseMirror")).not.toBeNull()); - expect(screen.getByRole("button", { name: "Bold" })).toHaveAttribute("title", "Bold"); - expect(screen.getByLabelText("Text style")).toHaveAttribute("title", "Text style"); - expect(screen.getByLabelText("Text colour")).toHaveAttribute("title", "Text colour"); - const controls = Array.from(screen.getByRole("toolbar").querySelectorAll("button, select, input:not([hidden])")) as HTMLElement[]; - expect(controls.length).toBeGreaterThan(15); - for (const el of controls) { - expect(el, el.outerHTML.slice(0, 80)).toHaveAttribute("title", el.getAttribute("aria-label")!); - } - }); - - it("titles the image button and the Show HTML toggle", async () => { - render(); - await waitFor(() => expect(document.querySelector(".ProseMirror")).not.toBeNull()); - expect(screen.getByRole("button", { name: "Image" })).toHaveAttribute("title", "Image"); - expect(screen.getByRole("button", { name: "Emoji" })).toHaveAttribute("title", "Emoji"); - const toggle = screen.getByRole("button", { name: "Show HTML" }); - expect(toggle).toHaveAttribute("title", "Show HTML"); - }); -}); diff --git a/solvway-admin-portal/app/components/products/RichTextEditor.tsx b/solvway-admin-portal/app/components/products/RichTextEditor.tsx deleted file mode 100644 index 4d609d7..0000000 --- a/solvway-admin-portal/app/components/products/RichTextEditor.tsx +++ /dev/null @@ -1,329 +0,0 @@ -"use client" - -import { useEffect, useRef, useState, type ChangeEvent, type ReactNode } from "react" -import { renderToStaticMarkup } from "react-dom/server" -import { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react" -import StarterKit from "@tiptap/starter-kit" -import TextAlign from "@tiptap/extension-text-align" -import { Color, TextStyle } from "@tiptap/extension-text-style" -import Image from "@tiptap/extension-image" -import Youtube from "@tiptap/extension-youtube" -import { TableKit } from "@tiptap/extension-table" -import { - AlignCenter, AlignLeft, AlignRight, Bold, Code, Eraser, ImagePlus, Italic, Link as LinkIcon, List, ListOrdered, - Minus, Quote, Smile, SquarePlay, Strikethrough, Table as TableIcon, Underline, -} from "lucide-react" - -import { EmojiPicker } from "frimousse" - -import { Button } from "@/app/components/ui/button" -import { Markdown } from "@/app/components/ui/markdown" -import { Popover, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover" -import { Textarea } from "@/app/components/ui/textarea" -import { useT } from "@/app/lib/i18n/MessagesProvider" - -export interface RichTextEditorProps { - id?: string - /** Marks the editing area aria-invalid, for a save error shown beside it. */ - invalid?: boolean - value: string - onChange: (html: string) => void - disabled?: boolean - onUploadImage?: (file: File) => Promise - trustedImageHosts?: string[] -} - -const SAFE_LINK = /^(https?:|mailto:)/i - -/** Stored value → editor HTML. Legacy Markdown descriptions are rendered once and saved back as HTML. */ -export function toEditorHtml(value: string): string { - if (!value.trim()) return "" - if (/^\s*{value}) -} - -function htmlOf(editor: Editor): string { - return editor.isEmpty ? "" : editor.getHTML() -} - -/** - * Shopify-style visual editor for the product Long Description (add-rich-text-long-description). - * Emits HTML; the storefront sanitises it on render. Tiptap's schema drops anything the toolbar - * cannot produce, including pasted scripts. - */ -export function RichTextEditor({ id, invalid, value, onChange, disabled, onUploadImage, trustedImageHosts = [] }: RichTextEditorProps) { - const t = useT() - const [source, setSource] = useState(null) - const [emojiOpen, setEmojiOpen] = useState(false) - const emitted = useRef(value) - // Current editor HTML, for the off-site image notice. - const [html, setHtml] = useState(() => toEditorHtml(value)) - - const editor = useEditor({ - immediatelyRender: false, - editable: !disabled, - content: toEditorHtml(value), - extensions: [ - StarterKit.configure({ - heading: { levels: [2, 3, 4] }, - // No auto-appended empty paragraph after a trailing heading/table: it would be stored. - trailingNode: false, - link: { openOnClick: false, protocols: ["http", "https", "mailto"], isAllowedUri: (url) => SAFE_LINK.test(url) }, - }), - TextStyle, - Color, - TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }), - // Inline, as in Shopify: a pasted

stays one paragraph instead of gaining an empty one. - Image.configure({ inline: true }), - Youtube.configure({ nocookie: true }), - TableKit, - ], - editorProps: { attributes: { ...(id ? { id } : {}), ...(invalid ? { "aria-invalid": "true" } : {}), class: "min-h-[160px] px-3 py-2 text-sm outline-none" } }, - onUpdate: ({ editor }) => { - const html = htmlOf(editor) - emitted.current = html - setHtml(html) - onChange(html) - }, - }) - - useEffect(() => { - if (editor && value !== emitted.current) { - emitted.current = value - editor.commands.setContent(toEditorHtml(value), { emitUpdate: false }) - setHtml(toEditorHtml(value)) - } - }, [editor, value]) - - useEffect(() => { - editor?.setEditable(!disabled, false) - }, [editor, disabled]) - - const state = useEditorState({ - editor, - selector: ({ editor }) => ({ - level: editor?.isActive("heading") ? String(editor.getAttributes("heading").level) : "0", - color: (editor?.getAttributes("textStyle").color as string | undefined) ?? "#000000", - active: Object.fromEntries( - ["bold", "italic", "underline", "strike", "bulletList", "orderedList", "blockquote", "link"].map((n) => [n, editor?.isActive(n) ?? false]), - ) as Record, - }), - }) - - function run(fn: (e: Editor) => void) { - if (editor) fn(editor) - } - - const fileInput = useRef(null) - const [uploaded, setUploaded] = useState([]) - const [imageError, setImageError] = useState(null) - const [busy, setBusy] = useState(false) - - const trusted = new Set([...trustedImageHosts, ...uploaded]) - const offsiteSrcs = Array.from( - new Set(Array.from(new DOMParser().parseFromString(html, "text/html").images, (img) => img.getAttribute("src") ?? "")), - ).filter((src) => { - try { return !trusted.has(new URL(src).host) } catch { return true } - }) - - // ponytail: images removed from the text stay in the public bucket (orphans); diff old/new srcs on save and delete them if storage growth matters. - async function upload(file: File): Promise { - const url = await onUploadImage!(file) - setUploaded((hosts) => [...hosts, new URL(url).host]) - return url - } - - function openImagePicker() { - fileInput.current?.click() - } - - async function pickImage(event: ChangeEvent) { - const file = event.target.files?.[0] - event.target.value = "" - if (!file || !editor) return - setImageError(null) - setBusy(true) - try { - const src = await upload(file) - editor.chain().focus().setImage({ src }).run() - } catch (err) { - setImageError(err instanceof Error ? err.message : "CatUploadImageFailed") - } finally { - setBusy(false) - } - } - - function addLink() { - const url = window.prompt(t("RtePromptLink")) - if (!url) return - if (!SAFE_LINK.test(url)) return - run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run()) - } - - async function reupload(src: string) { - if (!editor) return - setImageError(null) - setBusy(true) - try { - let blob: Blob - try { - const res = await fetch(src) - if (!res.ok) throw new Error(String(res.status)) - blob = await res.blob() - if (!blob.type.startsWith("image/")) throw new Error("not an image") - } catch { - setImageError("RteCopyFailed") - return - } - const name = new URL(src).pathname.split("/").pop() || "image" - const next = await upload(new File([blob], name, { type: blob.type })) - const { tr } = editor.state - editor.state.doc.descendants((node, pos) => { - if (node.type.name === "image" && node.attrs.src === src) tr.setNodeMarkup(pos, undefined, { ...node.attrs, src: next }) - }) - editor.view.dispatch(tr) - } catch (err) { - setImageError(err instanceof Error ? err.message : "CatUploadImageFailed") - } finally { - setBusy(false) - } - } - - function addYoutube() { - const src = window.prompt(t("RtePromptYoutube")) - // https only: the storefront drops any other embed. - if (src && /^https:\/\//i.test(src)) run((e) => e.chain().focus().setYoutubeVideo({ src }).run()) - } - - function toggleSource() { - if (!editor) return - if (source === null) { - setSource(htmlOf(editor)) - return - } - editor.commands.setContent(source, { emitUpdate: true }) - setSource(null) - } - - const off = disabled || !editor || source !== null || busy - const btn = (label: string, icon: ReactNode, onClick: () => void, active?: boolean) => ( - - ) - - return ( -
-
- - {btn(t("RteBold"), , () => run((e) => e.chain().focus().toggleBold().run()), state?.active.bold)} - {btn(t("RteItalic"), , () => run((e) => e.chain().focus().toggleItalic().run()), state?.active.italic)} - {btn(t("RteUnderline"), , () => run((e) => e.chain().focus().toggleUnderline().run()), state?.active.underline)} - {btn(t("RteStrikethrough"), , () => run((e) => e.chain().focus().toggleStrike().run()), state?.active.strike)} - { - const color = (ev.target as HTMLInputElement).value - run((e) => e.chain().focus().setColor(color).run()) - }} - onChange={() => {}} /> - {btn(t("RteAlignLeft"), , () => run((e) => e.chain().focus().setTextAlign("left").run()))} - {btn(t("RteAlignCentre"), , () => run((e) => e.chain().focus().setTextAlign("center").run()))} - {btn(t("RteAlignRight"), , () => run((e) => e.chain().focus().setTextAlign("right").run()))} - {btn(t("RteBulletList"), , () => run((e) => e.chain().focus().toggleBulletList().run()), state?.active.bulletList)} - {btn(t("RteNumberedList"), , () => run((e) => e.chain().focus().toggleOrderedList().run()), state?.active.orderedList)} - {btn(t("RteQuote"), , () => run((e) => e.chain().focus().toggleBlockquote().run()), state?.active.blockquote)} - {btn(t("RteDivider"), , () => run((e) => e.chain().focus().setHorizontalRule().run()))} - {btn(t("RteLink"), , addLink, state?.active.link)} - {onUploadImage ? ( - <> - - - - ) : null} - {btn(t("RteYoutube"), , addYoutube)} - {btn(t("RteTable"), , () => run((e) => e.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()))} - - - - - - { - run((e) => e.chain().focus().insertContent(emoji).run()) - setEmojiOpen(false) - }} - > - - - {t("Loading")} - {t("RteEmojiEmpty")} - - - - - - {btn(t("RteClearFormatting"), , () => run((e) => e.chain().focus().unsetAllMarks().clearNodes().run()))} - -
- - {source !== null ? ( -