moodle-student-bridge 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.7.0 — 2026-11-20
4
+
5
+ Archivos en modo remoto. / Files in remote mode.
6
+
7
+ - Descargas por enlace temporal (un solo uso, 15 min): `descargar_materiales` da un ZIP y cada
8
+ archivo; `leer_archivo` y el `.ics` del calendario también dan enlace. El servidor pide el archivo a
9
+ Moodle en el momento: el token nunca aparece en el enlace.
10
+ - `preparar_subida` (remoto + escritura): página temporal (30 min) para subir el archivo desde el
11
+ celular, que valida en el momento tipos, tamaño y cantidad según la tarea. Luego
12
+ `preparar_entrega` con `subida` (o `"ultima"`) y `confirmar`; la subida se borra al entregar.
13
+ - `archivos_privados` y `preparar_entrega` con `privados`: entregar un archivo subido a "Mis
14
+ archivos privados" desde la app oficial de Moodle (también en local).
15
+ - Seguridad: enlaces con identificador de 144 bits, páginas sin JavaScript con CSP estricta, límite de
16
+ memoria para subidas; `core_files_get_files` restringido a los archivos privados del usuario.
17
+ - Nueva variable `MOODLE_REMOTO_URL_PUBLICA`.
18
+
19
+ ## 1.6.0 — 2026-11-20
20
+
21
+ Modo remoto. / Remote mode.
22
+
23
+ - `--http` (o `npm run remoto`): servidor MCP por Streamable HTTP para usarlo como conector
24
+ personalizado en claude.ai (web y app móvil). Un servidor MCP por sesión.
25
+ - Seguridad: URL con clave secreta (≥ 32 caracteres, comparación en tiempo constante, 404 sin pistas),
26
+ límite por IP, límite de tamaño, caducidad de sesiones, protección contra DNS rebinding opcional,
27
+ registros sin la clave. `--nueva-clave` genera una.
28
+ - En remoto: sin `descargar_materiales`, sin exportar `.ics` y sin subir archivos locales; la
29
+ escritura exige además `MOODLE_REMOTO_ESCRITURA=1`.
30
+ - `Dockerfile` (sin root, con healthcheck) y guía `docs/REMOTO.md` (túnel o nube).
31
+
3
32
  ## 1.5.0 — 2026-11-20
4
33
 
5
34
  Experiencia. / Experience.
package/README.es.md CHANGED
@@ -41,6 +41,7 @@ con su propia cuenta. Funciona con cualquier Moodle que tenga la app móvil habi
41
41
  | `buscar` | Busca un tema en secciones, actividades, archivos y foros; opcionalmente dentro de los PDF y documentos |
42
42
  | `participantes` | Profesores y compañeros del curso con rol y último acceso; filtra por tu grupo, nombre o rol |
43
43
  | `mis_grupos` | Tus grupos en cada curso con sus integrantes (Moodle no muestra a estudiantes los integrantes de grupos ajenos) |
44
+ | `archivos_privados` | Tus archivos privados de Moodle (se puede entregar desde ahí) |
44
45
  | `quien_soy` | Comprueba con qué cuenta estás conectado |
45
46
  | `estado_conexion` | Diagnóstico: token, versión, modo y qué funciones admite tu Moodle |
46
47
 
@@ -130,6 +131,21 @@ npm run probar # prueba: tu usuario y lo que vence esta semana
130
131
  claude mcp add moodle-student --scope user -- node /ruta/a/moodle-student-bridge/src/index.js
131
132
  ```
132
133
 
134
+ ## Usarlo desde claude.ai y el celular (modo remoto)
135
+
136
+ Córrelo como servidor web y agrégalo a claude.ai como **conector personalizado**: funciona en el
137
+ navegador y en la app de Claude del celular.
138
+
139
+ ```bash
140
+ npx moodle-student-bridge --http --nueva-clave # genera MOODLE_REMOTO_CLAVE
141
+ npm run remoto # + un túnel, o despliega el Dockerfile
142
+ ```
143
+
144
+ URL del conector: `https://tu-dominio/mcp/<MOODLE_REMOTO_CLAVE>`. Tu token de Moodle se queda en tu
145
+ servidor. Los archivos funcionan con **enlaces temporales en el chat**: descargas (sueltas o en ZIP) y
146
+ una página para subir entregas desde el celular. Por defecto solo lectura; en remoto la escritura
147
+ exige **dos** variables: `MOODLE_ESCRITURA=1` y `MOODLE_REMOTO_ESCRITURA=1`. Guía completa: [docs/REMOTO.md](docs/REMOTO.md).
148
+
133
149
  ## Modo escritura (opcional)
134
150
 
135
151
  Con `MOODLE_ESCRITURA=1` (o la casilla *Enable write mode* en Claude Desktop) aparecen herramientas
@@ -137,7 +153,8 @@ para **modificar** tu Moodle:
137
153
 
138
154
  | Herramienta | Qué prepara |
139
155
  |---|---|
140
- | `preparar_entrega` | Entregar o **editar** una tarea: archivos locales y/o texto en línea, modo `reemplazar` o `agregar` |
156
+ | `preparar_entrega` | Entregar o **editar** una tarea: archivos locales, lo subido desde el celular (`subida`), archivos privados (`privados`) y/o texto en línea; modo `reemplazar` o `agregar` |
157
+ | `preparar_subida` | Modo remoto: página temporal para subir desde el celular, con las reglas de la tarea |
141
158
  | `preparar_borrado_entrega` | **Eliminar** tu entrega |
142
159
  | `preparar_mensaje` | Mensaje privado (`"yo"` = tus notas personales, un id de conversación o un nombre) |
143
160
  | `preparar_publicacion_foro` | Responder en una discusión o abrir una nueva |
package/README.md CHANGED
@@ -59,6 +59,7 @@ The tool names are in Spanish, but Claude understands requests in any language.
59
59
  | `buscar` | Search a course's sections, activities, files and forums; optionally inside PDFs/Office files |
60
60
  | `participantes` | Teachers and classmates with role and last access; filter by your group, name or role |
61
61
  | `mis_grupos` | Your groups in each course and their members |
62
+ | `archivos_privados` | Your Moodle private files (you can submit from there) |
62
63
  | `quien_soy` | Shows which account is connected |
63
64
  | `estado_conexion` | Diagnostics: token, Moodle version, mode and which features your Moodle supports |
64
65
 
@@ -143,6 +144,21 @@ npm run probar # smoke test: your user and what's due this week
143
144
  claude mcp add moodle-student --scope user -- node /path/to/moodle-student-bridge/src/index.js
144
145
  ```
145
146
 
147
+ ## Use it from claude.ai and your phone (remote mode)
148
+
149
+ Run it as a web server and add it to claude.ai as a **custom connector**: it then works in the browser
150
+ and in the Claude mobile app.
151
+
152
+ ```bash
153
+ npx moodle-student-bridge --http --nueva-clave # generate MOODLE_REMOTO_CLAVE
154
+ npm run remoto # + a tunnel, or deploy the Dockerfile
155
+ ```
156
+
157
+ Connector URL: `https://your-domain/mcp/<MOODLE_REMOTO_CLAVE>`. Your Moodle token stays on your server.
158
+ Files work through **temporary links in the chat**: downloads (single files or a ZIP) and an upload
159
+ page for submissions from your phone. Read-only by default; in remote mode, write mode needs **both**
160
+ `MOODLE_ESCRITURA=1` and `MOODLE_REMOTO_ESCRITURA=1`. Full guide (Spanish): [docs/REMOTO.md](docs/REMOTO.md).
161
+
146
162
  ## Write mode (optional)
147
163
 
148
164
  Set `MOODLE_ESCRITURA=1` (or tick *Enable write mode* in Claude Desktop) to get tools that **change**
@@ -150,7 +166,8 @@ your Moodle:
150
166
 
151
167
  | Tool | Prepares |
152
168
  |---|---|
153
- | `preparar_entrega` | Submit or **edit** an assignment: local files and/or online text, `reemplazar` (replace) or `agregar` (add) |
169
+ | `preparar_entrega` | Submit or **edit** an assignment: local files, a phone upload (`subida`), private files (`privados`) and/or online text; `reemplazar` (replace) or `agregar` (add) |
170
+ | `preparar_subida` | Remote mode: temporary upload page for your phone, with the assignment's rules |
154
171
  | `preparar_borrado_entrega` | **Delete** your submission |
155
172
  | `preparar_mensaje` | Private message (`"yo"` = your personal notes, a conversation id or a name) |
156
173
  | `preparar_publicacion_foro` | Reply to a discussion or start a new one |
