Skip to content

Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base

add optionnal auth

Hugo Richard2610ef5a80fb
diff --git a/apps/api/middleware/auth.ts b/apps/api/middleware/auth.ts
new file mode 100644
index 0000000..bf25f88
--- /dev/null
+++ b/apps/api/middleware/auth.ts
@@ -0,0 +1,51 @@
+import { defineMiddleware, getRequestURL, HTTPError } from 'nitro/h3'
+import { useRuntimeConfig } from 'nitro/runtime-config'
+
+/** Paths that don't require authentication */
+const PUBLIC_PATHS = [
+ '/api', // Health check
+ '/.well-known/',
+ '/health',
+ '/favicon.ico',
+]
+
+function isPublicPath(pathname: string): boolean {
+ return PUBLIC_PATHS.some(path =>
+ pathname === path || pathname.startsWith(`${path}/`.replace('//', '/')),
+ )
+}
+
+/**
+ * Optional API key authentication middleware
+ *
+ * Only enforces authentication if SAVOIR_SECRET_KEY is set.
+ * If not set, all requests are allowed (useful for development).
+ *
+ * Expected header: Authorization: Bearer <api-key>
+ */
+export default defineMiddleware((event, next) => {
+ const config = useRuntimeConfig()
+ const secretKey = config.savoirSecretKey
+
+ // If no secret key configured, skip authentication
+ if (!secretKey) {
+ return next()
+ }
+
+ const url = getRequestURL(event)
+
+ // Skip auth for public paths
+ if (isPublicPath(url.pathname)) {
+ return next()
+ }
+
+ // Validate API key
+ const authHeader = event.req.headers.get('Authorization')
+ const apiKey = authHeader?.replace('Bearer ', '')
+
+ if (!apiKey || apiKey !== secretKey) {
+ throw new HTTPError({ status: 401, message: 'Invalid or missing API key' })
+ }
+
+ return next()
+})
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index eb55a9e..57f1240 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -329,12 +329,14 @@ async function readFromSandbox(sandbox: Sandbox, paths: string[]): Promise<FileC
### Authentication
-All endpoints require an API key in the `Authorization` header:
+Authentication is optional. If `SAVOIR_SECRET_KEY` is configured, endpoints require an API key:
```
Authorization: Bearer <api-key>
```
+If not configured, the API is open (useful for local development).
+
### Source Endpoints
#### GET /api/sources
@@ -587,17 +589,35 @@ export class SavoirError extends Error {
## Security
-### API Key Validation
+### API Key Validation (Optional)
+
+Authentication is **optional** and only enforced if `SAVOIR_SECRET_KEY` is set.
+
+- If `SAVOIR_SECRET_KEY` is not set → API is open (useful for development)
+- If `SAVOIR_SECRET_KEY` is set → All requests require `Authorization: Bearer <key>`
```typescript
// apps/api/middleware/auth.ts
-export default defineEventHandler((event) => {
- const auth = getHeader(event, 'Authorization')
- const apiKey = auth?.replace('Bearer ', '')
+export default defineMiddleware((event, next) => {
+ const secretKey = useRuntimeConfig().savoirSecretKey
+
+ // Skip auth if no secret key configured
+ if (!secretKey) {
+ return next()
+ }
- if (!apiKey || apiKey !== useRuntimeConfig().savoirSecretKey) {
+ // Skip auth for public paths (/api health check, etc.)
+ if (isPublicPath(url.pathname)) {
+ return next()
+ }
+
+ const apiKey = getHeader(event, 'Authorization')?.replace('Bearer ', '')
+
+ if (!apiKey || apiKey !== secretKey) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
+
+ return next()
})
```