Spaces:
Running

File size: 21,694 Bytes
10963b9
 
 
a7cb154
 
 
10963b9
 
 
d28c7f4
264507b
d28c7f4
10963b9
0d070f3
264507b
 
 
 
 
 
 
 
0d070f3
a7cb154
 
 
d28c7f4
 
0d070f3
10963b9
264507b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10963b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75bceac
 
 
 
d28c7f4
 
 
 
 
 
 
 
 
10963b9
 
 
 
 
 
 
 
 
 
 
 
 
2efd444
10963b9
 
 
e5495e1
 
 
 
 
10963b9
e5495e1
 
2329257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5495e1
 
 
 
 
2329257
 
 
 
 
e5495e1
 
 
 
 
 
 
 
 
 
 
 
10963b9
 
a7cb154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d28c7f4
 
 
 
 
a7cb154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264507b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7cb154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175408e
37e6657
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175408e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d070f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10963b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/**
 * ADMIN USERS — User management endpoints
 *
 * Procedures: users (paginated list), updateUserRole,
 *             pendingApprovals / approveUser / rejectUser / resendApprovalEmail
 *             (the ADMIN APPROVAL GATE queue, owner directive 2026-11-24)
 */

import { users } from "@db/schema";
import { TRPCError } from "@trpc/server";
import { and, asc, count, desc, eq, inArray, sql } from "drizzle-orm";
import { z } from "zod";
import type { SafeUser } from "./context";
import { evictAllUserAuthCache, evictUserAuthCache } from "./context";
import {
  adminAlertEmail,
  bulkDecisionInputSchema,
  decideApproval,
  notifyAdminsOfRegistration,
  summarizeBulkResults,
} from "./lib/approval";
import type { ApprovalAction } from "./lib/approval";
import { getApprovalGateConfig } from "./lib/approval-gate-config";
import { maybeSendWelcomeEmail } from "./lib/email-drip";
import { env } from "./lib/env";
import { logger, maskEmail } from "./lib/logger";
import { adminMutation, adminQuery } from "./middleware";
import { getDb } from "./queries/connection";
import { invalidateSettingsCache } from "./lib/cache";

/**
 * Shared bulk runner — one implementation behind bulkApproveUsers /
 * bulkRejectUsers so the two buttons stay perfectly symmetrical.
 *
 *  - Duplicate ids are collapsed (the UI cannot produce them, but the API
 *    must stay idempotent under a retrying client).
 *  - Emails are snapshotted BEFORE deciding (approve needs them for the
 *    deferred welcome drip, mirroring the single approveUser path).
 *  - Per-row decisions run through decideApproval — the SAME state machine
 *    as the single actions: approve only lifts pending rows; reject skips
 *    admins (protected) and already-rejected rows; the acceptance notice
 *    (email + in-app) fires per decided row from inside decideApproval.
 *  - Independent rows: one bad row degrades to a skip entry, never aborts
 *    the batch.
 */
async function runBulkDecision(action: ApprovalAction, userIds: number[], adminUserId: number) {
  const db = getDb();
  const unique = [...new Set(userIds)];

  const targets = await db
    .select({ id: users.id, username: users.username, name: users.name, email: users.email })
    .from(users)
    .where(inArray(users.id, unique));
  const targetById = new Map(targets.map((t) => [t.id, t]));

  const entries = await Promise.all(
    unique.map(async (userId) => ({
      userId,
      result: await decideApproval({ userId, action, adminUserId, source: "dashboard" }),
    })),
  );
  const summary = summarizeBulkResults(entries);

  if (action === "approve") {
    for (const decidedId of summary.decidedIds) {
      const target = targetById.get(decidedId);
      if (target?.email) {
        void maybeSendWelcomeEmail(decidedId, target.username, target.email, target.name || target.username);
      }
    }
  }

  logger.info("[Admin] bulk approval decision applied", {
    action,
    adminUserId,
    requested: unique.length,
    decided: summary.decided,
    skipped: summary.skipped.length,
  });
  return summary;
}

