Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

19.6 KB
Raw Blame
#!/usr/bin/env node
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
// home/webext file-grant rig.
//
//   node scripts/test-webext-filegrant.ts
//
// WHAT THIS PROVES. Saving in place for a document that no granted folder
// covers goes through three more doors — a per-file grant the extension
// holds, the downloads API for the Downloads folder, and the one-time offer —
// and every one of them must (1) write only the sender's own file, (2) use a
// handle only when it is PROVEN to be that file (name and bytes), (3) fail to
// the browser's own picker, never to nothing. A file:// page never holds a
// grant: every local document shares that origin's storage.

import { readFileSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { createContext, runInContext } from 'node:vm'

const root = join(dirname(fileURLToPath(import.meta.url)), '..')
const SRC = join(root, 'home/webext')
const read = (p: string) => readFileSync(join(SRC, p), 'utf8')
const fg = await import('../home/webext/src/filegrant.js')
const bg = await import('../home/webext/src/background.js')

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}`)
}

/** An in-memory store + disk + downloads API, the shape filegrant.js takes as deps. */
function world(disk: Record<string, string>) {
  const store = new Map<string, any>()
  const downloaded: any[] = []
  let nextId = 1
  const items = new Map<number, any>()
  const listeners: any[] = []
  const kv: Record<string, unknown> = {}
  const deps: any = {
    all: async () => [...store.entries()],
    get: async (k: string) => store.get(k) ?? null,
    put: async (k: string, v: any) => { store.set(k, v) },
    del: async (k: string) => { store.delete(k) },
    fetch: async (url: string) => {
      const path = decodeURIComponent(url.replace(/^file:\/\//, ''))
      const body = disk[path]
      if (body === undefined) return { ok: false }
      const bytes = new TextEncoder().encode(body)
      return { ok: true, arrayBuffer: async () => bytes.buffer, text: async () => body }
    },
    storage: { get: async (k: string) => ({ [k]: kv[k] }), set: async (o: any) => { Object.assign(kv, o) } },
    downloads: {
      search: async (q: any) => (q.id != null ? [items.get(q.id)].filter(Boolean) : [...items.values()].slice(-1)),
      download: async (o: any) => { const id = nextId++; downloaded.push(o); items.set(id, { id, filename: `/Users/you/Downloads/${o.filename}`, state: 'complete' }); return id },
      erase: async () => {}, removeFile: async () => {},
      onChanged: { addListener: (f: any) => listeners.push(f), removeListener: () => {} },
    },
    setUiOptions: async () => {},
  }
  return { deps, store, downloaded, kv }
}
/** A handle over given bytes. */
const handleOf = (name: string, body: string, perm = 'granted') => ({
  name, kind: 'file', perm,
  queryPermission: async () => perm,
  requestPermission: async () => perm,
  getFile: async () => { const b = new TextEncoder().encode(body); return { size: b.length, arrayBuffer: async () => b.buffer } },
  createWritable: async () => ({ write: async () => {}, close: async () => {} }),
})

console.log('\n— the file grant: proven, never assumed')
{
  const w = world({ '/Users/you/Downloads/Q3.bento.html': 'DECK-Q3', '/Users/you/Desktop/Q3.bento.html': 'OTHER' })
  const h = handleOf('Q3.bento.html', 'DECK-Q3')
  await fg.addFileGrant(h, null, w.deps)
  const r = await fg.resolveFileGrant('/Users/you/Downloads/Q3.bento.html', w.deps)
  ok(r.ok && r.handle === h, 'a name-keyed grant serves the path whose bytes it holds')
  ok([...w.store.values()].some((v) => v.path === '/Users/you/Downloads/Q3.bento.html'), 'and the path is learned onto the record')
  const other = await fg.resolveFileGrant('/Users/you/Desktop/Q3.bento.html', w.deps)
  ok(!other.ok && other.reason === 'none', 'the same name with other bytes is NOT served — a grant is for one file')
  ok(!(await fg.resolveFileGrant('/Users/you/Downloads/Nope.bento.html', w.deps)).ok, 'no grant of that name → none')
  // TWINS: a byte-identical copy elsewhere must never be served by the other's grant
  const tw = world({ '/Users/you/Downloads/T.bento.html': 'SAME', '/Users/you/Documents/T.bento.html': 'SAME' })
  await fg.addFileGrant(handleOf('T.bento.html', 'SAME'), '/Users/you/Downloads/T.bento.html', tw.deps)
  ok((await fg.resolveFileGrant('/Users/you/Downloads/T.bento.html', tw.deps)).ok, 'a grant bound to a path serves that path')
  ok(!(await fg.resolveFileGrant('/Users/you/Documents/T.bento.html', tw.deps)).ok, 'and NOT a byte-identical twin at another path')
  const un = world({ '/Users/you/Downloads/U.bento.html': 'SAME', '/Users/you/Documents/U.bento.html': 'SAME' })
  un.deps.otherCopies = async (p: string) => ['/Users/you/Downloads/U.bento.html', '/Users/you/Documents/U.bento.html'].filter((x) => x !== p)
  await fg.addFileGrant(handleOf('U.bento.html', 'SAME'), null, un.deps)
  ok(!(await fg.resolveFileGrant('/Users/you/Downloads/U.bento.html', un.deps)).ok, 'an unbound grant is refused while a same-bytes twin exists (never guessed)')
  un.deps.otherCopies = async () => []
  ok((await fg.resolveFileGrant('/Users/you/Downloads/U.bento.html', un.deps)).ok && [...un.store.values()].some((v) => v.path === '/Users/you/Downloads/U.bento.html'), 'with no twin it serves the path and is bound to it from then on')
  const lapsed = world({ '/Users/you/Downloads/L.bento.html': 'L' })
  await fg.addFileGrant(handleOf('L.bento.html', 'L', 'prompt'), '/Users/you/Downloads/L.bento.html', lapsed.deps)
  const lr = await fg.resolveFileGrant('/Users/you/Downloads/L.bento.html', lapsed.deps)
  ok(!lr.ok && lr.reason === 'lapsed', 'a grant without permission is lapsed, and never prompted for from the worker')
  ok(!(await fg.declined('/x', w.deps)), 'not declined by default')
  await fg.decline('/x', w.deps)
  ok(await fg.declined('/x', w.deps), 'a decline is remembered')
  w.store.set(fg.declineKey('/x'), { at: Date.now() - fg.DECLINE_MS - 1 })
  ok(!(await fg.declined('/x', w.deps)), 'and expires after DECLINE_MS')
}

console.log('\n— downloads: the folder Chrome lets an extension write')
{
  const w = world({})
  const dir = await fg.downloadsDir(w.deps)
  ok(dir === '/Users/you/Downloads', `downloadsDir: learned from the API (${dir}) and`)
  ok(w.kv.downloadsDir === dir, 'remembered in extension storage')
  ok(fg.downloadsRelative('/Users/you/Downloads/Q3.bento.html', dir) === 'Q3.bento.html', 'downloadsRelative: a file in Downloads → its relative name')
  ok(fg.downloadsRelative('/Users/you/Downloads/decks/Q3.bento.html', dir) === 'decks/Q3.bento.html', 'downloadsRelative: nested is fine')
  ok(fg.downloadsRelative('/Users/you/Documents/Q3.bento.html', dir) === null && fg.downloadsRelative('/Users/you/Downloads/../x.html', dir) === null, 'downloadsRelative: outside, or climbing out → null')
  const n = await fg.writeViaDownloads('Q3.bento.html', '<html>hi</html>', w.deps)
  ok(n === 15 && w.downloaded.at(-1).conflictAction === 'overwrite' && w.downloaded.at(-1).saveAs === false && w.downloaded.at(-1).url.startsWith('data:text/html;base64,'), 'writeViaDownloads: overwrite in place, no dialog, the bytes as a data URL')
  const win = world({}); win.deps.downloads.search = async () => [{ filename: 'C:\\Users\\you\\Downloads\\x.txt' }]
  ok(await fg.downloadsDir(win.deps) === '/C:/Users/you/Downloads', 'downloadsDir: a Windows path becomes the file:// shape')
}

console.log('\n— the worker: folder, then file, then Downloads; own file only')
const FILE = (p: string) => ({ url: `file://${p}`, frameId: 0 })
{
  const w = world({ '/Users/you/Downloads/Q3.bento.html': 'DECK-Q3' })
  const h = handleOf('Q3.bento.html', 'DECK-Q3')
  await fg.addFileGrant(h, '/Users/you/Downloads/Q3.bento.html', w.deps)
  const deps = { readGrants: async () => [], filegrant: w.deps }
  const c = await bg.claim(FILE('/Users/you/Downloads/Q3.bento.html'), deps)
  ok(c.ok && c.via === 'file' && c.name === 'Q3.bento.html', 'claim: no folder grant → the file grant serves it (via file)')
  const wr = await bg.write(FILE('/Users/you/Downloads/Q3.bento.html'), 'NEW', deps)
  const decks = () => w.downloaded.filter((d) => d.filename.endsWith('.bento.html')).length
  ok(wr.ok && wr.via === 'file' && decks() === 0, 'write: through the file handle, not the downloads API')
  const dl = await bg.claim(FILE('/Users/you/Downloads/Other.bento.html'), deps)
  ok(dl.ok && dl.via === 'downloads', 'claim: a Downloads file with no grant → the downloads API (via downloads)')
  const dw = await bg.write(FILE('/Users/you/Downloads/Other.bento.html'), 'BYTES', deps)
  ok(dw.ok && dw.via === 'downloads' && w.downloaded.at(-1).filename === 'Other.bento.html', 'write: Downloads → downloads.download overwrite of that relative name')
  const doc = await bg.claim(FILE('/Users/you/Documents/Q3.bento.html'), deps)
  ok(!doc.ok, 'claim: a Documents file with no grant → not ok (the page falls to its picker, or the offer)')
  // the page names nothing: a payload path is never read
  const spoof = await bg.write({ url: 'file:///Users/you/Documents/x.bento.html', frameId: 0 } as any, 'X', { ...deps })
  ok(!spoof.ok && decks() === 1, 'write: only the sender\'s own url is ever resolved')
  const https = await bg.claim({ url: 'https://bento.page/slides/', frameId: 0 } as any, deps)
  ok(!https.ok, 'claim: not a local file → nothing')
  // a folder grant wins over a file grant for the same document
  const folderDeps = { ...deps, readGrants: async () => [{ name: 'Downloads-decks', queryPermission: async () => 'granted', resolve: async () => ['Q3.bento.html'] }], locateIn: async () => [{ file: { name: 'Q3.bento.html', createWritable: h.createWritable, isSameEntry: async () => true }, rel: ['Q3.bento.html'] }], findByName: async () => [] }
  const fc = await bg.claim(FILE('/Users/you/Downloads/Q3.bento.html'), folderDeps)
  ok(fc.ok && fc.via === 'folder', 'a folder grant that covers the file takes precedence')
  // a file grant whose file is gone is forgotten on use
  const gone = world({ '/Users/you/Downloads/G.bento.html': 'G' })
  const gh: any = handleOf('G.bento.html', 'G')
  gh.createWritable = async () => { const e: any = new Error('gone'); e.name = 'NotFoundError'; throw e }
  await fg.addFileGrant(gh, '/Users/you/Downloads/G.bento.html', gone.deps)
  const gw = await bg.write(FILE('/Users/you/Downloads/G.bento.html'), 'X', { readGrants: async () => [], filegrant: gone.deps, downloadsDir: async () => null })
  ok(!gw.ok && [...gone.store.values()].every((v) => !v.handle), 'write: NotFoundError on a file grant drops it')
}

