| 257 | } |
| 258 | |
| 259 | export function createProxyApp( |
| 260 | client: ClientContract<SchemaDef>, |
| 261 | schema: SchemaDef, |
| 262 | authDb: ClientContract<SchemaDef>, |
| 263 | auth?: { |
| 264 | studioAuthKey: string; |
| 265 | /** Seconds within which a signed request is considered valid. Defaults to 60. */ |
| 266 | signatureToleranceSecs: number; |
| 267 | }, |
| 268 | ): express.Application { |
| 269 | const app = express(); |
| 270 | app.use(cors()); |
| 271 | app.use( |
| 272 | express.json({ |
| 273 | limit: '5mb', |
| 274 | verify: (req, _res, buf) => { |
| 275 | // Capture the raw body string for use in signature verification. |
| 276 | (req as express.Request & { rawBody?: string }).rawBody = buf.toString('utf8'); |
| 277 | }, |
| 278 | }), |
| 279 | ); |
| 280 | app.use(express.urlencoded({ extended: true, limit: '5mb' })); |
| 281 | |
| 282 | if (auth?.studioAuthKey) { |
| 283 | // Apply signature-verification middleware to all authenticated endpoints. |
| 284 | const toleranceSecs = auth.signatureToleranceSecs; |
| 285 | const normalizedKey = normalizePublicKey(auth.studioAuthKey); |
| 286 | app.use(['/api/model', '/api/schema'], createSignatureMiddleware(normalizedKey, toleranceSecs)); |
| 287 | } |
| 288 | |
| 289 | app.use( |
| 290 | '/api/model', |
| 291 | ZenStackMiddleware({ |
| 292 | apiHandler: new RPCApiHandler({ schema }), |
| 293 | getClient: (req) => resolveClient(client, authDb, req, !!auth?.studioAuthKey), |
| 294 | }), |
| 295 | ); |
| 296 | |
| 297 | app.get('/api/schema', (_req, res: express.Response) => { |
| 298 | res.json({ ...schema, zenstackVersion: getVersion() }); |
| 299 | }); |
| 300 | |
| 301 | return app; |
| 302 | } |
| 303 | |
| 304 | /** |
| 305 | * Creates an Express middleware that verifies the ed25519 signature on every request. |