export const adminUsersProcedures = {
  // Users list — used by Admin.tsx frontend (trpc.admin.users.useQuery)
  users: adminQuery
    .input(z.object({ page: z.number().int().min(1).default(1), limit: z.number().int().min(1).max(100).default(20) }).optional())
    .query(async ({ input }) => {
      const db = getDb();
      const page = input?.page ?? 1;
      const limit = input?.limit ?? 20;
      const offset = (page - 1) * limit;

      const [[{ total }], allUsers] = await Promise.all([
        db.select({ total: count() }).from(users),
        db.select({
          id: users.id,
          username: users.username,
          name: users.name,
          email: users.email,
          avatar: users.avatar,
          role: users.role,
          preferredLanguage: users.preferredLanguage,
          // ✅ SECURITY FIX (audit run-2): SafeUser is now a curated Pick<> that
          // includes emailVerifiedAt — the admin list select must carry it for
          // the `as SafeUser[]` cast to hold.
          emailVerifiedAt: users.emailVerifiedAt,
          // ✅ ROOT-CURE (owner report 2026-11-26, "user says the admin confirmed
          // his email but the site still asks him to log in every time"): the
          // all-users table previously had NO gate column — a pending user looked
          // identical to an approved one, while emailVerifiedAt ('verified ✓')
          // actively suggested the account was done. The owner could not see
          // WHO was blocked or WHY. The REAL gate state now rides with every
          // row so the dashboard surfaces it (see Admin.tsx status column).
          approvalStatus: users.approvalStatus,
          approvalDecidedAt: users.approvalDecidedAt,
          createdAt: users.createdAt,
          updatedAt: users.updatedAt,
          lastSignInAt: users.lastSignInAt,
        })
          .from(users)
          .orderBy(desc(users.createdAt))
          .limit(limit)
          .offset(offset),
      ]);

      return { items: allUsers as SafeUser[], total: total ?? 0 };
    }),

  updateUserRole: adminMutation
    .input(z.object({ userId: z.number().int().positive(), role: z.enum(["user", "admin"]) }))
    .mutation(async ({ input }) => {
      const db = getDb();
      const [user] = await db
        .select({ id: users.id, role: users.role, tokenVersion: users.tokenVersion })
        .from(users)
        .where(eq(users.id, input.userId))
        .limit(1);
      if (!user) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
      if (user.role === input.role) return { success: true }; // no-op

      if (input.role === "user" && user.role === "admin") {
        // ✅ SECURITY FIX (audit run-1, fp admin-users.updateUserRole
        // .last-admin-guard.race-to-zero-admins): the old guard was a separate
        // SELECT-then-act — two concurrent demotes both read "admins = 2" and
        // BOTH demoted, leaving zero administrators, and ADMIN_RECOVERY cannot
        // restore the role (it has nobody to promote). The guard now travels
        // WITH the write: one conditional UPDATE that only fires while more
        // than one admin remains. MySQL forbids selecting the target table in
        // a subquery (ERROR 1093) — the derived table materializes it.
        // Concurrent demotes serialize on the row lock: the winner affects 1
        // row, the loser 0 rows → clean BAD_REQUEST, never zero admins.
        const [updateResult] = await db
          .update(users)
          .set({ role: input.role, tokenVersion: user.tokenVersion + 1, updatedAt: new Date() })
          .where(
            and(
              eq(users.id, input.userId),
              eq(users.role, "admin"),
              sql`(SELECT adminCount FROM (SELECT COUNT(*) AS adminCount FROM users WHERE role = 'admin') AS adminGuard) > 1`,
            ),
          );
        const affected = Number((updateResult as unknown as { affectedRows?: number }).affectedRows ?? 0);
        if (affected === 0) {
          // Zero rows: either a concurrent demote already removed this admin
          // (intent satisfied — success) or this IS the last admin (guard).
          const [fresh] = await db
            .select({ role: users.role })
            .from(users)
            .where(eq(users.id, input.userId))
            .limit(1);
          if (fresh && fresh.role !== "admin") {
            evictUserAuthCache(user.id);
            return { success: true };
          }
          throw new TRPCError({
            code: "BAD_REQUEST",
            message: "لا يمكن إزالة صلاحية المشرف الأخير — يجب أن يبقى مشرف واحد على الأقل",
          });
        }
        // ✅ INSTANT EFFECT: tokenVersion bump (in the same SET) kills ALL of
        // the target's existing sessions immediately, and the auth cache is
        // evicted so even the 30s user-cache window cannot serve the old role.
        evictUserAuthCache(user.id);
        return { success: true };
      }

      // ✅ INSTANT EFFECT (dashboard audit 2026-11-15): bump tokenVersion so a
      // role change kills ALL of the target's existing sessions immediately
      // (a demoted admin is locked out on their very next request instead of
      // riding a stale session for up to the token lifetime), and evict the
      // auth cache so even the 30s user-cache window cannot serve the old role.
      await db
        .update(users)
        .set({ role: input.role, tokenVersion: user.tokenVersion + 1, updatedAt: new Date() })
        .where(eq(users.id, input.userId));
      evictUserAuthCache(user.id);
      return { success: true };
    }),

  // ─── ADMIN APPROVAL GATE (owner directive, 2026-11-24) ────────────────────
  // The owner's authority over who may enter the platform: a live queue of
  // pending registrations + approve/reject actions. Reject also revokes any
  // live session (tokenVersion bump inside decideApproval) — "ألغاء دخول أي
  // حد في أي وقت" works even for accounts that are logged in right now.

  pendingApprovals: adminQuery
    .query(async () => {
      const db = getDb();
      const [rows, [{ pending }]] = await Promise.all([
        db
          .select({
            id: users.id,
            username: users.username,
            name: users.name,
            email: users.email,
            role: users.role,
            preferredLanguage: users.preferredLanguage,
            createdAt: users.createdAt,
            // ✅ ROOT-CURE (2026-11-26): the queue shows whether the registrant
            // already completed THEIR part (email confirmation) — the only thing
            // left is the owner's decision, so "email confirmed but can't enter"
            // reports become one-glance diagnosable.
            emailVerifiedAt: users.emailVerifiedAt,
          })
          .from(users)
          .where(eq(users.approvalStatus, "pending"))
          .orderBy(asc(users.createdAt))
          .limit(200),
        db.select({ pending: count() }).from(users).where(eq(users.approvalStatus, "pending")),
      ]);
      return { items: rows, total: pending ?? 0 };
    }),

  approveUser: adminMutation
    .input(z.object({ userId: z.number().int().positive() }))
    .mutation(async ({ ctx, input }) => {
      // Snapshot the email BEFORE the decision — approveUser also kicks off
      // the welcome drip (deferred from registration while the account was
      // locked out).
      const db = getDb();
      const [target] = await db
        .select({ username: users.username, name: users.name, email: users.email, role: users.role, approvalStatus: users.approvalStatus })
        .from(users)
        .where(eq(users.id, input.userId))
        .limit(1);
      if (!target) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });

      const result = await decideApproval({
        userId: input.userId,
        action: "approve",
        adminUserId: ctx.user.id,
        source: "dashboard",
      });
      if (!result.ok) {
        if (result.reason === "not_found") throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
        throw new TRPCError({ code: "BAD_REQUEST", message: "هذا الحساب ليس في انتظار الموافقة" });
      }

      // Deferred welcome drip (best-effort) — the account is now usable.
      if (target.email) {
        void maybeSendWelcomeEmail(input.userId, target.username, target.email, target.name || target.username);
      }
      return { success: true, status: result.status };
    }),

  rejectUser: adminMutation
    .input(z.object({ userId: z.number().int().positive() }))
    .mutation(async ({ ctx, input }) => {
      const result = await decideApproval({
        userId: input.userId,
        action: "reject",
        adminUserId: ctx.user.id,
        source: "dashboard",
      });
      if (!result.ok) {
        if (result.reason === "not_found") throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
        throw new TRPCError({ code: "BAD_REQUEST", message: "لا يمكن رفض هذا الحساب في حالته الحالية (حسابات المشرفين محمية)" });
      }
      return { success: true, status: result.status };
    }),

  // ── ✅ BULK DECISIONS (owner directive, 2026-12-01): "امكانية ان اقدر
  // اختار مجموعه كبيرة اللي عاوزها وعملها موافقة مرة واحدة ... واختيار كمية
  // كبيرة ارفضهم مرة واحدة". ONE call decides the whole batch through the
  // SAME decideApproval state machine per row (no duplicated security
  // logic): approve only moves pending rows; reject skips admins and
  // already-rejected rows. Decisions inside a batch are independent — one
  // bad row never aborts the others. The per-user acceptance notification
  // (email + in-app stream) rides decideApproval itself, so a 150-account
  // batch fans out exactly like 150 single approvals. The deferred welcome
  // drip mirrors the single approveUser path.

  bulkApproveUsers: adminMutation
    .input(z.object({ userIds: bulkDecisionInputSchema }))
    .mutation(async ({ ctx, input }) => {
      const summary = await runBulkDecision("approve", input.userIds, ctx.user.id);
      return {
        success: true,
        action: "approve" as const,
        total: summary.decided + summary.skipped.length,
        decided: summary.decided,
        decidedIds: summary.decidedIds,
        skipped: summary.skipped,
      };
    }),

  bulkRejectUsers: adminMutation
    .input(z.object({ userIds: bulkDecisionInputSchema }))
    .mutation(async ({ ctx, input }) => {
      const summary = await runBulkDecision("reject", input.userIds, ctx.user.id);
      return {
        success: true,
        action: "reject" as const,
        total: summary.decided + summary.skipped.length,
        decided: summary.decided,
        decidedIds: summary.decidedIds,
        skipped: summary.skipped,
      };
    }),

  resendApprovalEmail: adminMutation
    .input(z.object({ userId: z.number().int().positive() }))
    .mutation(async ({ input }) => {
      const to = adminAlertEmail();
      if (!to) {
        throw new TRPCError({ code: "BAD_REQUEST", message: "لم يُضبط بريد التنبيه (ADMIN_ALERT_EMAIL) على الخادم" });
      }
      const db = getDb();
      const [target] = await db
        .select({ username: users.username, name: users.name, email: users.email, approvalStatus: users.approvalStatus })
        .from(users)
        .where(eq(users.id, input.userId))
        .limit(1);
      if (!target) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
      if (target.approvalStatus !== "pending") {
        throw new TRPCError({ code: "BAD_REQUEST", message: "هذا الحساب ليس في انتظار الموافقة" });
      }
      const base = env.FRONTEND_URL;
      await notifyAdminsOfRegistration({
        userId: input.userId,
        username: target.username,
        name: target.name,
        email: target.email,
        frontendUrl: base,
      });
      logger.info("[Admin] approval email re-sent", { userId: input.userId, to: maskEmail(to) });
      return { success: true };
    }),

  // ✅ EMAIL DELIVERY VISIBILITY (owner report 2026-11-26): the last email
  // send outcomes from the bounded email_delivery_log ledger (migration
  // v22) — the dashboard can now answer "did the approval alert actually
  // go out, and if not, WHY" without any server-log access. Read-only,
  // best-effort: a missing table (pre-migration boot race) degrades to an
  // empty list instead of erroring the tab.
  emailDeliveryLog: adminQuery
    .query(async () => {
      const db = getDb();
      try {
        const [rows] = await db.execute(sql`
          SELECT id, at, class, toMasked, ok, providerStatus, reason
          FROM email_delivery_log
          ORDER BY id DESC
          LIMIT 10
        `) as unknown as [Array<{
          id: number; at: string; class: string; toMasked: string;
          ok: number; providerStatus: string | null; reason: string | null;
        }>, unknown];
        const items = (rows || []).map((r) => ({
          id: r.id,
          at: r.at,
          class: r.class,
          toMasked: r.toMasked,
          ok: !!r.ok,
          providerStatus: r.providerStatus,
          reason: r.reason,
        }));
        const lastAlert = items.find((r) => r.class === "approval-alert") ?? null;
        return { items, lastAlert, fromEmail: env.RESEND_FROM_EMAIL };
      } catch {
        // Ledger not created yet (boot race) — degrade to empty, never error.
        return { items: [], lastAlert: null, fromEmail: env.RESEND_FROM_EMAIL };
      }
    }),

  // ✅ ROOT FIX (owner report 2026-11-24, "راجع المشكلة من جذورها"): the v17
  // migration grandfathered every PRE-GATE account as 'approved' — the owner
  // signed in with his old @AHMEDBAZ account and the gate never stopped him.
  // The owner's authority must reach those accounts too: re-open puts ANY
  // non-admin account back into the pending queue (gate panel + alert email
  // with signed action links) and KILLS its live session (tokenVersion bump
  // + cache eviction — pending means no access, not just "no NEW sessions").
  reopenApproval: adminMutation
    .input(z.object({ userId: z.number().int().positive() }))
    .mutation(async ({ ctx, input }) => {
      const db = getDb();
      const [target] = await db
        .select({
          username: users.username,
          name: users.name,
          email: users.email,
          role: users.role,
          approvalStatus: users.approvalStatus,
          tokenVersion: users.tokenVersion,
        })
        .from(users)
        .where(eq(users.id, input.userId))
        .limit(1);
      if (!target) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
      // The authority can never be re-gated out of its own platform.
      if (target.role === "admin") {
        throw new TRPCError({ code: "BAD_REQUEST", message: "لا يمكن إعادة فتح مراجعة حسابات المشرفين" });
      }
      if (target.approvalStatus === "pending") {
        throw new TRPCError({ code: "BAD_REQUEST", message: "هذا الحساب بانتظار المراجعة بالفعل" });
      }

      await db
        .update(users)
        .set({
          approvalStatus: "pending",
          approvalDecidedAt: null,
          approvalDecidedByUserId: null,
          // Same semantics as reject: an account whose access the owner is
          // re-deciding must not keep the session it holds right now.
          tokenVersion: target.tokenVersion + 1,
        })
        .where(eq(users.id, input.userId));
      evictUserAuthCache(input.userId);
      logger.info("[Admin] approval re-opened — account re-gated to pending, live session revoked", {
        userId: input.userId,
        username: target.username,
        by: ctx.user.id,
      });

      // Owner alert (best-effort): in-app stream + the approval email with
      // fresh signed action links — the owner decides from inbox or dashboard.
      void notifyAdminsOfRegistration({
        userId: input.userId,
        username: target.username,
        name: target.name,
        email: target.email,
        frontendUrl: env.FRONTEND_URL,
      }).catch((notifyErr) => {
        logger.warn("[Admin] reopen alert failed (best-effort)", {
          userId: input.userId,
          error: notifyErr instanceof Error ? notifyErr.message : String(notifyErr),
        });
      });
      return { success: true, status: "pending" as const };
    }),

  // ── ✅ OWNER SWITCH (2026-12-01): the approval-gate toggle ────────────────
  // The owner's dashboard switch for the WHOLE gate. ON (default, the
  // 2026-11-24 contract): registrations land pending and need an explicit
  // approval. OFF: registrations approve themselves and already-pending
  // accounts pass through (rejected accounts stay blocked — a rejection is
  // the owner's permanent decision). State lives in the `approvalGate`
  // siteSettings section (cache-backed reader: lib/approval-gate-config.ts,
  // fails closed to ON); flipping it ALSO evicts the whole user auth cache so
  // cached sessions re-evaluate on the very next request.
  approvalGate: adminQuery
    .query(async () => {
      const cfg = await getApprovalGateConfig();
      return { enabled: cfg.enabled };
    }),

  setApprovalGate: adminMutation
    .input(z.object({ enabled: z.boolean() }))
    .mutation(async ({ ctx, input }) => {
      const db = getDb();
      // Same single-statement UPSERT the settings router uses (the table has
      // a UNIQUE (section, key) contract).
      await db.execute(
        sql`INSERT INTO siteSettings (\`section\`, \`key\`, \`value\`, \`type\`, \`sortOrder\`)
         VALUES ('approvalGate', 'enabled', ${input.enabled ? "true" : "false"}, 'text', 0)
         ON DUPLICATE KEY UPDATE \`value\` = VALUES(\`value\`)`,
      );
      // Drop BOTH caches: the settings cache (config re-read) and the user
      // auth cache (every session re-evaluates the gate on its next request).
      await invalidateSettingsCache();
      evictAllUserAuthCache();
      logger.info("[Admin] approval gate switched", { enabled: input.enabled, by: ctx.user.id });
      return { success: true, enabled: input.enabled };
    }),
};