Skip to content

Commit

Permalink
fix: Replace public key auth with token-based system
Browse files Browse the repository at this point in the history
  • Loading branch information
nadeesha committed Dec 31, 2024
1 parent 3330361 commit 95f5cf0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 72 deletions.
2 changes: 1 addition & 1 deletion adapters/valtown-adapter/jsr.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@inferable/valtown-adapter",
"version": "0.0.5",
"version": "0.0.8",
"license": "MIT",
"exports": "./mod.ts"
}
96 changes: 25 additions & 71 deletions adapters/valtown-adapter/mod.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,13 @@
const {
createVerify,
} = await import('node:crypto');

export class InferableService {
private functions: Parameters<InferableService["registerFunction"]>[0][] = [];

constructor(
private options: {
description: string;
publicKey: string;
token?: string;
},
) {
if (this.options.publicKey) {
const hasPrefix = this.options.publicKey.startsWith("-----BEGIN PUBLIC KEY-----");

if (!hasPrefix) {
const base64Content = this.options.publicKey;
const lines = base64Content.match(/.{1,64}/g) || [];
const formatted = [
"-----BEGIN PUBLIC KEY-----",
...lines,
"-----END PUBLIC KEY-----",
].join("\n");

this.options.publicKey = formatted;
}
}
// Remove public key formatting logic as it's no longer needed
}

registerFunction(options: {
Expand All @@ -43,57 +25,35 @@ export class InferableService {
this.functions.push(options);
}

private isAuthenticated({
xTimestamp,
xSignature,
method,
path,
body,
}: {
xTimestamp: string;
xSignature: string;
method: string;
path: string;
body: string;
}): boolean {
const signatureFromHeader = xSignature;

if (!signatureFromHeader) {
return false;
private isAuthenticated(token: string | null): boolean {
if (!this.options.token) {
return true; // If no token is configured, authentication is disabled
}

console.log("About to verify", {
xTimestamp,
method,
path,
body,
signatureFromHeader,
publicKey: this.options.publicKey,
});

const verifier = createVerify("SHA256");
const message = `${xTimestamp}${method}${path}${body}`;
console.log("Message to verify:", message);
verifier.update(message);
verifier.end();
const result = verifier.verify(this.options.publicKey, signatureFromHeader, "hex");
console.log("Verification result:", result);
return result;
return token === this.options.token;
}

getServer(): (request: Request) => Promise<Response> {
const server = async (request: Request): Promise<Response> => {
const url = new URL(request.url);
const path = url.pathname;

const hasPublicKey = this.options.publicKey !== undefined;
const hasToken = this.options.token !== undefined;
const authHeader = request.headers.get("Authorization");
const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : null;

if (!hasPublicKey) {
console.warn("No public key provided. Authentication is disabled. See https://docs.inferable.ai/valtown to learn how to enable it.");
if (!hasToken) {
console.warn("No token provided. Authentication is disabled. See https://docs.inferable.ai/valtown to learn how to enable it.");
}

// Metadata route
if (path === "/meta") {
if (hasToken && !this.isAuthenticated(token)) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
headers: { "content-type": "application/json" },
});
}

return new Response(
JSON.stringify({
description: this.options.description,
Expand All @@ -111,6 +71,13 @@ export class InferableService {

// Execution route
if (path.startsWith("/exec/functions/")) {
if (hasToken && !this.isAuthenticated(token)) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
headers: { "content-type": "application/json" },
});
}

const body = await request.body?.getReader().read();
const bodyText = body ? new TextDecoder().decode(body.value) : "";

Expand All @@ -121,19 +88,6 @@ export class InferableService {
});
}

if (hasPublicKey && !this.isAuthenticated({
xTimestamp: request.headers.get("X-Timestamp") || "",
xSignature: request.headers.get("X-Signature") || "",
method: request.method,
path,
body: bodyText,
})) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
headers: { "content-type": "application/json" },
});
}

const functionName = path.split("/")[3];

if (request.method !== "POST") {
Expand Down

0 comments on commit 95f5cf0

Please sign in to comment.