@kanorio/cli 1.0.0 → 1.1.0

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/README.md CHANGED
@@ -11,9 +11,28 @@ Requires Node.js 20 or later.
11
11
 
12
12
  ## Sign in
13
13
 
14
- 1. Create a personal access token (`knr_pat_…`) at <https://app.kanorio.com/account/api-access>.
15
- 2. Run `kanorio login` (prompts without echo) or `kanorio login --token knr_pat_…`. The token is stored in `~/.config/kanorio/config.json` (file mode 0600, directory 0700; `XDG_CONFIG_HOME` is respected).
16
- 3. In CI and scripts, set `KANORIO_TOKEN` instead; it takes precedence over the config file.
14
+ ```bash
15
+ kanorio login
16
+ ```
17
+
18
+ `login` opens Kanorio's approval page in your browser. You choose the sites and permissions there, and the CLI stores the session in `~/.config/kanorio/config.json` (file mode 0600, directory 0700; `XDG_CONFIG_HOME` is respected). No key is copied or pasted. The link is also printed, so a coding assistant can run the command and hand you the link; `--no-browser` prints it without opening it. `kanorio logout` ends the session, and you can change its sites or revoke it under Account settings > API access.
19
+
20
+ Without a browser, or in CI and scripts:
21
+
22
+ - Set `KANORIO_TOKEN` (a personal access token `knr_pat_…` or a service account token `knr_sa_…`); it takes precedence over the stored session.
23
+ - `kanorio login --with-token` prompts for a personal access token without echo; `echo "$TOKEN" | kanorio login` and `kanorio login --token knr_pat_…` store one too.
24
+
25
+ `kanorio whoami` shows who the credential acts as, its permissions, and the operations it cannot call.
26
+
27
+ ## Any API operation
28
+
29
+ ```bash
30
+ kanorio api GET '/sites/<siteId>/posts?limit=5'
31
+ kanorio api POST /sites/<siteId>/posts --file post.json
32
+ kanorio api POST /sites/<siteId>/posts/<postId>/publish
33
+ ```
34
+
35
+ `api` calls any Management API operation with the stored credential and prints the JSON response. Paths are relative to `/api/v1`; pass a body with `--file <path>`, `--file -` (stdin) or `--data '<json>'`, and an `Idempotency-Key` with `--idempotency-key`. A coding assistant can run these commands for you without ever seeing a token.
17
36
 
18
37
  ## Common commands
19
38
 
@@ -38,7 +57,7 @@ kanorio keys create --site <siteId> --write-env .env.local # issue a serve
38
57
 
39
58
  ### Server keys
40
59
 
41
- `keys create` issues a **server key** (`knr_sa_…`) so the server of a self-hosted front end can act on behalf of a visitor: submit a form, complete a customer sign-in, report an AI crawler hit. A server key cannot call the Management API. `--write-env <file>` writes `KANORIO_SERVER_KEY=…` into that file (created with mode 0600) and does not print the key; if the line already exists, add `--force` to replace it. The CLI warns when the file is not ignored by git. Without `--write-env` the key is printed once. To rotate: run the command again, deploy the new key, then revoke the old one under Site settings > Developer.
60
+ `keys create` issues a **server key** (`knr_sk_…`) so the server of a self-hosted front end can act on behalf of a visitor: submit a form, complete a customer sign-in, report an AI crawler hit. A server key cannot call the Management API. `--write-env <file>` writes `KANORIO_SERVER_KEY=…` into that file (created with mode 0600) and does not print the key; if the line already exists, add `--force` to replace it. The CLI warns when the file is not ignored by git. Without `--write-env` the key is printed once. To rotate: run the command again, deploy the new key, then revoke the old one under Site settings > Developer.
42
61
 
43
62
  ### Output and errors
44
63
 
package/dist/args.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * 參數解析:只用 node:util parseArgs,不引入第三方。
3
- * 所有旗標全域宣告(parseArgs 不支援子命令層級宣告),各命令自己決定要讀哪些。
2
+ * Argument parsing: node:util parseArgs only, no third-party dependency.
3
+ * Every flag is declared globally (parseArgs has no per-subcommand declarations); each command reads the ones it needs.
4
4
  */
5
5
  import { parseArgs } from "node:util";
6
- /** 由兩段組成的子命令;其餘命令只有一段 */
6
+ /** Subcommands made of two segments; every other command has one */
7
7
  const TWO_PART_COMMANDS = new Set(["sites", "pages", "domains", "sections", "jobs", "settings", "globals", "media", "keys"]);
8
8
  export class UsageError extends Error {
9
9
  exitCode = 2;
@@ -73,6 +73,10 @@ export function parseCliArgs(argv) {
73
73
  writeEnv: values["write-env"],
74
74
  keyName: values["key-name"],
75
75
  force: values.force === true,
76
+ data: values.data,
77
+ idempotencyKey: values["idempotency-key"],
78
+ withToken: values["with-token"] === true,
79
+ noBrowser: values["no-browser"] === true,
76
80
  },
77
81
  };
78
82
  }
@@ -115,5 +119,9 @@ const OPTIONS = {
115
119
  switching: { type: "boolean", default: false },
116
120
  "write-env": { type: "string" },
117
121
  "key-name": { type: "string" },
122
+ data: { type: "string" },
123
+ "idempotency-key": { type: "string" },
124
+ "with-token": { type: "boolean", default: false },
125
+ "no-browser": { type: "boolean", default: false },
118
126
  force: { type: "boolean", default: false },
119
127
  };
