Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140// Pairing with the reMarkable cloud and keeping the tokens around.//// The cloud hands out two JWTs: a long-lived *device token* obtained once by// exchanging a one-time code (from https://my.remarkable.com/device/browser/connect),// and a short-lived (about a day) *user token* minted from the device token// and sent as the bearer on every storage request. We store both in a small// JSON file and mint a fresh user token whenever the stored one has expired.
import { readFileSync, writeFileSync, mkdirSync, renameSync, chmodSync, existsSync, unlinkSync } from 'node:fs';import { join, dirname } from 'node:path';import { homedir, platform } from 'node:os';import { AuthError, CloudError } from './errors.js';
export const DEFAULT_AUTH_HOST = 'https://webapp-prod.cloud.remarkable.engineering';export const DEFAULT_SYNC_HOST = 'https://internal.cloud.remarkable.com';export const CONNECT_URL = 'https://my.remarkable.com/device/browser/connect';
export function defaultConfigPath () { if (process.env.NOTABLE_CONFIG) return process.env.NOTABLE_CONFIG; const base = process.env.XDG_CONFIG_HOME || join(homedir(), '.config'); return join(base, 'notable', 'cloud.json');}
export function defaultCacheDir () { if (process.env.NOTABLE_CACHE) return process.env.NOTABLE_CACHE; const base = process.env.XDG_CACHE_HOME || join(homedir(), '.cache'); return join(base, 'notable');}
export function defaultDeviceDesc () { const p = platform(); if (p === 'darwin') return 'desktop-macos'; if (p === 'win32') return 'desktop-windows'; return 'desktop-linux';}
// Resolve the hosts to talk to. Precedence: explicit config fields, then the// NOTABLE_AUTH_HOST / NOTABLE_SYNC_HOST environment, then NOTABLE_CLOUD_HOST// (one host for everything, e.g. a self-hosted rmfakecloud), then defaults.export function hosts (config = {}) { const one = config.host || process.env.NOTABLE_CLOUD_HOST || null; const strip = (h) => h.replace(/\/+$/, ''); return { authHost: strip(config.authHost || process.env.NOTABLE_AUTH_HOST || one || DEFAULT_AUTH_HOST), syncHost: strip(config.syncHost || process.env.NOTABLE_SYNC_HOST || one || DEFAULT_SYNC_HOST), };}
export function loadConfig (path = defaultConfigPath()) { if (!existsSync(path)) return {}; try { return JSON.parse(readFileSync(path, 'utf8')); } catch (err) { throw new CloudError(`cannot read ${path}: ${err.message}`, { cause: err }); }}
export function saveConfig (config, path = defaultConfigPath()) { mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); const tmp = `${path}.${process.pid}.tmp`; writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 }); chmodSync(tmp, 0o600); renameSync(tmp, path);}
export function deleteConfig (path = defaultConfigPath()) { if (existsSync(path)) unlinkSync(path);}
export function decodeJwt (token) { if (typeof token !== 'string') return null; const parts = token.split('.'); if (parts.length < 2) return null; try { return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')); } catch { return null; }}
// Expiry as a Date, or null when the token carries no `exp`.export function tokenExpiry (token) { const exp = decodeJwt(token)?.exp; return typeof exp === 'number' ? new Date(exp * 1000) : null;}
export function tokenExpired (token, skewMs = 60_000) { if (!token) return true; const expiry = tokenExpiry(token); return expiry ? expiry.getTime() - skewMs <= Date.now() : false;}
async function readToken (res, what) { const body = (await res.text()).trim(); if (!res.ok) { const Err = res.status === 401 || res.status === 403 || res.status === 400 ? AuthError : CloudError; throw new Err(`${what} failed: HTTP ${res.status}${body ? ` ${body.slice(0, 200)}` : ''}`, { status: res.status, body }); } const token = body.replace(/^"|"$/g, ''); if (!token) throw new CloudError(`${what} failed: empty token in response`); return token;}
// Exchange a one-time code for a device token.export async function registerDevice ({ code, deviceId, deviceDesc = defaultDeviceDesc(), authHost = DEFAULT_AUTH_HOST, fetch = globalThis.fetch, userAgent = 'notable' }) { code = String(code ?? '').trim(); if (!/^[a-z0-9]{8}$/i.test(code)) throw new AuthError('the one-time code should be 8 letters/digits'); const res = await fetch(`${authHost}/token/json/2/device/new`, { method: 'POST', headers: { authorization: 'Bearer', 'content-type': 'application/json', 'user-agent': userAgent }, body: JSON.stringify({ code: code.toLowerCase(), deviceDesc, deviceID: deviceId, secret: '' }), }); return readToken(res, 'device registration');}
// Mint a user token from a device token.export async function renewUserToken ({ deviceToken, authHost = DEFAULT_AUTH_HOST, fetch = globalThis.fetch, userAgent = 'notable' }) { if (!deviceToken) throw new AuthError('not logged in'); const res = await fetch(`${authHost}/token/json/2/user/new`, { method: 'POST', headers: { authorization: `Bearer ${deviceToken}`, 'user-agent': userAgent }, }); return readToken(res, 'user token renewal');}
// A human-readable summary of who the user token says we are.export function describeToken (userToken) { const claims = decodeJwt(userToken) || {}; const profile = claims['auth0-profile'] || {}; return { email: profile.Email || profile.email || null, name: profile.Name || profile.name || profile.GivenName || null, userId: profile.UserID || claims.sub || null, deviceDesc: claims['device-desc'] || null, deviceId: claims['device-id'] || null, scopes: typeof claims.scopes === 'string' ? claims.scopes.split(/\s+/).filter(Boolean) : [], expires: tokenExpiry(userToken), };}