@nikhil-qeas/api-core 0.4.1 → 0.5.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 (42) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +133 -12
  3. package/bin/qe-api.js +99 -26
  4. package/dist/auth/oauth2.d.ts +40 -0
  5. package/dist/auth/oauth2.js +138 -0
  6. package/dist/auth/token-manager.d.ts +13 -2
  7. package/dist/auth/token-manager.js +13 -1
  8. package/dist/contracts/ajv.d.ts +15 -0
  9. package/dist/contracts/ajv.js +37 -0
  10. package/dist/contracts/openapi.d.ts +19 -5
  11. package/dist/contracts/openapi.js +109 -26
  12. package/dist/http/api-client.d.ts +20 -2
  13. package/dist/http/api-client.js +68 -11
  14. package/dist/http/retry.d.ts +42 -0
  15. package/dist/http/retry.js +53 -0
  16. package/dist/http/types.d.ts +11 -1
  17. package/dist/index.d.ts +11 -3
  18. package/dist/index.js +4 -0
  19. package/dist/reporting/allure-adapter.d.ts +3 -3
  20. package/dist/reporting/metrics.d.ts +3 -0
  21. package/dist/reporting/metrics.js +6 -4
  22. package/dist/reporting/redaction.js +50 -2
  23. package/dist/testing/openapi-coverage.d.ts +116 -0
  24. package/dist/testing/openapi-coverage.js +296 -0
  25. package/package.json +25 -3
  26. package/templates/project/README.md +53 -0
  27. package/templates/project/__dot__env.example +14 -0
  28. package/templates/project/__dot__gitignore +7 -0
  29. package/templates/project/__dot__gitlab-ci.yml +25 -0
  30. package/templates/project/config/mocha.config.json +8 -0
  31. package/templates/project/eslint.config.mjs +27 -0
  32. package/templates/project/openapi/openapi.json +83 -0
  33. package/templates/project/src/clients/api.ts +32 -0
  34. package/templates/project/src/config/environment.ts +29 -0
  35. package/templates/project/src/contracts/openapi.ts +15 -0
  36. package/templates/project/src/observability.ts +15 -0
  37. package/templates/project/tests/contract/openapi.contract.spec.ts +33 -0
  38. package/templates/project/tests/security/authentication.spec.ts +36 -0
  39. package/templates/project/tests/setup/hooks.ts +17 -0
  40. package/templates/project/tests/smoke/health.spec.ts +17 -0
  41. package/templates/project/tests/support/mock-api.ts +66 -0
  42. package/templates/project/tsconfig.json +14 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,57 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@nikhil-qeas/api-core`. The format follows [Keep a Changelog](https://keepachangelog.com/), and the project uses semantic versioning (while below 1.0, minor versions may contain behavior changes, which are listed under "Changed").
4
+
5
+ ## [0.5.0] - 2026-11-23
6
+
7
+ This release also contains the 0.4.3 fixes below, which were never published on their own.
8
+
9
+ ### Added
10
+
11
+ - **Ajv-backed contract validation.** `createOpenApiValidator(spec)` and `createAjvCompiler()` validate responses against an OpenAPI 3.0 or 3.1 document. The JSON Schema dialect follows the document, standard formats are checked through `ajv-formats`, recursive and mutually recursive component schemas work, and each response schema is compiled once. `errorDetail: 'schema'` adds the violated schema locations to failures; response values and property names are never included. `ajv` and `ajv-formats` are **optional peer dependencies**: install them only if you use these helpers.
12
+ - **Spec-driven endpoint coverage.** `OpenApiCoverage` reads the operations and declared responses from an OpenAPI document and reports which ones the suite exercised, which responses the API returned that the spec does not declare, and which requests match no operation. It offers `assertCoverage()` thresholds for CI, JSON and Markdown reports, and `snapshot()` / `merge()` to combine parallel workers or sharded jobs. Pass its `recordEvent` as `ApiClient`'s `onEvent`.
13
+ - **OAuth2 and automatic re-authentication.** `clientCredentialsProvider()` and `refreshTokenProvider()` for `TokenManager`; `ApiClient` accepts an `auth` option that attaches the token and, on HTTP 401, renews it and resends the request once (for every method, since a 401 means the request was not processed). `skipAuth: true` and an explicit `Authorization` header opt a request out. `TokenManager.invalidate(rejectedToken)` expires only the rejected token, so a burst of 401s renews once. Token requests require https (localhost excepted), never follow redirects, and `OAuth2Error` never carries a response body, secret or token.
14
+ - **`Retry-After` and visible retries.** Retryable responses honor `Retry-After` (seconds or HTTP date); a wait longer than `maxRetryAfterMs` (default 10 s) is not slept: the response is returned immediately. Every attempt that is followed by another emits an event with `kind: 'retry'`, a `reason` and `retryInMs`. An injectable `clock` makes retries instant in tests.
15
+ - **A complete generated project.** `qe-api init` now creates a project with an `ApiClient` factory (retries, optional OAuth2), an OpenAPI document driving contract tests and an end-of-run coverage report with an optional `QE_COVERAGE_MIN_OPERATIONS` gate, working `@smoke`, `@contract` and `@security` samples against a local mock API, ESLint, `npm audit` and a GitLab pipeline. The generator pins the core at its own version and copies the TypeScript, ESLint and Ajv ranges from this package.
16
+ - **Tooling.** ESLint with type-aware rules; CI on Node 22, 24 and 26; an allowed-to-fail TypeScript 7 canary job; an end-to-end job that generates a project, installs it and runs its own checks (`npm run test:e2e`); Dependabot configuration.
17
+
18
+ ### Changed
19
+
20
+ - **Retry waits are exponential with jitter** (100, 200, 400 ms ... capped at `maxRetryDelayMs`, each randomized between half and all of its value) instead of linear (100, 200, 300 ms). Set `jitter: false` for fixed waits.
21
+ - **`HttpEvent['kind']` gains `'retry'`.** Code with an exhaustive `switch` over `kind` needs a new branch. The final outcome is still one `success` or `network-error` event, so consumers that only look at those keep working.
22
+ - **`ApiMetrics` gains `retries`.** `total`, `httpErrors` and the timings still describe final outcomes only.
23
+ - **A 401 re-authentication emits a `retry` event** (reason `reauthenticate`) for the rejected attempt.
24
+ - **`OpenApiValidator`:** an optional third argument carries `errorDetail`; a recursive schema now throws only when the compiler does not declare `supportsRefs`; invalid retry settings (negative or non-finite) throw when the client is created.
25
+ - **Generated projects** require Node 22.13 or newer (ESLint 10), run lint as part of `npm run check`, write the coverage report from `npm run test:ci`, and come with different sample tests.
26
+ - `tsconfig` files list `"types": ["node"]`, which TypeScript 7 requires.
27
+
28
+ ### Notes for upgrading
29
+
30
+ - The package passes its tests on Node 22, 24 and 26 and builds and passes under TypeScript 7; TypeScript 5.9 remains the supported compiler until `typescript-eslint` supports 7.
31
+ - `npm audit` in a generated project still reports moderate advisories in Mocha's `glob` and `minimatch`. They do not trip the high-severity gate. Do not run `npm audit fix --force`: it would downgrade Mocha.
32
+
33
+ ## [0.4.3] - 2026-11-22 (not published separately)
34
+
35
+ ### Fixed
36
+
37
+ - **OpenAPI contract checks silently passed responses declared through `#/components/responses/*`.** Such references are now resolved and validated; remote, unresolved and cyclic references throw.
38
+ - **Request path guard bypass.** `ApiClient` accepted encoded traversal such as `/users/%2e%2e/admin`, which the URL parser resolved to a different path. Paths are now judged after percent-decoding (up to three layers), a backslash counts as a separator, and malformed percent-encoding is rejected. Ordinary paths such as `/.well-known/jwks.json` and encoded data such as `%20` still work.
39
+ - **Redaction** matched short names as substrings (`shipping` and `mapping` were masked because they contain `pin`) and missed credentials inside strings. Short names now match as whole words; `x-api-key`, `credential` and card-number keys are masked; string values are scrubbed for `Bearer` and `Basic` credentials, JWTs and Luhn-valid card numbers.
40
+
41
+ ## [0.4.2] - 2026-11-22
42
+
43
+ ### Changed
44
+
45
+ - Generated projects use Mocha 12, and their JUnit output comes from Mocha's built-in `xunit` reporter instead of an incompatible plugin. Added `npm run audit:security` and a high-severity audit step to the generated pipeline.
46
+
47
+ ## [0.4.1] - 2026-11-22
48
+
49
+ ### Fixed
50
+
51
+ - The 0.4.0 generator wrote an ES module as the Mocha configuration; it now generates `config/mocha.config.json`.
52
+
53
+ ## [0.4.0] - 2026-11-22
54
+
55
+ ### Added
56
+
57
+ - The `qe-api init` project generator.
package/README.md CHANGED
@@ -7,53 +7,174 @@ A reusable TypeScript API test utility library and project initializer. Public n
7
7
  **Generate a complete new project:**
