openclaw-nerve/scripts/lib/validators.ts
2026-02-19 22:28:07 +01:00

59 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Input validation functions for the setup CLI.
*/
import net from 'node:net';
/** Check if a string is a valid HTTP(S) URL. */
export function isValidUrl(url: string): boolean {
try {
const u = new URL(url);
return ['http:', 'https:'].includes(u.protocol);
} catch {
return false;
}
}
/** Check if a port number is valid (165535). */
export function isValidPort(port: number): boolean {
return Number.isInteger(port) && port >= 1 && port <= 65535;
}
/** Check if a port is available for binding. */
export async function isPortAvailable(port: number, host: string = '127.0.0.1'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
server.once('error', () => resolve(false));
server.once('listening', () => {
server.close();
resolve(true);
});
server.listen(port, host);
});
}
/** Test if the OpenClaw gateway is reachable at the given URL. */
export async function testGatewayConnection(url: string): Promise<{ ok: boolean; message: string }> {
try {
const resp = await fetch(`${url}/health`, { signal: AbortSignal.timeout(5000) });
if (resp.ok) {
return { ok: true, message: 'Gateway reachable' };
}
return { ok: false, message: `Gateway returned HTTP ${resp.status}` };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { ok: false, message: `Cannot reach gateway: ${msg}` };
}
}
/** Loose validation for OpenAI API key format. */
export function isValidOpenAIKey(key: string): boolean {
// OpenAI keys start with sk- and are long
return key.startsWith('sk-') && key.length > 20;
}
/** Loose validation for Replicate API token format. */
export function isValidReplicateToken(token: string): boolean {
// Replicate tokens are typically r8_ prefixed or just long alphanumeric
return token.length > 10;
}