Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
ffcb783
fix(client-runtime): bind OIDC sessions to their relay, add relay policy
flvvius Nov 19, 2026
0fdcd2f
fix(relay): self-host stack runs least-privileged by default
flvvius Nov 19, 2026
85a0cb8
fix(relay): self-host Caddy caps request bodies, adds headers
flvvius Nov 19, 2026
a0afc70
chore(relay): pin self-host base images by digest
flvvius Nov 19, 2026
6273e4a
fix(relay): vet where self-declared endpoints resolve
flvvius Nov 19, 2026
d0b839f
docs(relay): what the self-hosted relay stores, operating it
flvvius Nov 19, 2026
794cc22
feat(web): let a build pin or allowlist its relay
flvvius Nov 19, 2026
f89ded5
fix(web,desktop): keep OIDC tokens out of localStorage
flvvius Nov 19, 2026
a21461c
fix(relay): accept only ID tokens from secure OIDC discovery
flvvius Nov 19, 2026
d4b43c7
fix(mobile): honor the relay pin and unregister the phone on sign-out
flvvius Nov 19, 2026
4e5f538
fix(server): bind the CLI credential to its relay and name it at sign-in
flvvius Nov 19, 2026
17cf94e
docs: document relay pinning and session binding
flvvius Nov 19, 2026
f643c8d
fix(server): let a link publish activity without remote control
flvvius Nov 19, 2026
ac3a2bb
chore(client-runtime,desktop): fix format, lint and unused exports
flvvius Nov 19, 2026
22d0956
fix(relay): bound carried traffic and state the client address
flvvius Nov 19, 2026
a8c6811
feat(relay): offboard an account and announce revocations
flvvius Nov 19, 2026
2d24ccf
feat(relay): self-host limits, link cap, file secrets, offboard
flvvius Nov 19, 2026
9370168
refactor(relay): follow repo lint rules for node imports and tags
flvvius Nov 19, 2026
9b8ef90
docs(relay): scope operating guide to self-hosting the relay
flvvius Nov 19, 2026
19eb8e8
fix(relay): print offboard usage instead of binding the port
flvvius Nov 19, 2026
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
3 changes: 3 additions & 0 deletions apps/desktop/src/ipc/DesktopIpcHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts";
import * as DesktopIpc from "./DesktopIpc.ts";
import { installNotificationBadge } from "./methods/notificationBadge.ts";
import { installOidcSessionStore, requestOidcToken } from "./methods/oidcSession.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import { getConnectionCatalog, setConnectionCatalog } from "./methods/connectionCatalog.ts";
import {
Expand Down Expand Up @@ -101,6 +102,8 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(completeLegacyLocalStorage);
yield* ipc.handleSync(getAppBranding);
yield* installRelayTelemetryEnabled();
yield* installOidcSessionStore();
yield* ipc.handle(requestOidcToken);
yield* ipc.handleSync(getSystemLocale);
yield* ipc.handleSync(getPreferredSystemLanguages);
yield* ipc.handleSync(getPrimaryPasteEnabled);
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/ipc/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ export const CLI_COMMAND_UNINSTALL_CHANNEL = "desktop:cli-command-uninstall";
export const CLI_COMMAND_ADD_TO_PATH_CHANNEL = "desktop:cli-command-add-to-path";
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_RELAY_TELEMETRY_ENABLED_CHANNEL = "desktop:get-relay-telemetry-enabled";
export const GET_OIDC_SESSION_CHANNEL = "desktop:get-oidc-session";
export const SET_OIDC_SESSION_CHANNEL = "desktop:set-oidc-session";
export const REQUEST_OIDC_TOKEN_CHANNEL = "desktop:request-oidc-token";
export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale";
export const GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL = "desktop:get-preferred-system-languages";
export const GET_PRIMARY_PASTE_ENABLED_CHANNEL = "desktop:get-primary-paste-enabled";
Expand Down
123 changes: 123 additions & 0 deletions apps/desktop/src/ipc/methods/oidcSession.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";

import * as DesktopConfig from "../../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as ElectronSafeStorage from "../../electron/ElectronSafeStorage.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import { installOidcSessionStore } from "./oidcSession.ts";

const SESSION = '{"refreshToken":"refresh-1"}';
const reverse = (value: string) => Array.from(value).reverse().join("");
const sealed = (value: string) => `sealed:${reverse(value)}`;

const layerSafeStorage = (available: boolean) =>
Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, {
isEncryptionAvailable: Effect.succeed(available),
encryptString: (value) => Effect.succeed(new TextEncoder().encode(sealed(value))),
decryptString: (value) =>
Effect.sync(() => reverse(new TextDecoder().decode(value).slice("sealed:".length))),
selectedStorageBackend: Effect.succeedNone,
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);

const layerEnvironment = (baseDir: string) =>
DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);

