All files user.ts

55.21% Statements 106/192
25% Branches 14/56
65.22% Functions 15/23
54.97% Lines 105/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 4045x 5x 5x                     5x 5x   5x 5x                                                           5x 35x     5x 13x 13x 13x 13x                   13x                 5x 3x     3x 3x 3x 3x 3x     3x     3x                                     3x 3x                                                                           5x                                         5x   2x     2x   2x 2x 2x                 5x                                       5x   178x     178x   178x 178x 178x     5x 178x 178x 178x 178x   178x 178x     5x 2x     2x     5x 152x     152x     5x           5x               5x   4x     4x       4x 4x 4x 3x   3x 3x   3x     5x                                         5x                 5x 91x 91x   91x     91x   91x     5x 91x 91x 91x 91x 91x   91x 91x 88x     1x   3x               3x         5x 87x 87x     87x 7x   87x 87x             5x 4x       4x       4x     5x 64x     64x             64x     5x 31x               31x 31x     5x        
import * as nacl from 'tweetnacl';
import * as naclUtil from 'tweetnacl-util';
import {
  // TODO consider using, from `naclUtil`, `encodeBase64`, `decodeBase64`, `encodeUTF8`, `decodeUTF8`
  decodeUint8ArrayFromBaseN,
  encodeUint8ArrayToBaseN,
  decodeUint8ArrayFromUTF,
  encodeUint8ArrayToUTF,
  hashObject,
  newid,
  stringify,
  parseJSON
} from './common';
import { commitChange } from './data-change';
import { getDB, IData, IGroup } from './db';
 
module.exports.nacl = nacl;
module.exports.naclUtil = naclUtil;
 
export interface ISigned {
  signature?: string
  signer?: string
}
 
export interface IDevice {
  id: string
  userId: string
  app: string
  name?: string
  expires?: number
  pushSubscription?: {
    endpoint: string
    expirationTime: number
    keys: any
  }
  subscriptionExpires?: number
}
 
export interface IUser extends ISigned, IData {
  type: 'User'
  group: 'users'
  name: string
  publicKey: string
  publicBoxKey: string
  devices?: { [deviceId: string]: IDevice }
}
 
export function isUser(data: IData): data is IUser {
  return data.type === 'User' && data.group === 'users';
}
 
export function newUser(name?: string): IUser & { secretKey: string } {
  const userId = newid();
  const newKey = nacl.sign.keyPair();
  const boxKey = nacl.box.keyPair.fromSecretKey(newKey.secretKey.slice(0, 32))
  const user: IUser & { secretKey: string } = {
    type: 'User',
    id: userId,
    group: 'users',
    name: name || userId,
    secretKey: encodeUint8ArrayToBaseN(newKey.secretKey),
    publicKey: encodeUint8ArrayToBaseN(newKey.publicKey),
    publicBoxKey: encodeUint8ArrayToBaseN(boxKey.publicKey),
    modified: Date.now(),
  }
  return user;
}
 
// expose public box key for now to update users if needed
export let publicBoxKey: string;
 
export let userId: string;
let secretKey: string;
 
