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,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,
},