pure-js-db 0.0.0-stage → 2.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (541) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +747 -3
  3. package/bindings/java/pom.xml +18 -0
  4. package/bindings/java/src/main/java/purejsdb/PureJsDBClient.java +146 -0
  5. package/bindings/java/src/main/java/purejsdb/TransactionClient.java +65 -0
  6. package/bindings/java/src/test/java/TestClient.java +68 -0
  7. package/bindings/orm/sequelize-adapter.js +1236 -0
  8. package/bindings/python/purejsdb/client.py +81 -0
  9. package/bindings/python/setup.py +9 -0
  10. package/bindings/python/test_client.py +63 -0
  11. package/config/datagrip-config.md +206 -0
  12. package/config/grafana-dashboard.json +1510 -0
  13. package/config/production.config.js +126 -0
  14. package/config/prometheus-scrape.yml +39 -0
  15. package/native/index.node +0 -0
  16. package/package.json +205 -6
  17. package/scripts/mcp-server.mjs +208 -0
  18. package/src/adapter/dialect-adapter.js +179 -0
  19. package/src/adapter/oracle-adapter.js +191 -0
  20. package/src/ai/ai-service.js +713 -0
  21. package/src/ai/rag-pipeline.js +160 -0
  22. package/src/alerting/alert-manager.js +622 -0
  23. package/src/alerting/index.js +10 -0
  24. package/src/arrow/arrow-ipc.js +973 -0
  25. package/src/arrow/flatbuffer.js +521 -0
  26. package/src/arrow/index.js +261 -0
  27. package/src/arrow/parquet.js +1525 -0
  28. package/src/audit/audit-log.js +1345 -0
  29. package/src/audit/audit-report.js +571 -0
  30. package/src/audit/index.js +6 -0
  31. package/src/backpressure/backpressure-controller.js +262 -0
  32. package/src/backpressure/index.js +6 -0
  33. package/src/backpressure/write-rate-limiter.js +243 -0
  34. package/src/backup/backup-manager.js +416 -0
  35. package/src/backup/index.js +8 -0
  36. package/src/backup/logical-backup.js +228 -0
  37. package/src/backup/snapshot.js +111 -0
  38. package/src/backup/toolkit.js +410 -0
  39. package/src/bindings/orm/prisma-adapter.js +571 -0
  40. package/src/bindings/orm/typeorm-adapter.js +477 -0
  41. package/src/cache/adaptive-cache-size.js +288 -0
  42. package/src/cache/adaptive-ttl.js +139 -0
  43. package/src/cache/cache-adapter.js +304 -0
  44. package/src/cache/circuit-breaker.js +294 -0
  45. package/src/cache/index.js +31 -0
  46. package/src/cache/lru-cache.js +353 -0
  47. package/src/cache/redis-adapter.js +391 -0
  48. package/src/cache/resilient-adapter.js +391 -0
  49. package/src/cache/result-cache.js +493 -0
  50. package/src/cache/semantic-cache.js +339 -0
  51. package/src/cdc/cdc-engine.js +1061 -0
  52. package/src/cdc/cdc-handlers.js +289 -0
  53. package/src/cdc/ddl-capture.js +330 -0
  54. package/src/cdc/debezium-adapter.js +366 -0
  55. package/src/cdc/schema-history.js +414 -0
  56. package/src/changelog/changelog-buffer.js +881 -0
  57. package/src/changelog/changelog-wal.js +299 -0
  58. package/src/changelog/linear-regression-predictor.js +186 -0
  59. package/src/changelog/predictive-growth.js +348 -0
  60. package/src/changelog/seasonal-predictor.js +450 -0
  61. package/src/changelog/write-rate-sampler.js +141 -0
  62. package/src/cli/dump-command.js +944 -0
  63. package/src/cli/interactive.js +188 -0
  64. package/src/cli/migrate-command.js +252 -0
  65. package/src/cli.js +533 -0
  66. package/src/cluster/failover.js +477 -0
  67. package/src/cluster/index.js +19 -0
  68. package/src/cluster/persistent-state.js +203 -0
  69. package/src/cluster/public-api.js +58 -0
  70. package/src/cluster/raft-http-transport.js +280 -0
  71. package/src/cluster/raft-log.js +313 -0
  72. package/src/cluster/raft.js +912 -0
  73. package/src/cluster/snapshot-persistence.js +131 -0
  74. package/src/concurrency/async-mutex.js +365 -0
  75. package/src/concurrency/circuit-breaker.js +326 -0
  76. package/src/concurrency/connection-pool.js +409 -0
  77. package/src/concurrency/connection-session.js +498 -0
  78. package/src/concurrency/index.js +29 -0
  79. package/src/concurrency/lock-manager.js +363 -0
  80. package/src/concurrency/lockfree-executor.js +322 -0
  81. package/src/concurrency/lockfree-manager.js +570 -0
  82. package/src/concurrency/mvcc.js +499 -0
  83. package/src/concurrency/occ-hot-row.js +726 -0
  84. package/src/concurrency/query-degradation.js +380 -0
  85. package/src/concurrency/query-isolation.js +374 -0
  86. package/src/concurrency/shared-memory-pool.js +459 -0
  87. package/src/concurrency/snapshot-buffer.js +461 -0
  88. package/src/concurrency/transaction-context.js +193 -0
  89. package/src/copy/copy-stream.js +643 -0
  90. package/src/copy/index.js +5 -0
  91. package/src/core/database.js +1947 -0
  92. package/src/core/index.js +13 -0
  93. package/src/daemon/compact-daemon.js +535 -0
  94. package/src/daemon/index.js +14 -0
  95. package/src/daemon/soa-daemon-integration.js +333 -0
  96. package/src/ddl/online-ddl.js +348 -0
  97. package/src/disruptor/disruptor.js +348 -0
  98. package/src/disruptor/event-bus.js +238 -0
  99. package/src/disruptor/event-pool.js +62 -0
  100. package/src/disruptor/index.js +31 -0
  101. package/src/disruptor/ring-buffer.js +150 -0
  102. package/src/disruptor/sequence.js +88 -0
  103. package/src/disruptor/wait-strategy.js +160 -0
  104. package/src/engine/public-api.js +210 -0
  105. package/src/executor/asof-join-executor.js +265 -0
  106. package/src/executor/bitmap-filter.js +1382 -0
  107. package/src/executor/compiled-expression.js +472 -0
  108. package/src/executor/compiled-predicate.js +458 -0
  109. package/src/executor/constraint-executor.js +577 -0
  110. package/src/executor/copy-executor.js +210 -0
  111. package/src/executor/cte/recursive-cte.js +89 -0
  112. package/src/executor/cte-executor.js +501 -0
  113. package/src/executor/cursor-executor.js +216 -0
  114. package/src/executor/database.js +41 -0
  115. package/src/executor/ddl-executor.js +3531 -0
  116. package/src/executor/dml-executor.js +3557 -0
  117. package/src/executor/executor-worker.js +331 -0
  118. package/src/executor/executor.js +10889 -0
  119. package/src/executor/explain-analyzer.js +422 -0
  120. package/src/executor/explain-executor.js +324 -0
  121. package/src/executor/expression.js +4972 -0
  122. package/src/executor/foreign-key-executor.js +691 -0
  123. package/src/executor/graph-table-executor.js +451 -0
  124. package/src/executor/grouping-executor.js +251 -0
  125. package/src/executor/hotpath.js +232 -0
  126. package/src/executor/hybrid-search-executor.js +326 -0
  127. package/src/executor/incremental-live-query.js +866 -0
  128. package/src/executor/index-maintenance-executor.js +731 -0
  129. package/src/executor/index.js +16 -0
  130. package/src/executor/info-schema-executor.js +123 -0
  131. package/src/executor/join/lateral-join.js +64 -0
  132. package/src/executor/join-executor.js +530 -0
  133. package/src/executor/lineage-executor.js +85 -0
  134. package/src/executor/live-query-manager.js +350 -0
  135. package/src/executor/loop-unroll.js +539 -0
  136. package/src/executor/match-recognize-executor.js +918 -0
  137. package/src/executor/multi-stream-wal.js +140 -0
  138. package/src/executor/nl2sql-executor.js +309 -0
  139. package/src/executor/parallel-dml.js +258 -0
  140. package/src/executor/pivot-executor.js +458 -0
  141. package/src/executor/pragma-executor.js +661 -0
  142. package/src/executor/select-executor.js +857 -0
  143. package/src/executor/sequence.js +139 -0
  144. package/src/executor/sql-reconstructor.js +296 -0
  145. package/src/executor/subquery-cache.js +186 -0
  146. package/src/executor/subquery-executor.js +1390 -0
  147. package/src/executor/system-catalog.js +731 -0
  148. package/src/executor/table-function-executor.js +656 -0
  149. package/src/executor/topn.js +103 -0
  150. package/src/executor/transaction-executor.js +926 -0
  151. package/src/executor/trigger-executor.js +441 -0
  152. package/src/executor/v8-turbofan-optimizer.js +363 -0
  153. package/src/executor/vector-acceleration.js +456 -0
  154. package/src/executor/vector-executor.js +847 -0
  155. package/src/executor/vectorized-columnar-engine.js +1130 -0
  156. package/src/executor/vectorized-executor-v2.js +993 -0
  157. package/src/executor/view-executor.js +149 -0
  158. package/src/executor/wal.js +1945 -0
  159. package/src/executor/wasm-simd-engine.js +929 -0
  160. package/src/executor/window-functions.js +894 -0
  161. package/src/fdw/fdw-manager.js +642 -0
  162. package/src/fdw/index.js +5 -0
  163. package/src/geo/geometry.js +447 -0
  164. package/src/geo/index.js +16 -0
  165. package/src/geo/spatial-functions.js +1241 -0
  166. package/src/graph/graph-helper.js +243 -0
  167. package/src/graph/pgq-matcher.js +2545 -0
  168. package/src/graph/property-graph.js +123 -0
  169. package/src/graphql-bridge.js +881 -0
  170. package/src/hotspot/access-tracker.js +188 -0
  171. package/src/hotspot/hotspot-detector.js +140 -0
  172. package/src/hotspot/hotspot-prefetcher.js +210 -0
  173. package/src/hotspot/index.js +7 -0
  174. package/src/http-api.js +1182 -0
  175. package/src/http-server/handlers/audit.js +224 -0
  176. package/src/http-server/handlers/changes-feed.js +261 -0
  177. package/src/http-server/handlers/management.js +464 -0
  178. package/src/http-server/handlers/query.js +573 -0
  179. package/src/http-server/handlers/transaction.js +251 -0
  180. package/src/http-server/index.js +89 -0
  181. package/src/http-server/openapi.js +656 -0
  182. package/src/http-server/router.js +120 -0
  183. package/src/http-server/server.js +1915 -0
  184. package/src/http-server/tls.js +126 -0
  185. package/src/http-server/ws-server.js +873 -0
  186. package/src/index/adaptive-hash-index.js +176 -0
  187. package/src/index/bitmap-index.js +429 -0
  188. package/src/index/brin-index.js +246 -0
  189. package/src/index/btree-index.js +428 -0
  190. package/src/index/btree.js +690 -0
  191. package/src/index/diskann-index.js +1903 -0
  192. package/src/index/fulltext/fulltext-index.js +66 -0
  193. package/src/index/fulltext/index.js +3 -0
  194. package/src/index/fulltext/inverted-index.js +197 -0
  195. package/src/index/fulltext/tokenizer.js +154 -0
  196. package/src/index/fulltext.js +287 -0
  197. package/src/index/gin-index.js +316 -0
  198. package/src/index/gist-index.js +463 -0
  199. package/src/index/gist-ops.js +325 -0
  200. package/src/index/graph-compressor.js +505 -0
  201. package/src/index/hash-index.js +180 -0
  202. package/src/index/hnsw-index.js +1232 -0
  203. package/src/index/hnsw-pq-index.js +1147 -0
  204. package/src/index/index-auto-tuner.js +1341 -0
  205. package/src/index/index-interface.js +364 -0
  206. package/src/index/index-selector.js +523 -0
  207. package/src/index/index.js +28 -0
  208. package/src/index/ivfpqsq-index.js +1163 -0
  209. package/src/index/offheap-btree-index.js +395 -0
  210. package/src/index/offheap-btree.js +748 -0
  211. package/src/index/product-quantizer.js +1447 -0
  212. package/src/index/robin-hood-hash-index.js +384 -0
  213. package/src/index/rtree-index.js +982 -0
  214. package/src/index/scalar-quantizer.js +411 -0
  215. package/src/index/semantic-index.js +283 -0
  216. package/src/index/string-interner.js +238 -0
  217. package/src/index/timestamp-index-advisor.js +491 -0
  218. package/src/index/timestamp-index-compressed.js +800 -0
  219. package/src/index/timestamp-index-compressor.js +547 -0
  220. package/src/index/timestamp-index.js +579 -0
  221. package/src/index/vector-index-serializer.js +499 -0
  222. package/src/index/vector-index-stats.js +450 -0
  223. package/src/index/vector-index.js +615 -0
  224. package/src/index-v3.js +27 -0
  225. package/src/index.js +33 -0
  226. package/src/internal/public-api.js +198 -0
  227. package/src/lineage/column-lineage.js +393 -0
  228. package/src/lineage/index.js +11 -0
  229. package/src/lineage/lineage-store.js +701 -0
  230. package/src/lineage/table-lineage.js +68 -0
  231. package/src/mcp/index.js +176 -0
  232. package/src/mcp/mcp-server.js +334 -0
  233. package/src/mcp/protocol.js +195 -0
  234. package/src/mcp/tools/backup-restore.js +131 -0
  235. package/src/mcp/tools/cdc-tools.js +201 -0
  236. package/src/mcp/tools/describe-table.js +100 -0
  237. package/src/mcp/tools/execute-sql.js +210 -0
  238. package/src/mcp/tools/explain-query.js +75 -0
  239. package/src/mcp/tools/index-management.js +191 -0
  240. package/src/mcp/tools/lineage.js +64 -0
  241. package/src/mcp/tools/list-tables.js +46 -0
  242. package/src/mcp/tools/monitoring.js +195 -0
  243. package/src/mcp/tools/schema-management.js +229 -0
  244. package/src/mcp/tools/text-to-sql.js +84 -0
  245. package/src/mcp/tools/transaction-management.js +191 -0
  246. package/src/mcp/tools/vector-search.js +101 -0
  247. package/src/mcp/transport/http.js +352 -0
  248. package/src/mcp/transport/stdio.js +117 -0
  249. package/src/memory/memory-manager.js +437 -0
  250. package/src/migration/migrator.js +389 -0
  251. package/src/monitor/index.js +36 -0
  252. package/src/monitor/metrics-exporter.js +517 -0
  253. package/src/monitor/monitor.js +385 -0
  254. package/src/monitor/performance-monitor.js +204 -0
  255. package/src/monitor/soa-monitor.js +628 -0
  256. package/src/multitenant/index.js +1 -0
  257. package/src/multitenant/tenant-manager.js +238 -0
  258. package/src/native/native-acceleration.js +3493 -0
  259. package/src/optimizer/adaptive-optimizer.js +666 -0
  260. package/src/optimizer/cse.js +383 -0
  261. package/src/optimizer/decorrelator.js +958 -0
  262. package/src/optimizer/derived-table-eliminator.js +367 -0
  263. package/src/optimizer/explain-visualizer.js +266 -0
  264. package/src/optimizer/histogram.js +290 -0
  265. package/src/optimizer/index.js +78 -0
  266. package/src/optimizer/jit-compiler.js +1200 -0
  267. package/src/optimizer/join-order-optimizer.js +717 -0
  268. package/src/optimizer/limit-pushdown.js +70 -0
  269. package/src/optimizer/optimized-plan.js +54 -0
  270. package/src/optimizer/optimizer-rule.js +295 -0
  271. package/src/optimizer/optimizer.js +1515 -0
  272. package/src/optimizer/pipeline.js +263 -0
  273. package/src/optimizer/predicate-pushdown.js +599 -0
  274. package/src/optimizer/query-plan-cache.js +275 -0
  275. package/src/optimizer/rule-adapters.js +343 -0
  276. package/src/optimizer/subquery-flattener.js +689 -0
  277. package/src/optimizer/timestamp-query-rewriter.js +498 -0
  278. package/src/orm/collection.js +160 -0
  279. package/src/orm/errors.js +76 -0
  280. package/src/orm/hooks.js +184 -0
  281. package/src/orm/index.js +93 -0
  282. package/src/orm/mixins/soft-delete.js +271 -0
  283. package/src/orm/model.js +951 -0
  284. package/src/orm/query-builder.js +681 -0
  285. package/src/orm/relations.js +303 -0
  286. package/src/orm/schema.js +443 -0
  287. package/src/orm/seeder.js +350 -0
  288. package/src/parallel/dml-pushdown-executor.js +430 -0
  289. package/src/parallel/dml-worker.js +151 -0
  290. package/src/parallel/morsel-queue.js +358 -0
  291. package/src/parallel/parallel-executor.js +277 -0
  292. package/src/parallel/pipeline-executor.js +423 -0
  293. package/src/parallel/shared-cache.js +206 -0
  294. package/src/parser/ast.js +3853 -0
  295. package/src/parser/parser.js +7909 -0
  296. package/src/parser/tokenizer.js +542 -0
  297. package/src/query/relation-preloader.js +327 -0
  298. package/src/replication/index.js +15 -0
  299. package/src/replication/lag-monitor.js +163 -0
  300. package/src/replication/master.js +117 -0
  301. package/src/replication/multi-master.js +495 -0
  302. package/src/replication/read-replica.js +490 -0
  303. package/src/replication/replica.js +395 -0
  304. package/src/replication/replication-http-transport.js +421 -0
  305. package/src/replication/wal-standby.js +334 -0
  306. package/src/runtime/index.js +4 -0
  307. package/src/runtime/plpgsql-interpreter.js +766 -0
  308. package/src/runtime/plpgsql-parser.js +852 -0
  309. package/src/runtime/stored-procedure.js +149 -0
  310. package/src/runtime/udf.js +194 -0
  311. package/src/schema/dsl-parser.js +896 -0
  312. package/src/schema/index.js +113 -0
  313. package/src/schema/introspector.js +246 -0
  314. package/src/schema/pg-migrator.js +599 -0
  315. package/src/schema/schema-differ.js +504 -0
  316. package/src/schema/schema-versioning.js +426 -0
  317. package/src/schema/type-generator.js +537 -0
  318. package/src/sdk/README.md +277 -0
  319. package/src/sdk/go/README.md +19 -0
  320. package/src/sdk/go/go.mod +3 -0
  321. package/src/sdk/go/pureclient/client.go +663 -0
  322. package/src/sdk/go/pureclient/client_test.go +413 -0
  323. package/src/sdk/java/README.md +19 -0
  324. package/src/sdk/java/pom.xml +87 -0
  325. package/src/sdk/java/pureclient/JsonUtil.java +366 -0
  326. package/src/sdk/java/pureclient/PureClient.java +835 -0
  327. package/src/sdk/java/pureclient/PureClientTest.java +570 -0
  328. package/src/sdk/java/pureclient/PureError.java +158 -0
  329. package/src/sdk/java/pureclient/Transaction.java +242 -0
  330. package/src/sdk/javascript/README.md +19 -0
  331. package/src/sdk/javascript/cdc.js +230 -0
  332. package/src/sdk/javascript/client.js +420 -0
  333. package/src/sdk/javascript/errors.js +66 -0
  334. package/src/sdk/javascript/index.js +35 -0
  335. package/src/sdk/javascript/pool.js +199 -0
  336. package/src/sdk/javascript/transaction.js +114 -0
  337. package/src/sdk/php/README.md +19 -0
  338. package/src/sdk/php/composer.json +30 -0
  339. package/src/sdk/php/src/PureClient.php +550 -0
  340. package/src/sdk/php/src/PureError.php +130 -0
  341. package/src/sdk/php/src/Transaction.php +172 -0
  342. package/src/sdk/public-api.js +16 -0
  343. package/src/sdk/python/README.md +19 -0
  344. package/src/sdk/python/pure_client.py +388 -0
  345. package/src/sdk/react-native/README.md +161 -0
  346. package/src/sdk/react-native/async-storage-adapter.js +147 -0
  347. package/src/sdk/react-native/embedded/embedded-client.js +266 -0
  348. package/src/sdk/react-native/embedded/hermes-jsi-bridge.js +207 -0
  349. package/src/sdk/react-native/embedded/sqlite-kv-adapter.js +345 -0
  350. package/src/sdk/react-native/expo-file-adapter.js +315 -0
  351. package/src/sdk/react-native/index.js +52 -0
  352. package/src/sdk/react-native/mobile-client.js +759 -0
  353. package/src/sdk/react-native/sync-manager.js +455 -0
  354. package/src/sdk/react-native/vector-search.js +322 -0
  355. package/src/sdk/rust/CHANGELOG.md +104 -0
  356. package/src/sdk/rust/Cargo.toml +35 -0
  357. package/src/sdk/rust/LICENSE +21 -0
  358. package/src/sdk/rust/PUBLISHING.md +202 -0
  359. package/src/sdk/rust/README.md +471 -0
  360. package/src/sdk/rust/RELEASE-CHECKLIST.md +340 -0
  361. package/src/sdk/rust/examples/basic_usage.rs +181 -0
  362. package/src/sdk/rust/scripts/publish.sh +233 -0
  363. package/src/sdk/rust/src/client.rs +481 -0
  364. package/src/sdk/rust/src/error.rs +95 -0
  365. package/src/sdk/rust/src/index/hnswpq.rs +626 -0
  366. package/src/sdk/rust/src/index/mod.rs +7 -0
  367. package/src/sdk/rust/src/lib.rs +66 -0
  368. package/src/sdk/rust/src/models.rs +198 -0
  369. package/src/sdk/rust/src/transaction.rs +123 -0
  370. package/src/sdk/rust/tests/concurrent_vector_search.rs +534 -0
  371. package/src/sdk/wechat/README.md +19 -0
  372. package/src/sdk/wechat/index.js +42 -0
  373. package/src/sdk/wechat/pure-js-db.js +105 -0
  374. package/src/sdk/wechat/stubs/empty.js +85 -0
  375. package/src/sdk/wechat/wx-database.js +225 -0
  376. package/src/sdk/wechat/wx-lite.js +191 -0
  377. package/src/sdk/wechat/wx-sqlite-adapter.js +655 -0
  378. package/src/sdk/wechat/wx-sqlite-database.js +146 -0
  379. package/src/sdk/wechat/wx-storage-adapter.js +609 -0
  380. package/src/security/api-key.js +215 -0
  381. package/src/security/auth.js +179 -0
  382. package/src/security/column-encryption-optimized.js +352 -0
  383. package/src/security/column-encryption.js +330 -0
  384. package/src/security/crypto-provider.js +345 -0
  385. package/src/security/data-masking.js +370 -0
  386. package/src/security/field-encryption.js +238 -0
  387. package/src/security/index.js +41 -0
  388. package/src/security/jwt.js +202 -0
  389. package/src/security/rbac.js +702 -0
  390. package/src/security/regex-guard.js +277 -0
  391. package/src/security/row-level-security.js +192 -0
  392. package/src/security/secure-erase.js +258 -0
  393. package/src/security/sql-firewall.js +185 -0
  394. package/src/security/sql-injection-detector.js +647 -0
  395. package/src/security/sql-rate-limiter.js +168 -0
  396. package/src/security/ssrf-guard.js +790 -0
  397. package/src/security/timing-safe.js +203 -0
  398. package/src/serializer/codecs.js +1155 -0
  399. package/src/serializer/index.js +13 -0
  400. package/src/serializer/serializer.js +468 -0
  401. package/src/server/public-api.js +14 -0
  402. package/src/server.js +31 -0
  403. package/src/service/log-service.js +593 -0
  404. package/src/sharding/cluster-manager.js +161 -0
  405. package/src/sharding/consistent-hash-ring-optimized.js +421 -0
  406. package/src/sharding/consistent-hash-ring.js +252 -0
  407. package/src/sharding/consistent-hash.js +175 -0
  408. package/src/sharding/distributed-executor.js +120 -0
  409. package/src/sharding/distributed-lock.js +256 -0
  410. package/src/sharding/distributed-transaction.js +262 -0
  411. package/src/sharding/failure-recovery.js +267 -0
  412. package/src/sharding/global-tx-coordinator.js +1299 -0
  413. package/src/sharding/index.js +16 -0
  414. package/src/sharding/parallel-write-coordinator.js +370 -0
  415. package/src/sharding/partition-manager.js +382 -0
  416. package/src/sharding/pushdown-executor.js +1101 -0
  417. package/src/sharding/scatter-gather-executor.js +460 -0
  418. package/src/sharding/shard-executor.js +624 -0
  419. package/src/sharding/shard-manager.js +717 -0
  420. package/src/sharding/three-phase-commit.js +699 -0
  421. package/src/sharding/two-phase-commit.js +1243 -0
  422. package/src/snapshot/historical-reader.js +257 -0
  423. package/src/snapshot/index.js +7 -0
  424. package/src/storage/batch-writer.js +110 -0
  425. package/src/storage/binary-storage-adapter.js +738 -0
  426. package/src/storage/blob-kv-adapter.js +253 -0
  427. package/src/storage/buffer-pool.js +458 -0
  428. package/src/storage/buffered-kv-adapter.js +325 -0
  429. package/src/storage/cold-data-migrator.js +519 -0
  430. package/src/storage/column-compression.js +878 -0
  431. package/src/storage/column-store-table.js +627 -0
  432. package/src/storage/column-store.js +1094 -0
  433. package/src/storage/columnar-file.js +489 -0
  434. package/src/storage/columnar-storage.js +485 -0
  435. package/src/storage/compact-recovery.js +394 -0
  436. package/src/storage/encrypted-kv-adapter.js +271 -0
  437. package/src/storage/file-kv-adapter.js +468 -0
  438. package/src/storage/hybrid-engine.js +1480 -0
  439. package/src/storage/importer.js +125 -0
  440. package/src/storage/in-memory-table-storage.js +291 -0
  441. package/src/storage/index.js +78 -0
  442. package/src/storage/io-thread-pool.js +240 -0
  443. package/src/storage/io-worker.js +42 -0
  444. package/src/storage/kv-adapter.js +322 -0
  445. package/src/storage/lsm/active-table.js +240 -0
  446. package/src/storage/lsm/block-cache.js +64 -0
  447. package/src/storage/lsm/bloom-filter.js +174 -0
  448. package/src/storage/lsm/compactor.js +460 -0
  449. package/src/storage/lsm/database-manager.js +177 -0
  450. package/src/storage/lsm/full-text-search.js +385 -0
  451. package/src/storage/lsm/index.js +14 -0
  452. package/src/storage/lsm/internal-key.js +140 -0
  453. package/src/storage/lsm/lsm-engine.js +798 -0
  454. package/src/storage/lsm/lsm-kv-adapter.js +137 -0
  455. package/src/storage/lsm/memtable.js +628 -0
  456. package/src/storage/lsm/mmap-region.js +289 -0
  457. package/src/storage/lsm/sstable-reader.js +403 -0
  458. package/src/storage/lsm/sstable-repair.js +437 -0
  459. package/src/storage/lsm/sstable-writer.js +202 -0
  460. package/src/storage/lsm/wal.js +800 -0
  461. package/src/storage/offheap-allocator.js +298 -0
  462. package/src/storage/page-checksum.js +221 -0
  463. package/src/storage/page-compression.js +95 -0
  464. package/src/storage/page-store.js +418 -0
  465. package/src/storage/page.js +261 -0
  466. package/src/storage/persisted-db.js +1885 -0
  467. package/src/storage/persisted-table-storage.js +280 -0
  468. package/src/storage/read-ahead.js +95 -0
  469. package/src/storage/shared-storage.js +688 -0
  470. package/src/storage/soa-table-storage.js +418 -0
  471. package/src/storage/storage-engine.js +187 -0
  472. package/src/storage/table-storage.js +215 -0
  473. package/src/storage/tiered-kv-adapter.js +381 -0
  474. package/src/storage/version-history-cleaner.js +888 -0
  475. package/src/studio/index.html +1503 -0
  476. package/src/studio/server.js +204 -0
  477. package/src/sync/change-log.js +144 -0
  478. package/src/sync/index.js +2 -0
  479. package/src/sync/sync-engine.js +428 -0
  480. package/src/sync/sync-handlers.js +196 -0
  481. package/src/test-utils.js +11 -0
  482. package/src/transaction/index.js +8 -0
  483. package/src/transaction/read-uncommitted.js +37 -0
  484. package/src/transaction/repeatable-read.js +380 -0
  485. package/src/transaction/rr-transaction-manager.js +262 -0
  486. package/src/transaction/ru-transaction-manager.js +76 -0
  487. package/src/transaction/serializable.js +205 -0
  488. package/src/transaction/transaction-manager.js +259 -0
  489. package/src/transaction/tx-manager.js +490 -0
  490. package/src/transaction/tx-state.js +43 -0
  491. package/src/tx/bfmark-snapshot.js +193 -0
  492. package/src/tx/row-lock.js +246 -0
  493. package/src/tx/ssi.js +229 -0
  494. package/src/types/datetime.js +621 -0
  495. package/src/types/decimal.js +220 -0
  496. package/src/types/enum-type.js +131 -0
  497. package/src/types/interval.js +565 -0
  498. package/src/types/json-type.js +376 -0
  499. package/src/types/jsonb.js +227 -0
  500. package/src/types/udt.js +180 -0
  501. package/src/utils/batch-processor.js +46 -0
  502. package/src/utils/debug-logger.js +116 -0
  503. package/src/utils/index-helper.js +74 -0
  504. package/src/utils/index.js +9 -0
  505. package/src/utils/join-engine.js +1713 -0
  506. package/src/utils/object-pool.js +610 -0
  507. package/src/utils/query-tracer.js +489 -0
  508. package/src/utils/timeout-util.js +92 -0
  509. package/src/utils/tx-log-persist.js +197 -0
  510. package/src/utils/undo-compress.js +93 -0
  511. package/src/utils/undo-log.js +196 -0
  512. package/src/utils/wal-common.js +138 -0
  513. package/src/vector/adaptive-ef.js +213 -0
  514. package/src/vector/distributed-vector-search.js +542 -0
  515. package/src/vector/federated-vector-search.js +707 -0
  516. package/src/vector/gpu-distance.js +647 -0
  517. package/src/vector/gpu-sq-distance.js +444 -0
  518. package/src/vector/hnsw-acceleration.js +298 -0
  519. package/src/vector/hnsw-profiler.js +341 -0
  520. package/src/vector/index.js +90 -0
  521. package/src/vector/public-api.js +29 -0
  522. package/src/vector/recall-benchmark.js +333 -0
  523. package/src/vector/simd-distance.js +511 -0
  524. package/src/vector/vector-scan.js +646 -0
  525. package/src/vector/wasm-hnsw.js +714 -0
  526. package/src/version/version-chain-manager.js +1277 -0
  527. package/src/version/version-delta-encoder.js +819 -0
  528. package/src/version.js +19 -0
  529. package/src/view/incremental-refresher.js +1015 -0
  530. package/src/view/index.js +12 -0
  531. package/src/view/materialized-view.js +204 -0
  532. package/src/view/view-manager.js +1368 -0
  533. package/src/wasm/bridge.js +79 -0
  534. package/src/worker/query-dispatcher.js +277 -0
  535. package/src/worker/session-worker-pool.js +355 -0
  536. package/src/worker/task-defs.js +330 -0
  537. package/src/worker/task-worker.js +406 -0
  538. package/src/worker/worker-pool.js +651 -0
  539. package/src/xml/xml-support.js +647 -0
  540. package/types/pure-js-db.d.ts +1988 -0
  541. package/types/schema.d.ts +65 -0
