Skip to content

Commit 49972da

Browse files
feat(backend,nextjs): add experimental poppy browser sessions (#10702)
1 parent b33a60f commit 49972da

10 files changed

Lines changed: 436 additions & 5 deletions

File tree

‎.changeset/artifacts-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"@clerk/backend": minor
33
---
44

5-
Fetch the Poppy JSON artifact with the Clerk-defined `clerkClient.artifacts.__experimental_getPoppyJson()` method.
5+
Fetch the Poppy JSON artifact with the Clerk-defined `clerkClient.artifacts.getPoppyJson()` method.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
"@clerk/backend": minor
3+
"@clerk/nextjs": minor
4+
---
5+
6+
Add support for Personal Agent Protocol signed-in browser sessions. Enable the Clerk-defined `poppy: true` option on `clerkMiddleware()` to publish Poppy and OAuth protected resource discovery on the application domain.
7+
8+
Expose `agent` on the auth object when an agent session is active.

‎packages/backend/src/api/__tests__/ArtifactsApi.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,6 @@ describe('ArtifactsAPI', () => {
1818
apiUrl: 'https://api.clerk.test',
1919
secretKey: 'sk_live_example',
2020
});
21-
await expect(artifacts.__experimental_getPoppyJson()).resolves.toEqual(data);
21+
await expect(artifacts.getPoppyJson()).resolves.toEqual(data);
2222
});
2323
});

‎packages/backend/src/api/endpoints/ArtifactsApi.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { AbstractAPI } from './AbstractApi';
33
export type PoppyMetadata = unknown;
44

