From 81b1248c62d959fe4f4ce5b7efb2e1f6a52fdada Mon Sep 17 00:00:00 2001 From: Garrett Fincke Date: Mon, 23 Nov 2026 19:24:25 -0500 Subject: [PATCH] fix(auth): paired devices renew their sessions instead of expiring Direct and tailnet pairings held a fixed 30 day bearer token, so a device in regular use was logged out with no way to renew. Paired clients now hold a token bound to a device key that renews while in use and stays revocable. Hosts or origins that cannot use device keys keep the bearer path. Ports upstream t3code dd512d86c5 (PR 37980), e396bb2e26 (PR 37990), and the in-place session re-read from eac011439a (PR 38410), without T3 Connect or relay code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ty8XE4o5owXdNytd9N92QG --- .../t3-native-controls/ios/T3DpopKeys.swift | 22 +++ .../ios/T3NativeControlsModule.swift | 10 + apps/mobile/src/connection/dpop.ts | 109 +++++++++++ apps/mobile/src/connection/platform.ts | 8 + .../state/remote-environment-projections.ts | 2 +- apps/server/src/auth/EnvironmentAuth.test.ts | 94 +++++++++ apps/server/src/auth/EnvironmentAuth.ts | 94 ++++++--- apps/server/src/auth/SessionStore.test.ts | 25 +++ apps/server/src/auth/SessionStore.ts | 172 +++++++++++++++-- apps/server/src/auth/http.ts | 18 +- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/persistence/AuthSessions.ts | 38 ++++ apps/web/src/connection/dpop.ts | 127 ++++++++++++ apps/web/src/connection/platform.ts | 9 +- docs/internals/environment-auth.md | 10 + docs/user/remote-access.md | 5 +- .../src/authorization/dpopProof.ts | 97 ++++++++++ .../client-runtime/src/authorization/index.ts | 1 + .../src/authorization/layer.test.ts | 1 + .../src/authorization/remote.ts | 72 +++++++ .../src/authorization/service.ts | 181 +++++++++++++++++- .../client-runtime/src/connection/catalog.ts | 16 +- .../src/connection/credentialStore.ts | 17 +- .../client-runtime/src/connection/driver.ts | 9 + .../client-runtime/src/connection/model.ts | 45 ++++- .../src/connection/onboarding.test.ts | 43 ++++- .../src/connection/onboarding.ts | 44 ++++- .../src/connection/registry.test.ts | 17 +- .../client-runtime/src/connection/registry.ts | 6 +- .../src/connection/resolver.test.ts | 1 + .../client-runtime/src/connection/resolver.ts | 32 ++-- .../src/state/environmentHttpAuth.ts | 70 +++++-- packages/contracts/src/auth.ts | 3 +- packages/contracts/src/environment.ts | 2 + 34 files changed, 1296 insertions(+), 105 deletions(-) create mode 100644 apps/mobile/modules/t3-native-controls/ios/T3DpopKeys.swift create mode 100644 apps/mobile/src/connection/dpop.ts create mode 100644 apps/web/src/connection/dpop.ts create mode 100644 packages/client-runtime/src/authorization/dpopProof.ts diff --git a/apps/mobile/modules/t3-native-controls/ios/T3DpopKeys.swift b/apps/mobile/modules/t3-native-controls/ios/T3DpopKeys.swift new file mode 100644 index 0000000000..4c427b1dd5 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/ios/T3DpopKeys.swift @@ -0,0 +1,22 @@ +// apps/mobile/modules/t3-native-controls/ios/T3DpopKeys.swift +// generates, checks & signs w/ P-256 keys for DPoP proofs +import CryptoKit +import Foundation + +/// P-256 keys for DPoP proofs, as 32-byte private scalars and 65-byte uncompressed public points. +enum T3DpopKeys { + /// The private scalar followed by the public point. + static func generate() -> Data { + let key = P256.Signing.PrivateKey() + return key.rawRepresentation + key.publicKey.x963Representation + } + + static func matches(privateKey: Data, publicKey: Data) throws -> Bool { + try P256.Signing.PrivateKey(rawRepresentation: privateKey).publicKey.x963Representation == publicKey + } + + /// ES256 over the JWS signing input, as the raw `r‖s` pair JWS uses. + static func sign(privateKey: Data, signingInput: Data) throws -> Data { + try P256.Signing.PrivateKey(rawRepresentation: privateKey).signature(for: signingInput).rawRepresentation + } +} diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift index 8cab6676b6..aa7756d0fb 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift @@ -57,6 +57,16 @@ public final class T3NativeControlsModule: Module { ViewName("ScrollEdgeBleed") } + AsyncFunction("generateDpopKey") { T3DpopKeys.generate() } + + AsyncFunction("dpopKeyMatches") { (privateKey: Data, publicKey: Data) in + try T3DpopKeys.matches(privateKey: privateKey, publicKey: publicKey) + } + + AsyncFunction("signDpop") { (privateKey: Data, signingInput: Data) in + try T3DpopKeys.sign(privateKey: privateKey, signingInput: signingInput) + } + AsyncFunction("presentVideo") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in try self.presentVideo( url: url, diff --git a/apps/mobile/src/connection/dpop.ts b/apps/mobile/src/connection/dpop.ts new file mode 100644 index 0000000000..6c87cc0cfc --- /dev/null +++ b/apps/mobile/src/connection/dpop.ts @@ -0,0 +1,109 @@ +// apps/mobile/src/connection/dpop.ts +// keeps this install's DPoP key in the keychain & signs w/ native P-256 +import { DpopProof } from "@t3tools/client-runtime/authorization"; +import { DpopPublicJwk } from "@t3tools/shared/dpopCommon"; +import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; +import * as SecureStore from "expo-secure-store"; + +const DPOP_KEY_STORAGE_KEY = "456code.connection.dpop-proof-key"; +const DEVICE_ONLY = { keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY }; + +const DpopPrivateJwkJson = Schema.fromJsonString( + Schema.Struct({ ...DpopPublicJwk.fields, d: Schema.String }), +); +const decodePrivateJwk = Schema.decodeUnknownEffect(DpopPrivateJwkJson); +const encodePrivateJwk = Schema.encodeEffect(DpopPrivateJwkJson); + +interface NativeDpopKeys { + /** A 32-byte private scalar followed by its 65-byte uncompressed public point. */ + generateDpopKey(): Promise; + dpopKeyMatches(privateKey: Uint8Array, publicKey: Uint8Array): Promise; + /** ES256 over the signing input, as the raw 64-byte `r||s` pair. */ + signDpop(privateKey: Uint8Array, signingInput: Uint8Array): Promise; +} + +// imported lazily since loading `expo` at module scope breaks node tests +const nativeDpopKeys = async () => + (await import("expo")).requireNativeModule("T3NativeControls"); + +const dpopError = (message: string) => (cause: unknown) => + new DpopProof.DpopProofError({ message, cause }); + +const base64UrlToBytes = (value: string) => Result.getOrThrow(Base64Url.decode(value)); + +function uncompressedPublicKey(jwk: DpopPublicJwk): Uint8Array { + const x = base64UrlToBytes(jwk.x); + const y = base64UrlToBytes(jwk.y); + if (x.length !== 32 || y.length !== 32) { + throw new Error("DPoP key coordinate is not 32 bytes."); + } + const publicKey = new Uint8Array(65); + publicKey[0] = 0x04; + publicKey.set(x, 1); + publicKey.set(y, 33); + return publicKey; +} + +const generateKey = Effect.fn("mobile.dpop.generateKey")(function* () { + const generated = yield* Effect.tryPromise({ + try: async () => (await nativeDpopKeys()).generateDpopKey(), + catch: dpopError("Could not generate the device key."), + }); + const publicKey = generated.slice(32); + if (generated.length !== 97 || publicKey[0] !== 0x04) { + return yield* new DpopProof.DpopProofError({ message: "Generated device key is invalid." }); + } + const jwk = { + kty: "EC" as const, + crv: "P-256" as const, + x: Base64Url.encode(publicKey.slice(1, 33)), + y: Base64Url.encode(publicKey.slice(33, 65)), + d: Base64Url.encode(generated.slice(0, 32)), + }; + const encoded = yield* encodePrivateJwk(jwk).pipe( + Effect.mapError(dpopError("Could not encode the device key.")), + ); + yield* Effect.tryPromise({ + try: () => SecureStore.setItemAsync(DPOP_KEY_STORAGE_KEY, encoded, DEVICE_ONLY), + catch: dpopError("Could not store the device key."), + }); + return jwk; +}); + +const loadStoredKey = Effect.fn("mobile.dpop.loadStoredKey")(function* (stored: string) { + const jwk = yield* decodePrivateJwk(stored).pipe( + Effect.mapError(dpopError("Stored device key is invalid.")), + ); + const matches = yield* Effect.tryPromise({ + try: async () => + (await nativeDpopKeys()).dpopKeyMatches(base64UrlToBytes(jwk.d), uncompressedPublicKey(jwk)), + catch: dpopError("Stored device key is invalid."), + }); + if (!matches) { + return yield* new DpopProof.DpopProofError({ message: "Stored device key is invalid." }); + } + return jwk; +}); + +export const loadOrCreateProofKey = Effect.fn("mobile.dpop.loadOrCreateProofKey")(function* () { + const stored = yield* Effect.tryPromise({ + try: () => SecureStore.getItemAsync(DPOP_KEY_STORAGE_KEY, DEVICE_ONLY), + catch: dpopError("Could not read the device key."), + }); + const { d, ...publicJwk } = stored ? yield* loadStoredKey(stored) : yield* generateKey(); + const privateKey = yield* Effect.try({ + try: () => base64UrlToBytes(d), + catch: dpopError("Could not read the device key."), + }); + return { + publicJwk, + sign: (signingInput) => + Effect.tryPromise({ + try: async () => (await nativeDpopKeys()).signDpop(privateKey, signingInput), + catch: dpopError("Could not sign the DPoP proof."), + }), + } satisfies DpopProof.DpopProofKey; +}); diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts index edf9bde99a..ce8bcb9a21 100644 --- a/apps/mobile/src/connection/platform.ts +++ b/apps/mobile/src/connection/platform.ts @@ -1,5 +1,6 @@ // apps/mobile/src/connection/platform.ts // supplies native client connectivity and authentication capabilities +import { DpopProof } from "@t3tools/client-runtime/authorization"; import { ClientCapabilities, PlatformConnectionSource } from "@t3tools/client-runtime/platform"; import { Connectivity, Wakeups } from "@t3tools/client-runtime/connection"; import * as Clock from "effect/Clock"; @@ -13,8 +14,10 @@ import * as Network from "expo-network"; import { AppState } from "react-native"; import { authClientMetadata } from "../lib/authClientMetadata"; +import * as ExpoCrypto from "../lib/expoCrypto"; import * as Runtime from "../lib/runtime"; import { mobileApplicationActiveWakeup } from "./app-state-wakeups"; +import { loadOrCreateProofKey } from "./dpop"; import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup"; import * as ConnectionStorage from "./storage"; @@ -161,6 +164,9 @@ const layerPlatformConnectionSource = Layer.succeed( const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer)); const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer)); +const layerDpopSigner = DpopProof.layerSigner(loadOrCreateProofKey()).pipe( + Layer.provide(ExpoCrypto.layer), +); type ConnectionPlatformLayerSource = | typeof layerProvidedConnectionStorage @@ -168,6 +174,7 @@ type ConnectionPlatformLayerSource = | typeof layerConnectivity | typeof layerWakeups | typeof layerProvidedCapabilities + | typeof layerDpopSigner | typeof layerPlatformConnectionSource | typeof EnvironmentOwnedDataCleanup.layer; @@ -181,6 +188,7 @@ export const layer: Layer.Layer< layerConnectivity, layerWakeups, layerProvidedCapabilities, + layerDpopSigner, layerPlatformConnectionSource, EnvironmentOwnedDataCleanup.layer, ); diff --git a/apps/mobile/src/state/remote-environment-projections.ts b/apps/mobile/src/state/remote-environment-projections.ts index c819826a22..e80d084539 100644 --- a/apps/mobile/src/state/remote-environment-projections.ts +++ b/apps/mobile/src/state/remote-environment-projections.ts @@ -62,7 +62,7 @@ export function createRemoteEnvironmentProjectionAtoms(input: { displayUrl, httpBaseUrl, wsBaseUrl, - bearerToken: authorization?.token ?? null, + bearerToken: authorization?._tag === "Bearer" ? authorization.token : null, }; return previous; }).pipe(Atom.withLabel(`mobile:saved-connection:${environmentId}`)); diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 14f12059ce..4d4c4a1389 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -6,6 +6,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; +import * as TestClock from "effect/testing/TestClock"; import * as ServerConfig from "../config.ts"; import { makeDpopKey } from "./dpop.testkit.ts"; @@ -300,6 +301,99 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), ); + it.effect("renews a pairing-link DPoP session in place while its device keeps using it", () => + Effect.gen(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const sessions = yield* SessionStore.SessionStore; + const admin = yield* serverAuth.issueSession({ label: "Owner" }); + const key = makeDpopKey(); + const other = makeDpopKey(); + const pair = (proofKeyThumbprint?: string) => + serverAuth + .issuePairingCredential({ scopes: ["orchestration:read"] }) + .pipe( + Effect.flatMap((pairing) => + serverAuth.exchangeBootstrapCredentialForAccessToken( + pairing.credential, + undefined, + requestMetadata, + proofKeyThumbprint ? { proofKeyThumbprint } : undefined, + ), + ), + ); + const sessionExpiry = (sessionId: string) => + serverAuth + .listClientSessions(admin.sessionId) + .pipe( + Effect.map( + (sessions) => + sessions.find((session) => session.sessionId === sessionId)?.expiresAt + .epochMilliseconds, + ), + ); + + const paired = yield* pair(key.thumbprint); + expect(paired.expires_in).toBe(60 * 60); + const { sessionId } = yield* sessions.verify(paired.access_token); + const pairedAt = (yield* DateTime.now).epochMilliseconds; + // Listed for the whole renewal window, so an idle device can still be revoked. + expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 30 * 24 * 60 * 60 * 1000); + + yield* TestClock.adjust("20 days"); + const replay = new EnvironmentAuth.ServerAuthInvalidCredentialError({ + dpopFailureReason: "replay", + }); + const rejected = yield* serverAuth + .renewAccessToken(paired.access_token, key.thumbprint, Effect.fail(replay)) + .pipe(Effect.flip); + expect(rejected).toBe(replay); + expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 30 * 24 * 60 * 60 * 1000); + + const renewed = yield* serverAuth.renewAccessToken( + paired.access_token, + key.thumbprint, + Effect.void, + ); + expect(renewed.scope).toBe("orchestration:read"); + const verified = yield* sessions.verify(renewed.access_token); + expect(verified.sessionId).toBe(sessionId); + expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 50 * 24 * 60 * 60 * 1000); + + const refused = (token: string, thumbprint: string) => + serverAuth + .renewAccessToken( + token, + thumbprint, + Effect.die("Invalid credentials cannot consume a proof."), + ) + .pipe( + Effect.flip, + Effect.map((error) => error._tag), + ); + expect(yield* refused(renewed.access_token, other.thumbprint)).toBe( + "ServerAuthInvalidCredentialError", + ); + // Bearer sessions keep their fixed lifetimes. + const bearer = yield* pair(); + expect(yield* refused(bearer.access_token, key.thumbprint)).toBe( + "ServerAuthInvalidCredentialError", + ); + + // Inside the renewed window, so only the revocation can refuse it. + expect(yield* serverAuth.revokeClientSession(admin.sessionId, sessionId)).toBe(true); + expect(yield* refused(renewed.access_token, key.thumbprint)).toBe( + "ServerAuthInvalidCredentialError", + ); + + // Idle past the window, the device pairs again. + const idle = yield* pair(key.thumbprint); + yield* TestClock.adjust("31 days"); + expect(yield* refused(idle.access_token, key.thumbprint)).toBe( + "ServerAuthInvalidCredentialError", + ); + }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), + ); + it.effect("preserves pairing grants after rejecting scopes they do not grant", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 6439292511..74af5f90ab 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -78,6 +78,12 @@ export interface IssuedBearerSession { const MCP_CLIENT_SUBJECT = "mcp-client"; const MCP_CLIENT_SESSION_TTL = Duration.days(30); +// A device pairing with its DPoP key renews the session itself, so the token can be short and +// the device stays signed in while used. One idle for the whole window pairs again. +const RENEWABLE_ACCESS_TOKEN_TTL = Duration.hours(1); +const RENEWABLE_SESSION_WINDOW = Duration.days(30); +const PAIRING_LINK_SUBJECT = "one-time-token"; + export interface McpClientSession { readonly sessionId: AuthSessionId; readonly label: string; @@ -392,6 +398,14 @@ export class EnvironmentAuth extends Context.Service< AuthAccessTokenResult, ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError >; + readonly renewAccessToken: ( + accessToken: string, + proofKeyThumbprint: string, + consumeProof: Effect.Effect, + ) => Effect.Effect< + AuthAccessTokenResult, + ServerAuthInvalidCredentialError | ServerAuthInternalError + >; readonly createPairingLink: (input?: { readonly ttl?: Duration.Duration; readonly label?: string; @@ -536,16 +550,15 @@ const rejectMcpClientAudience = (session ).pipe(Effect.tap(() => Effect.logWarning("Rejected an MCP client session outside /mcp."))) : Effect.succeed(session); +const toSessionVerificationError = (cause: SessionStore.SessionCredentialError) => + SessionStore.isSessionCredentialInvalidError(cause) + ? new ServerAuthInvalidCredentialError({ cause }) + : new ServerAuthSessionCredentialValidationError({ cause }); + const mapSessionVerificationErrors = ( effect: Effect.Effect, ): Effect.Effect => - effect.pipe( - Effect.mapError((cause) => - SessionStore.isSessionCredentialInvalidError(cause) - ? new ServerAuthInvalidCredentialError({ cause }) - : new ServerAuthSessionCredentialValidationError({ cause }), - ), - ); + effect.pipe(Effect.mapError(toSessionVerificationError)); export function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null { const header = request.headers["authorization"]; @@ -873,6 +886,43 @@ export const make = Effect.gen(function* () { ); }; + const toAccessTokenResult = (session: SessionStore.IssuedSession) => + DateTime.now.pipe( + Effect.map( + (now) => + ({ + access_token: session.token, + issued_token_type: AuthAccessTokenType, + token_type: session.proofKeyThumbprint ? "DPoP" : "Bearer", + expires_in: Math.max( + 0, + Math.floor((session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000), + ), + scope: encodeOAuthScope(session.scopes), + }) satisfies AuthAccessTokenResult, + ), + ); + + const renewAccessToken: EnvironmentAuth["Service"]["renewAccessToken"] = Effect.fn( + "EnvironmentAuth.renewAccessToken", + )(function* (accessToken, proofKeyThumbprint, consumeProof) { + const session = yield* sessions + .renew(accessToken, { + proofKeyThumbprint, + ttl: RENEWABLE_ACCESS_TOKEN_TTL, + renewalWindow: RENEWABLE_SESSION_WINDOW, + consumeProof, + }) + .pipe( + Effect.mapError((cause) => + isServerAuthCredentialError(cause) || isServerAuthInternalError(cause) + ? cause + : toSessionVerificationError(cause), + ), + ); + return yield* toAccessTokenResult(session); + }); + const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] = (credential, requestedScopes, requestMetadata, input) => { return resolveBootstrapGrant(credential, { @@ -888,6 +938,12 @@ export const make = Effect.gen(function* () { if (grantedScopes.length === 0) { return yield* new ServerAuthScopeNotGrantedError({}); } + // Only plain pairing links renew. CLI, desktop and peer sessions keep + // their own lifetimes, so rotating a credential still cuts them off. + const renewable = + input?.proofKeyThumbprint !== undefined && + grant.method === "one-time-token" && + grant.subject === PAIRING_LINK_SUBJECT; return yield* sessions .issue({ method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", @@ -896,9 +952,10 @@ export const make = Effect.gen(function* () { ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint, - ttl: Duration.hours(1), + ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), } : {}), + ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", client: { ...requestMetadata, @@ -912,25 +969,7 @@ export const make = Effect.gen(function* () { ); }), ), - Effect.flatMap((session) => - DateTime.now.pipe( - Effect.map( - (now) => - ({ - access_token: session.token, - issued_token_type: AuthAccessTokenType, - token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer", - expires_in: Math.max( - 0, - Math.floor( - (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000, - ), - ), - scope: encodeOAuthScope(session.scopes), - }) satisfies AuthAccessTokenResult, - ), - ), - ), + Effect.flatMap(toAccessTokenResult), Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"), ); }; @@ -1322,6 +1361,7 @@ export const make = Effect.gen(function* () { getSessionState, createBrowserSession, exchangeBootstrapCredentialForAccessToken, + renewAccessToken, createPairingLink, issuePairingCredential, issueStartupPairingCredential, diff --git a/apps/server/src/auth/SessionStore.test.ts b/apps/server/src/auth/SessionStore.test.ts index b224112168..11b31894c2 100644 --- a/apps/server/src/auth/SessionStore.test.ts +++ b/apps/server/src/auth/SessionStore.test.ts @@ -184,6 +184,31 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("SessionStore.lay }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))), ); + it.effect("keeps a socket on a session renewed in place until its moved deadline", () => + Effect.gen(function* () { + const sessions = yield* SessionStore.SessionStore; + const renewable = { ttl: Duration.hours(1), renewalWindow: Duration.hours(2) }; + const client = yield* sessions.issue({ ...relaySessionInput, ...renewable }); + const invalidated = yield* Deferred.make(); + const watcher = yield* sessions + .awaitInvalidation(client.sessionId, relaySessionInput.proofKeyThumbprint) + .pipe( + Effect.andThen(Deferred.succeed(invalidated, undefined)), + Effect.forkScoped({ startImmediately: true }), + ); + yield* TestClock.adjust(Duration.minutes(90)); + yield* sessions.renew(client.token, { + proofKeyThumbprint: relaySessionInput.proofKeyThumbprint, + consumeProof: Effect.void, + ...renewable, + }); + yield* TestClock.adjust(Duration.millis(120 * 60_000 - 1)); + expect(yield* Deferred.isDone(invalidated)).toBe(false); + yield* TestClock.adjust(Duration.millis(1)); + yield* Fiber.join(watcher); + }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))), + ); + it.effect("closes a DPoP socket when an earlier renewal in its chain is revoked", () => Effect.gen(function* () { const sessions = yield* SessionStore.SessionStore; diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index 5a25d152c5..d61fc3123a 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -24,6 +24,10 @@ import * as Option from "effect/Option"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as AuthSessions from "../persistence/AuthSessions.ts"; +import type { + ServerAuthInternalError, + ServerAuthInvalidCredentialError, +} from "./EnvironmentAuth.ts"; import * as PayloadSigner from "./PayloadSigner.ts"; import * as ServerSecretStore from "./ServerSecretStore.ts"; import { @@ -129,6 +133,17 @@ export class UnknownSessionTokenError extends Schema.TaggedError()( + "SessionTokenNotRenewableError", + { + sessionId: AuthSessionId, + }, +) { + override get message(): string { + return "Session token cannot be renewed with this key."; + } +} + export class SessionTokenRevokedError extends Schema.TaggedError()( "SessionTokenRevokedError", { @@ -238,6 +253,7 @@ export const SessionCredentialInvalidError = Schema.Union([ SessionTokenExpiredError, UnknownSessionTokenError, SessionTokenRevokedError, + SessionTokenNotRenewableError, InvalidSessionExpirationClaimError, MalformedWebSocketTokenError, InvalidWebSocketTokenSignatureError, @@ -384,7 +400,25 @@ export class SessionStore extends Context.Service< readonly peerLink?: boolean; readonly replaceActiveForSubjectAndMethod?: boolean; readonly replaceSessionId?: AuthSessionId; + /** Keeps the session alive this long past each renewal; `ttl` then bounds only the token. */ + readonly renewalWindow?: Duration.Duration; }) => Effect.Effect; + /** Trades a renewable token, even an expired one, for a fresh token on the same session. */ + readonly renew: ( + token: string, + input: { + readonly proofKeyThumbprint: string; + readonly ttl: Duration.Duration; + readonly renewalWindow: Duration.Duration; + readonly consumeProof: Effect.Effect< + void, + ServerAuthInvalidCredentialError | ServerAuthInternalError + >; + }, + ) => Effect.Effect< + IssuedSession, + SessionCredentialError | ServerAuthInvalidCredentialError | ServerAuthInternalError + >; readonly verify: (token: string) => Effect.Effect; readonly issueWebSocketToken: ( sessionId: AuthSessionId, @@ -439,6 +473,8 @@ const SessionClaims = Schema.Struct({ rtc: Schema.optionalKey(RuntimeMode), /** Signed, so a client cannot shed its peer link's limits. */ plk: Schema.optionalKey(Schema.Literal(1)), + /** Signed, so only sessions issued as renewable can renew. */ + rnw: Schema.optionalKey(Schema.Literal(1)), iat: Schema.Number, exp: Schema.Number, }); @@ -641,6 +677,23 @@ const make = Effect.gen(function* () { ); const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims)); + const signClaims = Effect.fnUntraced(function* (claims: SessionClaims) { + const encodedPayload = yield* encodeClaims(claims).pipe( + Effect.map(base64UrlEncode), + Effect.mapError( + (cause) => + new SessionCredentialIssueError({ + sessionId: claims.sid, + cause: new SessionClaimsEncodingError({ + sessionId: claims.sid, + operation: "encode_session_claims", + cause, + }), + }), + ), + ); + return `${encodedPayload}.${yield* signer.sign(encodedPayload)}`; + }); const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")( function* (input) { const sessionId = AuthSessionId.make( @@ -652,6 +705,9 @@ const make = Effect.gen(function* () { const expiresAt = DateTime.add(issuedAt, { milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL), }); + const sessionExpiresAt = input?.renewalWindow + ? DateTime.add(issuedAt, { milliseconds: Duration.toMillis(input.renewalWindow) }) + : expiresAt; const claims: SessionClaims = { v: 1, kind: "session", @@ -662,25 +718,12 @@ const make = Effect.gen(function* () { ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}), ...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}), ...(input?.peerLink === true ? { plk: 1 as const } : {}), + ...(input?.renewalWindow ? { rnw: 1 as const } : {}), iat: issuedAt.epochMilliseconds, exp: expiresAt.epochMilliseconds, }; - const encodedPayload = yield* encodeClaims(claims).pipe( - Effect.map(base64UrlEncode), - Effect.mapError( - (cause) => - new SessionCredentialIssueError({ - sessionId, - cause: new SessionClaimsEncodingError({ - sessionId, - operation: "encode_session_claims", - cause, - }), - }), - ), - ); - const signature = yield* signer.sign(encodedPayload); + const token = yield* signClaims(claims); const client = input?.client ?? createDefaultClientMetadata(); const sessionRecord = { sessionId, @@ -696,7 +739,7 @@ const make = Effect.gen(function* () { browser: client.browser ?? null, }, issuedAt, - expiresAt, + expiresAt: sessionExpiresAt, } satisfies AuthSessions.CreateAuthSessionInput; const replacedSessionIds = yield* ( input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod @@ -731,7 +774,7 @@ const make = Effect.gen(function* () { method: claims.method, client, issuedAt, - expiresAt, + expiresAt: sessionExpiresAt, lastConnectedAt: null, connected: false, }), @@ -739,7 +782,7 @@ const make = Effect.gen(function* () { return { sessionId, - token: `${encodedPayload}.${signature}`, + token, method: claims.method, client, expiresAt: expiresAt, @@ -848,6 +891,86 @@ const make = Effect.gen(function* () { }, ); + const renew: SessionStore["Service"]["renew"] = Effect.fn("SessionStore.renew")( + function* (token, input) { + const [encodedPayload, signature] = token.split("."); + if (!encodedPayload || !signature) { + return yield* new MalformedSessionTokenError({}); + } + if (!(yield* signer.verify(encodedPayload, signature))) { + return yield* new InvalidSessionTokenSignatureError({}); + } + const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe( + Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })), + ); + // The token's own expiry is ignored here: the session row's expiry is the renewal window. + if (claims.rnw !== 1 || claims.jkt !== input.proofKeyThumbprint) { + return yield* new SessionTokenNotRenewableError({ sessionId: claims.sid }); + } + const row = yield* authSessions + .getById({ sessionId: claims.sid }) + .pipe( + Effect.mapError( + (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }), + ), + ); + if (Option.isNone(row)) { + return yield* new UnknownSessionTokenError({ sessionId: claims.sid }); + } + if (row.value.revokedAt !== null) { + return yield* new SessionTokenRevokedError({ + sessionId: claims.sid, + revokedAt: row.value.revokedAt, + }); + } + const now = yield* DateTime.now; + if (row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) { + return yield* new SessionTokenExpiredError({ + sessionId: claims.sid, + expiresAt: row.value.expiresAt, + observedAt: now, + }); + } + yield* input.consumeProof; + const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(input.ttl) }); + const extended = yield* authSessions + .extend({ + sessionId: claims.sid, + expiresAt: DateTime.add(now, { milliseconds: Duration.toMillis(input.renewalWindow) }), + now, + }) + .pipe( + Effect.mapError( + (cause) => new SessionCredentialIssueError({ sessionId: claims.sid, cause }), + ), + ); + // A revoke can land between the read above and the update. + if (!extended) { + return yield* new SessionTokenNotRenewableError({ sessionId: claims.sid }); + } + const renewedToken = yield* signClaims({ + ...claims, + iat: now.epochMilliseconds, + exp: expiresAt.epochMilliseconds, + }); + const session = yield* loadActiveSession(claims.sid).pipe( + Effect.mapError( + (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }), + ), + ); + if (Option.isSome(session)) yield* emitUpsert(session.value); + return { + sessionId: claims.sid, + token: renewedToken, + method: claims.method, + client: toClientMetadata(row.value.client), + expiresAt, + scopes: row.value.scopes, + proofKeyThumbprint: input.proofKeyThumbprint, + } satisfies IssuedSession; + }, + ); + const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims)); const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn( "SessionStore.issueWebSocketToken", @@ -1071,12 +1194,24 @@ const make = Effect.gen(function* () { while (true) { const rows = yield* Effect.forEach(chain, readRow); if (rows.some((row) => Option.isNone(row) || row.value.revokedAt !== null)) return; + // Renewal moves a session's expiry in place, so the snapshot can be stale. + const currentRow = rows.at(-1); + if (currentRow !== undefined && Option.isSome(currentRow)) current = currentRow.value; const now = yield* DateTime.now; const remaining = current.expiresAt.epochMilliseconds - now.epochMilliseconds; if (remaining > 0) { yield* Effect.raceFirst(nextRemoval, Effect.sleep(Duration.millis(remaining))); continue; } + // A renewal can land between the read above and the clock sample. + const latest = yield* readRow(current.sessionId); + if ( + Option.isSome(latest) && + latest.value.expiresAt.epochMilliseconds > current.expiresAt.epochMilliseconds + ) { + current = latest.value; + continue; + } const successorId = proofKeyThumbprint === undefined ? undefined @@ -1102,6 +1237,7 @@ const make = Effect.gen(function* () { cookieName, legacyCookieName, issue, + renew, verify, issueWebSocketToken, verifyWebSocketToken, diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index ac6fa52f7d..3d63b60def 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -2,6 +2,7 @@ // authenticates environment requests and exposes credential operations import { authScopeRequiredResponse, + AuthAccessTokenType, AuthAccessWriteScope, AuthStandardClientScopes, AuthGrantScope, @@ -375,8 +376,7 @@ export const layer = HttpApiBuilder.group( if (requestedScopes === null || requestedScopes?.length === 0) { return yield* failEnvironmentInvalidRequest("invalid_scope"); } - // Not recorded: a replayer also holds the subject token and could sign its own proof. - // Recording would let anyone write replay state to disk. + // Bootstrap exchanges leave the proof unrecorded because its key is not always trusted. const proof = args.headers.dpop ? yield* checkRequestDpopProof({ request }).pipe( Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => @@ -395,6 +395,20 @@ export const layer = HttpApiBuilder.group( ) : undefined; yield* appendCredentialResponseHeaders; + if (args.payload.subject_token_type === AuthAccessTokenType) { + if (requestedScopes !== undefined) { + return yield* failEnvironmentInvalidRequest("invalid_scope"); + } + if (!proof) { + yield* appendDpopChallengeHeader; + return yield* failEnvironmentAuthInvalid("invalid_credential"); + } + return yield* serverAuth.renewAccessToken( + args.payload.subject_token, + proof.thumbprint, + proof.consume, + ); + } return yield* serverAuth.exchangeBootstrapCredentialForAccessToken( args.payload.subject_token, requestedScopes, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 7ce70da891..32e1f29035 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -217,6 +217,7 @@ export const make = Effect.gen(function* () { repositoryIdentity: true, connectionProbe: true, attachmentUploads: true, + accessTokenRenewal: true, questionAttachments: true, fileAttachments: { maxUploadBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES }, pullRequests: true, diff --git a/apps/server/src/persistence/AuthSessions.ts b/apps/server/src/persistence/AuthSessions.ts index 7b82b012e6..ce4f6c3dcc 100644 --- a/apps/server/src/persistence/AuthSessions.ts +++ b/apps/server/src/persistence/AuthSessions.ts @@ -80,6 +80,13 @@ export const RevokeAuthSessionInput = Schema.Struct({ }); export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type; +export const ExtendAuthSessionInput = Schema.Struct({ + sessionId: AuthSessionId, + expiresAt: Schema.DateTimeUtcFromString, + now: Schema.DateTimeUtcFromString, +}); +export type ExtendAuthSessionInput = typeof ExtendAuthSessionInput.Type; + export const RevokeOtherAuthSessionsInput = Schema.Struct({ currentSessionId: AuthSessionId, revokedAt: Schema.DateTimeUtcFromString, @@ -113,6 +120,10 @@ export class AuthSessionRepository extends Context.Service< readonly revoke: ( input: RevokeAuthSessionInput, ) => Effect.Effect; + /** Moves a live session's expiry; false when it is revoked, expired or missing. */ + readonly extend: ( + input: ExtendAuthSessionInput, + ) => Effect.Effect; readonly revokeAllExcept: ( input: RevokeOtherAuthSessionsInput, ) => Effect.Effect, AuthSessionRepositoryError>; @@ -334,6 +345,20 @@ export const make = Effect.gen(function* () { `, }); + const extendSessionRows = SqlSchema.findAll({ + Request: ExtendAuthSessionInput, + Result: Schema.Struct({ sessionId: AuthSessionId }), + execute: ({ sessionId, expiresAt, now }) => + sql` + UPDATE auth_sessions + SET expires_at = ${expiresAt} + WHERE session_id = ${sessionId} + AND revoked_at IS NULL + AND expires_at > ${now} + RETURNING session_id AS "sessionId" + `, + }); + const revokeOtherSessionRows = SqlSchema.findAll({ Request: RevokeOtherAuthSessionsInput, Result: Schema.Struct({ sessionId: AuthSessionId }), @@ -457,6 +482,18 @@ export const make = Effect.gen(function* () { Effect.map((rows) => rows.length > 0), ); + const extend: AuthSessionRepository["Service"]["extend"] = (input) => + extendSessionRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.extend:query", + "AuthSessionRepository.extend:decodeRows", + { sessionId: input.sessionId }, + ), + ), + Effect.map((rows) => rows.length > 0), + ); + const revokeAllExcept: AuthSessionRepository["Service"]["revokeAllExcept"] = (input) => revokeOtherSessionRows(input).pipe( Effect.mapError( @@ -487,6 +524,7 @@ export const make = Effect.gen(function* () { getById, listActive, revoke, + extend, revokeAllExcept, setLastConnectedAt, } satisfies AuthSessionRepository["Service"]; diff --git a/apps/web/src/connection/dpop.ts b/apps/web/src/connection/dpop.ts new file mode 100644 index 0000000000..7fedd49fb9 --- /dev/null +++ b/apps/web/src/connection/dpop.ts @@ -0,0 +1,127 @@ +// apps/web/src/connection/dpop.ts +// keeps this client's non-extractable DPoP key in IndexedDB +import { DpopProof } from "@t3tools/client-runtime/authorization"; +import { DpopPublicJwk } from "@t3tools/shared/dpopCommon"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Signature from "effect/crypto/Signature"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +interface StoredDpopKey { + readonly privateKey: CryptoKey; + readonly publicJwk: DpopPublicJwk; +} + +const DPOP_DATABASE_NAME = "456code:connection-auth"; +const DPOP_DATABASE_VERSION = 1; +const DPOP_KEY_STORE_NAME = "keys"; +const DPOP_KEY_ID = "direct-dpop-proof-key"; +const decodePublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk); + +export const layerCrypto = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe( + Layer.provideMerge(SecureRandom.layerWebCrypto), +); + +const dpopError = (message: string, cause?: unknown) => + new DpopProof.DpopProofError({ message, ...(cause === undefined ? {} : { cause }) }); + +const openDatabase = Effect.callback((resume) => { + const request = indexedDB.open(DPOP_DATABASE_NAME, DPOP_DATABASE_VERSION); + request.addEventListener("error", () => + resume(Effect.fail(dpopError("Could not open device key storage.", request.error))), + ); + request.addEventListener("upgradeneeded", () => { + if (!request.result.objectStoreNames.contains(DPOP_KEY_STORE_NAME)) { + request.result.createObjectStore(DPOP_KEY_STORE_NAME); + } + }); + request.addEventListener("success", () => resume(Effect.succeed(request.result))); +}); + +const withDatabase = ( + use: (database: IDBDatabase) => Effect.Effect, +) => Effect.acquireUseRelease(openDatabase, use, (database) => Effect.sync(() => database.close())); + +const readStoredKey = withDatabase((database) => + Effect.callback((resume) => { + const request = database + .transaction(DPOP_KEY_STORE_NAME, "readonly") + .objectStore(DPOP_KEY_STORE_NAME) + .get(DPOP_KEY_ID); + request.addEventListener("error", () => + resume(Effect.fail(dpopError("Could not read the device key.", request.error))), + ); + request.addEventListener("success", () => + resume(Effect.succeed((request.result as StoredDpopKey | undefined) ?? null)), + ); + }), +); + +const writeStoredKey = (key: StoredDpopKey) => + withDatabase((database) => + Effect.callback((resume) => { + const transaction = database.transaction(DPOP_KEY_STORE_NAME, "readwrite"); + transaction.addEventListener("error", () => + resume(Effect.fail(dpopError("Could not write the device key.", transaction.error))), + ); + transaction.addEventListener("complete", () => resume(Effect.void)); + transaction.objectStore(DPOP_KEY_STORE_NAME).put(key, DPOP_KEY_ID); + }), + ); + +const generateKey = Effect.gen(function* () { + const generated = yield* Effect.tryPromise({ + try: () => + crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [ + "sign", + "verify", + ]) as Promise, + catch: (cause) => dpopError("Could not generate the device key.", cause), + }); + const privateJwk = yield* Effect.tryPromise({ + try: () => crypto.subtle.exportKey("jwk", generated.privateKey), + catch: (cause) => dpopError("Could not export the device key.", cause), + }); + const publicJwk = yield* Effect.tryPromise({ + try: () => crypto.subtle.exportKey("jwk", generated.publicKey), + catch: (cause) => dpopError("Could not export the device key.", cause), + }).pipe( + Effect.flatMap((jwk) => + decodePublicJwk({ kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y }).pipe( + Effect.mapError((cause) => dpopError("Generated device key is invalid.", cause)), + ), + ), + ); + // re-imported so the key that gets stored can't be exported + const privateKey = yield* Effect.tryPromise({ + try: () => + crypto.subtle.importKey("jwk", privateJwk, { name: "ECDSA", namedCurve: "P-256" }, false, [ + "sign", + ]), + catch: (cause) => dpopError("Could not import the device key.", cause), + }); + return { privateKey, publicJwk } satisfies StoredDpopKey; +}); + +export const loadOrCreateProofKey = Effect.fn("web.dpop.loadOrCreateProofKey")(function* () { + if (typeof indexedDB === "undefined" || globalThis.crypto?.subtle === undefined) { + return yield* dpopError("This client cannot store a device key."); + } + const signature = yield* Signature.Signature; + const stored = yield* readStoredKey; + const key = stored ?? (yield* generateKey); + if (stored === null) yield* writeStoredKey(key); + const privateKey = yield* Signature.privateKeyFromCryptoKey( + Signature.ecdsaP256, + key.privateKey, + ).pipe(Effect.mapError((cause) => dpopError("Could not load the device key.", cause))); + return { + publicJwk: key.publicJwk, + sign: (signingInput) => + signature + .sign(privateKey, signingInput) + .pipe(Effect.mapError((cause) => dpopError("Could not sign the DPoP proof.", cause))), + } satisfies DpopProof.DpopProofKey; +}); diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index 8d4e3e5803..9e2d1f7d11 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -19,7 +19,7 @@ import { PrimaryConnectionTarget, Wakeups, } from "@t3tools/client-runtime/connection"; -import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization"; +import { bootstrapRemoteBearerSession, DpopProof } from "@t3tools/client-runtime/authorization"; import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment"; import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc"; import { @@ -38,6 +38,7 @@ import * as Stream from "effect/Stream"; import { FetchHttpClient } from "effect/http"; import { APP_VERSION } from "../branding"; +import * as ConnectionDpop from "./dpop"; import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth"; import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer"; import { @@ -569,11 +570,16 @@ const layerRpcRequestObserver = Layer.succeed( }), ); +const layerDpopSigner = DpopProof.layerSigner(ConnectionDpop.loadOrCreateProofKey()).pipe( + Layer.provide(ConnectionDpop.layerCrypto), +); + type ConnectionPlatformLayerSource = | typeof ConnectionStorage.layer | typeof layerConnectivity | typeof layerWakeups | typeof layerCapabilities + | typeof layerDpopSigner | typeof layerPlatformConnectionSource | typeof layerEnvironmentOwnedDataCleanup | typeof layerRpcRequestObserver; @@ -587,6 +593,7 @@ export const layer: Layer.Layer< layerConnectivity, layerWakeups, layerCapabilities, + layerDpopSigner, layerPlatformConnectionSource, layerEnvironmentOwnedDataCleanup, layerRpcRequestObserver, diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md index 61fa5c532c..14c5108a50 100644 --- a/docs/internals/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -25,6 +25,16 @@ DPoP proofs for clients that send them. DPoP binds a token to a client's proof k an invalid proof must fail rather than fall back to bearer authentication. The OAuth token-exchange vocabulary gives these grants a familiar meaning. +A device that exchanges a plain pairing link with a DPoP proof gets a one-hour +token on a session that renews: presenting the token, even expired, with a +proof from the same key moves the session's expiry 30 days out and returns a +fresh token for the same session. The session itself must still be unexpired +and unrevoked, so a device idle past the window pairs again. Renewal stays in place rather than issuing a +successor, so live sockets keep their session, Sharing & access shows one row +per device for its whole renewal window, and one revoke ends it. CLI, +desktop and peer sessions never renew, so rotating their credential still +cuts a device off. + ### MCP clients are a separate audience Agents T3 Code did not launch sign in to `/mcp` through a narrow OAuth diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index d7ba3606d6..8ebc544f0e 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -31,7 +31,10 @@ app link instead. The desktop app asks you to confirm the server address, then adds it. Pairing authorizes that device for future connections. Use a fresh one-time link -for each new device; you do not need the original token to reconnect. Links +for each new device; you do not need the original token to reconnect. A device +stays signed in while you keep using it, until you revoke it in **Settings → +Sharing & access** on the host. One unused for 30 days, or paired with a host +older than this release, has to pair again. Links created in Settings can only be copied from the client that created them while its Sharing & access page stays open. If you leave or reload that page, create another link to share. diff --git a/packages/client-runtime/src/authorization/dpopProof.ts b/packages/client-runtime/src/authorization/dpopProof.ts new file mode 100644 index 0000000000..039b43cbf6 --- /dev/null +++ b/packages/client-runtime/src/authorization/dpopProof.ts @@ -0,0 +1,97 @@ +// packages/client-runtime/src/authorization/dpopProof.ts +// signs RFC 9449 DPoP proofs w/ a key each client platform keeps on its device +import { normalizeDpopHtu, type DpopPublicJwk } from "@t3tools/shared/dpopCommon"; +import * as Cache from "effect/Cache"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +export class DpopProofError extends Schema.TaggedError()("DpopProofError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} + +/** A P-256 proof key. `sign` returns the raw `r||s` ES256 signature over the JWS signing input. */ +export interface DpopProofKey { + readonly publicJwk: DpopPublicJwk; + readonly sign: (signingInput: Uint8Array) => Effect.Effect; +} + +export interface DpopProofRequest { + readonly method: string; + readonly url: string; + readonly accessToken?: string | undefined; +} + +/** Signs proofs with this device's key, so a client without one can fall back to bearer. */ +export class DpopSigner extends Context.Service< + DpopSigner, + { + readonly createProof: (input: DpopProofRequest) => Effect.Effect; + } +>()("@t3tools/client-runtime/authorization/dpopProof/DpopSigner") {} + +const utf8 = (value: string) => new TextEncoder().encode(value); +const encodeSegment = (value: unknown) => Base64Url.encode(utf8(JSON.stringify(value))); + +const sha256Base64Url = (data: Uint8Array) => + Effect.flatMap(Digest.Digest, (digest) => digest.digest(Digest.sha256, data)).pipe( + Effect.map(Base64Url.encode), + ); + +const createProof = Effect.fn("DpopProof.createProof")(function* ( + input: DpopProofRequest & { readonly key: DpopProofKey }, +) { + const htu = normalizeDpopHtu(input.url); + if (htu === null) return yield* new DpopProofError({ message: "DPoP URL is invalid." }); + const random = yield* SecureRandom.SecureRandom; + const header = encodeSegment({ typ: "dpop+jwt", alg: "ES256", jwk: input.key.publicJwk }); + const payload = encodeSegment({ + htm: input.method.toUpperCase(), + htu, + jti: yield* random.uuidV4(), + iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000), + ...(input.accessToken ? { ath: yield* sha256Base64Url(utf8(input.accessToken)) } : {}), + }); + const signature = yield* input.key.sign(utf8(`${header}.${payload}`)); + return `${header}.${payload}.${Base64Url.encode(signature)}`; +}); + +// loads the key once & keeps it, while a failed load (like a locked keychain) retries +export const layerSigner = (loadOrCreateKey: Effect.Effect) => + Layer.effect( + DpopSigner, + Effect.gen(function* () { + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; + const context = yield* Effect.context(); + const keyCache = yield* Cache.makeWith( + () => loadOrCreateKey.pipe(Effect.provideContext(context)), + { + capacity: 1, + timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero), + }, + ); + const loadKey = Cache.get(keyCache, undefined); + return DpopSigner.of({ + createProof: Effect.fn("DpopSigner.createProof")(function* (input) { + const key = yield* loadKey.pipe( + Effect.mapError( + (cause) => new DpopProofError({ message: "Could not load the device key.", cause }), + ), + ); + return yield* createProof({ ...input, key }).pipe( + Effect.provideService(SecureRandom.SecureRandom, random), + Effect.provideService(Digest.Digest, digest), + ); + }), + }); + }), + ); diff --git a/packages/client-runtime/src/authorization/index.ts b/packages/client-runtime/src/authorization/index.ts index ba63bca275..51455aab24 100644 --- a/packages/client-runtime/src/authorization/index.ts +++ b/packages/client-runtime/src/authorization/index.ts @@ -1,2 +1,3 @@ +export * as DpopProof from "./dpopProof.ts"; export * from "./remote.ts"; export { type AuthorizedRemoteEnvironment } from "./service.ts"; diff --git a/packages/client-runtime/src/authorization/layer.test.ts b/packages/client-runtime/src/authorization/layer.test.ts index c72239abdd..d860b76ad6 100644 --- a/packages/client-runtime/src/authorization/layer.test.ts +++ b/packages/client-runtime/src/authorization/layer.test.ts @@ -67,6 +67,7 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* ( const layer = RemoteEnvironmentAuthorization.layer.pipe( Layer.provideMerge( Layer.mergeAll( + ConnectionCredentialStore.layerMemory(), RpcHttp.layerRemoteHttpClient(fetch.fetchFn), Layer.succeed( ClientCapabilities.ClientPresentation, diff --git a/packages/client-runtime/src/authorization/remote.ts b/packages/client-runtime/src/authorization/remote.ts index 4526a62184..05dd21f391 100644 --- a/packages/client-runtime/src/authorization/remote.ts +++ b/packages/client-runtime/src/authorization/remote.ts @@ -51,6 +51,78 @@ export const appendClientConnectionParams = ( } }; +export const exchangeRemoteDpopAccessToken = Effect.fn( + "clientRuntime.authorization.exchangeRemoteDpopAccessToken", +)(function* (input: { + readonly httpBaseUrl: string; + readonly credential: string; + /** An access token renews its own session on hosts that advertise `accessTokenRenewal`. */ + readonly credentialType?: typeof AuthEnvironmentBootstrapTokenType | typeof AuthAccessTokenType; + readonly scopes?: ReadonlyArray; + readonly clientMetadata?: AuthClientPresentationMetadata; + readonly dpopProof: string; + readonly timeoutMs?: number; +}) { + const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth"); + const response = yield* executeEnvironmentHttpRequest( + environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"), + input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS, + client.token({ + headers: { dpop: input.dpopProof }, + payload: { + grant_type: AuthTokenExchangeGrantType, + subject_token: input.credential, + subject_token_type: input.credentialType ?? AuthEnvironmentBootstrapTokenType, + requested_token_type: AuthAccessTokenType, + ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}), + ...clientMetadataTokenExchangeFields(input.clientMetadata), + }, + }), + ); + return response; +}); + +export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn( + "clientRuntime.authorization.resolveRemoteDpopWebSocketConnectionUrl", +)(function* (input: { + readonly wsBaseUrl: string; + readonly httpBaseUrl: string; + readonly accessToken: string; + readonly createProof: (input: { + readonly method: "GET" | "POST"; + readonly url: string; + readonly accessToken: string; + }) => Effect.Effect; + readonly clientMetadata?: AuthClientPresentationMetadata; + readonly timeoutMs?: number; +}) { + const ticketUrl = environmentEndpointUrl(input.httpBaseUrl, webSocketTicketPath("rpc")); + const dpop = yield* input.createProof({ + method: "POST", + url: ticketUrl, + accessToken: input.accessToken, + }); + const client = yield* makeEnvironmentHttpApiGroupClient(input.httpBaseUrl, "auth"); + const issued = yield* executeEnvironmentHttpRequest( + ticketUrl, + input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS, + client.webSocketTicketFor({ + headers: { authorization: `DPoP ${input.accessToken}`, dpop }, + params: { use: "rpc" }, + }), + ); + const url = rpcSocketUrl(input.wsBaseUrl); + const upgradeProof = yield* input.createProof({ + method: "GET", + url: `${url.protocol === "wss:" ? "https:" : "http:"}//${url.host}${url.pathname}`, + accessToken: Redacted.value(issued.ticket), + }); + url.searchParams.set("wsTicket", Redacted.value(issued.ticket)); + url.searchParams.set("dpop", upgradeProof); + appendClientConnectionParams(url, input.clientMetadata); + return url.toString(); +}); + export const bootstrapRemoteBearerSession = Effect.fn( "clientRuntime.authorization.bootstrapRemoteBearerSession", )(function* (input: { diff --git a/packages/client-runtime/src/authorization/service.ts b/packages/client-runtime/src/authorization/service.ts index 7bbe97c1dc..d85e594109 100644 --- a/packages/client-runtime/src/authorization/service.ts +++ b/packages/client-runtime/src/authorization/service.ts @@ -1,21 +1,43 @@ // packages/client-runtime/src/authorization/service.ts // authorizes remote environments with bearer tokens import { + AuthAccessTokenType, type ClientConnectionMethod, EnvironmentId, type ExecutionEnvironmentDescriptor, } from "@t3tools/contracts"; -import { resolveRemoteWebSocketConnectionUrl } from "./remote.ts"; -import { environmentMismatchError, mapRemoteEnvironmentError } from "../connection/errors.ts"; -import type { ConnectionAttemptError, PreparedHttpAuthorization } from "../connection/model.ts"; +import * as KeyedLock from "@t3tools/shared/KeyedLock"; +import * as DpopProof from "./dpopProof.ts"; +import { + exchangeRemoteDpopAccessToken, + resolveRemoteDpopWebSocketConnectionUrl, + resolveRemoteWebSocketConnectionUrl, +} from "./remote.ts"; +import { DpopConnectionCredential } from "../connection/catalog.ts"; +import * as ConnectionCredentialStore from "../connection/credentialStore.ts"; +import { + credentialMissingError, + environmentMismatchError, + mapRemoteEnvironmentError, +} from "../connection/errors.ts"; +import { + ConnectionBlockedError, + DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS, + type ConnectionAttemptError, + type DirectDpopConnection, + type DpopHttpAuthorization, + type PreparedHttpAuthorization, +} from "../connection/model.ts"; import { isNearbyAddress } from "../connection/routes.ts"; import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts"; +import { environmentEndpointUrl } from "../environment/endpoint.ts"; import * as ClientCapabilities from "../platform/capabilities.ts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import * as HttpClient from "effect/http/HttpClient"; export interface AuthorizedRemoteEnvironment { @@ -37,6 +59,13 @@ export class RemoteEnvironmentAuthorization extends Context.Service< readonly bearerToken: string; readonly connectionMethod: ClientConnectionMethod; }) => Effect.Effect; + /** A saved address paired with this device's DPoP key, which renews with the host itself. */ + readonly authorizeDirectDpop: (input: { + readonly expectedEnvironmentId: EnvironmentId; + readonly connectionId: string; + readonly httpBaseUrl: string; + readonly wsBaseUrl: string; + }) => Effect.Effect; /** * Lets the next direct authorization of this address skip its own descriptor * read. Kept only where the address reaches the same machine on every network. @@ -67,6 +96,9 @@ const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescript const make = Effect.gen(function* () { const presentation = yield* ClientCapabilities.ClientPresentation; const httpClient = yield* HttpClient.HttpClient; + const signer = yield* Effect.serviceOption(DpopProof.DpopSigner); + const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore; + const directTokenLocks = yield* KeyedLock.make(); // A route or host check hands its descriptor to the connect it leads to, once, // so the connect skips a round trip. Only over HTTPS or loopback: any other @@ -145,8 +177,151 @@ const make = Effect.gen(function* () { }, ); + const createProof = (proof: DpopProof.DpopProofRequest) => + Option.isNone(signer) + ? Effect.fail( + new ConnectionBlockedError({ + reason: "configuration", + detail: "This client cannot sign with a device key.", + }), + ) + : signer.value.createProof(proof).pipe( + Effect.mapError( + () => + new ConnectionBlockedError({ + reason: "configuration", + detail: "Could not create the environment authorization proof.", + }), + ), + ); + + // requests for one credential share a renewal w/o waiting on other hosts + const directDpopToken = Effect.fn("clientRuntime.connection.remote.directDpopToken")(function* ( + connection: DirectDpopConnection, + rejectedAccessToken?: string, + ) { + return yield* directTokenLocks.withLock( + connection.connectionId, + Effect.gen(function* () { + const stored = yield* credentials.get(connection.connectionId); + if (Option.isNone(stored) || stored.value._tag !== "DpopConnectionCredential") { + return yield* credentialMissingError(connection.connectionId); + } + const current = stored.value; + const now = yield* Clock.currentTimeMillis; + if ( + current.accessToken !== rejectedAccessToken && + current.expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS > now + ) { + return current; + } + const dpopProof = yield* createProof({ + method: "POST", + url: environmentEndpointUrl(connection.httpBaseUrl, "/oauth/token"), + }); + const access = yield* exchangeRemoteDpopAccessToken({ + httpBaseUrl: connection.httpBaseUrl, + credential: current.accessToken, + credentialType: AuthAccessTokenType, + dpopProof, + }).pipe( + Effect.mapError((error) => mapRemoteEnvironmentError(error, "direct")), + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.withSpan("environment.authorization.directRenewal"), + ); + const renewed = new DpopConnectionCredential({ + accessToken: access.access_token, + expiresAtEpochMs: (yield* Clock.currentTimeMillis) + access.expires_in * 1_000, + }); + yield* credentials.put(connection.connectionId, renewed); + return renewed; + }), + ); + }); + + // untraced since a span here would stay open for the socket's lifetime + const renewDirectDpopBeforeExpiry = Effect.fnUntraced(function* ( + connection: DirectDpopConnection, + initialExpiresAtEpochMs: number, + ) { + let expiresAtEpochMs = initialExpiresAtEpochMs; + while (true) { + const now = yield* Clock.currentTimeMillis; + // the floor spaces out retries & keeps a wall-clock jump from spinning + const floor = now < expiresAtEpochMs ? 5_000 : DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS; + yield* Effect.sleep( + Math.max(floor, expiresAtEpochMs - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS - now), + ); + const renewed = yield* directDpopToken(connection).pipe( + Effect.map((credential) => credential.expiresAtEpochMs), + Effect.withSpan("environment.authorization.renewSocket"), + Effect.catchTags({ ConnectionTransientError: () => Effect.succeed(expiresAtEpochMs) }), + ); + expiresAtEpochMs = Math.max(expiresAtEpochMs, renewed); + } + }); + + const directHttpAuthorization = ( + connection: DirectDpopConnection, + credential: DpopConnectionCredential, + ): DpopHttpAuthorization => ({ + _tag: "Dpop", + accessToken: credential.accessToken, + expiresAtEpochMs: credential.expiresAtEpochMs, + directConnection: connection, + current: (rejectedAccessToken) => + directDpopToken(connection, rejectedAccessToken).pipe( + Effect.map((renewed) => directHttpAuthorization(connection, renewed)), + ), + createProof, + renewBeforeExpiry: renewDirectDpopBeforeExpiry(connection, credential.expiresAtEpochMs), + }); + + const authorizeDirectDpop = Effect.fn("clientRuntime.connection.remote.authorizeDirectDpop")( + function* ( + input: Parameters[0], + ) { + const descriptor = yield* verifyDirectEndpoint({ + expectedEnvironmentId: input.expectedEnvironmentId, + httpBaseUrl: input.httpBaseUrl, + connectionMethod: "direct", + }); + const connection = { connectionId: input.connectionId, httpBaseUrl: input.httpBaseUrl }; + const openSocket = (credential: DpopConnectionCredential) => + resolveRemoteDpopWebSocketConnectionUrl({ + wsBaseUrl: input.wsBaseUrl, + httpBaseUrl: input.httpBaseUrl, + accessToken: credential.accessToken, + createProof, + clientMetadata: presentation.metadata, + }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.result); + let credential = yield* directDpopToken(connection); + let socket = yield* openSocket(credential); + // a token the host refuses before its expiry, like after a clock jump, renews once + if (Result.isFailure(socket) && socket.failure._tag === "EnvironmentAuthInvalidError") { + credential = yield* directDpopToken(connection, credential.accessToken); + socket = yield* openSocket(credential); + } + if (Result.isFailure(socket)) { + const failure = socket.failure; + return yield* failure._tag === "ConnectionBlockedError" + ? failure + : mapRemoteEnvironmentError(failure, "direct"); + } + return { + environmentId: descriptor.environmentId, + label: descriptor.label, + httpBaseUrl: input.httpBaseUrl, + socketUrl: socket.success, + descriptor, + httpAuthorization: directHttpAuthorization(connection, credential), + }; + }, + ); + return RemoteEnvironmentAuthorization.of({ authorizeBearer, + authorizeDirectDpop, // Untraced: it runs on every route and host check. rememberCheckedDescriptor: Effect.fnUntraced(function* (httpBaseUrl, descriptor, keepsItsHost) { if (Option.isNone(descriptor) || !keepsItsHost) { diff --git a/packages/client-runtime/src/connection/catalog.ts b/packages/client-runtime/src/connection/catalog.ts index cb3ec9b61a..7d2ee76976 100644 --- a/packages/client-runtime/src/connection/catalog.ts +++ b/packages/client-runtime/src/connection/catalog.ts @@ -49,7 +49,19 @@ export class BearerConnectionCredential extends Schema.TaggedClass()( + "DpopConnectionCredential", + { + accessToken: Schema.String, + expiresAtEpochMs: Schema.Number, + }, +) {} + +export const ConnectionCredential = Schema.Union([ + BearerConnectionCredential, + DpopConnectionCredential, +]); export type ConnectionCredential = typeof ConnectionCredential.Type; export class PrimaryConnectionRegistration extends Schema.TaggedClass()( @@ -64,7 +76,7 @@ export class BearerConnectionRegistration extends Schema.TaggedClass ConnectionCredentialStore.of(service); + +/** A store that lives only as long as its layer, for tests and other throwaway runtimes. */ +export const layerMemory = (initial: Iterable = []) => + Layer.sync(ConnectionCredentialStore, () => { + const stored = new Map(initial); + return make({ + get: (connectionId) => Effect.sync(() => Option.fromNullishOr(stored.get(connectionId))), + put: (connectionId, credential) => + Effect.sync(() => void stored.set(connectionId, credential)), + remove: (connectionId) => Effect.sync(() => void stored.delete(connectionId)), + }); + }); diff --git a/packages/client-runtime/src/connection/driver.ts b/packages/client-runtime/src/connection/driver.ts index 265c16e7f6..f1c73aa5fd 100644 --- a/packages/client-runtime/src/connection/driver.ts +++ b/packages/client-runtime/src/connection/driver.ts @@ -212,6 +212,15 @@ export const make = Effect.gen(function* () { const session = yield* sessions.connect(prepared); yield* reportProgress({ stage: "synchronizing", prepared }); yield* session.ready; + // the server closes a socket when its session expires unless the same key renewed it + if (prepared.httpAuthorization?._tag === "Dpop") { + yield* prepared.httpAuthorization.renewBeforeExpiry.pipe( + Effect.catch((error) => + Effect.logWarning("Could not renew the connection's credential.", { error }), + ), + Effect.forkScoped, + ); + } return { prepared, session } satisfies EnvironmentConnectionLease; }), ); diff --git a/packages/client-runtime/src/connection/model.ts b/packages/client-runtime/src/connection/model.ts index 9133719a41..be1375a7d4 100644 --- a/packages/client-runtime/src/connection/model.ts +++ b/packages/client-runtime/src/connection/model.ts @@ -1,4 +1,5 @@ import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import type * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; const ConnectionTargetBase = { @@ -116,9 +117,47 @@ export class ConnectionBlockedError extends Schema.TaggedError Effect.Effect; + readonly createProof: (input: { + readonly method: string; + readonly url: string; + readonly accessToken: string; + }) => Effect.Effect; + /** Keeps a live socket's session renewed until interrupted or its credential is refused. */ + readonly renewBeforeExpiry: Effect.Effect; +} + +export type PreparedHttpAuthorization = + | { + readonly _tag: "Bearer"; + readonly token: string; + } + | DpopHttpAuthorization; + +export interface DirectDpopConnection { + /** The credential store key. */ + readonly connectionId: string; + readonly httpBaseUrl: string; } export interface PreparedConnection { diff --git a/packages/client-runtime/src/connection/onboarding.test.ts b/packages/client-runtime/src/connection/onboarding.test.ts index 84ca1152db..8333e32b66 100644 --- a/packages/client-runtime/src/connection/onboarding.test.ts +++ b/packages/client-runtime/src/connection/onboarding.test.ts @@ -4,7 +4,7 @@ import { type AuthEnvironmentScope, ORCHESTRATION_PROTOCOL_VERSION, } from "@t3tools/contracts"; -import { describe, expect, it } from "@effect/vitest"; +import { assert, describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -14,6 +14,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import * as RpcHttp from "../rpc/http.ts"; import * as ClientCapabilities from "../platform/capabilities.ts"; +import * as DpopProof from "../authorization/dpopProof.ts"; import * as Persistence from "../platform/persistence.ts"; import { fetchRemoteSessionState } from "../authorization/remote.ts"; import { @@ -57,6 +58,7 @@ function layerPairingHttp( readonly selfUpdate?: boolean; readonly grantScopes?: ReadonlyArray; readonly exchangeGate?: { readonly reached: () => void; readonly release: Promise }; + readonly accessTokenRenewal?: boolean; }, ) { const grantScopes = options?.grantScopes ?? AuthStandardClientScopes; @@ -84,6 +86,7 @@ function layerPairingHttp( capabilities: { repositoryIdentity: true, ...(options?.selfUpdate === true ? { serverSelfUpdate: "boot-service" } : {}), + ...(options?.accessTokenRenewal === true ? { accessTokenRenewal: true } : {}), }, }), ); @@ -120,10 +123,11 @@ function layerPairingHttp( ), ); } + const dpop = new Headers(init.headers).has("dpop"); const granted = Response.json({ - access_token: "bearer-token", + access_token: dpop ? "dpop-token" : "bearer-token", issued_token_type: "urn:ietf:params:oauth:token-type:access_token", - token_type: "Bearer", + token_type: dpop ? "DPoP" : "Bearer", expires_in: 3600, scope: sessionScopes.join(" "), }); @@ -505,6 +509,7 @@ describe("connection onboarding", () => { pairingCode: "pairing-token", }); + assert(registration.credential._tag === "BearerConnectionCredential"); const session = yield* fetchRemoteSessionState({ httpBaseUrl: registration.profile.httpBaseUrl, bearerToken: registration.credential.token, @@ -515,6 +520,38 @@ describe("connection onboarding", () => { }).pipe(Effect.provide(layerPairingOnboarding({ grantScopes: scopes }))), ); + it.effect.each([ + { name: "a host that renews, with a device key", renews: true, signer: true, dpop: true }, + { name: "a host that renews, without a device key", renews: true, signer: false, dpop: false }, + { name: "an older host, with a device key", renews: false, signer: true, dpop: false }, + ])("pairs with $name as DPoP: $dpop", ({ renews, signer, dpop }) => + Effect.gen(function* () { + const registration = yield* preparePairingRegistration({ + host: "remote.example.test", + pairingCode: "pairing-token", + }); + expect(registration.credential).toMatchObject( + dpop + ? { _tag: "DpopConnectionCredential", accessToken: "dpop-token" } + : { _tag: "BearerConnectionCredential", token: "bearer-token" }, + ); + }).pipe( + Effect.provide( + Layer.merge( + layerPairingOnboarding({ accessTokenRenewal: renews }), + signer + ? Layer.succeed( + DpopProof.DpopSigner, + DpopProof.DpopSigner.of({ + createProof: (proof) => Effect.succeed(`proof:${proof.url}`), + }), + ) + : Layer.empty, + ), + ), + ), + ); + it.effect("refuses to add a route that reaches a different machine, keeping the code", () => Effect.gen(function* () { const calls: Array<{ readonly url: string; readonly init: RequestInit }> = []; diff --git a/packages/client-runtime/src/connection/onboarding.ts b/packages/client-runtime/src/connection/onboarding.ts index d17e8439af..52c98f4e9d 100644 --- a/packages/client-runtime/src/connection/onboarding.ts +++ b/packages/client-runtime/src/connection/onboarding.ts @@ -1,5 +1,6 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { resolveRemotePairingTarget } from "@t3tools/shared/remote"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -8,16 +9,25 @@ import * as Schema from "effect/Schema"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as HttpClient from "effect/http/HttpClient"; -import { bootstrapRemoteBearerSession } from "../authorization/remote.ts"; -import { deriveWsBaseUrl, normalizeHttpBaseUrl } from "../environment/endpoint.ts"; +import { + bootstrapRemoteBearerSession, + exchangeRemoteDpopAccessToken, +} from "../authorization/remote.ts"; +import { + deriveWsBaseUrl, + environmentEndpointUrl, + normalizeHttpBaseUrl, +} from "../environment/endpoint.ts"; import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts"; import * as ClientCapabilities from "../platform/capabilities.ts"; +import * as DpopProof from "../authorization/dpopProof.ts"; import { BearerConnectionCredential, BearerConnectionProfile, BearerConnectionRegistration, type ConnectionCatalogEntry, type ConnectionCredential, + DpopConnectionCredential, } from "./catalog.ts"; import * as ConnectionCredentialStore from "./credentialStore.ts"; import { mapRemoteEnvironmentError } from "./errors.ts"; @@ -123,6 +133,33 @@ export const preparePairingRegistration = Effect.fn( if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) { return yield* compatibilityError; } + // A key-bound session renews itself, but only on a host that can renew it. The proof is made + // before the one-time code is sent, so a device that cannot sign keeps the code for bearer. + const signer = yield* Effect.serviceOption(DpopProof.DpopSigner); + const dpopProof = + descriptor.capabilities.accessTokenRenewal === true && Option.isSome(signer) + ? yield* signer.value + .createProof({ + method: "POST", + url: environmentEndpointUrl(target.httpBaseUrl, "/oauth/token"), + }) + .pipe(Effect.option) + : Option.none(); + if (Option.isSome(dpopProof)) { + const access = yield* exchangeRemoteDpopAccessToken({ + httpBaseUrl: target.httpBaseUrl, + credential: target.credential, + clientMetadata: presentation.metadata, + dpopProof: dpopProof.value, + }).pipe(Effect.mapError(mapRemoteEnvironmentError)); + return new BearerConnectionRegistration({ + ...route, + credential: new DpopConnectionCredential({ + accessToken: access.access_token, + expiresAtEpochMs: (yield* Clock.currentTimeMillis) + access.expires_in * 1_000, + }), + }); + } const access = yield* bootstrapRemoteBearerSession({ httpBaseUrl: target.httpBaseUrl, credential: target.credential, @@ -153,7 +190,6 @@ const registerPairingConnection = Effect.fn( return registration.target.environmentId; }); -const isBearerCredential = Schema.is(BearerConnectionCredential); const isBearerProfile = Schema.is(BearerConnectionProfile); const updateBearerConnection = Effect.fn( @@ -203,7 +239,7 @@ export const prepareBearerConnectionUpdate = Effect.fn( } const credential = options.credential; - if (Option.isNone(credential) || !isBearerCredential(credential.value)) { + if (Option.isNone(credential)) { return yield* new ConnectionBlockedError({ reason: "authentication", detail: "The saved bearer credential is unavailable.", diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts index 83cde723f8..a9ecb6d857 100644 --- a/packages/client-runtime/src/connection/registry.test.ts +++ b/packages/client-runtime/src/connection/registry.test.ts @@ -326,9 +326,10 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( ...PREPARED, environmentId: target.environmentId, label: target.label, - httpAuthorization: Option.isSome(credential) - ? { _tag: "Bearer", token: credential.value.token } - : null, + httpAuthorization: + Option.isSome(credential) && credential.value._tag === "BearerConnectionCredential" + ? { _tag: "Bearer", token: credential.value.token } + : null, target, }; if (options?.prepareError) return yield* options.prepareError; @@ -976,11 +977,13 @@ describe("EnvironmentRegistry", () => { target._tag !== "BearerConnectionTarget" || storedCredentials === undefined ? Effect.undefined : Ref.get(storedCredentials).pipe( - Effect.map((current) => - current.get(target.connectionId)?.token === "old-bearer" + Effect.map((current) => { + const stored = current.get(target.connectionId); + return stored?._tag === "BearerConnectionCredential" && + stored.token === "old-bearer" ? new ConnectionBlockedError({ reason: "authentication", detail: "revoked" }) - : undefined, - ), + : undefined; + }), ), }); storedCredentials = harness.storedCredentials; diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.ts index 30ca2eea40..07263fc688 100644 --- a/packages/client-runtime/src/connection/registry.ts +++ b/packages/client-runtime/src/connection/registry.ts @@ -708,7 +708,11 @@ export const make = Effect.gen(function* () { yield* installEntryLocked(entry, { retainEquivalentRuntime: true }); - if (bearerReplaced && registration._tag === "BearerConnectionRegistration") { + if ( + bearerReplaced && + registration._tag === "BearerConnectionRegistration" && + registration.credential._tag === "BearerConnectionCredential" + ) { const scope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId); if (scope !== undefined) { const state = yield* SubscriptionRef.get(scope.supervisor.state); diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.ts index 4a4bf7e183..ea2e8ee646 100644 --- a/packages/client-runtime/src/connection/resolver.test.ts +++ b/packages/client-runtime/src/connection/resolver.test.ts @@ -52,6 +52,7 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o remove: (connectionId) => Effect.sync(() => void credentials.delete(connectionId)), }); const remote = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({ + authorizeDirectDpop: () => Effect.die("unused"), authorizeBearer: options?.authorizeBearer ?? ((input) => diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.ts index 50b96cc235..cc55ad3377 100644 --- a/packages/client-runtime/src/connection/resolver.ts +++ b/packages/client-runtime/src/connection/resolver.ts @@ -14,11 +14,7 @@ import * as HttpClient from "effect/http/HttpClient"; import { appendClientConnectionParams } from "../authorization/remote.ts"; import * as RemoteEnvironmentAuthorization from "../authorization/service.ts"; import * as ClientCapabilities from "../platform/capabilities.ts"; -import { - BearerConnectionCredential, - BearerConnectionProfile, - type ConnectionCatalogEntry, -} from "./catalog.ts"; +import { BearerConnectionProfile, type ConnectionCatalogEntry } from "./catalog.ts"; import * as ConnectionCredentialStore from "./credentialStore.ts"; import { credentialMissingError, @@ -61,7 +57,6 @@ export class ConnectionResolver extends Context.Service< >()("@t3tools/client-runtime/connection/resolver/ConnectionResolver") {} const isBearerProfile = Schema.is(BearerConnectionProfile); -const isBearerCredential = Schema.is(BearerConnectionCredential); function primarySocketUrl( target: PrimaryConnectionTarget, @@ -140,16 +135,21 @@ const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer") }), ), ); - if (!isBearerCredential(credential)) { - return yield* credentialMissingError(target.connectionId); - } - const authorized = yield* remote.authorizeBearer({ - expectedEnvironmentId: target.environmentId, - httpBaseUrl: profile.httpBaseUrl, - wsBaseUrl: profile.wsBaseUrl, - bearerToken: credential.token, - connectionMethod: "direct", - }); + const authorized = + credential._tag === "DpopConnectionCredential" + ? yield* remote.authorizeDirectDpop({ + expectedEnvironmentId: target.environmentId, + connectionId: credentialConnectionId(target.connectionId), + httpBaseUrl: profile.httpBaseUrl, + wsBaseUrl: profile.wsBaseUrl, + }) + : yield* remote.authorizeBearer({ + expectedEnvironmentId: target.environmentId, + httpBaseUrl: profile.httpBaseUrl, + wsBaseUrl: profile.wsBaseUrl, + bearerToken: credential.token, + connectionMethod: "direct", + }); return { ...authorized, target, diff --git a/packages/client-runtime/src/state/environmentHttpAuth.ts b/packages/client-runtime/src/state/environmentHttpAuth.ts index 1ae4274cf9..250c18f709 100644 --- a/packages/client-runtime/src/state/environmentHttpAuth.ts +++ b/packages/client-runtime/src/state/environmentHttpAuth.ts @@ -2,6 +2,7 @@ // authenticates environment requests without sharing upstream traces import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { ORCHESTRATION_PROTOCOL_HEADER, @@ -22,6 +23,7 @@ import { export interface EnvironmentHttpAuthHeaders { readonly authorization?: string; + readonly dpop?: string; } export function withOrchestrationProtocolHeader( @@ -53,10 +55,25 @@ const withEnvironmentRequestInit = ( ); }; -const environmentAuthHeaders = ( +const environmentAuthHeaders = Effect.fnUntraced(function* ( authorization: PreparedHttpAuthorization | null, -): EnvironmentHttpAuthHeaders => - authorization === null ? {} : { authorization: `Bearer ${authorization.token}` }; + method: HttpMethod.HttpMethod, + url: string, +) { + if (authorization === null) return {} satisfies EnvironmentHttpAuthHeaders; + if (authorization._tag === "Bearer") { + return { authorization: `Bearer ${authorization.token}` } satisfies EnvironmentHttpAuthHeaders; + } + const dpop = yield* authorization.createProof({ + method, + url, + accessToken: authorization.accessToken, + }); + return { + authorization: `DPoP ${authorization.accessToken}`, + dpop, + } satisfies EnvironmentHttpAuthHeaders; +}); export const executeAuthenticatedEnvironmentHttpRequest = Effect.fn( "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest", @@ -84,18 +101,45 @@ export const executeAuthenticatedEnvironmentHttpRequest = Effect.fn( Effect.Services>> | R > { const httpBaseUrl = input.prepared.httpBaseUrl; - const authorization = input.prepared.httpAuthorization; const requestUrl = input.url(makeEnvironmentHttpApiUrlBuilder(httpBaseUrl)[input.group]); const client = yield* makeEnvironmentHttpApiGroupClient(httpBaseUrl, input.group); - return yield* executeEnvironmentHttpRequest( - requestUrl, - input.timeoutMs, - withEnvironmentRequestInit( - authorization, - input.requestInit, - input.request({ client, headers: environmentAuthHeaders(authorization) }), - ), - ).pipe( + const authFetchError = (cause: unknown) => + new RemoteEnvironmentAuthFetchError({ + message: "Could not authorize the environment request.", + cause, + }); + const send = Effect.fnUntraced(function* (authorization: PreparedHttpAuthorization | null) { + const headers = yield* environmentAuthHeaders(authorization, input.method, requestUrl).pipe( + Effect.mapError(authFetchError), + ); + return yield* executeEnvironmentHttpRequest( + requestUrl, + input.timeoutMs, + withEnvironmentRequestInit( + authorization, + input.requestInit, + input.request({ client, headers }), + ), + ); + }); + return yield* Effect.gen(function* () { + const prepared = input.prepared.httpAuthorization; + if (prepared?._tag !== "Dpop") return yield* send(prepared); + const current = yield* prepared.current().pipe(Effect.mapError(authFetchError)); + const first = yield* send(current).pipe(Effect.result); + if (Result.isSuccess(first)) return first.success; + if ( + first.failure._tag !== "EnvironmentAuthInvalidError" || + first.failure.reason !== "invalid_credential" + ) { + return yield* first.failure; + } + // a token refused before its expiry, like after a clock jump, renews once + const renewed = yield* prepared + .current(current.accessToken) + .pipe(Effect.mapError(authFetchError)); + return yield* send(renewed); + }).pipe( Effect.timeoutOrElse({ duration: input.timeoutMs, orElse: () => diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index daa860ae82..5a2c76c4e4 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -216,7 +216,8 @@ export type AuthClientPresentationMetadata = typeof AuthClientPresentationMetada export const AuthTokenExchangeRequest = Schema.Struct({ grant_type: Schema.Literal(AuthTokenExchangeGrantType), subject_token: TrimmedNonEmptyString, - subject_token_type: Schema.Literal(AuthEnvironmentBootstrapTokenType), + /** An access token renews its own session, with a DPoP proof from the key it is bound to. */ + subject_token_type: Schema.Literals([AuthEnvironmentBootstrapTokenType, AuthAccessTokenType]), requested_token_type: Schema.Literal(AuthAccessTokenType), scope: Schema.optionalKey(TrimmedNonEmptyString), client_label: Schema.optionalKey(TrimmedNonEmptyString), diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index ade55bf927..d1caa252ed 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -87,6 +87,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ cartographer: Schema.optionalKey(Schema.Boolean), repositoryIdentity: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), connectionProbe: Schema.optionalKey(Schema.Boolean), + /** A DPoP session from a pairing link renews at /oauth/token; pair with a bearer where absent. */ + accessTokenRenewal: Schema.optionalKey(Schema.Boolean), attachmentUploads: Schema.optionalKey(Schema.Boolean), questionAttachments: Schema.optionalKey(Schema.Boolean), fileAttachments: Schema.optionalKey(