@kanorio/cli 1.1.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 CHANGED
@@ -24,6 +24,14 @@ Without a browser, or in CI and scripts:
24
24
 
25
25
  `kanorio whoami` shows who the credential acts as, its permissions, and the operations it cannot call.
26
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
+
27
35
  ## Any API operation
28
36
 
29
37
  ```bash
package/dist/args.js CHANGED
@@ -77,6 +77,7 @@ export function parseCliArgs(argv) {
77
77
  idempotencyKey: values["idempotency-key"],
78
78
  withToken: values["with-token"] === true,
79
79
  noBrowser: values["no-browser"] === true,
80
+ scope: (values.scope ?? []).flatMap((value) => value.split(/[\s,]+/)).filter(Boolean),
80
81
  },
81
82
  };
82
83
  }
@@ -123,5 +124,6 @@ const OPTIONS = {
123
124
  "idempotency-key": { type: "string" },
124
125
  "with-token": { type: "boolean", default: false },
125
126
  "no-browser": { type: "boolean", default: false },
127
+ scope: { type: "string", multiple: true },
126
128
  force: { type: "boolean", default: false },
127
129
  };
package/dist/commands.js CHANGED
@@ -185,15 +185,23 @@ function openInBrowser(url) {
185
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
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
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_]*$/;
188
190
  async function loginWithBrowser(cli, ctx) {
189
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.`);
190
196
  const log = ctx.log ?? ((line) => void process.stderr.write(`${line}\n`));
191
197
  const listener = await startLoopbackListener();
192
198
  try {
193
199
  const { verifier, challenge } = createPkce();
194
200
  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:");
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:");
197
205
  log(` ${url}`);
198
206
  log("Waiting for approval in the browser (the link works for 5 minutes)…");
199
207
  if (!cli.flags.noBrowser)
@@ -202,7 +210,13 @@ async function loginWithBrowser(cli, ctx) {
202
210
  const tokens = await exchangeAuthorizationCode({ apiUrl, code, verifier, redirectUri: listener.redirectUri, fetchImpl: ctx.fetchImpl, userAgent: ctx.userAgent });
203
211
  const { token: _replaced, ...current } = readConfig(ctx.env);
204
212
  void _replaced;
213
+ const previous = current.oauth;
205
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
+ }
206
220
  // Show the user who is signed in and which sites can be changed; failing to ask does not affect the sign-in
207
221
  const who = await request({
208
222
  apiUrl,
@@ -224,10 +238,14 @@ async function loginWithBrowser(cli, ctx) {
224
238
  }
225
239
  }
226
240
  /**
227
- * `kanorio login`: opens the browser for approval by default (no key to copy).
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.
228
243
  * `--token <pat>` or a PAT on stdin stores that token; `--with-token` pastes one in the terminal (not echoed).
229
244
  */
230
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
+ }
231
249
  if (cli.flags.token !== undefined)
232
250
  return storePersonalToken(cli, ctx, cli.flags.token);
233
251
  if (cli.flags.withToken) {
package/dist/help.js CHANGED
@@ -7,6 +7,10 @@ Auth
7
7
  and permissions, then stores the session (~/.config/kanorio/config.json, 0600).
8
8
  No key is copied or pasted, so a coding assistant can run it for you: it prints the
9
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.
10
14
  login --with-token Paste a personal access token instead (hidden prompt); or pipe it: echo $TOKEN | kanorio login
11
15
  login --token <pat> Store a personal access token given on the command line
12
16
  logout Remove the stored session or token (a browser session is also revoked on the server)
package/dist/oauth.js CHANGED
@@ -34,6 +34,11 @@ export function createPkce() {
34
34
  export function managementResource(apiUrl) {
35
35
  return `${apiUrl.replace(/\/+$/, "")}/api/v1`;
36
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
+ */
37
42
  export function buildAuthorizeUrl(params) {
38
43
  const url = new URL(`${params.apiUrl.replace(/\/+$/, "")}/oauth/authorize`);
39
44
  url.searchParams.set("response_type", "code");
@@ -43,6 +48,8 @@ export function buildAuthorizeUrl(params) {
43
48
  url.searchParams.set("code_challenge_method", "S256");
44
49
  url.searchParams.set("state", params.state);
45
50
  url.searchParams.set("resource", managementResource(params.apiUrl));
51
+ if (params.scopes && params.scopes.length > 0)
52
+ url.searchParams.set("scope", params.scopes.join(" "));
46
53
  return url.toString();
47
54
  }
48
55
  const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title>` +
package/dist/output.js CHANGED
@@ -74,6 +74,26 @@ export function formatResult(data, json) {
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 };
@@ -311,6 +311,10 @@ export interface DeliveryFormSubmitBody {
311
311
  export interface DeliveryFormSubmitResponse {
312
312
  ok: true;
313
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;
314
318
  }
315
319
  `;
316
320
  export function generateCollectionTypes(collections) {
@@ -330,7 +334,8 @@ export function generateCollectionTypes(collections) {
330
334
  lines.push(`export interface ${pascal}FieldData {`);
331
335
  for (const field of col.fields) {
332
336
  const prop = formatPropertyKey(field.id);
333
- 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;
334
339
  if (doc)
335
340
  lines.push(` /** ${doc} */`);
336
341
  lines.push(field.required ? ` ${prop}: ${type};` : ` ${prop}?: ${type} | null;`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanorio/cli",
3
- "version": "1.1.0",
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,