π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Switch twoof3 recovery to bundled QR decoding
Manav Rathi3293f3caee9b
diff --git a/web/apps/twoof3/next.config.js b/web/apps/twoof3/next.config.jsindex 511bb9d14c..a502745ca6 100644--- a/web/apps/twoof3/next.config.js+++ b/web/apps/twoof3/next.config.js@@ -1,7 +1,31 @@+const path = require("path");const baseConfig = require("ente-base/next.config.base.js");module.exports = {...baseConfig,+ webpack: (config, options) => {+ const nextConfig = baseConfig.webpack+ ? baseConfig.webpack(config, options)+ : config;++ nextConfig.module.rules.push({+ resourceQuery: /raw/,+ type: "asset/source",+ });+ nextConfig.resolve.alias = {+ ...(nextConfig.resolve.alias || {}),+ "qr-raw/decode.js": path.resolve(+ __dirname,+ "../../node_modules/qr/decode.js",+ ),+ "qr-raw/index.js": path.resolve(+ __dirname,+ "../../node_modules/qr/index.js",+ ),+ };++ return nextConfig;+ },...(process.env.NODE_ENV === "development" && {output: undefined,async rewrites() {diff --git a/web/apps/twoof3/package.json b/web/apps/twoof3/package.jsonindex de5ac66c11..48c82eb25a 100644--- a/web/apps/twoof3/package.json+++ b/web/apps/twoof3/package.json@@ -5,7 +5,7 @@"dependencies": {"@fontsource/space-grotesk": "^5.2.10","ente-base": "*",- "nayuki-qr-code-generator": "^1.8.0"+ "qr": "^0.5.5"},"devDependencies": {"ente-build-config": "*"diff --git a/web/apps/twoof3/src/features/twoof3/utils/export.ts b/web/apps/twoof3/src/features/twoof3/utils/export.tsindex 9e22dd197e..7227a8fb80 100644--- a/web/apps/twoof3/src/features/twoof3/utils/export.ts+++ b/web/apps/twoof3/src/features/twoof3/utils/export.ts@@ -112,7 +112,12 @@ const drawQr = (top: number,size: number,) => {- const moduleSize = size / qrSize;+ const moduleSize = Math.max(1, Math.floor(size / qrSize));+ const drawnSize = moduleSize * qrSize;+ const offsetX = Math.floor((size - drawnSize) / 2);+ const offsetY = Math.floor((size - drawnSize) / 2);+ const startX = left + offsetX;+ const startY = top + offsetY;context.fillStyle = "#ffffff";context.fillRect(left, top, size, size);@@ -120,8 +125,8 @@ const drawQr = (for (const module of modules) {context.fillStyle = "#111111";context.fillRect(- left + module.x * moduleSize,- top + module.y * moduleSize,+ startX + module.x * moduleSize,+ startY + module.y * moduleSize,moduleSize,moduleSize,);@@ -256,7 +261,13 @@ export const canvasToBlob = async (canvas: HTMLCanvasElement) =>}, "image/png");});-export const createOfflineRecoveryHtml = () => `<!doctype html>+const escapeScriptTagContent = (value: string) =>+ value.replace(/<\/script/giu, "<\\/script");++export const createOfflineRecoveryHtml = async () => {+ const { OFFLINE_QR_DECODER_SOURCE } = await import("./offlineQrSource");++ return `<!doctype html><html lang="en"><head><meta charset="utf-8" />@@ -363,7 +374,7 @@ export const createOfflineRecoveryHtml = () => `<!doctype html><div class="panel"><div class="eyebrow">Recover later</div><h1>Recover with any two cards.</h1>- <p>This file works offline. Upload two card images if your browser can read QR codes, or paste the two code strings manually.</p>+ <p>This file works offline. Upload two card images, or paste the two code strings manually.</p><div class="grid"><div><input id="file-a" type="file" accept="image/*,text/plain" />@@ -379,6 +390,7 @@ export const createOfflineRecoveryHtml = () => `<!doctype html><div id="result" class="result" hidden></div></div></main>+ <script>${escapeScriptTagContent(OFFLINE_QR_DECODER_SOURCE)}</script><script>const GF_POLY = 0x11b;const VERSION = 1;@@ -468,27 +480,129 @@ export const createOfflineRecoveryHtml = () => `<!doctype html>}return new TextDecoder().decode(output);};+ const loadImageFromFile = (file) =>+ new Promise((resolve, reject) => {+ const objectUrl = URL.createObjectURL(file);+ const image = new Image();+ image.onload = () => {+ resolve({+ dispose: () => URL.revokeObjectURL(objectUrl),+ height: image.naturalHeight,+ source: image,+ width: image.naturalWidth,+ });+ };+ image.onerror = () => {+ URL.revokeObjectURL(objectUrl);+ reject(new Error("Could not read that image."));+ };+ image.src = objectUrl;+ });+ const loadDrawableFromFile = async (file) => {+ if (typeof createImageBitmap === "function") {+ try {+ const bitmap = await createImageBitmap(file);+ return {+ dispose: () => bitmap.close(),+ height: bitmap.height,+ source: bitmap,+ width: bitmap.width,+ };+ } catch {}+ }+ return loadImageFromFile(file);+ };+ const imageDataFromFile = async (file) => {+ const drawable = await loadDrawableFromFile(file);+ const canvas = document.createElement("canvas");+ canvas.width = drawable.width;+ canvas.height = drawable.height;+ const context = canvas.getContext("2d");+ if (!context) {+ drawable.dispose();+ throw new Error("Could not read that image.");+ }+ try {+ context.drawImage(drawable.source, 0, 0, canvas.width, canvas.height);+ return context.getImageData(0, 0, canvas.width, canvas.height);+ } finally {+ drawable.dispose();+ }+ };+ const cropImage = (image, leftRatio, topRatio, widthRatio, heightRatio) => {+ const left = Math.max(0, Math.floor(image.width * leftRatio));+ const top = Math.max(0, Math.floor(image.height * topRatio));+ const width = Math.min(+ image.width - left,+ Math.floor(image.width * widthRatio),+ );+ const height = Math.min(+ image.height - top,+ Math.floor(image.height * heightRatio),+ );+ if (width < 64 || height < 64) return null;+ const data = new Uint8ClampedArray(width * height * 4);+ for (let row = 0; row < height; row++) {+ const sourceOffset = ((top + row) * image.width + left) * 4;+ const targetOffset = row * width * 4;+ data.set(+ image.data.slice(sourceOffset, sourceOffset + width * 4),+ targetOffset,+ );+ }+ return { data, height, width };+ };+ const decodeQrImage = (image) => {+ const decodeQR = globalThis.__twoOf3DecodeQR;+ if (typeof decodeQR !== "function") {+ throw new Error("Offline QR decoder could not load.");+ }+ const attempts = [+ { image, options: { cropToSquare: false } },+ { image },+ ];+ const cardLikeCrops = [+ [0.086, 0.213, 0.829, 0.591],+ [0.135, 0.238, 0.73, 0.49],+ [0.16, 0.255, 0.68, 0.52],+ ];+ for (const crop of cardLikeCrops) {+ const cropped = cropImage(image, ...crop);+ if (!cropped) continue;+ attempts.push(+ { image: cropped, options: { cropToSquare: false } },+ { image: cropped },+ );+ }+ let lastError = null;+ for (const attempt of attempts) {+ try {+ return decodeQR(attempt.image, attempt.options).trim();+ } catch (error) {+ lastError = error;+ }+ }+ throw lastError || new Error("Could not read that QR code.");+ };const fileToText = async (file) => {- if (file.type.startsWith("text/")) return file.text();- if (!("BarcodeDetector" in window)) throw new Error("QR image upload is not supported in this browser. Paste the code instead.");- const detector = new BarcodeDetector({ formats: ["qr_code"] });- const bitmap = await createImageBitmap(file);- const results = await detector.detect(bitmap);- bitmap.close();- const value = results[0] && results[0].rawValue;- if (!value) throw new Error("Could not read a QR code from that image.");+ if (file.type.startsWith("text/")) return (await file.text()).trim();+ const value = decodeQrImage(await imageDataFromFile(file));+ parseShare(value);return value;};const bindFile = (fileId, textareaId) => {const fileInput = document.getElementById(fileId);const textarea = document.getElementById(textareaId);+ const errorNode = document.getElementById("error");fileInput.addEventListener("change", async (event) => {const file = event.target.files && event.target.files[0];if (!file) return;try {textarea.value = (await fileToText(file)).trim();+ errorNode.textContent = "";} catch (error) {- document.getElementById("error").textContent = error.message || String(error);+ textarea.value = "";+ errorNode.textContent = error.message || String(error);}});};@@ -499,11 +613,14 @@ export const createOfflineRecoveryHtml = () => `<!doctype html>const resultNode = document.getElementById("result");errorNode.textContent = "";resultNode.hidden = true;+ const firstInput = document.getElementById("input-a").value.trim();+ const secondInput = document.getElementById("input-b").value.trim();+ if (!firstInput || !secondInput) {+ errorNode.textContent = "Upload or paste two cards first.";+ return;+ }try {- const secret = combineShares(- document.getElementById("input-a").value,- document.getElementById("input-b").value- );+ const secret = combineShares(firstInput, secondInput);resultNode.textContent = secret;resultNode.hidden = false;} catch (error) {@@ -513,9 +630,10 @@ export const createOfflineRecoveryHtml = () => `<!doctype html></script></body></html>`;+};-export const offlineRecoveryFile = () =>- new File([createOfflineRecoveryHtml()], "2of3-recovery.html", {+export const offlineRecoveryFile = async () =>+ new File([await createOfflineRecoveryHtml()], "2of3-recovery.html", {type: "text/html;charset=utf-8",});diff --git a/web/apps/twoof3/src/features/twoof3/utils/offlineQrSource.ts b/web/apps/twoof3/src/features/twoof3/utils/offlineQrSource.tsnew file mode 100644index 0000000000..0cb16538c0--- /dev/null+++ b/web/apps/twoof3/src/features/twoof3/utils/offlineQrSource.ts@@ -0,0 +1,36 @@+import qrDecodeModuleSource from "qr-raw/decode.js?raw";+import qrIndexModuleSource from "qr-raw/index.js?raw";++const stripSourceMapComment = (source: string) =>+ source.replace(/^\/\/# sourceMappingURL=.*$/gmu, "").trim();++const toStandaloneIndexSource = (source: string) =>+ stripSourceMapComment(source)+ .replace(/^export class Bitmap/mu, "class Bitmap")+ .replace(/^export const ECMode = /mu, "const ECMode = ")+ .replace(/^export const Encoding = /mu, "const Encoding = ")+ .replace(/^export function utf8ToBytes\(/mu, "function utf8ToBytes(")+ .replace(/^export function encodeQR\(/mu, "function encodeQR(")+ .replace(/^export default encodeQR;\n?/mu, "")+ .replace(/^export const utils = /mu, "const utils = ")+ .replace(/^export const _tests = /mu, "const qrIndexTests = ");++const toStandaloneDecodeSource = (source: string) =>+ [+ "const decodeQR = (() => {",+ stripSourceMapComment(source)+ .replace(/^import \{ Bitmap, utils \} from "\.\/index\.js";\n?/mu, "")+ .replace(/^export function decodeQR\(/mu, "function decodeQR(")+ .replace(/^export default decodeQR;\n?/mu, "")+ .replace(/^export const _tests = /mu, "const qrDecodeTests = "),+ "return decodeQR;",+ "})();",+ ].join("\n");++export const OFFLINE_QR_DECODER_SOURCE = [+ "(() => {",+ toStandaloneIndexSource(qrIndexModuleSource),+ toStandaloneDecodeSource(qrDecodeModuleSource),+ 'globalThis.__twoOf3DecodeQR = decodeQR;',+ "})();",+].join("\n\n");diff --git a/web/apps/twoof3/src/features/twoof3/utils/qrCode.ts b/web/apps/twoof3/src/features/twoof3/utils/qrCode.tsindex 010a5c3290..4ff4807d09 100644--- a/web/apps/twoof3/src/features/twoof3/utils/qrCode.ts+++ b/web/apps/twoof3/src/features/twoof3/utils/qrCode.ts@@ -1,4 +1,4 @@-import qrcodegen from "nayuki-qr-code-generator";+import encodeQR from "qr";export interface QrModule {finder: boolean;@@ -11,7 +11,17 @@ export interface QrSvgData {viewBoxSize: number;}-const QR_BORDER_MODULES = 2;+const QR_BORDER_MODULES = 4;++let decodeQrPromise: Promise<+ (typeof import("qr/decode.js"))["default"]+> | null = null;++interface DecodableImage {+ data: Uint8ClampedArray | number[];+ height: number;+ width: number;+}const isFinderModule = (x: number, y: number, size: number) => {const inTopBand = y < 7;@@ -28,25 +38,173 @@ const isFinderModule = (x: number, y: number, size: number) => {export const createQrSvgData = (value: string): QrSvgData | null => {try {- const qr = qrcodegen.QrCode.encodeText(- value,- qrcodegen.QrCode.Ecc.MEDIUM,- );+ const qr = encodeQR(value, "raw", { border: 0, ecc: "medium" });const modules: QrModule[] = [];- for (let y = 0; y < qr.size; y++) {- for (let x = 0; x < qr.size; x++) {- if (!qr.getModule(x, y)) continue;+ for (let y = 0; y < qr.length; y++) {+ for (let x = 0; x < qr[y]!.length; x++) {+ if (!qr[y]![x]) continue;modules.push({- finder: isFinderModule(x, y, qr.size),+ finder: isFinderModule(x, y, qr.length),x: x + QR_BORDER_MODULES,y: y + QR_BORDER_MODULES,});}}- return { modules, viewBoxSize: qr.size + QR_BORDER_MODULES * 2 };+ return { modules, viewBoxSize: qr.length + QR_BORDER_MODULES * 2 };} catch {return null;}};++interface DrawableImage {+ dispose: () => void;+ height: number;+ source: CanvasImageSource;+ width: number;+}++const loadImageFromFile = (file: File) =>+ new Promise<DrawableImage>((resolve, reject) => {+ const objectUrl = URL.createObjectURL(file);+ const image = new Image();++ image.onload = () => {+ resolve({+ dispose: () => URL.revokeObjectURL(objectUrl),+ height: image.naturalHeight,+ source: image,+ width: image.naturalWidth,+ });+ };+ image.onerror = () => {+ URL.revokeObjectURL(objectUrl);+ reject(new Error("Could not read that image."));+ };+ image.src = objectUrl;+ });++const loadDrawableFromFile = async (file: File): Promise<DrawableImage> => {+ if (typeof createImageBitmap === "function") {+ try {+ const bitmap = await createImageBitmap(file);+ return {+ dispose: () => bitmap.close(),+ height: bitmap.height,+ source: bitmap,+ width: bitmap.width,+ };+ } catch {+ // Fall through to HTMLImageElement decoding when bitmap decode fails.+ }+ }++ return loadImageFromFile(file);+};++const imageDataFromFile = async (file: File) => {+ const drawable = await loadDrawableFromFile(file);+ const canvas = document.createElement("canvas");+ canvas.width = drawable.width;+ canvas.height = drawable.height;++ const context = canvas.getContext("2d");+ if (!context) {+ drawable.dispose();+ throw new Error("Could not read that image.");+ }++ try {+ context.drawImage(drawable.source, 0, 0, canvas.width, canvas.height);+ return context.getImageData(0, 0, canvas.width, canvas.height);+ } finally {+ drawable.dispose();+ }+};++const cropImage = (+ image: DecodableImage,+ leftRatio: number,+ topRatio: number,+ widthRatio: number,+ heightRatio: number,+): DecodableImage | null => {+ const left = Math.max(0, Math.floor(image.width * leftRatio));+ const top = Math.max(0, Math.floor(image.height * topRatio));+ const width = Math.min(+ image.width - left,+ Math.floor(image.width * widthRatio),+ );+ const height = Math.min(+ image.height - top,+ Math.floor(image.height * heightRatio),+ );++ if (width < 64 || height < 64) return null;++ const data = new Uint8ClampedArray(width * height * 4);+ for (let row = 0; row < height; row++) {+ const sourceOffset = ((top + row) * image.width + left) * 4;+ const targetOffset = row * width * 4;+ data.set(+ image.data.slice(sourceOffset, sourceOffset + width * 4),+ targetOffset,+ );+ }++ return { data, height, width };+};++const decodeQrImage = async (image: DecodableImage) => {+ decodeQrPromise ??= import("qr/decode.js").then(({ default: decodeQR }) => {+ return decodeQR;+ });++ const decodeQR = await decodeQrPromise;+ const attempts: {+ image: DecodableImage;+ options?: { cropToSquare?: boolean };+ }[] = [+ { image, options: { cropToSquare: false } },+ { image },+ ];+ const cardLikeCrops = [+ [0.086, 0.213, 0.829, 0.591],+ [0.135, 0.238, 0.73, 0.49],+ [0.16, 0.255, 0.68, 0.52],+ ] as const;+ for (const crop of cardLikeCrops) {+ const [leftRatio, topRatio, widthRatio, heightRatio] = crop;+ const cropped = cropImage(+ image,+ leftRatio,+ topRatio,+ widthRatio,+ heightRatio,+ );+ if (!cropped) continue;+ attempts.push(+ { image: cropped, options: { cropToSquare: false } },+ { image: cropped },+ );+ }++ let lastError: unknown = null;+ for (const attempt of attempts) {+ try {+ return decodeQR(attempt.image, attempt.options).trim();+ } catch (error) {+ lastError = error;+ }+ }++ throw lastError instanceof Error+ ? lastError+ : new Error("Could not read that QR code.");+};++export const decodeQrFromFile = async (file: File) => {+ const imageData = await imageDataFromFile(file);+ return decodeQrImage(imageData);+};diff --git a/web/apps/twoof3/src/pages/index.tsx b/web/apps/twoof3/src/pages/index.tsxindex f68316f8e9..8936c3358e 100644--- a/web/apps/twoof3/src/pages/index.tsx+++ b/web/apps/twoof3/src/pages/index.tsx@@ -16,7 +16,10 @@ import {sanitizeFilename,shareFiles,} from "features/twoof3/utils/export";-import { createQrSvgData } from "features/twoof3/utils/qrCode";+import {+ createQrSvgData,+ decodeQrFromFile,+} from "features/twoof3/utils/qrCode";import {combineShares,parseShare,@@ -66,12 +69,6 @@ interface RecoverSlotDetails {length: number;}-interface BrowserWithBarcodeDetector extends Window {- BarcodeDetector?: new (options?: { formats?: string[] }) => {- detect: (source: ImageBitmap) => Promise<{ rawValue?: string }[]>;- };-}-const todayLabel = () =>new Intl.DateTimeFormat(undefined, {day: "numeric",@@ -156,11 +153,13 @@ const QrPreview = ({viewBox={`0 0 ${value.viewBoxSize} ${value.viewBoxSize}`}role="img"aria-label="QR code"+ shapeRendering="crispEdges"style={{width: "100%",height: "100%",display: "block",background: "#ffffff",+ imageRendering: "pixelated",}}><rect@@ -273,28 +272,7 @@ const readShareFile = async (file: File) => {return (await file.text()).trim();}- const barcodeWindow = window as BrowserWithBarcodeDetector;- if (!barcodeWindow.BarcodeDetector) {- throw new Error(- "This browser cannot read QR images. Paste the code instead.",- );- }-- const detector = new barcodeWindow.BarcodeDetector({- formats: ["qr_code"],- });- const bitmap = await createImageBitmap(file);-- try {- const matches = await detector.detect(bitmap);- const rawValue = matches[0]?.rawValue?.trim();- if (!rawValue) {- throw new Error("Could not find a QR code in that image.");- }- return rawValue;- } finally {- bitmap.close();- }+ return decodeQrFromFile(file);};const copyTextToClipboard = async (value: string) => {@@ -436,7 +414,7 @@ const Page = () => {downloadBlob(file, file.name);}- const recovery = offlineRecoveryFile();+ const recovery = await offlineRecoveryFile();downloadBlob(recovery, recovery.name);} catch (error) {setActionError(diff --git a/web/apps/twoof3/src/types/raw.d.ts b/web/apps/twoof3/src/types/raw.d.tsnew file mode 100644index 0000000000..811f0eb289--- /dev/null+++ b/web/apps/twoof3/src/types/raw.d.ts@@ -0,0 +1,5 @@+declare module "*?raw" {+ const content: string;++ export default content;+}diff --git a/web/yarn.lock b/web/yarn.lockindex 40f439f34f..21627af325 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -4235,11 +4235,6 @@ natural-compare@^1.4.0:resolved "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz"integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==-nayuki-qr-code-generator@^1.8.0:- version "1.8.0"- resolved "https://registry.yarnpkg.com/nayuki-qr-code-generator/-/nayuki-qr-code-generator-1.8.0.tgz#dbeebd7b3d2b53119c51a596ad43199ef6798916"- integrity sha512-wnpXdJ+zJ+8QzzGJTEnESaRYfNIUHSgX4ykvYuaomqqUbhJdun3v0sK/39BQjw3on/vf7ujPKIg2V07WejjmLw==-next@^15.5.9:version "15.5.9"resolved "https://registry.npmjs.org/next/-/next-15.5.9.tgz"@@ -4561,6 +4556,11 @@ qr-code-styling@^1.9.2:dependencies:qrcode-generator "^1.4.4"+qr@^0.5.5:+ version "0.5.5"+ resolved "https://registry.yarnpkg.com/qr/-/qr-0.5.5.tgz#0fbe55a97a8641b04ace23d3a07052f8db7d8827"+ integrity sha512-iQBvKj7MRKO+co+MY0IZpyLO+ezvttxsmV86WywrgPuAmgBkv0pytyi03wourniSoPgzffeBW6cBgIkpqcvjTg==+qrcode-generator@^1.4.4:version "1.5.2"resolved "https://registry.yarnpkg.com/qrcode-generator/-/qrcode-generator-1.5.2.tgz#43faea8061a60d2b4ca5e9b0c0c0fb99e2d93e3a"