@nikhil-qeas/api-core 0.5.1 → 0.7.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +141 -5
  3. package/bin/qe-api.js +4 -4
  4. package/dist/contracts/assertions.d.ts +11 -0
  5. package/dist/contracts/assertions.js +31 -0
  6. package/dist/contracts/openapi.d.ts +28 -1
  7. package/dist/contracts/openapi.js +113 -0
  8. package/dist/graphql/graphql.d.ts +86 -0
  9. package/dist/graphql/graphql.js +312 -0
  10. package/dist/http/api-client.d.ts +5 -0
  11. package/dist/http/api-client.js +30 -6
  12. package/dist/http/cookies.d.ts +32 -0
  13. package/dist/http/cookies.js +116 -0
  14. package/dist/http/multipart.d.ts +20 -0
  15. package/dist/http/multipart.js +48 -0
  16. package/dist/http/types.d.ts +16 -0
  17. package/dist/index.d.ts +21 -2
  18. package/dist/index.js +11 -1
  19. package/dist/reporting/redaction.d.ts +4 -0
  20. package/dist/reporting/redaction.js +26 -2
  21. package/dist/security/authorization-matrix.d.ts +55 -0
  22. package/dist/security/authorization-matrix.js +102 -0
  23. package/dist/security/headers.d.ts +21 -0
  24. package/dist/security/headers.js +45 -0
  25. package/dist/security/policy.js +3 -2
  26. package/dist/security/sensitive-data.d.ts +22 -0
  27. package/dist/security/sensitive-data.js +76 -0
  28. package/dist/testing/json-path.d.ts +6 -0
  29. package/dist/testing/json-path.js +97 -0
  30. package/dist/testing/matchers.d.ts +63 -0
  31. package/dist/testing/matchers.js +164 -0
  32. package/dist/testing/spec-cases.d.ts +98 -0
  33. package/dist/testing/spec-cases.js +795 -0
  34. package/dist/testing/wait-for.d.ts +40 -0
  35. package/dist/testing/wait-for.js +82 -0
  36. package/package.json +1 -1
  37. package/templates/project/README.md +55 -6
  38. package/templates/project/__dot__env.example +5 -0
  39. package/templates/project/openapi/openapi.json +243 -19
  40. package/templates/project/src/clients/api.ts +27 -6
  41. package/templates/project/src/{config/environment.ts → environment.ts} +16 -1
  42. package/templates/project/src/observability.ts +1 -1
  43. package/templates/project/src/{contracts/openapi.ts → openapi.ts} +1 -1
  44. package/templates/project/tests/contract/openapi.contract.spec.ts +1 -1
  45. package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
  46. package/templates/project/tests/security/authorization.spec.ts +29 -0
  47. package/templates/project/tests/security/hygiene.spec.ts +37 -0
  48. package/templates/project/tests/security/spec-cases.spec.ts +24 -0
  49. package/templates/project/tests/security/write-protection.spec.ts +60 -0
  50. package/templates/project/tests/smoke/health.spec.ts +3 -3
  51. package/templates/project/tests/support/approved-writes.ts +27 -0
  52. package/templates/project/tests/support/identities.ts +24 -0
  53. package/templates/project/tests/support/mock-api.ts +62 -3
  54. /package/templates/project/{config/mocha.config.json → __dot__mocharc.json} +0 -0
@@ -1,3 +1,4 @@
1
+ import type { MultipartPart } from './multipart.js';
1
2
  export type Method = 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
2
3
  export type Query = Record<string, string | number | boolean | readonly (string | number | boolean)[] | undefined>;