8
8
 
9
9
  ```bash
10
- npx --yes --package @nikhil-qeas/api-core@0.4.1 qe-api init my-api-project
10
+ npx --yes --package @nikhil-qeas/api-core@0.5.0 qe-api init my-api-project
11
11
  cd my-api-project
12
12
  npm install
13
13
  npm run check
14
14
  ```
15
15
 
16
- This creates a project with TypeScript, Mocha, test folders, client/auth/contract/data/workflow folders, a local mock smoke test, and GitLab CI with JUnit output.
16
+ The generated project is wired to everything in this package and runs out of the box against a local mock API (no environment, credentials or network needed):
17
+
18
+ - an `ApiClient` factory with retries, `Retry-After` handling and OAuth2 client credentials (set `OAUTH_*` to turn it on) with automatic token renewal;
19
+ - an OpenAPI document (`openapi/openapi.json`, replace it with yours) that drives both **contract tests** (Ajv-backed) and an end-of-run **coverage report** (`reports/coverage/api.md`, with an optional `QE_COVERAGE_MIN_OPERATIONS` gate);
20
+ - working `@smoke`, `@contract` and `@security` samples, including a token-renewal scenario and negative authentication tests;
21
+ - ESLint with type-aware rules, `npm audit`, JUnit output and a GitLab CI pipeline.
22
+
23
+ `npm run check` in the new project runs typecheck, lint and all tests. The project's README explains the layout. Generated projects pin this package at the version that generated them, and share its TypeScript, ESLint and Ajv ranges.
17
24
 
18
25
  **Add utilities to an existing project:**
19
26
 
20
27
  ```bash
21
- npm install --save-dev @nikhil-qeas/api-core@0.4.1
28
+ npm install --save-dev @nikhil-qeas/api-core@0.5.0
22
29
  ```
23
30
 
24
31
  Installing the package does **not** modify your source tree: utilities live under `node_modules`. Run the generator explicitly when you want a new project. The CLI refuses to overwrite an existing directory.
25
32
 
26
33
  ## Core modules
27
34
 
28
- - HTTP client with timeout handling, exact-body signing interface and safe GET retries
29
- - Token provider and lifecycle manager
30
- - OpenAPI response-contract adapter (supply a compatible JSON Schema validator)
35
+ - HTTP client with timeout handling, exact-body signing interface, and safe retries with exponential backoff, jitter and `Retry-After` support
36
+ - Token cache with OAuth2 client-credentials and refresh-token providers, and automatic re-authentication on HTTP 401
37
+ - OpenAPI 3.0/3.1 response-contract validation, with a ready-made Ajv backend (`createOpenApiValidator`)
31
38
  - Synthetic test data and cleanup helpers
32
39
  - In-process concurrency and execution context
33
40
  - JUnit, runner-neutral Mocha result collection and metadata-only Allure adapter
