From 6fffd861f67324d7afed4d2e74ce2a62286e1d54 Mon Sep 17 00:00:00 2001 From: Abhinav Dwivedi <226445476+learnerabhinavdwivedi-droid@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:11:58 +0530 Subject: [PATCH 1/6] fix(settings): reject an out-of-range array index instead of filling the gap setByPath grew an array up to the index in the path one element at a time, and validatePathAgainstDefaults accepts any index for an array in the schema. So PATCH /admin/settings with dvm.workers[2000000000] ran that loop inside the settings write lock, before any value validation. validatePathAgainstDefaults now rejects an index that is not a safe integer or is above MAX_SETTINGS_PATH_INDEX (10,000). setByPath only writes an existing index or appends at the array's length, and throws a SettingsPathError otherwise. The admin settings controller returns that as a 400 validation issue on the path instead of a 500. Closes #1251 Co-Authored-By: Claude Opus 5.5 (cherry picked from commit f5f9184a5f92843ca685fb95449d9874dcffa3d7) --- .changeset/settings-path-index-bound.md | 7 +++ CLI.md | 3 ++ .../admin/patch-settings-controller.ts | 19 +++++-- src/utils/settings-config.ts | 49 ++++++++++++++++--- .../admin/patch-settings-controller.spec.ts | 16 ++++++ test/unit/utils/settings-config.spec.ts | 48 ++++++++++++++++++ 6 files changed, 132 insertions(+), 10 deletions(-) create mode 100644 .changeset/settings-path-index-bound.md diff --git a/.changeset/settings-path-index-bound.md b/.changeset/settings-path-index-bound.md new file mode 100644 index 000000000..d95a46a16 --- /dev/null +++ b/.changeset/settings-path-index-bound.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(settings): reject an out-of-range array index instead of filling the gap + +Setting a path such as `dvm.workers[2000000000]` through `PATCH /admin/settings` or `nostream config set` grew the array one element at a time up to that index, inside the request and before the value was validated. A single request could hold the settings lock and fill the heap for as long as that took. A path may now name an array index only up to `MAX_SETTINGS_PATH_INDEX` (10,000), checked with the other path checks before the settings are read. Inside the array, a write must target an index that already exists or append one element at the end. Anything else is refused: the admin API answers with a 400 and a validation issue on the path, and the CLI prints the error. Updating an existing index and appending with `array[]` work as before. diff --git a/CLI.md b/CLI.md index d7358a6b0..102821398 100644 --- a/CLI.md +++ b/CLI.md @@ -102,6 +102,9 @@ nostream config set limits.event.content[0].maxLength 2048 nostream config set nip05.domainWhitelist '["example.com","relay.io"]' --type json ``` +An array index can update an element that exists or append one at the end (`[]`). An index past +the end, or above 10,000, is rejected. To replace a whole list, set the array itself with `--type json`. + ## Development Commands ```bash diff --git a/src/controllers/admin/patch-settings-controller.ts b/src/controllers/admin/patch-settings-controller.ts index c78394b3a..f438fc9e3 100644 --- a/src/controllers/admin/patch-settings-controller.ts +++ b/src/controllers/admin/patch-settings-controller.ts @@ -9,6 +9,7 @@ import { loadMergedSettings, loadUserSettings, saveSettings, + SettingsPathError, setByPath, validatePathAgainstDefaults, validateSettings, @@ -62,10 +63,20 @@ export class PatchAdminSettingsController implements IController { const userSettings = loadUserSettings() as unknown as Record // Taken before the changes are applied, in case applying them edits this object in place. const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record - const nextUserSettings = changes.reduce( - (settings, change) => setByPath(settings, change.path, change.value), - userSettings, - ) + let nextUserSettings: Record + try { + nextUserSettings = changes.reduce( + (settings, change) => setByPath(settings, change.path, change.value), + userSettings, + ) + } catch (error) { + // An index past the end of a stored array can only be found once the settings are read. The merged + // settings below replay the same writes onto arrays that are at least as long, so only this step can fail. + if (error instanceof SettingsPathError) { + return { ok: false as const, issues: [{ path: error.path, message: error.message }] } + } + throw error + } // The paths of the request were checked above, but a change to a path that holds a protected value, such as // replacing `admin`, writes that value too. Compare what would be saved with what is stored. diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 805963cc2..515023b8c 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -289,6 +289,23 @@ type PathToken = index: number } +/** + * The highest array index a settings path may name. Settings arrays are short lists, so a path such as + * `dvm.workers[2000000000]` is refused before the settings are read. + */ +export const MAX_SETTINGS_PATH_INDEX = 10_000 + +/** Thrown by `setByPath` when a path names an array index past the end of the array. */ +export class SettingsPathError extends Error { + public constructor( + public readonly path: string, + message: string, + ) { + super(message) + this.name = 'SettingsPathError' + } +} + export const toCategoryLabel = (key: string): string => { return key .split(/[_\-.]/) @@ -733,9 +750,17 @@ export const getByPath = (settings: unknown, path: string): unknown => { return current } -const ensureArrayLength = (target: unknown[], minimumLength: number): void => { - while (target.length <= minimumLength) { - target.push(undefined) +/** + * An array may be written at an index it already has, or at its length to append one element. A larger index + * would leave a gap, and filling that gap one element at a time takes as long as the caller-chosen index is big. + */ +const assertWritableIndex = (target: unknown[], index: number, path: string): void => { + if (index > target.length) { + throw new SettingsPathError( + path, + `Array index ${index} is past the end of an array of length ${target.length}. ` + + `Update an existing index or append at index ${target.length}.`, + ) } } @@ -775,7 +800,7 @@ export const setByPath = (settings: Record, path: string, value throw new Error(`Cannot index non-array path at [${token.index}]`) } - ensureArrayLength(current, token.index) + assertWritableIndex(current, token.index, path) const existing = current[token.index] if (existing === undefined) { @@ -804,16 +829,28 @@ export const setByPath = (settings: Record, path: string, value throw new Error(`Cannot index non-array path at [${last.index}]`) } - ensureArrayLength(current, last.index) + assertWritableIndex(current, last.index, path) current[last.index] = value return clone } export const validatePathAgainstDefaults = (path: string): ValidationIssue[] => { - const defaults = loadDefaults() as unknown const tokens = parsePath(path) + const outOfRange = tokens.find( + (token) => token.type === 'index' && (!Number.isSafeInteger(token.index) || token.index > MAX_SETTINGS_PATH_INDEX), + ) + if (outOfRange) { + return [ + { + path, + message: `Array index must be a whole number from 0 to ${MAX_SETTINGS_PATH_INDEX}`, + }, + ] + } + + const defaults = loadDefaults() as unknown if (pathExistsInSchema(defaults, tokens)) { return [] } diff --git a/test/unit/controllers/admin/patch-settings-controller.spec.ts b/test/unit/controllers/admin/patch-settings-controller.spec.ts index 70dad7f3f..243b9f1fe 100644 --- a/test/unit/controllers/admin/patch-settings-controller.spec.ts +++ b/test/unit/controllers/admin/patch-settings-controller.spec.ts @@ -147,4 +147,20 @@ describe('PatchAdminSettingsController settings write lock', () => { expect(settingsConfig.appendSettingsAuditLog).not.to.have.been.called expect(outboxRepository.enqueue).not.to.have.been.called }) + + it('reports an array index past the end of the stored array as a validation issue', async () => { + request.body = { path: 'limits.event.content[3].maxLength', value: 500 } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(400) + const body = response.send.firstCall.args[0] + expect(body.error).to.equal('Validation failed') + expect(body.issues).to.have.length(1) + expect(body.issues[0].path).to.equal('limits.event.content[3].maxLength') + expect(body.issues[0].message).to.include('append at index 0') + expect(settingsConfig.saveSettings).not.to.have.been.called + expect(outboxRepository.enqueue).not.to.have.been.called + }) }) diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 495579737..908bf49c0 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -15,8 +15,10 @@ import { getByPath, getTopLevelSettingCategories, loadDefaults, + MAX_SETTINGS_PATH_INDEX, parseTypedValue, parseValue, + SettingsPathError, setByPath, validatePathAgainstDefaults, validateSettings, @@ -100,6 +102,52 @@ describe('settings-config', () => { expect(issues[0].message).to.include('does not exist') }) + it('updates an existing array index and appends at the end of an array', () => { + const input = { limits: { event: { content: [{ maxLength: 100 }] } } } + + const updated = setByPath(input as any, 'limits.event.content[0].maxLength', 500) + const appended = setByPath(updated, 'limits.event.content[1].maxLength', 200) + const created = setByPath({} as any, 'dvm.workers[0].enabled', true) + + expect(getByPath(appended, 'limits.event.content')).to.deep.equal([{ maxLength: 500 }, { maxLength: 200 }]) + expect(getByPath(created, 'dvm.workers')).to.deep.equal([{ enabled: true }]) + }) + + it('refuses an array index past the end of an array without growing it', () => { + const input = { limits: { event: { content: [{ maxLength: 100 }] } } } + + for (const path of ['limits.event.content[2].maxLength', 'limits.event.content[2000000000]']) { + let error: unknown + try { + setByPath(input as any, path, 1) + } catch (caught) { + error = caught + } + + expect(error).to.be.instanceOf(SettingsPathError) + expect((error as SettingsPathError).path).to.equal(path) + expect((error as SettingsPathError).message).to.include('append at index 1') + } + + expect(() => setByPath({} as any, 'dvm.workers[2000000000].enabled', true)).to.throw(SettingsPathError) + expect(input.limits.event.content).to.deep.equal([{ maxLength: 100 }]) + }) + + it('rejects an out-of-range array index as a path validation issue', () => { + expect(validatePathAgainstDefaults(`limits.event.content[${MAX_SETTINGS_PATH_INDEX}].maxLength`)).to.deep.equal([]) + + for (const path of [ + `limits.event.content[${MAX_SETTINGS_PATH_INDEX + 1}].maxLength`, + 'limits.event.content[2000000000].maxLength', + 'limits.event.content[99999999999999999999].maxLength', + ]) { + const issues = validatePathAgainstDefaults(path) + expect(issues).to.have.length(1) + expect(issues[0].path).to.equal(path) + expect(issues[0].message).to.include(`from 0 to ${MAX_SETTINGS_PATH_INDEX}`) + } + }) + it('validates basic required fields', () => { const issues = validateSettings({} as any) From 0d07f6b439dcc85540781da7ff9c8d410a74f5b9 Mon Sep 17 00:00:00 2001 From: Abhinav Dwivedi <226445476+learnerabhinavdwivedi-droid@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:42:18 +0530 Subject: [PATCH 2/6] fix(settings): keep the rest of a default array when one of its fields is set An array in settings.yaml replaces the default array as a whole. With no override for a default array, setByPath started the user array empty. So payments.feeSchedules.admission[0].enabled, a guided field in the TUI and the admin dashboard, saved [{ enabled: true }], and the admission fee lost its default amount and whitelists. limits.event.content[1].maxLength was refused as past the end of an empty array. setByPath takes the effective (merged) settings as an optional fourth argument. When the path indexes into an array that the user settings do not hold yet, the array starts as a copy of the effective one. The admin settings controller and nostream config set pass the merged settings, so an indexed write changes that one field and keeps the other entries. Refs #1251 Co-Authored-By: Claude Opus 5.5 (cherry picked from commit f63d813a515c9992430f6f68604ca5a39417d1c7) --- .changeset/settings-path-default-arrays.md | 7 +++ CLI.md | 3 + src/cli/commands/config.ts | 5 +- .../admin/patch-settings-controller.ts | 7 ++- src/utils/settings-config.ts | 26 +++++++- .../admin/patch-settings-controller.spec.ts | 17 +++++ test/unit/utils/settings-config.spec.ts | 62 +++++++++++++++++++ 7 files changed, 120 insertions(+), 7 deletions(-) create mode 100644 .changeset/settings-path-default-arrays.md diff --git a/.changeset/settings-path-default-arrays.md b/.changeset/settings-path-default-arrays.md new file mode 100644 index 000000000..d39d60be6 --- /dev/null +++ b/.changeset/settings-path-default-arrays.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(settings): keep the rest of a default array when one of its fields is set + +An array in `settings.yaml` replaces the default array as a whole. With a `settings.yaml` that has no `payments.feeSchedules.admission`, `nostream config set payments.feeSchedules.admission[0].enabled true` (also what the TUI and the admin dashboard write) saved `admission: [{ enabled: true }]`, so the admission fee lost its default `amount` and whitelists. Setting `limits.event.content[1].maxLength` saved `[null, { maxLength }]`, which no longer validated once the relay read it back, and is refused since the out-of-range index fix. `PATCH /admin/settings` and `nostream config set` now copy the effective array into `settings.yaml` before writing the field, so the other entries and fields keep their values. diff --git a/CLI.md b/CLI.md index 102821398..48aa92187 100644 --- a/CLI.md +++ b/CLI.md @@ -105,6 +105,9 @@ nostream config set nip05.domainWhitelist '["example.com","relay.io"]' --type js An array index can update an element that exists or append one at the end (`[]`). An index past the end, or above 10,000, is rejected. To replace a whole list, set the array itself with `--type json`. +A list in `settings.yaml` replaces the default list as a whole. So when you change one element of a default +list that `settings.yaml` doesn't have yet, the whole list is copied there first, with only that field changed. + ## Development Commands ```bash diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts index 4e3e35ce6..3b7f98033 100644 --- a/src/cli/commands/config.ts +++ b/src/cli/commands/config.ts @@ -137,10 +137,11 @@ export const runConfigSet = async ( | { ok: false; validationIssues: Array<{ path: string; message: string }> } >(() => { const settings = loadUserSettings() as unknown as Record - const next = setByPath(settings, path, parseTypedValue(rawValue, valueType)) + const merged = loadMergedSettings() as unknown as Record + // With the merged settings, writing one field of a default array keeps the rest of that array. + const next = setByPath(settings, path, parseTypedValue(rawValue, valueType), merged) if (options.validate !== false) { - const merged = loadMergedSettings() as unknown as Record const mergedNext = setByPath(merged, path, getByPath(next, path)) const validationIssues = validateSettings(mergedNext as any) diff --git a/src/controllers/admin/patch-settings-controller.ts b/src/controllers/admin/patch-settings-controller.ts index f438fc9e3..35e8ef6ed 100644 --- a/src/controllers/admin/patch-settings-controller.ts +++ b/src/controllers/admin/patch-settings-controller.ts @@ -61,16 +61,18 @@ export class PatchAdminSettingsController implements IController { | { ok: false; issues: Array<{ path: string; message: string }> } >(() => { const userSettings = loadUserSettings() as unknown as Record + const merged = loadMergedSettings() as unknown as Record // Taken before the changes are applied, in case applying them edits this object in place. const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record let nextUserSettings: Record try { + // With the merged settings, writing one field of a default array keeps the rest of that array. nextUserSettings = changes.reduce( - (settings, change) => setByPath(settings, change.path, change.value), + (settings, change) => setByPath(settings, change.path, change.value, merged), userSettings, ) } catch (error) { - // An index past the end of a stored array can only be found once the settings are read. The merged + // An index past the end of an array can only be found once the settings are read. The merged // settings below replay the same writes onto arrays that are at least as long, so only this step can fail. if (error instanceof SettingsPathError) { return { ok: false as const, issues: [{ path: error.path, message: error.message }] } @@ -88,7 +90,6 @@ export class PatchAdminSettingsController implements IController { } } - const merged = loadMergedSettings() as unknown as Record const mergedNext = changes.reduce( (settings, change) => setByPath(settings, change.path, getByPath(nextUserSettings, change.path)), merged, diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 515023b8c..66be84ded 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -764,7 +764,20 @@ const assertWritableIndex = (target: unknown[], index: number, path: string): vo } } -export const setByPath = (settings: Record, path: string, value: unknown): Record => { +/** + * Returns a copy of `settings` with `value` written at `path`. + * + * An array in settings.yaml replaces the default array as a whole. When `effective` (the defaults merged with + * `settings`) is given, an indexed write into an array that `settings` does not hold yet starts from a copy of the + * effective array. So `limits.event.content[1].maxLength` changes that one field and keeps the other entries and + * fields, instead of saving an array that holds only the field that was written. + */ +export const setByPath = ( + settings: Record, + path: string, + value: unknown, + effective?: Record, +): Record => { const tokens = parsePath(path) const clone: Record = structuredClone(settings) @@ -773,6 +786,7 @@ export const setByPath = (settings: Record, path: string, value } let current: unknown = clone + let currentEffective: unknown = effective for (let i = 0; i < tokens.length - 1; i++) { const token = tokens[i] @@ -784,8 +798,14 @@ export const setByPath = (settings: Record, path: string, value } const existing = current[token.key] + const effectiveChild = + isPlainObject(currentEffective) && hasOwn(currentEffective, token.key) ? currentEffective[token.key] : undefined if (existing === undefined) { - current[token.key] = nextToken.type === 'index' ? [] : {} + if (nextToken.type === 'index') { + current[token.key] = Array.isArray(effectiveChild) ? structuredClone(effectiveChild) : [] + } else { + current[token.key] = {} + } } else if (nextToken.type === 'index' && !Array.isArray(existing)) { current[token.key] = [] } else if (nextToken.type === 'key' && !isPlainObject(existing)) { @@ -793,6 +813,7 @@ export const setByPath = (settings: Record, path: string, value } current = current[token.key] + currentEffective = effectiveChild continue } @@ -812,6 +833,7 @@ export const setByPath = (settings: Record, path: string, value } current = current[token.index] + currentEffective = Array.isArray(currentEffective) ? currentEffective[token.index] : undefined } const last = tokens[tokens.length - 1] diff --git a/test/unit/controllers/admin/patch-settings-controller.spec.ts b/test/unit/controllers/admin/patch-settings-controller.spec.ts index 243b9f1fe..8e70d9d24 100644 --- a/test/unit/controllers/admin/patch-settings-controller.spec.ts +++ b/test/unit/controllers/admin/patch-settings-controller.spec.ts @@ -163,4 +163,21 @@ describe('PatchAdminSettingsController settings write lock', () => { expect(settingsConfig.saveSettings).not.to.have.been.called expect(outboxRepository.enqueue).not.to.have.been.called }) + + it('saves the whole default array when one field of an entry the stored settings do not hold is changed', async () => { + const content = [ + { description: 'kinds 0-10', maxLength: 100, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, + ] + ;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) + request.body = { path: 'limits.event.content[1].maxLength', value: 500 } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(200) + const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0] + expect(saved.limits.event.content).to.deep.equal([content[0], { ...content[1], maxLength: 500 }]) + expect(content[1].maxLength).to.equal(200) + }) }) diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 908bf49c0..356ff9401 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -2,6 +2,7 @@ import { expect } from 'chai' import fs from 'fs' import os from 'os' import path from 'path' +import { mergeDeepRight } from 'ramda' import Sinon from 'sinon' import yaml from 'js-yaml' @@ -133,6 +134,67 @@ describe('settings-config', () => { expect(input.limits.event.content).to.deep.equal([{ maxLength: 100 }]) }) + it('starts an indexed write from the effective array when the settings do not hold that array', () => { + const effective = { + limits: { + event: { + content: [ + { description: 'kinds 0-10', maxLength: 100, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, + ], + }, + }, + } + + const second = setByPath({} as any, 'limits.event.content[1].maxLength', 500, effective) + const first = setByPath({ limits: { event: {} } } as any, 'limits.event.content[0].maxLength', 50, effective) + + expect(getByPath(second, 'limits.event.content')).to.deep.equal([ + { description: 'kinds 0-10', maxLength: 100, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 500, kinds: [[11, 39]] }, + ]) + expect(getByPath(first, 'limits.event.content')).to.deep.equal([ + { description: 'kinds 0-10', maxLength: 50, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, + ]) + expect(effective.limits.event.content[1].maxLength).to.equal(200) + }) + + it('writes into an array the settings already hold, and refuses an index past the end of the effective array', () => { + const effective = { limits: { event: { content: [{ maxLength: 100 }, { maxLength: 200 }] } } } + + const updated = setByPath( + { limits: { event: { content: [{ maxLength: 300 }] } } } as any, + 'limits.event.content[0].maxLength', + 400, + effective, + ) + + expect(getByPath(updated, 'limits.event.content')).to.deep.equal([{ maxLength: 400 }]) + expect(() => setByPath({} as any, 'limits.event.content[3].maxLength', 1, effective)) + .to.throw(SettingsPathError) + .with.property('message') + .that.includes('append at index 2') + }) + + it('keeps the rest of a default array when a guided field writes one of its fields', () => { + const defaults = loadDefaults() as any + + for (const [path, value] of [ + ['limits.event.content[1].maxLength', 50000], + ['payments.feeSchedules.admission[0].enabled', true], + ] as const) { + const saved = setByPath({} as any, path, value, defaults) + const reloaded = mergeDeepRight(defaults, saved) as any + const arrayPath = path.slice(0, path.lastIndexOf('[')) + const expected = setByPath(defaults, path, value) + + expect(getByPath(reloaded, arrayPath)).to.deep.equal(getByPath(expected, arrayPath)) + expect(getByPath(reloaded, path)).to.equal(value) + expect(validateSettings(reloaded).filter((issue) => issue.path.startsWith(arrayPath))).to.deep.equal([]) + } + }) + it('rejects an out-of-range array index as a path validation issue', () => { expect(validatePathAgainstDefaults(`limits.event.content[${MAX_SETTINGS_PATH_INDEX}].maxLength`)).to.deep.equal([]) From 77f07226fa8b9508edf7b123d90acd91e33f0587 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 29 Nov 2026 09:12:36 -0500 Subject: [PATCH 3/6] fix(settings): replay a batch change with the value it had at its step A batch can replace an array an earlier change wrote into. The replay read every path from the final settings, so `{"path":"limits.event.pubkey"}` arrived at the replay as `{ blacklist: [] }` and the following `blacklist[1]` write found an empty array: a batch whose final settings are valid answered 500. The first pass now records each change's value in the state right after that change, and the replay applies those in order. The replay is also inside the same `SettingsPathError` catch, so a batch that cannot be applied answers a 400 issue on the path rather than a 500. Raised by CodeRabbit on #1279. --- .../admin/patch-settings-controller.ts | 34 ++++++++++++------ .../admin/patch-settings-controller.spec.ts | 35 +++++++++++++++++++ 2 files changed, 59 insertions(+), 10 deletions(-) diff --git a/src/controllers/admin/patch-settings-controller.ts b/src/controllers/admin/patch-settings-controller.ts index 35e8ef6ed..f691f5791 100644 --- a/src/controllers/admin/patch-settings-controller.ts +++ b/src/controllers/admin/patch-settings-controller.ts @@ -65,15 +65,19 @@ export class PatchAdminSettingsController implements IController { // Taken before the changes are applied, in case applying them edits this object in place. const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record let nextUserSettings: Record + // Each change's value in the state right after it was applied, not its value at the end of the batch. + // A later change can replace an array an earlier one wrote into, so reading every path from the final + // settings would replay change 3 before change 2 and fail on a batch whose final settings are valid. + const applied: unknown[] = [] try { // With the merged settings, writing one field of a default array keeps the rest of that array. - nextUserSettings = changes.reduce( - (settings, change) => setByPath(settings, change.path, change.value, merged), - userSettings, - ) + nextUserSettings = changes.reduce((settings, change) => { + const next = setByPath(settings, change.path, change.value, merged) + applied.push(getByPath(next, change.path)) + return next + }, userSettings) } catch (error) { - // An index past the end of an array can only be found once the settings are read. The merged - // settings below replay the same writes onto arrays that are at least as long, so only this step can fail. + // An index past the end of an array can only be found once the settings are read. if (error instanceof SettingsPathError) { return { ok: false as const, issues: [{ path: error.path, message: error.message }] } } @@ -90,10 +94,20 @@ export class PatchAdminSettingsController implements IController { } } - const mergedNext = changes.reduce( - (settings, change) => setByPath(settings, change.path, getByPath(nextUserSettings, change.path)), - merged, - ) + // The replay runs the same writes in the same order onto the merged settings, whose arrays are at least + // as long as the stored ones at every step, so it can only fail where the first pass already did. + let mergedNext: Record + try { + mergedNext = changes.reduce( + (settings, change, index) => setByPath(settings, change.path, applied[index]), + merged, + ) + } catch (error) { + if (error instanceof SettingsPathError) { + return { ok: false as const, issues: [{ path: error.path, message: error.message }] } + } + throw error + } const validationIssues = validateSettings(mergedNext as unknown as Settings) if (validationIssues.length > 0) { diff --git a/test/unit/controllers/admin/patch-settings-controller.spec.ts b/test/unit/controllers/admin/patch-settings-controller.spec.ts index 8e70d9d24..ba887dda1 100644 --- a/test/unit/controllers/admin/patch-settings-controller.spec.ts +++ b/test/unit/controllers/admin/patch-settings-controller.spec.ts @@ -180,4 +180,39 @@ describe('PatchAdminSettingsController settings write lock', () => { expect(saved.limits.event.content).to.deep.equal([content[0], { ...content[1], maxLength: 500 }]) expect(content[1].maxLength).to.equal(200) }) + + it('saves a batch whose later change empties an array an earlier change wrote into', async () => { + // The replay passed each path's final value, so `pubkey` arrived as `{ blacklist: [] }` and the + // `blacklist[1]` write had no array left to append to: a valid batch answered 500. + request.body = { + changes: [ + { path: 'limits.event.pubkey', value: { blacklist: ['a.example'] } }, + { path: 'limits.event.pubkey.blacklist[1]', value: 'b.example' }, + { path: 'limits.event.pubkey.blacklist', value: [] }, + ], + } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(200) + const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0] + expect(saved.limits.event.pubkey.blacklist).to.deep.equal([]) + }) + + it('reports an unappliable batch as a path issue instead of a 500', async () => { + request.body = { + changes: [ + { path: 'limits.event.pubkey.blacklist', value: [] }, + { path: 'limits.event.pubkey.blacklist[1]', value: 'b.example' }, + ], + } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(400) + expect(response.send.firstCall.args[0].issues[0].path).to.equal('limits.event.pubkey.blacklist[1]') + expect(settingsConfig.saveSettings).not.to.have.been.called + }) }) From 6fe98057024676e0f1f69c7268c4c331c5edb8e1 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 29 Nov 2026 09:19:01 -0500 Subject: [PATCH 4/6] fix(settings): seed the replay from the merged settings too The replay stopped passing the merged settings as the effective seed, so a batch that replaced a parent object first (`limits.event = {}`) then wrote `limits.event.content[1].maxLength` replayed onto an empty array and answered 400 for settings the first pass had accepted. Both passes now take the same seed. Raised by Greptile on #1279. --- .../admin/patch-settings-controller.ts | 4 +++- .../admin/patch-settings-controller.spec.ts | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/controllers/admin/patch-settings-controller.ts b/src/controllers/admin/patch-settings-controller.ts index f691f5791..10a298f3c 100644 --- a/src/controllers/admin/patch-settings-controller.ts +++ b/src/controllers/admin/patch-settings-controller.ts @@ -98,8 +98,10 @@ export class PatchAdminSettingsController implements IController { // as long as the stored ones at every step, so it can only fail where the first pass already did. let mergedNext: Record try { + // The seed is the same `merged`, as in the first pass: a replay of `limits.event = {}` leaves + // an array an earlier default carried to be copied again, not started empty. mergedNext = changes.reduce( - (settings, change, index) => setByPath(settings, change.path, applied[index]), + (settings, change, index) => setByPath(settings, change.path, applied[index], merged), merged, ) } catch (error) { diff --git a/test/unit/controllers/admin/patch-settings-controller.spec.ts b/test/unit/controllers/admin/patch-settings-controller.spec.ts index ba887dda1..443c0f37c 100644 --- a/test/unit/controllers/admin/patch-settings-controller.spec.ts +++ b/test/unit/controllers/admin/patch-settings-controller.spec.ts @@ -200,6 +200,27 @@ describe('PatchAdminSettingsController settings write lock', () => { expect(saved.limits.event.pubkey.blacklist).to.deep.equal([]) }) + it('keeps copying the default array when an earlier change replaced its parent', async () => { + const content = [ + { description: 'kinds 0-10', maxLength: 100, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, + ] + ;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) + request.body = { + changes: [ + { path: 'limits.event', value: {} }, + { path: 'limits.event.content[1].maxLength', value: 500 }, + ], + } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(200) + const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0] + expect(saved.limits.event.content).to.deep.equal([content[0], { ...content[1], maxLength: 500 }]) + }) + it('reports an unappliable batch as a path issue instead of a 500', async () => { request.body = { changes: [ From 994da09183a687ee9c7255636ac5af08da19bc76 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 29 Nov 2026 09:25:01 -0500 Subject: [PATCH 5/6] fix(settings): seed an indexed write from the defaults, not the pre-batch settings An array is only seeded when the working settings lack it, and there the effective array is the default one. Reading it from the merged settings brought back an override an earlier change in the same batch had removed: stored `pubkey.blacklist = [A, B]`, a batch of `pubkey = {}` then `blacklist[0] = C` saved `[C, B]` where the two requests sent separately save `[C]`. Both passes and the CLI now pass `loadDefaults()`, which is the same object a single change saw before (`merged` equals defaults whenever the settings do not hold the key) and the right one mid-batch. Raised by CodeRabbit on #1279. --- src/cli/commands/config.ts | 5 ++-- .../admin/patch-settings-controller.ts | 19 +++++++++------ src/utils/settings-config.ts | 23 ++++++++++--------- .../admin/patch-settings-controller.spec.ts | 23 +++++++++++++++++++ 4 files changed, 50 insertions(+), 20 deletions(-) diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts index 3b7f98033..97057e8fd 100644 --- a/src/cli/commands/config.ts +++ b/src/cli/commands/config.ts @@ -3,6 +3,7 @@ import yaml from 'js-yaml' import { getByPath, + loadDefaults, loadMergedSettings, loadUserSettings, parseTypedValue, @@ -138,8 +139,8 @@ export const runConfigSet = async ( >(() => { const settings = loadUserSettings() as unknown as Record const merged = loadMergedSettings() as unknown as Record - // With the merged settings, writing one field of a default array keeps the rest of that array. - const next = setByPath(settings, path, parseTypedValue(rawValue, valueType), merged) + // With the defaults, writing one field of a default array keeps the rest of that array. + const next = setByPath(settings, path, parseTypedValue(rawValue, valueType), loadDefaults() as any) if (options.validate !== false) { const mergedNext = setByPath(merged, path, getByPath(next, path)) diff --git a/src/controllers/admin/patch-settings-controller.ts b/src/controllers/admin/patch-settings-controller.ts index 10a298f3c..d01dc9c99 100644 --- a/src/controllers/admin/patch-settings-controller.ts +++ b/src/controllers/admin/patch-settings-controller.ts @@ -6,6 +6,7 @@ import { adminSettingsPatchBodySchema } from '../../schemas/admin-settings-schem import { appendSettingsAuditLog, getByPath, + loadDefaults, loadMergedSettings, loadUserSettings, saveSettings, @@ -62,6 +63,10 @@ export class PatchAdminSettingsController implements IController { >(() => { const userSettings = loadUserSettings() as unknown as Record const merged = loadMergedSettings() as unknown as Record + // The seed for an indexed write. Only a key the working settings lack is seeded, so the effective + // array there is the default one: reading it from `merged` (the pre-batch settings) would bring back + // an override an earlier change in the same batch removed. + const defaults = loadDefaults() as unknown as Record // Taken before the changes are applied, in case applying them edits this object in place. const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record let nextUserSettings: Record @@ -70,9 +75,9 @@ export class PatchAdminSettingsController implements IController { // settings would replay change 3 before change 2 and fail on a batch whose final settings are valid. const applied: unknown[] = [] try { - // With the merged settings, writing one field of a default array keeps the rest of that array. + // With the defaults, writing one field of a default array keeps the rest of that array. nextUserSettings = changes.reduce((settings, change) => { - const next = setByPath(settings, change.path, change.value, merged) + const next = setByPath(settings, change.path, change.value, defaults) applied.push(getByPath(next, change.path)) return next }, userSettings) @@ -94,14 +99,14 @@ export class PatchAdminSettingsController implements IController { } } - // The replay runs the same writes in the same order onto the merged settings, whose arrays are at least - // as long as the stored ones at every step, so it can only fail where the first pass already did. + // The replay runs the same writes in the same order onto the merged settings, with the same seed the + // first pass used, so it can only fail where the first pass already did. let mergedNext: Record try { - // The seed is the same `merged`, as in the first pass: a replay of `limits.event = {}` leaves - // an array an earlier default carried to be copied again, not started empty. + // The seed is the same `defaults`, as in the first pass: a replay of `limits.event = {}` copies + // the default array again rather than starting it empty. mergedNext = changes.reduce( - (settings, change, index) => setByPath(settings, change.path, applied[index], merged), + (settings, change, index) => setByPath(settings, change.path, applied[index], defaults), merged, ) } catch (error) { diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 66be84ded..5f6dead29 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -767,16 +767,17 @@ const assertWritableIndex = (target: unknown[], index: number, path: string): vo /** * Returns a copy of `settings` with `value` written at `path`. * - * An array in settings.yaml replaces the default array as a whole. When `effective` (the defaults merged with - * `settings`) is given, an indexed write into an array that `settings` does not hold yet starts from a copy of the - * effective array. So `limits.event.content[1].maxLength` changes that one field and keeps the other entries and - * fields, instead of saving an array that holds only the field that was written. + * An array in settings.yaml replaces the default array as a whole. When `defaults` is given, an indexed write into + * an array that `settings` does not hold yet starts from a copy of the default array there. So + * `limits.event.content[1].maxLength` changes that one field and keeps the other entries and fields, instead of + * saving an array that holds only the field that was written. Pass the defaults, not the merged settings: a batch + * can remove an override before writing into the array, and the merged settings still carry it. */ export const setByPath = ( settings: Record, path: string, value: unknown, - effective?: Record, + defaults?: Record, ): Record => { const tokens = parsePath(path) const clone: Record = structuredClone(settings) @@ -786,7 +787,7 @@ export const setByPath = ( } let current: unknown = clone - let currentEffective: unknown = effective + let currentDefaults: unknown = defaults for (let i = 0; i < tokens.length - 1; i++) { const token = tokens[i] @@ -798,11 +799,11 @@ export const setByPath = ( } const existing = current[token.key] - const effectiveChild = - isPlainObject(currentEffective) && hasOwn(currentEffective, token.key) ? currentEffective[token.key] : undefined + const defaultChild = + isPlainObject(currentDefaults) && hasOwn(currentDefaults, token.key) ? currentDefaults[token.key] : undefined if (existing === undefined) { if (nextToken.type === 'index') { - current[token.key] = Array.isArray(effectiveChild) ? structuredClone(effectiveChild) : [] + current[token.key] = Array.isArray(defaultChild) ? structuredClone(defaultChild) : [] } else { current[token.key] = {} } @@ -813,7 +814,7 @@ export const setByPath = ( } current = current[token.key] - currentEffective = effectiveChild + currentDefaults = defaultChild continue } @@ -833,7 +834,7 @@ export const setByPath = ( } current = current[token.index] - currentEffective = Array.isArray(currentEffective) ? currentEffective[token.index] : undefined + currentDefaults = Array.isArray(currentDefaults) ? currentDefaults[token.index] : undefined } const last = tokens[tokens.length - 1] diff --git a/test/unit/controllers/admin/patch-settings-controller.spec.ts b/test/unit/controllers/admin/patch-settings-controller.spec.ts index 443c0f37c..b87f1f28d 100644 --- a/test/unit/controllers/admin/patch-settings-controller.spec.ts +++ b/test/unit/controllers/admin/patch-settings-controller.spec.ts @@ -36,6 +36,7 @@ describe('PatchAdminSettingsController settings write lock', () => { sandbox.stub(settingsConfig, 'withSettingsWriteLock').callsFake(async (operation: () => unknown) => operation()) sandbox.stub(settingsConfig, 'loadUserSettings').returns(baseSettings as any) sandbox.stub(settingsConfig, 'loadMergedSettings').returns(baseSettings as any) + sandbox.stub(settingsConfig, 'loadDefaults').returns(baseSettings as any) sandbox.stub(settingsConfig, 'saveSettings') sandbox.stub(settingsConfig, 'appendSettingsAuditLog') sandbox.stub(settingsConfig, 'validatePathAgainstDefaults').returns([]) @@ -170,6 +171,7 @@ describe('PatchAdminSettingsController settings write lock', () => { { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, ] ;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) + ;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) request.body = { path: 'limits.event.content[1].maxLength', value: 500 } const controller = new PatchAdminSettingsController(outboxRepository as any) @@ -206,6 +208,7 @@ describe('PatchAdminSettingsController settings write lock', () => { { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, ] ;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) + ;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) request.body = { changes: [ { path: 'limits.event', value: {} }, @@ -221,6 +224,26 @@ describe('PatchAdminSettingsController settings write lock', () => { expect(saved.limits.event.content).to.deep.equal([content[0], { ...content[1], maxLength: 500 }]) }) + it('does not bring back a stored override an earlier change in the batch removed', async () => { + const stored = { blacklist: ['a.example', 'b.example'] } + ;(settingsConfig.loadUserSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: stored } } }) + ;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: stored } } }) + ;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: { blacklist: [] } } } }) + request.body = { + changes: [ + { path: 'limits.event.pubkey', value: {} }, + { path: 'limits.event.pubkey.blacklist[0]', value: 'c.example' }, + ], + } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(200) + const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0] + expect(saved.limits.event.pubkey.blacklist).to.deep.equal(['c.example']) + }) + it('reports an unappliable batch as a path issue instead of a 500', async () => { request.body = { changes: [ From bf518d226349a749f816d3f08bc5f85981a93942 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 29 Nov 2026 09:34:33 -0500 Subject: [PATCH 6/6] fix(settings): copy defaults into a missing key, never into a stored array MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A stored array replaces the default array whole (`mergeDeepRight` replaces arrays, it does not merge them by index), so nothing below an array the settings hold may be copied from the defaults. The previous rule seeded nested defaults anyway: with a default `rateLimits[0].kinds = [[3,40,41]]` and a stored rule of `{ period, rate }`, writing `kinds[0]` saved `[1, 3, 40, 41]` — the operator's rule applying to two kinds they never listed. The seed now follows the merge: an object the settings hold is merged key by key, so defaults below it still apply, and an array the settings hold ends the seed. Raised by Greptile on #1279. --- src/utils/settings-config.ts | 11 +++++++++-- test/unit/utils/settings-config.spec.ts | 11 +++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 5f6dead29..263ee38f0 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -799,6 +799,9 @@ export const setByPath = ( } const existing = current[token.key] + // A key the settings hold replaces the default value whole, so nothing below it is copied from the + // defaults: the operator's array carries its own entries, and filling a nested array from the default + // would apply the operator's rule to event kinds they never listed. const defaultChild = isPlainObject(currentDefaults) && hasOwn(currentDefaults, token.key) ? currentDefaults[token.key] : undefined if (existing === undefined) { @@ -814,7 +817,9 @@ export const setByPath = ( } current = current[token.key] - currentDefaults = defaultChild + // An object the settings hold is merged with the default object key by key, so the defaults below it still + // apply; an array the settings hold replaces the default array whole, so nothing below it may be copied. + currentDefaults = Array.isArray(existing) ? undefined : defaultChild continue } @@ -834,7 +839,9 @@ export const setByPath = ( } current = current[token.index] - currentDefaults = Array.isArray(currentDefaults) ? currentDefaults[token.index] : undefined + // Same rule one level down: an entry the settings hold is the operator's, and its missing fields are not + // filled from the default entry at that index. + currentDefaults = existing === undefined && Array.isArray(currentDefaults) ? currentDefaults[token.index] : undefined } const last = tokens[tokens.length - 1] diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 356ff9401..39634a2b0 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -195,6 +195,17 @@ describe('settings-config', () => { } }) + it('does not copy a default into a nested array of a rule the settings hold', () => { + const defaults = { + limits: { event: { rateLimits: [{ period: 60000, rate: 720, kinds: [[3, 40, 41]] }] } }, + } as any + const settings = { limits: { event: { rateLimits: [{ period: 1000, rate: 5 }] } } } as any + + const next = setByPath(settings, 'limits.event.rateLimits[0].kinds[0]', 1, defaults) as any + + expect(next.limits.event.rateLimits[0]).to.deep.equal({ period: 1000, rate: 5, kinds: [1] }) + }) + it('rejects an out-of-range array index as a path validation issue', () => { expect(validatePathAgainstDefaults(`limits.event.content[${MAX_SETTINGS_PATH_INDEX}].maxLength`)).to.deep.equal([])