@apso/cli 0.48.0 → 0.49.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/README.md +28 -1
- package/dist/commands/dev.d.ts +2 -0
- package/dist/commands/dev.js +20 -3
- package/dist/commands/generate.js +49 -13
- package/dist/commands/mcp/serve.js +24 -41
- package/dist/commands/schema/diff.js +3 -4
- package/dist/commands/schema/pull.js +13 -11
- package/dist/commands/schema/push.js +6 -5
- package/dist/commands/schema/validate.d.ts +10 -0
- package/dist/commands/schema/validate.js +54 -0
- package/dist/commands/test/access.d.ts +11 -0
- package/dist/commands/test/access.js +65 -0
- package/dist/lib/access/cases.d.ts +120 -0
- package/dist/lib/access/cases.js +1163 -0
- package/dist/lib/access/index.d.ts +4 -0
- package/dist/lib/access/index.js +7 -0
- package/dist/lib/access/report.d.ts +75 -0
- package/dist/lib/access/report.js +118 -0
- package/dist/lib/access/rules.json +207 -0
- package/dist/lib/access/run.d.ts +38 -0
- package/dist/lib/access/run.js +111 -0
- package/dist/lib/access/tokens.d.ts +46 -0
- package/dist/lib/access/tokens.js +139 -0
- package/dist/lib/api/services.d.ts +10 -7
- package/dist/lib/api/services.js +19 -32
- package/dist/lib/apsorc-parser.d.ts +1 -1
- package/dist/lib/apsorc-parser.js +2 -0
- package/dist/lib/deploy/server-push.js +3 -1
- package/dist/lib/generators/go.d.ts +13 -1
- package/dist/lib/generators/go.js +144 -33
- package/dist/lib/generators/python.d.ts +3 -3
- package/dist/lib/generators/python.js +48 -24
- package/dist/lib/generators/typescript.d.ts +3 -5
- package/dist/lib/generators/typescript.js +78 -64
- package/dist/lib/guards.d.ts +111 -13
- package/dist/lib/guards.js +287 -23
- package/dist/lib/templates/go/handlers/handler.eta +8 -8
- package/dist/lib/templates/go/handlers/scope.eta +3 -2
- package/dist/lib/templates/go/index-module.eta +8 -5
- package/dist/lib/templates/go/mcp.eta +307 -0
- package/dist/lib/templates/go/middleware/auth.eta +587 -166
- package/dist/lib/templates/go/middleware/permission.eta +174 -0
- package/dist/lib/templates/go/services/service.eta +37 -16
- package/dist/lib/templates/go/utils/query.eta +37 -2
- package/dist/lib/templates/guards/guards.module.eta +37 -29
- package/dist/lib/templates/guards/index.eta +4 -0
- package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
- package/dist/lib/templates/guards/key.guard.eta +280 -0
- package/dist/lib/templates/guards/permission.guard.eta +168 -0
- package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
- package/dist/lib/templates/guards/scope.guard.eta +189 -41
- package/dist/lib/templates/python/auth.eta +354 -95
- package/dist/lib/templates/python/index-module.eta +7 -7
- package/dist/lib/templates/python/mcp.eta +284 -0
- package/dist/lib/templates/python/models/model.eta +6 -5
- package/dist/lib/templates/python/permissions.eta +121 -0
- package/dist/lib/templates/python/routers/router.eta +39 -1
- package/dist/lib/templates/python/schemas/schema.eta +18 -5
- package/dist/lib/templates/python/services/service.eta +38 -15
- package/dist/lib/templates/python/utils/query.eta +52 -25
- package/dist/lib/templates/rest/controller-rest.eta +43 -23
- package/dist/lib/templates/rest/index-module-rest.eta +0 -4
- package/dist/lib/templates/rest/service-rest.eta +3 -44
- package/dist/lib/types/auth.d.ts +84 -80
- package/dist/lib/types/auth.js +77 -60
- package/dist/lib/types/entity.d.ts +17 -9
- package/dist/lib/types/entity.js +3 -0
- package/dist/lib/types/index.d.ts +2 -2
- package/dist/lib/types/index.js +6 -5
- package/dist/lib/utils/crud-deps.d.ts +77 -6
- package/dist/lib/utils/crud-deps.js +197 -14
- package/dist/lib/utils/schema-convert.d.ts +20 -43
- package/dist/lib/utils/schema-convert.js +28 -78
- package/dist/lib/utils/template.d.ts +11 -0
- package/dist/lib/utils/template.js +36 -1
- package/dist/lib/verify/index.d.ts +6 -1
- package/dist/lib/verify/index.js +30 -13
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +36 -1
- package/package.json +1 -1
- package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
- package/dist/lib/templates/guards/auth.guard.eta +0 -233
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* A local token issuer for the access suite: it signs user tokens with the
|
|
4
|
+
* claim names of the project's own `auth` block and serves the public key as
|
|
5
|
+
* a JWKS, so a service started with AUTH_JWT_ISSUER and AUTH_JWKS_URI pointed
|
|
6
|
+
* here checks them the way it checks its real issuer's tokens.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.startIssuer = exports.setClaim = exports.sign = void 0;
|
|
10
|
+
const tslib_1 = require("tslib");
|
|
11
|
+
const crypto = tslib_1.__importStar(require("crypto"));
|
|
12
|
+
const http = tslib_1.__importStar(require("http"));
|
|
13
|
+
const bearer = (token) => ({ authorization: `Bearer ${token}` });
|
|
14
|
+
const bad = (label, token) => ({ label, headers: bearer(token) });
|
|
15
|
+
const b64url = (v) => Buffer.from(typeof v === "string" ? v : JSON.stringify(v)).toString("base64url");
|
|
16
|
+
const generate = (alg) => {
|
|
17
|
+
if (alg === "EdDSA")
|
|
18
|
+
return crypto.generateKeyPairSync("ed25519");
|
|
19
|
+
if (alg.startsWith("ES"))
|
|
20
|
+
return crypto.generateKeyPairSync("ec", { namedCurve: alg === "ES384" ? "P-384" : "P-256" });
|
|
21
|
+
return crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Sign a JWT. `alg` picks the signature; an unknown one (e.g. "none") leaves it empty.
|
|
25
|
+
* @param {object} payload - The claims; undefined values are dropped
|
|
26
|
+
* @param {string} alg - The JWS algorithm
|
|
27
|
+
* @param {crypto.KeyObject | string} key - The private key, or the secret for HS256
|
|
28
|
+
* @param {string} kid - The key id in the header
|
|
29
|
+
* @returns {string} The token
|
|
30
|
+
*/
|
|
31
|
+
function sign(payload, alg, key, kid = "apso-test") {
|
|
32
|
+
const now = Math.floor(Date.now() / 1000);
|
|
33
|
+
const body = { iat: now, exp: now + 600, ...payload };
|
|
34
|
+
for (const k of Object.keys(body))
|
|
35
|
+
if (body[k] === undefined)
|
|
36
|
+
delete body[k];
|
|
37
|
+
const head = `${b64url({ alg, typ: "JWT", kid })}.${b64url(body)}`;
|
|
38
|
+
const data = Buffer.from(head);
|
|
39
|
+
const hash = `sha${alg.slice(2)}`;
|
|
40
|
+
let sig = "";
|
|
41
|
+
if (alg === "HS256")
|
|
42
|
+
sig = crypto.createHmac("sha256", key).update(head).digest("base64url");
|
|
43
|
+
else if (alg === "EdDSA")
|
|
44
|
+
sig = crypto.sign(null, data, key).toString("base64url");
|
|
45
|
+
else if (alg.startsWith("RS"))
|
|
46
|
+
sig = crypto.sign(hash, data, key).toString("base64url");
|
|
47
|
+
else if (alg.startsWith("PS"))
|
|
48
|
+
sig = crypto
|
|
49
|
+
.sign(hash, data, {
|
|
50
|
+
key: key,
|
|
51
|
+
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
|
|
52
|
+
saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST,
|
|
53
|
+
})
|
|
54
|
+
.toString("base64url");
|
|
55
|
+
else if (alg.startsWith("ES"))
|
|
56
|
+
sig = crypto.sign(hash, data, { key: key, dsaEncoding: "ieee-p1363" }).toString("base64url");
|
|
57
|
+
return `${head}.${sig}`;
|
|
58
|
+
}
|
|
59
|
+
exports.sign = sign;
|
|
60
|
+
/** Auth0 namespaced claims are URLs with dots in them; any other dotted name is a path. */
|
|
61
|
+
function setClaim(payload, path, value) {
|
|
62
|
+
if (!path || value === undefined)
|
|
63
|
+
return;
|
|
64
|
+
if (!path.includes(".") || path.includes("://")) {
|
|
65
|
+
payload[path] = value;
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const parts = path.split(".");
|
|
69
|
+
let at = payload;
|
|
70
|
+
for (const part of parts.slice(0, -1)) {
|
|
71
|
+
at[part] = typeof at[part] === "object" && at[part] !== null ? at[part] : {};
|
|
72
|
+
at = at[part];
|
|
73
|
+
}
|
|
74
|
+
at[parts[parts.length - 1]] = value;
|
|
75
|
+
}
|
|
76
|
+
exports.setClaim = setClaim;
|
|
77
|
+
/**
|
|
78
|
+
* Start the issuer on a free local port.
|
|
79
|
+
* @param {ResolvedJwtAuth} auth - The project's auth block, defaults filled in
|
|
80
|
+
* @returns {Promise<Issuer>} The running issuer
|
|
81
|
+
*/
|
|
82
|
+
async function startIssuer(auth) {
|
|
83
|
+
var _a;
|
|
84
|
+
const alg = auth.algorithms[0];
|
|
85
|
+
const keys = generate(alg);
|
|
86
|
+
const impostor = generate(alg);
|
|
87
|
+
const jwks = { keys: [{ ...keys.publicKey.export({ format: "jwk" }), kid: "apso-test", alg, use: "sig" }] };
|
|
88
|
+
const server = http.createServer((_req, res) => {
|
|
89
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
90
|
+
res.end(JSON.stringify(jwks));
|
|
91
|
+
});
|
|
92
|
+
await new Promise((resolve) => {
|
|
93
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
94
|
+
});
|
|
95
|
+
const { port } = server.address();
|
|
96
|
+
const issuer = `http://127.0.0.1:${port}/`;
|
|
97
|
+
// A Better Auth service with no audience set expects the origin of its issuer as the audience.
|
|
98
|
+
const audience = (_a = auth.audience) !== null && _a !== void 0 ? _a : (auth.provider === "better-auth" ? new URL(issuer).origin : undefined);
|
|
99
|
+
const claims = ({ tenant, roles } = {}) => {
|
|
100
|
+
var _a;
|
|
101
|
+
const payload = {
|
|
102
|
+
iss: issuer,
|
|
103
|
+
aud: audience,
|
|
104
|
+
azp: auth.authorizedParties[0],
|
|
105
|
+
// Cognito access tokens carry client_id where others carry aud.
|
|
106
|
+
// eslint-disable-next-line camelcase
|
|
107
|
+
...(auth.provider === "cognito" ? { client_id: auth.audience, token_use: "access" } : {}),
|
|
108
|
+
};
|
|
109
|
+
setClaim(payload, auth.claims.userId, `apso-test-user-${tenant !== null && tenant !== void 0 ? tenant : "none"}`);
|
|
110
|
+
setClaim(payload, auth.claims.email, "access-test@example.com");
|
|
111
|
+
setClaim(payload, (_a = auth.claims.workspaceId) !== null && _a !== void 0 ? _a : auth.claims.organizationId, tenant);
|
|
112
|
+
// Clerk's role claim (o.rol) is one role, not a list.
|
|
113
|
+
if (roles && roles.length > 0)
|
|
114
|
+
setClaim(payload, auth.claims.roles, auth.provider === "clerk" ? roles[0] : roles);
|
|
115
|
+
return payload;
|
|
116
|
+
};
|
|
117
|
+
const valid = claims({ tenant: "1" });
|
|
118
|
+
return {
|
|
119
|
+
env: { AUTH_JWT_ISSUER: issuer, AUTH_JWKS_URI: `${issuer}jwks.json` },
|
|
120
|
+
roles: Boolean(auth.claims.roles),
|
|
121
|
+
user: (caller) => bearer(sign(claims(caller), alg, keys.privateKey)),
|
|
122
|
+
badTokens: () => [
|
|
123
|
+
bad("a token that is not a JWT", "not.a.jwt"),
|
|
124
|
+
bad("an expired token", sign({ ...valid, exp: Math.floor(Date.now() / 1000) - 60 }, alg, keys.privateKey)),
|
|
125
|
+
bad("a token from another issuer", sign({ ...valid, iss: "https://evil.example/" }, alg, keys.privateKey)),
|
|
126
|
+
...(audience
|
|
127
|
+
? // eslint-disable-next-line camelcase
|
|
128
|
+
[bad("a token for another audience", sign({ ...valid, aud: "https://other.example", client_id: "other" }, alg, keys.privateKey))]
|
|
129
|
+
: []),
|
|
130
|
+
bad("a token signed by another key", sign(valid, alg, impostor.privateKey)),
|
|
131
|
+
bad('a token with alg "none"', sign(valid, "none", "")),
|
|
132
|
+
bad("an HS256 token signed with the public key", sign(valid, "HS256", keys.publicKey.export({ type: "spki", format: "pem" }))),
|
|
133
|
+
],
|
|
134
|
+
close: () => {
|
|
135
|
+
server.close();
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
exports.startIssuer = startIssuer;
|
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
* backend's snake_case / nestjsx-crud shapes and are adapted to the CLI types
|
|
11
11
|
* below.
|
|
12
12
|
*/
|
|
13
|
-
import { UserProfile, Workspace, Service,
|
|
13
|
+
import { UserProfile, Workspace, Service, GitHubRepo, GitHubConnection, BuildStatus, PaginatedResponse, TokenExchangeResponse } from "./types";
|
|
14
|
+
import type { ApsorcType } from "../apsorc-parser";
|
|
14
15
|
type Raw = Record<string, any>;
|
|
15
16
|
/**
|
|
16
17
|
* Authentication API
|
|
@@ -61,18 +62,20 @@ export declare const servicesApi: {
|
|
|
61
62
|
delete(_workspaceSlug: string, serviceSlugOrId: string): Promise<void>;
|
|
62
63
|
};
|
|
63
64
|
/**
|
|
64
|
-
* Schema API
|
|
65
|
-
*
|
|
65
|
+
* Schema API. The schema lives on the service as its `apsorc` field: the
|
|
66
|
+
* .apsorc itself, whole, which is also what the web editor saves. Versioned
|
|
67
|
+
* rows exist under /api/ServiceSchemas.
|
|
66
68
|
*/
|
|
67
69
|
export declare const schemaApi: {
|
|
68
|
-
|
|
69
|
-
get(_workspaceSlug: string, serviceSlug: string): Promise<
|
|
70
|
-
update(_workspaceSlug: string, serviceSlugOrId: string,
|
|
70
|
+
/** The service's .apsorc, or null when the platform has none yet. */
|
|
71
|
+
get(_workspaceSlug: string, serviceSlug: string): Promise<ApsorcType | null>;
|
|
72
|
+
update(_workspaceSlug: string, serviceSlugOrId: string, apsorc: ApsorcType): Promise<ApsorcType | null>;
|
|
71
73
|
validate(_workspaceSlug?: string, _serviceSlug?: string, _schema?: unknown): Promise<{
|
|
72
74
|
valid: boolean;
|
|
73
75
|
errors: string[];
|
|
74
76
|
}>;
|
|
75
|
-
|
|
77
|
+
/** What pushing the local .apsorc would change on the platform. */
|
|
78
|
+
diff(workspaceSlug: string, serviceSlug: string, local: ApsorcType): Promise<{
|
|
76
79
|
hasChanges: boolean;
|
|
77
80
|
added: string[];
|
|
78
81
|
removed: string[];
|
package/dist/lib/api/services.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.codeApi = exports.githubApi = exports.envApi = exports.SERVICE_ENVS = exports.toBuildStatus = exports.buildApi = exports.schemaApi = exports.servicesApi = exports.workspacesApi = exports.authApi = void 0;
|
|
16
16
|
const client_1 = require("./client");
|
|
17
|
+
const schema_convert_1 = require("../utils/schema-convert");
|
|
17
18
|
function adaptWorkspace(raw) {
|
|
18
19
|
var _a, _b, _c, _d;
|
|
19
20
|
// /api/workspaces returns workspace_user rows with a nested `workspace`;
|
|
@@ -181,55 +182,41 @@ async function resolveServiceId(serviceSlugOrId) {
|
|
|
181
182
|
return svc.id;
|
|
182
183
|
}
|
|
183
184
|
/**
|
|
184
|
-
* Schema API
|
|
185
|
-
*
|
|
185
|
+
* Schema API. The schema lives on the service as its `apsorc` field: the
|
|
186
|
+
* .apsorc itself, whole, which is also what the web editor saves. Versioned
|
|
187
|
+
* rows exist under /api/ServiceSchemas.
|
|
186
188
|
*/
|
|
187
189
|
exports.schemaApi = {
|
|
188
|
-
|
|
189
|
-
const raw = await client_1.api.get(`/api/services/${serviceId}`);
|
|
190
|
-
return adaptSchemaFromService(raw);
|
|
191
|
-
},
|
|
190
|
+
/** The service's .apsorc, or null when the platform has none yet. */
|
|
192
191
|
async get(_workspaceSlug, serviceSlug) {
|
|
193
192
|
const id = await resolveServiceId(serviceSlug);
|
|
194
|
-
return
|
|
193
|
+
return apsorcFromService(await client_1.api.get(`/api/services/${id}`));
|
|
195
194
|
},
|
|
196
|
-
async update(_workspaceSlug, serviceSlugOrId,
|
|
195
|
+
async update(_workspaceSlug, serviceSlugOrId, apsorc) {
|
|
197
196
|
const id = await resolveServiceId(serviceSlugOrId);
|
|
198
|
-
|
|
199
|
-
const raw = await client_1.api.patch(`/api/services/${id}`, {
|
|
200
|
-
apsorc: JSON.stringify(schema),
|
|
201
|
-
});
|
|
202
|
-
return adaptSchemaFromService(raw);
|
|
197
|
+
return apsorcFromService(await client_1.api.patch(`/api/services/${id}`, { apsorc }));
|
|
203
198
|
},
|
|
204
|
-
// Validation
|
|
205
|
-
//
|
|
206
|
-
// for the
|
|
199
|
+
// Validation is computed locally by the CLI (the schema format is fully
|
|
200
|
+
// known client-side), so this does not call the BFF. The signature is kept
|
|
201
|
+
// for the caller; the arguments are intentionally unused here.
|
|
207
202
|
async validate(_workspaceSlug, _serviceSlug, _schema) {
|
|
208
203
|
return { valid: true, errors: [] };
|
|
209
204
|
},
|
|
210
|
-
|
|
211
|
-
|
|
205
|
+
/** What pushing the local .apsorc would change on the platform. */
|
|
206
|
+
async diff(workspaceSlug, serviceSlug, local) {
|
|
207
|
+
return (0, schema_convert_1.diffApsorc)(await this.get(workspaceSlug, serviceSlug), local);
|
|
212
208
|
},
|
|
213
209
|
};
|
|
214
|
-
function
|
|
215
|
-
var _a
|
|
216
|
-
let entities = [];
|
|
210
|
+
function apsorcFromService(raw) {
|
|
211
|
+
var _a;
|
|
217
212
|
const rc = raw.apsorc;
|
|
218
213
|
try {
|
|
219
|
-
|
|
220
|
-
|
|
214
|
+
// Old rows hold the .apsorc as a JSON string.
|
|
215
|
+
return (_a = (typeof rc === "string" ? JSON.parse(rc) : rc)) !== null && _a !== void 0 ? _a : null;
|
|
221
216
|
}
|
|
222
217
|
catch {
|
|
223
|
-
|
|
218
|
+
return null;
|
|
224
219
|
}
|
|
225
|
-
return {
|
|
226
|
-
id: String(raw.id),
|
|
227
|
-
serviceId: String(raw.id),
|
|
228
|
-
version: 1,
|
|
229
|
-
entities,
|
|
230
|
-
createdAt: (_b = raw.created_at) !== null && _b !== void 0 ? _b : raw.createdAt,
|
|
231
|
-
updatedAt: (_c = raw.updated_at) !== null && _c !== void 0 ? _c : raw.updatedAt,
|
|
232
|
-
};
|
|
233
220
|
}
|
|
234
221
|
/**
|
|
235
222
|
* Build / Deploy API
|
|
@@ -5,6 +5,7 @@ const tslib_1 = require("tslib");
|
|
|
5
5
|
const fs = tslib_1.__importStar(require("fs"));
|
|
6
6
|
const path = tslib_1.__importStar(require("path"));
|
|
7
7
|
const rc_1 = tslib_1.__importDefault(require("rc"));
|
|
8
|
+
const auth_1 = require("./types/auth");
|
|
8
9
|
const relationships_1 = require("./utils/relationships");
|
|
9
10
|
const perf_hooks_1 = require("perf_hooks");
|
|
10
11
|
// @apso/schema-tools is published on npm (apsoai/apso-packages).
|
|
@@ -130,6 +131,7 @@ const parseRc = () => {
|
|
|
130
131
|
const entities = apsoConfig.entities || [];
|
|
131
132
|
const relationships = apsoConfig.relationships || [];
|
|
132
133
|
const auth = apsoConfig.auth;
|
|
134
|
+
(0, auth_1.authProviders)(auth);
|
|
133
135
|
const language = apsoConfig.language;
|
|
134
136
|
const emitEvents = apsoConfig.emitEvents;
|
|
135
137
|
const http = apsoConfig.http;
|
|
@@ -31,7 +31,9 @@ function zipProject(cwd) {
|
|
|
31
31
|
const zip = new adm_zip_1.default();
|
|
32
32
|
zip.addLocalFolder(cwd, "", (filename) => {
|
|
33
33
|
const parts = filename.split(path.sep);
|
|
34
|
-
|
|
34
|
+
// .apso is local state, except the manifest the platform reads.
|
|
35
|
+
const kept = parts.join("/") === ".apso/manifest.json";
|
|
36
|
+
if (!kept && parts.some((p) => EXCLUDE_DIRS.has(p)))
|
|
35
37
|
return false;
|
|
36
38
|
const base = parts[parts.length - 1];
|
|
37
39
|
if (isSecretEnvFile(base))
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { BaseGenerator } from "./base";
|
|
2
2
|
import { TargetLanguage, GeneratedFile, ValidationResult, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, Entity, AuthConfig } from "../types";
|
|
3
|
+
import { RelationshipMap } from "../types";
|
|
3
4
|
/**
|
|
4
5
|
* Go/Gin generator that produces GORM models, DTOs, Gin handlers,
|
|
5
6
|
* and service layer code.
|
|
@@ -67,6 +68,17 @@ export declare class GoGenerator extends BaseGenerator {
|
|
|
67
68
|
* pascalCase; a relation's foreign key (organizationId) is OrganizationID.
|
|
68
69
|
*/
|
|
69
70
|
private goScope;
|
|
70
|
-
|
|
71
|
+
/**
|
|
72
|
+
* The foreign keys of an entity that a write must check: those onto
|
|
73
|
+
* tenant-scoped entities, with the Go field and column of each.
|
|
74
|
+
*/
|
|
75
|
+
private goReferences;
|
|
76
|
+
/**
|
|
77
|
+
* The MCP tools of every entity that opts in. Gin has no OpenAPI document at
|
|
78
|
+
* run time, so each tool's input schema is written from .apsorc here, from
|
|
79
|
+
* the same columns and foreign keys as the DTOs.
|
|
80
|
+
*/
|
|
81
|
+
private goMcpTools;
|
|
82
|
+
generateGuards(entities: Entity[], auth?: AuthConfig, relationshipMap?: RelationshipMap): Promise<GeneratedFile[]>;
|
|
71
83
|
generateQueryUtils(_entities: Entity[], _apiType: string): Promise<GeneratedFile[]>;
|
|
72
84
|
}
|
|
@@ -66,6 +66,22 @@ const gormTag = (settings) => settings
|
|
|
66
66
|
.join(";")
|
|
67
67
|
.replace(/\\/g, "\\\\")
|
|
68
68
|
.replace(/"/g, '\\"');
|
|
69
|
+
/** The JSON Schema of a Go DTO field type, for MCP tool input schemas. */
|
|
70
|
+
const jsonType = (goType) => {
|
|
71
|
+
if (goType === "string")
|
|
72
|
+
return { type: "string" };
|
|
73
|
+
if (goType === "time.Time")
|
|
74
|
+
return { type: "string", format: "date-time" };
|
|
75
|
+
if (goType === "bool")
|
|
76
|
+
return { type: "boolean" };
|
|
77
|
+
if (goType.startsWith("int") || goType.startsWith("uint"))
|
|
78
|
+
return { type: "integer" };
|
|
79
|
+
if (goType.startsWith("float"))
|
|
80
|
+
return { type: "number" };
|
|
81
|
+
if (goType.startsWith("[]") || goType.endsWith("Array"))
|
|
82
|
+
return { type: "array" };
|
|
83
|
+
return {};
|
|
84
|
+
};
|
|
69
85
|
/**
|
|
70
86
|
* Go/Gin generator that produces GORM models, DTOs, Gin handlers,
|
|
71
87
|
* and service layer code.
|
|
@@ -87,20 +103,21 @@ class GoGenerator extends base_1.BaseGenerator {
|
|
|
87
103
|
return ".go";
|
|
88
104
|
}
|
|
89
105
|
validateConfig(config) {
|
|
90
|
-
var _a;
|
|
106
|
+
var _a, _b;
|
|
91
107
|
const errors = [];
|
|
92
108
|
const warnings = [];
|
|
93
109
|
// Validate that entities are provided
|
|
94
110
|
if (!config.entities || config.entities.length === 0) {
|
|
95
111
|
errors.push("No entities defined in configuration");
|
|
96
112
|
}
|
|
113
|
+
errors.push(...(0, guards_1.removedScopeOptionErrors)((_a = config.entities) !== null && _a !== void 0 ? _a : []));
|
|
97
114
|
// Validate each entity
|
|
98
115
|
for (const entity of config.entities) {
|
|
99
116
|
if (!entity.name) {
|
|
100
117
|
errors.push("Entity missing required 'name' property");
|
|
101
118
|
}
|
|
102
119
|
// Validate field types
|
|
103
|
-
for (const field of (
|
|
120
|
+
for (const field of (_b = entity.fields) !== null && _b !== void 0 ? _b : []) {
|
|
104
121
|
if (!field.name) {
|
|
105
122
|
errors.push(`Entity '${entity.name}' has a field without a name`);
|
|
106
123
|
}
|
|
@@ -303,6 +320,8 @@ class GoGenerator extends base_1.BaseGenerator {
|
|
|
303
320
|
primaryKeySwaggerType: this.getPrimaryKeySwaggerType(primaryKeyType),
|
|
304
321
|
associations: [...new Set(relationshipsForTemplate)],
|
|
305
322
|
scope: (0, guards_1.entityScope)(entity, Boolean(options.auth)),
|
|
323
|
+
// A write that names a row the caller cannot read is answered like a scope error.
|
|
324
|
+
references: this.goReferences(entity, this.goAssociations(entity, relationships, options.allEntities), options.allEntities, options.auth).length > 0,
|
|
306
325
|
};
|
|
307
326
|
const content = await this.renderTemplate("./handlers/handler", data);
|
|
308
327
|
return [
|
|
@@ -328,8 +347,14 @@ class GoGenerator extends base_1.BaseGenerator {
|
|
|
328
347
|
createdAt,
|
|
329
348
|
updatedAt,
|
|
330
349
|
columns,
|
|
331
|
-
|
|
350
|
+
// Auth entities are for service callers only, so no other entity's
|
|
351
|
+
// response carries one.
|
|
352
|
+
associations: goRelationships.map((r) => ({
|
|
353
|
+
...r,
|
|
354
|
+
hidden: (0, guards_1.hidesRelation)(entityName, r.name, allEntities, options.auth),
|
|
355
|
+
})),
|
|
332
356
|
scope: this.goScope(entity, Boolean(options.auth)),
|
|
357
|
+
references: this.goReferences(entity, goRelationships, allEntities, options.auth),
|
|
333
358
|
};
|
|
334
359
|
const content = await this.renderTemplate("./services/service", data);
|
|
335
360
|
return [
|
|
@@ -455,7 +480,7 @@ ${downStatements}
|
|
|
455
480
|
});
|
|
456
481
|
const content = await this.renderTemplate("./index-module", {
|
|
457
482
|
entities: entitiesData,
|
|
458
|
-
|
|
483
|
+
permissions: (0, guards_1.hasPermissions)(entities),
|
|
459
484
|
});
|
|
460
485
|
const modelRefs = entities
|
|
461
486
|
.map((e) => `\t\t&${(0, casing_1.pascalCase)(e.name)}{},`)
|
|
@@ -574,39 +599,125 @@ ${modelRefs}
|
|
|
574
599
|
})),
|
|
575
600
|
};
|
|
576
601
|
}
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
602
|
+
/**
|
|
603
|
+
* The foreign keys of an entity that a write must check: those onto
|
|
604
|
+
* tenant-scoped entities, with the Go field and column of each.
|
|
605
|
+
*/
|
|
606
|
+
goReferences(entity, associations, allEntities, auth) {
|
|
607
|
+
const owned = associations.filter((a) => a.owns);
|
|
608
|
+
const scoped = (0, guards_1.scopedReferences)(entity, owned.map((a) => [`${a.camelReferenceName}Id`, a.name]), (0, guards_1.relationScopes)(allEntities, this.config.relationshipMap, Boolean(auth)));
|
|
609
|
+
return owned
|
|
610
|
+
.filter((a) => scoped[`${a.camelReferenceName}Id`])
|
|
611
|
+
.map((a) => ({ target: a.name, goField: a.fkField, column: a.fkColumn }));
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* The MCP tools of every entity that opts in. Gin has no OpenAPI document at
|
|
615
|
+
* run time, so each tool's input schema is written from .apsorc here, from
|
|
616
|
+
* the same columns and foreign keys as the DTOs.
|
|
617
|
+
*/
|
|
618
|
+
goMcpTools(entities, auth, relationshipMap) {
|
|
619
|
+
return entities.flatMap((entity) => {
|
|
620
|
+
var _a, _b;
|
|
621
|
+
const { mcp, mcpName, mcpPluralName } = (0, guards_1.mcpToolNames)(entity, auth);
|
|
622
|
+
if (mcp.length === 0)
|
|
623
|
+
return [];
|
|
624
|
+
const scoped = new Set((_a = (0, guards_1.entityScope)(entity, true)) === null || _a === void 0 ? void 0 : _a.fields.map((f) => f.field));
|
|
625
|
+
const properties = {};
|
|
626
|
+
const required = [];
|
|
627
|
+
for (const c of this.getGoFieldsForTemplate((_b = entity.fields) !== null && _b !== void 0 ? _b : [], entity)) {
|
|
628
|
+
properties[c.name] =
|
|
629
|
+
c.type === "enum" && Array.isArray(c.values)
|
|
630
|
+
? { type: "string", enum: c.values }
|
|
631
|
+
: jsonType(c.goType);
|
|
632
|
+
if (c.mustSend)
|
|
633
|
+
required.push(c.name);
|
|
634
|
+
}
|
|
635
|
+
for (const a of this.goAssociations(entity, relationshipMap[entity.name] || [], entities)) {
|
|
636
|
+
if (!a.owns)
|
|
637
|
+
continue;
|
|
638
|
+
const name = `${a.camelReferenceName}Id`;
|
|
639
|
+
properties[name] = jsonType(a.fkGoType.replace(/^\*/, ""));
|
|
640
|
+
if (!a.fkNullable && !scoped.has(name))
|
|
641
|
+
required.push(name);
|
|
642
|
+
}
|
|
643
|
+
const id = { type: entity.primaryKeyType === "uuid" ? "string" : "integer" };
|
|
644
|
+
const schema = (props, req) => JSON.stringify({ type: "object", properties: props, required: req });
|
|
645
|
+
const body = (req) => ({ type: "object", properties, required: req });
|
|
646
|
+
const plural = (0, pluralize_1.default)(entity.name);
|
|
647
|
+
const path = `/${(0, casing_1.kebabCase)(plural)}`;
|
|
648
|
+
const one = `${path}/:id`;
|
|
649
|
+
const tool = (op, name, method, toolPath, description, toolSchema) => mcp.includes(op)
|
|
650
|
+
? [{ name, method, path: toolPath, description, schema: toolSchema, list: !toolSchema }]
|
|
651
|
+
: [];
|
|
652
|
+
return [
|
|
653
|
+
...tool("read", `list_${mcpPluralName}`, "GET", path, `List ${plural}. Supports filter, sort, join, limit and page.`),
|
|
654
|
+
...tool("read", `get_${mcpName}`, "GET", one, `Get one ${entity.name} by id.`, schema({ id }, ["id"])),
|
|
655
|
+
...tool("create", `create_${mcpName}`, "POST", path, `Create a ${entity.name}.`, schema({ body: body(required) }, ["body"])),
|
|
656
|
+
...tool("update", `update_${mcpName}`, "PATCH", one, `Update fields of one ${entity.name} by id.`, schema({ id, body: body([]) }, ["id", "body"])),
|
|
657
|
+
...tool("delete", `delete_${mcpName}`, "DELETE", one, `Delete one ${entity.name} by id. This cannot be undone.`, schema({ id }, ["id"])),
|
|
658
|
+
];
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
async generateGuards(entities, auth, relationshipMap) {
|
|
662
|
+
var _a, _b;
|
|
663
|
+
if (relationshipMap === void 0) { relationshipMap = (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {}; }
|
|
664
|
+
const tools = this.goMcpTools(entities, auth, relationshipMap !== null && relationshipMap !== void 0 ? relationshipMap : {});
|
|
665
|
+
// Fails on a grants entity that would be an escalation path.
|
|
666
|
+
const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
|
|
667
|
+
if (permissions && !auth)
|
|
668
|
+
throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
|
|
669
|
+
const nested = auth ? (0, guards_1.nestedScopeEntities)(entities) : [];
|
|
581
670
|
if (nested.length > 0)
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
...apiKey,
|
|
595
|
-
goModel: (0, casing_1.pascalCase)(entity.name),
|
|
596
|
-
keyColumn: column(apiKey.keyField),
|
|
597
|
-
expiresColumn: column("expiresAt"),
|
|
598
|
-
workspaceColumn: column(apiKey.workspaceField),
|
|
599
|
-
roleColumn: apiKey.roleField ? column(apiKey.roleField) : undefined,
|
|
600
|
-
},
|
|
601
|
-
};
|
|
602
|
-
}
|
|
603
|
-
else {
|
|
604
|
-
throw new Error(`auth.provider "${auth.provider}" is generated for TypeScript services only. For Go, use "jwt" (Better Auth issues JWTs with its JWT plugin) or "api-key".`);
|
|
605
|
-
}
|
|
671
|
+
throw new Error(`${nested.join(", ")}: a scopeBy path through a parent (for example "project.organizationId") is enforced in TypeScript services only for now. In Go, put the tenant field on the entity and scope by it, or generate with --language typescript.`);
|
|
672
|
+
// The API key check is part of every service; auth adds user sign-in.
|
|
673
|
+
// One entry per trusted issuer; undefined when there is no sign-in.
|
|
674
|
+
const jwt = (0, types_1.resolveJwtProviders)(auth);
|
|
675
|
+
const data = {
|
|
676
|
+
jwt: jwt.length > 0 ? jwt : undefined,
|
|
677
|
+
mcp: tools.length > 0,
|
|
678
|
+
// Routes only a service caller reaches (sessions, accounts, ...).
|
|
679
|
+
authRoutes: (0, guards_1.authEntityNames)(entities, auth).map((name) => (0, casing_1.kebabCase)((0, pluralize_1.default)(name))),
|
|
680
|
+
relationScopes: (_b = (0, guards_1.relationScopes)(entities, relationshipMap, Boolean(auth))) !== null && _b !== void 0 ? _b : {},
|
|
681
|
+
tables: Object.fromEntries(entities.map((e) => [e.name, (0, ddl_1.tableName)(e)])),
|
|
682
|
+
};
|
|
606
683
|
const content = await this.renderTemplate("./middleware/auth", data);
|
|
607
684
|
const files = [{ path: "middleware/auth.go", content }];
|
|
685
|
+
if (permissions) {
|
|
686
|
+
// Go routes are kebab-case (/role-permissions); the rules are the same.
|
|
687
|
+
const rulesOf = (name) => { var _a; return (_a = permissions.routes[(0, pluralize_1.default)(name).toLowerCase()]) !== null && _a !== void 0 ? _a : {}; };
|
|
688
|
+
const grants = permissions.grants && {
|
|
689
|
+
...permissions.grants,
|
|
690
|
+
table: (0, ddl_1.tableName)(entities.find((e) => e.name === permissions.grants.entity)),
|
|
691
|
+
};
|
|
692
|
+
files.push({
|
|
693
|
+
path: "middleware/permission.go",
|
|
694
|
+
content: await this.renderTemplate("./middleware/permission", {
|
|
695
|
+
routes: entities
|
|
696
|
+
.filter((e) => e.permissions)
|
|
697
|
+
.map((e) => ({
|
|
698
|
+
path: (0, casing_1.kebabCase)((0, pluralize_1.default)(e.name)),
|
|
699
|
+
rules: Object.entries(rulesOf(e.name)).map(([op, rule]) => ({ op, ...rule })),
|
|
700
|
+
})),
|
|
701
|
+
joins: Object.entries(permissions.joins).map(([name, rules]) => ({ name, rules })),
|
|
702
|
+
grants,
|
|
703
|
+
}),
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
// The /mcp endpoint; cmd/main.go mounts it (see ensureGoMcpWiring).
|
|
707
|
+
if (tools.length > 0)
|
|
708
|
+
files.push({
|
|
709
|
+
path: "routes/mcp.go",
|
|
710
|
+
content: await this.renderTemplate("./mcp", {
|
|
711
|
+
tools,
|
|
712
|
+
// The same variables auth.go reads: AUTH_JWT_ISSUER, then _2 and so on.
|
|
713
|
+
issuers: jwt.map((p, i) => ({
|
|
714
|
+
env: `AUTH_JWT_ISSUER${i === 0 ? "" : `_${i + 1}`}`,
|
|
715
|
+
issuer: p.issuer,
|
|
716
|
+
})),
|
|
717
|
+
}),
|
|
718
|
+
});
|
|
608
719
|
// Shared helpers for services and handlers of entities with a direct scopeBy.
|
|
609
|
-
if (entities.some((e) => (0, guards_1.entityScope)(e, true))) {
|
|
720
|
+
if (auth && entities.some((e) => (0, guards_1.entityScope)(e, true))) {
|
|
610
721
|
files.push({
|
|
611
722
|
path: "services/scope.go",
|
|
612
723
|
content: await this.renderTemplate("./services/scope", {}),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BaseGenerator } from "./base";
|
|
2
|
-
import { TargetLanguage, GeneratedFile, ValidationResult, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, Entity, AuthConfig } from "../types";
|
|
2
|
+
import { TargetLanguage, GeneratedFile, ValidationResult, GeneratorConfig, EntityGenerationOptions, ControllerGenerationOptions, ServiceGenerationOptions, DtoGenerationOptions, MigrationGenerationOptions, Entity, AuthConfig, RelationshipMap } from "../types";
|
|
3
3
|
/**
|
|
4
4
|
* Python/FastAPI generator that produces SQLAlchemy models, Pydantic schemas,
|
|
5
5
|
* and FastAPI routers.
|
|
@@ -16,7 +16,7 @@ export declare class PythonGenerator extends BaseGenerator {
|
|
|
16
16
|
generateModule(_options: EntityGenerationOptions): Promise<GeneratedFile[]>;
|
|
17
17
|
generateMigration(options: MigrationGenerationOptions): Promise<GeneratedFile[]>;
|
|
18
18
|
generateEnums(entities: Entity[], _apiType: string): Promise<GeneratedFile[]>;
|
|
19
|
-
generateIndexModule(entities: Entity[], _apiType: string,
|
|
19
|
+
generateIndexModule(entities: Entity[], _apiType: string, _opts?: {
|
|
20
20
|
auth?: AuthConfig;
|
|
21
21
|
}): Promise<GeneratedFile[]>;
|
|
22
22
|
/**
|
|
@@ -43,6 +43,6 @@ export declare class PythonGenerator extends BaseGenerator {
|
|
|
43
43
|
generateDomainEvents(entities: Entity[], _apiType?: string, opts?: {
|
|
44
44
|
emitEvents?: boolean;
|
|
45
45
|
}): Promise<GeneratedFile[]>;
|
|
46
|
-
generateGuards(entities: Entity[], auth?: AuthConfig): Promise<GeneratedFile[]>;
|
|
46
|
+
generateGuards(entities: Entity[], auth?: AuthConfig, relationshipMap?: RelationshipMap): Promise<GeneratedFile[]>;
|
|
47
47
|
generateQueryUtils(_entities: Entity[], _apiType: string): Promise<GeneratedFile[]>;
|
|
48
48
|
}
|