/** Installs the store as startup does and answers like the renderer's bridge. */
const openStore = (baseDir: string, encryptionAvailable: boolean) =>
Effect.gen(function* () {
const invoke = new Map<string, DesktopIpc.DesktopIpcHandleListener>();
const sync = new Map<string, DesktopIpc.DesktopIpcSyncListener>();
const ipcMain: DesktopIpc.DesktopIpcMain = {
removeHandler: (channel) => void invoke.delete(channel),
handle: (channel, listener) => void invoke.set(channel, listener),
removeAllListeners: (channel) => void sync.delete(channel),
on: (channel, listener) => void sync.set(channel, listener),
};
yield* installOidcSessionStore().pipe(
Effect.provide(
Layer.mergeAll(
DesktopIpc.layerTest(ipcMain),
layerEnvironment(baseDir),
layerSafeStorage(encryptionAvailable),
NodeServices.layer,
),
),
);
const sender = { sender: { id: 1 } };
return {
get: () => {
const event = { ...sender, returnValue: undefined as unknown };
sync.get(IpcChannels.GET_OIDC_SESSION_CHANNEL)?.(event);
return event.returnValue;
},
set: (session: string | null) =>
Effect.promise(async () =>
invoke.get(IpcChannels.SET_OIDC_SESSION_CHANNEL)?.(sender, session),
),
};
});

const sessionFileContents = (baseDir: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return yield* fileSystem
.readFileString(environment.path.join(environment.stateDir, "oidc-session.bin"))
.pipe(Effect.orElseSucceed(() => null));
}).pipe(Effect.provide(layerEnvironment(baseDir)));

