The best way to control Claude Code, Codex and more from any computer or phone
fix(relay): revoke the previous link when switching accounts (#37820)
Julius Marminge committed
Nov 18, 2026 at 13:18 UTC
7da318e2d563b4e3c51edde06d435b5c4ec2eb9e
5 files changed
+178
-112
infra/relay/src/agentActivity/ApnsDeliveries.test.ts
+75
-70
@@ -931,79 +931,84 @@ describe("ApnsDeliveries", () => {
931
);
932
});
933
934
- it.effect("skips a queued Done Live Activity update after the thread resumes working", () => {
935
- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
936
- let executeCount = 0;
937
- const completedAt = "1970-01-01T00:00:01.000Z";
938
- const completedAggregate: RelayAgentActivityAggregateState = {
939
- ...aggregate,
940
- activeCount: 0,
941
- updatedAt: completedAt,
942
- activities: [
943
- {
944
- ...aggregate.activities[0]!,
945
- phase: "completed",
946
- status: "Done",
947
- updatedAt: completedAt,
948
- },
949
- ],
950
- };
951
- const payload = makeApnsDeliveryJobPayload({
952
- kind: "live_activity_update",
953
- userId: target.user_id,
954
- deviceId: target.device_id,
955
- token: target.activity_push_token ?? "activity-token",
956
- aggregate: completedAggregate,
957
- alert: { title: "Thread", body: "Done: Project" },
958
- createdAt: completedAt,
959
- expiresAt: "1970-01-01T00:10:00.000Z",
960
- jobId: "job-update-superseded-by-running",
961
- });
962
- const signed = signApnsDeliveryJob({
963
- secret: config.apnsDeliveryJobSigningSecret,
964
- payload,
965
- });
966
- const execute = (request: HttpClientRequest.HttpClientRequest) =>
967
- Effect.sync(() => {
968
- executeCount += 1;
969
- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
934
+ it.effect.each([true, false])(
935
+ "skips a queued Done update that is no longer visible (thread resumed: %s)",
936
+ (resumed) => {
937
+ const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
938
+ let executeCount = 0;
939
+ const completedAt = "1970-01-01T00:00:01.000Z";
940
+ const completedAggregate: RelayAgentActivityAggregateState = {
941
+ ...aggregate,
942
+ activeCount: 0,
943
+ updatedAt: completedAt,
944
+ activities: [
945
+ {
946
+ ...aggregate.activities[0]!,
947
+ phase: "completed",
948
+ status: "Done",
949
+ updatedAt: completedAt,
950
+ },
951
+ ],
952
+ };
953
+ const payload = makeApnsDeliveryJobPayload({
954
+ kind: "live_activity_update",
955
+ userId: target.user_id,
956
+ deviceId: target.device_id,
957
+ token: target.activity_push_token ?? "activity-token",
958
+ aggregate: completedAggregate,
959
+ alert: { title: "Thread", body: "Done: Project" },
960
+ createdAt: completedAt,
961
+ expiresAt: "1970-01-01T00:10:00.000Z",
962
+ jobId: "job-update-superseded-by-running",
963
+ });
964
+ const signed = signApnsDeliveryJob({
965
+ secret: config.apnsDeliveryJobSigningSecret,
966
+ payload,
967
});
968
+ const execute = (request: HttpClientRequest.HttpClientRequest) =>
969
+ Effect.sync(() => {
970
+ executeCount += 1;
971
+ return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
972
+ });
973
972
- return Effect.gen(function* () {
973
- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
974
- const result = yield* deliveries.processSignedJob(yield* signed);
974
+ return Effect.gen(function* () {
975
+ const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
976
+ const result = yield* deliveries.processSignedJob(yield* signed);
977
976
- expect(result).toMatchObject({
977
- kind: "live_activity_update",
978
- ok: true,
979
- apnsStatus: null,
980
- apnsReason: "Stale APNs delivery job skipped.",
981
- });
982
- expect(executeCount).toBe(0);
983
- expect(attempts).toMatchObject([
984
- {
985
- sourceJobId: "job-update-superseded-by-running",
986
- apnsReason: "Stale agent activity state skipped.",
987
- },
988
- ]);
989
- }).pipe(
990
- Effect.provide(
991
- layerFor({
992
- attempts,
993
- activityStates: [
994
- {
995
- ...state,
996
- phase: "running",
997
- headline: "Running",
998
- updatedAt: "1970-01-01T00:00:02.000Z",
999
- },
1000
- ],
1001
- config: signingConfig,
1002
- execute,
1003
- }),
1004
- ),
1005
- );
1006
- });
978
+ expect(result).toMatchObject({
979
+ kind: "live_activity_update",
980
+ ok: true,
981
+ apnsStatus: null,
982
+ apnsReason: "Stale APNs delivery job skipped.",
983
+ });
984
+ expect(executeCount).toBe(0);
985
+ expect(attempts).toMatchObject([
986
+ {
987
+ sourceJobId: "job-update-superseded-by-running",
988
+ apnsReason: "Stale agent activity state skipped.",
989
+ },
990
+ ]);
991
+ }).pipe(
992
+ Effect.provide(
993
+ layerFor({
994
+ attempts,
995
+ activityStates: resumed
996
+ ? [
997
+ {
998
+ ...state,
999
+ phase: "running",
1000
+ headline: "Running",
1001
+ updatedAt: "1970-01-01T00:00:02.000Z",
1002
+ },
1003
+ ]
1004
+ : [],
1005
+ config: signingConfig,
1006
+ execute,
1007
+ }),
1008
+ ),
1009
+ );
1010
+ },
1011
+ );
1012
1013
it.effect("retries an in-flight device's jobs without cancelling other devices", () => {
1014
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
infra/relay/src/environments/EnvironmentLinker.test.ts
+2
@@ -17,6 +17,7 @@ import * as Schema from "effect/Schema";
17
import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
18
import * as DpopProofs from "../auth/DpopProofs.ts";
19
import * as RelayTokens from "../auth/RelayTokens.ts";
20
+import * as RelayDb from "../db.ts";
21
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
22
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
23
import * as RelayConfiguration from "../Config.ts";
@@ -119,6 +120,7 @@ function layerTest(input?: {
120
Layer.provide(
121
Layer.mergeAll(
122
RelayConfiguration.layer(config),
123
+ Layer.succeed(RelayDb.RelayTransactions, { withTransaction: (effect) => effect }),
124
Layer.succeed(DpopProofs.DpopProofReplay, {
125
verifyAndConsume: () => Effect.die("unexpected DPoP proof verification"),
126
consume: input?.consume ?? (() => Effect.succeed(true)),
infra/relay/src/environments/EnvironmentLinker.ts
+25
-5
@@ -15,9 +15,11 @@ import * as DateTime from "effect/DateTime";
15
import * as Effect from "effect/Effect";
16
import * as Layer from "effect/Layer";
17
import * as Schema from "effect/Schema";
18
+import * as SqlError from "effect/sql/SqlError";
19
20
import * as DpopProofs from "../auth/DpopProofs.ts";
21
import * as RelayTokens from "../auth/RelayTokens.ts";
22
+import * as RelayDb from "../db.ts";
23
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
24
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
25
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
@@ -138,6 +140,7 @@ function isLoopbackManagedTunnelOrigin(
140
141
const make = Effect.gen(function* () {
142
const links = yield* EnvironmentLinks.EnvironmentLinks;
143
+ const transactions = yield* RelayDb.RelayTransactions;
144
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
145
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
146
const proofReplay = yield* DpopProofs.DpopProofReplay;
@@ -322,11 +325,28 @@ const make = Effect.gen(function* () {
325
stage: "validate_endpoint",
326
});
327
}
325
- yield* links.upsert({ ...input, proof: verified, endpoint });
326
- const environmentCredential = yield* credentials.create({
327
- environmentId: verified.environmentId,
328
- environmentPublicKey: verified.environmentPublicKey,
329
- });
328
+ const environmentCredential = yield* transactions
329
+ .withTransaction(
330
+ links.upsert({ ...input, proof: verified, endpoint }).pipe(
331
+ Effect.andThen(
332
+ credentials.create({
333
+ environmentId: verified.environmentId,
334
+ environmentPublicKey: verified.environmentPublicKey,
335
+ }),
336
+ ),
337
+ ),
338
+ )
339
+ .pipe(
340
+ Effect.mapError((cause) =>
341
+ SqlError.isSqlError(cause)
342
+ ? new EnvironmentLinks.EnvironmentLinkUpsertPersistenceError({
343
+ userId: input.userId,
344
+ environmentId: verified.environmentId,
345
+ cause,
346
+ })
347
+ : cause,
348
+ ),
349
+ );
350
return {
351
environmentId: verified.environmentId,
352
endpoint,
infra/relay/src/environments/EnvironmentLinks.test.ts
+19
@@ -10,7 +10,20 @@ import * as EnvironmentLinks from "./EnvironmentLinks.ts";
10
describe("EnvironmentLinks", () => {
11
it.effect("carries the webhook-hold opt-in over only from links with the same key", () => {
12
const inserted: Array<Record<string, unknown>> = [];
13
+ const revoked: Array<{ values: Record<string, unknown>; condition: unknown }> = [];
14
const fakeDb = {
15
+ $client: {
16
+ withTransaction: (effect: Effect.Effect<unknown>) => effect,
17
+ },
18
+ execute: () => Effect.void,
19
+ update: () => ({
20
+ set: (values: Record<string, unknown>) => ({
21
+ where: (condition: unknown) =>
22
+ Effect.sync(() => {
23
+ revoked.push({ values, condition });
24
+ }),
25
+ }),
26
+ }),
27
insert: () => ({
28
values: (values: Record<string, unknown>) => {
29
inserted.push(values);
@@ -38,6 +51,12 @@ describe("EnvironmentLinks", () => {
51
const query = new PgDialect().sqlToQuery(inserted[0]?.holdWebhooksWhileOffline as never);
52
expect(query.sql).toContain("environment_public_key");
53
expect(query.params).toEqual(["env-1", "public-key-1"]);
54
+ expect(revoked).toHaveLength(1);
55
+ expect(revoked[0]?.values.revokedAt).toEqual(inserted[0]?.updatedAt);
56
+ const priorLinks = new PgDialect().sqlToQuery(revoked[0]?.condition as never);
57
+ expect(priorLinks.sql).toContain('"user_id" <>');
58
+ expect(priorLinks.sql).toContain('"revoked_at" is null');
59
+ expect(priorLinks.params).toEqual(["env-1", "public-key-1", "user-1"]);
60
}).pipe(
61
Effect.provide(
62
EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
infra/relay/src/environments/EnvironmentLinks.ts
+57
-37
@@ -9,7 +9,7 @@ import * as DateTime from "effect/DateTime";
9
import * as Effect from "effect/Effect";
10
import * as Layer from "effect/Layer";
11
import * as Schema from "effect/Schema";
12
-import { and, eq, isNull, or, sql } from "drizzle-orm";
12
+import { and, eq, isNull, ne, or, sql } from "drizzle-orm";
13
14
import * as RelayDb from "../db.ts";
15
import { relayEnvironmentLinks } from "../persistence/schema.ts";
@@ -187,42 +187,62 @@ const make = Effect.gen(function* () {
187
AND other.hold_webhooks_while_offline
188
)`;
189
const { endpoint } = input;
190
- yield* db
191
- .insert(relayEnvironmentLinks)
192
- .values({
193
- userId: input.userId,
194
- environmentId,
195
- holdWebhooksWhileOffline: inheritedHoldWebhooks,
196
- environmentLabel: proof.descriptor.label,
197
- environmentPublicKey: proof.environmentPublicKey,
198
- endpointHttpBaseUrl: endpoint.httpBaseUrl,
199
- endpointWsBaseUrl: endpoint.wsBaseUrl,
200
- endpointProviderKind: endpoint.providerKind,
201
- notificationsEnabled: request.notificationsEnabled,
202
- liveActivitiesEnabled: request.liveActivitiesEnabled,
203
- managedTunnelsEnabled: request.managedTunnelsEnabled,
204
- createdByDeviceId: request.deviceId ?? null,
205
- revokedAt: null,
206
- createdAt: now,
207
- updatedAt: now,
208
- })
209
- .onConflictDoUpdate({
210
- target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
211
- set: {
212
- environmentPublicKey: proof.environmentPublicKey,
213
- environmentLabel: proof.descriptor.label,
214
- endpointHttpBaseUrl: endpoint.httpBaseUrl,
215
- endpointWsBaseUrl: endpoint.wsBaseUrl,
216
- endpointProviderKind: endpoint.providerKind,
217
- notificationsEnabled: request.notificationsEnabled,
218
- liveActivitiesEnabled: request.liveActivitiesEnabled,
219
- managedTunnelsEnabled: request.managedTunnelsEnabled,
220
- createdByDeviceId: request.deviceId ?? null,
221
- revokedAt: null,
222
- updatedAt: now,
223
- holdWebhooksWhileOffline: inheritedHoldWebhooks,
224
- },
225
- })
190
+ yield* db.$client
191
+ .withTransaction(
192
+ Effect.gen(function* () {
193
+ // Serialize account switches for the same proven environment identity.
194
+ yield* db.execute(
195
+ sql`select pg_advisory_xact_lock(hashtext(${environmentId}), hashtext(${proof.environmentPublicKey}))`,
196
+ );
197
+ yield* db
198
+ .insert(relayEnvironmentLinks)
199
+ .values({
200
+ userId: input.userId,
201
+ environmentId,
202
+ holdWebhooksWhileOffline: inheritedHoldWebhooks,
203
+ environmentLabel: proof.descriptor.label,
204
+ environmentPublicKey: proof.environmentPublicKey,
205
+ endpointHttpBaseUrl: endpoint.httpBaseUrl,
206
+ endpointWsBaseUrl: endpoint.wsBaseUrl,
207
+ endpointProviderKind: endpoint.providerKind,
208
+ notificationsEnabled: request.notificationsEnabled,
209
+ liveActivitiesEnabled: request.liveActivitiesEnabled,
210
+ managedTunnelsEnabled: request.managedTunnelsEnabled,
211
+ createdByDeviceId: request.deviceId ?? null,
212
+ revokedAt: null,
213
+ createdAt: now,
214
+ updatedAt: now,
215
+ })
216
+ .onConflictDoUpdate({
217
+ target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],
218
+ set: {
219
+ environmentPublicKey: proof.environmentPublicKey,
220
+ environmentLabel: proof.descriptor.label,
221
+ endpointHttpBaseUrl: endpoint.httpBaseUrl,
222
+ endpointWsBaseUrl: endpoint.wsBaseUrl,
223
+ endpointProviderKind: endpoint.providerKind,
224
+ notificationsEnabled: request.notificationsEnabled,
225
+ liveActivitiesEnabled: request.liveActivitiesEnabled,
226
+ managedTunnelsEnabled: request.managedTunnelsEnabled,
227
+ createdByDeviceId: request.deviceId ?? null,
228
+ revokedAt: null,
229
+ updatedAt: now,
230
+ holdWebhooksWhileOffline: inheritedHoldWebhooks,
231
+ },
232
+ });
233
+ yield* db
234
+ .update(relayEnvironmentLinks)
235
+ .set({ revokedAt: now, updatedAt: now })
236
+ .where(
237
+ and(
238
+ eq(relayEnvironmentLinks.environmentId, environmentId),
239
+ eq(relayEnvironmentLinks.environmentPublicKey, proof.environmentPublicKey),
240
+ ne(relayEnvironmentLinks.userId, input.userId),
241
+ isNull(relayEnvironmentLinks.revokedAt),
242
+ ),
243
+ );
244
+ }),
245
+ )
246
.pipe(
247
Effect.mapError(
248
(cause) =>