@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 CHANGED
@@ -37,25 +37,98 @@ function envBool(key, defaultValue = false) {
37
37
  return raw === "true" || raw === "1" || raw === "yes" || raw === "on";
38
38
  }
39
39
 
40
- // src/known-providers.ts
41
- var KNOWN_PROVIDERS = {
42
- payments: ["native", "stripe", "custom"],
43
- email: ["native", "smtp", "custom"],
44
- reviews: ["native", "custom"],
45
- search: ["native", "custom"],
46
- analytics: ["native", "custom"],
47
- shipping: ["native", "custom"],
48
- tax: ["native", "custom"],
49
- ai: ["none", "anthropic", "custom"]
40
+ // src/adapter-names.ts
41
+ var PROVIDER_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
42
+ function slotFolder(slot) {
43
+ return slot.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
44
+ }
45
+ function conventionPackage(slot, provider) {
46
+ return `@nymbalhq/${slotFolder(slot)}-${provider}`;
47
+ }
48
+ var builtIn = { builtIn: true };
49
+ var ADAPTER_CATALOGUE = {
50
+ payments: { native: builtIn, stripe: { sdk: "stripe" } },
51
+ email: {
52
+ native: builtIn,
53
+ smtp: { sdk: "nodemailer" },
54
+ mailgun: { sdk: "nodemailer" },
55
+ resend: { sdk: "nodemailer" },
56
+ ses: { sdk: "nodemailer" }
57
+ },
58
+ reviews: { native: builtIn },
59
+ search: { native: builtIn, algolia: {} },
60
+ analytics: { native: builtIn },
61
+ shipping: { native: builtIn, aftership: {}, easypost: {} },
62
+ tax: { native: builtIn },
63
+ ai: { none: builtIn, anthropic: { sdk: "@anthropic-ai/sdk" }, openai: {} },
64
+ documentStore: {
65
+ "in-memory": builtIn,
66
+ redis: { sdk: "ioredis" },
67
+ "postgres-jsonb": { sdk: "pg" }
68
+ },
69
+ eventBus: { "in-process": builtIn, "redis-streams": { sdk: "ioredis" } },
70
+ media: { "local-fs": builtIn, s3: { sdk: "@aws-sdk/client-s3" } },
71
+ security: { middleware: builtIn, cloudflare: {} }
50
72
  };
73
+ var SLOTS = Object.keys(ADAPTER_CATALOGUE);
74
+ var BUILT_IN = Object.fromEntries(
75
+ SLOTS.map((slot) => [
76
+ slot,
77
+ Object.entries(ADAPTER_CATALOGUE[slot]).filter(([, entry]) => entry.builtIn === true).map(([name]) => name)
78
+ ])
79
+ );
80
+ var COMMERCE_SLOTS = [
81
+ "payments",
82
+ "email",
83
+ "reviews",
84
+ "search",
85
+ "analytics",
86
+ "shipping",
87
+ "tax",
88
+ "ai"
89
+ ];
90
+ function isCommerceSlot(slot) {
91
+ return COMMERCE_SLOTS.includes(slot);
92
+ }
93
+ function editDistance(a, b) {
94
+ const d = Array.from(
95
+ { length: a.length + 1 },
96
+ (_, i) => Array.from({ length: b.length + 1 }, (_2, j) => i === 0 ? j : j === 0 ? i : 0)
97
+ );
98
+ for (let i = 1; i <= a.length; i++) {
99
+ for (let j = 1; j <= b.length; j++) {
100
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
101
+ let best = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
102
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
103
+ best = Math.min(best, d[i - 2][j - 2] + 1);
104
+ }
105
+ d[i][j] = best;
106
+ }
107
+ }
108
+ return d[a.length][b.length];
109
+ }
110
+ var MAX_SUGGESTION_DISTANCE = 2;
111
+ function suggestProvider(slot, name) {
112
+ const candidates = [
113
+ ...Object.keys(ADAPTER_CATALOGUE[slot]),
114
+ ...isCommerceSlot(slot) ? ["custom"] : []
115
+ ].sort();
116
+ let best;
117
+ for (const candidate of candidates) {
118
+ const distance = editDistance(candidate, name);
119
+ if (distance > MAX_SUGGESTION_DISTANCE) continue;
120
+ if (best === void 0 || distance < best.distance) best = { name: candidate, distance };
121
+ }
122
+ return best?.name;
123
+ }
124
+
125
+ // src/known-providers.ts
126
+ var KNOWN_PROVIDERS = Object.fromEntries(
127
+ COMMERCE_SLOTS.map((slot) => [slot, [...Object.keys(ADAPTER_CATALOGUE[slot]), "custom"]])
128
+ );
51
129
 
52
130
  // src/known-infrastructure.ts
53
- var KNOWN_INFRASTRUCTURE = {
54
- commandStore: ["sqlite", "postgres"],
55
- documentStore: ["in-memory", "redis", "postgres-jsonb"],
56
- eventBus: ["in-process", "redis-streams"],
57
- media: ["local-fs", "s3"]
58
- };
131
+ var COMMAND_STORES = ["sqlite", "postgres"];
59
132
  var REMOVED_INFRASTRUCTURE_KEYS = ["cloud", "compute"];
60
133
 
61
134
  // src/load.ts
@@ -64,34 +137,256 @@ import { dirname, isAbsolute, resolve } from "path";
64
137
  import { pathToFileURL } from "url";
65
138
  import { createJiti } from "jiti";
66
139
  import { z as z2 } from "zod";
67
- import { ConfigError as ConfigError2 } from "@nymbalhq/types";
140
+ import { ConfigError as ConfigError3 } from "@nymbalhq/types";
68
141
 
