@apso/cli 0.48.0 → 0.49.1

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 (82) hide show
  1. package/README.md +28 -1
  2. package/dist/commands/dev.d.ts +2 -0
  3. package/dist/commands/dev.js +20 -3
  4. package/dist/commands/generate.js +49 -13
  5. package/dist/commands/mcp/serve.js +24 -41
  6. package/dist/commands/schema/diff.js +3 -4
  7. package/dist/commands/schema/pull.js +13 -11
  8. package/dist/commands/schema/push.js +6 -5
  9. package/dist/commands/schema/validate.d.ts +10 -0
  10. package/dist/commands/schema/validate.js +54 -0
  11. package/dist/commands/test/access.d.ts +11 -0
  12. package/dist/commands/test/access.js +65 -0
  13. package/dist/lib/access/cases.d.ts +120 -0
  14. package/dist/lib/access/cases.js +1163 -0
  15. package/dist/lib/access/index.d.ts +4 -0
  16. package/dist/lib/access/index.js +7 -0
  17. package/dist/lib/access/report.d.ts +75 -0
  18. package/dist/lib/access/report.js +118 -0
  19. package/dist/lib/access/rules.json +207 -0
  20. package/dist/lib/access/run.d.ts +38 -0
  21. package/dist/lib/access/run.js +111 -0
  22. package/dist/lib/access/tokens.d.ts +46 -0
  23. package/dist/lib/access/tokens.js +139 -0
  24. package/dist/lib/api/services.d.ts +10 -7
  25. package/dist/lib/api/services.js +19 -32
  26. package/dist/lib/apsorc-parser.d.ts +1 -1
  27. package/dist/lib/apsorc-parser.js +2 -0
  28. package/dist/lib/deploy/server-push.js +3 -1
  29. package/dist/lib/generators/go.d.ts +13 -1
  30. package/dist/lib/generators/go.js +144 -33
  31. package/dist/lib/generators/python.d.ts +3 -3
  32. package/dist/lib/generators/python.js +48 -24
  33. package/dist/lib/generators/typescript.d.ts +3 -5
  34. package/dist/lib/generators/typescript.js +78 -64
  35. package/dist/lib/guards.d.ts +111 -13
  36. package/dist/lib/guards.js +287 -23
  37. package/dist/lib/templates/go/handlers/handler.eta +8 -8
  38. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  39. package/dist/lib/templates/go/index-module.eta +8 -5
  40. package/dist/lib/templates/go/mcp.eta +307 -0
  41. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  42. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  43. package/dist/lib/templates/go/services/service.eta +37 -16
  44. package/dist/lib/templates/go/utils/query.eta +37 -2
  45. package/dist/lib/templates/guards/guards.module.eta +37 -29
  46. package/dist/lib/templates/guards/index.eta +4 -0
  47. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  48. package/dist/lib/templates/guards/key.guard.eta +280 -0
  49. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  50. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  51. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  52. package/dist/lib/templates/python/auth.eta +354 -95
  53. package/dist/lib/templates/python/index-module.eta +7 -7
  54. package/dist/lib/templates/python/mcp.eta +284 -0
  55. package/dist/lib/templates/python/models/model.eta +6 -5
  56. package/dist/lib/templates/python/permissions.eta +121 -0
  57. package/dist/lib/templates/python/routers/router.eta +39 -1
  58. package/dist/lib/templates/python/schemas/schema.eta +18 -5
  59. package/dist/lib/templates/python/services/service.eta +38 -15
  60. package/dist/lib/templates/python/utils/query.eta +52 -25
  61. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  62. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  63. package/dist/lib/templates/rest/service-rest.eta +3 -44
  64. package/dist/lib/types/auth.d.ts +84 -80
  65. package/dist/lib/types/auth.js +77 -60
  66. package/dist/lib/types/entity.d.ts +17 -9
  67. package/dist/lib/types/entity.js +3 -0
  68. package/dist/lib/types/index.d.ts +2 -2
  69. package/dist/lib/types/index.js +6 -5
  70. package/dist/lib/utils/crud-deps.d.ts +77 -6
  71. package/dist/lib/utils/crud-deps.js +197 -14
  72. package/dist/lib/utils/schema-convert.d.ts +20 -43
  73. package/dist/lib/utils/schema-convert.js +28 -78
  74. package/dist/lib/utils/template.d.ts +11 -0
  75. package/dist/lib/utils/template.js +36 -1
  76. package/dist/lib/verify/index.d.ts +6 -1
  77. package/dist/lib/verify/index.js +30 -13
  78. package/npm-shrinkwrap.json +2 -2
  79. package/oclif.manifest.json +36 -1
  80. package/package.json +1 -1
  81. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  82. package/dist/lib/templates/guards/auth.guard.eta +0 -233
