@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 CHANGED
@@ -65,6 +65,7 @@ let _zenstackhq_orm = require("@zenstackhq/orm");
65
65
  let _zenstackhq_orm_dialects_mysql = require("@zenstackhq/orm/dialects/mysql");
66
66
  let _zenstackhq_orm_dialects_postgres = require("@zenstackhq/orm/dialects/postgres");
67
67
  let _zenstackhq_orm_dialects_sqlite = require("@zenstackhq/orm/dialects/sqlite");
68
+ let _zenstackhq_plugin_policy = require("@zenstackhq/plugin-policy");
68
69
  let _zenstackhq_server_api = require("@zenstackhq/server/api");
69
70
  let _zenstackhq_server_express = require("@zenstackhq/server/express");
70
71
  let cors = require("cors");
@@ -319,7 +320,7 @@ async function checkPluginResolution(schemaFile, model) {
319
320
  for (const plugin of plugins) {
320
321
  const provider = getPluginProvider(plugin);
321
322
  if (!provider.startsWith("@core/")) {
322
- const pluginSourcePath = plugin.$cstNode?.parent?.element.$document?.uri?.fsPath ?? schemaFile;
323
+ const pluginSourcePath = plugin.$cstNode?.container?.astNode.$document?.uri?.fsPath ?? schemaFile;
323
324
  await loadPluginModule(provider, node_path.default.dirname(pluginSourcePath));
324
325
  }
325
326
  }
@@ -2335,7 +2336,7 @@ async function runPull(options) {
2335
2336
  model.declarations.splice(index, 1);
2336
2337
  deletedEnums.push(colors.default.red(`- Enum ${decl.name} deleted`));
2337
2338
  });