@@ -0,0 +1,1182 @@
1
+ /**
2
+ * http-api.js — Pure-JS-DB HTTP API 封装
3
+ *
4
+ * 使用 Node.js 内置 http 模块(零外部依赖),提供 RESTful JSON API。
5
+ * 路由:
6
+ * POST /api/query — 执行 SQL
7
+ * GET /api/tables — 列出所有表
8
+ * GET /api/tables/:name — 描述表结构
9
+ * POST /api/explain — EXPLAIN 查询计划
10
+ * GET /api/stats — 数据库统计信息
11
+ * GET /api/v1/schema — 完整 schema 元数据(v1.14.0 新增)
12
+ * GET /api/v1/schema/:table — 单表 schema 元数据
13
+ * GET /api/v2/:table/rows — 分页查询(limit/offset/sort/filter)
14
+ * POST /api/v2/:table/rows — 插入单行或多行
15
+ * GET /api/v2/:table/rows/:id — 按主键查询单行
16
+ * PUT /api/v2/:table/rows/:id — 按主键更新单行
17
+ * DELETE /api/v2/:table/rows/:id — 按主键删除单行
18
+ * GET /api/v2/:table/schema — 表元数据(含主键信息)
19
+ */
20
+
21
+ import http from 'node:http';
22
+ import { performance } from 'node:perf_hooks';
23
+ import fs from 'node:fs/promises';
24
+ import path from 'node:path';
25
+
26
+ import { URL } from 'node:url';
27
+ import { Executor } from './executor/executor.js';
28
+ import { SchemaIntrospector } from './schema/introspector.js';
29
+ import { parseSQL } from './parser/parser.js';
30
+ import { SelectStatement } from './parser/ast.js';
31
+ // H-03 修复(2026-08-14):SQL 注入检测器默认接入 HTTP API 路径
32
+ import { SQLInjectionDetector } from './security/sql-injection-detector.js';
33
+ // 2026-10-27 UXR 修复:逻辑备份(供 /api/backup/* 使用)
34
+ import { LogicalBackup } from './backup/logical-backup.js';
35
+ // M-01 修复(2026-08-14):API Key 恒定时间比较
36
+
37
+ // M5 引擎级集成(2026-08-15):JWTManager / APIKeyManager / AuthManager 真集成
38
+ import { JWTManager } from './security/jwt.js';
39
+ import { APIKeyManager } from './security/api-key.js';
40
+ import { AuthManager } from './security/auth.js';
41
+ import { VERSION } from './version.js';
42
+
43
+ // ── 安全工具 ──
44
+
45
+ /**
46
+ * 校验表名是否存在于数据库(防止 SQL 注入)
47
+ */
48
+ function validateTableName(db, tableName) {
49
+ if (!db || !db.tables) {
50
+ return false;
51
+ }
52
+ return Object.prototype.hasOwnProperty.call(db.tables, tableName);
53
+ }
54
+
55
+ /**
56
+ * 校验列名是否存在于表结构(防止 SQL 注入)
57
+ */
58
+ function validateColumnName(table, columnName) {
59
+ if (!table?.columns) {
60
+ return false;
61
+ }
62
+ return table.columns.some(c => c.name === columnName);
63
+ }
64
+
65
+ /**
66
+ * 转义 SQL 字符串值(防止注入)
67
+ */
68
+ function escapeSQLValue(value) {
69
+ if (value === null || value === undefined) {
70
+ return 'NULL';
71
+ }
72
+ if (typeof value === 'number') {
73
+ return Number.isFinite(value) ? String(value) : 'NULL';
74
+ }
75
+ if (typeof value === 'boolean') {
76
+ return value ? '1' : '0';
77
+ }
78
+ // 字符串:转义单引号并包裹
79
+ return `'${String(value).replace(/'/g, "''")}'`;
80
+ }
81
+
82
+ /**
83
+ * 安全校验 filter 参数(P0-1 修复:防止 SQL 注入)
84
+ *
85
+ * 不再将用户输入的 filter 字符串直接拼接到 SQL WHERE 子句。
86
+ * 改为通过 SQL 解析器验证 filter 是安全的表达式:
87
+ * 1. 将 filter 包装为 SELECT * FROM _safe_ WHERE <filter>
88
+ * 2. 用 parseSQL 解析,检查是否为有效 SelectStatement
89
+ * 3. 拒绝含子查询、JOIN、CTE、UNION、多语句的 filter
90
+ *
91
+ * 通过校验后返回安全的 WHERE 子句字符串。
92
+ *
93
+ * @param {string} filter - 用户输入的 filter 参数
94
+ * @returns {string|null} 安全的 WHERE 子句,或 null(无效 filter)
95
+ */
96
+ function validateFilter(filter) {
97
+ if (!filter || typeof filter !== 'string') {
98
+ return null;
99
+ }
100
+ const trimmed = filter.trim();
101
+ if (!trimmed) {
102
+ return null;
103
+ }
104
+
105
+ // 第 1 道防线:拒绝明显危险模式
106
+ const dangerous = /\b(DROP|INSERT|DELETE|UPDATE|CREATE|ALTER|TRUNCATE|EXEC|EXECUTE|UNION|INTO|GRANT|REVOKE)\b/i;
107
+ if (dangerous.test(trimmed)) {
108
+ return null;
109
+ }
110
+
111
+ // 第 2 道防线:SQL 解析器验证
112
+ // 包装为 SELECT * FROM _safe_ WHERE <filter> 以复用 AST 验证
113
+ const parseResult = parseSQL(`SELECT * FROM _filter_validator_ WHERE ${trimmed}`);
114
+ if (!parseResult || parseResult.errors?.length > 0) {
115
+ return null;
116
+ }
117
+
118
+ const ast = parseResult.ast;
119
+ // 必须仅有一条 SELECT 语句(防止多语句注入)
120
+ if (!ast?.statements || ast.statements.length !== 1) {
121
+ return null;
122
+ }
123
+
124
+ const stmt = ast.statements[0];
125
+ if (!(stmt instanceof SelectStatement)) {
126
+ return null;
127
+ }
128
+
129
+ // 第 3 道防线:拒绝复杂结构(JOIN、CTE、子查询、UNION)
130
+ if (stmt.joins && stmt.joins.length > 0) {
131
+ return null;
132
+ }
133
+ if (stmt.cteList && stmt.cteList.length > 0) {
134
+ return null;
135
+ }
136
+ if (stmt.where && _containsSubquery(stmt.where)) {
137
+ return null;
138
+ }
139
+ if (stmt.groupBy && stmt.groupBy.length > 0) {
140
+ return null;
141
+ }
142
+ if (stmt.having) {
143
+ return null;
144
+ }
145
+
146
+ // 通过校验 → 返回安全的 WHERE 子句(已在解析器中被分词,无注入风险)
147
+ return `WHERE ${trimmed}`;
148
+ }
149
+
150
+ /**
151
+ * 检查表达式树是否包含子查询
152
+ *
153
+ * 覆盖所有子查询 AST 节点类型(src/parser/ast.js):
154
+ * - ScalarSubquery → 字段 selectStmt
155
+ * - InSubquery → 字段 subquery
156
+ * - ExistsSubquery → 字段 subquery
157
+ * - DerivedTable → 字段 subquery(FROM 子查询,正常 WHERE 不会出现但防御性处理)
158
+ *
159
+ * v1.40.3 修复:原实现仅检查 type==='SUBQUERY' / .subquery / .query,
160
+ * 漏检 ScalarSubquery(使用 selectStmt 字段),导致
161
+ * `id=(SELECT id FROM users WHERE name='Alice')` 通过校验 → SQL 注入。
162
+ *
163
+ * @param {object} expr - AST 表达式节点
164
+ * @returns {boolean}
165
+ */
166
+ function _containsSubquery(expr) {
167
+ if (!expr || typeof expr !== 'object') {
168
+ return false;
169
+ }
170
+ // 命中所有子查询节点类型(按类型名后缀 + 字段名双重判定)
171
+ if (expr.type === 'SUBQUERY' ||
172
+ expr.type === 'ScalarSubquery' ||
173
+ expr.type === 'InSubquery' ||
174
+ expr.type === 'ExistsSubquery' ||
175
+ expr.type === 'DerivedTable') {
176
+ return true;
177
+ }
178
+ // 字段判定:覆盖 selectStmt(ScalarSubquery)/ subquery(In/Exists/Derived)/ query(兼容旧名)
179
+ if (expr.subquery || expr.selectStmt || expr.query) {
180
+ return true;
181
+ }
182
+ // 递归遍历子节点
183
+ for (const key of Object.keys(expr)) {
184
+ // 跳过位置信息(loc)和已判定的字段,避免重复遍历
185
+ if (key === 'loc' || key === 'type') {
186
+ continue;
187
+ }
188
+ const val = expr[key];
189
+ if (Array.isArray(val)) {
190
+ if (val.some(v => _containsSubquery(v))) {
191
+ return true;
192
+ }
193
+ } else if (val && typeof val === 'object') {
194
+ if (_containsSubquery(val)) {
195
+ return true;
196
+ }
197
+ }
198
+ }
199
+ return false;
200
+ }
201
+
202
+ /**
203
+ * 解析 JSON 请求体(Promise 封装)
204
+ * 2026-08-14 M-03 修复:默认 1MB 大小限制,超限销毁连接(防内存 DoS)
205
+ * @param {object} req
206
+ * @param {number} [limit=1048576]
207
+ */
208
+ function parseBody(req, limit = 1048576) {
209
+ return new Promise((resolve, reject) => {
210
+ let body = '';
211
+ let totalBytes = 0;
212
+ req.on('data', chunk => {
213
+ totalBytes += chunk.length;
214
+ if (totalBytes > limit) {
215
+ reject(new Error('请求体超过大小限制'));
216
+ req.destroy();
217
+ return;
218
+ }
219
+ body += chunk;
220
+ });
221
+ req.on('end', () => {
222
+ try {
223
+ resolve(body ? JSON.parse(body) : {});
224
+ } catch (err) {
225
+ reject(new Error('请求体 JSON 解析失败'));
226
+ }
227
+ });
228
+ req.on('error', reject);
229
+ });
230
+ }
231
+
232
+ /**
233
+ * 统一错误响应(2026-08-14 M-06 修复:默认隐藏内部错误细节,防信息泄露)
234
+ * - NODE_ENV=development 时保留 err.message 便于调试
235
+ * - 其他环境(含未设置,生产默认)返回通用信息
236
+ * 2026-10-27 UXR 修复:响应增加稳定 code 字段;服务端始终记录错误日志,便于排查。
237
+ */
238
+ function sendError(res, err, statusCode = 500) {
239
+ const isDev = process.env.NODE_ENV === 'development';
240
+ const message = isDev ? (err?.message || '内部服务器错误') : '内部服务器错误';
241
+ const detail = isDev ? (err?.message || undefined) : undefined;
242
+ console.error(`[HttpApi] ${statusCode} 错误: ${err?.message || ''}`);
243
+ if (err?.stack) {
244
+ console.error(err.stack);
245
+ }
246
+ res.writeHead(statusCode, { 'Content-Type': 'application/json' });
247
+ res.end(JSON.stringify({
248
+ error: message,
249
+ ...(detail ? { detail } : {}),
250
+ code: statusCode,
251
+ }));
252
+ }
253
+
254
+ /**
255
+ * 从表结构推断主键列名(优先名为 'id' 的列,否则取第一列)
256
+ */
257
+ function inferPrimaryKey(table) {
258
+ if (!table?.columns?.length) {
259
+ return null;
260
+ }
261
+ const idCol = table.columns.find(c => c.name === 'id');
262
+ return idCol ? idCol.name : table.columns[0].name;
263
+ }
264
+
265
+ export class HttpApiServer {
266
+ /**
267
+ * @param {object} options
268
+ * @param {number} options.port - 监听端口(默认 3000)
269
+ * @param {string} [options.host] - 监听地址(默认 127.0.0.1;
270
+ * 2026-08-14 H-01 修复:零认证服务禁止绑定非回环地址,start() 会拒绝启动)
271
+ * @param {Executor} options.executor - 共享 Executor 实例
272
+ * @param {Object} [options.schema] - SchemaDslParser 解析的 schema 对象(用于富元数据)
273
+ * @param {string} [options.apiKey] - API Key 认证(配置后所有 API 需携带 X-API-Key)
274
+ * @param {string} [options.jwtSecret] - JWT HS256 密钥(配置后支持 Bearer 认证)
275
+ * @param {boolean} [options.enableInjectionCheck=true] - 是否自动接入 SQL 注入检测器(H-03 修复)
276
+ */
277
+ constructor(options = {}) {
278
+ this.port = options.port ?? 3000;
279
+ // v2.53.0 P0-7: 请求超时(查询在让出检查点被取消)
280
+ this._timeout = options.timeout ?? 30000;
281
+ // H-01 修复:默认仅绑定回环地址(原为未指定时绑定所有网卡)
282
+ this.host = options.host ?? '127.0.0.1';
283
+ this.executor = options.executor ?? new Executor();
284
+ this.schema = options.schema || null;
285
+ this.server = null;
286
+ // v1.34.6 安全加固
287
+ this._corsOrigins = Array.isArray(options.corsOrigins) ? options.corsOrigins : null;
288
+ this._trustUserIdHeader = options.trustUserIdHeader === true;
289
+ // H-01 修复:认证配置
290
+ this._apiKey = options.apiKey || null;
291
+ this._jwtSecret = options.jwtSecret || null;
292
+ // M5 引擎级集成(2026-08-15):用 JWTManager / APIKeyManager 替换内联实现
293
+ this._jwtManager = options.jwtSecret
294
+ ? new JWTManager({ secret: options.jwtSecret })
295
+ : null;
296
+ this._defaultApiKey = options.apiKey || null;
297
+ this._apiKeyManager = options.apiKey ? (() => {
298
+ const mgr = new APIKeyManager();
299
+ // P2-5(2026-10-27):使用用户配置的 apiKey 值注册,而不是随机生成新 key。
300
+ // 此前随机生成导致 options.apiKey 配置完全失效(请求侧用配置值永远 401)。
301
+ mgr.register(options.apiKey, 'configured', ['read', 'write']);
302
+ return mgr;
303
+ })() : null;
304
+ this._authManager = new AuthManager();
305
+ // M5:认证白名单(注册/登录端点无需认证即可访问)
306
+ this._authWhitelist = options.authWhitelist ?? ['/api/auth/register', '/api/auth/login', '/openapi.json', '/api-docs'];
307
+ // H-03 修复(2026-08-14):SQL 注入检测器接入用户 SQL 直通端点
308
+ // (POST /api/query、/api/explain)。不注入 executor 全局路径——
309
+ // 服务端内部生成的 SQL(v2 CRUD 转义/参数化、sync、CDC)由转义逻辑保证安全,
310
+ // 全局注入会对含 DROP 等关键字的合法字面量产生误报。
311
+ this._injectionDetector = options.enableInjectionCheck === false
312
+ ? null
313
+ : new SQLInjectionDetector();
314
+ // 2026-10-27 加固(M-4):服务器层安全模块接线(默认关闭,显式传入才生效)——
315
+ // 与 DBServer 对齐:HTTP API 部署可通过 options 注入 RBAC/防火墙/限流/RLS 到 executor。
316
+ if (options.rbac) {
317
+ this.executor.setRBAC(options.rbac);
318
+ }
319
+ if (options.sqlFirewall) {
320
+ this.executor.setSQLFirewall(options.sqlFirewall);
321
+ }
322
+ if (options.rateLimiter) {
323
+ this.executor.setRateLimiter(options.rateLimiter);
324
+ }
325
+ if (options.rls) {
326
+ this.executor.setRowLevelSecurity(options.rls);
327
+ }
328
+ // 2026-10-27 加固(H-2):认证端点 DoS 防护。register/login 是免认证白名单端点,
329
+ // 且无论成败每次都执行一次 scrypt(N=16384,实测 ~56ms CPU/次,同步阻塞事件循环)。
330
+ // 无速率限制时,攻击者可用 ~20 并发慢请求持续占满单线程事件循环。
331
+ // 防线:per-IP 固定窗口 + 全局固定窗口(超限直接 429,不触达 scrypt)。
332
+ this._authRateLimitPerIp = Math.max(1, options.authRateLimitPerIp ?? 10);
333
+ this._authRateLimitGlobal = Math.max(this._authRateLimitPerIp, options.authRateLimitGlobal ?? 60);
334
+ this._authRateWindowMs = Math.max(1000, options.authRateWindowMs ?? 60_000);
335
+ /** @type {Map<string, {count: number, start: number}>} ip → 计数(有界,防内存膨胀) */
336
+ this._authRatePerIp = new Map();
337
+ this._authRateGlobal = { count: 0, start: 0 };
338
+ // 2026-10-27 UXR 修复:查询监控统计(供 /api/monitor/stats 使用)
339
+ this._queryStats = {
340
+ totalQueries: 0,
341
+ errors: 0,
342
+ totalLatencyMs: 0,
343
+ slowQueryLog: [], // { sql, duration, timestamp },最多保留 20 条
344
+ };
345
+ }
346
+
347
+ /**
348
+ * 认证端点速率检查(固定窗口,2026-10-27 加固 #5)
349
+ * @param {string} ip - 客户端 IP(socket.remoteAddress)
350
+ * @returns {{ allowed: boolean, retryAfterSec: number }}
351
+ * @private
352
+ */
353
+ _checkAuthRateLimit(ip) {
354
+ const now = Date.now();
355
+ const windowMs = this._authRateWindowMs;
356
+
357
+ // 全局窗口
358
+ if (now - this._authRateGlobal.start > windowMs) {
359
+ this._authRateGlobal = { count: 0, start: now };
360
+ }
361
+ this._authRateGlobal.count++;
362
+ if (this._authRateGlobal.count > this._authRateLimitGlobal) {
363
+ return { allowed: false, retryAfterSec: Math.ceil((this._authRateGlobal.start + windowMs - now) / 1000) };
364
+ }
365
+
366
+ // per-IP 窗口(Map 有界:超限时淘汰最旧条目)
367
+ let entry = this._authRatePerIp.get(ip);
368
+ if (!entry || now - entry.start > windowMs) {
369
+ entry = { count: 0, start: now };
370
+ this._authRatePerIp.set(ip, entry);
371
+ if (this._authRatePerIp.size > 10_000) {
372
+ for (const [k, v] of this._authRatePerIp) {
373
+ if (now - v.start > windowMs) {
374
+ this._authRatePerIp.delete(k);
375
+ }
376
+ if (this._authRatePerIp.size <= 10_000) {
377
+ break;
378
+ }
379
+ }
380
+ }
381
+ }
382
+ entry.count++;
383
+ if (entry.count > this._authRateLimitPerIp) {
384
+ return { allowed: false, retryAfterSec: Math.ceil((entry.start + windowMs - now) / 1000) };
385
+ }
386
+ return { allowed: true, retryAfterSec: 0 };
387
+ }
388
+
389
+ /**
390
+ * 用户 SQL 直通前的注入检测(命中 critical/high 即拒绝)
391
+ * @param {string} sql
392
+ * @returns {string|null} 拒绝时的错误信息,null 表示放行
393
+ * @private
394
+ */
395
+ _checkSqlInjection(sql) {
396
+ if (!this._injectionDetector || typeof sql !== 'string') {
397
+ return null;
398
+ }
399
+ const result = this._injectionDetector.detect(sql);
400
+ if (result.detected && (result.severity === 'critical' || result.severity === 'high')) {
401
+ return `SQL 注入检测:检测到 ${result.type}(severity=${result.severity})`;
402
+ }
403
+ return null;
404
+ }
405
+
406
+ /** 是否已配置认证(JWTManager 或 APIKeyManager) */
407
+ get authEnabled() {
408
+ return !!(this._jwtManager || this._apiKeyManager);
409
+ }
410
+
411
+ /** 默认 API Key 明文值(仅用于测试/运维;生产环境不应暴露) */
412
+ get defaultApiKey() {
413
+ return this._defaultApiKey;
414
+ }
415
+
416
+ /**
417
+ * JWT HS256 验证(委托给 JWTManager,恒定时间签名比较)
418
+ * @private
419
+ */
420
+ _verifyJWT(token) {
421
+ try {
422
+ return this._jwtManager ? this._jwtManager.verify(token) : null;
423
+ } catch {
424
+ return null;
425
+ }
426
+ }
427
+
428
+ /**
429
+ * 根据 CORS 白名单解析 Origin(v1.34.6 P2-2 修复)
430
+ * @private
431
+ */
432
+ _resolveCorsOrigin(requestOrigin) {
433
+ // 显式白名单(不含 '*'):精确匹配
434
+ if (this._corsOrigins && this._corsOrigins.length > 0 && !this._corsOrigins.includes('*')) {
435
+ if (!requestOrigin) {
436
+ return this._corsOrigins[0];
437
+ }
438
+ return this._corsOrigins.includes(requestOrigin) ? requestOrigin : 'null';
439
+ }
440
+ // 显式配置含 '*':允许任意跨源
441
+ if (this._corsOrigins && this._corsOrigins.includes('*')) {
442
+ return '*';
443
+ }
444
+ // 未配置白名单:默认拒绝跨源(收紧默认值)
445
+ return 'null';
446
+ }
447
+
448
+ /**
449
+ * 启动 HTTP 服务器
450
+ * 2026-08-14 H-01 修复:零认证 + 非回环绑定 → 拒绝启动(fail-closed)
451
+ */
452
+ start() {
453
+ const isLoopback = this.host === '127.0.0.1' || this.host === 'localhost' || this.host === '::1';
454
+ if (!this.authEnabled && !isLoopback) {
455
+ return Promise.reject(new Error(
456
+ '安全拒绝启动:未配置认证(apiKey/jwtSecret)时禁止绑定非回环地址 ' +
457
+ `(${this.host}:${this.port})。请配置认证后启动,或显式绑定 127.0.0.1。`,
458
+ ));
459
+ }
460
+ if (!this.authEnabled) {
461
+ console.warn('⚠️ 高危警告:HTTP API 以零认证模式启动(仅限本机 127.0.0.1)。' +
462
+ '生产部署必须配置 apiKey/jwtSecret,否则任何能访问本机端口的进程均可执行任意 SQL。');
463
+ }
464
+ this.server = http.createServer((req, res) => this._handle(req, res));
465
+ return new Promise(resolve => {
466
+ this.server.listen(this.port, this.host, () => {
467
+ console.log(`HTTP API 启动: http://${this.host}:${this.port}`);
468
+ resolve();
469
+ });
470
+ });
471
+ }
472
+
473
+ /**
474
+ * 停止服务器
475
+ * @returns {Promise<void>} 服务器完全关闭后 resolve
476
+ */
477
+ stop() {
478
+ if (this.server) {
479
+ const server = this.server;
480
+ this.server = null;
481
+ // 强制关闭所有保持的连接(Keep-Alive),避免 libuv 句柄泄漏
482
+ server.closeAllConnections?.();
483
+ return new Promise(resolve => {
484
+ server.close(() => resolve());
485
+ // 兜底:如果 5 秒还没关闭,强制 resolve(防止 hang)
486
+ setTimeout(() => resolve(), 5000).unref?.();
487
+ });
488
+ }
489
+ return Promise.resolve();
490
+ }
491
+
492
+ async _handle(req, res) {
493
+ // v1.34.6 安全响应头 + CORS 白名单(P2-1/P2-2 修复)
494
+ res.setHeader('X-Content-Type-Options', 'nosniff');
495
+ res.setHeader('X-Frame-Options', 'DENY');
496
+ res.setHeader('X-XSS-Protection', '1; mode=block');
497
+ res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
498
+ res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
499
+ const requestOrigin = req.headers['origin'] || null;
500
+ res.setHeader('Access-Control-Allow-Origin', this._resolveCorsOrigin(requestOrigin));
501
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
502
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-API-Key, X-User-Id');
503
+ // M-02 修复(2026-08-14):'*' 与 Allow-Credentials 禁止共存,仅白名单具体 origin 时发送
504
+ const allowedOrigin = this._resolveCorsOrigin(requestOrigin);
505
+ if (allowedOrigin !== '*' && allowedOrigin !== 'null') {
506
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
507
+ }
508
+ res.setHeader('Vary', 'Origin');
509
+
510
+ if (req.method === 'OPTIONS') {
511
+ res.writeHead(204);
512
+ res.end();
513
+ return;
514
+ }
515
+
516
+ // 路由解析(必须在认证检查之前,whitelist 匹配需要 path)
517
+ const url = new URL(req.url, `http://localhost:${this.port}`);
518
+ const path = url.pathname;
519
+
520
+ // ── H-01 修复:认证检查(配置 apiKey/jwtSecret 后强制校验)──
521
+ if (this.authEnabled && !this._authWhitelist.includes(path)) {
522
+ const providedKey = req.headers['x-api-key'];
523
+ const authHeader = req.headers['authorization'];
524
+ const jwtToken = authHeader && authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
525
+ let authed = false;
526
+ if (jwtToken && this._jwtManager) {
527
+ try {
528
+ authed = !!this._jwtManager.verify(jwtToken);
529
+ } catch {
530
+ authed = false;
531
+ }
532
+ }
533
+ if (!authed && providedKey && this._apiKeyManager) {
534
+ authed = !!this._apiKeyManager.verify(providedKey);
535
+ }
536
+ if (!authed) {
537
+ // 2026-10-27 契约对齐:错误体统一为 {"error": true, "message": "..."}(error 为布尔)
538
+ const body = JSON.stringify({
539
+ error: true,
540
+ message: '无效或缺失的认证凭据(API Key 或 JWT)',
541
+ code: 401,
542
+ });
543
+ res.writeHead(401, {
544
+ 'Content-Type': 'application/json; charset=utf-8',
545
+ 'Content-Length': Buffer.byteLength(body),
546
+ });
547
+ res.end(body);
548
+ return;
549
+ }
550
+ }
551
+
552
+ try {
553
+ // ── 2026-10-27 加固 #5:认证端点速率限制(免认证白名单 + scrypt 同步阻塞 → DoS 面)──
554
+ if (path === '/api/auth/register' || path === '/api/auth/login') {
555
+ const rl = this._checkAuthRateLimit(req.socket?.remoteAddress || 'unknown');
556
+ if (!rl.allowed) {
557
+ res.writeHead(429, {
558
+ 'Content-Type': 'application/json',
559
+ 'Retry-After': String(rl.retryAfterSec),
560
+ });
561
+ res.end(JSON.stringify({ error: '认证端点请求过于频繁,请稍后重试', code: 429 }));
562
+ return;
563
+ }
564
+ }
565
+
566
+ // ── v2 自动 CRUD 路由 ──
567
+ if (path.startsWith('/api/v2/')) {
568
+ await this._handleV2(req, res, url);
569
+ return;
570
+ }
571
+
572
+ if (path === '/api/query' && req.method === 'POST') {
573
+ this._handleQuery(req, res);
574
+ } else if (path === '/api/tables' && req.method === 'GET') {
575
+ this._handleListTables(res);
576
+ } else if (path.startsWith('/api/tables/') && req.method === 'GET') {
577
+ // /api/tables/:tableName
578
+ const tableName = path.split('/')[3];
579
+ this._handleDescribeTable(tableName, res);
580
+ } else if (path === '/api/explain' && req.method === 'POST') {
581
+ this._handleExplain(req, res);
582
+ } else if (path === '/api/stats' && req.method === 'GET') {
583
+ this._handleStats(res);
584
+ } else if (path === '/api/health' && req.method === 'GET') {
585
+ this._handleHealth(res);
586
+ } else if (path === '/api/monitor/stats' && req.method === 'GET') {
587
+ this._handleMonitorStats(res);
588
+ } else if (path === '/api/backup/history' && req.method === 'GET') {
589
+ await this._handleBackupHistory(res);
590
+ } else if (path === '/api/backup/full' && req.method === 'POST') {
591
+ await this._handleBackupCreate(res, 'full');
592
+ } else if (path === '/api/backup/incremental' && req.method === 'POST') {
593
+ await this._handleBackupCreate(res, 'incremental');
594
+ } else if (path === '/api/v1/schema' && req.method === 'GET') {
595
+ this._handleSchemaIntrospection(res);
596
+ } else if (path.startsWith('/api/v1/schema/') && req.method === 'GET') {
597
+ const tableName = path.split('/')[4];
598
+ this._handleTableSchema(tableName, res);
599
+ } else if (path === '/api/auth/register' && req.method === 'POST') {
600
+ await this._handleAuthRegister(req, res);
601
+ } else if (path === '/api/auth/login' && req.method === 'POST') {
602
+ await this._handleAuthLogin(req, res);
603
+ } else {
604
+ res.writeHead(404, { 'Content-Type': 'application/json' });
605
+ res.end(JSON.stringify({ error: 'Not Found' }));
606
+ }
607
+ } catch (err) {
608
+ sendError(res, err, 500);
609
+ }
610
+ }
611
+
612
+ async _handleQuery(req, res) {
613
+ let body;
614
+ try {
615
+ body = await parseBody(req);
616
+ } catch (err) {
617
+ sendError(res, err, 400);
618
+ return;
619
+ }
620
+ const startTime = performance.now();
621
+ try {
622
+ const { sql, params, variables } = body;
623
+ // H-03 修复:用户 SQL 直通前注入检测(critical/high 拒绝)
624
+ const injectionMsg = this._checkSqlInjection(sql);
625
+ if (injectionMsg) {
626
+ this._recordQuery(sql, startTime, true);
627
+ res.writeHead(400, { 'Content-Type': 'application/json' });
628
+ res.end(JSON.stringify({ error: injectionMsg }));
629
+ return;
630
+ }
631
+ // v1.34.6 P0-X 修复:默认禁止 X-User-Id 头部身份注入
632
+ // 原代码无条件信任 X-User-Id 头,攻击者可伪造任意身份绕过 RBAC
633
+ const headerUserId = req.headers['x-user-id'] || null;
634
+ const userId = this._trustUserIdHeader ? headerUserId : null;
635
+ if (headerUserId && !this._trustUserIdHeader) {
636
+ console.warn(`[HttpApi] 拒绝 X-User-Id 头部注入: ${headerUserId}(trustUserIdHeader=false)`);
637
+ }
638
+ this.executor.currentUserId = userId;
639
+ // v2.53.0 P0-7: 旧 http-api 查询路径迁移到 executeSQLAsync 并支持请求级取消。
640
+ // 修复:executeSQL(sql, params=[], options={}) —— 之前把 {params,variables}
641
+ // 当作 params 传入导致所有 ? 占位符绑定为 NULL(参数化查询静默失效)。
642
+ // 现改走 executeSQLAsync(分片让出路径),并监听客户端断开/超时取消查询。
643
+ const controller = new AbortController();
644
+ let aborted = false;
645
+ const abortWith = (reason) => {
646
+ if (!aborted) {
647
+ aborted = true;
648
+ controller.abort(new Error(reason));
649
+ }
650
+ };
651
+ const onClose = () => {
652
+ if (!res || !res.writableEnded) {
653
+ abortWith('查询已取消(客户端断开连接)');
654
+ }
655
+ };
656
+ res.on('close', onClose);
657
+ const timer = setTimeout(
658
+ () => abortWith('查询超时(服务端中止,' + this._timeout + 'ms)'),
659
+ this._timeout,
660
+ );
661
+ let result;
662
+ try {
663
+ result = await this.executor.executeSQLAsync(sql, params, { variables, signal: controller.signal });
664
+ } finally {
665
+ clearTimeout(timer);
666
+ res.removeListener('close', onClose);
667
+ }
668
+ this._recordQuery(sql, startTime, false);
669
+ res.writeHead(200, { 'Content-Type': 'application/json' });
670
+ res.end(JSON.stringify(result));
671
+ } catch (err) {
672
+ this._recordQuery('', startTime, true);
673
+ // v2.53.0 P0-7: 取消/超时返回 408,便于客户端区分
674
+ if (err && (err.code === 'QUERY_ABORTED' || /查询已取消|查询超时/.test(err?.message || ''))) {
675
+ res.writeHead(408, { 'Content-Type': 'application/json' });
676
+ res.end(JSON.stringify({ error: err.message }));
677
+ return;
678
+ }
679
+ sendError(res, err, 500);
680
+ }
681
+ }
682
+
683
+ /**
684
+ * 记录一次查询的监控统计(2026-10-27 UXR 修复)。
685
+ * @private
686
+ */
687
+ _recordQuery(sql, startTime, isError) {
688
+ const durationMs = Math.max(0, performance.now() - startTime);
689
+ const s = this._queryStats;
690
+ s.totalQueries += 1;
691
+ s.totalLatencyMs += durationMs;
692
+ if (isError) {
693
+ s.errors += 1;
694
+ }
695
+ if (durationMs > 100) {
696
+ s.slowQueryLog.unshift({
697
+ sql: typeof sql === 'string' ? sql.slice(0, 500) : String(sql || '').slice(0, 500),
698
+ duration: Number(durationMs.toFixed(2)),
699
+ timestamp: new Date().toISOString(),
700
+ });
701
+ if (s.slowQueryLog.length > 20) {
702
+ s.slowQueryLog.length = 20;
703
+ }
704
+ }
705
+ }
706
+
707
+ _handleListTables(res) {
708
+ const db = this.executor.db;
709
+ // v2.51.0: 物化视图也作为关系列出
710
+ const tableNames = db ? [
711
+ ...Object.keys(db.tables || {}),
712
+ ...(typeof db.listMaterializedViews === 'function' ? db.listMaterializedViews() : []),
713
+ ] : [];
714
+ const tables = tableNames.map(name => {
715
+ const table = db.getTable(name);
716
+ return {
717
+ name,
718
+ columns: table.columns,
719
+ rowCount: table.rows?.length || 0,
720
+ isMaterializedView: !!table.isMaterializedView,
721
+ };
722
+ });
723
+ res.writeHead(200, { 'Content-Type': 'application/json' });
724
+ res.end(JSON.stringify({ tables }));
725
+ }
726
+
727
+ _handleDescribeTable(tableName, res) {
728
+ const db = this.executor.db;
729
+ // v2.51.0: 支持描述物化视图(只读关系)
730
+ const table = db && typeof db.hasTable === 'function' && db.hasTable(tableName)
731
+ ? db.getTable(tableName)
732
+ : db?.tables?.[tableName];
733
+ if (!table) {
734
+ res.writeHead(404, { 'Content-Type': 'application/json' });
735
+ res.end(JSON.stringify({ error: `表不存在: ${tableName}` }));
736
+ return;
737
+ }
738
+ res.writeHead(200, { 'Content-Type': 'application/json' });
739
+ res.end(JSON.stringify({
740
+ name: tableName,
741
+ columns: table.columns,
742
+ rowCount: table.rows?.length || 0,
743
+ indexes: table.indexes ? Object.keys(table.indexes) : [],
744
+ isMaterializedView: !!table.isMaterializedView,
745
+ }));
746
+ }
747
+
748
+ async _handleExplain(req, res) {
749
+ let body;
750
+ try {
751
+ body = await parseBody(req);
752
+ } catch (err) {
753
+ sendError(res, err, 400);
754
+ return;
755
+ }
756
+ try {
757
+ const { sql, format } = body;
758
+ // H-03 修复:EXPLAIN 同样为用户 SQL 直通,执行注入检测
759
+ const injectionMsg = this._checkSqlInjection(sql);
760
+ if (injectionMsg) {
761
+ res.writeHead(400, { 'Content-Type': 'application/json' });
762
+ res.end(JSON.stringify({ error: injectionMsg }));
763
+ return;
764
+ }
765
+ const plan = await this.executor.executeSQL(`EXPLAIN ${format === 'JSON' ? 'JSON ' : ''}${sql}`);
766
+ res.writeHead(200, { 'Content-Type': 'application/json' });
767
+ res.end(JSON.stringify({ plan }));
768
+ } catch (err) {
769
+ sendError(res, err, 500);
770
+ }
771
+ }
772
+
773
+ _handleStats(res) {
774
+ const db = this.executor.db;
775
+ const tables = db ? Object.keys(db.tables || {}).map(name => ({
776
+ name,
777
+ rowCount: db.tables[name].rows?.length || 0,
778
+ })) : [];
779
+ res.writeHead(200, { 'Content-Type': 'application/json' });
780
+ res.end(JSON.stringify({
781
+ tableCount: tables.length,
782
+ totalRows: tables.reduce((s, t) => s + t.rowCount, 0),
783
+ tables,
784
+ }));
785
+ }
786
+
787
+ /**
788
+ * GET /api/health — 健康检查(2026-10-27 UXR 修复:admin-ui 依赖此端点判断连接状态)
789
+ */
790
+ _handleHealth(res) {
791
+ res.writeHead(200, { 'Content-Type': 'application/json' });
792
+ res.end(JSON.stringify({
793
+ status: 'ok',
794
+ server: 'pure-js-db',
795
+ version: VERSION,
796
+ uptime: Math.round(process.uptime()),
797
+ time: new Date().toISOString(),
798
+ }));
799
+ }
800
+
801
+ /**
802
+ * GET /api/monitor/stats — 监控统计(2026-10-27 UXR 修复:admin-ui 监控面板数据源)
803
+ */
804
+ _handleMonitorStats(res) {
805
+ const s = this._queryStats;
806
+ const avgLatency = s.totalQueries > 0 ? s.totalLatencyMs / s.totalQueries : 0;
807
+ const errorRate = s.totalQueries > 0 ? s.errors / s.totalQueries : 0;
808
+ res.writeHead(200, { 'Content-Type': 'application/json' });
809
+ res.end(JSON.stringify({
810
+ totalQueries: s.totalQueries,
811
+ slowQueries: s.slowQueryLog.length,
812
+ avgLatency: Number(avgLatency.toFixed(2)),
813
+ errorRate: Number(errorRate.toFixed(4)),
814
+ slowQueryLog: s.slowQueryLog,
815
+ }));
816
+ }
817
+
818
+ /**
819
+ * 备份存放目录(默认 <cwd>/backups)
820
+ * @private
821
+ */
822
+ _backupDir() {
823
+ return path.join(process.cwd(), 'backups');
824
+ }
825
+
826
+ /**
827
+ * GET /api/backup/history — 备份历史(2026-10-27 UXR 修复)
828
+ */
829
+ async _handleBackupHistory(res) {
830
+ const dir = this._backupDir();
831
+ await fs.mkdir(dir, { recursive: true });
832
+ const files = await fs.readdir(dir).catch(() => []);
833
+ const history = [];
834
+ for (const f of files) {
835
+ if (!/\.(sql|json)$/i.test(f)) {
836
+ continue;
837
+ }
838
+ try {
839
+ const st = await fs.stat(path.join(dir, f));
840
+ const type = f.includes('-inc.') ? 'incremental' : 'full';
841
+ history.push({
842
+ file: f,
843
+ type,
844
+ timestamp: st.mtime.toISOString(),
845
+ size: st.size,
846
+ });
847
+ } catch { /* 瞬时文件跳过 */ }
848
+ }
849
+ history.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
850
+ res.writeHead(200, { 'Content-Type': 'application/json' });
851
+ res.end(JSON.stringify({ history }));
852
+ }
853
+
854
+ /**
855
+ * POST /api/backup/full 与 POST /api/backup/incremental(2026-10-27 UXR 修复)
856
+ * full 用 SQL dump;incremental 用 JSON 快照(当前实现为带时间戳的增量快照文件)。
857
+ */
858
+ async _handleBackupCreate(res, type) {
859
+ const dir = this._backupDir();
860
+ await fs.mkdir(dir, { recursive: true });
861
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
862
+ const isInc = type === 'incremental';
863
+ const file = `backup-${ts}${isInc ? '-inc' : ''}.${isInc ? 'json' : 'sql'}`;
864
+ const backup = new LogicalBackup(this.executor);
865
+ const content = isInc ? backup.backupToJSON() : backup.backup();
866
+ await fs.writeFile(path.join(dir, file), content, 'utf-8');
867
+ res.writeHead(200, { 'Content-Type': 'application/json' });
868
+ res.end(JSON.stringify({
869
+ success: true,
870
+ type,
871
+ file,
872
+ timestamp: new Date().toISOString(),
873
+ }));
874
+ }
875
+
876
+ _handleSchemaIntrospection(res) {
877
+ const introspector = new SchemaIntrospector({
878
+ schema: this.schema,
879
+ db: this.executor.db,
880
+ });
881
+ const metadata = introspector.introspect();
882
+ res.writeHead(200, { 'Content-Type': 'application/json' });
883
+ res.end(JSON.stringify(metadata));
884
+ }
885
+
886
+ _handleTableSchema(tableName, res) {
887
+ const introspector = new SchemaIntrospector({
888
+ schema: this.schema,
889
+ db: this.executor.db,
890
+ });
891
+ const tableMeta = introspector.introspectTable(tableName);
892
+ if (!tableMeta) {
893
+ res.writeHead(404, { 'Content-Type': 'application/json' });
894
+ res.end(JSON.stringify({ error: `表不存在: ${tableName}` }));
895
+ return;
896
+ }
897
+ res.writeHead(200, { 'Content-Type': 'application/json' });
898
+ res.end(JSON.stringify(tableMeta));
899
+ }
900
+
901
+ // ════════════════════════════════════════════════════════════════
902
+ // M5 认证端点 — 注册 / 登录(AuthManager + JWTManager)
903
+ // ════════════════════════════════════════════════════════════════
904
+
905
+ async _handleAuthRegister(req, res) {
906
+ let body;
907
+ try {
908
+ body = await parseBody(req);
909
+ } catch {
910
+ res.writeHead(400, { 'Content-Type': 'application/json' });
911
+ res.end(JSON.stringify({ error: '请求体解析失败' }));
912
+ return;
913
+ }
914
+ const { username, password } = body || {};
915
+ // 2026-10-27 加固(L-1):注册密码最小长度 8(库层保持宽松以兼容嵌入场景,HTTP 入口强制)
916
+ if (typeof password !== 'string' || password.length < 8) {
917
+ res.writeHead(400, { 'Content-Type': 'application/json' });
918
+ res.end(JSON.stringify({ error: '密码长度至少需要 8 个字符' }));
919
+ return;
920
+ }
921
+ try {
922
+ const result = await this._authManager.register(username, password);
923
+ res.writeHead(201, { 'Content-Type': 'application/json' });
924
+ res.end(JSON.stringify(result));
925
+ } catch (err) {
926
+ res.writeHead(400, { 'Content-Type': 'application/json' });
927
+ res.end(JSON.stringify({ error: err.message }));
928
+ }
929
+ }
930
+
931
+ async _handleAuthLogin(req, res) {
932
+ let body;
933
+ try {
934
+ body = await parseBody(req);
935
+ } catch {
936
+ res.writeHead(400, { 'Content-Type': 'application/json' });
937
+ res.end(JSON.stringify({ error: '请求体解析失败' }));
938
+ return;
939
+ }
940
+ const { username, password } = body || {};
941
+ try {
942
+ const session = await this._authManager.login(username, password);
943
+ // 用 JWTManager 签发 JWT(若已配置 jwtSecret)
944
+ if (this._jwtManager) {
945
+ const token = this._jwtManager.sign(
946
+ { sub: session.token, username: session.username },
947
+ { expiresIn: 3600 },
948
+ );
949
+ res.writeHead(200, { 'Content-Type': 'application/json' });
950
+ res.end(JSON.stringify({ token, expiresAt: session.expiresAt }));
951
+ } else {
952
+ // 未配置 jwtSecret:返回 session token(兼容模式)
953
+ res.writeHead(200, { 'Content-Type': 'application/json' });
954
+ res.end(JSON.stringify(session));
955
+ }
956
+ } catch (err) {
957
+ res.writeHead(401, { 'Content-Type': 'application/json' });
958
+ res.end(JSON.stringify({ error: err.message }));
959
+ }
960
+ }
961
+
962
+ // ════════════════════════════════════════════════════════════════
963
+ // v2 自动 CRUD REST API — 表级端点(NOC-01)
964
+ // ════════════════════════════════════════════════════════════════
965
+
966
+ async _handleV2(req, res, url) {
967
+ const path = url.pathname;
968
+ const segments = path.split('/').filter(Boolean); // ['api', 'v2', 'tableName', 'rows', '?']
969
+
970
+ // 至少需要 /api/v2/:table
971
+ if (segments.length < 3) {
972
+ res.writeHead(400, { 'Content-Type': 'application/json' });
973
+ res.end(JSON.stringify({ error: '路径格式: /api/v2/{table}/rows' }));
974
+ return;
975
+ }
976
+
977
+ const tableName = decodeURIComponent(segments[2]);
978
+ const db = this.executor.db;
979
+
980
+ // 校验表名(防注入)
981
+ if (!validateTableName(db, tableName)) {
982
+ res.writeHead(404, { 'Content-Type': 'application/json' });
983
+ res.end(JSON.stringify({ error: `表不存在: ${tableName}` }));
984
+ return;
985
+ }
986
+
987
+ const table = db.tables[tableName];
988
+ const hasRows = segments.length >= 4 && segments[3] === 'rows';
989
+ const hasSchema = segments.length >= 4 && segments[3] === 'schema';
990
+ const rowId = hasRows && segments.length >= 5 ? decodeURIComponent(segments[4]) : null;
991
+
992
+ try {
993
+ // GET /api/v2/:table/schema
994
+ if (hasSchema && req.method === 'GET') {
995
+ return this._v2GetSchema(tableName, table, res);
996
+ }
997
+
998
+ // GET /api/v2/:table/rows — 分页查询
999
+ if (hasRows && !rowId && req.method === 'GET') {
1000
+ return this._v2ListRows(tableName, table, url, res);
1001
+ }
1002
+
1003
+ // POST /api/v2/:table/rows — 插入
1004
+ if (hasRows && !rowId && req.method === 'POST') {
1005
+ return await this._v2InsertRows(tableName, table, req, res);
1006
+ }
1007
+
1008
+ // GET /api/v2/:table/rows/:id — 主键查询
1009
+ if (hasRows && rowId && req.method === 'GET') {
1010
+ return this._v2GetRowById(tableName, table, rowId, res);
1011
+ }
1012
+
1013
+ // PUT /api/v2/:table/rows/:id — 主键更新
1014
+ if (hasRows && rowId && req.method === 'PUT') {
1015
+ return await this._v2UpdateRowById(tableName, table, rowId, req, res);
1016
+ }
1017
+
1018
+ // DELETE /api/v2/:table/rows/:id — 主键删除
1019
+ if (hasRows && rowId && req.method === 'DELETE') {
1020
+ return this._v2DeleteRowById(tableName, table, rowId, res);
1021
+ }
1022
+
1023
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1024
+ res.end(JSON.stringify({ error: '不支持的 v2 路径或方法' }));
1025
+ } catch (err) {
1026
+ // 2026-10-27 加固(L-3):v2 CRUD 异常改走统一脱敏通道,不再直接回显 err.message
1027
+ sendError(res, err, 500);
1028
+ }
1029
+ }
1030
+
1031
+ /**
1032
+ * GET /api/v2/:table/schema — 表元数据
1033
+ */
1034
+ _v2GetSchema(tableName, table, res) {
1035
+ const pk = inferPrimaryKey(table);
1036
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1037
+ res.end(JSON.stringify({
1038
+ name: tableName,
1039
+ columns: table.columns,
1040
+ primaryKey: pk,
1041
+ rowCount: table.rows?.length || 0,
1042
+ indexes: table.indexes ? Object.keys(table.indexes) : [],
1043
+ }));
1044
+ }
1045
+
1046
+ /**
1047
+ * GET /api/v2/:table/rows?limit=&offset=&sort=&order=&filter=
1048
+ */
1049
+ _v2ListRows(tableName, table, url, res) {
1050
+ const limit = parseInt(url.searchParams.get('limit') || '100', 10);
1051
+ const offset = parseInt(url.searchParams.get('offset') || '0', 10);
1052
+ const sort = url.searchParams.get('sort');
1053
+ const order = (url.searchParams.get('order') || 'ASC').toUpperCase();
1054
+ const filter = url.searchParams.get('filter');
1055
+
1056
+ // 校验排序列名
1057
+ if (sort && !validateColumnName(table, sort)) {
1058
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1059
+ res.end(JSON.stringify({ error: `无效排序列: ${sort}` }));
1060
+ return;
1061
+ }
1062
+
1063
+ // 安全的 ORDER BY(仅白名单列 + ASC/DESC)
1064
+ const orderBy = sort ? ` ORDER BY ${sort} ${order === 'DESC' ? 'DESC' : 'ASC'}` : '';
1065
+ const limitClause = ` LIMIT ${Math.min(Math.max(limit, 1), 10000)} OFFSET ${Math.max(offset, 0)}`;
1066
+
1067
+ // P0-1 修复:filter 参数通过 SQL 解析器安全校验,防止 SQL 注入
1068
+ // 不再直接拼接用户输入到 WHERE 子句
1069
+ let whereClause = '';
1070
+ if (filter) {
1071
+ const validated = validateFilter(filter);
1072
+ if (validated === null) {
1073
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1074
+ res.end(JSON.stringify({
1075
+ error: '无效的 filter 参数',
1076
+ detail: 'filter 仅支持简单比较表达式(如 id=5, name LIKE \'John%\', age>18 AND age<65),不支持子查询/JOIN/DML语句',
1077
+ }));
1078
+ return;
1079
+ }
1080
+ whereClause = ` ${validated}`;
1081
+ }
1082
+
1083
+ const sql = `SELECT * FROM ${tableName}${whereClause}${orderBy}${limitClause}`;
1084
+ const [result] = this.executor.executeSQL(sql);
1085
+
1086
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1087
+ res.end(JSON.stringify({
1088
+ rows: result.rows,
1089
+ rowCount: result.rows.length,
1090
+ total: table.rows?.length || 0,
1091
+ }));
1092
+ }
1093
+
1094
+ /**
1095
+ * POST /api/v2/:table/rows — 插入单行或多行
1096
+ */
1097
+ async _v2InsertRows(tableName, table, req, res) {
1098
+ const body = await parseBody(req);
1099
+ const rows = Array.isArray(body) ? body : [body];
1100
+
1101
+ if (rows.length === 0) {
1102
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1103
+ res.end(JSON.stringify({ error: '请求体为空' }));
1104
+ return;
1105
+ }
1106
+
1107
+ const validColumns = table.columns.map(c => c.name);
1108
+ let inserted = 0;
1109
+
1110
+ for (const row of rows) {
1111
+ // 过滤无效列
1112
+ const validEntries = Object.entries(row).filter(([k]) => validColumns.includes(k));
1113
+ if (validEntries.length === 0) {
1114
+ continue;
1115
+ }
1116
+
1117
+ const cols = validEntries.map(([k]) => k).join(', ');
1118
+ const vals = validEntries.map(([, v]) => escapeSQLValue(v)).join(', ');
1119
+ this.executor.executeSQL(`INSERT INTO ${tableName} (${cols}) VALUES (${vals})`);
1120
+ inserted++;
1121
+ }
1122
+
1123
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1124
+ res.end(JSON.stringify({ inserted }));
1125
+ }
1126
+
1127
+ /**
1128
+ * GET /api/v2/:table/rows/:id — 按主键查询单行
1129
+ */
1130
+ _v2GetRowById(tableName, table, rowId, res) {
1131
+ const pk = inferPrimaryKey(table);
1132
+ const sql = `SELECT * FROM ${tableName} WHERE ${pk} = ${escapeSQLValue(rowId)}`;
1133
+ const [result] = this.executor.executeSQL(sql);
1134
+
1135
+ if (result.rows.length === 0) {
1136
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1137
+ res.end(JSON.stringify({ error: `行不存在: ${pk}=${rowId}` }));
1138
+ return;
1139
+ }
1140
+
1141
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1142
+ res.end(JSON.stringify(result.rows[0]));
1143
+ }
1144
+
1145
+ /**
1146
+ * PUT /api/v2/:table/rows/:id — 按主键更新单行
1147
+ */
1148
+ async _v2UpdateRowById(tableName, table, rowId, req, res) {
1149
+ const body = await parseBody(req);
1150
+ const pk = inferPrimaryKey(table);
1151
+ const validColumns = table.columns.map(c => c.name);
1152
+
1153
+ // 过滤无效列(不允许更新主键)
1154
+ const setClauses = Object.entries(body)
1155
+ .filter(([k]) => validColumns.includes(k) && k !== pk)
1156
+ .map(([k, v]) => `${k} = ${escapeSQLValue(v)}`);
1157
+
1158
+ if (setClauses.length === 0) {
1159
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1160
+ res.end(JSON.stringify({ error: '无有效更新字段' }));
1161
+ return;
1162
+ }
1163
+
1164
+ const sql = `UPDATE ${tableName} SET ${setClauses.join(', ')} WHERE ${pk} = ${escapeSQLValue(rowId)}`;
1165
+ this.executor.executeSQL(sql);
1166
+
1167
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1168
+ res.end(JSON.stringify({ updated: 1 }));
1169
+ }
1170
+
1171
+ /**
1172
+ * DELETE /api/v2/:table/rows/:id — 按主键删除单行
1173
+ */
1174
+ _v2DeleteRowById(tableName, table, rowId, res) {
1175
+ const pk = inferPrimaryKey(table);
1176
+ const sql = `DELETE FROM ${tableName} WHERE ${pk} = ${escapeSQLValue(rowId)}`;
1177
+ this.executor.executeSQL(sql);
1178
+
1179
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1180
+ res.end(JSON.stringify({ deleted: 1 }));
1181
+ }
1182
+ }