69
142
  // src/schema.ts
70
143
  import { z } from "zod";
144
+
145
+ // src/trusted-proxies.ts
146
+ import { isIP } from "net";
147
+ import proxyAddr from "@fastify/proxy-addr";
148
+ import {
149
+ ConfigError as ConfigError2
150
+ } from "@nymbalhq/types";
151
+ var TRUSTED_PROXIES_ENV = "NYMBAL_TRUSTED_PROXIES";
152
+ var CLIENT_IP_HEADER_ENV = "NYMBAL_CLIENT_IP_HEADER";
153
+ var REMOVED_HOPS_ENV = "NYMBAL_TRUST_PROXY_HOPS";
154
+ var LIST_KEY = "http.trustedProxies";
155
+ var HEADER_KEY = "http.clientIpHeader";
156
+ var DEFAULT_LIST = ["loopback"];
157
+ var PRESETS = ["loopback", "linklocal", "uniquelocal"];
158
+ var PRESET_MATCHERS = PRESETS.map((preset) => [preset, proxyAddr.compile(preset)]);
159
+ var TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
160
+ var CHAIN_HEADERS = ["x-forwarded-for", "forwarded"];
161
+ function trustedProxyProblem(entry) {
162
+ if (compiles(entry)) return mappedEveryIpv4(entry) ? "everyone" : null;
163
+ const slash = entry.lastIndexOf("/");
164
+ if (slash < 0) return "invalid";
165
+ const prefix = entry.slice(slash + 1);
166
+ const zero = /^0+$/.test(prefix) || prefix === "0.0.0.0";
167
+ return zero && isIP(entry.slice(0, slash)) !== 0 ? "everyone" : "invalid";
168
+ }
169
+ function mappedEveryIpv4(entry) {
170
+ const slash = entry.lastIndexOf("/");
171
+ if (slash < 0 || Number(entry.slice(slash + 1)) > 96) return false;
172
+ const address = entry.slice(0, slash).split("%")[0];
173
+ if (isIP(address) !== 6) return false;
174
+ return /^\[::ffff:[0-9a-f]{1,4}:[0-9a-f]{1,4}\]$/.test(new URL(`http://[${address}]`).hostname);
175
+ }
176
+ function compiles(entry) {
177
+ try {
178
+ proxyAddr.compile([entry]);
179
+ return true;
180
+ } catch {
181
+ return false;
182
+ }
183
+ }
184
+ function trustedProxyMessage(entry, source, problem) {
185
+ return problem === "everyone" ? `${source} entry '${entry}' trusts every address, so any client could choose its own; list the proxies in front instead, such as loopback or uniquelocal` : `${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`;
186
+ }
187
+ function clientIpHeaderProblem(name) {
188
+ if (!TOKEN.test(name)) return "is not an HTTP header name";
189
+ if (CHAIN_HEADERS.includes(name.toLowerCase())) {
190
+ 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";
191
+ }
192
+ return null;
193
+ }
194
+ function sourceLabel(source) {
195
+ return source.kind === "adapter" ? `adapter ${source.name}` : source.name;
196
+ }
197
+ function fromEnv(env2, name) {
198
+ const value = env2[name]?.trim();
199
+ return value === void 0 || value === "" ? void 0 : value;
200
+ }
201
+ function resolveList(config, env2, contribution) {
202
+ const variable = fromEnv(env2, TRUSTED_PROXIES_ENV)?.split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
203
+ if (variable !== void 0 && variable.length > 0) {
204
+ return { list: variable, source: { kind: "env", name: TRUSTED_PROXIES_ENV } };
205
+ }
206
+ if (config.http.trustedProxies !== void 0) {
207
+ return { list: config.http.trustedProxies, source: { kind: "config", name: LIST_KEY } };
208
+ }
209
+ if (contribution?.network.trustedProxies !== void 0) {
210
+ return {
211
+ list: contribution.network.trustedProxies,
212
+ source: { kind: "adapter", name: contribution.adapter }
213
+ };
214
+ }
215
+ return { list: [...DEFAULT_LIST], source: { kind: "default", name: "default" } };
216
+ }
217
+ function resolveHeader(config, env2, contribution) {
218
+ const variable = fromEnv(env2, CLIENT_IP_HEADER_ENV);
219
+ if (variable !== void 0) {
220
+ return { header: variable, source: { kind: "env", name: CLIENT_IP_HEADER_ENV } };
221
+ }
222
+ if (config.http.clientIpHeader !== void 0) {
223
+ return { header: config.http.clientIpHeader, source: { kind: "config", name: HEADER_KEY } };
224
+ }
225
+ if (contribution?.network.clientIpHeader !== void 0) {
226
+ return {
227
+ header: contribution.network.clientIpHeader,
228
+ source: { kind: "adapter", name: contribution.adapter }
229
+ };
230
+ }
231
+ return void 0;
232
+ }
233
+ function resolveTrustedProxies(config, env2, contribution) {
234
+ if (fromEnv(env2, REMOVED_HOPS_ENV) !== void 0) {
235
+ throw new ConfigError2(
236
+ `${REMOVED_HOPS_ENV} was removed: list the proxies in front in ${TRUSTED_PROXIES_ENV} instead, such as loopback or uniquelocal`,
237
+ { code: "config.trust_proxy_hops_removed", context: { variable: REMOVED_HOPS_ENV } }
238
+ );
239
+ }
240
+ const { list, source } = resolveList(config, env2, contribution);
241
+ for (const entry of list) {
242
+ const problem = trustedProxyProblem(entry);
243
+ if (problem === null) continue;
244
+ const label = sourceLabel(source);
245
+ throw new ConfigError2(trustedProxyMessage(entry, label, problem), {
246
+ code: problem === "everyone" ? "config.trusted_proxies_everyone" : "config.trusted_proxies_invalid",
247
+ context: { entry, source: label }
248
+ });
249
+ }
250
+ const header = resolveHeader(config, env2, contribution);
251
+ if (header !== void 0) {
252
+ const problem = clientIpHeaderProblem(header.header);
253
+ if (problem !== null) {
254
+ const label = sourceLabel(header.source);
255
+ throw new ConfigError2(`${label} '${header.header}' ${problem}`, {
256
+ code: "config.client_ip_header_invalid",
257
+ context: { header: header.header, source: label }
258
+ });
259
+ }
260
+ }
261
+ return {
262
+ trustedProxies: list,
263
+ trustedProxiesSource: source,
264
+ ...header !== void 0 && {
265
+ clientIpHeader: header.header,
266
+ clientIpHeaderSource: header.source
267
+ },
268
+ clientIpRequiresLock: header?.source.kind === "adapter" && contribution?.network.clientIpRequiresLock === true
269
+ };
270
+ }
271
+ function trustSuggestion(address) {
272
+ for (const [preset, holds] of PRESET_MATCHERS) if (holds(address, 0)) return preset;
273
+ return address;
274
+ }
275
+
276
+ // src/schema.ts
71
277
  var rateLimitRuleSchema = z.object({
72
278
  requests: z.number().int().positive(),
73
279
  window: z.string().regex(/^\d+(ms|s|m|h)$/, 'window must look like "60s", "5m", "1h"'),
74
- action: z.enum(["block", "challenge", "throttle"])
280
+ action: z.enum(["block", "challenge", "throttle"]),
281
+ /** Counts only the requests to the path that carry this header, such as `x-nymbal-order-email`. */
282
+ header: z.string().min(1).optional()
75
283
  });
