@zenstackhq/cli 3.8.0-beta.2 → 3.8.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/dist/index.cjs +143 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +145 -15
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -13
package/dist/index.mjs
CHANGED
|
@@ -6,9 +6,9 @@ import "dotenv/config";
|
|
|
6
6
|
import { DataModel, Enum, isDataField, isDataSource, isEnum, isInvocationExpr, isLiteralExpr, isPlugin } from "@zenstackhq/language/ast";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { invariant, lowerCaseFirst, singleDebounce } from "@zenstackhq/common-helpers";
|
|
9
|
-
import { PrismaSchemaGenerator, TsSchemaGenerator } from "@zenstackhq/sdk";
|
|
9
|
+
import { PrismaSchemaGenerator, TsSchemaGenerator, detectImportFileExtension } from "@zenstackhq/sdk";
|
|
10
10
|
import { createJiti } from "jiti";
|
|
11
|
-
import crypto, { createHash, randomUUID } from "node:crypto";
|
|
11
|
+
import crypto, { createHash, randomUUID, verify } from "node:crypto";
|
|
12
12
|
import fs from "node:fs";
|
|
13
13
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
14
14
|
import terminalLink from "terminal-link";
|
|
@@ -27,6 +27,7 @@ import { ZenStackClient } from "@zenstackhq/orm";
|
|
|
27
27
|
import { MysqlDialect } from "@zenstackhq/orm/dialects/mysql";
|
|
28
28
|
import { PostgresDialect } from "@zenstackhq/orm/dialects/postgres";
|
|
29
29
|
import { SqliteDialect } from "@zenstackhq/orm/dialects/sqlite";
|
|
30
|
+
import { PolicyPlugin } from "@zenstackhq/plugin-policy";
|
|
30
31
|
import { RPCApiHandler } from "@zenstackhq/server/api";
|
|
31
32
|
import { ZenStackMiddleware } from "@zenstackhq/server/express";
|
|
32
33
|
import cors from "cors";
|
|
@@ -289,7 +290,7 @@ async function checkPluginResolution(schemaFile, model) {
|
|
|
289
290
|
for (const plugin of plugins) {
|
|
290
291
|
const provider = getPluginProvider(plugin);
|
|
291
292
|
if (!provider.startsWith("@core/")) {
|
|
292
|
-
const pluginSourcePath = plugin.$cstNode?.
|
|
293
|
+
const pluginSourcePath = plugin.$cstNode?.container?.astNode.$document?.uri?.fsPath ?? schemaFile;
|
|
293
294
|
await loadPluginModule(provider, path.dirname(pluginSourcePath));
|
|
294
295
|
}
|
|
295
296
|
}
|
|
@@ -2305,7 +2306,7 @@ async function runPull(options) {
|
|
|
2305
2306
|
model.declarations.splice(index, 1);
|
|
2306
2307
|
deletedEnums.push(colors.red(`- Enum ${decl.name} deleted`));
|
|
2307
2308
|
});
|
|
2308
|
-
newModel.declarations.filter((d) =>
|
|
2309
|
+
newModel.declarations.filter((d) => d.$type === DataModel.$type || d.$type === Enum.$type).forEach((_declaration) => {
|
|
2309
2310
|
const newDataModel = _declaration;
|
|
2310
2311
|
const declarations = services.shared.workspace.IndexManager.allElements(newDataModel.$type, docsSet).toArray();
|
|
2311
2312
|
const originalDataModel = declarations.find((d) => getDbName(d.node) === getDbName(newDataModel))?.node;
|
|
@@ -2602,8 +2603,9 @@ const plugin = {
|
|
|
2602
2603
|
}
|
|
2603
2604
|
const lite = pluginOptions["lite"] === true;
|
|
2604
2605
|
const liteOnly = pluginOptions["liteOnly"] === true;
|
|
2605
|
-
|
|
2606
|
-
if (importWithFileExtension
|
|
2606
|
+
let importWithFileExtension = pluginOptions["importWithFileExtension"];
|
|
2607
|
+
if (importWithFileExtension === void 0) importWithFileExtension = detectImportFileExtension(outDir);
|
|
2608
|
+
else if (typeof importWithFileExtension !== "string") throw new Error("The \"importWithFileExtension\" option must be a string if specified.");
|
|
2607
2609
|
const generateModelTypes = pluginOptions["generateModels"] !== false;
|
|
2608
2610
|
const generateInputTypes = pluginOptions["generateInput"] !== false;
|
|
2609
2611
|
await new TsSchemaGenerator().generate(model, {
|
|
@@ -2640,7 +2642,7 @@ async function run$5(options) {
|
|
|
2640
2642
|
const logsEnabled = !options.silent;
|
|
2641
2643
|
if (logsEnabled) console.log(colors.green(`\nEnabled watch mode!`));
|
|
2642
2644
|
const schemaExtensions = ZModelLanguageMetaData.fileExtensions;
|
|
2643
|
-
const getRootModelWatchPaths = (model) => new Set(model.declarations.filter((v) => v.$cstNode?.
|
|
2645
|
+
const getRootModelWatchPaths = (model) => new Set(model.declarations.filter((v) => v.$cstNode?.container?.astNode.$type === "Model" && !!v.$cstNode.container.astNode.$document?.uri?.fsPath).map((v) => v.$cstNode.container.astNode.$document.uri.fsPath));
|
|
2644
2646
|
const watchedPaths = getRootModelWatchPaths(model);
|
|
2645
2647
|
if (logsEnabled) {
|
|
2646
2648
|
const logPaths = [...watchedPaths].map((at) => `- ${at}`).join("\n");
|
|
@@ -2722,7 +2724,7 @@ async function runPlugins(schemaFile, model, outputPath, options) {
|
|
|
2722
2724
|
cliPlugin = plugins_exports[provider.slice(6)];
|
|
2723
2725
|
if (!cliPlugin) throw new CliError(`Unknown core plugin: ${provider}`);
|
|
2724
2726
|
} else {
|
|
2725
|
-
const pluginSourcePath = plugin.$cstNode?.
|
|
2727
|
+
const pluginSourcePath = plugin.$cstNode?.container?.astNode.$document?.uri?.fsPath ?? schemaFile;
|
|
2726
2728
|
cliPlugin = await loadPluginModule(provider, path.dirname(pluginSourcePath));
|
|
2727
2729
|
}
|
|
2728
2730
|
if (cliPlugin) {
|
|
@@ -3052,7 +3054,40 @@ async function getLatestVersion() {
|
|
|
3052
3054
|
}
|
|
3053
3055
|
//#endregion
|
|
3054
3056
|
//#region src/actions/proxy.ts
|
|
3057
|
+
const ProxyAuthError = {
|
|
3058
|
+
MISSING_SIGNATURE_HEADER: "Missing x-zenstack-signature header",
|
|
3059
|
+
INVALID_TIMESTAMP: "Request timestamp is expired or invalid",
|
|
3060
|
+
INVALID_SIGNATURE_FORMAT: "Invalid x-zenstack-signature format"
|
|
3061
|
+
};
|
|
3062
|
+
function rejectAuth(res, code) {
|
|
3063
|
+
return res.status(401).json({
|
|
3064
|
+
code,
|
|
3065
|
+
message: ProxyAuthError[code]
|
|
3066
|
+
});
|
|
3067
|
+
}
|
|
3068
|
+
/**
|
|
3069
|
+
* Represents the identity claim embedded in the Authorization header.
|
|
3070
|
+
* The bearer token is a plain base64-encoded JSON string.
|
|
3071
|
+
*/
|
|
3072
|
+
const UserClaimSchema = z.discriminatedUnion("type", [z.object({ type: z.literal("superUser") }), z.object({
|
|
3073
|
+
type: z.literal("user"),
|
|
3074
|
+
data: z.record(z.string(), z.unknown())
|
|
3075
|
+
})]);
|
|
3076
|
+
/**
|
|
3077
|
+
* Accepts a public key in either PEM format or as a raw base64 / base64url DER string
|
|
3078
|
+
* (without the `-----BEGIN PUBLIC KEY-----` markers) and always returns a PEM string.
|
|
3079
|
+
*/
|
|
3080
|
+
function normalizePublicKey(key) {
|
|
3081
|
+
key = key.trim();
|
|
3082
|
+
if (key.startsWith("-----BEGIN PUBLIC KEY-----")) return key;
|
|
3083
|
+
return `-----BEGIN PUBLIC KEY-----\n${key.replace(/-/g, "+").replace(/_/g, "/")}\n-----END PUBLIC KEY-----`;
|
|
3084
|
+
}
|
|
3055
3085
|
async function run(options) {
|
|
3086
|
+
options = {
|
|
3087
|
+
...options,
|
|
3088
|
+
studioAuthKey: options.studioAuthKey ?? process.env["ZENSTACK_STUDIO_AUTH_KEY"]
|
|
3089
|
+
};
|
|
3090
|
+
if (!options.studioAuthKey) console.warn(colors.yellow("Warning: This proxy has no authentication. Do not expose it to the public network.\nTo secure it, get an API key from ZenStack Studio and set it via the ZENSTACK_STUDIO_AUTH_KEY environment variable."));
|
|
3056
3091
|
const allowedLogLevels = ["error", "query"];
|
|
3057
3092
|
const log = options.logLevel?.filter((level) => allowedLogLevels.includes(level));
|
|
3058
3093
|
const schemaFile = getSchemaFile(options.schema);
|
|
@@ -3086,7 +3121,9 @@ async function run(options) {
|
|
|
3086
3121
|
} catch (err) {
|
|
3087
3122
|
throw new CliError(`Failed to connect to the database: ${err instanceof Error ? err.message : String(err)}`);
|
|
3088
3123
|
}
|
|
3089
|
-
|
|
3124
|
+
const authDb = db.$use(new PolicyPlugin());
|
|
3125
|
+
if (options.studioAuthKey) console.log(colors.gray("Access policy plugin enabled for authorization."));
|
|
3126
|
+
startServer(db, schemaModule.schema, options, authDb);
|
|
3090
3127
|
}
|
|
3091
3128
|
function evaluateUrl(schemaUrl) {
|
|
3092
3129
|
if (isLiteralExpr(schemaUrl)) return getStringLiteral(schemaUrl);
|
|
@@ -3147,17 +3184,27 @@ async function createDialect(provider, databaseUrl, outputPath) {
|
|
|
3147
3184
|
default: throw new CliError(`Unsupported database provider: ${provider}`);
|
|
3148
3185
|
}
|
|
3149
3186
|
}
|
|
3150
|
-
function createProxyApp(client, schema) {
|
|
3187
|
+
function createProxyApp(client, schema, authDb, auth) {
|
|
3151
3188
|
const app = express();
|
|
3152
3189
|
app.use(cors());
|
|
3153
|
-
app.use(express.json({
|
|
3190
|
+
app.use(express.json({
|
|
3191
|
+
limit: "5mb",
|
|
3192
|
+
verify: (req, _res, buf) => {
|
|
3193
|
+
req.rawBody = buf.toString("utf8");
|
|
3194
|
+
}
|
|
3195
|
+
}));
|
|
3154
3196
|
app.use(express.urlencoded({
|
|
3155
3197
|
extended: true,
|
|
3156
3198
|
limit: "5mb"
|
|
3157
3199
|
}));
|
|
3200
|
+
if (auth?.studioAuthKey) {
|
|
3201
|
+
const toleranceSecs = auth.signatureToleranceSecs;
|
|
3202
|
+
const normalizedKey = normalizePublicKey(auth.studioAuthKey);
|
|
3203
|
+
app.use(["/api/model", "/api/schema"], createSignatureMiddleware(normalizedKey, toleranceSecs));
|
|
3204
|
+
}
|
|
3158
3205
|
app.use("/api/model", ZenStackMiddleware({
|
|
3159
3206
|
apiHandler: new RPCApiHandler({ schema }),
|
|
3160
|
-
getClient: () => client
|
|
3207
|
+
getClient: (req) => resolveClient(client, authDb, req, !!auth?.studioAuthKey)
|
|
3161
3208
|
}));
|
|
3162
3209
|
app.get("/api/schema", (_req, res) => {
|
|
3163
3210
|
res.json({
|
|
@@ -3167,8 +3214,87 @@ function createProxyApp(client, schema) {
|
|
|
3167
3214
|
});
|
|
3168
3215
|
return app;
|
|
3169
3216
|
}
|
|
3170
|
-
|
|
3171
|
-
|
|
3217
|
+
/**
|
|
3218
|
+
* Creates an Express middleware that verifies the ed25519 signature on every request.
|
|
3219
|
+
*
|
|
3220
|
+
* The signature header format is: `t=<unix-timestamp>,v1=<base64url-signature>`
|
|
3221
|
+
*
|
|
3222
|
+
* The signed message is constructed as:
|
|
3223
|
+
* - GET requests: `<raw-query-string><timestamp>[<authorizationToken>]`
|
|
3224
|
+
* - Other methods: `<raw-body><timestamp>[<authorizationToken>]`
|
|
3225
|
+
*
|
|
3226
|
+
* `authorizationToken` is the bearer token value from the `Authorization` header (if present).
|
|
3227
|
+
*/
|
|
3228
|
+
function createSignatureMiddleware(publicKey, toleranceSeconds) {
|
|
3229
|
+
let lastInvalidSigWarnAt = 0;
|
|
3230
|
+
const WARN_THROTTLE_SECS = 60;
|
|
3231
|
+
function warnInvalidSignature() {
|
|
3232
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
3233
|
+
if (now - lastInvalidSigWarnAt >= WARN_THROTTLE_SECS) {
|
|
3234
|
+
lastInvalidSigWarnAt = now;
|
|
3235
|
+
console.warn(colors.yellow("Warning: Received a request with an invalid signature. Please double-check whether you have the correct public API key configured."));
|
|
3236
|
+
}
|
|
3237
|
+
}
|
|
3238
|
+
return (req, res, next) => {
|
|
3239
|
+
const signatureHeader = req.headers["x-zenstack-signature"];
|
|
3240
|
+
if (!signatureHeader || typeof signatureHeader !== "string") return rejectAuth(res, "MISSING_SIGNATURE_HEADER");
|
|
3241
|
+
const parts = signatureHeader.split(",");
|
|
3242
|
+
const timestampPart = parts.find((p) => p.startsWith("t="));
|
|
3243
|
+
const sigPart = parts.find((p) => p.startsWith("v1="));
|
|
3244
|
+
if (!timestampPart || !sigPart) return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
|
|
3245
|
+
const timestamp = timestampPart.substring(2);
|
|
3246
|
+
const sig = sigPart.substring(3);
|
|
3247
|
+
const requestTime = parseInt(timestamp, 10);
|
|
3248
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
3249
|
+
if (isNaN(requestTime) || Math.abs(now - requestTime) > toleranceSeconds) return rejectAuth(res, "INVALID_TIMESTAMP");
|
|
3250
|
+
let payload;
|
|
3251
|
+
if (req.method === "GET" || req.method === "DELETE") {
|
|
3252
|
+
const qMark = req.originalUrl.indexOf("?");
|
|
3253
|
+
payload = qMark >= 0 ? req.originalUrl.substring(qMark + 1) : "";
|
|
3254
|
+
} else payload = req.rawBody ?? "";
|
|
3255
|
+
const authHeader = req.headers["authorization"];
|
|
3256
|
+
const authorizationToken = authHeader && authHeader.startsWith("Bearer ") ? authHeader.substring(7) : void 0;
|
|
3257
|
+
const message = authorizationToken ? `${payload}${timestamp}${authorizationToken}` : `${payload}${timestamp}`;
|
|
3258
|
+
try {
|
|
3259
|
+
if (!verify(null, Buffer.from(message, "utf8"), publicKey, Buffer.from(sig, "base64url"))) {
|
|
3260
|
+
warnInvalidSignature();
|
|
3261
|
+
return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
|
|
3262
|
+
}
|
|
3263
|
+
} catch {
|
|
3264
|
+
warnInvalidSignature();
|
|
3265
|
+
return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
|
|
3266
|
+
}
|
|
3267
|
+
return next();
|
|
3268
|
+
};
|
|
3269
|
+
}
|
|
3270
|
+
/**
|
|
3271
|
+
* Resolves the appropriate client for a request based on the Authorization header.
|
|
3272
|
+
*
|
|
3273
|
+
* - No studioAuthKey configured (authDb is undefined): always return the base client.
|
|
3274
|
+
* - SuperUser claim: return the base client (full access, no policy enforcement).
|
|
3275
|
+
* - Regular user claim: return authDb with the user identity set via $setAuth.
|
|
3276
|
+
* - No / invalid token: return the base client.
|
|
3277
|
+
*/
|
|
3278
|
+
function resolveClient(client, authDb, req, isAuthKeyEnabled) {
|
|
3279
|
+
const authHeader = req.headers["authorization"];
|
|
3280
|
+
if (!isAuthKeyEnabled && !authHeader) return client;
|
|
3281
|
+
if (!authHeader?.startsWith("Bearer ")) return authDb;
|
|
3282
|
+
const token = authHeader.substring(7);
|
|
3283
|
+
let claim;
|
|
3284
|
+
try {
|
|
3285
|
+
claim = UserClaimSchema.parse(JSON.parse(Buffer.from(token, "base64").toString("utf8")));
|
|
3286
|
+
} catch (err) {
|
|
3287
|
+
console.error(colors.red(`Failed to parse user claim from token: ${err instanceof Error ? err.message : String(err)}`));
|
|
3288
|
+
return authDb;
|
|
3289
|
+
}
|
|
3290
|
+
if (claim.type === "superUser") return client;
|
|
3291
|
+
else return authDb.$setAuth(claim.data);
|
|
3292
|
+
}
|
|
3293
|
+
function startServer(client, schema, options, authDb) {
|
|
3294
|
+
const server = createProxyApp(client, schema, authDb, options.studioAuthKey ? {
|
|
3295
|
+
studioAuthKey: options.studioAuthKey,
|
|
3296
|
+
signatureToleranceSecs: options.signatureToleranceSecs
|
|
3297
|
+
} : void 0).listen(options.port, () => {
|
|
3172
3298
|
console.log(`ZenStack proxy server is running on port: ${options.port}`);
|
|
3173
3299
|
console.log(`You can visit ZenStack Studio at: ${colors.blue("https://studio.zenstack.dev")}`);
|
|
3174
3300
|
});
|
|
@@ -3443,7 +3569,11 @@ Arguments following -- are passed to the seed script. E.g.: "zen db seed -- --us
|
|
|
3443
3569
|
program.command("init").description("Initialize an existing project for ZenStack").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(initAction);
|
|
3444
3570
|
program.command("check").description("Check a ZModel schema for syntax or semantic errors").addOption(schemaOption).addOption(noVersionCheckOption).action(checkAction);
|
|
3445
3571
|
program.command("format").description("Format a ZModel schema file").addOption(schemaOption).addOption(noVersionCheckOption).action(formatAction);
|
|
3446
|
-
program.command("proxy").alias("studio").description("Start the ZenStack proxy server").addOption(schemaOption).addOption(new Option("-p, --port <port>", "port to run the proxy server on").default(2311)).addOption(new Option("-o, --output <path>", "output directory for `zen generate` command")).addOption(new Option("-d, --databaseUrl <url>", "database connection URL")).addOption(new Option("-l, --logLevel <level...>", "Query log levels (e.g., query, error)")).addOption(
|
|
3572
|
+
program.command("proxy").alias("studio").description("Start the ZenStack proxy server").addOption(schemaOption).addOption(new Option("-p, --port <port>", "port to run the proxy server on").default(2311)).addOption(new Option("-o, --output <path>", "output directory for `zen generate` command")).addOption(new Option("-d, --databaseUrl <url>", "database connection URL")).addOption(new Option("-l, --logLevel <level...>", "Query log levels (e.g., query, error)")).addOption(new Option("--studioAuthKey <key>", "Authentication key from ZenStack Studio. When set, the proxy will only accept requests signed by your Studio project.\nCan also be set via the ZENSTACK_STUDIO_AUTH_KEY environment variable. ")).addOption(new Option("--signatureToleranceSecs <seconds>", "Maximum age (in seconds) of a signed request before it is rejected as a replay. Defaults to 60.").default(60).argParser((v) => {
|
|
3573
|
+
const parsed = parseInt(v, 10);
|
|
3574
|
+
if (isNaN(parsed) || parsed < 0) throw new CliError(`--signatureToleranceSecs must be a positive integer, got: ${v}`);
|
|
3575
|
+
return parsed;
|
|
3576
|
+
})).addOption(noVersionCheckOption).action(proxyAction);
|
|
3447
3577
|
program.addHelpCommand("help [command]", "Display help for a command");
|
|
3448
3578
|
program.hook("preAction", async (_thisCommand, actionCommand) => {
|
|
3449
3579
|
if (actionCommand.getOptionValue("versionCheck") !== false) await checkNewVersion();
|