console.log('\n— the page side: waiting on the offer')
{
  const SRC_BRIDGE = read('src/page-bridge.js')
  const posted: any[] = []
  const answers: Record<string, any> = {}
  const win: any = {
    location: { pathname: '/Users/you/Downloads/Q3.bento.html' },
    addEventListener() {},
    postMessage(msg: any) {
      posted.push(msg)
      // answer as the relay would, from a script of replies by op+payload
      const key = msg.payload?.token ? 'claim:token' : msg.op
      const res = answers[key]
      if (res) setTimeout(() => win._deliver({ __bento_tray__: true, dir: 'res', id: msg.id, result: res }), 0)
    },
    showSaveFilePicker: async () => ({ __native: true }),
    bento: { updates: { version: '1.2.1' } },
  }
  const listeners: any[] = []
  win.addEventListener = (_: string, f: any) => listeners.push(f)
  win._deliver = (data: any) => listeners.forEach((f) => f({ data, source: win }))
  const ctx: any = createContext({ window: win, setTimeout, clearTimeout, Date, Math, JSON, Promise, Blob, console, DOMException: class extends Error { constructor(m: string, n: string) { super(m); this.name = n } }, FileSystemHandle: class {}, crypto: { randomUUID: () => 'x' } })
  ctx.globalThis = ctx
  runInContext(SRC_BRIDGE, ctx)
  answers.claim = { ok: false, reason: 'setup', token: 'tok-1' }
  answers['claim:token'] = { ok: true, name: 'Q3.bento.html', via: 'file' }
  const h = await win.showSaveFilePicker({ id: 'bento-doc', suggestedName: 'Q3.bento.html' })
  ok(posted.filter((m) => m.op === 'claim').length === 2 && posted[1].payload?.token === 'tok-1', 'setup → the bridge asks again with the token and waits')
  ok(h.name === 'Q3.bento.html' && !h.__native, 'and the save goes through the extension once the window answered')
  answers['claim:token'] = { ok: false, reason: 'declined' }
  const h2 = await win.showSaveFilePicker({ id: 'bento-doc', suggestedName: 'Q3.bento.html' })
  ok(h2.__native === true, 'declined → the browser\'s own picker, as without the extension')
  ok(/120000/.test(SRC_BRIDGE), 'the second claim waits as long as a dialog takes')
}
{
  const manifest = JSON.parse(read('manifest.json'))
  ok(manifest.permissions.includes('downloads') && manifest.permissions.includes('downloads.ui'), 'manifest: downloads (the write) and downloads.ui (the bubble, quiet for the write)')
  const bgSrc = read('src/background.js')
  ok(/claimOrOffer/.test(bgSrc) && /filegrant\.html/.test(bgSrc) && /isFileAccessOn/.test(bgSrc), 'the worker offers the window only with file-URL access on')
  ok(/declined\(path\)/.test(bgSrc), 'a declined file is not asked again')
  const winSrc = read('src/filegrant-window.js')
  const flowSrc = read('src/grantflow.js')
  ok(/grantFileFor\(path\)/.test(winSrc) && /showOpenFilePicker/.test(flowSrc) && /grantPickedFile\)\(handle, path\)/.test(flowSrc), 'the window picks in the extension\'s context and a file grant is stored only through the proof (grantPickedFile: bytes and mtime)')
  const fgSrc = read('src/filegrant.js')
  ok(/export async function grantPickedFile/.test(fgSrc) && /handleIsPath\(handle, path, deps\)/.test(fgSrc) && /sameMtime\(handle, path, deps\)/.test(fgSrc), 'grantPickedFile proves bytes AND mtime before storing')
  const panel = read('src/panel.js')
  ok(/save\.status/.test(panel) && /grantFileFor\(tdPath\)/.test(panel) && /grantFolderFor\(tdPath\)/.test(panel), 'the side panel shows the active document\'s state and grants it through the same flow')
  const home = read('src/home.js')
  ok(/getAsFileSystemHandle/.test(home) && /addFileGrant\(handle, path\)/.test(home), 'the library takes drops as grants — a folder or a file — with no dialog')
  ok(/listFileGrants\(\)/.test(home) && /dropFileGrant\(g\.key\)/.test(home), 'Settings lists file grants with Remove')
}

