diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts index 0dc9ea4766..4c27f18197 100644 --- a/apps/server/src/cloud/CliTokenManager.ts +++ b/apps/server/src/cloud/CliTokenManager.ts @@ -132,6 +132,19 @@ const wrapError = (effect: Effect.Effect): Effect.Effect => 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 = + (makeError: (cause: unknown) => WrappedError) => + ( + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.mapError((cause) => (isCloudCliTokenManagerError(cause) ? cause : makeError(cause))), + ); + function stringToBytes(value: string): Uint8Array { return new TextEncoder().encode(value); } @@ -329,14 +342,17 @@ export const make = Effect.gen(function* () { }); case "expired_token": return yield* new CloudCliAuthorizationTimeoutError({ - cause: "The device authorization request expired before it was approved.", + 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)), + Effect.timeout(Duration.seconds(authorization.expires_in + authorization.interval + 5)), Effect.catchTag("TimeoutError", (cause) => Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })), ), @@ -376,7 +392,7 @@ 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* () { @@ -384,7 +400,7 @@ export const make = Effect.gen(function* () { return Option.isSome(token) ? token.value : yield* loginDevice().pipe(Effect.flatMap(persist)); - }).pipe(wrapError((cause) => new CloudCliAuthorizationError({ cause }))), + }).pipe(wrapUnknownError((cause) => new CloudCliAuthorizationError({ cause }))), ); return CloudCliTokenManager.of({ get, getWithDeviceLogin, getExisting, hasCredential, clear }); diff --git a/apps/web/src/components/auth/DeviceAuthorizationSurface.tsx b/apps/web/src/components/auth/DeviceAuthorizationSurface.tsx index 27cd3f3799..28e7c974b1 100644 --- a/apps/web/src/components/auth/DeviceAuthorizationSurface.tsx +++ b/apps/web/src/components/auth/DeviceAuthorizationSurface.tsx @@ -143,18 +143,28 @@ function ConfiguredDeviceAuthorizationSurface({ const [state, setState] = useState({ 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" }); diff --git a/docs/cloud/t3-connect-clerk.md b/docs/cloud/t3-connect-clerk.md index 2e349b8dca..78afa96337 100644 --- a/docs/cloud/t3-connect-clerk.md +++ b/docs/cloud/t3-connect-clerk.md @@ -42,10 +42,11 @@ 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`, plus the optional -`T3CODE_APP_BASE_URL` (web app origin for device-code login, default `https://app.t3.codes`; a -non-production stage should point it at a web app build that targets the same stage relay and Clerk -instance). Other than that default, there are no checked-in deployment defaults. +`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` with the deployed HTTPS relay URL. The relay still requires diff --git a/infra/relay/.env.example b/infra/relay/.env.example index 7d46b17b78..163c82bf33 100644 --- a/infra/relay/.env.example +++ b/infra/relay/.env.example @@ -9,15 +9,15 @@ RELAY_TUNNEL_ZONE_NAME=tunnels.example.com # Set this only when the derived relay hostname should not be used. # RELAY_DOMAIN=relay.example.com -# Optional: Hosted web app origin for device-code login +# Hosted web app origin for device-code login # `t3 connect login --device` sends users to /oauth/device and the # approval flow returns through /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. Defaults to https://app.t3.codes, which is only correct for the -# production stage; personal stages should point at their own app build (for -# local testing, e.g. http://localhost:5733). -# T3CODE_APP_BASE_URL=https://app.t3.codes +# 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 diff --git a/infra/relay/README.md b/infra/relay/README.md index 6778f5b712..f714f36240 100644 --- a/infra/relay/README.md +++ b/infra/relay/README.md @@ -87,10 +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. The optional -`T3CODE_APP_BASE_URL` selects the web app origin used by device-code login; it defaults to -`https://app.t3.codes`, which is only correct for `prod` — see the comment in `.env.example` for -personal stages. 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. diff --git a/infra/relay/migrations/postgres/20260707053647_device_authorizations/migration.sql b/infra/relay/migrations/postgres/20260707053647_device_authorizations/migration.sql new file mode 100644 index 0000000000..1d39eebaf8 --- /dev/null +++ b/infra/relay/migrations/postgres/20260707053647_device_authorizations/migration.sql @@ -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"); diff --git a/infra/relay/migrations/postgres/20260707053647_device_authorizations/snapshot.json b/infra/relay/migrations/postgres/20260707053647_device_authorizations/snapshot.json new file mode 100644 index 0000000000..af8b04a006 --- /dev/null +++ b/infra/relay/migrations/postgres/20260707053647_device_authorizations/snapshot.json @@ -0,0 +1,1790 @@ +{ + "dialect": "postgres", + "id": "6f7dd204-4cd8-45b0-ac98-0234a71b9748", + "prevIds": ["385d476b-d4f6-48a3-99e6-0a95af4ee4e4"], + "version": "8", + "ddl": [ + { + "isRlsEnabled": false, + "name": "relay_agent_activity_rows", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_delivery_attempts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_device_authorizations", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_dpop_proofs", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_credentials", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_links", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_live_activities", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_managed_endpoint_allocations", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_mobile_devices", + "entityType": "tables", + "schema": "public" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "state_json", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(36)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_job_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token_suffix", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_status", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_reason", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "transport_error", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_code_hash", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_code", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "client_id", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "scope", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "code_challenge", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "status", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "callback_state", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "redirect_uri", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "authorization_code", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_name", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_platform", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "client_version", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "request_ip", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "request_location", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "poll_interval_seconds", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_polled_at", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thumbprint", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "jti", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iat", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_hash", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'T3 Environment'", + "generated": null, + "identity": null, + "name": "environment_label", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_http_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_ws_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(32)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_provider_kind", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "notifications_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "live_activities_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "managed_tunnels_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_by_device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_start_queued_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_started_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ended_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_aggregate_json", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_live_activity_delivery_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "hostname", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_name", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "dns_record_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ready_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'iOS device'", + "generated": null, + "identity": null, + "name": "label", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "platform", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ios_major_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "app_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_to_start_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "preferences_json", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "updated_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_agent_activity_rows_updated", + "entityType": "indexes", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "thread_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "created_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "source_job_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_source_job", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_code", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_device_authorizations_user_code", + "entityType": "indexes", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "callback_state", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_device_authorizations_callback_state", + "entityType": "indexes", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "expires_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_device_authorizations_expires_at", + "entityType": "indexes", + "schema": "public", + "table": "relay_device_authorizations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "expires_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_dpop_proofs_expires_at", + "entityType": "indexes", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "credential_hash", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_hash", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "environment_public_key", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment_key", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_links_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_links" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_activity_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "hostname", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_hostname", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "tunnel_name", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_tunnel_name", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_to_start_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_to_start_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["environment_id", "environment_public_key", "thread_id"], + "nameExplicit": false, + "name": "relay_agent_activity_rows_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "columns": ["thumbprint", "jti"], + "nameExplicit": false, + "name": "relay_dpop_proofs_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_environment_links_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_environment_links" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_live_activities_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_live_activities" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_managed_endpoint_allocations_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_mobile_devices_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "relay_delivery_attempts_pkey", + "schema": "public", + "table": "relay_delivery_attempts", + "entityType": "pks" + }, + { + "columns": ["device_code_hash"], + "nameExplicit": false, + "name": "relay_device_authorizations_pkey", + "schema": "public", + "table": "relay_device_authorizations", + "entityType": "pks" + }, + { + "columns": ["credential_id"], + "nameExplicit": false, + "name": "relay_environment_credentials_pkey", + "schema": "public", + "table": "relay_environment_credentials", + "entityType": "pks" + } + ], + "renames": [] +} diff --git a/infra/relay/src/auth/DeviceAuthorizations.ts b/infra/relay/src/auth/DeviceAuthorizations.ts index 848779ea31..afc50daf40 100644 --- a/infra/relay/src/auth/DeviceAuthorizations.ts +++ b/infra/relay/src/auth/DeviceAuthorizations.ts @@ -3,7 +3,7 @@ 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, lt } from "drizzle-orm"; +import { and, eq, gt, isNull, lt, ne, or } from "drizzle-orm"; import * as RelayDb from "../db.ts"; import { relayDeviceAuthorizations } from "../persistence/schema.ts"; @@ -152,6 +152,8 @@ const make = Effect.gen(function* () { "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) @@ -165,6 +167,7 @@ const make = Effect.gen(function* () { eq(relayDeviceAuthorizations.userCode, input.userCode), eq(relayDeviceAuthorizations.status, "pending"), gt(relayDeviceAuthorizations.expiresAt, now), + isNull(relayDeviceAuthorizations.callbackState), ), ) .returning() @@ -257,11 +260,23 @@ const make = Effect.gen(function* () { }); const pruneExpired: DeviceAuthorizations["Service"]["pruneExpired"] = Effect.gen(function* () { - const now = DateTime.formatIso(yield* DateTime.now); - yield* Effect.annotateCurrentSpan({ "relay.device_authorization_prune.before": now }); + 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(lt(relayDeviceAuthorizations.expiresAt, now)) + .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")); diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 8e11ece556..6550af164f 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -754,14 +754,8 @@ export const deviceApi = HttpApiBuilder.group( return yield* relayDeviceTokenPollError("expired_token"); } const now = yield* DateTime.now; - if (record.expiresAt <= DateTime.formatIso(now)) { - yield* deviceAuthorizations.deleteByDeviceCodeHash(deviceCodeHash); - return yield* relayDeviceTokenPollError("expired_token"); - } - if (record.status === "denied") { - yield* deviceAuthorizations.deleteByDeviceCodeHash(deviceCodeHash); - return yield* relayDeviceTokenPollError("access_denied"); - } + // 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) { @@ -772,6 +766,14 @@ export const deviceApi = HttpApiBuilder.group( } 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 > @@ -814,18 +816,28 @@ export const deviceApprovalApi = HttpApiBuilder.group( yield* appendRelayCredentialResponseHeaders; const { userId } = yield* RelayClientPrincipal; yield* Effect.annotateCurrentSpan({ "user.id": userId }); - const callbackState = yield* crypto.randomUUIDv4.pipe( + const userCode = normalizeDeviceUserCode(args.params.userCode); + const requestedState = yield* crypto.randomUUIDv4.pipe( Effect.catch(() => relayInternalErrorResponse("internal_error")), ); - const redirectUri = `${appBaseUrl}/oauth/device/callback`; const now = yield* DateTime.now; - const record = yield* deviceAuthorizations.beginApproval({ - userCode: normalizeDeviceUserCode(args.params.userCode), - callbackState, - redirectUri, + // 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, }); - if (record === null) { + 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({ @@ -834,10 +846,10 @@ export const deviceApprovalApi = HttpApiBuilder.group( }).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", redirectUri); + authorizationUrl.searchParams.set("redirect_uri", record.redirectUri); authorizationUrl.searchParams.set("response_type", "code"); authorizationUrl.searchParams.set("scope", record.scope); - authorizationUrl.searchParams.set("state", callbackState); + authorizationUrl.searchParams.set("state", record.callbackState); authorizationUrl.searchParams.set("code_challenge", record.codeChallenge); authorizationUrl.searchParams.set("code_challenge_method", "S256"); return { authorizationUrl: authorizationUrl.toString() }; diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index 07312ba42e..b01f43e5a8 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -140,9 +140,11 @@ export default class Api extends Cloudflare.Worker()( const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY"); const clerkPublishableKey = yield* Config.string("CLERK_PUBLISHABLE_KEY"); const clerkJwtAudience = yield* Config.string("CLERK_JWT_AUDIENCE"); - const appBaseUrl = yield* Config.string("T3CODE_APP_BASE_URL").pipe( - Config.withDefault("https://app.t3.codes"), - ); + // 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;