1// F:\zApps\valtown.servers\APIServer\src\middleware\backendChains.ts
2import type { Context, Next } from "hono";
3import zidTrackingMiddleware from "./zTracker.ts";
1// F:\zApps\valtown.servers\APIServer\src\middleware\auth.session.ts
2import { Context, Next } from "hono";
3import { deleteCookie, getCookie, setCookie } from "hono/cookie";
1// F:\zApps\valtown.servers\APIServer\src\middleware\auth.oauth.ts
2/**
3* OAuth Authentication Middleware for Val.town/Deno
api_ianmenethil_comauthJWT.ts17 matches
1// F:\zApps\valtown.servers\APIServer\src\middleware\auth.jwt.ts
2import { Context, Next } from "hono";
3import { HTTPException } from "hono/http-exception";
12import { getClientIP } from "@/utils/ipUtils.ts";
1314const jwtApiConfig = AUTH_CONFIG.jwt.API;
1516/**
22return await signJwt(
23restPayload as Record<string, unknown>, // Ensure payload matches helper expectation
24jwtApiConfig.secretKey,
25jwtApiConfig.algorithm,
26{
27issuer: jwtApiConfig.issuer,
28audience: jwtApiConfig.audience,
29expiresIn: jwtApiConfig.expiresIn,
30subject: payload.sub || payload.id,
31issuedAt: true,
48const payload = await verifyJwt<AppJwtPayload>(
49token,
50customSecret || jwtApiConfig.secretKey,
51{
52issuer: jwtApiConfig.issuer,
53audience: jwtApiConfig.audience,
54algorithms: [jwtApiConfig.algorithm],
55},
56);
77customSecret?: string,
78): Promise<AuthResult> {
79if (!jwtApiConfig.enabled) {
80return {
81success: false,
237return await signJwt(
238refreshPayload as Record<string, unknown>,
239jwtApiConfig.secretKey,
240jwtApiConfig.algorithm,
241{
242issuer: jwtApiConfig.issuer,
243audience: jwtApiConfig.audience,
244expiresIn: jwtApiConfig.refreshExpiresIn,
245subject: payload.sub || payload.id,
246issuedAt: true,
1// F:\zApps\valtown.servers\APIServer\src\middleware\auth.internal.ts
2import { Context, Next } from "hono";
3import { AUTH_CONFIG } from "../core/authConfig.ts";
api_ianmenethil_comauthentication.ts19 matches
1// F:\zApps\valtown.servers\APIServer\src\middleware\authentication.ts
2import { Context, Next } from "hono";
3import { AUTH_CONFIG } from "../core/authConfig.ts";
13// Import authentication methods
14import { applyJwtAuth } from "./authJWT.ts";
15import { applyApiKeyAuth } from "./authApiKey.ts";
16import { applySessionAuth } from "./authSession.ts";
17import { applyOAuthAuth } from "./authOauth.ts"; // Restored import
20// Re-export all auth modules
21export * from "./authJWT.ts";
22export * from "./authApiKey.ts";
23export * from "./authSession.ts";
24export * from "./authOauth.ts"; // Ensure this file exists and exports applyOAuthAuth
38switch (method) {
39case "jwt":
40if (!AUTH_CONFIG.jwt.API.enabled) {
41return {
42success: false,
43error: { code: "JWT_API_DISABLED", message: "JWT (API) authentication is disabled" },
44};
45}
46return await applyJwtAuth(c.req.raw);
4748case "apiKey":
49if (!AUTH_CONFIG.methods.API_KEY.enabled) {
50return {
51success: false,
52error: { code: "API_KEY_DISABLED", message: "API key authentication is disabled" },
53};
54}
55return applyApiKeyAuth(c.req.raw);
5657case "session":
96export function createAuthMiddleware(options: AuthMiddlewareOptions = {}) {
97const defaultAuthTypes: AuthMethod[] = [
98AUTH_CONFIG.jwt.API.enabled && "jwt",
99AUTH_CONFIG.methods.SESSION.enabled && "session",
100AUTH_CONFIG.methods.API_KEY.enabled && "apiKey",
101AUTH_CONFIG.methods.BASIC.enabled && "basic",
102AUTH_CONFIG.oauth.enabled && "oauth",
110for (const authType of authTypesToTry) {
111if (
112!["jwt", "session", "apiKey", "basic", "oauth", "internal", "webhook", "none"].includes(
113authType,
114)
211* Preset authentication middlewares
212*/
213export const apiAuthMiddleware = createAuthMiddleware({
214methods: ["jwt", "apiKey"],
215});
216225226export const optionalAuthMiddleware = createAuthMiddleware({
227methods: ["jwt", "session", "apiKey"],
228optional: true,
229});
230231export const serviceAuthMiddleware = createAuthMiddleware({
232methods: ["apiKey"],
233});
234276*/
277export const requireJWT = createAuthMiddleware({ methods: ["jwt"] });
278export const requireAPIKey = createAuthMiddleware({ methods: ["apiKey"] });
279export const requireSession = createAuthMiddleware({ methods: ["session"] });
280export const requireBasicAuth = createAuthMiddleware({ methods: ["basic"] });
286export const authenticationMiddleware = createAuthMiddleware({
287methods: [
288AUTH_CONFIG.jwt.API.enabled && "jwt",
289AUTH_CONFIG.methods.SESSION.enabled && "session",
290AUTH_CONFIG.methods.API_KEY.enabled && "apiKey",
291AUTH_CONFIG.methods.BASIC.enabled && "basic",
292AUTH_CONFIG.oauth.enabled && "oauth",
api_ianmenethil_comauthApiKey.ts42 matches
1/**
2* API Key Authentication Middleware for Val.town/Deno
3* Handles API key validation from headers and query parameters
4*/
51314/**
15* Validates API key against configured valid keys
16*/
17export function validateApiKey(apiKey: string): boolean {
18if (!apiKey) return false;
1920const { keys } = AUTH_CONFIG.methods.API_KEY;
21return apiKey === keys.internal ||
22apiKey === keys.serviceToService ||
23apiKey === keys.webhook;
24}
2526/**
27* Validates internal API key for server-to-server communication
28*/
29export function validateInternalApiKey(apiKey: string): boolean {
30return apiKey === AUTH_CONFIG.methods.API_KEY.keys.internal;
31}
3235*/
36export function validateWebhookSecret(secret: string): boolean {
37return secret === AUTH_CONFIG.methods.API_KEY.keys.webhook;
38}
3940/**
41* Validates service-to-service API key
42*/
43export function validateServiceKey(serviceKey: string): boolean {
44return serviceKey === AUTH_CONFIG.methods.API_KEY.keys.serviceToService;
45}
4647/**
48* API Key authentication middleware
49*/
50export async function apiKeyAuthMiddleware(
51c: Context<{ Variables: Variables }>,
52next: () => Promise<void>,
53): Promise<Response | void> {
54const authResult = applyApiKeyAuth(c.req.raw);
5556if (!authResult.success) {
7879/**
80* API Key authentication logic
81*/
82export function applyApiKeyAuth(request: Request): AuthResult {
83const apiKeyConfig = AUTH_CONFIG.methods.API_KEY;
8485if (!apiKeyConfig.enabled) {
86return {
87success: false,
88error: { code: "API_KEY_DISABLED", message: "API key authentication is disabled" },
89response: createResponse(
90{
91success: false,
92error: { code: "API_KEY_DISABLED", message: "API key authentication is disabled" },
93},
94503,
9899const url = new URL(request.url);
100let apiKey = "";
101102// Check headers
103for (const headerName of apiKeyConfig.headerNames) {
104const headerValue = request.headers.get(headerName);
105if (headerValue) {
106apiKey = headerName === "Authorization" ? headerValue.replace("Bearer ", "") : headerValue;
107break;
108}
110111// Check query parameters if no header found
112if (!apiKey) {
113for (const paramName of apiKeyConfig.queryParamNames) {
114const paramValue = url.searchParams.get(paramName);
115if (paramValue) {
116apiKey = paramValue;
117break;
118}
120}
121122if (!validateApiKey(apiKey)) {
123logSecurityEvent(
124"Authentication Failure",
125{
126method: "API-Key",
127reason: "invalid_or_missing_key",
128endpoint: url.pathname,
129},
130"warn",
131"api-key-validator",
132{
133ip: getClientIP(request),
140error: {
141code: "UNAUTHORIZED",
142message: "Invalid or missing API key",
143},
144response: createResponse(
147error: {
148code: "UNAUTHORIZED",
149message: "Invalid or missing API key",
150},
151},
157// Determine which key was used
158let keyType = "unknown";
159if (apiKey === apiKeyConfig.keys.internal) keyType = "internal";
160else if (apiKey === apiKeyConfig.keys.serviceToService) keyType = "service";
161else if (apiKey === apiKeyConfig.keys.webhook) keyType = "webhook";
162163return {
164success: true,
165context: {
166type: "apiKey",
167user: `api-client-${keyType}`,
168scopes: apiKeyConfig.defaultScopes,
169authType: "apiKey",
170metadata: { keyType },
171},
api_ianmenethil_comauth.jwt.ts17 matches
1/**
2* JWT authentication middleware for Hono-based API server.
3* Provides JWT token creation, verification, and middleware functions.
4*/
31}
3233const jwtApiConfig = AUTH_CONFIG.jwt.API;
3435/**
45return await signJwt(
46restPayload as Record<string, unknown>,
47jwtApiConfig.secretKey,
48jwtApiConfig.algorithm,
49{
50issuer: jwtApiConfig.issuer,
51audience: jwtApiConfig.audience,
52expiresIn: jwtApiConfig.expiresIn,
53subject: payload.sub || payload.id,
54issuedAt: true,
74const payload = await verifyJwt<AppJwtPayload>(
75token,
76customSecret || jwtApiConfig.secretKey,
77{
78issuer: jwtApiConfig.issuer,
79audience: jwtApiConfig.audience,
80algorithms: [jwtApiConfig.algorithm],
81},
82);
110customSecret?: string,
111): Promise<AuthResult> {
112if (!jwtApiConfig.enabled) {
113return {
114success: false,
270return await signJwt(
271refreshPayload as Record<string, unknown>,
272jwtApiConfig.secretKey,
273jwtApiConfig.algorithm,
274{
275issuer: jwtApiConfig.issuer,
276audience: jwtApiConfig.audience,
277expiresIn: jwtApiConfig.refreshExpiresIn,
278subject: payload.sub || payload.id,
279issuedAt: true,
api_ianmenethil_comsqlService.ts15 matches
12interface SqlServiceConfig {
13readonly baseUrl: string;
14readonly apiVersion: string;
15readonly timeout: number;
16readonly retryAttempts: number;
23*/
24const DEFAULT_SQL_CONFIG: SqlServiceConfig = {
25baseUrl: "https://api.val.town",
26apiVersion: "v1",
27timeout: 30000,
28retryAttempts: 3,
6364/**
65* SQLite value types supported by the API.
66*/
67type TursoValue = string | number | boolean | null | Uint8Array;
341342/**
343* Creates HTTP headers for SQL API requests.
344*
345* @param bearerToken - Bearer token for authentication
359360/**
361* Builds URL for SQL API endpoints.
362*
363* @param endpoint - The API endpoint path
364* @returns Complete URL for the API request
365*
366* @example
370*/
371function buildSqlUrl(endpoint: string): string {
372return `${DEFAULT_SQL_CONFIG.baseUrl}/${DEFAULT_SQL_CONFIG.apiVersion}${endpoint}`;
373}
374383* @example
384* ```typescript
385* const response = await makeSqlRequest('https://api.val.town/v1/sqlite/execute', {
386* method: 'POST',
387* headers: createSqlHeaders('token'),
432* @param options - Authentication options
433* @returns Promise resolving to query result
434* @throws {SqlServiceError} On validation or API error
435*
436* @example
494* @param options - Authentication and batch options
495* @returns Promise resolving to array of query results
496* @throws {SqlServiceError} On validation or API error
497*
498* @example
1725// Auto-detect token from environment if not provided
1726const token = config.token || Deno.env.get("VALTOWN_TOKEN") ||
1727Deno.env.get("VALTOWN_API_KEY") || "";
17281729if (!token) {
1730throw new SqlServiceError(
1731"Bearer token is required. Set VALTOWN_TOKEN, VALTOWN_API_KEY environment variable or pass token in config.",
1732SQL_STATUS_CODES.UNAUTHORIZED,
1733);
17641765/**
1766* Execute SQL statement with the exact old API signature for backward compatibility.
1767*
1768* @param statement - SQL statement as string or object
api_ianmenethil_comoauthDBService.ts5 matches
640console.log(`[OAuthDbService] Processing OAuth user: ${provider}:${profile.id}`);
641642// Check if Val.town API key is available
643const apiKey = Deno.env.get("VALTOWN_API_KEY") || Deno.env.get("VALTOWN_TOKEN");
644if (!apiKey) {
645console.error("🚨 [OAuthDbService] VALTOWN_API_KEY not set - cannot process OAuth user");
646console.error(`🚨 [OAuthDbService] Provider: ${provider}, Profile ID: ${profile.id}`);
647throw new Error("Database access unavailable - OAuth requires valid API key");
648}
649