console.log('\n— a Chrome that asks where to save every download')
{
  // the downloads API "completes" with USER_CANCELED when Chrome prompted and the person cancelled
  const w = world({ '/Users/you/Downloads/P.bento.html': 'P' })
  w.deps.downloads.download = async (o: any) => { const id = 99; w.downloaded.push(o); return id }
  w.deps.downloads.search = async (q: any) => (q.id === 99 ? [{ id: 99, state: 'interrupted', error: 'USER_CANCELED', filename: '/Users/you/Downloads/P.bento.html' }] : [{ filename: '/Users/you/Downloads/x.txt' }])
  const deps = { readGrants: async () => [], filegrant: w.deps }
  const first = await bg.write(FILE('/Users/you/Downloads/P.bento.html'), 'X', deps)
  ok(!first.ok && first.retry === 'native' && /asks where to save/.test(first.reason), 'a prompted download: the page is told to finish this save with the browser\'s own picker')
  ok(w.kv.downloadsUnusable === true, 'and the Downloads door is switched off for this Chrome')
  const next = await bg.claim(FILE('/Users/you/Downloads/P.bento.html'), deps)
  ok(!next.ok && next.via !== 'downloads', 'the next claim no longer takes the Downloads door (the offer follows in the worker)')
  await fg.setDownloadsUnusable(false, w.deps)
  ok((await bg.claim(FILE('/Users/you/Downloads/P.bento.html'), deps)).via === 'downloads', 'Settings "Try again" reopens it')
  ok(/retry === 'native'/.test(read('src/page-bridge.js')) && /native\(forNative\(\{ suggestedName: name \}\)\)/.test(read('src/page-bridge.js')), 'page-bridge finishes such a save through the native picker instead of throwing the bytes away')
}

