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
api_ianmenethil_comemailService.ts24 matches
14interface EmailServiceConfig {
15readonly baseUrl: string;
16readonly apiVersion: string;
17readonly timeout: number;
18readonly retryAttempts: number;
24*/
25const DEFAULT_EMAIL_CONFIG: EmailServiceConfig = {
26baseUrl: "https://api.val.town",
27apiVersion: "v1",
28timeout: 30000,
29retryAttempts: 3,
221222/**
223* Create headers for Val Town API requests.
224* @param bearerToken Optional bearer token (uses env if not provided)
225* @returns Headers object
226*/
227function createHeaders(bearerToken?: string): Record<string, string> {
228const token = bearerToken || Deno.env.get("VALTOWN_TOKEN") || Deno.env.get("VALTOWN_API_KEY") ||
229"";
230237238/**
239* Build URL for Val Town API endpoints.
240* @param endpoint API endpoint path
241* @param baseUrl Optional base URL override
242* @returns Complete URL string
249250/**
251* Make HTTP request to Val Town API.
252* @param url Request URL
253* @param options Request options
278279/**
280* Send email using Val Town API.
281*
282* @param options Email options including recipients, content, and authentication
300const url = buildUrl("/email");
301302// Prepare request body according to Val.town API spec
303const requestBody: Record<string, unknown> = {
304subject: options.subject,
428return {
429bearerToken: this.config.token || Deno.env.get("VALTOWN_TOKEN") ||
430Deno.env.get("VALTOWN_API_KEY") || "",
431};
432} /**
571}
572573const subject = "๐ API Changes Detected";
574const htmlContent = this.generateChangeDetectionEmailHtml(data);
575const textContent = this.generateChangeDetectionEmailText(data);
716analysis
717? `
718<h3>๐ API Analysis</h3>
719<table>
720<tr><th>API Title</th><td>${analysis.title}</td></tr>
721<tr><th>Version</th><td>${analysis.version}</td></tr>
722<tr><th>Total Paths</th><td>${analysis.pathCount}</td></tr>
735<li><a href="${
736data.swaggerData?.spec?.servers?.[0]?.url || "#"
737}">API Documentation</a></li>
738</ul>
739</div>
811<h3>๐ง Recommended Actions</h3>
812<ul>
813<li>Check the Swagger API endpoint availability</li>
814<li>Verify Postman API credentials</li>
815<li>Review network connectivity</li>
816<li>Check system logs for detailed error information</li>
851RECOMMENDED ACTIONS
852-------------------
853- Check the Swagger API endpoint availability
854- Verify Postman API credentials
855- Review network connectivity
856- Check system logs for detailed error information
875<head>
876<meta charset="utf-8">
877<title>API Changes Detected</title>
878<style>
879body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
891<div class="container">
892<div class="header">
893<h1>๐ API Changes Detected</h1>
894<p>Swagger-Postman Integration</p>
895</div>
974975let content = `
976API CHANGES DETECTED
977====================
97810401041return {
1042title: info.title || "Unknown API",
1043version: info.version || "unknown",
1044pathCount: Object.keys(paths).length,
1082* await vtEmailService.sendWorkflowSuccessNotification({
1083* changesDetected: true,
1084* swaggerData: { spec: openApiSpec },
1085* updateResult: { itemsUpdated: 5, collectionId: 'abc123' },
1086* recipients: ['admin@example.com']
api_ianmenethil_comblobService.ts26 matches
1/**
2* vt.blob.service.ts โ Val Town blob storage service with complete API integration.
3*/
412interface BlobServiceConfig {
13readonly baseUrl: string;
14readonly apiVersion: string;
15readonly maxKeyLength: number;
16readonly minKeyLength: number;
24*/
25const DEFAULT_BLOB_CONFIG: BlobServiceConfig = {
26baseUrl: "https://api.val.town",
27apiVersion: "v1",
28maxKeyLength: 512,
29minKeyLength: 1,
5859/**
60* Blob listing item returned from the API.
61*/
62interface BlobListingItem {
102103/**
104* Backward compatibility type aliases for the old BlobService API.
105*/
106type BlobConfig = BlobServiceConfig;
130131/**
132* Validates a blob key according to Val Town API constraints.
133*
134* @param key - The blob key to validate
186187/**
188* Creates HTTP headers for blob API requests.
189*
190* @param bearerToken - Optional bearer token for authentication
212213/**
214* Builds URL for blob API endpoints.
215*
216* @param endpoint - The API endpoint path
217* @param key - Optional blob key for specific operations
218* @param queryParams - Optional query parameters
219* @returns Complete URL for the API request
220*
221* @example
226*/
227function buildUrl(endpoint: string, key?: string, queryParams?: Record<string, string>): string {
228const baseUrl = `${DEFAULT_BLOB_CONFIG.baseUrl}/${DEFAULT_BLOB_CONFIG.apiVersion}`;
229let url = `${baseUrl}${endpoint}`;
230257* @example
258* ```typescript
259* const response = await makeRequest('https://api.val.town/v1/blob', {
260* method: 'GET',
261* headers: createHeaders()
307* @param options - Optional filtering options
308* @returns Promise resolving to array of blob listing items
309* @throws {BlobServiceError} On API error
310*
311* @example
362* @param key - The unique blob key
363* @returns Promise resolving to blob binary data as ArrayBuffer
364* @throws {BlobServiceError} On validation or API error
365*
366* @example
414* @param encoding - Text encoding (default: 'utf-8')
415* @returns Promise resolving to blob content as string
416* @throws {BlobServiceError} On validation or API error
417*
418* @example
460* @param options - Authentication and storage options
461* @returns Promise resolving to operation result
462* @throws {BlobServiceError} On validation or API error
463*
464* @example
465* ```typescript
466* const result = await storeBlob('files/document.pdf', pdfBuffer, {
467* bearerToken: 'your-api-token'
468* });
469*
470* const textResult = await storeBlob('notes/memo.txt', 'Hello World', {
471* bearerToken: 'your-api-token',
472* contentType: 'text/plain'
473* });
533* @param options - Authentication options
534* @returns Promise resolving to operation result
535* @throws {BlobServiceError} On validation or API error
536*
537* @example
539* const userData = { name: 'John', age: 30 };
540* const result = await storeBlobAsJson('users/john.json', userData, {
541* bearerToken: 'your-api-token'
542* });
543* ```
568* @param options - Authentication options
569* @returns Promise resolving to operation result
570* @throws {BlobServiceError} On validation or API error
571*
572* @example
573* ```typescript
574* const result = await deleteBlob('temp/old-file.txt', {
575* bearerToken: 'your-api-token'
576* });
577*
687* @param key - The unique blob key
688* @returns Promise resolving to parsed JSON data
689* @throws {BlobServiceError} On validation, API, or JSON parsing error
690*
691* @example
736* ```typescript
737* const result = await copyBlob('temp/draft.txt', 'documents/final.txt', {
738* bearerToken: 'your-api-token'
739* });
740* ```
777* // Delete all temporary files
778* const results = await bulkDeleteBlobsByPrefix('temp/', {
779* bearerToken: 'your-api-token'
780* });
781*
1/**
2* webhookService.ts โ Webhook endpoint handlers for managing webhook records with CRUD operations.
3* Provides RESTful API for creating, listing, viewing, and deleting webhook entries.
4*/
5
api_ianmenethil_comtavilyApiService.ts26 matches
10TavilyExtractInput,
11TavilyExtractSchema,
12TavilyMapInput,
13TavilyMapInputSchema,
14TavilySearchInput,
15TavilySearchSchema,
16} from "@/external-apis/tavilyClient.ts";
1718function getLocalErrorMessage(error: unknown): string {
28* tavilySearch operation handler
29* POST /v1/tavily/search
30* Handles requests to the Tavily search API.
31*/
32export async function tavilySearchHandler(c: Context<{ Variables: Variables }>): Promise<Response> {
54console.error("[tavilySearchHandler] Error during Tavily search:", error);
5556if (message.includes("Configuration error: invalid or missing TAVILY_API_KEY")) {
57return c.json({
58success: false,
59error: "Tavily API configuration error. Please contact support.",
60}, 503);
61}
70return c.json({
71success: false,
72error: "Tavily API returned an error during search.",
73details: errorDetail,
74}, 502);
76return c.json({
77success: false,
78error: `Tavily API error during search. Parse Error: ${
79parseError instanceof Error ? parseError.message : "Unknown error"
80}`,
93* tavilyExtract operation handler
94* POST /v1/tavily/extract
95* Handles requests to the Tavily extract API.
96*/
97export async function tavilyExtractHandler(
121console.error("[tavilyExtractHandler] Error during Tavily extract:", error);
122123if (message.includes("Configuration error: invalid or missing TAVILY_API_KEY")) {
124return c.json({
125success: false,
126error: "Tavily API configuration error. Please contact support.",
127}, 503);
128}
137return c.json({
138success: false,
139error: "Tavily API returned an error during extract.",
140details: errorDetail,
141}, 502);
143return c.json({
144success: false,
145error: `Tavily API error during extract. Parse Error: ${
146parseError instanceof Error ? parseError.message : "Unknown error"
147}`,
160* tavilyCrawl operation handler (BETA)
161* POST /v1/tavily/crawl
162* Handles requests to the Tavily crawl API.
163*/
164export async function tavilyCrawlHandler(c: Context<{ Variables: Variables }>): Promise<Response> {
186console.error("[tavilyCrawlHandler] Error during Tavily crawl:", error);
187188if (message.includes("Configuration error: invalid or missing TAVILY_API_KEY")) {
189return c.json({
190success: false,
191error: "Tavily API configuration error. Please contact support.",
192}, 503);
193}
204return c.json({
205success: false,
206error: "Tavily API returned an error during crawl.",
207details: errorDetail,
208}, 502);
210return c.json({
211success: false,
212error: `Tavily API error during crawl. Parse Error: ${
213parseError instanceof Error ? parseError.message : "Unknown error"
214}`,
227* tavilyMap operation handler (BETA)
228* POST /v1/tavily/map
229* Handles requests to the Tavily map API.
230*/
231export async function tavilyMapHandler(c: Context<{ Variables: Variables }>): Promise<Response> {
232try {
233const requestBody = await c.req.json();
234const validationResult = TavilyMapInputSchema.safeParse(requestBody);
235236if (!validationResult.success) {
244245// Use the validated data with explicit type
246const mapInput: TavilyMapInput = validationResult.data;
247const tavilyResponse = await performTavilyMap(mapInput);
248249// Type assertion to ensure it's a valid JSON value
253console.error("[tavilyMapHandler] Error during Tavily map:", error);
254255if (message.includes("Configuration error: invalid or missing TAVILY_API_KEY")) {
256return c.json({
257success: false,
258error: "Tavily API configuration error. Please contact support.",
259}, 503);
260}
269return c.json({
270success: false,
271error: "Tavily API returned an error during map.",
272details: errorDetail,
273}, 502);
275return c.json({
276success: false,
277error: `Tavily API error during map. Parse Error: ${
278parseError instanceof Error ? parseError.message : "Unknown error"
279}`,
api_ianmenethil_comswaggerService.ts9 matches
5/**
6* Service for generating Swagger UI HTML documentation
7* Handles the generation of interactive Swagger UI that consumes OpenAPI specifications
8*/
9export class SwaggerUIService {
10/**
11* Generate Swagger UI HTML page
12* Creates a complete HTML page with Swagger UI embedded that fetches the OpenAPI spec
13*
14* @param specUrl - URL to the OpenAPI JSON specification
15* @returns HTML string for Swagger UI documentation page
16*/
17generateSwaggerHTML(specUrl: string = "/v1/openapi.json"): string {
18return `<!DOCTYPE html>
19<html>
20<head>
21<title>API Documentation</title>
22<link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css" />
23</head>
29url: '${specUrl}',
30dom_id: '#swagger-ui',
31presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.presets.standalone]
32});
33</script>
53/**
54* Validate that the spec URL is accessible
55* Basic validation to ensure the OpenAPI spec URL is valid
56*
57* @param specUrl - URL to validate
65return {
66valid: false,
67error: "Invalid OpenAPI specification URL",
68};
69}
104export function getSwaggerUI(c: Context<{ Variables: Variables }>): Response {
105try {
106const html = swaggerUIService.generateSwaggerHTML("/v1/openapi.json");
107return c.html(html);
108} catch (error) {
api_ianmenethil_comredoclyService.ts9 matches
5/**
6* Service for generating Redoc HTML documentation
7* Handles the generation of Redoc interface that consumes OpenAPI specifications
8*/
9export class RedoclyService {
10/**
11* Generate Redoc HTML page
12* Creates a complete HTML page with Redoc embedded that fetches the OpenAPI spec
13*
14* @param specUrl - URL to the OpenAPI JSON specification
15* @returns HTML string for Redoc documentation page
16*/
17generateRedocHTML(specUrl: string = "/v1/openapi.json"): string {
18return `<!DOCTYPE html>
19<html>
20<head>
21<title>API Documentation - Redoc</title>
22<meta charset="utf-8"/>
23<meta name="viewport" content="width=device-width, initial-scale=1">
24<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
25<style>body{margin:0;padding:0;}</style>
26</head>
49/**
50* Validate that the spec URL is accessible
51* Basic validation to ensure the OpenAPI spec URL is valid
52*
53* @param specUrl - URL to validate
61return {
62valid: false,
63error: "Invalid OpenAPI specification URL",
64};
65}
77export function getRedoc(c: Context<{ Variables: Variables }>): Response {
78try {
79const html = redoclyService.generateRedocHTML("/v1/openapi.json");
80return c.html(html);
81} catch (error) {
1// F:\zApps\valtown.servers\APIServer\src\handlers\proxy.service.ts
2import { getCurrentDateInSydney } from "@/utils/dateUtils.ts";
3import { Context } from "hono";