diff --git a/README.md b/README.md index 5b8db48..d93ec06 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Team 401's operations hub for projects, assignments, certifications, attendance, - Full-team and subteam Kanban boards - Certification-aware task assignment - Task comments, links, prerequisites, images, and file attachments -- Calendar events and task deadlines +- Recurring calendar events and task deadlines - Coach-managed attendance and kiosk timeclock - Student reports, team metrics, and CSV exports - Coach roster, account, PIN, and certification administration @@ -82,6 +82,16 @@ Cloudflare Pages builds with `npm run build` and publishes `out`. Configure the `workers/api/wrangler.jsonc` defines the `team401-ops-api` Worker, shared D1 database, R2 bucket, allowed browser origins, and `api.ops.team401.org` custom domain. +Password reset and QR device sign-in use the same Firebase project as normal login. The Worker requires these secrets: + +```text +FIREBASE_WEB_API_KEY +FIREBASE_SERVICE_ACCOUNT_EMAIL +FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY +``` + +The web API key is the same public Firebase key used by `NEXT_PUBLIC_FIREBASE_API_KEY`. The service-account email and PKCS#8 private key come from a Firebase Admin service-account JSON key and must only be stored as Cloudflare Worker secrets. Apply D1 migrations before deploying the Worker. In Firebase Authentication → Templates → Password reset, set the custom action URL to `https://ops.team401.org/login` so reset links finish inside Ops. + Renovate targets `staging`. Routine non-major updates may auto-merge only after validation succeeds. Promotion to `main` remains manual. ## Kiosk security diff --git a/migrations/0008_device_sign_in.sql b/migrations/0008_device_sign_in.sql new file mode 100644 index 0000000..f2ba738 --- /dev/null +++ b/migrations/0008_device_sign_in.sql @@ -0,0 +1,20 @@ +CREATE TABLE device_sign_in_requests ( + id TEXT PRIMARY KEY NOT NULL, + approval_token_hash TEXT NOT NULL UNIQUE, + poll_token_hash TEXT NOT NULL UNIQUE, + approved_uid TEXT, + expires_at INTEGER NOT NULL, + approved_at INTEGER, + denied_at INTEGER, + consumed_at INTEGER, + created_at INTEGER NOT NULL +); + +CREATE INDEX idx_device_sign_in_expiry + ON device_sign_in_requests(expires_at); + +CREATE TABLE auth_rate_limits ( + key TEXT PRIMARY KEY NOT NULL, + window_started_at INTEGER NOT NULL, + attempts INTEGER NOT NULL +); diff --git a/package-lock.json b/package-lock.json index cdba9ab..370622b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,24 +18,26 @@ "firebase": "^13.0.0", "jose": "^6.2.15", "lucide-react": "^1.31.0", - "next": "16.4.4", + "next": "16.4.5", "papaparse": "^5.6.0", + "qrcode": "^1.5.4", "react": "19.3.1", "react-dom": "19.3.1", "recharts": "^3.10.1", "tailwind-merge": "^3.6.0", - "web-push": "^3.6.7", + "web-push": "^4.0.0", "zustand": "^5.0.15" }, "devDependencies": { "@cloudflare/workers-types": "^5.20261103.1", "@tailwindcss/postcss": "^4", "@types/node": "^26.0.0", + "@types/qrcode": "^1.5.6", "@types/react": "^19", "@types/react-dom": "^19", "@types/web-push": "^3.6.4", "eslint": "^9", - "eslint-config-next": "16.4.4", + "eslint-config-next": "16.4.5", "tailwindcss": "^4", "typescript": "^6.0.0", "wrangler": "^4.157.0" @@ -2523,15 +2525,15 @@ } }, "node_modules/@next/env": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.4.tgz", - "integrity": "sha512-6/3ZuELR0tPLgNigvv8d/LAmfLIo1IpNfvrI/AHCAl9w9D0DNVGQGvo+OLPzAWR+WMW3vVyO7HaW0kfL97huBg==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.5.tgz", + "integrity": "sha512-JwSPwpdkZL5VMl2jA/q+JI8MZdweAL3xmw5/tb9y/TLtmS0YXZnmYDzSihwk8xTj1OL+WM53gTqaj96yuLp6Xw==", "license": "MIT" }, "node_modules/@next/eslint-plugin-next": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.4.tgz", - "integrity": "sha512-O3ZZhL+PMlqa8xgg8Sx/UeG1BGgl/jOGkyRZFC8pDZTNYBoIbbUZtwDotNR+aGsnROE321lOQ+MfwFjdVFz+FA==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.5.tgz", + "integrity": "sha512-dNmc4y4En/34tWxaBFF2tG/R9GeiRwVPf7v8Az/Pqk8FcT4Uv0ePmrZKvWBL2nFy1QprPgJW+6XjfyV6jbRV3Q==", "dev": true, "license": "MIT", "dependencies": { @@ -2572,9 +2574,9 @@ } }, "node_modules/@next/swc-darwin-arm64": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.4.tgz", - "integrity": "sha512-1KlZ5IJ7zcLBZvqG1q7nuRWm2LAAN4C3iBqqoBCRRl1UEv0A4k6Rek+x3j23UiWf8Gz+VsN+M/LylAWkxpm2mg==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.5.tgz", + "integrity": "sha512-W5TniBzWKASbNNwHZ/S/f1MxQUXU/LdjklVMWA0Ujbfl7SZnUzFls45hO0i/sF7Bx1jJBWp7WWmoQajXtX/O8A==", "cpu": [ "arm64" ], @@ -2588,9 +2590,9 @@ } }, "node_modules/@next/swc-darwin-x64": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.4.tgz", - "integrity": "sha512-Tb7efFdhbS/ph74RS7wob84gXGM58qxoO/WrkiMsTmy/JZktKOKBeiM45W0E/b8JfBzZJdexQqSmvedBwDK0PA==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.5.tgz", + "integrity": "sha512-uWq4qkHapBDS1oFltWS4YxTb9pLHAtLNcpbuK6SmRsebLYZqpBML/j/C0op+50JYGTpZgVL/DWNt/6oWlamrrw==", "cpu": [ "x64" ], @@ -2604,9 +2606,9 @@ } }, "node_modules/@next/swc-linux-arm64-gnu": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.4.tgz", - "integrity": "sha512-wojSfLnH8RRImhtbcn3Dlx9JICh6aQHgDA33XDr+EPua2tt7Q/yjDn0FTAbqfNlLrBmOASAGhLh6NvBk9L3gzw==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.5.tgz", + "integrity": "sha512-FdRcyOx5u5P51mlAqLB9EXdd8jZO5fsdHtk4BAQSkqOywCsbTNN/rmw+jO7pnmjNdAtu2AG46NzbCL2FPDrrgw==", "cpu": [ "arm64" ], @@ -2623,9 +2625,9 @@ } }, "node_modules/@next/swc-linux-arm64-musl": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.4.tgz", - "integrity": "sha512-zgxpGOZaR+2O6dOk5ZAUkKgH92ZtqNg3ohzyg2HmWc2N+AZH4dEpTwdpB0e5MR9YRVdVDUkEM5g6c3TWWn8g1g==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.5.tgz", + "integrity": "sha512-cyvmmgtRXR8aGVT86wi9Py53IlfyCx7P2fZxuAXAoTummDnhKtUyjrMeXfapqp4qgD+gT5RqyGD/VfA16jEK7Q==", "cpu": [ "arm64" ], @@ -2642,9 +2644,9 @@ } }, "node_modules/@next/swc-linux-x64-gnu": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.4.tgz", - "integrity": "sha512-fg3Wr030Y3BDkCXi6HGsPz0BUPTGZJS8TZSrCO0tS3O/KBsCyx4eP6aeaizCpGmcUKhtb4l7JoMc88QO2qBl2g==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.5.tgz", + "integrity": "sha512-hPc+Fl+N22DAvqZHq559NmamXboOX5Lu8I5Wl0DezfrhTk1Zz21NQeYoZDmNI/NjTcrdsVxM72Fzn2lI+Q+vAw==", "cpu": [ "x64" ], @@ -2661,9 +2663,9 @@ } }, "node_modules/@next/swc-linux-x64-musl": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.4.tgz", - "integrity": "sha512-40cr71PSdCV9zU2g0B1XG27af10tYU+9g8F+FtF3qSguQg0jSZDoxn0NrAvgFQ0cy9s0ZBA/00P9g/XL1O43xg==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.5.tgz", + "integrity": "sha512-gbACYE8IP/jlprNTpiWXHb8N9CofOzpnEwH2SrIz1dUbiJf1FbDssDupCAPeP1Taxe8mgG20sGZamJI7KFOdZw==", "cpu": [ "x64" ], @@ -2680,9 +2682,9 @@ } }, "node_modules/@next/swc-win32-arm64-msvc": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.4.tgz", - "integrity": "sha512-vFMiEbRZ+LYNeswslf4LuGuoPHE8JbtqV0GnmzbpnGNMs0uWaR2q98hu8M/UWGycNJERBXIUss+BGd3PIJ8VZg==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.5.tgz", + "integrity": "sha512-+8gj++ZMo8H20Xh2ijjNqyFk5LPLw0AC4Fs4Tq/G94rjjQXhOjN4jgSWsWKPFsyY26hfIeemJIwKtMxOsp5GBA==", "cpu": [ "arm64" ], @@ -2696,9 +2698,9 @@ } }, "node_modules/@next/swc-win32-x64-msvc": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.4.tgz", - "integrity": "sha512-jy2P4V8BDZ+CFCzYABHYRZ1CmyFhfmYe22i8KA4uEafdYPrUjJ3Ot+lx265mLWLHiZRIfBzCn3V1F17m0vzl9Q==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.5.tgz", + "integrity": "sha512-qNZj66pYXnaWLiF9R9GUbfBdrCv7kC6TaZfIwB2KH5WPc/8pEM3nVOj8hpQhWJU8S94rlH5MPDcX15+RrgUhiw==", "cpu": [ "x64" ], @@ -4065,6 +4067,16 @@ "@types/node": "*" } }, + "node_modules/@types/qrcode": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz", + "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/react": { "version": "19.3.0", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", @@ -4744,12 +4756,12 @@ } }, "node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz", + "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==", "license": "MIT", "engines": { - "node": ">= 14" + "node": ">= 20" } }, "node_modules/ajv": { @@ -5191,6 +5203,15 @@ "node": ">=6" } }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001809", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001809.tgz", @@ -5540,6 +5561,15 @@ } } }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/decimal.js-light": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", @@ -5599,6 +5629,12 @@ "node": ">=8" } }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, "node_modules/doctrine": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", @@ -6015,13 +6051,13 @@ } }, "node_modules/eslint-config-next": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.4.tgz", - "integrity": "sha512-r+rPQU1uaKDXWWWro6hDk3VrtBjmRyDz7UySTe9CU8HHG4eTXXLSHxasSwpOz/7FJZZuWBVcFERpjWszu04BbQ==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.5.tgz", + "integrity": "sha512-mvh39zYLoNjpT5tVmf8xZu7i5lEOb5jN5cW6qD9OpeCp4GEEOeYta0Z2XyKiD0pYdlvm5/Td6Bi890maPRlIjg==", "dev": true, "license": "MIT", "dependencies": { - "@next/eslint-plugin-next": "16.4.4", + "@next/eslint-plugin-next": "16.4.5", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", @@ -6889,9 +6925,9 @@ } }, "node_modules/http_ece": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz", - "integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.1.tgz", + "integrity": "sha512-+tzLoMYgXvicu60sVFoswTiu6BiQ6EX3DORRJQ3W2dNpNWCyZ3tcmRFZZ3jgVyw8ziWUCeUARKCkYDY6JgFx+w==", "license": "MIT", "engines": { "node": ">=16" @@ -6904,16 +6940,17 @@ "license": "MIT" }, "node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz", + "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==", "license": "MIT", "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" + "agent-base": "9.0.0", + "debug": "^4.3.4", + "proxy-agent-negotiate": "1.1.0" }, "engines": { - "node": ">= 14" + "node": ">= 20" } }, "node_modules/idb": { @@ -8091,6 +8128,7 @@ "version": "1.2.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -8150,12 +8188,12 @@ "license": "MIT" }, "node_modules/next": { - "version": "16.4.4", - "resolved": "https://registry.npmjs.org/next/-/next-16.4.4.tgz", - "integrity": "sha512-Hu4pOw2x0RQ0TQabNWbpsNg/3+SZf+rLQwvfhBLnptv98GS4dcIVMlfEyn9jb2/ZJDSahhnUKEs0YrfarjGX3A==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/next/-/next-16.4.5.tgz", + "integrity": "sha512-rmdfsWosjTUO+6R0S3KokoIk6Kj0sWDRTe86tZHdqaWH/oXq/udX3/4xb+YQi7aWbyEFoglDU54kaifLCdXbBw==", "license": "MIT", "dependencies": { - "@next/env": "16.4.4", + "@next/env": "16.4.5", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -8169,14 +8207,14 @@ "node": ">=20.9.0" }, "optionalDependencies": { - "@next/swc-darwin-arm64": "16.4.4", - "@next/swc-darwin-x64": "16.4.4", - "@next/swc-linux-arm64-gnu": "16.4.4", - "@next/swc-linux-arm64-musl": "16.4.4", - "@next/swc-linux-x64-gnu": "16.4.4", - "@next/swc-linux-x64-musl": "16.4.4", - "@next/swc-win32-arm64-msvc": "16.4.4", - "@next/swc-win32-x64-msvc": "16.4.4", + "@next/swc-darwin-arm64": "16.4.5", + "@next/swc-darwin-x64": "16.4.5", + "@next/swc-linux-arm64-gnu": "16.4.5", + "@next/swc-linux-arm64-musl": "16.4.5", + "@next/swc-linux-x64-gnu": "16.4.5", + "@next/swc-linux-x64-musl": "16.4.5", + "@next/swc-win32-arm64-msvc": "16.4.5", + "@next/swc-win32-x64-msvc": "16.4.5", "sharp": "^0.35.5" }, "peerDependencies": { @@ -8451,6 +8489,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/papaparse": { "version": "5.7.0", "resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.7.0.tgz", @@ -8474,7 +8521,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -8530,6 +8576,15 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/possible-typed-array-names": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", @@ -8614,6 +8669,23 @@ "node": ">=12.0.0" } }, + "node_modules/proxy-agent-negotiate": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz", + "integrity": "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } + } + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -8624,6 +8696,141 @@ "node": ">=6" } }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/qrcode/node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/qrcode/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/qrcode/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/qrcode/node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -8815,6 +9022,12 @@ "node": ">=9.3.0 || >=8.10.0 <9.0.0" } }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/reselect": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz", @@ -8997,6 +9210,12 @@ "semver": "bin/semver.js" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/set-function-length": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", @@ -9884,16 +10103,15 @@ } }, "node_modules/web-push": { - "version": "3.6.7", - "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz", - "integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/web-push/-/web-push-4.0.0.tgz", + "integrity": "sha512-iKzGK/q3k+kjoPK+fkbs8ymYvEqu5RJNAypEskW+UAYsC44upqb0f+T8QSYW4naowl9bzjlHRe8CI0NFCBzZeQ==", "license": "MPL-2.0", "dependencies": { "asn1.js": "^5.3.0", - "http_ece": "1.2.0", - "https-proxy-agent": "^7.0.0", - "jws": "^4.0.0", - "minimist": "^1.2.5" + "http_ece": "1.2.1", + "https-proxy-agent": "^9.1.0", + "jws": "^4.0.1" }, "bin": { "web-push": "src/cli.js" @@ -10014,6 +10232,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, "node_modules/which-typed-array": { "version": "1.1.22", "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.22.tgz", diff --git a/package.json b/package.json index bf4ac27..0309cf8 100644 --- a/package.json +++ b/package.json @@ -23,24 +23,26 @@ "firebase": "^13.0.0", "jose": "^6.2.15", "lucide-react": "^1.31.0", - "next": "16.4.4", + "next": "16.4.5", "papaparse": "^5.6.0", + "qrcode": "^1.5.4", "react": "19.3.1", "react-dom": "19.3.1", "recharts": "^3.10.1", "tailwind-merge": "^3.6.0", - "web-push": "^3.6.7", + "web-push": "^4.0.0", "zustand": "^5.0.15" }, "devDependencies": { "@cloudflare/workers-types": "^5.20261103.1", "@tailwindcss/postcss": "^4", "@types/node": "^26.0.0", + "@types/qrcode": "^1.5.6", "@types/react": "^19", "@types/react-dom": "^19", "@types/web-push": "^3.6.4", "eslint": "^9", - "eslint-config-next": "16.4.4", + "eslint-config-next": "16.4.5", "tailwindcss": "^4", "typescript": "^6.0.0", "wrangler": "^4.157.0" diff --git a/src/app/device-link/device-link-page.tsx b/src/app/device-link/device-link-page.tsx new file mode 100644 index 0000000..2914820 --- /dev/null +++ b/src/app/device-link/device-link-page.tsx @@ -0,0 +1,61 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useState } from "react"; +import { useAuth } from "@/context/auth-context"; +import { respondToDeviceLink } from "@/lib/auth-api"; + +export default function DeviceLinkPage() { + const { firebaseUser, profile, loading } = useAuth(); + const [credentials, setCredentials] = useState<{ id: string; token: string } | null>(null); + const [returnPath, setReturnPath] = useState("/device-link"); + const [working, setWorking] = useState<"approve" | "deny" | null>(null); + const [decision, setDecision] = useState<"approved" | "denied" | null>(null); + const [error, setError] = useState(""); + + useEffect(() => { + const url = new URL(window.location.href); + const id = url.searchParams.get("id"); + const token = url.searchParams.get("token"); + queueMicrotask(() => { + setReturnPath(`${url.pathname}${url.search}`); + if (id && token) setCredentials({ id, token }); + else setError("This device sign-in link is incomplete."); + }); + }, []); + + async function respond(approve: boolean) { + if (!credentials) return; + setWorking(approve ? "approve" : "deny"); + setError(""); + try { + await respondToDeviceLink(credentials.id, credentials.token, approve); + setDecision(approve ? "approved" : "denied"); + } catch (caught) { + setError(caught instanceof Error ? caught.message : "The device sign-in request could not be completed."); + } finally { + setWorking(null); + } + } + + return
+
+

401 Ops

Approve device sign-in

+ {loading ?

Checking your account…

: decision ? <> +

{decision === "approved" ? "Approved. The other device will sign in automatically." : "Denied. The other device was not signed in."}

+

You can close this page.

+ : !firebaseUser || !profile ? <> +

Sign in on this device first, then approve the new device.

+ Sign in + : <> +

Sign in the new device as {profile.displayName}?

+

Only approve a QR code currently visible on a device in front of you.

+
+ + +
+ } + {error &&

{error}

} +
+
; +} diff --git a/src/app/device-link/page.tsx b/src/app/device-link/page.tsx new file mode 100644 index 0000000..65c299f --- /dev/null +++ b/src/app/device-link/page.tsx @@ -0,0 +1,5 @@ +import DeviceLinkPage from "./device-link-page"; + +export default function Page() { + return ; +} diff --git a/src/app/login/login-page.tsx b/src/app/login/login-page.tsx index 7611f0e..ee416e8 100644 --- a/src/app/login/login-page.tsx +++ b/src/app/login/login-page.tsx @@ -3,13 +3,17 @@ import { useEffect, useState, FormEvent } from "react"; import { useRouter } from "next/navigation"; import { + confirmPasswordReset, + signInWithCustomToken, signInWithEmailAndPassword, - sendPasswordResetEmail, updatePassword, + verifyPasswordResetCode, } from "firebase/auth"; +import QRCode from "qrcode"; import { auth } from "@/lib/firebase"; import { useAuth } from "@/context/auth-context"; -import { saveUser } from "@/lib/core-api"; +import { fetchUser, saveUser } from "@/lib/core-api"; +import { beginDeviceLink, pollDeviceLink, requestPasswordReset, type DeviceLinkStart } from "@/lib/auth-api"; export default function LoginPage() { const { firebaseUser, profile, loading } = useAuth(); @@ -23,14 +27,44 @@ export default function LoginPage() { const [submitting, setSubmitting] = useState(false); const [resetMode, setResetMode] = useState(false); const [resetMessage, setResetMessage] = useState(null); + const [qrMode, setQrMode] = useState(false); + const [qrBusy, setQrBusy] = useState(false); + const [qrError, setQrError] = useState(null); + const [deviceLink, setDeviceLink] = useState<(DeviceLinkStart & { image: string }) | null>(null); + const [resetCode, setResetCode] = useState(null); + const [resetEmail, setResetEmail] = useState(""); + const [checkingResetCode, setCheckingResetCode] = useState(false); + + function destination() { + const next = new URLSearchParams(window.location.search).get("next"); + return next?.startsWith("/") && !next.startsWith("//") ? next : "/board"; + } // Already signed in with a finalized account -> go straight to the board. useEffect(() => { + if (new URLSearchParams(window.location.search).get("mode") === "resetPassword") return; if (!loading && firebaseUser && profile && !profile.mustResetPassword) { - router.replace("/board"); + router.replace(destination()); } }, [loading, firebaseUser, profile, router]); + useEffect(() => { + const search = new URLSearchParams(window.location.search); + const code = search.get("oobCode"); + if (search.get("mode") !== "resetPassword" || !code) return; + queueMicrotask(() => { + setCheckingResetCode(true); + setError(null); + verifyPasswordResetCode(auth, code).then((verifiedEmail) => { + setResetCode(code); + setResetEmail(verifiedEmail); + }).catch(() => { + setError("This password-reset link is invalid or has expired. Request a new link below."); + setResetMode(true); + }).finally(() => setCheckingResetCode(false)); + }); + }, []); + async function handleSignIn(e: FormEvent) { e.preventDefault(); setError(null); @@ -60,7 +94,7 @@ export default function LoginPage() { try { await updatePassword(auth.currentUser, newPassword); if (profile) await saveUser({ ...profile, mustResetPassword: false }); - router.replace("/board"); + router.replace(destination()); } catch { setError("Couldn't update your password. Try signing in again."); } finally { @@ -70,20 +104,95 @@ export default function LoginPage() { async function handleResetRequest(e: FormEvent) { e.preventDefault(); + setError(null); setSubmitting(true); setResetMessage(null); try { - await sendPasswordResetEmail(auth, email.trim().toLowerCase()); - setResetMessage("If that address has an account, a reset link has been sent."); + await requestPasswordReset(email.trim().toLowerCase()); + setResetMessage("If that address has an account, Firebase sent a reset link. Check spam or junk mail if it does not arrive within a few minutes."); + } catch (caught) { + setError(caught instanceof Error ? caught.message : "The reset request failed. Check your connection and try again."); + } finally { + setSubmitting(false); + } + } + + async function handleResetCompletion(e: FormEvent) { + e.preventDefault(); + if (!resetCode) return; + setError(null); + if (newPassword.length < 8) return setError("Use at least 8 characters."); + if (newPassword !== confirmPassword) return setError("Passwords don't match."); + setSubmitting(true); + try { + await confirmPasswordReset(auth, resetCode, newPassword); + const credential = await signInWithEmailAndPassword(auth, resetEmail, newPassword); + const nextProfile = await fetchUser(credential.user.uid); + if (nextProfile.mustResetPassword) await saveUser({ ...nextProfile, mustResetPassword: false }); + router.replace(destination()); } catch { - // Keep the response generic so this screen never reveals which students - // have accounts. Firebase may also intentionally hide that distinction. - setResetMessage("If that address has an account, a reset link has been sent."); + setError("The password could not be reset. The link may have expired; request a new one and try again."); } finally { setSubmitting(false); } } + async function beginQrSignIn() { + setQrMode(true); + setQrBusy(true); + setQrError(null); + setDeviceLink(null); + try { + const link = await beginDeviceLink(); + const image = await QRCode.toDataURL(link.approvalUrl, { width: 360, margin: 1, errorCorrectionLevel: "M" }); + setDeviceLink({ ...link, image }); + } catch (caught) { + setQrError(caught instanceof Error ? caught.message : "Could not create a sign-in code."); + } finally { + setQrBusy(false); + } + } + + useEffect(() => { + if (!deviceLink) return; + let cancelled = false; + let timer: number | undefined; + async function poll() { + if (!deviceLink) return; + try { + const result = await pollDeviceLink(deviceLink.id, deviceLink.pollToken); + if (result.status === "approved") { + await signInWithCustomToken(auth, result.customToken); + router.replace(destination()); + return; + } + if (!cancelled) timer = window.setTimeout(poll, 1500); + } catch (caught) { + if (cancelled) return; + setQrError(caught instanceof Error ? caught.message : "Could not finish QR sign-in."); + setDeviceLink(null); + } + } + timer = window.setTimeout(poll, 1000); + return () => { cancelled = true; if (timer) window.clearTimeout(timer); }; + }, [deviceLink, router]); + + if (checkingResetCode) { + return

Checking reset link…

; + } + + if (resetCode) { + return
+
+

401 Ops

Choose a new password

Resetting the password for {resetEmail}.

+ setNewPassword(event.target.value)} className="input" minLength={8} autoComplete="new-password" required /> + setConfirmPassword(event.target.value)} className="input" minLength={8} autoComplete="new-password" required /> + {error &&

{error}

} + +
+
; + } + // Stage 2: signed in on a temp password, must set a real one before continuing. if (firebaseUser && profile?.mustResetPassword) { return ( @@ -129,17 +238,17 @@ export default function LoginPage() { return (
event.preventDefault() : resetMode ? handleResetRequest : handleSignIn} className="bg-paper-raised border border-steel-line rounded w-full max-w-sm p-8 space-y-5" >

401 Ops

-

{resetMode ? "Reset your password" : "Sign in"}

+

{resetMode ? "Reset your password" : qrMode ? "Sign in with a QR code" : "Sign in"}

- {resetMode ? "Enter your account email and we’ll send you a reset link." : "Use the email and password your coach gave you."} + {resetMode ? "Enter your account email and we’ll send you a reset link." : qrMode ? "Scan this from a device where you are already signed in, then approve the new device." : "Use the email and password your coach gave you."}

- + {!qrMode && - - {!resetMode && + } + {!resetMode && !qrMode && } - {error &&

{error}

} - {resetMessage &&

{resetMessage}

} - - + {qrMode ? <> + {qrBusy &&
Creating secure code…
} + {deviceLink && <> + {/* Generated data URLs do not benefit from Next image optimization. */} + {/* eslint-disable-next-line @next/next/no-img-element */} + QR code for signing in this device + } + {qrError &&

{qrError}

} +
+ + +
+ : <> + {error &&

{error}

} + {resetMessage &&

{resetMessage}

} + + + {!resetMode && } + }
); diff --git a/src/components/auth-route-guard.tsx b/src/components/auth-route-guard.tsx index 4c70b59..4237c57 100644 --- a/src/components/auth-route-guard.tsx +++ b/src/components/auth-route-guard.tsx @@ -7,7 +7,7 @@ import { withBasePath } from "@/lib/base-path"; function isPublicPath(pathname: string) { const normalized = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname; - return normalized === "/" || normalized === "/login"; + return normalized === "/" || normalized === "/login" || normalized === "/device-link"; } export function AuthRouteGuard({ children }: { children: ReactNode }) { diff --git a/src/components/task-dialog.tsx b/src/components/task-dialog.tsx index 81e991b..afd3310 100644 --- a/src/components/task-dialog.tsx +++ b/src/components/task-dialog.tsx @@ -81,9 +81,11 @@ export function TaskDialog({ const isOnThisTask = !!(task && profile && task.assigneeUids.includes(profile.uid)); const isTaskCollaborator = !!(task && profile && (task.createdByUid === profile.uid || task.subteam === profile.subteam || isOnThisTask)); const canFullyEdit = mode === "create" || (!!task && !task.archived && (isCoach || isStudentLeader)); - const canEditContent = canFullyEdit || (!!task && !task.archived && isTaskCollaborator); - const canEditCertifications = canFullyEdit || (!!task && !task.archived && profile?.role === "student"); - const canSaveChanges = canFullyEdit || canEditContent || canEditCertifications; + const canEditTask = canFullyEdit || (!!task && !task.archived && isTaskCollaborator); + const canEditContent = canEditTask; + const canEditCertifications = canEditTask; + const canEditAssignees = canEditTask; + const canSaveChanges = canEditTask; const canDelete = mode === "edit" && !!task && (isCoach || (isStudentLeader && profile?.subteam === task.subteam)); const hasStatusControl = mode === "edit" && !task?.archived && (canFullyEdit || isTaskCollaborator); const canAttach = !!task && !task.archived && (canFullyEdit || isTaskCollaborator); @@ -177,16 +179,16 @@ export function TaskDialog({ } } else if (task) { const changes: Partial = {}; - if (canEditContent) Object.assign(changes, { title, description }); - if (canEditCertifications) Object.assign(changes, { requiredCertificationIds, requireAllCertifications: requireAll }); - if (canFullyEdit) Object.assign(changes, { - leadersOnly, subteam, priority, + if (canEditContent) Object.assign(changes, { + title, description, priority, dueDate: dueDate ? new Date(dueDate).toISOString() : null, pointOfContactUid: pointOfContactUid || task.createdByUid, blockedReason: blockedReason || null, blockedDetails, prerequisiteTaskIds, links, }); + if (canEditCertifications) Object.assign(changes, { requiredCertificationIds, requireAllCertifications: requireAll }); + if (canFullyEdit) Object.assign(changes, { leadersOnly, subteam }); await updateTask(task.id, changes); - if (canFullyEdit) { + if (canEditAssignees) { const changed = assigneeUids.length !== task.assigneeUids.length || assigneeUids.some((uid) => !task.assigneeUids.includes(uid)); if (changed) await setAssignees(task, assigneeUids); } @@ -430,8 +432,8 @@ export function TaskDialog({ className="input mt-1" value={blockedReason} onChange={(e) => setBlockedReason(e.target.value as BlockedReason)} - disabled={!canFullyEdit} - required={canFullyEdit} + disabled={!canEditTask} + required={canEditTask} > {Object.entries(BLOCKED_REASON_LABEL).map(([value, label]) => ( @@ -446,7 +448,7 @@ export function TaskDialog({ rows={2} value={blockedDetails} onChange={(e) => setBlockedDetails(e.target.value)} - disabled={!canFullyEdit} + disabled={!canEditTask} placeholder="Order number, person to follow up with, next check-in…" /> @@ -497,7 +499,7 @@ export function TaskDialog({ className="input mt-1" value={priority} onChange={(e) => setPriority(e.target.value as Priority)} - disabled={!canFullyEdit} + disabled={!canEditTask} > @@ -513,7 +515,7 @@ export function TaskDialog({ className="input mt-1" value={dueDate} onChange={(e) => setDueDate(e.target.value)} - disabled={!canFullyEdit} + disabled={!canEditTask} /> @@ -538,7 +540,7 @@ export function TaskDialog({
Assignment & requirements
- {canFullyEdit && ( + {canEditAssignees && (
Assignees
@@ -553,7 +555,7 @@ export function TaskDialog({ )}
)} - {!canFullyEdit && ( + {!canEditAssignees && (
Assignees

@@ -573,7 +575,7 @@ export function TaskDialog({ className="input mt-1" value={pointOfContactUid} onChange={(e) => setPointOfContactUid(e.target.value)} - disabled={!canFullyEdit} + disabled={!canEditTask} > {visibleUsers.map((user) => ( @@ -629,7 +631,7 @@ export function TaskDialog({ className="mt-0.5" checked={prerequisiteTaskIds.includes(candidate.id)} onChange={() => togglePrerequisite(candidate.id)} - disabled={!canFullyEdit} + disabled={!canEditTask} /> {candidate.title} @@ -655,12 +657,12 @@ export function TaskDialog({

The first link is shown on the task card. Put the most useful CAD or reference link first.

{links.map((link, index) => (
- changeLink(link.id, { label: event.target.value })} placeholder={index === 0 ? "Primary link label" : "Link label"} disabled={!canFullyEdit} /> - changeLink(link.id, { url: event.target.value })} placeholder="https://…" required disabled={!canFullyEdit} /> - {!canFullyEdit ? Open : } + changeLink(link.id, { label: event.target.value })} placeholder={index === 0 ? "Primary link label" : "Link label"} disabled={!canEditTask} /> + changeLink(link.id, { url: event.target.value })} placeholder="https://…" required disabled={!canEditTask} /> + {!canEditTask ? Open : }
))} - {canFullyEdit && } + {canEditTask && }
diff --git a/src/lib/auth-api.ts b/src/lib/auth-api.ts new file mode 100644 index 0000000..02fff5f --- /dev/null +++ b/src/lib/auth-api.ts @@ -0,0 +1,49 @@ +import { auth } from "@/lib/firebase"; + +const baseUrl = () => process.env.NEXT_PUBLIC_OPS_API_URL?.replace(/\/$/, ""); + +async function request(path: string, init?: RequestInit, authenticated = false): Promise { + const url = baseUrl(); + if (!url) throw new Error("The Ops authentication service is unavailable."); + const token = authenticated ? await auth.currentUser?.getIdToken() : null; + if (authenticated && !token) throw new Error("Sign in before approving another device."); + const response = await fetch(`${url}${path}`, { + ...init, + cache: "no-store", + headers: { + "Content-Type": "application/json", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + ...init?.headers, + }, + }); + const body = await response.json().catch(() => null) as (T & { error?: string }) | null; + if (!response.ok) throw new Error(body?.error ?? "The authentication request failed."); + return body as T; +} + +export interface DeviceLinkStart { + id: string; + pollToken: string; + approvalUrl: string; + expiresAt: number; +} + +export function requestPasswordReset(email: string) { + return request<{ sent: true }>("/auth/password-reset", { method: "POST", body: JSON.stringify({ email }) }); +} + +export function beginDeviceLink() { + return request("/auth/device-link", { method: "POST" }); +} + +export function pollDeviceLink(id: string, token: string) { + const query = new URLSearchParams({ id, token }); + return request<{ status: "pending" } | { status: "approved"; customToken: string }>(`/auth/device-link?${query}`); +} + +export function respondToDeviceLink(id: string, token: string, approve: boolean) { + return request<{ status: "approved" | "denied" }>("/auth/device-link", { + method: approve ? "PATCH" : "DELETE", + body: JSON.stringify({ id, token }), + }, true); +} diff --git a/workers/api/src/auth.ts b/workers/api/src/auth.ts new file mode 100644 index 0000000..fc976c1 --- /dev/null +++ b/workers/api/src/auth.ts @@ -0,0 +1,177 @@ +/// + +import { createFirebaseCustomToken, verifyFirebaseToken } from "./firebase-auth"; + +export interface AuthEnv { + DB: D1Database; + FIREBASE_PROJECT_ID: string; + FIREBASE_WEB_API_KEY?: string; + FIREBASE_SERVICE_ACCOUNT_EMAIL?: string; + FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY?: string; +} + +const linkLifetimeMs = 5 * 60 * 1000; +const idPattern = /^[0-9a-f-]{36}$/i; +const tokenPattern = /^[A-Za-z0-9_-]{40,100}$/; + +export function isAuthRoute(path: string) { + return path === "/auth/password-reset" || path === "/auth/device-link"; +} + +export async function handleAuth(request: Request, env: AuthEnv, cors: Headers) { + try { + const path = new URL(request.url).pathname; + if (path === "/auth/password-reset") return passwordReset(request, env, cors); + return deviceLink(request, env, cors); + } catch (error) { + console.error("Auth request failed", error); + const message = error instanceof Error ? error.message : "Authentication request failed"; + const status = message === "Unauthorized" ? 401 : message === "Forbidden" ? 403 : message.includes("not configured") ? 503 : message.startsWith("Invalid") ? 400 : message.includes("expired") || message.includes("used") || message.includes("denied") || message.includes("already answered") ? 410 : 500; + return json({ error: status === 500 ? "Authentication request failed" : message }, status, cors); + } +} + +async function passwordReset(request: Request, env: AuthEnv, cors: Headers) { + if (request.method !== "POST") return methodNotAllowed(cors, "POST, OPTIONS"); + const clientIp = request.headers.get("CF-Connecting-IP") ?? "unknown"; + const limit = await consumeRateLimit(env.DB, `password-reset:${clientIp}`, 5 * 60_000, 3); + if (!limit.allowed) { + const headers = new Headers(cors); + headers.set("Retry-After", String(Math.ceil(limit.retryAfterMs / 1000))); + return json({ error: "Too many reset requests. Wait a few minutes and try again." }, 429, headers); + } + const body = await request.json<{ email?: unknown }>().catch(() => ({} as { email?: unknown })); + const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : ""; + if (!email || email.length > 320 || !email.includes("@")) return json({ error: "Enter a valid email address." }, 400, cors); + if (!env.FIREBASE_WEB_API_KEY) throw new Error("Firebase password reset is not configured"); + const response = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=${encodeURIComponent(env.FIREBASE_WEB_API_KEY)}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ requestType: "PASSWORD_RESET", email }), + }); + if (!response.ok) { + const providerError = await response.text(); + console.error("Firebase password reset failed", response.status, providerError); + // Preserve account privacy while still telling the UI that delivery did not start. + if (!providerError.includes("EMAIL_NOT_FOUND")) throw new Error("Firebase password reset failed"); + } + return json({ sent: true }, 200, cors); +} + +async function deviceLink(request: Request, env: AuthEnv, cors: Headers) { + if (request.method === "POST") { + if (!env.FIREBASE_SERVICE_ACCOUNT_EMAIL || !env.FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY) throw new Error("QR sign-in is not configured yet"); + const clientIp = request.headers.get("CF-Connecting-IP") ?? "unknown"; + const limit = await consumeRateLimit(env.DB, `device-link:${clientIp}`, 60_000, 10); + if (!limit.allowed) return json({ error: "Too many sign-in requests. Try again shortly." }, 429, cors); + const origin = request.headers.get("Origin"); + if (!origin) throw new Error("Invalid sign-in origin"); + const id = crypto.randomUUID(); + const approvalToken = randomToken(); + const pollToken = randomToken(); + const now = Date.now(); + await env.DB.batch([ + env.DB.prepare("DELETE FROM device_sign_in_requests WHERE expires_at < ? OR consumed_at IS NOT NULL").bind(now - 24 * 60 * 60 * 1000), + env.DB.prepare(`INSERT INTO device_sign_in_requests + (id, approval_token_hash, poll_token_hash, expires_at, created_at) + VALUES (?, ?, ?, ?, ?)`).bind(id, await hashToken(approvalToken), await hashToken(pollToken), now + linkLifetimeMs, now), + ]); + const approvalUrl = new URL("/device-link", origin); + approvalUrl.searchParams.set("id", id); + approvalUrl.searchParams.set("token", approvalToken); + return json({ id, pollToken, approvalUrl: approvalUrl.toString(), expiresAt: now + linkLifetimeMs }, 201, cors); + } + + if (request.method === "GET") { + const url = new URL(request.url); + const id = url.searchParams.get("id") ?? ""; + const token = url.searchParams.get("token") ?? ""; + validateLinkCredentials(id, token); + const now = Date.now(); + const row = await env.DB.prepare(`SELECT approved_uid AS approvedUid, expires_at AS expiresAt, + denied_at AS deniedAt, consumed_at AS consumedAt FROM device_sign_in_requests + WHERE id = ? AND poll_token_hash = ?`).bind(id, await hashToken(token)).first<{ + approvedUid: string | null; expiresAt: number; deniedAt: number | null; consumedAt: number | null; + }>(); + if (!row) throw new Error("Invalid device sign-in request"); + if (row.expiresAt <= now) throw new Error("This QR code has expired"); + if (row.deniedAt) throw new Error("Sign-in was denied"); + if (row.consumedAt) throw new Error("This QR code has already been used"); + if (!row.approvedUid) return json({ status: "pending" }, 200, cors); + if (!env.FIREBASE_SERVICE_ACCOUNT_EMAIL || !env.FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY) throw new Error("QR sign-in is not configured"); + const profile = await env.DB.prepare("SELECT uid FROM users WHERE uid = ?").bind(row.approvedUid).first(); + if (!profile) throw new Error("Forbidden"); + const customToken = await createFirebaseCustomToken(row.approvedUid, env.FIREBASE_SERVICE_ACCOUNT_EMAIL, env.FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY); + const claimed = await env.DB.prepare("UPDATE device_sign_in_requests SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL").bind(now, id).run(); + if (claimed.meta.changes !== 1) throw new Error("This QR code has already been used"); + return json({ status: "approved", customToken }, 200, cors); + } + + if (request.method === "PATCH" || request.method === "DELETE") { + const uid = await verifyFirebaseToken(bearerToken(request), env.FIREBASE_PROJECT_ID); + const profile = await env.DB.prepare("SELECT uid FROM users WHERE uid = ?").bind(uid).first(); + if (!profile) throw new Error("Forbidden"); + const body = await request.json<{ id?: unknown; token?: unknown }>().catch(() => ({} as { id?: unknown; token?: unknown })); + const id = typeof body.id === "string" ? body.id : ""; + const token = typeof body.token === "string" ? body.token : ""; + validateLinkCredentials(id, token); + const now = Date.now(); + const result = request.method === "PATCH" + ? await env.DB.prepare(`UPDATE device_sign_in_requests SET approved_uid = ?, approved_at = ? + WHERE id = ? AND approval_token_hash = ? AND approved_uid IS NULL AND denied_at IS NULL + AND consumed_at IS NULL AND expires_at > ?`).bind(uid, now, id, await hashToken(token), now).run() + : await env.DB.prepare(`UPDATE device_sign_in_requests SET denied_at = ? + WHERE id = ? AND approval_token_hash = ? AND approved_uid IS NULL AND denied_at IS NULL + AND consumed_at IS NULL AND expires_at > ?`).bind(now, id, await hashToken(token), now).run(); + if (result.meta.changes !== 1) throw new Error("This QR code is invalid, expired, or already answered"); + return json({ status: request.method === "PATCH" ? "approved" : "denied" }, 200, cors); + } + + return methodNotAllowed(cors, "GET, POST, PATCH, DELETE, OPTIONS"); +} + +async function consumeRateLimit(db: D1Database, key: string, windowMs: number, maximum: number) { + const now = Date.now(); + const row = await db.prepare("SELECT window_started_at AS windowStartedAt, attempts FROM auth_rate_limits WHERE key = ?").bind(key).first<{ windowStartedAt: number; attempts: number }>(); + if (!row || now - row.windowStartedAt >= windowMs) { + await db.prepare(`INSERT INTO auth_rate_limits (key, window_started_at, attempts) VALUES (?, ?, 1) + ON CONFLICT(key) DO UPDATE SET window_started_at = excluded.window_started_at, attempts = 1`).bind(key, now).run(); + return { allowed: true, retryAfterMs: 0 }; + } + if (row.attempts >= maximum) return { allowed: false, retryAfterMs: Math.max(1000, windowMs - (now - row.windowStartedAt)) }; + await db.prepare("UPDATE auth_rate_limits SET attempts = attempts + 1 WHERE key = ?").bind(key).run(); + return { allowed: true, retryAfterMs: 0 }; +} + +function randomToken() { + const bytes = crypto.getRandomValues(new Uint8Array(32)); + return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +} + +async function hashToken(token: string) { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +function validateLinkCredentials(id: string, token: string) { + if (!idPattern.test(id) || !tokenPattern.test(token)) throw new Error("Invalid device sign-in request"); +} + +function bearerToken(request: Request) { + const authorization = request.headers.get("Authorization"); + if (!authorization?.startsWith("Bearer ")) throw new Error("Unauthorized"); + return authorization.slice("Bearer ".length); +} + +function json(body: unknown, status: number, headers: Headers) { + const next = new Headers(headers); + next.set("Content-Type", "application/json; charset=utf-8"); + next.set("Cache-Control", "no-store"); + return new Response(JSON.stringify(body), { status, headers: next }); +} + +function methodNotAllowed(headers: Headers, allow: string) { + const next = new Headers(headers); + next.set("Allow", allow); + return new Response("Method not allowed", { status: 405, headers: next }); +} diff --git a/workers/api/src/core.ts b/workers/api/src/core.ts index 881d469..06be525 100644 --- a/workers/api/src/core.ts +++ b/workers/api/src/core.ts @@ -102,19 +102,19 @@ function allowedTaskPatch(task: Task, changes: Record, actor: U const keys = Object.keys(changes); const only = (allowed: string[]) => keys.every((key) => allowed.includes(key)); if (only(["status", "order", "updatedAt", "history"])) return true; - const contentKeys = new Set(["title", "description"]); + const contentKeys = new Set(["title", "description", "priority", "dueDate", "pointOfContactUid", "blockedReason", "blockedDetails", "prerequisiteTaskIds", "links"]); const certificationKeys = new Set(["requiredCertificationIds", "requireAllCertifications"]); - if (only(["title", "description", "requiredCertificationIds", "requireAllCertifications", "updatedAt"])) { + if (only([...contentKeys, ...certificationKeys, "updatedAt"])) { const changesContent = keys.some((key) => contentKeys.has(key)); const changesCertifications = keys.some((key) => certificationKeys.has(key)); - return (!changesContent || canEditTaskContent(task, actor)) && (!changesCertifications || actor.role === "student"); + return (!changesContent || canEditTaskContent(task, actor)) && (!changesCertifications || canEditTaskContent(task, actor)); } if (only(["comments", "updatedAt"])) { const next = Array.isArray(changes.comments) ? changes.comments as Array> : []; const added = next.at(-1); return next.length === task.comments.length + 1 && JSON.stringify(next.slice(0, -1)) === JSON.stringify(task.comments) && added?.authorUid === actor.uid && typeof added.body === "string" && added.body.length > 0 && added.body.length <= 2000; } - if (only(["attachments", "updatedAt"]) && task.assigneeUids.includes(actor.uid)) { + if (only(["attachments", "updatedAt"]) && canEditTaskContent(task, actor)) { const next = Array.isArray(changes.attachments) ? changes.attachments as Array> : []; const beforeIds = new Set(task.attachments.map((item) => item.id)); const afterIds = new Set(next.map((item) => item.id)); const delta = [...new Set([...beforeIds, ...afterIds])].filter((id) => beforeIds.has(id) !== afterIds.has(id)); @@ -124,6 +124,7 @@ function allowedTaskPatch(task: Task, changes: Record, actor: U const next = Array.isArray(changes.assigneeUids) ? changes.assigneeUids.filter((value): value is string => typeof value === "string") : []; const before = new Set(task.assigneeUids); const after = new Set(next); const changed = [...new Set([...before, ...after])].filter((uid) => before.has(uid) !== after.has(uid)); + if (canEditTaskContent(task, actor)) return true; if (changed.length !== 1 || changed[0] !== actor.uid) return false; if (!before.has(actor.uid) && after.has(actor.uid)) { const required = Array.isArray(task.requiredCertificationIds) ? task.requiredCertificationIds.filter((id): id is string => typeof id === "string") : []; diff --git a/workers/api/src/firebase-auth.ts b/workers/api/src/firebase-auth.ts new file mode 100644 index 0000000..4c3c219 --- /dev/null +++ b/workers/api/src/firebase-auth.ts @@ -0,0 +1,28 @@ +import { createRemoteJWKSet, importPKCS8, jwtVerify, SignJWT } from "jose"; + +const firebaseKeys = createRemoteJWKSet( + new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com"), +); + +export async function verifyFirebaseToken(token: string, projectId: string) { + const { payload } = await jwtVerify(token, firebaseKeys, { + algorithms: ["RS256"], + audience: projectId, + issuer: `https://securetoken.google.com/${projectId}`, + }); + if (!payload.sub) throw new Error("Unauthorized"); + return payload.sub; +} + +export async function createFirebaseCustomToken(uid: string, serviceAccountEmail: string, privateKeyPem: string) { + const now = Math.floor(Date.now() / 1000); + const privateKey = await importPKCS8(privateKeyPem.replaceAll("\\n", "\n"), "RS256"); + return new SignJWT({ uid }) + .setProtectedHeader({ alg: "RS256", typ: "JWT" }) + .setIssuer(serviceAccountEmail) + .setSubject(serviceAccountEmail) + .setAudience("https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit") + .setIssuedAt(now) + .setExpirationTime(now + 60 * 60) + .sign(privateKey); +} diff --git a/workers/api/src/index.ts b/workers/api/src/index.ts index f4a6dff..3c1eaaa 100644 --- a/workers/api/src/index.ts +++ b/workers/api/src/index.ts @@ -1,11 +1,12 @@ /// -import { createRemoteJWKSet, jwtVerify } from "jose"; import { handleOperations, isOperationsRoute } from "./operations"; import { handleCore, isCoreRoute } from "./core"; import { handleNotifications, isNotificationRoute, sendDailyEmailDigests } from "./notifications"; +import { handleAuth, isAuthRoute, type AuthEnv } from "./auth"; +import { verifyFirebaseToken } from "./firebase-auth"; -interface Env { +interface Env extends AuthEnv { ATTACHMENTS: R2Bucket; DB: D1Database; FIREBASE_PROJECT_ID: string; @@ -17,10 +18,6 @@ interface Env { RESEND_API_KEY?: string; RESEND_FROM?: string; } - -const firebaseKeys = createRemoteJWKSet( - new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com"), -); const attachmentRoute = /^\/attachments\/([^/]+)\/([^/]+)\/([^/]+)$/; const certificationRoute = /^\/certifications(?:\/([^/]+))?$/; const maxAttachmentSize = 20 * 1024 * 1024; @@ -42,6 +39,10 @@ export default { return json({ ok: true }, 200, cors); } + if (isAuthRoute(url.pathname)) { + return handleAuth(request, env, cors); + } + if (isCoreRoute(url.pathname)) { try { const token = bearerToken(request); @@ -218,16 +219,6 @@ function certificationUpsert(db: D1Database, certification: CertificationRow) { .bind(certification.id, certification.name, certification.description, certification.subteam, new Date().toISOString()); } -async function verifyFirebaseToken(token: string, projectId: string) { - const { payload } = await jwtVerify(token, firebaseKeys, { - algorithms: ["RS256"], - audience: projectId, - issuer: `https://securetoken.google.com/${projectId}`, - }); - if (!payload.sub) throw new Error("Unauthorized"); - return payload.sub; -} - async function requireCoach(uid: string, env: Env) { const profile = await fetchD1Profile(env.DB, uid); if (profile?.role !== "coach") throw new Error("Forbidden"); diff --git a/workers/api/src/notifications.ts b/workers/api/src/notifications.ts index 53a6a8d..7967dce 100644 --- a/workers/api/src/notifications.ts +++ b/workers/api/src/notifications.ts @@ -1,6 +1,6 @@ /// -import webpush from "web-push"; +import { sendNotification, setVapidDetails } from "web-push"; export interface NotificationEnv { DB: D1Database; @@ -123,13 +123,13 @@ export async function notifyUsers(env: NotificationEnv, recipientUids: string[], VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`).bind(crypto.randomUUID(), uid, notification.type, notification.title, notification.body, notification.taskId ?? null, createdAt))); if (!env.VAPID_PUBLIC_KEY || !env.VAPID_PRIVATE_KEY || !env.VAPID_SUBJECT) return; - webpush.setVapidDetails(env.VAPID_SUBJECT, env.VAPID_PUBLIC_KEY, env.VAPID_PRIVATE_KEY); + setVapidDetails(env.VAPID_SUBJECT, env.VAPID_PUBLIC_KEY, env.VAPID_PRIVATE_KEY); const placeholders = uniqueUids.map(() => "?").join(","); const subscriptions = await env.DB.prepare(`SELECT endpoint, uid, p256dh, auth FROM push_subscriptions WHERE uid IN (${placeholders}) AND uid IN (SELECT uid FROM notification_preferences WHERE push_enabled = 1)`).bind(...uniqueUids).all<{ endpoint: string; uid: string; p256dh: string; auth: string }>(); await Promise.all(subscriptions.results.map(async (subscription) => { try { - await webpush.sendNotification({ endpoint: subscription.endpoint, keys: { p256dh: subscription.p256dh, auth: subscription.auth } }, JSON.stringify(notification)); + await sendNotification({ endpoint: subscription.endpoint, keys: { p256dh: subscription.p256dh, auth: subscription.auth } }, JSON.stringify(notification)); } catch (error) { const statusCode = typeof error === "object" && error && "statusCode" in error ? Number(error.statusCode) : 0; if (statusCode === 404 || statusCode === 410) await env.DB.prepare("DELETE FROM push_subscriptions WHERE endpoint = ?").bind(subscription.endpoint).run();