Compare commits

...
Author SHA1 Message Date
Julius Marminge e9b6980ced Add device-login tip to T3 Connect auth prompt
- Update the OAuth console message to mention `t3 connect login --device`
- Improve guidance for headless and remote machines
2026-07-06 23:32:24 -07:00
Julius Marminge 87c028fd05 Harden device login flow against transient relay failures
- Retry device authorization issuance on unique-code collisions
- Validate relay device/login payload sizes up front
- Keep polling and cleanup resilient to transient transport failures
2026-07-06 23:20:46 -07:00
Julius Marminge ebaeee9339 Harden device login flow and relay config
- Preserve device auth timeout errors and guard against stale lookup results
- Add relay device authorization schema and tighten stage-specific base URL defaults
2026-07-06 22:49:07 -07:00
Julius Marminge aa17397149 Document device-code login relay configuration
- Describe the new `t3 connect login --device` flow
- Add `T3CODE_APP_BASE_URL` guidance for relay stages
- Update relay README and Clerk setup docs
2026-07-06 22:29:31 -07:00
Julius Marminge e369795c4f Preserve device login return URL
- Open Clerk sign-in with the current page as the forced redirect URL
- Keep the device authorization flow returning users to where they started
2026-07-06 22:23:50 -07:00
Julius Marminge 560646c97e Add device login flow for T3 Connect
- Add device-code CLI login for headless machines
- Add relay and web approval/callback surfaces
- Update shared relay contracts and tests
2026-07-06 22:19:54 -07:00
36 changed files with 3699 additions and 26 deletions

No files matched your search