package/dist/bin.js CHANGED
@@ -26,7 +26,7 @@ async function main(argv) {
26
26
  const result = await handler(cli, {
27
27
  env: process.env,
28
28
  userAgent: `kanorio-cli/${version}`,
29
- // 淘汰警告走 stderr:--json 的 stdout 仍是乾淨的 JSON
29
+ // Deprecation warnings go to stderr: with --json, stdout stays clean JSON
30
30
  onDeprecation: (notice) => process.stderr.write(`${formatDeprecationWarning(notice)}\n`),
31
31
  });
32
32
  process.stdout.write(`${formatResult(result, json)}\n`);
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * REST 薄包裝:組 URL、帶 bearer、解 JSON、把 `{ error: { code, message, details } }` 轉成 ApiError。
3
- * 不含任何業務邏輯;伺服端怎麼回就怎麼給。
2
+ * Thin REST wrapper: builds the URL, sends the bearer token, parses JSON and turns `{ error: { code, message, details } }` into ApiError.
3
+ * No business logic; whatever the server answers is passed through.
4
4
  */
5
5
  export function isErrorEnvelope(value) {
6
6
  if (typeof value !== "object" || value === null)
@@ -26,7 +26,7 @@ export class ApiError extends Error {
26
26
  this.name = "ApiError";
27
27
  }
28
28
  }
29
- /** 非 JSON/非封包的回應(例如 Cloudflare 擋下、代理錯誤)也要能印出 code */
29
+ /** Responses that are not JSON or not an envelope (blocked by Cloudflare, a proxy error) still need a printable code */
30
30
  export function toApiError(status, body, retryAfterHeader) {
31
31
  const retryAfter = retryAfterHeader ? Number.parseInt(retryAfterHeader, 10) : undefined;
32
32
  if (isErrorEnvelope(body)) {
@@ -75,6 +75,7 @@ export function buildUrl(apiUrl, path, query) {
75
75
  export async function request(options) {
76
76
  const fetchImpl = options.fetchImpl ?? fetch;
77
77
  const headers = {
78
+ ...options.headers,
78
79
  authorization: `Bearer ${options.token}`,
79
80
  accept: "application/json",
80
81
  "user-agent": options.userAgent ?? "kanorio-cli",
package/dist/commands.js CHANGED
@@ -1,15 +1,16 @@
1
1
  /**
2
- * 子命令 → REST 呼叫。每個命令只做:取參數 → 組 request → 回伺服端 JSON。
3
- * 唯一的「便利」是 replace-sections 在未給 ifUnmodifiedSince 時先讀頁面拿 updatedAt;仍是兩次 REST 呼叫,不含業務判斷。
2
+ * Subcommand to REST call. Each command only reads its arguments, builds the request and returns the server's JSON.
3
+ * The one convenience: replace-sections reads the page for its updatedAt when ifUnmodifiedSince is not given. That is still two REST calls and no business logic.
4
4
  */
5
- import { execFileSync } from "node:child_process";
5
+ import { execFileSync, spawn } from "node:child_process";
6
6
  import { accessSync, chmodSync, constants as fsConstants, existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
7
7
  import { dirname, resolve } from "node:path";
8
8
  import { createInterface } from "node:readline";
9
9
  import { Writable } from "node:stream";
10
10
  import { UsageError } from "./args.js";
11
11
  import { ApiError, request } from "./client.js";
12
- import { clearToken, configPath, readConfig, resolveAuth, writeConfig } from "./config.js";
12
+ import { clearToken, configPath, readConfig, resolveAuth, withConfigLock, writeConfig } from "./config.js";
13
+ import { buildAuthorizeUrl, createPkce, exchangeAuthorizationCode, OAuthLoginError, randomState, refreshTokens, revokeToken, startLoopbackListener, } from "./oauth.js";
13
14
  import { generateCollectionTypes } from "./types-codegen.js";
14
15
  function need(cli, index, label) {
15
16
  const value = cli.positionals[index];
@@ -32,18 +33,57 @@ function readJsonFile(path) {
32
33
  throw new UsageError(`${path} is not valid JSON.`);
33
34
  }
34
35
  }
36
+ /** Refresh the access token when less than this is left, so it does not expire halfway through a request */
37
+ const REFRESH_SKEW_MS = 60_000;
38
+ /**
39
+ * The token for this call. `--token`, `KANORIO_TOKEN` or a stored PAT is used as is; a browser sign-in's access token is refreshed with the refresh token when it is about to expire.
40
+ * The refresh happens under a lock, and the config file is read again once the lock is held (another process may have just refreshed). If the refresh token is rejected (expired or revoked), the sign-in is cleared and the user is asked to sign in again.
41
+ */
42
+ async function resolveToken(cli, ctx) {
43
+ const auth = resolveAuth(cli.flags, ctx.env);
44
+ if (!auth.token) {
45
+ throw new ApiError("UNAUTHORIZED", 401, "Not signed in. Run `kanorio login` or set KANORIO_TOKEN.");
46
+ }
47
+ if (auth.tokenSource !== "oauth" || !auth.oauth || auth.oauth.expiresAt - Date.now() > REFRESH_SKEW_MS) {
48
+ return { token: auth.token, apiUrl: auth.apiUrl };
49
+ }
50
+ return withConfigLock(ctx.env, async () => {
51
+ const current = readConfig(ctx.env);
52
+ const session = current.oauth;
53
+ if (!session || session.apiUrl !== auth.apiUrl) {
54
+ throw new ApiError("UNAUTHORIZED", 401, "Not signed in. Run `kanorio login` or set KANORIO_TOKEN.");
55
+ }
56
+ if (session.expiresAt - Date.now() > REFRESH_SKEW_MS)
57
+ return { token: session.accessToken, apiUrl: auth.apiUrl };
58
+ try {
59
+ const tokens = await refreshTokens({ apiUrl: auth.apiUrl, refreshToken: session.refreshToken, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
60
+ writeConfig({ ...current, oauth: { ...tokens, apiUrl: auth.apiUrl } }, ctx.env);
61
+ return { token: tokens.accessToken, apiUrl: auth.apiUrl };
62
+ }
63
+ catch (error) {
64
+ if (error instanceof OAuthLoginError && error.code === "invalid_grant") {
65
+ clearToken(ctx.env);
66
+ throw new ApiError("UNAUTHORIZED", 401, "The session has expired or was revoked. Run `kanorio login` again.");
67
+ }
68
+ throw error;
69
+ }
70
+ });
71
+ }
35
72
  function authed(cli, ctx) {
73
+ // Being signed out must fail before anything is sent (as before: thrown synchronously); the token refresh waits until the call is actually made
36
74
  const auth = resolveAuth(cli.flags, ctx.env);
37
75
  if (!auth.token) {
38
- throw new ApiError("UNAUTHORIZED", 401, "No token. Run `kanorio login` or set KANORIO_TOKEN.");
76
+ throw new ApiError("UNAUTHORIZED", 401, "Not signed in. Run `kanorio login` or set KANORIO_TOKEN.");
39
77
  }
40
- const token = auth.token;
41
78
  return {
42
79
  apiUrl: auth.apiUrl,
43
- call: (method, path, extra = {}) => request({ apiUrl: auth.apiUrl, token, method, path, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent, onDeprecation: ctx.onDeprecation, ...extra }),
80
+ call: async (method, path, extra = {}) => {
81
+ const { token, apiUrl } = await resolveToken(cli, ctx);
82
+ return request({ apiUrl, token, method, path, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent, onDeprecation: ctx.onDeprecation, ...extra });
83
+ },
44
84
  };
45
85
  }
46
- /** 互動輸入 token 時不回顯:輸出導到黑洞,只手動印提示字 */
86
+ /** Typing a token interactively does not echo: output goes to a sink and only the prompt is printed by hand */
47
87
  async function promptSecret(prompt, stdin) {
48
88
  const input = stdin ?? process.stdin;
49
89
  if (!input.isTTY) {
@@ -68,15 +108,14 @@ async function promptSecret(prompt, stdin) {
68
108
  });
69
109
  });
70
110
  }
71
- const login = async (cli, ctx) => {
72
- const token = cli.flags.token ?? (await promptSecret("Paste your personal access token (knr_pat_…): ", ctx.stdin));
111
+ /** A pasted PAT is verified before it is stored, so a bad one is never written (403 means valid but without console:view, which is still stored) */
112
+ async function storePersonalToken(cli, ctx, token) {
73
113
  if (!token)
74
114
  throw new UsageError("Token is empty.");
75
115
  if (!token.startsWith("knr_pat_")) {
76
- throw new UsageError("Only personal access tokens (knr_pat_…) can be stored; OAuth tokens are for MCP clients.");
116
+ throw new UsageError("Only personal access tokens (knr_pat_…) can be pasted. To sign in without a token, run `kanorio login` and approve it in the browser.");
77
117
  }
78
118
  const apiUrl = resolveAuth({ api: cli.flags.api }, ctx.env).apiUrl;
79
- // 先驗再存:壞 token 不落地。403 代表 token 有效但沒 console:view,仍可存
80
119
  let verified = "ok";
81
120
  try {
82
121
  await request({ apiUrl, token, method: "GET", path: "/sites", fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
@@ -87,7 +126,8 @@ const login = async (cli, ctx) => {
87
126
  else
88
127
  throw error;
89
128
  }
90
- const current = readConfig(ctx.env);
129
+ const { oauth: _replaced, ...current } = readConfig(ctx.env);
130
+ void _replaced;
91
131
  const path = writeConfig({ ...current, token, ...(cli.flags.api ? { apiUrl } : {}) }, ctx.env);
92
132
  return {
93
133
  stored: path,
@@ -95,10 +135,116 @@ const login = async (cli, ctx) => {
95
135
  tokenPrefix: token.slice(0, 12),
96
136
  ...(verified === "limited" ? { warning: "Token lacks console:view; sites list/get will be forbidden." } : {}),
97
137
  };
138
+ }
139
+ /**
140
+ * A PAT piped in (`echo $TOKEN | kanorio login`, supported since 1.0). When stdin is not a terminal, wait briefly:
141
+ * data means a token; no data (a coding assistant running the command usually leaves stdin empty or open) means browser sign-in.
142
+ */
143
+ async function readPipedToken(stdin, waitMs = 300) {
144
+ const input = stdin ?? process.stdin;
145
+ if (input.isTTY)
146
+ return null;
147
+ return new Promise((resolve) => {
148
+ let data = "";
149
+ let done = false;
150
+ const finish = (value) => {
151
+ if (done)
152
+ return;
153
+ done = true;
154
+ clearTimeout(timer);
155
+ input.removeListener("data", onData);
156
+ input.removeListener("end", onEnd);
157
+ input.pause?.();
158
+ resolve(value);
159
+ };
160
+ const onData = (chunk) => {
161
+ data += String(chunk);
162
+ // Data arrived: wait for the rest (the pipe will end), no longer bound by the timeout
163
+ clearTimeout(timer);
164
+ };
165
+ const onEnd = () => finish(data.trim() || null);
166
+ const timer = setTimeout(() => finish(null), waitMs);
167
+ input.setEncoding?.("utf8");
168
+ input.on("data", onData);
169
+ input.on("end", onEnd);
170
+ input.on("error", () => finish(null));
171
+ });
172
+ }
173
+ function openInBrowser(url) {
174
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
175
+ try {
176
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
177
+ child.on("error", () => { });
178
+ child.unref();
179
+ }
180
+ catch {
181
+ // Failing to open the browser is not an error: the link is already printed and the user can open it
182
+ }
183
+ }
184
+ /**
185
+ * Browser sign-in: prints (and tries to open) Kanorio's approval page, waits for the user to approve, then stores the tokens in the config file.
186
+ * No key is copied or pasted along the way; when a coding assistant runs the command, it only has to hand the link to the user.
187
+ */
188
+ async function loginWithBrowser(cli, ctx) {
189
+ const apiUrl = resolveAuth({ api: cli.flags.api }, ctx.env).apiUrl;
190
+ const log = ctx.log ?? ((line) => void process.stderr.write(`${line}\n`));
191
+ const listener = await startLoopbackListener();
192
+ try {
193
+ const { verifier, challenge } = createPkce();
194
+ const state = randomState();
195
+ const url = buildAuthorizeUrl({ apiUrl, redirectUri: listener.redirectUri, challenge, state });
196
+ log("Open this link to sign in to Kanorio and choose what the CLI may do:");
197
+ log(` ${url}`);
198
+ log("Waiting for approval in the browser (the link works for 5 minutes)…");
199
+ if (!cli.flags.noBrowser)
200
+ (ctx.openBrowser ?? openInBrowser)(url);
201
+ const code = await listener.waitForCode(state);
202
+ const tokens = await exchangeAuthorizationCode({ apiUrl, code, verifier, redirectUri: listener.redirectUri, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
203
+ const { token: _replaced, ...current } = readConfig(ctx.env);
204
+ void _replaced;
205
+ const path = writeConfig({ ...current, oauth: { ...tokens, apiUrl }, ...(cli.flags.api ? { apiUrl } : {}) }, ctx.env);
206
+ // Show the user who is signed in and which sites can be changed; failing to ask does not affect the sign-in
207
+ const who = await request({
208
+ apiUrl,
209
+ token: tokens.accessToken,
210
+ method: "GET",
211
+ path: "/whoami",
212
+ fetchImpl: ctx.fetchImpl,
213
+ userAgent: ctx.userAgent,
214
+ }).catch(() => null);
215
+ return {
216
+ stored: path,
217
+ apiUrl,
218
+ ...(who ? { signedInAs: who.principal, websiteScope: who.websiteScope, websiteIds: who.websiteIds } : {}),
219
+ note: "Signed in. Manage or revoke this connection under Account settings > API access > Authorized apps.",
220
+ };
221
+ }
222
+ finally {
223
+ listener.close();
224
+ }
225
+ }
226
+ /**
227
+ * `kanorio login`: opens the browser for approval by default (no key to copy).
228
+ * `--token <pat>` or a PAT on stdin stores that token; `--with-token` pastes one in the terminal (not echoed).
229
+ */
230
+ const login = async (cli, ctx) => {
231
+ if (cli.flags.token !== undefined)
232
+ return storePersonalToken(cli, ctx, cli.flags.token);
233
+ if (cli.flags.withToken) {
234
+ return storePersonalToken(cli, ctx, await promptSecret("Paste your personal access token (knr_pat_…): ", ctx.stdin));
235
+ }
236
+ const piped = await readPipedToken(ctx.stdin);
237
+ if (piped)
238
+ return storePersonalToken(cli, ctx, piped);
239
+ return loginWithBrowser(cli, ctx);
98
240
  };
99
- const logout = async (_cli, ctx) => {
241
+ /** Sign out: a browser sign-in is also revoked on the server (a failed revoke does not block; the local tokens are always cleared) */
242
+ const logout = async (cli, ctx) => {
243
+ const session = readConfig(ctx.env).oauth;
244
+ const revoked = session ? await revokeToken({ apiUrl: session.apiUrl, token: session.refreshToken, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent }) : undefined;
245
+ void cli;
100
246
  clearToken(ctx.env);
101
- return { removed: configPath(ctx.env) };
247
+ return { removed: configPath(ctx.env), ...(revoked !== undefined ? { revoked } : {}) };
102
248
  };
103
249
  const sitesList = async (cli, ctx) => authed(cli, ctx).call("GET", "/sites");
104
250
  const sitesGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}`);
@@ -123,7 +269,7 @@ const sitesCreate = async (cli, ctx) => {
123
269
  const settingsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/settings`);
124
270
  const settingsUpdate = async (cli, ctx) => {
125
271
  const settings = cli.flags.file ? readJsonFile(cli.flags.file) : {};
126
- // 品牌身分(含外觀模式,立即生效)放 settings.brand;版面設計(草稿)放頂層(Headless ADR-0005 修訂一)
272
+ // Brand identity (including color scheme, effective immediately) goes under settings.brand; layout design (draft) stays at the top level
127
273
  const brand = settings.brand ?? {};
128
274
  if (cli.flags.brandColor) {
129
275
  brand.brandColor = { light: cli.flags.brandColor, dark: cli.flags.brandColorDark ?? cli.flags.brandColor };
@@ -146,7 +292,7 @@ const settingsUpdate = async (cli, ctx) => {
146
292
  return authed(cli, ctx).call("PATCH", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/settings`, { body: { settings } });
147
293
  };
148
294
  const globalsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/globals`);
149
- /** 全站層寫入:未給 --if-unmodified-since 時先讀 globals 拿 contentUpdatedAt(兩次 REST 呼叫,無業務判斷) */
295
+ /** Site-wide writes: without --if-unmodified-since, read globals first for contentUpdatedAt (two REST calls, no business logic) */
150
296
  async function globalsWrite(cli, ctx, method, suffix, bodyKey, label) {
151
297
  if (!cli.flags.file)
152
298
  throw new UsageError(`${label} needs --file <${bodyKey}.json>.`);
@@ -339,8 +485,8 @@ const doctorCheck = async (cli, ctx) => {
339
485
  const SERVER_KEY_ENV_NAME = "KANORIO_SERVER_KEY";
340
486
  const SERVER_KEY_ENV_LINE = /^[ \t]*(?:export[ \t]+)?KANORIO_SERVER_KEY[ \t]*=.*$/;
341
487
  /**
342
- * 把金鑰那一行寫進環境變數檔的內容:已有就換掉第一筆、其餘同名的行刪掉;沒有就加在結尾。
343
- * 同名的行只留一筆:dotenv 取最後一筆,留著舊的那一行,主機會繼續用該作廢的那把金鑰。
488
+ * Writes the key line into the contents of an env file: replaces the first existing line and removes other lines with the same name, or appends one.
489
+ * Only one line with that name is kept: dotenv takes the last one, so a leftover old line would keep the host on the revoked key.
344
490
  */
345
491
  function upsertServerKeyLine(existing, line) {
346
492
  const lines = existing.split("\n");
@@ -352,7 +498,7 @@ function upsertServerKeyLine(existing, line) {
352
498
  .filter((entry, index) => index === first || !SERVER_KEY_ENV_LINE.test(entry))
353
499
  .join("\n");
354
500
  }
355
- /** 寫不寫得進去:檔案在就看檔案,不在就看它的資料夾(要存在且可寫) */
501
+ /** Whether the write can succeed: check the file when it exists, otherwise its folder (which must exist and be writable) */
356
502
  function assertEnvFileWritable(envFile) {
357
503
  const target = existsSync(envFile) ? envFile : dirname(envFile);
358
504
  if (target !== envFile && !existsSync(target))
@@ -364,22 +510,22 @@ function assertEnvFileWritable(envFile) {
364
510
  throw new UsageError(`${target} is not writable. Fix its permissions, or point --write-env somewhere else.`);
365
511
  }
366
512
  }
367
- /** 檔案在不在 git 的忽略清單裡;不在 git 儲存庫裡、或沒有 git 回 null(無從判斷) */
513
+ /** Whether git ignores the file; null when outside a git repository or without git (cannot tell) */
368
514
  function isGitIgnored(file) {
369
515
  try {
370
516
  execFileSync("git", ["check-ignore", "-q", file], { cwd: dirname(file), stdio: "ignore" });
371
517
  return true;
372
518
  }
373
519
  catch (error) {
374
- // exit 1=沒被忽略;其餘(128=不在儲存庫、ENOENT=沒有 git)無從判斷
520
+ // exit 1 means not ignored; anything else (128 outside a repository, ENOENT without git) cannot tell
375
521
  return error.status === 1 ? false : null;
376
522
  }
377
523
  }
378
524
  /**
379
- * 簽發一把網站主機金鑰。`--write-env` 時把金鑰寫進環境變數檔、終端機不印明文:
380
- * 明文只經過「API 回應 → 檔案」,不進 shell 歷史、不進終端機捲動紀錄,也不會被 AI 工具讀到輸出。
381
- * 會不會覆寫、寫不寫得進去都在呼叫 API **之前**判斷,免得簽了金鑰卻寫不進去、留下一把沒人知道的金鑰。
382
- * 簽發之後才寫入失敗(檢查之後檔案被改了權限)時,改把金鑰印出來一次,不讓它消失。
525
+ * Issues a server key. With `--write-env` the key is written to the env file and never printed:
526
+ * the plaintext only travels from the API response to the file. It does not enter shell history or terminal scrollback, and an AI tool reading the output never sees it.
527
+ * Whether it would overwrite and whether the write can succeed are both checked **before** calling the API, so a key is never issued that cannot be written and that nobody knows.
528
+ * If the write fails after issuing (permissions changed after the check), the key is printed once instead of being lost.
383
529
  */
384
530
  const keysCreate = async (cli, ctx) => {
385
531
  const siteId = cli.flags.site ?? cli.positionals[0];
@@ -414,7 +560,7 @@ const keysCreate = async (cli, ctx) => {
414
560
  note: `Could not write ${envFile} (${error instanceof Error ? error.message : String(error)}). The key was created and is shown once here: store it on your frontend host as ${created.envName}, or revoke it under Site settings > Developer.`,
415
561
  };
416
562
  }
417
- // 新建的檔案只給擁有者讀寫;既有的檔案不動它的權限(可能是團隊刻意設的)
563
+ // A new file is readable and writable by its owner only; an existing file keeps its permissions (the team may have set them on purpose)
418
564
  if (isNew)
419
565
  chmodSync(envFile, 0o600);
420
566
  const warnings = [];
@@ -427,9 +573,76 @@ const keysCreate = async (cli, ctx) => {
427
573
  void _key;
428
574
  return { ...safe, written: envFile, ...(warnings.length > 0 ? { warnings } : {}) };
429
575
  };
576
+ const API_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
577
+ /** Reads all of stdin (`--file -`) */
578
+ async function readStdin(stdin) {
579
+ const input = stdin ?? process.stdin;
580
+ return new Promise((resolve, reject) => {
581
+ let data = "";
582
+ input.setEncoding?.("utf8");
583
+ input.on("data", (chunk) => {
584
+ data += chunk;
585
+ });
586
+ input.on("end", () => resolve(data));
587
+ input.on("error", reject);
588
+ });
589
+ }
590
+ /**
591
+ * General entry point: calls any Management API operation with the stored credential (like `gh api` and `vercel api`).
592
+ * For operations without a dedicated command, and so a coding assistant never handles the token: it runs the command while the token stays in the config file or the environment.
593
+ * Paths are relative to `/api/v1`; only the configured API host is called and full URLs are refused (the token is never sent to another host).
594
+ */
595
+ const apiCall = async (cli, ctx) => {
596
+ const method = need(cli, 0, "method").toUpperCase();
597
+ if (!API_METHODS.includes(method)) {
598
+ throw new UsageError(`Unknown method ${cli.positionals[0]}. Use one of ${API_METHODS.join(", ")}.`);
599
+ }
600
+ const raw = need(cli, 1, "path");
601
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
602
+ throw new UsageError("Pass a path such as /sites/<siteId>/posts, not a URL. The API origin comes from --api or KANORIO_API_URL.");
603
+ }
604
+ const withoutBase = raw.replace(/^\/?api\/v1(?=\/|\?|$)/, "");
605
+ const [pathname = "", search = ""] = withoutBase.split("?", 2);
606
+ if (!pathname || pathname === "/")
607
+ throw new UsageError("Missing <path>, for example /whoami or /sites/<siteId>/posts.");
608
+ const query = {};
609
+ for (const [key, value] of new URLSearchParams(search))
610
+ query[key] = value;
611
+ if (cli.flags.file && cli.flags.data)
612
+ throw new UsageError("Pass the body with --file or --data, not both.");
613
+ let body;
614
+ if (cli.flags.file === "-") {
615
+ const text = await readStdin(ctx.stdin);
616
+ try {
617
+ body = JSON.parse(text);
618
+ }
619
+ catch {
620
+ throw new UsageError("The body read from stdin is not valid JSON.");
621
+ }
622
+ }
623
+ else if (cli.flags.file) {
624
+ body = readJsonFile(cli.flags.file);
625
+ }
626
+ else if (cli.flags.data !== undefined) {
627
+ try {
628
+ body = JSON.parse(cli.flags.data);
629
+ }
630
+ catch {
631
+ throw new UsageError("--data is not valid JSON.");
632
+ }
633
+ }
634
+ if (body !== undefined && method === "GET")
635
+ throw new UsageError("GET takes no body. Put filters in the path's query string.");
636
+ const headers = cli.flags.idempotencyKey ? { "idempotency-key": cli.flags.idempotencyKey } : undefined;
637
+ return authed(cli, ctx).call(method, pathname.startsWith("/") ? pathname : `/${pathname}`, { query, body, headers });
638
+ };
639
+ /** Who the stored credential is, what it can do, and which operations it cannot call and why (`GET /whoami`; service account tokens can ask too) */
640
+ const whoami = async (cli, ctx) => authed(cli, ctx).call("GET", "/whoami", { query: { websiteId: cli.flags.site } });
430
641
  export const COMMANDS = {
431
642
  login,
432
643
  logout,
644
+ api: apiCall,
645
+ whoami,
433
646
  types: typesGenerate,
434
647
  doctor: doctorCheck,
435
648
  "keys create": keysCreate,
package/dist/config.js CHANGED
@@ -1,11 +1,20 @@
1
1
  /**
2
- * 本機設定:`$XDG_CONFIG_HOME/kanorio/config.json`(預設 `~/.config/kanorio/config.json`)。
3
- * 只存 PAT 與 API base;檔案 0600、目錄 0700。環境變數 `KANORIO_TOKEN` 永遠優先於檔案。
2
+ * Local config: `$XDG_CONFIG_HOME/kanorio/config.json` (default `~/.config/kanorio/config.json`).
3
+ * Stores the sign-in credential (OAuth tokens from browser sign-in, or a pasted PAT, one or the other) and the API base; file mode 0600, directory 0700.
4
+ * The `KANORIO_TOKEN` environment variable always wins over the file.
4
5
  */
5
- import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
7
  import { homedir } from "node:os";
7
8
  import { join } from "node:path";
8
9
  export const DEFAULT_API_URL = "https://app.kanorio.com";
10
+ function parseOAuthSession(value) {
11
+ if (typeof value !== "object" || value === null)
12
+ return null;
13
+ const o = value;
14
+ if (typeof o.accessToken !== "string" || typeof o.refreshToken !== "string" || typeof o.expiresAt !== "number" || typeof o.apiUrl !== "string")
15
+ return null;
16
+ return { accessToken: o.accessToken, refreshToken: o.refreshToken, expiresAt: o.expiresAt, apiUrl: o.apiUrl };
17
+ }
9
18
  export function configDir(env = process.env) {
10
19
  const base = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.trim() ? env.XDG_CONFIG_HOME : join(env.HOME ?? homedir(), ".config");
11
20
  return join(base, "kanorio");
@@ -22,9 +31,11 @@ export function readConfig(env = process.env) {
22
31
  if (typeof parsed !== "object" || parsed === null)
23
32
  return {};
24
33
  const obj = parsed;
34
+ const oauth = parseOAuthSession(obj.oauth);
25
35
  return {
26
36
  ...(typeof obj.token === "string" ? { token: obj.token } : {}),
27
37
  ...(typeof obj.apiUrl === "string" ? { apiUrl: obj.apiUrl } : {}),
38
+ ...(oauth ? { oauth } : {}),
28
39
  };
29
40
  }
30
41
  catch {
@@ -36,14 +47,15 @@ export function writeConfig(config, env = process.env) {
36
47
  mkdirSync(dir, { recursive: true, mode: 0o700 });
37
48
  const path = configPath(env);
38
49
  writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
39
- // writeFileSync 的 mode 只在建檔時生效;既有檔案(例如使用者手動建立)也要收緊
50
+ // writeFileSync's mode only applies on creation; an existing file (created by hand, for example) is tightened too
40
51
  chmodSync(path, 0o600);
41
52
  return path;
42
53
  }
43
- /** 只移除 token;其他設定(apiUrl)保留,什麼都不剩時刪檔 */
54
+ /** Removes the sign-in credential (PAT and browser sign-in tokens); other settings (apiUrl) stay, and the file is deleted when nothing is left */
44
55
  export function clearToken(env = process.env) {
45
56
  const rest = { ...readConfig(env) };
46
57
  delete rest.token;
58
+ delete rest.oauth;
47
59
  if (Object.keys(rest).length === 0) {
48
60
  if (existsSync(configPath(env)))
49
61
  unlinkSync(configPath(env));
@@ -59,5 +71,51 @@ export function resolveAuth(flags, env = process.env, config = readConfig(env))
59
71
  return { token: env.KANORIO_TOKEN, apiUrl, tokenSource: "env" };
60
72
  if (config.token)
61
73
  return { token: config.token, apiUrl, tokenSource: "config" };
74
+ // Browser sign-in tokens are valid only for the host that issued them; they are not used when --api points elsewhere
75
+ if (config.oauth && config.oauth.apiUrl === apiUrl)
76
+ return { token: config.oauth.accessToken, apiUrl, tokenSource: "oauth", oauth: config.oauth };
62
77
  return { token: null, apiUrl, tokenSource: null };
63
78
  }
79
+ const LOCK_STALE_MS = 30_000;
80
+ const LOCK_WAIT_MS = 15_000;
81
+ /**
82
+ * A lock file lets only one process refresh the tokens at a time. Each refresh revokes the previous refresh token, and replaying an old one revokes the whole grant;
83
+ * two commands running at once (coding assistants often do this) would each refresh with the same token and the later one would lose the sign-in.
84
+ * The process that gets the lock must read the config file again: the previous process may already have refreshed.
85
+ */
86
+ export async function withConfigLock(env, fn) {
87
+ const dir = configDir(env);
88
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
89
+ const lock = join(dir, "config.lock");
90
+ const deadline = Date.now() + LOCK_WAIT_MS;
91
+ for (;;) {
92
+ try {
93
+ closeSync(openSync(lock, "wx", 0o600));
94
+ break;
95
+ }
96
+ catch {
97
+ // Another process holds it; a stale lock left by a crashed process is removed
98
+ try {
99
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS)
100
+ unlinkSync(lock);
101
+ }
102
+ catch {
103
+ // Released just now
104
+ }
105
+ if (Date.now() > deadline)
106
+ throw new Error("Another kanorio command is refreshing the session. Try again.");
107
+ await new Promise((resolve) => setTimeout(resolve, 50));
108
+ }
109
+ }
110
+ try {
111
+ return await fn();
112
+ }
113
+ finally {
114
+ try {
115
+ unlinkSync(lock);
116
+ }
117
+ catch {
118
+ // Already removed
119
+ }
120
+ }
121
+ }
package/dist/help.js CHANGED
@@ -3,9 +3,24 @@ export const HELP = `kanorio - command-line wrapper around the Kanorio Managemen
3
3
  Usage: kanorio <command> [args] [--json] [--api <url>] [--token <pat>]
4
4
 
5
5
  Auth
6
- login [--token <pat>] Store a personal access token (~/.config/kanorio/config.json, 0600)
7
- logout Remove the stored token
8
- KANORIO_TOKEN=<pat> Environment variable; takes precedence over the config file
6
+ login [--no-browser] Sign in through the browser: opens Kanorio's approval page, where you choose the sites
7
+ and permissions, then stores the session (~/.config/kanorio/config.json, 0600).
8
+ No key is copied or pasted, so a coding assistant can run it for you: it prints the
9
+ link, you open it. --no-browser prints the link without opening it.
10
+ login --with-token Paste a personal access token instead (hidden prompt); or pipe it: echo $TOKEN | kanorio login
11
+ login --token <pat> Store a personal access token given on the command line
12
+ logout Remove the stored session or token (a browser session is also revoked on the server)
13
+ KANORIO_TOKEN=<token> Environment variable; takes precedence over the stored session
14
+
15
+ Any API operation
16
+ api <METHOD> <path> [--file <body.json> | --data '<json>'] [--idempotency-key <key>]
17
+ Call any Management API operation with the stored token and print the JSON response:
18
+ kanorio api GET '/sites/<siteId>/posts?limit=5'
19
+ kanorio api POST /sites/<siteId>/posts --file post.json
20
+ kanorio api POST /sites/<siteId>/posts/<postId>/publish
21
+ <path> is relative to /api/v1 (the API reference lists every operation). --file - reads the body from stdin.
22
+ A coding assistant can run this for you without ever seeing the token.
23
+ whoami [--site <siteId>] Who the stored token acts as, its permissions, and the operations it cannot call (with the reason)
9
24
 
10
25
  Sites
11
26
  sites list
@@ -65,7 +80,7 @@ Sections & Types
65
80
 
66
81
  Server keys
67
82
  keys create --site <siteId> [--name <account>] [--key-name <label>] [--write-env <.env.local>] [--force]
68
- Issue a server key (knr_sa_…) so your own server can submit forms, exchange customer sign-in codes and report
83
+ Issue a server key (knr_sk_…) so your own server can submit forms, exchange customer sign-in codes and report
69
84
  crawler hits on behalf of visitors. The key cannot call the Management API.
70
85
  --write-env writes KANORIO_SERVER_KEY=… into that file (created with mode 0600) and does not print the key;
71
86
  an existing KANORIO_SERVER_KEY line is only replaced with --force. Without --write-env the key is printed once.
package/dist/oauth.js ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Browser sign-in (OAuth 2.1 authorization code + PKCE, loopback redirect for native apps, RFC 8252).
3
+ *
4
+ * `kanorio login` opens the browser on Kanorio's approval page, where the user picks sites and permissions; after approval the browser returns to a temporary local
5
+ * `http://127.0.0.1:<port>/callback`, and the CLI exchanges the authorization code for an access token and a refresh token. No key is copied or pasted along the way,
6
+ * and a coding assistant running the command never sees the tokens.
7
+ *
8
+ * The tokens' audience (RFC 8707 resource) is the Management API: they work on `/api/v1` only and MCP refuses them, just as MCP's OAuth tokens
9
+ * do not work here. The access token expires after an hour and is refreshed with the refresh token; every refresh revokes the previous refresh token (a replay revokes the whole grant),
10
+ * so refreshes are serialized (the lock in config.ts).
11
+ */
12
+ import { createHash, randomBytes } from "node:crypto";
13
+ import { createServer } from "node:http";
14
+ /** The Kanorio CLI's client id (the URL of its Client ID Metadata Document; the authorization server knows this first-party client) */
15
+ export const CLI_OAUTH_CLIENT_ID = "https://kanorio.com/oauth/kanorio-cli.json";
16
+ /** Callback path; the port differs every time (RFC 8252 section 7.3: the authorization server ignores the port when matching loopback addresses) */
17
+ export const CLI_OAUTH_CALLBACK_PATH = "/callback";
18
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
19
+ export class OAuthLoginError extends Error {
20
+ code;
21
+ exitCode = 1;
22
+ constructor(code, message) {
23
+ super(message);
24
+ this.code = code;
25
+ this.name = "OAuthLoginError";
26
+ }
27
+ }
28
+ const base64url = (bytes) => bytes.toString("base64url");
29
+ export function createPkce() {
30
+ const verifier = base64url(randomBytes(32));
31
+ return { verifier, challenge: base64url(createHash("sha256").update(verifier).digest()) };
32
+ }
33
+ /** The tokens' audience: the Management API on this API host */
34
+ export function managementResource(apiUrl) {
35
+ return `${apiUrl.replace(/\/+$/, "")}/api/v1`;
36
+ }
37
+ export function buildAuthorizeUrl(params) {
38
+ const url = new URL(`${params.apiUrl.replace(/\/+$/, "")}/oauth/authorize`);
39
+ url.searchParams.set("response_type", "code");
40
+ url.searchParams.set("client_id", CLI_OAUTH_CLIENT_ID);
41
+ url.searchParams.set("redirect_uri", params.redirectUri);
42
+ url.searchParams.set("code_challenge", params.challenge);
43
+ url.searchParams.set("code_challenge_method", "S256");
44
+ url.searchParams.set("state", params.state);
45
+ url.searchParams.set("resource", managementResource(params.apiUrl));
46
+ return url.toString();
47
+ }
48
+ const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title>` +
49
+ `<meta name="viewport" content="width=device-width, initial-scale=1"><style>body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1.5rem;color:#1c1917}h1{font-size:1.25rem}</style></head>` +
50
+ `<body><h1>${title}</h1><p>${body}</p></body></html>`;
51
+ /** Starts a one-off callback server on a random port of 127.0.0.1 (local only, not exposed) */
52
+ export async function startLoopbackListener(options = {}) {
53
+ let settle = null;
54
+ let expected = null;
55
+ let early = null;
56
+ const server = createServer((req, res) => {
57
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
58
+ if (url.pathname !== CLI_OAUTH_CALLBACK_PATH) {
59
+ res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
60
+ return;
61
+ }
62
+ const finish = (status, title, body, outcome) => {
63
+ res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(page(title, body));
64
+ if (settle) {
65
+ if (outcome.code)
66
+ settle.resolve(outcome.code);
67
+ else
68
+ settle.reject(outcome.error ?? new OAuthLoginError("login_failed", "Sign-in failed."));
69
+ }
70
+ else {
71
+ early = outcome;
72
+ }
73
+ };
74
+ const error = url.searchParams.get("error");
75
+ if (error) {
76
+ const description = url.searchParams.get("error_description") ?? error;
77
+ finish(400, "Sign-in was not completed", "You can close this tab and run <code>kanorio login</code> again.", {
78
+ error: new OAuthLoginError(error, error === "access_denied" ? "Access was not approved." : description),
79
+ });
80
+ return;
81
+ }
82
+ const code = url.searchParams.get("code");
83
+ const state = url.searchParams.get("state");
84
+ if (!code || !state || (expected !== null && state !== expected)) {
85
+ finish(400, "Sign-in was not completed", "This sign-in link does not match the request that started it. Run <code>kanorio login</code> again.", {
86
+ error: new OAuthLoginError("invalid_state", "The sign-in response did not match this request."),
87
+ });
88
+ return;
89
+ }
90
+ finish(200, "Kanorio CLI is connected", "You can close this tab and go back to your terminal.", { code });
91
+ });
92
+ await new Promise((resolve, reject) => {
93
+ server.once("error", reject);
94
+ server.listen(0, "127.0.0.1", () => resolve());
95
+ });
96
+ const { port } = server.address();
97
+ const timeoutMs = options.timeoutMs ?? LOGIN_TIMEOUT_MS;
98
+ return {
99
+ redirectUri: `http://127.0.0.1:${port}${CLI_OAUTH_CALLBACK_PATH}`,
100
+ waitForCode(expectedState) {
101
+ expected = expectedState;
102
+ return new Promise((resolve, reject) => {
103
+ const timer = setTimeout(() => reject(new OAuthLoginError("timeout", "Timed out waiting for the browser. Run `kanorio login` again.")), timeoutMs);
104
+ timer.unref?.();
105
+ const done = (fn) => (value) => {
106
+ clearTimeout(timer);
107
+ fn(value);
108
+ };
109
+ settle = { resolve: done(resolve), reject: done(reject) };
110
+ if (early) {
111
+ if (early.code)
112
+ settle.resolve(early.code);
113
+ else
114
+ settle.reject(early.error ?? new OAuthLoginError("login_failed", "Sign-in failed."));
115
+ }
116
+ });
117
+ },
118
+ close() {
119
+ server.close();
120
+ server.closeAllConnections?.();
121
+ },
122
+ };
123
+ }
124
+ async function tokenRequest(apiUrl, form, fetchImpl, userAgent) {
125
+ const res = await fetchImpl(`${apiUrl.replace(/\/+$/, "")}/oauth/token`, {
126
+ method: "POST",
127
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", "user-agent": userAgent },
128
+ body: new URLSearchParams({ ...form, client_id: CLI_OAUTH_CLIENT_ID }).toString(),
129
+ });
130
+ const body = (await res.json().catch(() => ({})));
131
+ if (!res.ok || typeof body.access_token !== "string" || typeof body.refresh_token !== "string") {
132
+ const code = typeof body.error === "string" ? body.error : `http_${res.status}`;
133
+ const description = typeof body.error_description === "string" ? body.error_description : "The authorization server refused the request.";
134
+ throw new OAuthLoginError(code, description);
135
+ }
136
+ const expiresIn = typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : 3600;
137
+ return { accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: Date.now() + expiresIn * 1000 };
138
+ }
139
+ export function exchangeAuthorizationCode(params) {
140
+ return tokenRequest(params.apiUrl, { grant_type: "authorization_code", code: params.code, code_verifier: params.verifier, redirect_uri: params.redirectUri, resource: managementResource(params.apiUrl) }, params.fetchImpl ?? fetch, params.userAgent);
141
+ }
142
+ export function refreshTokens(params) {
143
+ return tokenRequest(params.apiUrl, { grant_type: "refresh_token", refresh_token: params.refreshToken, resource: managementResource(params.apiUrl) }, params.fetchImpl ?? fetch, params.userAgent);
144
+ }
145
+ /** Revokes the grant on sign-out (best effort: the local tokens are always cleared, and a failed server-side revoke does not block) */
146
+ export async function revokeToken(params) {
147
+ try {
148
+ const res = await (params.fetchImpl ?? fetch)(`${params.apiUrl.replace(/\/+$/, "")}/oauth/revoke`, {
149
+ method: "POST",
150
+ headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": params.userAgent },
151
+ body: new URLSearchParams({ token: params.token, client_id: CLI_OAUTH_CLIENT_ID }).toString(),
152
+ });
153
+ return res.ok;
154
+ }
155
+ catch {
156
+ return false;
157
+ }
158
+ }
159
+ export function randomState() {
160
+ return base64url(randomBytes(16));
161
+ }
package/dist/output.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 輸出:`--json` 原樣印 JSON;否則印人看的扁平格式。錯誤一律到 stderr 並以 code 開頭,方便腳本 grep。
2
+ * Output: `--json` prints the JSON as is; otherwise a flat format for people. Errors always go to stderr and start with the code, so scripts can grep them.
3
3
  */
4
4
  import { ApiError } from "./client.js";
5
5
  import { UsageError } from "./args.js";
@@ -15,7 +15,7 @@ function cell(value) {
15
15
  return value.length === 0 ? "[]" : `[${value.length}]`;
16
16
  return "{…}";
17
17
  }
18
- /** 物件陣列 → 對齊欄位的表格(只取頂層原始值欄位,巢狀用 --json 看) */
18
+ /** Array of objects to an aligned table (top-level primitive fields only; use --json for nested values) */
19
19
  function renderTable(rows) {
20
20
  const columns = [];
21
21
  for (const row of rows) {
@@ -67,7 +67,7 @@ export function formatResult(data, json) {
67
67
  return data.map(cell).join("\n");
68
68
  }
69
69
  const obj = data;
70
- // 常見形狀 { sites: [...] }/{ pages: [...] }:單一陣列欄位直接畫表
70
+ // Common shapes { sites: [...] } and { pages: [...] }: a single array field is drawn as a table
71
71
  const keys = Object.keys(obj);
72
72
  if (keys.length === 1 && Array.isArray(obj[keys[0] ?? ""])) {
73
73
  return formatResult(obj[keys[0] ?? ""], false);
@@ -1,11 +1,11 @@
1
1
  /**
2
- * `kanorio types`:從 `/api/v1/collections`(或 Management API `/v1/sites/:id/collections`)自描述 schema
3
- * 產生 TypeScript 型別定義。
2
+ * `kanorio types`: generates TypeScript types from the self-describing schema at `/api/v1/collections` (or the Management API's `/v1/sites/:id/collections`).
3
+ * The output is one file.
4
4
  *
5
- * - `DeliveryAsset`/`assets` map、`expanded` 一層展開、每個集合的 `FieldData`/`Expanded`/`Item`
6
- * - 系統集合的投影欄位(blog `segments`/`toc`/`contentHtml`、taxonomy `counts`)不硬編碼,
7
- * 改讀 `/collections` 回的 `virtualFields`(scope `item` 掛項目頂層、`fieldData` 掛欄位資料)
8
- * - 附上 `/pages`、`/globals/*`、`/forms/*`、`/redirects`、`/site` 的回應型別,一份檔案覆蓋整個 Delivery API
5
+ * - `DeliveryAsset` and the `assets` map, one level of `expanded`, and `FieldData`, `Expanded` and `Item` for each collection
6
+ * - Projected fields of system collections (blog `segments`, `toc`, `contentHtml`; taxonomy `counts`) are not hard-coded:
7
+ * they come from `virtualFields` in the `/collections` response (scope `item` goes on the item, `fieldData` goes in the field data)
8
+ * - Response types for `/pages`, `/globals/*`, `/forms/*`, `/redirects` and `/site` are included, so one file covers the whole Delivery API
9
9
  */
10
10
  function toPascalCase(key) {
11
11
  const parts = key
@@ -25,8 +25,11 @@ function isValidIdent(id) {
25
25
  function formatPropertyKey(id) {
26
26
  return isValidIdent(id) ? id : escapeStringLiteral(id);
27
27
  }
28
- /** 欄位型別 → TS;日期、網址、email 等仍是 string,但以 JSDoc 標出格式讓 IDE 提示 */
28
+ /** Field type to TS; dates, URLs, emails and the like stay string, with a JSDoc note on the format for IDE hints */
29
29
  function fieldTsType(field) {
30
+ // Fields with a fixed shape get their type literal from the server (the system collections' seo)
31
+ if (typeof field.tsType === "string" && field.tsType.trim())
32
+ return { type: field.tsType };
30
33
  switch (field.type) {
31
34
  case "number":
32
35
  return { type: "number" };
@@ -102,18 +105,33 @@ export interface ExpandedReference<TFieldData = Record<string, unknown>> {
102
105
 
103
106
  export interface DeliveryItemEnvelope<TFieldData, TExpanded = Record<string, unknown>> {
104
107
  id: string;
108
+ /** URL slug in the locale of the response */
105
109
  slug: string;
110
+ /**
111
+ * Path of this item's page on the site, in the locale of the response (\`/blog/hello\`, \`/en/blog/hello\`).
112
+ * The same address Kanorio lists in the sitemap. Absent when the item has no page of its own:
113
+ * a custom collection without \`pathTemplate\`, or a category, tag or author whose listing page is off.
114
+ */
115
+ path?: string;
106
116
  publishedAt: string | null;
107
117
  updatedAt: string;
108
118
  fieldData: TFieldData;
109
119
  expanded?: TExpanded;
120
+ /** Multilingual sites: the locale this item was served in (the requested locale when a translation exists, otherwise the primary locale) */
121
+ resolvedLocale?: string;
122
+ /** Multilingual sites: secondary locales that have a published translation of this item */
123
+ availableLocales?: string[];
124
+ /** Multilingual sites: the slug in every live locale */
125
+ localeSlugs?: Record<string, string>;
126
+ /** Multilingual sites, system collections: the path in every live locale (for hreflang and a language switcher) */
127
+ localePaths?: Record<string, string>;
110
128
  }
111
129
 
112
130
  export interface DeliveryListResponse<TItem> {
113
131
  data: TItem[];
114
132
  hasMore: boolean;
115
133
  nextCursor: string | null;
116
- /** 只在請求帶 total=true 時出現 */
134
+ /** Present only when the request asks for it with total=true */
117
135
  total?: number;
118
136
  assets: DeliveryAssetMap;
119
137
  }
@@ -256,7 +274,7 @@ export interface DeliveryRedirect {
256
274
  }
257
275
 
258
276
  export interface DeliveryRedirectsResponse {
259
- /** 完整清單,一次回完 */
277
+ /** The complete list, returned in one response */
260
278
  data: DeliveryRedirect[];
261
279
  hasMore: false;
262
280
  nextCursor: null;
@@ -305,6 +323,7 @@ export function generateCollectionTypes(collections) {
305
323
  const pascal = knownByKey.get(col.key) ?? toPascalCase(col.key);
306
324
  const virtualFieldData = (col.virtualFields ?? []).filter((v) => v.scope === "fieldData");
307
325
  const virtualItem = (col.virtualFields ?? []).filter((v) => v.scope === "item");
326
+ const virtualExpanded = (col.virtualFields ?? []).filter((v) => v.scope === "expanded");
308
327
  if (col.displayName || col.description) {
309
328
  lines.push(`/** ${[col.displayName, col.description].filter(Boolean).join(" — ")} (${col.key}) */`);
310
329
  }
@@ -331,6 +350,16 @@ export function generateCollectionTypes(collections) {
331
350
  const targetType = targetPascal ? `${targetPascal}FieldData` : "Record<string, unknown>";
332
351
  lines.push(rf.type === "reference" ? ` ${prop}?: ExpandedReference<${targetType}> | null;` : ` ${prop}?: Array<ExpandedReference<${targetType}>>;`);
333
352
  }
353
+ const expandedIds = new Set(refFields.map((rf) => rf.id));
354
+ for (const v of virtualExpanded) {
355
+ if (expandedIds.has(v.id))
356
+ continue;
357
+ const targetPascal = v.targetCollectionKey ? knownByKey.get(v.targetCollectionKey) : undefined;
358
+ const targetType = targetPascal ? `${targetPascal}FieldData` : "Record<string, unknown>";
359
+ if (v.description)
360
+ lines.push(` /** ${v.description} */`);
361
+ lines.push(` ${formatPropertyKey(v.id)}?: ExpandedReference<${targetType}> | null;`);
362
+ }
334
363
  lines.push("}");
335
364
  lines.push("");
336
365
  if (virtualItem.length > 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanorio/cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Thin command-line wrapper around the Kanorio Management API (/api/v1), TypeScript codegen (kanorio types), and external frontend doctor (kanorio doctor).",
5
5
  "license": "MIT",
6
6
  "private": false,
@@ -25,7 +25,7 @@
25
25
  },
26
26
  "type": "module",
27
27
  "bin": {
28
- "kanorio": "./dist/bin.js"
28
+ "kanorio": "dist/bin.js"
29
29
  },
30
30
  "files": [
31
31
  "dist",