@open-mercato/documents 0.9.1-develop.7574.1.837288eec1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contentSecurityPolicy.js +23 -0
- package/dist/contentSecurityPolicy.js.map +7 -0
- package/dist/modules/documents/api/[id]/comments/access-check/route.js +13 -6
- package/dist/modules/documents/api/[id]/comments/access-check/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/comments/route.js +2 -0
- package/dist/modules/documents/api/[id]/comments/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/content/route.js +2 -0
- package/dist/modules/documents/api/[id]/content/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/route.js +3 -0
- package/dist/modules/documents/api/[id]/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/shares/route.js +2 -0
- package/dist/modules/documents/api/[id]/shares/route.js.map +2 -2
- package/dist/modules/documents/api/[id]/versions/route.js +2 -0
- package/dist/modules/documents/api/[id]/versions/route.js.map +2 -2
- package/dist/modules/documents/api/_shared.js +10 -27
- package/dist/modules/documents/api/_shared.js.map +3 -3
- package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js +3 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js +1 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js +15 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js +15 -1
- package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js +20 -8
- package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js +3 -0
- package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/editorTypes.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js +46 -0
- package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js.map +7 -0
- package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js +14 -6
- package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js.map +2 -2
- package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js +3 -0
- package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js.map +2 -2
- package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js +3 -0
- package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js.map +2 -2
- package/dist/modules/documents/backend/documents/components/TemplatePreview.js +3 -0
- package/dist/modules/documents/backend/documents/components/TemplatePreview.js.map +2 -2
- package/dist/modules/documents/commands/comments.js +2 -2
- package/dist/modules/documents/commands/comments.js.map +2 -2
- package/dist/modules/documents/commands/folders.js +1 -0
- package/dist/modules/documents/commands/folders.js.map +2 -2
- package/dist/modules/documents/commands/interceptors.js +11 -0
- package/dist/modules/documents/commands/interceptors.js.map +2 -2
- package/dist/modules/documents/data/attachment-access.js +84 -0
- package/dist/modules/documents/data/attachment-access.js.map +7 -0
- package/dist/modules/documents/data/validators.js +11 -0
- package/dist/modules/documents/data/validators.js.map +2 -2
- package/dist/modules/documents/lib/actor.js +32 -0
- package/dist/modules/documents/lib/actor.js.map +7 -0
- package/dist/modules/documents/lib/collabMaterializer.js +52 -9
- package/dist/modules/documents/lib/collabMaterializer.js.map +2 -2
- package/dist/modules/documents/lib/collabPersistence.js +13 -0
- package/dist/modules/documents/lib/collabPersistence.js.map +7 -0
- package/dist/modules/documents/lib/permissions.js +35 -2
- package/dist/modules/documents/lib/permissions.js.map +2 -2
- package/dist/modules/documents/widgets/injection/related-documents/widget.client.js +3 -2
- package/dist/modules/documents/widgets/injection/related-documents/widget.client.js.map +2 -2
- package/dist/modules/documents/widgets/injection-table.js +12 -3
- package/dist/modules/documents/widgets/injection-table.js.map +2 -2
- package/dist/server/documents-collab-server.js +74 -1
- package/dist/server/documents-collab-server.js.map +2 -2
- package/jest.config.cjs +1 -1
- package/package.json +37 -37
- package/server/documents-collab-server.ts +79 -0
- package/src/contentSecurityPolicy.ts +21 -0
- package/src/modules/documents/api/[id]/comments/access-check/route.ts +13 -6
- package/src/modules/documents/api/[id]/comments/route.ts +2 -0
- package/src/modules/documents/api/[id]/content/route.ts +2 -0
- package/src/modules/documents/api/[id]/route.ts +3 -0
- package/src/modules/documents/api/[id]/shares/route.ts +2 -0
- package/src/modules/documents/api/[id]/versions/route.ts +2 -0
- package/src/modules/documents/api/_shared.ts +10 -36
- package/src/modules/documents/backend/documents/[id]/DocumentCanvas.tsx +3 -1
- package/src/modules/documents/backend/documents/[id]/DocumentEditorIsland.tsx +4 -1
- package/src/modules/documents/backend/documents/[id]/DocumentEditorSurface.tsx +19 -1
- package/src/modules/documents/backend/documents/[id]/DocumentPageClient.tsx +14 -0
- package/src/modules/documents/backend/documents/[id]/VersionHistoryPanel.tsx +23 -8
- package/src/modules/documents/backend/documents/[id]/VersionPreviewDialog.tsx +3 -0
- package/src/modules/documents/backend/documents/[id]/editorTypes.ts +1 -0
- package/src/modules/documents/backend/documents/[id]/saveCollaborativeContent.ts +43 -0
- package/src/modules/documents/backend/documents/[id]/useDocumentComments.ts +17 -7
- package/src/modules/documents/backend/documents/[id]/useDocumentEditor.ts +3 -0
- package/src/modules/documents/backend/documents/components/TemplateBodyEditor.tsx +3 -0
- package/src/modules/documents/backend/documents/components/TemplatePreview.tsx +3 -0
- package/src/modules/documents/commands/comments.ts +2 -2
- package/src/modules/documents/commands/folders.ts +1 -3
- package/src/modules/documents/commands/interceptors.ts +11 -0
- package/src/modules/documents/data/attachment-access.ts +83 -0
- package/src/modules/documents/data/validators.ts +12 -0
- package/src/modules/documents/lib/actor.ts +39 -0
- package/src/modules/documents/lib/collabMaterializer.ts +62 -11
- package/src/modules/documents/lib/collabPersistence.ts +10 -0
- package/src/modules/documents/lib/permissions.ts +52 -0
- package/src/modules/documents/widgets/injection/related-documents/widget.client.tsx +3 -2
- package/src/modules/documents/widgets/injection-table.ts +17 -3
|
@@ -65,6 +65,7 @@ type VersionHistoryPanelProps = {
|
|
|
65
65
|
*/
|
|
66
66
|
contentUpdatedAt?: string | null
|
|
67
67
|
onRestored?: () => void | Promise<void>
|
|
68
|
+
onBeforeSnapshot?: () => Promise<boolean>
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
export { resolveVersionRestoreCapability } from './componentCapabilities'
|
|
@@ -75,6 +76,7 @@ export function VersionHistoryPanel({
|
|
|
75
76
|
tier,
|
|
76
77
|
canRestore,
|
|
77
78
|
onRestored,
|
|
79
|
+
onBeforeSnapshot,
|
|
78
80
|
}: VersionHistoryPanelProps) {
|
|
79
81
|
const t = useT()
|
|
80
82
|
const mayRestore = resolveVersionRestoreCapability(canRestore, tier)
|
|
@@ -85,6 +87,7 @@ export function VersionHistoryPanel({
|
|
|
85
87
|
const [restoringVersionId, setRestoringVersionId] = React.useState<string | null>(null)
|
|
86
88
|
const [previewVersionId, setPreviewVersionId] = React.useState<string | null>(null)
|
|
87
89
|
const restoreInFlight = React.useRef(false)
|
|
90
|
+
const snapshotInFlight = React.useRef(false)
|
|
88
91
|
const reloadSequence = React.useRef(0)
|
|
89
92
|
const activeReload = React.useRef<AbortController | null>(null)
|
|
90
93
|
const activeDocumentId = React.useRef<string | null>(null)
|
|
@@ -141,16 +144,25 @@ export function VersionHistoryPanel({
|
|
|
141
144
|
}, [reload])
|
|
142
145
|
|
|
143
146
|
const handleSnapshot = React.useCallback(async () => {
|
|
144
|
-
if (!mayRestore) return
|
|
147
|
+
if (!mayRestore || snapshotInFlight.current) return
|
|
148
|
+
snapshotInFlight.current = true
|
|
145
149
|
setIsCreating(true)
|
|
146
150
|
const nextLabel = label.trim() || null
|
|
147
151
|
try {
|
|
148
152
|
await runMutation({
|
|
149
|
-
operation: () =>
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
153
|
+
operation: async () => {
|
|
154
|
+
if (onBeforeSnapshot && !(await onBeforeSnapshot())) {
|
|
155
|
+
throw new Error(t('documents.versions.error.save'))
|
|
156
|
+
}
|
|
157
|
+
if (currentDocumentIdRef.current !== documentId) {
|
|
158
|
+
throw new Error(t('documents.versions.error.save'))
|
|
159
|
+
}
|
|
160
|
+
return apiCallOrThrow(
|
|
161
|
+
`/api/documents/${encodeURIComponent(documentId)}/versions`,
|
|
162
|
+
{ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ label: nextLabel }) },
|
|
163
|
+
{ errorMessage: t('documents.versions.error.save') },
|
|
164
|
+
)
|
|
165
|
+
},
|
|
154
166
|
context: { formId: mutationContextId, resourceKind: 'documents.document_version', resourceId: documentId, retryLastMutation },
|
|
155
167
|
mutationPayload: { label: nextLabel },
|
|
156
168
|
})
|
|
@@ -162,8 +174,11 @@ export function VersionHistoryPanel({
|
|
|
162
174
|
} catch (error) {
|
|
163
175
|
if (currentDocumentIdRef.current !== documentId) return
|
|
164
176
|
flash(error instanceof Error ? error.message : t('documents.versions.error.save'), 'error')
|
|
165
|
-
} finally {
|
|
166
|
-
|
|
177
|
+
} finally {
|
|
178
|
+
snapshotInFlight.current = false
|
|
179
|
+
setIsCreating(false)
|
|
180
|
+
}
|
|
181
|
+
}, [documentId, label, mayRestore, mutationContextId, onBeforeSnapshot, reload, retryLastMutation, runMutation, t])
|
|
167
182
|
|
|
168
183
|
const handleRestore = React.useCallback(async (version: VersionPreview) => {
|
|
169
184
|
if (!mayRestore || restoreInFlight.current) return
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
3
|
import * as React from 'react'
|
|
4
|
+
import { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'
|
|
4
5
|
import { EditorContent, useEditor } from '@tiptap/react'
|
|
5
6
|
import { RotateCcw } from 'lucide-react'
|
|
6
7
|
import { apiCall } from '@open-mercato/ui/backend/utils/apiCall'
|
|
@@ -63,7 +64,9 @@ export function normalizeVersionPreview(
|
|
|
63
64
|
}
|
|
64
65
|
|
|
65
66
|
function ReadOnlyVersion({ contentHtml, fallbackLabel }: { contentHtml: string; fallbackLabel: string }) {
|
|
67
|
+
const nonce = useContentSecurityPolicyNonce()
|
|
66
68
|
const editor = useEditor({
|
|
69
|
+
injectNonce: nonce,
|
|
67
70
|
extensions: getDocumentEditorExtensions({ entityRefFallbackLabel: fallbackLabel }),
|
|
68
71
|
content: contentHtml,
|
|
69
72
|
editable: false,
|
|
@@ -20,6 +20,7 @@ export type DocumentEditorIslandProps = {
|
|
|
20
20
|
documentUpdatedAt?: string | null
|
|
21
21
|
readOnly: boolean
|
|
22
22
|
onEditorReady?: (editor: Editor | null) => void
|
|
23
|
+
onSaveReady?: (save: (() => Promise<boolean>) | null) => void
|
|
23
24
|
onComment?: (anchor: CommentAnchor) => void
|
|
24
25
|
onContentConflict?: () => void
|
|
25
26
|
onTitleChange?: (title: string, updatedAt: string | null) => void
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { CollabResources } from './editorTypes'
|
|
2
|
+
import { collabContentSaveResponseSchema } from '../../../data/validators'
|
|
3
|
+
import { COLLAB_CONTENT_SAVE_TIMEOUT_MS } from '../../../lib/collabPersistence'
|
|
4
|
+
|
|
5
|
+
export function saveCollaborativeContent(
|
|
6
|
+
resources: CollabResources,
|
|
7
|
+
signal: AbortSignal,
|
|
8
|
+
): Promise<boolean> {
|
|
9
|
+
const { provider } = resources
|
|
10
|
+
if (signal.aborted || !provider.synced || provider.configuration.websocketProvider.status !== 'connected') {
|
|
11
|
+
return Promise.resolve(false)
|
|
12
|
+
}
|
|
13
|
+
const requestId = crypto.randomUUID()
|
|
14
|
+
return new Promise<boolean>((resolve) => {
|
|
15
|
+
const finish = (saved: boolean) => {
|
|
16
|
+
clearTimeout(timer)
|
|
17
|
+
provider.off('stateless', onStateless)
|
|
18
|
+
provider.off('close', onFailure)
|
|
19
|
+
provider.off('disconnect', onFailure)
|
|
20
|
+
provider.off('destroy', onFailure)
|
|
21
|
+
signal.removeEventListener('abort', onFailure)
|
|
22
|
+
resolve(saved)
|
|
23
|
+
}
|
|
24
|
+
const onFailure = () => finish(false)
|
|
25
|
+
const onStateless = ({ payload }: { payload: string }) => {
|
|
26
|
+
let value: unknown
|
|
27
|
+
try { value = JSON.parse(payload) } catch { return }
|
|
28
|
+
const response = collabContentSaveResponseSchema.safeParse(value)
|
|
29
|
+
if (response.success && response.data.requestId === requestId) finish(response.data.saved)
|
|
30
|
+
}
|
|
31
|
+
const timer = setTimeout(onFailure, COLLAB_CONTENT_SAVE_TIMEOUT_MS)
|
|
32
|
+
provider.on('stateless', onStateless)
|
|
33
|
+
provider.on('close', onFailure)
|
|
34
|
+
provider.on('disconnect', onFailure)
|
|
35
|
+
provider.on('destroy', onFailure)
|
|
36
|
+
signal.addEventListener('abort', onFailure, { once: true })
|
|
37
|
+
try {
|
|
38
|
+
provider.sendStateless(JSON.stringify({ type: 'documents.content.save', requestId }))
|
|
39
|
+
} catch {
|
|
40
|
+
finish(false)
|
|
41
|
+
}
|
|
42
|
+
})
|
|
43
|
+
}
|
|
@@ -41,7 +41,7 @@ type GrantAccessDecision = 'share' | 'skip' | 'cancel'
|
|
|
41
41
|
|
|
42
42
|
type GrantAccessResolution =
|
|
43
43
|
| { cancelled: true }
|
|
44
|
-
| { cancelled: false; grantAccessTo?: string[] }
|
|
44
|
+
| { cancelled: false; grantAccessTo?: string[]; hasUnnotifiedMentions?: boolean }
|
|
45
45
|
|
|
46
46
|
export function useDocumentComments({ documentId, editor, canComment, canShare }: UseDocumentCommentsInput) {
|
|
47
47
|
const t = useT()
|
|
@@ -185,22 +185,29 @@ export function useDocumentComments({ documentId, editor, canComment, canShare }
|
|
|
185
185
|
)
|
|
186
186
|
if (!isCurrentSubmission()) return { cancelled: true }
|
|
187
187
|
if (!call.ok) throw new Error(t('documents.comments.error.save'))
|
|
188
|
-
const withoutAccess = readWithoutAccess(call.result)
|
|
188
|
+
const withoutAccess = readWithoutAccess(call.result).filter((user) => userIds.includes(user.userId))
|
|
189
189
|
if (withoutAccess.length === 0) return { cancelled: false }
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
190
|
+
const response = readRecord(call.result)
|
|
191
|
+
const shareableUserIds = new Set(
|
|
192
|
+
Array.isArray(response?.shareableUserIds)
|
|
193
|
+
? response.shareableUserIds.filter((value): value is string => typeof value === 'string').map((value) => value.toLowerCase())
|
|
194
|
+
: [],
|
|
195
|
+
)
|
|
196
|
+
const shareableUsers = withoutAccess.filter((user) => shareableUserIds.has(user.userId))
|
|
197
|
+
if (!canShare || shareableUsers.length === 0) {
|
|
198
|
+
return { cancelled: false, grantAccessTo: [], hasUnnotifiedMentions: true }
|
|
193
199
|
}
|
|
194
200
|
const pendingMentionNames = new Map(
|
|
195
201
|
activePendingMentions.map((mention) => [mention.userId.toLowerCase(), mention.name]),
|
|
196
202
|
)
|
|
197
|
-
const decision = await requestGrantAccess(
|
|
203
|
+
const decision = await requestGrantAccess(shareableUsers.map((user) => (
|
|
198
204
|
pendingMentionNames.get(user.userId) ?? user.label ?? labelFor(user.userId)
|
|
199
205
|
)))
|
|
200
206
|
if (decision === 'cancel' || !isCurrentSubmission()) return { cancelled: true }
|
|
201
207
|
return {
|
|
202
208
|
cancelled: false,
|
|
203
|
-
grantAccessTo: decision === 'share' ?
|
|
209
|
+
grantAccessTo: decision === 'share' ? shareableUsers.map((user) => user.userId) : [],
|
|
210
|
+
hasUnnotifiedMentions: decision === 'skip' || shareableUsers.length < withoutAccess.length,
|
|
204
211
|
}
|
|
205
212
|
}, [activePendingMentions, canShare, documentId, labelFor, requestGrantAccess, t])
|
|
206
213
|
|
|
@@ -237,6 +244,9 @@ export function useDocumentComments({ documentId, editor, canComment, canShare }
|
|
|
237
244
|
mutationPayload: { body: trimmedBody, parentCommentId, mentions },
|
|
238
245
|
})
|
|
239
246
|
if (!isCurrentSubmission()) return
|
|
247
|
+
if (grantResolution.hasUnnotifiedMentions) {
|
|
248
|
+
flash(t('documents.comments.grant.noAccessInfo'), 'info')
|
|
249
|
+
}
|
|
240
250
|
resetComposer()
|
|
241
251
|
await reload()
|
|
242
252
|
} catch (error) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"use client"
|
|
2
|
+
import { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'
|
|
2
3
|
|
|
3
4
|
import * as React from 'react'
|
|
4
5
|
import type { Editor } from '@tiptap/core'
|
|
@@ -62,6 +63,7 @@ function documentCounts(editor: Editor | null): EditorWordCount {
|
|
|
62
63
|
|
|
63
64
|
export function useDocumentEditor(input: UseDocumentEditorInput) {
|
|
64
65
|
const t = useT()
|
|
66
|
+
const nonce = useContentSecurityPolicyNonce()
|
|
65
67
|
const editorRef = React.useRef<Editor | null>(null)
|
|
66
68
|
const countTimerRef = React.useRef<number | null>(null)
|
|
67
69
|
const readOnlyRef = React.useRef(input.readOnly)
|
|
@@ -108,6 +110,7 @@ export function useDocumentEditor(input: UseDocumentEditorInput) {
|
|
|
108
110
|
}, [input.collabResources, input.editorMode, t])
|
|
109
111
|
|
|
110
112
|
const editor = useEditor({
|
|
113
|
+
injectNonce: nonce,
|
|
111
114
|
extensions,
|
|
112
115
|
content: input.editorMode === 'fallback' ? input.initialContentHtml : undefined,
|
|
113
116
|
editable: !input.readOnly,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
3
|
import * as React from 'react'
|
|
4
|
+
import { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'
|
|
4
5
|
import type { Editor } from '@tiptap/core'
|
|
5
6
|
import { EditorContent, useEditor, useEditorState } from '@tiptap/react'
|
|
6
7
|
import { Bold, Heading1, Heading2, Italic, List, ListOrdered } from 'lucide-react'
|
|
@@ -35,9 +36,11 @@ export function TemplateBodyEditor({ bodyHtml, tokenOptions, onChange }: {
|
|
|
35
36
|
onChange: (html: string) => void
|
|
36
37
|
}) {
|
|
37
38
|
const t = useT()
|
|
39
|
+
const nonce = useContentSecurityPolicyNonce()
|
|
38
40
|
const editorLabelId = React.useId()
|
|
39
41
|
const [token, setToken] = React.useState<string | undefined>()
|
|
40
42
|
const editor = useEditor({
|
|
43
|
+
injectNonce: nonce,
|
|
41
44
|
extensions: getDocumentEditorExtensions({
|
|
42
45
|
entityRefFallbackLabel: t('documents.editor.entityRef.fallbackLabel'),
|
|
43
46
|
}),
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
3
|
import * as React from 'react'
|
|
4
|
+
import { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'
|
|
4
5
|
import { EditorContent, useEditor } from '@tiptap/react'
|
|
5
6
|
import { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'
|
|
6
7
|
import { LoadingMessage } from '@open-mercato/ui/backend/detail'
|
|
@@ -9,7 +10,9 @@ import { getDocumentEditorExtensions } from '../../../lib/editorConfig'
|
|
|
9
10
|
import type { TemplatePreviewResult } from './templateUi'
|
|
10
11
|
|
|
11
12
|
function PreviewSurface({ html, fallbackLabel }: { html: string; fallbackLabel: string }) {
|
|
13
|
+
const nonce = useContentSecurityPolicyNonce()
|
|
12
14
|
const editor = useEditor({
|
|
15
|
+
injectNonce: nonce,
|
|
13
16
|
extensions: getDocumentEditorExtensions({ entityRefFallbackLabel: fallbackLabel }),
|
|
14
17
|
content: html,
|
|
15
18
|
editable: false,
|
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from '../data/validators'
|
|
22
22
|
import { DOCUMENTS_ENTITY_IDS } from '../lib/constants'
|
|
23
23
|
import { assertDocumentCommentCapacity } from '../lib/historyLimits'
|
|
24
|
-
import { resolveUserAccess } from '../lib/permissions'
|
|
24
|
+
import { resolveUserAccess, resolveUserDocumentTier } from '../lib/permissions'
|
|
25
25
|
import { resolveWatcherRecipients } from '../lib/watchers'
|
|
26
26
|
import type { DocumentsProjectionDescriptor } from './projection-types'
|
|
27
27
|
import {
|
|
@@ -641,7 +641,7 @@ export const createCommentCommand: CommandHandler<CommentCreateCommandInput, Com
|
|
|
641
641
|
for (const mentionedUserId of mentionUserIds) {
|
|
642
642
|
const grantIdentity = grantIdentityByUserId.get(mentionedUserId)
|
|
643
643
|
if (!grantIdentity || !canShare) continue
|
|
644
|
-
const tier = await
|
|
644
|
+
const tier = await resolveUserDocumentTier(em, input.documentId, input, mentionedUserId, ctx.container)
|
|
645
645
|
if (tier) continue
|
|
646
646
|
await assertUserPrincipal(ctx.container, input, mentionedUserId)
|
|
647
647
|
let share = await loadMentionShare(em, input, mentionedUserId, true)
|
|
@@ -257,9 +257,6 @@ const createFolderCommand: CommandHandler<FolderCreateCommandInput, FolderComman
|
|
|
257
257
|
if (existing && !existing.deletedAt) {
|
|
258
258
|
throw new CrudHttpError(409, { error: 'Record changed by another user' })
|
|
259
259
|
}
|
|
260
|
-
// Reviving a soft-deleted row adds an active folder just like a fresh
|
|
261
|
-
// insert, so both paths answer to the same organization-wide cap. Undo
|
|
262
|
-
// stays exempt: it only restores state the organization already held.
|
|
263
260
|
await assertOrganizationFolderCapacity(em, scope)
|
|
264
261
|
await assertWritableParent(em, input.parentFolderId ?? null, scope, actorUserId, features)
|
|
265
262
|
await assertValidPlacement(em, scope, null, input.parentFolderId ?? null)
|
|
@@ -486,6 +483,7 @@ const deleteFolderCommand: CommandHandler<FolderDeleteCommandInput, FolderComman
|
|
|
486
483
|
assertCommandFeature(features, 'documents.edit')
|
|
487
484
|
await assertFolderOwnerOrManager(undo.before!.ownerUserId, actorUserId, features)
|
|
488
485
|
assertVersionedSnapshot(folder, undo.after, DOCUMENTS_ENTITY_IDS.documentFolder)
|
|
486
|
+
await assertOrganizationFolderCapacity(em, scope)
|
|
489
487
|
await assertWritableParent(em, undo.before!.parentFolderId, scope, actorUserId, features)
|
|
490
488
|
await assertValidPlacement(em, scope, input.id, undo.before!.parentFolderId)
|
|
491
489
|
if (folder) {
|
|
@@ -10,6 +10,7 @@ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
|
10
10
|
import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
11
11
|
import { Document } from '../data/entities'
|
|
12
12
|
import { DOCUMENTS_ENTITY_IDS } from '../lib/constants'
|
|
13
|
+
import { resolveUserAccess } from '../lib/permissions'
|
|
13
14
|
import { resolveWatcherRecipients } from '../lib/watchers'
|
|
14
15
|
import type { DocumentsServiceContainer } from '../lib/platformServices'
|
|
15
16
|
import { emitDocumentsEvent } from '../events'
|
|
@@ -94,6 +95,11 @@ async function emitMentionProjection(
|
|
|
94
95
|
): Promise<void> {
|
|
95
96
|
try {
|
|
96
97
|
const notificationService = resolveDocumentsNotificationService(context.container)
|
|
98
|
+
const em = context.container.resolve('em') as EntityManager
|
|
99
|
+
if (!await resolveUserAccess(em, descriptor.documentId, {
|
|
100
|
+
tenantId: descriptor.tenantId,
|
|
101
|
+
organizationId: descriptor.organizationId,
|
|
102
|
+
}, descriptor.recipientUserId, context.container)) return
|
|
97
103
|
await notificationService.create(
|
|
98
104
|
{
|
|
99
105
|
recipientUserId: descriptor.recipientUserId,
|
|
@@ -136,6 +142,11 @@ async function emitWatchProjection(
|
|
|
136
142
|
): Promise<void> {
|
|
137
143
|
try {
|
|
138
144
|
const notificationService = resolveDocumentsNotificationService(context.container)
|
|
145
|
+
const em = context.container.resolve('em') as EntityManager
|
|
146
|
+
if (!await resolveUserAccess(em, descriptor.documentId, {
|
|
147
|
+
tenantId: descriptor.tenantId,
|
|
148
|
+
organizationId: descriptor.organizationId,
|
|
149
|
+
}, descriptor.recipientUserId, context.container)) return
|
|
139
150
|
await notificationService.create(
|
|
140
151
|
{
|
|
141
152
|
recipientUserId: descriptor.recipientUserId,
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
3
|
+
import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
4
|
+
import type { AttachmentAccessInput, AttachmentAccessResolver, ProtectedAttachmentTarget } from '@open-mercato/core/modules/attachments'
|
|
5
|
+
import { resolveActorUserId } from '../lib/actor'
|
|
6
|
+
import { deriveDocumentCapabilities, type DocumentCapabilities } from '../lib/capabilities'
|
|
7
|
+
import { loadScopedDocument, resolveActiveSubjectRoleIds, resolvePermission } from '../lib/permissions'
|
|
8
|
+
|
|
9
|
+
const ownerIdSchema = z.string().uuid()
|
|
10
|
+
const resolverId = 'documents.document-attachments'
|
|
11
|
+
|
|
12
|
+
async function capabilitiesForDocument(input: AttachmentAccessInput, documentId: string): Promise<DocumentCapabilities | null> {
|
|
13
|
+
const { subject, container, cache, signal } = input
|
|
14
|
+
const { tenantId, organizationId } = subject
|
|
15
|
+
if (!tenantId || !organizationId || !ownerIdSchema.safeParse(documentId).success || signal.aborted) return null
|
|
16
|
+
let actorUserId: string
|
|
17
|
+
try {
|
|
18
|
+
actorUserId = resolveActorUserId(subject.auth)
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (isCrudHttpError(error) && error.status === 403) return null
|
|
21
|
+
throw error
|
|
22
|
+
}
|
|
23
|
+
const principalKey = JSON.stringify([subject.auth.sub, tenantId, organizationId])
|
|
24
|
+
const cacheKey = JSON.stringify(['document', principalKey, documentId])
|
|
25
|
+
const cached = cache.get(cacheKey) as Promise<DocumentCapabilities | null> | undefined
|
|
26
|
+
if (cached) return cached
|
|
27
|
+
const pending = (async () => {
|
|
28
|
+
const em = container.resolve<EntityManager>('em')
|
|
29
|
+
const document = await loadScopedDocument(em, documentId, { tenantId, organizationId })
|
|
30
|
+
if (!document || signal.aborted) return null
|
|
31
|
+
const roleKey = JSON.stringify(['roles', principalKey])
|
|
32
|
+
let roles = cache.get(roleKey) as Promise<string[]> | undefined
|
|
33
|
+
if (!roles) {
|
|
34
|
+
roles = resolveActiveSubjectRoleIds(container, { tenantId, organizationId }, subject.auth.sub)
|
|
35
|
+
cache.set(roleKey, roles)
|
|
36
|
+
}
|
|
37
|
+
const projectedAuth = {
|
|
38
|
+
...subject.auth,
|
|
39
|
+
userId: actorUserId,
|
|
40
|
+
tenantId, orgId: organizationId, organizationId,
|
|
41
|
+
resolvedRoleIds: await roles,
|
|
42
|
+
features: [...subject.userFeatures],
|
|
43
|
+
isSuperAdmin: subject.isSuperAdmin,
|
|
44
|
+
}
|
|
45
|
+
if (signal.aborted) return null
|
|
46
|
+
const relationshipTier = await resolvePermission(em, documentId, projectedAuth)
|
|
47
|
+
return deriveDocumentCapabilities({
|
|
48
|
+
relationshipTier,
|
|
49
|
+
managerOverride: subject.userFeatures.includes('documents.manage'),
|
|
50
|
+
archived: document.archivedAt !== null && document.archivedAt !== undefined,
|
|
51
|
+
userFeatures: subject.userFeatures,
|
|
52
|
+
})
|
|
53
|
+
})()
|
|
54
|
+
cache.set(cacheKey, pending)
|
|
55
|
+
return pending
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const attachmentAccessResolvers: AttachmentAccessResolver[] = [{
|
|
59
|
+
id: resolverId,
|
|
60
|
+
targetPartition: '*',
|
|
61
|
+
targetEntity: 'documents:document',
|
|
62
|
+
async resolve(input) {
|
|
63
|
+
const targets = input.targets.filter((target) => target.entityId === 'documents:document')
|
|
64
|
+
if (targets.some((target) => !ownerIdSchema.safeParse(target.recordId).success)) {
|
|
65
|
+
return { ok: false, status: 404, reason: 'document_not_found' }
|
|
66
|
+
}
|
|
67
|
+
const requireEvery = input.action !== 'read' && input.action !== 'render'
|
|
68
|
+
let visible = false
|
|
69
|
+
for (const target of targets) {
|
|
70
|
+
const capabilities = await capabilitiesForDocument(input, target.recordId)
|
|
71
|
+
const allowed = input.action === 'delete' || input.action === 'reassign'
|
|
72
|
+
? capabilities?.canEdit === true
|
|
73
|
+
: capabilities?.canView === true
|
|
74
|
+
if (!allowed && requireEvery) return { ok: false, status: 404, reason: 'document_not_found' }
|
|
75
|
+
if (allowed) visible = true
|
|
76
|
+
}
|
|
77
|
+
return visible ? { ok: true } : { ok: false, status: 404, reason: 'document_not_found' }
|
|
78
|
+
},
|
|
79
|
+
}]
|
|
80
|
+
|
|
81
|
+
export const protectedAttachmentTargets: ProtectedAttachmentTarget[] = [{
|
|
82
|
+
resolverId, targetPartition: '*', targetEntity: 'documents:document',
|
|
83
|
+
}]
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
|
+
|
|
2
3
|
import {
|
|
3
4
|
DOCUMENTS_MAX_CONTENT_HTML_BYTES,
|
|
4
5
|
DOCUMENTS_MAX_CONTENT_TEXT_BYTES,
|
|
@@ -7,6 +8,17 @@ import {
|
|
|
7
8
|
import { containsCanonicalUuid } from '../lib/displayLabels'
|
|
8
9
|
import { DOCUMENT_VERSION_LABEL_MAX_LENGTH } from '../lib/versionLabels'
|
|
9
10
|
|
|
11
|
+
export const collabContentSaveRequestSchema = z.object({
|
|
12
|
+
type: z.literal('documents.content.save'),
|
|
13
|
+
requestId: z.string().uuid(),
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
export const collabContentSaveResponseSchema = z.object({
|
|
17
|
+
type: z.literal('documents.content.saved'),
|
|
18
|
+
requestId: z.string().uuid(),
|
|
19
|
+
saved: z.boolean(),
|
|
20
|
+
})
|
|
21
|
+
|
|
10
22
|
const uuid = () => z.string().uuid('documents.validation.common.invalidUuid')
|
|
11
23
|
|
|
12
24
|
function blankStringToNull(value: unknown): unknown {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import type { AuthContext } from '@open-mercato/shared/lib/auth/server'
|
|
3
|
+
import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
4
|
+
|
|
5
|
+
const actorUuidSchema = z.string().uuid()
|
|
6
|
+
|
|
7
|
+
function normalizeActorUuid(value: unknown): string | null {
|
|
8
|
+
if (typeof value !== 'string') return null
|
|
9
|
+
const normalized = value.trim()
|
|
10
|
+
return actorUuidSchema.safeParse(normalized).success ? normalized : null
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function isApiKeyAuth(auth: NonNullable<AuthContext>): boolean {
|
|
14
|
+
return auth.isApiKey === true || auth.sub.trim().startsWith('api_key:')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function resolveActorUserId(auth: NonNullable<AuthContext>): string {
|
|
18
|
+
const subject = auth.sub.trim()
|
|
19
|
+
if (isApiKeyAuth(auth)) {
|
|
20
|
+
// `keyId` is populated only by successful API-key authentication. Do not
|
|
21
|
+
// recover an actor by parsing an arbitrary prefixed subject when that
|
|
22
|
+
// validated field is absent, malformed, or disagrees with the subject.
|
|
23
|
+
const keyId = normalizeActorUuid(auth.keyId)
|
|
24
|
+
if (!keyId || subject !== `api_key:${keyId}`) {
|
|
25
|
+
throw new CrudHttpError(403, { error: 'api.errors.forbidden' })
|
|
26
|
+
}
|
|
27
|
+
if (auth.userId === undefined || auth.userId === null) return keyId
|
|
28
|
+
const backingUserId = normalizeActorUuid(auth.userId)
|
|
29
|
+
if (backingUserId) return backingUserId
|
|
30
|
+
throw new CrudHttpError(403, { error: 'api.errors.forbidden' })
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const actorUserId = normalizeActorUuid(subject)
|
|
34
|
+
const claimedUserId = auth.userId === undefined || auth.userId === null
|
|
35
|
+
? actorUserId
|
|
36
|
+
: normalizeActorUuid(auth.userId)
|
|
37
|
+
if (actorUserId && claimedUserId === actorUserId) return actorUserId
|
|
38
|
+
throw new CrudHttpError(403, { error: 'api.errors.forbidden' })
|
|
39
|
+
}
|
|
@@ -1,22 +1,75 @@
|
|
|
1
1
|
import { createRequire } from 'node:module'
|
|
2
|
-
import type { JSONContent } from '@tiptap/core'
|
|
3
2
|
import { TiptapTransformer } from '@hocuspocus/transformer'
|
|
4
3
|
import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
4
|
+
import { getSchema, type Extensions, type JSONContent } from '@tiptap/core'
|
|
5
|
+
import {
|
|
6
|
+
DOMParser as ProseMirrorDOMParser,
|
|
7
|
+
DOMSerializer,
|
|
8
|
+
Node as ProseMirrorNode,
|
|
9
|
+
type ParseOptions,
|
|
10
|
+
} from '@tiptap/pm/model'
|
|
5
11
|
import * as Y from 'yjs'
|
|
6
12
|
import { deriveContentTextFromHtml } from './contentService'
|
|
7
13
|
import { COLLAB_FRAGMENT_FIELD, getDocumentEditorExtensions } from './editorConfig'
|
|
8
14
|
import { assertDocumentContentResourceLimits } from './resourceLimits'
|
|
9
15
|
|
|
10
|
-
type
|
|
16
|
+
type HappyDomModule = typeof import('happy-dom')
|
|
17
|
+
type HappyDomWindow = InstanceType<HappyDomModule['Window']>
|
|
11
18
|
|
|
12
19
|
const requireFromHere = createRequire(import.meta.url)
|
|
13
|
-
let
|
|
20
|
+
let happyDomModule: HappyDomModule | null = null
|
|
14
21
|
|
|
15
|
-
function
|
|
16
|
-
if (!
|
|
17
|
-
|
|
22
|
+
function createHtmlWindow(): HappyDomWindow {
|
|
23
|
+
if (!happyDomModule) {
|
|
24
|
+
happyDomModule = requireFromHere('happy-dom') as HappyDomModule
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return new happyDomModule.Window({
|
|
28
|
+
settings: {
|
|
29
|
+
disableJavaScriptEvaluation: true,
|
|
30
|
+
disableJavaScriptFileLoading: true,
|
|
31
|
+
disableCSSFileLoading: true,
|
|
32
|
+
disableIframePageLoading: true,
|
|
33
|
+
disableComputedStyleRendering: true,
|
|
34
|
+
},
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function generateHtml(doc: JSONContent, extensions: Extensions): string {
|
|
39
|
+
const schema = getSchema(extensions)
|
|
40
|
+
const documentNode = ProseMirrorNode.fromJSON(schema, doc)
|
|
41
|
+
const localWindow = createHtmlWindow()
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const wrapper = localWindow.document.createElement('div')
|
|
45
|
+
DOMSerializer.fromSchema(schema).serializeFragment(
|
|
46
|
+
documentNode.content,
|
|
47
|
+
{ document: localWindow.document as unknown as Document },
|
|
48
|
+
wrapper as unknown as HTMLElement,
|
|
49
|
+
)
|
|
50
|
+
return wrapper.innerHTML
|
|
51
|
+
} finally {
|
|
52
|
+
localWindow.happyDOM.abort()
|
|
53
|
+
localWindow.happyDOM.close()
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function generateJson(html: string, extensions: Extensions, options?: ParseOptions): JSONContent {
|
|
58
|
+
const localWindow = createHtmlWindow()
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
const parsedDocument = new localWindow.DOMParser().parseFromString(
|
|
62
|
+
`<!DOCTYPE html><html><body>${html}</body></html>`,
|
|
63
|
+
'text/html',
|
|
64
|
+
)
|
|
65
|
+
const schema = getSchema(extensions)
|
|
66
|
+
return ProseMirrorDOMParser.fromSchema(schema)
|
|
67
|
+
.parse(parsedDocument.body as unknown as Node, options)
|
|
68
|
+
.toJSON()
|
|
69
|
+
} finally {
|
|
70
|
+
localWindow.happyDOM.abort()
|
|
71
|
+
localWindow.happyDOM.close()
|
|
18
72
|
}
|
|
19
|
-
return tiptapHtmlServer
|
|
20
73
|
}
|
|
21
74
|
|
|
22
75
|
function hasRenderableContent(node: JSONContent): boolean {
|
|
@@ -36,8 +89,7 @@ export function yDocToContent(ydoc: Y.Doc): { html: string; text: string } | nul
|
|
|
36
89
|
return { html: '', text: '' }
|
|
37
90
|
}
|
|
38
91
|
|
|
39
|
-
const
|
|
40
|
-
const html = generateHTML(json, getDocumentEditorExtensions())
|
|
92
|
+
const html = generateHtml(json, getDocumentEditorExtensions())
|
|
41
93
|
const text = deriveContentTextFromHtml(html)
|
|
42
94
|
assertDocumentContentResourceLimits({ contentHtml: html, contentText: text })
|
|
43
95
|
return { html, text }
|
|
@@ -52,8 +104,7 @@ export function htmlToYDoc(html: string): Y.Doc {
|
|
|
52
104
|
if (!html.trim()) return new Y.Doc()
|
|
53
105
|
|
|
54
106
|
const extensions = getDocumentEditorExtensions()
|
|
55
|
-
const
|
|
56
|
-
const json = generateJSON(html, extensions) as JSONContent
|
|
107
|
+
const json = generateJson(html, extensions)
|
|
57
108
|
return TiptapTransformer.toYdoc(json, COLLAB_FRAGMENT_FIELD, extensions)
|
|
58
109
|
}
|
|
59
110
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import * as Y from 'yjs'
|
|
2
|
+
|
|
3
|
+
export const COLLAB_CONTENT_SAVE_TIMEOUT_MS = 15000
|
|
4
|
+
|
|
5
|
+
export function containsDocumentSnapshot(durable: Y.Snapshot, requested: Y.Snapshot): boolean {
|
|
6
|
+
for (const [clientId, clock] of requested.sv) {
|
|
7
|
+
if ((durable.sv.get(clientId) ?? 0) < clock) return false
|
|
8
|
+
}
|
|
9
|
+
return Y.equalDeleteSets(Y.mergeDeleteSets([durable.ds, requested.ds]), durable.ds)
|
|
10
|
+
}
|