@venturekit/cli 0.0.0-dev.20260429204301 → 0.0.0-dev.20260430162351
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/commands/dev.d.ts.map +1 -1
- package/dist/commands/dev.js +68 -1
- package/dist/commands/dev.js.map +1 -1
- package/dist/utils/cognito-local.d.ts +86 -0
- package/dist/utils/cognito-local.d.ts.map +1 -0
- package/dist/utils/cognito-local.js +284 -0
- package/dist/utils/cognito-local.js.map +1 -0
- package/dist/utils/docker-compose.d.ts +5 -0
- package/dist/utils/docker-compose.d.ts.map +1 -1
- package/dist/utils/docker-compose.js +72 -1
- package/dist/utils/docker-compose.js.map +1 -1
- package/dist/utils/local-server.d.ts +68 -0
- package/dist/utils/local-server.d.ts.map +1 -1
- package/dist/utils/local-server.js +135 -27
- package/dist/utils/local-server.js.map +1 -1
- package/package.json +5 -4
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* MinIO → localhost:9000 / 9001 (buckets per project)
|
|
10
10
|
* pgweb → localhost:8081 (DB viewer, auto-added with Postgres)
|
|
11
11
|
* Redis Insight → localhost:5540 (queue/cache viewer, auto-added with Redis)
|
|
12
|
+
* cognito-local → localhost:9229 (Cognito mock, auto-added with auth intent)
|
|
12
13
|
*/
|
|
13
14
|
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
|
|
14
15
|
import { join } from 'path';
|
|
@@ -81,6 +82,10 @@ function allQueues(reg) {
|
|
|
81
82
|
}
|
|
82
83
|
return [...set].sort();
|
|
83
84
|
}
|
|
85
|
+
/** Does any registered project need cognito-local? */
|
|
86
|
+
function anyNeedsCognito(reg) {
|
|
87
|
+
return Object.values(reg).some((e) => e.needsCognito === true);
|
|
88
|
+
}
|
|
84
89
|
/**
|
|
85
90
|
* Generate the shared docker-compose.yml based on the full registry.
|
|
86
91
|
* Services use standard ports.
|
|
@@ -91,6 +96,7 @@ function generateSharedCompose(reg) {
|
|
|
91
96
|
const dbs = allDatabases(reg);
|
|
92
97
|
const needsRedis = anyNeedsRedis(reg);
|
|
93
98
|
const buckets = allBuckets(reg);
|
|
99
|
+
const needsCognito = anyNeedsCognito(reg);
|
|
94
100
|
// ── Postgres ────────────────────────────────────────────────────────
|
|
95
101
|
if (dbs.length > 0) {
|
|
96
102
|
services.push(` postgres:
|
|
@@ -209,6 +215,40 @@ function generateSharedCompose(reg) {
|
|
|
209
215
|
entrypoint: /bin/sh -c "${mcCommands}"
|
|
210
216
|
restart: "no"`);
|
|
211
217
|
}
|
|
218
|
+
// ── cognito-local ───────────────────────────────────────────────────
|
|
219
|
+
// jagregory/cognito-local emulates the Cognito User-Pool API on the
|
|
220
|
+
// standard Cognito SDK over plain HTTP. Pool + client provisioning is
|
|
221
|
+
// done at runtime by `vk dev` via the AWS SDK pointed at this endpoint
|
|
222
|
+
// (see provisionCognitoLocal in commands/dev.ts); the in-container
|
|
223
|
+
// `/app/.cognito` volume persists pool + user state across restarts.
|
|
224
|
+
// Port 9229 is the default and matches the README.
|
|
225
|
+
//
|
|
226
|
+
// **Issuer pinning.** The jagregory image sets `HOST=0.0.0.0` in its
|
|
227
|
+
// Dockerfile, and cognito-local uses `HOST` to build the JWT `iss`
|
|
228
|
+
// claim (→ `http://0.0.0.0:9229/<poolId>`). Flipping HOST to
|
|
229
|
+
// `localhost` would also rebind the socket to loopback-only, breaking
|
|
230
|
+
// port forwarding. Instead we bind-mount a small `config.json` into
|
|
231
|
+
// `/app/.cognito/config.json` that overrides `TokenConfig.IssuerDomain`
|
|
232
|
+
// to `http://localhost:9229` so tokens match what
|
|
233
|
+
// `COGNITO_ENDPOINT=http://localhost:9229` causes the verifier to
|
|
234
|
+
// expect. Without this, `/auth/me` silently 401s on every request
|
|
235
|
+
// because the issuer comparison fails.
|
|
236
|
+
if (needsCognito) {
|
|
237
|
+
services.push(` cognito-local:
|
|
238
|
+
image: jagregory/cognito-local:latest
|
|
239
|
+
restart: unless-stopped
|
|
240
|
+
ports:
|
|
241
|
+
- "9229:9229"
|
|
242
|
+
volumes:
|
|
243
|
+
- cognito-local-data:/app/.cognito
|
|
244
|
+
- ./cognito-local-config.json:/app/.cognito/config.json
|
|
245
|
+
healthcheck:
|
|
246
|
+
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:9229/health"]
|
|
247
|
+
interval: 5s
|
|
248
|
+
timeout: 5s
|
|
249
|
+
retries: 10`);
|
|
250
|
+
volumes.push(' cognito-local-data:');
|
|
251
|
+
}
|
|
212
252
|
if (services.length === 0)
|
|
213
253
|
return '';
|
|
214
254
|
let content = `# Auto-generated by VentureKit CLI — do not edit manually
|
|
@@ -244,7 +284,8 @@ export function ensureDockerCompose(_projectDir, intents, projectName, stage) {
|
|
|
244
284
|
const hasCaches = !!(intents.caches && intents.caches.length > 0);
|
|
245
285
|
const hasQueues = !!(intents.queues && intents.queues.length > 0);
|
|
246
286
|
const hasStorage = !!(intents.storage && intents.storage.length > 0);
|
|
247
|
-
const
|
|
287
|
+
const hasAuth = !!(intents.auth && intents.auth.length > 0);
|
|
288
|
+
const needsAnyService = hasDatabases || hasCaches || hasQueues || hasStorage || hasAuth;
|
|
248
289
|
if (!needsAnyService) {
|
|
249
290
|
return { composePath: null, envVars: {}, hasServices: false };
|
|
250
291
|
}
|
|
@@ -264,6 +305,7 @@ export function ensureDockerCompose(_projectDir, intents, projectName, stage) {
|
|
|
264
305
|
buckets: bucketNames,
|
|
265
306
|
queues: queueNames,
|
|
266
307
|
needsRedis: hasCaches || hasQueues,
|
|
308
|
+
needsCognito: hasAuth,
|
|
267
309
|
};
|
|
268
310
|
saveRegistry(reg);
|
|
269
311
|
// ── Regenerate shared compose ───────────────────────────────────────
|
|
@@ -274,6 +316,24 @@ export function ensureDockerCompose(_projectDir, intents, projectName, stage) {
|
|
|
274
316
|
if (existing !== content) {
|
|
275
317
|
writeFileSync(composePath, content, 'utf-8');
|
|
276
318
|
}
|
|
319
|
+
// ── cognito-local config override ───────────────────────────────────
|
|
320
|
+
// When any project needs cognito-local, ensure the pinned issuer
|
|
321
|
+
// config file exists alongside the compose file so the bind mount
|
|
322
|
+
// resolves. See `generateSharedCompose` for the full rationale.
|
|
323
|
+
if (anyNeedsCognito(reg)) {
|
|
324
|
+
const cognitoConfigPath = join(VK_HOME, 'cognito-local-config.json');
|
|
325
|
+
const cognitoConfig = JSON.stringify({
|
|
326
|
+
TokenConfig: {
|
|
327
|
+
IssuerDomain: 'http://localhost:9229',
|
|
328
|
+
},
|
|
329
|
+
}, null, 2) + '\n';
|
|
330
|
+
const existingCfg = existsSync(cognitoConfigPath)
|
|
331
|
+
? readFileSync(cognitoConfigPath, 'utf-8')
|
|
332
|
+
: '';
|
|
333
|
+
if (existingCfg !== cognitoConfig) {
|
|
334
|
+
writeFileSync(cognitoConfigPath, cognitoConfig, 'utf-8');
|
|
335
|
+
}
|
|
336
|
+
}
|
|
277
337
|
// ── Build project-specific env vars ─────────────────────────────────
|
|
278
338
|
const envVars = {};
|
|
279
339
|
if (hasDatabases) {
|
|
@@ -312,6 +372,17 @@ export function ensureDockerCompose(_projectDir, intents, projectName, stage) {
|
|
|
312
372
|
envVars['VENTURE_MINIO_SECRET_KEY'] = 'minioadmin';
|
|
313
373
|
envVars['VENTURE_STORAGE_BUCKET'] = `${projectName}-${intents.storage[0].id}`;
|
|
314
374
|
}
|
|
375
|
+
if (hasAuth) {
|
|
376
|
+
// Point `@venturekit/auth/server` at the in-docker cognito-local
|
|
377
|
+
// mock. The pool + client IDs aren't known yet at this stage —
|
|
378
|
+
// they're created at runtime by `provisionCognitoLocal()` and
|
|
379
|
+
// injected separately into the local server's env once available.
|
|
380
|
+
envVars['COGNITO_ENDPOINT'] = 'http://localhost:9229';
|
|
381
|
+
// cognito-local doesn't enforce a specific region, but the AWS SDK
|
|
382
|
+
// requires one — pin it to a stable value so cached SDK clients
|
|
383
|
+
// don't churn between dev sessions.
|
|
384
|
+
envVars['COGNITO_REGION'] = 'local';
|
|
385
|
+
}
|
|
315
386
|
return { composePath, envVars, hasServices: true };
|
|
316
387
|
}
|
|
317
388
|
//# sourceMappingURL=docker-compose.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docker-compose.js","sourceRoot":"","sources":["../../src/utils/docker-compose.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"docker-compose.js","sourceRoot":"","sources":["../../src/utils/docker-compose.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAmB7B,yEAAyE;AAEzE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;AAgBvC,SAAS,YAAY;IACnB,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;IACzC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;QAAE,OAAO,EAAE,CAAC;IAC9B,IAAI,CAAC;QAAC,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;IAAC,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,EAAE,CAAC;IAAC,CAAC;AAC3E,CAAC;AAED,SAAS,YAAY,CAAC,GAAoB;IACxC,SAAS,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACxC,aAAa,CAAC,IAAI,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;AACvF,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,MAAM,CAAC,MAAc,EAAE,KAAa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gBAAgB,CAAC,GAAG,OAAO,CAAC;IACtC,CAAC;IAED,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC;AACrD,CAAC"}
|
|
@@ -8,6 +8,50 @@
|
|
|
8
8
|
* existing handler() functions work unchanged.
|
|
9
9
|
*/
|
|
10
10
|
import * as http from 'http';
|
|
11
|
+
/**
|
|
12
|
+
* CORS configuration for the local dev server.
|
|
13
|
+
*
|
|
14
|
+
* Mirrors `api.cors` from the resolved env config (see `@venturekit/core`
|
|
15
|
+
* `ApiEnvConfig.cors`). When omitted, the server falls back to a dev-friendly
|
|
16
|
+
* default: echo the request's `Origin` back and enable credentials so
|
|
17
|
+
* `fetch(..., { credentials: 'include' })` from a browser dev app (e.g.
|
|
18
|
+
* http://localhost:3000 → http://localhost:3001) works without extra wiring.
|
|
19
|
+
*/
|
|
20
|
+
export interface LocalServerCors {
|
|
21
|
+
allowOrigins: string[];
|
|
22
|
+
allowMethods: string[];
|
|
23
|
+
allowHeaders: string[];
|
|
24
|
+
allowCredentials: boolean;
|
|
25
|
+
maxAgeSec: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Resolve the value of `Access-Control-Allow-Origin` for an incoming request.
|
|
29
|
+
*
|
|
30
|
+
* Matching rules (in order):
|
|
31
|
+
* 1. `allowOrigins` contains `'*'` → return `'*'`
|
|
32
|
+
* 2. `allowOrigins` contains the exact origin → return that origin
|
|
33
|
+
* 3. `allowOrigins` contains a pattern with `*` (e.g. `http://*.localhost:3000`)
|
|
34
|
+
* whose regex matches the request origin → return the request origin
|
|
35
|
+
* 4. otherwise → return `''` (no header emitted)
|
|
36
|
+
*
|
|
37
|
+
* The `*` in a pattern matches one or more non-slash characters so
|
|
38
|
+
* `http://*.localhost:3000` matches `http://tenant.localhost:3000` but NOT
|
|
39
|
+
* `http://localhost:3000` (use two entries for that).
|
|
40
|
+
*/
|
|
41
|
+
export declare function resolveAllowedOrigin(reqOrigin: string, allowOrigins: string[]): string;
|
|
42
|
+
/**
|
|
43
|
+
* Build the CORS response headers for the current request.
|
|
44
|
+
*
|
|
45
|
+
* - `isPreflight` controls whether the preflight-only headers (methods,
|
|
46
|
+
* allowed headers, max-age) are included.
|
|
47
|
+
* - When `cors` is `undefined`, defaults to a permissive dev mode: echo the
|
|
48
|
+
* request origin and allow credentials. This keeps `vk dev` working out of
|
|
49
|
+
* the box for browser-based admin apps during local development.
|
|
50
|
+
* - A wildcard `*` + `allowCredentials: true` is downgraded to echoing the
|
|
51
|
+
* request origin, since browsers reject `*` + credentials per the CORS
|
|
52
|
+
* spec.
|
|
53
|
+
*/
|
|
54
|
+
export declare function buildCorsHeaders(reqOrigin: string, cors: LocalServerCors | undefined, isPreflight: boolean): Record<string, string>;
|
|
11
55
|
/**
|
|
12
56
|
* Discovered route definition
|
|
13
57
|
*/
|
|
@@ -32,6 +76,23 @@ interface Route {
|
|
|
32
76
|
* - src/routes/users/[id]/put.ts -> PUT /users/{id}
|
|
33
77
|
*/
|
|
34
78
|
export declare function discoverRoutes(routesDir: string): Route[];
|
|
79
|
+
/**
|
|
80
|
+
* Build the HTTP status + headers for a Lambda-shaped result.
|
|
81
|
+
*
|
|
82
|
+
* Exported for unit tests — the end-to-end `writeLambdaResult` below
|
|
83
|
+
* drives `res.writeHead` / `res.end`, but the pure header-assembly
|
|
84
|
+
* logic (including the API Gateway v2 `cookies` → `Set-Cookie`
|
|
85
|
+
* translation) lives here so it can be asserted without spinning up
|
|
86
|
+
* an HTTP server.
|
|
87
|
+
*/
|
|
88
|
+
export declare function buildLambdaResponseHeaders(result: {
|
|
89
|
+
statusCode?: number;
|
|
90
|
+
headers?: Record<string, unknown>;
|
|
91
|
+
cookies?: unknown;
|
|
92
|
+
}): {
|
|
93
|
+
statusCode: number;
|
|
94
|
+
headers: Record<string, string | string[]>;
|
|
95
|
+
};
|
|
35
96
|
/**
|
|
36
97
|
* Discovered standalone function definition
|
|
37
98
|
*/
|
|
@@ -68,6 +129,13 @@ export interface LocalServerOptions {
|
|
|
68
129
|
env?: Record<string, string>;
|
|
69
130
|
/** Enable hot reload (file watching) — default: true */
|
|
70
131
|
watch?: boolean;
|
|
132
|
+
/**
|
|
133
|
+
* CORS configuration, typically derived from `api.cors` in the resolved
|
|
134
|
+
* env config. When `undefined`, the dev server falls back to a dev-friendly
|
|
135
|
+
* default: echo the request origin + allow credentials. See
|
|
136
|
+
* {@link buildCorsHeaders}.
|
|
137
|
+
*/
|
|
138
|
+
cors?: LocalServerCors;
|
|
71
139
|
}
|
|
72
140
|
/**
|
|
73
141
|
* Start the local development server.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-server.d.ts","sourceRoot":"","sources":["../../src/utils/local-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAU7B;;GAEG;AACH,UAAU,KAAK;IACb,MAAM,EAAE,MAAM,CAAC;IACf,iCAAiC;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,6CAA6C;IAC7C,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,gDAAgD;IAChD,WAAW,EAAE,MAAM,CAAC;CACrB;AAwCD;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,KAAK,EAAE,CAoCzD;
|
|
1
|
+
{"version":3,"file":"local-server.d.ts","sourceRoot":"","sources":["../../src/utils/local-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAU7B;;;;;;;;GAQG;AACH,MAAM,WAAW,eAAe;IAC9B,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,SAAS,EAA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;IACjC,4CAA4C;IAC5C,SAAS,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,6DAA6D;IAC7D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kEAAkE;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,wBAAwB;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,sCAAsC;IACtC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,wDAAwD;IACxD,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;;;;OAKG;IACH,IAAI,CAAC,EAAE,eAAe,CAAC;CACxB;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CA8jBxF"}
|
|
@@ -16,6 +16,87 @@ import { createJiti } from 'jiti';
|
|
|
16
16
|
import { createFileWatcher, logWatchEvent } from './file-watcher.js';
|
|
17
17
|
import { createLocalQueueProcessor } from './local-queue.js';
|
|
18
18
|
import { createLocalCronScheduler } from './local-cron.js';
|
|
19
|
+
/**
|
|
20
|
+
* Built-in dev endpoints (/_dev/*) need permissive but credential-safe CORS
|
|
21
|
+
* so that browser-based tooling (e.g. the admin calling /_dev/queue/*) works.
|
|
22
|
+
* We always echo the origin and allow credentials for these internal routes.
|
|
23
|
+
*/
|
|
24
|
+
const DEV_ENDPOINT_CORS_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
|
|
25
|
+
const DEV_ENDPOINT_CORS_HEADERS = ['Authorization', 'Content-Type', 'X-Tenant-Slug', 'X-Idempotency-Key'];
|
|
26
|
+
/**
|
|
27
|
+
* Resolve the value of `Access-Control-Allow-Origin` for an incoming request.
|
|
28
|
+
*
|
|
29
|
+
* Matching rules (in order):
|
|
30
|
+
* 1. `allowOrigins` contains `'*'` → return `'*'`
|
|
31
|
+
* 2. `allowOrigins` contains the exact origin → return that origin
|
|
32
|
+
* 3. `allowOrigins` contains a pattern with `*` (e.g. `http://*.localhost:3000`)
|
|
33
|
+
* whose regex matches the request origin → return the request origin
|
|
34
|
+
* 4. otherwise → return `''` (no header emitted)
|
|
35
|
+
*
|
|
36
|
+
* The `*` in a pattern matches one or more non-slash characters so
|
|
37
|
+
* `http://*.localhost:3000` matches `http://tenant.localhost:3000` but NOT
|
|
38
|
+
* `http://localhost:3000` (use two entries for that).
|
|
39
|
+
*/
|
|
40
|
+
export function resolveAllowedOrigin(reqOrigin, allowOrigins) {
|
|
41
|
+
if (!reqOrigin)
|
|
42
|
+
return '';
|
|
43
|
+
if (allowOrigins.includes('*'))
|
|
44
|
+
return '*';
|
|
45
|
+
if (allowOrigins.includes(reqOrigin))
|
|
46
|
+
return reqOrigin;
|
|
47
|
+
for (const pattern of allowOrigins) {
|
|
48
|
+
if (!pattern.includes('*'))
|
|
49
|
+
continue;
|
|
50
|
+
const regexStr = pattern
|
|
51
|
+
.split('*')
|
|
52
|
+
.map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
|
|
53
|
+
.join('[^/]+');
|
|
54
|
+
if (new RegExp(`^${regexStr}$`).test(reqOrigin))
|
|
55
|
+
return reqOrigin;
|
|
56
|
+
}
|
|
57
|
+
return '';
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Build the CORS response headers for the current request.
|
|
61
|
+
*
|
|
62
|
+
* - `isPreflight` controls whether the preflight-only headers (methods,
|
|
63
|
+
* allowed headers, max-age) are included.
|
|
64
|
+
* - When `cors` is `undefined`, defaults to a permissive dev mode: echo the
|
|
65
|
+
* request origin and allow credentials. This keeps `vk dev` working out of
|
|
66
|
+
* the box for browser-based admin apps during local development.
|
|
67
|
+
* - A wildcard `*` + `allowCredentials: true` is downgraded to echoing the
|
|
68
|
+
* request origin, since browsers reject `*` + credentials per the CORS
|
|
69
|
+
* spec.
|
|
70
|
+
*/
|
|
71
|
+
export function buildCorsHeaders(reqOrigin, cors, isPreflight) {
|
|
72
|
+
const effective = cors ?? {
|
|
73
|
+
allowOrigins: reqOrigin ? [reqOrigin] : ['*'],
|
|
74
|
+
allowMethods: DEV_ENDPOINT_CORS_METHODS,
|
|
75
|
+
allowHeaders: DEV_ENDPOINT_CORS_HEADERS,
|
|
76
|
+
allowCredentials: true,
|
|
77
|
+
maxAgeSec: 86400,
|
|
78
|
+
};
|
|
79
|
+
const matched = resolveAllowedOrigin(reqOrigin, effective.allowOrigins);
|
|
80
|
+
// '*' + credentials is rejected by browsers — echo origin instead when we have one.
|
|
81
|
+
const allowedOrigin = matched === '*' && effective.allowCredentials && reqOrigin ? reqOrigin : matched;
|
|
82
|
+
const headers = {};
|
|
83
|
+
if (allowedOrigin) {
|
|
84
|
+
headers['Access-Control-Allow-Origin'] = allowedOrigin;
|
|
85
|
+
// Tell shared caches the response varies by Origin so the wrong origin's
|
|
86
|
+
// headers aren't replayed to a different caller.
|
|
87
|
+
if (allowedOrigin !== '*')
|
|
88
|
+
headers['Vary'] = 'Origin';
|
|
89
|
+
}
|
|
90
|
+
if (effective.allowCredentials && allowedOrigin && allowedOrigin !== '*') {
|
|
91
|
+
headers['Access-Control-Allow-Credentials'] = 'true';
|
|
92
|
+
}
|
|
93
|
+
if (isPreflight) {
|
|
94
|
+
headers['Access-Control-Allow-Methods'] = effective.allowMethods.join(', ');
|
|
95
|
+
headers['Access-Control-Allow-Headers'] = effective.allowHeaders.join(', ');
|
|
96
|
+
headers['Access-Control-Max-Age'] = String(effective.maxAgeSec);
|
|
97
|
+
}
|
|
98
|
+
return headers;
|
|
99
|
+
}
|
|
19
100
|
/**
|
|
20
101
|
* Map file name to HTTP method (same logic as infra/constructs/api.ts)
|
|
21
102
|
*/
|
|
@@ -198,14 +279,15 @@ function buildLambdaEvent(req, body, pathname, search, pathParams, queryParams)
|
|
|
198
279
|
};
|
|
199
280
|
}
|
|
200
281
|
/**
|
|
201
|
-
*
|
|
282
|
+
* Build the HTTP status + headers for a Lambda-shaped result.
|
|
283
|
+
*
|
|
284
|
+
* Exported for unit tests — the end-to-end `writeLambdaResult` below
|
|
285
|
+
* drives `res.writeHead` / `res.end`, but the pure header-assembly
|
|
286
|
+
* logic (including the API Gateway v2 `cookies` → `Set-Cookie`
|
|
287
|
+
* translation) lives here so it can be asserted without spinning up
|
|
288
|
+
* an HTTP server.
|
|
202
289
|
*/
|
|
203
|
-
function
|
|
204
|
-
if (typeof result === 'string') {
|
|
205
|
-
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
|
206
|
-
res.end(result);
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
290
|
+
export function buildLambdaResponseHeaders(result) {
|
|
209
291
|
const statusCode = result.statusCode || 200;
|
|
210
292
|
const headers = {};
|
|
211
293
|
if (result.headers) {
|
|
@@ -217,6 +299,30 @@ function writeLambdaResult(result, res) {
|
|
|
217
299
|
if (!headers['content-type'] && !headers['Content-Type']) {
|
|
218
300
|
headers['Content-Type'] = 'application/json';
|
|
219
301
|
}
|
|
302
|
+
// API Gateway v2 encodes multiple Set-Cookie headers as a dedicated
|
|
303
|
+
// `cookies: string[]` field rather than repeating the header or using
|
|
304
|
+
// the v1 `multiValueHeaders` map. Translate it back into Set-Cookie
|
|
305
|
+
// so browsers see real cookies in `vk dev`. Without this, handlers
|
|
306
|
+
// like `/auth/login` return 200 but no cookies, and every subsequent
|
|
307
|
+
// request gets 401 — a very silent failure mode.
|
|
308
|
+
if (Array.isArray(result.cookies) && result.cookies.length > 0) {
|
|
309
|
+
headers['Set-Cookie'] = result.cookies.map(String);
|
|
310
|
+
}
|
|
311
|
+
return { statusCode, headers };
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Write a Lambda result back to the HTTP response.
|
|
315
|
+
*
|
|
316
|
+
* Supports API Gateway v2's `cookies: string[]` field — see
|
|
317
|
+
* {@link buildLambdaResponseHeaders} for the translation rules.
|
|
318
|
+
*/
|
|
319
|
+
function writeLambdaResult(result, res) {
|
|
320
|
+
if (typeof result === 'string') {
|
|
321
|
+
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
|
322
|
+
res.end(result);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const { statusCode, headers } = buildLambdaResponseHeaders(result);
|
|
220
326
|
res.writeHead(statusCode, headers);
|
|
221
327
|
if (result.body) {
|
|
222
328
|
res.end(result.isBase64Encoded ? Buffer.from(result.body, 'base64') : result.body);
|
|
@@ -262,7 +368,7 @@ export function discoverFunctions(functionsDir) {
|
|
|
262
368
|
* Returns a handle to stop the server.
|
|
263
369
|
*/
|
|
264
370
|
export async function startLocalServer(options) {
|
|
265
|
-
const { routesDir, port, projectName, stage, env, watch = true } = options;
|
|
371
|
+
const { routesDir, port, projectName, stage, env, watch = true, cors } = options;
|
|
266
372
|
// Inject environment variables
|
|
267
373
|
if (env) {
|
|
268
374
|
for (const [key, value] of Object.entries(env)) {
|
|
@@ -384,14 +490,13 @@ export async function startLocalServer(options) {
|
|
|
384
490
|
const parsedUrl = new URL(req.url || '/', `http://localhost:${port}`);
|
|
385
491
|
const pathname = parsedUrl.pathname;
|
|
386
492
|
const method = (req.method || 'GET').toUpperCase();
|
|
493
|
+
const reqOrigin = (typeof req.headers.origin === 'string' ? req.headers.origin : '') || '';
|
|
494
|
+
// Build CORS headers for the current request; `preflight: true` includes
|
|
495
|
+
// the preflight-only headers (methods/allowed headers/max-age).
|
|
496
|
+
const corsHeaders = (preflight = false) => buildCorsHeaders(reqOrigin, cors, preflight);
|
|
387
497
|
// CORS preflight
|
|
388
498
|
if (method === 'OPTIONS') {
|
|
389
|
-
res.writeHead(204,
|
|
390
|
-
'Access-Control-Allow-Origin': '*',
|
|
391
|
-
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
|
|
392
|
-
'Access-Control-Allow-Headers': '*',
|
|
393
|
-
'Access-Control-Max-Age': '86400',
|
|
394
|
-
});
|
|
499
|
+
res.writeHead(204, corsHeaders(true));
|
|
395
500
|
res.end();
|
|
396
501
|
return;
|
|
397
502
|
}
|
|
@@ -404,11 +509,11 @@ export async function startLocalServer(options) {
|
|
|
404
509
|
const body = await readBody(req);
|
|
405
510
|
const payload = body ? JSON.parse(body) : {};
|
|
406
511
|
const msgId = queueProcessor.enqueue(qName, payload);
|
|
407
|
-
res.writeHead(200, { 'Content-Type': 'application/json',
|
|
512
|
+
res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
408
513
|
res.end(JSON.stringify({ messageId: msgId, queue: qName }));
|
|
409
514
|
}
|
|
410
515
|
catch (err) {
|
|
411
|
-
res.writeHead(500, { 'Content-Type': 'application/json',
|
|
516
|
+
res.writeHead(500, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
412
517
|
res.end(JSON.stringify({ error: { code: 'ENQUEUE_ERROR', message: err instanceof Error ? err.message : 'Enqueue failed' } }));
|
|
413
518
|
}
|
|
414
519
|
return;
|
|
@@ -416,14 +521,14 @@ export async function startLocalServer(options) {
|
|
|
416
521
|
// --- Dev endpoint: /_dev/queues ---
|
|
417
522
|
// List queue stats
|
|
418
523
|
if (pathname === '/_dev/queues' && method === 'GET') {
|
|
419
|
-
res.writeHead(200, { 'Content-Type': 'application/json',
|
|
524
|
+
res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
420
525
|
res.end(JSON.stringify({ queues: queueProcessor.getStats(), dlq: queueProcessor.getDlq() }));
|
|
421
526
|
return;
|
|
422
527
|
}
|
|
423
528
|
// --- Dev endpoint: /_dev/crons ---
|
|
424
529
|
// List cron job status
|
|
425
530
|
if (pathname === '/_dev/crons' && method === 'GET') {
|
|
426
|
-
res.writeHead(200, { 'Content-Type': 'application/json',
|
|
531
|
+
res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
427
532
|
res.end(JSON.stringify({ crons: cronScheduler.getStatus() }));
|
|
428
533
|
return;
|
|
429
534
|
}
|
|
@@ -477,7 +582,7 @@ export async function startLocalServer(options) {
|
|
|
477
582
|
chalk.gray(' → ') +
|
|
478
583
|
chalk.green('OK') +
|
|
479
584
|
chalk.gray(` (${duration}ms)`));
|
|
480
|
-
res.writeHead(200, { 'Content-Type': 'application/json',
|
|
585
|
+
res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
481
586
|
res.end(JSON.stringify(result ?? { ok: true }));
|
|
482
587
|
}
|
|
483
588
|
catch (err) {
|
|
@@ -488,7 +593,7 @@ export async function startLocalServer(options) {
|
|
|
488
593
|
chalk.red('ERROR') +
|
|
489
594
|
chalk.gray(` (${duration}ms)`));
|
|
490
595
|
console.error(chalk.red(` ${err instanceof Error ? err.message : err}`));
|
|
491
|
-
res.writeHead(500, { 'Content-Type': 'application/json',
|
|
596
|
+
res.writeHead(500, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
492
597
|
res.end(JSON.stringify({ error: { code: 'FUNCTION_ERROR', message: err instanceof Error ? err.message : 'Function error' } }));
|
|
493
598
|
}
|
|
494
599
|
return;
|
|
@@ -564,7 +669,7 @@ export async function startLocalServer(options) {
|
|
|
564
669
|
chalk.gray(' → ') +
|
|
565
670
|
chalk.green('OK') +
|
|
566
671
|
chalk.gray(` (${duration}ms)`));
|
|
567
|
-
res.writeHead(200, { 'Content-Type': 'application/json',
|
|
672
|
+
res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
568
673
|
res.end(JSON.stringify(result ?? { ok: true }));
|
|
569
674
|
}
|
|
570
675
|
catch (err) {
|
|
@@ -575,7 +680,7 @@ export async function startLocalServer(options) {
|
|
|
575
680
|
chalk.red('ERROR') +
|
|
576
681
|
chalk.gray(` (${duration}ms)`));
|
|
577
682
|
console.error(chalk.red(` ${err instanceof Error ? err.message : err}`));
|
|
578
|
-
res.writeHead(500, { 'Content-Type': 'application/json',
|
|
683
|
+
res.writeHead(500, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
579
684
|
res.end(JSON.stringify({ error: { code: 'QUEUE_HANDLER_ERROR', message: err instanceof Error ? err.message : 'Queue handler error' } }));
|
|
580
685
|
}
|
|
581
686
|
return;
|
|
@@ -637,7 +742,7 @@ export async function startLocalServer(options) {
|
|
|
637
742
|
chalk.gray(' → ') +
|
|
638
743
|
chalk.green('OK') +
|
|
639
744
|
chalk.gray(` (${duration}ms)`));
|
|
640
|
-
res.writeHead(200, { 'Content-Type': 'application/json',
|
|
745
|
+
res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
641
746
|
res.end(JSON.stringify(result ?? { ok: true }));
|
|
642
747
|
}
|
|
643
748
|
catch (err) {
|
|
@@ -648,7 +753,7 @@ export async function startLocalServer(options) {
|
|
|
648
753
|
chalk.red('ERROR') +
|
|
649
754
|
chalk.gray(` (${duration}ms)`));
|
|
650
755
|
console.error(chalk.red(` ${err instanceof Error ? err.message : err}`));
|
|
651
|
-
res.writeHead(500, { 'Content-Type': 'application/json',
|
|
756
|
+
res.writeHead(500, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
652
757
|
res.end(JSON.stringify({ error: { code: 'CRON_HANDLER_ERROR', message: err instanceof Error ? err.message : 'Cron handler error' } }));
|
|
653
758
|
}
|
|
654
759
|
return;
|
|
@@ -656,7 +761,7 @@ export async function startLocalServer(options) {
|
|
|
656
761
|
// --- Dev endpoint: /_dev/functions ---
|
|
657
762
|
// Lists all discovered functions, queues, and crons for debugging
|
|
658
763
|
if (pathname === '/_dev/functions' && method === 'GET') {
|
|
659
|
-
res.writeHead(200, { 'Content-Type': 'application/json',
|
|
764
|
+
res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders() });
|
|
660
765
|
res.end(JSON.stringify({
|
|
661
766
|
functions: functions.map(f => ({ name: f.name, handler: f.handlerFile })),
|
|
662
767
|
queues: queues.map(q => ({ name: q.name, handler: q.handlerFile })),
|
|
@@ -708,9 +813,12 @@ export async function startLocalServer(options) {
|
|
|
708
813
|
// Invoke handler
|
|
709
814
|
const result = await handlerFn(event, context);
|
|
710
815
|
const duration = Date.now() - start;
|
|
711
|
-
//
|
|
816
|
+
// Merge CORS headers into the response. Handler-set headers win (so
|
|
817
|
+
// routes that explicitly configure CORS via `corsMiddleware` keep
|
|
818
|
+
// their exact values); dev-server headers fill any gaps so browser
|
|
819
|
+
// credentialed requests succeed out of the box.
|
|
712
820
|
if (typeof result === 'object' && result !== null) {
|
|
713
|
-
result.headers = { ...result.headers
|
|
821
|
+
result.headers = { ...corsHeaders(), ...result.headers };
|
|
714
822
|
}
|
|
715
823
|
writeLambdaResult(result, res);
|
|
716
824
|
const statusCode = typeof result === 'object' ? result.statusCode : 200;
|