Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
This commit is contained in:
+78
@@ -83,3 +83,81 @@ export async function hrFetch(session, capability, path, config, oidc, discovery
|
||||
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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user