init
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Мини-мок Keycloak для локальной разработки админки без настоящего Keycloak.
|
||||
*
|
||||
* Поднимает http://localhost:8081 c realm `gorodar` и клиентом `gorodar`,
|
||||
* автоматически «логинит» любого пользователя как admin с обеими ролями
|
||||
* (manage_area, manage_attraction). Токены не подписаны — только для UI-разработки.
|
||||
*
|
||||
* Использование: node scripts/mock-keycloak.mjs (затем npm run dev)
|
||||
*/
|
||||
import { createServer } from 'node:http'
|
||||
|
||||
const PORT = Number(process.env.MOCK_PORT ?? 8081)
|
||||
const REALM = 'gorodar'
|
||||
const CLIENT_ID = 'gorodar'
|
||||
const USER = 'admin'
|
||||
const ROLES = ['manage_area', 'manage_attraction']
|
||||
|
||||
const base = `http://localhost:${PORT}`
|
||||
const realmBase = `${base}/realms/${REALM}`
|
||||
const oidcPath = `/realms/${REALM}/protocol/openid-connect`
|
||||
|
||||
const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url')
|
||||
|
||||
function makeToken(ttlSeconds) {
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const header = b64url({ alg: 'HS256', typ: 'JWT' })
|
||||
const payload = b64url({
|
||||
iss: realmBase,
|
||||
sub: 'mock-user-id',
|
||||
aud: CLIENT_ID,
|
||||
azp: CLIENT_ID,
|
||||
iat: now,
|
||||
exp: now + ttlSeconds,
|
||||
preferred_username: USER,
|
||||
name: 'Админ Мок',
|
||||
resource_access: { [CLIENT_ID]: { roles: ROLES } },
|
||||
})
|
||||
return `${header}.${payload}.mock-signature`
|
||||
}
|
||||
|
||||
function sendJson(res, req, body, status = 200) {
|
||||
const headers = { 'Content-Type': 'application/json' }
|
||||
// keycloak-js отправляет token-запрос с credentials, поэтому эхаем Origin
|
||||
// вместо '*': wildcard не сочетается с Access-Control-Allow-Credentials.
|
||||
const origin = req.headers.origin
|
||||
if (origin) {
|
||||
headers['Access-Control-Allow-Origin'] = origin
|
||||
headers['Access-Control-Allow-Credentials'] = 'true'
|
||||
headers.Vary = 'Origin'
|
||||
}
|
||||
res.writeHead(status, headers)
|
||||
res.end(JSON.stringify(body))
|
||||
}
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const url = new URL(req.url ?? '/', base)
|
||||
console.log(new Date().toISOString(), req.method, url.pathname + (url.search || ''))
|
||||
|
||||
// discovery
|
||||
if (url.pathname === `/realms/${REALM}/.well-known/openid-configuration`) {
|
||||
return sendJson(res, req, {
|
||||
issuer: realmBase,
|
||||
authorization_endpoint: `${realmBase}/protocol/openid-connect/auth`,
|
||||
token_endpoint: `${realmBase}/protocol/openid-connect/token`,
|
||||
userinfo_endpoint: `${realmBase}/protocol/openid-connect/userinfo`,
|
||||
end_session_endpoint: `${realmBase}/protocol/openid-connect/logout`,
|
||||
jwks_uri: `${realmBase}/protocol/openid-connect/certs`,
|
||||
code_challenge_methods_supported: ['S256'],
|
||||
})
|
||||
}
|
||||
|
||||
// авторизация: сразу возвращаем код в redirect_uri (во fragment — keycloak-js
|
||||
// по умолчанию использует response_mode=fragment; iss обязателен для keycloak-js 25+)
|
||||
if (url.pathname === `${oidcPath}/auth`) {
|
||||
const redirect = new URL(url.searchParams.get('redirect_uri') ?? base)
|
||||
const fragment = new URLSearchParams({
|
||||
state: url.searchParams.get('state') ?? '',
|
||||
session_state: 'mock-session',
|
||||
code: 'mock-code',
|
||||
iss: realmBase,
|
||||
})
|
||||
res.writeHead(302, { Location: `${redirect.toString()}#${fragment.toString()}` })
|
||||
return res.end()
|
||||
}
|
||||
|
||||
// обмен кода на токены
|
||||
if (url.pathname === `${oidcPath}/token` && req.method === 'POST') {
|
||||
return sendJson(res, req, {
|
||||
access_token: makeToken(300),
|
||||
expires_in: 300,
|
||||
refresh_expires_in: 1800,
|
||||
refresh_token: makeToken(1800),
|
||||
token_type: 'Bearer',
|
||||
'not-before-policy': 0,
|
||||
session_state: 'mock-session',
|
||||
scope: 'openid profile',
|
||||
})
|
||||
}
|
||||
|
||||
if (url.pathname === `${oidcPath}/userinfo`) {
|
||||
return sendJson(res, req, { sub: 'mock-user-id', preferred_username: USER })
|
||||
}
|
||||
|
||||
if (url.pathname === `${oidcPath}/logout`) {
|
||||
const redirect = url.searchParams.get('post_logout_redirect_uri') ?? url.searchParams.get('redirect_uri') ?? base
|
||||
res.writeHead(302, { Location: redirect })
|
||||
return res.end()
|
||||
}
|
||||
|
||||
if (url.pathname === `/realms/${REALM}/`) {
|
||||
return sendJson(res, req, { realm: REALM, public: true, 'token-service': realmBase + '/protocol/openid-connect' })
|
||||
}
|
||||
|
||||
sendJson(res, req, { error: 'not_found' }, 404)
|
||||
})
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`Mock Keycloak: ${realmBase} (user=${USER}, roles=${ROLES.join(', ')})`)
|
||||
})
|
||||
Reference in New Issue
Block a user