Skip to content

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

Refactor server routes

Hakan Shehu954564d1bf57
diff --git a/apps/desktop/src/main/services/file-service.ts b/apps/desktop/src/main/services/file-service.ts
index 0df2da6a..20c11dc0 100644
--- a/apps/desktop/src/main/services/file-service.ts
+++ b/apps/desktop/src/main/services/file-service.ts
@@ -307,7 +307,7 @@ class FileService {
try {
const { data } = await httpClient.post<CreateUploadOutput>(
- `/v1/files/${credentials.workspaceId}`,
+ `/v1/workspaces/${credentials.workspaceId}/uploads`,
{
fileId: file.id,
uploadId: upload.upload_id,
@@ -328,7 +328,7 @@ class FileService {
});
const { status } = await httpClient.put<CompleteUploadOutput>(
- `/v1/files/${credentials.workspaceId}/${data.uploadId}`,
+ `/v1/workspaces/${credentials.workspaceId}/uploads/${data.uploadId}`,
{},
{
domain: credentials.serverDomain,
@@ -447,7 +447,7 @@ class FileService {
try {
const { data } = await httpClient.get<CreateDownloadOutput>(
- `/v1/files/${credentials.workspaceId}/${download.node_id}`,
+ `/v1/workspaces/${credentials.workspaceId}/downloads/${download.node_id}`,
{
domain: credentials.serverDomain,
token: credentials.token,
diff --git a/apps/desktop/src/main/services/server-service.ts b/apps/desktop/src/main/services/server-service.ts
index 25bcfcfb..997dc9b8 100644
--- a/apps/desktop/src/main/services/server-service.ts
+++ b/apps/desktop/src/main/services/server-service.ts
@@ -146,12 +146,12 @@ class ServerService {
public buildApiBaseUrl(domain: string) {
const protocol = domain.startsWith('localhost:') ? 'http' : 'https';
- return `${protocol}://${domain}`;
+ return `${protocol}://${domain}/client`;
}
public buildSynapseUrl(domain: string) {
const protocol = domain.startsWith('localhost:') ? 'ws' : 'wss';
- return `${protocol}://${domain}/v1/synapse`;
+ return `${protocol}://${domain}/client/v1/synapse`;
}
}
diff --git a/apps/desktop/src/main/services/sync-service.ts b/apps/desktop/src/main/services/sync-service.ts
index 6bbcef3c..7e4e7ba9 100644
--- a/apps/desktop/src/main/services/sync-service.ts
+++ b/apps/desktop/src/main/services/sync-service.ts
@@ -414,7 +414,7 @@ class SyncService {
);
const { data } = await httpClient.get<GetTransactionsOutput>(
- `/v1/nodes/${credentials.workspaceId}/transactions/${nodeId}`,
+ `/v1/workspaces/${credentials.workspaceId}/transactions/${nodeId}`,
{
domain: credentials.serverDomain,
token: credentials.token,
@@ -518,7 +518,7 @@ class SyncService {
this.debug(`Syncing missing node ${node.node_id} for user ${userId}`);
const { data } = await httpClient.get<GetTransactionsOutput>(
- `/v1/nodes/${credentials.workspaceId}/transactions/${node.node_id}`,
+ `/v1/workspaces/${credentials.workspaceId}/transactions/${node.node_id}`,
{
domain: credentials.serverDomain,
token: credentials.token,
@@ -571,7 +571,7 @@ class SyncService {
try {
const { data } = await httpClient.get<GetTransactionsOutput>(
- `/v1/nodes/${credentials.workspaceId}/transactions/${nodeId}`,
+ `/v1/workspaces/${credentials.workspaceId}/transactions/${nodeId}`,
{
domain: credentials.serverDomain,
token: credentials.token,
@@ -627,7 +627,7 @@ class SyncService {
const transactions: LocalTransaction[] =
unsyncedTransactions.map(mapTransaction);
const { data } = await httpClient.post<SyncTransactionsOutput>(
- `/v1/sync/${credentials.workspaceId}`,
+ `/v1/workspaces/${credentials.workspaceId}/transactions`,
{
transactions,
},
diff --git a/apps/server/src/api.ts b/apps/server/src/api.ts
index 989c8b2a..e1171785 100644
--- a/apps/server/src/api.ts
+++ b/apps/server/src/api.ts
@@ -3,14 +3,7 @@ import express, { Request, Response } from 'express';
import http from 'http';
-import { authMiddleware } from '@/middlewares/auth';
-import { accountsRouter } from '@/routes/accounts';
-import { avatarsRouter } from '@/routes/avatars';
-import { configRouter } from '@/routes/config';
-import { filesRouter } from '@/routes/files';
-import { nodesRouter } from '@/routes/nodes';
-import { syncRouter } from '@/routes/sync';
-import { workspacesRouter } from '@/routes/workspaces';
+import { clientRouter } from '@/routes/client';
import { socketService } from '@/services/socket-service';
import { createLogger } from '@/lib/logger';
@@ -28,16 +21,12 @@ export const initApi = async () => {
app.use(cors());
app.get('/', (_: Request, res: Response) => {
- res.send('Colanode');
+ res.send(
+ 'This is a Colanode server. For more information, visit https://colanode.com'
+ );
});
- app.use('/v1/accounts', accountsRouter);
- app.use('/v1/config', configRouter);
- app.use('/v1/workspaces', authMiddleware, workspacesRouter);
- app.use('/v1/sync', authMiddleware, syncRouter);
- app.use('/v1/avatars', authMiddleware, avatarsRouter);
- app.use('/v1/files', authMiddleware, filesRouter);
- app.use('/v1/nodes', authMiddleware, nodesRouter);
+ app.use('/client', clientRouter);
const server = http.createServer(app);
await socketService.init(server);
diff --git a/apps/server/src/controllers/client/accounts/account-sync.ts b/apps/server/src/controllers/client/accounts/account-sync.ts
new file mode 100644
index 00000000..6b817383
--- /dev/null
+++ b/apps/server/src/controllers/client/accounts/account-sync.ts
@@ -0,0 +1,79 @@
+import { Request, Response } from 'express';
+import {
+ AccountSyncOutput,
+ WorkspaceOutput,
+ WorkspaceRole,
+} from '@colanode/core';
+
+import { ApiError } from '@/types/api';
+import { database } from '@/data/database';
+
+export const accountSyncHandler = async (
+ _: Request,
+ res: Response
+): Promise<void> => {
+ const account = await database
+ .selectFrom('accounts')
+ .where('id', '=', res.locals.account.id)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!account) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'Account not found.',
+ });
+ return;
+ }
+
+ const workspaceOutputs: WorkspaceOutput[] = [];
+ const workspaceUsers = await database
+ .selectFrom('workspace_users')
+ .where('account_id', '=', account.id)
+ .selectAll()
+ .execute();
+
+ if (workspaceUsers.length > 0) {
+ const workspaceIds = workspaceUsers.map((wu) => wu.workspace_id);
+ const workspaces = await database
+ .selectFrom('workspaces')
+ .where('id', 'in', workspaceIds)
+ .selectAll()
+ .execute();
+
+ for (const workspaceUser of workspaceUsers) {
+ const workspace = workspaces.find(
+ (w) => w.id === workspaceUser.workspace_id
+ );
+
+ if (!workspace) {
+ continue;
+ }
+
+ workspaceOutputs.push({
+ id: workspace.id,
+ name: workspace.name,
+ versionId: workspaceUser.version_id,
+ avatar: workspace.avatar,
+ description: workspace.description,
+ user: {
+ id: workspaceUser.id,
+ accountId: workspaceUser.account_id,
+ role: workspaceUser.role as WorkspaceRole,
+ },
+ });
+ }
+ }
+
+ const output: AccountSyncOutput = {
+ account: {
+ id: account.id,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
+ },
+ workspaces: workspaceOutputs,
+ };
+
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/accounts/account-update.ts b/apps/server/src/controllers/client/accounts/account-update.ts
new file mode 100644
index 00000000..d1cff37e
--- /dev/null
+++ b/apps/server/src/controllers/client/accounts/account-update.ts
@@ -0,0 +1,108 @@
+import { Request, Response } from 'express';
+import { AccountUpdateInput, AccountUpdateOutput } from '@colanode/core';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+import { nodeService } from '@/services/node-service';
+
+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) {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'Invalid account id.',
+ });
+ return;
+ }
+
+ const account = await database
+ .selectFrom('accounts')
+ .where('id', '=', res.locals.account.id)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!account) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'Account not found.',
+ });
+ return;
+ }
+
+ const nameChanged = account.name !== input.name;
+ const avatarChanged = account.avatar !== input.avatar;
+
+ if (!nameChanged && !avatarChanged) {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'Nothing to update.',
+ });
+ return;
+ }
+
+ await database
+ .updateTable('accounts')
+ .set({
+ name: input.name,
+ avatar: input.avatar,
+ updated_at: new Date(),
+ })
+ .where('id', '=', account.id)
+ .execute();
+
+ const users = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where(
+ 'id',
+ 'in',
+ database
+ .selectFrom('workspace_users')
+ .select('id')
+ .where('account_id', '=', account.id)
+ )
+ .execute();
+
+ for (const user of users) {
+ if (user.attributes.type !== 'user') {
+ throw new Error('User node not found.');
+ }
+
+ const name = user.attributes.name ?? null;
+ const avatar = user.attributes.avatar ?? null;
+
+ if (account.name !== name || account.avatar !== avatar) {
+ continue;
+ }
+
+ await nodeService.updateNode({
+ nodeId: user.id,
+ userId: user.created_by,
+ workspaceId: user.workspace_id,
+ updater: (attributes) => {
+ if (attributes.type !== 'user') {
+ return null;
+ }
+
+ return {
+ ...attributes,
+ name: input.name,
+ avatar: input.avatar,
+ };
+ },
+ });
+ }
+
+ const output: AccountUpdateOutput = {
+ id: account.id,
+ name: input.name,
+ avatar: input.avatar,
+ };
+
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/accounts/index.ts b/apps/server/src/controllers/client/accounts/index.ts
new file mode 100644
index 00000000..15f327d9
--- /dev/null
+++ b/apps/server/src/controllers/client/accounts/index.ts
@@ -0,0 +1,6 @@
+export * from './account-sync';
+export * from './login-email';
+export * from './login-google';
+export * from './logout';
+export * from './register-email';
+export * from './account-update';
diff --git a/apps/server/src/controllers/client/accounts/login-email.ts b/apps/server/src/controllers/client/accounts/login-email.ts
new file mode 100644
index 00000000..97113519
--- /dev/null
+++ b/apps/server/src/controllers/client/accounts/login-email.ts
@@ -0,0 +1,63 @@
+import { Request, Response } from 'express';
+import { AccountStatus, EmailLoginInput } from '@colanode/core';
+import bcrypt from 'bcrypt';
+import { sha256 } from 'js-sha256';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+import { accountService } from '@/services/account-service';
+
+export const loginWithEmailHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const input: EmailLoginInput = req.body;
+ const email = input.email.toLowerCase();
+
+ const account = await database
+ .selectFrom('accounts')
+ .where('email', '=', email)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!account) {
+ res.status(400).json({
+ code: ApiError.EmailOrPasswordIncorrect,
+ message: 'Invalid credentials.',
+ });
+ return;
+ }
+
+ if (account.status === AccountStatus.Pending) {
+ res.status(400).json({
+ code: ApiError.UserPendingActivation,
+ message: 'User is pending activation.',
+ });
+ return;
+ }
+
+ if (!account.password) {
+ res.status(400).json({
+ code: ApiError.EmailOrPasswordIncorrect,
+ message: 'Invalid credentials.',
+ });
+ return;
+ }
+
+ const preHashedPassword = sha256(input.password);
+ const passwordMatch = await bcrypt.compare(
+ preHashedPassword,
+ account.password
+ );
+
+ if (!passwordMatch) {
+ res.status(400).json({
+ code: ApiError.EmailOrPasswordIncorrect,
+ message: 'Invalid credentials.',
+ });
+ return;
+ }
+
+ const output = await accountService.buildLoginOutput(account);
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/accounts/login-google.ts b/apps/server/src/controllers/client/accounts/login-google.ts
new file mode 100644
index 00000000..57b55caf
--- /dev/null
+++ b/apps/server/src/controllers/client/accounts/login-google.ts
@@ -0,0 +1,93 @@
+import { Request, Response } from 'express';
+import {
+ AccountStatus,
+ generateId,
+ GoogleLoginInput,
+ GoogleUserInfo,
+ IdType,
+} from '@colanode/core';
+import axios from 'axios';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+import { accountService } from '@/services/account-service';
+
+const GoogleUserInfoUrl = 'https://www.googleapis.com/oauth2/v1/userinfo';
+
+export const loginWithGoogleHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const input: GoogleLoginInput = req.body;
+ const url = `${GoogleUserInfoUrl}?access_token=${input.access_token}`;
+ const userInfoResponse = await axios.get(url);
+
+ if (userInfoResponse.status !== 200) {
+ res.status(400).json({
+ code: ApiError.GoogleAuthFailed,
+ message: 'Failed to authenticate with Google.',
+ });
+ return;
+ }
+
+ const googleUser: GoogleUserInfo = userInfoResponse.data;
+
+ if (!googleUser) {
+ res.status(400).json({
+ code: ApiError.GoogleAuthFailed,
+ message: 'Failed to authenticate with Google.',
+ });
+ return;
+ }
+
+ const existingAccount = await database
+ .selectFrom('accounts')
+ .where('email', '=', googleUser.email)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (existingAccount) {
+ const attrs = existingAccount.attrs
+ ? JSON.parse(existingAccount.attrs)
+ : {};
+
+ if (attrs?.googleId || existingAccount.status === AccountStatus.Pending) {
+ 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 accountService.buildLoginOutput(existingAccount);
+ res.status(200).json(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,
+ })
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!newAccount) {
+ res.status(500).json({
+ code: ApiError.InternalServerError,
+ message: 'Failed to create account.',
+ });
+ return;
+ }
+
+ const output = await accountService.buildLoginOutput(newAccount);
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/accounts/logout.ts b/apps/server/src/controllers/client/accounts/logout.ts
new file mode 100644
index 00000000..0c46ba58
--- /dev/null
+++ b/apps/server/src/controllers/client/accounts/logout.ts
@@ -0,0 +1,17 @@
+import { Request, Response } from 'express';
+
+import { database } from '@/data/database';
+
+export const logoutHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const account = res.locals.account;
+
+ await database
+ .deleteFrom('devices')
+ .where('id', '=', account.deviceId)
+ .execute();
+
+ res.status(200).end();
+};
diff --git a/apps/server/src/controllers/client/accounts/register-email.ts b/apps/server/src/controllers/client/accounts/register-email.ts
new file mode 100644
index 00000000..41111404
--- /dev/null
+++ b/apps/server/src/controllers/client/accounts/register-email.ts
@@ -0,0 +1,81 @@
+import { Request, Response } from 'express';
+import {
+ AccountStatus,
+ EmailRegisterInput,
+ generateId,
+ IdType,
+} from '@colanode/core';
+import bcrypt from 'bcrypt';
+import { sha256 } from 'js-sha256';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+import { SelectAccount } from '@/data/schema';
+import { accountService } from '@/services/account-service';
+
+const SaltRounds = 10;
+
+export const registerWithEmailHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const input: EmailRegisterInput = req.body;
+ const email = input.email.toLowerCase();
+
+ const existingAccount = await database
+ .selectFrom('accounts')
+ .selectAll()
+ .where('email', '=', email)
+ .executeTakeFirst();
+
+ const salt = await bcrypt.genSalt(SaltRounds);
+ const preHashedPassword = sha256(input.password);
+ const password = await bcrypt.hash(preHashedPassword, salt);
+
+ let account: SelectAccount | null | undefined = null;
+ if (existingAccount) {
+ if (existingAccount.status !== AccountStatus.Pending) {
+ res.status(400).json({
+ code: ApiError.EmailAlreadyExists,
+ message: 'Email already exists.',
+ });
+ return;
+ }
+
+ account = await database
+ .updateTable('accounts')
+ .set({
+ password: password,
+ name: input.name,
+ updated_at: new Date(),
+ status: AccountStatus.Active,
+ })
+ .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: AccountStatus.Active,
+ created_at: new Date(),
+ })
+ .returningAll()
+ .executeTakeFirst();
+ }
+
+ if (!account) {
+ res.status(500).json({
+ code: ApiError.InternalServerError,
+ message: 'Failed to create account.',
+ });
+ return;
+ }
+
+ const output = await accountService.buildLoginOutput(account);
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/avatars/avatar-download.ts b/apps/server/src/controllers/client/avatars/avatar-download.ts
new file mode 100644
index 00000000..73d01d1a
--- /dev/null
+++ b/apps/server/src/controllers/client/avatars/avatar-download.ts
@@ -0,0 +1,34 @@
+import { Request, Response } from 'express';
+import { GetObjectCommand } from '@aws-sdk/client-s3';
+
+import { Readable } from 'stream';
+
+import { avatarStorage, BUCKET_NAMES } from '@/data/storage';
+
+export const avatarDownloadHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ try {
+ const avatarId = req.params.avatarId;
+ const command = new GetObjectCommand({
+ Bucket: BUCKET_NAMES.AVATARS,
+ Key: `avatars/${avatarId}.jpeg`,
+ });
+
+ const avatarResponse = await avatarStorage.send(command);
+ if (!avatarResponse.Body) {
+ res.status(404).json({ error: 'Avatar not found' });
+ return;
+ }
+
+ if (avatarResponse.Body instanceof Readable) {
+ avatarResponse.Body.pipe(res);
+ } else {
+ res.status(404).json({ error: 'Avatar not found' });
+ }
+ } catch (error) {
+ console.error('Error downloading avatar:', error);
+ res.status(500).json({ error: 'Failed to download avatar' });
+ }
+};
diff --git a/apps/server/src/routes/avatars.ts b/apps/server/src/controllers/client/avatars/avatar-upload.ts
similarity index 60%
rename from apps/server/src/routes/avatars.ts
rename to apps/server/src/controllers/client/avatars/avatar-upload.ts
index fbeef2c4..012553cd 100644
--- a/apps/server/src/routes/avatars.ts
+++ b/apps/server/src/controllers/client/avatars/avatar-upload.ts
@@ -1,18 +1,15 @@
-import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
+import { Request, Response } from 'express';
+import sharp from 'sharp';
+import { PutObjectCommand } from '@aws-sdk/client-s3';
import { generateId, IdType } from '@colanode/core';
-import { Router } from 'express';
import multer from 'multer';
-import sharp from 'sharp';
import path from 'path';
-import { Readable } from 'stream';
import { avatarStorage, BUCKET_NAMES } from '@/data/storage';
-export const avatarsRouter = Router();
-
const storage = multer.memoryStorage();
-const upload = multer({
+const uploadMulter = multer({
storage,
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
fileFilter: (req, file, cb) => {
@@ -30,7 +27,12 @@ const upload = multer({
},
});
-avatarsRouter.post('/', upload.single('avatar'), async (req, res) => {
+export const avatarUploadParameter = uploadMulter.single('avatar');
+
+export const avatarUploadHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
try {
if (!req.file) {
res.status(400).json({ error: 'No file uploaded' });
@@ -61,29 +63,4 @@ avatarsRouter.post('/', upload.single('avatar'), async (req, res) => {
console.error('Error uploading file:', error);
res.status(500).json({ error: 'Failed to upload avatar' });
}
-});
-
-avatarsRouter.get('/:id', async (req, res) => {
- try {
- const { id } = req.params;
- const command = new GetObjectCommand({
- Bucket: BUCKET_NAMES.AVATARS,
- Key: `avatars/${id}.jpeg`,
- });
-
- const avatarResponse = await avatarStorage.send(command);
- if (!avatarResponse.Body) {
- res.status(404).json({ error: 'Avatar not found' });
- return;
- }
-
- if (avatarResponse.Body instanceof Readable) {
- avatarResponse.Body.pipe(res);
- } else {
- res.status(404).json({ error: 'Avatar not found' });
- }
- } catch (error) {
- console.error('Error downloading avatar:', error);
- res.status(500).json({ error: 'Failed to download avatar' });
- }
-});
+};
diff --git a/apps/server/src/controllers/client/avatars/index.ts b/apps/server/src/controllers/client/avatars/index.ts
new file mode 100644
index 00000000..b421092e
--- /dev/null
+++ b/apps/server/src/controllers/client/avatars/index.ts
@@ -0,0 +1,2 @@
+export * from './avatar-upload';
+export * from './avatar-download';
diff --git a/apps/server/src/routes/config.ts b/apps/server/src/controllers/client/config/index.ts
similarity index 56%
rename from apps/server/src/routes/config.ts
rename to apps/server/src/controllers/client/config/index.ts
index efe14bfe..7e40a413 100644
--- a/apps/server/src/routes/config.ts
+++ b/apps/server/src/controllers/client/config/index.ts
@@ -1,9 +1,10 @@
import { ServerConfig } from '@colanode/core';
-import { Request, Response,Router } from 'express';
+import { Request, Response } from 'express';
-export const configRouter = Router();
-
-configRouter.get('/', async (_: Request, res: Response) => {
+export const configGetHandler = async (
+ _: Request,
+ res: Response
+): Promise<void> => {
const config: ServerConfig = {
name: 'Colanode Cloud',
avatar: '',
@@ -12,4 +13,4 @@ configRouter.get('/', async (_: Request, res: Response) => {
};
res.status(200).json(config);
-});
+};
diff --git a/apps/server/src/controllers/client/index.ts b/apps/server/src/controllers/client/index.ts
new file mode 100644
index 00000000..718f1fea
--- /dev/null
+++ b/apps/server/src/controllers/client/index.ts
@@ -0,0 +1,4 @@
+export * from './accounts';
+export * from './avatars';
+export * from './config';
+export * from './workspaces';
diff --git a/apps/server/src/controllers/client/workspaces/files/file-download-get.ts b/apps/server/src/controllers/client/workspaces/files/file-download-get.ts
new file mode 100644
index 00000000..f1a75e09
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/files/file-download-get.ts
@@ -0,0 +1,78 @@
+import { Request, Response } from 'express';
+import { CreateDownloadOutput, hasCollaboratorAccess } from '@colanode/core';
+import { GetObjectCommand } from '@aws-sdk/client-s3';
+import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
+
+import { ApiError } from '@/types/api';
+import { database } from '@/data/database';
+import { fetchNodeRole } from '@/lib/nodes';
+import { BUCKET_NAMES, filesStorage } from '@/data/storage';
+
+export const fileDownloadGetHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const fileId = req.params.fileId as string;
+
+ const role = await fetchNodeRole(fileId, res.locals.workspaceUser.id);
+ if (role === null || !hasCollaboratorAccess(role)) {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ const node = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!node) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'File not found.',
+ });
+ return;
+ }
+
+ if (node.attributes.type !== 'file') {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'File not found.',
+ });
+ return;
+ }
+
+ // check if the upload is completed
+ const upload = await database
+ .selectFrom('uploads')
+ .selectAll()
+ .where('node_id', '=', fileId)
+ .executeTakeFirst();
+
+ if (!upload) {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'Upload not completed.',
+ });
+ return;
+ }
+
+ //generate presigned url for download
+ const command = new GetObjectCommand({
+ Bucket: BUCKET_NAMES.FILES,
+ Key: upload.path,
+ });
+
+ const presignedUrl = await getSignedUrl(filesStorage, command, {
+ expiresIn: 60 * 60 * 4, // 4 hours
+ });
+
+ const output: CreateDownloadOutput = {
+ url: presignedUrl,
+ };
+
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/workspaces/files/file-upload-complete.ts b/apps/server/src/controllers/client/workspaces/files/file-upload-complete.ts
new file mode 100644
index 00000000..40272ea0
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/files/file-upload-complete.ts
@@ -0,0 +1,122 @@
+import { Request, Response } from 'express';
+import { extractFileType, UploadMetadata } from '@colanode/core';
+import { HeadObjectCommand } from '@aws-sdk/client-s3';
+
+import { ApiError } from '@/types/api';
+import { database } from '@/data/database';
+import { redis } from '@/data/redis';
+import { BUCKET_NAMES, filesStorage } from '@/data/storage';
+import { nodeService } from '@/services/node-service';
+
+export const fileUploadCompleteHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const workspaceId = req.params.workspaceId as string;
+ const uploadId = req.params.uploadId as string;
+
+ const metadataJson = await redis.get(uploadId);
+ if (!metadataJson) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'Upload not found.',
+ });
+ return;
+ }
+
+ const metadata: UploadMetadata = JSON.parse(metadataJson);
+ const file = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', metadata.fileId)
+ .executeTakeFirst();
+
+ if (!file) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'File not found.',
+ });
+ return;
+ }
+
+ if (file.attributes.type !== 'file') {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'File not found.',
+ });
+ return;
+ }
+
+ if (file.attributes.size !== metadata.size) {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'Size mismatch.',
+ });
+ return;
+ }
+
+ const path = metadata.path;
+ // check if the file exists in the bucket
+ const command = new HeadObjectCommand({
+ Bucket: BUCKET_NAMES.FILES,
+ Key: path,
+ });
+
+ try {
+ const headObject = await filesStorage.send(command);
+
+ // Verify file size matches expected size
+ if (headObject.ContentLength !== metadata.size) {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'Uploaded file size does not match expected size',
+ });
+ return;
+ }
+
+ // Verify mime type matches expected type
+ if (headObject.ContentType !== metadata.mimeType) {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'Uploaded file type does not match expected type',
+ });
+ return;
+ }
+ } catch {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'File upload verification failed',
+ });
+ return;
+ }
+
+ await database
+ .insertInto('uploads')
+ .values({
+ node_id: file.id,
+ upload_id: uploadId,
+ workspace_id: workspaceId,
+ path: metadata.path,
+ mime_type: metadata.mimeType,
+ size: metadata.size,
+ type: extractFileType(metadata.mimeType),
+ created_by: res.locals.workspaceUser.id,
+ created_at: new Date(metadata.createdAt),
+ completed_at: new Date(),
+ })
+ .execute();
+
+ await nodeService.updateNode({
+ nodeId: file.id,
+ userId: res.locals.workspaceUser.id,
+ workspaceId: workspaceId,
+ updater: (attributes) => ({
+ ...attributes,
+ uploadStatus: 'completed',
+ uploadId: metadata.uploadId,
+ }),
+ });
+
+ await redis.del(uploadId);
+ res.status(200).json({ success: true });
+};
diff --git a/apps/server/src/controllers/client/workspaces/files/file-upload-init.ts b/apps/server/src/controllers/client/workspaces/files/file-upload-init.ts
new file mode 100644
index 00000000..ba59ae32
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/files/file-upload-init.ts
@@ -0,0 +1,85 @@
+import { Request, Response } from 'express';
+import {
+ CreateUploadInput,
+ CreateUploadOutput,
+ UploadMetadata,
+} from '@colanode/core';
+import { PutObjectCommand } from '@aws-sdk/client-s3';
+import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
+
+import { ApiError } from '@/types/api';
+import { database } from '@/data/database';
+import { BUCKET_NAMES, filesStorage } from '@/data/storage';
+import { redis } from '@/data/redis';
+
+export const fileUploadInitHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const workspaceId = req.params.workspaceId as string;
+ const input = req.body as CreateUploadInput;
+
+ const node = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', input.fileId)
+ .executeTakeFirst();
+
+ if (!node) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'File not found.',
+ });
+ return;
+ }
+
+ if (node.attributes.type !== 'file') {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'File not found.',
+ });
+ return;
+ }
+
+ if (node.created_by !== res.locals.workspaceUser.id) {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ //generate presigned url for upload
+ const path = `files/${workspaceId}/${input.fileId}_${input.uploadId}${node.attributes.extension}`;
+ const command = new PutObjectCommand({
+ Bucket: BUCKET_NAMES.FILES,
+ Key: path,
+ ContentLength: node.attributes.size,
+ ContentType: node.attributes.mimeType,
+ });
+
+ const expiresIn = 60 * 60 * 4; // 4 hours
+ const presignedUrl = await getSignedUrl(filesStorage, command, {
+ expiresIn,
+ });
+
+ const data: UploadMetadata = {
+ fileId: input.fileId,
+ path,
+ mimeType: node.attributes.mimeType,
+ size: node.attributes.size,
+ uploadId: input.uploadId,
+ createdAt: new Date().toISOString(),
+ };
+
+ await redis.set(input.uploadId, JSON.stringify(data), {
+ EX: expiresIn,
+ });
+
+ const output: CreateUploadOutput = {
+ uploadId: input.uploadId,
+ url: presignedUrl,
+ };
+
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/workspaces/files/index.ts b/apps/server/src/controllers/client/workspaces/files/index.ts
new file mode 100644
index 00000000..027f194e
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/files/index.ts
@@ -0,0 +1,3 @@
+export * from './file-download-get';
+export * from './file-upload-complete';
+export * from './file-upload-init';
diff --git a/apps/server/src/controllers/client/workspaces/index.ts b/apps/server/src/controllers/client/workspaces/index.ts
new file mode 100644
index 00000000..8666cd69
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/index.ts
@@ -0,0 +1,7 @@
+export * from './workspace-create';
+export * from './workspace-update';
+export * from './workspace-delete';
+export * from './workspace-get';
+export * from './users';
+export * from './files';
+export * from './transactions';
diff --git a/apps/server/src/controllers/client/workspaces/transactions/index.ts b/apps/server/src/controllers/client/workspaces/transactions/index.ts
new file mode 100644
index 00000000..a978e1b3
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/transactions/index.ts
@@ -0,0 +1,2 @@
+export * from './transactions-get';
+export * from './transactions-sync';
diff --git a/apps/server/src/controllers/client/workspaces/transactions/transactions-get.ts b/apps/server/src/controllers/client/workspaces/transactions/transactions-get.ts
new file mode 100644
index 00000000..ad708663
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/transactions/transactions-get.ts
@@ -0,0 +1,35 @@
+import { Request, Response } from 'express';
+import { GetTransactionsOutput, hasViewerAccess } from '@colanode/core';
+
+import { ApiError } from '@/types/api';
+import { database } from '@/data/database';
+import { fetchNodeRole, mapTransaction } from '@/lib/nodes';
+
+export const transactionsGetHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const nodeId = req.params.nodeId as string;
+
+ const role = await fetchNodeRole(nodeId, res.locals.workspaceUser.id);
+ if (role === null || !hasViewerAccess(role)) {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ const transactions = await database
+ .selectFrom('transactions')
+ .selectAll()
+ .where('node_id', '=', nodeId)
+ .orderBy('version', 'desc')
+ .execute();
+
+ const output: GetTransactionsOutput = {
+ transactions: transactions.map(mapTransaction),
+ };
+
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/routes/sync.ts b/apps/server/src/controllers/client/workspaces/transactions/transactions-sync.ts
similarity index 75%
rename from apps/server/src/routes/sync.ts
rename to apps/server/src/controllers/client/workspaces/transactions/transactions-sync.ts
index 99635037..44d5cae0 100644
--- a/apps/server/src/routes/sync.ts
+++ b/apps/server/src/controllers/client/workspaces/transactions/transactions-sync.ts
@@ -1,3 +1,4 @@
+import { Request, Response } from 'express';
import {
LocalCreateTransaction,
LocalDeleteTransaction,
@@ -7,46 +8,23 @@ import {
SyncTransactionsInput,
SyncTransactionStatus,
} from '@colanode/core';
-import { Request, Response, Router } from 'express';
-import { database } from '@/data/database';
import { SelectWorkspaceUser } from '@/data/schema';
import { nodeService } from '@/services/node-service';
-import { ApiError } from '@/types/api';
-export const syncRouter = Router();
-
-syncRouter.post('/:workspaceId', async (req: Request, res: Response) => {
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspaceId = req.params.workspaceId as string;
+export const transactionsSyncHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
const input = req.body as SyncTransactionsInput;
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', workspaceId)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
const results: SyncTransactionResult[] = [];
for (const transaction of input.transactions) {
try {
- const status = await handleLocalTransaction(workspaceUser, transaction);
+ const status = await handleLocalTransaction(
+ res.locals.workspaceUser,
+ transaction
+ );
results.push({
id: transaction.id,
status: status,
@@ -62,7 +40,7 @@ syncRouter.post('/:workspaceId', async (req: Request, res: Response) => {
console.log('executed mutations', results);
res.status(200).json({ results });
-});
+};
const handleLocalTransaction = async (
workspaceUser: SelectWorkspaceUser,
diff --git a/apps/server/src/controllers/client/workspaces/users/index.ts b/apps/server/src/controllers/client/workspaces/users/index.ts
new file mode 100644
index 00000000..5aea772c
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/users/index.ts
@@ -0,0 +1,2 @@
+export * from './user-create';
+export * from './user-role-update';
diff --git a/apps/server/src/controllers/client/workspaces/users/user-create.ts b/apps/server/src/controllers/client/workspaces/users/user-create.ts
new file mode 100644
index 00000000..50461f73
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/users/user-create.ts
@@ -0,0 +1,156 @@
+import { Request, Response } from 'express';
+import {
+ AccountStatus,
+ generateId,
+ IdType,
+ WorkspaceUserInviteResult,
+ WorkspaceUsersInviteInput,
+ WorkspaceUserStatus,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+import { fetchNode, mapNode } from '@/lib/nodes';
+import { getNameFromEmail } from '@/lib/utils';
+import { nodeService } from '@/services/node-service';
+import { SelectWorkspaceUser } from '@/data/schema';
+
+export const userCreateHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const workspaceId = req.params.workspaceId as string;
+ const input: WorkspaceUsersInviteInput = req.body;
+ const workspaceUser: SelectWorkspaceUser = res.locals.workspaceUser;
+
+ if (!input.emails || input.emails.length === 0) {
+ res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'BadRequest.',
+ });
+ return;
+ }
+
+ if (!res.locals.account) {
+ res.status(401).json({
+ code: ApiError.Unauthorized,
+ message: 'Unauthorized.',
+ });
+ return;
+ }
+
+ if (workspaceUser.role !== 'owner' && workspaceUser.role !== 'admin') {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ const workspaceNodeRow = await fetchNode(workspaceId);
+ if (!workspaceNodeRow) {
+ res.status(500).json({
+ code: ApiError.InternalServerError,
+ message: 'Something went wrong.',
+ });
+ return;
+ }
+
+ const workspaceNode = mapNode(workspaceNodeRow);
+ const results: WorkspaceUserInviteResult[] = [];
+ for (const email of input.emails) {
+ let account = await database
+ .selectFrom('accounts')
+ .select(['id', 'name', 'email', 'avatar'])
+ .where('email', '=', email)
+ .executeTakeFirst();
+
+ if (!account) {
+ account = await database
+ .insertInto('accounts')
+ .returning(['id', 'name', 'email', 'avatar'])
+ .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();
+ }
+
+ if (!account) {
+ results.push({
+ email: email,
+ result: 'error',
+ });
+ continue;
+ }
+
+ const existingWorkspaceUser = await database
+ .selectFrom('workspace_users')
+ .selectAll()
+ .where('account_id', '=', account.id)
+ .where('workspace_id', '=', workspaceId)
+ .executeTakeFirst();
+
+ if (existingWorkspaceUser) {
+ results.push({
+ email: email,
+ result: 'exists',
+ });
+ continue;
+ }
+
+ const userId = generateId(IdType.User);
+ const newWorkspaceUser = await database
+ .insertInto('workspace_users')
+ .returningAll()
+ .values({
+ id: userId,
+ account_id: account.id,
+ workspace_id: workspaceId,
+ role: input.role,
+ created_at: new Date(),
+ created_by: res.locals.account.id,
+ status: WorkspaceUserStatus.Active,
+ version_id: generateId(IdType.Version),
+ })
+ .executeTakeFirst();
+
+ if (!newWorkspaceUser) {
+ results.push({
+ email: email,
+ result: 'error',
+ });
+ }
+
+ await nodeService.createNode({
+ nodeId: userId,
+ attributes: {
+ type: 'user',
+ name: account.name,
+ email: account.email,
+ role: input.role,
+ accountId: account.id,
+ parentId: workspaceId,
+ },
+ userId: workspaceUser.id,
+ workspaceId: workspaceId,
+ ancestors: [workspaceNode],
+ });
+
+ results.push({
+ email: email,
+ result: 'success',
+ });
+ }
+
+ res.status(200).json({
+ results: results,
+ });
+};
diff --git a/apps/server/src/controllers/client/workspaces/users/user-role-update.ts b/apps/server/src/controllers/client/workspaces/users/user-role-update.ts
new file mode 100644
index 00000000..7f9cfc37
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/users/user-role-update.ts
@@ -0,0 +1,95 @@
+import { Request, Response } from 'express';
+import {
+ generateId,
+ IdType,
+ WorkspaceUserRoleUpdateInput,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+import { nodeService } from '@/services/node-service';
+import { mapTransaction } from '@/lib/nodes';
+import { SelectWorkspaceUser } from '@/data/schema';
+
+export const userRoleUpdateHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const workspaceId = req.params.workspaceId as string;
+ const userId = req.params.userId as string;
+ const input: WorkspaceUserRoleUpdateInput = req.body;
+ const workspaceUser: SelectWorkspaceUser = res.locals.workspaceUser;
+
+ if (workspaceUser.role !== 'owner' && workspaceUser.role !== 'admin') {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ const workspaceUserToUpdate = await database
+ .selectFrom('workspace_users')
+ .selectAll()
+ .where('id', '=', userId)
+ .executeTakeFirst();
+
+ if (!workspaceUserToUpdate) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'NotFound.',
+ });
+ return;
+ }
+
+ const user = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', workspaceUserToUpdate.id)
+ .executeTakeFirst();
+
+ if (!user) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'NotFound.',
+ });
+ return;
+ }
+
+ await database
+ .updateTable('workspace_users')
+ .set({
+ role: input.role,
+ updated_at: new Date(),
+ updated_by: workspaceUser.account_id,
+ version_id: generateId(IdType.Version),
+ })
+ .where('id', '=', userId)
+ .execute();
+
+ const updateUserOutput = await nodeService.updateNode({
+ nodeId: user.id,
+ userId: workspaceUser.account_id,
+ workspaceId: workspaceId,
+ updater: (attributes) => {
+ if (attributes.type !== 'user') {
+ return null;
+ }
+
+ attributes.role = input.role;
+ return attributes;
+ },
+ });
+
+ if (!updateUserOutput) {
+ res.status(500).json({
+ code: ApiError.InternalServerError,
+ message: 'Something went wrong.',
+ });
+ return;
+ }
+
+ res.status(200).json({
+ transaction: mapTransaction(updateUserOutput.transaction),
+ });
+};
diff --git a/apps/server/src/controllers/client/workspaces/workspace-create.ts b/apps/server/src/controllers/client/workspaces/workspace-create.ts
new file mode 100644
index 00000000..8618dd7a
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/workspace-create.ts
@@ -0,0 +1,38 @@
+import { WorkspaceCreateInput } from '@colanode/core';
+import { Request, Response } from 'express';
+
+import { workspaceService } from '@/services/workspace-service';
+import { ApiError } from '@/types/api';
+import { database } from '@/data/database';
+
+export const workspaceCreateHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const input: WorkspaceCreateInput = req.body;
+
+ if (!input.name) {
+ res.status(400).json({
+ code: ApiError.MissingRequiredFields,
+ message: 'Missing required fields.',
+ });
+ return;
+ }
+
+ const account = await database
+ .selectFrom('accounts')
+ .selectAll()
+ .where('id', '=', res.locals.account.id)
+ .executeTakeFirst();
+
+ if (!account) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'Account not found.',
+ });
+ return;
+ }
+
+ const output = await workspaceService.createWorkspace(account, input);
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/workspaces/workspace-delete.ts b/apps/server/src/controllers/client/workspaces/workspace-delete.ts
new file mode 100644
index 00000000..b8dbbc45
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/workspace-delete.ts
@@ -0,0 +1,28 @@
+import { Request, Response } from 'express';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+
+export const workspaceDeleteHandler = async (
+ req: Request,
+ res: Response
+): Promise<void> => {
+ const workspaceId = req.params.workspaceId as string;
+
+ if (res.locals.workspaceUser.role !== 'owner') {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ await database
+ .deleteFrom('workspaces')
+ .where('id', '=', workspaceId)
+ .execute();
+
+ res.status(200).json({
+ id: res.locals.workspace.id,
+ });
+};
diff --git a/apps/server/src/controllers/client/workspaces/workspace-get.ts b/apps/server/src/controllers/client/workspaces/workspace-get.ts
new file mode 100644
index 00000000..16ab869a
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/workspace-get.ts
@@ -0,0 +1,56 @@
+import { WorkspaceRole, WorkspaceOutput } from '@colanode/core';
+import { Request, Response } from 'express';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+
+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) {
+ res.status(404).json({
+ code: ApiError.ResourceNotFound,
+ message: 'Workspace not found.',
+ });
+ return;
+ }
+
+ const workspaceUser = await database
+ .selectFrom('workspace_users')
+ .selectAll()
+ .where('workspace_id', '=', workspaceId)
+ .where('account_id', '=', res.locals.account.id)
+ .executeTakeFirst();
+
+ if (!workspaceUser) {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ const output: WorkspaceOutput = {
+ id: workspace.id,
+ name: workspace.name,
+ description: workspace.description,
+ avatar: workspace.avatar,
+ versionId: workspace.version_id,
+ user: {
+ id: workspaceUser.id,
+ accountId: workspaceUser.account_id,
+ role: workspaceUser.role as WorkspaceRole,
+ },
+ };
+
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/controllers/client/workspaces/workspace-update.ts b/apps/server/src/controllers/client/workspaces/workspace-update.ts
new file mode 100644
index 00000000..7b0f9f75
--- /dev/null
+++ b/apps/server/src/controllers/client/workspaces/workspace-update.ts
@@ -0,0 +1,75 @@
+import { Request, Response } from 'express';
+import { WorkspaceOutput, WorkspaceUpdateInput } from '@colanode/core';
+
+import { database } from '@/data/database';
+import { nodeService } from '@/services/node-service';
+import { ApiError } from '@/types/api';
+
+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.workspaceUser.role !== 'owner') {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ 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) {
+ res.status(500).json({
+ code: ApiError.InternalServerError,
+ message: 'Internal server error.',
+ });
+ return;
+ }
+
+ await nodeService.updateNode({
+ nodeId: updatedWorkspace.id,
+ userId: res.locals.account.id,
+ workspaceId: workspaceId,
+ updater: (attributes) => {
+ if (attributes.type !== 'workspace') {
+ return null;
+ }
+
+ attributes.name = input.name;
+ attributes.description = input.description;
+ attributes.avatar = input.avatar;
+
+ return attributes;
+ },
+ });
+
+ const output: WorkspaceOutput = {
+ id: updatedWorkspace.id,
+ name: updatedWorkspace.name,
+ description: updatedWorkspace.description,
+ avatar: updatedWorkspace.avatar,
+ versionId: updatedWorkspace.version_id,
+ user: {
+ id: res.locals.workspaceUser.id,
+ accountId: res.locals.workspaceUser.account_id,
+ role: res.locals.workspaceUser.role,
+ },
+ };
+
+ res.status(200).json(output);
+};
diff --git a/apps/server/src/middlewares/workspace.ts b/apps/server/src/middlewares/workspace.ts
new file mode 100644
index 00000000..25a87053
--- /dev/null
+++ b/apps/server/src/middlewares/workspace.ts
@@ -0,0 +1,31 @@
+import { NextFunction, Request, RequestHandler, Response } from 'express';
+
+import { database } from '@/data/database';
+import { ApiError } from '@/types/api';
+
+export const workspaceMiddleware: RequestHandler = async (
+ req: Request,
+ res: Response,
+ next: NextFunction
+) => {
+ const workspaceId = req.params.workspaceId as string;
+
+ const workspaceUser = await database
+ .selectFrom('workspace_users')
+ .selectAll()
+ .where('workspace_id', '=', workspaceId)
+ .where('account_id', '=', res.locals.account.id)
+ .executeTakeFirst();
+
+ if (!workspaceUser) {
+ res.status(403).json({
+ code: ApiError.Forbidden,
+ message: 'Forbidden.',
+ });
+ return;
+ }
+
+ res.locals.workspaceUser = workspaceUser;
+
+ next();
+};
diff --git a/apps/server/src/routes/accounts.ts b/apps/server/src/routes/accounts.ts
deleted file mode 100644
index 74f4eef6..00000000
--- a/apps/server/src/routes/accounts.ts
+++ /dev/null
@@ -1,515 +0,0 @@
-import {
- AccountStatus,
- AccountSyncOutput,
- AccountUpdateInput,
- AccountUpdateOutput,
- EmailLoginInput,
- EmailRegisterInput,
- generateId,
- GoogleLoginInput,
- GoogleUserInfo,
- IdType,
- LoginOutput,
- WorkspaceOutput,
- WorkspaceRole,
-} from '@colanode/core';
-import axios from 'axios';
-import bcrypt from 'bcrypt';
-import { Request, Response, Router } from 'express';
-import { sha256 } from 'js-sha256';
-
-import { database } from '@/data/database';
-import { SelectAccount } from '@/data/schema';
-import { generateToken } from '@/lib/tokens';
-import { authMiddleware } from '@/middlewares/auth';
-import { nodeService } from '@/services/node-service';
-import { workspaceService } from '@/services/workspace-service';
-import { ApiError } from '@/types/api';
-
-const GoogleUserInfoUrl = 'https://www.googleapis.com/oauth2/v1/userinfo';
-const SaltRounds = 10;
-
-export const accountsRouter = Router();
-
-accountsRouter.post('/register/email', async (req: Request, res: Response) => {
- const input: EmailRegisterInput = req.body;
- const email = input.email.toLowerCase();
-
- const existingAccount = await database
- .selectFrom('accounts')
- .selectAll()
- .where('email', '=', email)
- .executeTakeFirst();
-
- const salt = await bcrypt.genSalt(SaltRounds);
- const preHashedPassword = sha256(input.password);
- const password = await bcrypt.hash(preHashedPassword, salt);
-
- let account: SelectAccount | null | undefined = null;
- if (existingAccount) {
- if (existingAccount.status !== AccountStatus.Pending) {
- res.status(400).json({
- code: ApiError.EmailAlreadyExists,
- message: 'Email already exists.',
- });
- return;
- }
-
- account = await database
- .updateTable('accounts')
- .set({
- password: password,
- name: input.name,
- updated_at: new Date(),
- status: AccountStatus.Active,
- })
- .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: AccountStatus.Active,
- created_at: new Date(),
- })
- .returningAll()
- .executeTakeFirst();
- }
-
- if (!account) {
- res.status(500).json({
- code: ApiError.InternalServerError,
- message: 'Failed to create account.',
- });
- return;
- }
-
- const output = await buildLoginOutput(account);
- res.status(200).json(output);
-});
-
-accountsRouter.post('/login/email', async (req: Request, res: Response) => {
- const input: EmailLoginInput = req.body;
- const email = input.email.toLowerCase();
-
- const account = await database
- .selectFrom('accounts')
- .where('email', '=', email)
- .selectAll()
- .executeTakeFirst();
-
- if (!account) {
- res.status(400).json({
- code: ApiError.EmailOrPasswordIncorrect,
- message: 'Invalid credentials.',
- });
- return;
- }
-
- if (account.status === AccountStatus.Pending) {
- res.status(400).json({
- code: ApiError.UserPendingActivation,
- message: 'User is pending activation.',
- });
- return;
- }
-
- if (!account.password) {
- res.status(400).json({
- code: ApiError.EmailOrPasswordIncorrect,
- message: 'Invalid credentials.',
- });
- return;
- }
-
- const preHashedPassword = sha256(input.password);
- const passwordMatch = await bcrypt.compare(
- preHashedPassword,
- account.password
- );
-
- if (!passwordMatch) {
- res.status(400).json({
- code: ApiError.EmailOrPasswordIncorrect,
- message: 'Invalid credentials.',
- });
- return;
- }
-
- const output = await buildLoginOutput(account);
- res.status(200).json(output);
-});
-
-accountsRouter.post('/login/google', async (req: Request, res: Response) => {
- const input: GoogleLoginInput = req.body;
- const url = `${GoogleUserInfoUrl}?access_token=${input.access_token}`;
- const userInfoResponse = await axios.get(url);
-
- if (userInfoResponse.status !== 200) {
- res.status(400).json({
- code: ApiError.GoogleAuthFailed,
- message: 'Failed to authenticate with Google.',
- });
- return;
- }
-
- const googleUser: GoogleUserInfo = userInfoResponse.data;
-
- if (!googleUser) {
- res.status(400).json({
- code: ApiError.GoogleAuthFailed,
- message: 'Failed to authenticate with Google.',
- });
- return;
- }
-
- const existingAccount = await database
- .selectFrom('accounts')
- .where('email', '=', googleUser.email)
- .selectAll()
- .executeTakeFirst();
-
- if (existingAccount) {
- const attrs = existingAccount.attrs
- ? JSON.parse(existingAccount.attrs)
- : {};
-
- if (attrs?.googleId || existingAccount.status === AccountStatus.Pending) {
- 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 buildLoginOutput(existingAccount);
- res.status(200).json(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,
- })
- .returningAll()
- .executeTakeFirst();
-
- if (!newAccount) {
- res.status(500).json({
- code: ApiError.InternalServerError,
- message: 'Failed to create account.',
- });
- return;
- }
-
- const output = await buildLoginOutput(newAccount);
- res.status(200).json(output);
-});
-
-accountsRouter.delete(
- '/logout',
- authMiddleware,
- async (req: Request, res: Response) => {
- const account = res.locals.account;
- if (!account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- await database
- .deleteFrom('devices')
- .where('id', '=', account.deviceId)
- .execute();
-
- res.status(200).end();
- }
-);
-
-accountsRouter.put(
- '/:id',
- authMiddleware,
- async (req: Request, res: Response) => {
- const id = req.params.id;
- const input: AccountUpdateInput = req.body;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- if (id !== res.locals.account.id) {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'Invalid account id.',
- });
- return;
- }
-
- const account = await database
- .selectFrom('accounts')
- .where('id', '=', res.locals.account.id)
- .selectAll()
- .executeTakeFirst();
-
- if (!account) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Account not found.',
- });
- return;
- }
-
- const nameChanged = account.name !== input.name;
- const avatarChanged = account.avatar !== input.avatar;
-
- if (!nameChanged && !avatarChanged) {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'Nothing to update.',
- });
- return;
- }
-
- await database
- .updateTable('accounts')
- .set({
- name: input.name,
- avatar: input.avatar,
- updated_at: new Date(),
- })
- .where('id', '=', account.id)
- .execute();
-
- const users = await database
- .selectFrom('nodes')
- .selectAll()
- .where(
- 'id',
- 'in',
- database
- .selectFrom('workspace_users')
- .select('id')
- .where('account_id', '=', account.id)
- )
- .execute();
-
- for (const user of users) {
- if (user.attributes.type !== 'user') {
- throw new Error('User node not found.');
- }
-
- const name = user.attributes.name ?? null;
- const avatar = user.attributes.avatar ?? null;
-
- if (account.name !== name || account.avatar !== avatar) {
- continue;
- }
-
- await nodeService.updateNode({
- nodeId: user.id,
- userId: user.created_by,
- workspaceId: user.workspace_id,
- updater: (attributes) => {
- if (attributes.type !== 'user') {
- return null;
- }
-
- return {
- ...attributes,
- name: input.name,
- avatar: input.avatar,
- };
- },
- });
- }
-
- const output: AccountUpdateOutput = {
- id: account.id,
- name: input.name,
- avatar: input.avatar,
- };
-
- res.status(200).json(output);
- }
-);
-
-accountsRouter.get(
- '/sync',
- authMiddleware,
- async (req: Request, res: Response) => {
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const account = await database
- .selectFrom('accounts')
- .where('id', '=', res.locals.account.id)
- .selectAll()
- .executeTakeFirst();
-
- if (!account) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Account not found.',
- });
- return;
- }
-
- const workspaceOutputs: WorkspaceOutput[] = [];
- const workspaceUsers = await database
- .selectFrom('workspace_users')
- .where('account_id', '=', account.id)
- .selectAll()
- .execute();
-
- if (workspaceUsers.length > 0) {
- const workspaceIds = workspaceUsers.map((wu) => wu.workspace_id);
- const workspaces = await database
- .selectFrom('workspaces')
- .where('id', 'in', workspaceIds)
- .selectAll()
- .execute();
-
- for (const workspaceUser of workspaceUsers) {
- const workspace = workspaces.find(
- (w) => w.id === workspaceUser.workspace_id
- );
-
- if (!workspace) {
- continue;
- }
-
- workspaceOutputs.push({
- id: workspace.id,
- name: workspace.name,
- versionId: workspaceUser.version_id,
- avatar: workspace.avatar,
- description: workspace.description,
- user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role as WorkspaceRole,
- },
- });
- }
- }
-
- const output: AccountSyncOutput = {
- account: {
- id: account.id,
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- },
- workspaces: workspaceOutputs,
- };
-
- res.status(200).json(output);
- }
-);
-
-const buildLoginOutput = async (
- account: SelectAccount
-): Promise<LoginOutput> => {
- const workspaceUsers = await database
- .selectFrom('workspace_users')
- .where('account_id', '=', account.id)
- .selectAll()
- .execute();
-
- const workspaceOutputs: WorkspaceOutput[] = [];
- if (workspaceUsers.length > 0) {
- const workspaceIds = workspaceUsers.map((wu) => wu.workspace_id);
- const workspaces = await database
- .selectFrom('workspaces')
- .where('id', 'in', workspaceIds)
- .selectAll()
- .execute();
-
- for (const workspaceUser of workspaceUsers) {
- const workspace = workspaces.find(
- (w) => w.id === workspaceUser.workspace_id
- );
-
- if (!workspace) {
- continue;
- }
-
- workspaceOutputs.push({
- id: workspace.id,
- name: workspace.name,
- versionId: workspaceUser.version_id,
- avatar: workspace.avatar,
- description: workspace.description,
- user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role as WorkspaceRole,
- },
- });
- }
- }
-
- if (workspaceOutputs.length === 0) {
- const workspace = await workspaceService.createDefaultWorkspace(account);
- workspaceOutputs.push(workspace);
- }
-
- const deviceId = generateId(IdType.Device);
- const { token, salt, hash } = generateToken(deviceId);
-
- const device = await database
- .insertInto('devices')
- .values({
- id: deviceId,
- account_id: account.id,
- token_hash: hash,
- token_salt: salt,
- token_generated_at: new Date(),
- type: 1,
- created_at: new Date(),
- version: '0.1.0',
- })
- .returningAll()
- .executeTakeFirst();
-
- if (!device) {
- throw new Error('Failed to create device.');
- }
-
- return {
- account: {
- id: account.id,
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- },
- workspaces: workspaceOutputs,
- deviceId: device.id,
- token,
- };
-};
diff --git a/apps/server/src/routes/client.ts b/apps/server/src/routes/client.ts
new file mode 100644
index 00000000..65a43e77
--- /dev/null
+++ b/apps/server/src/routes/client.ts
@@ -0,0 +1,126 @@
+import { Router } from 'express';
+
+import {
+ accountSyncHandler,
+ loginWithEmailHandler,
+ loginWithGoogleHandler,
+ logoutHandler,
+ registerWithEmailHandler,
+ accountUpdateHandler,
+ userCreateHandler,
+ userRoleUpdateHandler,
+ workspaceCreateHandler,
+ workspaceDeleteHandler,
+ workspaceGetHandler,
+ workspaceUpdateHandler,
+ avatarUploadHandler,
+ avatarDownloadHandler,
+ configGetHandler,
+ fileDownloadGetHandler,
+ fileUploadInitHandler,
+ fileUploadCompleteHandler,
+ transactionsGetHandler,
+ transactionsSyncHandler,
+} from '@/controllers/client';
+import { workspaceMiddleware } from '@/middlewares/workspace';
+import { authMiddleware } from '@/middlewares/auth';
+
+export const clientRouter = Router();
+
+clientRouter.get('/v1/config', configGetHandler);
+
+clientRouter.post('/v1/accounts/login/email', loginWithEmailHandler);
+
+clientRouter.post('/v1/accounts/login/google', loginWithGoogleHandler);
+
+clientRouter.post('/v1/accounts/register/email', registerWithEmailHandler);
+
+clientRouter.post('/v1/accounts/logout', authMiddleware, logoutHandler);
+
+clientRouter.put(
+ '/v1/accounts/:accountId',
+ authMiddleware,
+ accountUpdateHandler
+);
+
+clientRouter.get('/v1/accounts/sync', authMiddleware, accountSyncHandler);
+
+clientRouter.post('/v1/avatars', authMiddleware, 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/uploads',
+ authMiddleware,
+ workspaceMiddleware,
+ fileUploadInitHandler
+);
+
+clientRouter.put(
+ '/v1/workspaces/:workspaceId/uploads/:uploadId',
+ authMiddleware,
+ workspaceMiddleware,
+ fileUploadCompleteHandler
+);
+
+clientRouter.get(
+ '/v1/workspaces/:workspaceId/transactions/:nodeId',
+ authMiddleware,
+ workspaceMiddleware,
+ transactionsGetHandler
+);
+
+clientRouter.post(
+ '/v1/workspaces/:workspaceId/transactions',
+ authMiddleware,
+ workspaceMiddleware,
+ transactionsSyncHandler
+);
diff --git a/apps/server/src/routes/files.ts b/apps/server/src/routes/files.ts
deleted file mode 100644
index c2f3b8ff..00000000
--- a/apps/server/src/routes/files.ts
+++ /dev/null
@@ -1,387 +0,0 @@
-import {
- GetObjectCommand,
- HeadObjectCommand,
- PutObjectCommand,
-} from '@aws-sdk/client-s3';
-import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
-import {
- CreateDownloadOutput,
- CreateUploadInput,
- CreateUploadOutput,
- extractFileType,
- UploadMetadata,
-} from '@colanode/core';
-import { Request, Response, Router } from 'express';
-
-import { database } from '@/data/database';
-import { redis } from '@/data/redis';
-import { BUCKET_NAMES, filesStorage } from '@/data/storage';
-import { hasCollaboratorAccess } from '@/lib/constants';
-import { fetchNodeRole } from '@/lib/nodes';
-import { nodeService } from '@/services/node-service';
-import { ApiError } from '@/types/api';
-
-export const filesRouter = Router();
-
-filesRouter.get(
- '/:workspaceId/:fileId',
- async (req: Request, res: Response) => {
- const workspaceId = req.params.workspaceId as string;
- const fileId = req.params.fileId as string;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', workspaceId)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', workspace.id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const role = await fetchNodeRole(fileId, workspaceUser.id);
- if (role === null || !hasCollaboratorAccess(role)) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const node = await database
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', fileId)
- .executeTakeFirst();
-
- if (!node) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'File not found.',
- });
- return;
- }
-
- if (node.attributes.type !== 'file') {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'File not found.',
- });
- return;
- }
-
- // check if the upload is completed
- const upload = await database
- .selectFrom('uploads')
- .selectAll()
- .where('node_id', '=', fileId)
- .executeTakeFirst();
-
- if (!upload) {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'Upload not completed.',
- });
- return;
- }
-
- //generate presigned url for download
- const command = new GetObjectCommand({
- Bucket: BUCKET_NAMES.FILES,
- Key: upload.path,
- });
-
- const presignedUrl = await getSignedUrl(filesStorage, command, {
- expiresIn: 60 * 60 * 4, // 4 hours
- });
-
- const output: CreateDownloadOutput = {
- url: presignedUrl,
- };
-
- res.status(200).json(output);
- }
-);
-
-filesRouter.post('/:workspaceId', async (req: Request, res: Response) => {
- const workspaceId = req.params.workspaceId as string;
- const input = req.body as CreateUploadInput;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', workspaceId)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', workspace.id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const node = await database
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', input.fileId)
- .executeTakeFirst();
-
- if (!node) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'File not found.',
- });
- return;
- }
-
- if (node.attributes.type !== 'file') {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'File not found.',
- });
- return;
- }
-
- if (node.created_by !== workspaceUser.id) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- //generate presigned url for upload
- const path = `files/${workspaceId}/${input.fileId}_${input.uploadId}${node.attributes.extension}`;
- const command = new PutObjectCommand({
- Bucket: BUCKET_NAMES.FILES,
- Key: path,
- ContentLength: node.attributes.size,
- ContentType: node.attributes.mimeType,
- });
-
- const expiresIn = 60 * 60 * 4; // 4 hours
- const presignedUrl = await getSignedUrl(filesStorage, command, {
- expiresIn,
- });
-
- const data: UploadMetadata = {
- fileId: input.fileId,
- path,
- mimeType: node.attributes.mimeType,
- size: node.attributes.size,
- uploadId: input.uploadId,
- createdAt: new Date().toISOString(),
- };
-
- await redis.set(input.uploadId, JSON.stringify(data), {
- EX: expiresIn,
- });
-
- const output: CreateUploadOutput = {
- uploadId: input.uploadId,
- url: presignedUrl,
- };
-
- res.status(200).json(output);
-});
-
-filesRouter.put(
- '/:workspaceId/:uploadId',
- async (req: Request, res: Response) => {
- const workspaceId = req.params.workspaceId as string;
- const uploadId = req.params.uploadId as string;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', workspaceId)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', workspace.id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const metadataJson = await redis.get(uploadId);
- if (!metadataJson) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Upload not found.',
- });
- return;
- }
-
- const metadata: UploadMetadata = JSON.parse(metadataJson);
- const file = await database
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', metadata.fileId)
- .executeTakeFirst();
-
- if (!file) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'File not found.',
- });
- return;
- }
-
- if (file.attributes.type !== 'file') {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'File not found.',
- });
- return;
- }
-
- if (file.attributes.size !== metadata.size) {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'Size mismatch.',
- });
- return;
- }
-
- const path = metadata.path;
- // check if the file exists in the bucket
- const command = new HeadObjectCommand({
- Bucket: BUCKET_NAMES.FILES,
- Key: path,
- });
-
- try {
- const headObject = await filesStorage.send(command);
-
- // Verify file size matches expected size
- if (headObject.ContentLength !== metadata.size) {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'Uploaded file size does not match expected size',
- });
- return;
- }
-
- // Verify mime type matches expected type
- if (headObject.ContentType !== metadata.mimeType) {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'Uploaded file type does not match expected type',
- });
- return;
- }
- } catch {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'File upload verification failed',
- });
- return;
- }
-
- await database
- .insertInto('uploads')
- .values({
- node_id: file.id,
- upload_id: uploadId,
- workspace_id: workspace.id,
- path: metadata.path,
- mime_type: metadata.mimeType,
- size: metadata.size,
- type: extractFileType(metadata.mimeType),
- created_by: workspaceUser.id,
- created_at: new Date(metadata.createdAt),
- completed_at: new Date(),
- })
- .execute();
-
- await nodeService.updateNode({
- nodeId: file.id,
- userId: workspaceUser.id,
- workspaceId: workspace.id,
- updater: (attributes) => ({
- ...attributes,
- uploadStatus: 'completed',
- uploadId: metadata.uploadId,
- }),
- });
-
- await redis.del(uploadId);
- res.status(200).json({ success: true });
- }
-);
diff --git a/apps/server/src/routes/nodes.ts b/apps/server/src/routes/nodes.ts
deleted file mode 100644
index af73162a..00000000
--- a/apps/server/src/routes/nodes.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { GetTransactionsOutput, hasViewerAccess } from '@colanode/core';
-import { Request, Response, Router } from 'express';
-
-import { database } from '@/data/database';
-import { fetchNodeRole, mapTransaction } from '@/lib/nodes';
-import { ApiError } from '@/types/api';
-
-export const nodesRouter = Router();
-
-nodesRouter.get(
- '/:workspaceId/transactions/:nodeId',
- async (req: Request, res: Response) => {
- const workspaceId = req.params.workspaceId as string;
- const nodeId = req.params.nodeId as string;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', workspaceId)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', workspace.id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const role = await fetchNodeRole(nodeId, workspaceUser.id);
- if (role === null || !hasViewerAccess(role)) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const transactions = await database
- .selectFrom('transactions')
- .selectAll()
- .where('node_id', '=', nodeId)
- .orderBy('version', 'desc')
- .execute();
-
- const output: GetTransactionsOutput = {
- transactions: transactions.map(mapTransaction),
- };
-
- res.status(200).json(output);
- }
-);
diff --git a/apps/server/src/routes/workspaces.ts b/apps/server/src/routes/workspaces.ts
deleted file mode 100644
index e92c96b3..00000000
--- a/apps/server/src/routes/workspaces.ts
+++ /dev/null
@@ -1,612 +0,0 @@
-import {
- AccountStatus,
- generateId,
- IdType,
- WorkspaceCreateInput,
- WorkspaceOutput,
- WorkspaceRole,
- WorkspaceUpdateInput,
- WorkspaceUserInviteResult,
- WorkspaceUserRoleUpdateInput,
- WorkspaceUsersInviteInput,
- WorkspaceUserStatus,
-} from '@colanode/core';
-import { Request, Response, Router } from 'express';
-
-import { database } from '@/data/database';
-import { fetchNode, mapNode, mapTransaction } from '@/lib/nodes';
-import { getNameFromEmail } from '@/lib/utils';
-import { nodeService } from '@/services/node-service';
-import { workspaceService } from '@/services/workspace-service';
-import { ApiError } from '@/types/api';
-
-export const workspacesRouter = Router();
-
-workspacesRouter.post('/', async (req: Request, res: Response) => {
- const input: WorkspaceCreateInput = req.body;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- if (!input.name) {
- res.status(400).json({
- code: ApiError.MissingRequiredFields,
- message: 'Missing required fields.',
- });
- return;
- }
-
- const account = await database
- .selectFrom('accounts')
- .selectAll()
- .where('id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!account) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Account not found.',
- });
- return;
- }
-
- const output = await workspaceService.createWorkspace(account, input);
- res.status(200).json(output);
-});
-
-workspacesRouter.put('/:id', async (req: Request, res: Response) => {
- const id = req.params.id as string;
- const input: WorkspaceUpdateInput = req.body;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', id)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- if (workspaceUser.role !== 'owner') {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- 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', '=', id)
- .returningAll()
- .executeTakeFirst();
-
- if (!updatedWorkspace) {
- res.status(500).json({
- code: ApiError.InternalServerError,
- message: 'Internal server error.',
- });
- return;
- }
-
- await nodeService.updateNode({
- nodeId: updatedWorkspace.id,
- userId: res.locals.account.id,
- workspaceId: id,
- updater: (attributes) => {
- if (attributes.type !== 'workspace') {
- return null;
- }
-
- attributes.name = input.name;
- attributes.description = input.description;
- attributes.avatar = input.avatar;
-
- return attributes;
- },
- });
-
- const output: WorkspaceOutput = {
- id: updatedWorkspace.id,
- name: updatedWorkspace.name,
- description: updatedWorkspace.description,
- avatar: updatedWorkspace.avatar,
- versionId: updatedWorkspace.version_id,
- user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role,
- },
- };
-
- res.status(200).json(output);
-});
-
-workspacesRouter.delete('/:id', async (req: Request, res: Response) => {
- const id = req.params.id as string;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', id)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- if (workspaceUser.role !== 'owner') {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- await database.deleteFrom('workspaces').where('id', '=', id).execute();
-
- res.status(200).json({
- id: workspace.id,
- });
-});
-
-workspacesRouter.get('/:id', async (req: Request, res: Response) => {
- const id = req.params.id as string;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', id)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const output: WorkspaceOutput = {
- id: workspace.id,
- name: workspace.name,
- description: workspace.description,
- avatar: workspace.avatar,
- versionId: workspace.version_id,
- user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role as WorkspaceRole,
- },
- };
-
- res.status(200).json(output);
-});
-
-workspacesRouter.get('/', async (req: Request, res: Response) => {
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspaceUsers = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('account_id', '=', res.locals.account.id)
- .execute();
-
- const workspaceIds = workspaceUsers.map((wa) => wa.workspace_id);
- const workspaces = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', 'in', workspaceIds)
- .execute();
-
- const outputs: WorkspaceOutput[] = [];
- for (const workspace of workspaces) {
- const workspaceUser = workspaceUsers.find(
- (wa) => wa.workspace_id === workspace.id
- );
-
- if (!workspaceUser) {
- continue;
- }
-
- const output: WorkspaceOutput = {
- id: workspace.id,
- name: workspace.name,
- description: workspace.description,
- avatar: workspace.avatar,
- versionId: workspace.version_id,
- user: {
- id: workspaceUser.id,
- accountId: workspaceUser.account_id,
- role: workspaceUser.role as WorkspaceRole,
- },
- };
-
- outputs.push(output);
- }
-
- res.status(200).json(outputs);
-});
-
-workspacesRouter.post('/:id/users', async (req: Request, res: Response) => {
- const id = req.params.id as string;
- const input: WorkspaceUsersInviteInput = req.body;
-
- if (!input.emails || input.emails.length === 0) {
- res.status(400).json({
- code: ApiError.BadRequest,
- message: 'BadRequest.',
- });
- return;
- }
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', id)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const workspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!workspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- if (workspaceUser.role !== 'owner' && workspaceUser.role !== 'admin') {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const workspaceNodeRow = await fetchNode(workspace.id);
- if (!workspaceNodeRow) {
- res.status(500).json({
- code: ApiError.InternalServerError,
- message: 'Something went wrong.',
- });
- return;
- }
-
- const workspaceNode = mapNode(workspaceNodeRow);
- const results: WorkspaceUserInviteResult[] = [];
- for (const email of input.emails) {
- let account = await database
- .selectFrom('accounts')
- .select(['id', 'name', 'email', 'avatar'])
- .where('email', '=', email)
- .executeTakeFirst();
-
- if (!account) {
- account = await database
- .insertInto('accounts')
- .returning(['id', 'name', 'email', 'avatar'])
- .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();
- }
-
- if (!account) {
- results.push({
- email: email,
- result: 'error',
- });
- continue;
- }
-
- const existingWorkspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('account_id', '=', account.id)
- .where('workspace_id', '=', id)
- .executeTakeFirst();
-
- if (existingWorkspaceUser) {
- results.push({
- email: email,
- result: 'exists',
- });
- continue;
- }
-
- const userId = generateId(IdType.User);
- const newWorkspaceUser = await database
- .insertInto('workspace_users')
- .returningAll()
- .values({
- id: userId,
- account_id: account.id,
- workspace_id: id,
- role: input.role,
- created_at: new Date(),
- created_by: res.locals.account.id,
- status: WorkspaceUserStatus.Active,
- version_id: generateId(IdType.Version),
- })
- .executeTakeFirst();
-
- if (!newWorkspaceUser) {
- results.push({
- email: email,
- result: 'error',
- });
- }
-
- await nodeService.createNode({
- nodeId: userId,
- attributes: {
- type: 'user',
- name: account.name,
- email: account.email,
- role: input.role,
- accountId: account.id,
- parentId: id,
- },
- userId: workspaceUser.id,
- workspaceId: id,
- ancestors: [workspaceNode],
- });
-
- results.push({
- email: email,
- result: 'success',
- });
- }
-
- res.status(200).json({
- results: results,
- });
-});
-
-workspacesRouter.put(
- '/:id/users/:userId',
- async (req: Request, res: Response) => {
- const id = req.params.id as string;
- const userId = req.params.userId as string;
- const input: WorkspaceUserRoleUpdateInput = req.body;
-
- if (!res.locals.account) {
- res.status(401).json({
- code: ApiError.Unauthorized,
- message: 'Unauthorized.',
- });
- return;
- }
-
- const workspace = await database
- .selectFrom('workspaces')
- .selectAll()
- .where('id', '=', id)
- .executeTakeFirst();
-
- if (!workspace) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'Workspace not found.',
- });
- return;
- }
-
- const currentWorkspaceUser = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('workspace_id', '=', id)
- .where('account_id', '=', res.locals.account.id)
- .executeTakeFirst();
-
- if (!currentWorkspaceUser) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- if (
- currentWorkspaceUser.role !== 'owner' &&
- currentWorkspaceUser.role !== 'admin'
- ) {
- res.status(403).json({
- code: ApiError.Forbidden,
- message: 'Forbidden.',
- });
- return;
- }
-
- const workspaceUserToUpdate = await database
- .selectFrom('workspace_users')
- .selectAll()
- .where('id', '=', userId)
- .executeTakeFirst();
-
- if (!workspaceUserToUpdate) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'NotFound.',
- });
- return;
- }
-
- const user = await database
- .selectFrom('nodes')
- .selectAll()
- .where('id', '=', workspaceUserToUpdate.id)
- .executeTakeFirst();
-
- if (!user) {
- res.status(404).json({
- code: ApiError.ResourceNotFound,
- message: 'NotFound.',
- });
- return;
- }
-
- await database
- .updateTable('workspace_users')
- .set({
- role: input.role,
- updated_at: new Date(),
- updated_by: currentWorkspaceUser.account_id,
- version_id: generateId(IdType.Version),
- })
- .where('id', '=', userId)
- .execute();
-
- const updateUserOutput = await nodeService.updateNode({
- nodeId: user.id,
- userId: currentWorkspaceUser.account_id,
- workspaceId: workspace.id,
- updater: (attributes) => {
- if (attributes.type !== 'user') {
- return null;
- }
-
- attributes.role = input.role;
- return attributes;
- },
- });
-
- if (!updateUserOutput) {
- res.status(500).json({
- code: ApiError.InternalServerError,
- message: 'Something went wrong.',
- });
- return;
- }
-
- res.status(200).json({
- transaction: mapTransaction(updateUserOutput.transaction),
- });
- }
-);
diff --git a/apps/server/src/services/account-service.ts b/apps/server/src/services/account-service.ts
new file mode 100644
index 00000000..1f97f321
--- /dev/null
+++ b/apps/server/src/services/account-service.ts
@@ -0,0 +1,96 @@
+import {
+ generateId,
+ IdType,
+ LoginOutput,
+ WorkspaceOutput,
+ WorkspaceRole,
+} from '@colanode/core';
+
+import { SelectAccount } from '@/data/schema';
+import { database } from '@/data/database';
+import { workspaceService } from '@/services/workspace-service';
+import { generateToken } from '@/lib/tokens';
+
+class AccountService {
+ public async buildLoginOutput(account: SelectAccount): Promise<LoginOutput> {
+ const workspaceUsers = await database
+ .selectFrom('workspace_users')
+ .where('account_id', '=', account.id)
+ .selectAll()
+ .execute();
+
+ const workspaceOutputs: WorkspaceOutput[] = [];
+ if (workspaceUsers.length > 0) {
+ const workspaceIds = workspaceUsers.map((wu) => wu.workspace_id);
+ const workspaces = await database
+ .selectFrom('workspaces')
+ .where('id', 'in', workspaceIds)
+ .selectAll()
+ .execute();
+
+ for (const workspaceUser of workspaceUsers) {
+ const workspace = workspaces.find(
+ (w) => w.id === workspaceUser.workspace_id
+ );
+
+ if (!workspace) {
+ continue;
+ }
+
+ workspaceOutputs.push({
+ id: workspace.id,
+ name: workspace.name,
+ versionId: workspaceUser.version_id,
+ avatar: workspace.avatar,
+ description: workspace.description,
+ user: {
+ id: workspaceUser.id,
+ accountId: workspaceUser.account_id,
+ role: workspaceUser.role as WorkspaceRole,
+ },
+ });
+ }
+ }
+
+ if (workspaceOutputs.length === 0) {
+ const workspace = await workspaceService.createDefaultWorkspace(account);
+ workspaceOutputs.push(workspace);
+ }
+
+ const deviceId = generateId(IdType.Device);
+ const { token, salt, hash } = generateToken(deviceId);
+
+ const device = await database
+ .insertInto('devices')
+ .values({
+ id: deviceId,
+ account_id: account.id,
+ token_hash: hash,
+ token_salt: salt,
+ token_generated_at: new Date(),
+ type: 1,
+ created_at: new Date(),
+ version: '0.1.0',
+ })
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!device) {
+ throw new Error('Failed to create device.');
+ }
+
+ return {
+ account: {
+ id: account.id,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
+ },
+ workspaces: workspaceOutputs,
+ deviceId: device.id,
+ token,
+ };
+ }
+}
+
+export const accountService = new AccountService();
diff --git a/apps/server/src/services/socket-service.ts b/apps/server/src/services/socket-service.ts
index 734369c7..1dad4d53 100644
--- a/apps/server/src/services/socket-service.ts
+++ b/apps/server/src/services/socket-service.ts
@@ -28,7 +28,7 @@ class SocketService {
});
server.on('upgrade', async (request, socket, head) => {
- if (request.url !== '/v1/synapse') {
+ if (request.url !== '/client/v1/synapse') {
socket.destroy();
return;
}