275 lines
9.0 KiB
TypeScript
275 lines
9.0 KiB
TypeScript
/**
|
|
* Script de UNA SOLA VEZ para obtener un refresh token de Google.
|
|
*
|
|
* Uso:
|
|
* 1. Pega tu Client ID, Client Secret y correo en .env.local
|
|
* 2. Ejecuta: npm run get-token
|
|
* 3. Autoriza en el navegador. El refresh_token se imprime y se guarda
|
|
* automáticamente en GOOGLE_REFRESH_TOKEN dentro de .env.local
|
|
*
|
|
* Nunca se imprime el Client Secret en consola ni en logs.
|
|
*/
|
|
|
|
import http from "node:http";
|
|
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
|
import { resolve } from "node:path";
|
|
import { exec } from "node:child_process";
|
|
import { google } from "googleapis";
|
|
|
|
const RUTA_ENV = resolve(process.cwd(), ".env.local");
|
|
const PUERTO = 5555;
|
|
const RUTA_CALLBACK = "/oauth2callback";
|
|
const SCOPES = [
|
|
"https://www.googleapis.com/auth/calendar",
|
|
"https://www.googleapis.com/auth/gmail.send",
|
|
];
|
|
|
|
// Valores placeholder que vienen en el .env.local recién creado.
|
|
const PLACEHOLDERS = new Set([
|
|
"PEGA_AQUI_TU_CLIENT_ID",
|
|
"PEGA_AQUI_TU_CLIENT_SECRET",
|
|
]);
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Manejo de .env.local (sin dependencias extra)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Parsea el contenido de un archivo .env a un objeto clave/valor. */
|
|
function parsearEnv(contenido: string): Record<string, string> {
|
|
const env: Record<string, string> = {};
|
|
for (const lineaCruda of contenido.split("\n")) {
|
|
const linea = lineaCruda.trim();
|
|
if (!linea || linea.startsWith("#")) continue;
|
|
const idx = linea.indexOf("=");
|
|
if (idx === -1) continue;
|
|
const clave = linea.slice(0, idx).trim();
|
|
let valor = linea.slice(idx + 1).trim();
|
|
// Quita comillas envolventes si las hubiera.
|
|
if (
|
|
(valor.startsWith('"') && valor.endsWith('"')) ||
|
|
(valor.startsWith("'") && valor.endsWith("'"))
|
|
) {
|
|
valor = valor.slice(1, -1);
|
|
}
|
|
env[clave] = valor;
|
|
}
|
|
return env;
|
|
}
|
|
|
|
/** Lee y parsea .env.local. */
|
|
function cargarEnv(): Record<string, string> {
|
|
if (!existsSync(RUTA_ENV)) {
|
|
console.error("❌ No se encontró .env.local en la raíz del proyecto.");
|
|
process.exit(1);
|
|
}
|
|
return parsearEnv(readFileSync(RUTA_ENV, "utf8"));
|
|
}
|
|
|
|
/**
|
|
* Actualiza (o agrega) una variable dentro de .env.local conservando el resto
|
|
* de las líneas tal cual.
|
|
*/
|
|
function actualizarEnv(clave: string, valor: string): void {
|
|
const contenido = existsSync(RUTA_ENV) ? readFileSync(RUTA_ENV, "utf8") : "";
|
|
const lineas = contenido.split("\n");
|
|
let encontrado = false;
|
|
|
|
const nuevas = lineas.map((linea) => {
|
|
if (linea.trimStart().startsWith(`${clave}=`)) {
|
|
encontrado = true;
|
|
return `${clave}=${valor}`;
|
|
}
|
|
return linea;
|
|
});
|
|
|
|
if (!encontrado) nuevas.push(`${clave}=${valor}`);
|
|
writeFileSync(RUTA_ENV, nuevas.join("\n"));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Utilidades
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Intenta abrir una URL en el navegador por defecto del sistema. */
|
|
function abrirNavegador(url: string): void {
|
|
const comando =
|
|
process.platform === "darwin"
|
|
? "open"
|
|
: process.platform === "win32"
|
|
? 'start ""'
|
|
: "xdg-open";
|
|
exec(`${comando} "${url}"`, (error) => {
|
|
if (error) {
|
|
// Silencioso: la URL ya se imprimió, el usuario puede abrirla a mano.
|
|
}
|
|
});
|
|
}
|
|
|
|
/** HTML simple para mostrar en el navegador al terminar. */
|
|
function paginaResultado(titulo: string, mensaje: string, ok: boolean): string {
|
|
const color = ok ? "#16a34a" : "#dc2626";
|
|
return `<!doctype html><html lang="es"><head><meta charset="utf-8">
|
|
<title>${titulo}</title></head>
|
|
<body style="font-family:-apple-system,Helvetica,Arial,sans-serif;background:#f3f5fb;display:grid;place-items:center;height:100vh;margin:0">
|
|
<div style="background:#fff;border:1px solid #e6e8f0;border-radius:16px;padding:40px 48px;text-align:center;max-width:440px">
|
|
<div style="font-size:42px;color:${color};line-height:1">${ok ? "✓" : "✕"}</div>
|
|
<h1 style="color:#13284b;font-size:20px;margin:12px 0 8px">${titulo}</h1>
|
|
<p style="color:#54658a;font-size:15px;margin:0">${mensaje}</p>
|
|
</div></body></html>`;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Flujo principal
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function main(): void {
|
|
const env = cargarEnv();
|
|
const clientId = env.GOOGLE_CLIENT_ID;
|
|
const clientSecret = env.GOOGLE_CLIENT_SECRET;
|
|
const redirectUri = env.GOOGLE_REDIRECT_URI;
|
|
|
|
// Validación de credenciales (sin imprimir el secret).
|
|
const faltantes: string[] = [];
|
|
if (!clientId || PLACEHOLDERS.has(clientId)) faltantes.push("GOOGLE_CLIENT_ID");
|
|
if (!clientSecret || PLACEHOLDERS.has(clientSecret))
|
|
faltantes.push("GOOGLE_CLIENT_SECRET");
|
|
if (!redirectUri) faltantes.push("GOOGLE_REDIRECT_URI");
|
|
|
|
if (faltantes.length > 0) {
|
|
console.error(
|
|
`\n❌ Faltan valores reales en .env.local: ${faltantes.join(", ")}`
|
|
);
|
|
console.error(
|
|
" Pega tu Client ID, Client Secret y el Redirect URI antes de continuar.\n"
|
|
);
|
|
process.exit(1);
|
|
}
|
|
|
|
// Cliente OAuth2 (de google-auth-library, expuesto vía googleapis).
|
|
const oauth2Client = new google.auth.OAuth2(
|
|
clientId,
|
|
clientSecret,
|
|
redirectUri
|
|
);
|
|
|
|
const authUrl = oauth2Client.generateAuthUrl({
|
|
access_type: "offline",
|
|
prompt: "consent",
|
|
scope: SCOPES,
|
|
});
|
|
|
|
const servidor = http.createServer(async (req, res) => {
|
|
const url = new URL(req.url ?? "/", `http://localhost:${PUERTO}`);
|
|
|
|
if (url.pathname !== RUTA_CALLBACK) {
|
|
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
|
res.end("Ruta no encontrada.");
|
|
return;
|
|
}
|
|
|
|
const error = url.searchParams.get("error");
|
|
const code = url.searchParams.get("code");
|
|
|
|
if (error) {
|
|
console.error(`\n❌ Google devolvió un error de autorización: ${error}\n`);
|
|
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
res.end(
|
|
paginaResultado(
|
|
"Autorización cancelada",
|
|
"Vuelve a la terminal e inténtalo de nuevo.",
|
|
false
|
|
)
|
|
);
|
|
servidor.close(() => process.exit(1));
|
|
return;
|
|
}
|
|
|
|
if (!code) {
|
|
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
res.end(
|
|
paginaResultado(
|
|
"Falta el parámetro de autorización",
|
|
"No se recibió el 'code' de Google.",
|
|
false
|
|
)
|
|
);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const { tokens } = await oauth2Client.getToken(code);
|
|
const refreshToken = tokens.refresh_token;
|
|
|
|
if (!refreshToken) {
|
|
console.error("\n❌ Google no devolvió un refresh_token.");
|
|
console.error(
|
|
" Asegúrate de usar prompt=consent (ya está en el script) y de revocar"
|
|
);
|
|
console.error(
|
|
" el acceso previo en https://myaccount.google.com/permissions, luego reintenta.\n"
|
|
);
|
|
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
res.end(
|
|
paginaResultado(
|
|
"No se recibió refresh_token",
|
|
"Revoca el acceso de la app en tu cuenta de Google y vuelve a ejecutar el script.",
|
|
false
|
|
)
|
|
);
|
|
servidor.close(() => process.exit(1));
|
|
return;
|
|
}
|
|
|
|
// Guarda el refresh token en .env.local.
|
|
actualizarEnv("GOOGLE_REFRESH_TOKEN", refreshToken);
|
|
|
|
console.log("\n✅ ¡Refresh token obtenido y guardado en .env.local!\n");
|
|
console.log(" GOOGLE_REFRESH_TOKEN=" + refreshToken + "\n");
|
|
|
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
res.end(
|
|
paginaResultado(
|
|
"¡Listo! Token obtenido",
|
|
"El refresh token se guardó en .env.local. Ya puedes cerrar esta pestaña.",
|
|
true
|
|
)
|
|
);
|
|
|
|
servidor.close(() => process.exit(0));
|
|
} catch (e) {
|
|
const mensaje = e instanceof Error ? e.message : String(e);
|
|
console.error(`\n❌ Error al intercambiar el code por tokens: ${mensaje}\n`);
|
|
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
|
res.end(
|
|
paginaResultado(
|
|
"Error al obtener el token",
|
|
"Revisa la terminal para ver el detalle del error.",
|
|
false
|
|
)
|
|
);
|
|
servidor.close(() => process.exit(1));
|
|
}
|
|
});
|
|
|
|
servidor.listen(PUERTO, () => {
|
|
console.log("\n🔑 Generador de refresh token de Google\n");
|
|
console.log("1) Abre esta URL en tu navegador (intentaré abrirla por ti):\n");
|
|
console.log(" " + authUrl + "\n");
|
|
console.log(`2) Esperando el callback en http://localhost:${PUERTO}${RUTA_CALLBACK} ...\n`);
|
|
abrirNavegador(authUrl);
|
|
});
|
|
|
|
servidor.on("error", (e: NodeJS.ErrnoException) => {
|
|
if (e.code === "EADDRINUSE") {
|
|
console.error(
|
|
`\n❌ El puerto ${PUERTO} ya está en uso. Cierra lo que lo ocupe y reintenta.\n`
|
|
);
|
|
} else {
|
|
console.error(`\n❌ Error del servidor local: ${e.message}\n`);
|
|
}
|
|
process.exit(1);
|
|
});
|
|
}
|
|
|
|
main();
|