index.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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: 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: 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: 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. 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. scale,
  280. shouldAddWatermark,
  281. metadata:
  282. appState.exportEmbedScene && type === "svg"
  283. ? await (
  284. await import(/* webpackChunkName: "image" */ "./image")
  285. ).encodeSvgMetadata({
  286. text: serializeAsJSON(elements, appState),
  287. })
  288. : undefined,
  289. });
  290. if (type === "svg") {
  291. await fileSave(new Blob([tempSvg.outerHTML], { type: "image/svg+xml" }), {
  292. fileName: `${name}.svg`,
  293. extensions: [".svg"],
  294. });
  295. return;
  296. } else if (type === "clipboard-svg") {
  297. copyTextToSystemClipboard(tempSvg.outerHTML);
  298. return;
  299. }
  300. }
  301. const tempCanvas = exportToCanvas(elements, appState, {
  302. exportBackground,
  303. viewBackgroundColor,
  304. exportPadding,
  305. scale,
  306. shouldAddWatermark,
  307. });
  308. tempCanvas.style.display = "none";
  309. document.body.appendChild(tempCanvas);
  310. if (type === "png") {
  311. const fileName = `${name}.png`;
  312. let blob = await canvasToBlob(tempCanvas);
  313. if (appState.exportEmbedScene) {
  314. blob = await (
  315. await import(/* webpackChunkName: "image" */ "./image")
  316. ).encodePngMetadata({
  317. blob,
  318. metadata: serializeAsJSON(elements, appState),
  319. });
  320. }
  321. await fileSave(blob, {
  322. fileName: fileName,
  323. extensions: [".png"],
  324. });
  325. } else if (type === "clipboard") {
  326. try {
  327. await copyCanvasToClipboardAsPng(tempCanvas);
  328. } catch (error) {
  329. if (error.name === "CANVAS_POSSIBLY_TOO_BIG") {
  330. throw error;
  331. }
  332. throw new Error(t("alerts.couldNotCopyToClipboard"));
  333. }
  334. } else if (type === "backend") {
  335. exportToBackend(elements, {
  336. ...appState,
  337. viewBackgroundColor: exportBackground
  338. ? appState.viewBackgroundColor
  339. : getDefaultAppState().viewBackgroundColor,
  340. });
  341. }
  342. // clean up the DOM
  343. if (tempCanvas !== canvas) {
  344. tempCanvas.remove();
  345. }
  346. };
  347. export const loadScene = async (
  348. id: string | null,
  349. privateKey: string | null,
  350. // Supply initialData even if importing from backend to ensure we restore
  351. // localStorage user settings which we do not persist on server.
  352. // Non-optional so we don't forget to pass it even if `undefined`.
  353. initialData: ImportedDataState | undefined | null,
  354. ) => {
  355. let data;
  356. if (id != null) {
  357. // the private key is used to decrypt the content from the server, take
  358. // extra care not to leak it
  359. data = restore(
  360. await importFromBackend(id, privateKey),
  361. initialData?.appState,
  362. );
  363. } else {
  364. data = restore(initialData || {}, null);
  365. }
  366. return {
  367. elements: data.elements,
  368. appState: data.appState,
  369. commitToHistory: false,
  370. };
  371. };