File size: 4,386 Bytes
1444c0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { randomUUID } from "node:crypto";
import { createClient, type SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";

export const MAX_DEVICES = 20;

export interface Device {
  id: string;
  user_id: string;
  label: string;
  kind: "phone" | "tablet" | "watch" | "other";
  platform: "ios" | "android" | "other";
  phone?: string; // E.164
  created_at: string;
}

export interface DeviceStore {
  list(userId: string): Promise<Device[]>;
  add(device: Device): Promise<void>;
  remove(userId: string, id: string): Promise<boolean>;
}

export class DeviceError extends Error {}

/** Normalises user-entered numbers to E.164. 10-digit numbers are treated as US/Canada (+1). */
export function normalizePhone(raw: string): string {
  const s = raw.trim();
  if (!s) throw new DeviceError("phone number is empty");
  if (/[^\d+\-().\s]/.test(s)) throw new DeviceError("phone number may only contain digits, spaces, + - ( )");
  const digits = s.replace(/\D/g, "");
  let e164: string;
  if (s.startsWith("+")) e164 = `+${digits}`;
  else if (digits.length === 10) e164 = `+1${digits}`;
  else if (digits.length === 11 && digits.startsWith("1")) e164 = `+${digits}`;
  else throw new DeviceError("use international format, e.g. +14155550123 (or a 10-digit US number)");
  if (!/^\+[1-9]\d{6,14}$/.test(e164)) throw new DeviceError("phone number must be 7-15 digits in international format");
  return e164;
}

export const DeviceInput = z.object({
  label: z.string().trim().min(1, "name is required").max(60),
  kind: z.enum(["phone", "tablet", "watch", "other"]).default("phone"),
  platform: z.enum(["ios", "android", "other"]).default("other"),
  phone: z.string().max(40).optional(),
});

export async function addDevice(store: DeviceStore, userId: string, input: unknown): Promise<Device> {
  const parsed = DeviceInput.safeParse(input);
  if (!parsed.success) throw new DeviceError(parsed.error.issues.map((i) => i.message).join("; "));
  const existing = await store.list(userId);
  if (existing.length >= MAX_DEVICES) throw new DeviceError(`device limit reached (${MAX_DEVICES}); remove one first`);
  const phone = parsed.data.phone?.trim() ? normalizePhone(parsed.data.phone) : undefined;
  if (phone && existing.some((d) => d.phone === phone)) throw new DeviceError("that phone number is already added");
  const d: Device = { id: randomUUID(), user_id: userId, label: parsed.data.label, kind: parsed.data.kind,
    platform: parsed.data.platform, phone, created_at: new Date().toISOString() };
  await store.add(d);
  return d;
}

export class MemoryDeviceStore implements DeviceStore {
  items: Device[] = [];
  async list(userId: string) { return this.items.filter((d) => d.user_id === userId).sort((a, b) => b.created_at.localeCompare(a.created_at)); }
  async add(d: Device) { this.items.push(structuredClone(d)); }
  async remove(userId: string, id: string) {
    const n = this.items.length; this.items = this.items.filter((d) => !(d.user_id === userId && d.id === id)); return this.items.length < n;
  }
}

export class SupabaseDeviceStore implements DeviceStore {
  private db: SupabaseClient;
  constructor(url: string, serviceKey: string) { this.db = createClient(url, serviceKey, { auth: { persistSession: false } }); }
  async list(userId: string): Promise<Device[]> {
    const { data, error } = await this.db.from("wallet_devices").select("*").eq("user_id", userId).order("created_at", { ascending: false });
    if (error) throw new Error(error.message);
    return (data ?? []).map((r) => ({ ...r, phone: r.phone ?? undefined }) as Device);
  }
  async add(d: Device) {
    const { error } = await this.db.from("wallet_devices").insert({ ...d, phone: d.phone ?? null });
    if (error) throw new Error(error.message);
  }
  async remove(userId: string, id: string) {
    const { data, error } = await this.db.from("wallet_devices").delete().eq("user_id", userId).eq("id", id).select("id");
    if (error) throw new Error(error.message);
    return (data ?? []).length > 0;
  }
}

/** Lets the settings page hot-swap memory <-> Supabase without restarting. */
export class SwitchableDeviceStore implements DeviceStore {
  constructor(public target: DeviceStore) {}
  list(u: string) { return this.target.list(u); }
  add(d: Device) { return this.target.add(d); }
  remove(u: string, id: string) { return this.target.remove(u, id); }
}