fox-send/app/api.js

310 lines
7.4 KiB
JavaScript
Raw Normal View History

import { arrayToB64, b64ToArray, delay } from './utils';
2018-01-24 18:23:13 +00:00
function post(obj) {
return {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(obj)
};
}
2018-07-09 22:39:06 +00:00
export function parseNonce(header) {
2018-01-24 18:23:13 +00:00
header = header || '';
return header.split(' ')[1];
}
async function fetchWithAuth(url, params, keychain) {
const result = {};
params = params || {};
const h = await keychain.authHeader();
params.headers = new Headers({ Authorization: h });
const response = await fetch(url, params);
result.response = response;
result.ok = response.ok;
const nonce = parseNonce(response.headers.get('WWW-Authenticate'));
result.shouldRetry = response.status === 401 && nonce !== keychain.nonce;
keychain.nonce = nonce;
return result;
}
async function fetchWithAuthAndRetry(url, params, keychain) {
const result = await fetchWithAuth(url, params, keychain);
if (result.shouldRetry) {
return fetchWithAuth(url, params, keychain);
}
return result;
}
export async function del(id, owner_token) {
const response = await fetch(`/api/delete/${id}`, post({ owner_token }));
return response.ok;
}
export async function setParams(id, owner_token, params) {
const response = await fetch(
`/api/params/${id}`,
post({
owner_token,
dlimit: params.dlimit
})
);
return response.ok;
}
2018-01-30 20:15:09 +00:00
export async function fileInfo(id, owner_token) {
const response = await fetch(`/api/info/${id}`, post({ owner_token }));
2018-07-11 23:52:46 +00:00
2018-01-30 20:15:09 +00:00
if (response.ok) {
const obj = await response.json();
return obj;
}
2018-07-11 23:52:46 +00:00
2018-01-30 20:15:09 +00:00
throw new Error(response.status);
}
2018-01-24 18:23:13 +00:00
export async function metadata(id, keychain) {
const result = await fetchWithAuthAndRetry(
`/api/metadata/${id}`,
{ method: 'GET' },
keychain
);
if (result.ok) {
const data = await result.response.json();
const meta = await keychain.decryptMetadata(b64ToArray(data.metadata));
return {
size: data.size,
ttl: data.ttl,
iv: meta.iv,
name: meta.name,
type: meta.type
};
}
throw new Error(result.response.status);
}
export async function setPassword(id, owner_token, keychain) {
const auth = await keychain.authKeyB64();
const response = await fetch(
`/api/password/${id}`,
post({ owner_token, auth })
);
return response.ok;
}
2018-06-21 00:05:33 +00:00
function asyncInitWebSocket(server) {
return new Promise(resolve => {
const ws = new WebSocket(server);
ws.onopen = () => {
resolve(ws);
};
});
}
2018-06-22 20:17:23 +00:00
function listenForResponse(ws, canceller) {
return new Promise((resolve, reject) => {
ws.addEventListener('message', function(msg) {
try {
2018-06-21 00:05:33 +00:00
const response = JSON.parse(msg.data);
2018-06-21 20:57:53 +00:00
if (response.error) {
2018-06-22 20:17:23 +00:00
throw new Error(response.error);
2018-06-21 20:57:53 +00:00
} else {
resolve({
url: response.url,
id: response.id,
ownerToken: response.owner
});
}
2018-06-22 20:17:23 +00:00
} catch (e) {
2018-06-25 18:26:48 +00:00
ws.close();
2018-06-22 20:17:23 +00:00
canceller.cancelled = true;
canceller.error = e;
reject(e);
}
2018-06-21 00:05:33 +00:00
});
2018-06-22 20:17:23 +00:00
});
}
2018-06-21 00:05:33 +00:00
2018-06-22 20:17:23 +00:00
async function upload(
stream,
streamInfo,
metadata,
verifierB64,
onprogress,
canceller
) {
const host = window.location.hostname;
const port = window.location.port;
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const ws = await asyncInitWebSocket(`${protocol}//${host}:${port}/api/ws`);
2018-06-21 00:05:33 +00:00
2018-06-22 20:17:23 +00:00
try {
const metadataHeader = arrayToB64(new Uint8Array(metadata));
const fileMeta = {
fileMetadata: metadataHeader,
authorization: `send-v1 ${verifierB64}`
};
2018-06-25 18:26:48 +00:00
const responsePromise = listenForResponse(ws, canceller);
2018-06-21 00:05:33 +00:00
2018-06-22 20:17:23 +00:00
ws.send(JSON.stringify(fileMeta));
2018-06-21 00:05:33 +00:00
2018-06-22 20:17:23 +00:00
const reader = stream.getReader();
let state = await reader.read();
let size = 0;
while (!state.done) {
const buf = state.value;
if (canceller.cancelled) {
2018-06-25 18:26:48 +00:00
throw canceller.error;
2018-06-22 20:17:23 +00:00
}
2018-06-25 18:26:48 +00:00
2018-06-22 20:17:23 +00:00
ws.send(buf);
2018-07-09 22:39:06 +00:00
onprogress([size, streamInfo.fileSize]);
size += buf.length;
2018-06-22 20:17:23 +00:00
state = await reader.read();
while (ws.bufferedAmount > streamInfo.recordSize * 2) {
await delay();
}
2018-06-22 20:17:23 +00:00
}
2018-06-25 18:26:48 +00:00
const footer = new Uint8Array([0]);
ws.send(footer);
2018-06-22 20:17:23 +00:00
const response = await responsePromise; //promise only fufills if response is good
ws.close();
return response;
} catch (e) {
ws.close(4000);
throw e;
}
2018-06-21 00:05:33 +00:00
}
2018-06-25 17:57:52 +00:00
export function uploadWs(encrypted, info, metadata, verifierB64, onprogress) {
2018-06-21 20:57:53 +00:00
const canceller = { cancelled: false };
2018-06-21 00:05:33 +00:00
return {
2018-01-24 18:23:13 +00:00
cancel: function() {
2018-06-25 18:26:48 +00:00
canceller.error = new Error(0);
2018-06-21 20:57:53 +00:00
canceller.cancelled = true;
2018-01-24 18:23:13 +00:00
},
2018-06-21 00:05:33 +00:00
result: upload(
encrypted,
info,
metadata,
verifierB64,
2018-06-21 20:57:53 +00:00
onprogress,
canceller
2018-06-21 00:05:33 +00:00
)
2018-01-24 18:23:13 +00:00
};
}
2018-06-29 16:36:08 +00:00
////////////////////////
2018-07-06 22:49:50 +00:00
async function downloadS(id, keychain, signal) {
2018-06-29 16:36:08 +00:00
const auth = await keychain.authHeader();
2018-07-05 19:40:49 +00:00
const response = await fetch(`/api/download/${id}`, {
signal: signal,
method: 'GET',
headers: { Authorization: auth }
});
2018-06-29 16:36:08 +00:00
2018-07-05 19:40:49 +00:00
const authHeader = response.headers.get('WWW-Authenticate');
if (authHeader) {
keychain.nonce = parseNonce(authHeader);
}
2018-06-29 16:36:08 +00:00
2018-07-11 23:52:46 +00:00
if (response.status !== 200) {
throw new Error(response.status);
2018-06-29 16:36:08 +00:00
}
2018-07-11 23:52:46 +00:00
//const fileSize = response.headers.get('Content-Length');
return response.body;
2018-06-29 16:36:08 +00:00
}
2018-07-06 22:49:50 +00:00
async function tryDownloadStream(id, keychain, signal, tries = 1) {
2018-06-29 16:36:08 +00:00
try {
2018-07-06 22:49:50 +00:00
const result = await downloadS(id, keychain, signal);
2018-06-29 16:36:08 +00:00
return result;
} catch (e) {
if (e.message === '401' && --tries > 0) {
2018-07-06 22:49:50 +00:00
return tryDownloadStream(id, keychain, signal, tries);
2018-06-29 16:36:08 +00:00
}
2018-07-05 19:40:49 +00:00
if (e.name === 'AbortError') {
throw new Error('0');
}
2018-06-29 16:36:08 +00:00
throw e;
}
}
2018-07-06 22:49:50 +00:00
export function downloadStream(id, keychain) {
2018-06-29 16:36:08 +00:00
const controller = new AbortController();
function cancel() {
controller.abort();
}
return {
cancel,
2018-07-06 22:49:50 +00:00
result: tryDownloadStream(id, keychain, controller.signal, 2)
2018-06-29 16:36:08 +00:00
};
}
//////////////////
function download(id, keychain, onprogress, canceller) {
2018-01-24 18:23:13 +00:00
const xhr = new XMLHttpRequest();
canceller.oncancel = function() {
xhr.abort();
2018-01-24 18:23:13 +00:00
};
return new Promise(async function(resolve, reject) {
xhr.addEventListener('loadend', function() {
canceller.oncancel = function() {};
const authHeader = xhr.getResponseHeader('WWW-Authenticate');
if (authHeader) {
keychain.nonce = parseNonce(authHeader);
}
if (xhr.status !== 200) {
return reject(new Error(xhr.status));
}
2018-01-24 18:23:13 +00:00
const blob = new Blob([xhr.response]);
2018-06-21 00:05:33 +00:00
resolve(blob);
});
xhr.addEventListener('progress', function(event) {
if (event.lengthComputable && event.target.status === 200) {
onprogress([event.loaded, event.total]);
}
});
const auth = await keychain.authHeader();
xhr.open('get', `/api/download/${id}`);
xhr.setRequestHeader('Authorization', auth);
xhr.responseType = 'blob';
xhr.send();
});
2018-01-24 18:23:13 +00:00
}
async function tryDownload(id, keychain, onprogress, canceller, tries = 1) {
2018-01-24 18:23:13 +00:00
try {
const result = await download(id, keychain, onprogress, canceller);
2018-01-24 18:23:13 +00:00
return result;
} catch (e) {
if (e.message === '401' && --tries > 0) {
return tryDownload(id, keychain, onprogress, canceller, tries);
2018-01-24 18:23:13 +00:00
}
throw e;
}
}
export function downloadFile(id, keychain, onprogress) {
const canceller = {
oncancel: function() {} // download() sets this
};
function cancel() {
canceller.oncancel();
2018-01-24 18:23:13 +00:00
}
return {
cancel,
result: tryDownload(id, keychain, onprogress, canceller, 2)
2018-01-24 18:23:13 +00:00
};
}