index.ts 10 KB

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