// The low-level HTTP surface of the reMarkable cloud's sync v3 API: // // GET /sync/v4/root → { hash, generation, schemaVersion } // PUT /sync/v3/root ← { hash, generation, broadcast } (412 on stale generation) // GET /sync/v3/files/ → blob bytes // PUT /sync/v3/files/ ← blob bytes (rm-filename + x-goog-hash headers) // // Blobs are immutable and content-addressed, so they are cached on disk by // hash and never re-downloaded. import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; import { defaultConfigPath, defaultCacheDir, defaultDeviceDesc, hosts, loadConfig, saveConfig, deleteConfig, tokenExpired, registerDevice, renewUserToken, } from './auth.js'; import { crc32cHeader } from './crc32c.js'; import { sha256 } from './index-file.js'; import { AuthError, CloudError, GenerationConflictError, NotFoundError } from './errors.js'; const { version: VERSION } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))); export class CloudApi { // options: // configPath where tokens live (default ~/.config/notable/cloud.json); null → never persist // config an in-memory config object (skips reading configPath) // cacheDir blob cache directory (default ~/.cache/notable); null → no cache // fetch a fetch implementation (tests) // log function(message) for request tracing constructor ({ configPath = defaultConfigPath(), config = null, cacheDir = defaultCacheDir(), fetch = globalThis.fetch, log = null, userAgent = `notable/${VERSION}` } = {}) { this.configPath = configPath; this.config = config ?? (configPath ? loadConfig(configPath) : {}); this.cacheDir = cacheDir; this.fetch = fetch; this.log = log; this.userAgent = userAgent; this.uploaded = new Set(); // hashes we know the server has (this session) } get hosts () { return hosts(this.config); } get loggedIn () { return Boolean(this.config.deviceToken); } save () { if (this.configPath) saveConfig(this.config, this.configPath); } async login (code, { deviceDesc = defaultDeviceDesc() } = {}) { const deviceId = this.config.deviceId || randomUUID(); const deviceToken = await registerDevice({ code, deviceId, deviceDesc, authHost: this.hosts.authHost, fetch: this.fetch, userAgent: this.userAgent }); this.config = { ...this.config, deviceToken, deviceId, deviceDesc }; delete this.config.userToken; await this.renew(); return this.config; } logout () { this.config = {}; this.uploaded.clear(); if (this.configPath) deleteConfig(this.configPath); } async renew () { this.log?.('renewing user token'); this.config.userToken = await renewUserToken({ deviceToken: this.config.deviceToken, authHost: this.hosts.authHost, fetch: this.fetch, userAgent: this.userAgent }); this.save(); return this.config.userToken; } async token () { if (!this.config.deviceToken) throw new AuthError('not logged in — run `notable login`'); if (tokenExpired(this.config.userToken)) await this.renew(); return this.config.userToken; } async request (method, path, { body, headers = {}, retry = true } = {}) { const url = /^https?:/.test(path) ? path : `${this.hosts.syncHost}${path}`; const token = await this.token(); this.log?.(`${method} ${url}`); const res = await this.fetch(url, { method, headers: { authorization: `Bearer ${token}`, 'user-agent': this.userAgent, ...headers }, body, }); if ((res.status === 401 || res.status === 403) && retry) { await res.arrayBuffer().catch(() => {}); await this.renew(); return this.request(method, path, { body, headers, retry: false }); } if (res.status === 412) throw new GenerationConflictError(undefined, { status: 412, url }); if (res.status === 404) throw new NotFoundError(`${method} ${url}: not found`, { status: 404, url }); if (!res.ok) { const text = await res.text().catch(() => ''); throw new CloudError(`${method} ${url} failed: HTTP ${res.status}${text ? ` ${text.slice(0, 300)}` : ''}`, { status: res.status, body: text, url }); } return res; } // { hash, generation, schemaVersion }; an account that has never synced // has an empty hash and generation 0. async getRoot () { try { const res = await this.request('GET', '/sync/v4/root'); const json = await res.json(); return { hash: json.hash || '', generation: json.generation || 0, schemaVersion: json.schemaVersion ?? null }; } catch (err) { if (err instanceof NotFoundError) return { hash: '', generation: 0, schemaVersion: null }; throw err; } } // Point the root at a new index. `generation` must be the one we last read, // otherwise the server answers 412 and we throw GenerationConflictError. async putRoot (hash, generation, broadcast = true) { const body = Buffer.from(JSON.stringify({ broadcast, generation, hash })); const res = await this.request('PUT', '/sync/v3/root', { body, headers: { 'content-type': 'application/json', 'rm-filename': 'roothash', 'x-goog-hash': crc32cHeader(body) }, }); const json = await res.json(); if (json.hash && json.hash !== hash) throw new CloudError(`root hash mismatch after write: ${json.hash}`); return { hash, generation: json.generation }; } cachePath (hash) { return this.cacheDir ? join(this.cacheDir, 'blobs', hash) : null; } cacheRead (hash) { const p = this.cachePath(hash); if (!p || !existsSync(p)) return null; try { return readFileSync(p); } catch { return null; } } cacheWrite (hash, data) { const p = this.cachePath(hash); if (!p) return; try { mkdirSync(join(this.cacheDir, 'blobs'), { recursive: true }); const tmp = `${p}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; writeFileSync(tmp, data); renameSync(tmp, p); } catch (err) { this.log?.(`cache write failed for ${hash}: ${err.message}`); } } // Download a blob (cache first). `name` is the file name the blob is known // by (`root.docSchema`, `.docSchema`, `.metadata`, `/.rm`…). async getBlob (hash, name = '') { const cached = this.cacheRead(hash); if (cached) return cached; const res = await this.request('GET', `/sync/v3/files/${hash}`, { headers: name ? { 'rm-filename': name } : {} }); const data = Buffer.from(await res.arrayBuffer()); // Index blobs are addressed by a hash of their entries, plain files by a // hash of their bytes: only the latter can be checked here. if (!name.endsWith('.docSchema') && sha256(data) !== hash) { throw new CloudError(`blob ${hash} (${name}) failed its checksum`); } this.cacheWrite(hash, data); this.uploaded.add(hash); return data; } async putBlob (hash, name, data) { if (this.uploaded.has(hash)) return; const body = Buffer.isBuffer(data) ? data : Buffer.from(data); await this.request('PUT', `/sync/v3/files/${hash}`, { body, headers: { 'rm-filename': name, 'x-goog-hash': crc32cHeader(body), 'content-type': name === 'root.docSchema' ? 'text/plain; charset=UTF-8' : 'application/octet-stream', }, }); this.uploaded.add(hash); this.cacheWrite(hash, body); } }