Skip to content
TypeScript

fix(auth): keep pairing credentials out of access read models (#9523)

Theo Browne9d28c21a26ae
diff --git a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts
index 331a722534b..d8a0e3048c5 100644
--- a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts
+++ b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts
@@ -59,7 +59,7 @@ it.layer(NodeServices.layer)("EnvironmentAuth administrative operations", (it) =
expect(listedBeforeRevoke).toHaveLength(1);
expect(listedBeforeRevoke[0]?.id).toBe(created.id);
expect(listedBeforeRevoke[0]?.label).toBe("CI phone");
- expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);
+ expect(listedBeforeRevoke[0]).not.toHaveProperty("credential");
expect(revoked).toBe(true);
expect(listedAfterRevoke).toHaveLength(0);
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.ts
index 5242dd738b8..9a093be41ca 100644
--- a/apps/server/src/auth/PairingGrantStore.test.ts
+++ b/apps/server/src/auth/PairingGrantStore.test.ts
@@ -4,6 +4,8 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Stream from "effect/Stream";
+import * as Queue from "effect/Queue";
import * as TestClock from "effect/testing/TestClock";
import * as ServerConfig from "../config.ts";
@@ -194,6 +196,31 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
),
);
+ it.effect("keeps credentials out of pairing lists and change events", () =>
+ Effect.gen(function* () {
+ const grants = yield* PairingGrantStore.PairingGrantStore;
+ const changes = yield* Queue.unbounded<PairingGrantStore.BootstrapCredentialChange>();
+ yield* grants.streamChanges.pipe(
+ Stream.runForEach((change) => Queue.offer(changes, change)),
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ for (const input of [{}, { label: "Synthetic phone" }]) {
+ const issued = yield* grants.issueOneTimeToken(input);
+ const change = yield* Queue.take(changes);
+ expect(change?.type).toBe("pairingLinkUpserted");
+ if (change?.type !== "pairingLinkUpserted")
+ throw new Error("Expected a pairing link update");
+ expect(change.pairingLink.id).toBe(issued.id);
+ expect(change.pairingLink).not.toHaveProperty("credential");
+ const listed = (yield* grants.listActive()).find((link) => link.id === issued.id);
+ expect(listed).toEqual(change.pairingLink);
+ const consumed = yield* grants.consume(issued.credential);
+ expect(consumed.scopes).toEqual(change.pairingLink.scopes);
+ expect(yield* Queue.take(changes)).toEqual({ type: "pairingLinkRemoved", id: issued.id });
+ }
+ }).pipe(Effect.scoped, Effect.provide(makePairingGrantStoreLayer())),
+ );
+
it.effect("lists and revokes active pairing links", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
@@ -205,6 +232,9 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
+ for (const entry of activeBeforeRevoke) {
+ expect(entry).not.toHaveProperty("credential");
+ }
const revoked = yield* bootstrapCredentials.revoke(first.id);
const activeAfterRevoke = yield* bootstrapCredentials.listActive();
diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts
index 057a257ba66..d455d3ac451 100644
--- a/apps/server/src/auth/PairingGrantStore.ts
+++ b/apps/server/src/auth/PairingGrantStore.ts
@@ -340,7 +340,6 @@ export const make = Effect.gen(function* () {
row.label
? ({
id: row.id,
- credential: row.credential,
scopes: row.scopes,
subject: row.subject,
label: row.label,
@@ -349,7 +348,6 @@ export const make = Effect.gen(function* () {
} satisfies AuthPairingLink)
: ({
id: row.id,
- credential: row.credential,
scopes: row.scopes,
subject: row.subject,
createdAt: row.createdAt,
@@ -424,7 +422,6 @@ export const make = Effect.gen(function* () {
);
yield* emitUpsert({
id,
- credential,
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: input?.subject ?? "one-time-token",
...(input?.label ? { label: input.label } : {}),
diff --git a/apps/server/src/cliAuthFormat.test.ts b/apps/server/src/cliAuthFormat.test.ts
index a428adc7bea..3822919a927 100644
--- a/apps/server/src/cliAuthFormat.test.ts
+++ b/apps/server/src/cliAuthFormat.test.ts
@@ -30,7 +30,6 @@ it("formats pairing listings without exposing the secret token", () => {
[
{
id: "pairing-1",
- credential: "secret-pairing-token",
subject: "one-time-token",
label: "Phone",
scopes: ["orchestration:read"],
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 0c6f8b11127..5ffa0cb9e59 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -6,6 +6,7 @@ import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hos
import {
AuthAccessTokenType,
+ AuthStandardClientScopes,
AuthEnvironmentBootstrapTokenType,
AuthTokenExchangeGrantType,
CommandId,
@@ -63,6 +64,7 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
+import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
@@ -152,6 +154,7 @@ import * as ReviewService from "./review/ReviewService.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
+import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
@@ -482,6 +485,7 @@ const makeBrowserOtlpPayload = (spanName: string) =>
});
const buildAppUnderTest = (options?: {
+ onPairingChangesSubscribed?: Effect.Effect<void>;
config?: Partial<ServerConfig.ServerConfig["Service"]>;
layers?: {
keybindings?: Partial<Keybindings.Keybindings["Service"]>;
@@ -1108,6 +1112,24 @@ const buildAppUnderTest = (options?: {
...options?.layers?.cloudCliTokenManager,
}),
),
+ Layer.updateService(PairingGrantStore.PairingGrantStore, (grants) => {
+ const subscribed = options?.onPairingChangesSubscribed;
+ if (!subscribed) return grants;
+ return {
+ ...grants,
+ streamChanges: Stream.unwrap(
+ Effect.gen(function* () {
+ const changes = yield* Queue.unbounded<PairingGrantStore.BootstrapCredentialChange>();
+ yield* grants.streamChanges.pipe(
+ Stream.runForEach((change) => Queue.offer(changes, change)),
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ yield* subscribed;
+ return Stream.fromQueue(changes);
+ }),
+ ),
+ };
+ }),
Layer.provideMerge(makeAuthTestLayer()),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provide(workspaceAndProjectServicesLayer),
@@ -1134,16 +1156,19 @@ const parseSessionCookieFromWsUrl = (
};
};
-const wsRpcProtocolLayer = (wsUrl: string) => {
+const wsRpcProtocolLayer = (wsUrl: string, onMessage?: (message: string) => void) => {
const { cookie, url } = parseSessionCookieFromWsUrl(wsUrl);
const webSocketConstructorLayer = Layer.succeed(
Socket.WebSocketConstructor,
- (socketUrl, protocols) =>
- new NodeSocket.NodeWS.WebSocket(
+ (socketUrl, protocols) => {
+ const socket = new NodeSocket.NodeWS.WebSocket(
socketUrl,
protocols,
cookie ? { headers: { cookie } } : undefined,
- ) as unknown as globalThis.WebSocket,
+ );
+ if (onMessage) socket.on("message", (data) => onMessage(data.toString()));
+ return socket as unknown as globalThis.WebSocket;
+ },
);
return RpcClient.layerProtocolSocket().pipe(
@@ -1159,7 +1184,8 @@ type WsRpcClient =
const withWsRpcClient = <A, E, R>(
wsUrl: string,
f: (client: WsRpcClient) => Effect.Effect<A, E, R>,
-) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl)));
+ onMessage?: (message: string) => void,
+) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl, onMessage)));
const appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) => {
const isAbsoluteUrl = /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url);
@@ -3935,6 +3961,128 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+ it.effect("returns only pairing metadata to access-read HTTP sessions", () =>
+ Effect.gen(function* () {
+ yield* buildAppUnderTest();
+ const reader = yield* exchangeAccessToken(defaultDesktopBootstrapToken, {
+ scope: "access:read",
+ });
+ assert.equal(reader.response.status, 200);
+ assert.equal(reader.body.scope, "access:read");
+ const createdResponse = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: { cookie: yield* getAuthenticatedSessionCookieHeader() },
+ body: yield* HttpBody.json({ label: "Synthetic phone" }),
+ });
+ const created = (yield* createdResponse.json) as { id: string; credential: string };
+ assert.equal(createdResponse.status, 200);
+ const response = yield* HttpClient.get("/api/auth/pairing-links", {
+ headers: { authorization: `Bearer ${reader.body.access_token ?? ""}` },
+ });
+ assert.equal(response.status, 200);
+ const responseText = yield* response.text;
+ assert.notInclude(responseText, '"credential"');
+ assert.notInclude(responseText, created.credential);
+ const links = yield* responseJsonEffect<
+ ReadonlyArray<{
+ readonly id: string;
+ readonly label?: string;
+ readonly scopes: ReadonlyArray<string>;
+ }>
+ >(response);
+ const listed = links.find((link) => link.id === created.id);
+ assert.isDefined(listed);
+ assert.deepInclude(listed, {
+ label: "Synthetic phone",
+ scopes: [...AuthStandardClientScopes],
+ });
+
+ const unauthorizedCreate = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: { authorization: `Bearer ${reader.body.access_token ?? ""}` },
+ body: yield* HttpBody.json({}),
+ });
+ assert.equal(unauthorizedCreate.status, 403);
+ const idExchange = yield* exchangeAccessToken(created.id, { scope: "terminal:operate" });
+ assert.equal(idExchange.response.status, 401);
+ const authorized = yield* exchangeAccessToken(created.credential, {
+ scope: AuthStandardClientScopes.join(" "),
+ });
+ assert.equal(authorized.response.status, 200);
+ assert.equal(authorized.body.scope, AuthStandardClientScopes.join(" "));
+ const reused = yield* exchangeAccessToken(created.credential, { scope: "terminal:operate" });
+ assert.equal(reused.response.status, 401);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("returns only pairing metadata in access-read WebSocket snapshots and updates", () =>
+ Effect.gen(function* () {
+ const changesSubscribed = yield* Deferred.make<void>();
+ yield* buildAppUnderTest({
+ onPairingChangesSubscribed: Deferred.succeed(changesSubscribed, undefined).pipe(
+ Effect.asVoid,
+ ),
+ });
+ const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
+ const createLink = Effect.gen(function* () {
+ const response = yield* HttpClient.post("/api/auth/pairing-token", {
+ headers: { cookie: ownerCookie },
+ body: yield* HttpBody.json({}),
+ });
+ assert.equal(response.status, 200);
+ return (yield* response.json) as { id: string; credential: string };
+ });
+ const initialLink = yield* createLink;
+ const reader = yield* exchangeAccessToken(defaultDesktopBootstrapToken, {
+ scope: "access:read",
+ });
+ assert.equal(reader.body.scope, "access:read");
+ const ticketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", {
+ headers: { authorization: `Bearer ${reader.body.access_token ?? ""}` },
+ });
+ assert.equal(ticketResponse.status, 200);
+ const { ticket } = (yield* ticketResponse.json) as { ticket: string };
+ const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(ticket)}`;
+ const frames: string[] = [];
+ yield* withWsRpcClient(
+ wsUrl,
+ (client) =>
+ Effect.gen(function* () {
+ const snapshotReceived = yield* Deferred.make<void>();
+ const eventsFiber = yield* client.subscribeAuthAccess({}).pipe(
+ Stream.tap((event) =>
+ event.type === "snapshot"
+ ? Deferred.succeed(snapshotReceived, undefined)
+ : Effect.void,
+ ),
+ Stream.takeUntil((event) => event.type === "pairingLinkUpserted"),
+ Stream.runCollect,
+ Effect.forkChild,
+ );
+ yield* Deferred.await(snapshotReceived);
+ yield* Deferred.await(changesSubscribed);
+ const liveLink = yield* createLink;
+ const events = yield* Fiber.join(eventsFiber);
+ const snapshot = events.find((event) => event.type === "snapshot");
+ const update = events.find((event) => event.type === "pairingLinkUpserted");
+ assert.isDefined(snapshot);
+ assert.isDefined(update);
+ assert.isTrue(
+ snapshot?.payload.pairingLinks.some((link) => link.id === initialLink.id),
+ );
+ assert.equal(update?.payload.id, liveLink.id);
+ // Inspect the wire frames so client schema decoding cannot hide a leak.
+ assert.notInclude(frames.join(""), '"credential"');
+ assert.notInclude(frames.join(""), initialLink.credential);
+ assert.notInclude(frames.join(""), liveLink.credential);
+ const paired = yield* exchangeAccessToken(liveLink.credential, {
+ scope: AuthStandardClientScopes.join(" "),
+ });
+ assert.equal(paired.response.status, 200);
+ }),
+ (frame) => frames.push(frame),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)),
+ );
+
it.effect("lists and revokes pairing links for access management sessions", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
@@ -3962,7 +4110,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
});
const listedLinks = (yield* listResponse.json) as ReadonlyArray<{
readonly id: string;
- readonly credential: string;
}>;
const revokeResponse = yield* HttpClient.post("/api/auth/pairing-links/revoke", {
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index 6b81a7f70dd..d4a9c949231 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -25,6 +25,7 @@ import {
type AuthClientSession,
type AuthEnvironmentScope,
type AuthPairingLink,
+ type AuthPairingCredentialResult,
type AdvertisedEndpoint,
type DesktopDiscoveredSshHost,
type DesktopSshEnvironmentTarget,
@@ -541,6 +542,7 @@ function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): string {
type PairingLinkListRowProps = {
pairingLink: ServerPairingLinkRecord;
+ credential: string | undefined;
endpointUrl: string | null | undefined;
endpoints: ReadonlyArray<AdvertisedEndpoint>;
defaultEndpointKey: string | null;
@@ -551,6 +553,7 @@ type PairingLinkListRowProps = {
const PairingLinkListRow = memo(function PairingLinkListRow({
pairingLink,
+ credential,
endpointUrl,
endpoints,
defaultEndpointKey,
@@ -571,20 +574,22 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
const qrPanelId = useId();
const currentOriginPairingUrl = useMemo(
- () => resolveCurrentOriginPairingUrl(pairingLink.credential),
- [pairingLink.credential],
+ () => (credential ? resolveCurrentOriginPairingUrl(credential) : null),
+ [credential],
);
const hostedPairingUrl = useMemo(
() =>
- endpointUrl != null && endpointUrl !== ""
- ? resolveHostedPairingUrl(endpointUrl, pairingLink.credential)
+ credential && endpointUrl != null && endpointUrl !== ""
+ ? resolveHostedPairingUrl(endpointUrl, credential)
: null,
- [endpointUrl, pairingLink.credential],
+ [endpointUrl, credential],
);
const endpointPairingUrl = useMemo(() => {
const endpoint = selectPairingEndpoint(endpoints, defaultEndpointKey);
- return endpoint ? resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential) : null;
- }, [defaultEndpointKey, endpoints, pairingLink.credential]);
+ return endpoint && credential
+ ? resolveAdvertisedEndpointPairingUrl(endpoint, credential)
+ : null;
+ }, [defaultEndpointKey, endpoints, credential]);
const endpointCopyOptions = useMemo(() => {
const options: Array<{
readonly id: string;
@@ -594,11 +599,12 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
readonly detail: string;
readonly qrShareable: boolean;
}> = [];
+ if (!credential) return options;
for (const endpoint of endpoints) {
if (endpoint.status === "unavailable") {
continue;
}
- const url = resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential);
+ const url = resolveAdvertisedEndpointPairingUrl(endpoint, credential);
options.push({
id: endpoint.id,
preferenceKey: endpointDefaultPreferenceKey(endpoint),
@@ -609,19 +615,19 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
});
}
return options;
- }, [endpoints, pairingLink.credential]);
+ }, [endpoints, credential]);
const shareablePairingUrl =
endpointPairingUrl ??
- (endpointUrl != null && endpointUrl !== ""
- ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential))
+ (credential && endpointUrl != null && endpointUrl !== ""
+ ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, credential))
: isLoopbackHostname(window.location.hostname)
? null
: currentOriginPairingUrl);
// Value of the copy attempt that last failed. The clipboard-failure reveal
// dialog must show exactly what failed to copy, not the row's default URL.
const [failedCopyValue, setFailedCopyValue] = useState<string | null>(null);
- const revealValue = failedCopyValue ?? shareablePairingUrl ?? pairingLink.credential;
- const isRevealValueUrl = revealValue !== pairingLink.credential;
+ const revealValue = failedCopyValue ?? shareablePairingUrl ?? credential ?? "";
+ const isRevealValueUrl = revealValue !== credential;
const isRevealValueHostedAppPairingUrl = isRevealValueUrl && isHostedAppPairingUrl(revealValue);
// Never render a QR for a loopback URL, even in the manual-copy fallback.
const isRevealValueQrShareable =
@@ -686,8 +692,8 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
);
const handleCopyCode = useCallback(() => {
- copyPairingValue(pairingLink.credential, "code");
- }, [copyPairingValue, pairingLink.credential]);
+ if (credential) copyPairingValue(credential, "code");
+ }, [copyPairingValue, credential]);
const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt);
@@ -727,7 +733,11 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
<span aria-hidden> · </span>
<AccessScopeSummary scopes={pairingLink.scopes} label="Pairing link scopes" />
</p>
- {shareablePairingUrl === null ? (
+ {!credential ? (
+ <p className="text-[11px] text-muted-foreground/70">
+ Create a new link to share from this client.
+ </p>
+ ) : shareablePairingUrl === null ? (
<p className="text-[11px] text-muted-foreground/70">
Copy the token and pair from another client using this backend&apos;s reachable host.
</p>
@@ -747,13 +757,13 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
</Button>
) : null}
<Dialog
- open={isRevealDialogOpen}
+ open={credential !== undefined && isRevealDialogOpen}
onOpenChange={(open) => {
setIsRevealDialogOpen(open);
if (!open) setFailedCopyValue(null);
}}
>
- {canCopyToClipboard ? (
+ {!credential ? null : canCopyToClipboard ? (
shareablePairingUrl ? null : (
<Button size="xs" variant="outline" onClick={handleCopyCode}>
Copy code
@@ -1000,12 +1010,14 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({
});
type AuthorizedClientsHeaderActionProps = {
+ onPairingLinkCreated: (result: AuthPairingCredentialResult) => void;
clientSessions: ReadonlyArray<ServerClientSessionRecord>;
isRevokingOtherClients: boolean;
onRevokeOtherClients: () => void;
};
const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({
+ onPairingLinkCreated,
clientSessions,
isRevokingOtherClients,
onRevokeOtherClients,
@@ -1020,7 +1032,11 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
const handleCreatePairingLink = useCallback(async () => {
setIsCreatingPairingLink(true);
try {
- await createServerPairingCredential({ label: pairingLabel, scopes: pairingScopes });
+ const created = await createServerPairingCredential({
+ label: pairingLabel,
+ scopes: pairingScopes,
+ });
+ onPairingLinkCreated(created);
setPairingLabel("");
setPairingScopes([...AuthStandardClientScopes]);
setDialogOpen(false);
@@ -1036,7 +1052,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
} finally {
setIsCreatingPairingLink(false);
}
- }, [pairingLabel, pairingScopes]);
+ }, [onPairingLinkCreated, pairingLabel, pairingScopes]);
const togglePairingScope = useCallback((scope: AuthEnvironmentScope, checked: boolean) => {
setPairingScopes((current) =>
@@ -1180,6 +1196,7 @@ type PairingClientsListProps = {
presentation?: AccessSectionPresentation;
isLoading: boolean;
pairingLinks: ReadonlyArray<ServerPairingLinkRecord>;
+ createdPairingCredentials: ReadonlyMap<string, string>;
clientSessions: ReadonlyArray<ServerClientSessionRecord>;
revokingPairingLinkId: string | null;
revokingClientSessionId: string | null;
@@ -1194,6 +1211,7 @@ const PairingClientsList = memo(function PairingClientsList({
presentation = "current",
isLoading,
pairingLinks,
+ createdPairingCredentials,
clientSessions,
revokingPairingLinkId,
revokingClientSessionId,
@@ -1206,6 +1224,7 @@ const PairingClientsList = memo(function PairingClientsList({
<PairingLinkListRow
key={pairingLink.id}
pairingLink={pairingLink}
+ credential={createdPairingCredentials.get(pairingLink.id)}
endpointUrl={endpointUrl}
endpoints={endpoints}
defaultEndpointKey={defaultEndpointKey}
@@ -1795,6 +1814,13 @@ export function ConnectionsSettings() {
const [desktopAccessManagementMutationError, setDesktopAccessManagementMutationError] = useState<
string | null
>(null);
+ // Only this client's creation response can supply a shareable credential.
+ const [createdPairingCredentials, setCreatedPairingCredentials] = useState<
+ ReadonlyMap<string, string>
+ >(() => new Map());
+ const handlePairingLinkCreated = useCallback((created: AuthPairingCredentialResult) => {
+ setCreatedPairingCredentials((current) => new Map(current).set(created.id, created.credential));
+ }, []);
const [revokingDesktopPairingLinkId, setRevokingDesktopPairingLinkId] = useState<string | null>(
null,
);
@@ -3026,6 +3052,7 @@ export function ConnectionsSettings() {
presentation={presentation}
isLoading={isLoadingDesktopAccessManagement}
pairingLinks={visibleDesktopPairingLinks}
+ createdPairingCredentials={createdPairingCredentials}
clientSessions={desktopClientSessions}
revokingPairingLinkId={revokingDesktopPairingLinkId}
revokingClientSessionId={revokingDesktopClientSessionId}
@@ -3184,6 +3211,7 @@ export function ConnectionsSettings() {
title="Authorized clients"
headerAction={
<AuthorizedClientsHeaderAction
+ onPairingLinkCreated={handlePairingLinkCreated}
clientSessions={desktopClientSessions}
isRevokingOtherClients={isRevokingOtherDesktopClients}
onRevokeOtherClients={handleRevokeOtherDesktopClients}
diff --git a/apps/web/src/environments/primary/auth.ts b/apps/web/src/environments/primary/auth.ts
index f9381bcad71..fe0345e4152 100644
--- a/apps/web/src/environments/primary/auth.ts
+++ b/apps/web/src/environments/primary/auth.ts
@@ -119,7 +119,6 @@ const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
export interface ServerPairingLinkRecord {
readonly id: string;
- readonly credential: string;
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly subject: string;
readonly label?: string;
@@ -400,7 +399,6 @@ export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPair
if (pairingLink.label === undefined) {
return {
id: pairingLink.id,
- credential: pairingLink.credential,
scopes: pairingLink.scopes,
subject: pairingLink.subject,
createdAt: timestamps.createdAt,
@@ -409,7 +407,6 @@ export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPair
}
return {
id: pairingLink.id,
- credential: pairingLink.credential,
scopes: pairingLink.scopes,
subject: pairingLink.subject,
label: pairingLink.label,
diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md
index 771b57e14b3..98b3df0a0dc 100644
--- a/docs/internals/environment-auth.md
+++ b/docs/internals/environment-auth.md
@@ -22,6 +22,11 @@ OAuth-style scope strings:
| `relay:read` | Inspect managed relay connectivity. |
| `relay:write` | Link, configure, or unlink managed relay connectivity. |
+Pairing-link lists and access-stream snapshots and updates contain metadata only.
+The raw credential is returned only by the creation request, after the server checks
+`access:write` and the delegated scopes. Web and desktop clients keep that response
+in memory for sharing. They do not recover credentials from access read models.
+
Ordinary pairing links grant the four client-operation scopes and read access to
managed relay connectivity:
`orchestration:read orchestration:operate terminal:operate review:write relay:read`.
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 472c6ed3af3..17e60e8ee4c 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -46,6 +46,11 @@ If you are already running the desktop app and want to make it reachable from ot
3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
4. Use **Create Link** to generate a pairing link you can share with another device.
+Pairing codes and share links are available only in the client that created them,
+while its Connections page remains open. After you leave the page or reload it,
+create a new link to share. Other clients can see the active link's name, scopes,
+and expiry, and can revoke it if they have access management permission.
+
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
diff --git a/packages/client-runtime/src/state/auth.test.ts b/packages/client-runtime/src/state/auth.test.ts
index b31fe617912..9801cd8517c 100644
--- a/packages/client-runtime/src/state/auth.test.ts
+++ b/packages/client-runtime/src/state/auth.test.ts
@@ -8,7 +8,6 @@ describe("applyAuthAccessStreamEvent", () => {
it("accumulates rapid pairing-link and client updates into one snapshot", () => {
const pairingLink = {
id: "pairing-link",
- credential: "credential",
scopes: ["orchestration:read"],
subject: "subject",
label: "Phone",
@@ -56,7 +55,6 @@ describe("applyAuthAccessStreamEvent", () => {
pairingLinks: [
{
id: "pairing-link",
- credential: "credential",
scopes: ["orchestration:read"],
subject: "subject",
label: "Phone",
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
index a11c894a6fb..f4cbee0f688 100644
--- a/packages/contracts/src/auth.ts
+++ b/packages/contracts/src/auth.ts
@@ -218,9 +218,9 @@ export const AuthPairingCredentialResult = Schema.Struct({
});
export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;
+// Read models contain metadata only. Credentials are returned by creation alone.
export const AuthPairingLink = Schema.Struct({
id: TrimmedNonEmptyString,
- credential: TrimmedNonEmptyString,
scopes: AuthEnvironmentScopes,
subject: TrimmedNonEmptyString,
label: Schema.optionalKey(TrimmedNonEmptyString),