Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions client/src/hooks/use-document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,15 @@ export function useDocument(id?: string) {
}, [id]);

const handleSave = useCallback(async () => {
if (!id) return;
if (!id || !editedDoc) return;
try {
setSaving(true);
setError(null);
await api.put(`/document/${id}`, editedDoc);
// Content is owned by Yjs sync; REST persists metadata only (issue #47).
await api.put(`/document/${id}`, {
title: editedDoc.title,
isPublic: editedDoc.isPublic,
});
setDoc(editedDoc);
} catch (err) {
console.error('Failed to save document:', err);
Expand Down
25 changes: 8 additions & 17 deletions server/src/controllers/document.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,23 @@ import { getClientInfo } from '@/utils/getClientInfo';
export const createDoc = asyncErrorWrapper(async (req: AuthenticatedRequest, res: Response) => {
const clientInfo = getClientInfo(req);
const userId = req.user?.userId;
const { title, content = '', isPublic = false } = req.body;
const { title, isPublic = false } = req.body;

logger.debug('Document creation attempt', {
action: 'CREATE_DOCUMENT_ATTEMPT',
...clientInfo,
userId,
title,
isPublic,
contentLength: content.length,
});

try {
// `content` starts empty and is owned by Yjs sync afterwards (issue #47);
// accepting it here would store text no reader ever sees.
const newDoc = await prisma.document.create({
data: {
title,
content,
content: '',
isPublic,
authorId: req.user?.userId,
},
Expand Down Expand Up @@ -190,18 +191,7 @@ export const updateDoc = asyncErrorWrapper(async (req: AuthenticatedRequest, res
const clientInfo = getClientInfo(req);
const userId = req.user?.userId;
const documentId = req.params.id;
const { title, content, isPublic } = req.body;

// logger.info('Document update attempt', {
// action: 'UPDATE_DOCUMENT_ATTEMPT',
// ...clientInfo,
// userId,
// documentId,
// title,
// isPublic,
// contentLength: content?.length,
// });

const { title, isPublic } = req.body;
try {
const doc = await prisma.document.findFirst({
where: { id: documentId },
Expand All @@ -227,11 +217,12 @@ export const updateDoc = asyncErrorWrapper(async (req: AuthenticatedRequest, res
return;
}

// `content` is intentionally not writable here: it is a mirror of the
// Yjs document state maintained by dbPersistence.store (issue #47).
const updatedDoc = await prisma.document.update({
where: { id: doc.id },
data: { title, content, isPublic },
data: { title, isPublic },
});

// logger.info('Document updated successfully', {
// action: 'UPDATE_DOCUMENT_SUCCESS',
// ...clientInfo,
Expand Down
49 changes: 26 additions & 23 deletions server/src/lib/dbPersistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,35 +54,38 @@ export const dbPersistence = new Database({
});

if (existing) {
await prisma.yjsDocumentState.update({
where: { documentId: id },
data: {
state: Buffer.from(state),
version: { increment: 1 },
},
});

await prisma.document.update({
where: { id: id },
data: { content: plainText },
});
// Snapshot and its plaintext mirror must stay consistent: write both atomically.
await prisma.$transaction([
prisma.yjsDocumentState.update({
where: { documentId: id },
data: {
state: Buffer.from(state),
version: { increment: 1 },
},
}),
prisma.document.update({
where: { id: id },
data: { content: plainText },
}),
]);
} else {
const documentExists = await prisma.document.findFirst({
where: { id: id },
});

if (documentExists) {
await prisma.yjsDocumentState.create({
data: {
documentId: documentExists.id,
state: Buffer.from(state),
},
});

await prisma.document.update({
where: { id: documentExists.id },
data: { content: plainText },
});
await prisma.$transaction([
prisma.yjsDocumentState.create({
data: {
documentId: documentExists.id,
state: Buffer.from(state),
},
}),
prisma.document.update({
where: { id: documentExists.id },
data: { content: plainText },
}),
]);
} else {
logger.warn(`No Document found for ID prefix: ${documentName}`, {
action: 'DB_STORE_DOC_NOT_FOUND',
Expand Down
18 changes: 18 additions & 0 deletions server/test/document.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,24 @@ describe('Document Routes', () => {
expect(res.body.title).toBe('Updated Title');
});

it('should not overwrite document content via REST update (Yjs is the source of truth)', async () => {
const created = await prisma.document.create({
data: { title: 'Synced Doc', content: 'yjs-derived-content', authorId: userId },
});

const res = await request(app)
.put(`/api/document/${created.id}`)
.set('Authorization', `Bearer ${token}`)
.send({ title: 'Renamed', content: 'rest-overwrite-attempt' });

expect(res.status).toBe(StatusCodes.OK);
expect(res.body.title).toBe('Renamed');
expect(res.body.content).toBe('yjs-derived-content');

const doc = await prisma.document.findUniqueOrThrow({ where: { id: created.id } });
expect(doc.content).toBe('yjs-derived-content');
});

it('should delete a document', async () => {
const created = await prisma.document.create({
data: {
Expand Down
Loading