@open-mercato/documents 0.9.1-develop.7575.1.8480826a9b → 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.
Files changed (97) hide show
  1. package/dist/contentSecurityPolicy.js +23 -0
  2. package/dist/contentSecurityPolicy.js.map +7 -0
  3. package/dist/modules/documents/api/[id]/comments/access-check/route.js +13 -6
  4. package/dist/modules/documents/api/[id]/comments/access-check/route.js.map +2 -2
  5. package/dist/modules/documents/api/[id]/comments/route.js +2 -0
  6. package/dist/modules/documents/api/[id]/comments/route.js.map +2 -2
  7. package/dist/modules/documents/api/[id]/content/route.js +2 -0
  8. package/dist/modules/documents/api/[id]/content/route.js.map +2 -2
  9. package/dist/modules/documents/api/[id]/route.js +3 -0
  10. package/dist/modules/documents/api/[id]/route.js.map +2 -2
  11. package/dist/modules/documents/api/[id]/shares/route.js +2 -0
  12. package/dist/modules/documents/api/[id]/shares/route.js.map +2 -2
  13. package/dist/modules/documents/api/[id]/versions/route.js +2 -0
  14. package/dist/modules/documents/api/[id]/versions/route.js.map +2 -2
  15. package/dist/modules/documents/api/_shared.js +10 -27
  16. package/dist/modules/documents/api/_shared.js.map +3 -3
  17. package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js +3 -1
  18. package/dist/modules/documents/backend/documents/[id]/DocumentCanvas.js.map +2 -2
  19. package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js +1 -1
  20. package/dist/modules/documents/backend/documents/[id]/DocumentEditorIsland.js.map +2 -2
  21. package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js +15 -1
  22. package/dist/modules/documents/backend/documents/[id]/DocumentEditorSurface.js.map +2 -2
  23. package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js +15 -1
  24. package/dist/modules/documents/backend/documents/[id]/DocumentPageClient.js.map +2 -2
  25. package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js +20 -8
  26. package/dist/modules/documents/backend/documents/[id]/VersionHistoryPanel.js.map +2 -2
  27. package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js +3 -0
  28. package/dist/modules/documents/backend/documents/[id]/VersionPreviewDialog.js.map +2 -2
  29. package/dist/modules/documents/backend/documents/[id]/editorTypes.js.map +2 -2
  30. package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js +46 -0
  31. package/dist/modules/documents/backend/documents/[id]/saveCollaborativeContent.js.map +7 -0
  32. package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js +14 -6
  33. package/dist/modules/documents/backend/documents/[id]/useDocumentComments.js.map +2 -2
  34. package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js +3 -0
  35. package/dist/modules/documents/backend/documents/[id]/useDocumentEditor.js.map +2 -2
  36. package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js +3 -0
  37. package/dist/modules/documents/backend/documents/components/TemplateBodyEditor.js.map +2 -2
  38. package/dist/modules/documents/backend/documents/components/TemplatePreview.js +3 -0
  39. package/dist/modules/documents/backend/documents/components/TemplatePreview.js.map +2 -2
  40. package/dist/modules/documents/commands/comments.js +2 -2
  41. package/dist/modules/documents/commands/comments.js.map +2 -2
  42. package/dist/modules/documents/commands/folders.js +1 -0
  43. package/dist/modules/documents/commands/folders.js.map +2 -2
  44. package/dist/modules/documents/commands/interceptors.js +11 -0
  45. package/dist/modules/documents/commands/interceptors.js.map +2 -2
  46. package/dist/modules/documents/data/attachment-access.js +84 -0
  47. package/dist/modules/documents/data/attachment-access.js.map +7 -0
  48. package/dist/modules/documents/data/validators.js +11 -0
  49. package/dist/modules/documents/data/validators.js.map +2 -2
  50. package/dist/modules/documents/lib/actor.js +32 -0
  51. package/dist/modules/documents/lib/actor.js.map +7 -0
  52. package/dist/modules/documents/lib/collabMaterializer.js +52 -9
  53. package/dist/modules/documents/lib/collabMaterializer.js.map +2 -2
  54. package/dist/modules/documents/lib/collabPersistence.js +13 -0
  55. package/dist/modules/documents/lib/collabPersistence.js.map +7 -0
  56. package/dist/modules/documents/lib/permissions.js +35 -2
  57. package/dist/modules/documents/lib/permissions.js.map +2 -2
  58. package/dist/modules/documents/widgets/injection/related-documents/widget.client.js +3 -2
  59. package/dist/modules/documents/widgets/injection/related-documents/widget.client.js.map +2 -2
  60. package/dist/modules/documents/widgets/injection-table.js +12 -3
  61. package/dist/modules/documents/widgets/injection-table.js.map +2 -2
  62. package/dist/server/documents-collab-server.js +74 -1
  63. package/dist/server/documents-collab-server.js.map +2 -2
  64. package/jest.config.cjs +1 -1
  65. package/package.json +37 -37
  66. package/server/documents-collab-server.ts +79 -0
  67. package/src/contentSecurityPolicy.ts +21 -0
  68. package/src/modules/documents/api/[id]/comments/access-check/route.ts +13 -6
  69. package/src/modules/documents/api/[id]/comments/route.ts +2 -0
  70. package/src/modules/documents/api/[id]/content/route.ts +2 -0
  71. package/src/modules/documents/api/[id]/route.ts +3 -0
  72. package/src/modules/documents/api/[id]/shares/route.ts +2 -0
  73. package/src/modules/documents/api/[id]/versions/route.ts +2 -0
  74. package/src/modules/documents/api/_shared.ts +10 -36
  75. package/src/modules/documents/backend/documents/[id]/DocumentCanvas.tsx +3 -1
  76. package/src/modules/documents/backend/documents/[id]/DocumentEditorIsland.tsx +4 -1
  77. package/src/modules/documents/backend/documents/[id]/DocumentEditorSurface.tsx +19 -1
  78. package/src/modules/documents/backend/documents/[id]/DocumentPageClient.tsx +14 -0
  79. package/src/modules/documents/backend/documents/[id]/VersionHistoryPanel.tsx +23 -8
  80. package/src/modules/documents/backend/documents/[id]/VersionPreviewDialog.tsx +3 -0
  81. package/src/modules/documents/backend/documents/[id]/editorTypes.ts +1 -0
  82. package/src/modules/documents/backend/documents/[id]/saveCollaborativeContent.ts +43 -0
  83. package/src/modules/documents/backend/documents/[id]/useDocumentComments.ts +17 -7
  84. package/src/modules/documents/backend/documents/[id]/useDocumentEditor.ts +3 -0
  85. package/src/modules/documents/backend/documents/components/TemplateBodyEditor.tsx +3 -0
  86. package/src/modules/documents/backend/documents/components/TemplatePreview.tsx +3 -0
  87. package/src/modules/documents/commands/comments.ts +2 -2
  88. package/src/modules/documents/commands/folders.ts +1 -3
  89. package/src/modules/documents/commands/interceptors.ts +11 -0
  90. package/src/modules/documents/data/attachment-access.ts +83 -0
  91. package/src/modules/documents/data/validators.ts +12 -0
  92. package/src/modules/documents/lib/actor.ts +39 -0
  93. package/src/modules/documents/lib/collabMaterializer.ts +62 -11
  94. package/src/modules/documents/lib/collabPersistence.ts +10 -0
  95. package/src/modules/documents/lib/permissions.ts +52 -0
  96. package/src/modules/documents/widgets/injection/related-documents/widget.client.tsx +3 -2
  97. package/src/modules/documents/widgets/injection-table.ts +17 -3
