Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
type: block layout and style values are checked where they become CSS (#833)
nyblnet3afc7f3344cc
diff --git a/scripts/test-type-embed.ts b/scripts/test-type-embed.tsindex dc0ff983..f604ee4f 100644--- a/scripts/test-type-embed.ts+++ b/scripts/test-type-embed.ts@@ -139,5 +139,15 @@ console.log('\n— embedded documents don\'t carry sharing keys —');'and a FILE cannot carry such an id at all: parseDoc keeps only ids of a safe charset (a normal id survives)');}+// ───────────────────── a mark type that is not one of ours renders as a plain span+// (a synced mark never passed parseDoc; `constructor` used to read an inherited+// property — a function's source — into the markup as a tag name)+{+ const { blockHtml } = await import('../type/src/render.ts');+ const html = blockHtml({ id: 'b1', kind: 'para', text: 'Hello world', marks: [{ t: 'constructor', from: 0, to: 5 }, { t: '__proto__', from: 6, to: 11 }] } as never);+ ok(!/function|native code|\[object/i.test(html), `an unknown mark type never reads an inherited property into the markup (${html.slice(0, 80)})`);+ ok(html.includes('Hello') && html.includes('world'), 'and the text itself still renders');+}+console.log(`\n${checks - bad}/${checks} checks passed`);if (bad) process.exit(1);diff --git a/scripts/test-type-printframe-browser.mjs b/scripts/test-type-printframe-browser.mjsindex 4006cf55..e8cf2624 100644--- a/scripts/test-type-printframe-browser.mjs+++ b/scripts/test-type-printframe-browser.mjs@@ -169,6 +169,18 @@ try {'page.marginTop': (d) => { d.page.marginTop = `10px;background:url(http://rc.test/${tag}-mt)` },'page.marginX': (d) => { d.page.marginX = `10px;background:url(http://rc.test/${tag}-mx)` },'page.marginBottom': (d) => { d.page.marginBottom = `10px;background:url(http://rc.test/${tag}-mb)` },+ // a block's own layout, and a named style's — both written by blockStyle /+ // styleDeclarations into the editor, print and the saved preview+ 'block.align': (d) => { d.body[0].align = `left;background:url(http://rc.test/${tag}-align)` },+ 'block.lh': (d) => { d.body[0].lh = `1;background:url(http://rc.test/${tag}-lh)` },+ 'block.sb': (d) => { d.body[0].sb = `1;background:url(http://rc.test/${tag}-sb)` },+ 'block.sa': (d) => { d.body[0].sa = `1;background:url(http://rc.test/${tag}-sa)` },+ 'block.ind': (d) => { d.body[0].ind = `1;background:url(http://rc.test/${tag}-ind)` },+ 'style.align': (d) => { d.styles = { s1: { id: 's1', name: 'S', kind: 'para', align: `left;background:url(http://rc.test/${tag}-salign)` } }; d.body[0].styleId = 's1' },+ 'style.lh': (d) => { d.styles = { s1: { id: 's1', name: 'S', kind: 'para', lh: `1;background:url(http://rc.test/${tag}-slh)` } }; d.body[0].styleId = 's1' },+ 'style.sb': (d) => { d.styles = { s1: { id: 's1', name: 'S', kind: 'para', sb: `1;background:url(http://rc.test/${tag}-ssb)` } }; d.body[0].styleId = 's1' },+ // the preview's colours: `rgb…` used to match with no end anchor+ 'theme.background': (d) => { d.theme = { background: `rgb(0,0,0);}*{background:url(http://rc.test/${tag}-theme)}` } },})for (const name of Object.keys(CSSP('x'))) {const hits = []@@ -203,6 +215,63 @@ try {await ctx.close()}+ // ───────────────────────── 0c. a style id cannot end its CSS string+ // The live editor writes named styles as `[data-style-id="<id>"]` rules into+ // #t-style-rules. A newline, CR or form feed ENDS a CSS string, so an id+ // escaped only for `\` and `"` let what followed it be parsed as rules.+ // From a FILE (parseDoc) and from a SYNCED op (store mutated, then the+ // editor re-renders — no parseDoc), for each of the three. The positive+ // control writes the same id the old way into a sheet of its own and must+ // fetch, so a clean row means the escape held, not that the payload is dead.+ console.log('\n0c. a style id with a newline, CR or form feed stays inside its selector\n')+ const SID = (ch, tag) => `x${ch}]{}*{background:url(http://rc.test/sid-${tag})}`+ const CHARS = { '\\n': '\n', '\\r': '\r', '\\f': '\f' }+ for (const [label, ch] of Object.entries(CHARS)) {+ for (const via of ['control', 'file', 'synced']) {+ const hits = []+ const ctx = await browser.newContext()+ await ctx.route(/^https?:/, (r) => { if (r.request().url().includes('rc.test')) hits.push(r.request().url()); r.abort() })+ const p = await ctx.newPage()+ await p.goto(SHELL.href)+ await p.waitForFunction(() => window.bento?.doc)+ const id = SID(ch, `${via}-${label.slice(1)}`)+ const body = [{ id: 'b1', kind: 'para', text: 'Hello', styleId: id }]+ if (via === 'control') {+ // the OLD escape (only \ and "), into a sheet the rig owns+ await p.evaluate((id) => {+ const old = id.replace(/\\/g, '\\\\').replace(/"/g, '\\"')+ const st = document.createElement('style'); st.textContent = `.t-paper [data-style-id="${old}"]{font-size:14px}`+ document.head.appendChild(st)+ }, id)+ } else if (via === 'file') {+ await p.evaluate((j) => window.bento.loadDoc(j), JSON.stringify({ format: 'bento/type', docId: 'doc-sid', title: 't',+ styles: { [id]: { id, name: 'S', kind: 'para', size: 14 } }, body }))+ } else {+ await p.evaluate((j) => window.bento.loadDoc(j), JSON.stringify({ format: 'bento/type', docId: 'doc-sid', title: 't',+ body: [{ id: 'b1', kind: 'para', text: 'Hello' }] }))+ await p.evaluate(({ id }) => {+ const d = window.bento.store.doc+ d.styles = { [id]: { id, name: 'S', kind: 'para', size: 14 } }+ d.body[0].styleId = id+ window.bento.editor.render()+ }, { id })+ }+ await p.waitForTimeout(400)+ const star = await p.evaluate(() => [...document.styleSheets].flatMap((sh) => { try { return [...sh.cssRules] } catch { return [] } })+ .filter((r) => r.selectorText === '*' && /rc\.test/.test(r.cssText)).length)+ const rules = await p.evaluate(() => document.getElementById('t-style-rules')?.textContent || '')+ const size = await p.evaluate(() => { const el = document.querySelector('#paper [data-block-id="b1"], #paper [data-id="b1"]') || document.querySelector('#paper [data-style-id]'); return el ? getComputedStyle(el).fontSize : '' })+ const kept = await p.evaluate((id) => Object.hasOwn(window.bento.doc.styles || {}, id), id)+ if (via === 'control') ok(hits.length > 0 && star > 0,+ `control ${label}: the id escaped the OLD way breaks out (a * rule ${star}, fetched ${hits.length}), so the oracle can see it`)+ else ok(hits.length === 0 && star === 0,+ `${via} ${label}: the id stays in its selector (no * rule ${star}, fetched ${hits.length}${via === 'synced' ? `, rule written ${/data-style-id/.test(rules)}` : ''})`)+ if (via === 'synced') ok(/data-style-id/.test(rules) && size === '14px', `synced ${label}: and the style still APPLIES — the escaped selector matches its paragraph (font-size ${size})`)+ if (via === 'file') ok(!kept, `file ${label}: and parseDoc refuses the id outright (kept ${kept})`)+ await ctx.close()+ }+ }+// ─────────────────────────────────────────── 1. the builder emits inert markupconst H = `"'><img src=x onerror="top.__pwned=(top.__pwned||0)+1"><script>top.__pwned=(top.__pwned||0)+1</script></style><style></style><script>top.__pwned=(top.__pwned||0)+1</script><svg onload="top.__pwned=(top.__pwned||0)+1"></svg><iframe srcdoc="x"></iframe><base href="javascript:1"><meta http-equiv="refresh" content="0;url=javascript:1">`const JS = 'javascript:top.__pwned=(top.__pwned||0)+1'diff --git a/scripts/test-type-styles.ts b/scripts/test-type-styles.tsindex 16f04dda..b12d3b51 100644--- a/scripts/test-type-styles.ts+++ b/scripts/test-type-styles.ts@@ -372,8 +372,17 @@ H('styleSheetCss — the mechanism the live editor actually uses');// reaches an id in practiceconst hostile: TypeDoc = { ...doc, styles: { 'x"}body{display:none}[x="y': { id: 'x"}body{display:none}[x="y', kind: 'para', name: 'x', size: 10 } } };const hcss = styleSheetCss(hostile);- ok(hcss.includes('\\"') && !hcss.includes('}body{display:none}[x="y"]{font-size'),+ ok(hcss.includes('\\22 ') && !hcss.includes('}body{'),'a quote inside a style id is escaped, not left to break out of the selector');+ // a newline, CR or form feed ENDS a CSS string — escaping only \\ and " left+ // these open (measured in the editor: the rule after the id applied)+ for (const [label, ch, hex] of [['newline', '\n', 'a'], ['CR', '\r', 'd'], ['form feed', '\f', 'c']]) {+ const nid = `x${ch}]{}*{background:url(http://rc.test/x)}`;+ const ncss = styleSheetCss({ ...doc, styles: { [nid]: { id: nid, kind: 'para', name: 'x', size: 10 } } });+ const rule = ncss.split('\n').find(r => r.includes('font-size:10px')) ?? '';+ ok(rule.startsWith(`.t-paper [data-style-id="x\\${hex} `) && rule.endsWith('"]{font-size:10px}') && !ncss.includes(']{}*{'),+ `a ${label} inside a style id is a hex escape, so the id stays one selector (${JSON.stringify(rule.slice(0, 60))})`);+ }}console.log(`\n${checks - failures}/${checks} checks passed`);diff --git a/type/src/docstyles.ts b/type/src/docstyles.tsindex d8c29216..b3cadc79 100644--- a/type/src/docstyles.ts+++ b/type/src/docstyles.ts@@ -39,7 +39,7 @@import { fontAcross, safeFamily, safeSize } from './inline.ts';import type { Block, BlockKind, DocStyle, TypeDoc } from './model.ts';-import { docEffective, propsOf, type ParaLayout } from './layout.ts';+import { docEffective, propsOf, cssAlign, cssLen, type ParaLayout } from './layout.ts';import { t } from './i18n.ts';import type { FeatureContext } from './features.ts';// NOT `import './docstyles.css'` here: render.ts imports this module for@@ -169,16 +169,20 @@ function styleDeclarations(s: DocStyle): string {if (s.italic) out.push('font-style:italic');const color = safeStyleColor(s.color);if (color) out.push(`color:${color}`);- if (s.align) out.push(`text-align:${s.align}`);- if (s.lh !== undefined) out.push(`line-height:${s.lh}`);+ // checked at the write, as layout.ts blockStyle does (a synced style never+ // passed parseDoc)+ const align = cssAlign(s.align), lh = cssLen(s.lh, 0.5, 4);+ if (align) out.push(`text-align:${align}`);+ if (lh !== null) out.push(`line-height:${lh}`);// `padding-top:0` rides with `sb`, mirroring layout.ts's blockStyle: the// stylesheet spaces consecutive paragraphs with a// `margin-top:-10px; padding-top:10px` pair (the `p + p` first-line-indent// trick), and setting only margin-top would leave that padding behind and// add 10px on top of whatever the style asked for.- if (s.sb !== undefined) out.push(`margin-top:${s.sb}px`, 'padding-top:0');- if (s.sa !== undefined) out.push(`margin-bottom:${s.sa}px`);- if (s.ind !== undefined) out.push(`text-indent:${s.ind}px`);+ const sb = cssLen(s.sb, 0, 2000), sa = cssLen(s.sa, 0, 2000), ind = cssLen(s.ind, -2000, 2000);+ if (sb !== null) out.push(`margin-top:${sb}px`, 'padding-top:0');+ if (sa !== null) out.push(`margin-bottom:${sa}px`);+ if (ind !== null) out.push(`text-indent:${ind}px`);return out.join(';');}@@ -200,8 +204,16 @@ export function docStyleCss(doc: TypeDoc, b: Block): string {return s ? styleDeclarations(s) : '';}-/** A style's escaped id, safe inside a double-quoted CSS attribute selector. */-const cssAttrId = (id: string): string => id.replace(/\\/g, '\\\\').replace(/"/g, '\\"');+/**+ * A style's id, safe inside a double-quoted CSS attribute selector: every code+ * point outside [A-Za-z0-9_-] is written as a hex escape. Escaping only `\`+ * and `"` was not enough — a newline, CR or form feed ENDS a CSS string, and+ * what followed the id was parsed as rules (measured: a file's style id+ * carried `*{background:url(…)}` into #t-style-rules and fetched on open). A+ * synced op never passes parseDoc, so this is the layer it meets.+ */+export const cssAttrId = (id: string): string =>+ id.replace(/[^A-Za-z0-9_-]/gu, (c) => `\\${c.codePointAt(0)!.toString(16)} `);/*** Every style the document could paint, as ONE stylesheet — `[data-style-id]`diff --git a/type/src/inline.ts b/type/src/inline.tsindex 72eaa766..67e6f1db 100644--- a/type/src/inline.ts+++ b/type/src/inline.ts@@ -81,6 +81,9 @@ export interface Mark {}/** The tag each mark renders as. `link` is special-cased (it carries an href). */+/** The tag for a mark — an OWN key of TAG only: a synced mark type like+ * `constructor` must not read an inherited property into the markup. */+const tagOf = (m: Mark): string => (Object.hasOwn(TAG, m.t) ? TAG[m.t as keyof typeof TAG] : 'span');const TAG: Record<Exclude<MarkType, 'link'>, string> = {b: 'strong', i: 'em', u: 'u', s: 's', code: 'code',// a styled span; openTag builds the style attribute itself@@ -406,13 +409,13 @@ const openTag = (m: Mark) => {const who = m.by ? ` data-by="${escAttr(m.by)}"` : '';const when = m.at ? ` data-at="${escAttr(m.at)}"` : '';const title = m.by ? ` title="${escAttr(m.t === 'ins' ? `Inserted by ${m.by}` : `Deleted by ${m.by}`)}"` : '';- return `<${TAG[m.t]} class="t-trk"${who}${when}${title}>`;+ return `<${tagOf(m)} class="t-trk"${who}${when}${title}>`;}- if (m.t !== 'link') return `<${TAG[m.t]}>`;+ if (m.t !== 'link') return `<${tagOf(m)}>`;const href = safeHref(m.href ?? '');return href === null ? '<a>' : `<a href="${escAttr(href)}">`;};-const closeTag = (m: Mark) => m.t === 'link' ? '</a>' : `</${TAG[m.t]}>`;+const closeTag = (m: Mark) => m.t === 'link' ? '</a>' : `</${tagOf(m)}>`;/*** Render text + marks as HTML.diff --git a/type/src/layout.ts b/type/src/layout.tsindex 14328338..922c810a 100644--- a/type/src/layout.ts+++ b/type/src/layout.ts@@ -468,14 +468,27 @@ export function pageVars(page: PageSpec): Record<string, string> {* only the margin would leave the padding behind and add 10px to whatever the* author asked for.*/+/**+ * Values a style may carry into CSS — checked HERE, where they are written,+ * not only in parseDoc: a collaborator's synced op never passes parseDoc, and+ * a string like `0;background:url(…)` needs no `<` to inject a declaration+ * (into the editor, print and the preview saved in every file).+ */+export const cssAlign = (v: unknown): string | null =>+ v === 'left' || v === 'center' || v === 'right' || v === 'justify' ? v : null;+export const cssLen = (v: unknown, lo: number, hi: number): number | null =>+ typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi ? v : null;+export function blockStyle(b: Block): string {const p = propsOf(b);const out: string[] = [];- if (p.align) out.push(`text-align:${p.align}`);- if (p.lh !== undefined) out.push(`line-height:${p.lh}`);- if (p.sb !== undefined) out.push(`margin-top:${p.sb}px`, 'padding-top:0');- if (p.sa !== undefined) out.push(`margin-bottom:${p.sa}px`);- if (p.ind !== undefined) out.push(`text-indent:${p.ind}px`);+ const align = cssAlign(p.align), lh = cssLen(p.lh, 0.5, 4);+ const sb = cssLen(p.sb, 0, 2000), sa = cssLen(p.sa, 0, 2000), ind = cssLen(p.ind, -2000, 2000);+ if (align) out.push(`text-align:${align}`);+ if (lh !== null) out.push(`line-height:${lh}`);+ if (sb !== null) out.push(`margin-top:${sb}px`, 'padding-top:0');+ if (sa !== null) out.push(`margin-bottom:${sa}px`);+ if (ind !== null) out.push(`text-indent:${ind}px`);return out.join(';');}diff --git a/type/src/model.ts b/type/src/model.tsindex e5533b86..94f82f71 100644--- a/type/src/model.ts+++ b/type/src/model.ts@@ -569,6 +569,8 @@ function scrubEmbeds(doc: Record<string, unknown>, depth: number): Record<string/** A footnote id a FILE may carry: what uid() mints and nothing that could* leave an attribute. Render escapes ids too — a synced op never passes here. */const NOTE_ID = /^[A-Za-z0-9_.:-]{1,80}$/;+/** A named style's id (`~` joins a duplicate's key, see parseDoc). */+const STYLE_ID = /^[A-Za-z0-9_.:~-]{1,160}$/;export const uid = (p = 'b'): string => {const r = globalThis.crypto?.randomUUID?.();@@ -713,7 +715,7 @@ export function parseDoc(raw: string): ParseResult {// dangling footnote: docstyles.ts falls back to the block's KIND default// when the id does not resolve, so an unknown id is never a rendering// failure — only a "this named style no longer exists" the panel can show.- if (typeof b.styleId === 'string' && b.styleId) out.styleId = b.styleId; else delete out.styleId;+ if (typeof b.styleId === 'string' && STYLE_ID.test(b.styleId)) out.styleId = b.styleId; else delete out.styleId;delete out.level; delete out.cell; delete out.image; delete out.caption; delete out.refs; delete out.cites;delete out.fields;if (typeof b.role === 'string') out.role = b.role;@@ -845,7 +847,11 @@ export function parseDoc(raw: string): ParseResult {if (!isObj(raw0)) continue;const raw = raw0 as Record<string, unknown>;let id = typeof raw.id === 'string' && raw.id ? raw.id : key;+ // ids the app mints are block kinds; anything outside this charset is+ // refused rather than carried into the style sheet (docstyles cssAttrId)+ if (!STYLE_ID.test(id)) continue;if (usedIds.has(id)) id = `${id}~${key}`;+ if (!STYLE_ID.test(id)) continue;usedIds.add(id);const kind: BlockKind = ['para', 'h1', 'h2', 'h3', 'quote', 'ul', 'ol', 'cell', 'image', 'caption', 'toc', 'math', 'embed'].includes(raw.kind as string) ? raw.kind as BlockKind : 'para';diff --git a/type/src/preview.ts b/type/src/preview.tsindex 551951b6..490a46c3 100644--- a/type/src/preview.ts+++ b/type/src/preview.ts@@ -224,7 +224,9 @@ const PAPER = '#ffffff';function flat(v: unknown): string | null {const s = typeof v === 'string' ? v.trim() : '';- return /^#[0-9a-f]{3,8}$/i.test(s) || /^rgb/i.test(s) ? s : null;+ // ANCHORED at both ends: `rgb…` alone let `rgb(0,0,0);}*{…}` end the rule+ // in the stylesheet saved into every file+ return /^#[0-9a-f]{3,8}$/i.test(s) || /^rgba?\(\s*[\d.]+%?(\s*,\s*[\d.]+%?){2,3}\s*\)$/i.test(s) ? s : null;}/** The preview's own scoped stylesheet — a deliberately plain sheet, not an