76
284
  var rateLimitPathPattern = /^\/[\w\-/*:]*$/;
77
285
  var DEFAULT_JWT_SECRET = "dev-secret-please-override-me-1234567890";
286
+ var shipFromSchema = z.object({
287
+ firstName: z.string().min(1),
288
+ lastName: z.string().min(1),
289
+ company: z.string().optional(),
290
+ addressLine1: z.string().min(1),
291
+ addressLine2: z.string().optional(),
292
+ city: z.string().min(1),
293
+ region: z.string(),
294
+ postalCode: z.string().min(1),
295
+ country: z.string().regex(/^[A-Z]{2}$/, 'country must be two upper-case letters, such as "GB"'),
296
+ phone: z.string().optional()
297
+ });
78
298
  var storeSchema = z.object({
79
299
  name: z.string().min(1),
80
300
  currency: z.string().length(3),
81
301
  locale: z.string().min(2),
82
302
  timezone: z.string().min(1),
83
303
  /** The storefront's public URL, which the order email links from; with none, the email has no link. */
84
- url: z.string().url().transform((url) => url.replace(/\/+$/, "")).optional()
304
+ url: z.string().url().transform((url) => url.replace(/\/+$/, "")).optional(),
305
+ /** Where parcels are sent from, for shipping rates. */
306
+ shipFrom: shipFromSchema.optional()
85
307
  });
86
308
  var quotedList = (values) => values.map((v) => `'${v}'`).join(", ");
