onenote-cli 0.2.0 → 0.2.1-darwin-arm64
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/bin/onenote-cli +0 -0
- package/package.json +12 -44
- package/.env.example +0 -10
- package/.github/workflows/release.yml +0 -43
- package/.husky/pre-commit +0 -1
- package/.releaserc.json +0 -13
- package/.secretlintrc.json +0 -3
- package/CLAUDE.md +0 -42
- package/README.md +0 -254
- package/SKILL.md +0 -77
- package/bun.lock +0 -1427
- package/docs/azure-app-registration.md +0 -80
- package/docs/development-notes.md +0 -84
- package/docs/graph-api-endpoints.md +0 -131
- package/docs/local-search-architecture.md +0 -132
- package/docs/onen0te-cli-analysis.md +0 -130
- package/docs/setup.md +0 -141
- package/docs/zhihu-intro.md +0 -92
- package/src/auth.ts +0 -359
- package/src/cache.ts +0 -1709
- package/src/debug-tags.ts +0 -207
- package/src/export.ts +0 -367
- package/src/graph.ts +0 -1480
- package/src/index.ts +0 -1176
- package/src/markdown.ts +0 -134
- package/src/read-render.ts +0 -621
- package/src/sync-ui.tsx +0 -220
- package/tsconfig.json +0 -16
package/docs/setup.md
DELETED
|
@@ -1,141 +0,0 @@
|
|
|
1
|
-
# onenote-cli Authentication Setup Guide
|
|
2
|
-
|
|
3
|
-
This guide walks you through setting up Azure AD authentication for `onenote-cli` to access Microsoft OneNote via the Graph API.
|
|
4
|
-
|
|
5
|
-
## Prerequisites
|
|
6
|
-
|
|
7
|
-
- A Microsoft account (personal or organizational)
|
|
8
|
-
- An Azure account with an active subscription — [create one for free](https://azure.microsoft.com/pricing/purchase-options/azure-account)
|
|
9
|
-
- [Bun](https://bun.sh) runtime installed
|
|
10
|
-
|
|
11
|
-
## Step 1: Register an Azure AD Application
|
|
12
|
-
|
|
13
|
-
1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com)
|
|
14
|
-
2. Navigate to **Entra ID** > **App registrations** > **New registration**
|
|
15
|
-
3. Fill in the registration form:
|
|
16
|
-
- **Name**: `onenote-cli`
|
|
17
|
-
- **Supported account types**: Select **"Accounts in any organizational directory and personal Microsoft accounts"**
|
|
18
|
-
(This allows both work/school and personal Microsoft accounts)
|
|
19
|
-
- **Redirect URI**: Leave blank for now
|
|
20
|
-
4. Click **Register**
|
|
21
|
-
5. On the Overview page, copy the **Application (client) ID** — you will need this
|
|
22
|
-
|
|
23
|
-
## Step 2: Configure Platform for Device Code Flow
|
|
24
|
-
|
|
25
|
-
1. In your app registration, go to **Authentication** > **Add a platform**
|
|
26
|
-
2. Select **Mobile and desktop applications**
|
|
27
|
-
3. Check the box for `https://login.microsoftonline.com/common/oauth2/nativeclient`
|
|
28
|
-
4. Click **Configure**
|
|
29
|
-
5. Scroll down and set **Allow public client flows** to **Yes**
|
|
30
|
-
6. Click **Save**
|
|
31
|
-
|
|
32
|
-
> Device code flow requires "Allow public client flows" to be enabled. Without this, authentication will fail.
|
|
33
|
-
|
|
34
|
-
## Step 3: Configure API Permissions
|
|
35
|
-
|
|
36
|
-
1. In your app registration, go to **API permissions** > **Add a permission**
|
|
37
|
-
2. Select **Microsoft Graph** > **Delegated permissions**
|
|
38
|
-
3. Search and add the following permissions:
|
|
39
|
-
- `Notes.Read` — Read user OneNote notebooks
|
|
40
|
-
- `Notes.ReadWrite` — Read and write user OneNote notebooks
|
|
41
|
-
- `Notes.Read.All` — Read all notebooks the user can access
|
|
42
|
-
- `Notes.ReadWrite.All` — Read and write all notebooks the user can access
|
|
43
|
-
4. Click **Add permissions**
|
|
44
|
-
|
|
45
|
-
> For organizational accounts, an admin may need to **Grant admin consent** for these permissions.
|
|
46
|
-
|
|
47
|
-
## Step 4: Configure onenote-cli
|
|
48
|
-
|
|
49
|
-
You have two options to provide credentials:
|
|
50
|
-
|
|
51
|
-
### Option A: Environment variables (recommended)
|
|
52
|
-
|
|
53
|
-
Copy `.env.example` to `.env.local` and fill in your client ID:
|
|
54
|
-
|
|
55
|
-
```bash
|
|
56
|
-
cp .env.example .env.local
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
Edit `.env.local`:
|
|
60
|
-
|
|
61
|
-
```env
|
|
62
|
-
ONENOTE_CLIENT_ID=your-actual-client-id-here
|
|
63
|
-
ONENOTE_AUTHORITY=https://login.microsoftonline.com/common
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
### Option B: Config file
|
|
67
|
-
|
|
68
|
-
The CLI also reads from `~/.onenote-cli/config.json`. This file is auto-created on first run:
|
|
69
|
-
|
|
70
|
-
```json
|
|
71
|
-
{
|
|
72
|
-
"clientId": "your-actual-client-id-here",
|
|
73
|
-
"authority": "https://login.microsoftonline.com/common"
|
|
74
|
-
}
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
> Environment variables take priority over the config file.
|
|
78
|
-
|
|
79
|
-
## Step 5: Login
|
|
80
|
-
|
|
81
|
-
```bash
|
|
82
|
-
bun run src/index.ts login
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
This initiates the **device code flow**:
|
|
86
|
-
|
|
87
|
-
1. The CLI prints a URL and a code
|
|
88
|
-
2. Open the URL in your browser
|
|
89
|
-
3. Enter the code and sign in with your Microsoft account
|
|
90
|
-
4. Grant the requested permissions
|
|
91
|
-
5. Return to the terminal — you should see "Login successful!"
|
|
92
|
-
|
|
93
|
-
Tokens are cached at `~/.onenote-cli/msal-cache.json` so you don't need to login every time.
|
|
94
|
-
|
|
95
|
-
## Step 6: Verify
|
|
96
|
-
|
|
97
|
-
```bash
|
|
98
|
-
# List your notebooks
|
|
99
|
-
bun run src/index.ts notebooks list
|
|
100
|
-
|
|
101
|
-
# List all sections
|
|
102
|
-
bun run src/index.ts sections list
|
|
103
|
-
|
|
104
|
-
# List pages
|
|
105
|
-
bun run src/index.ts pages list
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
## Authority URL Reference
|
|
109
|
-
|
|
110
|
-
| Scenario | Authority URL |
|
|
111
|
-
|---|---|
|
|
112
|
-
| Multi-tenant + personal accounts | `https://login.microsoftonline.com/common` |
|
|
113
|
-
| Organizational accounts only (any tenant) | `https://login.microsoftonline.com/organizations` |
|
|
114
|
-
| Personal Microsoft accounts only | `https://login.microsoftonline.com/consumers` |
|
|
115
|
-
| Single tenant only | `https://login.microsoftonline.com/{tenant-id}` |
|
|
116
|
-
|
|
117
|
-
## Logout
|
|
118
|
-
|
|
119
|
-
To clear cached tokens:
|
|
120
|
-
|
|
121
|
-
```bash
|
|
122
|
-
bun run src/index.ts logout
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
## Troubleshooting
|
|
126
|
-
|
|
127
|
-
### "AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'"
|
|
128
|
-
|
|
129
|
-
→ Make sure **Allow public client flows** is set to **Yes** in your app's Authentication settings.
|
|
130
|
-
|
|
131
|
-
### "AADSTS65001: The user or administrator has not consented to use the application"
|
|
132
|
-
|
|
133
|
-
→ An admin needs to grant consent for the API permissions, or the user needs to consent during login.
|
|
134
|
-
|
|
135
|
-
### "AADSTS700016: Application with identifier '...' was not found"
|
|
136
|
-
|
|
137
|
-
→ Double-check that your `ONENOTE_CLIENT_ID` matches the Application (client) ID from Azure portal.
|
|
138
|
-
|
|
139
|
-
### Token expired
|
|
140
|
-
|
|
141
|
-
Tokens are automatically refreshed using the cached refresh token. If refresh fails, run `onenote login` again.
|
package/docs/zhihu-intro.md
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
# onenote-cli: 让你的 OneNote 笔记在 AI 时代存活下来
|
|
2
|
-
|
|
3
|
-
你的 OneNote 笔记本里藏着多少年的记忆?工作笔记、学习资料、读书笔记、灵感碎片……这些内容,AI 能帮你搜索吗?
|
|
4
|
-
|
|
5
|
-
答案是:现在可以了。
|
|
6
|
-
|
|
7
|
-
onenote-cli 是一个用 Bun + TypeScript 构建的命令行工具,通过 Microsoft Graph API 直接操作你的 OneNote 笔记本。最关键的功能:**全文搜索,精确到页面级别,点击 URL 直接跳转到匹配的那一页。**
|
|
8
|
-
|
|
9
|
-
## 为什么需要这个?
|
|
10
|
-
|
|
11
|
-
OneNote 的搜索功能只能在桌面端或网页端使用,无法被 AI 工具调用。当你想让 AI 帮你找一条几年前的笔记时,它做不到——因为 OneNote 没有暴露搜索 API 给第三方。
|
|
12
|
-
|
|
13
|
-
更糟的是,如果你的 OneDrive 里有超过 5000 个 OneNote 项目(笔记本+分区+分区组),微软的 Graph API 会直接返回 403 错误,连列出分区都做不到。
|
|
14
|
-
|
|
15
|
-
onenote-cli 解决了这两个问题。
|
|
16
|
-
|
|
17
|
-
## 它能做什么?
|
|
18
|
-
|
|
19
|
-
### 全文搜索(精确到页面)
|
|
20
|
-
|
|
21
|
-
```bash
|
|
22
|
-
$ onenote search "项目计划"
|
|
23
|
-
|
|
24
|
-
# (20240315) Q2 项目计划
|
|
25
|
-
Section: Work Notes | Notebook: My Notebook
|
|
26
|
-
...下季度**项目计划**:1. 完成用户认证模块重构 2. 上线新的推荐算法...
|
|
27
|
-
https://onenote.com/...?wd=target(...)
|
|
28
|
-
|
|
29
|
-
3 page-level results found.
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
搜索结果直接给出 OneNote Online 的页面级 URL,点击即可跳转到对应页面。不是打开整个分区,而是精确到那一页。
|
|
33
|
-
|
|
34
|
-
### 笔记本管理
|
|
35
|
-
|
|
36
|
-
```bash
|
|
37
|
-
$ onenote notebooks list
|
|
38
|
-
$ onenote sections list -n <notebook-id>
|
|
39
|
-
$ onenote pages create -s <section-id> -t "Meeting Notes" -b "<p>内容</p>"
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
### 5000 项目限制的解决方案
|
|
43
|
-
|
|
44
|
-
当 Graph API 因为 SharePoint 文档库超过 5000 项而返回 403 时,onenote-cli 会:
|
|
45
|
-
|
|
46
|
-
1. 通过 OneDrive API 直接下载 `.one` 二进制文件
|
|
47
|
-
2. 从二进制中提取页面内容(支持 UTF-8 和 UTF-16LE,中日韩文字都能搜到)
|
|
48
|
-
3. 提取页面 GUID,通过 OneNote API 获取官方页面 URL
|
|
49
|
-
4. 构建本地缓存索引
|
|
50
|
-
|
|
51
|
-
### AI 集成
|
|
52
|
-
|
|
53
|
-
作为 Claude Code Skill 一键安装:
|
|
54
|
-
|
|
55
|
-
```bash
|
|
56
|
-
$ npx skills add snomiao/onenote-cli
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
安装后,AI 可以直接搜索你的 OneNote 笔记,输出 Markdown 格式的结果:
|
|
60
|
-
|
|
61
|
-
```markdown
|
|
62
|
-
[Q2 项目计划](https://onenote.com/...?wd=target(...))
|
|
63
|
-
Work Notes | My Notebook
|
|
64
|
-
...下季度**项目计划**:1. 完成用户认证模块重构...
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
## 技术亮点
|
|
68
|
-
|
|
69
|
-
- **设备代码流认证**:支持 SSH / 无头环境
|
|
70
|
-
- **.one 二进制解析**:从 MS-ONESTORE 格式中提取页面文本和 GUID
|
|
71
|
-
- **官方页面 URL**:通过 `/me/onenote/sections/0-{guid}/pages` 端点获取,绕过 OneNote Online 的会话缓存
|
|
72
|
-
- **跨目录运行**:`.env.local` 和缓存从包目录自动加载
|
|
73
|
-
|
|
74
|
-
## 开始使用
|
|
75
|
-
|
|
76
|
-
```bash
|
|
77
|
-
git clone https://github.com/snomiao/onenote-cli.git
|
|
78
|
-
cd onenote-cli
|
|
79
|
-
bun install
|
|
80
|
-
cp .env.example .env.local # 填入你的 Azure AD Client ID
|
|
81
|
-
bun run src/index.ts auth login
|
|
82
|
-
bun run src/index.ts sync
|
|
83
|
-
bun run src/index.ts search "你想找的内容"
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
详细的 Azure AD 配置步骤见 GitHub 仓库的 [docs/setup.md](https://github.com/snomiao/onenote-cli/blob/main/docs/setup.md)。
|
|
87
|
-
|
|
88
|
-
---
|
|
89
|
-
|
|
90
|
-
**GitHub**: https://github.com/snomiao/onenote-cli
|
|
91
|
-
|
|
92
|
-
MIT License | by snomiao
|
package/src/auth.ts
DELETED
|
@@ -1,359 +0,0 @@
|
|
|
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
|
-
}
|