34
- - Safety policies, coverage registry, simple metrics and data redaction
41
+ - Spec-driven endpoint coverage from an OpenAPI document (`OpenApiCoverage`), plus a manual scenario registry
42
+ - Safety policies, simple metrics and data redaction
43
+
44
+ The library does not bundle Mocha, WDIO, Ajv, OAuth providers, or real application-specific test cases. Configure those in each consuming application as appropriate. Ajv is an optional peer dependency: install it only if you use the contract helpers below.
45
+
46
+ ## Contract validation with Ajv
47
+
48
+ ```bash
49
+ npm install --save-dev ajv ajv-formats
50
+ ```
51
+
52
+ ```ts
53
+ import { ApiClient, createOpenApiValidator } from '@nikhil-qeas/api-core';
54
+ import spec from './openapi.json' with { type: 'json' };
55
+
56
+ const contract = await createOpenApiValidator(spec, { errorDetail: 'schema' });
57
+ const api = new ApiClient({ baseUrl: process.env.QE_BASE_URL! });
58
+
59
+ const response = await api.request({ method: 'GET', path: '/accounts/42' });
60
+ contract.assertResponse({ method: 'GET', path: '/accounts/{id}', status: response.status, response });
61
+ ```
62
+
63
+ - The dialect follows the document: OpenAPI 3.1 uses JSON Schema 2020-12, 3.0 uses draft-07 with `nullable` and boolean `exclusiveMinimum`/`exclusiveMaximum` converted.
64
+ - Local `#/components/schemas/*` and `#/components/responses/*` references are resolved, including recursive and mutually recursive schemas. Remote references are rejected.
65
+ - Standard formats (`uuid`, `date-time`, `email`, `int32`, ...) are validated through `ajv-formats`; pass `{ formats: false }` to skip them. Unknown formats and OpenAPI keywords such as `example` and `x-*` are ignored.
66
+ - Each response schema is compiled once and cached.
67
+ - Failures never include response data. By default the message says details are suppressed; `errorDetail: 'schema'` adds the violated schema locations and rule messages (never values or property names).
68
+ - Use `createAjvCompiler({ dialect })` with `new OpenApiValidator(spec, compiler)` when you need to control the Ajv setup yourself, or pass any compiler with the same `compile()` shape.
69
+
70
+ ## Retries, backoff and Retry-After
71
+
72
+ ```ts
73
+ const api = new ApiClient({
74
+ baseUrl,
75
+ maxSafeRetries: 2, // default 1, at most 5 per request (or per call with `retry`)
76
+ retryDelayMs: 100, // first wait; doubles each retry
77
+ maxRetryDelayMs: 5_000, // cap for the doubling wait
78
+ jitter: true, // each wait is randomized between half and all of its value
79
+ maxRetryAfterMs: 10_000, // longest Retry-After that is waited out
80
+ onEvent: event => { if (event.kind === 'retry') console.warn(event.method, event.path, event.reason, event.retryInMs); }
81
+ });
82
+ ```
83
+
84
+ - **What is retried:** network failures, timeouts and 408/429/502/503/504 responses, only for GET, HEAD, OPTIONS and requests marked `idempotent: true`. A POST is never retried after an ambiguous failure, even when the server sends `Retry-After`. (A 401 is handled separately, see the OAuth2 section.)
85
+ - **`Retry-After`** (seconds or an HTTP date) is obeyed when present. If the server asks for longer than `maxRetryAfterMs`, the client does not sleep: it returns the 429/503 response immediately, so a test fails fast with the cause visible instead of stalling. Set `respectRetryAfter: false` to ignore the header.
86
+ - **Backoff** applies otherwise: 100 ms, 200 ms, 400 ms and so on up to the cap. Jitter keeps parallel workers from retrying in lockstep. Earlier versions waited a linear 100 ms, 200 ms, 300 ms.
87
+ - **Visibility:** every attempt that is followed by another one emits an event with `kind: 'retry'`, a `reason` (`status`, `network`, `timeout` or `reauthenticate`), the `status` or `error`, and `retryInMs`. The final outcome is still one `success` or `network-error` event, so code that only looks at those keeps working. `MetricsCollector` reports the number of retries separately and keeps `total` as the count of requests. `OpenApiCoverage` counts the statuses seen during retries.
88
+ - **Testing your own code:** pass `clock: { now, sleep, random }` to run retries instantly and deterministically.
89
+ - Invalid settings (negative or non-finite delays) throw when the client is created.
35
90
 
