Add persistent admin password login and deploy verified release
This commit is contained in:
1 parent
beeca041ef
commit
bf424102c8
12 files changed
+319
-35
No files matched your search
+20
-7
@@ -13,14 +13,15 @@ pnpm --dir frontend build
|
||||
if ($LASTEXITCODE -ne 0) { throw "前端构建失败" }
|
||||
mvn -f .\backend\pom.xml clean package
|
||||
if ($LASTEXITCODE -ne 0) { throw "后端构建失败" }
|
||||
$env:ADMIN_TOKEN = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
|
||||
$env:ADMIN_USERNAME = 'admin'
|
||||
$env:ADMIN_PASSWORD = '<设置至少12位的管理员密码>'
|
||||
$env:COOKIE_SECURE = 'false' # 本机 HTTP 开发;HTTPS 生产保持默认 true
|
||||
$env:DEVICE_TOKEN = [Convert]::ToHexString([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
|
||||
Write-Host "管理员令牌 $env:ADMIN_TOKEN"
|
||||
Write-Host "设备令牌 $env:DEVICE_TOKEN"
|
||||
java -jar .\backend\target\vibe-launcher-backend.jar
|
||||
```
|
||||
|
||||
后端会在同一地址提供内置布局编辑器和管理 API。打开 [管理后台](http://127.0.0.1:8080/)。点击「布局发布」,填写管理员令牌,再点「读取线上布局」。保存的首个版本来自 Android 内置布局。返回画布编辑,预览效果后重新打开「布局发布」,点击「发布当前画布」。导入本地布局也可以用同一流程发布。
|
||||
后端会在同一地址提供内置布局编辑器和管理 API。打开 [管理后台](http://127.0.0.1:8080/)。点击「布局发布」,在页面上方输入账号密码登录,再点「读取线上布局」。保存的首个版本来自 Android 内置布局。返回画布编辑,预览效果后重新打开「布局发布」,点击「发布当前画布」。导入本地布局也可以用同一流程发布。
|
||||
|
||||
开发时可运行 `pnpm --dir frontend dev`,打开 Vite 给出的地址,管理 API 默认代理到本机 8080。使用其他本地端口时,在启动 Vite 前设置 `LAUNCHER_API_TARGET`。需要直接双击打开离线编辑器时可使用 `frontend/canvas.html`。
|
||||
|
||||
@@ -61,11 +62,13 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
|
||||
|
||||
手机断网、令牌无效或新布局校验失败时,继续显示本地布局。冷启动依次读取主布局、上次有效布局和内置布局,如果三个来源都不可用则显示内存兜底桌面。
|
||||
|
||||
画布的「小组件目录」与「布局发布」共用当前页面的管理员令牌。读取目录后可切换「第三方小组件」和「系统小组件」,并按组件名称、应用名称、组件类名或应用包名搜索并添加到当前页,再调整尺寸和位置。添加到画布后按正常流程发布,设备首次使用组件仍需进行 Android 授权。
|
||||
画布的「小组件目录」与「布局发布」共用浏览器登录状态。读取目录后可切换「第三方小组件」和「系统小组件」,并按组件名称、应用名称、组件类名或应用包名搜索并添加到当前页,再调整尺寸和位置。添加到画布后按正常流程发布,设备首次使用组件仍需进行 Android 授权。
|
||||
|
||||
## HTTP 接口
|
||||
|
||||
管理接口使用 `Authorization: Bearer <ADMIN_TOKEN>`。设备接口使用 `Authorization: Bearer <DEVICE_TOKEN>`。
|
||||
管理后台使用账号密码登录,HttpOnly、SameSite=Strict Cookie 保持登录 30 天,关闭浏览器和重启服务后仍可使用。退出会清除本浏览器 Cookie;修改密码会使已有登录失效。生产部署在 `vibe-launcher-auth` Secret 增加 `ADMIN_USERNAME`(默认 admin)、`ADMIN_PASSWORD`(至少 12 位),通过 HTTPS 使用,`COOKIE_SECURE` 保持默认 true。未配置密码时不启用网页登录。可选 `ADMIN_TOKEN` 兼容原有脚本。
|
||||
|
||||
`POST /api/auth/login` 接收 JSON username、password;`GET /api/auth/session` 检查登录;`POST /api/auth/logout` 退出。登录、退出及 Cookie 认证的写操作需带 `X-Launcher-Request: 1`。设备接口使用 `Authorization: Bearer <DEVICE_TOKEN>`。
|
||||
|
||||
| 方法和路径 | 用途 |
|
||||
| --- | --- |
|
||||
@@ -95,14 +98,24 @@ $env:LAUNCHER_DEVICE_TOKEN = '<设备令牌>'
|
||||
| --- | --- |
|
||||
| 服务器 | `175.178.213.60`,Debian 12,k3s 单节点,SSH 密钥登录 |
|
||||
| 命名空间 / 工作负载 | `vibe-launcher` / `deploy/vibe-launcher-backend`,单副本 `Recreate` |
|
||||
| 镜像 | `docker.io/library/vibe-launcher-backend:1.1.0-deploy7`,`imagePullPolicy: IfNotPresent` |
|
||||
| 镜像 | `docker.io/library/vibe-launcher-backend:1.1.0-deploy8`,`imagePullPolicy: IfNotPresent` |
|
||||
| 端口 | 容器 8080,Service NodePort **30830**(30800 是 youlai-boot,30810 是 tts-server,30820 是 compose-remote-server) |
|
||||
| 公网入口 | `https://api.ttstd.com/launcher/`(灰云直连源站,不走 Cloudflare);nginx 剥掉 `/launcher/` 前缀后反代 `127.0.0.1:30830` |
|
||||
| 数据 | 宿主机 `/opt/vibe-launcher/data/layouts.sqlite` 挂到容器 `/data`,Pod 重建不丢版本历史 |
|
||||
| 令牌 | 服务器 `/opt/vibe-launcher/auth.env`(root,`600`)生成 Secret `vibe-launcher-auth`,令牌不入库 |
|
||||
|
||||
Android「布局同步」的服务根地址填写 `https://api.ttstd.com/launcher`,管理后台打开 `https://api.ttstd.com/launcher/` 并填入管理员令牌。编辑器会从当前访问路径推导 API 前缀,因此本地根目录访问与线上子路径访问都可用。
|
||||
Android「布局同步」的服务根地址填写 `https://api.ttstd.com/launcher`,管理后台打开 `https://api.ttstd.com/launcher/` 并使用账号密码登录。编辑器会从当前访问路径推导 API 前缀,因此本地根目录访问与线上子路径访问都可用。
|
||||
|
||||
升级流程:本地执行 `pnpm --dir frontend build` 和 `mvn -f backend/pom.xml clean package`,再上传新 JAR 到 `/opt/vibe-launcher/target/vibe-launcher-backend.jar`,用**新 tag** 构建并导入镜像,修改 `deploy.yaml` 的 image,执行 `kubectl apply`,最后运行 `kubectl -n vibe-launcher rollout status deploy/vibe-launcher-backend --timeout=180s`。同 tag 重建需额外执行 `rollout restart`。回滚用上一版 tag 执行 `kubectl -n vibe-launcher set image deploy/vibe-launcher-backend server=docker.io/library/vibe-launcher-backend:<旧 tag>` 并重启。nginx 站点配置备份放在 `/etc/nginx/backups/`(备份文件不要留在 `sites-enabled/`,否则会被 `include *` 加载并造成 server_name 冲突)。
|
||||
|
||||
上线验证可在服务器执行 `/opt/vibe-launcher/verify.sh`,覆盖 healthz、设备下发、管理接口 ETag、428/422 错误响应与版本历史。
|
||||
|
||||
### 账号密码登录部署验证
|
||||
|
||||
`1.1.0-deploy8` 增加浏览器账号密码登录。服务器管理员账号密码保存在 `/opt/vibe-launcher/auth.env`,文件权限为 `600`,通过 `vibe-launcher-auth` Secret 注入;不把凭据提交到 Git。
|
||||
|
||||
首次迁移脚本为 `backend/deploy/deploy-login.sh`,上传 JAR、Dockerfile 和 deploy.yaml 到 `/opt/vibe-launcher/` 后在服务器执行。脚本保留现有设备和管理员令牌,为未配置的管理员生成随机密码;部署失败时退回 deploy7 镜像。
|
||||
|
||||
服务器运行 `python3 /opt/vibe-launcher/verify-login.py` 验证公网登录、30 天 Cookie 属性、管理接口、写操作请求校验、设备接口权限隔离和退出登录;它读取同目录 auth.env,不打印密码,不发布或修改线上布局。脚本可用 `BASE`、`AUTH_FILE` 指定其他地址与凭据文件。
|
||||
|
||||
2026-11-26 已部署 deploy8,原有设备下发及版本历史验证通过,线上布局保持 v9;登录验证全部通过。本地前端生产构建与后端 16 项测试通过。
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
cd /opt/vibe-launcher
|
||||
STAGE=$(mktemp -d /opt/vibe-launcher/deploy8.XXXXXXXX)
|
||||
mkdir -p "$STAGE/target"
|
||||
cp target/vibe-launcher-backend.jar "$STAGE/target/"
|
||||
cp Dockerfile "$STAGE/"
|
||||
cp -p auth.env "$STAGE/auth.env.backup"
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
p = Path('/opt/vibe-launcher/auth.env')
|
||||
s = p.read_text()
|
||||
if 'ADMIN_USERNAME=' not in s: s += '\nADMIN_USERNAME=admin\n'
|
||||
if 'ADMIN_PASSWORD=' not in s: s += 'ADMIN_PASSWORD=' + secrets.token_urlsafe(24) + '\n'
|
||||
p.write_text(s)
|
||||
p.chmod(0o600)
|
||||
PY
|
||||
kubectl -n vibe-launcher create secret generic vibe-launcher-auth --from-env-file=auth.env --dry-run=client -o yaml | kubectl apply -f -
|
||||
docker build -t docker.io/library/vibe-launcher-backend:1.1.0-deploy8 "$STAGE"
|
||||
docker save docker.io/library/vibe-launcher-backend:1.1.0-deploy8 | k3s ctr images import -
|
||||
kubectl apply -f deploy.yaml
|
||||
if ! kubectl -n vibe-launcher rollout status deploy/vibe-launcher-backend --timeout=180s; then
|
||||
kubectl -n vibe-launcher set image deploy/vibe-launcher-backend server=docker.io/library/vibe-launcher-backend:1.1.0-deploy7
|
||||
exit 1
|
||||
fi
|
||||
bash verify.sh
|
||||
python3 verify-login.py
|
||||
@@ -26,7 +26,7 @@ spec:
|
||||
spec:
|
||||
containers:
|
||||
- name: server
|
||||
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy7
|
||||
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy8
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- name: http
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify deployed password login without logging credentials or changing layouts."""
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
base = os.environ.get('BASE', 'https://api.ttstd.com/launcher').rstrip('/')
|
||||
auth = dict(line.split('=', 1) for line in Path(os.environ.get('AUTH_FILE', '/opt/vibe-launcher/auth.env')).read_text().splitlines() if '=' in line and not line.startswith('#'))
|
||||
jar = http.cookiejar.CookieJar()
|
||||
client = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||
def request(path, expected=200, body=None, method=None, csrf=True):
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if csrf: headers['X-Launcher-Request'] = '1'
|
||||
req = urllib.request.Request(base + path, data=json.dumps(body).encode() if body is not None else None, headers=headers, method=method)
|
||||
try: response = client.open(req, timeout=15)
|
||||
except urllib.error.HTTPError as error: response = error
|
||||
assert response.code == expected, (path, response.code, expected)
|
||||
data = response.read()
|
||||
print(path, response.code)
|
||||
return response.headers, data
|
||||
request('/api/auth/session', 401)
|
||||
request('/api/auth/login', 403, {}, csrf=False)
|
||||
request('/api/auth/login', 401, {'username': auth['ADMIN_USERNAME'], 'password': 'invalid'})
|
||||
headers, _ = request('/api/auth/login', body={'username': auth['ADMIN_USERNAME'], 'password': auth['ADMIN_PASSWORD']})
|
||||
for attribute in ['HttpOnly', 'Secure', 'SameSite=Strict', 'Max-Age=2592000']:
|
||||
assert attribute in headers['Set-Cookie'], attribute
|
||||
request('/api/auth/session')
|
||||
request('/api/admin/layout')
|
||||
request('/api/admin/widget-providers')
|
||||
request('/api/admin/history')
|
||||
request('/api/admin/layout', 403, {}, method='PUT', csrf=False)
|
||||
request('/api/admin/layout', 428, {}, method='PUT')
|
||||
request('/api/layout', 401) # browser admin login must not authorize device API
|
||||
request('/api/auth/logout', body={})
|
||||
request('/api/auth/session', 401)
|
||||
request('/api/admin/layout', 401)
|
||||
print('Password login, cookie flags, authenticated reads, CSRF, device isolation and logout verified.')
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.ttstd.launcher;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
class BrowserAuth {
|
||||
private static final String COOKIE = "launcher_login";
|
||||
private static final long LIFETIME = 30L * 24 * 60 * 60;
|
||||
private long failureWindow;
|
||||
private int failures;
|
||||
private final String username;
|
||||
private final byte[] password;
|
||||
private final byte[] key;
|
||||
private final boolean enabled;
|
||||
private final boolean secure;
|
||||
|
||||
BrowserAuth(@Value("${launcher.admin-username:admin}") String username,
|
||||
@Value("${launcher.admin-password:}") String password,
|
||||
@Value("${launcher.cookie-secure:true}") boolean secure) {
|
||||
if (!password.isEmpty() && password.length() < 12)
|
||||
throw new IllegalArgumentException("ADMIN_PASSWORD 至少需要 12 个字符");
|
||||
this.username = username;
|
||||
this.password = RequestPolicy.sha256(password);
|
||||
this.key = RequestPolicy.sha256(username + "\n" + password);
|
||||
this.enabled = !password.isEmpty();
|
||||
this.secure = secure;
|
||||
}
|
||||
|
||||
void checkMutation(HttpServletRequest request) {
|
||||
if (!request.getMethod().equals("GET") && !"1".equals(request.getHeader("X-Launcher-Request")))
|
||||
throw new ApiError(403, "请求校验失败,请刷新页面");
|
||||
}
|
||||
|
||||
@PostMapping("/api/auth/login")
|
||||
synchronized Map<String, Object> login(@RequestBody Map<String, String> body, HttpServletRequest request, HttpServletResponse response) {
|
||||
checkMutation(request);
|
||||
long now = Instant.now().getEpochSecond();
|
||||
if (now - failureWindow >= 60) { failureWindow = now; failures = 0; }
|
||||
if (failures >= 20) throw new ApiError(429, "登录尝试过多,请稍后再试");
|
||||
if (!enabled || !MessageDigest.isEqual(RequestPolicy.sha256(body.getOrDefault("username", "")), RequestPolicy.sha256(username))
|
||||
|| !MessageDigest.isEqual(RequestPolicy.sha256(body.getOrDefault("password", "")), password))
|
||||
{
|
||||
failures++;
|
||||
throw new ApiError(401, "账号或密码错误");
|
||||
}
|
||||
failures = 0;
|
||||
String payload = (Instant.now().getEpochSecond() + LIFETIME) + "." + java.util.UUID.randomUUID();
|
||||
cookie(response, payload + "." + sign(payload), LIFETIME);
|
||||
return Map.of("username", username);
|
||||
}
|
||||
|
||||
@GetMapping("/api/auth/session")
|
||||
Map<String, Object> session(HttpServletRequest request) {
|
||||
if (!authenticated(request)) throw new ApiError(401, "请先登录");
|
||||
return Map.of("username", username);
|
||||
}
|
||||
|
||||
@PostMapping("/api/auth/logout")
|
||||
Map<String, Object> logout(HttpServletRequest request, HttpServletResponse response) {
|
||||
checkMutation(request);
|
||||
cookie(response, "", 0);
|
||||
return Map.of("ok", true);
|
||||
}
|
||||
|
||||
boolean authenticated(HttpServletRequest request) {
|
||||
if (!enabled || request.getCookies() == null) return false;
|
||||
for (var cookie : request.getCookies()) {
|
||||
if (!COOKIE.equals(cookie.getName())) continue;
|
||||
String value = cookie.getValue();
|
||||
int split = value.lastIndexOf('.');
|
||||
if (split < 0) return false;
|
||||
String payload = value.substring(0, split);
|
||||
try {
|
||||
long expires = Long.parseLong(payload.substring(0, payload.indexOf('.')));
|
||||
return expires > Instant.now().getEpochSecond() && MessageDigest.isEqual(
|
||||
sign(payload).getBytes(StandardCharsets.UTF_8), value.substring(split + 1).getBytes(StandardCharsets.UTF_8));
|
||||
} catch (RuntimeException invalid) { return false; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String sign(String payload) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (java.security.GeneralSecurityException error) { throw new IllegalStateException(error); }
|
||||
}
|
||||
|
||||
private void cookie(HttpServletResponse response, String value, long age) {
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, ResponseCookie.from(COOKIE, value).httpOnly(true)
|
||||
.secure(secure).sameSite("Strict").path("/").maxAge(age).build().toString());
|
||||
}
|
||||
}
|
||||
@@ -14,16 +14,18 @@ import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
@Component
|
||||
class RequestPolicy extends OncePerRequestFilter {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private BrowserAuth browserAuth;
|
||||
private final byte[] admin;
|
||||
private final byte[] device;
|
||||
|
||||
RequestPolicy(@Value("${launcher.admin-token}") String adminToken,
|
||||
@Value("${launcher.device-token}") String deviceToken) {
|
||||
if (!adminToken.matches("[!-~]{24,256}") || !deviceToken.matches("[!-~]{24,256}")
|
||||
if ((!adminToken.isEmpty() && !adminToken.matches("[!-~]{24,256}")) || !deviceToken.matches("[!-~]{24,256}")
|
||||
|| adminToken.equals(deviceToken)) {
|
||||
throw new IllegalArgumentException("请配置两组不同的 ADMIN_TOKEN 和 DEVICE_TOKEN,各使用 24–256 位可打印 ASCII 字符");
|
||||
throw new IllegalArgumentException("DEVICE_TOKEN 需要 24–256 位可打印 ASCII 字符;可选 ADMIN_TOKEN 需符合相同要求且与设备令牌不同");
|
||||
}
|
||||
this.admin = sha256("Bearer " + adminToken);
|
||||
this.admin = sha256(adminToken.isEmpty() ? java.util.UUID.randomUUID().toString() : "Bearer " + adminToken);
|
||||
this.device = sha256("Bearer " + deviceToken);
|
||||
}
|
||||
|
||||
@@ -39,6 +41,10 @@ class RequestPolicy extends OncePerRequestFilter {
|
||||
}
|
||||
|
||||
void requireAdmin(HttpServletRequest request, HttpServletResponse response) {
|
||||
if (browserAuth != null && browserAuth.authenticated(request)) {
|
||||
browserAuth.checkMutation(request);
|
||||
return;
|
||||
}
|
||||
require(request, response, admin);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,3 +7,7 @@ spring.mvc.throw-exception-if-no-handler-found=true
|
||||
launcher.admin-token=${ADMIN_TOKEN:}
|
||||
launcher.device-token=${DEVICE_TOKEN:}
|
||||
launcher.database=${LAYOUT_DB:backend/data/layouts.sqlite}
|
||||
|
||||
launcher.admin-username=${ADMIN_USERNAME:admin}
|
||||
launcher.admin-password=${ADMIN_PASSWORD:}
|
||||
launcher.cookie-secure=${COOKIE_SECURE:true}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ttstd.launcher;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
class BrowserAuthTest {
|
||||
@Test void persistentLoginAndPasswordChange() {
|
||||
var auth = new BrowserAuth("admin", "test-password-123456", true);
|
||||
var req = new MockHttpServletRequest("POST", "/api/auth/login");
|
||||
var res = new MockHttpServletResponse();
|
||||
assertThrows(ApiError.class, () -> auth.login(Map.of(), req, res));
|
||||
req.addHeader("X-Launcher-Request", "1");
|
||||
assertThrows(ApiError.class, () -> auth.login(Map.of("password", "wrong"), req, res));
|
||||
auth.login(Map.of("username", "admin", "password", "test-password-123456"), req, res);
|
||||
String header = res.getHeader("Set-Cookie");
|
||||
assertTrue(header.contains("HttpOnly"));
|
||||
assertTrue(header.contains("Secure"));
|
||||
assertTrue(header.contains("SameSite=Strict"));
|
||||
assertTrue(header.contains("Max-Age=2592000"));
|
||||
var cookie = new Cookie("launcher_login", header.split(";", 2)[0].split("=", 2)[1]);
|
||||
req.setCookies(cookie);
|
||||
assertTrue(auth.authenticated(req));
|
||||
assertTrue(new BrowserAuth("admin", "test-password-123456", true).authenticated(req));
|
||||
assertFalse(new BrowserAuth("admin", "changed-password-123456", true).authenticated(req));
|
||||
var policy = new RequestPolicy("", "test-device-token-123456789");
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(policy, "browserAuth", auth);
|
||||
req.setMethod("GET");
|
||||
policy.requireAdmin(req, new MockHttpServletResponse());
|
||||
var write = new MockHttpServletRequest("PUT", "/api/admin/layout");
|
||||
write.setCookies(cookie);
|
||||
assertThrows(ApiError.class, () -> policy.requireAdmin(write, new MockHttpServletResponse()));
|
||||
write.addHeader("X-Launcher-Request", "1");
|
||||
policy.requireAdmin(write, new MockHttpServletResponse());
|
||||
assertThrows(ApiError.class, () -> policy.requireDevice(req, new MockHttpServletResponse()));
|
||||
req.setMethod("POST");
|
||||
cookie.setValue(cookie.getValue() + "tampered");
|
||||
assertFalse(auth.authenticated(req));
|
||||
var out = new MockHttpServletResponse();
|
||||
auth.logout(req, out);
|
||||
assertTrue(out.getHeader("Set-Cookie").contains("Max-Age=0"));
|
||||
}
|
||||
}
|
||||
+14
-14
@@ -5,6 +5,8 @@ import {
|
||||
ElOption, ElSelect, ElTabPane, ElTabs,
|
||||
} from "element-plus";
|
||||
import zhCn from "element-plus/es/locale/lang/zh-cn";
|
||||
import LoginPanel from "./LoginPanel.vue";
|
||||
import { loggedIn } from "./auth";
|
||||
import ReleaseDialog from "./ReleaseDialog.vue";
|
||||
import LayoutSurface from "./LayoutSurface.vue";
|
||||
import DevicePreview from "./DevicePreview.vue";
|
||||
@@ -56,7 +58,7 @@ const tab = ref("preview");
|
||||
const snap = ref(true);
|
||||
const guides = ref(true);
|
||||
const release = ref(false);
|
||||
const adminToken = ref("");
|
||||
|
||||
const widgetCatalog = ref(false);
|
||||
type WidgetCategory = "third-party" | "system";
|
||||
interface WidgetProvider {
|
||||
@@ -92,7 +94,7 @@ watch(widgetCategory, () => {
|
||||
widgetQuery.value = "";
|
||||
});
|
||||
|
||||
watch(adminToken, () => {
|
||||
watch(loggedIn, () => {
|
||||
widgetProviders.value = [];
|
||||
widgetChoice.value = undefined;
|
||||
widgetQuery.value = "";
|
||||
@@ -101,9 +103,8 @@ watch(adminToken, () => {
|
||||
|
||||
async function readWidgetProviders() {
|
||||
if (widgetLoading.value) return;
|
||||
const token = adminToken.value.trim();
|
||||
if (!token) {
|
||||
widgetStatus.value = "请输入管理员令牌";
|
||||
if (!loggedIn.value) {
|
||||
widgetStatus.value = "请先在页面上方登录";
|
||||
return;
|
||||
}
|
||||
widgetLoading.value = true;
|
||||
@@ -111,12 +112,13 @@ async function readWidgetProviders() {
|
||||
try {
|
||||
const url = new URL("./api/admin/widget-providers", location.href);
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: "Bearer " + token },
|
||||
credentials: "same-origin",
|
||||
cache: "no-store", redirect: "error", signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) throw new Error(response.status === 401 ? "管理员令牌无效" : "目录读取失败");
|
||||
if (response.status === 401) loggedIn.value = false;
|
||||
if (!response.ok) throw new Error(response.status === 401 ? "登录已过期,请重新登录" : "目录读取失败");
|
||||
const data = await response.json() as { providers: WidgetProvider[] };
|
||||
if (adminToken.value.trim() !== token) return;
|
||||
if (!loggedIn.value) return;
|
||||
widgetProviders.value = data.providers;
|
||||
if (!data.providers.length) widgetStatus.value = "后端尚未导入小组件";
|
||||
} catch (error) {
|
||||
@@ -395,6 +397,7 @@ onUnmounted(() => {
|
||||
|
||||
<template>
|
||||
<ElConfigProvider :locale="zhCn" size="small">
|
||||
<LoginPanel v-if="hosted" />
|
||||
<header class="toolbar">
|
||||
<h1>桌面布局编辑器</h1>
|
||||
<nav aria-label="编辑命令">
|
||||
@@ -419,7 +422,7 @@ onUnmounted(() => {
|
||||
<ElButton v-for="template in templates" :key="template.label" :disabled="page.items.length >= 80"
|
||||
@click="addItem(template)">{{ template.label }}</ElButton>
|
||||
<ElButton v-if="hosted" :disabled="page.items.length >= 80"
|
||||
@click="widgetCatalog = true; if (adminToken && !widgetProviders.length) readWidgetProviders()">
|
||||
@click="widgetCatalog = true; if (loggedIn && !widgetProviders.length) readWidgetProviders()">
|
||||
小组件目录
|
||||
</ElButton>
|
||||
</div>
|
||||
@@ -540,10 +543,7 @@ onUnmounted(() => {
|
||||
</div>
|
||||
|
||||
<ElDialog v-model="widgetCatalog" title="小组件目录" width="min(660px, calc(100vw - 32px))">
|
||||
<label class="token-field">管理员令牌
|
||||
<ElInput v-model="adminToken" type="password" autocomplete="off" :disabled="widgetLoading"
|
||||
@keyup.enter="readWidgetProviders" />
|
||||
</label>
|
||||
|
||||
<ElButton :loading="widgetLoading" @click="readWidgetProviders">读取目录</ElButton>
|
||||
<p v-if="widgetStatus" role="status">{{ widgetStatus }}</p>
|
||||
<ElTabs v-if="widgetProviders.length" v-model="widgetCategory">
|
||||
@@ -562,7 +562,7 @@ onUnmounted(() => {
|
||||
@click="addCatalogWidget">添加到当前页</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
<ReleaseDialog v-if="hosted" v-model="release" v-model:token="adminToken" :layout="layout" :has-errors="issues.some(issue => issue.level === 'error')"
|
||||
<ReleaseDialog v-if="hosted" v-model="release" :layout="layout" :has-errors="issues.some(issue => issue.level === 'error')"
|
||||
:confirm-replace="confirmReplace" :warnings="issues.filter(issue => issue.level === 'warning')"
|
||||
@load="loadLayout" @published="markPublished" />
|
||||
</ElConfigProvider>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { ElButton, ElInput } from "element-plus";
|
||||
import { authRequest, loggedIn } from "./auth";
|
||||
const username = ref("admin");
|
||||
const password = ref("");
|
||||
const busy = ref(false);
|
||||
const message = ref("");
|
||||
onMounted(async () => {
|
||||
try { await authRequest("session"); loggedIn.value = true; } catch { loggedIn.value = false; }
|
||||
});
|
||||
async function submit() {
|
||||
busy.value = true;
|
||||
message.value = "";
|
||||
try {
|
||||
if (loggedIn.value) { await authRequest("logout", {}); loggedIn.value = false; }
|
||||
else { await authRequest("login", { username: username.value, password: password.value }); loggedIn.value = true; password.value = ""; }
|
||||
} catch (error) { message.value = error instanceof Error ? error.message : "请求失败"; }
|
||||
finally { busy.value = false; }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<form class="login-panel" @submit.prevent="submit" style="padding: 12px; display: flex; gap: 12px; align-items: center; flex-wrap: wrap">
|
||||
<template v-if="!loggedIn">
|
||||
<ElInput v-model="username" aria-label="账号" placeholder="管理员账号" autocomplete="username" style="width: 180px" />
|
||||
<ElInput v-model="password" aria-label="密码" placeholder="密码" type="password" autocomplete="current-password" show-password style="width: 220px" />
|
||||
</template>
|
||||
<span v-else>管理员已登录</span>
|
||||
<ElButton native-type="submit" :loading="busy">{{ loggedIn ? '退出登录' : '登录并保持 30 天' }}</ElButton>
|
||||
<span v-if="message" role="alert">{{ message }}</span>
|
||||
</form>
|
||||
</template>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from "vue";
|
||||
import { ElButton, ElDialog, ElInput, ElMessageBox } from "element-plus";
|
||||
import { loggedIn } from "./auth";
|
||||
import { normalizeLayout, type Issue, type Layout } from "./layout";
|
||||
|
||||
interface HistoryEntry { revision: number; publishedAt: string; restoredFrom?: number }
|
||||
@@ -9,7 +10,7 @@ interface History { revisions: HistoryEntry[]; nextBefore: number | null }
|
||||
const open = defineModel<boolean>({ required: true });
|
||||
const props = defineProps<{ layout: Layout; hasErrors: boolean; confirmReplace: () => Promise<boolean>; warnings: Issue[] }>();
|
||||
const emit = defineEmits<{ load: [layout: Layout, online?: boolean]; published: [revision: number] }>();
|
||||
const token = defineModel<string>("token", { required: true });
|
||||
|
||||
const tag = ref<string>();
|
||||
const revision = ref<number>();
|
||||
const history = ref<HistoryEntry[]>([]);
|
||||
@@ -19,7 +20,7 @@ const status = ref("");
|
||||
const error = ref(false);
|
||||
const apiBase = new URL("./api/admin/", location.href);
|
||||
|
||||
watch(token, () => {
|
||||
watch(loggedIn, () => {
|
||||
tag.value = revision.value = undefined;
|
||||
nextBefore.value = null;
|
||||
history.value = [];
|
||||
@@ -28,14 +29,14 @@ watch(token, () => {
|
||||
});
|
||||
|
||||
async function request<T>(path: string, options: RequestInit = {}) {
|
||||
const credential = token.value.trim();
|
||||
if (!credential) throw new Error("请输入管理员令牌");
|
||||
if (!loggedIn.value) throw new Error("请先在页面上方登录");
|
||||
const headers = new Headers(options.headers);
|
||||
headers.set("Authorization", "Bearer " + credential);
|
||||
headers.set("X-Launcher-Request", "1");
|
||||
const response = await fetch(new URL(path, apiBase), {
|
||||
...options, headers, cache: "no-store", redirect: "error",
|
||||
...options, headers, credentials: "same-origin", cache: "no-store", redirect: "error",
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (response.status === 401) loggedIn.value = false;
|
||||
if (response.status === 401 || response.status === 412 || response.status === 428) tag.value = undefined;
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
@@ -143,10 +144,7 @@ function moreHistory() {
|
||||
<template>
|
||||
<ElDialog v-model="open" title="布局发布" width="min(600px, calc(100vw - 32px))"
|
||||
:close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy">
|
||||
<label class="token-field">管理员令牌
|
||||
<ElInput v-model="token" type="password" autocomplete="off" spellcheck="false"
|
||||
aria-label="管理员令牌" :disabled="busy" @keyup.enter="loadOnline" />
|
||||
</label>
|
||||
|
||||
<div class="release-actions">
|
||||
<ElButton :disabled="busy" @click="loadOnline">读取线上布局</ElButton>
|
||||
<ElButton type="primary" :disabled="busy || !tag || hasErrors" @click="confirmPublish()">发布当前画布</ElButton>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ref } from "vue";
|
||||
export const loggedIn = ref(false);
|
||||
export async function authRequest(path: string, body?: object) {
|
||||
const response = await fetch(new URL("./api/auth/" + path, location.href), {
|
||||
method: body ? "POST" : "GET", credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json", "X-Launcher-Request": "1" },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
cache: "no-store", redirect: "error", signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.message || "登录失败");
|
||||
return data;
|
||||
}
|
||||
Reference in new issue
Block a user