bunsane 0.2.10 → 0.3.1

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.
Files changed (47) hide show
  1. package/CHANGELOG.md +318 -0
  2. package/CLAUDE.md +20 -0
  3. package/config/cache.config.ts +12 -2
  4. package/core/App.ts +300 -69
  5. package/core/ApplicationLifecycle.ts +68 -4
  6. package/core/Entity.ts +525 -256
  7. package/core/EntityHookManager.ts +88 -21
  8. package/core/EntityManager.ts +12 -3
  9. package/core/Logger.ts +4 -0
  10. package/core/RequestContext.ts +4 -1
  11. package/core/SchedulerManager.ts +105 -22
  12. package/core/cache/CacheFactory.ts +3 -1
  13. package/core/cache/CacheManager.ts +72 -17
  14. package/core/cache/RedisCache.ts +38 -3
  15. package/core/components/BaseComponent.ts +12 -2
  16. package/core/decorators/EntityHooks.ts +24 -12
  17. package/core/middleware/RateLimit.ts +105 -0
  18. package/core/middleware/index.ts +1 -0
  19. package/core/remote/OutboxWorker.ts +42 -35
  20. package/core/scheduler/DistributedLock.ts +22 -7
  21. package/database/PreparedStatementCache.ts +5 -13
  22. package/gql/builders/ResolverBuilder.ts +4 -4
  23. package/gql/complexityLimit.ts +95 -0
  24. package/gql/index.ts +15 -3
  25. package/gql/visitors/ResolverGeneratorVisitor.ts +16 -2
  26. package/package.json +1 -1
  27. package/query/ComponentInclusionNode.ts +18 -11
  28. package/query/OrNode.ts +2 -4
  29. package/query/Query.ts +42 -31
  30. package/query/SqlIdentifier.ts +105 -0
  31. package/query/builders/FullTextSearchBuilder.ts +19 -6
  32. package/service/ServiceRegistry.ts +28 -9
  33. package/service/index.ts +4 -2
  34. package/storage/LocalStorageProvider.ts +12 -3
  35. package/storage/S3StorageProvider.ts +6 -6
  36. package/tests/e2e/http.test.ts +6 -2
  37. package/tests/integration/entity/Entity.saveTimeout.test.ts +110 -0
  38. package/tests/unit/cache/CacheManager.test.ts +20 -0
  39. package/tests/unit/entity/Entity.components.test.ts +73 -0
  40. package/tests/unit/entity/Entity.drainSideEffects.test.ts +51 -0
  41. package/tests/unit/entity/Entity.reload.test.ts +63 -0
  42. package/tests/unit/entity/Entity.requireComponents.test.ts +72 -0
  43. package/tests/unit/query/Query.emptyString.test.ts +69 -0
  44. package/tests/unit/query/Query.test.ts +6 -4
  45. package/tests/unit/scheduler/SchedulerManager.timeBased.test.ts +95 -0
  46. package/tests/unit/storage/S3StorageProvider.test.ts +6 -10
  47. package/upload/FileValidator.ts +9 -6
@@ -1,6 +1,8 @@
1
1
  import { GraphVisitor } from "./GraphVisitor";
2
2
  import { TypeNode, OperationNode, FieldNode, InputNode, ScalarNode } from "../graph/GraphNode";
3
3
  import { ResolverBuilder } from "../builders/ResolverBuilder";
4
+ import { isSchemaInput } from "../schema";
5
+ import * as z from "zod";
4
6
  import { logger } from "../../core/Logger";
5
7
 
