diff options
| -rw-r--r-- | README.md | 12 | ||||
| -rw-r--r-- | SKILL.md | 2 | ||||
| -rw-r--r-- | package.json | 12 | ||||
| -rwxr-xr-x | scripts/icloud-note.mjs | 76 | ||||
| -rw-r--r-- | scripts/lib/note-helpers.mjs | 88 | ||||
| -rwxr-xr-x | tests/cli.test.sh | 82 | ||||
| -rwxr-xr-x | tests/conventional-commits.test.sh | 42 | ||||
| -rw-r--r-- | tests/helpers.test.mjs | 113 | ||||
| -rwxr-xr-x | tests/run.sh | 16 |
9 files changed, 414 insertions, 29 deletions
@@ -45,9 +45,19 @@ Runtime config (not in git): ## Tests ```bash -./tests/cli.test.sh +npm test +# or +./tests/run.sh ``` +Covers: + +- Pure helpers (`tests/helpers.test.mjs`) — note formatting, auth heuristics, argv, Conventional Commits subjects +- CLI dry-run (`tests/cli.test.sh`) — help, create/status/login without a browser (`ICLOUD_NOTES_DRY_RUN=1`) +- Git history (`tests/conventional-commits.test.sh`) — every commit subject matches Conventional Commits 1.0.0 + +Live Apple create/status (real headless Chromium) is manual after `icloud-note login`. + ## License MIT @@ -33,6 +33,8 @@ 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. +Do **not** set `ICLOUD_NOTES_DRY_RUN=1` for real sends (tests only). + If `icloud-note` is missing from PATH: ```bash diff --git a/package.json b/package.json new file mode 100644 index 0000000..0b3f513 --- /dev/null +++ b/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/scripts/icloud-note.mjs b/scripts/icloud-note.mjs index 30c3b83..aa42e95 100755 --- a/scripts/icloud-note.mjs +++ b/scripts/icloud-note.mjs @@ -10,14 +10,21 @@ 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 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 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); @@ -113,26 +120,23 @@ async function withLoginBrowser(fn) { async function pageLooksLoggedOut(page) { const url = page.url(); - if (/idmsa\.apple\.com|appleid\.apple\.com/i.test(url)) return true; - return page.evaluate(() => { + if (isAppleAuthUrl(url)) return true; + const signals = await page.evaluate(() => { const t = (document.body?.innerText || "").slice(0, 4000); - if (/Sign in to iCloud/i.test(t)) return true; - if ( + const hasPasswordField = Boolean( 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( + ), + ); + const hasSignInControl = [...document.querySelectorAll("a,button,div[role='button']")].some( (el) => /^sign in$/i.test((el.textContent || "").trim()), ); - const hasNotes = Boolean( + const hasNotesApp = Boolean( document.querySelector("iframe")?.contentWindow?.NotesApp?.dataManager, ); - return signIn && !hasNotes; - }).catch(() => false); + return { bodyText: t, hasPasswordField, hasSignInControl, hasNotesApp }; + }).catch(() => ({})); + return looksLoggedOut({ url, ...signals }); } async function waitForNotesApp(page, { timeoutMs = 120_000, allowLoginWait = false } = {}) { @@ -170,8 +174,7 @@ async function waitForNotesApp(page, { timeoutMs = 120_000, allowLoginWait = fal } async function createViaNotesApp(page, title, body) { - const fullText = [title, body].filter((s) => s != null && String(s).length) - .join("\n\n"); + const fullText = formatNoteText(title, body); return page.evaluate(async (text) => { const iframe = document.querySelector("iframe"); @@ -260,7 +263,7 @@ async function createViaUiFallback(page, title, body) { throw new Error("UI fallback: could not find New Note control"); } - const text = [title, body].filter(Boolean).join("\n\n"); + const text = formatNoteText(title, body); const editable = page .frameLocator("iframe") .locator('[contenteditable="true"], [role="textbox"]') @@ -272,6 +275,13 @@ async function createViaUiFallback(page, title, body) { } 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 }); @@ -283,6 +293,9 @@ async function cmdStatus() { } 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)."); } @@ -321,10 +334,23 @@ function readBody(opts) { } 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"); + 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) => { diff --git a/scripts/lib/note-helpers.mjs b/scripts/lib/note-helpers.mjs new file mode 100644 index 0000000..5dd43a0 --- /dev/null +++ b/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/tests/cli.test.sh b/tests/cli.test.sh index aefb371..d3f8d88 100755 --- a/tests/cli.test.sh +++ b/tests/cli.test.sh @@ -1,19 +1,29 @@ #!/usr/bin/env bash -# Smoke tests for icloud-note CLI (no Apple login / network create required). +# CLI smoke + dry-run tests (no Apple network / no visible browser). set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" CLI=(node "$ROOT/scripts/icloud-note.mjs") +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT +export ICLOUD_NOTES_CONFIG="$TMP/cfg" +export ICLOUD_NOTES_DRY_RUN=1 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" +# --- help --- +for flag in help -h --help; do + out="$("${CLI[@]}" "$flag" 2>&1)" || fail "help ($flag) exited non-zero" + [[ "$out" == *"icloud-note create"* ]] || fail "help missing create ($flag)" +done +out="$("${CLI[@]}" help 2>&1)" [[ "$out" == *"headless"* ]] || fail "help should say create/status are headless" [[ "$out" != *"--headed"* ]] || fail "help must not advertise --headed" +[[ "$out" == *"$ICLOUD_NOTES_CONFIG"* ]] || fail "help should show ICLOUD_NOTES_CONFIG path" pass "help" +# --- unknown --- set +e err="$("${CLI[@]}" nosuchcmd 2>&1)" code=$? @@ -22,6 +32,7 @@ set -e [[ "$err" == *"Unknown command"* ]] || fail "unknown command message" pass "unknown command" +# --- create validation --- set +e err="$("${CLI[@]}" create 2>&1)" code=$? @@ -30,4 +41,69 @@ set -e [[ "$err" == *"Provide --title"* ]] || fail "create empty message" pass "create requires content" +# --- create dry-run (no browser) --- +out="$("${CLI[@]}" create --title "T" --body "hello" 2>&1)" || fail "create dry-run failed" +[[ "$out" == *'dry-run: would create note title="T"'* ]] || fail "create dry-run output: $out" +[[ "$out" == *"chars="* ]] || fail "create dry-run missing chars" +pass "create dry-run --title/--body" + +printf 'from file\n' > "$TMP/body.txt" +out="$("${CLI[@]}" create --title "FileNote" --body-file "$TMP/body.txt" 2>&1)" \ + || fail "create body-file failed" +[[ "$out" == *'title="FileNote"'* ]] || fail "body-file title: $out" +pass "create --body-file" + +out="$(printf 'stdin body' | "${CLI[@]}" create --title "Stdin" --body-file - 2>&1)" \ + || fail "create stdin body-file failed" +[[ "$out" == *'title="Stdin"'* ]] || fail "stdin title: $out" +pass "create --body-file -" + +out="$("${CLI[@]}" create "Positional" --body "x" 2>&1)" || fail "positional create failed" +[[ "$out" == *'title="Positional"'* ]] || fail "positional title: $out" +pass "create positional title" + +# --- status dry-run without session --- +set +e +err="$("${CLI[@]}" status 2>&1)" +code=$? +set -e +[[ "$code" -ne 0 ]] || fail "status without session should fail" +[[ "$err" == *"No saved session"* ]] || fail "status empty message: $err" +pass "status dry-run without session" + +mkdir -p "$ICLOUD_NOTES_CONFIG" +echo '{"cookies":[]}' > "$ICLOUD_NOTES_CONFIG/storage-state.json" +out="$("${CLI[@]}" status 2>&1)" || fail "status dry-run with state failed" +[[ "$out" == *"dry-run status"* ]] || fail "status dry-run ok: $out" +pass "status dry-run with session file" + +# --- login dry-run must not open a browser --- +set +e +err="$("${CLI[@]}" login 2>&1)" +code=$? +set -e +[[ "$code" -ne 0 ]] || fail "login dry-run should refuse" +[[ "$err" == *"dry-run"* ]] || fail "login dry-run message: $err" +pass "login dry-run refuses browser" + +# --- login without display (real path, no dry-run) --- +unset ICLOUD_NOTES_DRY_RUN +set +e +err="$(env -u DISPLAY -u WAYLAND_DISPLAY ICLOUD_NOTES_CONFIG="$ICLOUD_NOTES_CONFIG" \ + "${CLI[@]}" login 2>&1)" +code=$? +set -e +[[ "$code" -ne 0 ]] || fail "login without DISPLAY should fail" +[[ "$err" == *"graphical session"* ]] || fail "login DISPLAY message: $err" +pass "login requires graphical session" + +# --- setup script present --- +[[ -x "$ROOT/scripts/setup.sh" ]] || fail "setup.sh not executable" +pass "setup.sh executable" + +# --- skill / docs mention headless --- +rg -q 'headless' "$ROOT/SKILL.md" || fail "SKILL.md should mention headless" +rg -q 'headless' "$ROOT/README.md" || fail "README.md should mention headless" +pass "docs mention headless" + echo "All cli tests passed." diff --git a/tests/conventional-commits.test.sh b/tests/conventional-commits.test.sh new file mode 100755 index 0000000..042b819 --- /dev/null +++ b/tests/conventional-commits.test.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Enforce Conventional Commits 1.0.0 on every commit subject in this repo. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +fail() { echo "FAIL: $*" >&2; exit 1; } +pass() { echo "ok: $*"; } + +# Same rule as scripts/lib/note-helpers.mjs isConventionalCommitSubject +RE='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-zA-Z0-9._/-]+\))?!?: .+' + +mapfile -t SUBJECTS < <(git log --format=%s) +[[ "${#SUBJECTS[@]}" -gt 0 ]] || fail "no commits" + +bad=0 +for s in "${SUBJECTS[@]}"; do + if [[ ! "$s" =~ $RE ]]; then + echo "non-conventional: $s" >&2 + bad=1 + else + pass "commit: $s" + fi +done +[[ "$bad" -eq 0 ]] || fail "one or more commits are not Conventional Commits" + +# Unit helper agrees with git history +node --input-type=module -e ' +import { isConventionalCommitSubject } from "./scripts/lib/note-helpers.mjs"; +import { execSync } from "node:child_process"; +const subjects = execSync("git log --format=%s", { encoding: "utf8" }) + .trim().split("\n").filter(Boolean); +for (const s of subjects) { + if (!isConventionalCommitSubject(s)) { + console.error("helper rejected:", s); + process.exit(1); + } +} +' + +echo "All conventional-commit checks passed." diff --git a/tests/helpers.test.mjs b/tests/helpers.test.mjs new file mode 100644 index 0000000..38742d8 --- /dev/null +++ b/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); + }); +}); diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..6d845df --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Full test suite for iphone-notes. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +echo "== helpers (node:test) ==" +node --test tests/helpers.test.mjs + +echo "== cli ==" +./tests/cli.test.sh + +echo "== conventional commits ==" +./tests/conventional-commits.test.sh + +echo "All tests passed." |