55
export class ArtifactsAPI extends AbstractAPI {
6-
public async __experimental_getPoppyJson() {
6+
public async getPoppyJson() {
77
const artifact = await this.request<{ object: 'artifact'; data: PoppyMetadata }>({
88
method: 'GET',
99
path: '/artifacts/well-known-poppy',

‎packages/backend/src/tokens/__tests__/authObjects.test.ts‎

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
1-
import type { JwtPayload } from '@clerk/shared/types';
2-
import { describe, expect, it, vi } from 'vitest';
1+
import type { AgentActClaim, JwtPayload } from '@clerk/shared/types';
2+
import { describe, expect, expectTypeOf, it, vi } from 'vitest';
33

44
import { createBackendApiClient } from '../../api/factory';
5+
import { createJwt, mockJwtPayload } from '../../fixtures';
56
import { mockTokens, mockVerificationResults } from '../../fixtures/machine';
7+
import { decodeJwt } from '../../jwt';
68
import type { AuthenticateContext } from '../authenticateContext';
79
import type { InvalidTokenAuthObject, UnauthenticatedMachineObject } from '../authObjects';
810
import {
911
authenticatedMachineObject,
1012
getAuthObjectForAcceptedToken,
13+
getAuthObjectFromJwt,
1114
makeAuthObjectSerializable,
1215
signedInAuthObject,
1316
signedOutAuthObject,
@@ -31,6 +34,71 @@ describe('makeAuthObjectSerializable', () => {
3134
});
3235

3336
describe('signedInAuthObject', () => {
37+
it.each([
38+
{ name: 'ordinary Session has no agent', claims: {}, expected: undefined },
39+
{
40+
name: 'impersonation remains actor attribution',
41+
claims: { act: { sub: 'impersonator' } },
42+
expected: undefined,
43+
},
44+
{
45+
name: 'agent-task Session uses the existing Session agent shape',
46+
claims: { agt: { id: 'agent_123', tsk: 'agtsk_123', reg: 'https://clerk.com' } },
47+
expected: { type: 'agent', sub: 'agent_123', task_id: 'agtsk_123' },
48+
},
49+
{
50+
name: 'Poppy Session uses the existing Session agent shape',
51+
claims: { agt: { id: 'https://agent.example', poppy: { session_id: 'protocol-session' } } },
52+
expected: { type: 'agent', sub: 'https://agent.example' },
53+
},
54+
{
55+
name: 'malformed agent claim is not exposed',
56+
claims: { agt: { id: 123, tsk: 'agtsk_123' } },
57+
expected: undefined,
58+
},
59+
])('$name', ({ claims, expected }) => {
60+
const auth = signedInAuthObject({}, 'token', {
61+
...mockJwtPayload,
62+
__raw: 'token',
63+
...claims,
64+
sub: 'user_123',
65+
sid: 'sess_123',
66+
});
67+
68+
expect(auth.agent).toEqual(expected);
69+
expectTypeOf(auth.agent).toEqualTypeOf<AgentActClaim | undefined>();
70+
expect(auth.userId).toBe('user_123');
71+
expect(auth.actor).toEqual('act' in claims ? claims.act : undefined);
72+
expect(auth).not.toHaveProperty('poppy');
73+
});
74+
75+
it('omits agent attribution from signed-out auth', async () => {
76+
const auth = signedOutAuthObject();
77+
78+
expect(auth).not.toHaveProperty('agent');
79+
expect(auth.userId).toBeNull();
80+
expect(auth.sessionId).toBeNull();
81+
expect(auth.isAuthenticated).toBe(false);
82+
expect(auth.has({ permission: 'org:admin' })).toBe(false);
83+
expect(await auth.getToken()).toBeNull();
84+
});
85+
86+
it('omits agent attribution when a pending Clerk Session is treated as signed out', () => {
87+
const auth = getAuthObjectFromJwt(
88+
decodeJwt(
89+
createJwt({
90+
payload: { sub: 'user_123', sid: 'sess_123', sts: 'pending', agt: { id: 'https://agent.example' } },
91+
}),
92+
),
93+
{},
94+
);
95+
96+
expect(auth).not.toHaveProperty('agent');
97+
expect(auth.isAuthenticated).toBe(false);
98+
expect(auth.userId).toBeNull();
99+
expect(auth.sessionStatus).toBe('pending');
100+
});
101+
34102
it('getToken returns the token passed in', async () => {
35103
const mockAuthenticateContext = { sessionToken: 'authContextToken' } as AuthenticateContext;
36104
const authObject = signedInAuthObject(mockAuthenticateContext, 'token', {

‎packages/backend/src/tokens/__tests__/request.test.ts‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ import {
77
mockInvalidSignatureJwt,
88
mockJwks,
99
mockJwt,
10+
mockJwtHeader,
1011
mockJwtPayload,
1112
mockM2MJwtPayload,
13+
pemEncodedPublicKey,
1214
signingJwks,
1315
} from '../../fixtures';
1416
import {
@@ -19,6 +21,7 @@ import {
1921
} from '../../fixtures/machine';
2022
import { signJwt } from '../../jwt/signJwt';
2123
import { server } from '../../mock-server';
24+
import { getCookieSuffix } from '../../util/shared';
2225
import type { AuthReason } from '../authStatus';
2326
import { AuthErrorReason, AuthStatus } from '../authStatus';
2427
import { JWT_CATEGORY_JWT_TEMPLATE, JWT_CATEGORY_M2M_TOKEN, JWT_CATEGORY_SESSION_TOKEN } from '../jwtCategories';
@@ -509,6 +512,122 @@ describe('tokens.authenticateRequest(options)', () => {
509512
vi.clearAllMocks();
510513
});
511514

515+
describe('agent Session JWT authentication', () => {
516+
const identity = { session_id: 'protocol-session', client_id: 'https://agent.example', user_id: 'pseudonym' };
517+
518+
it.each([
519+
{ name: 'valid bearer token', cookie: false, expired: false },
520+
{ name: 'valid session cookie', cookie: true, expired: false },
521+
{ name: 'expired bearer token', cookie: false, expired: true },
522+
])('uses normal JWT verification for $name without a backend call', async ({ cookie, expired }) => {
523+
const { data: jwt } = await signJwt(
524+
{
525+
...mockJwtPayload,
526+
...(expired ? { exp: mockJwtPayload.iat - 10 } : {}),
527+
agt: { id: identity.client_id, poppy: identity },
528+
},
529+
signingJwks,
530+
{ algorithm: 'RS256', header: { ...mockJwtHeader } },
531+
);
532+
const fetch = vi.spyOn(globalThis, 'fetch');
533+
const request = cookie
534+
? mockRequestWithCookies({}, { __session: jwt, __client_uat: mockJwtPayload.iat })
535+
: mockRequestWithHeaderAuth({ authorization: `Bearer ${jwt}` });
536+
const state = await authenticateRequest(
537+
request,
538+
mockOptions({ jwtKey: pemEncodedPublicKey, publishableKey: PK_LIVE }),
539+
);
540+
expect(fetch).not.toHaveBeenCalled();
541+
expect(state.isAuthenticated).toBe(!expired);
542+
if (expired) {
543+
expect(state.status).toBe(AuthStatus.Handshake);
544+
expect(state.toAuth()).toBeNull();
545+
} else {
546+
expect(state.toAuth()).toMatchObject({
547+
userId: mockJwtPayload.sub,
548+
sessionId: mockJwtPayload.sid,
549+
agent: {
550+
type: 'agent',
551+
sub: identity.client_id,
552+
},
553+
});
554+
}
555+
fetch.mockRestore();
556+
});
557+
558+
it.each([
559+
{ production: true, discovery: true },
560+
{ production: true, discovery: false },
561+
{ production: false, discovery: true },
562+
{ production: false, discovery: false },
563+
])(
564+
'accepts a signed agent handshake with production=$production and discovery=$discovery',
565+
async ({ production, discovery }) => {
566+
const publishableKey = production ? PK_LIVE : PK_TEST;
567+
const suffix = await getCookieSuffix(publishableKey);
568+
const { data: sessionToken } = await signJwt(
569+
{ ...mockJwtPayload, agt: { id: identity.client_id, reg: identity.client_id, poppy: identity } },
570+
signingJwks,
571+
{ algorithm: 'RS256', header: { ...mockJwtHeader, cat: JWT_CATEGORY_SESSION_TOKEN } },
572+
);
573+
const cookies = {
574+
__client_uat: String(mockJwtPayload.iat),
575+
[`__client_uat_${suffix}`]: String(mockJwtPayload.iat),
576+
[`__session_${suffix}`]: sessionToken!,
577+
...(!production ? { [`__clerk_db_jwt_${suffix}`]: 'dev-browser' } : {}),
578+
};
579+
const directives = Object.entries(cookies).map(
580+
([name, value]) => `${name}=${value}; Path=/; SameSite=Lax; Secure`,
581+
);
582+
if (production) {
583+
directives.unshift('__clerk_handshake=; Path=/; Max-Age=0');
584+
}
585+
const { data: handshake } = await signJwt({ handshake: directives }, signingJwks, {
586+
algorithm: 'RS256',
587+
header: { ...mockJwtHeader, cat: JWT_CATEGORY_SESSION_TOKEN },
588+
});
589+
const url = new URL('https://example.com/');
590+
if (!production) {
591+
url.searchParams.set('__clerk_handshake', handshake!);
592+
url.searchParams.set('__clerk_db_jwt', 'dev-browser');
593+
}
594+
const fetch = vi.spyOn(globalThis, 'fetch');
595+
const options = mockOptions({ jwtKey: pemEncodedPublicKey, publishableKey, poppy: discovery });
596+
const state = await authenticateRequest(
597+
mockRequestWithCookies({}, production ? { __clerk_handshake: handshake! } : {}, url.toString()),
598+
options,
599+
);
600+
const expectedAuth = {
601+
userId: mockJwtPayload.sub,
602+
sessionId: mockJwtPayload.sid,
603+
agent: { type: 'agent', sub: identity.client_id },
604+
};
605+
expect(state.isAuthenticated).toBe(true);
606+
expect(state.toAuth()).toMatchObject(expectedAuth);
607+
expect(state.headers.getSetCookie()).toEqual(directives);
608+
expect(state.headers.get('location')).toBe(production ? null : 'https://example.com/');
609+
const nextRequest = await authenticateRequest(
610+
mockRequestWithCookies({}, cookies, 'https://example.com/'),
611+
options,
612+
);
613+
expect(nextRequest.isAuthenticated).toBe(true);
614+
expect(nextRequest.toAuth()).toMatchObject(expectedAuth);
615+
expect(fetch).not.toHaveBeenCalled();
616+
fetch.mockRestore();
617+
},
618+
);
619+
620+
it('does not interpret an application cookie as authenticated agent identity', async () => {
621+
const state = await authenticateRequest(
622+
mockRequestWithCookies({}, { '__Host-poppy_session': 'untrusted' }),
623+
mockOptions({ jwtKey: pemEncodedPublicKey, publishableKey: PK_LIVE, poppy: true }),
624+
);
625+
expect(state.isAuthenticated).toBe(false);
626+
expect(state.toAuth()).toMatchObject({ userId: null, sessionId: null });
627+
expect(state.toAuth()).not.toHaveProperty('agent');
628+
});
629+
});
630+
512631
//
513632
// HTTP Authorization exists
514633
//

‎packages/backend/src/tokens/authObjects.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { createCheckAuthorization } from '@clerk/shared/authorization';
22
import { __experimental_JWTPayloadToAuthObjectProperties } from '@clerk/shared/jwtPayloadParser';
33
import type {
4+
AgentActClaim,
45
CheckAuthorizationFromSessionClaims,
56
Jwt,
67
JwtPayload,
@@ -31,6 +32,18 @@ type AuthObjectDebug = () => AuthObjectDebugData;
3132

3233
type Claims = Record<string, any>;
3334

35+
const getAuthAgent = (claims: JwtPayload): AgentActClaim | undefined => {
36+
const claim: unknown = claims.agt;
37+
if (typeof claim === 'object' && claim !== null && 'id' in claim && typeof claim.id === 'string' && claim.id) {
38+
return {
39+
type: 'agent',
40+
sub: claim.id,
41+
...('tsk' in claim && typeof claim.tsk === 'string' ? { task_id: claim.tsk } : {}),
42+
};
43+
}
44+
return undefined;
45+
};
46+
3447
/**
3548
* @internal
3649
*/
@@ -42,6 +55,7 @@ export type SignedInAuthObjectOptions = CreateBackendApiOptions & {
4255
* @internal
4356
*/
4457
export type SignedInAuthObject = SharedSignedInAuthObjectProperties & {
58+
agent?: AgentActClaim;
4559
/**
4660
* The allowed token type.
4761
*/
@@ -65,6 +79,7 @@ export type SignedInAuthObject = SharedSignedInAuthObjectProperties & {
6579
* @internal
6680
*/
6781
export type SignedOutAuthObject = {
82+
agent?: undefined;
6883
sessionClaims: null;
6984
sessionId: null;
7085
sessionStatus: SessionStatusClaim | null;
@@ -198,6 +213,7 @@ export function signedInAuthObject(
198213
const { actor, sessionId, sessionStatus, userId, orgId, orgRole, orgSlug, orgPermissions, factorVerificationAge } =
199214
__experimental_JWTPayloadToAuthObjectProperties(sessionClaims);
200215
const apiClient = createBackendApiClient(authenticateContext);
216+
const agent = getAuthAgent(sessionClaims);
201217
const getToken = createGetToken({
202218
sessionId,
203219
sessionToken,
@@ -206,6 +222,7 @@ export function signedInAuthObject(
206222
});
207223
return {
208224
tokenType: TokenType.SessionToken,
225+
...(agent ? { agent } : {}),
209226
actor,
210227
sessionClaims,
211228
sessionId,

‎packages/backend/src/tokens/types.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ import type { VerifyTokenOptions } from './verify';
1717
* @interface
1818
*/
1919
export type AuthenticateRequestOptions = {
20+
/**
21+
* Clerk's preview flag for publishing Poppy discovery through `clerkMiddleware()`.
22+
* The Backend API supplies Clerk's hosted browser Session endpoint. No application join or callback route is needed.
23+
* This option may change while Poppy is a draft.
24+
*/
25+
poppy?: boolean;
2026
/**
2127
* The Clerk Publishable Key from the [**API keys**](https://dashboard.clerk.com/~/api-keys) page in the Clerk Dashboard.
2228
*/

0 commit comments

Comments
 (0)