import * as uuid from "https://deno.land/std/uuid/mod.ts";
import { blob } from "https://esm.town/v/std/blob";
import { getPolicy } from "https://esm.town/v/xkonti/memoryApiPolicy";
import { Hono } from "npm:hono@3";
export const handleMemoryApiRequest = async (
req: Request,
apiName: string,
contactEmail: string,
lastPolicyUpdate: string,
blobKeyPrefix: string,
apiKeyPrefix: string,
) => {
const getMemoriesKey = (key: string): string => {
return `${blobKeyPrefix}${key}`;
};
const getMemories = async (key: string) => {
return await blob.getJSON(getMemoriesKey(key), []);
};
const setMemories = async (memories: any, key: string) => {
await blob.setJSON(getMemoriesKey(key), memories);
};
const verifyRequest = (c): { memoriesKey: string; error: any } => {
const authHeader = c.req.headers.get("Authorization");
if (!authHeader || !authHeader.startsWith("Basic ")) {
console.error("Missing or invalid authorization header");
return { memoriesKey: "", error: c.text("Unauthorized", 401) };
}
const base64Credentials = authHeader.split(" ")[1];
const credentials = atob(base64Credentials);
const [key, token] = credentials.split(":");
if (key == null || key === "") {
console.error("No memory key in authorization header");
return { memoriesKey: "", error: c.text("Forbidden", 403) };
}
const expectedKey = Deno.env.get(apiKeyPrefix + key) ?? null;
if (token !== expectedKey) {
console.error("Invalid API KEY header");
return { memoriesKey: "", error: c.text("Forbidden", 403) };
}
return { memoriesKey: key, error: null };
};
const app = new Hono();
app.get("/memory", async (c) => {
const { memoriesKey, error } = verifyRequest(c);
if (error != null) return error;
const memories = (await getMemories(memoriesKey))
.map(memory => ({
id: memory.id,
name: memory.name,
summary: memory.summary ?? "Missing summary",
reason: memory.reason,
}));
return c.json({
memories,
});
});
app.get("/memory/specific", async (c) => {
const { memoriesKey, error } = verifyRequest(c);
if (error != null) return error;
const idsQuery = c.req.query("ids");
if (!idsQuery) {
return c.text("Bad Request: No IDs provided", 400);
}
const ids = idsQuery.split(",");
if (ids.length === 0) {
return c.text("Bad Request: Invalid IDs format", 400);
}
const memories = await getMemories(memoriesKey);
const requestedMemories = memories.filter(memory => ids.includes(memory.id));
if (requestedMemories.length === 0) {
return c.text("No memories found with the provided IDs", 404);