fix(auth): route session lifecycle through Square

This commit is contained in:
2026-08-19 16:44:06 +08:00
parent 1907924203
commit dc776ff489
6 changed files with 80 additions and 63 deletions

View File

@@ -1,16 +0,0 @@
import {
NIANCODE_AUTH_CLIENT_ID,
NIANCODE_AUTH_GATEWAY_URL,
NIANCODE_AUTH_SCOPE,
} from '../../shared/auth-public';
export const NIANCODE_AUTH_CLIENT_SECRET = 'app';
export const NIANCODE_AUTH_PASSWORD_ENCODE_KEY = 'thanks,pig4cloud';
export const NIANCODE_AUTH_CONFIG = {
gatewayAuthUrl: NIANCODE_AUTH_GATEWAY_URL,
clientId: NIANCODE_AUTH_CLIENT_ID,
clientSecret: NIANCODE_AUTH_CLIENT_SECRET,
passwordEncodeKey: NIANCODE_AUTH_PASSWORD_ENCODE_KEY,
scope: NIANCODE_AUTH_SCOPE,
} as const;

View File

@@ -2,7 +2,6 @@ import type { IncomingMessage, ServerResponse } from 'http';
import type { HostApiContext } from '../context';
import { parseJsonBody, sendJson } from '../route-utils';
import { proxyAwareFetch } from '../../utils/proxy-fetch';
import { NIANCODE_AUTH_CONFIG } from '../auth-config';
import { WORKS_SQUARE_CONFIG } from '../works-config';
import {
clearWorksSquareSession,
@@ -92,14 +91,6 @@ function withoutRefreshToken(payload: unknown): unknown {
return publicPayload;
}
function normalizeAuthBase(): string {
const authBase = NIANCODE_AUTH_CONFIG.gatewayAuthUrl.replace(/\/+$/, '');
if (!/^https?:\/\//i.test(authBase)) {
throw new Error('authBase must start with http:// or https://');
}
return authBase;
}
function normalizeWorksBase(value = WORKS_SQUARE_CONFIG.apiBaseUrl): string {
const apiBase = value.replace(/\/+$/, '');
if (!/^https?:\/\//i.test(apiBase)) {
@@ -652,7 +643,6 @@ async function handleLogout(
await parseJsonBody<LogoutInput>(req),
['accessToken'],
);
const authBase = normalizeAuthBase();
const rendererAccessToken = readOptionalTrimmedString(body.accessToken);
const accessToken = getWorksSquareSessionSnapshot()?.accessToken
?? readRequiredString(rendererAccessToken, 'accessToken');
@@ -674,8 +664,8 @@ async function handleLogout(
let response: Response;
try {
response = await proxyAwareFetch(`${authBase}/token/logout`, {
method: 'DELETE',
response = await proxyAwareFetch(createWorksUrl('/api/auth/logout').toString(), {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
},

View File

@@ -1,7 +1,8 @@
import { createHash } from 'node:crypto';
import { NIANCODE_AUTH_CONFIG } from '../api/auth-config';
import { WORKS_SQUARE_CONFIG } from '../api/works-config';
import { proxyAwareFetch, runWithDeadline } from '../utils/proxy-fetch';
import { logger } from '../utils/logger';
import { NIANCODE_AUTH_GATEWAY_URL } from '../../shared/auth-public';
import { WORKS_SQUARE_SESSION_IDLE_TIMEOUT_MS } from '../../shared/auth-session';
const TOKEN_REFRESH_SKEW_MS = 30_000;
@@ -149,10 +150,6 @@ function expiresAtFromExpiresIn(expiresIn: unknown, nowMs = Date.now()): number
return Number.isFinite(seconds) && seconds > 0 ? nowMs + seconds * 1000 : null;
}
function createBasicAuthHeader(clientId: string, clientSecret: string): string {
return `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`;
}
function toPublicSnapshot(
session: StoredWorksSquareSession | null,
): WorksSquareSessionSnapshot | null {
@@ -327,7 +324,7 @@ async function createElectronSessionPersistence(
if (!record) return null;
if (
record.version !== SESSION_STORE_SCHEMA_VERSION
|| record.authBase !== NIANCODE_AUTH_CONFIG.gatewayAuthUrl
|| record.authBase !== NIANCODE_AUTH_GATEWAY_URL
) {
store.delete('record');
return null;
@@ -344,7 +341,7 @@ async function createElectronSessionPersistence(
const encrypted = safeStorage.encryptString(JSON.stringify(session));
store.set('record', {
version: SESSION_STORE_SCHEMA_VERSION,
authBase: NIANCODE_AUTH_CONFIG.gatewayAuthUrl,
authBase: NIANCODE_AUTH_GATEWAY_URL,
ciphertext: encrypted.toString('base64'),
});
},
@@ -723,22 +720,13 @@ async function refreshWorksSquareSession(
const fetchImpl = options.fetchImpl ?? proxyAwareFetch;
const nowMs = options.nowMs ?? Date.now();
const body = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: session.refreshToken,
});
const body = JSON.stringify({ refresh_token: session.refreshToken });
const { response, payload } = await runWithDeadline(async (signal) => {
const response = await fetchImpl(
`${NIANCODE_AUTH_CONFIG.gatewayAuthUrl.replace(/\/+$/, '')}/oauth2/token`,
`${WORKS_SQUARE_CONFIG.apiBaseUrl.replace(/\/+$/, '')}/api/auth/refresh`,
{
method: 'POST',
headers: {
Authorization: createBasicAuthHeader(
NIANCODE_AUTH_CONFIG.clientId,
NIANCODE_AUTH_CONFIG.clientSecret,
),
'Content-Type': 'application/x-www-form-urlencoded',
},
headers: { 'Content-Type': 'application/json' },
body,
signal,
},