36
- The library does not bundle Mocha, WDIO, Ajv, OAuth providers, or real application-specific test cases. Configure those in each consuming application as appropriate.
91
+ ## Endpoint coverage from your OpenAPI spec
92
+
93
+ `OpenApiCoverage` answers "which operations and documented responses did the suite actually exercise?" without any hand-written inventory.
94
+
95
+ ```ts
96
+ import { ApiClient, MetricsCollector, OpenApiCoverage } from '@nikhil-qeas/api-core';
97
+ import spec from './openapi.json' with { type: 'json' };
98
+
99
+ const coverage = new OpenApiCoverage(spec, { exclude: ['GET /health', 'legacyExport'] });
100
+ const metrics = new MetricsCollector();
101
+ const api = new ApiClient({
102
+ baseUrl: process.env.QE_BASE_URL!,
103
+ onEvent: event => { metrics.record(event); coverage.recordEvent(event); }
104
+ });
105
+
106
+ // Mocha root hook (after all tests):
107
+ await coverage.write('reports/coverage/api.md', 'markdown');
108
+ await coverage.write('reports/coverage/api.json');
109
+ coverage.assertCoverage({ minOperations: 80, failOnUndocumented: true });
110
+ ```
111
+
112
+ - Concrete paths are mapped to templates (`/accounts/42` -> `/accounts/{id}`), preferring the most specific one (`/accounts/me`). Query strings and trailing slashes are ignored.
113
+ - A response counts as covered when its exact status (`404`), range (`4XX`) or `default` entry is observed. A status the spec does not declare is reported as an **undocumented response**, which usually means spec drift.
114
+ - Requests that match no operation are reported as **unmatched** (a path or method missing from the spec). They never add coverage, and card-number-like values in paths are masked.
115
+ - Coverage means *exercised*, not *passed*: it counts requests, so pair it with your normal test results.
116
+ - `exclude` accepts `"METHOD /path/template"` or an `operationId`; `includeDeprecated: false` drops deprecated operations. TRACE operations and path items using `$ref` are not supported (the latter throws instead of under-reporting).
117
+ - Parallel Mocha workers or sharded CI jobs each see only their own requests. Write `JSON.stringify(coverage.snapshot())` per job and combine them with `coverage.merge(snapshot)` in a final job. A snapshot from a different spec is rejected without changing anything.
118
+ - Network errors carry no status and are not counted.
119
+
120
+ ## OAuth2 and automatic re-authentication
121
+
122
+ ```ts
123
+ import { ApiClient, TokenManager, clientCredentialsProvider } from '@nikhil-qeas/api-core';
124
+
125
+ const tokens = new TokenManager(clientCredentialsProvider({
126
+ tokenUrl: process.env.OAUTH_TOKEN_URL!,
127
+ clientId: process.env.OAUTH_CLIENT_ID!,
128
+ clientSecret: process.env.OAUTH_CLIENT_SECRET!,
129
+ scope: ['accounts.read'],
130
+ }));
131
+ const api = new ApiClient({ baseUrl: process.env.QE_BASE_URL!, auth: { tokens } });
132
+
133
+ await api.request({ method: 'GET', path: '/accounts' }); // sends Authorization: Bearer <token>
134
+ await api.request({ method: 'POST', path: '/login', skipAuth: true, json: {} }); // no token
135
+ await api.request({ method: 'GET', path: '/accounts', headers: { Authorization: 'Bearer wrong' } }); // negative test: sent as written
136
+ ```
137
+
138
+ - **Providers:** `clientCredentialsProvider` for service-to-service access and `refreshTokenProvider` for a refresh token you supply. Both validate the token response (Bearer type, token characters, `expires_in`) and apply a timeout. Other flows (authorization code with PKCE, JWT bearer, mTLS) stay in your project: implement `TokenProvider` and pass it to `TokenManager`.
139
+ - **Safe defaults:** the token URL must be `https` (plain `http` only for localhost, or with `allowInsecureTokenUrl`). Token requests never follow redirects, so credentials cannot be forwarded elsewhere. Errors carry the HTTP status and the OAuth `error` code, never the response body, the secret or a token.
140
+ - **Automatic renewal:** the cache renews tokens shortly before they expire (30s skew by default) and shares one renewal between concurrent callers.
141
+ - **401 handling:** when the server rejects a token, the client renews it and resends the request **once**, for every method. A 401 means the request was not processed, so this is safe where a 5xx retry is not. Rejections of a token that has already been replaced reuse the new token instead of renewing again, so a burst of 401s causes one renewal. The result and event carry `reauthenticated: true`. Turn it off with `auth: { tokens, refreshOnUnauthorized: false }`.
142
+ - **Headers:** an `Authorization` header you set on a request is never replaced or renewed, and `skipAuth: true` sends no token. Use `header` and `scheme` (`''` for a bare token) for APIs that expect something else, such as `X-Api-Token`.
143
+ - **Rotating refresh tokens** are single-use. The provider keeps the newest one in memory only, so do not share one refresh-token secret between parallel jobs.
144
+ - `TokenManager.invalidate()` still discards everything. Passing the rejected access token, as the client does, expires just that token and tries the refresh token first.
37
145
 
38
146
  ## Running the core test suite
39
147
 
40
148
  ```bash
41
149
  npm ci
42
- npm run check
43
- npm run test:ci
150
+ npm run check # typecheck + ESLint + build + tests
151
+ npm run test:ci # JUnit report in reports/junit/
152
+ npm run test:e2e # generates a project, installs it and runs its own checks (needs the npm registry)
44
153
  npm pack --dry-run
45
154
  ```
46
155
 
156
+ The project generator's output lives in real files under `templates/project/`, copied by `bin/qe-api.js`. Only `package.json` is built in code, so that the core version and shared tooling ranges always match this package. A leading dot in a template name is written `__dot__` (npm drops `.gitignore` files from packages). `test:e2e` packs this checkout, generates a project from it and runs `npm run check` there, so a template that no longer compiles or lints fails CI.
157
+
158
+ ### Supported runtimes and toolchain
159
+
160
+ - **Node.js 22.12 or newer.** GitLab CI runs the full suite on Node 22, 24 and 26 in parallel.
161
+ - **Linting:** `npm run lint` uses ESLint with type-aware rules, mainly to catch unawaited promises (a silently skipped check in a test framework), unused code and type-only imports. ESLint 10 itself needs Node 22.13+, so use that or newer when developing the library.
162
+ - **TypeScript 5.9** is the supported compiler. The code also typechecks, builds and passes every test under **TypeScript 7**: an allowed-to-fail CI job (`typescript-next`) tracks that. We stay on 5.9 until `typescript-eslint` supports 7. Both tsconfig files list `"types": ["node"]`, which TypeScript 7 requires (it no longer loads every `@types` package automatically).
163
+ - **`@types/node` stays on 22** on purpose: it matches the minimum supported runtime, so the library cannot use an API that Node 22 lacks. Raise it only when `engines` moves.
164
+ - **Dependency updates:** `.github/dependabot.yml` proposes weekly npm updates, grouped for dev tooling. Majors of `typescript` and `@types/node` are excluded because they need the decisions above. An `npm audit` job warns, without blocking, on high-severity advisories.
165
+
47
166
  ## Limitations and security
48
167
 
49
168
  The generated smoke test runs against a local isolated HTTP server. It does not connect to production systems. Source utilities do not automatically enforce all safety policies: integration code must wire authorization and environment gates before running write-capable requests. Use secret managers and secure runtime configuration; never commit tokens or response bodies to logs.
50
169
 
170
+ Generated projects run `npm audit` in CI and fail only on high-severity advisories. Today `npm audit` still reports moderate advisories in Mocha's own dependencies (`glob`, `minimatch`); review them, and do not use `npm audit fix --force`, which would downgrade Mocha. The `esbuild` postinstall approval warning from npm is separate from vulnerabilities.
171
+
51
172
  This is a public npm distribution. Review package contents and associated documentation before publishing. This version is suitable for a controlled integration pilot; domain-specific workflows and live-system compatibility are verified separately.
