settings

package
v0.28.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KeyBannerText      = "banner_text"
	KeyBannerKind      = "banner_kind"
	KeyMaintenanceMode = "maintenance_mode"
	KeyAllowSignup     = "allow_signup"
	KeyAllowedDomains  = "allowed_domains"

	KeyRateLimitPerUserPerMin = "rate_limit_per_user_per_min"
	KeyRateLimitPerIPPerMin   = "rate_limit_per_ip_per_min"
	KeyRateLimitAllowlist     = "rate_limit_allowlist"

	KeySMTPHost = "smtp_host"
	KeySMTPPort = "smtp_port"
	KeySMTPUser = "smtp_user"
	KeySMTPPass = "smtp_pass"
	KeySMTPFrom = "smtp_from"

	KeySiteVerificationMeta = "site_verification_meta"

	KeyShellNavHidden = "shell_nav_hidden"

	KindInfo, KindWarn = "info", "warn"
	FlagOff, FlagOn    = "0", "1"
)
View Source
const BillingChannelKeyPrefix = "billing_channel."

BillingChannelKeyPrefix namespaces the payment-channel credential keys (BC-5): every `billing_channel.<name>.<field>` row (e.g. billing_channel.waffo.merchant_id) lives in the generic site_settings KV table, is sealed at rest like smtp_pass, and is deliberately NOT a KeyOrder member — the generic settings page never renders channel cards; that surface is the dedicated admin billing-channels API.

View Source
const MaskedValue = "******"

MaskedValue is what sensitive keys (IsSensitive) render as in every read-back surface: the admin list response (both items and effective), the put response body and the admin.setting_change log entries. A client that submits MaskedValue back means "unchanged" — the put handler short-circuits on it without touching the store.

Variables

View Source
var Descriptions = map[string]string{
	KeyBannerText:             "站点公告文本,空 = 不展示公告",
	KeyBannerKind:             "公告样式:info = 蓝系 / warn = 橙红系",
	KeyMaintenanceMode:        "维护模式:开启后全站顶栏显示「维护中」条(仅提示,不阻断请求)",
	KeyAllowSignup:            "注册开关:关闭 = 邀请制,仅白名单内邮箱可注册",
	KeyAllowedDomains:         "注册邮箱域名白名单,逗号分隔(空 = 不限域名)",
	KeyRateLimitPerUserPerMin: "API 每用户限流(请求/分钟):0 = 关闭;修改后需重启生效",
	KeyRateLimitPerIPPerMin:   "认证路径每客户端 IP 限流(请求/分钟):0 = 关闭;修改后重启生效",
	KeyRateLimitAllowlist:     "限流豁免名单:逗号分隔 IP 或 CIDR(如 10.0.0.5, 192.168.0.0/16);修改后重启生效",

	KeySMTPHost:             "SMTP 服务器主机名(如 smtp.example.com;空 = 开发日志通道,邮件只写日志不外发)",
	KeySMTPPort:             "SMTP 端口(空 = 缺省 587)",
	KeySMTPUser:             "SMTP 认证用户名(空 = 不认证)",
	KeySMTPPass:             "SMTP 认证密码:保存后仅以掩码回显;落库前经 PLOYKIT_SEAL_KEY 加密,未配置该环境变量时拒绝保存",
	KeySMTPFrom:             "发件人邮箱(如 no-reply@example.com;空 = 未配置发件人)",
	KeySiteVerificationMeta: "站长验证:粘贴搜索引擎给的完整 <meta> 标签或 name|content 对(如 google-site-verification|abc123);清空即移除",
	KeyShellNavHidden:       "产品壳侧边栏隐藏菜单:JSON 字符串数组,元素为菜单路径(如 [\"/realtime\",\"/settings/workspace/schedules\"]);空 = 全部显示",
}
View Source
var ErrNoSealer = fmt.Errorf("%s: %w",
	"settings: sensitive key requires a configured sealer (PLOYKIT_SEAL_KEY)", sealx.ErrNoKey)

