Skip to content
Open
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
2 changes: 1 addition & 1 deletion .agents/skills/test-t3-app/references/feature-map.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ Code:
Connections:

- **settings.connections** — `/settings/connections`, "Environments": "This machine", "Linked environments", "Network access", "Tailscale HTTPS", "T3 Connect", "Load balancing".
- **settings.access** — `/settings/access`, "Sharing & access": paired devices, "Guest links", "Require approval for new devices".
- **settings.access** — `/settings/access`, "Sharing & access": paired devices, "Guest links", "Require approval for new devices", "Require enrolled founders".
- **settings.secrets** — `/settings/secrets`, "Secrets" (only when secrets are enabled).

More:
Expand Down
96 changes: 96 additions & 0 deletions apps/server/src/auth/EnvironmentAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,102 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
);

it.effect("binds a founder only from its pairing code or its approved Connect device", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const sessions = yield* SessionStore.SessionStore;
const founderOf = (sessionId: Parameters<typeof serverAuth.messageSenderOf>[0]) =>
serverAuth.messageSenderOf(sessionId).pipe(Effect.map((sender) => sender.founder));
const admin = yield* serverAuth.issueSession({ label: "Owner" });

const enrolled = yield* serverAuth.issuePairingCredential({ founder: "kameron" });
const phone = yield* serverAuth.createBrowserSession(enrolled.credential, requestMetadata);
expect(yield* founderOf((yield* sessions.verify(phone.sessionToken)).sessionId)).toBe(
"kameron",
);
// An agent sign-in code never names a person.
const agentCode = yield* serverAuth.issuePairingCredential({
access: "auto",
founder: "jeff",
});
expect(
(yield* serverAuth.listPairingLinks()).find((link) => link.id === agentCode.id)?.founder,
).toBeUndefined();

// Earlier sessions are not evidence of who holds a new one.
const desktop = () =>
sessions.issue({
subject: "desktop-bootstrap",
method: "browser-session-cookie",
client: { label: "Desktop", deviceType: "desktop" },
});
const firstDesktop = yield* desktop();
yield* serverAuth.setClientSessionFounder(admin.sessionId, firstDesktop.sessionId, "jeff");
expect(yield* founderOf((yield* desktop()).sessionId)).toBeNull();
const reusedKey = "reused-proof-key";
const pairWithKey = () =>
serverAuth
.issuePairingCredential()
.pipe(
Effect.flatMap((code) =>
serverAuth.exchangeBootstrapCredentialForAccessToken(
code.credential,
undefined,
requestMetadata,
{ proofKeyThumbprint: reusedKey },
),
),
);
yield* pairWithKey();
const [keyed] = (yield* serverAuth.listClientSessions(admin.sessionId)).filter(
(session) => session.subject !== "desktop-bootstrap" && session.founder === undefined,
);
yield* serverAuth.setClientSessionFounder(admin.sessionId, keyed!.sessionId, "jeff");
yield* pairWithKey();
expect(
(yield* serverAuth.listClientSessions(admin.sessionId)).filter(
(session) => session.founder === "jeff" && session.subject !== "desktop-bootstrap",
),
).toHaveLength(1);

// An approved Connect device keeps its founder through renewal, until it is revoked.
const deviceKey = "Hn4wT7qZpL2xV9cRb6mYs3kDf8gJa5eUo1iWt0zQrNE";
const signIn = () =>
serverAuth
.issueConnectCredential({ proofKeyThumbprint: deviceKey, requireApproval: false })
.pipe(
Effect.flatMap((code) =>
serverAuth.exchangeBootstrapCredentialForAccessToken(
code.credential,
undefined,
requestMetadata,
{ proofKeyThumbprint: deviceKey },
),
),
);
const deviceSessions = () =>
serverAuth
.listClientSessions(admin.sessionId)
.pipe(
Effect.map((all) =>
all.filter((session) => session.subject === EnvironmentAuth.CLOUD_CONNECT_SUBJECT),
),
);
yield* signIn();
const [device] = yield* deviceSessions();
expect(device?.founder).toBeUndefined();
yield* serverAuth.setClientSessionFounder(admin.sessionId, device!.sessionId, "kameron");
yield* signIn();
expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([
"kameron",
"kameron",
]);
yield* serverAuth.revokeClientSession(admin.sessionId, device!.sessionId);
yield* signIn();
expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([undefined]);
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
);