2338
- newModel.declarations.filter((d) => [_zenstackhq_language_ast.DataModel, _zenstackhq_language_ast.Enum].includes(d.$type)).forEach((_declaration) => {
2339
+ newModel.declarations.filter((d) => d.$type === _zenstackhq_language_ast.DataModel.$type || d.$type === _zenstackhq_language_ast.Enum.$type).forEach((_declaration) => {
2339
2340
  const newDataModel = _declaration;
2340
2341
  const declarations = services.shared.workspace.IndexManager.allElements(newDataModel.$type, docsSet).toArray();
2341
2342
  const originalDataModel = declarations.find((d) => getDbName(d.node) === getDbName(newDataModel))?.node;
@@ -2632,8 +2633,9 @@ const plugin = {
2632
2633
  }
2633
2634
  const lite = pluginOptions["lite"] === true;
2634
2635
  const liteOnly = pluginOptions["liteOnly"] === true;
2635
- const importWithFileExtension = pluginOptions["importWithFileExtension"];
2636
- if (importWithFileExtension && typeof importWithFileExtension !== "string") throw new Error("The \"importWithFileExtension\" option must be a string if specified.");
2636
+ let importWithFileExtension = pluginOptions["importWithFileExtension"];
2637
+ if (importWithFileExtension === void 0) importWithFileExtension = (0, _zenstackhq_sdk.detectImportFileExtension)(outDir);
2638
+ else if (typeof importWithFileExtension !== "string") throw new Error("The \"importWithFileExtension\" option must be a string if specified.");
2637
2639
  const generateModelTypes = pluginOptions["generateModels"] !== false;
2638
2640
  const generateInputTypes = pluginOptions["generateInput"] !== false;
2639
2641
  await new _zenstackhq_sdk.TsSchemaGenerator().generate(model, {
@@ -2670,7 +2672,7 @@ async function run$5(options) {
2670
2672
  const logsEnabled = !options.silent;
2671
2673
  if (logsEnabled) console.log(colors.default.green(`\nEnabled watch mode!`));
2672
2674
  const schemaExtensions = _zenstackhq_language.ZModelLanguageMetaData.fileExtensions;
2673
- const getRootModelWatchPaths = (model) => new Set(model.declarations.filter((v) => v.$cstNode?.parent?.element.$type === "Model" && !!v.$cstNode.parent.element.$document?.uri?.fsPath).map((v) => v.$cstNode.parent.element.$document.uri.fsPath));
2675
+ 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));
2674
2676
  const watchedPaths = getRootModelWatchPaths(model);
2675
2677
  if (logsEnabled) {
2676
2678
  const logPaths = [...watchedPaths].map((at) => `- ${at}`).join("\n");
@@ -2752,7 +2754,7 @@ async function runPlugins(schemaFile, model, outputPath, options) {
2752
2754
  cliPlugin = plugins_exports[provider.slice(6)];
2753
2755
  if (!cliPlugin) throw new CliError(`Unknown core plugin: ${provider}`);
2754
2756
  } else {
2755
- const pluginSourcePath = plugin.$cstNode?.parent?.element.$document?.uri?.fsPath ?? schemaFile;
2757
+ const pluginSourcePath = plugin.$cstNode?.container?.astNode.$document?.uri?.fsPath ?? schemaFile;
2756
2758
  cliPlugin = await loadPluginModule(provider, node_path.default.dirname(pluginSourcePath));
2757
2759
  }
2758
2760
  if (cliPlugin) {
@@ -3082,7 +3084,40 @@ async function getLatestVersion() {
3082
3084
  }
3083
3085
  //#endregion
3084
3086
  //#region src/actions/proxy.ts
3087
+ const ProxyAuthError = {
3088
+ MISSING_SIGNATURE_HEADER: "Missing x-zenstack-signature header",
3089
+ INVALID_TIMESTAMP: "Request timestamp is expired or invalid",
3090
+ INVALID_SIGNATURE_FORMAT: "Invalid x-zenstack-signature format"
3091
+ };
3092
+ function rejectAuth(res, code) {
3093
+ return res.status(401).json({
3094
+ code,
3095
+ message: ProxyAuthError[code]
3096
+ });
3097
+ }
3098
+ /**
3099
+ * Represents the identity claim embedded in the Authorization header.
3100
+ * The bearer token is a plain base64-encoded JSON string.
3101
+ */
3102
+ const UserClaimSchema = zod.z.discriminatedUnion("type", [zod.z.object({ type: zod.z.literal("superUser") }), zod.z.object({
3103
+ type: zod.z.literal("user"),
3104
+ data: zod.z.record(zod.z.string(), zod.z.unknown())
3105
+ })]);
3106
+ /**
3107
+ * Accepts a public key in either PEM format or as a raw base64 / base64url DER string
3108
+ * (without the `-----BEGIN PUBLIC KEY-----` markers) and always returns a PEM string.
3109
+ */
3110
+ function normalizePublicKey(key) {
3111
+ key = key.trim();
3112
+ if (key.startsWith("-----BEGIN PUBLIC KEY-----")) return key;
3113
+ return `-----BEGIN PUBLIC KEY-----\n${key.replace(/-/g, "+").replace(/_/g, "/")}\n-----END PUBLIC KEY-----`;
3114
+ }
3085
3115
  async function run(options) {
3116
+ options = {
3117
+ ...options,
3118
+ studioAuthKey: options.studioAuthKey ?? process.env["ZENSTACK_STUDIO_AUTH_KEY"]
3119
+ };
3120
+ if (!options.studioAuthKey) console.warn(colors.default.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."));
3086
3121
  const allowedLogLevels = ["error", "query"];
3087
3122
  const log = options.logLevel?.filter((level) => allowedLogLevels.includes(level));
3088
3123
  const schemaFile = getSchemaFile(options.schema);
@@ -3116,7 +3151,9 @@ async function run(options) {
3116
3151
  } catch (err) {
3117
3152
  throw new CliError(`Failed to connect to the database: ${err instanceof Error ? err.message : String(err)}`);
3118
3153
  }
3119
- startServer(db, schemaModule.schema, options);
3154
+ const authDb = db.$use(new _zenstackhq_plugin_policy.PolicyPlugin());
3155
+ if (options.studioAuthKey) console.log(colors.default.gray("Access policy plugin enabled for authorization."));
3156
+ startServer(db, schemaModule.schema, options, authDb);
3120
3157
  }
3121
3158
  function evaluateUrl(schemaUrl) {
3122
3159
  if ((0, _zenstackhq_language_ast.isLiteralExpr)(schemaUrl)) return (0, _zenstackhq_language_utils.getStringLiteral)(schemaUrl);
@@ -3177,17 +3214,27 @@ async function createDialect(provider, databaseUrl, outputPath) {
3177
3214
  default: throw new CliError(`Unsupported database provider: ${provider}`);
3178
3215
  }
3179
3216
  }
3180
- function createProxyApp(client, schema) {
3217
+ function createProxyApp(client, schema, authDb, auth) {
3181
3218
  const app = (0, express.default)();
3182
3219
  app.use((0, cors.default)());
3183
- app.use(express.default.json({ limit: "5mb" }));
3220
+ app.use(express.default.json({
3221
+ limit: "5mb",
3222
+ verify: (req, _res, buf) => {
3223
+ req.rawBody = buf.toString("utf8");
3224
+ }
3225
+ }));
3184
3226
  app.use(express.default.urlencoded({
3185
3227
  extended: true,
3186
3228
  limit: "5mb"
3187
3229
  }));
3230
+ if (auth?.studioAuthKey) {
3231
+ const toleranceSecs = auth.signatureToleranceSecs;
3232
+ const normalizedKey = normalizePublicKey(auth.studioAuthKey);
3233
+ app.use(["/api/model", "/api/schema"], createSignatureMiddleware(normalizedKey, toleranceSecs));
3234
+ }
3188
3235
  app.use("/api/model", (0, _zenstackhq_server_express.ZenStackMiddleware)({
3189
3236
  apiHandler: new _zenstackhq_server_api.RPCApiHandler({ schema }),
3190
- getClient: () => client
3237
+ getClient: (req) => resolveClient(client, authDb, req, !!auth?.studioAuthKey)
3191
3238
  }));
3192
3239
  app.get("/api/schema", (_req, res) => {
3193
3240
  res.json({
@@ -3197,8 +3244,87 @@ function createProxyApp(client, schema) {
3197
3244
  });
3198
3245
  return app;
3199
3246
  }
3200
- function startServer(client, schema, options) {
3201
- const server = createProxyApp(client, schema).listen(options.port, () => {
3247
+ /**
3248
+ * Creates an Express middleware that verifies the ed25519 signature on every request.
3249
+ *
3250
+ * The signature header format is: `t=<unix-timestamp>,v1=<base64url-signature>`
3251
+ *
3252
+ * The signed message is constructed as:
3253
+ * - GET requests: `<raw-query-string><timestamp>[<authorizationToken>]`
3254
+ * - Other methods: `<raw-body><timestamp>[<authorizationToken>]`
3255
+ *
3256
+ * `authorizationToken` is the bearer token value from the `Authorization` header (if present).
3257
+ */
3258
+ function createSignatureMiddleware(publicKey, toleranceSeconds) {
3259
+ let lastInvalidSigWarnAt = 0;
3260
+ const WARN_THROTTLE_SECS = 60;
3261
+ function warnInvalidSignature() {
3262
+ const now = Math.floor(Date.now() / 1e3);
3263
+ if (now - lastInvalidSigWarnAt >= WARN_THROTTLE_SECS) {
3264
+ lastInvalidSigWarnAt = now;
3265
+ console.warn(colors.default.yellow("Warning: Received a request with an invalid signature. Please double-check whether you have the correct public API key configured."));
3266
+ }
3267
+ }
3268
+ return (req, res, next) => {
3269
+ const signatureHeader = req.headers["x-zenstack-signature"];
3270
+ if (!signatureHeader || typeof signatureHeader !== "string") return rejectAuth(res, "MISSING_SIGNATURE_HEADER");
3271
+ const parts = signatureHeader.split(",");
3272
+ const timestampPart = parts.find((p) => p.startsWith("t="));
3273
+ const sigPart = parts.find((p) => p.startsWith("v1="));
3274
+ if (!timestampPart || !sigPart) return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3275
+ const timestamp = timestampPart.substring(2);
3276
+ const sig = sigPart.substring(3);
3277
+ const requestTime = parseInt(timestamp, 10);
3278
+ const now = Math.floor(Date.now() / 1e3);
3279
+ if (isNaN(requestTime) || Math.abs(now - requestTime) > toleranceSeconds) return rejectAuth(res, "INVALID_TIMESTAMP");
3280
+ let payload;
3281
+ if (req.method === "GET" || req.method === "DELETE") {
3282
+ const qMark = req.originalUrl.indexOf("?");
3283
+ payload = qMark >= 0 ? req.originalUrl.substring(qMark + 1) : "";
3284
+ } else payload = req.rawBody ?? "";
3285
+ const authHeader = req.headers["authorization"];
3286
+ const authorizationToken = authHeader && authHeader.startsWith("Bearer ") ? authHeader.substring(7) : void 0;
3287
+ const message = authorizationToken ? `${payload}${timestamp}${authorizationToken}` : `${payload}${timestamp}`;
3288
+ try {
3289
+ if (!(0, node_crypto.verify)(null, Buffer.from(message, "utf8"), publicKey, Buffer.from(sig, "base64url"))) {
3290
+ warnInvalidSignature();
3291
+ return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3292
+ }
3293
+ } catch {
3294
+ warnInvalidSignature();
3295
+ return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3296
+ }
3297
+ return next();
3298
+ };
3299
+ }
3300
+ /**
3301
+ * Resolves the appropriate client for a request based on the Authorization header.
3302
+ *
3303
+ * - No studioAuthKey configured (authDb is undefined): always return the base client.
3304
+ * - SuperUser claim: return the base client (full access, no policy enforcement).
3305
+ * - Regular user claim: return authDb with the user identity set via $setAuth.
3306
+ * - No / invalid token: return the base client.
3307
+ */
3308
+ function resolveClient(client, authDb, req, isAuthKeyEnabled) {
3309
+ const authHeader = req.headers["authorization"];
3310
+ if (!isAuthKeyEnabled && !authHeader) return client;
3311
+ if (!authHeader?.startsWith("Bearer ")) return authDb;
3312
+ const token = authHeader.substring(7);
3313
+ let claim;
3314
+ try {
3315
+ claim = UserClaimSchema.parse(JSON.parse(Buffer.from(token, "base64").toString("utf8")));
3316
+ } catch (err) {
3317
+ console.error(colors.default.red(`Failed to parse user claim from token: ${err instanceof Error ? err.message : String(err)}`));
3318
+ return authDb;
3319
+ }
3320
+ if (claim.type === "superUser") return client;
3321
+ else return authDb.$setAuth(claim.data);
3322
+ }
3323
+ function startServer(client, schema, options, authDb) {
3324
+ const server = createProxyApp(client, schema, authDb, options.studioAuthKey ? {
3325
+ studioAuthKey: options.studioAuthKey,
3326
+ signatureToleranceSecs: options.signatureToleranceSecs
3327
+ } : void 0).listen(options.port, () => {
3202
3328
  console.log(`ZenStack proxy server is running on port: ${options.port}`);
3203
3329
  console.log(`You can visit ZenStack Studio at: ${colors.default.blue("https://studio.zenstack.dev")}`);
3204
3330
  });
@@ -3473,7 +3599,11 @@ Arguments following -- are passed to the seed script. E.g.: "zen db seed -- --us
3473
3599
  program.command("init").description("Initialize an existing project for ZenStack").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(initAction);
3474
3600
  program.command("check").description("Check a ZModel schema for syntax or semantic errors").addOption(schemaOption).addOption(noVersionCheckOption).action(checkAction);
3475
3601
  program.command("format").description("Format a ZModel schema file").addOption(schemaOption).addOption(noVersionCheckOption).action(formatAction);
3476
- program.command("proxy").alias("studio").description("Start the ZenStack proxy server").addOption(schemaOption).addOption(new commander.Option("-p, --port <port>", "port to run the proxy server on").default(2311)).addOption(new commander.Option("-o, --output <path>", "output directory for `zen generate` command")).addOption(new commander.Option("-d, --databaseUrl <url>", "database connection URL")).addOption(new commander.Option("-l, --logLevel <level...>", "Query log levels (e.g., query, error)")).addOption(noVersionCheckOption).action(proxyAction);
3602
+ program.command("proxy").alias("studio").description("Start the ZenStack proxy server").addOption(schemaOption).addOption(new commander.Option("-p, --port <port>", "port to run the proxy server on").default(2311)).addOption(new commander.Option("-o, --output <path>", "output directory for `zen generate` command")).addOption(new commander.Option("-d, --databaseUrl <url>", "database connection URL")).addOption(new commander.Option("-l, --logLevel <level...>", "Query log levels (e.g., query, error)")).addOption(new commander.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 commander.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) => {
3603
+ const parsed = parseInt(v, 10);
3604
+ if (isNaN(parsed) || parsed < 0) throw new CliError(`--signatureToleranceSecs must be a positive integer, got: ${v}`);
3605
+ return parsed;
3606
+ })).addOption(noVersionCheckOption).action(proxyAction);
3477
3607
  program.addHelpCommand("help [command]", "Display help for a command");
3478
3608
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3479
3609
  if (actionCommand.getOptionValue("versionCheck") !== false) await checkNewVersion();