|
| 1 | +#!/usr/bin/env node |
| 2 | +import { mkdirSync, writeFileSync } from "node:fs"; |
| 3 | +import path from "node:path"; |
| 4 | +import { pathToFileURL } from "node:url"; |
| 5 | + |
| 6 | +import { discoverWorkerRecordRepoSlugs, exportWorkerRecords } from "./worker-records.ts"; |
| 7 | + |
| 8 | +export const CANONICAL_PROMOTION_KEYS = Object.freeze([ |
| 9 | + "real_behavior_proof_status", |
| 10 | + "real_behavior_proof_evidence_kind", |
| 11 | + "real_behavior_proof_needs_contributor_action", |
| 12 | + "pr_rating_overall", |
| 13 | + "pr_rating_proof", |
| 14 | + "pr_rating_patch", |
| 15 | +]); |
| 16 | + |
| 17 | +const DEFAULT_MAX_RECORDS = 10_000; |
| 18 | +const DEFAULT_RECORDS_URL = "https://clawsweeper.openclaw.ai"; |
| 19 | +const REPO_SLUG_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,199}$/; |
| 20 | + |
| 21 | +export function reportMetadataSpoofingFinding(markdown) { |
| 22 | + const frontMatterMatch = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); |
| 23 | + if (!frontMatterMatch) return null; |
| 24 | + const remainderStart = frontMatterMatch[0].length; |
| 25 | + const remainder = markdown.slice(remainderStart); |
| 26 | + const matches = []; |
| 27 | + for (const key of CANONICAL_PROMOTION_KEYS) { |
| 28 | + const match = new RegExp(`^${key}:`, "m").exec(remainder); |
| 29 | + if (!match) continue; |
| 30 | + const absoluteIndex = remainderStart + match.index; |
| 31 | + matches.push({ key, line: lineNumberAt(markdown, absoluteIndex) }); |
| 32 | + } |
| 33 | + if (!matches.length) return null; |
| 34 | + matches.sort((left, right) => left.line - right.line || left.key.localeCompare(right.key)); |
| 35 | + return { |
| 36 | + matched_keys: matches.map((match) => match.key), |
| 37 | + first_match_line: matches[0].line, |
| 38 | + }; |
| 39 | +} |
| 40 | + |
| 41 | +export async function auditCanonicalItemRecords(options) { |
| 42 | + const maxRecords = positiveInteger(options.maxRecords ?? DEFAULT_MAX_RECORDS, "maxRecords"); |
| 43 | + const repoSlugs = await resolveRepoSlugs(options); |
| 44 | + const findings = []; |
| 45 | + let scannedRecords = 0; |
| 46 | + for (const repoSlug of repoSlugs) { |
| 47 | + const snapshot = await (options.exportRecords ?? exportWorkerRecords)({ |
| 48 | + baseUrl: options.baseUrl, |
| 49 | + webhookSecret: options.webhookSecret, |
| 50 | + repoSlug, |
| 51 | + sections: ["items"], |
| 52 | + maxRecords: maxRecords - scannedRecords, |
| 53 | + fetch: options.fetch, |
| 54 | + }); |
| 55 | + scannedRecords += snapshot.records.length; |
| 56 | + if (scannedRecords > maxRecords) { |
| 57 | + throw new Error(`Canonical item audit exceeded the ${maxRecords}-record bound`); |
| 58 | + } |
| 59 | + for (const record of snapshot.records) { |
| 60 | + if (record.section !== "items" || record.deleted || typeof record.content !== "string") { |
| 61 | + continue; |
| 62 | + } |
| 63 | + const finding = reportMetadataSpoofingFinding(record.content); |
| 64 | + if (!finding) continue; |
| 65 | + findings.push({ |
| 66 | + repo_slug: repoSlug, |
| 67 | + item_number: Number(record.id), |
| 68 | + ...finding, |
| 69 | + }); |
| 70 | + } |
| 71 | + } |
| 72 | + findings.sort( |
| 73 | + (left, right) => |
| 74 | + left.repo_slug.localeCompare(right.repo_slug) || left.item_number - right.item_number, |
| 75 | + ); |
| 76 | + return { |
| 77 | + schema_version: 1, |
| 78 | + generated_at: (options.now ?? new Date()).toISOString(), |
| 79 | + repo_slugs: repoSlugs, |
| 80 | + scanned_records: scannedRecords, |
| 81 | + finding_count: findings.length, |
| 82 | + findings, |
| 83 | + }; |
| 84 | +} |
| 85 | + |
| 86 | +export async function runAuditCli(argv, env = process.env) { |
| 87 | + const args = parseArgs(argv); |
| 88 | + const webhookSecret = env.CLAWSWEEPER_RECORDS_SECRET ?? env.CLAWSWEEPER_WEBHOOK_SECRET ?? ""; |
| 89 | + if (!webhookSecret) throw new Error("CLAWSWEEPER_WEBHOOK_SECRET is required"); |
| 90 | + const inventory = await auditCanonicalItemRecords({ |
| 91 | + baseUrl: |
| 92 | + args.recordsUrl ?? |
| 93 | + env.CLAWSWEEPER_RECORDS_URL ?? |
| 94 | + env.CLAWSWEEPER_STATE_COORDINATOR_URL ?? |
| 95 | + DEFAULT_RECORDS_URL, |
| 96 | + webhookSecret, |
| 97 | + repoSlugs: args.repoSlugs ?? parseRepoSlugs(env.CLAWSWEEPER_RECORDS_REPO_SLUGS) ?? undefined, |
| 98 | + maxRecords: args.maxRecords ?? DEFAULT_MAX_RECORDS, |
| 99 | + }); |
| 100 | + const json = `${JSON.stringify(inventory, null, 2)}\n`; |
| 101 | + if (args.output) { |
| 102 | + const output = path.resolve(args.output); |
| 103 | + mkdirSync(path.dirname(output), { recursive: true }); |
| 104 | + writeFileSync(output, json, "utf8"); |
| 105 | + console.error( |
| 106 | + `Audited ${inventory.scanned_records} canonical item records; wrote ${inventory.finding_count} finding(s) to ${args.output}`, |
| 107 | + ); |
| 108 | + } else { |
| 109 | + process.stdout.write(json); |
| 110 | + } |
| 111 | + return inventory; |
| 112 | +} |
| 113 | + |
| 114 | +async function resolveRepoSlugs(options) { |
| 115 | + const configured = options.repoSlugs?.length |
| 116 | + ? options.repoSlugs |
| 117 | + : ( |
| 118 | + await (options.discoverRepoSlugs ?? discoverWorkerRecordRepoSlugs)({ |
| 119 | + baseUrl: options.baseUrl, |
| 120 | + webhookSecret: options.webhookSecret, |
| 121 | + fetch: options.fetch, |
| 122 | + }) |
| 123 | + ).map((entry) => entry.repoSlug); |
| 124 | + const repoSlugs = [...new Set(configured)].sort(); |
| 125 | + if (!repoSlugs.length) throw new Error("Canonical record store returned no repository slugs"); |
| 126 | + for (const repoSlug of repoSlugs) { |
| 127 | + if (!REPO_SLUG_PATTERN.test(repoSlug)) { |
| 128 | + throw new Error(`Invalid record repository slug: ${repoSlug}`); |
| 129 | + } |
| 130 | + } |
| 131 | + return repoSlugs; |
| 132 | +} |
| 133 | + |
| 134 | +function parseArgs(argv) { |
| 135 | + const parsed = {}; |
| 136 | + for (let index = 0; index < argv.length; index += 1) { |
| 137 | + const arg = argv[index]; |
| 138 | + if (arg === "--") continue; |
| 139 | + if (arg === "--output") parsed.output = requiredValue(argv, ++index, arg); |
| 140 | + else if (arg === "--records-url") parsed.recordsUrl = requiredValue(argv, ++index, arg); |
| 141 | + else if (arg === "--repo-slugs") { |
| 142 | + parsed.repoSlugs = parseRepoSlugs(requiredValue(argv, ++index, arg)); |
| 143 | + } else if (arg === "--max-records") { |
| 144 | + parsed.maxRecords = positiveInteger(requiredValue(argv, ++index, arg), arg); |
| 145 | + } else { |
| 146 | + throw new Error(`Unknown argument: ${arg}`); |
| 147 | + } |
| 148 | + } |
| 149 | + return parsed; |
| 150 | +} |
| 151 | + |
| 152 | +function parseRepoSlugs(value) { |
| 153 | + if (value === undefined || value.trim() === "") return undefined; |
| 154 | + return [...new Set(value.split(/[\s,]+/).filter(Boolean))].sort(); |
| 155 | +} |
| 156 | + |
| 157 | +function requiredValue(argv, index, flag) { |
| 158 | + const value = argv[index]; |
| 159 | + if (!value || value.startsWith("--")) throw new Error(`${flag} requires a value`); |
| 160 | + return value; |
| 161 | +} |
| 162 | + |
| 163 | +function positiveInteger(value, name) { |
| 164 | + const number = Number(value); |
| 165 | + if (!Number.isSafeInteger(number) || number < 1) { |
| 166 | + throw new Error(`${name} requires a positive safe integer`); |
| 167 | + } |
| 168 | + return number; |
| 169 | +} |
| 170 | + |
| 171 | +function lineNumberAt(markdown, index) { |
| 172 | + let line = 1; |
| 173 | + for (let offset = 0; offset < index; offset += 1) { |
| 174 | + if (markdown.charCodeAt(offset) === 10) line += 1; |
| 175 | + } |
| 176 | + return line; |
| 177 | +} |
| 178 | + |
| 179 | +if (import.meta.url === pathToFileURL(process.argv[1] || "").href) { |
| 180 | + await runAuditCli(process.argv.slice(2)); |
| 181 | +} |
0 commit comments