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
This commit is contained in:
1 parent
aa17397149
commit
ebaeee9339
10 files changed
+1916
-41
No files matched your search
@@ -132,6 +132,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);
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
@@ -143,18 +143,28 @@ function ConfiguredDeviceAuthorizationSurface({
|
||||
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" });
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <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. 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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
@@ -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"));
|
||||
|
||||
|
||||
+29
-17
@@ -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() };
|
||||
|
||||
@@ -140,9 +140,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");
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user