summaryrefslogtreecommitdiff
path: root/src/index.ts
blob: 22c9024bf2c3f1ccd6a6333f4ce285135bb6b7b1 (plain)
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import "dotenv/config";

import express from "express";
import expressWs from "express-ws";
import type * as ws from "ws";

import signupRouter from "./routes/signup";
import signinRouter from "./routes/signin";
import kidRouter from "./routes/kid";
import parentRouter from "./routes/parent";

import * as jose from "jose";
import {
  notificationScanQueue,
  storeNotification,
  getRecentNotifications,
} from "./queue/notification_scan";
import {
  accessibilityScanQueue,
  storeAccessibilityMessage,
  getRecentAccessibilityMessages,
} from "./queue/accessibility_scan";
import "./queue/push_notification";
import { db } from "./db/db";
import { linkedDevices, deviceConfig, users, alerts } from "./db/schema";
import { eq } from "drizzle-orm";
import { pushNotificationQueue } from "./queue/push_notification";
import { pinoHttp } from "pino-http";
import { logger } from "./lib/pino";

logger.info("Starting Buddy Backend server...");

const { app } = expressWs(express());

app.use(express.json());
app.use(pinoHttp({ logger }));

app.use("/", signupRouter);
app.use("/", signinRouter);
app.use("/", kidRouter);

/** Tracks which devices are currently connected via WebSocket */
const onlineDevices = new Map<number, { connectedAt: number }>();

interface ChildJwtPayload extends jose.JWTPayload {
  type: "child";
  id: number;
}

type KidWebSocket = ws.WebSocket & { deviceId: number | null };

app.use("/", parentRouter(onlineDevices));

