229 lines
13 KiB
JavaScript
229 lines
13 KiB
JavaScript
#!/usr/bin/env node
|
|
// Obtém um token de USUÁRIO pelo device flow (RFC 8628) com o client_id de uma aplicação (ex.: a web
|
|
// do produto) e chama uma API com ele — sem o token passar pela linha de comando, pelo chat ou por
|
|
// arquivo do repositório.
|
|
//
|
|
// Por que existe: testar a API do produto "como o usuário logado na web" exigia copiar o token do
|
|
// DevTools do navegador. Com o device flow, o agente pede o código, o usuário aprova no navegador dele
|
|
// (login normal, 2FA, SSO) e o token fica guardado fora do repositório, usado só por este script.
|
|
//
|
|
// Uso (um comando por linha; o agente leva o link de uma chamada para a outra):
|
|
// node device-token.mjs start --authority <url> --client-id <id> --scope "<escopos>" [--secret-env VAR]
|
|
// node device-token.mjs poll --authority <url> --client-id <id>
|
|
// node device-token.mjs login --authority <url> --client-id <id> --scope "<escopos>" [--secret-env VAR]
|
|
// node device-token.mjs claims --authority <url> --client-id <id>
|
|
// node device-token.mjs call --authority <url> --client-id <id> --url <url da API> [--method GET] [--body <arquivo.json>]
|
|
// node device-token.mjs logout --authority <url> --client-id <id>
|
|
//
|
|
// Subcomandos:
|
|
// start pede o código ao servidor e imprime o link (verification_uri_complete) e o user_code. Não
|
|
// espera: o agente mostra o link ao usuário e chama `poll` em seguida
|
|
// poll espera a decisão do usuário (respeita `interval` e `slow_down`) até autorizar, negar ou vencer
|
|
// login start + poll num só comando — para quem roda no próprio terminal
|
|
// claims mostra as claims do access token guardado (client_id, sub, scope, amr, exp…), nunca o token
|
|
// call chama a API com `Authorization: Bearer`; renova pelo refresh_token se o token estiver vencendo.
|
|
// Imprime status e corpo da resposta
|
|
// logout apaga o token e o código pendente guardados para esse authority + client_id
|
|
//
|
|
// Opções:
|
|
// --authority URL base do servidor de identidade (onde fica /.well-known/openid-configuration)
|
|
// --client-id o client_id da aplicação (o mesmo da web, se é ela que você quer imitar)
|
|
// --scope escopos separados por espaço; inclua o da API e `offline_access` se quiser refresh
|
|
// --secret-env NOME da variável de ambiente com o client_secret (client confidencial). O secret nunca
|
|
// é aceito como argumento, para não ir ao histórico do shell
|
|
// --url URL completa da API em `call`
|
|
// --method método HTTP em `call` (padrão GET)
|
|
// --body arquivo JSON enviado como corpo em `call`
|
|
// --dry-run mostra o que seria chamado, sem rede e sem ler o arquivo de tokens
|
|
//
|
|
// Onde fica o token: ~/.aliare-sdlc/device-tokens.json (fora do repositório; permissão 600 onde o sistema
|
|
// suporta), uma entrada por authority + client_id. Só módulos nativos do Node 18+.
|
|
|
|
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
import { homedir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
|
|
const USO = 'uso: node device-token.mjs <start|poll|login|claims|call|logout> --authority <url> --client-id <id> [--scope "<escopos>"] [--secret-env VAR] [--url <api> --method GET --body <arquivo>] [--dry-run]';
|
|
const GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
|
|
const DIR = join(homedir(), '.aliare-sdlc');
|
|
const ARQ = join(DIR, 'device-tokens.json');
|
|
|
|
function falha(msg, code = 1) { console.error(`erro: ${msg}`); process.exit(code); }
|
|
function uso(msg) { if (msg) console.error(`erro: ${msg}`); console.error(USO); process.exit(2); }
|
|
|
|
const args = process.argv.slice(2);
|
|
if (args.some((a) => a === '--help' || a === '-h')) { console.log(USO); process.exit(0); }
|
|
const o = { method: 'GET', dryRun: false };
|
|
let cmd = null;
|
|
for (let i = 0; i < args.length; i++) {
|
|
const a = args[i];
|
|
const next = () => { if (i + 1 >= args.length) uso(`${a} sem valor`); return args[++i]; };
|
|
if (a === '--authority') o.authority = next().replace(/\/+$/, '');
|
|
else if (a === '--client-id') o.clientId = next();
|
|
else if (a === '--scope') o.scope = next();
|
|
else if (a === '--secret-env') o.secretEnv = next();
|
|
else if (a === '--url') o.url = next();
|
|
else if (a === '--method') o.method = next().toUpperCase();
|
|
else if (a === '--body') o.body = next();
|
|
else if (a === '--dry-run') o.dryRun = true;
|
|
else if (a.startsWith('--')) uso(`opção desconhecida ${a}`);
|
|
else if (cmd === null) cmd = a;
|
|
else uso(`argumento a mais: ${a}`);
|
|
}
|
|
if (!['start', 'poll', 'login', 'claims', 'call', 'logout'].includes(cmd)) uso('subcomando ausente ou inválido');
|
|
if (!o.authority || !o.clientId) uso('--authority e --client-id são obrigatórios');
|
|
if (['start', 'login'].includes(cmd) && !o.scope) uso('--scope é obrigatório em start/login');
|
|
if (cmd === 'call' && !o.url) uso('--url é obrigatório em call');
|
|
if (o.secretEnv && !process.env[o.secretEnv] && !o.dryRun) falha(`variável ${o.secretEnv} vazia ou inexistente`);
|
|
|
|
const chave = `${o.authority}|${o.clientId}`;
|
|
const secret = () => (o.secretEnv ? process.env[o.secretEnv] : undefined);
|
|
|
|
// ---------- armazenamento local (fora do repositório) ----------
|
|
function lerTudo() {
|
|
if (!existsSync(ARQ)) return {};
|
|
try { return JSON.parse(readFileSync(ARQ, 'utf8')); } catch { falha(`${ARQ} corrompido; apague-o`); }
|
|
}
|
|
function gravar(entrada) {
|
|
const tudo = lerTudo();
|
|
if (entrada === null) delete tudo[chave]; else tudo[chave] = entrada;
|
|
mkdirSync(DIR, { recursive: true });
|
|
writeFileSync(ARQ, JSON.stringify(tudo, null, 2), { mode: 0o600 });
|
|
try { chmodSync(ARQ, 0o600); } catch { /* Windows: ACL do perfil do usuário */ }
|
|
}
|
|
const ler = () => lerTudo()[chave] || {};
|
|
|
|
// ---------- protocolo ----------
|
|
async function discovery() {
|
|
const url = `${o.authority}/.well-known/openid-configuration`;
|
|
const r = await fetch(url);
|
|
if (!r.ok) falha(`discovery respondeu HTTP ${r.status} em ${url} — confira o --authority (inclui o prefixo de rota?)`);
|
|
const d = await r.json();
|
|
if (!d.device_authorization_endpoint) falha('o discovery não anuncia device_authorization_endpoint: o servidor não tem o device flow ligado');
|
|
return d;
|
|
}
|
|
|
|
async function postForm(url, campos) {
|
|
const corpo = new URLSearchParams();
|
|
for (const [k, v] of Object.entries(campos)) if (v !== undefined && v !== null) corpo.set(k, v);
|
|
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, body: corpo });
|
|
const texto = await r.text();
|
|
let json = null;
|
|
try { json = JSON.parse(texto); } catch { /* corpo não-JSON */ }
|
|
return { status: r.status, json, texto };
|
|
}
|
|
|
|
const DICAS = {
|
|
unauthorized_client: 'o client não tem o grant device_code neste ambiente (cadastro do servidor; em produção, grant novo em client existente pode levar o TTL do cache)',
|
|
invalid_client: 'client inexistente, ou confidencial sem secret — use --secret-env',
|
|
invalid_scope: 'algum escopo pedido não existe ou não está liberado para este client',
|
|
invalid_grant: 'device_code inexistente ou de outro client — rode start de novo',
|
|
access_denied: 'o usuário clicou Negar',
|
|
expired_token: 'o código venceu sem decisão — rode start de novo',
|
|
};
|
|
function erroOAuth(resp, etapa) {
|
|
const e = resp.json?.error;
|
|
if (!e) falha(`${etapa}: HTTP ${resp.status} sem erro OAuth no corpo: ${resp.texto.slice(0, 300)}`);
|
|
falha(`${etapa}: ${e}${resp.json.error_description ? ` (${resp.json.error_description})` : ''} — ${DICAS[e] || 'veja a tabela de erros da SKILL.md'}`);
|
|
}
|
|
|
|
function decodificar(jwt) {
|
|
const partes = String(jwt).split('.');
|
|
if (partes.length !== 3) return null; // token de referência (opaco)
|
|
try { return JSON.parse(Buffer.from(partes[1], 'base64url').toString('utf8')); } catch { return null; }
|
|
}
|
|
|
|
function resumoClaims(token) {
|
|
const c = decodificar(token);
|
|
if (!c) return ' token opaco (de referência): sem claims legíveis — use o introspection endpoint do servidor';
|
|
const exp = c.exp ? new Date(c.exp * 1000) : null;
|
|
const linhas = [];
|
|
for (const k of ['iss', 'aud', 'client_id', 'sub', 'scope', 'amr', 'idp']) if (c[k] !== undefined) linhas.push(` ${k}: ${JSON.stringify(c[k])}`);
|
|
for (const k of Object.keys(c)) if (!['iss', 'aud', 'client_id', 'sub', 'scope', 'amr', 'idp', 'exp', 'nbf', 'iat', 'auth_time', 'jti', 'sid'].includes(k)) linhas.push(` ${k}: ${JSON.stringify(c[k])}`);
|
|
if (exp) linhas.push(` exp: ${exp.toISOString()} (${Math.round((exp - Date.now()) / 60000)} min restantes)`);
|
|
return linhas.join('\n');
|
|
}
|
|
|
|
function guardarTokens(t) {
|
|
const agora = Math.floor(Date.now() / 1000);
|
|
gravar({ ...ler(), pending: undefined, access_token: t.access_token, refresh_token: t.refresh_token || ler().refresh_token, id_token: t.id_token, expires_at: agora + (t.expires_in || 0), scope: t.scope });
|
|
}
|
|
|
|
async function start() {
|
|
if (o.dryRun) { console.log(`POST <device_authorization_endpoint de ${o.authority}> client_id=${o.clientId} scope="${o.scope}"${o.secretEnv ? ` client_secret=<$${o.secretEnv}>` : ''}`); return null; }
|
|
const d = await discovery();
|
|
const r = await postForm(d.device_authorization_endpoint, { client_id: o.clientId, client_secret: secret(), scope: o.scope });
|
|
if (r.status !== 200 || !r.json?.device_code) erroOAuth(r, 'deviceauthorization');
|
|
const j = r.json;
|
|
const agora = Math.floor(Date.now() / 1000);
|
|
gravar({ ...ler(), pending: { device_code: j.device_code, interval: j.interval || 5, expires_at: agora + (j.expires_in || 300), token_endpoint: d.token_endpoint, secretEnv: o.secretEnv } });
|
|
console.log(`Abra no navegador e aprove: ${j.verification_uri_complete || j.verification_uri}`);
|
|
console.log(`Código para conferir na tela: ${j.user_code}`);
|
|
console.log(`Vence em ${j.expires_in || 300} s. Depois rode o subcomando poll.`);
|
|
return j;
|
|
}
|
|
|
|
async function poll() {
|
|
if (o.dryRun) { console.log(`POST <token_endpoint> grant_type=${GRANT} device_code=<guardado> client_id=${o.clientId}`); return; }
|
|
const p = ler().pending;
|
|
if (!p) falha('nenhum código pendente para este authority + client_id — rode start');
|
|
if (p.secretEnv && !o.secretEnv) o.secretEnv = p.secretEnv;
|
|
// Só apaga o pendente se ainda for o deste poll: um `start` novo rodado enquanto este poll esperava
|
|
// gravou outro device_code, e apagá-lo deixaria o poll seguinte sem código.
|
|
const limparPendente = () => { const atual = ler(); if (atual.pending?.device_code === p.device_code) gravar({ ...atual, pending: undefined }); };
|
|
let intervalo = p.interval;
|
|
for (;;) {
|
|
if (ler().pending?.device_code !== p.device_code) falha('outro start gerou um código novo — este poll foi encerrado; rode poll de novo');
|
|
if (Date.now() / 1000 > p.expires_at) { limparPendente(); falha('expired_token (pelo relógio local) — rode start de novo'); }
|
|
await new Promise((res) => setTimeout(res, intervalo * 1000));
|
|
const r = await postForm(p.token_endpoint, { grant_type: GRANT, device_code: p.device_code, client_id: o.clientId, client_secret: secret() });
|
|
if (r.status === 200 && r.json?.access_token) {
|
|
guardarTokens(r.json);
|
|
console.log(`Token obtido e guardado em ${ARQ} (não impresso). Claims do access token:`);
|
|
console.log(resumoClaims(r.json.access_token));
|
|
if (!r.json.refresh_token) console.log(' sem refresh_token: peça offline_access no --scope (e o client precisa permitir) para renovar sem novo login');
|
|
return;
|
|
}
|
|
const e = r.json?.error;
|
|
if (e === 'authorization_pending') continue;
|
|
if (e === 'slow_down') { intervalo += 5; continue; } // RFC 8628 §3.5
|
|
limparPendente();
|
|
erroOAuth(r, 'polling');
|
|
}
|
|
}
|
|
|
|
async function tokenValido() {
|
|
const t = ler();
|
|
if (!t.access_token) falha('nenhum token guardado para este authority + client_id — rode start e poll');
|
|
if (t.expires_at - Date.now() / 1000 > 60) return t.access_token;
|
|
if (!t.refresh_token) falha('token vencido e sem refresh_token — rode start e poll de novo');
|
|
const d = await discovery();
|
|
const r = await postForm(d.token_endpoint, { grant_type: 'refresh_token', refresh_token: t.refresh_token, client_id: o.clientId, client_secret: secret() });
|
|
if (r.status !== 200 || !r.json?.access_token) erroOAuth(r, 'refresh');
|
|
guardarTokens(r.json);
|
|
console.error('(token renovado pelo refresh_token)');
|
|
return r.json.access_token;
|
|
}
|
|
|
|
async function call() {
|
|
const corpo = o.body ? readFileSync(o.body, 'utf8') : undefined;
|
|
if (o.dryRun) { console.log(`${o.method} ${o.url} Authorization: Bearer <token guardado>${corpo ? ` corpo: ${o.body}` : ''}`); return; }
|
|
const token = await tokenValido();
|
|
const headers = { Authorization: `Bearer ${token}`, Accept: 'application/json' };
|
|
if (corpo) headers['Content-Type'] = 'application/json';
|
|
const r = await fetch(o.url, { method: o.method, headers, body: corpo });
|
|
console.log(`HTTP ${r.status} ${r.statusText}`);
|
|
const www = r.headers.get('www-authenticate');
|
|
if (www) console.log(`WWW-Authenticate: ${www}`); // motivo do 401 (audience, issuer, assinatura…)
|
|
const texto = await r.text();
|
|
if (texto) console.log(texto);
|
|
if (r.status >= 400) process.exitCode = 1;
|
|
}
|
|
|
|
if (cmd === 'start') await start();
|
|
else if (cmd === 'poll') await poll();
|
|
else if (cmd === 'login') { if (await start()) await poll(); }
|
|
else if (cmd === 'claims') { const t = ler(); if (!t.access_token) falha('nenhum token guardado'); console.log(resumoClaims(t.access_token)); }
|
|
else if (cmd === 'call') await call();
|
|
else if (cmd === 'logout') { if (!o.dryRun) gravar(null); console.log('token e código pendente apagados para este authority + client_id'); }
|