describe("installOidcSessionStore", () => {
it.effect("keeps the session encrypted on disk across restarts and deletes it on sign-out", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped();

const first = yield* openStore(baseDir, true);
yield* first.set(SESSION);
assert.equal(first.get(), SESSION);
const onDisk = yield* sessionFileContents(baseDir);
assert.isNotNull(onDisk);
assert.notInclude(onDisk ?? "", "refresh-1");

const restarted = yield* openStore(baseDir, true);
assert.equal(restarted.get(), SESSION);

yield* restarted.set(null);
assert.isNull(restarted.get());
assert.isNull(yield* sessionFileContents(baseDir));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect("keeps the session in memory only when no keychain is available", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped();

const store = yield* openStore(baseDir, false);
yield* store.set(SESSION);

assert.equal(store.get(), SESSION);
assert.isNull(yield* sessionFileContents(baseDir));
assert.isNull((yield* openStore(baseDir, false)).get());
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
130 changes: 130 additions & 0 deletions apps/desktop/src/ipc/methods/oidcSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import { oidcDiscoveryUrl, parseOidcMetadata } from "@t3tools/shared/oidc";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Base64 from "effect/encoding/Base64";
import * as FileSystem from "effect/FileSystem";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientRequest from "effect/http/HttpClientRequest";

import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as ElectronSafeStorage from "../../electron/ElectronSafeStorage.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";

const OIDC_SESSION_FILE_NAME = "oidc-session.bin";
const TOKEN_REQUEST_TIMEOUT = Duration.seconds(10);
const TOKEN_GRANT_TYPES = new Set(["authorization_code", "refresh_token"]);

export class DesktopOidcTokenRequestError extends Schema.TaggedError<DesktopOidcTokenRequestError>()(
"DesktopOidcTokenRequestError",
{ reason: Schema.String, cause: Schema.optional(Schema.Defect()) },
) {
override get message(): string {
return `The token request was refused: ${this.reason}.`;
}
}

/**
* Keeps the renderer's OpenID Connect session encrypted with safeStorage. Read once here because a
* sync IPC handler cannot wait on the filesystem; every write updates this copy first. Without a
* keychain the session stays in memory and ends with the app.
*/
export const installOidcSessionStore = Effect.fn("desktop.ipc.oidcSession.install")(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const filePath = environment.path.join(environment.stateDir, OIDC_SESSION_FILE_NAME);
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
Effect.orElseSucceed(() => false),
);

const stored = yield* fileSystem.readFileString(filePath).pipe(
Effect.flatMap((encoded) => Effect.fromResult(Base64.decode(encoded.trim()))),
Effect.flatMap(safeStorage.decryptString),
Effect.orElseSucceed(() => null),
);
const session = yield* Ref.make<string | null>(stored);
const writes = yield* Semaphore.make(1);

yield* ipc.handleSync(
DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_OIDC_SESSION_CHANNEL,
result: Schema.NullOr(Schema.String),
handler: () => Ref.get(session),
}),
);
yield* ipc.handle(
DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_OIDC_SESSION_CHANNEL,
payload: Schema.NullOr(Schema.String),
result: Schema.Void,
handler: Effect.fn("desktop.ipc.oidcSession.set")(function* (next) {
yield* Ref.set(session, next);
yield* writes.withPermits(1)(
Effect.gen(function* () {
if (next !== null && (yield* encryptionAvailable)) {
const encrypted = yield* safeStorage.encryptString(next);
yield* writeFileStringAtomically({ filePath, contents: Base64.encode(encrypted) });
return;
}
if (next !== null) {
yield* Effect.logWarning(
"No OS keychain is available, so the sign-in session is kept in memory only.",
);
}
yield* fileSystem.remove(filePath, { force: true });
}),
);
}),
}),
);
});

