fix: support authenticated web deployments under a reverse proxy path

This commit is contained in:
AttilaNet
2026-11-10 20:01:44 +08:00
parent 0230a933b0
commit 99aff423d8
12 changed files with 529 additions and 31 deletions
+5 -2
View File
@@ -1,3 +1,5 @@
import {apiPath, webPath} from './paths.js';
export class ApiError extends Error {
constructor(message, status, detail) {
super(message);
@@ -16,17 +18,18 @@ function errorMessage(data, status) {
}
export async function request(path, {method = 'GET', body, signal, blob = false} = {}) {
const url = apiPath(path);
const headers = {Accept: blob ? '*/*' : 'application/json'};
if (body !== undefined && !(body instanceof FormData)) headers['Content-Type'] = 'application/json';
let response;
try {
response = await fetch(path, {method, credentials: 'same-origin', cache: 'no-store', headers, signal,
response = await fetch(url, {method, credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers, signal,
body: body === undefined ? undefined : body instanceof FormData ? body : JSON.stringify(body)});
} catch (error) {
if (error.name === 'AbortError') throw error;
throw new ApiError('无法连接 Web 服务,请检查服务是否仍在运行。', 0);
}
if (response.status === 401 && !path.startsWith('/api/auth/')) window.dispatchEvent(new CustomEvent('auth-required'));
if (response.status === 401 && !url.startsWith(webPath('/api/auth/'))) window.dispatchEvent(new CustomEvent('auth-required'));
if (!response.ok) {
const data = await response.json().catch(() => null);
throw new ApiError(errorMessage(data, response.status), response.status, data);
+9 -3
View File
@@ -1,4 +1,5 @@
import {api, request} from './api.js';
import {apiPath, webPath} from './paths.js';
import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTime, download, csvBlob, optionsList, detailsList, tabKeys} from './dom.js';
import {PageView, PAGES} from './pages.js';
import {notice, dialog, confirm, filePicker, fileBase64} from './ui.js';
@@ -418,7 +419,7 @@ function renderLogs(reset=false) {
const line=el('div',{class:`log-entry ${entry.level || entry.kind || ''}`,'data-entry-id':entry.id});
const stamp=entry.time || entry.timestamp || entry.at || '';
line.append(el('span',{class:'log-time',text:chinaTime(stamp),title:String(stamp)}),document.createTextNode(entry.message || entry.operation || textValue(entry)));
if(entry.details_available || entry.detail_url){line.classList.add('inspectable');line.tabIndex=0;line.setAttribute('role','button');line.title='查看脱敏请求 / 响应 JSON';line.addEventListener('click',()=>showDebugEntry(account,entry));line.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();showDebugEntry(account,entry);}});}
if(entry.details_available || entry.detail_url || entry.debug_url){line.classList.add('inspectable');line.tabIndex=0;line.setAttribute('role','button');line.title='查看脱敏请求 / 响应 JSON';line.addEventListener('click',()=>showDebugEntry(account,entry));line.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();showDebugEntry(account,entry);}});}
root.append(line);
}
log.rendered=log.entries.length;
@@ -439,7 +440,12 @@ async function fetchLogs(account) {
async function showDebugEntry(account,entry) {
const pre=el('pre',{class:'debug-json',text:'正在读取所选条目的脱敏详情…'});const open=dialog('请求 / 响应详情(已脱敏)',pre,{info:true});
try{let detail;if(entry.detail_url&&new URL(entry.detail_url,location.href).origin===location.origin)detail=await request(entry.detail_url);else detail=await api.debugEntry(account.id,entry.id);pre.textContent=JSON.stringify(detail.details ?? detail,null,2);}catch(failure){pre.textContent=failure.message;}
try{
let path;
try{path=apiPath(entry.detail_url || entry.debug_url);}catch{/* Use the account's own endpoint for untrusted URLs. */}
const detail=await (path?request(path):api.debugEntry(account.id,entry.id));
pre.textContent=JSON.stringify(detail.details ?? detail,null,2);
}catch(failure){pre.textContent=failure.message;}
await open;
}
@@ -479,7 +485,7 @@ function hideWorkbench() {
function requireAuth() {
if(state.redirecting)return;
state.redirecting=true;hideWorkbench();location.replace('/login');
state.redirecting=true;hideWorkbench();location.replace(webPath('/login'));
}
async function bootstrap() {
+1
View File
@@ -3,6 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light">
<title>牧羊人之心牧场助手 · Web</title>
<link rel="icon" href="data:,">
+1
View File
@@ -3,6 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="ranch-web-base-path" content="">
<meta name="color-scheme" content="light">
<title>管理登录 · 牧羊人之心牧场助手</title>
<link rel="icon" href="data:,">
+7 -2
View File
@@ -1,4 +1,8 @@
const form = document.querySelector('#auth-form');
// Keep login standalone: the server renders the prefix in both HTML documents.
const basePath = (document.querySelector('meta[name="ranch-web-base-path"]')?.content || '').replace(/\/+$/, '');
const webPath = path => `${basePath}${path}`;
form.setAttribute('action', webPath('/api/auth/login'));
const input = document.querySelector('#admin-password');
const button = form.querySelector('button[type="submit"]');
const status = document.querySelector('#auth-status');
@@ -24,16 +28,17 @@ function openWorkbench() {
leaving = true;
input.value = '';
setBusy(true, '正在进入工作台…');
location.replace('/');
location.replace(webPath('/'));
}
async function authRequest(path, body) {
let response;
try {
response = await fetch(path, {
response = await fetch(webPath(path), {
method: body === undefined ? 'GET' : 'POST',
credentials: 'same-origin',
cache: 'no-store',
redirect: 'error',
headers: body === undefined ? {Accept: 'application/json'} : {Accept: 'application/json', 'Content-Type': 'application/json'},
body,
});
+13
View File
@@ -0,0 +1,13 @@
// The server supplies this value; never infer it from the URL or proxy headers.
const basePath = (document.querySelector('meta[name="ranch-web-base-path"]')?.content || '').replace(/\/+$/, '');
export const webPath = path => `${basePath}${path}`;
export function apiPath(path) {
const url = new URL(path, location.origin);
if (url.origin !== location.origin || url.username || url.password) throw new TypeError('Invalid API URL');
let pathname = url.pathname;
if (basePath && pathname.startsWith(`${basePath}/`)) pathname = pathname.slice(basePath.length);
if (!pathname.startsWith('/api/')) throw new TypeError('Invalid API path');
return webPath(pathname) + url.search;
}