package/jest.config.cjs CHANGED
@@ -29,7 +29,7 @@ module.exports = {
29
29
  ],
30
30
  },
31
31
  transformIgnorePatterns: [
32
- 'node_modules/(?!(@mikro-orm|kysely)/)',
32
+ 'node_modules/(?!(sanitize-html|htmlparser2|domhandler|domutils|dom-serializer|domelementtype|entities|@mikro-orm|kysely)/)',
33
33
  ],
34
34
  testMatch: ['<rootDir>/src/**/__tests__/**/*.test.(ts|tsx)'],
35
35
  passWithNoTests: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/documents",
3
- "version": "0.9.1-develop.7575.1.8480826a9b",
3
+ "version": "0.10.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -75,37 +75,36 @@
75
75
  "@hocuspocus/server": "^4.4.0",
76
76
  "@hocuspocus/transformer": "^4.3.0",
77
77
  "@mikro-orm/core": "^7.1.14",
78
- "@open-mercato/events": "0.9.1-develop.7575.1.8480826a9b",
79
- "@open-mercato/ui": "0.9.1-develop.7575.1.8480826a9b",
80
- "@tiptap/core": "^3",
81
- "@tiptap/extension-bubble-menu": "^3",
82
- "@tiptap/extension-collaboration": "^3.27.3",
83
- "@tiptap/extension-collaboration-caret": "^3.27.3",
84
- "@tiptap/extension-highlight": "^3",
85
- "@tiptap/extension-image": "^3",
86
- "@tiptap/extension-link": "^3",
87
- "@tiptap/extension-list": "^3.27.3",
88
- "@tiptap/extension-placeholder": "^3",
89
- "@tiptap/extension-table": "^3",
90
- "@tiptap/extension-table-cell": "^3",
91
- "@tiptap/extension-table-header": "^3",
92
- "@tiptap/extension-table-row": "^3",
93
- "@tiptap/extension-task-item": "^3",
94
- "@tiptap/extension-task-list": "^3",
95
- "@tiptap/extension-text-align": "^3",
96
- "@tiptap/extension-text-style": "^3",
97
- "@tiptap/extensions": "^3",
98
- "@tiptap/html": "^3.27.3",
99
- "@tiptap/pm": "^3",
100
- "@tiptap/react": "^3",
101
- "@tiptap/starter-kit": "^3",
102
- "@tiptap/suggestion": "^3",
103
- "@tiptap/y-tiptap": "^3.0.6",
104
- "happy-dom": "^20.10.6",
78
+ "@open-mercato/events": "0.10.0",
79
+ "@open-mercato/ui": "0.10.0",
80
+ "@tiptap/core": "3.32.0",
81
+ "@tiptap/extension-bubble-menu": "3.32.0",
82
+ "@tiptap/extension-collaboration": "3.32.0",
83
+ "@tiptap/extension-collaboration-caret": "3.32.0",
84
+ "@tiptap/extension-highlight": "3.32.0",
85
+ "@tiptap/extension-image": "3.32.0",
86
+ "@tiptap/extension-link": "3.32.0",
87
+ "@tiptap/extension-list": "3.32.0",
88
+ "@tiptap/extension-placeholder": "3.32.0",
89
+ "@tiptap/extension-table": "3.32.0",
90
+ "@tiptap/extension-table-cell": "3.32.0",
91
+ "@tiptap/extension-table-header": "3.32.0",
92
+ "@tiptap/extension-table-row": "3.32.0",
93
+ "@tiptap/extension-task-item": "3.32.0",
94
+ "@tiptap/extension-task-list": "3.32.0",
95
+ "@tiptap/extension-text-align": "3.32.0",
96
+ "@tiptap/extension-text-style": "3.32.0",
97
+ "@tiptap/extensions": "3.32.0",
98
+ "@tiptap/pm": "3.32.0",
99
+ "@tiptap/react": "3.32.0",
100
+ "@tiptap/starter-kit": "3.32.0",
101
+ "@tiptap/suggestion": "3.32.0",
102
+ "@tiptap/y-tiptap": "3.0.7",
103
+ "happy-dom": "21.0.4",
105
104
  "jszip": "^3.10.1",
