index.ts 9.8 KB

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