forked from BetterAndBetterII/excalidraw-full
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-gate-frontend.patch
More file actions
229 lines (225 loc) · 8.22 KB
/
Copy pathcreate-gate-frontend.patch
File metadata and controls
229 lines (225 loc) · 8.22 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
diff --git a/excalidraw-app/App.tsx b/excalidraw-app/App.tsx
index 8c36fedb..d9740eab 100644
--- a/excalidraw-app/App.tsx
+++ b/excalidraw-app/App.tsx
@@ -140,6 +140,7 @@ import {
} from "./data/localStorage";
import { loadFilesFromFirebase } from "./data/firebase";
+import { consumeAuthError } from "./codiumAccessGate";
import {
LibraryIndexedDBAdapter,
LibraryLocalStorageMigrationAdapter,
@@ -605,6 +606,11 @@ const ExcalidrawWrapper = () => {
};
const loadCanvas = async () => {
+ // El acceso ya se decidió antes de renderizar (index.tsx). Aquí solo se
+ // muestra el aviso si el usuario vuelve de un login rechazado.
+ if (consumeAuthError(setErrorMessage)) {
+ return;
+ }
const jsonMatch = window.location.hash.match(
/^#json=([a-zA-Z0-9_-]+),([a-zA-Z0-9_-]+)$/,
);
diff --git a/excalidraw-app/codiumAccessGate.ts b/excalidraw-app/codiumAccessGate.ts
new file mode 100644
index 0000000..1f27978
--- /dev/null
+++ b/excalidraw-app/codiumAccessGate.ts
@@ -0,0 +1,112 @@
+import { jwtDecode } from "jwt-decode";
+
+import { getCollaborationLinkData } from "./data";
+
+// Codium access gate: usuarios sin sesión solo pueden abrir contenido EXISTENTE
+// (salas/escenas compartidas). El lienzo en blanco o una sala inexistente exigen
+// login. Gate blando (nivel de app), evaluado ANTES de renderizar para no
+// mostrar el editor a visitantes no autenticados.
+
+const UNAUTHORIZED_MESSAGE =
+ "Tu cuenta de GitHub no está autorizada para crear paneles en Codium.";
+
+export const isLoggedIn = (): boolean => {
+ const token = localStorage.getItem("token");
+ if (!token) {
+ return false;
+ }
+ try {
+ // jwt-decode maneja base64url correctamente (atob no).
+ const decoded = jwtDecode<{ exp?: number }>(token);
+ return typeof decoded.exp === "number" && decoded.exp * 1000 > Date.now();
+ } catch {
+ return false;
+ }
+};
+
+// Comprueba si una sala de colaboración EXISTE en el backend. Usa el endpoint
+// REST `documents:batchGet` (el único que implementa el backend self-hosted),
+// NO el SDK de Firebase: su getDoc abre un canal WebChannel "Listen" que el
+// backend no sirve (404) y haría fallar siempre la comprobación. El contenido va
+// cifrado con la roomKey; aquí solo nos interesa si existe, no descifrarlo.
+const roomExists = async (roomId: string): Promise<boolean> => {
+ let projectId = "";
+ try {
+ projectId = JSON.parse(import.meta.env.VITE_APP_FIREBASE_CONFIG).projectId;
+ } catch {
+ return false;
+ }
+ if (!projectId) {
+ return false;
+ }
+ // OJO: el nombre de recurso del documento NO lleva prefijo `/v1/` (ese prefijo
+ // es solo del path HTTP). Debe coincidir EXACTAMENTE con la key que guarda el
+ // SDK de Firebase al hacer commit, o el backend responde `missing`.
+ const docs = `projects/${projectId}/databases/(default)/documents`;
+ const name = `${docs}/scenes/${roomId}`;
+ try {
+ const res = await fetch(`/v1/${docs}:batchGet`, {
+ method: "POST",
+ headers: { "Content-Type": "text/plain" },
+ body: JSON.stringify({ documents: [name] }),
+ });
+ if (!res.ok) {
+ return false;
+ }
+ const data = await res.json();
+ return Array.isArray(data) && data.some((entry) => entry && entry.found);
+ } catch {
+ return false;
+ }
+};
+
+// Decide el acceso ANTES de renderizar. Devuelve false y redirige a login cuando
+// un visitante anónimo intenta llegar al lienzo en blanco o a una sala
+// inexistente. Devuelve true (renderizar) para usuarios logueados, salas/escenas
+// existentes, o un rebote de login rechazado (?auth_error), que la app muestra
+// luego con consumeAuthError.
+export const canAccessApp = async (): Promise<boolean> => {
+ const params = new URLSearchParams(window.location.search);
+ if (params.get("auth_error") === "unauthorized") {
+ return true;
+ }
+ if (params.get("token")) {
+ // Volvemos del callback de login: el token va en la URL y useAuth lo
+ // persistirá en localStorage. Dejar pasar (si no, se redirige a login en
+ // bucle porque aún no está en localStorage).
+ return true;
+ }
+ if (isLoggedIn()) {
+ return true;
+ }
+ const roomLinkData = getCollaborationLinkData(window.location.href);
+ if (roomLinkData && (await roomExists(roomLinkData.roomId))) {
+ return true;
+ }
+ const hash = window.location.hash;
+ if (/^#json=/.test(hash) || /^#url=/.test(hash)) {
+ return true;
+ }
+ window.location.href = "/auth/login";
+ return false;
+};
+
+// Si el visitante vuelve de un login rechazado, muestra el mensaje y limpia el
+// query param. Devuelve true si mostró mensaje.
+export const consumeAuthError = (
+ setErrorMessage: (message: string) => void,
+): boolean => {
+ const params = new URLSearchParams(window.location.search);
+ if (params.get("auth_error") !== "unauthorized") {
+ return false;
+ }
+ setErrorMessage(UNAUTHORIZED_MESSAGE);
+ params.delete("auth_error");
+ const qs = params.toString();
+ window.history.replaceState(
+ {},
+ document.title,
+ window.location.pathname + (qs ? `?${qs}` : "") + window.location.hash,
+ );
+ return true;
+};
diff --git a/excalidraw-app/index.html b/excalidraw-app/index.html
index 7eac3e39..c5bf396a 100644
--- a/excalidraw-app/index.html
+++ b/excalidraw-app/index.html
@@ -2,6 +2,34 @@
<html lang="en">
<head>
<meta charset="utf-8" />
+ <!-- Codium access gate (síncrono, antes de cargar el bundle): un visitante
+ sin sesión que abre la app en blanco se redirige a login al instante,
+ sin ver el editor. Las salas/escenas (#room=/#json=/#url=) las decide la
+ app (comprueba si existen). Ser conservador: si hay token, dejar pasar. -->
+ <script>
+ (function () {
+ try {
+ var loc = window.location;
+ var params = new URLSearchParams(loc.search);
+ if (params.get("auth_error") === "unauthorized") {
+ return;
+ }
+ if (params.get("token")) {
+ return;
+ }
+ if (localStorage.getItem("token")) {
+ return;
+ }
+ var hash = loc.hash || "";
+ if (/#room=/.test(hash) || /^#json=/.test(hash) || /^#url=/.test(hash)) {
+ return;
+ }
+ loc.replace("/auth/login");
+ } catch (e) {
+ /* ante cualquier duda, dejar que la app decida */
+ }
+ })();
+ </script>
<title>
Free, collaborative whiteboard • Hand-drawn look & feel | Excalidraw
</title>
diff --git a/excalidraw-app/index.tsx b/excalidraw-app/index.tsx
index 98c902e3..70769749 100644
--- a/excalidraw-app/index.tsx
+++ b/excalidraw-app/index.tsx
@@ -5,13 +5,21 @@ import { registerSW } from "virtual:pwa-register";
import "../excalidraw-app/sentry";
import ExcalidrawApp from "./App";
+import { canAccessApp } from "./codiumAccessGate";
window.__EXCALIDRAW_SHA__ = import.meta.env.VITE_APP_GIT_SHA;
const rootElement = document.getElementById("root")!;
const root = createRoot(rootElement);
registerSW();
-root.render(
- <StrictMode>
- <ExcalidrawApp />
- </StrictMode>,
-);
+// Gate de acceso ANTES de renderizar: evita el flash del editor a visitantes no
+// autenticados. Si no procede, canAccessApp() ya ha redirigido a login.
+canAccessApp().then((allowed) => {
+ if (!allowed) {
+ return;
+ }
+ root.render(
+ <StrictMode>
+ <ExcalidrawApp />
+ </StrictMode>,
+ );
+});
diff --git a/excalidraw-app/vite.config.mts b/excalidraw-app/vite.config.mts
index 90739e45..9a0ec645 100644
--- a/excalidraw-app/vite.config.mts
+++ b/excalidraw-app/vite.config.mts
@@ -149,6 +149,12 @@ export default defineConfig(({ mode }) => {
ViteEjsPlugin(),
VitePWA({
registerType: "autoUpdate",
+ // Codium self-host: desactivamos el service worker. Un SW cacheaba
+ // versiones viejas y provocaba ver el editor unos segundos tras cada
+ // deploy (y complicaba el gate de acceso). selfDestroying publica un SW
+ // que se desregistra y limpia caches en quienes ya lo tenían. El offline
+ // no aporta en una herramienta interna con login y backend.
+ selfDestroying: true,
devOptions: {
/* set this flag to true to enable in Development mode */
enabled: envVars.VITE_APP_ENABLE_PWA === "true",