Open-source and local-first Slack and Notion alternative that puts you in control of your data
TypeScript chatchat-applicationcrdteditorelectronknowledge-baselocal-firstnotionnotion-alternativerealtime-collaborationself-hostedslacksqliteteam-collaborationwikiyjs
User access improvements
Hakan Shehu15b2384a7e04
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.tsindex 8bdada7b..156579dd 100644--- a/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts+++ b/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts@@ -11,8 +11,6 @@ export const createUsersTable: Migration = {.addColumn('custom_name', 'text').addColumn('custom_avatar', 'text').addColumn('role', 'text', (col) => col.notNull())- .addColumn('storage_limit', 'integer', (col) => col.notNull())- .addColumn('max_file_size', 'integer', (col) => col.notNull()).addColumn('status', 'integer', (col) => col.notNull()).addColumn('created_at', 'text', (col) => col.notNull()).addColumn('updated_at', 'text')diff --git a/apps/desktop/src/main/databases/workspace/schema.ts b/apps/desktop/src/main/databases/workspace/schema.tsindex 800e8d89..632d5169 100644--- a/apps/desktop/src/main/databases/workspace/schema.ts+++ b/apps/desktop/src/main/databases/workspace/schema.ts@@ -20,8 +20,6 @@ interface UserTable {custom_name: ColumnType<string | null, string | null, string | null>;custom_avatar: ColumnType<string | null, string | null, string | null>;role: ColumnType<WorkspaceRole, WorkspaceRole, WorkspaceRole>;- storage_limit: ColumnType<bigint, bigint, bigint>;- max_file_size: ColumnType<bigint, bigint, bigint>;status: ColumnType<UserStatus, UserStatus, UserStatus>;created_at: ColumnType<string, string, never>;updated_at: ColumnType<string | null, string | null, string | null>;diff --git a/apps/desktop/src/main/services/accounts/account-client.ts b/apps/desktop/src/main/services/accounts/account-client.tsindex 6ac4278d..0b4062d7 100644--- a/apps/desktop/src/main/services/accounts/account-client.ts+++ b/apps/desktop/src/main/services/accounts/account-client.ts@@ -51,7 +51,7 @@ export class AccountClient {return response;} catch (error) {this.debug(`Error in request for account ${this.account.id}: ${error}`);- if (isAxiosError(error) && this.isServerError(error)) {+ if (isAxiosError(error) && this.shouldBackoff(error)) {this.backoff.increaseError();}throw error;@@ -88,11 +88,15 @@ export class AccountClient {return this.request<T>('delete', path, config);}- private isServerError(error: AxiosError): boolean {+ private shouldBackoff(error: AxiosError): boolean {if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {return true;}const status = error.response?.status ?? 0;+ if (status === 429) {+ return true;+ }+return status >= 500 && status < 600;}}diff --git a/apps/desktop/src/main/services/accounts/account-service.ts b/apps/desktop/src/main/services/accounts/account-service.tsindex 5a33deb4..3b8279a9 100644--- a/apps/desktop/src/main/services/accounts/account-service.ts+++ b/apps/desktop/src/main/services/accounts/account-service.ts@@ -69,9 +69,8 @@ export class AccountService {this.client = new AccountClient(this);this.connection = new AccountConnection(this);- this.eventLoop = new EventLoop(ms('1 minute'), ms('1 second'), () => {- this.sync();- });+ this.sync = this.sync.bind(this);+ this.eventLoop = new EventLoop(ms('1 minute'), ms('1 second'), this.sync);this.eventSubscriptionId = eventBus.subscribe((event) => {if (@@ -222,7 +221,8 @@ export class AccountService {message.type === 'account_updated' ||message.type === 'workspace_deleted' ||message.type === 'workspace_updated' ||- message.type === 'user_created'+ message.type === 'user_created' ||+ message.type === 'user_updated') {this.eventLoop.trigger();}diff --git a/apps/desktop/src/main/services/workspaces/user-service.ts b/apps/desktop/src/main/services/workspaces/user-service.tsindex 01d5100f..ca907600 100644--- a/apps/desktop/src/main/services/workspaces/user-service.ts+++ b/apps/desktop/src/main/services/workspaces/user-service.ts@@ -26,12 +26,10 @@ export class UserService {name: user.name,avatar: user.avatar,role: user.role,- storage_limit: BigInt(user.storageLimit),- max_file_size: BigInt(user.maxFileSize),version: BigInt(user.version),created_at: user.createdAt,updated_at: user.updatedAt,- status: UserStatus.Active,+ status: user.status,custom_name: user.customName,custom_avatar: user.customAvatar,})@@ -44,8 +42,7 @@ export class UserService {custom_name: user.customName,custom_avatar: user.customAvatar,role: user.role,- storage_limit: BigInt(user.storageLimit),- max_file_size: BigInt(user.maxFileSize),+ status: user.status,version: BigInt(user.version),updated_at: user.updatedAt,})diff --git a/apps/desktop/src/main/services/workspaces/workspace-service.ts b/apps/desktop/src/main/services/workspaces/workspace-service.tsindex d1d1d8ab..324c2f92 100644--- a/apps/desktop/src/main/services/workspaces/workspace-service.ts+++ b/apps/desktop/src/main/services/workspaces/workspace-service.ts@@ -144,6 +144,11 @@ export class WorkspaceService {fs.rmSync(workspacePath, { recursive: true, force: true });}+ await this.account.database+ .deleteFrom('workspaces')+ .where('id', '=', this.workspace.id)+ .execute();+eventBus.publish({type: 'workspace_deleted',workspace: this.workspace,diff --git a/apps/server/src/controllers/client/accounts/account-sync.ts b/apps/server/src/controllers/client/accounts/account-sync.tsindex 4fc66f1f..3941b9b4 100644--- a/apps/server/src/controllers/client/accounts/account-sync.ts+++ b/apps/server/src/controllers/client/accounts/account-sync.ts@@ -5,6 +5,7 @@ import {WorkspaceRole,ApiErrorCode,AccountSyncInput,+ UserStatus,} from '@colanode/core';import { database } from '@/data/database';@@ -57,6 +58,8 @@ export const accountSyncHandler = async (const users = await database.selectFrom('users').where('account_id', '=', account.id)+ .where('status', '=', UserStatus.Active)+ .where('role', '!=', 'none').selectAll().execute();diff --git a/apps/server/src/controllers/client/workspaces/users/user-role-update.ts b/apps/server/src/controllers/client/workspaces/users/user-role-update.tsindex a78f99cb..c7ae9e7d 100644--- a/apps/server/src/controllers/client/workspaces/users/user-role-update.ts+++ b/apps/server/src/controllers/client/workspaces/users/user-role-update.ts@@ -1,5 +1,5 @@import { Request, Response } from 'express';-import { UserRoleUpdateInput, ApiErrorCode } from '@colanode/core';+import { UserRoleUpdateInput, ApiErrorCode, UserStatus } from '@colanode/core';import { database } from '@/data/database';import { SelectUser } from '@/data/schema';@@ -34,10 +34,12 @@ export const userRoleUpdateHandler = async (});}+ const status = input.role === 'none' ? UserStatus.Removed : UserStatus.Active;await database.updateTable('users').set({role: input.role,+ status,updated_at: new Date(),updated_by: user.id,})@@ -47,7 +49,7 @@ export const userRoleUpdateHandler = async (eventBus.publish({type: 'user_updated',userId: userToUpdate.id,- accountId: user.account_id,+ accountId: userToUpdate.account_id,workspaceId: userToUpdate.workspace_id,});diff --git a/apps/server/src/controllers/client/workspaces/workspace-get.ts b/apps/server/src/controllers/client/workspaces/workspace-get.tsindex b1140415..2b23bc69 100644--- a/apps/server/src/controllers/client/workspaces/workspace-get.ts+++ b/apps/server/src/controllers/client/workspaces/workspace-get.ts@@ -1,4 +1,9 @@-import { WorkspaceRole, WorkspaceOutput, ApiErrorCode } from '@colanode/core';+import {+ WorkspaceRole,+ WorkspaceOutput,+ ApiErrorCode,+ UserStatus,+} from '@colanode/core';import { Request, Response } from 'express';import { database } from '@/data/database';@@ -30,7 +35,7 @@ export const workspaceGetHandler = async (.where('account_id', '=', res.locals.account.id).executeTakeFirst();- if (!user) {+ if (!user || user.status !== UserStatus.Active || user.role === 'none') {return ResponseBuilder.forbidden(res, {code: ApiErrorCode.WorkspaceNoAccess,message: 'You do not have access to this workspace.',diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.tsindex 4d360fd1..aec109f6 100644--- a/apps/server/src/data/schema.ts+++ b/apps/server/src/data/schema.ts@@ -8,6 +8,7 @@ import {MessageType,MessageAttributes,TransactionOperation,+ UserStatus,} from '@colanode/core';import {ColumnType,@@ -86,7 +87,7 @@ interface UserTable {created_by: ColumnType<string, string, never>;updated_at: ColumnType<Date | null, Date | null, Date>;updated_by: ColumnType<string | null, string | null, string>;- status: ColumnType<number, number, number>;+ status: ColumnType<UserStatus, UserStatus, UserStatus>;version: ColumnType<bigint, never, never>;}diff --git a/apps/server/src/middlewares/workspace.ts b/apps/server/src/middlewares/workspace.tsindex b31bde50..63494dbf 100644--- a/apps/server/src/middlewares/workspace.ts+++ b/apps/server/src/middlewares/workspace.ts@@ -1,5 +1,5 @@import { NextFunction, Request, RequestHandler, Response } from 'express';-import { ApiErrorCode } from '@colanode/core';+import { ApiErrorCode, UserStatus } from '@colanode/core';import { database } from '@/data/database';import { ResponseBuilder } from '@/lib/response-builder';@@ -18,7 +18,7 @@ export const workspaceMiddleware: RequestHandler = async (.where('account_id', '=', res.locals.account.id).executeTakeFirst();- if (!user) {+ if (!user || user.status !== UserStatus.Active || user.role === 'none') {return ResponseBuilder.forbidden(res, {code: ApiErrorCode.WorkspaceNoAccess,message: 'You do not have access to this workspace.',diff --git a/apps/server/src/services/account-service.ts b/apps/server/src/services/account-service.tsindex 1ce3dfc1..cc81b53e 100644--- a/apps/server/src/services/account-service.ts+++ b/apps/server/src/services/account-service.ts@@ -3,6 +3,7 @@ import {IdType,LoginSuccessOutput,LoginVerifyOutput,+ UserStatus,WorkspaceOutput,WorkspaceRole,} from '@colanode/core';@@ -37,6 +38,8 @@ class AccountService {const users = await database.selectFrom('users').where('account_id', '=', account.id)+ .where('status', '=', UserStatus.Active)+ .where('role', '!=', 'none').selectAll().execute();diff --git a/apps/server/src/services/interaction-service.ts b/apps/server/src/services/interaction-service.tsdeleted file mode 100644index 37b83e01..00000000--- a/apps/server/src/services/interaction-service.ts+++ /dev/null@@ -1,152 +0,0 @@-// import {-// InteractionAttributes,-// InteractionEvent,-// mergeInteractionAttributes,-// } from '@colanode/core';--// import { database } from '@/data/database';--// const UPDATE_RETRIES_COUNT = 10;--// class InteractionService {-// public async syncLocalInteractions(-// accountId: string,-// message: SyncInteractionsMessage-// ) {-// const user = await database-// .selectFrom('users')-// .selectAll()-// .where('id', '=', message.userId)-// .executeTakeFirst();--// if (!user || user.account_id !== accountId) {-// return false;-// }--// for (let i = 0; i < UPDATE_RETRIES_COUNT; i++) {-// const synced = await this.trySyncInteraction(user.workspace_id, message);--// if (synced) {-// return true;-// }-// }--// return false;-// }--// private async trySyncInteraction(-// _: string,-// __: SyncInteractionsMessage-// ): Promise<boolean> {-// return true;-// // if (message.events.length === 0) {-// // return true;-// // }--// // const firstEvent = message.events[0];-// // if (!firstEvent) {-// // return true;-// // }--// // const lastEvent = message.events[message.events.length - 1];-// // if (!lastEvent) {-// // return true;-// // }--// // const interaction = await database-// // .selectFrom('interactions')-// // .selectAll()-// // .where('user_id', '=', message.userId)-// // .where('node_id', '=', message.nodeId)-// // .executeTakeFirst();--// // const attributes = this.buildInteractionAttributes(-// // interaction?.attributes,-// // message.events-// // );--// // if (!attributes) {-// // return true;-// // }--// // if (interaction) {-// // const updatedInteraction = await database-// // .updateTable('interactions')-// // .returningAll()-// // .set({-// // attributes: JSON.stringify(attributes),-// // updated_at: new Date(lastEvent.createdAt),-// // server_updated_at: new Date(),-// // })-// // .where('user_id', '=', message.userId)-// // .where('node_id', '=', message.nodeId)-// // .where('version', '=', interaction.version)-// // .executeTakeFirst();--// // if (updatedInteraction) {-// // eventBus.publish({-// // type: 'interaction_updated',-// // userId: message.userId,-// // nodeId: message.nodeId,-// // rootId: message.rootId,-// // workspaceId,-// // });--// // return true;-// // }-// // }--// // const createdInteraction = await database-// // .insertInto('interactions')-// // .returningAll()-// // .values({-// // user_id: message.userId,-// // node_id: message.nodeId,-// // workspace_id: workspaceId,-// // attributes: JSON.stringify(attributes),-// // created_at: new Date(firstEvent.createdAt),-// // server_created_at: new Date(),-// // })-// // .onConflict((oc) => oc.columns(['user_id', 'node_id']).doNothing())-// // .executeTakeFirst();--// // if (createdInteraction) {-// // eventBus.publish({-// // type: 'interaction_updated',-// // userId: message.userId,-// // nodeId: message.nodeId,-// // rootId: message.rootId,-// // workspaceId,-// // });--// // return true;-// // }--// // return false;-// }--// private buildInteractionAttributes(-// attributes: InteractionAttributes | undefined,-// events: InteractionEvent[]-// ): InteractionAttributes | null {-// if (events.length === 0) {-// return null;-// }--// let result = { ...attributes };-// for (const event of events) {-// const merged = mergeInteractionAttributes(-// result,-// event.attribute,-// event.value-// );-// if (merged) {-// result = merged;-// }-// }--// return result;-// }-// }--// export const interactionService = new InteractionService();diff --git a/apps/server/src/services/socket-connection.ts b/apps/server/src/services/socket-connection.tsindex 8e52e20d..f5f94bf9 100644--- a/apps/server/src/services/socket-connection.ts+++ b/apps/server/src/services/socket-connection.ts@@ -3,7 +3,7 @@ import {Message,SynchronizerInput,SynchronizerInputMessage,- WorkspaceStatus,+ UserStatus,createDebugger,} from '@colanode/core';@@ -15,6 +15,7 @@ import {CollaborationUpdatedEvent,Event,UserCreatedEvent,+ UserUpdatedEvent,WorkspaceDeletedEvent,WorkspaceUpdatedEvent,} from '@/types/events';@@ -100,6 +101,8 @@ export class SocketConnection {this.handleCollaborationUpdatedEvent(event);} else if (event.type === 'user_created') {this.handleUserCreatedEvent(event);+ } else if (event.type === 'user_updated') {+ this.handleUserUpdatedEvent(event);}for (const user of this.users.values()) {@@ -256,12 +259,14 @@ export class SocketConnection {const user = await database.selectFrom('users').where('id', '=', userId)+ .where('status', '=', UserStatus.Active)+ .where('role', '!=', 'none').selectAll().executeTakeFirst();if (!user ||- user.status !== WorkspaceStatus.Active ||+ user.status !== UserStatus.Active ||user.account_id !== this.account.id) {return null;@@ -389,4 +394,16 @@ export class SocketConnection {userId: event.userId,});}++ private handleUserUpdatedEvent(event: UserUpdatedEvent) {+ if (event.accountId !== this.account.id) {+ return;+ }++ this.sendMessage({+ type: 'user_updated',+ accountId: event.accountId,+ userId: event.userId,+ });+ }}diff --git a/apps/server/src/synchronizers/users.ts b/apps/server/src/synchronizers/users.tsindex 7414461c..5a172cf3 100644--- a/apps/server/src/synchronizers/users.ts+++ b/apps/server/src/synchronizers/users.ts@@ -65,8 +65,6 @@ export class UserSynchronizer extends BaseSynchronizer<SyncUsersInput> {avatar: user.avatar,customName: user.custom_name,customAvatar: user.custom_avatar,- storageLimit: user.storage_limit.toString(),- maxFileSize: user.max_file_size.toString(),createdAt: user.created_at.toISOString(),updatedAt: user.updated_at?.toISOString() ?? null,version: user.version.toString(),diff --git a/packages/core/src/synchronizers/users.ts b/packages/core/src/synchronizers/users.tsindex 47e71adc..e0d2ec52 100644--- a/packages/core/src/synchronizers/users.ts+++ b/packages/core/src/synchronizers/users.ts@@ -13,8 +13,6 @@ export type SyncUserData = {role: WorkspaceRole;customName: string | null;customAvatar: string | null;- storageLimit: string;- maxFileSize: string;createdAt: string;updatedAt: string | null;version: string;diff --git a/packages/core/src/types/sockets.ts b/packages/core/src/types/sockets.tsindex 78442854..e0c2774b 100644--- a/packages/core/src/types/sockets.ts+++ b/packages/core/src/types/sockets.ts@@ -40,10 +40,17 @@ export type UserCreatedMessage = {userId: string;};+export type UserUpdatedMessage = {+ type: 'user_updated';+ accountId: string;+ userId: string;+};+export type Message =| AccountUpdatedMessage| WorkspaceUpdatedMessage| WorkspaceDeletedMessage| UserCreatedMessage+ | UserUpdatedMessage| SynchronizerInputMessage| SynchronizerOutputMessage<SynchronizerInput>;diff --git a/packages/core/src/types/workspaces.ts b/packages/core/src/types/workspaces.tsindex 7c6ff9cb..c05780db 100644--- a/packages/core/src/types/workspaces.ts+++ b/packages/core/src/types/workspaces.ts@@ -14,7 +14,7 @@ export enum WorkspaceStatus {export enum UserStatus {Active = 1,- Inactive = 2,+ Removed = 2,}export type WorkspaceCreateInput = {