@octabits-io/settings
Runtime settings an administrator manages in the app: an API key for a
model vendor, the SMTP relay, a feature switch, a numeric limit. Every setting
is declared once — its name, label, kind, choices, default, and the probe that
tests it after a save — and resolved stored → environment → default, so a
created app runs on its .env until an administrator opens the settings page,
and a value set there wins from then on. Secrets are encrypted through a cipher
you plug in, returned masked, unmasked through one call you gate, and never
part of an error. A write is validated against the declaration and returns the
before/after pair your audit log records.
npm i @octabits-io/settings zod # + drizzle-orm if you declare the table with ./drizzle
import { createSettings, defineSettings } from '@octabits-io/settings';
import { createPostgresSettingsStore } from '@octabits-io/settings/postgres';
export const settings = createSettings({
declaration: defineSettings({
groups: [
{
name: 'model',
label: 'Model',
fields: [
{ name: 'MODEL_PROVIDER', label: 'Provider', kind: 'choice', choices: ['scripted', 'mistral', 'ollama'], default: 'scripted' },
{ name: 'MODEL_API_KEY', label: 'API key', kind: 'secret', placeholder: 'sk-…' },
{ name: 'MODEL_URL', label: 'Endpoint', kind: 'url', default: 'http://localhost:11434' },
],
probe: async ({ values }) => probeModel(values), // "save, then test" — one shape for every vendor
},
{
name: 'features',
label: 'Features',
fields: [{ name: 'FEATURE_IMPORT', label: 'Spreadsheet import', kind: 'switch', default: false }],
},
],
}),
store: createPostgresSettingsStore({ db: pool }),
cipher, // the seam a secret crosses; see "Secrets"
env: process.env, // what a stored value falls back to
});
const provider = await settings.get('MODEL_PROVIDER'); // ok('scripted') from the default
const key = await settings.get('MODEL_API_KEY'); // ok('••••XYZ9') — masked
const importOn = await settings.isOn('FEATURE_IMPORT'); // a Result, like every read
if (importOn.ok && importOn.value) { /* … */ }
const change = await settings.set('MODEL_PROVIDER', 'mistral', { actor: staffId, reason: 'EU vendor' });
// change.value = { name, secret: false, before: { value: 'scripted', source: 'default' }, after: { value: 'mistral', source: 'stored' }, actor, reason, updatedAt }
await audit.record(tx, { actor: staffId, action: 'settings.set', target: { kind: 'setting', id: 'MODEL_PROVIDER' }, reason, before: change.value.before, after: change.value.after });
| Subpath | Deps | Contents |
|---|---|---|
. |
zod (peer), @octabits-io/result |
defineSettings / checkDeclaration (the declaration, validation by kind), createSettings (the resolver: get, resolve, getAll, isOn, set, reveal, invalidate, probe, close), the SettingsStore contract and createInMemorySettingsStore, the SettingsCipher and SettingsSync seams, maskSecret |
./postgres |
none | createPostgresSettingsStore over a structural SqlExecutor — pg Pool/Client, PGlite, a wrapper over postgres.js — plus settingsDdl() |
./drizzle |
drizzle-orm (optional peer) |
settingsColumns, the table for drizzle-kit, and createDrizzleSettingsStore |
A boundary lint keeps the root on zod and result and drizzle-orm in
./drizzle; the package type-checks with no Node typings — the environment
is a record you hand in, the cipher a seam.
When not to use it
A value that never changes at runtime and is not a secret (the port, the log
level) belongs in the environment and @octabits-io/server’s getEnv*
readers. A value per user (their locale, their notification preferences) is a
column on the user, not a setting. A value the code depends on at build time
is neither. Settings are what an operator changes while the app runs, and
what an administrator must be able to test on the spot.
The declaration
Every setting is a field in a group; the group is the admin page it lives on.
| Kind | Holds | Validation | In text (store, environment) |
|---|---|---|---|
text |
a string | — | as is |
secret |
a string | — | stored encrypted; see “Secrets” |
choice |
one of choices |
choices required |
as is |
number |
a finite number | schema for bounds |
"0.5" |
url |
an absolute URL | schemes (http, https by default) |
as is |
json |
a JSON document | schema for the shape |
JSON.stringify |
switch |
a boolean | — | true/false; 1/0, on/off, yes/no read too |
A field may carry a Zod schema on top of its kind — a bound on a number, a
pattern on a text, the shape of a JSON document — so the declaration is still
data and a host can also hand a schema it generated. defineSettings throws
on a malformed declaration (a duplicate name, a choice without choices, a
secret with a default, a default outside its kind): that is a programming
error, found at start-up, not an operator’s value. checkDeclaration is the
same check as a Result, for a declaration built from data.
A field may say when it applies: when: { setting: 'AI_MODEL', is: ['local'] }
names another setting of the same group — a choice or a switch — and the
values under which the field matters (null for unset). An endpoint under a
local model, a key under a vendor, a relay’s login under SMTP. It is
presentation only: the admin page shows the field while the condition holds,
and settingApplies(field.when, value) is the one test a form runs against
the value it holds now, before a save. The value still resolves and set
still takes it — a host whose code reads a setting under the wrong choice has
a bug the page must not hide. The declaration check refuses a when on
another group’s setting, on a setting that is no choice or switch, and with a
value that setting can never hold.
{ name: 'AI_BASE_URL', label: 'Endpoint', kind: 'url', when: { setting: 'AI_MODEL', is: ['local'] } },
The resolution order
get(name) answers, in this order, and resolve(name) says which:
- stored — the row an administrator wrote;
- environment —
env[name], the variable with the setting’s name; - default — the declaration’s;
- none —
null.
A stored row wins over the environment: an administrator who sets a value
in the app expects it to apply, whatever the container was started with. To
hand a setting back to the environment, set(name, null, …) removes the
row. A text the environment or the store carries that does not decode as the
kind is an error (setting_invalid) on read, not a silent fallback: a wrong
MODEL_TEMPERATURE=warm is found at the first read, named by setting, with
the value left out of the message.
Settings versus the environment. The environment is where a deployment
puts what it knows at start: the database URL, the issuer, the keys the
process must have before it serves a request — the resolver itself needs its
cipher’s key from somewhere, and that somewhere is not a setting. Settings
are what an operator may change later without a deploy, and what an
administrator with the right role may change at all. A setting with an
environment fallback is the bridge: a created app ships with its .env, the
settings page is empty, and the first value saved there is the first row.
Secrets
A secret field is:
- stored encrypted, through the
cipheryou pass —{ encrypt(text), decrypt(text) }, text in and text out.@octabits-io/pii’s string encryption fits behind a two-line adapter; so does Web Crypto with a key you derive. Without a cipher,setand every read of a stored secret refuse withsetting_cipher_missing; a secret from the environment still resolves; - returned masked by
get,resolve,getAlland in the before/after pair:••••and the last four characters,••••alone when the value is eight characters or shorter; - unmasked through
reveal(name)alone, and in a probe’s context — gaterevealbehind the role that may see the value, and use it where the value is used (the vendor client); - never in an error: a refused value, a cipher that fails, a store that fails — the
message names the setting and the reason and leaves the value out. The test
index.test.tsholds that for every path; - refused by declaration on a path that must not carry one:
set(name, value, { actor, allowSecret: false })answerssetting_secret_refusedfor a secret and writes anything else. A command bar, an assistant or a model-driven action passesallowSecret: falseand cannot be talked into a secret; - never a default: a secret’s default would be a secret in the source. The declaration refuses one.
import { createPiiEncryptionService } from '@octabits-io/pii';
const pii = createPiiEncryptionService({ recipient, identity });
const cipher: SettingsCipher = {
encrypt: async (text) => unwrap(await pii.encryptString(text)).toBase64(),
decrypt: async (text) => unwrap(await pii.decryptString(Uint8Array.fromBase64(text))),
};
The cache
Rows are cached per resolver after the first read and served until:
invalidate(name)orinvalidate()— called bysetfor the setting it wrote;- a message on
sync— the seam that keeps every replica honest:publish({ name })is called after a write,subscribe(handler)delivers every replica’s writes; cache: { ttlMs }— the ceiling, one minute by default (DEFAULT_SETTINGS_TTL_MS). A broadcast is a hint that can be lost (a reconnect, a replica that was down), so there is always a ceiling unless you passttlMs: Infinityon purpose.cache: falsereads the store on everyget.
A read that started before an invalidation does not cache what it read, so an invalidation
that lands while the store answers is not undone by the old row. set reads its
before/after pair past the cache and caches neither half.
One reader per process, a writer per transaction. A hint must reach the replicas only once the write is committed: heard before, a replica re-reads, caches the old row and serves it until the ceiling. So the two halves live on two resolvers:
- the reader — built once per process (per scope value, in a map, if you scope), over
the pooled store, with
sync.subscribe.subscribeis called when the resolver is built and holds a listener — withevents, a dedicatedLISTENconnection — untilsettings.close(); call it on shutdown, and never build a subscribing resolver per request. - the writer — built per transaction over the transaction’s store, with
cache: falseand asyncthat only publishes, on that transaction.events’ broadcast channel does this withpublishInTx: Postgres delivers aNOTIFYatCOMMIT, and never for a rollback.
import { createBroadcastChannel } from '@octabits-io/events/broadcast';
const channel = createBroadcastChannel<SettingsChange>({ channel: 'settings', schema: z.object({ name: z.string().optional() }) });
// The reader: once per process. Every replica's write drops its cache; a reconnect drops all of it.
const subscription = channel.subscribe({ connectionString: DIRECT_DATABASE_URL, onMessage: (change) => settings.invalidate(change.name), onReconnect: () => settings.invalidate() });
export const settings = createSettings({ declaration, store: createDrizzleSettingsStore({ db, table: appSetting }), cipher, env: process.env });
// The writer: per transaction, publishing on it — the hint leaves at COMMIT.
await db.transaction(async (tx) => {
const writer = createSettings({ declaration, store: createDrizzleSettingsStore({ db: tx, table: appSetting }), cipher, env: process.env, cache: false, sync: { publish: (change) => channel.publishInTx(tx, change) } });
const change = await writer.set('MODEL_PROVIDER', 'mistral', { actor: staffId, reason: 'EU vendor' });
if (!change.ok) throw change.error;
await audit.record(tx, { /* … the pair */ });
});
The reader above takes the channel’s messages straight into invalidate, so it needs no
sync of its own; a sync with subscribe is the same thing behind the seam, for a pub/sub
that is not events. A message with no name drops the whole cache — what a reconnect after
a gap calls for, since a broadcast is a hint with no replay.
Save, then test
A probe on a field or a group is async (context) => Result<ProbeReport>:
it receives the group’s values revealed — a probe is what the secret is
for — and answers { ok, message, details? } for the admin page.
settings.probe(name) runs the field’s own probe, else its group’s;
settings.probe(group) runs the group’s. A target without one is
setting_probe_missing. mail’s verifySmtpConnection fits as is:
probe: async ({ values }) => {
const checked = await verifySmtpConnection({
host: values.SMTP_HOST as string,
port: values.SMTP_PORT as number,
auth: { user: values.SMTP_USER as string, pass: values.SMTP_PASSWORD as string },
});
return ok(checked.ok ? { ok: true, message: 'The relay answered' } : { ok: false, message: checked.error.message });
},
The admin page
getAll() is the page as data: every group in declaration order, every field
with its label, kind, choices, placeholder, description and when, the value (a
secret masked), its source, whether a stored row exists (an environment value
an administrator cannot clear reads stored: false), who last wrote it and
when, and whether “save, then test” applies. No code crosses: the probe and
the schema stay on the declaration.
A value that is there but cannot be read — a stored row the declaration no
longer accepts (a choice since dropped), a ciphertext that no longer decrypts,
an environment text that does not parse — does not fail the page: its field
reads value: null with unreadable: { key, message } (setting_invalid,
setting_cipher_missing or setting_cipher_failed; the message never holds
the value). set overwrites it or, with null, deletes it, and the pair’s
before carries the same unreadable. get, resolve and reveal still
return the error: code that reads a setting must not run on a guess. Only a
failing store fails getAll as a whole.
The audit pair
set returns { name, secret, before, after, actor, reason?, updatedAt }
with before and after as { value, source } — resolved, not raw, so the
pair says what the app did before and does after, and masked for a secret.
Hand it to @octabits-io/audit’s record on the transaction of the write:
build the writer over a transaction-bound executor for the Postgres store, or
over your Drizzle transaction for the Drizzle store (see “One reader per
process, a writer per transaction” above).
Scoping
A store takes scope?: { column, value } — your column, stamped on every
write and filtered on every read, the key (column, name) — for a setting
per organisation. Without it, name is the key and the table holds one
value per setting. The resolver is scope-blind: build one per scope value,
or one global, as the host decides; scopeKey on a stored row says which
scope it came from.
The SQL adapter
./postgres takes a structural executor — query(text, params) resolving
to { rows } — so a pg Pool or Client, a PGlite instance, or
postgresJsExecutor from @octabits-io/postgres all fit. settingsDdl({ table?, scope? }) emits the table, idempotent, for a migration-managed
schema:
CREATE TABLE IF NOT EXISTS app_setting (
name text PRIMARY KEY,
value text NOT NULL,
secret boolean NOT NULL DEFAULT false,
updated_by text,
updated_at timestamptz NOT NULL DEFAULT now()
);
Non-secrets are stored plain, so a SQL report can read them; a secret row
carries its ciphertext and secret = true, so the report sees that it is not
for reading.
The Drizzle table
settingsColumns is the spreadable column set; the key is yours, because it
depends on the scope — primaryKey({ columns: [t.name] }) alone, or
[t.orgId, t.name] with a scope column. createDrizzleSettingsStore({ db, table, scope? }) is the store over it. columns.test.ts holds the column
set equal to settingsDdl() column for column.
What it does not do
It does not render the page (the host’s UI reads getAll()), does not decide
who may read or write (gate set, reveal and probe with your permission
check — @octabits-io/server/authz’s requirePermission fits), does not
write the audit entry (it returns the pair), and does not hold the cipher’s
key (that is the environment’s, or your key provider’s). It is one table of
text, one declaration, one order of resolution.
License
MIT
From @octabits-io/settings@0.3.1 in the platform repository.