Skip to content

Commit c8ee9e3

Browse files
pcncTrigger.dev RepoOps
authored andcommitted
feat(webapp,cli): expire CLI login tokens after 7 days without use
CLI and MCP logins now expire after 7 days without use; using the CLI at least weekly keeps a login alive. When a login lapses, the CLI and MCP server start a new login instead of asking you to log out first. Older CLI versions show the server's error and need `trigger.dev logout` before logging in again. Logins made before this change are unaffected. Self-hosters can change the window with `CLI_LOGIN_IDLE_TIMEOUT_DAYS` (`0` turns it off). Mono-RevId: 57f748f28db3c1b1c108d84812bcc753b6827542
1 parent 1a5a6b0 commit c8ee9e3

29 files changed

Lines changed: 730 additions & 101 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"trigger.dev": patch
3+
---
4+
5+
Logins made with `trigger.dev login` or the MCP server now stop working after 7 days without use. When that happens, the CLI and the MCP server start a new login instead of failing with an auth error, and in CI the CLI says to log in again. Self-hosted instances can change the window with `CLI_LOGIN_IDLE_TIMEOUT_DAYS`, or set it to `0` to turn it off for new logins. Logins made before this change aren't affected.

‎apps/webapp/app/env.server.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,6 +1104,10 @@ const EnvironmentSchema = z
11041104
.max(3650)
11051105
.default(90),
11061106

1107+
// A personal access token minted by a CLI or MCP login stops working after this many days
1108+
// without use. 0 turns it off. Applies to logins from now on: each token keeps the setting it
1109+
// was minted with, so tokens minted while it is 0 never expire from disuse.
1110+
CLI_LOGIN_IDLE_TIMEOUT_DAYS: z.coerce.number().int().min(0).max(3650).default(7),
11071111
CLI_LOGIN_NETWORK_CHECK: z.enum(["off", "log", "confirm"]).default("log"),
11081112
CLI_LOGIN_LEGACY_UNTIL: z.string().datetime().default("2027-01-01T00:00:00.000Z"),
11091113

‎apps/webapp/app/routes/account.tokens/route.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,12 @@ export default function Page() {
353353
</ExpiredLabel>
354354
) : personalAccessToken.expiresAt ? (
355355
<DateTime date={personalAccessToken.expiresAt} />
356+
) : personalAccessToken.idleTimeoutLabel !== null ? (
357+
personalAccessToken.isExpired ? (
358+
<ExpiredLabel>Expired (unused)</ExpiredLabel>
359+
) : (
360+
`After ${personalAccessToken.idleTimeoutLabel} unused`
361+
)
356362
) : (
357363
"Never"
358364
)}

‎apps/webapp/app/routes/api.v1.auth.user-actor-token.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import { type ActionFunctionArgs, json } from "@remix-run/server-runtime";
2-
import { signUserActorToken } from "@trigger.dev/rbac";
2+
import { personalAccessTokenValidUntil, signUserActorToken } from "@trigger.dev/rbac";
33
import { z } from "zod";
44
import { env } from "~/env.server";
55
import { logger } from "~/services/logger.server";
6-
import { personalAccessTokenAuthFailureBody } from "~/services/personalAccessToken.server";
6+
import {
7+
personalAccessTokenAuthFailureBody,
8+
updateLastAccessedAtIfStale,
9+
} from "~/services/personalAccessToken.server";
710
import { rbac } from "~/services/rbac.server";
811

912
// Callers pick the TTL (default 1h) up to a hard ceiling; renewal = mint again
@@ -66,9 +69,18 @@ export async function action({ request }: ActionFunctionArgs) {
6669
}
6770
const body = parsedBody.data ?? {};
6871

