2* Import Web SDK
3*/
4async function loadKlarnaSdk() {
5const { KlarnaSDK } = await import("https://js.klarna.com/web-sdk/v2/klarna.mjs");
6
25* Create payment intent with acquirer
26*/
27app.get("/order", async function(c) {
28const { amount, currency, interoperabilityToken, returnUrl } = c.req.query();
29const resp = await fetch(
35});
3637app.get("/paymentRequest", async function(c) {
38const { amount, currency, returnUrl } = c.req.query();
39const apiKey = process.env.API_KEY;
log-beelinemain.tsx1 match
5import { sqlite } from "https://esm.town/v/std/sqlite"; // Val Townβs built-in client [oai_citation:0β‘docs.val.town](https://docs.val.town/std/sqlite/usage/?utm_source=chatgpt.com)
67export default async function handler(req: Request): Promise<Response> {
8const { pathname } = new URL(req.url);
9
ChatuseAnthropicStream.tsx6 matches
2425/** merge delta (unchanged) */
26function mergeDelta(block: any, delta: any) {
27if (!delta) return;
28switch (delta.type) {
4041/** build request body helpers */
42async function buildBody(config: AppConfig, history: Message[], userText: string, clientPool: MCPClientPool) {
43const mcp = config.mcpServers
44.filter((s) => s.enabled && s.url)
7071/** final assembly */
72function assembleMessage(blocks: Record<number, any>): AssistantMsg {
73Object.values(blocks).forEach((b) => {
74if (b._input_json_str !== undefined) {
9495/** Execute a tool call */
96async function executeToolCall(
97toolName: string,
98input: any,
111/* ββββββββββββββββββββββββββββ useAnthropicStream βββββββββββββββββββββββββββ */
112113export default function useAnthropicStream(
114config: AppConfig,
115clientPool: MCPClientPool,
262);
263264/* Main send/stream function with tool use loop */
265const send = React.useCallback(
266async (history: Message[], userText: string): Promise<Message[]> => {
41* Initializes the entire SafeHash V2 application.
42*/
43async function initializeApplication(): Promise<void> {
44try {
45logInfo('π Starting SafeHash V2 initialization...', 'app_init_start');
93* Starts the HTTP server.
94*/
95function startServer():
96| void
97| ((
149* Gracefully shuts down the application.
150*/
151async function shutdownApplication(signal?: string): Promise<void> {
152if (appState.isShuttingDown) {
153logWarn('Shutdown already in progress', 'shutdown_already_in_progress');
194* Performs cleanup tasks during shutdown.
195*/
196async function cleanupOnShutdown(): Promise<void> {
197try {
198// Export any remaining tracing spans
228* Only uses signals supported by the current OS.
229*/
230function setupSignalHandlers(): void {
231if (typeof Deno !== 'undefined') {
232const isWindows = Deno.build?.os === 'windows';
268* Main application entry point.
269*/
270async function main(): Promise<
271| ((request: Request, env?: Record<string, unknown>, executionCtx?: ExecutionContext) => Response | Promise<Response>)
272| void
286287// For Val Town deployment, return the fetch handler
288if (fetchHandler && typeof fetchHandler === 'function') {
289return fetchHandler;
290}
ZenServervalidation.ts19 matches
186* Throws error for invalid input types to ensure type safety.
187*/
188export function sanitizeSQL(str: string): string {
189if (typeof str !== 'string') {
190throw new Error('sanitizeSQL expects a string input');
212* Validates nonce format using the pattern from constants.
213*/
214export function isValidNonceFormat(nonce: string): boolean {
215try {
216NonceSchema.parse(nonce);
224* Validates booking ID format using the pattern from constants.
225*/
226export function isValidBookingId(id: string): boolean {
227try {
228BookingIdSchema.parse(id);
236* Validates payment timestamp format.
237*/
238export function isValidPaymentTimestamp(timestamp: string): boolean {
239try {
240PaymentTimestampSchema.parse(timestamp);
248* Validates timestamp for replay attack prevention.
249*/
250export function isRequestTimestampValid(
251timestamp: string | undefined,
252toleranceMs: number = 5 * 60 * 1000, // 5 minutes
273* Validates payment mode value.
274*/
275export function isValidPaymentMode(mode: any): mode is PaymentMode {
276try {
277PaymentModeSchema.parse(mode);
285* Validates payment amount (no decimals, positive integer).
286*/
287export function isValidPaymentAmount(amount: any): boolean {
288try {
289PaymentAmountSchema.parse(amount);
297* Validates that payment amount string doesn't contain decimals.
298*/
299export function hasNoDecimals(amountString: string): boolean {
300return !/[.,]/.test(amountString);
301}
308* Validates email_verify field for honeypot detection.
309*/
310export function isHoneypotTriggered(emailVerify: string | undefined): boolean {
311// Honeypot is triggered if the field is filled (it should be empty)
312return !!(emailVerify && emailVerify.trim().length > 0);
316* Validates origin header against allowed origins.
317*/
318export function isValidOrigin(origin: string | null, allowedOrigins: string[]): boolean {
319if (!origin) return false;
320return allowedOrigins.includes(origin);
324* Validates referer header against origin.
325*/
326export function isValidReferer(referer: string | null, origin: string | null): boolean {
327if (!referer || !origin) return false;
328try {
336* Validates host header against expected host.
337*/
338export function isValidHost(host: string | null, expectedHost: string): boolean {
339if (!host) return false;
340return host === expectedHost;
344* Validates IP address format and extracts from headers.
345*/
346export function extractAndValidateIP(headers: Headers): string {
347// Check for Cloudflare headers first
348const cfConnectingIP = headers.get('cf-connecting-ip');
388* Formats Zod validation errors into user-friendly messages.
389*/
390export function formatValidationErrors(error: z.ZodError): string[] {
391return error.errors.map((err) => {
392const path = err.path.length > 0 ? `${err.path.join('.')}: ` : '';
398* Validates request data and returns formatted errors if validation fails.
399*/
400export function validateRequestData<T>(
401schema: z.ZodSchema<T>,
402data: unknown,
416* Validates required fields are present in request.
417*/
418export function checkRequiredFields<T extends Record<string, any>>(
419data: T,
420requiredFields: string[],
446* Creates a custom Zod schema for conditional validation.
447*/
448export function conditionalValidation<T>(
449condition: (data: any) => boolean,
450schema: z.ZodSchema<T>,
466* Creates a Zod schema for array validation with size limits.
467*/
468export function createArraySchema<T>(
469itemSchema: z.ZodSchema<T>,
470minItems: number = 0,
487BookingIdSchema,
488489// Validation functions
490isValidNonceFormat,
491isValidBookingId,
ZenServertracing.ts30 matches
21* Initializes the tracing system.
22*/
23export function initializeTracing(): void {
24const config = getConfig();
25tracingConfig = config.tracing || null;
39* Checks if tracing is enabled and should sample this request.
40*/
41function shouldTrace(): boolean {
42if (!isTracingEnabled || !tracingConfig) {
43return false;
55* Generates a unique span ID.
56*/
57function generateSpanId(): string {
58const bytes = crypto.getRandomValues(new Uint8Array(8));
59return Array.from(bytes)
65* Generates a unique trace ID.
66*/
67function generateTraceId(): string {
68const bytes = crypto.getRandomValues(new Uint8Array(16));
69return Array.from(bytes)
75* Creates a new trace span.
76*/
77export function createSpan(
78operationName: string,
79parentSpan?: TraceSpan,
124* Finishes a trace span.
125*/
126export function finishSpan(span: TraceSpan | null, tags: Record<string, any> = {}): void {
127if (!span || !isTracingEnabled) {
128return;
171* Adds a log entry to a span.
172*/
173export function addSpanLog(
174span: TraceSpan | null,
175level: string,
194* Adds tags to a span.
195*/
196export function addSpanTags(span: TraceSpan | null, tags: Record<string, any>): void {
197if (!span || !isTracingEnabled) {
198return;
205* Sets an error tag on a span.
206*/
207export function setSpanError(span: TraceSpan | null, error: Error): void {
208if (!span || !isTracingEnabled) {
209return;
222223// ========================================
224// High-Level Tracing Functions
225// ========================================
226228* Traces an HTTP request.
229*/
230export function traceHttpRequest(
231method: string,
232path: string,
246* Traces an HTTP response.
247*/
248export function traceHttpResponse(
249span: TraceSpan | null,
250status: number,
269* Traces a database operation.
270*/
271export function traceDatabaseOperation(
272operation: string,
273table: string,
284* Traces a security check.
285*/
286export function traceSecurityCheck(
287checkType: string,
288parentSpan?: TraceSpan,
296* Traces a crypto operation.
297*/
298export function traceCryptoOperation(
299operation: string,
300algorithm: string,
310* Traces a business logic operation.
311*/
312export function traceBusinessOperation(
313operation: string,
314parentSpan?: TraceSpan,
322323// ========================================
324// Async Function Tracing
325// ========================================
326327/**
328* Wraps an async function with tracing.
329*/
330export function withTracing<T extends any[], R>(
331operationName: string,
332fn: (...args: T) => Promise<R>,
352353/**
354* Executes a function with a new span context.
355*/
356export async function inSpan<T>(
357operationName: string,
358fn: (span: TraceSpan | null) => Promise<T> | T,
384* Sets the root span for a request context.
385*/
386export function setRequestSpan(correlationId: string, span: TraceSpan | null): void {
387if (span) {
388requestContexts.set(correlationId, span);
395* Gets the root span for a request context.
396*/
397export function getRequestSpan(correlationId: string): TraceSpan | null {
398return requestContexts.get(correlationId) || null;
399}
402* Clears the request context.
403*/
404export function clearRequestContext(correlationId: string): void {
405const span = requestContexts.get(correlationId);
406if (span) {
417* Exports a span to the configured tracing endpoint.
418*/
419async function exportSpan(span: TraceSpan): Promise<void> {
420if (!tracingConfig?.endpoint) {
421return;
462* Exports all active spans (useful for shutdown).
463*/
464export async function exportAllSpans(): Promise<void> {
465if (!tracingConfig?.endpoint || activeSpans.size === 0) {
466return;
492* Gets tracing statistics.
493*/
494export function getTracingStats(): {
495enabled: boolean;
496activeSpans: number;
511* Gets the current root span.
512*/
513export function getRootSpan(): TraceSpan | null {
514return rootSpan;
515}
518* Gets all active spans.
519*/
520export function getActiveSpans(): TraceSpan[] {
521return Array.from(activeSpans.values());
522}
529* Cleans up expired spans (older than 1 hour).
530*/
531export function cleanupExpiredSpans(): void {
532const oneHourAgo = performance.now() - (60 * 60 * 1000);
533const expiredSpanIds: string[] = [];
ZenServerlogging.ts31 matches
19* Initializes the logging system with configuration.
20*/
21export async function initializeLogging(): Promise<void> {
22if (isInitialized) {
23return;
68* Generates a new correlation ID for request tracking.
69*/
70export function generateCorrelationId(): string {
71return crypto.randomUUID();
72}
75* Sets the correlation ID for the current context.
76*/
77export function setCorrelationId(correlationId: string): void {
78currentCorrelationId = correlationId;
79}
82* Gets the current correlation ID.
83*/
84export function getCorrelationId(): string | null {
85return currentCorrelationId;
86}
89* Clears the current correlation ID.
90*/
91export function clearCorrelationId(): void {
92currentCorrelationId = null;
93}
9495/**
96* Executes a function with a specific correlation ID context.
97*/
98export async function withCorrelationId<T>(
99correlationId: string,
100fn: () => Promise<T> | T,
170* Formats log entry as JSON.
171*/
172function formatAsJSON(logRecord: LogRecord): string {
173const config = getConfig('logging');
174196* Formats log entry as human-readable text.
197*/
198function formatAsText(logRecord: LogRecord): string {
199const config = getConfig('logging');
200const timestamp = new Date().toISOString();
221222// ========================================
223// Core Logging Functions
224// ========================================
225227* Creates a structured log entry.
228*/
229function createLogEntry(
230level: LogLevel,
231message: string,
277* Logs debug information.
278*/
279export function logDebug(
280message: string,
281operation?: string,
288* Logs general information.
289*/
290export function logInfo(
291message: string,
292operation?: string,
299* Logs warning messages.
300*/
301export function logWarn(
302message: string,
303operation?: string,
310* Logs error messages.
311*/
312export function logError(
313message: string,
314error?: Error,
320321// ========================================
322// Specialized Logging Functions
323// ========================================
324326* Logs HTTP request information.
327*/
328export function logHttpRequest(
329method: string,
330path: string,
347* Logs HTTP response information.
348*/
349export function logHttpResponse(
350method: string,
351path: string,
372* Logs security events.
373*/
374export function logSecurityEvent(event: SecurityEvent): void {
375const level = event.severity === 'critical' || event.severity === 'high' ? 'ERROR' : 'WARN';
376392* Logs performance events.
393*/
394export function logPerformanceEvent(event: PerformanceEvent): void {
395const level = event.success ? 'DEBUG' : 'WARN';
396411* Logs database operations.
412*/
413export function logDatabaseOperation(
414operation: string,
415table: string,
437* Logs nonce operations.
438*/
439export function logNonceOperation(
440operation: 'generate' | 'validate' | 'expire' | 'reuse',
441nonce: string,
466* Logs authentication events.
467*/
468export function logAuthEvent(
469type: 'success' | 'failure' | 'generate' | 'validate' | 'exchange' | 'refresh' | 'internal',
470method: string,
491* Logs crypto operations.
492*/
493export function logCryptoOperation(
494operation: 'hash' | 'sign' | 'verify' | 'random',
495algorithm: string,
523* Measures and logs the duration of an operation.
524*/
525export async function measureAndLog<T>(
526operation: string,
527fn: () => Promise<T> | T,
563* Creates a performance timer for manual measurement.
564*/
565export function createTimer(operation: string) {
566const startTime = performance.now();
567586* Creates request logging data for middleware.
587*/
588export function createRequestLog(request: Request): {
589correlationId: string;
590startTime: number;
610* Logs request completion.
611*/
612export function logRequestCompletion(
613logData: Record<string, any>,
614response: Response,
632* Logs application startup.
633*/
634export function logStartup(version: string, environment: string): void {
635logInfo(
636`SafeHash API v${version} starting in ${environment} mode`,
643* Logs application shutdown.
644*/
645export function logShutdown(reason: string): void {
646logInfo(
647`SafeHash API shutting down: ${reason}`,
654* Logs health check results.
655*/
656export function logHealthCheck(
657service: string,
658healthy: boolean,
42/**
43* Generates HMAC signature for server responses using proper HMAC construction.
44* Uses SHA3-256 as the underlying hash function.
45*/
46generateHMAC(data: any, timestamp: string): string {
112* Generates a secure nonce (32 hex characters).
113*/
114export function generateNonce(): string {
115const bytes = crypto.getRandomValues(new Uint8Array(16));
116return Array.from(bytes)
122* Generates a secure random UUID v4.
123*/
124export function generateUUID(): string {
125return crypto.randomUUID();
126}
129* Generates a secure random string of specified length using given character set.
130*/
131export function generateRandomString(
132length: number,
133charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
147* Uses Deno's built-in crypto API for PBKDF2.
148*/
149export async function hashPassword(password: string, salt?: string): Promise<{
150hash: string;
151salt: string;
189* Verifies a password against a hash.
190*/
191export async function verifyPassword(
192password: string,
193hash: string,
216* Creates a SHA-256 hash of data using Deno's built-in crypto.
217*/
218export async function sha256(data: string): Promise<string> {
219const encoder = new TextEncoder();
220const dataBuffer = encoder.encode(data);
230* Creates a SHA-512 hash of data using Deno's built-in crypto.
231*/
232export async function sha512(data: string): Promise<string> {
233const encoder = new TextEncoder();
234const dataBuffer = encoder.encode(data);
244* Generates cryptographically secure random bytes.
245*/
246export function getRandomBytes(length: number): Uint8Array {
247if (length <= 0 || !Number.isInteger(length)) {
248throw new Error('Length must be a positive integer');
255* Generates a secure timestamp-based token.
256*/
257export function generateTimestampToken(): string {
258const timestamp = Date.now().toString();
259const randomBytes = getRandomBytes(8);
268* Validates a timestamp token and extracts the timestamp.
269*/
270export function validateTimestampToken(
271token: string,
272maxAgeMs: number = 15 * 60 * 1000,
299* Creates an encrypted token using AES-GCM.
300*/
301export async function encryptToken(
302data: string,
303key: CryptoKey,
330* Decrypts a token using AES-GCM.
331*/
332export async function decryptToken(
333encrypted: string,
334iv: string,
360* Generates an AES-GCM key for encryption/decryption.
361*/
362export async function generateEncryptionKey(): Promise<CryptoKey> {
363return await crypto.subtle.generateKey(
364{
374* Imports an encryption key from raw bytes.
375*/
376export async function importEncryptionKey(keyBytes: Uint8Array): Promise<CryptoKey> {
377return await crypto.subtle.importKey(
378'raw',
388389// ========================================
390// Factory Function
391// ========================================
392394* Creates a new CryptoService instance.
395*/
396export function createCryptoService(): CryptoService {
397return new CryptoServiceImpl();
398}
ZenServersecurity-service.ts12 matches
421422/**
423* Clears rate limit for a key (admin function).
424*/
425clearRateLimit(key: string): boolean {
506507/**
508* Gets list of blocked IPs (admin function).
509*/
510getBlockedIPs(): string[] {
513514/**
515* Gets list of suspicious IPs (admin function).
516*/
517getSuspiciousIPs(): string[] {
520521/**
522* Unblocks an IP address (admin function).
523*/
524unblockIP(ip: string): boolean {
535536/**
537* Clears suspicious status for an IP (admin function).
538*/
539clearSuspiciousIP(ip: string): boolean {
551552// ========================================
553// Utility Functions
554// ========================================
555557* Creates a rate limit key for IP and endpoint.
558*/
559export function createRateLimitKey(
560ip: string,
561endpoint: string,
567* Validates security headers comprehensively.
568*/
569export function validateSecurityHeaders(headers: Headers): {
570valid: boolean;
571issues: string[];
615* Checks if request is from a known bot/crawler.
616*/
617export function isKnownBot(userAgent: string): boolean {
618const botPatterns = [
619/googlebot/i,
637* Extracts geolocation info from IP (placeholder).
638*/
639export function getIPGeolocation(ip: string): {
640country?: string;
641region?: string;
672673// ========================================
674// Factory Function
675// ========================================
676678* Creates a new security service instance.
679*/
680export function createSecurityService(): SecurityService {
681return new SecurityServiceImpl();
682}