@tokenoftrust/cli 8.0.0 → 8.0.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "8.0.0",
3
+ "version": "8.0.1",
4
4
  "description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Token of Trust",
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Eligibility-config validation for `tot validate`: the tenant's `compliance` restriction block
3
+ * against the platform's rules-engine contract (ADR 0047).
4
+ *
5
+ * - `compliance.ruleProfile` names a shipped rule pack.
6
+ * - `compliance.stateEligibility` footprints are lists of 2-letter state codes, nothing else.
7
+ * - Tenant overrides are stricter-only: a key that would allow a rule-pack-prohibited destination,
8
+ * disable a rule, or raise a unit cap is refused, because the engine ignores it and the merchant
9
+ * would believe it took effect.
10
+ *
11
+ * Pure and dependency-free. Findings are plain `{ level, rule, file, message, fix }` objects; every
12
+ * one is an error, so `tot validate` exits non-zero.
13
+ */
14
+
15
+ /** Rule packs the platform ships (apps/storefront/src/config/compliance/rulesets.ts). */
16
+ export const KNOWN_RULE_PROFILES = Object.freeze(["vape-nicotine-us", "vape-nicotine-us-ovs"]);
17
+
18
+ /** Keys the engine never honors: each one relaxes the rule pack. */
19
+ export const PERMISSIVE_OVERRIDE_KEYS = Object.freeze(["allowRegions", "allowRules", "relaxedUnitLimit"]);
20
+
21
+ const STATE_ELIGIBILITY_KEYS = new Set(["restrictedStates", "eligibleStates", "directoryStates", "note"]);
22
+ const STATE_LIST_KEYS = ["restrictedStates", "eligibleStates", "directoryStates"];
23
+ const STATE_CODE = /^[A-Z]{2}$/;
24
+
25
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
26
+
27
+ /**
28
+ * @param {Record<string, any>} config the parsed `.tot/config.json`
29
+ * @param {string} [file]
30
+ * @returns {Array<{level: "error", rule: string, file: string, message: string, fix?: string}>}
31
+ */
32
+ export function eligibilityConfigFindings(config, file = ".tot/config.json") {
33
+ const compliance = config?.compliance;
34
+ if (compliance === undefined || !isObject(compliance)) return [];
35
+ const out = [];
36
+ const err = (rule, at, message, fix) => out.push({ level: "error", rule, file: `${file} ${at}`, message, fix });
37
+
38
+ if (compliance.ruleProfile !== undefined && !KNOWN_RULE_PROFILES.includes(compliance.ruleProfile)) {
39
+ err(
40
+ "compliance-rule-profile-unknown",
41
+ "compliance.ruleProfile",
42
+ `\`compliance.ruleProfile\` is ${JSON.stringify(compliance.ruleProfile)}, which is not a shipped rule pack — no checkout rules resolve and checkout blocks.`,
43
+ `Use one of: ${KNOWN_RULE_PROFILES.map((p) => `"${p}"`).join(", ")}.`,
44
+ );
45
+ }
46
+
47
+ for (const key of PERMISSIVE_OVERRIDE_KEYS) {
48
+ if (key in compliance) refusePermissive(err, key, "compliance");
49
+ }
50
+
51
+ const elig = compliance.stateEligibility;
52
+ if (elig === undefined || typeof elig === "boolean") return out;
53
+ if (!isObject(elig)) {
54
+ err("compliance-state-eligibility-shape", "compliance.stateEligibility", "`compliance.stateEligibility` must be an object.",
55
+ "Use { restrictedStates?: [...], eligibleStates?: [...], directoryStates?: [...], note?: string }.");
56
+ return out;
57
+ }
58
+ for (const key of Object.keys(elig)) {
59
+ if (PERMISSIVE_OVERRIDE_KEYS.includes(key)) refusePermissive(err, key, "compliance.stateEligibility");
60
+ else if (!STATE_ELIGIBILITY_KEYS.has(key)) {
61
+ err("compliance-state-eligibility-unknown-key", `compliance.stateEligibility.${key}`,
62
+ `\`compliance.stateEligibility.${key}\` is not a recognised key, so it is ignored.`,
63
+ `Use only ${[...STATE_ELIGIBILITY_KEYS].map((k) => `\`${k}\``).join(", ")}.`);
64
+ }
65
+ }
66
+ for (const key of STATE_LIST_KEYS) {
67
+ const list = elig[key];
68
+ if (list === undefined) continue;
69
+ const at = `compliance.stateEligibility.${key}`;
70
+ if (!Array.isArray(list)) {
71
+ err("compliance-state-code", at, `\`${at}\` must be an array of 2-letter state codes.`, 'e.g. ["UT", "CA"].');
72
+ continue;
73
+ }
74
+ for (const [i, code] of list.entries()) {
75
+ if (typeof code !== "string" || !STATE_CODE.test(code)) {
76
+ err("compliance-state-code", `${at}[${i}]`,
77
+ `${JSON.stringify(code)} is not a 2-letter uppercase state code; the engine ignores it.`,
78
+ 'Use the USPS code, e.g. "UT".');
79
+ }
80
+ }
81
+ if (key === "eligibleStates" && list.length === 0) {
82
+ err("compliance-state-footprint-empty", at,
83
+ "`eligibleStates` is empty, which fails closed: no destination is licensed.",
84
+ "List the licensed states, or remove `eligibleStates`.");
85
+ }
86
+ }
87
+ return out;
88
+ }
89
+
90
+ function refusePermissive(err, key, parent) {
91
+ err(
92
+ "compliance-permissive-override",
93
+ `${parent}.${key}`,
94
+ `\`${parent}.${key}\` would loosen the rule pack (allow a prohibited destination, disable a rule, or raise a unit cap). Tenant overrides are stricter-only and the engine ignores it.`,
95
+ `Remove \`${key}\`. To narrow the footprint use \`restrictedStates\` or \`eligibleStates\`.`,
96
+ );
97
+ }
98
+
99
+ const FACT_STATES = new Set(["known", "unknown", "invalid", "conflict", "not_applicable"]);
100
+ const BOOLEAN_FACTS = new Set(["has_nicotine", "cooling_agent", "contains_lithium_battery", "child_resistant_packaging"]);
101
+ const NUMBER_FACTS = new Set(["unit_weight_grams", "liquid_volume_ml"]);
102
+ const STRING_FACTS = new Set([
103
+ "compliance_category", "flavor_classification", "fda_authorization", "nicotine_origin", "manufacturer_legal_name", "system_type",
104
+ ]);
105
+ const STRING_LIST_FACTS = new Set(["flavor_labels", "registry_listings"]);
106
+
107
+ /**
108
+ * Regulatory fact declarations on catalog products (`variants[].catalog_link.facts`, storefront-catalog
109
+ * v2.1.0): a known fact carries a value of its key's type, any other state carries none, and a key is
110
+ * declared once per variant. Errors, because checkout reads these as the primary eligibility truth.
111
+ * @param {Array<{ file: string, record: any }>} products
112
+ */
113
+ export function catalogFactFindings(products) {
114
+ const out = [];
115
+ for (const { file, record } of products) {
116
+ const variants = Array.isArray(record?.variants) ? record.variants : [];
117
+ variants.forEach((variant, vi) => {
118
+ const facts = variant?.catalog_link?.facts;
119
+ if (facts === undefined) return;
120
+ const at = `variants[${vi}].catalog_link.facts`;
121
+ const err = (rule, i, message, fix) => out.push({ level: "error", rule, file: `${file} ${at}[${i}]`, message, fix });
122
+ if (!Array.isArray(facts)) {
123
+ out.push({ level: "error", rule: "catalog-fact-shape", file: `${file} ${at}`, message: "`catalog_link.facts` must be an array.", fix: "Re-accept the catalog item to rewrite its facts." });
124
+ return;
125
+ }
126
+ const seen = new Set();
127
+ facts.forEach((fact, i) => {
128
+ if (!isObject(fact) || typeof fact.key !== "string" || !fact.key) {
129
+ err("catalog-fact-shape", i, "a fact must be an object with a string `key`.");
130
+ return;
131
+ }
132
+ if (seen.has(fact.key)) err("catalog-fact-duplicate", i, `fact \`${fact.key}\` is declared more than once; checkout cannot tell which is true.`, "Keep one entry per key.");
133
+ seen.add(fact.key);
134
+ if (!FACT_STATES.has(fact.state)) {
135
+ err("catalog-fact-state", i, `fact \`${fact.key}\` has state ${JSON.stringify(fact.state)}; it must be one of ${[...FACT_STATES].join(", ")}.`);
136
+ return;
137
+ }
138
+ if (fact.state !== "known") {
139
+ if (fact.value !== undefined) err("catalog-fact-value", i, `fact \`${fact.key}\` is ${fact.state} but carries a value; a value is never read from a fact that is not known.`, "Remove `value` or mark the fact known.");
140
+ return;
141
+ }
142
+ const v = fact.value;
143
+ const ok = BOOLEAN_FACTS.has(fact.key) ? typeof v === "boolean"
144
+ : NUMBER_FACTS.has(fact.key) ? typeof v === "number" && Number.isFinite(v)
145
+ : STRING_FACTS.has(fact.key) ? typeof v === "string" && v.trim().length > 0
146
+ : STRING_LIST_FACTS.has(fact.key) ? Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string")
147
+ : v !== undefined;
148
+ if (!ok) {
149
+ err("catalog-fact-value", i, `known fact \`${fact.key}\` has ${v === undefined ? "no value" : `an unusable value ${JSON.stringify(v)}`}; checkout reads it as invalid.`,
150
+ "Give it a value of the fact's type, or mark the fact unknown.");
151
+ }
152
+ });
153
+ });
154
+ }
155
+ return out;
156
+ }
package/src/validate.mjs CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  parseMappingTarget,
24
24
  workspacePathForTenantRelative,
