Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/warm-touch-intent.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add optional `intent` parameter to `session.touch()` to indicate why the touch was triggered (focus, session switch, or org switch). This enables the backend to skip expensive client piggybacking for focus-only touches.
26 changes: 13 additions & 13 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -204,7 +204,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

describe('with `touchSession` set to false', () => {
Expand All@@ -215,7 +215,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load({ touchSession: false });
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});
});

Expand All@@ -230,7 +230,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('sets __session and __client_uat cookie before calling __unstable__onBeforeSetActive', async () => {
Expand All@@ -252,7 +252,7 @@ describe('Clerk singleton', () => {
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));

(window as any).__unstable__onAfterSetActive = () => {
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(beforeEmitMock).toHaveBeenCalled();
};

Expand DownExpand Up@@ -299,7 +299,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession2);
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -332,7 +332,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession.getToken).toHaveBeenCalled();
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -371,7 +371,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -454,7 +454,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});

Expand All@@ -479,7 +479,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: { id: 'org_id' } as Organization, beforeEmit: beforeEmitMock });

expect(executionOrder).toEqual(['session.touch', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(mockSession.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -534,7 +534,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('does not call __unstable__onBeforeSetActive before session.touch', async () => {
Expand DownExpand Up@@ -575,7 +575,7 @@ describe('Clerk singleton', () => {
},
});
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(sut.navigate).toHaveBeenCalledWith('/choose-organization');
});

Expand All@@ -587,7 +587,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});
});
Expand DownExpand Up@@ -660,7 +660,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSessionWithOrganization.touch).toHaveBeenCalled();
expect(mockSessionWithOrganization.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSessionWithOrganization.getToken).toHaveBeenCalled();
expect((mockSessionWithOrganization as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual(
'org_id',
Expand Down
14 changes: 10 additions & 4 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ import type {
Resources,
SDKMetadata,
SessionResource,
SessionTouchParams,
SetActiveParams,
SignedInSessionResource,
SignInProps,
Expand DownExpand Up@@ -1555,11 +1556,13 @@ export class Clerk implements ClerkInterface {
await onBeforeSetActive(newSession === null ? 'sign-out' : undefined);
}

const touchIntent: SessionTouchParams['intent'] = shouldSwitchOrganization ? 'select_org' : 'select_session';

//1. setLastActiveSession to passed user session (add a param).
// Note that this will also update the session's active organization
// id.
if (inActiveBrowserTab() || !this.#options.standardBrowser) {
await this.#touchCurrentSession(newSession);
await this.#touchCurrentSession(newSession, touchIntent);
// reload session from updated client
newSession = this.#getSessionFromClient(newSession?.id);
}
Expand DownExpand Up@@ -3016,7 +3019,7 @@ export class Clerk implements ClerkInterface {
this.#touchThrottledUntil = Date.now() + 5_000;

if (this.#options.touchSession) {
void this.#touchCurrentSession(this.session);
void this.#touchCurrentSession(this.session, 'focus');
}
});

Expand DownExpand Up@@ -3047,12 +3050,15 @@ export class Clerk implements ClerkInterface {
};

// TODO: Be more conservative about touches. Throttle, don't touch when only one user, etc
#touchCurrentSession = async (session?: SignedInSessionResource | null): Promise<void> => {
#touchCurrentSession = async (
session?: SignedInSessionResource | null,
intent: SessionTouchParams['intent'] = 'focus',
): Promise<void> => {
if (!session) {
return Promise.resolve();
}

await session.touch().catch(e => {
await session.touch({ intent }).catch(e => {
if (is4xxError(e)) {
void this.handleUnauthenticated();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import type {
SessionResource,
SessionStatus,
SessionTask,
SessionTouchParams,
SessionVerificationJSON,
SessionVerificationResource,
SessionVerifyAttemptFirstFactorParams,
Expand DownExpand Up@@ -86,10 +87,10 @@ export class Session extends BaseResource implements SessionResource {
});
};

touch = (): Promise<SessionResource> => {
touch = ({ intent }: SessionTouchParams = {}): Promise<SessionResource> => {
return this._basePost({
action: 'touch',
body: { active_organization_id: this.lastActiveOrganizationId },
body: { active_organization_id: this.lastActiveOrganizationId, intent },
}).then(res => {
// touch() will potentially change the session state, and so we need to ensure we emit the updated token that comes back in the response. This avoids potential issues where the session cookie is out of sync with the current session state.
if (res.lastActiveToken) {
Expand Down
87 changes: 87 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -467,6 +467,93 @@ describe('Session', () => {
token: session.lastActiveToken,
});
});

it('passes touch intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'focus' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'focus' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_session intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_session' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_session' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_org intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_org' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_org' },
method: 'POST',
}),
expect.anything(),
);
});
});

describe('isAuthorized()', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/types/session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,7 +239,7 @@ export interface SessionResource extends ClerkResource {
*/
end: () => Promise<SessionResource>;
remove: () => Promise<SessionResource>;
touch: () => Promise<SessionResource>;
touch: (params?: SessionTouchParams) => Promise<SessionResource>;
getToken: GetToken;
checkAuthorization: CheckAuthorization;
clearCache: () => void;
Expand DownExpand Up@@ -320,6 +320,12 @@ export type SessionStatus =
| 'revoked'
| 'pending';

export type SessionTouchIntent = 'focus' | 'select_session' | 'select_org';

export type SessionTouchParams = {
intent?: SessionTouchIntent;
};

export interface PublicUserData {
firstName: string | null;
lastName: string | null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(clerk-js): Send touch intent with session updates (core-2 backport) by nikosdouvlis · Pull Request #8135 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/warm-touch-intent.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add optional `intent` parameter to `session.touch()` to indicate why the touch was triggered (focus, session switch, or org switch). This enables the backend to skip expensive client piggybacking for focus-only touches.
26 changes: 13 additions & 13 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -204,7 +204,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

describe('with `touchSession` set to false', () => {
Expand All@@ -215,7 +215,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load({ touchSession: false });
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});
});

Expand All@@ -230,7 +230,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('sets __session and __client_uat cookie before calling __unstable__onBeforeSetActive', async () => {
Expand All@@ -252,7 +252,7 @@ describe('Clerk singleton', () => {
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));

(window as any).__unstable__onAfterSetActive = () => {
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(beforeEmitMock).toHaveBeenCalled();
};

Expand DownExpand Up@@ -299,7 +299,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession2);
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -332,7 +332,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession.getToken).toHaveBeenCalled();
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -371,7 +371,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -454,7 +454,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});

Expand All@@ -479,7 +479,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: { id: 'org_id' } as Organization, beforeEmit: beforeEmitMock });

expect(executionOrder).toEqual(['session.touch', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(mockSession.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -534,7 +534,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('does not call __unstable__onBeforeSetActive before session.touch', async () => {
Expand DownExpand Up@@ -575,7 +575,7 @@ describe('Clerk singleton', () => {
},
});
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(sut.navigate).toHaveBeenCalledWith('/choose-organization');
});

Expand All@@ -587,7 +587,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});
});
Expand DownExpand Up@@ -660,7 +660,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSessionWithOrganization.touch).toHaveBeenCalled();
expect(mockSessionWithOrganization.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSessionWithOrganization.getToken).toHaveBeenCalled();
expect((mockSessionWithOrganization as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual(
'org_id',
Expand Down
14 changes: 10 additions & 4 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ import type {
Resources,
SDKMetadata,
SessionResource,
SessionTouchParams,
SetActiveParams,
SignedInSessionResource,
SignInProps,
Expand DownExpand Up@@ -1555,11 +1556,13 @@ export class Clerk implements ClerkInterface {
await onBeforeSetActive(newSession === null ? 'sign-out' : undefined);
}

const touchIntent: SessionTouchParams['intent'] = shouldSwitchOrganization ? 'select_org' : 'select_session';

//1. setLastActiveSession to passed user session (add a param).
// Note that this will also update the session's active organization
// id.
if (inActiveBrowserTab() || !this.#options.standardBrowser) {
await this.#touchCurrentSession(newSession);
await this.#touchCurrentSession(newSession, touchIntent);
// reload session from updated client
newSession = this.#getSessionFromClient(newSession?.id);
}
Expand DownExpand Up@@ -3016,7 +3019,7 @@ export class Clerk implements ClerkInterface {
this.#touchThrottledUntil = Date.now() + 5_000;

if (this.#options.touchSession) {
void this.#touchCurrentSession(this.session);
void this.#touchCurrentSession(this.session, 'focus');
}
});

Expand DownExpand Up@@ -3047,12 +3050,15 @@ export class Clerk implements ClerkInterface {
};

// TODO: Be more conservative about touches. Throttle, don't touch when only one user, etc
#touchCurrentSession = async (session?: SignedInSessionResource | null): Promise<void> => {
#touchCurrentSession = async (
session?: SignedInSessionResource | null,
intent: SessionTouchParams['intent'] = 'focus',
): Promise<void> => {
if (!session) {
return Promise.resolve();
}

await session.touch().catch(e => {
await session.touch({ intent }).catch(e => {
if (is4xxError(e)) {
void this.handleUnauthenticated();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import type {
SessionResource,
SessionStatus,
SessionTask,
SessionTouchParams,
SessionVerificationJSON,
SessionVerificationResource,
SessionVerifyAttemptFirstFactorParams,
Expand DownExpand Up@@ -86,10 +87,10 @@ export class Session extends BaseResource implements SessionResource {
});
};

touch = (): Promise<SessionResource> => {
touch = ({ intent }: SessionTouchParams = {}): Promise<SessionResource> => {
return this._basePost({
action: 'touch',
body: { active_organization_id: this.lastActiveOrganizationId },
body: { active_organization_id: this.lastActiveOrganizationId, intent },
}).then(res => {
// touch() will potentially change the session state, and so we need to ensure we emit the updated token that comes back in the response. This avoids potential issues where the session cookie is out of sync with the current session state.
if (res.lastActiveToken) {
Expand Down
87 changes: 87 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -467,6 +467,93 @@ describe('Session', () => {
token: session.lastActiveToken,
});
});

it('passes touch intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'focus' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'focus' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_session intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_session' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_session' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_org intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_org' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_org' },
method: 'POST',
}),
expect.anything(),
);
});
});

describe('isAuthorized()', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/types/session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,7 +239,7 @@ export interface SessionResource extends ClerkResource {
*/
end: () => Promise<SessionResource>;
remove: () => Promise<SessionResource>;
touch: () => Promise<SessionResource>;
touch: (params?: SessionTouchParams) => Promise<SessionResource>;
getToken: GetToken;
checkAuthorization: CheckAuthorization;
clearCache: () => void;
Expand DownExpand Up@@ -320,6 +320,12 @@ export type SessionStatus =
| 'revoked'
| 'pending';

export type SessionTouchIntent = 'focus' | 'select_session' | 'select_org';

export type SessionTouchParams = {
intent?: SessionTouchIntent;
};

export interface PublicUserData {
firstName: string | null;
lastName: string | null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(clerk-js): Send touch intent with session updates (core-2 backport) by nikosdouvlis · Pull Request #8135 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/warm-touch-intent.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add optional `intent` parameter to `session.touch()` to indicate why the touch was triggered (focus, session switch, or org switch). This enables the backend to skip expensive client piggybacking for focus-only touches.
26 changes: 13 additions & 13 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -204,7 +204,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

describe('with `touchSession` set to false', () => {
Expand All@@ -215,7 +215,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load({ touchSession: false });
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});
});

Expand All@@ -230,7 +230,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('sets __session and __client_uat cookie before calling __unstable__onBeforeSetActive', async () => {
Expand All@@ -252,7 +252,7 @@ describe('Clerk singleton', () => {
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));

(window as any).__unstable__onAfterSetActive = () => {
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(beforeEmitMock).toHaveBeenCalled();
};

Expand DownExpand Up@@ -299,7 +299,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession2);
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -332,7 +332,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession.getToken).toHaveBeenCalled();
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -371,7 +371,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -454,7 +454,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});

Expand All@@ -479,7 +479,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: { id: 'org_id' } as Organization, beforeEmit: beforeEmitMock });

expect(executionOrder).toEqual(['session.touch', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(mockSession.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -534,7 +534,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('does not call __unstable__onBeforeSetActive before session.touch', async () => {
Expand DownExpand Up@@ -575,7 +575,7 @@ describe('Clerk singleton', () => {
},
});
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(sut.navigate).toHaveBeenCalledWith('/choose-organization');
});

Expand All@@ -587,7 +587,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});
});
Expand DownExpand Up@@ -660,7 +660,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSessionWithOrganization.touch).toHaveBeenCalled();
expect(mockSessionWithOrganization.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSessionWithOrganization.getToken).toHaveBeenCalled();
expect((mockSessionWithOrganization as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual(
'org_id',
Expand Down
14 changes: 10 additions & 4 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ import type {
Resources,
SDKMetadata,
SessionResource,
SessionTouchParams,
SetActiveParams,
SignedInSessionResource,
SignInProps,
Expand DownExpand Up@@ -1555,11 +1556,13 @@ export class Clerk implements ClerkInterface {
await onBeforeSetActive(newSession === null ? 'sign-out' : undefined);
}

const touchIntent: SessionTouchParams['intent'] = shouldSwitchOrganization ? 'select_org' : 'select_session';

//1. setLastActiveSession to passed user session (add a param).
// Note that this will also update the session's active organization
// id.
if (inActiveBrowserTab() || !this.#options.standardBrowser) {
await this.#touchCurrentSession(newSession);
await this.#touchCurrentSession(newSession, touchIntent);
// reload session from updated client
newSession = this.#getSessionFromClient(newSession?.id);
}
Expand DownExpand Up@@ -3016,7 +3019,7 @@ export class Clerk implements ClerkInterface {
this.#touchThrottledUntil = Date.now() + 5_000;

if (this.#options.touchSession) {
void this.#touchCurrentSession(this.session);
void this.#touchCurrentSession(this.session, 'focus');
}
});

Expand DownExpand Up@@ -3047,12 +3050,15 @@ export class Clerk implements ClerkInterface {
};

// TODO: Be more conservative about touches. Throttle, don't touch when only one user, etc
#touchCurrentSession = async (session?: SignedInSessionResource | null): Promise<void> => {
#touchCurrentSession = async (
session?: SignedInSessionResource | null,
intent: SessionTouchParams['intent'] = 'focus',
): Promise<void> => {
if (!session) {
return Promise.resolve();
}

await session.touch().catch(e => {
await session.touch({ intent }).catch(e => {
if (is4xxError(e)) {
void this.handleUnauthenticated();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import type {
SessionResource,
SessionStatus,
SessionTask,
SessionTouchParams,
SessionVerificationJSON,
SessionVerificationResource,
SessionVerifyAttemptFirstFactorParams,
Expand DownExpand Up@@ -86,10 +87,10 @@ export class Session extends BaseResource implements SessionResource {
});
};

touch = (): Promise<SessionResource> => {
touch = ({ intent }: SessionTouchParams = {}): Promise<SessionResource> => {
return this._basePost({
action: 'touch',
body: { active_organization_id: this.lastActiveOrganizationId },
body: { active_organization_id: this.lastActiveOrganizationId, intent },
}).then(res => {
// touch() will potentially change the session state, and so we need to ensure we emit the updated token that comes back in the response. This avoids potential issues where the session cookie is out of sync with the current session state.
if (res.lastActiveToken) {
Expand Down
87 changes: 87 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -467,6 +467,93 @@ describe('Session', () => {
token: session.lastActiveToken,
});
});

it('passes touch intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'focus' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'focus' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_session intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_session' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_session' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_org intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_org' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_org' },
method: 'POST',
}),
expect.anything(),
);
});
});

describe('isAuthorized()', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/types/session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,7 +239,7 @@ export interface SessionResource extends ClerkResource {
*/
end: () => Promise<SessionResource>;
remove: () => Promise<SessionResource>;
touch: () => Promise<SessionResource>;
touch: (params?: SessionTouchParams) => Promise<SessionResource>;
getToken: GetToken;
checkAuthorization: CheckAuthorization;
clearCache: () => void;
Expand DownExpand Up@@ -320,6 +320,12 @@ export type SessionStatus =
| 'revoked'
| 'pending';

export type SessionTouchIntent = 'focus' | 'select_session' | 'select_org';

export type SessionTouchParams = {
intent?: SessionTouchIntent;
};

export interface PublicUserData {
firstName: string | null;
lastName: string | null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(clerk-js): Send touch intent with session updates (core-2 backport) by nikosdouvlis · Pull Request #8135 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/warm-touch-intent.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add optional `intent` parameter to `session.touch()` to indicate why the touch was triggered (focus, session switch, or org switch). This enables the backend to skip expensive client piggybacking for focus-only touches.
26 changes: 13 additions & 13 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -204,7 +204,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

describe('with `touchSession` set to false', () => {
Expand All@@ -215,7 +215,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load({ touchSession: false });
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});
});

Expand All@@ -230,7 +230,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('sets __session and __client_uat cookie before calling __unstable__onBeforeSetActive', async () => {
Expand All@@ -252,7 +252,7 @@ describe('Clerk singleton', () => {
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));

(window as any).__unstable__onAfterSetActive = () => {
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(beforeEmitMock).toHaveBeenCalled();
};

Expand DownExpand Up@@ -299,7 +299,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession2);
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -332,7 +332,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession.getToken).toHaveBeenCalled();
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -371,7 +371,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -454,7 +454,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});

Expand All@@ -479,7 +479,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: { id: 'org_id' } as Organization, beforeEmit: beforeEmitMock });

expect(executionOrder).toEqual(['session.touch', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(mockSession.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -534,7 +534,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('does not call __unstable__onBeforeSetActive before session.touch', async () => {
Expand DownExpand Up@@ -575,7 +575,7 @@ describe('Clerk singleton', () => {
},
});
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(sut.navigate).toHaveBeenCalledWith('/choose-organization');
});

Expand All@@ -587,7 +587,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});
});
Expand DownExpand Up@@ -660,7 +660,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSessionWithOrganization.touch).toHaveBeenCalled();
expect(mockSessionWithOrganization.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSessionWithOrganization.getToken).toHaveBeenCalled();
expect((mockSessionWithOrganization as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual(
'org_id',
Expand Down
14 changes: 10 additions & 4 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ import type {
Resources,
SDKMetadata,
SessionResource,
SessionTouchParams,
SetActiveParams,
SignedInSessionResource,
SignInProps,
Expand DownExpand Up@@ -1555,11 +1556,13 @@ export class Clerk implements ClerkInterface {
await onBeforeSetActive(newSession === null ? 'sign-out' : undefined);
}

const touchIntent: SessionTouchParams['intent'] = shouldSwitchOrganization ? 'select_org' : 'select_session';

//1. setLastActiveSession to passed user session (add a param).
// Note that this will also update the session's active organization
// id.
if (inActiveBrowserTab() || !this.#options.standardBrowser) {
await this.#touchCurrentSession(newSession);
await this.#touchCurrentSession(newSession, touchIntent);
// reload session from updated client
newSession = this.#getSessionFromClient(newSession?.id);
}
Expand DownExpand Up@@ -3016,7 +3019,7 @@ export class Clerk implements ClerkInterface {
this.#touchThrottledUntil = Date.now() + 5_000;

if (this.#options.touchSession) {
void this.#touchCurrentSession(this.session);
void this.#touchCurrentSession(this.session, 'focus');
}
});

Expand DownExpand Up@@ -3047,12 +3050,15 @@ export class Clerk implements ClerkInterface {
};

// TODO: Be more conservative about touches. Throttle, don't touch when only one user, etc
#touchCurrentSession = async (session?: SignedInSessionResource | null): Promise<void> => {
#touchCurrentSession = async (
session?: SignedInSessionResource | null,
intent: SessionTouchParams['intent'] = 'focus',
): Promise<void> => {
if (!session) {
return Promise.resolve();
}

await session.touch().catch(e => {
await session.touch({ intent }).catch(e => {
if (is4xxError(e)) {
void this.handleUnauthenticated();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import type {
SessionResource,
SessionStatus,
SessionTask,
SessionTouchParams,
SessionVerificationJSON,
SessionVerificationResource,
SessionVerifyAttemptFirstFactorParams,
Expand DownExpand Up@@ -86,10 +87,10 @@ export class Session extends BaseResource implements SessionResource {
});
};

touch = (): Promise<SessionResource> => {
touch = ({ intent }: SessionTouchParams = {}): Promise<SessionResource> => {
return this._basePost({
action: 'touch',
body: { active_organization_id: this.lastActiveOrganizationId },
body: { active_organization_id: this.lastActiveOrganizationId, intent },
}).then(res => {
// touch() will potentially change the session state, and so we need to ensure we emit the updated token that comes back in the response. This avoids potential issues where the session cookie is out of sync with the current session state.
if (res.lastActiveToken) {
Expand Down
87 changes: 87 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -467,6 +467,93 @@ describe('Session', () => {
token: session.lastActiveToken,
});
});

it('passes touch intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'focus' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'focus' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_session intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_session' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_session' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_org intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_org' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_org' },
method: 'POST',
}),
expect.anything(),
);
});
});

describe('isAuthorized()', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/types/session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,7 +239,7 @@ export interface SessionResource extends ClerkResource {
*/
end: () => Promise<SessionResource>;
remove: () => Promise<SessionResource>;
touch: () => Promise<SessionResource>;
touch: (params?: SessionTouchParams) => Promise<SessionResource>;
getToken: GetToken;
checkAuthorization: CheckAuthorization;
clearCache: () => void;
Expand DownExpand Up@@ -320,6 +320,12 @@ export type SessionStatus =
| 'revoked'
| 'pending';

export type SessionTouchIntent = 'focus' | 'select_session' | 'select_org';

export type SessionTouchParams = {
intent?: SessionTouchIntent;
};

export interface PublicUserData {
firstName: string | null;
lastName: string | null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(clerk-js): Send touch intent with session updates (core-2 backport) by nikosdouvlis · Pull Request #8135 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/warm-touch-intent.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add optional `intent` parameter to `session.touch()` to indicate why the touch was triggered (focus, session switch, or org switch). This enables the backend to skip expensive client piggybacking for focus-only touches.
26 changes: 13 additions & 13 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -204,7 +204,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

describe('with `touchSession` set to false', () => {
Expand All@@ -215,7 +215,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load({ touchSession: false });
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});
});

Expand All@@ -230,7 +230,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('sets __session and __client_uat cookie before calling __unstable__onBeforeSetActive', async () => {
Expand All@@ -252,7 +252,7 @@ describe('Clerk singleton', () => {
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));

(window as any).__unstable__onAfterSetActive = () => {
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(beforeEmitMock).toHaveBeenCalled();
};

Expand DownExpand Up@@ -299,7 +299,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession2);
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -332,7 +332,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession.getToken).toHaveBeenCalled();
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -371,7 +371,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -454,7 +454,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});

Expand All@@ -479,7 +479,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: { id: 'org_id' } as Organization, beforeEmit: beforeEmitMock });

expect(executionOrder).toEqual(['session.touch', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(mockSession.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -534,7 +534,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('does not call __unstable__onBeforeSetActive before session.touch', async () => {
Expand DownExpand Up@@ -575,7 +575,7 @@ describe('Clerk singleton', () => {
},
});
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(sut.navigate).toHaveBeenCalledWith('/choose-organization');
});

Expand All@@ -587,7 +587,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});
});
Expand DownExpand Up@@ -660,7 +660,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSessionWithOrganization.touch).toHaveBeenCalled();
expect(mockSessionWithOrganization.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSessionWithOrganization.getToken).toHaveBeenCalled();
expect((mockSessionWithOrganization as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual(
'org_id',
Expand Down
14 changes: 10 additions & 4 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ import type {
Resources,
SDKMetadata,
SessionResource,
SessionTouchParams,
SetActiveParams,
SignedInSessionResource,
SignInProps,
Expand DownExpand Up@@ -1555,11 +1556,13 @@ export class Clerk implements ClerkInterface {
await onBeforeSetActive(newSession === null ? 'sign-out' : undefined);
}

const touchIntent: SessionTouchParams['intent'] = shouldSwitchOrganization ? 'select_org' : 'select_session';

//1. setLastActiveSession to passed user session (add a param).
// Note that this will also update the session's active organization
// id.
if (inActiveBrowserTab() || !this.#options.standardBrowser) {
await this.#touchCurrentSession(newSession);
await this.#touchCurrentSession(newSession, touchIntent);
// reload session from updated client
newSession = this.#getSessionFromClient(newSession?.id);
}
Expand DownExpand Up@@ -3016,7 +3019,7 @@ export class Clerk implements ClerkInterface {
this.#touchThrottledUntil = Date.now() + 5_000;

if (this.#options.touchSession) {
void this.#touchCurrentSession(this.session);
void this.#touchCurrentSession(this.session, 'focus');
}
});

Expand DownExpand Up@@ -3047,12 +3050,15 @@ export class Clerk implements ClerkInterface {
};

// TODO: Be more conservative about touches. Throttle, don't touch when only one user, etc
#touchCurrentSession = async (session?: SignedInSessionResource | null): Promise<void> => {
#touchCurrentSession = async (
session?: SignedInSessionResource | null,
intent: SessionTouchParams['intent'] = 'focus',
): Promise<void> => {
if (!session) {
return Promise.resolve();
}

await session.touch().catch(e => {
await session.touch({ intent }).catch(e => {
if (is4xxError(e)) {
void this.handleUnauthenticated();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import type {
SessionResource,
SessionStatus,
SessionTask,
SessionTouchParams,
SessionVerificationJSON,
SessionVerificationResource,
SessionVerifyAttemptFirstFactorParams,
Expand DownExpand Up@@ -86,10 +87,10 @@ export class Session extends BaseResource implements SessionResource {
});
};

touch = (): Promise<SessionResource> => {
touch = ({ intent }: SessionTouchParams = {}): Promise<SessionResource> => {
return this._basePost({
action: 'touch',
body: { active_organization_id: this.lastActiveOrganizationId },
body: { active_organization_id: this.lastActiveOrganizationId, intent },
}).then(res => {
// touch() will potentially change the session state, and so we need to ensure we emit the updated token that comes back in the response. This avoids potential issues where the session cookie is out of sync with the current session state.
if (res.lastActiveToken) {
Expand Down
87 changes: 87 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -467,6 +467,93 @@ describe('Session', () => {
token: session.lastActiveToken,
});
});

it('passes touch intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'focus' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'focus' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_session intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_session' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_session' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_org intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_org' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_org' },
method: 'POST',
}),
expect.anything(),
);
});
});

describe('isAuthorized()', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/types/session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,7 +239,7 @@ export interface SessionResource extends ClerkResource {
*/
end: () => Promise<SessionResource>;
remove: () => Promise<SessionResource>;
touch: () => Promise<SessionResource>;
touch: (params?: SessionTouchParams) => Promise<SessionResource>;
getToken: GetToken;
checkAuthorization: CheckAuthorization;
clearCache: () => void;
Expand DownExpand Up@@ -320,6 +320,12 @@ export type SessionStatus =
| 'revoked'
| 'pending';

export type SessionTouchIntent = 'focus' | 'select_session' | 'select_org';

export type SessionTouchParams = {
intent?: SessionTouchIntent;
};

export interface PublicUserData {
firstName: string | null;
lastName: string | null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(clerk-js): Send touch intent with session updates (core-2 backport) by nikosdouvlis · Pull Request #8135 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/warm-touch-intent.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add optional `intent` parameter to `session.touch()` to indicate why the touch was triggered (focus, session switch, or org switch). This enables the backend to skip expensive client piggybacking for focus-only touches.
26 changes: 13 additions & 13 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -204,7 +204,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

describe('with `touchSession` set to false', () => {
Expand All@@ -215,7 +215,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load({ touchSession: false });
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});
});

Expand All@@ -230,7 +230,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('sets __session and __client_uat cookie before calling __unstable__onBeforeSetActive', async () => {
Expand All@@ -252,7 +252,7 @@ describe('Clerk singleton', () => {
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));

(window as any).__unstable__onAfterSetActive = () => {
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(beforeEmitMock).toHaveBeenCalled();
};

Expand DownExpand Up@@ -299,7 +299,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession2);
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -332,7 +332,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession.getToken).toHaveBeenCalled();
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -371,7 +371,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -454,7 +454,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});

Expand All@@ -479,7 +479,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: { id: 'org_id' } as Organization, beforeEmit: beforeEmitMock });

expect(executionOrder).toEqual(['session.touch', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(mockSession.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -534,7 +534,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('does not call __unstable__onBeforeSetActive before session.touch', async () => {
Expand DownExpand Up@@ -575,7 +575,7 @@ describe('Clerk singleton', () => {
},
});
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(sut.navigate).toHaveBeenCalledWith('/choose-organization');
});

Expand All@@ -587,7 +587,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});
});
Expand DownExpand Up@@ -660,7 +660,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSessionWithOrganization.touch).toHaveBeenCalled();
expect(mockSessionWithOrganization.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSessionWithOrganization.getToken).toHaveBeenCalled();
expect((mockSessionWithOrganization as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual(
'org_id',
Expand Down
14 changes: 10 additions & 4 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ import type {
Resources,
SDKMetadata,
SessionResource,
SessionTouchParams,
SetActiveParams,
SignedInSessionResource,
SignInProps,
Expand DownExpand Up@@ -1555,11 +1556,13 @@ export class Clerk implements ClerkInterface {
await onBeforeSetActive(newSession === null ? 'sign-out' : undefined);
}

const touchIntent: SessionTouchParams['intent'] = shouldSwitchOrganization ? 'select_org' : 'select_session';

//1. setLastActiveSession to passed user session (add a param).
// Note that this will also update the session's active organization
// id.
if (inActiveBrowserTab() || !this.#options.standardBrowser) {
await this.#touchCurrentSession(newSession);
await this.#touchCurrentSession(newSession, touchIntent);
// reload session from updated client
newSession = this.#getSessionFromClient(newSession?.id);
}
Expand DownExpand Up@@ -3016,7 +3019,7 @@ export class Clerk implements ClerkInterface {
this.#touchThrottledUntil = Date.now() + 5_000;

if (this.#options.touchSession) {
void this.#touchCurrentSession(this.session);
void this.#touchCurrentSession(this.session, 'focus');
}
});

Expand DownExpand Up@@ -3047,12 +3050,15 @@ export class Clerk implements ClerkInterface {
};

// TODO: Be more conservative about touches. Throttle, don't touch when only one user, etc
#touchCurrentSession = async (session?: SignedInSessionResource | null): Promise<void> => {
#touchCurrentSession = async (
session?: SignedInSessionResource | null,
intent: SessionTouchParams['intent'] = 'focus',
): Promise<void> => {
if (!session) {
return Promise.resolve();
}

await session.touch().catch(e => {
await session.touch({ intent }).catch(e => {
if (is4xxError(e)) {
void this.handleUnauthenticated();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import type {
SessionResource,
SessionStatus,
SessionTask,
SessionTouchParams,
SessionVerificationJSON,
SessionVerificationResource,
SessionVerifyAttemptFirstFactorParams,
Expand DownExpand Up@@ -86,10 +87,10 @@ export class Session extends BaseResource implements SessionResource {
});
};

touch = (): Promise<SessionResource> => {
touch = ({ intent }: SessionTouchParams = {}): Promise<SessionResource> => {
return this._basePost({
action: 'touch',
body: { active_organization_id: this.lastActiveOrganizationId },
body: { active_organization_id: this.lastActiveOrganizationId, intent },
}).then(res => {
// touch() will potentially change the session state, and so we need to ensure we emit the updated token that comes back in the response. This avoids potential issues where the session cookie is out of sync with the current session state.
if (res.lastActiveToken) {
Expand Down
87 changes: 87 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -467,6 +467,93 @@ describe('Session', () => {
token: session.lastActiveToken,
});
});

it('passes touch intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'focus' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'focus' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_session intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_session' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_session' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_org intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_org' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_org' },
method: 'POST',
}),
expect.anything(),
);
});
});

describe('isAuthorized()', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/types/session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,7 +239,7 @@ export interface SessionResource extends ClerkResource {
*/
end: () => Promise<SessionResource>;
remove: () => Promise<SessionResource>;
touch: () => Promise<SessionResource>;
touch: (params?: SessionTouchParams) => Promise<SessionResource>;
getToken: GetToken;
checkAuthorization: CheckAuthorization;
clearCache: () => void;
Expand DownExpand Up@@ -320,6 +320,12 @@ export type SessionStatus =
| 'revoked'
| 'pending';

export type SessionTouchIntent = 'focus' | 'select_session' | 'select_org';

export type SessionTouchParams = {
intent?: SessionTouchIntent;
};

export interface PublicUserData {
firstName: string | null;
lastName: string | null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); feat(clerk-js): Send touch intent with session updates (core-2 backport) by nikosdouvlis · Pull Request #8135 · clerk/javascript · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/warm-touch-intent.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
---
'@clerk/clerk-js': patch
'@clerk/shared': patch
---

Add optional `intent` parameter to `session.touch()` to indicate why the touch was triggered (focus, session switch, or org switch). This enables the backend to skip expensive client piggybacking for focus-only touches.
26 changes: 13 additions & 13 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -204,7 +204,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

describe('with `touchSession` set to false', () => {
Expand All@@ -215,7 +215,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load({ touchSession: false });
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});
});

Expand All@@ -230,7 +230,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('sets __session and __client_uat cookie before calling __unstable__onBeforeSetActive', async () => {
Expand All@@ -252,7 +252,7 @@ describe('Clerk singleton', () => {
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));

(window as any).__unstable__onAfterSetActive = () => {
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(beforeEmitMock).toHaveBeenCalled();
};

Expand DownExpand Up@@ -299,7 +299,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession2);
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -332,7 +332,7 @@ describe('Clerk singleton', () => {

await waitFor(() => {
expect(executionOrder).toEqual(['session.touch', 'set cookie', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession.getToken).toHaveBeenCalled();
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -371,7 +371,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSession2.touch).toHaveBeenCalled();
expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSession2.getToken).toHaveBeenCalled();
expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(sut.session).toMatchObject(mockSession2);
Expand DownExpand Up@@ -454,7 +454,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});

Expand All@@ -479,7 +479,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: { id: 'org_id' } as Organization, beforeEmit: beforeEmitMock });

expect(executionOrder).toEqual(['session.touch', 'before emit']);
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id');
expect(mockSession.getToken).toHaveBeenCalled();
expect(beforeEmitMock).toHaveBeenCalledWith(mockSession);
Expand DownExpand Up@@ -534,7 +534,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
});

it('does not call __unstable__onBeforeSetActive before session.touch', async () => {
Expand DownExpand Up@@ -575,7 +575,7 @@ describe('Clerk singleton', () => {
},
});
await sut.setActive({ session: mockSession as any as PendingSessionResource });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(sut.navigate).toHaveBeenCalledWith('/choose-organization');
});

Expand All@@ -587,7 +587,7 @@ describe('Clerk singleton', () => {
const sut = new Clerk(productionPublishableKey);
await sut.load();
await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate });
expect(mockSession.touch).toHaveBeenCalled();
expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' });
expect(navigate).toHaveBeenCalled();
});
});
Expand DownExpand Up@@ -660,7 +660,7 @@ describe('Clerk singleton', () => {
await sut.setActive({ organization: 'some-org-slug' });

await waitFor(() => {
expect(mockSessionWithOrganization.touch).toHaveBeenCalled();
expect(mockSessionWithOrganization.touch).toHaveBeenCalledWith({ intent: 'select_org' });
expect(mockSessionWithOrganization.getToken).toHaveBeenCalled();
expect((mockSessionWithOrganization as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual(
'org_id',
Expand Down
14 changes: 10 additions & 4 deletions packages/clerk-js/src/core/clerk.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,6 +73,7 @@ import type {
Resources,
SDKMetadata,
SessionResource,
SessionTouchParams,
SetActiveParams,
SignedInSessionResource,
SignInProps,
Expand DownExpand Up@@ -1555,11 +1556,13 @@ export class Clerk implements ClerkInterface {
await onBeforeSetActive(newSession === null ? 'sign-out' : undefined);
}

const touchIntent: SessionTouchParams['intent'] = shouldSwitchOrganization ? 'select_org' : 'select_session';

//1. setLastActiveSession to passed user session (add a param).
// Note that this will also update the session's active organization
// id.
if (inActiveBrowserTab() || !this.#options.standardBrowser) {
await this.#touchCurrentSession(newSession);
await this.#touchCurrentSession(newSession, touchIntent);
// reload session from updated client
newSession = this.#getSessionFromClient(newSession?.id);
}
Expand DownExpand Up@@ -3016,7 +3019,7 @@ export class Clerk implements ClerkInterface {
this.#touchThrottledUntil = Date.now() + 5_000;

if (this.#options.touchSession) {
void this.#touchCurrentSession(this.session);
void this.#touchCurrentSession(this.session, 'focus');
}
});

Expand DownExpand Up@@ -3047,12 +3050,15 @@ export class Clerk implements ClerkInterface {
};

// TODO: Be more conservative about touches. Throttle, don't touch when only one user, etc
#touchCurrentSession = async (session?: SignedInSessionResource | null): Promise<void> => {
#touchCurrentSession = async (
session?: SignedInSessionResource | null,
intent: SessionTouchParams['intent'] = 'focus',
): Promise<void> => {
if (!session) {
return Promise.resolve();
}

await session.touch().catch(e => {
await session.touch({ intent }).catch(e => {
if (is4xxError(e)) {
void this.handleUnauthenticated();
}
Expand Down
5 changes: 3 additions & 2 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,7 @@ import type {
SessionResource,
SessionStatus,
SessionTask,
SessionTouchParams,
SessionVerificationJSON,
SessionVerificationResource,
SessionVerifyAttemptFirstFactorParams,
Expand DownExpand Up@@ -86,10 +87,10 @@ export class Session extends BaseResource implements SessionResource {
});
};

touch = (): Promise<SessionResource> => {
touch = ({ intent }: SessionTouchParams = {}): Promise<SessionResource> => {
return this._basePost({
action: 'touch',
body: { active_organization_id: this.lastActiveOrganizationId },
body: { active_organization_id: this.lastActiveOrganizationId, intent },
}).then(res => {
// touch() will potentially change the session state, and so we need to ensure we emit the updated token that comes back in the response. This avoids potential issues where the session cookie is out of sync with the current session state.
if (res.lastActiveToken) {
Expand Down
87 changes: 87 additions & 0 deletions packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -467,6 +467,93 @@ describe('Session', () => {
token: session.lastActiveToken,
});
});

it('passes touch intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'focus' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'focus' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_session intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_session' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_session' },
method: 'POST',
}),
expect.anything(),
);
});

it('passes select_org intent in the request body', async () => {
const sessionData = {
status: 'active',
id: 'session_1',
object: 'session',
user: createUser({}),
last_active_organization_id: 'org_123',
actor: null,
created_at: new Date().getTime(),
updated_at: new Date().getTime(),
} as SessionJSON;
const session = new Session(sessionData);

const requestSpy = BaseResource.clerk.getFapiClient().request as Mock;
requestSpy.mockResolvedValue({
payload: session,
});

await session.touch({ intent: 'select_org' });

expect(requestSpy).toHaveBeenCalledWith(
expect.objectContaining({
body: { active_organization_id: 'org_123', intent: 'select_org' },
method: 'POST',
}),
expect.anything(),
);
});
});

describe('isAuthorized()', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/types/session.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -239,7 +239,7 @@ export interface SessionResource extends ClerkResource {
*/
end: () => Promise<SessionResource>;
remove: () => Promise<SessionResource>;
touch: () => Promise<SessionResource>;
touch: (params?: SessionTouchParams) => Promise<SessionResource>;
getToken: GetToken;
checkAuthorization: CheckAuthorization;
clearCache: () => void;
Expand DownExpand Up@@ -320,6 +320,12 @@ export type SessionStatus =
| 'revoked'
| 'pending';

export type SessionTouchIntent = 'focus' | 'select_session' | 'select_org';

export type SessionTouchParams = {
intent?: SessionTouchIntent;
};

export interface PublicUserData {
firstName: string | null;
lastName: string | null;
Expand Down
Loading