export async function init(config?: { id: string, secretKey: string, name?: string, iconUrl?: string, dontWarn?: boolean, dontStore?: boolean }): Promise<string> {
  Iif (!config && userId && secretKey) {
    return userId;
  }
  const credentialsId = 'credentials';
  if (config) {
    userId = config.id;
    secretKey = config.secretKey;
    Iif (config.dontStore) {
      return userId;
    }
    Iif (config.dontWarn === false) {
      alert("You're about to be asked if you'd like to store a username and password for this site.  It is highly recommend you agree to this unless you're comfortable managing your user id and secret key yourself.")
    }
    const db = await getDB();
 
    // // don't use navigator to store creds, it creates problems
    // try {
    //   // switch name and id so name is shown
    //   // @ts-ignore
    //   const creds = await navigator.credentials.create({ password: { id: config.name || config.id, password: config.secretKey, name: config.id, iconUrl: config.iconUrl } });
    //   await navigator.credentials.store(creds);
    //   // @ts-ignore
    //   const storedCredentials = await navigator.credentials.get({ password: true })    
    //   if (storedCredentials) {
    //     await db.local.delete(credentialsId);
    //     return userId;
    //   }    
    // } catch { }
 
    // if `navigator.credentials` fails then store in db.local
    // can't use credential store so fallback to local storage for now 
    // TODO find a more secure way to do this
    await db.local.save({ id: credentialsId, config });
    return userId
  }
 
  const db = await getDB();
  async function ensurePublicBoxKeyExists() {
    const user: IUser = await db.get(userId);
    Iif (user && !user.publicBoxKey) {
      user.publicBoxKey = publicBoxKey;
      user.modified++;
      // signObject(user);
      // await db.save(user);
      await commitChange(user, { preserveModified: true });
    }
  }
 
  // look up stored credentials - first try credentials then try db.local
  try {
    // @ts-ignore
    const creds = await navigator.credentials.get({ password: true });
    Iif (creds) {
      // @ts-ignore
      userId = creds.name;
      // @ts-ignore
      secretKey = creds.password;
      publicBoxKey = hydrateUser(userId, secretKey).publicBoxKey;
      await ensurePublicBoxKeyExists();
      return userId
    }
  } catch { }
  // if all else fails try to look it up in db.local
  config = (await db.local.get(credentialsId))?.config;
  userId = config?.id;
  secretKey = config?.secretKey;
  publicBoxKey = hydrateUser(userId, secretKey).publicBoxKey;
  await ensurePublicBoxKeyExists();
  return userId;
}
 
export function hydrateUser(id: string, secretKey: string, displayName?: string): IUser {
  let secretKeyAry = decodeUint8ArrayFromBaseN(secretKey);
  Iif (secretKeyAry.length !== 64) {
    secretKeyAry = decodeUint8ArrayFromBaseN(secretKey, 36);
  }
  const keyPartLength = secretKeyAry.length / 2; // should be 32
  const publicKeyAry = secretKeyAry.slice(keyPartLength);
  const publicKey = encodeUint8ArrayToBaseN(publicKeyAry);
  const boxKey = nacl.box.keyPair.fromSecretKey(secretKeyAry.slice(0, keyPartLength));
  const publicBoxKey = encodeUint8ArrayToBaseN(boxKey.publicKey);
  return {
    id,
    publicKey,
    publicBoxKey,
    name: displayName || id,
    group: 'users',
    modified: 1, // don't want to overwrite data in the database with this most minimal user object
    type: 'User',
  }
}
 
export function signMessageWithSecretKey(msg: string, secretKey: string) {
  let _secretKey: Uint8Array;
  Iif (secretKey.length == 128) {
    _secretKey = decodeUint8ArrayFromBaseN(secretKey, 36)
  } else {
    _secretKey = decodeUint8ArrayFromBaseN(secretKey)
  }
  const msgDecoded = naclUtil.decodeUTF8(msg);
  const msgSigned = nacl.sign(msgDecoded, _secretKey);
  return encodeUint8ArrayToBaseN(msgSigned);
}
 
export interface IDataBox {
  fromUserId: string
  contents: string
  nonce: string
}
 
export function boxDataWithKeys(data: any, toPublicBoxKey: string, fromSecretKey: string, fromUserId: string): IDataBox {
  let _secretKey: Uint8Array;
  if (fromSecretKey.length == 128) {
    _secretKey = decodeUint8ArrayFromBaseN(fromSecretKey, 36)
  } else {
    _secretKey = decodeUint8ArrayFromBaseN(fromSecretKey)
  }
  const fromSecretBoxKey = _secretKey.slice(0, 32);
  const _toPublicBoxKey: Uint8Array = decodeUint8ArrayFromBaseN(toPublicBoxKey);
  const nonce = nacl.randomBytes(24);
  data = stringify(data);
  const dataDecoded = decodeUint8ArrayFromUTF(data);
  const dataBoxed = nacl.box(dataDecoded, nonce, _toPublicBoxKey, fromSecretBoxKey)
  return {
    fromUserId,
    contents: encodeUint8ArrayToBaseN(dataBoxed),
    nonce: encodeUint8ArrayToBaseN(nonce)
  }
}
 
