@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 +136 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +137 -8
- package/dist/index.mjs.map +1 -1
- package/package.json +13 -12
package/dist/index.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import path from "node:path";
|
|
|
8
8
|
import { invariant, lowerCaseFirst, singleDebounce } from "@zenstackhq/common-helpers";
|
|
9
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";
|
|
@@ -3053,7 +3054,40 @@ async function getLatestVersion() {
|
|
|
3053
3054
|
}
|
|
3054
3055
|
//#endregion
|
|
3055
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
|
+
}
|
|
3056
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."));
|
|
3057
3091
|
const allowedLogLevels = ["error", "query"];
|
|
3058
3092
|
const log = options.logLevel?.filter((level) => allowedLogLevels.includes(level));
|
|
3059
3093
|
const schemaFile = getSchemaFile(options.schema);
|
|
@@ -3087,7 +3121,9 @@ async function run(options) {
|
|
|
3087
3121
|
} catch (err) {
|
|
3088
3122
|
throw new CliError(`Failed to connect to the database: ${err instanceof Error ? err.message : String(err)}`);
|
|
3089
3123
|
}
|
|
3090
|
-
|
|
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);
|
|
3091
3127
|
}
|
|
3092
3128
|
function evaluateUrl(schemaUrl) {
|
|
3093
3129
|
if (isLiteralExpr(schemaUrl)) return getStringLiteral(schemaUrl);
|
|
@@ -3148,17 +3184,27 @@ async function createDialect(provider, databaseUrl, outputPath) {
|
|
|
3148
3184
|
default: throw new CliError(`Unsupported database provider: ${provider}`);
|
|
3149
3185
|
}
|
|
3150
3186
|
}
|
|
3151
|
-
function createProxyApp(client, schema) {
|
|
3187
|
+
function createProxyApp(client, schema, authDb, auth) {
|
|
3152
3188
|
const app = express();
|
|
3153
3189
|
app.use(cors());
|
|
3154
|
-
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
|
+
}));
|
|
3155
3196
|
app.use(express.urlencoded({
|
|
3156
3197
|
extended: true,
|
|
3157
3198
|
limit: "5mb"
|
|
3158
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
|
+
}
|
|
3159
3205
|
app.use("/api/model", ZenStackMiddleware({
|
|
3160
3206
|
apiHandler: new RPCApiHandler({ schema }),
|
|
3161
|
-
getClient: () => client
|
|
3207
|
+
getClient: (req) => resolveClient(client, authDb, req, !!auth?.studioAuthKey)
|
|
3162
3208
|
}));
|
|
3163
3209
|
app.get("/api/schema", (_req, res) => {
|
|
3164
3210
|
res.json({
|
|
@@ -3168,8 +3214,87 @@ function createProxyApp(client, schema) {
|
|
|
3168
3214
|
});
|
|
3169
3215
|
return app;
|
|
3170
3216
|
}
|
|
3171
|
-
|
|
3172
|
-
|
|
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, () => {
|
|
3173
3298
|
console.log(`ZenStack proxy server is running on port: ${options.port}`);
|
|
3174
3299
|
console.log(`You can visit ZenStack Studio at: ${colors.blue("https://studio.zenstack.dev")}`);
|
|
3175
3300
|
});
|
|
@@ -3444,7 +3569,11 @@ Arguments following -- are passed to the seed script. E.g.: "zen db seed -- --us
|
|
|
3444
3569
|
program.command("init").description("Initialize an existing project for ZenStack").argument("[path]", "project path", ".").addOption(noVersionCheckOption).action(initAction);
|
|
3445
3570
|
program.command("check").description("Check a ZModel schema for syntax or semantic errors").addOption(schemaOption).addOption(noVersionCheckOption).action(checkAction);
|
|
3446
3571
|
program.command("format").description("Format a ZModel schema file").addOption(schemaOption).addOption(noVersionCheckOption).action(formatAction);
|
|
3447
|
-
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);
|
|
3448
3577
|
program.addHelpCommand("help [command]", "Display help for a command");
|
|
3449
3578
|
program.hook("preAction", async (_thisCommand, actionCommand) => {
|
|
3450
3579
|
if (actionCommand.getOptionValue("versionCheck") !== false) await checkNewVersion();
|