aboutsummaryrefslogtreecommitdiffstats
path: root/lib/register.js
blob: eef2b7b411a78005e7dea2a5c0dc40332e648bed (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
const authenticator = require("otplib").authenticator;
const axios = require("axios");
const bcrypt = require("bcrypt");

register = ah(async (user, ip, requireChallenge) => {
  if (!(user && user.username)) throw new Error("Username required");

  let exists = await db.User.count({ where: { username: user.username } });
  if (exists) throw new Error(`Username ${user.username} taken`);

  if (user.password) {
    user.password = await bcrypt.hash(user.password, 1);
  }

  user.sms = user.formattedPhone || user.sms

  // Separate logic for presetting user preferences below into separate manageable file ... (& remove redundant user / account reference)
  let countries = {
    CA: "CAD",
    US: "USD",
    JP: "JPY",
    CN: "CNY",
    AU: "AUD",
    GB: "GBP",
  };

  if (!config.ipstack || ip.startsWith("127") || ip.startsWith("192"))
    user.currency = "CAD";
  else {
    let info = await axios.get(
      `http://api.ipstack.com/${ip}?access_key=${config.ipstack}`
    );
    user.currency = countries[info.data.country_code] || "USD";
  }

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

  user = await db.User.create(user);

  let account = await db.Account.create({
    user_id: user.id,
    asset: config.liquid.btcasset,
    balance: 0,
    pending: 0,
    name: "Bitcoin",
    ticker: "BTC",
    precision: 8,
  });

  user.accounts = [account];

  const d = ip.split(".");
  const numericIp = ((+d[0] * 256 + +d[1]) * 256 + +d[2]) * 256 + +d[3];
  if (Number.isInteger(numericIp)) {
    user.ip = numericIp;
    const ipExists = await db.User.findOne({ where: { ip: numericIp } });
  }

  user.account_id = account.id;
  await user.save();
  l.info("new user", user.username, ip);
  return user;
});
"> chunk) + 1); }, writeU16BE(num: number) { if (!Number.isSafeInteger(num) || num < u.minPlaintextSize || num > u.maxPlaintextSize) throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); const arr = new Uint8Array(2); new DataView(arr.buffer).setUint16(0, num, false); return arr; }, pad(plaintext: string): Uint8Array { const unpadded = u.utf8Encode(plaintext); const unpaddedLen = unpadded.length; const prefix = u.writeU16BE(unpaddedLen); const suffix = new Uint8Array(u.calcPaddedLen(unpaddedLen) - unpaddedLen); return concatBytes(prefix, unpadded, suffix); }, unpad(padded: Uint8Array): string { const unpaddedLen = new DataView(padded.buffer).getUint16(0); const unpadded = padded.subarray(2, 2 + unpaddedLen); if ( unpaddedLen < u.minPlaintextSize || unpaddedLen > u.maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + u.calcPaddedLen(unpaddedLen) ) throw new Error("invalid padding"); return u.utf8Decode(unpadded); }, hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array) { if (aad.length !== 32) throw new Error("AAD associated data must be 32 bytes"); const combined = concatBytes(aad, message); return hmac(sha256, key, combined); }, // metadata: always 65b (version: 1b, nonce: 32b, max: 32b) // plaintext: 1b to 0xffff // padded plaintext: 32b to 0xffff // ciphertext: 32b+2 to 0xffff+2 // raw payload: 99 (65+32+2) to 65603 (65+0xffff+2) // compressed payload (base64): 132b to 87472b decodePayload(payload: string) { if (typeof payload !== "string") throw new Error("payload must be a valid string"); const plen = payload.length; if (plen < 132 || plen > 87472) throw new Error("invalid payload length: " + plen); if (payload[0] === "#") throw new Error("unknown encryption version"); let data: Uint8Array; try { data = base64.decode(payload); } catch (error) { throw new Error("invalid base64: " + (error as any).message); } const dlen = data.length; if (dlen < 99 || dlen > 65603) throw new Error("invalid data length: " + dlen); const vers = data[0]; if (vers !== 2) throw new Error("unknown encryption version " + vers); return { nonce: data.subarray(1, 33), ciphertext: data.subarray(33, -32), mac: data.subarray(-32), }; }, }; export function encrypt( plaintext: string, conversationKey: Uint8Array, nonce = randomBytes(32), ): string { const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce); const padded = u.pad(plaintext); const ciphertext = chacha20(chacha_key, chacha_nonce, padded); const mac = u.hmacAad(hmac_key, ciphertext, nonce); return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac)); } export function decrypt(payload: string, conversationKey: Uint8Array): string { const { nonce, ciphertext, mac } = u.decodePayload(payload); const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce); const calculatedMac = u.hmacAad(hmac_key, ciphertext, nonce); if (!equalBytes(calculatedMac, mac)) throw new Error("invalid MAC"); const padded = chacha20(chacha_key, chacha_nonce, ciphertext); return u.unpad(padded); } export const v2 = { utils: u, encrypt, decrypt, };