onenote-cli 0.2.1-win32-arm64 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +10 -0
- package/.gitattributes +7 -0
- package/.github/workflows/release.yml +170 -0
- package/.github/workflows/rust-npm-release.yml +109 -0
- package/.husky/pre-commit +1 -0
- package/.releaserc.json +15 -0
- package/.secretlintrc.json +3 -0
- package/CLAUDE.md +42 -0
- package/README.md +267 -0
- package/SKILL.md +77 -0
- package/docs/azure-app-registration.md +80 -0
- package/docs/development-notes.md +84 -0
- package/docs/graph-api-endpoints.md +131 -0
- package/docs/local-search-architecture.md +132 -0
- package/docs/onen0te-cli-analysis.md +130 -0
- package/docs/setup.md +141 -0
- package/docs/zhihu-intro.md +92 -0
- package/package.json +46 -12
- package/rustify/onenote +556 -0
- package/rustify/onenote-cli +556 -0
- package/rustify/package.json +3 -0
- package/src/auth.ts +359 -0
- package/src/cache.ts +1709 -0
- package/src/debug-tags.ts +207 -0
- package/src/export.ts +367 -0
- package/src/graph.ts +1480 -0
- package/src/index.ts +1176 -0
- package/src/markdown.ts +134 -0
- package/src/read-render.ts +621 -0
- package/src/sync-ui.tsx +220 -0
- package/tsconfig.json +16 -0
- package/bin/onenote-cli.exe +0 -0
package/src/auth.ts
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PublicClientApplication,
|
|
3
|
+
type DeviceCodeRequest,
|
|
4
|
+
type AuthenticationResult,
|
|
5
|
+
type AccountInfo,
|
|
6
|
+
CryptoProvider,
|
|
7
|
+
} from "@azure/msal-node";
|
|
8
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
9
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
10
|
+
import { join, dirname } from "node:path";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
|
|
13
|
+
// Auto-load .env.local from the package root (one level up from src/) when
|
|
14
|
+
// running from a different working directory.
|
|
15
|
+
function autoLoadEnv() {
|
|
16
|
+
const packageRoot = dirname(import.meta.dir);
|
|
17
|
+
for (const name of [".env.local", ".env"]) {
|
|
18
|
+
const path = join(packageRoot, name);
|
|
19
|
+
if (!existsSync(path)) continue;
|
|
20
|
+
try {
|
|
21
|
+
const content = readFileSync(path, "utf-8");
|
|
22
|
+
for (const line of content.split(/\r?\n/)) {
|
|
23
|
+
const m = line.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)\s*$/);
|
|
24
|
+
if (!m) continue;
|
|
25
|
+
const key = m[1];
|
|
26
|
+
let val = m[2];
|
|
27
|
+
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
|
|
28
|
+
val = val.slice(1, -1);
|
|
29
|
+
}
|
|
30
|
+
if (process.env[key] === undefined) process.env[key] = val;
|
|
31
|
+
}
|
|
32
|
+
} catch {}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
autoLoadEnv();
|
|
36
|
+
|
|
37
|
+
const CACHE_PATH = join(homedir(), ".onenote-cli", "msal-cache.json");
|
|
38
|
+
const CONFIG_PATH = join(homedir(), ".onenote-cli", "config.json");
|
|
39
|
+
|
|
40
|
+
const SCOPES = [
|
|
41
|
+
"Notes.Read", "Notes.ReadWrite", "Notes.Read.All", "Notes.ReadWrite.All",
|
|
42
|
+
"Files.Read", "Files.Read.All", "Files.ReadWrite", "Files.ReadWrite.All",
|
|
43
|
+
"Sites.Read.All",
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
interface AppConfig {
|
|
47
|
+
clientId: string;
|
|
48
|
+
authority: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const DEFAULT_CONFIG: AppConfig = {
|
|
52
|
+
clientId: "YOUR_CLIENT_ID",
|
|
53
|
+
authority: "https://login.microsoftonline.com/common",
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
async function ensureDir(path: string) {
|
|
57
|
+
const dir = path.substring(0, path.lastIndexOf("/"));
|
|
58
|
+
await Bun.write(join(dir, ".keep"), "");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function loadConfig(): Promise<AppConfig> {
|
|
62
|
+
const envClientId = process.env.ONENOTE_CLIENT_ID;
|
|
63
|
+
const envAuthority = process.env.ONENOTE_AUTHORITY;
|
|
64
|
+
if (envClientId && envClientId !== "YOUR_CLIENT_ID") {
|
|
65
|
+
return {
|
|
66
|
+
clientId: envClientId,
|
|
67
|
+
authority: envAuthority || DEFAULT_CONFIG.authority,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const raw = await readFile(CONFIG_PATH, "utf-8");
|
|
73
|
+
return JSON.parse(raw) as AppConfig;
|
|
74
|
+
} catch {
|
|
75
|
+
await ensureDir(CONFIG_PATH);
|
|
76
|
+
await writeFile(CONFIG_PATH, JSON.stringify(DEFAULT_CONFIG, null, 2));
|
|
77
|
+
return DEFAULT_CONFIG;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function createPca(): Promise<PublicClientApplication> {
|
|
82
|
+
const config = await loadConfig();
|
|
83
|
+
if (config.clientId === "YOUR_CLIENT_ID") {
|
|
84
|
+
console.error(
|
|
85
|
+
`Please configure your Azure AD app credentials in:\n ${CONFIG_PATH}\n\n` +
|
|
86
|
+
"To register an app:\n" +
|
|
87
|
+
" 1. Go to https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps\n" +
|
|
88
|
+
" 2. New registration -> Name: onenote-cli, Supported account types: Personal + Org\n" +
|
|
89
|
+
" 3. Set platform to 'Mobile and desktop applications'\n" +
|
|
90
|
+
" 4. Copy the Application (client) ID into config.json\n"
|
|
91
|
+
);
|
|
92
|
+
process.exit(1);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const pca = new PublicClientApplication({
|
|
96
|
+
auth: {
|
|
97
|
+
clientId: config.clientId,
|
|
98
|
+
authority: config.authority,
|
|
99
|
+
},
|
|
100
|
+
cache: {
|
|
101
|
+
cachePlugin: {
|
|
102
|
+
beforeCacheAccess: async (ctx) => {
|
|
103
|
+
try {
|
|
104
|
+
const data = await readFile(CACHE_PATH, "utf-8");
|
|
105
|
+
ctx.tokenCache.deserialize(data);
|
|
106
|
+
} catch {
|
|
107
|
+
// no cache yet
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
afterCacheAccess: async (ctx) => {
|
|
111
|
+
if (ctx.cacheHasChanged) {
|
|
112
|
+
await ensureDir(CACHE_PATH);
|
|
113
|
+
await writeFile(CACHE_PATH, ctx.tokenCache.serialize());
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
return pca;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function listAccounts(): Promise<AccountInfo[]> {
|
|
124
|
+
const pca = await createPca();
|
|
125
|
+
return pca.getTokenCache().getAllAccounts() as Promise<AccountInfo[]>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Module-level "current" account used by getAccessToken when no account is passed.
|
|
129
|
+
// syncCache sets this to loop over each cached account.
|
|
130
|
+
let currentAccount: AccountInfo | undefined;
|
|
131
|
+
export function setCurrentAccount(account: AccountInfo | undefined): void {
|
|
132
|
+
currentAccount = account;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function deviceCodeFlow(pca: PublicClientApplication): Promise<AuthenticationResult> {
|
|
136
|
+
const request: DeviceCodeRequest = {
|
|
137
|
+
scopes: SCOPES,
|
|
138
|
+
deviceCodeCallback: async (response) => {
|
|
139
|
+
console.error(response.message);
|
|
140
|
+
// Auto-copy code to clipboard for convenience
|
|
141
|
+
try {
|
|
142
|
+
const clipboardy = await import("clipboardy");
|
|
143
|
+
await clipboardy.default.write(response.userCode);
|
|
144
|
+
console.error(`(Code "${response.userCode}" copied to clipboard)`);
|
|
145
|
+
} catch {}
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
const result = await pca.acquireTokenByDeviceCode(request);
|
|
149
|
+
if (!result) throw new Error("Authentication failed");
|
|
150
|
+
return result;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Extract the auth code (and state) from a pasted redirect URL or its query string. */
|
|
154
|
+
function parseRedirectInput(input: string): { code?: string; state?: string; error?: string } {
|
|
155
|
+
const text = input.trim();
|
|
156
|
+
if (!text) return {};
|
|
157
|
+
if (!text.includes("code=") && !text.includes("error=")) return {};
|
|
158
|
+
const query = text.includes("?") ? text.slice(text.indexOf("?") + 1) : text;
|
|
159
|
+
const params = new URLSearchParams(query.split("#")[0]);
|
|
160
|
+
const error = params.get("error");
|
|
161
|
+
if (error) return { error: `${error}: ${params.get("error_description") ?? ""}`.trim() };
|
|
162
|
+
return { code: params.get("code") ?? undefined, state: params.get("state") ?? undefined };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const page = (title: string, body: string) =>
|
|
166
|
+
"<html><body style='font-family:system-ui;padding:40px;text-align:center'>" +
|
|
167
|
+
`<h2>${title}</h2><p>${body}</p></body></html>`;
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Interactive auth via loopback redirect (PKCE). Starts a local server on a free port and opens
|
|
171
|
+
* the browser to the Microsoft sign-in URL with redirect_uri=http://localhost:PORT.
|
|
172
|
+
*
|
|
173
|
+
* When the CLI runs on a remote host (VPS/SSH) but the browser is on your desktop, the redirect
|
|
174
|
+
* to localhost fails to load — in that case paste the redirect URL from the address bar into the
|
|
175
|
+
* terminal. Whichever arrives first (loopback or paste) completes the sign-in.
|
|
176
|
+
*/
|
|
177
|
+
async function interactiveFlow(pca: PublicClientApplication): Promise<AuthenticationResult> {
|
|
178
|
+
const crypto = new CryptoProvider();
|
|
179
|
+
const { verifier, challenge } = await crypto.generatePkceCodes();
|
|
180
|
+
const expectedState = crypto.createNewGuid();
|
|
181
|
+
|
|
182
|
+
let settle!: (r: { code?: string; state?: string; error?: string }) => void;
|
|
183
|
+
const received = new Promise<{ code?: string; state?: string; error?: string }>((r) => (settle = r));
|
|
184
|
+
|
|
185
|
+
const server = Bun.serve({
|
|
186
|
+
hostname: "localhost",
|
|
187
|
+
port: 0,
|
|
188
|
+
fetch(req) {
|
|
189
|
+
const url = new URL(req.url);
|
|
190
|
+
if (url.pathname !== "/") return new Response("Not found", { status: 404 });
|
|
191
|
+
const parsed = parseRedirectInput(url.search);
|
|
192
|
+
if (!parsed.code && !parsed.error) return new Response("Waiting for sign-in...");
|
|
193
|
+
// Defer so this response is flushed before the CLI proceeds (and possibly exits on error).
|
|
194
|
+
setTimeout(() => settle(parsed), 50);
|
|
195
|
+
const ok = !!parsed.code;
|
|
196
|
+
return new Response(
|
|
197
|
+
ok
|
|
198
|
+
? page("Signed in successfully", "You can close this tab and return to the terminal.")
|
|
199
|
+
: page("Sign-in failed", "Please return to the terminal and try again."),
|
|
200
|
+
{ headers: { "Content-Type": "text/html; charset=utf-8" } },
|
|
201
|
+
);
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
const redirectUri = `http://localhost:${server.port}`;
|
|
205
|
+
|
|
206
|
+
const { createInterface } = await import("node:readline");
|
|
207
|
+
const rl = createInterface({ input: process.stdin, terminal: false });
|
|
208
|
+
rl.on("line", (line) => {
|
|
209
|
+
const parsed = parseRedirectInput(line);
|
|
210
|
+
if (parsed.code || parsed.error) settle(parsed);
|
|
211
|
+
else if (line.trim()) console.error("Couldn't find a code in that input — paste the full redirect URL.");
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
try {
|
|
215
|
+
const authUrl = await pca.getAuthCodeUrl({
|
|
216
|
+
scopes: SCOPES,
|
|
217
|
+
redirectUri,
|
|
218
|
+
codeChallenge: challenge,
|
|
219
|
+
codeChallengeMethod: "S256",
|
|
220
|
+
state: expectedState,
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
|
|
224
|
+
try {
|
|
225
|
+
const { spawn } = await import("node:child_process");
|
|
226
|
+
spawn(cmd, [authUrl], { stdio: "ignore", detached: true }).on("error", () => {}).unref();
|
|
227
|
+
} catch {}
|
|
228
|
+
console.error(
|
|
229
|
+
`\nIf your browser didn't open, visit:\n ${authUrl}\n\n` +
|
|
230
|
+
`After signing in you'll be redirected to ${redirectUri}/?code=...\n` +
|
|
231
|
+
"If that page fails to load (e.g. the CLI runs on a remote server / VPS),\n" +
|
|
232
|
+
"copy the full URL from the browser's address bar and paste it here, then press Enter:",
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
const { code, state, error } = await received;
|
|
236
|
+
if (error) throw new Error(`Sign-in failed — ${error}`);
|
|
237
|
+
if (state && state !== expectedState) throw new Error("Sign-in failed — state mismatch (stale or foreign redirect URL)");
|
|
238
|
+
const result = await pca.acquireTokenByCode({ code: code!, scopes: SCOPES, redirectUri, codeVerifier: verifier });
|
|
239
|
+
if (!result) throw new Error("Authentication failed");
|
|
240
|
+
return result;
|
|
241
|
+
} finally {
|
|
242
|
+
rl.close();
|
|
243
|
+
process.stdin.pause();
|
|
244
|
+
server.stop();
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Add a new account via interactive browser auth. */
|
|
249
|
+
export async function login(): Promise<string> {
|
|
250
|
+
const config = await loadConfig();
|
|
251
|
+
if (config.clientId === "YOUR_CLIENT_ID") {
|
|
252
|
+
console.error(`Please configure your Azure AD app credentials in:\n ${CONFIG_PATH}`);
|
|
253
|
+
process.exit(1);
|
|
254
|
+
}
|
|
255
|
+
// No cachePlugin: prevents silent reuse of an existing cached token
|
|
256
|
+
const freshPca = new PublicClientApplication({
|
|
257
|
+
auth: { clientId: config.clientId, authority: config.authority },
|
|
258
|
+
});
|
|
259
|
+
console.error("Opening browser for sign-in...");
|
|
260
|
+
const result = await interactiveFlow(freshPca);
|
|
261
|
+
|
|
262
|
+
// Merge new account's tokens into the shared on-disk cache
|
|
263
|
+
const newTokens = JSON.parse(freshPca.getTokenCache().serialize()) as Record<string, Record<string, unknown>>;
|
|
264
|
+
let existing: Record<string, Record<string, unknown>> = {};
|
|
265
|
+
try {
|
|
266
|
+
existing = JSON.parse(await readFile(CACHE_PATH, "utf-8"));
|
|
267
|
+
} catch {}
|
|
268
|
+
const merged = { ...existing };
|
|
269
|
+
for (const [section, entries] of Object.entries(newTokens)) {
|
|
270
|
+
merged[section] = { ...merged[section], ...entries };
|
|
271
|
+
}
|
|
272
|
+
await ensureDir(CACHE_PATH);
|
|
273
|
+
await writeFile(CACHE_PATH, JSON.stringify(merged));
|
|
274
|
+
return result.account?.username ?? "(unknown)";
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Get an access token silently for the given account (or module-level currentAccount, or first cached account). */
|
|
278
|
+
export async function getAccessToken(account?: AccountInfo): Promise<string> {
|
|
279
|
+
const pca = await createPca();
|
|
280
|
+
const accounts = await pca.getTokenCache().getAllAccounts() as AccountInfo[];
|
|
281
|
+
|
|
282
|
+
// Resolve: explicit > module-level current > match by homeAccountId > first
|
|
283
|
+
let target = account ?? currentAccount;
|
|
284
|
+
if (target) {
|
|
285
|
+
// Re-fetch from the shared cache to ensure we have the latest state
|
|
286
|
+
target = accounts.find((a) => a.homeAccountId === target!.homeAccountId) ?? target;
|
|
287
|
+
} else {
|
|
288
|
+
target = accounts[0];
|
|
289
|
+
}
|
|
290
|
+
if (target) {
|
|
291
|
+
try {
|
|
292
|
+
const result = await pca.acquireTokenSilent({ account: target, scopes: SCOPES });
|
|
293
|
+
return result.accessToken;
|
|
294
|
+
} catch {
|
|
295
|
+
// silent failed — fall through to device code for this account
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// No cached account or silent refresh failed
|
|
300
|
+
const result = await deviceCodeFlow(pca);
|
|
301
|
+
return result.accessToken;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export async function logout(email?: string): Promise<void> {
|
|
305
|
+
const pca = await createPca();
|
|
306
|
+
const accounts = await pca.getTokenCache().getAllAccounts() as AccountInfo[];
|
|
307
|
+
|
|
308
|
+
// Option C: 1 account → logout that one; multiple + no email → show list
|
|
309
|
+
if (!email) {
|
|
310
|
+
if (accounts.length === 0) {
|
|
311
|
+
console.log("Already logged out (no cached tokens).");
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (accounts.length === 1) {
|
|
315
|
+
email = accounts[0].username;
|
|
316
|
+
} else {
|
|
317
|
+
console.log("Multiple accounts found. Specify one or use --all:");
|
|
318
|
+
for (const a of accounts) {
|
|
319
|
+
console.log(` ${a.username}`);
|
|
320
|
+
}
|
|
321
|
+
console.log("\nExample: onenote auth logout snomiao@snomiao.com");
|
|
322
|
+
console.log(" onenote auth logout --all");
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const target = accounts.find((a) => a.username?.toLowerCase() === email!.toLowerCase());
|
|
328
|
+
if (!target) {
|
|
329
|
+
console.log(`Account '${email}' not found. Logged-in accounts:`);
|
|
330
|
+
for (const a of accounts) console.log(` ${a.username}`);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
await pca.getTokenCache().removeAccount(target);
|
|
335
|
+
console.log(`Logged out ${target.username}.`);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export async function logoutAll(): Promise<void> {
|
|
339
|
+
try {
|
|
340
|
+
const { unlink } = await import("node:fs/promises");
|
|
341
|
+
await unlink(CACHE_PATH);
|
|
342
|
+
console.log("Logged out all accounts. Token cache removed.");
|
|
343
|
+
} catch {
|
|
344
|
+
console.log("Already logged out (no cached tokens).");
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export async function whoami(): Promise<void> {
|
|
349
|
+
const pca = await createPca();
|
|
350
|
+
const accounts = await pca.getTokenCache().getAllAccounts() as AccountInfo[];
|
|
351
|
+
if (accounts.length === 0) {
|
|
352
|
+
console.log("Not logged in. Run `onenote auth login` to authenticate.");
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
for (const account of accounts) {
|
|
356
|
+
console.log(`${account.username} (${account.name ?? ""})`);
|
|
357
|
+
console.log(` tenant: ${account.tenantId ?? "unknown"} env: ${account.environment ?? "unknown"}`);
|
|
358
|
+
}
|
|
359
|
+
}
|