@ptkl/toolkit 1.4.2 → 1.4.3

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.
@@ -2,7 +2,7 @@
2
2
  import { Command } from "commander";
3
3
  import { commands } from "../commands/index.js";
4
4
  import Util from "../lib/util.js";
5
- import OAuthError from "../lib/oauth/OAuthError.js";
5
+ import { apiErrorMessage } from "../lib/apiError.js";
6
6
  import OAuthSession from "../lib/oauth/OAuthSession.js";
7
7
  const program = new Command();
8
8
  // Add global --profile option
@@ -33,38 +33,20 @@ program.hook('preAction', async (thisCommand, actionCommand) => {
33
33
  });
34
34
  commands.forEach(c => program.addCommand(c));
35
35
  program.parseAsync(process.argv).catch((err) => {
36
- const { response } = err;
37
36
  let active;
38
37
  try {
39
38
  active = Util.getCurrentProfile();
40
39
  }
41
40
  catch { /* none */ }
42
- const oauthMessage = OAuthSession.describeApiError(err, active);
43
- // Never dump the raw error for OAuth failures: axios errors carry the bearer token.
44
- if (!oauthMessage && !(err instanceof OAuthError)) {
45
- console.log("An error occurred while executing the command.", err);
46
- }
47
- if (err instanceof OAuthError) {
48
- console.error(err.message);
49
- }
50
- else if (oauthMessage) {
51
- console.error(oauthMessage);
52
- }
53
- else if (response && response.data) {
54
- console.error(response.data.message || "An error occurred with the API request.");
55
- }
56
- else {
57
- console.error(err.message || err || "An unknown error occurred.");
58
- }
41
+ console.error(apiErrorMessage(err, active));
59
42
  process.exit(1);
60
43
  });
61
44
  process.on('uncaughtException', (err) => {
62
- const { response } = err;
63
- if (response && response.data) {
64
- console.error(response.data.message);
65
- }
66
- else {
67
- console.error(err.message || String(err));
45
+ let active;
46
+ try {
47
+ active = Util.getCurrentProfile();
68
48
  }
49
+ catch { /* none */ }
50
+ console.error(apiErrorMessage(err, active));
69
51
  process.exit(1);
70
52
  });
@@ -0,0 +1,59 @@
1
+ import { mkdtempSync, mkdirSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { describe, expect, it, vi } from "vitest";
5
+ const home = mkdtempSync(join(tmpdir(), "ptkl-apierr-"));
6
+ process.env.HOME = home;
7
+ mkdirSync(join(home, ".ptkl"));
8
+ const { apiErrorMessage } = await import("../apiError.js");
9
+ const { withProfile } = await import("../scaffold.js");
10
+ const { default: Util } = await import("../util.js");
11
+ const oauth = { name: "o", host: "http://h", project: "p", auth: "oauth", token: "t" };
12
+ const http = (status, data, headers = {}) => ({
13
+ message: `Request failed with status code ${status}`,
14
+ config: { headers: { Authorization: "Bearer secret-token" } },
15
+ response: { status, data, headers },
16
+ });
17
+ const enc = (o) => new TextEncoder().encode(JSON.stringify(o));
18
+ describe("apiErrorMessage", () => {
19
+ it("decodes an ArrayBuffer JSON body", () => {
20
+ const u = enc({ message: "App with ref: x not found" });
21
+ const ab = u.buffer.slice(u.byteOffset, u.byteOffset + u.byteLength);
22
+ expect(apiErrorMessage(http(404, ab))).toBe("App with ref: x not found");
23
+ });
24
+ it("decodes Buffer and Uint8Array bodies", () => {
25
+ expect(apiErrorMessage(http(404, Buffer.from(JSON.stringify({ message: "nope" }))))).toBe("nope");
26
+ expect(apiErrorMessage(http(400, enc({ error_description: "bad" })))).toBe("bad");
27
+ });
28
+ it("reads plain-object and short string bodies", () => {
29
+ expect(apiErrorMessage(http(400, { message: "plain" }))).toBe("plain");
30
+ expect(apiErrorMessage(http(500, "boom"))).toBe("boom");
31
+ });
32
+ it("falls back to the HTTP status", () => {
33
+ expect(apiErrorMessage(http(404, Buffer.from("")))).toBe("HTTP 404");
34
+ expect(apiErrorMessage(http(502, {}))).toBe("HTTP 502");
35
+ });
36
+ it("handles non-HTTP errors", () => {
37
+ expect(apiErrorMessage(new Error("kaput"))).toBe("kaput");
38
+ expect(apiErrorMessage("str")).toBe("str");
39
+ });
40
+ it("returns the OAuth hint on 403", () => {
41
+ const msg = apiErrorMessage(http(403, { message: "Forbidden" }), oauth);
42
+ expect(msg).toMatch(/profile auth --add-scope/);
43
+ });
44
+ it("never leaks headers or tokens", () => {
45
+ for (const e of [http(404, Buffer.from("")), http(403, { message: "Forbidden" }, { authorization: "Bearer secret-token" }), http(401, {}, {})]) {
46
+ expect(apiErrorMessage(e, oauth)).not.toMatch(/secret-token|Bearer/);
47
+ }
48
+ });
49
+ });
50
+ describe("withProfile", () => {
51
+ it("prints the OAuth hint on a 403 and exits 1", async () => {
52
+ vi.spyOn(Util, "getCurrentProfile").mockReturnValue(oauth);
53
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => { });
54
+ const exit = vi.spyOn(process, "exit").mockImplementation((() => undefined));
55
+ await withProfile(async () => { throw http(403, { message: "Forbidden" }); })();
56
+ expect(errSpy.mock.calls[0][0]).toMatch(/lacks a permission[\s\S]*profile auth --add-scope/);
57
+ expect(exit).toHaveBeenCalledWith(1);
58
+ });
59
+ });
@@ -0,0 +1,37 @@
1
+ import OAuthSession from "./oauth/OAuthSession.js";
2
+ function bodyMessage(data) {
3
+ let body = data;
4
+ if (body instanceof ArrayBuffer)
5
+ body = Buffer.from(body);
6
+ else if (ArrayBuffer.isView(body))
7
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
8
+ if (Buffer.isBuffer(body))
9
+ body = body.toString("utf8");
10
+ if (typeof body === "string") {
11
+ try {
12
+ body = JSON.parse(body);
13
+ }
14
+ catch {
15
+ const text = body.trim();
16
+ return text && text.length <= 300 && !text.startsWith("<") ? text : undefined;
17
+ }
18
+ }
19
+ if (body && typeof body === "object") {
20
+ for (const key of ["message", "error_description", "error"]) {
21
+ if (typeof body[key] === "string" && body[key])
22
+ return body[key];
23
+ }
24
+ }
25
+ return undefined;
26
+ }
27
+ /** One-line, user-facing text for a failed command. Never includes headers, request config or tokens. */
28
+ export function apiErrorMessage(err, profile) {
29
+ const hint = OAuthSession.describeApiError(err, profile);
30
+ if (typeof hint === "string")
31
+ return hint;
32
+ const response = err?.response;
33
+ if (response) {
34
+ return bodyMessage(response.data) ?? `HTTP ${response.status}`;
35
+ }
36
+ return err?.message || String(err);
37
+ }
@@ -64,7 +64,7 @@ export default class OAuthSession {
64
64
  }
65
65
  catch (e) {
66
66
  if (e instanceof OAuthError && e.needsLogin) {
67
- throw new OAuthError("invalid_grant", `Your OAuth session for profile '${current.name}' has expired or was revoked. Run \`ptkl profile oauth -n ${current.name} --client-id ${current.client_id} -P ${current.project} -h ${current.host}\` to log in again.`);
67
+ throw new OAuthError("invalid_grant", `Your OAuth session for profile '${current.name}' has expired or was revoked. Run \`ptkl profile auth ${current.name}\` to log in again.`);
68
68
  }
69
69
  throw e;
70
70
  }
@@ -93,10 +93,10 @@ export default class OAuthSession {
93
93
  const named = /scope="([^"]+)"/.exec(challenge)?.[1] ?? res.data?.required_scope ?? res.data?.scope;
