Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/server/src/auth/CloudflareAccessAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,11 @@ it.live(
authenticated: boolean;
sessionMethod?: string;
sessionId?: string;
founder?: string;
};
expect(firstBody.authenticated).toBe(true);
expect(firstBody.sessionMethod).toBe("browser-session-cookie");
expect(firstBody.founder).toBe("kameron");
const setCookie = first.headers.get("set-cookie");
expect(setCookie).toBeTruthy();
expect(setCookie).toContain("HttpOnly");
Expand All @@ -308,9 +310,11 @@ it.live(
const secondBody = (await second.json()) as {
authenticated: boolean;
sessionId?: string;
founder?: string;
};
expect(secondBody.authenticated).toBe(true);
expect(secondBody.sessionId).toBe(firstBody.sessionId);
expect(secondBody.founder).toBe("kameron");
expect(second.headers.get("set-cookie")).toBeNull();
expect(jwksFetches).toBe(1);

Expand Down
10 changes: 9 additions & 1 deletion apps/server/src/auth/CloudflareAccessAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,17 @@ export const verifyCloudflareAccessJwt = Effect.fn("CloudflareAccessAuth.verifyJ
return yield* denied();
});

export interface CloudflareAccessMintedSession extends SessionStore.IssuedSession {
readonly founder: Founder;
}

export class CloudflareAccessAuth extends Context.Service<
CloudflareAccessAuth,
{
readonly config: CloudflareAccessConfig | null;
readonly tryAutoMintBrowserSession: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<SessionStore.IssuedSession | null>;
) => Effect.Effect<CloudflareAccessMintedSession | null>;
}
>()("t3/auth/CloudflareAccessAuth") {}

Expand Down Expand Up @@ -194,6 +198,10 @@ const make = Effect.fn("CloudflareAccessAuth.make")(function* (options?: {
scopes: AuthStandardClientScopes,
})
.pipe(
Effect.map((issued): CloudflareAccessMintedSession => ({
...issued,
founder: identity.founder,
})),
Effect.catch((cause) =>
Effect.logWarning("Failed to issue T3 browser session from Cloudflare Access JWT.", {
cause,
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ export interface AuthenticatedSession {
readonly subject: string;
readonly method: ServerAuthSessionMethod;
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly founder?: Founder;
readonly proofKeyThumbprint?: string;
readonly expiresAt?: DateTime.DateTime;
}
Expand Down Expand Up @@ -1003,6 +1004,7 @@ export const make = Effect.gen(function* () {
subject: session.subject,
method: session.method,
scopes: session.scopes,
...(session.founder ? { founder: session.founder } : {}),
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
Expand Down Expand Up @@ -1097,6 +1099,7 @@ export const make = Effect.gen(function* () {
...authScopeResponse(session.scopes),
sessionMethod: session.method,
sessionId: session.sessionId,
...(session.founder ? { founder: session.founder } : {}),
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
}) satisfies AuthSessionState,
),
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/auth/SessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export interface VerifiedSession {
readonly expiresAt?: DateTime.DateTime;
readonly subject: string;
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly founder?: Founder;
readonly proofKeyThumbprint?: string;
readonly runtimeModeCeiling?: RuntimeMode;
/** An MCP client that is another T3 Code environment's peer link. */
Expand Down Expand Up @@ -963,6 +964,7 @@ const make = Effect.gen(function* () {
expiresAt: row.value.expiresAt,
subject: row.value.subject,
scopes: row.value.scopes,
...(row.value.founder ? { founder: row.value.founder } : {}),
} satisfies VerifiedSession;
}
const [encodedPayload, signature] = token.split(".");
Expand Down Expand Up @@ -1032,6 +1034,7 @@ const make = Effect.gen(function* () {
expiresAt: rowHoldsDeadline ? row.value.expiresAt : expiresAt.value,
subject: claims.sub,
scopes: row.value.scopes,
...(row.value.founder ? { founder: row.value.founder } : {}),
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
...(claims.plk === 1 ? { peerLink: true as const } : {}),
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ export const layer = HttpApiBuilder.group(
...authScopeResponse(minted.scopes),
sessionMethod: minted.method,
sessionId: minted.sessionId,
founder: minted.founder,
expiresAt: DateTime.toUtc(minted.expiresAt),
} satisfies AuthSessionState;
}
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/routes/__root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
import { AppConnectionReporter, LinkOnConnectCoordinator } from "../state/peerLinks";
import { AutoAddLinkedEnvironments } from "../state/knownEnvironments";
import { LinkedSidebarFromHosts } from "../state/linkedSidebarHost";
import { AutoSeedFounderInboxOwner } from "../state/founderSessionSeed";

export const Route = createRootRoute({
beforeLoad: async ({ location }) => {
Expand Down Expand Up @@ -214,6 +215,7 @@ function RootRouteBranch() {
<LinkOnConnectCoordinator />
<AutoAddLinkedEnvironments />
<LinkedSidebarFromHosts />
<AutoSeedFounderInboxOwner />
<AddProjectToMachineDialogHost />
<UseInAnotherAppDialogHost />
{import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
Expand Down
45 changes: 45 additions & 0 deletions apps/web/src/state/founderSessionSeed.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useAtomValue } from "@effect/atom-react";
import { PRIMARY_LOCAL_ENVIRONMENT_ID, type Founder } from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { useEffect } from "react";

import {
updateClientSettings,
useClientSettings,
useClientSettingsHydrated,
} from "../hooks/useSettings";
import { environmentIdsKey } from "./environmentAtomList";
import { environmentSummaries } from "./presentation";
import { environmentSessionStatesAtom } from "./session";

/**
* Seeds `founderInboxOwner` once on fresh clients (such as a mobile browser authenticated via
* Cloudflare Access) from the authenticated session's `founder`. Waits for client settings to
* hydrate first so an explicit saved choice is never overwritten.
*/
export function AutoSeedFounderInboxOwner() {
const hydrated = useClientSettingsHydrated();
const founderInboxOwner = useClientSettings((settings) => settings.founderInboxOwner);
const identities = useAtomValue(environmentSummaries.identitiesAtom);
const states = useAtomValue(
environmentSessionStatesAtom(
environmentIdsKey(identities.map((identity) => identity.environmentId)),
),
);
let sessionFounder: Founder | undefined;
for (let i = 0; i < states.length; i++) {
const session = AsyncResult.getOrElse(states[i]!, () => null);
if (!session?.authenticated || session.founder === undefined) continue;
if (identities[i]?.environmentId === PRIMARY_LOCAL_ENVIRONMENT_ID) {
sessionFounder = session.founder;
break;
}
sessionFounder ??= session.founder;
}
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- seeds founderInboxOwner once when unset after settings hydrate
useEffect(() => {
if (!hydrated || founderInboxOwner !== undefined || sessionFounder === undefined) return;
void updateClientSettings({ founderInboxOwner: sessionFounder });
}, [hydrated, founderInboxOwner, sessionFounder]);
return null;
}
2 changes: 2 additions & 0 deletions packages/contracts/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,8 @@ export const AuthSessionState = Schema.Struct({
sessionMethod: Schema.optionalKey(ServerAuthSessionMethod),
/** This client's own session, so it can tell what it did from what another client did. */
sessionId: Schema.optionalKey(AuthSessionId),
/** Founder bound to this session (e.g. Cloudflare Access or founder-paired client), when known. */
founder: Schema.optionalKey(Founder),
expiresAt: Schema.optionalKey(Schema.DateTimeUtc),
});
export type AuthSessionState = typeof AuthSessionState.Type;
Expand Down
Loading