52
173
 
53
174
  ## Distribution
54
175
 
55
176
  Releases are published manually to public npmjs.org; GitHub Actions payment eligibility is not needed. See `docs/RELEASE.md` in the source repository for release verification and publication instructions.
56
177
 
57
- ## v0.4.1 consumer fix
178
+ ## Changelog
58
179
 
59
- The v0.4.0 generator accidentally supplied an ES module `.mjs` file as a JSON Mocha configuration. v0.4.1 generates `config/mocha.config.json` and points all Mocha scripts to that file. Existing v0.4.0 projects should replace the file and script references or regenerate in a fresh directory. The dependency audit must be checked in each generated project before enterprise use.
180
+ See `CHANGELOG.md` in the package for what changed in each release, including behavior changes that may need action when upgrading.
package/bin/qe-api.js CHANGED
@@ -1,27 +1,100 @@
1
1
  #!/usr/bin/env node
2
- import {existsSync,mkdirSync,writeFileSync} from 'node:fs';
3
- import {resolve,join,dirname} from 'node:path';
4
- const args=process.argv.slice(2);
5
- if(!args.length||args.includes('--help')){console.log('Usage: qe-api init <project-name> [--dir <path>]');process.exit(0);}
6
- const name=args[1],opt=args.indexOf('--dir');
7
- if(args[0]!=='init'||!name||!/^[a-z][a-z0-9-]{1,62}$/.test(name)||name.endsWith('-')||name.includes('--')||(opt<0&&args.length!==2)||(opt>=0&&(args.length!==4||!args[opt+1]))){console.error('Invalid arguments. Try: qe-api init my-api');process.exit(2);}
8
- const dest=resolve(opt<0?name:args[opt+1]);
9
- if(existsSync(dest)){console.error('Target already exists: '+dest);process.exit(1);}
10
- const packageJson={name,version:'0.1.0',private:true,type:'module',engines:{node:'>=22.12.0'},scripts:{typecheck:'tsc --noEmit',test:'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.json','test:smoke':'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.json --grep "@smoke"','test:ci':'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.json --reporter mocha-junit-reporter --reporter-options mochaFile=reports/junit/results.xml',check:'npm run typecheck && npm test'},devDependencies:{'@nikhil-qeas/api-core':'^0.4.1','@types/mocha':'^10.0.0','@types/node':'^22.0.0',mocha:'^11.0.0','mocha-junit-reporter':'^2.2.1',tsx:'^4.0.0',typescript:'^5.9.3'}};
11
- const files={
12
- 'package.json':JSON.stringify(packageJson,null,2)+'\n',
13
- 'tsconfig.json':JSON.stringify({compilerOptions:{target:'ES2022',module:'NodeNext',moduleResolution:'NodeNext',strict:true,esModuleInterop:true,types:['node','mocha'],noEmit:true,skipLibCheck:true},include:['src/**/*.ts','tests/**/*.ts']},null,2)+'\n',
14
- '.gitignore':'node_modules/\nreports/\n.env\n.env.*\n!.env.example\ndist/\n*.tgz\n',
15
- '.env.example':'QE_ENV=local\nQE_ALLOW_MUTATIONS=false\n# API_BASE_URL=https://test.example.invalid\n',
16
- 'config/mocha.config.json':JSON.stringify({extension:['ts'],spec:['tests/**/*.spec.ts'],timeout:30000,recursive:true,reporter:'spec'},null,2)+'\n',
17
- 'config/environments/.gitkeep':'',
18
- 'src/config/environment.ts':"export function targetBaseUrl(): string {\n const value=process.env.API_BASE_URL;\n if(!value)throw new Error('API_BASE_URL is required');\n const u=new URL(value);\n if(!['http:','https:'].includes(u.protocol))throw new Error('HTTP(S) required');\n return value;\n}\n",
19
- 'src/clients/api.ts':"import {ApiClient} from '@nikhil-qeas/api-core';\nimport {targetBaseUrl} from '../config/environment.js';\n/** Add project auth and security approvals before connecting bank endpoints. */\nexport function createApiClient(){return new ApiClient({baseUrl:targetBaseUrl(),timeoutMs:15000,maxSafeRetries:1});}\n",
20
- 'src/auth/.gitkeep':'','src/contracts/.gitkeep':'','src/data/.gitkeep':'','src/workflows/.gitkeep':'',
21
- 'tests/fixtures/.gitkeep':'','tests/regression/.gitkeep':'','tests/contract/.gitkeep':'','tests/negative/.gitkeep':'','tests/security/.gitkeep':'','docs/.gitkeep':'','reports/.gitkeep':'',
22
- 'tests/smoke/health.spec.ts':"import assert from 'node:assert/strict';\nimport {createServer} from 'node:http';\nimport {once} from 'node:events';\nimport {ApiClient,expectStatus} from '@nikhil-qeas/api-core';\ndescribe('@smoke local API core',()=>{it('tests an isolated mock server',async()=>{const server=createServer((_q,res)=>{res.setHeader('content-type','application/json');res.end(JSON.stringify({status:'ok'}));});server.listen(0,'127.0.0.1');try{await once(server,'listening');const addr=server.address();if(!addr||typeof addr==='string')throw Error('No port');const client=new ApiClient({baseUrl:'http://127.0.0.1:'+addr.port});const result=await client.request({method:'GET',path:'/health'});expectStatus(result,200);assert.deepEqual(result.body,{status:'ok'});}finally{server.close();}});});\n",
23
- '.gitlab-ci.yml':"stages: [verify,test]\nimage: node:22-bookworm-slim\nverify:\n stage: verify\n script:\n - npm ci\n - npm run typecheck\nsmoke:\n stage: test\n script:\n - npm ci\n - npm run test:ci\n artifacts:\n when: always\n reports:\n junit: reports/junit/results.xml\n paths: [reports/junit/]\n",
24
- 'README.md':'# '+name+'\n\nGenerated API automation project using @nikhil-qeas/api-core.\n\nRun npm install and npm run check. Sample smoke test uses a local mock HTTP server, not a banking environment.\n\nDirectories: src/clients, src/auth, src/contracts, src/data, src/workflows, tests/smoke, tests/regression, tests/contract, tests/negative, tests/security, config, reports, docs.\n\nStore credentials in approved environment secrets, not source control.\n'
25
- };
26
- for(const [path,data] of Object.entries(files)){const full=join(dest,path);mkdirSync(dirname(full),{recursive:true});writeFileSync(full,data,{flag:'wx'});}
27
- console.log('Created '+dest+' ('+Object.keys(files).length+' files). Run npm install && npm run check.');
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const USAGE = 'Usage: qe-api init <project-name> [--dir <path>]';
7
+ const TEMPLATE_DIR = fileURLToPath(new URL('../templates/project/', import.meta.url));
8
+ const OWN_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
9
+ /** Directories the generated project starts with, each kept in git by an empty .gitkeep. */
10
+ const EMPTY_DIRS = ['config/environments', 'src/auth', 'src/data', 'src/workflows', 'tests/fixtures', 'tests/regression', 'tests/negative', 'docs', 'reports'];
11
+ /** Tooling the generated project shares with this package, taken from its devDependencies so the two never drift apart. */
12
+ const SHARED_TOOLING = ['@eslint/js', '@types/node', 'ajv', 'ajv-formats', 'eslint', 'globals', 'typescript', 'typescript-eslint'];
13
+ const MOCHA = 'node --import tsx ./node_modules/mocha/bin/mocha.js --config config/mocha.config.json';
14
+
15
+ function parseArguments(args) {
16
+ const [command, name] = args;
17
+ const dirFlag = args.indexOf('--dir');
18
+ const shapeOk = dirFlag < 0 ? args.length === 2 : args.length === 4 && Boolean(args[dirFlag + 1]);
19
+ const nameOk = typeof name === 'string' && /^[a-z][a-z0-9-]{1,62}$/.test(name) && !name.endsWith('-') && !name.includes('--');
20
+ if (command !== 'init' || !nameOk || !shapeOk) return undefined;
21
+ return { name, destination: resolve(dirFlag < 0 ? name : args[dirFlag + 1]) };
22
+ }
23
+
24
+ function projectPackage(name) {
25
+ const devDependencies = {
26
+ '@nikhil-qeas/api-core': `^${OWN_PACKAGE.version}`,
27
+ '@types/mocha': '^10.0.0',
28
+ mocha: '^12.0.0',
29
+ tsx: '^4.0.0'
30
+ };
31
+ for (const dependency of SHARED_TOOLING) {
32
+ const range = OWN_PACKAGE.devDependencies?.[dependency];
33
+ if (!range) throw new Error(`Generator misconfigured: ${dependency} is not a devDependency of ${OWN_PACKAGE.name}`);
34
+ devDependencies[dependency] = range;
35
+ }
36
+ return {
37
+ name,
38
+ version: '0.1.0',
39
+ private: true,
40
+ type: 'module',
41
+ // ESLint 10 needs Node 22.13 or newer.
42
+ engines: { node: '>=22.13.0' },
43
+ scripts: {
44
+ typecheck: 'tsc --noEmit',
45
+ lint: 'eslint .',
46
+ test: MOCHA,
47
+ 'test:smoke': `${MOCHA} --grep "@smoke"`,
48
+ 'test:contract': `${MOCHA} --grep "@contract"`,
49
+ 'test:security': `${MOCHA} --grep "@security"`,
50
+ 'test:ci': `node -e "require('node:fs').mkdirSync('reports/junit',{recursive:true})" && ${MOCHA} --reporter xunit --reporter-option output=reports/junit/results.xml`,
51
+ check: 'npm run typecheck && npm run lint && npm test',
52
+ 'audit:security': 'npm audit --audit-level=high'
53
+ },
54
+ devDependencies: Object.fromEntries(Object.entries(devDependencies).sort(([a], [b]) => a.localeCompare(b)))
55
+ };
56
+ }
57
+
58
+ function* templateFiles(directory, prefix = '') {
59
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
60
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
61
+ if (entry.isDirectory()) yield* templateFiles(join(directory, entry.name), relative);
62
+ else yield relative;
63
+ }
64
+ }
65
+ /** npm drops files named .gitignore from packages, so templates spell a leading dot as "__dot__". */
66
+ function outputPath(templatePath) {
67
+ return templatePath.split('/').map(part => part.startsWith('__dot__') ? `.${part.slice('__dot__'.length)}` : part).join('/');
68
+ }
69
+
70
+ function projectFiles(name) {
71
+ const files = new Map();
72
+ files.set('package.json', `${JSON.stringify(projectPackage(name), null, 2)}\n`);
73
+ for (const path of templateFiles(TEMPLATE_DIR)) {
74
+ files.set(outputPath(path), readFileSync(join(TEMPLATE_DIR, path), 'utf8').replaceAll('__PROJECT_NAME__', name));
75
+ }
76
+ for (const directory of EMPTY_DIRS) files.set(`${directory}/.gitkeep`, '');
77
+ return files;
78
+ }
79
+
80
+ const args = process.argv.slice(2);
81
+ if (!args.length || args.includes('--help')) {
82
+ console.log(USAGE);
83
+ process.exit(0);
84
+ }
85
+ const parsed = parseArguments(args);
86
+ if (!parsed) {
87
+ console.error('Invalid arguments. Try: qe-api init my-api');
88
+ process.exit(2);
89
+ }
90
+ if (existsSync(parsed.destination)) {
91
+ console.error(`Target already exists: ${parsed.destination}`);
92
+ process.exit(1);
93
+ }
94
+ const files = projectFiles(parsed.name);
95
+ for (const [path, content] of files) {
96
+ const full = join(parsed.destination, path);
97
+ mkdirSync(dirname(full), { recursive: true });
98
+ writeFileSync(full, content, { flag: 'wx' });
99
+ }
100
+ console.log(`Created ${parsed.destination} (${files.size} files). Run npm install && npm run check.`);
@@ -0,0 +1,40 @@
1
+ import type { TokenProvider } from './token-manager.js';
2
+ export interface OAuth2EndpointOptions {
3
+ /** Token endpoint. Must be https, except for localhost (or when `allowInsecureTokenUrl` is set). */
4
+ tokenUrl: string;
5
+ clientId: string;
6
+ /** How the client authenticates: 'basic' (default, RFC 6749 section 2.3.1) or in the form body. */
7
+ clientAuth?: 'basic' | 'body' | undefined;
8
+ /** Extra form fields such as `resource`. May not override grant, client or token fields. */
9
+ extraParams?: Readonly<Record<string, string>> | undefined;
10
+ timeoutMs?: number | undefined;
11
+ /** Allow a plain-http token URL on a non-local host. Default false. */
12
+ allowInsecureTokenUrl?: boolean | undefined;
13
+ fetchImpl?: typeof fetch | undefined;
14
+ now?: (() => number) | undefined;
15
+ }
16
+ export interface OAuth2ClientOptions extends OAuth2EndpointOptions {
17
+ clientSecret: string;
18
+ scope?: string | readonly string[] | undefined;
19
+ audience?: string | undefined;
20
+ }
21
+ export interface OAuth2RefreshOptions extends OAuth2EndpointOptions {
22
+ /** Omit for public clients. */
23
+ clientSecret?: string | undefined;
24
+ /** The refresh token to start from. Providers that rotate refresh tokens keep the newest one in memory only. */
25
+ refreshToken: string;
26
+ scope?: string | readonly string[] | undefined;
27
+ }
28
+ /** A failed token request. Carries the HTTP status and the OAuth `error` code, never the response body or any credential. */
29
+ export declare class OAuth2Error extends Error {
30
+ readonly status?: number | undefined;
31
+ readonly code?: string | undefined;
32
+ constructor(message: string, status?: number | undefined, code?: string | undefined, options?: ErrorOptions);
33
+ }
34
+ /** OAuth 2.0 client credentials grant (service-to-service). Pair with `TokenManager`; there is no refresh token, so renewal re-requests. */
35
+ export declare function clientCredentialsProvider(options: OAuth2ClientOptions): TokenProvider;
36
+ /**
37
+ * OAuth 2.0 refresh token grant. Keeps the newest refresh token in memory when the server rotates it, so a rotating
38
+ * token supplied from a secret is single-use: do not reuse the same secret in parallel jobs.
39
+ */
40
+ export declare function refreshTokenProvider(options: OAuth2RefreshOptions): TokenProvider;
@@ -0,0 +1,138 @@
1
+ import { encodeForm } from '../http/api-client.js';
2
+ /** A failed token request. Carries the HTTP status and the OAuth `error` code, never the response body or any credential. */
3
+ export class OAuth2Error extends Error {
4
+ status;
5
+ code;
6
+ constructor(message, status, code, options) {
7
+ super(message, options);
8
+ this.status = status;
9
+ this.code = code;
10
+ this.name = 'OAuth2Error';
11
+ }
12
+ }
13
+ const RESERVED = new Set(['grant_type', 'client_id', 'client_secret', 'refresh_token', 'scope']);
14
+ const TOKEN_CHARS = /^[\x21-\x7E]+$/; // visible ASCII, no whitespace: also rules out header injection
15
+ const ERROR_CODE = /^[A-Za-z0-9_.-]{1,64}$/;
16
+ function resolveTokenUrl(raw, allowInsecure) {
17
+ let url;
18
+ try {
19
+ url = new URL(raw);
20
+ }
21
+ catch {
22
+ throw new Error('Invalid OAuth2 tokenUrl');
23
+ }
24
+ if (url.username || url.password || url.hash)
25
+ throw new Error('OAuth2 tokenUrl must not contain credentials or a fragment');
26
+ const local = url.hostname === 'localhost' || url.hostname.endsWith('.localhost') || url.hostname === '127.0.0.1' || url.hostname === '[::1]';
27
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && (local || allowInsecure)))
28
+ throw new Error('OAuth2 tokenUrl must use https');
29
+ return url;
30
+ }
31
+ function scopeValue(scope) {
32
+ const value = Array.isArray(scope) ? scope.join(' ') : scope;
33
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
34
+ }
35
+ function checkedExtras(extra) {
36
+ const entries = Object.entries(extra ?? {});
37
+ for (const [key] of entries)
38
+ if (RESERVED.has(key))
39
+ throw new Error(`OAuth2 extraParams may not set "${key}"`);
40
+ return entries;
41
+ }
42
+ function tokenField(value, name) {
43
+ if (typeof value !== 'string' || !TOKEN_CHARS.test(value))
44
+ throw new OAuth2Error(`OAuth2 token response has an invalid ${name}`);
45
+ return value;
46
+ }
47
+ function endpoint(options, secret) {
48
+ const url = resolveTokenUrl(options.tokenUrl, options.allowInsecureTokenUrl === true);
49
+ const fetcher = options.fetchImpl ?? fetch;
50
+ const now = options.now ?? Date.now;
51
+ const timeoutMs = options.timeoutMs ?? 15_000;
52
+ const extras = checkedExtras(options.extraParams);
53
+ if (!options.clientId)
54
+ throw new Error('OAuth2 clientId is required');
55
+ return async function requestToken(fields) {
56
+ const form = [...fields, ...extras];
57
+ const headers = { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' };
58
+ if (options.clientAuth !== 'body' && secret !== undefined) {
59
+ const id = encodeForm([['', options.clientId]]).slice(1);
60
+ const sec = encodeForm([['', secret]]).slice(1);
61
+ headers.Authorization = `Basic ${Buffer.from(`${id}:${sec}`).toString('base64')}`;
62
+ }
63
+ else {
64
+ form.push(['client_id', options.clientId]);
65
+ if (secret !== undefined)
66
+ form.push(['client_secret', secret]);
67
+ }
68
+ let response;
69
+ let text;
70
+ try {
71
+ // Never follow redirects: they would forward the client credentials to another location.
72
+ response = await fetcher(url, { method: 'POST', headers, body: encodeForm(form), redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
73
+ text = await response.text();
74
+ }
75
+ catch (error) {
76
+ const timedOut = error instanceof Error && ['TimeoutError', 'AbortError'].includes(error.name);
77
+ throw new OAuth2Error(`OAuth2 token request ${timedOut ? 'timed out' : 'failed'}`, undefined, undefined, { cause: error });
78
+ }
79
+ let body;
80
+ try {
81
+ body = text ? JSON.parse(text) : undefined;
82
+ }
83
+ catch {
84
+ body = undefined;
85
+ }
86
+ const data = body !== null && typeof body === 'object' && !Array.isArray(body) ? body : undefined;
87
+ if (!response.ok) {
88
+ const code = typeof data?.error === 'string' && ERROR_CODE.test(data.error) ? data.error : undefined;
89
+ throw new OAuth2Error(`OAuth2 token request failed (HTTP ${response.status}${code ? `, ${code}` : ''})`, response.status, code);
90
+ }
91
+ if (!data)
92
+ throw new OAuth2Error('OAuth2 token response is not a JSON object', response.status);
93
+ if (data.token_type !== undefined && (typeof data.token_type !== 'string' || data.token_type.toLowerCase() !== 'bearer')) {
94
+ throw new OAuth2Error('OAuth2 token response has an unsupported token_type', response.status);
95
+ }
96
+ const tokens = { accessToken: tokenField(data.access_token, 'access_token') };
97
+ const lifetime = typeof data.expires_in === 'string' && data.expires_in.trim() !== '' ? Number(data.expires_in) : data.expires_in;
98
+ if (typeof lifetime === 'number' && Number.isFinite(lifetime) && lifetime >= 0)
99
+ tokens.expiresAt = now() + lifetime * 1000;
100
+ if (data.refresh_token !== undefined)
101
+ tokens.refreshToken = tokenField(data.refresh_token, 'refresh_token');
102
+ return tokens;
103
+ };
104
+ }
105
+ /** OAuth 2.0 client credentials grant (service-to-service). Pair with `TokenManager`; there is no refresh token, so renewal re-requests. */
106
+ export function clientCredentialsProvider(options) {
107
+ if (!options.clientSecret)
108
+ throw new Error('OAuth2 clientSecret is required');
109
+ const requestToken = endpoint(options, options.clientSecret);
110
+ const scope = scopeValue(options.scope);
111
+ return {
112
+ acquire: () => requestToken([
113
+ ['grant_type', 'client_credentials'],
114
+ ...(scope ? [['scope', scope]] : []),
115
+ ...(options.audience ? [['audience', options.audience]] : [])
116
+ ])
117
+ };
118
+ }
119
+ /**
120
+ * OAuth 2.0 refresh token grant. Keeps the newest refresh token in memory when the server rotates it, so a rotating
121
+ * token supplied from a secret is single-use: do not reuse the same secret in parallel jobs.
122
+ */
123
+ export function refreshTokenProvider(options) {
124
+ if (!options.refreshToken)
125
+ throw new Error('OAuth2 refreshToken is required');
126
+ const requestToken = endpoint(options, options.clientSecret);
127
+ const scope = scopeValue(options.scope);
128
+ let latest = options.refreshToken;
129
+ const grant = async (refreshToken) => {
130
+ const tokens = await requestToken([['grant_type', 'refresh_token'], ['refresh_token', refreshToken], ...(scope ? [['scope', scope]] : [])]);
131
+ if (tokens.refreshToken)
132
+ latest = tokens.refreshToken;
133
+ else
134
+ tokens.refreshToken = refreshToken; // the server did not rotate it: keep using the same one
135
+ return tokens;
136
+ };
137
+ return { acquire: () => grant(latest), refresh: old => grant(old.refreshToken ?? latest) };
138
+ }
@@ -7,8 +7,14 @@ export interface TokenProvider {
7
7
  acquire(): Promise<Tokens>;
8
8
  refresh?(old: Tokens): Promise<Tokens>;
9
9
  }
10
+ /** What ApiClient needs from a token cache. `TokenManager` satisfies it. */
11
+ export interface TokenSource {
12
+ tokens(): Promise<Pick<Tokens, 'accessToken'>>;
13
+ /** Called with the access token the server rejected (HTTP 401). */
14
+ invalidate(rejectedAccessToken?: string): void;
15
+ }
10
16
  /** Caches tokens and deduplicates concurrent renewals within a worker. */
11
- export declare class TokenManager {
17
+ export declare class TokenManager implements TokenSource {
12
18
  private readonly provider;
13
19
  private readonly skewMs;
14
20
  private readonly now;
@@ -17,6 +23,11 @@ export declare class TokenManager {
17
23
  constructor(provider: TokenProvider, skewMs?: number, now?: () => number);
18
24
  tokens(): Promise<Tokens>;
19
25
  header(): Promise<Record<string, string>>;
20
- invalidate(): void;
26
+ /**
27
+ * Without an argument, discards the cached tokens so the next call logs in again.
28
+ * With the access token a server just rejected, marks only that token expired: the next call tries the refresh token first,
29
+ * and nothing happens if another request has already replaced the token, so a burst of 401s causes a single renewal.
30
+ */
31
+ invalidate(rejectedAccessToken?: string): void;
21
32
  private renew;
22
33
  }
@@ -19,7 +19,19 @@ export class TokenManager {
19
19
  return this.inflight;
20
20
  }
21
21
  async header() { return { Authorization: `Bearer ${(await this.tokens()).accessToken}` }; }
22
- invalidate() { this.current = undefined; }
22
+ /**
23
+ * Without an argument, discards the cached tokens so the next call logs in again.
24
+ * With the access token a server just rejected, marks only that token expired: the next call tries the refresh token first,
25
+ * and nothing happens if another request has already replaced the token, so a burst of 401s causes a single renewal.
26
+ */
27
+ invalidate(rejectedAccessToken) {
28
+ if (rejectedAccessToken === undefined) {
29
+ this.current = undefined;
30
+ return;
31
+ }
32
+ if (this.current?.accessToken === rejectedAccessToken)
33
+ this.current = { ...this.current, expiresAt: 0 };
34
+ }
23
35
  async renew() {
24
36
  if (this.current?.refreshToken && this.provider.refresh) {
25
37
  try {