From 6391b9ac75dd5ed9789f853507e3b59a824a89af Mon Sep 17 00:00:00 2001 From: unfunny Date: Thu, 22 Oct 2026 08:08:33 -0400 Subject: [PATCH] update SWBN generation, among other things --- .gitignore | 10 ++ BUILD.md | 93 ++++++++++++++++++ index.html | 19 +++- iwa-build.js | 199 +++++++++++++++++++++++++++----------- package-lock.json | 133 ++++++++++++++++++++++++- package.json | 6 +- public/iwa/manifest.json | 8 +- src/components/Editor.jsx | 8 +- src/mcp/client.js | 71 ++++++++++++++ vite.config.js | 7 +- 10 files changed, 484 insertions(+), 70 deletions(-) create mode 100644 BUILD.md create mode 100644 src/mcp/client.js diff --git a/.gitignore b/.gitignore index a547bf3..b721603 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,13 @@ dist-ssr *.njsproj *.sln *.sw? + +#private stuff +iwa_private_key.pem +iwa_public_key.pem +.env.local +.env +.env_local + +#junk +public/ diff --git a/BUILD.md b/BUILD.md new file mode 100644 index 0000000..c1cf18c --- /dev/null +++ b/BUILD.md @@ -0,0 +1,93 @@ +# Build System + +## Build Targets + +### 1. Default Build (Multi-file HTML) +```bash +npm run build +``` + +**Output:** +- `dist/index.html` (~4 KB) - Small HTML file +- `dist/assets/` - Separate CSS, JS, and font files +- Ready for web server hosting or IWA bundling + +### 2. IWA Build (Signed Web Bundle) +```bash +npm run build:iwa +# CI=true npm run build:iwa # Non-interactive mode (CI/CD) +# WEB_BUNDLE_SIGNING_PASSPHRASE=secret npm run build:iwa # Encrypted key +``` + +**Output:** +- `dist/dist.wbn` (~3.4 MB) - Unsigned web bundle +- `dist/dist.swbn` (~3.5 MB) - **Signed web bundle** for Chrome IWA +- `iwa_private_key.pem` - Private signing key (keep secure!) +- `iwa_public_key.pem` - Public key (IWA identity) + +### 3. Singlefile HTML Build +```bash +SINGLEFILE=1 npm run build +``` + +**Output:** `dist/index.html` (~3.8 MB single file) +- All assets inlined as data URIs +- Ready to open directly in browser (offline-capable) + +## Chrome IWA Installation + +After running `npm run build:iwa`: + +### Development Testing (Dev Mode Proxy) +```bash +# 1. Enable IWA Dev Mode flag in Chrome +chrome://flags/#enable-isolated-web-app-dev-mode + +# 2. Go to chrome://web-app-internals +# 3. Click "Install IWA with Dev Mode Proxy" +# 4. Enter URL: file:///home/unfunny/Source Files/AboveTheMark/dist/ +``` + +### Production Installation (Signed Bundle) +```bash +# 1. Enable IWA flag in Chrome +chrome://flags/#enable-isolated-web-app-dev-mode + +# 2. Go to chrome://web-app-internals +# 3. Click "Install IWA from Signed Web Bundle" +# 4. Browse to: dist/dist.swbn +``` + +### Information +Check `dist/iwa-info.txt` for: +- Web Bundle ID +- IWA Origin (`isolated-app://...`) +- Installation instructions + +## Build Files + +| File | Purpose | +|------|---------| +| `vite.config.js` | Vite configuration with build mode detection | +| `iwa-build.js` | IWA bundling and signing script | +| `index.html` | Main HTML entry point (with CSP headers) | +| `public/iwa/manifest.json` | PWA/IWA manifest | + +## Environment Variables + +- `SINGLEFILE=1` - Build singlefile HTML +- `IWA=1` - IWA build mode (used by vite.config.js) +- `WEB_BUNDLE_SIGNING_PASSPHRASE` - Encrypt private key (optional) +- `CI=true` - Non-interactive mode (use for CI/CD) + +## Signing Keys + +Keys are generated in project root: +- `iwa_private_key.pem` - Keep this secure! Never commit to version control if storing unencrypted. +- `iwa_public_key.pem` - Safe to share, used to verify bundle authenticity + +To generate keys manually: +```bash +openssl genpkey -algorithm Ed25519 -out iwa_private_key.pem +openssl pkey -in iwa_private_key.pem -pubout -out iwa_public_key.pem +``` diff --git a/index.html b/index.html index 03b929c..567b43a 100644 --- a/index.html +++ b/index.html @@ -6,7 +6,24 @@ - + + + + + + + AboveTheMark - GFM Editor diff --git a/iwa-build.js b/iwa-build.js index e2be6c5..6c4b231 100755 --- a/iwa-build.js +++ b/iwa-build.js @@ -1,61 +1,152 @@ #!/usr/bin/env node + /** - * IWA (Installer for Web Applications) Build Script - * Generates Chrome extension manifest and required files for deployment. - * - * Usage: npm run build:iwa + * IWA Build Script + * Bundles and signs the web app for Chrome Isolated Web Apps */ -import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'; -import { join, dirname } from 'path'; -import { fileURLToPath } from 'url'; +import { execSync } from 'child_process'; +import fs from 'fs'; -const __dirname = join( - dirname(fileURLToPath(import.meta.url)), - '.' -); +const DIST_DIR = './dist'; +const WBN_OUTPUT = `${DIST_DIR}/dist.wbn`; +const SWBN_OUTPUT = `${DIST_DIR}/dist.swbn`; +const PRIVATE_KEY_PATH = './iwa_private_key.pem'; +const PUBLIC_KEY_PATH = './iwa_public_key.pem'; +const INFO_FILE = `${DIST_DIR}/iwa-info.txt`; -// Read existing manifest for reference -const distManifestPath = join(__dirname, 'dist', 'manifest.json'); -try { - const distManifest = JSON.parse(readFileSync(distManifestPath, 'utf-8')); - - // Generate IWA manifest with Chrome-specific fields - const iwaManifest = { - name: distManifest.name, - short_name: distManifest.short_name, - description: distManifest.description, - version: distManifest.version || '1.0.0', - start_url: '../index.html', - display: distManifest.display || 'standalone', - default_locale: 'en-US', - installable: true, - background_color: distManifest.background_color, - theme_color: distManifest.theme_color, - icons: distManifest.icons.map(icon => ({ - src: icon.src, - sizes: icon.sizes, - type: icon.type, - purpose: 'any maskable' - })) - }; - - // Write IWA manifest - const iwaDir = join(__dirname, 'public', 'iwa'); - if (!existsSync(iwaDir)) { - mkdirSync(iwaDir, { recursive: true }); - } - - writeFileSync(join(iwaDir, 'manifest.json'), JSON.stringify(iwaManifest, null, 2)); - - console.log('✅ IWA manifest generated at:', join(iwaDir, 'manifest.json')); - console.log(''); - console.log('📦 Deployment instructions:'); - console.log(' 1. Copy /public/iwa to your package directory (e.g., /usr/local/share/applications/iwa/)'); - console.log(' 2. The manifest references index.html which loads from the main dist/index.html'); - console.log(' 3. Chrome will detect this and offer installation via the Chrome Store'); - -} catch (error) { - console.error('❌ Build failed:', error.message); - process.exit(1); +function log(message) { + console.log(`[IWA-Build] ${message}`); } + +if (process.env.IWA !== '1') { + log('This script runs as part of `npm run build:iwa`. Exiting.'); + process.exit(0); +} + +log('Starting IWA build...'); +log(`Working directory: ${DIST_DIR}`); + +if (!fs.existsSync(DIST_DIR)) { + throw new Error('Vite build failed. dist/ directory not found.'); +} + +const files = fs.readdirSync(DIST_DIR).sort(); +log(`Found ${files.length} files in dist/:`); + +// Generate keys if they don't exist +if (!fs.existsSync(PRIVATE_KEY_PATH)) { + log('\nGenerating new signing keys...'); + try { + execSync('openssl genpkey -algorithm Ed25519 -out ' + PRIVATE_KEY_PATH, { + stdio: 'inherit', + env: { ...process.env, OPENSSL_CONF: '' } + }); + log('Private key created:', PRIVATE_KEY_PATH); + } catch (err) { + throw new Error(`Failed to generate private key: ${err.message}`); + } + + const privateKeyContent = fs.readFileSync(PRIVATE_KEY_PATH, 'utf8'); + try { + execSync(`openssl pkey -in ${PRIVATE_KEY_PATH} -pubout -out ${PUBLIC_KEY_PATH}`, { + stdio: 'inherit', + env: { ...process.env, OPENSSL_CONF: '' } + }); + log('Public key created:', PUBLIC_KEY_PATH); + } catch (err) { + throw new Error(`Failed to extract public key: ${err.message}`); + } +} else { + log('\nUsing existing signing keys'); +} + +const publicKeyContent = fs.readFileSync(PUBLIC_KEY_PATH, 'utf8'); +log('\nPublic Key (IWA Identity):'); +console.log(publicKeyContent.trim()); + +let passphrase = process.env.WEB_BUNDLE_SIGNING_PASSPHRASE; +if (!passphrase) { + const isInteractive = !process.env.CI && !process.pipes?.length && process.stdin.isTTY; + + if (isInteractive) { + const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); + log('Enter passphrase to encrypt the signing key (or press Enter for unencrypted):'); + rl.on('close', () => { console.log('\n[Cancelled] Build cancelled.'); process.exit(0); }); + rl.question('', answer => { rl.close(); passphrase = answer; }); + } else { + log('[Non-interactive mode] Using unencrypted key'); + passphrase = ''; + } +} + +log('\n=== Bundling into unsigned web bundle ==='); +try { + execSync(`node node_modules/wbn/bin/wbn.js --dir ${DIST_DIR} -o ${WBN_OUTPUT}`, { stdio: 'inherit' }); + log('Unsigned bundle created:', WBN_OUTPUT); + const wbnStats = fs.statSync(WBN_OUTPUT); + log(`Size: ${(wbnStats.size / 1024).toFixed(2)} KB`); +} catch (err) { + throw new Error(`Failed to bundle: ${err.message}`); +} + +// Sign the bundle if passphrase provided, or always sign (unencrypted) +if (passphrase !== undefined) { + log('\n=== Signing web bundle ==='); + try { + let signArgs = `node node_modules/wbn-sign/bin/wbn-sign.js sign ${WBN_OUTPUT} ${PRIVATE_KEY_PATH} -o ${SWBN_OUTPUT}`; + if (passphrase && passphrase.length > 0) { + execSync(signArgs + ' -p "' + passphrase + '"', { stdio: 'inherit' }); + } else { + execSync(signArgs, { stdio: 'inherit' }); + } + log('Signed bundle created:', SWBN_OUTPUT); + const swbnStats = fs.statSync(SWBN_OUTPUT); + log(`Size: ${(swbnStats.size / 1024).toFixed(2)} KB`); + } catch (err) { + throw new Error(`Failed to sign bundle: ${err.message}`); + } +} else { + log('[No signing] Skipping signature generation'); +} + +// Extract bundle ID from the SWBN file or use public key +let bundleId = publicKeyContent.trim().replace(/-----[\s\S]*------/g, '').trim(); +bundleId = bundleId.replace(/\s+/g, ''); +const origin = `isolated-app://${bundleId}/`; + +log('\n=== IWA Information ==='); +console.log(`Web Bundle ID: ${bundleId}`); +console.log(`IWA Origin: ${origin}`); +log('Save these values for Chrome Web App Internals'); + +// Write to info file +const infoContent = `Web Bundle ID: ${bundleId} +IWA Origin: ${origin} + +To install your IWA: +1. Open Chrome (v120+) and enable: chrome://flags/#enable-isolated-web-app-dev-mode +2. Go to chrome://web-app-internals +3. Click "Install IWA from Signed Web Bundle" +4. Browse to the dist.swbn file + +Alternatively, use Dev Mode Proxy for development: +3. Click "Install IWA with Dev Mode Proxy" +4. Enter URL: file://${DIST_DIR}/ + +For testing without signing (unsigned bundle): +- Use: ${WBN_OUTPUT} +`; +fs.writeFileSync(INFO_FILE, infoContent); +log(`Info written to: ${INFO_FILE}`); + +log('\n=== Build Complete ==='); +log(`Output files:`); +console.log(` - ${SWBN_OUTPUT} (signed web bundle)`); +if (fs.existsSync(WBN_OUTPUT)) { + console.log(` - ${WBN_OUTPUT} (unsigned web bundle)`); +} +console.log(` - ${PRIVATE_KEY_PATH} (private key - keep secure!)`); +console.log(` - ${PUBLIC_KEY_PATH} (public key - IWA identity)`); + +log('\nIWA is ready to install!'); diff --git a/package-lock.json b/package-lock.json index dc0242e..d093b01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,9 @@ "react": "^18.3.1", "react-dom": "^18.3.1", "rehype-katex": "^7.0.1", - "remark-math": "^6.0.0" + "remark-math": "^6.0.0", + "wbn": "^0.0.9", + "wbn-sign": "^0.3.3" }, "devDependencies": { "@types/react": "^18.3.18", @@ -1509,6 +1511,18 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/base32-encode": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base32-encode/-/base32-encode-2.0.0.tgz", + "integrity": "sha512-mlmkfc2WqdDtMl/id4qm3A7RjW6jxcbAoMjdRmsPiwQP0ufD4oXItYMnPgVHe80lnAIy+1xwzhHE1s4FoIceSw==", + "license": "MIT", + "dependencies": { + "to-data-view": "^2.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -1633,6 +1647,15 @@ ], "license": "CC-BY-4.0" }, + "node_modules/cborg": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/cborg/-/cborg-1.10.2.tgz", + "integrity": "sha512-b3tFPA9pUr2zCUiCfRd2+wok2/LBSNUMKOuRRok+WlvvAgEt/PlbgPTsZUcwCOs53IJvLgTp0eotwtosE6njug==", + "license": "Apache-2.0", + "bin": { + "cborg": "cli.js" + } + }, "node_modules/ccount": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", @@ -3508,6 +3531,18 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/minimalistic-assert": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", @@ -3520,6 +3555,15 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/mute-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-1.0.0.tgz", + "integrity": "sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA==", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/nanoid": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.2.tgz", @@ -3619,7 +3663,6 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, "license": "ISC" }, "node_modules/picomatch": { @@ -3761,6 +3804,18 @@ "node": ">=0.10.0" } }, + "node_modules/read": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/read/-/read-2.1.0.tgz", + "integrity": "sha512-bvxi1QLJHcaywCAEsAk4DG3nVoqiY2Csps3qzWalhj5hFqRn1d/OixkFXtLO1PrgHUcAP0FNaSY/5GYNfENFFQ==", + "license": "ISC", + "dependencies": { + "mute-stream": "~1.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/readable-stream": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", @@ -4300,6 +4355,15 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/to-data-view": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-data-view/-/to-data-view-2.0.0.tgz", + "integrity": "sha512-RGEM5KqlPHr+WVTPmGNAXNeFEmsBnlkxXaIfEpUYV0AST2Z5W1EGq9L/MENFrMMmL2WQr1wjkmZy/M92eKhjYA==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -4647,6 +4711,71 @@ } } }, + "node_modules/wbn": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/wbn/-/wbn-0.0.9.tgz", + "integrity": "sha512-q/nuD6VVfOQOpQF9x6g1imfyzSxhHiRcABtTddD2CN/E+N+yfzf5G6XLHIYaajI7VMgSF8iXGsW6/MFc7Onrdg==", + "license": "W3C-20150513", + "dependencies": { + "cborg": "^1.9.4", + "commander": "^4.0.1", + "mime": "^2.4.4" + }, + "bin": { + "wbn": "bin/wbn.js" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/wbn-sign": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/wbn-sign/-/wbn-sign-0.3.3.tgz", + "integrity": "sha512-tJbQIzCwIz0XjGOEwQnQcNTY0dar5VTDji3GSNwlFBVEm1RyBYZELIz1/ki3AsbdcNPIkK/HKEzWMdgAWD8wPQ==", + "license": "W3C-20150513", + "dependencies": { + "base32-encode": "^2.0.0", + "cborg": "^4.2.14", + "commander": "^14.0.0", + "picocolors": "^1.1.1", + "read": "^2.0.0" + }, + "bin": { + "wbn-dump-id": "bin/wbn-dump-id.js", + "wbn-sign": "bin/wbn-sign.js" + }, + "engines": { + "node": ">= 22.13.0", + "npm": ">= 10.0.0" + } + }, + "node_modules/wbn-sign/node_modules/cborg": { + "version": "4.5.8", + "resolved": "https://registry.npmjs.org/cborg/-/cborg-4.5.8.tgz", + "integrity": "sha512-6/viltD51JklRhq4L7jC3zgy6gryuG5xfZ3kzpE+PravtyeQLeQmCYLREhQH7pWENg5pY4Yu/XCd6a7dKScVlw==", + "license": "Apache-2.0", + "bin": { + "cborg": "lib/bin.js" + } + }, + "node_modules/wbn-sign/node_modules/commander": { + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/wbn/node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, "node_modules/web-namespaces": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz", diff --git a/package.json b/package.json index 333dde5..9d13d24 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "dev": "vite", "build": "vite build", "build:single": "SINGLEFILE=1 vite build", - "build:iwa": "npm run build && node iwa-build.js", + "build:iwa": "bash -c 'IWA=1 npm run build && IWA=1 node iwa-build.js'", "preview": "vite preview" }, "dependencies": { @@ -21,7 +21,9 @@ "react": "^18.3.1", "react-dom": "^18.3.1", "rehype-katex": "^7.0.1", - "remark-math": "^6.0.0" + "remark-math": "^6.0.0", + "wbn": "^0.0.9", + "wbn-sign": "^0.3.3" }, "devDependencies": { "@types/react": "^18.3.18", diff --git a/public/iwa/manifest.json b/public/iwa/manifest.json index 5caf43b..2b74883 100644 --- a/public/iwa/manifest.json +++ b/public/iwa/manifest.json @@ -3,7 +3,7 @@ "short_name": "AboveTheMark", "description": "GitHub Flavored Markdown editor with LaTeX, SVG, PDF and DOCX support", "version": "1.0.0", - "start_url": "../index.html", + "start_url": "/index.html", "display": "standalone", "default_locale": "en-US", "installable": true, @@ -11,10 +11,10 @@ "theme_color": "#0969da", "icons": [ { - "src": "favicon.svg", - "sizes": "any", + "src": "../favicon.svg", + "sizes": "512x512", "type": "image/svg+xml", "purpose": "any maskable" } ] -} \ No newline at end of file +} diff --git a/src/components/Editor.jsx b/src/components/Editor.jsx index 62bf628..2a0913b 100644 --- a/src/components/Editor.jsx +++ b/src/components/Editor.jsx @@ -1,9 +1,10 @@ -import React, { useMemo } from 'react'; +import React, { useMemo, useState, useEffect } from 'react'; import MDEditor from '@uiw/react-md-editor'; import remarkMath from 'remark-math'; import rehypeKatex from 'rehype-katex'; import katex from 'katex'; import 'katex/dist/katex.css'; +import { MCPClient } from '../mcp/client'; /** * Custom Code component that handles: @@ -16,9 +17,6 @@ const CodeRenderer = ({ node, className, children, ...props }) => { const match = /language-(\w+)/.exec(className || ''); const language = match ? match[1].toLowerCase() : ''; - // react-markdown v9+ removed the `inline` prop. Language-tagged fenced - // blocks always carry a `language-*` className, which is sufficient to - // distinguish the special KaTeX / SVG blocks from inline code. if (language === 'katex' || language === 'math') { try { const html = katex.renderToString(codeString, { @@ -41,7 +39,6 @@ const CodeRenderer = ({ node, className, children, ...props }) => { } } - // Render SVG live diagram if (language === 'svg') { return (
@@ -104,7 +101,6 @@ export default function Editor({ } }), []); - // Handle drag and drop over the editor const handleDragOver = (e) => { e.preventDefault(); e.stopPropagation(); diff --git a/src/mcp/client.js b/src/mcp/client.js new file mode 100644 index 0000000..96ecbe6 --- /dev/null +++ b/src/mcp/client.js @@ -0,0 +1,71 @@ +export class MCPClient { + constructor() { + this.socket = null; + this.isConnected = false; + this.messages = []; + } + + async connect(remoteAddress, remotePort) { + if (typeof TCPSocket === 'undefined') { + console.error('TCPSocket is not supported in this browser.'); + return false; + } + + try { + const tcpSocket = new TCPSocket(remoteAddress, remotePort, { + keepAlive: true, + keepAliveDelay: 720000 + }); + + const { readable, writable } = await tcpSocket.opened; + this.socket = tcpSocket; + + this.isConnected = true; + console.log(`Connected to MCP server at ${remoteAddress}:${remotePort}`); + + this.setupReader(readable); + return true; + } catch (error) { + console.error('Failed to connect to MCP server:', error); + return false; + } + } + + setupReader(readable) { + const reader = readable.getReader(); + (async () => { + while (true) { + const { value, done } = await reader.read(); + if (done) break; + const message = new TextDecoder().decode(value); + console.log('Received from MCP:', message); + // Handle incoming JSON-RPC messages + } + })(); + } + + async sendRequest(method, params = {}) { + if (!this.isConnected) return; + + const request = { + jsonrpc: "2.0", + id: Date.now(), + method, + params + }; + + const encoder = new TextEncoder(); + const buffer = encoder.encode(JSON.stringify(request)); + const writer = this.writable.getWriter(); + await writer.write(buffer); + writer.releaseLock(); + } + + disconnect() { + if (this.socket) { + this.socket.close(); + this.isConnected = false; + } + } +} + diff --git a/vite.config.js b/vite.config.js index 0c87357..1f842aa 100644 --- a/vite.config.js +++ b/vite.config.js @@ -7,6 +7,9 @@ const singleFile = process.env.SINGLEFILE === '1'; const iwaBuild = process.env.IWA === '1'; export default defineConfig({ + define: { + __IWA__: JSON.stringify(iwaBuild), + }, plugins: [react(), ...(singleFile ? [viteSingleFile()] : [])], server: { host: true, @@ -34,5 +37,7 @@ export default defineConfig({ 'remark-math', 'file-saver' ] - } + }, + // Add CSP and other headers required for IWA after build + base: './', });