3
4
  export interface ApiRequest {
@@ -8,13 +9,25 @@ export interface ApiRequest {
8
9
  json?: unknown;
9
10
  form?: ReadonlyArray<readonly [string, string]>;
10
11
  rawBody?: string;
12
+ /** A multipart/form-data body: text fields and files. The client sets the Content-Type, boundary included. */
13
+ multipart?: ReadonlyArray<MultipartPart>;
11
14
  timeoutMs?: number;
12
15
  /** Explicitly mark mutation safe to repeat; obtain server-side idempotency support first. */
13
16
  idempotent?: boolean;
17
+ /**
18
+ * Declares that this POST changes nothing on the server (a GraphQL query, a search endpoint that takes a body), so a read-only
19
+ * execution policy lets it through. A claim, not a check: set it only when you are sure. Ignored for every method except POST,
20
+ * because PUT, PATCH and DELETE are writes by definition. `GraphQLClient` sets it for you, and only for documents it can prove are queries.
21
+ */
22
+ readOnly?: boolean;
14
23
  retry?: number;
15
24
  followRedirects?: boolean;
16
25
  /** Send this request without the client's configured `auth` (login, public endpoints, negative authentication tests). */
17
26
  skipAuth?: boolean;
27
+ /** Send this request without the client's cookies, and do not keep the cookies it sets (negative session tests). */
28
+ skipCookies?: boolean;
29
+ /** 'binary' returns the response body as a Uint8Array in `body` (downloads), with an empty `text`. Default: text, parsed as JSON when the content type says so. */
30
+ responseType?: 'auto' | 'binary';
18
31
  }
19
32
  export interface ApiResult<T = unknown> {
20
33
  status: number;
@@ -31,7 +44,10 @@ export interface ApiResult<T = unknown> {
31
44
  export interface RequestContext {
32
45
  readonly method: Method;
33
46
  readonly path: string;
47
+ /** The body as text. For a multipart or other binary body this is a lossy decoding: sign `exactBodyBytes`. */
34
48
  readonly exactBody: string;
49
+ /** The exact bytes that are sent. */
50
+ readonly exactBodyBytes: Uint8Array;
35
51
  readonly requestId: string;
36
52
  readonly attempt: number;
37
53
  }
package/dist/index.d.ts CHANGED
@@ -7,7 +7,16 @@ export { TokenManager } from './auth/token-manager.js';
7
7
  export type { Tokens, TokenProvider, TokenSource } from './auth/token-manager.js';
8
8
  export { clientCredentialsProvider, refreshTokenProvider, OAuth2Error } from './auth/oauth2.js';
9
9
  export type { OAuth2ClientOptions, OAuth2RefreshOptions, OAuth2EndpointOptions } from './auth/oauth2.js';
10
- export { expectStatus, expectClientError, expectResponseTime, expectContract } from './contracts/assertions.js';
10
+ export { expectStatus, expectClientError, expectResponseTime, expectContract, expectBody, expectJsonPath, expectHeader } from './contracts/assertions.js';
11
+ export { match, matches, assertMatches, Matcher } from './testing/matchers.js';
12
+ export type { MatchOptions, MatchResult, MatchType } from './testing/matchers.js';
13
+ export { jsonPath } from './testing/json-path.js';
14
+ export { waitFor, WaitTimeoutError } from './testing/wait-for.js';
15
+ export type { WaitForOptions } from './testing/wait-for.js';
16
+ export { CookieJar } from './http/cookies.js';
17
+ export type { CookieSetOptions } from './http/cookies.js';
18
+ export { encodeMultipart } from './http/multipart.js';
19
+ export type { MultipartPart, EncodedMultipart } from './http/multipart.js';
11
20
  export type { Validator } from './contracts/assertions.js';
12
21
  export { requireEnv, envEnum } from './config/env.js';
13
22
  export { redact } from './reporting/redaction.js';
@@ -24,17 +33,27 @@ export type { ApiMetrics } from './reporting/metrics.js';
24
33
  export { writeJunit } from './reporting/junit.js';
25
34
  export type { TestCaseResult } from './reporting/junit.js';
26
35
  export { OpenApiValidator } from './contracts/openapi.js';
27
- export type { OpenApiDocument, JsonSchemaCompiler, ContractCheck, OpenApiValidatorOptions } from './contracts/openapi.js';
36
+ export type { OpenApiDocument, JsonSchemaCompiler, ContractCheck, RequestCheck, OpenApiValidatorOptions } from './contracts/openapi.js';
28
37
  export { createAjvCompiler, createOpenApiValidator } from './contracts/ajv.js';
29
38
  export type { AjvCompilerOptions } from './contracts/ajv.js';
30
39
  export { ExecutionContext } from './testing/execution-context.js';
31
40
  export type { ExecutionOptions } from './testing/execution-context.js';
32
41
  export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
42
+ export { GraphQLClient, expectGraphQLError, expectGraphQLSuccess, operationKind, parseOperations } from './graphql/graphql.js';
43
+ export type { DocumentOperation, ExpectedGraphQLError, GraphQLAssertOptions, GraphQLClientOptions, GraphQLError, GraphQLRequest, GraphQLResult, GraphQLTransport, OperationKind } from './graphql/graphql.js';
33
44
  export type { SecurityPolicy } from './security/policy.js';
34
45
  export { attachSafeMetadata } from './reporting/allure-adapter.js';
35
46
  export type { AllureWriter } from './reporting/allure-adapter.js';
36
47
  export { MochaResultCollector } from './integrations/mocha.js';
37
48
  export { CoverageRegistry } from './testing/coverage.js';
38
49
  export type { CoverageRecord } from './testing/coverage.js';
50
+ export { OpenApiCases, assertCaseOutcome } from './testing/spec-cases.js';
51
+ export { AuthorizationMatrix } from './security/authorization-matrix.js';
52
+ export type { AuthorizationCell, AuthorizationReport, AuthorizationRule, AuthorizationSubject, AuthorizationMatrixOptions } from './security/authorization-matrix.js';
53
+ export { findSensitiveData, expectNoSensitiveData } from './security/sensitive-data.js';
54
+ export type { SensitiveFinding, SensitiveDataOptions } from './security/sensitive-data.js';
55
+ export { checkSecurityHeaders, expectSecurityHeaders } from './security/headers.js';
56
+ export type { HeaderFinding, SecurityHeaderOptions, Severity } from './security/headers.js';
57
+ export type { GeneratedCase, CaseKind, OperationInfo, OperationRef, OpenApiCasesOptions } from './testing/spec-cases.js';
39
58
  export { OpenApiCoverage } from './testing/openapi-coverage.js';
40
59
  export type { OpenApiCoverageOptions, OpenApiCoverageReport, OpenApiCoverageSnapshot, OperationCoverage, CoverageStat, CoverageThresholds } from './testing/openapi-coverage.js';
package/dist/index.js CHANGED
@@ -2,7 +2,12 @@ export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
2
2
  export { parseRetryAfter } from './http/retry.js';
3
3
  export { TokenManager } from './auth/token-manager.js';
4
4
  export { clientCredentialsProvider, refreshTokenProvider, OAuth2Error } from './auth/oauth2.js';
5
- export { expectStatus, expectClientError, expectResponseTime, expectContract } from './contracts/assertions.js';
5
+ export { expectStatus, expectClientError, expectResponseTime, expectContract, expectBody, expectJsonPath, expectHeader } from './contracts/assertions.js';
6
+ export { match, matches, assertMatches, Matcher } from './testing/matchers.js';
7
+ export { jsonPath } from './testing/json-path.js';
8
+ export { waitFor, WaitTimeoutError } from './testing/wait-for.js';
9
+ export { CookieJar } from './http/cookies.js';
10
+ export { encodeMultipart } from './http/multipart.js';
6
11
  export { requireEnv, envEnum } from './config/env.js';
7
12
  export { redact } from './reporting/redaction.js';
8
13
  export { createRunId } from './testing/run-id.js';
@@ -17,7 +22,12 @@ export { OpenApiValidator } from './contracts/openapi.js';
17
22
  export { createAjvCompiler, createOpenApiValidator } from './contracts/ajv.js';
18
23
  export { ExecutionContext } from './testing/execution-context.js';
19
24
  export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
25
+ export { GraphQLClient, expectGraphQLError, expectGraphQLSuccess, operationKind, parseOperations } from './graphql/graphql.js';
20
26
  export { attachSafeMetadata } from './reporting/allure-adapter.js';
21
27
  export { MochaResultCollector } from './integrations/mocha.js';
22
28
  export { CoverageRegistry } from './testing/coverage.js';
29
+ export { OpenApiCases, assertCaseOutcome } from './testing/spec-cases.js';
30
+ export { AuthorizationMatrix } from './security/authorization-matrix.js';
31
+ export { findSensitiveData, expectNoSensitiveData } from './security/sensitive-data.js';
32
+ export { checkSecurityHeaders, expectSecurityHeaders } from './security/headers.js';
23
33
  export { OpenApiCoverage } from './testing/openapi-coverage.js';
@@ -1,2 +1,6 @@
1
+ /** Splits a property or header name into lowercase words: accountNumber, account_number and Account-Number all give [account, number]. */
2
+ export declare function keyWords(key: string): string[];
3
+ /** Names what a string looks like when it holds a credential, or undefined. Never returns the value itself. */
4
+ export declare function credentialIn(text: string): string | undefined;
1
5
  /** For structured event metadata only. Never attach raw banking payloads to test reports. */
2
6
  export declare function redact(value: unknown, depth?: number): unknown;
@@ -9,13 +9,17 @@ const SECRET_WORDS = new Set(['pin', 'otp', 'cvv', 'cvc', 'pan', 'iban', 'ssn'])
9
9
  const BEARER_OR_BASIC = /\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/]+=*/gi;
10
10
  const JWT = /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g;
11
11
  const CARD_NUMBER = /\b[2-6](?:[ -]?\d){12,18}\b/g;
12
- function isSecretKey(key) {
13
- const words = key
12
+ /** Splits a property or header name into lowercase words: accountNumber, account_number and Account-Number all give [account, number]. */
13
+ export function keyWords(key) {
14
+ return key
14
15
  .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
15
16
  .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
16
17
  .toLowerCase()
17
18
  .split(/[^a-z0-9]+/)
18
19
  .filter(Boolean);
20
+ }
21
+ function isSecretKey(key) {
22
+ const words = keyWords(key);
19
23
  if (words.some(word => SECRET_WORDS.has(word)))
20
24
  return true;
21
25
  const compact = words.join('');
@@ -36,6 +40,26 @@ function passesLuhn(digits) {
36
40
  }
37
41
  return sum % 10 === 0;
38
42
  }
43
+ const BEARER_VALUE = /\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/]{16,}=*/i;
44
+ const PRIVATE_KEY = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
45
+ const CLOUD_KEY = /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/;
46
+ /** Names what a string looks like when it holds a credential, or undefined. Never returns the value itself. */
47
+ export function credentialIn(text) {
48
+ if (text.search(JWT) >= 0)
49
+ return 'a JSON Web Token';
50
+ if (PRIVATE_KEY.test(text))
51
+ return 'a private key';
52
+ if (CLOUD_KEY.test(text))
53
+ return 'a cloud access key';
54
+ if (BEARER_VALUE.test(text))
55
+ return 'an Authorization credential';
56
+ for (const found of text.matchAll(CARD_NUMBER)) {
57
+ const digits = found[0].replace(/[ -]/g, '');
58
+ if (digits.length >= 13 && digits.length <= 19 && passesLuhn(digits))
59
+ return 'a card number';
60
+ }
61
+ return undefined;
62
+ }
39
63
  /** Masks credentials that appear inside free text: Authorization-style values, JWTs and Luhn-valid card numbers. */
40
64
  function scrubString(text) {
41
65
  return text
@@ -0,0 +1,55 @@
1
+ import type { ApiRequest, ApiResult } from '../http/types.js';
2
+ /** Anything that sends requests as one identity: an `ApiClient` configured with that identity's credentials fits. */
3
+ export interface AuthorizationSubject {
4
+ request(request: ApiRequest): Promise<Pick<ApiResult, 'status'>>;
5
+ }
6
+ export interface AuthorizationRule {
7
+ /** Shown in reports. Default: "METHOD /path". */
8
+ name?: string | undefined;
9
+ request: ApiRequest;
10
+ /** Subjects that may do this. */
11
+ allow?: readonly string[] | undefined;
12
+ /** Subjects that must be refused. */
13
+ deny?: readonly string[] | undefined;
14
+ /** Statuses that count as "refused" for this rule. Default 401 and 403: add 404 when the API hides what exists. */
15
+ deniedStatuses?: readonly number[] | undefined;
16
+ }
17
+ export interface AuthorizationMatrixOptions {
18
+ /** Statuses that count as "refused" for every rule. Default 401 and 403. */
19
+ deniedStatuses?: readonly number[] | undefined;
20
+ /** Require every rule to say what happens for every subject. Default false: unlisted subjects are simply not tested. */
21
+ strict?: boolean | undefined;
22
+ }
23
+ export interface AuthorizationCell {
24
+ rule: string;
25
+ subject: string;
26
+ expectation: 'allow' | 'deny';
27
+ /** Undefined when the request itself failed. */
28
+ status?: number | undefined;
29
+ ok: boolean;
30
+ problem?: string | undefined;
31
+ }
32
+ export interface AuthorizationReport {
33
+ cells: AuthorizationCell[];
34
+ violations: AuthorizationCell[];
35
+ ok: boolean;
36
+ /** A table of rules by subjects: ✅ as expected, ❌ not, — not tested. Statuses only, never bodies. */
37
+ toMarkdown(): string;
38
+ }
39
+ /**
40
+ * Checks who may do what: function-level authorization (can a user call an admin operation?) and object-level authorization
41
+ * (can user B read user A's account?). Each rule names the subjects that may and must not; the matrix sends the request as each one
42
+ * and compares the status. Refusals are tested before grants, so a destructive request that wrongly succeeds for a subject who
43
+ * must be denied is reported on its own cell instead of breaking the grants that follow. Use disposable resources for destructive rules.
44
+ */
45
+ export declare class AuthorizationMatrix {
46
+ private readonly subjects;
47
+ private readonly options;
48
+ constructor(subjects: Readonly<Record<string, AuthorizationSubject>>, options?: AuthorizationMatrixOptions);
49
+ run(rules: readonly AuthorizationRule[]): Promise<AuthorizationReport>;
50
+ /** Runs the rules and throws, listing every violation, unless all behave as expected. Returns the report. */
51
+ assert(rules: readonly AuthorizationRule[]): Promise<AuthorizationReport>;
52
+ private plan;
53
+ private execute;
54
+ private table;
55
+ }
@@ -0,0 +1,102 @@
1
+ import assert from 'node:assert/strict';
2
+ /**
3
+ * Checks who may do what: function-level authorization (can a user call an admin operation?) and object-level authorization
4
+ * (can user B read user A's account?). Each rule names the subjects that may and must not; the matrix sends the request as each one
5
+ * and compares the status. Refusals are tested before grants, so a destructive request that wrongly succeeds for a subject who
6
+ * must be denied is reported on its own cell instead of breaking the grants that follow. Use disposable resources for destructive rules.
7
+ */
8
+ export class AuthorizationMatrix {
9
+ subjects;
10
+ options;
11
+ constructor(subjects, options = {}) {
12
+ this.subjects = subjects;
13
+ this.options = options;
14
+ if (!Object.keys(subjects).length)
15
+ throw new Error('An authorization matrix needs at least one subject');
16
+ }
17
+ async run(rules) {
18
+ const plans = this.plan(rules);
19
+ const results = new Map();
20
+ for (const plan of [...plans.filter(entry => entry.expectation === 'deny'), ...plans.filter(entry => entry.expectation === 'allow')]) {
21
+ results.set(plan, await this.execute(plan));
22
+ }
23
+ const cells = plans.map(plan => results.get(plan));
24
+ const violations = cells.filter(cell => !cell.ok);
25
+ return { cells, violations, ok: violations.length === 0, toMarkdown: () => this.table(rules, plans, results) };
26
+ }
27
+ /** Runs the rules and throws, listing every violation, unless all behave as expected. Returns the report. */
28
+ async assert(rules) {
29
+ const report = await this.run(rules);
30
+ if (!report.ok) {
31
+ const shown = report.violations.map(cell => `- ${cell.rule} as ${cell.subject}: ${cell.problem ?? 'unexpected result'}`);
32
+ assert.fail(`Authorization check failed in ${report.violations.length} of ${report.cells.length} cases:\n${shown.join('\n')}\n\n${report.toMarkdown()}`);
33
+ }
34
+ return report;
35
+ }
36
+ plan(rules) {
37
+ const known = Object.keys(this.subjects);
38
+ const plans = [];
39
+ rules.forEach((rule, ruleIndex) => {
40
+ const name = rule.name ?? `${rule.request.method} ${rule.request.path}`;
41
+ const allow = rule.allow ?? [];
42
+ const deny = rule.deny ?? [];
43
+ if (!allow.length && !deny.length)
44
+ throw new Error(`Rule "${name}" names no subjects`);
45
+ for (const subject of [...allow, ...deny])
46
+ if (!known.includes(subject))
47
+ throw new Error(`Rule "${name}" names an unknown subject "${subject}"`);
48
+ for (const subject of allow)
49
+ if (deny.includes(subject))
50
+ throw new Error(`Rule "${name}" both allows and denies "${subject}"`);
51
+ if (this.options.strict === true) {
52
+ const missing = known.filter(subject => !allow.includes(subject) && !deny.includes(subject));
53
+ if (missing.length)
54
+ throw new Error(`Rule "${name}" does not say what happens for: ${missing.join(', ')}`);
55
+ }
56
+ for (const subject of known) {
57
+ if (allow.includes(subject))
58
+ plans.push({ ruleIndex, rule, name, subject, expectation: 'allow' });
59
+ else if (deny.includes(subject))
60
+ plans.push({ ruleIndex, rule, name, subject, expectation: 'deny' });
61
+ }
62
+ });
63
+ return plans;
64
+ }
65
+ async execute(plan) {
66
+ const base = { rule: plan.name, subject: plan.subject, expectation: plan.expectation };
67
+ const subject = this.subjects[plan.subject];
68
+ if (!subject)
69
+ throw new Error(`Unknown subject "${plan.subject}"`);
70
+ let status;
71
+ try {
72
+ status = (await subject.request(plan.rule.request)).status;
73
+ }
74
+ catch (error) {
75
+ return { ...base, ok: false, problem: `the request failed (${error instanceof Error ? error.name : 'error'})` };
76
+ }
77
+ const denied = plan.rule.deniedStatuses ?? this.options.deniedStatuses ?? [401, 403];
78
+ const granted = status >= 200 && status < 300;
79
+ if (status >= 500)
80
+ return { ...base, status, ok: false, problem: `the server failed with HTTP ${status} instead of ${plan.expectation === 'deny' ? 'refusing' : 'answering'}` };
81
+ if (plan.expectation === 'deny') {
82
+ if (denied.includes(status))
83
+ return { ...base, status, ok: true };
84
+ return { ...base, status, ok: false, problem: granted ? `access was granted (HTTP ${status}) but must be refused` : `refused with HTTP ${status}, not ${denied.join(' or ')} (if the API hides what exists, add ${status} to deniedStatuses)` };
85
+ }
86
+ if (status >= 200 && status < 300)
87
+ return { ...base, status, ok: true };
88
+ return { ...base, status, ok: false, problem: denied.includes(status) ? `access was refused (HTTP ${status}) but is allowed` : `unexpected HTTP ${status} for an allowed request` };
89
+ }
90
+ table(rules, plans, results) {
91
+ const names = Object.keys(this.subjects);
92
+ const rows = rules.map((rule, ruleIndex) => {
93
+ const cells = names.map(subject => {
94
+ const plan = plans.find(entry => entry.ruleIndex === ruleIndex && entry.subject === subject);
95
+ const cell = plan ? results.get(plan) : undefined;
96
+ return cell === undefined ? '—' : `${cell.ok ? '✅' : '❌'} ${cell.status ?? 'error'}`;
97
+ });
98
+ return `| ${rule.name ?? `${rule.request.method} ${rule.request.path}`} | ${cells.join(' | ')} |`;
99
+ });
100
+ return [`| Request | ${names.join(' | ')} |`, `|---|${names.map(() => '---').join('|')}|`, ...rows].join('\n');
101
+ }
102
+ }
@@ -0,0 +1,21 @@
1
+ import type { ApiResult } from '../http/types.js';
2
+ export type Severity = 'high' | 'medium' | 'low';
3
+ export interface HeaderFinding {
4
+ header: string;
5
+ severity: Severity;
6
+ problem: string;
7
+ }
8
+ export interface SecurityHeaderOptions {
9
+ /** The API is served over https: require Strict-Transport-Security. Default false (a header sent over http has no effect). */
10
+ https?: boolean | undefined;
11
+ /** The response holds sensitive data: require `Cache-Control: no-store`. Default false. */
12
+ sensitive?: boolean | undefined;
13
+ /** For `expectSecurityHeaders`: the lowest severity that fails. Default 'medium'. */
14
+ failOn?: Severity | undefined;
15
+ /** Headers whose findings are accepted, e.g. ['x-powered-by']. */
16
+ ignore?: readonly string[] | undefined;
17
+ }
18
+ /** Header hygiene for an API response. Findings name the header and the problem; values are never quoted. */
19
+ export declare function checkSecurityHeaders(response: Pick<ApiResult, 'headers'>, options?: SecurityHeaderOptions): HeaderFinding[];
20
+ /** Fails when a finding at or above `failOn` (default medium) exists. */
21
+ export declare function expectSecurityHeaders(response: Pick<ApiResult, 'headers'>, options?: SecurityHeaderOptions): void;
@@ -0,0 +1,45 @@
1
+ import assert from 'node:assert/strict';
2
+ const RANK = { high: 3, medium: 2, low: 1 };
3
+ const SIX_MONTHS_SECONDS = 15_552_000;
4
+ /** Header hygiene for an API response. Findings name the header and the problem; values are never quoted. */
5
+ export function checkSecurityHeaders(response, options = {}) {
6
+ const headers = response.headers;
7
+ const found = [];
8
+ const add = (header, severity, problem) => { found.push({ header, severity, problem }); };
9
+ if (headers['x-content-type-options']?.toLowerCase() !== 'nosniff')
10
+ add('x-content-type-options', 'medium', 'should be "nosniff" so browsers do not guess the content type');
11
+ if (options.https === true) {
12
+ const hsts = headers['strict-transport-security'];
13
+ const maxAge = hsts === undefined ? undefined : /max-age\s*=\s*(\d+)/i.exec(hsts)?.[1];
14
+ if (hsts === undefined)
15
+ add('strict-transport-security', 'medium', 'is missing on an https API');
16
+ else if (maxAge === undefined || Number(maxAge) < SIX_MONTHS_SECONDS)
17
+ add('strict-transport-security', 'medium', 'max-age is missing or shorter than six months');
18
+ }
19
+ if (options.sensitive === true && !/\bno-store\b/i.test(headers['cache-control'] ?? ''))
20
+ add('cache-control', 'medium', 'should include "no-store" for a response with sensitive data');
21
+ const server = headers.server;
22
+ if (server !== undefined && /\d+\.\d+/.test(server))
23
+ add('server', 'low', 'reveals a software version number');
24
+ for (const name of ['x-powered-by', 'x-aspnet-version', 'x-aspnetmvc-version']) {
25
+ if (headers[name] !== undefined)
26
+ add(name, 'low', 'reveals the technology stack');
27
+ }
28
+ const origin = headers['access-control-allow-origin'];
29
+ if (origin === '*') {
30
+ if (headers['access-control-allow-credentials']?.toLowerCase() === 'true')
31
+ add('access-control-allow-origin', 'high', 'is "*" together with credentials allowed: any site can read authenticated responses');
32
+ else
33
+ add('access-control-allow-origin', 'low', 'is "*": any site can read this response');
34
+ }
35
+ const ignored = new Set((options.ignore ?? []).map(name => name.toLowerCase()));
36
+ return found.filter(finding => !ignored.has(finding.header));
37
+ }
38
+ /** Fails when a finding at or above `failOn` (default medium) exists. */
39
+ export function expectSecurityHeaders(response, options = {}) {
40
+ const threshold = RANK[options.failOn ?? 'medium'];
41
+ const failing = checkSecurityHeaders(response, options).filter(finding => RANK[finding.severity] >= threshold);
42
+ if (!failing.length)
43
+ return;
44
+ assert.fail(`Response headers have security problems:\n${failing.map(finding => `- ${finding.header}: ${finding.problem} (${finding.severity})`).join('\n')}`);
45
+ }
@@ -3,8 +3,9 @@ export function assertRequestPolicy(baseUrl, request, policy) {
3
3
  const url = new URL(baseUrl);
4
4
  if (policy.allowedHosts && !policy.allowedHosts.includes(url.hostname))
5
5
  throw new Error('Target hostname is not allowlisted');
6
- if ((policy.production || !policy.allowDestructive) && !['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {
7
- // POST may be a read-only query in some APIs; explicitly approve it at project level.
6
+ // A POST is a read only when the request says so (`readOnly`, e.g. a GraphQL query). PUT, PATCH and DELETE never are.
7
+ const reads = ['GET', 'HEAD', 'OPTIONS'].includes(request.method) || (request.method === 'POST' && request.readOnly === true);
8
+ if ((policy.production || !policy.allowDestructive) && !reads) {
8
9
  throw new Error('Write-capable HTTP request is blocked by the execution policy');
9
10
  }
10
11
  }
@@ -0,0 +1,22 @@
1
+ import type { ApiResult } from '../http/types.js';
2
+ export interface SensitiveFinding {
3
+ /** Where it was found, e.g. `$.users[0].password`. Never includes the value. */
4
+ path: string;
5
+ reason: string;
6
+ }
7
+ export interface SensitiveDataOptions {
8
+ /** Property names (any case or style) that belong in the response, e.g. `access_token` on a login response. */
9
+ allowKeys?: readonly string[] | undefined;
10
+ /** Paths that belong in the response, e.g. `$.access_token` or `$.items[*].apiKey`. A concrete index `[0]` matches `[*]`. */
11
+ allowPaths?: readonly string[] | undefined;
12
+ /** Also look inside string values for credentials: JWTs, private keys, cloud keys, Authorization values, card numbers. Default true. */
13
+ checkValues?: boolean | undefined;
14
+ }
15
+ /**
16
+ * Finds secrets that a response should not expose (excessive data exposure): properties whose names suggest a password, token,
17
+ * key or similar and that carry a value, and string values that look like credentials. Findings name the path and the reason,
18
+ * never the value.
19
+ */
20
+ export declare function findSensitiveData(value: unknown, options?: SensitiveDataOptions): SensitiveFinding[];
21
+ /** Fails when the response body exposes something sensitive. The message lists paths and reasons, never values. */
22
+ export declare function expectNoSensitiveData(response: Pick<ApiResult, 'status' | 'body'>, options?: SensitiveDataOptions): void;
@@ -0,0 +1,76 @@
1
+ import assert from 'node:assert/strict';
2
+ import { credentialIn, keyWords } from '../reporting/redaction.js';
3
+ const WORDS = new Set(['password', 'passwd', 'passphrase', 'secret', 'pin', 'otp', 'cvv', 'cvc', 'ssn', 'token']);
4
+ const COMPOUNDS = ['password', 'passwd', 'passphrase', 'secret', 'privatekey', 'apikey', 'credential', 'token'];
5
+ /** Names that contain a trigger word but are ordinary: `token_type`, pagination cursors. */
6
+ const HARMLESS = new Set(['tokentype', 'nextpagetoken', 'pagetoken', 'nexttoken', 'continuationtoken', 'expiresin']);
7
+ const MAX_DEPTH = 30;
8
+ function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
9
+ function compactName(key) { return keyWords(key).join(''); }
10
+ function suggestsSecret(key) {
11
+ const compact = compactName(key);
12
+ if (HARMLESS.has(compact))
13
+ return false;
14
+ return keyWords(key).some(word => WORDS.has(word)) || COMPOUNDS.some(name => compact.includes(name));
15
+ }
16
+ /** A secret-looking property only matters when it carries something: null, a boolean flag ("hasPassword") and "" expose nothing. */
17
+ function carriesValue(value) {
18
+ if (value === null || value === undefined || typeof value === 'boolean')
19
+ return false;
20
+ if (typeof value === 'string')
21
+ return value.length > 0;
22
+ if (Array.isArray(value))
23
+ return value.length > 0;
24
+ if (isRecord(value))
25
+ return Object.keys(value).length > 0;
26
+ return true;
27
+ }
28
+ function normalizePath(path) { return path.replace(/\[\d+\]/g, '[*]'); }
29
+ /**
30
+ * Finds secrets that a response should not expose (excessive data exposure): properties whose names suggest a password, token,
31
+ * key or similar and that carry a value, and string values that look like credentials. Findings name the path and the reason,
32
+ * never the value.
33
+ */
34
+ export function findSensitiveData(value, options = {}) {
35
+ const allowedKeys = new Set((options.allowKeys ?? []).map(compactName));
36
+ const allowedPaths = new Set((options.allowPaths ?? []).map(normalizePath));
37
+ const checkValues = options.checkValues !== false;
38
+ const findings = [];
39
+ const visit = (node, path, normalized, depth) => {
40
+ if (depth > MAX_DEPTH)
41
+ return;
42
+ if (Array.isArray(node)) {
43
+ node.forEach((item, index) => visit(item, `${path}[${index}]`, `${normalized}[*]`, depth + 1));
44
+ }
45
+ else if (isRecord(node)) {
46
+ for (const [key, child] of Object.entries(node)) {
47
+ const here = `${path}.${key}`;
48
+ const generic = `${normalized}.${key}`;
49
+ if (allowedPaths.has(generic) || allowedKeys.has(compactName(key)))
50
+ continue;
51
+ if (suggestsSecret(key) && carriesValue(child)) {
52
+ findings.push({ path: here, reason: 'the property name suggests a secret' });
53
+ continue;
54
+ }
55
+ visit(child, here, generic, depth + 1);
56
+ }
57
+ }
58
+ else if (typeof node === 'string' && checkValues && !allowedPaths.has(normalized)) {
59
+ const kind = credentialIn(node);
60
+ if (kind !== undefined)
61
+ findings.push({ path, reason: `the value looks like ${kind}` });
62
+ }
63
+ };
64
+ visit(value, '$', '$', 0);
65
+ return findings;
66
+ }
67
+ /** Fails when the response body exposes something sensitive. The message lists paths and reasons, never values. */
68
+ export function expectNoSensitiveData(response, options = {}) {
69
+ const findings = findSensitiveData(response.body, options);
70
+ if (!findings.length)
71
+ return;
72
+ const shown = findings.slice(0, 10).map(finding => `- ${finding.path}: ${finding.reason}`);
73
+ if (findings.length > 10)
74
+ shown.push(`- ... and ${findings.length - 10} more`);
75
+ assert.fail(`The response body (HTTP ${response.status}) exposes sensitive data:\n${shown.join('\n')}`);
76
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Evaluates a small JSONPath subset against parsed JSON and returns every match, in document order:
3
+ * `$`, `.name`, `['name']`, `[0]`, `[-1]`, `[*]`, `.*`, `..name`, `..*`. Filters, slices and unions throw: a path the library cannot
4
+ * evaluate must not silently match nothing. Only a value's own properties are read, never inherited ones.
5
+ */
6
+ export declare function jsonPath(value: unknown, path: string): unknown[];
@@ -0,0 +1,97 @@
1
+ const NAME = /^[A-Za-z0-9_$-]+/;
2
+ const MAX_DEPTH = 100;
3
+ function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
4
+ function hasOwn(value, key) { return Object.prototype.hasOwnProperty.call(value, key); }
5
+ function childrenOf(node) { return Array.isArray(node) ? node : isRecord(node) ? Object.values(node) : []; }
6
+ function parse(path) {
7
+ if (!path.startsWith('$'))
8
+ throw new Error('A JSONPath must start with $');
9
+ const steps = [];
10
+ let index = 1;
11
+ const unsupported = () => { throw new Error(`Unsupported JSONPath syntax at position ${index} in "${path}"`); };
12
+ while (index < path.length) {
13
+ if (path[index] === '.') {
14
+ const descendant = path[index + 1] === '.';
15
+ index += descendant ? 2 : 1;
16
+ if (path[index] === '*') {
17
+ steps.push(descendant ? { kind: 'descendant', name: '*' } : { kind: 'wildcard' });
18
+ index++;
19
+ continue;
20
+ }
21
+ const name = NAME.exec(path.slice(index))?.[0];
22
+ if (name === undefined)
23
+ return unsupported();
24
+ steps.push(descendant ? { kind: 'descendant', name } : { kind: 'child', name });
25
+ index += name.length;
26
+ }
27
+ else if (path[index] === '[') {
28
+ const rest = path.slice(index + 1);
29
+ const wildcard = /^\*\]/.exec(rest);
30
+ const numeric = /^(-?\d+)\]/.exec(rest);
31
+ const single = /^'((?:[^'\\]|\\.)*)'\]/.exec(rest);
32
+ const double = /^"((?:[^"\\]|\\.)*)"\]/.exec(rest);
33
+ const text = single ?? double;
34
+ if (wildcard) {
35
+ steps.push({ kind: 'wildcard' });
36
+ index += 1 + wildcard[0].length;
37
+ }
38
+ else if (numeric?.[1] !== undefined) {
39
+ steps.push({ kind: 'index', index: Number(numeric[1]) });
40
+ index += 1 + numeric[0].length;
41
+ }
42
+ else if (text?.[1] !== undefined) {
43
+ steps.push({ kind: 'child', name: text[1].replace(/\\(.)/g, '$1') });
44
+ index += 1 + text[0].length;
45
+ }
46
+ else
47
+ return unsupported(); // filters, slices and unions
48
+ }
49
+ else {
50
+ return unsupported();
51
+ }
52
+ }
53
+ return steps;
54
+ }
55
+ function descend(node, name, out, depth) {
56
+ if (depth > MAX_DEPTH)
57
+ return;
58
+ if (isRecord(node) && name !== '*' && hasOwn(node, name))
59
+ out.push(node[name]);
60
+ for (const child of childrenOf(node)) {
61
+ if (name === '*')
62
+ out.push(child);
63
+ descend(child, name, out, depth + 1);
64
+ }
65
+ }
66
+ /**
67
+ * Evaluates a small JSONPath subset against parsed JSON and returns every match, in document order:
68
+ * `$`, `.name`, `['name']`, `[0]`, `[-1]`, `[*]`, `.*`, `..name`, `..*`. Filters, slices and unions throw: a path the library cannot
69
+ * evaluate must not silently match nothing. Only a value's own properties are read, never inherited ones.
70
+ */
71
+ export function jsonPath(value, path) {
72
+ let nodes = [value];
73
+ for (const step of parse(path)) {
74
+ const next = [];
75
+ for (const node of nodes) {
76
+ if (step.kind === 'child') {
77
+ if (isRecord(node) && hasOwn(node, step.name))
78
+ next.push(node[step.name]);
79
+ }
80
+ else if (step.kind === 'index') {
81
+ if (Array.isArray(node)) {
82
+ const position = step.index < 0 ? node.length + step.index : step.index;
83
+ if (position >= 0 && position < node.length)
84
+ next.push(node[position]);
85
+ }
86
+ }
87
+ else if (step.kind === 'wildcard') {
88
+ next.push(...childrenOf(node));
89
+ }
90
+ else {
91
+ descend(node, step.name, next, 0);
92
+ }
93
+ }
94
+ nodes = next;
95
+ }
96
+ return nodes;
97
+ }