requestshield 0.0.0-stage → 1.0.0-stg.276

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.
Files changed (54) hide show
  1. package/README.md +292 -2
  2. package/config/.env.stg +8 -0
  3. package/package.json +25 -4
  4. package/skills/requestshield/SKILL.md +240 -0
  5. package/skills/requestshield/assets/AGENTS.codex.md +107 -0
  6. package/skills/requestshield/references/backend-java-core.md +152 -0
  7. package/skills/requestshield/references/backend-spring-boot.md +158 -0
  8. package/skills/requestshield/references/browser-manual.md +244 -0
  9. package/skills/requestshield/references/browser-seamless.md +213 -0
  10. package/skills/requestshield/references/cli.md +314 -0
  11. package/skills/requestshield/references/integration-planning.md +357 -0
  12. package/skills/requestshield/references/troubleshooting.md +131 -0
  13. package/src/agent-detector.mjs +102 -0
  14. package/src/api-client.mjs +155 -0
  15. package/src/args.mjs +147 -0
  16. package/src/browser-opener.mjs +32 -0
  17. package/src/cli.mjs +115 -0
  18. package/src/command-completion.mjs +10 -0
  19. package/src/command-registry.mjs +151 -0
  20. package/src/commands/agent-setup.mjs +195 -0
  21. package/src/commands/agent-status.mjs +65 -0
  22. package/src/commands/application-mutations.mjs +37 -0
  23. package/src/commands/application-response.mjs +55 -0
  24. package/src/commands/apps-get.mjs +28 -0
  25. package/src/commands/apps-list.mjs +93 -0
  26. package/src/commands/auth-status.mjs +42 -0
  27. package/src/commands/billing.mjs +106 -0
  28. package/src/commands/contract.mjs +59 -0
  29. package/src/commands/keys-create.mjs +22 -0
  30. package/src/commands/mutation-support.mjs +135 -0
  31. package/src/commands/output.mjs +26 -0
  32. package/src/commands/secret-commands.mjs +66 -0
  33. package/src/commands/secret-output.mjs +52 -0
  34. package/src/commands/service-status.mjs +34 -0
  35. package/src/commands/signin.mjs +95 -0
  36. package/src/commands/signout.mjs +14 -0
  37. package/src/commands/update-check.mjs +205 -0
  38. package/src/commands/usage.mjs +72 -0
  39. package/src/config.mjs +200 -0
  40. package/src/entrypoint.mjs +44 -0
  41. package/src/errors.mjs +16 -0
  42. package/src/integration-contract-client.mjs +85 -0
  43. package/src/integration-contract.mjs +114 -0
  44. package/src/main.mjs +6 -0
  45. package/src/oauth-client.mjs +153 -0
  46. package/src/oauth-loopback.mjs +120 -0
  47. package/src/package-profile.mjs +24 -0
  48. package/src/private-path.mjs +33 -0
  49. package/src/secret-output.mjs +121 -0
  50. package/src/service-status-client.mjs +87 -0
  51. package/src/session-files.mjs +192 -0
  52. package/src/session-store.mjs +204 -0
  53. package/src/terminal.mjs +143 -0
  54. package/src/usage-time.mjs +26 -0
