// A small stand-in for the reMarkable cloud, implementing just the endpoints // notable uses, with the same validation rules the real one is known to apply // (generation check on the root, CRC32C and SHA-256 checks on blobs, schema-4 // sorted root indexes). import { createServer } from 'node:http'; import { createHash, randomUUID } from 'node:crypto'; import { crc32cHeader } from '../../lib/cloud/crc32c.js'; const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url'); const fakeJwt = (payload) => `${b64url({ alg: 'HS256', typ: 'JWT' })}.${b64url(payload)}.sig`; const claims = (token) => { try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8')); } catch { return null; } }; function readBody (req) { return new Promise((resolve, reject) => { const chunks = []; req.on('data', c => chunks.push(c)); req.on('end', () => resolve(Buffer.concat(chunks))); req.on('error', reject); }); } function parseIndexLoose (text) { const lines = text.split('\n').filter(Boolean); const schema = lines.shift(); if (schema === '4') lines.shift(); return { schema, entries: lines.map(l => { const f = l.split(':'); return { hash: f[0], type: f[1], name: f.slice(2, -2).join(':'), subfiles: Number(f.at(-2)), size: Number(f.at(-1)) }; }) }; } export async function startCloudServer ({ code = 'abcd1234', userTokenTtlMs = 3600_000 } = {}) { const state = { blobs: new Map(), // hash → { data, name } root: null, // { hash, generation } deviceTokens: new Set(), userTokens: new Set(), requests: [], counts: {}, generationCounter: 0, }; const count = (key) => { state.counts[key] = (state.counts[key] ?? 0) + 1; }; const issueUserToken = (device) => { const now = Math.floor(Date.now() / 1000); const token = fakeJwt({ exp: Math.floor((Date.now() + userTokenTtlMs) / 1000), iat: now, sub: 'auth0|user-1', 'auth0-profile': { UserID: 'auth0|user-1', Email: 'robin@example.com', Name: 'Robin' }, 'device-desc': device['device-desc'], 'device-id': device['device-id'], scopes: 'sync:fox docedit', jti: randomUUID(), }); state.userTokens.add(token); return token; }; const server = createServer(async (req, res) => { const url = new URL(req.url, 'http://localhost'); const path = url.pathname; state.requests.push({ method: req.method, path }); const send = (status, body, headers = {}) => { res.writeHead(status, headers); res.end(body); }; const json = (status, obj) => send(status, JSON.stringify(obj), { 'content-type': 'application/json' }); const bearer = (req.headers.authorization ?? '').replace(/^Bearer\s*/i, ''); try { if (req.method === 'POST' && path === '/token/json/2/device/new') { count('device/new'); const body = JSON.parse((await readBody(req)).toString('utf8') || '{}'); if (body.code !== code) return json(400, { message: 'invalid code' }); if (!body.deviceID || !body.deviceDesc) return json(400, { message: 'missing device' }); const token = fakeJwt({ 'device-id': body.deviceID, 'device-desc': body.deviceDesc, sub: 'auth0|user-1' }); state.deviceTokens.add(token); return send(200, token, { 'content-type': 'text/plain' }); } if (req.method === 'POST' && path === '/token/json/2/user/new') { count('user/new'); if (!state.deviceTokens.has(bearer)) return send(401, 'Unauthorized'); return send(200, issueUserToken(claims(bearer)), { 'content-type': 'text/plain' }); } // everything below needs a live user token const c = state.userTokens.has(bearer) ? claims(bearer) : null; if (!c || c.exp * 1000 <= Date.now()) { count('401'); return send(401, 'Unauthorized'); } if (req.method === 'GET' && path === '/sync/v4/root') { count('GET root'); if (!state.root) return json(404, { message: 'root not found' }); return json(200, { hash: state.root.hash, generation: state.root.generation, schemaVersion: 3 }); } if (req.method === 'PUT' && path === '/sync/v3/root') { count('PUT root'); const body = JSON.parse((await readBody(req)).toString('utf8')); const current = state.root?.generation ?? 0; if (body.generation !== current) { count('412'); return send(412, 'Precondition Failed'); } const blob = state.blobs.get(body.hash); if (!blob) return json(400, { message: 'unknown root hash' }); const idx = parseIndexLoose(blob.data.toString('utf8')); if (idx.schema !== '4') return json(400, { message: 'invalid root schema' }); const ids = idx.entries.map(e => e.name); if (ids.some((id, i) => i && !(ids[i - 1] < id))) return json(400, { message: 'invalid root schema' }); state.generationCounter++; state.root = { hash: body.hash, generation: Date.now() * 1000 + state.generationCounter }; if (body.broadcast) count('broadcast'); return json(200, { hash: state.root.hash, generation: state.root.generation }); } const m = path.match(/^\/sync\/v3\/files\/([0-9a-f]{64})$/); if (m && req.method === 'GET') { count('GET file'); const blob = state.blobs.get(m[1]); if (!blob) return send(404, 'Not Found'); return send(200, blob.data, { 'content-type': 'application/octet-stream', 'x-goog-hash': crc32cHeader(blob.data) }); } if (m && req.method === 'PUT') { count('PUT file'); const data = await readBody(req); const name = req.headers['rm-filename']; if (!name) return json(400, { message: 'missing rm-filename' }); if (req.headers['x-goog-hash'] !== crc32cHeader(data)) return json(400, { message: 'crc mismatch' }); let expected; if (name === 'root.docSchema') { expected = createHash('sha256').update(data).digest('hex'); } else if (name.endsWith('.docSchema')) { const idx = parseIndexLoose(data.toString('utf8')); const names = idx.entries.map(e => e.name); if (names.some((n, i) => i && !(names[i - 1] < n))) return json(400, { message: 'unsorted doc index' }); const h = createHash('sha256'); for (const e of idx.entries) h.update(Buffer.from(e.hash, 'hex')); expected = h.digest('hex'); } else { expected = createHash('sha256').update(data).digest('hex'); } if (expected !== m[1]) return json(400, { message: `hash mismatch for ${name}` }); state.blobs.set(m[1], { data, name }); return send(200, ''); } return send(404, 'Not Found'); } catch (err) { return json(500, { message: err.message }); } }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const { port } = server.address(); return { url: `http://127.0.0.1:${port}`, code, state, rootEntries () { if (!state.root) return []; return parseIndexLoose(state.blobs.get(state.root.hash).data.toString('utf8')).entries; }, close: () => new Promise(resolve => server.close(resolve)), }; }