Skip to content

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

Improve permission checks

Hakan Shehu83de712f4cf2
diff --git a/apps/desktop/src/main/mutations/channels/channel-create.ts b/apps/desktop/src/main/mutations/channels/channel-create.ts
index 145cf584..8431b319 100644
--- a/apps/desktop/src/main/mutations/channels/channel-create.ts
+++ b/apps/desktop/src/main/mutations/channels/channel-create.ts
@@ -38,7 +38,6 @@ export class ChannelCreateMutationHandler
name: input.name,
avatar: input.avatar,
parentId: input.spaceId,
- collaborators: null,
};
await entryService.createEntry(input.userId, { id, attributes });
diff --git a/apps/desktop/src/main/mutations/chats/chat-create.ts b/apps/desktop/src/main/mutations/chats/chat-create.ts
index 8a8df082..ba0413cd 100644
--- a/apps/desktop/src/main/mutations/chats/chat-create.ts
+++ b/apps/desktop/src/main/mutations/chats/chat-create.ts
@@ -44,8 +44,8 @@ export class ChatCreateMutationHandler
type: 'chat',
parentId: input.workspaceId,
collaborators: {
- [input.userId]: 'collaborator',
- [input.otherUserId]: 'collaborator',
+ [input.userId]: 'admin',
+ [input.otherUserId]: 'admin',
},
};
diff --git a/apps/desktop/src/main/mutations/databases/field-create.ts b/apps/desktop/src/main/mutations/databases/field-create.ts
index 84e6aca2..fca9371e 100644
--- a/apps/desktop/src/main/mutations/databases/field-create.ts
+++ b/apps/desktop/src/main/mutations/databases/field-create.ts
@@ -14,6 +14,8 @@ import {
FieldCreateMutationOutput,
} from '@/shared/mutations/databases/field-create';
import { MutationError } from '@/shared/mutations';
+import { databaseService } from '@/main/data/database-service';
+import { fetchEntry } from '@/main/utils';
export class FieldCreateMutationHandler
implements MutationHandler<FieldCreateMutationInput>
@@ -29,11 +31,15 @@ export class FieldCreateMutationHandler
);
}
- const relationDatabase = await entryService.fetchEntry(
- input.relationDatabaseId,
+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(
input.userId
);
+ const relationDatabase = await fetchEntry(
+ workspaceDatabase,
+ input.relationDatabaseId
+ );
+
if (!relationDatabase || relationDatabase.type !== 'database') {
throw new MutationError(
'relation_database_not_found',
diff --git a/apps/desktop/src/main/mutations/files/file-create.ts b/apps/desktop/src/main/mutations/files/file-create.ts
index fc4e62ea..7b762b6d 100644
--- a/apps/desktop/src/main/mutations/files/file-create.ts
+++ b/apps/desktop/src/main/mutations/files/file-create.ts
@@ -1,4 +1,5 @@
import {
+ canCreateFile,
CreateFileMutationData,
FileStatus,
generateId,
@@ -14,7 +15,7 @@ import {
import { MutationError } from '@/shared/mutations';
import { databaseService } from '@/main/data/database-service';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapFile } from '@/main/utils';
+import { fetchEntry, fetchUser, mapEntry, mapFile } from '@/main/utils';
export class FileCreateMutationHandler
implements MutationHandler<FileCreateMutationInput>
@@ -34,7 +35,41 @@ export class FileCreateMutationHandler
input.userId
);
+ const user = await fetchUser(workspaceDatabase, input.userId);
+ if (!user) {
+ throw new MutationError('user_not_found', 'User not found.');
+ }
+
+ const entry = await fetchEntry(workspaceDatabase, input.entryId);
+ if (!entry) {
+ throw new MutationError('entry_not_found', 'Entry not found.');
+ }
+
+ const root = await fetchEntry(workspaceDatabase, input.rootId);
+ if (!root) {
+ throw new MutationError('entry_not_found', 'Entry not found.');
+ }
+
const fileId = generateId(IdType.File);
+ if (
+ !canCreateFile({
+ user: {
+ userId: input.userId,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ file: {
+ id: fileId,
+ parentId: input.parentId,
+ },
+ })
+ ) {
+ throw new MutationError(
+ 'unauthorized',
+ 'You are not allowed to upload a file in this entry.'
+ );
+ }
fileService.copyFileToWorkspace(
input.filePath,
diff --git a/apps/desktop/src/main/mutations/files/file-delete.ts b/apps/desktop/src/main/mutations/files/file-delete.ts
index a08a4b14..f2ba8e73 100644
--- a/apps/desktop/src/main/mutations/files/file-delete.ts
+++ b/apps/desktop/src/main/mutations/files/file-delete.ts
@@ -1,4 +1,9 @@
-import { DeleteFileMutationData, generateId, IdType } from '@colanode/core';
+import {
+ canDeleteFile,
+ DeleteFileMutationData,
+ generateId,
+ IdType,
+} from '@colanode/core';
import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
@@ -7,7 +12,8 @@ import {
FileDeleteMutationOutput,
} from '@/shared/mutations/files/file-delete';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapFile } from '@/main/utils';
+import { fetchEntry, fetchUser, mapEntry, mapFile } from '@/main/utils';
+import { MutationError } from '@/shared/mutations';
export class FileDeleteMutationHandler
implements MutationHandler<FileDeleteMutationInput>
@@ -26,9 +32,46 @@ export class FileDeleteMutationHandler
.executeTakeFirst();
if (!file) {
- return {
- success: true,
- };
+ throw new MutationError(
+ 'file_not_found',
+ 'File could not be found or has been already deleted.'
+ );
+ }
+
+ const user = await fetchUser(workspaceDatabase, input.userId);
+ if (!user) {
+ throw new MutationError('user_not_found', 'User not found.');
+ }
+
+ const entry = await fetchEntry(workspaceDatabase, file.root_id);
+ if (!entry) {
+ throw new MutationError('entry_not_found', 'Entry not found.');
+ }
+
+ const root = await fetchEntry(workspaceDatabase, entry.root_id);
+ if (!root) {
+ throw new MutationError('entry_not_found', 'Entry not found.');
+ }
+
+ if (
+ !canDeleteFile({
+ user: {
+ userId: input.userId,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ file: {
+ id: input.fileId,
+ parentId: file.parent_id,
+ createdBy: file.created_by,
+ },
+ })
+ ) {
+ throw new MutationError(
+ 'unauthorized',
+ 'You are not allowed to delete this file.'
+ );
}
const deletedAt = new Date().toISOString();
diff --git a/apps/desktop/src/main/mutations/messages/message-create.ts b/apps/desktop/src/main/mutations/messages/message-create.ts
index 8c8a58f3..4a98316c 100644
--- a/apps/desktop/src/main/mutations/messages/message-create.ts
+++ b/apps/desktop/src/main/mutations/messages/message-create.ts
@@ -1,5 +1,6 @@
import {
Block,
+ canCreateMessage,
CreateFileMutationData,
CreateMessageMutationData,
EditorNodeTypes,
@@ -24,7 +25,14 @@ import {
} from '@/main/data/workspace/schema';
import { databaseService } from '@/main/data/database-service';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapFile, mapFileState, mapMessage } from '@/main/utils';
+import {
+ fetchEntry,
+ fetchUser,
+ mapEntry,
+ mapFile,
+ mapFileState,
+ mapMessage,
+} from '@/main/utils';
export class MessageCreateMutationHandler
implements MutationHandler<MessageCreateMutationInput>
@@ -36,6 +44,37 @@ export class MessageCreateMutationHandler
input.userId
);
+ const user = await fetchUser(workspaceDatabase, input.userId);
+ if (!user) {
+ throw new MutationError('user_not_found', 'User not found.');
+ }
+
+ const entry = await fetchEntry(workspaceDatabase, input.conversationId);
+ if (!entry) {
+ throw new MutationError('entry_not_found', 'Conversation not found.');
+ }
+
+ const root = await fetchEntry(workspaceDatabase, input.rootId);
+ if (!root) {
+ throw new MutationError('entry_not_found', 'Conversation not found.');
+ }
+
+ if (
+ !canCreateMessage({
+ user: {
+ userId: input.userId,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ })
+ ) {
+ throw new MutationError(
+ 'unauthorized',
+ 'You are not allowed to create a message in this conversation.'
+ );
+ }
+
const editorContent = input.content.content ?? [];
const messageId = generateId(IdType.Message);
const createdAt = new Date().toISOString();
diff --git a/apps/desktop/src/main/mutations/messages/message-delete.ts b/apps/desktop/src/main/mutations/messages/message-delete.ts
index 2fdbf2cc..b55a6b90 100644
--- a/apps/desktop/src/main/mutations/messages/message-delete.ts
+++ b/apps/desktop/src/main/mutations/messages/message-delete.ts
@@ -1,4 +1,9 @@
-import { DeleteMessageMutationData, generateId, IdType } from '@colanode/core';
+import {
+ canDeleteMessage,
+ DeleteMessageMutationData,
+ generateId,
+ IdType,
+} from '@colanode/core';
import { databaseService } from '@/main/data/database-service';
import { MutationHandler } from '@/main/types';
@@ -7,7 +12,8 @@ import {
MessageDeleteMutationOutput,
} from '@/shared/mutations/messages/message-delete';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapMessage } from '@/main/utils';
+import { fetchEntry, fetchUser, mapEntry, mapMessage } from '@/main/utils';
+import { MutationError } from '@/shared/mutations';
export class MessageDeleteMutationHandler
implements MutationHandler<MessageDeleteMutationInput>
@@ -31,6 +37,41 @@ export class MessageDeleteMutationHandler
};
}
+ const user = await fetchUser(workspaceDatabase, input.userId);
+ if (!user) {
+ throw new MutationError('user_not_found', 'User not found.');
+ }
+
+ const entry = await fetchEntry(workspaceDatabase, message.entry_id);
+ if (!entry) {
+ throw new MutationError('entry_not_found', 'Conversation not found.');
+ }
+
+ const root = await fetchEntry(workspaceDatabase, message.root_id);
+ if (!root) {
+ throw new MutationError('entry_not_found', 'Conversation not found.');
+ }
+
+ if (
+ !canDeleteMessage({
+ user: {
+ userId: input.userId,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ message: {
+ id: message.id,
+ createdBy: message.created_by,
+ },
+ })
+ ) {
+ throw new MutationError(
+ 'unauthorized',
+ 'You are not allowed to delete this message.'
+ );
+ }
+
const deletedAt = new Date().toISOString();
const deleteMessageMutationData: DeleteMessageMutationData = {
id: input.messageId,
diff --git a/apps/desktop/src/main/mutations/messages/message-reaction-create.ts b/apps/desktop/src/main/mutations/messages/message-reaction-create.ts
index 3500e91b..90b8f131 100644
--- a/apps/desktop/src/main/mutations/messages/message-reaction-create.ts
+++ b/apps/desktop/src/main/mutations/messages/message-reaction-create.ts
@@ -1,4 +1,5 @@
import {
+ canCreateMessageReaction,
CreateMessageReactionMutation,
generateId,
IdType,
@@ -11,7 +12,13 @@ import {
MessageReactionCreateMutationOutput,
} from '@/shared/mutations/messages/message-reaction-create';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapMessageReaction } from '@/main/utils';
+import {
+ fetchEntry,
+ fetchUser,
+ mapEntry,
+ mapMessageReaction,
+} from '@/main/utils';
+import { MutationError } from '@/shared/mutations';
export class MessageReactionCreateMutationHandler
implements MutationHandler<MessageReactionCreateMutationInput>
@@ -23,6 +30,16 @@ export class MessageReactionCreateMutationHandler
input.userId
);
+ const message = await workspaceDatabase
+ .selectFrom('messages')
+ .selectAll()
+ .where('id', '=', input.messageId)
+ .executeTakeFirst();
+
+ if (!message) {
+ throw new MutationError('message_not_found', 'Message not found.');
+ }
+
const existingMessageReaction = await workspaceDatabase
.selectFrom('message_reactions')
.selectAll()
@@ -37,6 +54,35 @@ export class MessageReactionCreateMutationHandler
};
}
+ const user = await fetchUser(workspaceDatabase, input.userId);
+ if (!user) {
+ throw new MutationError('user_not_found', 'User not found.');
+ }
+
+ const root = await fetchEntry(workspaceDatabase, input.rootId);
+ if (!root) {
+ throw new MutationError('entry_not_found', 'Conversation not found.');
+ }
+
+ if (
+ !canCreateMessageReaction({
+ user: {
+ userId: input.userId,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ message: {
+ id: message.id,
+ createdBy: message.created_by,
+ },
+ })
+ ) {
+ throw new MutationError(
+ 'unauthorized',
+ 'You are not allowed to react to this message.'
+ );
+ }
+
const { createdMessageReaction, createdMutation } = await workspaceDatabase
.transaction()
.execute(async (trx) => {
diff --git a/apps/desktop/src/main/mutations/spaces/space-create.ts b/apps/desktop/src/main/mutations/spaces/space-create.ts
index dd5631b8..dd70ef7a 100644
--- a/apps/desktop/src/main/mutations/spaces/space-create.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-create.ts
@@ -45,11 +45,16 @@ export class SpaceCreateMutationHandler
collaborators: {
[input.userId]: 'admin',
},
- parentId: input.workspaceId,
+ parentId: spaceId,
description: input.description,
avatar: null,
};
+ await entryService.createEntry(input.userId, {
+ id: spaceId,
+ attributes: spaceAttributes,
+ });
+
const pageId = generateId(IdType.Page);
const pageAttributes: PageAttributes = {
type: 'page',
@@ -59,6 +64,11 @@ export class SpaceCreateMutationHandler
collaborators: {},
};
+ await entryService.createEntry(input.userId, {
+ id: pageId,
+ attributes: pageAttributes,
+ });
+
const channelId = generateId(IdType.Channel);
const channelAttributes: ChannelAttributes = {
type: 'channel',
@@ -66,20 +76,10 @@ export class SpaceCreateMutationHandler
parentId: spaceId,
};
- await entryService.createEntry(input.userId, [
- {
- id: spaceId,
- attributes: spaceAttributes,
- },
- {
- id: pageId,
- attributes: pageAttributes,
- },
- {
- id: channelId,
- attributes: channelAttributes,
- },
- ]);
+ await entryService.createEntry(input.userId, {
+ id: channelId,
+ attributes: channelAttributes,
+ });
return {
id: spaceId,
diff --git a/apps/desktop/src/main/services/entry-service.ts b/apps/desktop/src/main/services/entry-service.ts
index 28040f36..a05845e2 100644
--- a/apps/desktop/src/main/services/entry-service.ts
+++ b/apps/desktop/src/main/services/entry-service.ts
@@ -4,28 +4,27 @@ import {
LocalCreateTransaction,
LocalDeleteTransaction,
LocalUpdateTransaction,
- Entry,
EntryAttributes,
- EntryMutationContext,
- registry,
SyncCreateEntryTransactionData,
SyncDeleteEntryTransactionData,
SyncEntryInteractionData,
SyncEntryTransactionData,
SyncUpdateEntryTransactionData,
+ extractEntryText,
+ canDeleteEntry,
+ canUpdateEntry,
+ entryAttributesSchema,
+ Entry,
+ canCreateEntry,
} from '@colanode/core';
import { decodeState, YDoc } from '@colanode/crdt';
import { createDebugger } from '@/main/debugger';
-import { SelectWorkspace } from '@/main/data/app/schema';
import { databaseService } from '@/main/data/database-service';
+import { SelectEntryTransaction } from '@/main/data/workspace/schema';
import {
- SelectMutation,
- SelectEntry,
- SelectEntryTransaction,
-} from '@/main/data/workspace/schema';
-import {
- fetchEntryAncestors,
+ fetchEntry,
+ fetchUser,
mapEntry,
mapEntryInteraction,
mapEntryTransaction,
@@ -49,88 +48,71 @@ export type UpdateEntryResult =
class EntryService {
private readonly debug = createDebugger('service:entry');
- public async fetchEntry(
- entryId: string,
- userId: string
- ): Promise<Entry | null> {
- const workspaceDatabase =
- await databaseService.getWorkspaceDatabase(userId);
-
- const entryRow = await workspaceDatabase
- .selectFrom('entries')
- .where('id', '=', entryId)
- .selectAll()
- .executeTakeFirst();
-
- if (!entryRow) {
- return null;
- }
-
- return mapEntry(entryRow);
- }
-
- public async createEntry(
- userId: string,
- input: CreateEntryInput | CreateEntryInput[]
- ) {
+ public async createEntry(userId: string, input: CreateEntryInput) {
this.debug(`Creating ${Array.isArray(input) ? 'entries' : 'entry'}`);
- const workspace = await this.fetchWorkspace(userId);
-
- const inputs = Array.isArray(input) ? input : [input];
- const createdEntries: SelectEntry[] = [];
- const createdMutations: SelectMutation[] = [];
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
- await workspaceDatabase.transaction().execute(async (transaction) => {
- for (const inputItem of inputs) {
- const model = registry.getModel(inputItem.attributes.type);
- if (!model.schema.safeParse(inputItem.attributes).success) {
- throw new Error('Invalid attributes');
- }
-
- let ancestors: Entry[] = [];
- if (inputItem.attributes.parentId) {
- const ancestorRows = await fetchEntryAncestors(
- transaction,
- inputItem.attributes.parentId
- );
- ancestors = ancestorRows.map(mapEntry);
- }
+ const user = await fetchUser(workspaceDatabase, userId);
+ if (!user) {
+ throw new Error('User not found');
+ }
- const rootId = ancestors[0]?.id ?? inputItem.id;
- const context = new EntryMutationContext(
- workspace.account_id,
- workspace.workspace_id,
- userId,
- workspace.role,
- ancestors
- );
+ let root: Entry | null = null;
+ const parent = await fetchEntry(
+ workspaceDatabase,
+ input.attributes.parentId
+ );
- if (!model.canCreate(context, inputItem.attributes)) {
- throw new Error('Insufficient permissions');
+ if (parent) {
+ if (parent.id === parent.root_id) {
+ root = mapEntry(parent);
+ } else {
+ const rootRow = await fetchEntry(workspaceDatabase, parent.root_id);
+ if (rootRow) {
+ root = mapEntry(rootRow);
}
+ }
+ }
- const ydoc = new YDoc();
- const update = ydoc.updateAttributes(
- model.schema,
- inputItem.attributes
- );
+ if (
+ !canCreateEntry(
+ {
+ user: {
+ userId,
+ role: user.role,
+ },
+ root: root,
+ },
+ input.attributes
+ )
+ ) {
+ throw new Error('Insufficient permissions');
+ }
- const createdAt = new Date().toISOString();
- const transactionId = generateId(IdType.Transaction);
- const text = model.getText(inputItem.id, inputItem.attributes);
+ const ydoc = new YDoc();
+ const update = ydoc.updateAttributes(
+ entryAttributesSchema,
+ input.attributes
+ );
+
+ const createdAt = new Date().toISOString();
+ const transactionId = generateId(IdType.Transaction);
+ const text = extractEntryText(input.id, input.attributes);
- const createdEntry = await transaction
+ const { createdEntry, createdMutation } = await workspaceDatabase
+ .transaction()
+ .execute(async (trx) => {
+ const createdEntry = await trx
.insertInto('entries')
.returningAll()
.values({
- id: inputItem.id,
- root_id: rootId,
- attributes: JSON.stringify(inputItem.attributes),
+ id: input.id,
+ root_id: root?.id ?? input.id,
+ attributes: JSON.stringify(input.attributes),
created_at: createdAt,
- created_by: context.userId,
+ created_by: userId,
transaction_id: transactionId,
})
.executeTakeFirst();
@@ -139,19 +121,17 @@ class EntryService {
throw new Error('Failed to create entry');
}
- createdEntries.push(createdEntry);
-
- const createdTransaction = await transaction
+ const createdTransaction = await trx
.insertInto('entry_transactions')
.returningAll()
.values({
id: transactionId,
- entry_id: inputItem.id,
- root_id: rootId,
+ entry_id: input.id,
+ root_id: root?.id ?? input.id,
operation: 'create',
data: update,
created_at: createdAt,
- created_by: context.userId,
+ created_by: userId,
version: 0n,
})
.executeTakeFirst();
@@ -160,12 +140,12 @@ class EntryService {
throw new Error('Failed to create transaction');
}
- const mutation = await transaction
+ const createdMutation = await trx
.insertInto('mutations')
.returningAll()
.values({
id: generateId(IdType.Mutation),
- node_id: inputItem.id,
+ node_id: input.id,
type: 'apply_create_transaction',
data: JSON.stringify(mapEntryTransaction(createdTransaction)),
created_at: createdAt,
@@ -173,41 +153,47 @@ class EntryService {
})
.executeTakeFirst();
- if (!mutation) {
+ if (!createdMutation) {
throw new Error('Failed to create mutation');
}
- createdMutations.push(mutation);
-
if (text) {
- await transaction
+ await trx
.insertInto('texts')
- .values({ id: inputItem.id, name: text.name, text: text.text })
+ .values({ id: input.id, name: text.name, text: text.text })
.execute();
}
- }
- });
- for (const createdEntry of createdEntries) {
- this.debug(
- `Created entry ${createdEntry.id} with type ${createdEntry.type}`
- );
-
- eventBus.publish({
- type: 'entry_created',
- userId,
- entry: mapEntry(createdEntry),
+ return {
+ createdEntry,
+ createdMutation,
+ };
});
+
+ if (!createdEntry) {
+ throw new Error('Failed to create entry');
}
- for (const createdMutation of createdMutations) {
- this.debug(`Created mutation ${createdMutation.id}`);
+ this.debug(
+ `Created entry ${createdEntry.id} with type ${createdEntry.type}`
+ );
- eventBus.publish({
- type: 'mutation_created',
- userId,
- });
+ eventBus.publish({
+ type: 'entry_created',
+ userId,
+ entry: mapEntry(createdEntry),
+ });
+
+ if (!createdMutation) {
+ throw new Error('Failed to create mutation');
}
+
+ this.debug(`Created mutation ${createdMutation.id}`);
+
+ eventBus.publish({
+ type: 'mutation_created',
+ userId,
+ });
}
public async updateEntry(
@@ -232,45 +218,29 @@ class EntryService {
): Promise<UpdateEntryResult | null> {
this.debug(`Updating entry ${entryId}`);
- const workspace = await this.fetchWorkspace(userId);
-
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
- const ancestorRows = await fetchEntryAncestors(workspaceDatabase, entryId);
- const entryRow = ancestorRows.find((ancestor) => ancestor.id === entryId);
+ const entryRow = await fetchEntry(workspaceDatabase, entryId);
if (!entryRow) {
return 'not_found';
}
- const ancestors = ancestorRows.map(mapEntry);
- const entry = mapEntry(entryRow);
-
- if (!entry) {
+ const user = await fetchUser(workspaceDatabase, userId);
+ if (!user) {
return 'not_found';
}
- const context = new EntryMutationContext(
- workspace.account_id,
- workspace.workspace_id,
- userId,
- workspace.role,
- ancestors
- );
+ const root = await fetchEntry(workspaceDatabase, entryRow.root_id);
+ if (!root) {
+ return 'not_found';
+ }
+ const entry = mapEntry(entryRow);
const transactionId = generateId(IdType.Transaction);
const updatedAt = new Date().toISOString();
const updatedAttributes = updater(entry.attributes);
- const model = registry.getModel(entry.type);
- if (!model.schema.safeParse(updatedAttributes).success) {
- return 'invalid_attributes';
- }
-
- if (!model.canUpdate(context, entry, updatedAttributes)) {
- return 'unauthorized';
- }
-
const ydoc = new YDoc();
const previousTransactions = await workspaceDatabase
.selectFrom('entry_transactions')
@@ -286,8 +256,28 @@ class EntryService {
ydoc.applyUpdate(previousTransaction.data);
}
- const update = ydoc.updateAttributes(model.schema, updatedAttributes);
- const text = model.getText(entryId, updatedAttributes);
+ const update = ydoc.updateAttributes(
+ entryAttributesSchema,
+ updatedAttributes
+ );
+
+ if (
+ !canUpdateEntry(
+ {
+ user: {
+ userId,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: entry,
+ },
+ updatedAttributes
+ )
+ ) {
+ return 'unauthorized';
+ }
+
+ const text = extractEntryText(entryId, updatedAttributes);
const { updatedEntry, createdMutation } = await workspaceDatabase
.transaction()
@@ -298,7 +288,7 @@ class EntryService {
.set({
attributes: JSON.stringify(ydoc.getAttributes()),
updated_at: updatedAt,
- updated_by: context.userId,
+ updated_by: userId,
transaction_id: transactionId,
})
.where('id', '=', entryId)
@@ -319,7 +309,7 @@ class EntryService {
operation: 'update',
data: update,
created_at: updatedAt,
- created_by: context.userId,
+ created_by: userId,
version: 0n,
})
.executeTakeFirst();
@@ -395,28 +385,34 @@ class EntryService {
}
public async deleteEntry(entryId: string, userId: string) {
- const workspace = await this.fetchWorkspace(userId);
const workspaceDatabase =
await databaseService.getWorkspaceDatabase(userId);
- const ancestorRows = await fetchEntryAncestors(workspaceDatabase, entryId);
- const ancestors = ancestorRows.map(mapEntry);
+ const user = await fetchUser(workspaceDatabase, userId);
+ if (!user) {
+ throw new Error('User not found');
+ }
- const entry = ancestors.find((ancestor) => ancestor.id === entryId);
- if (!entry) {
+ const root = await fetchEntry(workspaceDatabase, entryId);
+ if (!root) {
throw new Error('Entry not found');
}
- const model = registry.getModel(entry.type);
- const context = new EntryMutationContext(
- workspace.account_id,
- workspace.workspace_id,
- userId,
- workspace.role,
- ancestors
- );
+ const entry = await fetchEntry(workspaceDatabase, entryId);
+ if (!entry) {
+ throw new Error('Entry not found');
+ }
- if (!model.canDelete(context, entry)) {
+ if (
+ !canDeleteEntry({
+ user: {
+ userId,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ })
+ ) {
throw new Error('Insufficient permissions');
}
@@ -441,11 +437,11 @@ class EntryService {
.values({
id: generateId(IdType.Transaction),
entry_id: entryId,
- root_id: entry.rootId,
+ root_id: root.root_id,
operation: 'delete',
data: null,
created_at: new Date().toISOString(),
- created_by: context.userId,
+ created_by: userId,
version: 0n,
})
.executeTakeFirst();
@@ -556,13 +552,7 @@ class EntryService {
const ydoc = new YDoc();
ydoc.applyUpdate(transaction.data);
const attributes = ydoc.getAttributes<EntryAttributes>();
-
- const model = registry.getModel(attributes.type);
- if (!model) {
- return;
- }
-
- const text = model.getText(transaction.entryId, attributes);
+ const text = extractEntryText(transaction.entryId, attributes);
const { createdEntry } = await workspaceDatabase
.transaction()
@@ -684,13 +674,7 @@ class EntryService {
ydoc.applyUpdate(transaction.data);
const attributes = ydoc.getAttributes<EntryAttributes>();
-
- const model = registry.getModel(attributes.type);
- if (!model) {
- return;
- }
-
- const text = model.getText(transaction.entryId, attributes);
+ const text = extractEntryText(transaction.entryId, attributes);
const { updatedEntry } = await workspaceDatabase
.transaction()
@@ -933,13 +917,7 @@ class EntryService {
.orderBy('id', 'asc')
.execute();
- const model = registry.getModel(entry.type);
- if (!model) {
- return true;
- }
-
const ydoc = new YDoc();
-
let lastTransaction: SelectEntryTransaction | undefined;
for (const previousTransaction of previousTransactions) {
if (previousTransaction.id === transaction.id) {
@@ -957,6 +935,9 @@ class EntryService {
return true;
}
+ const attributes = ydoc.getAttributes<EntryAttributes>();
+ const text = extractEntryText(transaction.entryId, attributes);
+
const updatedEntry = await workspaceDatabase
.transaction()
.execute(async (trx) => {
@@ -977,6 +958,24 @@ class EntryService {
return undefined;
}
+ if (text !== undefined) {
+ await trx
+ .deleteFrom('texts')
+ .where('id', '=', transaction.entryId)
+ .execute();
+ }
+
+ if (text) {
+ await trx
+ .insertInto('texts')
+ .values({
+ id: transaction.entryId,
+ name: text.name,
+ text: text.text,
+ })
+ .execute();
+ }
+
await trx
.deleteFrom('entry_transactions')
.where('id', '=', transaction.id)
@@ -1040,12 +1039,7 @@ class EntryService {
}
const attributes = ydoc.getAttributes<EntryAttributes>();
- const model = registry.getModel(attributes.type);
- if (!model) {
- return true;
- }
-
- const text = model.getText(transaction.entryId, attributes);
+ const text = extractEntryText(transaction.entryId, attributes);
const createdEntry = await workspaceDatabase
.transaction()
@@ -1178,20 +1172,6 @@ class EntryService {
`Server entry interaction for entry ${entryInteraction.entryId} has been synced`
);
}
-
- private async fetchWorkspace(userId: string): Promise<SelectWorkspace> {
- const workspace = await databaseService.appDatabase
- .selectFrom('workspaces')
- .selectAll()
- .where('user_id', '=', userId)
- .executeTakeFirst();
-
- if (!workspace) {
- throw new Error('Workspace not found');
- }
-
- return workspace;
- }
}
export const entryService = new EntryService();
diff --git a/apps/desktop/src/main/services/message-service.ts b/apps/desktop/src/main/services/message-service.ts
index eee99850..86ba4ddb 100644
--- a/apps/desktop/src/main/services/message-service.ts
+++ b/apps/desktop/src/main/services/message-service.ts
@@ -1,7 +1,7 @@
import {
CreateMessageReactionMutationData,
DeleteMessageReactionMutationData,
- extractText,
+ extractMessageText,
SyncMessageData,
SyncMessageInteractionData,
SyncMessageReactionData,
@@ -61,14 +61,17 @@ class MessageService {
.where('id', '=', message.id)
.execute();
- await workspaceDatabase
- .insertInto('texts')
- .values({
- id: message.id,
- name: null,
- text: extractText(message.id, message.content.blocks),
- })
- .execute();
+ const text = extractMessageText(message.id, message.content);
+ if (text) {
+ await workspaceDatabase
+ .insertInto('texts')
+ .values({
+ id: message.id,
+ name: null,
+ text: text.text,
+ })
+ .execute();
+ }
eventBus.publish({
type: 'message_updated',
@@ -102,14 +105,17 @@ class MessageService {
return;
}
- await workspaceDatabase
- .insertInto('texts')
- .values({
- id: message.id,
- name: null,
- text: extractText(message.id, message.content.blocks),
- })
- .execute();
+ const text = extractMessageText(message.id, message.content);
+ if (text) {
+ await workspaceDatabase
+ .insertInto('texts')
+ .values({
+ id: message.id,
+ name: null,
+ text: text.text,
+ })
+ .execute();
+ }
eventBus.publish({
type: 'message_created',
diff --git a/apps/desktop/src/main/utils.ts b/apps/desktop/src/main/utils.ts
index ac08338c..bf4b265a 100644
--- a/apps/desktop/src/main/utils.ts
+++ b/apps/desktop/src/main/utils.ts
@@ -114,6 +114,32 @@ export const fetchEntryAncestors = (
.execute();
};
+export const fetchEntry = (
+ database:
+ | Kysely<WorkspaceDatabaseSchema>
+ | Transaction<WorkspaceDatabaseSchema>,
+ entryId: string
+): Promise<SelectEntry | undefined> => {
+ return database
+ .selectFrom('entries')
+ .selectAll()
+ .where('id', '=', entryId)
+ .executeTakeFirst();
+};
+
+export const fetchUser = (
+ database:
+ | Kysely<WorkspaceDatabaseSchema>
+ | Transaction<WorkspaceDatabaseSchema>,
+ userId: string
+): Promise<SelectUser | undefined> => {
+ return database
+ .selectFrom('users')
+ .selectAll()
+ .where('id', '=', userId)
+ .executeTakeFirst();
+};
+
export const fetchWorkspaceCredentials = async (
userId: string
): Promise<WorkspaceCredentials | null> => {
@@ -308,6 +334,7 @@ export const mapFile = (row: SelectFile): File => {
id: row.id,
type: row.type,
parentId: row.parent_id,
+ entryId: row.entry_id,
rootId: row.root_id,
name: row.name,
originalName: row.original_name,
diff --git a/apps/desktop/src/renderer/components/channels/channel-container.tsx b/apps/desktop/src/renderer/components/channels/channel-container.tsx
index d050d09d..410ebf07 100644
--- a/apps/desktop/src/renderer/components/channels/channel-container.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-container.tsx
@@ -1,4 +1,4 @@
-import { extractEntryRole } from '@colanode/core';
+import { ChannelEntry, extractEntryRole } from '@colanode/core';
import { ChannelBody } from '@/renderer/components/channels/channel-body';
import { ChannelHeader } from '@/renderer/components/channels/channel-header';
@@ -11,27 +11,41 @@ interface ChannelContainerProps {
export const ChannelContainer = ({ channelId }: ChannelContainerProps) => {
const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- type: 'entry_tree_get',
+
+ const { data: entry, isPending: isPendingEntry } = useQuery({
+ type: 'entry_get',
entryId: channelId,
userId: workspace.userId,
});
- if (isPending) {
+ const channel = entry as ChannelEntry;
+ const { data: root, isPending: isPendingRoot } = useQuery(
+ {
+ type: 'entry_get',
+ entryId: channel?.rootId ?? '',
+ userId: workspace.userId,
+ },
+ {
+ enabled: !!channel?.rootId,
+ }
+ );
+
+ if (isPendingEntry || isPendingRoot) {
return null;
}
- const entries = data ?? [];
- const channel = entries.find((entry) => entry.id === channelId);
- const role = extractEntryRole(entries, workspace.userId);
+ if (!channel || !root) {
+ return null;
+ }
- if (!channel || channel.type !== 'channel' || !role) {
+ const role = extractEntryRole(root, workspace.userId);
+ if (!role) {
return null;
}
return (
<div className="flex h-full w-full flex-col">
- <ChannelHeader entries={entries} channel={channel} role={role} />
+ <ChannelHeader channel={channel} role={role} />
<ChannelBody channel={channel} role={role} />
</div>
);
diff --git a/apps/desktop/src/renderer/components/channels/channel-header.tsx b/apps/desktop/src/renderer/components/channels/channel-header.tsx
index 10b747e6..c44f7b57 100644
--- a/apps/desktop/src/renderer/components/channels/channel-header.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-header.tsx
@@ -1,4 +1,4 @@
-import { ChannelEntry, Entry, EntryRole } from '@colanode/core';
+import { ChannelEntry, EntryRole } from '@colanode/core';
import { ChannelSettings } from '@/renderer/components/channels/channel-settings';
import { EntryBreadcrumb } from '@/renderer/components/layouts/entry-breadcrumb';
@@ -7,23 +7,18 @@ import { Header } from '@/renderer/components/ui/header';
import { useContainer } from '@/renderer/contexts/container';
interface ChannelHeaderProps {
- entries: Entry[];
channel: ChannelEntry;
role: EntryRole;
}
-export const ChannelHeader = ({
- entries,
- channel,
- role,
-}: ChannelHeaderProps) => {
+export const ChannelHeader = ({ channel, role }: ChannelHeaderProps) => {
const container = useContainer();
return (
<Header>
<div className="flex w-full items-center gap-2 px-4">
<div className="flex-grow">
- {container.mode === 'main' && <EntryBreadcrumb entries={entries} />}
+ {container.mode === 'main' && <EntryBreadcrumb entry={channel} />}
{container.mode === 'modal' && (
<EntryFullscreenButton entryId={channel.id} />
)}
diff --git a/apps/desktop/src/renderer/components/channels/channel-settings.tsx b/apps/desktop/src/renderer/components/channels/channel-settings.tsx
index 46afac05..7f502df4 100644
--- a/apps/desktop/src/renderer/components/channels/channel-settings.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-settings.tsx
@@ -1,4 +1,4 @@
-import { ChannelEntry, hasEditorAccess, EntryRole } from '@colanode/core';
+import { ChannelEntry, EntryRole, hasEntryRole } from '@colanode/core';
import { Copy, Image, LetterText, Settings, Trash2 } from 'lucide-react';
import React from 'react';
@@ -23,8 +23,8 @@ export const ChannelSettings = ({ channel, role }: ChannelSettingsProps) => {
const [showUpdateDialog, setShowUpdateDialog] = React.useState(false);
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
- const canEdit = hasEditorAccess(role);
- const canDelete = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
+ const canDelete = hasEntryRole(role, 'editor');
return (
<React.Fragment>
diff --git a/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx b/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
index edf64ef5..7c0b9321 100644
--- a/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
@@ -1,4 +1,4 @@
-import { ChannelEntry, hasEditorAccess, EntryRole } from '@colanode/core';
+import { ChannelEntry, EntryRole, hasEntryRole } from '@colanode/core';
import { ChannelForm } from '@/renderer/components/channels/channel-form';
import {
@@ -27,7 +27,7 @@ export const ChannelUpdateDialog = ({
}: ChannelUpdateDialogProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const canEdit = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/components/chats/chat-header.tsx b/apps/desktop/src/renderer/components/chats/chat-header.tsx
index 4f94818a..8b7a5355 100644
--- a/apps/desktop/src/renderer/components/chats/chat-header.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-header.tsx
@@ -18,7 +18,7 @@ export const ChatHeader = ({ chat, role }: ChatHeaderProps) => {
<Header>
<div className="flex w-full items-center gap-2 px-4">
<div className="flex-grow">
- <EntryBreadcrumb entries={[chat]} />
+ <EntryBreadcrumb entry={chat} />
{container.mode === 'modal' && (
<EntryFullscreenButton entryId={chat.id} />
)}
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-role-dropdown.tsx b/apps/desktop/src/renderer/components/collaborators/entry-collaborator-role-dropdown.tsx
index 39e7c222..ef9d5b60 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-role-dropdown.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/entry-collaborator-role-dropdown.tsx
@@ -1,4 +1,5 @@
import { Check, ChevronDown } from 'lucide-react';
+import { EntryRole } from '@colanode/core';
import {
DropdownMenu,
@@ -9,7 +10,7 @@ import {
interface EntryCollaboratorRole {
name: string;
- value: string;
+ value: EntryRole;
description: string;
enabled: boolean;
}
@@ -28,9 +29,9 @@ const roles: EntryCollaboratorRole[] = [
enabled: true,
},
{
- name: 'Collaborator',
- value: 'collaborator',
- description: 'Can contribute in content',
+ name: 'Commenter',
+ value: 'commenter',
+ description: 'Can message or comment on content',
enabled: true,
},
{
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborators.tsx b/apps/desktop/src/renderer/components/collaborators/entry-collaborators.tsx
index d878d416..92e600d4 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborators.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/entry-collaborators.tsx
@@ -1,8 +1,8 @@
import {
- hasAdminAccess,
Entry,
EntryRole,
extractEntryName,
+ hasEntryRole,
} from '@colanode/core';
import React from 'react';
@@ -30,7 +30,7 @@ export const EntryCollaborators = ({
(collaborator) => collaborator.collaboratorId
);
- const isAdmin = hasAdminAccess(role);
+ const isAdmin = hasEntryRole(role, 'admin');
const ancestors = entries.filter((entry) => entry.id !== entryId);
return (
diff --git a/apps/desktop/src/renderer/components/databases/database-container.tsx b/apps/desktop/src/renderer/components/databases/database-container.tsx
index dc5ec234..d0640dbc 100644
--- a/apps/desktop/src/renderer/components/databases/database-container.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-container.tsx
@@ -1,4 +1,4 @@
-import { extractEntryRole } from '@colanode/core';
+import { DatabaseEntry, extractEntryRole } from '@colanode/core';
import { DatabaseBody } from '@/renderer/components/databases/database-body';
import { DatabaseHeader } from '@/renderer/components/databases/database-header';
@@ -11,27 +11,42 @@ interface DatabaseContainerProps {
export const DatabaseContainer = ({ databaseId }: DatabaseContainerProps) => {
const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- type: 'entry_tree_get',
+
+ const { data: entry, isPending: isPendingEntry } = useQuery({
+ type: 'entry_get',
entryId: databaseId,
userId: workspace.userId,
});
- if (isPending) {
+ const database = entry as DatabaseEntry;
+
+ const { data: root, isPending: isPendingRoot } = useQuery(
+ {
+ type: 'entry_get',
+ entryId: database?.rootId ?? '',
+ userId: workspace.userId,
+ },
+ {
+ enabled: !!database?.rootId,
+ }
+ );
+
+ if (isPendingEntry || isPendingRoot) {
return null;
}
- const entries = data ?? [];
- const database = entries.find((entry) => entry.id === databaseId);
- const role = extractEntryRole(entries, workspace.userId);
+ if (!database || !root) {
+ return null;
+ }
- if (!database || database.type !== 'database' || !role) {
+ const role = extractEntryRole(root, workspace.userId);
+ if (!role) {
return null;
}
return (
<div className="flex h-full w-full flex-col">
- <DatabaseHeader entries={entries} database={database} role={role} />
+ <DatabaseHeader database={database} role={role} />
<DatabaseBody database={database} role={role} />
</div>
);
diff --git a/apps/desktop/src/renderer/components/databases/database-header.tsx b/apps/desktop/src/renderer/components/databases/database-header.tsx
index 75ca8d95..c1362cce 100644
--- a/apps/desktop/src/renderer/components/databases/database-header.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-header.tsx
@@ -1,4 +1,4 @@
-import { DatabaseEntry, Entry, EntryRole } from '@colanode/core';
+import { DatabaseEntry, EntryRole } from '@colanode/core';
import { DatabaseSettings } from '@/renderer/components/databases/database-settings';
import { EntryBreadcrumb } from '@/renderer/components/layouts/entry-breadcrumb';
@@ -7,23 +7,18 @@ import { Header } from '@/renderer/components/ui/header';
import { useContainer } from '@/renderer/contexts/container';
interface DatabaseHeaderProps {
- entries: Entry[];
database: DatabaseEntry;
role: EntryRole;
}
-export const DatabaseHeader = ({
- entries,
- database,
- role,
-}: DatabaseHeaderProps) => {
+export const DatabaseHeader = ({ database, role }: DatabaseHeaderProps) => {
const container = useContainer();
return (
<Header>
<div className="flex w-full items-center gap-2 px-4">
<div className="flex-grow">
- {container.mode === 'main' && <EntryBreadcrumb entries={entries} />}
+ {container.mode === 'main' && <EntryBreadcrumb entry={database} />}
{container.mode === 'modal' && (
<EntryFullscreenButton entryId={database.id} />
)}
diff --git a/apps/desktop/src/renderer/components/databases/database-settings.tsx b/apps/desktop/src/renderer/components/databases/database-settings.tsx
index 1f9066d7..1b30a743 100644
--- a/apps/desktop/src/renderer/components/databases/database-settings.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-settings.tsx
@@ -1,4 +1,4 @@
-import { DatabaseEntry, hasEditorAccess, EntryRole } from '@colanode/core';
+import { DatabaseEntry, EntryRole, hasEntryRole } from '@colanode/core';
import { Copy, Image, LetterText, Settings, Trash2 } from 'lucide-react';
import React from 'react';
@@ -23,8 +23,8 @@ export const DatabaseSettings = ({ database, role }: DatabaseSettingsProps) => {
const [showUpdateDialog, setShowUpdateDialog] = React.useState(false);
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
- const canEdit = hasEditorAccess(role);
- const canDelete = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
+ const canDelete = hasEntryRole(role, 'admin');
return (
<React.Fragment>
diff --git a/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx b/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
index de8ead46..a4eb6968 100644
--- a/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
@@ -1,4 +1,4 @@
-import { DatabaseEntry, hasEditorAccess, EntryRole } from '@colanode/core';
+import { DatabaseEntry, EntryRole, hasEntryRole } from '@colanode/core';
import { DatabaseForm } from '@/renderer/components/databases/database-form';
import {
@@ -27,7 +27,7 @@ export const DatabaseUpdateDialog = ({
}: DatabaseUpdateDialogProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const canEdit = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/components/databases/database.tsx b/apps/desktop/src/renderer/components/databases/database.tsx
index 423edf54..e7bb6ba1 100644
--- a/apps/desktop/src/renderer/components/databases/database.tsx
+++ b/apps/desktop/src/renderer/components/databases/database.tsx
@@ -1,9 +1,4 @@
-import {
- DatabaseEntry,
- hasCollaboratorAccess,
- hasEditorAccess,
- EntryRole,
-} from '@colanode/core';
+import { DatabaseEntry, EntryRole, hasEntryRole } from '@colanode/core';
import React from 'react';
import { DatabaseContext } from '@/renderer/contexts/database';
@@ -21,8 +16,8 @@ export const Database = ({ database, role, children }: DatabaseProps) => {
const workspace = useWorkspace();
const { mutate } = useMutation();
- const canEdit = hasEditorAccess(role);
- const canCreateRecord = hasCollaboratorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
+ const canCreateRecord = hasEntryRole(role, 'editor');
return (
<DatabaseContext.Provider
diff --git a/apps/desktop/src/renderer/components/files/file-container.tsx b/apps/desktop/src/renderer/components/files/file-container.tsx
index 946eb325..78bf0641 100644
--- a/apps/desktop/src/renderer/components/files/file-container.tsx
+++ b/apps/desktop/src/renderer/components/files/file-container.tsx
@@ -12,16 +12,16 @@ interface FileContainerProps {
export const FileContainer = ({ fileId }: FileContainerProps) => {
const workspace = useWorkspace();
- const { data: file, isPending: isFilePending } = useQuery({
+ const { data: file, isPending: isPendingFile } = useQuery({
type: 'file_get',
id: fileId,
userId: workspace.userId,
});
- const { data: entries, isPending: isEntriesPending } = useQuery(
+ const { data: entry, isPending: isPendingEntry } = useQuery(
{
- type: 'entry_tree_get',
- entryId: file?.parentId ?? '',
+ type: 'entry_get',
+ entryId: file?.entryId ?? '',
userId: workspace.userId,
},
{
@@ -29,18 +29,33 @@ export const FileContainer = ({ fileId }: FileContainerProps) => {
}
);
- if (isFilePending || isEntriesPending) {
+ const { data: root, isPending: isPendingRoot } = useQuery(
+ {
+ type: 'entry_get',
+ entryId: file?.rootId ?? '',
+ userId: workspace.userId,
+ },
+ {
+ enabled: !!file,
+ }
+ );
+
+ if (isPendingFile || isPendingEntry || isPendingRoot) {
+ return null;
+ }
+
+ if (!file || !entry || !root) {
return null;
}
- const role = extractEntryRole(entries ?? [], workspace.userId);
- if (!file || !role) {
+ const role = extractEntryRole(root, workspace.userId);
+ if (!role) {
return null;
}
return (
<div className="flex h-full w-full flex-col">
- <FileHeader entries={entries ?? []} file={file} role={role} />
+ <FileHeader file={file} role={role} entry={entry} />
<FileBody file={file} />
</div>
);
diff --git a/apps/desktop/src/renderer/components/files/file-header.tsx b/apps/desktop/src/renderer/components/files/file-header.tsx
index 548f5474..d54af8f8 100644
--- a/apps/desktop/src/renderer/components/files/file-header.tsx
+++ b/apps/desktop/src/renderer/components/files/file-header.tsx
@@ -8,25 +8,25 @@ import { useContainer } from '@/renderer/contexts/container';
import { FileWithState } from '@/shared/types/files';
interface FileHeaderProps {
- entries: Entry[];
file: FileWithState;
+ entry: Entry;
role: EntryRole;
}
-export const FileHeader = ({ entries, file }: FileHeaderProps) => {
+export const FileHeader = ({ file, entry, role }: FileHeaderProps) => {
const container = useContainer();
return (
<Header>
<div className="flex w-full items-center gap-2 px-4">
<div className="flex-grow">
- {container.mode === 'main' && <EntryBreadcrumb entries={entries} />}
+ {container.mode === 'main' && <EntryBreadcrumb entry={entry} />}
{container.mode === 'modal' && (
<EntryFullscreenButton entryId={file.id} />
)}
</div>
<div className="flex items-center gap-2">
- <FileSettings fileId={file.id} />
+ <FileSettings file={file} role={role} entry={entry} />
</div>
</div>
</Header>
diff --git a/apps/desktop/src/renderer/components/files/file-settings.tsx b/apps/desktop/src/renderer/components/files/file-settings.tsx
index 13f8621f..3f2ce08b 100644
--- a/apps/desktop/src/renderer/components/files/file-settings.tsx
+++ b/apps/desktop/src/renderer/components/files/file-settings.tsx
@@ -1,5 +1,6 @@
import { Copy, Settings, Trash2 } from 'lucide-react';
import React from 'react';
+import { Entry, EntryRole, hasEntryRole } from '@colanode/core';
import { FileDeleteDialog } from '@/renderer/components/files/file-delete-dialog';
import {
@@ -8,13 +9,22 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
+import { FileWithState } from '@/shared/types/files';
+import { useWorkspace } from '@/renderer/contexts/workspace';
interface FileSettingsProps {
- fileId: string;
+ file: FileWithState;
+ role: EntryRole;
+ entry: Entry;
}
-export const FileSettings = ({ fileId }: FileSettingsProps) => {
+export const FileSettings = ({ file, role, entry }: FileSettingsProps) => {
+ const workspace = useWorkspace();
const [showDeleteModal, setShowDeleteModal] = React.useState(false);
+ const canDelete =
+ file.parentId === entry.id &&
+ (file.createdBy === workspace.userId || hasEntryRole(role, 'editor'));
+
return (
<React.Fragment>
<DropdownMenu>
@@ -29,19 +39,26 @@ export const FileSettings = ({ fileId }: FileSettingsProps) => {
<DropdownMenuItem
className="flex items-center gap-2"
onClick={() => {
+ if (!canDelete) {
+ return;
+ }
+
setShowDeleteModal(true);
}}
+ disabled={!canDelete}
>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- <FileDeleteDialog
- fileId={fileId}
- open={showDeleteModal}
- onOpenChange={setShowDeleteModal}
- />
+ {canDelete && (
+ <FileDeleteDialog
+ fileId={file.id}
+ open={showDeleteModal}
+ onOpenChange={setShowDeleteModal}
+ />
+ )}
</React.Fragment>
);
};
diff --git a/apps/desktop/src/renderer/components/folders/folder-body.tsx b/apps/desktop/src/renderer/components/folders/folder-body.tsx
index 7a8e73ff..ed2536ca 100644
--- a/apps/desktop/src/renderer/components/folders/folder-body.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-body.tsx
@@ -1,4 +1,4 @@
-import { FolderEntry } from '@colanode/core';
+import { EntryRole, FolderEntry } from '@colanode/core';
import {
Check,
Filter,
@@ -57,6 +57,7 @@ export const folderLayouts: FolderLayout[] = [
interface FolderBodyProps {
folder: FolderEntry;
+ role: EntryRole;
}
export const FolderBody = ({ folder }: FolderBodyProps) => {
diff --git a/apps/desktop/src/renderer/components/folders/folder-container.tsx b/apps/desktop/src/renderer/components/folders/folder-container.tsx
index 859eb69d..28098b57 100644
--- a/apps/desktop/src/renderer/components/folders/folder-container.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-container.tsx
@@ -1,4 +1,4 @@
-import { extractEntryRole } from '@colanode/core';
+import { extractEntryRole, FolderEntry } from '@colanode/core';
import { FolderBody } from '@/renderer/components/folders/folder-body';
import { FolderHeader } from '@/renderer/components/folders/folder-header';
@@ -12,28 +12,42 @@ interface FolderContainerProps {
export const FolderContainer = ({ folderId }: FolderContainerProps) => {
const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- type: 'entry_tree_get',
+ const { data: entry, isPending: isPendingEntry } = useQuery({
+ type: 'entry_get',
entryId: folderId,
userId: workspace.userId,
});
- if (isPending) {
+ const folder = entry as FolderEntry;
+
+ const { data: root, isPending: isPendingRoot } = useQuery(
+ {
+ type: 'entry_get',
+ entryId: folder?.rootId ?? '',
+ userId: workspace.userId,
+ },
+ {
+ enabled: !!folder?.rootId,
+ }
+ );
+
+ if (isPendingEntry || isPendingRoot) {
return null;
}
- const entries = data ?? [];
- const folder = entries.find((entry) => entry.id === folderId);
- const role = extractEntryRole(entries, workspace.userId);
+ if (!folder || !root) {
+ return null;
+ }
- if (!folder || folder.type !== 'folder' || !role) {
+ const role = extractEntryRole(root, workspace.userId);
+ if (!role) {
return null;
}
return (
<div className="flex h-full w-full flex-col">
- <FolderHeader entries={entries} folder={folder} role={role} />
- <FolderBody folder={folder} />
+ <FolderHeader folder={folder} role={role} />
+ <FolderBody folder={folder} role={role} />
</div>
);
};
diff --git a/apps/desktop/src/renderer/components/folders/folder-header.tsx b/apps/desktop/src/renderer/components/folders/folder-header.tsx
index bc4cc018..cd91eef6 100644
--- a/apps/desktop/src/renderer/components/folders/folder-header.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-header.tsx
@@ -1,4 +1,4 @@
-import { FolderEntry, Entry, EntryRole } from '@colanode/core';
+import { FolderEntry, EntryRole } from '@colanode/core';
import { FolderSettings } from '@/renderer/components/folders/folder-settings';
import { EntryBreadcrumb } from '@/renderer/components/layouts/entry-breadcrumb';
@@ -7,19 +7,18 @@ import { Header } from '@/renderer/components/ui/header';
import { useContainer } from '@/renderer/contexts/container';
interface FolderHeaderProps {
- entries: Entry[];
folder: FolderEntry;
role: EntryRole;
}
-export const FolderHeader = ({ entries, folder, role }: FolderHeaderProps) => {
+export const FolderHeader = ({ folder, role }: FolderHeaderProps) => {
const container = useContainer();
return (
<Header>
<div className="flex w-full items-center gap-2 px-4">
<div className="flex-grow">
- <EntryBreadcrumb entries={entries} />
+ <EntryBreadcrumb entry={folder} />
{container.mode === 'modal' && (
<EntryFullscreenButton entryId={folder.id} />
)}
diff --git a/apps/desktop/src/renderer/components/folders/folder-settings.tsx b/apps/desktop/src/renderer/components/folders/folder-settings.tsx
index 56a6cf51..ebf06781 100644
--- a/apps/desktop/src/renderer/components/folders/folder-settings.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-settings.tsx
@@ -1,4 +1,4 @@
-import { FolderEntry, hasEditorAccess, EntryRole } from '@colanode/core';
+import { EntryRole, FolderEntry, hasEntryRole } from '@colanode/core';
import { Copy, Image, LetterText, Settings, Trash2 } from 'lucide-react';
import React from 'react';
@@ -23,8 +23,8 @@ export const FolderSettings = ({ folder, role }: FolderSettingsProps) => {
const [showUpdateDialog, setShowUpdateDialog] = React.useState(false);
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
- const canEdit = hasEditorAccess(role);
- const canDelete = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
+ const canDelete = hasEntryRole(role, 'editor');
return (
<React.Fragment>
diff --git a/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx b/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
index cfdae575..3cd41538 100644
--- a/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
@@ -1,4 +1,4 @@
-import { FolderEntry, hasEditorAccess, EntryRole } from '@colanode/core';
+import { EntryRole, FolderEntry, hasEntryRole } from '@colanode/core';
import { FolderForm } from '@/renderer/components/folders/folder-form';
import {
@@ -27,7 +27,7 @@ export const FolderUpdateDialog = ({
}: FolderUpdateDialogProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const canEdit = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/components/layouts/entry-breadcrumb.tsx b/apps/desktop/src/renderer/components/layouts/entry-breadcrumb.tsx
index b4a284ad..610af1f7 100644
--- a/apps/desktop/src/renderer/components/layouts/entry-breadcrumb.tsx
+++ b/apps/desktop/src/renderer/components/layouts/entry-breadcrumb.tsx
@@ -16,15 +16,28 @@ import {
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useQuery } from '@/renderer/hooks/use-query';
interface EntryBreadcrumbProps {
- entries: Entry[];
+ entry: Entry;
}
const isClickable = (type: EntryType) => type !== 'space';
-export const EntryBreadcrumb = ({ entries }: EntryBreadcrumbProps) => {
+export const EntryBreadcrumb = ({ entry }: EntryBreadcrumbProps) => {
const workspace = useWorkspace();
+ const { data } = useQuery(
+ {
+ type: 'entry_tree_get',
+ entryId: entry.id,
+ userId: workspace.userId,
+ },
+ {
+ enabled: entry.type !== 'chat',
+ }
+ );
+
+ const entries = data?.length ? data : [entry];
// Show ellipsis if we have more than 3 nodes (first + last two)
const showEllipsis = entries.length > 3;
diff --git a/apps/desktop/src/renderer/components/messages/conversation.tsx b/apps/desktop/src/renderer/components/messages/conversation.tsx
index fa78cbe1..d543eefe 100644
--- a/apps/desktop/src/renderer/components/messages/conversation.tsx
+++ b/apps/desktop/src/renderer/components/messages/conversation.tsx
@@ -1,8 +1,4 @@
-import {
- hasAdminAccess,
- hasCollaboratorAccess,
- EntryRole,
-} from '@colanode/core';
+import { EntryRole, hasEntryRole } from '@colanode/core';
import React from 'react';
import { InView } from 'react-intersection-observer';
@@ -76,8 +72,8 @@ export const Conversation = ({
}
};
- const isAdmin = hasAdminAccess(role);
- const isCollaborator = hasCollaboratorAccess(role);
+ const isAdmin = hasEntryRole(role, 'admin');
+ const canCreateMessage = hasEntryRole(role, 'commenter');
return (
<ConversationContext.Provider
@@ -85,7 +81,7 @@ export const Conversation = ({
id: conversationId,
role,
rootId,
- canCreateMessage: isCollaborator,
+ canCreateMessage,
onReply: (message) => {
if (messageCreateRef.current) {
messageCreateRef.current.setReplyTo(message);
diff --git a/apps/desktop/src/renderer/components/pages/page-body.tsx b/apps/desktop/src/renderer/components/pages/page-body.tsx
index f0084a01..390761c6 100644
--- a/apps/desktop/src/renderer/components/pages/page-body.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-body.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect } from 'react';
-import { hasEditorAccess, EntryRole, PageEntry } from '@colanode/core';
+import { EntryRole, PageEntry, hasEntryRole } from '@colanode/core';
import { JSONContent } from '@tiptap/core';
import { Document } from '@/renderer/components/documents/document';
@@ -18,7 +18,7 @@ export const PageBody = ({ page, role }: PageBodyProps) => {
const workspace = useWorkspace();
const radar = useRadar();
const { mutate } = useMutation();
- const canEdit = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
const handleUpdate = useCallback(
(content: JSONContent) => {
diff --git a/apps/desktop/src/renderer/components/pages/page-container.tsx b/apps/desktop/src/renderer/components/pages/page-container.tsx
index 49954544..b8fd01c7 100644
--- a/apps/desktop/src/renderer/components/pages/page-container.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-container.tsx
@@ -1,4 +1,4 @@
-import { extractEntryRole } from '@colanode/core';
+import { extractEntryRole, PageEntry } from '@colanode/core';
import { PageBody } from '@/renderer/components/pages/page-body';
import { PageHeader } from '@/renderer/components/pages/page-header';
@@ -11,27 +11,41 @@ interface PageContainerProps {
export const PageContainer = ({ pageId }: PageContainerProps) => {
const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- type: 'entry_tree_get',
+
+ const { data: entry, isPending: isPendingEntry } = useQuery({
+ type: 'entry_get',
entryId: pageId,
userId: workspace.userId,
});
- if (isPending) {
+ const page = entry as PageEntry;
+
+ const { data: root, isPending: isPendingRoot } = useQuery(
+ {
+ type: 'entry_get',
+ entryId: page?.rootId ?? '',
+ userId: workspace.userId,
+ },
+ {
+ enabled: !!page?.rootId,
+ }
+ );
+
+ if (isPendingEntry || isPendingRoot) {
return null;
}
- const entries = data ?? [];
- const page = entries.find((entry) => entry.id === pageId);
- const role = extractEntryRole(entries, workspace.userId);
-
- if (!page || page.type !== 'page' || !role) {
+ if (!page || !root) {
return null;
}
+ const role = extractEntryRole(root, workspace.userId);
+ if (!role) {
+ return null;
+ }
return (
<div className="flex h-full w-full flex-col">
- <PageHeader entries={entries} page={page} role={role} />
+ <PageHeader page={page} role={role} />
<PageBody page={page} role={role} />
</div>
);
diff --git a/apps/desktop/src/renderer/components/pages/page-header.tsx b/apps/desktop/src/renderer/components/pages/page-header.tsx
index f2eb8c16..decdb517 100644
--- a/apps/desktop/src/renderer/components/pages/page-header.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-header.tsx
@@ -1,4 +1,4 @@
-import { Entry, EntryRole, PageEntry } from '@colanode/core';
+import { EntryRole, PageEntry } from '@colanode/core';
import { EntryBreadcrumb } from '@/renderer/components/layouts/entry-breadcrumb';
import { EntryFullscreenButton } from '@/renderer/components/layouts/entry-fullscreen-button';
@@ -7,19 +7,18 @@ import { Header } from '@/renderer/components/ui/header';
import { useContainer } from '@/renderer/contexts/container';
interface PageHeaderProps {
- entries: Entry[];
page: PageEntry;
role: EntryRole;
}
-export const PageHeader = ({ entries, page, role }: PageHeaderProps) => {
+export const PageHeader = ({ page, role }: PageHeaderProps) => {
const container = useContainer();
return (
<Header>
<div className="flex w-full items-center gap-2 px-4">
<div className="flex-grow">
- <EntryBreadcrumb entries={entries} />
+ <EntryBreadcrumb entry={page} />
{container.mode === 'modal' && (
<EntryFullscreenButton entryId={page.id} />
)}
diff --git a/apps/desktop/src/renderer/components/pages/page-settings.tsx b/apps/desktop/src/renderer/components/pages/page-settings.tsx
index 8a94a42b..1f6810fc 100644
--- a/apps/desktop/src/renderer/components/pages/page-settings.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-settings.tsx
@@ -1,4 +1,4 @@
-import { hasEditorAccess, EntryRole, PageEntry } from '@colanode/core';
+import { EntryRole, PageEntry, hasEntryRole } from '@colanode/core';
import { Copy, Image, LetterText, Settings, Trash2 } from 'lucide-react';
import React from 'react';
@@ -23,8 +23,8 @@ export const PageSettings = ({ page, role }: PageSettingsProps) => {
const [showUpdateDialog, setShowUpdateDialog] = React.useState(false);
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
- const canEdit = hasEditorAccess(role);
- const canDelete = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
+ const canDelete = hasEntryRole(role, 'editor');
return (
<React.Fragment>
diff --git a/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx b/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
index 10b3b45e..ae93284a 100644
--- a/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
@@ -1,4 +1,4 @@
-import { hasEditorAccess, EntryRole, PageEntry } from '@colanode/core';
+import { EntryRole, PageEntry, hasEntryRole } from '@colanode/core';
import { PageForm } from '@/renderer/components/pages/page-form';
import {
@@ -27,7 +27,7 @@ export const PageUpdateDialog = ({
}: PageUpdateDialogProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const canEdit = hasEditorAccess(role);
+ const canEdit = hasEntryRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/components/records/record-body.tsx b/apps/desktop/src/renderer/components/records/record-body.tsx
index 5b71320c..0379b353 100644
--- a/apps/desktop/src/renderer/components/records/record-body.tsx
+++ b/apps/desktop/src/renderer/components/records/record-body.tsx
@@ -1,7 +1,7 @@
import {
DatabaseEntry,
- hasEditorAccess,
EntryRole,
+ hasEntryRole,
RecordEntry,
} from '@colanode/core';
import { JSONContent } from '@tiptap/core';
@@ -20,23 +20,17 @@ import { useRadar } from '@/renderer/contexts/radar';
interface RecordBodyProps {
record: RecordEntry;
- recordRole: EntryRole;
database: DatabaseEntry;
- databaseRole: EntryRole;
+ role: EntryRole;
}
-export const RecordBody = ({
- record,
- recordRole,
- database,
- databaseRole,
-}: RecordBodyProps) => {
+export const RecordBody = ({ record, database, role }: RecordBodyProps) => {
const workspace = useWorkspace();
const radar = useRadar();
const { mutate } = useMutation();
const canEdit =
- record.createdBy === workspace.userId || hasEditorAccess(recordRole);
+ record.createdBy === workspace.userId || hasEntryRole(role, 'editor');
const handleUpdate = useCallback(
(content: JSONContent) => {
@@ -70,9 +64,9 @@ export const RecordBody = ({
}, [record.id, record.type, record.transactionId]);
return (
- <Database database={database} role={databaseRole}>
+ <Database database={database} role={role}>
<ScrollArea className="h-full max-h-full w-full overflow-y-auto px-10 pb-12">
- <RecordProvider record={record} role={recordRole}>
+ <RecordProvider record={record} role={role}>
<RecordAttributes />
</RecordProvider>
<Separator className="my-4 w-full" />
diff --git a/apps/desktop/src/renderer/components/records/record-container.tsx b/apps/desktop/src/renderer/components/records/record-container.tsx
index 0e3d28eb..25aac038 100644
--- a/apps/desktop/src/renderer/components/records/record-container.tsx
+++ b/apps/desktop/src/renderer/components/records/record-container.tsx
@@ -1,4 +1,4 @@
-import { extractEntryRole } from '@colanode/core';
+import { DatabaseEntry, extractEntryRole, RecordEntry } from '@colanode/core';
import { RecordBody } from '@/renderer/components/records/record-body';
import { RecordHeader } from '@/renderer/components/records/record-header';
@@ -11,55 +11,56 @@ interface RecordContainerProps {
export const RecordContainer = ({ recordId }: RecordContainerProps) => {
const workspace = useWorkspace();
- const { data, isPending } = useQuery({
- type: 'entry_tree_get',
+
+ const { data: entry, isPending: isPendingEntry } = useQuery({
+ type: 'entry_get',
entryId: recordId,
userId: workspace.userId,
});
- if (isPending) {
- return null;
- }
+ const record = entry as RecordEntry;
- const entries = data ?? [];
- const record = entries.find((entry) => entry.id === recordId);
- if (!record || record.type !== 'record') {
- return null;
- }
+ const { data: root, isPending: isPendingRoot } = useQuery(
+ {
+ type: 'entry_get',
+ entryId: record?.rootId ?? '',
+ userId: workspace.userId,
+ },
+ {
+ enabled: !!record?.rootId,
+ }
+ );
- const databaseIndex = entries.findIndex(
- (entry) => entry.id === record.attributes.databaseId
+ const { data: databaseEntry, isPending: isPendingDatabase } = useQuery(
+ {
+ type: 'entry_get',
+ entryId: record?.attributes.databaseId ?? '',
+ userId: workspace.userId,
+ },
+ {
+ enabled: !!record?.attributes.databaseId,
+ }
);
- if (databaseIndex === -1) {
+
+ const database = databaseEntry as DatabaseEntry;
+
+ if (isPendingEntry || isPendingRoot || isPendingDatabase) {
return null;
}
- const database = entries[databaseIndex];
- if (!database || database.type !== 'database') {
+ if (!record || !root || !database) {
return null;
}
- const databaseAncestors = entries.slice(0, databaseIndex);
-
- const recordRole = extractEntryRole(entries, workspace.userId);
- const databaseRole = extractEntryRole(
- [...databaseAncestors, database],
- workspace.userId
- );
-
- if (!recordRole || !databaseRole) {
+ const role = extractEntryRole(root, workspace.userId);
+ if (!role) {
return null;
}
return (
<div className="flex h-full w-full flex-col">
- <RecordHeader entries={entries} record={record} role={recordRole} />
- <RecordBody
- record={record}
- recordRole={recordRole}
- database={database}
- databaseRole={databaseRole}
- />
+ <RecordHeader record={record} role={role} />
+ <RecordBody record={record} database={database} role={role} />
</div>
);
};
diff --git a/apps/desktop/src/renderer/components/records/record-header.tsx b/apps/desktop/src/renderer/components/records/record-header.tsx
index 66acf95c..b7a701d2 100644
--- a/apps/desktop/src/renderer/components/records/record-header.tsx
+++ b/apps/desktop/src/renderer/components/records/record-header.tsx
@@ -1,4 +1,4 @@
-import { Entry, EntryRole, RecordEntry } from '@colanode/core';
+import { EntryRole, RecordEntry } from '@colanode/core';
import { EntryBreadcrumb } from '@/renderer/components/layouts/entry-breadcrumb';
import { EntryFullscreenButton } from '@/renderer/components/layouts/entry-fullscreen-button';
@@ -7,19 +7,18 @@ import { Header } from '@/renderer/components/ui/header';
import { useContainer } from '@/renderer/contexts/container';
interface RecordHeaderProps {
- entries: Entry[];
record: RecordEntry;
role: EntryRole;
}
-export const RecordHeader = ({ entries, record, role }: RecordHeaderProps) => {
+export const RecordHeader = ({ record, role }: RecordHeaderProps) => {
const container = useContainer();
return (
<Header>
<div className="flex w-full items-center gap-2 px-4">
<div className="flex-grow">
- {container.mode === 'main' && <EntryBreadcrumb entries={entries} />}
+ {container.mode === 'main' && <EntryBreadcrumb entry={record} />}
{container.mode === 'modal' && (
<EntryFullscreenButton entryId={record.id} />
)}
diff --git a/apps/desktop/src/renderer/components/records/record-provider.tsx b/apps/desktop/src/renderer/components/records/record-provider.tsx
index 5f0ace4e..ce11e2f9 100644
--- a/apps/desktop/src/renderer/components/records/record-provider.tsx
+++ b/apps/desktop/src/renderer/components/records/record-provider.tsx
@@ -1,4 +1,4 @@
-import { hasEditorAccess, EntryRole, RecordEntry } from '@colanode/core';
+import { EntryRole, RecordEntry, hasEntryRole } from '@colanode/core';
import React from 'react';
import { RecordContext } from '@/renderer/contexts/record';
@@ -19,7 +19,7 @@ export const RecordProvider = ({
const { mutate } = useMutation();
const canEdit =
- record.createdBy === workspace.userId || hasEditorAccess(role);
+ record.createdBy === workspace.userId || hasEntryRole(role, 'editor');
return (
<RecordContext.Provider
diff --git a/apps/desktop/src/renderer/components/records/record-settings.tsx b/apps/desktop/src/renderer/components/records/record-settings.tsx
index 29083323..d7b97063 100644
--- a/apps/desktop/src/renderer/components/records/record-settings.tsx
+++ b/apps/desktop/src/renderer/components/records/record-settings.tsx
@@ -1,4 +1,4 @@
-import { hasEditorAccess, EntryRole, RecordEntry } from '@colanode/core';
+import { EntryRole, RecordEntry, hasEntryRole } from '@colanode/core';
import { Copy, Settings, Trash2 } from 'lucide-react';
import React from 'react';
@@ -23,7 +23,7 @@ export const RecordSettings = ({ record, role }: RecordSettingsProps) => {
const workspace = useWorkspace();
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
const canDelete =
- record.createdBy === workspace.userId || hasEditorAccess(role);
+ record.createdBy === workspace.userId || hasEntryRole(role, 'editor');
return (
<React.Fragment>
diff --git a/apps/desktop/src/renderer/components/spaces/space-settings-dialog.tsx b/apps/desktop/src/renderer/components/spaces/space-settings-dialog.tsx
index 1a6b889f..e3e95f9b 100644
--- a/apps/desktop/src/renderer/components/spaces/space-settings-dialog.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-settings-dialog.tsx
@@ -1,4 +1,4 @@
-import { extractEntryRole, hasAdminAccess, SpaceEntry } from '@colanode/core';
+import { extractEntryRole, SpaceEntry, hasEntryRole } from '@colanode/core';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import { Info, Trash2, Users } from 'lucide-react';
@@ -38,7 +38,7 @@ export const SpaceSettingsDialog = ({
return null;
}
- const canDelete = hasAdminAccess(role);
+ const canDelete = hasEntryRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/shared/mutations/index.ts b/apps/desktop/src/shared/mutations/index.ts
index 17afaa42..e1527cfb 100644
--- a/apps/desktop/src/shared/mutations/index.ts
+++ b/apps/desktop/src/shared/mutations/index.ts
@@ -36,12 +36,15 @@ export type MutationErrorCode =
| 'account_not_found'
| 'account_login_failed'
| 'account_register_failed'
+ | 'user_not_found'
+ | 'entry_not_found'
| 'server_not_found'
| 'invalid_attributes'
| 'space_not_found'
| 'channel_not_found'
| 'unauthorized'
| 'invalid_file'
+ | 'file_not_found'
| 'node_not_found'
| 'view_not_found'
| 'field_not_found'
diff --git a/apps/desktop/src/shared/types/files.ts b/apps/desktop/src/shared/types/files.ts
index 0aa0ae70..d830a992 100644
--- a/apps/desktop/src/shared/types/files.ts
+++ b/apps/desktop/src/shared/types/files.ts
@@ -13,6 +13,7 @@ export type File = {
id: string;
type: FileType;
parentId: string;
+ entryId: string;
rootId: string;
name: string;
originalName: string;
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
index 7538f53e..6c576e46 100644
--- a/apps/server/src/controllers/client/workspaces/files/file-download-get.ts
+++ b/apps/server/src/controllers/client/workspaces/files/file-download-get.ts
@@ -1,5 +1,5 @@
import { Request, Response } from 'express';
-import { CreateDownloadOutput, hasViewerAccess } from '@colanode/core';
+import { CreateDownloadOutput, hasEntryRole } from '@colanode/core';
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
@@ -29,7 +29,7 @@ export const fileDownloadGetHandler = async (
}
const role = await fetchEntryRole(file.root_id, res.locals.user.id);
- if (role === null || !hasViewerAccess(role)) {
+ if (role === null || !hasEntryRole(role, 'viewer')) {
res.status(403).json({
code: ApiError.Forbidden,
message: 'Forbidden.',
diff --git a/apps/server/src/services/entry-service.ts b/apps/server/src/services/entry-service.ts
index 3ffaa5d0..f8cf8bb7 100644
--- a/apps/server/src/services/entry-service.ts
+++ b/apps/server/src/services/entry-service.ts
@@ -3,13 +3,15 @@ import {
generateId,
IdType,
EntryAttributes,
- EntryMutationContext,
EntryRole,
- registry,
MarkEntrySeenMutation,
MarkEntryOpenedMutation,
extractEntryRole,
- hasViewerAccess,
+ hasEntryRole,
+ entryAttributesSchema,
+ canCreateEntry,
+ canUpdateEntry,
+ canDeleteEntry,
} from '@colanode/core';
import { decodeState, YDoc } from '@colanode/crdt';
import { Transaction } from 'kysely';
@@ -26,7 +28,7 @@ import {
SelectCollaboration,
} from '@/data/schema';
import { eventBus } from '@/lib/event-bus';
-import { fetchEntryAncestors, mapEntry } from '@/lib/entries';
+import { fetchEntry, fetchEntryAncestors, mapEntry } from '@/lib/entries';
import { createLogger } from '@/lib/logger';
import {
ApplyCreateTransactionInput,
@@ -60,9 +62,11 @@ class EntryService {
public async createEntry(
input: CreateEntryInput
): Promise<CreateEntryOutput | null> {
- const model = registry.getModel(input.attributes.type);
const ydoc = new YDoc();
- const update = ydoc.updateAttributes(model.schema, input.attributes);
+ const update = ydoc.updateAttributes(
+ entryAttributesSchema,
+ input.attributes
+ );
const attributes = ydoc.getAttributes<EntryAttributes>();
const attributesJson = JSON.stringify(attributes);
@@ -177,8 +181,10 @@ class EntryService {
return { type: 'error', output: null };
}
- const model = registry.getModel(updatedAttributes.type);
- const update = ydoc.updateAttributes(model.schema, updatedAttributes);
+ const update = ydoc.updateAttributes(
+ entryAttributesSchema,
+ updatedAttributes
+ );
const attributes = ydoc.getAttributes<EntryAttributes>();
const attributesJson = JSON.stringify(attributes);
@@ -239,7 +245,6 @@ class EntryService {
await this.applyCollaboratorUpdates(
trx,
input.entryId,
- entry.rootId,
input.userId,
input.workspaceId,
collaboratorChanges
@@ -295,29 +300,27 @@ class EntryService {
user: SelectUser,
input: ApplyCreateTransactionInput
): Promise<ApplyCreateTransactionOutput | null> {
+ const root = await fetchEntry(input.rootId);
+ if (!root) {
+ return null;
+ }
+
const ydoc = new YDoc();
ydoc.applyUpdate(input.data);
const attributes = ydoc.getAttributes<EntryAttributes>();
- const ancestorRows = attributes.parentId
- ? await fetchEntryAncestors(attributes.parentId)
- : [];
-
- const ancestors = ancestorRows.map(mapEntry);
- const context = new EntryMutationContext(
- user.account_id,
- user.workspace_id,
- user.id,
- user.role,
- ancestors
- );
-
- const model = registry.getModel(attributes.type);
- if (!model.schema.safeParse(attributes).success) {
- return null;
- }
-
- if (!model.canCreate(context, attributes)) {
+ if (
+ !canCreateEntry(
+ {
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ },
+ attributes
+ )
+ ) {
return null;
}
@@ -325,9 +328,9 @@ class EntryService {
id: input.entryId,
root_id: input.rootId,
attributes: JSON.stringify(attributes),
- workspace_id: context.workspaceId,
+ workspace_id: user.workspace_id,
created_at: input.createdAt,
- created_by: context.userId,
+ created_by: user.id,
transaction_id: input.id,
};
@@ -335,12 +338,12 @@ class EntryService {
id: input.id,
entry_id: input.entryId,
root_id: input.rootId,
- workspace_id: context.workspaceId,
+ workspace_id: user.workspace_id,
operation: 'create',
data:
typeof input.data === 'string' ? decodeState(input.data) : input.data,
created_at: input.createdAt,
- created_by: context.userId,
+ created_by: user.id,
server_created_at: new Date(),
};
@@ -357,7 +360,7 @@ class EntryService {
entryId: input.entryId,
entryType: attributes.type,
rootId: input.rootId,
- workspaceId: context.workspaceId,
+ workspaceId: user.workspace_id,
});
for (const createdCollaboration of createdCollaborations) {
@@ -365,7 +368,7 @@ class EntryService {
type: 'collaboration_created',
collaboratorId: createdCollaboration.collaborator_id,
entryId: input.entryId,
- workspaceId: context.workspaceId,
+ workspaceId: user.workspace_id,
});
}
@@ -402,10 +405,12 @@ class EntryService {
user: SelectUser,
input: ApplyUpdateTransactionInput
): Promise<UpdateResult<ApplyUpdateTransactionOutput>> {
- const ancestorRows = await fetchEntryAncestors(input.entryId);
- const ancestors = ancestorRows.map(mapEntry);
+ const root = await fetchEntry(input.rootId);
+ if (!root) {
+ return { type: 'error', output: null };
+ }
- const entry = ancestors.find((ancestor) => ancestor.id === input.entryId);
+ const entry = await fetchEntry(input.entryId);
if (!entry) {
return { type: 'error', output: null };
}
@@ -430,20 +435,20 @@ class EntryService {
const attributes = ydoc.getAttributes<EntryAttributes>();
const attributesJson = JSON.stringify(attributes);
- const model = registry.getModel(attributes.type);
- if (!model.schema.safeParse(attributes).success) {
- return { type: 'error', output: null };
- }
-
- const context = new EntryMutationContext(
- user.account_id,
- user.workspace_id,
- user.id,
- user.role,
- ancestors
- );
- if (!model.canUpdate(context, entry, attributes)) {
+ if (
+ !canUpdateEntry(
+ {
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ },
+ attributes
+ )
+ ) {
return { type: 'error', output: null };
}
@@ -469,7 +474,7 @@ class EntryService {
transaction_id: input.id,
})
.where('id', '=', input.entryId)
- .where('transaction_id', '=', entry.transactionId)
+ .where('transaction_id', '=', entry.transaction_id)
.executeTakeFirst();
if (!updatedEntry) {
@@ -483,7 +488,7 @@ class EntryService {
id: input.id,
entry_id: input.entryId,
root_id: input.rootId,
- workspace_id: context.workspaceId,
+ workspace_id: user.workspace_id,
operation: 'update',
data:
typeof input.data === 'string'
@@ -503,9 +508,8 @@ class EntryService {
await this.applyCollaboratorUpdates(
trx,
input.entryId,
- input.rootId,
input.userId,
- context.workspaceId,
+ user.workspace_id,
collaboratorChanges
);
@@ -521,8 +525,8 @@ class EntryService {
type: 'entry_updated',
entryId: input.entryId,
entryType: entry.type,
- rootId: entry.rootId,
- workspaceId: context.workspaceId,
+ rootId: entry.root_id,
+ workspaceId: user.workspace_id,
});
for (const createdCollaboration of createdCollaborations) {
@@ -530,7 +534,7 @@ class EntryService {
type: 'collaboration_created',
collaboratorId: createdCollaboration.collaborator_id,
entryId: input.entryId,
- workspaceId: context.workspaceId,
+ workspaceId: user.workspace_id,
});
}
@@ -539,7 +543,7 @@ class EntryService {
type: 'collaboration_updated',
collaboratorId: updatedCollaboration.collaborator_id,
entryId: input.entryId,
- workspaceId: context.workspaceId,
+ workspaceId: user.workspace_id,
});
}
@@ -559,23 +563,26 @@ class EntryService {
user: SelectUser,
input: ApplyDeleteTransactionInput
): Promise<ApplyDeleteTransactionOutput | null> {
- const ancestorRows = await fetchEntryAncestors(input.entryId);
- const ancestors = ancestorRows.map(mapEntry);
- const entry = ancestors.find((ancestor) => ancestor.id === input.entryId);
+ const entry = await fetchEntry(input.entryId);
if (!entry) {
return null;
}
- const model = registry.getModel(entry.attributes.type);
- const context = new EntryMutationContext(
- user.account_id,
- user.workspace_id,
- user.id,
- user.role,
- ancestors
- );
+ const root = await fetchEntry(entry.root_id);
+ if (!root) {
+ return null;
+ }
- if (!model.canDelete(context, entry)) {
+ if (
+ !canDeleteEntry({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ })
+ ) {
return null;
}
@@ -636,7 +643,7 @@ class EntryService {
type: 'entry_deleted',
entryId: input.entryId,
entryType: entry.type,
- rootId: entry.rootId,
+ rootId: entry.root_id,
workspaceId: user.workspace_id,
});
@@ -687,7 +694,7 @@ class EntryService {
const rootEntry = mapEntry(root);
const role = extractEntryRole(rootEntry, user.id);
- if (!hasViewerAccess(role)) {
+ if (!role || !hasEntryRole(role, 'viewer')) {
return false;
}
@@ -768,7 +775,7 @@ class EntryService {
const rootEntry = mapEntry(root);
const role = extractEntryRole(rootEntry, user.id);
- if (!hasViewerAccess(role)) {
+ if (!role || !hasEntryRole(role, 'viewer')) {
return false;
}
@@ -881,7 +888,6 @@ class EntryService {
private async applyCollaboratorUpdates(
transaction: Transaction<DatabaseSchema>,
entryId: string,
- rootId: string,
userId: string,
workspaceId: string,
updateResult: CollaboratorChangeResult
diff --git a/apps/server/src/services/file-service.ts b/apps/server/src/services/file-service.ts
index 60279f10..aedc8b16 100644
--- a/apps/server/src/services/file-service.ts
+++ b/apps/server/src/services/file-service.ts
@@ -1,10 +1,11 @@
import {
+ canCreateFile,
+ canDeleteFile,
CreateFileMutation,
DeleteFileMutation,
extractEntryRole,
FileStatus,
- hasCollaboratorAccess,
- hasViewerAccess,
+ hasEntryRole,
MarkFileOpenedMutation,
MarkFileSeenMutation,
} from '@colanode/core';
@@ -12,7 +13,7 @@ import { DeleteObjectCommand } from '@aws-sdk/client-s3';
import { database } from '@/data/database';
import { SelectUser } from '@/data/schema';
-import { mapEntry } from '@/lib/entries';
+import { fetchEntry, mapEntry } from '@/lib/entries';
import { eventBus } from '@/lib/event-bus';
import { filesStorage, BUCKET_NAMES } from '@/data/storage';
@@ -30,19 +31,30 @@ class FileService {
return true;
}
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', mutation.data.rootId)
- .executeTakeFirst();
+ const entry = await fetchEntry(mutation.data.entryId);
+ if (!entry) {
+ return false;
+ }
+ const root = await fetchEntry(mutation.data.rootId);
if (!root) {
return false;
}
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!hasCollaboratorAccess(role)) {
+ if (
+ !canCreateFile({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ file: {
+ id: mutation.data.id,
+ parentId: mutation.data.parentId,
+ },
+ })
+ ) {
return false;
}
@@ -95,19 +107,31 @@ class FileService {
return true;
}
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', mutation.data.rootId)
- .executeTakeFirst();
+ const entry = await fetchEntry(file.entry_id);
+ if (!entry) {
+ return false;
+ }
+ const root = await fetchEntry(file.root_id);
if (!root) {
return false;
}
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!hasCollaboratorAccess(role)) {
+ if (
+ !canDeleteFile({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ file: {
+ id: mutation.data.id,
+ parentId: file.parent_id,
+ createdBy: file.created_by,
+ },
+ })
+ ) {
return false;
}
@@ -177,19 +201,14 @@ class FileService {
return false;
}
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', file.root_id)
- .executeTakeFirst();
-
+ const root = await fetchEntry(file.root_id);
if (!root) {
return false;
}
const rootEntry = mapEntry(root);
const role = extractEntryRole(rootEntry, user.id);
- if (!hasViewerAccess(role)) {
+ if (!role || !hasEntryRole(role, 'viewer')) {
return false;
}
@@ -250,7 +269,7 @@ class FileService {
): Promise<boolean> {
const file = await database
.selectFrom('files')
- .select(['id', 'root_id', 'workspace_id'])
+ .select(['id', 'entry_id', 'root_id', 'workspace_id'])
.where('id', '=', mutation.data.fileId)
.executeTakeFirst();
@@ -258,19 +277,14 @@ class FileService {
return false;
}
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', file.root_id)
- .executeTakeFirst();
-
+ const root = await fetchEntry(file.root_id);
if (!root) {
return false;
}
const rootEntry = mapEntry(root);
const role = extractEntryRole(rootEntry, user.id);
- if (!hasViewerAccess(role)) {
+ if (!role || !hasEntryRole(role, 'viewer')) {
return false;
}
diff --git a/apps/server/src/services/message-service.ts b/apps/server/src/services/message-service.ts
index efec6ac8..5b8caa3a 100644
--- a/apps/server/src/services/message-service.ts
+++ b/apps/server/src/services/message-service.ts
@@ -1,17 +1,19 @@
import {
+ canCreateMessage,
+ canCreateMessageReaction,
+ canDeleteMessage,
CreateMessageMutation,
CreateMessageReactionMutation,
DeleteMessageMutation,
DeleteMessageReactionMutation,
extractEntryRole,
- hasCollaboratorAccess,
- hasViewerAccess,
+ hasEntryRole,
MarkMessageSeenMutation,
} from '@colanode/core';
import { database } from '@/data/database';
import { SelectUser } from '@/data/schema';
-import { mapEntry } from '@/lib/entries';
+import { fetchEntry, mapEntry } from '@/lib/entries';
import { eventBus } from '@/lib/event-bus';
class MessageService {
@@ -28,19 +30,23 @@ class MessageService {
return true;
}
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', mutation.data.rootId)
- .executeTakeFirst();
+ const root = await fetchEntry(mutation.data.rootId);
+ const entry = await fetchEntry(mutation.data.entryId);
- if (!root) {
+ if (!root || !entry) {
return false;
}
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!hasCollaboratorAccess(role)) {
+ if (
+ !canCreateMessage({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ })
+ ) {
return false;
}
@@ -80,7 +86,7 @@ class MessageService {
): Promise<boolean> {
const message = await database
.selectFrom('messages')
- .select(['id', 'root_id', 'workspace_id'])
+ .select(['id', 'entry_id', 'root_id', 'workspace_id', 'created_by'])
.where('id', '=', mutation.data.id)
.executeTakeFirst();
@@ -88,19 +94,27 @@ class MessageService {
return true;
}
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', message.root_id)
- .executeTakeFirst();
+ const root = await fetchEntry(message.root_id);
+ const entry = await fetchEntry(message.entry_id);
- if (!root) {
+ if (!root || !entry) {
return false;
}
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!hasCollaboratorAccess(role)) {
+ if (
+ !canDeleteMessage({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ entry: mapEntry(entry),
+ message: {
+ id: message.id,
+ createdBy: message.created_by,
+ },
+ })
+ ) {
return false;
}
@@ -154,7 +168,7 @@ class MessageService {
): Promise<boolean> {
const message = await database
.selectFrom('messages')
- .select(['id', 'root_id', 'workspace_id'])
+ .select(['id', 'root_id', 'workspace_id', 'created_by'])
.where('id', '=', mutation.data.messageId)
.executeTakeFirst();
@@ -172,9 +186,19 @@ class MessageService {
return false;
}
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!hasCollaboratorAccess(role)) {
+ if (
+ !canCreateMessageReaction({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapEntry(root),
+ message: {
+ id: message.id,
+ createdBy: message.created_by,
+ },
+ })
+ ) {
return false;
}
@@ -238,7 +262,7 @@ class MessageService {
const rootEntry = mapEntry(root);
const role = extractEntryRole(rootEntry, user.id);
- if (!hasCollaboratorAccess(role)) {
+ if (!role || !hasEntryRole(role, 'commenter')) {
return false;
}
@@ -293,7 +317,7 @@ class MessageService {
const rootEntry = mapEntry(root);
const role = extractEntryRole(rootEntry, user.id);
- if (!hasViewerAccess(role)) {
+ if (!role || !hasEntryRole(role, 'viewer')) {
return false;
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 59644dde..0596be02 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -23,8 +23,9 @@ export * from './types/entries';
export * from './types/servers';
export * from './types/sync';
export * from './types/workspaces';
-export * from './lib/blocks';
export * from './types/mutations';
export * from './types/messages';
export * from './synchronizers';
export * from './lib/entries';
+export * from './lib/texts';
+export * from './lib/permissions';
diff --git a/packages/core/src/lib/entries.ts b/packages/core/src/lib/entries.ts
index 04dd0114..22125faa 100644
--- a/packages/core/src/lib/entries.ts
+++ b/packages/core/src/lib/entries.ts
@@ -46,27 +46,6 @@ export const extractEntryRole = (
return role;
};
-export const hasAdminAccess = (role: EntryRole | null): boolean => {
- return role === 'admin';
-};
-
-export const hasEditorAccess = (role: EntryRole | null): boolean => {
- return role === 'admin' || role === 'editor';
-};
-
-export const hasCollaboratorAccess = (role: EntryRole | null): boolean => {
- return role === 'admin' || role === 'editor' || role === 'collaborator';
-};
-
-export const hasViewerAccess = (role: EntryRole | null): boolean => {
- return (
- role === 'admin' ||
- role === 'editor' ||
- role === 'collaborator' ||
- role === 'viewer'
- );
-};
-
export const generateNodeIndex = (
previous?: string | null,
next?: string | null
diff --git a/packages/core/src/lib/permissions.ts b/packages/core/src/lib/permissions.ts
new file mode 100644
index 00000000..38c0f117
--- /dev/null
+++ b/packages/core/src/lib/permissions.ts
@@ -0,0 +1,284 @@
+import { isEqual } from 'lodash-es';
+
+import { extractEntryRole } from './entries';
+
+import { Entry, EntryAttributes } from '../registry';
+import { WorkspaceRole } from '../types/workspaces';
+
+import { EntryRole } from '~/registry/core';
+
+export type UserInput = {
+ userId: string;
+ role: WorkspaceRole;
+};
+
+export type CanCreateEntryInput = {
+ user: UserInput;
+ root: Entry | null;
+};
+
+export const canCreateEntry = (
+ input: CanCreateEntryInput,
+ attributes: EntryAttributes
+): boolean => {
+ if (input.user.role === 'none') {
+ return false;
+ }
+
+ if (attributes.type === 'chat') {
+ return true;
+ }
+
+ if (attributes.type === 'space') {
+ return hasWorkspaceRole(input.user.role, 'collaborator');
+ }
+
+ const root = input.root;
+ if (!root) {
+ return false;
+ }
+
+ const rootRole = extractEntryRole(root, input.user.userId);
+ if (!rootRole) {
+ return false;
+ }
+
+ return hasEntryRole(rootRole, 'editor');
+};
+
+export type CanUpdateEntryInput = {
+ user: UserInput;
+ root: Entry;
+ entry: Entry;
+};
+
+export const canUpdateEntry = (
+ input: CanUpdateEntryInput,
+ attributes: EntryAttributes
+): boolean => {
+ if (input.user.role === 'none') {
+ return false;
+ }
+
+ if (attributes.type === 'chat') {
+ return false;
+ }
+
+ const rootRole = extractEntryRole(input.root, input.user.userId);
+ if (!rootRole) {
+ return false;
+ }
+
+ if (attributes.type === 'space') {
+ if (input.entry.type !== 'space') {
+ return false;
+ }
+
+ const afterCollaborators = attributes.collaborators;
+ const beforeCollaborators = input.entry.attributes.collaborators;
+
+ if (!isEqual(afterCollaborators, beforeCollaborators)) {
+ return hasEntryRole(rootRole, 'admin');
+ }
+ }
+
+ return hasEntryRole(rootRole, 'editor');
+};
+
+export type CanDeleteEntryInput = {
+ user: UserInput;
+ root: Entry;
+ entry: Entry;
+};
+
+export const canDeleteEntry = (input: CanDeleteEntryInput): boolean => {
+ if (input.user.role === 'none') {
+ return false;
+ }
+
+ const entry = input.entry;
+ if (entry.attributes.type === 'chat') {
+ return false;
+ }
+
+ const rootRole = extractEntryRole(input.root, input.user.userId);
+ if (!rootRole) {
+ return false;
+ }
+
+ if (entry.attributes.type === 'record') {
+ return input.entry.createdBy === input.user.userId;
+ }
+
+ if (entry.attributes.type === 'space') {
+ return hasEntryRole(rootRole, 'admin');
+ }
+
+ return hasEntryRole(rootRole, 'editor');
+};
+
+export const hasWorkspaceRole = (
+ currentRole: WorkspaceRole,
+ targetRole: WorkspaceRole
+) => {
+ if (targetRole === 'owner') {
+ return currentRole === 'owner';
+ }
+
+ if (targetRole === 'admin') {
+ return currentRole === 'admin' || currentRole === 'owner';
+ }
+
+ if (targetRole === 'collaborator') {
+ return (
+ currentRole === 'admin' ||
+ currentRole === 'collaborator' ||
+ currentRole === 'owner'
+ );
+ }
+
+ if (targetRole === 'guest') {
+ return (
+ currentRole === 'admin' ||
+ currentRole === 'owner' ||
+ currentRole === 'collaborator' ||
+ currentRole === 'guest'
+ );
+ }
+
+ return false;
+};
+
+export const hasEntryRole = (currentRole: EntryRole, targetRole: EntryRole) => {
+ if (targetRole === 'admin') {
+ return currentRole === 'admin';
+ }
+
+ if (targetRole === 'editor') {
+ return currentRole === 'admin' || currentRole === 'editor';
+ }
+
+ if (targetRole === 'commenter') {
+ return (
+ currentRole === 'admin' ||
+ currentRole === 'editor' ||
+ currentRole === 'commenter'
+ );
+ }
+
+ if (targetRole === 'viewer') {
+ return (
+ currentRole === 'admin' ||
+ currentRole === 'editor' ||
+ currentRole === 'commenter' ||
+ currentRole === 'viewer'
+ );
+ }
+
+ return false;
+};
+
+export type CreateMessageInput = {
+ user: UserInput;
+ root: Entry;
+ entry: Entry;
+};
+
+export const canCreateMessage = (input: CreateMessageInput): boolean => {
+ const rootRole = extractEntryRole(input.root, input.user.userId);
+ if (!rootRole) {
+ return false;
+ }
+
+ return hasEntryRole(rootRole, 'commenter');
+};
+
+export type DeleteMessageInput = {
+ user: UserInput;
+ root: Entry;
+ entry: Entry;
+ message: {
+ id: string;
+ createdBy: string;
+ };
+};
+
+export const canDeleteMessage = (input: DeleteMessageInput): boolean => {
+ const rootRole = extractEntryRole(input.root, input.user.userId);
+ if (!rootRole) {
+ return false;
+ }
+
+ if (input.message.createdBy === input.user.userId) {
+ return true;
+ }
+
+ return hasEntryRole(rootRole, 'admin');
+};
+
+export type CanCreateMessageReactionInput = {
+ user: UserInput;
+ root: Entry;
+ message: {
+ id: string;
+ createdBy: string;
+ };
+};
+
+export const canCreateMessageReaction = (
+ input: CanCreateMessageReactionInput
+): boolean => {
+ const rootRole = extractEntryRole(input.root, input.user.userId);
+ if (!rootRole) {
+ return false;
+ }
+
+ return hasEntryRole(rootRole, 'viewer');
+};
+
+export type CreateFileInput = {
+ user: UserInput;
+ root: Entry;
+ entry: Entry;
+ file: {
+ id: string;
+ parentId: string;
+ };
+};
+
+export const canCreateFile = (input: CreateFileInput): boolean => {
+ const rootRole = extractEntryRole(input.root, input.user.userId);
+ if (!rootRole) {
+ return false;
+ }
+
+ if (input.file.parentId === input.entry.id) {
+ return hasEntryRole(rootRole, 'editor');
+ }
+
+ return hasEntryRole(rootRole, 'commenter');
+};
+
+export type DeleteFileInput = {
+ user: UserInput;
+ root: Entry;
+ entry: Entry;
+ file: {
+ id: string;
+ parentId: string;
+ createdBy: string;
+ };
+};
+
+export const canDeleteFile = (input: DeleteFileInput): boolean => {
+ const rootRole = extractEntryRole(input.root, input.user.userId);
+ if (!rootRole) {
+ return false;
+ }
+
+ if (input.file.createdBy === input.user.userId) {
+ return true;
+ }
+
+ return hasEntryRole(rootRole, 'admin');
+};
diff --git a/packages/core/src/lib/blocks.ts b/packages/core/src/lib/texts.ts
similarity index 53%
rename from packages/core/src/lib/blocks.ts
rename to packages/core/src/lib/texts.ts
index 9ba1d7ae..3cecfcc6 100644
--- a/packages/core/src/lib/blocks.ts
+++ b/packages/core/src/lib/texts.ts
@@ -1,6 +1,51 @@
import { Block } from '../registry/block';
+import { EntryAttributes } from '../registry';
+import { MessageContent } from '../types/messages';
-const collectText = (
+export type TextResult = {
+ id: string;
+ name: string | null;
+ text: string | null;
+};
+
+export const extractEntryText = (
+ id: string,
+ attributes: EntryAttributes
+): TextResult | undefined => {
+ if (attributes.type === 'page') {
+ return {
+ id,
+ name: attributes.name,
+ text: extractBlockTexts(id, attributes.content),
+ };
+ }
+ return undefined;
+};
+
+export const extractMessageText = (
+ id: string,
+ content: MessageContent
+): TextResult | undefined => {
+ return {
+ id,
+ name: null,
+ text: extractBlockTexts(id, content.blocks),
+ };
+};
+
+const extractBlockTexts = (
+ entryId: string,
+ blocks: Record<string, Block> | undefined | null
+): string | null => {
+ if (!blocks) {
+ return null;
+ }
+
+ const result = collectBlockText(entryId, blocks);
+ return result.length > 0 ? result : null;
+};
+
+const collectBlockText = (
blockId: string,
blocks: Record<string, Block>
): string => {
@@ -27,20 +72,8 @@ const collectText = (
// Recursively collect text from children
for (const child of children) {
- texts.push(collectText(child.id, blocks));
+ texts.push(collectBlockText(child.id, blocks));
}
return texts.join('\n');
};
-
-export const extractText = (
- entryId: string,
- blocks: Record<string, Block> | undefined | null
-): string | null => {
- if (!blocks) {
- return null;
- }
-
- const result = collectText(entryId, blocks);
- return result.length > 0 ? result : null;
-};
diff --git a/packages/core/src/registry/channel.ts b/packages/core/src/registry/channel.ts
index 4a6f7fef..c5651292 100644
--- a/packages/core/src/registry/channel.ts
+++ b/packages/core/src/registry/channel.ts
@@ -1,65 +1,10 @@
-import { isEqual } from 'lodash-es';
import { z } from 'zod';
-import { EntryModel, entryRoleEnum } from './core';
-
export const channelAttributesSchema = z.object({
type: z.literal('channel'),
name: z.string(),
avatar: z.string().nullable().optional(),
parentId: z.string(),
- collaborators: z.record(z.string(), entryRoleEnum).nullable().optional(),
});
export type ChannelAttributes = z.infer<typeof channelAttributesSchema>;
-
-export const channelModel: EntryModel = {
- type: 'channel',
- schema: channelAttributesSchema,
- getText: (id, attributes) => {
- if (attributes.type !== 'channel') {
- return undefined;
- }
-
- return {
- id,
- name: attributes.name,
- text: null,
- };
- },
- canCreate: async (context, attributes) => {
- if (attributes.type !== 'channel') {
- return false;
- }
-
- if (context.ancestors.length !== 1) {
- return false;
- }
-
- const parent = context.ancestors[0];
- if (!parent || parent.type !== 'space') {
- return false;
- }
-
- const collaboratorIds = Object.keys(attributes.collaborators ?? {});
- if (collaboratorIds.length > 0 && !context.hasAdminAccess()) {
- return false;
- }
-
- return context.hasEditorAccess();
- },
- canUpdate: async (context, node, attributes) => {
- if (attributes.type !== 'channel' || node.type !== 'channel') {
- return false;
- }
-
- if (!isEqual(node.attributes.collaborators, attributes.collaborators)) {
- return context.hasAdminAccess();
- }
-
- return context.hasEditorAccess();
- },
- canDelete: async (context, _) => {
- return context.hasEditorAccess();
- },
-};
diff --git a/packages/core/src/registry/chat.ts b/packages/core/src/registry/chat.ts
index 8929781e..89d5dee5 100644
--- a/packages/core/src/registry/chat.ts
+++ b/packages/core/src/registry/chat.ts
@@ -1,6 +1,6 @@
import { z } from 'zod';
-import { EntryModel, entryRoleEnum } from './core';
+import { entryRoleEnum } from './core';
export const chatAttributesSchema = z.object({
type: z.literal('chat'),
@@ -9,33 +9,3 @@ export const chatAttributesSchema = z.object({
});
export type ChatAttributes = z.infer<typeof chatAttributesSchema>;
-
-export const chatModel: EntryModel = {
- type: 'chat',
- schema: chatAttributesSchema,
- getText: () => {
- return undefined;
- },
- canCreate: async (context, attributes) => {
- if (attributes.type !== 'chat') {
- return false;
- }
-
- const collaboratorIds = Object.keys(attributes.collaborators ?? {});
- if (collaboratorIds.length !== 2) {
- return false;
- }
-
- if (!collaboratorIds.includes(context.userId)) {
- return false;
- }
-
- return true;
- },
- canUpdate: async () => {
- return false;
- },
- canDelete: async () => {
- return false;
- },
-};
diff --git a/packages/core/src/registry/core.ts b/packages/core/src/registry/core.ts
index a8ddb158..275bfd8f 100644
--- a/packages/core/src/registry/core.ts
+++ b/packages/core/src/registry/core.ts
@@ -1,85 +1,4 @@
-import { z, ZodSchema } from 'zod';
+import { z } from 'zod';
-import {
- extractEntryRole,
- hasAdminAccess,
- hasCollaboratorAccess,
- hasEditorAccess,
- hasViewerAccess,
-} from '../lib/entries';
-import { WorkspaceRole } from '../types/workspaces';
-
-import { Entry, EntryAttributes } from './';
-
-export type EntryRole = 'admin' | 'editor' | 'collaborator' | 'viewer';
-export const entryRoleEnum = z.enum([
- 'admin',
- 'editor',
- 'collaborator',
- 'viewer',
-]);
-
-export type EntryText = {
- id: string;
- name: string | null;
- text: string | null;
-};
-
-export class EntryMutationContext {
- public accountId: string;
- public workspaceId: string;
- public userId: string;
- public ancestors: Entry[];
- public entryRole: EntryRole | null;
- public workspaceRole: WorkspaceRole | null;
-
- constructor(
- accountId: string,
- workspaceId: string,
- userId: string,
- workspaceRole: WorkspaceRole | null,
- ancestors: Entry[]
- ) {
- this.accountId = accountId;
- this.workspaceId = workspaceId;
- this.userId = userId;
- this.workspaceRole = workspaceRole;
- this.ancestors = ancestors;
- this.entryRole = extractEntryRole(ancestors, userId);
- }
-
- public hasAdminAccess = () => {
- return hasAdminAccess(this.entryRole);
- };
-
- public hasEditorAccess = () => {
- return hasEditorAccess(this.entryRole);
- };
-
- public hasCollaboratorAccess = () => {
- return hasCollaboratorAccess(this.entryRole);
- };
-
- public hasViewerAccess = () => {
- return hasViewerAccess(this.entryRole);
- };
-}
-
-export interface EntryModel {
- type: string;
- schema: ZodSchema;
- canCreate: (
- context: EntryMutationContext,
- attributes: EntryAttributes
- ) => Promise<boolean>;
- canUpdate: (
- context: EntryMutationContext,
- entry: Entry,
- attributes: EntryAttributes
- ) => Promise<boolean>;
- canDelete: (context: EntryMutationContext, entry: Entry) => Promise<boolean>;
- getText: (
- id: string,
- attributes: EntryAttributes
- ) => EntryText | undefined | null;
-}
+export type EntryRole = 'admin' | 'editor' | 'commenter' | 'viewer';
+export const entryRoleEnum = z.enum(['admin', 'editor', 'commenter', 'viewer']);
diff --git a/packages/core/src/registry/database.ts b/packages/core/src/registry/database.ts
index 50815fdd..0b0b7779 100644
--- a/packages/core/src/registry/database.ts
+++ b/packages/core/src/registry/database.ts
@@ -1,7 +1,5 @@
-import { isEqual } from 'lodash-es';
import { z } from 'zod';
-import { EntryModel, entryRoleEnum } from './core';
import { fieldAttributesSchema } from './fields';
export const viewFieldAttributesSchema = z.object({
@@ -73,52 +71,9 @@ export const databaseAttributesSchema = z.object({
name: z.string(),
avatar: z.string().nullable().optional(),
parentId: z.string(),
- collaborators: z.record(z.string(), entryRoleEnum).nullable().optional(),
fields: z.record(z.string(), fieldAttributesSchema),
views: z.record(z.string(), viewAttributesSchema),
});
export type DatabaseAttributes = z.infer<typeof databaseAttributesSchema>;
export type ViewType = 'table' | 'board' | 'calendar';
-
-export const databaseModel: EntryModel = {
- type: 'database',
- schema: databaseAttributesSchema,
- getText: (id, attributes) => {
- if (attributes.type !== 'database') {
- return undefined;
- }
-
- return {
- id,
- name: attributes.name,
- text: null,
- };
- },
- canCreate: async (context, attributes) => {
- if (attributes.type !== 'database') {
- return false;
- }
-
- const collaboratorIds = Object.keys(attributes.collaborators ?? {});
- if (collaboratorIds.length > 0 && !context.hasAdminAccess()) {
- return false;
- }
-
- return context.hasEditorAccess();
- },
- canUpdate: async (context, node, attributes) => {
- if (attributes.type !== 'database' || node.type !== 'database') {
- return false;
- }
-
- if (!isEqual(node.attributes.collaborators, attributes.collaborators)) {
- return context.hasAdminAccess();
- }
-
- return context.hasEditorAccess();
- },
- canDelete: async (context, _) => {
- return context.hasEditorAccess();
- },
-};
diff --git a/packages/core/src/registry/folder.ts b/packages/core/src/registry/folder.ts
index 95486600..7d49462a 100644
--- a/packages/core/src/registry/folder.ts
+++ b/packages/core/src/registry/folder.ts
@@ -1,7 +1,6 @@
-import { isEqual } from 'lodash-es';
import { z } from 'zod';
-import { EntryModel, entryRoleEnum } from './core';
+import { entryRoleEnum } from './core';
export const folderAttributesSchema = z.object({
type: z.literal('folder'),
@@ -12,45 +11,3 @@ export const folderAttributesSchema = z.object({
});
export type FolderAttributes = z.infer<typeof folderAttributesSchema>;
-
-export const folderModel: EntryModel = {
- type: 'folder',
- schema: folderAttributesSchema,
- getText: (id, attributes) => {
- if (attributes.type !== 'folder') {
- return undefined;
- }
-
- return {
- id,
- name: attributes.name,
- text: null,
- };
- },
- canCreate: async (context, attributes) => {
- if (attributes.type !== 'folder') {
- return false;
- }
-
- const collaboratorIds = Object.keys(attributes.collaborators ?? {});
- if (collaboratorIds.length > 0 && !context.hasAdminAccess()) {
- return false;
- }
-
- return context.hasEditorAccess();
- },
- canUpdate: async (context, node, attributes) => {
- if (attributes.type !== 'folder' || node.type !== 'folder') {
- return false;
- }
-
- if (!isEqual(node.attributes.collaborators, attributes.collaborators)) {
- return context.hasAdminAccess();
- }
-
- return context.hasEditorAccess();
- },
- canDelete: async (context, _) => {
- return context.hasEditorAccess();
- },
-};
diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.ts
index d4741c84..1d860c04 100644
--- a/packages/core/src/registry/index.ts
+++ b/packages/core/src/registry/index.ts
@@ -1,11 +1,12 @@
-import { ChannelAttributes, channelModel } from './channel';
-import { ChatAttributes, chatModel } from './chat';
-import { EntryModel } from './core';
-import { DatabaseAttributes, databaseModel } from './database';
-import { FolderAttributes, folderModel } from './folder';
-import { PageAttributes, pageModel } from './page';
-import { RecordAttributes, recordModel } from './record';
-import { SpaceAttributes, spaceModel } from './space';
+import { z } from 'zod';
+
+import { ChannelAttributes, channelAttributesSchema } from './channel';
+import { ChatAttributes, chatAttributesSchema } from './chat';
+import { DatabaseAttributes, databaseAttributesSchema } from './database';
+import { FolderAttributes, folderAttributesSchema } from './folder';
+import { PageAttributes, pageAttributesSchema } from './page';
+import { RecordAttributes, recordAttributesSchema } from './record';
+import { SpaceAttributes, spaceAttributesSchema } from './space';
type EntryBase = {
id: string;
@@ -73,27 +74,12 @@ export type Entry =
| RecordEntry
| SpaceEntry;
-class Registry {
- private models: Map<string, EntryModel> = new Map();
-
- constructor() {
- this.models.set('channel', channelModel);
- this.models.set('chat', chatModel);
- this.models.set('database', databaseModel);
- this.models.set('folder', folderModel);
- this.models.set('page', pageModel);
- this.models.set('record', recordModel);
- this.models.set('space', spaceModel);
- }
-
- getModel(type: string): EntryModel {
- const model = this.models.get(type);
- if (!model) {
- throw new Error(`Model for type ${type} not found`);
- }
-
- return model;
- }
-}
-
-export const registry = new Registry();
+export const entryAttributesSchema = z.discriminatedUnion('type', [
+ channelAttributesSchema,
+ chatAttributesSchema,
+ databaseAttributesSchema,
+ folderAttributesSchema,
+ pageAttributesSchema,
+ recordAttributesSchema,
+ spaceAttributesSchema,
+]);
diff --git a/packages/core/src/registry/page.ts b/packages/core/src/registry/page.ts
index c4ccc948..3f69f6ed 100644
--- a/packages/core/src/registry/page.ts
+++ b/packages/core/src/registry/page.ts
@@ -1,10 +1,7 @@
-import { isEqual } from 'lodash-es';
import { z } from 'zod';
import { blockSchema } from './block';
-import { EntryModel, entryRoleEnum } from './core';
-
-import { extractText } from '../lib/blocks';
+import { entryRoleEnum } from './core';
export const pageAttributesSchema = z.object({
type: z.literal('page'),
@@ -16,45 +13,3 @@ export const pageAttributesSchema = z.object({
});
export type PageAttributes = z.infer<typeof pageAttributesSchema>;
-
-export const pageModel: EntryModel = {
- type: 'page',
- schema: pageAttributesSchema,
- getText: (id, attributes) => {
- if (attributes.type !== 'page') {
- return undefined;
- }
-
- return {
- id,
- name: attributes.name,
- text: extractText(id, attributes.content),
- };
- },
- canCreate: async (context, attributes) => {
- if (attributes.type !== 'page') {
- return false;
- }
-
- const collaboratorIds = Object.keys(attributes.collaborators ?? {});
- if (collaboratorIds.length > 0 && !context.hasAdminAccess()) {
- return false;
- }
-
- return context.hasEditorAccess();
- },
- canUpdate: async (context, node, attributes) => {
- if (attributes.type !== 'page' || node.type !== 'page') {
- return false;
- }
-
- if (!isEqual(attributes.collaborators, node.attributes.collaborators)) {
- return context.hasAdminAccess();
- }
-
- return context.hasEditorAccess();
- },
- canDelete: async (context, _) => {
- return context.hasEditorAccess();
- },
-};
diff --git a/packages/core/src/registry/record.ts b/packages/core/src/registry/record.ts
index db789cb8..6f9295f2 100644
--- a/packages/core/src/registry/record.ts
+++ b/packages/core/src/registry/record.ts
@@ -1,11 +1,8 @@
import { z } from 'zod';
-import { EntryModel } from './core';
import { blockSchema } from './block';
import { fieldValueSchema } from './fields';
-import { extractText } from '../lib/blocks';
-
export const recordAttributesSchema = z.object({
type: z.literal('record'),
parentId: z.string(),
@@ -17,48 +14,3 @@ export const recordAttributesSchema = z.object({
});
export type RecordAttributes = z.infer<typeof recordAttributesSchema>;
-
-export const recordModel: EntryModel = {
- type: 'record',
- schema: recordAttributesSchema,
- getText: (id, attributes) => {
- if (attributes.type !== 'record') {
- return undefined;
- }
-
- return {
- id,
- name: attributes.name,
- text: extractText(id, attributes.content),
- };
- },
- canCreate: async (context, attributes) => {
- if (attributes.type !== 'record') {
- return false;
- }
-
- return context.hasCollaboratorAccess();
- },
- canUpdate: async (context, node, attributes) => {
- if (attributes.type !== 'record' || node.type !== 'record') {
- return false;
- }
-
- if (node.createdBy === context.userId) {
- return true;
- }
-
- return context.hasEditorAccess();
- },
- canDelete: async (context, node) => {
- if (node.type !== 'record') {
- return false;
- }
-
- if (node.createdBy === context.userId) {
- return true;
- }
-
- return context.hasEditorAccess();
- },
-};
diff --git a/packages/core/src/registry/space.ts b/packages/core/src/registry/space.ts
index 8e8613fa..767ba596 100644
--- a/packages/core/src/registry/space.ts
+++ b/packages/core/src/registry/space.ts
@@ -1,6 +1,6 @@
import { z } from 'zod';
-import { EntryModel, entryRoleEnum } from './core';
+import { entryRoleEnum } from './core';
export const spaceAttributesSchema = z.object({
type: z.literal('space'),
@@ -12,32 +12,3 @@ export const spaceAttributesSchema = z.object({
});
export type SpaceAttributes = z.infer<typeof spaceAttributesSchema>;
-
-export const spaceModel: EntryModel = {
- type: 'space',
- schema: spaceAttributesSchema,
- getText: (id, attributes) => {
- if (attributes.type !== 'space') {
- return undefined;
- }
-
- return {
- id,
- name: attributes.name,
- text: null,
- };
- },
- canCreate: async (context, __) => {
- if (context.workspaceRole === 'guest' || context.workspaceRole === 'none') {
- return false;
- }
-
- return true;
- },
- canUpdate: async (context, _, __) => {
- return context.hasAdminAccess();
- },
- canDelete: async (context, _) => {
- return context.hasAdminAccess();
- },
-};