⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
Merge main and preserve API-key checks alongside OIDC logout
tinseverbc71ac8de341
diff --cc apps/api/src/auth.tsindex 2ad209107,78f23fc4f..20159519f--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@@ -61,7 -54,17 +62,18 @@@ import { handleMemberAdded } from "./woimport { handleMemberRemoved } from "./workspace-members/handle-member-removed";import { handleOwnerPromoted } from "./workspace-members/handle-owner-promoted";import { hideInaccessibleInvitationProjects } from "./project-access/hide-inaccessible-invitation-projects";+import assertManagedProfileUnchanged from "./user/controllers/assert-managed-profile-unchanged";+ import { hideInvitationsFromNonInviters } from "./utils/hide-invitations-from-non-inviters";+ import { assertOwnerInvitationResendAllowed } from "./utils/assert-owner-invitation-resend-allowed";+ import {+ assertNativeAuthApiKeyAllowed,+ nativeAuthApiKey,+ } from "./utils/native-auth-api-key";+ import {+ assertNativeOrganizationReadAllowed,+ readableNativeOrganizations,+ } from "./utils/native-organization-read-access";+ import { satisfies } from "./utils/role-permissions";import clearEmailVerificationOnAdminChange from "./user/controllers/clear-email-verification-on-admin-change";import deleteAccountData from "./user/controllers/delete-account-data";import prepareAdminUserRemoval from "./user/controllers/prepare-admin-user-removal";@@@ -822,29 -794,28 +835,48 @@@ export const auth = betterAuth(},},},+ account: {+ create: {+ before: async (account, ctx) => {+ rememberSignInSessionId(account.idToken, ctx);+ },+ },+ update: {+ before: async (account, ctx) => {+ rememberSignInSessionId(account.idToken, ctx);+ },+ },+ },+ session: {+ create: {+ before: async (_session, ctx) => {+ const oidcSid = takeSignInSessionId(ctx);+ if (oidcSid) return { data: { oidcSid } };+ },+ },+ },},hooks: {- before: createAuthMiddleware(async (ctx) => {+ before: createAuthMiddleware(async (ctx): Promise<void> => {+ // Runs before provider hooks can turn a key into its owner's session.+ await assertNativeAuthApiKeyAllowed(ctx);+ let organizationViewer: {+ user: { id: string };+ session: {+ id?: string;+ activeOrganizationId?: unknown;+ activeTeamId?: unknown;+ };+ } | null = null;+ if (ctx.path.startsWith("/organization/")) {+ const key = nativeAuthApiKey(ctx);+ // Resolve real bearer sessions through the provider's bearer hook as+ // well as cookies. The nested /get-session call does not enter here.+ organizationViewer = key+ ? { user: { id: key.userId }, session: {} }+ : await auth.api.getSession({ headers: new Headers(ctx.headers) });+ await assertNativeOrganizationReadAllowed(ctx, organizationViewer);+ }if (ctx.path === "/admin/remove-user") {await prepareAdminUserRemoval(ctx);}diff --cc apps/api/src/index.tsindex dfd763e25,eb668c6bf..fecd2bd82--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@@ -19,12 -19,8 +19,13 @@@ import { HTTPException } from "hono/httimport activity from "./activity";import admin from "./admin";import { auth } from "./auth";+ import { forwardAuthRequest } from "./utils/forward-auth-request";import { organizationRoutes } from "./auth-openapi";+import {+ handleBackchannelLogoutRoute,+ MAX_LOGOUT_REQUEST_BYTES,+ noStore,+} from "./backchannel-logout";import billing from "./billing";import calendarFeed, { publicCalendarFeed } from "./calendar-feed";import column from "./column";@@@ -975,7 -920,7 +941,8 @@@ export function createApp()userId,initiatorId,workspaceId,+ c.get("apiKey")?.id,+ sessionId,);}},diff --cc apps/api/src/ws/index.tsindex 5d7ec3cef,3ab112d47..1df57fc57--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@@ -44,7 -44,7 +45,8 @@@ type ProjectConnection =userId: string;initiatorId: string;workspaceId: string;+ sessionId: string | null;+ apiKeyId?: string;};type UserConnection = {@@@ -666,7 -606,7 +693,8 @@@ export function addConnectionuserId: string,initiatorId: string,workspaceId: string,+ apiKeyId?: string,+ sessionId: string | null = null,) {if (!projectConnections.has(projectId)) {projectConnections.set(projectId, new Set());@@@ -676,7 -616,7 +704,8 @@@userId,initiatorId,workspaceId,+ sessionId,+ ...(apiKeyId ? { apiKeyId } : {}),};projectConnections.get(projectId)?.add(conn);return conn;diff --cc apps/docs/core/social-providers/custom-oauth.mdxindex e03c79e2b,c09931f57..ce61900d9--- a/apps/docs/core/social-providers/custom-oauth.mdx+++ b/apps/docs/core/social-providers/custom-oauth.mdx@@@ -232,34 -188,6 +232,34 @@@ For safety, Kaneo only links to an exisOn existing installations, local accounts created before this requirement may still have an unverified email. Those users will receive `error=account_not_linked` until they verify the local account. Before enforcing SSO-only access, keep the login form available so affected users can sign in with an email OTP or magic link, which verifies the email. If users are already locked out, temporarily set `DISABLE_LOGIN_FORM=false` and `CUSTOM_OAUTH_AUTO_LOGIN=false`, recreate the Kaneo container, and have them complete an email sign-in before enabling SSO-only access again.+## Managed profile fields++When your identity provider is the source of truth for names, profile pictures, or languages, let it manage them in Kaneo:++```bash+CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS=name,image,locale+# Optional: link people to the page where they change these fields+CUSTOM_OAUTH_ACCOUNT_URL=https://keycloak.example.com/realms/your-realm/account+```++At every sign-in through this provider, Kaneo copies the listed fields from the provider's claims. It reads the claims from the ID token when the token contains `sub` and `email`, and from the user info endpoint otherwise.++| Field | Claim | What Kaneo stores |+|-------|-------|-------------------|+| `name` | `name` | The same name Kaneo uses when it creates the account: `name`, then `given_name` and `family_name`, then `preferred_username`, then the part of the email before the `@`. |+| `image` | `picture` | An absolute `http` or `https` URL of up to 2,048 characters. Without one, Kaneo removes the profile picture, but keeps a picture uploaded in Kaneo until the provider sends one. A picture from the provider replaces the upload and deletes it. |+| `locale` | `locale` | The matching Kaneo language: first by tag, then by language and script, then by language, so `de` becomes `de-DE` and `zh-Hant` or `zh-HK` becomes `zh-TW`. A missing or unsupported value keeps the current language. |++Fields you do not list stay as they are. Accounts that Kaneo creates through the provider start with the same values. Signing in never changes the email address, but it marks the email of an account already linked to the provider as verified when the provider reports the same address as verified.++People with a linked provider account see managed fields as read-only on their profile and preferences pages, with a link to `CUSTOM_OAUTH_ACCOUNT_URL` when you set it. They can still remove a picture they uploaded in Kaneo earlier, but they cannot upload a new one. People without a linked provider account keep full editing.+- The API enforces this too, also for API keys and administrators. `POST /api/auth/update-user` and `POST /api/auth/admin/update-user` answer `403` with the code `PROFILE_FIELD_MANAGED_BY_PROVIDER` when they would change a managed field, except removing a picture uploaded in Kaneo. A request that sends the current value again succeeds. While the provider manages the picture, `PUT /api/user/avatar` answers the same way, and so does `DELETE /api/user/avatar` if a picture other than an upload made in Kaneo is stored.++The API enforces this too, including administrator edits. Profile edits through `POST /api/auth/update-user` and `POST /api/auth/admin/update-user` require a user session; API keys receive `403` with the code `SESSION_REQUIRED`. With a user session, these endpoints answer `403` with the code `PROFILE_FIELD_MANAGED_BY_PROVIDER` when they would change a managed field, except removing a picture uploaded in Kaneo. A request that sends the current value again succeeds. While the provider manages the picture, `PUT /api/user/avatar` answers the same way for sessions and API keys, and so does `DELETE /api/user/avatar` if a picture other than an upload made in Kaneo is stored.++In Keycloak, the default `profile` client scope maps the `picture` and `locale` user attributes to these claims. Keycloak only sets `locale` when internationalization is enabled for the realm.++If you remove the provider settings later, remove `CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS` as well, so people can edit their profiles in Kaneo again.+## Security Notes- Always use HTTPS in productiondiff --cc tests/api-integration/managed-profile-edits.test.tsindex 09e9f2299,000000000..bbc8f35c7mode 100644,000000..100644--- a/tests/api-integration/managed-profile-edits.test.ts+++ b/tests/api-integration/managed-profile-edits.test.ts@@@ -1,489 -1,0 +1,491 @@@+import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import { auth } from "../../apps/api/src/auth";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { buildAvatarUrl } from "../../apps/api/src/user/avatar";+import { signUpWithSession } from "./helpers/auth-session";+import { resetTestDatabase } from "./helpers/database";+import { readErrorBody } from "./helpers/error-body";+import { createWorkspaceMember } from "./helpers/fixtures";++type App = ReturnType<typeof createApp>["app"];++const PICTURE = "https://id.example.com/jane.png";+const PNG = Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00,+]).toString("base64");++async function linkCustomAccount(userId: string) {+ await db.insert(schema.accountTable).values({+ accountId: `sub-${randomUUID()}`,+ providerId: "custom",+ userId,+ });+}++async function signUpProviderUser(app: App) {+ const session = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Jane Doe",+ });+ await linkCustomAccount(session.userId);+ return session;+}++async function setImage(userId: string, image: string | null) {+ await db+ .update(schema.userTable)+ .set({ image })+ .where(eq(schema.userTable.id, userId));+}++async function storeUpload(userId: string) {+ const [avatar] = await db+ .insert(schema.userAvatarTable)+ .values({+ userId,+ mimeType: "image/png",+ size: 9,+ data: Buffer.from(PNG, "base64"),+ })+ .returning({ id: schema.userAvatarTable.id });+ if (!avatar) throw new Error("Failed to seed avatar");+ const image = buildAvatarUrl(avatar.id);+ await setImage(userId, image);+ return image;+}++async function loadProfile(userId: string) {+ const [user] = await db+ .select({+ name: schema.userTable.name,+ email: schema.userTable.email,+ emailVerified: schema.userTable.emailVerified,+ image: schema.userTable.image,+ locale: schema.userTable.locale,+ })+ .from(schema.userTable)+ .where(eq(schema.userTable.id, userId));+ return user;+}++function listAvatars() {+ return db+ .select({ id: schema.userAvatarTable.id })+ .from(schema.userAvatarTable);+}++function updateUser(+ app: App,+ headers: Record<string, string>,+ data: Record<string, unknown>,+) {+ return app.request("/api/auth/update-user", {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: JSON.stringify(data),+ });+}++function adminUpdateUser(+ app: App,+ cookies: string,+ userId: string,+ data: Record<string, unknown>,+) {+ return app.request("/api/auth/admin/update-user", {+ method: "POST",+ headers: { "content-type": "application/json", cookie: cookies },+ body: JSON.stringify({ userId, data }),+ });+}++function uploadAvatar(app: App, cookies: string) {+ return app.request("/api/user/avatar", {+ method: "PUT",+ headers: { "content-type": "application/json", cookie: cookies },+ body: JSON.stringify({ contentType: "image/png", data: PNG }),+ });+}++function removeAvatar(app: App, cookies: string) {+ return app.request("/api/user/avatar", {+ method: "DELETE",+ headers: { cookie: cookies },+ });+}++async function expectManagedRefusal(response: Response) {+ expect(response.status).toBe(403);+ expect(await readErrorBody(response)).toMatchObject({+ code: "PROFILE_FIELD_MANAGED_BY_PROVIDER",+ });+}++describe("API integration: profile fields managed by the custom provider", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ describe("POST /api/auth/update-user", () => {+ it.each([+ ["name", { name: "Janet Doe" }],+ ["locale", { locale: "fr-FR" }],+ ["image", { image: PICTURE }],+ ])("refuses a new %s and keeps the stored profile", async (field, data) => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", field);+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ const before = await loadProfile(userId);++ await expectManagedRefusal(+ await updateUser(app, { cookie: cookies }, data),+ );+ expect(await loadProfile(userId)).toEqual(before);+ });++ it("accepts the current managed values sent again", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,image,locale");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ await setImage(userId, PICTURE);++ const response = await updateUser(+ app,+ { cookie: cookies },+ { name: "Jane Doe", image: PICTURE, locale: null },+ );++ expect(response.status).toBe(200);+ });++ it("accepts changes to fields the provider does not manage", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);++ const response = await updateUser(+ app,+ { cookie: cookies },+ { name: "Jane Doe", locale: "de-DE", image: PICTURE },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(userId)).toMatchObject({+ name: "Jane Doe",+ locale: "de-DE",+ image: PICTURE,+ });+ });++ it("keeps profiles editable while no field is managed", async () => {+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);++ const response = await updateUser(+ app,+ { cookie: cookies },+ { name: "Janet Doe" },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(userId)).toMatchObject({ name: "Janet Doe" });+ });++ it("keeps profiles editable for people without a provider account", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,image,locale");+ const { app } = createApp();+ const { userId, cookies } = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Local Person",+ });++ const response = await updateUser(+ app,+ { cookie: cookies },+ { name: "Renamed Person", image: PICTURE, locale: "de-DE" },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(userId)).toMatchObject({+ name: "Renamed Person",+ image: PICTURE,+ locale: "de-DE",+ });+ });++ it.each(["x-api-key", "Authorization"])(+ "refuses a managed change sent with an API key in %s",+ async (header) => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ const { app } = createApp();+ const { userId } = await signUpProviderUser(app);+ const { key } = await auth.api.createApiKey({+ body: { userId, name: "Managed profile test" },+ });+- await expectManagedRefusal(- await updateUser(- app,- { [header]: header === "Authorization" ? `Bearer ${key}` : key },- { name: "Janet Doe" },- ),++ const response = await updateUser(++ app,++ { [header]: header === "Authorization" ? `Bearer ${key}` : key },++ { name: "Janet Doe" },+ );++ expect(response.status).toBe(403);++ expect(await readErrorBody(response)).toMatchObject({++ code: "SESSION_REQUIRED",++ });+ expect(await loadProfile(userId)).toMatchObject({ name: "Jane Doe" });+ },+ );++ it("refuses a managed change sent with a session bearer token", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name");+ const { app } = createApp();+ const signUp = await app.request("/api/auth/sign-up/email", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ email: "[email protected]",+ password: "correct horse battery staple",+ name: "Jane Doe",+ }),+ });+ expect(signUp.status).toBe(200);+ const { token, user } = (await signUp.json()) as {+ token: string;+ user: { id: string };+ };+ await linkCustomAccount(user.id);++ await expectManagedRefusal(+ await updateUser(+ app,+ { Authorization: `Bearer ${token}` },+ { name: "Janet Doe" },+ ),+ );+ expect(await loadProfile(user.id)).toMatchObject({ name: "Jane Doe" });+ });+ });++ describe("POST /api/auth/admin/update-user", () => {+ async function setUp(managedFields = "name") {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", managedFields);+ const { app } = createApp();+ const admin = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Instance Admin",+ role: "admin",+ });+ const target = await createWorkspaceMember({ role: "member" });+ return { app, admin, target };+ }++ it.each([+ ["name", { name: "Renamed Member" }],+ ["image", { image: PICTURE }],+ ["locale", { locale: "fr-FR" }],+ ])("refuses a new %s for a provider user", async (field, data) => {+ const { app, admin, target } = await setUp(field);+ await linkCustomAccount(target.user.id);+ const before = await loadProfile(target.user.id);++ await expectManagedRefusal(+ await adminUpdateUser(app, admin.cookies, target.user.id, data),+ );+ expect(await loadProfile(target.user.id)).toEqual(before);+ });++ it("changes the email of a provider user when the managed name stays", async () => {+ const { app, admin, target } = await setUp();+ await linkCustomAccount(target.user.id);++ const response = await adminUpdateUser(+ app,+ admin.cookies,+ target.user.id,+ { name: target.user.name, email: "[email protected]" },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(target.user.id)).toMatchObject({+ name: target.user.name,+ email: "[email protected]",+ emailVerified: false,+ });+ });++ it("renames people without a provider account", async () => {+ const { app, admin, target } = await setUp();++ const response = await adminUpdateUser(+ app,+ admin.cookies,+ target.user.id,+ { name: "Renamed Member" },+ );++ expect(response.status).toBe(200);+ expect(await loadProfile(target.user.id)).toMatchObject({+ name: "Renamed Member",+ });+ });+ });++ describe("profile picture", () => {+ it("refuses an upload while the provider manages the picture", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { cookies } = await signUpProviderUser(app);++ await expectManagedRefusal(await uploadAvatar(app, cookies));+ expect(await listAvatars()).toHaveLength(0);+ });++ it("refuses removing the picture the provider sent", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ await setImage(userId, PICTURE);++ await expectManagedRefusal(+ await updateUser(app, { cookie: cookies }, { image: null }),+ );+ await expectManagedRefusal(await removeAvatar(app, cookies));+ expect(await loadProfile(userId)).toMatchObject({ image: PICTURE });+ });++ it("still removes a picture uploaded to Kaneo before", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ const upload = await storeUpload(userId);++ expect(+ (await updateUser(app, { cookie: cookies }, { image: null })).status,+ ).toBe(200);+ expect((await removeAvatar(app, cookies)).status).toBe(200);++ expect(await loadProfile(userId)).toMatchObject({ image: null });+ expect(await listAvatars()).toHaveLength(0);+ expect((await app.request(upload)).status).toBe(404);+ });++ it("also removes an upload when the file is deleted before the picture is cleared", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ await storeUpload(userId);++ expect((await removeAvatar(app, cookies)).status).toBe(200);+ expect(+ (await updateUser(app, { cookie: cookies }, { image: null })).status,+ ).toBe(200);++ expect(await loadProfile(userId)).toMatchObject({ image: null });+ expect(await listAvatars()).toHaveLength(0);+ });++ it("refuses replacing an upload with another one", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpProviderUser(app);+ const upload = await storeUpload(userId);++ await expectManagedRefusal(await uploadAvatar(app, cookies));+ await expectManagedRefusal(+ await updateUser(+ app,+ { cookie: cookies },+ { image: buildAvatarUrl("another-avatar") },+ ),+ );+ expect(await loadProfile(userId)).toMatchObject({ image: upload });+ });++ it("keeps uploads open for people without a provider account", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { cookies } = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Local Person",+ });++ const response = await uploadAvatar(app, cookies);++ expect(response.status).toBe(200);+ expect(await listAvatars()).toHaveLength(1);+ });++ it("keeps removal open for people without a provider account", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ const { app } = createApp();+ const { userId, cookies } = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Local Person",+ });+ await storeUpload(userId);+ await setImage(userId, PICTURE);++ expect((await removeAvatar(app, cookies)).status).toBe(200);+ expect(await listAvatars()).toHaveLength(0);+ expect(+ (await updateUser(app, { cookie: cookies }, { image: null })).status,+ ).toBe(200);+ expect(await loadProfile(userId)).toMatchObject({ image: null });+ });++ it("keeps uploads open while the picture is not managed", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "name,locale");+ const { app } = createApp();+ const { cookies } = await signUpProviderUser(app);++ expect((await uploadAvatar(app, cookies)).status).toBe(200);+ expect((await removeAvatar(app, cookies)).status).toBe(200);+ });+ });++ describe("GET /api/user/me", () => {+ async function readManagedFields(app: App, cookies: string) {+ const response = await app.request("/api/user/me", {+ headers: { cookie: cookies },+ });+ expect(response.status).toBe(200);+ const body = (await response.json()) as {+ managedProfileFields: string[];+ };+ return body.managedProfileFields;+ }++ it("lists the managed fields for a provider user", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image,name");+ const { app } = createApp();+ const { cookies } = await signUpProviderUser(app);++ expect(await readManagedFields(app, cookies)).toEqual(["name", "image"]);+ });++ it("lists nothing for people without a provider account", async () => {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image,name");+ const { app } = createApp();+ const { cookies } = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Local Person",+ });++ expect(await readManagedFields(app, cookies)).toEqual([]);+ });+ });+});diff --cc tests/api/ws/session-connections.test.tsindex 987b0d60b,000000000..265f1a4e3mode 100644,000000..100644--- a/tests/api/ws/session-connections.test.ts+++ b/tests/api/ws/session-connections.test.ts@@@ -1,135 -1,0 +1,151 @@@+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";++vi.mock("../../../apps/api/src/events", () => ({+ subscribeToEvent: vi.fn(),+ publishEvent: vi.fn(),+}));++import {+ addConnection,+ addUserConnection,+ broadcastToUser,+ initializeWebSocketAdapter,+ removeConnection,+ removeUserConnection,+ revokeSessionConnections,+ SESSION_ENDED_CLOSE_CODE,+ shutdownWebSocketAdapter,+} from "../../../apps/api/src/ws/index";++function makeFakeWs() {+ return {+ send: vi.fn(),+ close: vi.fn(),+ readyState: 1,+ raw: undefined,+ url: null,+ protocol: null,+ } as never;+}++function mocksOf(ws: unknown) {+ return ws as {+ send: ReturnType<typeof vi.fn>;+ close: ReturnType<typeof vi.fn>;+ };+}++describe("revokeSessionConnections", () => {+ const originalRedisUrl = process.env.REDIS_URL;++ beforeEach(async () => {+ delete process.env.REDIS_URL;+ await initializeWebSocketAdapter();+ });++ afterEach(async () => {+ await shutdownWebSocketAdapter();+ if (originalRedisUrl === undefined) {+ delete process.env.REDIS_URL;+ } else {+ process.env.REDIS_URL = originalRedisUrl;+ }+ });++ it("closes only the sockets of the ended session and keeps delivering to the others", async () => {+ const firstTab = makeFakeWs();+ const secondTab = makeFakeWs();+ const phone = makeFakeWs();+ const apiKey = makeFakeWs();+ const endedBoard = makeFakeWs();+ const phoneBoard = makeFakeWs();++ const apiKeyBoard = makeFakeWs();+ const connections = [+ addUserConnection("user-1", firstTab, "session-a"),+ addUserConnection("user-1", secondTab, "session-a"),+ addUserConnection("user-1", phone, "session-b"),+ addUserConnection("user-1", apiKey),+ ];+ const boards = [+ addConnection(+ "project-1",+ endedBoard,+ "user-1",+ "user-1:a",+ "ws-1",++ undefined,+ "session-a",+ ),+ addConnection(+ "project-1",+ phoneBoard,+ "user-1",+ "user-1:b",+ "ws-1",++ undefined,+ "session-b",+ ),++ addConnection(++ "project-1",++ apiKeyBoard,++ "user-1",++ "user-1:key",++ "ws-1",++ "api-key-1",++ ),+ ];+++ expect(boards[2]).toMatchObject({++ apiKeyId: "api-key-1",++ sessionId: null,++ });+++ await revokeSessionConnections("user-1", ["session-a"]);++ for (const ws of [firstTab, secondTab, endedBoard]) {+ expect(mocksOf(ws).close).toHaveBeenCalledWith(+ SESSION_ENDED_CLOSE_CODE,+ "Session ended",+ );+ expect(mocksOf(ws).send).not.toHaveBeenCalled();+ }- for (const ws of [phone, apiKey, phoneBoard]) {++ for (const ws of [phone, apiKey, phoneBoard, apiKeyBoard]) {+ expect(mocksOf(ws).close).not.toHaveBeenCalled();+ expect(mocksOf(ws).send).not.toHaveBeenCalled();+ }++ broadcastToUser("user-1", { type: "NOTIFICATION_CREATED" });++ await vi.waitFor(+ () => {+ for (const ws of [phone, apiKey])+ expect(mocksOf(ws).send).toHaveBeenCalledWith(+ JSON.stringify({ type: "NOTIFICATION_CREATED" }),+ );+ },+ { timeout: 300 },+ );+ expect(mocksOf(firstTab).send).not.toHaveBeenCalled();+ expect(mocksOf(secondTab).send).not.toHaveBeenCalled();++ for (const conn of connections) removeUserConnection("user-1", conn);+ for (const conn of boards) removeConnection("project-1", conn);+ });++ it("does nothing without session IDs", async () => {+ const ws = makeFakeWs();+ const conn = addUserConnection("user-1", ws, "session-a");++ await revokeSessionConnections("user-1", []);++ expect(mocksOf(ws).close).not.toHaveBeenCalled();+ removeUserConnection("user-1", conn);+ });+});diff --cc tests/api/ws/user-broadcast-redis-failure.test.tsindex 5745c8af8,606fe9cf1..214ba048c--- a/tests/api/ws/user-broadcast-redis-failure.test.ts+++ b/tests/api/ws/user-broadcast-redis-failure.test.ts@@@ -187,109 -165,6 +187,111 @@@ describe("broadcastToUser with the redi});});+describe("ended sessions with the redis adapter", () => {+ beforeEach(async () => {+ publish.mockReset().mockResolvedValue(1);+ listeners.length = 0;+ await initializeWebSocketAdapter();+ });++ afterEach(async () => {+ await shutdownWebSocketAdapter();+ sessionRows.mockReset().mockResolvedValue([]);+ });++ it("publishes the ended session IDs to the other instances", async () => {+ await revokeSessionConnections("user-1", ["session-a"]);++ await vi.waitFor(() => expect(publish).toHaveBeenCalledOnce());+ expect(JSON.parse(publish.mock.calls[0][1])).toMatchObject({+ userId: "user-1",+ message: { type: "SESSIONS_ENDED", sessionIds: ["session-a"] },+ });+ });++ it("closes only the ended session's sockets when another instance ends it", () => {+ const ended = makeFakeWs();+ const kept = makeFakeWs();+ const endedBoard = makeFakeWs();+ const connections = [+ addUserConnection("user-1", ended, "session-a"),+ addUserConnection("user-1", kept, "session-b"),+ ];+ const board = addConnection(+ "project",+ endedBoard,+ "user-1",+ "window",+ "workspace",++ undefined,+ "session-a",+ );+ try {+ emitUserBroadcast({+ userId: "user-1",+ origin: "other-instance",+ message: { type: "SESSIONS_ENDED", sessionIds: ["session-a"] },+ });++ for (const ws of [ended, endedBoard])+ expect(closeMock(ws)).toHaveBeenCalledWith(+ SESSION_ENDED_CLOSE_CODE,+ "Session ended",+ );+ expect(closeMock(kept)).not.toHaveBeenCalled();+ expect(sendMock(kept)).not.toHaveBeenCalled();+ } finally {+ for (const conn of connections) removeUserConnection("user-1", conn);+ removeConnection("project", board);+ }+ });++ it("closes the sockets of sessions that ended while the subscriber was away", async () => {+ sessionRows.mockResolvedValue([{ id: "session-b" }]);+ const ended = makeFakeWs();+ const kept = makeFakeWs();+ const apiKey = makeFakeWs();+ const endedBoard = makeFakeWs();+ const connections = [+ addUserConnection("user-1", ended, "session-a"),+ addUserConnection("user-1", kept, "session-b"),+ addUserConnection("user-1", apiKey),+ ];+ const board = addConnection(+ "project",+ endedBoard,+ "user-1",+ "window",+ "workspace",++ undefined,+ "session-c",+ );+ try {+ const ready = subscriber.on.mock.calls+ .filter(([event]) => event === "ready")+ .at(-1)?.[1];+ ready?.("", "", "");++ await vi.waitFor(() =>+ expect(closeMock(ended)).toHaveBeenCalledWith(+ SESSION_ENDED_CLOSE_CODE,+ "Session ended",+ ),+ );+ expect(closeMock(endedBoard)).toHaveBeenCalledWith(+ SESSION_ENDED_CLOSE_CODE,+ "Session ended",+ );+ expect(closeMock(kept)).not.toHaveBeenCalled();+ expect(closeMock(apiKey)).not.toHaveBeenCalled();+ expect(sessionRows).toHaveBeenCalledOnce();+ } finally {+ for (const conn of connections) removeUserConnection("user-1", conn);+ removeConnection("project", board);+ }+ });+});+it("resynchronizes healthy browser sockets after the Redis subscriber recovers", async () => {await initializeWebSocketAdapter();const ws = makeFakeWs();