it.effect("prefers a bearer token over an empty primary cookie", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
Expand Down
8 changes: 7 additions & 1 deletion apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,7 @@ export class EnvironmentAuth extends Context.Service<
readonly purpose?: "startup";
readonly mcpApproval?: AuthMcpClientAccess;
readonly requiresConnectApproval?: boolean;
readonly founder?: Founder;
}) => Effect.Effect<
IssuedPairingLink,
ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
Expand Down Expand Up @@ -1004,6 +1005,7 @@ export const make = Effect.gen(function* () {
...requestMetadata,
...(grant.label ? { label: grant.label } : {}),
},
...(grant.founder === undefined ? {} : { founder: grant.founder }),
})
.pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })));
return {
Expand All @@ -1019,7 +1021,7 @@ export const make = Effect.gen(function* () {

type ResolvedBootstrapGrant = Pick<
PairingGrantStore.BootstrapGrant,
"scopes" | "subject" | "label"
"scopes" | "subject" | "label" | "founder"
> & {
readonly method: PairingGrantStore.BootstrapGrant["method"] | "reusable-dev-token";
};
Expand Down Expand Up @@ -1124,6 +1126,7 @@ export const make = Effect.gen(function* () {
...requestMetadata,
...(grant.label ? { label: grant.label } : {}),
},
...(grant.founder === undefined ? {} : { founder: grant.founder }),
})
.pipe(
Effect.mapError(
Expand Down Expand Up @@ -1176,6 +1179,7 @@ export const make = Effect.gen(function* () {
...(input?.purpose ? { purpose: input.purpose } : {}),
...(input?.mcpApproval ? { mcpApproval: input.mcpApproval } : {}),
...(input?.requiresConnectApproval ? { requiresConnectApproval: true } : {}),
...(input?.founder === undefined ? {} : { founder: input.founder }),
});
return {
id: issued.id,
Expand Down Expand Up @@ -1386,6 +1390,8 @@ export const make = Effect.gen(function* () {
subject: "one-time-token",
...(input?.label ? { label: input.label } : {}),
...(input?.access ? { mcpApproval: input.access } : {}),
// An agent sign-in is never a founder.
...(input?.founder === undefined || input.access ? {} : { founder: input.founder }),
}).pipe(
Effect.map((issued) => ({
...toPairingCredential(issued),
Expand Down
9 changes: 9 additions & 0 deletions apps/server/src/auth/PairingGrantStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
parseMcpApprovalCode,
type ServerAuthBootstrapMethod,
connectDeviceVerificationCode,
type Founder,
} from "@t3tools/contracts";
import {
DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
Expand Down Expand Up @@ -39,6 +40,8 @@ export interface BootstrapGrant {
readonly subject: string;
readonly label?: string;
readonly proofKeyThumbprint?: string;
/** The founder whose client this code enrolls. */
readonly founder?: Founder;
readonly expiresAt: DateTime.DateTime;
}

Expand Down Expand Up @@ -257,6 +260,8 @@ export class PairingGrantStore extends Context.Service<
readonly mcpApproval?: AuthMcpClientAccess;
/** Spendable only after someone trusts `proofKeyThumbprint` as a T3 Connect device. */
readonly requiresConnectApproval?: boolean;
/** Sessions this code starts belong to this founder. */
readonly founder?: Founder;
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
/** A device's open or denied request, reused so retries keep one request and one code. */
readonly findPendingConnect: (
Expand Down Expand Up @@ -330,6 +335,7 @@ const toPairingLink = (row: AuthPairingLinks.AuthPairingLinkRecord): AuthPairing
scopes: row.scopes,
subject: row.subject,
...(row.label ? { label: row.label } : {}),
...(row.founder === null ? {} : { founder: row.founder }),
createdAt: row.createdAt,
expiresAt: row.expiresAt,
...(row.requiresConnectApproval === 1 && row.proofKeyThumbprint
Expand Down Expand Up @@ -495,6 +501,7 @@ const make = Effect.gen(function* () {
label: input?.label ?? null,
proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
...(input?.requiresConnectApproval ? { requiresConnectApproval: true } : {}),
...(input?.founder === undefined ? {} : { founder: input.founder }),
createdAt: now,
expiresAt: expiresAt,
})
Expand All @@ -516,6 +523,7 @@ const make = Effect.gen(function* () {
scopes: input?.scopes ?? AuthStandardClientScopes,
subject,
...(input?.label ? { label: input.label } : {}),
...(input?.founder === undefined ? {} : { founder: input.founder }),
createdAt: now,
expiresAt,
...(input?.requiresConnectApproval && input.proofKeyThumbprint
Expand Down Expand Up @@ -674,6 +682,7 @@ const make = Effect.gen(function* () {
...(consumed.value.proofKeyThumbprint
? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
: {}),
...(consumed.value.founder === null ? {} : { founder: consumed.value.founder }),
expiresAt: consumed.value.expiresAt,
} satisfies BootstrapGrant;
}
Expand Down
15 changes: 15 additions & 0 deletions apps/server/src/auth/SessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,8 @@ export class SessionStore extends Context.Service<
readonly peerLink?: boolean;
readonly replaceActiveForSubjectAndMethod?: boolean;
readonly replaceSessionId?: AuthSessionId;
/** The founder the client's pairing code enrolled. */
readonly founder?: Founder;
}) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
/**
Expand Down Expand Up @@ -762,6 +764,7 @@ const make = Effect.gen(function* () {
issuedAt,
expiresAt,
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
...(input?.founder === undefined ? {} : { founder: input.founder }),
} satisfies AuthSessions.CreateAuthSessionInput;
const replacedSessionIds = yield* (
input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod
Expand All @@ -788,6 +791,17 @@ const make = Effect.gen(function* () {
discard: true,
});
}
// An approved T3 Connect device key can supply the founder, so read back what was stored.
const founder =
client.deviceType === "bot"
? null
: (input?.founder ??
(claims.jkt === undefined
? null
: yield* authSessions.getById({ sessionId }).pipe(
Effect.map((row) => (Option.isSome(row) ? row.value.founder : null)),
Effect.orElseSucceed(() => null),
)));
yield* emitUpsert(
toAuthClientSession({
sessionId,
Expand All @@ -799,6 +813,7 @@ const make = Effect.gen(function* () {
expiresAt,
lastConnectedAt: null,
connected: false,
...(founder === null ? {} : { founder }),
}),
);

Expand Down
9 changes: 5 additions & 4 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1760,14 +1760,15 @@ const shellAttentionMentions = (text: string | null | undefined) => {
};

const shellInbox = (
inbox: ThreadInbox | undefined,
{ inbox, standing }: { readonly inbox?: ThreadInbox | undefined; readonly standing?: unknown },
pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null,
latestUserAuthoredMessageAt: DateTime.Utc | null,
) =>
inbox === undefined
? {}
: {
inbox: projectThreadInbox(inbox, {
standing: standing != null,
pendingHumanRequest: pendingRuntimeRequest !== null,
latestHumanMessageAt:
latestUserAuthoredMessageAt === null
Expand Down Expand Up @@ -1861,7 +1862,7 @@ export function threadShellFromProjection(
});
return {
createdBy: projection.thread.createdBy,
...shellInbox(projection.thread.inbox, pendingRuntimeRequest, latestUserAuthoredMessageAt),
...shellInbox(projection.thread, pendingRuntimeRequest, latestUserAuthoredMessageAt),
creationSource: projection.thread.creationSource,
id: projection.thread.id,
projectId: projection.thread.projectId,
Expand Down Expand Up @@ -2215,7 +2216,7 @@ function shellFromState(input: {
? {}
: { historyOrigin: input.state.thread.historyOrigin }),
...shellInbox(
input.state.thread.inbox,
input.state.thread,
input.state.pendingRuntimeRequest,
input.state.latestUserAuthoredMessageAt,
),
Expand Down Expand Up @@ -8644,7 +8645,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
pendingRuntimeRequest: null,
// The same projected inbox the shell carries, so an answered ask is already gone.
...shellInbox(
thread.inbox,
thread,
null,
row.latest_user_authored_message_at === null
? null
Expand Down
20 changes: 15 additions & 5 deletions apps/server/src/persistence/AuthPairingLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
import * as SqlSchema from "effect/sql/SqlSchema";

import { AuthClientMetadata, AuthEnvironmentScopes } from "@t3tools/contracts";
import { AuthClientMetadata, AuthEnvironmentScopes, Founder } from "@t3tools/contracts";

import {
type AuthPairingLinkRepositoryError,
Expand Down Expand Up @@ -40,6 +40,8 @@ export const AuthPairingLinkRecord = Schema.Struct({
requiresConnectApproval: SqliteFlag,
connectApproved: SqliteFlag,
requestedClient: Schema.NullOr(Schema.fromJsonString(AuthClientMetadata)),
/** The founder whose client this code enrolls. */
founder: Schema.NullOr(Founder),
});
export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;

Expand All @@ -52,6 +54,7 @@ export const CreateAuthPairingLinkInput = Schema.Struct({
label: Schema.NullOr(Schema.String),
proofKeyThumbprint: Schema.NullOr(Schema.String),
requiresConnectApproval: Schema.optionalKey(Schema.Boolean),
founder: Schema.optionalKey(Founder),
createdAt: Schema.DateTimeUtcFromString,
expiresAt: Schema.DateTimeUtcFromString,
});
Expand Down Expand Up @@ -126,6 +129,7 @@ const AuthPairingLinkRawDbRow = Schema.Struct({
requiresConnectApproval: Schema.Unknown,
connectApproved: Schema.Unknown,
requestedClient: Schema.Unknown,
founder: Schema.Unknown,
});

const decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord);
Expand Down Expand Up @@ -197,6 +201,7 @@ export const make = Effect.gen(function* () {
label,
proof_key_thumbprint,
requires_connect_approval,
founder,
created_at,
expires_at,
consumed_at,
Expand All @@ -211,6 +216,7 @@ export const make = Effect.gen(function* () {
${input.label},
${input.proofKeyThumbprint},
${input.requiresConnectApproval ? 1 : 0},
${input.founder ?? null},
${input.createdAt},
${input.expiresAt},
NULL,
Expand Down Expand Up @@ -281,7 +287,8 @@ export const make = Effect.gen(function* () {
SELECT 1 FROM auth_connect_devices
WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
) AS "connectApproved",
requested_client_json AS "requestedClient"
requested_client_json AS "requestedClient",
founder AS "founder"
`,
});

Expand All @@ -307,7 +314,8 @@ export const make = Effect.gen(function* () {
SELECT 1 FROM auth_connect_devices
WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
) AS "connectApproved",
requested_client_json AS "requestedClient"
requested_client_json AS "requestedClient",
founder AS "founder"
FROM auth_pairing_links
WHERE revoked_at IS NULL
AND consumed_at IS NULL
Expand Down Expand Up @@ -354,7 +362,8 @@ export const make = Effect.gen(function* () {
SELECT 1 FROM auth_connect_devices
WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
) AS "connectApproved",
requested_client_json AS "requestedClient"
requested_client_json AS "requestedClient",
founder AS "founder"
FROM auth_pairing_links
WHERE credential = ${credential}
`,
Expand All @@ -378,7 +387,8 @@ export const make = Effect.gen(function* () {
SELECT 1 FROM auth_connect_devices
WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
) AS "connectApproved",
requested_client_json AS "requestedClient"
requested_client_json AS "requestedClient",
founder AS "founder"
FROM auth_pairing_links
`;

Expand Down
Loading
Loading