generate-internal-api-key.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env -S deno run --allow-env
  2. /**
  3. * Internal API Key Generator
  4. *
  5. * Generates a secure internal API key and its bcrypt hash for manual insertion
  6. * into the internal_api_keys table.
  7. *
  8. * Usage:
  9. * deno run --allow-env scripts/generate-internal-api-key.ts [key_name]
  10. *
  11. * Example:
  12. * deno run --allow-env scripts/generate-internal-api-key.ts "Analytics Service"
  13. */
  14. import * as bcrypt from "https://deno.land/x/bcrypt@v0.4.1/mod.ts";
  15. function generateApiKey(): string {
  16. const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
  17. const length = 48;
  18. let result = "int_shopcall_";
  19. for (let i = 0; i < length; i++) {
  20. result += characters.charAt(Math.floor(Math.random() * characters.length));
  21. }
  22. return result;
  23. }
  24. async function hashApiKey(apiKey: string): Promise<string> {
  25. const salt = await bcrypt.genSalt(12);
  26. return await bcrypt.hash(apiKey, salt);
  27. }
  28. async function main() {
  29. const args = Deno.args;
  30. const keyName = args[0] || "Untitled Internal Key";
  31. console.log("\n🔑 Generating Internal API Key...\n");
  32. console.log("━".repeat(80));
  33. // Generate API key
  34. const apiKey = generateApiKey();
  35. console.log("\n✅ API Key Generated:");
  36. console.log(` ${apiKey}`);
  37. // Generate hash
  38. console.log("\n⏳ Generating bcrypt hash (this may take a few seconds)...");
  39. const hash = await hashApiKey(apiKey);
  40. console.log("✅ Hash Generated:");
  41. console.log(` ${hash}`);
  42. // Generate SQL
  43. console.log("\n📝 SQL INSERT Statement:");
  44. console.log("━".repeat(80));
  45. console.log(`
  46. INSERT INTO internal_api_keys (
  47. key_name,
  48. api_key,
  49. key_hash,
  50. description,
  51. created_by,
  52. expires_at
  53. ) VALUES (
  54. '${keyName}',
  55. '${apiKey}',
  56. '${hash}',
  57. 'Auto-generated internal API key',
  58. 'admin',
  59. NULL -- or set expiration: '2025-12-31 23:59:59+00'
  60. );
  61. `);
  62. console.log("━".repeat(80));
  63. console.log("\n⚠️ IMPORTANT:");
  64. console.log(" 1. Store the API key securely - it cannot be retrieved later!");
  65. console.log(" 2. Execute the SQL statement in your Supabase database");
  66. console.log(" 3. Update the description and created_by fields as needed");
  67. console.log(" 4. Set an expiration date if required");
  68. console.log("\n📚 See INTERNAL_API_KEYS.md for usage documentation\n");
  69. }
  70. if (import.meta.main) {
  71. main();
  72. }