87
309
  function infrastructureValue(slot, values) {
88
310
  return z.enum(values, {
89
- errorMap: (issue, ctx) => issue.code === z.ZodIssueCode.invalid_enum_value ? {
90
- message: `unknown ${slot} '${String(issue.received)}'; the ${slot} values are ${quotedList(values)}`
91
- } : { message: ctx.defaultError }
311
+ error: (issue) => issue.code === "invalid_value" ? `unknown ${slot} '${String(issue.input)}'; the ${slot} values are ${quotedList(values)}` : void 0
312
+ });
313
+ }
314
+ var NPM_PACKAGE_NAME = /^(?:@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/;
315
+ var packageNameSchema = z.string().max(214, "an npm package name is at most 214 characters").regex(NPM_PACKAGE_NAME, "must be an npm package name, such as `@acme/nymbal-search`");
316
+ function providerNameSchema(where) {
317
+ return z.string().superRefine((value, ctx) => {
318
+ if (!PROVIDER_NAME.test(value)) {
319
+ ctx.addIssue({
320
+ code: z.ZodIssueCode.custom,
321
+ message: `${where} '${value}' is not a provider name: a provider matches ${PROVIDER_NAME.source}`
322
+ });
323
+ }
324
+ });
325
+ }
326
+ function choiceOf(slot, provider) {
327
+ if (slot === "security") return `security.adapter '${provider}'`;
328
+ if (slot === "documentStore" || slot === "eventBus" || slot === "media") {
329
+ return `infrastructure.${slot} '${provider}'`;
330
+ }
331
+ return `${slot}.provider '${provider}'`;
332
+ }
333
+ function packageBesideBuiltIn(slot, block, ctx) {
334
+ if (block.package === void 0 || !BUILT_IN[slot].includes(block.provider)) return;
335
+ ctx.addIssue({
336
+ code: z.ZodIssueCode.custom,
337
+ path: ["package"],
338
+ 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`
339
+ });
340
+ }
341
+ function customOutsideCommerce(slot, provider, ctx) {
342
+ if (provider !== "custom") return;
343
+ ctx.addIssue({
344
+ code: z.ZodIssueCode.custom,
345
+ path: [slot === "security" ? "adapter" : "provider"],
346
+ 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)}' }`
92
347
  });
93
348
  }
94
- var INFRASTRUCTURE_KEYS = [...Object.keys(KNOWN_INFRASTRUCTURE), "redis", "s3"];
349
+ var KERNEL_CONFIGURED = {
350
+ documentStore: {
351
+ "in-memory": "it is built in and takes none",
352
+ redis: "infrastructure.redis configures it",
353
+ "postgres-jsonb": "it uses the command store's Postgres connection (DATABASE_URL)"
354
+ },
355
+ eventBus: {
356
+ "in-process": "it is built in and takes none",
357
+ "redis-streams": "infrastructure.redis configures it"
358
+ },
359
+ media: {
360
+ "local-fs": "it is built in and takes none",
361
+ s3: "infrastructure.s3 configures it"
362
+ }
363
+ };
364
+ function infrastructureBlock(slot) {
365
+ return z.object(
366
+ {
367
+ provider: providerNameSchema(`infrastructure.${slot}`),
368
+ /** The npm package the adapter comes from, in place of `@nymbalhq/<slot>-<provider>`. */
369
+ package: packageNameSchema.optional(),
370
+ /** The adapter's `ctx.config`, for a provider whose connection the kernel does not build. */
371
+ config: z.record(z.string(), z.unknown()).optional()
372
+ },
373
+ {
374
+ error: (issue) => issue.code === "invalid_type" && typeof issue.input === "string" ? `infrastructure.${slot} takes a block: write { provider: '${issue.input}' }` : void 0
375
+ }
376
+ ).superRefine((block, ctx) => {
377
+ customOutsideCommerce(slot, block.provider, ctx);
378
+ packageBesideBuiltIn(slot, block, ctx);
379
+ const configuredBy = Object.hasOwn(KERNEL_CONFIGURED[slot], block.provider) ? KERNEL_CONFIGURED[slot][block.provider] : void 0;
380
+ if (block.config !== void 0 && configuredBy !== void 0) {
381
+ ctx.addIssue({
382
+ code: z.ZodIssueCode.custom,
383
+ path: ["config"],
384
+ message: `infrastructure.${slot} '${block.provider}' takes no config: ${configuredBy}`
385
+ });
386
+ }
387
+ });
388
+ }
389
+ var INFRASTRUCTURE_KEYS = ["commandStore", "documentStore", "eventBus", "media", "redis", "s3"];
95
390
  function unrecognizedInfrastructureKeys(keys) {
96
391
  return keys.map(
97
392
  (key) => REMOVED_INFRASTRUCTURE_KEYS.includes(key) ? `infrastructure.${key} was removed: it drives nothing, so delete it from the config` : `unknown infrastructure key '${key}'; the infrastructure keys are ${quotedList(INFRASTRUCTURE_KEYS)}`
@@ -126,43 +421,41 @@ var s3Schema = z.object(
126
421
  forcePathStyle: z.boolean().optional()
127
422
  },
128
423
  {
129
- errorMap: (issue, ctx) => issue.code === z.ZodIssueCode.unrecognized_keys ? {
130
- 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`
131
- } : { message: ctx.defaultError }
424
+ error: (issue) => issue.code === "unrecognized_keys" ? `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` : void 0
132
425
  }
133
426
  ).strict();
134
427
  var infrastructureSchema = z.object(
135
428
  {
136
- commandStore: infrastructureValue("commandStore", KNOWN_INFRASTRUCTURE.commandStore),
137
- documentStore: infrastructureValue("documentStore", KNOWN_INFRASTRUCTURE.documentStore),
138
- eventBus: infrastructureValue("eventBus", KNOWN_INFRASTRUCTURE.eventBus),
139
- media: infrastructureValue("media", KNOWN_INFRASTRUCTURE.media).default("local-fs"),
429
+ commandStore: infrastructureValue("commandStore", COMMAND_STORES),
430
+ documentStore: infrastructureBlock("documentStore"),
431
+ eventBus: infrastructureBlock("eventBus"),
432
+ media: infrastructureBlock("media").default({ provider: "local-fs" }),
140
433
  redis: redisSchema.optional(),
141
434
  s3: s3Schema.optional()
142
435
  },
143
436
  {
144
- errorMap: (issue, ctx) => issue.code === z.ZodIssueCode.unrecognized_keys ? { message: unrecognizedInfrastructureKeys(issue.keys) } : { message: ctx.defaultError }
437
+ error: (issue) => issue.code === "unrecognized_keys" ? unrecognizedInfrastructureKeys(issue.keys) : void 0
145
438
  }
146
439
  ).strict().superRefine((infra, ctx) => {
147
- if (infra.documentStore === "postgres-jsonb" && infra.commandStore !== "postgres") {
440
+ if (infra.documentStore.provider === "postgres-jsonb" && infra.commandStore !== "postgres") {
148
441
  ctx.addIssue({
149
442
  code: z.ZodIssueCode.custom,
150
443
  path: ["documentStore"],
151
444
  message: `documentStore 'postgres-jsonb' shares the command store's Postgres connection, so it needs commandStore 'postgres' (not '${infra.commandStore}')`
152
445
  });
153
446
  }
154
- if (infra.eventBus === "redis-streams" && infra.documentStore === "in-memory") {
447
+ if (infra.eventBus.provider === "redis-streams" && infra.documentStore.provider === "in-memory") {
155
448
  ctx.addIssue({
156
449
  code: z.ZodIssueCode.custom,
157
450
  path: ["eventBus"],
158
451
  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`
159
452
  });
160
453
  }
161
- if (infra.s3 !== void 0 && infra.media !== "s3") {
454
+ if (infra.s3 !== void 0 && infra.media.provider !== "s3") {
162
455
  ctx.addIssue({
163
456
  code: z.ZodIssueCode.custom,
164
457
  path: ["s3"],
165
- message: `infrastructure.s3 configures media 's3', but media is '${infra.media}': set media to 's3' or delete the s3 block`
458
+ message: `infrastructure.s3 configures media 's3', but media is '${infra.media.provider}': set media to 's3' or delete the s3 block`
166
459
  });
167
460
  }
168
461
  });
@@ -177,13 +470,44 @@ var customRuleSchema = z.object({
177
470
  expression: z.string().min(1),
178
471
  action: z.enum(["block", "managed_challenge", "js_challenge", "log"])
179
472
  });
473
+ var HEADER_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
474
+ var OWNED_HEADERS = [
475
+ "host",
476
+ "cookie",
477
+ "authorization",
478
+ "content-length",
479
+ "content-type",
480
+ "transfer-encoding",
481
+ "connection",
482
+ "forwarded",
483
+ "x-nymbal-shopper",
484
+ "x-correlation-id",
485
+ "x-real-ip"
486
+ ];
487
+ var originLockHeaderSchema = z.string().superRefine((header, ctx) => {
488
+ const lower = header.toLowerCase();
489
+ const problem = !HEADER_TOKEN.test(header) ? "is not an HTTP header name" : OWNED_HEADERS.includes(lower) || lower.startsWith("x-forwarded-") || lower.startsWith("cf-") ? "is a header HTTP, a CDN or the API already uses; choose your own, such as X-Nymbal-Origin" : null;
490
+ if (problem !== null) {
491
+ ctx.addIssue({
492
+ code: z.ZodIssueCode.custom,
493
+ message: `security.originLock.header '${header}' ${problem}`
494
+ });
495
+ }
496
+ });
180
497
  var securityFields = z.object({
181
- adapter: z.enum(["middleware", "cloudflare", "aws-waf", "akamai"]),
498
+ /** `middleware` is the kernel's own; any other resolves as a commerce provider does, `security-<adapter>`. */
499
+ adapter: providerNameSchema("security.adapter"),
500
+ /** The npm package the adapter comes from, in place of `@nymbalhq/security-<adapter>`. */
501
+ package: packageNameSchema.optional(),
502
+ /** A third-party adapter's `ctx.config`; `cloudflare` reads `security.cloudflare`, and `middleware` takes none. */
503
+ config: z.record(z.string(), z.unknown()).optional(),
182
504
  rateLimit: z.record(
183
505
  z.string().regex(rateLimitPathPattern, {
184
506
  message: 'rate limit keys must start with "/" and use only letters, numbers, -, _, /, *, :'
185
507
  }),
186
- rateLimitRuleSchema
508
+ rateLimitRuleSchema,
509
+ // Zod 4 reports a bad key as "Invalid key in record" and nests the key schema's message; surface that message.
510
+ { error: (issue) => issue.code === "invalid_key" ? issue.issues[0]?.message : void 0 }
187
511
  ).default({}),
188
512
  botProtection: z.object({
189
513
  mode: z.enum(["off", "managed", "strict"]).default("off"),
@@ -194,13 +518,15 @@ var securityFields = z.object({
194
518
  contentSecurityPolicy: z.union([z.enum(["strict", "relaxed", "off"]), z.string()]).default("strict"),
195
519
  referrerPolicy: z.string().default("strict-origin-when-cross-origin"),
196
520
  xFrameOptions: z.enum(["deny", "sameorigin"]).default("deny")
197
- }).default({}),
521
+ }).prefault({}),
198
522
  csrf: z.boolean().default(true),
523
+ /** The header a CDN proves a request crossed it in; `NYMBAL_ORIGIN_SECRET` holds the value and turns the lock on. */
524
+ originLock: z.object({ header: originLockHeaderSchema.default("X-Nymbal-Origin") }).prefault({}),
199
525
  auth: z.object({
200
526
  jwtSecret: z.string().min(16).default(DEFAULT_JWT_SECRET),
201
527
  accessTtl: z.string().regex(/^\d+(ms|s|m|h|d)$/, 'TTL must look like "15m"').default("15m"),
202
528
  refreshTtl: z.string().regex(/^\d+(ms|s|m|h|d)$/, 'TTL must look like "7d"').default("7d")
203
- }).default({}),
529
+ }).prefault({}),
204
530
  cloudflare: cloudflareSchema.optional(),
205
531
  geo: z.object({
206
532
  block: z.array(z.string().regex(/^[A-Z]{2}$/, 'geo.block codes are ISO 3166 alpha-2, like "RU"')).default([])
@@ -209,6 +535,15 @@ var securityFields = z.object({
209
535
  managedRulesets: z.array(z.enum(["cloudflare", "owasp"])).default([])
210
536
  });
211
537
  var securitySchema = securityFields.superRefine((security, ctx) => {
538
+ customOutsideCommerce("security", security.adapter, ctx);
539
+ packageBesideBuiltIn("security", { provider: security.adapter, package: security.package }, ctx);
540
+ if (security.config !== void 0 && (security.adapter === "middleware" || security.adapter === "cloudflare")) {
541
+ ctx.addIssue({
542
+ code: z.ZodIssueCode.custom,
543
+ path: ["config"],
544
+ message: `security.config is a third-party adapter's config; security.adapter '${security.adapter}' ${security.adapter === "cloudflare" ? "reads security.cloudflare" : "takes none"}`
545
+ });
546
+ }
212
547
  if (security.adapter === "cloudflare") {
213
548
  for (const field of ["zoneId", "apiToken"]) {
214
549
  if (!security.cloudflare?.[field]) {
@@ -232,44 +567,71 @@ var securitySchema = securityFields.superRefine((security, ctx) => {
232
567
  seen.add(rule.name);
233
568
  });
234
569
  });
235
- var NPM_PACKAGE_NAME = /^(?:@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/;
236
- function adapterBlock(slot, providers) {
237
- const known = providers.map((p) => `'${p}'`).join(", ");
570
+ function adapterBlock(slot) {
238
571
  return z.object({
239
- provider: z.enum(providers, {
240
- errorMap: (issue, ctx) => issue.code === z.ZodIssueCode.invalid_enum_value ? {
241
- message: `unknown ${slot} provider '${String(issue.received)}'; the ${slot} providers are ${known}`
242
- } : { message: ctx.defaultError }
243
- }),
572
+ provider: providerNameSchema(`${slot}.provider`),
244
573
  config: z.record(z.string(), z.unknown()).optional(),
245
- /** The npm package a `custom` slot's adapter comes from, for tooling (`nymbal test:contracts`); the kernel never reads it. */
246
- package: z.string().max(214, "an npm package name is at most 214 characters").regex(NPM_PACKAGE_NAME, "must be an npm package name, such as `@acme/nymbal-search`").optional()
247
- });
574
+ /**
575
+ * The npm package the adapter comes from, in place of `@nymbalhq/<slot>-<provider>`. On a `custom` slot it is for
576
+ * tooling (`nymbal test:contracts`): the kernel takes the adapter passed to `createApp` and imports nothing.
577
+ */
578
+ package: packageNameSchema.optional()
579
+ }).superRefine((block, ctx) => packageBesideBuiltIn(slot, block, ctx));
248
580
  }
249
581
  var commerceSchema = z.object({
250
- payments: adapterBlock("payments", KNOWN_PROVIDERS.payments),
251
- email: adapterBlock("email", KNOWN_PROVIDERS.email),
252
- reviews: adapterBlock("reviews", KNOWN_PROVIDERS.reviews),
253
- search: adapterBlock("search", KNOWN_PROVIDERS.search),
254
- analytics: adapterBlock("analytics", KNOWN_PROVIDERS.analytics),
255
- shipping: adapterBlock("shipping", KNOWN_PROVIDERS.shipping),
256
- tax: adapterBlock("tax", KNOWN_PROVIDERS.tax),
257
- ai: adapterBlock("ai", KNOWN_PROVIDERS.ai),
582
+ payments: adapterBlock("payments"),
583
+ email: adapterBlock("email"),
584
+ reviews: adapterBlock("reviews"),
585
+ search: adapterBlock("search"),
586
+ analytics: adapterBlock("analytics"),
587
+ shipping: adapterBlock("shipping"),
588
+ tax: adapterBlock("tax"),
589
+ ai: adapterBlock("ai"),
258
590
  orders: z.object({
259
591
  numberPrefix: z.string().min(1).default("NYM"),
260
- numberStart: z.number().int().nonnegative().default(1e3)
261
- }).default({})
592
+ numberStart: z.number().int().nonnegative().default(1e3),
593
+ /** How long an order key opens the order on its own: the checkout's, and the order email's. */
594
+ keyLifetime: z.object({
595
+ checkout: z.string().regex(/^\d+(ms|s|m|h|d)$/, 'TTL must look like "48h"').default("48h"),
596
+ email: z.string().regex(/^\d+(ms|s|m|h|d)$/, 'TTL must look like "30d"').default("30d")
597
+ }).prefault({})
598
+ }).prefault({})
262
599
  });
263
600
  var httpSchema = z.object({
264
601
  adapter: z.enum(["fastify", "hono"]).default("fastify"),
265
602
  port: z.number().int().positive().default(3001),
266
603
  host: z.string().default("0.0.0.0"),
267
- /** Whether `X-Forwarded-For` sets the client IP the rate limiter keys on; only behind a proxy you run. */
268
- trustProxy: z.boolean().default(false),
604
+ /**
605
+ * The proxies in front whose `X-Forwarded-For` sets the client address the rate limiter keys on: `loopback`,
606
+ * `linklocal`, `uniquelocal`, an IP address or a CIDR. Unset, `loopback`; NYMBAL_TRUSTED_PROXIES replaces it.
607
+ */
608
+ trustedProxies: z.array(
609
+ z.string().superRefine((entry, ctx) => {
610
+ const problem = trustedProxyProblem(entry);
611
+ if (problem !== null) {
612
+ ctx.addIssue({
613
+ code: z.ZodIssueCode.custom,
614
+ message: trustedProxyMessage(entry, "http.trustedProxies", problem)
615
+ });
616
+ }
617
+ })
618
+ ).optional(),
619
+ /**
620
+ * One header a listed proxy sets to the client's address (`True-Client-IP`, `CF-Connecting-IP`), read in place of
621
+ * `X-Forwarded-For` and only from a listed proxy. NYMBAL_CLIENT_IP_HEADER replaces it.
622
+ */
623
+ clientIpHeader: z.string().superRefine((name, ctx) => {
624
+ const problem = clientIpHeaderProblem(name);
625
+ if (problem !== null)
626
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `'${name}' ${problem}` });
627
+ }).optional(),
628
+ trustProxy: z.never({
629
+ error: "http.trustProxy was removed: list the proxies in front in http.trustedProxies (or NYMBAL_TRUSTED_PROXIES), such as ['loopback'] or ['uniquelocal']"
630
+ }).optional(),
269
631
  cors: z.object({
270
632
  allowedOrigins: z.array(z.string()).default(["http://localhost:3000", "http://localhost:4321"]),
271
633
  credentials: z.boolean().default(true)
272
- }).default({})
634
+ }).prefault({})
273
635
  });
