summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--README.md9
-rw-r--r--SKILL.md9
-rwxr-xr-xscripts/icloud-note.mjs212
-rwxr-xr-xtests/cli.test.sh2
5 files changed, 158 insertions, 75 deletions
diff --git a/.gitignore b/.gitignore
index d5d7ab7..4d90a92 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
# Local runtime (lives under ~/.config/icloud-notes — never commit)
browser-profile/
+storage-state.json
node_modules/
package-lock.json
.env
diff --git a/README.md b/README.md
index b90b8f0..abb3fa0 100644
--- a/README.md
+++ b/README.md
@@ -20,9 +20,9 @@ icloud-note create --title "Hello" --body "From Linux"
| Command | Purpose |
|---|---|
| `icloud-note setup` | Install Playwright Chromium + `~/.local/bin` wrapper |
-| `icloud-note login` | Headed sign-in; saves session under `~/.config/icloud-notes/` |
-| `icloud-note status` | Check whether the saved session can open Notes |
-| `icloud-note create` | Create a note (`--title`, `--body` / `--body-file`) |
+| `icloud-note login` | **Only** command that opens a visible browser (one-time Apple ID) |
+| `icloud-note status` | Headless check that the saved session can open Notes |
+| `icloud-note create` | Headless create (`--title`, `--body` / `--body-file`) — no window |
## Layout
@@ -37,7 +37,8 @@ Runtime config (not in git):
```text
~/.config/icloud-notes/
- browser-profile/ Playwright persistent profile (private)
+ storage-state.json Cookies/session for headless create (private)
+ browser-profile/ Used only during `login` (private)
node_modules/ Playwright install
```
diff --git a/SKILL.md b/SKILL.md
index c4acb87..403e43f 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -24,12 +24,15 @@ Linked as: `~/.agents/skills/iphone-icloud-notes` → that repo
```bash
icloud-note status
-icloud-note login # one-time / when session expired (headed browser)
+icloud-note login # ONE-TIME only — only command that opens a window
icloud-note create --title "Title" --body "Body text"
icloud-note create --title "Title" --body-file /path/to.txt
icloud-note create --title "Title" --body-file - # stdin
```
+`create` / `status` are **always headless** (no visible browser). Never pass flags
+to force a window. Never run `login` unless the user must re-authenticate.
+
If `icloud-note` is missing from PATH:
```bash
@@ -69,5 +72,5 @@ Browser profile: `~/.config/icloud-notes/browser-profile/`
icloud-note login
```
-Requires a graphical session for `login` (DISPLAY/Wayland). After that, `create`
-can run headed or headless using the saved profile.
+Requires a graphical session for `login` only. After that, `create` / `status`
+use `~/.config/icloud-notes/storage-state.json` headlessly — no window.
diff --git a/scripts/icloud-note.mjs b/scripts/icloud-note.mjs
index 13a6efd..30c3b83 100755
--- a/scripts/icloud-note.mjs
+++ b/scripts/icloud-note.mjs
@@ -16,6 +16,7 @@ const CONFIG_DIR =
process.env.ICLOUD_NOTES_CONFIG ||
path.join(os.homedir(), ".config", "icloud-notes");
const PROFILE_DIR = path.join(CONFIG_DIR, "browser-profile");
+const STATE_PATH = path.join(CONFIG_DIR, "storage-state.json");
const NOTES_URL = "https://www.icloud.com/notes/";
function die(msg, code = 1) {
@@ -39,17 +40,71 @@ function loadPlaywright() {
}
}
-async function withNotesContext({ headed, fn }) {
+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: !headed,
+ headless: false,
viewport: { width: 1280, height: 900 },
args: ["--disable-blink-features=AutomationControlled"],
});
try {
- const page =
- context.pages()[0] || (await context.newPage());
+ const page = context.pages()[0] || (await context.newPage());
return await fn(page, context);
} finally {
await context.close();
@@ -88,7 +143,14 @@ async function waitForNotesApp(page, { timeoutMs = 120_000, allowLoginWait = fal
const ready = await page.evaluate(() => {
const iframe = document.querySelector("iframe");
const w = iframe?.contentWindow;
- return Boolean(w?.NotesApp?.dataManager);
+ 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;
@@ -121,30 +183,47 @@ async function createViaNotesApp(page, title, body) {
const dataManager = app.dataManager;
const mv = app.mainViewModel;
- let Note = mv?.selectedNote?.constructor;
- if (!Note && dataManager.allNotes?.length) {
- Note = dataManager.allNotes[0].constructor;
- }
- if (!Note?.createNoteWithTitleText) {
+ 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 ||
- (Array.isArray(dataManager.folders) ? dataManager.folders[0] : null) ||
- (dataManager.allFolders && dataManager.allFolders[0]) ||
+ (folderList?.objectAt ? folderList.objectAt(0) : folderList?.[0]) ||
null;
if (!folder) {
throw new Error("Could not resolve a Notes folder");
}
- const note = Note.createNoteWithTitleText(text, folder);
- dataManager.userDidCreateNote(note);
+ 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)"),
@@ -156,30 +235,26 @@ async function createViaNotesApp(page, title, body) {
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;
- for (const sel of candidates) {
- const btn = page.frameLocator("iframe").locator(sel).first();
- if ((await btn.count().catch(() => 0)) > 0) {
- await btn.click({ timeout: 5000 });
- clicked = true;
- break;
- }
- }
- if (!clicked) {
- // try top-level too
+ const scopes = [page.frameLocator("iframe"), page];
+ for (const scope of scopes) {
for (const sel of candidates) {
- const btn = page.locator(sel).first();
+ 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");
@@ -198,12 +273,9 @@ async function createViaUiFallback(page, title, body) {
async function cmdStatus() {
try {
- await withNotesContext({
- headed: false,
- fn: async (page) => {
- await waitForNotesApp(page, { timeoutMs: 20_000 });
- console.log("ok: logged in to icloud.com/notes");
- },
+ 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}`);
@@ -214,22 +286,22 @@ async function cmdLogin() {
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…");
- console.error("Sign in, complete 2FA, wait until Notes loads, then return here.");
- await withNotesContext({
- headed: true,
- fn: async (page) => {
- await page.goto(NOTES_URL, { waitUntil: "domcontentloaded" });
- try {
- await waitForNotesApp(page, {
- timeoutMs: 10 * 60_000,
- allowLoginWait: true,
- });
- console.log("ok: session saved — you can close the window next time");
- } catch (err) {
- die(`login incomplete: ${err.message}`);
- }
- },
+ 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}`);
+ }
});
}
@@ -255,24 +327,27 @@ async function cmdCreate(opts) {
die("Provide --title and/or --body / --body-file / stdin");
}
- const headed = Boolean(opts.values.headed);
- await withNotesContext({
- headed,
- fn: 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);
- console.log(
- `created: ${result.title}${result.recordName ? ` (${result.recordName})` : ""}`,
- );
- },
+ 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})` : ""}`,
+ );
});
}
@@ -280,10 +355,12 @@ function printHelp() {
console.log(`Usage:
icloud-note setup
icloud-note status
- icloud-note login
- icloud-note create --title TITLE [--body TEXT | --body-file PATH|-] [--headed]
+ 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).
`);
}
@@ -317,7 +394,6 @@ async function main() {
title: { type: "string" },
body: { type: "string" },
"body-file": { type: "string" },
- headed: { type: "boolean", default: false },
},
allowPositionals: true,
});
diff --git a/tests/cli.test.sh b/tests/cli.test.sh
index 2694938..aefb371 100755
--- a/tests/cli.test.sh
+++ b/tests/cli.test.sh
@@ -10,6 +10,8 @@ pass() { echo "ok: $*"; }
out="$("${CLI[@]}" help 2>&1)" || fail "help exited non-zero"
[[ "$out" == *"icloud-note create"* ]] || fail "help missing create usage"
+[[ "$out" == *"headless"* ]] || fail "help should say create/status are headless"
+[[ "$out" != *"--headed"* ]] || fail "help must not advertise --headed"
pass "help"
set +e