mirror of
https://github.com/docmost/docmost.git
synced 2026-05-14 20:54:07 +08:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 52b34bc6f4 |
@@ -44,6 +44,7 @@
|
|||||||
"@nestjs-labs/nestjs-ioredis": "^11.0.4",
|
"@nestjs-labs/nestjs-ioredis": "^11.0.4",
|
||||||
"@nestjs/bullmq": "^11.0.4",
|
"@nestjs/bullmq": "^11.0.4",
|
||||||
"@nestjs/common": "^11.1.9",
|
"@nestjs/common": "^11.1.9",
|
||||||
|
"nestjs-cls": "^4.5.0",
|
||||||
"@nestjs/config": "^4.0.2",
|
"@nestjs/config": "^4.0.2",
|
||||||
"@nestjs/core": "^11.1.9",
|
"@nestjs/core": "^11.1.9",
|
||||||
"@nestjs/event-emitter": "^3.0.1",
|
"@nestjs/event-emitter": "^3.0.1",
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
|
import { AuditActorInterceptor } from './common/interceptors/audit-actor.interceptor';
|
||||||
import { CoreModule } from './core/core.module';
|
import { CoreModule } from './core/core.module';
|
||||||
import { EnvironmentModule } from './integrations/environment/environment.module';
|
import { EnvironmentModule } from './integrations/environment/environment.module';
|
||||||
import { CollaborationModule } from './collaboration/collaboration.module';
|
import { CollaborationModule } from './collaboration/collaboration.module';
|
||||||
@@ -18,6 +20,7 @@ import { SecurityModule } from './integrations/security/security.module';
|
|||||||
import { TelemetryModule } from './integrations/telemetry/telemetry.module';
|
import { TelemetryModule } from './integrations/telemetry/telemetry.module';
|
||||||
import { RedisModule } from '@nestjs-labs/nestjs-ioredis';
|
import { RedisModule } from '@nestjs-labs/nestjs-ioredis';
|
||||||
import { RedisConfigService } from './integrations/redis/redis-config.service';
|
import { RedisConfigService } from './integrations/redis/redis-config.service';
|
||||||
|
import { ClsModule } from 'nestjs-cls';
|
||||||
|
|
||||||
const enterpriseModules = [];
|
const enterpriseModules = [];
|
||||||
try {
|
try {
|
||||||
@@ -35,6 +38,10 @@ try {
|
|||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
ClsModule.forRoot({
|
||||||
|
global: true,
|
||||||
|
middleware: { mount: true },
|
||||||
|
}),
|
||||||
CoreModule,
|
CoreModule,
|
||||||
DatabaseModule,
|
DatabaseModule,
|
||||||
EnvironmentModule,
|
EnvironmentModule,
|
||||||
@@ -60,6 +67,12 @@ try {
|
|||||||
...enterpriseModules,
|
...enterpriseModules,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [
|
||||||
|
AppService,
|
||||||
|
{
|
||||||
|
provide: APP_INTERCEPTOR,
|
||||||
|
useClass: AuditActorInterceptor,
|
||||||
|
},
|
||||||
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { TokenService } from '../../core/auth/services/token.service';
|
|||||||
import { UserRepo } from '@docmost/db/repos/user/user.repo';
|
import { UserRepo } from '@docmost/db/repos/user/user.repo';
|
||||||
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
||||||
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
||||||
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
|
||||||
import { findHighestUserSpaceRole } from '@docmost/db/repos/space/utils';
|
import { findHighestUserSpaceRole } from '@docmost/db/repos/space/utils';
|
||||||
import { SpaceRole } from '../../common/helpers/types/permission';
|
import { SpaceRole } from '../../common/helpers/types/permission';
|
||||||
import { getPageId } from '../collaboration.util';
|
import { getPageId } from '../collaboration.util';
|
||||||
@@ -24,7 +23,6 @@ export class AuthenticationExtension implements Extension {
|
|||||||
private userRepo: UserRepo,
|
private userRepo: UserRepo,
|
||||||
private pageRepo: PageRepo,
|
private pageRepo: PageRepo,
|
||||||
private readonly spaceMemberRepo: SpaceMemberRepo,
|
private readonly spaceMemberRepo: SpaceMemberRepo,
|
||||||
private readonly pagePermissionRepo: PagePermissionRepo,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async onAuthenticate(data: onAuthenticatePayload) {
|
async onAuthenticate(data: onAuthenticatePayload) {
|
||||||
@@ -70,31 +68,9 @@ export class AuthenticationExtension implements Extension {
|
|||||||
throw new UnauthorizedException();
|
throw new UnauthorizedException();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check page-level permissions
|
if (userSpaceRole === SpaceRole.READER) {
|
||||||
const { hasRestriction, canAccess, canEdit } =
|
data.connection.readOnly = true;
|
||||||
await this.pagePermissionRepo.getUserPageAccessLevel(user.id, page.id);
|
this.logger.debug(`User granted readonly access to page: ${pageId}`);
|
||||||
|
|
||||||
if (hasRestriction) {
|
|
||||||
// Page has restrictions - use page-level permissions
|
|
||||||
if (!canAccess) {
|
|
||||||
this.logger.warn(
|
|
||||||
`User ${user.id} denied page-level access to page: ${pageId}`,
|
|
||||||
);
|
|
||||||
throw new UnauthorizedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!canEdit) {
|
|
||||||
data.connection.readOnly = true;
|
|
||||||
this.logger.debug(
|
|
||||||
`User ${user.id} granted readonly access to restricted page: ${pageId}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// No restrictions - use space-level permissions
|
|
||||||
if (userSpaceRole === SpaceRole.READER) {
|
|
||||||
data.connection.readOnly = true;
|
|
||||||
this.logger.debug(`User granted readonly access to page: ${pageId}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.logger.debug(`Authenticated user ${user.id} on page ${pageId}`);
|
this.logger.debug(`Authenticated user ${user.id} on page ${pageId}`);
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
export const AuditEvent = {
|
||||||
|
// Workspace Invitations
|
||||||
|
WORKSPACE_CREATED: 'workspace.created',
|
||||||
|
WORKSPACE_INVITE_CREATED: 'workspace.invite_created',
|
||||||
|
WORKSPACE_INVITE_REVOKED: 'workspace.invite_revoked',
|
||||||
|
|
||||||
|
WORKSPACE_INVITE_ACCEPTED: 'workspace.invite_accepted',
|
||||||
|
|
||||||
|
WORKSPACE_USER_CREATED: 'workspace.user_created',
|
||||||
|
WORKSPACE_USER_DEACTIVATED: 'workspace.user_deactivated',
|
||||||
|
|
||||||
|
WORKSPACE_ALLOWED_DOMAIN_UPDATED: 'workspace.allowed_domain_updated',
|
||||||
|
WORKSPACE_ICON_CHANGED: 'workspace.icon_changed',
|
||||||
|
WORKSPACE_NAME_CHANGED: 'workspace.name_changed',
|
||||||
|
|
||||||
|
WORKSPACE_AI_TOGGLED: 'workspace.ai_toggled',
|
||||||
|
|
||||||
|
USER_CREATED: 'user.created',
|
||||||
|
USER_DELETED: 'user.deleted',
|
||||||
|
USER_LOGIN: 'user.login',
|
||||||
|
USER_LOGOUT: 'user.logout',
|
||||||
|
USER_ROLE_CHANGED: 'user.user_role_changed',
|
||||||
|
USER_PASSWORD_CHANGED: 'user.password_changed',
|
||||||
|
USER_PASSWORD_RESET: 'user.reset_password',
|
||||||
|
USER_PHOTO_CHANGED: 'user.reset_password',
|
||||||
|
USER_NAME_CHANGED: 'user.name_changed',
|
||||||
|
USER_EMAIL_CHANGED: 'user.email_changed',
|
||||||
|
USER_MFA_SETUP: 'user.mfa_setup',
|
||||||
|
USER_MFA_BACKUP_CODE_GENERATED: 'user.mfa_backup_code_generated',
|
||||||
|
|
||||||
|
// API Keys
|
||||||
|
API_KEY_CREATED: 'api_key.created',
|
||||||
|
API_KEY_UPDATED: 'api_key.updated',
|
||||||
|
API_KEY_DELETED: 'api_key.deleted',
|
||||||
|
|
||||||
|
// Space
|
||||||
|
SPACE_CREATED: 'space.created',
|
||||||
|
SPACE_UPDATED: 'space.updated',
|
||||||
|
SPACE_DELETED: 'space.deleted',
|
||||||
|
|
||||||
|
SPACE_MEMBER_ADDED: 'space.member_added',
|
||||||
|
SPACE_MEMBER_REMOVED: 'space.member_removed',
|
||||||
|
SPACE_MEMBER_ROLE_CHANGED: 'space.member_role_changed',
|
||||||
|
|
||||||
|
// OR SPACE_USER_ADDED: 'space.user_added',
|
||||||
|
// SPACE_GROUP_ADDED: 'space.group_added',
|
||||||
|
|
||||||
|
// GROUP
|
||||||
|
GROUP_CREATED: 'group.created',
|
||||||
|
GROUP_UPDATED: 'group.updated',
|
||||||
|
GROUP_DELETED: 'group.deleted',
|
||||||
|
|
||||||
|
GROUP_MEMBER_ADDED: 'group.member_added',
|
||||||
|
GROUP_MEMBER_REMOVED: 'group.member_removed',
|
||||||
|
|
||||||
|
// Comments
|
||||||
|
COMMENT_CREATED: 'comment.created',
|
||||||
|
COMMENT_UPDATED: 'comment.updated',
|
||||||
|
COMMENT_DELETED: 'comment.deleted',
|
||||||
|
COMMENT_RESOLVED: 'comment.resolved',
|
||||||
|
COMMENT_REOPENED: 'comment.reopened',
|
||||||
|
|
||||||
|
// PAGE
|
||||||
|
PAGE_CREATED: 'page.created',
|
||||||
|
PAGE_UPDATED: 'page.updated',
|
||||||
|
PAGE_TRASHED: 'page.trash',
|
||||||
|
PAGE_DELETED: 'page.deleted',
|
||||||
|
PAGE_SHARED: 'page.shared',
|
||||||
|
|
||||||
|
ATTACHMENT_UPLOADED: 'attachment.uploaded',
|
||||||
|
|
||||||
|
PAGE_IMPORTED: 'page.imported',
|
||||||
|
PAGE_RESTORED: 'page.restored',
|
||||||
|
PAGE_EXPORTED: 'page.exported',
|
||||||
|
SPACE_EXPORTED: 'space.imported',
|
||||||
|
|
||||||
|
// SSO EVENTS
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type AuditEventType = (typeof AuditEvent)[keyof typeof AuditEvent];
|
||||||
|
|
||||||
|
export type ActorType = 'user' | 'system' | 'api_key';
|
||||||
|
|
||||||
|
export interface AuditLogPayload {
|
||||||
|
event: AuditEventType;
|
||||||
|
resourceType: string;
|
||||||
|
resourceId?: string;
|
||||||
|
changes?: {
|
||||||
|
before?: Record<string, any>;
|
||||||
|
after?: Record<string, any>;
|
||||||
|
};
|
||||||
|
metadata?: Record<string, any>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuditLogData extends AuditLogPayload {
|
||||||
|
workspaceId: string;
|
||||||
|
actorId?: string;
|
||||||
|
actorType: ActorType;
|
||||||
|
ipAddress?: string;
|
||||||
|
userAgent?: string;
|
||||||
|
}
|
||||||
@@ -14,12 +14,3 @@ export enum SpaceVisibility {
|
|||||||
OPEN = 'open', // any workspace member can see that it exists and join.
|
OPEN = 'open', // any workspace member can see that it exists and join.
|
||||||
PRIVATE = 'private', // only added space users can see
|
PRIVATE = 'private', // only added space users can see
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum PageAccessLevel {
|
|
||||||
RESTRICTED = 'restricted', // only specific users/groups can view or edit
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum PagePermissionRole {
|
|
||||||
READER = 'reader', // can only view content and descendants
|
|
||||||
WRITER = 'writer', // can edit content, descendants, and add new users to permission
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import {
|
||||||
|
CallHandler,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
NestInterceptor,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { ClsService } from 'nestjs-cls';
|
||||||
|
import { AuditContext, AUDIT_CONTEXT_KEY } from '../middlewares/audit-context.middleware';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuditActorInterceptor implements NestInterceptor {
|
||||||
|
constructor(private readonly cls: ClsService) {}
|
||||||
|
|
||||||
|
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||||||
|
const request = context.switchToHttp().getRequest();
|
||||||
|
const user = request.user?.user;
|
||||||
|
|
||||||
|
if (user?.id) {
|
||||||
|
const auditContext = this.cls.get<AuditContext>(AUDIT_CONTEXT_KEY);
|
||||||
|
if (auditContext) {
|
||||||
|
auditContext.actorId = user.id;
|
||||||
|
this.cls.set(AUDIT_CONTEXT_KEY, auditContext);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return next.handle();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||||
|
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||||
|
import { ClsService } from 'nestjs-cls';
|
||||||
|
|
||||||
|
export interface AuditContext {
|
||||||
|
workspaceId: string | null;
|
||||||
|
actorId: string | null;
|
||||||
|
actorType: 'user' | 'system' | 'api_key';
|
||||||
|
ipAddress: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AUDIT_CONTEXT_KEY = 'auditContext';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuditContextMiddleware implements NestMiddleware {
|
||||||
|
constructor(private readonly cls: ClsService) {}
|
||||||
|
|
||||||
|
use(req: FastifyRequest['raw'], res: FastifyReply['raw'], next: () => void) {
|
||||||
|
const workspaceId = (req as any).workspaceId ?? null;
|
||||||
|
const ipAddress = this.extractIpAddress(req);
|
||||||
|
|
||||||
|
const auditContext: AuditContext = {
|
||||||
|
workspaceId,
|
||||||
|
actorId: null,
|
||||||
|
actorType: 'user',
|
||||||
|
ipAddress,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.cls.set(AUDIT_CONTEXT_KEY, auditContext);
|
||||||
|
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
private extractIpAddress(req: FastifyRequest['raw']): string | null {
|
||||||
|
const xForwardedFor = req.headers['x-forwarded-for'];
|
||||||
|
if (xForwardedFor) {
|
||||||
|
const ips = Array.isArray(xForwardedFor)
|
||||||
|
? xForwardedFor[0]
|
||||||
|
: xForwardedFor.split(',')[0];
|
||||||
|
return ips?.trim() ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const xRealIp = req.headers['x-real-ip'];
|
||||||
|
if (xRealIp) {
|
||||||
|
return Array.isArray(xRealIp) ? xRealIp[0] : xRealIp;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (req as any).socket?.remoteAddress ?? null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,7 +53,6 @@ import { TokenService } from '../auth/services/token.service';
|
|||||||
import { JwtAttachmentPayload, JwtType } from '../auth/dto/jwt-payload';
|
import { JwtAttachmentPayload, JwtType } from '../auth/dto/jwt-payload';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import { RemoveIconDto } from './dto/attachment.dto';
|
import { RemoveIconDto } from './dto/attachment.dto';
|
||||||
import { PageAccessService } from '../page-access/page-access.service';
|
|
||||||
|
|
||||||
@Controller()
|
@Controller()
|
||||||
export class AttachmentController {
|
export class AttachmentController {
|
||||||
@@ -68,7 +67,6 @@ export class AttachmentController {
|
|||||||
private readonly attachmentRepo: AttachmentRepo,
|
private readonly attachmentRepo: AttachmentRepo,
|
||||||
private readonly environmentService: EnvironmentService,
|
private readonly environmentService: EnvironmentService,
|
||||||
private readonly tokenService: TokenService,
|
private readonly tokenService: TokenService,
|
||||||
private readonly pageAccessService: PageAccessService,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@@ -113,8 +111,13 @@ export class AttachmentController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Checks both space-level and page-level edit permissions
|
const spaceAbility = await this.spaceAbility.createForUser(
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
user,
|
||||||
|
page.spaceId,
|
||||||
|
);
|
||||||
|
if (spaceAbility.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
|
||||||
const spaceId = page.spaceId;
|
const spaceId = page.spaceId;
|
||||||
|
|
||||||
@@ -168,13 +171,14 @@ export class AttachmentController {
|
|||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = await this.pageRepo.findById(attachment.pageId);
|
const spaceAbility = await this.spaceAbility.createForUser(
|
||||||
if (!page) {
|
user,
|
||||||
throw new NotFoundException();
|
attachment.spaceId,
|
||||||
}
|
);
|
||||||
|
|
||||||
// Checks both space-level and page-level view permissions
|
if (spaceAbility.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
||||||
await this.pageAccessService.validateCanView(page, user);
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const fileStream = await this.storageService.read(attachment.filePath);
|
const fileStream = await this.storageService.read(attachment.filePath);
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ import {
|
|||||||
SpaceCaslSubject,
|
SpaceCaslSubject,
|
||||||
} from '../casl/interfaces/space-ability.type';
|
} from '../casl/interfaces/space-ability.type';
|
||||||
import { CommentRepo } from '@docmost/db/repos/comment/comment.repo';
|
import { CommentRepo } from '@docmost/db/repos/comment/comment.repo';
|
||||||
import { PageAccessService } from '../page-access/page-access.service';
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Controller('comments')
|
@Controller('comments')
|
||||||
@@ -34,7 +33,6 @@ export class CommentController {
|
|||||||
private readonly commentRepo: CommentRepo,
|
private readonly commentRepo: CommentRepo,
|
||||||
private readonly pageRepo: PageRepo,
|
private readonly pageRepo: PageRepo,
|
||||||
private readonly spaceAbility: SpaceAbilityFactory,
|
private readonly spaceAbility: SpaceAbilityFactory,
|
||||||
private readonly pageAccessService: PageAccessService,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@@ -49,7 +47,10 @@ export class CommentController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
||||||
|
if (ability.cannot(SpaceCaslAction.Create, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
|
||||||
return this.commentService.create(
|
return this.commentService.create(
|
||||||
{
|
{
|
||||||
@@ -74,8 +75,10 @@ export class CommentController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.pageAccessService.validateCanView(page, user);
|
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
||||||
|
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
return this.commentService.findByPageId(page.id, pagination);
|
return this.commentService.findByPageId(page.id, pagination);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,13 +90,13 @@ export class CommentController {
|
|||||||
throw new NotFoundException('Comment not found');
|
throw new NotFoundException('Comment not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = await this.pageRepo.findById(comment.pageId);
|
const ability = await this.spaceAbility.createForUser(
|
||||||
if (!page) {
|
user,
|
||||||
throw new NotFoundException('Page not found');
|
comment.spaceId,
|
||||||
|
);
|
||||||
|
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.pageAccessService.validateCanView(page, user);
|
|
||||||
|
|
||||||
return comment;
|
return comment;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,12 +108,17 @@ export class CommentController {
|
|||||||
throw new NotFoundException('Comment not found');
|
throw new NotFoundException('Comment not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = await this.pageRepo.findById(comment.pageId);
|
const ability = await this.spaceAbility.createForUser(
|
||||||
if (!page) {
|
user,
|
||||||
throw new NotFoundException('Page not found');
|
comment.spaceId,
|
||||||
}
|
);
|
||||||
|
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
// must be a space member with edit permission
|
||||||
|
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'You must have space edit permission to edit comments',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return this.commentService.update(comment, dto, user);
|
return this.commentService.update(comment, dto, user);
|
||||||
}
|
}
|
||||||
@@ -123,27 +131,41 @@ export class CommentController {
|
|||||||
throw new NotFoundException('Comment not found');
|
throw new NotFoundException('Comment not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = await this.pageRepo.findById(comment.pageId);
|
const ability = await this.spaceAbility.createForUser(
|
||||||
if (!page) {
|
user,
|
||||||
throw new NotFoundException('Page not found');
|
comment.spaceId,
|
||||||
}
|
);
|
||||||
|
|
||||||
// Check page-level edit permission first
|
// must be a space member with edit permission
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
|
||||||
// Check if user is the comment owner
|
// Check if user is the comment owner
|
||||||
const isOwner = comment.creatorId === user.id;
|
const isOwner = comment.creatorId === user.id;
|
||||||
|
|
||||||
if (isOwner) {
|
if (isOwner) {
|
||||||
|
/*
|
||||||
|
// Check if comment has children from other users
|
||||||
|
const hasChildrenFromOthers =
|
||||||
|
await this.commentRepo.hasChildrenFromOtherUsers(comment.id, user.id);
|
||||||
|
|
||||||
|
// Owner can delete if no children from other users
|
||||||
|
if (!hasChildrenFromOthers) {
|
||||||
|
await this.commentRepo.deleteComment(comment.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If has children from others, only space admin can delete
|
||||||
|
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Settings)) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Only space admins can delete comments with replies from other users',
|
||||||
|
);
|
||||||
|
}*/
|
||||||
await this.commentRepo.deleteComment(comment.id);
|
await this.commentRepo.deleteComment(comment.id);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ability = await this.spaceAbility.createForUser(
|
|
||||||
user,
|
|
||||||
comment.spaceId,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Space admin can delete any comment
|
// Space admin can delete any comment
|
||||||
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Settings)) {
|
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Settings)) {
|
||||||
throw new ForbiddenException(
|
throw new ForbiddenException(
|
||||||
|
|||||||
@@ -14,9 +14,14 @@ import { SearchModule } from './search/search.module';
|
|||||||
import { SpaceModule } from './space/space.module';
|
import { SpaceModule } from './space/space.module';
|
||||||
import { GroupModule } from './group/group.module';
|
import { GroupModule } from './group/group.module';
|
||||||
import { CaslModule } from './casl/casl.module';
|
import { CaslModule } from './casl/casl.module';
|
||||||
import { PageAccessModule } from './page-access/page-access.module';
|
|
||||||
import { DomainMiddleware } from '../common/middlewares/domain.middleware';
|
import { DomainMiddleware } from '../common/middlewares/domain.middleware';
|
||||||
|
import { AuditContextMiddleware } from '../common/middlewares/audit-context.middleware';
|
||||||
import { ShareModule } from './share/share.module';
|
import { ShareModule } from './share/share.module';
|
||||||
|
import {
|
||||||
|
AUDIT_SERVICE,
|
||||||
|
NoopAuditService,
|
||||||
|
} from '../integrations/audit/audit.service';
|
||||||
|
import { ClsMiddleware } from 'nestjs-cls';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -30,20 +35,33 @@ import { ShareModule } from './share/share.module';
|
|||||||
SpaceModule,
|
SpaceModule,
|
||||||
GroupModule,
|
GroupModule,
|
||||||
CaslModule,
|
CaslModule,
|
||||||
PageAccessModule,
|
|
||||||
ShareModule,
|
ShareModule,
|
||||||
],
|
],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: AUDIT_SERVICE,
|
||||||
|
useClass: NoopAuditService,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
exports: [AUDIT_SERVICE],
|
||||||
})
|
})
|
||||||
export class CoreModule implements NestModule {
|
export class CoreModule implements NestModule {
|
||||||
configure(consumer: MiddlewareConsumer) {
|
configure(consumer: MiddlewareConsumer) {
|
||||||
|
const excludedRoutes = [
|
||||||
|
{ path: 'auth/setup', method: RequestMethod.POST },
|
||||||
|
{ path: 'health', method: RequestMethod.GET },
|
||||||
|
{ path: 'health/live', method: RequestMethod.GET },
|
||||||
|
{ path: 'billing/stripe/webhook', method: RequestMethod.POST },
|
||||||
|
];
|
||||||
|
|
||||||
consumer
|
consumer
|
||||||
.apply(DomainMiddleware)
|
.apply(DomainMiddleware)
|
||||||
.exclude(
|
.exclude(...excludedRoutes)
|
||||||
{ path: 'auth/setup', method: RequestMethod.POST },
|
.forRoutes('*');
|
||||||
{ path: 'health', method: RequestMethod.GET },
|
|
||||||
{ path: 'health/live', method: RequestMethod.GET },
|
consumer
|
||||||
{ path: 'billing/stripe/webhook', method: RequestMethod.POST },
|
.apply(AuditContextMiddleware)
|
||||||
)
|
.exclude(...excludedRoutes)
|
||||||
.forRoutes('*');
|
.forRoutes('*');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
|
||||||
import { PageAccessService } from './page-access.service';
|
|
||||||
|
|
||||||
@Global()
|
|
||||||
@Module({
|
|
||||||
providers: [PageAccessService],
|
|
||||||
exports: [PageAccessService],
|
|
||||||
})
|
|
||||||
export class PageAccessModule {}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
|
||||||
import { Page, User } from '@docmost/db/types/entity.types';
|
|
||||||
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
|
||||||
import SpaceAbilityFactory from '../casl/abilities/space-ability.factory';
|
|
||||||
import {
|
|
||||||
SpaceCaslAction,
|
|
||||||
SpaceCaslSubject,
|
|
||||||
} from '../casl/interfaces/space-ability.type';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class PageAccessService {
|
|
||||||
constructor(
|
|
||||||
private readonly pagePermissionRepo: PagePermissionRepo,
|
|
||||||
private readonly spaceAbility: SpaceAbilityFactory,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate user can view page, throws ForbiddenException if not.
|
|
||||||
* If page has restrictions: page-level permission determines access.
|
|
||||||
* If no restrictions: space-level permission determines access.
|
|
||||||
*/
|
|
||||||
async validateCanView(page: Page, user: User): Promise<void> {
|
|
||||||
// TODO: cache by pageId and userId.
|
|
||||||
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
|
||||||
|
|
||||||
// User must be at least a space member
|
|
||||||
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
|
|
||||||
const { hasRestriction, canAccess } =
|
|
||||||
await this.pagePermissionRepo.getUserPageAccessLevel(user.id, page.id);
|
|
||||||
|
|
||||||
if (hasRestriction) {
|
|
||||||
// Page has restrictions - use page-level permission
|
|
||||||
if (!canAccess) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// No restriction - space membership (checked above) is sufficient for view
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate user can edit page, throws ForbiddenException if not.
|
|
||||||
* If page has restrictions: page-level writer permission determines access.
|
|
||||||
* If no restrictions: space-level edit permission determines access.
|
|
||||||
*/
|
|
||||||
async validateCanEdit(page: Page, user: User): Promise<void> {
|
|
||||||
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
|
||||||
|
|
||||||
// User must be at least a space member
|
|
||||||
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
|
|
||||||
const { hasRestriction, canEdit } =
|
|
||||||
await this.pagePermissionRepo.getUserPageAccessLevel(user.id, page.id);
|
|
||||||
|
|
||||||
if (hasRestriction) {
|
|
||||||
// Page has restrictions - use page-level permission
|
|
||||||
if (!canEdit) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// No restrictions - use space-level permission
|
|
||||||
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page)) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
import {
|
|
||||||
ArrayMaxSize,
|
|
||||||
ArrayMinSize,
|
|
||||||
IsArray,
|
|
||||||
IsEnum,
|
|
||||||
IsNotEmpty,
|
|
||||||
IsOptional,
|
|
||||||
IsString,
|
|
||||||
IsUUID,
|
|
||||||
} from 'class-validator';
|
|
||||||
import { PagePermissionRole } from '../../../common/helpers/types/permission';
|
|
||||||
|
|
||||||
export class PageIdDto {
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
pageId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class RestrictPageDto extends PageIdDto {}
|
|
||||||
|
|
||||||
export class AddPagePermissionDto extends PageIdDto {
|
|
||||||
@IsEnum(PagePermissionRole)
|
|
||||||
role: string;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsArray()
|
|
||||||
@ArrayMaxSize(25, {
|
|
||||||
message: 'userIds must be an array with no more than 25 elements',
|
|
||||||
})
|
|
||||||
@ArrayMinSize(1)
|
|
||||||
@IsUUID('all', { each: true })
|
|
||||||
userIds?: string[];
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsArray()
|
|
||||||
@ArrayMaxSize(25, {
|
|
||||||
message: 'groupIds must be an array with no more than 25 elements',
|
|
||||||
})
|
|
||||||
@ArrayMinSize(1)
|
|
||||||
@IsUUID('all', { each: true })
|
|
||||||
groupIds?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export class RemovePagePermissionDto extends PageIdDto {
|
|
||||||
@IsOptional()
|
|
||||||
@IsUUID()
|
|
||||||
userId?: string;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsUUID()
|
|
||||||
groupId?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class UpdatePagePermissionRoleDto extends PageIdDto {
|
|
||||||
@IsEnum(PagePermissionRole)
|
|
||||||
role: string;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsUUID()
|
|
||||||
userId?: string;
|
|
||||||
|
|
||||||
@IsOptional()
|
|
||||||
@IsUUID()
|
|
||||||
groupId?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class RemovePageRestrictionDto extends PageIdDto {}
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
HttpCode,
|
|
||||||
HttpStatus,
|
|
||||||
Post,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { PagePermissionService } from './services/page-permission.service';
|
|
||||||
import {
|
|
||||||
AddPagePermissionDto,
|
|
||||||
PageIdDto,
|
|
||||||
RemovePagePermissionDto,
|
|
||||||
RemovePageRestrictionDto,
|
|
||||||
RestrictPageDto,
|
|
||||||
UpdatePagePermissionRoleDto,
|
|
||||||
} from './dto/page-permission.dto';
|
|
||||||
import { AuthUser } from '../../common/decorators/auth-user.decorator';
|
|
||||||
import { AuthWorkspace } from '../../common/decorators/auth-workspace.decorator';
|
|
||||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
|
||||||
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
|
|
||||||
import { User, Workspace } from '@docmost/db/types/entity.types';
|
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
|
||||||
@Controller('pages/permissions')
|
|
||||||
export class PagePermissionController {
|
|
||||||
constructor(
|
|
||||||
private readonly pagePermissionService: PagePermissionService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('restrict')
|
|
||||||
async restrictPage(
|
|
||||||
@Body() dto: RestrictPageDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
await this.pagePermissionService.restrictPage(dto.pageId, user, workspace.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('add')
|
|
||||||
async addPagePermission(
|
|
||||||
@Body() dto: AddPagePermissionDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
@AuthWorkspace() workspace: Workspace,
|
|
||||||
) {
|
|
||||||
if (
|
|
||||||
(!dto.userIds || dto.userIds.length === 0) &&
|
|
||||||
(!dto.groupIds || dto.groupIds.length === 0)
|
|
||||||
) {
|
|
||||||
throw new BadRequestException('userIds or groupIds is required');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.pagePermissionService.addPagePermissions(dto, user, workspace.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('remove')
|
|
||||||
async removePagePermission(
|
|
||||||
@Body() dto: RemovePagePermissionDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
) {
|
|
||||||
if (!dto.userId && !dto.groupId) {
|
|
||||||
throw new BadRequestException('userId or groupId is required');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.pagePermissionService.removePagePermission(dto, user);
|
|
||||||
}
|
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('update-role')
|
|
||||||
async updatePagePermissionRole(
|
|
||||||
@Body() dto: UpdatePagePermissionRoleDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
) {
|
|
||||||
if (!dto.userId && !dto.groupId) {
|
|
||||||
throw new BadRequestException('userId or groupId is required');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.pagePermissionService.updatePagePermissionRole(dto, user);
|
|
||||||
}
|
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('unrestrict')
|
|
||||||
async removePageRestriction(
|
|
||||||
@Body() dto: RemovePageRestrictionDto,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
) {
|
|
||||||
await this.pagePermissionService.removePageRestriction(dto.pageId, user);
|
|
||||||
}
|
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
|
||||||
@Post('list')
|
|
||||||
async getPagePermissions(
|
|
||||||
@Body() dto: PageIdDto,
|
|
||||||
@Body() pagination: PaginationOptions,
|
|
||||||
@AuthUser() user: User,
|
|
||||||
) {
|
|
||||||
return this.pagePermissionService.getPagePermissions(
|
|
||||||
dto.pageId,
|
|
||||||
user,
|
|
||||||
pagination,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
UseGuards,
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { PageService } from './services/page.service';
|
import { PageService } from './services/page.service';
|
||||||
import { PageAccessService } from '../page-access/page-access.service';
|
|
||||||
import { CreatePageDto } from './dto/create-page.dto';
|
import { CreatePageDto } from './dto/create-page.dto';
|
||||||
import { UpdatePageDto } from './dto/update-page.dto';
|
import { UpdatePageDto } from './dto/update-page.dto';
|
||||||
import { MovePageDto, MovePageToSpaceDto } from './dto/move-page.dto';
|
import { MovePageDto, MovePageToSpaceDto } from './dto/move-page.dto';
|
||||||
@@ -45,7 +44,6 @@ export class PageController {
|
|||||||
private readonly pageRepo: PageRepo,
|
private readonly pageRepo: PageRepo,
|
||||||
private readonly pageHistoryService: PageHistoryService,
|
private readonly pageHistoryService: PageHistoryService,
|
||||||
private readonly spaceAbility: SpaceAbilityFactory,
|
private readonly spaceAbility: SpaceAbilityFactory,
|
||||||
private readonly pageAccessService: PageAccessService,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@@ -63,7 +61,10 @@ export class PageController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.pageAccessService.validateCanView(page, user);
|
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
||||||
|
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
|
||||||
return page;
|
return page;
|
||||||
}
|
}
|
||||||
@@ -75,24 +76,12 @@ export class PageController {
|
|||||||
@AuthUser() user: User,
|
@AuthUser() user: User,
|
||||||
@AuthWorkspace() workspace: Workspace,
|
@AuthWorkspace() workspace: Workspace,
|
||||||
) {
|
) {
|
||||||
if (createPageDto.parentPageId) {
|
const ability = await this.spaceAbility.createForUser(
|
||||||
// Creating under a parent page - check edit permission on parent
|
user,
|
||||||
const parentPage = await this.pageRepo.findById(
|
createPageDto.spaceId,
|
||||||
createPageDto.parentPageId,
|
);
|
||||||
);
|
if (ability.cannot(SpaceCaslAction.Create, SpaceCaslSubject.Page)) {
|
||||||
if (!parentPage || parentPage.spaceId !== createPageDto.spaceId) {
|
throw new ForbiddenException();
|
||||||
throw new NotFoundException('Parent page not found');
|
|
||||||
}
|
|
||||||
await this.pageAccessService.validateCanEdit(parentPage, user);
|
|
||||||
} else {
|
|
||||||
// Creating at root level - require space-level permission
|
|
||||||
const ability = await this.spaceAbility.createForUser(
|
|
||||||
user,
|
|
||||||
createPageDto.spaceId,
|
|
||||||
);
|
|
||||||
if (ability.cannot(SpaceCaslAction.Create, SpaceCaslSubject.Page)) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.pageService.create(user.id, workspace.id, createPageDto);
|
return this.pageService.create(user.id, workspace.id, createPageDto);
|
||||||
@@ -107,7 +96,10 @@ export class PageController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
||||||
|
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
|
||||||
return this.pageService.update(page, updatePageDto, user.id);
|
return this.pageService.update(page, updatePageDto, user.id);
|
||||||
}
|
}
|
||||||
@@ -136,9 +128,10 @@ export class PageController {
|
|||||||
}
|
}
|
||||||
await this.pageService.forceDelete(deletePageDto.pageId, workspace.id);
|
await this.pageService.forceDelete(deletePageDto.pageId, workspace.id);
|
||||||
} else {
|
} else {
|
||||||
// User with edit permission can delete
|
// Soft delete requires page manage permissions
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
await this.pageService.removePage(
|
await this.pageService.removePage(
|
||||||
deletePageDto.pageId,
|
deletePageDto.pageId,
|
||||||
user.id,
|
user.id,
|
||||||
@@ -160,18 +153,11 @@ export class PageController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
//Todo: currently, this means if they are not admins, they need to add a space admin to the page, which is not possible as it was soft-deleted
|
|
||||||
// so page is virtually lost. Fix.
|
|
||||||
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
||||||
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Page)) {
|
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Page)) {
|
||||||
throw new ForbiddenException();
|
throw new ForbiddenException();
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: can users with page level edit, but no space level edit restore pages they can edit?
|
|
||||||
|
|
||||||
// Check page-level edit permission (if restoring to a restricted ancestor)
|
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
|
||||||
|
|
||||||
await this.pageRepo.restorePage(pageIdDto.pageId, workspace.id);
|
await this.pageRepo.restorePage(pageIdDto.pageId, workspace.id);
|
||||||
|
|
||||||
return this.pageRepo.findById(pageIdDto.pageId, {
|
return this.pageRepo.findById(pageIdDto.pageId, {
|
||||||
@@ -198,7 +184,6 @@ export class PageController {
|
|||||||
|
|
||||||
return this.pageService.getRecentSpacePages(
|
return this.pageService.getRecentSpacePages(
|
||||||
recentPageDto.spaceId,
|
recentPageDto.spaceId,
|
||||||
user.id,
|
|
||||||
pagination,
|
pagination,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -213,7 +198,6 @@ export class PageController {
|
|||||||
@Body() pagination: PaginationOptions,
|
@Body() pagination: PaginationOptions,
|
||||||
@AuthUser() user: User,
|
@AuthUser() user: User,
|
||||||
) {
|
) {
|
||||||
//TODO: should space admin see deleted pages they dont have access to?
|
|
||||||
if (deletedPageDto.spaceId) {
|
if (deletedPageDto.spaceId) {
|
||||||
const ability = await this.spaceAbility.createForUser(
|
const ability = await this.spaceAbility.createForUser(
|
||||||
user,
|
user,
|
||||||
@@ -231,6 +215,7 @@ export class PageController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: scope to workspaces
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@Post('/history')
|
@Post('/history')
|
||||||
async getPageHistory(
|
async getPageHistory(
|
||||||
@@ -243,7 +228,10 @@ export class PageController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.pageAccessService.validateCanView(page, user);
|
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
||||||
|
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
|
||||||
return this.pageHistoryService.findHistoryByPageId(page.id, pagination);
|
return this.pageHistoryService.findHistoryByPageId(page.id, pagination);
|
||||||
}
|
}
|
||||||
@@ -259,14 +247,13 @@ export class PageController {
|
|||||||
throw new NotFoundException('Page history not found');
|
throw new NotFoundException('Page history not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the page to check permissions
|
const ability = await this.spaceAbility.createForUser(
|
||||||
const page = await this.pageRepo.findById(history.pageId);
|
user,
|
||||||
if (!page) {
|
history.spaceId,
|
||||||
throw new NotFoundException('Page not found');
|
);
|
||||||
|
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.pageAccessService.validateCanView(page, user);
|
|
||||||
|
|
||||||
return history;
|
return history;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,12 +285,7 @@ export class PageController {
|
|||||||
throw new ForbiddenException();
|
throw new ForbiddenException();
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.pageService.getSidebarPages(
|
return this.pageService.getSidebarPages(spaceId, pagination, dto.pageId);
|
||||||
spaceId,
|
|
||||||
pagination,
|
|
||||||
dto.pageId,
|
|
||||||
user.id,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@@ -333,11 +315,7 @@ export class PageController {
|
|||||||
throw new ForbiddenException();
|
throw new ForbiddenException();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check page-level edit permission on the source page
|
return this.pageService.movePageToSpace(movedPage, dto.spaceId);
|
||||||
await this.pageAccessService.validateCanEdit(movedPage, user);
|
|
||||||
|
|
||||||
// Moves only accessible pages; inaccessible child pages become root pages in original space
|
|
||||||
return this.pageService.movePageToSpace(movedPage, dto.spaceId, user.id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@@ -348,10 +326,6 @@ export class PageController {
|
|||||||
throw new NotFoundException('Page to copy not found');
|
throw new NotFoundException('Page to copy not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check page-level view permission on the source page (need to read to copy)
|
|
||||||
// Inaccessible child branches are automatically skipped during duplication
|
|
||||||
await this.pageAccessService.validateCanView(copiedPage, user);
|
|
||||||
|
|
||||||
// If spaceId is provided, it's a copy to different space
|
// If spaceId is provided, it's a copy to different space
|
||||||
if (dto.spaceId) {
|
if (dto.spaceId) {
|
||||||
const abilities = await Promise.all([
|
const abilities = await Promise.all([
|
||||||
@@ -394,22 +368,10 @@ export class PageController {
|
|||||||
user,
|
user,
|
||||||
movedPage.spaceId,
|
movedPage.spaceId,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page)) {
|
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page)) {
|
||||||
throw new ForbiddenException();
|
throw new ForbiddenException();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check page-level edit permission
|
|
||||||
await this.pageAccessService.validateCanEdit(movedPage, user);
|
|
||||||
|
|
||||||
// If moving to a new parent, check permission on the target parent
|
|
||||||
if (dto.parentPageId && dto.parentPageId !== movedPage.parentPageId) {
|
|
||||||
const targetParent = await this.pageRepo.findById(dto.parentPageId);
|
|
||||||
if (targetParent) {
|
|
||||||
await this.pageAccessService.validateCanEdit(targetParent, user);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.pageService.movePage(dto, movedPage);
|
return this.pageService.movePage(dto, movedPage);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -421,8 +383,10 @@ export class PageController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.pageAccessService.validateCanView(page, user);
|
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
||||||
|
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
return this.pageService.getPageBreadCrumbs(page.id);
|
return this.pageService.getPageBreadCrumbs(page.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,12 @@ import { PageService } from './services/page.service';
|
|||||||
import { PageController } from './page.controller';
|
import { PageController } from './page.controller';
|
||||||
import { PageHistoryService } from './services/page-history.service';
|
import { PageHistoryService } from './services/page-history.service';
|
||||||
import { TrashCleanupService } from './services/trash-cleanup.service';
|
import { TrashCleanupService } from './services/trash-cleanup.service';
|
||||||
import { PagePermissionService } from './services/page-permission.service';
|
|
||||||
import { PagePermissionController } from './page-permission.controller';
|
|
||||||
import { StorageModule } from '../../integrations/storage/storage.module';
|
import { StorageModule } from '../../integrations/storage/storage.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
controllers: [PageController, PagePermissionController],
|
controllers: [PageController],
|
||||||
providers: [PageService, PageHistoryService, TrashCleanupService, PagePermissionService],
|
providers: [PageService, PageHistoryService, TrashCleanupService],
|
||||||
exports: [PageService, PageHistoryService, PagePermissionService],
|
exports: [PageService, PageHistoryService],
|
||||||
imports: [StorageModule],
|
imports: [StorageModule],
|
||||||
})
|
})
|
||||||
export class PageModule {}
|
export class PageModule {}
|
||||||
|
|||||||
@@ -1,438 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
ForbiddenException,
|
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
|
||||||
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
|
||||||
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
|
||||||
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
|
||||||
import {
|
|
||||||
AddPagePermissionDto,
|
|
||||||
RemovePagePermissionDto,
|
|
||||||
UpdatePagePermissionRoleDto,
|
|
||||||
} from '../dto/page-permission.dto';
|
|
||||||
import { Page, User } from '@docmost/db/types/entity.types';
|
|
||||||
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
|
|
||||||
import {
|
|
||||||
PageAccessLevel,
|
|
||||||
PagePermissionRole,
|
|
||||||
} from '../../../common/helpers/types/permission';
|
|
||||||
import { executeTx } from '@docmost/db/utils';
|
|
||||||
import SpaceAbilityFactory from '../../casl/abilities/space-ability.factory';
|
|
||||||
import {
|
|
||||||
SpaceCaslAction,
|
|
||||||
SpaceCaslSubject,
|
|
||||||
} from '../../casl/interfaces/space-ability.type';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class PagePermissionService {
|
|
||||||
constructor(
|
|
||||||
private pagePermissionRepo: PagePermissionRepo,
|
|
||||||
private pageRepo: PageRepo,
|
|
||||||
private spaceAbility: SpaceAbilityFactory,
|
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async restrictPage(
|
|
||||||
pageId: string,
|
|
||||||
authUser: User,
|
|
||||||
workspaceId: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const page = await this.pageRepo.findById(pageId);
|
|
||||||
if (!page) {
|
|
||||||
throw new NotFoundException('Page not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const ability = await this.spaceAbility.createForUser(authUser, page.spaceId);
|
|
||||||
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page)) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: does this check if any of the page's ancestor's is restricted and the user don't have access to it?
|
|
||||||
// to have access to this page, they must already have access to the page if any of it's ancestor's is restricted
|
|
||||||
|
|
||||||
const existingAccess =
|
|
||||||
await this.pagePermissionRepo.findPageAccessByPageId(pageId);
|
|
||||||
if (existingAccess) {
|
|
||||||
throw new BadRequestException('Page is already restricted');
|
|
||||||
}
|
|
||||||
|
|
||||||
await executeTx(this.db, async (trx) => {
|
|
||||||
const pageAccess = await this.pagePermissionRepo.insertPageAccess(
|
|
||||||
{
|
|
||||||
pageId: pageId,
|
|
||||||
workspaceId: workspaceId,
|
|
||||||
accessLevel: PageAccessLevel.RESTRICTED,
|
|
||||||
creatorId: authUser.id,
|
|
||||||
},
|
|
||||||
trx,
|
|
||||||
);
|
|
||||||
|
|
||||||
await this.pagePermissionRepo.insertPagePermissions(
|
|
||||||
[
|
|
||||||
{
|
|
||||||
pageAccessId: pageAccess.id,
|
|
||||||
userId: authUser.id,
|
|
||||||
role: PagePermissionRole.WRITER,
|
|
||||||
addedById: authUser.id,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
trx,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async addPagePermissions(
|
|
||||||
dto: AddPagePermissionDto,
|
|
||||||
authUser: User,
|
|
||||||
workspaceId: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const page = await this.pageRepo.findById(dto.pageId);
|
|
||||||
if (!page) {
|
|
||||||
throw new NotFoundException('Page not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.validateWriteAccess(page, authUser);
|
|
||||||
|
|
||||||
const pageAccess = await this.pagePermissionRepo.findPageAccessByPageId(
|
|
||||||
dto.pageId,
|
|
||||||
);
|
|
||||||
if (!pageAccess) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'Page is not restricted. Restrict the page first.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let validUsers = [];
|
|
||||||
let validGroups = [];
|
|
||||||
|
|
||||||
if (dto.userIds && dto.userIds.length > 0) {
|
|
||||||
validUsers = await this.db
|
|
||||||
.selectFrom('users')
|
|
||||||
.select(['id'])
|
|
||||||
.where('id', 'in', dto.userIds)
|
|
||||||
.where('workspaceId', '=', workspaceId)
|
|
||||||
.where(({ not, exists, selectFrom }) =>
|
|
||||||
not(
|
|
||||||
exists(
|
|
||||||
selectFrom('pagePermissions')
|
|
||||||
.select('id')
|
|
||||||
.whereRef('pagePermissions.userId', '=', 'users.id')
|
|
||||||
.where('pagePermissions.pageAccessId', '=', pageAccess.id),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dto.groupIds && dto.groupIds.length > 0) {
|
|
||||||
validGroups = await this.db
|
|
||||||
.selectFrom('groups')
|
|
||||||
.select(['id'])
|
|
||||||
.where('id', 'in', dto.groupIds)
|
|
||||||
.where('workspaceId', '=', workspaceId)
|
|
||||||
.where(({ not, exists, selectFrom }) =>
|
|
||||||
not(
|
|
||||||
exists(
|
|
||||||
selectFrom('pagePermissions')
|
|
||||||
.select('id')
|
|
||||||
.whereRef('pagePermissions.groupId', '=', 'groups.id')
|
|
||||||
.where('pagePermissions.pageAccessId', '=', pageAccess.id),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
const permissionsToAdd = [];
|
|
||||||
|
|
||||||
for (const user of validUsers) {
|
|
||||||
permissionsToAdd.push({
|
|
||||||
pageAccessId: pageAccess.id,
|
|
||||||
userId: user.id,
|
|
||||||
role: dto.role,
|
|
||||||
addedById: authUser.id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const group of validGroups) {
|
|
||||||
permissionsToAdd.push({
|
|
||||||
pageAccessId: pageAccess.id,
|
|
||||||
groupId: group.id,
|
|
||||||
role: dto.role,
|
|
||||||
addedById: authUser.id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (permissionsToAdd.length > 0) {
|
|
||||||
await this.pagePermissionRepo.insertPagePermissions(permissionsToAdd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async removePagePermission(
|
|
||||||
dto: RemovePagePermissionDto,
|
|
||||||
authUser: User,
|
|
||||||
): Promise<void> {
|
|
||||||
const page = await this.pageRepo.findById(dto.pageId);
|
|
||||||
if (!page) {
|
|
||||||
throw new NotFoundException('Page not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.validateWriteAccess(page, authUser);
|
|
||||||
|
|
||||||
const pageAccess = await this.pagePermissionRepo.findPageAccessByPageId(
|
|
||||||
dto.pageId,
|
|
||||||
);
|
|
||||||
if (!pageAccess) {
|
|
||||||
throw new BadRequestException('Page is not restricted');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!dto.userId && !dto.groupId) {
|
|
||||||
throw new BadRequestException('Please provide a userId or groupId');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dto.userId) {
|
|
||||||
const permission = await this.pagePermissionRepo.findPagePermissionByUserId(
|
|
||||||
pageAccess.id,
|
|
||||||
dto.userId,
|
|
||||||
);
|
|
||||||
if (!permission) {
|
|
||||||
throw new NotFoundException('Permission not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (permission.role === PagePermissionRole.WRITER) {
|
|
||||||
await this.validateLastWriter(pageAccess.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.pagePermissionRepo.deletePagePermissionByUserId(
|
|
||||||
pageAccess.id,
|
|
||||||
dto.userId,
|
|
||||||
);
|
|
||||||
} else if (dto.groupId) {
|
|
||||||
const permission =
|
|
||||||
await this.pagePermissionRepo.findPagePermissionByGroupId(
|
|
||||||
pageAccess.id,
|
|
||||||
dto.groupId,
|
|
||||||
);
|
|
||||||
if (!permission) {
|
|
||||||
throw new NotFoundException('Permission not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (permission.role === PagePermissionRole.WRITER) {
|
|
||||||
await this.validateLastWriter(pageAccess.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.pagePermissionRepo.deletePagePermissionByGroupId(
|
|
||||||
pageAccess.id,
|
|
||||||
dto.groupId,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async updatePagePermissionRole(
|
|
||||||
dto: UpdatePagePermissionRoleDto,
|
|
||||||
authUser: User,
|
|
||||||
): Promise<void> {
|
|
||||||
const page = await this.pageRepo.findById(dto.pageId);
|
|
||||||
if (!page) {
|
|
||||||
throw new NotFoundException('Page not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.validateWriteAccess(page, authUser);
|
|
||||||
|
|
||||||
const pageAccess = await this.pagePermissionRepo.findPageAccessByPageId(
|
|
||||||
dto.pageId,
|
|
||||||
);
|
|
||||||
if (!pageAccess) {
|
|
||||||
throw new BadRequestException('Page is not restricted');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!dto.userId && !dto.groupId) {
|
|
||||||
throw new BadRequestException('Please provide a userId or groupId');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dto.userId) {
|
|
||||||
const permission =
|
|
||||||
await this.pagePermissionRepo.findPagePermissionByUserId(
|
|
||||||
pageAccess.id,
|
|
||||||
dto.userId,
|
|
||||||
);
|
|
||||||
if (!permission) {
|
|
||||||
throw new NotFoundException('Permission not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (permission.role === dto.role) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (permission.role === PagePermissionRole.WRITER) {
|
|
||||||
await this.validateLastWriter(pageAccess.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.pagePermissionRepo.updatePagePermissionRole(
|
|
||||||
pageAccess.id,
|
|
||||||
dto.role,
|
|
||||||
{ userId: dto.userId },
|
|
||||||
);
|
|
||||||
} else if (dto.groupId) {
|
|
||||||
const permission =
|
|
||||||
await this.pagePermissionRepo.findPagePermissionByGroupId(
|
|
||||||
pageAccess.id,
|
|
||||||
dto.groupId,
|
|
||||||
);
|
|
||||||
if (!permission) {
|
|
||||||
throw new NotFoundException('Permission not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (permission.role === dto.role) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (permission.role === PagePermissionRole.WRITER) {
|
|
||||||
await this.validateLastWriter(pageAccess.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.pagePermissionRepo.updatePagePermissionRole(
|
|
||||||
pageAccess.id,
|
|
||||||
dto.role,
|
|
||||||
{ groupId: dto.groupId },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async removePageRestriction(pageId: string, authUser: User): Promise<void> {
|
|
||||||
const page = await this.pageRepo.findById(pageId);
|
|
||||||
if (!page) {
|
|
||||||
throw new NotFoundException('Page not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.validateWriteAccess(page, authUser);
|
|
||||||
|
|
||||||
const pageAccess =
|
|
||||||
await this.pagePermissionRepo.findPageAccessByPageId(pageId);
|
|
||||||
if (!pageAccess) {
|
|
||||||
throw new BadRequestException('Page is not restricted');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.pagePermissionRepo.deletePageAccess(pageId);
|
|
||||||
}
|
|
||||||
|
|
||||||
async getPagePermissions(
|
|
||||||
pageId: string,
|
|
||||||
authUser: User,
|
|
||||||
pagination: PaginationOptions,
|
|
||||||
) {
|
|
||||||
const page = await this.pageRepo.findById(pageId);
|
|
||||||
if (!page) {
|
|
||||||
throw new NotFoundException('Page not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const ability = await this.spaceAbility.createForUser(authUser, page.spaceId);
|
|
||||||
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
|
|
||||||
const pageAccess =
|
|
||||||
await this.pagePermissionRepo.findPageAccessByPageId(pageId);
|
|
||||||
if (!pageAccess) {
|
|
||||||
return {
|
|
||||||
items: [],
|
|
||||||
pagination: {
|
|
||||||
page: 1,
|
|
||||||
perPage: pagination.limit,
|
|
||||||
totalItems: 0,
|
|
||||||
totalPages: 0,
|
|
||||||
hasNextPage: false,
|
|
||||||
hasPrevPage: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.pagePermissionRepo.getPagePermissionsPaginated(
|
|
||||||
pageAccess.id,
|
|
||||||
pagination,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateLastWriter(pageAccessId: string): Promise<void> {
|
|
||||||
const writerCount =
|
|
||||||
await this.pagePermissionRepo.countWritersByPageAccessId(pageAccessId);
|
|
||||||
if (writerCount <= 1) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'There must be at least one user with "Can edit" permission',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if user has writer permission on ALL restricted ancestors of a page.
|
|
||||||
* Used for permission management operations.
|
|
||||||
*/
|
|
||||||
async hasWritePermission(userId: string, pageId: string): Promise<boolean> {
|
|
||||||
const hasRestriction =
|
|
||||||
await this.pagePermissionRepo.hasRestrictedAncestor(pageId);
|
|
||||||
|
|
||||||
if (!hasRestriction) {
|
|
||||||
return false; // no restrictions, defer to space permissions
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.pagePermissionRepo.canUserEditPage(userId, pageId);
|
|
||||||
}
|
|
||||||
|
|
||||||
async hasPageAccess(pageId: string): Promise<boolean> {
|
|
||||||
const pageAccess =
|
|
||||||
await this.pagePermissionRepo.findPageAccessByPageId(pageId);
|
|
||||||
return !!pageAccess;
|
|
||||||
}
|
|
||||||
|
|
||||||
async validateWriteAccess(page: Page, user: User): Promise<void> {
|
|
||||||
const hasWritePermission = await this.hasWritePermission(user.id, page.id);
|
|
||||||
if (hasWritePermission) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
|
||||||
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Page)) {
|
|
||||||
throw new ForbiddenException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if user can view a page.
|
|
||||||
* User must have permission (reader or writer) on EVERY restricted ancestor.
|
|
||||||
* Returns true if:
|
|
||||||
* - No ancestors are restricted (defer to space permission)
|
|
||||||
* - User has permission on all restricted ancestors
|
|
||||||
*/
|
|
||||||
async canViewPage(userId: string, pageId: string): Promise<boolean> {
|
|
||||||
return this.pagePermissionRepo.canUserAccessPage(userId, pageId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if user can edit a page.
|
|
||||||
* User must have WRITER permission on EVERY restricted ancestor.
|
|
||||||
* Returns true if:
|
|
||||||
* - No ancestors are restricted (defer to space permission)
|
|
||||||
* - User has writer permission on all restricted ancestors
|
|
||||||
*/
|
|
||||||
async canEditPage(userId: string, pageId: string): Promise<boolean> {
|
|
||||||
return this.pagePermissionRepo.canUserEditPage(userId, pageId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Filter page IDs to only those the user can access.
|
|
||||||
*/
|
|
||||||
async filterAccessiblePages(
|
|
||||||
pageIds: string[],
|
|
||||||
userId: string,
|
|
||||||
): Promise<string[]> {
|
|
||||||
const results =
|
|
||||||
await this.pagePermissionRepo.filterAccessiblePageIdsWithPermissions(
|
|
||||||
pageIds,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
return results.map((r) => r.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
import { CreatePageDto } from '../dto/create-page.dto';
|
import { CreatePageDto } from '../dto/create-page.dto';
|
||||||
import { UpdatePageDto } from '../dto/update-page.dto';
|
import { UpdatePageDto } from '../dto/update-page.dto';
|
||||||
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
||||||
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
|
||||||
import { InsertablePage, Page, User } from '@docmost/db/types/entity.types';
|
import { InsertablePage, Page, User } from '@docmost/db/types/entity.types';
|
||||||
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
|
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
|
||||||
import {
|
import {
|
||||||
@@ -48,7 +47,6 @@ export class PageService {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private pageRepo: PageRepo,
|
private pageRepo: PageRepo,
|
||||||
private pagePermissionRepo: PagePermissionRepo,
|
|
||||||
private attachmentRepo: AttachmentRepo,
|
private attachmentRepo: AttachmentRepo,
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
private readonly storageService: StorageService,
|
private readonly storageService: StorageService,
|
||||||
@@ -57,61 +55,6 @@ export class PageService {
|
|||||||
private eventEmitter: EventEmitter2,
|
private eventEmitter: EventEmitter2,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
|
||||||
* Filters a list of pages to only those accessible to the user while maintaining tree integrity.
|
|
||||||
* A page is included only if:
|
|
||||||
* 1. The user has access to it
|
|
||||||
* 2. Its parent is also included (or it's the root page)
|
|
||||||
* This ensures that if a middle page is inaccessible, its entire subtree is excluded.
|
|
||||||
*/
|
|
||||||
private async filterAccessibleTreePages<T extends { id: string; parentPageId: string | null }>(
|
|
||||||
pages: T[],
|
|
||||||
rootPageId: string,
|
|
||||||
userId: string,
|
|
||||||
): Promise<T[]> {
|
|
||||||
if (pages.length === 0) return [];
|
|
||||||
|
|
||||||
const pageIds = pages.map((p) => p.id);
|
|
||||||
const accessiblePages =
|
|
||||||
await this.pagePermissionRepo.filterAccessiblePageIdsWithPermissions(
|
|
||||||
pageIds,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
const accessibleSet = new Set(accessiblePages.map((p) => p.id));
|
|
||||||
|
|
||||||
// Build a map for quick lookup
|
|
||||||
const pageMap = new Map(pages.map((p) => [p.id, p]));
|
|
||||||
|
|
||||||
// Prune: include a page only if it's accessible AND its parent chain to root is included
|
|
||||||
const includedIds = new Set<string>();
|
|
||||||
|
|
||||||
// Process pages in a way that ensures parents are processed before children
|
|
||||||
// We do this by iterating until no more pages can be added
|
|
||||||
let changed = true;
|
|
||||||
while (changed) {
|
|
||||||
changed = false;
|
|
||||||
for (const page of pages) {
|
|
||||||
if (includedIds.has(page.id)) continue;
|
|
||||||
if (!accessibleSet.has(page.id)) continue;
|
|
||||||
|
|
||||||
// Root page: include if accessible
|
|
||||||
if (page.id === rootPageId) {
|
|
||||||
includedIds.add(page.id);
|
|
||||||
changed = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Non-root: include if parent is already included
|
|
||||||
if (page.parentPageId && includedIds.has(page.parentPageId)) {
|
|
||||||
includedIds.add(page.id);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return pages.filter((p) => includedIds.has(p.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
async findById(
|
async findById(
|
||||||
pageId: string,
|
pageId: string,
|
||||||
includeContent?: boolean,
|
includeContent?: boolean,
|
||||||
@@ -224,7 +167,7 @@ export class PageService {
|
|||||||
page.id,
|
page.id,
|
||||||
);
|
);
|
||||||
|
|
||||||
return this.pageRepo.findById(page.id, {
|
return await this.pageRepo.findById(page.id, {
|
||||||
includeSpace: true,
|
includeSpace: true,
|
||||||
includeContent: true,
|
includeContent: true,
|
||||||
includeCreator: true,
|
includeCreator: true,
|
||||||
@@ -237,7 +180,6 @@ export class PageService {
|
|||||||
spaceId: string,
|
spaceId: string,
|
||||||
pagination: PaginationOptions,
|
pagination: PaginationOptions,
|
||||||
pageId?: string,
|
pageId?: string,
|
||||||
userId?: string,
|
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
let query = this.db
|
let query = this.db
|
||||||
.selectFrom('pages')
|
.selectFrom('pages')
|
||||||
@@ -263,83 +205,16 @@ export class PageService {
|
|||||||
query = query.where('parentPageId', 'is', null);
|
query = query.where('parentPageId', 'is', null);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await executeWithPagination(query, {
|
const result = executeWithPagination(query, {
|
||||||
page: pagination.page,
|
page: pagination.page,
|
||||||
perPage: 250,
|
perPage: 250,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (userId && result.items.length > 0) {
|
|
||||||
const pageIds = result.items.map((p: any) => p.id);
|
|
||||||
|
|
||||||
// Single query to get accessible pages with their edit permissions
|
|
||||||
const accessiblePages =
|
|
||||||
await this.pagePermissionRepo.filterAccessiblePageIdsWithPermissions(
|
|
||||||
pageIds,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
|
|
||||||
const permissionMap = new Map(
|
|
||||||
accessiblePages.map((p) => [p.id, p.canEdit]),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Filter and add canEdit flag in one pass
|
|
||||||
result.items = result.items
|
|
||||||
.filter((p: any) => permissionMap.has(p.id))
|
|
||||||
.map((p: any) => ({
|
|
||||||
...p,
|
|
||||||
canEdit: permissionMap.get(p.id),
|
|
||||||
}));
|
|
||||||
|
|
||||||
// For pages with hasChildren: true, verify they have accessible children
|
|
||||||
const pagesWithChildren = result.items.filter((p: any) => p.hasChildren);
|
|
||||||
if (pagesWithChildren.length > 0) {
|
|
||||||
const parentIds = pagesWithChildren.map((p: any) => p.id);
|
|
||||||
const parentsWithAccessibleChildren =
|
|
||||||
await this.pagePermissionRepo.getParentIdsWithAccessibleChildren(
|
|
||||||
parentIds,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
const hasAccessibleChildrenSet = new Set(parentsWithAccessibleChildren);
|
|
||||||
|
|
||||||
result.items = result.items.map((p: any) => ({
|
|
||||||
...p,
|
|
||||||
hasChildren: p.hasChildren && hasAccessibleChildrenSet.has(p.id),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
async movePageToSpace(rootPage: Page, spaceId: string, userId: string) {
|
async movePageToSpace(rootPage: Page, spaceId: string) {
|
||||||
const allPages = await this.pageRepo.getPageAndDescendants(rootPage.id, {
|
|
||||||
includeContent: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Filter to only accessible pages while maintaining tree integrity
|
|
||||||
const accessiblePages = await this.filterAccessibleTreePages(
|
|
||||||
allPages,
|
|
||||||
rootPage.id,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
const accessibleIds = new Set(accessiblePages.map((p) => p.id));
|
|
||||||
|
|
||||||
// Find inaccessible pages whose parent is being moved - these need to be orphaned
|
|
||||||
const pagesToOrphan = allPages.filter(
|
|
||||||
(p) => !accessibleIds.has(p.id) && p.parentPageId && accessibleIds.has(p.parentPageId),
|
|
||||||
);
|
|
||||||
|
|
||||||
await executeTx(this.db, async (trx) => {
|
await executeTx(this.db, async (trx) => {
|
||||||
// Orphan inaccessible child pages (make them root pages in original space)
|
|
||||||
for (const page of pagesToOrphan) {
|
|
||||||
const orphanPosition = await this.nextPagePosition(rootPage.spaceId, null);
|
|
||||||
await this.pageRepo.updatePage(
|
|
||||||
{ parentPageId: null, position: orphanPosition },
|
|
||||||
page.id,
|
|
||||||
trx,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update root page
|
// Update root page
|
||||||
const nextPosition = await this.nextPagePosition(spaceId);
|
const nextPosition = await this.nextPagePosition(spaceId);
|
||||||
await this.pageRepo.updatePage(
|
await this.pageRepo.updatePage(
|
||||||
@@ -347,50 +222,44 @@ export class PageService {
|
|||||||
rootPage.id,
|
rootPage.id,
|
||||||
trx,
|
trx,
|
||||||
);
|
);
|
||||||
|
const pageIds = await this.pageRepo
|
||||||
const pageIdsToMove = accessiblePages.map((p) => p.id);
|
.getPageAndDescendants(rootPage.id, { includeContent: false })
|
||||||
|
.then((pages) => pages.map((page) => page.id));
|
||||||
if (pageIdsToMove.length > 1) {
|
// The first id is the root page id
|
||||||
// Update sub pages (all accessible pages except root)
|
if (pageIds.length > 1) {
|
||||||
|
// Update sub pages
|
||||||
await this.pageRepo.updatePages(
|
await this.pageRepo.updatePages(
|
||||||
{ spaceId },
|
{ spaceId },
|
||||||
pageIdsToMove.filter((id) => id !== rootPage.id),
|
pageIds.filter((id) => id !== rootPage.id),
|
||||||
trx,
|
trx,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pageIdsToMove.length > 0) {
|
if (pageIds.length > 0) {
|
||||||
// Clear page-level permissions - moved pages inherit destination space permissions
|
|
||||||
// (page_permissions cascade deletes via foreign key)
|
|
||||||
await trx
|
|
||||||
.deleteFrom('pageAccess')
|
|
||||||
.where('pageId', 'in', pageIdsToMove)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
// update spaceId in shares
|
// update spaceId in shares
|
||||||
await trx
|
await trx
|
||||||
.updateTable('shares')
|
.updateTable('shares')
|
||||||
.set({ spaceId: spaceId })
|
.set({ spaceId: spaceId })
|
||||||
.where('pageId', 'in', pageIdsToMove)
|
.where('pageId', 'in', pageIds)
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
// Update comments
|
// Update comments
|
||||||
await trx
|
await trx
|
||||||
.updateTable('comments')
|
.updateTable('comments')
|
||||||
.set({ spaceId: spaceId })
|
.set({ spaceId: spaceId })
|
||||||
.where('pageId', 'in', pageIdsToMove)
|
.where('pageId', 'in', pageIds)
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
// Update attachments
|
// Update attachments
|
||||||
await this.attachmentRepo.updateAttachmentsByPageId(
|
await this.attachmentRepo.updateAttachmentsByPageId(
|
||||||
{ spaceId },
|
{ spaceId },
|
||||||
pageIdsToMove,
|
pageIds,
|
||||||
trx,
|
trx,
|
||||||
);
|
);
|
||||||
|
|
||||||
await this.aiQueue.add(QueueJob.PAGE_MOVED_TO_SPACE, {
|
await this.aiQueue.add(QueueJob.PAGE_MOVED_TO_SPACE, {
|
||||||
pageId: pageIdsToMove,
|
pageId: pageIds,
|
||||||
workspaceId: rootPage.workspaceId,
|
workspaceId: rootPage.workspaceId
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -415,17 +284,10 @@ export class PageService {
|
|||||||
nextPosition = await this.nextPagePosition(spaceId);
|
nextPosition = await this.nextPagePosition(spaceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const allPages = await this.pageRepo.getPageAndDescendants(rootPage.id, {
|
const pages = await this.pageRepo.getPageAndDescendants(rootPage.id, {
|
||||||
includeContent: true,
|
includeContent: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Filter to only accessible pages while maintaining tree integrity
|
|
||||||
const pages = await this.filterAccessibleTreePages(
|
|
||||||
allPages,
|
|
||||||
rootPage.id,
|
|
||||||
authUser.id,
|
|
||||||
);
|
|
||||||
|
|
||||||
const pageMap = new Map<string, CopyPageMapEntry>();
|
const pageMap = new Map<string, CopyPageMapEntry>();
|
||||||
pages.forEach((page) => {
|
pages.forEach((page) => {
|
||||||
pageMap.set(page.id, {
|
pageMap.set(page.id, {
|
||||||
@@ -525,14 +387,9 @@ export class PageService {
|
|||||||
workspaceId: page.workspaceId,
|
workspaceId: page.workspaceId,
|
||||||
creatorId: authUser.id,
|
creatorId: authUser.id,
|
||||||
lastUpdatedById: authUser.id,
|
lastUpdatedById: authUser.id,
|
||||||
parentPageId:
|
parentPageId: page.id === rootPage.id
|
||||||
page.id === rootPage.id
|
? (isDuplicateInSameSpace ? rootPage.parentPageId : null)
|
||||||
? isDuplicateInSameSpace
|
: (page.parentPageId ? pageMap.get(page.parentPageId)?.newPageId : null),
|
||||||
? rootPage.parentPageId
|
|
||||||
: null
|
|
||||||
: page.parentPageId
|
|
||||||
? pageMap.get(page.parentPageId)?.newPageId
|
|
||||||
: null,
|
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -711,43 +568,16 @@ export class PageService {
|
|||||||
|
|
||||||
async getRecentSpacePages(
|
async getRecentSpacePages(
|
||||||
spaceId: string,
|
spaceId: string,
|
||||||
userId: string,
|
|
||||||
pagination: PaginationOptions,
|
pagination: PaginationOptions,
|
||||||
): Promise<PaginationResult<Page>> {
|
): Promise<PaginationResult<Page>> {
|
||||||
const result = await this.pageRepo.getRecentPagesInSpace(spaceId, pagination);
|
return await this.pageRepo.getRecentPagesInSpace(spaceId, pagination);
|
||||||
|
|
||||||
if (result.items.length > 0) {
|
|
||||||
const pageIds = result.items.map((p) => p.id);
|
|
||||||
const accessiblePages =
|
|
||||||
await this.pagePermissionRepo.filterAccessiblePageIdsWithPermissions(
|
|
||||||
pageIds,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
const accessibleSet = new Set(accessiblePages.map((p) => p.id));
|
|
||||||
result.items = result.items.filter((p) => accessibleSet.has(p.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getRecentPages(
|
async getRecentPages(
|
||||||
userId: string,
|
userId: string,
|
||||||
pagination: PaginationOptions,
|
pagination: PaginationOptions,
|
||||||
): Promise<PaginationResult<Page>> {
|
): Promise<PaginationResult<Page>> {
|
||||||
const result = await this.pageRepo.getRecentPages(userId, pagination);
|
return await this.pageRepo.getRecentPages(userId, pagination);
|
||||||
|
|
||||||
if (result.items.length > 0) {
|
|
||||||
const pageIds = result.items.map((p) => p.id);
|
|
||||||
const accessiblePages =
|
|
||||||
await this.pagePermissionRepo.filterAccessiblePageIdsWithPermissions(
|
|
||||||
pageIds,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
const accessibleSet = new Set(accessiblePages.map((p) => p.id));
|
|
||||||
result.items = result.items.filter((p) => accessibleSet.has(p.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getDeletedSpacePages(
|
async getDeletedSpacePages(
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { sql } from 'kysely';
|
|||||||
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
||||||
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
||||||
import { ShareRepo } from '@docmost/db/repos/share/share.repo';
|
import { ShareRepo } from '@docmost/db/repos/share/share.repo';
|
||||||
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
const tsquery = require('pg-tsquery')();
|
const tsquery = require('pg-tsquery')();
|
||||||
@@ -19,7 +18,6 @@ export class SearchService {
|
|||||||
private pageRepo: PageRepo,
|
private pageRepo: PageRepo,
|
||||||
private shareRepo: ShareRepo,
|
private shareRepo: ShareRepo,
|
||||||
private spaceMemberRepo: SpaceMemberRepo,
|
private spaceMemberRepo: SpaceMemberRepo,
|
||||||
private pagePermissionRepo: PagePermissionRepo,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async searchPage(
|
async searchPage(
|
||||||
@@ -120,22 +118,10 @@ export class SearchService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
let results: any[] = await queryResults.execute();
|
queryResults = await queryResults.execute();
|
||||||
|
|
||||||
// Filter results by page-level permissions (if user is authenticated)
|
|
||||||
if (opts.userId && results.length > 0) {
|
|
||||||
const pageIds = results.map((r: any) => r.id);
|
|
||||||
const accessiblePages =
|
|
||||||
await this.pagePermissionRepo.filterAccessiblePageIdsWithPermissions(
|
|
||||||
pageIds,
|
|
||||||
opts.userId,
|
|
||||||
);
|
|
||||||
const accessibleSet = new Set(accessiblePages.map((p) => p.id));
|
|
||||||
results = results.filter((r: any) => accessibleSet.has(r.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
const searchResults = results.map((result: SearchResponseDto) => {
|
const searchResults = queryResults.map((result: SearchResponseDto) => {
|
||||||
if (result.highlight) {
|
if (result.highlight) {
|
||||||
result.highlight = result.highlight
|
result.highlight = result.highlight
|
||||||
.replace(/\r\n|\r|\n/g, ' ')
|
.replace(/\r\n|\r|\n/g, ' ')
|
||||||
@@ -224,18 +210,6 @@ export class SearchService {
|
|||||||
pageSearch = pageSearch.where('spaceId', 'in', userSpaceIds);
|
pageSearch = pageSearch.where('spaceId', 'in', userSpaceIds);
|
||||||
pages = await pageSearch.execute();
|
pages = await pageSearch.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter by page-level permissions
|
|
||||||
if (pages.length > 0) {
|
|
||||||
const pageIds = pages.map((p) => p.id);
|
|
||||||
const accessiblePages =
|
|
||||||
await this.pagePermissionRepo.filterAccessiblePageIdsWithPermissions(
|
|
||||||
pageIds,
|
|
||||||
userId,
|
|
||||||
);
|
|
||||||
const accessibleSet = new Set(accessiblePages.map((p) => p.id));
|
|
||||||
pages = pages.filter((p) => accessibleSet.has(p.id));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { users, groups, pages };
|
return { users, groups, pages };
|
||||||
|
|||||||
@@ -26,8 +26,6 @@ import {
|
|||||||
UpdateShareDto,
|
UpdateShareDto,
|
||||||
} from './dto/share.dto';
|
} from './dto/share.dto';
|
||||||
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
import { PageRepo } from '@docmost/db/repos/page/page.repo';
|
||||||
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
|
||||||
import { PageAccessService } from '../page-access/page-access.service';
|
|
||||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||||
import { Public } from '../../common/decorators/public.decorator';
|
import { Public } from '../../common/decorators/public.decorator';
|
||||||
import { ShareRepo } from '@docmost/db/repos/share/share.repo';
|
import { ShareRepo } from '@docmost/db/repos/share/share.repo';
|
||||||
@@ -43,8 +41,6 @@ export class ShareController {
|
|||||||
private readonly spaceAbility: SpaceAbilityFactory,
|
private readonly spaceAbility: SpaceAbilityFactory,
|
||||||
private readonly shareRepo: ShareRepo,
|
private readonly shareRepo: ShareRepo,
|
||||||
private readonly pageRepo: PageRepo,
|
private readonly pageRepo: PageRepo,
|
||||||
private readonly pagePermissionRepo: PagePermissionRepo,
|
|
||||||
private readonly pageAccessService: PageAccessService,
|
|
||||||
private readonly environmentService: EnvironmentService,
|
private readonly environmentService: EnvironmentService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@@ -100,7 +96,6 @@ export class ShareController {
|
|||||||
@AuthUser() user: User,
|
@AuthUser() user: User,
|
||||||
@AuthWorkspace() workspace: Workspace,
|
@AuthWorkspace() workspace: Workspace,
|
||||||
) {
|
) {
|
||||||
// TODO: look into permission
|
|
||||||
const page = await this.pageRepo.findById(dto.pageId);
|
const page = await this.pageRepo.findById(dto.pageId);
|
||||||
if (!page) {
|
if (!page) {
|
||||||
throw new NotFoundException('Shared page not found');
|
throw new NotFoundException('Shared page not found');
|
||||||
@@ -127,21 +122,9 @@ export class ShareController {
|
|||||||
throw new NotFoundException('Page not found');
|
throw new NotFoundException('Page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
// User must be able to edit the page to create a share
|
const ability = await this.spaceAbility.createForUser(user, page.spaceId);
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
if (ability.cannot(SpaceCaslAction.Create, SpaceCaslSubject.Share)) {
|
||||||
|
throw new ForbiddenException();
|
||||||
// Block includeSubPages if user cannot access all descendants
|
|
||||||
if (createShareDto.includeSubPages) {
|
|
||||||
const hasInaccessible =
|
|
||||||
await this.pagePermissionRepo.hasInaccessibleDescendants(
|
|
||||||
page.id,
|
|
||||||
user.id,
|
|
||||||
);
|
|
||||||
if (hasInaccessible) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'Cannot share subpages: restricted pages found',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.shareService.createShare({
|
return this.shareService.createShare({
|
||||||
@@ -161,26 +144,9 @@ export class ShareController {
|
|||||||
throw new NotFoundException('Share not found');
|
throw new NotFoundException('Share not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = await this.pageRepo.findById(share.pageId);
|
const ability = await this.spaceAbility.createForUser(user, share.spaceId);
|
||||||
if (!page) {
|
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Share)) {
|
||||||
throw new NotFoundException('Page not found');
|
throw new ForbiddenException();
|
||||||
}
|
|
||||||
|
|
||||||
// User must be able to edit the page to update its share
|
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
|
||||||
|
|
||||||
// Block includeSubPages if user cannot access all descendants
|
|
||||||
if (updateShareDto.includeSubPages) {
|
|
||||||
const hasInaccessible =
|
|
||||||
await this.pagePermissionRepo.hasInaccessibleDescendants(
|
|
||||||
page.id,
|
|
||||||
user.id,
|
|
||||||
);
|
|
||||||
if (hasInaccessible) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'Cannot share subpages: restricted pages found',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.shareService.updateShare(share.id, updateShareDto);
|
return this.shareService.updateShare(share.id, updateShareDto);
|
||||||
@@ -195,14 +161,11 @@ export class ShareController {
|
|||||||
throw new NotFoundException('Share not found');
|
throw new NotFoundException('Share not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = await this.pageRepo.findById(share.pageId);
|
const ability = await this.spaceAbility.createForUser(user, share.spaceId);
|
||||||
if (!page) {
|
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Share)) {
|
||||||
throw new NotFoundException('Page not found');
|
throw new ForbiddenException();
|
||||||
}
|
}
|
||||||
|
|
||||||
// User must be able to edit the page to delete its share
|
|
||||||
await this.pageAccessService.validateCanEdit(page, user);
|
|
||||||
|
|
||||||
await this.shareRepo.deleteShare(share.id);
|
await this.shareRepo.deleteShare(share.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import {
|
|||||||
} from '../../common/helpers/prosemirror/utils';
|
} from '../../common/helpers/prosemirror/utils';
|
||||||
import { Node } from '@tiptap/pm/model';
|
import { Node } from '@tiptap/pm/model';
|
||||||
import { ShareRepo } from '@docmost/db/repos/share/share.repo';
|
import { ShareRepo } from '@docmost/db/repos/share/share.repo';
|
||||||
import { PagePermissionRepo } from '@docmost/db/repos/page/page-permission.repo';
|
|
||||||
import { updateAttachmentAttr } from './share.util';
|
import { updateAttachmentAttr } from './share.util';
|
||||||
import { Page } from '@docmost/db/types/entity.types';
|
import { Page } from '@docmost/db/types/entity.types';
|
||||||
import { validate as isValidUUID } from 'uuid';
|
import { validate as isValidUUID } from 'uuid';
|
||||||
@@ -32,7 +31,6 @@ export class ShareService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly shareRepo: ShareRepo,
|
private readonly shareRepo: ShareRepo,
|
||||||
private readonly pageRepo: PageRepo,
|
private readonly pageRepo: PageRepo,
|
||||||
private readonly pagePermissionRepo: PagePermissionRepo,
|
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
private readonly tokenService: TokenService,
|
private readonly tokenService: TokenService,
|
||||||
) {}
|
) {}
|
||||||
@@ -44,114 +42,16 @@ export class ShareService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (share.includeSubPages) {
|
if (share.includeSubPages) {
|
||||||
const allPages = await this.pageRepo.getPageAndDescendants(share.pageId, {
|
const pageList = await this.pageRepo.getPageAndDescendants(share.pageId, {
|
||||||
includeContent: false,
|
includeContent: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Filter out restricted pages and maintain tree integrity
|
return { share, pageTree: pageList };
|
||||||
const filteredPages = await this.filterPublicPages(allPages, share.pageId);
|
|
||||||
|
|
||||||
return { share, pageTree: filteredPages };
|
|
||||||
} else {
|
} else {
|
||||||
return { share, pageTree: [] };
|
return { share, pageTree: [] };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Filter pages for public share - exclude restricted pages.
|
|
||||||
* A page is included only if:
|
|
||||||
* 1. It has no page_access restriction AND
|
|
||||||
* 2. Its parent is also included (or it's the root)
|
|
||||||
*/
|
|
||||||
private async filterPublicPages<
|
|
||||||
T extends { id: string; parentPageId: string | null },
|
|
||||||
>(pages: T[], rootPageId: string): Promise<T[]> {
|
|
||||||
if (pages.length === 0) return [];
|
|
||||||
|
|
||||||
// Get all restricted page IDs
|
|
||||||
const restrictedIds =
|
|
||||||
await this.pagePermissionRepo.getRestrictedDescendantIds(rootPageId);
|
|
||||||
const restrictedSet = new Set(restrictedIds);
|
|
||||||
|
|
||||||
// Include pages that are NOT restricted and have valid parent chain
|
|
||||||
const includedIds = new Set<string>();
|
|
||||||
|
|
||||||
let changed = true;
|
|
||||||
while (changed) {
|
|
||||||
changed = false;
|
|
||||||
for (const page of pages) {
|
|
||||||
if (includedIds.has(page.id)) continue;
|
|
||||||
if (restrictedSet.has(page.id)) continue;
|
|
||||||
|
|
||||||
// Root page: include if not restricted
|
|
||||||
if (page.id === rootPageId) {
|
|
||||||
includedIds.add(page.id);
|
|
||||||
changed = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Non-root: include if parent is included
|
|
||||||
if (page.parentPageId && includedIds.has(page.parentPageId)) {
|
|
||||||
includedIds.add(page.id);
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return pages.filter((p) => includedIds.has(p.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a specific page is accessible within a public share.
|
|
||||||
* A page is accessible if no page in its ancestor chain
|
|
||||||
* (from the page up to and including the share root) has a page_access restriction.
|
|
||||||
*/
|
|
||||||
private async isPagePubliclyAccessible(
|
|
||||||
pageId: string,
|
|
||||||
shareRootPageId: string,
|
|
||||||
): Promise<boolean> {
|
|
||||||
if (pageId === shareRootPageId) {
|
|
||||||
const hasRestriction = await this.db
|
|
||||||
.selectFrom('pageAccess')
|
|
||||||
.select('id')
|
|
||||||
.where('pageId', '=', pageId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
return !hasRestriction;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the depth from share root to the requested page
|
|
||||||
const shareToPage = await this.db
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.select('depth')
|
|
||||||
.where('ancestorId', '=', shareRootPageId)
|
|
||||||
.where('descendantId', '=', pageId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
if (!shareToPage) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get all ancestor IDs in the chain from pageId to shareRootPageId
|
|
||||||
const chainPageIds = await this.db
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.select('ancestorId')
|
|
||||||
.where('descendantId', '=', pageId)
|
|
||||||
.where('depth', '<=', shareToPage.depth)
|
|
||||||
.where('depth', '>', 0)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
const idsToCheck = [pageId, ...chainPageIds.map((c) => c.ancestorId)];
|
|
||||||
|
|
||||||
// Check if any page in the chain has a restriction
|
|
||||||
const hasRestricted = await this.db
|
|
||||||
.selectFrom('pageAccess')
|
|
||||||
.select('pageId')
|
|
||||||
.where('pageId', 'in', idsToCheck)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
return !hasRestricted;
|
|
||||||
}
|
|
||||||
|
|
||||||
async createShare(opts: {
|
async createShare(opts: {
|
||||||
authUserId: string;
|
authUserId: string;
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
@@ -203,17 +103,6 @@ export class ShareService {
|
|||||||
throw new NotFoundException('Shared page not found');
|
throw new NotFoundException('Shared page not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
// For descendant pages, verify the ancestor chain has no restrictions
|
|
||||||
if (share.level > 0) {
|
|
||||||
const isAccessible = await this.isPagePubliclyAccessible(
|
|
||||||
dto.pageId,
|
|
||||||
share.pageId,
|
|
||||||
);
|
|
||||||
if (!isAccessible) {
|
|
||||||
throw new NotFoundException('Shared page not found');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const page = await this.pageRepo.findById(dto.pageId, {
|
const page = await this.pageRepo.findById(dto.pageId, {
|
||||||
includeContent: true,
|
includeContent: true,
|
||||||
includeCreator: true,
|
includeCreator: true,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
|
Inject,
|
||||||
Injectable,
|
Injectable,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -14,6 +15,11 @@ import { RemoveSpaceMemberDto } from '../dto/remove-space-member.dto';
|
|||||||
import { UpdateSpaceMemberRoleDto } from '../dto/update-space-member-role.dto';
|
import { UpdateSpaceMemberRoleDto } from '../dto/update-space-member-role.dto';
|
||||||
import { SpaceRole } from '../../../common/helpers/types/permission';
|
import { SpaceRole } from '../../../common/helpers/types/permission';
|
||||||
import { PaginationResult } from '@docmost/db/pagination/pagination';
|
import { PaginationResult } from '@docmost/db/pagination/pagination';
|
||||||
|
import { AuditEvent } from '../../../common/events/audit-events';
|
||||||
|
import {
|
||||||
|
AUDIT_SERVICE,
|
||||||
|
IAuditService,
|
||||||
|
} from '../../../integrations/audit/audit.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SpaceMemberService {
|
export class SpaceMemberService {
|
||||||
@@ -21,6 +27,7 @@ export class SpaceMemberService {
|
|||||||
private spaceMemberRepo: SpaceMemberRepo,
|
private spaceMemberRepo: SpaceMemberRepo,
|
||||||
private spaceRepo: SpaceRepo,
|
private spaceRepo: SpaceRepo,
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
|
@Inject(AUDIT_SERVICE) private readonly auditService: IAuditService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async addUserToSpace(
|
async addUserToSpace(
|
||||||
@@ -161,8 +168,43 @@ export class SpaceMemberService {
|
|||||||
|
|
||||||
if (membersToAdd.length > 0) {
|
if (membersToAdd.length > 0) {
|
||||||
await this.spaceMemberRepo.insertSpaceMember(membersToAdd);
|
await this.spaceMemberRepo.insertSpaceMember(membersToAdd);
|
||||||
} else {
|
|
||||||
// either they are already members or do not exist on the workspace
|
// Audit log for each member added
|
||||||
|
for (const user of validUsers) {
|
||||||
|
this.auditService.log({
|
||||||
|
event: AuditEvent.SPACE_MEMBER_ADDED,
|
||||||
|
resourceType: 'space_members',
|
||||||
|
resourceId: dto.spaceId,
|
||||||
|
changes: {
|
||||||
|
after: { role: dto.role },
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
spaceId: dto.spaceId,
|
||||||
|
spaceName: space.name,
|
||||||
|
userId: user.id,
|
||||||
|
userName: user.name,
|
||||||
|
memberType: 'user',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const group of validGroups) {
|
||||||
|
this.auditService.log({
|
||||||
|
event: AuditEvent.SPACE_MEMBER_ADDED,
|
||||||
|
resourceType: 'space_members',
|
||||||
|
resourceId: dto.spaceId,
|
||||||
|
changes: {
|
||||||
|
after: { role: dto.role },
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
spaceId: dto.spaceId,
|
||||||
|
spaceName: space.name,
|
||||||
|
groupId: group.id,
|
||||||
|
groupName: group.name,
|
||||||
|
memberType: 'group',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -209,6 +251,22 @@ export class SpaceMemberService {
|
|||||||
spaceMember.id,
|
spaceMember.id,
|
||||||
dto.spaceId,
|
dto.spaceId,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.auditService.log({
|
||||||
|
event: AuditEvent.SPACE_MEMBER_REMOVED,
|
||||||
|
resourceType: 'space_member',
|
||||||
|
resourceId: dto.spaceId,
|
||||||
|
changes: {
|
||||||
|
before: { role: spaceMember.role },
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
spaceId: dto.spaceId,
|
||||||
|
spaceName: space.name,
|
||||||
|
userId: spaceMember.userId,
|
||||||
|
groupId: spaceMember.groupId,
|
||||||
|
memberType: spaceMember.userId ? 'user' : 'group',
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateSpaceMemberRole(
|
async updateSpaceMemberRole(
|
||||||
@@ -259,6 +317,23 @@ export class SpaceMemberService {
|
|||||||
spaceMember.id,
|
spaceMember.id,
|
||||||
dto.spaceId,
|
dto.spaceId,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.auditService.log({
|
||||||
|
event: AuditEvent.SPACE_MEMBER_ROLE_CHANGED,
|
||||||
|
resourceType: 'space_members',
|
||||||
|
resourceId: dto.spaceId,
|
||||||
|
changes: {
|
||||||
|
before: { role: spaceMember.role },
|
||||||
|
after: { role: dto.role },
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
spaceId: dto.spaceId,
|
||||||
|
spaceName: space.name,
|
||||||
|
userId: spaceMember.userId,
|
||||||
|
groupId: spaceMember.groupId,
|
||||||
|
memberType: spaceMember.userId ? 'user' : 'group',
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async validateLastAdmin(spaceId: string): Promise<void> {
|
async validateLastAdmin(spaceId: string): Promise<void> {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
|
Inject,
|
||||||
Injectable,
|
Injectable,
|
||||||
Logger,
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
@@ -33,6 +34,11 @@ import {
|
|||||||
validateAllowedEmail,
|
validateAllowedEmail,
|
||||||
validateSsoEnforcement,
|
validateSsoEnforcement,
|
||||||
} from '../../auth/auth.util';
|
} from '../../auth/auth.util';
|
||||||
|
import { AuditEvent } from '../../../common/events/audit-events';
|
||||||
|
import {
|
||||||
|
AUDIT_SERVICE,
|
||||||
|
IAuditService,
|
||||||
|
} from '../../../integrations/audit/audit.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class WorkspaceInvitationService {
|
export class WorkspaceInvitationService {
|
||||||
@@ -46,6 +52,7 @@ export class WorkspaceInvitationService {
|
|||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
@InjectQueue(QueueName.BILLING_QUEUE) private billingQueue: Queue,
|
@InjectQueue(QueueName.BILLING_QUEUE) private billingQueue: Queue,
|
||||||
private readonly environmentService: EnvironmentService,
|
private readonly environmentService: EnvironmentService,
|
||||||
|
@Inject(AUDIT_SERVICE) private readonly auditService: IAuditService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async getInvitations(workspaceId: string, pagination: PaginationOptions) {
|
async getInvitations(workspaceId: string, pagination: PaginationOptions) {
|
||||||
@@ -179,6 +186,24 @@ export class WorkspaceInvitationService {
|
|||||||
workspace.hostname,
|
workspace.hostname,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Audit log for each invitation created
|
||||||
|
for (const invitation of invites) {
|
||||||
|
this.auditService.log({
|
||||||
|
event: AuditEvent.WORKSPACE_INVITE_CREATED,
|
||||||
|
resourceType: 'workspace_invitation',
|
||||||
|
resourceId: invitation.id,
|
||||||
|
changes: {
|
||||||
|
after: {
|
||||||
|
email: invitation.email,
|
||||||
|
role: invitation.role,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
groupIds: invitation.groupIds,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -344,11 +369,32 @@ export class WorkspaceInvitationService {
|
|||||||
invitationId: string,
|
invitationId: string,
|
||||||
workspaceId: string,
|
workspaceId: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
|
const invitation = await this.db
|
||||||
|
.selectFrom('workspaceInvitations')
|
||||||
|
.select(['id', 'email', 'role'])
|
||||||
|
.where('id', '=', invitationId)
|
||||||
|
.where('workspaceId', '=', workspaceId)
|
||||||
|
.executeTakeFirst();
|
||||||
|
|
||||||
await this.db
|
await this.db
|
||||||
.deleteFrom('workspaceInvitations')
|
.deleteFrom('workspaceInvitations')
|
||||||
.where('id', '=', invitationId)
|
.where('id', '=', invitationId)
|
||||||
.where('workspaceId', '=', workspaceId)
|
.where('workspaceId', '=', workspaceId)
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
|
if (invitation) {
|
||||||
|
this.auditService.log({
|
||||||
|
event: AuditEvent.WORKSPACE_INVITE_REVOKED,
|
||||||
|
resourceType: 'workspace_invitation',
|
||||||
|
resourceId: invitation.id,
|
||||||
|
changes: {
|
||||||
|
before: {
|
||||||
|
email: invitation.email,
|
||||||
|
role: invitation.role,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getInvitationLinkById(
|
async getInvitationLinkById(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
ForbiddenException,
|
ForbiddenException,
|
||||||
|
Inject,
|
||||||
Injectable,
|
Injectable,
|
||||||
Logger,
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
@@ -34,6 +35,11 @@ import { QueueJob, QueueName } from '../../../integrations/queue/constants';
|
|||||||
import { Queue } from 'bullmq';
|
import { Queue } from 'bullmq';
|
||||||
import { generateRandomSuffixNumbers } from '../../../common/helpers';
|
import { generateRandomSuffixNumbers } from '../../../common/helpers';
|
||||||
import { isPageEmbeddingsTableExists } from '@docmost/db/helpers/helpers';
|
import { isPageEmbeddingsTableExists } from '@docmost/db/helpers/helpers';
|
||||||
|
import { AuditEvent } from '../../../common/events/audit-events';
|
||||||
|
import {
|
||||||
|
AUDIT_SERVICE,
|
||||||
|
IAuditService,
|
||||||
|
} from '../../../integrations/audit/audit.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class WorkspaceService {
|
export class WorkspaceService {
|
||||||
@@ -52,6 +58,7 @@ export class WorkspaceService {
|
|||||||
@InjectQueue(QueueName.ATTACHMENT_QUEUE) private attachmentQueue: Queue,
|
@InjectQueue(QueueName.ATTACHMENT_QUEUE) private attachmentQueue: Queue,
|
||||||
@InjectQueue(QueueName.BILLING_QUEUE) private billingQueue: Queue,
|
@InjectQueue(QueueName.BILLING_QUEUE) private billingQueue: Queue,
|
||||||
@InjectQueue(QueueName.AI_QUEUE) private aiQueue: Queue,
|
@InjectQueue(QueueName.AI_QUEUE) private aiQueue: Queue,
|
||||||
|
@Inject(AUDIT_SERVICE) private readonly auditService: IAuditService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async findById(workspaceId: string) {
|
async findById(workspaceId: string) {
|
||||||
@@ -428,6 +435,20 @@ export class WorkspaceService {
|
|||||||
user.id,
|
user.id,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.auditService.log({
|
||||||
|
event: AuditEvent.USER_ROLE_CHANGED,
|
||||||
|
resourceType: 'users',
|
||||||
|
resourceId: user.id,
|
||||||
|
changes: {
|
||||||
|
before: { role: user.role },
|
||||||
|
after: { role: newRole },
|
||||||
|
},
|
||||||
|
metadata: {
|
||||||
|
userName: user.name,
|
||||||
|
userEmail: user.email,
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async generateHostname(
|
async generateHostname(
|
||||||
@@ -531,6 +552,19 @@ export class WorkspaceService {
|
|||||||
.execute();
|
.execute();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.auditService.log({
|
||||||
|
event: AuditEvent.USER_DELETED,
|
||||||
|
resourceType: 'users',
|
||||||
|
resourceId: user.id,
|
||||||
|
changes: {
|
||||||
|
before: {
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.attachmentQueue.add(QueueJob.DELETE_USER_AVATARS, user);
|
await this.attachmentQueue.add(QueueJob.DELETE_USER_AVATARS, user);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import { GroupUserRepo } from '@docmost/db/repos/group/group-user.repo';
|
|||||||
import { SpaceRepo } from '@docmost/db/repos/space/space.repo';
|
import { SpaceRepo } from '@docmost/db/repos/space/space.repo';
|
||||||
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
||||||
import { PageRepo } from './repos/page/page.repo';
|
import { PageRepo } from './repos/page/page.repo';
|
||||||
import { PagePermissionRepo } from './repos/page/page-permission.repo';
|
|
||||||
import { CommentRepo } from './repos/comment/comment.repo';
|
import { CommentRepo } from './repos/comment/comment.repo';
|
||||||
import { PageHistoryRepo } from './repos/page/page-history.repo';
|
import { PageHistoryRepo } from './repos/page/page-history.repo';
|
||||||
import { AttachmentRepo } from './repos/attachment/attachment.repo';
|
import { AttachmentRepo } from './repos/attachment/attachment.repo';
|
||||||
@@ -72,7 +71,6 @@ types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
|||||||
SpaceRepo,
|
SpaceRepo,
|
||||||
SpaceMemberRepo,
|
SpaceMemberRepo,
|
||||||
PageRepo,
|
PageRepo,
|
||||||
PagePermissionRepo,
|
|
||||||
PageHistoryRepo,
|
PageHistoryRepo,
|
||||||
CommentRepo,
|
CommentRepo,
|
||||||
AttachmentRepo,
|
AttachmentRepo,
|
||||||
@@ -89,7 +87,6 @@ types.setTypeParser(types.builtins.INT8, (val) => Number(val));
|
|||||||
SpaceRepo,
|
SpaceRepo,
|
||||||
SpaceMemberRepo,
|
SpaceMemberRepo,
|
||||||
PageRepo,
|
PageRepo,
|
||||||
PagePermissionRepo,
|
|
||||||
PageHistoryRepo,
|
PageHistoryRepo,
|
||||||
CommentRepo,
|
CommentRepo,
|
||||||
AttachmentRepo,
|
AttachmentRepo,
|
||||||
|
|||||||
@@ -1,200 +0,0 @@
|
|||||||
import { Kysely, sql } from 'kysely';
|
|
||||||
|
|
||||||
export async function up(db: Kysely<any>): Promise<void> {
|
|
||||||
await db.schema
|
|
||||||
.createTable('page_hierarchy')
|
|
||||||
.ifNotExists()
|
|
||||||
.addColumn('ancestor_id', 'uuid', (col) =>
|
|
||||||
col.notNull().references('pages.id').onDelete('cascade'),
|
|
||||||
)
|
|
||||||
.addColumn('descendant_id', 'uuid', (col) =>
|
|
||||||
col.notNull().references('pages.id').onDelete('cascade'),
|
|
||||||
)
|
|
||||||
.addColumn('depth', 'integer', (col) => col.notNull().defaultTo(0))
|
|
||||||
.addPrimaryKeyConstraint('page_hierarchy_pkey', [
|
|
||||||
'ancestor_id',
|
|
||||||
'descendant_id',
|
|
||||||
])
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
// indexes
|
|
||||||
await db.schema
|
|
||||||
.createIndex('idx_page_hierarchy_descendant')
|
|
||||||
.ifNotExists()
|
|
||||||
.on('page_hierarchy')
|
|
||||||
.column('descendant_id')
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createIndex('idx_page_hierarchy_ancestor_depth')
|
|
||||||
.ifNotExists()
|
|
||||||
.on('page_hierarchy')
|
|
||||||
.columns(['ancestor_id', 'depth'])
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createIndex('idx_page_hierarchy_descendant_depth')
|
|
||||||
.ifNotExists()
|
|
||||||
.on('page_hierarchy')
|
|
||||||
.columns(['descendant_id', 'depth'])
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
// rebuild function
|
|
||||||
await sql`
|
|
||||||
CREATE OR REPLACE FUNCTION rebuild_page_hierarchy()
|
|
||||||
RETURNS void
|
|
||||||
LANGUAGE plpgsql
|
|
||||||
AS $$
|
|
||||||
BEGIN
|
|
||||||
TRUNCATE page_hierarchy;
|
|
||||||
|
|
||||||
WITH RECURSIVE page_tree AS (
|
|
||||||
SELECT id AS ancestor_id, id AS descendant_id, 0 AS depth
|
|
||||||
FROM pages WHERE deleted_at IS NULL
|
|
||||||
UNION ALL
|
|
||||||
SELECT pt.ancestor_id, p.id AS descendant_id, pt.depth + 1
|
|
||||||
FROM page_tree pt
|
|
||||||
JOIN pages p ON p.parent_page_id = pt.descendant_id
|
|
||||||
WHERE p.deleted_at IS NULL
|
|
||||||
)
|
|
||||||
INSERT INTO page_hierarchy (ancestor_id, descendant_id, depth)
|
|
||||||
SELECT ancestor_id, descendant_id, depth FROM page_tree;
|
|
||||||
END;
|
|
||||||
$$;
|
|
||||||
`.execute(db);
|
|
||||||
|
|
||||||
// Create insert trigger function
|
|
||||||
await sql`
|
|
||||||
CREATE OR REPLACE FUNCTION page_hierarchy_after_insert()
|
|
||||||
RETURNS TRIGGER
|
|
||||||
LANGUAGE plpgsql
|
|
||||||
AS $$
|
|
||||||
BEGIN
|
|
||||||
IF NEW.deleted_at IS NOT NULL THEN
|
|
||||||
RETURN NEW;
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
IF NEW.parent_page_id IS NULL THEN
|
|
||||||
INSERT INTO page_hierarchy (ancestor_id, descendant_id, depth)
|
|
||||||
VALUES (NEW.id, NEW.id, 0);
|
|
||||||
ELSE
|
|
||||||
INSERT INTO page_hierarchy (ancestor_id, descendant_id, depth)
|
|
||||||
SELECT ancestor_id, NEW.id, depth + 1
|
|
||||||
FROM page_hierarchy
|
|
||||||
WHERE descendant_id = NEW.parent_page_id
|
|
||||||
UNION ALL
|
|
||||||
SELECT NEW.id, NEW.id, 0;
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
RETURN NEW;
|
|
||||||
END;
|
|
||||||
$$;
|
|
||||||
`.execute(db);
|
|
||||||
|
|
||||||
await sql`
|
|
||||||
CREATE OR REPLACE TRIGGER page_hierarchy_after_insert_trigger
|
|
||||||
AFTER INSERT ON pages
|
|
||||||
FOR EACH ROW
|
|
||||||
EXECUTE FUNCTION page_hierarchy_after_insert();
|
|
||||||
`.execute(db);
|
|
||||||
|
|
||||||
// Create update trigger function
|
|
||||||
await sql`
|
|
||||||
CREATE OR REPLACE FUNCTION page_hierarchy_after_update()
|
|
||||||
RETURNS TRIGGER
|
|
||||||
LANGUAGE plpgsql
|
|
||||||
AS $$
|
|
||||||
DECLARE
|
|
||||||
subtree_ids UUID[];
|
|
||||||
BEGIN
|
|
||||||
-- Only process if parent_page_id or deleted_at changed
|
|
||||||
IF OLD.parent_page_id IS NOT DISTINCT FROM NEW.parent_page_id
|
|
||||||
AND OLD.deleted_at IS NOT DISTINCT FROM NEW.deleted_at THEN
|
|
||||||
RETURN NEW;
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
-- Handle soft-delete: remove from closure when deleted_at is set
|
|
||||||
IF OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL THEN
|
|
||||||
SELECT array_agg(descendant_id) INTO subtree_ids
|
|
||||||
FROM page_hierarchy
|
|
||||||
WHERE ancestor_id = NEW.id;
|
|
||||||
|
|
||||||
DELETE FROM page_hierarchy
|
|
||||||
WHERE descendant_id = ANY(subtree_ids);
|
|
||||||
|
|
||||||
RETURN NEW;
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
-- Handle restore: rebuild closure when deleted_at is cleared
|
|
||||||
IF OLD.deleted_at IS NOT NULL AND NEW.deleted_at IS NULL THEN
|
|
||||||
IF NEW.parent_page_id IS NULL THEN
|
|
||||||
INSERT INTO page_hierarchy (ancestor_id, descendant_id, depth)
|
|
||||||
VALUES (NEW.id, NEW.id, 0);
|
|
||||||
ELSE
|
|
||||||
INSERT INTO page_hierarchy (ancestor_id, descendant_id, depth)
|
|
||||||
SELECT ancestor_id, NEW.id, depth + 1
|
|
||||||
FROM page_hierarchy
|
|
||||||
WHERE descendant_id = NEW.parent_page_id
|
|
||||||
UNION ALL
|
|
||||||
SELECT NEW.id, NEW.id, 0;
|
|
||||||
END IF;
|
|
||||||
RETURN NEW;
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
-- Skip if page is soft-deleted
|
|
||||||
IF NEW.deleted_at IS NOT NULL THEN
|
|
||||||
RETURN NEW;
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
-- Move operation: parent changed
|
|
||||||
-- Get all descendants of the moved page (including itself)
|
|
||||||
SELECT array_agg(descendant_id) INTO subtree_ids
|
|
||||||
FROM page_hierarchy
|
|
||||||
WHERE ancestor_id = NEW.id;
|
|
||||||
|
|
||||||
-- Delete old ancestor relationships (keep internal subtree links)
|
|
||||||
DELETE FROM page_hierarchy
|
|
||||||
WHERE descendant_id = ANY(subtree_ids)
|
|
||||||
AND NOT (ancestor_id = ANY(subtree_ids));
|
|
||||||
|
|
||||||
-- Insert new ancestor relationships (if new parent exists)
|
|
||||||
IF NEW.parent_page_id IS NOT NULL THEN
|
|
||||||
INSERT INTO page_hierarchy (ancestor_id, descendant_id, depth)
|
|
||||||
SELECT
|
|
||||||
new_anc.ancestor_id,
|
|
||||||
sub.descendant_id,
|
|
||||||
new_anc.depth + sub.depth + 1
|
|
||||||
FROM page_hierarchy new_anc
|
|
||||||
CROSS JOIN page_hierarchy sub
|
|
||||||
WHERE new_anc.descendant_id = NEW.parent_page_id
|
|
||||||
AND sub.ancestor_id = NEW.id
|
|
||||||
AND sub.descendant_id = ANY(subtree_ids);
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
RETURN NEW;
|
|
||||||
END;
|
|
||||||
$$;
|
|
||||||
`.execute(db);
|
|
||||||
|
|
||||||
await sql`
|
|
||||||
CREATE OR REPLACE TRIGGER page_hierarchy_after_update_trigger
|
|
||||||
AFTER UPDATE ON pages
|
|
||||||
FOR EACH ROW
|
|
||||||
EXECUTE FUNCTION page_hierarchy_after_update();
|
|
||||||
`.execute(db);
|
|
||||||
|
|
||||||
await sql`SELECT rebuild_page_hierarchy()`.execute(db);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function down(db: Kysely<any>): Promise<void> {
|
|
||||||
await sql`DROP TRIGGER IF EXISTS page_hierarchy_after_update_trigger ON pages`.execute(
|
|
||||||
db,
|
|
||||||
);
|
|
||||||
await sql`DROP TRIGGER IF EXISTS page_hierarchy_after_insert_trigger ON pages`.execute(
|
|
||||||
db,
|
|
||||||
);
|
|
||||||
await sql`DROP FUNCTION IF EXISTS page_hierarchy_after_update()`.execute(db);
|
|
||||||
await sql`DROP FUNCTION IF EXISTS page_hierarchy_after_insert()`.execute(db);
|
|
||||||
await sql`DROP FUNCTION IF EXISTS rebuild_page_hierarchy()`.execute(db);
|
|
||||||
await db.schema.dropTable('page_hierarchy').ifExists().execute();
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
import { Kysely, sql } from 'kysely';
|
|
||||||
|
|
||||||
export async function up(db: Kysely<any>): Promise<void> {
|
|
||||||
await db.schema
|
|
||||||
.createTable('page_access')
|
|
||||||
.addColumn('id', 'uuid', (col) =>
|
|
||||||
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
|
|
||||||
)
|
|
||||||
.addColumn('page_id', 'uuid', (col) =>
|
|
||||||
col.notNull().unique().references('pages.id').onDelete('cascade'),
|
|
||||||
)
|
|
||||||
.addColumn('workspace_id', 'uuid', (col) =>
|
|
||||||
col.notNull().references('workspaces.id').onDelete('cascade'),
|
|
||||||
)
|
|
||||||
.addColumn('access_level', 'varchar', (col) => col.notNull())
|
|
||||||
.addColumn('creator_id', 'uuid', (col) =>
|
|
||||||
col.references('users.id').onDelete('set null'),
|
|
||||||
)
|
|
||||||
.addColumn('created_at', 'timestamptz', (col) =>
|
|
||||||
col.notNull().defaultTo(sql`now()`),
|
|
||||||
)
|
|
||||||
.addColumn('updated_at', 'timestamptz', (col) =>
|
|
||||||
col.notNull().defaultTo(sql`now()`),
|
|
||||||
)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createTable('page_permissions')
|
|
||||||
.addColumn('id', 'uuid', (col) =>
|
|
||||||
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
|
|
||||||
)
|
|
||||||
.addColumn('page_access_id', 'uuid', (col) =>
|
|
||||||
col.notNull().references('page_access.id').onDelete('cascade'),
|
|
||||||
)
|
|
||||||
.addColumn('user_id', 'uuid', (col) =>
|
|
||||||
col.references('users.id').onDelete('cascade'),
|
|
||||||
)
|
|
||||||
.addColumn('group_id', 'uuid', (col) =>
|
|
||||||
col.references('groups.id').onDelete('cascade'),
|
|
||||||
)
|
|
||||||
.addColumn('role', 'varchar', (col) => col.notNull())
|
|
||||||
.addColumn('added_by_id', 'uuid', (col) =>
|
|
||||||
col.references('users.id').onDelete('set null'),
|
|
||||||
)
|
|
||||||
.addColumn('created_at', 'timestamptz', (col) =>
|
|
||||||
col.notNull().defaultTo(sql`now()`),
|
|
||||||
)
|
|
||||||
.addColumn('updated_at', 'timestamptz', (col) =>
|
|
||||||
col.notNull().defaultTo(sql`now()`),
|
|
||||||
)
|
|
||||||
.addUniqueConstraint('page_access_user_unique', [
|
|
||||||
'page_access_id',
|
|
||||||
'user_id',
|
|
||||||
])
|
|
||||||
.addUniqueConstraint('page_access_group_unique', [
|
|
||||||
'page_access_id',
|
|
||||||
'group_id',
|
|
||||||
])
|
|
||||||
.addCheckConstraint(
|
|
||||||
'allow_either_user_id_or_group_id_check',
|
|
||||||
sql`((user_id IS NOT NULL AND group_id IS NULL) OR (user_id IS NULL AND group_id IS NOT NULL))`,
|
|
||||||
)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createIndex('idx_page_access_workspace')
|
|
||||||
.on('page_access')
|
|
||||||
.column('workspace_id')
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createIndex('idx_page_permissions_page_access')
|
|
||||||
.on('page_permissions')
|
|
||||||
.column('page_access_id')
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createIndex('idx_page_permissions_user')
|
|
||||||
.on('page_permissions')
|
|
||||||
.column('user_id')
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
await db.schema
|
|
||||||
.createIndex('idx_page_permissions_group')
|
|
||||||
.on('page_permissions')
|
|
||||||
.column('group_id')
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function down(db: Kysely<any>): Promise<void> {
|
|
||||||
await db.schema.dropTable('page_permissions').ifExists().execute();
|
|
||||||
await db.schema.dropTable('page_access').ifExists().execute();
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { Kysely, sql } from 'kysely';
|
||||||
|
|
||||||
|
export async function up(db: Kysely<any>): Promise<void> {
|
||||||
|
await db.schema
|
||||||
|
.createTable('audit_logs')
|
||||||
|
.addColumn('id', 'uuid', (col) =>
|
||||||
|
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
|
||||||
|
)
|
||||||
|
.addColumn('workspace_id', 'uuid', (col) =>
|
||||||
|
col.notNull().references('workspaces.id').onDelete('cascade'),
|
||||||
|
)
|
||||||
|
.addColumn('actor_id', 'uuid', (col) =>
|
||||||
|
col.references('users.id').onDelete('set null'),
|
||||||
|
)
|
||||||
|
.addColumn('actor_type', 'varchar', (col) =>
|
||||||
|
col.notNull().defaultTo('user'),
|
||||||
|
)
|
||||||
|
.addColumn('event', 'varchar', (col) => col.notNull())
|
||||||
|
.addColumn('resource_type', 'varchar', (col) => col.notNull())
|
||||||
|
.addColumn('resource_id', 'uuid')
|
||||||
|
.addColumn('changes', 'jsonb')
|
||||||
|
.addColumn('metadata', 'jsonb')
|
||||||
|
.addColumn('ip_address', sql `inet`)
|
||||||
|
.addColumn('created_at', 'timestamptz', (col) =>
|
||||||
|
col.notNull().defaultTo(sql`now()`),
|
||||||
|
)
|
||||||
|
.execute();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(db: Kysely<any>): Promise<void> {
|
||||||
|
await db.schema.dropTable('audit_logs').execute();
|
||||||
|
}
|
||||||
@@ -152,14 +152,4 @@ export class GroupUserRepo {
|
|||||||
.where('groupId', '=', groupId)
|
.where('groupId', '=', groupId)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUserGroupIds(userId: string): Promise<string[]> {
|
|
||||||
const results = await this.db
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupId')
|
|
||||||
.where('userId', '=', userId)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
return results.map((r) => r.groupId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,692 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
|
||||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
|
||||||
import { dbOrTx } from '@docmost/db/utils';
|
|
||||||
import {
|
|
||||||
InsertablePageAccess,
|
|
||||||
InsertablePagePermission,
|
|
||||||
PageAccess,
|
|
||||||
PagePermission,
|
|
||||||
} from '@docmost/db/types/entity.types';
|
|
||||||
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
|
|
||||||
import { executeWithPagination } from '@docmost/db/pagination/pagination';
|
|
||||||
import { sql } from 'kysely';
|
|
||||||
import { GroupRepo } from '@docmost/db/repos/group/group.repo';
|
|
||||||
import { GroupUserRepo } from '@docmost/db/repos/group/group-user.repo';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class PagePermissionRepo {
|
|
||||||
constructor(
|
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
|
||||||
private readonly groupRepo: GroupRepo,
|
|
||||||
private readonly groupUserRepo: GroupUserRepo,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async findPageAccessByPageId(
|
|
||||||
pageId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<PageAccess | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('pageAccess')
|
|
||||||
.selectAll()
|
|
||||||
.where('pageId', '=', pageId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async insertPageAccess(
|
|
||||||
data: InsertablePageAccess,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<PageAccess> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.insertInto('pageAccess')
|
|
||||||
.values(data)
|
|
||||||
.returningAll()
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async deletePageAccess(pageId: string, trx?: KyselyTransaction): Promise<void> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
await db.deleteFrom('pageAccess').where('pageId', '=', pageId).execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async insertPagePermissions(
|
|
||||||
permissions: InsertablePagePermission[],
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<void> {
|
|
||||||
if (permissions.length === 0) return;
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
await db
|
|
||||||
.insertInto('pagePermissions')
|
|
||||||
.values(permissions)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findPagePermissionByUserId(
|
|
||||||
pageAccessId: string,
|
|
||||||
userId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<PagePermission | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('pagePermissions')
|
|
||||||
.selectAll()
|
|
||||||
.where('pageAccessId', '=', pageAccessId)
|
|
||||||
.where('userId', '=', userId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async findPagePermissionByGroupId(
|
|
||||||
pageAccessId: string,
|
|
||||||
groupId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<PagePermission | undefined> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
return db
|
|
||||||
.selectFrom('pagePermissions')
|
|
||||||
.selectAll()
|
|
||||||
.where('pageAccessId', '=', pageAccessId)
|
|
||||||
.where('groupId', '=', groupId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
async deletePagePermissionByUserId(
|
|
||||||
pageAccessId: string,
|
|
||||||
userId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<void> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
await db
|
|
||||||
.deleteFrom('pagePermissions')
|
|
||||||
.where('pageAccessId', '=', pageAccessId)
|
|
||||||
.where('userId', '=', userId)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async deletePagePermissionByGroupId(
|
|
||||||
pageAccessId: string,
|
|
||||||
groupId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<void> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
await db
|
|
||||||
.deleteFrom('pagePermissions')
|
|
||||||
.where('pageAccessId', '=', pageAccessId)
|
|
||||||
.where('groupId', '=', groupId)
|
|
||||||
.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async updatePagePermissionRole(
|
|
||||||
pageAccessId: string,
|
|
||||||
role: string,
|
|
||||||
opts: { userId?: string; groupId?: string },
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<void> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
let query = db
|
|
||||||
.updateTable('pagePermissions')
|
|
||||||
.set({ role, updatedAt: new Date() })
|
|
||||||
.where('pageAccessId', '=', pageAccessId);
|
|
||||||
|
|
||||||
if (opts.userId) {
|
|
||||||
query = query.where('userId', '=', opts.userId);
|
|
||||||
} else if (opts.groupId) {
|
|
||||||
query = query.where('groupId', '=', opts.groupId);
|
|
||||||
}
|
|
||||||
|
|
||||||
await query.execute();
|
|
||||||
}
|
|
||||||
|
|
||||||
async countWritersByPageAccessId(
|
|
||||||
pageAccessId: string,
|
|
||||||
trx?: KyselyTransaction,
|
|
||||||
): Promise<number> {
|
|
||||||
const db = dbOrTx(this.db, trx);
|
|
||||||
const result = await db
|
|
||||||
.selectFrom('pagePermissions')
|
|
||||||
.select((eb) => eb.fn.count('id').as('count'))
|
|
||||||
.where('pageAccessId', '=', pageAccessId)
|
|
||||||
.where('role', '=', 'writer')
|
|
||||||
.executeTakeFirst();
|
|
||||||
return Number(result?.count ?? 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
async getPagePermissionsPaginated(
|
|
||||||
pageAccessId: string,
|
|
||||||
pagination: PaginationOptions,
|
|
||||||
) {
|
|
||||||
let query = this.db
|
|
||||||
.selectFrom('pagePermissions')
|
|
||||||
.leftJoin('users', 'users.id', 'pagePermissions.userId')
|
|
||||||
.leftJoin('groups', 'groups.id', 'pagePermissions.groupId')
|
|
||||||
.select([
|
|
||||||
'pagePermissions.id',
|
|
||||||
'pagePermissions.role',
|
|
||||||
'pagePermissions.createdAt',
|
|
||||||
'users.id as userId',
|
|
||||||
'users.name as userName',
|
|
||||||
'users.avatarUrl as userAvatarUrl',
|
|
||||||
'users.email as userEmail',
|
|
||||||
'groups.id as groupId',
|
|
||||||
'groups.name as groupName',
|
|
||||||
'groups.isDefault as groupIsDefault',
|
|
||||||
])
|
|
||||||
.select((eb) => this.groupRepo.withMemberCount(eb))
|
|
||||||
.where('pageAccessId', '=', pageAccessId)
|
|
||||||
.orderBy((eb) => eb('groups.id', 'is not', null), 'desc')
|
|
||||||
.orderBy('pagePermissions.createdAt', 'asc');
|
|
||||||
|
|
||||||
if (pagination.query) {
|
|
||||||
query = query.where((eb) =>
|
|
||||||
eb(
|
|
||||||
sql`f_unaccent(users.name)`,
|
|
||||||
'ilike',
|
|
||||||
sql`f_unaccent(${'%' + pagination.query + '%'})`,
|
|
||||||
)
|
|
||||||
.or(
|
|
||||||
sql`users.email`,
|
|
||||||
'ilike',
|
|
||||||
sql`f_unaccent(${'%' + pagination.query + '%'})`,
|
|
||||||
)
|
|
||||||
.or(
|
|
||||||
sql`f_unaccent(groups.name)`,
|
|
||||||
'ilike',
|
|
||||||
sql`f_unaccent(${'%' + pagination.query + '%'})`,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await executeWithPagination(query, {
|
|
||||||
page: pagination.page,
|
|
||||||
perPage: pagination.limit,
|
|
||||||
});
|
|
||||||
|
|
||||||
const members = result.items.map((member) => {
|
|
||||||
if (member.userId) {
|
|
||||||
return {
|
|
||||||
id: member.userId,
|
|
||||||
name: member.userName,
|
|
||||||
email: member.userEmail,
|
|
||||||
avatarUrl: member.userAvatarUrl,
|
|
||||||
type: 'user' as const,
|
|
||||||
role: member.role,
|
|
||||||
createdAt: member.createdAt,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
id: member.groupId,
|
|
||||||
name: member.groupName,
|
|
||||||
memberCount: member.memberCount as number,
|
|
||||||
isDefault: member.groupIsDefault,
|
|
||||||
type: 'group' as const,
|
|
||||||
role: member.role,
|
|
||||||
createdAt: member.createdAt,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
result.items = members as any;
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
async getUserPagePermission(
|
|
||||||
userId: string,
|
|
||||||
pageId: string,
|
|
||||||
): Promise<{ role: string } | undefined> {
|
|
||||||
const result = await this.db
|
|
||||||
.selectFrom('pageAccess')
|
|
||||||
.innerJoin('pagePermissions', 'pagePermissions.pageAccessId', 'pageAccess.id')
|
|
||||||
.select(['pagePermissions.role'])
|
|
||||||
.where('pageAccess.pageId', '=', pageId)
|
|
||||||
.where('pagePermissions.userId', '=', userId)
|
|
||||||
.unionAll(
|
|
||||||
this.db
|
|
||||||
.selectFrom('pageAccess')
|
|
||||||
.innerJoin('pagePermissions', 'pagePermissions.pageAccessId', 'pageAccess.id')
|
|
||||||
.innerJoin('groupUsers', 'groupUsers.groupId', 'pagePermissions.groupId')
|
|
||||||
.select(['pagePermissions.role'])
|
|
||||||
.where('pageAccess.pageId', '=', pageId)
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
async findRestrictedAncestor(
|
|
||||||
pageId: string,
|
|
||||||
): Promise<{ pageId: string; accessLevel: string; depth: number } | undefined> {
|
|
||||||
return this.db
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin('pageAccess', 'pageAccess.pageId', 'pageHierarchy.ancestorId')
|
|
||||||
.select([
|
|
||||||
'pageAccess.pageId',
|
|
||||||
'pageAccess.accessLevel',
|
|
||||||
'pageHierarchy.depth',
|
|
||||||
])
|
|
||||||
.where('pageHierarchy.descendantId', '=', pageId)
|
|
||||||
.orderBy('pageHierarchy.depth', 'asc')
|
|
||||||
.executeTakeFirst();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if user can access a page by verifying they have permission on ALL restricted ancestors.
|
|
||||||
*/
|
|
||||||
async canUserAccessPage(userId: string, pageId: string): Promise<boolean> {
|
|
||||||
const deniedAncestor = await this.db
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin('pageAccess', 'pageAccess.pageId', 'pageHierarchy.ancestorId')
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on((eb) =>
|
|
||||||
eb.or([
|
|
||||||
eb('pagePermissions.userId', '=', userId),
|
|
||||||
eb(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
eb
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupUsers.groupId')
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.where('pageHierarchy.descendantId', '=', pageId)
|
|
||||||
.where('pagePermissions.id', 'is', null)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
return !deniedAncestor;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if user can edit a page by verifying they have WRITER permission on ALL restricted ancestors.
|
|
||||||
*/
|
|
||||||
async canUserEditPage(userId: string, pageId: string): Promise<boolean> {
|
|
||||||
const deniedAncestor = await this.db
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin('pageAccess', 'pageAccess.pageId', 'pageHierarchy.ancestorId')
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on('pagePermissions.role', '=', 'writer')
|
|
||||||
.on((eb) =>
|
|
||||||
eb.or([
|
|
||||||
eb('pagePermissions.userId', '=', userId),
|
|
||||||
eb(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
eb
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupUsers.groupId')
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.where('pageHierarchy.descendantId', '=', pageId)
|
|
||||||
.where('pagePermissions.id', 'is', null)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
return !deniedAncestor;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get user's access level for a page, checking ALL restricted ancestors.
|
|
||||||
* Returns:
|
|
||||||
* - hasRestriction: whether page or any ancestor has restrictions
|
|
||||||
* - canAccess: user has permission on all restricted ancestors (always true if no restrictions)
|
|
||||||
* - canEdit: user has writer permission on all restricted ancestors (always true if no restrictions)
|
|
||||||
*/
|
|
||||||
async getUserPageAccessLevel(
|
|
||||||
userId: string,
|
|
||||||
pageId: string,
|
|
||||||
): Promise<{ hasRestriction: boolean; canAccess: boolean; canEdit: boolean }> {
|
|
||||||
const result = await this.db
|
|
||||||
.selectFrom('pages')
|
|
||||||
.select((eb) => [
|
|
||||||
// hasRestriction: any ancestor has page_access entry
|
|
||||||
eb
|
|
||||||
.case()
|
|
||||||
.when(
|
|
||||||
eb.exists(
|
|
||||||
eb
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin(
|
|
||||||
'pageAccess',
|
|
||||||
'pageAccess.pageId',
|
|
||||||
'pageHierarchy.ancestorId',
|
|
||||||
)
|
|
||||||
.select('pageAccess.id')
|
|
||||||
.whereRef('pageHierarchy.descendantId', '=', 'pages.id'),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.then(true)
|
|
||||||
.else(false)
|
|
||||||
.end()
|
|
||||||
.as('hasRestriction'),
|
|
||||||
// canAccess: no restricted ancestor without ANY permission
|
|
||||||
eb
|
|
||||||
.case()
|
|
||||||
.when(
|
|
||||||
eb.not(
|
|
||||||
eb.exists(
|
|
||||||
eb
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin(
|
|
||||||
'pageAccess',
|
|
||||||
'pageAccess.pageId',
|
|
||||||
'pageHierarchy.ancestorId',
|
|
||||||
)
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on((eb2) =>
|
|
||||||
eb2.or([
|
|
||||||
eb2('pagePermissions.userId', '=', userId),
|
|
||||||
eb2(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
eb2
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupUsers.groupId')
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.whereRef('pageHierarchy.descendantId', '=', 'pages.id')
|
|
||||||
.where('pagePermissions.id', 'is', null),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.then(true)
|
|
||||||
.else(false)
|
|
||||||
.end()
|
|
||||||
.as('canAccess'),
|
|
||||||
// canEdit: no restricted ancestor without WRITER permission
|
|
||||||
eb
|
|
||||||
.case()
|
|
||||||
.when(
|
|
||||||
eb.not(
|
|
||||||
eb.exists(
|
|
||||||
eb
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin(
|
|
||||||
'pageAccess',
|
|
||||||
'pageAccess.pageId',
|
|
||||||
'pageHierarchy.ancestorId',
|
|
||||||
)
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on('pagePermissions.role', '=', 'writer')
|
|
||||||
.on((eb2) =>
|
|
||||||
eb2.or([
|
|
||||||
eb2('pagePermissions.userId', '=', userId),
|
|
||||||
eb2(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
eb2
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupUsers.groupId')
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.whereRef('pageHierarchy.descendantId', '=', 'pages.id')
|
|
||||||
.where('pagePermissions.id', 'is', null),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.then(true)
|
|
||||||
.else(false)
|
|
||||||
.end()
|
|
||||||
.as('canEdit'),
|
|
||||||
])
|
|
||||||
.where('pages.id', '=', pageId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
return {
|
|
||||||
hasRestriction: Boolean(result?.hasRestriction),
|
|
||||||
canAccess: Boolean(result?.canAccess),
|
|
||||||
canEdit: Boolean(result?.canEdit),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Filter a list of page IDs to only those the user can access.
|
|
||||||
* Returns page IDs with their permission level (canEdit).
|
|
||||||
* Single query implementation for efficiency.
|
|
||||||
*/
|
|
||||||
async filterAccessiblePageIdsWithPermissions(
|
|
||||||
pageIds: string[],
|
|
||||||
userId: string,
|
|
||||||
): Promise<Array<{ id: string; canEdit: boolean }>> {
|
|
||||||
if (pageIds.length === 0) return [];
|
|
||||||
|
|
||||||
const results = await this.db
|
|
||||||
.selectFrom('pages')
|
|
||||||
.select('pages.id')
|
|
||||||
// Check if user lacks writer permission on any restricted ancestor
|
|
||||||
.select((eb) =>
|
|
||||||
eb
|
|
||||||
.case()
|
|
||||||
.when(
|
|
||||||
eb.not(
|
|
||||||
eb.exists(
|
|
||||||
eb
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin(
|
|
||||||
'pageAccess',
|
|
||||||
'pageAccess.pageId',
|
|
||||||
'pageHierarchy.ancestorId',
|
|
||||||
)
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on('pagePermissions.role', '=', 'writer')
|
|
||||||
.on((eb2) =>
|
|
||||||
eb2.or([
|
|
||||||
eb2('pagePermissions.userId', '=', userId),
|
|
||||||
eb2(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
eb2
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupUsers.groupId')
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.whereRef('pageHierarchy.descendantId', '=', 'pages.id')
|
|
||||||
.where('pagePermissions.id', 'is', null),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.then(true)
|
|
||||||
.else(false)
|
|
||||||
.end()
|
|
||||||
.as('canEdit'),
|
|
||||||
)
|
|
||||||
.where('pages.id', 'in', pageIds)
|
|
||||||
// Filter: user must have access (any permission on all restricted ancestors)
|
|
||||||
.where(({ not, exists, selectFrom }) =>
|
|
||||||
not(
|
|
||||||
exists(
|
|
||||||
selectFrom('pageHierarchy')
|
|
||||||
.innerJoin(
|
|
||||||
'pageAccess',
|
|
||||||
'pageAccess.pageId',
|
|
||||||
'pageHierarchy.ancestorId',
|
|
||||||
)
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on((eb) =>
|
|
||||||
eb.or([
|
|
||||||
eb('pagePermissions.userId', '=', userId),
|
|
||||||
eb(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
eb
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupUsers.groupId')
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.whereRef('pageHierarchy.descendantId', '=', 'pages.id')
|
|
||||||
.where('pagePermissions.id', 'is', null),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
return results.map((r) => ({ id: r.id, canEdit: Boolean(r.canEdit) }));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a page or any of its ancestors has restrictions.
|
|
||||||
* Used to determine if page-level permission checks are needed.
|
|
||||||
*/
|
|
||||||
async hasRestrictedAncestor(pageId: string): Promise<boolean> {
|
|
||||||
const result = await this.db
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin('pageAccess', 'pageAccess.pageId', 'pageHierarchy.ancestorId')
|
|
||||||
.select('pageAccess.id')
|
|
||||||
.where('pageHierarchy.descendantId', '=', pageId)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
return !!result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Given a list of parent page IDs, return which ones have at least one accessible child.
|
|
||||||
* Efficient batch query for sidebar hasChildren calculation.
|
|
||||||
*/
|
|
||||||
async getParentIdsWithAccessibleChildren(
|
|
||||||
parentIds: string[],
|
|
||||||
userId: string,
|
|
||||||
): Promise<string[]> {
|
|
||||||
if (parentIds.length === 0) return [];
|
|
||||||
|
|
||||||
const results = await this.db
|
|
||||||
.selectFrom('pages as child')
|
|
||||||
.select('child.parentPageId')
|
|
||||||
.distinct()
|
|
||||||
.where('child.parentPageId', 'in', parentIds)
|
|
||||||
.where('child.deletedAt', 'is', null)
|
|
||||||
.where(({ not, exists, selectFrom }) =>
|
|
||||||
not(
|
|
||||||
exists(
|
|
||||||
selectFrom('pageHierarchy')
|
|
||||||
.innerJoin(
|
|
||||||
'pageAccess',
|
|
||||||
'pageAccess.pageId',
|
|
||||||
'pageHierarchy.ancestorId',
|
|
||||||
)
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on((eb) =>
|
|
||||||
eb.or([
|
|
||||||
eb('pagePermissions.userId', '=', userId),
|
|
||||||
eb(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
eb
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupUsers.groupId')
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.whereRef('pageHierarchy.descendantId', '=', 'child.id')
|
|
||||||
.where('pagePermissions.id', 'is', null),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
return results.map((r) => r.parentPageId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if any descendant of a page has restrictions that the user cannot access.
|
|
||||||
* Used to determine if includeSubPages can be enabled for sharing.
|
|
||||||
*/
|
|
||||||
async hasInaccessibleDescendants(
|
|
||||||
pageId: string,
|
|
||||||
userId: string,
|
|
||||||
): Promise<boolean> {
|
|
||||||
// Get all descendant page IDs (excluding the root page itself)
|
|
||||||
const descendants = await this.db
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.select('descendantId')
|
|
||||||
.where('ancestorId', '=', pageId)
|
|
||||||
.where('depth', '>', 0)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
if (descendants.length === 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const descendantIds = descendants.map((d) => d.descendantId);
|
|
||||||
|
|
||||||
// Check if any descendant has a restriction the user cannot access
|
|
||||||
const inaccessible = await this.db
|
|
||||||
.selectFrom('pageAccess')
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on((eb) =>
|
|
||||||
eb.or([
|
|
||||||
eb('pagePermissions.userId', '=', userId),
|
|
||||||
eb(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
eb
|
|
||||||
.selectFrom('groupUsers')
|
|
||||||
.select('groupUsers.groupId')
|
|
||||||
.where('groupUsers.userId', '=', userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.where('pageAccess.pageId', 'in', descendantIds)
|
|
||||||
.where('pagePermissions.id', 'is', null)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
return !!inaccessible;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all descendant page IDs that have restrictions (page_access entries).
|
|
||||||
* Used to filter restricted pages from public share trees.
|
|
||||||
*/
|
|
||||||
async getRestrictedDescendantIds(pageId: string): Promise<string[]> {
|
|
||||||
const results = await this.db
|
|
||||||
.selectFrom('pageHierarchy')
|
|
||||||
.innerJoin('pageAccess', 'pageAccess.pageId', 'pageHierarchy.descendantId')
|
|
||||||
.select('pageHierarchy.descendantId')
|
|
||||||
.where('pageHierarchy.ancestorId', '=', pageId)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
return results.map((r) => r.descendantId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+28
-45
@@ -3,18 +3,13 @@
|
|||||||
* Please do not edit it manually.
|
* Please do not edit it manually.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { ColumnType } from 'kysely';
|
import type { ColumnType } from "kysely";
|
||||||
|
|
||||||
export type Generated<T> =
|
export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>
|
||||||
T extends ColumnType<infer S, infer I, infer U>
|
? ColumnType<S, I | undefined, U>
|
||||||
? ColumnType<S, I | undefined, U>
|
: ColumnType<T, T | undefined, T>;
|
||||||
: ColumnType<T, T | undefined, T>;
|
|
||||||
|
|
||||||
export type Int8 = ColumnType<
|
export type Int8 = ColumnType<string, bigint | number | string, bigint | number | string>;
|
||||||
string,
|
|
||||||
bigint | number | string,
|
|
||||||
bigint | number | string
|
|
||||||
>;
|
|
||||||
|
|
||||||
export type Json = JsonValue;
|
export type Json = JsonValue;
|
||||||
|
|
||||||
@@ -32,13 +27,13 @@ export type Timestamp = ColumnType<Date, Date | string, Date | string>;
|
|||||||
|
|
||||||
export interface ApiKeys {
|
export interface ApiKeys {
|
||||||
createdAt: Generated<Timestamp>;
|
createdAt: Generated<Timestamp>;
|
||||||
|
creatorId: string;
|
||||||
deletedAt: Timestamp | null;
|
deletedAt: Timestamp | null;
|
||||||
expiresAt: Timestamp | null;
|
expiresAt: Timestamp | null;
|
||||||
id: Generated<string>;
|
id: Generated<string>;
|
||||||
lastUsedAt: Timestamp | null;
|
lastUsedAt: Timestamp | null;
|
||||||
name: string | null;
|
name: string | null;
|
||||||
updatedAt: Generated<Timestamp>;
|
updatedAt: Generated<Timestamp>;
|
||||||
creatorId: string;
|
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,6 +56,20 @@ export interface Attachments {
|
|||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AuditLogs {
|
||||||
|
actorId: string | null;
|
||||||
|
actorType: Generated<string>;
|
||||||
|
changes: Json | null;
|
||||||
|
createdAt: Generated<Timestamp>;
|
||||||
|
event: string;
|
||||||
|
id: Generated<string>;
|
||||||
|
ipAddress: string | null;
|
||||||
|
metadata: Json | null;
|
||||||
|
resourceId: string | null;
|
||||||
|
resourceType: string;
|
||||||
|
workspaceId: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AuthAccounts {
|
export interface AuthAccounts {
|
||||||
authProviderId: string | null;
|
authProviderId: string | null;
|
||||||
createdAt: Generated<Timestamp>;
|
createdAt: Generated<Timestamp>;
|
||||||
@@ -77,25 +86,25 @@ export interface AuthProviders {
|
|||||||
createdAt: Generated<Timestamp>;
|
createdAt: Generated<Timestamp>;
|
||||||
creatorId: string | null;
|
creatorId: string | null;
|
||||||
deletedAt: Timestamp | null;
|
deletedAt: Timestamp | null;
|
||||||
|
groupSync: Generated<boolean>;
|
||||||
id: Generated<string>;
|
id: Generated<string>;
|
||||||
isEnabled: Generated<boolean>;
|
isEnabled: Generated<boolean>;
|
||||||
groupSync: Generated<boolean>;
|
|
||||||
ldapBaseDn: string | null;
|
ldapBaseDn: string | null;
|
||||||
ldapBindDn: string | null;
|
ldapBindDn: string | null;
|
||||||
ldapBindPassword: string | null;
|
ldapBindPassword: string | null;
|
||||||
|
ldapConfig: Json | null;
|
||||||
ldapTlsCaCert: string | null;
|
ldapTlsCaCert: string | null;
|
||||||
ldapTlsEnabled: Generated<boolean | null>;
|
ldapTlsEnabled: Generated<boolean | null>;
|
||||||
ldapUrl: string | null;
|
ldapUrl: string | null;
|
||||||
ldapUserAttributes: Json | null;
|
ldapUserAttributes: Json | null;
|
||||||
ldapUserSearchFilter: string | null;
|
ldapUserSearchFilter: string | null;
|
||||||
ldapConfig: Json | null;
|
|
||||||
settings: Json | null;
|
|
||||||
name: string;
|
name: string;
|
||||||
oidcClientId: string | null;
|
oidcClientId: string | null;
|
||||||
oidcClientSecret: string | null;
|
oidcClientSecret: string | null;
|
||||||
oidcIssuer: string | null;
|
oidcIssuer: string | null;
|
||||||
samlCertificate: string | null;
|
samlCertificate: string | null;
|
||||||
samlUrl: string | null;
|
samlUrl: string | null;
|
||||||
|
settings: Json | null;
|
||||||
type: string;
|
type: string;
|
||||||
updatedAt: Generated<Timestamp>;
|
updatedAt: Generated<Timestamp>;
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
@@ -197,12 +206,6 @@ export interface GroupUsers {
|
|||||||
userId: string;
|
userId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PageHierarchy {
|
|
||||||
ancestorId: string;
|
|
||||||
descendantId: string;
|
|
||||||
depth: Generated<number>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PageHistory {
|
export interface PageHistory {
|
||||||
content: Json | null;
|
content: Json | null;
|
||||||
coverPhoto: string | null;
|
coverPhoto: string | null;
|
||||||
@@ -231,9 +234,11 @@ export interface Pages {
|
|||||||
icon: string | null;
|
icon: string | null;
|
||||||
id: Generated<string>;
|
id: Generated<string>;
|
||||||
isLocked: Generated<boolean>;
|
isLocked: Generated<boolean>;
|
||||||
|
isRestricted: Generated<boolean>;
|
||||||
lastUpdatedById: string | null;
|
lastUpdatedById: string | null;
|
||||||
parentPageId: string | null;
|
parentPageId: string | null;
|
||||||
position: string | null;
|
position: string | null;
|
||||||
|
restrictedById: string | null;
|
||||||
slugId: string;
|
slugId: string;
|
||||||
spaceId: string;
|
spaceId: string;
|
||||||
textContent: string | null;
|
textContent: string | null;
|
||||||
@@ -304,12 +309,12 @@ export interface Users {
|
|||||||
deletedAt: Timestamp | null;
|
deletedAt: Timestamp | null;
|
||||||
email: string;
|
email: string;
|
||||||
emailVerifiedAt: Timestamp | null;
|
emailVerifiedAt: Timestamp | null;
|
||||||
|
hasGeneratedPassword: Generated<boolean | null>;
|
||||||
id: Generated<string>;
|
id: Generated<string>;
|
||||||
invitedById: string | null;
|
invitedById: string | null;
|
||||||
lastActiveAt: Timestamp | null;
|
lastActiveAt: Timestamp | null;
|
||||||
lastLoginAt: Timestamp | null;
|
lastLoginAt: Timestamp | null;
|
||||||
locale: string | null;
|
locale: string | null;
|
||||||
hasGeneratedPassword: Generated<boolean | null>;
|
|
||||||
name: string | null;
|
name: string | null;
|
||||||
password: string | null;
|
password: string | null;
|
||||||
role: string | null;
|
role: string | null;
|
||||||
@@ -366,30 +371,10 @@ export interface Workspaces {
|
|||||||
updatedAt: Generated<Timestamp>;
|
updatedAt: Generated<Timestamp>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PageAccess {
|
|
||||||
id: Generated<string>;
|
|
||||||
pageId: string;
|
|
||||||
workspaceId: string;
|
|
||||||
accessLevel: string;
|
|
||||||
creatorId: string | null;
|
|
||||||
createdAt: Generated<Timestamp>;
|
|
||||||
updatedAt: Generated<Timestamp>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PagePermissions {
|
|
||||||
id: Generated<string>;
|
|
||||||
pageAccessId: string;
|
|
||||||
userId: string | null;
|
|
||||||
groupId: string | null;
|
|
||||||
role: string;
|
|
||||||
addedById: string | null;
|
|
||||||
createdAt: Generated<Timestamp>;
|
|
||||||
updatedAt: Generated<Timestamp>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DB {
|
export interface DB {
|
||||||
apiKeys: ApiKeys;
|
apiKeys: ApiKeys;
|
||||||
attachments: Attachments;
|
attachments: Attachments;
|
||||||
|
auditLogs: AuditLogs;
|
||||||
authAccounts: AuthAccounts;
|
authAccounts: AuthAccounts;
|
||||||
authProviders: AuthProviders;
|
authProviders: AuthProviders;
|
||||||
backlinks: Backlinks;
|
backlinks: Backlinks;
|
||||||
@@ -398,10 +383,8 @@ export interface DB {
|
|||||||
fileTasks: FileTasks;
|
fileTasks: FileTasks;
|
||||||
groups: Groups;
|
groups: Groups;
|
||||||
groupUsers: GroupUsers;
|
groupUsers: GroupUsers;
|
||||||
pageAccess: PageAccess;
|
|
||||||
pageHierarchy: PageHierarchy;
|
|
||||||
pageHistory: PageHistory;
|
pageHistory: PageHistory;
|
||||||
pagePermissions: PagePermissions;
|
AuditLog: PagePermissions;
|
||||||
pages: Pages;
|
pages: Pages;
|
||||||
shares: Shares;
|
shares: Shares;
|
||||||
spaceMembers: SpaceMembers;
|
spaceMembers: SpaceMembers;
|
||||||
|
|||||||
@@ -1,53 +1,6 @@
|
|||||||
import {
|
import { DB } from '@docmost/db/types/db';
|
||||||
ApiKeys,
|
|
||||||
Attachments,
|
|
||||||
AuthAccounts,
|
|
||||||
AuthProviders,
|
|
||||||
Backlinks,
|
|
||||||
Billing,
|
|
||||||
Comments,
|
|
||||||
FileTasks,
|
|
||||||
Groups,
|
|
||||||
GroupUsers,
|
|
||||||
PageAccess,
|
|
||||||
PageHierarchy,
|
|
||||||
PageHistory,
|
|
||||||
PagePermissions,
|
|
||||||
Pages,
|
|
||||||
Shares,
|
|
||||||
SpaceMembers,
|
|
||||||
Spaces,
|
|
||||||
UserMfa,
|
|
||||||
Users,
|
|
||||||
UserTokens,
|
|
||||||
WorkspaceInvitations,
|
|
||||||
Workspaces,
|
|
||||||
} from '@docmost/db/types/db';
|
|
||||||
import { PageEmbeddings } from '@docmost/db/types/embeddings.types';
|
import { PageEmbeddings } from '@docmost/db/types/embeddings.types';
|
||||||
|
|
||||||
export interface DbInterface {
|
export interface DbInterface extends DB {
|
||||||
attachments: Attachments;
|
|
||||||
authAccounts: AuthAccounts;
|
|
||||||
authProviders: AuthProviders;
|
|
||||||
backlinks: Backlinks;
|
|
||||||
billing: Billing;
|
|
||||||
comments: Comments;
|
|
||||||
fileTasks: FileTasks;
|
|
||||||
groups: Groups;
|
|
||||||
groupUsers: GroupUsers;
|
|
||||||
pageAccess: PageAccess;
|
|
||||||
pageHierarchy: PageHierarchy;
|
|
||||||
pageEmbeddings: PageEmbeddings;
|
pageEmbeddings: PageEmbeddings;
|
||||||
pageHistory: PageHistory;
|
|
||||||
pagePermissions: PagePermissions;
|
|
||||||
pages: Pages;
|
|
||||||
shares: Shares;
|
|
||||||
spaceMembers: SpaceMembers;
|
|
||||||
spaces: Spaces;
|
|
||||||
userMfa: UserMfa;
|
|
||||||
users: Users;
|
|
||||||
userTokens: UserTokens;
|
|
||||||
workspaceInvitations: WorkspaceInvitations;
|
|
||||||
workspaces: Workspaces;
|
|
||||||
apiKeys: ApiKeys;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,6 @@ import {
|
|||||||
Attachments,
|
Attachments,
|
||||||
Comments,
|
Comments,
|
||||||
Groups,
|
Groups,
|
||||||
PageAccess as _PageAccess,
|
|
||||||
PageHierarchy as _PageHierarchy,
|
|
||||||
PagePermissions as _PagePermissions,
|
|
||||||
Pages,
|
Pages,
|
||||||
Spaces,
|
Spaces,
|
||||||
Users,
|
Users,
|
||||||
@@ -23,6 +20,7 @@ import {
|
|||||||
FileTasks,
|
FileTasks,
|
||||||
UserMfa as _UserMFA,
|
UserMfa as _UserMFA,
|
||||||
ApiKeys,
|
ApiKeys,
|
||||||
|
AuditLogs,
|
||||||
} from './db';
|
} from './db';
|
||||||
import { PageEmbeddings } from '@docmost/db/types/embeddings.types';
|
import { PageEmbeddings } from '@docmost/db/types/embeddings.types';
|
||||||
|
|
||||||
@@ -135,16 +133,7 @@ export type PageEmbedding = Selectable<PageEmbeddings>;
|
|||||||
export type InsertablePageEmbedding = Insertable<PageEmbeddings>;
|
export type InsertablePageEmbedding = Insertable<PageEmbeddings>;
|
||||||
export type UpdatablePageEmbedding = Updateable<Omit<PageEmbeddings, 'id'>>;
|
export type UpdatablePageEmbedding = Updateable<Omit<PageEmbeddings, 'id'>>;
|
||||||
|
|
||||||
// Page Hierarchy (closure table - composite primary key)
|
// Audit Log
|
||||||
export type PageHierarchy = Selectable<_PageHierarchy>;
|
export type AuditLog = Selectable<AuditLogs>;
|
||||||
export type InsertablePageHierarchy = Insertable<_PageHierarchy>;
|
export type InsertableAuditLog = Insertable<AuditLogs>;
|
||||||
|
export type UpdatableAuditLog = Updateable<Omit<AuditLogs, 'id'>>;
|
||||||
// Page Access
|
|
||||||
export type PageAccess = Selectable<_PageAccess>;
|
|
||||||
export type InsertablePageAccess = Insertable<_PageAccess>;
|
|
||||||
export type UpdatablePageAccess = Updateable<Omit<_PageAccess, 'id'>>;
|
|
||||||
|
|
||||||
// Page Permission
|
|
||||||
export type PagePermission = Selectable<_PagePermissions>;
|
|
||||||
export type InsertablePagePermission = Insertable<_PagePermissions>;
|
|
||||||
export type UpdatablePagePermission = Updateable<Omit<_PagePermissions, 'id'>>;
|
|
||||||
|
|||||||
+1
-1
Submodule apps/server/src/ee updated: 075761c2d9...741c15eba3
@@ -0,0 +1,48 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { AuditLogPayload, ActorType } from '../../common/events/audit-events';
|
||||||
|
|
||||||
|
export type IAuditService = {
|
||||||
|
log(payload: AuditLogPayload): void | Promise<void>;
|
||||||
|
logWithContext(
|
||||||
|
payload: AuditLogPayload,
|
||||||
|
context: {
|
||||||
|
workspaceId: string;
|
||||||
|
actorId?: string;
|
||||||
|
actorType?: ActorType;
|
||||||
|
ipAddress?: string;
|
||||||
|
userAgent?: string;
|
||||||
|
},
|
||||||
|
): void | Promise<void>;
|
||||||
|
setActorId(actorId: string): void;
|
||||||
|
setActorType(actorType: ActorType): void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AUDIT_SERVICE = Symbol('AUDIT_SERVICE');
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class NoopAuditService implements IAuditService {
|
||||||
|
log(_payload: AuditLogPayload): void {
|
||||||
|
// No-op: swallow the log when EE module is not available
|
||||||
|
}
|
||||||
|
|
||||||
|
logWithContext(
|
||||||
|
_payload: AuditLogPayload,
|
||||||
|
_context: {
|
||||||
|
workspaceId: string;
|
||||||
|
actorId?: string;
|
||||||
|
actorType?: ActorType;
|
||||||
|
ipAddress?: string;
|
||||||
|
userAgent?: string;
|
||||||
|
},
|
||||||
|
): void {
|
||||||
|
// No-op: swallow the log when EE module is not available
|
||||||
|
}
|
||||||
|
|
||||||
|
setActorId(_actorId: string): void {
|
||||||
|
// No-op
|
||||||
|
}
|
||||||
|
|
||||||
|
setActorType(_actorType: ActorType): void {
|
||||||
|
// No-op
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ export enum QueueName {
|
|||||||
FILE_TASK_QUEUE = '{file-task-queue}',
|
FILE_TASK_QUEUE = '{file-task-queue}',
|
||||||
SEARCH_QUEUE = '{search-queue}',
|
SEARCH_QUEUE = '{search-queue}',
|
||||||
AI_QUEUE = '{ai-queue}',
|
AI_QUEUE = '{ai-queue}',
|
||||||
|
AUDIT_QUEUE = '{audit-queue}',
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum QueueJob {
|
export enum QueueJob {
|
||||||
@@ -58,4 +59,7 @@ export enum QueueJob {
|
|||||||
|
|
||||||
GENERATE_PAGE_EMBEDDINGS = 'generate-page-embeddings',
|
GENERATE_PAGE_EMBEDDINGS = 'generate-page-embeddings',
|
||||||
DELETE_PAGE_EMBEDDINGS = 'delete-page-embeddings',
|
DELETE_PAGE_EMBEDDINGS = 'delete-page-embeddings',
|
||||||
|
|
||||||
|
AUDIT_LOG = 'audit-log',
|
||||||
|
AUDIT_CLEANUP = 'audit-cleanup',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,6 +73,14 @@ import { BacklinksProcessor } from './processors/backlinks.processor';
|
|||||||
attempts: 1,
|
attempts: 1,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: QueueName.AUDIT_QUEUE,
|
||||||
|
defaultJobOptions: {
|
||||||
|
removeOnComplete: true,
|
||||||
|
removeOnFail: true,
|
||||||
|
attempts: 3,
|
||||||
|
},
|
||||||
|
}),
|
||||||
],
|
],
|
||||||
exports: [BullModule],
|
exports: [BullModule],
|
||||||
providers: [BacklinksProcessor],
|
providers: [BacklinksProcessor],
|
||||||
|
|||||||
Generated
+19
@@ -578,6 +578,9 @@ importers:
|
|||||||
nanoid:
|
nanoid:
|
||||||
specifier: 3.3.11
|
specifier: 3.3.11
|
||||||
version: 3.3.11
|
version: 3.3.11
|
||||||
|
nestjs-cls:
|
||||||
|
specifier: ^4.5.0
|
||||||
|
version: 4.5.0(@nestjs/common@11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.9)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
nestjs-kysely:
|
nestjs-kysely:
|
||||||
specifier: ^1.2.0
|
specifier: ^1.2.0
|
||||||
version: 1.2.0(@nestjs/common@11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.9)(kysely@0.28.2)(reflect-metadata@0.2.2)
|
version: 1.2.0(@nestjs/common@11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.9)(kysely@0.28.2)(reflect-metadata@0.2.2)
|
||||||
@@ -7982,6 +7985,15 @@ packages:
|
|||||||
neo-async@2.6.2:
|
neo-async@2.6.2:
|
||||||
resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==}
|
resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==}
|
||||||
|
|
||||||
|
nestjs-cls@4.5.0:
|
||||||
|
resolution: {integrity: sha512-oi3GNCc5pnsnVI5WJKMDwmg4NP+JyEw+edlwgepyUba5+RGGtJzpbVaaxXGW1iPbDuQde3/fA8Jdjq9j88BVcQ==}
|
||||||
|
engines: {node: '>=16'}
|
||||||
|
peerDependencies:
|
||||||
|
'@nestjs/common': '> 7.0.0 < 11'
|
||||||
|
'@nestjs/core': '> 7.0.0 < 11'
|
||||||
|
reflect-metadata: '*'
|
||||||
|
rxjs: '>= 7'
|
||||||
|
|
||||||
nestjs-kysely@1.2.0:
|
nestjs-kysely@1.2.0:
|
||||||
resolution: {integrity: sha512-KseCGb0SXCzIYC+Hx3Z3d+kPAfSZCSK6j9UoqUV/gcBCPad9utC7itmoUw0/w5sV+Jf9pc1DKpgClP1IkflA4w==}
|
resolution: {integrity: sha512-KseCGb0SXCzIYC+Hx3Z3d+kPAfSZCSK6j9UoqUV/gcBCPad9utC7itmoUw0/w5sV+Jf9pc1DKpgClP1IkflA4w==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@@ -19131,6 +19143,13 @@ snapshots:
|
|||||||
|
|
||||||
neo-async@2.6.2: {}
|
neo-async@2.6.2: {}
|
||||||
|
|
||||||
|
nestjs-cls@4.5.0(@nestjs/common@11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.9)(reflect-metadata@0.2.2)(rxjs@7.8.2):
|
||||||
|
dependencies:
|
||||||
|
'@nestjs/common': 11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
|
'@nestjs/core': 11.1.9(@nestjs/common@11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/websockets@11.1.9)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
|
reflect-metadata: 0.2.2
|
||||||
|
rxjs: 7.8.2
|
||||||
|
|
||||||
nestjs-kysely@1.2.0(@nestjs/common@11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.9)(kysely@0.28.2)(reflect-metadata@0.2.2):
|
nestjs-kysely@1.2.0(@nestjs/common@11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.9)(kysely@0.28.2)(reflect-metadata@0.2.2):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@nestjs/common': 11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
'@nestjs/common': 11.1.9(class-transformer@0.5.1)(class-validator@0.14.3)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
|
|||||||
Reference in New Issue
Block a user