/**
* Identity providers such as Entra refuse to redeem a code sent from the renderer's custom-scheme
* origin, so token requests run here. Discovery runs here too, so only an issuer's own token
* endpoint can be reached, and only with an authorization code or refresh token grant.
*/
export const requestOidcToken = DesktopIpc.makeIpcMethod({
channel: IpcChannels.REQUEST_OIDC_TOKEN_CHANNEL,
payload: Schema.Struct({
issuer: Schema.String,
tokenEndpoint: Schema.String,
body: Schema.String,
}),
result: Schema.Struct({ status: Schema.Number, body: Schema.String }),
handler: Effect.fn("desktop.ipc.oidcSession.requestToken")(function* (input) {
const grantType = new URLSearchParams(input.body).get("grant_type");
if (grantType === null || !TOKEN_GRANT_TYPES.has(grantType)) {
return yield* new DesktopOidcTokenRequestError({ reason: "unsupported grant type" });
}
const httpClient = yield* HttpClient.HttpClient;
const metadata = yield* HttpClientRequest.get(oidcDiscoveryUrl(input.issuer)).pipe(
HttpClientRequest.acceptJson,
HttpClient.filterStatusOk(httpClient).execute,
Effect.flatMap((response) => response.json),
Effect.flatMap((body) =>
Effect.try({
try: () => parseOidcMetadata(input.issuer, body),
catch: (cause) => new DesktopOidcTokenRequestError({ reason: "discovery failed", cause }),
}),
),
Effect.timeout(TOKEN_REQUEST_TIMEOUT),
);
if (metadata.tokenEndpoint !== input.tokenEndpoint) {
return yield* new DesktopOidcTokenRequestError({ reason: "not the issuer's token endpoint" });
}
const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(
HttpClientRequest.bodyText(input.body, "application/x-www-form-urlencoded"),
HttpClientRequest.acceptJson,
httpClient.execute,
Effect.timeout(TOKEN_REQUEST_TIMEOUT),
);
return { status: response.status, body: yield* response.text };
}),
});
6 changes: 6 additions & 0 deletions apps/desktop/src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
const enabled = ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL);
return enabled === null ? null : enabled === true;
},
getOidcSession: () => {
const session: unknown = ipcRenderer.sendSync(IpcChannels.GET_OIDC_SESSION_CHANNEL);
return typeof session === "string" ? session : null;
},
setOidcSession: (session) => ipcRenderer.invoke(IpcChannels.SET_OIDC_SESSION_CHANNEL, session),
requestOidcToken: (input) => ipcRenderer.invoke(IpcChannels.REQUEST_OIDC_TOKEN_CHANNEL, input),
getPathForFile: (file: File) => webUtils.getPathForFile(file),
getClientPlatform: () => clientPlatform,
restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL),
Expand Down
9 changes: 7 additions & 2 deletions apps/mobile/src/features/cloud/CloudAuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
cloudAccountService,
createCloudRelayAccountService,
deactivateCloudRelayAccount,
signOutAndUnregisterDevice,
} from "./cloudAccountService";
import { CloudAuthContext, type CloudAuth } from "./cloudAuth";
import { getMobileOidcController } from "./oidc/mobileOidc";
Expand Down Expand Up @@ -50,7 +51,7 @@ function OidcAuthBridge(props: {
userId: snapshot.userId,
accountLabel: snapshot.label,
getToken: props.controller.getToken,
signOut: props.controller.signOut,
signOut: () => signOutAndUnregisterDevice(props.controller.getToken, props.controller.signOut),
};
return <CloudAuthContext.Provider value={value}>{props.children}</CloudAuthContext.Provider>;
}
Expand All @@ -68,7 +69,11 @@ function ClerkAuthBridge(props: { readonly children: ReactNode }) {
userId: userId ?? null,
accountLabel: user?.primaryEmailAddress?.emailAddress ?? null,
getToken: () => getToken(resolveRelayClerkTokenOptions()),
signOut: () => signOut(),
signOut: () =>
signOutAndUnregisterDevice(
() => getToken(resolveRelayClerkTokenOptions()),
() => signOut(),
),
};
return <CloudAuthContext.Provider value={value}>{props.children}</CloudAuthContext.Provider>;
}
Expand Down
17 changes: 17 additions & 0 deletions apps/mobile/src/features/cloud/cloudAccountService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@ export function activateCloudRelayAccount(
});
}

/**
* The relay accepts the device's unregistration only with a valid token, so the device leaves
* before the session does; otherwise the relay keeps pushing to a signed-out phone.
*/
export async function signOutAndUnregisterDevice(
readToken: () => Promise<string | null>,
signOut: () => Promise<unknown>,
): Promise<void> {
await runtime.runPromise(
unregisterAgentAwarenessDeviceForCurrentUser(readToken).pipe(
Effect.timeout("5 seconds"),
Effect.ignore,
),
);
await signOut();
}

function clerkTokenReader(clerk: ClerkInstance): () => Promise<string | null> {
return async () =>
clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null;
Expand Down
6 changes: 3 additions & 3 deletions apps/mobile/src/features/cloud/oidc/mobileOidc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ let controller: OidcController | null | undefined;
/** The one controller for this app; null when the build has no OpenID Connect provider. */
export function getMobileOidcController(): OidcController | null {
if (controller !== undefined) return controller;
const { oidc } = resolveCloudPublicConfig();
const { oidc, relay } = resolveCloudPublicConfig();
controller =
oidc.issuer && oidc.clientId
oidc.issuer && oidc.clientId && relay.url
? createOidcController({
config: { issuer: oidc.issuer, clientId: oidc.clientId },
config: { relayUrl: relay.url, issuer: oidc.issuer, clientId: oidc.clientId },
redirectUri,
sessions: secureSessionStore(),
pending: memoryStore(),
Expand Down
Loading
Loading