Compare commits

...
64 changed files with 2132 additions and 545 deletions

No files matched your search

+5
View File
@@ -10,3 +10,8 @@
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Public, ingest-only mobile OpenTelemetry configuration.
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
@@ -64,6 +64,13 @@ function mockSpawnerLayer(statusJson = "{}") {
);
}
function dieOnSpawnLayer() {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
);
}
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
return makeDesktopEnvironmentLayer({
dirname: "/repo/apps/desktop/src",
@@ -86,6 +93,7 @@ function makeLayer(input: {
readonly baseDir: string;
readonly networkInterfaces?: DesktopNetworkInterfaces;
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
@@ -97,7 +105,7 @@ function makeLayer(input: {
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(mockSpawnerLayer()),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
Layer.provideMerge(networkLayer),
Layer.provideMerge(DesktopConfig.layerTest(env)),
Layer.provideMerge(environmentLayer),
@@ -116,13 +124,23 @@ const withHarness = <A, E, R>(
| DesktopAppSettings.DesktopAppSettings
>,
env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-server-exposure-test-",
});
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
return yield* effect.pipe(
Effect.provide(
makeLayer({
baseDir,
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
}),
),
);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
describe("DesktopServerExposure", () => {
@@ -239,6 +257,27 @@ describe("DesktopServerExposure", () => {
),
);
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
// mode stays at default "local-only", tailscaleServeEnabled stays false.
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
// would have crashed the test if the gate was missing.
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["http://127.0.0.1:4173/"],
);
}),
{},
dieOnSpawnLayer(),
),
);
it.effect("uses ConfigProvider desktop exposure overrides", () =>
withHarness(
lanNetworkInterfaces,
@@ -12,6 +12,7 @@ import type {
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -22,8 +23,11 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
@@ -412,6 +416,18 @@ const make = Effect.gen(function* () {
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
const stateRef = yield* Ref.make(initialRuntimeState());
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
// Store Tailscale CLI lives inside Tailscale's sandbox container, so each
// spawn re-triggers the "Other apps" TCC prompt.
const cachedReadMagicDnsName = yield* Effect.cachedWithTTL(
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
),
TAILSCALE_STATUS_CACHE_TTL,
);
const readNetworkInterfaces = networkInterfaces.read;
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
@@ -516,11 +532,20 @@ const make = Effect.gen(function* () {
exposure: toResolvedExposure(state),
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
});
// Don't spawn the Tailscale CLI when the user hasn't opted into any
// network exposure. The spawn itself triggers a macOS "Other apps"
// TCC prompt on Mac App Store Tailscale builds.
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
return coreEndpoints;
}
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: state.port,
serveEnabled: state.tailscaleServeEnabled,
servePort: state.tailscaleServePort,
networkInterfaces: currentNetworkInterfaces,
readMagicDnsName: cachedReadMagicDnsName,
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
@@ -104,6 +104,25 @@ describe("tailscale endpoint provider", () => {
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
Effect.gen(function* () {
let readerCalls = 0;
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
readMagicDnsName: Effect.sync(() => {
readerCalls += 1;
return "desktop.tail.ts.net";
}),
});
assert.equal(readerCalls, 1);
assert.deepEqual(
endpoints.map((endpoint) => endpoint.httpBaseUrl),
["https://desktop.tail.ts.net/"],
);
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
);
it.effect(
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
() =>
@@ -105,6 +105,11 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
readonly servePort?: number;
readonly networkInterfaces: DesktopNetworkInterfaces;
readonly statusJson?: string | null;
readonly readMagicDnsName?: Effect.Effect<
string | null,
never,
ChildProcessSpawner.ChildProcessSpawner
>;
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
}): Effect.fn.Return<
readonly AdvertisedEndpoint[],
@@ -112,12 +117,15 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const readDnsName =
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed<string | null>(null)),
);
const dnsName =
input.statusJson === undefined
? yield* readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
)
? yield* readDnsName
: input.statusJson
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.orElseSucceed(() => null),
+34 -42
View File
@@ -1,29 +1,35 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { afterEach } from "vite-plus/test";
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
const originalFetch = globalThis.fetch;
const clerkPublishableKey = (hostname: string): string =>
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
function makeHttpClientLayer(
handler: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
) {
return Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => handler(request)),
);
}
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
const calls: Array<FetchCall> = [];
let responseIndex = 0;
const fetchFn = ((input, init) => {
calls.push([input, init ?? {}]);
const response = responses[responseIndex++];
if (!response) {
return Promise.reject(new Error("Unexpected fetch call"));
}
return Promise.resolve(response);
}) satisfies typeof fetch;
return { fetchFn, calls };
};
describe("Desktop cloud auth IPC", () => {
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalClerkPublishableKey === undefined) {
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
} else {
@@ -33,16 +39,8 @@ describe("Desktop cloud auth IPC", () => {
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "sign_in_attempt" } }),
);
}),
);
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -55,32 +53,25 @@ describe("Desktop cloud auth IPC", () => {
body,
});
assert(forwardedRequest !== null);
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
const [url, init] = forwardedRequest;
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
assert.equal(init.method, "POST");
assert.equal(
forwardedRequest.headers["content-type"],
new Headers(init.headers).get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8",
);
assert.equal(forwardedRequest.body._tag, "Uint8Array");
if (forwardedRequest.body._tag === "Uint8Array") {
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
}
}).pipe(Effect.provide(layer));
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
});
});
it.effect(
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
() => {
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
const layer = makeHttpClientLayer((request) =>
Effect.sync(() => {
forwardedRequest = request;
return HttpClientResponse.fromWeb(
request,
Response.json({ response: { object: "client" } }),
);
}),
);
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
globalThis.fetch = fetch.fetchFn;
return Effect.gen(function* () {
yield* fetchCloudAuth.handler({
@@ -89,9 +80,10 @@ describe("Desktop cloud auth IPC", () => {
headers: {},
});
assert(forwardedRequest !== null);
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
}).pipe(Effect.provide(layer));
const forwardedRequest = fetch.calls[0];
assert(forwardedRequest !== undefined);
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
});
},
);
+66 -43
View File
@@ -8,9 +8,11 @@ import {
} from "@t3tools/shared/relayAuth";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
@@ -52,6 +54,68 @@ export function validateClerkFrontendApiUrl(rawUrl: string): URL {
return url;
}
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
return Effect.gen(function* () {
const method = (input.method ?? "GET") as "GET" | "POST";
const headers = new Headers(input.headers);
const response = yield* HttpClientRequest.make(method)(url).pipe(
HttpClientRequest.setHeaders(headers),
input.body === undefined
? identity
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
HttpClient.execute,
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed to execute.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
});
}
const electronNetFetchLayer = Layer.unwrap(
Effect.gen(function* () {
const electronFetch = yield* Effect.promise(async () => {
const electron = (await import("electron")) as {
readonly net?: { readonly fetch?: typeof globalThis.fetch };
};
return typeof electron.net?.fetch === "function"
? electron.net.fetch.bind(electron.net)
: null;
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
if (!electronFetch) {
yield* Effect.logWarning(
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
);
}
return FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
);
}),
);
export const createCloudAuthRequest = makeIpcMethod({
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
payload: Schema.Void,
@@ -108,47 +172,6 @@ export const fetchCloudAuth = makeIpcMethod({
}),
});
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
url,
{
headers: input.headers,
},
);
const request =
input.body === undefined
? requestWithoutBody
: HttpClientRequest.bodyText(
requestWithoutBody,
input.body,
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
);
const response = yield* HttpClient.execute(request).pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch failed.",
cause,
}),
),
);
const body = yield* response.text.pipe(
Effect.mapError(
(cause) =>
new DesktopCloudAuthFetchError({
reason: "Desktop cloud auth fetch response could not be read.",
cause,
}),
),
);
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
statusText: "",
headers: response.headers,
body,
};
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
}),
});
+5
View File
@@ -161,6 +161,11 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
tracesToken: repoEnv.EXPO_PUBLIC_OTLP_TRACES_TOKEN ?? null,
},
eas: {
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
},
@@ -41,7 +41,7 @@ export function normalizeAgentAwarenessRelayBaseUrl(
}
function readRelayConfig(): { readonly url: string } | null {
const relayUrl = resolveCloudPublicConfig().relayUrl;
const relayUrl = resolveCloudPublicConfig().relay.url;
if (!relayUrl) {
logRegistrationDebug("relay registration skipped; relay config missing");
return null;
@@ -66,7 +66,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
const config = resolveCloudPublicConfig();
const publishableKey = config.clerk.publishableKey;
const relayUrl = config.relay.url;
useEffect(() => {
if (!publishableKey || !relayUrl) {
@@ -50,7 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
}
function readRelayUrl(): string | null {
return resolveCloudPublicConfig().relayUrl;
return resolveCloudPublicConfig().relay.url;
}
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
@@ -1,7 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
ManagedRelayClient,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime";
@@ -9,23 +8,13 @@ import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
import { mobileRuntime } from "../../lib/runtime";
import { mobileRuntimeContextLayer } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
const managedRelayAtomRuntime = Atom.runtime(
Layer.effect(
ManagedRelayClient,
mobileRuntime.contextEffect.pipe(
Effect.map((context) => Context.get(context, ManagedRelayClient)),
),
),
);
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { resolveCloudPublicConfig } from "./publicConfig";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
@@ -13,9 +13,18 @@ vi.mock("expo-constants", () => ({
describe("resolveCloudPublicConfig", () => {
it("returns no cloud configuration for an unconfigured build", () => {
expect(resolveCloudPublicConfig({})).toEqual({
clerkPublishableKey: null,
clerkJwtTemplate: null,
relayUrl: null,
clerk: {
publishableKey: null,
jwtTemplate: null,
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
});
});
@@ -24,11 +33,25 @@ describe("resolveCloudPublicConfig", () => {
resolveCloudPublicConfig({
clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " },
relay: { url: " https://relay.example.test/// " },
observability: {
tracesUrl: " https://api.axiom.co/v1/traces ",
tracesDataset: " mobile-traces ",
tracesToken: " public-ingest-token ",
},
}),
).toEqual({
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: "https://relay.example.test",
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: "https://relay.example.test",
},
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
});
});
@@ -39,9 +62,59 @@ describe("resolveCloudPublicConfig", () => {
relay: { url: "http://relay.example.test" },
}),
).toEqual({
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: null,
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
});
});
it("rejects an insecure traces URL", () => {
expect(
resolveCloudPublicConfig({
observability: {
tracesUrl: "http://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
}).observability,
).toEqual({
tracesUrl: null,
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
});
});
it("keeps tracing disabled unless every public tracing value is configured", () => {
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
expect(
hasMobileTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
},
}),
),
).toBe(false);
expect(
hasMobileTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
}),
),
).toBe(true);
});
});
+69 -17
View File
@@ -2,40 +2,92 @@ import Constants from "expo-constants";
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
export interface CloudPublicConfig {
readonly clerkPublishableKey: string | null;
readonly clerkJwtTemplate: string | null;
readonly relayUrl: string | null;
readonly clerk: {
readonly publishableKey: string | null;
readonly jwtTemplate: string | null;
};
readonly relay: {
readonly url: string | null;
};
readonly observability: {
readonly tracesUrl: string | null;
readonly tracesDataset: string | null;
readonly tracesToken: string | null;
};
}
type UntrustedSection<T> = {
readonly [Key in keyof T]?: unknown;
};
type ExpoExtra =
| {
readonly [Section in keyof CloudPublicConfig]?: UntrustedSection<CloudPublicConfig[Section]>;
}
| undefined;
function trimNonEmpty(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
const clerk = extra?.clerk as
| { readonly publishableKey?: unknown; readonly jwtTemplate?: unknown }
| undefined;
const relay = extra?.relay as { readonly url?: unknown } | undefined;
function normalizeSecureUrl(value: unknown): string | null {
const raw = trimNonEmpty(value);
if (raw === null) {
return null;
}
try {
const url = new URL(raw);
return url.protocol === "https:" ? url.toString() : null;
} catch {
return null;
}
}
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
return {
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
clerk: {
publishableKey: trimNonEmpty(extra?.clerk?.publishableKey),
jwtTemplate: trimNonEmpty(extra?.clerk?.jwtTemplate),
},
relay: {
url: normalizeSecureRelayUrl(trimNonEmpty(extra?.relay?.url) ?? ""),
},
observability: {
tracesUrl: normalizeSecureUrl(extra?.observability?.tracesUrl),
tracesDataset: trimNonEmpty(extra?.observability?.tracesDataset),
tracesToken: trimNonEmpty(extra?.observability?.tracesToken),
},
} satisfies CloudPublicConfig;
}
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
return Boolean(config.clerk.publishableKey && config.clerk.jwtTemplate && config.relay.url);
}
type Configured<T> = {
readonly [Key in keyof T]: NonNullable<T[Key]>;
};
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
readonly observability: Configured<CloudPublicConfig["observability"]>;
};
export function hasMobileTracingPublicConfig(
config: CloudPublicConfig = resolveCloudPublicConfig(),
): config is MobileTracingPublicConfig {
return Boolean(
config.observability.tracesUrl &&
config.observability.tracesDataset &&
config.observability.tracesToken,
);
}
export function resolveRelayClerkTokenOptions() {
const { clerkJwtTemplate } = resolveCloudPublicConfig();
if (!clerkJwtTemplate) {
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
if (!jwtTemplate) {
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
}
return relayClerkTokenOptions(clerkJwtTemplate);
return relayClerkTokenOptions(jwtTemplate);
}
@@ -0,0 +1,52 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { makeMobileTracingLayer } from "./mobileTracing";
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
extra: {},
},
},
}));
it.effect("exports spans through the scoped mobile OTLP layer", () => {
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
const tracingLayer = makeMobileTracingLayer(
{
tracesUrl: "https://api.axiom.test/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
{
appVariant: "test",
serviceVersion: "1.2.3",
},
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
const tracedApplication = Layer.effectDiscard(
Effect.void.pipe(Effect.withSpan("mobile.test.span")),
).pipe(Layer.provide(tracingLayer));
return Effect.gen(function* () {
yield* Layer.build(tracedApplication);
expect(fetchFn).not.toHaveBeenCalled();
}).pipe(
Effect.scoped,
Effect.andThen(
Effect.sync(() => {
expect(fetchFn).toHaveBeenCalledOnce();
const [url, init] = fetchFn.mock.calls[0]!;
expect(String(url)).toBe("https://api.axiom.test/v1/traces");
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");
expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");
expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");
}),
),
);
});
@@ -0,0 +1,60 @@
import Constants from "expo-constants";
import * as Layer from "effect/Layer";
import type { HttpClient } from "effect/unstable/http";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
export interface MobileTracingConfig {
readonly tracesUrl: string;
readonly tracesDataset: string;
readonly tracesToken: string;
}
export interface MobileTracingResource {
readonly serviceVersion?: string;
readonly appVariant: string;
}
export function resolveMobileTracingConfig(): MobileTracingConfig | null {
const config = resolveCloudPublicConfig();
if (!hasMobileTracingPublicConfig(config)) {
return null;
}
const { tracesUrl, tracesDataset, tracesToken } = config.observability;
return { tracesUrl, tracesDataset, tracesToken };
}
export function makeMobileTracingLayer(
config: MobileTracingConfig | null,
resource: MobileTracingResource,
): Layer.Layer<never, never, HttpClient.HttpClient> {
if (config === null) {
return Layer.empty;
}
return OtlpTracer.layer({
url: config.tracesUrl,
headers: {
Authorization: `Bearer ${config.tracesToken}`,
"X-Axiom-Dataset": config.tracesDataset,
},
resource: {
serviceName: "t3-mobile",
serviceVersion: resource.serviceVersion,
attributes: {
"service.runtime": "react-native",
"service.component": "mobile",
"deployment.environment.name": resource.appVariant,
},
},
}).pipe(Layer.provide(OtlpSerialization.layerJson));
}
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), {
serviceVersion: Constants.expoConfig?.version,
appVariant:
typeof Constants.expoConfig?.extra?.appVariant === "string"
? Constants.expoConfig.extra.appVariant
: "unknown",
});
+8 -7
View File
@@ -6,19 +6,20 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { mobileCryptoLayer } from "../features/cloud/dpop";
import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer";
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
import { mobileTracingLayer } from "../features/observability/mobileTracing";
function configuredRelayUrl(): string {
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
}
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
export const mobileRuntime = ManagedRuntime.make(
Layer.mergeAll(
mobileHttpClientLayer,
mobileCryptoLayer,
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
),
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provideMerge(mobileCryptoLayer),
Layer.provideMerge(mobileHttpClientLayer),
Layer.provideMerge(mobileTracingLayer.pipe(Layer.provide(mobileHttpClientLayer))),
),
);
export const mobileRuntimeContextLayer = Layer.effectContext(mobileRuntime.contextEffect);
@@ -1,3 +1,4 @@
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -18,6 +19,7 @@ export const ObservabilityLive = Layer.unwrap(
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
httpHeaderRedactionLayer,
);
const tracerLayer = Layer.unwrap(
@@ -344,6 +344,26 @@ function runtimeEventToActivities(
];
}
case "tool.denied": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "error",
kind: "tool.denied",
summary: `Tool denied: ${event.payload.toolName}`,
payload: {
toolName: event.payload.toolName,
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
...(event.payload.reason ? { detail: truncateDetail(event.payload.reason) } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "runtime.warning": {
return [
{
@@ -351,7 +371,9 @@ function runtimeEventToActivities(
createdAt: event.createdAt,
tone: "info",
kind: "runtime.warning",
summary: "Runtime warning",
// Use the adapter-supplied message as the row label so the work log
// shows what the warning was about, not a generic "Runtime warning".
summary: truncateDetail(event.payload.message, 120),
payload: {
message: truncateDetail(event.payload.message),
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
@@ -972,6 +972,52 @@ function sdkNativeMethod(message: SDKMessage): string {
return `claude/${message.type}`;
}
// Discriminator/identity keys carry no human-readable content; everything else
// on an unmodeled SDK message is potentially worth surfacing in the work log.
const SDK_MESSAGE_NOISE_KEYS = new Set([
"type",
"subtype",
"uuid",
"parent_uuid",
"session_id",
"parent_tool_use_id",
"request_id",
]);
// Pull the salient scalar content out of a message the adapter doesn't model
// yet, so the work-log row shows what actually arrived (e.g. a notification's
// text) instead of an opaque "unhandled subtype" placeholder. Nested structures
// are left to the full payload retained in the event's `detail`.
function previewUnknownSdkContent(message: unknown): string | undefined {
if (!message || typeof message !== "object") {
return undefined;
}
const parts: string[] = [];
for (const [key, value] of Object.entries(message as Record<string, unknown>)) {
if (SDK_MESSAGE_NOISE_KEYS.has(key)) {
continue;
}
if (typeof value === "string") {
const trimmed = value.trim();
if (trimmed.length > 0) {
parts.push(`${key}: ${trimmed}`);
}
} else if (typeof value === "number" || typeof value === "boolean") {
parts.push(`${key}: ${String(value)}`);
}
}
if (parts.length === 0) {
return undefined;
}
const joined = parts.join(" · ");
return joined.length > 280 ? `${joined.slice(0, 279)}…` : joined;
}
function describeUnknownSdkMessage(kind: string, message: unknown): string {
const preview = previewUnknownSdkContent(message);
return preview ? `${kind} — ${preview}` : `${kind} (no displayable text content)`;
}
function sdkNativeItemId(message: SDKMessage): string | undefined {
if (message.type === "assistant") {
const maybeId = (message.message as { id?: unknown }).id;
@@ -2267,10 +2313,31 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
case "thinking_tokens":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
type: "tool.denied",
payload: {
toolName: message.tool_name,
...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),
...(message.decision_reason ? { reason: message.decision_reason } : {}),
...(message.agent_id ? { agentId: message.agent_id } : {}),
},
});
return;
case "mirror_error":
yield* emitRuntimeError(
context,
`Claude workspace mirror error: ${message.error}`,
message,
);
return;
default:
yield* emitRuntimeWarning(
context,
`Unhandled Claude system message subtype '${message.subtype}'.`,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
message,
);
return;
@@ -2384,7 +2451,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
default:
yield* emitRuntimeWarning(
context,
`Unhandled Claude SDK message type '${message.type}'.`,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
message,
);
return;
@@ -392,5 +392,20 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
expect(error.detail).toBe("Relative filesystem browse paths require a current project.");
}),
);
it.effect("returns an empty listing when the OS denies directory access", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries;
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-eacces-" });
const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });
vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce(denied);
const result = yield* workspaceEntries.browse({
partialPath: appendSeparator(cwd),
});
expect(result).toEqual({ parentPath: cwd, entries: [] });
}),
);
});
});
@@ -457,7 +457,18 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
cause,
}),
});
}).pipe(
// The user can deny macOS TCC prompts for the target dir (Documents,
// Downloads, Music, etc.); surface an empty listing instead of an
// error so the caller doesn't retry-loop the prompt.
Effect.catchIf(
(error) => {
const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
return code === "EACCES" || code === "EPERM";
},
() => Effect.succeed<Dirent[]>([]),
),
);
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
+6 -20
View File
@@ -562,11 +562,7 @@ function OpenCommandPaletteDialog() {
!relativePathNeedsActiveProject,
});
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
const {
filteredEntries: filteredBrowseEntries,
highlightedEntry: highlightedBrowseEntry,
exactEntry: exactBrowseEntry,
} = useMemo(
const { filteredEntries: filteredBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
() => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }),
[browseEntries, browseFilterQuery, highlightedItemValue],
);
@@ -587,27 +583,17 @@ function OpenCommandPaletteDialog() {
[browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient],
);
// Prefetch the parent and the most likely next child so browse navigation
// stays warm without scanning every child directory in large trees.
// Prefetch only the parent (for back-navigation). Prefetching the
// highlighted child on every arrow-key press triggers a macOS TCC prompt
// whenever the highlighted entry is a permission-gated home dir (Music,
// Documents, Downloads, Desktop, etc.), so we wait for explicit navigation.
useEffect(() => {
if (!isBrowsing || filteredBrowseEntries.length === 0) return;
if (canNavigateUp(query)) {
prefetchBrowsePath(getBrowseParentPath(query)!);
}
const nextChild = highlightedBrowseEntry ?? exactBrowseEntry;
if (nextChild) {
prefetchBrowsePath(appendBrowsePathSegment(query, nextChild.name));
}
}, [
exactBrowseEntry,
filteredBrowseEntries.length,
highlightedBrowseEntry,
isBrowsing,
prefetchBrowsePath,
query,
]);
}, [filteredBrowseEntries.length, isBrowsing, prefetchBrowsePath, query]);
const openProjectFromSearch = useMemo(
() => async (project: (typeof projects)[number]) => {
+73 -82
View File
@@ -284,11 +284,7 @@ interface SidebarThreadRowProps {
isActive: boolean;
jumpLabel: string | null;
appSettingsConfirmThreadArchive: boolean;
renamingThreadKey: string | null;
renamingTitle: string;
setRenamingTitle: (title: string) => void;
renamingInputRef: React.RefObject<HTMLInputElement | null>;
renamingCommittedRef: React.RefObject<boolean>;
isRenaming: boolean;
confirmingArchiveThreadKey: string | null;
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
@@ -314,17 +310,77 @@ interface SidebarThreadRowProps {
openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void;
}
interface SidebarThreadRenameInputProps {
thread: SidebarThreadSummary;
threadRef: ScopedThreadRef;
commitRename: (
threadRef: ScopedThreadRef,
newTitle: string,
originalTitle: string,
) => Promise<void>;
cancelRename: () => void;
}
const SidebarThreadRenameInput = memo(function SidebarThreadRenameInput({
thread,
threadRef,
commitRename,
cancelRename,
}: SidebarThreadRenameInputProps) {
const [title, setTitle] = useState(thread.title);
const committedRef = useRef(false);
const handleInputRef = useCallback((element: HTMLInputElement | null) => {
if (!element) return;
element.focus();
element.select();
}, []);
const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setTitle(event.target.value);
}, []);
const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
event.stopPropagation();
if (event.key === "Enter") {
event.preventDefault();
committedRef.current = true;
void commitRename(threadRef, title, thread.title);
} else if (event.key === "Escape") {
event.preventDefault();
committedRef.current = true;
cancelRename();
}
},
[cancelRename, commitRename, thread.title, threadRef, title],
);
const handleBlur = useCallback(() => {
if (!committedRef.current) {
void commitRename(threadRef, title, thread.title);
}
}, [commitRename, thread.title, threadRef, title]);
const handleClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
event.stopPropagation();
}, []);
return (
<input
ref={handleInputRef}
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={title}
onChange={handleChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
onClick={handleClick}
/>
);
});
const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
const {
orderedProjectThreadKeys,
isActive,
jumpLabel,
appSettingsConfirmThreadArchive,
renamingThreadKey,
renamingTitle,
setRenamingTitle,
renamingInputRef,
renamingCommittedRef,
isRenaming,
confirmingArchiveThreadKey,
setConfirmingArchiveThreadKey,
confirmArchiveButtonRefs,
@@ -454,45 +510,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
},
[openPrLink, prStatus],
);
const handleRenameInputRef = useCallback(
(element: HTMLInputElement | null) => {
if (element && renamingInputRef.current !== element) {
renamingInputRef.current = element;
element.focus();
element.select();
}
},
[renamingInputRef],
);
const handleRenameInputChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setRenamingTitle(event.target.value);
},
[setRenamingTitle],
);
const handleRenameInputKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
event.stopPropagation();
if (event.key === "Enter") {
event.preventDefault();
renamingCommittedRef.current = true;
void commitRename(threadRef, renamingTitle, thread.title);
} else if (event.key === "Escape") {
event.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
},
[cancelRename, commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef],
);
const handleRenameInputBlur = useCallback(() => {
if (!renamingCommittedRef.current) {
void commitRename(threadRef, renamingTitle, thread.title);
}
}, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]);
const handleRenameInputClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
event.stopPropagation();
}, []);
const handleConfirmArchiveRef = useCallback(
(element: HTMLButtonElement | null) => {
if (element) {
@@ -578,15 +595,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{renamingThreadKey === threadKey ? (
<input
ref={handleRenameInputRef}
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={handleRenameInputChange}
onKeyDown={handleRenameInputKeyDown}
onBlur={handleRenameInputBlur}
onClick={handleRenameInputClick}
{isRenaming ? (
<SidebarThreadRenameInput
thread={thread}
threadRef={threadRef}
commitRename={commitRename}
cancelRename={cancelRename}
/>
) : (
<Tooltip>
@@ -734,10 +748,6 @@ interface SidebarProjectThreadListProps {
threadJumpLabelByKey: ReadonlyMap<string, string>;
appSettingsConfirmThreadArchive: boolean;
renamingThreadKey: string | null;
renamingTitle: string;
setRenamingTitle: (title: string) => void;
renamingInputRef: React.RefObject<HTMLInputElement | null>;
renamingCommittedRef: React.RefObject<boolean>;
confirmingArchiveThreadKey: string | null;
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
@@ -784,10 +794,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
threadJumpLabelByKey,
appSettingsConfirmThreadArchive,
renamingThreadKey,
renamingTitle,
setRenamingTitle,
renamingInputRef,
renamingCommittedRef,
confirmingArchiveThreadKey,
setConfirmingArchiveThreadKey,
confirmArchiveButtonRefs,
@@ -834,11 +840,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
isActive={activeRouteThreadKey === threadKey}
jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null}
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
renamingThreadKey={renamingThreadKey}
renamingTitle={renamingTitle}
setRenamingTitle={setRenamingTitle}
renamingInputRef={renamingInputRef}
renamingCommittedRef={renamingCommittedRef}
isRenaming={renamingThreadKey === threadKey}
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
@@ -1058,7 +1060,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
),
);
const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null);
const [projectRenameTarget, setProjectRenameTarget] = useState<SidebarProjectGroupMember | null>(
null,
@@ -1069,8 +1070,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const [projectGroupingSelection, setProjectGroupingSelection] = useState<
SidebarProjectGroupingMode | "inherit"
>("inherit");
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>());
const memberProjectByScopedKey = useMemo(
() =>
@@ -1762,7 +1761,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const cancelRename = useCallback(() => {
setRenamingThreadKey(null);
renamingInputRef.current = null;
}, []);
const commitRename = useCallback(
@@ -1771,7 +1769,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const finishRename = () => {
setRenamingThreadKey((current) => {
if (current !== threadKey) return current;
renamingInputRef.current = null;
return null;
});
};
@@ -1925,8 +1922,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
if (clicked === "rename") {
setRenamingThreadKey(threadKey);
setRenamingTitle(thread.title);
renamingCommittedRef.current = false;
return;
}
@@ -2088,10 +2083,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
threadJumpLabelByKey={threadJumpLabelByKey}
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
renamingThreadKey={renamingThreadKey}
renamingTitle={renamingTitle}
setRenamingTitle={setRenamingTitle}
renamingInputRef={renamingInputRef}
renamingCommittedRef={renamingCommittedRef}
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
+2
View File
@@ -4,6 +4,7 @@ import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import {
PrimaryEnvironmentHttpClient,
primaryEnvironmentHttpClientLive,
@@ -28,6 +29,7 @@ const primaryHttpRuntime = ManagedRuntime.make(
Layer.mergeAll(
remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)),
Layer.succeed(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit),
httpHeaderRedactionLayer,
),
),
),
+5
View File
@@ -8,6 +8,7 @@ import * as Layer from "effect/Layer";
import * as Planetscale from "alchemy/Planetscale";
import { PlanetscaleDatabase, RelayHyperdrive } from "./src/db.ts";
import { RelayObservability } from "./src/observability.ts";
import { ManagedEndpointZone, RelayApiZone } from "./src/zone.ts";
import Api from "./src/worker.ts";
@@ -27,6 +28,7 @@ export default Alchemy.Stack(
const hyperdrive = yield* RelayHyperdrive;
const managedEndpointZone = yield* ManagedEndpointZone.pipe(Effect.orDie);
const relayApiZone = yield* RelayApiZone.pipe(Effect.orDie);
const observability = yield* RelayObservability;
const api = yield* Api;
return {
@@ -37,6 +39,9 @@ export default Alchemy.Stack(
url: api.url,
relayApiZoneId: relayApiZone.zoneId,
managedEndpointZoneId: managedEndpointZone.zoneId,
mobileTracingUrl: observability.traces.otelTracesEndpoint,
mobileTracingDataset: observability.traces.name,
mobileTracingToken: observability.mobileIngestToken.token,
};
}),
);
+52 -1
View File
@@ -1,6 +1,11 @@
import { describe, expect, it } from "vite-plus/test";
import { hasDeployChanges, reconcileRootEnvRelayUrl, serializeGithubOutput } from "./deploy.ts";
import {
hasDeployChanges,
reconcileRootEnvPublicConfig,
reconcileRootEnvRelayUrl,
serializeGithubOutput,
} from "./deploy.ts";
describe("hasDeployChanges", () => {
it("detects resource, binding, and deletion changes", () => {
@@ -51,6 +56,52 @@ describe("reconcileRootEnvRelayUrl", () => {
});
});
describe("reconcileRootEnvPublicConfig", () => {
const config = {
relayUrl: "https://relay.example.test",
mobileTracingUrl: "https://api.axiom.co/v1/traces",
mobileTracingDataset: "t3-code-mobile-traces-dev",
mobileTracingToken: "xaat-public-ingest",
} as const;
it("adds the complete local client config", () => {
expect(reconcileRootEnvPublicConfig("", config)).toBe(
[
"T3CODE_RELAY_URL=https://relay.example.test",
"T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",
"",
].join("\n"),
);
});
it("replaces stale values while preserving unrelated entries", () => {
expect(
reconcileRootEnvPublicConfig(
[
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example",
"T3CODE_RELAY_URL=https://old.example.test",
"T3CODE_MOBILE_OTLP_TRACES_URL=https://old.example.test/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=old-dataset",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=old-token",
"",
].join("\n"),
config,
),
).toBe(
[
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example",
"T3CODE_RELAY_URL=https://relay.example.test",
"T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",
"",
].join("\n"),
);
});
});
describe("serializeGithubOutput", () => {
it("serializes relay deploy metadata for GitHub Actions outputs", () => {
expect(
+69 -20
View File
@@ -23,6 +23,7 @@ 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 Redacted from "effect/Redacted";
import { Command, Flag, Prompt } from "effect/unstable/cli";
import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
@@ -42,15 +43,49 @@ export interface RelayDeployOptions {
readonly githubOutput: boolean;
}
export interface RelayPublicConfig {
readonly relayUrl: string;
readonly mobileTracingUrl: string;
readonly mobileTracingDataset: string;
readonly mobileTracingToken: string;
}
const publicConfigEnvEntries = (config: RelayPublicConfig) =>
({
T3CODE_RELAY_URL: config.relayUrl,
T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileTracingUrl,
T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileTracingDataset,
T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileTracingToken,
}) as const;
export function reconcileRootEnvPublicConfig(contents: string, config: RelayPublicConfig): string {
let next = contents;
for (const [name, value] of Object.entries(publicConfigEnvEntries(config))) {
const entry = `${name}=${value}`;
const pattern = new RegExp(`^${name}=.*$`, "mu");
if (pattern.test(next)) {
next = next.replace(pattern, entry);
continue;
}
if (!next) {
next = `${entry}\n`;
continue;
}
next = `${next}${next.endsWith("\n") ? "" : "\n"}${entry}\n`;
}
return next;
}
export function reconcileRootEnvRelayUrl(contents: string, relayUrl: string): string {
const entry = `T3CODE_RELAY_URL=${relayUrl}`;
if (/^T3CODE_RELAY_URL=.*$/mu.test(contents)) {
return contents.replace(/^T3CODE_RELAY_URL=.*$/mu, entry);
}
if (!contents) {
return `${entry}\n`;
}
return `${contents}${contents.endsWith("\n") ? "" : "\n"}${entry}\n`;
return reconcileRootEnvPublicConfig(contents, {
relayUrl,
mobileTracingUrl: "",
mobileTracingDataset: "",
mobileTracingToken: "",
})
.split("\n")
.filter((line) => !line.startsWith("T3CODE_MOBILE_OTLP_TRACES_"))
.join("\n");
}
export function hasDeployChanges(plan: Plan.Plan): boolean {
@@ -68,7 +103,7 @@ export type RelayDeployResult = "applied" | "noop" | "dry-run" | "cancelled";
export interface RelayDeployOutcome {
readonly result: RelayDeployResult;
readonly changed: boolean;
readonly relayUrl: Option.Option<string>;
readonly publicConfig: Option.Option<RelayPublicConfig>;
}
export function serializeGithubOutput(entries: Readonly<Record<string, string | boolean>>): string {
@@ -106,15 +141,17 @@ const relayDeployStage = Config.nonEmptyString("stage").pipe(
),
);
const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (relayUrl: string) {
const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (
config: RelayPublicConfig,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* repoRoot;
const rootEnvPath = path.join(root, ".env");
const contents = (yield* fs.exists(rootEnvPath)) ? yield* fs.readFileString(rootEnvPath) : "";
yield* fs.writeFileString(rootEnvPath, reconcileRootEnvRelayUrl(contents, relayUrl));
yield* Console.log(`Updated ${rootEnvPath} with T3CODE_RELAY_URL=${relayUrl}`);
yield* fs.writeFileString(rootEnvPath, reconcileRootEnvPublicConfig(contents, config));
yield* Console.log(`Updated ${rootEnvPath} with relay URL and mobile tracing configuration`);
});
const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function* (
@@ -127,7 +164,9 @@ const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function*
serializeGithubOutput({
changed: outcome.changed,
result: outcome.result,
...(Option.isSome(outcome.relayUrl) ? { relay_url: outcome.relayUrl.value } : {}),
...(Option.isSome(outcome.publicConfig)
? { relay_url: outcome.publicConfig.value.relayUrl }
: {}),
}),
{ flag: "a" },
);
@@ -160,7 +199,7 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
return {
result: "dry-run",
changed,
relayUrl: Option.none<string>(),
publicConfig: Option.none<RelayPublicConfig>(),
} satisfies RelayDeployOutcome;
}
if (!options.yes && changed) {
@@ -175,20 +214,30 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
return {
result: "cancelled",
changed,
relayUrl: Option.none<string>(),
publicConfig: Option.none<RelayPublicConfig>(),
} satisfies RelayDeployOutcome;
}
}
const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));
if (output.url === undefined) {
if (
output.url === undefined ||
output.mobileTracingUrl === undefined ||
output.mobileTracingDataset === undefined ||
output.mobileTracingToken === undefined
) {
return yield* new RelayDeployError({
message: "Alchemy relay deploy output did not include a URL",
message: "Alchemy relay deploy output did not include complete public client config",
});
}
return {
result: changed ? "applied" : "noop",
changed,
relayUrl: Option.some(output.url),
publicConfig: Option.some({
relayUrl: output.url,
mobileTracingUrl: output.mobileTracingUrl,
mobileTracingDataset: output.mobileTracingDataset,
mobileTracingToken: Redacted.value(output.mobileTracingToken),
}),
} satisfies RelayDeployOutcome;
},
(effect, options, configProvider, stage) =>
@@ -216,8 +265,8 @@ export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployO
);
const stage = Option.getOrElse(options.stage, () => configuredStage);
const outcome = yield* runRelayDeploy(options, configProvider, stage);
if (Option.isSome(outcome.relayUrl)) {
yield* reconcileRootEnv(outcome.relayUrl.value);
if (Option.isSome(outcome.publicConfig)) {
yield* reconcileRootEnv(outcome.publicConfig.value);
}
if (options.githubOutput) {
yield* writeGithubOutput(outcome);
@@ -101,8 +101,13 @@ const make = Effect.gen(function* () {
"relay.mobile.device_id": input.deviceId,
"relay.operation": "replayForLiveActivityRegistration",
});
const activeStates = yield* rows.listForUser({ userId: input.userId });
const targets = yield* liveActivities.listTargets({ userId: input.userId });
const { activeStates, targets } = yield* Effect.all(
{
activeStates: rows.listForUser({ userId: input.userId }),
targets: liveActivities.listTargets({ userId: input.userId }),
},
{ concurrency: 2 },
);
const target = targets.find((row) => row.device_id === input.deviceId) ?? null;
if (target === null) {
return null;
@@ -1,7 +1,6 @@
import type { RelayAgentActivityState } from "@t3tools/contracts/relay";
import { RelayAgentActivityState as RelayAgentActivityStateSchema } from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { cast } from "effect/Function";
@@ -13,23 +12,32 @@ import { and, desc, eq, isNull } from "drizzle-orm";
import { RelayDb } from "../db.ts";
import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts";
export class AgentActivityRowUpsertPersistenceError extends Data.TaggedError(
export class AgentActivityRowUpsertPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowUpsertPersistenceError>()(
"AgentActivityRowUpsertPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist agent activity state";
}
}
export class AgentActivityRowDeletePersistenceError extends Data.TaggedError(
export class AgentActivityRowDeletePersistenceError extends Schema.TaggedErrorClass<AgentActivityRowDeletePersistenceError>()(
"AgentActivityRowDeletePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to delete agent activity state";
}
}
export class AgentActivityRowListPersistenceError extends Data.TaggedError(
export class AgentActivityRowListPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowListPersistenceError>()(
"AgentActivityRowListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list agent activity state";
}
}
export interface AgentActivityRowsShape {
readonly upsert: (input: {
+32 -18
View File
@@ -2,20 +2,13 @@ import * as NodeCrypto from "node:crypto";
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import {
Headers,
HttpClient,
HttpClientRequest,
type HttpBody,
type HttpClientError,
} from "effect/unstable/http";
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
import type { ApnsCredentials } from "../Config.ts";
import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
@@ -45,18 +38,39 @@ export interface ApnsDeliveryResult {
readonly apnsId: string | null;
}
export class ApnsSigningError extends Data.TaggedError("ApnsSigningError")<{
readonly phase: "encoding" | "signing";
readonly cause: unknown;
}> {}
export class ApnsSigningError extends Schema.TaggedErrorClass<ApnsSigningError>()(
"ApnsSigningError",
{
phase: Schema.Literals(["encoding", "signing"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed during APNs JWT ${this.phase}`;
}
}
export class ApnsHttpRequestError extends Data.TaggedError("ApnsHttpRequestError")<{
readonly cause: HttpClientError.HttpClientError | HttpBody.HttpBodyError;
}> {}
export class ApnsHttpRequestError extends Schema.TaggedErrorClass<ApnsHttpRequestError>()(
"ApnsHttpRequestError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "APNs HTTP request failed";
}
}
export class ApnsInvalidResponseError extends Data.TaggedError("ApnsInvalidResponseError")<{
readonly cause: unknown;
}> {}
export class ApnsInvalidResponseError extends Schema.TaggedErrorClass<ApnsInvalidResponseError>()(
"ApnsInvalidResponseError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "APNs returned an invalid response";
}
}
export type ApnsError = ApnsSigningError | ApnsHttpRequestError | ApnsInvalidResponseError;
@@ -9,7 +9,6 @@ import {
RelayAgentAwarenessPreferences as RelayAgentAwarenessPreferencesSchema,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -74,9 +73,16 @@ export type ApnsDeliveryError =
| LiveActivities.LiveActivityTargetListPersistenceError
| LiveActivities.LiveActivityDeliveryMarkPersistenceError;
export class ApnsDeliveryJobClaimInFlight extends Data.TaggedError("ApnsDeliveryJobClaimInFlight")<{
readonly sourceJobId: string;
}> {}
export class ApnsDeliveryJobClaimInFlight extends Schema.TaggedErrorClass<ApnsDeliveryJobClaimInFlight>()(
"ApnsDeliveryJobClaimInFlight",
{
sourceJobId: Schema.String,
},
) {
override get message(): string {
return `APNs delivery job '${this.sourceJobId}' is already in flight`;
}
}
const decodeRelayAgentActivityAggregateStateJson = Schema.decodeUnknownOption(
Schema.fromJsonString(RelayAgentActivityAggregateStateSchema),
@@ -2,10 +2,10 @@ import * as Alchemy from "alchemy";
import * as Cloudflare from "alchemy/Cloudflare";
import * as Crypto from "effect/Crypto";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import type { RelayDeliveryResult } from "@t3tools/contracts/relay";
@@ -22,9 +22,14 @@ import {
} from "./apnsDeliveryJobs.ts";
import * as RelayConfiguration from "../Config.ts";
export class ApnsDeliveryQueueSendError extends Data.TaggedError("ApnsDeliveryQueueSendError")<{
readonly cause: unknown;
}> {}
export class ApnsDeliveryQueueSendError extends Schema.TaggedErrorClass<ApnsDeliveryQueueSendError>()(
"ApnsDeliveryQueueSendError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to enqueue APNs delivery";
}
}
export type ApnsDeliveryQueueError = ApnsDeliveryQueueSendError;
@@ -1,20 +1,23 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { and, eq, isNull } from "drizzle-orm";
import * as Crypto from "effect/Crypto";
import * as Schema from "effect/Schema";
import { RelayDb } from "../db.ts";
import { relayDeliveryAttempts } from "../persistence/schema.ts";
export class DeliveryAttemptRecordPersistenceError extends Data.TaggedError(
export class DeliveryAttemptRecordPersistenceError extends Schema.TaggedErrorClass<DeliveryAttemptRecordPersistenceError>()(
"DeliveryAttemptRecordPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist APNs delivery attempt";
}
}
export interface DeliveryAttemptInput {
readonly userId: string | null;
+23 -12
View File
@@ -3,31 +3,42 @@ import type {
RelayDeviceRegistrationRequest,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { and, eq } from "drizzle-orm";
import { sql } from "drizzle-orm";
import { RelayDb } from "../db.ts";
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
export class DeviceRegistrationPersistenceError extends Data.TaggedError(
export class DeviceRegistrationPersistenceError extends Schema.TaggedErrorClass<DeviceRegistrationPersistenceError>()(
"DeviceRegistrationPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist mobile device registration";
}
}
export class DeviceUnregistrationPersistenceError extends Data.TaggedError(
export class DeviceUnregistrationPersistenceError extends Schema.TaggedErrorClass<DeviceUnregistrationPersistenceError>()(
"DeviceUnregistrationPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to unregister mobile device";
}
}
export class DeviceListPersistenceError extends Data.TaggedError("DeviceListPersistenceError")<{
readonly cause: unknown;
}> {}
export class DeviceListPersistenceError extends Schema.TaggedErrorClass<DeviceListPersistenceError>()(
"DeviceListPersistenceError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list mobile devices";
}
}
export interface DevicesShape {
readonly register: (input: {
+21 -13
View File
@@ -5,7 +5,6 @@ import type {
} from "@t3tools/contracts/relay";
import { RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema } from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { cast } from "effect/Function";
@@ -16,23 +15,32 @@ import { and, eq, sql } from "drizzle-orm";
import { RelayDb } from "../db.ts";
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
export class LiveActivityRegistrationPersistenceError extends Data.TaggedError(
export class LiveActivityRegistrationPersistenceError extends Schema.TaggedErrorClass<LiveActivityRegistrationPersistenceError>()(
"LiveActivityRegistrationPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist Live Activity registration";
}
}
export class LiveActivityTargetListPersistenceError extends Data.TaggedError(
export class LiveActivityTargetListPersistenceError extends Schema.TaggedErrorClass<LiveActivityTargetListPersistenceError>()(
"LiveActivityTargetListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list Live Activity delivery targets";
}
}
export class LiveActivityDeliveryMarkPersistenceError extends Data.TaggedError(
export class LiveActivityDeliveryMarkPersistenceError extends Schema.TaggedErrorClass<LiveActivityDeliveryMarkPersistenceError>()(
"LiveActivityDeliveryMarkPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist Live Activity delivery state";
}
}
export interface DeviceRow {
readonly user_id: string;
@@ -2,7 +2,6 @@ import * as NodeCrypto from "node:crypto";
import { RelayAgentActivityAggregateState, type RelayDeliveryKind } from "@t3tools/contracts/relay";
import { stableStringify } from "@t3tools/shared/relaySigning";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
@@ -50,13 +49,23 @@ export const SignedApnsDeliveryJob = Schema.Struct({
});
export type SignedApnsDeliveryJob = typeof SignedApnsDeliveryJob.Type;
export class ApnsDeliveryJobInvalid extends Data.TaggedError("ApnsDeliveryJobInvalid")<{
readonly message: string;
}> {}
export class ApnsDeliveryJobInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobInvalid>()(
"ApnsDeliveryJobInvalid",
{
message: Schema.String,
},
) {}
export class ApnsDeliveryJobExpired extends Data.TaggedError("ApnsDeliveryJobExpired")<{
readonly expiresAt: string;
}> {}
export class ApnsDeliveryJobExpired extends Schema.TaggedErrorClass<ApnsDeliveryJobExpired>()(
"ApnsDeliveryJobExpired",
{
expiresAt: Schema.String,
},
) {
override get message(): string {
return `APNs delivery job expired at ${this.expiresAt}`;
}
}
export type ApnsDeliveryJobVerificationError = ApnsDeliveryJobInvalid | ApnsDeliveryJobExpired;
+10 -5
View File
@@ -1,8 +1,8 @@
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
import { lt } from "drizzle-orm";
@@ -10,11 +10,16 @@ import { verifyDpopProof } from "@t3tools/shared/dpop";
import { RelayDb } from "../db.ts";
import { relayDpopProofs } from "../persistence/schema.ts";
export class DpopProofReplayPersistenceError extends Data.TaggedError(
export class DpopProofReplayPersistenceError extends Schema.TaggedErrorClass<DpopProofReplayPersistenceError>()(
"DpopProofReplayPersistenceError",
)<{
readonly cause: unknown;
}> {}
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to persist DPoP proof replay state";
}
}
export interface DpopProofReplayShape {
readonly verifyAndConsume: (input: {
+1 -1
View File
@@ -63,6 +63,6 @@ export const RelayHyperdrive = Effect.gen(function* () {
caching: {
disabled: true,
},
originConnectionLimit: 5,
originConnectionLimit: 20,
});
});
@@ -14,14 +14,17 @@ import {
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import { RELAY_HEALTH_RESPONSE_TYP, RELAY_MINT_RESPONSE_TYP } from "@t3tools/shared/relayJwt";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as Tracer from "effect/Tracer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
@@ -50,6 +53,9 @@ const decodeHealthRequestBody = Schema.decodeUnknownSync(
const decodeMintRequestBody = Schema.decodeUnknownSync(
Schema.fromJsonString(RelayCloudMintCredentialRequest),
);
const isEnvironmentConnectNotAuthorized = Schema.is(
EnvironmentConnector.EnvironmentConnectNotAuthorized,
);
function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {
return request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}";
@@ -221,6 +227,58 @@ function makeLinks(
}
describe("EnvironmentConnector", () => {
it.effect("loads the environment link and managed allocation concurrently", () =>
Effect.gen(function* () {
const started = yield* Ref.make(0);
const bothStarted = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const waitForPeer = Effect.gen(function* () {
const count = yield* Ref.updateAndGet(started, (value) => value + 1);
if (count === 2) {
yield* Deferred.succeed(bothStarted, undefined);
}
yield* Deferred.await(release);
});
const links = makeLinks();
const allocations = makeAllocations();
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
const healthRequest = decodeHealthRequestBody(requestBodyText(request));
return HttpClientResponse.fromWeb(
request,
Response.json(signHealthResponse(healthRequest), { status: 200 }),
);
});
const status = Effect.gen(function* () {
const connector = yield* EnvironmentConnector.EnvironmentConnector;
return yield* connector.status({
userId: "user_123",
environmentId: "env-connector-test" as never,
});
}).pipe(
Effect.provide(
connectorTestLayer(execute, {
links: {
...links,
getForUser: (input) => waitForPeer.pipe(Effect.andThen(links.getForUser(input))),
},
allocations: {
...allocations,
get: (input) => waitForPeer.pipe(Effect.andThen(allocations.get(input))),
},
}),
),
);
const fiber = yield* Effect.forkChild(status);
yield* Deferred.await(bothStarted);
yield* Deferred.succeed(release, undefined);
yield* Fiber.join(fiber);
expect(yield* Ref.get(started)).toBe(2);
}),
);
it.effect("checks linked environment health through the managed endpoint", () => {
const seenUrls: Array<string> = [];
const seenProofs: Array<RelayCloudEnvironmentHealthProofPayload> = [];
@@ -280,7 +338,13 @@ describe("EnvironmentConnector", () => {
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
if (isEnvironmentConnectNotAuthorized(result.failure)) {
expect(result.failure).toMatchObject({
operation: "status",
reason: "endpoint_provider_not_managed",
});
}
}
expect(requestCount).toBe(0);
}).pipe(
@@ -300,6 +364,14 @@ describe("EnvironmentConnector", () => {
it.effect("rejects stale managed endpoints before sending a mint request", () => {
let requestCount = 0;
const spans: Array<Tracer.NativeSpan> = [];
const tracer = Tracer.make({
span: (options) => {
const span = new Tracer.NativeSpan(options);
spans.push(span);
return span;
},
});
const execute = () =>
Effect.sync(() => {
requestCount += 1;
@@ -318,8 +390,27 @@ describe("EnvironmentConnector", () => {
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
if (isEnvironmentConnectNotAuthorized(result.failure)) {
expect(result.failure).toMatchObject({
operation: "connect",
reason: "managed_endpoint_mismatch",
});
}
}
const resolutionSpan = spans.find(
(span) => span.name === "relay.environment_connector.resolve_managed_endpoint",
);
expect(Object.fromEntries(resolutionSpan?.attributes ?? [])).toMatchObject({
"relay.authorization.allocation_hostname": "env.example.test",
"relay.authorization.allocation_has_ready_at": true,
"relay.authorization.allocation_has_tunnel_id": true,
"relay.authorization.allocation_has_dns_record_id": true,
"relay.authorization.linked_http_base_url": "https://attacker.example.test/",
"relay.authorization.linked_ws_base_url": "wss://attacker.example.test/ws",
"relay.authorization.resolved_http_base_url": "https://env.example.test/",
"relay.authorization.resolved_ws_base_url": "wss://env.example.test/ws",
});
expect(requestCount).toBe(0);
}).pipe(
Effect.provide(
@@ -333,6 +424,7 @@ describe("EnvironmentConnector", () => {
}),
}),
),
Effect.provideService(Tracer.Tracer, tracer),
);
});
@@ -355,7 +447,13 @@ describe("EnvironmentConnector", () => {
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
if (isEnvironmentConnectNotAuthorized(result.failure)) {
expect(result.failure).toMatchObject({
operation: "status",
reason: "managed_endpoint_allocation_not_ready",
});
}
}
expect(requestCount).toBe(0);
}).pipe(
@@ -28,7 +28,6 @@ import {
import { stableStringify } from "@t3tools/shared/relaySigning";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -41,29 +40,93 @@ import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
import * as RelayConfiguration from "../Config.ts";
import { isManagedEndpointHostname } from "../deploymentConfig.ts";
export class EnvironmentConnectNotAuthorized extends Data.TaggedError(
export const EnvironmentConnectNotAuthorizedReason = Schema.Literals([
"client_proof_key_thumbprint_missing",
"environment_link_not_found",
"endpoint_provider_not_managed",
"managed_endpoint_allocation_not_found",
"managed_endpoint_base_domain_not_configured",
"managed_endpoint_allocation_not_ready",
"managed_endpoint_hostname_invalid",
"managed_endpoint_mismatch",
]);
export type EnvironmentConnectNotAuthorizedReason =
typeof EnvironmentConnectNotAuthorizedReason.Type;
function environmentConnectNotAuthorizedReasonMessage(
reason: EnvironmentConnectNotAuthorizedReason,
): string {
switch (reason) {
case "client_proof_key_thumbprint_missing":
return "the client proof key thumbprint is missing";
case "environment_link_not_found":
return "no active environment link was found";
case "endpoint_provider_not_managed":
return "the linked endpoint is not relay-managed";
case "managed_endpoint_allocation_not_found":
return "no managed endpoint allocation was found";
case "managed_endpoint_base_domain_not_configured":
return "the managed endpoint base domain is not configured";
case "managed_endpoint_allocation_not_ready":
return "the managed endpoint allocation is incomplete";
case "managed_endpoint_hostname_invalid":
return "the managed endpoint hostname is invalid";
case "managed_endpoint_mismatch":
return "the linked endpoint does not match its managed allocation";
}
}
export class EnvironmentConnectNotAuthorized extends Schema.TaggedErrorClass<EnvironmentConnectNotAuthorized>()(
"EnvironmentConnectNotAuthorized",
)<{
readonly environmentId: string;
}> {}
{
environmentId: Schema.String,
operation: Schema.Literals(["connect", "status"]),
reason: EnvironmentConnectNotAuthorizedReason,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' is not authorized for ${this.operation}: ${environmentConnectNotAuthorizedReasonMessage(this.reason)}`;
}
}
export class EnvironmentMintRequestFailed extends Data.TaggedError("EnvironmentMintRequestFailed")<{
readonly cause: unknown;
}> {}
export class EnvironmentMintRequestFailed extends Schema.TaggedErrorClass<EnvironmentMintRequestFailed>()(
"EnvironmentMintRequestFailed",
{
environmentId: Schema.String,
operation: Schema.Literals(["connect", "status"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Environment '${this.environmentId}' ${this.operation} request failed`;
}
}
export class EnvironmentMintRequestTimedOut extends Data.TaggedError(
export class EnvironmentMintRequestTimedOut extends Schema.TaggedErrorClass<EnvironmentMintRequestTimedOut>()(
"EnvironmentMintRequestTimedOut",
)<{
readonly environmentId: string;
readonly timeoutMs: number;
}> {}
{
environmentId: Schema.String,
timeoutMs: Schema.Number,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' mint request timed out after ${this.timeoutMs}ms`;
}
}
export class EnvironmentMintResponseInvalid extends Data.TaggedError(
export class EnvironmentMintResponseInvalid extends Schema.TaggedErrorClass<EnvironmentMintResponseInvalid>()(
"EnvironmentMintResponseInvalid",
)<{
readonly environmentId: string;
}> {}
{
environmentId: Schema.String,
operation: Schema.Literals(["connect", "status"]),
},
) {
override get message(): string {
return `Environment '${this.environmentId}' returned an invalid ${this.operation} response`;
}
}
export type EnvironmentConnectorError =
| EnvironmentConnectNotAuthorized
@@ -232,31 +295,90 @@ const make = Effect.gen(function* () {
);
const resolveManagedEndpoint = Effect.fn("relay.environment_connector.resolve_managed_endpoint")(
function* (input: {
readonly userId: string;
readonly operation: "connect" | "status";
readonly link: EnvironmentLinks.RelayLinkedEnvironmentRecord;
readonly allocation: ManagedEndpointAllocations.ManagedEndpointAllocation | null;
}) {
if (input.link.endpoint.providerKind !== "cloudflare_tunnel") {
yield* Effect.annotateCurrentSpan({
"relay.authorization.endpoint_provider_kind": input.link.endpoint.providerKind,
});
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "endpoint_provider_not_managed",
});
}
const allocation = yield* allocations.get({
userId: input.userId,
environmentId: input.link.environmentId,
if (!input.allocation) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_allocation_not_found",
});
}
const allocationAttributes = {
"relay.authorization.allocation_hostname": input.allocation.hostname,
"relay.authorization.allocation_has_ready_at": input.allocation.readyAt !== null,
"relay.authorization.allocation_has_tunnel_id": input.allocation.tunnelId !== null,
"relay.authorization.allocation_has_dns_record_id": input.allocation.dnsRecordId !== null,
} as const;
if (!settings.managedEndpointBaseDomain) {
yield* Effect.annotateCurrentSpan(allocationAttributes);
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_base_domain_not_configured",
});
}
if (
input.allocation.readyAt === null ||
input.allocation.tunnelId === null ||
input.allocation.dnsRecordId === null
) {
yield* Effect.annotateCurrentSpan(allocationAttributes);
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_allocation_not_ready",
});
}
if (
!isManagedEndpointHostname(input.allocation.hostname, settings.managedEndpointBaseDomain)
) {
yield* Effect.annotateCurrentSpan({
...allocationAttributes,
"relay.authorization.managed_endpoint_base_domain": settings.managedEndpointBaseDomain,
});
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_hostname_invalid",
});
}
const endpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({
allocation: input.allocation,
baseDomain: settings.managedEndpointBaseDomain,
});
const endpoint = allocation
? ManagedEndpointAllocations.resolveReadyManagedEndpoint({
allocation,
baseDomain: settings.managedEndpointBaseDomain,
})
: null;
if (
endpoint === null ||
endpoint.httpBaseUrl !== input.link.endpoint.httpBaseUrl ||
endpoint.wsBaseUrl !== input.link.endpoint.wsBaseUrl
) {
yield* Effect.annotateCurrentSpan({
...allocationAttributes,
"relay.authorization.linked_http_base_url": input.link.endpoint.httpBaseUrl,
"relay.authorization.linked_ws_base_url": input.link.endpoint.wsBaseUrl,
...(endpoint
? {
"relay.authorization.resolved_http_base_url": endpoint.httpBaseUrl,
"relay.authorization.resolved_ws_base_url": endpoint.wsBaseUrl,
}
: {}),
});
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
operation: input.operation,
reason: "managed_endpoint_mismatch",
});
}
return endpoint;
@@ -269,22 +391,50 @@ const make = Effect.gen(function* () {
"relay.environment_id": input.environmentId,
"relay.operation": "status",
});
const link = yield* links.getForUser(input);
const { link, allocation } = yield* Effect.all(
{
link: links.getForUser(input),
allocation: allocations.get(input),
},
{ concurrency: 2 },
);
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
operation: "status",
reason: "environment_link_not_found",
});
}
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
const endpoint = yield* resolveManagedEndpoint({
operation: "status",
link,
allocation,
});
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 2 });
const nonce = yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "status",
cause,
}),
),
);
const payload = {
iss: relayIssuer,
aud: `t3-env:${link.environmentId}`,
sub: input.userId,
jti: yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "status",
cause,
}),
),
),
iat: Math.floor(now.epochMilliseconds / 1_000),
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
@@ -296,7 +446,16 @@ const make = Effect.gen(function* () {
privateKey: Redacted.value(settings.cloudMintPrivateKey),
typ: RELAY_HEALTH_REQUEST_TYP,
payload,
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "status",
cause,
}),
),
);
const checkedAt = DateTime.formatIso(now);
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe(
@@ -336,7 +495,10 @@ const make = Effect.gen(function* () {
now: yield* DateTime.now,
});
if (!verified) {
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
return yield* new EnvironmentMintResponseInvalid({
environmentId: input.environmentId,
operation: "status",
});
}
return {
environmentId: link.environmentId,
@@ -354,24 +516,56 @@ const make = Effect.gen(function* () {
...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),
});
if (input.clientProofKeyThumbprint.trim().length === 0) {
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
operation: "connect",
reason: "client_proof_key_thumbprint_missing",
});
}
const link = yield* links.getForUser(input);
const { link, allocation } = yield* Effect.all(
{
link: links.getForUser(input),
allocation: allocations.get(input),
},
{ concurrency: 2 },
);
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.environmentId,
operation: "connect",
reason: "environment_link_not_found",
});
}
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
const endpoint = yield* resolveManagedEndpoint({
operation: "connect",
link,
allocation,
});
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 2 });
const nonce = yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
);
const payload = {
iss: relayIssuer,
aud: `t3-env:${link.environmentId}`,
sub: input.userId,
jti: yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
),
iat: Math.floor(now.epochMilliseconds / 1_000),
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
@@ -386,11 +580,27 @@ const make = Effect.gen(function* () {
privateKey: Redacted.value(settings.cloudMintPrivateKey),
typ: RELAY_MINT_REQUEST_TYP,
payload,
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
);
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const decoded = yield* environmentClient.cloud.t3MintCredential({ payload: { proof } }).pipe(
withoutRedirects,
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
Effect.flatMap(
Option.match({
@@ -415,7 +625,10 @@ const make = Effect.gen(function* () {
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
});
if (!verified) {
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
return yield* new EnvironmentMintResponseInvalid({
environmentId: input.environmentId,
operation: "connect",
});
}
return {
environmentId: link.environmentId,
@@ -1,33 +1,42 @@
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { and, eq, isNull, ne, notExists } from "drizzle-orm";
import { RelayDb } from "../db.ts";
import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persistence/schema.ts";
export class EnvironmentCredentialCreatePersistenceError extends Data.TaggedError(
export class EnvironmentCredentialCreatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialCreatePersistenceError>()(
"EnvironmentCredentialCreatePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist environment credential";
}
}
export class EnvironmentCredentialAuthenticatePersistenceError extends Data.TaggedError(
export class EnvironmentCredentialAuthenticatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialAuthenticatePersistenceError>()(
"EnvironmentCredentialAuthenticatePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to authenticate environment credential";
}
}
export class EnvironmentCredentialRevokePersistenceError extends Data.TaggedError(
export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialRevokePersistenceError>()(
"EnvironmentCredentialRevokePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to revoke environment credential";
}
}
export interface EnvironmentCredentialPrincipal {
readonly credentialId: string;
@@ -1,6 +1,6 @@
import {
RelayEnvironmentLinkProofPayload,
type RelayEnvironmentLinkProofInvalidReason,
RelayEnvironmentLinkProofInvalidReason,
type RelayEnvironmentLinkRequest,
} from "@t3tools/contracts/relay";
import {
@@ -10,7 +10,6 @@ import {
verifyRelayJwt,
} from "@t3tools/shared/relayJwt";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -23,14 +22,28 @@ import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
import * as RelayConfiguration from "../Config.ts";
export class EnvironmentLinkProofExpired extends Data.TaggedError("EnvironmentLinkProofExpired")<{
readonly expiresAt: string;
}> {}
export class EnvironmentLinkProofExpired extends Schema.TaggedErrorClass<EnvironmentLinkProofExpired>()(
"EnvironmentLinkProofExpired",
{
expiresAt: Schema.String,
},
) {
override get message(): string {
return `Environment link proof expired at ${this.expiresAt}`;
}
}
export class EnvironmentLinkProofInvalid extends Data.TaggedError("EnvironmentLinkProofInvalid")<{
readonly environmentId: string;
readonly reason: RelayEnvironmentLinkProofInvalidReason;
}> {}
export class EnvironmentLinkProofInvalid extends Schema.TaggedErrorClass<EnvironmentLinkProofInvalid>()(
"EnvironmentLinkProofInvalid",
{
environmentId: Schema.String,
reason: RelayEnvironmentLinkProofInvalidReason,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' link proof is invalid: ${this.reason}`;
}
}
export type EnvironmentLinkError =
| EnvironmentLinkProofExpired
@@ -5,10 +5,10 @@ import type {
RelayManagedEndpoint,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { and, eq, isNull, or } from "drizzle-orm";
import { RelayDb } from "../db.ts";
@@ -24,41 +24,59 @@ export interface AgentAwarenessDeliveryUserRecord {
readonly liveActivitiesEnabled: boolean;
}
export class EnvironmentLinkUpsertPersistenceError extends Data.TaggedError(
export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUpsertPersistenceError>()(
"EnvironmentLinkUpsertPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist environment link";
}
}
export class EnvironmentLinkUserListPersistenceError extends Data.TaggedError(
export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUserListPersistenceError>()(
"EnvironmentLinkUserListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list users linked to environment";
}
}
export class EnvironmentPublicKeyListPersistenceError extends Data.TaggedError(
export class EnvironmentPublicKeyListPersistenceError extends Schema.TaggedErrorClass<EnvironmentPublicKeyListPersistenceError>()(
"EnvironmentPublicKeyListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list environment public keys";
}
}
export class EnvironmentLinkListPersistenceError extends Data.TaggedError(
export class EnvironmentLinkListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkListPersistenceError>()(
"EnvironmentLinkListPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to list environment links";
}
}
export class EnvironmentLinkLookupPersistenceError extends Data.TaggedError(
export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkLookupPersistenceError>()(
"EnvironmentLinkLookupPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to look up environment link";
}
}
export class EnvironmentLinkRevokePersistenceError extends Data.TaggedError(
export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkRevokePersistenceError>()(
"EnvironmentLinkRevokePersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to revoke environment link";
}
}
export interface EnvironmentLinksShape {
readonly upsert: (input: {
@@ -11,7 +11,6 @@ import {
import { stableStringify } from "@t3tools/shared/relaySigning";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
@@ -21,23 +20,38 @@ import * as Schema from "effect/Schema";
import * as DpopProofs from "../auth/DpopProofs.ts";
import * as RelayConfiguration from "../Config.ts";
export class EnvironmentPublishSignatureExpired extends Data.TaggedError(
export class EnvironmentPublishSignatureExpired extends Schema.TaggedErrorClass<EnvironmentPublishSignatureExpired>()(
"EnvironmentPublishSignatureExpired",
)<{
readonly expiresAt: string;
}> {}
{
expiresAt: Schema.String,
},
) {
override get message(): string {
return `Environment publish signature expired at ${this.expiresAt}`;
}
}
export class EnvironmentPublishSignatureInvalid extends Data.TaggedError(
export class EnvironmentPublishSignatureInvalid extends Schema.TaggedErrorClass<EnvironmentPublishSignatureInvalid>()(
"EnvironmentPublishSignatureInvalid",
)<{
readonly environmentId: string;
}> {}
{
environmentId: Schema.String,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' publish signature is invalid`;
}
}
export class EnvironmentPublishPublicKeyMissing extends Data.TaggedError(
export class EnvironmentPublishPublicKeyMissing extends Schema.TaggedErrorClass<EnvironmentPublishPublicKeyMissing>()(
"EnvironmentPublishPublicKeyMissing",
)<{
readonly environmentId: string;
}> {}
{
environmentId: Schema.String,
},
) {
override get message(): string {
return `Environment '${this.environmentId}' has no publish public key`;
}
}
export type EnvironmentPublishSignatureError =
| EnvironmentPublishSignatureExpired
@@ -1,10 +1,10 @@
import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
import { and, eq } from "drizzle-orm";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { RelayDb } from "../db.ts";
import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts";
@@ -36,11 +36,17 @@ export function resolveReadyManagedEndpoint(input: {
return managedEndpointForHostname(input.allocation.hostname);
}
export class ManagedEndpointAllocationPersistenceError extends Data.TaggedError(
export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErrorClass<ManagedEndpointAllocationPersistenceError>()(
"ManagedEndpointAllocationPersistenceError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to persist managed endpoint allocation";
}
}
const isManagedEndpointAllocationPersistenceError = Schema.is(
ManagedEndpointAllocationPersistenceError,
);
interface ManagedEndpointAllocationKey {
readonly userId: string;
@@ -98,7 +104,7 @@ const whereAllocation = (input: ManagedEndpointAllocationKey) =>
);
const persistenceError = (cause: unknown) =>
cause instanceof ManagedEndpointAllocationPersistenceError
isManagedEndpointAllocationPersistenceError(cause)
? cause
: new ManagedEndpointAllocationPersistenceError({ cause });
@@ -3,12 +3,12 @@ import * as Cloudflare from "alchemy/Cloudflare";
import * as Arr from "effect/Array";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import type {
RelayManagedEndpoint,
@@ -25,28 +25,44 @@ import {
} from "../deploymentConfig.ts";
import { ManagedEndpointAllocations } from "./ManagedEndpointAllocations.ts";
export class ManagedEndpointProvisioningNotConfigured extends Data.TaggedError(
export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedErrorClass<ManagedEndpointProvisioningNotConfigured>()(
"ManagedEndpointProvisioningNotConfigured",
)<{}> {}
{},
) {
override get message(): string {
return "Managed endpoint provisioning is not configured";
}
}
export class ManagedEndpointProvisioningFailed extends Data.TaggedError(
export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointProvisioningFailed>()(
"ManagedEndpointProvisioningFailed",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Managed endpoint provisioning failed";
}
}
export class ManagedEndpointDeprovisioningFailed extends Data.TaggedError(
export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointDeprovisioningFailed>()(
"ManagedEndpointDeprovisioningFailed",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Managed endpoint deprovisioning failed";
}
}
export class ManagedEndpointOriginNotAllowed extends Data.TaggedError(
export class ManagedEndpointOriginNotAllowed extends Schema.TaggedErrorClass<ManagedEndpointOriginNotAllowed>()(
"ManagedEndpointOriginNotAllowed",
)<{
readonly host: string;
readonly port: number;
}> {}
{
host: Schema.String,
port: Schema.Number,
},
) {
override get message(): string {
return `Managed endpoint origin '${this.host}:${this.port}' is not allowed`;
}
}
export type ManagedEndpointProviderError =
| ManagedEndpointProvisioningNotConfigured
@@ -80,11 +96,14 @@ interface ManagedEndpointTunnel {
readonly name?: string | null;
}
export class ManagedEndpointTunnelClientError extends Data.TaggedError(
export class ManagedEndpointTunnelClientError extends Schema.TaggedErrorClass<ManagedEndpointTunnelClientError>()(
"ManagedEndpointTunnelClientError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Managed endpoint tunnel provider request failed";
}
}
export interface ManagedEndpointTunnelClientShape {
readonly list: (request: {
@@ -124,11 +143,14 @@ interface ManagedEndpointCnameRecordInput {
readonly proxied: true;
}
export class ManagedEndpointDnsClientError extends Data.TaggedError(
export class ManagedEndpointDnsClientError extends Schema.TaggedErrorClass<ManagedEndpointDnsClientError>()(
"ManagedEndpointDnsClientError",
)<{
readonly cause: unknown;
}> {}
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Managed endpoint DNS provider request failed";
}
}
export interface ManagedEndpointDnsClientShape {
readonly listRecords: (
+6
View File
@@ -181,6 +181,10 @@ describe("relay request tracing", () => {
const request = HttpServerRequest.fromWeb(
new Request("https://relay.test/v1/mobile/devices?client=mobile", {
method: "POST",
headers: {
authorization: "Bearer secret",
dpop: "signed-proof",
},
}),
);
@@ -192,6 +196,8 @@ describe("relay request tracing", () => {
expect(spans[0]?.kind).toBe("server");
expect(spans[0]?.attributes.get("url.path")).toBe("/v1/mobile/devices");
expect(spans[0]?.attributes.get("http.response.status_code")).toBe(204);
expect(spans[0]?.attributes.get("http.request.header.authorization")).toBe("<redacted>");
expect(spans[0]?.attributes.get("http.request.header.dpop")).toBe("<redacted>");
expect(Option.isNone(spans[0]!.parent)).toBe(true);
expect(Option.getOrUndefined(spans[1]!.parent)?.spanId).toBe(spans[0]?.spanId);
}),
+24 -24
View File
@@ -1,9 +1,9 @@
import { createClerkClient, verifyToken } from "@clerk/backend";
import { sql as drizzleSql } from "drizzle-orm";
import * as Data from "effect/Data";
import * as Crypto from "effect/Crypto";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Record from "effect/Record";
@@ -19,6 +19,7 @@ import * as HttpTraceContext from "effect/unstable/http/HttpTraceContext";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import {
RelayApi,
@@ -68,6 +69,7 @@ import { withSpanAttributes } from "../observability.ts";
import { RelayDb } from "../db.ts";
const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const;
const RELAY_DPOP_ACCESS_TOKEN_TTL = "30 minutes";
const relayCorsAllowedHeaders = [
"authorization",
"b3",
@@ -75,11 +77,7 @@ const relayCorsAllowedHeaders = [
"content-type",
"dpop",
] as const;
const relayCorsExposedHeaders = [
"traceparent",
"x-t3-relay-auth-failure",
"www-authenticate",
] as const;
const relayCorsExposedHeaders = ["traceparent", "www-authenticate"] as const;
const relayCorsHeaders = {
"access-control-allow-origin": "*",
@@ -177,7 +175,10 @@ export const traceRelayHttpRequestWith = <E, R, LayerError, LayerRequirements>(
HttpServerRequest.HttpServerRequest | R
>,
tracerLayer: Layer.Layer<never, LayerError, LayerRequirements>,
) => traceRelayHttpRequest(httpEffect).pipe(Effect.provide(tracerLayer));
) =>
traceRelayHttpRequest(httpEffect).pipe(
Effect.provide(Layer.merge(tracerLayer, httpHeaderRedactionLayer)),
);
export const withoutCapturedParentSpan = <A, E, R>(
effect: Effect.Effect<A, E, R>,
@@ -352,12 +353,7 @@ export const healthApi = HttpApiBuilder.group(
"health",
Effect.fn("relay.api.health")(
function* () {
const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
yield* db.execute(drizzleSql`SELECT 1`);
const completedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
yield* Effect.logInfo("relay health db probe completed", {
durationMs: completedAt - startedAt,
});
return { ok: true, service: "relay" as const };
},
Effect.catch(() => relayInternalErrorResponse("database_unavailable")),
@@ -603,7 +599,7 @@ export const tokenApi = HttpApiBuilder.group(
Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),
);
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 5 });
const expiresAt = DateTime.addDuration(now, RELAY_DPOP_ACCESS_TOKEN_TTL);
const jti = yield* crypto.randomUUIDv4.pipe(
Effect.catch(() => relayInternalErrorResponse("internal_error")),
);
@@ -621,7 +617,7 @@ export const tokenApi = HttpApiBuilder.group(
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
issued_token_type: RelayAccessTokenType,
token_type: "DPoP" as const,
expires_in: 300,
expires_in: Duration.toSeconds(RELAY_DPOP_ACCESS_TOKEN_TTL),
scope: encodeOAuthScope(requestedScopes),
};
}, mapRelayCommonApiErrors("invalid_dpop")),
@@ -813,9 +809,16 @@ export const serverApi = HttpApiBuilder.group(
}),
);
class ClerkTokenVerificationFailed extends Data.TaggedError("ClerkTokenVerificationFailed")<{
readonly cause: unknown;
}> {}
class ClerkTokenVerificationFailed extends Schema.TaggedErrorClass<ClerkTokenVerificationFailed>()(
"ClerkTokenVerificationFailed",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Clerk token verification failed";
}
}
const isHttpUnauthorized = Schema.is(HttpApiError.Unauthorized);
@@ -824,7 +827,7 @@ const currentTraceId = Effect.currentParentSpan.pipe(
Effect.orElseSucceed(() => "unavailable"),
);
const COMMON_AUTH_INVALID_REASONS = [
const RelayCommonPersistenceError = Schema.Union([
Devices.DeviceRegistrationPersistenceError,
Devices.DeviceUnregistrationPersistenceError,
Devices.DeviceListPersistenceError,
@@ -844,18 +847,15 @@ const COMMON_AUTH_INVALID_REASONS = [
AgentActivityRows.AgentActivityRowListPersistenceError,
LiveActivities.LiveActivityDeliveryMarkPersistenceError,
DeliveryAttempts.DeliveryAttemptRecordPersistenceError,
] as const;
type RelayCommonPersistenceError = InstanceType<(typeof COMMON_AUTH_INVALID_REASONS)[number]>;
]);
type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type;
const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError);
type MapRelayCommonApiError<E> =
| Exclude<E, HttpApiError.Unauthorized | RelayCommonPersistenceError>
| (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError)
| (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError);
function isRelayCommonPersistenceError(error: unknown): error is RelayCommonPersistenceError {
return COMMON_AUTH_INVALID_REASONS.some((ErrorType) => error instanceof ErrorType);
}
function relayInternalErrorResponse(reason: RelayInternalError["reason"]) {
return currentTraceId.pipe(
Effect.flatMap((traceId) =>
+85
View File
@@ -0,0 +1,85 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import { expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import type { OtlpTracer } from "effect/unstable/observability";
import { EnvironmentConnectNotAuthorized } from "./environments/EnvironmentConnector.ts";
import { makeRelayTraceLayer } from "./observability.ts";
interface ExportedRequest {
readonly authorization: string | undefined;
readonly body: string;
readonly dataset: string | undefined;
}
const otlpAttributeValue = (value: {
readonly stringValue?: string | null;
readonly boolValue?: boolean | null;
readonly intValue?: number | null;
readonly doubleValue?: number | null;
}) => value.stringValue ?? value.boolValue ?? value.intValue ?? value.doubleValue;
const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
it.effect("exports schema error fields as span attributes", () =>
Effect.gen(function* () {
const exportedRequest = yield* Deferred.make<ExportedRequest>();
yield* HttpServer.serveEffect(
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
yield* Deferred.succeed(exportedRequest, {
authorization: request.headers.authorization,
body: yield* request.text,
dataset: request.headers["x-axiom-dataset"],
});
return HttpServerResponse.empty({ status: 204 });
}),
);
yield* Effect.fail(
new EnvironmentConnectNotAuthorized({
environmentId: "environment-1",
operation: "connect",
reason: "managed_endpoint_allocation_not_ready",
}),
).pipe(
Effect.withSpan("relay.test.schema_error"),
Effect.exit,
Effect.provide(
makeRelayTraceLayer({
tracesEndpoint: "/v1/traces",
tracesDatasetName: "relay-test-traces",
ingestToken: Redacted.make("test-token"),
}),
),
);
const request = yield* Deferred.await(exportedRequest).pipe(Effect.timeout("1 second"));
const payload = (yield* decodeJson(request.body)) as OtlpTracer.TraceData;
const span = payload.resourceSpans
.flatMap((resourceSpan) => resourceSpan.scopeSpans)
.flatMap((scopeSpan) => scopeSpan.spans)
.find((candidate) => candidate.name === "relay.test.schema_error");
const attributes = Object.fromEntries(
(span?.attributes ?? []).map((attribute) => [
attribute.key,
otlpAttributeValue(attribute.value),
]),
);
expect(request.authorization).toBe("Bearer test-token");
expect(request.dataset).toBe("relay-test-traces");
expect(attributes).toMatchObject({
"error.type": "EnvironmentConnectNotAuthorized",
"error.environmentId": "environment-1",
"error.operation": "connect",
"error.reason": "managed_endpoint_allocation_not_ready",
});
}).pipe(Effect.provide(NodeHttpServer.layerTest), Effect.scoped),
);
+170 -17
View File
@@ -1,9 +1,14 @@
import * as Alchemy from "alchemy";
import * as Axiom from "alchemy/Axiom";
import * as Output from "alchemy/Output";
import * as Layer from "effect/Layer";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as Tracer from "effect/Tracer";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { relayResourceNameForStage } from "./deploymentConfig.ts";
@@ -29,7 +34,7 @@ export const RelayObservability = Effect.gen(function* () {
useRetentionPeriod: true,
});
const ingestToken = yield* Axiom.ApiToken("RelayAxiomIngestToken", {
const workerIngestToken = yield* Axiom.ApiToken("RelayWorkerAxiomIngestToken", {
name: relayResourceNameForStage("t3-code-relay-otel-ingest", stage),
description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",
datasetCapabilities: Output.map(traces.name, (dataset) => ({
@@ -37,6 +42,14 @@ export const RelayObservability = Effect.gen(function* () {
})),
});
const mobileIngestToken = yield* Axiom.ApiToken("RelayMobileAxiomIngestToken", {
name: relayResourceNameForStage("t3-code-mobile-otel-ingest", stage),
description: "Owned by Alchemy. Scoped OTLP ingest token for T3 Code mobile spans.",
datasetCapabilities: Output.map(traces.name, (dataset) => ({
[dataset]: { ingest: ["create" as const] },
})),
});
yield* Axiom.View("RelayRecentSpansView", {
name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),
description: "Recent relay HTTP request spans.",
@@ -44,7 +57,7 @@ export const RelayObservability = Effect.gen(function* () {
aplQuery: Output.map(traces.name, relayRecentSpansQuery),
});
return { traces, ingestToken } as const;
return { traces, workerIngestToken, mobileIngestToken } as const;
});
export const withSpanAttributes =
@@ -54,23 +67,163 @@ export const withSpanAttributes =
Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))),
);
const appendEncodedAttributes = (
attributes: Record<string, unknown>,
prefix: string,
value: unknown,
): void => {
if (
value === null ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean" ||
typeof value === "bigint" ||
Array.isArray(value)
) {
attributes[prefix] = value;
return;
}
if (typeof value !== "object") {
return;
}
for (const [key, child] of Object.entries(value)) {
appendEncodedAttributes(attributes, `${prefix}.${key}`, child);
}
};
const schemaErrorAttributes = (error: unknown): Record<string, unknown> | undefined => {
if (typeof error !== "object" || error === null) {
return undefined;
}
const constructor = error.constructor;
if (!Schema.isSchema(constructor)) {
return undefined;
}
const encoded = Schema.encodeUnknownOption(constructor as unknown as Schema.Encoder<unknown>)(
error,
);
if (Option.isNone(encoded) || typeof encoded.value !== "object" || encoded.value === null) {
return undefined;
}
const tag = Reflect.get(encoded.value, "_tag");
if (typeof tag !== "string") {
return undefined;
}
const attributes: Record<string, unknown> = {
"error.type": tag,
};
for (const [key, value] of Object.entries(encoded.value)) {
if (key !== "_tag") {
appendEncodedAttributes(attributes, `error.${key}`, value);
}
}
return attributes;
};
const annotateSchemaError = (span: Tracer.Span, exit: Exit.Exit<unknown, unknown>): void => {
if (Exit.isSuccess(exit)) {
return;
}
for (const reason of exit.cause.reasons) {
const error = Cause.isFailReason(reason)
? reason.error
: Cause.isDieReason(reason)
? reason.defect
: undefined;
const attributes = schemaErrorAttributes(error);
if (attributes) {
for (const [key, value] of Object.entries(attributes)) {
span.attribute(key, value);
}
return;
}
}
};
class RelayTraceSpan implements Tracer.Span {
readonly _tag = "Span";
private readonly delegate: Tracer.Span;
constructor(delegate: Tracer.Span) {
this.delegate = delegate;
}
get name() {
return this.delegate.name;
}
get spanId() {
return this.delegate.spanId;
}
get traceId() {
return this.delegate.traceId;
}
get parent() {
return this.delegate.parent;
}
get annotations() {
return this.delegate.annotations;
}
get status() {
return this.delegate.status;
}
get attributes() {
return this.delegate.attributes;
}
get links() {
return this.delegate.links;
}
get sampled() {
return this.delegate.sampled;
}
get kind() {
return this.delegate.kind;
}
end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
annotateSchemaError(this.delegate, exit);
this.delegate.end(endTime, exit);
}
attribute(key: string, value: unknown): void {
this.delegate.attribute(key, value);
}
event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
this.delegate.event(name, startTime, attributes);
}
addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
this.delegate.addLinks(links);
}
}
const withSchemaErrorAttributes = (delegate: Tracer.Tracer): Tracer.Tracer =>
Tracer.make({
span: (options) => new RelayTraceSpan(delegate.span(options)),
...(delegate.context ? { context: delegate.context } : {}),
});
export const makeRelayTraceLayer = (input: {
readonly tracesEndpoint: string;
readonly tracesDatasetName: string;
readonly ingestToken: Redacted.Redacted<string>;
}) =>
OtlpTracer.layer({
url: input.tracesEndpoint,
resource: {
serviceName: "t3-code-relay-worker",
attributes: {
"service.runtime": "cloudflare-worker",
"service.component": "relay",
Layer.effect(
Tracer.Tracer,
OtlpTracer.make({
url: input.tracesEndpoint,
resource: {
serviceName: "t3-code-relay-worker",
attributes: {
"service.runtime": "cloudflare-worker",
"service.component": "relay",
},
},
},
headers: {
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
"X-Axiom-Dataset": input.tracesDatasetName,
},
exportInterval: "1 second",
}).pipe(Layer.provide(OtlpSerialization.layerJson));
headers: {
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
"X-Axiom-Dataset": input.tracesDatasetName,
},
exportInterval: "1 second",
}).pipe(Effect.map(withSchemaErrorAttributes)),
).pipe(Layer.provide(OtlpSerialization.layerJson));
+1 -1
View File
@@ -129,7 +129,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
const apnsDeliveryQueueSender = yield* Cloudflare.QueueBinding.bind(apnsDeliveryQueue);
const axiomDatasetName = yield* observability.traces.name;
const axiomIngestToken = yield* observability.ingestToken.token;
const axiomIngestToken = yield* observability.workerIngestToken.token;
const axiomTracesEndpoint = yield* observability.traces.otelTracesEndpoint;
const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY");
+2
View File
@@ -1,6 +1,7 @@
import { definePlugin } from "@oxlint/plugins";
import noInlineSchemaCompile from "./rules/no-inline-schema-compile.ts";
import noManualEffectRuntimeInTests from "./rules/no-manual-effect-runtime-in-tests.ts";
export default definePlugin({
meta: {
@@ -8,5 +9,6 @@ export default definePlugin({
},
rules: {
"no-inline-schema-compile": noInlineSchemaCompile,
"no-manual-effect-runtime-in-tests": noManualEffectRuntimeInTests,
},
});
@@ -0,0 +1,73 @@
import { assert, describe } from "@effect/vitest";
import { createOxlintRuleHarness } from "../test/utils.ts";
const rule = createOxlintRuleHarness("t3code/no-manual-effect-runtime-in-tests", {
filename: "fixture.test.ts",
});
describe("t3code/no-manual-effect-runtime-in-tests", () => {
rule.valid(
"allows @effect/vitest effect tests",
`
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
it.effect("runs an Effect", () => Effect.succeed("ok"));
`,
);
const runtimeMethods = [
"runCallback",
"runCallbackWith",
"runFork",
"runForkWith",
"runPromise",
"runPromiseExit",
"runPromiseExitWith",
"runPromiseWith",
"runSync",
"runSyncExit",
"runSyncExitWith",
"runSyncWith",
] as const;
for (const method of runtimeMethods) {
rule.invalid(
`reports Effect.${method}`,
`
import * as Effect from "effect/Effect";
test("runs an Effect", () => {
Effect.${method}(Effect.succeed("ok"));
});
`,
(output) => {
assert.match(output, /Use @effect\/vitest with it\.effect/);
},
);
}
rule.invalid(
"reports ManagedRuntime.make",
`
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
test("makes a runtime", () => {
ManagedRuntime.make(Layer.empty);
});
`,
);
});
const productionRule = createOxlintRuleHarness("t3code/no-manual-effect-runtime-in-tests");
productionRule.valid(
"allows production runtime boundaries",
`
import * as Effect from "effect/Effect";
export const main = () => Effect.runPromise(Effect.void);
`,
);
@@ -0,0 +1,113 @@
import { defineRule } from "@oxlint/plugins";
import * as Option from "effect/Option";
import { getPropertyName, isIdentifier, unwrapExpression } from "../utils.ts";
const TEST_FILE_PATTERN = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
const EFFECT_RUNTIME_METHODS = new Set([
"runCallback",
"runCallbackWith",
"runFork",
"runForkWith",
"runPromise",
"runPromiseExit",
"runPromiseExitWith",
"runPromiseWith",
"runSync",
"runSyncExit",
"runSyncExitWith",
"runSyncWith",
]);
// Existing manual runners are tracked as debt. The rule permits no net-new
// occurrences in these files, while unlisted test files must have zero.
const LEGACY_BASELINE = new Map<string, number>([
["apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts", 1],
["apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts", 2],
["apps/mobile/src/state/use-remote-environment-registry.test.ts", 2],
["apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts", 5],
["apps/server/src/orchestration/commandInvariants.test.ts", 6],
["apps/server/src/orchestration/Layers/CheckpointReactor.test.ts", 42],
["apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts", 5],
["apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts", 4],
["apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts", 70],
["apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts", 31],
["apps/server/src/orchestration/Layers/ThreadDeletionReactor.test.ts", 2],
["apps/server/src/orchestration/projector.test.ts", 20],
["apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts", 4],
["apps/server/src/provider/acp/CursorAcpSupport.test.ts", 1],
["apps/server/src/provider/Layers/ClaudeAdapter.test.ts", 2],
["apps/server/src/provider/Layers/CodexAdapter.test.ts", 1],
["apps/server/src/provider/Layers/CodexSessionRuntime.test.ts", 5],
["apps/server/src/provider/Layers/CursorAdapter.test.ts", 1],
["apps/server/src/provider/Layers/CursorProvider.test.ts", 4],
["apps/server/src/provider/Layers/ProviderService.test.ts", 2],
["apps/server/src/provider/Layers/ProviderSessionReaper.test.ts", 21],
["apps/server/src/relay/AgentAwarenessRelay.test.ts", 4],
["apps/server/src/server.test.ts", 1],
["apps/web/src/cloud/dpop.test.ts", 2],
["apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts", 1],
["oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.test.ts", 7],
["packages/client-runtime/src/managedRelayState.test.ts", 1],
["packages/client-runtime/src/wsTransport.test.ts", 2],
]);
const baselineFor = (filename: string): number => {
const normalized = filename.replaceAll("\\", "/");
for (const [suffix, count] of LEGACY_BASELINE) {
if (normalized.endsWith(suffix)) return count;
}
return 0;
};
const manualRunnerName = (callee: unknown): Option.Option<string> => {
const expression = unwrapExpression(callee);
if (Option.isNone(expression) || expression.value.type !== "MemberExpression") {
return Option.none();
}
const object = unwrapExpression(expression.value.object);
const property = getPropertyName(expression.value.property);
if (Option.isNone(property)) return Option.none();
if (isIdentifier(object, "Effect") && EFFECT_RUNTIME_METHODS.has(property.value)) {
return Option.some(`Effect.${property.value}`);
}
if (isIdentifier(object, "ManagedRuntime") && property.value === "make") {
return Option.some("ManagedRuntime.make");
}
return Option.none();
};
export default defineRule({
meta: {
type: "problem",
docs: {
description:
"Disallow manually creating or running Effect runtimes in tests; use @effect/vitest.",
},
},
create(context) {
if (!TEST_FILE_PATTERN.test(context.filename)) return {};
const allowedCount = baselineFor(context.filename);
let occurrenceCount = 0;
return {
CallExpression(node) {
const runner = manualRunnerName(node.callee);
if (Option.isNone(runner)) return;
occurrenceCount++;
if (occurrenceCount <= allowedCount) return;
context.report({
node: node.callee,
message: `Do not use ${runner.value} in tests. Use @effect/vitest with it.effect(...) and test layers instead.`,
});
},
};
},
});
+9 -2
View File
@@ -48,6 +48,10 @@ interface RuleHarness {
readonly invalid: (name: string, source: string, assertion?: (output: string) => void) => void;
}
interface RuleHarnessOptions {
readonly filename?: string;
}
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
@@ -73,7 +77,10 @@ const spawnAndCollectOutput = Effect.fnUntraced(function* (command: ChildProcess
return { exitCode, stdout, stderr };
}, Effect.scoped);
export const createOxlintRuleHarness = (ruleName: string): RuleHarness => {
export const createOxlintRuleHarness = (
ruleName: string,
options: RuleHarnessOptions = {},
): RuleHarness => {
const [pluginName, shortRuleName] = ruleName.split("/");
const diagnosticRuleName =
pluginName && shortRuleName ? `${pluginName}\\(${shortRuleName}\\)` : ruleName;
@@ -84,7 +91,7 @@ export const createOxlintRuleHarness = (ruleName: string): RuleHarness => {
const path = yield* Path.Path;
const fixtureDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-oxlint-" });
const configPath = path.join(fixtureDir, ".oxlintrc.json");
const sourcePath = path.join(fixtureDir, "fixture.ts");
const sourcePath = path.join(fixtureDir, options.filename ?? "fixture.ts");
const repoRoot = path.join(import.meta.dirname, "..", "..");
const oxlintBin = path.join(
repoRoot,
+5 -1
View File
@@ -15,6 +15,7 @@ import type {
EnvironmentScopeRequiredError,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -111,7 +112,10 @@ export type RemoteEnvironmentAuthError =
export const remoteHttpClientLayer = (
fetchFn: typeof globalThis.fetch,
): Layer.Layer<HttpClient.HttpClient> =>
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));
Layer.merge(
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),
httpHeaderRedactionLayer,
);
const failRemoteRequest = (
requestUrl: string,
+17
View File
@@ -241,6 +241,7 @@ const ModelReroutedType = Schema.Literal("model.rerouted");
const ConfigWarningType = Schema.Literal("config.warning");
const DeprecationNoticeType = Schema.Literal("deprecation.notice");
const FilesPersistedType = Schema.Literal("files.persisted");
const ToolDeniedType = Schema.Literal("tool.denied");
const RuntimeWarningType = Schema.Literal("runtime.warning");
const RuntimeErrorType = Schema.Literal("runtime.error");
@@ -589,6 +590,14 @@ const FilesPersistedPayload = Schema.Struct({
});
export type FilesPersistedPayload = typeof FilesPersistedPayload.Type;
const ToolDeniedPayload = Schema.Struct({
toolName: TrimmedNonEmptyStringSchema,
toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
reason: Schema.optional(TrimmedNonEmptyStringSchema),
agentId: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ToolDeniedPayload = typeof ToolDeniedPayload.Type;
const RuntimeWarningPayload = Schema.Struct({
message: TrimmedNonEmptyStringSchema,
detail: Schema.optional(Schema.Unknown),
@@ -934,6 +943,13 @@ const ProviderRuntimeFilesPersistedEvent = Schema.Struct({
});
export type ProviderRuntimeFilesPersistedEvent = typeof ProviderRuntimeFilesPersistedEvent.Type;
const ProviderRuntimeToolDeniedEvent = Schema.Struct({
...ProviderRuntimeEventBase.fields,
type: ToolDeniedType,
payload: ToolDeniedPayload,
});
export type ProviderRuntimeToolDeniedEvent = typeof ProviderRuntimeToolDeniedEvent.Type;
const ProviderRuntimeWarningEvent = Schema.Struct({
...ProviderRuntimeEventBase.fields,
type: RuntimeWarningType,
@@ -994,6 +1010,7 @@ export const ProviderRuntimeEventV2 = Schema.Union([
ProviderRuntimeConfigWarningEvent,
ProviderRuntimeDeprecationNoticeEvent,
ProviderRuntimeFilesPersistedEvent,
ProviderRuntimeToolDeniedEvent,
ProviderRuntimeWarningEvent,
ProviderRuntimeErrorEvent,
]);
+55 -11
View File
@@ -329,7 +329,11 @@ export class RelayAuthInvalidError extends Schema.TaggedErrorClass<RelayAuthInva
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 401 },
) {}
) {
override get message(): string {
return `Relay authentication failed: ${this.reason}`;
}
}
export class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofExpiredError>()(
"RelayEnvironmentLinkProofExpiredError",
@@ -338,7 +342,11 @@ export class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorCla
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 401 },
) {}
) {
override get message(): string {
return "Relay environment link proof expired";
}
}
export class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofInvalidError>()(
"RelayEnvironmentLinkProofInvalidError",
@@ -348,7 +356,11 @@ export class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorCla
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 400 },
) {}
) {
override get message(): string {
return `Relay environment link proof is invalid: ${this.reason}`;
}
}
export class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErrorClass<RelayEnvironmentConnectNotAuthorizedError>()(
"RelayEnvironmentConnectNotAuthorizedError",
@@ -357,7 +369,11 @@ export class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErro
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 403 },
) {}
) {
override get message(): string {
return "Relay environment connection is not authorized";
}
}
export class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointUnavailableError>()(
"RelayEnvironmentEndpointUnavailableError",
@@ -367,7 +383,11 @@ export class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedError
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 502 },
) {}
) {
override get message(): string {
return `Relay environment endpoint is unavailable: ${this.reason}`;
}
}
export class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointTimedOutError>()(
"RelayEnvironmentEndpointTimedOutError",
@@ -376,7 +396,11 @@ export class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorCla
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 504 },
) {}
) {
override get message(): string {
return "Relay environment endpoint request timed out";
}
}
export class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<RelayEnvironmentLinkFailedError>()(
"RelayEnvironmentLinkFailedError",
@@ -386,7 +410,11 @@ export class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<Rel
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 500 },
) {}
) {
override get message(): string {
return `Relay environment link failed: ${this.reason}`;
}
}
export class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentLinkUnavailableError>()(
"RelayEnvironmentLinkUnavailableError",
@@ -396,7 +424,11 @@ export class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClas
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 503 },
) {}
) {
override get message(): string {
return `Relay environment link is unavailable: ${this.reason}`;
}
}
export class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofExpiredError>()(
"RelayAgentActivityPublishProofExpiredError",
@@ -405,7 +437,11 @@ export class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErr
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 401 },
) {}
) {
override get message(): string {
return "Relay agent activity publish proof expired";
}
}
export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofInvalidError>()(
"RelayAgentActivityPublishProofInvalidError",
@@ -415,7 +451,11 @@ export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErr
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 401 },
) {}
) {
override get message(): string {
return `Relay agent activity publish proof is invalid: ${this.reason}`;
}
}
export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalError>()(
"RelayInternalError",
@@ -425,7 +465,11 @@ export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalErr
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 500 },
) {}
) {
override get message(): string {
return `Relay internal error: ${this.reason}`;
}
}
export const RelayProtectedError = Schema.Union([
RelayAuthInvalidError,
+4
View File
@@ -31,6 +31,10 @@
"types": "./src/observability.ts",
"import": "./src/observability.ts"
},
"./httpObservability": {
"types": "./src/httpObservability.ts",
"import": "./src/httpObservability.ts"
},
"./shell": {
"types": "./src/shell.ts",
"import": "./src/shell.ts"
+8
View File
@@ -0,0 +1,8 @@
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Headers from "effect/unstable/http/Headers";
export const httpHeaderRedactionLayer = Layer.effect(
Headers.CurrentRedactedNames,
Effect.map(Headers.CurrentRedactedNames, (names) => [...names, "dpop"]),
);
+22 -1
View File
@@ -27,6 +27,12 @@ describe("loadRepoEnv", () => {
expect(env.EXPO_PUBLIC_CLERK_JWT_TEMPLATE).toBeUndefined();
expect(env.T3CODE_RELAY_URL).toBeUndefined();
expect(env.VITE_T3CODE_RELAY_URL).toBeUndefined();
expect(env.T3CODE_MOBILE_OTLP_TRACES_URL).toBeUndefined();
expect(env.T3CODE_MOBILE_OTLP_TRACES_DATASET).toBeUndefined();
expect(env.T3CODE_MOBILE_OTLP_TRACES_TOKEN).toBeUndefined();
expect(env.EXPO_PUBLIC_OTLP_TRACES_URL).toBeUndefined();
expect(env.EXPO_PUBLIC_OTLP_TRACES_DATASET).toBeUndefined();
expect(env.EXPO_PUBLIC_OTLP_TRACES_TOKEN).toBeUndefined();
});
it("applies process, root local, and root precedence in that order", () => {
@@ -73,26 +79,41 @@ describe("loadRepoEnv", () => {
VITE_CLERK_JWT_TEMPLATE: "template_legacy",
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_canonical",
VITE_T3CODE_RELAY_URL: "https://legacy.example.test",
EXPO_PUBLIC_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
EXPO_PUBLIC_OTLP_TRACES_DATASET: "mobile-traces",
EXPO_PUBLIC_OTLP_TRACES_TOKEN: "mobile-token",
}),
).toEqual({
clerkPublishableKey: "pk_legacy",
clerkJwtTemplate: "template_legacy",
clerkCliOAuthClientId: "oauth_canonical",
relayUrl: "https://legacy.example.test",
mobileOtlpTracesUrl: "https://api.axiom.co/v1/traces",
mobileOtlpTracesDataset: "mobile-traces",
mobileOtlpTracesToken: "mobile-token",
});
});
it("projects only the configured aliases", () => {
it("projects canonical mobile tracing values to Expo public aliases", () => {
expect(
loadRepoEnv({
baseEnv: {
T3CODE_RELAY_URL: "https://relay.example.test",
T3CODE_MOBILE_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
T3CODE_MOBILE_OTLP_TRACES_DATASET: "mobile-traces",
T3CODE_MOBILE_OTLP_TRACES_TOKEN: "mobile-token",
},
repoRoot: makeTemporaryDirectory(),
}),
).toEqual({
T3CODE_RELAY_URL: "https://relay.example.test",
VITE_T3CODE_RELAY_URL: "https://relay.example.test",
T3CODE_MOBILE_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
T3CODE_MOBILE_OTLP_TRACES_DATASET: "mobile-traces",
T3CODE_MOBILE_OTLP_TRACES_TOKEN: "mobile-token",
EXPO_PUBLIC_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
EXPO_PUBLIC_OTLP_TRACES_DATASET: "mobile-traces",
EXPO_PUBLIC_OTLP_TRACES_TOKEN: "mobile-token",
});
});
});
+36
View File
@@ -9,6 +9,9 @@ export interface T3CodePublicConfig {
readonly clerkJwtTemplate: string | undefined;
readonly clerkCliOAuthClientId: string | undefined;
readonly relayUrl: string | undefined;
readonly mobileOtlpTracesUrl: string | undefined;
readonly mobileOtlpTracesDataset: string | undefined;
readonly mobileOtlpTracesToken: string | undefined;
}
type Environment = Readonly<Record<string, string | undefined>>;
@@ -57,6 +60,24 @@ export function loadRepoEnv({
VITE_T3CODE_RELAY_URL: config.relayUrl,
}
: {}),
...(config.mobileOtlpTracesUrl
? {
T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileOtlpTracesUrl,
EXPO_PUBLIC_OTLP_TRACES_URL: config.mobileOtlpTracesUrl,
}
: {}),
...(config.mobileOtlpTracesDataset
? {
T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileOtlpTracesDataset,
EXPO_PUBLIC_OTLP_TRACES_DATASET: config.mobileOtlpTracesDataset,
}
: {}),
...(config.mobileOtlpTracesToken
? {
T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileOtlpTracesToken,
EXPO_PUBLIC_OTLP_TRACES_TOKEN: config.mobileOtlpTracesToken,
}
: {}),
};
}
@@ -76,6 +97,21 @@ export function resolvePublicConfig(...sources: readonly Environment[]): T3CodeP
),
clerkCliOAuthClientId: firstNonEmpty(sources, "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID"),
relayUrl: firstNonEmpty(sources, "T3CODE_RELAY_URL", "VITE_T3CODE_RELAY_URL"),
mobileOtlpTracesUrl: firstNonEmpty(
sources,
"T3CODE_MOBILE_OTLP_TRACES_URL",
"EXPO_PUBLIC_OTLP_TRACES_URL",
),
mobileOtlpTracesDataset: firstNonEmpty(
sources,
"T3CODE_MOBILE_OTLP_TRACES_DATASET",
"EXPO_PUBLIC_OTLP_TRACES_DATASET",
),
mobileOtlpTracesToken: firstNonEmpty(
sources,
"T3CODE_MOBILE_OTLP_TRACES_TOKEN",
"EXPO_PUBLIC_OTLP_TRACES_TOKEN",
),
};
}
+1
View File
@@ -91,6 +91,7 @@ export default defineConfig({
"typescript/restrict-template-expressions": "off",
"typescript/unbound-method": "off",
"t3code/no-inline-schema-compile": "warn",
"t3code/no-manual-effect-runtime-in-tests": "error",
},
options: {
// Revisit once Oxlint's tsgolint path can integrate with @effect/tsgo diagnostics.