cartspec 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # `@shipcraftlabs/cartspec`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-dependency deterministic CLI & Node.js SDK to audit any Shopify or DTC storefront for **AI shopping agent readiness** (ChatGPT Shopping / `OAI-SearchBot`, Perplexity / `PerplexityBot`, Google Shopping / UCP, Shop MCP, and ClaudeBot).
4
+
5
+ - Live Web Auditor & 1-Click Shopify OAuth Sync: https://cartspec.vespori.com
6
+ - Live 52-Brand DTC Empirical Benchmark: https://cartspec.vespori.com/benchmark
7
+
8
+ ## Quick CLI Usage
9
+
10
+ ```bash
11
+ npx @shipcraftlabs/cartspec audit allbirds.com
12
+ npx @shipcraftlabs/cartspec audit tecovas.com --json
13
+ ```
14
+
15
+ ## What It Audits Deterministically
16
+
17
+ 1. **`robots.txt` AI Crawler Directives:** `OAI-SearchBot`, `GPTBot`, `PerplexityBot`, `Google-Extended`, `ClaudeBot`, `Anthropic-AI`, and wildcard rules.
18
+ 2. **Schema.org Policy & Offer Graph:** Extracts `Product`, `Offer`, `GTIN`/`SKU`, `MerchantReturnPolicy`, `OfferShippingDetails`, and `AggregateRating` from live HTML JSON-LD blocks.
19
+ 3. **Agent Discovery Endpoints:** Checks `/sitemap.xml`, `/llms.txt`, `/.well-known/ucp`, and `/.well-known/mcp`.
20
+ 4. **Live Shopify `/products.json` Telemetry:** Samples up to 25 SKUs for barcode/GTIN completeness, SKU codes, weights, descriptions, and exports a ready-to-import Shopify Metafields CSV + Liquid JSON-LD patch.
21
+
22
+ ## GitHub Action (`CartSpec Storefront Audit`)
23
+
24
+ Fail theme or Hydrogen CI builds before a merge accidentally blocks `OAI-SearchBot` or strips JSON-LD schema:
25
+
26
+ ```yaml
27
+ - uses: devansh2396/cartspec@v0.1.0
28
+ with:
29
+ store: yourstore.com
30
+ min_score: 70
31
+ ```
32
+
33
+ ## Programmatic SDK Usage
34
+
35
+ ```js
36
+ import { auditStorefront } from '@shipcraftlabs/cartspec';
37
+
38
+ const report = await auditStorefront('allbirds.com');
39
+ console.log(report.score, report.grade, report.prioritizedFixes);
40
+ ```
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { auditStorefront } from '../src/audit.mjs';
4
+
5
+ async function main() {
6
+ const { values, positionals } = parseArgs({
7
+ allowPositionals: true,
8
+ options: {
9
+ json: { type: 'boolean', default: false },
10
+ help: { type: 'boolean', short: 'h', default: false },
11
+ },
12
+ });
13
+
14
+ if (values.help || positionals.length === 0) {
15
+ console.log('Usage: cartspec audit <store-domain> [--json]');
16
+ process.exit(values.help ? 0 : 2);
17
+ }
18
+
19
+ const target = positionals[0] === 'audit' ? positionals[1] : positionals[0];
20
+ if (!target) {
21
+ console.error('Error: missing <store-domain>. Example: cartspec audit allbirds.com');
22
+ process.exit(2);
23
+ }
24
+
25
+ const report = await auditStorefront(target);
26
+ if (values.json) {
27
+ console.log(JSON.stringify(report, null, 2));
28
+ return;
29
+ }
30
+
31
+ console.log(`\nCartSpec Agentic Storefront Audit — ${report.domain} (${report.platform})`);
32
+ console.log(`Score: ${report.score}/100 (Grade ${report.grade}) · ${report.durationMs}ms\n`);
33
+ for (const b of report.breakdown) {
34
+ console.log(`- ${b.label}: ${b.score}/${b.max}`);
35
+ }
36
+ console.log('\nAI Shopping Crawlers:');
37
+ for (const bot of report.robots.bots) {
38
+ console.log(` • ${bot.agent}: ${bot.status.toUpperCase()} (${bot.rule})`);
39
+ }
40
+ if (report.catalog.isShopifyProductsJson) {
41
+ console.log(
42
+ `\nShopify Catalog Sample (${report.catalog.sampledProducts} SKUs): avg ${report.catalog.summary.averageAttributeScore}% complete · missing barcodes: ${report.catalog.summary.missingBarcode} · missing weight: ${report.catalog.summary.missingWeight}`,
43
+ );
44
+ }
45
+ console.log('\nTop Fixes:');
46
+ for (const fix of report.prioritizedFixes) {
47
+ console.log(` [${fix.severity.toUpperCase()}] ${fix.title}`);
48
+ }
49
+ }
50
+
51
+ main().catch((err) => {
52
+ console.error(`CartSpec error: ${err.message}`);
53
+ process.exit(1);
54
+ });
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "cartspec",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Agentic Storefront Protocol Auditor & Shopify Catalog Enrichment CLI/SDK for ChatGPT Shopping, Perplexity, Google AI Mode, and UCP/ACP readiness.",
5
+ "type": "module",
6
+ "main": "./src/index.mjs",
7
+ "bin": {
8
+ "cartspec": "./bin/cartspec.mjs"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "src/",
13
+ "README.md"
14
+ ],
15
+ "exports": {
16
+ ".": "./src/index.mjs"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test tests/auditor.test.mjs"
20
+ },
21
+ "keywords": [
22
+ "agentic-commerce",
23
+ "shopify",
24
+ "ucp",
25
+ "acp",
26
+ "json-ld",
27
+ "ecommerce-audit",
28
+ "ai-search"
29
+ ],
30
+ "author": "Devansh Agrawal <hello@vespori.com>",
31
+ "license": "MIT",
32
+ "engines": {
33
+ "node": ">=20.0.0"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/devansh2396/cartspec.git"
38
+ },
39
+ "homepage": "https://cartspec.vespori.com/"
40
+ }
package/src/audit.mjs ADDED
@@ -0,0 +1,173 @@
1
+ import {
2
+ analyzeShopifyCatalog,
3
+ buildLiquidSchemaPatch,
4
+ computeAgenticScore,
5
+ extractJsonLdSummary,
6
+ parseRobotsTxt,
7
+ } from './parsers.mjs';
8
+ import { normalizeStoreUrl, safeFetchText } from './ssrf.mjs';
9
+
10
+ function extractSampleProductUrls(homeHtml, productsJson, baseOrigin) {
11
+ const urls = [];
12
+ const products = Array.isArray(productsJson?.products) ? productsJson.products : [];
13
+ for (const p of products.slice(0, 2)) {
14
+ if (p?.handle) urls.push(`${baseOrigin}/products/${p.handle}`);
15
+ }
16
+ if (urls.length < 2) {
17
+ const linkMatches = [...String(homeHtml || '').matchAll(/href=["']([^"']*\/products\/[^"'?#]+)["']/gi)];
18
+ for (const m of linkMatches) {
19
+ try {
20
+ const resolved = new URL(m[1], baseOrigin).toString();
21
+ if (!urls.includes(resolved)) urls.push(resolved);
22
+ if (urls.length >= 2) break;
23
+ } catch {
24
+ // skip invalid url
25
+ }
26
+ }
27
+ }
28
+ return urls.slice(0, 2);
29
+ }
30
+
31
+ /**
32
+ * Audit a live e-commerce storefront for AI shopping agent readiness across 6 protocol layers.
33
+ */
34
+ export async function auditStorefront(rawStoreUrl) {
35
+ const originUrl = normalizeStoreUrl(rawStoreUrl);
36
+ const origin = originUrl.origin;
37
+ const domain = originUrl.hostname;
38
+ const startedAt = Date.now();
39
+
40
+ const [homeRes, robotsRes, productsRes, sitemapRes, llmsRes, ucpRes, mcpRes] = await Promise.all([
41
+ safeFetchText(origin, { accept: 'text/html' }).catch((e) => ({ ok: false, status: 0, text: '', error: e.message })),
42
+ safeFetchText(`${origin}/robots.txt`, { accept: 'text/plain' }).catch(() => ({ ok: false, status: 0, text: '' })),
43
+ safeFetchText(`${origin}/products.json?limit=25`, { accept: 'application/json' }).catch(() => ({
44
+ ok: false,
45
+ status: 0,
46
+ text: '',
47
+ })),
48
+ safeFetchText(`${origin}/sitemap.xml`, { accept: 'application/xml,text/xml' }).catch(() => ({
49
+ ok: false,
50
+ status: 0,
51
+ text: '',
52
+ })),
53
+ safeFetchText(`${origin}/llms.txt`, { accept: 'text/plain' }).catch(() => ({ ok: false, status: 0, text: '' })),
54
+ safeFetchText(`${origin}/.well-known/ucp`, { accept: 'application/json' }).catch(() => ({
55
+ ok: false,
56
+ status: 0,
57
+ text: '',
58
+ })),
59
+ safeFetchText(`${origin}/.well-known/mcp.json`, { accept: 'application/json' }).catch(() => ({
60
+ ok: false,
61
+ status: 0,
62
+ text: '',
63
+ })),
64
+ ]);
65
+
66
+ if (!homeRes.ok && homeRes.status === 0) {
67
+ throw new Error(`Unable to reach "${origin}": ${homeRes.error || 'network timeout or TLS failure'}`);
68
+ }
69
+
70
+ let parsedProductsJson = null;
71
+ if (productsRes.ok && productsRes.text) {
72
+ try {
73
+ parsedProductsJson = JSON.parse(productsRes.text);
74
+ } catch {
75
+ parsedProductsJson = null;
76
+ }
77
+ }
78
+
79
+ const productUrls = extractSampleProductUrls(homeRes.text, parsedProductsJson, origin);
80
+ const productPages = await Promise.all(
81
+ productUrls.map((u) => safeFetchText(u, { accept: 'text/html' }).catch(() => ({ ok: false, status: 0, text: '' }))),
82
+ );
83
+
84
+ const combinedHtmlForJsonLd = [homeRes.text, ...productPages.map((p) => p.text)].join('\n');
85
+ const robots = parseRobotsTxt(robotsRes.ok ? robotsRes.text : '');
86
+ const jsonLd = extractJsonLdSummary(combinedHtmlForJsonLd);
87
+ const catalog = analyzeShopifyCatalog(parsedProductsJson, domain);
88
+
89
+ const lowerHome = String(homeRes.text || '').toLowerCase();
90
+ const isShopify =
91
+ catalog.isShopifyProductsJson ||
92
+ lowerHome.includes('cdn.shopify.com') ||
93
+ lowerHome.includes('shopify.theme');
94
+
95
+ const htmlSignals = {
96
+ isShopify,
97
+ hasCanonical: /<link[^>]*rel=["']canonical["']/i.test(homeRes.text || ''),
98
+ hasMetaDescription: /<meta[^>]*name=["']description["']/i.test(homeRes.text || ''),
99
+ hasPolicyLinks: /return|refund|shipping/i.test(lowerHome),
100
+ sampleProductUrlsAudited: productUrls,
101
+ };
102
+
103
+ const discovery = {
104
+ sitemapPresent: sitemapRes.ok && sitemapRes.text.includes('<'),
105
+ llmsTxtPresent: llmsRes.ok && llmsRes.text.trim().length > 10,
106
+ ucpPresent: ucpRes.ok && ucpRes.text.trim().startsWith('{'),
107
+ mcpPresent: mcpRes.ok && mcpRes.text.trim().startsWith('{'),
108
+ };
109
+
110
+ const scoring = computeAgenticScore({ robots, jsonLd, catalog, discovery, htmlSignals });
111
+
112
+ const prioritizedFixes = [];
113
+ if (robots.blockedCount > 0) {
114
+ prioritizedFixes.push({
115
+ severity: 'critical',
116
+ title: `Unblock ${robots.blockedCount} AI Shopping Crawler(s) in robots.txt`,
117
+ detail: `AI buyers using ${robots.bots
118
+ .filter((b) => b.status === 'blocked')
119
+ .map((b) => b.agent)
120
+ .join(', ')} are explicitly blocked from indexing your catalog.`,
121
+ });
122
+ }
123
+ if (!jsonLd.hasReturnPolicy || !jsonLd.hasShippingDetails) {
124
+ prioritizedFixes.push({
125
+ severity: 'high',
126
+ title: 'Add MerchantReturnPolicy & OfferShippingDetails JSON-LD',
127
+ detail:
128
+ 'Shopping agents filter strictly on delivery windows and return windows before recommending products. Copy the generated Liquid JSON-LD patch below into your product template.',
129
+ });
130
+ }
131
+ if (catalog.isShopifyProductsJson && catalog.summary.missingBarcode > 0) {
132
+ prioritizedFixes.push({
133
+ severity: 'high',
134
+ title: `Fill Missing GTIN/Barcodes on ${catalog.summary.missingBarcode} of ${catalog.sampledProducts} Sampled Products`,
135
+ detail:
136
+ 'Without GTIN/UPC identifiers, agents cannot match your SKU cleanly against cross-store catalog reviews and price checks.',
137
+ });
138
+ }
139
+ if (catalog.isShopifyProductsJson && (catalog.summary.missingType > 0 || catalog.summary.averageAttributeScore < 75)) {
140
+ prioritizedFixes.push({
141
+ severity: 'medium',
142
+ title: `Enrich Structured Material, Use-Case & Category Fields (Avg ${catalog.summary.averageAttributeScore}% Complete)`,
143
+ detail:
144
+ 'Download the generated Shopify Metafield Import CSV below to backfill missing category, material, and agentic summary fields cleanly.',
145
+ });
146
+ }
147
+ if (!discovery.ucpPresent && !discovery.llmsTxtPresent) {
148
+ prioritizedFixes.push({
149
+ severity: 'medium',
150
+ title: 'Publish Agentic Discovery Signals (/llms.txt & /.well-known/ucp)',
151
+ detail:
152
+ 'Expose structured store policy, best-seller handles, and shipping rules in /llms.txt and UCP endpoints so agents cite exact policies cleanly.',
153
+ });
154
+ }
155
+
156
+ return {
157
+ domain,
158
+ origin,
159
+ auditedAt: new Date().toISOString(),
160
+ durationMs: Date.now() - startedAt,
161
+ platform: isShopify ? 'Shopify' : 'Custom / Non-Shopify',
162
+ score: scoring.totalScore,
163
+ grade: scoring.grade,
164
+ breakdown: scoring.breakdown,
165
+ robots,
166
+ jsonLd,
167
+ catalog,
168
+ discovery,
169
+ htmlSignals,
170
+ prioritizedFixes,
171
+ liquidSchemaPatch: buildLiquidSchemaPatch(),
172
+ };
173
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,12 @@
1
+ export { auditStorefront } from './audit.mjs';
2
+ export {
3
+ AI_SHOPPING_BOTS,
4
+ analyzeShopifyCatalog,
5
+ buildLiquidSchemaPatch,
6
+ buildShopifyMetafieldCsv,
7
+ computeAgenticScore,
8
+ extractJsonLdSummary,
9
+ parseRobotsTxt,
10
+ stripHtml,
11
+ } from './parsers.mjs';
12
+ export { assertPublicHostname, isPrivateOrReservedIp, normalizeStoreUrl, safeFetchText } from './ssrf.mjs';
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Pure deterministic parsers for AI shopping bots (robots.txt), Schema.org JSON-LD,
3
+ * Shopify live /products.json catalogs, and 0-100 Agentic Storefront Readiness scoring.
4
+ */
5
+
6
+ export const AI_SHOPPING_BOTS = [
7
+ { agent: 'OAI-SearchBot', role: 'OpenAI ChatGPT Shopping & Search index' },
8
+ { agent: 'ChatGPT-User', role: 'OpenAI live user browsing & product fetch' },
9
+ { agent: 'GPTBot', role: 'OpenAI web corpus & model discovery' },
10
+ { agent: 'PerplexityBot', role: 'Perplexity Shopping & answer engine index' },
11
+ { agent: 'ClaudeBot', role: 'Anthropic web search & commerce retrieval' },
12
+ { agent: 'Google-Extended', role: 'Google Gemini / AI Mode product grounding' },
13
+ { agent: 'Applebot-Extended', role: 'Apple Intelligence discovery' },
14
+ ];
15
+
16
+ const MATERIAL_KEYWORDS = [
17
+ 'merino', 'wool', 'cotton', 'organic cotton', 'linen', 'bamboo', 'eucalyptus',
18
+ 'leather', 'suede', 'canvas', 'nylon', 'polyester', 'recycled polyester',
19
+ 'silicone', 'stainless steel', 'titanium', 'aluminum', 'ceramic', 'glass', 'oak',
20
+ ];
21
+
22
+ const USE_CASE_KEYWORDS = [
23
+ 'running', 'walking', 'travel', 'gym', 'training', 'hiking', 'office', 'everyday',
24
+ 'sleep', 'sensitive skin', 'waterproof', 'breathable', 'insulated', 'dishwasher safe',
25
+ ];
26
+
27
+ /**
28
+ * Strip HTML tags into clean single-spaced plain text.
29
+ */
30
+ export function stripHtml(html) {
31
+ return String(html || '')
32
+ .replace(/<script[\s\S]*?<\/script>/gi, ' ')
33
+ .replace(/<style[\s\S]*?<\/style>/gi, ' ')
34
+ .replace(/<[^>]+>/g, ' ')
35
+ .replace(/&nbsp;/gi, ' ')
36
+ .replace(/&amp;/gi, '&')
37
+ .replace(/\s+/g, ' ')
38
+ .trim();
39
+ }
40
+
41
+ /**
42
+ * Evaluate robots.txt rules accurately for each AI shopping bot.
43
+ */
44
+ export function parseRobotsTxt(raw) {
45
+ const lines = String(raw || '').split(/\r?\n/);
46
+ const groups = [];
47
+ let current = null;
48
+
49
+ for (const rawLine of lines) {
50
+ const line = rawLine.replace(/#.*$/, '').trim();
51
+ if (!line) continue;
52
+ const colon = line.indexOf(':');
53
+ if (colon <= 0) continue;
54
+ const key = line.slice(0, colon).trim().toLowerCase();
55
+ const value = line.slice(colon + 1).trim();
56
+
57
+ if (key === 'user-agent') {
58
+ if (!current || current.rules.length > 0) {
59
+ current = { agents: [], rules: [] };
60
+ groups.push(current);
61
+ }
62
+ current.agents.push(value.toLowerCase());
63
+ } else if ((key === 'disallow' || key === 'allow') && current) {
64
+ current.rules.push({ type: key, path: value });
65
+ }
66
+ }
67
+
68
+ function evaluateAgent(agentName) {
69
+ const target = agentName.toLowerCase();
70
+ const specificGroups = groups.filter((g) => g.agents.includes(target));
71
+ const activeGroups = specificGroups.length > 0 ? specificGroups : groups.filter((g) => g.agents.includes('*'));
72
+
73
+ if (activeGroups.length === 0) {
74
+ return { agent: agentName, status: 'allowed', rule: 'no matching restriction', matchedScope: 'default' };
75
+ }
76
+
77
+ const matchedRules = activeGroups.flatMap((g) => g.rules);
78
+ const rootDisallow = matchedRules.some((r) => r.type === 'disallow' && r.path === '/');
79
+ const rootAllow = matchedRules.some((r) => r.type === 'allow' && r.path === '/');
80
+ const productsDisallow = matchedRules.some(
81
+ (r) => r.type === 'disallow' && (r.path === '/products' || r.path === '/products/' || r.path === '/products*'),
82
+ );
83
+
84
+ if (rootDisallow && !rootAllow) {
85
+ return {
86
+ agent: agentName,
87
+ status: 'blocked',
88
+ rule: 'Disallow: /',
89
+ matchedScope: specificGroups.length > 0 ? agentName : '*',
90
+ };
91
+ }
92
+ if (productsDisallow) {
93
+ return {
94
+ agent: agentName,
95
+ status: 'restricted',
96
+ rule: 'Disallow: /products',
97
+ matchedScope: specificGroups.length > 0 ? agentName : '*',
98
+ };
99
+ }
100
+ return {
101
+ agent: agentName,
102
+ status: 'allowed',
103
+ rule: specificGroups.length > 0 ? 'explicitly permitted' : 'inherits * allow',
104
+ matchedScope: specificGroups.length > 0 ? agentName : '*',
105
+ };
106
+ }
107
+
108
+ const bots = AI_SHOPPING_BOTS.map((b) => ({
109
+ ...b,
110
+ ...evaluateAgent(b.agent),
111
+ }));
112
+
113
+ const blockedCount = bots.filter((b) => b.status === 'blocked').length;
114
+ const restrictedCount = bots.filter((b) => b.status === 'restricted').length;
115
+ const allowedCount = bots.filter((b) => b.status === 'allowed').length;
116
+
117
+ return {
118
+ present: String(raw || '').trim().length > 0,
119
+ allowedCount,
120
+ restrictedCount,
121
+ blockedCount,
122
+ bots,
123
+ };
124
+ }
125
+
126
+ function flattenJsonLdNodes(input, out = []) {
127
+ if (!input) return out;
128
+ if (Array.isArray(input)) {
129
+ for (const item of input) flattenJsonLdNodes(item, out);
130
+ return out;
131
+ }
132
+ if (typeof input === 'object') {
133
+ out.push(input);
134
+ if (Array.isArray(input['@graph'])) flattenJsonLdNodes(input['@graph'], out);
135
+ }
136
+ return out;
137
+ }
138
+
139
+ function normalizeTypes(node) {
140
+ const raw = node?.['@type'];
141
+ if (!raw) return [];
142
+ return (Array.isArray(raw) ? raw : [raw]).map((t) => String(t).split('/').pop());
143
+ }
144
+
145
+ /**
146
+ * Extract all valid JSON-LD blocks from HTML and summarize Schema.org agentic commerce coverage.
147
+ */
148
+ export function extractJsonLdSummary(html) {
149
+ const regex = /<script[^>]*type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi;
150
+ const nodes = [];
151
+ let parseErrors = 0;
152
+
153
+ let match;
154
+ while ((match = regex.exec(String(html || ''))) !== null) {
155
+ const rawJson = match[1].trim();
156
+ if (!rawJson) continue;
157
+ try {
158
+ const parsed = JSON.parse(rawJson);
159
+ flattenJsonLdNodes(parsed, nodes);
160
+ } catch {
161
+ parseErrors += 1;
162
+ }
163
+ }
164
+
165
+ const productNodes = nodes.filter((n) => {
166
+ const types = normalizeTypes(n);
167
+ return types.includes('Product') || types.includes('ProductGroup');
168
+ });
169
+
170
+ const orgNodes = nodes.filter((n) => {
171
+ const types = normalizeTypes(n);
172
+ return types.includes('Organization') || types.includes('Store') || types.includes('OnlineStore');
173
+ });
174
+
175
+ const hasReturnPolicy = nodes.some(
176
+ (n) => normalizeTypes(n).includes('MerchantReturnPolicy') || JSON.stringify(n).includes('hasMerchantReturnPolicy'),
177
+ );
178
+ const hasShippingDetails = nodes.some(
179
+ (n) => normalizeTypes(n).includes('OfferShippingDetails') || JSON.stringify(n).includes('shippingDetails'),
180
+ );
181
+ const hasOfferPrice = productNodes.some((p) => {
182
+ const offers = Array.isArray(p.offers) ? p.offers : [p.offers].filter(Boolean);
183
+ return offers.some((o) => o && (o.price !== undefined || o.lowPrice !== undefined));
184
+ });
185
+ const hasGtinOrSku = productNodes.some(
186
+ (p) => Boolean(p.gtin || p.gtin13 || p.gtin12 || p.gtin8 || p.mpn || p.sku),
187
+ );
188
+ const hasAggregateRating = productNodes.some((p) => Boolean(p.aggregateRating)) ||
189
+ nodes.some((n) => normalizeTypes(n).includes('AggregateRating'));
190
+
191
+ return {
192
+ totalBlocks: nodes.length,
193
+ parseErrors,
194
+ productCount: productNodes.length,
195
+ organizationCount: orgNodes.length,
196
+ hasOfferPrice,
197
+ hasGtinOrSku,
198
+ hasReturnPolicy,
199
+ hasShippingDetails,
200
+ hasAggregateRating,
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Extract deterministic catalog attribute gaps from Shopify /products.json payload and build Metafield CSV.
206
+ */
207
+ export function analyzeShopifyCatalog(productsPayload, storeDomain = 'store.com') {
208
+ const products = Array.isArray(productsPayload?.products) ? productsPayload.products : [];
209
+ if (products.length === 0) {
210
+ return {
211
+ isShopifyProductsJson: false,
212
+ sampledProducts: 0,
213
+ summary: {
214
+ thinDescriptions: 0,
215
+ missingType: 0,
216
+ missingBarcode: 0,
217
+ missingWeight: 0,
218
+ missingSku: 0,
219
+ averageAttributeScore: 0,
220
+ },
221
+ items: [],
222
+ csv: '',
223
+ };
224
+ }
225
+
226
+ let thinDescriptions = 0;
227
+ let missingType = 0;
228
+ let missingBarcode = 0;
229
+ let missingWeight = 0;
230
+ let missingSku = 0;
231
+
232
+ const items = products.slice(0, 25).map((p) => {
233
+ const cleanBody = stripHtml(p.body_html || '');
234
+ const variants = Array.isArray(p.variants) ? p.variants : [];
235
+ const tags = Array.isArray(p.tags)
236
+ ? p.tags
237
+ : String(p.tags || '').split(',').map((t) => t.trim()).filter(Boolean);
238
+
239
+ const searchHaystack = `${p.title || ''} ${cleanBody} ${tags.join(' ')}`.toLowerCase();
240
+ const detectedMaterials = MATERIAL_KEYWORDS.filter((kw) => searchHaystack.includes(kw));
241
+ const detectedUseCases = USE_CASE_KEYWORDS.filter((kw) => searchHaystack.includes(kw));
242
+
243
+ const noBarcodeCount = variants.filter((v) => !String(v.barcode || '').trim()).length;
244
+ const noWeightCount = variants.filter((v) => !Number(v.grams) || Number(v.grams) <= 0).length;
245
+ const noSkuCount = variants.filter((v) => !String(v.sku || '').trim()).length;
246
+
247
+ const missingFields = [];
248
+ if (cleanBody.length < 140) {
249
+ thinDescriptions += 1;
250
+ missingFields.push('rich_product_specs');
251
+ }
252
+ if (!String(p.product_type || '').trim()) {
253
+ missingType += 1;
254
+ missingFields.push('product_type');
255
+ }
256
+ if (variants.length > 0 && noBarcodeCount === variants.length) {
257
+ missingBarcode += 1;
258
+ missingFields.push('gtin_barcode');
259
+ }
260
+ if (variants.length > 0 && noWeightCount === variants.length) {
261
+ missingWeight += 1;
262
+ missingFields.push('shipping_weight_grams');
263
+ }
264
+ if (variants.length > 0 && noSkuCount === variants.length) {
265
+ missingSku += 1;
266
+ missingFields.push('variant_sku');
267
+ }
268
+ if (detectedMaterials.length === 0) missingFields.push('material_metafield');
269
+ if (detectedUseCases.length === 0) missingFields.push('use_case_metafield');
270
+
271
+ const totalChecks = 7;
272
+ const completenessPct = Math.round(((totalChecks - missingFields.length) / totalChecks) * 100);
273
+
274
+ return {
275
+ handle: p.handle,
276
+ title: p.title,
277
+ vendor: p.vendor || storeDomain,
278
+ productType: p.product_type || '',
279
+ variantCount: variants.length,
280
+ price: variants[0]?.price || null,
281
+ descriptionChars: cleanBody.length,
282
+ detectedMaterials,
283
+ detectedUseCases,
284
+ missingBarcodeVariants: noBarcodeCount,
285
+ missingWeightVariants: noWeightCount,
286
+ missingFields,
287
+ completenessPct,
288
+ productUrl: `https://${storeDomain}/products/${p.handle}`,
289
+ suggestedAgenticSummary: cleanBody.slice(0, 260),
290
+ };
291
+ });
292
+
293
+ const avgScore = Math.round(items.reduce((acc, x) => acc + x.completenessPct, 0) / items.length);
294
+ const csv = buildShopifyMetafieldCsv(items);
295
+
296
+ return {
297
+ isShopifyProductsJson: true,
298
+ sampledProducts: items.length,
299
+ summary: {
300
+ thinDescriptions,
301
+ missingType,
302
+ missingBarcode,
303
+ missingWeight,
304
+ missingSku,
305
+ averageAttributeScore: avgScore,
306
+ },
307
+ items,
308
+ csv,
309
+ };
310
+ }
311
+
312
+ function csvCell(val) {
313
+ const s = String(val ?? '');
314
+ return `"${s.replaceAll('"', '""')}"`;
315
+ }
316
+
317
+ /**
318
+ * Generate RFC-4180 compliant Shopify Metafield bulk import CSV for immediate merchant remediation.
319
+ */
320
+ export function buildShopifyMetafieldCsv(items) {
321
+ const header = [
322
+ 'Handle',
323
+ 'Title',
324
+ 'Vendor',
325
+ 'Type',
326
+ 'Missing_Fields',
327
+ 'Metafield: custom.material [single_line_text_field]',
328
+ 'Metafield: custom.use_case [single_line_text_field]',
329
+ 'Metafield: agentic.summary [multi_line_text_field]',
330
+ 'Review_Action',
331
+ ];
332
+ const rows = [header.map(csvCell).join(',')];
333
+ for (const item of items) {
334
+ rows.push(
335
+ [
336
+ item.handle,
337
+ item.title,
338
+ item.vendor,
339
+ item.productType || 'FILL_CATEGORY',
340
+ item.missingFields.join('; '),
341
+ item.detectedMaterials.join(', ') || 'ADD_EXACT_MATERIAL',
342
+ item.detectedUseCases.join(', ') || 'ADD_TARGET_USE_CASE',
343
+ item.suggestedAgenticSummary || 'ADD_STRUCTURED_SPECS',
344
+ item.missingBarcodeVariants > 0 ? 'Add GTIN/UPC barcodes + shipping grams in Shopify Admin' : 'Verify & sync',
345
+ ]
346
+ .map(csvCell)
347
+ .join(','),
348
+ );
349
+ }
350
+ return rows.join('\n');
351
+ }
352
+
353
+ /**
354
+ * Build a production Shopify Liquid Schema.org JSON-LD patch snippet covering Product, Offer, Shipping & Return Policy.
355
+ */
356
+ export function buildLiquidSchemaPatch() {
357
+ return `{% comment %} CartSpec Agentic Commerce Schema.org JSON-LD Patch {% endcomment %}
358
+ <script type="application/ld+json">
359
+ {
360
+ "@context": "https://schema.org",
361
+ "@type": "Product",
362
+ "name": {{ product.title | json }},
363
+ "description": {{ product.description | strip_html | strip_newlines | truncate: 500 | json }},
364
+ "sku": {{ product.selected_or_first_available_variant.sku | json }},
365
+ {% if product.selected_or_first_available_variant.barcode != blank %}
366
+ "gtin": {{ product.selected_or_first_available_variant.barcode | json }},
367
+ {% endif %}
368
+ "brand": { "@type": "Brand", "name": {{ product.vendor | json }} },
369
+ {% if product.metafields.custom.material != blank %}
370
+ "material": {{ product.metafields.custom.material.value | json }},
371
+ {% endif %}
372
+ "offers": {
373
+ "@type": "Offer",
374
+ "url": {{ shop.url | append: product.url | json }},
375
+ "priceCurrency": {{ cart.currency.iso_code | json }},
376
+ "price": {{ product.selected_or_first_available_variant.price | divided_by: 100.0 | json }},
377
+ "availability": "https://schema.org/{% if product.available %}InStock{% else %}OutOfStock{% endif %}",
378
+ "hasMerchantReturnPolicy": {
379
+ "@type": "MerchantReturnPolicy",
380
+ "applicableCountry": "US",
381
+ "returnPolicyCategory": "https://schema.org/MerchantReturnFiniteReturnWindow",
382
+ "merchantReturnDays": 30
383
+ }
384
+ }
385
+ }
386
+ </script>`;
387
+ }
388
+
389
+ /**
390
+ * Compute weighted 0-100 Agentic Storefront Readiness score with concrete layer diagnostics.
391
+ */
392
+ export function computeAgenticScore({ robots, jsonLd, catalog, discovery, htmlSignals }) {
393
+ // 1. AI Shopping Bot Access (20 pts)
394
+ const coreBots = robots.bots.filter((b) =>
395
+ ['OAI-SearchBot', 'ChatGPT-User', 'PerplexityBot', 'Google-Extended'].includes(b.agent),
396
+ );
397
+ const coreAllowed = coreBots.filter((b) => b.status === 'allowed').length;
398
+ const botPoints = Math.round((coreAllowed / Math.max(1, coreBots.length)) * 20);
399
+
400
+ // 2. Schema.org Product + Offer + GTIN Depth (25 pts)
401
+ let schemaPoints = 0;
402
+ if (jsonLd.organizationCount > 0) schemaPoints += 5;
403
+ if (jsonLd.productCount > 0) schemaPoints += 8;
404
+ if (jsonLd.hasOfferPrice) schemaPoints += 5;
405
+ if (jsonLd.hasGtinOrSku) schemaPoints += 4;
406
+ if (jsonLd.hasAggregateRating) schemaPoints += 3;
407
+
408
+ // 3. Return & Shipping Machine Readability (15 pts)
409
+ let policyPoints = 0;
410
+ if (jsonLd.hasReturnPolicy) policyPoints += 6;
411
+ if (jsonLd.hasShippingDetails) policyPoints += 5;
412
+ if (htmlSignals.hasPolicyLinks) policyPoints += 4;
413
+
414
+ // 4. Structured Catalog Metafields & Attributes (25 pts)
415
+ let catalogPoints = 0;
416
+ if (catalog.isShopifyProductsJson && catalog.sampledProducts > 0) {
417
+ catalogPoints = Math.round((catalog.summary.averageAttributeScore / 100) * 25);
418
+ } else if (jsonLd.productCount > 0) {
419
+ catalogPoints = 12;
420
+ }
421
+
422
+ // 5. Agent Discovery Protocols (10 pts)
423
+ let discoveryPoints = 0;
424
+ if (discovery.sitemapPresent) discoveryPoints += 4;
425
+ if (discovery.llmsTxtPresent) discoveryPoints += 3;
426
+ if (discovery.ucpPresent || discovery.mcpPresent) discoveryPoints += 3;
427
+
428
+ // 6. Base Storefront Semantics (5 pts)
429
+ let storefrontPoints = 0;
430
+ if (htmlSignals.hasCanonical) storefrontPoints += 3;
431
+ if (htmlSignals.hasMetaDescription) storefrontPoints += 2;
432
+
433
+ const totalScore = Math.min(
434
+ 100,
435
+ botPoints + schemaPoints + policyPoints + catalogPoints + discoveryPoints + storefrontPoints,
436
+ );
437
+
438
+ const grade =
439
+ totalScore >= 85 ? 'A' : totalScore >= 70 ? 'B' : totalScore >= 55 ? 'C' : totalScore >= 40 ? 'D' : 'F';
440
+
441
+ return {
442
+ totalScore,
443
+ grade,
444
+ breakdown: [
445
+ { key: 'bots', label: 'AI Shopping Bot Access (robots.txt)', score: botPoints, max: 20 },
446
+ { key: 'schema', label: 'Product & Offer Schema (JSON-LD + GTIN)', score: schemaPoints, max: 25 },
447
+ { key: 'policies', label: 'Machine-Readable Return & Shipping Policy', score: policyPoints, max: 15 },
448
+ { key: 'catalog', label: 'SKU Attribute & Metafield Completeness', score: catalogPoints, max: 25 },
449
+ { key: 'discovery', label: 'Discovery Endpoints (sitemap / llms.txt / UCP)', score: discoveryPoints, max: 10 },
450
+ { key: 'semantics', label: 'Canonical & Storefront Grounding', score: storefrontPoints, max: 5 },
451
+ ],
452
+ };
453
+ }
package/src/ssrf.mjs ADDED
@@ -0,0 +1,142 @@
1
+ import dns from 'node:dns/promises';
2
+ import net from 'node:net';
3
+
4
+ const BLOCKED_HOSTNAMES = new Set([
5
+ 'localhost',
6
+ 'localhost.localdomain',
7
+ 'ip6-localhost',
8
+ 'ip6-loopback',
9
+ 'metadata.google.internal',
10
+ '169.254.169.254',
11
+ ]);
12
+
13
+ /**
14
+ * Determine whether an IPv4 or IPv6 literal belongs to loopback, link-local, RFC1918, or reserved ranges.
15
+ */
16
+ export function isPrivateOrReservedIp(ipRaw) {
17
+ const ip = String(ipRaw || '').trim().toLowerCase();
18
+ const ver = net.isIP(ip);
19
+ if (ver === 4) {
20
+ const parts = ip.split('.').map(Number);
21
+ if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
22
+ const [a, b] = parts;
23
+ if (a === 0 || a === 10 || a === 127) return true;
24
+ if (a === 169 && b === 254) return true;
25
+ if (a === 172 && b >= 16 && b <= 31) return true;
26
+ if (a === 192 && b === 168) return true;
27
+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
28
+ if (a >= 224) return true; // multicast/reserved
29
+ return false;
30
+ }
31
+ if (ver === 6) {
32
+ if (ip === '::' || ip === '::1') return true;
33
+ if (ip.startsWith('fe80:') || ip.startsWith('fc') || ip.startsWith('fd')) return true;
34
+ if (ip.startsWith('::ffff:')) return isPrivateOrReservedIp(ip.slice(7));
35
+ return false;
36
+ }
37
+ return true;
38
+ }
39
+
40
+ /**
41
+ * Normalize a store domain or URL strictly into an HTTPS origin/URL, blocking non-public hostnames and IP literals.
42
+ */
43
+ export function normalizeStoreUrl(rawInput) {
44
+ let candidate = String(rawInput || '').trim();
45
+ if (!candidate) throw new Error('Please enter a store domain or URL (for example, allbirds.com).');
46
+ if (!/^https?:\/\//i.test(candidate)) {
47
+ candidate = `https://${candidate}`;
48
+ }
49
+ const parsed = new URL(candidate);
50
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
51
+ throw new Error('Only http and https storefront URLs are supported.');
52
+ }
53
+ const hostname = parsed.hostname.toLowerCase();
54
+ if (
55
+ !hostname ||
56
+ BLOCKED_HOSTNAMES.has(hostname) ||
57
+ hostname.endsWith('.local') ||
58
+ hostname.endsWith('.internal') ||
59
+ hostname.endsWith('.localhost') ||
60
+ !hostname.includes('.') ||
61
+ net.isIP(hostname) !== 0
62
+ ) {
63
+ throw new Error(`Blocked non-public or IP-literal target host "${hostname}".`);
64
+ }
65
+ return new URL(`https://${hostname}${parsed.port ? `:${parsed.port}` : ''}`);
66
+ }
67
+
68
+ /**
69
+ * Resolve DNS for hostname and reject if any resolved address falls inside private/reserved ranges.
70
+ */
71
+ export async function assertPublicHostname(hostname) {
72
+ const records = await dns.lookup(hostname, { all: true, verbatim: true });
73
+ if (!records || records.length === 0) {
74
+ throw new Error(`Could not resolve DNS for "${hostname}".`);
75
+ }
76
+ for (const rec of records) {
77
+ if (isPrivateOrReservedIp(rec.address)) {
78
+ throw new Error(`Resolved address "${rec.address}" for "${hostname}" is not publicly routable.`);
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Fetch a URL cleanly with SSRF redirect guards, per-request timeout, and byte-size cap.
85
+ */
86
+ export async function safeFetchText(targetUrl, { timeoutMs = 8000, maxBytes = 1024 * 1024, accept = '*/*' } = {}) {
87
+ let current = new URL(targetUrl);
88
+ for (let hop = 0; hop <= 4; hop += 1) {
89
+ const cleanOrigin = normalizeStoreUrl(current.toString());
90
+ await assertPublicHostname(cleanOrigin.hostname);
91
+
92
+ const controller = new AbortController();
93
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
94
+ let res;
95
+ try {
96
+ res = await fetch(current.toString(), {
97
+ method: 'GET',
98
+ redirect: 'manual',
99
+ signal: controller.signal,
100
+ headers: {
101
+ 'User-Agent': 'CartSpec-AgenticAuditor/0.1 (+https://cartspec.vespori.com)',
102
+ Accept: accept,
103
+ },
104
+ });
105
+ } finally {
106
+ clearTimeout(timer);
107
+ }
108
+
109
+ if (res.status >= 300 && res.status < 400) {
110
+ const location = res.headers.get('location');
111
+ if (!location) {
112
+ return { ok: false, status: res.status, url: current.toString(), text: '' };
113
+ }
114
+ current = new URL(location, current);
115
+ continue;
116
+ }
117
+
118
+ const reader = res.body?.getReader();
119
+ if (!reader) {
120
+ const text = await res.text();
121
+ return { ok: res.ok, status: res.status, url: current.toString(), text: text.slice(0, maxBytes) };
122
+ }
123
+
124
+ const chunks = [];
125
+ let total = 0;
126
+ while (true) {
127
+ const { done, value } = await reader.read();
128
+ if (done) break;
129
+ total += value.byteLength;
130
+ if (total > maxBytes) {
131
+ const remaining = value.subarray(0, Math.max(0, value.byteLength - (total - maxBytes)));
132
+ if (remaining.byteLength > 0) chunks.push(remaining);
133
+ await reader.cancel().catch(() => {});
134
+ break;
135
+ }
136
+ chunks.push(value);
137
+ }
138
+ const text = Buffer.concat(chunks.map((c) => Buffer.from(c))).toString('utf8');
139
+ return { ok: res.ok, status: res.status, url: current.toString(), text };
140
+ }
141
+ throw new Error('Too many redirects while inspecting storefront URL.');
142
+ }