瀏覽代碼

feat: add internal API key generator script #50

- Helper script to generate internal API keys with bcrypt hash
- Outputs ready-to-use SQL INSERT statement
- Simplifies key creation process
Claude 5 月之前
父節點
當前提交
dfe12902a7
共有 1 個文件被更改,包括 85 次插入0 次删除
  1. 85 0
      scripts/generate-internal-api-key.ts

+ 85 - 0
scripts/generate-internal-api-key.ts

@@ -0,0 +1,85 @@
+#!/usr/bin/env -S deno run --allow-env
+
+/**
+ * Internal API Key Generator
+ *
+ * Generates a secure internal API key and its bcrypt hash for manual insertion
+ * into the internal_api_keys table.
+ *
+ * Usage:
+ *   deno run --allow-env scripts/generate-internal-api-key.ts [key_name]
+ *
+ * Example:
+ *   deno run --allow-env scripts/generate-internal-api-key.ts "Analytics Service"
+ */
+
+import * as bcrypt from "https://deno.land/x/bcrypt@v0.4.1/mod.ts";
+
+function generateApiKey(): string {
+  const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
+  const length = 48;
+  let result = "int_shopcall_";
+
+  for (let i = 0; i < length; i++) {
+    result += characters.charAt(Math.floor(Math.random() * characters.length));
+  }
+
+  return result;
+}
+
+async function hashApiKey(apiKey: string): Promise<string> {
+  const salt = await bcrypt.genSalt(12);
+  return await bcrypt.hash(apiKey, salt);
+}
+
+async function main() {
+  const args = Deno.args;
+  const keyName = args[0] || "Untitled Internal Key";
+
+  console.log("\n🔑 Generating Internal API Key...\n");
+  console.log("━".repeat(80));
+
+  // Generate API key
+  const apiKey = generateApiKey();
+  console.log("\n✅ API Key Generated:");
+  console.log(`   ${apiKey}`);
+
+  // Generate hash
+  console.log("\n⏳ Generating bcrypt hash (this may take a few seconds)...");
+  const hash = await hashApiKey(apiKey);
+  console.log("✅ Hash Generated:");
+  console.log(`   ${hash}`);
+
+  // Generate SQL
+  console.log("\n📝 SQL INSERT Statement:");
+  console.log("━".repeat(80));
+  console.log(`
+INSERT INTO internal_api_keys (
+  key_name,
+  api_key,
+  key_hash,
+  description,
+  created_by,
+  expires_at
+) VALUES (
+  '${keyName}',
+  '${apiKey}',
+  '${hash}',
+  'Auto-generated internal API key',
+  'admin',
+  NULL  -- or set expiration: '2025-12-31 23:59:59+00'
+);
+`);
+
+  console.log("━".repeat(80));
+  console.log("\n⚠️  IMPORTANT:");
+  console.log("   1. Store the API key securely - it cannot be retrieved later!");
+  console.log("   2. Execute the SQL statement in your Supabase database");
+  console.log("   3. Update the description and created_by fields as needed");
+  console.log("   4. Set an expiration date if required");
+  console.log("\n📚 See INTERNAL_API_KEYS.md for usage documentation\n");
+}
+
+if (import.meta.main) {
+  main();
+}