export function getSignature(msg: string, secretKey: string) {
  let _secretKey: Uint8Array;
  Iif (secretKey.length == 128) {
    _secretKey = decodeUint8ArrayFromBaseN(secretKey, 36)
  } else {
    _secretKey = decodeUint8ArrayFromBaseN(secretKey)
  }
  const msgDecoded = naclUtil.decodeUTF8(msg);
  const sig = nacl.sign.detached(msgDecoded, _secretKey);
  return encodeUint8ArrayToBaseN(sig);
}
 
export function signObjectWithIdAndSecretKey<T>(obj: T, userId: string, secretKey: string): T & ISigned {
  const signedObj = obj as T & ISigned;
  delete signedObj.signature;
  signedObj.signer = userId;
  const hash = hashObject(signedObj);
  // signedObj.signature = signMessageWithSecretKey(hash, secretKey);
  signedObj.signature = getSignature(hash, secretKey);
  return signedObj;
}
 
export function signMessage(msg: string) {
  Iif (!secretKey) {
    throw new Error('secret key not set, have you called `init`?')
  }
  return signMessageWithSecretKey(msg, secretKey);
}
 
export function signObject<T>(obj: T): T & ISigned {
  Iif (!secretKey) {
    throw new Error('secret key not set, have you called `init`?')
  }
  return signObjectWithIdAndSecretKey(obj, userId, secretKey);
}
 
export function boxDataForPublicKey(data: any, toPublicBoxKey: string) {
  const fromSecretKey = secretKey;
  const fromUserId = userId;
  return boxDataWithKeys(data, toPublicBoxKey, fromSecretKey, fromUserId);
}
 
export async function boxDataForUser(data: any, toUserId: string) {
  const fromSecretKey = secretKey;
  const fromUserId = userId;
  const db = await getDB();
  const toUser: IUser = await db.get(toUserId);
  return boxDataWithKeys(data, toUser.publicBoxKey, fromSecretKey, fromUserId);
}
 
export function openMessage(signedMsg: string, publicKey: string) {
  let _publicKey: Uint8Array;
  Iif (publicKey.length == 64) {
    _publicKey = decodeUint8ArrayFromBaseN(publicKey, 36)
  } else {
    _publicKey = decodeUint8ArrayFromBaseN(publicKey);
  }
  let msgDecoded: Uint8Array;
  let msgOpened: Uint8Array;
  try {
    msgDecoded = decodeUint8ArrayFromBaseN(signedMsg);
    msgOpened = nacl.sign.open(msgDecoded, _publicKey);
    if (!msgOpened) throw 'failed';
  } catch {
    msgDecoded = decodeUint8ArrayFromBaseN(signedMsg, 36);
    msgOpened = nacl.sign.open(msgDecoded, _publicKey);
  }
  return naclUtil.encodeUTF8(msgOpened);
}
 
export function openBoxWithSecretKey(box: IDataBox, fromPublicBoxKey: string, toSecretKey: string): any {
  let _secretKey: Uint8Array;
  if (toSecretKey.length == 128) {
    _secretKey = decodeUint8ArrayFromBaseN(toSecretKey, 36)
  } else {
    _secretKey = decodeUint8ArrayFromBaseN(toSecretKey)
  }
  const _toSecretKey = _secretKey.slice(0, 32);
  const boxedData = decodeUint8ArrayFromBaseN(box.contents);
  const nonce = decodeUint8ArrayFromBaseN(box.nonce);
  const fromPublicKey = decodeUint8ArrayFromBaseN(fromPublicBoxKey);
 
  const dataAry = nacl.box.open(boxedData, nonce, fromPublicKey, _toSecretKey);
  Iif (dataAry === null) {
    console.log('Message was null or verification failed', box)
    throw new Error('Message was null or verification failed');
  }
  const dataStr = encodeUint8ArrayToUTF(dataAry);
  return parseJSON(dataStr);
}
 
