#!/usr/bin/env node // Notable's sidecar, run by the desktop app (mollusc, see mollusc.json at the // root of the repository) beside the page: the reMarkable cloud, reached // through the notable library, behind a small HTTP API for the page. Anything // in the user's browser can reach 127.0.0.1, so every request but /health // needs the token mollusc shares with the page at launch. // // GET /health // POST /status → { loggedIn, user, hosts, configPath, settings, error? } // POST /login { code, deviceDesc? } → the same, once paired // POST /logout → the same // POST /settings { patch? } → settings (authorUuid, syncDir, syncFormats, …) // POST /tree { force? } → { hash, generation, docs: [{ id, name, parent, …, fileType, pageCount, cover }] } // POST /doc { id } → { doc, fileType, content, pages, authors, author } // GET /doc/:id/page/:pageId → the page's .rm bytes (204 when the page has none) // PUT /doc/:id/page/:pageId → { doc }: the page's .rm replaced by the body // GET /doc/:id/thumbnail/:pageId → the page's PNG thumbnail (204 when there is none) // PUT /doc/:id/thumbnail/:pageId → { doc }: the thumbnail replaced by the body // GET /doc/:id/file/:kind → the document's pdf or epub // PUT /doc/:id/pdf → { doc }: the PDF replaced by the body // POST /doc/add-page { id, after?, template? } → { doc, pageId } // POST /doc/remove-page { id, pageId } → { doc } // POST /doc/template { id, pageId, template } → { doc } // POST /notebook { name, parent?, template? } → { doc } // POST /folder { name, parent? } → { doc } // POST /rename { id, name } → { doc } // POST /move { ids, parent } → { docs } parent: '' (root), 'trash', or a folder's id // POST /trash { ids } → { docs } // POST /restore { ids, parent? } → { docs } // POST /purge { ids } → { docs } // POST /upload { paths, parent? } → { docs } local files: pdf, epub, rm, md, txt // POST /export { id, format, path } → { files } markdown | svg | pdf, written at path // POST /download { id, dir } → { files } the document's raw files, under dir // POST /sync { dir, formats, raw, trash, prune, dryRun } → lines of JSON: { event } as it goes, then { summary } or { error } // // Writes go through the library's root-index transactions, which retry when // the tablet published in between; they are run one at a time here as well. import { createServer } from 'node:http'; import { timingSafeEqual } from 'node:crypto'; import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { RemarkableCloud, cloud as rm, randomUuid } from '../../lib/index.js'; const port = Number(process.env.NOTABLE_APP_PORT || process.env.MOLLUSC_PORT); const token = process.env.NOTABLE_APP_TOKEN || process.env.MOLLUSC_TOKEN; if (!port || !token) { console.error('notable sidecar: NOTABLE_APP_PORT and NOTABLE_APP_TOKEN are required'); process.exit(1); } // The page's origins: the app's own (desktop and Android spell it differently), and Vite's in dev. const APP_ORIGINS = new Set(['app://com.berjon.notable', process.env.MOLLUSC_APP_ORIGIN].filter(Boolean)); const DEV_ORIGIN = /^http:\/\/(127\.0\.0\.1|localhost):\d+$/; const allowedOrigin = (origin) => APP_ORIGINS.has(origin) || DEV_ORIGIN.test(origin); const configPath = process.env.NOTABLE_CONFIG || rm.defaultConfigPath(); const settingsPath = join(dirname(configPath), 'app.json'); const log = (m) => console.error(`[notable] ${m}`); const cloud = RemarkableCloud.open({ configPath, cacheDir: process.env.NOTABLE_CACHE || rm.defaultCacheDir(), log }); // ---- the app's own settings (next to the cloud credentials) ------------- const SETTINGS_KEYS = ['authorUuid', 'syncDir', 'syncFormats', 'syncRaw', 'syncTrash', 'syncPrune', 'view', 'pen']; function loadSettings () { try { return JSON.parse(readFileSync(settingsPath, 'utf8')); } catch { return {}; } } function saveSettings (s) { mkdirSync(dirname(settingsPath), { recursive: true, mode: 0o700 }); writeFileSync(settingsPath, JSON.stringify(s, null, 2) + '\n', { mode: 0o600 }); } let settings = loadSettings(); // Strokes this app writes carry its own author UUID, made once per install. if (!settings.authorUuid) { settings.authorUuid = randomUuid(); saveSettings(settings); } function patchSettings (patch = {}) { for (const [k, v] of Object.entries(patch)) { if (!SETTINGS_KEYS.includes(k) || k === 'authorUuid') continue; if (v === null) delete settings[k]; else settings[k] = v; } saveSettings(settings); return settings; } // ---- one write at a time -------------------------------------------------- let chain = Promise.resolve(); function serial (fn) { const p = chain.then(fn, fn); chain = p.catch(() => {}); return p; } // ---- views of the library's objects --------------------------------------- function docJson (tree, d) { return { id: d.id, name: d.name, parent: d.parent, type: d.type, isFolder: d.isFolder, pinned: d.pinned, deleted: d.isDeleted, trashed: tree.isTrashed(d), lastModified: d.lastModified ? d.lastModified.getTime() : null, hash: d.hash, size: d.size, path: tree.path(d), }; } function fileTypeOf (d, content) { if (content?.fileType) return content.fileType; if (d.files.some(f => f.name === `${d.id}.pdf`)) return 'pdf'; if (d.files.some(f => f.name === `${d.id}.epub`)) return 'epub'; return 'notebook'; } const byIdx = (a, b) => ((a.idx?.value ?? '') < (b.idx?.value ?? '') ? -1 : (a.idx?.value ?? '') > (b.idx?.value ?? '') ? 1 : 0); // The pages of a document in reading order, with what the page needs to know about each. function pageEntries (d, content) { const cpages = content?.cPages?.pages; const entries = Array.isArray(cpages) ? cpages.filter(p => p && p.id && !(p.deleted && p.deleted.value)).sort(byIdx) : (Array.isArray(content?.pages) ? content.pages.filter(Boolean).map(id => ({ id })) : []); return entries.map(p => ({ id: p.id, template: p.template?.value ?? null, redir: typeof p.redir?.value === 'number' ? p.redir.value : null, modified: p.modifed ? Number(p.modifed) : null, hasRm: d.files.some(f => f.name === `${d.id}/${p.id}.rm`), hasThumbnail: d.files.some(f => f.name === `${d.id}.thumbnails/${p.id}.png`), })); } async function status () { const out = { loggedIn: cloud.api.loggedIn, user: null, hosts: cloud.api.hosts, configPath, settings }; if (out.loggedIn) { try { out.user = rm.describeToken(await cloud.api.token()); } catch (err) { out.error = err.message; if (err instanceof rm.AuthError && /invalid|revoked|401|403/i.test(err.message)) out.loggedIn = false; } } return out; } async function treeJson (force = false) { const tree = await cloud.refresh({ force }); const docs = await rm.pmap([...tree.docs.values()], 8, async (d) => { const j = docJson(tree, d); if (!d.isFolder) { const content = await cloud.content(d).catch(() => ({})); j.fileType = fileTypeOf(d, content); const pages = pageEntries(d, content); j.pageCount = pages.length; j.cover = pages.find(p => p.hasThumbnail)?.id ?? null; } return j; }); return { hash: tree.hash, generation: tree.generation, docs }; } async function docInfo (id) { const d = await cloud.docOf(id); const content = await cloud.content(d); const authors = [...rm.contentAuthors(content)].map(([index, uuid]) => ({ index, uuid })); const mine = authors.find(a => a.uuid === settings.authorUuid); return { doc: docJson(cloud.tree, d), fileType: fileTypeOf(d, content), content, pages: pageEntries(d, content), authors, author: { uuid: settings.authorUuid, index: mine ? mine.index : Math.max(0, ...authors.map(a => a.index)) + 1 }, files: d.files.map(f => f.name), }; } async function blobOf (id, name) { const d = await cloud.docOf(id); const f = d.files.find(x => x.name === name); return f ? cloud.api.getBlob(f.hash, f.name) : null; } const folderSpec = (parent) => (parent === 'trash' ? rm.TRASH_FOLDER : (parent || rm.ROOT)); const ids = (body) => (Array.isArray(body.ids) ? body.ids : [body.id]).filter(Boolean); const withDoc = async (d) => ({ doc: docJson(cloud.tree, d) }); const withDocs = async (ds) => ({ docs: ds.map(d => docJson(cloud.tree, d)) }); async function exportDoc ({ id, format, path }) { if (!path) throw new rm.CloudError('a path to write to is required'); const d = await cloud.docOf(id); const r = await cloud.export(d, format); const empty = !r.pages || (Array.isArray(r.data) ? !r.data.length : !r.data); if (empty) throw new rm.CloudError('nothing to export: the document has no handwritten or typed pages'); mkdirSync(dirname(path), { recursive: true }); const files = []; if (Array.isArray(r.data) && r.data.length > 1) { const base = path.replace(/\.svg$/i, ''); r.data.forEach((svg, i) => { const p = `${base}-p${String(i + 1).padStart(2, '0')}.svg`; writeFileSync(p, svg); files.push(p); }); } else { writeFileSync(path, Array.isArray(r.data) ? r.data[0] : r.data); files.push(path); } return { files }; } async function download ({ id, dir }) { if (!dir) throw new rm.CloudError('a directory to write to is required'); const d = await cloud.docOf(id); const files = await cloud.download(d, join(dir, rm.safeFileName(d.name))); return { files }; } // ---- routes ---------------------------------------------------------------- const JSON_ROUTES = { '/status': () => status(), '/login': async (b) => { if (!b.code) throw new rm.CloudError('the one-time code is required'); await cloud.api.login(String(b.code).trim(), b.deviceDesc ? { deviceDesc: b.deviceDesc } : {}); return status(); }, '/logout': async () => { cloud.api.logout(); return status(); }, '/settings': (b) => (b.patch ? patchSettings(b.patch) : settings), '/tree': (b) => treeJson(Boolean(b.force)), '/doc': (b) => docInfo(b.id), '/doc/add-page': (b) => serial(async () => { const { doc, pageId } = await cloud.addPage(b.id, { after: b.after ?? null, template: b.template ?? null, authorUuid: settings.authorUuid }); return { ...(await withDoc(doc)), pageId }; }), '/doc/remove-page': (b) => serial(async () => withDoc(await cloud.removePage(b.id, b.pageId))), '/doc/template': (b) => serial(async () => withDoc(await cloud.setPageTemplate(b.id, b.pageId, b.template))), '/notebook': (b) => serial(async () => withDoc(await cloud.createNotebook({ name: b.name, parent: folderSpec(b.parent), template: b.template || 'Blank', authorUuid: settings.authorUuid }))), '/folder': (b) => serial(async () => withDoc(await cloud.createFolder(b.name, folderSpec(b.parent)))), '/rename': (b) => serial(async () => withDoc(await cloud.rename(b.id, b.name))), '/move': (b) => serial(async () => { const out = []; for (const id of ids(b)) out.push(await cloud.move(id, folderSpec(b.parent))); return withDocs(out); }), '/trash': (b) => serial(async () => { const out = []; for (const id of ids(b)) out.push(await cloud.trash(id)); return withDocs(out); }), '/restore': (b) => serial(async () => { const out = []; for (const id of ids(b)) out.push(await cloud.restore(id, folderSpec(b.parent))); return withDocs(out); }), '/purge': (b) => serial(async () => { const out = []; for (const id of ids(b)) out.push(...await cloud.purge(id)); return withDocs(out); }), '/upload': (b) => serial(async () => { const out = []; for (const p of b.paths ?? []) out.push(await cloud.upload(p, { parent: folderSpec(b.parent) })); return withDocs(out); }), '/export': (b) => exportDoc(b), '/download': (b) => download(b), }; const BINARY_ROUTES = [ ['GET', /^\/doc\/([^/]+)\/page\/([^/]+)$/, (id, pageId) => blobOf(id, `${id}/${pageId}.rm`), 'application/octet-stream'], ['PUT', /^\/doc\/([^/]+)\/page\/([^/]+)$/, (id, pageId, body) => serial(async () => withDoc(await cloud.savePage(id, pageId, body)))], ['GET', /^\/doc\/([^/]+)\/thumbnail\/([^/]+)$/, (id, pageId) => blobOf(id, `${id}.thumbnails/${pageId}.png`), 'image/png'], ['PUT', /^\/doc\/([^/]+)\/thumbnail\/([^/]+)$/, (id, pageId, body) => serial(async () => withDoc(await cloud.editDocument(id, ({ doc, put }) => put(`${doc.id}.thumbnails/${pageId}.png`, body))))], ['GET', /^\/doc\/([^/]+)\/file\/(pdf|epub)$/, (id, kind) => blobOf(id, `${id}.${kind}`), (kind) => (kind === 'pdf' ? 'application/pdf' : 'application/epub+zip')], ['PUT', /^\/doc\/([^/]+)\/pdf$/, (id, body) => serial(async () => withDoc(await cloud.editDocument(id, ({ doc, put }) => put(`${doc.id}.pdf`, body))))], ]; function errorStatus (err) { if (err instanceof rm.NotFoundError) return 404; if (err instanceof rm.AuthError) return 401; if (err instanceof rm.AmbiguousPathError) return 409; if (err instanceof rm.CloudError) return err.status >= 400 ? 502 : 400; return 500; } function authorised (req) { const given = Buffer.from((req.headers.authorization || '').replace(/^Bearer /, '')); const want = Buffer.from(token); return given.length === want.length && timingSafeEqual(given, want); } function readBody (req, limit) { return new Promise((resolve, reject) => { const chunks = []; let size = 0; req.on('data', (c) => { size += c.length; if (size > limit) { reject(new rm.CloudError('request body too large')); req.destroy(); return; } chunks.push(c); }); req.on('end', () => resolve(Buffer.concat(chunks))); req.on('error', reject); }); } const server = createServer(async (req, res) => { const url = new URL(req.url, 'http://127.0.0.1'); const origin = req.headers.origin; if (origin && allowedOrigin(origin)) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Vary', 'Origin'); } const send = (code, data) => { res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(data)); }; const fail = (err) => { const code = errorStatus(err); if (code === 500) log(`${req.method} ${url.pathname}: ${err.stack || err.message}`); send(code, { error: err.message, name: err.name, status: err.status }); }; if (req.method === 'OPTIONS') { res.writeHead(204, { 'Access-Control-Allow-Methods': 'GET, POST, PUT', 'Access-Control-Allow-Headers': 'authorization, content-type', 'Access-Control-Max-Age': '600' }); return res.end(); } if (url.pathname === '/health') return send(200, { ok: true, loggedIn: cloud.api.loggedIn }); if (!authorised(req)) return send(401, { error: 'unauthorised' }); try { for (const [method, re, fn, type] of BINARY_ROUTES) { const m = method === req.method && url.pathname.match(re); if (!m) continue; const args = m.slice(1); if (method === 'PUT') { const body = await readBody(req, 512 * 1024 * 1024); return send(200, await fn(...args, body)); } const data = await fn(...args); if (!data) { res.writeHead(204); return res.end(); } res.writeHead(200, { 'Content-Type': typeof type === 'function' ? type(args[1]) : type, 'Content-Length': data.length, 'Cache-Control': 'no-store' }); return res.end(data); } if (req.method !== 'POST') return send(404, { error: 'not found' }); const body = JSON.parse((await readBody(req, 16 * 1024 * 1024)).toString('utf8') || '{}'); if (url.pathname === '/sync') { if (!body.dir) throw new rm.CloudError('a directory to mirror into is required'); patchSettings({ syncDir: body.dir, syncFormats: body.formats ?? [], syncRaw: body.raw !== false, syncTrash: Boolean(body.trash), syncPrune: body.prune !== false }); res.writeHead(200, { 'Content-Type': 'application/x-ndjson', 'Cache-Control': 'no-store' }); const line = (o) => res.write(JSON.stringify(o) + '\n'); await serial(async () => { try { const summary = await cloud.sync(body.dir, { formats: body.formats ?? [], raw: body.raw !== false, trash: Boolean(body.trash), prune: body.prune !== false, dryRun: Boolean(body.dryRun), onEvent: (e) => line({ event: { ...e, doc: e.doc ? { id: e.doc.id, name: e.doc.name } : undefined } }), }); line({ summary }); } catch (err) { line({ error: err.message, name: err.name }); } }); return res.end(); } const route = JSON_ROUTES[url.pathname]; if (!route) return send(404, { error: 'not found' }); send(200, await route(body)); } catch (err) { fail(err); } }); server.listen(port, '127.0.0.1', () => { log(`sidecar on http://127.0.0.1:${port} (credentials: ${configPath})`); });