@tupik/openapi 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +106 -2
- package/bin/contract-cli.mjs +4 -0
- package/bin/tupik.mjs +4 -0
- package/dist/cli.d.mts +68 -0
- package/dist/cli.d.ts +68 -0
- package/dist/cli.mjs +299 -0
- package/dist/index.d.mts +164 -0
- package/dist/index.d.ts +164 -0
- package/dist/index.mjs +223 -0
- package/dist/shared/openapi.B3aGIYpz.mjs +544 -0
- package/dist/shared/openapi.BCSoJoZR.d.mts +246 -0
- package/dist/shared/openapi.BCSoJoZR.d.ts +246 -0
- package/package.json +66 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Carlos Alberto Barbosa Stenzel / Tupik Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,107 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tupik/openapi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
OpenAPI 3.1 generator for **Tupik** apps, built from the route metadata (`access`, data classes, error catalog),
|
|
4
|
+
plus the `tupik` CLI: security audit, personal data map (LGPD/GDPR) and contract snapshot/breaking-change check.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install @tupik/openapi @tupik/core
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { createApp, createModule } from '@tupik/core';
|
|
16
|
+
import { diffContracts, generateOpenApiDocument, hasBreakingChanges, snapshotContract } from '@tupik/openapi';
|
|
17
|
+
|
|
18
|
+
const v1 = createApp().register(createModule('/users').get('/:id', { access: 'public', handler: (ctx) => ({ id: ctx.params.id }) }));
|
|
19
|
+
const v2 = createApp().register(createModule('/users').post('/', { access: 'public', handler: () => ({ created: true }) }));
|
|
20
|
+
|
|
21
|
+
const doc = generateOpenApiDocument(v1, { info: { title: 'Users', version: '1.0.0' } });
|
|
22
|
+
console.log(doc.openapi, Object.keys(doc.paths)); // 3.1.0 [ '/users/{id}' ]
|
|
23
|
+
|
|
24
|
+
const changes = diffContracts(snapshotContract(v1), snapshotContract(v2));
|
|
25
|
+
console.log(hasBreakingChanges(changes)); // true: GET /users/:id was removed
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
What the document gets from each route's metadata:
|
|
29
|
+
|
|
30
|
+
- `security`: `[]` on public routes, `[{ scheme: [] }]` when a principal is required, `[{}, { scheme: [] }]` for
|
|
31
|
+
`auth: 'optional'` (`securityScheme`, or the only entry of `securitySchemes`; `routeSecurity` still overrides).
|
|
32
|
+
- `x-access` with the access kind (`public`, `authenticated`, `policy`, `owner`).
|
|
33
|
+
- `x-data-class` on every field classified with `classify` (`pii`, `health`, `secret`), also when the response is a
|
|
34
|
+
derived schema (`z.array(User)`, `User.pick(...)`, nesting): the class lives on the field schema.
|
|
35
|
+
- `application/problem+json` responses for the route's `errors` and its access denials (401/403/404), with a
|
|
36
|
+
`code` enum per status.
|
|
37
|
+
|
|
38
|
+
### CLI
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
# <module> must export the app as `default` or `app`
|
|
42
|
+
npx tupik audit ./dist/app.js --format sarif --out audit.sarif --fail-on error
|
|
43
|
+
npx tupik data-map ./dist/app.js --config privacy.json --out docs/data-map.md
|
|
44
|
+
npx tupik contract check ./dist/app.js --baseline contract.json --fail-on-breaking
|
|
45
|
+
npx tupik fuzz ./dist/app.js # runs tupik-fuzz from @tupik/testing
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`tupik audit` reports public routes, routes that receive or return `pii`/`health` (an error when the route is
|
|
49
|
+
public), writes without a `'rate-limited'` middleware, `:id` routes without `owner` or a policy and, with
|
|
50
|
+
`--baseline`, contract changes (breaking = error). Formats `text`, `json`, `sarif`; `--fail-on error|warning|note|none`;
|
|
51
|
+
`--disable rule,...`. `tupik data-map` lists per route the classified fields it receives and returns, merged with
|
|
52
|
+
purpose and legal basis from `--config` (`{ "defaults": {...}, "routes": { "POST /users": { "purpose", "legalBasis",
|
|
53
|
+
"retention", "notes" } } }`); `--strict` fails while a route lacks them.
|
|
54
|
+
|
|
55
|
+
To accept one finding on purpose, tag the route with `acceptAudit(rule, reason)`. The reason is mandatory (an empty one
|
|
56
|
+
throws, and a hand-written acceptance tag without a reason is ignored with a message saying so). The finding stays in
|
|
57
|
+
the report as a `note` with `accepted`, the text report prints `accepted: <reason>` under it, and SARIF marks it as
|
|
58
|
+
suppressed in source:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { classify, createModule } from '@tupik/core';
|
|
62
|
+
import { acceptAudit } from '@tupik/openapi';
|
|
63
|
+
import { z } from 'zod';
|
|
64
|
+
|
|
65
|
+
const SignUp = classify(z.object({ email: z.string(), password: z.string() }), { email: 'pii', password: 'secret' });
|
|
66
|
+
|
|
67
|
+
createModule('/auth').post('/sign-up', {
|
|
68
|
+
access: 'public',
|
|
69
|
+
schema: { body: SignUp },
|
|
70
|
+
tags: [acceptAudit('public-sensitive-data', 'sign-up receives the e-mail before there is a user')],
|
|
71
|
+
handler: () => ({ ok: true }),
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`tupik-contract snapshot|check` stays as a standalone bin. Snapshots record routes, methods, declared statuses,
|
|
76
|
+
request schema presence, the access kind, auth level and data classes, and required body fields when the body schema
|
|
77
|
+
exposes a JSON Schema. Exit codes: `0` ok, `1` findings/breaking changes, `2` usage, `3` error.
|
|
78
|
+
|
|
79
|
+
### Data subject requests
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { defineSubjectRequests } from '@tupik/openapi';
|
|
83
|
+
|
|
84
|
+
app.register(defineSubjectRequests({
|
|
85
|
+
export: (subjectId) => db.exportUser(subjectId), // GET /privacy/export
|
|
86
|
+
erase: (subjectId) => db.eraseUser(subjectId), // DELETE /privacy/data (202)
|
|
87
|
+
}));
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Both routes require a principal (`access` defaults to `'authenticated'`; `'public'` throws), the subject is the
|
|
91
|
+
principal id (or `subjectId: (ctx) => ...`), and `tupik data-map` lists them.
|
|
92
|
+
|
|
93
|
+
## Key API
|
|
94
|
+
|
|
95
|
+
| Export | Purpose |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `generateOpenApiDocument(app, { info?, schemaConverter?, securitySchemes?, securityScheme? })` | OpenAPI 3.1 document from routes and their metadata |
|
|
98
|
+
| `snapshotContract(app)` / `diffContracts(a, b)` / `hasBreakingChanges` / `formatContractChanges` | Contract diffing |
|
|
99
|
+
| `auditApp(app, options)` / `formatAuditText` / `auditToSarif` / `shouldFail` | Security audit |
|
|
100
|
+
| `acceptAudit(rule, reason)` | Route tag that accepts one audit finding, with the reason shown in every report format |
|
|
101
|
+
| `buildDataMap(app, config)` / `formatDataMapMarkdown` / `parseDataMapConfig` | Personal data map |
|
|
102
|
+
| `defineSubjectRequests({ export, erase })` | Export/erase routes for data subject requests |
|
|
103
|
+
| `@tupik/openapi/cli`: `runTupikCli(argv)`, `runContractCli(argv)` | Programmatic CLIs |
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT
|
package/bin/tupik.mjs
ADDED
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { ContractAppLike } from './index.mjs';
|
|
2
|
+
import '@tupik/core';
|
|
3
|
+
|
|
4
|
+
/** I/O seams of the CLIs (tests inject them; defaults use `import()` and `node:fs`). */
|
|
5
|
+
interface CliDeps {
|
|
6
|
+
/** Loads the app module. Default: dynamic `import()` (paths resolved against `cwd`). */
|
|
7
|
+
loadModule?: (specifier: string) => Promise<unknown>;
|
|
8
|
+
stdout?: (line: string) => void;
|
|
9
|
+
readFile?: (path: string) => Promise<string>;
|
|
10
|
+
writeFile?: (path: string, data: string) => Promise<void>;
|
|
11
|
+
/** Base directory for relative paths. Default: the process working directory. */
|
|
12
|
+
cwd?: string;
|
|
13
|
+
}
|
|
14
|
+
interface ResolvedCliDeps {
|
|
15
|
+
readonly loadModule: (specifier: string) => Promise<unknown>;
|
|
16
|
+
readonly stdout: (line: string) => void;
|
|
17
|
+
readonly readFile: (path: string) => Promise<string>;
|
|
18
|
+
readonly writeFile: (path: string, data: string) => Promise<void>;
|
|
19
|
+
readonly cwd: string | undefined;
|
|
20
|
+
}
|
|
21
|
+
declare class UsageError extends Error {
|
|
22
|
+
}
|
|
23
|
+
interface ParsedArgs {
|
|
24
|
+
readonly positionals: string[];
|
|
25
|
+
readonly options: Map<string, string | true>;
|
|
26
|
+
}
|
|
27
|
+
/** `--flag value`, `--flag=value` and boolean `--flag`; names in `valueFlags` take the next argument. */
|
|
28
|
+
declare function parseArgs(argv: readonly string[], valueFlags: ReadonlySet<string>): ParsedArgs;
|
|
29
|
+
declare function optionalValue(args: ParsedArgs, name: string): string | undefined;
|
|
30
|
+
/** `--name` restricted to `choices` (default when absent). */
|
|
31
|
+
declare function choiceValue<TChoice extends string>(args: ParsedArgs, name: string, choices: readonly TChoice[], fallback: TChoice): TChoice;
|
|
32
|
+
/** The `<module>` positional at `index` (after the command words). */
|
|
33
|
+
declare function requireModule(args: ParsedArgs, index?: number): string;
|
|
34
|
+
declare function resolveCliDeps(deps: CliDeps): ResolvedCliDeps;
|
|
35
|
+
/** Loads `<module>` and returns its app. */
|
|
36
|
+
declare function loadApp(io: ResolvedCliDeps, specifier: string): Promise<ContractAppLike>;
|
|
37
|
+
/** Reads and parses a JSON file (relative to `cwd`), naming the file on a syntax error. */
|
|
38
|
+
declare function readJson(io: ResolvedCliDeps, path: string, label: string): Promise<unknown>;
|
|
39
|
+
declare function writeOutput(io: ResolvedCliDeps, path: string, data: string): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Runs `body`, mapping a `UsageError` to exit 2 (with `usage`) and any other
|
|
42
|
+
* error to exit 3. CLIs never throw.
|
|
43
|
+
*/
|
|
44
|
+
declare function runCommand(io: ResolvedCliDeps, usage: string, body: () => Promise<number>): Promise<number>;
|
|
45
|
+
|
|
46
|
+
type ContractCliDeps = CliDeps;
|
|
47
|
+
declare const CONTRACT_CLI_USAGE: string;
|
|
48
|
+
/**
|
|
49
|
+
* `tupik-contract` entry point. Never throws: returns the process exit code
|
|
50
|
+
* (0 ok, 1 breaking with `--fail-on-breaking`, 2 usage, 3 runtime error).
|
|
51
|
+
*/
|
|
52
|
+
declare function runContractCli(argv: readonly string[], deps?: ContractCliDeps): Promise<number>;
|
|
53
|
+
/** `snapshot` / `check` with already parsed arguments (shared with `tupik contract`). */
|
|
54
|
+
declare function runContractCommand(io: ResolvedCliDeps, positionals: string[], options: Map<string, string | true>): Promise<number>;
|
|
55
|
+
|
|
56
|
+
interface TupikCliDeps extends CliDeps {
|
|
57
|
+
/** Runs an external `tupik-<command>` binary; resolves its exit code. Default: `node:child_process`. */
|
|
58
|
+
spawn?: (command: string, args: readonly string[]) => Promise<number>;
|
|
59
|
+
}
|
|
60
|
+
declare const TUPIK_CLI_USAGE: string;
|
|
61
|
+
/**
|
|
62
|
+
* `tupik` entry point: `audit`, `data-map` and `contract` run here; `fuzz`
|
|
63
|
+
* and `lint` run the `tupik-<command>` binary of their package. Never throws.
|
|
64
|
+
*/
|
|
65
|
+
declare function runTupikCli(argv: readonly string[], deps?: TupikCliDeps): Promise<number>;
|
|
66
|
+
|
|
67
|
+
export { CONTRACT_CLI_USAGE, TUPIK_CLI_USAGE, UsageError, choiceValue, loadApp, optionalValue, parseArgs, readJson, requireModule, resolveCliDeps, runCommand, runContractCli, runContractCommand, runTupikCli, writeOutput };
|
|
68
|
+
export type { CliDeps, ContractCliDeps, ParsedArgs, ResolvedCliDeps, TupikCliDeps };
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { ContractAppLike } from './index.js';
|
|
2
|
+
import '@tupik/core';
|
|
3
|
+
|
|
4
|
+
/** I/O seams of the CLIs (tests inject them; defaults use `import()` and `node:fs`). */
|
|
5
|
+
interface CliDeps {
|
|
6
|
+
/** Loads the app module. Default: dynamic `import()` (paths resolved against `cwd`). */
|
|
7
|
+
loadModule?: (specifier: string) => Promise<unknown>;
|
|
8
|
+
stdout?: (line: string) => void;
|
|
9
|
+
readFile?: (path: string) => Promise<string>;
|
|
10
|
+
writeFile?: (path: string, data: string) => Promise<void>;
|
|
11
|
+
/** Base directory for relative paths. Default: the process working directory. */
|
|
12
|
+
cwd?: string;
|
|
13
|
+
}
|
|
14
|
+
interface ResolvedCliDeps {
|
|
15
|
+
readonly loadModule: (specifier: string) => Promise<unknown>;
|
|
16
|
+
readonly stdout: (line: string) => void;
|
|
17
|
+
readonly readFile: (path: string) => Promise<string>;
|
|
18
|
+
readonly writeFile: (path: string, data: string) => Promise<void>;
|
|
19
|
+
readonly cwd: string | undefined;
|
|
20
|
+
}
|
|
21
|
+
declare class UsageError extends Error {
|
|
22
|
+
}
|
|
23
|
+
interface ParsedArgs {
|
|
24
|
+
readonly positionals: string[];
|
|
25
|
+
readonly options: Map<string, string | true>;
|
|
26
|
+
}
|
|
27
|
+
/** `--flag value`, `--flag=value` and boolean `--flag`; names in `valueFlags` take the next argument. */
|
|
28
|
+
declare function parseArgs(argv: readonly string[], valueFlags: ReadonlySet<string>): ParsedArgs;
|
|
29
|
+
declare function optionalValue(args: ParsedArgs, name: string): string | undefined;
|
|
30
|
+
/** `--name` restricted to `choices` (default when absent). */
|
|
31
|
+
declare function choiceValue<TChoice extends string>(args: ParsedArgs, name: string, choices: readonly TChoice[], fallback: TChoice): TChoice;
|
|
32
|
+
/** The `<module>` positional at `index` (after the command words). */
|
|
33
|
+
declare function requireModule(args: ParsedArgs, index?: number): string;
|
|
34
|
+
declare function resolveCliDeps(deps: CliDeps): ResolvedCliDeps;
|
|
35
|
+
/** Loads `<module>` and returns its app. */
|
|
36
|
+
declare function loadApp(io: ResolvedCliDeps, specifier: string): Promise<ContractAppLike>;
|
|
37
|
+
/** Reads and parses a JSON file (relative to `cwd`), naming the file on a syntax error. */
|
|
38
|
+
declare function readJson(io: ResolvedCliDeps, path: string, label: string): Promise<unknown>;
|
|
39
|
+
declare function writeOutput(io: ResolvedCliDeps, path: string, data: string): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Runs `body`, mapping a `UsageError` to exit 2 (with `usage`) and any other
|
|
42
|
+
* error to exit 3. CLIs never throw.
|
|
43
|
+
*/
|
|
44
|
+
declare function runCommand(io: ResolvedCliDeps, usage: string, body: () => Promise<number>): Promise<number>;
|
|
45
|
+
|
|
46
|
+
type ContractCliDeps = CliDeps;
|
|
47
|
+
declare const CONTRACT_CLI_USAGE: string;
|
|
48
|
+
/**
|
|
49
|
+
* `tupik-contract` entry point. Never throws: returns the process exit code
|
|
50
|
+
* (0 ok, 1 breaking with `--fail-on-breaking`, 2 usage, 3 runtime error).
|
|
51
|
+
*/
|
|
52
|
+
declare function runContractCli(argv: readonly string[], deps?: ContractCliDeps): Promise<number>;
|
|
53
|
+
/** `snapshot` / `check` with already parsed arguments (shared with `tupik contract`). */
|
|
54
|
+
declare function runContractCommand(io: ResolvedCliDeps, positionals: string[], options: Map<string, string | true>): Promise<number>;
|
|
55
|
+
|
|
56
|
+
interface TupikCliDeps extends CliDeps {
|
|
57
|
+
/** Runs an external `tupik-<command>` binary; resolves its exit code. Default: `node:child_process`. */
|
|
58
|
+
spawn?: (command: string, args: readonly string[]) => Promise<number>;
|
|
59
|
+
}
|
|
60
|
+
declare const TUPIK_CLI_USAGE: string;
|
|
61
|
+
/**
|
|
62
|
+
* `tupik` entry point: `audit`, `data-map` and `contract` run here; `fuzz`
|
|
63
|
+
* and `lint` run the `tupik-<command>` binary of their package. Never throws.
|
|
64
|
+
*/
|
|
65
|
+
declare function runTupikCli(argv: readonly string[], deps?: TupikCliDeps): Promise<number>;
|
|
66
|
+
|
|
67
|
+
export { CONTRACT_CLI_USAGE, TUPIK_CLI_USAGE, UsageError, choiceValue, loadApp, optionalValue, parseArgs, readJson, requireModule, resolveCliDeps, runCommand, runContractCli, runContractCommand, runTupikCli, writeOutput };
|
|
68
|
+
export type { CliDeps, ContractCliDeps, ParsedArgs, ResolvedCliDeps, TupikCliDeps };
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import { s as snapshotContract, p as parseContractSnapshot, d as diffContracts, f as formatContractChanges, h as hasBreakingChanges, A as AUDIT_RULES, a as parseDataMapConfig, b as buildDataMap, c as formatDataMapMarkdown, e as auditApp, g as shouldFail, i as auditToSarif, j as formatAuditText } from './shared/openapi.B3aGIYpz.mjs';
|
|
2
|
+
import '@tupik/core';
|
|
3
|
+
|
|
4
|
+
class UsageError extends Error {
|
|
5
|
+
}
|
|
6
|
+
function parseArgs(argv, valueFlags) {
|
|
7
|
+
const positionals = [];
|
|
8
|
+
const options = /* @__PURE__ */ new Map();
|
|
9
|
+
for (let i = 0; i < argv.length; i++) {
|
|
10
|
+
const arg = argv[i];
|
|
11
|
+
if (arg === void 0) continue;
|
|
12
|
+
if (!arg.startsWith("--")) {
|
|
13
|
+
positionals.push(arg);
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
const eq = arg.indexOf("=");
|
|
17
|
+
const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
|
|
18
|
+
if (eq !== -1) {
|
|
19
|
+
options.set(name, arg.slice(eq + 1));
|
|
20
|
+
} else if (valueFlags.has(name)) {
|
|
21
|
+
const next = argv[i + 1];
|
|
22
|
+
if (next === void 0 || next.startsWith("--")) throw new UsageError(`missing value for --${name}`);
|
|
23
|
+
options.set(name, next);
|
|
24
|
+
i++;
|
|
25
|
+
} else {
|
|
26
|
+
options.set(name, true);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return { positionals, options };
|
|
30
|
+
}
|
|
31
|
+
function optionalValue(args, name) {
|
|
32
|
+
const value = args.options.get(name);
|
|
33
|
+
if (value === true || value === "") throw new UsageError(`missing value for --${name}`);
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
function requireValue(args, name) {
|
|
37
|
+
const value = args.options.get(name);
|
|
38
|
+
if (typeof value !== "string" || value === "") throw new UsageError(`missing --${name} <file>`);
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
function choiceValue(args, name, choices, fallback) {
|
|
42
|
+
const value = optionalValue(args, name);
|
|
43
|
+
if (value === void 0) return fallback;
|
|
44
|
+
if (!choices.includes(value)) throw new UsageError(`--${name} must be one of ${choices.join(", ")} (got "${value}")`);
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
function requireModule(args, index = 1) {
|
|
48
|
+
const spec = args.positionals[index];
|
|
49
|
+
if (spec === void 0) throw new UsageError("missing <module>");
|
|
50
|
+
return spec;
|
|
51
|
+
}
|
|
52
|
+
function isAbsolute(path) {
|
|
53
|
+
return path.startsWith("/") || path.startsWith("\\") || /^[A-Za-z]:[\\/]/.test(path);
|
|
54
|
+
}
|
|
55
|
+
function resolvePath(cwd, path) {
|
|
56
|
+
if (cwd === void 0 || isAbsolute(path)) return path;
|
|
57
|
+
return `${cwd.replace(/[\\/]+$/, "")}/${path}`;
|
|
58
|
+
}
|
|
59
|
+
function isPathSpecifier(spec) {
|
|
60
|
+
return spec.startsWith(".") || isAbsolute(spec);
|
|
61
|
+
}
|
|
62
|
+
function errorMessage(error) {
|
|
63
|
+
return error instanceof Error ? error.message : String(error);
|
|
64
|
+
}
|
|
65
|
+
function isObjectLike(value) {
|
|
66
|
+
return (typeof value === "object" || typeof value === "function") && value !== null;
|
|
67
|
+
}
|
|
68
|
+
function isAppLike(value) {
|
|
69
|
+
if (!isObjectLike(value)) return false;
|
|
70
|
+
const routes = value["routes"];
|
|
71
|
+
return Array.isArray(routes) && routes.every((r) => isObjectLike(r) && typeof r["method"] === "string" && typeof r["path"] === "string");
|
|
72
|
+
}
|
|
73
|
+
function extractApp(mod, specifier) {
|
|
74
|
+
const candidate = isObjectLike(mod) ? mod["default"] ?? mod["app"] : void 0;
|
|
75
|
+
if (!isAppLike(candidate)) {
|
|
76
|
+
throw new Error(`module "${specifier}" must export a Tupik app with \`routes\` as \`default\` or \`app\``);
|
|
77
|
+
}
|
|
78
|
+
return candidate;
|
|
79
|
+
}
|
|
80
|
+
async function defaultLoadModule(specifier, cwd) {
|
|
81
|
+
if (!isPathSpecifier(specifier)) return import(specifier);
|
|
82
|
+
const { resolve } = await import('node:path');
|
|
83
|
+
const { pathToFileURL } = await import('node:url');
|
|
84
|
+
return import(pathToFileURL(resolve(cwd ?? process.cwd(), specifier)).href);
|
|
85
|
+
}
|
|
86
|
+
async function defaultReadFile(path) {
|
|
87
|
+
const fs = await import('node:fs/promises');
|
|
88
|
+
return fs.readFile(path, "utf8");
|
|
89
|
+
}
|
|
90
|
+
async function defaultWriteFile(path, data) {
|
|
91
|
+
const fs = await import('node:fs/promises');
|
|
92
|
+
const { dirname } = await import('node:path');
|
|
93
|
+
await fs.mkdir(dirname(path), { recursive: true });
|
|
94
|
+
await fs.writeFile(path, data, "utf8");
|
|
95
|
+
}
|
|
96
|
+
function resolveCliDeps(deps) {
|
|
97
|
+
const cwd = deps.cwd;
|
|
98
|
+
return {
|
|
99
|
+
cwd,
|
|
100
|
+
stdout: deps.stdout ?? ((line) => {
|
|
101
|
+
console.log(line);
|
|
102
|
+
}),
|
|
103
|
+
loadModule: deps.loadModule ?? ((spec) => defaultLoadModule(spec, cwd)),
|
|
104
|
+
readFile: deps.readFile ?? defaultReadFile,
|
|
105
|
+
writeFile: deps.writeFile ?? defaultWriteFile
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
async function loadApp(io, specifier) {
|
|
109
|
+
return extractApp(await io.loadModule(specifier), specifier);
|
|
110
|
+
}
|
|
111
|
+
async function readJson(io, path, label) {
|
|
112
|
+
const raw = await io.readFile(resolvePath(io.cwd, path));
|
|
113
|
+
try {
|
|
114
|
+
return JSON.parse(raw);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
throw new Error(`invalid ${label}: ${path} is not valid JSON (${errorMessage(error)})`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async function writeOutput(io, path, data) {
|
|
120
|
+
await io.writeFile(resolvePath(io.cwd, path), data);
|
|
121
|
+
}
|
|
122
|
+
async function runCommand(io, usage, body) {
|
|
123
|
+
try {
|
|
124
|
+
return await body();
|
|
125
|
+
} catch (error) {
|
|
126
|
+
io.stdout(`error: ${errorMessage(error)}`);
|
|
127
|
+
if (!(error instanceof UsageError)) return 3;
|
|
128
|
+
io.stdout(usage);
|
|
129
|
+
return 2;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const CONTRACT_CLI_USAGE = [
|
|
134
|
+
"Usage: tupik-contract <command> [options]",
|
|
135
|
+
"",
|
|
136
|
+
"Commands:",
|
|
137
|
+
" snapshot <module> --out <file> write the route contract of <module> as JSON",
|
|
138
|
+
" check <module> --baseline <file> [--fail-on-breaking] diff <module> against a baseline snapshot",
|
|
139
|
+
"",
|
|
140
|
+
"<module> must export a Tupik app as `default` or `app`.",
|
|
141
|
+
"Exit codes: 0 ok, 1 breaking changes (with --fail-on-breaking), 2 usage, 3 error.",
|
|
142
|
+
"",
|
|
143
|
+
"Note: only runtime-inspectable facts are compared: routes, methods, paths, declared",
|
|
144
|
+
"response status codes, presence of body/query/params/headers schemas, the access kind,",
|
|
145
|
+
"auth level and data classes of each route (route metadata), and required body fields",
|
|
146
|
+
"when the body schema exposes a JSON Schema. Other changes inside a schema are not detected."
|
|
147
|
+
].join("\n");
|
|
148
|
+
const VALUE_FLAGS$1 = /* @__PURE__ */ new Set(["out", "baseline"]);
|
|
149
|
+
async function runContractCli(argv, deps = {}) {
|
|
150
|
+
const io = resolveCliDeps(deps);
|
|
151
|
+
return runCommand(io, CONTRACT_CLI_USAGE, async () => {
|
|
152
|
+
const args = parseArgs(argv, VALUE_FLAGS$1);
|
|
153
|
+
const command = args.positionals[0];
|
|
154
|
+
if (args.options.has("help") && command === void 0) {
|
|
155
|
+
io.stdout(CONTRACT_CLI_USAGE);
|
|
156
|
+
return 0;
|
|
157
|
+
}
|
|
158
|
+
return runContractCommand(io, args.positionals, args.options);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async function runContractCommand(io, positionals, options) {
|
|
162
|
+
const args = { positionals, options };
|
|
163
|
+
const command = positionals[0];
|
|
164
|
+
if (command === "snapshot") {
|
|
165
|
+
const moduleSpec = requireModule(args);
|
|
166
|
+
const out = requireValue(args, "out");
|
|
167
|
+
const snapshot = snapshotContract(await loadApp(io, moduleSpec));
|
|
168
|
+
await writeOutput(io, out, `${JSON.stringify(snapshot, null, 2)}
|
|
169
|
+
`);
|
|
170
|
+
io.stdout(`snapshot written: ${out} (${snapshot.routes.length} routes)`);
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
if (command === "check") {
|
|
174
|
+
const moduleSpec = requireModule(args);
|
|
175
|
+
const baselinePath = requireValue(args, "baseline");
|
|
176
|
+
const baseline = parseContractSnapshot(await readJson(io, baselinePath, "baseline"));
|
|
177
|
+
const changes = diffContracts(baseline, snapshotContract(await loadApp(io, moduleSpec)));
|
|
178
|
+
io.stdout(formatContractChanges(changes));
|
|
179
|
+
return options.has("fail-on-breaking") && hasBreakingChanges(changes) ? 1 : 0;
|
|
180
|
+
}
|
|
181
|
+
throw new UsageError(command === void 0 ? "missing command" : `unknown command "${command}"`);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const TUPIK_CLI_USAGE = [
|
|
185
|
+
"Usage: tupik <command> [options]",
|
|
186
|
+
"",
|
|
187
|
+
"Commands:",
|
|
188
|
+
" audit <module> security report of the route metadata",
|
|
189
|
+
" [--format text|json|sarif] [--out <file>] [--fail-on error|warning|note|none]",
|
|
190
|
+
" [--baseline <contract.json>] [--disable <rule,...>] [--rate-limit-tag <tag>]",
|
|
191
|
+
" data-map <module> personal data map (LGPD/GDPR) as Markdown (+ JSON with --out)",
|
|
192
|
+
" [--config <file>] [--out <file.md>] [--format markdown|json] [--strict]",
|
|
193
|
+
" contract snapshot|check ... same as tupik-contract",
|
|
194
|
+
" fuzz, lint run tupik-fuzz (@tupik/testing) / tupik-lint (@tupik/lint)",
|
|
195
|
+
"",
|
|
196
|
+
"<module> must export a Tupik app as `default` or `app`.",
|
|
197
|
+
`Audit rules: ${Object.keys(AUDIT_RULES).join(", ")}.`,
|
|
198
|
+
"Exit codes: 0 ok, 1 findings at --fail-on (audit) or missing legal basis with --strict (data-map),",
|
|
199
|
+
"2 usage, 3 error."
|
|
200
|
+
].join("\n");
|
|
201
|
+
const VALUE_FLAGS = /* @__PURE__ */ new Set(["format", "out", "fail-on", "baseline", "disable", "rate-limit-tag", "config"]);
|
|
202
|
+
const FAIL_ON = ["error", "warning", "note", "none"];
|
|
203
|
+
const EXTERNAL_COMMANDS = { fuzz: "@tupik/testing", lint: "@tupik/lint" };
|
|
204
|
+
function disabledRules(args) {
|
|
205
|
+
const value = optionalValue(args, "disable");
|
|
206
|
+
if (value === void 0) return [];
|
|
207
|
+
const rules = value.split(",").map((rule) => rule.trim()).filter((rule) => rule !== "");
|
|
208
|
+
for (const rule of rules) {
|
|
209
|
+
if (!Object.hasOwn(AUDIT_RULES, rule)) throw new UsageError(`unknown audit rule "${rule}" (rules: ${Object.keys(AUDIT_RULES).join(", ")})`);
|
|
210
|
+
}
|
|
211
|
+
return rules;
|
|
212
|
+
}
|
|
213
|
+
const AUDIT_FORMATS = {
|
|
214
|
+
text: (report) => formatAuditText(report),
|
|
215
|
+
json: (report) => JSON.stringify(report, null, 2),
|
|
216
|
+
sarif: (report, uri) => JSON.stringify(auditToSarif(report, { uri }), null, 2)
|
|
217
|
+
};
|
|
218
|
+
function artifactUri(spec) {
|
|
219
|
+
return spec.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
220
|
+
}
|
|
221
|
+
const audit = async (io, args) => {
|
|
222
|
+
const moduleSpec = requireModule(args);
|
|
223
|
+
const format = choiceValue(args, "format", Object.keys(AUDIT_FORMATS), "text");
|
|
224
|
+
const failOn = choiceValue(args, "fail-on", FAIL_ON, "error");
|
|
225
|
+
const disable = disabledRules(args);
|
|
226
|
+
const baselinePath = optionalValue(args, "baseline");
|
|
227
|
+
const rateLimitTag = optionalValue(args, "rate-limit-tag");
|
|
228
|
+
const out = optionalValue(args, "out");
|
|
229
|
+
const app = await loadApp(io, moduleSpec);
|
|
230
|
+
const report = auditApp(app, {
|
|
231
|
+
disable,
|
|
232
|
+
...rateLimitTag === void 0 ? {} : { rateLimitTag },
|
|
233
|
+
...baselinePath === void 0 ? {} : { baseline: parseContractSnapshot(await readJson(io, baselinePath, "baseline")) }
|
|
234
|
+
});
|
|
235
|
+
const output = AUDIT_FORMATS[format](report, artifactUri(moduleSpec));
|
|
236
|
+
if (out === void 0) io.stdout(output);
|
|
237
|
+
else {
|
|
238
|
+
await writeOutput(io, out, `${output}
|
|
239
|
+
`);
|
|
240
|
+
io.stdout(`audit written: ${out} (${report.findings.length} findings in ${report.routes} routes)`);
|
|
241
|
+
}
|
|
242
|
+
return shouldFail(report, failOn) ? 1 : 0;
|
|
243
|
+
};
|
|
244
|
+
const dataMap = async (io, args) => {
|
|
245
|
+
const moduleSpec = requireModule(args);
|
|
246
|
+
const configPath = optionalValue(args, "config");
|
|
247
|
+
const out = optionalValue(args, "out");
|
|
248
|
+
const format = choiceValue(args, "format", ["markdown", "json"], "markdown");
|
|
249
|
+
const config = configPath === void 0 ? {} : parseDataMapConfig(await readJson(io, configPath, "data map config"));
|
|
250
|
+
const map = buildDataMap(await loadApp(io, moduleSpec), config);
|
|
251
|
+
const markdown = formatDataMapMarkdown(map);
|
|
252
|
+
const json = `${JSON.stringify(map, null, 2)}
|
|
253
|
+
`;
|
|
254
|
+
if (out === void 0) io.stdout(format === "json" ? json.trimEnd() : markdown.trimEnd());
|
|
255
|
+
else {
|
|
256
|
+
const base = out.replace(/\.(md|json)$/, "");
|
|
257
|
+
await writeOutput(io, `${base}.md`, markdown);
|
|
258
|
+
await writeOutput(io, `${base}.json`, json);
|
|
259
|
+
io.stdout(`data map written: ${base}.md, ${base}.json (${map.routes.length} routes, ${map.unannotated.length} without legal basis)`);
|
|
260
|
+
}
|
|
261
|
+
return args.options.has("strict") && map.unannotated.length > 0 ? 1 : 0;
|
|
262
|
+
};
|
|
263
|
+
const contract = (io, args) => runContractCommand(io, args.positionals.slice(1), args.options);
|
|
264
|
+
const COMMANDS = { audit, "data-map": dataMap, contract };
|
|
265
|
+
async function defaultSpawn(command, args) {
|
|
266
|
+
const { spawn } = await import('node:child_process');
|
|
267
|
+
return new Promise((resolve, reject) => {
|
|
268
|
+
const child = spawn(command, [...args], { stdio: "inherit", shell: process.platform === "win32" });
|
|
269
|
+
child.once("error", reject);
|
|
270
|
+
child.once("exit", (code) => resolve(code ?? 1));
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
async function runExternal(io, spawn, command, argv) {
|
|
274
|
+
const binary = `tupik-${command}`;
|
|
275
|
+
try {
|
|
276
|
+
return await spawn(binary, argv);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (error.code !== "ENOENT") throw error;
|
|
279
|
+
throw new Error(`tupik ${command} needs ${binary}: install ${EXTERNAL_COMMANDS[command] ?? "the package that provides it"}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
async function runTupikCli(argv, deps = {}) {
|
|
283
|
+
const io = { ...resolveCliDeps(deps), spawn: deps.spawn ?? defaultSpawn };
|
|
284
|
+
return runCommand(io, TUPIK_CLI_USAGE, async () => {
|
|
285
|
+
const command = argv[0];
|
|
286
|
+
if (command !== void 0 && Object.hasOwn(EXTERNAL_COMMANDS, command)) return runExternal(io, io.spawn, command, argv.slice(1));
|
|
287
|
+
const args = parseArgs(argv, VALUE_FLAGS);
|
|
288
|
+
const name = args.positionals[0];
|
|
289
|
+
if (name === void 0 && args.options.has("help")) {
|
|
290
|
+
io.stdout(TUPIK_CLI_USAGE);
|
|
291
|
+
return 0;
|
|
292
|
+
}
|
|
293
|
+
const runner = name !== void 0 && Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : void 0;
|
|
294
|
+
if (runner === void 0) throw new UsageError(name === void 0 ? "missing command" : `unknown command "${name}"`);
|
|
295
|
+
return runner(io, args);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export { CONTRACT_CLI_USAGE, TUPIK_CLI_USAGE, UsageError, choiceValue, loadApp, optionalValue, parseArgs, readJson, requireModule, resolveCliDeps, runCommand, runContractCli, runContractCommand, runTupikCli, writeOutput };
|