app.ws("/kid/connect", (ws, req) => {
  logger.info({ ip: req.ip }, "New WebSocket connection to /kid/connect");

  (ws as unknown as KidWebSocket).deviceId = null;

  ws.on("message", async (msg) => {
    let data: Record<string, unknown> | undefined;
    try {
      data = JSON.parse(msg.toString()) as Record<string, unknown>;
    } catch {
      ws.send(JSON.stringify({ success: false, reason: "Invalid JSON" }));
      return;
    }

    console.log(data);

    if (data.type === "token") {
      try {
        const publicKey = process.env.JWT_PUBLIC_KEY!;
        const spki = await jose.importSPKI(publicKey, "RS256");
        const { payload } = await jose.jwtVerify(data.token as string, spki, {
          audience: "urn:buddy:devices",
          issuer: "urn:lajosh:buddy",
        });

        if ((payload as ChildJwtPayload).type !== "child") {
          ws.send(
            JSON.stringify({ success: false, reason: "Invalid token type" }),
          );
          return;
        }

        const deviceId = (payload as ChildJwtPayload).id;

        (ws as unknown as KidWebSocket).deviceId = deviceId;

        logger.info(
          { deviceId },
          "WebSocket client authenticated successfully",
        );

        onlineDevices.set(deviceId, { connectedAt: Date.now() });
        await db
          .update(linkedDevices)
          .set({ lastOnline: Math.floor(Date.now() / 1000) })
          .where(eq(linkedDevices.id, deviceId));

        ws.send(
          JSON.stringify({
            success: true,
            type: "token",
            message: "authenticated",
          }),
        );
      } catch {
        ws.send(JSON.stringify({ success: false, reason: "Invalid token" }));
      }

      return;
    }

    if (data.type === "notification") {
      const deviceId = (ws as unknown as KidWebSocket).deviceId;
      if (!deviceId) {
        ws.send(
          JSON.stringify({ success: false, reason: "Not authenticated" }),
        );
        return;
      }

      try {
        const notification = {
          title: data.title as string,
          message: data.message as string,
          packageName: data.packageName as string,
          timestamp: Math.floor(Date.now() / 1000),
        };

        // Store the notification in Redis with 72-hour TTL
        await storeNotification(deviceId, notification);

        // Get all recent notifications (last 72 hours) for context
        const recentNotifications = await getRecentNotifications(deviceId);

        await notificationScanQueue.add("scanNotification", {
          deviceId,
          notification,
          recentNotifications,
        });

        logger.info(
          {
            deviceId,
            packageName: data.packageName,
            contextNotificationsCount: recentNotifications.length,
          },
          "Notification queued for scanning with context",
        );

        ws.send(JSON.stringify({ success: true, todo: "queued" }));
      } catch (e) {
        logger.error({ error: e, deviceId }, "Failed to enqueue notification");
        ws.send(
          JSON.stringify({
            success: false,
            reason: "Failed to queue notification",
          }),
        );
      }

      return;
    }

    if (data.type === "status_ping") {
      const { dev_enabled } = data;

      const deviceId = (ws as unknown as KidWebSocket).deviceId;
      if (!deviceId) {
        ws.send(
          JSON.stringify({ success: false, reason: "Not authenticated" }),
        );
        return;
      }

      const userDevice = await db
        .select()
        .from(linkedDevices)
        .where(eq(linkedDevices.id, deviceId))
        .limit(1);

      const config = await db
        .select()
        .from(deviceConfig)
        .where(eq(deviceConfig.deviceId, deviceId))
        .limit(1);

      if (config.length > 0 && !config[0]!.familyLinkAntiCircumvention) {
        return;
      }

      if (userDevice[0]?.devEnabled === false && dev_enabled === true) {
        await db
          .update(linkedDevices)
          .set({ devEnabled: true })
          .where(eq(linkedDevices.id, deviceId));

        const device = await db
          .select()
          .from(linkedDevices)
          .where(eq(linkedDevices.id, deviceId))
          .limit(1);

        if (device.length > 0) {
          const parentId = device[0]!.parentId;
          const deviceName = device[0]!.nickname;

          const parent = await db
            .select({ pushTokens: users.pushTokens })
            .from(users)
            .where(eq(users.id, parentId))
            .limit(1);

          if (
            parent.length > 0 &&
            parent[0]!.pushTokens &&
            parent[0]!.pushTokens.length > 0
          ) {
            await pushNotificationQueue.add("dev-mode-enabled-alert", {
              pushTokens: parent[0]!.pushTokens,
              notification: {
                title: `⚠️ Possible circumvention attempt detected`,
                body: `Developer mode was enabled on ${deviceName}, allowing the use of ADB to kill Buddy and Family Link`,
                data: {
                  type: "dev_mode_enabled",
                  screen: "DeviceDetail",
                  deviceId: deviceId.toString(),
                  deviceName: deviceName,
                },
                channelId: "alerts",
              },
            });

            await db.insert(alerts).values({
              deviceId: deviceId,
              parentId: parentId,
              category: "circumvention",
              title: "Possible circumvention detected",
              message: `Developer mode was enabled on ${deviceName}`,
              summary: `Developer mode was enabled on ${deviceName}, allowing the use of ADB to kill Buddy and Family Link. This could be an attempt to bypass parental controls.`,
              confidence: 90,
              packageName: null,
              timestamp: Math.floor(Date.now() / 1000),
              read: false,
            });
          }
        }
      }

      if (userDevice[0]?.devEnabled === true && dev_enabled === false) {
        await db
          .update(linkedDevices)
          .set({ devEnabled: false })
          .where(eq(linkedDevices.id, deviceId));
      }

      return;
    }

    if (data.type === "contact_added") {
      logger.info("Contact added message received from device");
      const deviceId = (ws as unknown as KidWebSocket).deviceId;
      if (!deviceId) {
        ws.send(
          JSON.stringify({ success: false, reason: "Not authenticated" }),
        );
        return;
      }

      try {
        let contactType = "unknown";
        let contactIdentifier = "";

        if (
          data.phoneNumbers &&
          Array.isArray(data.phoneNumbers) &&
          data.phoneNumbers.length > 0
        ) {
          contactType = "phone";
          contactIdentifier = data.phoneNumbers.join(", ");
        } else if (
          data.emails &&
          Array.isArray(data.emails) &&
          data.emails.length > 0
        ) {
          contactType = "email";
          contactIdentifier = data.emails.join(", ");
        }

        const device = await db
          .select()
          .from(linkedDevices)
          .where(eq(linkedDevices.id, deviceId))
          .limit(1);

        if (device.length > 0) {
          const parentId = device[0]!.parentId;
          const deviceName = device[0]!.nickname;

          const config = await db
            .select()
            .from(deviceConfig)
            .where(eq(deviceConfig.deviceId, deviceId))
            .limit(1);

          const shouldNotify =
            config.length === 0 || config[0]!.notifyNewContactAdded;

          if (shouldNotify) {
            const parent = await db
              .select({ pushTokens: users.pushTokens })
              .from(users)
              .where(eq(users.id, parentId))
              .limit(1);

            if (
              parent.length > 0 &&
              parent[0]!.pushTokens &&
              parent[0]!.pushTokens.length > 0
            ) {
              await pushNotificationQueue.add("new-contact-alert", {
                pushTokens: parent[0]!.pushTokens,
                notification: {
                  title: `👤 New Contact Added`,
                  body: `${data.name} was added on ${deviceName}`,
                  data: {
                    type: "new_contact",
                    screen: "ContactDetail",
                    deviceId: deviceId.toString(),
                    deviceName: deviceName,
                    contactName: data.name,
                    contactIdentifier: contactIdentifier,
                    contactType,
                  },
                  channelId: "alerts",
                },
              });

              logger.info(
                { parentId, deviceId, contactName: data.name },
                "New contact notification queued for parent",
              );
            }
          }
        }

        ws.send(
          JSON.stringify({
            success: true,
          }),
        );
      } catch (e) {
        logger.error(
          { error: e, deviceId },
          "Failed to send contact notification",
        );
        ws.send(
          JSON.stringify({
            success: false,
            reason: "Failed to send notification",
          }),
        );
      }

      return;
    }

    if (data.type === "accessibility_message_detected") {
      const deviceId = (ws as unknown as KidWebSocket).deviceId;
      if (!deviceId) {
        ws.send(
          JSON.stringify({ success: false, reason: "Not authenticated" }),
        );
        return;
      }

      try {
        const accessibilityMessage = {
          app: data.app as string,
          sender: data.sender as string,
          message: data.message as string,
          timestamp:
            (data.timestamp as number) || Math.floor(Date.now() / 1000),
        };

        // Store the message in Redis with 72-hour TTL
        await storeAccessibilityMessage(deviceId, accessibilityMessage);

        // Get all recent messages (last 72 hours) for context
        const recentMessages = await getRecentAccessibilityMessages(deviceId);

        await accessibilityScanQueue.add("scanAccessibilityMessage", {
          deviceId,
          accessibilityMessage,
          recentMessages,
        });

        logger.info(
          {
            deviceId,
            app: data.app,
            sender: data.sender,
            contextMessagesCount: recentMessages.length,
          },
          "Accessibility message queued for scanning with context",
        );

        ws.send(JSON.stringify({ success: true, todo: "queued" }));
      } catch (e) {
        logger.error(
          { error: e, deviceId },
          "Failed to enqueue accessibility message",
        );
        ws.send(
          JSON.stringify({
            success: false,
            reason: "Failed to queue accessibility message",
          }),
        );
      }

      return;
    }

    if (data.type === "circumvention_event") {
      const deviceId = (ws as unknown as KidWebSocket).deviceId;
      if (!deviceId) {
        ws.send(
          JSON.stringify({ success: false, reason: "Not authenticated" }),
        );
        return;
      }

      try {
        const packageName = data.packageName as string;
        const className = data.className as string;

        const device = await db
          .select()
          .from(linkedDevices)
          .where(eq(linkedDevices.id, deviceId))
          .limit(1);

        if (device.length === 0) {
          logger.error(
            { deviceId },
            "Device not found for circumvention event",
          );
          ws.send(JSON.stringify({ success: true }));
          return;
        }

        const parentId = device[0]!.parentId;
        const deviceName = device[0]!.nickname;

        /** Maps circumvention event keys to their descriptions for parent alerts */
        const circumventionDescriptions: Record<
          string,
          { name: string; description: string }
        > = {
          "com.miui.securitycore:PrivateSpaceMainActivity": {
            name: "Xiaomi Second Space",
            description:
              "Second Space allows creating a separate, isolated environment on the device where apps can be hidden and run independently",
          },
        };

        const eventKey = `${packageName}:${className.split(".").pop()}`;
        const eventInfo = circumventionDescriptions[eventKey] || {
          name: "Circumvention Feature",
          description:
            "A feature that could be used to bypass parental controls was accessed",
        };

        const config = await db
          .select()
          .from(deviceConfig)
          .where(eq(deviceConfig.deviceId, deviceId))
          .limit(1);

        if (config.length > 0 && !config[0]!.familyLinkAntiCircumvention) {
          logger.info(
            { deviceId },
            "Family Link anti-circumvention disabled, skipping notification",
          );
          ws.send(JSON.stringify({ success: true }));
          return;
        }

        const parent = await db
          .select({ pushTokens: users.pushTokens })
          .from(users)
          .where(eq(users.id, parentId))
          .limit(1);

        if (
          parent.length > 0 &&
          parent[0]!.pushTokens &&
          parent[0]!.pushTokens.length > 0
        ) {
          await pushNotificationQueue.add("circumvention-event-alert", {
            pushTokens: parent[0]!.pushTokens,
            notification: {
              title: `⚠️ Circumvention Attempt Detected`,
              body: `${eventInfo.name} was accessed on ${deviceName}`,
              data: {
                type: "circumvention_event",
                screen: "DeviceDetail",
                deviceId: deviceId.toString(),
                deviceName: deviceName,
                featureName: eventInfo.name,
              },
              channelId: "alerts",
            },
          });

          await db.insert(alerts).values({
            deviceId: deviceId,
            parentId: parentId,
            category: "circumvention",
            title: `${eventInfo.name} accessed`,
            message: `${eventInfo.name} was accessed on ${deviceName}`,
            summary: eventInfo.description,
            confidence: 95,
            packageName: packageName,
            timestamp: Math.floor(Date.now() / 1000),
            read: false,
          });

          logger.info(
            { parentId, deviceId, featureName: eventInfo.name },
            "Circumvention event notification sent",
          );
        }

        ws.send(JSON.stringify({ success: true }));
      } catch (e) {
        logger.error(
          { error: e, deviceId },
          "Failed to process circumvention event",
        );
        ws.send(
          JSON.stringify({
            success: false,
            reason: "Failed to process circumvention event",
          }),
        );
      }

      return;
    }

    logger.debug(
      { data, deviceId: (ws as unknown as KidWebSocket).deviceId },
      "Unknown message type received",
    );

    ws.send(JSON.stringify({ success: false, reason: "Unknown message type" }));
  });

  ws.on("close", async () => {
    const deviceId = (ws as unknown as KidWebSocket).deviceId;
    if (deviceId) {
      logger.info({ deviceId }, "WebSocket connection closed");
      onlineDevices.delete(deviceId);
      await db
        .update(linkedDevices)
        .set({ lastOnline: Math.floor(Date.now() / 1000) })
        .where(eq(linkedDevices.id, deviceId));
    }
  });
});

app.listen(3000, () => {
  logger.info({ port: 3000 }, "Buddy Backend server is running");
});