package/docs/REMOTO.md ADDED
@@ -0,0 +1,143 @@
1
+ # Modo remoto: usar el MCP desde claude.ai y el celular
2
+
3
+ En modo remoto, moodle-student-bridge corre como un servidor web y lo conectas a **claude.ai** como un
4
+ *conector personalizado*. Así lo puedes usar desde el navegador y desde la **app de Claude en el
5
+ celular**, sin tener la computadora encendida (si lo despliegas en la nube).
6
+
7
+ > Necesitas que tu plan de Claude permita agregar **conectores personalizados**. Los conectores que
8
+ > agregas en claude.ai también aparecen en la app móvil.
9
+
10
+ ## Cómo funciona
11
+
12
+ ```
13
+ claude.ai / app móvil ──HTTPS──▶ tu servidor (moodle-student-bridge --http) ──▶ tu Moodle
14
+ URL con clave secreta tu token se queda aquí
15
+ ```
16
+
17
+ - Es un servidor **para ti**: tu token de Moodle vive solo en el servidor, nunca viaja a claude.ai.
18
+ - La URL lleva una **clave secreta** larga: `https://tu-dominio/mcp/<MOODLE_REMOTO_CLAVE>`.
19
+ Quien tenga la URL puede usar tu Moodle (en solo lectura, salvo que actives la escritura):
20
+ **trátala como una contraseña**.
21
+
22
+ ## 1. Genera tu clave
23
+
24
+ ```bash
25
+ npx moodle-student-bridge --http --nueva-clave
26
+ # MOODLE_REMOTO_CLAVE=...
27
+ ```
28
+
29
+ Guárdala en tu `.env` junto a `MOODLE_URL` y `MOODLE_TOKEN`.
30
+
31
+ ## 2. Elige dónde correrlo
32
+
33
+ ### Opción A — Tu computadora + un túnel (rápido para probar)
34
+
35
+ ```bash
36
+ npm run remoto # escucha en http://127.0.0.1:3000
37
+ cloudflared tunnel --url http://localhost:3000
38
+ ```
39
+
40
+ `cloudflared` te da una URL `https://algo.trycloudflare.com`. Tu conector será:
41
+
42
+ ```
43
+ https://algo.trycloudflare.com/mcp/<MOODLE_REMOTO_CLAVE>
44
+ ```
45
+
46
+ Los túneles rápidos cambian de URL en cada arranque y solo funcionan con la PC encendida. Para algo
47
+ fijo, usa un túnel con nombre de Cloudflare o la opción B.
48
+
49
+ ### Opción B — En la nube con Docker (siempre disponible)
50
+
51
+ El repo incluye un `Dockerfile`. En cualquier servicio que ejecute contenedores (Render, Railway,
52
+ Fly.io, un VPS…), configura estas variables **como secretos**:
53
+
54
+ | Variable | Valor |
55
+ |---|---|
56
+ | `MOODLE_URL` | `https://moodle.tu-universidad.edu` |
57
+ | `MOODLE_TOKEN` | tu token |
58
+ | `MOODLE_REMOTO_CLAVE` | la clave del paso 1 |
59
+ | `MOODLE_TZ` | p. ej. `America/Guayaquil` |
60
+ | `MOODLE_REMOTO_URL_PUBLICA` | `https://mi-moodle.onrender.com` (para los enlaces de archivos) |
61
+ | `MOODLE_REMOTO_HOSTS` | tu dominio, p. ej. `mi-moodle.onrender.com` (protección extra) |
62
+
63
+ ```bash
64
+ docker build -t moodle-student-bridge .
65
+ docker run -p 3000:3000 --env-file .env moodle-student-bridge
66
+ ```
67
+
68
+ El contenedor corre sin root, expone `/salud` para los chequeos y escucha en el puerto `PORT`.
69
+
70
+ > Algunos servicios gratuitos "duermen" el contenedor tras un rato sin uso: la primera respuesta puede tardar.
71
+
72
+ ## 3. Conéctalo en claude.ai
73
+
74
+ 1. claude.ai → **Configuración → Conectores → Agregar conector personalizado**.
75
+ 2. Nombre: `Moodle`. URL: `https://tu-dominio/mcp/<MOODLE_REMOTO_CLAVE>`.
76
+ 3. Listo: pregúntale *"¿qué tengo que entregar esta semana?"* desde la web o desde la app.
77
+
78
+ ## Archivos desde el celular
79
+
80
+ El servidor no puede ver los archivos de tu celular ni guardar cosas en él, así que en remoto los
81
+ archivos van por **enlaces temporales** que Claude te muestra en el chat. Necesitas configurar
82
+ `MOODLE_REMOTO_URL_PUBLICA` con la dirección https de tu servidor.
83
+
84
+ **Descargar** (`descargar_materiales`, `leer_archivo`, calendario `.ics`):
85
+
86
+ > **Tú:** Pásame los PDF del segundo parcial de Física.
87
+ > **Claude:** 📦 Descargar todo en un ZIP · 📄 Leyes de Kepler.pdf · …
88
+
89
+ Al abrir el enlace, tu servidor pide el archivo a Moodle y te lo entrega: el token nunca sale del
90
+ servidor ni aparece en el enlace. Los enlaces son de **un solo uso** y caducan a los **15 minutos**.
91
+
92
+ **Entregar** (modo escritura en remoto):
93
+
94
+ 1. *"Quiero entregar mi informe en el proyecto de Física"* → Claude usa `preparar_subida` y te da un
95
+ enlace 📤 a una página con las reglas de la tarea (tipos, tamaño y cantidad).
96
+ 2. Eliges el archivo en el celular. La página **rechaza en el momento** lo que no cumple. Subir **no**
97
+ entrega nada.
98
+ 3. Le dices *"ya lo subí"*: Claude prepara la entrega con lo subido, te muestra la vista previa con
99
+ todos los avisos y solo entrega si confirmas.
100
+ 4. Tras entregar, o a los **30 minutos**, el archivo se borra del servidor.
101
+
102
+ **Alternativa — "Mis archivos privados" de Moodle:** si tu Moodle los tiene, sube el archivo desde la
103
+ app oficial de Moodle (Archivos privados) y pide *"entrega el archivo X de mis archivos privados"*
104
+ (`archivos_privados` + `preparar_entrega` con `privados`). Esto también funciona en modo local.
105
+
106
+ ## Qué cambia en remoto
107
+
108
+ | | Local | Remoto |
109
+ |---|---|---|
110
+ | Herramientas de lectura, asistencia, comandos rápidos | ✅ | ✅ |
111
+ | `descargar_materiales` | guarda en Descargas | 🔗 enlace a ZIP y a cada archivo |
112
+ | `leer_archivo` | texto + guarda en Descargas | texto + 🔗 enlace al original |
113
+ | Exportar `.ics` | guarda el archivo | 🔗 enlace (o `suscripcion=true`, que se actualiza solo) |
114
+ | Entregar archivos | rutas de tu PC o archivos privados | 📤 `preparar_subida` o archivos privados |
115
+ | Modo escritura | `MOODLE_ESCRITURA=1` | además `MOODLE_REMOTO_ESCRITURA=1` |
116
+
117
+ ## Seguridad
118
+
119
+ - **Solo lectura por defecto.** En remoto, la escritura exige **dos** variables: `MOODLE_ESCRITURA=1`
120
+ y `MOODLE_REMOTO_ESCRITURA=1`. Aun así, cada acción pide vista previa y tu confirmación.
121
+ - La clave se compara en tiempo constante; una clave incorrecta da el mismo 404 que cualquier ruta
122
+ inexistente.
123
+ - Límite de 120 peticiones por minuto por IP (`MOODLE_REMOTO_LIMITE`) y 1 MB por petición.
124
+ - Las sesiones caducan tras 30 minutos sin uso.
125
+ - Los registros nunca muestran la clave (salvo una temporal) ni el contenido de las peticiones.
126
+ - Enlaces de archivos: identificador aleatorio de 144 bits, de un solo uso, caducan (15 min las
127
+ descargas, 30 min las subidas), páginas sin JavaScript con CSP estricta, solo archivos de tu propio
128
+ Moodle, subidas limitadas en tamaño (y 120 MB en total) y borradas tras usarse. No compartas los
129
+ enlaces mientras estén vigentes.
130
+ - Si se filtra la URL: cambia `MOODLE_REMOTO_CLAVE`, reinicia y actualiza el conector. Si crees que
131
+ también se expuso tu token de Moodle, regénéralo.
132
+
133
+ ## Variables
134
+
135
+ | Variable | Uso |
136
+ |---|---|
137
+ | `MOODLE_REMOTO_CLAVE` | Clave secreta de la URL (≥ 32 caracteres) |
138
+ | `MOODLE_REMOTO_URL_PUBLICA` | Dirección https de tu servidor, para crear los enlaces de descarga y subida |
139
+ | `PORT` / `MOODLE_REMOTO_PUERTO` | Puerto (por defecto 3000) |
140
+ | `HOST` / `MOODLE_REMOTO_HOST` | Interfaz (por defecto `127.0.0.1`; en contenedores `0.0.0.0`) |
141
+ | `MOODLE_REMOTO_HOSTS` | Dominios permitidos en la cabecera Host (anti DNS rebinding) |
142
+ | `MOODLE_REMOTO_LIMITE` | Peticiones por minuto por IP (por defecto 120) |
143
+ | `MOODLE_REMOTO_ESCRITURA` | `1` para permitir escritura en remoto (además de `MOODLE_ESCRITURA=1`) |
package/docs/ROADMAP.md CHANGED
@@ -46,8 +46,8 @@ Las fases van en orden de prioridad.
46
46
 
47
47
  ## Fase 5 — Grandes y opcionales
48
48
 
49
- - Modo remoto (HTTP) para usarlo desde claude.ai o el celular.
50
- - Exportar apuntes del curso a un vault de Obsidian.
49
+ - ✅ Modo remoto (HTTP) para usarlo desde claude.ai o el celular (v1.6) — ver [REMOTO.md](REMOTO.md).
50
+ - ⏸ Exportar apuntes del curso a un vault de Obsidian (pospuesto).
51
51
 
52
52
  ## Fase 6 — Modo restringido: cuestionarios (pruebas y demostración)
53
53
 
package/manifest.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "manifest_version": "0.2",
3
3
  "name": "moodle-student-bridge",
4
4
  "display_name": "Moodle Student Bridge",
5
- "version": "1.5.0",
5
+ "version": "1.7.0",
6
6
  "description": "Connect Claude to your Moodle as a student: deadlines, assignments, quizzes, files, announcements and grades.",