6
8
  /**
@@ -54,9 +56,21 @@ export class ResolverGeneratorVisitor extends GraphVisitor {
54
56
 
55
57
  const type = node.operationType.charAt(0).toUpperCase() + node.operationType.slice(1).toLowerCase() as "Query" | "Mutation" | "Subscription";
56
58
 
57
- // Extract Zod schema from input if it's a Zod type (check for '_def' property)
59
+ // Extract Zod schema from input. If it's already a Zod type (`_def`),
60
+ // use directly. If it's a Schema DSL input (`t.` API), convert each
61
+ // field `.toZod()` into a Zod object so the resolver validates it
62
+ // instead of passing raw args through (H-GQL-4).
58
63
  const input = node.metadata.input;
59
- const zodSchema = (input && typeof input === 'object' && '_def' in input) ? input as any : null;
64
+ let zodSchema: any = null;
65
+ if (input && typeof input === 'object' && '_def' in input) {
66
+ zodSchema = input;
67
+ } else if (isSchemaInput(input)) {
68
+ const zodShape: Record<string, z.ZodType> = {};
69
+ for (const [key, field] of Object.entries(input)) {
70
+ zodShape[key] = (field as any).toZod();
71
+ }
72
+ zodSchema = z.object(zodShape);
73
+ }
60
74
 
61
75
  // Create resolver definitions for operations
62
76
  const resolverDef = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunsane",
3
- "version": "0.2.10",
3
+ "version": "0.3.1",
4
4
  "author": {
5
5
  "name": "yaaruu"
6
6
  },
@@ -5,6 +5,7 @@ import { shouldUseLateralJoins, shouldUseDirectPartition } from "../core/Config"
5
5
  import { FilterBuilderRegistry } from "./FilterBuilderRegistry";
6
6
  import { ComponentRegistry } from "../core/components";
7
7
  import { getMetadataStorage } from "../core/metadata";
8
+ import { assertIdentifier } from "./SqlIdentifier";
8
9
 
9
10
  /**
10
11
  * Check if a component property is numeric based on metadata
@@ -331,12 +332,16 @@ export class ComponentInclusionNode extends QueryNode {
331
332
  const sortComponentTableName = this.getComponentTableName(typeId);
332
333
  const nullsClause = sortOrder.nullsFirst ? 'NULLS FIRST' : 'NULLS LAST';
333
334
  const isNumeric = isNumericProperty(sortOrder.component, sortOrder.property);
335
+ // Validate property name before interpolating into JSON path.
336
+ // Without this, a malicious or malformed sortOrder.property could
337
+ // inject SQL through the template (C08).
338
+ const safeProperty = assertIdentifier(sortOrder.property, 'sortOrder.property');
334
339
 
335
340
  // Build scalar subquery to get sort value for each entity
336
341
  // This avoids nested loop join by forcing row-by-row evaluation
337
342
  const sortExpr = isNumeric
338
- ? `(sort_c.data->>'${sortOrder.property}')::numeric`
339
- : `sort_c.data->>'${sortOrder.property}'`;
343
+ ? `(sort_c.data->>'${safeProperty}')::numeric`
344
+ : `sort_c.data->>'${safeProperty}'`;
340
345
 
341
346
  const subquery = `(
342
347
  SELECT ${sortExpr}
@@ -454,9 +459,10 @@ export class ComponentInclusionNode extends QueryNode {
454
459
 
455
460
  const nullsClause = sortOrder.nullsFirst ? 'NULLS FIRST' : 'NULLS LAST';
456
461
  const isNumeric = isNumericProperty(sortOrder.component, sortOrder.property);
462
+ const safeProperty = assertIdentifier(sortOrder.property, 'sortOrder.property');
457
463
  const sortExpr = isNumeric
458
- ? `(c.data->>'${sortOrder.property}')::numeric`
459
- : `c.data->>'${sortOrder.property}'`;
464
+ ? `(c.data->>'${safeProperty}')::numeric`
465
+ : `c.data->>'${safeProperty}'`;
460
466
 
461
467
  let sql: string;
462
468
  if (useDirectPartition) {
@@ -508,9 +514,10 @@ export class ComponentInclusionNode extends QueryNode {
508
514
 
509
515
  const nullsClause = sortOrder.nullsFirst ? 'NULLS FIRST' : 'NULLS LAST';
510
516
  const isNumeric = isNumericProperty(sortOrder.component, sortOrder.property);
517
+ const safeProperty = assertIdentifier(sortOrder.property, 'sortOrder.property');
511
518
  const sortExpr = isNumeric
512
- ? `(sort_c.data->>'${sortOrder.property}')::numeric`
513
- : `sort_c.data->>'${sortOrder.property}'`;
519
+ ? `(sort_c.data->>'${safeProperty}')::numeric`
520
+ : `sort_c.data->>'${safeProperty}'`;
514
521
 
515
522
  // Use scalar subquery to avoid cartesian product explosion
516
523
  // This forces PostgreSQL to evaluate sort value per-entity, preventing
@@ -599,11 +606,11 @@ export class ComponentInclusionNode extends QueryNode {
599
606
  condition = result.sql;
600
607
  // Note: custom builder is responsible for adding parameters via context.addParam()
601
608
  } else {
602
- // Default filter logic
603
- // Validate filter value to prevent PostgreSQL UUID parsing errors
604
- if (filter.value === '' || (typeof filter.value === 'string' && filter.value.trim() === '')) {
605
- throw new Error(`Filter value for field "${filter.field}" is an empty string. This would cause PostgreSQL UUID parsing errors.`);
606
- }
609
+ // Default filter logic. Empty-string values are permitted
610
+ // here `c.data->>'field'` extracts text, so `=`/`!=`/
611
+ // `LIKE` against '' is legitimate. The UUID-cast path
612
+ // below is gated on a regex that empty string cannot
613
+ // match, so unsafe casts never fire.
607
614
 
608
615
  // Check if value looks like a UUID (case-insensitive, with or without hyphens)
609
616
  const valueStr = String(filter.value);
package/query/OrNode.ts CHANGED
@@ -305,15 +305,13 @@ export class OrNode extends QueryNode {
305
305
  public execute(context: QueryContext): QueryResult {
306
306
  // Try optimized UNION ALL path for direct partition access
307
307
  // This avoids the slow multi-partition scanning by querying each partition directly
308
+ // (Verbose console.log debug traces removed — H-QUERY-2. Re-enable via
309
+ // a framework logger at debug level if needed.)
308
310
  const canUseOptimized = this.canUseUnionAllOptimization() && this.dependencies.length === 0;
309
- console.log(`OrNode: Using optimized path: ${canUseOptimized}, dependencies: ${this.dependencies.length}, direct partition: ${require("../core/Config").shouldUseDirectPartition()}`);
310
- console.log(`OrNode: Component types:`, Array.from(this.orQuery.getComponentTypes()));
311
311
 
312
312
  if (canUseOptimized) {
313
- console.log("OrNode: Using optimized UNION path");
314
313
  return this.executeUnionAllOptimized(context);
315
314
  }
316
- console.log("OrNode: Using fallback path");
317
315
 
318
316
  // Fall back to original implementation for:
319
317
  // - HASH partitioning (no direct partition access)
package/query/Query.ts CHANGED
@@ -12,6 +12,7 @@ import { getMetadataStorage } from "../core/metadata";
12
12
  import { shouldUseDirectPartition } from "../core/Config";
13
13
  import type { SQL } from "bun";
14
14
  import type { ComponentConstructor, TypedEntity, ComponentRecord } from "../types/query.types";
15
+ import { assertComponentTableName, assertFieldPath } from "./SqlIdentifier";
15
16
 
16
17
  export type FilterOperator = "=" | ">" | "<" | ">=" | "<=" | "!=" | "LIKE" | "ILIKE" | "IN" | "NOT IN" | string;
17
18
 
@@ -338,7 +339,13 @@ class Query<TComponents extends readonly ComponentConstructor[] = []> {
338
339
  throw new Error(`Component ${component.name} not registered`);
339
340
  }
340
341
 
341
- const tableName = ComponentRegistry.getPartitionTableName(typeId);
342
+ // Validate the resolved partition table name against the component
343
+ // table allow-list before passing to pg_class lookup. Although
344
+ // `relname` here is a bound parameter ($1) and cannot inject SQL
345
+ // directly, we still reject unexpected names so a registry
346
+ // poisoning bug cannot query arbitrary tables.
347
+ const rawTableName = ComponentRegistry.getPartitionTableName(typeId);
348
+ const tableName = rawTableName ? assertComponentTableName(rawTableName, 'estimatedCount.tableName') : null;
342
349
  const dbConn = this.getDb();
343
350
 
344
351
  // Use PostgreSQL's statistics for fast count estimate
@@ -423,14 +430,11 @@ class Query<TComponents extends readonly ComponentConstructor[] = []> {
423
430
  console.log('---');
424
431
  }
425
432
 
426
- // Validate params before execution to catch UUID errors early
427
- for (let i = 0; i < result.params.length; i++) {
428
- const param = result.params[i];
429
- if (param === '' || (typeof param === 'string' && param.trim() === '')) {
430
- logger.error(`Empty string parameter detected at position ${i + 1} in count query`);
431
- throw new Error(`Query count parameter $${i + 1} is an empty string. This will cause PostgreSQL UUID parsing errors.`);
432
- }
433
- }
433
+ // Empty-string params are legitimate for text-field filters
434
+ // (`c.data->>'field' = ''`). UUID-typed params never reach this
435
+ // point empty — findById guards at entry; cursor/excluded IDs come
436
+ // from saved entities. PG emits a clear error if a UUID cast meets
437
+ // an empty string at execution time.
434
438
 
435
439
  // Safely extract count from result - handle undefined/null cases
436
440
  if (!countResult || countResult.length === 0 || countResult[0] === undefined) {
@@ -557,10 +561,17 @@ class Query<TComponents extends readonly ComponentConstructor[] = []> {
557
561
  // Execute the DAG to get the base query
558
562
  const result = dag.execute(this.context);
559
563
 
560
- // Determine the component table name
561
- const componentTableName = shouldUseDirectPartition()
564
+ // Determine the component table name. Validate against allow-list so
565
+ // a poisoned registry cannot inject SQL through the embedded name.
566
+ const rawComponentTableName = shouldUseDirectPartition()
562
567
  ? (ComponentRegistry.getPartitionTableName(typeId) || 'components')
563
568
  : 'components';
569
+ const componentTableName = assertComponentTableName(rawComponentTableName, 'doAggregate.componentTableName');
570
+
571
+ // Validate the field path — each dotted segment must be a safe
572
+ // identifier. Without this, a caller-supplied field with quote or
573
+ // `->` metacharacters would corrupt the JSON path expression (C08).
574
+ assertFieldPath(field, 'doAggregate.field');
564
575
 
565
576
  // Build the JSON path for the field
566
577
  let jsonPath: string;
@@ -609,14 +620,8 @@ AND c.deleted_at IS NULL`;
609
620
  console.log('---');
610
621
  }
611
622
 
612
- // Validate params
613
- for (let i = 0; i < result.params.length; i++) {
614
- const param = result.params[i];
615
- if (param === '' || (typeof param === 'string' && param.trim() === '')) {
616
- logger.error(`Empty string parameter detected at position ${i + 1} in ${aggregateType} query`);
617
- throw new Error(`Query ${aggregateType} parameter $${i + 1} is an empty string.`);
618
- }
619
- }
623
+ // Empty-string params are legitimate for text-field filters; see
624
+ // comment above in doCount.
620
625
 
621
626
  // Extract result
622
627
  if (!aggregateResult || aggregateResult.length === 0 || aggregateResult[0] === undefined) {
@@ -641,6 +646,19 @@ AND c.deleted_at IS NULL`;
641
646
  */
