Skip to content
7 changes: 7 additions & 0 deletions .changeset/settings-path-default-arrays.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 7 additions & 0 deletions .changeset/settings-path-index-bound.md
Original file line number Diff line number Diff line change
@@ -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[<length>]` work as before.
6 changes: 6 additions & 0 deletions CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ 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 (`[<length>]`). 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
Expand Down
6 changes: 4 additions & 2 deletions src/cli/commands/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import yaml from 'js-yaml'

import {
getByPath,
loadDefaults,
loadMergedSettings,
loadUserSettings,
parseTypedValue,
Expand Down Expand Up @@ -137,10 +138,11 @@ export const runConfigSet = async (
| { ok: false; validationIssues: Array<{ path: string; message: string }> }
>(() => {
const settings = loadUserSettings() as unknown as Record<string, unknown>
const next = setByPath(settings, path, parseTypedValue(rawValue, valueType))
const merged = loadMergedSettings() as unknown as Record<string, unknown>
// 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 merged = loadMergedSettings() as unknown as Record<string, unknown>
const mergedNext = setByPath(merged, path, getByPath(next, path))
const validationIssues = validateSettings(mergedNext as any)

Expand Down
51 changes: 42 additions & 9 deletions src/controllers/admin/patch-settings-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import { adminSettingsPatchBodySchema } from '../../schemas/admin-settings-schem
import {
appendSettingsAuditLog,
getByPath,
loadDefaults,
loadMergedSettings,
loadUserSettings,
saveSettings,
SettingsPathError,
setByPath,
validatePathAgainstDefaults,
validateSettings,
Expand Down Expand Up @@ -60,12 +62,32 @@ export class PatchAdminSettingsController implements IController {
| { ok: false; issues: Array<{ path: string; message: string }> }
>(() => {
const userSettings = loadUserSettings() as unknown as Record<string, unknown>
const merged = loadMergedSettings() as unknown as Record<string, unknown>
// 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<string, unknown>
// Taken before the changes are applied, in case applying them edits this object in place.
const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record<string, unknown>
const nextUserSettings = changes.reduce(
(settings, change) => setByPath(settings, change.path, change.value),
userSettings,
)
let nextUserSettings: Record<string, unknown>
// 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 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, defaults)
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.
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.
Expand All @@ -77,11 +99,22 @@ export class PatchAdminSettingsController implements IController {
}
}

const merged = loadMergedSettings() as unknown as Record<string, unknown>
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, with the same seed the
// first pass used, so it can only fail where the first pass already did.
let mergedNext: Record<string, unknown>
try {
// 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], defaults),
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) {
Expand Down
83 changes: 75 additions & 8 deletions src/utils/settings-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(/[_\-.]/)
Expand Down Expand Up @@ -733,13 +750,35 @@ 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}.`,
)
}
}

export const setByPath = (settings: Record<string, unknown>, path: string, value: unknown): Record<string, unknown> => {
/**
* Returns a copy of `settings` with `value` written at `path`.
*
* 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<string, unknown>,
path: string,
value: unknown,
defaults?: Record<string, unknown>,
): Record<string, unknown> => {
const tokens = parsePath(path)
const clone: Record<string, unknown> = structuredClone(settings)

Expand All @@ -748,6 +787,7 @@ export const setByPath = (settings: Record<string, unknown>, path: string, value
}

let current: unknown = clone
let currentDefaults: unknown = defaults

for (let i = 0; i < tokens.length - 1; i++) {
const token = tokens[i]
Expand All @@ -759,23 +799,35 @@ export const setByPath = (settings: Record<string, unknown>, path: string, value
}

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) {
current[token.key] = nextToken.type === 'index' ? [] : {}
if (nextToken.type === 'index') {
current[token.key] = Array.isArray(defaultChild) ? structuredClone(defaultChild) : []
} else {
current[token.key] = {}
}
} else if (nextToken.type === 'index' && !Array.isArray(existing)) {
current[token.key] = []
} else if (nextToken.type === 'key' && !isPlainObject(existing)) {
current[token.key] = {}
}

current = current[token.key]
// 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
}

if (!Array.isArray(current)) {
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) {
Expand All @@ -787,6 +839,9 @@ export const setByPath = (settings: Record<string, unknown>, path: string, value
}

current = current[token.index]
// 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]
Expand All @@ -804,16 +859,28 @@ export const setByPath = (settings: Record<string, unknown>, 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 []
}
Expand Down
Loading
Loading