aboutsummaryrefslogtreecommitdiffstats
path: root/lib/register.ts
blob: 3f612ec33521d987ca62f84aa9db6b51ea830718 (plain) (blame)
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
import config from "$config";
import countries from "$lib/countries";
import { db, s } from "$lib/db";
import { l, warn } from "$lib/logging";
import { createBalanceAccount, createCreditAccounts } from "$lib/tb";
import { fail } from "$lib/utils";
import { bytesToHex, randomBytes } from "@noble/hashes/utils.js";
import { got } from "got";
import { getPublicKey, nip19 } from "nostr-tools";
import { encrypt as nip49encrypt } from "nostr-tools/nip49";
import { authenticator } from "otplib";
import { v4 } from "uuid";

const valid = /^[\p{L}\p{N}]{2,24}$/u;
export default async (user, ip) => {
  let { password, pubkey, username } = user;
  l("registering", username);

  const reserved = ["ecash"];
  if (!username) fail("Username required");
  username = username.toLowerCase().replace(/\s/g, "");
  if (!valid.test(username)) fail("Usernames can only have letters and numbers");
  if (reserved.includes(username)) fail("Invalid username");
  if (username.includes("undefined")) fail("Invalid username");

  const id = v4();
  user.id = id;

  const exists = await db.exists(`user:${username}`);
  if (exists) fail(`Username ${username} taken`);

  if (password) {
    user.password = await Bun.password.hash(password, {
      algorithm: "bcrypt",
      cost: 4,
    });
  }

  user.created = Date.now();

  user.currency = "USD";
  if (config.ipregistry) {
    try {
      const {
        location: {
          country: { code },
        },
      }: any = await got(
        `https://api.ipregistry.co/${ip}?key=${config.ipregistry}&fields=location.country.code`,
      ).json();

      user.currency = countries[code];
      user.country = code; // stored for analytics (signup geography)
    } catch (e) {
      warn("unable to detect country from IP", username);
    }
  }

  user.currencies = [...new Set([user.currency, "CAD", "USD"])];
  user.fiat = false;
  user.otpsecret = authenticator.generateSecret();
  user.migrated = true;
  user.locktime = 300;

  user.passkeys = [];

  let sk;
  if (!pubkey) {
    sk = randomBytes(32);
    pubkey = getPublicKey(sk);
    user.pubkey = pubkey;
    if (password) user.nsec = nip49encrypt(sk, password);
  }

  user.npub = nip19.npubEncode(pubkey);

  const account = JSON.stringify({
    id,
    type: "ecash",
  });

  const bytes = randomBytes(32);
  const secret = bytesToHex(bytes);
  const app = {
    uid: id,
    secret,
    pubkey: getPublicKey(bytes),
    max_amount: 1000000,
    budget_renewal: "weekly",
    name: username,
    created: Date.now(),
  };

  await s(`app:${app.pubkey}`, app);
  await db.sAdd(`${id}:apps`, app.pubkey);

  await createBalanceAccount(id);
  await createCreditAccounts(id);

  db.multi()
    .set(`user:${id}`, JSON.stringify(user))
    .set(`user:${username}`, id)
    .set(`user:${pubkey}`, id)
    .set(`account:${id}`, account)
    .set(`${pubkey}:follows:n`, 0)
    .set(`${pubkey}:followers:n`, 0)
    .set(`${pubkey}:pubkeys`, "[]")
    .lPush(`${id}:accounts`, id)
    .exec();

  l("new user", username);
  if (sk) user.sk = bytesToHex(sk);

  return user;
};