From 91609d15aae0614872d3e46fb4d4cb649dea5ba3 Mon Sep 17 00:00:00 2001 From: youbin Date: Thu, 2 Apr 2026 21:16:23 +0800 Subject: [PATCH] add office 365 mail console --- .dockerignore | 4 + .env.example | 6 + .gitignore | 3 + Dockerfile | 12 + README.md | 98 ++++++ docker-compose.yml | 11 + package-lock.json | 843 +++++++++++++++++++++++++++++++++++++++++++++ package.json | 17 + public/app.js | 306 ++++++++++++++++ public/index.html | 78 +++++ public/login.css | 123 +++++++ public/login.html | 33 ++ public/styles.css | 295 ++++++++++++++++ server.js | 458 ++++++++++++++++++++++++ 14 files changed, 2287 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/app.js create mode 100644 public/index.html create mode 100644 public/login.css create mode 100644 public/login.html create mode 100644 public/styles.css create mode 100644 server.js diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8609355 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +node_modules +npm-debug.log* +.git +.env diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..61a0e38 --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +TENANT_ID=your-tenant-id +CLIENT_ID=your-client-id +CLIENT_SECRET=your-client-secret +MAILBOX_ADDRESS= +ACCESS_PASSWORD=change-this-password +PORT=3000 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..03c5ccf --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +.env +npm-debug.log* diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..3e035ff --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM node:18-alpine + +WORKDIR /app + +COPY package*.json ./ +RUN npm install --omit=dev + +COPY . ./ + +EXPOSE 3000 + +CMD ["npm", "start"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..efe3e62 --- /dev/null +++ b/README.md @@ -0,0 +1,98 @@ +# Office 365 Mail Console + +一个最小化的 Web 控制台,用于: + +- 列出租户中的成员账号 +- 点击账号后读取该账号收件箱中的最新一封邮件 + +## 环境要求 + +- Node.js 18+ +- Microsoft Entra 应用注册 +- 已授予并管理员同意以下 Microsoft Graph Application Permissions: + - `Mail.Read` + - `User.Read.All` + +## 配置 + +1. 复制 `.env.example` 为 `.env` +2. 填入以下值: + +```env +TENANT_ID=your-tenant-id +CLIENT_ID=your-client-id +CLIENT_SECRET=your-client-secret +MAILBOX_ADDRESS= +ACCESS_PASSWORD=change-this-password +PORT=3000 +``` + +说明: + +- `MAILBOX_ADDRESS` 为可选默认选中账号。页面首次加载完成后,如果能在租户中找到这个邮箱地址,会自动展示它的最新邮件。 +- `ACCESS_PASSWORD` 为访问控制台所需的口令。设置后,用户必须先输入该密码才能打开页面和访问 API。 +- 读取租户账号和邮件实际依赖的是 `TENANT_ID`、`CLIENT_ID`、`CLIENT_SECRET`。 + +### Entra ID (Azure AD) 应用配置参数说明 + +| 参数名 | 必填 | 说明 | 获取方式 | +| --- | --- | --- | --- | +| `TENANT_ID` | 是 | Entra 租户 ID,用于向租户申请 Graph 访问令牌 | Azure AD 应用注册概览页 | +| `CLIENT_ID` | 是 | 应用程序(客户端) ID,用于标识当前应用 | Azure AD 应用注册概览页 | +| `CLIENT_SECRET` | 是 | 应用客户端密钥,用于应用身份认证 | Azure AD「证书和密码」 | +| `Mail.Read` | 是 | 读取邮箱内容所需的 Microsoft Graph 应用程序权限 | Azure AD「API 权限」 | +| `User.Read.All` | 是 | 列出租户成员账号所需的 Microsoft Graph 应用程序权限 | Azure AD「API 权限」 | +| `ACCESS_PASSWORD` | 可选 | 控制台访问密码,设置后访问页面前必须先登录 | 自定义 | + +补充说明: + +- 这两个 Graph 权限都要选择「应用程序权限」,并完成管理员同意。 +- 本项目采用 `client_credentials` 模式,不需要配置重定向 URI。 +- 如果只配置 `Mail.Read`,页面可以读邮件,但无法列出所有账号;如果只配置 `User.Read.All`,页面可以列出账号,但无法读取邮件正文。 + +## 运行 + +```bash +npm install +npm start +``` + +启动后访问:`http://localhost:3000` + +如果已设置 `ACCESS_PASSWORD`,首次访问会先进入登录页。 + +## Docker Compose 部署 + +```bash +# 1. 复制配置文件 +cp .env.example .env + +# 2. 填入 .env 中的 TENANT_ID / CLIENT_ID / CLIENT_SECRET / ACCESS_PASSWORD + +# 3. 构建并启动 +docker compose up -d --build + +# 4. 查看日志 +docker compose logs -f + +# 5. 停止服务 +docker compose down +``` + +默认映射端口:`3000` + +如果需要修改外部端口,调整 `docker-compose.yml` 中的 `ports` 映射即可。 + +## 接口 + +- `GET /api/users` + - 返回租户成员账号列表 +- `GET /api/users/:userId/latest-email` + - 返回该账号收件箱最新一封邮件 + +## 注意事项 + +- 账号列表依赖 `User.Read.All`,否则无法拉取租户用户。 +- 某些账号虽然存在于租户中,但不一定拥有 Exchange 邮箱;这类账号读取邮件时可能返回空结果或权限错误。 +- 当前页面以邮件全文为主,保留发件人和接收时间,并显示完整 HTML / 纯文本正文。 +- 当前版本使用基于 Cookie 的本地访问验证;更换 `ACCESS_PASSWORD` 后,旧登录会话会失效。 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..6c5ea98 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,11 @@ +services: + office365-mail-console: + build: + context: . + dockerfile: Dockerfile + container_name: office365-mail-console + env_file: + - .env + ports: + - "3000:3000" + restart: unless-stopped diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..b64a367 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,843 @@ +{ + "name": "office365-mail-console", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "office365-mail-console", + "version": "1.0.0", + "dependencies": { + "dotenv": "^16.4.5", + "express": "^4.21.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", + "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "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/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..faa20db --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "office365-mail-console", + "version": "1.0.0", + "private": true, + "description": "Web console for listing Microsoft 365 accounts and reading the latest inbox message.", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "engines": { + "node": ">=18" + }, + "dependencies": { + "dotenv": "^16.4.5", + "express": "^4.21.2" + } +} diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..2568aef --- /dev/null +++ b/public/app.js @@ -0,0 +1,306 @@ +const state = { + users: [], + filteredUsers: [], + selectedUser: null, + lastMessage: null, + defaultMailboxAddress: '', + initialAutoSelected: false, +}; + +const elements = { + userList: document.getElementById('user-list'), + userCount: document.getElementById('user-count'), + searchInput: document.getElementById('search-input'), + refreshUsers: document.getElementById('refresh-users'), + refreshMail: document.getElementById('refresh-mail'), + emptyState: document.getElementById('empty-state'), + mailPanel: document.getElementById('mail-panel'), + mailStatus: document.getElementById('mail-status'), + mailEmpty: document.getElementById('mail-empty'), + mailCard: document.getElementById('mail-card'), + mailFrom: document.getElementById('mail-from'), + mailTime: document.getElementById('mail-time'), + mailPreview: document.getElementById('mail-preview'), + mailBodyFrame: document.getElementById('mail-body-frame'), +}; + +function formatIdentity(user) { + return user.mail || user.userPrincipalName || 'No mailbox address'; +} + +function formatRecipient(recipient) { + if (!recipient || (!recipient.name && !recipient.address)) { + return '-'; + } + + return recipient.name && recipient.address + ? `${recipient.name} <${recipient.address}>` + : recipient.name || recipient.address; +} + +function formatRecipientList(recipients) { + if (!recipients || recipients.length === 0) { + return '-'; + } + + return recipients.map(formatRecipient).join(', '); +} + +function setStatus(message, tone = 'neutral') { + elements.mailStatus.textContent = message; + elements.mailStatus.className = `status ${tone}`; +} + +function clearStatus() { + elements.mailStatus.textContent = ''; + elements.mailStatus.className = 'status hidden'; +} + +function renderUserList() { + elements.userCount.textContent = `共 ${state.filteredUsers.length} 个账号`; + + if (state.filteredUsers.length === 0) { + elements.userList.innerHTML = '
没有匹配的账号
'; + return; + } + + const fragment = document.createDocumentFragment(); + + state.filteredUsers.forEach((user) => { + const button = document.createElement('button'); + button.type = 'button'; + button.className = `user-item${state.selectedUser?.id === user.id ? ' active' : ''}`; + button.dataset.userId = user.id; + button.innerHTML = ` + ${escapeHtml(user.displayName)} + ${escapeHtml(formatIdentity(user))} + ${escapeHtml(user.department || user.jobTitle || '未设置部门 / 职位')} + `; + fragment.appendChild(button); + }); + + elements.userList.innerHTML = ''; + elements.userList.appendChild(fragment); +} + +function applyUserFilter() { + const keyword = elements.searchInput.value.trim().toLowerCase(); + state.filteredUsers = state.users.filter((user) => { + if (!keyword) { + return true; + } + + return [user.displayName, user.mail, user.userPrincipalName, user.department, user.jobTitle] + .filter(Boolean) + .some((value) => value.toLowerCase().includes(keyword)); + }); + + renderUserList(); +} + +function showMailPanel() { + elements.emptyState.classList.add('hidden'); + elements.mailPanel.classList.remove('hidden'); +} + +function renderEmptyMail(message) { + showMailPanel(); + setStatus(message, 'warning'); + elements.mailCard.classList.add('hidden'); + elements.mailEmpty.classList.remove('hidden'); +} + +function buildEmailDocument(content) { + const baseHeadContent = ` + + + + `; + + if (/]/i.test(content)) { + if (/]/i.test(content)) { + return content.replace(/]*)>/i, `${baseHeadContent}`); + } + + return content.replace(/]*)>/i, `${baseHeadContent}`); + } + + return ` + + +${baseHeadContent} + + ${content} + `; +} + +function renderMessageBody(message) { + const bodyContent = message.body?.content || message.bodyPreview || '暂无正文'; + const contentType = (message.body?.contentType || 'text').toLowerCase(); + const isHtml = contentType === 'html'; + + if (isHtml) { + elements.mailBodyFrame.classList.remove('hidden'); + elements.mailPreview.classList.add('hidden'); + elements.mailBodyFrame.srcdoc = buildEmailDocument(bodyContent); + return; + } + + elements.mailBodyFrame.classList.add('hidden'); + elements.mailBodyFrame.srcdoc = ''; + elements.mailPreview.classList.remove('hidden'); + elements.mailPreview.textContent = bodyContent; +} + +function renderMessage(message) { + showMailPanel(); + clearStatus(); + elements.mailEmpty.classList.add('hidden'); + elements.mailCard.classList.remove('hidden'); + + elements.mailFrom.textContent = formatRecipient(message.from); + elements.mailTime.textContent = message.receivedDateTime + ? new Date(message.receivedDateTime).toLocaleString('zh-CN', { hour12: false }) + : '-'; + renderMessageBody(message); +} + +async function requestJson(url) { + const response = await fetch(url); + const payload = await response.json().catch(() => ({})); + + if (response.status === 401) { + window.location.assign('/login'); + throw new Error('Authentication required'); + } + + if (!response.ok) { + throw new Error(payload.error || 'Request failed'); + } + + return payload; +} + +async function loadUsers() { + elements.userCount.textContent = '加载账号中...'; + elements.refreshUsers.disabled = true; + + try { + const payload = await requestJson('/api/users'); + state.users = payload.users || []; + state.defaultMailboxAddress = payload.defaultMailboxAddress || ''; + applyUserFilter(); + + if (state.selectedUser) { + const nextSelected = state.users.find((user) => user.id === state.selectedUser.id); + state.selectedUser = nextSelected || null; + renderUserList(); + } + + if (!state.selectedUser && !state.initialAutoSelected && state.defaultMailboxAddress) { + const normalizedDefault = state.defaultMailboxAddress.toLowerCase(); + const defaultUser = state.users.find((user) => { + return [user.mail, user.userPrincipalName] + .filter(Boolean) + .some((value) => value.toLowerCase() === normalizedDefault); + }); + + if (defaultUser) { + state.initialAutoSelected = true; + loadLatestEmail(defaultUser.id); + } + } + } catch (error) { + elements.userList.innerHTML = `
${escapeHtml(error.message)}
`; + elements.userCount.textContent = '加载失败'; + } finally { + elements.refreshUsers.disabled = false; + } +} + +async function loadLatestEmail(userId) { + const user = state.users.find((entry) => entry.id === userId); + + if (!user) { + return; + } + + state.selectedUser = user; + state.lastMessage = null; + renderUserList(); + showMailPanel(); + elements.mailEmpty.classList.add('hidden'); + elements.mailCard.classList.add('hidden'); + setStatus('正在读取最新邮件...', 'loading'); + elements.refreshMail.disabled = true; + + try { + const payload = await requestJson(`/api/users/${encodeURIComponent(userId)}/latest-email`); + state.lastMessage = payload.message; + + if (!payload.message) { + renderEmptyMail('该账号收件箱当前没有邮件。'); + return; + } + + renderMessage(payload.message); + } catch (error) { + renderEmptyMail(error.message); + } finally { + elements.refreshMail.disabled = false; + } +} + +function escapeHtml(value) { + return String(value) + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); +} + +elements.userList.addEventListener('click', (event) => { + const button = event.target.closest('[data-user-id]'); + + if (!button) { + return; + } + + loadLatestEmail(button.dataset.userId); +}); + +elements.searchInput.addEventListener('input', () => { + applyUserFilter(); +}); + +elements.refreshUsers.addEventListener('click', () => { + loadUsers(); +}); + +elements.refreshMail.addEventListener('click', () => { + if (state.selectedUser) { + loadLatestEmail(state.selectedUser.id); + } +}); + +loadUsers(); diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..0468d40 --- /dev/null +++ b/public/index.html @@ -0,0 +1,78 @@ + + + + + + Office 365 Mail Console + + + +
+ + +
+
+

Latest Mail

+

选择一个账号

+

右侧会显示该账号收件箱最新一封邮件的核心信息。

+
+ + +
+
+ + + + diff --git a/public/login.css b/public/login.css new file mode 100644 index 0000000..c93f6cc --- /dev/null +++ b/public/login.css @@ -0,0 +1,123 @@ +:root { + color-scheme: dark; + --bg: #07111f; + --panel: rgba(10, 22, 41, 0.9); + --line: rgba(154, 180, 220, 0.2); + --text: #eef4ff; + --muted: #94a6c4; + --accent: #6ee7ff; + --danger: #ff9c9c; + --shadow: 0 24px 80px rgba(0, 0, 0, 0.38); + font-family: Inter, "Segoe UI", system-ui, sans-serif; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-height: 100vh; + color: var(--text); + background: + radial-gradient(circle at top left, rgba(59, 169, 255, 0.18), transparent 24%), + radial-gradient(circle at bottom right, rgba(110, 231, 255, 0.1), transparent 28%), + linear-gradient(180deg, #06101d 0%, #09172c 100%); +} + +body, +input, +button { + font: inherit; +} + +.auth-shell { + min-height: 100vh; + display: grid; + place-items: center; + padding: 24px; +} + +.auth-card { + width: min(440px, 100%); + padding: 32px; + border: 1px solid var(--line); + border-radius: 24px; + background: var(--panel); + box-shadow: var(--shadow); + backdrop-filter: blur(20px); +} + +.eyebrow { + margin: 0 0 8px; + color: var(--accent); + text-transform: uppercase; + letter-spacing: 0.12em; + font-size: 12px; +} + +h1 { + margin: 0; + font-size: 32px; +} + +.auth-copy { + margin: 12px 0 0; + color: var(--muted); + line-height: 1.7; +} + +.auth-error { + margin-top: 18px; + padding: 12px 14px; + border-radius: 14px; + border: 1px solid rgba(255, 156, 156, 0.2); + background: rgba(255, 156, 156, 0.08); + color: var(--danger); +} + +.auth-form { + display: grid; + gap: 10px; + margin-top: 22px; +} + +.auth-form label { + color: var(--muted); + font-size: 14px; +} + +.auth-form input, +.auth-form button { + border: 1px solid var(--line); + border-radius: 14px; +} + +.auth-form input { + padding: 13px 14px; + color: var(--text); + background: rgba(14, 28, 50, 0.9); +} + +.auth-form button { + margin-top: 6px; + padding: 12px 14px; + color: #07213c; + font-weight: 700; + cursor: pointer; + background: linear-gradient(135deg, var(--accent), #89f0ff); +} + +.hidden { + display: none; +} + +@media (max-width: 640px) { + .auth-card { + padding: 24px; + } + + h1 { + font-size: 26px; + } +} diff --git a/public/login.html b/public/login.html new file mode 100644 index 0000000..393a49f --- /dev/null +++ b/public/login.html @@ -0,0 +1,33 @@ + + + + + + 访问验证 + + + +
+
+

Protected Access

+

输入访问密码

+

验证通过后才能进入 Office 365 邮件控制台。

+ + + +
+ + + +
+
+
+ + + + diff --git a/public/styles.css b/public/styles.css new file mode 100644 index 0000000..10db22d --- /dev/null +++ b/public/styles.css @@ -0,0 +1,295 @@ +:root { + color-scheme: dark; + --bg: #07111f; + --panel: rgba(9, 20, 38, 0.88); + --panel-strong: rgba(12, 28, 52, 0.96); + --line: rgba(154, 180, 220, 0.18); + --text: #eef4ff; + --muted: #94a6c4; + --accent: #6ee7ff; + --accent-strong: #3ba9ff; + --warning: #ffcf66; + --danger: #ff8e8e; + --shadow: 0 24px 80px rgba(0, 0, 0, 0.36); + font-family: Inter, "Segoe UI", system-ui, sans-serif; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-height: 100vh; + color: var(--text); + background: + radial-gradient(circle at top left, rgba(59, 169, 255, 0.2), transparent 24%), + radial-gradient(circle at bottom right, rgba(110, 231, 255, 0.12), transparent 28%), + linear-gradient(180deg, #06101d 0%, #09172c 100%); +} + +button, +input { + font: inherit; +} + +.app-shell { + display: grid; + grid-template-columns: 360px minmax(0, 1fr); + min-height: 100vh; +} + +.sidebar, +.content { + padding: 24px; +} + +.sidebar { + border-right: 1px solid var(--line); + background: rgba(7, 17, 31, 0.72); + backdrop-filter: blur(18px); +} + +.sidebar-header h1, +.panel h2, +.mail-card h3 { + margin: 0; +} + +.sidebar-copy, +.muted, +.label, +.user-address, +.user-meta, +.user-empty, +.status, +.empty-block p { + color: var(--muted); +} + +.eyebrow { + margin: 0 0 8px; + color: var(--accent); + text-transform: uppercase; + letter-spacing: 0.12em; + font-size: 12px; +} + +.search-box { + display: grid; + gap: 8px; + margin: 24px 0 16px; +} + +.search-box input, +button { + border: 1px solid var(--line); + border-radius: 14px; + color: var(--text); + background: rgba(15, 28, 51, 0.8); +} + +.search-box input { + padding: 12px 14px; +} + +button { + cursor: pointer; + padding: 11px 14px; + transition: border-color 120ms ease, transform 120ms ease, background 120ms ease; +} + +button:hover:not(:disabled) { + border-color: rgba(110, 231, 255, 0.5); + background: rgba(18, 38, 68, 0.92); +} + +button:disabled { + cursor: wait; + opacity: 0.7; +} + +.list-meta, +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.user-list { + display: grid; + gap: 10px; + margin-top: 14px; + max-height: calc(100vh - 245px); + overflow: auto; + padding-right: 4px; +} + +.user-item, +.panel, +.mail-card { + border: 1px solid var(--line); + border-radius: 20px; + background: var(--panel); + box-shadow: var(--shadow); +} + +.user-item { + width: 100%; + padding: 14px; + text-align: left; + display: grid; + gap: 6px; +} + +.user-item.active { + border-color: rgba(110, 231, 255, 0.55); + background: linear-gradient(180deg, rgba(19, 39, 71, 0.96), rgba(11, 24, 45, 0.96)); +} + +.user-name { + font-weight: 700; +} + +.user-address, +.user-meta, +.label { + font-size: 13px; +} + +.content { + display: flex; +} + +.panel { + width: 100%; + padding: 28px; + background: var(--panel-strong); +} + +.panel-intro { + display: grid; + place-content: center; + min-height: calc(100vh - 48px); +} + +.status { + margin: 20px 0; + padding: 12px 14px; + border-radius: 14px; + border: 1px solid var(--line); + background: rgba(255, 255, 255, 0.03); +} + +.status.loading { + color: var(--accent); +} + +.status.warning { + color: var(--warning); +} + +.status.neutral { + color: var(--muted); +} + +.mail-card { + margin-top: 20px; + padding: 22px; +} + +.mail-summary { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px; + margin-bottom: 16px; + padding-bottom: 16px; + border-bottom: 1px solid var(--line); +} + +.mail-summary p, +.preview-block pre, +.empty-block h3, +.empty-block p { + margin: 6px 0 0; +} + +.preview-block { + margin-top: 0; +} + +.preview-block pre { + white-space: pre-wrap; + word-break: break-word; + line-height: 1.6; + color: #dce7ff; +} + +.mail-body-frame { + width: 100%; + min-height: 720px; + margin-top: 12px; + border: 1px solid var(--line); + border-radius: 14px; + background: #ffffff; +} + +.mono { + font-family: "SFMono-Regular", Consolas, monospace; +} + +.empty-block { + margin-top: 20px; + padding: 24px; + border: 1px dashed var(--line); + border-radius: 18px; +} + +.hidden { + display: none; +} + +a { + color: var(--accent); +} + +@media (max-width: 980px) { + .app-shell { + grid-template-columns: 1fr; + } + + .sidebar { + border-right: 0; + border-bottom: 1px solid var(--line); + } + + .user-list { + max-height: 320px; + } + + .panel-intro { + min-height: auto; + } +} + +@media (max-width: 720px) { + .sidebar, + .content { + padding: 16px; + } + + .panel { + padding: 20px; + } + + .mail-summary { + grid-template-columns: 1fr; + } + + .panel-header, + .list-meta { + align-items: flex-start; + flex-direction: column; + } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..3c35e9d --- /dev/null +++ b/server.js @@ -0,0 +1,458 @@ +const path = require('path'); +const { execFile } = require('child_process'); +const crypto = require('crypto'); +const { promisify } = require('util'); + +const dotenv = require('dotenv'); +const express = require('express'); + +dotenv.config(); + +const { + TENANT_ID, + CLIENT_ID, + CLIENT_SECRET, + MAILBOX_ADDRESS = '', + ACCESS_PASSWORD = '', + PORT = '3000', +} = process.env; + +const requiredEnv = { + TENANT_ID, + CLIENT_ID, + CLIENT_SECRET, +}; + +const missingEnv = Object.entries(requiredEnv) + .filter(([, value]) => !value) + .map(([key]) => key); + +if (missingEnv.length > 0) { + console.error(`Missing required environment variables: ${missingEnv.join(', ')}`); + process.exit(1); +} + +const app = express(); +const GRAPH_BASE_URL = 'https://graph.microsoft.com/v1.0'; +const APP_PUBLIC_DIR = path.join(__dirname, 'public'); +const AUTH_COOKIE_NAME = 'office365_mail_auth'; +const AUTH_SESSION_TTL_MS = 12 * 60 * 60 * 1000; +const execFileAsync = promisify(execFile); +const authEnabled = Boolean(ACCESS_PASSWORD); +const authCookieSecret = authEnabled + ? crypto.createHash('sha256').update(`${TENANT_ID}:${CLIENT_ID}:${CLIENT_SECRET}:${ACCESS_PASSWORD}`).digest() + : null; +const tokenCache = { + accessToken: null, + expiresAt: 0, +}; + +function timingSafeStringEqual(left, right) { + const leftBuffer = Buffer.from(left); + const rightBuffer = Buffer.from(right); + + if (leftBuffer.length !== rightBuffer.length) { + return false; + } + + return crypto.timingSafeEqual(leftBuffer, rightBuffer); +} + +function parseCookies(cookieHeader = '') { + return cookieHeader + .split(';') + .map((segment) => segment.trim()) + .filter(Boolean) + .reduce((cookies, segment) => { + const separatorIndex = segment.indexOf('='); + + if (separatorIndex === -1) { + return cookies; + } + + const key = segment.slice(0, separatorIndex).trim(); + const value = segment.slice(separatorIndex + 1).trim(); + cookies[key] = decodeURIComponent(value); + return cookies; + }, {}); +} + +function signAuthCookiePayload(payload) { + return crypto.createHmac('sha256', authCookieSecret).update(payload).digest('hex'); +} + +function createAuthCookieValue() { + const expiresAt = String(Date.now() + AUTH_SESSION_TTL_MS); + return `${expiresAt}.${signAuthCookiePayload(expiresAt)}`; +} + +function setAuthCookie(response) { + response.setHeader( + 'Set-Cookie', + `${AUTH_COOKIE_NAME}=${encodeURIComponent(createAuthCookieValue())}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${AUTH_SESSION_TTL_MS / 1000}`, + ); +} + +function clearAuthCookie(response) { + response.setHeader( + 'Set-Cookie', + `${AUTH_COOKIE_NAME}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`, + ); +} + +function isAuthenticatedRequest(request) { + if (!authEnabled) { + return true; + } + + const token = parseCookies(request.headers.cookie)[AUTH_COOKIE_NAME]; + + if (!token) { + return false; + } + + const [expiresAt, signature] = token.split('.'); + + if (!expiresAt || !signature || !/^\d+$/.test(expiresAt)) { + return false; + } + + if (Date.now() > Number(expiresAt)) { + return false; + } + + return timingSafeStringEqual(signature, signAuthCookiePayload(expiresAt)); +} + +function isPublicAuthPath(pathname) { + return pathname === '/login' || pathname === '/login.css' || pathname === '/auth/login'; +} + +function buildGraphUrl(pathname, query = {}) { + const url = pathname.startsWith('https://') + ? new URL(pathname) + : new URL(`${GRAPH_BASE_URL}${pathname}`); + + Object.entries(query).forEach(([key, value]) => { + if (value !== undefined && value !== null && value !== '') { + url.searchParams.set(key, value); + } + }); + + return url.toString(); +} + +function parseResponseBody(text) { + if (!text) { + return null; + } + + try { + return JSON.parse(text); + } catch { + return text; + } +} + +async function curlJsonRequest(url, { method = 'GET', headers = {}, form = null } = {}) { + const args = [ + '-sS', + '-L', + '--connect-timeout', + '15', + '--max-time', + '90', + '-w', + '\n%{http_code}', + ]; + + if (method !== 'GET') { + args.push('-X', method); + } + + Object.entries(headers).forEach(([key, value]) => { + args.push('-H', `${key}: ${value}`); + }); + + if (form) { + Object.entries(form).forEach(([key, value]) => { + args.push('--data-urlencode', `${key}=${value}`); + }); + } + + args.push(url); + + try { + const { stdout } = await execFileAsync('curl', args, { + maxBuffer: 20 * 1024 * 1024, + }); + const separatorIndex = stdout.lastIndexOf('\n'); + const bodyText = separatorIndex === -1 ? stdout : stdout.slice(0, separatorIndex); + const statusText = separatorIndex === -1 ? '' : stdout.slice(separatorIndex + 1).trim(); + + return { + status: Number(statusText), + body: parseResponseBody(bodyText), + }; + } catch (error) { + const requestError = new Error('Microsoft request failed.'); + requestError.status = 502; + requestError.details = error.stderr || error.message || null; + throw requestError; + } +} + +async function getAccessToken() { + const now = Date.now(); + + if (tokenCache.accessToken && now < tokenCache.expiresAt - 60_000) { + return tokenCache.accessToken; + } + + const response = await curlJsonRequest( + `https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + form: { + client_id: CLIENT_ID, + client_secret: CLIENT_SECRET, + scope: 'https://graph.microsoft.com/.default', + grant_type: 'client_credentials', + }, + }, + ); + + if (response.status < 200 || response.status >= 300) { + const error = new Error('Failed to acquire Microsoft Graph access token.'); + error.status = response.status; + error.details = response.body; + throw error; + } + + const payload = response.body; + tokenCache.accessToken = payload.access_token; + tokenCache.expiresAt = now + (payload.expires_in || 3600) * 1000; + + return tokenCache.accessToken; +} + +async function graphRequest(pathname, query, init = {}) { + const accessToken = await getAccessToken(); + const response = await curlJsonRequest(buildGraphUrl(pathname, query), { + method: init.method || 'GET', + headers: { + Authorization: `Bearer ${accessToken}`, + ...(init.headers || {}), + }, + }); + + if (response.status < 200 || response.status >= 300) { + const error = new Error('Microsoft Graph request failed.'); + error.status = response.status; + error.details = response.body; + throw error; + } + + return response.body; +} + +async function listUsers() { + const users = []; + let nextUrl = buildGraphUrl('/users', { + '$top': '999', + '$select': 'id,displayName,mail,userPrincipalName,jobTitle,department,accountEnabled,userType', + }); + + while (nextUrl) { + const page = await graphRequest(nextUrl); + users.push(...(page.value || [])); + nextUrl = page['@odata.nextLink'] || null; + } + + return users + .filter((user) => user.accountEnabled !== false && user.userType !== 'Guest') + .map((user) => ({ + id: user.id, + displayName: user.displayName || user.userPrincipalName || user.mail || 'Unnamed user', + mail: user.mail || '', + userPrincipalName: user.userPrincipalName || '', + jobTitle: user.jobTitle || '', + department: user.department || '', + mailboxAddress: user.mail || user.userPrincipalName || '', + hasMailboxAddress: Boolean(user.mail || user.userPrincipalName), + })) + .sort((a, b) => a.displayName.localeCompare(b.displayName, 'zh-Hans-CN')); +} + +async function getUserById(userId) { + const user = await graphRequest(`/users/${encodeURIComponent(userId)}`, { + '$select': 'id,displayName,mail,userPrincipalName,jobTitle,department,accountEnabled,userType', + }); + + return { + id: user.id, + displayName: user.displayName || user.userPrincipalName || user.mail || 'Unnamed user', + mail: user.mail || '', + userPrincipalName: user.userPrincipalName || '', + jobTitle: user.jobTitle || '', + department: user.department || '', + mailboxAddress: user.mail || user.userPrincipalName || '', + hasMailboxAddress: Boolean(user.mail || user.userPrincipalName), + }; +} + +function formatRecipients(recipients = []) { + return recipients.map((recipient) => ({ + name: recipient.emailAddress?.name || '', + address: recipient.emailAddress?.address || '', + })); +} + +async function getLatestEmail(userId) { + const payload = await graphRequest(`/users/${encodeURIComponent(userId)}/mailFolders/Inbox/messages`, { + '$top': '1', + '$orderby': 'receivedDateTime desc', + '$select': 'id,subject,receivedDateTime,from,webLink,hasAttachments,isRead,toRecipients,ccRecipients,internetMessageId', + }); + + const message = payload.value?.[0]; + + if (!message) { + return null; + } + + const details = await graphRequest( + `/users/${encodeURIComponent(userId)}/messages/${encodeURIComponent(message.id)}`, + { + '$select': 'body,bodyPreview', + }, + { + headers: { + Prefer: 'outlook.body-content-type="html"', + }, + }, + ); + + return { + id: message.id, + subject: message.subject || '(No subject)', + receivedDateTime: message.receivedDateTime, + from: { + name: message.from?.emailAddress?.name || '', + address: message.from?.emailAddress?.address || '', + }, + toRecipients: formatRecipients(message.toRecipients), + ccRecipients: formatRecipients(message.ccRecipients), + body: { + contentType: details.body?.contentType || 'text', + content: details.body?.content || '', + }, + bodyPreview: details.bodyPreview || '', + webLink: message.webLink || '', + hasAttachments: Boolean(message.hasAttachments), + isRead: Boolean(message.isRead), + internetMessageId: message.internetMessageId || '', + }; +} + +function sendGraphError(response, error) { + const graphMessage = error.details?.error?.message; + const graphCode = error.details?.error?.code; + + response.status(error.status || 500).json({ + error: graphMessage || error.message || 'Unexpected server error.', + code: graphCode || 'internal_error', + details: error.details || null, + }); +} + +app.use(express.urlencoded({ extended: false })); + +app.use((request, response, next) => { + if (!authEnabled || isPublicAuthPath(request.path) || isAuthenticatedRequest(request)) { + next(); + return; + } + + if (request.path.startsWith('/api/')) { + response.status(401).json({ + error: 'Authentication required.', + code: 'auth_required', + }); + return; + } + + response.redirect('/login'); +}); + +app.get('/login', (request, response) => { + if (!authEnabled || isAuthenticatedRequest(request)) { + response.redirect('/'); + return; + } + + response.sendFile(path.join(APP_PUBLIC_DIR, 'login.html')); +}); + +app.post('/auth/login', (request, response) => { + if (!authEnabled) { + response.redirect('/'); + return; + } + + const submittedPassword = typeof request.body.password === 'string' ? request.body.password : ''; + + if (timingSafeStringEqual(submittedPassword, ACCESS_PASSWORD)) { + setAuthCookie(response); + response.redirect('/'); + return; + } + + clearAuthCookie(response); + response.redirect('/login?error=1'); +}); + +app.get('/', (_request, response) => { + response.sendFile(path.join(APP_PUBLIC_DIR, 'index.html')); +}); + +app.use(express.static(APP_PUBLIC_DIR, { index: false })); + +app.get('/api/users', async (_request, response) => { + try { + const users = await listUsers(); + response.json({ + users, + defaultMailboxAddress: MAILBOX_ADDRESS, + }); + } catch (error) { + sendGraphError(response, error); + } +}); + +app.get('/api/users/:userId/latest-email', async (request, response) => { + try { + const user = await getUserById(request.params.userId); + + if (!user.hasMailboxAddress) { + response.status(400).json({ + error: 'This account does not expose a mailbox address in Microsoft Graph.', + code: 'mailbox_not_available', + }); + return; + } + + const message = await getLatestEmail(user.id); + response.json({ user, message }); + } catch (error) { + sendGraphError(response, error); + } +}); + +app.listen(Number(PORT), () => { + console.log(`Office 365 mail console listening on http://localhost:${PORT}`); + console.log(`Access password protection: ${authEnabled ? 'enabled' : 'disabled'}`); +});