ErrNoSealer is returned when a sensitive key is written without a configured sealer. Fail-closed by design: no plaintext credential ever lands in the generic site_settings table — PLOYKIT_SEAL_KEY unset means sensitive writes are rejected, not degraded (AGENTS.md sealx constraint). It wraps sealx.ErrNoKey so callers that cannot import this package (billing reaches the store through its own structural port) still classify the error with errors.Is(err, sealx.ErrNoKey) and surface a 503 "configure the seal key" instead of a 500 (billing fix #10).

Functions

func IsSensitive added in v0.8.0

func IsSensitive(key string) bool

IsSensitive reports whether the key holds a credential that must never be echoed in plaintext — every read-back surface masks it with MaskedValue. smtp_pass plus the whole billing_channel.* namespace (BC-5): channel merchant ids, product ids and modes are as sensitive as the secrets — anything with the prefix seals at rest and unseals fail-closed.

func Normalize

func Normalize(key, value string) string

func ParseVerificationMeta added in v0.8.0

func ParseVerificationMeta(stored string) (name, content string, err error)

ParseVerificationMeta splits the stored normalized pair back into its parts and re-validates both. Products recompose the meta tag server-side (`<meta name="…" content="…">`) from this output — the stored user input is never reflected, only the recomposed tag is.

func SplitDomains

func SplitDomains(csv string) []string

func SplitIPAllowlist

func SplitIPAllowlist(csv string) []string

func Validate

func Validate(key, value string) error

Types

type KeySpec added in v0.15.0

type KeySpec struct {
	// Key is the settings key, e.g. "resend_api_key". Lowercase letters,
	// digits and underscores, starting with a letter, at most 64 chars; must
	// not collide with a built-in key or the billing_channel.* namespace.
	Key string

	// Description is shown in the admin settings UI next to the field.
	Description string

	// Sensitive marks a credential: sealed at rest (sealx, fail-closed),
	// masked on every read-back surface, excluded from public /config
	// (consumers filter with Store.IsSensitive), never logged.
	Sensitive bool

	// Env optionally names an environment variable that backs the key while
	// no DB row exists (DB row > env > Default). Live on every boot until an
	// admin saves a value — the "never bootstrap-seeded" generation of the
	// D2 fork in keys.go; an env credential is never frozen into the table.
	Env string

	// Default is the effective value when neither a DB row nor a non-empty
	// env value exists.
	Default string

	// Validate rejects invalid values on the admin PUT path. nil = the
	// generic 8192-char cap (same as billing_channel fields).
	Validate func(value string) error

	// Normalize canonicalizes a value before storing. nil = TrimSpace (the
	// built-in default).
	Normalize func(value string) string
}

KeySpec describes one product-registered settings key.

type Store

type Store struct {
	// contains filtered or unexported fields
}

func Bootstrap

func Bootstrap(pool *pgxpool.Pool, envLookup func(string) string) (*Store, error)

func NewStore

func NewStore(pool *pgxpool.Pool) *Store

func (*Store) All

func (s *Store) All(ctx context.Context) (map[string]string, error)

func (*Store) BillingChannelFields added in v0.13.0

func (s *Store) BillingChannelFields(ctx context.Context) (map[string]map[string]string, error)

BillingChannelFields returns every billing_channel.<name>.<field> row with values unsealed, grouped by channel name (BC-5 hot-read; same shape as SMTPConfig). Rows outside the prefix and malformed keys are skipped. A row that fails to unseal is SKIPPED with a warn log naming the key — the read still returns a partial map and nil error (billing fix #5, 2026-10-24): one poisoned row (legacy plaintext, rotated seal key) used to error the whole read and take EVERY channel down with it; now it only leaves that one channel unconfigured until the credential is re-saved. The sealx fail-closed discipline is unchanged for the row itself: the unreadable value is never returned, never fallen back to plaintext — skipping is a refusal, not a degradation. A channel with no rows is absent from the map. This is the source the hot-reload channel registry polls.

func (*Store) DefaultsMap added in v0.15.0

func (s *Store) DefaultsMap() map[string]string

DefaultsMap merges the built-in defaults with registered keys' Defaults. (Named DefaultsMap because the package-level Defaults is already a map.)

func (*Store) Descriptions added in v0.15.0

func (s *Store) Descriptions() map[string]string

Descriptions merges the built-in copy with registered keys' Descriptions (the admin settings list response renders from this map).

func (*Store) Effective

func (s *Store) Effective(ctx context.Context) (map[string]string, error)

Effective resolves every key — built-ins in KeyOrder order, then product-registered keys in registration order (registry.go).

func (*Store) EffectiveKey added in v0.17.0

func (s *Store) EffectiveKey(ctx context.Context, key string) (string, error)

EffectiveKey is the single-key hot-read (DB row > env fallback > default, same merge as Effective) for callers that need ONE value: unlike Effective it never touches unrelated keys, so a sealed credential that cannot be unsealed in this environment (no PLOYKIT_SEAL_KEY) cannot fail the read — boot-time reconcilers (e.g. legal.Wire's billing-model check) must use this, not Effective, or an unrelated sensitive key would refuse the app startup.

func (*Store) Get

func (s *Store) Get(ctx context.Context, key string) (value string, found bool, err error)

func (*Store) IsSensitive added in v0.15.0

func (s *Store) IsSensitive(key string) bool

IsSensitive extends the built-in rule with this store's registered keys. Package-level IsSensitive covers the built-ins only; consumers with a Store (the admin HTTP adapter, the public /config builder) must use this method so registered credentials seal and mask identically.

func (*Store) Maintenance

func (s *Store) Maintenance(ctx context.Context) (bool, error)

func (*Store) Normalize added in v0.15.0

func (s *Store) Normalize(key, value string) string

Normalize extends the built-in normalization with registered keys (nil spec.Normalize = TrimSpace, same as the built-in default).

func (*Store) RateLimits

func (s *Store) RateLimits(ctx context.Context) (perUser, perIP int, allowlist []string, err error)

func (*Store) RegisterKeys added in v0.15.0

func (s *Store) RegisterKeys(specs ...KeySpec) error

RegisterKeys adds product keys to this store's registry. Call it at boot, before the admin settings routes serve traffic (reads take the registry lock, but registration between concurrent requests is not a supported lifecycle). An error names the offending spec: bad key shape, built-in or billing_channel collision, bad Env shape, or duplicate registration.

func (*Store) RegistrationGate

func (s *Store) RegistrationGate(ctx context.Context) (allow bool, domains []string, err error)

func (*Store) SMTPConfig added in v0.8.0

func (s *Store) SMTPConfig(ctx context.Context) (host string, port int, user, pass, from string, err error)

SMTPConfig hot-reads the outbound mail settings (same shape as Maintenance): DB row > env fallback > Defaults, with the stored smtp_pass decrypted. An empty host keeps the dev-channel semantics (log-only mailer); port defaults to 587. Meant for product hot-mailers polling on a short TTL.

func (*Store) Set

func (s *Store) Set(ctx context.Context, key, value, actor string) error

func (*Store) SetMany added in v0.13.0

func (s *Store) SetMany(ctx context.Context, kv map[string]string, actor string) error

SetMany writes multiple keys in ONE transaction (billing fix #11, 2026-10-24): the admin channel-fields save submits a whole card and used to loop Set() per key — a mid-loop failure left a half-saved channel for the hot-reload registry to pick up. Sealing of sensitive keys happens up front so a rejected seal never opens (or partially commits) the transaction. An empty map is a no-op.

func (*Store) SiteVerificationMeta added in v0.8.0

func (s *Store) SiteVerificationMeta(ctx context.Context) (string, error)

SiteVerificationMeta hot-reads the verification meta in its normalized `name|content` stored form (DB row > env SITE_VERIFICATION_META > ""). Parse the pair with ParseVerificationMeta and recompose the tag server-side — stored user input is never reflected verbatim.

func (*Store) Validate added in v0.15.0

func (s *Store) Validate(key, value string) error

Validate extends the built-in whitelist with registered keys: a registered key runs its spec.Validate (nil = 8192-char cap). Package-level Validate stays closed-whitelist for callers without a Store.

func (*Store) WithSealer added in v0.8.0

func (s *Store) WithSealer(secrets *sealx.Secrets) *Store

WithSealer attaches the credential sealer used to encrypt sensitive keys (v1: smtp_pass) at rest. Call it once after Bootstrap/NewStore and before the first admin write; returns the store for chaining. Build the argument with sealx.NewSecretsFromEnv() (nil when PLOYKIT_SEAL_KEY is unset — sensitive writes then stay rejected and reads of stored rows error, which is the intended posture).

Sealing lives on the Store rather than on the HTTP adapter on purpose: it is a storage property, and every writer (admin UI today, product code tomorrow) gets the same guarantee.

Directories

Path Synopsis
adapters

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL