From 304fc5ab6ce8540a6651b291e18e37d74166647d Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Sun, 15 Nov 2026 07:18:36 +0500 Subject: [PATCH 1/7] feat: add secure NFC assignment reader --- .env.example | 8 + package-lock.json | 416 ++++++++++++++++++++++++++++++++++++++ package.json | 1 + src/config/env.ts | 7 + src/db/migrate.ts | 4 +- src/db/schema.sql | 22 ++ src/security/oci-vault.ts | 19 ++ src/sources/nfc/lms.ts | 83 ++++++++ tests/nfc-lms.test.mjs | 29 +++ 9 files changed, 587 insertions(+), 2 deletions(-) create mode 100644 src/security/oci-vault.ts create mode 100644 src/sources/nfc/lms.ts create mode 100644 tests/nfc-lms.test.mjs diff --git a/.env.example b/.env.example index 94009df..4bb96d7 100644 --- a/.env.example +++ b/.env.example @@ -33,6 +33,14 @@ VU_STUDENT_ID= # Quote passwords containing #; dotenv treats an unquoted # as a comment. VU_PASSWORD= +# ---------- Optional NFC-IET CMS daily check ---------- +# Keep the student ID and password in OCI Vault, never in this file or WhatsApp. +# These are the secret OCIDs; Maya's VM needs a least-privilege instance-principal policy. +NFC_CMS_SYNC=false +NFC_SYNC_CRON=0 7 * * * +NFC_STUDENT_ID_SECRET_OCID= +NFC_PASSWORD_SECRET_OCID= + # ---------- AI ---------- GEMINI_API_KEY= GEMINI_MODEL=gemini-3.5-flash diff --git a/package-lock.json b/package-lock.json index 1aa7fb9..426546d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "better-sqlite3": "13.0.3", "dotenv": "18.0.7", "node-cron": "4.6.0", + "oci-secrets": "2.146.0", "pino": "9.14.0", "playwright": "1.64.1", "qrcode-terminal": "0.12.0", @@ -1473,6 +1474,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/isomorphic-fetch": { + "version": "0.0.35", + "resolved": "https://registry.npmjs.org/@types/isomorphic-fetch/-/isomorphic-fetch-0.0.35.tgz", + "integrity": "sha512-DaZNUvLDCAnCTjgwxgiL1eQdxIKEpNLOlTNtAgnZc50bG2copGhRrFN9/PxPBuJe+tZVLCbQ7ls0xveXVRPkvw==", + "license": "MIT" + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -1480,6 +1487,15 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-b0jGiOgHtZ2jqdPgPnP6WLCXZk1T8p06A/vPGzUvxpFGgKMbjXJDjC5m52ErqBnIuWZFgGoIJyRdeG5AyreJjA==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/node": { "version": "22.20.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", @@ -1489,6 +1505,15 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/opossum": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@types/opossum/-/opossum-4.1.1.tgz", + "integrity": "sha512-9TMnd8AWRVtnZMqBbbzceQoJdafErgUViogFaQ3eetsbeLtiFFZ695mepNaLtlfJi4uRP3GmHfe3CJ2DZKaxYA==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/qrcode-terminal": { "version": "0.12.2", "resolved": "https://registry.npmjs.org/@types/qrcode-terminal/-/qrcode-terminal-0.12.2.tgz", @@ -1502,6 +1527,21 @@ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", "license": "MIT" }, + "node_modules/@types/sshpk": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/@types/sshpk/-/sshpk-1.10.3.tgz", + "integrity": "sha512-cru1waDhHZnZuB18E6Dgf2UXf8U93mdOEDcKYe5jTri+fpucidSs7DLmGICpLxN+95aYkwtgeyny9fBFzQVdmA==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/uuid": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.3.4.tgz", + "integrity": "sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw==", + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.71.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.1.tgz", @@ -1781,6 +1821,24 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, "node_modules/async-mutex": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz", @@ -1869,6 +1927,15 @@ ], "license": "MIT" }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "license": "BSD-3-Clause", + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, "node_modules/better-sqlite3": { "version": "13.0.3", "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", @@ -1942,6 +2009,12 @@ "url": "https://opencollective.com/express" } }, + "node_modules/core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==", + "license": "MIT" + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -1963,6 +2036,18 @@ "integrity": "sha512-axn2UMEnkhyDUPWOwVKBMVIzSQy2ejH2xRGy1wq81dqRwApXfIzfbE3hIX0ZRFBIihf/KDqK158DLwESu4AK1w==", "license": "MIT" }, + "node_modules/dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==", + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0" + }, + "engines": { + "node": ">=0.10" + } + }, "node_modules/data-uri-to-buffer": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", @@ -2031,6 +2116,16 @@ "url": "https://dotenvx.com" } }, + "node_modules/ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==", + "license": "MIT", + "dependencies": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, "node_modules/ecdsa-sig-formatter": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", @@ -2050,6 +2145,12 @@ "once": "^1.4.0" } }, + "node_modules/es6-promise": { + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.6.tgz", + "integrity": "sha512-aRVgGdnmW2OiySVPUC9e6m+plolMAJKjZnQlCwNSuK5yQ0JN61DZSO1X1Ufd1foqWRAlig0rhduTCHe7sVtK5Q==", + "license": "MIT" + }, "node_modules/esbuild": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", @@ -2272,6 +2373,15 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "license": "MIT" }, + "node_modules/extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==", + "engines": [ + "node >=0.6.0" + ], + "license": "MIT" + }, "node_modules/fast-copy": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-4.2.0.tgz", @@ -2467,6 +2577,15 @@ "node": ">=18" } }, + "node_modules/getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==", + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -2531,6 +2650,20 @@ "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", "license": "MIT" }, + "node_modules/http-signature": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.3.1.tgz", + "integrity": "sha512-Y29YKEc8MQsjch/VzkUVJ+2MXd9WcR42fK5u36CZf4G8bXw2DXMTWuESiB0R6m59JAWxlPPw5/Fri/t/AyyueA==", + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.14.1" + }, + "engines": { + "node": ">=0.10" + } + }, "node_modules/https-proxy-agent": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", @@ -2614,6 +2747,36 @@ "dev": true, "license": "ISC" }, + "node_modules/isomorphic-fetch": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-3.0.0.tgz", + "integrity": "sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.6.1", + "whatwg-fetch": "^3.4.1" + } + }, + "node_modules/isomorphic-fetch/node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, "node_modules/joycon": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", @@ -2624,6 +2787,12 @@ "node": ">=10" } }, + "node_modules/jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==", + "license": "MIT" + }, "node_modules/json-bigint": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", @@ -2633,6 +2802,12 @@ "bignumber.js": "^9.0.0" } }, + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", + "license": "(AFL-2.1 OR BSD-3-Clause)" + }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", @@ -2647,6 +2822,52 @@ "dev": true, "license": "MIT" }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", + "license": "MIT", + "dependencies": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/jssha": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jssha/-/jssha-3.3.1.tgz", + "integrity": "sha512-VCMZj12FCFMQYcFLPRm/0lOBbLi8uM2BhXPTqw3U4YAfs4AZfiApOoBLoN8cQE60Z50m1MYMTQVCfgF/KaCVhQ==", + "license": "BSD-3-Clause", + "engines": { + "node": "*" + } + }, "node_modules/jwa": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", @@ -2717,6 +2938,48 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, "node_modules/long": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", @@ -2871,6 +3134,58 @@ "url": "https://opencollective.com/node-fetch" } }, + "node_modules/oci-common": { + "version": "2.146.0", + "resolved": "https://registry.npmjs.org/oci-common/-/oci-common-2.146.0.tgz", + "integrity": "sha512-aKGR5aq/0I08G6pkKx3dmDPgMhSDLgpw1z0m7TFf9LVyv12PYhmIlgpYfQ4kbqAbgzgEghIx+HiI0GSpSozbXg==", + "license": "(UPL-1.0 OR Apache-2.0)", + "dependencies": { + "@types/isomorphic-fetch": "0.0.35", + "@types/jsonwebtoken": "9.0.3", + "@types/opossum": "4.1.1", + "@types/sshpk": "1.10.3", + "@types/uuid": "8.3.4", + "es6-promise": "4.2.6", + "http-signature": "1.3.1", + "isomorphic-fetch": "3.0.0", + "jsonwebtoken": "9.0.3", + "jssha": "3.3.1", + "node-fetch": "2.7.0", + "opossum": "5.0.1", + "sshpk": "1.18.0", + "uuid": "11.1.1" + } + }, + "node_modules/oci-common/node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/oci-secrets": { + "version": "2.146.0", + "resolved": "https://registry.npmjs.org/oci-secrets/-/oci-secrets-2.146.0.tgz", + "integrity": "sha512-sWrjx69nJuyUbrfGBmbLEn88Mnkog2JSGIGverioV1sWVyxs5vhkEUGbEYmWmKrDoZoRjMkpjIAQcd6VqVsl8w==", + "license": "(UPL-1.0 OR Apache-2.0)", + "dependencies": { + "oci-common": "2.146.0", + "opossum": "5.0.1" + } + }, "node_modules/on-exit-leak-free": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", @@ -2890,6 +3205,15 @@ "wrappy": "1" } }, + "node_modules/opossum": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/opossum/-/opossum-5.0.1.tgz", + "integrity": "sha512-iUDUQmFl3RanaBVLMDTZ6WtXj/Hk84pwJ5JWoJaQd1lXGifdApHhszI3biZvdBDdpTERCmB6x+7+uNvzhzVZIg==", + "license": "Apache-2.0", + "engines": { + "node": ">= 10" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -3288,6 +3612,12 @@ "node": ">=10" } }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, "node_modules/secure-json-parse": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.1.tgz", @@ -3408,6 +3738,31 @@ "node": ">= 10.x" } }, + "node_modules/sshpk": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.18.0.tgz", + "integrity": "sha512-2p2KJZTSqQ/I3+HX42EpYOa2l3f8Erv8MWKsy2I9uf4wA7yFIkXRffYdsx86y6z4vHtV8u7g+pPlr8/4ouAxsQ==", + "license": "MIT", + "dependencies": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + }, + "bin": { + "sshpk-conv": "bin/sshpk-conv", + "sshpk-sign": "bin/sshpk-sign", + "sshpk-verify": "bin/sshpk-verify" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/strip-json-comments": { "version": "5.0.3", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz", @@ -3481,6 +3836,12 @@ "url": "https://github.com/sponsors/Borewit" } }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -3519,6 +3880,12 @@ "fsevents": "~2.3.3" } }, + "node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==", + "license": "Unlicense" + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -3598,6 +3965,33 @@ "punycode": "^2.1.0" } }, + "node_modules/uuid": { + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==", + "engines": [ + "node >=0.6.0" + ], + "license": "MIT", + "dependencies": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, "node_modules/web-streams-polyfill": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", @@ -3607,12 +4001,34 @@ "node": ">= 8" } }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, "node_modules/whatsapp-rust-bridge": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/whatsapp-rust-bridge/-/whatsapp-rust-bridge-0.5.4.tgz", "integrity": "sha512-yYO1qSs0Fe7tGtnxOFHomocUD6IZtoAgmA4oDFyGIRZ67D3QZk3w7swA6XXFXNQngiyrg2k7tul6IrM3eUFh7A==", "license": "MIT" }, + "node_modules/whatwg-fetch": { + "version": "3.6.20", + "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.6.20.tgz", + "integrity": "sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg==", + "license": "MIT" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index f34bffa..f63d38d 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "better-sqlite3": "13.0.3", "dotenv": "18.0.7", "node-cron": "4.6.0", + "oci-secrets": "2.146.0", "pino": "9.14.0", "playwright": "1.64.1", "qrcode-terminal": "0.12.0", diff --git a/src/config/env.ts b/src/config/env.ts index 394d667..e333f70 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -62,6 +62,10 @@ const envSchema = z VU_LMS_SYNC: booleanFlag('false'), VU_STUDENT_ID: z.string().trim().default(''), VU_PASSWORD: z.string().default(''), + NFC_CMS_SYNC: booleanFlag('false'), + NFC_SYNC_CRON: cronExpression('0 7 * * *'), + NFC_STUDENT_ID_SECRET_OCID: z.string().trim().default(''), + NFC_PASSWORD_SECRET_OCID: z.string().trim().default(''), MAX_REPLIES_PER_HOUR: positiveInteger(20), DATABASE_PATH: z.string().trim().min(1).default('./data/maya.db'), AUTH_DIR: z.string().trim().min(1).default('./auth_info'), @@ -81,6 +85,9 @@ const envSchema = z if (value.VU_LMS_SYNC && (!value.VU_STUDENT_ID || !value.VU_PASSWORD)) { context.addIssue({ code: 'custom', path: ['VU_LMS_SYNC'], message: 'requires VU_STUDENT_ID and VU_PASSWORD' }); } + if (value.NFC_CMS_SYNC && (!value.NFC_STUDENT_ID_SECRET_OCID || !value.NFC_PASSWORD_SECRET_OCID)) { + context.addIssue({ code: 'custom', path: ['NFC_CMS_SYNC'], message: 'requires NFC_STUDENT_ID_SECRET_OCID and NFC_PASSWORD_SECRET_OCID' }); + } }); const result = envSchema.safeParse(process.env); diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 33b9f6c..5b6bb32 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -6,7 +6,7 @@ const schema = readFileSync(new URL('./schema.sql', import.meta.url), 'utf8'); export function migrate(): void { db.transaction(() => { const version = Number(db.pragma('user_version', { simple: true })); - if (version > 2) throw new Error(`Database schema version ${version} is newer than this Maya build`); + if (version > 3) throw new Error(`Database schema version ${version} is newer than this Maya build`); const hadMessageFts = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'").get()); db.exec(schema); if (!hadMessageFts) db.exec("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')"); @@ -22,6 +22,6 @@ export function migrate(): void { if (dialogueColumns.length > 0 && !dialogueColumns.some(({ name }) => name === 'answer_ref')) { db.exec('ALTER TABLE owner_dialogue ADD COLUMN answer_ref TEXT'); } - if (version < 2) db.pragma('user_version = 2'); + if (version < 3) db.pragma('user_version = 3'); })(); } diff --git a/src/db/schema.sql b/src/db/schema.sql index bd5bd50..a27f559 100644 --- a/src/db/schema.sql +++ b/src/db/schema.sql @@ -177,6 +177,28 @@ CREATE TABLE IF NOT EXISTS source_sync_state ( last_failure_at TEXT ); +-- LMS checks can be paused independently without deleting imported assignment records. +CREATE TABLE IF NOT EXISTS source_controls ( + source TEXT PRIMARY KEY, + checking_paused INTEGER NOT NULL DEFAULT 0 CHECK (checking_paused IN (0, 1)), + reminders_paused INTEGER NOT NULL DEFAULT 0 CHECK (reminders_paused IN (0, 1)), + updated_at TEXT NOT NULL +); + +-- NFC portal metadata stays separate from a generic reminder task. +CREATE TABLE IF NOT EXISTS nfc_assignments ( + assignment_id TEXT PRIMARY KEY, + task_id INTEGER UNIQUE REFERENCES tasks(id) ON DELETE SET NULL, + course_code TEXT NOT NULL, + portal_status TEXT NOT NULL, + marks TEXT, + portal_url TEXT NOT NULL, + last_seen_at TEXT NOT NULL, + submitted_at TEXT, + submission_receipt TEXT +); +CREATE INDEX IF NOT EXISTS idx_nfc_assignments_status ON nfc_assignments(portal_status, last_seen_at); + CREATE TABLE IF NOT EXISTS calendar_jobs ( task_id INTEGER PRIMARY KEY REFERENCES tasks(id) ON DELETE CASCADE, revision INTEGER NOT NULL DEFAULT 1 diff --git a/src/security/oci-vault.ts b/src/security/oci-vault.ts new file mode 100644 index 0000000..9b10d46 --- /dev/null +++ b/src/security/oci-vault.ts @@ -0,0 +1,19 @@ +import * as common from 'oci-common'; +import { SecretsClient } from 'oci-secrets'; + +/** Retrieves one OCI Vault secret using the VM's instance principal, never a user key. */ +export async function readOciVaultSecret(secretId: string): Promise { + if (!/^ocid1\.vaultsecret\./u.test(secretId)) throw new Error('Invalid OCI Vault secret OCID'); + const provider = await new common.InstancePrincipalsAuthenticationDetailsProviderBuilder().build(); + const client = new SecretsClient({ authenticationDetailsProvider: provider }); + try { + const response = await client.getSecretBundle({ secretId }); + const content = response.secretBundle.secretBundleContent?.content; + if (!content) throw new Error('OCI Vault returned an empty secret'); + const value = Buffer.from(content, 'base64').toString('utf8').trim(); + if (!value) throw new Error('OCI Vault returned an empty secret'); + return value; + } finally { + client.close(); + } +} diff --git a/src/sources/nfc/lms.ts b/src/sources/nfc/lms.ts new file mode 100644 index 0000000..9bb15df --- /dev/null +++ b/src/sources/nfc/lms.ts @@ -0,0 +1,83 @@ +import { chromium, type Page } from 'playwright'; +import { localDateTimeToUtc } from '../../utils/time.js'; + +const LOGIN_URL = 'https://www.cms.nfciet.com/login'; +const ASSIGNMENTS_URL = 'https://www.cms.nfciet.com/student/assignments'; +const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +export interface NfcAssignment { + externalId: string; + course: string; + title: string; + marks: string | null; + dueAt: string; + status: 'open' | 'submitted' | 'reviewing' | 'graded' | 'expired' | 'unknown'; + portalUrl: string; +} + +export interface NfcCredentials { studentId: string; password: string } + +function normalizedStatus(value: string): NfcAssignment['status'] { + const input = value.toLocaleLowerCase(); + if (input.includes('expired') || input.includes('closed')) return 'expired'; + if (input.includes('submitted')) return 'submitted'; + if (input.includes('review')) return 'reviewing'; + if (input.includes('graded')) return 'graded'; + if (input.includes('open') || input.includes('pending') || input.includes('active')) return 'open'; + return 'unknown'; +} + +export function parseNfcDueDate(value: string): string { + const match = /^(\d{1,2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}), (\d{1,2}):(\d{2}) (AM|PM)$/u.exec(value.trim()); + if (!match) throw new Error('NFC CMS has an unrecognized assignment deadline'); + const [, rawDay, monthName, year, rawHour, minute, period] = match; + const hour = (Number(rawHour) % 12) + (period === 'PM' ? 12 : 0); + if (Number(rawHour) < 1 || Number(rawHour) > 12 || Number(minute) > 59) throw new Error('NFC CMS has an invalid assignment deadline'); + return localDateTimeToUtc(`${year}-${String(months.indexOf(monthName!) + 1).padStart(2, '0')}-${rawDay!.padStart(2, '0')}`, + `${String(hour).padStart(2, '0')}:${minute}`); +} + +export function parseNfcAssignmentRows(rows: readonly { cells: string[]; href: string | null }[]): NfcAssignment[] { + const ids = new Set(); + return rows.map(({ cells, href }) => { + if (cells.length !== 6 || !href) throw new Error('NFC CMS assignment table layout changed'); + const [title, course, marks, due, status] = cells.map((cell) => cell.trim()); + const id = /\/student\/assignments\/(\d+)$/u.exec(new URL(href).pathname)?.[1]; + if (!id || ids.has(id) || !title || !course) throw new Error('NFC CMS assignment row is invalid'); + ids.add(id); + return { externalId: id, title: title.slice(0, 300), course: course.slice(0, 100), marks: marks || null, + dueAt: parseNfcDueDate(due ?? ''), status: normalizedStatus(status ?? ''), portalUrl: href }; + }); +} + +async function assignmentRows(page: Page): Promise<{ cells: string[]; href: string | null }[]> { + const rows = await page.locator('table tr').all(); + if (rows.length > 501) throw new Error('NFC CMS has too many assignments'); + const result: { cells: string[]; href: string | null }[] = []; + for (const row of rows.slice(1)) { + result.push({ + cells: (await row.locator(':scope > th, :scope > td').allInnerTexts()).map((cell) => cell.trim()), + href: await row.locator('a[href*="/student/assignments/"]').getAttribute('href'), + }); + } + return result; +} + +export async function fetchNfcAssignments(credentials: NfcCredentials): Promise { + const browser = await chromium.launch({ headless: true }); + try { + const page = await browser.newPage({ acceptDownloads: false }); + page.setDefaultTimeout(30_000); + await page.goto(LOGIN_URL, { waitUntil: 'domcontentloaded', timeout: 45_000 }); + if (new URL(page.url()).origin !== new URL(LOGIN_URL).origin) throw new Error('NFC CMS login redirected outside the official site'); + await page.locator('input[name="email"]').fill(credentials.studentId); + await page.locator('input[name="password"]').fill(credentials.password); + await page.locator('button[type="submit"]').click(); + await page.waitForURL((url) => url.pathname === '/student/dashboard', { timeout: 30_000 }); + await page.goto(ASSIGNMENTS_URL, { waitUntil: 'domcontentloaded', timeout: 45_000 }); + if (new URL(page.url()).pathname !== '/student/assignments') throw new Error('NFC CMS assignments page did not open after sign-in'); + return parseNfcAssignmentRows(await assignmentRows(page)); + } finally { + await browser.close(); + } +} diff --git a/tests/nfc-lms.test.mjs b/tests/nfc-lms.test.mjs new file mode 100644 index 0000000..6af1d59 --- /dev/null +++ b/tests/nfc-lms.test.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +process.env.GEMINI_API_KEY = 'test-key'; +process.env.DATABASE_PATH = ':memory:'; +process.env.BOT_MODE = 'separate'; +process.env.OWNER_JID = '999999999999@s.whatsapp.net'; +process.env.TIMEZONE = 'Asia/Karachi'; + +const { parseNfcAssignmentRows, parseNfcDueDate } = await import('../src/sources/nfc/lms.ts'); + +test('parses NFC CMS assignment rows with Pakistan-time deadlines and stable portal IDs', () => { + const items = parseNfcAssignmentRows([{ + cells: ['Assignment 2', 'AI-312', '10.00', '17 Oct 2026, 02:56 PM', 'Open', 'View'], + href: 'https://www.cms.nfciet.com/student/assignments/68', + }]); + assert.deepEqual(items, [{ + externalId: '68', course: 'AI-312', title: 'Assignment 2', marks: '10.00', + dueAt: '2026-10-17T09:56:00.000Z', status: 'open', + portalUrl: 'https://www.cms.nfciet.com/student/assignments/68', + }]); +}); + +test('rejects NFC deadline or table changes instead of guessing', () => { + assert.throws(() => parseNfcDueDate('tomorrow sometime'), /unrecognized assignment deadline/); + assert.throws(() => parseNfcAssignmentRows([{ + cells: ['Assignment', 'AI-312'], href: 'https://www.cms.nfciet.com/student/assignments/68', + }]), /table layout changed/); +}); From e93b98148de22f366c28d355c65596e80845d994 Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Sun, 15 Nov 2026 07:28:10 +0500 Subject: [PATCH 2/7] feat: sync NFC CMS assignments --- src/features/nfc.ts | 28 +++++++++++++++++ src/scheduler/jobs.ts | 26 ++++++++++++++++ src/sources/nfc/assignments.ts | 48 +++++++++++++++++++++++++++++ src/sources/nfc/lms.ts | 9 ++++-- tests/nfc-lms.test.mjs | 7 +++++ tests/nfc-scheduler.test.mjs | 40 +++++++++++++++++++++++++ tests/nfc-sync.test.mjs | 55 ++++++++++++++++++++++++++++++++++ 7 files changed, 211 insertions(+), 2 deletions(-) create mode 100644 src/features/nfc.ts create mode 100644 src/sources/nfc/assignments.ts create mode 100644 tests/nfc-scheduler.test.mjs create mode 100644 tests/nfc-sync.test.mjs diff --git a/src/features/nfc.ts b/src/features/nfc.ts new file mode 100644 index 0000000..857de48 --- /dev/null +++ b/src/features/nfc.ts @@ -0,0 +1,28 @@ +import { config } from '../config/env.js'; +import { db } from '../db/client.js'; +import { universityCheckingPaused } from '../db/repos/source-controls.js'; +import { readOciVaultSecret } from '../security/oci-vault.js'; +import { upsertNfcAssignments } from '../sources/nfc/assignments.js'; +import { fetchNfcAssignments, type NfcCredentials } from '../sources/nfc/lms.js'; + +export async function syncNfcAssignments( + readSecret: typeof readOciVaultSecret = readOciVaultSecret, + fetchAssignments: typeof fetchNfcAssignments = fetchNfcAssignments, + apply: typeof upsertNfcAssignments = upsertNfcAssignments, +): Promise<{ created: number; updated: number; unchanged: number; skipped: boolean }> { + if (universityCheckingPaused('nfc-cms')) return { created: 0, updated: 0, unchanged: 0, skipped: true }; + try { + const credentials: NfcCredentials = { + studentId: await readSecret(config.NFC_STUDENT_ID_SECRET_OCID), + password: await readSecret(config.NFC_PASSWORD_SECRET_OCID), + }; + const result = apply(await fetchAssignments(credentials)); + db.prepare(`INSERT INTO source_sync_state (source, last_success_at, last_failure_at) VALUES ('nfc-cms', ?, NULL) + ON CONFLICT(source) DO UPDATE SET last_success_at = excluded.last_success_at, last_failure_at = NULL`).run(new Date().toISOString()); + return { ...result, skipped: false }; + } catch (error) { + db.prepare(`INSERT INTO source_sync_state (source, last_failure_at) VALUES ('nfc-cms', ?) + ON CONFLICT(source) DO UPDATE SET last_failure_at = excluded.last_failure_at`).run(new Date().toISOString()); + throw error; + } +} diff --git a/src/scheduler/jobs.ts b/src/scheduler/jobs.ts index 25b7848..e8c426d 100644 --- a/src/scheduler/jobs.ts +++ b/src/scheduler/jobs.ts @@ -8,6 +8,7 @@ import { extractOnce } from '../features/extract.js'; import { processPendingMedia } from '../features/media.js'; import { runWeeklyPlan } from '../features/weeklyPlan.js'; import { syncVuClassicTodo } from '../features/vu.js'; +import { syncNfcAssignments } from '../features/nfc.js'; import { sendToOwner } from '../channels/whatsapp/send.js'; import { logger } from '../utils/logger.js'; import { cleanupMemories } from '../db/repos/memories.js'; @@ -28,6 +29,7 @@ interface JobDependencies { calendar: typeof syncCalendarOnce; calendarRead: typeof syncUpcomingCalendarEvents; vu: typeof syncVuClassicTodo; + nfc: typeof syncNfcAssignments; schedule: typeof cron.schedule; every: typeof setInterval; clear: typeof clearInterval; @@ -62,6 +64,7 @@ export function startJobs( const calendar = dependencies.calendar ?? syncCalendarOnce; const calendarRead = dependencies.calendarRead ?? syncUpcomingCalendarEvents; const vu = dependencies.vu ?? syncVuClassicTodo; + const nfc = dependencies.nfc ?? syncNfcAssignments; const schedule = dependencies.schedule ?? cron.schedule; const every = dependencies.every ?? setInterval; const clear = dependencies.clear ?? clearInterval; @@ -71,6 +74,7 @@ export function startJobs( }); let extractionRunning = false; let vuRunning = false; + let nfcRunning = false; let stopping = false; let stopWork: Promise | null = null; const pending = new Set>(); @@ -139,6 +143,19 @@ export function startJobs( vuRunning = false; } }; + const runNfc = async () => { + if (stopping || nfcRunning) return; + nfcRunning = true; + try { + const counts = await nfc(); + logger.info({ ...counts }, 'NFC CMS assignment sync completed'); + } catch (error) { + logger.error({ errorType: error instanceof Error ? error.name : 'unknown' }, 'NFC CMS assignment sync failed'); + await sendToOwner('I couldn’t update your NFC assignment deadlines today. I have not attempted any upload; I’ll try again at the next scheduled check.'); + } finally { + nfcRunning = false; + } + }; const jobs = [ schedule(config.MORNING_DIGEST_CRON, () => runScheduledJob('morning'), { @@ -189,6 +206,15 @@ export function startJobs( name: 'maya-vu-classic-todo', })); } + if (config.NFC_CMS_SYNC) { + jobs.push(schedule(config.NFC_SYNC_CRON, () => { + if (!stopping) track(runNfc()); + }, { + timezone: config.TIMEZONE, + noOverlap: true, + name: 'maya-nfc-assignments', + })); + } const extractionTimer = every( () => { if (!stopping) track(runExtraction()); diff --git a/src/sources/nfc/assignments.ts b/src/sources/nfc/assignments.ts new file mode 100644 index 0000000..96c7d2f --- /dev/null +++ b/src/sources/nfc/assignments.ts @@ -0,0 +1,48 @@ +import { db } from '../../db/client.js'; +import { createTask } from '../../db/repos/tasks.js'; +import type { NfcAssignment } from './lms.js'; + +type Change = 'created' | 'updated' | 'unchanged'; + +function upsert(item: NfcAssignment): Change { + const previous = db.prepare<[string], { taskId: number | null; portalStatus: string; dueAt: string | null; title: string; subject: string | null; status: string }>(` + SELECT n.task_id AS taskId, n.portal_status AS portalStatus, t.due_at AS dueAt, t.title, t.subject, t.status + FROM nfc_assignments n LEFT JOIN tasks t ON t.id = n.task_id WHERE n.assignment_id = ? + `).get(item.externalId); + const now = new Date().toISOString(); + if (!previous?.taskId) { + const taskId = createTask({ type: 'assignment', subject: item.course, title: item.title, dueAt: item.dueAt }); + if (item.status === 'expired') { + db.prepare("UPDATE tasks SET status = 'expired', updated_at = ? WHERE id = ?").run(now, taskId); + } else if (item.status === 'submitted' || item.status === 'reviewing' || item.status === 'graded') { + db.prepare("UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ?").run(now, taskId); + } + db.prepare("INSERT INTO source_tasks (source, external_id, task_id) VALUES ('nfc-cms', ?, ?)").run(item.externalId, taskId); + db.prepare(`INSERT INTO nfc_assignments + (assignment_id, task_id, course_code, portal_status, marks, portal_url, last_seen_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`) + .run(item.externalId, taskId, item.course, item.status, item.marks, item.portalUrl, now); + return 'created'; + } + const changed = previous.portalStatus !== item.status || previous.dueAt !== item.dueAt || + previous.title !== item.title || previous.subject !== item.course; + if (previous.status === 'open') { + if (item.status === 'expired') db.prepare("UPDATE tasks SET status = 'expired', updated_at = ? WHERE id = ? AND status = 'open'").run(now, previous.taskId); + else if (item.status === 'submitted' || item.status === 'reviewing' || item.status === 'graded') + db.prepare("UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'open'").run(now, previous.taskId); + else db.prepare(`UPDATE tasks SET subject = ?, title = ?, due_at = ?, reminded_morning = CASE WHEN due_at IS NOT ? THEN 0 ELSE reminded_morning END, + reminded_evening = CASE WHEN due_at IS NOT ? THEN 0 ELSE reminded_evening END, updated_at = ? WHERE id = ? AND status = 'open'`) + .run(item.course, item.title, item.dueAt, item.dueAt, item.dueAt, now, previous.taskId); + } + db.prepare(`UPDATE nfc_assignments SET course_code = ?, portal_status = ?, marks = ?, portal_url = ?, last_seen_at = ? + WHERE assignment_id = ?`).run(item.course, item.status, item.marks, item.portalUrl, now, item.externalId); + return changed ? 'updated' : 'unchanged'; +} + +export function upsertNfcAssignments(items: NfcAssignment[]): { created: number; updated: number; unchanged: number } { + return db.transaction(() => { + const counts = { created: 0, updated: 0, unchanged: 0 }; + for (const item of items) counts[upsert(item)] += 1; + return counts; + })(); +} diff --git a/src/sources/nfc/lms.ts b/src/sources/nfc/lms.ts index 9bb15df..1e605c5 100644 --- a/src/sources/nfc/lms.ts +++ b/src/sources/nfc/lms.ts @@ -24,7 +24,9 @@ function normalizedStatus(value: string): NfcAssignment['status'] { if (input.includes('review')) return 'reviewing'; if (input.includes('graded')) return 'graded'; if (input.includes('open') || input.includes('pending') || input.includes('active')) return 'open'; - return 'unknown'; + // A new label may mean the portal changed its lifecycle. Do not guess that an + // assignment is actionable and create a reminder from an unfamiliar state. + throw new Error('NFC CMS has an unrecognized assignment status'); } export function parseNfcDueDate(value: string): string { @@ -75,7 +77,10 @@ export async function fetchNfcAssignments(credentials: NfcCredentials): Promise< await page.locator('button[type="submit"]').click(); await page.waitForURL((url) => url.pathname === '/student/dashboard', { timeout: 30_000 }); await page.goto(ASSIGNMENTS_URL, { waitUntil: 'domcontentloaded', timeout: 45_000 }); - if (new URL(page.url()).pathname !== '/student/assignments') throw new Error('NFC CMS assignments page did not open after sign-in'); + const assignmentsUrl = new URL(page.url()); + if (assignmentsUrl.origin !== new URL(LOGIN_URL).origin || assignmentsUrl.pathname !== '/student/assignments') { + throw new Error('NFC CMS assignments page did not open after sign-in'); + } return parseNfcAssignmentRows(await assignmentRows(page)); } finally { await browser.close(); diff --git a/tests/nfc-lms.test.mjs b/tests/nfc-lms.test.mjs index 6af1d59..4a99059 100644 --- a/tests/nfc-lms.test.mjs +++ b/tests/nfc-lms.test.mjs @@ -27,3 +27,10 @@ test('rejects NFC deadline or table changes instead of guessing', () => { cells: ['Assignment', 'AI-312'], href: 'https://www.cms.nfciet.com/student/assignments/68', }]), /table layout changed/); }); + +test('rejects an unfamiliar NFC assignment lifecycle', () => { + assert.throws(() => parseNfcAssignmentRows([{ + cells: ['Assignment', 'AI-312', '10', '17 Oct 2026, 02:56 PM', 'Waiting for faculty', 'View'], + href: 'https://www.cms.nfciet.com/student/assignments/68', + }]), /unrecognized assignment status/); +}); diff --git a/tests/nfc-scheduler.test.mjs b/tests/nfc-scheduler.test.mjs new file mode 100644 index 0000000..660f17d --- /dev/null +++ b/tests/nfc-scheduler.test.mjs @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +process.env.GEMINI_API_KEY = 'test'; +process.env.BOT_MODE = 'separate'; +process.env.OWNER_JID = '123@s.whatsapp.net'; +process.env.DATABASE_PATH = ':memory:'; +process.env.NFC_CMS_SYNC = 'true'; +process.env.NFC_STUDENT_ID_SECRET_OCID = 'ocid1.vaultsecret.oc1.ap-singapore-1.teststudent'; +process.env.NFC_PASSWORD_SECRET_OCID = 'ocid1.vaultsecret.oc1.ap-singapore-1.testpassword'; +process.env.NFC_SYNC_CRON = '0 7 * * *'; + +const { startJobs } = await import('../src/scheduler/jobs.ts'); + +test('daily NFC check uses the timezone, does not overlap, and stops cleanly', async () => { + const registrations = []; + let runs = 0; + let finish; + const stop = startJobs({ + nfc: async () => { + runs++; + return new Promise((resolve) => { finish = resolve; }); + }, + schedule: (expression, callback, options) => { + registrations.push({ expression, callback, options }); + return { stop: () => undefined }; + }, + every: () => 1, + clear: () => undefined, + }); + const nfc = registrations.find(({ options }) => options.name === 'maya-nfc-assignments'); + assert.equal(nfc.expression, '0 7 * * *'); + assert.equal(nfc.options.timezone, 'Asia/Karachi'); + assert.equal(nfc.options.noOverlap, true); + nfc.callback(); + nfc.callback(); + assert.equal(runs, 1); + finish({ created: 1, updated: 0, unchanged: 0, skipped: false }); + await stop(); +}); diff --git a/tests/nfc-sync.test.mjs b/tests/nfc-sync.test.mjs new file mode 100644 index 0000000..63cf312 --- /dev/null +++ b/tests/nfc-sync.test.mjs @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +process.env.GEMINI_API_KEY = 'test-key'; +process.env.DATABASE_PATH = ':memory:'; +process.env.BOT_MODE = 'separate'; +process.env.OWNER_JID = '999999999999@s.whatsapp.net'; + +const { db } = await import('../src/db/client.ts'); +const { migrate } = await import('../src/db/migrate.ts'); +const { setUniversityCheckingPaused } = await import('../src/db/repos/source-controls.ts'); +const { syncNfcAssignments } = await import('../src/features/nfc.ts'); +migrate(); + +const active = [{ + externalId: '68', course: 'AI-312', title: 'Assignment 2', marks: '10.00', dueAt: '2027-01-17T09:56:00.000Z', + status: 'open', portalUrl: 'https://www.cms.nfciet.com/student/assignments/68', +}]; + +test('NFC sync imports an assignment and records source state without retaining credentials', async () => { + const result = await syncNfcAssignments( + async (id) => id.includes('STUDENT') ? 'student@example.test' : 'private-password', + async () => active, + ); + assert.deepEqual(result, { created: 1, updated: 0, unchanged: 0, skipped: false }); + assert.deepEqual(db.prepare('SELECT subject, title, status FROM tasks').get(), { + subject: 'AI-312', title: 'Assignment 2', status: 'open', + }); + assert.deepEqual(db.prepare('SELECT assignment_id AS assignmentId, portal_status AS portalStatus FROM nfc_assignments').get(), { + assignmentId: '68', portalStatus: 'open', + }); +}); + +test('pausing NFC prevents Vault and portal access while preserving known assignments', async () => { + setUniversityCheckingPaused('nfc-cms', true); + const result = await syncNfcAssignments( + async () => { throw new Error('Vault must not be called while paused'); }, + async () => { throw new Error('Portal must not be called while paused'); }, + ); + assert.deepEqual(result, { created: 0, updated: 0, unchanged: 0, skipped: true }); + assert.equal(db.prepare('SELECT COUNT(*) AS n FROM nfc_assignments').get().n, 1); + setUniversityCheckingPaused('nfc-cms', false); +}); + +test('a portal-reported submission stops future task reminders', async () => { + await syncNfcAssignments(async () => 'ignored', async () => [{ ...active[0], status: 'submitted' }]); + assert.equal(db.prepare('SELECT status FROM tasks').get().status, 'done'); +}); + +test('already expired portal assignments are stored without creating a reminder task', async () => { + await syncNfcAssignments(async () => 'ignored', async () => [{ + ...active[0], externalId: '69', title: 'Expired assignment', status: 'expired', + }]); + assert.deepEqual(db.prepare("SELECT status FROM tasks WHERE title = 'Expired assignment'").get(), { status: 'expired' }); +}); From 5a61ce16e3b87c30ad61b07ffe8c407a09473414 Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Sun, 15 Nov 2026 07:28:16 +0500 Subject: [PATCH 3/7] feat: control university deadline checks --- src/db/repos/source-controls.ts | 16 ++++++++++++++++ src/features/owner-agent.ts | 2 ++ src/features/owner-tools.ts | 21 ++++++++++++++++++++- src/features/vu.ts | 4 ++++ tests/owner-agent.test.mjs | 10 ++++++++++ 5 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/db/repos/source-controls.ts diff --git a/src/db/repos/source-controls.ts b/src/db/repos/source-controls.ts new file mode 100644 index 0000000..d8c2bd5 --- /dev/null +++ b/src/db/repos/source-controls.ts @@ -0,0 +1,16 @@ +import { db } from '../client.js'; + +export type UniversitySource = 'nfc-cms' | 'vu-classic-todo'; + +export function universityCheckingPaused(source: UniversitySource): boolean { + return Boolean(db.prepare<[UniversitySource], { checkingPaused: number }>( + 'SELECT checking_paused AS checkingPaused FROM source_controls WHERE source = ?', + ).get(source)?.checkingPaused); +} + +export function setUniversityCheckingPaused(source: UniversitySource, paused: boolean): void { + db.prepare(`INSERT INTO source_controls (source, checking_paused, reminders_paused, updated_at) + VALUES (?, ?, 0, ?) ON CONFLICT(source) DO UPDATE SET + checking_paused = excluded.checking_paused, updated_at = excluded.updated_at`) + .run(source, paused ? 1 : 0, new Date().toISOString()); +} diff --git a/src/features/owner-agent.ts b/src/features/owner-agent.ts index 28f75ba..e41c71e 100644 --- a/src/features/owner-agent.ts +++ b/src/features/owner-agent.ts @@ -193,6 +193,8 @@ export function handleOwnerControlConfirmation(text: string, sourceRef: string | (args.key === 'MEDIA_ENABLED' && /\bmedia\b/iu.test(said)) : proposal.toolName === 'cancel_reminder' ? /\breminder\b/iu.test(said) && said.includes(String(args.reminderId)) + : proposal.toolName === 'set_university_checking' + ? /\b(?:university|nfc|vu|lms)\b/iu.test(said) : proposal.toolName === 'cleanup_expired_memories' ? /\b(?:expired|temporary)\b/iu.test(said) && /\b(?:memor|clean|clear|delet)/iu.test(said) : false; diff --git a/src/features/owner-tools.ts b/src/features/owner-tools.ts index d74aaae..5dfb2b8 100644 --- a/src/features/owner-tools.ts +++ b/src/features/owner-tools.ts @@ -5,6 +5,7 @@ import { getRuntimeSetting, listRuntimeSettings, resetRuntimeSetting, setRuntime } from '../config/runtime.js'; import { db } from '../db/client.js'; import { getGroupPolicy, listGroupPolicies, setGroupPause, setGroupPolicy } from '../db/repos/group-policies.js'; +import { setUniversityCheckingPaused, universityCheckingPaused, type UniversitySource } from '../db/repos/source-controls.js'; import { clearMemoryIds, expiredTemporaryMemories, listMemories } from '../db/repos/memories.js'; import { markDone } from '../db/repos/tasks.js'; import { cancelOwnerReminder, createOwnerReminder, getOwnerReminder, listOwnerReminders, @@ -58,6 +59,11 @@ const empty = z.object({}).strict(); const settingKey = z.enum(['MEDIA_ENABLED', 'MEDIA_MAX_BYTES', 'MEDIA_BATCH_SIZE', 'EXTRACT_BATCH_SIZE']); const changeableKey = z.enum(['MEDIA_ENABLED', 'MEDIA_BATCH_SIZE', 'EXTRACT_BATCH_SIZE']); const groupArg = z.object({ group: z.string().trim().min(1).max(120) }).strict(); +const universityArg = z.object({ university: z.enum(['nfc', 'vu', 'both']), enabled: z.boolean() }).strict(); + +function selectedUniversities(university: z.output['university']): UniversitySource[] { + return university === 'nfc' ? ['nfc-cms'] : university === 'vu' ? ['vu-classic-todo'] : ['nfc-cms', 'vu-classic-todo']; +} function groupId(nameOrId: string): string { const candidate = nameOrId.trim().replace(/\s+group$/iu, ''); @@ -120,6 +126,19 @@ const registry: OwnerTool[] = [ { revision: ({ key }) => JSON.stringify(getRuntimeSetting(key)), confirm: ({ key }) => key === 'MEDIA_ENABLED', preview: ({ key, value }) => `set ${key} to ${String(value)}` }), + tool('set_university_checking', 'Pause or resume deadline checks for NFC, VU, or both universities. Pausing never deletes known assignments or stops their existing reminders.', 'sensitive', universityArg, + ({ university }) => `university:${university}`, + ({ university, enabled }) => { + const sources = selectedUniversities(university); + sources.forEach((source) => setUniversityCheckingPaused(source, !enabled)); + const label = university === 'both' ? 'NFC and VU' : university.toUpperCase(); + return { message: enabled + ? `${label} deadline checking is back on. Your existing reminders stayed in place.` + : `${label} deadline checking is paused. I kept your existing assignments and reminders.` }; + }, + { revision: ({ university }) => selectedUniversities(university).map((source) => `${source}:${universityCheckingPaused(source)}`).join(','), + confirm: () => true, + preview: ({ university, enabled }) => `${enabled ? 'resume' : 'pause'} ${university === 'both' ? 'NFC and VU' : university.toUpperCase()} deadline checking` }), tool('reset_runtime_setting', 'Remove a non-secret runtime override and restore the deployment default.', 'reversible', z.object({ key: settingKey }).strict(), ({ key }) => key, ({ key }) => ({ message: `${key} is back to its deployment default: ${String(resetRuntimeSetting(key))}.` }), @@ -233,7 +252,7 @@ export function isOwnerControlRequest(text: string): boolean { const input = text.toLocaleLowerCase(); if (/\b(?:whatsapp|my|your)\s+status\b/iu.test(input) && !/\b(?:system|service|settings?|monitoring)\b/iu.test(input)) return false; - return /\b(?:settings?|media\s+(?:reading|limit|size|batch|on|off|band)|(?:enable|disable|turn\s+(?:on|off))\s+media|\d+\s*mb|monitor(?:ing)?|pause|resume|health|queue|cleanup|expired|remind(?:er|ers)?|alert|system\s+status|maya\s+status)\b/iu.test(input) || + return /\b(?:settings?|media\s+(?:reading|limit|size|batch|on|off|band)|(?:enable|disable|turn\s+(?:on|off))\s+media|\d+\s*mb|monitor(?:ing)?|pause|resume|health|queue|cleanup|expired|remind(?:er|ers)?|alert|system\s+status|maya\s+status|(?:nfc|vu|university)\s+(?:checking|check|monitoring))\b/iu.test(input) || (/\bgroups?\b/iu.test(input) && /\b(?:list|show|set|change|pause|resume|stop|start|enable|disable|turn|policy|monitor|reading|off|on)\b/iu.test(input)) || /سیٹنگ|نگرانی|یاد\s*دلاؤ|\b(?:group|media)\s+(?:ko|ki)\s+(?:band|on|off|chalu)\b/iu.test(input); } diff --git a/src/features/vu.ts b/src/features/vu.ts index 184e999..618629e 100644 --- a/src/features/vu.ts +++ b/src/features/vu.ts @@ -1,11 +1,15 @@ import { upsertVuItems } from '../sources/vu/classic-todo.js'; import { fetchClassicTodoItems } from '../sources/vu/lms.js'; import { db } from '../db/client.js'; +import { universityCheckingPaused } from '../db/repos/source-controls.js'; export async function syncVuClassicTodo( fetchItems: typeof fetchClassicTodoItems = fetchClassicTodoItems, apply: typeof upsertVuItems = upsertVuItems, ): Promise<{ created: number; updated: number; unchanged: number }> { + if (universityCheckingPaused('vu-classic-todo')) { + return { created: 0, updated: 0, unchanged: 0 }; + } try { const items = await fetchItems(); const result = apply(items); diff --git a/tests/owner-agent.test.mjs b/tests/owner-agent.test.mjs index dd0be3f..4cfdf96 100644 --- a/tests/owner-agent.test.mjs +++ b/tests/owner-agent.test.mjs @@ -15,6 +15,7 @@ const { runOwnerAgent, handleOwnerControlConfirmation } = await import('../src/f const { getRuntimeSetting } = await import('../src/config/runtime.ts'); const { rememberGroup } = await import('../src/db/repos/groups.ts'); const { getGroupPolicy } = await import('../src/db/repos/group-policies.ts'); +const { universityCheckingPaused } = await import('../src/db/repos/source-controls.ts'); const { listOwnerReminders } = await import('../src/db/repos/owner-reminders.ts'); const { sendDueOwnerReminders } = await import('../src/features/owner-reminders.ts'); const { handleOwnerText } = await import('../src/features/commands.ts'); @@ -107,6 +108,15 @@ test('Urdu cancellation leaves a proposed setting unchanged', async () => { assert.equal(getRuntimeSetting('MEDIA_ENABLED'), false); }); +test('university deadline checks need confirmation and can pause NFC without losing records', async () => { + assert.match(await runOwnerAgent('Pause NFC deadline checking', 'request-nfc-pause', owner, + async () => call('set_university_checking', { university: 'nfc', enabled: false })), /confirm/i); + assert.equal(universityCheckingPaused('nfc-cms'), false); + assert.match(handleOwnerControlConfirmation('yes, pause NFC checking', 'request-nfc-pause-confirm', owner), /paused/i); + assert.equal(universityCheckingPaused('nfc-cms'), true); + assert.equal(universityCheckingPaused('vu-classic-todo'), false); +}); + test('owner reminders send once after their due time and retry a failed send', async () => { const dueAt = new Date(Date.now() + 60_000).toISOString(); assert.match(await runOwnerAgent('Remind me to stretch in a minute', 'request-10', owner, From 83a9dd9e583e5a8466e3d9f61d8cccf4012a3e47 Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Sun, 15 Nov 2026 07:30:07 +0500 Subject: [PATCH 4/7] docs: explain NFC CMS safeguards --- ARCHITECTURE.md | 5 ++-- README.md | 5 +++- docs/HOSTING.md | 2 +- docs/NFC-CMS.md | 57 ++++++++++++++++++++++++++++++++++++++++++ docs/OWNER-CONTROLS.md | 2 +- 5 files changed, 66 insertions(+), 5 deletions(-) create mode 100644 docs/NFC-CMS.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 008060e..1a76b00 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -27,6 +27,7 @@ flowchart TD E --> AI[Gemini, structured JSON] AI --> T[(SQLite: tasks)] VU[VU Classic To Do: optional daily read / manual CSV] --> T + NFC[NFC CMS Assignments: optional daily read] --> T T --> S[Scheduler: morning / evening / weekly] T --> Q Q --> AI @@ -51,10 +52,10 @@ flowchart TD - **One way out.** Only `sendToOwner()` can send messages. This is the main safety rule. - **Loop guard.** Self mode keeps the `🤖 :` prefix and ignores it on input. Separate mode sends plain text and ignores Maya's outgoing messages through `key.fromMe`. - **Status isolation.** In separate mode, Maya marks only the verified owner's Status as viewed and sends a short private comment through `sendToOwner()` when it has readable text, a caption, or supported photo/video media. Status content goes to Gemini for that comment only; it is not stored or used for task extraction or future answers. Photo/video downloads are bounded by `MEDIA_MAX_BYTES`. Unsupported or oversized media without a caption is viewed without a comment. Other people's Status and all other broadcasts are ignored. An alternate PN/LID on a broadcast message never makes it an owner chat. -- **Sources are pluggable.** `Source` owns an input lifecycle and emits normalized items. WhatsApp emits group messages into `messages`; the VU CSV importer and optional daily portal reader normalize only Classic To Do quizzes and assignments and upsert them through the same source ID mapping. The portal reader opens a fresh headless browser for each check and does not retain a login session. +- **Sources are pluggable.** `Source` owns an input lifecycle and emits normalized items. WhatsApp emits group messages into `messages`; the VU CSV importer and optional daily portal reader normalize only Classic To Do quizzes and assignments. The NFC reader normalizes only the owner's Assignment-list rows through their stable portal ID. Both portal readers open a fresh headless browser for each check and do not retain a login session. NFC credentials are read from OCI Vault through the VM instance principal, never from SQLite or Gemini context. Unknown portal layouts or assignment states fail closed. NFC upload/submission is not implemented. - **Owner memory.** Deliberately saved facts live in `memory_items`, separate from group history and deadline tasks. Lifecycle rules distinguish permanent, semi-permanent with review dates, and temporary with a due/expiry/completion anchor plus seven-day grace. `memory_fts` indexes titles and bodies; structured filters and IDs take precedence. The ask prompt includes at most eight relevant memories. A daily 03:00 local job marks semi-permanent records for review and cleans eligible temporary records. In separate mode, only verified owner text or transcribed voice can request a change; Gemini classifies the request, while application code validates retention, resolves the named target, and performs the write. Destructive operations use owner-bound, short-lived, single-use database confirmations. `/memory` and `/timetable` are optional shortcuts; developer controls start with `/debug`. - **Timetable versions.** An owner image/PDF is parsed into a typed `timetable_versions` draft and `timetable_entries`; the bounded original bytes are discarded. The owner can inspect/correct rows and confirm. A transaction archives the previous active version and activates the new one only after required day/time/subject validation. Old versions remain in SQLite until explicit deletion. Existing group media extraction and task reminders are unchanged. -- **Owner controls.** In separate mode, a verified owner message or transcribed voice note may enter a bounded manual Gemini function-calling loop. Gemini proposes only registered tools; `owner-tools.ts` validates inputs, owner scope, exact group targets, risk, and outputs before code executes them. Image/PDF descriptions use question answering without tools. The loop has three model turns, six tool calls, a 45-second overall deadline, and serial execution. SQLite stores only allowlisted non-secret setting overrides, per-group policies, scoped single-use confirmations, operation receipts, private reminders, and metadata-only audit records. `.env` remains the source of deployment defaults and secrets. The existing `sendToOwner()` boundary remains the only message sender. See [owner controls](docs/OWNER-CONTROLS.md). +- **Owner controls.** In separate mode, a verified owner message or transcribed voice note may enter a bounded manual Gemini function-calling loop. Gemini proposes only registered tools; `owner-tools.ts` validates inputs, owner scope, exact group targets, risk, and outputs before code executes them. Image/PDF descriptions use question answering without tools. The loop has three model turns, six tool calls, a 45-second overall deadline, and serial execution. SQLite stores only allowlisted non-secret setting overrides, per-group policies, source-check pause controls, scoped single-use confirmations, operation receipts, private reminders, and metadata-only audit records. `.env` remains the source of deployment defaults and secret *references*; NFC secret values remain in OCI Vault. The existing `sendToOwner()` boundary remains the only message sender. See [owner controls](docs/OWNER-CONTROLS.md). - **Unified private context.** In separate mode, `context.ts` selects matching messages through SQLite FTS5 and source filters, then adds a bounded number of relevant tasks, memories, timetable rows, reminders and enabled Calendar events. Group membership and retrieval policy are enforced in SQL before any text reaches Gemini. Source and timestamps remain attached; a 14,000-character evidence cap limits prompt growth. Three short owner Q&A turns are kept for 48 hours to resolve follow-up references. Self mode keeps its earlier ask path. See [Phase 3 behavior](docs/PHASE3.md). - **Reply-aware continuity and owner media updates.** In separate mode, a reply to Maya's own WhatsApp message links the exact recent private turn into the bounded answer context; otherwise the last three turns provide short follow-up context. An owner media/text request to correct academic tasks creates a 15-minute, owner-bound structured preview. The model proposes fields but never task IDs or writes; code resolves targets, detects ambiguity, rechecks task state and applies only confirmed clear changes transactionally. Owner update events keep a WhatsApp source reference without replacing group-message provenance. - **Completion versus expiry.** Natural completion resolves one open or recently expired task by title, subject/course and recent discussion. An ambiguous choice is owner-bound in SQLite for ten minutes and uses numbered *choices*, not task IDs. Scheduled work changes passed open deadlines to `expired`, not `done`; the owner can still mark an expired item done. A VU reschedule can reopen its source task with a future date; a group reschedule additionally needs the same course and title in its source message. Expiry queues Calendar removal through the task-status trigger. diff --git a/README.md b/README.md index cdea0f8..37ceded 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Your personal WhatsApp assistant that never misses a deadline.** -**Development status:** Core and Phases 2–5 are implemented. The separate-number assistant now selects bounded, relevant context for private answers and can carry a short follow-up across a restart. Media reading, Google Calendar, and daily VU Classic To Do checks require opt-in setup. Live VU login and import have been verified; the next unattended daily run still needs confirmation. The live Calendar check remains with the owner. +**Development status:** Core and Phases 2–5 are implemented. The separate-number assistant now selects bounded, relevant context for private answers and can carry a short follow-up across a restart. Media reading, Google Calendar, daily VU Classic To Do checks, and read-only NFC-IET CMS assignment checks require opt-in setup. NFC uploads are deliberately not enabled yet. If you're in a busy WhatsApp group (a class, a course, a team, a community), you know the problem: the important stuff gets buried. A quiz date is posted at 11 PM, someone changes the room the next morning, and by Friday it's lost under 200 messages of "ok" and "thanks". You find out the deadline was yesterday. @@ -23,6 +23,7 @@ Maya fixes that. On her own number, she quietly reads every group she has joined - 🎛️ **Lets you manage safe settings privately** in separate mode: ask for current settings, a media limit up to 10 MB, group monitoring rules, or a personal reminder. Maya previews sensitive changes and waits for your confirmation. See [owner controls](docs/OWNER-CONTROLS.md). - 👀 **Views only your WhatsApp Status** in separate mode and sends you a short private comment when she can read its text, caption, photo, or supported video. She does not store Status content or turn it into tasks, and ignores other people's Status updates. Photo and video comments send the media to Gemini and use the configured `MEDIA_MAX_BYTES` limit, independently of `MEDIA_ENABLED` (which controls group and direct owner media). Unsupported or oversized Status media without a caption is viewed without a comment. - 📚 **Tracks VU Classic To Do deadlines** for quizzes and assignments through an optional daily portal check or a manual CSV import. +- 🎓 **Tracks NFC-IET CMS assignments** through an optional read-only daily portal check. It never uploads or submits coursework automatically. - 📅 **Connects to Google Calendar** when authorized: Maya creates events for her dated tasks, reads upcoming meetings, answers questions about them, and reminds you once on the day of events whose title contains `important`. - 🔒 **Runs on your own machine.** Messages and tasks are stored locally in SQLite; joined group text is sent to Gemini for analysis in separate mode. - 💸 **API costs depend on your Gemini plan and usage.** Check your model's pricing and set a budget alert before leaving Maya running. @@ -83,6 +84,8 @@ Google Calendar sync is optional. To enable it, follow [the Calendar setup guide VU students can enable an optional daily check of only the assignment and quiz tables in Classic To Do, or continue using the manual CSV importer. Follow [the VU setup guide](docs/VU-CLASSIC-TODO.md). The automatic check requires private LMS credentials and a Chromium browser on the host; Maya does not read bell, notice-board, or GDB items. +NFC-IET students can enable a read-only daily Assignment-page check with credentials held in OCI Vault. Follow [the NFC CMS guide](docs/NFC-CMS.md). Maya records verified portal deadlines and states, but has no file-upload or submission feature. + For an always-on host, see the [hosting guide](docs/HOSTING.md). It covers the current systemd setup and optional PM2 or Docker deployments with persistent private storage. To save a consistent SQLite snapshot while Maya is running, use `npm run backup-db`. It keeps the newest seven completed snapshots in `data/backups/`. These backups contain private group messages, tasks, and saved memories, so keep them private. Backups on the same disk do not protect against loss of the machine; off-machine backup automation is deferred. diff --git a/docs/HOSTING.md b/docs/HOSTING.md index 2a6be75..189bfe3 100644 --- a/docs/HOSTING.md +++ b/docs/HOSTING.md @@ -75,4 +75,4 @@ Maya sends selected group text and chosen media to Gemini for extraction. The SQ Maya currently reads `/opt/maya-assistant/.env` at startup. From your authorized laptop, connect with `ssh -i ~/.ssh/id_ed25519 ubuntu@`, then use `sudoedit /opt/maya-assistant/.env` on the VM. Restore ownership and permissions with `sudo chown maya:maya /opt/maya-assistant/.env` and `sudo chmod 600 /opt/maya-assistant/.env`; restart with `sudo systemctl restart maya`. Check `sudo systemctl status maya` and `sudo journalctl -u maya -n 30 --no-pager` for configuration errors. The values are listed in [`.env.example`](../.env.example): the Gemini key, optional Google OAuth tokens, and optional VU LMS password are sensitive; owner JID, groups and schedules are configuration. WhatsApp `auth_info/` and SQLite `data/` stay on persistent private disk, not in Vault. Do not paste keys into chat, commit `.env`, or copy it to a public location. Manual VU CSV imports require no LMS password; the optional daily portal check does. -If you want to edit secrets in the **Oracle Cloud Console**, OCI Vault is the future path: create a standard virtual vault and a software-protected key, store each key as a secret, then give the VM a narrowly scoped instance principal permission to read only those secrets. Add a VM startup retrieval step to put current values into Maya's private environment and restart Maya after changing a secret version in the Console. This repository does **not** yet fetch Vault secrets; changing a Vault value alone will not change the running service. Check [Oracle's Always Free Vault limits](https://docs.oracle.com/en-us/iaas/Content/FreeTier/freetier_topic-Always_Free_Resources.htm) and [secret version instructions](https://docs.oracle.com/en-us/iaas/Content/secret-management/Tasks/create-secret-version.htm) before setting it up. Avoid a private vault, which is outside Always Free. +NFC CMS credentials use OCI Vault directly at read time. Create a standard virtual vault and software-protected key, store the student ID and password as separate secrets, then give the VM a narrowly scoped instance-principal permission to read only those two secret bundles. Put only their OCIDs in the private `.env`; changing a secret version in the Console is picked up on Maya's next NFC check, without copying the password to the VM file. See [the NFC CMS guide](NFC-CMS.md). Other existing secrets remain in `.env` unless and until they receive the same dedicated Vault integration. Check [Oracle's Always Free Vault limits](https://docs.oracle.com/en-us/iaas/Content/FreeTier/freetier_topic-Always_Free_Resources.htm) and [secret version instructions](https://docs.oracle.com/en-us/iaas/Content/secret-management/Tasks/create-secret-version.htm) before setting it up. Avoid a private vault, which is outside Always Free. diff --git a/docs/NFC-CMS.md b/docs/NFC-CMS.md new file mode 100644 index 0000000..929b299 --- /dev/null +++ b/docs/NFC-CMS.md @@ -0,0 +1,57 @@ +# NFC-IET CMS assignments + +This optional integration reads the **Assignments** page in the owner's own NFC-IET CMS account. It turns the portal's assignment title, course, marks, deadline and status into Maya tasks. It does not read quiz answers, grades, messages, or other students' records. + +## What it does today + +- signs in only to the official `cms.nfciet.com` site with a fresh headless browser; +- reads the assignment list once per scheduled check; +- creates or updates Maya tasks from the portal's stable assignment ID; +- stops reminders when the portal says an assignment is submitted, under review, graded or expired; +- fails closed if the login flow, assignment-table shape, deadline format or status labels change. + +The browser keeps no saved CMS cookies. It is closed at the end of every check. A failure does not delete tasks or make Maya guess. + +## What it does not do yet + +Maya does **not** upload or submit assignments in this version. A WhatsApp announcement can help identify an assignment, but it is never permission to submit anything. The future upload flow must show the owner the selected portal assignment and file, require a final private confirmation, then verify the portal receipt. It will be built only after an open, non-critical assignment form can be inspected with the owner. + +## Store NFC credentials in OCI Vault + +Do not put an NFC password in `.env`, GitHub, WhatsApp, a screenshot, or chat. On the Oracle VM: + +1. In Oracle Cloud Console, create a **standard** Vault and a software-protected master encryption key. These fit the Always Free Vault allowance. +2. Create two secret values: one for the NFC CMS student ID and one for the NFC CMS password. Give them clear names such as `maya-nfc-student-id` and `maya-nfc-password`. +3. Create a dynamic group containing only Maya's VM instance, then add a policy that permits that dynamic group to read **only those two secret bundles**. Do not grant broad Vault administration or secret-management permissions. +4. Put only the two secret OCIDs in `/opt/maya-assistant/.env`: + + ```dotenv + NFC_CMS_SYNC=true + NFC_SYNC_CRON=0 7 * * * + NFC_STUDENT_ID_SECRET_OCID=ocid1.vaultsecret... + NFC_PASSWORD_SECRET_OCID=ocid1.vaultsecret... + ``` + +5. Keep `/opt/maya-assistant/.env` owned by the Maya service account with mode `0600`, then restart: `sudo systemctl restart maya`. + +The VM obtains its permission through its OCI instance principal. The secret values are fetched into memory for a single check and are never written to the database or logs. To rotate a password later, add a new secret version in OCI Vault; the next scheduled check reads the current version. No code deployment is needed. + +## Control it privately + +In Maya's private chat, say or send a voice note such as: + +- `pause NFC deadline checking` +- `resume NFC checking` +- `pause VU and NFC deadline checking` + +Maya asks for one explicit confirmation. Pausing stops new portal checks but preserves tasks already imported and their existing reminders. + +## Verify safely + +After enabling it, wait for the scheduled time or restart Maya and inspect the service log: + +```bash +sudo journalctl -u maya -n 80 --no-pager +``` + +Then ask Maya privately for your tasks. Never test an upload with an important deadline until the future confirmation-and-receipt flow exists. diff --git a/docs/OWNER-CONTROLS.md b/docs/OWNER-CONTROLS.md index 4a25752..7eb6239 100644 --- a/docs/OWNER-CONTROLS.md +++ b/docs/OWNER-CONTROLS.md @@ -24,7 +24,7 @@ Maya asks for a specific group, date, or reminder when it cannot safely resolve | `MEDIA_BATCH_SIZE` | 1–3 | Maximum queued group files processed in one extraction run. | | `EXTRACT_BATCH_SIZE` | 1–50 | Maximum queued messages sent in one extraction batch. | -Raising the media limit or switching media reading on or off needs confirmation. Every group-policy change also needs confirmation. A change takes effect on the next media or extraction operation. Existing in-flight reads keep the limit they started with. The scheduled extraction interval, cron expressions, reply-rate safety limit, model, bot/owner identity, database/auth paths, Gemini key, Google OAuth values, and VU credentials remain `.env`-only and require a restart when changed. No tool reads or edits arbitrary environment variables or secrets. +Raising the media limit or switching media reading on or off needs confirmation. Every group-policy change also needs confirmation. The owner can also pause or resume NFC, VU, or both university deadline checks by text or voice; that needs confirmation and preserves existing tasks/reminders. A change takes effect on the next media, extraction, or source operation. Existing in-flight reads keep the limit they started with. The scheduled extraction interval, cron expressions, reply-rate safety limit, model, bot/owner identity, database/auth paths, Gemini key, Google OAuth values, and VU credentials remain `.env`-only and require a restart when changed. NFC secret values live in OCI Vault; `.env` contains only their references. No tool reads or edits arbitrary environment variables or secrets. ## Groups and large files From a326e98d26bcdd825656764a8813a43c19bebaf8 Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Sun, 15 Nov 2026 07:41:55 +0500 Subject: [PATCH 5/7] fix: align schema version guard --- ARCHITECTURE.md | 2 +- docs/OWNER-CONTROLS.md | 2 +- tests/memory.test.mjs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 1a76b00..c56d674 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -254,7 +254,7 @@ CREATE TABLE IF NOT EXISTS source_tasks ( Store times in **UTC**, and convert to `TIMEZONE` only when you show them or schedule something. -The live schema also has `memory_items`, `memory_fts` with insert/update/delete triggers, `memory_events`, `timetable_versions`, `timetable_entries`, `memory_confirmations`, `memory_save_drafts`, `runtime_settings`, `group_policies`, `owner_action_confirmations`, `owner_action_audit`, `owner_agent_requests`, and `owner_reminders` in [`src/db/schema.sql`](src/db/schema.sql). `migrate()` applies these additively and sets SQLite `user_version = 2`; it rejects a newer database version. Memory has no foreign key into `messages` or `tasks`, so deleting a memory never deletes group history, deadlines, or auth/config. See [saved memory behavior and recovery](docs/MEMORY.md). The SQL above documents the original core schema; `schema.sql` is authoritative for all current tables. +The live schema also has `memory_items`, `memory_fts` with insert/update/delete triggers, `memory_events`, `timetable_versions`, `timetable_entries`, `memory_confirmations`, `memory_save_drafts`, `runtime_settings`, `group_policies`, `source_controls`, `nfc_assignments`, `owner_action_confirmations`, `owner_action_audit`, `owner_agent_requests`, and `owner_reminders` in [`src/db/schema.sql`](src/db/schema.sql). `migrate()` applies these additively and sets SQLite `user_version = 3`; it rejects a newer database version. Memory has no foreign key into `messages` or `tasks`, so deleting a memory never deletes group history, deadlines, or auth/config. See [saved memory behavior and recovery](docs/MEMORY.md). The SQL above documents the original core schema; `schema.sql` is authoritative for all current tables. Normalize stored timestamp inputs to the fixed-millisecond ISO UTC form (`YYYY-MM-DDTHH:mm:ss.sssZ`), so SQLite text ordering works at interval boundaries. Application updates must also write `updated_at` in the same ISO UTC format. Reset both reminder flags when a task's due date changes. Mark a reminder only after `sendToOwner()` reports a successful send. diff --git a/docs/OWNER-CONTROLS.md b/docs/OWNER-CONTROLS.md index 7eb6239..2259ee1 100644 --- a/docs/OWNER-CONTROLS.md +++ b/docs/OWNER-CONTROLS.md @@ -44,4 +44,4 @@ An owner-created reminder has a title and an exact future time within one year. `src/config/runtime.ts` is the allowlisted settings service; `src/db/repos/group-policies.ts` applies group rules at ingestion and in the queued-message/media and retrieval queries. `owner_agent_requests` and `owner_action_audit` prevent duplicate writes on WhatsApp redelivery and record action metadata without secrets. To add a tool, define a bounded schema and result, specify its owner scope, target, risk, confirmation and revision rules, then add deterministic tests for invalid input, replay, and a partial failure. Do not add arbitrary SQL, shell, filesystem, recipient, secret, or URL tools. -Before deploying the schema migration to a host with real data, run `npm run backup-db` there and keep the snapshot private. The app upgrades SQLite to `user_version=2` on startup. A branch push alone does not update the running VM; deployment follows a merged main build and the host's deployment workflow. +Before deploying the schema migration to a host with real data, run `npm run backup-db` there and keep the snapshot private. The app upgrades SQLite to `user_version=3` on startup. A branch push alone does not update the running VM; deployment follows a merged main build and the host's deployment workflow. diff --git a/tests/memory.test.mjs b/tests/memory.test.mjs index 9c1664c..68769cf 100644 --- a/tests/memory.test.mjs +++ b/tests/memory.test.mjs @@ -113,8 +113,8 @@ test('online backup contains memory and FTS content and restores cleanly', async test('future schema version fails closed without modifying existing records', () => { const before = listMemories({ category: 'preference' }).length; - db.pragma('user_version = 3'); + db.pragma('user_version = 4'); assert.throws(() => migrate(), /newer than this Maya build/); - db.pragma('user_version = 2'); + db.pragma('user_version = 3'); assert.equal(listMemories({ category: 'preference' }).length, before); }); From aad78ba92c4c0b178a9f299a2a45a7f1c6d674ec Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Sun, 15 Nov 2026 07:41:55 +0500 Subject: [PATCH 6/7] fix: resolve NFC assignment links safely --- src/sources/nfc/lms.ts | 7 +++++-- tests/nfc-lms.test.mjs | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/sources/nfc/lms.ts b/src/sources/nfc/lms.ts index 1e605c5..697753e 100644 --- a/src/sources/nfc/lms.ts +++ b/src/sources/nfc/lms.ts @@ -44,11 +44,14 @@ export function parseNfcAssignmentRows(rows: readonly { cells: string[]; href: s return rows.map(({ cells, href }) => { if (cells.length !== 6 || !href) throw new Error('NFC CMS assignment table layout changed'); const [title, course, marks, due, status] = cells.map((cell) => cell.trim()); - const id = /\/student\/assignments\/(\d+)$/u.exec(new URL(href).pathname)?.[1]; + const assignmentUrl = new URL(href, ASSIGNMENTS_URL); + const id = assignmentUrl.origin === new URL(LOGIN_URL).origin + ? /\/student\/assignments\/(\d+)$/u.exec(assignmentUrl.pathname)?.[1] + : undefined; if (!id || ids.has(id) || !title || !course) throw new Error('NFC CMS assignment row is invalid'); ids.add(id); return { externalId: id, title: title.slice(0, 300), course: course.slice(0, 100), marks: marks || null, - dueAt: parseNfcDueDate(due ?? ''), status: normalizedStatus(status ?? ''), portalUrl: href }; + dueAt: parseNfcDueDate(due ?? ''), status: normalizedStatus(status ?? ''), portalUrl: assignmentUrl.href }; }); } diff --git a/tests/nfc-lms.test.mjs b/tests/nfc-lms.test.mjs index 4a99059..796ee1c 100644 --- a/tests/nfc-lms.test.mjs +++ b/tests/nfc-lms.test.mjs @@ -21,6 +21,14 @@ test('parses NFC CMS assignment rows with Pakistan-time deadlines and stable por }]); }); +test('accepts a same-site relative assignment link and stores its canonical URL', () => { + const [item] = parseNfcAssignmentRows([{ + cells: ['Assignment 3', 'AI-313', '20', '18 Oct 2026, 10:00 AM', 'Open', 'View'], + href: '/student/assignments/69', + }]); + assert.equal(item.portalUrl, 'https://www.cms.nfciet.com/student/assignments/69'); +}); + test('rejects NFC deadline or table changes instead of guessing', () => { assert.throws(() => parseNfcDueDate('tomorrow sometime'), /unrecognized assignment deadline/); assert.throws(() => parseNfcAssignmentRows([{ From df7457314e5bba33de7db0f703e1c2659cf60197 Mon Sep 17 00:00:00 2001 From: Muawiya Amir Date: Sun, 15 Nov 2026 07:41:55 +0500 Subject: [PATCH 7/7] test: cover paused VU sync --- tests/vu-source-state.test.mjs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/vu-source-state.test.mjs b/tests/vu-source-state.test.mjs index 4300f6c..4452efa 100644 --- a/tests/vu-source-state.test.mjs +++ b/tests/vu-source-state.test.mjs @@ -9,6 +9,7 @@ process.env.DATABASE_PATH = ':memory:'; const { db } = await import('../src/db/client.ts'); const { migrate } = await import('../src/db/migrate.ts'); const { syncVuClassicTodo } = await import('../src/features/vu.ts'); +const { setUniversityCheckingPaused } = await import('../src/db/repos/source-controls.ts'); migrate(); after(() => db.close()); @@ -23,3 +24,11 @@ test('manual and scheduled VU sync share success/failure state', async () => { assert.ok(state.last_success_at); assert.equal(state.last_failure_at, null); }); + +test('a paused VU source does not access the portal', async () => { + setUniversityCheckingPaused('vu-classic-todo', true); + assert.deepEqual(await syncVuClassicTodo(async () => { + throw new Error('portal must not be called while VU is paused'); + }), { created: 0, updated: 0, unchanged: 0 }); + setUniversityCheckingPaused('vu-classic-todo', false); +});