@@ -0,0 +1,195 @@
1
+ // @ts-check
2
+
3
+ import { cp, lstat, mkdir, readFile, realpath, rename, rm } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { CliError } from "../errors.mjs";
9
+ import { detectAgents } from "../agent-detector.mjs";
10
+ import { agentSkillPath } from "./agent-status.mjs";
11
+ import { rendererFor } from "../terminal.mjs";
12
+
13
+ /**
14
+ * @param {{ agent?: "codex" | "claude", force: boolean, json?: boolean }} options
15
+ * @param {{ env?: NodeJS.ProcessEnv, homeDir?: string, log: (message: string) => void, sourceDir?: string, executablePath?: string, detectAgents?: () => Promise<Array<"codex" | "claude">>, selectAgent?: (detected: Array<"codex" | "claude">) => Promise<"codex" | "claude">, terminal?: import('../terminal.mjs').TerminalContext }} deps
16
+ */
17
+ export async function setupAgent(options, deps) {
18
+ const agent = await resolveAgent(options.agent, deps, !options.json);
19
+ const destination = agentSkillPath(agent, deps);
20
+ const skillsRoot = path.dirname(destination);
21
+ await mkdir(skillsRoot, { recursive: true });
22
+
23
+ const exists = await pathExists(destination);
24
+ if (exists && !options.force) {
25
+ throw new CliError(`RequestShield skill already exists at ${destination}; use --force to replace it`, {
26
+ code: "SKILL_EXISTS",
27
+ exitCode: 2,
28
+ });
29
+ }
30
+
31
+ // Copy into a staging directory so an interrupted copy cannot leave a
32
+ // partially installed skill at the final destination.
33
+ const staging = path.join(skillsRoot, `.requestshield-${randomUUID()}.tmp`);
34
+ const backup = `${destination}.${randomUUID()}.backup`;
35
+ try {
36
+ const source = deps.sourceDir ?? await resolveSkillSource(deps.executablePath);
37
+ await cp(source, staging, {
38
+ recursive: true,
39
+ errorOnExist: true,
40
+ });
41
+
42
+ // Keep the old installation recoverable until the staged copy is in place.
43
+ if (exists) await rename(destination, backup);
44
+ await rename(staging, destination);
45
+ if (exists) await rm(backup, { recursive: true, force: true });
46
+ } catch (error) {
47
+ await rm(staging, { recursive: true, force: true });
48
+ if (await pathExists(backup)) {
49
+ await rm(destination, { recursive: true, force: true });
50
+ await rename(backup, destination);
51
+ }
52
+ throw error;
53
+ }
54
+ const agentLabel = agent === "codex" ? "Codex" : "Claude";
55
+ const result = { agent, path: destination, status: /** @type {const} */ ("installed") };
56
+ if (options.json) deps.log(JSON.stringify({ data: result }, null, 2));
57
+ else {
58
+ const renderer = rendererFor(deps);
59
+ deps.log([
60
+ renderer.heading("Agent setup", "🤖"),
61
+ renderer.message("success", `Installed RequestShield skill for ${agentLabel}.`),
62
+ renderer.fields([["Path", destination]]),
63
+ renderer.paragraph(`Restart ${agentLabel} or start a new task before using the skill.`),
64
+ ].join("\n\n"));
65
+ }
66
+ return result;
67
+ }
68
+
69
+ /** @param {string} [executablePath] */
70
+ async function resolveSkillSource(executablePath) {
71
+ // Resolve from this module, not the user's cwd or the shell's argv. Following
72
+ // the executable also supports explicitly supplied npm-link test fixtures.
73
+ const executable = await realpath(
74
+ executablePath ?? fileURLToPath(new URL("../main.mjs", import.meta.url)),
75
+ );
76
+ const packageRoot = path.resolve(path.dirname(executable), "..");
77
+ const bundled = path.join(packageRoot, "skills", "requestshield");
78
+ if (await pathExists(path.join(bundled, "SKILL.md"))) return bundled;
79
+
80
+ // Only a source checkout has both the private runner manifest and packaging
81
+ // script. Installed packages must never pick up an unrelated sibling skill.
82
+ const devManifestPath = path.join(packageRoot, "dev", "package.json");
83
+ if (await pathExists(devManifestPath)
84
+ && await pathExists(path.join(packageRoot, "scripts", "package-skill.mjs"))) {
85
+ const devManifest = JSON.parse(await readFile(devManifestPath, "utf8"));
86
+ const canonical = path.resolve(packageRoot, "../skills/requestshield");
87
+ if (devManifest.private === true
88
+ && devManifest.name === "@intellifend/requestshield-dev"
89
+ && await pathExists(path.join(canonical, "SKILL.md"))) return canonical;
90
+ }
91
+ throw new CliError("The RequestShield skill is missing. Reinstall the CLI and try again. If the problem continues, contact support.", {
92
+ code: "SKILL_SOURCE_MISSING",
93
+ });
94
+ }
95
+
96
+ /**
97
+ * Explicit selection bypasses detection. Automatic setup selects a single
98
+ * detected agent or asks the user when both agents are present.
99
+ *
100
+ * @param {"codex" | "claude" | undefined} requested
101
+ * @param {{ env?: NodeJS.ProcessEnv, homeDir?: string, detectAgents?: () => Promise<Array<"codex" | "claude">>, selectAgent?: (detected: Array<"codex" | "claude">) => Promise<"codex" | "claude"> }} deps
102
+ * @param {boolean} allowPrompt
103
+ * @returns {Promise<"codex" | "claude">}
104
+ */
105
+ async function resolveAgent(requested, deps, allowPrompt) {
106
+ // A command-line choice is authoritative and avoids probing the machine.
107
+ if (requested) return requested;
108
+
109
+ const detected = deps.detectAgents
110
+ ? await deps.detectAgents()
111
+ : await detectAgents({ env: deps.env, homeDir: deps.homeDir });
112
+
113
+ if (detected.length === 1) return detected[0];
114
+ if (detected.length === 0) {
115
+ throw new CliError(
116
+ [
117
+ "No supported coding agent detected.",
118
+ "",
119
+ "Choose one explicitly:",
120
+ " requestshield agent setup --codex",
121
+ " requestshield agent setup --claude",
122
+ ].join("\n"),
123
+ { code: "AGENT_NOT_FOUND", exitCode: 2 },
124
+ );
125
+ }
126
+
127
+ // Never choose silently when both agents are present. Interactive users get
128
+ // a prompt; non-interactive callers receive a stable conflict error.
129
+ if (!allowPrompt) {
130
+ throw new CliError("Multiple coding agents detected. Choose --codex or --claude explicitly when using --json.", {
131
+ code: "INSTALL_CONFLICT",
132
+ exitCode: 2,
133
+ });
134
+ }
135
+ const selectAgent = deps.selectAgent ?? promptForAgent;
136
+ const selected = await selectAgent(detected);
137
+ if (!detected.includes(selected)) {
138
+ throw new CliError(`Selected agent is not available: ${selected}`, {
139
+ code: "INVALID_AGENT",
140
+ exitCode: 2,
141
+ });
142
+ }
143
+ return selected;
144
+ }
145
+
146
+ /**
147
+ * Ask an interactive user which detected agent should receive the skill.
148
+ *
149
+ * @returns {Promise<"codex" | "claude">}
150
+ */
151
+ async function promptForAgent() {
152
+ if (process.stdin.isTTY !== true || process.stderr.isTTY !== true) {
153
+ throw new CliError(
154
+ [
155
+ "Multiple coding agents detected.",
156
+ "",
157
+ "Choose one explicitly:",
158
+ " requestshield agent setup --codex",
159
+ " requestshield agent setup --claude",
160
+ ].join("\n"),
161
+ { code: "INSTALL_CONFLICT", exitCode: 2 },
162
+ );
163
+ }
164
+
165
+ const prompt = createInterface({
166
+ input: process.stdin,
167
+ output: process.stderr,
168
+ });
169
+ try {
170
+ process.stderr.write(
171
+ "Multiple coding agents detected.\n\n 1. Codex\n 2. Claude\n\n",
172
+ );
173
+ while (true) {
174
+ const answer = (await prompt.question("Select an agent [1-2]: "))
175
+ .trim()
176
+ .toLowerCase();
177
+ if (answer === "1" || answer === "codex") return "codex";
178
+ if (answer === "2" || answer === "claude") return "claude";
179
+ process.stderr.write("Enter 1 for Codex or 2 for Claude.\n");
180
+ }
181
+ } finally {
182
+ prompt.close();
183
+ }
184
+ }
185
+
186
+ /** @param {string} target */
187
+ async function pathExists(target) {
188
+ try {
189
+ await lstat(target);
190
+ return true;
191
+ } catch (error) {
192
+ if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") return false;
193
+ throw error;
194
+ }
195
+ }
@@ -0,0 +1,65 @@
1
+ // @ts-check
2
+
3
+ import { lstat, readFile, stat } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { rendererFor } from "../terminal.mjs";
7
+
8
+ /** @typedef {"codex" | "claude"} Agent */
9
+ /** @typedef {{ agent: Agent, path: string, status: "installed" | "missing" | "invalid" }} AgentInstallation */
10
+
11
+ /** @param {Agent} agent @param {{ homeDir?: string }} [deps] */
12
+ export function agentSkillPath(agent, deps = {}) {
13
+ return path.join(deps.homeDir ?? os.homedir(), agent === "codex" ? ".agents" : ".claude", "skills", "requestshield");
14
+ }
15
+
16
+ /**
17
+ * Inspect the personal Skill installation only; this does not prove an agent
18
+ * has loaded the Skill, and never probes executables or creates directories.
19
+ * @param {Agent} agent
20
+ * @param {{ homeDir?: string }} [deps]
21
+ * @returns {Promise<AgentInstallation>}
22
+ */
23
+ export async function inspectAgent(agent, deps = {}) {
24
+ const destination = agentSkillPath(agent, deps);
25
+ try {
26
+ await lstat(destination);
27
+ } catch (error) {
28
+ return { agent, path: destination, status: /** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT" ? "missing" : "invalid" };
29
+ }
30
+
31
+ try {
32
+ // stat follows an intentional directory symlink; broken links are invalid.
33
+ if (!(await stat(destination)).isDirectory()) return { agent, path: destination, status: "invalid" };
34
+ const contents = await readFile(path.join(destination, "SKILL.md"), "utf8");
35
+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(contents);
36
+ const valid = frontmatter !== null
37
+ && /^name:\s*(?:requestshield|"requestshield"|'requestshield')\s*$/m.test(frontmatter[1])
38
+ && frontmatter[2].trim().length > 0;
39
+ return { agent, path: destination, status: valid ? "installed" : "invalid" };
40
+ } catch {
41
+ return { agent, path: destination, status: "invalid" };
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @param {{ agent?: Agent, json?: boolean }} options
47
+ * @param {{ homeDir?: string, log: (message: string) => void, terminal?: import('../terminal.mjs').TerminalContext }} deps
48
+ */
49
+ export async function showAgentStatus(options, deps) {
50
+ const agents = options.agent ? [options.agent] : /** @type {Agent[]} */ (["codex", "claude"]);
51
+ const result = await Promise.all(agents.map((agent) => inspectAgent(agent, deps)));
52
+ if (options.json) {
53
+ deps.log(JSON.stringify({ data: result }, null, 2));
54
+ } else {
55
+ const renderer = rendererFor(deps);
56
+ deps.log([
57
+ renderer.heading("Agent Skills", "🤖"),
58
+ renderer.table(["AGENT", "STATUS", "PATH"], result.map(installation => [
59
+ installation.agent === "codex" ? "Codex" : "Claude", installation.status, installation.path,
60
+ ])),
61
+ renderer.muted(renderer.paragraph("This checks installed Skill files, not whether an agent has loaded them.")),
62
+ ].join("\n\n"));
63
+ }
64
+ return result;
65
+ }
@@ -0,0 +1,37 @@
1
+ // @ts-check
2
+ import { parseApplicationResponse } from "./application-response.mjs";
3
+ import { outputContext, printApplication } from "./output.mjs";
4
+ import { confirmAction, mutationKey, parseAccepted, printAccepted, validateHttpStatus, withMutationRecovery } from "./mutation-support.mjs";
5
+
6
+ /** @typedef {import('./mutation-support.mjs').MutationResponse} MutationResponse */
7
+ /** @typedef {import('./mutation-support.mjs').CommandOutput & {sessions: {loadToken(): Promise<string>}}} Dependencies */
8
+
9
+ /** @param {{appKey: string, name: string, json?: boolean, yes?: boolean, idempotencyKey?: string}} options
10
+ * @param {Dependencies & {api: {renameApp(token: string, appKey: string, options: {name: string, idempotencyKey: string}): Promise<MutationResponse>}}} deps
11
+ */
12
+ export async function renameApp(options, deps) {
13
+ deps = outputContext(options, deps);
14
+ const idempotencyKey = mutationKey(options.idempotencyKey);
15
+ const token = await deps.sessions.loadToken();
16
+ const application = await withMutationRecovery(idempotencyKey, deps, async () => {
17
+ const result = await deps.api.renameApp(token, options.appKey, {name: options.name, idempotencyKey});
18
+ validateHttpStatus(result, 200);
19
+ return parseApplicationResponse(result.body, options.appKey);
20
+ });
21
+ printApplication(application, options, deps);
22
+ return application;
23
+ }
24
+
25
+ /** @param {{appKey: string, enabled: boolean, json?: boolean, yes?: boolean, idempotencyKey?: string}} options
26
+ * @param {Dependencies & {api: {setAppEnabled(token: string, appKey: string, options: {enabled: boolean, idempotencyKey: string}): Promise<MutationResponse>}}} deps
27
+ */
28
+ export async function setAppEnabled(options, deps) {
29
+ deps = outputContext(options, deps);
30
+ if (!options.enabled) await confirmAction(options, deps, `Disable application ${options.appKey}?`, "DISABLE");
31
+ const idempotencyKey = mutationKey(options.idempotencyKey);
32
+ const token = await deps.sessions.loadToken();
33
+ await withMutationRecovery(idempotencyKey, deps, async () => {
34
+ parseAccepted(await deps.api.setAppEnabled(token, options.appKey, {enabled: options.enabled, idempotencyKey}));
35
+ });
36
+ return printAccepted(options.enabled ? "Application enable" : "Application disable", options.appKey, deps, options);
37
+ }
@@ -0,0 +1,55 @@
1
+ // @ts-check
2
+ import { CliError } from "../errors.mjs";
3
+
4
+ export const APPLICATION_STATUSES = new Set(["attention_required", "pending", "disabled", "revoked", "enabled"]);
5
+
6
+ /** @typedef {{appKey: string, name: string, status: string, createdAt: string, updatedAt: string}} Application */
7
+
8
+ /** Construct metadata from the implemented API schema; never relay extra fields.
9
+ * @param {unknown} value @param {string} [requestedAppKey] @returns {Application}
10
+ */
11
+ export function parseApplication(value, requestedAppKey) {
12
+ const data = responseObject(value);
13
+ const {appKey, name, status, createdAt, updatedAt} = data;
14
+ if (typeof appKey !== "string" || !/^[A-Za-z0-9._~-]{1,128}$/.test(appKey)) {
15
+ throw invalidResponse("The application response contained an invalid App Key");
16
+ }
17
+ if (requestedAppKey !== undefined && appKey !== requestedAppKey) {
18
+ throw invalidResponse("The application response did not match the requested App Key");
19
+ }
20
+ if (typeof name !== "string" || !name.trim() || [...name].length > 100 || /[\p{Cc}\p{Cs}]/u.test(name)) {
21
+ throw invalidResponse("The application response contained an invalid name");
22
+ }
23
+ if (typeof status !== "string" || !APPLICATION_STATUSES.has(status)) {
24
+ throw invalidResponse("The application response contained an unsupported status");
25
+ }
26
+ if (!isTimestamp(createdAt) || !isTimestamp(updatedAt)) {
27
+ throw invalidResponse("The application response contained invalid timestamps");
28
+ }
29
+ return {appKey, name, status, createdAt, updatedAt};
30
+ }
31
+
32
+ /** @param {unknown} body @param {string} requestedAppKey */
33
+ export function parseApplicationResponse(body, requestedAppKey) {
34
+ return parseApplication(responseObject(body).data, requestedAppKey);
35
+ }
36
+
37
+ /** @param {unknown} value @returns {Record<string, unknown>} */
38
+ export function responseObject(value) {
39
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
40
+ throw invalidResponse("The API response did not contain the expected object");
41
+ }
42
+ return /** @type {Record<string, unknown>} */ (value);
43
+ }
44
+
45
+ /** @param {unknown} value @returns {value is string} */
46
+ function isTimestamp(value) {
47
+ return typeof value === "string"
48
+ && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value)
49
+ && Number.isFinite(Date.parse(value));
50
+ }
51
+
52
+ /** @param {string} message */
53
+ export function invalidResponse(message) {
54
+ return new CliError(message, {code: "INVALID_RESPONSE"});
55
+ }
@@ -0,0 +1,28 @@
1
+ // @ts-check
2
+
3
+ import { parseApplicationResponse } from "./application-response.mjs";
4
+ import { printApplication } from "./output.mjs";
5
+
6
+ /**
7
+ * @param {{ appKey: string, json?: boolean }} options
8
+ * @param {{ api: { getApp(accessToken: string, appKey: string): Promise<{body: unknown}> }, sessions: { loadToken(): Promise<string> }, log: (message: string) => void, terminal?: import('../terminal.mjs').TerminalContext }} deps
9
+ */
10
+ export async function getApp(options, deps) {
11
+ const app = await fetchApp(options.appKey, deps);
12
+ printApplication(app, options, deps);
13
+ return app;
14
+ }
15
+
16
+ /** @param {string} appKey @param {Pick<Parameters<typeof getApp>[1], 'api' | 'sessions'>} deps */
17
+ export async function fetchApp(appKey, deps) {
18
+ const accessToken =
19
+ await deps.sessions.loadToken();
20
+
21
+ const result =
22
+ await deps.api.getApp(accessToken, appKey);
23
+
24
+ const app =
25
+ parseApplicationResponse(result.body, appKey);
26
+
27
+ return app;
28
+ }
@@ -0,0 +1,93 @@
1
+ // @ts-check
2
+
3
+ import { CliError } from "../errors.mjs";
4
+ import { getCommandInvocation } from "../config.mjs";
5
+ import { rendererFor } from "../terminal.mjs";
6
+ import { invalidResponse, parseApplication, responseObject } from "./application-response.mjs";
7
+
8
+ const HEADERS = ["APP KEY", "NAME", "STATUS"];
9
+ const MAX_PAGES = 100;
10
+
11
+ /** @typedef {{ appKey: string, name: string, status: string, createdAt: string, updatedAt: string }} App */
12
+
13
+ /**
14
+ * @param {{json: boolean, limit?: number, cursor?: string, all?: boolean}} options
15
+ * @param {{api: {listApps(accessToken: string, options: {limit?: number, cursor?: string}): Promise<{body: unknown}>}, sessions: {loadToken(): Promise<string>}, log: (message: string) => void, profile?: import('../config.mjs').Profile, terminal?: import('../terminal.mjs').TerminalContext}} deps
16
+ */
17
+ export async function listApps(options, deps) {
18
+ const result = await collectApps(options, deps);
19
+ const {data: apps, nextCursor} = result;
20
+ if (options.json) deps.log(JSON.stringify(result, null, 2));
21
+ else {
22
+ const renderer = rendererFor(deps);
23
+ const sections = [renderer.heading("Applications", "📦")];
24
+ if (apps.length === 0) {
25
+ sections.push(renderer.paragraph(nextCursor === null && !options.cursor
26
+ ? "No applications are available to this account."
27
+ : "No applications were returned on this page."));
28
+ } else {
29
+ sections.push(renderer.table(HEADERS, apps.map(app => [app.appKey, app.name, app.status])));
30
+ }
31
+ if (nextCursor !== null) sections.push(
32
+ renderer.paragraph("More applications are available. Continue with this command or use --all:"),
33
+ renderer.command(` ${getCommandInvocation(deps.profile)} app list --cursor ${nextCursor}`),
34
+ );
35
+ deps.log(sections.join("\n\n"));
36
+ }
37
+ return result;
38
+ }
39
+
40
+ /** @param {{limit?: number, cursor?: string, all?: boolean}} options
41
+ * @param {Pick<Parameters<typeof listApps>[1], 'api' | 'sessions'>} deps */
42
+ export async function collectApps(options, deps) {
43
+ /** @type {App[]} */
44
+ const apps = [];
45
+ let cursor = options.cursor;
46
+ let nextCursor = null;
47
+ const seen = new Set(cursor ? [cursor] : []);
48
+ for (let page = 0; page < MAX_PAGES; page++) {
49
+ // Long traversals can cross token expiry; each page may refresh safely.
50
+ const accessToken = await deps.sessions.loadToken();
51
+ const result = await deps.api.listApps(accessToken, {
52
+ ...(options.limit !== undefined ? {limit: options.limit} : {}),
53
+ ...(cursor !== undefined ? {cursor} : {}),
54
+ });
55
+ const parsed = parseApps(result.body);
56
+ if (parsed.data.length > (options.limit ?? 50)) throw invalidResponse("The applications response exceeded the requested page size");
57
+ apps.push(...parsed.data);
58
+ nextCursor = parsed.nextCursor;
59
+ if (nextCursor !== null && seen.has(nextCursor)) {
60
+ throw new CliError("The API repeated an application cursor; pagination stopped without returning partial results", {code: "PAGINATION_STALLED"});
61
+ }
62
+ if (!options.all || nextCursor === null) break;
63
+ seen.add(nextCursor);
64
+ cursor = nextCursor;
65
+ if (page === MAX_PAGES - 1) {
66
+ throw new CliError("Application pagination exceeded 100 pages; use --limit and --cursor to retrieve individual pages", {code: "PAGINATION_LIMIT"});
67
+ }
68
+ }
69
+
70
+ return {data: apps, nextCursor};
71
+ }
72
+
73
+ /** @param {unknown} body @returns {{ data: App[], nextCursor: string | null }} */
74
+ function parseApps(body) {
75
+ const {data, nextCursor} = responseObject(body);
76
+
77
+ if (!Array.isArray(data)) {
78
+ throw new CliError("The applications response did not contain a data array", {
79
+ code: "INVALID_RESPONSE",
80
+ });
81
+ }
82
+
83
+ if (nextCursor !== null && (typeof nextCursor !== "string" || !/^[A-Za-z0-9_-]{1,1024}$/.test(nextCursor))) {
84
+ throw new CliError("The applications response contained an invalid nextCursor", {
85
+ code: "INVALID_RESPONSE",
86
+ });
87
+ }
88
+
89
+ // Rebuild every item from approved metadata so unexpected API fields never reach output.
90
+ const apps = data.map(entry => parseApplication(entry));
91
+
92
+ return { data: apps, nextCursor };
93
+ }
@@ -0,0 +1,42 @@
1
+ // @ts-check
2
+
3
+ import { rendererFor } from "../terminal.mjs";
4
+
5
+ /** @param {{json?: boolean}} options
6
+ * @param {{sessions: {status(): Promise<import('../session-store.mjs').SessionStatus>}, log: (message: string) => void, terminal?: import('../terminal.mjs').TerminalContext}} deps
7
+ */
8
+ export async function showAuthStatus({ json = false }, deps) {
9
+ const status = await deps.sessions.status();
10
+ // Rebuild the output so future storage fields can never expose credentials.
11
+ const result = {
12
+ state: status.state, localOnly: true,
13
+ ...(["valid", "expired", "refresh_uncertain"].includes(status.state) ? {
14
+ expiresAt: status.expiresAt, scopes: status.scopes ? [...status.scopes] : [],
15
+ } : {}),
16
+ };
17
+ if (json) {
18
+ deps.log(JSON.stringify(result, null, 2));
19
+ return;
20
+ }
21
+ const descriptions = {
22
+ signed_out: "signed out",
23
+ valid: "locally valid",
24
+ expired: "continue with your next command to renew sign-in",
25
+ refresh_uncertain: "sign in again to continue",
26
+ config_mismatch: "saved session belongs to different configuration; sign in again",
27
+ invalid: "saved session is invalid; sign in again",
28
+ configuration_error: "sign-in is unavailable; update the CLI or contact support",
29
+ };
30
+ const renderer = rendererFor(deps);
31
+ /** @type {Array<[string, string]>} */
32
+ const fields = [
33
+ ["Session (local)", descriptions[result.state]],
34
+ ];
35
+ if (result.expiresAt !== undefined) fields.push(["Access token expires at", new Date(result.expiresAt).toUTCString()]);
36
+ if (result.scopes) fields.push(["Granted scopes", result.scopes.join(" ")]);
37
+ deps.log([
38
+ renderer.heading("Authentication", "👤"),
39
+ renderer.fields(fields),
40
+ renderer.muted(renderer.paragraph("This is local status; online session validity was not checked.")),
41
+ ].join("\n\n"));
42
+ }
@@ -0,0 +1,106 @@
1
+ // @ts-check
2
+ import { validateAppKey } from "../args.mjs";
3
+ import { utcTimestamp } from "../usage-time.mjs";
4
+ import { rendererFor } from "../terminal.mjs";
5
+ import { invalidResponse, responseObject } from "./application-response.mjs";
6
+ import { printData } from "./output.mjs";
7
+
8
+ const STATUSES = new Set(["unsubscribed", "creating", "checkout_pending", "active", "past_due", "canceled", "failed", "customer_pending", "customer_failed"]);
9
+ const STATUS_LABELS = new Map([
10
+ ["unsubscribed", "Not subscribed"], ["creating", "Setting up"], ["checkout_pending", "Checkout pending"],
11
+ ["active", "Active"], ["past_due", "Past due"], ["canceled", "Canceled"], ["failed", "Setup failed"],
12
+ ["customer_pending", "Account setup pending"], ["customer_failed", "Account setup failed"],
13
+ ]);
14
+
15
+ /** @param {{appKey: string, json?: boolean}} options
16
+ * @param {{api: {getBilling(token: string, appKey: string): Promise<{body: unknown}>}, sessions: {loadToken(): Promise<string>}, log(message: string): void, terminal?: import('../terminal.mjs').TerminalContext}} deps
17
+ */
18
+ export async function showBilling(options, deps) {
19
+ validateAppKey(options.appKey);
20
+ const token = await deps.sessions.loadToken();
21
+ const result = await deps.api.getBilling(token, options.appKey);
22
+ const data = parseBillingResponse(result.body, options.appKey);
23
+ if (options.json) printData(data, deps);
24
+ else {
25
+ const renderer = rendererFor(deps);
26
+ deps.log([renderer.heading("Account billing"), renderer.fields([
27
+ ["App Key", data.appKey], ["Plan", data.plan === null ? "Unavailable" : data.plan === "free" ? "Express" : "Pro"],
28
+ ["Status", STATUS_LABELS.get(data.status) ?? data.status],
29
+ ["Billing period", data.billingPeriod === null ? "Unavailable" : `${data.billingPeriod.start} to ${data.billingPeriod.end}`],
30
+ ["Usage (approximate)", data.usage === null ? "Unavailable" : `${quantity(data.usage)} / ${quantity(data.includedAllowance)} included calls`],
31
+ ["Remaining quota", `${quantity(data.remainingQuota)}${data.remainingQuota === null ? "" : " calls"}`],
32
+ ["Overage", `${quantity(data.overage)}${data.overage === null ? "" : " calls"}`],
33
+ ["Estimated cost", data.estimatedCost === null ? "Unavailable" : `${money(data.estimatedCost.totalAmountMinor, data.estimatedCost.currency)} before taxes`],
34
+ ["Base charge", data.estimatedCost === null ? "Unavailable" : money(data.estimatedCost.baseAmountMinor, data.estimatedCost.currency)],
35
+ ["Estimated overage cost", data.estimatedCost === null ? "Unavailable" : money(data.estimatedCost.overageAmountMinor, data.estimatedCost.currency)],
36
+ ["Reported at", data.reportedAt], ["Usage through", data.usageThrough ?? "Unavailable"],
37
+ ]), renderer.paragraph("Totals cover all applications in your account. Calls are authenticated API v2 token verification requests, including rejected requests and retries. API v1 and service errors are excluded."),
38
+ renderer.paragraph("Usage, remaining quota and overage are approximate. Data may be delayed or incomplete; the usage cutoff is not a guarantee of complete reporting."),
39
+ renderer.paragraph("Estimated cost includes the period's base charge and usage reported so far, before taxes. This is not a final invoice.")].join("\n\n"));
40
+ }
41
+ return data;
42
+ }
43
+
44
+ /** Validate and copy only the public billing contract; the server owns all billing calculations.
45
+ * @param {unknown} body @param {string} appKey
46
+ */
47
+ export function parseBillingResponse(body, appKey) {
48
+ const data = responseObject(responseObject(body).data);
49
+ const {status, plan} = data;
50
+ if (data.appKey !== appKey || data.scope !== "account" || typeof status !== "string" || !STATUSES.has(status)
51
+ || (plan !== null && plan !== "free" && plan !== "pro") || data.unit !== "token_verification_requests" || data.approximate !== true) throw invalidBilling();
52
+ const reportedAt = timestamp(data.reportedAt);
53
+ const usageThrough = data.usageThrough === null ? null : timestamp(data.usageThrough);
54
+ const billingPeriod = parsePeriod(data.billingPeriod);
55
+ const includedAllowance = nullableQuantity(data.includedAllowance), usage = nullableQuantity(data.usage);
56
+ const remainingQuota = nullableQuantity(data.remainingQuota), overage = nullableQuantity(data.overage);
57
+ const estimatedCost = parseCost(data.estimatedCost);
58
+ if (usageThrough !== null && (billingPeriod === null || usageThrough < billingPeriod.start || usageThrough > billingPeriod.end || usageThrough > reportedAt)) throw invalidBilling();
59
+ if (plan === null && [billingPeriod, includedAllowance, usage, remainingQuota, overage, usageThrough, estimatedCost].some(value => value !== null)) throw invalidBilling();
60
+ if (plan !== null && (!["active", "past_due"].includes(status) || [billingPeriod, includedAllowance, usage, remainingQuota, overage, usageThrough, estimatedCost].some(value => value === null))) throw invalidBilling();
61
+ return {appKey, scope: /** @type {const} */ ("account"), status, plan, billingPeriod, includedAllowance, usage,
62
+ remainingQuota, overage, unit: /** @type {const} */ ("token_verification_requests"), approximate: /** @type {const} */ (true),
63
+ reportedAt, usageThrough, estimatedCost};
64
+ }
65
+
66
+ /** @param {unknown} value */
67
+ function parsePeriod(value) {
68
+ if (value === null) return null;
69
+ const period = responseObject(value), start = timestamp(period.start), end = timestamp(period.end);
70
+ if (start >= end) throw invalidBilling();
71
+ return {start, end};
72
+ }
73
+
74
+ /** @param {unknown} value */
75
+ function parseCost(value) {
76
+ if (value === null) return null;
77
+ const cost = responseObject(value);
78
+ if (cost.currency !== "USD") throw invalidBilling();
79
+ return {currency: /** @type {const} */ ("USD"), baseAmountMinor: integer(cost.baseAmountMinor),
80
+ overageAmountMinor: integer(cost.overageAmountMinor), totalAmountMinor: integer(cost.totalAmountMinor)};
81
+ }
82
+
83
+ /** @param {unknown} value */
84
+ function timestamp(value) {
85
+ const time = utcTimestamp(value);
86
+ if (time === undefined) throw invalidBilling();
87
+ return new Date(time).toISOString();
88
+ }
89
+
90
+ /** @param {unknown} value */
91
+ function integer(value) {
92
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw invalidBilling();
93
+ return value;
94
+ }
95
+
96
+ /** @param {unknown} value */
97
+ function nullableQuantity(value) { return value === null ? null : integer(value); }
98
+ /** @param {number | null} value */
99
+ function quantity(value) { return value === null ? "Unavailable" : value.toLocaleString("en-US"); }
100
+ /** Decimal placement only: never calculate a price or derive a total in the CLI.
101
+ * @param {number} minor @param {string} currency */
102
+ function money(minor, currency) {
103
+ const digits = String(minor).padStart(3, "0");
104
+ return `${currency} ${digits.slice(0, -2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")}.${digits.slice(-2)}`;
105
+ }
106
+ function invalidBilling() { return invalidResponse("The billing response did not match the requested app or billing schema"); }