Initial fixes (#1)
build-and-deploy / prepare (push) Successful in 2s
Tests / frontend-test (push) Successful in 13s
build-and-deploy / build-and-push (., Dockerfile, hr-appeals-web) (push) Successful in 18s
build-and-deploy / build-and-push (server, server/Dockerfile, hr-appeals-auth) (push) Successful in 9s
build-and-deploy / deploy (push) Successful in 7s
build-and-deploy / prepare (push) Successful in 2s
Tests / frontend-test (push) Successful in 13s
build-and-deploy / build-and-push (., Dockerfile, hr-appeals-web) (push) Successful in 18s
build-and-deploy / build-and-push (server, server/Dockerfile, hr-appeals-auth) (push) Successful in 9s
build-and-deploy / deploy (push) Successful in 7s
Co-authored-by: Mariya Trishina <trishina.mariya@tnsu.kz> Reviewed-on: http://git.tnsu.kz/gorbenko.pavel/hr-appeals/pulls/1
This commit was merged in pull request #1.
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
node_modules
|
||||
dist
|
||||
@@ -0,0 +1,22 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM node:20-alpine AS build
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS runtime
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
COPY --from=build /app/dist ./dist
|
||||
|
||||
EXPOSE 3000
|
||||
CMD ["node", "dist/index.js"]
|
||||
Generated
+1113
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "hr-appeals-auth",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.21.2",
|
||||
"jsonwebtoken": "^9.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/jsonwebtoken": "^9.0.7",
|
||||
"@types/node": "^22.20.1",
|
||||
"typescript": "~5.8.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
function requireEnv(name: string): string {
|
||||
const value = process.env[name];
|
||||
if (!value) {
|
||||
throw new Error(`Не задана переменная окружения ${name}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export const config = {
|
||||
tenantId: requireEnv('GRAPH_TENANT_ID'),
|
||||
clientId: requireEnv('GRAPH_CLIENT_ID'),
|
||||
certPath: requireEnv('GRAPH_CERT_PATH'),
|
||||
keyPath: requireEnv('GRAPH_KEY_PATH'),
|
||||
scope: process.env.GRAPH_SCOPE ?? 'https://graph.microsoft.com/.default',
|
||||
port: Number(process.env.PORT ?? 3000)
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { config } from './config';
|
||||
|
||||
interface CachedToken {
|
||||
accessToken: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
interface TokenResponse {
|
||||
access_token: string;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
const TOKEN_ENDPOINT = `https://login.microsoftonline.com/${config.tenantId}/oauth2/v2.0/token`;
|
||||
|
||||
// Обновляем токен заранее, а не строго по истечении — иначе запрос, уже летящий
|
||||
// к Graph с почти протухшим токеном, может получить 401.
|
||||
const REFRESH_MARGIN_MS = 60_000;
|
||||
|
||||
let cached: CachedToken | null = null;
|
||||
|
||||
function buildClientAssertion(): string {
|
||||
const certificatePem = readFileSync(config.certPath, 'utf8');
|
||||
const privateKey = readFileSync(config.keyPath, 'utf8');
|
||||
|
||||
// x5t — SHA-1 отпечаток DER-сертификата, base64url. По нему Azure AD находит
|
||||
// публичный ключ приложения и проверяет подпись JWT.
|
||||
const der = certificatePem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\s+/g, '');
|
||||
const thumbprint = createHash('sha1').update(Buffer.from(der, 'base64')).digest('base64url');
|
||||
|
||||
const nowSeconds = Math.floor(Date.now() / 1000);
|
||||
|
||||
return jwt.sign(
|
||||
{
|
||||
aud: TOKEN_ENDPOINT,
|
||||
iss: config.clientId,
|
||||
sub: config.clientId,
|
||||
jti: randomUUID(),
|
||||
nbf: nowSeconds,
|
||||
exp: nowSeconds + 5 * 60
|
||||
},
|
||||
privateKey,
|
||||
{ algorithm: 'RS256', header: { alg: 'RS256', x5t: thumbprint } }
|
||||
);
|
||||
}
|
||||
|
||||
export async function getAppOnlyToken(): Promise<string> {
|
||||
if (cached && cached.expiresAt - REFRESH_MARGIN_MS > Date.now()) {
|
||||
return cached.accessToken;
|
||||
}
|
||||
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'client_credentials',
|
||||
client_id: config.clientId,
|
||||
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
|
||||
client_assertion: buildClientAssertion(),
|
||||
scope: config.scope
|
||||
});
|
||||
|
||||
const response = await fetch(TOKEN_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Не удалось получить app-only токен: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as TokenResponse;
|
||||
cached = {
|
||||
accessToken: data.access_token,
|
||||
expiresAt: Date.now() + data.expires_in * 1000
|
||||
};
|
||||
return cached.accessToken;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import express from 'express';
|
||||
import { config } from './config';
|
||||
import { getAppOnlyToken } from './graphAuth';
|
||||
|
||||
const app = express();
|
||||
|
||||
app.get('/healthz', (_req, res) => {
|
||||
res.status(200).send('ok');
|
||||
});
|
||||
|
||||
// Временный диагностический эндпоинт: подтверждает, что связка
|
||||
// "сертификат -> подписанный JWT -> access-токен" реально работает,
|
||||
// до того как появится сама логика сохранения формы в Graph/SharePoint.
|
||||
app.get('/diag/token', async (_req, res) => {
|
||||
try {
|
||||
await getAppOnlyToken();
|
||||
res.status(200).json({ ok: true });
|
||||
} catch (error) {
|
||||
res.status(502).json({ ok: false, error: (error as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(config.port, () => {
|
||||
console.log(`hr-appeals-auth listening on :${config.port}`);
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user