@kanorio/cli 1.0.0 → 1.2.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 +31 -4
- package/dist/args.js +13 -3
- package/dist/bin.js +1 -1
- package/dist/client.js +4 -3
- package/dist/commands.js +258 -27
- package/dist/config.js +63 -5
- package/dist/help.js +23 -4
- package/dist/oauth.js +168 -0
- package/dist/output.js +26 -3
- package/dist/types-codegen.js +44 -10
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -11,9 +11,36 @@ Requires Node.js 20 or later.
|
|
|
11
11
|
|
|
12
12
|
## Sign in
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
+
A browser sign-in starts with the permissions you chose on the approval page. When a command answers `FORBIDDEN` with `reason: missing_scope`, the error names the permission and the command that adds it:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
kanorio login --scope marketing:manage
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The approval page then lists only the added permission; what the CLI already had is kept. You can also allow it in the dashboard: the error's `manageUrl` opens the Kanorio CLI connection, where the requested permission is listed. A personal access token is edited under Account settings > API access instead, and the error links to it.
|
|
34
|
+
|
|
35
|
+
## Any API operation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
kanorio api GET '/sites/<siteId>/posts?limit=5'
|
|
39
|
+
kanorio api POST /sites/<siteId>/posts --file post.json
|
|
40
|
+
kanorio api POST /sites/<siteId>/posts/<postId>/publish
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`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
44
|
|
|
18
45
|
## Common commands
|
|
19
46
|
|
|
@@ -38,7 +65,7 @@ kanorio keys create --site <siteId> --write-env .env.local # issue a serve
|
|
|
38
65
|
|
|
39
66
|
### Server keys
|
|
40
67
|
|
|
41
|
-
`keys create` issues a **server key** (`
|
|
68
|
+
`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
69
|
|
|
43
70
|
### Output and errors
|
|
44
71
|
|
package/dist/args.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
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,11 @@ 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,
|
|
80
|
+
scope: (values.scope ?? []).flatMap((value) => value.split(/[\s,]+/)).filter(Boolean),
|
|
76
81
|
},
|
|
77
82
|
};
|
|
78
83
|
}
|
|
@@ -115,5 +120,10 @@ const OPTIONS = {
|
|
|
115
120
|
switching: { type: "boolean", default: false },
|
|
116
121
|
"write-env": { type: "string" },
|
|
117
122
|
"key-name": { type: "string" },
|
|
123
|
+
data: { type: "string" },
|
|
124
|
+
"idempotency-key": { type: "string" },
|
|
125
|
+
"with-token": { type: "boolean", default: false },
|
|
126
|
+
"no-browser": { type: "boolean", default: false },
|
|
127
|
+
scope: { type: "string", multiple: true },
|
|
118
128
|
force: { type: "boolean", default: false },
|
|
119
129
|
};
|
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
|
-
//
|
|
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
|
|
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
|
-
/**
|
|
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
|
-
*
|
|
3
|
-
*
|
|
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, "
|
|
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 = {}) =>
|
|
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
|
-
/**
|
|
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
|
-
|
|
72
|
-
|
|
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
|
|
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,134 @@ 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
|
+
/** A permission name as the API spells it, for example `marketing:manage` (the API decides which ones exist) */
|
|
189
|
+
const SCOPE_SHAPE = /^[a-z][a-z_]*:[a-z][a-z_]*$/;
|
|
190
|
+
async function loginWithBrowser(cli, ctx) {
|
|
191
|
+
const apiUrl = resolveAuth({ api: cli.flags.api }, ctx.env).apiUrl;
|
|
192
|
+
const scopes = [...new Set(cli.flags.scope)];
|
|
193
|
+
const malformed = scopes.find((scope) => !SCOPE_SHAPE.test(scope));
|
|
194
|
+
if (malformed)
|
|
195
|
+
throw new UsageError(`"${malformed}" is not a permission name. Use the name from the error or from \`kanorio whoami\`, for example --scope marketing:manage.`);
|
|
196
|
+
const log = ctx.log ?? ((line) => void process.stderr.write(`${line}\n`));
|
|
197
|
+
const listener = await startLoopbackListener();
|
|
198
|
+
try {
|
|
199
|
+
const { verifier, challenge } = createPkce();
|
|
200
|
+
const state = randomState();
|
|
201
|
+
const url = buildAuthorizeUrl({ apiUrl, redirectUri: listener.redirectUri, challenge, state, scopes });
|
|
202
|
+
log(scopes.length > 0
|
|
203
|
+
? `Open this link to approve the added permission${scopes.length > 1 ? "s" : ""} (${scopes.join(", ")}) for the CLI:`
|
|
204
|
+
: "Open this link to sign in to Kanorio and choose what the CLI may do:");
|
|
205
|
+
log(` ${url}`);
|
|
206
|
+
log("Waiting for approval in the browser (the link works for 5 minutes)…");
|
|
207
|
+
if (!cli.flags.noBrowser)
|
|
208
|
+
(ctx.openBrowser ?? openInBrowser)(url);
|
|
209
|
+
const code = await listener.waitForCode(state);
|
|
210
|
+
const tokens = await exchangeAuthorizationCode({ apiUrl, code, verifier, redirectUri: listener.redirectUri, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
|
|
211
|
+
const { token: _replaced, ...current } = readConfig(ctx.env);
|
|
212
|
+
void _replaced;
|
|
213
|
+
const previous = current.oauth;
|
|
214
|
+
const path = writeConfig({ ...current, oauth: { ...tokens, apiUrl }, ...(cli.flags.api ? { apiUrl } : {}) }, ctx.env);
|
|
215
|
+
// The session this sign-in replaces is no longer reachable from this machine: revoke it, so the account lists one CLI
|
|
216
|
+
// connection with the permissions just approved instead of the old and the new one side by side. Best effort.
|
|
217
|
+
if (previous && previous.apiUrl === apiUrl && previous.refreshToken !== tokens.refreshToken) {
|
|
218
|
+
await revokeToken({ apiUrl, token: previous.refreshToken, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
|
|
219
|
+
}
|
|
220
|
+
// Show the user who is signed in and which sites can be changed; failing to ask does not affect the sign-in
|
|
221
|
+
const who = await request({
|
|
222
|
+
apiUrl,
|
|
223
|
+
token: tokens.accessToken,
|
|
224
|
+
method: "GET",
|
|
225
|
+
path: "/whoami",
|
|
226
|
+
fetchImpl: ctx.fetchImpl,
|
|
227
|
+
userAgent: ctx.userAgent,
|
|
228
|
+
}).catch(() => null);
|
|
229
|
+
return {
|
|
230
|
+
stored: path,
|
|
231
|
+
apiUrl,
|
|
232
|
+
...(who ? { signedInAs: who.principal, websiteScope: who.websiteScope, websiteIds: who.websiteIds } : {}),
|
|
233
|
+
note: "Signed in. Manage or revoke this connection under Account settings > API access > Authorized apps.",
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
listener.close();
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* `kanorio login`: opens the browser for approval by default (no key to copy). `--scope <permission>` asks for more
|
|
242
|
+
* permissions on top of what the CLI already has; the approval page lists the additions.
|
|
243
|
+
* `--token <pat>` or a PAT on stdin stores that token; `--with-token` pastes one in the terminal (not echoed).
|
|
244
|
+
*/
|
|
245
|
+
const login = async (cli, ctx) => {
|
|
246
|
+
if (cli.flags.scope.length > 0 && (cli.flags.token !== undefined || cli.flags.withToken)) {
|
|
247
|
+
throw new UsageError("--scope asks for permissions during browser sign-in. A token's permissions are set where the token was created.");
|
|
248
|
+
}
|
|
249
|
+
if (cli.flags.token !== undefined)
|
|
250
|
+
return storePersonalToken(cli, ctx, cli.flags.token);
|
|
251
|
+
if (cli.flags.withToken) {
|
|
252
|
+
return storePersonalToken(cli, ctx, await promptSecret("Paste your personal access token (knr_pat_…): ", ctx.stdin));
|
|
253
|
+
}
|
|
254
|
+
const piped = await readPipedToken(ctx.stdin);
|
|
255
|
+
if (piped)
|
|
256
|
+
return storePersonalToken(cli, ctx, piped);
|
|
257
|
+
return loginWithBrowser(cli, ctx);
|
|
98
258
|
};
|
|
99
|
-
|
|
259
|
+
/** Sign out: a browser sign-in is also revoked on the server (a failed revoke does not block; the local tokens are always cleared) */
|
|
260
|
+
const logout = async (cli, ctx) => {
|
|
261
|
+
const session = readConfig(ctx.env).oauth;
|
|
262
|
+
const revoked = session ? await revokeToken({ apiUrl: session.apiUrl, token: session.refreshToken, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent }) : undefined;
|
|
263
|
+
void cli;
|
|
100
264
|
clearToken(ctx.env);
|
|
101
|
-
return { removed: configPath(ctx.env) };
|
|
265
|
+
return { removed: configPath(ctx.env), ...(revoked !== undefined ? { revoked } : {}) };
|
|
102
266
|
};
|
|
103
267
|
const sitesList = async (cli, ctx) => authed(cli, ctx).call("GET", "/sites");
|
|
104
268
|
const sitesGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}`);
|
|
@@ -123,7 +287,7 @@ const sitesCreate = async (cli, ctx) => {
|
|
|
123
287
|
const settingsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/settings`);
|
|
124
288
|
const settingsUpdate = async (cli, ctx) => {
|
|
125
289
|
const settings = cli.flags.file ? readJsonFile(cli.flags.file) : {};
|
|
126
|
-
//
|
|
290
|
+
// Brand identity (including color scheme, effective immediately) goes under settings.brand; layout design (draft) stays at the top level
|
|
127
291
|
const brand = settings.brand ?? {};
|
|
128
292
|
if (cli.flags.brandColor) {
|
|
129
293
|
brand.brandColor = { light: cli.flags.brandColor, dark: cli.flags.brandColorDark ?? cli.flags.brandColor };
|
|
@@ -146,7 +310,7 @@ const settingsUpdate = async (cli, ctx) => {
|
|
|
146
310
|
return authed(cli, ctx).call("PATCH", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/settings`, { body: { settings } });
|
|
147
311
|
};
|
|
148
312
|
const globalsGet = async (cli, ctx) => authed(cli, ctx).call("GET", `/sites/${encodeURIComponent(need(cli, 0, "siteId"))}/globals`);
|
|
149
|
-
/**
|
|
313
|
+
/** Site-wide writes: without --if-unmodified-since, read globals first for contentUpdatedAt (two REST calls, no business logic) */
|
|
150
314
|
async function globalsWrite(cli, ctx, method, suffix, bodyKey, label) {
|
|
151
315
|
if (!cli.flags.file)
|
|
152
316
|
throw new UsageError(`${label} needs --file <${bodyKey}.json>.`);
|
|
@@ -339,8 +503,8 @@ const doctorCheck = async (cli, ctx) => {
|
|
|
339
503
|
const SERVER_KEY_ENV_NAME = "KANORIO_SERVER_KEY";
|
|
340
504
|
const SERVER_KEY_ENV_LINE = /^[ \t]*(?:export[ \t]+)?KANORIO_SERVER_KEY[ \t]*=.*$/;
|
|
341
505
|
/**
|
|
342
|
-
*
|
|
343
|
-
*
|
|
506
|
+
* 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.
|
|
507
|
+
* 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
508
|
*/
|
|
345
509
|
function upsertServerKeyLine(existing, line) {
|
|
346
510
|
const lines = existing.split("\n");
|
|
@@ -352,7 +516,7 @@ function upsertServerKeyLine(existing, line) {
|
|
|
352
516
|
.filter((entry, index) => index === first || !SERVER_KEY_ENV_LINE.test(entry))
|
|
353
517
|
.join("\n");
|
|
354
518
|
}
|
|
355
|
-
/**
|
|
519
|
+
/** Whether the write can succeed: check the file when it exists, otherwise its folder (which must exist and be writable) */
|
|
356
520
|
function assertEnvFileWritable(envFile) {
|
|
357
521
|
const target = existsSync(envFile) ? envFile : dirname(envFile);
|
|
358
522
|
if (target !== envFile && !existsSync(target))
|
|
@@ -364,22 +528,22 @@ function assertEnvFileWritable(envFile) {
|
|
|
364
528
|
throw new UsageError(`${target} is not writable. Fix its permissions, or point --write-env somewhere else.`);
|
|
365
529
|
}
|
|
366
530
|
}
|
|
367
|
-
/**
|
|
531
|
+
/** Whether git ignores the file; null when outside a git repository or without git (cannot tell) */
|
|
368
532
|
function isGitIgnored(file) {
|
|
369
533
|
try {
|
|
370
534
|
execFileSync("git", ["check-ignore", "-q", file], { cwd: dirname(file), stdio: "ignore" });
|
|
371
535
|
return true;
|
|
372
536
|
}
|
|
373
537
|
catch (error) {
|
|
374
|
-
// exit 1
|
|
538
|
+
// exit 1 means not ignored; anything else (128 outside a repository, ENOENT without git) cannot tell
|
|
375
539
|
return error.status === 1 ? false : null;
|
|
376
540
|
}
|
|
377
541
|
}
|
|
378
542
|
/**
|
|
379
|
-
*
|
|
380
|
-
*
|
|
381
|
-
*
|
|
382
|
-
*
|
|
543
|
+
* Issues a server key. With `--write-env` the key is written to the env file and never printed:
|
|
544
|
+
* 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.
|
|
545
|
+
* 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.
|
|
546
|
+
* If the write fails after issuing (permissions changed after the check), the key is printed once instead of being lost.
|
|
383
547
|
*/
|
|
384
548
|
const keysCreate = async (cli, ctx) => {
|
|
385
549
|
const siteId = cli.flags.site ?? cli.positionals[0];
|
|
@@ -414,7 +578,7 @@ const keysCreate = async (cli, ctx) => {
|
|
|
414
578
|
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
579
|
};
|
|
416
580
|
}
|
|
417
|
-
//
|
|
581
|
+
// 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
582
|
if (isNew)
|
|
419
583
|
chmodSync(envFile, 0o600);
|
|
420
584
|
const warnings = [];
|
|
@@ -427,9 +591,76 @@ const keysCreate = async (cli, ctx) => {
|
|
|
427
591
|
void _key;
|
|
428
592
|
return { ...safe, written: envFile, ...(warnings.length > 0 ? { warnings } : {}) };
|
|
429
593
|
};
|
|
594
|
+
const API_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
|
|
595
|
+
/** Reads all of stdin (`--file -`) */
|
|
596
|
+
async function readStdin(stdin) {
|
|
597
|
+
const input = stdin ?? process.stdin;
|
|
598
|
+
return new Promise((resolve, reject) => {
|
|
599
|
+
let data = "";
|
|
600
|
+
input.setEncoding?.("utf8");
|
|
601
|
+
input.on("data", (chunk) => {
|
|
602
|
+
data += chunk;
|
|
603
|
+
});
|
|
604
|
+
input.on("end", () => resolve(data));
|
|
605
|
+
input.on("error", reject);
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* General entry point: calls any Management API operation with the stored credential (like `gh api` and `vercel api`).
|
|
610
|
+
* 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.
|
|
611
|
+
* 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).
|
|
612
|
+
*/
|
|
613
|
+
const apiCall = async (cli, ctx) => {
|
|
614
|
+
const method = need(cli, 0, "method").toUpperCase();
|
|
615
|
+
if (!API_METHODS.includes(method)) {
|
|
616
|
+
throw new UsageError(`Unknown method ${cli.positionals[0]}. Use one of ${API_METHODS.join(", ")}.`);
|
|
617
|
+
}
|
|
618
|
+
const raw = need(cli, 1, "path");
|
|
619
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
|
|
620
|
+
throw new UsageError("Pass a path such as /sites/<siteId>/posts, not a URL. The API origin comes from --api or KANORIO_API_URL.");
|
|
621
|
+
}
|
|
622
|
+
const withoutBase = raw.replace(/^\/?api\/v1(?=\/|\?|$)/, "");
|
|
623
|
+
const [pathname = "", search = ""] = withoutBase.split("?", 2);
|
|
624
|
+
if (!pathname || pathname === "/")
|
|
625
|
+
throw new UsageError("Missing <path>, for example /whoami or /sites/<siteId>/posts.");
|
|
626
|
+
const query = {};
|
|
627
|
+
for (const [key, value] of new URLSearchParams(search))
|
|
628
|
+
query[key] = value;
|
|
629
|
+
if (cli.flags.file && cli.flags.data)
|
|
630
|
+
throw new UsageError("Pass the body with --file or --data, not both.");
|
|
631
|
+
let body;
|
|
632
|
+
if (cli.flags.file === "-") {
|
|
633
|
+
const text = await readStdin(ctx.stdin);
|
|
634
|
+
try {
|
|
635
|
+
body = JSON.parse(text);
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
throw new UsageError("The body read from stdin is not valid JSON.");
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
else if (cli.flags.file) {
|
|
642
|
+
body = readJsonFile(cli.flags.file);
|
|
643
|
+
}
|
|
644
|
+
else if (cli.flags.data !== undefined) {
|
|
645
|
+
try {
|
|
646
|
+
body = JSON.parse(cli.flags.data);
|
|
647
|
+
}
|
|
648
|
+
catch {
|
|
649
|
+
throw new UsageError("--data is not valid JSON.");
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (body !== undefined && method === "GET")
|
|
653
|
+
throw new UsageError("GET takes no body. Put filters in the path's query string.");
|
|
654
|
+
const headers = cli.flags.idempotencyKey ? { "idempotency-key": cli.flags.idempotencyKey } : undefined;
|
|
655
|
+
return authed(cli, ctx).call(method, pathname.startsWith("/") ? pathname : `/${pathname}`, { query, body, headers });
|
|
656
|
+
};
|
|
657
|
+
/** 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) */
|
|
658
|
+
const whoami = async (cli, ctx) => authed(cli, ctx).call("GET", "/whoami", { query: { websiteId: cli.flags.site } });
|
|
430
659
|
export const COMMANDS = {
|
|
431
660
|
login,
|
|
432
661
|
logout,
|
|
662
|
+
api: apiCall,
|
|
663
|
+
whoami,
|
|
433
664
|
types: typesGenerate,
|
|
434
665
|
doctor: doctorCheck,
|
|
435
666
|
"keys create": keysCreate,
|
package/dist/config.js
CHANGED
|
@@ -1,11 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
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
|
|
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
|
-
/**
|
|
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,28 @@ 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 [--
|
|
7
|
-
|
|
8
|
-
|
|
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 --scope <permission> Ask for more permissions on top of what the CLI already has, for example
|
|
11
|
+
--scope marketing:manage (repeat the flag or separate names with commas). The approval
|
|
12
|
+
page lists only the additions. Use it when a command answers FORBIDDEN with
|
|
13
|
+
reason missing_scope; the error names the permission.
|
|
14
|
+
login --with-token Paste a personal access token instead (hidden prompt); or pipe it: echo $TOKEN | kanorio login
|
|
15
|
+
login --token <pat> Store a personal access token given on the command line
|
|
16
|
+
logout Remove the stored session or token (a browser session is also revoked on the server)
|
|
17
|
+
KANORIO_TOKEN=<token> Environment variable; takes precedence over the stored session
|
|
18
|
+
|
|
19
|
+
Any API operation
|
|
20
|
+
api <METHOD> <path> [--file <body.json> | --data '<json>'] [--idempotency-key <key>]
|
|
21
|
+
Call any Management API operation with the stored token and print the JSON response:
|
|
22
|
+
kanorio api GET '/sites/<siteId>/posts?limit=5'
|
|
23
|
+
kanorio api POST /sites/<siteId>/posts --file post.json
|
|
24
|
+
kanorio api POST /sites/<siteId>/posts/<postId>/publish
|
|
25
|
+
<path> is relative to /api/v1 (the API reference lists every operation). --file - reads the body from stdin.
|
|
26
|
+
A coding assistant can run this for you without ever seeing the token.
|
|
27
|
+
whoami [--site <siteId>] Who the stored token acts as, its permissions, and the operations it cannot call (with the reason)
|
|
9
28
|
|
|
10
29
|
Sites
|
|
11
30
|
sites list
|
|
@@ -65,7 +84,7 @@ Sections & Types
|
|
|
65
84
|
|
|
66
85
|
Server keys
|
|
67
86
|
keys create --site <siteId> [--name <account>] [--key-name <label>] [--write-env <.env.local>] [--force]
|
|
68
|
-
Issue a server key (
|
|
87
|
+
Issue a server key (knr_sk_…) so your own server can submit forms, exchange customer sign-in codes and report
|
|
69
88
|
crawler hits on behalf of visitors. The key cannot call the Management API.
|
|
70
89
|
--write-env writes KANORIO_SERVER_KEY=… into that file (created with mode 0600) and does not print the key;
|
|
71
90
|
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,168 @@
|
|
|
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
|
+
/**
|
|
38
|
+
* `scopes` are the permissions this sign-in asks for. Without them the approval page starts from Kanorio's default set
|
|
39
|
+
* (or from what this CLI was already granted); with them it adds these to what was already granted and lists the additions,
|
|
40
|
+
* so the user approves exactly the new permissions. The user can still change the selection on the page.
|
|
41
|
+
*/
|
|
42
|
+
export function buildAuthorizeUrl(params) {
|
|
43
|
+
const url = new URL(`${params.apiUrl.replace(/\/+$/, "")}/oauth/authorize`);
|
|
44
|
+
url.searchParams.set("response_type", "code");
|
|
45
|
+
url.searchParams.set("client_id", CLI_OAUTH_CLIENT_ID);
|
|
46
|
+
url.searchParams.set("redirect_uri", params.redirectUri);
|
|
47
|
+
url.searchParams.set("code_challenge", params.challenge);
|
|
48
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
49
|
+
url.searchParams.set("state", params.state);
|
|
50
|
+
url.searchParams.set("resource", managementResource(params.apiUrl));
|
|
51
|
+
if (params.scopes && params.scopes.length > 0)
|
|
52
|
+
url.searchParams.set("scope", params.scopes.join(" "));
|
|
53
|
+
return url.toString();
|
|
54
|
+
}
|
|
55
|
+
const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title>` +
|
|
56
|
+
`<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>` +
|
|
57
|
+
`<body><h1>${title}</h1><p>${body}</p></body></html>`;
|
|
58
|
+
/** Starts a one-off callback server on a random port of 127.0.0.1 (local only, not exposed) */
|
|
59
|
+
export async function startLoopbackListener(options = {}) {
|
|
60
|
+
let settle = null;
|
|
61
|
+
let expected = null;
|
|
62
|
+
let early = null;
|
|
63
|
+
const server = createServer((req, res) => {
|
|
64
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
65
|
+
if (url.pathname !== CLI_OAUTH_CALLBACK_PATH) {
|
|
66
|
+
res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const finish = (status, title, body, outcome) => {
|
|
70
|
+
res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(page(title, body));
|
|
71
|
+
if (settle) {
|
|
72
|
+
if (outcome.code)
|
|
73
|
+
settle.resolve(outcome.code);
|
|
74
|
+
else
|
|
75
|
+
settle.reject(outcome.error ?? new OAuthLoginError("login_failed", "Sign-in failed."));
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
early = outcome;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
const error = url.searchParams.get("error");
|
|
82
|
+
if (error) {
|
|
83
|
+
const description = url.searchParams.get("error_description") ?? error;
|
|
84
|
+
finish(400, "Sign-in was not completed", "You can close this tab and run <code>kanorio login</code> again.", {
|
|
85
|
+
error: new OAuthLoginError(error, error === "access_denied" ? "Access was not approved." : description),
|
|
86
|
+
});
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const code = url.searchParams.get("code");
|
|
90
|
+
const state = url.searchParams.get("state");
|
|
91
|
+
if (!code || !state || (expected !== null && state !== expected)) {
|
|
92
|
+
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.", {
|
|
93
|
+
error: new OAuthLoginError("invalid_state", "The sign-in response did not match this request."),
|
|
94
|
+
});
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
finish(200, "Kanorio CLI is connected", "You can close this tab and go back to your terminal.", { code });
|
|
98
|
+
});
|
|
99
|
+
await new Promise((resolve, reject) => {
|
|
100
|
+
server.once("error", reject);
|
|
101
|
+
server.listen(0, "127.0.0.1", () => resolve());
|
|
102
|
+
});
|
|
103
|
+
const { port } = server.address();
|
|
104
|
+
const timeoutMs = options.timeoutMs ?? LOGIN_TIMEOUT_MS;
|
|
105
|
+
return {
|
|
106
|
+
redirectUri: `http://127.0.0.1:${port}${CLI_OAUTH_CALLBACK_PATH}`,
|
|
107
|
+
waitForCode(expectedState) {
|
|
108
|
+
expected = expectedState;
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
const timer = setTimeout(() => reject(new OAuthLoginError("timeout", "Timed out waiting for the browser. Run `kanorio login` again.")), timeoutMs);
|
|
111
|
+
timer.unref?.();
|
|
112
|
+
const done = (fn) => (value) => {
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
fn(value);
|
|
115
|
+
};
|
|
116
|
+
settle = { resolve: done(resolve), reject: done(reject) };
|
|
117
|
+
if (early) {
|
|
118
|
+
if (early.code)
|
|
119
|
+
settle.resolve(early.code);
|
|
120
|
+
else
|
|
121
|
+
settle.reject(early.error ?? new OAuthLoginError("login_failed", "Sign-in failed."));
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
},
|
|
125
|
+
close() {
|
|
126
|
+
server.close();
|
|
127
|
+
server.closeAllConnections?.();
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
async function tokenRequest(apiUrl, form, fetchImpl, userAgent) {
|
|
132
|
+
const res = await fetchImpl(`${apiUrl.replace(/\/+$/, "")}/oauth/token`, {
|
|
133
|
+
method: "POST",
|
|
134
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", "user-agent": userAgent },
|
|
135
|
+
body: new URLSearchParams({ ...form, client_id: CLI_OAUTH_CLIENT_ID }).toString(),
|
|
136
|
+
});
|
|
137
|
+
const body = (await res.json().catch(() => ({})));
|
|
138
|
+
if (!res.ok || typeof body.access_token !== "string" || typeof body.refresh_token !== "string") {
|
|
139
|
+
const code = typeof body.error === "string" ? body.error : `http_${res.status}`;
|
|
140
|
+
const description = typeof body.error_description === "string" ? body.error_description : "The authorization server refused the request.";
|
|
141
|
+
throw new OAuthLoginError(code, description);
|
|
142
|
+
}
|
|
143
|
+
const expiresIn = typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : 3600;
|
|
144
|
+
return { accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: Date.now() + expiresIn * 1000 };
|
|
145
|
+
}
|
|
146
|
+
export function exchangeAuthorizationCode(params) {
|
|
147
|
+
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);
|
|
148
|
+
}
|
|
149
|
+
export function refreshTokens(params) {
|
|
150
|
+
return tokenRequest(params.apiUrl, { grant_type: "refresh_token", refresh_token: params.refreshToken, resource: managementResource(params.apiUrl) }, params.fetchImpl ?? fetch, params.userAgent);
|
|
151
|
+
}
|
|
152
|
+
/** Revokes the grant on sign-out (best effort: the local tokens are always cleared, and a failed server-side revoke does not block) */
|
|
153
|
+
export async function revokeToken(params) {
|
|
154
|
+
try {
|
|
155
|
+
const res = await (params.fetchImpl ?? fetch)(`${params.apiUrl.replace(/\/+$/, "")}/oauth/revoke`, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": params.userAgent },
|
|
158
|
+
body: new URLSearchParams({ token: params.token, client_id: CLI_OAUTH_CLIENT_ID }).toString(),
|
|
159
|
+
});
|
|
160
|
+
return res.ok;
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
export function randomState() {
|
|
167
|
+
return base64url(randomBytes(16));
|
|
168
|
+
}
|
package/dist/output.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
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
|
-
/**
|
|
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,13 +67,33 @@ export function formatResult(data, json) {
|
|
|
67
67
|
return data.map(cell).join("\n");
|
|
68
68
|
}
|
|
69
69
|
const obj = data;
|
|
70
|
-
//
|
|
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);
|
|
74
74
|
}
|
|
75
75
|
return renderObject(obj);
|
|
76
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* The credential lacks a permission. Where to add it depends on the credential, so the hint names the exact next step:
|
|
79
|
+
* a browser sign-in asks for the permission again (or the user allows the request in the dashboard), a personal access
|
|
80
|
+
* token is edited in the dashboard.
|
|
81
|
+
*/
|
|
82
|
+
function missingPermissionHint(details) {
|
|
83
|
+
if (!details || typeof details !== "object")
|
|
84
|
+
return null;
|
|
85
|
+
const { reason, requiredScope, credentialKind, manageUrl } = details;
|
|
86
|
+
if (reason !== "missing_scope" || typeof requiredScope !== "string")
|
|
87
|
+
return null;
|
|
88
|
+
if (credentialKind === "OAUTH") {
|
|
89
|
+
const dashboard = typeof manageUrl === "string" ? `, or allow it in the dashboard at ${manageUrl}` : "";
|
|
90
|
+
return `hint: this sign-in was not granted "${requiredScope}". To add it, run: kanorio login --scope ${requiredScope}${dashboard}`;
|
|
91
|
+
}
|
|
92
|
+
if (credentialKind === "PAT" && typeof manageUrl === "string") {
|
|
93
|
+
return `hint: this token was not granted "${requiredScope}". Add it to the token at ${manageUrl}`;
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
77
97
|
export function formatError(error, json) {
|
|
78
98
|
if (error instanceof ApiError) {
|
|
79
99
|
const payload = {
|
|
@@ -94,6 +114,9 @@ export function formatError(error, json) {
|
|
|
94
114
|
lines.push(`retry after ${error.retryAfter}s`);
|
|
95
115
|
if (error.code === "UNAUTHORIZED")
|
|
96
116
|
lines.push("hint: run `kanorio login` or set KANORIO_TOKEN.");
|
|
117
|
+
const permissionHint = missingPermissionHint(error.details);
|
|
118
|
+
if (permissionHint)
|
|
119
|
+
lines.push(permissionHint);
|
|
97
120
|
if (error.code === "CONFLICT")
|
|
98
121
|
lines.push("hint: re-run `pages get` and retry with the new updatedAt.");
|
|
99
122
|
return { text: lines.join("\n"), exitCode: error.exitCode };
|
package/dist/types-codegen.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `kanorio types
|
|
3
|
-
*
|
|
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
|
|
6
|
-
* -
|
|
7
|
-
*
|
|
8
|
-
* -
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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;
|
|
@@ -293,6 +311,10 @@ export interface DeliveryFormSubmitBody {
|
|
|
293
311
|
export interface DeliveryFormSubmitResponse {
|
|
294
312
|
ok: true;
|
|
295
313
|
state?: "closed" | "not_open" | "full";
|
|
314
|
+
/** Id of this submission; absent when state is present */
|
|
315
|
+
submissionId?: string;
|
|
316
|
+
/** Where to send the visitor now, when the form has a redirect after submit; answers are already filled in */
|
|
317
|
+
redirectUrl?: string;
|
|
296
318
|
}
|
|
297
319
|
`;
|
|
298
320
|
export function generateCollectionTypes(collections) {
|
|
@@ -305,13 +327,15 @@ export function generateCollectionTypes(collections) {
|
|
|
305
327
|
const pascal = knownByKey.get(col.key) ?? toPascalCase(col.key);
|
|
306
328
|
const virtualFieldData = (col.virtualFields ?? []).filter((v) => v.scope === "fieldData");
|
|
307
329
|
const virtualItem = (col.virtualFields ?? []).filter((v) => v.scope === "item");
|
|
330
|
+
const virtualExpanded = (col.virtualFields ?? []).filter((v) => v.scope === "expanded");
|
|
308
331
|
if (col.displayName || col.description) {
|
|
309
332
|
lines.push(`/** ${[col.displayName, col.description].filter(Boolean).join(" — ")} (${col.key}) */`);
|
|
310
333
|
}
|
|
311
334
|
lines.push(`export interface ${pascal}FieldData {`);
|
|
312
335
|
for (const field of col.fields) {
|
|
313
336
|
const prop = formatPropertyKey(field.id);
|
|
314
|
-
const { type, doc } = fieldTsType(field);
|
|
337
|
+
const { type, doc: typeDoc } = fieldTsType(field);
|
|
338
|
+
const doc = typeof field.tsDoc === "string" && field.tsDoc.trim() ? field.tsDoc.trim().replaceAll("*/", "*\\/") : typeDoc;
|
|
315
339
|
if (doc)
|
|
316
340
|
lines.push(` /** ${doc} */`);
|
|
317
341
|
lines.push(field.required ? ` ${prop}: ${type};` : ` ${prop}?: ${type} | null;`);
|
|
@@ -331,6 +355,16 @@ export function generateCollectionTypes(collections) {
|
|
|
331
355
|
const targetType = targetPascal ? `${targetPascal}FieldData` : "Record<string, unknown>";
|
|
332
356
|
lines.push(rf.type === "reference" ? ` ${prop}?: ExpandedReference<${targetType}> | null;` : ` ${prop}?: Array<ExpandedReference<${targetType}>>;`);
|
|
333
357
|
}
|
|
358
|
+
const expandedIds = new Set(refFields.map((rf) => rf.id));
|
|
359
|
+
for (const v of virtualExpanded) {
|
|
360
|
+
if (expandedIds.has(v.id))
|
|
361
|
+
continue;
|
|
362
|
+
const targetPascal = v.targetCollectionKey ? knownByKey.get(v.targetCollectionKey) : undefined;
|
|
363
|
+
const targetType = targetPascal ? `${targetPascal}FieldData` : "Record<string, unknown>";
|
|
364
|
+
if (v.description)
|
|
365
|
+
lines.push(` /** ${v.description} */`);
|
|
366
|
+
lines.push(` ${formatPropertyKey(v.id)}?: ExpandedReference<${targetType}> | null;`);
|
|
367
|
+
}
|
|
334
368
|
lines.push("}");
|
|
335
369
|
lines.push("");
|
|
336
370
|
if (virtualItem.length > 0) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kanorio/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.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": "
|
|
28
|
+
"kanorio": "dist/bin.js"
|
|
29
29
|
},
|
|
30
30
|
"files": [
|
|
31
31
|
"dist",
|