mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
261 lines
8.4 KiB
TypeScript
261 lines
8.4 KiB
TypeScript
import { z } from "zod";
|
|
import {
|
|
DevicePairingCodeSchema,
|
|
RemoteAccessHeaderListSchema,
|
|
formatRemoteAccessHeaderParam,
|
|
} from "./device-pairing";
|
|
|
|
export const LOCAL_OPENCODE_SERVER_ID = "local";
|
|
export const OPENCODE_SERVER_USERNAME = "opencode";
|
|
export const OPENCODE_SERVER_LINK_PROTOCOL = "ocm:";
|
|
export const OPENCODE_SERVER_LINK_VERSION = "2";
|
|
|
|
const HttpUrlSchema = z
|
|
.string()
|
|
.trim()
|
|
.url()
|
|
.refine((value) => /^https?:\/\//i.test(value), "URL must start with http:// or https://");
|
|
|
|
export const OpenCodeServerSchema = z.object({
|
|
id: z.string(),
|
|
name: z.string(),
|
|
baseUrl: z.string(),
|
|
username: z.string(),
|
|
enabled: z.boolean(),
|
|
hasPassword: z.boolean(),
|
|
createdAt: z.number(),
|
|
updatedAt: z.number(),
|
|
});
|
|
|
|
export const OpenCodeConnectPairingSchema = z.object({
|
|
connectCode: z.string().regex(/^[A-Za-z0-9_-]+$/).min(1).max(256),
|
|
});
|
|
|
|
export const CreateOpenCodeServerRequestSchema = z
|
|
.object({
|
|
name: z.string().trim().min(1).max(100),
|
|
baseUrl: HttpUrlSchema,
|
|
username: z.string().trim().min(1).max(100).default(OPENCODE_SERVER_USERNAME),
|
|
password: z.string().min(1).max(1024).optional(),
|
|
pairing: OpenCodeConnectPairingSchema.optional(),
|
|
enabled: z.boolean().default(true),
|
|
})
|
|
.refine((value) => !(value.password && value.pairing), "Provide either a password or a pairing code, not both");
|
|
|
|
export const UpdateOpenCodeServerRequestSchema = z
|
|
.object({
|
|
name: z.string().trim().min(1).max(100).optional(),
|
|
baseUrl: HttpUrlSchema.optional(),
|
|
username: z.string().trim().min(1).max(100).optional(),
|
|
password: z.string().min(1).max(1024).nullable().optional(),
|
|
pairing: OpenCodeConnectPairingSchema.optional(),
|
|
enabled: z.boolean().optional(),
|
|
})
|
|
.refine((value) => !(value.password && value.pairing), "Provide either a password or a pairing code, not both");
|
|
|
|
export const TestOpenCodeServerRequestSchema = z.object({
|
|
baseUrl: HttpUrlSchema,
|
|
username: z.string().trim().min(1).max(100).default(OPENCODE_SERVER_USERNAME),
|
|
password: z.string().max(1024).optional(),
|
|
serverId: z.string().trim().min(1).optional(),
|
|
});
|
|
|
|
export const OpenCodeServerTestResultSchema = z.object({
|
|
ok: z.boolean(),
|
|
version: z.string().nullable(),
|
|
versionSupported: z.boolean(),
|
|
error: z.string().nullable(),
|
|
});
|
|
|
|
export const OpenCodeServerStatusSchema = z.object({
|
|
serverId: z.string(),
|
|
connected: z.boolean(),
|
|
version: z.string().nullable(),
|
|
error: z.string().nullable(),
|
|
});
|
|
|
|
export const ManagerAppLinkSchema = z.object({
|
|
kind: z.literal("manager"),
|
|
name: z.string().trim().min(1).max(100),
|
|
baseUrl: HttpUrlSchema,
|
|
code: DevicePairingCodeSchema,
|
|
headers: RemoteAccessHeaderListSchema,
|
|
});
|
|
|
|
export type OpenCodeServer = z.infer<typeof OpenCodeServerSchema>;
|
|
export type OpenCodeConnectPairing = z.infer<typeof OpenCodeConnectPairingSchema>;
|
|
export type CreateOpenCodeServerRequest = z.input<typeof CreateOpenCodeServerRequestSchema>;
|
|
export type UpdateOpenCodeServerRequest = z.input<typeof UpdateOpenCodeServerRequestSchema>;
|
|
export type TestOpenCodeServerRequest = z.input<typeof TestOpenCodeServerRequestSchema>;
|
|
export type OpenCodeServerTestResult = z.infer<typeof OpenCodeServerTestResultSchema>;
|
|
export type OpenCodeServerStatus = z.infer<typeof OpenCodeServerStatusSchema>;
|
|
export type ManagerAppLink = z.infer<typeof ManagerAppLinkSchema>;
|
|
|
|
export interface OpenCodeConnectLink {
|
|
name: string;
|
|
baseUrl: string;
|
|
pairing: { connectCode: string };
|
|
}
|
|
|
|
const CONNECT_CODE_PATTERN = /^[A-Za-z0-9_-]{1,256}$/;
|
|
const CONNECT_LINK_PATH_PATTERN = /^\/auth\/connect\/([A-Za-z0-9_-]{1,256})$/;
|
|
|
|
function readConnectOrigin(value: string): string | null {
|
|
let url: URL;
|
|
try {
|
|
url = new URL(value);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
|
if (url.username || url.password || url.search || url.hash) return null;
|
|
if (url.pathname !== "/") return null;
|
|
return url.origin;
|
|
}
|
|
|
|
const ConnectOriginSchema = z.string().transform((value, ctx) => {
|
|
const origin = readConnectOrigin(value);
|
|
if (origin === null) {
|
|
ctx.addIssue({ code: "custom", message: "URL must be an http(s) origin" });
|
|
return z.NEVER;
|
|
}
|
|
return origin;
|
|
});
|
|
|
|
const ConnectPayloadSchema = z.object({
|
|
code: z.string().regex(CONNECT_CODE_PATTERN),
|
|
urls: z.array(ConnectOriginSchema).min(1),
|
|
name: z.string().optional(),
|
|
});
|
|
|
|
function parseConnectPayload(text: string): OpenCodeConnectLink | null {
|
|
let payload: unknown;
|
|
try {
|
|
payload = JSON.parse(text);
|
|
} catch {
|
|
return null;
|
|
}
|
|
|
|
const parsed = ConnectPayloadSchema.safeParse(payload);
|
|
if (!parsed.success) return null;
|
|
|
|
const baseUrl = parsed.data.urls[0];
|
|
if (baseUrl === undefined) return null;
|
|
|
|
const name = parsed.data.name?.trim();
|
|
return {
|
|
name: name !== undefined && name.length > 0 ? name : new URL(baseUrl).hostname,
|
|
baseUrl,
|
|
pairing: { connectCode: parsed.data.code },
|
|
};
|
|
}
|
|
|
|
function parseConnectUrl(text: string): OpenCodeConnectLink | null {
|
|
let url: URL;
|
|
try {
|
|
url = new URL(text);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
|
if (url.username || url.password || url.search || url.hash) return null;
|
|
const connectCode = CONNECT_LINK_PATH_PATTERN.exec(url.pathname)?.[1];
|
|
if (!connectCode) return null;
|
|
return { name: url.hostname, baseUrl: url.origin, pairing: { connectCode } };
|
|
}
|
|
|
|
export function parseOpenCodeConnectLink(text: string): OpenCodeConnectLink | null {
|
|
const trimmed = text.trim();
|
|
const link = trimmed.startsWith("{") ? parseConnectPayload(trimmed) : parseConnectUrl(trimmed);
|
|
if (link === null) return null;
|
|
return { ...link, name: link.name.slice(0, 100) };
|
|
}
|
|
|
|
export function buildManagerAppLink(link: ManagerAppLink): string {
|
|
const params = buildLinkParams(link);
|
|
params.set("code", link.code);
|
|
for (const header of link.headers) params.append("h", formatRemoteAccessHeaderParam(header));
|
|
return buildLinkUrl(params);
|
|
}
|
|
|
|
export function parseManagerAppLink(text: string): ManagerAppLink | null {
|
|
return readLink(ManagerAppLinkSchema, text, (url) => {
|
|
const headers: Array<{ name: string; value: string }> = [];
|
|
for (const raw of url.searchParams.getAll("h")) {
|
|
const separator = raw.indexOf(":");
|
|
if (separator < 0) return null;
|
|
headers.push({ name: raw.slice(0, separator), value: raw.slice(separator + 1) });
|
|
}
|
|
return { headers };
|
|
});
|
|
}
|
|
|
|
function parseOpenCodeServerLinkUrl(text: string): URL | null {
|
|
let url: URL;
|
|
try {
|
|
url = new URL(text.trim());
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (url.protocol !== OPENCODE_SERVER_LINK_PROTOCOL || url.hostname !== "link") return null;
|
|
return url;
|
|
}
|
|
|
|
type LinkQueryFields = {
|
|
kind: string | null;
|
|
name: string | null;
|
|
baseUrl: string | null;
|
|
code: string | null;
|
|
};
|
|
|
|
function buildLinkParams(link: { kind: string; name: string; baseUrl: string }): URLSearchParams {
|
|
return new URLSearchParams({
|
|
v: OPENCODE_SERVER_LINK_VERSION,
|
|
kind: link.kind,
|
|
name: link.name,
|
|
url: link.baseUrl,
|
|
});
|
|
}
|
|
|
|
function buildLinkUrl(params: URLSearchParams): string {
|
|
return `${OPENCODE_SERVER_LINK_PROTOCOL}//link?${params.toString()}`;
|
|
}
|
|
|
|
function readLinkQueryFields(text: string): { url: URL; fields: LinkQueryFields } | null {
|
|
const url = parseOpenCodeServerLinkUrl(text);
|
|
if (!url || url.searchParams.get("v") !== OPENCODE_SERVER_LINK_VERSION) return null;
|
|
return {
|
|
url,
|
|
fields: {
|
|
kind: url.searchParams.get("kind"),
|
|
name: url.searchParams.get("name"),
|
|
baseUrl: url.searchParams.get("url"),
|
|
code: url.searchParams.get("code"),
|
|
},
|
|
};
|
|
}
|
|
|
|
function readLink<T, Details extends object>(
|
|
schema: z.ZodType<T>,
|
|
text: string,
|
|
readDetails: (url: URL) => Details | null,
|
|
): T | null {
|
|
const link = readLinkQueryFields(text);
|
|
if (!link) return null;
|
|
const details = readDetails(link.url);
|
|
if (!details) return null;
|
|
const parsed = schema.safeParse({ ...link.fields, ...details });
|
|
return parsed.success ? parsed.data : null;
|
|
}
|
|
|
|
const REMOTE_DIRECTORY_KEY_PATTERN = /^(srv_[A-Za-z0-9_-]+)\|(.+)$/s;
|
|
|
|
export function buildServerDirectoryKey(serverId: string, directory: string): string {
|
|
return serverId === LOCAL_OPENCODE_SERVER_ID ? directory : `${serverId}|${directory}`;
|
|
}
|
|
|
|
export function parseServerDirectoryKey(key: string): { serverId: string; directory: string } {
|
|
const match = REMOTE_DIRECTORY_KEY_PATTERN.exec(key);
|
|
return match?.[1] && match[2] ? { serverId: match[1], directory: match[2] } : { serverId: LOCAL_OPENCODE_SERVER_ID, directory: key };
|
|
}
|