mirror of
https://github.com/docmost/docmost.git
synced 2026-05-08 23:33:09 +08:00
Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| db404815b0 | |||
| d9ebeb2b85 | |||
| c3a9a52b7f | |||
| bcb004af21 | |||
| ac675e7d74 | |||
| bf89eff5e7 | |||
| 183787fa0c | |||
| 15aa04a5f7 | |||
| 79343a5d52 | |||
| 61e252918e | |||
| e98fa7f69a | |||
| 6d148a35eb | |||
| 0bbc1c35de | |||
| 47097969a0 | |||
| 13f529e064 | |||
| 8fc8422fbc |
+3
-2
@@ -1,5 +1,6 @@
|
|||||||
node_modules
|
node_modules
|
||||||
.git
|
.git
|
||||||
.gitignore
|
|
||||||
dist
|
dist
|
||||||
data
|
/data
|
||||||
|
.env*
|
||||||
|
.nx
|
||||||
|
|||||||
+3
-3
@@ -1,13 +1,14 @@
|
|||||||
FROM node:22-slim AS base
|
FROM node:22-slim AS base
|
||||||
LABEL org.opencontainers.image.source="https://github.com/docmost/docmost"
|
LABEL org.opencontainers.image.source="https://github.com/docmost/docmost"
|
||||||
|
|
||||||
|
RUN npm install -g pnpm@10.4.0
|
||||||
|
|
||||||
FROM base AS builder
|
FROM base AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
RUN npm install -g pnpm@10.4.0
|
|
||||||
RUN pnpm install --frozen-lockfile
|
RUN pnpm install --frozen-lockfile
|
||||||
RUN pnpm build
|
RUN pnpm build
|
||||||
|
|
||||||
@@ -31,12 +32,11 @@ COPY --from=builder /app/packages/editor-ext/package.json /app/packages/editor-e
|
|||||||
# Copy root package files
|
# Copy root package files
|
||||||
COPY --from=builder /app/package.json /app/package.json
|
COPY --from=builder /app/package.json /app/package.json
|
||||||
COPY --from=builder /app/pnpm*.yaml /app/
|
COPY --from=builder /app/pnpm*.yaml /app/
|
||||||
|
COPY --from=builder /app/.npmrc /app/.npmrc
|
||||||
|
|
||||||
# Copy patches
|
# Copy patches
|
||||||
COPY --from=builder /app/patches /app/patches
|
COPY --from=builder /app/patches /app/patches
|
||||||
|
|
||||||
RUN npm install -g pnpm@10.4.0
|
|
||||||
|
|
||||||
RUN chown -R node:node /app
|
RUN chown -R node:node /app
|
||||||
|
|
||||||
USER node
|
USER node
|
||||||
|
|||||||
+21
-22
@@ -10,51 +10,50 @@
|
|||||||
"format": "prettier --write \"src/**/*.tsx\" \"src/**/*.ts\""
|
"format": "prettier --write \"src/**/*.tsx\" \"src/**/*.ts\""
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@casl/ability": "^6.7.2",
|
|
||||||
"@casl/react": "^4.0.0",
|
"@casl/react": "^4.0.0",
|
||||||
"@docmost/editor-ext": "workspace:*",
|
"@docmost/editor-ext": "workspace:*",
|
||||||
"@emoji-mart/data": "^1.2.1",
|
"@emoji-mart/data": "^1.2.1",
|
||||||
"@emoji-mart/react": "^1.1.1",
|
"@emoji-mart/react": "^1.1.1",
|
||||||
"@excalidraw/excalidraw": "0.18.0-864353b",
|
"@excalidraw/excalidraw": "0.18.0-c158187",
|
||||||
"@mantine/core": "^8.1.3",
|
"@mantine/core": "^8.3.12",
|
||||||
"@mantine/dates": "^8.3.2",
|
"@mantine/dates": "^8.3.12",
|
||||||
"@mantine/form": "^8.1.3",
|
"@mantine/form": "^8.3.12",
|
||||||
"@mantine/hooks": "^8.1.3",
|
"@mantine/hooks": "^8.3.12",
|
||||||
"@mantine/modals": "^8.1.3",
|
"@mantine/modals": "^8.3.12",
|
||||||
"@mantine/notifications": "^8.1.3",
|
"@mantine/notifications": "^8.3.12",
|
||||||
"@mantine/spotlight": "^8.1.3",
|
"@mantine/spotlight": "^8.3.12",
|
||||||
"@tabler/icons-react": "^3.34.0",
|
"@tabler/icons-react": "^3.36.1",
|
||||||
"@tanstack/react-query": "^5.80.6",
|
"@tanstack/react-query": "^5.90.17",
|
||||||
"@tiptap/extension-character-count": "^2.10.3",
|
"@tiptap/extension-character-count": "^2.27.1",
|
||||||
"alfaaz": "^1.1.0",
|
"alfaaz": "^1.1.0",
|
||||||
"axios": "^1.13.2",
|
"axios": "^1.13.2",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"emoji-mart": "^5.6.0",
|
"emoji-mart": "^5.6.0",
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"highlightjs-sap-abap": "^0.3.0",
|
"highlightjs-sap-abap": "^0.3.0",
|
||||||
"i18next": "^23.14.0",
|
"i18next": "^23.16.8",
|
||||||
"i18next-http-backend": "^2.6.1",
|
"i18next-http-backend": "^2.7.3",
|
||||||
"jotai": "^2.12.5",
|
"jotai": "^2.16.2",
|
||||||
"jotai-optics": "^0.4.0",
|
"jotai-optics": "^0.4.0",
|
||||||
"js-cookie": "^3.0.5",
|
"js-cookie": "^3.0.5",
|
||||||
"jwt-decode": "^4.0.0",
|
"jwt-decode": "^4.0.0",
|
||||||
"katex": "0.16.22",
|
"katex": "0.16.27",
|
||||||
"lowlight": "^3.3.0",
|
"lowlight": "^3.3.0",
|
||||||
"mantine-form-zod-resolver": "^1.3.0",
|
"mantine-form-zod-resolver": "^1.3.0",
|
||||||
"mermaid": "^11.11.0",
|
"mermaid": "^11.12.2",
|
||||||
"mitt": "^3.0.1",
|
"mitt": "^3.0.1",
|
||||||
"posthog-js": "^1.255.1",
|
"posthog-js": "^1.255.1",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-arborist": "3.4.0",
|
"react-arborist": "3.4.0",
|
||||||
"react-clear-modal": "^2.0.15",
|
"react-clear-modal": "^2.0.17",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-drawio": "^1.0.1",
|
"react-drawio": "^1.0.7",
|
||||||
"react-error-boundary": "^4.1.2",
|
"react-error-boundary": "^4.1.2",
|
||||||
"react-helmet-async": "^2.0.5",
|
"react-helmet-async": "^2.0.5",
|
||||||
"react-i18next": "^15.0.1",
|
"react-i18next": "^15.0.1",
|
||||||
"react-router-dom": "^7.0.1",
|
"react-router-dom": "^7.12.0",
|
||||||
"semver": "^7.7.2",
|
"semver": "^7.7.3",
|
||||||
"socket.io-client": "^4.8.1",
|
"socket.io-client": "^4.8.3",
|
||||||
"tippy.js": "^6.3.7",
|
"tippy.js": "^6.3.7",
|
||||||
"tiptap-extension-global-drag-handle": "^0.1.18",
|
"tiptap-extension-global-drag-handle": "^0.1.18",
|
||||||
"zod": "^3.25.76"
|
"zod": "^3.25.76"
|
||||||
|
|||||||
@@ -13,21 +13,21 @@
|
|||||||
"Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.": "このユーザをグループから削除してもよろしいですか? ユーザはこのグループがアクセス権を持つリソースにアクセスできなくなります。",
|
"Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.": "このユーザをグループから削除してもよろしいですか? ユーザはこのグループがアクセス権を持つリソースにアクセスできなくなります。",
|
||||||
"Are you sure you want to remove this user from the space? The user will lose all access to this space.": "このユーザをスペースから削除してもよろしいですか? ユーザはこのスペースへのアクセス権をすべて失います。",
|
"Are you sure you want to remove this user from the space? The user will lose all access to this space.": "このユーザをスペースから削除してもよろしいですか? ユーザはこのスペースへのアクセス権をすべて失います。",
|
||||||
"Are you sure you want to restore this version? Any changes not versioned will be lost.": "このバージョンを復元してもよろしいですか? バージョン管理されていない変更は失われます。",
|
"Are you sure you want to restore this version? Any changes not versioned will be lost.": "このバージョンを復元してもよろしいですか? バージョン管理されていない変更は失われます。",
|
||||||
"Can become members of groups and spaces in workspace": "ワークスペース内のグループやスペースのメンバーになることができます",
|
"Can become members of groups and spaces in workspace": "ワークスペース内のグループやスペースのメンバーになれます",
|
||||||
"Can create and edit pages in space.": "スペース内のページを作成および編集できます。",
|
"Can create and edit pages in space.": "スペース内のページを作成・編集できます",
|
||||||
"Can edit": "編集可能",
|
"Can edit": "編集可能",
|
||||||
"Can manage workspace": "ワークスペースを管理できます",
|
"Can manage workspace": "ワークスペースを管理できます",
|
||||||
"Can manage workspace but cannot delete it": "ワークスペースを管理できますが、削除はできません",
|
"Can manage workspace but cannot delete it": "ワークスペースを管理できますが削除はできません",
|
||||||
"Can view": "閲覧可能",
|
"Can view": "閲覧可能",
|
||||||
"Can view pages in space but not edit.": "スペース内のページを閲覧できますが、編集はできません。",
|
"Can view pages in space but not edit.": "スペース内のページを閲覧できますが編集はできません",
|
||||||
"Cancel": "キャンセル",
|
"Cancel": "キャンセル",
|
||||||
"Change email": "メールアドレスの変更",
|
"Change email": "メールアドレスの変更",
|
||||||
"Change password": "パスワードの変更",
|
"Change password": "パスワードの変更",
|
||||||
"Change photo": "画像の変更",
|
"Change photo": "画像の変更",
|
||||||
"Choose a role": "ロールを選んでください",
|
"Choose a role": "ロールを選んでください",
|
||||||
"Choose your preferred color scheme.": "お好みのカラースキームを選択してください。",
|
"Choose your preferred color scheme.": "お好みのカラースキームを選択してください",
|
||||||
"Choose your preferred interface language.": "お好みのインターフェース言語を選択してください。",
|
"Choose your preferred interface language.": "お好みの言語を選択してください",
|
||||||
"Choose your preferred page width.": "左右の余白を縮小する場合はオンにしてください。",
|
"Choose your preferred page width.": "お好みのページ幅を選択してください",
|
||||||
"Confirm": "確認",
|
"Confirm": "確認",
|
||||||
"Copy link": "リンクをコピー",
|
"Copy link": "リンクをコピー",
|
||||||
"Create": "新規作成",
|
"Create": "新規作成",
|
||||||
@@ -40,24 +40,24 @@
|
|||||||
"Date": "日付",
|
"Date": "日付",
|
||||||
"Delete": "削除",
|
"Delete": "削除",
|
||||||
"Delete group": "グループを削除",
|
"Delete group": "グループを削除",
|
||||||
"Are you sure you want to delete this page? This will delete its children and page history. This action is irreversible.": "このページを削除してもよろしいですか?この操作により、子ページおよびページ履歴が削除されます。この操作は元に戻せません。",
|
"Are you sure you want to delete this page? This will delete its children and page history. This action is irreversible.": "このページを削除してもよろしいですか?子ページとページ履歴も削除されます。この操作は取り消せません。",
|
||||||
"Description": "説明",
|
"Description": "説明",
|
||||||
"Details": "詳細",
|
"Details": "詳細",
|
||||||
"e.g ACME": "例: 山田太郎",
|
"e.g ACME": "例: 山田太郎",
|
||||||
"e.g ACME Inc": "例: 株式会社サンプル",
|
"e.g ACME Inc": "例: 株式会社サンプル",
|
||||||
"e.g Developers": "例: エンジニア",
|
"e.g Developers": "例: エンジニア",
|
||||||
"e.g Group for developers": "例: エンジニアグループ",
|
"e.g Group for developers": "例: 開発チーム",
|
||||||
"e.g product": "例: product",
|
"e.g product": "例: product",
|
||||||
"e.g Product Team": "例: 製品チーム",
|
"e.g Product Team": "例: プロダクトチーム",
|
||||||
"e.g Sales": "例: 営業",
|
"e.g Sales": "例: 営業部",
|
||||||
"e.g Space for product team": "例: 製品チームのスペース",
|
"e.g Space for product team": "例: プロダクトチーム用スペース",
|
||||||
"e.g Space for sales team to collaborate": "例: 営業チーム連携用スペース",
|
"e.g Space for sales team to collaborate": "例: 営業チーム用スペース",
|
||||||
"Edit": "編集",
|
"Edit": "編集",
|
||||||
"Read": "読む",
|
"Read": "閲覧",
|
||||||
"Edit group": "グループを編集",
|
"Edit group": "グループを編集",
|
||||||
"Email": "メールアドレス",
|
"Email": "メールアドレス",
|
||||||
"Enter a strong password": "強力なパスワードを入力してください",
|
"Enter a strong password": "強力なパスワードを入力してください",
|
||||||
"Enter valid email addresses separated by comma or space max_50": "有効なメールアドレスをカンマまたはスペースで区切って入力してください(最大 50 個)",
|
"Enter valid email addresses separated by comma or space max_50": "メールアドレスをカンマまたはスペース区切りで入力(最大50件)",
|
||||||
"enter valid emails addresses": "有効なメールアドレスを入力してください",
|
"enter valid emails addresses": "有効なメールアドレスを入力してください",
|
||||||
"Enter your current password": "現在のパスワードを入力してください",
|
"Enter your current password": "現在のパスワードを入力してください",
|
||||||
"enter your full name": "氏名を入力してください",
|
"enter your full name": "氏名を入力してください",
|
||||||
@@ -81,18 +81,18 @@
|
|||||||
"Group description": "グループ説明",
|
"Group description": "グループ説明",
|
||||||
"Group name": "グループ名",
|
"Group name": "グループ名",
|
||||||
"Groups": "グループ",
|
"Groups": "グループ",
|
||||||
"Has full access to space settings and pages.": "スペース設定とページにフルアクセスできます。",
|
"Has full access to space settings and pages.": "スペース設定とページにフルアクセスできます",
|
||||||
"Home": "ホーム",
|
"Home": "ホーム",
|
||||||
"Import pages": "ページをインポート",
|
"Import pages": "ページをインポート",
|
||||||
"Import pages & space settings": "ページとスペース設定をインポート",
|
"Import pages & space settings": "ページとスペース設定をインポート",
|
||||||
"Importing pages": "ページをインポートしています",
|
"Importing pages": "ページをインポートしています",
|
||||||
"invalid invitation link": "招待リンクが間違っています",
|
"invalid invitation link": "無効な招待リンクです",
|
||||||
"Invitation signup": "招待登録",
|
"Invitation signup": "招待登録",
|
||||||
"Invite by email": "メールアドレスで招待する",
|
"Invite by email": "メールアドレスで招待する",
|
||||||
"Invite members": "メンバーを招待する",
|
"Invite members": "メンバーを招待する",
|
||||||
"Invite new members": "新しいメンバーを招待する",
|
"Invite new members": "新しいメンバーを招待する",
|
||||||
"Invited members who are yet to accept their invitation will appear here.": "招待をまだ承諾していないメンバーはここに表示されます。",
|
"Invited members who are yet to accept their invitation will appear here.": "招待を承諾していないメンバーがここに表示されます",
|
||||||
"Invited members will be granted access to spaces the groups can access": "招待されたメンバーは、グループがアクセスできるスペースにアクセス権が付与されます",
|
"Invited members will be granted access to spaces the groups can access": "招待されたメンバーはグループがアクセスできるスペースにアクセスできます",
|
||||||
"Join the workspace": "ワークスペースに参加",
|
"Join the workspace": "ワークスペースに参加",
|
||||||
"Language": "言語",
|
"Language": "言語",
|
||||||
"Light": "ライト",
|
"Light": "ライト",
|
||||||
@@ -113,20 +113,20 @@
|
|||||||
"New page": "新規ページ",
|
"New page": "新規ページ",
|
||||||
"New password": "新しいパスワード",
|
"New password": "新しいパスワード",
|
||||||
"No group found": "グループが見つかりません",
|
"No group found": "グループが見つかりません",
|
||||||
"No page history saved yet.": "まだページの履歴が保存されていません。",
|
"No page history saved yet.": "ページ履歴がありません",
|
||||||
"No pages yet": "ページがありません",
|
"No pages yet": "ページがありません",
|
||||||
"No results found...": "結果が見つかりませんでした...",
|
"No results found...": "結果が見つかりません",
|
||||||
"No user found": "ユーザがいません",
|
"No user found": "ユーザーが見つかりません",
|
||||||
"Overview": "概要",
|
"Overview": "概要",
|
||||||
"Owner": "所有者",
|
"Owner": "所有者",
|
||||||
"page": "ページ",
|
"page": "ページ",
|
||||||
"Page deleted successfully": "ページが正常に削除されました",
|
"Page deleted successfully": "ページを削除しました",
|
||||||
"Page history": "ページの履歴",
|
"Page history": "ページ履歴",
|
||||||
"Page import is in progress. Please do not close this tab.": "ページのインポートが進行中です。このタブを閉じないでください。",
|
"Page import is in progress. Please do not close this tab.": "ページをインポート中です。このタブを閉じないでください",
|
||||||
"Pages": "ページ",
|
"Pages": "ページ",
|
||||||
"pages": "ページ",
|
"pages": "ページ",
|
||||||
"Password": "パスワード",
|
"Password": "パスワード",
|
||||||
"Password changed successfully": "パスワードが正常に変更されました",
|
"Password changed successfully": "パスワードを変更しました",
|
||||||
"Pending": "保留中",
|
"Pending": "保留中",
|
||||||
"Please confirm your action": "アクションを確認してください",
|
"Please confirm your action": "アクションを確認してください",
|
||||||
"Preferences": "設定",
|
"Preferences": "設定",
|
||||||
@@ -143,95 +143,95 @@
|
|||||||
"Search for groups": "グループを検索",
|
"Search for groups": "グループを検索",
|
||||||
"Search for users": "ユーザーを検索",
|
"Search for users": "ユーザーを検索",
|
||||||
"Search for users and groups": "ユーザーとグループを検索",
|
"Search for users and groups": "ユーザーとグループを検索",
|
||||||
"Search...": "検索する語句を入力",
|
"Search...": "検索",
|
||||||
"Select language": "言語を選択",
|
"Select language": "言語を選択",
|
||||||
"Select role": "ロールを選択",
|
"Select role": "ロールを選択",
|
||||||
"Select role to assign to all invited members": "招待されたすべてのメンバーに割り当てるロールを選択してください",
|
"Select role to assign to all invited members": "招待するメンバーに割り当てるロールを選択",
|
||||||
"Select theme": "テーマを選択",
|
"Select theme": "テーマを選択",
|
||||||
"Send invitation": "招待を送る",
|
"Send invitation": "招待を送る",
|
||||||
"Invitation sent": "招待が送信されました",
|
"Invitation sent": "招待を送信しました",
|
||||||
"Settings": "設定",
|
"Settings": "設定",
|
||||||
"Setup workspace": "ワークスペースを設定する",
|
"Setup workspace": "ワークスペースを設定する",
|
||||||
"Sign In": "サインイン",
|
"Sign In": "サインイン",
|
||||||
"Sign Up": "アカウント登録",
|
"Sign Up": "新規登録",
|
||||||
"Slug": "Slug (URL用文字列)",
|
"Slug": "スラッグ(URL識別子)",
|
||||||
"Space": "スペース",
|
"Space": "スペース",
|
||||||
"Space description": "スペース説明",
|
"Space description": "スペース説明",
|
||||||
"Space menu": "スペースメニュー",
|
"Space menu": "スペースメニュー",
|
||||||
"Space name": "スペース名",
|
"Space name": "スペース名",
|
||||||
"Space settings": "スペース設定",
|
"Space settings": "スペース設定",
|
||||||
"Space slug": "スペースのSlug (URL用文字列)",
|
"Space slug": "スペースのスラッグ(URL識別子)",
|
||||||
"Spaces": "スペース",
|
"Spaces": "スペース",
|
||||||
"Spaces you belong to": "所属しているスペース",
|
"Spaces you belong to": "所属しているスペース",
|
||||||
"No space found": "スペースが見つかりません",
|
"No space found": "スペースが見つかりません",
|
||||||
"Search for spaces": "スペースを検索",
|
"Search for spaces": "スペースを検索",
|
||||||
"Start typing to search...": "検索を開始するには入力してください...",
|
"Start typing to search...": "入力して検索",
|
||||||
"Status": "ステータス",
|
"Status": "ステータス",
|
||||||
"Successfully imported": "インポートに成功しました",
|
"Successfully imported": "インポートしました",
|
||||||
"Successfully restored": "正常に復元されました",
|
"Successfully restored": "復元しました",
|
||||||
"System settings": "システム設定",
|
"System settings": "システム設定",
|
||||||
"Theme": "テーマ",
|
"Theme": "テーマ",
|
||||||
"To change your email, you have to enter your password and new email.": "メールアドレスを変更するには、パスワードと新しいメールアドレスを入力する必要があります。",
|
"To change your email, you have to enter your password and new email.": "メールアドレスを変更するには、パスワードと新しいメールアドレスを入力してください",
|
||||||
"Toggle full page width": "ページ幅を切り替える",
|
"Toggle full page width": "ページ幅を切り替え",
|
||||||
"Unable to import pages. Please try again.": "ページをインポートできません。もう一度お試しください。",
|
"Unable to import pages. Please try again.": "ページをインポートできませんでした。もう一度お試しください",
|
||||||
"untitled": "無題",
|
"untitled": "無題",
|
||||||
"Untitled": "無題",
|
"Untitled": "無題",
|
||||||
"Updated successfully": "正常に更新されました",
|
"Updated successfully": "更新しました",
|
||||||
"User": "ユーザー",
|
"User": "ユーザー",
|
||||||
"Workspace": "ワークスペース",
|
"Workspace": "ワークスペース",
|
||||||
"Workspace Name": "ワークスペース名",
|
"Workspace Name": "ワークスペース名",
|
||||||
"Workspace settings": "ワークスペース設定",
|
"Workspace settings": "ワークスペース設定",
|
||||||
"You can change your password here.": "パスワードを変更できます。",
|
"You can change your password here.": "パスワードを変更できます",
|
||||||
"Your Email": "メールアドレス",
|
"Your Email": "メールアドレス",
|
||||||
"Your import is complete.": "インポートが完了しました。",
|
"Your import is complete.": "インポートが完了しました",
|
||||||
"Your name": "名前",
|
"Your name": "名前",
|
||||||
"Your Name": "名前",
|
"Your Name": "名前",
|
||||||
"Your password": "パスワード",
|
"Your password": "パスワード",
|
||||||
"Your password must be a minimum of 8 characters.": "パスワードは最低 8 文字必要です。",
|
"Your password must be a minimum of 8 characters.": "パスワードは8文字以上にしてください",
|
||||||
"Sidebar toggle": "サイドバー切り替え",
|
"Sidebar toggle": "サイドバー切り替え",
|
||||||
"Comments": "コメント",
|
"Comments": "コメント",
|
||||||
"404 page not found": "404 ページが見つかりません",
|
"404 page not found": "404 ページが見つかりません",
|
||||||
"Sorry, we can't find the page you are looking for.": "お探しのページが見つかりません。",
|
"Sorry, we can't find the page you are looking for.": "お探しのページが見つかりません",
|
||||||
"Take me back to homepage": "ホームに戻る",
|
"Take me back to homepage": "ホームに戻る",
|
||||||
"Forgot password": "パスワードを忘れた",
|
"Forgot password": "パスワードを忘れた",
|
||||||
"Forgot your password?": "パスワードを忘れましたか?",
|
"Forgot your password?": "パスワードを忘れましたか?",
|
||||||
"A password reset link has been sent to your email. Please check your inbox.": "パスワードリセットリンクがあなたのメールアドレスに送信されました。受信箱を確認してください。",
|
"A password reset link has been sent to your email. Please check your inbox.": "パスワードリセット用のリンクをメールに送信しました。受信トレイを確認してください",
|
||||||
"Send reset link": "リセットリンクを送る",
|
"Send reset link": "リセットリンクを送信",
|
||||||
"Password reset": "パスワードリセット",
|
"Password reset": "パスワードリセット",
|
||||||
"Your new password": "新しいパスワード",
|
"Your new password": "新しいパスワード",
|
||||||
"Set password": "パスワードを設定",
|
"Set password": "パスワードを設定",
|
||||||
"Write a comment": "コメントを書く",
|
"Write a comment": "コメントを書く",
|
||||||
"Reply...": "返信...",
|
"Reply...": "返信...",
|
||||||
"Error loading comments.": "コメントの読み込み中にエラーが発生しました。",
|
"Error loading comments.": "コメントの読み込みに失敗しました",
|
||||||
"No comments yet.": "コメントがありません。",
|
"No comments yet.": "コメントがありません",
|
||||||
"Edit comment": "コメントを編集する",
|
"Edit comment": "コメントを編集する",
|
||||||
"Delete comment": "コメントを削除する",
|
"Delete comment": "コメントを削除する",
|
||||||
"Are you sure you want to delete this comment?": "このコメントを削除してもよろしいですか?",
|
"Are you sure you want to delete this comment?": "このコメントを削除してもよろしいですか?",
|
||||||
"Comment created successfully": "コメントが作成されました",
|
"Comment created successfully": "コメントを作成しました",
|
||||||
"Error creating comment": "コメントの作成中にエラーが発生しました",
|
"Error creating comment": "コメントの作成に失敗しました",
|
||||||
"Comment updated successfully": "コメントが更新されました",
|
"Comment updated successfully": "コメントを更新しました",
|
||||||
"Failed to update comment": "コメントの更新に失敗しました",
|
"Failed to update comment": "コメントの更新に失敗しました",
|
||||||
"Comment deleted successfully": "コメントが削除されました",
|
"Comment deleted successfully": "コメントを削除しました",
|
||||||
"Failed to delete comment": "コメントの削除に失敗しました",
|
"Failed to delete comment": "コメントの削除に失敗しました",
|
||||||
"Comment resolved successfully": "コメントが解決されました",
|
"Comment resolved successfully": "コメントを解決しました",
|
||||||
"Comment re-opened successfully": "コメントが再開されました",
|
"Comment re-opened successfully": "コメントを再開しました",
|
||||||
"Comment unresolved successfully": "コメントが再解決されました",
|
"Comment unresolved successfully": "コメントを未解決に戻しました",
|
||||||
"Failed to resolve comment": "コメントの解決に失敗しました",
|
"Failed to resolve comment": "コメントの解決に失敗しました",
|
||||||
"Resolve comment": "コメントを解決",
|
"Resolve comment": "コメントを解決",
|
||||||
"Unresolve comment": "コメントを再解決",
|
"Unresolve comment": "コメントを未解決に戻す",
|
||||||
"Resolve Comment Thread": "コメントスレッドを解決",
|
"Resolve Comment Thread": "コメントスレッドを解決",
|
||||||
"Unresolve Comment Thread": "コメントスレッドを再解決",
|
"Unresolve Comment Thread": "コメントスレッドを未解決に戻す",
|
||||||
"Are you sure you want to resolve this comment thread? This will mark it as completed.": "このコメントスレッドを解決しますか? これにより完了としてマークされます。",
|
"Are you sure you want to resolve this comment thread? This will mark it as completed.": "このコメントスレッドを解決しますか?完了としてマークされます",
|
||||||
"Are you sure you want to unresolve this comment thread?": "このコメントスレッドを再解決しますか?",
|
"Are you sure you want to unresolve this comment thread?": "このコメントスレッドを未解決に戻しますか?",
|
||||||
"Resolved": "解決済",
|
"Resolved": "解決済",
|
||||||
"No active comments.": "アクティブなコメントはありません。",
|
"No active comments.": "アクティブなコメントはありません",
|
||||||
"No resolved comments.": "解決されたコメントはありません。",
|
"No resolved comments.": "解決済みのコメントはありません",
|
||||||
"Revoke invitation": "招待を取り消す",
|
"Revoke invitation": "招待を取り消す",
|
||||||
"Revoke": "取り消す",
|
"Revoke": "取り消す",
|
||||||
"Don't": "取り消さない",
|
"Don't": "取り消さない",
|
||||||
"Are you sure you want to revoke this invitation? The user will not be able to join the workspace.": "この招待を取り消してもよろしいですか? ユーザはワークスペースに参加できなくなります。",
|
"Are you sure you want to revoke this invitation? The user will not be able to join the workspace.": "この招待を取り消してもよろしいですか?ユーザーはワークスペースに参加できなくなります",
|
||||||
"Resend invitation": "招待を再度送る",
|
"Resend invitation": "招待を再度送る",
|
||||||
"Anyone with this link can join this workspace.": "このリンクを持っている人は誰でもこのワークスペースに参加できます。",
|
"Anyone with this link can join this workspace.": "このリンクを知っている人は誰でもワークスペースに参加できます",
|
||||||
"Invite link": "招待リンク",
|
"Invite link": "招待リンク",
|
||||||
"Copy": "コピー",
|
"Copy": "コピー",
|
||||||
"Copy to space": "スペースにコピー",
|
"Copy to space": "スペースにコピー",
|
||||||
@@ -239,13 +239,13 @@
|
|||||||
"Duplicate": "複製",
|
"Duplicate": "複製",
|
||||||
"Select a user": "ユーザを選択",
|
"Select a user": "ユーザを選択",
|
||||||
"Select a group": "グループを選択",
|
"Select a group": "グループを選択",
|
||||||
"Export all pages and attachments in this space.": "このスペースのすべてのページと添付ファイルをエクスポートします。",
|
"Export all pages and attachments in this space.": "このスペースのすべてのページと添付ファイルをエクスポートします",
|
||||||
"Delete space": "スペースを削除",
|
"Delete space": "スペースを削除",
|
||||||
"Are you sure you want to delete this space?": "このスペースを削除してもよろしいですか?",
|
"Are you sure you want to delete this space?": "このスペースを削除してもよろしいですか?",
|
||||||
"Delete this space with all its pages and data.": "このスペースおよびスペース内のすべてのページとデータを削除します。",
|
"Delete this space with all its pages and data.": "このスペースとすべてのページ、データを削除します",
|
||||||
"All pages, comments, attachments and permissions in this space will be deleted irreversibly.": "このスペース内のすべてのページ、コメント、添付ファイル、および権限は完全に削除されます。",
|
"All pages, comments, attachments and permissions in this space will be deleted irreversibly.": "スペース内のすべてのページ、コメント、添付ファイル、権限が完全に削除されます",
|
||||||
"Confirm space name": "スペース名を確認する",
|
"Confirm space name": "スペース名を確認する",
|
||||||
"Type the space name <b>{{spaceName}}</b> to confirm your action.": "アクションを確認するためにスペース名 <b>{{spaceName}}</b> を入力してください。",
|
"Type the space name <b>{{spaceName}}</b> to confirm your action.": "確認のためスペース名 <b>{{spaceName}}</b> を入力してください",
|
||||||
"Format": "フォーマット",
|
"Format": "フォーマット",
|
||||||
"Include subpages": "サブページを含める",
|
"Include subpages": "サブページを含める",
|
||||||
"Include attachments": "添付ファイルを含める",
|
"Include attachments": "添付ファイルを含める",
|
||||||
@@ -273,12 +273,12 @@
|
|||||||
"Success": "成功",
|
"Success": "成功",
|
||||||
"Warning": "警告",
|
"Warning": "警告",
|
||||||
"Danger": "危険",
|
"Danger": "危険",
|
||||||
"Mermaid diagram error:": "Mermaid コードエラー",
|
"Mermaid diagram error:": "Mermaid ダイアグラムエラー:",
|
||||||
"Invalid Mermaid diagram": "無効な Mermaid コードです",
|
"Invalid Mermaid diagram": "無効な Mermaid ダイアグラムです",
|
||||||
"Double-click to edit Draw.io diagram": "ダブルクリックしてDraw.ioの図を編集",
|
"Double-click to edit Draw.io diagram": "ダブルクリックして Draw.io 図を編集",
|
||||||
"Exit": "終了",
|
"Exit": "終了",
|
||||||
"Save & Exit": "保存して終了",
|
"Save & Exit": "保存して終了",
|
||||||
"Double-click to edit Excalidraw diagram": "ダブルクリックしてExcalidraw図を編集",
|
"Double-click to edit Excalidraw diagram": "ダブルクリックして Excalidraw 図を編集",
|
||||||
"Paste link": "リンクを貼り付け",
|
"Paste link": "リンクを貼り付け",
|
||||||
"Edit link": "リンクを編集",
|
"Edit link": "リンクを編集",
|
||||||
"Remove link": "リンクを削除",
|
"Remove link": "リンクを削除",
|
||||||
@@ -315,22 +315,22 @@
|
|||||||
"Bullet List": "箇条書きリスト",
|
"Bullet List": "箇条書きリスト",
|
||||||
"Numbered List": "番号付きリスト",
|
"Numbered List": "番号付きリスト",
|
||||||
"Blockquote": "引用",
|
"Blockquote": "引用",
|
||||||
"Just start typing with plain text.": "すぐに文章を書き始められます。",
|
"Just start typing with plain text.": "プレーンテキストを入力します",
|
||||||
"Track tasks with a to-do list.": "Todoリストでタスクを追跡します。",
|
"Track tasks with a to-do list.": "Todo リストでタスクを管理します",
|
||||||
"Big section heading.": "大きいフォントのセクション見出しです。",
|
"Big section heading.": "大見出し",
|
||||||
"Medium section heading.": "中くらいのフォントのセクション見出しです。",
|
"Medium section heading.": "中見出し",
|
||||||
"Small section heading.": "小さいフォントのセクション見出しです。",
|
"Small section heading.": "小見出し",
|
||||||
"Create a simple bullet list.": "シンプルな箇条書きのリストを作成します。",
|
"Create a simple bullet list.": "箇条書きリストを作成します",
|
||||||
"Create a list with numbering.": "番号付きのリストを作成します。",
|
"Create a list with numbering.": "番号付きリストを作成します",
|
||||||
"Create block quote.": "引用文を作成します。",
|
"Create block quote.": "引用ブロックを作成します",
|
||||||
"Insert code snippet.": "コードスニペットを入力します。",
|
"Insert code snippet.": "コードスニペットを挿入します",
|
||||||
"Insert horizontal rule divider": "水平線を挿入します。",
|
"Insert horizontal rule divider": "区切り線を挿入します",
|
||||||
"Upload any image from your device.": "画像をアップロードします。",
|
"Upload any image from your device.": "デバイスから画像をアップロードします",
|
||||||
"Upload any video from your device.": "動画をアップロードします。",
|
"Upload any video from your device.": "デバイスから動画をアップロードします",
|
||||||
"Upload any file from your device.": "ファイルをアップロードします。",
|
"Upload any file from your device.": "デバイスからファイルをアップロードします",
|
||||||
"Table": "テーブル",
|
"Table": "テーブル",
|
||||||
"Insert a table.": "表を挿入します。",
|
"Insert a table.": "テーブルを挿入します",
|
||||||
"Insert collapsible block.": "折りたたみ可能なブロックを挿入します。",
|
"Insert collapsible block.": "折りたたみブロックを挿入します",
|
||||||
"Video": "動画",
|
"Video": "動画",
|
||||||
"Divider": "区切り線",
|
"Divider": "区切り線",
|
||||||
"Quote": "引用",
|
"Quote": "引用",
|
||||||
@@ -338,16 +338,16 @@
|
|||||||
"File attachment": "ファイル添付",
|
"File attachment": "ファイル添付",
|
||||||
"Toggle block": "ブロックを切り替える",
|
"Toggle block": "ブロックを切り替える",
|
||||||
"Callout": "コールアウト",
|
"Callout": "コールアウト",
|
||||||
"Insert callout notice.": "コールアウトブロックを挿入します。",
|
"Insert callout notice.": "コールアウトを挿入します",
|
||||||
"Math inline": "インライン数式",
|
"Math inline": "インライン数式",
|
||||||
"Insert inline math equation.": "インライン数式を挿入します。",
|
"Insert inline math equation.": "インライン数式を挿入します",
|
||||||
"Math block": "数式ブロック",
|
"Math block": "数式ブロック",
|
||||||
"Insert math equation": "数式を挿入します",
|
"Insert math equation": "数式を挿入します",
|
||||||
"Mermaid diagram": "Mermaidコード",
|
"Mermaid diagram": "Mermaid ダイアグラム",
|
||||||
"Insert mermaid diagram": "Mermaidコードを記述して図を挿入します",
|
"Insert mermaid diagram": "Mermaid ダイアグラムを挿入します",
|
||||||
"Insert and design Drawio diagrams": "Drawioの図を挿入してデザインします",
|
"Insert and design Drawio diagrams": "Draw.io 図を挿入・編集します",
|
||||||
"Insert current date": "今日の日付を挿入します",
|
"Insert current date": "現在の日付を挿入します",
|
||||||
"Draw and sketch excalidraw diagrams": "Excalidrawの図を埋め込みます",
|
"Draw and sketch excalidraw diagrams": "Excalidraw 図を挿入します",
|
||||||
"Multiple": "複数",
|
"Multiple": "複数",
|
||||||
"Heading {{level}}": "見出し {{level}}",
|
"Heading {{level}}": "見出し {{level}}",
|
||||||
"Toggle title": "タイトルの表示/非表示を切り替える",
|
"Toggle title": "タイトルの表示/非表示を切り替える",
|
||||||
@@ -357,29 +357,29 @@
|
|||||||
"Yesterday, {{time}}": "昨日、{{time}}",
|
"Yesterday, {{time}}": "昨日、{{time}}",
|
||||||
"Space created successfully": "スペースを作成しました",
|
"Space created successfully": "スペースを作成しました",
|
||||||
"Space updated successfully": "スペースを更新しました",
|
"Space updated successfully": "スペースを更新しました",
|
||||||
"Space deleted successfully": "スペースが削除されました",
|
"Space deleted successfully": "スペースを削除しました",
|
||||||
"Members added successfully": "メンバーを追加しました",
|
"Members added successfully": "メンバーを追加しました",
|
||||||
"Member removed successfully": "メンバーが削除されました",
|
"Member removed successfully": "メンバーを削除しました",
|
||||||
"Member role updated successfully": "メンバーのロールを更新しました",
|
"Member role updated successfully": "メンバーのロールを更新しました",
|
||||||
"Created by: <b>{{creatorName}}</b>": "作成者: <b>{{creatorName}}</b>",
|
"Created by: <b>{{creatorName}}</b>": "作成者: <b>{{creatorName}}</b>",
|
||||||
"Created at: {{time}}": "が作成しました:{{time}}",
|
"Created at: {{time}}": "作成日: {{time}}",
|
||||||
"Edited by {{name}} {{time}}": "最終編集: {{name}} {{time}}",
|
"Edited by {{name}} {{time}}": "最終編集: {{name}} {{time}}",
|
||||||
"Word count: {{wordCount}}": "ワード数: {{wordCount}}",
|
"Word count: {{wordCount}}": "単語数: {{wordCount}}",
|
||||||
"Character count: {{characterCount}}": "文字数: {{characterCount}}",
|
"Character count: {{characterCount}}": "文字数: {{characterCount}}",
|
||||||
"New update": "新規更新",
|
"New update": "新規更新",
|
||||||
"{{latestVersion}} is available": "{{latestVersion}}は利用可能です",
|
"{{latestVersion}} is available": "{{latestVersion}} が利用可能です",
|
||||||
"Default page edit mode": "デフォルトのページ編集モード",
|
"Default page edit mode": "デフォルトのページ編集モード",
|
||||||
"Choose your preferred page edit mode. Avoid accidental edits.": "希望のページ編集モードを選択してください。誤って編集を防ぎます。",
|
"Choose your preferred page edit mode. Avoid accidental edits.": "お好みのページ編集モードを選択してください(誤編集を防止します)",
|
||||||
"Reading": "読み取り",
|
"Reading": "読み取り",
|
||||||
"Delete member": "メンバーを削除する",
|
"Delete member": "メンバーを削除する",
|
||||||
"Member deleted successfully": "メンバーが削除されました",
|
"Member deleted successfully": "メンバーを削除しました",
|
||||||
"Are you sure you want to delete this workspace member? This action is irreversible.": "ワークスペースメンバーを削除してもよろしいですか?この操作は元に戻せません。",
|
"Are you sure you want to delete this workspace member? This action is irreversible.": "このメンバーを削除してもよろしいですか?この操作は取り消せません",
|
||||||
"Move": "移動",
|
"Move": "移動",
|
||||||
"Move page": "ページを移動",
|
"Move page": "ページを移動",
|
||||||
"Move page to a different space.": "ページを別のスペースに移動します。",
|
"Move page to a different space.": "ページを別のスペースに移動します",
|
||||||
"Real-time editor connection lost. Retrying...": "リアルタイムエディターの接続が失われました。再試行しています…",
|
"Real-time editor connection lost. Retrying...": "リアルタイム編集の接続が切断されました。再接続中...",
|
||||||
"Table of contents": "目次",
|
"Table of contents": "目次",
|
||||||
"Add headings (H1, H2, H3) to generate a table of contents.": "見出し(H1、H2、H3)を追加して目次を生成します。",
|
"Add headings (H1, H2, H3) to generate a table of contents.": "見出し(H1、H2、H3)を追加すると目次が生成されます",
|
||||||
"Share": "共有",
|
"Share": "共有",
|
||||||
"Public sharing": "公開共有",
|
"Public sharing": "公開共有",
|
||||||
"Shared by": "共有者",
|
"Shared by": "共有者",
|
||||||
@@ -398,13 +398,13 @@
|
|||||||
"Delete share": "共有を削除",
|
"Delete share": "共有を削除",
|
||||||
"Are you sure you want to delete this shared link?": "この共有リンクを削除してもよろしいですか?",
|
"Are you sure you want to delete this shared link?": "この共有リンクを削除してもよろしいですか?",
|
||||||
"Publicly shared pages from spaces you are a member of will appear here": "メンバーであるスペースからの公開ページがここに表示されます",
|
"Publicly shared pages from spaces you are a member of will appear here": "メンバーであるスペースからの公開ページがここに表示されます",
|
||||||
"Share deleted successfully": "共有が正常に削除されました",
|
"Share deleted successfully": "共有を削除しました",
|
||||||
"Share not found": "共有が見つかりません",
|
"Share not found": "共有が見つかりません",
|
||||||
"Failed to share page": "ページの共有に失敗しました",
|
"Failed to share page": "ページの共有に失敗しました",
|
||||||
"Copy page": "ページをコピー",
|
"Copy page": "ページをコピー",
|
||||||
"Copy page to a different space.": "ページを別のスペースにコピーします。",
|
"Copy page to a different space.": "ページを別のスペースにコピーします",
|
||||||
"Page copied successfully": "ページのコピーに成功しました",
|
"Page copied successfully": "ページをコピーしました",
|
||||||
"Page duplicated successfully": "ページが正常に複製されました",
|
"Page duplicated successfully": "ページを複製しました",
|
||||||
"Find": "検索",
|
"Find": "検索",
|
||||||
"Not found": "見つかりません",
|
"Not found": "見つかりません",
|
||||||
"Previous Match (Shift+Enter)": "前の一致 (Shift+Enter)",
|
"Previous Match (Shift+Enter)": "前の一致 (Shift+Enter)",
|
||||||
@@ -419,26 +419,26 @@
|
|||||||
"Error": "エラー",
|
"Error": "エラー",
|
||||||
"Failed to disable MFA": "MFAの無効化に失敗しました",
|
"Failed to disable MFA": "MFAの無効化に失敗しました",
|
||||||
"Disable two-factor authentication": "二要素認証を無効化",
|
"Disable two-factor authentication": "二要素認証を無効化",
|
||||||
"Disabling two-factor authentication will make your account less secure. You'll only need your password to sign in.": "二要素認証を無効化すると、アカウントのセキュリティが低下します。サインインにはパスワードのみが必要になります。",
|
"Disabling two-factor authentication will make your account less secure. You'll only need your password to sign in.": "二要素認証を無効にすると、アカウントのセキュリティが低下します。サインインにはパスワードのみが必要になります",
|
||||||
"Please enter your password to disable two-factor authentication:": "二要素認証を無効化するにはパスワードを入力してください:",
|
"Please enter your password to disable two-factor authentication:": "二要素認証を無効にするにはパスワードを入力してください",
|
||||||
"Two-factor authentication has been enabled": "二要素認証が有効になりました",
|
"Two-factor authentication has been enabled": "二要素認証を有効にしました",
|
||||||
"Two-factor authentication has been disabled": "二要素認証が無効になりました",
|
"Two-factor authentication has been disabled": "二要素認証を無効にしました",
|
||||||
"2-step verification": "2段階確認",
|
"2-step verification": "2段階認証",
|
||||||
"Protect your account with an additional verification layer when signing in.": "サインイン時に追加の認証レイヤーでアカウントを保護します。",
|
"Protect your account with an additional verification layer when signing in.": "サインイン時に追加の認証でアカウントを保護します",
|
||||||
"Two-factor authentication is active on your account.": "二要素認証がアカウントで有効です。",
|
"Two-factor authentication is active on your account.": "二要素認証が有効です",
|
||||||
"Add 2FA method": "2FAメソッドを追加",
|
"Add 2FA method": "2FAメソッドを追加",
|
||||||
"Backup codes": "バックアップコード",
|
"Backup codes": "バックアップコード",
|
||||||
"Disable": "無効にする",
|
"Disable": "無効にする",
|
||||||
"Invalid verification code": "無効な認証コード",
|
"Invalid verification code": "無効な認証コード",
|
||||||
"New backup codes have been generated": "新しいバックアップコードが生成されました",
|
"New backup codes have been generated": "新しいバックアップコードを生成しました",
|
||||||
"Failed to regenerate backup codes": "バックアップコードの再生成に失敗しました",
|
"Failed to regenerate backup codes": "バックアップコードの再生成に失敗しました",
|
||||||
"About backup codes": "バックアップコードについて",
|
"About backup codes": "バックアップコードについて",
|
||||||
"Backup codes can be used to access your account if you lose access to your authenticator app. Each code can only be used once.": "バックアップコードは、認証アプリへのアクセスを失った場合にアカウントにアクセスするために使用できます。各コードは一度しか使用できません。",
|
"Backup codes can be used to access your account if you lose access to your authenticator app. Each code can only be used once.": "認証アプリにアクセスできない場合、バックアップコードでアカウントにアクセスできます。各コードは1回のみ使用可能です",
|
||||||
"You can regenerate new backup codes at any time. This will invalidate all existing codes.": "いつでも新しいバックアップコードを再生成できます。これにより、既存のすべてのコードが無効になります。",
|
"You can regenerate new backup codes at any time. This will invalidate all existing codes.": "新しいバックアップコードはいつでも再生成できます。既存のコードはすべて無効になります",
|
||||||
"Confirm password": "パスワードを確認",
|
"Confirm password": "パスワードを確認",
|
||||||
"Generate new backup codes": "新しいバックアップコードを生成",
|
"Generate new backup codes": "新しいバックアップコードを生成",
|
||||||
"Save your new backup codes": "新しいバックアップコードを保存",
|
"Save your new backup codes": "新しいバックアップコードを保存",
|
||||||
"Make sure to save these codes in a secure place. Your old backup codes are no longer valid.": "これらのコードを安全な場所に保存してください。古いバックアップコードは無効です。",
|
"Make sure to save these codes in a secure place. Your old backup codes are no longer valid.": "これらのコードを安全な場所に保存してください。古いバックアップコードは無効になりました",
|
||||||
"Your new backup codes": "新しいバックアップコード",
|
"Your new backup codes": "新しいバックアップコード",
|
||||||
"I've saved my backup codes": "バックアップコードを保存しました",
|
"I've saved my backup codes": "バックアップコードを保存しました",
|
||||||
"Failed to setup MFA": "MFAの設定に失敗しました",
|
"Failed to setup MFA": "MFAの設定に失敗しました",
|
||||||
@@ -449,51 +449,51 @@
|
|||||||
"Enter this code manually in your authenticator app:": "このコードを認証アプリに手動で入力してください:",
|
"Enter this code manually in your authenticator app:": "このコードを認証アプリに手動で入力してください:",
|
||||||
"2. Enter the 6-digit code from your authenticator": "2. 認証アプリからの6桁のコードを入力してください",
|
"2. Enter the 6-digit code from your authenticator": "2. 認証アプリからの6桁のコードを入力してください",
|
||||||
"Verify and enable": "確認と有効化",
|
"Verify and enable": "確認と有効化",
|
||||||
"Failed to generate QR code. Please try again.": "QRコードの生成に失敗しました。再試行してください。",
|
"Failed to generate QR code. Please try again.": "QRコードの生成に失敗しました。もう一度お試しください",
|
||||||
"Backup": "バックアップ",
|
"Backup": "バックアップ",
|
||||||
"Save codes": "コードを保存",
|
"Save codes": "コードを保存",
|
||||||
"Save your backup codes": "バックアップコードを保存",
|
"Save your backup codes": "バックアップコードを保存",
|
||||||
"These codes can be used to access your account if you lose access to your authenticator app. Each code can only be used once.": "これらのコードは、認証アプリへのアクセスを失った場合にアカウントにアクセスするために使用できます。各コードは一度しか使用できません。",
|
"These codes can be used to access your account if you lose access to your authenticator app. Each code can only be used once.": "認証アプリにアクセスできない場合、これらのコードでアカウントにアクセスできます。各コードは1回のみ使用可能です",
|
||||||
"Print": "印刷",
|
"Print": "印刷",
|
||||||
"Two-factor authentication has been set up. Please log in again.": "二要素認証が設定されました。再度ログインしてください。",
|
"Two-factor authentication has been set up. Please log in again.": "二要素認証を設定しました。再度ログインしてください",
|
||||||
"Two-Factor authentication required": "二要素認証が必要です",
|
"Two-Factor authentication required": "二要素認証が必要です",
|
||||||
"Your workspace requires two-factor authentication for all users": "ワークスペースでは、すべてのユーザーに二要素認証が必要です",
|
"Your workspace requires two-factor authentication for all users": "このワークスペースではすべてのユーザーに二要素認証が必要です",
|
||||||
"To continue accessing your workspace, you must set up two-factor authentication. This adds an extra layer of security to your account.": "ワークスペースへのアクセスを続けるには、二要素認証を設定する必要があります。これにより、アカウントに追加のセキュリティ層が追加されます。",
|
"To continue accessing your workspace, you must set up two-factor authentication. This adds an extra layer of security to your account.": "ワークスペースにアクセスするには二要素認証を設定してください。アカウントのセキュリティが強化されます",
|
||||||
"Set up two-factor authentication": "二要素認証を設定",
|
"Set up two-factor authentication": "二要素認証を設定",
|
||||||
"Cancel and logout": "キャンセルしてログアウト",
|
"Cancel and logout": "キャンセルしてログアウト",
|
||||||
"Your workspace requires two-factor authentication. Please set it up to continue.": "ワークスペースでは二要素認証が必要です。続行するには設定してください。",
|
"Your workspace requires two-factor authentication. Please set it up to continue.": "このワークスペースでは二要素認証が必要です。続行するには設定してください",
|
||||||
"This adds an extra layer of security to your account by requiring a verification code from your authenticator app.": "これにより、認証アプリからの確認コードが必要となり、アカウントに追加のセキュリティ層が追加されます。",
|
"This adds an extra layer of security to your account by requiring a verification code from your authenticator app.": "認証アプリからの確認コードでアカウントのセキュリティが強化されます",
|
||||||
"Password is required": "パスワードが必要です",
|
"Password is required": "パスワードが必要です",
|
||||||
"Password must be at least 8 characters": "パスワードは8文字以上必要です",
|
"Password must be at least 8 characters": "パスワードは8文字以上必要です",
|
||||||
"Please enter a 6-digit code": "6桁のコードを入力してください",
|
"Please enter a 6-digit code": "6桁のコードを入力してください",
|
||||||
"Code must be exactly 6 digits": "コードは正確に6桁である必要があります",
|
"Code must be exactly 6 digits": "コードは6桁で入力してください",
|
||||||
"Enter the 6-digit code found in your authenticator app": "認証アプリに表示された6桁のコードを入力してください",
|
"Enter the 6-digit code found in your authenticator app": "認証アプリに表示された6桁のコードを入力してください",
|
||||||
"Need help authenticating?": "認証に関するヘルプが必要ですか?",
|
"Need help authenticating?": "認証に関するヘルプが必要ですか?",
|
||||||
"MFA QR Code": "MFA QRコード",
|
"MFA QR Code": "MFA QRコード",
|
||||||
"Account created successfully. Please log in to set up two-factor authentication.": "アカウントが正常に作成されました。二要素認証を設定するためにログインしてください。",
|
"Account created successfully. Please log in to set up two-factor authentication.": "アカウントを作成しました。二要素認証を設定するためにログインしてください",
|
||||||
"Password reset successful. Please log in with your new password and complete two-factor authentication.": "パスワードのリセットが成功しました。新しいパスワードでログインし、二要素認証を完了してください。",
|
"Password reset successful. Please log in with your new password and complete two-factor authentication.": "パスワードをリセットしました。新しいパスワードでログインして二要素認証を完了してください",
|
||||||
"Password reset successful. Please log in with your new password to set up two-factor authentication.": "パスワードのリセットが成功しました。二要素認証を設定するために新しいパスワードでログインしてください。",
|
"Password reset successful. Please log in with your new password to set up two-factor authentication.": "パスワードをリセットしました。新しいパスワードでログインして二要素認証を設定してください",
|
||||||
"Password reset was successful. Please log in with your new password.": "パスワードのリセットが成功しました。新しいパスワードでログインしてください。",
|
"Password reset was successful. Please log in with your new password.": "パスワードをリセットしました。新しいパスワードでログインしてください",
|
||||||
"Two-factor authentication": "二要素認証",
|
"Two-factor authentication": "二要素認証",
|
||||||
"Use authenticator app instead": "代わりに認証アプリを使用",
|
"Use authenticator app instead": "代わりに認証アプリを使用",
|
||||||
"Verify backup code": "バックアップコードを確認",
|
"Verify backup code": "バックアップコードを確認",
|
||||||
"Use backup code": "バックアップコードを使用",
|
"Use backup code": "バックアップコードを使用",
|
||||||
"Enter one of your backup codes": "バックアップコードのいずれかを入力してください",
|
"Enter one of your backup codes": "バックアップコードのいずれかを入力してください",
|
||||||
"Backup code": "バックアップコード",
|
"Backup code": "バックアップコード",
|
||||||
"Enter one of your backup codes. Each backup code can only be used once.": "バックアップコードのいずれかを入力してください。各バックアップコードは一度しか使用できません。",
|
"Enter one of your backup codes. Each backup code can only be used once.": "バックアップコードを入力してください。各コードは1回のみ使用可能です",
|
||||||
"Verify": "確認",
|
"Verify": "確認",
|
||||||
"Trash": "ごみ箱",
|
"Trash": "ごみ箱",
|
||||||
"Pages in trash will be permanently deleted after 30 days.": "ごみ箱内のページは30日後に完全に削除されます。",
|
"Pages in trash will be permanently deleted after 30 days.": "ごみ箱内のページは30日後に完全に削除されます",
|
||||||
"Deleted": "削除",
|
"Deleted": "削除",
|
||||||
"No pages in trash": "ごみ箱にページがありません",
|
"No pages in trash": "ごみ箱にページがありません",
|
||||||
"Permanently delete page?": "ページを完全に削除しますか?",
|
"Permanently delete page?": "ページを完全に削除しますか?",
|
||||||
"Are you sure you want to permanently delete '{{title}}'? This action cannot be undone.": "{{title}}』を完全に削除しますか? この操作は元に戻せません。",
|
"Are you sure you want to permanently delete '{{title}}'? This action cannot be undone.": "「{{title}}」を完全に削除しますか?この操作は取り消せません",
|
||||||
"Restore '{{title}}' and its sub-pages?": "{{title}}』とそのサブページを復元しますか?",
|
"Restore '{{title}}' and its sub-pages?": "「{{title}}」とそのサブページを復元しますか?",
|
||||||
"Move to trash": "ごみ箱に移動",
|
"Move to trash": "ごみ箱に移動",
|
||||||
"Move this page to trash?": "このページをごみ箱に移動しますか?",
|
"Move this page to trash?": "このページをごみ箱に移動しますか?",
|
||||||
"Restore page": "ページを復元",
|
"Restore page": "ページを復元",
|
||||||
"Page moved to trash": "ページがごみ箱に移動されました",
|
"Page moved to trash": "ページをごみ箱に移動しました",
|
||||||
"Page restored successfully": "ページが正常に復元されました",
|
"Page restored successfully": "ページを復元しました",
|
||||||
"Deleted by": "削除者",
|
"Deleted by": "削除者",
|
||||||
"Deleted at": "削除日時",
|
"Deleted at": "削除日時",
|
||||||
"Preview": "プレビュー",
|
"Preview": "プレビュー",
|
||||||
@@ -511,10 +511,10 @@
|
|||||||
"Enterprise": "エンタープライズ",
|
"Enterprise": "エンタープライズ",
|
||||||
"Download attachment": "添付ファイルをダウンロード",
|
"Download attachment": "添付ファイルをダウンロード",
|
||||||
"Allowed email domains": "許可されたメールドメイン",
|
"Allowed email domains": "許可されたメールドメイン",
|
||||||
"Only users with email addresses from these domains can signup via SSO.": "これらのドメインからのメールアドレスを持つユーザーのみがSSOで登録できます。",
|
"Only users with email addresses from these domains can signup via SSO.": "これらのドメインのメールアドレスを持つユーザーのみSSO経由で登録できます",
|
||||||
"Enter valid domain names separated by comma or space": "コンマまたはスペースで区切って有効なドメイン名を入力してください",
|
"Enter valid domain names separated by comma or space": "コンマまたはスペースで区切って有効なドメイン名を入力してください",
|
||||||
"Enforce two-factor authentication": "二要素認証を強制する",
|
"Enforce two-factor authentication": "二要素認証を強制する",
|
||||||
"Once enforced, all members must enable two-factor authentication to access the workspace.": "一度強制されると、すべてのメンバーはワークスペースにアクセスするために二要素認証を有効にする必要があります。",
|
"Once enforced, all members must enable two-factor authentication to access the workspace.": "有効にすると、すべてのメンバーが二要素認証を設定しないとワークスペースにアクセスできなくなります",
|
||||||
"Toggle MFA enforcement": "MFAの強制を切り替える",
|
"Toggle MFA enforcement": "MFAの強制を切り替える",
|
||||||
"Display name": "表示名",
|
"Display name": "表示名",
|
||||||
"Allow signup": "登録を許可する",
|
"Allow signup": "登録を許可する",
|
||||||
@@ -532,10 +532,10 @@
|
|||||||
"Upload image": "画像をアップロード",
|
"Upload image": "画像をアップロード",
|
||||||
"Remove image": "画像を削除",
|
"Remove image": "画像を削除",
|
||||||
"Failed to remove image": "画像の削除に失敗しました",
|
"Failed to remove image": "画像の削除に失敗しました",
|
||||||
"Image exceeds 10MB limit.": "画像が10MBの制限を超えています。",
|
"Image exceeds 10MB limit.": "画像が10MBの制限を超えています",
|
||||||
"Image removed successfully": "画像が正常に削除されました",
|
"Image removed successfully": "画像を削除しました",
|
||||||
"API key": "APIキー",
|
"API key": "APIキー",
|
||||||
"API key created successfully": "APIキーが正常に作成されました",
|
"API key created successfully": "APIキーを作成しました",
|
||||||
"API keys": "APIキー",
|
"API keys": "APIキー",
|
||||||
"API management": "API管理",
|
"API management": "API管理",
|
||||||
"Are you sure you want to revoke this API key": "このAPIキーを無効にしてもよろしいですか",
|
"Are you sure you want to revoke this API key": "このAPIキーを無効にしてもよろしいですか",
|
||||||
@@ -550,9 +550,9 @@
|
|||||||
"No API keys found": "APIキーが見つかりません",
|
"No API keys found": "APIキーが見つかりません",
|
||||||
"No expiration": "期限なし",
|
"No expiration": "期限なし",
|
||||||
"Revoke API key": "APIキーを無効にする",
|
"Revoke API key": "APIキーを無効にする",
|
||||||
"Revoked successfully": "正常に無効化されました",
|
"Revoked successfully": "無効にしました",
|
||||||
"Select expiration date": "有効期限を選択してください",
|
"Select expiration date": "有効期限を選択してください",
|
||||||
"This action cannot be undone. Any applications using this API key will stop working.": "この操作は元に戻せません。このAPIキーを使用しているアプリケーションは動作を停止します。",
|
"This action cannot be undone. Any applications using this API key will stop working.": "この操作は取り消せません。このAPIキーを使用しているアプリケーションは動作しなくなります",
|
||||||
"Update API key": "APIキーを更新",
|
"Update API key": "APIキーを更新",
|
||||||
"Manage API keys for all users in the workspace": "ワークスペース内のすべてのユーザーのAPIキーを管理",
|
"Manage API keys for all users in the workspace": "ワークスペース内のすべてのユーザーのAPIキーを管理",
|
||||||
"AI settings": "AI設定",
|
"AI settings": "AI設定",
|
||||||
@@ -562,7 +562,7 @@
|
|||||||
"AI is thinking...": "AIが考え中...",
|
"AI is thinking...": "AIが考え中...",
|
||||||
"Ask a question...": "質問を入力...",
|
"Ask a question...": "質問を入力...",
|
||||||
"AI-powered search (Ask AI)": "AIによる検索(AIに質問)",
|
"AI-powered search (Ask AI)": "AIによる検索(AIに質問)",
|
||||||
"AI search uses vector embeddings to provide semantic search capabilities across your workspace content.": "AI検索はベクター埋め込みを使用して、ワークスペースコンテンツ全体にわたって意味検索機能を提供します。",
|
"AI search uses vector embeddings to provide semantic search capabilities across your workspace content.": "AI検索はベクター埋め込みを使用してワークスペース全体の意味検索を実現します",
|
||||||
"Toggle AI search": "AI検索を切り替え",
|
"Toggle AI search": "AI検索を切り替え",
|
||||||
"Sources": "ソース",
|
"Sources": "ソース",
|
||||||
"Ask AI not available for attachments": "添付ファイルにはAI質問は利用できません",
|
"Ask AI not available for attachments": "添付ファイルにはAI質問は利用できません",
|
||||||
|
|||||||
@@ -3,3 +3,15 @@ import { atom } from 'jotai';
|
|||||||
export const showCommentPopupAtom = atom<boolean>(false);
|
export const showCommentPopupAtom = atom<boolean>(false);
|
||||||
export const activeCommentIdAtom = atom<string>('');
|
export const activeCommentIdAtom = atom<string>('');
|
||||||
export const draftCommentIdAtom = atom<string>('');
|
export const draftCommentIdAtom = atom<string>('');
|
||||||
|
|
||||||
|
// Read-only comment state
|
||||||
|
export const showReadOnlyCommentPopupAtom = atom<boolean>(false);
|
||||||
|
export type YjsSelection = {
|
||||||
|
anchor: any;
|
||||||
|
head: any;
|
||||||
|
};
|
||||||
|
export type ReadOnlyCommentData = {
|
||||||
|
yjsSelection: YjsSelection;
|
||||||
|
selectedText: string;
|
||||||
|
};
|
||||||
|
export const readOnlyCommentDataAtom = atom<ReadOnlyCommentData | null>(null);
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import {
|
|||||||
} from "@tanstack/react-query";
|
} from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
createComment,
|
createComment,
|
||||||
|
createReadOnlyComment,
|
||||||
|
CreateReadOnlyCommentData,
|
||||||
deleteComment,
|
deleteComment,
|
||||||
getPageComments,
|
getPageComments,
|
||||||
updateComment,
|
updateComment,
|
||||||
@@ -106,4 +108,23 @@ export function useDeleteCommentMutation(pageId?: string) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useCreateReadOnlyCommentMutation() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return useMutation<IComment, Error, CreateReadOnlyCommentData>({
|
||||||
|
mutationFn: (data) => createReadOnlyComment(data),
|
||||||
|
onSuccess: (data) => {
|
||||||
|
queryClient.refetchQueries({ queryKey: RQ_KEY(data.pageId) });
|
||||||
|
notifications.show({ message: t("Comment created successfully") });
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
notifications.show({
|
||||||
|
message: t("Error creating comment"),
|
||||||
|
color: "red",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// EE: useResolveCommentMutation has been moved to @/ee/comment/queries/comment-query
|
// EE: useResolveCommentMutation has been moved to @/ee/comment/queries/comment-query
|
||||||
|
|||||||
@@ -40,3 +40,20 @@ export async function getPageComments(
|
|||||||
export async function deleteComment(commentId: string): Promise<void> {
|
export async function deleteComment(commentId: string): Promise<void> {
|
||||||
await api.post("/comments/delete", { commentId });
|
await api.post("/comments/delete", { commentId });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CreateReadOnlyCommentData = {
|
||||||
|
pageId: string;
|
||||||
|
content: string;
|
||||||
|
selection?: string;
|
||||||
|
yjsSelection: {
|
||||||
|
anchor: any;
|
||||||
|
head: any;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function createReadOnlyComment(
|
||||||
|
data: CreateReadOnlyCommentData,
|
||||||
|
): Promise<IComment> {
|
||||||
|
const req = await api.post<IComment>("/comments/create-readonly", data);
|
||||||
|
return req.data;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import {
|
||||||
|
BubbleMenu,
|
||||||
|
isNodeSelection,
|
||||||
|
isTextSelection,
|
||||||
|
useEditor,
|
||||||
|
} from "@tiptap/react";
|
||||||
|
import { FC, useEffect, useRef } from "react";
|
||||||
|
import { IconMessage } from "@tabler/icons-react";
|
||||||
|
import classes from "./bubble-menu.module.css";
|
||||||
|
import { ActionIcon, Tooltip } from "@mantine/core";
|
||||||
|
import {
|
||||||
|
readOnlyCommentDataAtom,
|
||||||
|
showReadOnlyCommentPopupAtom,
|
||||||
|
} from "@/features/comment/atoms/comment-atom";
|
||||||
|
import { useAtom } from "jotai";
|
||||||
|
import { isCellSelection } from "@docmost/editor-ext";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { ySyncPluginKey } from "y-prosemirror";
|
||||||
|
import { getRelativeSelection } from "y-prosemirror";
|
||||||
|
|
||||||
|
type ReadOnlyBubbleMenuProps = {
|
||||||
|
editor: ReturnType<typeof useEditor>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ReadOnlyBubbleMenu: FC<ReadOnlyBubbleMenuProps> = ({ editor }) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [showReadOnlyCommentPopup, setShowReadOnlyCommentPopup] = useAtom(
|
||||||
|
showReadOnlyCommentPopupAtom,
|
||||||
|
);
|
||||||
|
const [, setReadOnlyCommentData] = useAtom(readOnlyCommentDataAtom);
|
||||||
|
const showPopupRef = useRef(showReadOnlyCommentPopup);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
showPopupRef.current = showReadOnlyCommentPopup;
|
||||||
|
}, [showReadOnlyCommentPopup]);
|
||||||
|
|
||||||
|
const handleCommentClick = () => {
|
||||||
|
if (!editor) return;
|
||||||
|
|
||||||
|
const view = editor.view;
|
||||||
|
const ystate = ySyncPluginKey.getState(view.state);
|
||||||
|
|
||||||
|
if (ystate?.binding) {
|
||||||
|
const selection = getRelativeSelection(ystate.binding, view.state);
|
||||||
|
const { from, to } = editor.state.selection;
|
||||||
|
const selectedText = editor.state.doc.textBetween(from, to);
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
setReadOnlyCommentData({
|
||||||
|
yjsSelection: {
|
||||||
|
anchor: selection.anchor,
|
||||||
|
head: selection.head,
|
||||||
|
},
|
||||||
|
selectedText,
|
||||||
|
});
|
||||||
|
setShowReadOnlyCommentPopup(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Don't render if editor is not available or is editable
|
||||||
|
if (!editor || editor.isEditable) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BubbleMenu
|
||||||
|
editor={editor}
|
||||||
|
pluginKey="readonly"
|
||||||
|
shouldShow={({ state, editor }) => {
|
||||||
|
// Safety check - don't show if editor became editable
|
||||||
|
if (!editor || editor.isEditable || editor.isDestroyed) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { selection } = state;
|
||||||
|
const { empty, from, to } = selection;
|
||||||
|
|
||||||
|
if (
|
||||||
|
editor.isActive("image") ||
|
||||||
|
empty ||
|
||||||
|
isNodeSelection(selection) ||
|
||||||
|
isCellSelection(selection) ||
|
||||||
|
showPopupRef?.current
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if actual text is selected (not just empty block)
|
||||||
|
const hasText = state.doc.textBetween(from, to).length > 0;
|
||||||
|
return isTextSelection(selection) && hasText;
|
||||||
|
}}
|
||||||
|
tippyOptions={{
|
||||||
|
moveTransition: "transform 0.15s ease-out",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className={classes.bubbleMenu}>
|
||||||
|
<Tooltip label={t("Comment")} withArrow>
|
||||||
|
<ActionIcon
|
||||||
|
variant="default"
|
||||||
|
size="lg"
|
||||||
|
radius="0"
|
||||||
|
aria-label={t("Comment")}
|
||||||
|
style={{ border: "none" }}
|
||||||
|
onClick={handleCommentClick}
|
||||||
|
>
|
||||||
|
<IconMessage size={16} stroke={2} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
</BubbleMenu>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import React, { useState } from "react";
|
||||||
|
import { Dialog, Group, Stack, Text } from "@mantine/core";
|
||||||
|
import { useClickOutside } from "@mantine/hooks";
|
||||||
|
import { useAtom } from "jotai";
|
||||||
|
import {
|
||||||
|
activeCommentIdAtom,
|
||||||
|
readOnlyCommentDataAtom,
|
||||||
|
showReadOnlyCommentPopupAtom,
|
||||||
|
} from "@/features/comment/atoms/comment-atom";
|
||||||
|
import CommentEditor from "@/features/comment/components/comment-editor";
|
||||||
|
import CommentActions from "@/features/comment/components/comment-actions";
|
||||||
|
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
||||||
|
import { useCreateReadOnlyCommentMutation } from "@/features/comment/queries/comment-query";
|
||||||
|
import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom";
|
||||||
|
import { useEditor } from "@tiptap/react";
|
||||||
|
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useQueryEmit } from "@/features/websocket/use-query-emit";
|
||||||
|
|
||||||
|
type ReadOnlyCommentDialogProps = {
|
||||||
|
editor: ReturnType<typeof useEditor>;
|
||||||
|
pageId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function ReadOnlyCommentDialog({ editor, pageId }: ReadOnlyCommentDialogProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [comment, setComment] = useState("");
|
||||||
|
const [, setShowReadOnlyCommentPopup] = useAtom(showReadOnlyCommentPopupAtom);
|
||||||
|
const [, setActiveCommentId] = useAtom(activeCommentIdAtom);
|
||||||
|
const [readOnlyCommentData, setReadOnlyCommentData] = useAtom(
|
||||||
|
readOnlyCommentDataAtom,
|
||||||
|
);
|
||||||
|
const [currentUser] = useAtom(currentUserAtom);
|
||||||
|
const [, setAsideState] = useAtom(asideStateAtom);
|
||||||
|
const useClickOutsideRef = useClickOutside(() => {
|
||||||
|
handleDialogClose();
|
||||||
|
});
|
||||||
|
const createCommentMutation = useCreateReadOnlyCommentMutation();
|
||||||
|
const { isPending } = createCommentMutation;
|
||||||
|
|
||||||
|
const emit = useQueryEmit();
|
||||||
|
|
||||||
|
const handleDialogClose = () => {
|
||||||
|
setShowReadOnlyCommentPopup(false);
|
||||||
|
setReadOnlyCommentData(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddComment = async () => {
|
||||||
|
if (!readOnlyCommentData) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const commentData = {
|
||||||
|
pageId: pageId,
|
||||||
|
content: JSON.stringify(comment),
|
||||||
|
selection: readOnlyCommentData.selectedText,
|
||||||
|
yjsSelection: readOnlyCommentData.yjsSelection,
|
||||||
|
};
|
||||||
|
|
||||||
|
const createdComment =
|
||||||
|
await createCommentMutation.mutateAsync(commentData);
|
||||||
|
|
||||||
|
setActiveCommentId(createdComment.id);
|
||||||
|
setAsideState({ tab: "comments", isAsideOpen: true });
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
const selector = `div[data-comment-id="${createdComment.id}"]`;
|
||||||
|
const commentElement = document.querySelector(selector);
|
||||||
|
commentElement?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||||
|
}, 400);
|
||||||
|
|
||||||
|
emit({
|
||||||
|
operation: "invalidateComment",
|
||||||
|
pageId: pageId,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setShowReadOnlyCommentPopup(false);
|
||||||
|
setReadOnlyCommentData(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCommentEditorChange = (newContent: any) => {
|
||||||
|
setComment(newContent);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
opened={true}
|
||||||
|
onClose={handleDialogClose}
|
||||||
|
ref={useClickOutsideRef}
|
||||||
|
size="lg"
|
||||||
|
radius="md"
|
||||||
|
w={300}
|
||||||
|
position={{ bottom: 500, right: 50 }}
|
||||||
|
withCloseButton
|
||||||
|
withBorder
|
||||||
|
>
|
||||||
|
<Stack gap={2}>
|
||||||
|
<Group>
|
||||||
|
<CustomAvatar
|
||||||
|
size="sm"
|
||||||
|
avatarUrl={currentUser.user.avatarUrl}
|
||||||
|
name={currentUser.user.name}
|
||||||
|
/>
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
<Group justify="space-between" wrap="nowrap">
|
||||||
|
<Text size="sm" fw={500} lineClamp={1}>
|
||||||
|
{currentUser.user.name}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
</div>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
<CommentEditor
|
||||||
|
onUpdate={handleCommentEditorChange}
|
||||||
|
onSave={handleAddComment}
|
||||||
|
placeholder={t("Write a comment")}
|
||||||
|
editable={true}
|
||||||
|
autofocus={true}
|
||||||
|
/>
|
||||||
|
<CommentActions onSave={handleAddComment} isLoading={isPending} />
|
||||||
|
</Stack>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ReadOnlyCommentDialog;
|
||||||
@@ -1,19 +1,21 @@
|
|||||||
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
|
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
|
||||||
import { ActionIcon, Anchor, Text } from "@mantine/core";
|
import { ActionIcon, Anchor, Text } from "@mantine/core";
|
||||||
import { IconFileDescription } from "@tabler/icons-react";
|
import { IconFileDescription } from "@tabler/icons-react";
|
||||||
import { Link, useLocation, useParams } from "react-router-dom";
|
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
|
||||||
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||||
import {
|
import {
|
||||||
buildPageUrl,
|
buildPageUrl,
|
||||||
buildSharedPageUrl,
|
buildSharedPageUrl,
|
||||||
} from "@/features/page/page.utils.ts";
|
} from "@/features/page/page.utils.ts";
|
||||||
|
import { extractPageSlugId } from "@/lib";
|
||||||
import classes from "./mention.module.css";
|
import classes from "./mention.module.css";
|
||||||
|
|
||||||
export default function MentionView(props: NodeViewProps) {
|
export default function MentionView(props: NodeViewProps) {
|
||||||
const { node } = props;
|
const { node } = props;
|
||||||
const { label, entityType, entityId, slugId, anchorId } = node.attrs;
|
const { label, entityType, entityId, slugId, anchorId } = node.attrs;
|
||||||
const { spaceSlug } = useParams();
|
const { spaceSlug, pageSlug } = useParams();
|
||||||
const { shareId } = useParams();
|
const { shareId } = useParams();
|
||||||
|
const navigate = useNavigate();
|
||||||
const {
|
const {
|
||||||
data: page,
|
data: page,
|
||||||
isLoading,
|
isLoading,
|
||||||
@@ -23,6 +25,20 @@ export default function MentionView(props: NodeViewProps) {
|
|||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const isShareRoute = location.pathname.startsWith("/share");
|
const isShareRoute = location.pathname.startsWith("/share");
|
||||||
|
|
||||||
|
const currentPageSlugId = extractPageSlugId(pageSlug);
|
||||||
|
const isSamePage = currentPageSlugId === slugId;
|
||||||
|
|
||||||
|
const handleClick = (e: React.MouseEvent) => {
|
||||||
|
if (isSamePage && anchorId) {
|
||||||
|
e.preventDefault();
|
||||||
|
const element = document.querySelector(`[id="${anchorId}"]`);
|
||||||
|
if (element) {
|
||||||
|
element.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||||
|
navigate(`#${anchorId}`, { replace: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const shareSlugUrl = buildSharedPageUrl({
|
const shareSlugUrl = buildSharedPageUrl({
|
||||||
shareId,
|
shareId,
|
||||||
pageSlugId: slugId,
|
pageSlugId: slugId,
|
||||||
@@ -45,6 +61,7 @@ export default function MentionView(props: NodeViewProps) {
|
|||||||
to={
|
to={
|
||||||
isShareRoute ? shareSlugUrl : buildPageUrl(spaceSlug, slugId, label, anchorId)
|
isShareRoute ? shareSlugUrl : buildPageUrl(spaceSlug, slugId, label, anchorId)
|
||||||
}
|
}
|
||||||
|
onClick={handleClick}
|
||||||
underline="never"
|
underline="never"
|
||||||
className={classes.pageMentionLink}
|
className={classes.pageMentionLink}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -28,9 +28,12 @@ import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-
|
|||||||
import {
|
import {
|
||||||
activeCommentIdAtom,
|
activeCommentIdAtom,
|
||||||
showCommentPopupAtom,
|
showCommentPopupAtom,
|
||||||
|
showReadOnlyCommentPopupAtom,
|
||||||
} from "@/features/comment/atoms/comment-atom";
|
} from "@/features/comment/atoms/comment-atom";
|
||||||
import CommentDialog from "@/features/comment/components/comment-dialog";
|
import CommentDialog from "@/features/comment/components/comment-dialog";
|
||||||
import { EditorBubbleMenu } from "@/features/editor/components/bubble-menu/bubble-menu";
|
import { EditorBubbleMenu } from "@/features/editor/components/bubble-menu/bubble-menu";
|
||||||
|
import { ReadOnlyBubbleMenu } from "@/features/editor/components/bubble-menu/read-only-bubble-menu";
|
||||||
|
import ReadOnlyCommentDialog from "@/features/editor/components/bubble-menu/read-only-comment-dialog";
|
||||||
import TableCellMenu from "@/features/editor/components/table/table-cell-menu.tsx";
|
import TableCellMenu from "@/features/editor/components/table/table-cell-menu.tsx";
|
||||||
import TableMenu from "@/features/editor/components/table/table-menu.tsx";
|
import TableMenu from "@/features/editor/components/table/table-menu.tsx";
|
||||||
import ImageMenu from "@/features/editor/components/image/image-menu.tsx";
|
import ImageMenu from "@/features/editor/components/image/image-menu.tsx";
|
||||||
@@ -70,7 +73,7 @@ export default function PageEditor({
|
|||||||
content,
|
content,
|
||||||
}: PageEditorProps) {
|
}: PageEditorProps) {
|
||||||
|
|
||||||
|
|
||||||
const collaborationURL = useCollaborationUrl();
|
const collaborationURL = useCollaborationUrl();
|
||||||
const isComponentMounted = useRef(false);
|
const isComponentMounted = useRef(false);
|
||||||
const editorCreated = useRef(false);
|
const editorCreated = useRef(false);
|
||||||
@@ -78,12 +81,13 @@ export default function PageEditor({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
isComponentMounted.current = true;
|
isComponentMounted.current = true;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const [currentUser] = useAtom(currentUserAtom);
|
const [currentUser] = useAtom(currentUserAtom);
|
||||||
const [, setEditor] = useAtom(pageEditorAtom);
|
const [, setEditor] = useAtom(pageEditorAtom);
|
||||||
const [, setAsideState] = useAtom(asideStateAtom);
|
const [, setAsideState] = useAtom(asideStateAtom);
|
||||||
const [, setActiveCommentId] = useAtom(activeCommentIdAtom);
|
const [, setActiveCommentId] = useAtom(activeCommentIdAtom);
|
||||||
const [showCommentPopup, setShowCommentPopup] = useAtom(showCommentPopupAtom);
|
const [showCommentPopup, setShowCommentPopup] = useAtom(showCommentPopupAtom);
|
||||||
|
const [showReadOnlyCommentPopup] = useAtom(showReadOnlyCommentPopupAtom);
|
||||||
const ydocRef = useRef<Y.Doc | null>(null);
|
const ydocRef = useRef<Y.Doc | null>(null);
|
||||||
if (!ydocRef.current) {
|
if (!ydocRef.current) {
|
||||||
ydocRef.current = new Y.Doc();
|
ydocRef.current = new Y.Doc();
|
||||||
@@ -104,7 +108,7 @@ export default function PageEditor({
|
|||||||
const slugId = extractPageSlugId(pageSlug);
|
const slugId = extractPageSlugId(pageSlug);
|
||||||
const userPageEditMode =
|
const userPageEditMode =
|
||||||
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
||||||
|
|
||||||
const canScroll = useCallback(() => isComponentMounted.current && editorCreated.current, [isComponentMounted, editorCreated]);
|
const canScroll = useCallback(() => isComponentMounted.current && editorCreated.current, [isComponentMounted, editorCreated]);
|
||||||
const { handleScrollTo } = useEditorScroll({ canScroll });
|
const { handleScrollTo } = useEditorScroll({ canScroll });
|
||||||
// Providers only created once per pageId
|
// Providers only created once per pageId
|
||||||
@@ -429,7 +433,13 @@ export default function PageEditor({
|
|||||||
<LinkMenu editor={editor} appendTo={menuContainerRef} />
|
<LinkMenu editor={editor} appendTo={menuContainerRef} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{editor && !editorIsEditable && (
|
||||||
|
<ReadOnlyBubbleMenu key="readonly-bubble" editor={editor} />
|
||||||
|
)}
|
||||||
{showCommentPopup && <CommentDialog editor={editor} pageId={pageId} />}
|
{showCommentPopup && <CommentDialog editor={editor} pageId={pageId} />}
|
||||||
|
{showReadOnlyCommentPopup && (
|
||||||
|
<ReadOnlyCommentDialog editor={editor} pageId={pageId} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
onClick={() => editor.commands.focus("end")}
|
onClick={() => editor.commands.focus("end")}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import api from "@/lib/api-client";
|
import api from "@/lib/api-client";
|
||||||
import { IFileTask } from "@/features/file-task/types/file-task.types.ts";
|
import { IFileTask } from "@/features/file-task/types/file-task.types.ts";
|
||||||
|
import { IPagination, QueryParams } from "@/lib/types.ts";
|
||||||
|
import { IApiKey } from "@/ee/api-key";
|
||||||
|
|
||||||
export async function getFileTaskById(fileTaskId: string): Promise<IFileTask> {
|
export async function getFileTaskById(fileTaskId: string): Promise<IFileTask> {
|
||||||
const req = await api.post<IFileTask>("/file-tasks/info", {
|
const req = await api.post<IFileTask>("/file-tasks/info", {
|
||||||
@@ -8,7 +10,10 @@ export async function getFileTaskById(fileTaskId: string): Promise<IFileTask> {
|
|||||||
return req.data;
|
return req.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getFileTasks(): Promise<IFileTask[]> {
|
export async function getFileTasks(
|
||||||
const req = await api.post<IFileTask[]>("/file-tasks");
|
params?: QueryParams,
|
||||||
|
): Promise<IPagination<IFileTask>> {
|
||||||
|
const req = await api.post("/file-tasks", { ...params });
|
||||||
return req.data;
|
return req.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
import { zodResolver } from 'mantine-form-zod-resolver';
|
import { zodResolver } from 'mantine-form-zod-resolver';
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
name: z.string().trim().min(2).max(50),
|
name: z.string().trim().min(2).max(100),
|
||||||
description: z.string().max(500),
|
description: z.string().max(500),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
import { zodResolver } from "mantine-form-zod-resolver";
|
import { zodResolver } from "mantine-form-zod-resolver";
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
name: z.string().min(2).max(50),
|
name: z.string().min(2).max(100),
|
||||||
description: z.string().max(500),
|
description: z.string().max(500),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ export default function GroupList() {
|
|||||||
>
|
>
|
||||||
<Group gap="sm" wrap="nowrap">
|
<Group gap="sm" wrap="nowrap">
|
||||||
<IconGroupCircle />
|
<IconGroupCircle />
|
||||||
<div>
|
<div style={{ minWidth: 0, overflow: "hidden" }}>
|
||||||
<Text fz="sm" fw={500} lineClamp={1}>
|
<Text fz="sm" fw={500} lineClamp={1}>
|
||||||
{group.name}
|
{group.name}
|
||||||
</Text>
|
</Text>
|
||||||
|
|||||||
@@ -269,12 +269,15 @@ function Node({ node, style, dragHandle, tree }: NodeRendererProps<any>) {
|
|||||||
const toggleMobileSidebar = useToggleSidebar(mobileSidebarAtom);
|
const toggleMobileSidebar = useToggleSidebar(mobileSidebarAtom);
|
||||||
|
|
||||||
const prefetchPage = () => {
|
const prefetchPage = () => {
|
||||||
timerRef.current = setTimeout(() => {
|
timerRef.current = setTimeout(async () => {
|
||||||
queryClient.prefetchQuery({
|
const page = await queryClient.fetchQuery({
|
||||||
queryKey: ["pages", node.data.slugId],
|
queryKey: ["pages", node.data.id],
|
||||||
queryFn: () => getPageById({ pageId: node.data.slugId }),
|
queryFn: () => getPageById({ pageId: node.data.id }),
|
||||||
staleTime: 5 * 60 * 1000,
|
staleTime: 5 * 60 * 1000,
|
||||||
});
|
});
|
||||||
|
if (page?.slugId) {
|
||||||
|
queryClient.setQueryData(["pages", page.slugId], page);
|
||||||
|
}
|
||||||
}, 150);
|
}, 150);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import {
|
|||||||
Switch,
|
Switch,
|
||||||
Text,
|
Text,
|
||||||
TextInput,
|
TextInput,
|
||||||
Tooltip,
|
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { IconExternalLink, IconWorld, IconLock } from "@tabler/icons-react";
|
import { IconExternalLink, IconWorld, IconLock } from "@tabler/icons-react";
|
||||||
import React, { useEffect, useMemo, useState } from "react";
|
import React, { useEffect, useMemo, useState } from "react";
|
||||||
@@ -21,12 +20,12 @@ import {
|
|||||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||||
import { extractPageSlugId, getPageIcon } from "@/lib";
|
import { extractPageSlugId, getPageIcon } from "@/lib";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { usePageQuery } from "@/features/page/queries/page-query.ts";
|
||||||
import CopyTextButton from "@/components/common/copy.tsx";
|
import CopyTextButton from "@/components/common/copy.tsx";
|
||||||
import { getAppUrl, isCloud } from "@/lib/config.ts";
|
import { getAppUrl, isCloud } from "@/lib/config.ts";
|
||||||
import { buildPageUrl } from "@/features/page/page.utils.ts";
|
import { buildPageUrl } from "@/features/page/page.utils.ts";
|
||||||
import classes from "@/features/share/components/share.module.css";
|
import classes from "@/features/share/components/share.module.css";
|
||||||
import useTrial from "@/ee/hooks/use-trial.tsx";
|
import useTrial from "@/ee/hooks/use-trial.tsx";
|
||||||
import { getCheckoutLink } from "@/ee/billing/services/billing-service.ts";
|
|
||||||
|
|
||||||
interface ShareModalProps {
|
interface ShareModalProps {
|
||||||
readOnly: boolean;
|
readOnly: boolean;
|
||||||
@@ -35,7 +34,9 @@ export default function ShareModal({ readOnly }: ShareModalProps) {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { pageSlug } = useParams();
|
const { pageSlug } = useParams();
|
||||||
const pageId = extractPageSlugId(pageSlug);
|
const pageSlugId = extractPageSlugId(pageSlug);
|
||||||
|
const { data: page } = usePageQuery({ pageId: pageSlugId });
|
||||||
|
const pageId = page?.id;
|
||||||
const { data: share } = useShareForPageQuery(pageId);
|
const { data: share } = useShareForPageQuery(pageId);
|
||||||
const { spaceSlug } = useParams();
|
const { spaceSlug } = useParams();
|
||||||
const { isTrial } = useTrial();
|
const { isTrial } = useTrial();
|
||||||
|
|||||||
@@ -27,9 +27,7 @@ import {
|
|||||||
getShares,
|
getShares,
|
||||||
updateShare,
|
updateShare,
|
||||||
} from "@/features/share/services/share-service.ts";
|
} from "@/features/share/services/share-service.ts";
|
||||||
import { IPage } from "@/features/page/types/page.types.ts";
|
|
||||||
import { IPagination, QueryParams } from "@/lib/types.ts";
|
import { IPagination, QueryParams } from "@/lib/types.ts";
|
||||||
import { useEffect } from "react";
|
|
||||||
|
|
||||||
export function useGetSharesQuery(
|
export function useGetSharesQuery(
|
||||||
params?: QueryParams,
|
params?: QueryParams,
|
||||||
@@ -72,7 +70,7 @@ export function useShareForPageQuery(
|
|||||||
queryKey: ["share-for-page", pageId],
|
queryKey: ["share-for-page", pageId],
|
||||||
queryFn: () => getShareForPage(pageId),
|
queryFn: () => getShareForPage(pageId),
|
||||||
enabled: !!pageId,
|
enabled: !!pageId,
|
||||||
staleTime: 0,
|
staleTime: 60 * 1000,
|
||||||
retry: false,
|
retry: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Group, Box, Button, TextInput, Stack, Textarea } from "@mantine/core";
|
import { Group, Box, Button, TextInput, Stack, Textarea } from "@mantine/core";
|
||||||
import React, { useEffect } from "react";
|
import React, { useEffect } from "react";
|
||||||
import { useForm, zodResolver } from "@mantine/form";
|
import { useForm } from "@mantine/form";
|
||||||
|
import { zodResolver } from "mantine-form-zod-resolver";
|
||||||
import * as z from "zod";
|
import * as z from "zod";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useCreateSpaceMutation } from "@/features/space/queries/space-query.ts";
|
import { useCreateSpaceMutation } from "@/features/space/queries/space-query.ts";
|
||||||
@@ -9,12 +10,12 @@ import { getSpaceUrl } from "@/lib/config.ts";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
name: z.string().trim().min(2).max(50),
|
name: z.string().trim().min(2).max(100),
|
||||||
slug: z
|
slug: z
|
||||||
.string()
|
.string()
|
||||||
.trim()
|
.trim()
|
||||||
.min(2)
|
.min(2)
|
||||||
.max(50)
|
.max(100)
|
||||||
.regex(
|
.regex(
|
||||||
/^[a-zA-Z0-9]+$/,
|
/^[a-zA-Z0-9]+$/,
|
||||||
"Space slug must be alphanumeric. No special characters",
|
"Space slug must be alphanumeric. No special characters",
|
||||||
|
|||||||
@@ -7,12 +7,12 @@ import { ISpace } from "@/features/space/types/space.types.ts";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
name: z.string().min(2).max(50),
|
name: z.string().min(2).max(100),
|
||||||
description: z.string().max(250),
|
description: z.string().max(500),
|
||||||
slug: z
|
slug: z
|
||||||
.string()
|
.string()
|
||||||
.min(2)
|
.min(2)
|
||||||
.max(50)
|
.max(100)
|
||||||
.regex(
|
.regex(
|
||||||
/^[a-zA-Z0-9]+$/,
|
/^[a-zA-Z0-9]+$/,
|
||||||
"Space slug must be alphanumeric. No special characters",
|
"Space slug must be alphanumeric. No special characters",
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export default function SpaceList() {
|
|||||||
variant="filled"
|
variant="filled"
|
||||||
name={space.name}
|
name={space.name}
|
||||||
/>
|
/>
|
||||||
<div>
|
<div style={{ minWidth: 0, overflow: "hidden" }}>
|
||||||
<Text fz="sm" fw={500} lineClamp={1}>
|
<Text fz="sm" fw={500} lineClamp={1}>
|
||||||
{space.name}
|
{space.name}
|
||||||
</Text>
|
</Text>
|
||||||
|
|||||||
+25
-25
@@ -30,48 +30,48 @@
|
|||||||
"test:e2e": "jest --config test/jest-e2e.json"
|
"test:e2e": "jest --config test/jest-e2e.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ai-sdk/azure": "^2.0.47",
|
"@ai-sdk/google": "^3.0.9",
|
||||||
"@ai-sdk/google": "^2.0.18",
|
"@ai-sdk/openai": "^3.0.11",
|
||||||
"@ai-sdk/openai": "^2.0.46",
|
"@ai-sdk/openai-compatible": "^2.0.12",
|
||||||
"@aws-sdk/client-s3": "3.701.0",
|
"@aws-sdk/client-s3": "3.701.0",
|
||||||
"@aws-sdk/lib-storage": "3.701.0",
|
"@aws-sdk/lib-storage": "3.701.0",
|
||||||
"@aws-sdk/s3-request-presigner": "3.701.0",
|
"@aws-sdk/s3-request-presigner": "3.701.0",
|
||||||
"@casl/ability": "^6.7.3",
|
|
||||||
"@fastify/cookie": "^11.0.2",
|
"@fastify/cookie": "^11.0.2",
|
||||||
"@fastify/multipart": "^9.0.3",
|
"@fastify/multipart": "^9.3.0",
|
||||||
"@fastify/static": "^8.2.0",
|
"@fastify/static": "^8.3.0",
|
||||||
"@langchain/textsplitters": "^0.1.0",
|
"@langchain/core": "1.1.13",
|
||||||
|
"@langchain/textsplitters": "1.0.1",
|
||||||
"@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.11",
|
||||||
"@nestjs/config": "^4.0.2",
|
"@nestjs/config": "^4.0.2",
|
||||||
"@nestjs/core": "^11.1.9",
|
"@nestjs/core": "^11.1.11",
|
||||||
"@nestjs/event-emitter": "^3.0.1",
|
"@nestjs/event-emitter": "^3.0.1",
|
||||||
"@nestjs/jwt": "11.0.0",
|
"@nestjs/jwt": "11.0.0",
|
||||||
"@nestjs/mapped-types": "^2.1.0",
|
"@nestjs/mapped-types": "^2.1.0",
|
||||||
"@nestjs/passport": "^11.0.5",
|
"@nestjs/passport": "^11.0.5",
|
||||||
"@nestjs/platform-fastify": "^11.1.9",
|
"@nestjs/platform-fastify": "^11.1.11",
|
||||||
"@nestjs/platform-socket.io": "^11.1.9",
|
"@nestjs/platform-socket.io": "^11.1.11",
|
||||||
"@nestjs/schedule": "^6.0.1",
|
"@nestjs/schedule": "^6.1.0",
|
||||||
"@nestjs/terminus": "^11.0.0",
|
"@nestjs/terminus": "^11.0.0",
|
||||||
"@nestjs/websockets": "^11.1.9",
|
"@nestjs/websockets": "^11.1.11",
|
||||||
"@node-saml/passport-saml": "^5.1.0",
|
"@node-saml/passport-saml": "^5.1.0",
|
||||||
"@react-email/components": "0.0.28",
|
"@react-email/components": "0.0.28",
|
||||||
"@react-email/render": "1.0.2",
|
"@react-email/render": "1.0.2",
|
||||||
"@socket.io/redis-adapter": "^8.3.0",
|
"@socket.io/redis-adapter": "^8.3.0",
|
||||||
"ai": "^5.0.65",
|
"ai": "^6.0.37",
|
||||||
"ai-sdk-ollama": "^0.12.0",
|
"ai-sdk-ollama": "^3.1.1",
|
||||||
"bcrypt": "^6.0.0",
|
"bcrypt": "^6.0.0",
|
||||||
"bullmq": "^5.65.0",
|
"bullmq": "^5.65.0",
|
||||||
"cache-manager": "^6.4.3",
|
"cache-manager": "^6.4.3",
|
||||||
"cheerio": "^1.1.0",
|
"cheerio": "^1.1.2",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.3",
|
"class-validator": "^0.14.3",
|
||||||
"cookie": "^1.0.2",
|
"cookie": "^1.1.1",
|
||||||
"fs-extra": "^11.3.0",
|
"fs-extra": "^11.3.3",
|
||||||
"happy-dom": "20.0.10",
|
"happy-dom": "20.1.0",
|
||||||
"ioredis": "^5.4.1",
|
"ioredis": "^5.4.1",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.3",
|
||||||
"kysely": "^0.28.2",
|
"kysely": "^0.28.2",
|
||||||
"kysely-migration-cli": "^0.4.2",
|
"kysely-migration-cli": "^0.4.2",
|
||||||
"ldapts": "^7.4.0",
|
"ldapts": "^7.4.0",
|
||||||
@@ -79,9 +79,9 @@
|
|||||||
"mime-types": "^2.1.35",
|
"mime-types": "^2.1.35",
|
||||||
"nanoid": "3.3.11",
|
"nanoid": "3.3.11",
|
||||||
"nestjs-kysely": "^1.2.0",
|
"nestjs-kysely": "^1.2.0",
|
||||||
"nodemailer": "^7.0.11",
|
"nodemailer": "^7.0.12",
|
||||||
"openid-client": "^5.7.1",
|
"openid-client": "^5.7.1",
|
||||||
"otpauth": "^9.4.0",
|
"otpauth": "^9.4.1",
|
||||||
"p-limit": "^6.2.0",
|
"p-limit": "^6.2.0",
|
||||||
"passport-google-oauth20": "^2.0.0",
|
"passport-google-oauth20": "^2.0.0",
|
||||||
"passport-jwt": "^4.0.1",
|
"passport-jwt": "^4.0.1",
|
||||||
@@ -95,11 +95,11 @@
|
|||||||
"rxjs": "^7.8.2",
|
"rxjs": "^7.8.2",
|
||||||
"sanitize-filename-ts": "1.0.2",
|
"sanitize-filename-ts": "1.0.2",
|
||||||
"sharp": "0.34.3",
|
"sharp": "0.34.3",
|
||||||
"socket.io": "^4.8.1",
|
"socket.io": "^4.8.3",
|
||||||
"stripe": "^17.5.0",
|
"stripe": "^17.5.0",
|
||||||
"tmp-promise": "^3.0.3",
|
"tmp-promise": "^3.0.3",
|
||||||
"typesense": "^2.1.0",
|
"typesense": "^2.1.0",
|
||||||
"ws": "^8.18.3",
|
"ws": "^8.19.0",
|
||||||
"yauzl": "^3.2.0"
|
"yauzl": "^3.2.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -124,7 +124,7 @@
|
|||||||
"eslint-config-prettier": "^10.0.1",
|
"eslint-config-prettier": "^10.0.1",
|
||||||
"globals": "^15.15.0",
|
"globals": "^15.15.0",
|
||||||
"jest": "^29.7.0",
|
"jest": "^29.7.0",
|
||||||
"kysely-codegen": "^0.17.0",
|
"kysely-codegen": "^0.19.0",
|
||||||
"prettier": "^3.5.1",
|
"prettier": "^3.5.1",
|
||||||
"react-email": "3.0.2",
|
"react-email": "3.0.2",
|
||||||
"source-map-support": "^0.5.21",
|
"source-map-support": "^0.5.21",
|
||||||
|
|||||||
@@ -67,4 +67,8 @@ export class CollaborationGateway {
|
|||||||
async destroy(): Promise<void> {
|
async destroy(): Promise<void> {
|
||||||
await this.hocuspocus.destroy();
|
await this.hocuspocus.destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async openDirectConnection(documentName: string) {
|
||||||
|
return this.hocuspocus.openDirectConnection(documentName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,10 @@
|
|||||||
import { StarterKit } from '@tiptap/starter-kit';
|
import { StarterKit } from '@tiptap/starter-kit';
|
||||||
|
import {
|
||||||
|
initProseMirrorDoc,
|
||||||
|
relativePositionToAbsolutePosition,
|
||||||
|
} from 'y-prosemirror';
|
||||||
|
import * as Y from 'yjs';
|
||||||
|
import { Document } from '@hocuspocus/server';
|
||||||
import { TextAlign } from '@tiptap/extension-text-align';
|
import { TextAlign } from '@tiptap/extension-text-align';
|
||||||
import { TaskList } from '@tiptap/extension-task-list';
|
import { TaskList } from '@tiptap/extension-task-list';
|
||||||
import { TaskItem } from '@tiptap/extension-task-item';
|
import { TaskItem } from '@tiptap/extension-task-item';
|
||||||
@@ -116,3 +122,169 @@ export function jsonToNode(tiptapJson: JSONContent) {
|
|||||||
export function getPageId(documentName: string) {
|
export function getPageId(documentName: string) {
|
||||||
return documentName.split('.')[1];
|
return documentName.split('.')[1];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type YjsSelection = {
|
||||||
|
anchor: any;
|
||||||
|
head: any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function setYjsMark(
|
||||||
|
doc: Document,
|
||||||
|
fragment: Y.XmlFragment,
|
||||||
|
yjsSelection: YjsSelection,
|
||||||
|
markName: string,
|
||||||
|
markAttributes: Record<string, any>,
|
||||||
|
) {
|
||||||
|
const schema = getSchema(tiptapExtensions);
|
||||||
|
const { mapping } = initProseMirrorDoc(fragment, schema);
|
||||||
|
|
||||||
|
// Convert JSON positions to Y.js RelativePosition objects
|
||||||
|
const anchorRelPos = Y.createRelativePositionFromJSON(yjsSelection.anchor);
|
||||||
|
const headRelPos = Y.createRelativePositionFromJSON(yjsSelection.head);
|
||||||
|
|
||||||
|
const anchor = relativePositionToAbsolutePosition(
|
||||||
|
doc,
|
||||||
|
fragment,
|
||||||
|
anchorRelPos,
|
||||||
|
mapping,
|
||||||
|
);
|
||||||
|
const head = relativePositionToAbsolutePosition(
|
||||||
|
doc,
|
||||||
|
fragment,
|
||||||
|
headRelPos,
|
||||||
|
mapping,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (anchor === null || head === null) {
|
||||||
|
throw new Error(
|
||||||
|
'Could not resolve Y.js relative positions to absolute positions',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const from = Math.min(anchor, head);
|
||||||
|
const to = Math.max(anchor, head);
|
||||||
|
|
||||||
|
// Apply mark directly to Y.js XmlText nodes
|
||||||
|
// This bypasses updateYFragment which has compatibility issues
|
||||||
|
applyMarkToYFragment(fragment, from, to, markName, markAttributes);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyMarkToYFragment(
|
||||||
|
fragment: Y.XmlFragment,
|
||||||
|
from: number,
|
||||||
|
to: number,
|
||||||
|
markName: string,
|
||||||
|
markAttributes: Record<string, any>,
|
||||||
|
) {
|
||||||
|
let pos = 0;
|
||||||
|
|
||||||
|
const processItem = (item: any): boolean => {
|
||||||
|
if (pos >= to) return false;
|
||||||
|
|
||||||
|
if (item instanceof Y.XmlText) {
|
||||||
|
const textLength = item.length;
|
||||||
|
const itemEnd = pos + textLength;
|
||||||
|
|
||||||
|
if (itemEnd > from && pos < to) {
|
||||||
|
const formatFrom = Math.max(0, from - pos);
|
||||||
|
const formatTo = Math.min(textLength, to - pos);
|
||||||
|
const formatLength = formatTo - formatFrom;
|
||||||
|
|
||||||
|
if (formatLength > 0) {
|
||||||
|
item.format(formatFrom, formatLength, { [markName]: markAttributes });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pos = itemEnd;
|
||||||
|
} else if (item instanceof Y.XmlElement) {
|
||||||
|
pos++; // Opening tag
|
||||||
|
for (let i = 0; i < item.length; i++) {
|
||||||
|
if (!processItem(item.get(i))) return false;
|
||||||
|
}
|
||||||
|
pos++; // Closing tag
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < fragment.length; i++) {
|
||||||
|
if (!processItem(fragment.get(i))) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes a mark from all text in the fragment that has the specified attribute value.
|
||||||
|
* Useful for deleting comments by commentId.
|
||||||
|
*/
|
||||||
|
export function removeYjsMarkByAttribute(
|
||||||
|
fragment: Y.XmlFragment,
|
||||||
|
markName: string,
|
||||||
|
attributeName: string,
|
||||||
|
attributeValue: string,
|
||||||
|
) {
|
||||||
|
const processItem = (item: any) => {
|
||||||
|
if (item instanceof Y.XmlText) {
|
||||||
|
// Get all formatting deltas to find ranges with this mark
|
||||||
|
const deltas = item.toDelta();
|
||||||
|
let offset = 0;
|
||||||
|
|
||||||
|
for (const delta of deltas) {
|
||||||
|
const length = delta.insert?.length ?? 0;
|
||||||
|
const attributes = delta.attributes ?? {};
|
||||||
|
const markAttr = attributes[markName];
|
||||||
|
|
||||||
|
if (markAttr && markAttr[attributeName] === attributeValue) {
|
||||||
|
// Remove the mark by setting it to null
|
||||||
|
item.format(offset, length, { [markName]: null });
|
||||||
|
}
|
||||||
|
offset += length;
|
||||||
|
}
|
||||||
|
} else if (item instanceof Y.XmlElement) {
|
||||||
|
for (let i = 0; i < item.length; i++) {
|
||||||
|
processItem(item.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < fragment.length; i++) {
|
||||||
|
processItem(fragment.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates a mark's attributes for all text that has the specified attribute value.
|
||||||
|
* Useful for resolving/unresolving comments by commentId.
|
||||||
|
*/
|
||||||
|
export function updateYjsMarkAttribute(
|
||||||
|
fragment: Y.XmlFragment,
|
||||||
|
markName: string,
|
||||||
|
findByAttribute: { name: string; value: string },
|
||||||
|
newAttributes: Record<string, any>,
|
||||||
|
) {
|
||||||
|
const processItem = (item: any) => {
|
||||||
|
if (item instanceof Y.XmlText) {
|
||||||
|
const deltas = item.toDelta();
|
||||||
|
let offset = 0;
|
||||||
|
|
||||||
|
for (const delta of deltas) {
|
||||||
|
const length = delta.insert?.length ?? 0;
|
||||||
|
const attributes = delta.attributes ?? {};
|
||||||
|
const markAttr = attributes[markName];
|
||||||
|
|
||||||
|
if (markAttr && markAttr[findByAttribute.name] === findByAttribute.value) {
|
||||||
|
// Update the mark with new attributes (merge with existing)
|
||||||
|
item.format(offset, length, {
|
||||||
|
[markName]: { ...markAttr, ...newAttributes },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
offset += length;
|
||||||
|
}
|
||||||
|
} else if (item instanceof Y.XmlElement) {
|
||||||
|
for (let i = 0; i < item.length; i++) {
|
||||||
|
processItem(item.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < fragment.length; i++) {
|
||||||
|
processItem(fragment.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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}`);
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ export class PersistenceExtension implements Extension {
|
|||||||
content: tiptapJson,
|
content: tiptapJson,
|
||||||
textContent: textContent,
|
textContent: textContent,
|
||||||
ydoc: ydocState,
|
ydoc: ydocState,
|
||||||
lastUpdatedById: context.user.id,
|
lastUpdatedById: context?.user?.id,
|
||||||
contributorIds: contributorIds,
|
contributorIds: contributorIds,
|
||||||
},
|
},
|
||||||
pageId,
|
pageId,
|
||||||
@@ -157,7 +157,7 @@ export class PersistenceExtension implements Extension {
|
|||||||
page: {
|
page: {
|
||||||
...page,
|
...page,
|
||||||
content: tiptapJson,
|
content: tiptapJson,
|
||||||
lastUpdatedById: context.user.id,
|
lastUpdatedById: context?.user?.id,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -179,7 +179,7 @@ export class PersistenceExtension implements Extension {
|
|||||||
|
|
||||||
async onChange(data: onChangePayload) {
|
async onChange(data: onChangePayload) {
|
||||||
const documentName = data.documentName;
|
const documentName = data.documentName;
|
||||||
const userId = data.context?.user.id;
|
const userId = data.context?.user?.id;
|
||||||
if (!userId) return;
|
if (!userId) return;
|
||||||
|
|
||||||
if (!this.contributors.has(documentName)) {
|
if (!this.contributors.has(documentName)) {
|
||||||
|
|||||||
@@ -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
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { CommentService } from './comment.service';
|
import { CommentService } from './comment.service';
|
||||||
import { CreateCommentDto } from './dto/create-comment.dto';
|
import { CreateCommentDto } from './dto/create-comment.dto';
|
||||||
|
import { CreateReadOnlyCommentDto } from './dto/create-readonly-comment.dto';
|
||||||
import { UpdateCommentDto } from './dto/update-comment.dto';
|
import { UpdateCommentDto } from './dto/update-comment.dto';
|
||||||
import { PageIdDto, CommentIdDto } from './dto/comments.input';
|
import { PageIdDto, CommentIdDto } from './dto/comments.input';
|
||||||
import { AuthUser } from '../../common/decorators/auth-user.decorator';
|
import { AuthUser } from '../../common/decorators/auth-user.decorator';
|
||||||
@@ -24,7 +25,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 +34,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 +48,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(
|
||||||
{
|
{
|
||||||
@@ -61,6 +63,28 @@ export class CommentController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
@Post('create-readonly')
|
||||||
|
async createReadOnly(
|
||||||
|
@Body() createCommentDto: CreateReadOnlyCommentDto,
|
||||||
|
@AuthUser() user: User,
|
||||||
|
@AuthWorkspace() workspace: Workspace,
|
||||||
|
) {
|
||||||
|
const page = await this.pageRepo.findById(createCommentDto.pageId);
|
||||||
|
if (!page || page.deletedAt) {
|
||||||
|
throw new NotFoundException('Page not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.commentService.createReadOnlyComment(
|
||||||
|
{
|
||||||
|
userId: user.id,
|
||||||
|
page,
|
||||||
|
workspaceId: workspace.id,
|
||||||
|
},
|
||||||
|
createCommentDto,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@Post('/')
|
@Post('/')
|
||||||
async findPageComments(
|
async findPageComments(
|
||||||
@@ -74,8 +98,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 +113,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 +131,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 +154,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(
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { CommentService } from './comment.service';
|
import { CommentService } from './comment.service';
|
||||||
import { CommentController } from './comment.controller';
|
import { CommentController } from './comment.controller';
|
||||||
|
import { CollaborationModule } from '../../collaboration/collaboration.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [],
|
imports: [CollaborationModule],
|
||||||
controllers: [CommentController],
|
controllers: [CommentController],
|
||||||
providers: [CommentService],
|
providers: [CommentService],
|
||||||
exports: [CommentService],
|
exports: [CommentService],
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ import {
|
|||||||
BadRequestException,
|
BadRequestException,
|
||||||
ForbiddenException,
|
ForbiddenException,
|
||||||
Injectable,
|
Injectable,
|
||||||
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { CreateCommentDto } from './dto/create-comment.dto';
|
import { CreateCommentDto } from './dto/create-comment.dto';
|
||||||
|
import { CreateReadOnlyCommentDto } from './dto/create-readonly-comment.dto';
|
||||||
import { UpdateCommentDto } from './dto/update-comment.dto';
|
import { UpdateCommentDto } from './dto/update-comment.dto';
|
||||||
import { CommentRepo } from '@docmost/db/repos/comment/comment.repo';
|
import { CommentRepo } from '@docmost/db/repos/comment/comment.repo';
|
||||||
import { Comment, Page, User } from '@docmost/db/types/entity.types';
|
import { Comment, Page, User } from '@docmost/db/types/entity.types';
|
||||||
@@ -12,13 +14,19 @@ import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
|
|||||||
import { PaginationResult } from '@docmost/db/pagination/pagination';
|
import { PaginationResult } from '@docmost/db/pagination/pagination';
|
||||||
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 { CollaborationGateway } from '../../collaboration/collaboration.gateway';
|
||||||
|
import { setYjsMark } from '../../collaboration/collaboration.util';
|
||||||
|
import * as Y from 'yjs';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CommentService {
|
export class CommentService {
|
||||||
|
private readonly logger = new Logger(CommentService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private commentRepo: CommentRepo,
|
private commentRepo: CommentRepo,
|
||||||
private pageRepo: PageRepo,
|
private pageRepo: PageRepo,
|
||||||
private spaceMemberRepo: SpaceMemberRepo,
|
private spaceMemberRepo: SpaceMemberRepo,
|
||||||
|
private collaborationGateway: CollaborationGateway,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async findById(commentId: string) {
|
async findById(commentId: string) {
|
||||||
@@ -105,4 +113,49 @@ export class CommentService {
|
|||||||
|
|
||||||
return comment;
|
return comment;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async createReadOnlyComment(
|
||||||
|
opts: { userId: string; page: Page; workspaceId: string },
|
||||||
|
createCommentDto: CreateReadOnlyCommentDto,
|
||||||
|
): Promise<Comment> {
|
||||||
|
const { userId, page, workspaceId } = opts;
|
||||||
|
const commentContent = JSON.parse(createCommentDto.content);
|
||||||
|
|
||||||
|
const comment = await this.commentRepo.insertComment({
|
||||||
|
pageId: page.id,
|
||||||
|
content: commentContent,
|
||||||
|
selection: createCommentDto?.selection?.substring(0, 250),
|
||||||
|
type: 'inline',
|
||||||
|
creatorId: userId,
|
||||||
|
workspaceId: workspaceId,
|
||||||
|
spaceId: page.spaceId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const documentName = `page.${page.id}`;
|
||||||
|
const directConnection =
|
||||||
|
await this.collaborationGateway.openDirectConnection(documentName);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await directConnection.transact((doc) => {
|
||||||
|
const fragment = doc.getXmlFragment('default');
|
||||||
|
setYjsMark(doc, fragment, createCommentDto.yjsSelection, 'comment', {
|
||||||
|
commentId: comment.id,
|
||||||
|
resolved: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to apply comment mark for comment ${comment.id}`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
await this.commentRepo.deleteComment(comment.id);
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Failed to apply comment mark. Selection may have changed.',
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await directConnection.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
return comment;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { IsJSON, IsObject, IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateReadOnlyCommentDto {
|
||||||
|
@IsString()
|
||||||
|
pageId: string;
|
||||||
|
|
||||||
|
@IsJSON()
|
||||||
|
content: any;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
selection: string;
|
||||||
|
|
||||||
|
@IsObject()
|
||||||
|
yjsSelection: {
|
||||||
|
anchor: any;
|
||||||
|
head: any;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -14,7 +14,6 @@ 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 { ShareModule } from './share/share.module';
|
import { ShareModule } from './share/share.module';
|
||||||
|
|
||||||
@@ -30,7 +29,6 @@ import { ShareModule } from './share/share.module';
|
|||||||
SpaceModule,
|
SpaceModule,
|
||||||
GroupModule,
|
GroupModule,
|
||||||
CaslModule,
|
CaslModule,
|
||||||
PageAccessModule,
|
|
||||||
ShareModule,
|
ShareModule,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {Transform, TransformFnParams} from "class-transformer";
|
|||||||
|
|
||||||
export class CreateGroupDto {
|
export class CreateGroupDto {
|
||||||
@MinLength(2)
|
@MinLength(2)
|
||||||
@MaxLength(50)
|
@MaxLength(100)
|
||||||
@IsString()
|
@IsString()
|
||||||
@Transform(({ value }: TransformFnParams) => value?.trim())
|
@Transform(({ value }: TransformFnParams) => value?.trim())
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
@@ -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(
|
||||||
@@ -76,16 +74,13 @@ export class SearchService {
|
|||||||
queryResults = queryResults.where('spaceId', '=', searchParams.spaceId);
|
queryResults = queryResults.where('spaceId', '=', searchParams.spaceId);
|
||||||
} else if (opts.userId && !searchParams.spaceId) {
|
} else if (opts.userId && !searchParams.spaceId) {
|
||||||
// only search spaces the user is a member of
|
// only search spaces the user is a member of
|
||||||
const userSpaceIds = await this.spaceMemberRepo.getUserSpaceIds(
|
queryResults = queryResults
|
||||||
opts.userId,
|
.where(
|
||||||
);
|
'spaceId',
|
||||||
if (userSpaceIds.length > 0) {
|
'in',
|
||||||
queryResults = queryResults
|
this.spaceMemberRepo.getUserSpaceIdsQuery(opts.userId),
|
||||||
.where('spaceId', 'in', userSpaceIds)
|
)
|
||||||
.where('workspaceId', '=', opts.workspaceId);
|
.where('workspaceId', '=', opts.workspaceId);
|
||||||
} else {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
} else if (searchParams.shareId && !searchParams.spaceId && !opts.userId) {
|
} else if (searchParams.shareId && !searchParams.spaceId && !opts.userId) {
|
||||||
// search in shares
|
// search in shares
|
||||||
const shareId = searchParams.shareId;
|
const shareId = searchParams.shareId;
|
||||||
@@ -120,22 +115,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 +207,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,
|
||||||
@@ -234,80 +123,82 @@ export class ShareService {
|
|||||||
.withRecursive('page_hierarchy', (cte) =>
|
.withRecursive('page_hierarchy', (cte) =>
|
||||||
cte
|
cte
|
||||||
.selectFrom('pages')
|
.selectFrom('pages')
|
||||||
|
.leftJoin('shares', 'shares.pageId', 'pages.id')
|
||||||
.select([
|
.select([
|
||||||
'id',
|
'pages.id',
|
||||||
'slugId',
|
'pages.slugId',
|
||||||
'pages.title',
|
'pages.title',
|
||||||
'pages.icon',
|
'pages.icon',
|
||||||
'parentPageId',
|
'pages.parentPageId',
|
||||||
sql`0`.as('level'),
|
sql`0`.as('level'),
|
||||||
|
'shares.id as shareId',
|
||||||
|
'shares.key as shareKey',
|
||||||
|
'shares.includeSubPages',
|
||||||
|
'shares.searchIndexing',
|
||||||
|
'shares.creatorId',
|
||||||
|
'shares.spaceId',
|
||||||
|
'shares.workspaceId',
|
||||||
|
'shares.createdAt',
|
||||||
])
|
])
|
||||||
.where(isValidUUID(pageId) ? 'id' : 'slugId', '=', pageId)
|
.where(isValidUUID(pageId) ? 'pages.id' : 'pages.slugId', '=', pageId)
|
||||||
.where('deletedAt', 'is', null)
|
.where('pages.deletedAt', 'is', null)
|
||||||
.unionAll((union) =>
|
.unionAll(
|
||||||
union
|
(union) =>
|
||||||
.selectFrom('pages as p')
|
union
|
||||||
.select([
|
.selectFrom('pages as p')
|
||||||
'p.id',
|
.innerJoin('page_hierarchy as ph', 'ph.parentPageId', 'p.id')
|
||||||
'p.slugId',
|
.leftJoin('shares as s', 's.pageId', 'p.id')
|
||||||
'p.title',
|
.select([
|
||||||
'p.icon',
|
'p.id',
|
||||||
'p.parentPageId',
|
'p.slugId',
|
||||||
// Increase the level by 1 for each ancestor.
|
'p.title',
|
||||||
sql`ph.level + 1`.as('level'),
|
'p.icon',
|
||||||
])
|
'p.parentPageId',
|
||||||
.innerJoin('page_hierarchy as ph', 'ph.parentPageId', 'p.id')
|
sql`ph.level + 1`.as('level'),
|
||||||
.where('p.deletedAt', 'is', null),
|
's.id as shareId',
|
||||||
|
's.key as shareKey',
|
||||||
|
's.includeSubPages',
|
||||||
|
's.searchIndexing',
|
||||||
|
's.creatorId',
|
||||||
|
's.spaceId',
|
||||||
|
's.workspaceId',
|
||||||
|
's.createdAt',
|
||||||
|
])
|
||||||
|
.where('p.deletedAt', 'is', null)
|
||||||
|
.where(sql`ph.share_id`, 'is', null) // stop if share found
|
||||||
|
.where(sql`ph.level`, '<', sql`25`), // prevent loop
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.selectFrom('page_hierarchy')
|
.selectFrom('page_hierarchy')
|
||||||
.leftJoin('shares', 'shares.pageId', 'page_hierarchy.id')
|
.selectAll()
|
||||||
.select([
|
.where('shareId', 'is not', null)
|
||||||
'page_hierarchy.id as sharedPageId',
|
.limit(1)
|
||||||
'page_hierarchy.slugId as sharedPageSlugId',
|
|
||||||
'page_hierarchy.title as sharedPageTitle',
|
|
||||||
'page_hierarchy.icon as sharedPageIcon',
|
|
||||||
'page_hierarchy.level as level',
|
|
||||||
'shares.id',
|
|
||||||
'shares.key',
|
|
||||||
'shares.pageId',
|
|
||||||
'shares.includeSubPages',
|
|
||||||
'shares.searchIndexing',
|
|
||||||
'shares.creatorId',
|
|
||||||
'shares.spaceId',
|
|
||||||
'shares.workspaceId',
|
|
||||||
'shares.createdAt',
|
|
||||||
'shares.updatedAt',
|
|
||||||
])
|
|
||||||
.where('shares.id', 'is not', null)
|
|
||||||
.orderBy('page_hierarchy.level', 'asc')
|
|
||||||
.executeTakeFirst();
|
.executeTakeFirst();
|
||||||
|
|
||||||
if (!share || share.workspaceId != workspaceId) {
|
if (!share || share.workspaceId !== workspaceId) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (share.level === 1 && !share.includeSubPages) {
|
if ((share.level as number) > 0 && !share.includeSubPages) {
|
||||||
// we can only show a page if its shared ancestor permits it
|
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: share.id,
|
id: share.shareId,
|
||||||
key: share.key,
|
key: share.shareKey,
|
||||||
includeSubPages: share.includeSubPages,
|
includeSubPages: share.includeSubPages,
|
||||||
searchIndexing: share.searchIndexing,
|
searchIndexing: share.searchIndexing,
|
||||||
pageId: share.pageId,
|
pageId: share.id,
|
||||||
creatorId: share.creatorId,
|
creatorId: share.creatorId,
|
||||||
spaceId: share.spaceId,
|
spaceId: share.spaceId,
|
||||||
workspaceId: share.workspaceId,
|
workspaceId: share.workspaceId,
|
||||||
createdAt: share.createdAt,
|
createdAt: share.createdAt,
|
||||||
level: share.level,
|
level: share.level,
|
||||||
sharedPage: {
|
sharedPage: {
|
||||||
id: share.sharedPageId,
|
id: share.id,
|
||||||
slugId: share.sharedPageSlugId,
|
slugId: share.slugId,
|
||||||
title: share.sharedPageTitle,
|
title: share.title,
|
||||||
icon: share.sharedPageIcon,
|
icon: share.icon,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {Transform, TransformFnParams} from "class-transformer";
|
|||||||
|
|
||||||
export class CreateSpaceDto {
|
export class CreateSpaceDto {
|
||||||
@MinLength(2)
|
@MinLength(2)
|
||||||
@MaxLength(50)
|
@MaxLength(100)
|
||||||
@IsString()
|
@IsString()
|
||||||
@Transform(({ value }: TransformFnParams) => value?.trim())
|
@Transform(({ value }: TransformFnParams) => value?.trim())
|
||||||
name: string;
|
name: string;
|
||||||
@@ -19,7 +19,7 @@ export class CreateSpaceDto {
|
|||||||
description?: string;
|
description?: string;
|
||||||
|
|
||||||
@MinLength(2)
|
@MinLength(2)
|
||||||
@MaxLength(50)
|
@MaxLength(100)
|
||||||
@IsAlphanumeric()
|
@IsAlphanumeric()
|
||||||
slug: string;
|
slug: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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();
|
|
||||||
}
|
|
||||||
@@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -293,24 +293,18 @@ export class PageRepo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getRecentPages(userId: string, pagination: PaginationOptions) {
|
async getRecentPages(userId: string, pagination: PaginationOptions) {
|
||||||
const userSpaceIds = await this.spaceMemberRepo.getUserSpaceIds(userId);
|
|
||||||
|
|
||||||
const query = this.db
|
const query = this.db
|
||||||
.selectFrom('pages')
|
.selectFrom('pages')
|
||||||
.select(this.baseFields)
|
.select(this.baseFields)
|
||||||
.select((eb) => this.withSpace(eb))
|
.select((eb) => this.withSpace(eb))
|
||||||
.where('spaceId', 'in', userSpaceIds)
|
.where('spaceId', 'in', this.spaceMemberRepo.getUserSpaceIdsQuery(userId))
|
||||||
.where('deletedAt', 'is', null)
|
.where('deletedAt', 'is', null)
|
||||||
.orderBy('updatedAt', 'desc');
|
.orderBy('updatedAt', 'desc');
|
||||||
|
|
||||||
const hasEmptyIds = userSpaceIds.length === 0;
|
return executeWithPagination(query, {
|
||||||
const result = executeWithPagination(query, {
|
|
||||||
page: pagination.page,
|
page: pagination.page,
|
||||||
perPage: pagination.limit,
|
perPage: pagination.limit,
|
||||||
hasEmptyIds,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getDeletedPagesInSpace(spaceId: string, pagination: PaginationOptions) {
|
async getDeletedPagesInSpace(spaceId: string, pagination: PaginationOptions) {
|
||||||
|
|||||||
@@ -137,25 +137,19 @@ export class ShareRepo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getShares(userId: string, pagination: PaginationOptions) {
|
async getShares(userId: string, pagination: PaginationOptions) {
|
||||||
const userSpaceIds = await this.spaceMemberRepo.getUserSpaceIds(userId);
|
|
||||||
|
|
||||||
const query = this.db
|
const query = this.db
|
||||||
.selectFrom('shares')
|
.selectFrom('shares')
|
||||||
.select(this.baseFields)
|
.select(this.baseFields)
|
||||||
.select((eb) => this.withPage(eb))
|
.select((eb) => this.withPage(eb))
|
||||||
.select((eb) => this.withSpace(eb, userId))
|
.select((eb) => this.withSpace(eb, userId))
|
||||||
.select((eb) => this.withCreator(eb))
|
.select((eb) => this.withCreator(eb))
|
||||||
.where('spaceId', 'in', userSpaceIds)
|
.where('spaceId', 'in', this.spaceMemberRepo.getUserSpaceIdsQuery(userId))
|
||||||
.orderBy('updatedAt', 'desc');
|
.orderBy('updatedAt', 'desc');
|
||||||
|
|
||||||
const hasEmptyIds = userSpaceIds.length === 0;
|
return executeWithPagination(query, {
|
||||||
const result = executeWithPagination(query, {
|
|
||||||
page: pagination.page,
|
page: pagination.page,
|
||||||
perPage: pagination.limit,
|
perPage: pagination.limit,
|
||||||
hasEmptyIds,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
withPage(eb: ExpressionBuilder<DB, 'shares'>) {
|
withPage(eb: ExpressionBuilder<DB, 'shares'>) {
|
||||||
|
|||||||
@@ -209,34 +209,33 @@ export class SpaceMemberRepo {
|
|||||||
return roles;
|
return roles;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUserSpaceIds(userId: string): Promise<string[]> {
|
getUserSpaceIdsQuery(userId: string) {
|
||||||
const membership = await this.db
|
return this.db
|
||||||
.selectFrom('spaceMembers')
|
.selectFrom('spaceMembers')
|
||||||
.innerJoin('spaces', 'spaces.id', 'spaceMembers.spaceId')
|
.innerJoin('spaces', 'spaces.id', 'spaceMembers.spaceId')
|
||||||
.select(['spaces.id'])
|
.select('spaces.id')
|
||||||
.where('userId', '=', userId)
|
.where('userId', '=', userId)
|
||||||
.union(
|
.union(
|
||||||
this.db
|
this.db
|
||||||
.selectFrom('spaceMembers')
|
.selectFrom('spaceMembers')
|
||||||
.innerJoin('groupUsers', 'groupUsers.groupId', 'spaceMembers.groupId')
|
.innerJoin('groupUsers', 'groupUsers.groupId', 'spaceMembers.groupId')
|
||||||
.innerJoin('spaces', 'spaces.id', 'spaceMembers.spaceId')
|
.innerJoin('spaces', 'spaces.id', 'spaceMembers.spaceId')
|
||||||
.select(['spaces.id'])
|
.select('spaces.id')
|
||||||
.where('groupUsers.userId', '=', userId),
|
.where('groupUsers.userId', '=', userId),
|
||||||
)
|
);
|
||||||
.execute();
|
}
|
||||||
|
|
||||||
|
async getUserSpaceIds(userId: string): Promise<string[]> {
|
||||||
|
const membership = await this.getUserSpaceIdsQuery(userId).execute();
|
||||||
return membership.map((space) => space.id);
|
return membership.map((space) => space.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUserSpaces(userId: string, pagination: PaginationOptions) {
|
async getUserSpaces(userId: string, pagination: PaginationOptions) {
|
||||||
const userSpaceIds = await this.getUserSpaceIds(userId);
|
|
||||||
|
|
||||||
let query = this.db
|
let query = this.db
|
||||||
.selectFrom('spaces')
|
.selectFrom('spaces')
|
||||||
.selectAll()
|
.selectAll()
|
||||||
.select((eb) => [this.spaceRepo.withMemberCount(eb)])
|
.select((eb) => [this.spaceRepo.withMemberCount(eb)])
|
||||||
//.where('workspaceId', '=', workspaceId)
|
.where('id', 'in', this.getUserSpaceIdsQuery(userId))
|
||||||
.where('id', 'in', userSpaceIds)
|
|
||||||
.orderBy('createdAt', 'asc');
|
.orderBy('createdAt', 'asc');
|
||||||
|
|
||||||
if (pagination.query) {
|
if (pagination.query) {
|
||||||
@@ -253,14 +252,9 @@ export class SpaceMemberRepo {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasEmptyIds = userSpaceIds.length === 0;
|
return executeWithPagination(query, {
|
||||||
|
|
||||||
const result = executeWithPagination(query, {
|
|
||||||
page: pagination.page,
|
page: pagination.page,
|
||||||
perPage: pagination.limit,
|
perPage: pagination.limit,
|
||||||
hasEmptyIds,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-30
@@ -197,12 +197,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;
|
||||||
@@ -366,27 +360,6 @@ 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;
|
||||||
@@ -398,10 +371,7 @@ 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;
|
|
||||||
pages: Pages;
|
pages: Pages;
|
||||||
shares: Shares;
|
shares: Shares;
|
||||||
spaceMembers: SpaceMembers;
|
spaceMembers: SpaceMembers;
|
||||||
|
|||||||
@@ -9,10 +9,7 @@ import {
|
|||||||
FileTasks,
|
FileTasks,
|
||||||
Groups,
|
Groups,
|
||||||
GroupUsers,
|
GroupUsers,
|
||||||
PageAccess,
|
|
||||||
PageHierarchy,
|
|
||||||
PageHistory,
|
PageHistory,
|
||||||
PagePermissions,
|
|
||||||
Pages,
|
Pages,
|
||||||
Shares,
|
Shares,
|
||||||
SpaceMembers,
|
SpaceMembers,
|
||||||
@@ -35,11 +32,8 @@ export interface DbInterface {
|
|||||||
fileTasks: FileTasks;
|
fileTasks: FileTasks;
|
||||||
groups: Groups;
|
groups: Groups;
|
||||||
groupUsers: GroupUsers;
|
groupUsers: GroupUsers;
|
||||||
pageAccess: PageAccess;
|
|
||||||
pageHierarchy: PageHierarchy;
|
|
||||||
pageEmbeddings: PageEmbeddings;
|
pageEmbeddings: PageEmbeddings;
|
||||||
pageHistory: PageHistory;
|
pageHistory: PageHistory;
|
||||||
pagePermissions: PagePermissions;
|
|
||||||
pages: Pages;
|
pages: Pages;
|
||||||
shares: Shares;
|
shares: Shares;
|
||||||
spaceMembers: SpaceMembers;
|
spaceMembers: SpaceMembers;
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -134,17 +131,3 @@ export type UpdatableApiKey = Updateable<Omit<ApiKeys, 'id'>>;
|
|||||||
export type PageEmbedding = Selectable<PageEmbeddings>;
|
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)
|
|
||||||
export type PageHierarchy = Selectable<_PageHierarchy>;
|
|
||||||
export type InsertablePageHierarchy = Insertable<_PageHierarchy>;
|
|
||||||
|
|
||||||
// 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...1d1ab6cf81
@@ -105,7 +105,7 @@ export class EnvironmentVariables {
|
|||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@ValidateIf((obj) => obj.AI_DRIVER)
|
@ValidateIf((obj) => obj.AI_DRIVER)
|
||||||
@IsIn(['openai', 'gemini', 'ollama'])
|
@IsIn(['openai', 'openai-compatible', 'gemini', 'ollama'])
|
||||||
@IsString()
|
@IsString()
|
||||||
AI_DRIVER: string;
|
AI_DRIVER: string;
|
||||||
|
|
||||||
@@ -117,11 +117,10 @@ export class EnvironmentVariables {
|
|||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@ValidateIf((obj) => obj.AI_EMBEDDING_DIMENSION)
|
@ValidateIf((obj) => obj.AI_EMBEDDING_DIMENSION)
|
||||||
@IsIn(['768', '1024', '1536', '2000'])
|
@IsIn(['768', '1024', '1536', '2000', '3072'])
|
||||||
@IsString()
|
@IsString()
|
||||||
AI_EMBEDDING_DIMENSION: string;
|
AI_EMBEDDING_DIMENSION: string;
|
||||||
|
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@ValidateIf((obj) => obj.AI_DRIVER)
|
@ValidateIf((obj) => obj.AI_DRIVER)
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -129,13 +128,20 @@ export class EnvironmentVariables {
|
|||||||
AI_COMPLETION_MODEL: string;
|
AI_COMPLETION_MODEL: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@ValidateIf((obj) => obj.AI_DRIVER && obj.AI_DRIVER === 'openai')
|
@ValidateIf(
|
||||||
|
(obj) =>
|
||||||
|
obj.AI_DRIVER && ['openai', 'openai-compatible'].includes(obj.AI_DRIVER),
|
||||||
|
)
|
||||||
@IsString()
|
@IsString()
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
OPENAI_API_KEY: string;
|
OPENAI_API_KEY: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@ValidateIf((obj) => obj.AI_DRIVER && obj.OPENAI_API_URL && obj.AI_DRIVER === 'openai')
|
@ValidateIf(
|
||||||
|
(obj) =>
|
||||||
|
obj.AI_DRIVER === 'openai-compatible' ||
|
||||||
|
(obj.AI_DRIVER === 'openai' && obj.OPENAI_API_URL),
|
||||||
|
)
|
||||||
@IsUrl({ protocols: ['http', 'https'], require_tld: false })
|
@IsUrl({ protocols: ['http', 'https'], require_tld: false })
|
||||||
OPENAI_API_URL: string;
|
OPENAI_API_URL: string;
|
||||||
|
|
||||||
|
|||||||
@@ -10,46 +10,59 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import SpaceAbilityFactory from '../../core/casl/abilities/space-ability.factory';
|
import SpaceAbilityFactory from '../../core/casl/abilities/space-ability.factory';
|
||||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||||
import { User } from '@docmost/db/types/entity.types';
|
import { User, Workspace } from '@docmost/db/types/entity.types';
|
||||||
import {
|
import {
|
||||||
SpaceCaslAction,
|
SpaceCaslAction,
|
||||||
SpaceCaslSubject,
|
SpaceCaslSubject,
|
||||||
} from '../../core/casl/interfaces/space-ability.type';
|
} from '../../core/casl/interfaces/space-ability.type';
|
||||||
|
import {
|
||||||
|
WorkspaceCaslAction,
|
||||||
|
WorkspaceCaslSubject,
|
||||||
|
} from '../../core/casl/interfaces/workspace-ability.type';
|
||||||
|
import WorkspaceAbilityFactory from '../../core/casl/abilities/workspace-ability.factory';
|
||||||
|
import { AuthWorkspace } from '../../common/decorators/auth-workspace.decorator';
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
import { KyselyDB } from '@docmost/db/types/kysely.types';
|
||||||
import { AuthUser } from '../../common/decorators/auth-user.decorator';
|
import { AuthUser } from '../../common/decorators/auth-user.decorator';
|
||||||
import { FileTaskIdDto } from './dto/file-task-dto';
|
import { FileTaskIdDto } from './dto/file-task-dto';
|
||||||
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
|
||||||
|
import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
|
||||||
|
import { executeWithPagination } from '@docmost/db/pagination/pagination';
|
||||||
|
|
||||||
@Controller('file-tasks')
|
@Controller('file-tasks')
|
||||||
export class FileTaskController {
|
export class FileTaskController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly spaceMemberRepo: SpaceMemberRepo,
|
|
||||||
private readonly spaceAbility: SpaceAbilityFactory,
|
private readonly spaceAbility: SpaceAbilityFactory,
|
||||||
|
private readonly workspaceAbility: WorkspaceAbilityFactory,
|
||||||
|
private readonly spaceMemberRepo: SpaceMemberRepo,
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
@Post()
|
@Post()
|
||||||
async getFileTasks(@AuthUser() user: User) {
|
async getFileTasks(
|
||||||
const userSpaceIds = await this.spaceMemberRepo.getUserSpaceIds(user.id);
|
@Body() pagination: PaginationOptions,
|
||||||
|
@AuthUser() user: User,
|
||||||
if (!userSpaceIds || userSpaceIds.length === 0) {
|
@AuthWorkspace() workspace: Workspace,
|
||||||
return [];
|
) {
|
||||||
|
const ability = this.workspaceAbility.createForUser(user, workspace);
|
||||||
|
if (
|
||||||
|
ability.cannot(WorkspaceCaslAction.Manage, WorkspaceCaslSubject.Settings)
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException();
|
||||||
}
|
}
|
||||||
|
|
||||||
const fileTasks = await this.db
|
const query = this.db
|
||||||
.selectFrom('fileTasks')
|
.selectFrom('fileTasks')
|
||||||
.selectAll()
|
.selectAll()
|
||||||
.where('spaceId', 'in', userSpaceIds)
|
.where('spaceId', 'in', this.spaceMemberRepo.getUserSpaceIdsQuery(user.id))
|
||||||
.execute();
|
.orderBy('createdAt', 'desc');
|
||||||
|
|
||||||
if (!fileTasks) {
|
return executeWithPagination(query, {
|
||||||
throw new NotFoundException('File task not found');
|
page: pagination.page,
|
||||||
}
|
perPage: pagination.limit,
|
||||||
|
});
|
||||||
return fileTasks;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@braintree/sanitize-url": "^7.1.0",
|
"@braintree/sanitize-url": "^7.1.0",
|
||||||
|
"@casl/ability": "^6.7.5",
|
||||||
"@docmost/editor-ext": "workspace:*",
|
"@docmost/editor-ext": "workspace:*",
|
||||||
"@floating-ui/dom": "^1.7.3",
|
"@floating-ui/dom": "^1.7.3",
|
||||||
"@hocuspocus/extension-redis": "^2.15.3",
|
"@hocuspocus/extension-redis": "^2.15.3",
|
||||||
|
|||||||
Generated
+744
-644
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user