52 lines
1.9 KiB
JavaScript
52 lines
1.9 KiB
JavaScript
import { createHmac, randomBytes } from "node:crypto";
|
|
import pg from "pg";
|
|
|
|
const args = process.argv.slice(2);
|
|
const get = (name, fallback) => {
|
|
const index = args.indexOf(`--${name}`);
|
|
return index >= 0 ? args[index + 1] : fallback;
|
|
};
|
|
|
|
const app = get("app");
|
|
if (!app) {
|
|
console.error("Aufruf: npm run db:key -- --app plan --name 'Plan' [--daily 400] [--monthly 12000] [--from plan@hubsport.club]");
|
|
process.exit(1);
|
|
}
|
|
|
|
const name = get("name", app);
|
|
const domain = get("domain", process.env.MAIL_FROM_DOMAIN || "hubsport.club");
|
|
const daily = Number(get("daily", 500));
|
|
const monthly = Number(get("monthly", 15000));
|
|
const from = get("from");
|
|
const pepper = process.env.API_KEY_PEPPER || "dev-only-pepper";
|
|
const key = `ck_live_${randomBytes(24).toString("base64url")}`;
|
|
const hash = createHmac("sha256", pepper).update(key).digest("hex");
|
|
const prefix = key.slice(0, 16);
|
|
|
|
function databaseUrl() {
|
|
if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
|
|
const host = process.env.DB_HOST;
|
|
if (host) {
|
|
const user = encodeURIComponent(process.env.DB_USER ?? "");
|
|
const password = encodeURIComponent(process.env.DB_PASSWORD ?? "");
|
|
const name = process.env.DB_NAME ?? "courier";
|
|
const port = process.env.DB_PORT ?? "5432";
|
|
return `postgresql://${user}:${password}@${host}:${port}/${name}`;
|
|
}
|
|
return `postgresql://courier@127.0.0.1:${process.env.DB_PORT || "55432"}/courier`;
|
|
}
|
|
|
|
const url = databaseUrl();
|
|
const client = new pg.Client({ connectionString: url });
|
|
await client.connect();
|
|
const { rows } = await client.query(
|
|
`insert into api_keys (app, name, prefix, key_hash, from_domain, allowed_from, daily_limit, monthly_limit)
|
|
values ($1,$2,$3,$4,$5,$6,$7,$8)
|
|
returning id, app, created_at`,
|
|
[app, name, prefix, hash, domain, from ? [from] : null, daily, monthly],
|
|
);
|
|
await client.end();
|
|
|
|
console.log(JSON.stringify(rows[0], null, 2));
|
|
console.log(`\nAPI-Key (nur jetzt sichtbar):\n${key}\n`);
|