diff --git a/src/hooks/access.ts b/src/hooks/access.ts index cda2335..7f2d24d 100644 --- a/src/hooks/access.ts +++ b/src/hooks/access.ts @@ -28,7 +28,7 @@ function parseProxyHeaders(requestHeaders: IncomingHttpHeaders): ProxyAuthHeader } export async function verifyYDocAccess( - { documentName, requestHeaders, connection }: onAuthenticatePayload + { documentName, requestHeaders, connection, token }: onAuthenticatePayload ): Promise<{} | ProxyAuthHeadersT> { if (documentName.startsWith("test/")) return {} @@ -38,24 +38,54 @@ export async function verifyYDocAccess( throw new HocusPocusError("Invalid document name") } - const response = await fetchStorage( - `/ydocs/${documentName}/access-level/`, - { headers: proxyAuthHeaders } - ) - - if (response?.ok) { - const data = await response.json() - if (data === "read-write") { - return proxyAuthHeaders - } else if (data === "read-only") { - connection.readOnly = true - return proxyAuthHeaders + if (token == documentName) { + const response = await fetchStorage( + `/ydocs/${documentName}/access-level/`, + { headers: proxyAuthHeaders } + ) + + if (response?.ok) { + const data = await response.json() + if (data === "read-write") { + return proxyAuthHeaders + } else if (data === "read-only") { + connection.readOnly = true + return proxyAuthHeaders + } else { + throw new HocusPocusError("Access Denied") + } + } else if (response?.status === 404) { + throw new HocusPocusError("YDoc not found") } else { - throw new HocusPocusError("Access Denied") + throw new HocusPocusError() } - } else if (response?.status === 404) { - throw new HocusPocusError("YDoc not found") } else { - throw new HocusPocusError() + const response = await fetchStorage( + `/v2/ydocs/${documentName}/access-level/`, + { + headers: { + "X-Storage-Token": token, + ...proxyAuthHeaders, + } + } + ) + + if (response?.ok) { + const data = await response.json() + if (data === "read-write") { + return proxyAuthHeaders + } else if (data === "read-only") { + connection.readOnly = true + return proxyAuthHeaders + } else { + throw new HocusPocusError("Access Denied") + } + } else if (response?.status === 403) { + throw new HocusPocusError("Invalid storage token") + } else if (response?.status === 404) { + throw new HocusPocusError("YDoc not found") + } else { + throw new HocusPocusError() + } } }