summaryrefslogtreecommitdiff
path: root/legacy/nodejs/scripts/icloud-note.mjs
diff options
context:
space:
mode:
Diffstat (limited to 'legacy/nodejs/scripts/icloud-note.mjs')
-rwxr-xr-xlegacy/nodejs/scripts/icloud-note.mjs436
1 files changed, 436 insertions, 0 deletions
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)));