106
- "prosemirror-model": "^1.25.9",
105
+ "prosemirror-model": "^1.25.12",
107
106
  "prosemirror-state": "^1.4.4",
108
- "prosemirror-view": "^1.42.3",
107
+ "prosemirror-view": "^1.42.6",
109
108
  "puppeteer-core": "^25.3.0",
110
109
  "y-prosemirror": "^1.3.7",
111
110
  "y-protocols": "^1.0.7",
@@ -113,25 +112,27 @@
113
112
  },
114
113
  "peerDependencies": {
115
114
  "@mikro-orm/postgresql": "^7.0.14",
116
- "@open-mercato/shared": "0.9.1-develop.7575.1.8480826a9b",
115
+ "@open-mercato/shared": "0.10.0",
117
116
  "react": "^19.0.0",
118
- "react-dom": "^19.0.0"
117
+ "react-dom": "^19.0.0",
118
+ "react-is": ">=18.0.0"
119
119
  },
120
120
  "devDependencies": {
121
- "@open-mercato/core": "0.9.1-develop.7575.1.8480826a9b",
122
- "@open-mercato/shared": "0.9.1-develop.7575.1.8480826a9b",
121
+ "@open-mercato/core": "0.10.0",
122
+ "@open-mercato/shared": "0.10.0",
123
123
  "@types/jest": "^30.0.0",
124
124
  "@types/pg": "^8.23.1",
125
125
  "@types/react": "^19.2.18",
126
126
  "@types/react-dom": "^19.2.5",
127
127
  "cross-env": "^10.1.0",
128
128
  "esbuild": "^0.28.2",
129
- "glob": "^13.0.6",
129
+ "glob": "^14.0.6",
130
130
  "jest": "^30.4.2",
131
131
  "pdfjs-dist": "^6.0.227",
132
132
  "pg": "8.23.0",
133
133
  "react": "19.2.8",
134
134
  "react-dom": "19.2.8",
135
+ "react-is": "^19.2.8",
135
136
  "testcontainers": "^12.0.3",
136
137
  "ts-jest": "^29.4.11",
137
138
  "tsx": "^4.23.12",
@@ -144,6 +145,5 @@
144
145
  "type": "git",
145
146
  "url": "https://github.com/open-mercato/open-mercato",
146
147
  "directory": "packages/documents"
147
- },
148
- "stableVersion": "0.9.0"
148
+ }
149
149
  }
@@ -26,9 +26,12 @@ import type {
26
26
  onChangePayload,
27
27
  onRequestPayload,
28
28
  onStoreDocumentPayload,
29
+ onStatelessPayload,
29
30
  Server as HocuspocusServer,
30
31
  } from '@hocuspocus/server'
31
32
  import * as Y from 'yjs'
33
+ import { collabContentSaveRequestSchema } from '@open-mercato/documents/modules/documents/data/validators'
34
+ import { containsDocumentSnapshot } from '@open-mercato/documents/modules/documents/lib/collabPersistence'
32
35
  import { hasAllFeatures } from '@open-mercato/shared/lib/auth/featureMatch'
33
36
  import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
34
37
  import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
