fox-send/app/user.js

240 lines
6.4 KiB
JavaScript
Raw Normal View History

2018-08-07 22:40:17 +00:00
import assets from '../common/assets';
import { getFileList, setFileList } from './api';
import { encryptStream, decryptStream } from './ece';
2018-09-21 21:16:56 +00:00
import { arrayToB64, b64ToArray, streamToArrayBuffer } from './utils';
2018-08-07 22:40:17 +00:00
import { blobStream } from './streams';
import { getFileListKey, prepareScopedBundleKey, preparePkce } from './fxa';
2018-09-21 21:16:56 +00:00
import storage from './storage';
2018-08-07 22:40:17 +00:00
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
2019-02-12 19:50:06 +00:00
const anonId = arrayToB64(crypto.getRandomValues(new Uint8Array(16)));
async function hashId(id) {
const d = new Date();
const month = d.getUTCMonth();
const year = d.getUTCFullYear();
const encoded = textEncoder.encode(`${id}:${year}:${month}`);
const hash = await crypto.subtle.digest('SHA-256', encoded);
return arrayToB64(new Uint8Array(hash.slice(16)));
}
2018-08-07 22:40:17 +00:00
export default class User {
constructor(storage, limits, authConfig) {
this.authConfig = authConfig;
this.limits = limits;
2018-08-07 22:40:17 +00:00
this.storage = storage;
this.data = storage.user || {};
2018-08-07 22:40:17 +00:00
}
get info() {
return this.data || this.storage.user || {};
}
set info(data) {
this.data = data;
this.storage.user = data;
}
2019-02-12 19:50:06 +00:00
get firstAction() {
return this.storage.get('firstAction');
}
set firstAction(action) {
this.storage.set('firstAction', action);
}
2018-08-07 22:40:17 +00:00
get avatar() {
const defaultAvatar = assets.get('user.svg');
if (this.info.avatarDefault) {
return defaultAvatar;
2018-08-07 22:40:17 +00:00
}
return this.info.avatar || defaultAvatar;
2018-08-07 22:40:17 +00:00
}
get name() {
return this.info.displayName;
2018-08-07 22:40:17 +00:00
}
get email() {
return this.info.email;
2018-08-07 22:40:17 +00:00
}
get loggedIn() {
return !!this.info.access_token;
2018-08-07 22:40:17 +00:00
}
get bearerToken() {
return this.info.access_token;
2018-08-07 22:40:17 +00:00
}
get maxSize() {
return this.loggedIn
? this.limits.MAX_FILE_SIZE
: this.limits.ANON.MAX_FILE_SIZE;
2018-08-07 22:40:17 +00:00
}
get maxExpireSeconds() {
return this.loggedIn
? this.limits.MAX_EXPIRE_SECONDS
: this.limits.ANON.MAX_EXPIRE_SECONDS;
2018-08-07 22:40:17 +00:00
}
get maxDownloads() {
return this.loggedIn
? this.limits.MAX_DOWNLOADS
: this.limits.ANON.MAX_DOWNLOADS;
2018-08-07 22:40:17 +00:00
}
2019-02-12 19:50:06 +00:00
async metricId() {
return this.loggedIn ? hashId(this.info.uid) : undefined;
}
async deviceId() {
return this.loggedIn ? hashId(this.storage.id) : hashId(anonId);
}
async startAuthFlow(trigger, utms = {}) {
this.utms = utms;
this.trigger = trigger;
2019-03-05 20:58:40 +00:00
try {
const params = new URLSearchParams({
entrypoint: `send-${trigger}`,
2019-03-05 20:58:40 +00:00
form_type: 'email',
utm_source: utms.source || 'send',
utm_campaign: utms.campaign || 'none'
});
const res = await fetch(
`${this.authConfig.issuer}/metrics-flow?${params.toString()}`,
{
mode: 'cors'
}
2019-03-05 20:58:40 +00:00
);
const { flowId, flowBeginTime } = await res.json();
this.flowId = flowId;
this.flowBeginTime = flowBeginTime;
} catch (e) {
console.error(e);
this.flowId = null;
this.flowBeginTime = null;
}
}
async login(email) {
2018-09-21 21:16:56 +00:00
const state = arrayToB64(crypto.getRandomValues(new Uint8Array(16)));
storage.set('oauthState', state);
const keys_jwk = await prepareScopedBundleKey(this.storage);
const code_challenge = await preparePkce(this.storage);
const options = {
2019-03-07 20:08:42 +00:00
action: 'email',
client_id: this.authConfig.client_id,
code_challenge,
code_challenge_method: 'S256',
response_type: 'code',
scope: `profile ${this.authConfig.key_scope}`,
2018-09-21 21:16:56 +00:00
state,
keys_jwk
};
if (email) {
options.email = email;
}
2019-03-05 20:58:40 +00:00
if (this.flowId && this.flowBeginTime) {
options.flow_id = this.flowId;
options.flow_begin_time = this.flowBeginTime;
}
if (this.trigger) {
options.endpoint = `send-${this.trigger}`;
}
2019-03-05 20:58:40 +00:00
if (this.utms) {
options.utm_campaign = this.utms.campaign || 'none';
options.utm_content = this.utms.content || 'none';
options.utm_medium = this.utms.medium || 'none';
options.utm_source = this.utms.source || 'send';
options.utm_term = this.utms.term || 'none';
}
const params = new URLSearchParams(options);
location.assign(
`${this.authConfig.authorization_endpoint}?${params.toString()}`
);
}
2018-09-21 21:16:56 +00:00
async finishLogin(code, state) {
const localState = storage.get('oauthState');
storage.remove('oauthState');
if (state !== localState) {
throw new Error('state mismatch');
}
const tokenResponse = await fetch(this.authConfig.token_endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
code,
client_id: this.authConfig.client_id,
code_verifier: this.storage.get('pkceVerifier')
})
});
const auth = await tokenResponse.json();
const infoResponse = await fetch(this.authConfig.userinfo_endpoint, {
method: 'GET',
headers: {
Authorization: `Bearer ${auth.access_token}`
}
});
const userInfo = await infoResponse.json();
userInfo.access_token = auth.access_token;
userInfo.fileListKey = await getFileListKey(this.storage, auth.keys_jwe);
this.info = userInfo;
this.storage.remove('pkceVerifier');
}
2018-08-07 22:40:17 +00:00
logout() {
this.storage.clearLocalFiles();
this.info = {};
2018-08-07 22:40:17 +00:00
}
async syncFileList() {
let changes = { incoming: false, outgoing: false, downloadCount: false };
if (!this.loggedIn) {
return this.storage.merge();
}
let list = [];
const key = b64ToArray(this.info.fileListKey);
const sha = await crypto.subtle.digest('SHA-256', key);
const kid = arrayToB64(new Uint8Array(sha)).substring(0, 16);
2018-08-07 22:40:17 +00:00
try {
const encrypted = await getFileList(this.bearerToken, kid);
2018-08-07 22:40:17 +00:00
const decrypted = await streamToArrayBuffer(
decryptStream(blobStream(encrypted), key)
2018-08-07 22:40:17 +00:00
);
list = JSON.parse(textDecoder.decode(decrypted));
} catch (e) {
2018-11-05 23:56:59 +00:00
if (e.message === '401') {
this.logout();
return { incoming: true };
2018-11-05 23:56:59 +00:00
}
2018-08-07 22:40:17 +00:00
}
changes = await this.storage.merge(list);
if (!changes.outgoing) {
return changes;
}
try {
const blob = new Blob([
textEncoder.encode(JSON.stringify(this.storage.files))
]);
const encrypted = await streamToArrayBuffer(
encryptStream(blobStream(blob), key)
2018-08-07 22:40:17 +00:00
);
await setFileList(this.bearerToken, kid, encrypted);
2018-08-07 22:40:17 +00:00
} catch (e) {
//
}
return changes;
}
toJSON() {
return this.info;
2018-08-07 22:40:17 +00:00
}
}