CI / build (push) Successful in 33s
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
164 lines
8.9 KiB
JavaScript
164 lines
8.9 KiB
JavaScript
// HR tokens and upstream responses remain in this process. Never send them to the browser.
|
||
export class HrError extends Error {
|
||
constructor(code, status) { super(code); this.code = code; this.status = status; }
|
||
}
|
||
|
||
export function hrConfig(raw) {
|
||
if (!raw) return null;
|
||
try {
|
||
const config = JSON.parse(raw)['hr-sync'];
|
||
const url = new URL(config.base_url);
|
||
if (!['http:', 'https:'].includes(url.protocol) || !config.audience ||
|
||
!Array.isArray(config.required_scopes) || !Array.isArray(config.scopes) ||
|
||
!['hr:read', 'hr:salary:read'].every(scope => config.scopes.includes(scope))) return null;
|
||
return config;
|
||
} catch { return null; }
|
||
}
|
||
|
||
export async function hrFetch(session, capability, path, config, oidc, discovery) {
|
||
if (!config) throw new HrError('hr_not_configured', 503);
|
||
if (!['hr:read', 'hr:salary:read'].includes(capability) || !path.startsWith('/') || path.startsWith('//')) {
|
||
throw new HrError('invalid_request', 400);
|
||
}
|
||
if (!session.accessToken) throw new HrError('reauthentication_required', 401);
|
||
session.hrTokens ||= new Map();
|
||
let exchanged = session.hrTokens.get(capability);
|
||
if (!exchanged || exchanged.expiresAt <= Date.now() + 30000) {
|
||
session.exchangeJobs ||= new Map();
|
||
if (!session.exchangeJobs.has(capability)) {
|
||
const job = (async () => {
|
||
if (session.accessExpiresAt <= Date.now() + 30000) {
|
||
if (!session.refreshJob) {
|
||
session.refreshJob = (async () => {
|
||
if (!session.refreshToken) throw new HrError('reauthentication_required', 401);
|
||
const response = await fetch(discovery.token_endpoint, {
|
||
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||
body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: session.refreshToken,
|
||
client_id: oidc.clientId, client_secret: oidc.clientSecret }), signal: AbortSignal.timeout(8000),
|
||
});
|
||
if (!response.ok) throw new HrError('reauthentication_required', 401);
|
||
const tokens = await response.json();
|
||
if (!tokens.access_token || !tokens.refresh_token) throw new HrError('reauthentication_required', 401);
|
||
session.accessToken = tokens.access_token;
|
||
session.refreshToken = tokens.refresh_token;
|
||
session.accessExpiresAt = Date.now() + Math.max(1, Number(tokens.expires_in) || 3600) * 1000;
|
||
session.hrTokens.clear();
|
||
})().finally(() => { session.refreshJob = null; });
|
||
}
|
||
await session.refreshJob;
|
||
}
|
||
const response = await fetch(discovery.token_endpoint, {
|
||
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||
body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
|
||
subject_token: session.accessToken,
|
||
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
|
||
audience: config.audience,
|
||
scope: [...new Set(['openid', ...config.required_scopes, capability])].join(' '),
|
||
client_id: oidc.clientId, client_secret: oidc.clientSecret }), signal: AbortSignal.timeout(8000),
|
||
});
|
||
if (!response.ok) {
|
||
const code = (await response.json().catch(() => ({}))).error;
|
||
if (code === 'invalid_grant') throw new HrError('hr_exchange_denied', 403);
|
||
if (code === 'invalid_target') throw new HrError('hr_target_unavailable', 503);
|
||
throw new HrError('hr_exchange_failed', 503);
|
||
}
|
||
const tokens = await response.json();
|
||
if (!tokens.access_token) throw new HrError('hr_exchange_failed', 503);
|
||
const result = { token: tokens.access_token,
|
||
expiresAt: Date.now() + Math.max(1, Number(tokens.expires_in) || 300) * 1000 };
|
||
session.hrTokens.set(capability, result);
|
||
return result;
|
||
})().finally(() => session.exchangeJobs.delete(capability));
|
||
session.exchangeJobs.set(capability, job);
|
||
}
|
||
exchanged = await session.exchangeJobs.get(capability);
|
||
}
|
||
const base = config.base_url.endsWith('/') ? config.base_url : `${config.base_url}/`;
|
||
const response = await fetch(new URL(path.slice(1), base), {
|
||
headers: { Authorization: `Bearer ${exchanged.token}` }, signal: AbortSignal.timeout(8000),
|
||
});
|
||
if (response.status === 401) throw new HrError('reauthentication_required', 401);
|
||
if (response.status === 403) throw new HrError('hr_endpoint_forbidden', 403);
|
||
if (response.status === 404) throw new HrError('hr_not_found', 404);
|
||
if (!response.ok) throw new HrError('hr_unavailable', 503);
|
||
return response.json();
|
||
}
|
||
|
||
// 伺服器服務身分(AUTHENTIK-HANDOFF.md §1):先 client_credentials 拿站台自己的 token,
|
||
// 再 token exchange 換成 HR Sync 的 token。沿用既有的 OIDC_CLIENT_ID/OIDC_CLIENT_SECRET,
|
||
// 不需要新的環境變數。token 只留在伺服器記憶體,不送到瀏覽器、不寫進 log。
|
||
const service = { access: null, accessJob: null, exchanged: new Map(), jobs: new Map() };
|
||
|
||
export function resetServiceTokens() {
|
||
service.access = null; service.accessJob = null; service.exchanged.clear(); service.jobs.clear();
|
||
}
|
||
|
||
async function serviceAccessToken(oidc, discovery) {
|
||
if (service.access && service.access.expiresAt > Date.now() + 60000) return service.access.token;
|
||
if (!service.accessJob) {
|
||
service.accessJob = (async () => {
|
||
const response = await fetch(discovery.token_endpoint, {
|
||
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||
body: new URLSearchParams({ grant_type: 'client_credentials', client_id: oidc.clientId,
|
||
client_secret: oidc.clientSecret, scope: 'openid' }), signal: AbortSignal.timeout(8000),
|
||
});
|
||
if (!response.ok) throw new HrError('hr_service_unavailable', 503);
|
||
const tokens = await response.json();
|
||
if (!tokens.access_token) throw new HrError('hr_service_unavailable', 503);
|
||
service.access = { token: tokens.access_token,
|
||
expiresAt: Date.now() + Math.max(1, Number(tokens.expires_in) || 3600) * 1000 };
|
||
service.exchanged.clear();
|
||
return service.access.token;
|
||
})().finally(() => { service.accessJob = null; });
|
||
}
|
||
return service.accessJob;
|
||
}
|
||
|
||
export async function serviceHrFetch(capability, path, config, oidc, discovery) {
|
||
if (!config) throw new HrError('hr_not_configured', 503);
|
||
if (!['hr:read', 'hr:salary:read'].includes(capability) || !path.startsWith('/') || path.startsWith('//')) {
|
||
throw new HrError('invalid_request', 400);
|
||
}
|
||
let exchanged = service.exchanged.get(capability);
|
||
if (!exchanged || exchanged.expiresAt <= Date.now() + 30000) {
|
||
if (!service.jobs.has(capability)) {
|
||
const job = (async () => {
|
||
const subject = await serviceAccessToken(oidc, discovery);
|
||
const response = await fetch(discovery.token_endpoint, {
|
||
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||
body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
|
||
subject_token: subject,
|
||
subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
|
||
audience: config.audience,
|
||
scope: [...new Set(['openid', ...config.required_scopes, capability])].join(' '),
|
||
client_id: oidc.clientId, client_secret: oidc.clientSecret }), signal: AbortSignal.timeout(8000),
|
||
});
|
||
if (!response.ok) {
|
||
const code = (await response.json().catch(() => ({}))).error;
|
||
// 服務帳號沒有這個能力,或 HR Sync 不再信任這個 client:都屬於服務身分失敗。
|
||
if (code === 'invalid_grant') throw new HrError('hr_service_denied', 503);
|
||
if (code === 'invalid_target') throw new HrError('hr_target_unavailable', 503);
|
||
throw new HrError('hr_exchange_failed', 503);
|
||
}
|
||
const tokens = await response.json();
|
||
if (!tokens.access_token) throw new HrError('hr_exchange_failed', 503);
|
||
const result = { token: tokens.access_token,
|
||
expiresAt: Date.now() + Math.max(1, Number(tokens.expires_in) || 300) * 1000 };
|
||
service.exchanged.set(capability, result);
|
||
return result;
|
||
})().finally(() => service.jobs.delete(capability));
|
||
service.jobs.set(capability, job);
|
||
}
|
||
exchanged = await service.jobs.get(capability);
|
||
}
|
||
const base = config.base_url.endsWith('/') ? config.base_url : `${config.base_url}/`;
|
||
const response = await fetch(new URL(path.slice(1), base), {
|
||
headers: { Authorization: `Bearer ${exchanged.token}` }, signal: AbortSignal.timeout(8000),
|
||
});
|
||
if (response.status === 401) { service.exchanged.delete(capability); throw new HrError('reauthentication_required', 401); }
|
||
if (response.status === 403) throw new HrError('hr_endpoint_forbidden', 403);
|
||
if (response.status === 404) throw new HrError('hr_not_found', 404);
|
||
if (!response.ok) throw new HrError('hr_unavailable', 503);
|
||
return response.json();
|
||
}
|