w3pk 0.10.4 → 0.10.5

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.
@@ -1,194 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/inspect/browser.ts
21
- var browser_exports = {};
22
- __export(browser_exports, {
23
- inspect: () => inspect,
24
- inspectNow: () => inspectNow
25
- });
26
- module.exports = __toCommonJS(browser_exports);
27
- function extractTransactionSnippets(content, maxLength = 3e4) {
28
- const keywords = [
29
- "signMessage",
30
- "signTypedData",
31
- "sign(",
32
- "signature",
33
- "sendTransaction",
34
- "transaction",
35
- "eth_sign",
36
- "Contract(",
37
- "ethers.Contract",
38
- "new Contract",
39
- "w3pk",
40
- "Web3Passkey",
41
- "useW3PK",
42
- "wallet",
43
- "signer",
44
- "provider",
45
- "authorization",
46
- "delegation",
47
- "EIP7702"
48
- ];
49
- const lines = content.split("\n");
50
- const relevantLines = [];
51
- const maxLines = 500;
52
- for (let i = 0; i < lines.length && relevantLines.length < maxLines; i++) {
53
- const line = lines[i];
54
- const lowerLine = line.toLowerCase();
55
- if (keywords.some((kw) => lowerLine.includes(kw.toLowerCase()))) {
56
- const start = Math.max(0, i - 2);
57
- const end = Math.min(lines.length, i + 3);
58
- for (let j = start; j < end; j++) {
59
- if (!relevantLines.includes(lines[j])) {
60
- relevantLines.push(lines[j]);
61
- }
62
- }
63
- }
64
- }
65
- const snippet = relevantLines.join("\n");
66
- if (snippet.length > maxLength) {
67
- return snippet.substring(0, maxLength) + "\n\n// ... (truncated)";
68
- }
69
- return snippet || "// No transaction code found";
70
- }
71
- async function fetchAppSource(appUrl, maxTotalSizeKB = 100) {
72
- let markdown = `# Application Code Analysis
73
-
74
- `;
75
- markdown += `**App URL:** ${appUrl}
76
-
77
- `;
78
- markdown += `**Note:** Only transaction-related code snippets shown
79
-
80
- `;
81
- markdown += `---
82
-
83
- `;
84
- const scripts = Array.from(document.querySelectorAll("script[src]"));
85
- const scriptUrls = scripts.map((script) => script.src).filter(
86
- (src) => src && !src.includes("node_modules") && !src.includes("chrome-extension")
87
- );
88
- markdown += `## JavaScript Files (${scriptUrls.length})
89
-
90
- `;
91
- let totalSnippets = 0;
92
- let cumulativeSizeKB = 0;
93
- const maxTotalBytes = maxTotalSizeKB * 1024;
94
- for (const scriptUrl of scriptUrls.slice(0, 15)) {
95
- if (cumulativeSizeKB >= maxTotalSizeKB) {
96
- console.warn(`[W3PK Inspect] Reached total size limit of ${maxTotalSizeKB} KB - stopping collection`);
97
- markdown += `
98
- **Note:** Collection stopped - reached ${maxTotalSizeKB} KB limit
99
- `;
100
- break;
101
- }
102
- try {
103
- const response = await fetch(scriptUrl);
104
- if (!response.ok) continue;
105
- const content = await response.text();
106
- const snippets = extractTransactionSnippets(content);
107
- if (snippets && !snippets.includes("No transaction code found")) {
108
- const snippetSize = new Blob([snippets]).size / 1024;
109
- if (cumulativeSizeKB + snippetSize > maxTotalSizeKB) {
110
- console.warn(`[W3PK Inspect] Skipping ${new URL(scriptUrl).pathname} - would exceed total size limit`);
111
- break;
112
- }
113
- markdown += `### \`${new URL(scriptUrl).pathname}\`
114
-
115
- `;
116
- markdown += "```javascript\n";
117
- markdown += snippets;
118
- markdown += "\n```\n\n---\n\n";
119
- totalSnippets++;
120
- cumulativeSizeKB += snippetSize;
121
- }
122
- } catch (error) {
123
- }
124
- }
125
- if (totalSnippets === 0) {
126
- markdown += `No transaction-related code found in JavaScript files.
127
- `;
128
- }
129
- return markdown;
130
- }
131
- async function inspect(options = {}) {
132
- if (typeof window === "undefined") {
133
- throw new Error(
134
- "Browser inspect() can only be called in browser environments. For Node.js, use the CLI or Node.js API."
135
- );
136
- }
137
- const {
138
- appUrl = window.location.origin,
139
- rukhUrl = "https://rukh.w3hc.org",
140
- context = "w3pk",
141
- model = "anthropic",
142
- focusMode = "transactions",
143
- maxTotalSizeKB = 100
144
- } = options;
145
- console.log("[W3PK Inspect] Starting inspection of", appUrl);
146
- console.log("[W3PK Inspect] Focus mode:", focusMode);
147
- console.log("[W3PK Inspect] Max total size:", maxTotalSizeKB, "KB");
148
- const sourceMarkdown = await fetchAppSource(appUrl, maxTotalSizeKB);
149
- console.log("[W3PK Inspect] Collected source code, sending to Rukh API...");
150
- const message = "Analyze this web application and provide a security report listing all transaction and signing methods.";
151
- const formData = new FormData();
152
- formData.append("message", message);
153
- formData.append("model", model);
154
- formData.append("context", context);
155
- const blob = new Blob([sourceMarkdown], { type: "text/markdown" });
156
- formData.append("file", blob, "app-source.md");
157
- const response = await fetch(`${rukhUrl}/ask`, {
158
- method: "POST",
159
- body: formData
160
- });
161
- if (!response.ok) {
162
- const error = await response.text();
163
- throw new Error(`Rukh API error: ${response.status} - ${error}`);
164
- }
165
- const data = await response.json();
166
- const report = data.output || data.response || data.message || JSON.stringify(data);
167
- console.log("[W3PK Inspect] Analysis complete!");
168
- const scripts = Array.from(document.querySelectorAll("script[src]"));
169
- const analyzedFiles = scripts.map((script) => new URL(script.src).pathname).filter((src) => src && !src.includes("node_modules"));
170
- return {
171
- report,
172
- analyzedFiles,
173
- appUrl
174
- };
175
- }
176
- async function inspectNow(options) {
177
- console.log("\u{1F50D} W3PK Security Inspection Starting...\n");
178
- try {
179
- const result = await inspect(options);
180
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
181
- console.log("\u{1F4CB} SECURITY REPORT");
182
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n");
183
- console.log(result.report);
184
- console.log("\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
185
- console.log(
186
- `\u2705 Analyzed ${result.analyzedFiles.length} files from ${result.appUrl}`
187
- );
188
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
189
- } catch (error) {
190
- console.error("\u274C Inspection failed:", error);
191
- throw error;
192
- }
193
- }
194
- //# sourceMappingURL=browser.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/inspect/browser.ts"],"sourcesContent":["/**\n * Browser Inspection Module\n *\n * Provides client-side code inspection capabilities for analyzing running web3 applications.\n * Fetches JavaScript sources from the current page and analyzes transaction/signing patterns\n * to generate security reports via the Rukh API.\n *\n * This module is designed to be used directly in the browser console or embedded in\n * web applications to help end-users understand the security posture of the apps they use.\n *\n * @module inspect/browser\n */\n\n/**\n * Configuration options for browser-based application inspection\n */\nexport interface BrowserInspectOptions {\n /**\n * The origin/URL of the app to inspect\n * @default window.location.origin\n */\n appUrl?: string;\n\n /**\n * Rukh API endpoint\n * @default 'https://rukh.w3hc.org'\n */\n rukhUrl?: string;\n\n /**\n * Context to use for analysis\n * @default 'w3pk'\n */\n context?: string;\n\n /**\n * AI model to use\n * @default 'anthropic'\n */\n model?: \"anthropic\" | \"mistral\" | \"openai\";\n\n /**\n * Focus mode for analysis\n * @default 'transactions'\n */\n focusMode?: \"transactions\" | \"all\";\n\n /**\n * Maximum total size in KB for all collected code (prevents exceeding API token limits)\n * @default 100\n */\n maxTotalSizeKB?: number;\n}\n\n/**\n * Result of a browser-based inspection\n */\nexport interface BrowserInspectResult {\n /**\n * The security report markdown generated by Rukh API\n */\n report: string;\n\n /**\n * List of JavaScript file paths that were analyzed\n */\n analyzedFiles: string[];\n\n /**\n * The application URL that was inspected\n */\n appUrl: string;\n}\n\n/**\n * Extracts transaction-related code snippets from JavaScript content\n *\n * Scans JavaScript code for keywords related to signing, transactions, and web3 operations,\n * then extracts relevant code snippets with surrounding context.\n *\n * @param content - The JavaScript source code to analyze\n * @param maxLength - Maximum length of extracted snippets in characters\n * @returns Extracted code snippets or a message if no relevant code found\n * @internal\n */\nfunction extractTransactionSnippets(\n content: string,\n maxLength: number = 30000,\n): string {\n const keywords = [\n \"signMessage\",\n \"signTypedData\",\n \"sign(\",\n \"signature\",\n \"sendTransaction\",\n \"transaction\",\n \"eth_sign\",\n \"Contract(\",\n \"ethers.Contract\",\n \"new Contract\",\n \"w3pk\",\n \"Web3Passkey\",\n \"useW3PK\",\n \"wallet\",\n \"signer\",\n \"provider\",\n \"authorization\",\n \"delegation\",\n \"EIP7702\",\n ];\n\n const lines = content.split(\"\\n\");\n const relevantLines: string[] = [];\n const maxLines = 500;\n\n for (let i = 0; i < lines.length && relevantLines.length < maxLines; i++) {\n const line = lines[i];\n const lowerLine = line.toLowerCase();\n\n if (keywords.some((kw) => lowerLine.includes(kw.toLowerCase()))) {\n const start = Math.max(0, i - 2);\n const end = Math.min(lines.length, i + 3);\n\n for (let j = start; j < end; j++) {\n if (!relevantLines.includes(lines[j])) {\n relevantLines.push(lines[j]);\n }\n }\n }\n }\n\n const snippet = relevantLines.join(\"\\n\");\n\n if (snippet.length > maxLength) {\n return snippet.substring(0, maxLength) + \"\\n\\n// ... (truncated)\";\n }\n\n return snippet || \"// No transaction code found\";\n}\n\n/**\n * Fetches JavaScript source code from the currently running application\n *\n * Discovers and fetches all script tags in the current page, extracts transaction-related\n * snippets, and formats them as markdown for analysis.\n *\n * @param appUrl - The base URL of the application being inspected\n * @param maxTotalSizeKB - Maximum total size in KB for all collected code\n * @returns Markdown-formatted source code with transaction-related snippets\n * @internal\n */\nasync function fetchAppSource(appUrl: string, maxTotalSizeKB: number = 100): Promise<string> {\n let markdown = `# Application Code Analysis\\n\\n`;\n markdown += `**App URL:** ${appUrl}\\n\\n`;\n markdown += `**Note:** Only transaction-related code snippets shown\\n\\n`;\n markdown += `---\\n\\n`;\n\n const scripts = Array.from(document.querySelectorAll(\"script[src]\"));\n const scriptUrls = scripts\n .map((script) => (script as HTMLScriptElement).src)\n .filter(\n (src) =>\n src &&\n !src.includes(\"node_modules\") &&\n !src.includes(\"chrome-extension\"),\n );\n\n markdown += `## JavaScript Files (${scriptUrls.length})\\n\\n`;\n\n let totalSnippets = 0;\n let cumulativeSizeKB = 0;\n const maxTotalBytes = maxTotalSizeKB * 1024;\n\n for (const scriptUrl of scriptUrls.slice(0, 15)) {\n // Check if we've reached the size limit\n if (cumulativeSizeKB >= maxTotalSizeKB) {\n console.warn(`[W3PK Inspect] Reached total size limit of ${maxTotalSizeKB} KB - stopping collection`);\n markdown += `\\n**Note:** Collection stopped - reached ${maxTotalSizeKB} KB limit\\n`;\n break;\n }\n\n try {\n const response = await fetch(scriptUrl);\n if (!response.ok) continue;\n\n const content = await response.text();\n const snippets = extractTransactionSnippets(content);\n\n if (snippets && !snippets.includes(\"No transaction code found\")) {\n const snippetSize = new Blob([snippets]).size / 1024;\n\n // Check if adding this snippet would exceed the limit\n if (cumulativeSizeKB + snippetSize > maxTotalSizeKB) {\n console.warn(`[W3PK Inspect] Skipping ${new URL(scriptUrl).pathname} - would exceed total size limit`);\n break;\n }\n\n markdown += `### \\`${new URL(scriptUrl).pathname}\\`\\n\\n`;\n markdown += \"```javascript\\n\";\n markdown += snippets;\n markdown += \"\\n```\\n\\n---\\n\\n\";\n totalSnippets++;\n cumulativeSizeKB += snippetSize;\n }\n } catch (error) {\n // Skip files that can't be fetched\n }\n }\n\n if (totalSnippets === 0) {\n markdown += `No transaction-related code found in JavaScript files.\\n`;\n }\n\n return markdown;\n}\n\n/**\n * Inspects the currently running web application and returns a security report\n *\n * This function can be called by end-users in their browser console to analyze\n * the security of the web application they're currently using.\n *\n * @param options - Configuration options\n * @returns A security report analyzing transaction and signing methods\n *\n * @example\n * ```typescript\n * // In browser console or app code:\n * import { inspect } from 'w3pk';\n *\n * const report = await inspect();\n * console.log(report.report);\n * ```\n *\n * @example\n * ```typescript\n * // With custom options:\n * const report = await inspect({\n * appUrl: 'https://w3pk.w3hc.org',\n * model: 'anthropic',\n * focusMode: 'transactions'\n * });\n * ```\n */\nexport async function inspect(\n options: BrowserInspectOptions = {},\n): Promise<BrowserInspectResult> {\n // Check if running in browser\n if (typeof window === \"undefined\") {\n throw new Error(\n \"Browser inspect() can only be called in browser environments. For Node.js, use the CLI or Node.js API.\",\n );\n }\n\n const {\n appUrl = window.location.origin,\n rukhUrl = \"https://rukh.w3hc.org\",\n context = \"w3pk\",\n model = \"anthropic\",\n focusMode = \"transactions\",\n maxTotalSizeKB = 100,\n } = options;\n\n console.log(\"[W3PK Inspect] Starting inspection of\", appUrl);\n console.log(\"[W3PK Inspect] Focus mode:\", focusMode);\n console.log(\"[W3PK Inspect] Max total size:\", maxTotalSizeKB, \"KB\");\n\n // Fetch and analyze source code\n const sourceMarkdown = await fetchAppSource(appUrl, maxTotalSizeKB);\n\n console.log(\"[W3PK Inspect] Collected source code, sending to Rukh API...\");\n\n // Prepare request to Rukh API\n const message =\n \"Analyze this web application and provide a security report listing all transaction and signing methods.\";\n\n const formData = new FormData();\n formData.append(\"message\", message);\n formData.append(\"model\", model);\n formData.append(\"context\", context);\n\n // Create blob from markdown\n const blob = new Blob([sourceMarkdown], { type: \"text/markdown\" });\n formData.append(\"file\", blob, \"app-source.md\");\n\n // Send to Rukh API\n const response = await fetch(`${rukhUrl}/ask`, {\n method: \"POST\",\n body: formData,\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Rukh API error: ${response.status} - ${error}`);\n }\n\n const data = await response.json();\n const report =\n data.output || data.response || data.message || JSON.stringify(data);\n\n console.log(\"[W3PK Inspect] Analysis complete!\");\n\n // Extract script URLs for analyzedFiles\n const scripts = Array.from(document.querySelectorAll(\"script[src]\"));\n const analyzedFiles = scripts\n .map((script) => new URL((script as HTMLScriptElement).src).pathname)\n .filter((src) => src && !src.includes(\"node_modules\"));\n\n return {\n report,\n analyzedFiles,\n appUrl,\n };\n}\n\n/**\n * Quick inspection helper that logs the report to console\n * Perfect for use in browser DevTools console\n *\n * @example\n * ```javascript\n * // In browser console:\n * await w3pk.inspectNow()\n * ```\n */\nexport async function inspectNow(\n options?: BrowserInspectOptions,\n): Promise<void> {\n console.log(\"🔍 W3PK Security Inspection Starting...\\n\");\n\n try {\n const result = await inspect(options);\n\n console.log(\"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\");\n console.log(\"📋 SECURITY REPORT\");\n console.log(\"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\");\n console.log(result.report);\n console.log(\"\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\");\n console.log(\n `✅ Analyzed ${result.analyzedFiles.length} files from ${result.appUrl}`,\n );\n console.log(\"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\");\n } catch (error) {\n console.error(\"❌ Inspection failed:\", error);\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqFA,SAAS,2BACP,SACA,YAAoB,KACZ;AACR,QAAM,WAAW;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,QAAM,gBAA0B,CAAC;AACjC,QAAM,WAAW;AAEjB,WAAS,IAAI,GAAG,IAAI,MAAM,UAAU,cAAc,SAAS,UAAU,KAAK;AACxE,UAAM,OAAO,MAAM,CAAC;AACpB,UAAM,YAAY,KAAK,YAAY;AAEnC,QAAI,SAAS,KAAK,CAAC,OAAO,UAAU,SAAS,GAAG,YAAY,CAAC,CAAC,GAAG;AAC/D,YAAM,QAAQ,KAAK,IAAI,GAAG,IAAI,CAAC;AAC/B,YAAM,MAAM,KAAK,IAAI,MAAM,QAAQ,IAAI,CAAC;AAExC,eAAS,IAAI,OAAO,IAAI,KAAK,KAAK;AAChC,YAAI,CAAC,cAAc,SAAS,MAAM,CAAC,CAAC,GAAG;AACrC,wBAAc,KAAK,MAAM,CAAC,CAAC;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,QAAM,UAAU,cAAc,KAAK,IAAI;AAEvC,MAAI,QAAQ,SAAS,WAAW;AAC9B,WAAO,QAAQ,UAAU,GAAG,SAAS,IAAI;AAAA,EAC3C;AAEA,SAAO,WAAW;AACpB;AAaA,eAAe,eAAe,QAAgB,iBAAyB,KAAsB;AAC3F,MAAI,WAAW;AAAA;AAAA;AACf,cAA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O,CAAC,QAAQ,OAAO,CAAC,IAAI,SAAS,cAAc,CAAC;AAEvD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAYA,eAAsB,WACpB,SACe;AACf,UAAQ,IAAI,kDAA2C;AAEvD,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ,OAAO;AAEpC,YAAQ,IAAI,kPAA0C;AACtD,YAAQ,IAAI,2BAAoB;AAChC,YAAQ,IAAI,oPAA4C;AACxD,YAAQ,IAAI,OAAO,MAAM;AACzB,YAAQ,IAAI,oPAA4C;AACxD,YAAQ;AAAA,MACN,mBAAc,OAAO,cAAc,MAAM,eAAe,OAAO,MAAM;AAAA,IACvE;AACA,YAAQ,IAAI,kPAA0C;AAAA,EACxD,SAAS,OAAO;AACd,YAAQ,MAAM,6BAAwB,KAAK;AAC3C,UAAM;AAAA,EACR;AACF;","names":[]}
@@ -1,173 +0,0 @@
1
- // src/inspect/browser.ts
2
- function extractTransactionSnippets(content, maxLength = 3e4) {
3
- const keywords = [
4
- "signMessage",
5
- "signTypedData",
6
- "sign(",
7
- "signature",
8
- "sendTransaction",
9
- "transaction",
10
- "eth_sign",
11
- "Contract(",
12
- "ethers.Contract",
13
- "new Contract",
14
- "w3pk",
15
- "Web3Passkey",
16
- "useW3PK",
17
- "wallet",
18
- "signer",
19
- "provider",
20
- "authorization",
21
- "delegation",
22
- "EIP7702"
23
- ];
24
- const lines = content.split("\n");
25
- const relevantLines = [];
26
- const maxLines = 500;
27
- for (let i = 0; i < lines.length && relevantLines.length < maxLines; i++) {
28
- const line = lines[i];
29
- const lowerLine = line.toLowerCase();
30
- if (keywords.some((kw) => lowerLine.includes(kw.toLowerCase()))) {
31
- const start = Math.max(0, i - 2);
32
- const end = Math.min(lines.length, i + 3);
33
- for (let j = start; j < end; j++) {
34
- if (!relevantLines.includes(lines[j])) {
35
- relevantLines.push(lines[j]);
36
- }
37
- }
38
- }
39
- }
40
- const snippet = relevantLines.join("\n");
41
- if (snippet.length > maxLength) {
42
- return snippet.substring(0, maxLength) + "\n\n// ... (truncated)";
43
- }
44
- return snippet || "// No transaction code found";
45
- }
46
- async function fetchAppSource(appUrl, maxTotalSizeKB = 100) {
47
- let markdown = `# Application Code Analysis
48
-
49
- `;
50
- markdown += `**App URL:** ${appUrl}
51
-
52
- `;
53
- markdown += `**Note:** Only transaction-related code snippets shown
54
-
55
- `;
56
- markdown += `---
57
-
58
- `;
59
- const scripts = Array.from(document.querySelectorAll("script[src]"));
60
- const scriptUrls = scripts.map((script) => script.src).filter(
61
- (src) => src && !src.includes("node_modules") && !src.includes("chrome-extension")
62
- );
63
- markdown += `## JavaScript Files (${scriptUrls.length})
64
-
65
- `;
66
- let totalSnippets = 0;
67
- let cumulativeSizeKB = 0;
68
- const maxTotalBytes = maxTotalSizeKB * 1024;
69
- for (const scriptUrl of scriptUrls.slice(0, 15)) {
70
- if (cumulativeSizeKB >= maxTotalSizeKB) {
71
- console.warn(`[W3PK Inspect] Reached total size limit of ${maxTotalSizeKB} KB - stopping collection`);
72
- markdown += `
73
- **Note:** Collection stopped - reached ${maxTotalSizeKB} KB limit
74
- `;
75
- break;
76
- }
77
- try {
78
- const response = await fetch(scriptUrl);
79
- if (!response.ok) continue;
80
- const content = await response.text();
81
- const snippets = extractTransactionSnippets(content);
82
- if (snippets && !snippets.includes("No transaction code found")) {
83
- const snippetSize = new Blob([snippets]).size / 1024;
84
- if (cumulativeSizeKB + snippetSize > maxTotalSizeKB) {
85
- console.warn(`[W3PK Inspect] Skipping ${new URL(scriptUrl).pathname} - would exceed total size limit`);
86
- break;
87
- }
88
- markdown += `### \`${new URL(scriptUrl).pathname}\`
89
-
90
- `;
91
- markdown += "```javascript\n";
92
- markdown += snippets;
93
- markdown += "\n```\n\n---\n\n";
94
- totalSnippets++;
95
- cumulativeSizeKB += snippetSize;
96
- }
97
- } catch (error) {
98
- }
99
- }
100
- if (totalSnippets === 0) {
101
- markdown += `No transaction-related code found in JavaScript files.
102
- `;
103
- }
104
- return markdown;
105
- }
106
- async function inspect(options = {}) {
107
- if (typeof window === "undefined") {
108
- throw new Error(
109
- "Browser inspect() can only be called in browser environments. For Node.js, use the CLI or Node.js API."
110
- );
111
- }
112
- const {
113
- appUrl = window.location.origin,
114
- rukhUrl = "https://rukh.w3hc.org",
115
- context = "w3pk",
116
- model = "anthropic",
117
- focusMode = "transactions",
118
- maxTotalSizeKB = 100
119
- } = options;
120
- console.log("[W3PK Inspect] Starting inspection of", appUrl);
121
- console.log("[W3PK Inspect] Focus mode:", focusMode);
122
- console.log("[W3PK Inspect] Max total size:", maxTotalSizeKB, "KB");
123
- const sourceMarkdown = await fetchAppSource(appUrl, maxTotalSizeKB);
124
- console.log("[W3PK Inspect] Collected source code, sending to Rukh API...");
125
- const message = "Analyze this web application and provide a security report listing all transaction and signing methods.";
126
- const formData = new FormData();
127
- formData.append("message", message);
128
- formData.append("model", model);
129
- formData.append("context", context);
130
- const blob = new Blob([sourceMarkdown], { type: "text/markdown" });
131
- formData.append("file", blob, "app-source.md");
132
- const response = await fetch(`${rukhUrl}/ask`, {
133
- method: "POST",
134
- body: formData
135
- });
136
- if (!response.ok) {
137
- const error = await response.text();
138
- throw new Error(`Rukh API error: ${response.status} - ${error}`);
139
- }
140
- const data = await response.json();
141
- const report = data.output || data.response || data.message || JSON.stringify(data);
142
- console.log("[W3PK Inspect] Analysis complete!");
143
- const scripts = Array.from(document.querySelectorAll("script[src]"));
144
- const analyzedFiles = scripts.map((script) => new URL(script.src).pathname).filter((src) => src && !src.includes("node_modules"));
145
- return {
146
- report,
147
- analyzedFiles,
148
- appUrl
149
- };
150
- }
151
- async function inspectNow(options) {
152
- console.log("\u{1F50D} W3PK Security Inspection Starting...\n");
153
- try {
154
- const result = await inspect(options);
155
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
156
- console.log("\u{1F4CB} SECURITY REPORT");
157
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n");
158
- console.log(result.report);
159
- console.log("\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
160
- console.log(
161
- `\u2705 Analyzed ${result.analyzedFiles.length} files from ${result.appUrl}`
162
- );
163
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
164
- } catch (error) {
165
- console.error("\u274C Inspection failed:", error);
166
- throw error;
167
- }
168
- }
169
- export {
170
- inspect,
171
- inspectNow
172
- };
173
- //# sourceMappingURL=browser.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/inspect/browser.ts"],"sourcesContent":["/**\n * Browser Inspection Module\n *\n * Provides client-side code inspection capabilities for analyzing running web3 applications.\n * Fetches JavaScript sources from the current page and analyzes transaction/signing patterns\n * to generate security reports via the Rukh API.\n *\n * This module is designed to be used directly in the browser console or embedded in\n * web applications to help end-users understand the security posture of the apps they use.\n *\n * @module inspect/browser\n */\n\n/**\n * Configuration options for browser-based application inspection\n */\nexport interface BrowserInspectOptions {\n /**\n * The origin/URL of the app to inspect\n * @default window.location.origin\n */\n appUrl?: string;\n\n /**\n * Rukh API endpoint\n * @default 'https://rukh.w3hc.org'\n */\n rukhUrl?: string;\n\n /**\n * Context to use for analysis\n * @default 'w3pk'\n */\n context?: string;\n\n /**\n * AI model to use\n * @default 'anthropic'\n */\n model?: \"anthropic\" | \"mistral\" | \"openai\";\n\n /**\n * Focus mode for analysis\n * @default 'transactions'\n */\n focusMode?: \"transactions\" | \"all\";\n\n /**\n * Maximum total size in KB for all collected code (prevents exceeding API token limits)\n * @default 100\n */\n maxTotalSizeKB?: number;\n}\n\n/**\n * Result of a browser-based inspection\n */\nexport interface BrowserInspectResult {\n /**\n * The security report markdown generated by Rukh API\n */\n report: string;\n\n /**\n * List of JavaScript file paths that were analyzed\n */\n analyzedFiles: string[];\n\n /**\n * The application URL that was inspected\n */\n appUrl: string;\n}\n\n/**\n * Extracts transaction-related code snippets from JavaScript content\n *\n * Scans JavaScript code for keywords related to signing, transactions, and web3 operations,\n * then extracts relevant code snippets with surrounding context.\n *\n * @param content - The JavaScript source code to analyze\n * @param maxLength - Maximum length of extracted snippets in characters\n * @returns Extracted code snippets or a message if no relevant code found\n * @internal\n */\nfunction extractTransactionSnippets(\n content: string,\n maxLength: number = 30000,\n): string {\n const keywords = [\n \"signMessage\",\n \"signTypedData\",\n \"sign(\",\n \"signature\",\n \"sendTransaction\",\n \"transaction\",\n \"eth_sign\",\n \"Contract(\",\n \"ethers.Contract\",\n \"new Contract\",\n \"w3pk\",\n \"Web3Passkey\",\n \"useW3PK\",\n \"wallet\",\n \"signer\",\n \"provider\",\n \"authorization\",\n \"delegation\",\n \"EIP7702\",\n ];\n\n const lines = content.split(\"\\n\");\n const relevantLines: string[] = [];\n const maxLines = 500;\n\n for (let i = 0; i < lines.length && relevantLines.length < maxLines; i++) {\n const line = lines[i];\n const lowerLine = line.toLowerCase();\n\n if (keywords.some((kw) => lowerLine.includes(kw.toLowerCase()))) {\n const start = Math.max(0, i - 2);\n const end = Math.min(lines.length, i + 3);\n\n for (let j = start; j < end; j++) {\n if (!relevantLines.includes(lines[j])) {\n relevantLines.push(lines[j]);\n }\n }\n }\n }\n\n const snippet = relevantLines.join(\"\\n\");\n\n if (snippet.length > maxLength) {\n return snippet.substring(0, maxLength) + \"\\n\\n// ... (truncated)\";\n }\n\n return snippet || \"// No transaction code found\";\n}\n\n/**\n * Fetches JavaScript source code from the currently running application\n *\n * Discovers and fetches all script tags in the current page, extracts transaction-related\n * snippets, and formats them as markdown for analysis.\n *\n * @param appUrl - The base URL of the application being inspected\n * @param maxTotalSizeKB - Maximum total size in KB for all collected code\n * @returns Markdown-formatted source code with transaction-related snippets\n * @internal\n */\nasync function fetchAppSource(appUrl: string, maxTotalSizeKB: number = 100): Promise<string> {\n let markdown = `# Application Code Analysis\\n\\n`;\n markdown += `**App URL:** ${appUrl}\\n\\n`;\n markdown += `**Note:** Only transaction-related code snippets shown\\n\\n`;\n markdown += `---\\n\\n`;\n\n const scripts = Array.from(document.querySelectorAll(\"script[src]\"));\n const scriptUrls = scripts\n .map((script) => (script as HTMLScriptElement).src)\n .filter(\n (src) =>\n src &&\n !src.includes(\"node_modules\") &&\n !src.includes(\"chrome-extension\"),\n );\n\n markdown += `## JavaScript Files (${scriptUrls.length})\\n\\n`;\n\n let totalSnippets = 0;\n let cumulativeSizeKB = 0;\n const maxTotalBytes = maxTotalSizeKB * 1024;\n\n for (const scriptUrl of scriptUrls.slice(0, 15)) {\n // Check if we've reached the size limit\n if (cumulativeSizeKB >= maxTotalSizeKB) {\n console.warn(`[W3PK Inspect] Reached total size limit of ${maxTotalSizeKB} KB - stopping collection`);\n markdown += `\\n**Note:** Collection stopped - reached ${maxTotalSizeKB} KB limit\\n`;\n break;\n }\n\n try {\n const response = await fetch(scriptUrl);\n if (!response.ok) continue;\n\n const content = await response.text();\n const snippets = extractTransactionSnippets(content);\n\n if (snippets && !snippets.includes(\"No transaction code found\")) {\n const snippetSize = new Blob([snippets]).size / 1024;\n\n // Check if adding this snippet would exceed the limit\n if (cumulativeSizeKB + snippetSize > maxTotalSizeKB) {\n console.warn(`[W3PK Inspect] Skipping ${new URL(scriptUrl).pathname} - would exceed total size limit`);\n break;\n }\n\n markdown += `### \\`${new URL(scriptUrl).pathname}\\`\\n\\n`;\n markdown += \"```javascript\\n\";\n markdown += snippets;\n markdown += \"\\n```\\n\\n---\\n\\n\";\n totalSnippets++;\n cumulativeSizeKB += snippetSize;\n }\n } catch (error) {\n // Skip files that can't be fetched\n }\n }\n\n if (totalSnippets === 0) {\n markdown += `No transaction-related code found in JavaScript files.\\n`;\n }\n\n return markdown;\n}\n\n/**\n * Inspects the currently running web application and returns a security report\n *\n * This function can be called by end-users in their browser console to analyze\n * the security of the web application they're currently using.\n *\n * @param options - Configuration options\n * @returns A security report analyzing transaction and signing methods\n *\n * @example\n * ```typescript\n * // In browser console or app code:\n * import { inspect } from 'w3pk';\n *\n * const report = await inspect();\n * console.log(report.report);\n * ```\n *\n * @example\n * ```typescript\n * // With custom options:\n * const report = await inspect({\n * appUrl: 'https://w3pk.w3hc.org',\n * model: 'anthropic',\n * focusMode: 'transactions'\n * });\n * ```\n */\nexport async function inspect(\n options: BrowserInspectOptions = {},\n): Promise<BrowserInspectResult> {\n // Check if running in browser\n if (typeof window === \"undefined\") {\n throw new Error(\n \"Browser inspect() can only be called in browser environments. For Node.js, use the CLI or Node.js API.\",\n );\n }\n\n const {\n appUrl = window.location.origin,\n rukhUrl = \"https://rukh.w3hc.org\",\n context = \"w3pk\",\n model = \"anthropic\",\n focusMode = \"transactions\",\n maxTotalSizeKB = 100,\n } = options;\n\n console.log(\"[W3PK Inspect] Starting inspection of\", appUrl);\n console.log(\"[W3PK Inspect] Focus mode:\", focusMode);\n console.log(\"[W3PK Inspect] Max total size:\", maxTotalSizeKB, \"KB\");\n\n // Fetch and analyze source code\n const sourceMarkdown = await fetchAppSource(appUrl, maxTotalSizeKB);\n\n console.log(\"[W3PK Inspect] Collected source code, sending to Rukh API...\");\n\n // Prepare request to Rukh API\n const message =\n \"Analyze this web application and provide a security report listing all transaction and signing methods.\";\n\n const formData = new FormData();\n formData.append(\"message\", message);\n formData.append(\"model\", model);\n formData.append(\"context\", context);\n\n // Create blob from markdown\n const blob = new Blob([sourceMarkdown], { type: \"text/markdown\" });\n formData.append(\"file\", blob, \"app-source.md\");\n\n // Send to Rukh API\n const response = await fetch(`${rukhUrl}/ask`, {\n method: \"POST\",\n body: formData,\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Rukh API error: ${response.status} - ${error}`);\n }\n\n const data = await response.json();\n const report =\n data.output || data.response || data.message || JSON.stringify(data);\n\n console.log(\"[W3PK Inspect] Analysis complete!\");\n\n // Extract script URLs for analyzedFiles\n const scripts = Array.from(document.querySelectorAll(\"script[src]\"));\n const analyzedFiles = scripts\n .map((script) => new URL((script as HTMLScriptElement).src).pathname)\n .filter((src) => src && !src.includes(\"node_modules\"));\n\n return {\n report,\n analyzedFiles,\n appUrl,\n };\n}\n\n/**\n * Quick inspection helper that logs the report to console\n * Perfect for use in browser DevTools console\n *\n * @example\n * ```javascript\n * // In browser console:\n * await w3pk.inspectNow()\n * ```\n */\nexport async function inspectNow(\n options?: BrowserInspectOptions,\n): Promise<void> {\n console.log(\"🔍 W3PK Security Inspection Starting...\\n\");\n\n try {\n const result = await inspect(options);\n\n console.log(\"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\");\n console.log(\"📋 SECURITY REPORT\");\n console.log(\"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n\");\n console.log(result.report);\n console.log(\"\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\");\n console.log(\n `✅ Analyzed ${result.analyzedFiles.length} files from ${result.appUrl}`,\n );\n console.log(\"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\");\n } catch (error) {\n console.error(\"❌ Inspection failed:\", error);\n throw error;\n }\n}\n"],"mappings":";AAq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AA2C;AAEvD,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ,OAAO;AAEpC,YAAQ,IAAI,kPAA0C;AACtD,YAAQ,IAAI,2BAAoB;AAChC,YAAQ,IAAI,oPAA4C;AACxD,YAAQ,IAAI,OAAO,MAAM;AACzB,YAAQ,IAAI,oPAA4C;AACxD,YAAQ;AAAA,MACN,mBAAc,OAAO,cAAc,MAAM,eAAe,OAAO,MAAM;AAAA,IACvE;AACA,YAAQ,IAAI,kPAA0C;AAAA,EACxD,SAAS,OAAO;AACd,YAAQ,MAAM,6BAAwB,KAAK;AAC3C,UAAM;AAAA,EACR;AACF;","names":[]}
@@ -1 +0,0 @@
1
- export { BrowserInspectOptions, BrowserInspectResult, inspect, inspectNow } from './browser.mjs';
@@ -1 +0,0 @@
1
- export { BrowserInspectOptions, BrowserInspectResult, inspect, inspectNow } from './browser.js';
@@ -1,196 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/inspect/index.ts
21
- var inspect_exports = {};
22
- __export(inspect_exports, {
23
- inspect: () => inspect,
24
- inspectNow: () => inspectNow
25
- });
26
- module.exports = __toCommonJS(inspect_exports);
27
-
28
- // src/inspect/browser.ts
29
- function extractTransactionSnippets(content, maxLength = 3e4) {
30
- const keywords = [
31
- "signMessage",
32
- "signTypedData",
33
- "sign(",
34
- "signature",
35
- "sendTransaction",
36
- "transaction",
37
- "eth_sign",
38
- "Contract(",
39
- "ethers.Contract",
40
- "new Contract",
41
- "w3pk",
42
- "Web3Passkey",
43
- "useW3PK",
44
- "wallet",
45
- "signer",
46
- "provider",
47
- "authorization",
48
- "delegation",
49
- "EIP7702"
50
- ];
51
- const lines = content.split("\n");
52
- const relevantLines = [];
53
- const maxLines = 500;
54
- for (let i = 0; i < lines.length && relevantLines.length < maxLines; i++) {
55
- const line = lines[i];
56
- const lowerLine = line.toLowerCase();
57
- if (keywords.some((kw) => lowerLine.includes(kw.toLowerCase()))) {
58
- const start = Math.max(0, i - 2);
59
- const end = Math.min(lines.length, i + 3);
60
- for (let j = start; j < end; j++) {
61
- if (!relevantLines.includes(lines[j])) {
62
- relevantLines.push(lines[j]);
63
- }
64
- }
65
- }
66
- }
67
- const snippet = relevantLines.join("\n");
68
- if (snippet.length > maxLength) {
69
- return snippet.substring(0, maxLength) + "\n\n// ... (truncated)";
70
- }
71
- return snippet || "// No transaction code found";
72
- }
73
- async function fetchAppSource(appUrl, maxTotalSizeKB = 100) {
74
- let markdown = `# Application Code Analysis
75
-
76
- `;
77
- markdown += `**App URL:** ${appUrl}
78
-
79
- `;
80
- markdown += `**Note:** Only transaction-related code snippets shown
81
-
82
- `;
83
- markdown += `---
84
-
85
- `;
86
- const scripts = Array.from(document.querySelectorAll("script[src]"));
87
- const scriptUrls = scripts.map((script) => script.src).filter(
88
- (src) => src && !src.includes("node_modules") && !src.includes("chrome-extension")
89
- );
90
- markdown += `## JavaScript Files (${scriptUrls.length})
91
-
92
- `;
93
- let totalSnippets = 0;
94
- let cumulativeSizeKB = 0;
95
- const maxTotalBytes = maxTotalSizeKB * 1024;
96
- for (const scriptUrl of scriptUrls.slice(0, 15)) {
97
- if (cumulativeSizeKB >= maxTotalSizeKB) {
98
- console.warn(`[W3PK Inspect] Reached total size limit of ${maxTotalSizeKB} KB - stopping collection`);
99
- markdown += `
100
- **Note:** Collection stopped - reached ${maxTotalSizeKB} KB limit
101
- `;
102
- break;
103
- }
104
- try {
105
- const response = await fetch(scriptUrl);
106
- if (!response.ok) continue;
107
- const content = await response.text();
108
- const snippets = extractTransactionSnippets(content);
109
- if (snippets && !snippets.includes("No transaction code found")) {
110
- const snippetSize = new Blob([snippets]).size / 1024;
111
- if (cumulativeSizeKB + snippetSize > maxTotalSizeKB) {
112
- console.warn(`[W3PK Inspect] Skipping ${new URL(scriptUrl).pathname} - would exceed total size limit`);
113
- break;
114
- }
115
- markdown += `### \`${new URL(scriptUrl).pathname}\`
116
-
117
- `;
118
- markdown += "```javascript\n";
119
- markdown += snippets;
120
- markdown += "\n```\n\n---\n\n";
121
- totalSnippets++;
122
- cumulativeSizeKB += snippetSize;
123
- }
124
- } catch (error) {
125
- }
126
- }
127
- if (totalSnippets === 0) {
128
- markdown += `No transaction-related code found in JavaScript files.
129
- `;
130
- }
131
- return markdown;
132
- }
133
- async function inspect(options = {}) {
134
- if (typeof window === "undefined") {
135
- throw new Error(
136
- "Browser inspect() can only be called in browser environments. For Node.js, use the CLI or Node.js API."
137
- );
138
- }
139
- const {
140
- appUrl = window.location.origin,
141
- rukhUrl = "https://rukh.w3hc.org",
142
- context = "w3pk",
143
- model = "anthropic",
144
- focusMode = "transactions",
145
- maxTotalSizeKB = 100
146
- } = options;
147
- console.log("[W3PK Inspect] Starting inspection of", appUrl);
148
- console.log("[W3PK Inspect] Focus mode:", focusMode);
149
- console.log("[W3PK Inspect] Max total size:", maxTotalSizeKB, "KB");
150
- const sourceMarkdown = await fetchAppSource(appUrl, maxTotalSizeKB);
151
- console.log("[W3PK Inspect] Collected source code, sending to Rukh API...");
152
- const message = "Analyze this web application and provide a security report listing all transaction and signing methods.";
153
- const formData = new FormData();
154
- formData.append("message", message);
155
- formData.append("model", model);
156
- formData.append("context", context);
157
- const blob = new Blob([sourceMarkdown], { type: "text/markdown" });
158
- formData.append("file", blob, "app-source.md");
159
- const response = await fetch(`${rukhUrl}/ask`, {
160
- method: "POST",
161
- body: formData
162
- });
163
- if (!response.ok) {
164
- const error = await response.text();
165
- throw new Error(`Rukh API error: ${response.status} - ${error}`);
166
- }
167
- const data = await response.json();
168
- const report = data.output || data.response || data.message || JSON.stringify(data);
169
- console.log("[W3PK Inspect] Analysis complete!");
170
- const scripts = Array.from(document.querySelectorAll("script[src]"));
171
- const analyzedFiles = scripts.map((script) => new URL(script.src).pathname).filter((src) => src && !src.includes("node_modules"));
172
- return {
173
- report,
174
- analyzedFiles,
175
- appUrl
176
- };
177
- }
178
- async function inspectNow(options) {
179
- console.log("\u{1F50D} W3PK Security Inspection Starting...\n");
180
- try {
181
- const result = await inspect(options);
182
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
183
- console.log("\u{1F4CB} SECURITY REPORT");
184
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n");
185
- console.log(result.report);
186
- console.log("\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
187
- console.log(
188
- `\u2705 Analyzed ${result.analyzedFiles.length} files from ${result.appUrl}`
189
- );
190
- console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
191
- } catch (error) {
192
- console.error("\u274C Inspection failed:", error);
193
- throw error;
194
- }
195
- }
196
- //# sourceMappingURL=index.js.map