@unkey/hono
Version:
<div align="center"> <h1 align="center">@unkey/hono</h1> <h5>Hono.js middleware for authenticating API keys</h5> </div>
44 lines • 1.21 kB
JavaScript
// src/index.ts
import { Unkey } from "@unkey/api";
import { HTTPException } from "hono/http-exception";
import * as errors from "@unkey/api/models/errors";
function unkey(config) {
const unkey2 = new Unkey({
rootKey: config.rootKey
});
return async (c, next) => {
const key = config.getKey ? config.getKey(c) : c.req.header("Authorization")?.replace("Bearer ", "") ?? null;
if (!key) {
return c.json({ error: "unauthorized" }, { status: 401 });
}
if (typeof key !== "string") {
return key;
}
try {
const res = await unkey2.keys.verifyKey({
key,
permissions: config.permissions,
tags: config.tags
});
if (!res.data.valid && config.handleInvalidKey) {
return config.handleInvalidKey(c, res);
}
c.set("unkey", res);
} catch (err) {
if (err instanceof errors.APIError) {
if (config.onError) {
return config.onError(c, err);
}
throw new HTTPException(500, {
message: `unkey error: [CODE: ${err.statusCode}] - ${err.message}`
});
}
throw err;
}
await next();
};
}
export {
unkey
};
//# sourceMappingURL=index.mjs.map