pgserve 2.1.3 → 2.2.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 (235) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +105 -1
  3. package/bin/autopg-wrapper.cjs +16 -0
  4. package/bin/pgserve-wrapper.cjs +32 -6
  5. package/bin/postgres-server.js +56 -0
  6. package/console/README.md +131 -0
  7. package/console/api.js +173 -0
  8. package/console/app.jsx +483 -0
  9. package/console/colors_and_type.css +227 -0
  10. package/console/components.jsx +167 -0
  11. package/console/console.css +1666 -0
  12. package/console/data.jsx +350 -0
  13. package/console/index.html +31 -0
  14. package/console/screens/databases.jsx +5 -0
  15. package/console/screens/health.jsx +5 -0
  16. package/console/screens/ingress.jsx +5 -0
  17. package/console/screens/optimizer.jsx +5 -0
  18. package/console/screens/rlm-sim.jsx +5 -0
  19. package/console/screens/rlm-trace.jsx +5 -0
  20. package/console/screens/security.jsx +5 -0
  21. package/console/screens/settings.jsx +611 -0
  22. package/console/screens/sql.jsx +5 -0
  23. package/console/screens/sync.jsx +5 -0
  24. package/console/screens/tables.jsx +5 -0
  25. package/console/tweaks-panel.jsx +425 -0
  26. package/package.json +14 -2
  27. package/scripts/postinstall.cjs +60 -0
  28. package/src/cli-config.cjs +310 -0
  29. package/src/cli-install.cjs +112 -11
  30. package/src/cli-restart.cjs +228 -0
  31. package/src/cli-ui.cjs +580 -0
  32. package/src/cluster.js +43 -38
  33. package/src/postgres.js +141 -19
  34. package/src/settings-loader.cjs +235 -0
  35. package/src/settings-migrate.cjs +212 -0
  36. package/src/settings-pg-args.cjs +146 -0
  37. package/src/settings-schema.cjs +422 -0
  38. package/src/settings-validator.cjs +416 -0
  39. package/src/settings-writer.cjs +288 -0
  40. package/src/upgrade/index.js +65 -0
  41. package/src/upgrade/runner.js +23 -0
  42. package/src/upgrade/steps/binary-cache-flush.js +67 -0
  43. package/src/upgrade/steps/consumer-signal.js +40 -0
  44. package/src/upgrade/steps/env-refresh.js +89 -0
  45. package/src/upgrade/steps/health-validate.js +53 -0
  46. package/src/upgrade/steps/plpgsql-resolve.js +66 -0
  47. package/src/upgrade/steps/port-reconcile.js +52 -0
  48. package/.claude/context/windows-debug.md +0 -119
  49. package/.genie/AGENTS.md +0 -15
  50. package/.genie/agents/README.md +0 -110
  51. package/.genie/agents/analyze.md +0 -176
  52. package/.genie/agents/forge.md +0 -290
  53. package/.genie/agents/garbage-cleaner.md +0 -324
  54. package/.genie/agents/garbage-collector.md +0 -596
  55. package/.genie/agents/github-issue-gc.md +0 -618
  56. package/.genie/agents/review.md +0 -380
  57. package/.genie/agents/semantic-analyzer/find-duplicates.md +0 -90
  58. package/.genie/agents/semantic-analyzer/find-orphans.md +0 -99
  59. package/.genie/agents/semantic-analyzer.md +0 -101
  60. package/.genie/agents/update.md +0 -182
  61. package/.genie/agents/wish.md +0 -357
  62. package/.genie/brainstorms/pgserve-v2/DESIGN.md +0 -174
  63. package/.genie/code/AGENTS.md +0 -694
  64. package/.genie/code/agents/audit/risk.md +0 -173
  65. package/.genie/code/agents/audit/security.md +0 -189
  66. package/.genie/code/agents/audit.md +0 -145
  67. package/.genie/code/agents/challenge.md +0 -230
  68. package/.genie/code/agents/change-reviewer.md +0 -295
  69. package/.genie/code/agents/code-garbage-collector.md +0 -425
  70. package/.genie/code/agents/code-quality.md +0 -410
  71. package/.genie/code/agents/commit-suggester.md +0 -255
  72. package/.genie/code/agents/commit.md +0 -124
  73. package/.genie/code/agents/consensus.md +0 -204
  74. package/.genie/code/agents/daily-standup.md +0 -722
  75. package/.genie/code/agents/docgen.md +0 -48
  76. package/.genie/code/agents/explore.md +0 -79
  77. package/.genie/code/agents/fix.md +0 -100
  78. package/.genie/code/agents/git/commit-advisory.md +0 -219
  79. package/.genie/code/agents/git/workflows/issue.md +0 -244
  80. package/.genie/code/agents/git/workflows/pr.md +0 -179
  81. package/.genie/code/agents/git/workflows/release.md +0 -460
  82. package/.genie/code/agents/git/workflows/report.md +0 -342
  83. package/.genie/code/agents/git.md +0 -432
  84. package/.genie/code/agents/implementor.md +0 -161
  85. package/.genie/code/agents/install.md +0 -515
  86. package/.genie/code/agents/issue-creator.md +0 -344
  87. package/.genie/code/agents/polish.md +0 -116
  88. package/.genie/code/agents/qa.md +0 -653
  89. package/.genie/code/agents/refactor.md +0 -294
  90. package/.genie/code/agents/release.md +0 -1129
  91. package/.genie/code/agents/roadmap.md +0 -885
  92. package/.genie/code/agents/tests.md +0 -557
  93. package/.genie/code/agents/tracer.md +0 -50
  94. package/.genie/code/agents/update/upstream-update.md +0 -85
  95. package/.genie/code/agents/update/versions/generic-update.md +0 -305
  96. package/.genie/code/agents/vibe.md +0 -1317
  97. package/.genie/code/spells/agent-configuration.md +0 -58
  98. package/.genie/code/spells/automated-rc-publishing.md +0 -106
  99. package/.genie/code/spells/branch-tracker-guidance.md +0 -28
  100. package/.genie/code/spells/debug.md +0 -320
  101. package/.genie/code/spells/emoji-naming-convention.md +0 -303
  102. package/.genie/code/spells/evidence-storage.md +0 -26
  103. package/.genie/code/spells/file-naming-rules.md +0 -35
  104. package/.genie/code/spells/forge-code-blueprints.md +0 -195
  105. package/.genie/code/spells/genie-integration.md +0 -153
  106. package/.genie/code/spells/publishing-protocol.md +0 -61
  107. package/.genie/code/spells/team-consultation-protocol.md +0 -284
  108. package/.genie/code/spells/tool-requirements.md +0 -20
  109. package/.genie/code/spells/triad-maintenance-protocol.md +0 -154
  110. package/.genie/code/teams/tech-council/council.md +0 -328
  111. package/.genie/code/teams/tech-council/jt.md +0 -352
  112. package/.genie/code/teams/tech-council/nayr.md +0 -305
  113. package/.genie/code/teams/tech-council/oettam.md +0 -375
  114. package/.genie/neurons/README.md +0 -193
  115. package/.genie/neurons/forge.md +0 -106
  116. package/.genie/neurons/genie.md +0 -63
  117. package/.genie/neurons/review.md +0 -106
  118. package/.genie/neurons/wish.md +0 -104
  119. package/.genie/product/README.md +0 -20
  120. package/.genie/product/cli-automation.md +0 -359
  121. package/.genie/product/environment.md +0 -60
  122. package/.genie/product/mission.md +0 -60
  123. package/.genie/product/roadmap.md +0 -44
  124. package/.genie/product/tech-stack.md +0 -34
  125. package/.genie/product/templates/context-template.md +0 -218
  126. package/.genie/product/templates/qa-done-report-template.md +0 -68
  127. package/.genie/product/templates/review-report-template.md +0 -89
  128. package/.genie/product/templates/wish-template.md +0 -120
  129. package/.genie/scripts/helpers/analyze-commit.js +0 -195
  130. package/.genie/scripts/helpers/bullet-counter.js +0 -194
  131. package/.genie/scripts/helpers/bullet-find.js +0 -289
  132. package/.genie/scripts/helpers/bullet-id.js +0 -244
  133. package/.genie/scripts/helpers/check-secrets.js +0 -237
  134. package/.genie/scripts/helpers/count-tokens.js +0 -200
  135. package/.genie/scripts/helpers/create-frontmatter.js +0 -456
  136. package/.genie/scripts/helpers/detect-markers.js +0 -293
  137. package/.genie/scripts/helpers/detect-todos.js +0 -267
  138. package/.genie/scripts/helpers/detect-unlabeled-blocks.js +0 -135
  139. package/.genie/scripts/helpers/embeddings.js +0 -344
  140. package/.genie/scripts/helpers/find-empty-sections.js +0 -158
  141. package/.genie/scripts/helpers/index.js +0 -319
  142. package/.genie/scripts/helpers/validate-frontmatter.js +0 -578
  143. package/.genie/scripts/helpers/validate-links.js +0 -207
  144. package/.genie/scripts/helpers/validate-paths.js +0 -373
  145. package/.genie/spells/README.md +0 -9
  146. package/.genie/spells/ace-protocol.md +0 -118
  147. package/.genie/spells/ask-one-at-a-time.md +0 -175
  148. package/.genie/spells/backup-analyzer.md +0 -542
  149. package/.genie/spells/blocker.md +0 -12
  150. package/.genie/spells/break-things-move-fast.md +0 -56
  151. package/.genie/spells/context-candidates.md +0 -72
  152. package/.genie/spells/context-critic.md +0 -51
  153. package/.genie/spells/defer-to-expertise.md +0 -278
  154. package/.genie/spells/delegate-dont-do.md +0 -292
  155. package/.genie/spells/error-investigation-protocol.md +0 -328
  156. package/.genie/spells/evidence-based-completion.md +0 -273
  157. package/.genie/spells/experiment.md +0 -65
  158. package/.genie/spells/file-creation-protocol.md +0 -229
  159. package/.genie/spells/forge-integration.md +0 -281
  160. package/.genie/spells/forge-orchestration.md +0 -514
  161. package/.genie/spells/gather-context.md +0 -18
  162. package/.genie/spells/global-health-check.md +0 -34
  163. package/.genie/spells/global-noop-roundtrip.md +0 -25
  164. package/.genie/spells/install-genie.md +0 -1232
  165. package/.genie/spells/install.md +0 -82
  166. package/.genie/spells/investigate-before-commit.md +0 -112
  167. package/.genie/spells/know-yourself.md +0 -288
  168. package/.genie/spells/learn.md +0 -828
  169. package/.genie/spells/mcp-diagnostic-protocol.md +0 -246
  170. package/.genie/spells/mcp-first.md +0 -124
  171. package/.genie/spells/multi-step-execution.md +0 -67
  172. package/.genie/spells/orchestration-boundary-protocol.md +0 -256
  173. package/.genie/spells/orchestrator-not-implementor.md +0 -189
  174. package/.genie/spells/prompt.md +0 -746
  175. package/.genie/spells/reflect.md +0 -404
  176. package/.genie/spells/routing-decision-matrix.md +0 -368
  177. package/.genie/spells/run-in-parallel.md +0 -12
  178. package/.genie/spells/session-state-updater-example.md +0 -196
  179. package/.genie/spells/session-state-updater.md +0 -220
  180. package/.genie/spells/track-long-running-tasks.md +0 -133
  181. package/.genie/spells/troubleshoot-infrastructure.md +0 -176
  182. package/.genie/spells/upgrade-genie.md +0 -415
  183. package/.genie/spells/url-presentation-protocol.md +0 -301
  184. package/.genie/spells/wish-initiation.md +0 -158
  185. package/.genie/spells/wish-issue-linkage.md +0 -410
  186. package/.genie/spells/wish-lifecycle.md +0 -100
  187. package/.genie/state/provider-status.json +0 -3
  188. package/.genie/state/version.json +0 -16
  189. package/.genie/wishes/canonical-pgserve-pm2-supervision/WISH.md +0 -290
  190. package/.genie/wishes/pgserve-v2/BRIEF-from-genie-pgserve.md +0 -99
  191. package/.genie/wishes/pgserve-v2/WISH.md +0 -442
  192. package/.genie/wishes/release-system-genie-pattern/WISH.md +0 -268
  193. package/.genie/wishes/release-system-genie-pattern/validation.md +0 -205
  194. package/.gitguardian.yaml +0 -29
  195. package/.gitguardianignore +0 -16
  196. package/.github/workflows/ci.yml +0 -122
  197. package/.github/workflows/release.yml +0 -289
  198. package/.github/workflows/version.yml +0 -228
  199. package/.husky/pre-commit +0 -2
  200. package/AGENTS.md +0 -433
  201. package/CLAUDE.md +0 -1
  202. package/Makefile +0 -285
  203. package/assets/icon.ico +0 -0
  204. package/bun.lock +0 -435
  205. package/bunfig.toml +0 -28
  206. package/ecosystem.config.cjs +0 -23
  207. package/eslint.config.js +0 -63
  208. package/examples/multi-tenant-demo.js +0 -104
  209. package/install.sh +0 -123
  210. package/knip.json +0 -9
  211. package/tests/audit.test.js +0 -189
  212. package/tests/backpressure.test.js +0 -167
  213. package/tests/benchmarks/runner.js +0 -1197
  214. package/tests/benchmarks/vector-generator.js +0 -368
  215. package/tests/cli-install.test.js +0 -322
  216. package/tests/control-db.test.js +0 -285
  217. package/tests/daemon-args.test.js +0 -86
  218. package/tests/daemon-control.test.js +0 -171
  219. package/tests/daemon-fingerprint-integration.test.js +0 -111
  220. package/tests/daemon-pr24-regression.test.js +0 -198
  221. package/tests/fingerprint.test.js +0 -263
  222. package/tests/fixtures/240-orphan-seed.sql +0 -30
  223. package/tests/multi-tenant.test.js +0 -374
  224. package/tests/orphan-cleanup.test.js +0 -390
  225. package/tests/pg-version-regex.test.js +0 -129
  226. package/tests/quick-bench.js +0 -135
  227. package/tests/router-handshake-retry.test.js +0 -119
  228. package/tests/router-handshake-watchdog.test.js +0 -110
  229. package/tests/sdk.test.js +0 -71
  230. package/tests/stale-postmaster-pid.test.js +0 -85
  231. package/tests/stress-test.js +0 -439
  232. package/tests/sync-perf-test.js +0 -150
  233. package/tests/tcp-listen.test.js +0 -368
  234. package/tests/tenancy.test.js +0 -403
  235. package/tests/wrapper-supervision.test.js +0 -107
