@getstrata/core 2.2.56 → 2.2.58

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @getstrata/core changelog
2
2
 
3
+ ## 2.2.58
4
+
5
+ PostgreSQL runtime privilege fix: Replace broad table/sequence grants with explicit CRUD and sequence usage/read permissions. Repair legacy helper-managed grants that allowed TRUNCATE across RLS tenant boundaries. Preserve provisioning locks and transactional rollback. Resolves #364 through #370.
6
+ UUID schema columns: Add table.uuid() with PostgreSQL native UUID, MySQL CHAR(36) and SQLite TEXT. Supports explicit constraints and application-supplied identifiers; existing schemas remain unchanged. #365
7
+ Model and view generators: Add make:model for declarative models with automatic repositories, and make:view for escaped Eta templates. Support nested names and explicit model metadata, with path validation and overwrite protection. Migrations remain explicit and separate. #368
8
+ Repeated form values: Add opt-in { preserveRepeated: true } parsing through core form helpers and WebFormRequest, retaining repeated text and files in order. Existing parsing defaults remain unchanged; applications retain responsibility for duplicate validation. #366
9
+ Mail extension documentation and coverage: Qualify existing injected MailDriver integrations, including HTTPS providers, cancellation, deadlines, error propagation and provider-controlled idempotency. This adds tests and guidance without changing stock mail transports. #367
10
+
11
+ ## 2.2.57
12
+
13
+ Add opt-in CsrfOptions.targetOrigin with strict request Host/URL authority and source-origin validation while retaining signed cookie/token checks and existing defaults. Preserve native Request identity and ignore forwarding claims. Fall back safely to JSON error formatting for malformed native URL metadata.
14
+
3
15
  ## 2.2.56
4
16
 
5
17
  - Stop adding schema CREATE to PostgreSQL runtime roles; keep USAGE, existing object/default grants and both catalog/ACL concurrency protocols. Existing grants, PUBLIC privileges, memberships and ownership are not revoked automatically; restricted deployments can use the documented public schema-only migration runner.
