@nymbalhq/config 1.4.0 → 1.6.0

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/define-config.ts","../src/env.ts","../src/known-providers.ts","../src/known-infrastructure.ts","../src/load.ts","../src/schema.ts"],"sourcesContent":["import type { NymbalConfigInput } from './schema.js'\n\nexport function defineConfig<T extends NymbalConfigInput>(config: T): T {\n return config\n}\n","import { ConfigError } from '@nymbalhq/types'\n\nexport function env(key: string, defaultValue?: string): string {\n const value = process.env[key]\n if (value !== undefined && value !== '') return value\n if (defaultValue !== undefined) return defaultValue\n throw new ConfigError(`Missing required environment variable: ${key}`, {\n context: { key },\n })\n}\n\nexport function envOptional(key: string): string | undefined {\n const value = process.env[key]\n return value !== undefined && value !== '' ? value : undefined\n}\n\nexport function envNumber(key: string, defaultValue?: number): number {\n const raw = envOptional(key)\n if (raw === undefined) {\n if (defaultValue !== undefined) return defaultValue\n throw new ConfigError(`Missing required environment variable: ${key}`, { context: { key } })\n }\n const parsed = Number(raw)\n if (!Number.isFinite(parsed)) {\n throw new ConfigError(`Environment variable ${key} is not a valid number: ${raw}`, {\n context: { key, raw },\n })\n }\n return parsed\n}\n\nexport function envBool(key: string, defaultValue = false): boolean {\n const raw = envOptional(key)?.toLowerCase()\n if (raw === undefined) return defaultValue\n return raw === 'true' || raw === '1' || raw === 'yes' || raw === 'on'\n}\n","import type { CommerceSlot } from '@nymbalhq/types'\n\nexport type { CommerceSlot }\n\n/**\n * The providers each commerce slot accepts. A provider that needs an SDK lives in an `@nymbalhq/adapter-*` package the\n * kernel loads only when the config names it; `custom` takes the adapter a project passes to `createApp`.\n */\nexport const KNOWN_PROVIDERS = {\n payments: ['native', 'stripe', 'custom'],\n email: ['native', 'smtp', 'custom'],\n reviews: ['native', 'custom'],\n search: ['native', 'custom'],\n analytics: ['native', 'custom'],\n shipping: ['native', 'custom'],\n tax: ['native', 'custom'],\n ai: ['none', 'anthropic', 'custom'],\n} as const satisfies Readonly<Record<CommerceSlot, readonly [string, ...string[]]>>\n","/**\n * The values each infrastructure slot accepts: only what is built. `in-memory`, `in-process` and `local-fs` are the\n * kernel's own; `redis`, `postgres-jsonb`, `redis-streams` and `s3` live in `@nymbalhq/*` packages the kernel loads\n * only when the config names them.\n */\nexport const KNOWN_INFRASTRUCTURE = {\n commandStore: ['sqlite', 'postgres'],\n documentStore: ['in-memory', 'redis', 'postgres-jsonb'],\n eventBus: ['in-process', 'redis-streams'],\n media: ['local-fs', 's3'],\n} as const satisfies Readonly<Record<string, readonly [string, ...string[]]>>\n\nexport type InfrastructureSlot = keyof typeof KNOWN_INFRASTRUCTURE\n\n/** Keys that drove nothing and were removed; a config that still sets one is told to delete it. */\nexport const REMOVED_INFRASTRUCTURE_KEYS = ['cloud', 'compute'] as const\n","import { existsSync } from 'node:fs'\nimport { dirname, isAbsolute, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { createJiti } from 'jiti'\nimport { z } from 'zod'\nimport { ConfigError, type CommerceSlotAdapters } from '@nymbalhq/types'\nimport { KNOWN_PROVIDERS } from './known-providers.js'\nimport { nymbalConfigSchema, type NymbalConfig } from './schema.js'\n\nconst CONFIG_FILE = 'nymbal.config.ts'\n\nexport interface LoadedConfig {\n config: NymbalConfig\n path: string\n projectRoot: string\n /** The module's named `adapters` export: one adapter per slot whose provider is `custom`, for createApp. */\n adapters?: Partial<CommerceSlotAdapters>\n}\n\nexport function findConfigFile(startDir: string): string | null {\n let current = isAbsolute(startDir) ? startDir : resolve(startDir)\n while (true) {\n const candidate = resolve(current, CONFIG_FILE)\n if (existsSync(candidate)) return candidate\n const parent = dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\nexport async function loadConfig(startDir: string = process.cwd()): Promise<LoadedConfig> {\n const path = findConfigFile(startDir)\n if (!path) {\n throw new ConfigError(\n `Could not find ${CONFIG_FILE} in ${startDir} or any parent directory.`,\n { context: { startDir } },\n )\n }\n\n const jiti = createJiti(pathToFileURL(path).href, { interopDefault: true })\n let mod: Record<string, unknown>\n try {\n mod = await jiti.import<Record<string, unknown>>(path)\n } catch (err) {\n throw new ConfigError(`Failed to load ${path}: ${(err as Error).message}`, {\n cause: err,\n context: { path },\n })\n }\n\n const raw = mod['default'] ?? mod\n const adapters = adaptersExport(mod['adapters'], path)\n try {\n const config = nymbalConfigSchema.parse(raw)\n return { config, path, projectRoot: dirname(path), ...(adapters !== undefined && { adapters }) }\n } catch (err) {\n if (err instanceof z.ZodError) {\n throw new ConfigError(formatZodError(err, path), {\n cause: err,\n context: { path, issues: err.issues },\n })\n }\n throw err\n }\n}\n\n/** The `adapters` export, keyed by commerce slot; anything else is a mistake worth naming before createApp runs. */\nfunction adaptersExport(value: unknown, path: string): Partial<CommerceSlotAdapters> | undefined {\n if (value === undefined) return undefined\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ConfigError(`${path}: the adapters export must be an object keyed by commerce slot`, {\n code: 'config.adapters_invalid',\n context: { path },\n })\n }\n const slots = Object.keys(KNOWN_PROVIDERS)\n const unknown = Object.keys(value).filter((key) => !slots.includes(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${path}: the adapters export names ${unknown.join(', ')}, which is no commerce slot (${slots.join(', ')})`,\n { code: 'config.adapters_invalid', context: { path, unknown } },\n )\n }\n return value as Partial<CommerceSlotAdapters>\n}\n\nfunction formatZodError(err: z.ZodError, path: string): string {\n const lines = err.issues.map((issue) => {\n const at = issue.path.length > 0 ? issue.path.join('.') : '<root>'\n return ` • ${at}: ${issue.message}`\n })\n return `Invalid configuration in ${path}:\\n${lines.join('\\n')}`\n}\n","import { z } from 'zod'\nimport {\n KNOWN_INFRASTRUCTURE,\n REMOVED_INFRASTRUCTURE_KEYS,\n type InfrastructureSlot,\n} from './known-infrastructure.js'\nimport { KNOWN_PROVIDERS, type CommerceSlot } from './known-providers.js'\n\nconst rateLimitRuleSchema = z.object({\n requests: z.number().int().positive(),\n window: z.string().regex(/^\\d+(ms|s|m|h)$/, 'window must look like \"60s\", \"5m\", \"1h\"'),\n action: z.enum(['block', 'challenge', 'throttle']),\n})\n\nconst rateLimitPathPattern = /^\\/[\\w\\-/*:]*$/\n\n/** The schema's JWT secret when none is configured: fine for development, refused in production. */\nexport const DEFAULT_JWT_SECRET = 'dev-secret-please-override-me-1234567890'\n\nexport const storeSchema = z.object({\n name: z.string().min(1),\n currency: z.string().length(3),\n locale: z.string().min(2),\n timezone: z.string().min(1),\n /** The storefront's public URL, which the order email links from; with none, the email has no link. */\n url: z\n .string()\n .url()\n .transform((url) => url.replace(/\\/+$/, ''))\n .optional(),\n})\n\nconst quotedList = (values: readonly string[]): string => values.map((v) => `'${v}'`).join(', ')\n\n/** A slot's value must be one the slot lists; an unknown one is named with the list. */\nfunction infrastructureValue<const V extends readonly [string, ...string[]]>(\n slot: InfrastructureSlot,\n values: V,\n) {\n return z.enum(values, {\n errorMap: (issue, ctx) =>\n issue.code === z.ZodIssueCode.invalid_enum_value\n ? {\n message: `unknown ${slot} '${String(issue.received)}'; the ${slot} values are ${quotedList(values)}`,\n }\n : { message: ctx.defaultError },\n })\n}\n\nconst INFRASTRUCTURE_KEYS = [...Object.keys(KNOWN_INFRASTRUCTURE), 'redis', 's3']\n\nfunction unrecognizedInfrastructureKeys(keys: string[]): string {\n return keys\n .map((key) =>\n (REMOVED_INFRASTRUCTURE_KEYS as readonly string[]).includes(key)\n ? `infrastructure.${key} was removed: it drives nothing, so delete it from the config`\n : `unknown infrastructure key '${key}'; the infrastructure keys are ${quotedList(INFRASTRUCTURE_KEYS)}`,\n )\n .join('; ')\n}\n\n/** The shared Redis connection of the `redis` document store and the `redis-streams` bus. */\nexport const redisSchema = z\n .object({\n /** Defaults to `REDIS_URL`. */\n url: z.string().min(1).optional(),\n /** Namespaces every key and stream; defaults to `NYMBAL_REDIS_PREFIX`, then `'nymbal'`. */\n prefix: z.string().min(1).optional(),\n /** How long a publish waits for the groups it delivers to (default 15 000). */\n ackTimeoutMs: z.number().int().positive().optional(),\n /** How long an entry may stay pending on a consumer before a live one takes it over (default 5 000). */\n claimIdleMs: z.number().int().positive().optional(),\n /** The approximate length each stream is trimmed to (default 10 000). */\n streamMaxLen: z.number().int().positive().optional(),\n })\n .strict()\n\nconst S3_KEYS = ['bucket', 'region', 'endpoint', 'prefix', 'publicUrl', 'forcePathStyle']\n\n/**\n * The bucket `media: 's3'` stores in. Each field falls back to the environment in the platform; credentials are never\n * config keys: the AWS SDK's default chain provides them.\n */\nexport const s3Schema = z\n .object(\n {\n /** Defaults to `S3_BUCKET`; one of the two is required. */\n bucket: z.string().min(1).optional(),\n /** Defaults to `AWS_REGION`, then `'us-east-1'`. */\n region: z.string().min(1).optional(),\n /** An S3-compatible API (MinIO, R2); defaults to `S3_ENDPOINT`, then AWS. */\n endpoint: z.string().min(1).optional(),\n /** Where every object key starts; defaults to `NYMBAL_S3_PREFIX`, then none. */\n prefix: z.string().optional(),\n /** Where the bucket's objects are served from (a CDN); defaults to `S3_PUBLIC_URL`, then the bucket's own URL. */\n publicUrl: z.string().min(1).optional(),\n /** Path-style requests; true by default when an endpoint is set. */\n forcePathStyle: z.boolean().optional(),\n },\n {\n errorMap: (issue, ctx) =>\n issue.code === z.ZodIssueCode.unrecognized_keys\n ? {\n message: `unknown infrastructure.s3 key${issue.keys.length > 1 ? 's' : ''} ${quotedList(issue.keys)}; the s3 keys are ${quotedList(S3_KEYS)}, and credentials come from the AWS SDK (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, a profile or a role), never the config`,\n }\n : { message: ctx.defaultError },\n },\n )\n .strict()\n\nexport const infrastructureSchema = z\n .object(\n {\n commandStore: infrastructureValue('commandStore', KNOWN_INFRASTRUCTURE.commandStore),\n documentStore: infrastructureValue('documentStore', KNOWN_INFRASTRUCTURE.documentStore),\n eventBus: infrastructureValue('eventBus', KNOWN_INFRASTRUCTURE.eventBus),\n media: infrastructureValue('media', KNOWN_INFRASTRUCTURE.media).default('local-fs'),\n redis: redisSchema.optional(),\n s3: s3Schema.optional(),\n },\n {\n errorMap: (issue, ctx) =>\n issue.code === z.ZodIssueCode.unrecognized_keys\n ? { message: unrecognizedInfrastructureKeys(issue.keys) }\n : { message: ctx.defaultError },\n },\n )\n .strict()\n .superRefine((infra, ctx) => {\n if (infra.documentStore === 'postgres-jsonb' && infra.commandStore !== 'postgres') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['documentStore'],\n message: `documentStore 'postgres-jsonb' shares the command store's Postgres connection, so it needs commandStore 'postgres' (not '${infra.commandStore}')`,\n })\n }\n if (infra.eventBus === 'redis-streams' && infra.documentStore === 'in-memory') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['eventBus'],\n message: `eventBus 'redis-streams' needs a shared documentStore ('redis' or 'postgres-jsonb'), not 'in-memory': a named group hands each event to one instance, so a per-process read model would miss the rest`,\n })\n }\n if (infra.s3 !== undefined && infra.media !== 's3') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['s3'],\n message: `infrastructure.s3 configures media 's3', but media is '${infra.media}': set media to 's3' or delete the s3 block`,\n })\n }\n })\n\n/** Where a `cloudflare` store's rules go: required when `security.adapter` is `cloudflare`, read with `env()`. */\nconst cloudflareSchema = z.object({\n zoneId: z.string().optional(),\n apiToken: z.string().optional(),\n /** The Cloudflare v4 API; the adapter defaults it to https://api.cloudflare.com/client/v4. */\n apiBase: z.string().url().optional(),\n})\n\nconst customRuleSchema = z.object({\n name: z.string().min(1),\n expression: z.string().min(1),\n action: z.enum(['block', 'managed_challenge', 'js_challenge', 'log']),\n})\n\nconst securityFields = z.object({\n adapter: z.enum(['middleware', 'cloudflare', 'aws-waf', 'akamai']),\n rateLimit: z\n .record(\n z.string().regex(rateLimitPathPattern, {\n message: 'rate limit keys must start with \"/\" and use only letters, numbers, -, _, /, *, :',\n }),\n rateLimitRuleSchema,\n )\n .default({}),\n botProtection: z\n .object({\n mode: z.enum(['off', 'managed', 'strict']).default('off'),\n allowList: z.array(z.string()).default([]),\n })\n .default({ mode: 'off', allowList: [] }),\n headers: z\n .object({\n hsts: z.boolean().default(true),\n contentSecurityPolicy: z\n .union([z.enum(['strict', 'relaxed', 'off']), z.string()])\n .default('strict'),\n referrerPolicy: z.string().default('strict-origin-when-cross-origin'),\n xFrameOptions: z.enum(['deny', 'sameorigin']).default('deny'),\n })\n .default({}),\n csrf: z.boolean().default(true),\n auth: z\n .object({\n jwtSecret: z.string().min(16).default(DEFAULT_JWT_SECRET),\n accessTtl: z\n .string()\n .regex(/^\\d+(ms|s|m|h|d)$/, 'TTL must look like \"15m\"')\n .default('15m'),\n refreshTtl: z\n .string()\n .regex(/^\\d+(ms|s|m|h|d)$/, 'TTL must look like \"7d\"')\n .default('7d'),\n })\n .default({}),\n cloudflare: cloudflareSchema.optional(),\n geo: z\n .object({\n block: z\n .array(z.string().regex(/^[A-Z]{2}$/, 'geo.block codes are ISO 3166 alpha-2, like \"RU\"'))\n .default([]),\n })\n .default({ block: [] }),\n customRules: z.array(customRuleSchema).default([]),\n managedRulesets: z.array(z.enum(['cloudflare', 'owasp'])).default([]),\n})\n\nexport const securitySchema = securityFields.superRefine((security, ctx) => {\n if (security.adapter === 'cloudflare') {\n for (const field of ['zoneId', 'apiToken'] as const) {\n if (!security.cloudflare?.[field]) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['cloudflare', field],\n message: `security.adapter 'cloudflare' needs security.cloudflare.${field}`,\n })\n }\n }\n }\n const seen = new Set<string>()\n security.customRules.forEach((rule, i) => {\n if (seen.has(rule.name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['customRules', i, 'name'],\n message: `customRules has two rules named '${rule.name}'; names must be unique`,\n })\n }\n seen.add(rule.name)\n })\n})\n\n/**\n * npm's rules for a new package name: lower case and URL-safe, optionally `@scope/`, never starting with `.` or `_`.\n * The 214-character limit is checked beside it.\n */\nconst NPM_PACKAGE_NAME = /^(?:@[a-z0-9~-][a-z0-9._~-]*\\/)?[a-z0-9~-][a-z0-9._~-]*$/\n\n/** A slot's block: its provider must be one the slot knows, and an unknown one is named with the slot's list. */\nfunction adapterBlock<const P extends readonly [string, ...string[]]>(\n slot: CommerceSlot,\n providers: P,\n) {\n const known = providers.map((p) => `'${p}'`).join(', ')\n return z.object({\n provider: z.enum(providers, {\n errorMap: (issue, ctx) =>\n issue.code === z.ZodIssueCode.invalid_enum_value\n ? {\n message: `unknown ${slot} provider '${String(issue.received)}'; the ${slot} providers are ${known}`,\n }\n : { message: ctx.defaultError },\n }),\n config: z.record(z.string(), z.unknown()).optional(),\n /** The npm package a `custom` slot's adapter comes from, for tooling (`nymbal test:contracts`); the kernel never reads it. */\n package: z\n .string()\n .max(214, 'an npm package name is at most 214 characters')\n .regex(NPM_PACKAGE_NAME, 'must be an npm package name, such as `@acme/nymbal-search`')\n .optional(),\n })\n}\n\nexport const commerceSchema = z.object({\n payments: adapterBlock('payments', KNOWN_PROVIDERS.payments),\n email: adapterBlock('email', KNOWN_PROVIDERS.email),\n reviews: adapterBlock('reviews', KNOWN_PROVIDERS.reviews),\n search: adapterBlock('search', KNOWN_PROVIDERS.search),\n analytics: adapterBlock('analytics', KNOWN_PROVIDERS.analytics),\n shipping: adapterBlock('shipping', KNOWN_PROVIDERS.shipping),\n tax: adapterBlock('tax', KNOWN_PROVIDERS.tax),\n ai: adapterBlock('ai', KNOWN_PROVIDERS.ai),\n orders: z\n .object({\n numberPrefix: z.string().min(1).default('NYM'),\n numberStart: z.number().int().nonnegative().default(1000),\n })\n .default({}),\n})\n\nexport const httpSchema = z.object({\n adapter: z.enum(['fastify', 'hono']).default('fastify'),\n port: z.number().int().positive().default(3001),\n host: z.string().default('0.0.0.0'),\n /** Whether `X-Forwarded-For` sets the client IP the rate limiter keys on; only behind a proxy you run. */\n trustProxy: z.boolean().default(false),\n cors: z\n .object({\n allowedOrigins: z\n .array(z.string())\n .default(['http://localhost:3000', 'http://localhost:4321']),\n credentials: z.boolean().default(true),\n })\n .default({}),\n})\n\nexport const deploymentSchema = z.object({\n strategy: z.enum(['standard', 'blue-green']).default('standard'),\n})\n\nexport const featuresSchema = z.object({\n staging: z.boolean().default(false),\n heartbeat: z.boolean().default(false),\n autoUpdates: z.boolean().default(false),\n})\n\n/**\n * The bucket delivered events past retention are archived to before they are deleted. Its objects hold customer\n * data, so it must be private: never the media bucket, which serves its objects publicly. Credentials come from the\n * AWS SDK's default chain, as `infrastructure.s3`'s do.\n */\nexport const eventArchiveSchema = z\n .object({\n adapter: z.literal('s3'),\n bucket: z.string().min(1),\n /** Where every archive key starts; none when not given. */\n prefix: z.string().optional(),\n /** `'us-east-1'` when not given. */\n region: z.string().min(1).optional(),\n /** An S3-compatible API (MinIO, R2). */\n endpoint: z.string().min(1).optional(),\n /** Path-style requests; true by default when an endpoint is set. */\n forcePathStyle: z.boolean().optional(),\n })\n .strict()\n\nexport const eventsSchema = z\n .object({\n /** Days a delivered event stays in the log. */\n retentionDays: z.number().int().min(1).default(30),\n archive: eventArchiveSchema.optional(),\n })\n .strict()\n\nexport const nymbalConfigSchema = z\n .object({\n store: storeSchema,\n template: z.enum(['astro', 'nextjs']),\n infrastructure: infrastructureSchema,\n security: securitySchema,\n commerce: commerceSchema,\n http: httpSchema,\n deployment: deploymentSchema,\n features: featuresSchema.default({\n staging: false,\n heartbeat: false,\n autoUpdates: false,\n }),\n events: eventsSchema.default({}),\n })\n .superRefine((cfg, ctx) => {\n const archiveBucket = cfg.events.archive?.bucket\n if (\n archiveBucket !== undefined &&\n cfg.infrastructure.media === 's3' &&\n archiveBucket === cfg.infrastructure.s3?.bucket\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['events', 'archive', 'bucket'],\n message: `events.archive.bucket is infrastructure.s3.bucket ('${archiveBucket}'), the media bucket, which serves its objects publicly; archive events to a private bucket of their own`,\n })\n }\n // SMTP left the kernel for @nymbalhq/adapter-smtp; a native block still asking for it would print to the console.\n const email = cfg.commerce.email\n if (email.provider === 'native' && email.config?.['transport'] === 'smtp') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['commerce', 'email', 'config', 'transport'],\n message: `the native email provider only prints to the console; for SMTP mail set email.provider to 'smtp' (@nymbalhq/adapter-smtp)`,\n })\n }\n })\n\nexport type NymbalConfigInput = z.input<typeof nymbalConfigSchema>\nexport type NymbalConfig = z.output<typeof nymbalConfigSchema>\n"],"mappings":";AAEO,SAAS,aAA0C,QAAc;AACtE,SAAO;AACT;;;ACJA,SAAS,mBAAmB;AAErB,SAAS,IAAI,KAAa,cAA+B;AAC9D,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,MAAI,UAAU,UAAa,UAAU,GAAI,QAAO;AAChD,MAAI,iBAAiB,OAAW,QAAO;AACvC,QAAM,IAAI,YAAY,0CAA0C,GAAG,IAAI;AAAA,IACrE,SAAS,EAAE,IAAI;AAAA,EACjB,CAAC;AACH;AAEO,SAAS,YAAY,KAAiC;AAC3D,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,SAAO,UAAU,UAAa,UAAU,KAAK,QAAQ;AACvD;AAEO,SAAS,UAAU,KAAa,cAA+B;AACpE,QAAM,MAAM,YAAY,GAAG;AAC3B,MAAI,QAAQ,QAAW;AACrB,QAAI,iBAAiB,OAAW,QAAO;AACvC,UAAM,IAAI,YAAY,0CAA0C,GAAG,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAAA,EAC7F;AACA,QAAM,SAAS,OAAO,GAAG;AACzB,MAAI,CAAC,OAAO,SAAS,MAAM,GAAG;AAC5B,UAAM,IAAI,YAAY,wBAAwB,GAAG,2BAA2B,GAAG,IAAI;AAAA,MACjF,SAAS,EAAE,KAAK,IAAI;AAAA,IACtB,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEO,SAAS,QAAQ,KAAa,eAAe,OAAgB;AAClE,QAAM,MAAM,YAAY,GAAG,GAAG,YAAY;AAC1C,M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CAAgC,MAAM,KAAK,IAAI,CAAC;AAAA,MACxG,EAAE,MAAM,2BAA2B,SAAS,EAAE,MAAM,QAAQ,EAAE;AAAA,IAChE;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,eAAe,KAAiB,MAAsB;AAC7D,QAAM,QAAQ,IAAI,OAAO,IAAI,CAAC,UAAU;AACtC,UAAM,KAAK,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,KAAK,GAAG,IAAI;AAC1D,WAAO,YAAO,EAAE,KAAK,MAAM,OAAO;AAAA,EACpC,CAAC;AACD,SAAO,4BAA4B,IAAI;AAAA,EAAM,MAAM,KAAK,IAAI,CAAC;AAC/D;","names":["z","ConfigError","ConfigError","z"]}
1
+ {"version":3,"sources":["../src/define-config.ts","../src/env.ts","../src/adapter-names.ts","../src/known-providers.ts","../src/known-infrastructure.ts","../src/load.ts","../src/schema.ts","../src/trusted-proxies.ts","../src/secure-cookies.ts","../src/origin-lock.ts"],"sourcesContent":["import type { NymbalConfigInput } from './schema.js'\n\nexport function defineConfig<T extends NymbalConfigInput>(config: T): T {\n return config\n}\n","import { ConfigError } from '@nymbalhq/types'\n\nexport function env(key: string, defaultValue?: string): string {\n const value = process.env[key]\n if (value !== undefined && value !== '') return value\n if (defaultValue !== undefined) return defaultValue\n throw new ConfigError(`Missing required environment variable: ${key}`, {\n context: { key },\n })\n}\n\nexport function envOptional(key: string): string | undefined {\n const value = process.env[key]\n return value !== undefined && value !== '' ? value : undefined\n}\n\nexport function envNumber(key: string, defaultValue?: number): number {\n const raw = envOptional(key)\n if (raw === undefined) {\n if (defaultValue !== undefined) return defaultValue\n throw new ConfigError(`Missing required environment variable: ${key}`, { context: { key } })\n }\n const parsed = Number(raw)\n if (!Number.isFinite(parsed)) {\n throw new ConfigError(`Environment variable ${key} is not a valid number: ${raw}`, {\n context: { key, raw },\n })\n }\n return parsed\n}\n\nexport function envBool(key: string, defaultValue = false): boolean {\n const raw = envOptional(key)?.toLowerCase()\n if (raw === undefined) return defaultValue\n return raw === 'true' || raw === '1' || raw === 'yes' || raw === 'on'\n}\n","import type { CommerceSlot, Slot } from '@nymbalhq/types'\n\n/**\n * What a slot's provider may be called: lower-case letters, digits and hyphens, starting with a letter or digit. The\n * bound keeps every convention name within npm's 214 characters.\n */\nexport const PROVIDER_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/\n\n/** A slot as its package names and folders spell it: `documentStore` is `document-store`. */\nexport function slotFolder(slot: Slot): string {\n return slot.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)\n}\n\n/** The package a provider lives in when the config names no `package`: `@nymbalhq/<slot folder>-<provider>`. */\nexport function conventionPackage(slot: Slot, provider: string): string {\n return `@nymbalhq/${slotFolder(slot)}-${provider}`\n}\n\nexport interface CatalogueEntry {\n /** The kernel's own provider, which no package holds. */\n builtIn?: true\n /** The SDK the provider's package peers, which the project installs beside it. */\n sdk?: string\n}\n\nconst builtIn = { builtIn: true } as const\n\n/**\n * The providers Nymbal ships, by slot: the kernel's built-ins and the first-party packages, each with the SDK it peers.\n * It never decides what loads; it gives install lines, suggestions for a mistyped provider and `nymbal add`'s list.\n */\nexport const ADAPTER_CATALOGUE: Readonly<Record<Slot, Readonly<Record<string, CatalogueEntry>>>> = {\n payments: { native: builtIn, stripe: { sdk: 'stripe' } },\n email: {\n native: builtIn,\n smtp: { sdk: 'nodemailer' },\n mailgun: { sdk: 'nodemailer' },\n resend: { sdk: 'nodemailer' },\n ses: { sdk: 'nodemailer' },\n },\n reviews: { native: builtIn },\n search: { native: builtIn, algolia: {} },\n analytics: { native: builtIn },\n shipping: { native: builtIn, aftership: {}, easypost: {} },\n tax: { native: builtIn },\n ai: { none: builtIn, anthropic: { sdk: '@anthropic-ai/sdk' }, openai: {} },\n documentStore: {\n 'in-memory': builtIn,\n redis: { sdk: 'ioredis' },\n 'postgres-jsonb': { sdk: 'pg' },\n },\n eventBus: { 'in-process': builtIn, 'redis-streams': { sdk: 'ioredis' } },\n media: { 'local-fs': builtIn, s3: { sdk: '@aws-sdk/client-s3' } },\n security: { middleware: builtIn, cloudflare: {} },\n}\n\nconst SLOTS = Object.keys(ADAPTER_CATALOGUE) as Slot[]\n\n/** Each slot's built-in providers: the kernel's own adapter is used, and nothing is imported. */\nexport const BUILT_IN: Readonly<Record<Slot, readonly string[]>> = Object.fromEntries(\n SLOTS.map((slot) => [\n slot,\n Object.entries(ADAPTER_CATALOGUE[slot])\n .filter(([, entry]) => entry.builtIn === true)\n .map(([name]) => name),\n ]),\n) as unknown as Record<Slot, readonly string[]>\n\nexport const COMMERCE_SLOTS = [\n 'payments',\n 'email',\n 'reviews',\n 'search',\n 'analytics',\n 'shipping',\n 'tax',\n 'ai',\n] as const satisfies readonly CommerceSlot[]\n\nexport function isCommerceSlot(slot: Slot): slot is CommerceSlot {\n return (COMMERCE_SLOTS as readonly string[]).includes(slot)\n}\n\n/** Optimal string alignment distance: insertions, deletions, substitutions and adjacent transpositions. */\nfunction editDistance(a: string, b: string): number {\n const d: number[][] = Array.from({ length: a.length + 1 }, (_, i) =>\n Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n )\n for (let i = 1; i <= a.length; i++) {\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n let best = Math.min(d[i - 1]![j]! + 1, d[i]![j - 1]! + 1, d[i - 1]![j - 1]! + cost)\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n best = Math.min(best, d[i - 2]![j - 2]! + 1)\n }\n d[i]![j] = best\n }\n }\n return d[a.length]![b.length]!\n}\n\nconst MAX_SUGGESTION_DISTANCE = 2\n\n/**\n * The catalogue name `name` was most likely meant to be, among the slot's catalogue names and, on a commerce slot,\n * `custom`: the nearest within two edits, the alphabetically first on a tie; none when nothing is that near.\n */\nexport function suggestProvider(slot: Slot, name: string): string | undefined {\n const candidates = [\n ...Object.keys(ADAPTER_CATALOGUE[slot]),\n ...(isCommerceSlot(slot) ? ['custom'] : []),\n ].sort()\n let best: { name: string; distance: number } | undefined\n for (const candidate of candidates) {\n const distance = editDistance(candidate, name)\n if (distance > MAX_SUGGESTION_DISTANCE) continue\n if (best === undefined || distance < best.distance) best = { name: candidate, distance }\n }\n return best?.name\n}\n","import type { CommerceSlot } from '@nymbalhq/types'\nimport { ADAPTER_CATALOGUE, COMMERCE_SLOTS } from './adapter-names.js'\n\nexport type { CommerceSlot }\n\n/**\n * The providers Nymbal ships for each commerce slot, from the catalogue, and `custom`, the adapter a project passes\n * to `createApp`. A slot accepts any provider name; this list gates nothing.\n */\nexport const KNOWN_PROVIDERS: Readonly<Record<CommerceSlot, readonly string[]>> =\n Object.fromEntries(\n COMMERCE_SLOTS.map((slot) => [slot, [...Object.keys(ADAPTER_CATALOGUE[slot]), 'custom']]),\n ) as unknown as Record<CommerceSlot, readonly string[]>\n","/** The command store's dialects: a kernel dialect, not an adapter slot, so it stays a closed list. */\nexport const COMMAND_STORES = ['sqlite', 'postgres'] as const\n\n/** The infrastructure slots: the command store, and the three that take an adapter block. */\nexport type InfrastructureSlot = 'commandStore' | 'documentStore' | 'eventBus' | 'media'\n\n/** Keys that drove nothing and were removed; a config that still sets one is told to delete it. */\nexport const REMOVED_INFRASTRUCTURE_KEYS = ['cloud', 'compute'] as const\n","import { existsSync } from 'node:fs'\nimport { dirname, isAbsolute, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { createJiti } from 'jiti'\nimport { z } from 'zod'\nimport { ConfigError, type CommerceSlotAdapters } from '@nymbalhq/types'\nimport { KNOWN_PROVIDERS } from './known-providers.js'\nimport { nymbalConfigSchema, type NymbalConfig } from './schema.js'\n\nconst CONFIG_FILE = 'nymbal.config.ts'\n\nexport interface LoadedConfig {\n config: NymbalConfig\n path: string\n projectRoot: string\n /** The module's named `adapters` export: one adapter per slot whose provider is `custom`, for createApp. */\n adapters?: Partial<CommerceSlotAdapters>\n}\n\nexport function findConfigFile(startDir: string): string | null {\n let current = isAbsolute(startDir) ? startDir : resolve(startDir)\n while (true) {\n const candidate = resolve(current, CONFIG_FILE)\n if (existsSync(candidate)) return candidate\n const parent = dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\nexport async function loadConfig(startDir: string = process.cwd()): Promise<LoadedConfig> {\n const path = findConfigFile(startDir)\n if (!path) {\n throw new ConfigError(\n `Could not find ${CONFIG_FILE} in ${startDir} or any parent directory.`,\n { context: { startDir } },\n )\n }\n\n const jiti = createJiti(pathToFileURL(path).href, { interopDefault: true })\n let mod: Record<string, unknown>\n try {\n mod = await jiti.import<Record<string, unknown>>(path)\n } catch (err) {\n throw new ConfigError(`Failed to load ${path}: ${(err as Error).message}`, {\n cause: err,\n context: { path },\n })\n }\n\n const raw = mod['default'] ?? mod\n const adapters = adaptersExport(mod['adapters'], path)\n try {\n const config = nymbalConfigSchema.parse(raw)\n return { config, path, projectRoot: dirname(path), ...(adapters !== undefined && { adapters }) }\n } catch (err) {\n if (err instanceof z.ZodError) {\n throw new ConfigError(formatZodError(err, path), {\n cause: err,\n context: { path, issues: err.issues },\n })\n }\n throw err\n }\n}\n\n/** The `adapters` export, keyed by commerce slot; anything else is a mistake worth naming before createApp runs. */\nfunction adaptersExport(value: unknown, path: string): Partial<CommerceSlotAdapters> | undefined {\n if (value === undefined) return undefined\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new ConfigError(`${path}: the adapters export must be an object keyed by commerce slot`, {\n code: 'config.adapters_invalid',\n context: { path },\n })\n }\n const slots = Object.keys(KNOWN_PROVIDERS)\n const unknown = Object.keys(value).filter((key) => !slots.includes(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${path}: the adapters export names ${unknown.join(', ')}, which is no commerce slot (${slots.join(', ')})`,\n { code: 'config.adapters_invalid', context: { path, unknown } },\n )\n }\n return value as Partial<CommerceSlotAdapters>\n}\n\nfunction formatZodError(err: z.ZodError, path: string): string {\n const lines = err.issues.map((issue) => {\n const at = issue.path.length > 0 ? issue.path.join('.') : '<root>'\n return ` • ${at}: ${issue.message}`\n })\n return `Invalid configuration in ${path}:\\n${lines.join('\\n')}`\n}\n","import { z } from 'zod'\nimport type { Slot } from '@nymbalhq/types'\nimport { BUILT_IN, PROVIDER_NAME, slotFolder } from './adapter-names.js'\nimport {\n COMMAND_STORES,\n REMOVED_INFRASTRUCTURE_KEYS,\n type InfrastructureSlot,\n} from './known-infrastructure.js'\nimport { type CommerceSlot } from './known-providers.js'\nimport {\n clientIpHeaderProblem,\n trustedProxyMessage,\n trustedProxyProblem,\n} from './trusted-proxies.js'\n\nconst rateLimitRuleSchema = z.object({\n requests: z.number().int().positive(),\n window: z.string().regex(/^\\d+(ms|s|m|h)$/, 'window must look like \"60s\", \"5m\", \"1h\"'),\n action: z.enum(['block', 'challenge', 'throttle']),\n /** Counts only the requests to the path that carry this header, such as `x-nymbal-order-email`. */\n header: z.string().min(1).optional(),\n})\n\nconst rateLimitPathPattern = /^\\/[\\w\\-/*:]*$/\n\n/** The schema's JWT secret when none is configured: fine for development, refused in production. */\nexport const DEFAULT_JWT_SECRET = 'dev-secret-please-override-me-1234567890'\n\n/** An address the store ships from; `region` may be empty, for countries without one. */\nconst shipFromSchema = z.object({\n firstName: z.string().min(1),\n lastName: z.string().min(1),\n company: z.string().optional(),\n addressLine1: z.string().min(1),\n addressLine2: z.string().optional(),\n city: z.string().min(1),\n region: z.string(),\n postalCode: z.string().min(1),\n country: z.string().regex(/^[A-Z]{2}$/, 'country must be two upper-case letters, such as \"GB\"'),\n phone: z.string().optional(),\n})\n\nexport const storeSchema = z.object({\n name: z.string().min(1),\n currency: z.string().length(3),\n locale: z.string().min(2),\n timezone: z.string().min(1),\n /** The storefront's public URL, which the order email links from; with none, the email has no link. */\n url: z\n .string()\n .url()\n .transform((url) => url.replace(/\\/+$/, ''))\n .optional(),\n /** Where parcels are sent from, for shipping rates. */\n shipFrom: shipFromSchema.optional(),\n})\n\nconst quotedList = (values: readonly string[]): string => values.map((v) => `'${v}'`).join(', ')\n\n/** A slot's value must be one the slot lists; an unknown one is named with the list. */\nfunction infrastructureValue<const V extends readonly [string, ...string[]]>(\n slot: InfrastructureSlot,\n values: V,\n) {\n return z.enum(values, {\n error: (issue) =>\n issue.code === 'invalid_value'\n ? `unknown ${slot} '${String(issue.input)}'; the ${slot} values are ${quotedList(values)}`\n : undefined,\n })\n}\n\n/**\n * npm's rules for a new package name: lower case and URL-safe, optionally `@scope/`, never starting with `.` or `_`.\n * The 214-character limit is checked beside it.\n */\nconst NPM_PACKAGE_NAME = /^(?:@[a-z0-9~-][a-z0-9._~-]*\\/)?[a-z0-9~-][a-z0-9._~-]*$/\n\nconst packageNameSchema = z\n .string()\n .max(214, 'an npm package name is at most 214 characters')\n .regex(NPM_PACKAGE_NAME, 'must be an npm package name, such as `@acme/nymbal-search`')\n\n/** A provider name, refused with the value and the pattern when it is not one: it becomes part of a package name. */\nfunction providerNameSchema(where: string) {\n return z.string().superRefine((value, ctx) => {\n if (!PROVIDER_NAME.test(value)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `${where} '${value}' is not a provider name: a provider matches ${PROVIDER_NAME.source}`,\n })\n }\n })\n}\n\n/** How a slot's choice reads in a message: `payments.provider 'stripe'`, `infrastructure.media 's3'`. */\nfunction choiceOf(slot: Slot, provider: string): string {\n if (slot === 'security') return `security.adapter '${provider}'`\n if (slot === 'documentStore' || slot === 'eventBus' || slot === 'media') {\n return `infrastructure.${slot} '${provider}'`\n }\n return `${slot}.provider '${provider}'`\n}\n\n/** `package` names a third party's adapter, which a built-in provider never is. */\nfunction packageBesideBuiltIn(\n slot: Slot,\n block: { provider: string; package?: string | undefined },\n ctx: z.RefinementCtx,\n): void {\n if (block.package === undefined || !BUILT_IN[slot].includes(block.provider)) return\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['package'],\n message: `${choiceOf(slot, block.provider)} is built in, so it takes no package: delete package, or give the third-party adapter's own provider name beside it`,\n })\n}\n\n/** `custom` is the adapter passed to `createApp`, which only a commerce slot takes. */\nfunction customOutsideCommerce(slot: Slot, provider: string, ctx: z.RefinementCtx): void {\n if (provider !== 'custom') return\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [slot === 'security' ? 'adapter' : 'provider'],\n message: `${choiceOf(slot, provider)}: only a commerce slot takes an adapter passed to createApp; name a third-party adapter with package: { provider: 'acme', package: '@acme/nymbal-${slotFolder(slot)}' }`,\n })\n}\n\ntype BlockSlot = 'documentStore' | 'eventBus' | 'media'\n\n/**\n * The providers whose connection the kernel builds itself, and what configures each: their block takes no `config`.\n * Any other provider gets the block's `config` as its adapter's `ctx.config`.\n */\nconst KERNEL_CONFIGURED: Readonly<Record<BlockSlot, Readonly<Record<string, string>>>> = {\n documentStore: {\n 'in-memory': 'it is built in and takes none',\n redis: 'infrastructure.redis configures it',\n 'postgres-jsonb': \"it uses the command store's Postgres connection (DATABASE_URL)\",\n },\n eventBus: {\n 'in-process': 'it is built in and takes none',\n 'redis-streams': 'infrastructure.redis configures it',\n },\n media: {\n 'local-fs': 'it is built in and takes none',\n s3: 'infrastructure.s3 configures it',\n },\n}\n\n/** An infrastructure slot's block, `{ provider, package?, config? }`; a string is refused, saying how to write it. */\nfunction infrastructureBlock(slot: BlockSlot) {\n return z\n .object(\n {\n provider: providerNameSchema(`infrastructure.${slot}`),\n /** The npm package the adapter comes from, in place of `@nymbalhq/<slot>-<provider>`. */\n package: packageNameSchema.optional(),\n /** The adapter's `ctx.config`, for a provider whose connection the kernel does not build. */\n config: z.record(z.string(), z.unknown()).optional(),\n },\n {\n error: (issue) =>\n issue.code === 'invalid_type' && typeof issue.input === 'string'\n ? `infrastructure.${slot} takes a block: write { provider: '${issue.input}' }`\n : undefined,\n },\n )\n .superRefine((block, ctx) => {\n customOutsideCommerce(slot, block.provider, ctx)\n packageBesideBuiltIn(slot, block, ctx)\n const configuredBy = Object.hasOwn(KERNEL_CONFIGURED[slot], block.provider)\n ? KERNEL_CONFIGURED[slot][block.provider]\n : undefined\n if (block.config !== undefined && configuredBy !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['config'],\n message: `infrastructure.${slot} '${block.provider}' takes no config: ${configuredBy}`,\n })\n }\n })\n}\n\nconst INFRASTRUCTURE_KEYS = ['commandStore', 'documentStore', 'eventBus', 'media', 'redis', 's3']\n\nfunction unrecognizedInfrastructureKeys(keys: string[]): string {\n return keys\n .map((key) =>\n (REMOVED_INFRASTRUCTURE_KEYS as readonly string[]).includes(key)\n ? `infrastructure.${key} was removed: it drives nothing, so delete it from the config`\n : `unknown infrastructure key '${key}'; the infrastructure keys are ${quotedList(INFRASTRUCTURE_KEYS)}`,\n )\n .join('; ')\n}\n\n/** The shared Redis connection of the `redis` document store and the `redis-streams` bus. */\nexport const redisSchema = z\n .object({\n /** Defaults to `REDIS_URL`. */\n url: z.string().min(1).optional(),\n /** Namespaces every key and stream; defaults to `NYMBAL_REDIS_PREFIX`, then `'nymbal'`. */\n prefix: z.string().min(1).optional(),\n /** How long a publish waits for the groups it delivers to (default 15 000). */\n ackTimeoutMs: z.number().int().positive().optional(),\n /** How long an entry may stay pending on a consumer before a live one takes it over (default 5 000). */\n claimIdleMs: z.number().int().positive().optional(),\n /** The approximate length each stream is trimmed to (default 10 000). */\n streamMaxLen: z.number().int().positive().optional(),\n })\n .strict()\n\nconst S3_KEYS = ['bucket', 'region', 'endpoint', 'prefix', 'publicUrl', 'forcePathStyle']\n\n/**\n * The bucket `media: { provider: 's3' }` stores in. Each field falls back to the environment in the platform;\n * credentials are never config keys: the AWS SDK's default chain provides them.\n */\nexport const s3Schema = z\n .object(\n {\n /** Defaults to `S3_BUCKET`; one of the two is required. */\n bucket: z.string().min(1).optional(),\n /** Defaults to `AWS_REGION`, then `'us-east-1'`. */\n region: z.string().min(1).optional(),\n /** An S3-compatible API (MinIO, R2); defaults to `S3_ENDPOINT`, then AWS. */\n endpoint: z.string().min(1).optional(),\n /** Where every object key starts; defaults to `NYMBAL_S3_PREFIX`, then none. */\n prefix: z.string().optional(),\n /** Where the bucket's objects are served from (a CDN); defaults to `S3_PUBLIC_URL`, then the bucket's own URL. */\n publicUrl: z.string().min(1).optional(),\n /** Path-style requests; true by default when an endpoint is set. */\n forcePathStyle: z.boolean().optional(),\n },\n {\n error: (issue) =>\n issue.code === 'unrecognized_keys'\n ? `unknown infrastructure.s3 key${issue.keys.length > 1 ? 's' : ''} ${quotedList(issue.keys)}; the s3 keys are ${quotedList(S3_KEYS)}, and credentials come from the AWS SDK (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, a profile or a role), never the config`\n : undefined,\n },\n )\n .strict()\n\nexport const infrastructureSchema = z\n .object(\n {\n commandStore: infrastructureValue('commandStore', COMMAND_STORES),\n documentStore: infrastructureBlock('documentStore'),\n eventBus: infrastructureBlock('eventBus'),\n media: infrastructureBlock('media').default({ provider: 'local-fs' }),\n redis: redisSchema.optional(),\n s3: s3Schema.optional(),\n },\n {\n error: (issue) =>\n issue.code === 'unrecognized_keys' ? unrecognizedInfrastructureKeys(issue.keys) : undefined,\n },\n )\n .strict()\n .superRefine((infra, ctx) => {\n if (infra.documentStore.provider === 'postgres-jsonb' && infra.commandStore !== 'postgres') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['documentStore'],\n message: `documentStore 'postgres-jsonb' shares the command store's Postgres connection, so it needs commandStore 'postgres' (not '${infra.commandStore}')`,\n })\n }\n if (\n infra.eventBus.provider === 'redis-streams' &&\n infra.documentStore.provider === 'in-memory'\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['eventBus'],\n message: `eventBus 'redis-streams' needs a shared documentStore ('redis' or 'postgres-jsonb'), not 'in-memory': a named group hands each event to one instance, so a per-process read model would miss the rest`,\n })\n }\n if (infra.s3 !== undefined && infra.media.provider !== 's3') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['s3'],\n message: `infrastructure.s3 configures media 's3', but media is '${infra.media.provider}': set media to 's3' or delete the s3 block`,\n })\n }\n })\n\n/** Where a `cloudflare` store's rules go: required when `security.adapter` is `cloudflare`, read with `env()`. */\nconst cloudflareSchema = z.object({\n zoneId: z.string().optional(),\n apiToken: z.string().optional(),\n /** The Cloudflare v4 API; the adapter defaults it to https://api.cloudflare.com/client/v4. */\n apiBase: z.string().url().optional(),\n})\n\nconst customRuleSchema = z.object({\n name: z.string().min(1),\n expression: z.string().min(1),\n action: z.enum(['block', 'managed_challenge', 'js_challenge', 'log']),\n})\n\n/** An RFC 9110 field name. */\nconst HEADER_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\n/** Headers HTTP, the API or a CDN already gives a meaning, which a CDN would overwrite or the API would misread. */\nconst OWNED_HEADERS = [\n 'host',\n 'cookie',\n 'authorization',\n 'content-length',\n 'content-type',\n 'transfer-encoding',\n 'connection',\n 'forwarded',\n 'x-nymbal-shopper',\n 'x-correlation-id',\n 'x-real-ip',\n]\n\nconst originLockHeaderSchema = z.string().superRefine((header, ctx) => {\n const lower = header.toLowerCase()\n const problem = !HEADER_TOKEN.test(header)\n ? 'is not an HTTP header name'\n : OWNED_HEADERS.includes(lower) || lower.startsWith('x-forwarded-') || lower.startsWith('cf-')\n ? 'is a header HTTP, a CDN or the API already uses; choose your own, such as X-Nymbal-Origin'\n : null\n if (problem !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `security.originLock.header '${header}' ${problem}`,\n })\n }\n})\n\nconst securityFields = z.object({\n /** `middleware` is the kernel's own; any other resolves as a commerce provider does, `security-<adapter>`. */\n adapter: providerNameSchema('security.adapter'),\n /** The npm package the adapter comes from, in place of `@nymbalhq/security-<adapter>`. */\n package: packageNameSchema.optional(),\n /** A third-party adapter's `ctx.config`; `cloudflare` reads `security.cloudflare`, and `middleware` takes none. */\n config: z.record(z.string(), z.unknown()).optional(),\n rateLimit: z\n .record(\n z.string().regex(rateLimitPathPattern, {\n message: 'rate limit keys must start with \"/\" and use only letters, numbers, -, _, /, *, :',\n }),\n rateLimitRuleSchema,\n // Zod 4 reports a bad key as \"Invalid key in record\" and nests the key schema's message; surface that message.\n { error: (issue) => (issue.code === 'invalid_key' ? issue.issues[0]?.message : undefined) },\n )\n .default({}),\n botProtection: z\n .object({\n mode: z.enum(['off', 'managed', 'strict']).default('off'),\n allowList: z.array(z.string()).default([]),\n })\n .default({ mode: 'off', allowList: [] }),\n headers: z\n .object({\n hsts: z.boolean().default(true),\n contentSecurityPolicy: z\n .union([z.enum(['strict', 'relaxed', 'off']), z.string()])\n .default('strict'),\n referrerPolicy: z.string().default('strict-origin-when-cross-origin'),\n xFrameOptions: z.enum(['deny', 'sameorigin']).default('deny'),\n })\n .prefault({}),\n csrf: z.boolean().default(true),\n /** The header a CDN proves a request crossed it in; `NYMBAL_ORIGIN_SECRET` holds the value and turns the lock on. */\n originLock: z.object({ header: originLockHeaderSchema.default('X-Nymbal-Origin') }).prefault({}),\n auth: z\n .object({\n jwtSecret: z.string().min(16).default(DEFAULT_JWT_SECRET),\n accessTtl: z\n .string()\n .regex(/^\\d+(ms|s|m|h|d)$/, 'TTL must look like \"15m\"')\n .default('15m'),\n refreshTtl: z\n .string()\n .regex(/^\\d+(ms|s|m|h|d)$/, 'TTL must look like \"7d\"')\n .default('7d'),\n })\n .prefault({}),\n cloudflare: cloudflareSchema.optional(),\n geo: z\n .object({\n block: z\n .array(z.string().regex(/^[A-Z]{2}$/, 'geo.block codes are ISO 3166 alpha-2, like \"RU\"'))\n .default([]),\n })\n .default({ block: [] }),\n customRules: z.array(customRuleSchema).default([]),\n managedRulesets: z.array(z.enum(['cloudflare', 'owasp'])).default([]),\n})\n\nexport const securitySchema = securityFields.superRefine((security, ctx) => {\n customOutsideCommerce('security', security.adapter, ctx)\n packageBesideBuiltIn('security', { provider: security.adapter, package: security.package }, ctx)\n if (\n security.config !== undefined &&\n (security.adapter === 'middleware' || security.adapter === 'cloudflare')\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['config'],\n message: `security.config is a third-party adapter's config; security.adapter '${security.adapter}' ${security.adapter === 'cloudflare' ? 'reads security.cloudflare' : 'takes none'}`,\n })\n }\n if (security.adapter === 'cloudflare') {\n for (const field of ['zoneId', 'apiToken'] as const) {\n if (!security.cloudflare?.[field]) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['cloudflare', field],\n message: `security.adapter 'cloudflare' needs security.cloudflare.${field}`,\n })\n }\n }\n }\n const seen = new Set<string>()\n security.customRules.forEach((rule, i) => {\n if (seen.has(rule.name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['customRules', i, 'name'],\n message: `customRules has two rules named '${rule.name}'; names must be unique`,\n })\n }\n seen.add(rule.name)\n })\n})\n\n/** A commerce slot's block: any provider name, the npm package it comes from, and the adapter's config. */\nfunction adapterBlock(slot: CommerceSlot) {\n return z\n .object({\n provider: providerNameSchema(`${slot}.provider`),\n config: z.record(z.string(), z.unknown()).optional(),\n /**\n * The npm package the adapter comes from, in place of `@nymbalhq/<slot>-<provider>`. On a `custom` slot it is for\n * tooling (`nymbal test:contracts`): the kernel takes the adapter passed to `createApp` and imports nothing.\n */\n package: packageNameSchema.optional(),\n })\n .superRefine((block, ctx) => packageBesideBuiltIn(slot, block, ctx))\n}\n\nexport const commerceSchema = z.object({\n payments: adapterBlock('payments'),\n email: adapterBlock('email'),\n reviews: adapterBlock('reviews'),\n search: adapterBlock('search'),\n analytics: adapterBlock('analytics'),\n shipping: adapterBlock('shipping'),\n tax: adapterBlock('tax'),\n ai: adapterBlock('ai'),\n orders: z\n .object({\n numberPrefix: z.string().min(1).default('NYM'),\n numberStart: z.number().int().nonnegative().default(1000),\n /** How long an order key opens the order on its own: the checkout's, and the order email's. */\n keyLifetime: z\n .object({\n checkout: z\n .string()\n .regex(/^\\d+(ms|s|m|h|d)$/, 'TTL must look like \"48h\"')\n .default('48h'),\n email: z\n .string()\n .regex(/^\\d+(ms|s|m|h|d)$/, 'TTL must look like \"30d\"')\n .default('30d'),\n })\n .prefault({}),\n })\n .prefault({}),\n})\n\nexport const httpSchema = z.object({\n adapter: z.enum(['fastify', 'hono']).default('fastify'),\n port: z.number().int().positive().default(3001),\n host: z.string().default('0.0.0.0'),\n /**\n * The proxies in front whose `X-Forwarded-For` sets the client address the rate limiter keys on: `loopback`,\n * `linklocal`, `uniquelocal`, an IP address or a CIDR. Unset, `loopback`; NYMBAL_TRUSTED_PROXIES replaces it.\n */\n trustedProxies: z\n .array(\n z.string().superRefine((entry, ctx) => {\n const problem = trustedProxyProblem(entry)\n if (problem !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: trustedProxyMessage(entry, 'http.trustedProxies', problem),\n })\n }\n }),\n )\n .optional(),\n /**\n * One header a listed proxy sets to the client's address (`True-Client-IP`, `CF-Connecting-IP`), read in place of\n * `X-Forwarded-For` and only from a listed proxy. NYMBAL_CLIENT_IP_HEADER replaces it.\n */\n clientIpHeader: z\n .string()\n .superRefine((name, ctx) => {\n const problem = clientIpHeaderProblem(name)\n if (problem !== null)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: `'${name}' ${problem}` })\n })\n .optional(),\n trustProxy: z\n .never({\n error:\n \"http.trustProxy was removed: list the proxies in front in http.trustedProxies (or NYMBAL_TRUSTED_PROXIES), such as ['loopback'] or ['uniquelocal']\",\n })\n .optional(),\n cors: z\n .object({\n allowedOrigins: z\n .array(z.string())\n .default(['http://localhost:3000', 'http://localhost:4321']),\n credentials: z.boolean().default(true),\n })\n .prefault({}),\n})\n\nexport const deploymentSchema = z.object({\n strategy: z.enum(['standard', 'blue-green']).default('standard'),\n})\n\nexport const featuresSchema = z.object({\n staging: z.boolean().default(false),\n heartbeat: z.boolean().default(false),\n autoUpdates: z.boolean().default(false),\n})\n\n/**\n * The bucket delivered events past retention are archived to before they are deleted. Its objects hold customer\n * data, so it must be private: never the media bucket, which serves its objects publicly. Credentials come from the\n * AWS SDK's default chain, as `infrastructure.s3`'s do.\n */\nexport const eventArchiveSchema = z\n .object({\n adapter: z.literal('s3'),\n bucket: z.string().min(1),\n /** Where every archive key starts; none when not given. */\n prefix: z.string().optional(),\n /** `'us-east-1'` when not given. */\n region: z.string().min(1).optional(),\n /** An S3-compatible API (MinIO, R2). */\n endpoint: z.string().min(1).optional(),\n /** Path-style requests; true by default when an endpoint is set. */\n forcePathStyle: z.boolean().optional(),\n })\n .strict()\n\nexport const eventsSchema = z\n .object({\n /** Days a delivered event stays in the log. */\n retentionDays: z.number().int().min(1).default(30),\n archive: eventArchiveSchema.optional(),\n })\n .strict()\n\nconst MCP_WRITES = ['proposal', 'apply'] as const\n\n/**\n * The AI crawlers `robots.txt` names and allows by default, each as its vendor documents it:\n * - GPTBot, OAI-SearchBot, ChatGPT-User: https://platform.openai.com/docs/bots\n * - ClaudeBot, Claude-User, Claude-SearchBot:\n * https://support.claude.com/en/articles/8896518-does-anthropic-crawl-data-from-the-web-and-how-can-site-owners-block-the-crawler\n * - PerplexityBot, Perplexity-User: https://docs.perplexity.ai/guides/bots\n * - Google-Extended: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers\n * - Applebot-Extended: https://support.apple.com/en-us/119829\n */\nexport const DEFAULT_AGENT_CRAWLERS: readonly string[] = Object.freeze([\n 'GPTBot',\n 'OAI-SearchBot',\n 'ChatGPT-User',\n 'ClaudeBot',\n 'Claude-User',\n 'Claude-SearchBot',\n 'PerplexityBot',\n 'Perplexity-User',\n 'Google-Extended',\n 'Applebot-Extended',\n])\n\nconst CRAWL_OTHERS = ['allow', 'disallow'] as const\n\n/** The link types the Agentic Commerce Protocol (2026-04-17) names for a session's `links`. */\nexport const ACP_LINK_TYPES = [\n 'terms_of_use',\n 'privacy_policy',\n 'return_policy',\n 'shipping_policy',\n 'contact_us',\n 'about_us',\n 'faq',\n 'support',\n] as const\n\n/** The shortest ACP key the store takes, from the config or `NYMBAL_ACP_API_KEY`. */\nexport const ACP_KEY_MIN_LENGTH = 32\n\n/**\n * How agents reach the store. Under `mcp.writes: 'proposal'` an admin command tool's call is kept as a proposal an\n * admin approves or rejects, unless `autoApprove` lists its command; `'apply'` approves every command at the call.\n * Either way the proposal is recorded. A command that moves money cannot be listed in `autoApprove`. `ucp` is the\n * Universal Commerce Protocol profile and its MCP endpoint; `links` are the legal pages a UCP checkout names. `acp`\n * is the Agentic Commerce Protocol's checkout (beta, off unless enabled), held by a bearer key of at least 32\n * characters (`apiKey`, else `NYMBAL_ACP_API_KEY`). `crawl` is what `robots.txt`, `llms.txt` and the product feed serve.\n * `assistant` is what the admin's assistant may send its AI provider.\n */\nexport const agentsSchema = z\n .object({\n mcp: z\n .object({\n enabled: z.boolean().default(true),\n writes: z\n .enum(MCP_WRITES, {\n error: (issue) =>\n issue.code === 'invalid_value'\n ? `must be 'proposal' or 'apply', not ${JSON.stringify(issue.input)}`\n : undefined,\n })\n .default('proposal'),\n })\n .strict()\n .prefault({}),\n autoApprove: z.array(z.string().min(1)).default([]),\n ucp: z\n .object({\n enabled: z.boolean().default(true),\n links: z\n .array(\n z\n .object({\n type: z.string().min(1),\n url: z.string().url(),\n title: z.string().optional(),\n })\n .strict(),\n )\n .default([]),\n })\n .strict()\n .prefault({}),\n acp: z\n .object({\n enabled: z.boolean().default(false),\n apiKey: z\n .string()\n .min(ACP_KEY_MIN_LENGTH, { error: `must be at least ${ACP_KEY_MIN_LENGTH} characters` })\n .optional(),\n links: z\n .array(\n z\n .object({\n type: z.enum(ACP_LINK_TYPES),\n url: z.string().url(),\n title: z.string().optional(),\n })\n .strict(),\n )\n .default([]),\n merchantId: z.string().min(1).optional(),\n })\n .strict()\n .prefault({}),\n crawl: z\n .object({\n robots: z.boolean().default(true),\n llms: z.boolean().default(true),\n feed: z.boolean().default(true),\n allow: z.array(z.string().min(1)).default(() => [...DEFAULT_AGENT_CRAWLERS]),\n others: z\n .enum(CRAWL_OTHERS, {\n error: (issue) =>\n issue.code === 'invalid_value'\n ? `must be 'allow' or 'disallow', not ${JSON.stringify(issue.input)}`\n : undefined,\n })\n .default('allow'),\n })\n .strict()\n .prefault({}),\n assistant: z\n .object({\n /** false keeps every tool that answers a customer's email, phone or address off the admin's assistant. */\n customerData: z.boolean().default(true),\n })\n .strict()\n .prefault({}),\n })\n .strict()\n\nexport const nymbalConfigSchema = z\n .object({\n store: storeSchema,\n template: z.enum(['astro', 'nextjs']),\n infrastructure: infrastructureSchema,\n security: securitySchema,\n commerce: commerceSchema,\n http: httpSchema,\n deployment: deploymentSchema,\n features: featuresSchema.default({\n staging: false,\n heartbeat: false,\n autoUpdates: false,\n }),\n events: eventsSchema.prefault({}),\n agents: agentsSchema.prefault({}),\n })\n .superRefine((cfg, ctx) => {\n const archiveBucket = cfg.events.archive?.bucket\n if (\n archiveBucket !== undefined &&\n cfg.infrastructure.media.provider === 's3' &&\n archiveBucket === cfg.infrastructure.s3?.bucket\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['events', 'archive', 'bucket'],\n message: `events.archive.bucket is infrastructure.s3.bucket ('${archiveBucket}'), the media bucket, which serves its objects publicly; archive events to a private bucket of their own`,\n })\n }\n // SMTP left the kernel for @nymbalhq/email-smtp; a native block still asking for it would print to the console.\n const email = cfg.commerce.email\n if (email.provider === 'native' && email.config?.['transport'] === 'smtp') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['commerce', 'email', 'config', 'transport'],\n message: `the native email provider only prints to the console; for SMTP mail set email.provider to 'smtp' (@nymbalhq/email-smtp)`,\n })\n }\n })\n\nexport type NymbalConfigInput = z.input<typeof nymbalConfigSchema>\nexport type NymbalConfig = z.output<typeof nymbalConfigSchema>\n","import { isIP } from 'node:net'\nimport proxyAddr from '@fastify/proxy-addr'\nimport {\n ConfigError,\n type NetworkSource,\n type ResolvedNetwork,\n type SecurityNetwork,\n} from '@nymbalhq/types'\nimport type { NymbalConfig } from './schema.js'\n\nexport const TRUSTED_PROXIES_ENV = 'NYMBAL_TRUSTED_PROXIES'\nexport const CLIENT_IP_HEADER_ENV = 'NYMBAL_CLIENT_IP_HEADER'\nconst REMOVED_HOPS_ENV = 'NYMBAL_TRUST_PROXY_HOPS'\nconst LIST_KEY = 'http.trustedProxies'\nconst HEADER_KEY = 'http.clientIpHeader'\nconst DEFAULT_LIST = ['loopback']\n\nconst PRESETS = ['loopback', 'linklocal', 'uniquelocal'] as const\nconst PRESET_MATCHERS = PRESETS.map((preset) => [preset, proxyAddr.compile(preset)] as const)\n\n/** An RFC 9110 field name. */\nconst TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\n/** Chains, which the trusted list walks: never a single client address. */\nconst CHAIN_HEADERS = ['x-forwarded-for', 'forwarded']\n\n/**\n * What is wrong with one trusted-proxy entry, by proxy-addr's own reading of it (the reading Fastify applies when it is\n * built): `everyone` for a prefix of 0 or an IPv4-mapped range of /96 or wider (at /96 proxy-addr matches every IPv4\n * peer against it), `invalid` for anything else it refuses, `null` when it compiles.\n */\nexport function trustedProxyProblem(entry: string): 'invalid' | 'everyone' | null {\n if (compiles(entry)) return mappedEveryIpv4(entry) ? 'everyone' : null\n const slash = entry.lastIndexOf('/')\n if (slash < 0) return 'invalid'\n const prefix = entry.slice(slash + 1)\n const zero = /^0+$/.test(prefix) || prefix === '0.0.0.0'\n return zero && isIP(entry.slice(0, slash)) !== 0 ? 'everyone' : 'invalid'\n}\n\nfunction mappedEveryIpv4(entry: string): boolean {\n const slash = entry.lastIndexOf('/')\n if (slash < 0 || Number(entry.slice(slash + 1)) > 96) return false\n const address = entry.slice(0, slash).split('%')[0]!\n if (isIP(address) !== 6) return false\n // The WHATWG form of any IPv4-mapped address is ::ffff:<hextet>:<hextet>.\n return /^\\[::ffff:[0-9a-f]{1,4}:[0-9a-f]{1,4}\\]$/.test(new URL(`http://[${address}]`).hostname)\n}\n\nfunction compiles(entry: string): boolean {\n try {\n proxyAddr.compile([entry])\n return true\n } catch {\n return false\n }\n}\n\nexport function trustedProxyMessage(\n entry: string,\n source: string,\n problem: 'invalid' | 'everyone',\n): string {\n return problem === 'everyone'\n ? `${source} entry '${entry}' trusts every address, so any client could choose its own; list the proxies in front instead, such as loopback or uniquelocal`\n : `${source} entry '${entry}' is not a proxy address: list loopback, linklocal, uniquelocal, an IP address or a CIDR such as 10.0.0.0/8`\n}\n\n/** Why a client-address header name cannot be used, or null. */\nexport function clientIpHeaderProblem(name: string): string | null {\n if (!TOKEN.test(name)) return 'is not an HTTP header name'\n if (CHAIN_HEADERS.includes(name.toLowerCase())) {\n return 'is a chain of addresses, which the trusted proxy list already reads; name a header that holds one client address, such as True-Client-IP'\n }\n return null\n}\n\nfunction sourceLabel(source: NetworkSource): string {\n return source.kind === 'adapter' ? `adapter ${source.name}` : source.name\n}\n\n/** A variable's value, or undefined when it is unset or blank. */\nfunction fromEnv(env: NodeJS.ProcessEnv, name: string): string | undefined {\n const value = env[name]?.trim()\n return value === undefined || value === '' ? undefined : value\n}\n\nfunction resolveList(\n config: NymbalConfig,\n env: NodeJS.ProcessEnv,\n contribution: { adapter: string; network: SecurityNetwork } | undefined,\n): { list: string[]; source: NetworkSource } {\n const variable = fromEnv(env, TRUSTED_PROXIES_ENV)\n ?.split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry !== '')\n if (variable !== undefined && variable.length > 0) {\n return { list: variable, source: { kind: 'env', name: TRUSTED_PROXIES_ENV } }\n }\n if (config.http.trustedProxies !== undefined) {\n return { list: config.http.trustedProxies, source: { kind: 'config', name: LIST_KEY } }\n }\n if (contribution?.network.trustedProxies !== undefined) {\n return {\n list: contribution.network.trustedProxies,\n source: { kind: 'adapter', name: contribution.adapter },\n }\n }\n return { list: [...DEFAULT_LIST], source: { kind: 'default', name: 'default' } }\n}\n\nfunction resolveHeader(\n config: NymbalConfig,\n env: NodeJS.ProcessEnv,\n contribution: { adapter: string; network: SecurityNetwork } | undefined,\n): { header: string; source: NetworkSource } | undefined {\n const variable = fromEnv(env, CLIENT_IP_HEADER_ENV)\n if (variable !== undefined) {\n return { header: variable, source: { kind: 'env', name: CLIENT_IP_HEADER_ENV } }\n }\n if (config.http.clientIpHeader !== undefined) {\n return { header: config.http.clientIpHeader, source: { kind: 'config', name: HEADER_KEY } }\n }\n if (contribution?.network.clientIpHeader !== undefined) {\n return {\n header: contribution.network.clientIpHeader,\n source: { kind: 'adapter', name: contribution.adapter },\n }\n }\n return undefined\n}\n\n/**\n * The proxies whose forwarded client address the API believes, and the one client-address header it reads from them.\n * Each resolves on its own: its variable, else its config key, else the security adapter's contribution, else the\n * default (`loopback`; no header). Every value is checked as Fastify will read it, so a list this returns cannot fail the\n * server's construction; trusting every address is refused, as is the removed hop count.\n */\nexport function resolveTrustedProxies(\n config: NymbalConfig,\n env: NodeJS.ProcessEnv,\n contribution?: { adapter: string; network: SecurityNetwork },\n): ResolvedNetwork {\n if (fromEnv(env, REMOVED_HOPS_ENV) !== undefined) {\n throw new ConfigError(\n `${REMOVED_HOPS_ENV} was removed: list the proxies in front in ${TRUSTED_PROXIES_ENV} instead, such as loopback or uniquelocal`,\n { code: 'config.trust_proxy_hops_removed', context: { variable: REMOVED_HOPS_ENV } },\n )\n }\n\n const { list, source } = resolveList(config, env, contribution)\n for (const entry of list) {\n const problem = trustedProxyProblem(entry)\n if (problem === null) continue\n const label = sourceLabel(source)\n throw new ConfigError(trustedProxyMessage(entry, label, problem), {\n code:\n problem === 'everyone'\n ? 'config.trusted_proxies_everyone'\n : 'config.trusted_proxies_invalid',\n context: { entry, source: label },\n })\n }\n\n const header = resolveHeader(config, env, contribution)\n if (header !== undefined) {\n const problem = clientIpHeaderProblem(header.header)\n if (problem !== null) {\n const label = sourceLabel(header.source)\n throw new ConfigError(`${label} '${header.header}' ${problem}`, {\n code: 'config.client_ip_header_invalid',\n context: { header: header.header, source: label },\n })\n }\n }\n\n return {\n trustedProxies: list,\n trustedProxiesSource: source,\n ...(header !== undefined && {\n clientIpHeader: header.header,\n clientIpHeaderSource: header.source,\n }),\n clientIpRequiresLock:\n header?.source.kind === 'adapter' && contribution?.network.clientIpRequiresLock === true,\n }\n}\n\n/** The preset that holds `address` (an IPv4-mapped address by its IPv4 form), else the address itself. */\nexport function trustSuggestion(address: string): string {\n for (const [preset, holds] of PRESET_MATCHERS) if (holds(address, 0)) return preset\n return address\n}\n","import type { NymbalConfig } from './schema.js'\n\nexport const PUBLIC_URL_ENV = 'NYMBAL_PUBLIC_URL'\n\n/**\n * Whether the cookies the API sets carry `Secure`: exactly when the store's public origin is https, that origin being\n * NYMBAL_PUBLIC_URL when set, else `store.url`. With neither, production's. NODE_ENV alone is not enough: a staging\n * store served over https would send its session cookies over http too.\n */\nexport function secureCookies(\n config: Pick<NymbalConfig, 'store'>,\n env: Record<string, string | undefined>,\n): boolean {\n const fromEnv = env[PUBLIC_URL_ENV]?.trim()\n const origin = fromEnv !== undefined && fromEnv !== '' ? fromEnv : config.store.url\n if (origin === undefined) return env['NODE_ENV'] === 'production'\n return /^https:/i.test(origin)\n}\n","import { ConfigError, type ResolvedOriginLock } from '@nymbalhq/types'\nimport type { NymbalConfig } from './schema.js'\n\nexport const ORIGIN_SECRET_ENV = 'NYMBAL_ORIGIN_SECRET'\n\n/** Long enough not to be guessed, and only characters any CDN can send in a header value. */\nconst ENTRY = /^[A-Za-z0-9+/=_.~-]{32,256}$/\n\n/**\n * The origin lock from `NYMBAL_ORIGIN_SECRET`: one secret, or several separated by commas while one is rotated out.\n * Blank entries are dropped and a blank variable is unset. A refusal names the entry's position, never its text, since\n * the message reaches logs and terminals.\n */\nexport function resolveOriginLock(\n config: NymbalConfig,\n env: NodeJS.ProcessEnv,\n): ResolvedOriginLock | undefined {\n const secrets = (env[ORIGIN_SECRET_ENV] ?? '')\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry !== '')\n if (secrets.length === 0) return undefined\n const invalid = secrets.findIndex((entry) => !ENTRY.test(entry))\n if (invalid >= 0) {\n const position = invalid + 1\n throw new ConfigError(\n `${ORIGIN_SECRET_ENV} entry ${position} is not an origin secret: each entry is 32 to 256 characters of A-Z a-z 0-9 + / = _ . ~ - (nymbal security:apply makes one)`,\n { code: 'config.origin_secret_invalid', context: { variable: ORIGIN_SECRET_ENV, position } },\n )\n }\n return { header: config.security.originLock.header, secrets }\n}\n"],"mappings":";AAEO,SAAS,aAA0C,QAAc;AACtE,SAAO;AACT;;;ACJA,SAAS,mBAAmB;AAErB,SAAS,IAAI,KAAa,cAA+B;AAC9D,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,MAAI,UAAU,UAAa,UAAU,GAAI,QAAO;AAChD,MAAI,iBAAiB,OAAW,QAAO;AACvC,QAAM,IAAI,YAAY,0CAA0C,GAAG,IAAI;AAAA,IACrE,SAAS,EAAE,IAAI;AAAA,EACjB,CAAC;AACH;AAEO,SAAS,YAAY,KAAiC;AAC3D,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,SAAO,UAAU,UAAa,UAAU,KAAK,QAAQ;AACvD;AAEO,SAAS,UAAU,KAAa,cAA+B;AACpE,QAAM,MAAM,YAAY,GAAG;AAC3B,MAAI,QAAQ,QAAW;AACrB,QAAI,iBAAiB,OAAW,QAAO;AACvC,UAAM,IAAI,YAAY,0CAA0C,GAAG,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAAA,EAC7F;AACA,QAAM,SAAS,OAAO,GAAG;AACzB,MAAI,CAAC,OAAO,SAAS,MAAM,GAAG;AAC5B,UAAM,IAAI,YAAY,wBAAwB,GAAG,2BAA2B,GAAG,IAAI;AAAA,MACjF,SAAS,EAAE,KAAK,IAAI;AAAA,IACtB,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEO,SAAS,QAAQ,KAAa,eAAe,OAAgB;AAClE,QAAM,MAAM,YAAY,GAAG,GAAG,YAAY;AAC1C,MAAI,QAAQ,OAAW,QAAO;AAC9B,SAAO,QAAQ,UAAU,QAAQ,OAAO,QAAQ,SAAS,QAAQ;AACnE;;;AC7BO,IAAM,gBAAgB;AAGtB,SAAS,WAAW,MAAoB;AAC7C,SAAO,KAAK,QAAQ,UAAU,CAAC,MAAM,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I,MAAM,KAAK,KAAK,GAAG,IAAI;AAC1D,WAAO,YAAO,EAAE,KAAK,MAAM,OAAO;AAAA,EACpC,CAAC;AACD,SAAO,4BAA4B,IAAI;AAAA,EAAM,MAAM,KAAK,IAAI,CAAC;AAC/D;;;AG1FO,IAAM,iBAAiB;AAOvB,SAAS,cACd,QACAE,MACS;AACT,QAAMC,WAAUD,KAAI,cAAc,GAAG,KAAK;AAC1C,QAAM,SAASC,aAAY,UAAaA,aAAY,KAAKA,WAAU,OAAO,MAAM;AAChF,MAAI,WAAW,OAAW,QAAOD,KAAI,UAAU,MAAM;AACrD,SAAO,WAAW,KAAK,MAAM;AAC/B;;;ACjBA,SAAS,eAAAE,oBAA4C;AAG9C,IAAM,oBAAoB;AAGjC,IAAM,QAAQ;AAOP,SAAS,kBACd,QACAC,MACgC;AAChC,QAAM,WAAWA,KAAI,iBAAiB,KAAK,IACxC,MAAM,GAAG,EACT,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAC3B,OAAO,CAAC,UAAU,UAAU,EAAE;AACjC,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,QAAM,UAAU,QAAQ,UAAU,CAAC,UAAU,CAAC,MAAM,KAAK,KAAK,CAAC;AAC/D,MAAI,WAAW,GAAG;AAChB,UAAM,WAAW,UAAU;AAC3B,UAAM,IAAID;AAAA,MACR,GAAG,iBAAiB,UAAU,QAAQ;AAAA,MACtC,EAAE,MAAM,gCAAgC,SAAS,EAAE,UAAU,mBAAmB,SAAS,EAAE;AAAA,IAC7F;AAAA,EACF;AACA,SAAO,EAAE,QAAQ,OAAO,SAAS,WAAW,QAAQ,QAAQ;AAC9D;","names":["_","z","ConfigError","ConfigError","env","ConfigError","z","env","fromEnv","ConfigError","env"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nymbalhq/config",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "Typed configuration surface for Nymbal",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,9 +27,10 @@
27
27
  "dist"
28
28
  ],
29
29
  "dependencies": {
30
- "@nymbalhq/types": "1.4.0",
30
+ "@fastify/proxy-addr": "^5.1.2",
31
+ "@nymbalhq/types": "1.6.0",
31
32
  "jiti": "^2.4.0",
32
- "zod": "^3.23.8"
33
+ "zod": "^4.6.7"
33
34
  },
34
35
  "devDependencies": {
35
36
  "@typescript/native": "npm:typescript@^7.0.2",