@@ -148,6 +148,10 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}).`;
case "RelayDeviceTokenPollError":
return `Relay rejected the device authorization poll (${error.code}).`;
case "RelayDeviceAuthorizationNotFoundError":
return "Relay could not find the device authorization.";
}
}
+9 -1
View File
@@ -350,8 +350,16 @@ const runCloudCommand = <A, E>(
return yield* run.pipe(Effect.provide(runtimeLayer));
});
const deviceLoginFlag = Flag.boolean("device").pipe(
Flag.withDescription(
"Sign in with a device code approved from another browser (for SSH and headless machines).",
),
Flag.withDefault(false),
);
const connectLoginCommand = Command.make("login", {
...projectLocationFlags,
device: deviceLoginFlag,
}).pipe(
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
Command.withHandler((flags) =>
@@ -359,7 +367,7 @@ const connectLoginCommand = Command.make("login", {
flags,
Effect.gen(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* flags.device ? tokens.getWithDeviceLogin : tokens.get;
yield* Console.log("Signed in to T3 Connect.");
}),
),
+168 -5
View File
@@ -21,12 +21,25 @@ import * as HttpRouter from "effect/unstable/http/HttpRouter";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
RelayDeviceAuthorizationGrantType,
RelayDeviceAuthorizationResponse,
RelayDeviceTokenPollCode,
RelayDeviceTokenResponse,
} from "@t3tools/contracts/relay";
import {
HostProcessArchitecture,
HostProcessHostname,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { cloudCliOAuthConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
import { cloudCliOAuthConfig, relayUrlConfig, type CloudCliOAuthConfig } from "./publicConfig.ts";
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
const CLOUD_CLI_DEVICE_POLL_MAX_TRANSPORT_FAILURES = 5;
const PersistedToken = Schema.Struct({
accessToken: Schema.String,
@@ -46,6 +59,10 @@ const OAuthTokenResponse = Schema.Struct({
token_type: Schema.String,
});
const DeviceTokenPollErrorBody = Schema.Struct({
code: RelayDeviceTokenPollCode,
});
export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(
"CloudCliCredentialRemovalError",
{ cause: Schema.Defect() },
@@ -104,6 +121,7 @@ export class CloudCliTokenManager extends Context.Service<
CloudCliTokenManager,
{
readonly get: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly getWithDeviceLogin: Effect.Effect<PersistedToken, CloudCliTokenManagerError>;
readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;
readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;
readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;
@@ -115,6 +133,19 @@ const wrapError =
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, WrappedError, R> =>
effect.pipe(Effect.mapError(makeError));
const isCloudCliTokenManagerError = Schema.is(CloudCliTokenManagerError);
// Keeps already-typed manager errors (e.g. the authorization timeout) intact
// instead of collapsing them into a generic authorization failure.
const wrapUnknownError =
<WrappedError extends CloudCliTokenManagerError>(makeError: (cause: unknown) => WrappedError) =>
<A, E, R>(
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, WrappedError | CloudCliTokenManagerError, R> =>
effect.pipe(
Effect.mapError((cause) => (isCloudCliTokenManagerError(cause) ? cause : makeError(cause))),
);
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
@@ -125,7 +156,9 @@ function bytesToString(value: Uint8Array): string {
export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
// Device-token polling reads structured 400 bodies, so it needs the unfiltered client.
const rawHttpClient = yield* HttpClient.HttpClient;
const httpClient = rawHttpClient.pipe(HttpClient.filterStatusOk);
const secrets = yield* ServerSecretStore.ServerSecretStore;
const semaphore = yield* Semaphore.make(1);
const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {
@@ -222,7 +255,14 @@ export const make = Effect.gen(function* () {
authorizationUrl.searchParams.set("state", state);
authorizationUrl.searchParams.set("code_challenge", challenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
yield* Console.log(
[
`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}`,
"",
"Tip: on a headless or remote machine (SSH, VPS), run `t3 connect login --device` instead.",
"",
].join("\n"),
);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", (cause) =>
@@ -242,6 +282,121 @@ export const make = Effect.gen(function* () {
});
});
const loginDevice = Effect.fn("cloud.cli_token.login_device")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const relayUrl = yield* relayUrlConfig;
const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
const challenge = Encoding.encodeBase64Url(
yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),
);
const hostname = yield* HostProcessHostname;
const platform = yield* HostProcessPlatform;
const architecture = yield* HostProcessArchitecture;
const authorization = yield* HttpClientRequest.post(`${relayUrl}/v1/device/authorization`).pipe(
HttpClientRequest.bodyUrlParams({
client_id: metadata.clientId,
scope: metadata.scopes.join(" "),
code_challenge: challenge,
code_challenge_method: "S256",
device_name: hostname,
device_platform: `${platform} (${architecture}) node-v${process.versions.node}`,
}),
httpClient.execute,
Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayDeviceAuthorizationResponse)),
);
yield* Console.log(
[
`To authorize T3 Connect, open ${authorization.verification_uri} on another device and enter this code:`,
"",
` ${authorization.user_code}`,
"",
"Or open this link directly:",
authorization.verification_uri_complete,
"",
"Waiting for approval...",
].join("\n"),
);
let pollInterval = Duration.seconds(authorization.interval);
// Approval can take minutes; a flaky network or a relay blip mid-wait
// must not abort the whole login, so only repeated transport failures do.
let consecutiveTransportFailures = 0;
const failTransportOrContinue = (cause: unknown) => {
consecutiveTransportFailures += 1;
return consecutiveTransportFailures >= CLOUD_CLI_DEVICE_POLL_MAX_TRANSPORT_FAILURES
? Effect.fail(new CloudCliAuthorizationError({ cause }))
: Effect.succeed(Option.none<HttpClientResponse.HttpClientResponse>());
};
const poll = Effect.gen(function* () {
while (true) {
yield* Effect.sleep(pollInterval);
const response = yield* rawHttpClient
.execute(
HttpClientRequest.post(`${relayUrl}/v1/device/token`).pipe(
HttpClientRequest.bodyUrlParams({
grant_type: RelayDeviceAuthorizationGrantType,
device_code: authorization.device_code,
client_id: metadata.clientId,
}),
),
)
.pipe(Effect.map(Option.some), Effect.catch(failTransportOrContinue));
if (Option.isNone(response)) {
continue;
}
if (response.value.status === 200) {
return yield* HttpClientResponse.schemaBodyJson(RelayDeviceTokenResponse)(response.value);
}
if (response.value.status !== 400) {
// Gateway errors and other unexpected statuses are transient.
yield* failTransportOrContinue(
`Relay device token poll returned status ${response.value.status}.`,
);
continue;
}
consecutiveTransportFailures = 0;
const body = yield* HttpClientResponse.schemaBodyJson(DeviceTokenPollErrorBody)(
response.value,
).pipe(Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })));
switch (body.code) {
case "authorization_pending":
continue;
case "slow_down":
pollInterval = Duration.sum(pollInterval, Duration.seconds(5));
continue;
case "access_denied":
return yield* new CloudCliAuthorizationError({
cause: "The device authorization request was denied.",
});
case "expired_token":
return yield* new CloudCliAuthorizationTimeoutError({
cause:
"The device authorization request expired or was already redeemed before this device could complete it.",
});
}
}
});
// The relay owns the authoritative expiry (it answers expired_token), so
// the local timeout is a backstop padded past the final scheduled poll.
const grant = yield* poll.pipe(
Effect.timeout(Duration.seconds(authorization.expires_in + authorization.interval + 5)),
Effect.catchTag("TimeoutError", (cause) =>
Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),
),
);
return yield* exchangeToken(metadata, {
grant_type: "authorization_code",
code: grant.authorization_code,
redirect_uri: grant.redirect_uri,
client_id: metadata.clientId,
code_verifier: verifier,
});
});
const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {
const token = yield* read();
if (Option.isNone(token)) return token;
@@ -267,10 +422,18 @@ export const make = Effect.gen(function* () {
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))),
}).pipe(wrapUnknownError((cause) => new CloudCliAuthorizationError({ cause }))),
);
const getWithDeviceLogin = semaphore.withPermits(1)(
Effect.gen(function* () {
const token = yield* getExistingNoLock();
return Option.isSome(token)
? token.value
: yield* loginDevice().pipe(Effect.flatMap(persist));
}).pipe(wrapUnknownError((cause) => new CloudCliAuthorizationError({ cause }))),
);
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
return CloudCliTokenManager.of({ get, getWithDeviceLogin, getExisting, hasCredential, clear });
});
export const layer = Layer.effect(CloudCliTokenManager, make);
+1
View File
@@ -192,6 +192,7 @@ describe("reconcileDesiredCloudLink", () => {
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
getWithDeviceLogin: unusedSecretStoreOperation(),
getExisting: Effect.succeed(Option.none()),
hasCredential: unusedSecretStoreOperation(),
clear: unusedSecretStoreOperation(),
+86
View File
@@ -0,0 +1,86 @@
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import type {
RelayDeviceApprovalResponse,
RelayDeviceAuthorizationDetails,
RelayOkResponse,
} from "@t3tools/contracts/relay";
import * as Effect from "effect/Effect";
import { runtime } from "../lib/runtime";
export type DeviceAuthorizationResult<A> =
| { readonly _tag: "success"; readonly value: A }
| { readonly _tag: "not-found" }
| { readonly _tag: "failed"; readonly message: string };
function mapFailure(error: ManagedRelay.ManagedRelayClientError): DeviceAuthorizationResult<never> {
if (
error._tag === "ManagedRelayRequestFailedError" &&
error.relayError?._tag === "RelayDeviceAuthorizationNotFoundError"
) {
return { _tag: "not-found" };
}
return { _tag: "failed", message: error.message };
}
function runDeviceAuthorizationRequest<A>(
run: (
client: ManagedRelay.ManagedRelayClient["Service"],
) => Effect.Effect<A, ManagedRelay.ManagedRelayClientError>,
): Promise<DeviceAuthorizationResult<A>> {
return runtime.runPromise(
ManagedRelay.ManagedRelayClient.pipe(
Effect.flatMap(run),
Effect.map((value) => ({ _tag: "success", value }) as DeviceAuthorizationResult<A>),
Effect.catch((error) => Effect.succeed(mapFailure(error))),
),
);
}
export function getDeviceAuthorization(
clerkToken: string,
userCode: string,
): Promise<DeviceAuthorizationResult<RelayDeviceAuthorizationDetails>> {
return runDeviceAuthorizationRequest((client) =>
client.getDeviceAuthorization({ clerkToken, userCode }),
);
}
export function approveDeviceAuthorization(
clerkToken: string,
userCode: string,
): Promise<DeviceAuthorizationResult<RelayDeviceApprovalResponse>> {
return runDeviceAuthorizationRequest((client) =>
client.approveDeviceAuthorization({ clerkToken, userCode }),
);
}
export function denyDeviceAuthorization(
clerkToken: string,
userCode: string,
): Promise<DeviceAuthorizationResult<RelayOkResponse>> {
return runDeviceAuthorizationRequest((client) =>
client.denyDeviceAuthorization({ clerkToken, userCode }),
);
}
export function completeDeviceAuthorization(
clerkToken: string,
input: { readonly state: string; readonly code: string },
): Promise<DeviceAuthorizationResult<RelayOkResponse>> {
return runDeviceAuthorizationRequest((client) =>
client.completeDeviceAuthorization({ clerkToken, payload: input }),
);
}
export function formatDeviceUserCodeInput(raw: string): string {
const normalized = raw
.toUpperCase()
.replaceAll(/[^A-Z0-9]/gu, "")
.slice(0, 8);
return normalized.length > 4 ? `${normalized.slice(0, 4)}-${normalized.slice(4)}` : normalized;
}
export function isCompleteDeviceUserCode(value: string): boolean {
return /^[A-Z0-9]{4}-[A-Z0-9]{4}$/u.test(value);
}
+4
View File
@@ -160,6 +160,10 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
return `Relay rejected the agent activity publish proof (${error.reason}).`;
case "RelayInternalError":
return `Relay encountered an internal error (${error.reason}).`;
case "RelayDeviceTokenPollError":
return `Relay rejected the device authorization poll (${error.code}).`;
case "RelayDeviceAuthorizationNotFoundError":
return "Relay could not find the device authorization.";
}
}
@@ -0,0 +1,489 @@
import { useAuth, useClerk } from "@clerk/react";
import type { RelayDeviceAuthorizationDetails } from "@t3tools/contracts/relay";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { APP_DISPLAY_NAME } from "../../branding";
import {
approveDeviceAuthorization,
completeDeviceAuthorization,
denyDeviceAuthorization,
formatDeviceUserCodeInput,
getDeviceAuthorization,
isCompleteDeviceUserCode,
} from "../../cloud/deviceAuthorization";
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../../cloud/publicConfig";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
function DeviceSurfaceShell({ children }: { readonly children: React.ReactNode }) {
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
<div className="pointer-events-none absolute inset-0 opacity-80">
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-sky-500)_14%,transparent),transparent)]" />
<div className="absolute inset-y-0 left-0 w-72 bg-[radial-gradient(28rem_18rem_at_left,color-mix(in_srgb,var(--color-violet-500)_10%,transparent),transparent)]" />
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
</div>
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
{APP_DISPLAY_NAME}
</p>
{children}
</section>
</div>
);
}
function DeviceSurfaceMessage({
title,
message,
children,
}: {
readonly title: string;
readonly message: string;
readonly children?: React.ReactNode;
}) {
return (
<DeviceSurfaceShell>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">{title}</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
{children}
</DeviceSurfaceShell>
);
}
function SignInGate({
title,
message,
children,
}: {
readonly title: string;
readonly message: string;
readonly children: React.ReactNode;
}) {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const clerk = useClerk();
if (!isLoaded) {
return <DeviceSurfaceMessage title={title} message="Checking your session." />;
}
if (!isSignedIn) {
return (
<DeviceSurfaceMessage title={title} message={message}>
<div className="mt-6">
<Button
size="sm"
onClick={() => clerk.openSignIn({ forceRedirectUrl: window.location.href })}
>
Sign in to continue
</Button>
</div>
</DeviceSurfaceMessage>
);
}
return children;
}
function useClerkTokenReader(): () => Promise<string | null> {
const { getToken } = useAuth({ treatPendingAsSignedOut: false });
return useCallback(
async () => (await getToken(resolveRelayClerkTokenOptions())) ?? null,
[getToken],
);
}
const GENERIC_FAILURE_MESSAGE =
"The device authorization service could not be reached. Try again in a moment.";
const NOT_FOUND_MESSAGE =
"That code was not recognized. It may have expired or already been used — run `t3 connect login --device` again to get a fresh code.";
type DeviceApprovalStep =
| { readonly step: "enter" }
| { readonly step: "looking-up" }
| { readonly step: "review"; readonly details: RelayDeviceAuthorizationDetails }
| { readonly step: "approving"; readonly details: RelayDeviceAuthorizationDetails }
| { readonly step: "denied" }
| { readonly step: "redirecting" };
export function DeviceAuthorizationSurface({
initialUserCode,
}: {
readonly initialUserCode?: string;
}) {
if (!hasCloudPublicConfig()) {
return (
<DeviceSurfaceMessage
title="Device authorization unavailable"
message="T3 Connect is not configured for this app, so there is nothing to authorize here."
/>
);
}
return (
<SignInGate
title="Authorize device"
message="Sign in to your T3 Connect account to authorize the device that requested access."
>
<ConfiguredDeviceAuthorizationSurface
{...(initialUserCode !== undefined ? { initialUserCode } : {})}
/>
</SignInGate>
);
}
function ConfiguredDeviceAuthorizationSurface({
initialUserCode,
}: {
readonly initialUserCode?: string;
}) {
const readClerkToken = useClerkTokenReader();
const [userCode, setUserCode] = useState(() => formatDeviceUserCodeInput(initialUserCode ?? ""));
const [state, setState] = useState<DeviceApprovalStep>({ step: "enter" });
const [errorMessage, setErrorMessage] = useState("");
const autoLookupAttemptedRef = useRef(false);
const lookupRequestSeqRef = useRef(0);
const lookup = useCallback(
async (code: string) => {
// A newer lookup supersedes any in-flight one; stale results must not
// reach setState or the review step could show the wrong device.
const requestSeq = ++lookupRequestSeqRef.current;
setErrorMessage("");
setState({ step: "looking-up" });
const clerkToken = await readClerkToken();
if (lookupRequestSeqRef.current !== requestSeq) {
return;
}
if (!clerkToken) {
setState({ step: "enter" });
setErrorMessage("Your session expired. Sign in again to continue.");
return;
}
const result = await getDeviceAuthorization(clerkToken, code);
if (lookupRequestSeqRef.current !== requestSeq) {
return;
}
if (result._tag === "success") {
if (result.value.status !== "pending") {
setState({ step: "enter" });
setErrorMessage(NOT_FOUND_MESSAGE);
return;
}
setState({ step: "review", details: result.value });
return;
}
setState({ step: "enter" });
setErrorMessage(result._tag === "not-found" ? NOT_FOUND_MESSAGE : GENERIC_FAILURE_MESSAGE);
},
[readClerkToken],
);
useEffect(() => {
if (autoLookupAttemptedRef.current) {
return;
}
autoLookupAttemptedRef.current = true;
const initial = formatDeviceUserCodeInput(initialUserCode ?? "");
if (isCompleteDeviceUserCode(initial)) {
void lookup(initial);
}
}, [initialUserCode, lookup]);
const approve = useCallback(
async (details: RelayDeviceAuthorizationDetails) => {
setErrorMessage("");
setState({ step: "approving", details });
const clerkToken = await readClerkToken();
if (!clerkToken) {
setState({ step: "review", details });
setErrorMessage("Your session expired. Sign in again to continue.");
return;
}
const result = await approveDeviceAuthorization(clerkToken, details.userCode);
if (result._tag === "success") {
setState({ step: "redirecting" });
window.location.assign(result.value.authorizationUrl);
return;
}
if (result._tag === "not-found") {
setState({ step: "enter" });
setErrorMessage(NOT_FOUND_MESSAGE);
return;
}
setState({ step: "review", details });
setErrorMessage(GENERIC_FAILURE_MESSAGE);
},
[readClerkToken],
);
const deny = useCallback(
async (details: RelayDeviceAuthorizationDetails) => {
setErrorMessage("");
const clerkToken = await readClerkToken();
if (!clerkToken) {
setErrorMessage("Your session expired. Sign in again to continue.");
return;
}
const result = await denyDeviceAuthorization(clerkToken, details.userCode);
if (result._tag === "success" || result._tag === "not-found") {
setState({ step: "denied" });
return;
}
setErrorMessage(GENERIC_FAILURE_MESSAGE);
},
[readClerkToken],
);
if (state.step === "denied") {
return (
<DeviceSurfaceMessage
title="Request denied"
message="The device was not authorized. You can close this window."
/>
);
}
if (state.step === "redirecting") {
return (
<DeviceSurfaceMessage
title="Finishing authorization"
message="Confirming access with the sign-in service."
/>
);
}
if (state.step === "review" || state.step === "approving") {
const { details } = state;
const approving = state.step === "approving";
return (
<DeviceSurfaceShell>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">Authorize device</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
A device is asking to sign in to your T3 Connect account with this code:
</p>
<p className="mt-4 text-center font-mono text-3xl font-semibold tracking-[0.2em]">
{details.userCode}
</p>
<dl className="mt-5 space-y-2 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
<DeviceDetailRow label="Device">
{details.deviceName ?? "Unknown device"}
{details.devicePlatform ? ` · ${details.devicePlatform}` : ""}
{details.clientVersion ? ` · ${details.clientVersion}` : ""}
</DeviceDetailRow>
{details.requestIp ? (
<DeviceDetailRow label="Address">
{details.requestIp}
{details.requestLocation ? ` (${details.requestLocation})` : ""}
</DeviceDetailRow>
) : null}
<DeviceDetailRow label="Requested">
{formatTimestamp(details.requestedAt)}
</DeviceDetailRow>
</dl>
{errorMessage ? <DeviceSurfaceError message={errorMessage} /> : null}
<div className="mt-6 flex flex-wrap gap-2">
<Button disabled={approving} size="sm" onClick={() => void approve(details)}>
{approving ? "Authorizing..." : "Allow"}
</Button>
<Button
disabled={approving}
size="sm"
variant="outline"
onClick={() => void deny(details)}
>
Deny
</Button>
</div>
<p className="mt-5 text-xs leading-relaxed text-muted-foreground">
Do not click Allow unless you started this login attempt yourself with{" "}
<span className="font-mono">t3 connect login --device</span>. Anyone with this code can
request access to your account.
</p>
</DeviceSurfaceShell>
);
}
const lookingUp = state.step === "looking-up";
return (
<DeviceSurfaceShell>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">Authorize device</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
Enter the code shown in your terminal to authorize the device requesting access to your T3
Connect account.
</p>
<form
className="mt-6 space-y-4"
onSubmit={(event) => {
event.preventDefault();
if (isCompleteDeviceUserCode(userCode)) {
void lookup(userCode);
}
}}
>
<Input
aria-label="Device code"
autoCapitalize="characters"
autoComplete="off"
autoCorrect="off"
autoFocus
className="text-center font-mono text-xl tracking-[0.25em] uppercase"
disabled={lookingUp}
nativeInput
onChange={(event) => setUserCode(formatDeviceUserCodeInput(event.currentTarget.value))}
placeholder="XXXX-XXXX"
spellCheck={false}
value={userCode}
/>
{errorMessage ? <DeviceSurfaceError message={errorMessage} /> : null}
<Button disabled={lookingUp || !isCompleteDeviceUserCode(userCode)} size="sm" type="submit">
{lookingUp ? "Checking..." : "Continue"}
</Button>
</form>
</DeviceSurfaceShell>
);
}
function DeviceDetailRow({
label,
children,
}: {
readonly label: string;
readonly children: React.ReactNode;
}) {
return (
<div className="flex gap-3">
<dt className="w-20 shrink-0 font-medium text-foreground/70">{label}</dt>
<dd className="text-foreground/85">{children}</dd>
</div>
);
}
function DeviceSurfaceError({ message }: { readonly message: string }) {
return (
<div className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
{message}
</div>
);
}
function formatTimestamp(value: string): string {
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString();
}
export function DeviceAuthorizationCallbackSurface({
code,
state,
authorizationError,
}: {
readonly code?: string;
readonly state?: string;
readonly authorizationError?: string;
}) {
if (!hasCloudPublicConfig()) {
return (
<DeviceSurfaceMessage
title="Device authorization unavailable"
message="T3 Connect is not configured for this app, so there is nothing to authorize here."
/>
);
}
if (authorizationError) {
return (
<DeviceSurfaceMessage
title="Authorization not completed"
message="The sign-in service did not grant access to the device. You can close this window, or run `t3 connect login --device` again to retry."
/>
);
}
if (!code || !state) {
return (
<DeviceSurfaceMessage
title="Authorization not completed"
message="This page is missing its authorization details. Start again from your terminal with `t3 connect login --device`."
/>
);
}
return (
<SignInGate
title="Finish device authorization"
message="Sign in to finish authorizing the device."
>
<ConfiguredDeviceAuthorizationCallbackSurface code={code} state={state} />
</SignInGate>
);
}
function ConfiguredDeviceAuthorizationCallbackSurface({
code,
state,
}: {
readonly code: string;
readonly state: string;
}) {
const readClerkToken = useClerkTokenReader();
const [status, setStatus] = useState<"completing" | "done" | "not-found" | "failed">(
"completing",
);
const completionAttemptedRef = useRef(false);
useEffect(() => {
if (completionAttemptedRef.current) {
return;
}
completionAttemptedRef.current = true;
void (async () => {
const clerkToken = await readClerkToken();
if (!clerkToken) {
setStatus("failed");
return;
}
const result = await completeDeviceAuthorization(clerkToken, { state, code });
setStatus(
result._tag === "success" ? "done" : result._tag === "not-found" ? "not-found" : "failed",
);
})();
}, [code, readClerkToken, state]);
if (status === "completing") {
return (
<DeviceSurfaceMessage
title="Finishing device authorization"
message="Handing the authorization back to your device."
/>
);
}
if (status === "done") {
return (
<DeviceSurfaceMessage
title="Device authorized"
message="You can close this window and return to your terminal — it signs in automatically within a few seconds."
/>
);
}
return (
<DeviceSurfaceMessage
title="Authorization not completed"
message={
status === "not-found"
? NOT_FOUND_MESSAGE
: "The device authorization could not be completed. Run `t3 connect login --device` again to retry."
}
/>
);
}
+42
View File
@@ -20,6 +20,8 @@ import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as OauthDeviceRouteImport } from './routes/oauth.device'
import { Route as OauthDeviceCallbackRouteImport } from './routes/oauth.device_.callback'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -77,6 +79,16 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
path: '/archived',
getParentRoute: () => SettingsRoute,
} as any)
const OauthDeviceRoute = OauthDeviceRouteImport.update({
id: '/oauth/device',
path: '/oauth/device',
getParentRoute: () => rootRouteImport,
} as any)
const OauthDeviceCallbackRoute = OauthDeviceCallbackRouteImport.update({
id: '/oauth/device_/callback',
path: '/oauth/device/callback',
getParentRoute: () => rootRouteImport,
} as any)
const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({
id: '/draft/$draftId',
path: '/draft/$draftId',
@@ -93,6 +105,7 @@ export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/oauth/device': typeof OauthDeviceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -102,10 +115,12 @@ export interface FileRoutesByFullPath {
'/settings/source-control': typeof SettingsSourceControlRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
'/oauth/device/callback': typeof OauthDeviceCallbackRoute
}
export interface FileRoutesByTo {
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/oauth/device': typeof OauthDeviceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -116,12 +131,14 @@ export interface FileRoutesByTo {
'/': typeof ChatIndexRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
'/oauth/device/callback': typeof OauthDeviceCallbackRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/oauth/device': typeof OauthDeviceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -132,6 +149,7 @@ export interface FileRoutesById {
'/_chat/': typeof ChatIndexRoute
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute
'/oauth/device_/callback': typeof OauthDeviceCallbackRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
@@ -139,6 +157,7 @@ export interface FileRouteTypes {
| '/'
| '/pair'
| '/settings'
| '/oauth/device'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -148,10 +167,12 @@ export interface FileRouteTypes {
| '/settings/source-control'
| '/$environmentId/$threadId'
| '/draft/$draftId'
| '/oauth/device/callback'
fileRoutesByTo: FileRoutesByTo
to:
| '/pair'
| '/settings'
| '/oauth/device'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -162,11 +183,13 @@ export interface FileRouteTypes {
| '/'
| '/$environmentId/$threadId'
| '/draft/$draftId'
| '/oauth/device/callback'
id:
| '__root__'
| '/_chat'
| '/pair'
| '/settings'
| '/oauth/device'
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -177,12 +200,15 @@ export interface FileRouteTypes {
| '/_chat/'
| '/_chat/$environmentId/$threadId'
| '/_chat/draft/$draftId'
| '/oauth/device_/callback'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
PairRoute: typeof PairRoute
SettingsRoute: typeof SettingsRouteWithChildren
OauthDeviceRoute: typeof OauthDeviceRoute
OauthDeviceCallbackRoute: typeof OauthDeviceCallbackRoute
}
declare module '@tanstack/react-router' {
@@ -264,6 +290,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsArchivedRouteImport
parentRoute: typeof SettingsRoute
}
'/oauth/device': {
id: '/oauth/device'
path: '/oauth/device'
fullPath: '/oauth/device'
preLoaderRoute: typeof OauthDeviceRouteImport
parentRoute: typeof rootRouteImport
}
'/oauth/device_/callback': {
id: '/oauth/device_/callback'
path: '/oauth/device/callback'
fullPath: '/oauth/device/callback'
preLoaderRoute: typeof OauthDeviceCallbackRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat/draft/$draftId': {
id: '/_chat/draft/$draftId'
path: '/draft/$draftId'
@@ -323,6 +363,8 @@ const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
PairRoute: PairRoute,
SettingsRoute: SettingsRouteWithChildren,
OauthDeviceRoute: OauthDeviceRoute,
OauthDeviceCallbackRoute: OauthDeviceCallbackRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
+1 -1
View File
@@ -96,7 +96,7 @@ function RootRouteView() {
};
}, [pathname]);
if (pathname === "/pair") {
if (pathname === "/pair" || pathname.startsWith("/oauth/device")) {
return (
<>
<DocumentTitleSync />
+15
View File
@@ -0,0 +1,15 @@
import { createFileRoute } from "@tanstack/react-router";
import { DeviceAuthorizationSurface } from "../components/auth/DeviceAuthorizationSurface";
export const Route = createFileRoute("/oauth/device")({
validateSearch: (search: Record<string, unknown>) => ({
user_code: typeof search.user_code === "string" ? search.user_code : undefined,
}),
component: DeviceAuthorizationRouteView,
});
function DeviceAuthorizationRouteView() {
const { user_code } = Route.useSearch();
return <DeviceAuthorizationSurface {...(user_code ? { initialUserCode: user_code } : {})} />;
}
@@ -0,0 +1,23 @@
import { createFileRoute } from "@tanstack/react-router";
import { DeviceAuthorizationCallbackSurface } from "../components/auth/DeviceAuthorizationSurface";
export const Route = createFileRoute("/oauth/device_/callback")({
validateSearch: (search: Record<string, unknown>) => ({
code: typeof search.code === "string" ? search.code : undefined,
state: typeof search.state === "string" ? search.state : undefined,
error: typeof search.error === "string" ? search.error : undefined,
}),
component: DeviceAuthorizationCallbackRouteView,
});
function DeviceAuthorizationCallbackRouteView() {
const { code, state, error } = Route.useSearch();
return (
<DeviceAuthorizationCallbackSurface
{...(code ? { code } : {})}
{...(state ? { state } : {})}
{...(error ? { authorizationError: error } : {})}
/>
);
}
+28 -12
View File
@@ -42,7 +42,10 @@ deployments.
For a hosted relay deployment, copy `infra/relay/.env.example` to `infra/relay/.env`. The relay
deployment reads `RELAY_DOMAIN`, `RELAY_API_ZONE_NAME`, `RELAY_TUNNEL_ZONE_NAME`,
`CLERK_PUBLISHABLE_KEY`, and `CLERK_JWT_AUDIENCE` through Effect `Config`. There are no checked-in
`CLERK_PUBLISHABLE_KEY`, and `CLERK_JWT_AUDIENCE` through Effect `Config`, plus
`T3CODE_APP_BASE_URL` (web app origin for device-code login; `prod` defaults to
`https://app.t3.codes`, and every other stage must set it explicitly to a web app build that
targets the same stage relay and Clerk instance). Other than that default, there are no checked-in
deployment defaults.
`vp run --filter t3code-relay deploy` invokes Alchemy from the relay directory, so Alchemy loads
`infra/relay/.env`. After a successful deployment, the wrapper updates the repository-root `.env`
@@ -63,19 +66,30 @@ In **Clerk Dashboard > OAuth applications**:
1. Create an OAuth application for the T3 CLI.
2. Enable the **Public** option so authorization-code exchange uses PKCE.
3. Add `http://127.0.0.1:34338/callback` as an allowed redirect URI.
4. Enable the `openid`, `profile`, and `email` scopes.
5. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build
3. Add `http://127.0.0.1:34338/callback` as an allowed redirect URI. This serves the default
loopback login flow.
4. Add `<app origin>/oauth/device/callback` as an additional allowed redirect URI for device-code
login (`t3 connect login --device`). The app origin must match the relay stage's
`T3CODE_APP_BASE_URL` (production: `https://app.t3.codes/oauth/device/callback`). For local
web-app testing against a development Clerk instance, also add the dev-server variant such as
`http://localhost:5733/oauth/device/callback`.
5. Enable the `openid`, `profile`, and `email` scopes.
6. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build
environment to the generated public client ID.
The CLI derives Clerk's frontend API URL from the publishable key and calls Clerk's
`/oauth/authorize` and `/oauth/token` endpoints directly. The relay is not involved in the OAuth
handshake; it only validates the issued Clerk bearer token when the CLI manages an environment link.
`/oauth/authorize` and `/oauth/token` endpoints directly. In the default loopback flow the relay is
not involved in the OAuth handshake; it only validates the issued Clerk bearer token when the CLI
manages an environment link. In the device flow the relay additionally brokers the pending
authorization (it stores the PKCE challenge and hands the Clerk authorization code back to the
polling CLI), but the token exchange still happens directly between the CLI and Clerk, so both
flows store the same credential.
The CLI supports these headless operations:
```sh
t3 connect login
t3 connect login --device
t3 connect link
t3 connect status
t3 connect unlink
@@ -84,7 +98,11 @@ t3 serve
```
`t3 connect login` opens the Clerk authorization flow and stores the CLI credential without enabling
cloud exposure. `t3 connect link` installs the pinned managed `cloudflared` binary when needed,
cloud exposure. `t3 connect login --device` uses a device-code flow instead: the CLI prints a short
code and a link to `<T3CODE_APP_BASE_URL>/oauth/device`, where a signed-in user reviews the
requesting device and approves or denies it while the CLI polls the relay for the result. Use it on
VPSes, containers, and other machines where the loopback browser flow is impractical.
`t3 connect link` installs the pinned managed `cloudflared` binary when needed,
authorizes when needed, and records durable intent to expose the environment. It works without a
running T3 server. The next `t3 serve` or `t3 start` reconciles the relay link and launches the
managed tunnel. `t3 connect unlink` records disabled intent immediately, stops a reachable running
@@ -92,16 +110,14 @@ connector, and attempts to revoke the relay-side environment record. It retains
authorization so `t3 connect link` can re-enable exposure without another browser flow. `t3 connect
logout` performs the same cleanup and removes the stored CLI authorization.
The current OAuth callback listener binds to loopback port `34338`. When running the CLI over SSH,
forward that port before running `t3 connect login` or `t3 connect link`:
The default loopback callback listener binds to port `34338`. When running the CLI over SSH, either
use `t3 connect login --device` (recommended — no port forwarding required) or forward that port
before running `t3 connect login` or `t3 connect link`:
```sh
ssh -L 34338:127.0.0.1:34338 <host>
```
A relay-hosted callback broker can remove this port-forward requirement later without changing the
stored PKCE token model.
## JWT Template
In **Clerk Dashboard > JWT templates**, create a template with:
+10
View File
@@ -9,6 +9,16 @@ RELAY_TUNNEL_ZONE_NAME=tunnels.example.com
# Set this only when the derived relay hostname should not be used.
# RELAY_DOMAIN=relay.example.com
# Hosted web app origin for device-code login
# `t3 connect login --device` sends users to <origin>/oauth/device and the
# approval flow returns through <origin>/oauth/device/callback, so the origin
# must serve a web app built against this relay stage and its Clerk instance,
# and the callback URL must be an allowed redirect URI on the Clerk CLI OAuth
# application. The `prod` stage defaults to https://app.t3.codes; every other
# stage must set this explicitly to its own app build (for local testing,
# e.g. http://localhost:5733) or the deploy fails.
# T3CODE_APP_BASE_URL=http://localhost:5733
# Required: Clerk
# Get the keys from the Clerk Dashboard under API keys. Set the JWT audience to
# the `aud` claim configured on the `t3-relay` JWT template.
+6 -1
View File
@@ -19,6 +19,8 @@ The relay currently owns:
- Linking T3 Code environments to a cloud account.
- Provisioning and tracking managed environment endpoints.
- Issuing short-lived credentials used to connect clients to linked environments.
- Brokering OAuth device authorization for headless CLI logins (`t3 connect login --device`),
including the pending-authorization records approved at `app.t3.codes/oauth/device`.
- Listing linked environments and registered mobile devices for an account.
- Registering mobile notification preferences and APNs tokens.
- Receiving published agent activity and delivering notifications or Live Activity updates.
@@ -85,7 +87,10 @@ vp run --filter t3code-relay deploy
The stack provisions the Cloudflare Worker and queues, managed endpoint resources, database
connectivity, and relay tracing resources. Copy [`infra/relay/.env.example`](./.env.example) to
`infra/relay/.env` and fill in the deployment-specific values before deploying. Alchemy loads that
file from the relay directory. Runtime secrets include Clerk and APNs credentials. Production adopts
file from the relay directory. Runtime secrets include Clerk and APNs credentials.
`T3CODE_APP_BASE_URL` selects the web app origin used by device-code login; `prod` defaults to
`https://app.t3.codes`, and every other stage must set it explicitly — see the comment in
`.env.example`. Production adopts
the configured API and tunnel DNS zones as retained Cloudflare resources. Personal stages reference
the production-owned zones.
@@ -0,0 +1,29 @@
CREATE TABLE "relay_device_authorizations" (
"device_code_hash" varchar(64) PRIMARY KEY,
"user_code" varchar(16) NOT NULL,
"client_id" varchar(191) NOT NULL,
"scope" text NOT NULL,
"code_challenge" varchar(128) NOT NULL,
"status" varchar(16) NOT NULL,
"user_id" varchar(255),
"callback_state" varchar(64),
"redirect_uri" text,
"authorization_code" text,
"device_name" text,
"device_platform" varchar(128),
"client_version" varchar(64),
"request_ip" varchar(64),
"request_location" varchar(191),
"poll_interval_seconds" integer NOT NULL,
"last_polled_at" varchar(64),
"expires_at" varchar(64) NOT NULL,
"created_at" varchar(64) NOT NULL,
"updated_at" varchar(64) NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX "idx_relay_device_authorizations_user_code" ON "relay_device_authorizations" ("user_code");
--> statement-breakpoint
CREATE UNIQUE INDEX "idx_relay_device_authorizations_callback_state" ON "relay_device_authorizations" ("callback_state");
--> statement-breakpoint
CREATE INDEX "idx_relay_device_authorizations_expires_at" ON "relay_device_authorizations" ("expires_at");
File diff suppressed because it is too large. Load diff
+2
View File
@@ -18,6 +18,8 @@ export class RelayConfiguration extends Context.Service<
RelayConfiguration,
{
readonly relayIssuer: string;
/** Origin of the hosted web app that serves the device-authorization approval page. */
readonly appBaseUrl: string;
readonly apns: ApnsCredentials;
readonly clerkSecretKey: Redacted.Redacted<string>;
readonly clerkPublishableKey: string;
@@ -31,6 +31,7 @@ import * as ApnsClient from "./ApnsClient.ts";
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -10,6 +10,7 @@ import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
const config: RelayConfiguration.RelayConfiguration["Service"] = {
relayIssuer: "https://relay.example.com",
appBaseUrl: "https://app.example.test",
apns: {
teamId: "team-1",
keyId: "key-1",
@@ -123,6 +123,7 @@ function makeDeliveryAttempts(
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -0,0 +1,297 @@
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { and, eq, gt, isNull, lt, ne, or } from "drizzle-orm";
import * as RelayDb from "../db.ts";
import { relayDeviceAuthorizations } from "../persistence/schema.ts";
export class DeviceAuthorizationPersistenceError extends Schema.TaggedErrorClass<DeviceAuthorizationPersistenceError>()(
"DeviceAuthorizationPersistenceError",
{
operation: Schema.Literals([
"create",
"find-by-user-code",
"find-by-device-code",
"begin-approval",
"complete-approval",
"deny",
"stamp-polled",
"take-approved",
"delete",
"prune-expired",
]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to persist device authorization state during '${this.operation}'`;
}
}
export type DeviceAuthorizationRecord = typeof relayDeviceAuthorizations.$inferSelect;
export class DeviceAuthorizations extends Context.Service<
DeviceAuthorizations,
{
readonly create: (input: {
readonly deviceCodeHash: string;
readonly userCode: string;
readonly clientId: string;
readonly scope: string;
readonly codeChallenge: string;
readonly deviceName: string | null;
readonly devicePlatform: string | null;
readonly clientVersion: string | null;
readonly requestIp: string | null;
readonly requestLocation: string | null;
readonly pollIntervalSeconds: number;
readonly expiresAt: DateTime.DateTime;
}) => Effect.Effect<void, DeviceAuthorizationPersistenceError>;
readonly findByUserCode: (
userCode: string,
) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly findByDeviceCodeHash: (
deviceCodeHash: string,
) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly beginApproval: (input: {
readonly userCode: string;
readonly callbackState: string;
readonly redirectUri: string;
readonly now: DateTime.DateTime;
}) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly completeApproval: (input: {
readonly callbackState: string;
readonly authorizationCode: string;
readonly userId: string;
readonly now: DateTime.DateTime;
}) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly deny: (input: {
readonly userCode: string;
readonly userId: string;
readonly now: DateTime.DateTime;
}) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly stampPolled: (input: {
readonly deviceCodeHash: string;
readonly now: DateTime.DateTime;
}) => Effect.Effect<void, DeviceAuthorizationPersistenceError>;
readonly takeApproved: (
deviceCodeHash: string,
) => Effect.Effect<DeviceAuthorizationRecord | null, DeviceAuthorizationPersistenceError>;
readonly deleteByDeviceCodeHash: (
deviceCodeHash: string,
) => Effect.Effect<void, DeviceAuthorizationPersistenceError>;
readonly pruneExpired: Effect.Effect<void, DeviceAuthorizationPersistenceError>;
}
>()("t3code-relay/auth/DeviceAuthorizations") {}
const persistenceError =
(operation: DeviceAuthorizationPersistenceError["operation"]) => (cause: unknown) =>
new DeviceAuthorizationPersistenceError({ operation, cause });
const make = Effect.gen(function* () {
const db = yield* RelayDb.RelayDb;
const firstOrNull = (rows: ReadonlyArray<DeviceAuthorizationRecord>) => rows[0] ?? null;
const create: DeviceAuthorizations["Service"]["create"] = Effect.fn(
"relay.device_authorizations.create",
)(function* (input) {
const now = DateTime.formatIso(yield* DateTime.now);
yield* db
.insert(relayDeviceAuthorizations)
.values({
deviceCodeHash: input.deviceCodeHash,
userCode: input.userCode,
clientId: input.clientId,
scope: input.scope,
codeChallenge: input.codeChallenge,
status: "pending",
deviceName: input.deviceName,
devicePlatform: input.devicePlatform,
clientVersion: input.clientVersion,
requestIp: input.requestIp,
requestLocation: input.requestLocation,
pollIntervalSeconds: input.pollIntervalSeconds,
expiresAt: DateTime.formatIso(input.expiresAt),
createdAt: now,
updatedAt: now,
})
.pipe(Effect.mapError(persistenceError("create")));
});
const findByUserCode: DeviceAuthorizations["Service"]["findByUserCode"] = Effect.fn(
"relay.device_authorizations.find_by_user_code",
)(function* (userCode) {
return firstOrNull(
yield* db
.select()
.from(relayDeviceAuthorizations)
.where(eq(relayDeviceAuthorizations.userCode, userCode))
.limit(1)
.pipe(Effect.mapError(persistenceError("find-by-user-code"))),
);
});
const findByDeviceCodeHash: DeviceAuthorizations["Service"]["findByDeviceCodeHash"] = Effect.fn(
"relay.device_authorizations.find_by_device_code",
)(function* (deviceCodeHash) {
return firstOrNull(
yield* db
.select()
.from(relayDeviceAuthorizations)
.where(eq(relayDeviceAuthorizations.deviceCodeHash, deviceCodeHash))
.limit(1)
.pipe(Effect.mapError(persistenceError("find-by-device-code"))),
);
});
const beginApproval: DeviceAuthorizations["Service"]["beginApproval"] = Effect.fn(
"relay.device_authorizations.begin_approval",
)(function* (input) {
const now = DateTime.formatIso(input.now);
// Claims only rows without a callback state; repeated approvals must
// reuse the first issued state so an in-flight Clerk redirect stays valid.
return firstOrNull(
yield* db
.update(relayDeviceAuthorizations)
.set({
callbackState: input.callbackState,
redirectUri: input.redirectUri,
updatedAt: now,
})
.where(
and(
eq(relayDeviceAuthorizations.userCode, input.userCode),
eq(relayDeviceAuthorizations.status, "pending"),
gt(relayDeviceAuthorizations.expiresAt, now),
isNull(relayDeviceAuthorizations.callbackState),
),
)
.returning()
.pipe(Effect.mapError(persistenceError("begin-approval"))),
);
});
const completeApproval: DeviceAuthorizations["Service"]["completeApproval"] = Effect.fn(
"relay.device_authorizations.complete_approval",
)(function* (input) {
const now = DateTime.formatIso(input.now);
return firstOrNull(
yield* db
.update(relayDeviceAuthorizations)
.set({
status: "approved",
authorizationCode: input.authorizationCode,
userId: input.userId,
updatedAt: now,
})
.where(
and(
eq(relayDeviceAuthorizations.callbackState, input.callbackState),
eq(relayDeviceAuthorizations.status, "pending"),
gt(relayDeviceAuthorizations.expiresAt, now),
),
)
.returning()
.pipe(Effect.mapError(persistenceError("complete-approval"))),
);
});
const deny: DeviceAuthorizations["Service"]["deny"] = Effect.fn(
"relay.device_authorizations.deny",
)(function* (input) {
const now = DateTime.formatIso(input.now);
return firstOrNull(
yield* db
.update(relayDeviceAuthorizations)
.set({
status: "denied",
userId: input.userId,
updatedAt: now,
})
.where(
and(
eq(relayDeviceAuthorizations.userCode, input.userCode),
eq(relayDeviceAuthorizations.status, "pending"),
gt(relayDeviceAuthorizations.expiresAt, now),
),
)
.returning()
.pipe(Effect.mapError(persistenceError("deny"))),
);
});
const stampPolled: DeviceAuthorizations["Service"]["stampPolled"] = Effect.fn(
"relay.device_authorizations.stamp_polled",
)(function* (input) {
yield* db
.update(relayDeviceAuthorizations)
.set({ lastPolledAt: DateTime.formatIso(input.now) })
.where(eq(relayDeviceAuthorizations.deviceCodeHash, input.deviceCodeHash))
.pipe(Effect.mapError(persistenceError("stamp-polled")));
});
const takeApproved: DeviceAuthorizations["Service"]["takeApproved"] = Effect.fn(
"relay.device_authorizations.take_approved",
)(function* (deviceCodeHash) {
return firstOrNull(
yield* db
.delete(relayDeviceAuthorizations)
.where(
and(
eq(relayDeviceAuthorizations.deviceCodeHash, deviceCodeHash),
eq(relayDeviceAuthorizations.status, "approved"),
),
)
.returning()
.pipe(Effect.mapError(persistenceError("take-approved"))),
);
});
const deleteByDeviceCodeHash: DeviceAuthorizations["Service"]["deleteByDeviceCodeHash"] =
Effect.fn("relay.device_authorizations.delete")(function* (deviceCodeHash) {
yield* db
.delete(relayDeviceAuthorizations)
.where(eq(relayDeviceAuthorizations.deviceCodeHash, deviceCodeHash))
.pipe(Effect.mapError(persistenceError("delete")));
});
const pruneExpired: DeviceAuthorizations["Service"]["pruneExpired"] = Effect.gen(function* () {
const now = yield* DateTime.now;
const cutoff = DateTime.formatIso(now);
// Approved-but-unredeemed rows get a grace window so a completion near
// the expiry boundary can still be picked up by the next CLI poll.
const approvedCutoff = DateTime.formatIso(DateTime.subtract(now, { minutes: 10 }));
yield* Effect.annotateCurrentSpan({ "relay.device_authorization_prune.before": cutoff });
yield* db
.delete(relayDeviceAuthorizations)
.where(
or(
and(
lt(relayDeviceAuthorizations.expiresAt, cutoff),
ne(relayDeviceAuthorizations.status, "approved"),
),
lt(relayDeviceAuthorizations.expiresAt, approvedCutoff),
),
)
.pipe(Effect.mapError(persistenceError("prune-expired")));
}).pipe(Effect.withSpan("relay.device_authorizations.prune_expired"));
return DeviceAuthorizations.of({
create,
findByUserCode,
findByDeviceCodeHash,
beginApproval,
completeApproval,
deny,
stampPolled,
takeApproved,
deleteByDeviceCodeHash,
pruneExpired,
});
});
export const layer = Layer.effect(DeviceAuthorizations, make);
+1
View File
@@ -16,6 +16,7 @@ const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test/",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -63,6 +63,7 @@ function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {
const settings = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -30,6 +30,7 @@ const environmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {
});
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -25,6 +25,7 @@ const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
});
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
@@ -12,6 +12,7 @@ import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
const config = RelayConfiguration.RelayConfiguration.of({
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
environment: "sandbox",
teamId: "team-id",
+1
View File
@@ -32,6 +32,7 @@ vi.mock("@clerk/backend", () => ({
const relaySettings: RelayConfiguration.RelayConfiguration["Service"] = {
relayIssuer: "https://relay.example.test",
appBaseUrl: "https://app.example.test",
apns: {
teamId: "apns-team",
keyId: "apns-key",
+285
View File
@@ -5,6 +5,7 @@ import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Record from "effect/Record";
import * as Redacted from "effect/Redacted";
@@ -34,6 +35,9 @@ import {
RelayMobileRegistrationScope,
RelayAuthInvalidError,
type RelayAuthInvalidReason,
RelayDeviceAuthorizationNotFoundError,
RelayDeviceTokenPollError,
type RelayDeviceTokenPollCode,
RelayEnvironmentAuth,
RelayEnvironmentConnectNotAuthorizedError,
RelayEnvironmentEndpointTimedOutError,
@@ -47,9 +51,11 @@ import {
type RelayDpopAccessTokenScope,
RelayInternalError,
} from "@t3tools/contracts/relay";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt";
import * as DeliveryAttempts from "../agentActivity/DeliveryAttempts.ts";
import * as DeviceAuthorizations from "../auth/DeviceAuthorizations.ts";
import * as AgentActivityRows from "../agentActivity/AgentActivityRows.ts";
import * as Devices from "../agentActivity/Devices.ts";
import * as DpopProofs from "../auth/DpopProofs.ts";
@@ -623,6 +629,284 @@ export const tokenApi = HttpApiBuilder.group(
}),
);
const RELAY_DEVICE_AUTHORIZATION_TTL = Duration.minutes(15);
const RELAY_DEVICE_POLL_INTERVAL_SECONDS = 5;
// Consonant-only alphabet: no accidental words, no ambiguous I/O/0/1.
const RELAY_DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
const RELAY_DEVICE_USER_CODE_LENGTH = 8;
function normalizeDeviceUserCode(userCode: string): string {
return userCode.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "");
}
function formatDeviceUserCode(userCode: string): string {
return userCode.length === RELAY_DEVICE_USER_CODE_LENGTH
? `${userCode.slice(0, 4)}-${userCode.slice(4)}`
: userCode;
}
function deviceUserCodeFromBytes(bytes: Uint8Array): string {
let code = "";
for (let index = 0; index < RELAY_DEVICE_USER_CODE_LENGTH; index++) {
code +=
RELAY_DEVICE_USER_CODE_ALPHABET[(bytes[index] ?? 0) % RELAY_DEVICE_USER_CODE_ALPHABET.length];
}
return code;
}
function trimTrailingSlash(value: string): string {
return value.replace(/\/+$/u, "");
}
function hashDeviceCode(crypto: Crypto.Crypto, deviceCode: string) {
return crypto.digest("SHA-256", new TextEncoder().encode(deviceCode)).pipe(
Effect.map(Encoding.encodeHex),
Effect.catch(() => relayInternalErrorResponse("internal_error")),
);
}
function deviceAuthorizationDetails(record: DeviceAuthorizations.DeviceAuthorizationRecord) {
return {
userCode: formatDeviceUserCode(record.userCode),
status: record.status,
scope: record.scope,
deviceName: record.deviceName,
devicePlatform: record.devicePlatform,
clientVersion: record.clientVersion,
requestIp: record.requestIp,
requestLocation: record.requestLocation,
requestedAt: record.createdAt,
expiresAt: record.expiresAt,
};
}
const relayDeviceTokenPollError = Effect.fnUntraced(function* (code: RelayDeviceTokenPollCode) {
const traceId = yield* currentTraceId;
yield* Effect.annotateCurrentSpan({ "relay.device_authorization.poll_result": code });
return yield* new RelayDeviceTokenPollError({ code, traceId });
});
const relayDeviceAuthorizationNotFoundError = Effect.fnUntraced(function* () {
const traceId = yield* currentTraceId;
return yield* new RelayDeviceAuthorizationNotFoundError({
code: "device_authorization_not_found",
traceId,
});
});
export const deviceApi = HttpApiBuilder.group(
RelayApi,
"device",
Effect.fnUntraced(function* (handlers) {
const config = yield* RelayConfiguration.RelayConfiguration;
const crypto = yield* Crypto.Crypto;
const deviceAuthorizations = yield* DeviceAuthorizations.DeviceAuthorizations;
const appBaseUrl = trimTrailingSlash(config.appBaseUrl);
return handlers
.handle(
"authorizeDevice",
Effect.fn("relay.api.device.authorizeDevice")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const request = yield* HttpServerRequest.HttpServerRequest;
yield* Effect.annotateCurrentSpan({
"relay.oauth.client_id": args.payload.client_id,
});
// A fresh code pair is generated per attempt so a user-code
// collision on the unique index retries instead of failing the
// login request.
const issueAuthorization = Effect.gen(function* () {
const randomBytes = yield* crypto
.randomBytes(32 + RELAY_DEVICE_USER_CODE_LENGTH)
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
const deviceCode = Encoding.encodeBase64Url(randomBytes.slice(0, 32));
const deviceCodeHash = yield* hashDeviceCode(crypto, deviceCode);
const userCode = deviceUserCodeFromBytes(randomBytes.slice(32));
const now = yield* DateTime.now;
const expiresAt = DateTime.addDuration(now, RELAY_DEVICE_AUTHORIZATION_TTL);
yield* deviceAuthorizations.create({
deviceCodeHash,
userCode,
clientId: args.payload.client_id,
scope: args.payload.scope,
codeChallenge: args.payload.code_challenge,
deviceName: args.payload.device_name ?? null,
devicePlatform: args.payload.device_platform ?? null,
clientVersion: args.payload.client_version ?? null,
requestIp: request.headers["cf-connecting-ip"] ?? null,
requestLocation: request.headers["cf-ipcountry"] ?? null,
pollIntervalSeconds: RELAY_DEVICE_POLL_INTERVAL_SECONDS,
expiresAt,
});
return { deviceCode, userCode };
});
const issued = yield* issueAuthorization.pipe(
Effect.retry({
times: 2,
while: (error) => error._tag === "DeviceAuthorizationPersistenceError",
}),
);
const formattedUserCode = formatDeviceUserCode(issued.userCode);
return {
device_code: issued.deviceCode,
user_code: formattedUserCode,
verification_uri: `${appBaseUrl}/oauth/device`,
verification_uri_complete: `${appBaseUrl}/oauth/device?user_code=${formattedUserCode}`,
expires_in: Duration.toSeconds(RELAY_DEVICE_AUTHORIZATION_TTL),
interval: RELAY_DEVICE_POLL_INTERVAL_SECONDS,
};
}, mapRelayCommonApiErrors("not_authorized")),
)
.handle(
"redeemDeviceCode",
Effect.fn("relay.api.device.redeemDeviceCode")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const deviceCodeHash = yield* hashDeviceCode(crypto, args.payload.device_code);
const record = yield* deviceAuthorizations.findByDeviceCodeHash(deviceCodeHash);
if (record === null || record.clientId !== args.payload.client_id) {
return yield* relayDeviceTokenPollError("expired_token");
}
const now = yield* DateTime.now;
// Approved rows stay redeemable past expiry (until pruning) so a
// completion near the deadline is not lost to the next poll.
if (record.status === "approved") {
const granted = yield* deviceAuthorizations.takeApproved(deviceCodeHash);
if (granted?.authorizationCode && granted.redirectUri) {
return {
authorization_code: granted.authorizationCode,
redirect_uri: granted.redirectUri,
};
}
return yield* relayDeviceTokenPollError("expired_token");
}
if (record.status === "denied") {
yield* deviceAuthorizations.deleteByDeviceCodeHash(deviceCodeHash);
return yield* relayDeviceTokenPollError("access_denied");
}
if (record.expiresAt <= DateTime.formatIso(now)) {
yield* deviceAuthorizations.deleteByDeviceCodeHash(deviceCodeHash);
return yield* relayDeviceTokenPollError("expired_token");
}
const polledTooFast =
record.lastPolledAt !== null &&
Date.parse(record.lastPolledAt) + (record.pollIntervalSeconds - 1) * 1_000 >
now.epochMilliseconds;
yield* deviceAuthorizations.stampPolled({ deviceCodeHash, now });
return yield* relayDeviceTokenPollError(
polledTooFast ? "slow_down" : "authorization_pending",
);
}, mapRelayCommonApiErrors("not_authorized")),
);
}),
);
export const deviceApprovalApi = HttpApiBuilder.group(
RelayApi,
"deviceApproval",
Effect.fnUntraced(function* (handlers) {
const config = yield* RelayConfiguration.RelayConfiguration;
const crypto = yield* Crypto.Crypto;
const deviceAuthorizations = yield* DeviceAuthorizations.DeviceAuthorizations;
const appBaseUrl = trimTrailingSlash(config.appBaseUrl);
return handlers
.handle(
"getDeviceAuthorization",
Effect.fn("relay.api.device_approval.getDeviceAuthorization")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const record = yield* deviceAuthorizations.findByUserCode(
normalizeDeviceUserCode(args.params.userCode),
);
const now = DateTime.formatIso(yield* DateTime.now);
if (record === null || record.expiresAt <= now) {
return yield* relayDeviceAuthorizationNotFoundError();
}
return deviceAuthorizationDetails(record);
}, mapRelayCommonApiErrors("not_authorized")),
)
.handle(
"approveDeviceAuthorization",
Effect.fn("relay.api.device_approval.approveDeviceAuthorization")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const { userId } = yield* RelayClientPrincipal;
yield* Effect.annotateCurrentSpan({ "user.id": userId });
const userCode = normalizeDeviceUserCode(args.params.userCode);
const requestedState = yield* crypto.randomUUIDv4.pipe(
Effect.catch(() => relayInternalErrorResponse("internal_error")),
);
const now = yield* DateTime.now;
// beginApproval only claims rows without a callback state. A reload
// or second tab reuses the already-issued state so the first Clerk
// redirect still completes.
const claimed = yield* deviceAuthorizations.beginApproval({
userCode,
callbackState: requestedState,
redirectUri: `${appBaseUrl}/oauth/device/callback`,
now,
});
const record = claimed ?? (yield* deviceAuthorizations.findByUserCode(userCode));
if (
record === null ||
record.status !== "pending" ||
record.expiresAt <= DateTime.formatIso(now) ||
record.callbackState === null ||
record.redirectUri === null
) {
return yield* relayDeviceAuthorizationNotFoundError();
}
const clerkFrontendApiUrl = yield* Effect.try({
try: () => clerkFrontendApiUrlFromPublishableKey(config.clerkPublishableKey),
catch: (cause) => new ClerkTokenVerificationFailed({ cause }),
}).pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
const authorizationUrl = new URL(`${clerkFrontendApiUrl}/oauth/authorize`);
authorizationUrl.searchParams.set("client_id", record.clientId);
authorizationUrl.searchParams.set("redirect_uri", record.redirectUri);
authorizationUrl.searchParams.set("response_type", "code");
authorizationUrl.searchParams.set("scope", record.scope);
authorizationUrl.searchParams.set("state", record.callbackState);
authorizationUrl.searchParams.set("code_challenge", record.codeChallenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
return { authorizationUrl: authorizationUrl.toString() };
}, mapRelayCommonApiErrors("not_authorized")),
)
.handle(
"completeDeviceAuthorization",
Effect.fn("relay.api.device_approval.completeDeviceAuthorization")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const { userId } = yield* RelayClientPrincipal;
yield* Effect.annotateCurrentSpan({ "user.id": userId });
const now = yield* DateTime.now;
const record = yield* deviceAuthorizations.completeApproval({
callbackState: args.payload.state,
authorizationCode: args.payload.code,
userId,
now,
});
if (record === null) {
return yield* relayDeviceAuthorizationNotFoundError();
}
return { ok: true };
}, mapRelayCommonApiErrors("not_authorized")),
)
.handle(
"denyDeviceAuthorization",
Effect.fn("relay.api.device_approval.denyDeviceAuthorization")(function* (args) {
yield* appendRelayCredentialResponseHeaders;
const { userId } = yield* RelayClientPrincipal;
yield* Effect.annotateCurrentSpan({ "user.id": userId });
const now = yield* DateTime.now;
const record = yield* deviceAuthorizations.deny({
userCode: normalizeDeviceUserCode(args.params.userCode),
userId,
now,
});
if (record === null) {
return yield* relayDeviceAuthorizationNotFoundError();
}
return { ok: true };
}, mapRelayCommonApiErrors("not_authorized")),
);
}),
);
export const dpopClientApi = HttpApiBuilder.group(
RelayApi,
"dpopClient",
@@ -893,6 +1177,7 @@ const RelayCommonPersistenceError = Schema.Union([
EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError,
EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError,
DpopProofs.DpopProofReplayPersistenceError,
DeviceAuthorizations.DeviceAuthorizationPersistenceError,
LiveActivities.LiveActivityTargetListPersistenceError,
AgentActivityRows.AgentActivityRowUpsertPersistenceError,
AgentActivityRows.AgentActivityRowDeletePersistenceError,
+31
View File
@@ -168,6 +168,37 @@ export const relayDeliveryAttempts = pgTable(
],
);
export const relayDeviceAuthorizations = pgTable(
"relay_device_authorizations",
{
deviceCodeHash: varchar("device_code_hash", { length: 64 }).primaryKey(),
userCode: varchar("user_code", { length: 16 }).notNull(),
clientId: varchar("client_id", { length: 191 }).notNull(),
scope: text("scope").notNull(),
codeChallenge: varchar("code_challenge", { length: 128 }).notNull(),
status: varchar("status", { length: 16 }).notNull().$type<"pending" | "approved" | "denied">(),
userId: varchar("user_id", { length: 255 }),
callbackState: varchar("callback_state", { length: 64 }),
redirectUri: text("redirect_uri"),
authorizationCode: text("authorization_code"),
deviceName: text("device_name"),
devicePlatform: varchar("device_platform", { length: 128 }),
clientVersion: varchar("client_version", { length: 64 }),
requestIp: varchar("request_ip", { length: 64 }),
requestLocation: varchar("request_location", { length: 191 }),
pollIntervalSeconds: integer("poll_interval_seconds").notNull(),
lastPolledAt: varchar("last_polled_at", { length: 64 }),
expiresAt: varchar("expires_at", { length: 64 }).notNull(),
createdAt: varchar("created_at", { length: 64 }).notNull(),
updatedAt: varchar("updated_at", { length: 64 }).notNull(),
},
(table) => [
uniqueIndex("idx_relay_device_authorizations_user_code").on(table.userCode),
uniqueIndex("idx_relay_device_authorizations_callback_state").on(table.callbackState),
index("idx_relay_device_authorizations_expires_at").on(table.expiresAt),
],
);
export const relayDpopProofs = pgTable(
"relay_dpop_proofs",
{
+35 -6
View File
@@ -4,6 +4,7 @@ import * as Drizzle from "alchemy/Drizzle";
import * as Config from "effect/Config";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import * as Etag from "effect/unstable/http/Etag";
@@ -16,6 +17,8 @@ import { RelayApi } from "@t3tools/contracts/relay";
import {
clientApi,
deviceApi,
deviceApprovalApi,
dpopClientApi,
healthApi,
metadataApi,
@@ -36,6 +39,7 @@ import { makeRelayTraceLayer, RelayObservability } from "./observability.ts";
import * as DeliveryAttempts from "./agentActivity/DeliveryAttempts.ts";
import * as AgentActivityRows from "./agentActivity/AgentActivityRows.ts";
import * as Devices from "./agentActivity/Devices.ts";
import * as DeviceAuthorizations from "./auth/DeviceAuthorizations.ts";
import * as DpopProofs from "./auth/DpopProofs.ts";
import * as RelayTokens from "./auth/RelayTokens.ts";
import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts";
@@ -79,6 +83,8 @@ const relayApiLayer = Layer.mergeAll(
mobileApi,
clientApi,
tokenApi,
deviceApi,
deviceApprovalApi,
dpopClientApi,
serverApi,
);
@@ -135,6 +141,11 @@ export default class Api extends Cloudflare.Worker<Api>()(
const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY");
const clerkPublishableKey = yield* Config.string("CLERK_PUBLISHABLE_KEY");
const clerkJwtAudience = yield* Config.string("CLERK_JWT_AUDIENCE");
// The default only fits prod: a stage relay needs a web app build that
// targets that same stage, so non-prod deploys must set the URL explicitly.
const appBaseUrl = yield* stage === "prod"
? Config.string("T3CODE_APP_BASE_URL").pipe(Config.withDefault("https://app.t3.codes"))
: Config.string("T3CODE_APP_BASE_URL");
const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey;
const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey;
@@ -155,6 +166,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
const loadSettings = Effect.gen(function* () {
return RelayConfiguration.RelayConfiguration.of({
relayIssuer: relayPublicOrigin,
appBaseUrl,
apns: {
environment,
teamId: apnsTeamId,
@@ -194,7 +206,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
alchemyRuntimeContext,
),
),
Layer.provideMerge(DpopProofs.layer),
Layer.provideMerge(Layer.mergeAll(DpopProofs.layer, DeviceAuthorizations.layer)),
Layer.provideMerge(ApnsDeliveries.layer),
Layer.provideMerge(ApnsClient.layer),
Layer.provideMerge(
@@ -239,12 +251,29 @@ export default class Api extends Cloudflare.Worker<Api>()(
),
);
// Each prune runs to completion even when the other fails; a failure in
// one must not leave the other's expired rows behind for a whole cycle.
yield* Cloudflare.cron("*/5 * * * *").subscribe(() =>
DpopProofs.DpopProofReplay.pipe(
Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired),
Effect.withSpan("relay.cron.prune_expired_dpop_proofs"),
Effect.provide(runtimeLayer),
),
Effect.gen(function* () {
const dpopPruneExit = yield* Effect.exit(
DpopProofs.DpopProofReplay.pipe(
Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired),
Effect.withSpan("relay.cron.prune_expired_dpop_proofs"),
),
);
const devicePruneExit = yield* Effect.exit(
DeviceAuthorizations.DeviceAuthorizations.pipe(
Effect.flatMap((deviceAuthorizations) => deviceAuthorizations.pruneExpired),
Effect.withSpan("relay.cron.prune_expired_device_authorizations"),
),
);
if (Exit.isFailure(dpopPruneExit)) {
return yield* Effect.failCause(dpopPruneExit.cause);
}
if (Exit.isFailure(devicePruneExit)) {
return yield* Effect.failCause(devicePruneExit.cause);
}
}).pipe(Effect.provide(runtimeLayer)),
);
const fetch = Layer.merge(
@@ -70,6 +70,15 @@ function relayProtectedError(error: RelayProtectedError): ConnectionAttemptError
detail: error.message,
traceId: error.traceId,
});
case "RelayDeviceTokenPollError":
case "RelayDeviceAuthorizationNotFoundError":
// Device-authorization errors never occur while connecting to an
// environment; map them defensively as configuration problems.
return new ConnectionBlockedError({
reason: "configuration",
detail: error.message,
traceId: error.traceId,
});
}
}
@@ -84,6 +84,10 @@ function relayClient(
registerDevice: () => unsupported("registerDevice"),
unregisterDevice: () => unsupported("unregisterDevice"),
registerLiveActivity: () => unsupported("registerLiveActivity"),
getDeviceAuthorization: () => unsupported("getDeviceAuthorization"),
approveDeviceAuthorization: () => unsupported("approveDeviceAuthorization"),
completeDeviceAuthorization: () => unsupported("completeDeviceAuthorization"),
denyDeviceAuthorization: () => unsupported("denyDeviceAuthorization"),
resetTokenCache: Effect.void,
});
}
@@ -112,6 +112,10 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
registerDevice: () => Effect.die("unused"),
unregisterDevice: () => Effect.die("unused"),
registerLiveActivity: () => Effect.die("unused"),
getDeviceAuthorization: () => Effect.die("unused"),
approveDeviceAuthorization: () => Effect.die("unused"),
completeDeviceAuthorization: () => Effect.die("unused"),
denyDeviceAuthorization: () => Effect.die("unused"),
resetTokenCache: Effect.void,
} satisfies ManagedRelay.ManagedRelayClient["Service"]);
const connectivity = Connectivity.Connectivity.of({
@@ -272,6 +276,10 @@ describe("RelayEnvironmentDiscovery", () => {
registerDevice: () => Effect.die("unused"),
unregisterDevice: () => Effect.die("unused"),
registerLiveActivity: () => Effect.die("unused"),
getDeviceAuthorization: () => Effect.die("unused"),
approveDeviceAuthorization: () => Effect.die("unused"),
completeDeviceAuthorization: () => Effect.die("unused"),
denyDeviceAuthorization: () => Effect.die("unused"),
resetTokenCache: Effect.void,
} satisfies ManagedRelay.ManagedRelayClient["Service"]);
const layer = RelayEnvironmentDiscovery.layer.pipe(
@@ -4,6 +4,9 @@ import {
type RelayClientEnvironmentRecord,
type RelayClientDeviceRecord,
RelayConnectEnvironmentEndpoint,
type RelayDeviceApprovalResponse,
type RelayDeviceAuthorizationDetails,
type RelayDeviceCompletionRequest,
type RelayDeviceRegistrationRequest,
RelayDpopAccessTokenScope,
RelayDpopTokenExchangeGrantType,
@@ -92,6 +95,10 @@ export const ManagedRelayRequestAction = Schema.Literals([
"register relay mobile device",
"unregister relay mobile device",
"register relay live activity",
"get relay device authorization",
"approve relay device authorization",
"complete relay device authorization",
"deny relay device authorization",
]);
export type ManagedRelayRequestAction = typeof ManagedRelayRequestAction.Type;
@@ -107,6 +114,10 @@ export const ManagedRelayRequestActivity = Schema.Literals([
"Relay mobile device registration",
"Relay mobile device unregistration",
"Relay Live Activity registration",
"Relay device authorization lookup",
"Relay device authorization approval",
"Relay device authorization completion",
"Relay device authorization denial",
]);
export type ManagedRelayRequestActivity = typeof ManagedRelayRequestActivity.Type;
@@ -286,6 +297,22 @@ export class ManagedRelayClient extends Context.Service<
readonly clerkToken: string;
readonly payload: RelayLiveActivityRegistrationRequest;
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
readonly getDeviceAuthorization: (input: {
readonly clerkToken: string;
readonly userCode: string;
}) => Effect.Effect<RelayDeviceAuthorizationDetails, ManagedRelayClientError>;
readonly approveDeviceAuthorization: (input: {
readonly clerkToken: string;
readonly userCode: string;
}) => Effect.Effect<RelayDeviceApprovalResponse, ManagedRelayClientError>;
readonly completeDeviceAuthorization: (input: {
readonly clerkToken: string;
readonly payload: RelayDeviceCompletionRequest;
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
readonly denyDeviceAuthorization: (input: {
readonly clerkToken: string;
readonly userCode: string;
}) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;
readonly resetTokenCache: Effect.Effect<void>;
}
>()("@t3tools/client-runtime/relay/managedRelay/ManagedRelayClient") {}
@@ -399,6 +426,14 @@ function disabledManagedRelayClient(relayUrl: string): ManagedRelayClient["Servi
registerDevice: unavailable("clientRuntime.managedRelay.registerDevice"),
unregisterDevice: unavailable("clientRuntime.managedRelay.unregisterDevice"),
registerLiveActivity: unavailable("clientRuntime.managedRelay.registerLiveActivity"),
getDeviceAuthorization: unavailable("clientRuntime.managedRelay.getDeviceAuthorization"),
approveDeviceAuthorization: unavailable(
"clientRuntime.managedRelay.approveDeviceAuthorization",
),
completeDeviceAuthorization: unavailable(
"clientRuntime.managedRelay.completeDeviceAuthorization",
),
denyDeviceAuthorization: unavailable("clientRuntime.managedRelay.denyDeviceAuthorization"),
resetTokenCache: Effect.void.pipe(
Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
),
@@ -867,6 +902,66 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* (
Effect.withSpan("clientRuntime.managedRelay.registerLiveActivity"),
withRelayClientTracing,
),
getDeviceAuthorization: Effect.fnUntraced(
function* (input) {
return yield* client.deviceApproval
.getDeviceAuthorization({
headers: bearerHeaders(input.clerkToken),
params: { userCode: input.userCode },
})
.pipe(
Effect.mapError(relayRequestError("get relay device authorization")),
timeoutRelayRequest("Relay device authorization lookup"),
);
},
Effect.withSpan("clientRuntime.managedRelay.getDeviceAuthorization"),
withRelayClientTracing,
),
approveDeviceAuthorization: Effect.fnUntraced(
function* (input) {
return yield* client.deviceApproval
.approveDeviceAuthorization({
headers: bearerHeaders(input.clerkToken),
params: { userCode: input.userCode },
})
.pipe(
Effect.mapError(relayRequestError("approve relay device authorization")),
timeoutRelayRequest("Relay device authorization approval"),
);
},
Effect.withSpan("clientRuntime.managedRelay.approveDeviceAuthorization"),
withRelayClientTracing,
),
completeDeviceAuthorization: Effect.fnUntraced(
function* (input) {
return yield* client.deviceApproval
.completeDeviceAuthorization({
headers: bearerHeaders(input.clerkToken),
payload: input.payload,
})
.pipe(
Effect.mapError(relayRequestError("complete relay device authorization")),
timeoutRelayRequest("Relay device authorization completion"),
);
},
Effect.withSpan("clientRuntime.managedRelay.completeDeviceAuthorization"),
withRelayClientTracing,
),
denyDeviceAuthorization: Effect.fnUntraced(
function* (input) {
return yield* client.deviceApproval
.denyDeviceAuthorization({
headers: bearerHeaders(input.clerkToken),
params: { userCode: input.userCode },
})
.pipe(
Effect.mapError(relayRequestError("deny relay device authorization")),
timeoutRelayRequest("Relay device authorization denial"),
);
},
Effect.withSpan("clientRuntime.managedRelay.denyDeviceAuthorization"),
withRelayClientTracing,
),
resetTokenCache: SynchronizedRef.set(cachedTokens, []).pipe(
Effect.andThen(options.accessTokenStore ? options.accessTokenStore.clear : Effect.void),
Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
@@ -83,6 +83,10 @@ function createManager(
registerDevice: () => Effect.die("unused"),
unregisterDevice: () => Effect.die("unused"),
registerLiveActivity: () => Effect.die("unused"),
getDeviceAuthorization: () => Effect.die("unused"),
approveDeviceAuthorization: () => Effect.die("unused"),
completeDeviceAuthorization: () => Effect.die("unused"),
denyDeviceAuthorization: () => Effect.die("unused"),
resetTokenCache: Effect.void,
...overrides,
});
+215
View File
@@ -457,6 +457,40 @@ export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErr
}
}
export const RelayDeviceTokenPollCode = Schema.Literals([
"authorization_pending",
"slow_down",
"access_denied",
"expired_token",
]);
export type RelayDeviceTokenPollCode = typeof RelayDeviceTokenPollCode.Type;
export class RelayDeviceTokenPollError extends Schema.TaggedErrorClass<RelayDeviceTokenPollError>()(
"RelayDeviceTokenPollError",
{
code: RelayDeviceTokenPollCode,
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 400 },
) {
override get message(): string {
return `Relay device authorization is not redeemable: ${this.code}`;
}
}
export class RelayDeviceAuthorizationNotFoundError extends Schema.TaggedErrorClass<RelayDeviceAuthorizationNotFoundError>()(
"RelayDeviceAuthorizationNotFoundError",
{
code: Schema.Literal("device_authorization_not_found"),
traceId: TrimmedNonEmptyString,
},
{ httpApiStatus: 404 },
) {
override get message(): string {
return "Relay device authorization was not found, already handled, or expired.";
}
}
export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalError>()(
"RelayInternalError",
{
@@ -473,6 +507,8 @@ export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalErr
export const RelayProtectedError = Schema.Union([
RelayAuthInvalidError,
RelayDeviceTokenPollError,
RelayDeviceAuthorizationNotFoundError,
RelayEnvironmentLinkProofExpiredError,
RelayEnvironmentLinkProofInvalidError,
RelayEnvironmentConnectNotAuthorizedError,
@@ -654,6 +690,116 @@ export const RelayDpopAccessTokenResponse = Schema.Struct({
});
export type RelayDpopAccessTokenResponse = typeof RelayDpopAccessTokenResponse.Type;
export const RelayDeviceAuthorizationGrantType =
"urn:ietf:params:oauth:grant-type:device_code" as const;
// Bounds mirror the relay_device_authorizations column widths so overlong
// input fails request validation instead of surfacing as a persistence error.
const RelayDeviceClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(191));
const RelayDeviceScope = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
const RelayDeviceCodeChallenge = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
export const RelayDeviceAuthorizationRequest = Schema.Struct({
client_id: RelayDeviceClientId.annotate({
description: "Clerk OAuth client id of the CLI requesting device authorization.",
}),
scope: RelayDeviceScope.annotate({
description: "Space-separated OAuth scopes requested from Clerk.",
}),
code_challenge: RelayDeviceCodeChallenge.annotate({
description: "PKCE code challenge generated by the device.",
}),
code_challenge_method: Schema.Literal("S256"),
device_name: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(191)).annotate({
description: "Human-readable device name shown on the approval page.",
}),
),
device_platform: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(128)).annotate({
description: "Platform descriptor shown on the approval page.",
}),
),
client_version: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(64)).annotate({
description: "CLI version shown on the approval page.",
}),
),
})
.annotate({ description: "Starts an OAuth device authorization for a browserless client." })
.pipe(HttpApiSchema.asFormUrlEncoded());
export type RelayDeviceAuthorizationRequest = typeof RelayDeviceAuthorizationRequest.Type;
export const RelayDeviceAuthorizationResponse = Schema.Struct({
device_code: TrimmedNonEmptyString,
user_code: TrimmedNonEmptyString,
verification_uri: TrimmedNonEmptyString,
verification_uri_complete: TrimmedNonEmptyString,
expires_in: Schema.Int.check(Schema.isGreaterThan(0)),
interval: Schema.Int.check(Schema.isGreaterThan(0)),
});
export type RelayDeviceAuthorizationResponse = typeof RelayDeviceAuthorizationResponse.Type;
export const RelayDeviceTokenRequest = Schema.Struct({
grant_type: Schema.Literal(RelayDeviceAuthorizationGrantType),
device_code: TrimmedNonEmptyString.check(Schema.isMaxLength(128)),
client_id: RelayDeviceClientId,
})
.annotate({ description: "Polls a pending device authorization for its granted code." })
.pipe(HttpApiSchema.asFormUrlEncoded());
export type RelayDeviceTokenRequest = typeof RelayDeviceTokenRequest.Type;
export const RelayDeviceTokenResponse = Schema.Struct({
authorization_code: TrimmedNonEmptyString.annotate({
description:
"Clerk authorization code bound to the device's PKCE challenge. The device exchanges it directly at the Clerk token endpoint.",
}),
redirect_uri: TrimmedNonEmptyString.annotate({
description: "Redirect URI used in the brokered authorization; echo it in the token exchange.",
}),
});
export type RelayDeviceTokenResponse = typeof RelayDeviceTokenResponse.Type;
export const RelayDeviceAuthorizationStatus = Schema.Literals(["pending", "approved", "denied"]);
export type RelayDeviceAuthorizationStatus = typeof RelayDeviceAuthorizationStatus.Type;
export const RelayDeviceAuthorizationDetails = Schema.Struct({
userCode: TrimmedNonEmptyString,
status: RelayDeviceAuthorizationStatus,
scope: TrimmedNonEmptyString,
deviceName: Schema.NullOr(Schema.String),
devicePlatform: Schema.NullOr(Schema.String),
clientVersion: Schema.NullOr(Schema.String),
requestIp: Schema.NullOr(Schema.String),
requestLocation: Schema.NullOr(Schema.String),
requestedAt: TrimmedNonEmptyString,
expiresAt: TrimmedNonEmptyString,
});
export type RelayDeviceAuthorizationDetails = typeof RelayDeviceAuthorizationDetails.Type;
export const RelayDeviceAuthorizationParams = Schema.Struct({
userCode: TrimmedNonEmptyString.check(Schema.isMaxLength(32)),
});
export type RelayDeviceAuthorizationParams = typeof RelayDeviceAuthorizationParams.Type;
export const RelayDeviceApprovalResponse = Schema.Struct({
authorizationUrl: TrimmedNonEmptyString.annotate({
description:
"Clerk authorize URL the approving browser must visit to mint the device's authorization code.",
}),
});
export type RelayDeviceApprovalResponse = typeof RelayDeviceApprovalResponse.Type;
export const RelayDeviceCompletionRequest = Schema.Struct({
state: TrimmedNonEmptyString.check(Schema.isMaxLength(64)).annotate({
description: "Opaque state returned by the approval step and echoed by Clerk.",
}),
code: TrimmedNonEmptyString.check(Schema.isMaxLength(512)).annotate({
description: "Authorization code issued by Clerk for the approved device.",
}),
});
export type RelayDeviceCompletionRequest = typeof RelayDeviceCompletionRequest.Type;
export const RelayBearerRequestHeaders = Schema.Struct({
authorization: TrimmedNonEmptyString,
});
@@ -942,6 +1088,73 @@ export const RelayTokenGroup = HttpApiGroup.make("token")
.add(RelayExchangeDpopAccessTokenEndpoint)
.annotate(OpenApi.Description, "OAuth token exchange for DPoP-bound client access.");
const RelayDeviceTokenErrors = [RelayDeviceTokenPollError, RelayInternalError] as const;
const RelayDeviceApprovalErrors = [
RelayAuthInvalidError,
RelayDeviceAuthorizationNotFoundError,
RelayInternalError,
] as const;
export const RelayDeviceGroup = HttpApiGroup.make("device")
.add(
HttpApiEndpoint.post("authorizeDevice", "/v1/device/authorization", {
payload: RelayDeviceAuthorizationRequest,
success: RelayDeviceAuthorizationResponse,
error: RelayInternalError,
}).annotate(OpenApi.Summary, "Start a device authorization"),
HttpApiEndpoint.post("redeemDeviceCode", "/v1/device/token", {
payload: RelayDeviceTokenRequest,
success: RelayDeviceTokenResponse,
error: RelayDeviceTokenErrors,
}).annotate(OpenApi.Summary, "Poll a device authorization for its granted code"),
)
.annotate(
OpenApi.Description,
"OAuth device authorization for browserless CLIs, brokered through the Clerk authorization-code flow.",
);
export const RelayDeviceApprovalGroup = HttpApiGroup.make("deviceApproval")
.add(
HttpApiEndpoint.get("getDeviceAuthorization", "/v1/client/device-authorizations/:userCode", {
headers: RelayBearerRequestHeaders,
params: RelayDeviceAuthorizationParams,
success: RelayDeviceAuthorizationDetails,
error: RelayDeviceApprovalErrors,
}).annotate(OpenApi.Summary, "Look up a pending device authorization by user code"),
HttpApiEndpoint.post(
"approveDeviceAuthorization",
"/v1/client/device-authorizations/:userCode/approve",
{
headers: RelayBearerRequestHeaders,
params: RelayDeviceAuthorizationParams,
success: RelayDeviceApprovalResponse,
error: RelayDeviceApprovalErrors,
},
).annotate(OpenApi.Summary, "Approve a device authorization"),
HttpApiEndpoint.post(
"completeDeviceAuthorization",
"/v1/client/device-authorizations/complete",
{
headers: RelayBearerRequestHeaders,
payload: RelayDeviceCompletionRequest,
success: RelayOkResponse,
error: RelayDeviceApprovalErrors,
},
).annotate(OpenApi.Summary, "Attach the Clerk authorization code to an approved device"),
HttpApiEndpoint.post(
"denyDeviceAuthorization",
"/v1/client/device-authorizations/:userCode/deny",
{
headers: RelayBearerRequestHeaders,
params: RelayDeviceAuthorizationParams,
success: RelayOkResponse,
error: RelayDeviceApprovalErrors,
},
).annotate(OpenApi.Summary, "Deny a device authorization"),
)
.annotate(OpenApi.Description, "Signed-in approval surface for pending device authorizations.")
.middleware(RelayClientAuth);
export const RelayConnectEnvironmentEndpoint = HttpApiEndpoint.post(
"connectEnvironment",
"/v1/environments/:environmentId/connect",
@@ -1000,6 +1213,8 @@ export const RelayApi = HttpApi.make("RelayApi")
RelayMobileGroup,
RelayClientGroup,
RelayTokenGroup,
RelayDeviceGroup,
RelayDeviceApprovalGroup,
RelayDpopClientGroup,
RelayServerGroup,
)