Skip to content

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

Use registry models in server

Hakan Shehu9d81698e18c6
diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.ts
index 7547ad91..29441062 100644
--- a/apps/server/src/data/schema.ts
+++ b/apps/server/src/data/schema.ts
@@ -1,4 +1,4 @@
-import { ServerNodeAttributes } from '@/types/nodes';
+import { NodeAttributes } from '@colanode/core';
import {
ColumnType,
Insertable,
@@ -87,11 +87,7 @@ interface NodeTable {
parent_id: ColumnType<string | null, never, never>;
type: ColumnType<string, never, never>;
index: ColumnType<string | null, never, never>;
- attributes: JSONColumnType<
- ServerNodeAttributes,
- string | null,
- string | null
- >;
+ attributes: JSONColumnType<NodeAttributes, string | null, string | null>;
state: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
created_at: ColumnType<Date, Date, never>;
updated_at: ColumnType<Date | null, Date | null, Date>;
diff --git a/apps/server/src/lib/nodes.ts b/apps/server/src/lib/nodes.ts
index 919d40f7..a9807453 100644
--- a/apps/server/src/lib/nodes.ts
+++ b/apps/server/src/lib/nodes.ts
@@ -2,8 +2,14 @@ import { database } from '@/data/database';
import { SelectNode } from '@/data/schema';
import { NodeCollaborator, ServerNode } from '@/types/nodes';
import { fromUint8Array } from 'js-base64';
-
-export const mapNode = (node: SelectNode): ServerNode => {
+import {
+ extractNodeCollaborators,
+ extractNodeRole,
+ Node,
+ NodeType,
+} from '@colanode/core';
+
+export const mapServerNode = (node: SelectNode): ServerNode => {
return {
id: node.id,
parentId: node.parent_id,
@@ -22,6 +28,24 @@ export const mapNode = (node: SelectNode): ServerNode => {
};
};
+export const mapNode = (node: SelectNode): Node => {
+ return {
+ id: node.id,
+ parentId: node.parent_id,
+ type: node.type as NodeType,
+ index: node.index,
+ attributes: node.attributes,
+ createdAt: node.created_at.toISOString(),
+ createdBy: node.created_by,
+ updatedAt: node.updated_at?.toISOString() ?? null,
+ updatedBy: node.updated_by ?? null,
+ versionId: node.version_id,
+ serverCreatedAt: node.server_created_at.toISOString(),
+ serverUpdatedAt: node.server_updated_at?.toISOString() ?? null,
+ serverVersionId: node.version_id,
+ } as Node;
+};
+
export const fetchNode = async (nodeId: string): Promise<SelectNode | null> => {
const result = await database
.selectFrom('nodes')
@@ -66,10 +90,7 @@ export const fetchNodeCollaborators = async (
const collaboratorsMap = new Map<string, string>();
for (const ancestor of ancestors) {
- const collaborators = (ancestor.attributes.collaborators ?? {}) as Record<
- string,
- string
- >;
+ const collaborators = extractNodeCollaborators(ancestor.attributes);
for (const [collaboratorId, role] of Object.entries(collaborators)) {
collaboratorsMap.set(collaboratorId, role);
}
@@ -93,7 +114,7 @@ export const fetchNodeRole = async (
return null;
}
- return extractNodeRole(ancestors, collaboratorId);
+ return extractNodeRole(ancestors.map(mapNode), collaboratorId);
};
export const fetchWorkspaceUsers = async (
@@ -107,19 +128,3 @@ export const fetchWorkspaceUsers = async (
return result.map((row) => row.id);
};
-
-export const extractNodeRole = (
- ancestors: SelectNode[],
- collaboratorId: string
-): string | null => {
- let role: string | null = null;
- for (const ancestor of ancestors) {
- const collaborators = ancestor.attributes.collaborators ?? {};
- const collaboratorRole = collaborators[collaboratorId];
- if (collaboratorRole) {
- role = collaboratorRole;
- }
- }
-
- return role;
-};
diff --git a/apps/server/src/queues/events.ts b/apps/server/src/queues/events.ts
index 5e6daa85..9e5b9159 100644
--- a/apps/server/src/queues/events.ts
+++ b/apps/server/src/queues/events.ts
@@ -3,7 +3,7 @@ import { redisConfig } from '@/data/redis';
import { CreateUserNode } from '@/data/schema';
import { filesStorage } from '@/data/storage';
import { BUCKET_NAMES } from '@/data/storage';
-import { generateId, IdType, NodeTypes } from '@colanode/core';
+import { generateId, IdType, NodeAttributes, NodeTypes } from '@colanode/core';
import { fetchNodeCollaborators, fetchWorkspaceUsers } from '@/lib/nodes';
import { synapse } from '@/services/synapse';
import {
@@ -12,7 +12,6 @@ import {
NodeEvent,
NodeUpdatedEvent,
} from '@/types/events';
-import { ServerNodeAttributes } from '@/types/nodes';
import { DeleteObjectCommand } from '@aws-sdk/client-s3';
import { Job, Queue, Worker } from 'bullmq';
import { difference } from 'lodash-es';
@@ -82,7 +81,7 @@ const handleNodeUpdatedEvent = async (
const handleNodeDeletedEvent = async (
event: NodeDeletedEvent
): Promise<void> => {
- if (event.attributes.type === NodeTypes.File) {
+ if (event.attributes.type === 'file') {
const command = new DeleteObjectCommand({
Bucket: BUCKET_NAMES.FILES,
Key: `files/${event.id}${event.attributes.extension}`,
@@ -263,10 +262,10 @@ const checkForCollaboratorsChange = async (
}
};
-const extractCollaboratorIds = (collaborators: ServerNodeAttributes) => {
- if (!collaborators.collaborators) {
- return [];
+const extractCollaboratorIds = (collaborators: NodeAttributes) => {
+ if ('collaborators' in collaborators && collaborators.collaborators) {
+ return Object.keys(collaborators.collaborators).sort();
}
- return Object.keys(collaborators.collaborators).sort();
+ return [];
};
diff --git a/apps/server/src/routes/accounts.ts b/apps/server/src/routes/accounts.ts
index 1d9da9e0..1ae9bff8 100644
--- a/apps/server/src/routes/accounts.ts
+++ b/apps/server/src/routes/accounts.ts
@@ -11,17 +11,16 @@ import {
} from '@/types/accounts';
import axios from 'axios';
import { ApiError, ColanodeRequest, ColanodeResponse } from '@/types/api';
-import { generateId, IdType } from '@colanode/core';
+import { generateId, IdType, NodeAttributes } from '@colanode/core';
import { database } from '@/data/database';
import bcrypt from 'bcrypt';
import { WorkspaceOutput, WorkspaceRole } from '@/types/workspaces';
import { authMiddleware } from '@/middlewares/auth';
import { generateToken } from '@/lib/tokens';
-import { mapNode } from '@/lib/nodes';
+import { mapServerNode } from '@/lib/nodes';
import { enqueueTask } from '@/queues/tasks';
import * as Y from 'yjs';
import { CompiledQuery } from 'kysely';
-import { ServerNodeAttributes } from '@/types/nodes';
import { NodeUpdatedEvent } from '@/types/events';
import { enqueueEvent } from '@/queues/events';
import { SelectAccount } from '@/data/schema';
@@ -311,6 +310,10 @@ accountsRouter.put(
);
for (const user of users) {
+ if (user.attributes.type !== 'user') {
+ throw new Error('User node not found.');
+ }
+
const name = user.attributes.name;
const avatar = user.attributes.avatar;
@@ -330,7 +333,7 @@ accountsRouter.put(
attributesMap.set('avatar', input.avatar);
}
- const attributes = attributesMap.toJSON() as ServerNodeAttributes;
+ const attributes = attributesMap.toJSON() as NodeAttributes;
const attributesJson = JSON.stringify(attributes);
const state = Y.encodeStateAsUpdate(doc);
@@ -446,7 +449,7 @@ const buildLoginOutput = async (
id: workspaceUser.id,
accountId: workspaceUser.account_id,
role: workspaceUser.role as WorkspaceRole,
- node: mapNode(userNode),
+ node: mapServerNode(userNode),
},
});
}
diff --git a/apps/server/src/routes/files.ts b/apps/server/src/routes/files.ts
index cff2de25..cdde8667 100644
--- a/apps/server/src/routes/files.ts
+++ b/apps/server/src/routes/files.ts
@@ -70,6 +70,13 @@ filesRouter.get(
});
}
+ if (node.attributes.type !== 'file') {
+ return res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'File not found.',
+ });
+ }
+
//generate presigned url for download
const command = new GetObjectCommand({
Bucket: BUCKET_NAMES.FILES,
@@ -145,6 +152,13 @@ filesRouter.post(
});
}
+ if (node.attributes.type !== 'file') {
+ return res.status(400).json({
+ code: ApiError.BadRequest,
+ message: 'File not found.',
+ });
+ }
+
//generate presigned url for upload
const command = new PutObjectCommand({
Bucket: BUCKET_NAMES.FILES,
diff --git a/apps/server/src/routes/sync.ts b/apps/server/src/routes/sync.ts
index d1e43398..66dc9b15 100644
--- a/apps/server/src/routes/sync.ts
+++ b/apps/server/src/routes/sync.ts
@@ -14,8 +14,7 @@ import {
SyncLocalChangesInput,
} from '@/types/sync';
import { SelectWorkspaceUser } from '@/data/schema';
-import { ServerNodeAttributes } from '@/types/nodes';
-import { fromUint8Array, toUint8Array } from 'js-base64';
+import { toUint8Array } from 'js-base64';
import {
NodeCreatedEvent,
NodeDeletedEvent,
@@ -23,8 +22,13 @@ import {
} from '@/types/events';
import { enqueueEvent } from '@/queues/events';
import { synapse } from '@/services/synapse';
-import { getValidator } from '@/validators';
-import { mapNode } from '@/lib/nodes';
+import { fetchNodeAncestors, mapNode, mapServerNode } from '@/lib/nodes';
+import {
+ Node,
+ NodeAttributes,
+ NodeMutationContext,
+ registry,
+} from '@colanode/core';
export const syncRouter = Router();
@@ -121,16 +125,34 @@ const handleCreateNodeChange = async (
Y.applyUpdate(doc, toUint8Array(changeData.state));
const attributesMap = doc.getMap('attributes');
- const attributes = attributesMap.toJSON() as ServerNodeAttributes;
+ const attributes = attributesMap.toJSON() as NodeAttributes;
- const validator = getValidator(attributes.type);
- if (!validator) {
+ const model = registry[attributes.type];
+ if (!model) {
return {
status: 'error',
};
}
- if (!(await validator.canCreate(workspaceUser, attributes))) {
+ if (!model.schema.safeParse(attributes).success) {
+ return {
+ status: 'error',
+ };
+ }
+
+ const ancestorRows = attributes.parentId
+ ? await fetchNodeAncestors(attributes.parentId)
+ : [];
+
+ const ancestors = ancestorRows.map(mapNode);
+ const context = new NodeMutationContext(
+ workspaceUser.account_id,
+ workspaceUser.workspace_id,
+ changeData.createdBy,
+ ancestors
+ );
+
+ if (!model.canCreate(context, attributes)) {
return {
status: 'error',
};
@@ -197,24 +219,40 @@ const handleUpdateNodeChange = async (
}
const attributesMap = doc.getMap('attributes');
- const attributes = attributesMap.toJSON() as ServerNodeAttributes;
+ const attributes = attributesMap.toJSON() as NodeAttributes;
const attributesJson = JSON.stringify(attributes);
const state = Y.encodeStateAsUpdate(doc);
- const validator = getValidator(existingNode.type);
- if (!validator) {
+ const model = registry[attributes.type];
+ if (!model) {
return {
status: 'error',
};
}
- if (
- !(await validator.canUpdate(
- workspaceUser,
- mapNode(existingNode),
- attributes
- ))
- ) {
+ if (!model.schema.safeParse(attributes).success) {
+ return {
+ status: 'error',
+ };
+ }
+
+ const ancestorRows = await fetchNodeAncestors(existingNode.id);
+ const ancestors = ancestorRows.map(mapNode);
+ const node = ancestors.find((ancestor) => ancestor.id === existingNode.id);
+ if (!node) {
+ return {
+ status: 'error',
+ };
+ }
+
+ const context = new NodeMutationContext(
+ workspaceUser.account_id,
+ workspaceUser.workspace_id,
+ changeData.updatedBy,
+ ancestors
+ );
+
+ if (!model.canUpdate(context, node, attributes)) {
return {
status: 'error',
};
@@ -282,14 +320,30 @@ const handleDeleteNodeChange = async (
};
}
- const validator = getValidator(existingNode.type);
- if (!validator) {
+ const model = registry[existingNode.type];
+ if (!model) {
return {
status: 'error',
};
}
- if (!(await validator.canDelete(workspaceUser, mapNode(existingNode)))) {
+ const ancestorRows = await fetchNodeAncestors(existingNode.id);
+ const ancestors = ancestorRows.map(mapNode);
+ const node = ancestors.find((ancestor) => ancestor.id === existingNode.id);
+ if (!node) {
+ return {
+ status: 'error',
+ };
+ }
+
+ const context = new NodeMutationContext(
+ workspaceUser.account_id,
+ workspaceUser.workspace_id,
+ changeData.deletedBy,
+ ancestors
+ );
+
+ if (!model.canDelete(context, node)) {
return {
status: 'error',
};
diff --git a/apps/server/src/routes/workspaces.ts b/apps/server/src/routes/workspaces.ts
index 208f2032..8e636fc2 100644
--- a/apps/server/src/routes/workspaces.ts
+++ b/apps/server/src/routes/workspaces.ts
@@ -23,7 +23,7 @@ import {
import { getNameFromEmail } from '@/lib/utils';
import { AccountStatus } from '@/types/accounts';
import { ServerNode } from '@/types/nodes';
-import { mapNode } from '@/lib/nodes';
+import { mapServerNode } from '@/lib/nodes';
import { NodeCreatedEvent } from '@/types/events';
import { enqueueEvent } from '@/queues/events';
@@ -272,7 +272,7 @@ workspacesRouter.put(
id: workspaceUser.id,
accountId: workspaceUser.account_id,
role: workspaceUser.role,
- node: mapNode(userNode),
+ node: mapServerNode(userNode),
},
};
@@ -396,7 +396,7 @@ workspacesRouter.get(
id: workspaceUser.id,
accountId: workspaceUser.account_id,
role: workspaceUser.role as WorkspaceRole,
- node: mapNode(userNode),
+ node: mapServerNode(userNode),
},
};
@@ -464,7 +464,7 @@ workspacesRouter.get(
id: workspaceUser.id,
accountId: workspaceUser.account_id,
role: workspaceUser.role as WorkspaceRole,
- node: mapNode(userNode),
+ node: mapServerNode(userNode),
},
};
@@ -610,7 +610,7 @@ workspacesRouter.post(
});
}
- users.push(mapNode(existingUser));
+ users.push(mapServerNode(existingUser));
continue;
}
diff --git a/apps/server/src/types/events.ts b/apps/server/src/types/events.ts
index 6b7bb2b1..9d8c654f 100644
--- a/apps/server/src/types/events.ts
+++ b/apps/server/src/types/events.ts
@@ -1,4 +1,4 @@
-import { ServerNodeAttributes } from '@/types/nodes';
+import { NodeAttributes } from '@colanode/core';
export type NodeEvent = NodeCreatedEvent | NodeUpdatedEvent | NodeDeletedEvent;
@@ -6,7 +6,7 @@ export type NodeCreatedEvent = {
type: 'node_created';
id: string;
workspaceId: string;
- attributes: ServerNodeAttributes;
+ attributes: NodeAttributes;
createdBy: string;
createdAt: string;
serverCreatedAt: string;
@@ -17,8 +17,8 @@ export type NodeUpdatedEvent = {
type: 'node_updated';
id: string;
workspaceId: string;
- beforeAttributes: ServerNodeAttributes;
- afterAttributes: ServerNodeAttributes;
+ beforeAttributes: NodeAttributes;
+ afterAttributes: NodeAttributes;
updatedBy: string;
updatedAt: string;
serverUpdatedAt: string;
@@ -29,6 +29,6 @@ export type NodeDeletedEvent = {
type: 'node_deleted';
id: string;
workspaceId: string;
- attributes: ServerNodeAttributes;
+ attributes: NodeAttributes;
deletedAt: string;
};
diff --git a/apps/server/src/types/nodes.ts b/apps/server/src/types/nodes.ts
index 558e0865..8f3480b3 100644
--- a/apps/server/src/types/nodes.ts
+++ b/apps/server/src/types/nodes.ts
@@ -1,10 +1,12 @@
+import { NodeAttributes } from '@colanode/core';
+
export type ServerNode = {
id: string;
workspaceId: string;
parentId?: string | null;
type: string;
index: string | null;
- attributes: ServerNodeAttributes;
+ attributes: NodeAttributes;
state: string;
createdAt: Date;
createdBy: string;
@@ -15,14 +17,6 @@ export type ServerNode = {
serverUpdatedAt?: Date | null;
};
-export type ServerNodeAttributes = {
- type: string;
- parentId?: string | null;
- index?: string | null;
- content?: NodeBlock[] | null;
- [key: string]: any;
-};
-
export type NodeBlock = {
type: string;
text?: string | null;
diff --git a/apps/server/src/types/validators.ts b/apps/server/src/types/validators.ts
deleted file mode 100644
index 90e98b15..00000000
--- a/apps/server/src/types/validators.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-
-export interface Validator {
- canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes,
- ): Promise<boolean>;
-
- canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes,
- ): Promise<boolean>;
-
- canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- ): Promise<boolean>;
-}
diff --git a/apps/server/src/validators/channel-validator.ts b/apps/server/src/validators/channel-validator.ts
deleted file mode 100644
index 6ba50f07..00000000
--- a/apps/server/src/validators/channel-validator.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { hasAdminAccess, hasEditorAccess } from '@/lib/constants';
-import { fetchNodeRole } from '@/lib/nodes';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-import { isEqual } from 'lodash-es';
-
-export class ChannelValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- if (!attributes.parentId) {
- return false;
- }
-
- const parentId = attributes.parentId;
- const role = await fetchNodeRole(parentId, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- if (attributes.collaborators) {
- return hasAdminAccess(role);
- }
-
- return hasEditorAccess(role);
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- if (!isEqual(node.attributes.collaborators, attributes.collaborators)) {
- return hasAdminAccess(role);
- }
-
- return hasEditorAccess(role);
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode
- ): Promise<boolean> {
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-}
diff --git a/apps/server/src/validators/chat-validator.ts b/apps/server/src/validators/chat-validator.ts
deleted file mode 100644
index cfc25a40..00000000
--- a/apps/server/src/validators/chat-validator.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-import { WorkspaceRole } from '@/types/workspaces';
-
-export class ChatValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes,
- ): Promise<boolean> {
- if (workspaceUser.role === WorkspaceRole.Viewer) {
- return false;
- }
-
- const collaborators = attributes.collaborators ?? {};
- if (!collaborators[workspaceUser.id]) {
- return false;
- }
-
- return true;
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes,
- ): Promise<boolean> {
- return false;
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- ): Promise<boolean> {
- return false;
- }
-}
diff --git a/apps/server/src/validators/database-validator.ts b/apps/server/src/validators/database-validator.ts
deleted file mode 100644
index 1c430653..00000000
--- a/apps/server/src/validators/database-validator.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { hasEditorAccess } from '@/lib/constants';
-import { fetchNodeRole } from '@/lib/nodes';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-
-export class DatabaseValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes,
- ): Promise<boolean> {
- if (!attributes.parentId) {
- return false;
- }
-
- const parentId = attributes.parentId;
- const role = await fetchNodeRole(parentId, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes,
- ): Promise<boolean> {
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- ): Promise<boolean> {
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-}
diff --git a/apps/server/src/validators/file-validator.ts b/apps/server/src/validators/file-validator.ts
deleted file mode 100644
index b06c7a65..00000000
--- a/apps/server/src/validators/file-validator.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { hasEditorAccess } from '@/lib/constants';
-import { NodeTypes } from '@colanode/core';
-import { extractNodeRole, fetchNodeAncestors } from '@/lib/nodes';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-
-export class FileValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- if (!attributes.parentId) {
- return false;
- }
-
- const ancestors = await fetchNodeAncestors(attributes.parentId);
- if (ancestors.length === 0) {
- return false;
- }
-
- const parent = ancestors.find(
- (ancestor) => ancestor.id === attributes.parentId
- );
-
- if (!parent) {
- return false;
- }
-
- if (parent.type === NodeTypes.File) {
- return parent.created_by === workspaceUser.id;
- }
-
- const role = extractNodeRole(ancestors, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- if (!attributes.parentId) {
- return false;
- }
-
- const ancestors = await fetchNodeAncestors(attributes.parentId);
- if (ancestors.length === 0) {
- return false;
- }
-
- const parent = ancestors.find(
- (ancestor) => ancestor.id === attributes.parentId
- );
-
- if (!parent) {
- return false;
- }
-
- if (parent.type === NodeTypes.File) {
- return parent.created_by === workspaceUser.id;
- }
-
- const role = extractNodeRole(ancestors, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode
- ): Promise<boolean> {
- if (!node.parentId) {
- return false;
- }
-
- const ancestors = await fetchNodeAncestors(node.parentId);
- if (ancestors.length === 0) {
- return false;
- }
-
- const parent = ancestors.find((ancestor) => ancestor.id === node.parentId);
- if (!parent) {
- return false;
- }
-
- if (parent.type === NodeTypes.File) {
- return parent.created_by === workspaceUser.id;
- }
-
- const role = extractNodeRole(ancestors, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-}
diff --git a/apps/server/src/validators/folder-validator.ts b/apps/server/src/validators/folder-validator.ts
deleted file mode 100644
index a11608c9..00000000
--- a/apps/server/src/validators/folder-validator.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { hasAdminAccess, hasEditorAccess } from '@/lib/constants';
-import { fetchNodeRole } from '@/lib/nodes';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-import { isEqual } from 'lodash-es';
-
-export class FolderValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- if (!attributes.parentId) {
- return false;
- }
-
- const parentId = attributes.parentId;
- const role = await fetchNodeRole(parentId, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- if (attributes.collaborators) {
- return hasAdminAccess(role);
- }
-
- return hasEditorAccess(role);
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- if (!isEqual(node.attributes.collaborators, attributes.collaborators)) {
- return hasAdminAccess(role);
- }
-
- return hasEditorAccess(role);
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode
- ): Promise<boolean> {
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-}
diff --git a/apps/server/src/validators/index.ts b/apps/server/src/validators/index.ts
deleted file mode 100644
index 59e3a1e9..00000000
--- a/apps/server/src/validators/index.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { NodeTypes } from '@colanode/core';
-import { Validator } from '@/types/validators';
-import { ChannelValidator } from '@/validators/channel-validator';
-import { ChatValidator } from '@/validators/chat-validator';
-import { DatabaseValidator } from '@/validators/database-validator';
-import { FileValidator } from '@/validators/file-validator';
-import { FolderValidator } from '@/validators/folder-validator';
-import { MessageValidator } from '@/validators/message-validator';
-import { PageValidator } from '@/validators/page-validator';
-import { RecordValidator } from '@/validators/record-validator';
-import { SpaceValidator } from '@/validators/space-validator';
-
-const validators: Record<string, Validator> = {
- [NodeTypes.Channel]: new ChannelValidator(),
- [NodeTypes.Chat]: new ChatValidator(),
- [NodeTypes.Database]: new DatabaseValidator(),
- [NodeTypes.File]: new FileValidator(),
- [NodeTypes.Folder]: new FolderValidator(),
- [NodeTypes.Message]: new MessageValidator(),
- [NodeTypes.Page]: new PageValidator(),
- [NodeTypes.Record]: new RecordValidator(),
- [NodeTypes.Space]: new SpaceValidator(),
-};
-
-export const getValidator = (type: string): Validator | undefined => {
- return validators[type];
-};
diff --git a/apps/server/src/validators/message-validator.ts b/apps/server/src/validators/message-validator.ts
deleted file mode 100644
index e0830cc8..00000000
--- a/apps/server/src/validators/message-validator.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { hasAdminAccess, hasCollaboratorAccess } from '@/lib/constants';
-import { fetchNodeRole } from '@/lib/nodes';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-import { isEqual } from 'lodash-es';
-
-export class MessageValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- if (!attributes.parentId) {
- return false;
- }
-
- const parentId = attributes.parentId;
- const role = await fetchNodeRole(parentId, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasCollaboratorAccess(role);
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- if (
- !isEqual(attributes.content, node.attributes.content) &&
- node.createdBy !== workspaceUser.id
- ) {
- return false;
- }
-
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasCollaboratorAccess(role);
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode
- ): Promise<boolean> {
- if (node.createdBy === workspaceUser.id) {
- return true;
- }
-
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasAdminAccess(role);
- }
-}
diff --git a/apps/server/src/validators/page-validator.ts b/apps/server/src/validators/page-validator.ts
deleted file mode 100644
index 0967f3d3..00000000
--- a/apps/server/src/validators/page-validator.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { hasAdminAccess, hasEditorAccess } from '@/lib/constants';
-import { isEqual } from 'lodash-es';
-import { fetchNodeRole } from '@/lib/nodes';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-
-export class PageValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- if (!attributes.parentId) {
- return false;
- }
-
- const parentId = attributes.parentId;
- const role = await fetchNodeRole(parentId, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- if (attributes.collaborators) {
- return hasAdminAccess(role);
- }
-
- return hasEditorAccess(role);
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- if (!isEqual(node.attributes.collaborators, attributes.collaborators)) {
- return hasAdminAccess(role);
- }
-
- return hasEditorAccess(role);
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode
- ): Promise<boolean> {
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-}
diff --git a/apps/server/src/validators/record-validator.ts b/apps/server/src/validators/record-validator.ts
deleted file mode 100644
index 2b26d073..00000000
--- a/apps/server/src/validators/record-validator.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { hasCollaboratorAccess, hasEditorAccess } from '@/lib/constants';
-import { fetchNodeRole } from '@/lib/nodes';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-
-export class RecordValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes,
- ): Promise<boolean> {
- if (!attributes.parentId) {
- return false;
- }
-
- const parentId = attributes.parentId;
- const role = await fetchNodeRole(parentId, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasCollaboratorAccess(role);
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes,
- ): Promise<boolean> {
- if (node.createdBy === workspaceUser.id) {
- return true;
- }
-
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- ): Promise<boolean> {
- if (node.createdBy === workspaceUser.id) {
- return true;
- }
-
- const role = await fetchNodeRole(node.id, workspaceUser.id);
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-}
diff --git a/apps/server/src/validators/space-validator.ts b/apps/server/src/validators/space-validator.ts
deleted file mode 100644
index d6a2378f..00000000
--- a/apps/server/src/validators/space-validator.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { SelectWorkspaceUser } from '@/data/schema';
-import { hasAdminAccess, hasEditorAccess } from '@/lib/constants';
-import { ServerNode, ServerNodeAttributes } from '@/types/nodes';
-import { Validator } from '@/types/validators';
-import { WorkspaceRole } from '@/types/workspaces';
-
-export class SpaceValidator implements Validator {
- async canCreate(
- workspaceUser: SelectWorkspaceUser,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- if (workspaceUser.role === WorkspaceRole.Viewer) {
- return false;
- }
-
- const collaborators = attributes.collaborators ?? {};
- const role = collaborators[workspaceUser.id];
-
- return hasAdminAccess(role);
- }
-
- async canUpdate(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode,
- attributes: ServerNodeAttributes
- ): Promise<boolean> {
- const collaborators = attributes.collaborators ?? {};
- const role = collaborators[workspaceUser.id];
- if (!role) {
- return false;
- }
-
- return hasEditorAccess(role);
- }
-
- async canDelete(
- workspaceUser: SelectWorkspaceUser,
- node: ServerNode
- ): Promise<boolean> {
- const collaborators = node.attributes.collaborators ?? {};
- const role = collaborators[workspaceUser.id];
- if (!role) {
- return false;
- }
-
- return hasAdminAccess(role);
- }
-}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 641dc37c..996ec705 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,5 +1,6 @@
export * from './lib/constants';
export * from './lib/id';
+export * from './lib/nodes';
export * from './registry/block';
export * from './registry/channel';
export * from './registry/chat';
diff --git a/packages/core/src/lib/nodes.ts b/packages/core/src/lib/nodes.ts
new file mode 100644
index 00000000..7bf006cf
--- /dev/null
+++ b/packages/core/src/lib/nodes.ts
@@ -0,0 +1,27 @@
+import { Node, NodeAttributes, NodeRole } from '../index';
+
+export const extractNodeCollaborators = (
+ attributes: NodeAttributes
+): Record<string, NodeRole> => {
+ if ('collaborators' in attributes && attributes.collaborators) {
+ return attributes.collaborators as Record<string, NodeRole>;
+ }
+
+ return {};
+};
+
+export const extractNodeRole = (
+ ancestors: Node[],
+ collaboratorId: string
+): NodeRole | null => {
+ let role: NodeRole | null = null;
+ for (const ancestor of ancestors) {
+ const collaborators = extractNodeCollaborators(ancestor.attributes);
+ const collaboratorRole = collaborators[collaboratorId];
+ if (collaboratorRole) {
+ role = collaboratorRole;
+ }
+ }
+
+ return role;
+};
diff --git a/packages/core/src/registry/core.ts b/packages/core/src/registry/core.ts
index 68e7d098..e425a4f8 100644
--- a/packages/core/src/registry/core.ts
+++ b/packages/core/src/registry/core.ts
@@ -1,5 +1,6 @@
import { ZodSchema } from 'zod';
import { Node, NodeAttributes } from './';
+import { extractNodeRole } from '../lib/nodes';
export type NodeRole = 'admin' | 'editor' | 'collaborator' | 'viewer';
@@ -8,7 +9,7 @@ export class NodeMutationContext {
public workspaceId: string;
public userId: string;
public ancestors: Node[];
- public role: NodeRole = 'viewer';
+ public role: NodeRole | null;
constructor(
accountId: string,
@@ -20,6 +21,7 @@ export class NodeMutationContext {
this.workspaceId = workspaceId;
this.userId = userId;
this.ancestors = ancestors;
+ this.role = extractNodeRole(ancestors, userId);
}
public hasAdminAccess = () => {
diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.ts
index cf92f91d..f136180c 100644
--- a/packages/core/src/registry/index.ts
+++ b/packages/core/src/registry/index.ts
@@ -87,6 +87,18 @@ export type UserNode = NodeBase & {
attributes: UserAttributes;
};
+export type NodeType =
+ | 'channel'
+ | 'chat'
+ | 'database'
+ | 'file'
+ | 'folder'
+ | 'message'
+ | 'page'
+ | 'record'
+ | 'space'
+ | 'user';
+
export type Node =
| ChannelNode
| ChatNode