requestshield 0.1.2 → 0.1.4

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.
@@ -0,0 +1,118 @@
1
+ # Troubleshooting
2
+
3
+ Work outward from the request, not from the code. Most reports of "RequestShield is
4
+ broken" are one of four things: the browser never attached a token, CORS stripped the
5
+ header, the backend never verified it, or one token was verified twice.
6
+
7
+ ## First three checks
8
+
9
+ ```bash
10
+ requestshield server # platform healthy or degraded?
11
+ requestshield apps get <app-key> # status: ready (no traffic yet) or active?
12
+ requestshield credentials status <app-key> # provisioned and active?
13
+ ```
14
+
15
+ `status: ready` means the platform has never seen traffic for that key — the integration
16
+ is not wired up yet, so debugging backend enforcement logic is premature. Start at the
17
+ browser.
18
+
19
+ Run `credentials status` even when the pre-edit Credentials check in
20
+ `integration-planning.md` passed during the install. That check greps the **local
21
+ shell**; it says nothing about what the deployed backend actually receives, and a secret
22
+ can be rotated, or missed by the deploy environment, after it passed. This is the check
23
+ that answers `consume_unauthorized`.
24
+
25
+ ## Reason codes
26
+
27
+ `result.getReason().getCode()` returns a stable code, safe to log. Use codes to explain
28
+ a decision, never to amend one.
29
+
30
+ The table below is a working list, not the authoritative one — the customer
31
+ documentation owns that. Check a code against it before quoting a meaning to the user,
32
+ and treat a code that is not listed here as unrecognised rather than guessing from its
33
+ name.
34
+
35
+ | Code | Means | Usual cause |
36
+ | --- | --- | --- |
37
+ | `ok` | Verified and consumed | — |
38
+ | `missing_token` | No token reached the backend | Script tag absent or loaded after the request; Seamless path mismatch (case, trailing slash, wrong origin); an uncovered transport (form POST, sendBeacon, sync XHR, `no-cors`); a Manual call site that never attaches the header; CORS not allowing `X-IntelliFend-Token`; or CSP missing `worker-src blob:` so `getToken()` returns empty. |
39
+ | `unknown_customer` | App Key not recognised | Typo, deactivated key, or browser and backend configured with different App Keys. |
40
+ | `token_tampered` | Token failed integrity checks | Something modified the value in transit — a proxy rewriting headers, or application code trimming or re-encoding it. Pass the value through unchanged. |
41
+ | `token_expired` | Token too old | The page held a token instead of obtaining a fresh one per request, or a very slow round trip. |
42
+ | `token_replayed` | Already consumed | The same token verified twice: a retry reusing the first token, or two verification paths on one request (`@RequestShieldProtected` plus a manual `verify()`, or a filter plus a controller). |
43
+ | `consume_unauthorized` | Backend credentials rejected | API Secret wrong, rotated, or not injected — check `credentials status` and the environment variable. |
44
+ | `invalid_request` | Malformed verification request | Usually a mis-set `challenge-server-url`. |
45
+ | `not_found` | Token unknown to the platform | Cross-environment mismatch — a staging page's token verified against production, or the reverse. |
46
+ | `service_unavailable` | Platform unreachable | Check `requestshield server`. See degraded behaviour below. |
47
+
48
+ ## "It blocks everything"
49
+
50
+ Almost always `missing_token` or `unknown_customer`. Confirm in this order — each step is
51
+ cheap and rules out a whole class:
52
+
53
+ 1. Open the network tab. Does the protected request carry `X-IntelliFend-Token` with a
54
+ non-empty value?
55
+ 2. **Header absent** → browser half. Seamless: compare the requested URL against
56
+ `data-protect` character for character — case and trailing slash are significant — and
57
+ check the transport is `fetch` or async XHR from page scope. Manual: find the call
58
+ site, and every retry path.
59
+ 3. **Header absent on a cross-origin request only** → CORS. The API's
60
+ `Access-Control-Allow-Headers` must include `X-IntelliFend-Token`, or the browser
61
+ strips it before it ever leaves.
62
+ 4. **Header present but empty** → the SDK ran and could not obtain a token. Check the CSP
63
+ includes `worker-src 'self' blob:` and that `connect-src` allows the challenge host,
64
+ then check `requestshield server`. (In Manual mode an empty token means the header
65
+ should be omitted, not sent empty — see `browser-manual.md`.)
66
+ 5. **Header present and populated** → backend half. Compare the App Key on both sides
67
+ character for character, then confirm the secret is actually injected at runtime.
68
+
69
+ ## "It blocks nothing"
70
+
71
+ Enumerate rather than assuming the browser is at fault:
72
+
73
+ - The endpoint is in `MONITOR` mode — evaluating and always continuing. Protection-shaped,
74
+ not protection.
75
+ - The decision is computed but only logged, never enforced.
76
+ - Verification happens after the mutation has already been performed.
77
+ - Application code overrides `isAllowed()` from a reason code — a separate decision table
78
+ in application code removes the protection.
79
+ - The backend never verifies at all: a browser-only install. Grep for the client or the
80
+ annotation before trusting a claim that the backend is wired up.
81
+ - Results are `isDegraded()` — the platform was unreachable and requests were allowed by
82
+ the availability policy.
83
+
84
+ ## Degraded results are allowed by design
85
+
86
+ When the Challenge Server cannot be reached, `verify()` returns a result that is
87
+ **allowed** and **degraded**. Availability is deliberately chosen over enforcement so a
88
+ platform outage cannot take down a customer's checkout flow.
89
+
90
+ Communicate the consequence clearly: during a degraded window, traffic passes without
91
+ real verification. Log the degraded rate as its own metric so it is visible, and check
92
+ `requestshield server` when it rises. Never "fix" a degraded result by overriding
93
+ `isAllowed()` — that converts a platform incident into a customer-facing outage.
94
+
95
+ ## Confirming traffic reaches the platform
96
+
97
+ ```bash
98
+ requestshield challenge volume <app-key> --from 2026-08-01T00:00:00Z \
99
+ --to 2026-08-27T23:59:59Z --granularity day
100
+ ```
101
+
102
+ Challenge volume is runtime evidence that the browser/platform half is active. It does
103
+ not prove that the backend enforces a blocking decision. Report static correctness,
104
+ platform traffic, and backend enforcement separately. Use the controlled negative test
105
+ in `SKILL.md` to prove enforcement.
106
+
107
+ ## Secret exposure
108
+
109
+ If the API Secret appears in a repo, a log, a build artifact, or a chat transcript,
110
+ rotate it — deleting the line does not un-expose it:
111
+
112
+ ```bash
113
+ requestshield app key rotate --app-key <app-key>
114
+ ```
115
+
116
+ The App Key is unchanged, so no browser edit is needed. Deploy the new secret to backend
117
+ secret storage; the previous one is deactivated automatically. Warn the user that the new
118
+ secret is displayed once.
@@ -0,0 +1,74 @@
1
+ // @ts-check
2
+
3
+ import { constants } from "node:fs";
4
+ import { access } from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+
8
+ /**
9
+ * Detect supported agents from their executable or local configuration.
10
+ *
11
+ * @param {{ env?: NodeJS.ProcessEnv, homeDir?: string }} [options]
12
+ * @returns {Promise<Array<"codex" | "claude">>}
13
+ */
14
+ export async function detectAgents(options = {}) {
15
+ const env = options.env ?? process.env;
16
+ const homeDir = options.homeDir ?? os.homedir();
17
+ const codexHome = env.CODEX_HOME ?? path.join(homeDir, ".codex");
18
+
19
+ // Executables prove the CLI is on PATH. Configuration files cover desktop
20
+ // installs and agents that were previously configured but are not on PATH.
21
+ const [codexCommand, claudeCommand, codexConfig, claudeConfig, claudeState] =
22
+ await Promise.all([
23
+ commandExists("codex", env),
24
+ commandExists("claude", env),
25
+ pathExists(codexHome),
26
+ pathExists(path.join(homeDir, ".claude")),
27
+ pathExists(path.join(homeDir, ".claude.json")),
28
+ ]);
29
+
30
+ /** @type {Array<"codex" | "claude">} */
31
+ const detected = [];
32
+ if (codexCommand || codexConfig) detected.push("codex");
33
+ if (claudeCommand || claudeConfig || claudeState) detected.push("claude");
34
+ return detected;
35
+ }
36
+
37
+ /**
38
+ * Inspect PATH without starting the coding agent.
39
+ *
40
+ * @param {string} command
41
+ * @param {NodeJS.ProcessEnv} env
42
+ */
43
+ async function commandExists(command, env) {
44
+ const searchPath = env.PATH ?? env.Path ?? "";
45
+ const extensions = process.platform === "win32"
46
+ ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";")
47
+ : [""];
48
+
49
+ for (const directory of searchPath.split(path.delimiter)) {
50
+ if (!directory) continue;
51
+ for (const extension of extensions) {
52
+ try {
53
+ await access(
54
+ path.join(directory, `${command}${extension}`),
55
+ process.platform === "win32" ? constants.F_OK : constants.X_OK,
56
+ );
57
+ return true;
58
+ } catch {
59
+ // Continue through the remaining executable candidates.
60
+ }
61
+ }
62
+ }
63
+ return false;
64
+ }
65
+
66
+ /** @param {string} target */
67
+ async function pathExists(target) {
68
+ try {
69
+ await access(target);
70
+ return true;
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
package/src/args.mjs CHANGED
@@ -1,122 +1,85 @@
1
- // @ts-check
2
-
3
- import { CliError } from "./errors.mjs";
4
-
5
- const HELP = `RequestShield CLI
6
-
7
- Usage:
8
- requestshield [command] [options]
9
-
10
- Commands:
11
- update
12
- check Check for and install the latest CLI version
13
-
14
- auth
15
- signin Sign in to RequestShield
16
- status Show authentication status
17
-
18
- keys
19
- create Create a new application and key pair
20
- deactivate Deactivate application credentials
21
- rotate Rotate the Secret Key for an application
22
-
23
- agent
24
- setup Install the RequestShield Agent Skill
25
- setup --agent codex Install the Skill for Codex
26
- setup --agent claude Install the Skill for Claude
27
- setup --status Show Agent Skill installation status
28
-
29
- contract
30
- get Get the RequestShield integration contract
31
-
32
- apps
33
- list List accessible applications
34
- get <app-key> Get application information
35
- readiness <app-key> Check application readiness
36
-
37
- credentials
38
- status <app-key> Show credential status without exposing secrets
39
-
40
- challenge
41
- volume <app-key> Get challenge volume for an application
42
-
43
- billing
44
- get <app-key> Get billing and plan information
45
-
46
- protect
47
- list <app-key> List protected endpoints
48
- add Add a protected endpoint
49
- remove Remove a protected endpoint
50
-
51
- Options:
52
- -h, --help Show help
53
- -v, --version Show CLI version
54
- --json Output machine-readable JSON`;
55
-
56
- /**
57
- * @typedef {{ command: "help", help: string }
58
- * | { command: "version" }
59
- * | { command: "update-check" }
60
- * | { command: "signin" }
61
- * | { command: "keys-create", yes: boolean }
62
- * | { command: "agent-setup", agent: "codex", force: boolean }} ParsedArgs
63
- */
64
-
65
- /** @param {string[]} argv @returns {ParsedArgs} */
66
- export function parseArgs(argv) {
67
- if (argv.length === 0 || argv.includes("--help") || argv.includes("-h")) {
68
- return { command: "help", help: HELP };
69
- }
70
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v" || argv[0] === "-V")) {
71
- return { command: "version" };
72
- }
73
- if (argv[0] === "update" && argv[1] === "check") {
74
- assertOnly(argv.slice(2), new Set());
75
- return { command: "update-check" };
76
- }
77
- if (argv[0] === "signin") {
78
- assertOnly(argv.slice(1), new Set());
79
- return { command: "signin" };
80
- }
81
- if (argv[0] === "keys" && argv[1] === "create") {
82
- assertOnly(argv.slice(2), new Set(["--yes"]));
83
- return { command: "keys-create", yes: argv.includes("--yes") };
84
- }
85
- if (argv[0] === "agent" && argv[1] === "setup") {
86
- const rest = argv.slice(2);
87
- /** @type {string | undefined} */
88
- let agent;
89
- let force = false;
90
- for (let index = 0; index < rest.length; index++) {
91
- const arg = rest[index];
92
- if (arg === "--force") {
93
- force = true;
94
- } else if (arg === "--agent") {
95
- agent = rest[++index];
96
- if (!agent || agent.startsWith("--")) {
97
- throw new CliError("--agent needs a value", { exitCode: 2 });
98
- }
99
- } else {
100
- throw new CliError(`Unknown option: ${arg}`, { exitCode: 2 });
101
- }
102
- }
103
- if (agent !== "codex") {
104
- throw new CliError("--agent codex is required; no other agent is supported", {
105
- exitCode: 2,
106
- });
107
- }
108
- return { command: "agent-setup", agent: "codex", force };
109
- }
110
- throw new CliError(`Unknown command.\n\n${HELP}`, { exitCode: 2 });
111
- }
112
-
113
- /** @param {string[]} args @param {Set<string>} allowed */
114
- function assertOnly(args, allowed) {
115
- for (const arg of args) {
116
- if (!allowed.has(arg)) {
117
- throw new CliError(`Unknown option: ${arg}`, { exitCode: 2 });
118
- }
119
- }
120
- }
121
-
122
- export { HELP };
1
+ // @ts-check
2
+
3
+ import { CliError } from "./errors.mjs";
4
+
5
+ const HELP = `RequestShield CLI
6
+
7
+ Usage:
8
+ requestshield signin
9
+ requestshield keys create [--yes]
10
+ requestshield agent setup [--force]
11
+ requestshield agent setup --codex [--force]
12
+ requestshield agent setup --claude [--force]
13
+ requestshield update check
14
+ requestshield --help
15
+ requestshield --version`;
16
+
17
+ /**
18
+ * @typedef {{ command: "help", help: string }
19
+ * | { command: "version" }
20
+ * | { command: "update-check" }
21
+ * | { command: "signin" }
22
+ * | { command: "keys-create", yes: boolean }
23
+ * | { command: "agent-setup", agent?: "codex" | "claude", force: boolean }} ParsedArgs
24
+ */
25
+
26
+ /** @param {string[]} argv @returns {ParsedArgs} */
27
+ export function parseArgs(argv) {
28
+ if (argv.length === 0 || argv.includes("--help") || argv.includes("-h")) {
29
+ return { command: "help", help: HELP };
30
+ }
31
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v" || argv[0] === "-V")) {
32
+ return { command: "version" };
33
+ }
34
+ if (argv[0] === "update" && argv[1] === "check") {
35
+ assertOnly(argv.slice(2), new Set());
36
+ return { command: "update-check" };
37
+ }
38
+ if (argv[0] === "signin") {
39
+ assertOnly(argv.slice(1), new Set());
40
+ return { command: "signin" };
41
+ }
42
+ if (argv[0] === "keys" && argv[1] === "create") {
43
+ assertOnly(argv.slice(2), new Set(["--yes"]));
44
+ return { command: "keys-create", yes: argv.includes("--yes") };
45
+ }
46
+ if (argv[0] === "agent" && argv[1] === "setup") {
47
+ const rest = argv.slice(2);
48
+ /** @type {"codex" | "claude" | undefined} */
49
+ let agent;
50
+ let force = false;
51
+ for (let index = 0; index < rest.length; index++) {
52
+ const arg = rest[index];
53
+ if (arg === "--force") {
54
+ force = true;
55
+ } else if (arg === "--codex" || arg === "--claude") {
56
+ if (agent !== undefined) {
57
+ throw new CliError("Only one of --codex or --claude may be provided", {
58
+ code: "INVALID_AGENT",
59
+ exitCode: 2,
60
+ });
61
+ }
62
+ agent = arg === "--codex" ? "codex" : "claude";
63
+ } else {
64
+ throw new CliError(`Unknown option: ${arg}`, { exitCode: 2 });
65
+ }
66
+ }
67
+ return {
68
+ command: "agent-setup",
69
+ ...(agent ? { agent } : {}),
70
+ force,
71
+ };
72
+ }
73
+ throw new CliError(`Unknown command.\n\n${HELP}`, { exitCode: 2 });
74
+ }
75
+
76
+ /** @param {string[]} args @param {Set<string>} allowed */
77
+ function assertOnly(args, allowed) {
78
+ for (const arg of args) {
79
+ if (!allowed.has(arg)) {
80
+ throw new CliError(`Unknown option: ${arg}`, { exitCode: 2 });
81
+ }
82
+ }
83
+ }
84
+
85
+ export { HELP };
package/src/cli.mjs CHANGED
@@ -1,51 +1,51 @@
1
- #!/usr/bin/env node
2
- // @ts-check
3
-
4
- import { parseArgs } from "./args.mjs";
5
- import { ManagementApiClient } from "./api-client.mjs";
6
- import { SessionStore } from "./session-store.mjs";
7
- import { signin } from "./commands/signin.mjs";
8
- import { createKeys } from "./commands/keys-create.mjs";
9
- import { setupAgent } from "./commands/agent-setup.mjs";
10
- import { checkForUpdate } from "./commands/update-check.mjs";
11
- import packageJson from "../package.json" with { type: "json" };
12
-
13
- /**
14
- * @param {string[]} argv
15
- * @param {{ log?: (message: string) => void, api?: ManagementApiClient, sessions?: SessionStore, env?: NodeJS.ProcessEnv, homeDir?: string, sourceDir?: string, wait?: (milliseconds: number) => Promise<unknown>, confirm?: () => Promise<boolean>, fetchImpl?: typeof fetch, confirmUpdate?: () => Promise<boolean>, installLatest?: (packageName: string, version: string) => Promise<void> }} [deps]
16
- */
17
- export async function run(argv, deps = {}) {
18
- const parsed = parseArgs(argv);
19
- const log = deps.log ?? ((message) => console.log(message));
20
- if (parsed.command === "help") return log(parsed.help);
21
- if (parsed.command === "version") return log("requestshield " + packageJson.version);
22
- if (parsed.command === "update-check") {
23
- return checkForUpdate({
24
- currentVersion: packageJson.version,
25
- packageName: packageJson.name,
26
- log,
27
- fetchImpl: deps.fetchImpl,
28
- confirm: deps.confirmUpdate,
29
- install: deps.installLatest,
30
- });
31
- }
32
-
33
- if (parsed.command === "agent-setup") {
34
- return setupAgent(parsed, { log, ...deps });
35
- }
36
-
37
- const env = deps.env ?? process.env;
38
-
39
- const api = deps.api ?? new ManagementApiClient({
40
- baseUrl:
41
- env.REQUESTSHIELD_API_URL ??
42
- "https://api.intellifend.ai",
43
- });
44
-
45
- const sessions = deps.sessions ?? new SessionStore({
46
- env,
47
- homeDir: deps.homeDir,
48
- });
49
- if (parsed.command === "signin") return signin({ api, sessions, log, ...deps });
50
- if (parsed.command === "keys-create") return createKeys(parsed, { api, sessions, log, ...deps });
51
- }
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+
4
+ import { parseArgs } from "./args.mjs";
5
+ import { ManagementApiClient } from "./api-client.mjs";
6
+ import { SessionStore } from "./session-store.mjs";
7
+ import { signin } from "./commands/signin.mjs";
8
+ import { createKeys } from "./commands/keys-create.mjs";
9
+ import { setupAgent } from "./commands/agent-setup.mjs";
10
+ import { checkForUpdate } from "./commands/update-check.mjs";
11
+ import packageJson from "../package.json" with { type: "json" };
12
+
13
+ /**
14
+ * @param {string[]} argv
15
+ * @param {{ log?: (message: string) => void, api?: ManagementApiClient, sessions?: SessionStore, env?: NodeJS.ProcessEnv, homeDir?: string, sourceDir?: string, executablePath?: string, detectAgents?: () => Promise<Array<"codex" | "claude">>, selectAgent?: (detected: Array<"codex" | "claude">) => Promise<"codex" | "claude">, wait?: (milliseconds: number) => Promise<unknown>, confirm?: () => Promise<boolean>, fetchImpl?: typeof fetch, confirmUpdate?: () => Promise<boolean>, installLatest?: (packageName: string, version: string) => Promise<void> }} [deps]
16
+ */
17
+ export async function run(argv, deps = {}) {
18
+ const parsed = parseArgs(argv);
19
+ const log = deps.log ?? ((message) => console.log(message));
20
+ if (parsed.command === "help") return log(parsed.help);
21
+ if (parsed.command === "version") return log("requestshield " + packageJson.version);
22
+ if (parsed.command === "update-check") {
23
+ return checkForUpdate({
24
+ currentVersion: packageJson.version,
25
+ packageName: packageJson.name,
26
+ log,
27
+ fetchImpl: deps.fetchImpl,
28
+ confirm: deps.confirmUpdate,
29
+ install: deps.installLatest,
30
+ });
31
+ }
32
+
33
+ if (parsed.command === "agent-setup") {
34
+ return setupAgent(parsed, { log, ...deps });
35
+ }
36
+
37
+ const env = deps.env ?? process.env;
38
+
39
+ const api = deps.api ?? new ManagementApiClient({
40
+ baseUrl:
41
+ env.REQUESTSHIELD_API_URL ??
42
+ "https://api.intellifend.ai",
43
+ });
44
+
45
+ const sessions = deps.sessions ?? new SessionStore({
46
+ env,
47
+ homeDir: deps.homeDir,
48
+ });
49
+ if (parsed.command === "signin") return signin({ api, sessions, log, ...deps });
50
+ if (parsed.command === "keys-create") return createKeys(parsed, { api, sessions, log, ...deps });
51
+ }