export async function openBox(box: IDataBox) {
  const db = await getDB();
  const fromUser: IUser = await db.get(box.fromUserId);
  Iif (!fromUser) {
    throw new Error('box sent by unknown user');
  }
  return openBoxWithSecretKey(box, fromUser.publicBoxKey, secretKey);
}
 
export function verifySignature(message: string, signature: string, publicKey: string) {
  const messageAry = naclUtil.decodeUTF8(message);
  const sig = decodeUint8ArrayFromBaseN(signature);
  let _publicKey: Uint8Array;
  Iif (publicKey.length == 64) {
    _publicKey = decodeUint8ArrayFromBaseN(publicKey, 36)
  } else {
    _publicKey = decodeUint8ArrayFromBaseN(publicKey);
  }
  return nacl.sign.detached.verify(messageAry, sig, _publicKey);
}
 
export function verifySignedObject(obj: ISigned, publicKey: string) {
  try {
    const signature = obj.signature;
    delete obj.signature;
    const hash = hashObject(obj);
    obj.signature = signature;
    let error;
    try {
      if (verifySignature(hash, signature, publicKey)) {
        return;
      }
    } catch (err) {
      error = err;
    }
    const sigHash = openMessage(signature, publicKey);
    Iif (hash !== sigHash) {
      Iif (error) {
        throw error;
      }
      throw new Error('signature hash does not match');
    }
  } catch (err) {
    throw new Error('Object signature verification failed: ' + String(err));
  }
}
 
// TODO maybe cache the results to speed up duplicate calls
export async function verifySigner(obj: ISigned & { id?: string }) {
  const db = await getDB();
  let signer: IUser = await db.get(obj.signer);
  // if we dont' have the signer in the db and _this_ is to create that user, use it
  // NOTE security warning
  if (!signer && obj.signer === obj.id) {
    signer = obj as IUser;
  }
  try {
    verifySignedObject(obj, signer.publicKey);
  } catch (err) {
    throw new Error(`Could not verify object signature: ${JSON.stringify({ obj, signer }, null, 2)}`)
  }
}
 
// This tries to convert keys in old format to new format before comparing
export function keysEqual(publicKey1: string, publicKey2: string) {
  Iif (publicKey1.length == 64) {
    const keyAry = decodeUint8ArrayFromBaseN(publicKey1, 36);
    publicKey1 = encodeUint8ArrayToBaseN(keyAry)
  }
  Iif (publicKey2.length == 64) {
    const keyAry = decodeUint8ArrayFromBaseN(publicKey2, 36);
    publicKey2 = encodeUint8ArrayToBaseN(keyAry)
  }
  return publicKey1 === publicKey2;
}
 
export function newData<T>(fields?: Partial<IData> & T): IData & T {
  Iif (!userId) {
    console.warn('user has not been initialized so group may be uninitialized')
  }
  const value: IData & T = {
    id: newid(),
    type: 'Data',
    group: userId,
    modified: Date.now(),
    ...fields
  }
  return value
}
 
export function newGroup(fields?: Partial<IGroup>): IGroup {
  const group: IGroup = newData({
    type: 'Group',
    blockedUserIds: [],
    members: [],
    name: 'New Group',
    owner: userId,
    ...fields
  });
  group.group = group.id;
  return group;
}
 
export function generateRandomSecureString() {
  const newKey = nacl.sign.keyPair();
  return encodeUint8ArrayToBaseN(newKey.secretKey).replace(/[\/\+\=]/g, '');
}