user.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import assets from '../common/assets';
  2. import { getFileList, setFileList } from './api';
  3. import { encryptStream, decryptStream } from './ece';
  4. import { arrayToB64, b64ToArray, streamToArrayBuffer } from './utils';
  5. import { blobStream } from './streams';
  6. import { getFileListKey, prepareScopedBundleKey, preparePkce } from './fxa';
  7. import storage from './storage';
  8. const textEncoder = new TextEncoder();
  9. const textDecoder = new TextDecoder();
  10. const anonId = arrayToB64(crypto.getRandomValues(new Uint8Array(16)));
  11. async function hashId(id) {
  12. const d = new Date();
  13. const month = d.getUTCMonth();
  14. const year = d.getUTCFullYear();
  15. const encoded = textEncoder.encode(`${id}:${year}:${month}`);
  16. const hash = await crypto.subtle.digest('SHA-256', encoded);
  17. return arrayToB64(new Uint8Array(hash.slice(16)));
  18. }
  19. export default class User {
  20. constructor(storage, limits, authConfig) {
  21. this.authConfig = authConfig;
  22. this.limits = limits;
  23. this.storage = storage;
  24. this.data = storage.user || {};
  25. }
  26. get info() {
  27. return this.data || this.storage.user || {};
  28. }
  29. set info(data) {
  30. this.data = data;
  31. this.storage.user = data;
  32. }
  33. get firstAction() {
  34. return this.storage.get('firstAction');
  35. }
  36. set firstAction(action) {
  37. this.storage.set('firstAction', action);
  38. }
  39. get surveyed() {
  40. return this.storage.get('surveyed');
  41. }
  42. set surveyed(yes) {
  43. this.storage.set('surveyed', yes);
  44. }
  45. get avatar() {
  46. const defaultAvatar = assets.get('user.svg');
  47. if (this.info.avatarDefault) {
  48. return defaultAvatar;
  49. }
  50. return this.info.avatar || defaultAvatar;
  51. }
  52. get name() {
  53. return this.info.displayName;
  54. }
  55. get email() {
  56. return this.info.email;
  57. }
  58. get loggedIn() {
  59. return !!this.info.access_token;
  60. }
  61. get bearerToken() {
  62. return this.info.access_token;
  63. }
  64. get refreshToken() {
  65. return this.info.refresh_token;
  66. }
  67. get maxSize() {
  68. return this.limits.MAX_FILE_SIZE;
  69. }
  70. get maxExpireSeconds() {
  71. return this.limits.MAX_EXPIRE_SECONDS;
  72. }
  73. get maxDownloads() {
  74. return this.limits.MAX_DOWNLOADS;
  75. }
  76. async metricId() {
  77. return this.loggedIn ? hashId(this.info.uid) : undefined;
  78. }
  79. async deviceId() {
  80. return this.loggedIn ? hashId(this.storage.id) : hashId(anonId);
  81. }
  82. async startAuthFlow(trigger, utms = {}) {
  83. this.utms = utms;
  84. this.trigger = trigger;
  85. this.flowId = null;
  86. this.flowBeginTime = null;
  87. }
  88. async login(email) {
  89. const state = arrayToB64(crypto.getRandomValues(new Uint8Array(16)));
  90. storage.set('oauthState', state);
  91. const keys_jwk = await prepareScopedBundleKey(this.storage);
  92. const code_challenge = await preparePkce(this.storage);
  93. const options = {
  94. action: 'email',
  95. access_type: 'offline',
  96. client_id: this.authConfig.client_id,
  97. code_challenge,
  98. code_challenge_method: 'S256',
  99. response_type: 'code',
  100. scope: `profile ${this.authConfig.key_scope}`,
  101. state,
  102. keys_jwk
  103. };
  104. if (email) {
  105. options.email = email;
  106. }
  107. if (this.flowId && this.flowBeginTime) {
  108. options.flow_id = this.flowId;
  109. options.flow_begin_time = this.flowBeginTime;
  110. }
  111. if (this.trigger) {
  112. options.entrypoint = `send-${this.trigger}`;
  113. }
  114. if (this.utms) {
  115. options.utm_campaign = this.utms.campaign || 'none';
  116. options.utm_content = this.utms.content || 'none';
  117. options.utm_medium = this.utms.medium || 'none';
  118. options.utm_source = this.utms.source || 'send';
  119. options.utm_term = this.utms.term || 'none';
  120. }
  121. const params = new URLSearchParams(options);
  122. location.assign(
  123. `${this.authConfig.authorization_endpoint}?${params.toString()}`
  124. );
  125. }
  126. async finishLogin(code, state) {
  127. const localState = storage.get('oauthState');
  128. storage.remove('oauthState');
  129. if (state !== localState) {
  130. throw new Error('state mismatch');
  131. }
  132. const tokenResponse = await fetch(this.authConfig.token_endpoint, {
  133. method: 'POST',
  134. headers: {
  135. 'Content-Type': 'application/json'
  136. },
  137. body: JSON.stringify({
  138. code,
  139. client_id: this.authConfig.client_id,
  140. code_verifier: this.storage.get('pkceVerifier')
  141. })
  142. });
  143. const auth = await tokenResponse.json();
  144. const infoResponse = await fetch(this.authConfig.userinfo_endpoint, {
  145. method: 'GET',
  146. headers: {
  147. Authorization: `Bearer ${auth.access_token}`
  148. }
  149. });
  150. const userInfo = await infoResponse.json();
  151. userInfo.access_token = auth.access_token;
  152. userInfo.refresh_token = auth.refresh_token;
  153. userInfo.fileListKey = await getFileListKey(this.storage, auth.keys_jwe);
  154. this.info = userInfo;
  155. this.storage.remove('pkceVerifier');
  156. }
  157. async refresh() {
  158. if (!this.refreshToken) {
  159. return false;
  160. }
  161. try {
  162. const tokenResponse = await fetch(this.authConfig.token_endpoint, {
  163. method: 'POST',
  164. headers: {
  165. 'Content-Type': 'application/json'
  166. },
  167. body: JSON.stringify({
  168. client_id: this.authConfig.client_id,
  169. grant_type: 'refresh_token',
  170. refresh_token: this.refreshToken
  171. })
  172. });
  173. if (tokenResponse.ok) {
  174. const auth = await tokenResponse.json();
  175. const info = { ...this.info, access_token: auth.access_token };
  176. this.info = info;
  177. return true;
  178. }
  179. } catch (e) {
  180. console.error(e);
  181. }
  182. await this.logout();
  183. return false;
  184. }
  185. async logout() {
  186. try {
  187. if (this.refreshToken) {
  188. await fetch(this.authConfig.revocation_endpoint, {
  189. method: 'POST',
  190. headers: {
  191. 'Content-Type': 'application/json'
  192. },
  193. body: JSON.stringify({
  194. refresh_token: this.refreshToken
  195. })
  196. });
  197. }
  198. if (this.bearerToken) {
  199. await fetch(this.authConfig.revocation_endpoint, {
  200. method: 'POST',
  201. headers: {
  202. 'Content-Type': 'application/json'
  203. },
  204. body: JSON.stringify({
  205. token: this.bearerToken
  206. })
  207. });
  208. }
  209. } catch (e) {
  210. console.error(e);
  211. // oh well, we tried
  212. }
  213. this.storage.clearLocalFiles();
  214. this.info = {};
  215. }
  216. async syncFileList() {
  217. let changes = { incoming: false, outgoing: false, downloadCount: false };
  218. if (!this.loggedIn) {
  219. return this.storage.merge();
  220. }
  221. let list = [];
  222. const key = b64ToArray(this.info.fileListKey);
  223. const sha = await crypto.subtle.digest('SHA-256', key);
  224. const kid = arrayToB64(new Uint8Array(sha)).substring(0, 16);
  225. const retry = async () => {
  226. const refreshed = await this.refresh();
  227. if (refreshed) {
  228. return await this.syncFileList();
  229. } else {
  230. return { incoming: true };
  231. }
  232. };
  233. try {
  234. const encrypted = await getFileList(this.bearerToken, kid);
  235. const decrypted = await streamToArrayBuffer(
  236. decryptStream(blobStream(encrypted), key)
  237. );
  238. list = JSON.parse(textDecoder.decode(decrypted));
  239. } catch (e) {
  240. if (e.message === '401') {
  241. return retry(e);
  242. }
  243. }
  244. changes = await this.storage.merge(list);
  245. if (!changes.outgoing) {
  246. return changes;
  247. }
  248. try {
  249. const blob = new Blob([
  250. textEncoder.encode(JSON.stringify(this.storage.files))
  251. ]);
  252. const encrypted = await streamToArrayBuffer(
  253. encryptStream(blobStream(blob), key)
  254. );
  255. await setFileList(this.bearerToken, kid, encrypted);
  256. } catch (e) {
  257. if (e.message === '401') {
  258. return retry(e);
  259. }
  260. }
  261. return changes;
  262. }
  263. toJSON() {
  264. return this.info;
  265. }
  266. }