Skip to content

feat: setup project to use hocuspocus v3 #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: rollback-updates
Choose a base branch
from
Open
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
68 changes: 49 additions & 19 deletions hocuspocus-server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions hocuspocus-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
"@blocknote/core": "^0.25.1",
"@blocknote/react": "^0.25.1",
"@blocknote/server-util": "^0.25.0",
"@hocuspocus/common": "2.15.2",
"@hocuspocus/extension-sqlite": "^2.15.2",
"@hocuspocus/server": "^2.15.2",
"@hocuspocus/common": "3.0.6-rc.0",
"@hocuspocus/extension-sqlite": "3.0.6-rc.0",
"@hocuspocus/server": "3.0.6-rc.0",
"@hono/node-server": "^1.0.8",
"@hono/node-ws": "^1.0.8",
"@tiptap/core": "2.11.5",
Expand All @@ -38,6 +38,7 @@
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.5.0",
"@typescript-eslint/parser": "^5.5.0",
"@types/node": "^20.11.18",
"eslint": "^8.10.0",
"eslint-config-react-app": "^7.0.0",
"eslint-plugin-import": "^2.31.0",
Expand Down
27 changes: 19 additions & 8 deletions hocuspocus-server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SQLite } from "@hocuspocus/extension-sqlite";
import { Document, Server } from "@hocuspocus/server";
import { type Document, Hocuspocus } from "@hocuspocus/server";

import { serve } from "@hono/node-server";
import { createNodeWebSocket } from "@hono/node-ws";
Expand All @@ -10,7 +10,8 @@ import { FAKE_authInfoFromToken } from "./auth.js";
import { threadsRouter } from "./threads.js";
import { RejectUnauthorized } from "./rejectUnauthorized.js";
// Setup Hocuspocus server
const hocuspocusServer = Server.configure({

const hocuspocus = new Hocuspocus({
async onAuthenticate(data) {
const { token } = data;

Expand All @@ -19,15 +20,19 @@ const hocuspocusServer = Server.configure({
if (authInfo === "unauthorized") {
throw new Error("Not authorized!");
}

data.connection.readOnly = authInfo.role === "COMMENT-ONLY";
data.connectionConfig.readOnly = authInfo.role === "COMMENT-ONLY";
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to double check whether this does what I think it does....

},

extensions: [
new SQLite({
database: "db.sqlite",
database: ":memory:",
}),
// TODO we can actually just do the auth check in here, and not need the server to inject the mark or anything
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might actually really simplify things, if we choose to do the authorization at the hocuspocus layer instead, it would allow clients to safely make modifications to the threads on their side. To make it safe though, we need to inspect what exactly was updated (i.e. they can only modify their own comments).

new RejectUnauthorized("threads", (payload) => {
// eslint-disable-next-line no-console
console.warn("rejecting update to document", payload.documentName);
}),
new RejectUnauthorized("threads"),
],

// TODO: for good security, you'd want to make sure that either:
Expand All @@ -46,7 +51,7 @@ app.get(
"/hocuspocus",
upgradeWebSocket((c) => ({
onOpen(_evt, ws) {
hocuspocusServer.handleConnection(ws.raw, c.req.raw);
hocuspocus.handleConnection(ws.raw, c.req.raw as any);
},
}))
);
Expand All @@ -61,7 +66,7 @@ const documentMiddleware = createMiddleware<{
};
}>(async (c, next) => {
const documentId = c.req.param("documentId");
const document = hocuspocusServer.documents.get(documentId!);
const document = hocuspocus.documents.get(documentId!);

if (!document) {
return c.json({ error: "Document not found" }, 404);
Expand All @@ -85,6 +90,12 @@ app.route(
const server = serve({
fetch: app.fetch,
port: 8787,
}, (info) => {
hocuspocus.hooks('onListen', {
instance: hocuspocus,
configuration: hocuspocus.configuration,
port: info.port
})
});

// Setup WebSocket support (needed for HocusPocus)
Expand Down
93 changes: 22 additions & 71 deletions hocuspocus-server/src/rejectUnauthorized.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import type { CloseEvent } from "@hocuspocus/common";
import {
beforeHandleMessagePayload,
Extension,
IncomingMessage,
MessageType,
} from "@hocuspocus/server";
import { type beforeSyncPayload, Extension } from "@hocuspocus/server";
import * as syncProtocol from "y-protocols/sync";
import * as Y from "yjs";

Expand All @@ -18,55 +12,10 @@ import * as Y from "yjs";
* - if the update is accepted, we do nothing
*/
export class RejectUnauthorized implements Extension {
constructor(private readonly threadsMapKey: string) {}
/**
* Extract the yjsUpdate from the incoming message
* @param message
* @returns
*/
private getYUpdate(message: Uint8Array) {
/**
* The messages we are interested in are of the following format:
* [docIdLength: number, ...docIdString: string, hocuspocusMessageType: number, ySyncMessageType: number, ...yjsUpdate: Uint8Array]
*
* We check that the hocuspocusMessageType is Sync and that the ySyncMessageType is messageYjsUpdate.
*/
const incomingMessage = new IncomingMessage(message);
// Read the docID string, but don't use it
incomingMessage.readVarString();

// Read the hocuspocusMessageType
const hocuspocusMessageType = incomingMessage.readVarUint();
// If the hocuspocusMessageType is not Sync, we don't handle the message, since it is not an update
if (
!(
hocuspocusMessageType === MessageType.Sync ||
hocuspocusMessageType === MessageType.SyncReply
)
) {
return;
}

// Read the ySyncMessageType
const ySyncMessageType = incomingMessage.readVarUint();

// If the ySyncMessageType is not a messageYjsUpdate or a messageYjsSyncStep2, we don't handle the message, since it is not an update
if (
!(
ySyncMessageType === syncProtocol.messageYjsUpdate ||
ySyncMessageType === syncProtocol.messageYjsSyncStep2
)
) {
// not an update we want to handle
return;
}

// Read the yjsUpdate
const yUpdate = incomingMessage.readVarUint8Array();

return yUpdate;
}

constructor(
private readonly threadsMapKey: string,
private readonly onReject?: (payload: beforeSyncPayload) => void
) {}
/**
* This function protects against changes to the restricted type.
* It does this by:
Expand Down Expand Up @@ -112,29 +61,31 @@ export class RejectUnauthorized implements Extension {
return didNeedToUndo;
}

async beforeHandleMessage({
update,
document: ydoc,
}: beforeHandleMessagePayload) {
const yUpdate = this.getYUpdate(update);

if (!yUpdate) {
/**
* Before the document is synchronized, we check if the update modifies the restricted type.
* If it does, we reject the update by undoing it, and calling the onReject callback.
*/
async beforeSync(data: beforeSyncPayload) {
// If the ySyncMessageType is not a messageYjsUpdate or a messageYjsSyncStep2, we don't handle the message, since it is not an update
if (
!(
data.type === syncProtocol.messageYjsUpdate ||
data.type === syncProtocol.messageYjsSyncStep2
)
) {
// not an update we want to handle
return;
}

const protectedType = ydoc.getMap(this.threadsMapKey);
const protectedType = data.document.getMap(this.threadsMapKey);
const didRollback = this.applyUpdateAndRollbackIfNeeded(
yUpdate,
ydoc,
data.payload,
data.document,
protectedType
);

if (didRollback) {
// TODO, we can close their connection or just let them continue, since we've already undone their changes (and our changes are newer than theirs)
const error = {
reason: `Modification of a restricted type: ${this.threadsMapKey} was rejected`,
} satisfies Partial<CloseEvent>;
throw error;
this.onReject?.(data);
}
}
}
Loading