mirror of
https://github.com/hanzoai/dev-desktop.git
synced 2026-11-23 05:52:02 +00:00
Dev reads the credential vault the CLI, hanzod and the desktop app share, read-only; sign-in, switching and sign-out run `hanzo auth`, which owns the vault, its locks and refresh. Client storage holds no tokens once the machine answers. A signed-in desktop links itself at /v1/sources unasked. The sidebar's bottom-left is the signed-in account (avatar, name, plan or Admin) with account/org switching, Usage, Settings, plans and billing, the phone-app QR and sign out. Co-authored-by: Hanzo Dev <[email protected]>
921 lines
35 KiB
TypeScript
921 lines
35 KiB
TypeScript
import * as Mime from "effect/http/Mime";
|
|
import {
|
|
AuthOrchestrationOperateScope,
|
|
AuthOrchestrationReadScope,
|
|
EnvironmentHttpApi,
|
|
} from "@hanzodev/contracts";
|
|
import { isDevProxiedPath } from "@hanzodev/shared/devProxy";
|
|
import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@hanzodev/shared/mcpApp";
|
|
import { FILE_PREVIEW_SCROLL_SCRIPT } from "@hanzodev/shared/htmlRender";
|
|
import { decodeOtlpTraceRecords } from "@hanzodev/shared/observability";
|
|
import * as ByteSize from "effect/ByteSize";
|
|
import * as Context from "effect/Context";
|
|
import * as Effect from "effect/Effect";
|
|
import * as FileSystem from "effect/FileSystem";
|
|
import * as Layer from "effect/Layer";
|
|
import * as Option from "effect/Option";
|
|
import * as Path from "effect/Path";
|
|
import * as Schema from "effect/Schema";
|
|
import * as Stream from "effect/Stream";
|
|
import * as Tracer from "effect/Tracer";
|
|
import { cast, pipe } from "effect/Function";
|
|
import {
|
|
HttpClient,
|
|
HttpClientResponse,
|
|
HttpMiddleware,
|
|
HttpRouter,
|
|
HttpServerResponse,
|
|
HttpServerRequest,
|
|
HttpServerRespondable,
|
|
} from "effect/http";
|
|
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
|
|
import { OtlpTracer, OtlpSerialization } from "effect/observability";
|
|
|
|
import * as ServerConfig from "./config.ts";
|
|
import { ASSET_ROUTE_PREFIX, readMcpAppHtml, resolveAsset } from "./assets/AssetAccess.ts";
|
|
import { sourceControlMediaResponse } from "./assets/sourceControlMediaResponse.ts";
|
|
import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
|
|
import {
|
|
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
|
|
storeAttachmentUpload,
|
|
validateAttachmentUploadToken,
|
|
} from "./assets/AttachmentUpload.ts";
|
|
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
|
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
|
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
|
|
import {
|
|
annotateEnvironmentRequest,
|
|
failEnvironmentScopeRequired,
|
|
failEnvironmentAuthInvalid,
|
|
failEnvironmentInternal,
|
|
} from "./auth/http.ts";
|
|
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
|
import { WEBHOOK_ROUTE_PREFIX } from "./scheduledTasks/ScheduledTaskService.ts";
|
|
import {
|
|
browserApiCorsAllowedHeaders,
|
|
browserApiCorsAllowedMethods,
|
|
DESKTOP_RENDERER_ORIGINS,
|
|
MCP_HTTP_PATH,
|
|
} from "./httpCors.ts";
|
|
import { sharedIdentityHost } from "./provider/hanzoLocalIdentity.ts";
|
|
import {
|
|
IDENTITY_ID,
|
|
readFreshSharedIdentity,
|
|
runHanzoAuth,
|
|
} from "./provider/hanzoSharedIdentityNode.ts";
|
|
import { ingestAnalyticsBody, readRecentAnalyticsSnapshot } from "./analyticsHub.ts";
|
|
import { requestUrl } from "./requestUrl.ts";
|
|
|
|
const OTLP_TRACES_PROXY_PATH = "/v1/o11y/traces";
|
|
const HANZO_IDENTITIES_PATH = "/v1/hanzo/identities";
|
|
const HANZO_BEACON_PATH = "/_/beacon";
|
|
const HANZO_ANALYTICS_EVENT_PATH = "/api/analytics/event";
|
|
const HANZO_ANALYTICS_RECENT_PATH = "/api/analytics/recent";
|
|
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
|
|
const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
|
|
// Opaque origin blocks cookies, storage and API access while allowing scripts.
|
|
// Agent HTML can open without a click, so disallow blocking modals.
|
|
const HTML_CONTENT_SECURITY_POLICY =
|
|
"sandbox allow-scripts allow-forms allow-popups allow-downloads";
|
|
|
|
// Proxies may strip disposition; force document-capable downloads to octet-stream.
|
|
const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/;
|
|
const isSafeDownloadMimeType = (mimeType: string): boolean =>
|
|
DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) &&
|
|
!/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());
|
|
const isSafeInlineMediaMimeType = (mimeType: string): boolean =>
|
|
DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && /^(?:audio|video)\//i.test(mimeType);
|
|
const isSafeInlineDocumentMimeType = (mimeType: string): boolean =>
|
|
mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html";
|
|
|
|
export function downloadContentDisposition(fileName?: string): string {
|
|
if (fileName === undefined) {
|
|
return "attachment";
|
|
}
|
|
// toWellFormed: encodeURIComponent throws URIError on unpaired surrogates.
|
|
const sanitized = fileName.toWellFormed().replace(/[\p{Cc}"\\]/gu, "_");
|
|
const asciiFallback = sanitized.replace(/[^\u0020-\u007e]/g, "_");
|
|
const needsExtended = asciiFallback !== sanitized;
|
|
const extendedName = encodeURIComponent(sanitized).replace(
|
|
/['()*]/g,
|
|
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
|
);
|
|
return `attachment; filename="${asciiFallback}"${
|
|
needsExtended ? `; filename*=UTF-8''${extendedName}` : ""
|
|
}`;
|
|
}
|
|
|
|
export function assetResponseHeaders(
|
|
filePath: string,
|
|
options?: {
|
|
readonly download?: boolean;
|
|
readonly fileName?: string;
|
|
readonly mimeType?: string;
|
|
},
|
|
): Record<string, string> {
|
|
const lowerPath = filePath.toLowerCase();
|
|
const inlineMimeType = options?.mimeType?.split(";", 1)[0]?.trim();
|
|
return {
|
|
"Cache-Control": "private, max-age=3600",
|
|
"X-Content-Type-Options": "nosniff",
|
|
...(options?.download
|
|
? {
|
|
"Content-Disposition": downloadContentDisposition(options.fileName),
|
|
"Content-Security-Policy": "default-src 'none'; sandbox",
|
|
"Content-Type":
|
|
options.mimeType !== undefined && isSafeDownloadMimeType(options.mimeType)
|
|
? options.mimeType
|
|
: "application/octet-stream",
|
|
}
|
|
: inlineMimeType !== undefined && isSafeInlineMediaMimeType(inlineMimeType)
|
|
? { "Content-Type": inlineMimeType }
|
|
: inlineMimeType !== undefined && isSafeInlineDocumentMimeType(inlineMimeType)
|
|
? {
|
|
"Content-Type":
|
|
inlineMimeType.toLowerCase() === "text/html"
|
|
? "text/html; charset=utf-8"
|
|
: "application/pdf",
|
|
...(inlineMimeType.toLowerCase() === "text/html"
|
|
? { "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY }
|
|
: {}),
|
|
}
|
|
: lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
|
|
? {
|
|
"Content-Type": "text/html; charset=utf-8",
|
|
"Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,
|
|
}
|
|
: {}),
|
|
...(!options?.download && lowerPath.endsWith(".svg")
|
|
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
|
|
: {}),
|
|
};
|
|
}
|
|
|
|
function assetByteRange(header: string, size: bigint) {
|
|
const match = /^bytes=(\d*)-(\d*)$/i.exec(header.trim());
|
|
if (!match || (!match[1] && !match[2])) return null;
|
|
const first = match[1] ? BigInt(match[1]) : null;
|
|
const last = match[2] ? BigInt(match[2]) : null;
|
|
if (first !== null && last !== null && last < first) return null;
|
|
if (size === 0n || (first !== null && first >= size) || (first === null && last === 0n)) {
|
|
return { _tag: "Unsatisfiable" as const };
|
|
}
|
|
const start = first ?? (last! >= size ? 0n : size - last!);
|
|
const end = first === null || last === null || last >= size ? size - 1n : last;
|
|
if (!Number.isSafeInteger(Number(start)) || !Number.isSafeInteger(Number(end))) {
|
|
return { _tag: "Unsatisfiable" as const };
|
|
}
|
|
return {
|
|
_tag: "Range" as const,
|
|
offset: start,
|
|
bytesToRead: end - start + 1n,
|
|
contentRange: `bytes ${start}-${end}/${size}`,
|
|
};
|
|
}
|
|
|
|
export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
|
|
asset: {
|
|
readonly path: string;
|
|
readonly download?: boolean;
|
|
readonly fileName?: string;
|
|
readonly mimeType?: string;
|
|
readonly file?: OpenMediaFile;
|
|
readonly renderIntent?: "mcp-app" | "file-preview";
|
|
},
|
|
rangeHeader?: string,
|
|
ifRangeHeader?: string,
|
|
method: "GET" | "HEAD" = "GET",
|
|
) {
|
|
const headers = assetResponseHeaders(asset.path, asset);
|
|
if (
|
|
asset.renderIntent === "mcp-app" &&
|
|
!asset.download &&
|
|
headers["Content-Type"] === "text/html; charset=utf-8"
|
|
) {
|
|
const bytes = yield* readMcpAppHtml(asset.path);
|
|
if (bytes === null) {
|
|
return HttpServerResponse.text("MCP app is too large to preview.", { status: 413 });
|
|
}
|
|
const body = pipe(
|
|
new TextDecoder().decode(bytes),
|
|
injectMcpAppThemeBootstrap,
|
|
injectMcpAppCookieBootstrap,
|
|
(html) => new TextEncoder().encode(html),
|
|
);
|
|
headers["Content-Length"] = String(body.byteLength);
|
|
return method === "HEAD"
|
|
? HttpServerResponse.empty({ status: 200, headers })
|
|
: HttpServerResponse.uint8Array(body, { headers });
|
|
}
|
|
if (
|
|
asset.renderIntent === "file-preview" &&
|
|
!asset.download &&
|
|
headers["Content-Type"] === "text/html; charset=utf-8"
|
|
) {
|
|
const bytes = yield* readMcpAppHtml(asset.path);
|
|
// A page too large to buffer is served as is, without scroll restoration.
|
|
if (bytes !== null) {
|
|
const script = new TextEncoder().encode(FILE_PREVIEW_SCROLL_SCRIPT);
|
|
const body = new Uint8Array(bytes.byteLength + script.byteLength);
|
|
body.set(bytes);
|
|
body.set(script, bytes.byteLength);
|
|
headers["Content-Length"] = String(body.byteLength);
|
|
return method === "HEAD"
|
|
? HttpServerResponse.empty({ status: 200, headers })
|
|
: HttpServerResponse.uint8Array(body, { headers });
|
|
}
|
|
}
|
|
const mediaFile = asset.file;
|
|
const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined;
|
|
const isMedia = /^(?:audio|video)\//i.test(headers["Content-Type"] ?? "");
|
|
if (isMedia) {
|
|
// Without file identity, validators cannot guarantee byte equality; attachments must also expire with their URL.
|
|
headers["Cache-Control"] = "private, no-store";
|
|
}
|
|
let status = 200;
|
|
let offset = 0n;
|
|
let bytesToRead: bigint | undefined;
|
|
{
|
|
headers["Accept-Ranges"] = "bytes";
|
|
// If-Range requires a matching validator. A full response is safe when we cannot validate it.
|
|
if (method === "GET" && rangeHeader && ifRangeHeader === undefined) {
|
|
const fs = yield* FileSystem.FileSystem;
|
|
const info = mediaInfo ?? (yield* fs.stat(asset.path));
|
|
const range = assetByteRange(rangeHeader, info.size);
|
|
if (range?._tag === "Unsatisfiable") {
|
|
return HttpServerResponse.empty({
|
|
status: 416,
|
|
headers: { ...headers, "Content-Range": `bytes */${info.size}` },
|
|
});
|
|
}
|
|
if (range?._tag === "Range") {
|
|
status = 206;
|
|
offset = range.offset;
|
|
bytesToRead = range.bytesToRead;
|
|
headers["Content-Range"] = range.contentRange;
|
|
}
|
|
}
|
|
}
|
|
if (mediaFile && mediaInfo) {
|
|
const size = bytesToRead ?? mediaInfo.size;
|
|
headers["Content-Type"] ??= Option.getOrElse(
|
|
Mime.getType(asset.path),
|
|
() => "application/octet-stream",
|
|
);
|
|
headers["Content-Length"] = String(size);
|
|
if (!isMedia) {
|
|
headers["Last-Modified"] = mediaInfo.mtime.toUTCString();
|
|
headers.ETag = `W/"${mediaInfo.size.toString(16)}-${mediaInfo.mtimeMs.toString(16)}"`;
|
|
}
|
|
if (method === "HEAD" || size === 0n) {
|
|
return HttpServerResponse.empty({ status, headers });
|
|
}
|
|
const body = streamMediaFile(mediaFile, offset, size);
|
|
if (!body) {
|
|
return HttpServerResponse.text("File is too large to preview.", { status: 413 });
|
|
}
|
|
return HttpServerResponse.stream(body, {
|
|
status,
|
|
headers,
|
|
});
|
|
}
|
|
return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers });
|
|
});
|
|
|
|
export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compression(), {
|
|
global: true,
|
|
});
|
|
|
|
export const layerBrowserApiCors = Layer.unwrap(
|
|
Effect.gen(function* () {
|
|
const config = yield* ServerConfig.ServerConfig;
|
|
const devOrigin = config.devUrl?.origin;
|
|
// Credentialed dev requests need explicit Vite/Electron origins; packaged desktop uses the default wildcard.
|
|
const cors = HttpMiddleware.cors({
|
|
...(devOrigin
|
|
? {
|
|
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
|
|
credentials: true,
|
|
}
|
|
: {}),
|
|
allowedMethods: browserApiCorsAllowedMethods,
|
|
allowedHeaders: browserApiCorsAllowedHeaders,
|
|
maxAge: 600,
|
|
});
|
|
return HttpRouter.middleware(
|
|
(httpEffect) => {
|
|
const withCors = cors(httpEffect);
|
|
return Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) =>
|
|
request.url.split("?", 1)[0] === MCP_HTTP_PATH ? httpEffect : withCors,
|
|
);
|
|
},
|
|
{ global: true },
|
|
);
|
|
}),
|
|
);
|
|
|
|
function isLoopbackHostname(hostname: string): boolean {
|
|
const normalizedHostname = hostname
|
|
.trim()
|
|
.toLowerCase()
|
|
.replace(/^\[(.*)\]$/, "$1");
|
|
return LOOPBACK_HOSTNAMES.has(normalizedHostname);
|
|
}
|
|
|
|
function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
|
|
const redirectUrl = new URL(devUrl.toString());
|
|
redirectUrl.pathname = requestUrl.pathname;
|
|
redirectUrl.search = requestUrl.search;
|
|
redirectUrl.hash = requestUrl.hash;
|
|
return redirectUrl.toString();
|
|
}
|
|
|
|
export const authenticateRawRouteWithScope =
|
|
/* Request instrumentation already owns the span; keep this helper in that context. */
|
|
Effect.fnUntraced(function* (
|
|
scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
|
|
) {
|
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
|
const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
|
|
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
|
|
failEnvironmentAuthInvalid(
|
|
EnvironmentAuth.serverAuthCredentialReason(error),
|
|
EnvironmentAuth.serverAuthDpopFailureReason(error),
|
|
),
|
|
),
|
|
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
|
failEnvironmentInternal("internal_error", error),
|
|
),
|
|
);
|
|
if (!session.scopes.includes(scope)) {
|
|
return yield* failEnvironmentScopeRequired(scope);
|
|
}
|
|
});
|
|
|
|
export const layerServerEnvironmentHttpApi = HttpApiBuilder.group(
|
|
EnvironmentHttpApi,
|
|
"metadata",
|
|
Effect.fnUntraced(function* (handlers) {
|
|
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
|
return handlers.handle(
|
|
"descriptor",
|
|
Effect.fn("environment.metadata.descriptor")(function* (args) {
|
|
yield* annotateEnvironmentRequest(args.endpoint.name);
|
|
return yield* serverEnvironment.getDescriptor;
|
|
}, traceRelayRequest),
|
|
);
|
|
}),
|
|
);
|
|
|
|
class DecodeOtlpTraceRecordsError extends Schema.TaggedError<DecodeOtlpTraceRecordsError>()(
|
|
"DecodeOtlpTraceRecordsError",
|
|
{ cause: Schema.Defect() },
|
|
) {}
|
|
|
|
// Tracing once-per-second renderer exports would create more spans than it forwards.
|
|
export const layerOtlpTracesProxyRoute = HttpRouter.add(
|
|
"POST",
|
|
OTLP_TRACES_PROXY_PATH,
|
|
Effect.gen(function* () {
|
|
yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
|
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
const config = yield* ServerConfig.ServerConfig;
|
|
const otlpTracesUrl = config.otlpTracesUrl;
|
|
const otlpHeaders = config.otlpTracesExport.headers;
|
|
const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
|
|
const httpClient = yield* HttpClient.HttpClient;
|
|
const serialization = yield* OtlpSerialization.OtlpSerialization;
|
|
const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
|
|
|
|
yield* Effect.try({
|
|
try: () => decodeOtlpTraceRecords(bodyJson),
|
|
catch: (cause) => new DecodeOtlpTraceRecordsError({ cause }),
|
|
}).pipe(
|
|
Effect.flatMap((records) => browserTraceCollector.record(records)),
|
|
Effect.catch((cause) => Effect.logWarning("Failed to decode browser OTLP traces", { cause })),
|
|
);
|
|
|
|
if (otlpTracesUrl === undefined) {
|
|
return HttpServerResponse.empty({ status: 204 });
|
|
}
|
|
|
|
return yield* httpClient
|
|
.post(otlpTracesUrl, {
|
|
body: serialization.traces(bodyJson),
|
|
headers: otlpHeaders,
|
|
})
|
|
.pipe(
|
|
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
|
Effect.as(HttpServerResponse.empty({ status: 204 })),
|
|
Effect.tapError((cause) =>
|
|
Effect.logWarning("Failed to export browser OTLP traces", {
|
|
cause,
|
|
otlpTracesUrl,
|
|
}),
|
|
),
|
|
Effect.orElseSucceed(() =>
|
|
HttpServerResponse.text("Trace export failed.", { status: 502 }),
|
|
),
|
|
);
|
|
}).pipe(
|
|
Effect.catchTags({
|
|
EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
|
|
EnvironmentInternalError: HttpServerRespondable.toResponse,
|
|
EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
|
|
}),
|
|
Effect.withTracerEnabled(false),
|
|
),
|
|
);
|
|
|
|
export const layerHanzoIdentitiesRoute = HttpRouter.add(
|
|
"GET",
|
|
HANZO_IDENTITIES_PATH,
|
|
Effect.gen(function* () {
|
|
yield* authenticateRawRouteWithScope(AuthOrchestrationReadScope);
|
|
const host = yield* sharedIdentityHost();
|
|
const snapshot = yield* Effect.promise(() => readFreshSharedIdentity(host));
|
|
// @effect-diagnostics-next-line globalJsonInEffect:off
|
|
return HttpServerResponse.text(JSON.stringify(snapshot), {
|
|
contentType: "application/json; charset=utf-8",
|
|
headers: {
|
|
"Cache-Control": "no-store",
|
|
},
|
|
});
|
|
}).pipe(
|
|
Effect.catchTags({
|
|
EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
|
|
EnvironmentInternalError: HttpServerRespondable.toResponse,
|
|
EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
|
|
}),
|
|
Effect.withTracerEnabled(false),
|
|
),
|
|
);
|
|
|
|
/** The `id` of an identity request body: a string, null when absent, undefined when the body is not JSON. */
|
|
const parseIdentityBody = (raw: string): string | null | undefined => {
|
|
try {
|
|
const body: unknown = raw ? JSON.parse(raw) : {};
|
|
const value = (body as { id?: unknown }).id;
|
|
return typeof value === "string" ? value : null;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
};
|
|
|
|
/** The machine's identity is the CLI's: sign-in, switching, and sign-out run `hanzo auth`, which owns the vault and its locks. */
|
|
const identityAction = (
|
|
action: "login" | "use" | "logout",
|
|
build: (id: string | null) => ReadonlyArray<string>,
|
|
timeoutMs: number,
|
|
) =>
|
|
HttpRouter.add(
|
|
"POST",
|
|
`${HANZO_IDENTITIES_PATH}/${action}`,
|
|
Effect.gen(function* () {
|
|
yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
|
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
const raw = yield* request.text.pipe(Effect.orElseSucceed(() => ""));
|
|
const parsed = parseIdentityBody(raw);
|
|
if (parsed === undefined) {
|
|
return HttpServerResponse.text("Invalid JSON body.", { status: 400 });
|
|
}
|
|
const id = parsed;
|
|
if (action !== "login" && (id === null || !IDENTITY_ID.test(id))) {
|
|
return HttpServerResponse.text("Expected an identity as owner/name.", { status: 400 });
|
|
}
|
|
const host = yield* sharedIdentityHost();
|
|
const failure = yield* Effect.promise(() =>
|
|
runHanzoAuth(host, build(id), timeoutMs).then(
|
|
() => null,
|
|
(error: unknown) => (error instanceof Error ? error.message : String(error)),
|
|
),
|
|
);
|
|
if (failure !== null) {
|
|
return HttpServerResponse.text(failure, { status: 502 });
|
|
}
|
|
const snapshot = yield* Effect.promise(() => readFreshSharedIdentity(host));
|
|
// @effect-diagnostics-next-line globalJsonInEffect:off
|
|
return HttpServerResponse.text(JSON.stringify(snapshot), {
|
|
contentType: "application/json; charset=utf-8",
|
|
headers: { "Cache-Control": "no-store" },
|
|
});
|
|
}).pipe(
|
|
Effect.catchTags({
|
|
EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
|
|
EnvironmentInternalError: HttpServerRespondable.toResponse,
|
|
EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
|
|
}),
|
|
Effect.withTracerEnabled(false),
|
|
),
|
|
);
|
|
|
|
export const layerHanzoIdentityActionRoutes = Layer.mergeAll(
|
|
identityAction("login", () => ["login"], 5 * 60_000),
|
|
identityAction("use", (id) => ["use", id ?? ""], 20_000),
|
|
identityAction("logout", (id) => ["logout", id ?? ""], 20_000),
|
|
);
|
|
|
|
const handleAnalyticsIngest = Effect.gen(function* () {
|
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
const rawBody = yield* request.text.pipe(Effect.orElseSucceed(() => ""));
|
|
const accepted = ingestAnalyticsBody(rawBody, request.headers);
|
|
// @effect-diagnostics-next-line globalJsonInEffect:off
|
|
const responseBody = JSON.stringify({
|
|
ok: true,
|
|
accepted: accepted.length,
|
|
eventIds: accepted.map((entry) => entry.payload.event_id),
|
|
});
|
|
return HttpServerResponse.text(responseBody, {
|
|
status: 202,
|
|
contentType: "application/json; charset=utf-8",
|
|
headers: { "Cache-Control": "no-store" },
|
|
});
|
|
}).pipe(Effect.withTracerEnabled(false));
|
|
|
|
export const layerHanzoAnalyticsRoutes = Layer.mergeAll(
|
|
HttpRouter.add("POST", HANZO_BEACON_PATH, handleAnalyticsIngest),
|
|
HttpRouter.add("POST", HANZO_ANALYTICS_EVENT_PATH, handleAnalyticsIngest),
|
|
HttpRouter.add(
|
|
"GET",
|
|
HANZO_ANALYTICS_RECENT_PATH,
|
|
Effect.sync(() => {
|
|
const snapshot = readRecentAnalyticsSnapshot();
|
|
// @effect-diagnostics-next-line globalJsonInEffect:off
|
|
return HttpServerResponse.text(JSON.stringify(snapshot), {
|
|
status: 200,
|
|
contentType: "application/json; charset=utf-8",
|
|
headers: { "Cache-Control": "no-store" },
|
|
});
|
|
}).pipe(Effect.withTracerEnabled(false)),
|
|
),
|
|
);
|
|
|
|
const UNTRACED_REQUEST_PATHS: ReadonlySet<string> = new Set([
|
|
OTLP_TRACES_PROXY_PATH,
|
|
HANZO_IDENTITIES_PATH,
|
|
HANZO_BEACON_PATH,
|
|
HANZO_ANALYTICS_EVENT_PATH,
|
|
HANZO_ANALYTICS_RECENT_PATH,
|
|
]);
|
|
|
|
// HttpRouter.serve builds routes privately; provide the server-wide TracerDisabledWhen to the served layer.
|
|
const layerUntracedRequests = Layer.succeed(HttpMiddleware.TracerDisabledWhen)((request) => {
|
|
const queryIndex = request.url.indexOf("?");
|
|
const path = queryIndex === -1 ? request.url : request.url.slice(0, queryIndex);
|
|
// Signed URLs carry bearer tokens in the path, so they never reach a trace.
|
|
return (
|
|
UNTRACED_REQUEST_PATHS.has(path) ||
|
|
path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`) ||
|
|
path.startsWith(`${ASSET_ROUTE_PREFIX}/`) ||
|
|
path.startsWith(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`)
|
|
);
|
|
});
|
|
|
|
export const withUntracedRequests = Layer.provide(layerUntracedRequests);
|
|
|
|
// Request spans otherwise parent to the server's lifetime span, so every request shares one trace id.
|
|
export const withRootRequestSpans = <A, E, R>(layer: Layer.Layer<A, E, R>) =>
|
|
Layer.fromBuild((memoMap, scope) =>
|
|
Layer.buildWithMemoMap(layer, memoMap, scope).pipe(
|
|
// ParentSpan is optional to every reader, so removing it leaves R satisfied.
|
|
Effect.updateContext(
|
|
(context: Context.Context<R>) =>
|
|
Context.omit(Tracer.ParentSpan)(context) as Context.Context<R>,
|
|
),
|
|
),
|
|
);
|
|
|
|
export const layerAssetRoute = HttpRouter.add(
|
|
"GET",
|
|
`${ASSET_ROUTE_PREFIX}/*`,
|
|
Effect.gen(function* () {
|
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
const url = requestUrl(request);
|
|
if (Option.isNone(url)) {
|
|
return HttpServerResponse.text("Bad Request", { status: 400 });
|
|
}
|
|
|
|
const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
|
const separatorIndex = suffix.indexOf("/");
|
|
if (separatorIndex <= 0) {
|
|
return HttpServerResponse.text("Not Found", { status: 404 });
|
|
}
|
|
|
|
const asset = yield* resolveAsset(
|
|
suffix.slice(0, separatorIndex),
|
|
suffix.slice(separatorIndex + 1),
|
|
);
|
|
if (!asset) {
|
|
return HttpServerResponse.text("Not Found", { status: 404 });
|
|
}
|
|
if (asset.kind === "bytes") {
|
|
return HttpServerResponse.uint8Array(asset.bytes, {
|
|
contentType: asset.mimeType,
|
|
headers: { "cache-control": "private, max-age=3600", "x-content-type-options": "nosniff" },
|
|
});
|
|
}
|
|
if (asset.kind === "source-control-media") {
|
|
return yield* sourceControlMediaResponse(asset, request.headers).pipe(
|
|
Effect.tapError((cause) =>
|
|
// The URL can carry a token in its query string, and the error keeps the request it
|
|
// failed on; the host and the failure kind are enough to diagnose.
|
|
Effect.logWarning("Failed to fetch source control media.", {
|
|
host: URL.canParse(asset.url) ? new URL(asset.url).host : undefined,
|
|
reason: cause.reason._tag,
|
|
}),
|
|
),
|
|
Effect.orElseSucceed(() =>
|
|
HttpServerResponse.empty({
|
|
status: 502,
|
|
headers: { "cache-control": "private, no-store", "x-content-type-options": "nosniff" },
|
|
}),
|
|
),
|
|
);
|
|
}
|
|
return yield* assetFileResponse(
|
|
asset,
|
|
request.method === "GET" ? request.headers.range : undefined,
|
|
request.headers["if-range"],
|
|
request.method === "HEAD" ? "HEAD" : "GET",
|
|
).pipe(
|
|
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
|
);
|
|
}),
|
|
);
|
|
|
|
export const layerAttachmentUploadRoute = HttpRouter.add(
|
|
"POST",
|
|
`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
|
|
Effect.gen(function* () {
|
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
const url = requestUrl(request);
|
|
if (Option.isNone(url)) {
|
|
return HttpServerResponse.text("Bad Request", { status: 400 });
|
|
}
|
|
|
|
const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
|
|
if (!token) {
|
|
return HttpServerResponse.text("Not Found", { status: 404 });
|
|
}
|
|
const claims = yield* validateAttachmentUploadToken(token);
|
|
if (!claims) {
|
|
return HttpServerResponse.text("Not Found", { status: 404 });
|
|
}
|
|
|
|
const contentLengthHeader = request.headers["content-length"];
|
|
if (
|
|
contentLengthHeader !== undefined &&
|
|
(!Number.isInteger(Number(contentLengthHeader)) ||
|
|
Number(contentLengthHeader) !== claims.sizeBytes)
|
|
) {
|
|
return HttpServerResponse.text("Content-Length must match the upload size.", {
|
|
status: 400,
|
|
});
|
|
}
|
|
|
|
// Keep the request stream in the route scope until the response is sent.
|
|
const bodyPull = yield* Stream.toPull(request.stream);
|
|
const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
|
|
return stored.ok
|
|
? HttpServerResponse.empty({ status: 204 })
|
|
: HttpServerResponse.text(stored.detail, { status: stored.status });
|
|
}),
|
|
);
|
|
|
|
const decodeBuildManifest = Schema.decodeUnknownEffect(
|
|
Schema.fromJsonString(
|
|
Schema.Record(
|
|
Schema.String,
|
|
Schema.Struct({
|
|
file: Schema.String,
|
|
css: Schema.optional(Schema.Array(Schema.String)),
|
|
assets: Schema.optional(Schema.Array(Schema.String)),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
|
|
const loadImmutableBuildAssets = Effect.gen(function* () {
|
|
const config = yield* ServerConfig.ServerConfig;
|
|
const staticDir =
|
|
config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
|
|
if (!staticDir) return new Set<string>();
|
|
const fileSystem = yield* FileSystem.FileSystem;
|
|
const path = yield* Path.Path;
|
|
return yield* fileSystem.readFileString(path.join(staticDir, ".vite", "manifest.json")).pipe(
|
|
Effect.flatMap(decodeBuildManifest),
|
|
Effect.map(
|
|
(manifest) =>
|
|
new Set(
|
|
Object.values(manifest).flatMap((entry) => [
|
|
entry.file,
|
|
...(entry.css ?? []),
|
|
...(entry.assets ?? []),
|
|
]),
|
|
),
|
|
),
|
|
Effect.orElseSucceed(() => new Set<string>()),
|
|
);
|
|
});
|
|
|
|
const openStaticFile = Effect.fn("openStaticFile")(function* (filePath: string) {
|
|
const fileSystem = yield* FileSystem.FileSystem;
|
|
const pathInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
|
|
if (pathInfo?.type !== "File") return null;
|
|
const file = yield* fileSystem.open(filePath, { flag: "r" }).pipe(
|
|
Effect.catchTags({
|
|
PlatformError: (error) =>
|
|
error.reason._tag === "NotFound" ? Effect.succeed(null) : Effect.fail(error),
|
|
}),
|
|
);
|
|
// Electron asar can stat and read files even when opening a handle returns NotFound.
|
|
// Refresh path metadata because the file may have been replaced since the first stat.
|
|
const info = yield* file === null ? fileSystem.stat(filePath) : file.stat;
|
|
return info.type === "File" ? { file, info } : null;
|
|
});
|
|
|
|
const streamStaticFile = (file: FileSystem.File, size: bigint) =>
|
|
Stream.unfold(
|
|
0n,
|
|
Effect.fnUntraced(function* (offset: bigint) {
|
|
if (offset >= size) return;
|
|
const remaining = size - offset;
|
|
const bytes = yield* file.readAlloc(Number(remaining < 65_536n ? remaining : 65_536n));
|
|
if (Option.isNone(bytes)) return;
|
|
return [bytes.value, offset + BigInt(bytes.value.byteLength)] as const;
|
|
}),
|
|
);
|
|
|
|
// The app can approve agents and start threads in one click, so no other site may frame it.
|
|
const SPA_FRAME_HEADERS = {
|
|
"Content-Security-Policy": "frame-ancestors 'none'",
|
|
"X-Frame-Options": "DENY",
|
|
};
|
|
|
|
const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(
|
|
function* (immutableBuildAssets: ReadonlySet<string>) {
|
|
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
const url = requestUrl(request);
|
|
|
|
if (Option.isNone(url)) {
|
|
return HttpServerResponse.text("Bad Request", { status: 400 });
|
|
}
|
|
|
|
const config = yield* ServerConfig.ServerConfig;
|
|
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
|
|
return HttpServerResponse.text("Not Found", { status: 404 });
|
|
}
|
|
|
|
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
|
|
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
|
|
status: 302,
|
|
});
|
|
}
|
|
|
|
const staticDir =
|
|
config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
|
|
if (!staticDir && config.devUrl) {
|
|
// `vp run dev --share --built` prints the pairing URL before its first
|
|
// web build lands in apps/web/dist. Reload until it does.
|
|
return HttpServerResponse.text(
|
|
'<!doctype html><meta http-equiv="refresh" content="2"><p>Waiting for the first web build. This page reloads by itself.</p>',
|
|
{ status: 503, contentType: "text/html", headers: { "Retry-After": "2" } },
|
|
);
|
|
}
|
|
if (!staticDir) {
|
|
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
|
|
status: 503,
|
|
});
|
|
}
|
|
|
|
const path = yield* Path.Path;
|
|
const staticRoot = path.resolve(staticDir);
|
|
const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
|
|
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
|
|
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
|
|
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
|
|
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
|
|
if (
|
|
staticRelativePath.length === 0 ||
|
|
hasRawLeadingParentSegment ||
|
|
hasPathTraversalSegment ||
|
|
staticRelativePath.includes("\0")
|
|
) {
|
|
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
|
}
|
|
|
|
const isWithinStaticRoot = (candidate: string) =>
|
|
candidate === staticRoot ||
|
|
candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
|
|
|
|
let filePath = path.resolve(staticRoot, staticRelativePath);
|
|
if (!isWithinStaticRoot(filePath)) {
|
|
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
|
}
|
|
|
|
const ext = path.extname(filePath);
|
|
if (!ext) {
|
|
filePath = path.resolve(filePath, "index.html");
|
|
if (!isWithinStaticRoot(filePath)) {
|
|
return HttpServerResponse.text("Invalid static file path", { status: 400 });
|
|
}
|
|
}
|
|
|
|
let opened = yield* openStaticFile(filePath);
|
|
if (!opened) {
|
|
filePath = path.resolve(staticRoot, "index.html");
|
|
opened = yield* openStaticFile(filePath);
|
|
if (!opened) {
|
|
return HttpServerResponse.text("Not Found", { status: 404 });
|
|
}
|
|
}
|
|
const fileInfo = opened.info;
|
|
const mimeType = Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream");
|
|
const isHtml = mimeType === "text/html";
|
|
|
|
// A hash-like name is not enough: custom static files can use the same naming pattern.
|
|
const relativePath = path.relative(staticRoot, filePath).replaceAll("\\", "/");
|
|
const immutable =
|
|
!isHtml &&
|
|
/^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) &&
|
|
immutableBuildAssets.has(relativePath);
|
|
const cacheControl = immutable ? "public, max-age=31536000, immutable" : "no-cache";
|
|
const validators = (info: FileSystem.File.Info) => {
|
|
// Deployments can preserve HTML size and mtime while changing its bundle URLs.
|
|
const modifiedAt = isHtml ? undefined : Option.getOrUndefined(info.mtime);
|
|
return modifiedAt
|
|
? {
|
|
ETag: `W/"${info.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`,
|
|
"Last-Modified": modifiedAt.toUTCString(),
|
|
}
|
|
: {};
|
|
};
|
|
const headers: Record<string, string> = {
|
|
"Cache-Control": cacheControl,
|
|
...(isHtml ? SPA_FRAME_HEADERS : {}),
|
|
...validators(fileInfo),
|
|
};
|
|
const etag = headers.ETag;
|
|
const lastModified = headers["Last-Modified"];
|
|
|
|
// If-None-Match precedes dates and uses weak GET/HEAD comparison even across compression.
|
|
const ifNoneMatch = request.headers["if-none-match"];
|
|
const ifModifiedSince = request.headers["if-modified-since"];
|
|
const unchanged =
|
|
ifNoneMatch !== undefined
|
|
? ifNoneMatch.split(",").some((value) => {
|
|
const candidate = value.trim();
|
|
return (
|
|
candidate === "*" ||
|
|
(etag !== undefined && candidate.replace(/^W\//i, "") === etag.slice(2))
|
|
);
|
|
})
|
|
: ifModifiedSince !== undefined &&
|
|
lastModified !== undefined &&
|
|
Date.parse(lastModified) <= Date.parse(ifModifiedSince);
|
|
if (!isHtml && unchanged) {
|
|
return HttpServerResponse.empty({
|
|
status: 304,
|
|
headers: { ...headers, Vary: "Accept-Encoding" },
|
|
});
|
|
}
|
|
|
|
const contentType = isHtml ? "text/html; charset=utf-8" : mimeType;
|
|
if (opened.file === null && request.method !== "HEAD") {
|
|
const fileSystem = yield* FileSystem.FileSystem;
|
|
// Complete fallback reads before success headers; stream errors arrive too late for a 500.
|
|
const bytes = yield* fileSystem.readFile(filePath);
|
|
const info = yield* fileSystem.stat(filePath);
|
|
return HttpServerResponse.uint8Array(bytes, {
|
|
headers: {
|
|
"Cache-Control": cacheControl,
|
|
...(isHtml ? SPA_FRAME_HEADERS : {}),
|
|
...validators({ ...info, size: ByteSize.bytes(bytes.byteLength) }),
|
|
},
|
|
contentType,
|
|
});
|
|
}
|
|
// The request scope closes the handle for GET, HEAD, 304, errors, and cancellation.
|
|
// HEAD still passes through compression, which selects headers without reading the stream.
|
|
return HttpServerResponse.stream(
|
|
opened.file === null ? Stream.empty : streamStaticFile(opened.file, fileInfo.size),
|
|
{
|
|
headers,
|
|
contentType,
|
|
contentLength: Number(fileInfo.size),
|
|
},
|
|
);
|
|
},
|
|
Effect.catchTags({
|
|
PlatformError: () =>
|
|
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
|
|
}),
|
|
);
|
|
|
|
export const layerStaticAndDevRoute = Layer.unwrap(
|
|
loadImmutableBuildAssets.pipe(
|
|
Effect.map((assets) => HttpRouter.add("GET", "*", handleStaticAndDevRequest(assets))),
|
|
),
|
|
);
|