@zenstackhq/cli 3.8.0-beta.3 → 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");
@@ -3083,7 +3084,40 @@ async function getLatestVersion() {
3083
3084
  }
3084
3085
  //#endregion
3085
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
+ }
3086
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."));
3087
3121
  const allowedLogLevels = ["error", "query"];
3088
3122
  const log = options.logLevel?.filter((level) => allowedLogLevels.includes(level));
3089
3123
  const schemaFile = getSchemaFile(options.schema);
@@ -3117,7 +3151,9 @@ async function run(options) {
3117
3151
  } catch (err) {
3118
3152
  throw new CliError(`Failed to connect to the database: ${err instanceof Error ? err.message : String(err)}`);
3119
3153
  }
3120
- 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);
3121
3157
  }
3122
3158
  function evaluateUrl(schemaUrl) {
3123
3159
  if ((0, _zenstackhq_language_ast.isLiteralExpr)(schemaUrl)) return (0, _zenstackhq_language_utils.getStringLiteral)(schemaUrl);
@@ -3178,17 +3214,27 @@ async function createDialect(provider, databaseUrl, outputPath) {
3178
3214
  default: throw new CliError(`Unsupported database provider: ${provider}`);
3179
3215
  }
3180
3216
  }
3181
- function createProxyApp(client, schema) {
3217
+ function createProxyApp(client, schema, authDb, auth) {
3182
3218
  const app = (0, express.default)();
3183
3219
  app.use((0, cors.default)());
3184
- 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
+ }));
3185
3226
  app.use(express.default.urlencoded({
3186
3227
  extended: true,
3187
3228
  limit: "5mb"
3188
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
+ }
3189
3235
  app.use("/api/model", (0, _zenstackhq_server_express.ZenStackMiddleware)({
3190
3236
  apiHandler: new _zenstackhq_server_api.RPCApiHandler({ schema }),
3191
- getClient: () => client
3237
+ getClient: (req) => resolveClient(client, authDb, req, !!auth?.studioAuthKey)
3192
3238
  }));
3193
3239
  app.get("/api/schema", (_req, res) => {
3194
3240
  res.json({
@@ -3198,8 +3244,87 @@ function createProxyApp(client, schema) {
3198
3244
  });
3199
3245
  return app;
3200
3246
  }
3201
- function startServer(client, schema, options) {
3202
- 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, () => {
3203
3328
  console.log(`ZenStack proxy server is running on port: ${options.port}`);
3204
3329
  console.log(`You can visit ZenStack Studio at: ${colors.default.blue("https://studio.zenstack.dev")}`);
3205
3330
  });
@@ -3474,7 +3599,11 @@ Arguments following -- are passed to the seed script. E.g.: "zen db seed -- --us
3474
3599
  program.command("init").description("Initialize an existing project for ZenStack").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(initAction);
3475
3600
  program.command("check").description("Check a ZModel schema for syntax or semantic errors").addOption(schemaOption).addOption(noVersionCheckOption).action(checkAction);
3476
3601
  program.command("format").description("Format a ZModel schema file").addOption(schemaOption).addOption(noVersionCheckOption).action(formatAction);
3477
- 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);
3478
3607
  program.addHelpCommand("help [command]", "Display help for a command");
3479
3608
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3480
3609
  if (actionCommand.getOptionValue("versionCheck") !== false) await checkNewVersion();