Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

dash: CSV export escapes text that would run as a formula (#818)

nyblnet2db1c592779a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ee455ad1..ec136590 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1538,6 +1538,11 @@ jobs:
# dead end wearing a live button.
run: node scripts/test-dash-recovery.ts
+ - name: dash CSV export rig
+ # Text starting = + - @ tab or CR is exported with a leading quote, so
+ # opening the CSV in a spreadsheet never runs it as a formula.
+ run: node scripts/test-dash-csv-export.ts
+
- name: dash i18n rig
# A core catalog ships inside every saved workbook and cannot be patched
# without a release, so drift has to fail here rather than in the field:
diff --git a/dash/CHANGELOG.md b/dash/CHANGELOG.md
index 81fe52c0..6b36ac35 100644
--- a/dash/CHANGELOG.md
+++ b/dash/CHANGELOG.md
@@ -12,6 +12,7 @@ There is no server, so a break here would be permanent.
The release that came out of watching somebody use 0.2.0.
+- **CSV export no longer lets a cell run as a formula.** Text starting with `=`, `+`, `-`, `@`, a tab or a return is written with a leading `'`, so opening the CSV in Excel or Sheets shows it as text.
- **Neutral title while sealed, matching the saved file's title.**
- **A sealed workbook deletes this browser's earlier plaintext recovery copy and version history of itself** on open; other workbooks' copies are untouched.
diff --git a/dash/src/csvout.ts b/dash/src/csvout.ts
new file mode 100644
index 00000000..0da80244
--- /dev/null
+++ b/dash/src/csvout.ts
@@ -0,0 +1,23 @@
+// One CSV field, as dash writes it.
+//
+// TWO jobs, and the second is the one that matters:
+//
+// 1. RFC 4180 quoting — a comma, quote, CR or LF puts the field in quotes and
+// doubles its quotes.
+// 2. FORMULA INJECTION. A spreadsheet that opens a CSV evaluates any field
+// beginning with `=`, `+`, `-`, `@`, a tab or a CR as a formula — so a
+// text cell holding `=HYPERLINK("http://x","click")` (typed, pasted, or
+// submitted through a form by a stranger) becomes a live link, or worse,
+// the moment someone opens the export in Excel. TEXT that starts that way
+// gets a leading `'`, the convention Excel and Sheets both read as "this
+// is text". A NUMBER is never touched: `-5` stored as a number is data,
+// and prefixing it would turn every negative into a string.
+
+const TRIGGER = /^[=+\-@\t\r]/
+
+export function csvField(v: unknown): string {
+ if (v === null || v === undefined) return ''
+ let s = typeof v === 'string' ? v : String(v)
+ if (typeof v === 'string' && TRIGGER.test(s)) s = `'${s}`
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
+}
diff --git a/dash/src/main.ts b/dash/src/main.ts
index 15f5cb2f..49b9c052 100644
--- a/dash/src/main.ts
+++ b/dash/src/main.ts
@@ -20,6 +20,7 @@
// apart HERE, where the DOM is still visible, or an oversized workbook opens
// as the starter and saves over itself.
+import { csvField } from './csvout.ts'
import './styles.css'
import { configureApp, appConfig } from '../../kernel/src/app.ts'
import {
@@ -2273,14 +2274,15 @@ function retype(store: Store, col: Column, x: number, y: number): void {
* calls this defect out by name.
*/
function exportCsv(store: Store, sheet: TableSheet): void {
- const q = (s: string) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s)
+ // csvout.ts: RFC 4180 quoting AND the formula-injection escape - a text cell
+ // starting = + - @ tab or CR must not run as a formula in whoever opens this.
const n = sheet.rids.reduce((a, [, c]) => a + c, 0)
- const lines = [sheet.columns.map((c) => q(c.name)).join(',')]
+ const lines = [sheet.columns.map((c) => csvField(c.name)).join(',')]
for (let i = 0; i < n; i++) {
lines.push(sheet.columns.map((c) => {
const d = sheet.data[c.id]
const v = d?.enc === 'raw' ? d.v[i] : d?.enc === 'dict' ? (d.idx[i] == null ? null : d.dict[d.idx[i]!]) : null
- return q(v == null ? '' : String(v))
+ return csvField(v)
}).join(','))
}
const blob = new Blob([lines.join('\r\n')], { type: 'text/csv' })
diff --git a/scripts/test-dash-csv-export.ts b/scripts/test-dash-csv-export.ts
new file mode 100644
index 00000000..ced327c6
--- /dev/null
+++ b/scripts/test-dash-csv-export.ts
@@ -0,0 +1,51 @@
+#!/usr/bin/env node
+// CSV export: quoting, and formula injection.
+//
+// node scripts/test-dash-csv-export.ts
+//
+// A spreadsheet opening a CSV evaluates any field starting = + - @ tab or CR.
+// Dash's text cells can hold such text from a paste, a typo, or a stranger's
+// form submission, so TEXT that starts that way is exported with a leading
+// `'` (read as "text" by Excel and Sheets). Numbers are never touched.
+
+import { csvField } from '../dash/src/csvout.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+console.log('\nformula-leading text is escaped')
+for (const [v, want] of [
+ ['=HYPERLINK("http://x","click")', `"'=HYPERLINK(""http://x"",""click"")"`],
+ ['=IMPORTXML("http://x","//a")', `"'=IMPORTXML(""http://x"",""//a"")"`],
+ ['+1+1', "'+1+1"],
+ ['-2+3', "'-2+3"],
+ ['@SUM(A1)', "'@SUM(A1)"],
+ ['\t=1', "'\t=1"],
+ ['\r=1', `"'\r=1"`],
+] as const) {
+ ok(csvField(v) === want, `${JSON.stringify(v)} → ${JSON.stringify(csvField(v))}`)
+}
+
+console.log('\nCONTROLS: ordinary values are untouched')
+for (const [v, want] of [
+ [-5, '-5'],
+ [3.25, '3.25'],
+ [true, 'true'],
+ ['plain', 'plain'],
+ ['a=b', 'a=b'],
+ ['', ''],
+ [null, ''],
+ ['has, comma', '"has, comma"'],
+ ['say "hi"', '"say ""hi"""'],
+ ['two\nlines', '"two\nlines"'],
+] as const) {
+ ok(csvField(v) === want, `${JSON.stringify(v)} → ${JSON.stringify(csvField(v))}`)
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)