// NoEyes documentation example. Node 24+, playwright 1.62.1 and its Chromium. import { createRequire } from 'node:module'; import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; const { chromium } = createRequire(import.meta.url)(process.env.NOEYES_PLAYWRIGHT_MODULE || 'playwright'); export async function runAgent({ provider, userDataDir, mode = 'read', keyword, allowSetup = false, expectedKeyFile, historyChatId, historyEventId, origin = 'https://noeyes.work', launch = {} }) { if (!['read', 'messaging', 'restart-check'].includes(mode)) throw Error('Unknown mode'); const searchTerm = typeof keyword === 'string' ? keyword.trim() : ''; if (mode === 'read' && !searchTerm) throw Error('Read mode requires a non-empty search keyword'); const address = mode === 'read' ? '' : (await provider?.request({ method: 'eth_accounts', params: [] }))?.[0]?.toLowerCase(); if (mode !== 'read' && !/^0x[a-f0-9]{40}$/.test(address || '')) throw Error('Signer must expose the authorized wallet'); const context = await chromium.launchPersistentContext(resolve(userDataDir), { headless: true, ...launch }); try { const page = await context.newPage(); const base = new URL(origin); if (base.protocol !== 'https:' && base.hostname !== '127.0.0.1') throw Error('HTTPS origin required'); await page.goto(base.origin + '/docs/headless/', { waitUntil: 'load' }); await page.exposeBinding('authorizedSign', async ({ frame }, input) => { if (mode === 'read' || frame !== page.mainFrame() || new URL(frame.url()).origin !== base.origin) { throw Error('Signing is unavailable in this context'); } if (input.method !== 'personal_sign' || !Array.isArray(input.params) || input.params.length !== 2 || String(input.params[1]).toLowerCase() !== address || typeof input.params[0] !== 'string') { throw Error('Unsupported signing request'); } // The protected provider enforces the operator's action and signing policy. return provider.request(input); }); await page.addScriptTag({ url: base.origin + '/noeyes.js' }); const expected = mode === 'restart-check' ? JSON.parse(await readFile(expectedKeyFile, 'utf8')) : null; const result = await page.evaluate(async ({ address, origin, mode, keyword, allowSetup, expected, historyChatId, historyEventId }) => { const NoEyes = await window.NoEyesReady; if (NoEyes.version !== '11.1.2') throw Error('SDK changed; read and validate the current example before continuing'); const walletProvider = { request: async input => { if (input.method === 'eth_accounts') return address ? [address] : []; return window.authorizedSign(input); } }; const client = NoEyes.createClient({ apiBase: origin, walletProvider, profileName: '' }); try { if (mode === 'read') { const result = await client.profiles.search(keyword, 10); return { mode, keyword, profiles: result.profiles || [] }; } const identity = client.chats.getIdentity(address, { profile: '' }).identity; const profile = (await client.profiles.get(address, { refresh: true })).profile; if (!profile) throw Error('Create an authorized profile using the setup guide first'); let status = await client.chats.getStatus(identity, { refresh: true }); if (mode === 'restart-check') { if (expected.origin !== origin || expected.identity !== identity || !status.has_local_key || !status.local_public_key || status.local_public_key !== expected.publicKey || status.published_public_key !== expected.publicKey) throw Error('Identity/key reuse check failed; stop and diagnose'); } else if (status.state === 'setup_required' && allowSetup) { await client.chats.enable(identity); } else if (status.state === 'restore_required') { throw Error('Use the authorized https://noeyes.work/docs/recovery/ procedure; this example does not replace keys'); } else if (!['ready', 'locked'].includes(status.state)) { throw Error('Messaging needs attention: ' + status.state); } if (!client.chats.isUnlocked(identity)) await client.chats.unlock(identity); status = await client.chats.getStatus(identity, { refresh: true }); if (status.state !== 'ready' || !status.can_read || !status.local_public_key || status.local_public_key !== status.published_public_key) throw Error('Messaging not verified ready'); if (historyChatId || historyEventId) { if (!historyChatId || !historyEventId) throw Error('Supply both history identifiers'); // Verify the exact earlier message by its canonical ID and decrypt state. const history = await client.chats.messages(historyChatId, identity, { limit: 100 }); const old = history.messages.find(row => [row.message_id, row.event_id, row.spasm_id, row.id].includes(historyEventId)); if (!old || old.decrypt_state !== 'ready') throw Error('Earlier message not decrypted in this page; use its history page and retry verification'); } return { mode, origin, identity, publicKey: status.local_public_key, state: status.state }; } finally { client.dispose(); } }, { address, origin: base.origin, mode, keyword: searchTerm, allowSetup, expected, historyChatId, historyEventId }); if (mode === 'messaging') { if (!expectedKeyFile) throw Error('Supply a checkpoint path'); // Public identity/key checkpoint only. Private CryptoKeys stay in IndexedDB. await writeFile(expectedKeyFile, JSON.stringify(result, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); } return result; } finally { await context.close(); } } if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { const mode = process.argv[2] || 'read'; const state = process.env.NOEYES_STATE_DIR; const signer = process.env.NOEYES_SIGNER_MODULE; if (!state || (mode !== 'read' && !signer)) throw Error('Set NOEYES_STATE_DIR and, for messaging, NOEYES_SIGNER_MODULE'); await mkdir(state, { recursive: true, mode: 0o700 }); const provider = mode === 'read' ? undefined : (await import(pathToFileURL(resolve(signer)).href)).provider; const result = await runAgent({ provider, userDataDir: resolve(state, 'chromium'), mode, keyword: process.argv[3], allowSetup: process.env.NOEYES_ALLOW_INITIAL_SETUP === 'true', expectedKeyFile: resolve(state, 'identity.json'), historyChatId: process.env.NOEYES_HISTORY_CHAT_ID, historyEventId: process.env.NOEYES_HISTORY_EVENT_ID }); console.log(JSON.stringify(result, null, 2)); }