Merge pull request 'feature/support-for-secret-files' (#12) from feature/support-for-secret-files into master

Reviewed-on: #12
This commit is contained in:
silentsilas 2022-02-22 07:42:10 +00:00
commit 621cbe867b
7 changed files with 199 additions and 98 deletions

View File

@ -2,3 +2,8 @@ type IntendedUser = {
name: string;
emails: string[];
};
type IntendedLink = {
filename: string | null,
filetype: string | null
};

View File

@ -27,15 +27,18 @@ interface Keys {
iv: string;
}
interface Link {
interface LinkFiles {
text: Blob | null;
file: Blob | null;
filename: string | null;
filetype: string | null;
}
const AuthPage = (props: AuthPageProps) => {
const { service, recipient, user } = props;
const [secretFileUrl, _setsecretFileUrl] = useState<string>("#");
const [secretFileUrl, setSecretFileUrl] = useState<string>("#");
const [secretFileName, setSecretFileName] = useState<string>("");
const [secretMessage, setSecretMessage] = useState<string>("Decrypting...");
useEffect(() => {
@ -45,14 +48,14 @@ const AuthPage = (props: AuthPageProps) => {
}, []);
const init = async (): Promise<void> => {
const link: LinkFiles | null = await retrieveLink();
const keys: Keys | null = await retrieveKeys();
const link: Link | null = await retrieveLink();
if (link && keys) {
await decrypt(link, keys);
}
};
const retrieveLink = async (): Promise<Link | null> => {
const retrieveLink = async (): Promise<LinkFiles | null> => {
const urlSegments = new URL(document.URL).pathname.split("/");
const linkId = urlSegments.pop() || urlSegments.pop();
if (!linkId) {
@ -60,14 +63,26 @@ const AuthPage = (props: AuthPageProps) => {
return null;
}
const textResponse = await fetch(`/uploads/links/${linkId}/text`);
const linkResponse = await fetch(`/links/${linkId}`);
const linkData: IntendedLink = await linkResponse.json();
const textResponse = await fetch(
`/uploads/links/${linkId}/secret_message.txt`
);
const textData = await textResponse.blob();
const fileResponse = await fetch(`/uploads/links/${linkId}/file`);
const fileResponse = await fetch(
`/uploads/links/${linkId}/${linkData.filename}`
);
const fileData = await fileResponse.blob();
if (linkData.filename) {
await setSecretFileName(linkData.filename);
}
return {
text: textData.size > 0 ? textData : null,
file: fileData.size > 0 ? fileData : null,
filename: linkData.filename,
filetype: linkData.filetype,
};
};
@ -96,7 +111,7 @@ const AuthPage = (props: AuthPageProps) => {
}
};
const decrypt = async (link: Link, keys: Keys) => {
const decrypt = async (link: LinkFiles, keys: Keys) => {
const convertedKey = HexMix.hexToUint8(keys.key);
const convertedIv = HexMix.hexToUint8(keys.iv);
const importedKey = await window.crypto.subtle.importKey(
@ -123,6 +138,21 @@ const AuthPage = (props: AuthPageProps) => {
});
}
if (link?.file) {
const uploadedFile = await link.file.arrayBuffer();
const encodedFile = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
length: 256,
iv: convertedIv,
},
importedKey,
uploadedFile
);
const blob = new Blob([encodedFile], {
type: link.filetype ? link.filetype : "text/plain",
});
setSecretFileUrl(window.URL.createObjectURL(blob));
}
};
@ -193,12 +223,14 @@ const AuthPage = (props: AuthPageProps) => {
<TextAlignWrapper align="left">
<Label htmlFor="service">Secret File</Label>
</TextAlignWrapper>
<InputButtonWithIcon
variant="download"
id="downloadfile"
value={secretFileUrl}
onClick={() => {}}
/>
<a href={secretFileUrl} download style={{ width: "100%" }}>
<InputButtonWithIcon
variant="download"
id="downloadfile"
value={secretFileName}
onClick={() => {}}
/>
</a>
<Spacer space="3rem" />
<a href={`https://intended.link/auth/${service}`}>
<Button variant="primary" wide onClick={() => {}}>

View File

@ -1,80 +1,157 @@
import React, { useEffect, useState } from "react";
import { ProgressIndicator, Header2, Button, IconArrow, Label, FileInput, TextArea, CenteredContainer, Spacer, TextAlignWrapper, GlobalStyle } from '@intended/intended-ui';
import {
ProgressIndicator,
Header2,
Button,
IconArrow,
Label,
FileInput,
TextArea,
CenteredContainer,
Spacer,
TextAlignWrapper,
GlobalStyle,
} from "@intended/intended-ui";
import HexMix from "../utils/hexmix";
type JustPageProps = {
csrf: string
csrf: string;
};
interface AESKey {
key: CryptoKey;
iv: Uint8Array;
exported: ArrayBuffer;
keyHex: string;
ivHex: string;
}
const JustPage = (props: JustPageProps) => {
const [secretInput, setSecretInput] = useState("");
const [fileInput, setFileInput] = useState<File | null>(null);
const [fileInput, setFileInput] = useState<string | null>(null);
const [fileName, setFileName] = useState("");
const [fileType, setFileType] = useState("");
useEffect(() => {
sessionStorage.clear();
}, [])
}, []);
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setSecretInput(e.target.value);
};
const handleFile = (file: File) => {
setFileInput(file);
setFileName(file.name);
setFileType(file.type);
if (file instanceof File) {
if (file.size > 2097152) {
// TODO: may not need this check
alert("Error: Max file size is 2mb.");
return;
}
const reader = new FileReader();
reader.onloadend = loadFile;
reader.readAsArrayBuffer(file);
}
};
const loadFile = (fileEvent: ProgressEvent<FileReader>) => {
// Make sure we actually got a binary file
if (
fileEvent &&
fileEvent.target &&
fileEvent.target.result instanceof ArrayBuffer
) {
const data = fileEvent.target.result as ArrayBuffer;
HexMix.arrayBufferToString(data, (result: string) => {
setFileInput(result);
});
} else {
alert("File is either missing or corrupt.");
}
};
const fileFormData = async (form: FormData, aesKey: AESKey) => {
const encoded = HexMix.stringToArrayBuffer(fileInput as string);
const encrypted = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: aesKey.iv,
},
aesKey.key,
encoded
);
const blobData = new Blob([encrypted]);
form.append("file_content", blobData, fileName);
form.append("filename", fileName);
form.append("filetype", fileType);
};
const textFormData = async (form: FormData, aesKey: AESKey) => {
const encoded = HexMix.stringToArrayBuffer(secretInput);
const encrypted = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: aesKey.iv,
},
aesKey.key,
encoded
);
const blobData = new Blob([encrypted]);
form.append("text_content", blobData, "secret_message.txt");
};
const createKey = async (): Promise<AESKey> => {
const key = await window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"]
);
const iv = window.crypto.getRandomValues(new Uint8Array(16));
const exported = await window.crypto.subtle.exportKey("raw", key);
const keyHex = HexMix.uint8ToHex(new Uint8Array(exported));
const ivHex = HexMix.uint8ToHex(iv);
return {
key,
iv,
exported,
keyHex,
ivHex,
};
};
const postContents = async () => {
if (!window.crypto.subtle) {
alert('Browser does not support SubtleCrypto');
alert("Browser does not support SubtleCrypto");
return;
}
const key = await window.crypto.subtle.generateKey(
{
name: 'AES-GCM',
length: 256
},
true,
['encrypt', 'decrypt']
);
const encoded = HexMix.stringToArrayBuffer(secretInput);
const iv = window.crypto.getRandomValues(new Uint8Array(16));
const exported = await window.crypto.subtle.exportKey('raw', key);
const encrypted = await window.crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv
},
key,
encoded
);
const keyHex = HexMix.uint8ToHex(new Uint8Array(exported));
const ivHex = HexMix.uint8ToHex(iv);
const key = await createKey();
const formData = new FormData();
const blobData = new Blob([encrypted]);
formData.append('text_content', blobData);
// formData.append('filetype', 'text/plain');
// formData.append('filename', 'secret.txt');
await fileFormData(formData, key);
await textFormData(formData, key);
try {
const link: Response = await fetch(`${window.location.origin}/just`, {
const link: Response = await fetch(`${window.location.origin}/just`, {
headers: {
"X-CSRF-Token": props.csrf
"X-CSRF-Token": props.csrf,
},
body: formData,
method: "POST"
method: "POST",
});
const { id: link_id } = await link.json()
const { id: link_id } = await link.json();
sessionStorage.setItem("link_id", link_id);
sessionStorage.setItem("key_hex", keyHex);
sessionStorage.setItem("iv_hex", ivHex);
sessionStorage.setItem("key_hex", key.keyHex);
sessionStorage.setItem("iv_hex", key.ivHex);
window.location.href = `${window.location.origin}/just/for`;
} catch (err: any) {
alert(err.message);
@ -103,10 +180,13 @@ const JustPage = (props: JustPageProps) => {
</TextAlignWrapper>
<Spacer space="1.6rem" />
<FileInput id="fileInput" value={fileName} handleFile={handleFile} />
{ fileInput ? "" : ""}
<Spacer space="4rem" />
<div
style={{ display: "flex", justifyContent: "flex-end", width: "100%" }}
style={{
display: "flex",
justifyContent: "flex-end",
width: "100%",
}}
>
<Button variant="secondary" onClick={postContents}>
<IconArrow arrowDirection="right" />

View File

@ -47,26 +47,15 @@ defmodule EntenduWeb.LinkController do
def auth_page(conn, %{"id" => link_id}) do
with %Link{service: service, recipient: recipient} = link <- Links.get_link(link_id) do
conn
|> put_session(:intended_link, link)
|> put_session(:intended_link, %{service: service, recipient: recipient})
|> render("auth.html", %{intended_link: %{service: service, recipient: recipient}})
end
end
def text(conn, %{"id" => link_id}) do
with user = get_session(conn, :current_user),
%Link{recipient: recipient} = link <- Links.get_link(link_id),
true <- UserFromAuth.can_access?(recipient, user) do
path = EncryptedLink.url({link.text_content, link})
send_file(conn, 200, path)
end
end
def file(conn, %{"id" => link_id}) do
with user = get_session(conn, :current_user),
%Link{recipient: recipient} = link <- Links.get_link(link_id),
true <- UserFromAuth.can_access?(recipient, user) do
path = EncryptedLink.url({link.file_content, link})
send_file(conn, 200, path)
def authorized_link(conn, %{"id" => link_id}) do
with %Link{} = link <- Links.get_link(link_id) do
conn
|> render("show_authorized.json", %{link: link})
end
end
end

View File

@ -12,8 +12,12 @@ defmodule EntenduWeb.Plugs.AuthorizeLink do
def init(_params) do
end
def call(conn, params) do
%{params: %{"path" => [_, link_id, _]}} = conn
defp get_link_id(%{params: %{"id" => link_id}}), do: link_id
defp get_link_id(%{params: %{"path" => [_, link_id, _]}}), do: link_id
def call(conn, _params) do
link_id = get_link_id(conn)
user = get_session(conn, :current_user)
if !user do
@ -23,8 +27,7 @@ defmodule EntenduWeb.Plugs.AuthorizeLink do
|> render("error_code.json", message: "Unauthorized", code: 403)
|> halt
else
with {:ok, user} <- get_user_from_path(conn),
%Link{recipient: recipient} = link <- Links.get_link(link_id),
with %Link{recipient: recipient} = link <- Links.get_link(link_id),
true <- UserFromAuth.can_access?(recipient, user) do
conn
|> assign(:link, link)
@ -52,19 +55,4 @@ defmodule EntenduWeb.Plugs.AuthorizeLink do
end
end
end
defp get_user_from_path(%{params: %{"path" => [_, link_id, _]}} = conn) do
get_session(conn, :current_user)
|> get_user_from_path()
end
defp get_user_from_path(nil) do
{:error, "User not authenticated"}
end
defp get_user_from_path(%{id: _, name: _, emails: _} = user) do
{:ok, user}
end
defp get_user_from_path(_), do: {:error, "Link does not exist"}
end

View File

@ -16,11 +16,15 @@ defmodule EntenduWeb.Router do
plug :accepts, ["json"]
end
pipeline :authorized_links do
pipeline :authorized_files do
plug AuthorizeLink
plug Plug.Static, at: "/uploads", from: Path.expand('./uploads'), gzip: false
end
pipeline :authorized_link do
plug AuthorizeLink
end
scope "/", EntenduWeb do
pipe_through :browser
@ -31,8 +35,6 @@ defmodule EntenduWeb.Router do
post "/just/for", LinkController, :for
get "/just/for/you", LinkController, :you_page
get "/just/for/you/:id", LinkController, :auth_page
get "/links/:id/text", LinkController, :text
get "/links/:id/file", LinkController, :file
end
scope "/auth", EntenduWeb do
@ -44,10 +46,15 @@ defmodule EntenduWeb.Router do
end
scope "/uploads", EntenduWeb do
pipe_through [:browser, :authorized_links]
pipe_through [:browser, :authorized_files]
get "/*path", FileNotFoundController, :index
end
scope "/links", EntenduWeb do
pipe_through [:browser, :authorized_link]
get "/:id", LinkController, :authorized_link
end
# Other scopes may use custom stacks.
# scope "/api", EntenduWeb do
# pipe_through :api

View File

@ -31,9 +31,9 @@ defmodule Entendu.EncryptedLink do
# end
# Override the persisted filenames:
def filename(_version, {_file, %{filename: filename}}) do
if filename, do: filename, else: "text"
end
# def filename(_version, {_file, %{filename: filename}}) do
# if filename, do: filename, else: "text"
# end
# Override the storage directory:
def storage_dir(version, {_file, scope}) do