summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorChristopher Warner <cwarner@kernelcode.com>2026-10-10 18:47:24 -0400
committerChristopher Warner <cwarner@kernelcode.com>2026-10-10 18:47:24 -0400
commit5c61196f27b9342e5f25414c11df5710f956f406 (patch)
treec81f15f54c9baa35f61ce3c71b81f1c1e7b5f590 /scripts
parent78862ba855c6e66cac64a86c25dca6149d8fb2fd (diff)
downloadiphone-notes-5c61196f27b9342e5f25414c11df5710f956f406.tar.gz
iphone-notes-5c61196f27b9342e5f25414c11df5710f956f406.tar.bz2
iphone-notes-5c61196f27b9342e5f25414c11df5710f956f406.tar.xz
iphone-notes-5c61196f27b9342e5f25414c11df5710f956f406.zip
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 <cursoragent@cursor.com>
Diffstat (limited to 'scripts')
-rwxr-xr-xscripts/icloud-note.mjs436
-rw-r--r--scripts/lib/note-helpers.mjs88
-rwxr-xr-xscripts/setup.sh43
3 files changed, 25 insertions, 542 deletions
diff --git a/scripts/icloud-note.mjs b/scripts/icloud-note.mjs
deleted file mode 100755
index aa42e95..0000000
--- a/scripts/icloud-note.mjs
+++ /dev/null
@@ -1,436 +0,0 @@
-#!/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/scripts/lib/note-helpers.mjs b/scripts/lib/note-helpers.mjs
deleted file mode 100644
index 5dd43a0..0000000
--- a/scripts/lib/note-helpers.mjs
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * 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/scripts/setup.sh b/scripts/setup.sh
index a4a03fa..9c64c4c 100755
--- a/scripts/setup.sh
+++ b/scripts/setup.sh
@@ -1,36 +1,43 @@
#!/usr/bin/env bash
-# Install Playwright + Chromium for icloud-note under ~/.config/icloud-notes
+# Build Rust icloud-note, ensure Chromium, install to ~/.local/bin, link agent skill.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CONFIG_DIR="${ICLOUD_NOTES_CONFIG:-$HOME/.config/icloud-notes}"
-SKILL_SCRIPT="$REPO_ROOT/scripts/icloud-note.mjs"
-BIN="$HOME/.local/bin/icloud-note"
+BIN_DIR="$HOME/.local/bin"
+BIN="$BIN_DIR/icloud-note"
AGENTS_SKILL="$HOME/.agents/skills/iphone-icloud-notes"
CURSOR_SKILL="$HOME/.cursor/skills/iphone-icloud-notes"
-mkdir -p "$CONFIG_DIR" "$HOME/.local/bin" "$HOME/.agents/skills" "$HOME/.cursor/skills"
+mkdir -p "$CONFIG_DIR" "$BIN_DIR" "$HOME/.agents/skills" "$HOME/.cursor/skills"
chmod 700 "$CONFIG_DIR"
-cd "$CONFIG_DIR"
-if [[ ! -f package.json ]]; then
- npm init -y >/dev/null
+# Prefer existing Playwright Chromium; otherwise install via npx playwright
+if [[ -z "${ICLOUD_NOTES_CHROME:-}" ]]; then
+ if compgen -G "$HOME/.cache/ms-playwright/chromium-*/chrome-linux64/chrome" > /dev/null; then
+ CHROME="$(ls -1 "$HOME/.cache/ms-playwright"/chromium-*/chrome-linux64/chrome | head -1)"
+ echo "ok: using Playwright Chromium at $CHROME"
+ elif command -v npm >/dev/null 2>&1; then
+ echo "Installing Playwright Chromium for automation…"
+ mkdir -p "$CONFIG_DIR"
+ cd "$CONFIG_DIR"
+ if [[ ! -f package.json ]]; then
+ npm init -y >/dev/null
+ fi
+ npm install playwright@latest
+ npx playwright install chromium
+ else
+ echo "warn: no Chromium found and npm unavailable; install Chromium or set ICLOUD_NOTES_CHROME" >&2
+ fi
fi
-npm install playwright@latest
-npx playwright install chromium
+cd "$REPO_ROOT"
+cargo build --release
+install -m 755 "$REPO_ROOT/target/release/icloud-note" "$BIN"
-cat > "$BIN" <<EOF
-#!/usr/bin/env bash
-exec node "$SKILL_SCRIPT" "\$@"
-EOF
-chmod 755 "$BIN" "$SKILL_SCRIPT" "$REPO_ROOT/scripts/setup.sh"
-
-# Point agent skill dirs at this repo (source of truth)
ln -sfn "$REPO_ROOT" "$AGENTS_SKILL"
ln -sfn "$REPO_ROOT" "$CURSOR_SKILL"
-echo "ok: playwright installed in $CONFIG_DIR"
-echo "ok: wrapper $BIN"
+echo "ok: installed $BIN"
echo "ok: skill linked -> $REPO_ROOT"
echo "Next: icloud-note login"