@@ -0,0 +1,416 @@
1
+ /**
2
+ * Settings validator — shared between CLI (`autopg config set …`) and the
3
+ * UI helper (`PUT /api/settings`).
4
+ *
5
+ * Public surface:
6
+ * - validateSetting(key, value, { schema? }) — single-leaf check, throws
7
+ * ValidationError on failure.
8
+ * - validateAll(settings, { schema? }) — full-tree check; throws on first
9
+ * failure to keep error reporting deterministic for CLI (UI batches by
10
+ * calling per-field on form blur).
11
+ * - ValidationError — { code, field, message } shape, code is one of the
12
+ * 7 stable codes.
13
+ * - ETAG_MISMATCH is exposed here so callers can `instanceof EtagMismatchError`
14
+ * uniformly; the writer is the only producer.
15
+ *
16
+ * 7 error codes:
17
+ * - INVALID_KEY — key not in schema (and not under postgres._extra)
18
+ * - INVALID_GUC_NAME — postgres._extra.<name> failed GUC_NAME_REGEX
19
+ * - INVALID_GUC_VALUE — postgres._extra.<name> value contains forbidden chars
20
+ * - INVALID_TYPE — value type doesn't match schema (e.g. string for int)
21
+ * - OUT_OF_RANGE — int/float value outside [min,max] or not in enum
22
+ * - READONLY — attempted write to a readonly-marked field
23
+ * - ETAG_MISMATCH — concurrent write detected (writer-side only)
24
+ */
25
+
26
+ 'use strict';
27
+
28
+ const {
29
+ SCHEMA,
30
+ GUC_NAME_REGEX,
31
+ FORBIDDEN_VALUE_CHARS,
32
+ flattenSchema,
33
+ } = require('./settings-schema.cjs');
34
+
35
+ const ERROR_CODES = Object.freeze({
36
+ INVALID_KEY: 'INVALID_KEY',
37
+ INVALID_GUC_NAME: 'INVALID_GUC_NAME',
38
+ INVALID_GUC_VALUE: 'INVALID_GUC_VALUE',
39
+ INVALID_TYPE: 'INVALID_TYPE',
40
+ OUT_OF_RANGE: 'OUT_OF_RANGE',
41
+ READONLY: 'READONLY',
42
+ ETAG_MISMATCH: 'ETAG_MISMATCH',
43
+ });
44
+
45
+ class ValidationError extends Error {
46
+ constructor(code, field, message) {
47
+ super(`${field} — ${code}: ${message}`);
48
+ this.name = 'ValidationError';
49
+ this.code = code;
50
+ this.field = field;
51
+ this.detail = message;
52
+ }
53
+ }
54
+
55
+ class EtagMismatchError extends ValidationError {
56
+ constructor(currentEtag, providedEtag) {
57
+ super(
58
+ ERROR_CODES.ETAG_MISMATCH,
59
+ '_etag',
60
+ `expected ${providedEtag ?? '(none)'} but file has ${currentEtag}`,
61
+ );
62
+ this.name = 'EtagMismatchError';
63
+ this.currentEtag = currentEtag;
64
+ this.providedEtag = providedEtag;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Coerce a value into the descriptor's type when the input is a string
70
+ * (CLI argv path). `parse` is permissive; the caller should use the
71
+ * coerced value when persisting so `set` round-trips through `get`.
72
+ *
73
+ * Returns the coerced value or throws ValidationError(INVALID_TYPE).
74
+ */
75
+ function coerce(field, descriptor, value) {
76
+ if (descriptor.type === 'guc_map') {
77
+ if (value && typeof value === 'object' && !Array.isArray(value)) return value;
78
+ throw new ValidationError(
79
+ ERROR_CODES.INVALID_TYPE,
80
+ field,
81
+ `expected object map, got ${describe(value)}`,
82
+ );
83
+ }
84
+ if (descriptor.nullable && (value === null || value === '')) return value;
85
+
86
+ switch (descriptor.type) {
87
+ case 'int': {
88
+ if (typeof value === 'number' && Number.isInteger(value)) return value;
89
+ if (typeof value === 'string' && /^-?\d+$/.test(value)) {
90
+ return Number.parseInt(value, 10);
91
+ }
92
+ throw new ValidationError(
93
+ ERROR_CODES.INVALID_TYPE,
94
+ field,
95
+ `expected integer, got ${describe(value)}`,
96
+ );
97
+ }
98
+ case 'bool': {
99
+ if (typeof value === 'boolean') return value;
100
+ if (value === 'true' || value === '1') return true;
101
+ if (value === 'false' || value === '0') return false;
102
+ throw new ValidationError(
103
+ ERROR_CODES.INVALID_TYPE,
104
+ field,
105
+ `expected boolean, got ${describe(value)}`,
106
+ );
107
+ }
108
+ case 'enum':
109
+ case 'string': {
110
+ if (typeof value === 'string') return value;
111
+ // Permit numbers + booleans → string for ergonomics (e.g.
112
+ // `config set ui.crt true`). The validator below enforces enum.
113
+ if (typeof value === 'number' || typeof value === 'boolean') {
114
+ return String(value);
115
+ }
116
+ throw new ValidationError(
117
+ ERROR_CODES.INVALID_TYPE,
118
+ field,
119
+ `expected string, got ${describe(value)}`,
120
+ );
121
+ }
122
+ default:
123
+ // Unknown type: pass through. Caller's validateLeaf will fail
124
+ // with INVALID_KEY since this descriptor wouldn't be in the schema.
125
+ return value;
126
+ }
127
+ }
128
+
129
+ function describe(value) {
130
+ if (value === null) return 'null';
131
+ if (Array.isArray(value)) return 'array';
132
+ return typeof value;
133
+ }
134
+
135
+ /**
136
+ * Validate a single leaf against its schema descriptor (already coerced).
137
+ * Throws ValidationError on failure; returns { ok: true, value } on success
138
+ * (value is the (possibly normalized) value to persist).
139
+ */
140
+ function validateLeaf(field, descriptor, value) {
141
+ if (descriptor.readonly) {
142
+ throw new ValidationError(
143
+ ERROR_CODES.READONLY,
144
+ field,
145
+ 'this field is read-only',
146
+ );
147
+ }
148
+ if (descriptor.nullable && (value === null || value === '')) {
149
+ return { ok: true, value };
150
+ }
151
+
152
+ switch (descriptor.type) {
153
+ case 'int': {
154
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
155
+ throw new ValidationError(
156
+ ERROR_CODES.INVALID_TYPE,
157
+ field,
158
+ `expected integer, got ${describe(value)}`,
159
+ );
160
+ }
161
+ if (descriptor.range) {
162
+ const [min, max] = descriptor.range;
163
+ if (value < min || value > max) {
164
+ throw new ValidationError(
165
+ ERROR_CODES.OUT_OF_RANGE,
166
+ field,
167
+ `value ${value} outside [${min}, ${max}]`,
168
+ );
169
+ }
170
+ }
171
+ // GUCs (curated ints) also pass through the value-char check below
172
+ // via toString during boot-time arg construction. Here we only check
173
+ // shape.
174
+ return { ok: true, value };
175
+ }
176
+ case 'bool': {
177
+ if (typeof value !== 'boolean') {
178
+ throw new ValidationError(
179
+ ERROR_CODES.INVALID_TYPE,
180
+ field,
181
+ `expected boolean, got ${describe(value)}`,
182
+ );
183
+ }
184
+ return { ok: true, value };
185
+ }
186
+ case 'enum': {
187
+ if (typeof value !== 'string') {
188
+ throw new ValidationError(
189
+ ERROR_CODES.INVALID_TYPE,
190
+ field,
191
+ `expected string, got ${describe(value)}`,
192
+ );
193
+ }
194
+ if (!descriptor.enum.includes(value)) {
195
+ throw new ValidationError(
196
+ ERROR_CODES.OUT_OF_RANGE,
197
+ field,
198
+ `must be one of [${descriptor.enum.join(', ')}], got "${value}"`,
199
+ );
200
+ }
201
+ assertScalarSafe(field, value);
202
+ return { ok: true, value };
203
+ }
204
+ case 'string': {
205
+ if (typeof value !== 'string') {
206
+ throw new ValidationError(
207
+ ERROR_CODES.INVALID_TYPE,
208
+ field,
209
+ `expected string, got ${describe(value)}`,
210
+ );
211
+ }
212
+ // GUC string values are tightened (no \n/\r/\0, no leading -).
213
+ // Generic strings allow most characters but still ban nulls / newlines
214
+ // because they break our log line parsing.
215
+ assertScalarSafe(field, value, { strictGuc: !!descriptor.guc });
216
+ return { ok: true, value };
217
+ }
218
+ case 'guc_map': {
219
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
220
+ throw new ValidationError(
221
+ ERROR_CODES.INVALID_TYPE,
222
+ field,
223
+ `expected object map, got ${describe(value)}`,
224
+ );
225
+ }
226
+ // Validate every (key, value) inside the passthrough map.
227
+ for (const [gucName, gucValue] of Object.entries(value)) {
228
+ validateExtraEntry(`${field}.${gucName}`, gucName, gucValue);
229
+ }
230
+ return { ok: true, value };
231
+ }
232
+ default:
233
+ throw new ValidationError(
234
+ ERROR_CODES.INVALID_KEY,
235
+ field,
236
+ `unknown schema type "${descriptor.type}"`,
237
+ );
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Check a value for forbidden characters (\n / \r / \0) and, for GUC
243
+ * values, also reject a leading `-` (would look like a CLI flag to
244
+ * Bun.spawn array-form). Defense-in-depth alongside Bun.spawn's
245
+ * shell-bypass.
246
+ */
247
+ function assertScalarSafe(field, value, { strictGuc = false } = {}) {
248
+ if (typeof value === 'number' || typeof value === 'boolean') return;
249
+ if (typeof value !== 'string') {
250
+ throw new ValidationError(
251
+ ERROR_CODES.INVALID_GUC_VALUE,
252
+ field,
253
+ `expected scalar primitive, got ${describe(value)}`,
254
+ );
255
+ }
256
+ if (FORBIDDEN_VALUE_CHARS.test(value)) {
257
+ throw new ValidationError(
258
+ ERROR_CODES.INVALID_GUC_VALUE,
259
+ field,
260
+ 'value contains forbidden control character (\\n, \\r, or \\0)',
261
+ );
262
+ }
263
+ if (strictGuc && value.startsWith('-')) {
264
+ throw new ValidationError(
265
+ ERROR_CODES.INVALID_GUC_VALUE,
266
+ field,
267
+ 'value must not start with "-" (looks like a CLI flag)',
268
+ );
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Validate a single entry of `postgres._extra`. The key must match
274
+ * GUC_NAME_REGEX; the value must be a scalar primitive and pass the
275
+ * forbidden-char + leading-`-` checks.
276
+ */
277
+ function validateExtraEntry(field, gucName, gucValue) {
278
+ if (typeof gucName !== 'string' || !GUC_NAME_REGEX.test(gucName)) {
279
+ throw new ValidationError(
280
+ ERROR_CODES.INVALID_GUC_NAME,
281
+ field,
282
+ `must match ${GUC_NAME_REGEX} (lowercase ASCII, starts with letter)`,
283
+ );
284
+ }
285
+ if (
286
+ typeof gucValue !== 'string' &&
287
+ typeof gucValue !== 'number' &&
288
+ typeof gucValue !== 'boolean'
289
+ ) {
290
+ throw new ValidationError(
291
+ ERROR_CODES.INVALID_GUC_VALUE,
292
+ field,
293
+ `expected scalar primitive, got ${describe(gucValue)}`,
294
+ );
295
+ }
296
+ assertScalarSafe(field, gucValue, { strictGuc: true });
297
+ }
298
+
299
+ /**
300
+ * Resolve a dotted key against the schema. Supports:
301
+ * - server.port → schema leaf
302
+ * - postgres.shared_buffers → schema leaf
303
+ * - postgres._extra → the guc_map leaf
304
+ * - postgres._extra.<name> → dynamic entry under guc_map
305
+ *
306
+ * Returns { kind: 'leaf', descriptor } | { kind: 'extra-entry', gucName }
307
+ * or throws INVALID_KEY.
308
+ */
309
+ function resolveKey(key, schema = SCHEMA) {
310
+ if (typeof key !== 'string' || !key.length) {
311
+ throw new ValidationError(ERROR_CODES.INVALID_KEY, String(key), 'empty key');
312
+ }
313
+ const parts = key.split('.');
314
+ if (parts.length === 2) {
315
+ const [section, field] = parts;
316
+ const descriptor = schema[section]?.[field];
317
+ if (!descriptor) {
318
+ throw new ValidationError(
319
+ ERROR_CODES.INVALID_KEY,
320
+ key,
321
+ `not in schema (section="${section}", field="${field}")`,
322
+ );
323
+ }
324
+ return { kind: 'leaf', descriptor };
325
+ }
326
+ if (parts.length === 3 && parts[0] === 'postgres' && parts[1] === '_extra') {
327
+ return { kind: 'extra-entry', gucName: parts[2] };
328
+ }
329
+ throw new ValidationError(
330
+ ERROR_CODES.INVALID_KEY,
331
+ key,
332
+ 'unsupported key shape (only section.field or postgres._extra.<name>)',
333
+ );
334
+ }
335
+
336
+ /**
337
+ * Validate `value` against the descriptor for `key`. `value` may be a
338
+ * string (from CLI argv); we coerce per descriptor.type before the
339
+ * structural check.
340
+ */
341
+ function validateSetting(key, value, { schema = SCHEMA } = {}) {
342
+ const resolved = resolveKey(key, schema);
343
+ if (resolved.kind === 'extra-entry') {
344
+ validateExtraEntry(key, resolved.gucName, value);
345
+ return { ok: true, value };
346
+ }
347
+ const coerced = coerce(key, resolved.descriptor, value);
348
+ return validateLeaf(key, resolved.descriptor, coerced);
349
+ }
350
+
351
+ /**
352
+ * Validate the entire settings tree. Throws on first failure for
353
+ * deterministic CLI error reporting.
354
+ */
355
+ function validateAll(settings, { schema = SCHEMA } = {}) {
356
+ if (!settings || typeof settings !== 'object') {
357
+ throw new ValidationError(ERROR_CODES.INVALID_TYPE, '_root', 'settings must be an object');
358
+ }
359
+ for (const [section, fields] of Object.entries(schema)) {
360
+ const sectionValue = settings[section];
361
+ if (sectionValue === undefined) continue; // missing section → fall back to defaults later
362
+ if (!sectionValue || typeof sectionValue !== 'object') {
363
+ throw new ValidationError(
364
+ ERROR_CODES.INVALID_TYPE,
365
+ section,
366
+ `expected object, got ${describe(sectionValue)}`,
367
+ );
368
+ }
369
+ for (const [field, descriptor] of Object.entries(fields)) {
370
+ const dottedKey = `${section}.${field}`;
371
+ if (!(field in sectionValue)) continue;
372
+ validateLeaf(dottedKey, descriptor, sectionValue[field]);
373
+ }
374
+ // Reject unknown section keys to catch typos at write time.
375
+ for (const field of Object.keys(sectionValue)) {
376
+ if (!(field in fields)) {
377
+ throw new ValidationError(
378
+ ERROR_CODES.INVALID_KEY,
379
+ `${section}.${field}`,
380
+ `not in schema`,
381
+ );
382
+ }
383
+ }
384
+ }
385
+ // Reject unknown top-level sections.
386
+ for (const section of Object.keys(settings)) {
387
+ // Allow internal metadata keys (start with `_`) so we can store
388
+ // schema version markers without tripping the validator.
389
+ if (section.startsWith('_')) continue;
390
+ if (!(section in schema)) {
391
+ throw new ValidationError(
392
+ ERROR_CODES.INVALID_KEY,
393
+ section,
394
+ `not in schema`,
395
+ );
396
+ }
397
+ }
398
+ return { ok: true };
399
+ }
400
+
401
+ module.exports = {
402
+ ERROR_CODES,
403
+ ValidationError,
404
+ EtagMismatchError,
405
+ validateSetting,
406
+ validateAll,
407
+ resolveKey,
408
+ // Test surface
409
+ _internals: {
410
+ coerce,
411
+ validateLeaf,
412
+ validateExtraEntry,
413
+ assertScalarSafe,
414
+ flattenSchema,
415
+ },
416
+ };
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Settings writer — atomic, validated, chmod 0600, etag-aware.
3
+ *
4
+ * Public surface:
5
+ * - writeSettings(newSettings, { ifMatch?, settingsPath? })
6
+ * Validates, writes atomically (tmp + rename), chmod 0600, returns
7
+ * the new etag.
8
+ *
9
+ * - setLeaf(key, value, { ifMatch? }) → convenience for `autopg config set`.
10
+ * Reads current settings, deep-merges the leaf, writes.
11
+ *
12
+ * - removeExtra(gucName) → convenience for the UI's "delete row" action
13
+ * inside `postgres._extra`.
14
+ *
15
+ * Concurrency model:
16
+ * - On write: callers (UI helper) pass `ifMatch`. If the on-disk file
17
+ * etag has drifted, we throw EtagMismatchError so the caller can
18
+ * surface a "settings changed, reload?" banner instead of clobbering.
19
+ * - CLI is single-process and skips ifMatch (each `set` is its own
20
+ * transaction); callers may opt in by reading the loader etag first.
21
+ *
22
+ * File-mode invariant:
23
+ * - Every successful write leaves `settings.json` at mode 0600 on
24
+ * POSIX. On Windows, fs.chmodSync degrades gracefully (NTFS ACLs
25
+ * would be the proper equivalent, out of scope for v1).
26
+ */
27
+
28
+ 'use strict';
29
+
30
+ const fs = require('node:fs');
31
+ const path = require('node:path');
32
+
33
+ const { SCHEMA, SCHEMA_VERSION, buildDefaults } = require('./settings-schema.cjs');
34
+ const {
35
+ ValidationError,
36
+ EtagMismatchError,
37
+ validateAll,
38
+ validateSetting,
39
+ } = require('./settings-validator.cjs');
40
+ const {
41
+ computeEtag,
42
+ readSettingsFile,
43
+ getConfigDir,
44
+ getSettingsPath,
45
+ loadEffectiveConfig,
46
+ } = require('./settings-loader.cjs');
47
+
48
+ const FILE_MODE = 0o600;
49
+ const DIR_MODE = 0o700;
50
+
51
+ /**
52
+ * Ensure the config directory exists with mode 0700. Idempotent.
53
+ * 0700 (vs 0755 in the legacy install path) because it now contains
54
+ * the password-bearing settings.json.
55
+ */
56
+ function ensureConfigDir(configDir = getConfigDir()) {
57
+ if (!fs.existsSync(configDir)) {
58
+ fs.mkdirSync(configDir, { recursive: true, mode: DIR_MODE });
59
+ return;
60
+ }
61
+ // Best-effort tighten if it was created loose by an earlier wave.
62
+ try {
63
+ fs.chmodSync(configDir, DIR_MODE);
64
+ } catch {
65
+ // Non-POSIX or unowned dir — fall through; the file's own 0600 is
66
+ // the real defense.
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Atomically write `bytes` to `targetPath`. Writes a sibling tmp file
72
+ * (same dir so rename is atomic on Linux/macOS), chmods it, then
73
+ * renames over the target.
74
+ */
75
+ function atomicWrite(targetPath, bytes) {
76
+ const dir = path.dirname(targetPath);
77
+ const tmp = path.join(dir, `.${path.basename(targetPath)}.tmp.${process.pid}.${Date.now()}`);
78
+ // mode here only affects POSIX. Windows ignores it; we re-chmod after rename anyway.
79
+ fs.writeFileSync(tmp, bytes, { mode: FILE_MODE });
80
+ // Some filesystems (Linux ext4) require an explicit chmod after writeFileSync
81
+ // because umask can mask the mode bits.
82
+ try {
83
+ fs.chmodSync(tmp, FILE_MODE);
84
+ } catch {
85
+ // ignore on platforms that don't support chmod (Windows fallback)
86
+ }
87
+ fs.renameSync(tmp, targetPath);
88
+ // Re-chmod after rename in case the filesystem didn't preserve mode
89
+ // through the rename (rare but reported on some FUSE mounts).
90
+ try {
91
+ fs.chmodSync(targetPath, FILE_MODE);
92
+ } catch {
93
+ // ignore
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Serialize the settings tree to deterministic JSON: section order
99
+ * follows SCHEMA, fields within a section follow SCHEMA, unknown keys
100
+ * (which validateAll already rejected) cannot appear here. Determinism
101
+ * is what makes the etag stable across UI re-saves of unchanged
102
+ * content.
103
+ */
104
+ function serializeSettings(settings) {
105
+ const orderedSections = Object.keys(SCHEMA);
106
+ const out = { _schemaVersion: SCHEMA_VERSION };
107
+ // Carry forward `_`-prefixed top-level metadata (e.g. `_migratedFrom`)
108
+ // so migration markers and similar audit breadcrumbs survive a round-
109
+ // trip through the writer. validateAll already ignores these keys.
110
+ for (const [k, v] of Object.entries(settings)) {
111
+ if (k.startsWith('_') && k !== '_schemaVersion') out[k] = v;
112
+ }
113
+ for (const section of orderedSections) {
114
+ if (!settings[section]) continue;
115
+ out[section] = {};
116
+ for (const field of Object.keys(SCHEMA[section])) {
117
+ if (field in settings[section]) {
118
+ out[section][field] = settings[section][field];
119
+ }
120
+ }
121
+ }
122
+ return `${JSON.stringify(out, null, 2)}\n`;
123
+ }
124
+
125
+ /**
126
+ * Deep-merge `patch` into `base` (in place is fine since base is fresh
127
+ * each call). Arrays are replaced wholesale (not concatenated). Used
128
+ * to apply UI's partial PUT body on top of the current effective tree.
129
+ */
130
+ function deepMerge(base, patch) {
131
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return base;
132
+ for (const [key, value] of Object.entries(patch)) {
133
+ if (
134
+ value &&
135
+ typeof value === 'object' &&
136
+ !Array.isArray(value) &&
137
+ base[key] &&
138
+ typeof base[key] === 'object' &&
139
+ !Array.isArray(base[key])
140
+ ) {
141
+ deepMerge(base[key], value);
142
+ } else {
143
+ base[key] = value;
144
+ }
145
+ }
146
+ return base;
147
+ }
148
+
149
+ /**
150
+ * Drop schema-internal helper fields from a settings tree (e.g. the
151
+ * `_schemaVersion` metadata we add on serialize) before re-validation.
152
+ * Validator's "unknown key" check ignores `_`-prefixed top-level keys
153
+ * but we strip on read for consistency.
154
+ */
155
+ function stripMeta(settings) {
156
+ if (!settings || typeof settings !== 'object') return settings;
157
+ const { _schemaVersion, ...rest } = settings;
158
+ void _schemaVersion;
159
+ return rest;
160
+ }
161
+
162
+ /**
163
+ * Read current parsed settings from disk (or {}) and compute the etag
164
+ * the caller's `ifMatch` should be compared against.
165
+ */
166
+ function readCurrent(settingsPath = getSettingsPath()) {
167
+ const { raw, parsed } = readSettingsFile(settingsPath);
168
+ return {
169
+ parsed: stripMeta(parsed) || {},
170
+ etag: computeEtag(raw),
171
+ };
172
+ }
173
+
174
+ /**
175
+ * Write the supplied (full) settings tree. Validates, atomically writes,
176
+ * chmods 0600, returns `{ etag }` of the new file. Throws ValidationError
177
+ * on shape/validation failure or EtagMismatchError on concurrency clash.
178
+ *
179
+ * `ifMatch` semantics:
180
+ * - undefined → caller doesn't care (CLI). Skip the check.
181
+ * - string → compare against current on-disk etag; mismatch throws.
182
+ */
183
+ function writeSettings(newSettings, { ifMatch, settingsPath = getSettingsPath() } = {}) {
184
+ if (!newSettings || typeof newSettings !== 'object') {
185
+ throw new ValidationError('INVALID_TYPE', '_root', 'expected object');
186
+ }
187
+
188
+ // Concurrency check first so we don't waste validation work when
189
+ // there's a race.
190
+ if (ifMatch !== undefined) {
191
+ const { etag: currentEtag } = readCurrent(settingsPath);
192
+ if (currentEtag !== ifMatch) {
193
+ throw new EtagMismatchError(currentEtag, ifMatch);
194
+ }
195
+ }
196
+
197
+ // Always validate the post-merge tree, not the patch — gives us a
198
+ // single source of truth for "what's about to land on disk".
199
+ const merged = stripMeta(newSettings);
200
+ validateAll(merged);
201
+
202
+ ensureConfigDir(path.dirname(settingsPath));
203
+ const bytes = serializeSettings(merged);
204
+ atomicWrite(settingsPath, bytes);
205
+
206
+ return { etag: computeEtag(Buffer.from(bytes, 'utf8')) };
207
+ }
208
+
209
+ /**
210
+ * Read current settings, apply a single-leaf update, and write back.
211
+ * Used by `autopg config set` and by validateSetting-aware UI flows.
212
+ *
213
+ * Supports:
214
+ * - section.field (curated leaf)
215
+ * - postgres._extra.<gucName> (extra-entry; sets/replaces)
216
+ */
217
+ function setLeaf(key, value, { ifMatch, settingsPath = getSettingsPath() } = {}) {
218
+ // Validate first so we never partially mutate on a bad input.
219
+ const { value: validated } = validateSetting(key, value);
220
+
221
+ // Read current settings tree (file-only, no env merge — the file is
222
+ // what we're editing). Defaults backfill missing sections so nesting
223
+ // works on a fresh install.
224
+ const { parsed: current } = readCurrent(settingsPath);
225
+ const baseline = buildDefaults();
226
+ const tree = deepMerge(baseline, current);
227
+
228
+ if (key.startsWith('postgres._extra.')) {
229
+ const gucName = key.slice('postgres._extra.'.length);
230
+ if (!tree.postgres) tree.postgres = {};
231
+ if (!tree.postgres._extra) tree.postgres._extra = {};
232
+ tree.postgres._extra[gucName] = validated;
233
+ } else {
234
+ const [section, field] = key.split('.');
235
+ if (!tree[section]) tree[section] = {};
236
+ tree[section][field] = validated;
237
+ }
238
+
239
+ return writeSettings(tree, { ifMatch, settingsPath });
240
+ }
241
+
242
+ /**
243
+ * Remove a key from `postgres._extra`. No-op if missing. Returns
244
+ * `{ etag }` of the new file (or current etag if no change was needed).
245
+ */
246
+ function removeExtra(gucName, { ifMatch, settingsPath = getSettingsPath() } = {}) {
247
+ const { parsed: current } = readCurrent(settingsPath);
248
+ const tree = deepMerge(buildDefaults(), current);
249
+ if (tree.postgres?._extra && gucName in tree.postgres._extra) {
250
+ delete tree.postgres._extra[gucName];
251
+ return writeSettings(tree, { ifMatch, settingsPath });
252
+ }
253
+ return { etag: readCurrent(settingsPath).etag };
254
+ }
255
+
256
+ /**
257
+ * Initialize `settings.json` with schema defaults. Refuses to clobber
258
+ * an existing file unless `force: true`. Used by `autopg config init`.
259
+ */
260
+ function initSettings({ force = false, settingsPath = getSettingsPath() } = {}) {
261
+ if (fs.existsSync(settingsPath) && !force) {
262
+ const err = new Error(
263
+ `${settingsPath} already exists; pass force=true to overwrite`,
264
+ );
265
+ err.code = 'EEXIST';
266
+ throw err;
267
+ }
268
+ return writeSettings(buildDefaults(), { settingsPath });
269
+ }
270
+
271
+ module.exports = {
272
+ writeSettings,
273
+ setLeaf,
274
+ removeExtra,
275
+ initSettings,
276
+ ensureConfigDir,
277
+ serializeSettings,
278
+ FILE_MODE,
279
+ DIR_MODE,
280
+ // Test surface
281
+ _internals: {
282
+ atomicWrite,
283
+ deepMerge,
284
+ stripMeta,
285
+ readCurrent,
286
+ loadEffectiveConfig,
287
+ },
288
+ };