2026-07-07 13:04:02 +08:00

189 lines
5.6 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getPublicAppOrigin } from '@/lib/public-app-url'
import { consumeDingtalkSessionTicket } from '@/lib/dingtalk-session-ticket'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
function stringifyForInlineScript(value: string) {
return JSON.stringify(value).replace(/</g, '\\u003c')
}
function buildPublicUrl(path: string, request?: NextRequest) {
try {
return new URL(path, getPublicAppOrigin()).toString()
} catch {
return new URL(path, request?.url || 'https://sc.jiansun.vip').toString()
}
}
function appendSetCookies(target: NextResponse, cookies: string[]) {
const cookieNames: string[] = []
for (const cookie of cookies) {
target.headers.append('set-cookie', cookie)
const cookieName = String(cookie).split('=', 1)[0]?.trim()
if (cookieName) {
cookieNames.push(cookieName)
}
}
return cookieNames
}
function createErrorPage(message: string, status = 410) {
const safeMessage = stringifyForInlineScript(message)
return new NextResponse(
`<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>正在进入素材库</title>
<meta http-equiv="Cache-Control" content="no-store" />
<style>
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0f172a;color:#f8fafc;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
main{width:min(420px,calc(100vw - 48px));padding:32px 24px;text-align:center}
h1{margin:0 0 12px;font-size:22px}
p{margin:0;color:#cbd5e1;line-height:1.7}
</style>
</head>
<body>
<main>
<h1>正在进入素材库</h1>
<p id="message"></p>
</main>
<script>
document.getElementById('message').textContent = ${safeMessage};
</script>
</body>
</html>`,
{
status,
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
},
},
)
}
function createSessionLandingPage({
request,
redirectPath,
cookies,
}: {
request: NextRequest
redirectPath: string
cookies: string[]
}) {
const redirectUrl = buildPublicUrl(redirectPath, request)
const sessionUrl = buildPublicUrl('/api/auth/session', request)
const response = new NextResponse(
`<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>正在进入素材库</title>
<meta http-equiv="Cache-Control" content="no-store" />
<style>
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0f172a;color:#f8fafc;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
main{width:min(420px,calc(100vw - 48px));padding:32px 24px;text-align:center}
h1{margin:0 0 12px;font-size:22px}
p{margin:0;color:#cbd5e1;line-height:1.7}
.spinner{width:38px;height:38px;margin:0 auto 20px;border:4px solid rgba(255,255,255,.24);border-top-color:#60a5fa;border-radius:999px;animation:spin .85s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
</style>
</head>
<body>
<main>
<div class="spinner" aria-hidden="true"></div>
<h1>正在进入素材库</h1>
<p id="message">正在写入素材库登录状态...</p>
</main>
<script>
(function () {
var target = ${stringifyForInlineScript(redirectUrl)};
var sessionUrl = ${stringifyForInlineScript(sessionUrl)};
var message = document.getElementById('message');
var attempts = 0;
function setMessage(text) {
if (message) message.textContent = text;
}
function enterTarget() {
window.location.href = target;
}
function checkSession() {
attempts += 1;
fetch(sessionUrl, {
credentials: 'include',
cache: 'no-store',
headers: { 'Accept': 'application/json' }
})
.then(function (response) {
return response.ok ? response.json() : null;
})
.then(function (data) {
if (data && data.user) {
setMessage('登录状态已生效,正在进入考核调研...');
setTimeout(enterTarget, 120);
return;
}
if (attempts >= 12) {
setMessage('登录状态写入超时,请返回钉钉重新打开通知。');
return;
}
setTimeout(checkSession, 350);
})
.catch(function () {
if (attempts >= 12) {
setMessage('登录状态确认失败,请返回钉钉重新打开通知。');
return;
}
setTimeout(checkSession, 350);
});
}
setTimeout(checkSession, 250);
})();
</script>
</body>
</html>`,
{
status: 200,
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
},
},
)
const cookieNames = appendSetCookies(response, cookies)
console.log('[Dingtalk H5] 通过一次性票据写入会话Cookie:', {
redirectPath,
redirectUrl,
cookieNames,
})
return response
}
export async function GET(request: NextRequest) {
const ticket = consumeDingtalkSessionTicket(request.nextUrl.searchParams.get('ticket'))
if (!ticket) {
return createErrorPage('登录票据已失效,请返回钉钉重新打开通知。')
}
return createSessionLandingPage({
request,
redirectPath: ticket.redirectPath,
cookies: ticket.cookies,
})
}