From 5c61196f27b9342e5f25414c11df5710f956f406 Mon Sep 17 00:00:00 2001 From: Christopher Warner Date: Sat, 10 Oct 2026 18:47:24 -0400 Subject: feat!: rewrite icloud-note CLI in Rust with chromiumoxide Replace the Node/Playwright driver with a single Rust binary so create/status stay headless without a visible browser. Move the previous implementation to legacy/nodejs for reference. BREAKING CHANGE: the supported CLI is the Rust `icloud-note` binary; the Node entrypoint is no longer installed by setup.sh. Co-authored-by: Cursor --- legacy/nodejs/README.md | 4 + legacy/nodejs/package.json | 12 + legacy/nodejs/scripts/icloud-note.mjs | 436 +++++++++++++++++++++++++++++ legacy/nodejs/scripts/lib/note-helpers.mjs | 88 ++++++ legacy/nodejs/tests/helpers.test.mjs | 113 ++++++++ 5 files changed, 653 insertions(+) create mode 100644 legacy/nodejs/README.md create mode 100644 legacy/nodejs/package.json create mode 100755 legacy/nodejs/scripts/icloud-note.mjs create mode 100644 legacy/nodejs/scripts/lib/note-helpers.mjs create mode 100644 legacy/nodejs/tests/helpers.test.mjs (limited to 'legacy') diff --git a/legacy/nodejs/README.md b/legacy/nodejs/README.md new file mode 100644 index 0000000..59be97c --- /dev/null +++ b/legacy/nodejs/README.md @@ -0,0 +1,4 @@ +# Legacy Node/Playwright implementation + +Superseded by the Rust `icloud-note` binary (`chromiumoxide`) at the repo root. +Kept for reference only; not installed by `scripts/setup.sh`. diff --git a/legacy/nodejs/package.json b/legacy/nodejs/package.json new file mode 100644 index 0000000..0b3f513 --- /dev/null +++ b/legacy/nodejs/package.json @@ -0,0 +1,12 @@ +{ + "name": "iphone-notes", + "private": true, + "type": "module", + "description": "Create Apple Notes from Linux via icloud.com/notes", + "scripts": { + "test": "./tests/run.sh" + }, + "engines": { + "node": ">=20" + } +} diff --git a/legacy/nodejs/scripts/icloud-note.mjs b/legacy/nodejs/scripts/icloud-note.mjs new file mode 100755 index 0000000..aa42e95 --- /dev/null +++ b/legacy/nodejs/scripts/icloud-note.mjs @@ -0,0 +1,436 @@ +#!/usr/bin/env node +/** + * Create Apple Notes via https://www.icloud.com/notes using a persistent + * Playwright Chromium profile under ~/.config/icloud-notes/ + */ +import { createRequire } from "node:module"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; +import { + formatNoteText, + isAppleAuthUrl, + looksLoggedOut, + requireCreateContent, + resolveConfigPaths, +} from "./lib/note-helpers.mjs"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const paths = resolveConfigPaths(process.env, os.homedir()); +const CONFIG_DIR = paths.configDir; +const PROFILE_DIR = paths.profileDir; +const STATE_PATH = paths.statePath; +const NOTES_URL = "https://www.icloud.com/notes/"; +const DRY_RUN = process.env.ICLOUD_NOTES_DRY_RUN === "1"; + +function die(msg, code = 1) { + console.error(msg); + process.exit(code); +} + +function ensureConfigDir() { + fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); + fs.mkdirSync(PROFILE_DIR, { recursive: true, mode: 0o700 }); +} + +function loadPlaywright() { + const require = createRequire(path.join(CONFIG_DIR, "package.json")); + try { + return require("playwright"); + } catch { + die( + `Playwright not installed. Run:\n ${path.join(__dirname, "setup.sh")}`, + ); + } +} + +async function ensureStorageState(chromium) { + if (fs.existsSync(STATE_PATH)) return; + // One-time migration from an older profile-only login (still headless). + if (!fs.existsSync(path.join(PROFILE_DIR, "Default"))) { + throw new Error("No saved session. Run: icloud-note login"); + } + const context = await chromium.launchPersistentContext(PROFILE_DIR, { + headless: true, + args: [ + "--headless=new", + "--ozone-platform=headless", + "--disable-blink-features=AutomationControlled", + ], + }); + try { + await context.storageState({ path: STATE_PATH }); + fs.chmodSync(STATE_PATH, 0o600); + } finally { + await context.close(); + } +} + +/** + * Headless-only path for status/create. Uses saved storage state — never opens + * a visible window (launchPersistentContext can still flash UI on Linux). + */ +async function withHeadlessNotes(fn) { + ensureConfigDir(); + const { chromium } = loadPlaywright(); + await ensureStorageState(chromium); + const browser = await chromium.launch({ + headless: true, + args: [ + "--disable-blink-features=AutomationControlled", + "--headless=new", + "--ozone-platform=headless", + ], + }); + try { + const context = await browser.newContext({ + storageState: STATE_PATH, + viewport: { width: 1280, height: 900 }, + }); + const page = await context.newPage(); + try { + return await fn(page, context); + } finally { + await context.close(); + } + } finally { + await browser.close(); + } +} + +/** Headed login only — saves storage-state.json for later headless runs. */ +async function withLoginBrowser(fn) { + ensureConfigDir(); + const { chromium } = loadPlaywright(); + const context = await chromium.launchPersistentContext(PROFILE_DIR, { + headless: false, + viewport: { width: 1280, height: 900 }, + args: ["--disable-blink-features=AutomationControlled"], + }); + try { + const page = context.pages()[0] || (await context.newPage()); + return await fn(page, context); + } finally { + await context.close(); + } +} + +async function pageLooksLoggedOut(page) { + const url = page.url(); + if (isAppleAuthUrl(url)) return true; + const signals = await page.evaluate(() => { + const t = (document.body?.innerText || "").slice(0, 4000); + const hasPasswordField = Boolean( + document.querySelector( + 'input[type="password"], #password_text_field, #account_name_text_field', + ), + ); + const hasSignInControl = [...document.querySelectorAll("a,button,div[role='button']")].some( + (el) => /^sign in$/i.test((el.textContent || "").trim()), + ); + const hasNotesApp = Boolean( + document.querySelector("iframe")?.contentWindow?.NotesApp?.dataManager, + ); + return { bodyText: t, hasPasswordField, hasSignInControl, hasNotesApp }; + }).catch(() => ({})); + return looksLoggedOut({ url, ...signals }); +} + +async function waitForNotesApp(page, { timeoutMs = 120_000, allowLoginWait = false } = {}) { + await page.goto(NOTES_URL, { waitUntil: "domcontentloaded", timeout: 60_000 }); + const deadline = Date.now() + timeoutMs; + let sawLogin = false; + while (Date.now() < deadline) { + const ready = await page.evaluate(() => { + const iframe = document.querySelector("iframe"); + const w = iframe?.contentWindow; + const dm = w?.NotesApp?.dataManager; + if (!dm) return false; + // Need at least one loaded note/folder so Note.create* is reachable + const notes = dm.allNotes || dm.__CW__allNotes; + const folders = dm.allFolders || dm.__CW__allFolders || dm.folders; + const n = notes?.length || 0; + const f = folders?.length || 0; + return n > 0 || f > 0; + }).catch(() => false); + if (ready) return; + + if (await pageLooksLoggedOut(page)) { + sawLogin = true; + if (!allowLoginWait) { + throw new Error("Not signed in. Run: icloud-note login"); + } + } + await page.waitForTimeout(1000); + } + throw new Error( + sawLogin + ? "Login did not finish. Complete Apple ID sign-in in the browser window." + : "NotesApp did not become ready. Run: icloud-note login", + ); +} + +async function createViaNotesApp(page, title, body) { + const fullText = formatNoteText(title, body); + + return page.evaluate(async (text) => { + const iframe = document.querySelector("iframe"); + const w = iframe?.contentWindow; + const app = w?.NotesApp; + if (!app?.dataManager) { + throw new Error("NotesApp unavailable"); + } + + const dataManager = app.dataManager; + const mv = app.mainViewModel; + const noteList = dataManager.allNotes || dataManager.__CW__allNotes; + const sample = + mv?.selectedNote || + (noteList?.objectAt ? noteList.objectAt(0) : noteList?.[0]) || + null; + const Note = sample?.constructor; + if (!Note?.createNoteWithTitleText && !Note?.createEmptyNote) { + throw new Error( + "Could not find Note.createNoteWithTitleText — UI may have changed", + ); + } + + const folderList = + dataManager.allFolders || + dataManager.__CW__allFolders || + dataManager.folders; + const folder = + mv?.selectedFolder || + dataManager.defaultFolder || + dataManager.inboxFolder || + (folderList?.objectAt ? folderList.objectAt(0) : folderList?.[0]) || + null; + + if (!folder) { + throw new Error("Could not resolve a Notes folder"); + } + + let note; + if (typeof Note.createNoteWithTitleText === "function") { + note = Note.createNoteWithTitleText(text, folder); + } else { + note = Note.createEmptyNote(folder); + if (typeof note.userDidChangeTopoText === "function") { + // Prefer structured text update when available + note.userDidChangeTopoText?.(text); + } + if (note.Title !== undefined) note.Title = text.split("\n")[0] || "Note"; + } + if (typeof dataManager.userDidCreateNote === "function") { + dataManager.userDidCreateNote(note); + } + await note.save(true); + return { + title: String(note.Title || text.split("\n")[0] || "(untitled)"), + recordName: String(note.recordName || note.id || ""), + }; + }, fullText); +} + +async function createViaUiFallback(page, title, body) { + // Last resort: keyboard into the Notes UI + const candidates = [ + '[title="Create a note"]', + 'button[aria-label="Create"]', + 'ui-button[aria-label="Create"]', + 'button[aria-label*="New Note" i]', + 'button[title*="New Note" i]', + 'button[aria-label*="Create" i]', + '[data-testid="new-note"]', + ]; + let clicked = false; + const scopes = [page.frameLocator("iframe"), page]; + for (const scope of scopes) { + for (const sel of candidates) { + const btn = scope.locator(sel).first(); + if ((await btn.count().catch(() => 0)) > 0) { + await btn.click({ timeout: 5000 }); + clicked = true; + break; + } + } + if (clicked) break; + } + if (!clicked) { + throw new Error("UI fallback: could not find New Note control"); + } + + const text = formatNoteText(title, body); + const editable = page + .frameLocator("iframe") + .locator('[contenteditable="true"], [role="textbox"]') + .first(); + await editable.click({ timeout: 10_000 }); + await editable.fill(text); + await page.waitForTimeout(1500); + return { title: title || text.split("\n")[0] || "(untitled)", recordName: "" }; +} + +async function cmdStatus() { + if (DRY_RUN) { + if (!fs.existsSync(STATE_PATH) && !fs.existsSync(path.join(PROFILE_DIR, "Default"))) { + die("not ready: No saved session. Run: icloud-note login"); + } + console.log("ok: dry-run status (would check Notes headless)"); + return; + } + try { + await withHeadlessNotes(async (page) => { + await waitForNotesApp(page, { timeoutMs: 20_000 }); + console.log("ok: logged in to icloud.com/notes (headless)"); + }); + } catch (err) { + die(`not ready: ${err.message}`); + } +} + +async function cmdLogin() { + if (DRY_RUN) { + die("login dry-run: would open a visible browser (refusing)"); + } + if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) { + die("login needs a graphical session (DISPLAY or WAYLAND_DISPLAY)."); + } + console.error("Opening Chromium for Apple ID sign-in (one-time)…"); + console.error("Sign in, complete 2FA, wait until Notes loads."); + await withLoginBrowser(async (page, context) => { + await page.goto(NOTES_URL, { waitUntil: "domcontentloaded" }); + try { + await waitForNotesApp(page, { + timeoutMs: 10 * 60_000, + allowLoginWait: true, + }); + await context.storageState({ path: STATE_PATH }); + fs.chmodSync(STATE_PATH, 0o600); + console.log(`ok: session saved to ${STATE_PATH}`); + console.log("ok: create/status will run headless (no window)"); + } catch (err) { + die(`login incomplete: ${err.message}`); + } + }); +} + +function readBody(opts) { + if (opts.values["body-file"]) { + const f = opts.values["body-file"]; + if (f === "-") { + return fs.readFileSync(0, "utf8"); + } + return fs.readFileSync(f, "utf8"); + } + if (opts.values.body != null) return String(opts.values.body); + if (!process.stdin.isTTY) { + return fs.readFileSync(0, "utf8"); + } + return ""; +} + +async function cmdCreate(opts) { + let title; + let body; + try { + ({ title, body } = requireCreateContent( + opts.values.title || "", + readBody(opts), + )); + } catch (err) { + die(err.message); + } + + if (DRY_RUN) { + const text = formatNoteText(title, body); + console.log( + `dry-run: would create note title=${JSON.stringify(title)} chars=${text.length}`, + ); + return; + } + + await withHeadlessNotes(async (page) => { + await waitForNotesApp(page, { timeoutMs: 90_000 }); + let result; + try { + result = await createViaNotesApp(page, title, body); + } catch (err) { + console.error(`NotesApp path failed (${err.message}); trying UI…`); + result = await createViaUiFallback(page, title, body); + } + // Give CloudKit a moment to flush + await page.waitForTimeout(2000); + // Refresh saved cookies/session after a successful create + try { + await page.context().storageState({ path: STATE_PATH }); + fs.chmodSync(STATE_PATH, 0o600); + } catch { + /* non-fatal */ + } + console.log( + `created: ${result.title}${result.recordName ? ` (${result.recordName})` : ""}`, + ); + }); +} + +function printHelp() { + console.log(`Usage: + icloud-note setup + icloud-note status + icloud-note login # only command that opens a visible browser + icloud-note create --title TITLE [--body TEXT | --body-file PATH|-] + +Config: ${CONFIG_DIR} +Session: ${STATE_PATH} +create/status always run headless (no window). +`); +} + +async function main() { + const argv = process.argv.slice(2); + const cmd = argv[0] || "help"; + + if (cmd === "help" || cmd === "-h" || cmd === "--help") { + printHelp(); + return; + } + + if (cmd === "setup") { + const setup = path.join(__dirname, "setup.sh"); + const r = spawnSync(setup, { stdio: "inherit" }); + process.exit(r.status ?? 1); + } + + if (cmd === "status") { + await cmdStatus(); + return; + } + if (cmd === "login") { + await cmdLogin(); + return; + } + if (cmd === "create") { + const opts = parseArgs({ + args: argv.slice(1), + options: { + title: { type: "string" }, + body: { type: "string" }, + "body-file": { type: "string" }, + }, + allowPositionals: true, + }); + if (!opts.values.title && opts.positionals[0]) { + opts.values.title = opts.positionals[0]; + } + await cmdCreate(opts); + return; + } + + die(`Unknown command: ${cmd}\nRun: icloud-note help`); +} + +main().catch((err) => die(err.stack || String(err))); diff --git a/legacy/nodejs/scripts/lib/note-helpers.mjs b/legacy/nodejs/scripts/lib/note-helpers.mjs new file mode 100644 index 0000000..5dd43a0 --- /dev/null +++ b/legacy/nodejs/scripts/lib/note-helpers.mjs @@ -0,0 +1,88 @@ +/** + * Pure helpers for icloud-note (unit-tested; no Playwright). + */ + +/** Join title + body the way Apple Notes expects (first line = title). */ +export function formatNoteText(title, body) { + const t = title == null ? "" : String(title); + const b = body == null ? "" : String(body); + return [t, b].filter((s) => s.length > 0).join("\n\n"); +} + +/** True when a URL is clearly an Apple auth/sign-in page. */ +export function isAppleAuthUrl(url) { + return /idmsa\.apple\.com|appleid\.apple\.com/i.test(String(url || "")); +} + +/** + * Heuristic "logged out" detection from page signals (mirrors pageLooksLoggedOut). + * @param {{ url?: string, bodyText?: string, hasPasswordField?: boolean, hasSignInControl?: boolean, hasNotesApp?: boolean }} s + */ +export function looksLoggedOut(s = {}) { + if (isAppleAuthUrl(s.url)) return true; + const t = String(s.bodyText || "").slice(0, 4000); + if (/Sign in to iCloud/i.test(t)) return true; + if (s.hasPasswordField) return true; + if (s.hasSignInControl && !s.hasNotesApp) return true; + return false; +} + +/** Resolve XDG-style config paths (overridable via env for tests). */ +export function resolveConfigPaths(env = process.env, homedir = "") { + const home = + homedir || + env.HOME || + env.USERPROFILE || + "/tmp"; + const configDir = + env.ICLOUD_NOTES_CONFIG || `${home}/.config/icloud-notes`; + return { + configDir, + profileDir: `${configDir}/browser-profile`, + statePath: `${configDir}/storage-state.json`, + }; +} + +/** + * Parse create CLI flags (subset of node:util parseArgs shape). + * @returns {{ title: string, bodyFile?: string, body?: string, positionals: string[] }} + */ +export function parseCreateArgv(argv) { + const out = { title: "", body: undefined, bodyFile: undefined, positionals: [] }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--title") { + out.title = String(argv[++i] ?? ""); + } else if (a === "--body") { + out.body = String(argv[++i] ?? ""); + } else if (a === "--body-file") { + out.bodyFile = String(argv[++i] ?? ""); + } else if (a.startsWith("-")) { + throw new Error(`Unknown option: ${a}`); + } else { + out.positionals.push(a); + } + } + if (!out.title && out.positionals[0]) { + out.title = out.positionals[0]; + } + return out; +} + +/** Validate create has something to send. */ +export function requireCreateContent(title, body) { + const t = title == null ? "" : String(title); + const b = body == null ? "" : String(body).replace(/\s+$/, ""); + if (!t && !b) { + throw new Error("Provide --title and/or --body / --body-file / stdin"); + } + return { title: t, body: b }; +} + +/** Conventional Commits 1.0.0 subject line (first line of message). */ +export function isConventionalCommitSubject(subject) { + const line = String(subject || "").trim(); + return /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-zA-Z0-9._/-]+\))?!?: .+/.test( + line, + ); +} diff --git a/legacy/nodejs/tests/helpers.test.mjs b/legacy/nodejs/tests/helpers.test.mjs new file mode 100644 index 0000000..38742d8 --- /dev/null +++ b/legacy/nodejs/tests/helpers.test.mjs @@ -0,0 +1,113 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + formatNoteText, + isAppleAuthUrl, + looksLoggedOut, + resolveConfigPaths, + parseCreateArgv, + requireCreateContent, + isConventionalCommitSubject, +} from "../scripts/lib/note-helpers.mjs"; + +describe("formatNoteText", () => { + it("joins title and body with a blank line", () => { + assert.equal(formatNoteText("Hi", "body"), "Hi\n\nbody"); + }); + it("title only", () => { + assert.equal(formatNoteText("Hi", ""), "Hi"); + }); + it("body only", () => { + assert.equal(formatNoteText("", "body"), "body"); + }); + it("ignores nullish", () => { + assert.equal(formatNoteText(null, "x"), "x"); + }); +}); + +describe("isAppleAuthUrl / looksLoggedOut", () => { + it("detects idmsa / appleid URLs", () => { + assert.equal(isAppleAuthUrl("https://idmsa.apple.com/appleauth/auth"), true); + assert.equal(isAppleAuthUrl("https://appleid.apple.com/"), true); + assert.equal(isAppleAuthUrl("https://www.icloud.com/notes/"), false); + }); + it("detects sign-in page signals", () => { + assert.equal( + looksLoggedOut({ bodyText: "Sign in to iCloud to continue" }), + true, + ); + assert.equal(looksLoggedOut({ hasPasswordField: true }), true); + assert.equal( + looksLoggedOut({ hasSignInControl: true, hasNotesApp: false }), + true, + ); + assert.equal( + looksLoggedOut({ hasSignInControl: true, hasNotesApp: true }), + false, + ); + assert.equal(looksLoggedOut({ url: "https://www.icloud.com/notes/" }), false); + }); +}); + +describe("resolveConfigPaths", () => { + it("uses ICLOUD_NOTES_CONFIG when set", () => { + const p = resolveConfigPaths({ ICLOUD_NOTES_CONFIG: "/tmp/icloud-test" }); + assert.equal(p.configDir, "/tmp/icloud-test"); + assert.equal(p.statePath, "/tmp/icloud-test/storage-state.json"); + assert.equal(p.profileDir, "/tmp/icloud-test/browser-profile"); + }); + it("defaults under homedir/.config/icloud-notes", () => { + const p = resolveConfigPaths({}, "/home/me"); + assert.equal(p.configDir, "/home/me/.config/icloud-notes"); + }); +}); + +describe("parseCreateArgv / requireCreateContent", () => { + it("parses flags", () => { + const a = parseCreateArgv(["--title", "T", "--body", "B"]); + assert.equal(a.title, "T"); + assert.equal(a.body, "B"); + }); + it("positional title", () => { + const a = parseCreateArgv(["MyTitle"]); + assert.equal(a.title, "MyTitle"); + }); + it("body-file flag", () => { + const a = parseCreateArgv(["--title", "T", "--body-file", "/tmp/x"]); + assert.equal(a.bodyFile, "/tmp/x"); + }); + it("rejects unknown options", () => { + assert.throws(() => parseCreateArgv(["--headed"]), /Unknown option/); + }); + it("requireCreateContent throws when empty", () => { + assert.throws(() => requireCreateContent("", ""), /Provide --title/); + }); + it("requireCreateContent trims body trailing whitespace", () => { + const r = requireCreateContent("T", "hi\n\n"); + assert.equal(r.body, "hi"); + }); +}); + +describe("isConventionalCommitSubject", () => { + it("accepts Conventional Commits subjects", () => { + assert.equal( + isConventionalCommitSubject( + "feat: add icloud.com/notes helper and agent skill", + ), + true, + ); + assert.equal( + isConventionalCommitSubject( + "fix: run create/status headless without a visible browser", + ), + true, + ); + assert.equal(isConventionalCommitSubject("feat(notes): add dry-run"), true); + assert.equal(isConventionalCommitSubject("feat!: breaking"), true); + }); + it("rejects non-conventional subjects", () => { + assert.equal(isConventionalCommitSubject("Added tests"), false); + assert.equal(isConventionalCommitSubject("feat add stuff"), false); + assert.equal(isConventionalCommitSubject("FIX: caps type"), false); + }); +}); -- cgit v1.2.3