mirror of
https://github.com/daggerhashimoto/openclaw-nerve
synced 2026-04-21 10:37:17 +00:00
59 lines
1.8 KiB
TypeScript
59 lines
1.8 KiB
TypeScript
/**
|
||
* 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 (1–65535). */
|
||
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;
|
||
}
|