@@ -2505,6 +2508,32 @@ export function createCollabHooks(deps: CollabHooksDeps) {
2505
2508
  assertConnectionAuthorization,
2506
2509
  establishConnectionAuthorization,
2507
2510
  releaseConnectionAuthorization,
2511
+ async saveContent(data: {
2512
+ documentName: string
2513
+ document: Y.Doc
2514
+ context: CollabContext
2515
+ store: (confirmPersistence: (snapshot: Y.Snapshot) => void) => Promise<unknown>
2516
+ }): Promise<boolean> {
2517
+ try {
2518
+ assertScopedContext(data.context)
2519
+ const scope = roomScopes.get(data.document)
2520
+ const isCurrent = () => data.context.documentId === data.documentName
2521
+ && scope?.tenantId === data.context.tenantId
2522
+ && scope.organizationId === data.context.organizationId
2523
+ && !data.context.readOnly
2524
+ && !isInvalidated(data.documentName, data.document)
2525
+ && !isFinalDrainPending(data.documentName)
2526
+ if (!isCurrent() || !(await deps.authorizeContext(data.context)) || !isCurrent()) return false
2527
+ const requested = Y.snapshot(data.document)
2528
+ const confirmation: { snapshot: Y.Snapshot | null } = { snapshot: null }
2529
+ await data.store((snapshot) => { confirmation.snapshot = snapshot })
2530
+ if (!isCurrent() || !(await deps.authorizeContext(data.context)) || !isCurrent()) return false
2531
+ const durable = confirmation.snapshot
2532
+ return Boolean(durable && containsDocumentSnapshot(durable, requested))
2533
+ } catch {
2534
+ return false
2535
+ }
2536
+ },
2508
2537
  reauthorizeActiveConnection,
2509
2538
  recordRedisAggregate(document: Y.Doc, byteLength: number): void {
2510
2539
  const previous = roomResourceBudgets.get(document)
@@ -2747,6 +2776,7 @@ export function createCollabHooks(deps: CollabHooksDeps) {
2747
2776
  documentName: string
2748
2777
  context: CollabContext
2749
2778
  document: Y.Doc
2779
+ confirmPersistence?: (snapshot: Y.Snapshot) => void
2750
2780
  }): Promise<void> {
2751
2781
  try {
2752
2782
  assertScopedContext(data.context)
@@ -2833,6 +2863,7 @@ export function createCollabHooks(deps: CollabHooksDeps) {
2833
2863
  logger.warn('materialization failed; preserving previous html/text', { room: data.documentName })
2834
2864
  }
2835
2865
  const yjsState = Buffer.from(Y.encodeStateAsUpdate(data.document))
2866
+ const storingSnapshot = Y.snapshot(data.document)
2836
2867
  const resourceBudgetRevision = roomResourceBudgets.get(data.document)?.revision ?? 0
2837
2868
  assertDocumentContentResourceLimits({
2838
2869
  yjsState,
@@ -2950,6 +2981,7 @@ export function createCollabHooks(deps: CollabHooksDeps) {
2950
2981
  })
2951
2982
  }
2952
2983
  deps.onPersisted?.(data.document, yjsState, collaborationGeneration)
2984
+ if (materialized) data.confirmPersistence?.(storingSnapshot)
2953
2985
  if (finalDrainAuthorized) deps.finalDrainRegistry?.complete(data.document)
2954
2986
  return
2955
2987
  }
@@ -3141,6 +3173,8 @@ export async function main(): Promise<void> {
3141
3173
  const finalDrainRegistry = createCollabFinalDrainRegistry()
3142
3174
  let server: HocuspocusServer<CollabContext> | null = null
3143
3175
  let redisStoreExtension: DocumentsCollabRedisExtension | null = null
3176
+ const savingConnections = new WeakSet<object>()
3177
+ const storeConfirmations = new WeakMap<onStoreDocumentPayload<CollabContext>, (snapshot: Y.Snapshot) => void>()
3144
3178
  const closeRoomConnectionsForContentReset = (documentName: string): void => {
3145
3179
  if (server) closeCollabRoomConnectionsForContentReset(server.hocuspocus, documentName)
3146
3180
  }
@@ -3325,8 +3359,53 @@ export async function main(): Promise<void> {
3325
3359
  documentName: data.documentName,
3326
3360
  context: data.lastContext,
3327
3361
  document: data.document,
3362
+ confirmPersistence: storeConfirmations.get(data),
3328
3363
  })
3329
3364
  },
3365
+ async onStateless(data: onStatelessPayload) {
3366
+ let value: unknown
3367
+ try { value = JSON.parse(data.payload) } catch { return }
3368
+ const request = collabContentSaveRequestSchema.safeParse(value)
3369
+ if (!request.success) return
3370
+ const respond = (saved: boolean) => data.connection.sendStateless(JSON.stringify({
3371
+ type: 'documents.content.saved',
3372
+ requestId: request.data.requestId,
3373
+ saved,
3374
+ }))
3375
+ if (savingConnections.has(data.connection) || !server) {
3376
+ respond(false)
3377
+ return
3378
+ }
3379
+ savingConnections.add(data.connection)
3380
+ try {
3381
+ const runtime = server.hocuspocus
3382
+ const context: CollabContext = data.connection.context
3383
+ const saved = await hooks.saveContent({
3384
+ documentName: data.documentName,
3385
+ document: data.document,
3386
+ context,
3387
+ store: async (confirmPersistence) => {
3388
+ const payload: onStoreDocumentPayload<CollabContext> = {
3389
+ instance: runtime,
3390
+ document: data.document,
3391
+ documentName: data.documentName,
3392
+ clientsCount: data.document.getConnectionsCount(),
3393
+ lastContext: context,
3394
+ lastTransactionOrigin: { source: 'local', context },
3395
+ }
3396
+ storeConfirmations.set(payload, confirmPersistence)
3397
+ try {
3398
+ await runtime.storeDocumentHooks(data.document, payload, true)
3399
+ } finally {
3400
+ storeConfirmations.delete(payload)
3401
+ }
3402
+ },
3403
+ })
3404
+ respond(saved)
3405
+ } finally {
3406
+ savingConnections.delete(data.connection)
3407
+ }
3408
+ },
3330
3409
  async onRequest(data: onRequestPayload) {
3331
3410
  return handleCollabServerRequest(data)
3332
3411
  },
@@ -0,0 +1,21 @@
1
+ import { createLogger } from '@open-mercato/shared/lib/logger'
2
+ import { resolveDocumentsCollaborationEndpoint } from './modules/documents/lib/collabEndpoint'
3
+
4
+ let warnedAboutExcludedEndpoint = false
5
+
6
+ export function resolveDocumentsCollaborationCspOrigins(): string[] {
7
+ const endpoint = resolveDocumentsCollaborationEndpoint()
8
+ if (!endpoint) return []
9
+ const url = new URL(endpoint)
10
+ if (url.username || url.password || !/^(?:[a-z0-9.-]+|\[[0-9a-f:]+\])$/i.test(url.hostname)) {
11
+ if (!warnedAboutExcludedEndpoint) {
12
+ warnedAboutExcludedEndpoint = true
13
+ createLogger('documents:csp').warn(
14
+ '[internal] Collaboration endpoint excluded from CSP; use a credential-free DNS or IPv6 URL',
15
+ { configuration: 'NEXT_PUBLIC_DOCUMENTS_COLLAB_URL' },
16
+ )
17
+ }
18
+ return []
19
+ }
20
+ return [url.origin]
21
+ }
@@ -1,7 +1,7 @@
1
1
  import { NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
4
- import { assertTier, resolveUserAccess } from '../../../../lib/permissions'
4
+ import { assertTier, hasUserDocumentViewPermission, resolveUserDocumentTier } from '../../../../lib/permissions'
5
5
  import {
6
6
  handleDocumentsRouteError,
7
7
  readBody,
@@ -20,6 +20,7 @@ const accessCheckSchema = z.object({
20
20
 
21
21
  const accessCheckResponseSchema = z.object({
22
22
  withoutAccess: z.array(z.string().uuid()),
23
+ shareableUserIds: z.array(z.string().uuid()).optional(),
23
24
  withoutAccessUsers: z.array(
24
25
  z.object({
25
26
  userId: z.string().uuid(),
@@ -48,16 +49,22 @@ export async function POST(request: Request, context: RouteContext): Promise<Res
48
49
  const input = accessCheckSchema.parse(await readBody(request))
49
50
  const uniqueUserIds = Array.from(new Set(input.userIds.map((userId) => userId.toLowerCase())))
50
51
  const withoutAccess: string[] = []
52
+ const shareableUserIds: string[] = []
53
+ const scope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId }
51
54
 
52
55
  for (const userId of uniqueUserIds) {
53
- const tier = await resolveUserAccess(
56
+ const canView = await hasUserDocumentViewPermission(scope, userId, ctx.container)
57
+ const tier = canView ? await resolveUserDocumentTier(
54
58
  ctx.em,
55
59
  documentId,
56
- { tenantId: ctx.tenantId, organizationId: ctx.organizationId },
60
+ scope,
57
61
  userId,
58
62
  ctx.container,
59
- )
60
- if (!tier) withoutAccess.push(userId)
63
+ ) : null
64
+ if (!tier) {
65
+ withoutAccess.push(userId)
66
+ if (canView) shareableUserIds.push(userId)
67
+ }
61
68
  }
62
69
  // Keep the historical response shape for clients, but never turn this
63
70
  // authorization probe into a user-directory/PII lookup. The caller
@@ -68,7 +75,7 @@ export async function POST(request: Request, context: RouteContext): Promise<Res
68
75
  secondary: null,
69
76
  }))
70
77
 
71
- return NextResponse.json({ withoutAccess, withoutAccessUsers })
78
+ return NextResponse.json({ withoutAccess, withoutAccessUsers, shareableUserIds })
72
79
  } catch (error) {
73
80
  return handleDocumentsRouteError(error, 'documents.comments.accessCheck')
74
81
  }
@@ -26,6 +26,7 @@ import {
26
26
  resolveDocumentsCommandBus,
27
27
  } from '../../_commands'
28
28
  import {
29
+ assertDocumentId,
29
30
  assertDocumentNotArchived,
30
31
  handleDocumentsRouteError,
31
32
  readBody,
@@ -243,6 +244,7 @@ export async function GET(request: Request, context: RouteContext): Promise<Resp
243
244
  try {
244
245
  const documentId = await resolveId(context)
245
246
  const ctx = await resolveDocumentsContext(request, ['documents.view'])
247
+ assertDocumentId(documentId)
246
248
  const tier = await assertTier(ctx.em, documentId, ctx.auth, 'viewer')
247
249
  const userId = resolveActorUserId(ctx.auth)
248
250
  const url = new URL(request.url)
@@ -13,6 +13,7 @@ import type {
13
13
  ReplaceDocumentContentCommandResult,
14
14
  } from '../../../commands/content'
15
15
  import {
16
+ assertDocumentId,
16
17
  assertDocumentNotArchived,
17
18
  handleDocumentsRouteError,
18
19
  readBody,
@@ -58,6 +59,7 @@ export async function GET(request: Request, context: RouteContext): Promise<Resp
58
59
  try {
59
60
  const id = await resolveId(context)
60
61
  const ctx = await resolveDocumentsContext(request, ['documents.view'])
62
+ assertDocumentId(id)
61
63
  await assertTier(ctx.em, id, ctx.auth, 'viewer')
62
64
  const content = await loadDocumentContent(ctx.em, id, {
63
65
  tenantId: ctx.tenantId,
@@ -92,6 +92,9 @@ export async function GET(request: Request, context: RouteContext): Promise<Resp
92
92
  try {
93
93
  const id = await resolveId(context)
94
94
  const ctx = await resolveDocumentsContext(request, ['documents.view'])
95
+ if (!z.string().uuid().safeParse(id).success) {
96
+ throw new CrudHttpError(404, { error: 'documents.documents.notFound' })
97
+ }
95
98
  const projection = await resolveDocumentCapabilityProjection(ctx, id)
96
99
  if (!projection.relationshipTier && await isRemovedDocumentVisibleToActor(ctx, id)) {
97
100
  throw new CrudHttpError(404, { error: 'documents.documents.notFound' })
@@ -24,6 +24,7 @@ import {
24
24
  resolveDocumentsCommandBus,
25
25
  } from '../../_commands'
26
26
  import {
27
+ assertDocumentId,
27
28
  assertDocumentNotArchived,
28
29
  handleDocumentsRouteError,
29
30
  loadScopedShare,
@@ -142,6 +143,7 @@ export async function GET(request: Request, context: RouteContext): Promise<Resp
142
143
  try {
143
144
  const documentId = await resolveId(context)
144
145
  const ctx = await resolveDocumentsContext(request, ['documents.share'])
146
+ assertDocumentId(documentId)
145
147
  await assertCanShare(ctx, documentId)
146
148
  const loadedShares = await findWithDecryption(
147
149
  ctx.em,
@@ -9,6 +9,7 @@ import { DOCUMENTS_VERSION_LIST_PAGE_SIZE } from '../../../lib/historyLimits'
9
9
  import { assertTier } from '../../../lib/permissions'
10
10
  import { resolveUserLabels } from '../../../lib/userLabels'
11
11
  import {
12
+ assertDocumentId,
12
13
  assertDocumentNotArchived,
13
14
  handleDocumentsRouteError,
14
15
  readBody,
@@ -87,6 +88,7 @@ export async function GET(request: Request, context: RouteContext): Promise<Resp
87
88
  try {
88
89
  const documentId = await resolveId(context)
89
90
  const ctx = await resolveDocumentsContext(request, ['documents.view'])
91
+ assertDocumentId(documentId)
90
92
  await assertTier(ctx.em, documentId, ctx.auth, 'viewer')
91
93
  const url = new URL(request.url)
92
94
  const query = versionListQuerySchema.parse(Object.fromEntries(url.searchParams.entries()))
@@ -1,3 +1,5 @@
1
+ import { resolveActorUserId } from '../lib/actor'
2
+ export { resolveActorUserId } from '../lib/actor'
1
3
  import { NextResponse } from 'next/server'
2
4
  import type { EntityManager } from '@mikro-orm/postgresql'
3
5
  import type { AwilixContainer } from 'awilix'
@@ -138,8 +140,6 @@ export function withDocumentsContextErrors(doc: OpenApiRouteDoc): OpenApiRouteDo
138
140
  return { ...doc, methods }
139
141
  }
140
142
 
141
- const actorUuidSchema = z.string().uuid()
142
-
143
143
  export const ROUTE_ERROR_TRANSLATIONS: Record<string, { key: string; fallback: string }> = {
144
144
  Unauthorized: { key: 'api.errors.unauthorized', fallback: 'Unauthorized' },
145
145
  Forbidden: { key: 'api.errors.forbidden', fallback: 'Forbidden' },
@@ -274,16 +274,6 @@ function readAuthScopeId(auth: NonNullable<AuthContext>, key: 'actorTenantId' |
274
274
  return null
275
275
  }
276
276
 
277
- function normalizeActorUuid(value: unknown): string | null {
278
- if (typeof value !== 'string') return null
279
- const normalized = value.trim()
280
- return actorUuidSchema.safeParse(normalized).success ? normalized : null
281
- }
282
-
283
- function isApiKeyAuth(auth: NonNullable<AuthContext>): boolean {
284
- return auth.isApiKey === true || auth.sub.trim().startsWith('api_key:')
285
- }
286
-
287
277
  export function hasDocumentsFeature(auth: DocumentsAuthContext, feature: string): boolean {
288
278
  if (auth.isSuperAdmin === true) return true
289
279
  return hasAllFeatures([feature], auth.features)
@@ -455,30 +445,6 @@ export async function resolveDocumentsContext(
455
445
  }
456
446
  }
457
447
 
458
- export function resolveActorUserId(auth: NonNullable<AuthContext>): string {
459
- const subject = auth.sub.trim()
460
- if (isApiKeyAuth(auth)) {
461
- // `keyId` is populated only by successful API-key authentication. Do not
462
- // recover an actor by parsing an arbitrary prefixed subject when that
463
- // validated field is absent, malformed, or disagrees with the subject.
464
- const keyId = normalizeActorUuid(auth.keyId)
465
- if (!keyId || subject !== `api_key:${keyId}`) {
466
- throw new CrudHttpError(403, { error: 'api.errors.forbidden' })
467
- }
468
- if (auth.userId === undefined || auth.userId === null) return keyId
469
- const backingUserId = normalizeActorUuid(auth.userId)
470
- if (backingUserId) return backingUserId
471
- throw new CrudHttpError(403, { error: 'api.errors.forbidden' })
472
- }
473
-
474
- const actorUserId = normalizeActorUuid(subject)
475
- const claimedUserId = auth.userId === undefined || auth.userId === null
476
- ? actorUserId
477
- : normalizeActorUuid(auth.userId)
478
- if (actorUserId && claimedUserId === actorUserId) return actorUserId
479
- throw new CrudHttpError(403, { error: 'api.errors.forbidden' })
480
- }
481
-
482
448
  export async function readBody(
483
449
  request: Request,
484
450
  maxBytes = DOCUMENTS_JSON_BODY_LIMITS.standard,
@@ -544,6 +510,14 @@ export async function handleDocumentsRouteError(error: unknown, label: string):
544
510
  )
545
511
  }
546
512
 
513
+ const documentIdSchema = z.string().uuid()
514
+
515
+ export function assertDocumentId(id: string): void {
516
+ if (!documentIdSchema.safeParse(id).success) {
517
+ throw new CrudHttpError(404, { error: 'documents.documents.notFound' })
518
+ }
519
+ }
520
+
547
521
  export async function loadScopedDocument(ctx: DocumentsRouteContext, id: string): Promise<Document> {
548
522
  const document = await findOneWithDecryption(ctx.em, Document, {
549
523
  id,
@@ -15,6 +15,7 @@ import { OutlinePane } from './OutlinePane'
15
15
  import { captureCommentAnchor, type CommentAnchor } from './CommentAnchorNavigation'
16
16
  import { DOCUMENT_EDITOR_CONTENT_CLASS } from './editorTypes'
17
17
  import { DOCUMENT_PAGINATION_STYLES } from './documentPagination'
18
+ import { useContentSecurityPolicyNonce } from '@open-mercato/ui/theme/ContentSecurityPolicyProvider'
18
19
 
19
20
  type TitleModel = {
20
21
  value: string
@@ -49,6 +50,7 @@ export function DocumentCanvas({
49
50
  onComment?: (anchor: CommentAnchor) => void
50
51
  }) {
51
52
  const t = useT()
53
+ const nonce = useContentSecurityPolicyNonce()
52
54
  const editorState = useEditorState({
53
55
  editor,
54
56
  selector: ({ editor: current }) => current ? {
@@ -71,7 +73,7 @@ export function DocumentCanvas({
71
73
 
72
74
  return (
73
75
  <div className="om-doc-canvas max-h-[calc(100dvh-var(--topbar-height,0px)-12rem)] min-h-96 overflow-auto bg-muted p-0 sm:px-4 sm:py-8 md:px-8 md:py-10">
74
- <style>{DOCUMENT_PAGINATION_STYLES}</style>
76
+ <style nonce={nonce}>{DOCUMENT_PAGINATION_STYLES}</style>
75
77
  {notice ? <Alert status="information" style="lighter" className="mx-auto mb-4 max-w-3xl"><AlertDescription>{notice}</AlertDescription></Alert> : null}
76
78
  <div className="mx-auto flex w-fit min-w-full flex-col gap-4 lg:flex-row lg:items-start">
77
79
  {outlineOpen ? <OutlinePane editor={editor} /> : null}
@@ -30,7 +30,10 @@ export default function DocumentEditorIsland(props: DocumentEditorIslandProps) {
30
30
  router.replace(query ? `?${query}` : '?', { scroll: false })
31
31
  }, [forcedReadOnly, router, searchParams])
32
32
 
33
- if (collaboration.mode === 'connecting') return <LoadingMessage label={t('documents.editor.loading')} />
33
+ if (
34
+ collaboration.mode === 'connecting'
35
+ || (collaboration.mode === 'collab' && collaboration.connectionStatus === 'connecting')
36
+ ) return <LoadingMessage label={t('documents.editor.loading')} />
34
37
  if (collaboration.mode === 'fallback') {
35
38
  return <DocumentEditorSurface {...props} readOnly={forcedReadOnly} key={`fallback:${props.documentId}`} transport="fallback" connectionStatus="offline" presenceUsers={[]} mode={mode} onModeChange={changeMode} />
36
39
  }
@@ -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 { Link2, Unlink } from 'lucide-react'
5
6
  import { Button } from '@open-mercato/ui/primitives/button'
6
7
  import { Input } from '@open-mercato/ui/primitives/input'
@@ -18,6 +19,7 @@ import { useDocumentEditor } from './useDocumentEditor'
18
19
  import { useFallbackContentPersistence } from './useFallbackContentPersistence'
19
20
  import { useDocumentTitle } from './useDocumentTitle'
20
21
  import { useEditorInsertions } from './useEditorInsertions'
22
+ import { saveCollaborativeContent } from './saveCollaborativeContent'
21
23
 
22
24
  type Props = DocumentEditorIslandProps & {
23
25
  transport: 'collab' | 'fallback'
@@ -30,6 +32,7 @@ type Props = DocumentEditorIslandProps & {
30
32
 
31
33
  export function DocumentEditorSurface(input: Props) {
32
34
  const t = useT()
35
+ const nonce = useContentSecurityPolicyNonce()
33
36
  const [outlineOpen, setOutlineOpen] = React.useState(false)
34
37
  const [suggestionRange, setSuggestionRange] = React.useState<{ from: number; to: number } | null>(null)
35
38
  const modeChangeInFlightRef = React.useRef(false)
@@ -60,6 +63,21 @@ export function DocumentEditorSurface(input: Props) {
60
63
  readOnly: effectiveReadOnly,
61
64
  onTitleChange: input.onTitleChange,
62
65
  })
66
+ React.useEffect(() => {
67
+ const controller = new AbortController()
68
+ input.onSaveReady?.(async () => {
69
+ if (controller.signal.aborted || input.readOnly || !editorModel.editorRef.current) return false
70
+ return input.transport === 'fallback'
71
+ ? fallbackPersistence.saveNow()
72
+ : input.collabResources
73
+ ? saveCollaborativeContent(input.collabResources, controller.signal)
74
+ : false
75
+ })
76
+ return () => {
77
+ controller.abort()
78
+ input.onSaveReady?.(null)
79
+ }
80
+ }, [editorModel.editorRef, fallbackPersistence.saveNow, input.collabResources, input.onSaveReady, input.readOnly, input.transport])
63
81
  const insertions = useEditorInsertions({
64
82
  documentId: input.documentId,
65
83
  editorRef: editorModel.editorRef,
@@ -102,7 +120,7 @@ export function DocumentEditorSurface(input: Props) {
102
120
 
103
121
  return (
104
122
  <div className={cn('space-y-3', input.transport === 'collab' && 'om-doc-collab', input.mode === 'preview' && 'om-doc-preview')}>
105
- <style>{EDITOR_PRESENCE_STYLES}</style>
123
+ <style nonce={nonce}>{EDITOR_PRESENCE_STYLES}</style>
106
124
  <div className="overflow-hidden rounded-lg border border-border bg-muted shadow-sm">
107
125
  <div className="sticky top-0 z-sticky border-b border-border bg-card/95">
108
126
  <div className="flex flex-wrap items-center justify-between gap-2 px-3 py-2">
@@ -79,6 +79,17 @@ export function DocumentPageClient({ documentId }: { documentId: string }) {
79
79
  const scrollVersionsIntoView = React.useRef(false)
80
80
  const [editorEpoch, setEditorEpoch] = React.useState(0)
81
81
  const [editor, setEditor] = React.useState<Editor | null>(null)
82
+ const contentSaveRef = React.useRef<{ documentId: string; save: () => Promise<boolean> } | null>(null)
83
+ const displayedDocumentId = state.status === 'ready' ? state.document.id : null
84
+ const registerContentSave = React.useCallback((save: (() => Promise<boolean>) | null) => {
85
+ contentSaveRef.current = save && displayedDocumentId ? { documentId: displayedDocumentId, save } : null
86
+ }, [displayedDocumentId])
87
+ const saveBeforeSnapshot = React.useCallback(async () => {
88
+ const registered = contentSaveRef.current
89
+ if (!registered || registered.documentId !== documentId) return false
90
+ const saved = await registered.save()
91
+ return saved && contentSaveRef.current === registered
92
+ }, [documentId])
82
93
  const [commentFocusRequest, setCommentFocusRequest] = React.useState<CommentFocusRequest | null>(null)
83
94
  const requestSequence = React.useRef(0)
84
95
  const mutationContextId = `documents-detail:${documentId}`
@@ -135,6 +146,7 @@ export function DocumentPageClient({ documentId }: { documentId: string }) {
135
146
  const nextContent = contentCall.status === 404
136
147
  ? { contentHtml: '', updatedAt: null }
137
148
  : normalizeDocumentContent(contentCall.result)
149
+ contentSaveRef.current = null
138
150
  setState((current) => current.status === 'ready' ? {
139
151
  ...current,
140
152
  content: nextContent,
@@ -411,6 +423,7 @@ export function DocumentPageClient({ documentId }: { documentId: string }) {
411
423
  documentUpdatedAt={document.updatedAt}
412
424
  readOnly={!capabilities.canEdit}
413
425
  onEditorReady={setEditor}
426
+ onSaveReady={registerContentSave}
414
427
  onContentConflict={handleContentConflict}
415
428
  onComment={capabilities.canComment ? (anchor) => setCommentFocusRequest((current) => ({ anchor, requestId: (current?.requestId ?? 0) + 1 })) : undefined}
416
429
  onTitleChange={(title, updatedAt) => setState((current) => current.status === 'ready' ? {
@@ -441,6 +454,7 @@ export function DocumentPageClient({ documentId }: { documentId: string }) {
441
454
  canRestore={capabilities.canEdit}
442
455
  contentUpdatedAt={content.updatedAt}
443
456
  onRestored={reloadEditor}
457
+ onBeforeSnapshot={saveBeforeSnapshot}
444
458
  />
445
459
  </div>
446
460
  ) : null}