1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
|
#!/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 STATE_PATH = path.join(CONFIG_DIR, "storage-state.json");
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 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 (/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;
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 = [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;
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 = [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 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 (!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) {
const title = opts.values.title || "";
const body = readBody(opts).replace(/\s+$/, "");
if (!title && !body) {
die("Provide --title and/or --body / --body-file / stdin");
}
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)));
|