274
636
  var deploymentSchema = z.object({
275
637
  strategy: z.enum(["standard", "blue-green"]).default("standard")
@@ -296,6 +658,75 @@ var eventsSchema = z.object({
296
658
  retentionDays: z.number().int().min(1).default(30),
297
659
  archive: eventArchiveSchema.optional()
298
660
  }).strict();
661
+ var MCP_WRITES = ["proposal", "apply"];
662
+ var DEFAULT_AGENT_CRAWLERS = Object.freeze([
663
+ "GPTBot",
664
+ "OAI-SearchBot",
665
+ "ChatGPT-User",
666
+ "ClaudeBot",
667
+ "Claude-User",
668
+ "Claude-SearchBot",
669
+ "PerplexityBot",
670
+ "Perplexity-User",
671
+ "Google-Extended",
672
+ "Applebot-Extended"
673
+ ]);
674
+ var CRAWL_OTHERS = ["allow", "disallow"];
675
+ var ACP_LINK_TYPES = [
676
+ "terms_of_use",
677
+ "privacy_policy",
678
+ "return_policy",
679
+ "shipping_policy",
680
+ "contact_us",
681
+ "about_us",
682
+ "faq",
683
+ "support"
684
+ ];
685
+ var ACP_KEY_MIN_LENGTH = 32;
686
+ var agentsSchema = z.object({
687
+ mcp: z.object({
688
+ enabled: z.boolean().default(true),
689
+ writes: z.enum(MCP_WRITES, {
690
+ error: (issue) => issue.code === "invalid_value" ? `must be 'proposal' or 'apply', not ${JSON.stringify(issue.input)}` : void 0
691
+ }).default("proposal")
692
+ }).strict().prefault({}),
693
+ autoApprove: z.array(z.string().min(1)).default([]),
694
+ ucp: z.object({
695
+ enabled: z.boolean().default(true),
696
+ links: z.array(
697
+ z.object({
698
+ type: z.string().min(1),
699
+ url: z.string().url(),
700
+ title: z.string().optional()
701
+ }).strict()
702
+ ).default([])
703
+ }).strict().prefault({}),
704
+ acp: z.object({
705
+ enabled: z.boolean().default(false),
706
+ apiKey: z.string().min(ACP_KEY_MIN_LENGTH, { error: `must be at least ${ACP_KEY_MIN_LENGTH} characters` }).optional(),
707
+ links: z.array(
708
+ z.object({
709
+ type: z.enum(ACP_LINK_TYPES),
710
+ url: z.string().url(),
711
+ title: z.string().optional()
712
+ }).strict()
713
+ ).default([]),
714
+ merchantId: z.string().min(1).optional()
715
+ }).strict().prefault({}),
716
+ crawl: z.object({
717
+ robots: z.boolean().default(true),
718
+ llms: z.boolean().default(true),
719
+ feed: z.boolean().default(true),
720
+ allow: z.array(z.string().min(1)).default(() => [...DEFAULT_AGENT_CRAWLERS]),
721
+ others: z.enum(CRAWL_OTHERS, {
722
+ error: (issue) => issue.code === "invalid_value" ? `must be 'allow' or 'disallow', not ${JSON.stringify(issue.input)}` : void 0
723
+ }).default("allow")
724
+ }).strict().prefault({}),
725
+ assistant: z.object({
726
+ /** false keeps every tool that answers a customer's email, phone or address off the admin's assistant. */
727
+ customerData: z.boolean().default(true)
728
+ }).strict().prefault({})
729
+ }).strict();
299
730
  var nymbalConfigSchema = z.object({
300
731
  store: storeSchema,
301
732
  template: z.enum(["astro", "nextjs"]),
@@ -309,10 +740,11 @@ var nymbalConfigSchema = z.object({
309
740
  heartbeat: false,
310
741
  autoUpdates: false
311
742
  }),
312
- events: eventsSchema.default({})
743
+ events: eventsSchema.prefault({}),
744
+ agents: agentsSchema.prefault({})
313
745
  }).superRefine((cfg, ctx) => {
314
746
  const archiveBucket = cfg.events.archive?.bucket;
315
- if (archiveBucket !== void 0 && cfg.infrastructure.media === "s3" && archiveBucket === cfg.infrastructure.s3?.bucket) {
747
+ if (archiveBucket !== void 0 && cfg.infrastructure.media.provider === "s3" && archiveBucket === cfg.infrastructure.s3?.bucket) {
316
748
  ctx.addIssue({
317
749
  code: z.ZodIssueCode.custom,
318
750
  path: ["events", "archive", "bucket"],
@@ -324,7 +756,7 @@ var nymbalConfigSchema = z.object({
324
756
  ctx.addIssue({
325
757
  code: z.ZodIssueCode.custom,
326
758
  path: ["commerce", "email", "config", "transport"],
327
- message: `the native email provider only prints to the console; for SMTP mail set email.provider to 'smtp' (@nymbalhq/adapter-smtp)`
759
+ message: `the native email provider only prints to the console; for SMTP mail set email.provider to 'smtp' (@nymbalhq/email-smtp)`
328
760
  });
329
761
  }
330
762
  });
@@ -344,7 +776,7 @@ function findConfigFile(startDir) {
344
776
  async function loadConfig(startDir = process.cwd()) {
345
777
  const path = findConfigFile(startDir);
346
778
  if (!path) {
347
- throw new ConfigError2(
779
+ throw new ConfigError3(
348
780
  `Could not find ${CONFIG_FILE} in ${startDir} or any parent directory.`,
349
781
  { context: { startDir } }
350
782
  );
@@ -354,7 +786,7 @@ async function loadConfig(startDir = process.cwd()) {
354
786
  try {
355
787
  mod = await jiti.import(path);
356
788
  } catch (err) {
357
- throw new ConfigError2(`Failed to load ${path}: ${err.message}`, {
789
+ throw new ConfigError3(`Failed to load ${path}: ${err.message}`, {
358
790
  cause: err,
359
791
  context: { path }
360
792
  });
@@ -366,7 +798,7 @@ async function loadConfig(startDir = process.cwd()) {
366
798
  return { config, path, projectRoot: dirname(path), ...adapters !== void 0 && { adapters } };
367
799
  } catch (err) {
368
800
  if (err instanceof z2.ZodError) {
369
- throw new ConfigError2(formatZodError(err, path), {
801
+ throw new ConfigError3(formatZodError(err, path), {
370
802
  cause: err,
371
803
  context: { path, issues: err.issues }
372
804
  });
@@ -377,7 +809,7 @@ async function loadConfig(startDir = process.cwd()) {
377
809
  function adaptersExport(value, path) {
378
810
  if (value === void 0) return void 0;
379
811
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
380
- throw new ConfigError2(`${path}: the adapters export must be an object keyed by commerce slot`, {
812
+ throw new ConfigError3(`${path}: the adapters export must be an object keyed by commerce slot`, {
381
813
  code: "config.adapters_invalid",
382
814
  context: { path }
383
815
  });
@@ -385,7 +817,7 @@ function adaptersExport(value, path) {
385
817
  const slots = Object.keys(KNOWN_PROVIDERS);
386
818
  const unknown = Object.keys(value).filter((key) => !slots.includes(key));
387
819
  if (unknown.length > 0) {
388
- throw new ConfigError2(
820
+ throw new ConfigError3(
389
821
  `${path}: the adapters export names ${unknown.join(", ")}, which is no commerce slot (${slots.join(", ")})`,
390
822
  { code: "config.adapters_invalid", context: { path, unknown } }
391
823
  );
@@ -400,12 +832,51 @@ function formatZodError(err, path) {
400
832
  return `Invalid configuration in ${path}:
401
833
  ${lines.join("\n")}`;
402
834
  }
835
+
836
+ // src/secure-cookies.ts
837
+ var PUBLIC_URL_ENV = "NYMBAL_PUBLIC_URL";
838
+ function secureCookies(config, env2) {
839
+ const fromEnv2 = env2[PUBLIC_URL_ENV]?.trim();
840
+ const origin = fromEnv2 !== void 0 && fromEnv2 !== "" ? fromEnv2 : config.store.url;
841
+ if (origin === void 0) return env2["NODE_ENV"] === "production";
842
+ return /^https:/i.test(origin);
843
+ }
844
+
845
+ // src/origin-lock.ts
846
+ import { ConfigError as ConfigError4 } from "@nymbalhq/types";
847
+ var ORIGIN_SECRET_ENV = "NYMBAL_ORIGIN_SECRET";
848
+ var ENTRY = /^[A-Za-z0-9+/=_.~-]{32,256}$/;
849
+ function resolveOriginLock(config, env2) {
850
+ const secrets = (env2[ORIGIN_SECRET_ENV] ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
851
+ if (secrets.length === 0) return void 0;
852
+ const invalid = secrets.findIndex((entry) => !ENTRY.test(entry));
853
+ if (invalid >= 0) {
854
+ const position = invalid + 1;
855
+ throw new ConfigError4(
856
+ `${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)`,
857
+ { code: "config.origin_secret_invalid", context: { variable: ORIGIN_SECRET_ENV, position } }
858
+ );
859
+ }
860
+ return { header: config.security.originLock.header, secrets };
861
+ }
403
862
  export {
863
+ ACP_KEY_MIN_LENGTH,
864
+ ACP_LINK_TYPES,
865
+ ADAPTER_CATALOGUE,
866
+ BUILT_IN,
867
+ CLIENT_IP_HEADER_ENV,
868
+ COMMAND_STORES,
869
+ DEFAULT_AGENT_CRAWLERS,
404
870
  DEFAULT_JWT_SECRET,
405
- KNOWN_INFRASTRUCTURE,
406
871
  KNOWN_PROVIDERS,
872
+ ORIGIN_SECRET_ENV,
873
+ PROVIDER_NAME,
874
+ PUBLIC_URL_ENV,
407
875
  REMOVED_INFRASTRUCTURE_KEYS,
876
+ TRUSTED_PROXIES_ENV,
877
+ agentsSchema,
408
878
  commerceSchema,
879
+ conventionPackage,
409
880
  defineConfig,
410
881
  deploymentSchema,
411
882
  env,
@@ -421,8 +892,15 @@ export {
421
892
  loadConfig,
422
893
  nymbalConfigSchema,
423
894
  redisSchema,
895
+ resolveOriginLock,
896
+ resolveTrustedProxies,
424
897
  s3Schema,
898
+ secureCookies,
425
899
  securitySchema,
426
- storeSchema
900
+ slotFolder,
901
+ storeSchema,
902
+ suggestProvider,
903
+ trustSuggestion,
904
+ trustedProxyProblem
427
905
  };
428
906
  //# sourceMappingURL=index.js.map