Feat : Setup cloudflare worker for cloud endpoint
This commit is contained in:
72
cloud/src/utils/apiKey.js
Normal file
72
cloud/src/utils/apiKey.js
Normal file
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* API Key utilities for Worker
|
||||
* Supports both formats:
|
||||
* - New: sk-{machineId}-{keyId}-{crc8}
|
||||
* - Old: sk-{random8}
|
||||
*/
|
||||
|
||||
const API_KEY_SECRET = "endpoint-proxy-api-key-secret";
|
||||
|
||||
/**
|
||||
* Generate CRC (8-char HMAC) using Web Crypto API
|
||||
*/
|
||||
async function generateCrc(machineId, keyId) {
|
||||
const encoder = new TextEncoder();
|
||||
const keyData = encoder.encode(API_KEY_SECRET);
|
||||
const data = encoder.encode(machineId + keyId);
|
||||
|
||||
const key = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
keyData,
|
||||
{ name: "HMAC", hash: "SHA-256" },
|
||||
false,
|
||||
["sign"]
|
||||
);
|
||||
|
||||
const signature = await crypto.subtle.sign("HMAC", key, data);
|
||||
const hashArray = Array.from(new Uint8Array(signature));
|
||||
const hashHex = hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
|
||||
|
||||
return hashHex.slice(0, 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse API key and extract machineId + keyId
|
||||
* @param {string} apiKey
|
||||
* @returns {Promise<{ machineId: string, keyId: string, isNewFormat: boolean } | null>}
|
||||
*/
|
||||
export async function parseApiKey(apiKey) {
|
||||
if (!apiKey || !apiKey.startsWith("sk-")) return null;
|
||||
|
||||
const parts = apiKey.split("-");
|
||||
|
||||
// New format: sk-{machineId}-{keyId}-{crc8} = 4 parts
|
||||
if (parts.length === 4) {
|
||||
const [, machineId, keyId, crc] = parts;
|
||||
|
||||
// Verify CRC
|
||||
const expectedCrc = await generateCrc(machineId, keyId);
|
||||
if (crc !== expectedCrc) return null;
|
||||
|
||||
return { machineId, keyId, isNewFormat: true };
|
||||
}
|
||||
|
||||
// Old format: sk-{random8} = 2 parts
|
||||
if (parts.length === 2) {
|
||||
return { machineId: null, keyId: parts[1], isNewFormat: false };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Bearer token from Authorization header
|
||||
* @param {Request} request
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function extractBearerToken(request) {
|
||||
const authHeader = request.headers.get("Authorization");
|
||||
if (!authHeader || !authHeader.startsWith("Bearer ")) return null;
|
||||
return authHeader.slice(7);
|
||||
}
|
||||
|
||||
84
cloud/src/utils/logger.js
Normal file
84
cloud/src/utils/logger.js
Normal file
@@ -0,0 +1,84 @@
|
||||
// Logger utility for worker
|
||||
|
||||
const LOG_LEVELS = {
|
||||
DEBUG: 0,
|
||||
INFO: 1,
|
||||
WARN: 2,
|
||||
ERROR: 3
|
||||
};
|
||||
|
||||
const LEVEL = LOG_LEVELS.INFO;
|
||||
|
||||
// ANSI color codes
|
||||
const COLORS = {
|
||||
reset: "\x1b[0m",
|
||||
red: "\x1b[31m",
|
||||
green: "\x1b[32m",
|
||||
yellow: "\x1b[33m",
|
||||
blue: "\x1b[34m",
|
||||
cyan: "\x1b[36m"
|
||||
};
|
||||
|
||||
function formatTime() {
|
||||
return new Date().toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
|
||||
function formatInline(data) {
|
||||
if (!data) return "";
|
||||
if (typeof data === "string") return data;
|
||||
try {
|
||||
return Object.entries(data).map(([k, v]) => `${k}=${v}`).join(" | ");
|
||||
} catch {
|
||||
return String(data);
|
||||
}
|
||||
}
|
||||
|
||||
export function debug(tag, message, data) {
|
||||
if (LEVEL <= LOG_LEVELS.DEBUG) {
|
||||
const extra = data ? ` | ${formatInline(data)}` : "";
|
||||
console.log(`[${formatTime()}] 🔍 [${tag}] ${message}${extra}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function info(tag, message, data) {
|
||||
if (LEVEL <= LOG_LEVELS.INFO) {
|
||||
const extra = data ? ` | ${formatInline(data)}` : "";
|
||||
console.log(`[${formatTime()}] ℹ️ [${tag}] ${message}${extra}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function warn(tag, message, data) {
|
||||
if (LEVEL <= LOG_LEVELS.WARN) {
|
||||
const extra = data ? ` | ${formatInline(data)}` : "";
|
||||
console.warn(`${COLORS.yellow}[${formatTime()}] ⚠️ [${tag}] ${message}${extra}${COLORS.reset}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function error(tag, message, data) {
|
||||
if (LEVEL <= LOG_LEVELS.ERROR) {
|
||||
const extra = data ? ` | ${formatInline(data)}` : "";
|
||||
console.error(`${COLORS.red}[${formatTime()}] ❌ [${tag}] ${message}${extra}${COLORS.reset}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function request(method, path, extra) {
|
||||
const data = extra ? ` | ${formatInline(extra)}` : "";
|
||||
console.log(`[${formatTime()}] 📥 ${method} ${path}${data}`);
|
||||
}
|
||||
|
||||
export function response(status, duration, extra) {
|
||||
const icon = status < 400 ? "📤" : "💥";
|
||||
const data = extra ? ` | ${formatInline(extra)}` : "";
|
||||
console.log(`[${formatTime()}] ${icon} ${status} (${duration}ms)${data}`);
|
||||
}
|
||||
|
||||
export function stream(event, data) {
|
||||
const extra = data ? ` | ${formatInline(data)}` : "";
|
||||
console.log(`[${formatTime()}] 🌊 [STREAM] ${event}${extra}`);
|
||||
}
|
||||
|
||||
// Mask sensitive data
|
||||
export function maskKey(key) {
|
||||
if (!key || key.length < 8) return "***";
|
||||
return `${key.slice(0, 4)}...${key.slice(-4)}`;
|
||||
}
|
||||
Reference in New Issue
Block a user