642
647
  @timed("Query.exec")
643
648
  public async exec(): Promise<TypedEntity<TComponents>[]> {
649
+ // Apply default LIMIT so unbounded queries cannot load entire tables
650
+ // into memory. Configurable via BUNSANE_DEFAULT_QUERY_LIMIT, 0 to
651
+ // disable. When the default is applied without an explicit .take(),
652
+ // warn once at execution so developers notice runaway queries
653
+ // (H-QUERY-1).
654
+ if (this.context.limit === null || this.context.limit === undefined) {
655
+ const envLimit = parseInt(process.env.BUNSANE_DEFAULT_QUERY_LIMIT ?? '10000', 10);
656
+ if (envLimit > 0) {
657
+ this.context.limit = envLimit;
658
+ logger.warn({ scope: 'Query.exec', defaultLimit: envLimit }, 'Query executed without explicit .take() — applying framework default LIMIT. Call .take(N) to suppress this warning.');
659
+ }
660
+ }
661
+
644
662
  return new Promise<TypedEntity<TComponents>[]>((resolve, reject) => {
645
663
  // Add timeout to prevent hanging queries
646
664
  const timeout = setTimeout(() => {
@@ -767,14 +785,11 @@ AND c.deleted_at IS NULL`;
767
785
  console.log('---');
768
786
  }
769
787
 
770
- // Validate params before execution to catch UUID errors early
771
- for (let i = 0; i < result.params.length; i++) {
772
- const param = result.params[i];
773
- if (param === '' || (typeof param === 'string' && param.trim() === '')) {
774
- logger.error(`Empty string parameter detected at position ${i + 1}: SQL=${result.sql.substring(0, 200)}`);
775
- throw new Error(`Query parameter $${i + 1} is an empty string. This will cause PostgreSQL UUID parsing errors. SQL: ${result.sql.substring(0, 100)}...`);
776
- }
777
- }
788
+ // Empty-string params are legitimate for text-field filters
789
+ // (`c.data->>'field' = ''`). UUID-typed params never reach this
790
+ // point empty — findById guards at entry; cursor/excluded IDs
791
+ // originate from saved entities. PG emits a clear error at
792
+ // execution time if a UUID cast meets an empty string.
778
793
 
779
794
  // Validate parameters before execution
780
795
  for (let i = 0; i < result.params.length; i++) {
@@ -994,10 +1009,6 @@ AND c.deleted_at IS NULL`;
994
1009
  static filterOp = FilterOp;
995
1010
 
996
1011
  public static filter(field: string, operator: FilterOperator, value: any): QueryFilter {
997
- // Validate value to catch empty strings early
998
- if (value === '' || (typeof value === 'string' && value.trim() === '')) {
999
- throw new Error(`Query.filter: Cannot create filter for field "${field}" with empty string value. This would cause PostgreSQL UUID parsing errors.`);
1000
- }
1001
1012
  return { field, operator, value };
1002
1013
  }
1003
1014
 
@@ -0,0 +1,105 @@
1
+ /**
2
+ * SQL identifier sanitization helpers.
3
+ *
4
+ * These helpers prevent SQL injection when interpolating caller-supplied or
5
+ * metadata-derived strings into SQL via `db.unsafe(...)` or template literals.
6
+ * Parameter binding (`$1`, `$2`) is always preferred for values, but column
7
+ * names, table names, ORDER BY fields, and JSON path segments cannot be
8
+ * parameterized — they are sanitized against a strict allow-list instead.
9
+ *
10
+ * Ticket C08.
11
+ */
12
+
13
+ /** Matches a safe identifier: letter/underscore followed by letters/digits/underscores. */
14
+ const IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
15
+
16
+ /** Matches a safe component table name: `components` or `components_<ident>`. */
17
+ const COMPONENT_TABLE_RE = /^components(?:_[a-z0-9_]+)?$/;
18
+
19
+ /**
20
+ * PostgreSQL text-search languages supported by `to_tsvector(config, ...)`.
21
+ * Extend as needed for deployments with additional dictionaries installed.
22
+ */
23
+ const ALLOWED_TS_LANGUAGES = new Set<string>([
24
+ 'simple',
25
+ 'english',
26
+ 'french',
27
+ 'german',
28
+ 'spanish',
29
+ 'italian',
30
+ 'portuguese',
31
+ 'dutch',
32
+ 'russian',
33
+ 'swedish',
34
+ 'norwegian',
35
+ 'danish',
36
+ 'finnish',
37
+ 'turkish',
38
+ 'hungarian',
39
+ 'arabic',
40
+ 'indonesian',
41
+ 'irish',
42
+ 'lithuanian',
43
+ 'nepali',
44
+ 'romanian',
45
+ 'tamil',
46
+ 'yiddish',
47
+ ]);
48
+
49
+ /**
50
+ * Assert a string is a safe SQL identifier (column name, alias). Throws
51
+ * `InvalidIdentifierError` if not.
52
+ */
53
+ export function assertIdentifier(value: unknown, context: string): string {
54
+ if (typeof value !== 'string' || !IDENT_RE.test(value)) {
55
+ throw new InvalidIdentifierError(context, String(value));
56
+ }
57
+ return value;
58
+ }
59
+
60
+ /**
61
+ * Assert a string is a safe component table name (e.g. `components`,
62
+ * `components_user`). Throws if not.
63
+ */
64
+ export function assertComponentTableName(value: unknown, context: string): string {
65
+ if (typeof value !== 'string' || !COMPONENT_TABLE_RE.test(value)) {
66
+ throw new InvalidIdentifierError(context, String(value));
67
+ }
68
+ return value;
69
+ }
70
+
71
+ /**
72
+ * Assert a dotted JSON field path is safe. Each segment must be a valid
73
+ * identifier. Empty paths / empty segments are rejected.
74
+ */
75
+ export function assertFieldPath(value: unknown, context: string): string {
76
+ if (typeof value !== 'string' || value.length === 0) {
77
+ throw new InvalidIdentifierError(context, String(value));
78
+ }
79
+ const parts = value.split('.');
80
+ for (const p of parts) {
81
+ if (!IDENT_RE.test(p)) {
82
+ throw new InvalidIdentifierError(context, value);
83
+ }
84
+ }
85
+ return value;
86
+ }
87
+
88
+ /**
89
+ * Assert a text-search language is in the allow-list. Defaults to `simple`
90
+ * when undefined (behavior preserved from the prior implementation).
91
+ */
92
+ export function assertTsLanguage(value: unknown, context: string = 'tsLanguage'): string {
93
+ if (value === undefined || value === null) return 'simple';
94
+ if (typeof value !== 'string' || !ALLOWED_TS_LANGUAGES.has(value.toLowerCase())) {
95
+ throw new InvalidIdentifierError(context, String(value));
96
+ }
97
+ return value.toLowerCase();
98
+ }
99
+
100
+ export class InvalidIdentifierError extends Error {
101
+ constructor(context: string, value: string) {
102
+ super(`Invalid SQL identifier in ${context}: ${JSON.stringify(value)}`);
103
+ this.name = 'InvalidIdentifierError';
104
+ }
105
+ }
@@ -8,6 +8,7 @@
8
8
  import type { FilterBuilder, FilterBuilderOptions } from "../FilterBuilder";
9
9
  import type { QueryFilter } from "../QueryContext";
10
10
  import type { QueryContext } from "../QueryContext";
11
+ import { assertTsLanguage, assertFieldPath } from "../SqlIdentifier";
11
12
 
12
13
  /**
13
14
  * Full-text search filter value interface
@@ -68,12 +69,16 @@ export const fullTextSearchBuilder: FilterBuilder = (
68
69
  const value = filter.value as FullTextFilterValue;
69
70
  const { query, language = 'english', type = 'plain' } = value;
70
71
 
72
+ // Validate identifiers (C08).
73
+ const safeLanguage = assertTsLanguage(language, 'fullTextSearchBuilder.language');
74
+ assertFieldPath(filter.field, 'fullTextSearchBuilder.field');
75
+
71
76
  // Build the text search vector from the specified field
72
77
  const fieldPath = filter.field.includes('.')
73
78
  ? filter.field.split('.').map(p => `'${p}'`).join('->')
74
79
  : `'${filter.field}'`;
75
80
 
76
- const vectorSql = `to_tsvector('${language}', ${alias}.data->${fieldPath})`;
81
+ const vectorSql = `to_tsvector('${safeLanguage}', ${alias}.data->${fieldPath})`;
77
82
 
78
83
  // Choose the appropriate query function based on type
79
84
  let queryFunction: string;
@@ -93,7 +98,7 @@ export const fullTextSearchBuilder: FilterBuilder = (
93
98
  break;
94
99
  }
95
100
 
96
- const querySql = `${queryFunction}('${language}', $${context.addParam(query)})`;
101
+ const querySql = `${queryFunction}('${safeLanguage}', $${context.addParam(query)})`;
97
102
 
98
103
  return {
99
104
  sql: `${vectorSql} @@ ${querySql}`,
@@ -120,12 +125,16 @@ export const fullTextSearchWithRankBuilder: FilterBuilder = (
120
125
  const value = filter.value as FullTextFilterValue;
121
126
  const { query, language = 'english', type = 'plain' } = value;
122
127
 
128
+ // Validate identifiers (C08).
129
+ const safeLanguage = assertTsLanguage(language, 'fullTextSearchWithRankBuilder.language');
130
+ assertFieldPath(filter.field, 'fullTextSearchWithRankBuilder.field');
131
+
123
132
  // Build the text search vector from the specified field
124
133
  const fieldPath = filter.field.includes('.')
125
134
  ? filter.field.split('.').map(p => `'${p}'`).join('->')
126
135
  : `'${filter.field}'`;
127
136
 
128
- const vectorSql = `to_tsvector('${language}', ${alias}.data->${fieldPath})`;
137
+ const vectorSql = `to_tsvector('${safeLanguage}', ${alias}.data->${fieldPath})`;
129
138
 
130
139
  // Choose the appropriate query function based on type
131
140
  let queryFunction: string;
@@ -145,7 +154,7 @@ export const fullTextSearchWithRankBuilder: FilterBuilder = (
145
154
  break;
146
155
  }
147
156
 
148
- const querySql = `${queryFunction}('${language}', $${context.addParam(query)})`;
157
+ const querySql = `${queryFunction}('${safeLanguage}', $${context.addParam(query)})`;
149
158
 
150
159
  // Include ranking in the condition (can be used for ordering)
151
160
  const rankSql = `ts_rank(${vectorSql}, ${querySql})`;
@@ -187,16 +196,20 @@ export function createFullTextSearchBuilder(
187
196
  language: string = 'english',
188
197
  searchType: 'plain' | 'phrase' | 'web' | 'tsquery' = 'plain'
189
198
  ): { builder: FilterBuilder; options: FilterBuilderOptions } {
199
+ // Validate the language at factory-construction time so callers get an
200
+ // immediate error on invalid input rather than a runtime SQL error.
201
+ const safeLanguage = assertTsLanguage(language, 'createFullTextSearchBuilder.language');
190
202
  const builder: FilterBuilder = (filter: QueryFilter, alias: string, context: QueryContext) => {
191
203
  const value = filter.value as FullTextFilterValue;
192
204
  const query = value.query;
205
+ assertFieldPath(filter.field, 'createFullTextSearchBuilder.field');
193
206
 
194
207
  // Build the text search vector from the specified field
195
208
  const fieldPath = filter.field.includes('.')
196
209
  ? filter.field.split('.').map(p => `'${p}'`).join('->')
197
210
  : `'${filter.field}'`;
198
211
 
199
- const vectorSql = `to_tsvector('${language}', ${alias}.data->${fieldPath})`;
212
+ const vectorSql = `to_tsvector('${safeLanguage}', ${alias}.data->${fieldPath})`;
200
213
 
201
214
  // Choose the appropriate query function based on type
202
215
  let queryFunction: string;
@@ -216,7 +229,7 @@ export function createFullTextSearchBuilder(
216
229
  break;
217
230
  }
218
231
 
219
- const querySql = `${queryFunction}('${language}', $${context.addParam(query)})`;
232
+ const querySql = `${queryFunction}('${safeLanguage}', $${context.addParam(query)})`;
220
233
 
221
234
  return {
222
235
  sql: `${vectorSql} @@ ${querySql}`,
@@ -1,35 +1,54 @@
1
1
  import type BaseService from "./Service";
2
- import ApplicationLifecycle, {ApplicationPhase} from "../core/ApplicationLifecycle";
2
+ import ApplicationLifecycle, {ApplicationPhase, type PhaseChangeEvent} from "../core/ApplicationLifecycle";
3
3
  import { generateGraphQLSchemaV2 } from "../gql";
4
4
  import { GraphQLSchema } from "graphql";
5
5
 
6
- class ServiceRegistry {
6
+ /**
7
+ * ServiceRegistry is a singleton. The default export and the re-exported
8
+ * named `ServiceRegistry` from `service/index.ts` both resolve to the
9
+ * singleton instance (for backward compatibility). When you need the class
10
+ * itself (for typing or subclassing), import `ServiceRegistryClass`.
11
+ */
12
+ export class ServiceRegistry {
7
13
  static #instance: ServiceRegistry;
8
14
 
9
15
  private services: Map<string, BaseService> = new Map();
10
16
  private schema: GraphQLSchema | null = null;
17
+ private phaseListener: ((event: PhaseChangeEvent) => void) | null = null;
11
18
 
12
19
 
13
20
  constructor() {
14
-
21
+
15
22
  }
16
23
 
17
24
  public init() {
18
- ApplicationLifecycle.addPhaseListener((event) => {
25
+ // Remove previous listener if re-init (tests) to prevent listener stacking.
26
+ if (this.phaseListener) {
27
+ ApplicationLifecycle.removePhaseListener(this.phaseListener);
28
+ }
29
+ this.phaseListener = (event: PhaseChangeEvent) => {
19
30
  switch(event.detail) {
20
31
  case ApplicationPhase.SYSTEM_REGISTERING: {
21
32
  const servicesArray = Array.from(this.services.values());
22
-
23
- const result = generateGraphQLSchemaV2(servicesArray, {
24
- enableArchetypeOperations: false
33
+
34
+ const result = generateGraphQLSchemaV2(servicesArray, {
35
+ enableArchetypeOperations: false
25
36
  });
26
-
37
+
27
38
  this.schema = result.schema;
28
39
  ApplicationLifecycle.setPhase(ApplicationPhase.SYSTEM_READY);
29
40
  break;
30
41
  };
31
42
  }
32
- });
43
+ };
44
+ ApplicationLifecycle.addPhaseListener(this.phaseListener);
45
+ }
46
+
47
+ public dispose(): void {
48
+ if (this.phaseListener) {
49
+ ApplicationLifecycle.removePhaseListener(this.phaseListener);
50
+ this.phaseListener = null;
51
+ }
33
52
  }
34
53
 
35
54
 
package/service/index.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import BaseService from "./Service";
2
- import ServiceRegistry from "./ServiceRegistry";
2
+ import ServiceRegistry from "./ServiceRegistry";
3
+ import { ServiceRegistry as ServiceRegistryClass } from "./ServiceRegistry";
3
4
  import { httpEndpoint } from "../rest";
4
5
 
5
6
  export {
6
7
  BaseService,
7
- ServiceRegistry
8
+ ServiceRegistry,
9
+ ServiceRegistryClass,
8
10
  }
9
11
 
10
12
  // Shorthand decorators for HTTP methods
@@ -1,4 +1,6 @@
1
1
  import fs from "fs";
2
+ import { pipeline } from "stream/promises";
3
+ import { Readable } from "stream";
2
4
  import path from "path";
3
5
  import { StorageProvider } from "./StorageProvider";
4
6
  import type { UploadConfiguration, StorageResult, FileMetadata } from "../types/upload.types";
@@ -51,9 +53,16 @@ export class LocalStorageProvider extends StorageProvider {
51
53
  fs.mkdirSync(uploadDir, { recursive: true });
52
54
  }
53
55
 
54
- // Write file to disk
55
- const buffer = Buffer.from(await file.arrayBuffer());
56
- fs.writeFileSync(fullPath, buffer);
56
+ // Stream File → disk to avoid full in-memory buffering of large uploads.
57
+ const writeStream = fs.createWriteStream(fullPath);
58
+ try {
59
+ const webStream = file.stream() as ReadableStream<Uint8Array>;
60
+ const nodeStream = Readable.fromWeb(webStream as any);
61
+ await pipeline(nodeStream, writeStream);
62
+ } catch (streamError) {
63
+ try { fs.unlinkSync(fullPath); } catch { /* best-effort cleanup */ }
64
+ throw streamError;
65
+ }
57
66
 
58
67
  // Generate URL
59
68
  const url = this.buildUrl(relativePath);
@@ -213,11 +213,11 @@ export class S3StorageProvider extends StorageProvider {
213
213
  const destKey = this.resolveKey(destinationPath);
214
214
 
215
215
  try {
216
- const [data, stat] = await Promise.all([
217
- this.client.file(sourceKey).arrayBuffer(),
218
- this.client.stat(sourceKey),
219
- ]);
220
- await this.client.write(destKey, data, {
216
+ const stat = await this.client.stat(sourceKey);
217
+ const sourceFile = this.client.file(sourceKey);
218
+ // Pass the S3File directly so Bun streams bytes rather than loading
219
+ // the entire object into memory (previously `arrayBuffer()`).
220
+ await this.client.write(destKey, sourceFile, {
221
221
  type: stat.type,
222
222
  acl: this.acl,
223
223
  });
@@ -226,7 +226,7 @@ export class S3StorageProvider extends StorageProvider {
226
226
  } catch (error) {
227
227
  const msg =
228
228
  error instanceof Error ? error.message : "Unknown error";
229
- logger.error({ sourceKey, destKey }, "Failed to copy file");
229
+ logger.error({ sourceKey, destKey, err: msg }, "Failed to copy file");
230
230
  return false;
231
231
  }
232
232
  }
@@ -76,8 +76,12 @@ describe("E2E HTTP Routes", () => {
76
76
 
77
77
  it("OPTIONS /health returns 204 when CORS configured", async () => {
78
78
  app.setCors({ origin: "*" });
79
- // Re-compose middleware chain not needed CORS headers are added per-request in handleRequest
80
- const res = await fetch(`${BASE}/health`, { method: "OPTIONS" });
79
+ // Preflight must carry Origin header per CORS spec; otherwise the
80
+ // server emits no Access-Control-Allow-Origin (no `|| '*'` fallback).
81
+ const res = await fetch(`${BASE}/health`, {
82
+ method: "OPTIONS",
83
+ headers: { Origin: "https://client.example" },
84
+ });
81
85
  expect(res.status).toBe(204);
82
86
  expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
83
87
  });