index.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import {
  2. ExcalidrawElement,
  3. NonDeletedExcalidrawElement,
  4. } from "../element/types";
  5. import { getDefaultAppState } from "../appState";
  6. import { AppState } from "../types";
  7. import { exportToCanvas, exportToSvg } from "../scene/export";
  8. import { fileSave } from "browser-nativefs";
  9. import { t } from "../i18n";
  10. import {
  11. copyCanvasToClipboardAsPng,
  12. copyTextToSystemClipboard,
  13. } from "../clipboard";
  14. import { serializeAsJSON } from "./json";
  15. import { ExportType } from "../scene/types";
  16. import { restore } from "./restore";
  17. import { ImportedDataState } from "./types";
  18. export { loadFromBlob } from "./blob";
  19. export { saveAsJSON, loadFromJSON } from "./json";
  20. const BACKEND_GET = process.env.REACT_APP_BACKEND_V1_GET_URL;
  21. const BACKEND_V2_POST = process.env.REACT_APP_BACKEND_V2_POST_URL;
  22. const BACKEND_V2_GET = process.env.REACT_APP_BACKEND_V2_GET_URL;
  23. export const SOCKET_SERVER = process.env.REACT_APP_SOCKET_SERVER_URL;
  24. export type EncryptedData = {
  25. data: ArrayBuffer;
  26. iv: Uint8Array;
  27. };
  28. export type SocketUpdateDataSource = {
  29. SCENE_INIT: {
  30. type: "SCENE_INIT";
  31. payload: {
  32. elements: readonly ExcalidrawElement[];
  33. };
  34. };
  35. SCENE_UPDATE: {
  36. type: "SCENE_UPDATE";
  37. payload: {
  38. elements: readonly ExcalidrawElement[];
  39. };
  40. };
  41. MOUSE_LOCATION: {
  42. type: "MOUSE_LOCATION";
  43. payload: {
  44. socketId: string;
  45. pointer: { x: number; y: number };
  46. button: "down" | "up";
  47. selectedElementIds: AppState["selectedElementIds"];
  48. username: string;
  49. };
  50. };
  51. };
  52. export type SocketUpdateDataIncoming =
  53. | SocketUpdateDataSource[keyof SocketUpdateDataSource]
  54. | {
  55. type: "INVALID_RESPONSE";
  56. };
  57. // TODO: Make this part of `AppState`.
  58. (window as any).handle = null;
  59. const byteToHex = (byte: number): string => `0${byte.toString(16)}`.slice(-2);
  60. const generateRandomID = async () => {
  61. const arr = new Uint8Array(10);
  62. window.crypto.getRandomValues(arr);
  63. return Array.from(arr, byteToHex).join("");
  64. };
  65. const generateEncryptionKey = async () => {
  66. const key = await window.crypto.subtle.generateKey(
  67. {
  68. name: "AES-GCM",
  69. length: 128,
  70. },
  71. true, // extractable
  72. ["encrypt", "decrypt"],
  73. );
  74. return (await window.crypto.subtle.exportKey("jwk", key)).k;
  75. };
  76. export const createIV = () => {
  77. const arr = new Uint8Array(12);
  78. return window.crypto.getRandomValues(arr);
  79. };
  80. export const getCollaborationLinkData = (link: string) => {
  81. if (link.length === 0) {
  82. return;
  83. }
  84. const hash = new URL(link).hash;
  85. return hash.match(/^#room=([a-zA-Z0-9_-]+),([a-zA-Z0-9_-]+)$/);
  86. };
  87. export const generateCollaborationLink = async () => {
  88. const id = await generateRandomID();
  89. const key = await generateEncryptionKey();
  90. return `${window.location.origin}${window.location.pathname}#room=${id},${key}`;
  91. };
  92. export const getImportedKey = (key: string, usage: KeyUsage) =>
  93. window.crypto.subtle.importKey(
  94. "jwk",
  95. {
  96. alg: "A128GCM",
  97. ext: true,
  98. k: key,
  99. key_ops: ["encrypt", "decrypt"],
  100. kty: "oct",
  101. },
  102. {
  103. name: "AES-GCM",
  104. length: 128,
  105. },
  106. false, // extractable
  107. [usage],
  108. );
  109. export const encryptAESGEM = async (
  110. data: Uint8Array,
  111. key: string,
  112. ): Promise<EncryptedData> => {
  113. const importedKey = await getImportedKey(key, "encrypt");
  114. const iv = createIV();
  115. return {
  116. data: await window.crypto.subtle.encrypt(
  117. {
  118. name: "AES-GCM",
  119. iv,
  120. },
  121. importedKey,
  122. data,
  123. ),
  124. iv,
  125. };
  126. };
  127. export const decryptAESGEM = async (
  128. data: ArrayBuffer,
  129. key: string,
  130. iv: Uint8Array,
  131. ): Promise<SocketUpdateDataIncoming> => {
  132. try {
  133. const importedKey = await getImportedKey(key, "decrypt");
  134. const decrypted = await window.crypto.subtle.decrypt(
  135. {
  136. name: "AES-GCM",
  137. iv: iv,
  138. },
  139. importedKey,
  140. data,
  141. );
  142. const decodedData = new TextDecoder("utf-8").decode(
  143. new Uint8Array(decrypted) as any,
  144. );
  145. return JSON.parse(decodedData);
  146. } catch (error) {
  147. window.alert(t("alerts.decryptFailed"));
  148. console.error(error);
  149. }
  150. return {
  151. type: "INVALID_RESPONSE",
  152. };
  153. };
  154. export const exportToBackend = async (
  155. elements: readonly ExcalidrawElement[],
  156. appState: AppState,
  157. ) => {
  158. const json = serializeAsJSON(elements, appState);
  159. const encoded = new TextEncoder().encode(json);
  160. const key = await window.crypto.subtle.generateKey(
  161. {
  162. name: "AES-GCM",
  163. length: 128,
  164. },
  165. true, // extractable
  166. ["encrypt", "decrypt"],
  167. );
  168. // The iv is set to 0. We are never going to reuse the same key so we don't
  169. // need to have an iv. (I hope that's correct...)
  170. const iv = new Uint8Array(12);
  171. // We use symmetric encryption. AES-GCM is the recommended algorithm and
  172. // includes checks that the ciphertext has not been modified by an attacker.
  173. const encrypted = await window.crypto.subtle.encrypt(
  174. {
  175. name: "AES-GCM",
  176. iv: iv,
  177. },
  178. key,
  179. encoded,
  180. );
  181. // We use jwk encoding to be able to extract just the base64 encoded key.
  182. // We will hardcode the rest of the attributes when importing back the key.
  183. const exportedKey = await window.crypto.subtle.exportKey("jwk", key);
  184. try {
  185. const response = await fetch(BACKEND_V2_POST, {
  186. method: "POST",
  187. body: encrypted,
  188. });
  189. const json = await response.json();
  190. if (json.id) {
  191. const url = new URL(window.location.href);
  192. // We need to store the key (and less importantly the id) as hash instead
  193. // of queryParam in order to never send it to the server
  194. url.hash = `json=${json.id},${exportedKey.k!}`;
  195. const urlString = url.toString();
  196. window.prompt(`🔒${t("alerts.uploadedSecurly")}`, urlString);
  197. } else {
  198. window.alert(t("alerts.couldNotCreateShareableLink"));
  199. }
  200. } catch (error) {
  201. console.error(error);
  202. window.alert(t("alerts.couldNotCreateShareableLink"));
  203. }
  204. };
  205. const importFromBackend = async (
  206. id: string | null,
  207. privateKey?: string | null,
  208. ): Promise<ImportedDataState> => {
  209. let elements: readonly ExcalidrawElement[] = [];
  210. let appState = getDefaultAppState();
  211. try {
  212. const response = await fetch(
  213. privateKey ? `${BACKEND_V2_GET}${id}` : `${BACKEND_GET}${id}.json`,
  214. );
  215. if (!response.ok) {
  216. window.alert(t("alerts.importBackendFailed"));
  217. return { elements, appState };
  218. }
  219. let data;
  220. if (privateKey) {
  221. const buffer = await response.arrayBuffer();
  222. const key = await getImportedKey(privateKey, "decrypt");
  223. const iv = new Uint8Array(12);
  224. const decrypted = await window.crypto.subtle.decrypt(
  225. {
  226. name: "AES-GCM",
  227. iv: iv,
  228. },
  229. key,
  230. buffer,
  231. );
  232. // We need to convert the decrypted array buffer to a string
  233. const string = new window.TextDecoder("utf-8").decode(
  234. new Uint8Array(decrypted) as any,
  235. );
  236. data = JSON.parse(string);
  237. } else {
  238. // Legacy format
  239. data = await response.json();
  240. }
  241. elements = data.elements || elements;
  242. appState = { ...appState, ...data.appState };
  243. } catch (error) {
  244. window.alert(t("alerts.importBackendFailed"));
  245. console.error(error);
  246. } finally {
  247. return { elements, appState };
  248. }
  249. };
  250. export const exportCanvas = async (
  251. type: ExportType,
  252. elements: readonly NonDeletedExcalidrawElement[],
  253. appState: AppState,
  254. canvas: HTMLCanvasElement,
  255. {
  256. exportBackground,
  257. exportPadding = 10,
  258. viewBackgroundColor,
  259. name,
  260. scale = 1,
  261. shouldAddWatermark,
  262. }: {
  263. exportBackground: boolean;
  264. exportPadding?: number;
  265. viewBackgroundColor: string;
  266. name: string;
  267. scale?: number;
  268. shouldAddWatermark: boolean;
  269. },
  270. ) => {
  271. if (elements.length === 0) {
  272. return window.alert(t("alerts.cannotExportEmptyCanvas"));
  273. }
  274. if (type === "svg" || type === "clipboard-svg") {
  275. const tempSvg = exportToSvg(elements, {
  276. exportBackground,
  277. viewBackgroundColor,
  278. exportPadding,
  279. shouldAddWatermark,
  280. });
  281. if (type === "svg") {
  282. await fileSave(new Blob([tempSvg.outerHTML], { type: "image/svg+xml" }), {
  283. fileName: `${name}.svg`,
  284. extensions: [".svg"],
  285. });
  286. return;
  287. } else if (type === "clipboard-svg") {
  288. copyTextToSystemClipboard(tempSvg.outerHTML);
  289. return;
  290. }
  291. }
  292. const tempCanvas = exportToCanvas(elements, appState, {
  293. exportBackground,
  294. viewBackgroundColor,
  295. exportPadding,
  296. scale,
  297. shouldAddWatermark,
  298. });
  299. tempCanvas.style.display = "none";
  300. document.body.appendChild(tempCanvas);
  301. if (type === "png") {
  302. const fileName = `${name}.png`;
  303. tempCanvas.toBlob(async (blob: any) => {
  304. if (blob) {
  305. await fileSave(blob, {
  306. fileName: fileName,
  307. extensions: [".png"],
  308. });
  309. }
  310. });
  311. } else if (type === "clipboard") {
  312. try {
  313. copyCanvasToClipboardAsPng(tempCanvas);
  314. } catch {
  315. window.alert(t("alerts.couldNotCopyToClipboard"));
  316. }
  317. } else if (type === "backend") {
  318. exportToBackend(elements, {
  319. ...appState,
  320. viewBackgroundColor: exportBackground
  321. ? appState.viewBackgroundColor
  322. : getDefaultAppState().viewBackgroundColor,
  323. });
  324. }
  325. // clean up the DOM
  326. if (tempCanvas !== canvas) {
  327. tempCanvas.remove();
  328. }
  329. };
  330. export const loadScene = async (
  331. id: string | null,
  332. privateKey?: string | null,
  333. initialData?: ImportedDataState,
  334. ) => {
  335. let data;
  336. if (id != null) {
  337. // the private key is used to decrypt the content from the server, take
  338. // extra care not to leak it
  339. data = restore(await importFromBackend(id, privateKey));
  340. } else {
  341. data = restore(initialData || {});
  342. }
  343. return {
  344. elements: data.elements,
  345. appState: data.appState,
  346. commitToHistory: false,
  347. };
  348. };