Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Switch from express to fastify (#16)

Hakan Shehu412a396b2834
diff --git a/apps/desktop/src/main/databases/account/schema.ts b/apps/desktop/src/main/databases/account/schema.ts
index c935dfc5..1e6190ad 100644
--- a/apps/desktop/src/main/databases/account/schema.ts
+++ b/apps/desktop/src/main/databases/account/schema.ts
@@ -9,8 +9,8 @@ interface WorkspaceTable {
description: ColumnType<string | null, string | null, string | null>;
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>;
+ storage_limit: ColumnType<string, string, string>;
+ max_file_size: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
}
diff --git a/apps/desktop/src/main/databases/workspace/schema.ts b/apps/desktop/src/main/databases/workspace/schema.ts
index 35900214..ad11c5cf 100644
--- a/apps/desktop/src/main/databases/workspace/schema.ts
+++ b/apps/desktop/src/main/databases/workspace/schema.ts
@@ -20,7 +20,7 @@ interface UserTable {
status: ColumnType<UserStatus, UserStatus, UserStatus>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
}
export type SelectUser = Selectable<UserTable>;
@@ -33,8 +33,8 @@ interface NodeTable {
parent_id: ColumnType<string | null, never, never>;
root_id: ColumnType<string, string, never>;
attributes: ColumnType<string, string, string>;
- local_revision: ColumnType<bigint, bigint, bigint>;
- server_revision: ColumnType<bigint, bigint, bigint>;
+ local_revision: ColumnType<string, string, string>;
+ server_revision: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
created_by: ColumnType<string, string, never>;
@@ -48,7 +48,7 @@ export type UpdateNode = Updateable<NodeTable>;
interface NodeStateTable {
id: ColumnType<string, string, never>;
state: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
}
export type SelectNodeState = Selectable<NodeStateTable>;
@@ -70,7 +70,7 @@ interface NodeInteractionTable {
node_id: ColumnType<string, string, never>;
collaborator_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
first_seen_at: ColumnType<string | null, string | null, string | null>;
last_seen_at: ColumnType<string | null, string | null, string | null>;
first_opened_at: ColumnType<string | null, string | null, string | null>;
@@ -86,7 +86,7 @@ interface NodeReactionTable {
collaborator_id: ColumnType<string, string, never>;
reaction: ColumnType<string, string, string>;
root_id: ColumnType<string, string, string>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
}
@@ -132,7 +132,7 @@ export type UpdateNodeText = Updateable<NodeTextTable>;
interface CollaborationTable {
node_id: ColumnType<string, string, never>;
role: ColumnType<string, string, string>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
deleted_at: ColumnType<string | null, string | null, string | null>;
@@ -145,8 +145,8 @@ export type UpdateCollaboration = Updateable<CollaborationTable>;
interface DocumentTable {
id: ColumnType<string, string, never>;
type: ColumnType<DocumentType, never, never>;
- local_revision: ColumnType<bigint, bigint, bigint>;
- server_revision: ColumnType<bigint, bigint, bigint>;
+ local_revision: ColumnType<string, string, string>;
+ server_revision: ColumnType<string, string, string>;
content: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
created_by: ColumnType<string, string, never>;
@@ -161,7 +161,7 @@ export type UpdateDocument = Updateable<DocumentTable>;
interface DocumentStateTable {
id: ColumnType<string, string, never>;
state: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
}
export type SelectDocumentState = Selectable<DocumentStateTable>;
@@ -243,7 +243,7 @@ export type UpdateTombstone = Updateable<TombstoneTable>;
interface CursorTable {
key: ColumnType<string, string, never>;
- value: ColumnType<bigint, bigint, bigint>;
+ value: ColumnType<string, string, string>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
}
diff --git a/apps/desktop/src/main/mutations/accounts/account-update.ts b/apps/desktop/src/main/mutations/accounts/account-update.ts
index 95575132..dd1a2cdd 100644
--- a/apps/desktop/src/main/mutations/accounts/account-update.ts
+++ b/apps/desktop/src/main/mutations/accounts/account-update.ts
@@ -1,4 +1,4 @@
-import { AccountUpdateOutput } from '@colanode/core';
+import { AccountUpdateInput, AccountUpdateOutput } from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
import { eventBus } from '@/shared/lib/event-bus';
@@ -27,12 +27,14 @@ export class AccountUpdateMutationHandler
}
try {
+ const body: AccountUpdateInput = {
+ name: input.name,
+ avatar: input.avatar,
+ };
+
const { data } = await accountService.client.put<AccountUpdateOutput>(
`/v1/accounts/${input.id}`,
- {
- name: input.name,
- avatar: input.avatar,
- }
+ body
);
const updatedAccount = await appService.database
diff --git a/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts b/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
index 24e7b6fc..97ebd8b9 100644
--- a/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
@@ -61,7 +61,7 @@ export class NodeMarkOpenedMutationHandler
collaborator_id: workspace.userId,
last_opened_at: lastOpenedAt,
first_opened_at: firstOpenedAt,
- revision: 0n,
+ revision: '0',
root_id: node.rootId,
})
.onConflict((b) =>
diff --git a/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts b/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
index e2698bcf..7b9fc24f 100644
--- a/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
@@ -62,7 +62,7 @@ export class NodeMarkSeenMutationHandler
collaborator_id: workspace.userId,
last_seen_at: lastSeenAt,
first_seen_at: firstSeenAt,
- revision: 0n,
+ revision: '0',
root_id: node.rootId,
})
.onConflict((b) =>
diff --git a/apps/desktop/src/main/mutations/users/user-role-update.ts b/apps/desktop/src/main/mutations/users/user-role-update.ts
index 1b13f835..bfa36eef 100644
--- a/apps/desktop/src/main/mutations/users/user-role-update.ts
+++ b/apps/desktop/src/main/mutations/users/user-role-update.ts
@@ -1,3 +1,5 @@
+import { UserRoleUpdateInput } from '@colanode/core';
+
import { MutationHandler } from '@/main/lib/types';
import {
UserRoleUpdateMutationInput,
@@ -17,11 +19,13 @@ export class UserRoleUpdateMutationHandler
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
try {
+ const body: UserRoleUpdateInput = {
+ role: input.role,
+ };
+
await workspace.account.client.put(
`/v1/workspaces/${workspace.id}/users/${input.userId}`,
- {
- role: input.role,
- }
+ body
);
return {
diff --git a/apps/desktop/src/main/mutations/users/users-invite.ts b/apps/desktop/src/main/mutations/users/users-invite.ts
index 357c15c3..6367b63a 100644
--- a/apps/desktop/src/main/mutations/users/users-invite.ts
+++ b/apps/desktop/src/main/mutations/users/users-invite.ts
@@ -1,4 +1,4 @@
-import { UsersInviteOutput } from '@colanode/core';
+import { UsersInviteInput, UsersInviteOutput } from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
import {
@@ -19,12 +19,14 @@ export class UsersInviteMutationHandler
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
try {
+ const body: UsersInviteInput = {
+ emails: input.emails,
+ role: input.role,
+ };
+
await workspace.account.client.post<UsersInviteOutput>(
`/v1/workspaces/${workspace.id}/users`,
- {
- emails: input.emails,
- role: input.role,
- }
+ body
);
return {
diff --git a/apps/desktop/src/main/mutations/workspaces/workspace-create.ts b/apps/desktop/src/main/mutations/workspaces/workspace-create.ts
index 8add7942..b689aad5 100644
--- a/apps/desktop/src/main/mutations/workspaces/workspace-create.ts
+++ b/apps/desktop/src/main/mutations/workspaces/workspace-create.ts
@@ -1,4 +1,4 @@
-import { WorkspaceOutput } from '@colanode/core';
+import { WorkspaceCreateInput, WorkspaceOutput } from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
import { eventBus } from '@/shared/lib/event-bus';
@@ -27,13 +27,15 @@ export class WorkspaceCreateMutationHandler
}
try {
+ const body: WorkspaceCreateInput = {
+ name: input.name,
+ description: input.description,
+ avatar: input.avatar,
+ };
+
const { data } = await account.client.post<WorkspaceOutput>(
`/v1/workspaces`,
- {
- name: input.name,
- description: input.description,
- avatar: input.avatar,
- }
+ body
);
const createdWorkspace = await account.database
diff --git a/apps/desktop/src/main/mutations/workspaces/workspace-update.ts b/apps/desktop/src/main/mutations/workspaces/workspace-update.ts
index b00682bb..19450e3f 100644
--- a/apps/desktop/src/main/mutations/workspaces/workspace-update.ts
+++ b/apps/desktop/src/main/mutations/workspaces/workspace-update.ts
@@ -1,3 +1,5 @@
+import { WorkspaceUpdateInput } from '@colanode/core';
+
import { appService } from '@/main/services/app-service';
import { MutationHandler } from '@/main/lib/types';
import { mapWorkspace } from '@/main/lib/mappers';
@@ -34,13 +36,15 @@ export class WorkspaceUpdateMutationHandler
}
try {
+ const body: WorkspaceUpdateInput = {
+ name: input.name,
+ description: input.description,
+ avatar: input.avatar,
+ };
+
const { data } = await accountService.client.put<Workspace>(
`/v1/workspaces/${input.id}`,
- {
- name: input.name,
- description: input.description,
- avatar: input.avatar,
- }
+ body
);
const updatedWorkspace = await accountService.database
diff --git a/apps/desktop/src/main/services/accounts/account-service.ts b/apps/desktop/src/main/services/accounts/account-service.ts
index 63bc8bec..6881a3cb 100644
--- a/apps/desktop/src/main/services/accounts/account-service.ts
+++ b/apps/desktop/src/main/services/accounts/account-service.ts
@@ -1,4 +1,5 @@
import {
+ AccountSyncInput,
AccountSyncOutput,
ApiErrorCode,
ApiErrorOutput,
@@ -245,12 +246,14 @@ export class AccountService {
}
try {
+ const body: AccountSyncInput = {
+ platform: process.platform,
+ version: this.app.version,
+ };
+
const { data } = await this.client.post<AccountSyncOutput>(
'/v1/accounts/sync',
- {
- platform: process.platform,
- version: this.app.version,
- }
+ body
);
const hasChanges =
diff --git a/apps/desktop/src/main/services/workspaces/collaboration-service.ts b/apps/desktop/src/main/services/workspaces/collaboration-service.ts
index 0eff9f74..642c363a 100644
--- a/apps/desktop/src/main/services/workspaces/collaboration-service.ts
+++ b/apps/desktop/src/main/services/workspaces/collaboration-service.ts
@@ -49,18 +49,18 @@ export class CollaborationService {
created_at: collaboration.createdAt,
updated_at: collaboration.updatedAt,
deleted_at: collaboration.deletedAt,
- revision: BigInt(collaboration.revision),
+ revision: collaboration.revision,
})
.onConflict((oc) =>
oc
.columns(['node_id'])
.doUpdateSet({
role: collaboration.role,
- revision: BigInt(collaboration.revision),
+ revision: collaboration.revision,
updated_at: collaboration.updatedAt,
deleted_at: collaboration.deletedAt,
})
- .where('revision', '<', BigInt(collaboration.revision))
+ .where('revision', '<', collaboration.revision)
)
.executeTakeFirst();
diff --git a/apps/desktop/src/main/services/workspaces/document-service.ts b/apps/desktop/src/main/services/workspaces/document-service.ts
index 5193e4e9..e4c6d0a7 100644
--- a/apps/desktop/src/main/services/workspaces/document-service.ts
+++ b/apps/desktop/src/main/services/workspaces/document-service.ts
@@ -145,8 +145,8 @@ export class DocumentService {
.values({
id: id,
content: JSON.stringify(content),
- local_revision: 0n,
- server_revision: 0n,
+ local_revision: '0',
+ server_revision: '0',
created_at: updatedAt,
created_by: this.workspace.userId,
})
@@ -251,7 +251,7 @@ export class DocumentService {
}
const localRevision = BigInt(document.local_revision) + 1n;
- const serverRevision = BigInt(document.server_revision) + 1n;
+ const serverRevision = document.server_revision;
const updateId = generateId(IdType.Update);
const updatedAt = new Date().toISOString();
const text = extractDocumentText(document.id, afterContent);
@@ -274,7 +274,7 @@ export class DocumentService {
.returningAll()
.set({
content: JSON.stringify(afterContent),
- local_revision: localRevision,
+ local_revision: localRevision.toString(),
server_revision: serverRevision,
updated_at: updatedAt,
updated_by: this.workspace.userId,
@@ -510,7 +510,7 @@ export class DocumentService {
.returningAll()
.set({
content: JSON.stringify(content),
- local_revision: localRevision,
+ local_revision: localRevision.toString(),
})
.where('id', '=', data.documentId)
.where('local_revision', '=', node.local_revision)
@@ -637,7 +637,7 @@ export class DocumentService {
ydoc.applyUpdate(data.data);
const serverState = ydoc.getState();
- const serverRevision = BigInt(data.revision);
+ const serverRevision = data.revision;
for (const update of documentUpdates) {
if (update.id === data.id || mergedUpdateIds.includes(update.id)) {
@@ -679,7 +679,7 @@ export class DocumentService {
.set({
content: JSON.stringify(content),
server_revision: serverRevision,
- local_revision: localRevision,
+ local_revision: localRevision.toString(),
updated_at: data.createdAt,
updated_by: data.createdBy,
})
@@ -706,7 +706,7 @@ export class DocumentService {
state: serverState,
revision: serverRevision,
})
- .where('revision', '=', BigInt(documentState?.revision ?? 0))
+ .where('revision', '=', documentState?.revision ?? '0')
)
.executeTakeFirst();
@@ -805,7 +805,7 @@ export class DocumentService {
id: data.documentId,
content: JSON.stringify(content),
server_revision: serverRevision,
- local_revision: localRevision,
+ local_revision: localRevision.toString(),
created_at: data.createdAt,
created_by: data.createdBy,
})
diff --git a/apps/desktop/src/main/services/workspaces/file-service.ts b/apps/desktop/src/main/services/workspaces/file-service.ts
index 4f7a7bfd..49594dd4 100644
--- a/apps/desktop/src/main/services/workspaces/file-service.ts
+++ b/apps/desktop/src/main/services/workspaces/file-service.ts
@@ -1,6 +1,8 @@
import {
+ CompleteUploadInput,
CompleteUploadOutput,
CreateDownloadOutput,
+ CreateUploadInput,
CreateUploadOutput,
FileAttributes,
FileStatus,
@@ -109,11 +111,13 @@ export class FileService {
);
}
- if (metadata.size > this.workspace.maxFileSize) {
+ const fileSize = BigInt(metadata.size);
+ const maxFileSize = BigInt(this.workspace.maxFileSize);
+ if (fileSize > maxFileSize) {
throw new MutationError(
MutationErrorCode.FileTooLarge,
'The file you are trying to upload is too large. The maximum file size is ' +
- formatBytes(this.workspace.maxFileSize)
+ formatBytes(maxFileSize)
);
}
@@ -122,15 +126,16 @@ export class FileService {
this.workspace.userId
);
- if (storageUsed + BigInt(metadata.size) > this.workspace.storageLimit) {
+ const storageLimit = BigInt(this.workspace.storageLimit);
+ if (storageUsed + fileSize > storageLimit) {
throw new MutationError(
MutationErrorCode.StorageLimitExceeded,
'You have reached your storage limit. You have used ' +
formatBytes(storageUsed) +
' and you are trying to upload a file of size ' +
- formatBytes(metadata.size) +
+ formatBytes(fileSize) +
'. Your storage limit is ' +
- formatBytes(this.workspace.storageLimit)
+ formatBytes(storageLimit)
);
}
@@ -303,7 +308,7 @@ export class FileService {
}
const file = mapNode(node) as LocalFileNode;
- if (node.server_revision === BigInt(0)) {
+ if (node.server_revision === '0') {
// file is not synced with the server, we need to wait for the sync to complete
return;
}
@@ -340,12 +345,14 @@ export class FileService {
}
try {
+ const createUploadInput: CreateUploadInput = {
+ fileId: file.id,
+ };
+
const { data } =
await this.workspace.account.client.post<CreateUploadOutput>(
`/v1/workspaces/${this.workspace.id}/files`,
- {
- fileId: file.id,
- }
+ createUploadInput
);
const presignedUrl = data.url;
@@ -390,11 +397,13 @@ export class FileService {
},
});
+ const completeUploadInput: CompleteUploadInput = {
+ uploadId: data.uploadId,
+ };
+
await this.workspace.account.client.put<CompleteUploadOutput>(
`/v1/workspaces/${this.workspace.id}/files/${file.id}`,
- {
- uploadId: data.uploadId,
- }
+ completeUploadInput
);
const finalFileState = await this.workspace.database
@@ -502,7 +511,7 @@ export class FileService {
const file = mapNode(node) as LocalFileNode;
- if (node.server_revision === BigInt(0)) {
+ if (node.server_revision === '0') {
// file is not synced with the server, we need to wait for the sync to complete
return;
}
@@ -535,8 +544,7 @@ export class FileService {
try {
const { data } =
await this.workspace.account.client.get<CreateDownloadOutput>(
- `/v1/workspaces/${this.workspace.id}/downloads/${file.id}`,
- {}
+ `/v1/workspaces/${this.workspace.id}/downloads/${file.id}`
);
const presignedUrl = data.url;
diff --git a/apps/desktop/src/main/services/workspaces/mutation-service.ts b/apps/desktop/src/main/services/workspaces/mutation-service.ts
index 1f1343a1..841da5e3 100644
--- a/apps/desktop/src/main/services/workspaces/mutation-service.ts
+++ b/apps/desktop/src/main/services/workspaces/mutation-service.ts
@@ -1,4 +1,9 @@
-import { createDebugger, Mutation, SyncMutationsOutput } from '@colanode/core';
+import {
+ createDebugger,
+ Mutation,
+ SyncMutationsInput,
+ SyncMutationsOutput,
+} from '@colanode/core';
import ms from 'ms';
import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
@@ -88,12 +93,14 @@ export class MutationService {
`Sending batch ${currentBatch++} of ${totalBatches} mutations for user ${this.workspace.id}`
);
+ const body: SyncMutationsInput = {
+ mutations: batch,
+ };
+
const { data } =
await this.workspace.account.client.post<SyncMutationsOutput>(
`/v1/workspaces/${this.workspace.id}/mutations`,
- {
- mutations: batch,
- }
+ body
);
const syncedMutationIds: string[] = [];
diff --git a/apps/desktop/src/main/services/workspaces/node-interaction-service.ts b/apps/desktop/src/main/services/workspaces/node-interaction-service.ts
index 7686fc39..074250c5 100644
--- a/apps/desktop/src/main/services/workspaces/node-interaction-service.ts
+++ b/apps/desktop/src/main/services/workspaces/node-interaction-service.ts
@@ -23,9 +23,8 @@ export class NodeInteractionService {
.where('collaborator_id', '=', nodeInteraction.collaboratorId)
.executeTakeFirst();
- const revision = BigInt(nodeInteraction.revision);
if (existingNodeInteraction) {
- if (existingNodeInteraction.revision === revision) {
+ if (existingNodeInteraction.revision === nodeInteraction.revision) {
debug(
`Server node interaction for node ${nodeInteraction.nodeId} is already synced`
);
@@ -44,7 +43,7 @@ export class NodeInteractionService {
last_seen_at: nodeInteraction.lastSeenAt,
last_opened_at: nodeInteraction.lastOpenedAt,
first_opened_at: nodeInteraction.firstOpenedAt,
- revision,
+ revision: nodeInteraction.revision,
})
.onConflict((b) =>
b.columns(['node_id', 'collaborator_id']).doUpdateSet({
@@ -52,7 +51,7 @@ export class NodeInteractionService {
first_seen_at: nodeInteraction.firstSeenAt,
last_opened_at: nodeInteraction.lastOpenedAt,
first_opened_at: nodeInteraction.firstOpenedAt,
- revision,
+ revision: nodeInteraction.revision,
})
)
.executeTakeFirst();
diff --git a/apps/desktop/src/main/services/workspaces/node-reaction-service.ts b/apps/desktop/src/main/services/workspaces/node-reaction-service.ts
index 5381e2dc..18b1d179 100644
--- a/apps/desktop/src/main/services/workspaces/node-reaction-service.ts
+++ b/apps/desktop/src/main/services/workspaces/node-reaction-service.ts
@@ -88,7 +88,7 @@ export class NodeReactionService {
collaborator_id: this.workspace.userId,
reaction,
root_id: node.rootId,
- revision: 0n,
+ revision: '0',
created_at: new Date().toISOString(),
})
.onConflict((cb) => cb.doNothing())
@@ -267,9 +267,8 @@ export class NodeReactionService {
.where('reaction', '=', nodeReaction.reaction)
.executeTakeFirst();
- const revision = BigInt(nodeReaction.revision);
if (existingNodeReaction) {
- if (existingNodeReaction.revision === revision) {
+ if (existingNodeReaction.revision === nodeReaction.revision) {
debug(
`Server node reaction for node ${nodeReaction.nodeId} is already synced`
);
@@ -280,7 +279,7 @@ export class NodeReactionService {
.updateTable('node_reactions')
.returningAll()
.set({
- revision,
+ revision: nodeReaction.revision,
})
.where('node_id', '=', nodeReaction.nodeId)
.where('collaborator_id', '=', nodeReaction.collaboratorId)
@@ -306,11 +305,11 @@ export class NodeReactionService {
reaction: nodeReaction.reaction,
root_id: nodeReaction.rootId,
created_at: nodeReaction.createdAt,
- revision,
+ revision: nodeReaction.revision,
})
.onConflict((b) =>
b.columns(['node_id', 'collaborator_id', 'reaction']).doUpdateSet({
- revision,
+ revision: nodeReaction.revision,
})
)
.executeTakeFirst();
diff --git a/apps/desktop/src/main/services/workspaces/node-service.ts b/apps/desktop/src/main/services/workspaces/node-service.ts
index adab188c..33fe42cc 100644
--- a/apps/desktop/src/main/services/workspaces/node-service.ts
+++ b/apps/desktop/src/main/services/workspaces/node-service.ts
@@ -110,8 +110,8 @@ export class NodeService {
attributes: JSON.stringify(input.attributes),
created_at: createdAt,
created_by: this.workspace.userId,
- local_revision: BigInt(0),
- server_revision: BigInt(0),
+ local_revision: '0',
+ server_revision: '0',
})
.executeTakeFirst();
@@ -305,7 +305,7 @@ export class NodeService {
attributes: JSON.stringify(attributes),
updated_at: updatedAt,
updated_by: this.workspace.userId,
- local_revision: localRevision,
+ local_revision: localRevision.toString(),
})
.where('id', '=', nodeId)
.where('local_revision', '=', node.localRevision)
@@ -536,8 +536,6 @@ export class NodeService {
private async tryCreateServerNode(
update: SyncNodeUpdateData
): Promise<boolean> {
- const serverRevision = BigInt(update.revision);
-
const ydoc = new YDoc(update.data);
const attributes = ydoc.getObject<NodeAttributes>();
@@ -565,8 +563,8 @@ export class NodeService {
attributes: JSON.stringify(attributes),
created_at: update.createdAt,
created_by: update.createdBy,
- local_revision: 0n,
- server_revision: serverRevision,
+ local_revision: '0',
+ server_revision: update.revision,
})
.executeTakeFirst();
@@ -579,7 +577,7 @@ export class NodeService {
.returningAll()
.values({
id: update.nodeId,
- revision: serverRevision,
+ revision: update.revision,
state: decodeState(update.data),
})
.executeTakeFirst();
@@ -658,7 +656,6 @@ export class NodeService {
const ydoc = new YDoc(nodeState?.state);
ydoc.applyUpdate(update.data);
- const serverRevision = BigInt(update.revision);
const serverState = ydoc.getState();
for (const nodeUpdate of nodeUpdates) {
@@ -695,8 +692,8 @@ export class NodeService {
attributes: JSON.stringify(attributes),
updated_at: update.createdAt,
updated_by: update.createdBy,
- local_revision: localRevision,
- server_revision: serverRevision,
+ local_revision: localRevision.toString(),
+ server_revision: update.revision,
})
.where('id', '=', existingNode.id)
.where('local_revision', '=', existingNode.local_revision)
@@ -711,16 +708,16 @@ export class NodeService {
.returningAll()
.values({
id: existingNode.id,
- revision: serverRevision,
+ revision: update.revision,
state: serverState,
})
.onConflict((cb) =>
cb
.doUpdateSet({
- revision: serverRevision,
+ revision: update.revision,
state: serverState,
})
- .where('revision', '=', BigInt(nodeState?.revision ?? 0))
+ .where('revision', '=', nodeState?.revision ?? '0')
)
.executeTakeFirst();
@@ -1041,7 +1038,7 @@ export class NodeService {
.returningAll()
.set({
attributes: JSON.stringify(attributes),
- local_revision: localRevision,
+ local_revision: localRevision.toString(),
})
.where('id', '=', mutation.nodeId)
.where('local_revision', '=', node.local_revision)
diff --git a/apps/desktop/src/main/services/workspaces/synchronizer.ts b/apps/desktop/src/main/services/workspaces/synchronizer.ts
index ec12f693..271c29c7 100644
--- a/apps/desktop/src/main/services/workspaces/synchronizer.ts
+++ b/apps/desktop/src/main/services/workspaces/synchronizer.ts
@@ -32,7 +32,7 @@ export class Synchronizer<TInput extends SynchronizerInput> {
) => Promise<void>;
private status: SynchronizerStatus = 'idle';
- private cursor: bigint = 0n;
+ private cursor: string = '0';
private initialized: boolean = false;
constructor(
@@ -105,12 +105,12 @@ export class Synchronizer<TInput extends SynchronizerInput> {
}
this.status = 'processing';
- let lastCursor: bigint | null = null;
+ let lastCursor: string | null = null;
try {
for (const item of message.items) {
await this.processor(item.data);
- lastCursor = BigInt(item.cursor);
+ lastCursor = item.cursor;
}
} catch (error) {
debug(`Error consuming items: ${error}`);
@@ -157,10 +157,10 @@ export class Synchronizer<TInput extends SynchronizerInput> {
.where('key', '=', this.cursorKey)
.executeTakeFirst();
- return cursor?.value ?? 0n;
+ return cursor?.value ?? '0';
}
- private async saveCursor(cursor: bigint) {
+ private async saveCursor(cursor: string) {
await this.workspace.database
.insertInto('cursors')
.values({
diff --git a/apps/desktop/src/main/services/workspaces/user-service.ts b/apps/desktop/src/main/services/workspaces/user-service.ts
index 8f77f6d9..a9e1ce35 100644
--- a/apps/desktop/src/main/services/workspaces/user-service.ts
+++ b/apps/desktop/src/main/services/workspaces/user-service.ts
@@ -25,7 +25,7 @@ export class UserService {
name: user.name,
avatar: user.avatar,
role: user.role,
- revision: BigInt(user.revision),
+ revision: user.revision,
created_at: user.createdAt,
updated_at: user.updatedAt,
status: user.status,
@@ -42,10 +42,10 @@ export class UserService {
custom_avatar: user.customAvatar,
role: user.role,
status: user.status,
- revision: BigInt(user.revision),
+ revision: user.revision,
updated_at: user.updatedAt,
})
- .where('revision', '<', BigInt(user.revision))
+ .where('revision', '<', user.revision)
)
.executeTakeFirst();
diff --git a/apps/desktop/src/main/services/workspaces/workspace-service.ts b/apps/desktop/src/main/services/workspaces/workspace-service.ts
index f1e7e993..ae6e683e 100644
--- a/apps/desktop/src/main/services/workspaces/workspace-service.ts
+++ b/apps/desktop/src/main/services/workspaces/workspace-service.ts
@@ -98,11 +98,11 @@ export class WorkspaceService {
return this.workspace.role;
}
- public get maxFileSize(): bigint {
+ public get maxFileSize(): string {
return this.workspace.maxFileSize;
}
- public get storageLimit(): bigint {
+ public get storageLimit(): string {
return this.workspace.storageLimit;
}
diff --git a/apps/desktop/src/renderer/contexts/record.ts b/apps/desktop/src/renderer/contexts/record.ts
index 078c06a6..5a9a63d9 100644
--- a/apps/desktop/src/renderer/contexts/record.ts
+++ b/apps/desktop/src/renderer/contexts/record.ts
@@ -28,7 +28,7 @@ interface RecordContext {
updatedAt?: string | null;
databaseId: string;
canEdit: boolean;
- localRevision: bigint;
+ localRevision: string;
updateFieldValue: (field: FieldAttributes, value: FieldValue) => void;
removeFieldValue: (field: FieldAttributes) => void;
getBooleanValue: (field: BooleanFieldAttributes) => boolean;
diff --git a/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts b/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
index 8407d43b..026babe5 100644
--- a/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
+++ b/apps/desktop/src/shared/mutations/workspaces/workspace-user-role-update.ts
@@ -1,9 +1,11 @@
+import { WorkspaceRole } from '@colanode/core';
+
export type UserRoleUpdateMutationInput = {
type: 'user_role_update';
accountId: string;
workspaceId: string;
userId: string;
- role: string;
+ role: WorkspaceRole;
};
export type UserRoleUpdateMutationOutput = {
diff --git a/apps/desktop/src/shared/types/documents.ts b/apps/desktop/src/shared/types/documents.ts
index 1453ec9d..557e1c33 100644
--- a/apps/desktop/src/shared/types/documents.ts
+++ b/apps/desktop/src/shared/types/documents.ts
@@ -2,8 +2,8 @@ import { DocumentContent } from '@colanode/core';
export type Document = {
id: string;
- localRevision: bigint;
- serverRevision: bigint;
+ localRevision: string;
+ serverRevision: string;
content: DocumentContent;
createdAt: string;
createdBy: string;
@@ -13,7 +13,7 @@ export type Document = {
export type DocumentState = {
id: string;
- revision: bigint;
+ revision: string;
state: Uint8Array;
};
diff --git a/apps/desktop/src/shared/types/nodes.ts b/apps/desktop/src/shared/types/nodes.ts
index 153a30d0..5a83af8c 100644
--- a/apps/desktop/src/shared/types/nodes.ts
+++ b/apps/desktop/src/shared/types/nodes.ts
@@ -22,7 +22,7 @@ export type NodeInteraction = {
nodeId: string;
collaboratorId: string;
rootId: string;
- revision: bigint;
+ revision: string;
lastSeenAt: string | null;
firstSeenAt: string | null;
lastOpenedAt: string | null;
@@ -62,8 +62,8 @@ export type NodeCounter = {
};
export type LocalNodeBase = {
- localRevision: bigint;
- serverRevision: bigint;
+ localRevision: string;
+ serverRevision: string;
};
export type LocalChannelNode = ChannelNode & LocalNodeBase;
diff --git a/apps/desktop/src/shared/types/workspaces.ts b/apps/desktop/src/shared/types/workspaces.ts
index 73f805ba..f5e1aaf8 100644
--- a/apps/desktop/src/shared/types/workspaces.ts
+++ b/apps/desktop/src/shared/types/workspaces.ts
@@ -8,8 +8,8 @@ export type Workspace = {
accountId: string;
role: WorkspaceRole;
userId: string;
- maxFileSize: bigint;
- storageLimit: bigint;
+ maxFileSize: string;
+ storageLimit: string;
};
export type ContainerTab = {
diff --git a/apps/server/package.json b/apps/server/package.json
index d8160fe1..97735152 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -19,9 +19,6 @@
},
"description": "",
"devDependencies": {
- "@types/cors": "^2.8.17",
- "@types/express": "^5.0.1",
- "@types/multer": "^1.4.12",
"@types/node": "^22.14.1",
"@types/nodemailer": "^6.4.17",
"@types/pg": "^8.11.13",
@@ -35,6 +32,8 @@
"@aws-sdk/s3-request-presigner": "^3.787.0",
"@colanode/core": "*",
"@colanode/crdt": "*",
+ "@fastify/multipart": "^9.0.3",
+ "@fastify/websocket": "^11.0.2",
"@langchain/core": "^0.3.46",
"@langchain/google-genai": "^0.2.4",
"@langchain/langgraph": "^0.2.65",
@@ -42,20 +41,18 @@
"@node-rs/argon2": "^2.0.2",
"axios": "^1.8.4",
"bullmq": "^5.49.2",
- "cors": "^2.8.5",
"diff": "^7.0.0",
"dotenv": "^16.5.0",
- "express": "^5.1.0",
+ "fastify": "^5.3.2",
+ "fastify-type-provider-zod": "^4.0.2",
"handlebars": "^4.7.8",
"js-sha256": "^0.11.0",
"kysely": "^0.28.1",
"langchain": "^0.3.23",
"langfuse-langchain": "^3.37.2",
- "multer": "^1.4.5-lts.2",
"nodemailer": "^6.10.1",
"pg": "^8.15.1",
"redis": "^4.7.0",
- "sharp": "^0.34.1",
- "ws": "^8.18.1"
+ "sharp": "^0.34.1"
}
}
diff --git a/apps/server/src/api/client/controllers/accounts/account-sync.ts b/apps/server/src/api/client/controllers/accounts/account-sync.ts
deleted file mode 100644
index 3941b9b4..00000000
--- a/apps/server/src/api/client/controllers/accounts/account-sync.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { Request, Response } from 'express';
-import {
- AccountSyncOutput,
- WorkspaceOutput,
- WorkspaceRole,
- ApiErrorCode,
- AccountSyncInput,
- UserStatus,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-
-export const accountSyncHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const account = await database
- .selectFrom('accounts')
- .where('id', '=', res.locals.account.id)
- .selectAll()
- .executeTakeFirst();
-
- if (!account) {
- return ResponseBuilder.notFound(res, {
- code: ApiErrorCode.AccountNotFound,
- message: 'Account not found. Check your token.',
- });
- }
-
- const device = await database
- .selectFrom('devices')
- .selectAll()
- .where('id', '=', res.locals.account.deviceId)
- .executeTakeFirst();
-
- if (!device) {
- return ResponseBuilder.notFound(res, {
- code: ApiErrorCode.DeviceNotFound,
- message: 'Device not found. Check your token.',
- });
- }
-
- const input: AccountSyncInput = req.body;
-
- await database
- .updateTable('devices')
- .set({
- synced_at: new Date(),
- ip: res.locals.ip,
- platform: input.platform,
- version: input.version,
- })
- .where('id', '=', device.id)
- .execute();
-
- const workspaceOutputs: WorkspaceOutput[] = [];
- const users = await database
- .selectFrom('users')
- .where('account_id', '=', account.id)
- .where('status', '=', UserStatus.Active)
- .where('role', '!=', 'none')
- .selectAll()
- .execute();
-
- if (users.length > 0) {
- const workspaceIds = users.map((u) => u.workspace_id);
- const workspaces = await database
- .selectFrom('workspaces')
- .where('id', 'in', workspaceIds)
- .selectAll()
- .execute();
-
- for (const user of users) {
- const workspace = workspaces.find((w) => w.id === user.workspace_id);
-
- if (!workspace) {
- continue;
- }
-
- workspaceOutputs.push({
- id: workspace.id,
- name: workspace.name,
- avatar: workspace.avatar,
- description: workspace.description,
- user: {
- id: user.id,
- accountId: user.account_id,
- role: user.role as WorkspaceRole,
- storageLimit: user.storage_limit,
- maxFileSize: user.max_file_size,
- },
- });
- }
- }
-
- const output: AccountSyncOutput = {
- account: {
- id: account.id,
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- },
- workspaces: workspaceOutputs,
- };
-
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/accounts/account-update.ts b/apps/server/src/api/client/controllers/accounts/account-update.ts
deleted file mode 100644
index fa2b11bf..00000000
--- a/apps/server/src/api/client/controllers/accounts/account-update.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { Request, Response } from 'express';
-import {
- AccountUpdateInput,
- AccountUpdateOutput,
- ApiErrorCode,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { eventBus } from '@/lib/event-bus';
-import { ResponseBuilder } from '@/lib/response-builder';
-
-export const accountUpdateHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const accountId = req.params.accountId;
- const input: AccountUpdateInput = req.body;
-
- if (accountId !== res.locals.account.id) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountMismatch,
- message:
- 'The provided account id does not match the account id in the token. Make sure you are using the correct account token.',
- });
- }
-
- const account = await database
- .selectFrom('accounts')
- .where('id', '=', res.locals.account.id)
- .selectAll()
- .executeTakeFirst();
-
- if (!account) {
- return ResponseBuilder.notFound(res, {
- code: ApiErrorCode.AccountNotFound,
- message: 'Account not found or has been deleted.',
- });
- }
-
- const nameChanged = account.name !== input.name;
- const avatarChanged = account.avatar !== input.avatar;
-
- if (!nameChanged && !avatarChanged) {
- const output: AccountUpdateOutput = {
- id: account.id,
- name: input.name,
- avatar: input.avatar,
- };
-
- return ResponseBuilder.success(res, output);
- }
-
- const { updatedAccount, updatedUsers } = await database
- .transaction()
- .execute(async (tx) => {
- const updatedAccount = await tx
- .updateTable('accounts')
- .returningAll()
- .set({
- name: input.name,
- avatar: input.avatar,
- updated_at: new Date(),
- })
- .where('id', '=', account.id)
- .executeTakeFirst();
-
- if (!updatedAccount) {
- throw new Error('Account not found or has been deleted.');
- }
-
- const updatedUsers = await tx
- .updateTable('users')
- .returningAll()
- .set({
- name: input.name,
- avatar: input.avatar,
- updated_at: new Date(),
- updated_by: account.id,
- })
- .where('account_id', '=', account.id)
- .execute();
-
- return { updatedAccount, updatedUsers };
- });
-
- if (!updatedAccount) {
- return ResponseBuilder.notFound(res, {
- code: ApiErrorCode.AccountNotFound,
- message: 'Account not found or has been deleted.',
- });
- }
-
- eventBus.publish({
- type: 'account_updated',
- accountId: account.id,
- });
-
- if (updatedUsers.length > 0) {
- for (const user of updatedUsers) {
- eventBus.publish({
- type: 'user_updated',
- userId: user.id,
- accountId: account.id,
- workspaceId: user.workspace_id,
- });
- }
- }
-
- const output: AccountUpdateOutput = {
- id: account.id,
- name: input.name,
- avatar: input.avatar,
- };
-
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/accounts/email-login.ts b/apps/server/src/api/client/controllers/accounts/email-login.ts
deleted file mode 100644
index 5bbc1c8d..00000000
--- a/apps/server/src/api/client/controllers/accounts/email-login.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { Request, Response } from 'express';
-import { AccountStatus, EmailLoginInput, ApiErrorCode } from '@colanode/core';
-import argon2 from '@node-rs/argon2';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { rateLimitService } from '@/services/rate-limit-service';
-import { configuration } from '@/lib/configuration';
-import {
- buildLoginSuccessOutput,
- buildLoginVerifyOutput,
-} from '@/lib/accounts';
-
-export const emailLoginHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const ip = res.locals.ip;
- const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
- if (isIpRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many authentication attempts. Please try again later.',
- });
- }
-
- const input: EmailLoginInput = req.body;
- const email = input.email.toLowerCase();
-
- const isEmailRateLimited =
- await rateLimitService.isAuthEmailRateLimitted(email);
- if (isEmailRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many authentication attempts. Please try again later.',
- });
- }
-
- const account = await database
- .selectFrom('accounts')
- .where('email', '=', email)
- .selectAll()
- .executeTakeFirst();
-
- if (!account || !account.password) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.EmailOrPasswordIncorrect,
- message: 'Invalid email or password.',
- });
- }
-
- if (account.status === AccountStatus.Unverified) {
- if (configuration.account.verificationType === 'email') {
- const output = await buildLoginVerifyOutput(account);
- return ResponseBuilder.success(res, output);
- }
-
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountPendingVerification,
- message:
- 'Account is not verified yet. Contact your administrator to verify your account.',
- });
- }
-
- const passwordMatch = await argon2.verify(account.password, input.password);
-
- if (!passwordMatch) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.EmailOrPasswordIncorrect,
- message: 'Invalid email or password.',
- });
- }
-
- const output = await buildLoginSuccessOutput(account, {
- ip: res.locals.ip,
- platform: input.platform,
- version: input.version,
- });
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/accounts/email-password-reset-complete.ts b/apps/server/src/api/client/controllers/accounts/email-password-reset-complete.ts
deleted file mode 100644
index 8275b67f..00000000
--- a/apps/server/src/api/client/controllers/accounts/email-password-reset-complete.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import {
- AccountStatus,
- ApiErrorCode,
- EmailPasswordResetCompleteInput,
- EmailPasswordResetCompleteOutput,
-} from '@colanode/core';
-import { Request, Response } from 'express';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { generatePasswordHash, verifyOtpCode } from '@/lib/accounts';
-import { rateLimitService } from '@/services/rate-limit-service';
-
-export const emailPasswordResetCompleteHandler = async (
- req: Request,
- res: Response
-) => {
- const ip = res.locals.ip;
- const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
- if (isIpRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many authentication attempts. Please try again later.',
- });
- }
-
- const input: EmailPasswordResetCompleteInput = req.body;
- const accountId = await verifyOtpCode(input.id, input.otp);
-
- if (!accountId) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountOtpInvalid,
- message: 'Invalid or expired code. Please request a new code.',
- });
- }
-
- const account = await database
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', accountId)
- .executeTakeFirst();
-
- if (!account) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountOtpInvalid,
- message: 'Invalid or expired code. Please request a new code.',
- });
- }
-
- const password = await generatePasswordHash(input.password);
- const updatedAccount = await database
- .updateTable('accounts')
- .returningAll()
- .set({
- password,
- status: AccountStatus.Active,
- updated_at: new Date(),
- })
- .where('id', '=', accountId)
- .executeTakeFirst();
-
- if (!updatedAccount) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountOtpInvalid,
- message: 'Invalid or expired code. Please request a new code.',
- });
- }
-
- // automatically logout all devices
- await database
- .deleteFrom('devices')
- .where('account_id', '=', accountId)
- .execute();
-
- const output: EmailPasswordResetCompleteOutput = {
- success: true,
- };
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/accounts/email-password-reset-init.ts b/apps/server/src/api/client/controllers/accounts/email-password-reset-init.ts
deleted file mode 100644
index 12629768..00000000
--- a/apps/server/src/api/client/controllers/accounts/email-password-reset-init.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { Request, Response } from 'express';
-import {
- generateId,
- IdType,
- ApiErrorCode,
- EmailPasswordResetInitInput,
- EmailPasswordResetInitOutput,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { rateLimitService } from '@/services/rate-limit-service';
-import { configuration } from '@/lib/configuration';
-import { generateOtpCode, saveOtp } from '@/lib/otps';
-import { AccountPasswordResetOtpAttributes, Otp } from '@/types/otps';
-import { jobService } from '@/services/job-service';
-
-export const emailPasswordResetInitHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const ip = res.locals.ip;
- const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
- if (isIpRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many authentication attempts. Please try again later.',
- });
- }
-
- const input: EmailPasswordResetInitInput = req.body;
- const email = input.email.toLowerCase();
-
- const isEmailRateLimited =
- await rateLimitService.isAuthEmailRateLimitted(email);
- if (isEmailRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many authentication attempts. Please try again later.',
- });
- }
-
- const id = generateId(IdType.OtpCode);
- const expiresAt = new Date(
- Date.now() + configuration.account.otpTimeout * 1000
- );
- const otpCode = await generateOtpCode();
-
- const account = await database
- .selectFrom('accounts')
- .selectAll()
- .where('email', '=', email)
- .executeTakeFirst();
-
- if (!account) {
- const output: EmailPasswordResetInitOutput = {
- id,
- expiresAt,
- };
- return ResponseBuilder.success(res, output);
- }
-
- const otp: Otp<AccountPasswordResetOtpAttributes> = {
- id,
- expiresAt,
- otp: otpCode,
- attributes: {
- accountId: account.id,
- attempts: 0,
- },
- };
-
- await saveOtp(id, otp);
- await jobService.addJob({
- type: 'send_email_password_reset_email',
- otpId: id,
- });
-
- const output: EmailPasswordResetInitOutput = {
- id,
- expiresAt,
- };
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/accounts/email-register.ts b/apps/server/src/api/client/controllers/accounts/email-register.ts
deleted file mode 100644
index c437bdd4..00000000
--- a/apps/server/src/api/client/controllers/accounts/email-register.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { Request, Response } from 'express';
-import {
- AccountStatus,
- EmailRegisterInput,
- generateId,
- IdType,
- ApiErrorCode,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { SelectAccount } from '@/data/schema';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { rateLimitService } from '@/services/rate-limit-service';
-import { configuration } from '@/lib/configuration';
-import {
- buildLoginSuccessOutput,
- buildLoginVerifyOutput,
- generatePasswordHash,
-} from '@/lib/accounts';
-
-export const emailRegisterHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const ip = res.locals.ip;
- const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
- if (isIpRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many authentication attempts. Please try again later.',
- });
- }
-
- const input: EmailRegisterInput = req.body;
- const email = input.email.toLowerCase();
-
- const isEmailRateLimited =
- await rateLimitService.isAuthEmailRateLimitted(email);
- if (isEmailRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many authentication attempts. Please try again later.',
- });
- }
-
- const existingAccount = await database
- .selectFrom('accounts')
- .selectAll()
- .where('email', '=', email)
- .executeTakeFirst();
-
- const password = await generatePasswordHash(input.password);
-
- let account: SelectAccount | null | undefined = null;
-
- const status =
- configuration.account.verificationType === 'automatic'
- ? AccountStatus.Active
- : AccountStatus.Unverified;
-
- if (existingAccount) {
- if (existingAccount.status !== AccountStatus.Pending) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.EmailAlreadyExists,
- message: 'Email already exists. Login or use another email.',
- });
- }
-
- account = await database
- .updateTable('accounts')
- .set({
- password: password,
- name: input.name,
- updated_at: new Date(),
- status: status,
- })
- .where('id', '=', existingAccount.id)
- .returningAll()
- .executeTakeFirst();
- } else {
- account = await database
- .insertInto('accounts')
- .values({
- id: generateId(IdType.Account),
- name: input.name,
- email: email,
- password: password,
- status: status,
- created_at: new Date(),
- })
- .returningAll()
- .executeTakeFirst();
- }
-
- if (!account) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountCreationFailed,
- message: 'Failed to create account.',
- });
- }
-
- if (account.status === AccountStatus.Unverified) {
- if (configuration.account.verificationType === 'email') {
- const output = await buildLoginVerifyOutput(account);
- return ResponseBuilder.success(res, output);
- }
-
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountPendingVerification,
- message:
- 'Account is not verified yet. Contact your administrator to verify your account.',
- });
- }
-
- const output = await buildLoginSuccessOutput(account, {
- ip: res.locals.ip,
- platform: input.platform,
- version: input.version,
- });
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/accounts/email-verify.ts b/apps/server/src/api/client/controllers/accounts/email-verify.ts
deleted file mode 100644
index 5b711ff8..00000000
--- a/apps/server/src/api/client/controllers/accounts/email-verify.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { AccountStatus, ApiErrorCode, EmailVerifyInput } from '@colanode/core';
-import { Request, Response } from 'express';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { buildLoginSuccessOutput, verifyOtpCode } from '@/lib/accounts';
-
-export const emailVerifyHandler = async (req: Request, res: Response) => {
- const input: EmailVerifyInput = req.body;
- const accountId = await verifyOtpCode(input.id, input.otp);
-
- if (!accountId) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountOtpInvalid,
- message: 'Invalid or expired OTP code. Please request a new OTP code.',
- });
- }
-
- const account = await database
- .updateTable('accounts')
- .returningAll()
- .set({
- status: AccountStatus.Active,
- })
- .where('id', '=', accountId)
- .executeTakeFirst();
-
- if (!account) {
- return ResponseBuilder.notFound(res, {
- code: ApiErrorCode.AccountNotFound,
- message: 'Account not found.',
- });
- }
-
- const output = await buildLoginSuccessOutput(account, {
- ip: res.locals.ip,
- platform: input.platform,
- version: input.version,
- });
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/accounts/index.ts b/apps/server/src/api/client/controllers/accounts/index.ts
deleted file mode 100644
index 1694cd73..00000000
--- a/apps/server/src/api/client/controllers/accounts/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export * from './account-sync';
-export * from './email-login';
-export * from './login-google';
-export * from './logout';
-export * from './email-register';
-export * from './account-update';
-export * from './email-verify';
-export * from './email-password-reset-init';
-export * from './email-password-reset-complete';
diff --git a/apps/server/src/api/client/controllers/accounts/login-google.ts b/apps/server/src/api/client/controllers/accounts/login-google.ts
deleted file mode 100644
index eaab8718..00000000
--- a/apps/server/src/api/client/controllers/accounts/login-google.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { Request, Response } from 'express';
-import {
- AccountStatus,
- generateId,
- GoogleLoginInput,
- GoogleUserInfo,
- IdType,
- ApiErrorCode,
-} from '@colanode/core';
-import axios from 'axios';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { rateLimitService } from '@/services/rate-limit-service';
-import { configuration } from '@/lib/configuration';
-import { buildLoginSuccessOutput } from '@/lib/accounts';
-
-const GoogleUserInfoUrl = 'https://www.googleapis.com/oauth2/v1/userinfo';
-
-export const loginWithGoogleHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- if (!configuration.account.allowGoogleLogin) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.GoogleAuthFailed,
- message: 'Google login is not allowed.',
- });
- }
-
- const ip = res.locals.ip;
- const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
- if (isIpRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many authentication attempts. Please try again later.',
- });
- }
-
- const input: GoogleLoginInput = req.body;
- const url = `${GoogleUserInfoUrl}?access_token=${input.access_token}`;
- const userInfoResponse = await axios.get(url);
-
- if (userInfoResponse.status !== 200) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.GoogleAuthFailed,
- message: 'Failed to authenticate with Google.',
- });
- }
-
- const googleUser: GoogleUserInfo = userInfoResponse.data;
-
- if (!googleUser) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.GoogleAuthFailed,
- message: 'Failed to authenticate with Google.',
- });
- }
-
- const existingAccount = await database
- .selectFrom('accounts')
- .where('email', '=', googleUser.email)
- .selectAll()
- .executeTakeFirst();
-
- if (existingAccount) {
- if (existingAccount.status !== AccountStatus.Active) {
- await database
- .updateTable('accounts')
- .set({
- attrs: JSON.stringify({ googleId: googleUser.id }),
- updated_at: new Date(),
- status: AccountStatus.Active,
- })
- .where('id', '=', existingAccount.id)
- .execute();
- }
-
- const output = await buildLoginSuccessOutput(existingAccount, {
- ip: res.locals.ip,
- platform: input.platform,
- version: input.version,
- });
- return ResponseBuilder.success(res, output);
- }
-
- const newAccount = await database
- .insertInto('accounts')
- .values({
- id: generateId(IdType.Account),
- name: googleUser.name,
- email: googleUser.email,
- status: AccountStatus.Active,
- created_at: new Date(),
- password: null,
- attrs: JSON.stringify({ googleId: googleUser.id }),
- })
- .returningAll()
- .executeTakeFirst();
-
- if (!newAccount) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountCreationFailed,
- message: 'Failed to create account.',
- });
- }
-
- const output = await buildLoginSuccessOutput(newAccount, {
- ip: res.locals.ip,
- platform: input.platform,
- version: input.version,
- });
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/accounts/logout.ts b/apps/server/src/api/client/controllers/accounts/logout.ts
deleted file mode 100644
index 58d9f574..00000000
--- a/apps/server/src/api/client/controllers/accounts/logout.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { Request, Response } from 'express';
-
-import { database } from '@/data/database';
-import { eventBus } from '@/lib/event-bus';
-import { ResponseBuilder } from '@/lib/response-builder';
-
-export const logoutHandler = async (
- _: Request,
- res: Response
-): Promise<void> => {
- const account = res.locals.account;
-
- await database
- .deleteFrom('devices')
- .where('id', '=', account.deviceId)
- .execute();
-
- eventBus.publish({
- type: 'device_deleted',
- accountId: account.id,
- deviceId: account.deviceId,
- });
-
- return ResponseBuilder.success(res, {});
-};
diff --git a/apps/server/src/api/client/controllers/avatars/avatar-download.ts b/apps/server/src/api/client/controllers/avatars/avatar-download.ts
deleted file mode 100644
index 404e2ffc..00000000
--- a/apps/server/src/api/client/controllers/avatars/avatar-download.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { Request, Response } from 'express';
-import { GetObjectCommand } from '@aws-sdk/client-s3';
-import { ApiErrorCode } from '@colanode/core';
-
-import { Readable } from 'stream';
-
-import { avatarS3 } from '@/data/storage';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { configuration } from '@/lib/configuration';
-
-export const avatarDownloadHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- try {
- const avatarId = req.params.avatarId;
- const command = new GetObjectCommand({
- Bucket: configuration.avatarS3.bucketName,
- Key: `avatars/${avatarId}.jpeg`,
- });
-
- const avatarResponse = await avatarS3.send(command);
- if (!avatarResponse.Body) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AvatarNotFound,
- message: 'Avatar not found',
- });
- }
-
- if (avatarResponse.Body instanceof Readable) {
- avatarResponse.Body.pipe(res);
- } else {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AvatarNotFound,
- message: 'Avatar not found',
- });
- }
- } catch {
- return ResponseBuilder.internalError(res, {
- code: ApiErrorCode.AvatarDownloadFailed,
- message: 'Failed to download avatar',
- });
- }
-};
diff --git a/apps/server/src/api/client/controllers/avatars/avatar-upload.ts b/apps/server/src/api/client/controllers/avatars/avatar-upload.ts
deleted file mode 100644
index c0e84e1a..00000000
--- a/apps/server/src/api/client/controllers/avatars/avatar-upload.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { Request, Response } from 'express';
-import sharp from 'sharp';
-import { PutObjectCommand } from '@aws-sdk/client-s3';
-import { ApiErrorCode, generateId, IdType } from '@colanode/core';
-import multer from 'multer';
-
-import path from 'path';
-
-import { avatarS3 } from '@/data/storage';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { configuration } from '@/lib/configuration';
-
-const storage = multer.memoryStorage();
-const uploadMulter = multer({
- storage,
- limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
- fileFilter: (req, file, cb) => {
- const filetypes = /jpeg|jpg|png|webp/;
- const extname = filetypes.test(
- path.extname(file.originalname).toLowerCase()
- );
- const mimetype = filetypes.test(file.mimetype);
-
- if (mimetype && extname) {
- return cb(null, true);
- } else {
- cb(new Error('Only images are allowed'));
- }
- },
-});
-
-export const avatarUploadParameter = uploadMulter.single('avatar');
-
-export const avatarUploadHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- try {
- if (!req.file) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AvatarFileNotUploaded,
- message: 'Avatar file not uploaded as part of request',
- });
- }
-
- // Resize image to a maximum of 500x500 pixels while keeping aspect ratio, and convert to JPEG using Sharp
- const jpegBuffer = await sharp(req.file.buffer)
- .resize({
- width: 500,
- height: 500,
- fit: 'inside',
- })
- .jpeg()
- .toBuffer();
-
- const avatarId = generateId(IdType.Avatar);
- const command = new PutObjectCommand({
- Bucket: configuration.avatarS3.bucketName,
- Key: `avatars/${avatarId}.jpeg`,
- Body: jpegBuffer,
- ContentType: 'image/jpeg',
- });
-
- await avatarS3.send(command);
- return ResponseBuilder.success(res, { success: true, id: avatarId });
- } catch {
- return ResponseBuilder.internalError(res, {
- code: ApiErrorCode.AvatarUploadFailed,
- message: 'Failed to upload avatar',
- });
- }
-};
diff --git a/apps/server/src/api/client/controllers/avatars/index.ts b/apps/server/src/api/client/controllers/avatars/index.ts
deleted file mode 100644
index b421092e..00000000
--- a/apps/server/src/api/client/controllers/avatars/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from './avatar-upload';
-export * from './avatar-download';
diff --git a/apps/server/src/api/client/controllers/config/index.ts b/apps/server/src/api/client/controllers/config/index.ts
deleted file mode 100644
index 13cff3e6..00000000
--- a/apps/server/src/api/client/controllers/config/index.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { ServerConfig } from '@colanode/core';
-import { Request, Response } from 'express';
-
-import { configuration } from '@/lib/configuration';
-
-export const configGetHandler = async (
- _: Request,
- res: Response
-): Promise<void> => {
- const config: ServerConfig = {
- name: configuration.server.name,
- avatar: configuration.server.avatar,
- version: '0.1.0',
- ip: res.locals.ip,
- attributes: {},
- };
-
- res.status(200).json(config);
-};
diff --git a/apps/server/src/api/client/controllers/index.ts b/apps/server/src/api/client/controllers/index.ts
deleted file mode 100644
index 718f1fea..00000000
--- a/apps/server/src/api/client/controllers/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export * from './accounts';
-export * from './avatars';
-export * from './config';
-export * from './workspaces';
diff --git a/apps/server/src/api/client/controllers/workspaces/files/file-download-get.ts b/apps/server/src/api/client/controllers/workspaces/files/file-download-get.ts
deleted file mode 100644
index 3fda2b8a..00000000
--- a/apps/server/src/api/client/controllers/workspaces/files/file-download-get.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { Request, Response } from 'express';
-import {
- CreateDownloadOutput,
- hasNodeRole,
- ApiErrorCode,
- extractNodeRole,
- FileStatus,
-} from '@colanode/core';
-
-import { fetchNodeTree, mapNode } from '@/lib/nodes';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { database } from '@/data/database';
-import { buildDownloadUrl } from '@/lib/files';
-
-export const fileDownloadGetHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const fileId = req.params.fileId as string;
-
- const tree = await fetchNodeTree(fileId);
- if (tree.length === 0) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileNotFound,
- message: 'File not found.',
- });
- }
-
- const nodes = tree.map((node) => mapNode(node));
- const file = nodes[nodes.length - 1]!;
- if (!file || file.id !== fileId) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileNotFound,
- message: 'File not found.',
- });
- }
-
- if (file.type !== 'file') {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileNotFound,
- message: 'This node is not a file.',
- });
- }
-
- if (file.attributes.status !== FileStatus.Ready) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileNotReady,
- message: 'File is not ready to be downloaded.',
- });
- }
-
- const role = extractNodeRole(nodes, res.locals.user.id);
- if (role === null || !hasNodeRole(role, 'viewer')) {
- return ResponseBuilder.forbidden(res, {
- code: ApiErrorCode.FileNoAccess,
- message: 'You do not have access to this file.',
- });
- }
-
- const upload = await database
- .selectFrom('uploads')
- .selectAll()
- .where('file_id', '=', fileId)
- .executeTakeFirst();
-
- if (!upload || !upload.uploaded_at) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileUploadNotFound,
- message: 'File upload not found.',
- });
- }
-
- const presignedUrl = await buildDownloadUrl(upload.path);
- const output: CreateDownloadOutput = {
- url: presignedUrl,
- };
-
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/workspaces/files/file-upload-complete.ts b/apps/server/src/api/client/controllers/workspaces/files/file-upload-complete.ts
deleted file mode 100644
index 7bea7c6a..00000000
--- a/apps/server/src/api/client/controllers/workspaces/files/file-upload-complete.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-import { Request, Response } from 'express';
-import { FileStatus, ApiErrorCode } from '@colanode/core';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { mapNode, updateNode } from '@/lib/nodes';
-import { fetchFileMetadata } from '@/lib/files';
-
-export const fileUploadCompleteHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const workspaceId = req.params.workspaceId as string;
- const fileId = req.params.fileId as string;
- const uploadId = req.body.uploadId as string;
-
- const node = await database
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', fileId)
- .executeTakeFirst();
-
- if (!node) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileNotFound,
- message: 'File not found.',
- });
- }
-
- if (node.created_by !== res.locals.user.id) {
- return ResponseBuilder.forbidden(res, {
- code: ApiErrorCode.FileOwnerMismatch,
- message: 'You cannot complete this file upload.',
- });
- }
-
- if (node.workspace_id !== workspaceId) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.WorkspaceMismatch,
- message: 'File does not belong to this workspace.',
- });
- }
-
- const file = mapNode(node);
- if (file.type !== 'file') {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileNotFound,
- message: 'This node is not a file.',
- });
- }
-
- if (file.attributes.status === FileStatus.Ready) {
- return ResponseBuilder.success(res, {
- success: true,
- });
- }
-
- if (file.attributes.status === FileStatus.Error) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileError,
- message: 'File has failed to upload.',
- });
- }
-
- const upload = await database
- .selectFrom('uploads')
- .selectAll()
- .where('file_id', '=', fileId)
- .executeTakeFirst();
-
- if (!upload) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileUploadNotFound,
- message: 'Upload not found.',
- });
- }
-
- if (upload.file_id !== fileId || upload.upload_id !== uploadId) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileUploadNotFound,
- message: 'Upload not found.',
- });
- }
-
- const path = upload.path;
- const metadata = await fetchFileMetadata(path);
- if (metadata === null) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileNotFound,
- message: 'File not found.',
- });
- }
-
- if (metadata.size !== file.attributes.size) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileSizeMismatch,
- message: 'Uploaded file size does not match expected size',
- });
- }
-
- if (metadata.mimeType !== file.attributes.mimeType) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileMimeTypeMismatch,
- message: 'Uploaded file type does not match expected type',
- });
- }
-
- const result = await updateNode({
- nodeId: fileId,
- userId: res.locals.user.id,
- workspaceId: workspaceId,
- updater(attributes) {
- if (attributes.type !== 'file') {
- throw new Error('Node is not a file');
- }
-
- attributes.status = FileStatus.Ready;
- return attributes;
- },
- });
-
- if (result === null) {
- return ResponseBuilder.internalError(res, {
- code: ApiErrorCode.FileUploadCompleteFailed,
- message: 'Failed to complete file upload.',
- });
- }
-
- await database
- .updateTable('uploads')
- .set({
- uploaded_at: new Date(),
- })
- .where('file_id', '=', fileId)
- .execute();
-
- return ResponseBuilder.success(res, {
- success: true,
- });
-};
diff --git a/apps/server/src/api/client/controllers/workspaces/files/file-upload-init.ts b/apps/server/src/api/client/controllers/workspaces/files/file-upload-init.ts
deleted file mode 100644
index 0f6daefa..00000000
--- a/apps/server/src/api/client/controllers/workspaces/files/file-upload-init.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { Request, Response } from 'express';
-import {
- CreateUploadInput,
- CreateUploadOutput,
- ApiErrorCode,
- generateId,
- IdType,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { mapNode } from '@/lib/nodes';
-import { buildFilePath, buildUploadUrl } from '@/lib/files';
-import { SelectUser } from '@/data/schema';
-
-export const fileUploadInitHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const input = req.body as CreateUploadInput;
- const user = res.locals.user as SelectUser;
-
- const node = await database
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', input.fileId)
- .executeTakeFirst();
-
- if (!node) {
- return ResponseBuilder.notFound(res, {
- code: ApiErrorCode.FileNotFound,
- message: 'File not found.',
- });
- }
-
- if (node.created_by !== user.id) {
- return ResponseBuilder.forbidden(res, {
- code: ApiErrorCode.FileOwnerMismatch,
- message: 'You do not have access to this file.',
- });
- }
-
- //generate presigned url for upload
- const file = mapNode(node);
- if (file.type !== 'file') {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileNotFound,
- message: 'This node is not a file.',
- });
- }
-
- const upload = await database
- .selectFrom('uploads')
- .selectAll()
- .where('file_id', '=', input.fileId)
- .executeTakeFirst();
-
- if (upload && upload.uploaded_at) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileAlreadyUploaded,
- message: 'This file is already uploaded.',
- });
- }
-
- const storageUsedRow = await database
- .selectFrom('uploads')
- .select(({ fn }) => [fn.sum('size').as('storage_used')])
- .where('created_by', '=', res.locals.user.id)
- .executeTakeFirst();
-
- const storageUsed = BigInt(storageUsedRow?.storage_used ?? 0);
- const storageLimit = user.storage_limit;
-
- if (storageUsed >= storageLimit) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileUploadInitFailed,
- message: 'You have reached the maximum storage limit.',
- });
- }
-
- const path = buildFilePath(node.workspace_id, input.fileId, file.attributes);
- const uploadId = generateId(IdType.Upload);
- const upsertedUpload = await database
- .insertInto('uploads')
- .values({
- file_id: input.fileId,
- upload_id: uploadId,
- workspace_id: node.workspace_id,
- root_id: node.id,
- mime_type: file.attributes.mimeType,
- size: file.attributes.size,
- path: path,
- version_id: file.attributes.version,
- created_at: new Date(),
- created_by: res.locals.user.id,
- })
- .onConflict((b) =>
- b.columns(['file_id']).doUpdateSet({
- upload_id: uploadId,
- mime_type: file.attributes.mimeType,
- size: file.attributes.size,
- path: path,
- version_id: file.attributes.version,
- created_at: new Date(),
- created_by: res.locals.user.id,
- })
- )
- .executeTakeFirst();
-
- if (!upsertedUpload) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.FileUploadInitFailed,
- message: 'Failed to initialize file upload.',
- });
- }
-
- const presignedUrl = await buildUploadUrl(
- path,
- file.attributes.size,
- file.attributes.mimeType
- );
-
- const output: CreateUploadOutput = {
- url: presignedUrl,
- uploadId: uploadId,
- };
-
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/workspaces/files/index.ts b/apps/server/src/api/client/controllers/workspaces/files/index.ts
deleted file mode 100644
index 027f194e..00000000
--- a/apps/server/src/api/client/controllers/workspaces/files/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from './file-download-get';
-export * from './file-upload-complete';
-export * from './file-upload-init';
diff --git a/apps/server/src/api/client/controllers/workspaces/index.ts b/apps/server/src/api/client/controllers/workspaces/index.ts
deleted file mode 100644
index 3d95cb42..00000000
--- a/apps/server/src/api/client/controllers/workspaces/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export * from './workspace-create';
-export * from './workspace-update';
-export * from './workspace-delete';
-export * from './workspace-get';
-export * from './users';
-export * from './files';
-export * from './mutations';
diff --git a/apps/server/src/api/client/controllers/workspaces/mutations/index.ts b/apps/server/src/api/client/controllers/workspaces/mutations/index.ts
deleted file mode 100644
index 3481ac42..00000000
--- a/apps/server/src/api/client/controllers/workspaces/mutations/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './mutations-sync';
diff --git a/apps/server/src/api/client/controllers/workspaces/users/index.ts b/apps/server/src/api/client/controllers/workspaces/users/index.ts
deleted file mode 100644
index 5aea772c..00000000
--- a/apps/server/src/api/client/controllers/workspaces/users/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from './user-create';
-export * from './user-role-update';
diff --git a/apps/server/src/api/client/controllers/workspaces/users/user-create.ts b/apps/server/src/api/client/controllers/workspaces/users/user-create.ts
deleted file mode 100644
index c0d726b4..00000000
--- a/apps/server/src/api/client/controllers/workspaces/users/user-create.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import { Request, Response } from 'express';
-import {
- AccountStatus,
- ApiErrorCode,
- generateId,
- IdType,
- UserInviteResult,
- UsersInviteInput,
- UserStatus,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { getNameFromEmail } from '@/lib/utils';
-import { SelectAccount, SelectUser } from '@/data/schema';
-import { eventBus } from '@/lib/event-bus';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { configuration } from '@/lib/configuration';
-
-export const userCreateHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const workspaceId = req.params.workspaceId as string;
- const input: UsersInviteInput = req.body;
- const user: SelectUser = res.locals.user;
-
- if (!input.emails || input.emails.length === 0) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.UserEmailRequired,
- message: 'User email is required.',
- });
- }
-
- if (user.role !== 'owner' && user.role !== 'admin') {
- return ResponseBuilder.forbidden(res, {
- code: ApiErrorCode.UserInviteNoAccess,
- message: 'You do not have access to invite users to this workspace.',
- });
- }
-
- const results: UserInviteResult[] = [];
- for (const email of input.emails) {
- const account = await getOrCreateAccount(email);
- if (!account) {
- results.push({
- email: email,
- result: 'error',
- });
- continue;
- }
-
- const existingUser = await database
- .selectFrom('users')
- .selectAll()
- .where('account_id', '=', account.id)
- .where('workspace_id', '=', workspaceId)
- .executeTakeFirst();
-
- if (existingUser) {
- results.push({
- email: email,
- result: 'exists',
- });
- continue;
- }
-
- const userId = generateId(IdType.User);
- const newUser = await database
- .insertInto('users')
- .returningAll()
- .values({
- id: userId,
- account_id: account.id,
- workspace_id: workspaceId,
- role: input.role,
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- storage_limit: configuration.user.storageLimit,
- max_file_size: configuration.user.maxFileSize,
- created_at: new Date(),
- created_by: res.locals.account.id,
- status: UserStatus.Active,
- })
- .executeTakeFirst();
-
- if (!newUser) {
- results.push({
- email: email,
- result: 'error',
- });
- }
-
- eventBus.publish({
- type: 'user_created',
- accountId: account.id,
- userId: userId,
- workspaceId: workspaceId,
- });
-
- results.push({
- email: email,
- result: 'success',
- });
- }
-
- return ResponseBuilder.success(res, {
- results: results,
- });
-};
-
-const getOrCreateAccount = async (
- email: string
-): Promise<SelectAccount | undefined> => {
- const account = await database
- .selectFrom('accounts')
- .selectAll()
- .where('email', '=', email)
- .executeTakeFirst();
-
- if (account) {
- return account;
- }
-
- const createdAccount = await database
- .insertInto('accounts')
- .returningAll()
- .values({
- id: generateId(IdType.Account),
- name: getNameFromEmail(email),
- email: email,
- avatar: null,
- attrs: null,
- password: null,
- status: AccountStatus.Pending,
- created_at: new Date(),
- updated_at: null,
- })
- .executeTakeFirst();
-
- return createdAccount;
-};
diff --git a/apps/server/src/api/client/controllers/workspaces/users/user-role-update.ts b/apps/server/src/api/client/controllers/workspaces/users/user-role-update.ts
deleted file mode 100644
index c7ae9e7d..00000000
--- a/apps/server/src/api/client/controllers/workspaces/users/user-role-update.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { Request, Response } from 'express';
-import { UserRoleUpdateInput, ApiErrorCode, UserStatus } from '@colanode/core';
-
-import { database } from '@/data/database';
-import { SelectUser } from '@/data/schema';
-import { eventBus } from '@/lib/event-bus';
-import { ResponseBuilder } from '@/lib/response-builder';
-
-export const userRoleUpdateHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const userId = req.params.userId as string;
- const input: UserRoleUpdateInput = req.body;
- const user: SelectUser = res.locals.user;
-
- if (user.role !== 'owner' && user.role !== 'admin') {
- return ResponseBuilder.forbidden(res, {
- code: ApiErrorCode.UserUpdateNoAccess,
- message: 'You do not have access to update users to this workspace.',
- });
- }
-
- const userToUpdate = await database
- .selectFrom('users')
- .selectAll()
- .where('id', '=', userId)
- .executeTakeFirst();
-
- if (!userToUpdate) {
- return ResponseBuilder.notFound(res, {
- code: ApiErrorCode.UserNotFound,
- message: 'User not found.',
- });
- }
-
- 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,
- })
- .where('id', '=', userToUpdate.id)
- .execute();
-
- eventBus.publish({
- type: 'user_updated',
- userId: userToUpdate.id,
- accountId: userToUpdate.account_id,
- workspaceId: userToUpdate.workspace_id,
- });
-
- return ResponseBuilder.success(res, {
- success: true,
- });
-};
diff --git a/apps/server/src/api/client/controllers/workspaces/workspace-create.ts b/apps/server/src/api/client/controllers/workspaces/workspace-create.ts
deleted file mode 100644
index 281f2d64..00000000
--- a/apps/server/src/api/client/controllers/workspaces/workspace-create.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { WorkspaceCreateInput, ApiErrorCode } from '@colanode/core';
-import { Request, Response } from 'express';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { createWorkspace } from '@/lib/workspaces';
-
-export const workspaceCreateHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const input: WorkspaceCreateInput = req.body;
-
- if (!input.name) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.WorkspaceNameRequired,
- message: 'Workspace name is required.',
- });
- }
-
- const account = await database
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!account) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.AccountNotFound,
- message: 'Account not found.',
- });
- }
-
- const output = await createWorkspace(account, input);
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/workspaces/workspace-delete.ts b/apps/server/src/api/client/controllers/workspaces/workspace-delete.ts
deleted file mode 100644
index 5c87f6a3..00000000
--- a/apps/server/src/api/client/controllers/workspaces/workspace-delete.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Request, Response } from 'express';
-import { ApiErrorCode } from '@colanode/core';
-
-import { database } from '@/data/database';
-import { eventBus } from '@/lib/event-bus';
-import { ResponseBuilder } from '@/lib/response-builder';
-
-export const workspaceDeleteHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const workspaceId = req.params.workspaceId as string;
-
- if (res.locals.user.role !== 'owner') {
- return ResponseBuilder.forbidden(res, {
- code: ApiErrorCode.WorkspaceDeleteNotAllowed,
- message:
- 'You are not allowed to delete this workspace. Only owners can delete workspaces.',
- });
- }
-
- await database
- .deleteFrom('workspaces')
- .where('id', '=', workspaceId)
- .execute();
-
- eventBus.publish({
- type: 'workspace_deleted',
- workspaceId: workspaceId,
- });
-
- return ResponseBuilder.success(res, {
- id: res.locals.workspace.id,
- });
-};
diff --git a/apps/server/src/api/client/controllers/workspaces/workspace-get.ts b/apps/server/src/api/client/controllers/workspaces/workspace-get.ts
deleted file mode 100644
index 2b23bc69..00000000
--- a/apps/server/src/api/client/controllers/workspaces/workspace-get.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import {
- WorkspaceRole,
- WorkspaceOutput,
- ApiErrorCode,
- UserStatus,
-} from '@colanode/core';
-import { Request, Response } from 'express';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-
-export const workspaceGetHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const workspaceId = req.params.workspaceId as string;
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', workspaceId)
- .executeTakeFirst();
-
- if (!workspace) {
- return ResponseBuilder.badRequest(res, {
- code: ApiErrorCode.WorkspaceNotFound,
- message: 'Workspace not found.',
- });
- }
-
- const user = await database
- .selectFrom('users')
- .selectAll()
- .where('workspace_id', '=', workspaceId)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- 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.',
- });
- }
-
- const output: WorkspaceOutput = {
- id: workspace.id,
- name: workspace.name,
- description: workspace.description,
- avatar: workspace.avatar,
- user: {
- id: user.id,
- accountId: user.account_id,
- role: user.role as WorkspaceRole,
- storageLimit: user.storage_limit,
- maxFileSize: user.max_file_size,
- },
- };
-
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/controllers/workspaces/workspace-update.ts b/apps/server/src/api/client/controllers/workspaces/workspace-update.ts
deleted file mode 100644
index 459718dd..00000000
--- a/apps/server/src/api/client/controllers/workspaces/workspace-update.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { Request, Response } from 'express';
-import {
- WorkspaceOutput,
- WorkspaceUpdateInput,
- ApiErrorCode,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { eventBus } from '@/lib/event-bus';
-import { ResponseBuilder } from '@/lib/response-builder';
-
-export const workspaceUpdateHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const workspaceId = req.params.workspaceId as string;
- const input: WorkspaceUpdateInput = req.body;
-
- if (res.locals.user.role !== 'owner') {
- return ResponseBuilder.forbidden(res, {
- code: ApiErrorCode.WorkspaceUpdateNotAllowed,
- message:
- 'You are not allowed to update this workspace. Only owners can update workspaces.',
- });
- }
-
- const updatedWorkspace = await database
- .updateTable('workspaces')
- .set({
- name: input.name,
- description: input.description,
- avatar: input.avatar,
- updated_at: new Date(),
- updated_by: res.locals.account.id,
- })
- .where('id', '=', workspaceId)
- .returningAll()
- .executeTakeFirst();
-
- if (!updatedWorkspace) {
- return ResponseBuilder.internalError(res, {
- code: ApiErrorCode.WorkspaceUpdateFailed,
- message: 'Failed to update workspace.',
- });
- }
-
- eventBus.publish({
- type: 'workspace_updated',
- workspaceId: updatedWorkspace.id,
- });
-
- const output: WorkspaceOutput = {
- id: updatedWorkspace.id,
- name: updatedWorkspace.name,
- description: updatedWorkspace.description,
- avatar: updatedWorkspace.avatar,
- user: {
- id: res.locals.user.id,
- accountId: res.locals.user.account_id,
- role: res.locals.user.role,
- storageLimit: res.locals.user.storage_limit,
- maxFileSize: res.locals.user.max_file_size,
- },
- };
-
- return ResponseBuilder.success(res, output);
-};
diff --git a/apps/server/src/api/client/middlewares/auth.ts b/apps/server/src/api/client/middlewares/auth.ts
deleted file mode 100644
index 0ada6b37..00000000
--- a/apps/server/src/api/client/middlewares/auth.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { NextFunction, Request, Response, RequestHandler } from 'express';
-import { ApiErrorCode } from '@colanode/core';
-
-import { parseToken, verifyToken } from '@/lib/tokens';
-import { ResponseBuilder } from '@/lib/response-builder';
-import { rateLimitService } from '@/services/rate-limit-service';
-
-export const authMiddleware: RequestHandler = async (
- req: Request,
- res: Response,
- next: NextFunction
-) => {
- const token = req.headers.authorization?.split(' ')[1];
-
- if (!token) {
- return ResponseBuilder.unauthorized(res, {
- code: ApiErrorCode.TokenMissing,
- message: 'No token provided',
- });
- }
-
- const tokenData = parseToken(token);
- if (!tokenData) {
- return ResponseBuilder.unauthorized(res, {
- code: ApiErrorCode.TokenInvalid,
- message: 'Token is invalid or expired',
- });
- }
-
- const isRateLimited = await rateLimitService.isDeviceApiRateLimitted(
- tokenData.deviceId
- );
-
- if (isRateLimited) {
- return ResponseBuilder.tooManyRequests(res, {
- code: ApiErrorCode.TooManyRequests,
- message: 'Too many requests from this device. Please try again later.',
- });
- }
-
- const result = await verifyToken(tokenData);
- if (!result.authenticated) {
- return ResponseBuilder.unauthorized(res, {
- code: ApiErrorCode.TokenInvalid,
- message: 'Token is invalid or expired',
- });
- }
-
- res.locals.account = result.account;
- next();
-};
diff --git a/apps/server/src/api/client/middlewares/ip.ts b/apps/server/src/api/client/middlewares/ip.ts
deleted file mode 100644
index c917d4b4..00000000
--- a/apps/server/src/api/client/middlewares/ip.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextFunction, Request, Response, RequestHandler } from 'express';
-
-export const ipMiddleware: RequestHandler = async (
- req: Request,
- res: Response,
- next: NextFunction
-) => {
- let ip = req.get('CF-Connecting-IP') || req.get('X-Forwarded-For') || req.ip;
- ip = Array.isArray(ip) ? ip[0] : ip;
- if (ip?.includes(',')) {
- ip = ip.split(',')[0];
- }
-
- res.locals.ip = ip;
- next();
-};
diff --git a/apps/server/src/api/client/middlewares/workspace.ts b/apps/server/src/api/client/middlewares/workspace.ts
deleted file mode 100644
index 63494dbf..00000000
--- a/apps/server/src/api/client/middlewares/workspace.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { NextFunction, Request, RequestHandler, Response } from 'express';
-import { ApiErrorCode, UserStatus } from '@colanode/core';
-
-import { database } from '@/data/database';
-import { ResponseBuilder } from '@/lib/response-builder';
-
-export const workspaceMiddleware: RequestHandler = async (
- req: Request,
- res: Response,
- next: NextFunction
-) => {
- const workspaceId = req.params.workspaceId as string;
-
- const user = await database
- .selectFrom('users')
- .selectAll()
- .where('workspace_id', '=', workspaceId)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- 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.',
- });
- }
-
- res.locals.user = user;
-
- next();
-};
diff --git a/apps/server/src/api/client/plugins/account-auth.ts b/apps/server/src/api/client/plugins/account-auth.ts
new file mode 100644
index 00000000..473d03dd
--- /dev/null
+++ b/apps/server/src/api/client/plugins/account-auth.ts
@@ -0,0 +1,76 @@
+import { FastifyPluginCallback } from 'fastify';
+import fp from 'fastify-plugin';
+import { ApiErrorCode } from '@colanode/core';
+
+import { parseToken, verifyToken } from '@/lib/tokens';
+import { rateLimitService } from '@/services/rate-limit-service';
+import { RequestAccount } from '@/types/api';
+
+declare module 'fastify' {
+ interface FastifyRequest {
+ account: RequestAccount;
+ }
+}
+
+const accountAuthenticatorCallback: FastifyPluginCallback = (
+ fastify,
+ _,
+ done
+) => {
+ if (!fastify.hasRequestDecorator('account')) {
+ fastify.decorateRequest('account');
+ }
+
+ fastify.addHook('onRequest', async (request, reply) => {
+ if (!request.headers.authorization) {
+ return reply.code(401).send({
+ code: ApiErrorCode.TokenMissing,
+ message: 'No token provided',
+ });
+ }
+
+ const auth = request.headers.authorization;
+ const parts = auth.split(' ');
+ const token = parts.length === 2 ? parts[1] : parts[0];
+
+ if (!token) {
+ return reply.code(401).send({
+ code: ApiErrorCode.TokenMissing,
+ message: 'No token provided',
+ });
+ }
+
+ const tokenData = parseToken(token);
+ if (!tokenData) {
+ return reply.code(401).send({
+ code: ApiErrorCode.TokenInvalid,
+ message: 'Token is invalid or expired',
+ });
+ }
+
+ const isRateLimited = await rateLimitService.isDeviceApiRateLimitted(
+ tokenData.deviceId
+ );
+
+ if (isRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many requests from this device. Please try again later.',
+ });
+ }
+
+ const result = await verifyToken(tokenData);
+ if (!result.authenticated) {
+ return reply.code(401).send({
+ code: ApiErrorCode.TokenInvalid,
+ message: 'Token is invalid or expired',
+ });
+ }
+
+ request.account = result.account;
+ });
+
+ done();
+};
+
+export const accountAuthenticator = fp(accountAuthenticatorCallback);
diff --git a/apps/server/src/api/client/plugins/error-handler.ts b/apps/server/src/api/client/plugins/error-handler.ts
new file mode 100644
index 00000000..e67c0feb
--- /dev/null
+++ b/apps/server/src/api/client/plugins/error-handler.ts
@@ -0,0 +1,34 @@
+import { ApiErrorCode, createDebugger } from '@colanode/core';
+import { FastifyPluginCallback } from 'fastify';
+import fp from 'fastify-plugin';
+import { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod';
+
+const debug = createDebugger('api:client:error-handler');
+
+export const errorHandlerCallback: FastifyPluginCallback = (
+ fastify,
+ _,
+ done
+) => {
+ fastify.setErrorHandler(async (error, _, reply) => {
+ debug(`Error processing request ${error.code} - ${error.message}`);
+
+ // TODO: return detailed validation errors
+ if (hasZodFastifySchemaValidationErrors(error)) {
+ return reply.code(400).send({
+ code: ApiErrorCode.ValidationError,
+ message:
+ 'One or more fields are invalid. Please check your request and try again.',
+ });
+ }
+
+ return reply.code(500).send({
+ code: ApiErrorCode.Unknown,
+ message: 'An unexpected error occurred. Please try again later.',
+ });
+ });
+
+ done();
+};
+
+export const errorHandler = fp(errorHandlerCallback);
diff --git a/apps/server/src/api/client/plugins/ip.ts b/apps/server/src/api/client/plugins/ip.ts
new file mode 100644
index 00000000..fa792d4b
--- /dev/null
+++ b/apps/server/src/api/client/plugins/ip.ts
@@ -0,0 +1,32 @@
+import { FastifyPluginCallback } from 'fastify';
+import fp from 'fastify-plugin';
+
+declare module 'fastify' {
+ interface FastifyRequest {
+ originalIp: string;
+ }
+}
+
+const ipDecoratorCallback: FastifyPluginCallback = (fastify, _, done) => {
+ if (!fastify.hasRequestDecorator('originalIp')) {
+ fastify.decorateRequest('originalIp');
+ }
+
+ fastify.addHook('onRequest', async (request) => {
+ const ipValue =
+ request.headers['cf-connecting-ip'] ||
+ request.headers['x-forwarded-for'] ||
+ request.ip;
+
+ let ip = Array.isArray(ipValue) ? ipValue[0] : ipValue;
+ if (ip?.includes(',')) {
+ ip = ip.split(',')[0];
+ }
+
+ request.originalIp = ip ?? request.ip;
+ });
+
+ done();
+};
+
+export const ipDecorator = fp(ipDecoratorCallback);
diff --git a/apps/server/src/api/client/plugins/workspace-auth.ts b/apps/server/src/api/client/plugins/workspace-auth.ts
new file mode 100644
index 00000000..5fd113a5
--- /dev/null
+++ b/apps/server/src/api/client/plugins/workspace-auth.ts
@@ -0,0 +1,57 @@
+import { FastifyPluginCallback } from 'fastify';
+import fp from 'fastify-plugin';
+import { ApiErrorCode, UserStatus } from '@colanode/core';
+
+import { database } from '@/data/database';
+import { SelectUser } from '@/data/schema';
+
+declare module 'fastify' {
+ interface FastifyRequest {
+ user: SelectUser;
+ }
+}
+
+interface WorkspaceParams {
+ workspaceId: string;
+}
+
+const workspaceAuthenticatorCallback: FastifyPluginCallback = (
+ fastify,
+ _,
+ done
+) => {
+ if (!fastify.hasRequestDecorator('user')) {
+ fastify.decorateRequest('user');
+ }
+
+ fastify.addHook('onRequest', async (request, reply) => {
+ const workspaceId = (request.params as WorkspaceParams).workspaceId;
+
+ if (!workspaceId) {
+ return reply.code(400).send({
+ code: ApiErrorCode.WorkspaceNoAccess,
+ message: 'Workspace ID is required',
+ });
+ }
+
+ const user = await database
+ .selectFrom('users')
+ .selectAll()
+ .where('workspace_id', '=', workspaceId)
+ .where('account_id', '=', request.account.id)
+ .executeTakeFirst();
+
+ if (!user || user.status !== UserStatus.Active || user.role === 'none') {
+ return reply.code(403).send({
+ code: ApiErrorCode.WorkspaceNoAccess,
+ message: 'You do not have access to this workspace.',
+ });
+ }
+
+ request.user = user;
+ });
+
+ done();
+};
+
+export const workspaceAuthenticator = fp(workspaceAuthenticatorCallback);
diff --git a/apps/server/src/api/client/routes.ts b/apps/server/src/api/client/routes.ts
deleted file mode 100644
index 8004a79e..00000000
--- a/apps/server/src/api/client/routes.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { Router } from 'express';
-
-import {
- accountSyncHandler,
- emailLoginHandler,
- emailRegisterHandler,
- logoutHandler,
- accountUpdateHandler,
- userCreateHandler,
- userRoleUpdateHandler,
- workspaceCreateHandler,
- workspaceDeleteHandler,
- workspaceGetHandler,
- workspaceUpdateHandler,
- avatarUploadHandler,
- avatarDownloadHandler,
- configGetHandler,
- fileDownloadGetHandler,
- fileUploadInitHandler,
- fileUploadCompleteHandler,
- avatarUploadParameter,
- mutationsSyncHandler,
- emailVerifyHandler,
- emailPasswordResetInitHandler,
- emailPasswordResetCompleteHandler,
-} from '@/api/client/controllers';
-import { workspaceMiddleware } from '@/api/client/middlewares/workspace';
-import { authMiddleware } from '@/api/client/middlewares/auth';
-
-export const clientRouter = Router();
-
-clientRouter.get('/v1/config', configGetHandler);
-
-clientRouter.post('/v1/accounts/emails/login', emailLoginHandler);
-
-clientRouter.post('/v1/accounts/emails/register', emailRegisterHandler);
-
-clientRouter.post('/v1/accounts/emails/verify', emailVerifyHandler);
-
-clientRouter.post(
- '/v1/accounts/emails/passwords/reset/init',
- emailPasswordResetInitHandler
-);
-
-clientRouter.post(
- '/v1/accounts/emails/passwords/reset/complete',
- emailPasswordResetCompleteHandler
-);
-
-clientRouter.delete('/v1/accounts/logout', authMiddleware, logoutHandler);
-
-clientRouter.put(
- '/v1/accounts/:accountId',
- authMiddleware,
- accountUpdateHandler
-);
-
-clientRouter.post('/v1/accounts/sync', authMiddleware, accountSyncHandler);
-
-clientRouter.post(
- '/v1/avatars',
- authMiddleware,
- avatarUploadParameter,
- avatarUploadHandler
-);
-
-clientRouter.get(
- '/v1/avatars/:avatarId',
- authMiddleware,
- avatarDownloadHandler
-);
-
-clientRouter.post('/v1/workspaces', authMiddleware, workspaceCreateHandler);
-
-clientRouter.put(
- '/v1/workspaces/:workspaceId',
- authMiddleware,
- workspaceMiddleware,
- workspaceUpdateHandler
-);
-
-clientRouter.delete(
- '/v1/workspaces/:workspaceId',
- authMiddleware,
- workspaceMiddleware,
- workspaceDeleteHandler
-);
-
-clientRouter.get(
- '/v1/workspaces/:workspaceId',
- authMiddleware,
- workspaceMiddleware,
- workspaceGetHandler
-);
-
-clientRouter.post(
- '/v1/workspaces/:workspaceId/users',
- authMiddleware,
- workspaceMiddleware,
- userCreateHandler
-);
-
-clientRouter.put(
- '/v1/workspaces/:workspaceId/users/:userId',
- authMiddleware,
- workspaceMiddleware,
- userRoleUpdateHandler
-);
-
-clientRouter.get(
- '/v1/workspaces/:workspaceId/downloads/:fileId',
- authMiddleware,
- workspaceMiddleware,
- fileDownloadGetHandler
-);
-
-clientRouter.post(
- '/v1/workspaces/:workspaceId/files',
- authMiddleware,
- workspaceMiddleware,
- fileUploadInitHandler
-);
-
-clientRouter.put(
- '/v1/workspaces/:workspaceId/files/:fileId',
- authMiddleware,
- workspaceMiddleware,
- fileUploadCompleteHandler
-);
-
-clientRouter.post(
- '/v1/workspaces/:workspaceId/mutations',
- authMiddleware,
- workspaceMiddleware,
- mutationsSyncHandler
-);
diff --git a/apps/server/src/api/client/routes/accounts/account-sync.ts b/apps/server/src/api/client/routes/accounts/account-sync.ts
new file mode 100644
index 00000000..ca545ab0
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/account-sync.ts
@@ -0,0 +1,126 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ AccountSyncOutput,
+ WorkspaceOutput,
+ WorkspaceRole,
+ ApiErrorCode,
+ AccountSyncInput,
+ UserStatus,
+ accountSyncOutputSchema,
+ apiErrorOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+
+export const accountSyncRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/sync',
+ schema: {
+ response: {
+ 200: accountSyncOutputSchema,
+ 400: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ 401: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const account = await database
+ .selectFrom('accounts')
+ .where('id', '=', request.account.id)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!account) {
+ return reply.code(404).send({
+ code: ApiErrorCode.AccountNotFound,
+ message: 'Account not found. Check your token.',
+ });
+ }
+
+ const device = await database
+ .selectFrom('devices')
+ .selectAll()
+ .where('id', '=', request.account.deviceId)
+ .executeTakeFirst();
+
+ if (!device) {
+ return reply.code(404).send({
+ code: ApiErrorCode.DeviceNotFound,
+ message: 'Device not found. Check your token.',
+ });
+ }
+
+ const input = request.body as AccountSyncInput;
+
+ await database
+ .updateTable('devices')
+ .set({
+ synced_at: new Date(),
+ ip: request.originalIp,
+ platform: input.platform,
+ version: input.version,
+ })
+ .where('id', '=', device.id)
+ .execute();
+
+ const workspaceOutputs: WorkspaceOutput[] = [];
+ const users = await database
+ .selectFrom('users')
+ .where('account_id', '=', account.id)
+ .where('status', '=', UserStatus.Active)
+ .where('role', '!=', 'none')
+ .selectAll()
+ .execute();
+
+ if (users.length > 0) {
+ const workspaceIds = users.map((u) => u.workspace_id);
+ const workspaces = await database
+ .selectFrom('workspaces')
+ .where('id', 'in', workspaceIds)
+ .selectAll()
+ .execute();
+
+ for (const user of users) {
+ const workspace = workspaces.find((w) => w.id === user.workspace_id);
+
+ if (!workspace) {
+ continue;
+ }
+
+ workspaceOutputs.push({
+ id: workspace.id,
+ name: workspace.name,
+ avatar: workspace.avatar,
+ description: workspace.description,
+ user: {
+ id: user.id,
+ accountId: user.account_id,
+ role: user.role as WorkspaceRole,
+ storageLimit: user.storage_limit,
+ maxFileSize: user.max_file_size,
+ },
+ });
+ }
+ }
+
+ const output: AccountSyncOutput = {
+ account: {
+ id: account.id,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
+ },
+ workspaces: workspaceOutputs,
+ };
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/account-update.ts b/apps/server/src/api/client/routes/accounts/account-update.ts
new file mode 100644
index 00000000..fdcb8c7c
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/account-update.ts
@@ -0,0 +1,140 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import {
+ AccountUpdateInput,
+ accountUpdateInputSchema,
+ AccountUpdateOutput,
+ accountUpdateOutputSchema,
+ ApiErrorCode,
+ apiErrorOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { eventBus } from '@/lib/event-bus';
+
+export const accountUpdateRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'PUT',
+ url: '/:accountId',
+ schema: {
+ params: z.object({
+ accountId: z.string(),
+ }),
+ body: accountUpdateInputSchema,
+ response: {
+ 200: accountUpdateOutputSchema,
+ 400: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ 401: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const accountId = request.params.accountId;
+ const input = request.body as AccountUpdateInput;
+
+ if (accountId !== request.account.id) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountMismatch,
+ message:
+ 'The provided account id does not match the account id in the token. Make sure you are using the correct account token.',
+ });
+ }
+
+ const account = await database
+ .selectFrom('accounts')
+ .where('id', '=', request.account.id)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!account) {
+ return reply.code(404).send({
+ code: ApiErrorCode.AccountNotFound,
+ message: 'Account not found or has been deleted.',
+ });
+ }
+
+ const nameChanged = account.name !== input.name;
+ const avatarChanged = account.avatar !== input.avatar;
+
+ if (!nameChanged && !avatarChanged) {
+ const output: AccountUpdateOutput = {
+ id: account.id,
+ name: input.name,
+ avatar: input.avatar,
+ };
+
+ return output;
+ }
+
+ const { updatedAccount, updatedUsers } = await database
+ .transaction()
+ .execute(async (tx) => {
+ const updatedAccount = await tx
+ .updateTable('accounts')
+ .returningAll()
+ .set({
+ name: input.name,
+ avatar: input.avatar,
+ updated_at: new Date(),
+ })
+ .where('id', '=', account.id)
+ .executeTakeFirst();
+
+ if (!updatedAccount) {
+ throw new Error('Account not found or has been deleted.');
+ }
+
+ const updatedUsers = await tx
+ .updateTable('users')
+ .returningAll()
+ .set({
+ name: input.name,
+ avatar: input.avatar,
+ updated_at: new Date(),
+ updated_by: account.id,
+ })
+ .where('account_id', '=', account.id)
+ .execute();
+
+ return { updatedAccount, updatedUsers };
+ });
+
+ if (!updatedAccount) {
+ return reply.code(404).send({
+ code: ApiErrorCode.AccountNotFound,
+ message: 'Account not found or has been deleted.',
+ });
+ }
+
+ eventBus.publish({
+ type: 'account_updated',
+ accountId: account.id,
+ });
+
+ if (updatedUsers.length > 0) {
+ for (const user of updatedUsers) {
+ eventBus.publish({
+ type: 'user_updated',
+ userId: user.id,
+ accountId: account.id,
+ workspaceId: user.workspace_id,
+ });
+ }
+ }
+
+ const output: AccountUpdateOutput = {
+ id: account.id,
+ name: input.name,
+ avatar: input.avatar,
+ };
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/email-login.ts b/apps/server/src/api/client/routes/accounts/email-login.ts
new file mode 100644
index 00000000..ec67cd93
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/email-login.ts
@@ -0,0 +1,107 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ AccountStatus,
+ emailLoginInputSchema,
+ ApiErrorCode,
+ apiErrorOutputSchema,
+ loginOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { rateLimitService } from '@/services/rate-limit-service';
+import { configuration } from '@/lib/configuration';
+import {
+ buildLoginSuccessOutput,
+ buildLoginVerifyOutput,
+ verifyPassword,
+} from '@/lib/accounts';
+
+export const emailLoginRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/emails/login',
+ schema: {
+ body: emailLoginInputSchema,
+ response: {
+ 200: loginOutputSchema,
+ 400: apiErrorOutputSchema,
+ 429: apiErrorOutputSchema,
+ 401: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const ip = request.originalIp;
+ const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
+ if (isIpRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
+ const input = request.body;
+ const email = input.email.toLowerCase();
+
+ const isEmailRateLimited =
+ await rateLimitService.isAuthEmailRateLimitted(email);
+ if (isEmailRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
+ const account = await database
+ .selectFrom('accounts')
+ .where('email', '=', email)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!account || !account.password) {
+ return reply.code(400).send({
+ code: ApiErrorCode.EmailOrPasswordIncorrect,
+ message: 'Invalid email or password.',
+ });
+ }
+
+ if (account.status === AccountStatus.Unverified) {
+ if (configuration.account.verificationType === 'email') {
+ const output = await buildLoginVerifyOutput(account);
+ return output;
+ }
+
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountPendingVerification,
+ message:
+ 'Account is not verified yet. Contact your administrator to verify your account.',
+ });
+ }
+
+ const passwordMatch = await verifyPassword(
+ input.password,
+ account.password
+ );
+
+ if (!passwordMatch) {
+ return reply.code(400).send({
+ code: ApiErrorCode.EmailOrPasswordIncorrect,
+ message: 'Invalid email or password.',
+ });
+ }
+
+ const output = await buildLoginSuccessOutput(account, {
+ ip: request.ip,
+ platform: input.platform,
+ version: input.version,
+ });
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/email-password-reset-complete.ts b/apps/server/src/api/client/routes/accounts/email-password-reset-complete.ts
new file mode 100644
index 00000000..37449746
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/email-password-reset-complete.ts
@@ -0,0 +1,98 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ AccountStatus,
+ ApiErrorCode,
+ apiErrorOutputSchema,
+ EmailPasswordResetCompleteInput,
+ EmailPasswordResetCompleteOutput,
+ emailPasswordResetCompleteOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { generatePasswordHash, verifyOtpCode } from '@/lib/accounts';
+import { rateLimitService } from '@/services/rate-limit-service';
+
+export const emailPasswordResetCompleteRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/emails/passwords/reset/complete',
+ schema: {
+ response: {
+ 200: emailPasswordResetCompleteOutputSchema,
+ 400: apiErrorOutputSchema,
+ 401: apiErrorOutputSchema,
+ 429: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const ip = request.originalIp;
+ const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
+ if (isIpRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
+ const input = request.body as EmailPasswordResetCompleteInput;
+ const accountId = await verifyOtpCode(input.id, input.otp);
+
+ if (!accountId) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountOtpInvalid,
+ message: 'Invalid or expired code. Please request a new code.',
+ });
+ }
+
+ const account = await database
+ .selectFrom('accounts')
+ .selectAll()
+ .where('id', '=', accountId)
+ .executeTakeFirst();
+
+ if (!account) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountOtpInvalid,
+ message: 'Invalid or expired code. Please request a new code.',
+ });
+ }
+
+ const password = await generatePasswordHash(input.password);
+ const updatedAccount = await database
+ .updateTable('accounts')
+ .returningAll()
+ .set({
+ password,
+ status: AccountStatus.Active,
+ updated_at: new Date(),
+ })
+ .where('id', '=', accountId)
+ .executeTakeFirst();
+
+ if (!updatedAccount) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountOtpInvalid,
+ message: 'Invalid or expired code. Please request a new code.',
+ });
+ }
+
+ // automatically logout all devices
+ await database
+ .deleteFrom('devices')
+ .where('account_id', '=', accountId)
+ .execute();
+
+ const output: EmailPasswordResetCompleteOutput = {
+ success: true,
+ };
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/email-password-reset-init.ts b/apps/server/src/api/client/routes/accounts/email-password-reset-init.ts
new file mode 100644
index 00000000..ee24d7b3
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/email-password-reset-init.ts
@@ -0,0 +1,102 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ generateId,
+ IdType,
+ ApiErrorCode,
+ EmailPasswordResetInitInput,
+ EmailPasswordResetInitOutput,
+ apiErrorOutputSchema,
+ emailPasswordResetInitOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { rateLimitService } from '@/services/rate-limit-service';
+import { configuration } from '@/lib/configuration';
+import { generateOtpCode, saveOtp } from '@/lib/otps';
+import { AccountPasswordResetOtpAttributes, Otp } from '@/types/otps';
+import { jobService } from '@/services/job-service';
+
+export const emailPasswordResetInitRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/emails/passwords/reset/init',
+ schema: {
+ response: {
+ 200: emailPasswordResetInitOutputSchema,
+ 400: apiErrorOutputSchema,
+ 429: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const ip = request.originalIp;
+ const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
+ if (isIpRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
+ const input = request.body as EmailPasswordResetInitInput;
+ const email = input.email.toLowerCase();
+
+ const isEmailRateLimited =
+ await rateLimitService.isAuthEmailRateLimitted(email);
+ if (isEmailRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
+ const id = generateId(IdType.OtpCode);
+ const expiresAt = new Date(
+ Date.now() + configuration.account.otpTimeout * 1000
+ );
+ const otpCode = await generateOtpCode();
+
+ const account = await database
+ .selectFrom('accounts')
+ .selectAll()
+ .where('email', '=', email)
+ .executeTakeFirst();
+
+ if (!account) {
+ const output: EmailPasswordResetInitOutput = {
+ id,
+ expiresAt,
+ };
+ return output;
+ }
+
+ const otp: Otp<AccountPasswordResetOtpAttributes> = {
+ id,
+ expiresAt,
+ otp: otpCode,
+ attributes: {
+ accountId: account.id,
+ attempts: 0,
+ },
+ };
+
+ await saveOtp(id, otp);
+ await jobService.addJob({
+ type: 'send_email_password_reset_email',
+ otpId: id,
+ });
+
+ const output: EmailPasswordResetInitOutput = {
+ id,
+ expiresAt,
+ };
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/email-register.ts b/apps/server/src/api/client/routes/accounts/email-register.ts
new file mode 100644
index 00000000..d7a1045c
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/email-register.ts
@@ -0,0 +1,139 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ AccountStatus,
+ EmailRegisterInput,
+ generateId,
+ IdType,
+ ApiErrorCode,
+ apiErrorOutputSchema,
+ loginOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { SelectAccount } from '@/data/schema';
+import { rateLimitService } from '@/services/rate-limit-service';
+import { configuration } from '@/lib/configuration';
+import {
+ buildLoginSuccessOutput,
+ buildLoginVerifyOutput,
+ generatePasswordHash,
+} from '@/lib/accounts';
+
+export const emailRegisterRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/emails/register',
+ schema: {
+ response: {
+ 200: loginOutputSchema,
+ 400: apiErrorOutputSchema,
+ 429: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const ip = request.originalIp;
+ const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
+ if (isIpRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
+ const input = request.body as EmailRegisterInput;
+ const email = input.email.toLowerCase();
+
+ const isEmailRateLimited =
+ await rateLimitService.isAuthEmailRateLimitted(email);
+ if (isEmailRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
+ const existingAccount = await database
+ .selectFrom('accounts')
+ .selectAll()
+ .where('email', '=', email)
+ .executeTakeFirst();
+
+ const password = await generatePasswordHash(input.password);
+
+ let account: SelectAccount | null | undefined = null;
+
+ const status =
+ configuration.account.verificationType === 'automatic'
+ ? AccountStatus.Active
+ : AccountStatus.Unverified;
+
+ if (existingAccount) {
+ if (existingAccount.status !== AccountStatus.Pending) {
+ return reply.code(400).send({
+ code: ApiErrorCode.EmailAlreadyExists,
+ message: 'Email already exists. Login or use another email.',
+ });
+ }
+
+ account = await database
+ .updateTable('accounts')
+ .set({
+ password: password,
+ name: input.name,
+ updated_at: new Date(),
+ status: status,
+ })
+ .where('id', '=', existingAccount.id)
+ .returningAll()
+ .executeTakeFirst();
+ } else {
+ account = await database
+ .insertInto('accounts')
+ .values({
+ id: generateId(IdType.Account),
+ name: input.name,
+ email: email,
+ password: password,
+ status: status,
+ created_at: new Date(),
+ })
+ .returningAll()
+ .executeTakeFirst();
+ }
+
+ if (!account) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountCreationFailed,
+ message: 'Failed to create account.',
+ });
+ }
+
+ if (account.status === AccountStatus.Unverified) {
+ if (configuration.account.verificationType === 'email') {
+ const output = await buildLoginVerifyOutput(account);
+ return output;
+ }
+
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountPendingVerification,
+ message:
+ 'Account is not verified yet. Contact your administrator to verify your account.',
+ });
+ }
+
+ const output = await buildLoginSuccessOutput(account, {
+ ip: request.originalIp,
+ platform: input.platform,
+ version: input.version,
+ });
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/email-verify.ts b/apps/server/src/api/client/routes/accounts/email-verify.ts
new file mode 100644
index 00000000..2b11ad8e
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/email-verify.ts
@@ -0,0 +1,67 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ AccountStatus,
+ ApiErrorCode,
+ apiErrorOutputSchema,
+ EmailVerifyInput,
+ loginOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { buildLoginSuccessOutput, verifyOtpCode } from '@/lib/accounts';
+
+export const emailVerifyRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/emails/verify',
+ schema: {
+ response: {
+ 200: loginOutputSchema,
+ 400: apiErrorOutputSchema,
+ 429: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const input = request.body as EmailVerifyInput;
+ const accountId = await verifyOtpCode(input.id, input.otp);
+
+ if (!accountId) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountOtpInvalid,
+ message:
+ 'Invalid or expired OTP code. Please request a new OTP code.',
+ });
+ }
+
+ const account = await database
+ .updateTable('accounts')
+ .returningAll()
+ .set({
+ status: AccountStatus.Active,
+ })
+ .where('id', '=', accountId)
+ .executeTakeFirst();
+
+ if (!account) {
+ return reply.code(404).send({
+ code: ApiErrorCode.AccountNotFound,
+ message: 'Account not found.',
+ });
+ }
+
+ const output = await buildLoginSuccessOutput(account, {
+ ip: request.originalIp,
+ platform: input.platform,
+ version: input.version,
+ });
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/index.ts b/apps/server/src/api/client/routes/accounts/index.ts
new file mode 100644
index 00000000..d1b56f7f
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/index.ts
@@ -0,0 +1,32 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { accountSyncRoute } from './account-sync';
+import { emailLoginRoute } from './email-login';
+import { loginWithGoogleRoute } from './login-google';
+import { logoutRoute } from './logout';
+import { emailRegisterRoute } from './email-register';
+import { accountUpdateRoute } from './account-update';
+import { emailVerifyRoute } from './email-verify';
+import { emailPasswordResetInitRoute } from './email-password-reset-init';
+import { emailPasswordResetCompleteRoute } from './email-password-reset-complete';
+
+import { accountAuthenticator } from '@/api/client/plugins/account-auth';
+
+export const accountRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(emailLoginRoute);
+ instance.register(loginWithGoogleRoute);
+ instance.register(emailRegisterRoute);
+ instance.register(emailVerifyRoute);
+ instance.register(emailPasswordResetInitRoute);
+ instance.register(emailPasswordResetCompleteRoute);
+
+ instance.register(async (subInstance) => {
+ await subInstance.register(accountAuthenticator);
+
+ await subInstance.register(accountSyncRoute);
+ await subInstance.register(logoutRoute);
+ await subInstance.register(accountUpdateRoute);
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/login-google.ts b/apps/server/src/api/client/routes/accounts/login-google.ts
new file mode 100644
index 00000000..f6992776
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/login-google.ts
@@ -0,0 +1,132 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ AccountStatus,
+ generateId,
+ GoogleLoginInput,
+ GoogleUserInfo,
+ IdType,
+ ApiErrorCode,
+ apiErrorOutputSchema,
+ loginOutputSchema,
+} from '@colanode/core';
+import axios from 'axios';
+
+import { database } from '@/data/database';
+import { rateLimitService } from '@/services/rate-limit-service';
+import { configuration } from '@/lib/configuration';
+import { buildLoginSuccessOutput } from '@/lib/accounts';
+
+const GoogleUserInfoUrl = 'https://www.googleapis.com/oauth2/v1/userinfo';
+
+export const loginWithGoogleRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/google/login',
+ schema: {
+ response: {
+ 200: loginOutputSchema,
+ 400: apiErrorOutputSchema,
+ 429: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ if (!configuration.account.allowGoogleLogin) {
+ return reply.code(400).send({
+ code: ApiErrorCode.GoogleAuthFailed,
+ message: 'Google login is not allowed.',
+ });
+ }
+
+ const ip = request.originalIp;
+ const isIpRateLimited = await rateLimitService.isAuthIpRateLimitted(ip);
+ if (isIpRateLimited) {
+ return reply.code(429).send({
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
+ const input = request.body as GoogleLoginInput;
+ const url = `${GoogleUserInfoUrl}?access_token=${input.access_token}`;
+ const userInfoResponse = await axios.get(url);
+
+ if (userInfoResponse.status !== 200) {
+ return reply.code(400).send({
+ code: ApiErrorCode.GoogleAuthFailed,
+ message: 'Failed to authenticate with Google.',
+ });
+ }
+
+ const googleUser: GoogleUserInfo = userInfoResponse.data;
+
+ if (!googleUser) {
+ return reply.code(400).send({
+ code: ApiErrorCode.GoogleAuthFailed,
+ message: 'Failed to authenticate with Google.',
+ });
+ }
+
+ const existingAccount = await database
+ .selectFrom('accounts')
+ .where('email', '=', googleUser.email)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (existingAccount) {
+ if (existingAccount.status !== AccountStatus.Active) {
+ await database
+ .updateTable('accounts')
+ .set({
+ attrs: JSON.stringify({ googleId: googleUser.id }),
+ updated_at: new Date(),
+ status: AccountStatus.Active,
+ })
+ .where('id', '=', existingAccount.id)
+ .execute();
+ }
+
+ const output = await buildLoginSuccessOutput(existingAccount, {
+ ip: request.originalIp,
+ platform: input.platform,
+ version: input.version,
+ });
+ return output;
+ }
+
+ const newAccount = await database
+ .insertInto('accounts')
+ .values({
+ id: generateId(IdType.Account),
+ name: googleUser.name,
+ email: googleUser.email,
+ status: AccountStatus.Active,
+ created_at: new Date(),
+ password: null,
+ attrs: JSON.stringify({ googleId: googleUser.id }),
+ })
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!newAccount) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountCreationFailed,
+ message: 'Failed to create account.',
+ });
+ }
+
+ const output = await buildLoginSuccessOutput(newAccount, {
+ ip: request.originalIp,
+ platform: input.platform,
+ version: input.version,
+ });
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/accounts/logout.ts b/apps/server/src/api/client/routes/accounts/logout.ts
new file mode 100644
index 00000000..4040fc14
--- /dev/null
+++ b/apps/server/src/api/client/routes/accounts/logout.ts
@@ -0,0 +1,35 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+
+import { database } from '@/data/database';
+import { eventBus } from '@/lib/event-bus';
+
+export const logoutRoute: FastifyPluginCallbackZod = (instance, _, done) => {
+ instance.route({
+ method: 'DELETE',
+ url: '/logout',
+ schema: {
+ response: {
+ 200: z.object({}),
+ },
+ },
+ handler: async (request) => {
+ const account = request.account;
+
+ await database
+ .deleteFrom('devices')
+ .where('id', '=', account.deviceId)
+ .execute();
+
+ eventBus.publish({
+ type: 'device_deleted',
+ accountId: account.id,
+ deviceId: account.deviceId,
+ });
+
+ return {};
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/avatars/avatar-download.ts b/apps/server/src/api/client/routes/avatars/avatar-download.ts
new file mode 100644
index 00000000..e4a5ae85
--- /dev/null
+++ b/apps/server/src/api/client/routes/avatars/avatar-download.ts
@@ -0,0 +1,59 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import { GetObjectCommand } from '@aws-sdk/client-s3';
+import { ApiErrorCode } from '@colanode/core';
+
+import { Readable } from 'stream';
+
+import { avatarS3 } from '@/data/storage';
+import { configuration } from '@/lib/configuration';
+
+export const avatarDownloadRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'GET',
+ url: '/:avatarId',
+ schema: {
+ params: z.object({
+ avatarId: z.string(),
+ }),
+ },
+ handler: async (request, reply) => {
+ try {
+ const avatarId = request.params.avatarId;
+ const command = new GetObjectCommand({
+ Bucket: configuration.avatarS3.bucketName,
+ Key: `avatars/${avatarId}.jpeg`,
+ });
+
+ const avatarResponse = await avatarS3.send(command);
+ if (!avatarResponse.Body) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AvatarNotFound,
+ message: 'Avatar not found',
+ });
+ }
+
+ if (avatarResponse.Body instanceof Readable) {
+ reply.header('Content-Type', 'image/jpeg');
+ return reply.send(avatarResponse.Body);
+ }
+
+ return reply.code(400).send({
+ code: ApiErrorCode.AvatarNotFound,
+ message: 'Avatar not found',
+ });
+ } catch {
+ return reply.code(500).send({
+ code: ApiErrorCode.AvatarDownloadFailed,
+ message: 'Failed to download avatar',
+ });
+ }
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/avatars/avatar-upload.ts b/apps/server/src/api/client/routes/avatars/avatar-upload.ts
new file mode 100644
index 00000000..30465074
--- /dev/null
+++ b/apps/server/src/api/client/routes/avatars/avatar-upload.ts
@@ -0,0 +1,85 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import sharp from 'sharp';
+import { PutObjectCommand } from '@aws-sdk/client-s3';
+import {
+ ApiErrorCode,
+ apiErrorOutputSchema,
+ avatarUploadOutputSchema,
+ generateId,
+ IdType,
+} from '@colanode/core';
+
+import { avatarS3 } from '@/data/storage';
+import { configuration } from '@/lib/configuration';
+
+export const avatarUploadRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/',
+ schema: {
+ response: {
+ 200: avatarUploadOutputSchema,
+ 400: apiErrorOutputSchema,
+ 500: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ try {
+ const file = await request.file();
+ if (!file) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AvatarFileNotUploaded,
+ message: 'Avatar file not uploaded as part of request',
+ });
+ }
+
+ // Validate file type
+ const filetypes = /jpeg|jpg|png|webp/;
+ const extname = filetypes.test(file.filename.toLowerCase());
+ const mimetype = filetypes.test(file.mimetype);
+
+ if (!mimetype || !extname) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AvatarFileNotUploaded,
+ message: 'Only images are allowed',
+ });
+ }
+
+ // Read the file buffer
+ const buffer = await file.toBuffer();
+
+ // Resize image to a maximum of 500x500 pixels while keeping aspect ratio, and convert to JPEG using Sharp
+ const jpegBuffer = await sharp(buffer)
+ .resize({
+ width: 500,
+ height: 500,
+ fit: 'inside',
+ })
+ .jpeg()
+ .toBuffer();
+
+ const avatarId = generateId(IdType.Avatar);
+ const command = new PutObjectCommand({
+ Bucket: configuration.avatarS3.bucketName,
+ Key: `avatars/${avatarId}.jpeg`,
+ Body: jpegBuffer,
+ ContentType: 'image/jpeg',
+ });
+
+ await avatarS3.send(command);
+ return { success: true, id: avatarId };
+ } catch {
+ return reply.code(500).send({
+ code: ApiErrorCode.AvatarUploadFailed,
+ message: 'Failed to upload avatar',
+ });
+ }
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/avatars/index.ts b/apps/server/src/api/client/routes/avatars/index.ts
new file mode 100644
index 00000000..b0b392d6
--- /dev/null
+++ b/apps/server/src/api/client/routes/avatars/index.ts
@@ -0,0 +1,15 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { avatarUploadRoute } from './avatar-upload';
+import { avatarDownloadRoute } from './avatar-download';
+
+import { accountAuthenticator } from '@/api/client/plugins/account-auth';
+
+export const avatarRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(accountAuthenticator);
+
+ instance.register(avatarUploadRoute);
+ instance.register(avatarDownloadRoute);
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/config.ts b/apps/server/src/api/client/routes/config.ts
new file mode 100644
index 00000000..33e31fa7
--- /dev/null
+++ b/apps/server/src/api/client/routes/config.ts
@@ -0,0 +1,29 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { ServerConfig, serverConfigSchema } from '@colanode/core';
+
+import { configuration } from '@/lib/configuration';
+
+export const configGetRoute: FastifyPluginCallbackZod = (instance, _, done) => {
+ instance.route({
+ method: 'GET',
+ url: '/',
+ schema: {
+ response: {
+ 200: serverConfigSchema,
+ },
+ },
+ handler: async (request) => {
+ const config: ServerConfig = {
+ name: configuration.server.name,
+ avatar: configuration.server.avatar,
+ version: '0.1.0',
+ ip: request.originalIp,
+ attributes: {},
+ };
+
+ return config;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/index.ts b/apps/server/src/api/client/routes/index.ts
new file mode 100644
index 00000000..c3db2cfc
--- /dev/null
+++ b/apps/server/src/api/client/routes/index.ts
@@ -0,0 +1,17 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { synapseRoutes } from '@/api/client/routes/synapse';
+import { accountRoutes } from '@/api/client/routes/accounts';
+import { avatarRoutes } from '@/api/client/routes/avatars';
+import { workspaceRoutes } from '@/api/client/routes/workspaces';
+import { configGetRoute } from '@/api/client/routes/config';
+
+export const clientRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(synapseRoutes, { prefix: '/synapse' });
+ instance.register(configGetRoute, { prefix: '/config' });
+ instance.register(accountRoutes, { prefix: '/accounts' });
+ instance.register(avatarRoutes, { prefix: '/avatars' });
+ instance.register(workspaceRoutes, { prefix: '/workspaces' });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/synapse/index.ts b/apps/server/src/api/client/routes/synapse/index.ts
new file mode 100644
index 00000000..23955b4b
--- /dev/null
+++ b/apps/server/src/api/client/routes/synapse/index.ts
@@ -0,0 +1,13 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { socketHandler } from './socket';
+
+import { accountAuthenticator } from '@/api/client/plugins/account-auth';
+
+export const synapseRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(accountAuthenticator);
+
+ instance.register(socketHandler);
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/synapse/socket.ts b/apps/server/src/api/client/routes/synapse/socket.ts
new file mode 100644
index 00000000..705683f3
--- /dev/null
+++ b/apps/server/src/api/client/routes/synapse/socket.ts
@@ -0,0 +1,14 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { accountAuthenticator } from '@/api/client/plugins/account-auth';
+import { socketService } from '@/services/socket-service';
+
+export const socketHandler: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(accountAuthenticator);
+
+ instance.get('/', { websocket: true }, (socket, request) => {
+ socketService.addConnection(request.account, socket);
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/downloads/file-download-get.ts b/apps/server/src/api/client/routes/workspaces/downloads/file-download-get.ts
new file mode 100644
index 00000000..449ecca6
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/downloads/file-download-get.ts
@@ -0,0 +1,100 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import {
+ CreateDownloadOutput,
+ hasNodeRole,
+ ApiErrorCode,
+ extractNodeRole,
+ FileStatus,
+ createDownloadOutputSchema,
+ apiErrorOutputSchema,
+} from '@colanode/core';
+
+import { fetchNodeTree, mapNode } from '@/lib/nodes';
+import { database } from '@/data/database';
+import { buildDownloadUrl } from '@/lib/files';
+
+export const fileDownloadGetRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'GET',
+ url: '/:fileId',
+ schema: {
+ params: z.object({
+ fileId: z.string(),
+ }),
+ response: {
+ 200: createDownloadOutputSchema,
+ 400: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const fileId = request.params.fileId;
+
+ const tree = await fetchNodeTree(fileId);
+ if (tree.length === 0) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileNotFound,
+ message: 'File not found.',
+ });
+ }
+
+ const nodes = tree.map((node) => mapNode(node));
+ const file = nodes[nodes.length - 1]!;
+ if (!file || file.id !== fileId) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileNotFound,
+ message: 'File not found.',
+ });
+ }
+
+ if (file.type !== 'file') {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileNotFound,
+ message: 'This node is not a file.',
+ });
+ }
+
+ if (file.attributes.status !== FileStatus.Ready) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileNotReady,
+ message: 'File is not ready to be downloaded.',
+ });
+ }
+
+ const role = extractNodeRole(nodes, request.user.id);
+ if (role === null || !hasNodeRole(role, 'viewer')) {
+ return reply.code(403).send({
+ code: ApiErrorCode.FileNoAccess,
+ message: 'You do not have access to this file.',
+ });
+ }
+
+ const upload = await database
+ .selectFrom('uploads')
+ .selectAll()
+ .where('file_id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!upload || !upload.uploaded_at) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileUploadNotFound,
+ message: 'File upload not found.',
+ });
+ }
+
+ const presignedUrl = await buildDownloadUrl(upload.path);
+ const output: CreateDownloadOutput = {
+ url: presignedUrl,
+ };
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/downloads/index.ts b/apps/server/src/api/client/routes/workspaces/downloads/index.ts
new file mode 100644
index 00000000..29cbe69a
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/downloads/index.ts
@@ -0,0 +1,9 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { fileDownloadGetRoute } from './file-download-get';
+
+export const downloadRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(fileDownloadGetRoute);
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/files/file-upload-complete.ts b/apps/server/src/api/client/routes/workspaces/files/file-upload-complete.ts
new file mode 100644
index 00000000..1ac8be9a
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/files/file-upload-complete.ts
@@ -0,0 +1,163 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import {
+ FileStatus,
+ ApiErrorCode,
+ completeUploadOutputSchema,
+ apiErrorOutputSchema,
+ completeUploadInputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { mapNode, updateNode } from '@/lib/nodes';
+import { fetchFileMetadata } from '@/lib/files';
+
+export const fileUploadCompleteRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'PUT',
+ url: '/:fileId',
+ schema: {
+ params: z.object({
+ workspaceId: z.string(),
+ fileId: z.string(),
+ }),
+ body: completeUploadInputSchema,
+ response: {
+ 200: completeUploadOutputSchema,
+ 400: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const workspaceId = request.params.workspaceId;
+ const fileId = request.params.fileId;
+ const uploadId = request.body.uploadId;
+
+ const node = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!node) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileNotFound,
+ message: 'File not found.',
+ });
+ }
+
+ if (node.created_by !== request.user.id) {
+ return reply.code(403).send({
+ code: ApiErrorCode.FileOwnerMismatch,
+ message: 'You cannot complete this file upload.',
+ });
+ }
+
+ if (node.workspace_id !== workspaceId) {
+ return reply.code(400).send({
+ code: ApiErrorCode.WorkspaceMismatch,
+ message: 'File does not belong to this workspace.',
+ });
+ }
+
+ const file = mapNode(node);
+ if (file.type !== 'file') {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileNotFound,
+ message: 'This node is not a file.',
+ });
+ }
+
+ if (file.attributes.status === FileStatus.Ready) {
+ return { success: true };
+ }
+
+ if (file.attributes.status === FileStatus.Error) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileError,
+ message: 'File has failed to upload.',
+ });
+ }
+
+ const upload = await database
+ .selectFrom('uploads')
+ .selectAll()
+ .where('file_id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!upload) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileUploadNotFound,
+ message: 'Upload not found.',
+ });
+ }
+
+ if (upload.file_id !== fileId || upload.upload_id !== uploadId) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileUploadNotFound,
+ message: 'Upload not found.',
+ });
+ }
+
+ const path = upload.path;
+ const metadata = await fetchFileMetadata(path);
+ if (metadata === null) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileNotFound,
+ message: 'File not found.',
+ });
+ }
+
+ if (metadata.size !== file.attributes.size) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileSizeMismatch,
+ message: 'Uploaded file size does not match expected size',
+ });
+ }
+
+ if (metadata.mimeType !== file.attributes.mimeType) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileMimeTypeMismatch,
+ message: 'Uploaded file type does not match expected type',
+ });
+ }
+
+ const result = await updateNode({
+ nodeId: fileId,
+ userId: request.account.id,
+ workspaceId: workspaceId,
+ updater(attributes) {
+ if (attributes.type !== 'file') {
+ throw new Error('Node is not a file');
+ }
+
+ attributes.status = FileStatus.Ready;
+ return attributes;
+ },
+ });
+
+ if (result === null) {
+ return reply.code(500).send({
+ code: ApiErrorCode.FileUploadCompleteFailed,
+ message: 'Failed to complete file upload.',
+ });
+ }
+
+ await database
+ .updateTable('uploads')
+ .set({
+ uploaded_at: new Date(),
+ })
+ .where('file_id', '=', fileId)
+ .execute();
+
+ return { success: true };
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/files/file-upload-init.ts b/apps/server/src/api/client/routes/workspaces/files/file-upload-init.ts
new file mode 100644
index 00000000..eed13124
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/files/file-upload-init.ts
@@ -0,0 +1,151 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ CreateUploadOutput,
+ ApiErrorCode,
+ generateId,
+ IdType,
+ createUploadInputSchema,
+ createUploadOutputSchema,
+ apiErrorOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { mapNode } from '@/lib/nodes';
+import { buildFilePath, buildUploadUrl } from '@/lib/files';
+
+export const fileUploadInitRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/',
+ schema: {
+ body: createUploadInputSchema,
+ response: {
+ 200: createUploadOutputSchema,
+ 400: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const input = request.body;
+ const user = request.user;
+
+ const node = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', input.fileId)
+ .executeTakeFirst();
+
+ if (!node) {
+ return reply.code(404).send({
+ code: ApiErrorCode.FileNotFound,
+ message: 'File not found.',
+ });
+ }
+
+ if (node.created_by !== user.id) {
+ return reply.code(403).send({
+ code: ApiErrorCode.FileOwnerMismatch,
+ message: 'You do not have access to this file.',
+ });
+ }
+
+ const file = mapNode(node);
+ if (file.type !== 'file') {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileNotFound,
+ message: 'This node is not a file.',
+ });
+ }
+
+ const upload = await database
+ .selectFrom('uploads')
+ .selectAll()
+ .where('file_id', '=', input.fileId)
+ .executeTakeFirst();
+
+ if (upload && upload.uploaded_at) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileAlreadyUploaded,
+ message: 'This file is already uploaded.',
+ });
+ }
+
+ const storageUsedRow = await database
+ .selectFrom('uploads')
+ .select(({ fn }) => [fn.sum('size').as('storage_used')])
+ .where('created_by', '=', request.user.id)
+ .executeTakeFirst();
+
+ const storageUsed = BigInt(storageUsedRow?.storage_used ?? 0);
+ const storageLimit = BigInt(user.storage_limit);
+
+ if (storageUsed >= storageLimit) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileUploadInitFailed,
+ message: 'You have reached the maximum storage limit.',
+ });
+ }
+
+ const path = buildFilePath(
+ node.workspace_id,
+ input.fileId,
+ file.attributes
+ );
+
+ const uploadId = generateId(IdType.Upload);
+ const upsertedUpload = await database
+ .insertInto('uploads')
+ .values({
+ file_id: input.fileId,
+ upload_id: uploadId,
+ workspace_id: node.workspace_id,
+ root_id: node.root_id,
+ mime_type: file.attributes.mimeType,
+ size: file.attributes.size,
+ path: path,
+ version_id: file.attributes.version,
+ created_at: new Date(),
+ created_by: request.user.id,
+ })
+ .onConflict((b) =>
+ b.columns(['file_id']).doUpdateSet({
+ upload_id: uploadId,
+ mime_type: file.attributes.mimeType,
+ size: file.attributes.size,
+ path: path,
+ version_id: file.attributes.version,
+ created_at: new Date(),
+ created_by: request.user.id,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!upsertedUpload) {
+ return reply.code(400).send({
+ code: ApiErrorCode.FileUploadInitFailed,
+ message: 'Failed to initialize file upload.',
+ });
+ }
+
+ //generate presigned url for upload
+ const presignedUrl = await buildUploadUrl(
+ path,
+ file.attributes.size,
+ file.attributes.mimeType
+ );
+
+ const output: CreateUploadOutput = {
+ url: presignedUrl,
+ uploadId: uploadId,
+ };
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/files/index.ts b/apps/server/src/api/client/routes/workspaces/files/index.ts
new file mode 100644
index 00000000..29aa6b76
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/files/index.ts
@@ -0,0 +1,11 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { fileUploadCompleteRoute } from './file-upload-complete';
+import { fileUploadInitRoute } from './file-upload-init';
+
+export const fileRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(fileUploadCompleteRoute);
+ instance.register(fileUploadInitRoute);
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/index.ts b/apps/server/src/api/client/routes/workspaces/index.ts
new file mode 100644
index 00000000..2fc99fef
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/index.ts
@@ -0,0 +1,39 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { fileRoutes } from './files';
+import { downloadRoutes } from './downloads';
+import { userRoutes } from './users';
+import { mutationsRoutes } from './mutations';
+import { workspaceCreateRoute } from './workspace-create';
+import { workspaceDeleteRoute } from './workspace-delete';
+import { workspaceGetRoute } from './workspace-get';
+import { workspaceUpdateRoute } from './workspace-update';
+
+import { accountAuthenticator } from '@/api/client/plugins/account-auth';
+import { workspaceAuthenticator } from '@/api/client/plugins/workspace-auth';
+
+export const workspaceRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(accountAuthenticator);
+
+ instance.register(workspaceCreateRoute);
+
+ instance.register(
+ (subInstance) => {
+ subInstance.register(workspaceAuthenticator);
+
+ subInstance.register(workspaceDeleteRoute);
+ subInstance.register(workspaceGetRoute);
+ subInstance.register(workspaceUpdateRoute);
+
+ subInstance.register(fileRoutes, { prefix: '/files' });
+ subInstance.register(downloadRoutes, { prefix: '/downloads' });
+ subInstance.register(userRoutes, { prefix: '/users' });
+ subInstance.register(mutationsRoutes, { prefix: '/mutations' });
+ },
+ {
+ prefix: '/:workspaceId',
+ }
+ );
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/mutations/index.ts b/apps/server/src/api/client/routes/workspaces/mutations/index.ts
new file mode 100644
index 00000000..f1bc5fc8
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/mutations/index.ts
@@ -0,0 +1,9 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { mutationsSyncRoute } from './mutations-sync';
+
+export const mutationsRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(mutationsSyncRoute);
+
+ done();
+};
diff --git a/apps/server/src/api/client/controllers/workspaces/mutations/mutations-sync.ts b/apps/server/src/api/client/routes/workspaces/mutations/mutations-sync.ts
similarity index 79%
rename from apps/server/src/api/client/controllers/workspaces/mutations/mutations-sync.ts
rename to apps/server/src/api/client/routes/workspaces/mutations/mutations-sync.ts
index 95f37811..1da9b455 100644
--- a/apps/server/src/api/client/controllers/workspaces/mutations/mutations-sync.ts
+++ b/apps/server/src/api/client/routes/workspaces/mutations/mutations-sync.ts
@@ -1,6 +1,5 @@
-import { Request, Response } from 'express';
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
import {
- SyncMutationsInput,
SyncMutationResult,
SyncMutationStatus,
Mutation,
@@ -12,10 +11,10 @@ import {
MarkNodeOpenedMutation,
UpdateNodeMutation,
UpdateDocumentMutation,
+ syncMutationsInputSchema,
} from '@colanode/core';
import { SelectUser } from '@/data/schema';
-import { ResponseBuilder } from '@/lib/response-builder';
import {
createNodeFromMutation,
updateNodeFromMutation,
@@ -25,30 +24,43 @@ import { createNodeReaction, deleteNodeReaction } from '@/lib/node-reactions';
import { markNodeAsOpened, markNodeAsSeen } from '@/lib/node-interactions';
import { updateDocumentFromMutation } from '@/lib/documents';
-export const mutationsSyncHandler = async (
- req: Request,
- res: Response
-): Promise<void> => {
- const input = req.body as SyncMutationsInput;
-
- const results: SyncMutationResult[] = [];
- for (const mutation of input.mutations) {
- try {
- const status = await handleMutation(res.locals.user, mutation);
- results.push({
- id: mutation.id,
- status: status,
- });
- } catch (error) {
- console.error('Error handling local mutation', error);
- results.push({
- id: mutation.id,
- status: 'error',
- });
- }
- }
+export const mutationsSyncRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/',
+ schema: {
+ body: syncMutationsInputSchema,
+ },
+ handler: async (request) => {
+ const input = request.body;
+ const user = request.user;
+
+ const results: SyncMutationResult[] = [];
+ for (const mutation of input.mutations) {
+ try {
+ const status = await handleMutation(user, mutation);
+ results.push({
+ id: mutation.id,
+ status: status,
+ });
+ } catch (error) {
+ console.error('Error handling local mutation', error);
+ results.push({
+ id: mutation.id,
+ status: 'error',
+ });
+ }
+ }
+
+ return { results };
+ },
+ });
- return ResponseBuilder.success(res, { results });
+ done();
};
const handleMutation = async (
diff --git a/apps/server/src/api/client/routes/workspaces/users/index.ts b/apps/server/src/api/client/routes/workspaces/users/index.ts
new file mode 100644
index 00000000..cafc1b4d
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/users/index.ts
@@ -0,0 +1,11 @@
+import { FastifyPluginCallback } from 'fastify';
+
+import { userCreateRoute } from './user-create';
+import { userRoleUpdateRoute } from './user-role-update';
+
+export const userRoutes: FastifyPluginCallback = (instance, _, done) => {
+ instance.register(userCreateRoute);
+ instance.register(userRoleUpdateRoute);
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/users/user-create.ts b/apps/server/src/api/client/routes/workspaces/users/user-create.ts
new file mode 100644
index 00000000..3c689893
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/users/user-create.ts
@@ -0,0 +1,164 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import {
+ AccountStatus,
+ ApiErrorCode,
+ apiErrorOutputSchema,
+ generateId,
+ IdType,
+ UserInviteResult,
+ usersInviteInputSchema,
+ usersInviteOutputSchema,
+ UserStatus,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { getNameFromEmail } from '@/lib/utils';
+import { SelectAccount } from '@/data/schema';
+import { eventBus } from '@/lib/event-bus';
+import { configuration } from '@/lib/configuration';
+
+export const userCreateRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/',
+ schema: {
+ params: z.object({
+ workspaceId: z.string(),
+ }),
+ body: usersInviteInputSchema,
+ response: {
+ 200: usersInviteOutputSchema,
+ 400: apiErrorOutputSchema,
+ 403: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const workspaceId = request.params.workspaceId;
+ const input = request.body;
+ const user = request.user;
+
+ if (!input.emails || input.emails.length === 0) {
+ return reply.code(400).send({
+ code: ApiErrorCode.UserEmailRequired,
+ message: 'User email is required.',
+ });
+ }
+
+ if (user.role !== 'owner' && user.role !== 'admin') {
+ return reply.code(403).send({
+ code: ApiErrorCode.UserInviteNoAccess,
+ message: 'You do not have access to invite users to this workspace.',
+ });
+ }
+
+ const results: UserInviteResult[] = [];
+ for (const email of input.emails) {
+ const account = await getOrCreateAccount(email);
+ if (!account) {
+ results.push({
+ email: email,
+ result: 'error',
+ });
+ continue;
+ }
+
+ const existingUser = await database
+ .selectFrom('users')
+ .selectAll()
+ .where('account_id', '=', account.id)
+ .where('workspace_id', '=', workspaceId)
+ .executeTakeFirst();
+
+ if (existingUser) {
+ results.push({
+ email: email,
+ result: 'exists',
+ });
+ continue;
+ }
+
+ const userId = generateId(IdType.User);
+ const newUser = await database
+ .insertInto('users')
+ .returningAll()
+ .values({
+ id: userId,
+ account_id: account.id,
+ workspace_id: workspaceId,
+ role: input.role,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
+ storage_limit: configuration.user.storageLimit.toString(),
+ max_file_size: configuration.user.maxFileSize.toString(),
+ created_at: new Date(),
+ created_by: request.account.id,
+ status: UserStatus.Active,
+ })
+ .executeTakeFirst();
+
+ if (!newUser) {
+ results.push({
+ email: email,
+ result: 'error',
+ });
+ continue;
+ }
+
+ eventBus.publish({
+ type: 'user_created',
+ accountId: account.id,
+ userId: userId,
+ workspaceId: workspaceId,
+ });
+
+ results.push({
+ email: email,
+ result: 'success',
+ });
+ }
+
+ return { results };
+ },
+ });
+
+ done();
+};
+
+const getOrCreateAccount = async (
+ email: string
+): Promise<SelectAccount | undefined> => {
+ const account = await database
+ .selectFrom('accounts')
+ .selectAll()
+ .where('email', '=', email)
+ .executeTakeFirst();
+
+ if (account) {
+ return account;
+ }
+
+ const createdAccount = await database
+ .insertInto('accounts')
+ .returningAll()
+ .values({
+ id: generateId(IdType.Account),
+ name: getNameFromEmail(email),
+ email: email,
+ avatar: null,
+ attrs: null,
+ password: null,
+ status: AccountStatus.Pending,
+ created_at: new Date(),
+ updated_at: null,
+ })
+ .executeTakeFirst();
+
+ return createdAccount;
+};
diff --git a/apps/server/src/api/client/routes/workspaces/users/user-role-update.ts b/apps/server/src/api/client/routes/workspaces/users/user-role-update.ts
new file mode 100644
index 00000000..13858d0e
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/users/user-role-update.ts
@@ -0,0 +1,83 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import {
+ ApiErrorCode,
+ UserStatus,
+ userRoleUpdateInputSchema,
+ apiErrorOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { eventBus } from '@/lib/event-bus';
+
+export const userRoleUpdateRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'PUT',
+ url: '/:userId',
+ schema: {
+ params: z.object({
+ userId: z.string(),
+ }),
+ body: userRoleUpdateInputSchema,
+ response: {
+ 200: z.object({ success: z.boolean() }),
+ 400: apiErrorOutputSchema,
+ 403: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const userId = request.params.userId;
+ const input = request.body;
+ const user = request.user;
+
+ if (user.role !== 'owner' && user.role !== 'admin') {
+ return reply.code(403).send({
+ code: ApiErrorCode.UserUpdateNoAccess,
+ message: 'You do not have access to update users to this workspace.',
+ });
+ }
+
+ const userToUpdate = await database
+ .selectFrom('users')
+ .selectAll()
+ .where('id', '=', userId)
+ .executeTakeFirst();
+
+ if (!userToUpdate) {
+ return reply.code(404).send({
+ code: ApiErrorCode.UserNotFound,
+ message: 'User not found.',
+ });
+ }
+
+ 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,
+ })
+ .where('id', '=', userToUpdate.id)
+ .execute();
+
+ eventBus.publish({
+ type: 'user_updated',
+ userId: userToUpdate.id,
+ accountId: userToUpdate.account_id,
+ workspaceId: userToUpdate.workspace_id,
+ });
+
+ return { success: true };
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/workspace-create.ts b/apps/server/src/api/client/routes/workspaces/workspace-create.ts
new file mode 100644
index 00000000..efab790e
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/workspace-create.ts
@@ -0,0 +1,56 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import {
+ ApiErrorCode,
+ workspaceCreateInputSchema,
+ apiErrorOutputSchema,
+ workspaceOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { createWorkspace } from '@/lib/workspaces';
+
+export const workspaceCreateRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'POST',
+ url: '/',
+ schema: {
+ body: workspaceCreateInputSchema,
+ response: {
+ 200: workspaceOutputSchema,
+ 400: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const input = request.body;
+
+ if (!input.name) {
+ return reply.code(400).send({
+ code: ApiErrorCode.WorkspaceNameRequired,
+ message: 'Workspace name is required.',
+ });
+ }
+
+ const account = await database
+ .selectFrom('accounts')
+ .selectAll()
+ .where('id', '=', request.account.id)
+ .executeTakeFirst();
+
+ if (!account) {
+ return reply.code(400).send({
+ code: ApiErrorCode.AccountNotFound,
+ message: 'Account not found.',
+ });
+ }
+
+ const output = await createWorkspace(account, input);
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/workspace-delete.ts b/apps/server/src/api/client/routes/workspaces/workspace-delete.ts
new file mode 100644
index 00000000..27c6050d
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/workspace-delete.ts
@@ -0,0 +1,55 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import { ApiErrorCode, apiErrorOutputSchema } from '@colanode/core';
+
+import { database } from '@/data/database';
+import { eventBus } from '@/lib/event-bus';
+
+export const workspaceDeleteRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'DELETE',
+ url: '/:workspaceId',
+ schema: {
+ params: z.object({
+ workspaceId: z.string(),
+ }),
+ response: {
+ 200: z.object({ id: z.string() }),
+ 400: apiErrorOutputSchema,
+ 403: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const workspaceId = request.params.workspaceId;
+
+ if (request.user.role !== 'owner') {
+ return reply.code(403).send({
+ code: ApiErrorCode.WorkspaceDeleteNotAllowed,
+ message:
+ 'You are not allowed to delete this workspace. Only owners can delete workspaces.',
+ });
+ }
+
+ await database
+ .deleteFrom('workspaces')
+ .where('id', '=', workspaceId)
+ .execute();
+
+ eventBus.publish({
+ type: 'workspace_deleted',
+ workspaceId: workspaceId,
+ });
+
+ return {
+ id: workspaceId,
+ };
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/workspace-get.ts b/apps/server/src/api/client/routes/workspaces/workspace-get.ts
new file mode 100644
index 00000000..7110fbb3
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/workspace-get.ts
@@ -0,0 +1,82 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import {
+ WorkspaceRole,
+ WorkspaceOutput,
+ ApiErrorCode,
+ UserStatus,
+ apiErrorOutputSchema,
+ workspaceOutputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+
+export const workspaceGetRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'GET',
+ url: '/:workspaceId',
+ schema: {
+ params: z.object({
+ workspaceId: z.string(),
+ }),
+ response: {
+ 200: workspaceOutputSchema,
+ 400: apiErrorOutputSchema,
+ 403: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const workspaceId = request.params.workspaceId;
+
+ const workspace = await database
+ .selectFrom('workspaces')
+ .selectAll()
+ .where('id', '=', workspaceId)
+ .executeTakeFirst();
+
+ if (!workspace) {
+ return reply.code(400).send({
+ code: ApiErrorCode.WorkspaceNotFound,
+ message: 'Workspace not found.',
+ });
+ }
+
+ const user = await database
+ .selectFrom('users')
+ .selectAll()
+ .where('workspace_id', '=', workspaceId)
+ .where('account_id', '=', request.account.id)
+ .executeTakeFirst();
+
+ if (!user || user.status !== UserStatus.Active || user.role === 'none') {
+ return reply.code(403).send({
+ code: ApiErrorCode.WorkspaceNoAccess,
+ message: 'You do not have access to this workspace.',
+ });
+ }
+
+ const output: WorkspaceOutput = {
+ id: workspace.id,
+ name: workspace.name,
+ description: workspace.description,
+ avatar: workspace.avatar,
+ user: {
+ id: user.id,
+ accountId: user.account_id,
+ role: user.role as WorkspaceRole,
+ storageLimit: user.storage_limit,
+ maxFileSize: user.max_file_size,
+ },
+ };
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/api/client/routes/workspaces/workspace-update.ts b/apps/server/src/api/client/routes/workspaces/workspace-update.ts
new file mode 100644
index 00000000..ad6b4d04
--- /dev/null
+++ b/apps/server/src/api/client/routes/workspaces/workspace-update.ts
@@ -0,0 +1,90 @@
+import { FastifyPluginCallbackZod } from 'fastify-type-provider-zod';
+import { z } from 'zod';
+import {
+ WorkspaceOutput,
+ ApiErrorCode,
+ apiErrorOutputSchema,
+ workspaceOutputSchema,
+ workspaceUpdateInputSchema,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { eventBus } from '@/lib/event-bus';
+
+export const workspaceUpdateRoute: FastifyPluginCallbackZod = (
+ instance,
+ _,
+ done
+) => {
+ instance.route({
+ method: 'PUT',
+ url: '/',
+ schema: {
+ params: z.object({
+ workspaceId: z.string(),
+ }),
+ body: workspaceUpdateInputSchema,
+ response: {
+ 200: workspaceOutputSchema,
+ 400: apiErrorOutputSchema,
+ 403: apiErrorOutputSchema,
+ 404: apiErrorOutputSchema,
+ },
+ },
+ handler: async (request, reply) => {
+ const workspaceId = request.params.workspaceId;
+ const input = request.body;
+
+ if (request.user.role !== 'owner') {
+ return reply.code(403).send({
+ code: ApiErrorCode.WorkspaceUpdateNotAllowed,
+ message:
+ 'You are not allowed to update this workspace. Only owners can update workspaces.',
+ });
+ }
+
+ const updatedWorkspace = await database
+ .updateTable('workspaces')
+ .set({
+ name: input.name,
+ description: input.description,
+ avatar: input.avatar,
+ updated_at: new Date(),
+ updated_by: request.user.id,
+ })
+ .where('id', '=', workspaceId)
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!updatedWorkspace) {
+ return reply.code(500).send({
+ code: ApiErrorCode.WorkspaceUpdateFailed,
+ message: 'Failed to update workspace.',
+ });
+ }
+
+ eventBus.publish({
+ type: 'workspace_updated',
+ workspaceId: updatedWorkspace.id,
+ });
+
+ const output: WorkspaceOutput = {
+ id: updatedWorkspace.id,
+ name: updatedWorkspace.name,
+ description: updatedWorkspace.description,
+ avatar: updatedWorkspace.avatar,
+ user: {
+ id: request.user.id,
+ accountId: request.user.account_id,
+ role: request.user.role,
+ storageLimit: request.user.storage_limit,
+ maxFileSize: request.user.max_file_size,
+ },
+ };
+
+ return output;
+ },
+ });
+
+ done();
+};
diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts
index feb9fa70..6d780ea0 100644
--- a/apps/server/src/app.ts
+++ b/apps/server/src/app.ts
@@ -1,39 +1,51 @@
-import cors from 'cors';
-import express, { Request, Response } from 'express';
import { createDebugger } from '@colanode/core';
-
-import http from 'http';
-
-import { clientRouter } from '@/api/client/routes';
-import { ipMiddleware } from '@/api/client/middlewares/ip';
-import { socketService } from '@/services/socket-service';
+import { fastify } from 'fastify';
+import fastifyMultipart from '@fastify/multipart';
+import fastifyWebsocket from '@fastify/websocket';
+import {
+ serializerCompiler,
+ validatorCompiler,
+} from 'fastify-type-provider-zod';
+
+import { clientRoutes } from '@/api/client/routes';
+import { ipDecorator } from '@/api/client/plugins/ip';
+import { errorHandler } from '@/api/client/plugins/error-handler';
const debug = createDebugger('server:app');
export const initApp = async () => {
- const app = express();
- const port = 3000;
-
- app.use(
- express.json({
- limit: '50mb',
- })
- );
- app.use(cors());
- app.use(ipMiddleware);
-
- app.get('/', (_: Request, res: Response) => {
- res.send(
+ const server = fastify({
+ bodyLimit: 10 * 1024 * 1024, // 10MB
+ });
+
+ // register the global error handler in the beginning of the app
+ server.register(errorHandler);
+
+ server.setSerializerCompiler(serializerCompiler);
+ server.setValidatorCompiler(validatorCompiler);
+
+ await server.register(fastifyMultipart, {
+ limits: {
+ fileSize: 10 * 1024 * 1024, // 10MB
+ },
+ });
+
+ await server.register(fastifyWebsocket);
+ await server.register(ipDecorator);
+ await server.register(clientRoutes, { prefix: '/client/v1' });
+
+ server.get('/', (_, reply) => {
+ reply.send(
'This is a Colanode server. For more information, visit https://colanode.com'
);
});
- app.use('/client', clientRouter);
-
- const server = http.createServer(app);
- await socketService.init(server);
+ server.listen({ port: 3000 }, (err, address) => {
+ if (err) {
+ debug(`Failed to start server: ${err}`);
+ process.exit(1);
+ }
- server.listen(port, () => {
- debug(`Server is running at http://localhost:${port}`);
+ debug(`Server is running at ${address}`);
});
};
diff --git a/apps/server/src/data/database.ts b/apps/server/src/data/database.ts
index c167617d..6cddbbd8 100644
--- a/apps/server/src/data/database.ts
+++ b/apps/server/src/data/database.ts
@@ -16,6 +16,14 @@ import { configuration } from '@/lib/configuration';
const debug = createDebugger('server:database');
+pg.types.setTypeParser(pg.types.builtins.NUMERIC, (val) => {
+ return parseFloat(val);
+});
+
+pg.types.setTypeParser(pg.types.builtins.INT4, (val) => {
+ return parseInt(val);
+});
+
const dialect = new PostgresDialect({
pool: new pg.Pool({
connectionString: configuration.postgres.url,
diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.ts
index f86735e7..7e584380 100644
--- a/apps/server/src/data/schema.ts
+++ b/apps/server/src/data/schema.ts
@@ -73,15 +73,15 @@ interface UserTable {
id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
account_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, never, never>;
+ revision: ColumnType<string, never, never>;
email: ColumnType<string, string, string>;
role: ColumnType<WorkspaceRole, WorkspaceRole, WorkspaceRole>;
name: ColumnType<string, string, string>;
avatar: ColumnType<string | null, string | null, string | null>;
custom_name: ColumnType<string | null, string | null, string | null>;
custom_avatar: ColumnType<string | null, string | null, string | null>;
- storage_limit: ColumnType<bigint, bigint, bigint>;
- max_file_size: ColumnType<bigint, bigint, bigint>;
+ storage_limit: ColumnType<string, string, string>;
+ max_file_size: ColumnType<string, string, string>;
created_at: ColumnType<Date, Date, never>;
created_by: ColumnType<string, string, never>;
updated_at: ColumnType<Date | null, Date | null, Date>;
@@ -99,7 +99,7 @@ interface NodeTable {
parent_id: ColumnType<string | null, never, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
attributes: JSONColumnType<NodeAttributes, string | null, string | null>;
created_at: ColumnType<Date, Date, never>;
created_by: ColumnType<string, string, never>;
@@ -116,7 +116,7 @@ interface NodeUpdateTable {
node_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, never, never>;
+ revision: ColumnType<string, never, never>;
data: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
created_at: ColumnType<Date, Date, never>;
created_by: ColumnType<string, string, never>;
@@ -136,7 +136,7 @@ interface NodeInteractionTable {
collaborator_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, never, never>;
+ revision: ColumnType<string, never, never>;
first_seen_at: ColumnType<Date | null, Date | null, Date | null>;
last_seen_at: ColumnType<Date | null, Date | null, Date | null>;
first_opened_at: ColumnType<Date | null, Date | null, Date | null>;
@@ -152,7 +152,7 @@ interface NodeReactionTable {
collaborator_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, never, never>;
+ revision: ColumnType<string, never, never>;
reaction: ColumnType<string, string, string>;
created_at: ColumnType<Date, Date, Date>;
deleted_at: ColumnType<Date | null, Date | null, Date | null>;
@@ -166,7 +166,7 @@ interface NodeTombstoneTable {
id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, never, never>;
+ revision: ColumnType<string, never, never>;
deleted_at: ColumnType<Date, Date, Date>;
deleted_by: ColumnType<string, string, never>;
}
@@ -190,7 +190,7 @@ interface CollaborationTable {
node_id: ColumnType<string, string, never>;
collaborator_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, never, never>;
+ revision: ColumnType<string, never, never>;
role: ColumnType<NodeRole, NodeRole, NodeRole>;
created_at: ColumnType<Date, Date, never>;
created_by: ColumnType<string, string, never>;
@@ -208,7 +208,7 @@ interface DocumentTable {
id: ColumnType<string, string, never>;
type: ColumnType<DocumentType, never, never>;
workspace_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
content: JSONColumnType<DocumentContent, string, string>;
created_at: ColumnType<Date, Date, never>;
created_by: ColumnType<string, string, never>;
@@ -225,7 +225,7 @@ interface DocumentUpdateTable {
document_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- revision: ColumnType<bigint, never, never>;
+ revision: ColumnType<string, never, never>;
data: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
created_at: ColumnType<Date, Date, never>;
created_by: ColumnType<string, string, never>;
@@ -261,7 +261,7 @@ export type UpdateUpload = Updateable<UploadTable>;
interface NodeEmbeddingTable {
node_id: ColumnType<string, string, never>;
chunk: ColumnType<number, number, number>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
workspace_id: ColumnType<string, string, never>;
text: ColumnType<string, string, string>;
summary: ColumnType<string | null, string | null, string | null>;
@@ -278,7 +278,7 @@ export type UpdateNodeEmbedding = Updateable<NodeEmbeddingTable>;
interface DocumentEmbeddingTable {
document_id: ColumnType<string, string, never>;
chunk: ColumnType<number, number, number>;
- revision: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<string, string, string>;
workspace_id: ColumnType<string, string, never>;
text: ColumnType<string, string, string>;
summary: ColumnType<string | null, string | null, string | null>;
diff --git a/apps/server/src/jobs/check-document-embeddings.ts b/apps/server/src/jobs/check-document-embeddings.ts
index 9f2fe7fa..ac500367 100644
--- a/apps/server/src/jobs/check-document-embeddings.ts
+++ b/apps/server/src/jobs/check-document-embeddings.ts
@@ -63,7 +63,7 @@ export const checkDocumentEmbeddingsHandler = async () => {
.orderBy('created_at', 'asc')
.executeTakeFirst();
- const revision = firstEmbedding?.revision ?? 0n;
+ const revision = firstEmbedding?.revision ?? '0';
if (revision >= document.revision) {
continue;
}
@@ -72,7 +72,7 @@ export const checkDocumentEmbeddingsHandler = async () => {
}
if (documents.length > 0) {
- lastRevision = documents[documents.length - 1]?.revision ?? 0n;
+ lastRevision = documents[documents.length - 1]?.revision ?? '0';
}
if (documents.length < BATCH_SIZE) {
diff --git a/apps/server/src/jobs/check-node-embeddings.ts b/apps/server/src/jobs/check-node-embeddings.ts
index afbb7eb7..4b3192a5 100644
--- a/apps/server/src/jobs/check-node-embeddings.ts
+++ b/apps/server/src/jobs/check-node-embeddings.ts
@@ -76,7 +76,7 @@ export const checkNodeEmbeddingsHandler = async () => {
.orderBy('created_at', 'asc')
.executeTakeFirst();
- const revision = firstEmbedding?.revision ?? 0n;
+ const revision = firstEmbedding?.revision ?? '0';
if (revision >= node.revision) {
continue;
}
@@ -85,7 +85,7 @@ export const checkNodeEmbeddingsHandler = async () => {
}
if (nodes.length > 0) {
- lastRevision = nodes[nodes.length - 1]?.revision ?? 0n;
+ lastRevision = nodes[nodes.length - 1]?.revision ?? '0';
}
if (nodes.length < BATCH_SIZE) {
diff --git a/apps/server/src/lib/accounts.ts b/apps/server/src/lib/accounts.ts
index f48a5b11..5f2c1bdb 100644
--- a/apps/server/src/lib/accounts.ts
+++ b/apps/server/src/lib/accounts.ts
@@ -39,6 +39,13 @@ export const generatePasswordHash = async (
});
};
+export const verifyPassword = async (
+ password: string,
+ hash: string
+): Promise<boolean> => {
+ return await argon2.verify(hash, password);
+};
+
export const buildLoginSuccessOutput = async (
account: SelectAccount,
metadata: DeviceMetadata
diff --git a/apps/server/src/lib/embeddings.ts b/apps/server/src/lib/embeddings.ts
index bb34d567..c9c38d89 100644
--- a/apps/server/src/lib/embeddings.ts
+++ b/apps/server/src/lib/embeddings.ts
@@ -7,20 +7,20 @@ import { jobService } from '@/services/job-service';
export const fetchEmbeddingCursor = async (
cursorId: string
-): Promise<bigint> => {
+): Promise<string> => {
const cursorStringValue = await redis.get(`embedding_cursor:${cursorId}`);
if (!cursorStringValue) {
- return 0n;
+ return '0';
}
- return BigInt(cursorStringValue);
+ return cursorStringValue;
};
export const updateEmbeddingCursor = async (
cursorId: string,
- value: bigint
+ value: string
) => {
- await redis.set(`embedding_cursor:${cursorId}`, value.toString());
+ await redis.set(`embedding_cursor:${cursorId}`, value);
};
export const deleteEmbeddingCursor = async (cursorId: string) => {
diff --git a/apps/server/src/lib/response-builder.ts b/apps/server/src/lib/response-builder.ts
deleted file mode 100644
index 99d6b1ad..00000000
--- a/apps/server/src/lib/response-builder.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { Response } from 'express';
-import { ApiErrorOutput } from '@colanode/core';
-
-export class ResponseBuilder {
- static error(res: Response, status: number, error: ApiErrorOutput): void {
- res.status(status).json(error);
- }
-
- static notFound(res: Response, error: ApiErrorOutput): void {
- ResponseBuilder.error(res, 404, error);
- }
-
- static badRequest(res: Response, error: ApiErrorOutput): void {
- ResponseBuilder.error(res, 400, error);
- }
-
- static unauthorized(res: Response, error: ApiErrorOutput): void {
- ResponseBuilder.error(res, 401, error);
- }
-
- static forbidden(res: Response, error: ApiErrorOutput): void {
- ResponseBuilder.error(res, 403, error);
- }
-
- static internalError(res: Response, error: ApiErrorOutput): void {
- ResponseBuilder.error(res, 500, error);
- }
-
- static tooManyRequests(res: Response, error: ApiErrorOutput): void {
- ResponseBuilder.error(res, 429, error);
- }
-
- static success<T>(res: Response, data: T): void {
- res.status(200).json(data);
- }
-}
diff --git a/apps/server/src/lib/workspaces.ts b/apps/server/src/lib/workspaces.ts
index 3d230a94..f99c2e91 100644
--- a/apps/server/src/lib/workspaces.ts
+++ b/apps/server/src/lib/workspaces.ts
@@ -55,8 +55,8 @@ export const createWorkspace = async (
name: account.name,
email: account.email,
avatar: account.avatar,
- storage_limit: configuration.user.storageLimit,
- max_file_size: configuration.user.maxFileSize,
+ storage_limit: configuration.user.storageLimit.toString(),
+ max_file_size: configuration.user.maxFileSize.toString(),
created_at: date,
created_by: account.id,
status: UserStatus.Active,
diff --git a/apps/server/src/services/socket-connection.ts b/apps/server/src/services/socket-connection.ts
index 6fa799e3..1b562d7d 100644
--- a/apps/server/src/services/socket-connection.ts
+++ b/apps/server/src/services/socket-connection.ts
@@ -35,8 +35,9 @@ type SocketUser = {
synchronizers: Map<string, BaseSynchronizer<SynchronizerInput>>;
};
+const debug = createDebugger('server:service:socket-connection');
+
export class SocketConnection {
- private readonly debug = createDebugger('server:service:socket-connection');
private readonly account: RequestAccount;
private readonly socket: WebSocket;
@@ -45,9 +46,7 @@ export class SocketConnection {
new Map();
constructor(account: RequestAccount, socket: WebSocket) {
- this.debug(
- `New connection, account:${account.id}, device:${account.deviceId}`
- );
+ debug(`New connection, account:${account.id}, device:${account.deviceId}`);
this.account = account;
this.socket = socket;
@@ -75,7 +74,7 @@ export class SocketConnection {
}
private async handleMessage(message: Message) {
- this.debug(
+ debug(
`Socket message, account:${this.account.id}, device:${this.account.deviceId}, type:${message.type}`
);
@@ -136,7 +135,7 @@ export class SocketConnection {
message: SynchronizerInputMessage,
user: SocketUser
): BaseSynchronizer<SynchronizerInput> | null {
- const cursor = BigInt(message.cursor);
+ const cursor = message.cursor;
if (message.input.type === 'users') {
return new UserSynchronizer(message.id, user.user, message.input, cursor);
} else if (message.input.type === 'collaborations') {
diff --git a/apps/server/src/services/socket-service.ts b/apps/server/src/services/socket-service.ts
index e326015c..810310bb 100644
--- a/apps/server/src/services/socket-service.ts
+++ b/apps/server/src/services/socket-service.ts
@@ -1,16 +1,10 @@
-import { WebSocketServer, WebSocket } from 'ws';
-import { createDebugger } from '@colanode/core';
+import { WebSocket } from 'ws';
-import { IncomingMessage, Server } from 'http';
-
-import { rateLimitService } from '@/services/rate-limit-service';
import { SocketConnection } from '@/services/socket-connection';
import { eventBus } from '@/lib/event-bus';
-import { parseToken, verifyToken } from '@/lib/tokens';
import { RequestAccount } from '@/types/api';
class SocketService {
- private readonly debug = createDebugger('server:service:socket');
private readonly connections: Map<string, SocketConnection> = new Map();
constructor() {
@@ -20,8 +14,9 @@ class SocketService {
if (connection) {
connection.close();
this.connections.delete(event.deviceId);
- return;
}
+
+ return;
}
for (const connection of this.connections.values()) {
@@ -30,81 +25,15 @@ class SocketService {
});
}
- public async init(server: Server) {
- this.debug('Initializing socket service');
-
- const wss = new WebSocketServer({
- noServer: true,
- });
-
- server.on('upgrade', async (request, socket, head) => {
- this.debug(
- `Upgrade request, url: ${request.url}, device: ${request.headers['device-id']}`
- );
-
- if (request.url !== '/client/v1/synapse') {
- this.debug(`Invalid upgrade request ${request.url}`);
- socket.destroy();
- return;
- }
-
- const token = request.headers['authorization'];
- if (!token) {
- this.debug(`Invalid upgrade request, no token`);
- socket.destroy();
- return;
- }
-
- const tokenData = parseToken(token);
- if (!tokenData) {
- this.debug(`Invalid upgrade request, invalid token`);
- socket.destroy();
- return;
- }
+ public addConnection(account: RequestAccount, socket: WebSocket) {
+ const existingConnection = this.connections.get(account.deviceId);
+ if (existingConnection) {
+ existingConnection.close();
+ this.connections.delete(account.deviceId);
+ }
- const isRateLimited = await rateLimitService.isDeviceSocketRateLimitted(
- tokenData.deviceId
- );
-
- if (isRateLimited) {
- this.debug(`Rate limited device ${tokenData.deviceId}`);
- socket.destroy();
- return;
- }
-
- const result = await verifyToken(tokenData);
- if (!result.authenticated) {
- this.debug(`Invalid upgrade request, invalid token`);
- socket.destroy();
- return;
- }
-
- const account = result.account;
- wss.handleUpgrade(request, socket, head, (ws) => {
- this.debug(`Upgrading connection for device ${tokenData.deviceId}`);
- wss.emit('connection', ws, request, account);
- });
- });
-
- wss.on(
- 'connection',
- async (
- socket: WebSocket,
- _: IncomingMessage,
- account: RequestAccount
- ) => {
- socket.on('close', () => {
- this.debug(`Closing connection for device ${account.deviceId}`);
- const connection = this.connections.get(account.deviceId);
- if (connection) {
- this.connections.delete(account.deviceId);
- }
- });
-
- const connection = new SocketConnection(account, socket);
- this.connections.set(account.deviceId, connection);
- }
- );
+ const connection = new SocketConnection(account, socket);
+ this.connections.set(account.deviceId, connection);
}
}
diff --git a/apps/server/src/synchronizers/base.ts b/apps/server/src/synchronizers/base.ts
index 1df110b0..2827b1d5 100644
--- a/apps/server/src/synchronizers/base.ts
+++ b/apps/server/src/synchronizers/base.ts
@@ -9,11 +9,11 @@ export abstract class BaseSynchronizer<T extends SynchronizerInput> {
public readonly id: string;
public readonly user: ConnectedUser;
public readonly input: T;
- public readonly cursor: bigint;
+ public readonly cursor: string;
protected status: SynchronizerStatus = 'pending';
- constructor(id: string, user: ConnectedUser, input: T, cursor: bigint) {
+ constructor(id: string, user: ConnectedUser, input: T, cursor: string) {
this.id = id;
this.user = user;
this.input = input;
diff --git a/package-lock.json b/package-lock.json
index 5e74d51c..b8c59c56 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -182,6 +182,8 @@
"@aws-sdk/s3-request-presigner": "^3.787.0",
"@colanode/core": "*",
"@colanode/crdt": "*",
+ "@fastify/multipart": "^9.0.3",
+ "@fastify/websocket": "^11.0.2",
"@langchain/core": "^0.3.46",
"@langchain/google-genai": "^0.2.4",
"@langchain/langgraph": "^0.2.65",
@@ -189,26 +191,21 @@
"@node-rs/argon2": "^2.0.2",
"axios": "^1.8.4",
"bullmq": "^5.49.2",
- "cors": "^2.8.5",
"diff": "^7.0.0",
"dotenv": "^16.5.0",
- "express": "^5.1.0",
+ "fastify": "^5.3.2",
+ "fastify-type-provider-zod": "^4.0.2",
"handlebars": "^4.7.8",
"js-sha256": "^0.11.0",
"kysely": "^0.28.1",
"langchain": "^0.3.23",
"langfuse-langchain": "^3.37.2",
- "multer": "^1.4.5-lts.2",
"nodemailer": "^6.10.1",
"pg": "^8.15.1",
"redis": "^4.7.0",
- "sharp": "^0.34.1",
- "ws": "^8.18.1"
+ "sharp": "^0.34.1"
},
"devDependencies": {
- "@types/cors": "^2.8.17",
- "@types/express": "^5.0.1",
- "@types/multer": "^1.4.12",
"@types/node": "^22.14.1",
"@types/nodemailer": "^6.4.17",
"@types/pg": "^8.11.13",
@@ -218,54 +215,6 @@
"tsx": "^4.19.2"
}
},
- "apps/server/node_modules/accepts": {
- "version": "2.0.0",
- "license": "MIT",
- "dependencies": {
- "mime-types": "^3.0.0",
- "negotiator": "^1.0.0"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
- "apps/server/node_modules/body-parser": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz",
- "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==",
- "license": "MIT",
- "dependencies": {
- "bytes": "^3.1.2",
- "content-type": "^1.0.5",
- "debug": "^4.4.0",
- "http-errors": "^2.0.0",
- "iconv-lite": "^0.6.3",
- "on-finished": "^2.4.1",
- "qs": "^6.14.0",
- "raw-body": "^3.0.0",
- "type-is": "^2.0.0"
- },
- "engines": {
- "node": ">=18"
- }
- },
- "apps/server/node_modules/content-disposition": {
- "version": "1.0.0",
- "license": "MIT",
- "dependencies": {
- "safe-buffer": "5.2.1"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
- "apps/server/node_modules/cookie-signature": {
- "version": "1.2.2",
- "license": "MIT",
- "engines": {
- "node": ">=6.6.0"
- }
- },
"apps/server/node_modules/diff": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz",
@@ -275,212 +224,6 @@
"node": ">=0.3.1"
}
},
- "apps/server/node_modules/express": {
- "version": "5.1.0",
- "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
- "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
- "license": "MIT",
- "dependencies": {
- "accepts": "^2.0.0",
- "body-parser": "^2.2.0",
- "content-disposition": "^1.0.0",
- "content-type": "^1.0.5",
- "cookie": "^0.7.1",
- "cookie-signature": "^1.2.1",
- "debug": "^4.4.0",
- "encodeurl": "^2.0.0",
- "escape-html": "^1.0.3",
- "etag": "^1.8.1",
- "finalhandler": "^2.1.0",
- "fresh": "^2.0.0",
- "http-errors": "^2.0.0",
- "merge-descriptors": "^2.0.0",
- "mime-types": "^3.0.0",
- "on-finished": "^2.4.1",
- "once": "^1.4.0",
- "parseurl": "^1.3.3",
- "proxy-addr": "^2.0.7",
- "qs": "^6.14.0",
- "range-parser": "^1.2.1",
- "router": "^2.2.0",
- "send": "^1.1.0",
- "serve-static": "^2.2.0",
- "statuses": "^2.0.1",
- "type-is": "^2.0.1",
- "vary": "^1.1.2"
- },
- "engines": {
- "node": ">= 18"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "apps/server/node_modules/finalhandler": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz",
- "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==",
- "license": "MIT",
- "dependencies": {
- "debug": "^4.4.0",
- "encodeurl": "^2.0.0",
- "escape-html": "^1.0.3",
- "on-finished": "^2.4.1",
- "parseurl": "^1.3.3",
- "statuses": "^2.0.1"
- },
- "engines": {
- "node": ">= 0.8"
- }
- },
- "apps/server/node_modules/fresh": {
- "version": "2.0.0",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "apps/server/node_modules/iconv-lite": {
- "version": "0.6.3",
- "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
- "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
- "license": "MIT",
- "dependencies": {
- "safer-buffer": ">= 2.1.2 < 3.0.0"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "apps/server/node_modules/media-typer": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
- "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "apps/server/node_modules/merge-descriptors": {
- "version": "2.0.0",
- "license": "MIT",
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "apps/server/node_modules/mime-db": {
- "version": "1.54.0",
- "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
- "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "apps/server/node_modules/mime-types": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz",
- "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==",
- "license": "MIT",
- "dependencies": {
- "mime-db": "^1.54.0"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
- "apps/server/node_modules/negotiator": {
- "version": "1.0.0",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "apps/server/node_modules/qs": {
- "version": "6.14.0",
- "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
- "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
- "license": "BSD-3-Clause",
- "dependencies": {
- "side-channel": "^1.1.0"
- },
- "engines": {
- "node": ">=0.6"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "apps/server/node_modules/raw-body": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz",
- "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==",
- "license": "MIT",
- "dependencies": {
- "bytes": "3.1.2",
- "http-errors": "2.0.0",
- "iconv-lite": "0.6.3",
- "unpipe": "1.0.0"
- },
- "engines": {
- "node": ">= 0.8"
- }
- },
- "apps/server/node_modules/send": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz",
- "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==",
- "license": "MIT",
- "dependencies": {
- "debug": "^4.3.5",
- "encodeurl": "^2.0.0",
- "escape-html": "^1.0.3",
- "etag": "^1.8.1",
- "fresh": "^2.0.0",
- "http-errors": "^2.0.0",
- "mime-types": "^3.0.1",
- "ms": "^2.1.3",
- "on-finished": "^2.4.1",
- "range-parser": "^1.2.1",
- "statuses": "^2.0.1"
- },
- "engines": {
- "node": ">= 18"
- }
- },
- "apps/server/node_modules/serve-static": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz",
- "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==",
- "license": "MIT",
- "dependencies": {
- "encodeurl": "^2.0.0",
- "escape-html": "^1.0.3",
- "parseurl": "^1.3.3",
- "send": "^1.2.0"
- },
- "engines": {
- "node": ">= 18"
- }
- },
- "apps/server/node_modules/type-is": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
- "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
- "license": "MIT",
- "dependencies": {
- "content-type": "^1.0.5",
- "media-typer": "^1.1.0",
- "mime-types": "^3.0.0"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
"node_modules/@alloc/quick-lru": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",
@@ -2858,6 +2601,210 @@
"npm": ">=9.0.0"
}
},
+ "node_modules/@fastify/ajv-compiler": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.2.tgz",
+ "integrity": "sha512-Rkiu/8wIjpsf46Rr+Fitd3HRP+VsxUFDDeag0hs9L0ksfnwx2g7SPQQTFL0E8Qv+rfXzQOxBJnjUB9ITUDjfWQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^8.12.0",
+ "ajv-formats": "^3.0.1",
+ "fast-uri": "^3.0.0"
+ }
+ },
+ "node_modules/@fastify/ajv-compiler/node_modules/ajv": {
+ "version": "8.17.1",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
+ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/@fastify/ajv-compiler/node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
+ "node_modules/@fastify/busboy": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.1.1.tgz",
+ "integrity": "sha512-5DGmA8FTdB2XbDeEwc/5ZXBl6UbBAyBOOLlPuBnZ/N1SwdH9Ii+cOX3tBROlDgcTXxjOYnLMVoKk9+FXAw0CJw==",
+ "license": "MIT"
+ },
+ "node_modules/@fastify/deepmerge": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@fastify/deepmerge/-/deepmerge-2.0.2.tgz",
+ "integrity": "sha512-3wuLdX5iiiYeZWP6bQrjqhrcvBIf0NHbQH1Ur1WbHvoiuTYUEItgygea3zs8aHpiitn0lOB8gX20u1qO+FDm7Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/@fastify/error": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.1.0.tgz",
+ "integrity": "sha512-KeFcciOr1eo/YvIXHP65S94jfEEqn1RxTRBT1aJaHxY5FK0/GDXYozsQMMWlZoHgi8i0s+YtrLsgj/JkUUjSkQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/@fastify/fast-json-stringify-compiler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-5.0.3.tgz",
+ "integrity": "sha512-uik7yYHkLr6fxd8hJSZ8c+xF4WafPK+XzneQDPU+D10r5X19GW8lJcom2YijX2+qtFF1ENJlHXKFM9ouXNJYgQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "fast-json-stringify": "^6.0.0"
+ }
+ },
+ "node_modules/@fastify/forwarded": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.0.0.tgz",
+ "integrity": "sha512-kJExsp4JCms7ipzg7SJ3y8DwmePaELHxKYtg+tZow+k0znUTf3cb+npgyqm8+ATZOdmfgfydIebPDWM172wfyA==",
+ "license": "MIT"
+ },
+ "node_modules/@fastify/merge-json-schemas": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.2.1.tgz",
+ "integrity": "sha512-OA3KGBCy6KtIvLf8DINC5880o5iBlDX4SxzLQS8HorJAbqluzLRn80UXU0bxZn7UOFhFgpRJDasfwn9nG4FG4A==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "dequal": "^2.0.3"
+ }
+ },
+ "node_modules/@fastify/multipart": {
+ "version": "9.0.3",
+ "resolved": "https://registry.npmjs.org/@fastify/multipart/-/multipart-9.0.3.tgz",
+ "integrity": "sha512-pJogxQCrT12/6I5Fh6jr3narwcymA0pv4B0jbC7c6Bl9wnrxomEUnV0d26w6gUls7gSXmhG8JGRMmHFIPsxt1g==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/busboy": "^3.0.0",
+ "@fastify/deepmerge": "^2.0.0",
+ "@fastify/error": "^4.0.0",
+ "fastify-plugin": "^5.0.0",
+ "secure-json-parse": "^3.0.0"
+ }
+ },
+ "node_modules/@fastify/multipart/node_modules/secure-json-parse": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-3.0.2.tgz",
+ "integrity": "sha512-H6nS2o8bWfpFEV6U38sOSjS7bTbdgbCGU9wEM6W14P5H0QOsz94KCusifV44GpHDTu2nqZbuDNhTzu+mjDSw1w==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@fastify/proxy-addr": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.0.0.tgz",
+ "integrity": "sha512-37qVVA1qZ5sgH7KpHkkC4z9SK6StIsIcOmpjvMPXNb3vx2GQxhZocogVYbr2PbbeLCQxYIPDok307xEvRZOzGA==",
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/forwarded": "^3.0.0",
+ "ipaddr.js": "^2.1.0"
+ }
+ },
+ "node_modules/@fastify/proxy-addr/node_modules/ipaddr.js": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.2.0.tgz",
+ "integrity": "sha512-Ag3wB2o37wslZS19hZqorUnrnzSkpOVy+IiiDEiTqNubEYpYuHWIf6K4psgN2ZWKExS4xhVCrRVfb/wfW8fWJA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@fastify/websocket": {
+ "version": "11.0.2",
+ "resolved": "https://registry.npmjs.org/@fastify/websocket/-/websocket-11.0.2.tgz",
+ "integrity": "sha512-1oyJkNSZNJGjo/A5fXvlpEcm1kTBD91nRAN9lA7RNVsVNsyC5DuhOXdNL9/4UawVe7SKvzPT/QVI4RdtE9ylnA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "duplexify": "^4.1.3",
+ "fastify-plugin": "^5.0.0",
+ "ws": "^8.16.0"
+ }
+ },
"node_modules/@floating-ui/core": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.6.8.tgz",
@@ -6910,17 +6857,6 @@
"@types/node": "*"
}
},
- "node_modules/@types/body-parser": {
- "version": "1.19.5",
- "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz",
- "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/connect": "*",
- "@types/node": "*"
- }
- },
"node_modules/@types/cacheable-request": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",
@@ -6934,26 +6870,6 @@
"@types/responselike": "^1.0.0"
}
},
- "node_modules/@types/connect": {
- "version": "3.4.38",
- "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
- "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/node": "*"
- }
- },
- "node_modules/@types/cors": {
- "version": "2.8.17",
- "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz",
- "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/node": "*"
- }
- },
"node_modules/@types/debug": {
"version": "4.1.12",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",
@@ -6984,31 +6900,6 @@
"integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
"license": "MIT"
},
- "node_modules/@types/express": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.1.tgz",
- "integrity": "sha512-UZUw8vjpWFXuDnjFTh7/5c2TWDlQqeXHi6hcN7F2XSVT5P+WmUnnbFS3KA6Jnc6IsEqI2qCVu2bK0R0J4A8ZQQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/body-parser": "*",
- "@types/express-serve-static-core": "^5.0.0",
- "@types/serve-static": "*"
- }
- },
- "node_modules/@types/express-serve-static-core": {
- "version": "5.0.2",
- "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.0.2.tgz",
- "integrity": "sha512-vluaspfvWEtE4vcSDlKRNer52DvOGrB2xv6diXy6UKyKW0lqZiWHGNApSyxOv+8DE5Z27IzVvE7hNkxg7EXIcg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/node": "*",
- "@types/qs": "*",
- "@types/range-parser": "*",
- "@types/send": "*"
- }
- },
"node_modules/@types/fs-extra": {
"version": "9.0.13",
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-9.0.13.tgz",
@@ -7048,13 +6939,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/http-errors": {
- "version": "2.0.4",
- "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz",
- "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/is-hotkey": {
"version": "0.1.10",
"resolved": "https://registry.npmjs.org/@types/is-hotkey/-/is-hotkey-0.1.10.tgz",
@@ -7127,13 +7011,6 @@
"license": "MIT",
"peer": true
},
- "node_modules/@types/mime": {
- "version": "1.3.5",
- "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz",
- "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/mime-types": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@types/mime-types/-/mime-types-2.1.4.tgz",
@@ -7156,16 +7033,6 @@
"devOptional": true,
"license": "MIT"
},
- "node_modules/@types/multer": {
- "version": "1.4.12",
- "resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.12.tgz",
- "integrity": "sha512-pQ2hoqvXiJt2FP9WQVLPRO+AmiIm/ZYkavPlIQnx282u4ZrVdztx0pkh3jjpQt0Kz+YI0YhSG264y08UJKoUQg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/express": "*"
- }
- },
"node_modules/@types/node": {
"version": "22.14.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.14.1.tgz",
@@ -7214,20 +7081,6 @@
"devOptional": true,
"license": "MIT"
},
- "node_modules/@types/qs": {
- "version": "6.9.17",
- "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.17.tgz",
- "integrity": "sha512-rX4/bPcfmvxHDv0XjfJELTTr+iB+tn032nPILqHm5wbthUUUuVtNGGqzhya9XUxjTP8Fpr0qYgSZZKxGY++svQ==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/@types/range-parser": {
- "version": "1.2.7",
- "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
- "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/react": {
"version": "18.3.20",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
@@ -7272,29 +7125,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/send": {
- "version": "0.17.4",
- "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz",
- "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/mime": "^1",
- "@types/node": "*"
- }
- },
- "node_modules/@types/serve-static": {
- "version": "1.15.7",
- "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz",
- "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/http-errors": "*",
- "@types/node": "*",
- "@types/send": "*"
- }
- },
"node_modules/@types/unist": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
@@ -7669,6 +7499,12 @@
"node": ">=6.5"
}
},
+ "node_modules/abstract-logging": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
+ "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==",
+ "license": "MIT"
+ },
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@@ -7784,6 +7620,45 @@
"url": "https://github.com/sponsors/epoberezkin"
}
},
+ "node_modules/ajv-formats": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "ajv": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/ajv-formats/node_modules/ajv": {
+ "version": "8.17.1",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
+ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/ajv-formats/node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
"node_modules/ansi-escapes": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-5.0.0.tgz",
@@ -7886,12 +7761,6 @@
"node": ">=8.5"
}
},
- "node_modules/append-field": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
- "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
- "license": "MIT"
- },
"node_modules/arg": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
@@ -8181,6 +8050,15 @@
"node": ">= 4.0.0"
}
},
+ "node_modules/atomic-sleep": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
+ "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
"node_modules/author-regex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/author-regex/-/author-regex-1.0.0.tgz",
@@ -8245,6 +8123,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/avvio": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/avvio/-/avvio-9.1.0.tgz",
+ "integrity": "sha512-fYASnYi600CsH/j9EQov7lECAniYiBFiiAtBNuZYLA2leLe9qOvZzqYHFjtIj6gD2VMoMLP14834LFWvr4IfDw==",
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/error": "^4.0.0",
+ "fastq": "^1.17.1"
+ }
+ },
"node_modules/axios": {
"version": "1.8.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz",
@@ -8517,6 +8405,7 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+ "dev": true,
"license": "MIT"
},
"node_modules/bufferutil": {
@@ -8563,21 +8452,11 @@
"esbuild": ">=0.18"
}
},
- "node_modules/busboy": {
- "version": "1.6.0",
- "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
- "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
- "dependencies": {
- "streamsearch": "^1.1.0"
- },
- "engines": {
- "node": ">=10.16.0"
- }
- },
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.8"
@@ -8737,6 +8616,7 @@
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
@@ -9182,57 +9062,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/concat-stream": {
- "version": "1.6.2",
- "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
- "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
- "engines": [
- "node >= 0.8"
- ],
- "license": "MIT",
- "dependencies": {
- "buffer-from": "^1.0.0",
- "inherits": "^2.0.3",
- "readable-stream": "^2.2.2",
- "typedarray": "^0.0.6"
- }
- },
- "node_modules/concat-stream/node_modules/isarray": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
- "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
- "license": "MIT"
- },
- "node_modules/concat-stream/node_modules/readable-stream": {
- "version": "2.3.8",
- "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
- "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
- "license": "MIT",
- "dependencies": {
- "core-util-is": "~1.0.0",
- "inherits": "~2.0.3",
- "isarray": "~1.0.0",
- "process-nextick-args": "~2.0.0",
- "safe-buffer": "~5.1.1",
- "string_decoder": "~1.1.1",
- "util-deprecate": "~1.0.1"
- }
- },
- "node_modules/concat-stream/node_modules/safe-buffer": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
- "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
- "license": "MIT"
- },
- "node_modules/concat-stream/node_modules/string_decoder": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
- "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
- "license": "MIT",
- "dependencies": {
- "safe-buffer": "~5.1.0"
- }
- },
"node_modules/consola": {
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/consola/-/consola-3.4.1.tgz",
@@ -9269,6 +9098,7 @@
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
@@ -9278,6 +9108,7 @@
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",
"integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
@@ -9290,25 +9121,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/core-util-is": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
- "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
- "license": "MIT"
- },
- "node_modules/cors": {
- "version": "2.8.5",
- "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
- "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
- "license": "MIT",
- "dependencies": {
- "object-assign": "^4",
- "vary": "^1"
- },
- "engines": {
- "node": ">= 0.10"
- }
- },
"node_modules/create-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
@@ -9632,6 +9444,7 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.8"
@@ -9820,6 +9633,18 @@
"node": ">= 0.4"
}
},
+ "node_modules/duplexify": {
+ "version": "4.1.3",
+ "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz",
+ "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==",
+ "license": "MIT",
+ "dependencies": {
+ "end-of-stream": "^1.4.1",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1",
+ "stream-shift": "^1.0.2"
+ }
+ },
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
@@ -9830,6 +9655,7 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+ "dev": true,
"license": "MIT"
},
"node_modules/electron": {
@@ -10468,6 +10294,7 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.8"
@@ -10776,6 +10603,7 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "dev": true,
"license": "MIT"
},
"node_modules/escape-string-regexp": {
@@ -11230,6 +11058,7 @@
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
@@ -11507,6 +11336,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/fast-decode-uri-component": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz",
+ "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==",
+ "license": "MIT"
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -11548,6 +11383,52 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/fast-json-stringify": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-6.0.1.tgz",
+ "integrity": "sha512-s7SJE83QKBZwg54dIbD5rCtzOBVD43V1ReWXXYqBgwCwHLYAAT0RQc/FmrQglXqWPpz6omtryJQOau5jI4Nrvg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/merge-json-schemas": "^0.2.0",
+ "ajv": "^8.12.0",
+ "ajv-formats": "^3.0.1",
+ "fast-uri": "^3.0.0",
+ "json-schema-ref-resolver": "^2.0.0",
+ "rfdc": "^1.2.0"
+ }
+ },
+ "node_modules/fast-json-stringify/node_modules/ajv": {
+ "version": "8.17.1",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
+ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/fast-json-stringify/node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
"node_modules/fast-levenshtein": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
@@ -11555,6 +11436,40 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/fast-querystring": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz",
+ "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-decode-uri-component": "^1.0.1"
+ }
+ },
+ "node_modules/fast-redact": {
+ "version": "3.5.0",
+ "resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-3.5.0.tgz",
+ "integrity": "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/fast-uri": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.6.tgz",
+ "integrity": "sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
"node_modules/fast-xml-parser": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz",
@@ -11577,6 +11492,59 @@
"fxparser": "src/cli/cli.js"
}
},
+ "node_modules/fastify": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.3.2.tgz",
+ "integrity": "sha512-AIPqBgtqBAwkOkrnwesEE+dOyU30dQ4kh7udxeGVR05CRGwubZx+p2H8P0C4cRnQT0+EPK4VGea2DTL2RtWttg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/ajv-compiler": "^4.0.0",
+ "@fastify/error": "^4.0.0",
+ "@fastify/fast-json-stringify-compiler": "^5.0.0",
+ "@fastify/proxy-addr": "^5.0.0",
+ "abstract-logging": "^2.0.1",
+ "avvio": "^9.0.0",
+ "fast-json-stringify": "^6.0.0",
+ "find-my-way": "^9.0.0",
+ "light-my-request": "^6.0.0",
+ "pino": "^9.0.0",
+ "process-warning": "^5.0.0",
+ "rfdc": "^1.3.1",
+ "secure-json-parse": "^4.0.0",
+ "semver": "^7.6.0",
+ "toad-cache": "^3.7.0"
+ }
+ },
+ "node_modules/fastify-plugin": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-5.0.1.tgz",
+ "integrity": "sha512-HCxs+YnRaWzCl+cWRYFnHmeRFyR5GVnJTAaCJQiYzQSDwK9MgJdyAsuL3nh0EWRCYMgQ5MeziymvmAhUHYHDUQ==",
+ "license": "MIT"
+ },
+ "node_modules/fastify-type-provider-zod": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/fastify-type-provider-zod/-/fastify-type-provider-zod-4.0.2.tgz",
+ "integrity": "sha512-FDRzSL3ZuoZ+4YDevR1YOinmDKkxOdy3QB9dDR845sK+bQvDroPKhHAXLEAOObDxL7SMA0OZN/A4osrNBTdDTQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@fastify/error": "^4.0.0",
+ "zod-to-json-schema": "^3.23.3"
+ },
+ "peerDependencies": {
+ "fastify": "^5.0.0",
+ "zod": "^3.14.2"
+ }
+ },
"node_modules/fastq": {
"version": "1.18.0",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.18.0.tgz",
@@ -11723,6 +11691,20 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/find-my-way": {
+ "version": "9.3.0",
+ "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.3.0.tgz",
+ "integrity": "sha512-eRoFWQw+Yv2tuYlK2pjFS2jGXSxSppAs3hSQjfxVKxM5amECzIgYYc1FEI8ZmhSh/Ig+FrKEz43NLRKJjYCZVg==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-querystring": "^1.0.0",
+ "safe-regex2": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/find-up": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
@@ -11895,6 +11877,7 @@
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
@@ -12604,6 +12587,7 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"depd": "2.0.0",
@@ -12878,6 +12862,7 @@
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.10"
@@ -13203,12 +13188,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/is-promise": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
- "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
- "license": "MIT"
- },
"node_modules/is-property": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
@@ -13532,6 +13511,25 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/json-schema-ref-resolver": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-2.0.1.tgz",
+ "integrity": "sha512-HG0SIB9X4J8bwbxCbnd5FfPEbcXAJYTi1pBJeP/QPON+w8ovSME8iRG+ElHNxZNX2Qh6eYn1GdzJFS4cDFfx0Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "dequal": "^2.0.3"
+ }
+ },
"node_modules/json-schema-traverse": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
@@ -13854,6 +13852,52 @@
"url": "https://github.com/sponsors/dmonad"
}
},
+ "node_modules/light-my-request": {
+ "version": "6.6.0",
+ "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz",
+ "integrity": "sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "cookie": "^1.0.1",
+ "process-warning": "^4.0.0",
+ "set-cookie-parser": "^2.6.0"
+ }
+ },
+ "node_modules/light-my-request/node_modules/cookie": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
+ "integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/light-my-request/node_modules/process-warning": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.1.tgz",
+ "integrity": "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/lilconfig": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
@@ -14255,6 +14299,7 @@
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
@@ -14548,36 +14593,6 @@
"@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3"
}
},
- "node_modules/multer": {
- "version": "1.4.5-lts.2",
- "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz",
- "integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==",
- "license": "MIT",
- "dependencies": {
- "append-field": "^1.0.0",
- "busboy": "^1.0.0",
- "concat-stream": "^1.5.2",
- "mkdirp": "^0.5.4",
- "object-assign": "^4.1.1",
- "type-is": "^1.6.4",
- "xtend": "^4.0.0"
- },
- "engines": {
- "node": ">= 6.0.0"
- }
- },
- "node_modules/multer/node_modules/mkdirp": {
- "version": "0.5.6",
- "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
- "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
- "license": "MIT",
- "dependencies": {
- "minimist": "^1.2.6"
- },
- "bin": {
- "mkdirp": "bin/cmd.js"
- }
- },
"node_modules/murmur-32": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/murmur-32/-/murmur-32-0.2.0.tgz",
@@ -14974,6 +14989,7 @@
"version": "1.13.3",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz",
"integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -15089,10 +15105,20 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/on-exit-leak-free": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
+ "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
@@ -15463,6 +15489,7 @@
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.8"
@@ -15775,6 +15802,59 @@
"node": ">=0.10.0"
}
},
+ "node_modules/pino": {
+ "version": "9.6.0",
+ "resolved": "https://registry.npmjs.org/pino/-/pino-9.6.0.tgz",
+ "integrity": "sha512-i85pKRCt4qMjZ1+L7sy2Ag4t1atFcdbEt76+7iRJn1g2BvsnRMGu9p8pivl9fs63M2kF/A0OacFZhTub+m/qMg==",
+ "license": "MIT",
+ "dependencies": {
+ "atomic-sleep": "^1.0.0",
+ "fast-redact": "^3.1.1",
+ "on-exit-leak-free": "^2.1.0",
+ "pino-abstract-transport": "^2.0.0",
+ "pino-std-serializers": "^7.0.0",
+ "process-warning": "^4.0.0",
+ "quick-format-unescaped": "^4.0.3",
+ "real-require": "^0.2.0",
+ "safe-stable-stringify": "^2.3.1",
+ "sonic-boom": "^4.0.1",
+ "thread-stream": "^3.0.0"
+ },
+ "bin": {
+ "pino": "bin.js"
+ }
+ },
+ "node_modules/pino-abstract-transport": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz",
+ "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==",
+ "license": "MIT",
+ "dependencies": {
+ "split2": "^4.0.0"
+ }
+ },
+ "node_modules/pino-std-serializers": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.0.0.tgz",
+ "integrity": "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA==",
+ "license": "MIT"
+ },
+ "node_modules/pino/node_modules/process-warning": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.1.tgz",
+ "integrity": "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/pirates": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz",
@@ -16090,10 +16170,20 @@
"node": "^12.13.0 || ^14.15.0 || >=16.0.0"
}
},
- "node_modules/process-nextick-args": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
- "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
+ "node_modules/process-warning": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",
+ "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
"license": "MIT"
},
"node_modules/progress": {
@@ -16356,6 +16446,7 @@
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
@@ -16444,6 +16535,12 @@
],
"license": "MIT"
},
+ "node_modules/quick-format-unescaped": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
+ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",
+ "license": "MIT"
+ },
"node_modules/quick-lru": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
@@ -16473,6 +16570,7 @@
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.6"
@@ -16862,6 +16960,15 @@
"node": ">=8.10.0"
}
},
+ "node_modules/real-require": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
+ "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12.13.0"
+ }
+ },
"node_modules/rechoir": {
"version": "0.8.0",
"resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz",
@@ -16991,6 +17098,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/resedit": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/resedit/-/resedit-2.0.3.tgz",
@@ -17086,6 +17202,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/ret": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz",
+ "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/retry": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
@@ -17110,7 +17235,6 @@
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
"integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
- "dev": true,
"license": "MIT"
},
"node_modules/rimraf": {
@@ -17195,31 +17319,6 @@
"license": "MIT",
"peer": true
},
- "node_modules/router": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
- "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
- "license": "MIT",
- "dependencies": {
- "debug": "^4.4.0",
- "depd": "^2.0.0",
- "is-promise": "^4.0.0",
- "parseurl": "^1.3.3",
- "path-to-regexp": "^8.0.0"
- },
- "engines": {
- "node": ">= 18"
- }
- },
- "node_modules/router/node_modules/path-to-regexp": {
- "version": "8.2.0",
- "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz",
- "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==",
- "license": "MIT",
- "engines": {
- "node": ">=16"
- }
- },
"node_modules/run-parallel": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
@@ -17301,10 +17400,39 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/safe-regex2": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.0.0.tgz",
+ "integrity": "sha512-YwJwe5a51WlK7KbOJREPdjNrpViQBI3p4T50lfwPuDhZnE3XGVTlGvi+aolc5+RvxDD6bnUmjVsU9n1eboLUYw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "ret": "~0.5.0"
+ }
+ },
+ "node_modules/safe-stable-stringify": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
+ "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "devOptional": true,
"license": "MIT"
},
"node_modules/scheduler": {
@@ -17316,6 +17444,22 @@
"loose-envify": "^1.1.0"
}
},
+ "node_modules/secure-json-parse": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.0.0.tgz",
+ "integrity": "sha512-dxtLJO6sc35jWidmLxo7ij+Eg48PM/kleBsxpC8QJE0qJICe+KawkDQmvCMZUr9u7WKVHgMW6vy3fQ7zMiFZMA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
"node_modules/semver": {
"version": "7.7.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz",
@@ -17435,6 +17579,12 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/set-cookie-parser": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz",
+ "integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==",
+ "license": "MIT"
+ },
"node_modules/set-function-length": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
@@ -17473,6 +17623,7 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+ "dev": true,
"license": "ISC"
},
"node_modules/sharp": {
@@ -17540,6 +17691,7 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
@@ -17559,6 +17711,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
@@ -17575,6 +17728,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
@@ -17593,6 +17747,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
@@ -17771,6 +17926,15 @@
"node": ">= 10"
}
},
+ "node_modules/sonic-boom": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz",
+ "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==",
+ "license": "MIT",
+ "dependencies": {
+ "atomic-sleep": "^1.0.0"
+ }
+ },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
@@ -17881,6 +18045,7 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.8"
@@ -17903,13 +18068,11 @@
"node": ">= 0.10.0"
}
},
- "node_modules/streamsearch": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
- "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
- "engines": {
- "node": ">=10.0.0"
- }
+ "node_modules/stream-shift": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz",
+ "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==",
+ "license": "MIT"
},
"node_modules/string_decoder": {
"version": "1.3.0",
@@ -18477,6 +18640,15 @@
"node": ">=0.8"
}
},
+ "node_modules/thread-stream": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
+ "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==",
+ "license": "MIT",
+ "dependencies": {
+ "real-require": "^0.2.0"
+ }
+ },
"node_modules/tiny-each-async": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/tiny-each-async/-/tiny-each-async-2.0.3.tgz",
@@ -18637,10 +18809,20 @@
"node": ">=8.0"
}
},
+ "node_modules/toad-cache": {
+ "version": "3.7.0",
+ "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.0.tgz",
+ "integrity": "sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.6"
@@ -19124,6 +19306,7 @@
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
@@ -19211,12 +19394,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/typedarray": {
- "version": "0.0.6",
- "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
- "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
- "license": "MIT"
- },
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
@@ -19350,6 +19527,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.8"
@@ -19538,6 +19716,7 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.8"
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 56d5acbd..ff31d5b0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -35,3 +35,4 @@ export * from './lib/debugger';
export * from './types/crdt';
export * from './lib/mentions';
export * from './types/mentions';
+export * from './types/avatars';
diff --git a/packages/core/src/types/accounts.ts b/packages/core/src/types/accounts.ts
index fdf04058..ee94f507 100644
--- a/packages/core/src/types/accounts.ts
+++ b/packages/core/src/types/accounts.ts
@@ -1,57 +1,6 @@
-import { WorkspaceOutput } from './workspaces';
-
-export type GoogleLoginInput = {
- access_token: string;
- token_type: string;
- expires_in: number;
- platform: string;
- version: string;
-};
-
-export type EmailRegisterInput = {
- name: string;
- email: string;
- password: string;
- platform: string;
- version: string;
-};
-
-export type EmailLoginInput = {
- email: string;
- password: string;
- platform: string;
- version: string;
-};
-
-export type GoogleUserInfo = {
- id: string;
- email: string;
- name: string;
- picture: string;
-};
-
-export type LoginOutput = LoginSuccessOutput | LoginVerifyOutput;
-
-export type LoginSuccessOutput = {
- type: 'success';
- account: AccountOutput;
- workspaces: WorkspaceOutput[];
- deviceId: string;
- token: string;
-};
-
-export type LoginVerifyOutput = {
- type: 'verify';
- id: string;
- expiresAt: Date;
-};
-
-export type AccountOutput = {
- id: string;
- name: string;
- email: string;
- avatar?: string | null;
-};
+import { z } from 'zod';
+
+import { workspaceOutputSchema } from './workspaces';
export enum AccountStatus {
Pending = 0,
@@ -59,54 +8,156 @@ export enum AccountStatus {
Unverified = 2,
}
-export type AccountUpdateInput = {
- name: string;
- avatar?: string | null;
-};
-
-export type AccountUpdateOutput = {
- id: string;
- name: string;
- avatar?: string | null;
-};
-
-export type AccountSyncInput = {
- platform: string;
- version: string;
-};
-
-export type AccountSyncOutput = {
- account: AccountOutput;
- workspaces: WorkspaceOutput[];
- token?: string;
-};
-
-export type EmailVerifyInput = {
- id: string;
- otp: string;
- platform: string;
- version: string;
-};
-
-export type EmailPasswordResetInitInput = {
- email: string;
- platform: string;
- version: string;
-};
-
-export type EmailPasswordResetCompleteInput = {
- id: string;
- otp: string;
- password: string;
- platform: string;
- version: string;
-};
-
-export type EmailPasswordResetInitOutput = {
- id: string;
- expiresAt: Date;
-};
-
-export type EmailPasswordResetCompleteOutput = {
- success: boolean;
-};
+export const accountOutputSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ email: z.string().email(),
+ avatar: z.string().optional().nullable(),
+});
+
+export type AccountOutput = z.infer<typeof accountOutputSchema>;
+
+export const accountUpdateInputSchema = z.object({
+ name: z.string(),
+ avatar: z.string().nullable().optional(),
+});
+
+export type AccountUpdateInput = z.infer<typeof accountUpdateInputSchema>;
+
+export const accountUpdateOutputSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ avatar: z.string().nullable().optional(),
+});
+
+export type AccountUpdateOutput = z.infer<typeof accountUpdateOutputSchema>;
+
+export const accountSyncInputSchema = z.object({
+ platform: z.string(),
+ version: z.string(),
+});
+
+export type AccountSyncInput = z.infer<typeof accountSyncInputSchema>;
+
+export const emailRegisterInputSchema = z.object({
+ name: z.string({ required_error: 'Name is required' }),
+ email: z.string({ required_error: 'Email is required' }).email({
+ message: 'Invalid email address',
+ }),
+ password: z.string({ required_error: 'Password is required' }),
+ platform: z.string({ required_error: 'Platform is required' }),
+ version: z.string({ required_error: 'Version is required' }),
+});
+
+export type EmailRegisterInput = z.infer<typeof emailRegisterInputSchema>;
+
+export const emailLoginInputSchema = z.object({
+ email: z.string({ required_error: 'Email is required' }).email({
+ message: 'Invalid email address',
+ }),
+ password: z.string({ required_error: 'Password is required' }),
+ platform: z.string({ required_error: 'Platform is required' }),
+ version: z.string({ required_error: 'Version is required' }),
+});
+
+export type EmailLoginInput = z.infer<typeof emailLoginInputSchema>;
+
+export const loginSuccessOutputSchema = z.object({
+ type: z.literal('success'),
+ account: accountOutputSchema,
+ workspaces: z.array(workspaceOutputSchema),
+ deviceId: z.string(),
+ token: z.string(),
+});
+
+export type LoginSuccessOutput = z.infer<typeof loginSuccessOutputSchema>;
+
+export const loginVerifyOutputSchema = z.object({
+ type: z.literal('verify'),
+ id: z.string(),
+ expiresAt: z.date(),
+});
+
+export type LoginVerifyOutput = z.infer<typeof loginVerifyOutputSchema>;
+
+export const loginOutputSchema = z.discriminatedUnion('type', [
+ loginSuccessOutputSchema,
+ loginVerifyOutputSchema,
+]);
+
+export type LoginOutput = z.infer<typeof loginOutputSchema>;
+
+export const accountSyncOutputSchema = z.object({
+ account: accountOutputSchema,
+ workspaces: z.array(workspaceOutputSchema),
+ token: z.string().optional(),
+});
+
+export type AccountSyncOutput = z.infer<typeof accountSyncOutputSchema>;
+
+export const emailVerifyInputSchema = z.object({
+ id: z.string(),
+ otp: z.string(),
+ platform: z.string(),
+ version: z.string(),
+});
+
+export type EmailVerifyInput = z.infer<typeof emailVerifyInputSchema>;
+
+export const emailPasswordResetInitInputSchema = z.object({
+ email: z.string().email(),
+ platform: z.string(),
+ version: z.string(),
+});
+
+export type EmailPasswordResetInitInput = z.infer<
+ typeof emailPasswordResetInitInputSchema
+>;
+
+export const emailPasswordResetCompleteInputSchema = z.object({
+ id: z.string(),
+ otp: z.string(),
+ password: z.string(),
+ platform: z.string(),
+ version: z.string(),
+});
+
+export type EmailPasswordResetCompleteInput = z.infer<
+ typeof emailPasswordResetCompleteInputSchema
+>;
+
+export const emailPasswordResetInitOutputSchema = z.object({
+ id: z.string(),
+ expiresAt: z.date(),
+});
+
+export type EmailPasswordResetInitOutput = z.infer<
+ typeof emailPasswordResetInitOutputSchema
+>;
+
+export const emailPasswordResetCompleteOutputSchema = z.object({
+ success: z.boolean(),
+});
+
+export type EmailPasswordResetCompleteOutput = z.infer<
+ typeof emailPasswordResetCompleteOutputSchema
+>;
+
+export const googleLoginInputSchema = z.object({
+ access_token: z.string(),
+ token_type: z.string(),
+ expires_in: z.number(),
+ platform: z.string(),
+ version: z.string(),
+});
+
+export type GoogleLoginInput = z.infer<typeof googleLoginInputSchema>;
+
+export const googleUserInfoSchema = z.object({
+ id: z.string(),
+ email: z.string().email(),
+ name: z.string(),
+ picture: z.string(),
+});
+
+export type GoogleUserInfo = z.infer<typeof googleUserInfoSchema>;
diff --git a/packages/core/src/types/api.ts b/packages/core/src/types/api.ts
index d331122d..dc94e39c 100644
--- a/packages/core/src/types/api.ts
+++ b/packages/core/src/types/api.ts
@@ -1,7 +1,4 @@
-export type ApiErrorOutput = {
- message: string;
- code: ApiErrorCode;
-};
+import { z } from 'zod';
export enum ApiErrorCode {
AccountNotFound = 'account_not_found',
@@ -44,6 +41,7 @@ export enum ApiErrorCode {
TokenInvalid = 'token_invalid',
RootNotFound = 'root_not_found',
+ ValidationError = 'validation_error',
TooManyRequests = 'too_many_requests',
Unauthorized = 'unauthorized',
Forbidden = 'forbidden',
@@ -51,3 +49,10 @@ export enum ApiErrorCode {
BadRequest = 'bad_request',
Unknown = 'unknown',
}
+
+export const apiErrorOutputSchema = z.object({
+ message: z.string(),
+ code: z.nativeEnum(ApiErrorCode),
+});
+
+export type ApiErrorOutput = z.infer<typeof apiErrorOutputSchema>;
diff --git a/packages/core/src/types/avatars.ts b/packages/core/src/types/avatars.ts
new file mode 100644
index 00000000..9f549957
--- /dev/null
+++ b/packages/core/src/types/avatars.ts
@@ -0,0 +1,8 @@
+import { z } from 'zod';
+
+export const avatarUploadOutputSchema = z.object({
+ success: z.boolean(),
+ id: z.string(),
+});
+
+export type AvatarUploadOutput = z.infer<typeof avatarUploadOutputSchema>;
diff --git a/packages/core/src/types/files.ts b/packages/core/src/types/files.ts
index ca116d9d..a743c299 100644
--- a/packages/core/src/types/files.ts
+++ b/packages/core/src/types/files.ts
@@ -1,21 +1,45 @@
-export type CreateUploadInput = {
- fileId: string;
-};
+import { z } from 'zod';
-export type CreateUploadOutput = {
- url: string;
- uploadId: string;
-};
+export const createUploadInputSchema = z.object({
+ fileId: z.string(),
+});
-export type CreateDownloadOutput = {
- url: string;
-};
+export type CreateUploadInput = z.infer<typeof createUploadInputSchema>;
-export type CompleteUploadOutput = {
- success: boolean;
-};
+export const createUploadOutputSchema = z.object({
+ url: z.string(),
+ uploadId: z.string(),
+});
-export type FileSubtype = 'image' | 'video' | 'audio' | 'pdf' | 'other';
+export type CreateUploadOutput = z.infer<typeof createUploadOutputSchema>;
+
+export const createDownloadOutputSchema = z.object({
+ url: z.string(),
+});
+
+export type CreateDownloadOutput = z.infer<typeof createDownloadOutputSchema>;
+
+export const completeUploadInputSchema = z.object({
+ uploadId: z.string(),
+});
+
+export type CompleteUploadInput = z.infer<typeof completeUploadInputSchema>;
+
+export const completeUploadOutputSchema = z.object({
+ success: z.boolean(),
+});
+
+export type CompleteUploadOutput = z.infer<typeof completeUploadOutputSchema>;
+
+export const fileSubtypeSchema = z.enum([
+ 'image',
+ 'video',
+ 'audio',
+ 'pdf',
+ 'other',
+]);
+
+export type FileSubtype = z.infer<typeof fileSubtypeSchema>;
export enum FileStatus {
Pending = 0,
diff --git a/packages/core/src/types/mutations.ts b/packages/core/src/types/mutations.ts
index 4ad2139e..dc78e58f 100644
--- a/packages/core/src/types/mutations.ts
+++ b/packages/core/src/types/mutations.ts
@@ -1,124 +1,194 @@
-export type SyncMutationsInput = {
- mutations: Mutation[];
-};
-
-export type SyncMutationsOutput = {
- results: SyncMutationResult[];
-};
-
-export type SyncMutationStatus = 'success' | 'error';
-
-export type SyncMutationResult = {
- id: string;
- status: SyncMutationStatus;
-};
-
-export type MutationBase = {
- id: string;
- createdAt: string;
-};
-
-export type CreateNodeMutationData = {
- nodeId: string;
- updateId: string;
- createdAt: string;
- data: string;
-};
-
-export type CreateNodeMutation = MutationBase & {
- type: 'create_node';
- data: CreateNodeMutationData;
-};
-
-export type UpdateNodeMutationData = {
- nodeId: string;
- updateId: string;
- data: string;
- createdAt: string;
-};
-
-export type UpdateNodeMutation = MutationBase & {
- type: 'update_node';
- data: UpdateNodeMutationData;
-};
-
-export type DeleteNodeMutationData = {
- nodeId: string;
- rootId: string;
- deletedAt: string;
-};
-
-export type DeleteNodeMutation = MutationBase & {
- type: 'delete_node';
- data: DeleteNodeMutationData;
-};
-
-export type CreateNodeReactionMutationData = {
- nodeId: string;
- reaction: string;
- rootId: string;
- createdAt: string;
-};
-
-export type CreateNodeReactionMutation = MutationBase & {
- type: 'create_node_reaction';
- data: CreateNodeReactionMutationData;
-};
-
-export type DeleteNodeReactionMutationData = {
- nodeId: string;
- reaction: string;
- rootId: string;
- deletedAt: string;
-};
-
-export type DeleteNodeReactionMutation = MutationBase & {
- type: 'delete_node_reaction';
- data: DeleteNodeReactionMutationData;
-};
-
-export type MarkNodeSeenMutationData = {
- nodeId: string;
- collaboratorId: string;
- seenAt: string;
-};
-
-export type MarkNodeSeenMutation = MutationBase & {
- type: 'mark_node_seen';
- data: MarkNodeSeenMutationData;
-};
-
-export type MarkNodeOpenedMutationData = {
- nodeId: string;
- collaboratorId: string;
- openedAt: string;
-};
-
-export type MarkNodeOpenedMutation = MutationBase & {
- type: 'mark_node_opened';
- data: MarkNodeOpenedMutationData;
-};
-
-export type UpdateDocumentMutationData = {
- documentId: string;
- updateId: string;
- data: string;
- createdAt: string;
-};
-
-export type UpdateDocumentMutation = MutationBase & {
- type: 'update_document';
- data: UpdateDocumentMutationData;
-};
-
-export type Mutation =
- | CreateNodeMutation
- | UpdateNodeMutation
- | DeleteNodeMutation
- | CreateNodeReactionMutation
- | DeleteNodeReactionMutation
- | MarkNodeSeenMutation
- | MarkNodeOpenedMutation
- | UpdateDocumentMutation;
+import { z } from 'zod';
+export const syncMutationStatusSchema = z.enum(['success', 'error']);
+
+export type SyncMutationStatus = z.infer<typeof syncMutationStatusSchema>;
+
+export const syncMutationResultSchema = z.object({
+ id: z.string(),
+ status: syncMutationStatusSchema,
+});
+
+export type SyncMutationResult = z.infer<typeof syncMutationResultSchema>;
+
+export const syncMutationsInputSchema = z.object({
+ mutations: z.array(z.lazy(() => mutationSchema)),
+});
+
+export type SyncMutationsInput = z.infer<typeof syncMutationsInputSchema>;
+
+export const syncMutationsOutputSchema = z.object({
+ results: z.array(syncMutationResultSchema),
+});
+
+export type SyncMutationsOutput = z.infer<typeof syncMutationsOutputSchema>;
+
+export const mutationBaseSchema = z.object({
+ id: z.string(),
+ createdAt: z.string(),
+});
+
+export type MutationBase = z.infer<typeof mutationBaseSchema>;
+
+export const createNodeMutationDataSchema = z.object({
+ nodeId: z.string(),
+ updateId: z.string(),
+ createdAt: z.string(),
+ data: z.string(),
+});
+
+export type CreateNodeMutationData = z.infer<
+ typeof createNodeMutationDataSchema
+>;
+
+export const createNodeMutationSchema = mutationBaseSchema.extend({
+ type: z.literal('create_node'),
+ data: createNodeMutationDataSchema,
+});
+
+export type CreateNodeMutation = z.infer<typeof createNodeMutationSchema>;
+
+export const updateNodeMutationDataSchema = z.object({
+ nodeId: z.string(),
+ updateId: z.string(),
+ data: z.string(),
+ createdAt: z.string(),
+});
+
+export type UpdateNodeMutationData = z.infer<
+ typeof updateNodeMutationDataSchema
+>;
+
+export const updateNodeMutationSchema = mutationBaseSchema.extend({
+ type: z.literal('update_node'),
+ data: updateNodeMutationDataSchema,
+});
+
+export type UpdateNodeMutation = z.infer<typeof updateNodeMutationSchema>;
+
+export const deleteNodeMutationDataSchema = z.object({
+ nodeId: z.string(),
+ rootId: z.string(),
+ deletedAt: z.string(),
+});
+
+export type DeleteNodeMutationData = z.infer<
+ typeof deleteNodeMutationDataSchema
+>;
+
+export const deleteNodeMutationSchema = mutationBaseSchema.extend({
+ type: z.literal('delete_node'),
+ data: deleteNodeMutationDataSchema,
+});
+
+export type DeleteNodeMutation = z.infer<typeof deleteNodeMutationSchema>;
+
+export const createNodeReactionMutationDataSchema = z.object({
+ nodeId: z.string(),
+ reaction: z.string(),
+ rootId: z.string(),
+ createdAt: z.string(),
+});
+
+export type CreateNodeReactionMutationData = z.infer<
+ typeof createNodeReactionMutationDataSchema
+>;
+
+export const createNodeReactionMutationSchema = mutationBaseSchema.extend({
+ type: z.literal('create_node_reaction'),
+ data: createNodeReactionMutationDataSchema,
+});
+
+export type CreateNodeReactionMutation = z.infer<
+ typeof createNodeReactionMutationSchema
+>;
+
+export const deleteNodeReactionMutationDataSchema = z.object({
+ nodeId: z.string(),
+ reaction: z.string(),
+ rootId: z.string(),
+ deletedAt: z.string(),
+});
+
+export type DeleteNodeReactionMutationData = z.infer<
+ typeof deleteNodeReactionMutationDataSchema
+>;
+
+export const deleteNodeReactionMutationSchema = mutationBaseSchema.extend({
+ type: z.literal('delete_node_reaction'),
+ data: deleteNodeReactionMutationDataSchema,
+});
+
+export type DeleteNodeReactionMutation = z.infer<
+ typeof deleteNodeReactionMutationSchema
+>;
+
+export const markNodeSeenMutationDataSchema = z.object({
+ nodeId: z.string(),
+ collaboratorId: z.string(),
+ seenAt: z.string(),
+});
+
+export type MarkNodeSeenMutationData = z.infer<
+ typeof markNodeSeenMutationDataSchema
+>;
+
+export const markNodeSeenMutationSchema = mutationBaseSchema.extend({
+ type: z.literal('mark_node_seen'),
+ data: markNodeSeenMutationDataSchema,
+});
+
+export type MarkNodeSeenMutation = z.infer<typeof markNodeSeenMutationSchema>;
+
+export const markNodeOpenedMutationDataSchema = z.object({
+ nodeId: z.string(),
+ collaboratorId: z.string(),
+ openedAt: z.string(),
+});
+
+export type MarkNodeOpenedMutationData = z.infer<
+ typeof markNodeOpenedMutationDataSchema
+>;
+
+export const markNodeOpenedMutationSchema = mutationBaseSchema.extend({
+ type: z.literal('mark_node_opened'),
+ data: markNodeOpenedMutationDataSchema,
+});
+
+export type MarkNodeOpenedMutation = z.infer<
+ typeof markNodeOpenedMutationSchema
+>;
+
+export const updateDocumentMutationDataSchema = z.object({
+ documentId: z.string(),
+ updateId: z.string(),
+ data: z.string(),
+ createdAt: z.string(),
+});
+
+export type UpdateDocumentMutationData = z.infer<
+ typeof updateDocumentMutationDataSchema
+>;
+
+export const updateDocumentMutationSchema = mutationBaseSchema.extend({
+ type: z.literal('update_document'),
+ data: updateDocumentMutationDataSchema,
+});
+
+export type UpdateDocumentMutation = z.infer<
+ typeof updateDocumentMutationSchema
+>;
+
+export const mutationSchema = z.discriminatedUnion('type', [
+ createNodeMutationSchema,
+ updateNodeMutationSchema,
+ deleteNodeMutationSchema,
+ createNodeReactionMutationSchema,
+ deleteNodeReactionMutationSchema,
+ markNodeSeenMutationSchema,
+ markNodeOpenedMutationSchema,
+ updateDocumentMutationSchema,
+]);
+
+export type Mutation = z.infer<typeof mutationSchema>;
export type MutationType = Mutation['type'];
diff --git a/packages/core/src/types/servers.ts b/packages/core/src/types/servers.ts
index 90832b05..a831ab82 100644
--- a/packages/core/src/types/servers.ts
+++ b/packages/core/src/types/servers.ts
@@ -1,9 +1,15 @@
-export type ServerConfig = {
- name: string;
- avatar: string;
- version: string;
- attributes: ServerAttributes;
- ip: string | null | undefined;
-};
-
-export type ServerAttributes = Record<string, unknown>;
+import { z } from 'zod';
+
+export const serverAttributesSchema = z.record(z.string(), z.unknown());
+
+export type ServerAttributes = z.infer<typeof serverAttributesSchema>;
+
+export const serverConfigSchema = z.object({
+ name: z.string(),
+ avatar: z.string(),
+ version: z.string(),
+ ip: z.string().nullable().optional(),
+ attributes: serverAttributesSchema,
+});
+
+export type ServerConfig = z.infer<typeof serverConfigSchema>;
diff --git a/packages/core/src/types/workspaces.ts b/packages/core/src/types/workspaces.ts
index aa7e9f31..893f8831 100644
--- a/packages/core/src/types/workspaces.ts
+++ b/packages/core/src/types/workspaces.ts
@@ -1,9 +1,4 @@
-export type WorkspaceRole =
- | 'owner'
- | 'admin'
- | 'collaborator'
- | 'guest'
- | 'none';
+import { z } from 'zod';
export enum WorkspaceStatus {
Active = 1,
@@ -15,48 +10,74 @@ export enum UserStatus {
Removed = 2,
}
-export type WorkspaceCreateInput = {
- name: string;
- description?: string | null;
- avatar?: string | null;
-};
-
-export type WorkspaceOutput = {
- id: string;
- name: string;
- description?: string | null;
- avatar?: string | null;
- user: WorkspaceUserOutput;
-};
-
-export type WorkspaceUserOutput = {
- id: string;
- accountId: string;
- role: WorkspaceRole;
- storageLimit: bigint;
- maxFileSize: bigint;
-};
-
-export type WorkspaceUpdateInput = {
- name: string;
- description?: string | null;
- avatar?: string | null;
-};
-
-export type UsersInviteInput = {
- emails: string[];
- role: WorkspaceRole;
-};
-
-export type UserInviteResult = {
- email: string;
- result: 'success' | 'error' | 'exists';
-};
-
-export type UsersInviteOutput = {
- results: UserInviteResult[];
-};
-
-export type UserRoleUpdateInput = {
- role: WorkspaceRole;
-};
+export const workspaceRoleSchema = z.enum([
+ 'owner',
+ 'admin',
+ 'collaborator',
+ 'guest',
+ 'none',
+]);
+
+export type WorkspaceRole = z.infer<typeof workspaceRoleSchema>;
+
+export const workspaceCreateInputSchema = z.object({
+ name: z.string(),
+ description: z.string().nullable().optional(),
+ avatar: z.string().nullable().optional(),
+});
+
+export type WorkspaceCreateInput = z.infer<typeof workspaceCreateInputSchema>;
+
+export const workspaceUserOutputSchema = z.object({
+ id: z.string(),
+ accountId: z.string(),
+ role: workspaceRoleSchema,
+ storageLimit: z.string(),
+ maxFileSize: z.string(),
+});
+
+export type WorkspaceUserOutput = z.infer<typeof workspaceUserOutputSchema>;
+
+export const workspaceOutputSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ description: z.string().nullable().optional(),
+ avatar: z.string().nullable().optional(),
+ user: workspaceUserOutputSchema,
+});
+
+export type WorkspaceOutput = z.infer<typeof workspaceOutputSchema>;
+
+export const workspaceUpdateInputSchema = z.object({
+ name: z.string(),
+ description: z.string().nullable().optional(),
+ avatar: z.string().nullable().optional(),
+});
+
+export type WorkspaceUpdateInput = z.infer<typeof workspaceUpdateInputSchema>;
+
+export const usersInviteInputSchema = z.object({
+ emails: z.array(z.string().email()),
+ role: workspaceRoleSchema,
+});
+
+export type UsersInviteInput = z.infer<typeof usersInviteInputSchema>;
+
+export const userInviteResultSchema = z.object({
+ email: z.string().email(),
+ result: z.enum(['success', 'error', 'exists']),
+});
+
+export type UserInviteResult = z.infer<typeof userInviteResultSchema>;
+
+export const usersInviteOutputSchema = z.object({
+ results: z.array(userInviteResultSchema),
+});
+
+export type UsersInviteOutput = z.infer<typeof usersInviteOutputSchema>;
+
+export const userRoleUpdateInputSchema = z.object({
+ role: workspaceRoleSchema,
+});
+
+export type UserRoleUpdateInput = z.infer<typeof userRoleUpdateInputSchema>;