69-
// Every use of the UAT rechecks its source PAT, so a UAT outliving the PAT's expiry would
70-
// just stop working early. Grant only what the PAT has left instead.
71-
const sourceValidUntil = patAuth.expiresAt ?? undefined;
72+
// A successful mint is a use of the PAT, so it keeps a CLI login token from going idle. A
73+
// refused request doesn't count.
74+
const lastUsedAt = await updateLastAccessedAtIfStale(patAuth.tokenId, patAuth.lastAccessedAt);
75+
76+
// Every use of the UAT rechecks its source PAT, so a UAT outliving the PAT's fixed or idle
77+
// expiry would just stop working early. Grant only what the PAT has left instead.
78+
const sourceValidUntil = personalAccessTokenValidUntil({
79+
expiresAt: patAuth.expiresAt ?? null,
80+
idleTimeoutSeconds: patAuth.idleTimeoutSeconds ?? null,
81+
lastAccessedAt: lastUsedAt,
82+
createdAt: patAuth.createdAt ?? lastUsedAt,
83+
});
7284
const requestedTtlSeconds = body.ttlSeconds ?? DEFAULT_UAT_TTL_SECONDS;
7385
const ttlSeconds = sourceValidUntil
7486
? Math.max(

‎apps/webapp/app/services/personalAccessToken.server.ts‎

Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
isUserActorToken,
2121
personalAccessTokenExpiry,
2222
personalAccessTokenExpiryMessage,
23+
personalAccessTokenValidUntil,
2324
type PersonalAccessTokenExpiry,
2425
verifyUserActorToken,
2526
type UserActorClaims,
@@ -59,8 +60,18 @@ type CreatePersonalAccessTokenOptions = {
5960
auditSource?: AdminAuditSourceEndpoint;
6061
/** Days until the token stops working. Omitted for tokens that don't expire. */
6162
expiresInDays?: number;
63+
/** Seconds without use after which the token stops working. Omitted for no idle limit. */
64+
idleTimeoutSeconds?: number;
6265
};
6366

67+
/** The columns `personalAccessTokenExpiry` reads, for every lookup that checks expiry. */
68+
const expiryColumns = {
69+
expiresAt: true,
70+
idleTimeoutSeconds: true,
71+
lastAccessedAt: true,
72+
createdAt: true,
73+
} as const;
74+
6475
export type PersonalAccessTokenExpiryOption = {
6576
/** Lifetime in days. */
6677
value: number;
@@ -106,7 +117,7 @@ export function personalAccessTokenAuthFailureBody(failure: {
106117
return { error: failure.error };
107118
}
108119

109-
/** The 401 body for an expired token, pointing at the page where a replacement is made. */
120+
/** The 401 body for an expired token: a CLI login says to log in again, others where to make a new one. */
110121
export function personalAccessTokenExpiryBody(expiry: PersonalAccessTokenExpiry) {
111122
return {
112123
error: personalAccessTokenExpiryMessage(
@@ -128,6 +139,7 @@ export async function getValidPersonalAccessTokens(userId: string) {
128139
createdAt: true,
129140
lastAccessedAt: true,
130141
expiresAt: true,
142+
idleTimeoutSeconds: true,
131143
},
132144
where: {
133145
userId,
@@ -142,6 +154,10 @@ export async function getValidPersonalAccessTokens(userId: string) {
142154
createdAt: pat.createdAt,
143155
lastAccessedAt: pat.lastAccessedAt,
144156
expiresAt: pat.expiresAt,
157+
idleTimeoutLabel:
158+
pat.idleTimeoutSeconds === null
159+
? null
160+
: expiryLabel(Math.round(pat.idleTimeoutSeconds / SECONDS_PER_DAY)),
145161
isExpired: personalAccessTokenExpiry(pat) !== undefined,
146162
isExpiringSoon:
147163
pat.expiresAt !== null &&
@@ -266,25 +282,31 @@ export type PersonalAccessTokenAuthenticationResult = {
266282
* and the apiBuilder's RBAC-routed PAT flow (which gets `lastAccessedAt`
267283
* from `rbac.authenticatePat`'s result). Keeps the throttle policy in one
268284
* place rather than expecting every plugin implementer to re-implement it.
285+
*
286+
* Returns the last-used time now in effect: the cached value when it was fresh, otherwise now.
269287
*/
270288
export async function updateLastAccessedAtIfStale(
271289
tokenId: string,
272290
lastAccessedAt: Date | null
273-
): Promise<void> {
291+
): Promise<Date> {
274292
if (lastAccessedAt && Date.now() - lastAccessedAt.getTime() <= PAT_LAST_ACCESSED_THROTTLE_MS) {
275-
return; // fresh — no roundtrip
293+
return lastAccessedAt; // fresh — no roundtrip
276294
}
295+
const now = new Date();
296+
// If a concurrent request wins the conditional write, it stored a time within the throttle
297+
// window of `now`, so `now` is still the last-used time to within that window.
277298
await prisma.personalAccessToken.updateMany({
278299
where: {
279300
id: tokenId,
280301
revokedAt: null,
281302
OR: [
282303
{ lastAccessedAt: null },
283-
{ lastAccessedAt: { lt: new Date(Date.now() - PAT_LAST_ACCESSED_THROTTLE_MS) } },
304+
{ lastAccessedAt: { lt: new Date(now.getTime() - PAT_LAST_ACCESSED_THROTTLE_MS) } },
284305
],
285306
},
286-
data: { lastAccessedAt: new Date() },
307+
data: { lastAccessedAt: now },
287308
});
309+
return now;
288310
}
289311

290312
const AuthorizationHeaderSchema = z.string().regex(/^Bearer .+$/);
@@ -413,11 +435,15 @@ export async function authenticatePersonalAccessToken(
413435
return;
414436
}
415437

438+
// Checked before the lastAccessedAt write, so a request can't revive an idle-expired token.
416439
if (personalAccessTokenExpiry(personalAccessToken)) {
417440
return;
418441
}
419442

420-
await updateLastAccessedAtIfStale(personalAccessToken.id, personalAccessToken.lastAccessedAt);
443+
const lastUsedAt = await updateLastAccessedAtIfStale(
444+
personalAccessToken.id,
445+
personalAccessToken.lastAccessedAt
446+
);
421447

422448
const decryptedToken = decryptPersonalAccessToken(personalAccessToken);
423449

@@ -431,7 +457,10 @@ export async function authenticatePersonalAccessToken(
431457
return {
432458
userId: personalAccessToken.userId,
433459
tokenId: personalAccessToken.id,
434-
validUntil: personalAccessToken.expiresAt ?? undefined,
460+
validUntil: personalAccessTokenValidUntil({
461+
...personalAccessToken,
462+
lastAccessedAt: lastUsedAt,
463+
}),
435464
};
436465
}
437466

@@ -453,7 +482,7 @@ export async function getPersonalAccessTokenExpiry(
453482

454483
const personalAccessToken = await $replica.personalAccessToken.findFirst({
455484
where: { hashedToken: hashToken(token), revokedAt: null },
456-
select: { expiresAt: true },
485+
select: expiryColumns,
457486
});
458487
return personalAccessToken ? personalAccessTokenExpiry(personalAccessToken) : undefined;
459488
}
@@ -485,7 +514,7 @@ export async function assertSourcePatActive(claims: UserActorClaims): Promise<bo
485514

486515
const found = await prisma.personalAccessToken.findFirst({
487516
where: { id: claims.pat, revokedAt: null },
488-
select: { expiresAt: true },
517+
select: expiryColumns,
489518
});
490519
return found !== null && !personalAccessTokenExpiry(found);
491520
}
@@ -663,6 +692,10 @@ export async function createPersonalAccessTokenFromAuthorizationCode(
663692
name: "cli",
664693
userId,
665694
auditSource: { ip: approval.approverIp ?? null, userAgent: null },
695+
idleTimeoutSeconds:
696+
env.CLI_LOGIN_IDLE_TIMEOUT_DAYS > 0
697+
? env.CLI_LOGIN_IDLE_TIMEOUT_DAYS * SECONDS_PER_DAY
698+
: undefined,
666699
});
667700

668701
const bound = await prisma.authorizationCode.updateMany({
@@ -744,6 +777,7 @@ export async function createPersonalAccessToken({
744777
roleId,
745778
auditSource,
746779
expiresInDays,
780+
idleTimeoutSeconds,
747781
}: CreatePersonalAccessTokenOptions) {
748782
const token = createToken();
749783
const encryptedToken = encryptToken(token, env.ENCRYPTION_KEYRING);
@@ -759,6 +793,7 @@ export async function createPersonalAccessToken({
759793
expiresInDays === undefined
760794
? undefined
761795
: new Date(Date.now() + expiresInDays * SECONDS_PER_DAY * 1000),
796+
idleTimeoutSeconds,
762797
},
763798
});
764799

‎apps/webapp/test/cliLoginBinding.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const mockEnv = vi.hoisted(() => ({
1313
SESSION_SECRET: "test-session-secret-for-cli-login-binding",
1414
ENCRYPTION_KEY: "0123456789abcdef0123456789abcdef",
1515
CLI_LOGIN_LEGACY_UNTIL: "2000-01-01T00:00:00.000Z",
16+
CLI_LOGIN_IDLE_TIMEOUT_DAYS: 7,
1617
}));
1718

1819
vi.mock("~/db.server", () => ({

‎apps/webapp/test/cliLoginNetwork.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const mockEnv = vi.hoisted(() => ({
1313
ENCRYPTION_KEY: "0123456789abcdef0123456789abcdef",
1414
CLI_LOGIN_NETWORK_CHECK: "log" as "off" | "log" | "confirm",
1515
CLI_LOGIN_LEGACY_UNTIL: "2999-01-01T00:00:00.000Z",
16+
CLI_LOGIN_IDLE_TIMEOUT_DAYS: 7,
1617
}));
1718
const logger = vi.hoisted(() => ({ debug: vi.fn(), error: vi.fn(), warn: vi.fn(), info: vi.fn() }));
1819

‎apps/webapp/test/cliPersonalAccessTokenRevocation.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ vi.mock("~/env.server", async () => {
2323
SESSION_SECRET: "test-session-secret-for-cli-pat-revocation",
2424
ENCRYPTION_KEY: "0123456789abcdef0123456789abcdef",
2525
CLI_LOGIN_LEGACY_UNTIL: "2999-01-01T00:00:00.000Z",
26+
CLI_LOGIN_IDLE_TIMEOUT_DAYS: 7,
2627
}),
2728
};
2829
});

0 commit comments

Comments
 (0)