7
7
  "long_description": "Uses your own Moodle mobile-app token (service moodle_mobile_app), so it works without an admin-issued API token. Read-only by default. Optional write mode (submit/edit/delete assignment submissions, messages, forum posts) always works in two steps: a preview with every check and warning, then an explicit confirmation code.",
8
8
  "author": {
@@ -221,6 +221,14 @@
221
221
  {
222
222
  "name": "cambiar_sitio",
223
223
  "description": "Switch the active Moodle site"
224
+ },
225
+ {
226
+ "name": "archivos_privados",
227
+ "description": "Your Moodle private files"
228
+ },
229
+ {
230
+ "name": "preparar_subida",
231
+ "description": "Remote write mode: temporary upload page for your phone"
224
232
  }
225
233
  ],
226
234
  "compatibility": {
package/package.json CHANGED
@@ -1,16 +1,18 @@
1
1
  {
2
2
  "name": "moodle-student-bridge",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "MCP bridge for students: connect Claude to your Moodle courses, assignments, quizzes, files and grades using your own mobile-app token — no admin-issued API token needed.",
5
5
  "keywords": [
6
6
  "attendance",
7
7
  "claude",
8
+ "claude.ai",
8
9
  "lms",
9
10
  "mcp",
10
11
  "model-context-protocol",
11
12
  "moodle",
12
13
  "ntfy",
13
14
  "reminders",
15
+ "remote",
14
16
  "students"
15
17
  ],
16
18
  "type": "module",
@@ -34,7 +36,8 @@
34
36
  "probar": "node src/probar.js",
35
37
  "recordar": "node src/recordar.js",
36
38
  "test": "node scripts/verificar-sintaxis.js && node --test test/*.test.js",
37
- "mcpb": "npx -y @anthropic-ai/mcpb@2.1.2 pack . moodle-student-bridge.mcpb"
39
+ "mcpb": "npx -y @anthropic-ai/mcpb@2.1.2 pack . moodle-student-bridge.mcpb",
40
+ "remoto": "node src/index.js --http"
38
41
  },
39
42
  "engines": {
40
43
  "node": ">=20.12"
package/src/enlaces.js ADDED
@@ -0,0 +1,108 @@
1
+ // Enlaces temporales del modo remoto: descargas (archivo, ZIP, .ics) y páginas de subida.
2
+ //
3
+ // - Cada enlace tiene un identificador aleatorio de 144 bits (imposible de adivinar), caduca y tiene
4
+ // un número máximo de usos. El token de Moodle NUNCA aparece en el enlace: el servidor descarga de
5
+ // Moodle y entrega el archivo.
6
+ // - Las subidas se guardan en memoria con límites de tamaño y se borran al usarse o al caducar.
7
+
8
+ import { randomBytes } from "node:crypto";
9
+ import { MoodleError } from "./moodle.js";
10
+
11
+ export const DESCARGA_TTL_MS = 15 * 60_000;
12
+ export const SUBIDA_TTL_MS = 30 * 60_000;
13
+ const MAX_ENLACES = 500;
14
+ export const MAX_MEMORIA_SUBIDAS = 120 * 1048576; // 120 MB entre todas las subidas pendientes
15
+
16
+ export const nuevoId = () => randomBytes(18).toString("base64url");
17
+
18
+ export class Enlaces {
19
+ constructor(ahora = () => Date.now()) {
20
+ this.ahora = ahora;
21
+ this.mapa = new Map();
22
+ }
23
+
24
+ baseUrl() {
25
+ const b = (process.env.MOODLE_REMOTO_URL_PUBLICA ?? "").replace(/\/+$/, "");
26
+ if (!/^https?:\/\/[^/]+/.test(b))
27
+ throw new MoodleError("Falta MOODLE_REMOTO_URL_PUBLICA (la dirección https de tu servidor, p. ej. https://mi-moodle.onrender.com) para crear enlaces.", "config");
28
+ return b;
29
+ }
30
+
31
+ limpiar() {
32
+ const t = this.ahora();
33
+ for (const [id, e] of this.mapa) if (e.expira < t || e.usos <= 0) this.mapa.delete(id);
34
+ }
35
+
36
+ _guardar(entrada) {
37
+ this.limpiar();
38
+ if (this.mapa.size >= MAX_ENLACES) throw new MoodleError("Hay demasiados enlaces activos; espera unos minutos.", "limite");
39
+ const id = nuevoId();
40
+ this.mapa.set(id, entrada);
41
+ return id;
42
+ }
43
+
44
+ /**
45
+ * Enlace de descarga. `generar` se ejecuta al abrirlo y devuelve { nombre, tipo, datos }.
46
+ * Por defecto de un solo uso.
47
+ */
48
+ descarga(generar, { nombre, usos = 1, ttl = DESCARGA_TTL_MS } = {}) {
49
+ const id = this._guardar({ clase: "descarga", generar, nombre, usos, expira: this.ahora() + ttl });
50
+ return { id, url: `${this.baseUrl()}/d/${id}`, expira: this.ahora() + ttl };
51
+ }
52
+
53
+ /** Toma un enlace de descarga (consume un uso). */
54
+ tomarDescarga(id) {
55
+ this.limpiar();
56
+ const e = this.mapa.get(id);
57
+ if (!e || e.clase !== "descarga") return null;
58
+ e.usos--;
59
+ return e;
60
+ }
61
+
62
+ /** Página de subida con las reglas de la tarea (tipos, tamaño, cantidad). */
63
+ subida(reglas, { ttl = SUBIDA_TTL_MS } = {}) {
64
+ const id = this._guardar({ clase: "subida", reglas, archivos: [], usos: 1, expira: this.ahora() + ttl });
65
+ return { id, url: `${this.baseUrl()}/subir/${id}`, expira: this.ahora() + ttl };
66
+ }
67
+
68
+ verSubida(id) {
69
+ this.limpiar();
70
+ const e = this.mapa.get(id);
71
+ return e?.clase === "subida" ? e : null;
72
+ }
73
+
74
+ memoriaSubidas() {
75
+ let total = 0;
76
+ for (const e of this.mapa.values()) if (e.clase === "subida") total += e.archivos.reduce((s, f) => s + f.datos.length, 0);
77
+ return total;
78
+ }
79
+
80
+ /** Archivos recibidos en una subida (para preparar_entrega). */
81
+ archivosDe(id) {
82
+ const e = this.verSubida(id);
83
+ if (!e) throw new MoodleError("La subida no existe o caducó (30 min). Crea otra con preparar_subida.", "subida");
84
+ if (!e.archivos.length) throw new MoodleError("Todavía no subiste ningún archivo en ese enlace. Ábrelo y elige el archivo.", "subida");
85
+ return e.archivos;
86
+ }
87
+
88
+ /** La subida más reciente con archivos (cuando el usuario dice "ya lo subí"). */
89
+ ultimaSubidaConArchivos() {
90
+ this.limpiar();
91
+ let ultima = null;
92
+ for (const [id, e] of this.mapa) if (e.clase === "subida" && e.archivos.length && (!ultima || e.recibido > ultima.e.recibido)) ultima = { id, e };
93
+ return ultima?.id ?? null;
94
+ }
95
+
96
+ borrar(id) {
97
+ this.mapa.delete(id);
98
+ }
99
+ }
100
+
101
+ /** Almacén compartido por todas las sesiones del servidor remoto. */
102
+ export const enlaces = new Enlaces();
103
+
104
+ /** Content-Disposition seguro para cualquier nombre (RFC 6266 / 5987). */
105
+ export function disposicion(nombre = "archivo") {
106
+ const ascii = nombre.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
107
+ return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(nombre)}`;
108
+ }
package/src/escritura.js CHANGED
@@ -11,6 +11,7 @@ import { randomInt } from "node:crypto";
11
11
  import { appendFile, mkdir, readFile, realpath, stat } from "node:fs/promises";
12
12
  import { motivoArchivoBloqueado } from "./seguridad.js";
13
13
  import { ejecutarAsistencia } from "./asistencia.js";
14
+ import { enlaces } from "./enlaces.js";
14
15
  import { homedir } from "node:os";
15
16
  import { basename, dirname, extname, join, resolve } from "node:path";
16
17
  import { z } from "zod";
@@ -249,6 +250,33 @@ export async function leerArchivosLocales(rutas) {
249
250
  return salida;
250
251
  }
251
252
 
253
+ /**
254
+ * Junta los archivos a entregar desde sus tres orígenes posibles:
255
+ * - rutas locales (solo en modo local; con las protecciones de leerArchivosLocales)
256
+ * - una subida hecha desde el celular con preparar_subida (modo remoto)
257
+ * - "Mis archivos privados" de Moodle
258
+ * Cada elemento trae `obtener()` para leer los bytes recién al confirmar.
259
+ */
260
+ export async function reunirArchivos(m, { archivos = [], subida, privados = [] } = {}) {
261
+ const salida = [];
262
+ for (const f of await leerArchivosLocales(archivos)) salida.push({ ...f, origen: "local", obtener: () => readFile(f.ruta) });
263
+ if (subida)
264
+ for (const f of enlaces.archivosDe(subida)) salida.push({ nombre: f.nombre, tamano: f.tamano, origen: "subida", obtener: async () => f.datos });
265
+ if (privados.length) {
266
+ const lista = await m.archivosPrivados();
267
+ for (const p of privados) {
268
+ const q = normalizar(p.replace(/^\/+/, ""));
269
+ let hallados = lista.filter((f) => normalizar(f.ruta.replace(/^\/+/, "")) === q || normalizar(f.filename) === q);
270
+ if (!hallados.length) hallados = lista.filter((f) => normalizar(f.ruta).includes(q));
271
+ if (!hallados.length) throw new MoodleError(`No encontré "${p}" en tus archivos privados. Usa archivos_privados para ver la lista.`);
272
+ if (hallados.length > 1) throw new MoodleError(`"${p}" coincide con varios archivos privados: ${hallados.map((f) => f.ruta).join(", ")}.`);
273
+ const f = hallados[0];
274
+ salida.push({ nombre: f.filename, tamano: f.filesize, origen: "privado", obtener: () => m.bajar(f.fileurl) });
275
+ }
276
+ }
277
+ return salida;
278
+ }
279
+
252
280
  /** Comprueba archivos/texto contra las reglas de la tarea. Devuelve problemas (bloqueos) y avisos. */
253
281
  export function validarContenido(a, { archivosNuevos = [], modo = "reemplazar", texto }) {
254
282
  const problemas = [];
@@ -294,7 +322,7 @@ export function validarContenido(a, { archivosNuevos = [], modo = "reemplazar",
294
322
  * @param moodle () => instancia Moodle
295
323
  * @param resolverTarea, resolverCurso helpers de index.js
296
324
  */
297
- export function registrarEscritura({ herramienta, moodle, resolverTarea, resolverCurso, resolverAlias = () => null, confirmaciones = new Confirmaciones() }) {
325
+ export function registrarEscritura({ herramienta, moodle, resolverTarea, resolverCurso, resolverAlias = () => null, remoto = false, confirmaciones = new Confirmaciones() }) {
298
326
  const lineas = (titulo, items) => (items.length ? [`\n${titulo}`, ...items.map((i) => `- ${i}`)] : []);
299
327
 
300
328
  const pie = (codigo) =>
@@ -309,16 +337,22 @@ export function registrarEscritura({ herramienta, moodle, resolverTarea, resolve
309
337
  {
310
338
  tarea: z.string().describe("Id o nombre de la tarea"),
311
339
  curso: z.string().optional(),
312
- archivos: z.array(z.string()).optional().describe("Rutas locales de los archivos a entregar"),
340
+ archivos: z.array(z.string()).optional().describe(remoto ? "No disponible en remoto: usa subida o privados" : "Rutas locales de los archivos a entregar"),
341
+ subida: z.string().optional().describe("Id de una subida hecha con preparar_subida, o 'ultima' para la más reciente"),
342
+ privados: z.array(z.string()).optional().describe("Nombres de archivos de 'Mis archivos privados' de Moodle (ver archivos_privados)"),
313
343
  texto: z.string().optional().describe("Texto en línea (HTML o texto plano), si la tarea lo admite"),
314
344
  modo: z.enum(["reemplazar", "agregar"]).default("reemplazar").describe("reemplazar los archivos actuales o agregarlos a los existentes"),
315
345
  enviar_para_calificar: z.boolean().default(true).describe("En tareas con borradores: además de guardar, enviarla para calificar"),
316
346
  },
317
- async ({ tarea, curso, archivos = [], texto, modo = "reemplazar", enviar_para_calificar = true }) => {
318
- if (!archivos.length && texto === undefined) throw new MoodleError("Indica archivos y/o texto para entregar.");
347
+ async ({ tarea, curso, archivos = [], subida, privados = [], texto, modo = "reemplazar", enviar_para_calificar = true }) => {
348
+ if (!archivos.length && !subida && !privados.length && texto === undefined) throw new MoodleError("Indica archivos, una subida, archivos privados y/o texto para entregar.");
349
+ if (remoto && archivos.length)
350
+ throw new MoodleError("En modo remoto no se pueden leer archivos del dispositivo: usa preparar_subida (enlace para subir desde el celular) o tus archivos privados de Moodle.");
319
351
  const t = await resolverTarea(tarea, curso);
320
352
  const a = await analizarTarea(moodle(), t);
321
- const nuevos = await leerArchivosLocales(archivos);
353
+ const idSubida = subida ? (subida === "ultima" ? enlaces.ultimaSubidaConArchivos() : subida) : undefined;
354
+ if (subida && !idSubida) throw new MoodleError("No hay ninguna subida con archivos. Crea una con preparar_subida y sube el archivo.");
355
+ const nuevos = await reunirArchivos(moodle(), { archivos, subida: idSubida, privados });
322
356
  const v = validarContenido(a, { archivosNuevos: nuevos, modo, texto });
323
357
  const bloqueos = [...a.bloqueos, ...v.problemas];
324
358
 
@@ -345,7 +379,9 @@ export function registrarEscritura({ herramienta, moodle, resolverTarea, resolve
345
379
  tipo: "entrega",
346
380
  assignid: t.id,
347
381
  nombre: t.name,
348
- archivos: nuevos.map((f) => f.ruta),
382
+ archivos: nuevos.filter((f) => f.origen === "local").map((f) => f.ruta),
383
+ subida: idSubida,
384
+ privados,
349
385
  texto,
350
386
  modo,
351
387
  enviar: !!(t.submissiondrafts && enviar_para_calificar),
@@ -355,6 +391,32 @@ export function registrarEscritura({ herramienta, moodle, resolverTarea, resolve
355
391
  },
356
392
  );
357
393
 
394
+ // ---------------- subir desde el celular (solo remoto)
395
+
396
+ if (remoto)
397
+ herramienta(
398
+ "preparar_subida",
399
+ "Modo remoto: crea un enlace temporal (30 min, un solo uso) a una página donde el usuario elige el archivo desde su celular o computadora. La página ya aplica las reglas de la tarea (tipos, tamaño, cantidad). Subir NO entrega: después usa preparar_entrega con subida.",
400
+ { tarea: z.string().describe("Id o nombre de la tarea"), curso: z.string().optional() },
401
+ async ({ tarea, curso }) => {
402
+ const t = await resolverTarea(tarea, curso);
403
+ const a = await analizarTarea(moodle(), t);
404
+ if (a.bloqueos.length) return [`# ${t.name}`, ...lineas("⛔ No se puede entregar:", a.bloqueos)].join("\n");
405
+ if (!a.archivosOn) return `⛔ "${t.name}" no acepta archivos${a.textoOn ? " (solo texto en línea: usa preparar_entrega con texto)" : ""}.`;
406
+ const extensiones = a.tipos && !a.tipos.desconocidos.length ? [...a.tipos.extensiones] : null;
407
+ const l = enlaces.subida({ tarea: t.name, curso: t.curso, extensiones, maxBytes: a.maxBytes || 25 * 1048576, maxArchivos: a.maxArchivos || 1 });
408
+ return [
409
+ `# Subir archivo para: ${t.name}`,
410
+ `📤 [Elegir y subir el archivo](${l.url})`,
411
+ `Reglas: ${extensiones ? extensiones.join(", ") : "cualquier tipo"} · hasta ${bytes(a.maxBytes || 25 * 1048576)} · máx. ${a.maxArchivos || 1} archivo(s).`,
412
+ ...lineas("⚠ Avisos de la tarea:", a.avisos),
413
+ "",
414
+ `Id de la subida: ${l.id}`,
415
+ "Enlace privado, de un solo uso y válido 30 min. Muéstraselo al usuario. Cuando diga que ya subió el archivo, llama a preparar_entrega con subida=<id> (o 'ultima').",
416
+ ].join("\n");
417
+ },
418
+ );
419
+
358
420
  herramienta(
359
421
  "preparar_borrado_entrega",
360
422
  "PASO 1 de 2 para ELIMINAR tu entrega de una tarea (archivos y texto). Solo comprueba; devuelve un resumen y un código para `confirmar`.",
@@ -618,7 +680,7 @@ async function ejecutarEntrega(m, acc, { aceptar_declaracion, resolverTarea }) {
618
680
  m._cache.clear();
619
681
  const t = await resolverTarea(String(acc.assignid));
620
682
  const a = await analizarTarea(m, t);
621
- const nuevos = await leerArchivosLocales(acc.archivos);
683
+ const nuevos = await reunirArchivos(m, acc);
622
684
  const v = validarContenido(a, { archivosNuevos: nuevos, modo: acc.modo, texto: acc.texto });
623
685
  const bloqueos = [...a.bloqueos, ...v.problemas];
624
686
  if (bloqueos.length) throw new MoodleError(`Cancelado, no se envió nada: ${bloqueos.join(" ")}`);
@@ -636,7 +698,7 @@ async function ejecutarEntrega(m, acc, { aceptar_declaracion, resolverTarea }) {
636
698
  const conservar = acc.modo === "agregar" || !nuevos.length ? a.archivosActuales : [];
637
699
  const subir = [];
638
700
  for (const f of conservar) subir.push({ nombre: f.filename, datos: await m.bajar(f.fileurl) });
639
- for (const f of nuevos) subir.push({ nombre: f.nombre, datos: await readFile(f.ruta) });
701
+ for (const f of nuevos) subir.push({ nombre: f.nombre, datos: await f.obtener() });
640
702
  const itemid = subir.length
641
703
  ? await m.subirBorrador(subir)
642
704
  : (await m.llamar("core_files_get_unused_draft_itemid", {})).itemid;
@@ -657,6 +719,9 @@ async function ejecutarEntrega(m, acc, { aceptar_declaracion, resolverTarea }) {
657
719
  if (Array.isArray(w) && w.length) throw new MoodleError(`Se guardó como borrador, pero no se pudo enviar para calificar: ${w.map((x) => x.message ?? x.item).join("; ")}`);
658
720
  }
659
721
 
722
+ // La subida temporal ya no hace falta: se borra de la memoria del servidor.
723
+ if (acc.subida) enlaces.borrar(acc.subida);
724
+
660
725
  // 6. Verificar lo que quedó en Moodle.
661
726
  m._cache.clear();
662
727
  const despues = await analizarTarea(m, t);
package/src/estudio.js CHANGED
@@ -3,7 +3,9 @@
3
3
 
4
4
  import { mkdir, stat, writeFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
- import { extname, join, resolve } from "node:path";
6
+ import { extname, join, resolve, sep } from "node:path";
7
+ import { zipSync } from "fflate";
8
+ import { enlaces } from "./enlaces.js";
7
9
  import { z } from "zod";
8
10
  import { extractText, getDocumentProxy } from "unpdf";
9
11
  import { MoodleError, fecha, hace, htmlATexto, normalizar, textoOffice } from "./moodle.js";
@@ -112,7 +114,7 @@ export function crearBuscador(consulta) {
112
114
 
113
115
  // ------------------------------------------------------------------ registro
114
116
 
115
- export function registrarEstudio({ herramienta, moodle, resolverCurso }) {
117
+ export function registrarEstudio({ herramienta, moodle, resolverCurso, remoto = false }) {
116
118
  const cursosObjetivo = async (curso) => {
117
119
  const c = await resolverCurso(curso);
118
120
  return c ? [c] : moodle().cursos();
@@ -335,11 +337,13 @@ export function registrarEstudio({ herramienta, moodle, resolverCurso }) {
335
337
  },
336
338
  );
337
339
 
338
- // ---------------- descargar_materiales
340
+ // ---------------- descargar_materiales (en remoto devuelve enlaces temporales en vez de guardar en disco)
339
341
 
340
342
  herramienta(
341
343
  "descargar_materiales",
342
- "Descarga los archivos de un curso (o de una sección) a tu computadora, organizados en Descargas/moodle-student-bridge/<curso>/<sección>/. No vuelve a bajar lo que ya tienes. No modifica Moodle.",
344
+ remoto
345
+ ? "Descarga los archivos de un curso (o de una sección): devuelve un enlace a un ZIP con todo y enlaces a cada archivo, para abrirlos desde el celular o el navegador. Enlaces temporales de un solo uso. No modifica Moodle."
346
+ : "Descarga los archivos de un curso (o de una sección) a tu computadora, organizados en Descargas/moodle-student-bridge/<curso>/<sección>/. No vuelve a bajar lo que ya tienes. No modifica Moodle.",
343
347
  {
344
348
  curso: z.string().describe("Id o parte del nombre del curso"),
345
349
  seccion: z.string().optional().describe("Parte del nombre de la sección (opcional)"),
@@ -374,6 +378,39 @@ export function registrarEstudio({ herramienta, moodle, resolverCurso }) {
374
378
  const MAX_BYTES = 500 * 1048576;
375
379
  const totalBytes = archivos.reduce((s, f) => s + (f.filesize ?? 0), 0);
376
380
  const mb = (b) => `${(b / 1048576).toFixed(1)} MB`;
381
+
382
+ // Modo remoto: en vez de escribir en el disco del servidor, enlaces temporales para el celular.
383
+ if (remoto && !solo_listar) {
384
+ const MAX_ZIP = 150 * 1048576;
385
+ if (totalBytes > MAX_ZIP) return `Son ${mb(totalBytes)}: supera el máximo de ${mb(MAX_ZIP)} por ZIP. Filtra por sección o por tipos.`;
386
+ const rel = (f) => f.dest.slice(base.length + 1).split(sep).join("/");
387
+ const zipNombre = `${nombreSeguro(c.shortname || c.fullname, 60)}${seccion ? `-${nombreSeguro(seccion, 40)}` : ""}.zip`;
388
+ const zip = enlaces.descarga(
389
+ async () => {
390
+ const entradas = {};
391
+ for (const f of archivos) entradas[rel(f)] = new Uint8Array(await m.bajar(f.fileurl));
392
+ return { nombre: zipNombre, tipo: "application/zip", datos: Buffer.from(zipSync(entradas, { level: 0 })) };
393
+ },
394
+ { nombre: zipNombre },
395
+ );
396
+ const sueltos = archivos.slice(0, 25).map((f) => {
397
+ const l = enlaces.descarga(async () => ({ nombre: f.filename, tipo: f.mimetype, datos: await m.bajar(f.fileurl) }), { nombre: f.filename });
398
+ return `- [${f.filename}](${l.url}) (${mb(f.filesize ?? 0)})`;
399
+ });
400
+ return [
401
+ `# ${c.fullname}${seccion ? ` · ${seccion}` : ""}: ${archivos.length} archivos (${mb(totalBytes)})`,
402
+ "",
403
+ `📦 [Descargar todo en un ZIP](${zip.url})`,
404
+ "",
405
+ ...sueltos,
406
+ archivos.length > 25 ? `… y ${archivos.length - 25} más (incluidos en el ZIP).` : "",
407
+ "",
408
+ "Enlaces temporales de un solo uso, válidos 15 minutos. Muéstraselos al usuario tal cual (son privados: no los compartas).",
409
+ ]
410
+ .filter((x) => x !== "")
411
+ .join("\n");
412
+ }
413
+
377
414
  if (solo_listar)
378
415
  return [`Se descargarían ${archivos.length} archivos (${mb(totalBytes)}) en:`, base, "", ...archivos.slice(0, 80).map((f) => `- ${f.dest.slice(base.length + 1)} (${mb(f.filesize ?? 0)})`)].join("\n");
379
416
  if (archivos.length > MAX_ARCHIVOS || totalBytes > MAX_BYTES)
package/src/index.js CHANGED
@@ -16,13 +16,19 @@ import { registrarAsistencia } from "./asistencia.js";
16
16
  import { Sitios, leerSitios } from "./sitios.js";
17
17
  import { Anonimizador } from "./privacidad.js";
18
18
  import { registrarPrompts } from "./prompts.js";
19
+ import { enlaces } from "./enlaces.js";
19
20
  import { createHash } from "node:crypto";
20
21
 
21
22
  cargarEnv();
22
23
 
23
24
  const MAX_TEXTO = 60_000;
24
25
 
25
- const MODO_ESCRITURA = ["1", "true"].includes(process.env.MOODLE_ESCRITURA ?? "");
26
+ const activado = (v) => ["1", "true"].includes(process.env[v] ?? "");
27
+
28
+ // Modo remoto (HTTP, para claude.ai web y móvil): ver remoto.js.
29
+ const MODO_REMOTO = process.argv.includes("--http") || activado("MOODLE_REMOTO");
30
+ // En remoto, escribir en Moodle exige además MOODLE_REMOTO_ESCRITURA=1 (doble llave a propósito).
31
+ const MODO_ESCRITURA = activado("MOODLE_ESCRITURA") && (!MODO_REMOTO || activado("MOODLE_REMOTO_ESCRITURA"));
26
32
 
27
33
  // Uno o varios sitios Moodle (ver sitios.js); las herramientas siempre usan el sitio activo.
28
34
  const sitios = new Sitios(leerSitios(), { escritura: MODO_ESCRITURA, inicial: process.env.MOODLE_SITIO });
@@ -54,9 +60,8 @@ const anonimo = new Anonimizador({
54
60
  });
55
61
  sitios.alCambiar.push(() => (anonimo.listoHasta = 0));
56
62
 
57
- const server = new McpServer(
58
- { name: "moodle-student-bridge", version: "1.5.0" },
59
- {
63
+ const INFO_SERVIDOR = { name: "moodle-student-bridge", version: "1.7.0" };
64
+ const OPCIONES_SERVIDOR = {
60
65
  instructions:
61
66
  "Herramientas para el Moodle del estudiante. Las de lectura se pueden usar libremente. " +
62
67
  "Si existen herramientas preparar_* (modo escritura activado): NUNCA llames a `confirmar` por iniciativa propia. " +
@@ -65,15 +70,29 @@ const server = new McpServer(
65
70
  "muéstrasela y pide que la acepte antes de usar aceptar_declaracion=true." +
66
71
  (MODO_ANONIMO
67
72
  ? " Modo anónimo activo: los compañeros aparecen como alias 'Estudiante-XXXX'. No intentes deducir sus nombres reales; usa el alias (también sirve como destinatario de mensajes)."
68
- : ""),
69
- },
70
- );
73
+ : "") +
74
+ (MODO_REMOTO ? " Servidor remoto: no tiene acceso a los archivos del dispositivo del usuario." : ""),
75
+ };
71
76
 
72
77
  const texto = (t) => ({ content: [{ type: "text", text: t }] });
73
78
 
79
+ /**
80
+ * Herramientas registradas. Se guardan en una lista para poder crear un servidor MCP por sesión
81
+ * (modo remoto) o uno solo (modo local por stdio).
82
+ */
83
+ const HERRAMIENTAS = [];
84
+
85
+ /** Crea un servidor MCP con todas las herramientas y comandos rápidos. */
86
+ export function crearServidor() {
87
+ const s = new McpServer(INFO_SERVIDOR, OPCIONES_SERVIDOR);
88
+ for (const h of HERRAMIENTAS) s.registerTool(h.nombre, { description: h.descripcion, inputSchema: h.esquema }, h.manejar);
89
+ registrarPrompts(s);
90
+ return s;
91
+ }
92
+
74
93
  /** Registra una herramienta y convierte cualquier error en un mensaje legible. */
75
94
  function herramienta(nombre, descripcion, esquema, fn) {
76
- server.registerTool(nombre, { description: descripcion, inputSchema: esquema }, async (args) => {
95
+ HERRAMIENTAS.push({ nombre, descripcion, esquema, manejar: async (args) => {
77
96
  // Modo anónimo: los alias se cargan ANTES de ejecutar; si falla, no se devuelve nada (falla cerrado).
78
97
  if (anonimo.activo) {
79
98
  try {
@@ -93,7 +112,7 @@ function herramienta(nombre, descripcion, esquema, fn) {
93
112
  // Última barrera: ningún texto sale con el token dentro (ni con nombres de compañeros en modo anónimo).
94
113
  for (const c of salida.content ?? []) if (c.type === "text") c.text = anonimo.aplicar(limpiar(c.text));
95
114
  return salida;
96
- });
115
+ } });
97
116
  }
98
117
 
99
118
  /** Busca un curso por id o por parte del nombre. */
@@ -386,8 +405,19 @@ herramienta(
386
405
  async ({ url }) => {
387
406
  const m = moodle();
388
407
  if (new URL(url).origin !== new URL(m.url).origin) throw new MoodleError("La URL no pertenece al sitio Moodle configurado.");
389
- const { ruta, tipo, datos } = await m.descargar(url);
390
- const cab = `Archivo guardado en: ${ruta}\nTipo: ${tipo}\n`;
408
+ let ruta, tipo, datos, cab;
409
+ if (MODO_REMOTO) {
410
+ // En remoto no se guarda en el disco del servidor: se lee en memoria y se ofrece un enlace temporal.
411
+ datos = await m.bajar(url);
412
+ ruta = decodeURIComponent(new URL(url).pathname.split("/").pop() || "archivo");
413
+ tipo = /\.pdf$/i.test(ruta) ? "application/pdf" : "application/octet-stream";
414
+ const nombre = ruta;
415
+ const l = enlaces.descarga(async () => ({ nombre, tipo, datos }), { nombre });
416
+ cab = `Archivo: ${nombre}\n⬇ Descargar el original: ${l.url} (un solo uso, 15 min)\n`;
417
+ } else {
418
+ ({ ruta, tipo, datos } = await m.descargar(url));
419
+ cab = `Archivo guardado en: ${ruta}\nTipo: ${tipo}\n`;
420
+ }
391
421
  if (tipo.includes("pdf") || ruta.toLowerCase().endsWith(".pdf")) {
392
422
  const pdf = await getDocumentProxy(new Uint8Array(datos));
393
423
  const { totalPages, text } = await extractText(pdf, { mergePages: true });
@@ -578,12 +608,23 @@ herramienta(
578
608
  );
579
609
 
580
610
  // Fase 2: estudiar (solo lectura).
581
- registrarEstudio({ herramienta, moodle, resolverCurso });
611
+ registrarEstudio({ herramienta, moodle, resolverCurso, remoto: MODO_REMOTO });
582
612
  // Fase 3: organización (solo lectura).
583
- registrarOrganizacion({ herramienta, moodle, resolverCurso });
613
+ registrarOrganizacion({ herramienta, moodle, resolverCurso, remoto: MODO_REMOTO });
614
+
615
+ herramienta(
616
+ "archivos_privados",
617
+ "Lista tus archivos privados de Moodle (\"Mis archivos privados\"). Puedes subir ahí un archivo desde la app oficial de Moodle y luego entregarlo con preparar_entrega (privados).",
618
+ {},
619
+ async () => {
620
+ const fs = await moodle().archivosPrivados();
621
+ if (!fs.length) return "No tienes archivos privados. Puedes subirlos desde la app de Moodle (menú → Archivos) o desde la web (Mis archivos privados).";
622
+ return ["# Mis archivos privados", ...fs.map((f) => `- ${f.ruta} (${Math.ceil((f.filesize ?? 0) / 1024)} KB · ${fecha(f.timemodified)})`), "", "Para entregar uno: preparar_entrega con privados=[\"nombre\"]."].join("\n");
623
+ },
624
+ );
584
625
 
585
626
  // Herramientas que modifican Moodle: solo si el usuario las activa explícitamente.
586
- const confirmaciones = MODO_ESCRITURA ? registrarEscritura({ herramienta, moodle, resolverTarea, resolverCurso, resolverAlias: (t) => anonimo.resolver(t) }) : null;
627
+ const confirmaciones = MODO_ESCRITURA ? registrarEscritura({ herramienta, moodle, resolverTarea, resolverCurso, resolverAlias: (t) => anonimo.resolver(t), remoto: MODO_REMOTO }) : null;
587
628
 
588
629
  // Asistencia: lectura siempre; marcar solo con modo escritura (usa los mismos códigos de confirmación).
589
630
  registrarAsistencia({ herramienta, moodle, resolverCurso, confirmaciones, escritura: MODO_ESCRITURA });
@@ -611,7 +652,14 @@ if (sitios.lista.length > 1) {
611
652
  );
612
653
  }
613
654
 
614
- // Comandos rápidos (prompts MCP).
615
- registrarPrompts(server);
616
-
617
- await server.connect(new StdioServerTransport());
655
+ if (MODO_REMOTO) {
656
+ // Servidor HTTP para claude.ai (web y móvil): un servidor MCP por sesión.
657
+ const { iniciarRemoto, generarClave } = await import("./remoto.js");
658
+ if (process.argv.includes("--nueva-clave")) {
659
+ console.log(`MOODLE_REMOTO_CLAVE=${generarClave()}`);
660
+ process.exit(0);
661
+ }
662
+ await iniciarRemoto(crearServidor, { escritura: MODO_ESCRITURA });
663
+ } else {
664
+ await crearServidor().connect(new StdioServerTransport());
665
+ }
package/src/moodle.js CHANGED
@@ -204,6 +204,21 @@ export class Moodle {
204
204
  });
205
205
  }
206
206
 
207
+ /** Archivos privados del usuario ("Mis archivos privados" en Moodle), recorriendo carpetas. */
208
+ async archivosPrivados(ruta = "/", profundidad = 0) {
209
+ const { userid } = await this.sitio();
210
+ const r = await this.llamar("core_files_get_files", {
211
+ contextid: -1, component: "user", filearea: "private", itemid: 0, filepath: ruta, filename: "", contextlevel: "user", instanceid: userid,
212
+ });
213
+ const salida = [];
214
+ for (const f of r.files ?? []) {
215
+ if (f.isdir) {
216
+ if (profundidad < 3 && f.filepath !== ruta) salida.push(...(await this.archivosPrivados(f.filepath, profundidad + 1)));
217
+ } else salida.push({ ...f, fileurl: f.url, ruta: `${f.filepath}${f.filename}` });
218
+ }
219
+ return salida;
220
+ }
221
+
207
222
  /** Secciones y módulos de un curso (con caché). */
208
223
  async contenidosCurso(courseid) {
209
224
  return this.llamarCache("core_course_get_contents", { courseid });
@@ -8,6 +8,7 @@ import { z } from "zod";
8
8
  import { MoodleError, faltan, fecha, hace, htmlATexto, normalizar } from "./moodle.js";
9
9
  import { analizarTarea } from "./escritura.js";
10
10
  import { nombreEvento } from "./resumen.js";
11
+ import { enlaces } from "./enlaces.js";
11
12
 
12
13
  /** "(SOF) FISICA - A" → "FISICA" */
13
14
  export const nombreMateria = (c) => (c?.fullname ?? "").replace(/^\([^)]*\)\s*/, "").replace(/\s+-\s+[A-Z0-9]{1,3}$/, "").trim() || c?.shortname || "";
@@ -100,7 +101,7 @@ export function generarIcs(eventos, { host = "moodle", cursos = new Map(), ahora
100
101
 
101
102
  // ------------------------------------------------------------------ registro
102
103
 
103
- export function registrarOrganizacion({ herramienta, moodle, resolverCurso }) {
104
+ export function registrarOrganizacion({ herramienta, moodle, resolverCurso, remoto = false }) {
104
105
  herramienta(
105
106
  "calendario",
106
107
  "Calendario completo: entregas, apertura y cierre de cuestionarios, clases con asistencia y eventos del curso o de la institución, día por día. Puede exportarlo a .ics o darte el enlace de suscripción oficial de Moodle para Google Calendar/Outlook.",
@@ -139,7 +140,13 @@ export function registrarOrganizacion({ herramienta, moodle, resolverCurso }) {
139
140
  partes.push(`- ${hora}${dur} · ${tipoTxt} · ${nombreEvento(e)}${porId.get(e.courseid) ? ` — ${nombreMateria(porId.get(e.courseid))}` : ""}${e.location ? ` · 📍 ${e.location}` : ""}`);
140
141
  }
141
142
 
142
- if (exportar_ics && eventos.length) {
143
+ if (exportar_ics && remoto && eventos.length) {
144
+ const nombre = `calendario-moodle${c ? `-${c.id}` : ""}.ics`;
145
+ const ics = generarIcs(eventos, { host: new URL(m.url).host, cursos: porId });
146
+ const l = enlaces.descarga(async () => ({ nombre, tipo: "text/calendar; charset=utf-8", datos: Buffer.from(ics) }), { nombre });
147
+ partes.push("", `📅 [Descargar ${nombre}](${l.url}) · enlace de un solo uso, válido 15 min. Ábrelo en el celular para añadirlo a tu calendario (es una copia: no se actualiza sola; para eso usa suscripcion=true).`);
148
+ }
149
+ if (exportar_ics && !remoto && eventos.length) {
143
150
  const base = resolve(process.env.MOODLE_DESCARGAS || join(homedir(), "Downloads", "moodle-student-bridge"));
144
151
  await mkdir(base, { recursive: true });
145
152
  const ruta = join(base, `calendario-moodle${c ? `-${c.id}` : ""}.ics`);
package/src/remoto.js ADDED
@@ -0,0 +1,275 @@
1
+ // Modo remoto: servidor MCP por HTTP (Streamable HTTP) para usarlo desde claude.ai (web y móvil)
2
+ // como "conector personalizado". Pensado para UN estudiante: su token vive solo en este servidor.
3
+ //
4
+ // Seguridad:
5
+ // - La URL lleva una clave secreta larga: https://tu-servidor/mcp/<MOODLE_REMOTO_CLAVE>
6
+ // (los conectores de claude.ai no permiten cabeceras propias). Se compara en tiempo constante.
7
+ // Cualquier otra ruta responde 404, igual que una clave incorrecta, sin dar pistas.
8
+ // - Límite de peticiones por IP y de tamaño del cuerpo. Sesiones con caducidad por inactividad.
9
+ // - Por defecto escucha solo en 127.0.0.1 (para usar con un túnel); en contenedores, HOST=0.0.0.0.
10
+ // - Protección contra DNS rebinding si se define MOODLE_REMOTO_HOSTS.
11
+ // - Nunca se registra la ruta (contiene la clave) ni el contenido de las peticiones.
12
+
13
+ import { createServer } from "node:http";
14
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
15
+ import { extname } from "node:path";
16
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
17
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
18
+ import { MAX_MEMORIA_SUBIDAS, disposicion, enlaces } from "./enlaces.js";
19
+ import { nombreSeguro } from "./estudio.js";
20
+
21
+ const escHtml = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
22
+ const mb = (b) => `${(b / 1048576).toFixed(1)} MB`;
23
+
24
+ /** Página mínima, sin JavaScript ni recursos externos (CSP estricta). */
25
+ function pagina(titulo, cuerpo) {
26
+ return `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
27
+ <title>${escHtml(titulo)}</title><style>
28
+ body{font-family:system-ui,sans-serif;max-width:32rem;margin:2rem auto;padding:0 1rem;color:#1a1a1a;background:#fafafa}
29
+ h1{font-size:1.3rem}.caja{background:#fff;border:1px solid #ddd;border-radius:12px;padding:1rem 1.2rem}
30
+ .ok{color:#0a7a2f}.mal{color:#b00020}small{color:#555}button{font-size:1rem;padding:.7rem 1.2rem;border-radius:8px;border:0;background:#1f4fd6;color:#fff;margin-top:1rem}
31
+ input[type=file]{margin-top:.8rem;max-width:100%}li{margin:.2rem 0}
32
+ @media (prefers-color-scheme:dark){body{background:#111;color:#eee}.caja{background:#1c1c1c;border-color:#333}small{color:#aaa}}
33
+ </style></head><body><h1>${escHtml(titulo)}</h1><div class="caja">${cuerpo}</div><p><small>moodle-student-bridge · enlace temporal</small></p></body></html>`;
34
+ }
35
+
36
+ function enviarHtml(res, status, html) {
37
+ if (res.headersSent) return;
38
+ res.writeHead(status, {
39
+ "Content-Type": "text/html; charset=utf-8",
40
+ "Cache-Control": "no-store",
41
+ "X-Content-Type-Options": "nosniff",
42
+ "Referrer-Policy": "no-referrer",
43
+ "X-Frame-Options": "DENY",
44
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
45
+ });
46
+ res.end(html);
47
+ }
48
+
49
+ /** GET /d/<id>: entrega el archivo (lo pide a Moodle en el momento; el token no sale del servidor). */
50
+ async function servirDescarga(id, res, log) {
51
+ const e = enlaces.tomarDescarga(id);
52
+ if (!e) return enviarHtml(res, 404, pagina("Enlace no disponible", '<p class="mal">Este enlace caducó o ya se usó.</p><p>Pídele a Claude uno nuevo.</p>'));
53
+ try {
54
+ const { nombre, tipo, datos } = await e.generar();
55
+ res.writeHead(200, {
56
+ "Content-Type": tipo || "application/octet-stream",
57
+ "Content-Length": datos.length,
58
+ "Content-Disposition": disposicion(nombre),
59
+ "Cache-Control": "no-store",
60
+ "X-Content-Type-Options": "nosniff",
61
+ "Referrer-Policy": "no-referrer",
62
+ });
63
+ res.end(datos);
64
+ } catch (err) {
65
+ log(`[remoto] descarga falló: ${err.message}`);
66
+ enviarHtml(res, 502, pagina("No se pudo descargar", `<p class="mal">${escHtml(err.message)}</p>`));
67
+ }
68
+ }
69
+
70
+ function formularioSubida(id, e, aviso = "") {
71
+ const r = e.reglas;
72
+ const tipos = r.extensiones ? r.extensiones.join(", ") : "cualquiera";
73
+ return pagina(
74
+ `Subir archivo · ${r.tarea}`,
75
+ `${aviso}<p><b>${escHtml(r.tarea)}</b><br><small>${escHtml(r.curso)}</small></p>
76
+ <ul><li>Tipos permitidos: <b>${escHtml(tipos)}</b></li><li>Tamaño máximo: <b>${mb(r.maxBytes)}</b> por archivo</li><li>Archivos: hasta <b>${r.maxArchivos}</b></li></ul>
77
+ <form method="post" enctype="multipart/form-data" action="/subir/${escHtml(id)}">
78
+ <input type="file" name="archivo" required ${r.maxArchivos > 1 ? "multiple" : ""} ${r.extensiones ? `accept="${escHtml(r.extensiones.join(","))}"` : ""}>
79
+ <br><button type="submit">Subir</button></form>
80
+ <p><small>Subir NO entrega la tarea: después vuelve al chat; Claude te mostrará la vista previa y pedirá tu confirmación.</small></p>`,
81
+ );
82
+ }
83
+
84
+ /** GET/POST /subir/<id>: página de subida desde el celular, con las reglas de la tarea. */
85
+ async function servirSubida(id, req, res) {
86
+ const e = enlaces.verSubida(id);
87
+ if (!e) return enviarHtml(res, 404, pagina("Enlace no disponible", '<p class="mal">Este enlace de subida caducó o no existe.</p><p>Pídele a Claude uno nuevo.</p>'));
88
+ if (e.cerrada)
89
+ return enviarHtml(res, 200, pagina("Archivo recibido", `<p class="ok">✔ Ya recibimos: ${e.archivos.map((f) => escHtml(f.nombre)).join(", ")}</p><p>Vuelve al chat y dile a Claude que ya lo subiste.</p>`));
90
+ if (req.method === "GET") return enviarHtml(res, 200, formularioSubida(id, e));
91
+ if (req.method !== "POST") return enviarHtml(res, 405, pagina("Método no permitido", ""));
92
+
93
+ const r = e.reglas;
94
+ const limite = r.maxBytes * r.maxArchivos + 1048576;
95
+ const largo = Number(req.headers["content-length"] ?? NaN);
96
+ if (!Number.isFinite(largo) || largo > limite) return enviarHtml(res, 413, formularioSubida(id, e, `<p class="mal">El archivo supera el máximo permitido (${mb(r.maxBytes)}).</p>`));
97
+ if (enlaces.memoriaSubidas() + largo > MAX_MEMORIA_SUBIDAS) return enviarHtml(res, 503, formularioSubida(id, e, '<p class="mal">El servidor está ocupado con otras subidas. Inténtalo en unos minutos.</p>'));
98
+
99
+ let form;
100
+ try {
101
+ form = await new Request("http://local/subir", { method: "POST", headers: { "content-type": req.headers["content-type"] ?? "" }, body: req, duplex: "half" }).formData();
102
+ } catch {
103
+ return enviarHtml(res, 400, formularioSubida(id, e, '<p class="mal">No se pudo leer el archivo. Inténtalo de nuevo.</p>'));
104
+ }
105
+ const archivos = form.getAll("archivo").filter((f) => typeof f === "object" && f.size > 0);
106
+ const problemas = [];
107
+ if (!archivos.length) problemas.push("No elegiste ningún archivo (o está vacío).");
108
+ if (archivos.length > r.maxArchivos) problemas.push(`Solo se permite${r.maxArchivos > 1 ? `n ${r.maxArchivos} archivos` : " 1 archivo"}.`);
109
+ const recibidos = [];
110
+ for (const f of archivos) {
111
+ const nombre = nombreSeguro(f.name || "archivo");
112
+ const ext = extname(nombre).toLowerCase();
113
+ if (f.size > r.maxBytes) problemas.push(`${nombre}: pesa ${mb(f.size)} y el máximo es ${mb(r.maxBytes)}.`);
114
+ if (r.extensiones && !r.extensiones.includes(ext)) problemas.push(`${nombre}: el tipo ${ext || "(sin extensión)"} no está permitido.`);
115
+ recibidos.push({ nombre, tamano: f.size, datos: Buffer.from(await f.arrayBuffer()) });
116
+ }
117
+ if (problemas.length) return enviarHtml(res, 400, formularioSubida(id, e, `<p class="mal">${problemas.map(escHtml).join("<br>")}</p>`));
118
+ e.archivos = recibidos;
119
+ e.cerrada = true;
120
+ e.recibido = Date.now();
121
+ return enviarHtml(
122
+ res,
123
+ 200,
124
+ pagina("Archivo recibido", `<p class="ok">✔ Recibido: ${recibidos.map((f) => `${escHtml(f.nombre)} (${mb(f.tamano)})`).join(", ")}</p><p>Vuelve al chat y dile a Claude que ya lo subiste. <b>Todavía no se entregó.</b></p>`),
125
+ );
126
+ }
127
+
128
+ const MAX_CUERPO = 1024 * 1024; // 1 MB
129
+ const INACTIVIDAD_MS = 30 * 60_000;
130
+
131
+ export function claveValida(clave) {
132
+ return typeof clave === "string" && clave.length >= 32 && /^[A-Za-z0-9_-]+$/.test(clave);
133
+ }
134
+
135
+ export function generarClave() {
136
+ return randomBytes(32).toString("base64url");
137
+ }
138
+
139
+ /** Compara en tiempo constante (no revela cuántos caracteres coinciden). */
140
+ export function mismaClave(a, b) {
141
+ const x = Buffer.from(String(a));
142
+ const y = Buffer.from(String(b));
143
+ return x.length === y.length && timingSafeEqual(x, y);
144
+ }
145
+
146
+ /** Límite simple de peticiones por IP (ventana deslizante de 1 minuto). */
147
+ export function crearLimitador(maxPorMinuto = 120, ahora = () => Date.now()) {
148
+ const marcas = new Map();
149
+ return (ip) => {
150
+ const t = ahora();
151
+ const lista = (marcas.get(ip) ?? []).filter((x) => t - x < 60_000);
152
+ lista.push(t);
153
+ marcas.set(ip, lista);
154
+ if (marcas.size > 10_000) marcas.clear();
155
+ return lista.length <= maxPorMinuto;
156
+ };
157
+ }
158
+
159
+ function leerCuerpo(req) {
160
+ return new Promise((ok, mal) => {
161
+ let tam = 0;
162
+ const partes = [];
163
+ req.on("data", (c) => {
164
+ tam += c.length;
165
+ if (tam > MAX_CUERPO) {
166
+ mal(Object.assign(new Error("cuerpo demasiado grande"), { status: 413 }));
167
+ req.destroy();
168
+ } else partes.push(c);
169
+ });
170
+ req.on("end", () => {
171
+ if (!partes.length) return ok(undefined);
172
+ try {
173
+ ok(JSON.parse(Buffer.concat(partes).toString("utf8")));
174
+ } catch {
175
+ mal(Object.assign(new Error("JSON inválido"), { status: 400 }));
176
+ }
177
+ });
178
+ req.on("error", mal);
179
+ });
180
+ }
181
+
182
+ const responder = (res, status, cuerpo, tipo = "text/plain; charset=utf-8") => {
183
+ if (res.headersSent) return;
184
+ res.writeHead(status, { "Content-Type": tipo, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer" });
185
+ res.end(cuerpo);
186
+ };
187
+
188
+ /**
189
+ * Arranca el servidor HTTP.
190
+ * @param crearServidor () => McpServer (uno nuevo por sesión)
191
+ */
192
+ export async function iniciarRemoto(crearServidor, { escritura = false, puerto, host, clave, silencioso = false } = {}) {
193
+ puerto = Number(puerto ?? process.env.PORT ?? process.env.MOODLE_REMOTO_PUERTO ?? 3000);
194
+ host = host ?? process.env.HOST ?? process.env.MOODLE_REMOTO_HOST ?? "127.0.0.1";
195
+ clave = clave ?? process.env.MOODLE_REMOTO_CLAVE;
196
+ const log = (...a) => !silencioso && console.error(...a);
197
+
198
+ let temporal = false;
199
+ if (!claveValida(clave)) {
200
+ if (clave) throw new Error("MOODLE_REMOTO_CLAVE debe tener al menos 32 caracteres (letras, números, - o _). Genera una con: npm run remoto -- --nueva-clave");
201
+ clave = generarClave();
202
+ temporal = true;
203
+ }
204
+
205
+ const hostsPermitidos = (process.env.MOODLE_REMOTO_HOSTS ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(Boolean);
206
+ const permitido = crearLimitador(Number(process.env.MOODLE_REMOTO_LIMITE ?? 120));
207
+ const sesiones = new Map(); // id → { transporte, ultimo }
208
+ const ruta = `/mcp/${clave}`;
209
+
210
+ const limpieza = setInterval(() => {
211
+ const t = Date.now();
212
+ for (const [id, s] of sesiones) if (t - s.ultimo > INACTIVIDAD_MS) s.transporte.close().catch(() => {});
213
+ }, 60_000);
214
+ limpieza.unref();
215
+
216
+ const servidor = createServer(async (req, res) => {
217
+ const ip = req.socket.remoteAddress ?? "?";
218
+ try {
219
+ const url = new URL(req.url ?? "/", "http://x");
220
+ if (url.pathname === "/salud") return responder(res, 200, "ok");
221
+ if (!permitido(ip)) return responder(res, 429, "Demasiadas peticiones");
222
+ // Enlaces temporales: el identificador aleatorio del enlace es su propia credencial.
223
+ const enlace = url.pathname.match(/^\/(d|subir)\/([A-Za-z0-9_-]{24})$/);
224
+ if (enlace) return enlace[1] === "d" ? await servirDescarga(enlace[2], res, log) : await servirSubida(enlace[2], req, res);
225
+ if (!mismaClave(url.pathname, ruta)) return responder(res, 404, "No encontrado");
226
+ if (hostsPermitidos.length && !hostsPermitidos.includes(String(req.headers.host ?? "").toLowerCase().replace(/:\d+$/, "")))
227
+ return responder(res, 403, "Host no permitido");
228
+
229
+ const idSesion = req.headers["mcp-session-id"];
230
+ const cuerpo = req.method === "POST" ? await leerCuerpo(req) : undefined;
231
+ let sesion = idSesion ? sesiones.get(String(idSesion)) : undefined;
232
+
233
+ if (!sesion) {
234
+ if (req.method !== "POST" || !isInitializeRequest(cuerpo)) {
235
+ return responder(res, idSesion ? 404 : 400, JSON.stringify({ jsonrpc: "2.0", error: { code: -32000, message: idSesion ? "Sesión no encontrada o caducada" : "Falta la inicialización" }, id: null }), "application/json");
236
+ }
237
+ const transporte = new StreamableHTTPServerTransport({
238
+ sessionIdGenerator: () => randomUUID(),
239
+ onsessioninitialized: (id) => sesiones.set(id, { transporte, ultimo: Date.now() }),
240
+ });
241
+ transporte.onclose = () => transporte.sessionId && sesiones.delete(transporte.sessionId);
242
+ await crearServidor().connect(transporte);
243
+ return await transporte.handleRequest(req, res, cuerpo);
244
+ }
245
+ sesion.ultimo = Date.now();
246
+ await sesion.transporte.handleRequest(req, res, cuerpo);
247
+ } catch (e) {
248
+ log(`[remoto] error ${e.status ?? 500}: ${e.message}`);
249
+ responder(res, e.status ?? 500, e.status ? e.message : "Error interno");
250
+ }
251
+ });
252
+
253
+ await new Promise((ok, mal) => {
254
+ servidor.once("error", mal);
255
+ servidor.listen(puerto, host, ok);
256
+ });
257
+ const real = servidor.address();
258
+ log(
259
+ [
260
+ "",
261
+ `moodle-student-bridge · modo remoto escuchando en http://${host}:${real.port}`,
262
+ `Modo: ${escritura ? "lectura + ESCRITURA (con confirmación)" : "solo lectura"}`,
263
+ "",
264
+ "URL del conector (agrega delante tu dominio https, p. ej. el del túnel):",
265
+ // La clave solo se imprime si es temporal: en Docker o en la nube los registros pueden guardarse.
266
+ temporal ? ` https://<tu-dominio>${ruta}` : " https://<tu-dominio>/mcp/<tu MOODLE_REMOTO_CLAVE>",
267
+ "",
268
+ temporal
269
+ ? "⚠ Esta clave es TEMPORAL: cambia en cada arranque. Guarda una fija en MOODLE_REMOTO_CLAVE (npm run remoto -- --nueva-clave)."
270
+ : "La URL contiene tu clave secreta: trátala como una contraseña.",
271
+ "",
272
+ ].join("\n"),
273
+ );
274
+ return { servidor, puerto: real.port, ruta, cerrar: () => new Promise((ok) => { clearInterval(limpieza); for (const s of sesiones.values()) s.transporte.close().catch(() => {}); servidor.close(() => ok()); }) };
275
+ }
package/src/seguridad.js CHANGED
@@ -87,6 +87,9 @@ function motivoContenidoMovil(params = {}, escritura) {
87
87
  /** Devuelve null si se permite, o el motivo del rechazo. */
88
88
  export function motivoFuncionNoPermitida(funcion, { escritura = false, params } = {}) {
89
89
  if (funcion === "tool_mobile_get_content") return motivoContenidoMovil(params, escritura);
90
+ // Solo lectura de "Mis archivos privados" (no de otras áreas de archivos).
91
+ if (funcion === "core_files_get_files")
92
+ return params?.component === "user" && params?.filearea === "private" ? null : "core_files_get_files solo está permitido para tus archivos privados.";
90
93
  if (FUNCIONES_LECTURA.has(funcion)) return null;
91
94
  if (FUNCIONES_ESCRITURA.has(funcion)) return escritura ? null : `"${funcion}" modifica Moodle y el modo escritura está desactivado.`;
92
95
  return `"${funcion}" no está en la lista de funciones permitidas de moodle-student-bridge.`;