moodle-student-bridge 1.7.0 → 1.8.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 +22 -0
- package/README.es.md +30 -0
- package/README.md +17 -0
- package/docs/REMOTO.md +16 -2
- package/docs/ROADMAP.md +1 -1
- package/manifest.json +1 -1
- package/package.json +1 -1
- package/src/enlaces.js +15 -1
- package/src/escritura.js +4 -0
- package/src/index.js +23 -4
- package/src/moodle.js +3 -2
- package/src/remoto.js +10 -4
- package/src/restringido.js +294 -0
- package/src/seguridad.js +13 -1
- package/src/sitios.js +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.8.0 — 2026-11-20
|
|
4
|
+
|
|
5
|
+
Modo restringido (beta). / Restricted mode (beta).
|
|
6
|
+
|
|
7
|
+
- Cuestionarios desde Claude **solo para pruebas y demostración**: `restringido_ver_cuestionario`,
|
|
8
|
+
`restringido_preparar_intento`, `restringido_ver_preguntas`, `restringido_marcar` y
|
|
9
|
+
`restringido_preparar_envio` (+ `confirmar`).
|
|
10
|
+
- Desactivado por defecto. Triple llave (`MOODLE_MODO_RESTRINGIDO=1`, `MOODLE_ESCRITURA=1`,
|
|
11
|
+
`MOODLE_ACEPTO_RESPONSABILIDAD=si`), solo en modo local, aviso de responsabilidad al arrancar, en
|
|
12
|
+
`estado_conexion` y en cada salida.
|
|
13
|
+
- La IA solo marca la respuesta que indica el estudiante; las instrucciones del servidor le prohíben
|
|
14
|
+
sugerir o explicar respuestas durante un intento.
|
|
15
|
+
- Bloquea Safe Exam Browser / ventana segura; la contraseña solo la que dio el profesor; respeta las
|
|
16
|
+
razones de Moodle para impedir el acceso. Iniciar y enviar piden confirmación.
|
|
17
|
+
- Lista de funciones separada (`FUNCIONES_RESTRINGIDO`): sin el modo, ninguna llega a la red.
|
|
18
|
+
|
|
19
|
+
## 1.7.1 — 2026-11-20
|
|
20
|
+
|
|
21
|
+
- Despliegue en Render con un clic (`render.yaml` + botón en el README).
|
|
22
|
+
- La URL pública se detecta sola en Render, Railway y Fly.io (`MOODLE_REMOTO_URL_PUBLICA` sigue
|
|
23
|
+
teniendo prioridad), y se usa por defecto como host permitido contra DNS rebinding.
|
|
24
|
+
|
|
3
25
|
## 1.7.0 — 2026-11-20
|
|
4
26
|
|
|
5
27
|
Archivos en modo remoto. / Files in remote mode.
|
package/README.es.md
CHANGED
|
@@ -141,6 +141,8 @@ npx moodle-student-bridge --http --nueva-clave # genera MOODLE_REMOTO_CLAVE
|
|
|
141
141
|
npm run remoto # + un túnel, o despliega el Dockerfile
|
|
142
142
|
```
|
|
143
143
|
|
|
144
|
+
[](https://render.com/deploy?repo=https://github.com/MattSeb15/moodle-student-bridge)
|
|
145
|
+
|
|
144
146
|
URL del conector: `https://tu-dominio/mcp/<MOODLE_REMOTO_CLAVE>`. Tu token de Moodle se queda en tu
|
|
145
147
|
servidor. Los archivos funcionan con **enlaces temporales en el chat**: descargas (sueltas o en ZIP) y
|
|
146
148
|
una página para subir entregas desde el celular. Por defecto solo lectura; en remoto la escritura
|
|
@@ -189,6 +191,33 @@ para **modificar** tu Moodle:
|
|
|
189
191
|
El historial se guarda en `~/.moodle-student-bridge/historial.jsonl` (configurable con
|
|
190
192
|
`MOODLE_HISTORIAL`) y nunca incluye el token.
|
|
191
193
|
|
|
194
|
+
## ⚠ Modo restringido: cuestionarios (pruebas y demostración)
|
|
195
|
+
|
|
196
|
+
> **Aviso:** usar herramientas de IA en evaluaciones puede violar el reglamento de tu institución y tener
|
|
197
|
+
> consecuencias académicas graves. Este modo existe **solo para pruebas y para demostrar** lo que el MCP es
|
|
198
|
+
> capaz de hacer. **Su uso es responsabilidad total y exclusiva del estudiante**; los autores no se hacen
|
|
199
|
+
> responsables.
|
|
200
|
+
|
|
201
|
+
Permite abrir un cuestionario, ver sus preguntas, **marcar la respuesta que tú digas** y enviarlo. Está
|
|
202
|
+
**desactivado por defecto** y tiene varias barreras:
|
|
203
|
+
|
|
204
|
+
- **Triple llave:** `MOODLE_MODO_RESTRINGIDO=1` + `MOODLE_ESCRITURA=1` + `MOODLE_ACEPTO_RESPONSABILIDAD=si`.
|
|
205
|
+
No se puede activar desde el formulario de Claude Desktop.
|
|
206
|
+
- **Solo en modo local**, nunca en el servidor remoto.
|
|
207
|
+
- **La IA no resuelve:** las instrucciones del servidor y cada respuesta le prohíben sugerir, elegir, razonar
|
|
208
|
+
o explicar respuestas durante un intento. Solo marca lo que indiques literalmente.
|
|
209
|
+
- **No se esquiva nada:** si el cuestionario exige Safe Exam Browser o ventana segura, se bloquea; la
|
|
210
|
+
contraseña solo puede ser la que dio el profesor; si Moodle impide el acceso, se respeta.
|
|
211
|
+
- **Iniciar** (consume un intento y arranca el reloj) y **enviar** (definitivo) piden código de confirmación.
|
|
212
|
+
- El aviso aparece al arrancar, en `estado_conexion` y en cada respuesta de estas herramientas. Todo queda
|
|
213
|
+
en el historial.
|
|
214
|
+
|
|
215
|
+
Herramientas: `restringido_ver_cuestionario`, `restringido_preparar_intento`, `restringido_ver_preguntas`,
|
|
216
|
+
`restringido_marcar` y `restringido_preparar_envio` (+ `confirmar`). Tipos de pregunta: opción múltiple
|
|
217
|
+
(una o varias), verdadero/falso, respuesta corta o numérica, emparejamiento y ensayo. Estado: **beta**.
|
|
218
|
+
|
|
219
|
+
Para **estudiar** no hace falta este modo: `revisar_intento` revisa intentos ya terminados.
|
|
220
|
+
|
|
192
221
|
## 3. Recordatorios en el celular (opcional)
|
|
193
222
|
|
|
194
223
|
Usa [ntfy](https://ntfy.sh): gratis y sin cuenta.
|
|
@@ -230,6 +259,7 @@ usa tu propio servidor con `NTFY_SERVER` y `NTFY_TOKEN`.
|
|
|
230
259
|
| `RECORDAR_HORAS`, `INTERVALO_MIN` | Cuándo avisar (por defecto `24,3` y `60`) |
|
|
231
260
|
| `MOODLE_ESCRITURA` | `1` para activar el modo escritura (por defecto desactivado) |
|
|
232
261
|
| `MOODLE_ANONIMO` | `1` para mostrar a los compañeros como alias |
|
|
262
|
+
| `MOODLE_MODO_RESTRINGIDO`, `MOODLE_ACEPTO_RESPONSABILIDAD` | Modo restringido de cuestionarios (`1` y `si`, además de `MOODLE_ESCRITURA=1`); solo local |
|
|
233
263
|
| `MOODLE_URL_<X>`, `MOODLE_TOKEN_<X>`, `MOODLE_NOMBRE_<X>`, `MOODLE_SITIO` | Moodle adicionales y el activo al arrancar |
|
|
234
264
|
| `RECORDAR_ASISTENCIA` | `0` para desactivar el aviso de clases |
|
|
235
265
|
| `MOODLE_HISTORIAL` | Archivo del historial de acciones de escritura |
|
package/README.md
CHANGED
|
@@ -154,6 +154,8 @@ npx moodle-student-bridge --http --nueva-clave # generate MOODLE_REMOTO_CLAVE
|
|
|
154
154
|
npm run remoto # + a tunnel, or deploy the Dockerfile
|
|
155
155
|
```
|
|
156
156
|
|
|
157
|
+
[](https://render.com/deploy?repo=https://github.com/MattSeb15/moodle-student-bridge)
|
|
158
|
+
|
|
157
159
|
Connector URL: `https://your-domain/mcp/<MOODLE_REMOTO_CLAVE>`. Your Moodle token stays on your server.
|
|
158
160
|
Files work through **temporary links in the chat**: downloads (single files or a ZIP) and an upload
|
|
159
161
|
page for submissions from your phone. Read-only by default; in remote mode, write mode needs **both**
|
|
@@ -202,6 +204,20 @@ your Moodle:
|
|
|
202
204
|
The log is stored in `~/.moodle-student-bridge/historial.jsonl` (configurable with `MOODLE_HISTORIAL`)
|
|
203
205
|
and never contains the token.
|
|
204
206
|
|
|
207
|
+
## ⚠ Restricted mode: quizzes (testing and demo only)
|
|
208
|
+
|
|
209
|
+
> **Warning:** using AI tools during assessments may break your institution's rules and have serious academic
|
|
210
|
+
> consequences. This mode exists **only for testing and demonstrating** what the MCP can do. **Its use is the
|
|
211
|
+
> student's sole responsibility**; the authors accept no liability.
|
|
212
|
+
|
|
213
|
+
Lets you open a quiz, view its questions, **mark the answer you say** and submit it. **Off by default**, with
|
|
214
|
+
several barriers: three keys (`MOODLE_MODO_RESTRINGIDO=1`, `MOODLE_ESCRITURA=1`,
|
|
215
|
+
`MOODLE_ACEPTO_RESPONSABILIDAD=si`), **local mode only**, the AI is instructed never to suggest or explain
|
|
216
|
+
answers during an attempt, Safe Exam Browser / secure window quizzes are blocked, only the teacher-given
|
|
217
|
+
password can be used, and starting or submitting an attempt needs a confirmation code. Status: **beta**.
|
|
218
|
+
|
|
219
|
+
To **study**, use `revisar_intento` on finished attempts instead.
|
|
220
|
+
|
|
205
221
|
## 3. Phone reminders (optional)
|
|
206
222
|
|
|
207
223
|
Uses [ntfy](https://ntfy.sh): free, no account needed.
|
|
@@ -240,6 +256,7 @@ own server with `NTFY_SERVER` and `NTFY_TOKEN`.
|
|
|
240
256
|
| `MOODLE_DESCARGAS` | Download folder (default `~/Downloads/moodle-student-bridge`) |
|
|
241
257
|
| `MOODLE_ESCRITURA` | `1` to enable write mode (off by default) |
|
|
242
258
|
| `MOODLE_ANONIMO` | `1` to show classmates as aliases |
|
|
259
|
+
| `MOODLE_MODO_RESTRINGIDO`, `MOODLE_ACEPTO_RESPONSABILIDAD` | Restricted quiz mode (`1` and `si`, plus `MOODLE_ESCRITURA=1`); local only |
|
|
243
260
|
| `MOODLE_URL_<X>`, `MOODLE_TOKEN_<X>`, `MOODLE_NOMBRE_<X>`, `MOODLE_SITIO` | Extra Moodle sites and the one active at start |
|
|
244
261
|
| `RECORDAR_ASISTENCIA` | `0` to turn off class reminders |
|
|
245
262
|
| `MOODLE_HISTORIAL` | Write-action log file |
|
package/docs/REMOTO.md
CHANGED
|
@@ -46,7 +46,21 @@ https://algo.trycloudflare.com/mcp/<MOODLE_REMOTO_CLAVE>
|
|
|
46
46
|
Los túneles rápidos cambian de URL en cada arranque y solo funcionan con la PC encendida. Para algo
|
|
47
47
|
fijo, usa un túnel con nombre de Cloudflare o la opción B.
|
|
48
48
|
|
|
49
|
-
### Opción B —
|
|
49
|
+
### Opción B — Render con un clic (recomendado)
|
|
50
|
+
|
|
51
|
+
[](https://render.com/deploy?repo=https://github.com/MattSeb15/moodle-student-bridge)
|
|
52
|
+
|
|
53
|
+
1. Crea una cuenta en [Render](https://render.com) (gratis) y pulsa el botón.
|
|
54
|
+
2. Render lee `render.yaml`, construye el `Dockerfile` y te pide los secretos: `MOODLE_URL`,
|
|
55
|
+
`MOODLE_TOKEN` y `MOODLE_REMOTO_CLAVE`. Pégalos desde tu `.env`.
|
|
56
|
+
3. Cuando termine, tu servidor queda en `https://<nombre>.onrender.com`. La URL pública se detecta sola
|
|
57
|
+
(no hace falta `MOODLE_REMOTO_URL_PUBLICA`) y solo se aceptan peticiones a ese dominio.
|
|
58
|
+
4. Tu conector: `https://<nombre>.onrender.com/mcp/<MOODLE_REMOTO_CLAVE>`.
|
|
59
|
+
|
|
60
|
+
> El plan gratuito de Render "duerme" el servicio tras ~15 minutos sin uso: la primera pregunta después
|
|
61
|
+
> puede tardar unos 30–60 s mientras despierta. Los enlaces y subidas pendientes se pierden al dormir.
|
|
62
|
+
|
|
63
|
+
### Opción C — Otra nube con Docker
|
|
50
64
|
|
|
51
65
|
El repo incluye un `Dockerfile`. En cualquier servicio que ejecute contenedores (Render, Railway,
|
|
52
66
|
Fly.io, un VPS…), configura estas variables **como secretos**:
|
|
@@ -135,7 +149,7 @@ app oficial de Moodle (Archivos privados) y pide *"entrega el archivo X de mis a
|
|
|
135
149
|
| Variable | Uso |
|
|
136
150
|
|---|---|
|
|
137
151
|
| `MOODLE_REMOTO_CLAVE` | Clave secreta de la URL (≥ 32 caracteres) |
|
|
138
|
-
| `MOODLE_REMOTO_URL_PUBLICA` | Dirección https de tu servidor, para
|
|
152
|
+
| `MOODLE_REMOTO_URL_PUBLICA` | Dirección https de tu servidor, para los enlaces de archivos (en Render, Railway y Fly se detecta sola) |
|
|
139
153
|
| `PORT` / `MOODLE_REMOTO_PUERTO` | Puerto (por defecto 3000) |
|
|
140
154
|
| `HOST` / `MOODLE_REMOTO_HOST` | Interfaz (por defecto `127.0.0.1`; en contenedores `0.0.0.0`) |
|
|
141
155
|
| `MOODLE_REMOTO_HOSTS` | Dominios permitidos en la cabecera Host (anti DNS rebinding) |
|
package/docs/ROADMAP.md
CHANGED
|
@@ -49,7 +49,7 @@ Las fases van en orden de prioridad.
|
|
|
49
49
|
- ✅ Modo remoto (HTTP) para usarlo desde claude.ai o el celular (v1.6) — ver [REMOTO.md](REMOTO.md).
|
|
50
50
|
- ⏸ Exportar apuntes del curso a un vault de Obsidian (pospuesto).
|
|
51
51
|
|
|
52
|
-
## Fase 6 — Modo restringido: cuestionarios (pruebas y demostración)
|
|
52
|
+
## ✅ Fase 6 — Modo restringido: cuestionarios (pruebas y demostración) (v1.8, beta)
|
|
53
53
|
|
|
54
54
|
Abrir un cuestionario, ver sus preguntas y marcar respuestas desde Claude. **Existe solo para pruebas y
|
|
55
55
|
para demostrar lo que el MCP es capaz de hacer.**
|
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
|
+
"version": "1.8.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": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "moodle-student-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.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",
|
package/src/enlaces.js
CHANGED
|
@@ -15,6 +15,20 @@ export const MAX_MEMORIA_SUBIDAS = 120 * 1048576; // 120 MB entre todas las subi
|
|
|
15
15
|
|
|
16
16
|
export const nuevoId = () => randomBytes(18).toString("base64url");
|
|
17
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Dirección pública del servidor. MOODLE_REMOTO_URL_PUBLICA tiene prioridad; si no está, se detecta
|
|
20
|
+
* en plataformas conocidas (Render, Railway, Fly.io) para no tener que configurarla a mano.
|
|
21
|
+
*/
|
|
22
|
+
export function urlPublica(env = process.env) {
|
|
23
|
+
const candidata =
|
|
24
|
+
env.MOODLE_REMOTO_URL_PUBLICA ||
|
|
25
|
+
env.RENDER_EXTERNAL_URL ||
|
|
26
|
+
(env.RAILWAY_PUBLIC_DOMAIN && `https://${env.RAILWAY_PUBLIC_DOMAIN}`) ||
|
|
27
|
+
(env.FLY_APP_NAME && `https://${env.FLY_APP_NAME}.fly.dev`) ||
|
|
28
|
+
"";
|
|
29
|
+
return candidata.replace(/\/+$/, "");
|
|
30
|
+
}
|
|
31
|
+
|
|
18
32
|
export class Enlaces {
|
|
19
33
|
constructor(ahora = () => Date.now()) {
|
|
20
34
|
this.ahora = ahora;
|
|
@@ -22,7 +36,7 @@ export class Enlaces {
|
|
|
22
36
|
}
|
|
23
37
|
|
|
24
38
|
baseUrl() {
|
|
25
|
-
const b = (
|
|
39
|
+
const b = urlPublica();
|
|
26
40
|
if (!/^https?:\/\/[^/]+/.test(b))
|
|
27
41
|
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
42
|
return b;
|
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 { ejecutarRestringido } from "./restringido.js";
|
|
14
15
|
import { enlaces } from "./enlaces.js";
|
|
15
16
|
import { homedir } from "node:os";
|
|
16
17
|
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
@@ -639,6 +640,9 @@ export async function ejecutar(m, acc, { aceptar_declaracion, resolverTarea } =
|
|
|
639
640
|
const despues = await analizarTarea(m, t);
|
|
640
641
|
return { texto: `✔ Entrega eliminada de "${acc.nombre}". Estado ahora: ${despues.estado}.`, detalle: { assignid: acc.assignid } };
|
|
641
642
|
}
|
|
643
|
+
case "quiz_iniciar":
|
|
644
|
+
case "quiz_enviar":
|
|
645
|
+
return ejecutarRestringido(m, acc);
|
|
642
646
|
case "asistencia":
|
|
643
647
|
return ejecutarAsistencia(m, acc);
|
|
644
648
|
case "mensaje": {
|
package/src/index.js
CHANGED
|
@@ -17,6 +17,7 @@ import { Sitios, leerSitios } from "./sitios.js";
|
|
|
17
17
|
import { Anonimizador } from "./privacidad.js";
|
|
18
18
|
import { registrarPrompts } from "./prompts.js";
|
|
19
19
|
import { enlaces } from "./enlaces.js";
|
|
20
|
+
import { AVISO, registrarRestringido, restringidoActivo } from "./restringido.js";
|
|
20
21
|
import { createHash } from "node:crypto";
|
|
21
22
|
|
|
22
23
|
cargarEnv();
|
|
@@ -31,7 +32,17 @@ const MODO_REMOTO = process.argv.includes("--http") || activado("MOODLE_REMOTO")
|
|
|
31
32
|
const MODO_ESCRITURA = activado("MOODLE_ESCRITURA") && (!MODO_REMOTO || activado("MOODLE_REMOTO_ESCRITURA"));
|
|
32
33
|
|
|
33
34
|
// Uno o varios sitios Moodle (ver sitios.js); las herramientas siempre usan el sitio activo.
|
|
34
|
-
|
|
35
|
+
// Modo restringido (cuestionarios): triple llave y solo en local. Ver restringido.js.
|
|
36
|
+
const MODO_RESTRINGIDO = restringidoActivo(process.env, { remoto: MODO_REMOTO });
|
|
37
|
+
if (MODO_RESTRINGIDO) console.error(`\n${AVISO}\n`);
|
|
38
|
+
else if (process.env.MOODLE_MODO_RESTRINGIDO === "1")
|
|
39
|
+
console.error(
|
|
40
|
+
MODO_REMOTO
|
|
41
|
+
? "Modo restringido ignorado: no está disponible en el servidor remoto."
|
|
42
|
+
: "Modo restringido NO activado: requiere también MOODLE_ESCRITURA=1 y MOODLE_ACEPTO_RESPONSABILIDAD=si (lee el aviso en docs/ROADMAP.md).",
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
const sitios = new Sitios(leerSitios(), { escritura: MODO_ESCRITURA, restringido: MODO_RESTRINGIDO, inicial: process.env.MOODLE_SITIO });
|
|
35
46
|
const moodle = () => sitios.actual();
|
|
36
47
|
|
|
37
48
|
/** Explicación práctica para los errores más comunes de conexión. */
|
|
@@ -60,7 +71,7 @@ const anonimo = new Anonimizador({
|
|
|
60
71
|
});
|
|
61
72
|
sitios.alCambiar.push(() => (anonimo.listoHasta = 0));
|
|
62
73
|
|
|
63
|
-
const INFO_SERVIDOR = { name: "moodle-student-bridge", version: "1.
|
|
74
|
+
const INFO_SERVIDOR = { name: "moodle-student-bridge", version: "1.8.0" };
|
|
64
75
|
const OPCIONES_SERVIDOR = {
|
|
65
76
|
instructions:
|
|
66
77
|
"Herramientas para el Moodle del estudiante. Las de lectura se pueden usar libremente. " +
|
|
@@ -71,7 +82,10 @@ const OPCIONES_SERVIDOR = {
|
|
|
71
82
|
(MODO_ANONIMO
|
|
72
83
|
? " 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)."
|
|
73
84
|
: "") +
|
|
74
|
-
(MODO_REMOTO ? " Servidor remoto: no tiene acceso a los archivos del dispositivo del usuario." : "")
|
|
85
|
+
(MODO_REMOTO ? " Servidor remoto: no tiene acceso a los archivos del dispositivo del usuario." : "") +
|
|
86
|
+
(MODO_RESTRINGIDO
|
|
87
|
+
? " MODO RESTRINGIDO activo (herramientas restringido_*): durante un intento de cuestionario NUNCA sugieras, elijas, razones ni expliques respuestas ni des pistas; marca solo la respuesta que el usuario indique literalmente. Si te pide resolverlo, niégate y recuérdale el reglamento académico."
|
|
88
|
+
: ""),
|
|
75
89
|
};
|
|
76
90
|
|
|
77
91
|
const texto = (t) => ({ content: [{ type: "text", text: t }] });
|
|
@@ -567,6 +581,7 @@ const FUNCIONALIDADES = [
|
|
|
567
581
|
["Escritura: entregas", ["mod_assign_save_submission", "mod_assign_submit_for_grading", "mod_assign_remove_submission", "core_files_get_unused_draft_itemid"]],
|
|
568
582
|
["Escritura: mensajes", ["core_message_send_messages_to_conversation", "core_message_send_instant_messages"]],
|
|
569
583
|
["Escritura: foros", ["mod_forum_add_discussion_post", "mod_forum_add_discussion", "mod_forum_update_discussion_post", "mod_forum_delete_post"]],
|
|
584
|
+
["Modo restringido: cuestionarios", ["mod_quiz_start_attempt", "mod_quiz_get_attempt_data", "mod_quiz_save_attempt", "mod_quiz_process_attempt", "mod_quiz_get_attempt_summary"]],
|
|
570
585
|
];
|
|
571
586
|
|
|
572
587
|
herramienta(
|
|
@@ -595,7 +610,8 @@ herramienta(
|
|
|
595
610
|
`✅ Token válido · usuario: ${s.fullname}`,
|
|
596
611
|
`Sitio: ${s.sitename} · ${s.siteurl}`,
|
|
597
612
|
`Moodle ${s.release}`,
|
|
598
|
-
`Modo: ${MODO_ESCRITURA ? "lectura + ESCRITURA (con confirmación)" : "solo lectura"}`,
|
|
613
|
+
`Modo: ${MODO_ESCRITURA ? "lectura + ESCRITURA (con confirmación)" : "solo lectura"}${MODO_RESTRINGIDO ? " + RESTRINGIDO (cuestionarios)" : ""}`,
|
|
614
|
+
...(MODO_RESTRINGIDO ? ["", AVISO, ""] : []),
|
|
599
615
|
`Subida de archivos: ${s.uploadfiles ? `permitida (máx. ${Math.round((s.usermaxuploadfilesize ?? 0) / 1048576)} MB por archivo)` : "no permitida"}`,
|
|
600
616
|
`Funciones del sitio disponibles para tu token: ${disponibles.size} · el MCP usa ${usadas.filter((f) => disponibles.has(f)).length}/${usadas.length}`,
|
|
601
617
|
"",
|
|
@@ -629,6 +645,9 @@ const confirmaciones = MODO_ESCRITURA ? registrarEscritura({ herramienta, moodle
|
|
|
629
645
|
// Asistencia: lectura siempre; marcar solo con modo escritura (usa los mismos códigos de confirmación).
|
|
630
646
|
registrarAsistencia({ herramienta, moodle, resolverCurso, confirmaciones, escritura: MODO_ESCRITURA });
|
|
631
647
|
|
|
648
|
+
// Fase 6: modo restringido (cuestionarios). Desactivado por defecto; ver restringido.js.
|
|
649
|
+
if (MODO_RESTRINGIDO && confirmaciones) registrarRestringido({ herramienta, moodle, resolverCurso, confirmaciones });
|
|
650
|
+
|
|
632
651
|
// Varios Moodle: al cambiar de sitio se descartan las acciones preparadas en el anterior.
|
|
633
652
|
sitios.alCambiar.push(() => confirmaciones?.pendientes.clear());
|
|
634
653
|
if (sitios.lista.length > 1) {
|
package/src/moodle.js
CHANGED
|
@@ -44,7 +44,7 @@ export function aplanar(obj, prefijo = "", salida = new URLSearchParams()) {
|
|
|
44
44
|
|
|
45
45
|
export class Moodle {
|
|
46
46
|
/** @param escritura si es false, cualquier función que modifique Moodle se rechaza antes de enviarse. */
|
|
47
|
-
constructor({ url, token, escritura = false }) {
|
|
47
|
+
constructor({ url, token, escritura = false, restringido = false }) {
|
|
48
48
|
if (!url || !token) {
|
|
49
49
|
throw new MoodleError(
|
|
50
50
|
"Faltan MOODLE_URL y/o MOODLE_TOKEN. Configúralos en el .env o en las variables de entorno del MCP.",
|
|
@@ -54,12 +54,13 @@ export class Moodle {
|
|
|
54
54
|
this.url = url.replace(/\/+$/, "");
|
|
55
55
|
this.token = token;
|
|
56
56
|
this.escritura = !!escritura;
|
|
57
|
+
this.restringido = !!restringido;
|
|
57
58
|
this._sitio = null;
|
|
58
59
|
this._cache = new Map();
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
async llamar(funcion, params = {}) {
|
|
62
|
-
const motivo = motivoFuncionNoPermitida(funcion, { escritura: this.escritura, params });
|
|
63
|
+
const motivo = motivoFuncionNoPermitida(funcion, { escritura: this.escritura, restringido: this.restringido, params });
|
|
63
64
|
if (motivo) throw new MoodleError(`Bloqueado por seguridad: ${motivo}`, "no_permitida");
|
|
64
65
|
const cuerpo = aplanar({ ...params, wstoken: this.token, wsfunction: funcion, moodlewsrestformat: "json" });
|
|
65
66
|
const res = await fetch(`${this.url}/webservice/rest/server.php`, {
|
package/src/remoto.js
CHANGED
|
@@ -15,7 +15,7 @@ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
|
15
15
|
import { extname } from "node:path";
|
|
16
16
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
17
17
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
18
|
-
import { MAX_MEMORIA_SUBIDAS, disposicion, enlaces } from "./enlaces.js";
|
|
18
|
+
import { MAX_MEMORIA_SUBIDAS, disposicion, enlaces, urlPublica } from "./enlaces.js";
|
|
19
19
|
import { nombreSeguro } from "./estudio.js";
|
|
20
20
|
|
|
21
21
|
const escHtml = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
@@ -202,7 +202,12 @@ export async function iniciarRemoto(crearServidor, { escritura = false, puerto,
|
|
|
202
202
|
temporal = true;
|
|
203
203
|
}
|
|
204
204
|
|
|
205
|
-
|
|
205
|
+
// Anti DNS rebinding: hosts explícitos o, si no, el de la URL pública detectada (Render, Railway, Fly).
|
|
206
|
+
const publica = urlPublica();
|
|
207
|
+
const hostsPermitidos = (process.env.MOODLE_REMOTO_HOSTS || (publica && !process.env.MOODLE_REMOTO_URL_PUBLICA ? new URL(publica).hostname : ""))
|
|
208
|
+
.split(",")
|
|
209
|
+
.map((h) => h.trim().toLowerCase())
|
|
210
|
+
.filter(Boolean);
|
|
206
211
|
const permitido = crearLimitador(Number(process.env.MOODLE_REMOTO_LIMITE ?? 120));
|
|
207
212
|
const sesiones = new Map(); // id → { transporte, ultimo }
|
|
208
213
|
const ruta = `/mcp/${clave}`;
|
|
@@ -261,9 +266,10 @@ export async function iniciarRemoto(crearServidor, { escritura = false, puerto,
|
|
|
261
266
|
`moodle-student-bridge · modo remoto escuchando en http://${host}:${real.port}`,
|
|
262
267
|
`Modo: ${escritura ? "lectura + ESCRITURA (con confirmación)" : "solo lectura"}`,
|
|
263
268
|
"",
|
|
264
|
-
"URL del conector (agrega delante tu dominio https, p. ej. el del túnel):",
|
|
269
|
+
publica ? "URL del conector:" : "URL del conector (agrega delante tu dominio https, p. ej. el del túnel):",
|
|
265
270
|
// La clave solo se imprime si es temporal: en Docker o en la nube los registros pueden guardarse.
|
|
266
|
-
|
|
271
|
+
` ${publica || "https://<tu-dominio>"}${temporal ? ruta : "/mcp/<tu MOODLE_REMOTO_CLAVE>"}`,
|
|
272
|
+
publica ? `Enlaces de archivos: ${publica}/d/… y ${publica}/subir/…` : "Para enlaces de archivos configura MOODLE_REMOTO_URL_PUBLICA.",
|
|
267
273
|
"",
|
|
268
274
|
temporal
|
|
269
275
|
? "⚠ Esta clave es TEMPORAL: cambia en cada arranque. Guarda una fija en MOODLE_REMOTO_CLAVE (npm run remoto -- --nueva-clave)."
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// Fase 6 — MODO RESTRINGIDO: cuestionarios desde Claude.
|
|
2
|
+
//
|
|
3
|
+
// Existe SOLO para pruebas y para demostrar lo que el MCP es capaz de hacer. Desactivado por defecto.
|
|
4
|
+
// Barreras:
|
|
5
|
+
// - Triple llave: MOODLE_MODO_RESTRINGIDO=1 + MOODLE_ESCRITURA=1 + MOODLE_ACEPTO_RESPONSABILIDAD=si.
|
|
6
|
+
// - Solo en modo local (nunca en el servidor remoto).
|
|
7
|
+
// - La IA no resuelve: marca exactamente la respuesta que el estudiante indique. Las instrucciones del
|
|
8
|
+
// servidor y cada salida le prohíben sugerir, elegir o explicar respuestas durante un intento.
|
|
9
|
+
// - No se esquiva nada: Safe Exam Browser / ventana segura → bloqueado; contraseña → solo la que dio
|
|
10
|
+
// el profesor; las razones de Moodle para impedir el acceso se respetan.
|
|
11
|
+
// - Iniciar (consume un intento, arranca el reloj) y enviar (definitivo) exigen código de confirmación.
|
|
12
|
+
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
import { MoodleError, faltan, fecha, htmlATexto, normalizar } from "./moodle.js";
|
|
15
|
+
|
|
16
|
+
export const AVISO =
|
|
17
|
+
"⚠ MODO RESTRINGIDO — Usar herramientas de IA en evaluaciones puede violar el reglamento de tu institución " +
|
|
18
|
+
"y tener consecuencias académicas graves. Este modo existe solo para pruebas y demostraciones. Su uso es " +
|
|
19
|
+
"responsabilidad total y exclusiva del estudiante; los autores no se hacen responsables.";
|
|
20
|
+
|
|
21
|
+
const NO_RESOLVER =
|
|
22
|
+
"INSTRUCCIÓN PARA EL ASISTENTE: durante este intento NO sugieras, elijas, razones ni expliques respuestas, ni " +
|
|
23
|
+
"des pistas sobre los temas de las preguntas. Marca únicamente la respuesta que el estudiante indique de forma literal.";
|
|
24
|
+
|
|
25
|
+
/** ¿Está activado el modo restringido con sus tres llaves? */
|
|
26
|
+
export function restringidoActivo(env = process.env, { remoto = false } = {}) {
|
|
27
|
+
return env.MOODLE_MODO_RESTRINGIDO === "1" && ["1", "true"].includes(env.MOODLE_ESCRITURA ?? "") && (env.MOODLE_ACEPTO_RESPONSABILIDAD ?? "").toLowerCase() === "si" && !remoto;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Reglas de acceso que este modo nunca intenta esquivar. */
|
|
31
|
+
const REGLAS_BLOQUEANTES = {
|
|
32
|
+
quizaccess_seb: "exige Safe Exam Browser",
|
|
33
|
+
quizaccess_securewindow: "exige ventana segura del navegador",
|
|
34
|
+
quizaccess_browsersecurity: "exige ventana segura del navegador",
|
|
35
|
+
quizaccess_proctoring: "tiene supervisión (proctoring)",
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// ------------------------------------------------------------------ análisis de una pregunta en curso
|
|
39
|
+
|
|
40
|
+
const dec = (s = "") => s.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
41
|
+
const attr = (tag, nombre) => dec(tag.match(new RegExp(`\\b${nombre}="([^"]*)"`))?.[1] ?? "");
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* HTML de una pregunta de un intento EN CURSO → campos que hay que enviar para guardar la respuesta.
|
|
45
|
+
* Soporta opción múltiple (una o varias), verdadero/falso, respuesta corta/numérica, emparejamiento
|
|
46
|
+
* (desplegables) y ensayo.
|
|
47
|
+
*/
|
|
48
|
+
export function parsearPreguntaViva(html = "") {
|
|
49
|
+
const h = html.replace(/\r/g, "");
|
|
50
|
+
const iTexto = h.indexOf('class="qtext"');
|
|
51
|
+
const iResp = h.indexOf('class="ablock');
|
|
52
|
+
const enunciado = iTexto >= 0 ? htmlATexto(h.slice(h.indexOf(">", iTexto) + 1, iResp > iTexto ? h.lastIndexOf("<", iResp) : undefined).replace(/<input[^>]*>/gi, "")) : "";
|
|
53
|
+
const fijos = [...h.matchAll(/<input[^>]*type="hidden"[^>]*>/gi)]
|
|
54
|
+
.map((m) => ({ name: attr(m[0], "name"), value: attr(m[0], "value") }))
|
|
55
|
+
.filter((c) => /:sequencecheck$|_answerformat$/.test(c.name));
|
|
56
|
+
|
|
57
|
+
const opciones = [];
|
|
58
|
+
for (const m of h.matchAll(/<input[^>]*type="(radio|checkbox)"[^>]*>/gi)) {
|
|
59
|
+
const tag = m[0];
|
|
60
|
+
const name = attr(tag, "name");
|
|
61
|
+
if (!name || /_:flagged$/.test(name)) continue;
|
|
62
|
+
const id = attr(tag, "id");
|
|
63
|
+
const etiquetaId = attr(tag, "aria-labelledby") || (id ? `${id}_label` : "");
|
|
64
|
+
let texto = "";
|
|
65
|
+
if (etiquetaId) {
|
|
66
|
+
const i = h.indexOf(`id="${etiquetaId}"`);
|
|
67
|
+
if (i >= 0) texto = htmlATexto(h.slice(h.indexOf(">", i) + 1, h.indexOf('</div> </div>', i) > 0 ? h.indexOf("</div> </div>", i) : h.indexOf("</label>", i)));
|
|
68
|
+
}
|
|
69
|
+
if (!texto && id) texto = htmlATexto(h.match(new RegExp(`<label[^>]*for="${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"[^>]*>([\\s\\S]*?)</label>`))?.[1] ?? "");
|
|
70
|
+
const letra = texto.match(/^([a-z])[.)]\s*/i)?.[1]?.toLowerCase() ?? null;
|
|
71
|
+
opciones.push({ tipo: m[1].toLowerCase(), name, value: attr(tag, "value"), texto: texto.replace(/^[a-z][.)]\s*/i, "").trim(), letra, marcada: /\bchecked\b/i.test(tag) });
|
|
72
|
+
}
|
|
73
|
+
const textos = [...h.matchAll(/<input[^>]*type="text"[^>]*>/gi)].map((m) => ({ name: attr(m[0], "name"), value: attr(m[0], "value") })).filter((c) => c.name);
|
|
74
|
+
const areas = [...h.matchAll(/<textarea[^>]*name="([^"]+)"[^>]*>([\s\S]*?)<\/textarea>/gi)].map((m) => ({ name: m[1], value: htmlATexto(m[2]) }));
|
|
75
|
+
const selects = [...h.matchAll(/<select[^>]*name="([^"]+)"[^>]*>([\s\S]*?)<\/select>/gi)].map((m, i) => ({
|
|
76
|
+
name: m[1],
|
|
77
|
+
n: i + 1,
|
|
78
|
+
opciones: [...m[2].matchAll(/<option[^>]*value="([^"]*)"[^>]*>([\s\S]*?)<\/option>/gi)].map((o) => ({ value: dec(o[1]), texto: htmlATexto(o[2]), sel: /selected/i.test(o[0]) })).filter((o) => o.value !== "" && o.value !== "0"),
|
|
79
|
+
}));
|
|
80
|
+
return { enunciado, fijos, opciones, textos: [...textos, ...areas], selects };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Convierte la respuesta que dijo el estudiante en los campos de Moodle. Lanza error si es ambigua. */
|
|
84
|
+
export function camposRespuesta(p, respuesta) {
|
|
85
|
+
const r = String(respuesta ?? "").trim();
|
|
86
|
+
if (!r) throw new MoodleError("La respuesta está vacía.");
|
|
87
|
+
const campos = [...p.fijos];
|
|
88
|
+
const radios = p.opciones.filter((o) => o.tipo === "radio");
|
|
89
|
+
const checks = p.opciones.filter((o) => o.tipo === "checkbox");
|
|
90
|
+
const elegir = (lista, dicho) => {
|
|
91
|
+
const d = normalizar(dicho).replace(/[.)]\s*$/, "").trim();
|
|
92
|
+
const porLetra = lista.filter((o) => o.letra && o.letra === d);
|
|
93
|
+
if (porLetra.length === 1) return porLetra[0];
|
|
94
|
+
const exacta = lista.filter((o) => normalizar(o.texto) === d);
|
|
95
|
+
if (exacta.length === 1) return exacta[0];
|
|
96
|
+
const parcial = lista.filter((o) => normalizar(o.texto).includes(d));
|
|
97
|
+
if (parcial.length === 1) return parcial[0];
|
|
98
|
+
throw new MoodleError(`No pude identificar "${dicho}" entre las opciones (${lista.map((o) => (o.letra ? `${o.letra}. ` : "") + o.texto).join(" | ")}). Dila con su letra.`);
|
|
99
|
+
};
|
|
100
|
+
if (radios.length) {
|
|
101
|
+
const o = elegir(radios, r);
|
|
102
|
+
campos.push({ name: o.name, value: o.value });
|
|
103
|
+
return { campos, resumen: `${o.letra ? `${o.letra}. ` : ""}${o.texto}` };
|
|
104
|
+
}
|
|
105
|
+
if (checks.length) {
|
|
106
|
+
const elegidas = [...new Set(r.split(/\s*(?:,|;|\sy\s)\s*/i).map((x) => x.trim()).filter(Boolean).map((x) => elegir(checks, x)))];
|
|
107
|
+
for (const o of checks) campos.push({ name: o.name, value: elegidas.includes(o) ? o.value || "1" : "0" });
|
|
108
|
+
return { campos, resumen: elegidas.map((o) => `${o.letra ? `${o.letra}. ` : ""}${o.texto}`).join(" · ") };
|
|
109
|
+
}
|
|
110
|
+
if (p.selects.length) {
|
|
111
|
+
const pares = r.split(/\s*;\s*/).map((x) => x.match(/^(\d+)\s*[=:→-]\s*(.+)$/)).filter(Boolean);
|
|
112
|
+
if (pares.length !== p.selects.length) throw new MoodleError(`Indica una opción para cada uno de los ${p.selects.length} elementos, así: "1=…; 2=…".`);
|
|
113
|
+
const resumen = [];
|
|
114
|
+
for (const [, n, dicho] of pares) {
|
|
115
|
+
const s = p.selects.find((x) => x.n === Number(n));
|
|
116
|
+
if (!s) throw new MoodleError(`No existe el elemento ${n}.`);
|
|
117
|
+
const o = elegir(s.opciones.map((x) => ({ ...x, letra: null })), dicho);
|
|
118
|
+
campos.push({ name: s.name, value: o.value });
|
|
119
|
+
resumen.push(`${n}=${o.texto}`);
|
|
120
|
+
}
|
|
121
|
+
return { campos, resumen: resumen.join("; ") };
|
|
122
|
+
}
|
|
123
|
+
if (p.textos.length) {
|
|
124
|
+
campos.push({ name: p.textos[0].name, value: r });
|
|
125
|
+
return { campos, resumen: r.length > 80 ? `${r.slice(0, 80)}…` : r };
|
|
126
|
+
}
|
|
127
|
+
throw new MoodleError("Este tipo de pregunta no se puede responder desde aquí; respóndela en Moodle.");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function mostrarPregunta(q, p) {
|
|
131
|
+
const l = [`## Pregunta ${q.number ?? q.slot} (slot ${q.slot}) · ${q.type}${q.maxmark ? ` · vale ${q.maxmark}` : ""}`, p.enunciado || "(sin enunciado)"];
|
|
132
|
+
for (const o of p.opciones) l.push(`${o.marcada ? "[x]" : "[ ]"} ${o.letra ? `${o.letra}. ` : ""}${o.texto}`);
|
|
133
|
+
for (const s of p.selects) l.push(`${s.n}. → ${s.opciones.find((o) => o.sel)?.texto ?? "(sin elegir)"} opciones: ${s.opciones.map((o) => o.texto).join(" | ")}`);
|
|
134
|
+
for (const t of p.textos) l.push(`Respuesta escrita: ${t.value ? `«${t.value}»` : "(vacía)"}`);
|
|
135
|
+
return l.join("\n");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ------------------------------------------------------------------ registro
|
|
139
|
+
|
|
140
|
+
export function registrarRestringido({ herramienta, moodle, resolverCurso, confirmaciones }) {
|
|
141
|
+
const cab = (t) => `${AVISO}\n\n${t}`;
|
|
142
|
+
|
|
143
|
+
async function resolverQuiz(cuestionario, curso) {
|
|
144
|
+
const c = await resolverCurso(curso);
|
|
145
|
+
const qs = await moodle().cuestionarios(c ? [c.id] : undefined);
|
|
146
|
+
const n = Number(cuestionario);
|
|
147
|
+
let h = qs.filter((q) => q.id === n || q.coursemodule === n);
|
|
148
|
+
if (!h.length) h = qs.filter((q) => normalizar(q.name).includes(normalizar(cuestionario)));
|
|
149
|
+
if (!h.length) throw new MoodleError(`No encontré el cuestionario "${cuestionario}".`);
|
|
150
|
+
if (h.length > 1) throw new MoodleError(`"${cuestionario}" coincide con varios:\n${h.map((q) => `- [${q.id}] ${q.name} (${q.curso})`).join("\n")}`);
|
|
151
|
+
return h[0];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function analizarQuiz(q) {
|
|
155
|
+
const m = moodle();
|
|
156
|
+
const [acceso, { attempts = [] }] = await Promise.all([
|
|
157
|
+
m.llamar("mod_quiz_get_quiz_access_information", { quizid: q.id }),
|
|
158
|
+
m.llamar("mod_quiz_get_user_quiz_attempts", { quizid: q.id, status: "all" }),
|
|
159
|
+
]);
|
|
160
|
+
const bloqueos = [];
|
|
161
|
+
for (const r of acceso.activerulenames ?? []) if (REGLAS_BLOQUEANTES[r]) bloqueos.push(`El cuestionario ${REGLAS_BLOQUEANTES[r]}: este modo no lo esquiva.`);
|
|
162
|
+
for (const r of acceso.preventaccessreasons ?? []) bloqueos.push(htmlATexto(r));
|
|
163
|
+
if (!acceso.canattempt) bloqueos.push("Moodle no te permite intentar este cuestionario.");
|
|
164
|
+
const enCurso = attempts.find((a) => a.state === "inprogress" || a.state === "overdue");
|
|
165
|
+
const usados = attempts.filter((a) => a.state !== "abandoned").length;
|
|
166
|
+
const pideClave = (acceso.activerulenames ?? []).includes("quizaccess_password");
|
|
167
|
+
return { acceso, attempts, enCurso, usados, pideClave, bloqueos };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
herramienta(
|
|
171
|
+
"restringido_ver_cuestionario",
|
|
172
|
+
"MODO RESTRINGIDO: estado de un cuestionario (reglas de acceso, intentos, tiempo límite, si hay un intento en curso) antes de iniciarlo.",
|
|
173
|
+
{ cuestionario: z.string(), curso: z.string().optional() },
|
|
174
|
+
async ({ cuestionario, curso }) => {
|
|
175
|
+
const q = await resolverQuiz(cuestionario, curso);
|
|
176
|
+
const a = await analizarQuiz(q);
|
|
177
|
+
return cab(
|
|
178
|
+
[
|
|
179
|
+
`# ${q.name} — ${q.curso}`,
|
|
180
|
+
`Abre: ${fecha(q.timeopen)} · Cierra: ${fecha(q.timeclose)}${q.timeclose ? ` (${faltan(q.timeclose)})` : ""}`,
|
|
181
|
+
`Tiempo límite: ${q.timelimit ? `${Math.round(q.timelimit / 60)} min` : "sin límite"} · Intentos: ${a.usados}/${q.attempts || "∞"}`,
|
|
182
|
+
`Reglas: ${(a.acceso.accessrules ?? []).map(htmlATexto).join(" · ") || "ninguna"}`,
|
|
183
|
+
a.enCurso ? `▶ Intento en curso: id ${a.enCurso.id} (usa restringido_ver_preguntas).` : "",
|
|
184
|
+
a.bloqueos.length ? `\n⛔ No se puede:\n${a.bloqueos.map((b) => `- ${b}`).join("\n")}` : a.enCurso ? "" : "Se puede iniciar con restringido_preparar_intento.",
|
|
185
|
+
]
|
|
186
|
+
.filter(Boolean)
|
|
187
|
+
.join("\n"),
|
|
188
|
+
);
|
|
189
|
+
},
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
herramienta(
|
|
193
|
+
"restringido_preparar_intento",
|
|
194
|
+
"MODO RESTRINGIDO · PASO 1 de 2 para INICIAR un intento (consume un intento y arranca el temporizador). Solo comprueba; devuelve un código para `confirmar`.",
|
|
195
|
+
{ cuestionario: z.string(), curso: z.string().optional(), contrasena: z.string().optional().describe("Solo la contraseña que dio el profesor") },
|
|
196
|
+
async ({ cuestionario, curso, contrasena }) => {
|
|
197
|
+
const q = await resolverQuiz(cuestionario, curso);
|
|
198
|
+
const a = await analizarQuiz(q);
|
|
199
|
+
if (a.enCurso) return cab(`Ya tienes un intento en curso (id ${a.enCurso.id}). No hace falta iniciar otro: usa restringido_ver_preguntas.`);
|
|
200
|
+
if (a.bloqueos.length) return cab(`⛔ No se puede iniciar "${q.name}":\n${a.bloqueos.map((b) => `- ${b}`).join("\n")}`);
|
|
201
|
+
if (a.pideClave && !contrasena) return cab("⛔ Este cuestionario pide una contraseña. Solo puedes usar la que te dio el profesor (parámetro contrasena).");
|
|
202
|
+
const codigo = confirmaciones.crear({ tipo: "quiz_iniciar", quizid: q.id, nombre: q.name, contrasena });
|
|
203
|
+
return cab(
|
|
204
|
+
[
|
|
205
|
+
`# Iniciar intento: ${q.name}`,
|
|
206
|
+
`Curso: ${q.curso}`,
|
|
207
|
+
`Intento ${a.usados + 1} de ${q.attempts || "∞"} · tiempo límite: ${q.timelimit ? `${Math.round(q.timelimit / 60)} min (el reloj NO se detiene)` : "sin límite"}`,
|
|
208
|
+
`Cierra: ${fecha(q.timeclose)}`,
|
|
209
|
+
"",
|
|
210
|
+
"⚠ Al confirmar se CONSUME un intento y empieza a correr el tiempo.",
|
|
211
|
+
`\nCódigo de confirmación: ${codigo} (válido 10 min, un solo uso). Muéstrale este resumen al usuario y confirma solo si lo aprueba.`,
|
|
212
|
+
].join("\n"),
|
|
213
|
+
);
|
|
214
|
+
},
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
herramienta(
|
|
218
|
+
"restringido_ver_preguntas",
|
|
219
|
+
"MODO RESTRINGIDO: muestra las preguntas de una página de tu intento en curso con lo que tienes marcado. NO resuelve ni sugiere.",
|
|
220
|
+
{ intento: z.number().int(), pagina: z.number().int().min(0).default(0) },
|
|
221
|
+
async ({ intento, pagina = 0 }) => {
|
|
222
|
+
const r = await moodle().llamar("mod_quiz_get_attempt_data", { attemptid: intento, page: pagina });
|
|
223
|
+
const partes = [`# Intento ${intento} · página ${pagina + 1}${r.nextpage >= 0 ? ` (hay más: página ${r.nextpage + 1})` : " (última)"}`, NO_RESOLVER];
|
|
224
|
+
for (const q of r.questions ?? []) partes.push("", mostrarPregunta(q, parsearPreguntaViva(q.html)));
|
|
225
|
+
partes.push("", "Para marcar: restringido_marcar con intento, pregunta (slot) y la respuesta que diga el estudiante (letra, texto, o \"1=…; 2=…\" en emparejamiento).");
|
|
226
|
+
return cab(partes.join("\n"));
|
|
227
|
+
},
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
herramienta(
|
|
231
|
+
"restringido_marcar",
|
|
232
|
+
"MODO RESTRINGIDO: guarda en tu intento EXACTAMENTE la respuesta que indique el estudiante (no la elige la IA). Se puede cambiar mientras el intento esté abierto.",
|
|
233
|
+
{
|
|
234
|
+
intento: z.number().int(),
|
|
235
|
+
pregunta: z.number().int().describe("Número de slot de la pregunta (aparece en restringido_ver_preguntas)"),
|
|
236
|
+
respuesta: z.string().describe("Lo que dijo el estudiante: letra (\"b\"), texto de la opción, varias separadas por comas, \"1=…; 2=…\" o texto libre"),
|
|
237
|
+
},
|
|
238
|
+
async ({ intento, pregunta, respuesta }) => {
|
|
239
|
+
const m = moodle();
|
|
240
|
+
const resumen = await m.llamar("mod_quiz_get_attempt_summary", { attemptid: intento });
|
|
241
|
+
const qs = (resumen.questions ?? []).find((x) => x.slot === pregunta);
|
|
242
|
+
if (!qs) throw new MoodleError(`El intento no tiene la pregunta con slot ${pregunta}.`);
|
|
243
|
+
const datos = await m.llamar("mod_quiz_get_attempt_data", { attemptid: intento, page: qs.page });
|
|
244
|
+
const q = (datos.questions ?? []).find((x) => x.slot === pregunta);
|
|
245
|
+
const p = parsearPreguntaViva(q?.html ?? "");
|
|
246
|
+
const { campos, resumen: marcado } = camposRespuesta(p, respuesta);
|
|
247
|
+
const r = await m.llamar("mod_quiz_save_attempt", { attemptid: intento, data: campos });
|
|
248
|
+
if (r.status === false) throw new MoodleError(`Moodle no guardó la respuesta: ${(r.warnings ?? []).map((w) => w.message).join("; ")}`);
|
|
249
|
+
return cab(`✔ Pregunta ${qs.number ?? pregunta}: marcado «${marcado}». Puedes cambiarlo mientras el intento siga abierto.\n${NO_RESOLVER}`);
|
|
250
|
+
},
|
|
251
|
+
);
|
|
252
|
+
|
|
253
|
+
herramienta(
|
|
254
|
+
"restringido_preparar_envio",
|
|
255
|
+
"MODO RESTRINGIDO · PASO 1 de 2 para ENVIAR (terminar) el intento. Muestra preguntas sin responder y el tiempo restante; devuelve un código para `confirmar`.",
|
|
256
|
+
{ intento: z.number().int() },
|
|
257
|
+
async ({ intento }) => {
|
|
258
|
+
const m = moodle();
|
|
259
|
+
const [s, datos] = await Promise.all([
|
|
260
|
+
m.llamar("mod_quiz_get_attempt_summary", { attemptid: intento }),
|
|
261
|
+
m.llamar("mod_quiz_get_attempt_data", { attemptid: intento, page: 0 }).catch(() => ({})),
|
|
262
|
+
]);
|
|
263
|
+
const quizid = datos.attempt?.quiz;
|
|
264
|
+
const acc = quizid ? await m.llamar("mod_quiz_get_attempt_access_information", { quizid, attemptid: intento }).catch(() => ({})) : {};
|
|
265
|
+
const qs = s.questions ?? [];
|
|
266
|
+
const sin = qs.filter((q) => ["todo", "invalid"].includes(q.state) || /sin responder|not yet answered/i.test(q.status ?? ""));
|
|
267
|
+
const codigo = confirmaciones.crear({ tipo: "quiz_enviar", attemptid: intento, nombre: `intento ${intento}` });
|
|
268
|
+
return cab(
|
|
269
|
+
[
|
|
270
|
+
`# Enviar intento ${intento}`,
|
|
271
|
+
`Preguntas: ${qs.length} · sin responder: ${sin.length}${sin.length ? ` (${sin.map((q) => q.number ?? q.slot).join(", ")})` : ""}`,
|
|
272
|
+
acc.endtime ? `Tiempo restante: ${faltan(acc.endtime)}` : "",
|
|
273
|
+
"",
|
|
274
|
+
"⚠ Enviar es DEFINITIVO: después no podrás cambiar ninguna respuesta.",
|
|
275
|
+
`\nCódigo de confirmación: ${codigo} (válido 10 min, un solo uso). Confirma solo si el usuario lo aprueba.`,
|
|
276
|
+
]
|
|
277
|
+
.filter(Boolean)
|
|
278
|
+
.join("\n"),
|
|
279
|
+
);
|
|
280
|
+
},
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Ejecuta inicio o envío de un intento (lo llama `confirmar`). */
|
|
285
|
+
export async function ejecutarRestringido(m, acc) {
|
|
286
|
+
if (acc.tipo === "quiz_iniciar") {
|
|
287
|
+
const r = await m.llamar("mod_quiz_start_attempt", { quizid: acc.quizid, forcenew: 0, preflightdata: acc.contrasena ? [{ name: "quizpassword", value: acc.contrasena }] : [] });
|
|
288
|
+
if (r.warnings?.length && !r.attempt) throw new MoodleError(`Moodle no inició el intento: ${r.warnings.map((w) => w.message).join("; ")}`);
|
|
289
|
+
return { texto: `${AVISO}\n\n✔ Intento iniciado (id ${r.attempt.id}). Usa restringido_ver_preguntas con intento=${r.attempt.id}.\n${NO_RESOLVER}`, detalle: { attemptid: r.attempt.id } };
|
|
290
|
+
}
|
|
291
|
+
const r = await m.llamar("mod_quiz_process_attempt", { attemptid: acc.attemptid, finishattempt: 1, timeup: 0, data: [] });
|
|
292
|
+
if (r.state !== "finished") throw new MoodleError(`El intento no quedó terminado (estado: ${r.state}). ${(r.warnings ?? []).map((w) => w.message).join("; ")}`);
|
|
293
|
+
return { texto: `${AVISO}\n\n✔ Intento ${acc.attemptid} enviado. Cuando el profesor lo permita, revísalo con revisar_intento.`, detalle: { attemptid: acc.attemptid } };
|
|
294
|
+
}
|
package/src/seguridad.js
CHANGED
|
@@ -84,14 +84,26 @@ function motivoContenidoMovil(params = {}, escritura) {
|
|
|
84
84
|
return null;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
/** Cuestionarios en curso: SOLO con el modo restringido (triple llave, ver restringido.js). */
|
|
88
|
+
export const FUNCIONES_RESTRINGIDO = new Set([
|
|
89
|
+
"mod_quiz_get_quiz_access_information",
|
|
90
|
+
"mod_quiz_get_attempt_access_information",
|
|
91
|
+
"mod_quiz_get_attempt_summary",
|
|
92
|
+
"mod_quiz_get_attempt_data",
|
|
93
|
+
"mod_quiz_start_attempt",
|
|
94
|
+
"mod_quiz_save_attempt",
|
|
95
|
+
"mod_quiz_process_attempt",
|
|
96
|
+
]);
|
|
97
|
+
|
|
87
98
|
/** Devuelve null si se permite, o el motivo del rechazo. */
|
|
88
|
-
export function motivoFuncionNoPermitida(funcion, { escritura = false, params } = {}) {
|
|
99
|
+
export function motivoFuncionNoPermitida(funcion, { escritura = false, restringido = false, params } = {}) {
|
|
89
100
|
if (funcion === "tool_mobile_get_content") return motivoContenidoMovil(params, escritura);
|
|
90
101
|
// Solo lectura de "Mis archivos privados" (no de otras áreas de archivos).
|
|
91
102
|
if (funcion === "core_files_get_files")
|
|
92
103
|
return params?.component === "user" && params?.filearea === "private" ? null : "core_files_get_files solo está permitido para tus archivos privados.";
|
|
93
104
|
if (FUNCIONES_LECTURA.has(funcion)) return null;
|
|
94
105
|
if (FUNCIONES_ESCRITURA.has(funcion)) return escritura ? null : `"${funcion}" modifica Moodle y el modo escritura está desactivado.`;
|
|
106
|
+
if (FUNCIONES_RESTRINGIDO.has(funcion)) return restringido ? null : `"${funcion}" solo está disponible en el modo restringido (desactivado).`;
|
|
95
107
|
return `"${funcion}" no está en la lista de funciones permitidas de moodle-student-bridge.`;
|
|
96
108
|
}
|
|
97
109
|
|
package/src/sitios.js
CHANGED
|
@@ -23,9 +23,10 @@ export function leerSitios(env = process.env) {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
export class Sitios {
|
|
26
|
-
constructor(lista, { escritura = false, inicial } = {}) {
|
|
26
|
+
constructor(lista, { escritura = false, restringido = false, inicial } = {}) {
|
|
27
27
|
this.lista = lista;
|
|
28
28
|
this.escritura = escritura;
|
|
29
|
+
this.restringido = restringido;
|
|
29
30
|
this.instancias = new Map();
|
|
30
31
|
this.alCambiar = [];
|
|
31
32
|
this.activo = lista.length ? (inicial ? this.buscar(inicial).nombre : lista[0].nombre) : null;
|
|
@@ -43,7 +44,7 @@ export class Sitios {
|
|
|
43
44
|
if (!this.activo) return new Moodle({ url: undefined, token: undefined }); // lanza el error de configuración
|
|
44
45
|
if (!this.instancias.has(this.activo)) {
|
|
45
46
|
const s = this.buscar(this.activo);
|
|
46
|
-
this.instancias.set(this.activo, new Moodle({ url: s.url, token: s.token, escritura: this.escritura }));
|
|
47
|
+
this.instancias.set(this.activo, new Moodle({ url: s.url, token: s.token, escritura: this.escritura, restringido: this.restringido }));
|
|
47
48
|
}
|
|
48
49
|
return this.instancias.get(this.activo);
|
|
49
50
|
}
|