Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8c367df4a | ||
|
|
ea3e9987d7 | ||
|
|
12ecd648ba | ||
|
|
e980a2fd8f |
No files matched your search
@@ -0,0 +1,245 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { IncomingHttpHeaders } from "node:http";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Ref, Schema, ServiceMap } from "effect";
|
||||
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
|
||||
const BOOTSTRAP_TOKEN_TTL_MS = 5 * 60 * 1_000;
|
||||
const AUTH_COOKIE_MAX_AGE_SECONDS = 30 * 24 * 60 * 60;
|
||||
const AUTH_COOKIE_NAME = "t3_auth";
|
||||
const BOOTSTRAP_HASH_KEY = "t3_bootstrap";
|
||||
const COOKIE_SECRET_FILENAME = "browser-auth-secret";
|
||||
|
||||
interface BootstrapState {
|
||||
readonly token: string;
|
||||
readonly expiresAt: number;
|
||||
readonly consumedAt: number | null;
|
||||
}
|
||||
|
||||
interface AuthCookiePayload {
|
||||
readonly v: 1;
|
||||
readonly purpose: "browser-auth";
|
||||
readonly iat: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
export class BrowserAuthError extends Schema.TaggedErrorClass<BrowserAuthError>()(
|
||||
"BrowserAuthError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
export interface BrowserAuthShape {
|
||||
readonly getPairingUrl: (baseUrl: string) => Effect.Effect<string, never>;
|
||||
readonly getAllowedOrigins: Effect.Effect<ReadonlySet<string>, never>;
|
||||
readonly isAllowedOrigin: (origin: string | undefined) => Effect.Effect<boolean, never>;
|
||||
readonly consumeBootstrapToken: (token: string) => Effect.Effect<boolean, never>;
|
||||
readonly isAuthenticatedRequest: (headers: IncomingHttpHeaders) => Effect.Effect<boolean, never>;
|
||||
readonly createAuthCookie: (isSecure: boolean) => Effect.Effect<string, never>;
|
||||
}
|
||||
|
||||
export class BrowserAuth extends ServiceMap.Service<BrowserAuth, BrowserAuthShape>()(
|
||||
"t3/browserAuth",
|
||||
) {}
|
||||
|
||||
function makeBootstrapToken(): string {
|
||||
return crypto.randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function makeCookieSecret(): string {
|
||||
return crypto.randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function toBase64Url(input: string): string {
|
||||
return Buffer.from(input, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
function fromBase64Url(input: string): string {
|
||||
return Buffer.from(input, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
function signCookie(payload: AuthCookiePayload, secret: string): string {
|
||||
const payloadEncoded = toBase64Url(JSON.stringify(payload));
|
||||
const signature = crypto.createHmac("sha256", secret).update(payloadEncoded).digest("base64url");
|
||||
return `${payloadEncoded}.${signature}`;
|
||||
}
|
||||
|
||||
function verifyCookie(cookie: string, secret: string, now = Date.now()): boolean {
|
||||
const separatorIndex = cookie.lastIndexOf(".");
|
||||
if (separatorIndex <= 0 || separatorIndex >= cookie.length - 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const payloadEncoded = cookie.slice(0, separatorIndex);
|
||||
const providedSignature = cookie.slice(separatorIndex + 1);
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(payloadEncoded)
|
||||
.digest("base64url");
|
||||
|
||||
const providedBuffer = Buffer.from(providedSignature, "utf8");
|
||||
const expectedBuffer = Buffer.from(expectedSignature, "utf8");
|
||||
if (providedBuffer.length !== expectedBuffer.length) {
|
||||
return false;
|
||||
}
|
||||
if (!crypto.timingSafeEqual(providedBuffer, expectedBuffer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fromBase64Url(payloadEncoded)) as Partial<AuthCookiePayload>;
|
||||
if (parsed.v !== 1 || parsed.purpose !== "browser-auth") {
|
||||
return false;
|
||||
}
|
||||
if (typeof parsed.exp !== "number" || !Number.isFinite(parsed.exp)) {
|
||||
return false;
|
||||
}
|
||||
return parsed.exp > now;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function parseCookies(cookieHeader: string | string[] | undefined): Map<string, string> {
|
||||
const raw = Array.isArray(cookieHeader) ? cookieHeader.join("; ") : cookieHeader;
|
||||
if (!raw) return new Map();
|
||||
|
||||
const cookies = new Map<string, string>();
|
||||
for (const segment of raw.split(";")) {
|
||||
const trimmed = segment.trim();
|
||||
if (trimmed.length === 0) continue;
|
||||
const separatorIndex = trimmed.indexOf("=");
|
||||
if (separatorIndex <= 0) continue;
|
||||
const key = trimmed.slice(0, separatorIndex).trim();
|
||||
const value = trimmed.slice(separatorIndex + 1).trim();
|
||||
if (key.length === 0 || value.length === 0) continue;
|
||||
cookies.set(key, value);
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function normalizeOriginSet(serverConfig: ServerConfigShape): ReadonlySet<string> {
|
||||
const origins = new Set<string>();
|
||||
origins.add(`http://localhost:${serverConfig.port}`);
|
||||
origins.add(`http://127.0.0.1:${serverConfig.port}`);
|
||||
origins.add(`http://[::1]:${serverConfig.port}`);
|
||||
|
||||
if (
|
||||
serverConfig.host &&
|
||||
serverConfig.host !== "0.0.0.0" &&
|
||||
serverConfig.host !== "::" &&
|
||||
serverConfig.host !== "[::]"
|
||||
) {
|
||||
const host =
|
||||
serverConfig.host.includes(":") && !serverConfig.host.startsWith("[")
|
||||
? `[${serverConfig.host}]`
|
||||
: serverConfig.host;
|
||||
origins.add(`http://${host}:${serverConfig.port}`);
|
||||
}
|
||||
|
||||
if (serverConfig.devUrl) {
|
||||
origins.add(serverConfig.devUrl.origin);
|
||||
}
|
||||
|
||||
return origins;
|
||||
}
|
||||
|
||||
function formatAuthCookie(cookieValue: string, isSecure: boolean): string {
|
||||
const attributes = [
|
||||
`${AUTH_COOKIE_NAME}=${cookieValue}`,
|
||||
"HttpOnly",
|
||||
"Path=/",
|
||||
"SameSite=Strict",
|
||||
`Max-Age=${AUTH_COOKIE_MAX_AGE_SECONDS}`,
|
||||
];
|
||||
if (isSecure) {
|
||||
attributes.push("Secure");
|
||||
}
|
||||
return attributes.join("; ");
|
||||
}
|
||||
|
||||
export const BrowserAuthLive = Layer.effect(
|
||||
BrowserAuth,
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const cookieSecretPath = path.join(serverConfig.stateDir, COOKIE_SECRET_FILENAME);
|
||||
|
||||
const existingSecret = yield* fileSystem
|
||||
.readFileString(cookieSecretPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const cookieSecret =
|
||||
existingSecret && existingSecret.trim().length > 0
|
||||
? existingSecret.trim()
|
||||
: makeCookieSecret();
|
||||
|
||||
if (existingSecret === null || existingSecret.trim().length === 0) {
|
||||
yield* fileSystem.makeDirectory(path.dirname(cookieSecretPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(cookieSecretPath, `${cookieSecret}\n`);
|
||||
}
|
||||
|
||||
const bootstrapState = yield* Ref.make<BootstrapState>({
|
||||
token: makeBootstrapToken(),
|
||||
expiresAt: Date.now() + BOOTSTRAP_TOKEN_TTL_MS,
|
||||
consumedAt: null,
|
||||
});
|
||||
const allowedOrigins = normalizeOriginSet(serverConfig);
|
||||
|
||||
const getPairingUrl: BrowserAuthShape["getPairingUrl"] = (baseUrl) =>
|
||||
Ref.get(bootstrapState).pipe(
|
||||
Effect.map((state) => {
|
||||
const target = new URL(baseUrl);
|
||||
target.hash = `${BOOTSTRAP_HASH_KEY}=${state.token}`;
|
||||
return target.toString();
|
||||
}),
|
||||
);
|
||||
|
||||
const isAllowedOrigin: BrowserAuthShape["isAllowedOrigin"] = (origin) =>
|
||||
Effect.succeed(typeof origin === "string" && allowedOrigins.has(origin));
|
||||
|
||||
const consumeBootstrapToken: BrowserAuthShape["consumeBootstrapToken"] = (token) =>
|
||||
Ref.modify(bootstrapState, (state) => {
|
||||
const now = Date.now();
|
||||
const matches =
|
||||
token.length > 0 &&
|
||||
state.consumedAt === null &&
|
||||
state.expiresAt > now &&
|
||||
state.token === token;
|
||||
return [matches, matches ? { ...state, consumedAt: now } : state] as const;
|
||||
});
|
||||
|
||||
const isAuthenticatedRequest: BrowserAuthShape["isAuthenticatedRequest"] = (headers) =>
|
||||
Effect.succeed(
|
||||
verifyCookie(parseCookies(headers.cookie).get(AUTH_COOKIE_NAME) ?? "", cookieSecret),
|
||||
);
|
||||
|
||||
const createAuthCookie: BrowserAuthShape["createAuthCookie"] = (isSecure) =>
|
||||
Effect.succeed(
|
||||
formatAuthCookie(
|
||||
signCookie(
|
||||
{
|
||||
v: 1,
|
||||
purpose: "browser-auth",
|
||||
iat: Date.now(),
|
||||
exp: Date.now() + AUTH_COOKIE_MAX_AGE_SECONDS * 1_000,
|
||||
},
|
||||
cookieSecret,
|
||||
),
|
||||
isSecure,
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
getPairingUrl,
|
||||
getAllowedOrigins: Effect.succeed(allowedOrigins),
|
||||
isAllowedOrigin,
|
||||
consumeBootstrapToken,
|
||||
isAuthenticatedRequest,
|
||||
createAuthCookie,
|
||||
} satisfies BrowserAuthShape;
|
||||
}),
|
||||
);
|
||||
@@ -259,7 +259,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4666);
|
||||
assert.equal(resolvedConfig?.host, undefined);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -301,6 +301,19 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses fixed loopback defaults in web mode", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows overriding desktop host with --host", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--host", "0.0.0.0"], {
|
||||
|
||||
+37
-13
@@ -29,6 +29,7 @@ import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
import { BrowserAuth, BrowserAuthLive } from "./browserAuth";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
@@ -268,7 +269,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
() => "127.0.0.1",
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
@@ -291,20 +292,28 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
(() => {
|
||||
const serverConfigLayer = ServerConfigLive(input);
|
||||
const browserAuthLayer = BrowserAuthLive.pipe(Layer.provide(serverConfigLayer));
|
||||
return Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(browserAuthLayer),
|
||||
);
|
||||
})();
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const isLoopbackHost = (host: string | undefined): boolean =>
|
||||
host === "127.0.0.1" || host === "::1" || host === "[::1]" || host === "localhost";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
@@ -337,6 +346,7 @@ const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
@@ -357,15 +367,29 @@ const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const browserBaseUrl =
|
||||
config.host && !isWildcardHost(config.host) && !isLoopbackHost(config.host)
|
||||
? bindUrl
|
||||
: localUrl;
|
||||
const pairingUrl = yield* browserAuth.getPairingUrl(browserBaseUrl);
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
localUrl,
|
||||
pairingUrl,
|
||||
});
|
||||
|
||||
if (config.host && !isWildcardHost(config.host) && !isLoopbackHost(config.host)) {
|
||||
yield* Effect.logWarning("server is exposed beyond loopback", {
|
||||
host: config.host,
|
||||
bindUrl,
|
||||
});
|
||||
}
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
const target = pairingUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
@@ -416,7 +440,7 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withDescription("Legacy auth token for non-browser WebSocket clients."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Http from "node:http";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
@@ -56,6 +57,7 @@ import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { ServerSettingsService } from "./serverSettings.ts";
|
||||
import { BrowserAuth, BrowserAuthLive } from "./browserAuth.ts";
|
||||
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
@@ -245,6 +247,8 @@ interface SocketChannels {
|
||||
}
|
||||
|
||||
const channelsBySocket = new WeakMap<WebSocket, SocketChannels>();
|
||||
let currentBootstrapToken: string | null = null;
|
||||
let currentBrowserCookie: string | null = null;
|
||||
|
||||
function enqueue<T>(channel: MessageChannel<T>, item: T) {
|
||||
const waiter = channel.waiters.shift();
|
||||
@@ -290,10 +294,46 @@ function asWebSocketResponse(message: unknown): WebSocketResponse | null {
|
||||
return message as WebSocketResponse;
|
||||
}
|
||||
|
||||
function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
|
||||
interface ConnectWsOptions {
|
||||
readonly token?: string;
|
||||
readonly headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
async function pairBrowserSession(
|
||||
port: number,
|
||||
origin = `http://127.0.0.1:${port}`,
|
||||
): Promise<string> {
|
||||
if (!currentBootstrapToken) {
|
||||
throw new Error("Browser bootstrap token not initialized");
|
||||
}
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: origin,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
if (response.statusCode !== 204) {
|
||||
throw new Error(`Browser bootstrap failed with status ${response.statusCode}`);
|
||||
}
|
||||
|
||||
const setCookie = response.headers["set-cookie"];
|
||||
const cookieHeader = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
||||
if (!cookieHeader) {
|
||||
throw new Error("Browser bootstrap missing auth cookie");
|
||||
}
|
||||
|
||||
return cookieHeader.split(";", 1)[0] ?? "";
|
||||
}
|
||||
|
||||
function connectWsOnce(port: number, options: ConnectWsOptions = {}): Promise<WebSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
|
||||
const query = options.token ? `?token=${encodeURIComponent(options.token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`, {
|
||||
headers: options.headers,
|
||||
});
|
||||
const channels: SocketChannels = {
|
||||
push: { queue: [], waiters: [] },
|
||||
response: { queue: [], waiters: [] },
|
||||
@@ -317,12 +357,25 @@ function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
|
||||
});
|
||||
}
|
||||
|
||||
async function connectWs(port: number, token?: string, attempts = 5): Promise<WebSocket> {
|
||||
async function connectWs(
|
||||
port: number,
|
||||
options: ConnectWsOptions = {},
|
||||
attempts = 5,
|
||||
): Promise<WebSocket> {
|
||||
const normalizedOptions =
|
||||
options.token || options.headers
|
||||
? options
|
||||
: {
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
Cookie: (currentBrowserCookie ??= await pairBrowserSession(port)),
|
||||
},
|
||||
};
|
||||
let lastError: unknown = new Error("WebSocket connection failed");
|
||||
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
try {
|
||||
return await connectWsOnce(port, token);
|
||||
return await connectWsOnce(port, normalizedOptions);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt < attempts - 1) {
|
||||
@@ -337,9 +390,9 @@ async function connectWs(port: number, token?: string, attempts = 5): Promise<We
|
||||
/** Connect and wait for the server.welcome push. Returns [ws, welcomeData]. */
|
||||
async function connectAndAwaitWelcome(
|
||||
port: number,
|
||||
token?: string,
|
||||
options: ConnectWsOptions = {},
|
||||
): Promise<[WebSocket, WsPushMessage<typeof WS_CHANNELS.serverWelcome>]> {
|
||||
const ws = await connectWs(port, token);
|
||||
const ws = await connectWs(port, options);
|
||||
const welcome = await waitForPush(ws, WS_CHANNELS.serverWelcome);
|
||||
return [ws, welcome];
|
||||
}
|
||||
@@ -411,14 +464,20 @@ async function rewriteKeybindingsAndWaitForPush(
|
||||
async function requestPath(
|
||||
port: number,
|
||||
requestPath: string,
|
||||
): Promise<{ statusCode: number; body: string }> {
|
||||
options: {
|
||||
readonly method?: string;
|
||||
readonly headers?: Record<string, string>;
|
||||
readonly body?: string;
|
||||
} = {},
|
||||
): Promise<{ statusCode: number; body: string; headers: Http.IncomingHttpHeaders }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = Http.request(
|
||||
{
|
||||
hostname: "127.0.0.1",
|
||||
port,
|
||||
path: requestPath,
|
||||
method: "GET",
|
||||
method: options.method ?? "GET",
|
||||
headers: options.headers,
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
@@ -429,11 +488,15 @@ async function requestPath(
|
||||
resolve({
|
||||
statusCode: res.statusCode ?? 0,
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
headers: res.headers,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
req.once("error", reject);
|
||||
if (options.body) {
|
||||
req.write(options.body);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
@@ -483,6 +546,24 @@ describe("WebSocket Server", () => {
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function createTestServer(
|
||||
options: {
|
||||
persistenceLayer?: Layer.Layer<
|
||||
@@ -512,6 +593,7 @@ describe("WebSocket Server", () => {
|
||||
const baseDir = options.baseDir ?? makeTempDir("t3code-ws-base-");
|
||||
const devUrl = options.devUrl ? new URL(options.devUrl) : undefined;
|
||||
const derivedPaths = deriveServerPathsSync(baseDir, devUrl);
|
||||
const reservedPort = await reserveLoopbackPort();
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
||||
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
||||
@@ -522,8 +604,8 @@ describe("WebSocket Server", () => {
|
||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: undefined,
|
||||
port: reservedPort,
|
||||
host: "127.0.0.1",
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
@@ -534,6 +616,7 @@ describe("WebSocket Server", () => {
|
||||
autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false,
|
||||
logWebSocketEvents: options.logWebSocketEvents ?? Boolean(options.devUrl),
|
||||
} satisfies ServerConfigShape);
|
||||
const browserAuthLayer = BrowserAuthLive.pipe(Layer.provide(serverConfigLayer));
|
||||
const infrastructureLayer = providerLayer.pipe(Layer.provideMerge(persistenceLayer));
|
||||
const runtimeOverrides = Layer.mergeAll(
|
||||
options.gitManager ? Layer.succeed(GitManager, options.gitManager) : Layer.empty,
|
||||
@@ -558,12 +641,22 @@ describe("WebSocket Server", () => {
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(browserAuthLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtimeServices = await Effect.runPromise(
|
||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||
);
|
||||
currentBrowserCookie = null;
|
||||
currentBootstrapToken = null;
|
||||
currentBootstrapToken = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
const pairingUrl = yield* browserAuth.getPairingUrl("http://pair.test");
|
||||
return new URL(pairingUrl).hash.replace(/^#t3_bootstrap=/, "");
|
||||
}).pipe(Effect.provide(runtimeServices)),
|
||||
);
|
||||
|
||||
try {
|
||||
const runtime = await Effect.runPromise(
|
||||
@@ -591,6 +684,8 @@ describe("WebSocket Server", () => {
|
||||
connections.length = 0;
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
currentBootstrapToken = null;
|
||||
currentBrowserCookie = null;
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1954,9 +2049,120 @@ describe("WebSocket Server", () => {
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed");
|
||||
await expect(
|
||||
connectWs(port, { headers: { Origin: `http://127.0.0.1:${port}` } }),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
|
||||
const [authorizedWs] = await connectAndAwaitWelcome(port, "secret-token");
|
||||
const [authorizedWs] = await connectAndAwaitWelcome(port, { token: "secret-token" });
|
||||
connections.push(authorizedWs);
|
||||
});
|
||||
|
||||
it("issues an auth cookie from a valid bootstrap token", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
expect(String(response.headers["set-cookie"])).toContain("t3_auth=");
|
||||
});
|
||||
|
||||
it("rejects bootstrap requests from foreign origins", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: "https://evil.example",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("consumes bootstrap tokens exactly once", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const first = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
const second = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(first.statusCode).toBe(204);
|
||||
expect(second.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("reports auth session state from the browser cookie", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const unauthenticated = await requestPath(port, "/api/auth/session");
|
||||
expect(unauthenticated.statusCode).toBe(200);
|
||||
expect(JSON.parse(unauthenticated.body)).toEqual({ authenticated: false });
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
const authenticated = await requestPath(port, "/api/auth/session", {
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
Cookie: cookie,
|
||||
},
|
||||
});
|
||||
|
||||
expect(authenticated.statusCode).toBe(200);
|
||||
expect(JSON.parse(authenticated.body)).toEqual({ authenticated: true });
|
||||
});
|
||||
|
||||
it("rejects websocket connections without a browser origin", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
await expect(connectWs(port, { headers: { Cookie: cookie } })).rejects.toThrow(
|
||||
"WebSocket connection failed",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects websocket connections from a foreign origin even with a valid cookie", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
await expect(
|
||||
connectWs(port, {
|
||||
headers: {
|
||||
Origin: "https://evil.example",
|
||||
Cookie: cookie,
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
});
|
||||
});
|
||||
+191
-19
@@ -79,6 +79,7 @@ import { expandHomePath } from "./os-jank.ts";
|
||||
import { makeServerPushBus } from "./wsServer/pushBus.ts";
|
||||
import { makeServerReadiness } from "./wsServer/readiness.ts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
import { BrowserAuth } from "./browserAuth";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -122,6 +123,27 @@ function rejectUpgrade(socket: Duplex, statusCode: number, message: string): voi
|
||||
);
|
||||
}
|
||||
|
||||
function readRequestBody(request: http.IncomingMessage): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on("data", (chunk: Buffer | string) => {
|
||||
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
||||
});
|
||||
request.once("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
||||
request.once("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function corsHeaders(origin: string): Record<string, string> {
|
||||
return {
|
||||
"Access-Control-Allow-Origin": origin,
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
Vary: "Origin",
|
||||
};
|
||||
}
|
||||
|
||||
function websocketRawToString(raw: unknown): string | null {
|
||||
if (typeof raw === "string") {
|
||||
return raw;
|
||||
@@ -219,7 +241,8 @@ export type ServerRuntimeServices =
|
||||
| Keybindings
|
||||
| ServerSettingsService
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
| AnalyticsService
|
||||
| BrowserAuth;
|
||||
|
||||
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
|
||||
"ServerLifecycleError",
|
||||
@@ -256,6 +279,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const serverSettingsManager = yield* ServerSettingsService;
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -422,7 +446,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
headers: http.OutgoingHttpHeaders,
|
||||
body?: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
@@ -436,6 +460,134 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
return;
|
||||
}
|
||||
|
||||
const requestOrigin = req.headers.origin;
|
||||
const authEndpointHeaders =
|
||||
typeof requestOrigin === "string" && (yield* browserAuth.isAllowedOrigin(requestOrigin))
|
||||
? corsHeaders(requestOrigin)
|
||||
: {};
|
||||
|
||||
if (url.pathname === "/api/auth/bootstrap") {
|
||||
if (req.method === "OPTIONS") {
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
respond(204, authEndpointHeaders);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
respond(405, { "Content-Type": "text/plain" }, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(
|
||||
403,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Forbidden origin",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const bodyText = yield* Effect.tryPromise({
|
||||
try: () => readRequestBody(req),
|
||||
catch: () =>
|
||||
new RouteRequestError({ message: "Failed to read auth bootstrap request body." }),
|
||||
});
|
||||
|
||||
let parsedBody: unknown;
|
||||
try {
|
||||
parsedBody = JSON.parse(bodyText);
|
||||
} catch {
|
||||
respond(
|
||||
400,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Invalid JSON body",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const token =
|
||||
typeof parsedBody === "object" &&
|
||||
parsedBody !== null &&
|
||||
"token" in parsedBody &&
|
||||
typeof (parsedBody as { token?: unknown }).token === "string"
|
||||
? (parsedBody as { token: string }).token
|
||||
: null;
|
||||
if (!token) {
|
||||
respond(
|
||||
400,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Missing bootstrap token",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const consumed = yield* browserAuth.consumeBootstrapToken(token);
|
||||
if (!consumed) {
|
||||
respond(
|
||||
401,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Invalid bootstrap token",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const cookieHeader = yield* browserAuth.createAuthCookie(url.protocol === "https:");
|
||||
respond(204, {
|
||||
...authEndpointHeaders,
|
||||
"Set-Cookie": cookieHeader,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/auth/session") {
|
||||
if (req.method === "OPTIONS") {
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(204, {});
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
respond(204, authEndpointHeaders);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "GET") {
|
||||
respond(405, { "Content-Type": "text/plain" }, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof requestOrigin === "string" &&
|
||||
!(yield* browserAuth.isAllowedOrigin(requestOrigin))
|
||||
) {
|
||||
respond(
|
||||
403,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Forbidden origin",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const authenticated = yield* browserAuth.isAuthenticatedRequest(req.headers);
|
||||
respond(
|
||||
200,
|
||||
{ "Content-Type": "application/json", ...authEndpointHeaders },
|
||||
JSON.stringify({ authenticated }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
@@ -986,25 +1138,45 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
httpServer.on("upgrade", (request, socket, head) => {
|
||||
socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
|
||||
|
||||
if (authToken) {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
|
||||
if (providedToken !== authToken) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
}
|
||||
const requestOrigin = request.headers.origin;
|
||||
const hasLegacyToken = Boolean(authToken && providedToken === authToken);
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
if (hasLegacyToken && !requestOrigin) {
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof requestOrigin !== "string") {
|
||||
rejectUpgrade(socket, 401, "Missing WebSocket origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
rejectUpgrade(socket, 401, "Forbidden WebSocket origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAuthenticatedRequest(request.headers))) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
);
|
||||
});
|
||||
|
||||
wss.on("connection", (ws) => {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
clearBootstrapTokenFromUrl,
|
||||
consumeBootstrapTokenFromHash,
|
||||
ensureBrowserPairing,
|
||||
resolveServerHttpOrigin,
|
||||
} from "./browserAuth";
|
||||
|
||||
describe("browserAuth", () => {
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
const setTestWindow = (href: string) => {
|
||||
let currentUrl = new URL(href);
|
||||
const location = {
|
||||
get hash() {
|
||||
return currentUrl.hash;
|
||||
},
|
||||
get host() {
|
||||
return currentUrl.host;
|
||||
},
|
||||
get hostname() {
|
||||
return currentUrl.hostname;
|
||||
},
|
||||
get href() {
|
||||
return currentUrl.toString();
|
||||
},
|
||||
get origin() {
|
||||
return currentUrl.origin;
|
||||
},
|
||||
get pathname() {
|
||||
return currentUrl.pathname;
|
||||
},
|
||||
get port() {
|
||||
return currentUrl.port;
|
||||
},
|
||||
get protocol() {
|
||||
return currentUrl.protocol;
|
||||
},
|
||||
get search() {
|
||||
return currentUrl.search;
|
||||
},
|
||||
toString() {
|
||||
return currentUrl.toString();
|
||||
},
|
||||
};
|
||||
const history = {
|
||||
state: {} as unknown,
|
||||
replaceState: (state: unknown, _unused: string, nextUrl?: string | URL | null) => {
|
||||
history.state = state;
|
||||
if (!nextUrl) return;
|
||||
currentUrl = new URL(String(nextUrl));
|
||||
},
|
||||
};
|
||||
vi.stubGlobal("window", {
|
||||
location,
|
||||
history,
|
||||
nativeApi: undefined,
|
||||
desktopBridge: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
setTestWindow("http://localhost:3773/");
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("reads and clears bootstrap tokens from the url hash", () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
|
||||
expect(consumeBootstrapTokenFromHash()).toBe("pair-me");
|
||||
|
||||
clearBootstrapTokenFromUrl();
|
||||
|
||||
expect(window.location.hash).toBe("");
|
||||
expect(consumeBootstrapTokenFromHash()).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves the server http origin from the current location when no ws override exists", () => {
|
||||
setTestWindow("http://localhost:4123/chat");
|
||||
|
||||
expect(resolveServerHttpOrigin()).toBe("http://localhost:4123");
|
||||
});
|
||||
|
||||
it("exchanges a bootstrap token before checking the auth session", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: true }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://localhost:3773/api/auth/bootstrap",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://localhost:3773/api/auth/session",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("polls auth session after a successful bootstrap until the cookie is visible", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: true }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("returns false when bootstrap exchange fails", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response("nope", {
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(window.location.hash).toBe("#t3_bootstrap=pair-me");
|
||||
});
|
||||
|
||||
it("checks the existing auth session when no bootstrap token is present", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://localhost:3773/api/auth/session",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("bypasses browser pairing when the electron desktop bridge is available", async () => {
|
||||
vi.stubGlobal("window", {
|
||||
location: {
|
||||
href: "file:///app/index.html",
|
||||
origin: "file://",
|
||||
hash: "",
|
||||
},
|
||||
history: {
|
||||
state: undefined,
|
||||
replaceState: vi.fn(),
|
||||
},
|
||||
nativeApi: undefined,
|
||||
desktopBridge: {
|
||||
getWsUrl: () => "ws://127.0.0.1:3773",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
const BOOTSTRAP_HASH_KEY = "t3_bootstrap";
|
||||
const AUTH_SESSION_POLL_ATTEMPTS = 50;
|
||||
const AUTH_SESSION_POLL_INTERVAL_MS = 100;
|
||||
|
||||
interface AuthSessionResponse {
|
||||
readonly authenticated: boolean;
|
||||
}
|
||||
|
||||
function normalizeServerHttpOrigin(rawUrl: string): string {
|
||||
const wsUrl = new URL(rawUrl);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
}
|
||||
|
||||
export function resolveServerHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeServerHttpOrigin(wsCandidate);
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeBootstrapTokenFromHash(
|
||||
locationLike: Location = window.location,
|
||||
): string | null {
|
||||
const hash = locationLike.hash.startsWith("#") ? locationLike.hash.slice(1) : locationLike.hash;
|
||||
const params = new URLSearchParams(hash);
|
||||
const token = params.get(BOOTSTRAP_HASH_KEY);
|
||||
return token && token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
export function clearBootstrapTokenFromUrl(locationLike: Location = window.location): void {
|
||||
const currentUrl = new URL(locationLike.href);
|
||||
currentUrl.hash = "";
|
||||
window.history.replaceState(window.history.state, "", currentUrl.toString());
|
||||
}
|
||||
|
||||
async function exchangeBootstrapToken(serverOrigin: string, token: string): Promise<void> {
|
||||
const response = await fetch(`${serverOrigin}/api/auth/bootstrap`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Browser pairing failed with status ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSession(serverOrigin: string): Promise<boolean> {
|
||||
const response = await fetch(`${serverOrigin}/api/auth/session`, {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Auth session check failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const parsed = (await response.json()) as Partial<AuthSessionResponse>;
|
||||
return parsed.authenticated === true;
|
||||
}
|
||||
|
||||
async function waitForAuthenticatedSession(serverOrigin: string): Promise<boolean> {
|
||||
for (let attempt = 0; attempt < AUTH_SESSION_POLL_ATTEMPTS; attempt += 1) {
|
||||
if (await fetchSession(serverOrigin)) {
|
||||
return true;
|
||||
}
|
||||
if (attempt < AUTH_SESSION_POLL_ATTEMPTS - 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, AUTH_SESSION_POLL_INTERVAL_MS));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function ensureBrowserPairing(): Promise<boolean> {
|
||||
if (typeof window === "undefined") return false;
|
||||
if (window.nativeApi || window.desktopBridge) return true;
|
||||
|
||||
const serverOrigin = resolveServerHttpOrigin();
|
||||
const bootstrapToken = consumeBootstrapTokenFromHash();
|
||||
|
||||
if (bootstrapToken) {
|
||||
try {
|
||||
await exchangeBootstrapToken(serverOrigin, bootstrapToken);
|
||||
clearBootstrapTokenFromUrl();
|
||||
return waitForAuthenticatedSession(serverOrigin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fetchSession(serverOrigin);
|
||||
}
|
||||
+114
-1
@@ -9,6 +9,8 @@ import "./index.css";
|
||||
import { isElectron } from "./env";
|
||||
import { getRouter } from "./router";
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { ensureBrowserPairing } from "./browserAuth";
|
||||
import { initializeNativeApi } from "./nativeApi";
|
||||
|
||||
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
@@ -16,9 +18,120 @@ const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
const router = getRouter(history);
|
||||
|
||||
document.title = APP_DISPLAY_NAME;
|
||||
const UNPAIRED_RETRY_INTERVAL_MS = 1_000;
|
||||
|
||||
function PairingRequiredScreen() {
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
|
||||
<div className="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(42rem_16rem_at_top,color-mix(in_srgb,var(--color-amber-500)_16%,transparent),transparent)]" />
|
||||
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_92%,var(--color-black))_0%,var(--background)_56%)]" />
|
||||
</div>
|
||||
|
||||
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
|
||||
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
|
||||
{APP_DISPLAY_NAME}
|
||||
</p>
|
||||
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
|
||||
Browser pairing required
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||
This browser is not paired with the local T3 session.
|
||||
</p>
|
||||
<p className="mt-3 text-sm leading-relaxed text-muted-foreground">
|
||||
Restart <code>t3</code> to open a paired browser, or open the pairing URL printed in the
|
||||
CLI.
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BootstrappedApp() {
|
||||
const [state, setState] = React.useState<"loading" | "ready" | "unpaired">("loading");
|
||||
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
void ensureBrowserPairing()
|
||||
.then((authenticated) => {
|
||||
if (!active) return;
|
||||
if (!authenticated) {
|
||||
setState("unpaired");
|
||||
return;
|
||||
}
|
||||
initializeNativeApi();
|
||||
setState("ready");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
setState("unpaired");
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (state !== "unpaired") {
|
||||
return;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
let retryTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const retry = () => {
|
||||
void ensureBrowserPairing()
|
||||
.then((authenticated) => {
|
||||
if (!active || !authenticated) {
|
||||
if (active) {
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
}
|
||||
return;
|
||||
}
|
||||
initializeNativeApi();
|
||||
setState("ready");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
if (retryTimeout !== null) {
|
||||
clearTimeout(retryTimeout);
|
||||
}
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
if (state === "loading") {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connecting to {APP_DISPLAY_NAME} server...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (state === "unpaired") {
|
||||
return <PairingRequiredScreen />;
|
||||
}
|
||||
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
<BootstrappedApp />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -4,6 +4,21 @@ import { createWsNativeApi } from "./wsNativeApi";
|
||||
|
||||
let cachedApi: NativeApi | undefined;
|
||||
|
||||
export function initializeNativeApi(): NativeApi {
|
||||
if (typeof window === "undefined") {
|
||||
throw new Error("Native API not available outside the browser");
|
||||
}
|
||||
if (cachedApi) return cachedApi;
|
||||
|
||||
if (window.nativeApi) {
|
||||
cachedApi = window.nativeApi;
|
||||
return cachedApi;
|
||||
}
|
||||
|
||||
cachedApi = createWsNativeApi();
|
||||
return cachedApi;
|
||||
}
|
||||
|
||||
export function readNativeApi(): NativeApi | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
if (cachedApi) return cachedApi;
|
||||
|
||||
+2
-22
@@ -9,6 +9,7 @@ import { resolveModelSlugForProvider } from "@t3tools/shared/model";
|
||||
import { create } from "zustand";
|
||||
import { type ChatMessage, type Project, type Thread } from "./types";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
import { resolveServerHttpOrigin } from "./browserAuth";
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -199,30 +200,9 @@ function toLegacyProvider(providerName: string | null): ProviderKind {
|
||||
return "codex";
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
if (!wsCandidate) return window.location.origin;
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
function toAttachmentPreviewUrl(rawUrl: string): string {
|
||||
if (rawUrl.startsWith("/")) {
|
||||
return `${resolveWsHttpOrigin()}${rawUrl}`;
|
||||
return `${resolveServerHttpOrigin()}${rawUrl}`;
|
||||
}
|
||||
return rawUrl;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user