@@ -33,6 +33,8 @@ declare class Blueprint {
33
33
  /** Generated 64-bit primary key; does not change existing id() migrations. */
34
34
  bigId(name?: string): ColumnDefinition;
35
35
  string(name: string, length?: number): ColumnDefinition;
36
+ /** Application-supplied UUID: native PostgreSQL UUID, MySQL CHAR(36), SQLite TEXT. */
37
+ uuid(name: string): ColumnDefinition;
36
38
  text(name: string): ColumnDefinition;
37
39
  boolean(name: string): ColumnDefinition;
38
40
  integer(name: string): ColumnDefinition;
@@ -1,4 +1,4 @@
1
- type ColumnKind = "id" | "bigId" | "string" | "text" | "boolean" | "integer" | "bigInteger" | "timestamp" | "json" | "jsonb" | "foreignId";
1
+ type ColumnKind = "id" | "bigId" | "uuid" | "string" | "text" | "boolean" | "integer" | "bigInteger" | "timestamp" | "json" | "jsonb" | "foreignId";
2
2
  interface ForeignKeyOptions {
3
3
  referencesTable: string;
4
4
  referencesColumn: string;
@@ -1,3 +1,8 @@
1
1
  import type { Middleware } from "./middleware";
2
- declare function createCsrfMiddleware(): Middleware;
2
+ interface CsrfOptions {
3
+ /** Explicit public origin for TLS offload; requires matching URL authority and Host on every request. */
4
+ targetOrigin?: string;
5
+ }
6
+ declare function createCsrfMiddleware(options?: CsrfOptions): Middleware;
7
+ export type { CsrfOptions };
3
8
  export { createCsrfMiddleware };
@@ -0,0 +1,6 @@
1
+ /** Explicit target policy only. Forwarding headers never select an origin or approve a host. */
2
+ declare function createCsrfOriginPolicy(value: unknown): {
3
+ acceptsSourceOrigin(source: string | null): boolean;
4
+ assertHost(request: Request): void;
5
+ };
6
+ export { createCsrfOriginPolicy };
@@ -1,6 +1,28 @@
1
- interface FormDataLike {
2
- entries(): Iterable<[string, unknown]>;
1
+ interface FormDataLike<T = unknown> {
2
+ entries(): Iterable<[string, T]>;
3
3
  }
4
- declare function parseFormBody(request: Request): Promise<Record<string, string>>;
5
- declare function formDataToRecord(formData: FormDataLike): Record<string, string>;
4
+ interface FormBodyOptions {
5
+ /** Preserve every entry as an array, including single text fields and File entries. */
6
+ preserveRepeated?: boolean;
7
+ }
8
+ type PreservedFormValues = Record<string, (string | File)[]>;
9
+ declare function parseFormBody(request: Request, options: {
10
+ preserveRepeated: true;
11
+ }): Promise<PreservedFormValues>;
12
+ declare function parseFormBody(request: Request, options?: {
13
+ preserveRepeated?: false;
14
+ }): Promise<Record<string, string>>;
15
+ declare function parseFormBody(request: Request, options: FormBodyOptions): Promise<Record<string, string> | PreservedFormValues>;
16
+ declare function formDataToRecord(formData: FormData, options: {
17
+ preserveRepeated: true;
18
+ }): PreservedFormValues;
19
+ declare function formDataToRecord<T>(formData: FormDataLike<T>, options: {
20
+ preserveRepeated: true;
21
+ }): Record<string, T[]>;
22
+ declare function formDataToRecord(formData: FormDataLike, options?: {
23
+ preserveRepeated?: false;
24
+ }): Record<string, string>;
25
+ declare function formDataToRecord(formData: FormData, options: FormBodyOptions): Record<string, string> | PreservedFormValues;
26
+ declare function formDataToRecord<T>(formData: FormDataLike<T>, options: FormBodyOptions): Record<string, string> | Record<string, T[]>;
27
+ export type { FormBodyOptions, PreservedFormValues };
6
28
  export { formDataToRecord, parseFormBody };
@@ -1,4 +1,7 @@
1
+ import { type FormBodyOptions } from "./parseFormBody";
1
2
  declare abstract class WebFormRequest<TOutput> {
3
+ #private;
4
+ constructor(options?: FormBodyOptions);
2
5
  authorize(_request: Request): boolean | Promise<boolean>;
3
6
  protected abstract parse(payload: unknown): TOutput;
4
7
  validatePayload(payload: unknown): TOutput;
@@ -10,7 +10,7 @@
10
10
  * existing volumes get the role and table GRANTs after migrate:fresh. Production
11
11
  * runtime processes only connect through the already-provisioned restricted role.
12
12
  *
13
- * Admin DDL (GRANT ALL TABLES, CREATE TABLE, DROP TABLE) must run on the
13
+ * Admin DDL (table grants, CREATE TABLE, DROP TABLE) must run on the
14
14
  * application database. postgres/template1 are only for CREATE DATABASE.
15
15
  */
16
16
  declare const POSTGRES_APP_ROLE = "strata_app";
@@ -365,6 +365,12 @@ class Blueprint {
365
365
  this.columns.push(column);
366
366
  return column;
367
367
  }
368
+ uuid(name) {
369
+ const column = new ColumnDefinition(name, "uuid");
370
+ column.notNullable();
371
+ this.columns.push(column);
372
+ return column;
373
+ }
368
374
  text(name) {
369
375
  const column = new ColumnDefinition(name, "text");
370
376
  column.notNullable();
@@ -507,6 +513,10 @@ function compileColumnType(driver, column) {
507
513
  return compileIdType(driver);
508
514
  case "string":
509
515
  return compileStringType(driver, column.length);
516
+ case "uuid":
517
+ if (column.autoIncrement)
518
+ throw new UnsupportedSchemaFeatureError("auto-increment UUID columns", driver);
519
+ return driver === "pgsql" ? "UUID" : driver === "mysql" ? "CHAR(36)" : "TEXT";
510
520
  case "text":
511
521
  return compileTextType(driver);
512
522
  case "boolean":
@@ -357,6 +357,12 @@ class Blueprint {
357
357
  this.columns.push(column);
358
358
  return column;
359
359
  }
360
+ uuid(name) {
361
+ const column = new ColumnDefinition(name, "uuid");
362
+ column.notNullable();
363
+ this.columns.push(column);
364
+ return column;
365
+ }
360
366
  text(name) {
361
367
  const column = new ColumnDefinition(name, "text");
362
368
  column.notNullable();
@@ -499,6 +505,10 @@ function compileColumnType(driver, column) {
499
505
  return compileIdType(driver);
500
506
  case "string":
501
507
  return compileStringType(driver, column.length);
508
+ case "uuid":
509
+ if (column.autoIncrement)
510
+ throw new UnsupportedSchemaFeatureError("auto-increment UUID columns", driver);
511
+ return driver === "pgsql" ? "UUID" : driver === "mysql" ? "CHAR(36)" : "TEXT";
502
512
  case "text":
503
513
  return compileTextType(driver);
504
514
  case "boolean":
@@ -4,10 +4,15 @@ function requestPrefersJson(request) {
4
4
  if (!request) {
5
5
  return true;
6
6
  }
7
+ let pathname;
8
+ try {
9
+ pathname = new URL(request.url).pathname;
10
+ } catch {
11
+ return true;
12
+ }
7
13
  if (request.headers.get("HX-Request") === "true") {
8
14
  return false;
9
15
  }
10
- const pathname = new URL(request.url).pathname;
11
16
  if (pathname.startsWith("/api/")) {
12
17
  return true;
13
18
  }
@@ -28,9 +28,58 @@ var init_asyncContextStore = () => {};
28
28
 
29
29
  // ../../src/core/http/csrfMiddleware.ts
30
30
  import { currentAuthUser, currentCredentialSource } from "@getstrata/core/auth/authContext";
31
- import { ForbiddenError } from "@getstrata/core/errors/http";
31
+ import { ForbiddenError as ForbiddenError2 } from "@getstrata/core/errors/http";
32
32
  import { envFlagEnabled as envFlagEnabled2, isProductionEnv as isProductionEnv2 } from "@getstrata/core/runtime/appEnv";
33
33
 
34
+ // ../../src/core/http/csrfOriginPolicy.ts
35
+ import { isIP } from "net";
36
+ import { ForbiddenError } from "@getstrata/core/errors/http";
37
+ function parseAuthority(authority, protocol) {
38
+ if (!authority || authority.endsWith(":") || /[\s\\/@?#%,*]/.test(authority))
39
+ return null;
40
+ try {
41
+ const url = new URL(`${protocol}//${authority}`);
42
+ const hostname = url.hostname.replace(/\.$/, "");
43
+ const ip = hostname.startsWith("[") ? hostname.slice(1, -1) : hostname;
44
+ if (!isIP(ip) && (hostname.length > 253 || !hostname.split(".").every((label) => label.length > 0 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label))))
45
+ return null;
46
+ return url.host;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ function parseOrigin(value, allowRootPath) {
52
+ if (typeof value !== "string" || value !== value.trim())
53
+ return null;
54
+ const match = /^(https?):\/\/([^/?#]+)(\/?)$/i.exec(value);
55
+ if (!match || !allowRootPath && match[3])
56
+ return null;
57
+ const protocol = `${match[1]?.toLowerCase()}:`;
58
+ const host = parseAuthority(match[2] ?? null, protocol);
59
+ return host ? `${protocol}//${host}` : null;
60
+ }
61
+ function createCsrfOriginPolicy(value) {
62
+ const origin = parseOrigin(value, true);
63
+ if (!origin)
64
+ throw new TypeError("CSRF targetOrigin must be a single HTTP(S) origin without credentials, path, query, fragment or wildcard.");
65
+ const target = new URL(origin);
66
+ return {
67
+ acceptsSourceOrigin(source) {
68
+ return parseOrigin(source, false) === origin;
69
+ },
70
+ assertHost(request) {
71
+ let url;
72
+ try {
73
+ url = new URL(request.url);
74
+ } catch {
75
+ throw new ForbiddenError("Unrecognized request host.");
76
+ }
77
+ if (!/^https?:$/.test(url.protocol) || url.username || url.password || parseAuthority(url.host, target.protocol) !== target.host || parseAuthority(request.headers.get("host"), target.protocol) !== target.host)
78
+ throw new ForbiddenError("Unrecognized request host.");
79
+ }
80
+ };
81
+ }
82
+
34
83
  // ../../src/core/http/csrfToken.ts
35
84
  import { timingSafeEqual } from "crypto";
36
85
 
@@ -272,8 +321,11 @@ function appendSetCookie(response, cookie) {
272
321
  headers
273
322
  });
274
323
  }
275
- function createCsrfMiddleware() {
324
+ function createCsrfMiddleware(options = {}) {
325
+ const targetOrigin = options.targetOrigin;
326
+ const policy = targetOrigin === undefined ? undefined : createCsrfOriginPolicy(targetOrigin);
276
327
  return async (request, next) => {
328
+ policy?.assertHost(request);
277
329
  const credentialSource = currentCredentialSource();
278
330
  const developmentHeaderProof = credentialSource === "guest" && currentAuthUser() !== null && envFlagEnabled2(process.env.AUTH_DEV_HEADERS) && !isProductionEnv2();
279
331
  if (credentialSource === "bearer" || credentialSource === "basic" || developmentHeaderProof) {
@@ -296,19 +348,19 @@ function createCsrfMiddleware() {
296
348
  }
297
349
  const submitted = await readSubmittedCsrfTokenFromBody(request);
298
350
  if (!verifyCsrfToken(request, submitted)) {
299
- throw new ForbiddenError("Invalid or missing CSRF token.");
351
+ throw new ForbiddenError2("Invalid or missing CSRF token.");
300
352
  }
301
353
  const originHeader = request.headers.get("origin");
302
354
  let headerOrigin = null;
303
- if (originHeader) {
355
+ if (!policy && originHeader) {
304
356
  try {
305
357
  headerOrigin = new URL(originHeader).origin;
306
358
  } catch {
307
359
  headerOrigin = null;
308
360
  }
309
361
  }
310
- if (!headerOrigin || headerOrigin !== new URL(request.url).origin) {
311
- throw new ForbiddenError("Cross-site cookie requests are not allowed.");
362
+ if (policy ? !policy.acceptsSourceOrigin(originHeader) : !headerOrigin || headerOrigin !== new URL(request.url).origin) {
363
+ throw new ForbiddenError2("Cross-site cookie requests are not allowed.");
312
364
  }
313
365
  return await next();
314
366
  };
@@ -419,10 +419,15 @@ function requestPrefersJson(request) {
419
419
  if (!request) {
420
420
  return true;
421
421
  }
422
+ let pathname;
423
+ try {
424
+ pathname = new URL(request.url).pathname;
425
+ } catch {
426
+ return true;
427
+ }
422
428
  if (request.headers.get("HX-Request") === "true") {
423
429
  return false;
424
430
  }
425
- const pathname = new URL(request.url).pathname;
426
431
  if (pathname.startsWith("/api/")) {
427
432
  return true;
428
433
  }
@@ -1,14 +1,25 @@
1
1
  // @bun
2
2
  // ../../src/core/http/parseFormBody.ts
3
3
  import { BadRequestError } from "@getstrata/core/errors/http";
4
- async function parseFormBody(request) {
4
+ async function parseFormBody(request, options = {}) {
5
5
  const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
6
6
  if (!contentType.includes("application/x-www-form-urlencoded") && !contentType.includes("multipart/form-data")) {
7
7
  throw new BadRequestError("Expected a form submission.");
8
8
  }
9
- return formDataToRecord(await request.formData());
9
+ return formDataToRecord(await request.formData(), options);
10
10
  }
11
- function formDataToRecord(formData) {
11
+ function formDataToRecord(formData, options = {}) {
12
+ if (options.preserveRepeated === true) {
13
+ const values = new Map;
14
+ for (const [key, value] of formData.entries()) {
15
+ const entries = values.get(key);
16
+ if (entries)
17
+ entries.push(value);
18
+ else
19
+ values.set(key, [value]);
20
+ }
21
+ return Object.fromEntries(values);
22
+ }
12
23
  const values = {};
13
24
  for (const [key, value] of formData.entries()) {
14
25
  if (typeof value === "string") {
@@ -54,10 +54,15 @@ function requestPrefersJson(request) {
54
54
  if (!request) {
55
55
  return true;
56
56
  }
57
+ let pathname;
58
+ try {
59
+ pathname = new URL(request.url).pathname;
60
+ } catch {
61
+ return true;
62
+ }
57
63
  if (request.headers.get("HX-Request") === "true") {
58
64
  return false;
59
65
  }
60
- const pathname = new URL(request.url).pathname;
61
66
  if (pathname.startsWith("/api/")) {
62
67
  return true;
63
68
  }
@@ -38,10 +38,15 @@ function requestPrefersJson(request) {
38
38
  if (!request) {
39
39
  return true;
40
40
  }
41
+ let pathname;
42
+ try {
43
+ pathname = new URL(request.url).pathname;
44
+ } catch {
45
+ return true;
46
+ }
41
47
  if (request.headers.get("HX-Request") === "true") {
42
48
  return false;
43
49
  }
44
- const pathname = new URL(request.url).pathname;
45
50
  if (pathname.startsWith("/api/")) {
46
51
  return true;
47
52
  }
@@ -14,10 +14,15 @@ function requestPrefersJson(request) {
14
14
  if (!request) {
15
15
  return true;
16
16
  }
17
+ let pathname;
18
+ try {
19
+ pathname = new URL(request.url).pathname;
20
+ } catch {
21
+ return true;
22
+ }
17
23
  if (request.headers.get("HX-Request") === "true") {
18
24
  return false;
19
25
  }
20
- const pathname = new URL(request.url).pathname;
21
26
  if (pathname.startsWith("/api/")) {
22
27
  return true;
23
28
  }
@@ -9,10 +9,15 @@ function requestPrefersJson(request) {
9
9
  if (!request) {
10
10
  return true;
11
11
  }
12
+ let pathname;
13
+ try {
14
+ pathname = new URL(request.url).pathname;
15
+ } catch {
16
+ return true;
17
+ }
12
18
  if (request.headers.get("HX-Request") === "true") {
13
19
  return false;
14
20
  }
15
- const pathname = new URL(request.url).pathname;
16
21
  if (pathname.startsWith("/api/")) {
17
22
  return true;
18
23
  }
@@ -473,10 +473,15 @@ function requestPrefersJson(request) {
473
473
  if (!request) {
474
474
  return true;
475
475
  }
476
+ let pathname;
477
+ try {
478
+ pathname = new URL(request.url).pathname;
479
+ } catch {
480
+ return true;
481
+ }
476
482
  if (request.headers.get("HX-Request") === "true") {
477
483
  return false;
478
484
  }
479
- const pathname = new URL(request.url).pathname;
480
485
  if (pathname.startsWith("/api/")) {
481
486
  return true;
482
487
  }
@@ -358,10 +358,15 @@ function requestPrefersJson(request) {
358
358
  if (!request) {
359
359
  return true;
360
360
  }
361
+ let pathname;
362
+ try {
363
+ pathname = new URL(request.url).pathname;
364
+ } catch {
365
+ return true;
366
+ }
361
367
  if (request.headers.get("HX-Request") === "true") {
362
368
  return false;
363
369
  }
364
- const pathname = new URL(request.url).pathname;
365
370
  if (pathname.startsWith("/api/")) {
366
371
  return true;
367
372
  }
@@ -7,10 +7,15 @@ function requestPrefersJson(request) {
7
7
  if (!request) {
8
8
  return true;
9
9
  }
10
+ let pathname;
11
+ try {
12
+ pathname = new URL(request.url).pathname;
13
+ } catch {
14
+ return true;
15
+ }
10
16
  if (request.headers.get("HX-Request") === "true") {
11
17
  return false;
12
18
  }
13
- const pathname = new URL(request.url).pathname;
14
19
  if (pathname.startsWith("/api/")) {
15
20
  return true;
16
21
  }
@@ -30,14 +35,25 @@ function requestPrefersJson(request) {
30
35
 
31
36
  // ../../src/core/http/parseFormBody.ts
32
37
  import { BadRequestError } from "@getstrata/core/errors/http";
33
- async function parseFormBody(request) {
38
+ async function parseFormBody(request, options = {}) {
34
39
  const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
35
40
  if (!contentType.includes("application/x-www-form-urlencoded") && !contentType.includes("multipart/form-data")) {
36
41
  throw new BadRequestError("Expected a form submission.");
37
42
  }
38
- return formDataToRecord(await request.formData());
39
- }
40
- function formDataToRecord(formData) {
43
+ return formDataToRecord(await request.formData(), options);
44
+ }
45
+ function formDataToRecord(formData, options = {}) {
46
+ if (options.preserveRepeated === true) {
47
+ const values = new Map;
48
+ for (const [key, value] of formData.entries()) {
49
+ const entries = values.get(key);
50
+ if (entries)
51
+ entries.push(value);
52
+ else
53
+ values.set(key, [value]);
54
+ }
55
+ return Object.fromEntries(values);
56
+ }
41
57
  const values = {};
42
58
  for (const [key, value] of formData.entries()) {
43
59
  if (typeof value === "string") {
@@ -178,6 +194,10 @@ function parsePositiveIntParam(value, name = "id") {
178
194
 
179
195
  // ../../src/core/http/webFormRequest.ts
180
196
  class WebFormRequest {
197
+ #preserveRepeated;
198
+ constructor(options = {}) {
199
+ this.#preserveRepeated = options.preserveRepeated === true;
200
+ }
181
201
  authorize(_request) {
182
202
  return true;
183
203
  }
@@ -188,7 +208,7 @@ class WebFormRequest {
188
208
  if (!await this.authorize(request)) {
189
209
  throw new ForbiddenError;
190
210
  }
191
- const payload = requestPrefersJson(request) ? await parseJsonBody(request, (body) => body) : await parseFormBody(request);
211
+ const payload = requestPrefersJson(request) ? await parseJsonBody(request, (body) => body) : await parseFormBody(request, { preserveRepeated: this.#preserveRepeated });
192
212
  try {
193
213
  return this.validatePayload(payload);
194
214
  } catch (error) {
@@ -197,11 +197,15 @@ function postgresAppRolePrivilegeSql(options) {
197
197
  const role = assertSafeSqlIdentifier(options.role ?? POSTGRES_APP_ROLE, "role name");
198
198
  return `GRANT CONNECT ON DATABASE ${database} TO ${role};
199
199
  GRANT USAGE ON SCHEMA public TO ${role};
200
- GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO ${role};
201
- GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO ${role};
200
+ REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM ${role};
201
+ GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${role};
202
+ REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM ${role};
203
+ GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO ${role};
202
204
  GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO ${role};
203
- ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO ${role};
204
- ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO ${role};
205
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON TABLES FROM ${role};
206
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${role};
207
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON SEQUENCES FROM ${role};
208
+ ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO ${role};
205
209
  ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT EXECUTE ON FUNCTIONS TO ${role};
206
210
  `;
207
211
  }
@@ -87,7 +87,7 @@ export type { ContentSecurityPolicyDirectives, ContentSecurityPolicyOptions, } f
87
87
  export { configureContentSecurityPolicy, generateCspNonce, HTMX_2_0_4_INDICATOR_STYLE_HASH, resetContentSecurityPolicyForTests, resolveContentSecurityPolicy, resolveHtmlContentSecurityPolicy, serverHtmxContentSecurityPolicy, spaContentSecurityPolicy, strictApiContentSecurityPolicy, } from "../core/http/contentSecurityPolicy.ts";
88
88
  export { readBunRequestCookie, readRequestCookie } from "../core/http/cookies.ts";
89
89
  export { type CorsConfig, type CorsOptions, createCorsMiddleware, } from "../core/http/corsMiddleware.ts";
90
- export { createCsrfMiddleware } from "../core/http/csrfMiddleware.ts";
90
+ export { type CsrfOptions, createCsrfMiddleware } from "../core/http/csrfMiddleware.ts";
91
91
  export { createCsrfProtection } from "../core/http/csrfProtection.ts";
92
92
  export { createCsrfTokenCookie, readSubmittedCsrfToken, readSubmittedCsrfTokenFromBody, resolveCsrfToken, resolveCsrfTokenForRequest, verifyCsrfToken, } from "../core/http/csrfToken.ts";
93
93
  export { applyConditionalGet, assertIfMatch, computeEtagFromJson, type EtagVersioned, etagFromResource, etagValuesMatch, ifMatchSatisfied, ifNoneMatchSatisfied, isEtagEnabled, notModifiedResponse, } from "../core/http/etag.ts";
package/dist/index.js CHANGED
@@ -6990,6 +6990,12 @@ class Blueprint {
6990
6990
  this.columns.push(column);
6991
6991
  return column;
6992
6992
  }
6993
+ uuid(name) {
6994
+ const column = new ColumnDefinition(name, "uuid");
6995
+ column.notNullable();
6996
+ this.columns.push(column);
6997
+ return column;
6998
+ }
6993
6999
  text(name) {
6994
7000
  const column = new ColumnDefinition(name, "text");
6995
7001
  column.notNullable();
@@ -7132,6 +7138,10 @@ function compileColumnType(driver, column) {
7132
7138
  return compileIdType(driver);
7133
7139
  case "string":
7134
7140
  return compileStringType(driver, column.length);
7141
+ case "uuid":
7142
+ if (column.autoIncrement)
7143
+ throw new UnsupportedSchemaFeatureError("auto-increment UUID columns", driver);
7144
+ return driver === "pgsql" ? "UUID" : driver === "mysql" ? "CHAR(36)" : "TEXT";
7135
7145
  case "text":
7136
7146
  return compileTextType(driver);
7137
7147
  case "boolean":
@@ -12046,10 +12056,15 @@ function requestPrefersJson(request) {
12046
12056
  if (!request) {
12047
12057
  return true;
12048
12058
  }
12059
+ let pathname;
12060
+ try {
12061
+ pathname = new URL(request.url).pathname;
12062
+ } catch {
12063
+ return true;
12064
+ }
12049
12065
  if (request.headers.get("HX-Request") === "true") {
12050
12066
  return false;
12051
12067
  }
12052
- const pathname = new URL(request.url).pathname;
12053
12068
  if (pathname.startsWith("/api/")) {
12054
12069
  return true;
12055
12070
  }
@@ -12640,6 +12655,54 @@ function buildCorsHeaders(request, options) {
12640
12655
  }
12641
12656
  return headers;
12642
12657
  }
12658
+ // ../../src/core/http/csrfOriginPolicy.ts
12659
+ import { isIP } from "net";
12660
+ function parseAuthority(authority, protocol) {
12661
+ if (!authority || authority.endsWith(":") || /[\s\\/@?#%,*]/.test(authority))
12662
+ return null;
12663
+ try {
12664
+ const url = new URL(`${protocol}//${authority}`);
12665
+ const hostname = url.hostname.replace(/\.$/, "");
12666
+ const ip = hostname.startsWith("[") ? hostname.slice(1, -1) : hostname;
12667
+ if (!isIP(ip) && (hostname.length > 253 || !hostname.split(".").every((label) => label.length > 0 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label))))
12668
+ return null;
12669
+ return url.host;
12670
+ } catch {
12671
+ return null;
12672
+ }
12673
+ }
12674
+ function parseOrigin(value, allowRootPath) {
12675
+ if (typeof value !== "string" || value !== value.trim())
12676
+ return null;
12677
+ const match = /^(https?):\/\/([^/?#]+)(\/?)$/i.exec(value);
12678
+ if (!match || !allowRootPath && match[3])
12679
+ return null;
12680
+ const protocol = `${match[1]?.toLowerCase()}:`;
12681
+ const host = parseAuthority(match[2] ?? null, protocol);
12682
+ return host ? `${protocol}//${host}` : null;
12683
+ }
12684
+ function createCsrfOriginPolicy(value) {
12685
+ const origin = parseOrigin(value, true);
12686
+ if (!origin)
12687
+ throw new TypeError("CSRF targetOrigin must be a single HTTP(S) origin without credentials, path, query, fragment or wildcard.");
12688
+ const target = new URL(origin);
12689
+ return {
12690
+ acceptsSourceOrigin(source) {
12691
+ return parseOrigin(source, false) === origin;
12692
+ },
12693
+ assertHost(request) {
12694
+ let url;
12695
+ try {
12696
+ url = new URL(request.url);
12697
+ } catch {
12698
+ throw new ForbiddenError("Unrecognized request host.");
12699
+ }
12700
+ if (!/^https?:$/.test(url.protocol) || url.username || url.password || parseAuthority(url.host, target.protocol) !== target.host || parseAuthority(request.headers.get("host"), target.protocol) !== target.host)
12701
+ throw new ForbiddenError("Unrecognized request host.");
12702
+ }
12703
+ };
12704
+ }
12705
+
12643
12706
  // ../../src/core/http/csrfToken.ts
12644
12707
  import { timingSafeEqual as timingSafeEqual3 } from "crypto";
12645
12708
  var CSRF_COOKIE = appCookieName("csrf");
@@ -12748,8 +12811,11 @@ function appendSetCookie(response, cookie) {
12748
12811
  headers
12749
12812
  });
12750
12813
  }
12751
- function createCsrfMiddleware() {
12814
+ function createCsrfMiddleware(options = {}) {
12815
+ const targetOrigin = options.targetOrigin;
12816
+ const policy = targetOrigin === undefined ? undefined : createCsrfOriginPolicy(targetOrigin);
12752
12817
  return async (request, next) => {
12818
+ policy?.assertHost(request);
12753
12819
  const credentialSource = currentCredentialSource();
12754
12820
  const developmentHeaderProof = credentialSource === "guest" && currentAuthUser() !== null && envFlagEnabled(process.env.AUTH_DEV_HEADERS) && !isProductionEnv();
12755
12821
  if (credentialSource === "bearer" || credentialSource === "basic" || developmentHeaderProof) {
@@ -12776,14 +12842,14 @@ function createCsrfMiddleware() {
12776
12842
  }
12777
12843
  const originHeader = request.headers.get("origin");
12778
12844
  let headerOrigin = null;
12779
- if (originHeader) {
12845
+ if (!policy && originHeader) {
12780
12846
  try {
12781
12847
  headerOrigin = new URL(originHeader).origin;
12782
12848
  } catch {
12783
12849
  headerOrigin = null;
12784
12850
  }
12785
12851
  }
12786
- if (!headerOrigin || headerOrigin !== new URL(request.url).origin) {
12852
+ if (policy ? !policy.acceptsSourceOrigin(originHeader) : !headerOrigin || headerOrigin !== new URL(request.url).origin) {
12787
12853
  throw new ForbiddenError("Cross-site cookie requests are not allowed.");
12788
12854
  }
12789
12855
  return await next();
@@ -14237,14 +14303,25 @@ function createValidateSignatureMiddleware() {
14237
14303
  };
14238
14304
  }
14239
14305
  // ../../src/core/http/parseFormBody.ts
14240
- async function parseFormBody(request) {
14306
+ async function parseFormBody(request, options = {}) {
14241
14307
  const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
14242
14308
  if (!contentType.includes("application/x-www-form-urlencoded") && !contentType.includes("multipart/form-data")) {
14243
14309
  throw new BadRequestError("Expected a form submission.");
14244
14310
  }
14245
- return formDataToRecord(await request.formData());
14311
+ return formDataToRecord(await request.formData(), options);
14246
14312
  }
14247
- function formDataToRecord(formData) {
14313
+ function formDataToRecord(formData, options = {}) {
14314
+ if (options.preserveRepeated === true) {
14315
+ const values = new Map;
14316
+ for (const [key, value] of formData.entries()) {
14317
+ const entries = values.get(key);
14318
+ if (entries)
14319
+ entries.push(value);
14320
+ else
14321
+ values.set(key, [value]);
14322
+ }
14323
+ return Object.fromEntries(values);
14324
+ }
14248
14325
  const values = {};
14249
14326
  for (const [key, value] of formData.entries()) {
14250
14327
  if (typeof value === "string") {
@@ -14256,6 +14333,10 @@ function formDataToRecord(formData) {
14256
14333
 
14257
14334
  // ../../src/core/http/webFormRequest.ts
14258
14335
  class WebFormRequest {
14336
+ #preserveRepeated;
14337
+ constructor(options = {}) {
14338
+ this.#preserveRepeated = options.preserveRepeated === true;
14339
+ }
14259
14340
  authorize(_request) {
14260
14341
  return true;
14261
14342
  }
@@ -14266,7 +14347,7 @@ class WebFormRequest {
14266
14347
  if (!await this.authorize(request)) {
14267
14348
  throw new ForbiddenError;
14268
14349
  }
14269
- const payload = requestPrefersJson(request) ? await parseJsonBody(request, (body) => body) : await parseFormBody(request);
14350
+ const payload = requestPrefersJson(request) ? await parseJsonBody(request, (body) => body) : await parseFormBody(request, { preserveRepeated: this.#preserveRepeated });
14270
14351
  try {
14271
14352
  return this.validatePayload(payload);
14272
14353
  } catch (error) {
@@ -16417,7 +16498,7 @@ import { createHash as createHash8 } from "crypto";
16417
16498
  init_databaseTenantContext();
16418
16499
 
16419
16500
  // ../../src/core/tenant/publicTenantHost.ts
16420
- import { BlockList, isIP } from "net";
16501
+ import { BlockList, isIP as isIP2 } from "net";
16421
16502
  function normalizeTenantHostname(authority) {
16422
16503
  if (!authority || authority !== authority.trim() || /[\s\\/@?#%,]/.test(authority)) {
16423
16504
  throw new ForbiddenError("Invalid tenant hostname.");
@@ -16430,7 +16511,7 @@ function normalizeTenantHostname(authority) {
16430
16511
  }
16431
16512
  const hostname = url.hostname.toLowerCase().replace(/\.$/, "");
16432
16513
  const ip = hostname.startsWith("[") ? hostname.slice(1, -1) : hostname;
16433
- if (!isIP(ip) && (hostname.length > 253 || !hostname.split(".").every((label) => label.length > 0 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label)))) {
16514
+ if (!isIP2(ip) && (hostname.length > 253 || !hostname.split(".").every((label) => label.length > 0 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label)))) {
16434
16515
  throw new ForbiddenError("Invalid tenant hostname.");
16435
16516
  }
16436
16517
  return hostname;
@@ -16441,14 +16522,14 @@ function createPublicTenantSelector(options) {
16441
16522
  throw new Error("Public tenancy supports at most 128 trusted proxy addresses.");
16442
16523
  const proxies = new BlockList;
16443
16524
  for (const address of addresses) {
16444
- const version = isIP(address);
16525
+ const version = isIP2(address);
16445
16526
  if (!version)
16446
16527
  throw new Error("Trusted proxy addresses must be literal IP addresses.");
16447
16528
  proxies.addAddress(address, version === 6 ? "ipv6" : "ipv4");
16448
16529
  }
16449
16530
  return async (request) => {
16450
16531
  const peer = currentRequestMeta().peerAddress;
16451
- const version = peer ? isIP(peer) : 0;
16532
+ const version = peer ? isIP2(peer) : 0;
16452
16533
  const trusted = peer && version && proxies.check(peer, version === 6 ? "ipv6" : "ipv4");
16453
16534
  const forwarded = trusted ? request.headers.get("x-forwarded-host") : null;
16454
16535
  const authority = forwarded ?? request.headers.get("host") ?? new URL(request.url).host;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/core",
3
- "version": "2.2.56",
3
+ "version": "2.2.58",
4
4
  "description": "Strata Bun framework public API",
5
5
  "type": "module",
6
6
  "license": "MIT",