@@ -0,0 +1,4 @@
1
+ export * from "./report";
2
+ export * from "./tokens";
3
+ export * from "./cases";
4
+ export * from "./run";
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./report"), exports);
5
+ tslib_1.__exportStar(require("./tokens"), exports);
6
+ tslib_1.__exportStar(require("./cases"), exports);
7
+ tslib_1.__exportStar(require("./run"), exports);
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The access rule list (rules.json, from apsoai/cli#208) and the record of a
3
+ * suite run against it. Every case's label starts with the rule it proves,
4
+ * "[R6] ..." or "[R11,R12] ...", so a run can be reported rule by rule and a
5
+ * rule with no case fails the run.
6
+ */
7
+ export type Language = "typescript" | "python" | "go";
8
+ export type RuleStatus = "enforced" | "refused" | "pending" | "na";
9
+ export interface Rule {
10
+ id: string;
11
+ group: string;
12
+ rule: string;
13
+ status: Record<Language, RuleStatus>;
14
+ /** The work that builds a pending rule. */
15
+ issue?: string;
16
+ /** Set on rules only the hosted platform provides: what the platform adds. */
17
+ platform?: string;
18
+ note?: string;
19
+ }
20
+ export declare const RULES: Rule[];
21
+ export declare const LANGUAGES: Language[];
22
+ /** The rule ids a case label names, e.g. "[R11,R12] ..." gives R11 and R12. */
23
+ export declare const ruleIdsOf: (label: string) => string[];
24
+ export interface CaseResult {
25
+ rules: string[];
26
+ /** The part of the run the case belongs to (a provider, or a service). */
27
+ leg: string;
28
+ label: string;
29
+ pass: boolean;
30
+ detail?: string;
31
+ }
32
+ export interface Response {
33
+ status: number;
34
+ text: string;
35
+ }
36
+ export interface Checker {
37
+ /** Pass when the response has one of the given statuses. */
38
+ expect(label: string, res: Response, ...ok: number[]): boolean;
39
+ assert(label: string, cond: boolean, detail?: string): boolean;
40
+ failures: string[];
41
+ }
42
+ export interface RuleRow {
43
+ id: string;
44
+ rule: string;
45
+ status: RuleStatus;
46
+ /** pass, FAIL, "no case" (a failure for an enforced or refused rule), or "-". */
47
+ result: string;
48
+ passed: number;
49
+ failed: number;
50
+ note: string;
51
+ }
52
+ export interface Report {
53
+ language: Language;
54
+ results: CaseResult[];
55
+ checker(leg: string): Checker;
56
+ /** Things wrong with the suite itself: untagged cases, unknown rule ids. */
57
+ problems(): string[];
58
+ rows(only?: (rule: Rule) => boolean): RuleRow[];
59
+ /** Rules marked enforced or refused for this language that ran no case. */
60
+ uncovered(): string[];
61
+ table(only?: (rule: Rule) => boolean): string;
62
+ }
63
+ /**
64
+ * A record of one language's run.
65
+ * @param {Language} language - The language of the service under test
66
+ * @param {Function} log - Where case lines go
67
+ * @returns {Report} The record
68
+ */
69
+ export declare function createReport(language: Language, log?: (line: string) => unknown): Report;
70
+ /**
71
+ * One table for several languages' runs, as Markdown.
72
+ * @param {Record<string, RuleRow[]>} byLanguage - Each language's rows, from Report.rows()
73
+ * @returns {string} The table
74
+ */
75
+ export declare function markdownTable(byLanguage: Partial<Record<Language, RuleRow[]>>): string;
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ /**
3
+ * The access rule list (rules.json, from apsoai/cli#208) and the record of a
4
+ * suite run against it. Every case's label starts with the rule it proves,
5
+ * "[R6] ..." or "[R11,R12] ...", so a run can be reported rule by rule and a
6
+ * rule with no case fails the run.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.markdownTable = exports.createReport = exports.ruleIdsOf = exports.LANGUAGES = exports.RULES = void 0;
10
+ const tslib_1 = require("tslib");
11
+ const rules_json_1 = tslib_1.__importDefault(require("./rules.json"));
12
+ exports.RULES = rules_json_1.default.rules;
13
+ exports.LANGUAGES = ["typescript", "python", "go"];
14
+ const TAG = /^\[(R\d+(?:\s*,\s*R\d+)*)]\s*/;
15
+ /** The rule ids a case label names, e.g. "[R11,R12] ..." gives R11 and R12. */
16
+ const ruleIdsOf = (label) => { var _a, _b; return (_b = (_a = TAG.exec(label)) === null || _a === void 0 ? void 0 : _a[1].split(/\s*,\s*/)) !== null && _b !== void 0 ? _b : []; };
17
+ exports.ruleIdsOf = ruleIdsOf;
18
+ /**
19
+ * A record of one language's run.
20
+ * @param {Language} language - The language of the service under test
21
+ * @param {Function} log - Where case lines go
22
+ * @returns {Report} The record
23
+ */
24
+ function createReport(language, log = console.log) {
25
+ const results = [];
26
+ const known = new Set(exports.RULES.map((r) => r.id));
27
+ const record = (leg, failures, label, pass, shown, detail) => {
28
+ log(` ${pass ? "ok " : "FAIL"} ${label}${shown}`);
29
+ results.push({ rules: (0, exports.ruleIdsOf)(label), leg, label, pass, detail: pass ? undefined : detail });
30
+ if (!pass)
31
+ failures.push(`${leg}: ${label}${detail ? ` ${detail}` : ""}`);
32
+ return pass;
33
+ };
34
+ const rows = (only = () => true) => exports.RULES.filter((rule) => only(rule)).map((rule) => {
35
+ var _a;
36
+ const cases = results.filter((c) => c.rules.includes(rule.id));
37
+ const failed = cases.filter((c) => !c.pass).length;
38
+ const status = rule.status[language];
39
+ const needsCase = status === "enforced" || status === "refused";
40
+ let result = "-";
41
+ if (failed > 0)
42
+ result = "FAIL";
43
+ else if (cases.length > 0)
44
+ result = "pass";
45
+ else if (needsCase)
46
+ result = "no case";
47
+ return {
48
+ id: rule.id,
49
+ rule: rule.rule,
50
+ status,
51
+ result,
52
+ passed: cases.length - failed,
53
+ failed,
54
+ note: status === "pending" ? (_a = rule.issue) !== null && _a !== void 0 ? _a : "" : "",
55
+ };
56
+ });
57
+ return {
58
+ language,
59
+ results,
60
+ checker(leg) {
61
+ const failures = [];
62
+ return {
63
+ failures,
64
+ expect: (label, res, ...ok) => record(leg, failures, label, ok.includes(res.status), `: ${res.status}`, `got ${res.status} ${res.text.slice(0, 300)}`),
65
+ assert: (label, cond, detail = "") => record(leg, failures, label, Boolean(cond), "", detail),
66
+ };
67
+ },
68
+ problems() {
69
+ const out = new Set();
70
+ for (const c of results) {
71
+ if (c.rules.length === 0)
72
+ out.add(`case names no rule: "${c.label}"`);
73
+ for (const id of c.rules)
74
+ if (!known.has(id))
75
+ out.add(`case names unknown rule ${id}: "${c.label}"`);
76
+ }
77
+ return [...out];
78
+ },
79
+ rows,
80
+ uncovered: () => rows()
81
+ .filter((r) => r.result === "no case")
82
+ .map((r) => r.id),
83
+ table(only) {
84
+ const lines = rows(only).map((r) => `${r.id.padEnd(4)} ${r.status.padEnd(9)} ${r.result.padEnd(8)} ${String(r.passed + r.failed).padStart(5)} ${r.note}`);
85
+ return [`Access rules, ${language}`, "rule status result cases", ...lines].join("\n");
86
+ },
87
+ };
88
+ }
89
+ exports.createReport = createReport;
90
+ /**
91
+ * One table for several languages' runs, as Markdown.
92
+ * @param {Record<string, RuleRow[]>} byLanguage - Each language's rows, from Report.rows()
93
+ * @returns {string} The table
94
+ */
95
+ function markdownTable(byLanguage) {
96
+ const langs = exports.LANGUAGES.filter((l) => byLanguage[l]);
97
+ const cell = (r) => {
98
+ if (!r)
99
+ return "";
100
+ if (r.status === "na")
101
+ return "n/a";
102
+ const count = r.passed + r.failed;
103
+ if (r.status === "pending")
104
+ return count > 0 ? `pending (${r.result}, ${count})` : "pending";
105
+ return `${r.status}: ${r.result}${count > 0 ? ` (${count})` : ""}`;
106
+ };
107
+ const lines = exports.RULES.map((rule) => {
108
+ var _a;
109
+ const cells = langs.map((l) => cell(byLanguage[l].find((r) => r.id === rule.id)));
110
+ return `| ${rule.id} | ${rule.rule} | ${cells.join(" | ")} | ${(_a = rule.issue) !== null && _a !== void 0 ? _a : ""} |`;
111
+ });
112
+ return [
113
+ `| # | Rule | ${langs.join(" | ")} | Built by |`,
114
+ `|---|---|${langs.map(() => "---").join("|")}|---|`,
115
+ ...lines,
116
+ ].join("\n");
117
+ }
118
+ exports.markdownTable = markdownTable;
@@ -0,0 +1,207 @@
1
+ {
2
+ "source": "apsoai/cli#208, draft 1. This file is the one place the rule list lives: correct a rule here and the suite, the check and `apso test access` follow.",
3
+ "statuses": {
4
+ "enforced": "The generated service enforces the rule in this language. The suite must run at least one case for it.",
5
+ "refused": "`apso generate` refuses the feature in this language. The suite must run a case that shows the refusal.",
6
+ "pending": "Not built yet. `issue` names the work that builds it and must add the cases.",
7
+ "na": "Does not apply to this language."
8
+ },
9
+ "rules": [
10
+ {
11
+ "id": "R0",
12
+ "group": "Default",
13
+ "rule": "The default is no access. A request is refused unless a rule below allows it. A missing setting, an unknown credential or an unrecognised case never opens anything.",
14
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
15
+ },
16
+ {
17
+ "id": "R1",
18
+ "group": "Who is calling",
19
+ "rule": "Every route needs a valid credential unless it is marked public. The health check is public.",
20
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
21
+ },
22
+ {
23
+ "id": "R2",
24
+ "group": "Who is calling",
25
+ "rule": "A token is accepted only when its signature, issuer, audience, expiry and algorithm all check out against the issuer's published keys.",
26
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
27
+ },
28
+ {
29
+ "id": "R3",
30
+ "group": "Who is calling",
31
+ "rule": "A token from an issuer that is not listed is refused. With several issuers, each token is checked only against its own issuer's keys, audience and claim names.",
32
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
33
+ },
34
+ {
35
+ "id": "R4",
36
+ "group": "Who is calling",
37
+ "rule": "Every accepted request has exactly one kind of caller: a user or a service.",
38
+ "status": { "typescript": "pending", "python": "pending", "go": "pending" },
39
+ "issue": "apsoai/cli#206"
40
+ },
41
+ {
42
+ "id": "R5",
43
+ "group": "Who is calling",
44
+ "rule": "An API key that does not match the chosen key source is refused.",
45
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
46
+ },
47
+ {
48
+ "id": "R6",
49
+ "group": "Tenant scope",
50
+ "rule": "A user caller reads and changes only rows of their own tenant.",
51
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" },
52
+ "note": "A scopeBy path through a parent (project.organizationId) is enforced in TypeScript and refused at generate in Python and Go. The scope covers every operation: `apso generate` refuses `scopeOptions.enforceOn`."
53
+ },
54
+ {
55
+ "id": "R7",
56
+ "group": "Tenant scope",
57
+ "rule": "Nothing in the query can widen that: not a filter, an `or` group, an embed, a sort or a count, in either query syntax. A TypeScript service accepts the PostgREST syntax only and answers 400 to a nestjsx parameter.",
58
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" },
59
+ "note": "A relation between two entities scoped by the same keys loads only rows of the caller's tenant, whatever the stored foreign key names."
60
+ },
61
+ {
62
+ "id": "R8",
63
+ "group": "Tenant scope",
64
+ "rule": "On create and update the tenant always becomes the caller's tenant, whatever the body says.",
65
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" },
66
+ "note": "No schema option turns this off: `apso generate` refuses `scopeOptions.injectOnCreate`. A foreign key to a tenant-scoped entity must name a row the caller can read, or the write is refused with 403. A service caller can set any tenant and any foreign key."
67
+ },
68
+ {
69
+ "id": "R9",
70
+ "group": "Tenant scope",
71
+ "rule": "A user token with no tenant is refused on tenant-scoped entities. The service never looks the tenant up.",
72
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
73
+ },
74
+ {
75
+ "id": "R10",
76
+ "group": "Tenant scope",
77
+ "rule": "Scope is skipped only for roles the schema names, and for service callers.",
78
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
79
+ },
80
+ {
81
+ "id": "R11",
82
+ "group": "Permissions",
83
+ "rule": "An operation limited to certain roles is refused to every other role, directly and through a join.",
84
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
85
+ },
86
+ {
87
+ "id": "R12",
88
+ "group": "Permissions",
89
+ "rule": "A grant adds a permission in the granting tenant only. It never removes a default, and a caller cannot grant a permission to themselves.",
90
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
91
+ },
92
+ {
93
+ "id": "R13",
94
+ "group": "Service callers",
95
+ "rule": "A caller with a valid API key is a service caller. It may call any route and sends its own tenant filter.",
96
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
97
+ },
98
+ {
99
+ "id": "R14",
100
+ "group": "Service callers",
101
+ "rule": "The key source is chosen once at start-up from the environment: a key set there, else the platform's gateway token, else keys are off. A key that fails its source is refused, and no other source is tried. With no key source and no sign-in configured, every request is refused.",
102
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
103
+ },
104
+ {
105
+ "id": "R15",
106
+ "group": "Platform gateway",
107
+ "rule": "A valid key at the gateway becomes a signed service token for that one service, valid for about a minute.",
108
+ "status": { "typescript": "pending", "python": "pending", "go": "pending" },
109
+ "issue": "apsoai/build-engine#179",
110
+ "platform": "The gateway checks the key against the platform's key table and signs the service token.",
111
+ "note": "The suite signs service tokens itself, so only the service's half (it accepts a valid token) has cases."
112
+ },
113
+ {
114
+ "id": "R16",
115
+ "group": "Platform gateway",
116
+ "rule": "A service token that is expired, changed, or issued for another service is refused.",
117
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" },
118
+ "platform": "Only a service the platform deployed is given the gateway's keys to check service tokens against."
119
+ },
120
+ {
121
+ "id": "R17",
122
+ "group": "Platform gateway",
123
+ "rule": "A service token header sent from outside is never trusted.",
124
+ "status": { "typescript": "pending", "python": "pending", "go": "pending" },
125
+ "issue": "apsoai/build-engine#179",
126
+ "platform": "The gateway replaces any service token header a caller sends.",
127
+ "note": "The service's half has cases: a token the gateway did not sign is refused."
128
+ },
129
+ {
130
+ "id": "R18",
131
+ "group": "Platform gateway",
132
+ "rule": "A request with no key reaches the service, and the service decides.",
133
+ "status": { "typescript": "pending", "python": "pending", "go": "pending" },
134
+ "issue": "apsoai/build-engine#179",
135
+ "platform": "The gateway lets a request with no key through unchanged.",
136
+ "note": "The service's half has cases: with no key, the user token decides."
137
+ },
138
+ {
139
+ "id": "R19",
140
+ "group": "Platform gateway",
141
+ "rule": "A browser cannot send the key.",
142
+ "status": { "typescript": "pending", "python": "pending", "go": "pending" },
143
+ "issue": "apsoai/build-engine#179",
144
+ "platform": "The gateway refuses the key header from browser origins."
145
+ },
146
+ {
147
+ "id": "R20",
148
+ "group": "Platform gateway",
149
+ "rule": "No service can read the key table, and the engine refuses to deploy code that has no guard.",
150
+ "status": { "typescript": "pending", "python": "pending", "go": "pending" },
151
+ "issue": "apsoai/build-engine#179",
152
+ "platform": "The key table is outside every service's database, and the engine checks for the guard before a deploy."
153
+ },
154
+ {
155
+ "id": "R21",
156
+ "group": "MCP",
157
+ "rule": "Only operations the schema opts in are tools.",
158
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
159
+ },
160
+ {
161
+ "id": "R22",
162
+ "group": "MCP",
163
+ "rule": "When sign-in is configured, every MCP request needs a valid token issued for the MCP endpoint, including listing tools.",
164
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
165
+ },
166
+ {
167
+ "id": "R23",
168
+ "group": "MCP",
169
+ "rule": "A tool call gets the same answer as the same REST call: same sign-in, permission and tenant checks.",
170
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
171
+ },
172
+ {
173
+ "id": "R24",
174
+ "group": "Logging",
175
+ "rule": "Every request, allowed or refused, writes one line with the caller, the request id, the route or tool, and the status.",
176
+ "status": { "typescript": "enforced", "python": "pending", "go": "pending" },
177
+ "issue": "apsoai/apso-packages#75"
178
+ },
179
+ {
180
+ "id": "R25",
181
+ "group": "Logging",
182
+ "rule": "No token, key or cookie value appears in any log line.",
183
+ "status": { "typescript": "enforced", "python": "pending", "go": "pending" },
184
+ "issue": "apsoai/apso-packages#75",
185
+ "note": "API keys have cases today. Tokens and cookies wait for the logging library."
186
+ },
187
+ {
188
+ "id": "R26",
189
+ "group": "Build time",
190
+ "rule": "A feature a language cannot enforce is refused by `apso generate` for that language.",
191
+ "status": { "typescript": "na", "python": "enforced", "go": "enforced" },
192
+ "note": "TypeScript enforces every feature, so it has nothing to refuse."
193
+ },
194
+ {
195
+ "id": "R27",
196
+ "group": "Build time",
197
+ "rule": "A schema that cannot be enforced fails at generate: MCP or permissions without sign-in, an unprotected grants entity. A tenant scope whose provider maps no tenant claim does not fail: generate warns, and at run time a token with no tenant gets the \"no tenant\" 403 on tenant-scoped entities, in every language.",
198
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
199
+ },
200
+ {
201
+ "id": "R28",
202
+ "group": "Service callers",
203
+ "rule": "The auth entities answer a service caller only. With the `better-auth` provider these are the session, user and membership entities named in the `auth` block, plus Better Auth's other tables. A signed-in user is refused on every one of their routes, no other entity's route loads them through a join or an embed, and `apso generate` refuses `mcp` on them.",
204
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
205
+ }
206
+ ]
207
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Run the access rule cases on a project: start its service locally the way
3
+ * `apso test smoke` does, point its token check at a local issuer, and report
4
+ * rule by rule. Nothing is regenerated: the service's own AUTH_JWT_ISSUER and
5
+ * AUTH_JWKS_URI settings are what make the test tokens acceptable.
6
+ */
7
+ import { AuthConfig } from "../types/auth";
8
+ import { Entity } from "../types/entity";
9
+ import { TargetLanguage } from "../types/generator";
10
+ import { RelationshipMap } from "../types/relationship";
11
+ import { Step } from "../verify";
12
+ import { McpClient } from "./cases";
13
+ import { CaseResult } from "./report";
14
+ /** An MCP client for the cases, over the service's /mcp endpoint. */
15
+ export declare function connectMcp(base: string, headers: Record<string, string>): Promise<McpClient>;
16
+ export interface AccessLine {
17
+ id: string;
18
+ rule: string;
19
+ /** pass, FAIL, or why the rule has no result here. */
20
+ result: string;
21
+ cases: number;
22
+ detail: string;
23
+ }
24
+ export interface AccessResult {
25
+ ok: boolean;
26
+ /** Build and start steps; a failure here means no case ran. */
27
+ steps: Step[];
28
+ lines: AccessLine[];
29
+ failures: CaseResult[];
30
+ notes: string[];
31
+ }
32
+ export interface AccessOptions {
33
+ skipBuild?: boolean;
34
+ language?: TargetLanguage;
35
+ auth?: AuthConfig;
36
+ log?: (line: string) => void;
37
+ }
38
+ export declare function accessTest(projectDir: string, entities: Entity[], relationships: RelationshipMap, { skipBuild, language, auth, log }?: AccessOptions): Promise<AccessResult>;
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ /**
3
+ * Run the access rule cases on a project: start its service locally the way
4
+ * `apso test smoke` does, point its token check at a local issuer, and report
5
+ * rule by rule. Nothing is regenerated: the service's own AUTH_JWT_ISSUER and
6
+ * AUTH_JWKS_URI settings are what make the test tokens acceptable.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.accessTest = exports.connectMcp = void 0;
10
+ // eslint-disable-next-line node/no-missing-import
11
+ const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
12
+ // eslint-disable-next-line node/no-missing-import
13
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
14
+ const auth_1 = require("../types/auth");
15
+ const verify_1 = require("../verify");
16
+ const cases_1 = require("./cases");
17
+ const report_1 = require("./report");
18
+ const tokens_1 = require("./tokens");
19
+ /** An MCP client for the cases, over the service's /mcp endpoint. */
20
+ async function connectMcp(base, headers) {
21
+ const client = new index_js_1.Client({ name: "apso-access", version: "1" });
22
+ await client.connect(new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(`${base}/mcp`), { requestInit: { headers } }));
23
+ return {
24
+ listTools: async () => {
25
+ const { tools } = await client.listTools();
26
+ return tools.map((tool) => tool.name);
27
+ },
28
+ callTool: async (name, args) => {
29
+ var _a, _b, _c;
30
+ const result = await client.callTool({ name, arguments: args });
31
+ const text = (_c = (_b = (_a = result.content) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.text) !== null && _c !== void 0 ? _c : "";
32
+ if (result.isError)
33
+ return { error: text || "refused" };
34
+ try {
35
+ return { json: JSON.parse(text) };
36
+ }
37
+ catch {
38
+ return { json: undefined };
39
+ }
40
+ },
41
+ };
42
+ }
43
+ exports.connectMcp = connectMcp;
44
+ const BUILD_TIME = new Set(["R26", "R27"]);
45
+ async function accessTest(projectDir, entities, relationships, { skipBuild = false, language = "typescript", auth, log } = {}) {
46
+ var _a, _b, _c;
47
+ const lang = language;
48
+ const report = (0, report_1.createReport)(lang, log !== null && log !== void 0 ? log : (() => null));
49
+ const notes = [];
50
+ let issuer;
51
+ // Every provider is a JWT provider. AUTH_JWT_ISSUER and AUTH_JWKS_URI point
52
+ // the first listed one at the local issuer, so test users sign in through it.
53
+ const providers = (0, auth_1.authProviders)(auth);
54
+ if (providers.length > 0)
55
+ issuer = await (0, tokens_1.startIssuer)((0, auth_1.resolveJwtAuth)(providers[0]));
56
+ else
57
+ notes.push("This project has no auth block, so there are no user callers. Only the rules for API keys ran.");
58
+ if (providers.length > 1)
59
+ notes.push(`auth lists ${providers.length} providers. Test users sign in through the first ("${providers[0].provider}").`);
60
+ const model = (0, cases_1.buildModel)(entities, relationships, lang, (_a = providers.find((p) => p.permissionEntity)) !== null && _a !== void 0 ? _a : providers[0]);
61
+ const key = { "x-api-key": verify_1.SMOKE_KEY };
62
+ let result;
63
+ try {
64
+ result = await (0, verify_1.smokeTest)(projectDir, entities, relationships, {
65
+ skipBuild,
66
+ language,
67
+ env: issuer === null || issuer === void 0 ? void 0 : issuer.env,
68
+ check: async (base) => {
69
+ await (0, cases_1.runAccessCases)({
70
+ base,
71
+ model,
72
+ t: report.checker(language),
73
+ key,
74
+ user: issuer === null || issuer === void 0 ? void 0 : issuer.user,
75
+ roles: issuer === null || issuer === void 0 ? void 0 : issuer.roles,
76
+ badTokens: issuer === null || issuer === void 0 ? void 0 : issuer.badTokens(),
77
+ mcp: (headers) => connectMcp(base, headers),
78
+ log,
79
+ warn: (line) => notes.push(`Warning (not a rule failure): ${line}`),
80
+ });
81
+ },
82
+ });
83
+ }
84
+ finally {
85
+ issuer === null || issuer === void 0 ? void 0 : issuer.close();
86
+ }
87
+ const ran = ((_b = result.steps[0]) === null || _b === void 0 ? void 0 : _b.name) !== "skipped" && result.steps.every((s) => s.ok);
88
+ if (!ran)
89
+ return { ok: result.ok && ((_c = result.steps[0]) === null || _c === void 0 ? void 0 : _c.name) === "skipped", steps: result.steps, lines: [], failures: [], notes };
90
+ const lines = report.rows().map((row) => {
91
+ const rule = report_1.RULES.find((r) => r.id === row.id);
92
+ const cases = row.passed + row.failed;
93
+ let [outcome, detail] = [row.result, ""];
94
+ if (cases === 0) {
95
+ if (rule.platform)
96
+ [outcome, detail] = ["n/a", `Platform only. ${rule.platform}`];
97
+ else if (row.status === "pending")
98
+ [outcome, detail] = ["pending", `Not built yet (${rule.issue}).`];
99
+ else if (row.status === "refused")
100
+ [outcome, detail] = ["n/a", `apso generate refuses this feature for ${language}.`];
101
+ else if (BUILD_TIME.has(row.id) || row.status === "na")
102
+ [outcome, detail] = ["n/a", "Checked by apso generate, not at run time."];
103
+ else
104
+ [outcome, detail] = ["not run", "Nothing in this schema calls for it, or it needs user sign-in."];
105
+ }
106
+ return { id: row.id, rule: row.rule, result: outcome, cases, detail };
107
+ });
108
+ const failures = report.results.filter((c) => !c.pass);
109
+ return { ok: failures.length === 0, steps: result.steps, lines, failures, notes };
110
+ }
111
+ exports.accessTest = accessTest;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A local token issuer for the access suite: it signs user tokens with the
3
+ * claim names of the project's own `auth` block and serves the public key as
4
+ * a JWKS, so a service started with AUTH_JWT_ISSUER and AUTH_JWKS_URI pointed
5
+ * here checks them the way it checks its real issuer's tokens.
6
+ */
7
+ /// <reference types="node" />
8
+ import * as crypto from "crypto";
9
+ import { ResolvedJwtAuth } from "../types/auth";
10
+ type Headers = Record<string, string>;
11
+ /**
12
+ * Sign a JWT. `alg` picks the signature; an unknown one (e.g. "none") leaves it empty.
13
+ * @param {object} payload - The claims; undefined values are dropped
14
+ * @param {string} alg - The JWS algorithm
15
+ * @param {crypto.KeyObject | string} key - The private key, or the secret for HS256
16
+ * @param {string} kid - The key id in the header
17
+ * @returns {string} The token
18
+ */
19
+ export declare function sign(payload: Record<string, unknown>, alg: string, key: crypto.KeyObject | string, kid?: string): string;
20
+ /** Auth0 namespaced claims are URLs with dots in them; any other dotted name is a path. */
21
+ export declare function setClaim(payload: Record<string, any>, path: string | undefined, value: unknown): void;
22
+ export interface Caller {
23
+ /** The tenant claim; leave out for a token with no tenant. */
24
+ tenant?: string;
25
+ roles?: string[];
26
+ }
27
+ export interface Issuer {
28
+ /** Environment that points the service's token check at this issuer. */
29
+ env: Record<string, string>;
30
+ /** True when the auth block names a roles claim, so a token can carry roles. */
31
+ roles: boolean;
32
+ user(caller?: Caller): Headers;
33
+ /** Tokens a service must refuse, each named for what is wrong with it. */
34
+ badTokens(): {
35
+ label: string;
36
+ headers: Headers;
37
+ }[];
38
+ close(): void;
39
+ }
40
+ /**
41
+ * Start the issuer on a free local port.
42
+ * @param {ResolvedJwtAuth} auth - The project's auth block, defaults filled in
43
+ * @returns {Promise<Issuer>} The running issuer
44
+ */
45
+ export declare function startIssuer(auth: ResolvedJwtAuth): Promise<Issuer>;
46
+ export {};