api_ianmenethil_comauthInternal.ts2 matches
5import { internalJwtService } from "@/services/internalJWTService.ts"; // Adjust path if necessary
67export function createInternalAuthMiddleware() {
8const internalJwtConfig = AUTH_CONFIG.jwt.INTERNAL;
9if (!internalJwtConfig.enabled) {
75}
7677export function requireInternalAuth(requiredScope?: string) {
78return async (c: Context<{ Variables: HonoVariables }>, next: Next): Promise<Response | void> => {
79const internalContext = c.get("internalAuth");
api_ianmenethil_comauthentication.ts11 matches
32* Apply authentication based on method
33*/
34async function applyAuthMethod(
35method: AuthMethod,
36c: Context<{ Variables: HonoVariables }>,
94* Multi-method authentication middleware
95*/
96export function createAuthMiddleware(options: AuthMiddlewareOptions = {}) {
97const defaultAuthTypes: AuthMethod[] = [
98AUTH_CONFIG.jwt.API.enabled && "jwt",
234235/**
236* Helper functions
237*/
238export function getAuthContext(c: Context<{ Variables: HonoVariables }>): AuthContext | undefined {
239return c.get("auth");
240}
241242export function isAuthenticated(c: Context<{ Variables: HonoVariables }>): boolean {
243return !!c.get("auth");
244}
245246export function getCurrentUserId(c: Context<{ Variables: HonoVariables }>): string | undefined {
247const auth = c.get("auth");
248return auth?.userId || auth?.user;
249}
250251export function getCurrentUserEmail(c: Context<{ Variables: HonoVariables }>): string | undefined {
252const auth = c.get("auth");
253return auth?.email;
254}
255256export function hasScope(c: Context<{ Variables: HonoVariables }>, scope: string): boolean {
257const auth = c.get("auth");
258return auth?.scopes?.includes(scope) || false;
259}
260261export function hasPermission(
262c: Context<{ Variables: HonoVariables }>,
263permission: string,
267}
268269export function getAuthMethod(c: Context<{ Variables: HonoVariables }>): AuthMethod | undefined {
270const auth = c.get("auth");
271return auth?.type;
273274/**
275* Shorthand functions for specific auth requirements
276*/
277export const requireJWT = createAuthMiddleware({ methods: ["jwt"] });
api_ianmenethil_comauthBasic.ts3 matches
50* Basic Auth authentication logic for the authentication orchestrator
51*/
52export async function applyBasicAuth(
53c: Context<{ Variables: HonoVariables }>,
54): Promise<AuthResult> {
171* Basic Auth authentication middleware for the orchestrator
172*/
173export async function basicAuthMiddleware(
174c: Context<{ Variables: HonoVariables }>,
175next: () => Promise<void>,
413414/**
415* Utility function to hash passwords using bcrypt
416*/
417export const hashPassword = async (password: string, saltRounds = 12): Promise<string> => {
api_ianmenethil_comauthApiKey.ts6 matches
15* Validates API key against configured valid keys
16*/
17export function validateApiKey(apiKey: string): boolean {
18if (!apiKey) return false;
1927* 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}
34* Validates webhook secret for webhook authentication
35*/
36export function validateWebhookSecret(secret: string): boolean {
37return secret === AUTH_CONFIG.methods.API_KEY.keys.webhook;
38}
41* Validates service-to-service API key
42*/
43export function validateServiceKey(serviceKey: string): boolean {
44return serviceKey === AUTH_CONFIG.methods.API_KEY.keys.serviceToService;
45}
48* API Key authentication middleware
49*/
50export async function apiKeyAuthMiddleware(
51c: Context<{ Variables: Variables }>,
52next: () => Promise<void>,
80* API Key authentication logic
81*/
82export function applyApiKeyAuth(request: Request): AuthResult {
83const apiKeyConfig = AUTH_CONFIG.methods.API_KEY;
84
api_ianmenethil_comauth.jwt.ts9 matches
1/**
2* JWT authentication middleware for Hono-based API server.
3* Provides JWT token creation, verification, and middleware functions.
4*/
521* @returns A string representation of the error message
22*/
23function getErrorMessage(error: unknown): string {
24if (error instanceof Error) {
25return error.message;
40* const token = await createJWT({ sub: 'user123', email: 'user@example.com' });
41*/
42export async function createJWT(payload: AppJwtPayload): Promise<string> {
43try {
44const { iat: _iat, exp: _exp, ...restPayload } = payload;
67* @returns Promise resolving to decoded payload or null if invalid
68*/
69export async function verifyAppJWT(
70token: string,
71customSecret?: string,
106* @returns Promise resolving to authentication result
107*/
108export async function applyJwtAuth(
109request: Request,
110customSecret?: string,
199* JWT Bearer token authentication middleware
200*/
201export async function jwtAuthMiddleware(
202c: Context<{ Variables: HonoVariables }>,
203next: Next,
230* JWT-only middleware for endpoints that strictly require JWT authentication
231*/
232export function jwtOnlyMiddleware(customSecret?: string) {
233return async (c: Context<{ Variables: HonoVariables }>, next: Next): Promise<Response | void> => {
234const authResult = await applyJwtAuth(c.req.raw, customSecret);
260* Creates a refresh token with extended expiry
261*/
262export async function createRefreshToken(payload: AppJwtPayload): Promise<string> {
263try {
264const { iat: _iat, exp: _exp, ...restPayload } = payload;
291* @returns Promise resolving to new token pair or null if invalid
292*/
293export async function refreshAccessToken(
294refreshTokenValue: string,
295): Promise<{ accessToken: string; refreshToken: string } | null> {
api_ianmenethil_comsqlService.ts40 matches
290* ```
291*/
292function validateBearerToken(token: string): void {
293if (typeof token !== "string" || token.trim().length === 0) {
294throw new SqlServiceError(
311* ```
312*/
313function validateSqlStatement(statement: SqlStatement): void {
314if (typeof statement === "string") {
315if (statement.trim().length === 0) {
351* ```
352*/
353function createSqlHeaders(bearerToken: string): Record<string, string> {
354return {
355"Authorization": `Bearer ${bearerToken}`,
369* ```
370*/
371function buildSqlUrl(endpoint: string): string {
372return `${DEFAULT_SQL_CONFIG.baseUrl}/${DEFAULT_SQL_CONFIG.apiVersion}${endpoint}`;
373}
390* ```
391*/
392async function makeSqlRequest(url: string, options: RequestInit): Promise<Response> {
393let lastError: Error | null = null;
394423);
424} // ============================================================================
425// CORE SQL EXECUTION FUNCTIONS
426// ============================================================================
427446* ```
447*/
448export async function executeSql(
449statement: SqlStatement,
450options: SqlOperationOptions,
505* ```
506*/
507export async function executeBatchSql(
508statements: SqlStatement[],
509options: BatchSqlOptions,
558}
559} // ============================================================================
560// TABLE MANAGEMENT FUNCTIONS
561// ============================================================================
562583* ```
584*/
585export async function createTable(
586schema: TableSchema,
587options: SqlOperationOptions,
636* ```
637*/
638export async function dropTable(
639tableName: string,
640options: SqlOperationOptions,
661* ```
662*/
663export async function tableExists(
664tableName: string,
665options: SqlOperationOptions,
692* ```
693*/
694export async function listTables(
695options: SqlOperationOptions,
696): Promise<SqlOperationResult<string[]>> {
745* ```
746*/
747export async function insertRecord(
748tableName: string,
749data: Record<string, TursoValue>,
790* ```
791*/
792export async function insertMultipleRecords(
793tableName: string,
794records: Record<string, TursoValue>[],
854* ```
855*/
856export async function selectRecords(
857tableName: string,
858options: SqlOperationOptions,
924* ```
925*/
926export async function findRecordById(
927tableName: string,
928id: TursoValue,
956* ```
957*/
958export async function updateRecords(
959tableName: string,
960data: Record<string, TursoValue>,
1018* ```
1019*/
1020export async function deleteRecords(
1021tableName: string,
1022where: Record<string, TursoValue>,
1071* ```
1072*/
1073export async function deleteRecordById(
1074tableName: string,
1075id: TursoValue,
1079return await deleteRecords(tableName, { [idColumn]: id }, options);
1080} // ============================================================================
1081// INDEX MANAGEMENT FUNCTIONS
1082// ============================================================================
10831099* ```
1100*/
1101export async function createIndex(
1102indexDef: IndexDefinition,
1103tableName: string,
1134* ```
1135*/
1136export async function dropIndex(
1137indexName: string,
1138options: SqlOperationOptions,
1144return await executeSql(sql, options);
1145} // ============================================================================
1146// UTILITY FUNCTIONS
1147// ============================================================================
11481164* ```
1165*/
1166export async function countRecordsWithWhere(
1167tableName: string,
1168options: SqlOperationOptions,
1219* ```
1220*/
1221export async function countRecords(
1222tableName: string,
1223options: SqlOperationOptions,
1285* ```
1286*/
1287export async function executeQuery(
1288sql: string,
1289args: TursoValue[] = [],
1317* ```
1318*/
1319export async function upsertRecord(
1320tableName: string,
1321data: Record<string, TursoValue>,
1356}
1357} // ============================================================================
1358// ORM-STYLE UTILITY FUNCTIONS (From Legacy Version)
1359// ============================================================================
13601375* ```
1376*/
1377export function buildWhereClause(conditions: WhereCondition): {
1378whereClause: string;
1379whereArgs: TursoValue[];
1433* ```
1434*/
1435export function mapRowToObject(row: TursoRow, columns: string[]): Record<string, TursoValue> {
1436const obj: Record<string, TursoValue> = {};
1437for (let i = 0; i < columns.length; i++) {
1458* ```
1459*/
1460export async function selectWithMapping(
1461tableName: string,
1462options: SqlOperationOptions,
1541* ```
1542*/
1543export async function findOne(
1544tableName: string,
1545where: WhereCondition,
1581* ```
1582*/
1583export async function findMany(
1584tableName: string,
1585options: SqlOperationOptions,
1612* ```
1613*/
1614export async function recordExists(
1615tableName: string,
1616where: WhereCondition,
1647* ```
1648*/
1649export async function getTableInfo(
1650tableName: string,
1651options: SqlOperationOptions,
1675* ```
1676*/
1677export async function executeTransaction(
1678operations: SqlStatement[],
1679options: SqlOperationOptions,
2144export { ValTownSqlService as SqlService };
21452146// Export all functions (already exported individually above)
2147// This section serves as a convenient index of all available functions
21482149/**
2150* Available SQL service functions:
2151*
2152* ## Core Execution
api_ianmenethil_comoauthDBService.ts3 matches
112updated_at?: number;
113} // ============================================================================
114// HELPER FUNCTIONS
115// ============================================================================
116118* Convert database user to SQL-compatible format.
119*/
120function userToSqlRecord(user: DatabaseUser): Record<string, string | number | null> {
121return {
122id: user.id,
135* Convert OAuth account to SQL-compatible format.
136*/
137function oauthAccountToSqlRecord(
138account: DatabaseOAuthAccount,
139): Record<string, string | number | null> {
api_ianmenethil_comemailService.ts11 matches
191192// ============================================================================
193// UTILITY FUNCTIONS
194// ============================================================================
195198* @returns ISO date string in Sydney timezone
199*/
200function getCurrentDateInSydney(): string {
201return new Date().toLocaleString("en-AU", {
202timeZone: "Australia/Sydney",
214* @returns Basic configuration object
215*/
216function getConfig<T>(): T {
217return {} as T;
218} // ============================================================================
219// HTTP UTILITY FUNCTIONS
220// ============================================================================
221225* @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"";
242* @returns Complete URL string
243*/
244function buildUrl(endpoint: string, baseUrl?: string): string {
245const base = baseUrl || DEFAULT_EMAIL_CONFIG.baseUrl;
246const cleanEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;
254* @returns Promise resolving to Response
255*/
256async function makeRequest(url: string, options: RequestInit): Promise<Response> {
257const controller = new AbortController();
258const timeoutId = setTimeout(() => controller.abort(), DEFAULT_EMAIL_CONFIG.timeout);
274}
275} // ============================================================================
276// CORE EMAIL FUNCTIONS
277// ============================================================================
278294* ```
295*/
296export async function sendEmail(
297options: EmailOptions,
298): Promise<EmailOperationResult<{ message: string }>> {
366*/
367368export function sendSimpleEmail(
369to: string[],
370subject: string,
1051// ============================================================================
10521053// Export all types and functions
1054export type {
1055EmailAttachment,
api_ianmenethil_comblobService.ts19 matches
141* ```
142*/
143function validateBlobKey(key: string): void {
144if (typeof key !== "string") {
145throw new BlobServiceError("Blob key must be a string", STATUS_CODES.BAD_REQUEST);
172*/
173174function validateBearerToken(token: string): void {
175if (typeof token !== "string" || token.trim().length === 0) {
176throw new BlobServiceError(
197* ```
198*/
199function createHeaders(bearerToken?: string, contentType?: string): Record<string, string> {
200const headers: Record<string, string> = {};
201225* ```
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}`;
264*/
265266async function makeRequest(url: string, options: RequestInit): Promise<Response> {
267let lastError: Error | null = null;
268299300// ============================================================================
301// CORE BLOB SERVICE FUNCTIONS
302// ============================================================================
303318* ```
319*/
320export async function listBlobs(
321options: ListBlobsOptions = {},
322): Promise<BlobOperationResult<BlobListingItem[]>> {
371*/
372373export async function downloadBlob(key: string): Promise<BlobOperationResult<ArrayBuffer>> {
374try {
375validateBlobKey(key);
422* ```
423*/
424export async function downloadBlobAsText(
425key: string,
426encoding: string = "utf-8",
475*/
476477export async function storeBlob(
478key: string,
479data: ArrayBuffer | Uint8Array | string,
543* ```
544*/
545export async function storeBlobAsJson(
546key: string,
547data: unknown,
582*/
583584export async function deleteBlob(
585key: string,
586options: AuthenticatedBlobOptions,
622623// ============================================================================
624// UTILITY FUNCTIONS
625// ============================================================================
626639* ```
640*/
641export async function blobExists(key: string): Promise<boolean> {
642try {
643validateBlobKey(key);
668*/
669670export async function getBlobMetadata(key: string): Promise<BlobListingItem | null> {
671try {
672const result = await listBlobs();
695* ```
696*/
697export async function downloadBlobAsJson<T = unknown>(
698key: string,
699): Promise<BlobOperationResult<T>> {
740* ```
741*/
742export async function copyBlob(
743sourceKey: string,
744destinationKey: string,
788*/
789790export async function bulkDeleteBlobsByPrefix(
791prefix: string,
792options: AuthenticatedBlobOptions,
1188}
11891190// Export all types and functions
1191export type {
1192AuthenticatedBlobOptions,
api_ianmenethil_comwebhookService.ts7 matches
23* @returns Sanitized string
24*/
25function sanitizeInput(input: string): string {
26return input.replace(/[<>\"'&]/g, "").trim();
27}
33* @returns Parsed timestamp filter object
34*/
35function parseTimestampFilters(from?: string, to?: string): { from?: Date; to?: Date } {
36const result: { from?: Date; to?: Date } = {};
3758* @returns Headers as key-value object
59*/
60function extractHeaders(request: Request): Record<string, string> {
61const headers: Record<string, string> = {};
62request.headers.forEach((value, key) => {
71* @returns Response with webhook creation result
72*/
73export async function createWebhook(c: Context<{ Variables: Variables }>): Promise<Response> {
74const requestId = crypto.randomUUID();
75159* @returns Response with webhook records list
160*/
161export async function listWebhooks(c: Context<{ Variables: Variables }>): Promise<Response> {
162const requestId = crypto.randomUUID();
163249* @returns Response with webhook record details
250*/
251export async function getWebhook(c: Context<{ Variables: Variables }>): Promise<Response> {
252const requestId = crypto.randomUUID();
253316* @returns Response with deletion confirmation
317*/
318export async function deleteWebhook(c: Context<{ Variables: Variables }>): Promise<Response> {
319const requestId = crypto.randomUUID();
320