94
94
  const missing = typeof named === "string" && named.trim() ? named.trim() : undefined;
95
95
  return `This profile's token lacks ${missing ? `the permission "${missing}"` : "a permission this command needs"}. `
96
- + `Log in again with \`ptkl profile new --add-scope "${missing ?? "<permission>"}"\`, or use an API-user profile (\`--legacy\`) for CI.`;
96
+ + `Log in again with \`ptkl profile auth --add-scope "${missing ?? "<permission>"}"\`, or use an API-user profile (\`--legacy\`) for CI.`;
97
97
  }
98
98
  if (res.status === 401 && OAuthSession.isOAuth(profile)) {
99
- return `The OAuth token was rejected. Run \`ptkl profile oauth\` again to log in${profile ? ` (profile '${profile.name}')` : ""}.`;
99
+ return `The OAuth token was rejected. Run \`ptkl profile auth${profile ? ` ${profile.name}` : ""}\` again to log in.`;
100
100
  }
101
101
  return undefined;
102
102
  }
@@ -184,7 +184,7 @@ describe("OAuthSession", () => {
184
184
  it("tells the user to log in again on invalid_grant", async () => {
185
185
  const p = oauthProfile(mock.base, { expires_at: 1, refresh_token: "dead" });
186
186
  seed(p);
187
- await expect(new OAuthSession().ensureFresh(p)).rejects.toThrow(/ptkl profile oauth/);
187
+ await expect(new OAuthSession().ensureFresh(p)).rejects.toThrow(/ptkl profile auth/);
188
188
  });
189
189
  it("logout revokes the refresh token and clears stored tokens", async () => {
190
190
  const p = oauthProfile(mock.base);
@@ -1,4 +1,5 @@
1
1
  import Util from "./util.js";
2
+ import { apiErrorMessage } from "./apiError.js";
2
3
  import OutputFormatCommand from "../commands/outputCommand.js";
3
4
  // Re-exported so new commands only need to import from this one module.
4
5
  export { OutputFormatCommand };
@@ -42,9 +43,12 @@ export function withProfile(fn) {
42
43
  return await fn(profile, ...args);
43
44
  }
44
45
  catch (err) {
45
- const response = err?.response;
46
- const message = response?.data?.message ?? err?.message ?? String(err);
47
- console.error(message);
46
+ let active;
47
+ try {
48
+ active = Util.getCurrentProfile();
49
+ }
50
+ catch { /* none */ }
51
+ console.error(apiErrorMessage(err, active));
48
52
  process.exit(1);
49
53
  }
50
54
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptkl/toolkit",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
4
4
  "description": "A command-line toolkit for managing Protokol platform applications, profiles, functions, and components",
5
5
  "keywords": [
6
6
  "protokol",