summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore7
-rw-r--r--LICENSE21
-rw-r--r--README.md52
-rw-r--r--SKILL.md73
-rwxr-xr-xscripts/icloud-note.mjs334
-rwxr-xr-xscripts/setup.sh36
-rwxr-xr-xtests/cli.test.sh31
7 files changed, 554 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d5d7ab7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+# Local runtime (lives under ~/.config/icloud-notes — never commit)
+browser-profile/
+node_modules/
+package-lock.json
+.env
+*.log
+.DS_Store
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..14fac91
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b90b8f0
--- /dev/null
+++ b/README.md
@@ -0,0 +1,52 @@
+# iphone-notes
+
+Create real **Apple Notes** on an iPhone from Linux by driving
+[icloud.com/notes](https://www.icloud.com/notes/) with Playwright and a saved
+Apple ID browser session.
+
+Also packaged as a Cursor/Goose agent skill (`SKILL.md`) so agents can forward
+prompt results to your phone as Notes.
+
+## Quick start
+
+```bash
+./scripts/setup.sh
+icloud-note login # Apple ID + 2FA once (graphical session)
+icloud-note create --title "Hello" --body "From Linux"
+```
+
+## CLI
+
+| 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`) |
+
+## Layout
+
+```text
+SKILL.md Agent instructions
+scripts/icloud-note.mjs CLI
+scripts/setup.sh One-time install + skill symlinks
+tests/cli.test.sh Smoke tests (no Apple network required)
+```
+
+Runtime config (not in git):
+
+```text
+~/.config/icloud-notes/
+ browser-profile/ Playwright persistent profile (private)
+ node_modules/ Playwright install
+```
+
+## Tests
+
+```bash
+./tests/cli.test.sh
+```
+
+## License
+
+MIT
diff --git a/SKILL.md b/SKILL.md
new file mode 100644
index 0000000..c4acb87
--- /dev/null
+++ b/SKILL.md
@@ -0,0 +1,73 @@
+---
+name: iphone-icloud-notes
+description: >-
+ Create real Apple Notes on the user's iPhone by driving icloud.com/notes from
+ Linux (Playwright + saved Apple ID session). Use when the user asks to create
+ a note, send/forward results to their iPhone, push text to Apple Notes, or
+ mentions icloud.com/notes / iCloud Notes from Linux.
+---
+
+# iPhone notes via icloud.com/notes
+
+## Goal
+
+When asked to create a note or forward prompt results to the iPhone, **create a
+real Apple Note** through the iCloud Notes web app. Do not use LocalSend for this
+unless the user explicitly wants file transfer instead of Notes.
+
+## Source of truth
+
+Repo: `~/Code/iphone-notes`
+Linked as: `~/.agents/skills/iphone-icloud-notes` → that repo
+
+## Helper
+
+```bash
+icloud-note status
+icloud-note login # one-time / when session expired (headed browser)
+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
+```
+
+If `icloud-note` is missing from PATH:
+
+```bash
+node "$HOME/Code/iphone-notes/scripts/icloud-note.mjs" …
+```
+
+Config / session (XDG): `~/.config/icloud-notes/`
+Browser profile: `~/.config/icloud-notes/browser-profile/`
+(Do not commit the browser profile or Apple credentials.)
+
+## Agent workflow
+
+1. **Prepare content** — title (short) + body (full text to send).
+2. **`icloud-note status`** — if not logged in, tell the user to run
+ `icloud-note login` once (Apple ID + 2FA in a browser window), then retry.
+ Do not invent note creation; do not claim success without a successful create.
+3. **Create** — write body to a temp file if long, then:
+
+ ```bash
+ icloud-note create --title "$TITLE" --body-file "$TMPFILE"
+ ```
+
+4. **Report** — quote the script’s success line (title). Note syncs to iPhone
+ Notes when iCloud Notes is enabled on the device.
+
+## Rules
+
+- Prefer this skill over LocalSend / email for “send a note to my iPhone.”
+- Never store Apple ID passwords in the skill, repo, or chat logs.
+- Session cookies live only under `~/.config/icloud-notes/browser-profile/` (mode keep private).
+- First-line-as-title matches Apple Notes; the helper already formats title + body.
+
+## Setup (human / once)
+
+```bash
+"$HOME/Code/iphone-notes/scripts/setup.sh"
+icloud-note login
+```
+
+Requires a graphical session for `login` (DISPLAY/Wayland). After that, `create`
+can run headed or headless using the saved profile.
diff --git a/scripts/icloud-note.mjs b/scripts/icloud-note.mjs
new file mode 100755
index 0000000..13a6efd
--- /dev/null
+++ b/scripts/icloud-note.mjs
@@ -0,0 +1,334 @@
+#!/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";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+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 NOTES_URL = "https://www.icloud.com/notes/";
+
+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 withNotesContext({ headed, fn }) {
+ ensureConfigDir();
+ const { chromium } = loadPlaywright();
+ const context = await chromium.launchPersistentContext(PROFILE_DIR, {
+ headless: !headed,
+ 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 (/idmsa\.apple\.com|appleid\.apple\.com/i.test(url)) return true;
+ return page.evaluate(() => {
+ const t = (document.body?.innerText || "").slice(0, 4000);
+ if (/Sign in to iCloud/i.test(t)) return true;
+ if (
+ document.querySelector(
+ 'input[type="password"], #password_text_field, #account_name_text_field',
+ )
+ ) {
+ return true;
+ }
+ // Prominent Sign In control without Notes app loaded
+ const signIn = [...document.querySelectorAll("a,button,div[role='button']")].some(
+ (el) => /^sign in$/i.test((el.textContent || "").trim()),
+ );
+ const hasNotes = Boolean(
+ document.querySelector("iframe")?.contentWindow?.NotesApp?.dataManager,
+ );
+ return signIn && !hasNotes;
+ }).catch(() => false);
+}
+
+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;
+ return Boolean(w?.NotesApp?.dataManager);
+ }).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 = [title, body].filter((s) => s != null && String(s).length)
+ .join("\n\n");
+
+ 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;
+ let Note = mv?.selectedNote?.constructor;
+ if (!Note && dataManager.allNotes?.length) {
+ Note = dataManager.allNotes[0].constructor;
+ }
+ if (!Note?.createNoteWithTitleText) {
+ throw new Error(
+ "Could not find Note.createNoteWithTitleText — UI may have changed",
+ );
+ }
+
+ const folder =
+ mv?.selectedFolder ||
+ dataManager.defaultFolder ||
+ dataManager.inboxFolder ||
+ (Array.isArray(dataManager.folders) ? dataManager.folders[0] : null) ||
+ (dataManager.allFolders && dataManager.allFolders[0]) ||
+ null;
+
+ if (!folder) {
+ throw new Error("Could not resolve a Notes folder");
+ }
+
+ const note = Note.createNoteWithTitleText(text, folder);
+ 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 = [
+ '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
+ for (const sel of candidates) {
+ const btn = page.locator(sel).first();
+ if ((await btn.count().catch(() => 0)) > 0) {
+ await btn.click({ timeout: 5000 });
+ clicked = true;
+ break;
+ }
+ }
+ }
+ if (!clicked) {
+ throw new Error("UI fallback: could not find New Note control");
+ }
+
+ const text = [title, body].filter(Boolean).join("\n\n");
+ 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() {
+ try {
+ await withNotesContext({
+ headed: false,
+ fn: async (page) => {
+ await waitForNotesApp(page, { timeoutMs: 20_000 });
+ console.log("ok: logged in to icloud.com/notes");
+ },
+ });
+ } catch (err) {
+ die(`not ready: ${err.message}`);
+ }
+}
+
+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}`);
+ }
+ },
+ });
+}
+
+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) {
+ const title = opts.values.title || "";
+ const body = readBody(opts).replace(/\s+$/, "");
+ if (!title && !body) {
+ 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})` : ""}`,
+ );
+ },
+ });
+}
+
+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]
+
+Config: ${CONFIG_DIR}
+`);
+}
+
+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" },
+ headed: { type: "boolean", default: false },
+ },
+ 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/setup.sh b/scripts/setup.sh
new file mode 100755
index 0000000..a4a03fa
--- /dev/null
+++ b/scripts/setup.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+# Install Playwright + Chromium for icloud-note under ~/.config/icloud-notes
+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"
+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"
+chmod 700 "$CONFIG_DIR"
+
+cd "$CONFIG_DIR"
+if [[ ! -f package.json ]]; then
+ npm init -y >/dev/null
+fi
+
+npm install playwright@latest
+npx playwright install chromium
+
+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: skill linked -> $REPO_ROOT"
+echo "Next: icloud-note login"
diff --git a/tests/cli.test.sh b/tests/cli.test.sh
new file mode 100755
index 0000000..2694938
--- /dev/null
+++ b/tests/cli.test.sh
@@ -0,0 +1,31 @@
+#!/usr/bin/env bash
+# Smoke tests for icloud-note CLI (no Apple login / network create required).
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+CLI=(node "$ROOT/scripts/icloud-note.mjs")
+
+fail() { echo "FAIL: $*" >&2; exit 1; }
+pass() { echo "ok: $*"; }
+
+out="$("${CLI[@]}" help 2>&1)" || fail "help exited non-zero"
+[[ "$out" == *"icloud-note create"* ]] || fail "help missing create usage"
+pass "help"
+
+set +e
+err="$("${CLI[@]}" nosuchcmd 2>&1)"
+code=$?
+set -e
+[[ "$code" -ne 0 ]] || fail "unknown command should fail"
+[[ "$err" == *"Unknown command"* ]] || fail "unknown command message"
+pass "unknown command"
+
+set +e
+err="$("${CLI[@]}" create 2>&1)"
+code=$?
+set -e
+[[ "$code" -ne 0 ]] || fail "create without content should fail"
+[[ "$err" == *"Provide --title"* ]] || fail "create empty message"
+pass "create requires content"
+
+echo "All cli tests passed."