console.log('\n— the grant flow: the folder when Chrome allows it, the picker near the document')
{
  const gf = await import('../home/webext/src/grantflow.js')
  ok(gf.inBlockedFolder('/Users/you/Documents/Q3.bento.html') && gf.inBlockedFolder('/Users/you/Downloads/Q3.bento.html') && gf.inBlockedFolder('/Users/you/Desktop/Q3.bento.html') && gf.inBlockedFolder('/Users/you/Q3.bento.html') && gf.inBlockedFolder('/C:/Users/you/OneDrive/Documents/Q3.bento.html') && gf.inBlockedFolder('/home/you/Q3.bento.html'),
    'inBlockedFolder: directly in home / Documents / Desktop / Downloads (and OneDrive) → a file grant')
  ok(!gf.inBlockedFolder('/Users/you/Documents/Decks/Q3.bento.html') && !gf.inBlockedFolder('/Users/you/Desktop/teams-test/B1.bento.html') && !gf.inBlockedFolder('/Volumes/Work/Q3.bento.html'),
    'inBlockedFolder: any subfolder → the FOLDER is offered, so its siblings save too')
  // nearest start: the held handle sharing the longest path
  const decks = { name: 'Decks', tag: 'decks' }, other = { name: 'Other', tag: 'other' }
  const fileH = { name: 'x.bento.html', tag: 'file' }
  const deps: any = {
    prefixes: async () => ({ Decks: '/Users/you/Documents/Decks', Other: '/Users/you/Pictures/Other' }),
    getGrants: async () => [decks, other],
    listFileGrants: async () => [{ handle: fileH, path: '/Users/you/Desktop/teams-test/x.bento.html' }],
  }
  ok((await gf.startInFor('/Users/you/Documents/Decks/2026/Q3.bento.html', deps)) === decks, 'startInFor: a folder grant above the document')
  ok((await gf.startInFor('/Users/you/Desktop/teams-test/B2.bento.html', deps)) === fileH, 'startInFor: a file grant beside it (its picker opens in that folder)')
  ok((await gf.startInFor('/Users/you/Downloads/new.bento.html', { prefixes: async () => ({}), getGrants: async () => [], listFileGrants: async () => [] })) === 'downloads', 'startInFor: nothing near → the well-known folder the path is under')
  ok((await gf.startInFor('/Users/you/Music/x.bento.html', deps)) === 'documents', 'startInFor: sharing only the home is not "near"')
  // folder grant: accepted only if it contains the document
  let stored: any[] = []
  const learned: any[] = []
  const base = { ...deps, getGrants: async () => stored, putGrants: async (l: any[]) => { stored = l }, learnPrefix: async (n: string, p: string) => { learned.push([n, p]) } }
  const teams = { name: 'teams-test', requestPermission: async () => 'granted', isSameEntry: async () => false }
  const okR = await gf.grantFolderFor('/Users/you/Desktop/teams-test/B2.bento.html', { ...base, showDirectoryPicker: async (o: any) => { base.seen = o; return teams }, prefixFor: async () => '/Users/you/Desktop/teams-test' })
  ok(okR.ok && stored.includes(teams) && learned[0][1] === '/Users/you/Desktop/teams-test' && base.seen.id === gf.PICKER_ID && base.seen.mode === 'readwrite', 'grantFolderFor: the folder is stored, placed, and the picker remembers its folder (id)')
  const wrong = await gf.grantFolderFor('/Users/you/Desktop/teams-test/B2.bento.html', { ...base, showDirectoryPicker: async () => ({ name: 'Elsewhere', requestPermission: async () => 'granted' }), prefixFor: async () => null })
  ok(!wrong.ok && wrong.reason === 'not-containing' && wrong.name === 'Elsewhere', 'grantFolderFor: a folder that does not contain the document is refused, by name')
  const home = read('src/filegrant-window.js'), panel = read('src/panel.js')
  ok(/inBlockedFolder\(path\)/.test(home) && /grantFolderFor\(path\)/.test(home) && /grantFileFor\(path\)/.test(home), 'the offer window offers the folder first, "Only this file" as the alternative')
  ok(/grantFolderFor\(tdPath\)/.test(panel) && /inBlockedFolder\(tdPath\)/.test(panel), 'the side panel does the same')
}

console.log(`\n${checks - failures}/${checks} checks passed`)
process.exit(failures ? 1 : 0)