This repository was archived by the owner on Feb 19, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathopenProjectApi.ts
More file actions
150 lines (127 loc) · 4.63 KB
/
openProjectApi.ts
File metadata and controls
150 lines (127 loc) · 4.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import type { onAuthenticatePayload, onLoadDocumentPayload, onStoreDocumentPayload } from "@hocuspocus/server";
import { Extension } from "@hocuspocus/server";
import * as Y from "yjs";
import type { ApiResponseDocument } from "../types";
import { ServerBlockNoteEditor } from "@blocknote/server-util";
import { BlockNoteSchema } from "@blocknote/core";
import { openProjectWorkPackageStaticBlockSpec } from "op-blocknote-extensions";
import { decryptToken } from "../services/decryptTokenService";
export const editorSchema = BlockNoteSchema.create().extend({
blockSpecs: {
"openProjectWorkPackage": openProjectWorkPackageStaticBlockSpec(),
},
});
export function createEditor() {
return ServerBlockNoteEditor.create({ schema: editorSchema });
}
export class OpenProjectApi implements Extension {
/**
* Authenticate the user by validating the token and document access
*/
async onAuthenticate(data: onAuthenticatePayload) {
const { token, documentName } = data;
const resourceUrl = documentName;
if (!token) {
throw new Error('Unauthorized: Token missing.');
}
const decryptedToken = decryptToken(token);
const allowedDomains = process.env.ALLOWED_DOMAINS?.split(',') || [];
if (allowedDomains.length <= 0) {
throw new Error('Unauthorized: No allowed domains configured.');
}
try {
const url = new URL(resourceUrl);
const isAllowed = allowedDomains.some(domain =>
url.hostname === domain.trim() || url.hostname.endsWith('.' + domain.trim())
);
if (!isAllowed) {
throw new Error('Unauthorized: Invalid base URL domain.');
}
} catch (error) {
if (error instanceof TypeError) {
throw new Error('Unauthorized: Invalid base URL format.');
}
throw error;
}
const response = await fetch(resourceUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${decryptedToken}`,
},
});
if (!response.ok) {
throw new Error('Unauthorized: Invalid token or document access denied.');
}
const jsonData = await response.json() as ApiResponseDocument;
// data.documentName = resourceUrl;
data.context.resourceUrl = resourceUrl;
data.context.token = decryptedToken;
if (!jsonData._links?.update) {
// https://tiptap.dev/docs/hocuspocus/guides/auth#read-only-mode
data.connectionConfig.readOnly = true;
data.context.readonly = true;
}
}
/**
* Retrieve data from the API. This should return the YDoc data
*/
async onLoadDocument(data: onLoadDocumentPayload) {
const { resourceUrl } = data.context;
console.log(`GET ${resourceUrl}`);
const response = await fetch(resourceUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${data.context.token}`,
},
});
if (!response.ok) {
console.warn(`Error fetching document: ${response.statusText}`);
return;
}
const jsonData = await response.json() as ApiResponseDocument;
if (jsonData.contentBinary) {
const update = new Uint8Array(Buffer.from(jsonData.contentBinary, 'base64'));
Y.applyUpdate(data.document, update);
}
}
/**
* Store data to the API. The data is a YDoc update
*/
async onStoreDocument(data: onStoreDocumentPayload): Promise<void> {
const { resourceUrl, readonly } = data.context;
if (!resourceUrl) {
console.warn("Missing parameters in context. Skipping store.");
return;
}
if (readonly) {
console.warn("Readonly user cannot make requests to store the document");
return;
}
console.log(`PATCH ${resourceUrl}`);
const base64Data = Buffer.from(Y.encodeStateAsUpdate(data.document)).toString("base64");
// Create a copy of the document to avoid side effects
const editor = createEditor();
const tempYdoc = new Y.Doc();
Y.applyUpdate(tempYdoc, Y.encodeStateAsUpdate(data.document));
const tempFragment = tempYdoc.getXmlFragment("document-store");
const editorData = editor.yXmlFragmentToBlocks(tempFragment);
// @ts-expect-error BlockNote types are complicated
const markdownData = await editor.blocksToMarkdownLossy(editorData);
const response = await fetch(resourceUrl, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${data.context.token}`,
},
body: JSON.stringify({
content_binary: base64Data,
description: markdownData,
}),
});
if (!response.ok) {
console.warn(`Error storing document: ${response.statusText}`);
}
}
}