25
25
  } from "./tot-repo-mappings.mjs";
26
+ import { catalogFactFindings, eligibilityConfigFindings } from "./eligibility-config.mjs";
26
27
  import { isForbiddenPublicPath, publicBinaryFindings } from "./public-binaries.mjs";
27
28
  import { createRedirectShadowCollector, shadowedRedirectMessage } from "./redirect-shadows.mjs";
28
29
  import { pageSlugFindings } from "./page-slugs.mjs";
@@ -114,7 +115,6 @@ export function catalogSkuFindings(products) {
114
115
  return out;
115
116
  }
116
117
 
117
- const GENERIC_PRODUCT_TYPES = new Set(["physical", "digital", "gift_certificate"]);
118
118
  const CATALOG_FLAVOR_FIELDS = new Set(["flavor", "flavour", "flavors", "flavours"]);
119
119
  const CATALOG_CATEGORY_FIELDS = new Set(["compliance category", "product category", "product_category"]);
120
120
  const CATALOG_NICOTINE_FORMAT_LABELS = new Set([
@@ -122,11 +122,6 @@ const CATALOG_NICOTINE_FORMAT_LABELS = new Set([
122
122
  "freebase", "free base", "freebase nicotine", "free base nicotine", "synthetic", "synthetic nicotine",
123
123
  "tfn", "tobacco free nicotine", "tobacco-free nicotine",
124
124
  ]);
125
- const CATALOG_NICOTINE_HINTS = [
126
- "nicotine", "vape", "vapor", "vaping", "e-liquid", "eliquid", "e-juice", "ejuice",
127
- "e liquid", "salt nic", "nic salt", "pod", "disposable", "ends", "cig",
128
- ];
129
- const CATALOG_ACCESSORY_HINTS = ["battery", "coil", "charger", "case", "lanyard"];
130
125
 
131
126
  function readCatalogMetafield(product, namespace, keys) {
132
127
  const mfs = Array.isArray(product?.metafields) ? product.metafields : [];
@@ -159,39 +154,39 @@ function collectCatalogFlavorLabels(product, variant) {
159
154
  return [...labels];
160
155
  }
161
156
 
157
+ const catalogFactOf = (variant, key) =>
158
+ (Array.isArray(variant?.catalog_link?.facts) ? variant.catalog_link.facts : []).find((f) => f?.key === key);
159
+
160
+ /** A catalog fact settles a field unless it is unknown; conflicting/invalid facts settle it restrictively. */
161
+ const factDecides = (fact) => fact !== undefined && fact.state !== "unknown";
162
+
163
+ /**
164
+ * The classification a product still lacks. The accepted catalog facts
165
+ * (`variants[].catalog_link.facts`) are the primary truth; merchant fields are the secondary
166
+ * declaration. Nothing is inferred from a title, tag or product type: a product whose category is
167
+ * not recorded is unclassified, and a nicotine-bearing one needs a flavour reading.
168
+ */
162
169
  function productClassificationGaps(product) {
163
170
  if (!product || typeof product !== "object") return [];
164
171
  const explicitCategory =
165
172
  readCatalogMetafield(product, "compliance", new Set(["product_category"])) ??
166
173
  readCatalogMetafield(product, "bigcommerce_custom", CATALOG_CATEGORY_FIELDS);
167
- const productType = typeof product.product_type === "string" ? product.product_type.trim().toLowerCase() : "";
168
- const merchantType = GENERIC_PRODUCT_TYPES.has(productType) ? "" : productType;
169
174
  const variants = Array.isArray(product.variants) && product.variants.length > 0 ? product.variants : [null];
170
175
  const gaps = new Set();
171
176
  for (const variant of variants) {
172
- const explicitFlavors = collectCatalogFlavorLabels(product, variant);
173
- const category = explicitCategory;
174
- const categoryClassified = Boolean(category) || merchantType.length > 0;
177
+ const categoryFact = catalogFactOf(variant, "compliance_category");
178
+ const category = categoryFact?.state === "known" && typeof categoryFact.value === "string" ? categoryFact.value : explicitCategory;
179
+ const categoryClassified = factDecides(categoryFact) || Boolean(category);
175
180
  if (!categoryClassified) gaps.add("category");
176
- const haystack = [
177
- merchantType,
178
- (category ?? "").toLowerCase(),
179
- typeof product.title === "string" ? product.title.toLowerCase() : "",
180
- ...(Array.isArray(product.tags) ? product.tags : []).map((t) => String(t ?? "").toLowerCase()),
181
- ].join(" ");
182
- const isAccessory =
183
- ((category ?? "").trim().toLowerCase() === "accessory" ||
184
- CATALOG_ACCESSORY_HINTS.some((n) => haystack.includes(n))) &&
185
- !["e-liquid", "eliquid", "juice", "salt"].some((n) => haystack.includes(n));
186
- const nicStrength = typeof variant?.option_values?.["Nicotine strength"] === "string"
187
- ? variant.option_values["Nicotine strength"].toLowerCase()
188
- : undefined;
189
- const nicOptionSaysZero = nicStrength !== undefined && /^0\s*mg\b/.test(nicStrength);
190
- const nicOptionSaysNonZero = nicStrength !== undefined && /\d/.test(nicStrength) && !nicOptionSaysZero;
191
- const containsNicotine =
192
- !isAccessory &&
193
- (nicOptionSaysNonZero || (!nicOptionSaysZero && CATALOG_NICOTINE_HINTS.some((n) => haystack.includes(n))));
194
- const flavorClassified = explicitFlavors.length > 0;
181
+ const nicotineFact = catalogFactOf(variant, "has_nicotine");
182
+ const hardware = ["accessory", "none"].includes((category ?? "").trim().toLowerCase());
183
+ const containsNicotine = nicotineFact?.state === "known" && nicotineFact.value === false ? false : !hardware;
184
+ const flavorFact = catalogFactOf(variant, "flavor_classification");
185
+ const labelsFact = catalogFactOf(variant, "flavor_labels");
186
+ const flavorClassified =
187
+ factDecides(flavorFact) ||
188
+ (labelsFact?.state === "known" && Array.isArray(labelsFact.value) && labelsFact.value.length > 0) ||
189
+ collectCatalogFlavorLabels(product, variant).length > 0;
195
190
  if ((containsNicotine || !categoryClassified) && !flavorClassified) gaps.add("flavor");
196
191
  }
197
192
  return ["category", "flavor"].filter((g) => gaps.has(g));
@@ -242,7 +237,7 @@ function validateCatalogSkus(contentDir, rel, config = null) {
242
237
  if (error) parseErrors.push(mk(ERROR, "catalog-parse", rel(path), `invalid JSON: ${error}`));
243
238
  else products.push({ file: rel(path), record: value });
244
239
  }
245
- return [...parseErrors, ...catalogSkuFindings(products), ...catalogComplianceFindings(products, config)];
240
+ return [...parseErrors, ...catalogSkuFindings(products), ...catalogFactFindings(products), ...catalogComplianceFindings(products, config)];
246
241
  }
247
242
 
248
243
  // --- canonical `.tot/config.json` shape (the #24/#25 regression guard) --------
@@ -264,6 +259,7 @@ export function validateConfigShape(config, file = ".tot/config.json") {
264
259
  out.push(mk(ERROR, "config-tenant", file, "`tenant` must be a non-empty string"));
265
260
  }
266
261
  out.push(...validateDeclaredConfig(config, file));
262
+ out.push(...eligibilityConfigFindings(config, file));
267
263
  if (!Array.isArray(config.mappings)) {
268
264
  out.push(mk(ERROR, "config-mappings", file, "`mappings` must be an array", "seed shape: [{workspace,repo,kind}]"));
269
265
  return out;