DEV Community

Cover image for CHAPTER 48 SECURE FRONTEND & CLIENT-SIDE AI ARCHITECTURE
Black Shadow Team ©
Black Shadow Team ©

Posted on

CHAPTER 48 SECURE FRONTEND & CLIENT-SIDE AI ARCHITECTURE

#ai

CHAPTER 48

SECURE FRONTEND & CLIENT-SIDE AI ARCHITECTURE

Browser Security, CSP, XSS Defense, CSRF, Secure File Uploads, Web Workers, Local AI, IndexedDB, Client-Side Privacy, Token Protection, Secure UI State, Media Processing Security & Frontend Threat Modeling


48.1 Introduction

The frontend is often treated as a presentation layer.

For a modern AI application, that assumption is incomplete.

A browser-based AI application may:

  • accept images and videos,
  • process documents,
  • interact with microphones and cameras,
  • communicate with AI APIs,
  • display generated content,
  • maintain authentication state,
  • store temporary data,
  • execute JavaScript,
  • communicate with multiple backend services,
  • use Web Workers,
  • use browser databases,
  • invoke local AI models,
  • handle large media files.

Consequently, the frontend becomes an important security boundary.

A secure frontend architecture should assume that:

Anything running in the user's browser is ultimately under the user's control.

This does not mean the frontend is unimportant.

It means the frontend should enforce usability and defense-in-depth controls while the server remains the ultimate authority for sensitive operations.


48.2 Browser Trust Model

The browser should be considered a partially trusted execution environment.

A useful model is:

                 SERVER
                   │
          Source of Truth
                   │
                   ▼
             ┌──────────┐
             │ Frontend │
             └────┬─────┘
                  │
        ┌─────────┼─────────┐
        │         │         │
        ▼         ▼         ▼
      UI State  Browser   Local Files
                 Storage
Enter fullscreen mode Exit fullscreen mode

The frontend can improve security, but it should not be the only enforcement layer.

For example:

Frontend:
    "This button is disabled."

Backend:
    "This operation is actually unauthorized."
Enter fullscreen mode Exit fullscreen mode

The second control is the security boundary.


48.3 Client-Side vs Server-Side Security

A common architectural mistake is placing security decisions exclusively in frontend code.

For example:

if (user.role === "admin") {
  showAdminPanel();
}
Enter fullscreen mode Exit fullscreen mode

This controls visibility.

It does not establish authorization.

The backend must independently verify the user's authorization before executing the privileged operation.

Therefore:

Frontend Authorization
        +
Backend Authorization
        =
Defense in Depth
Enter fullscreen mode Exit fullscreen mode

The backend remains authoritative.


48.4 Frontend Threat Model

A frontend threat model should consider:

Input threats

  • malicious text,
  • malicious HTML,
  • unexpected file types,
  • oversized uploads,
  • malformed media,
  • dangerous metadata.

Browser threats

  • XSS,
  • CSRF,
  • clickjacking,
  • malicious browser extensions,
  • insecure storage,
  • compromised dependencies.

Network threats

  • insecure connections,
  • incorrect CORS configuration,
  • token leakage,
  • unauthorized API access.

AI-specific threats

  • prompt injection,
  • malicious uploaded content,
  • unsafe generated content,
  • untrusted model output,
  • excessive client-side permissions.

48.5 XSS

Cross-Site Scripting occurs when attacker-controlled content becomes executable browser content.

Conceptually:

Untrusted Input
      ↓
Unsafe Rendering
      ↓
Browser interprets content
      ↓
Unexpected script execution
Enter fullscreen mode Exit fullscreen mode

AI applications can encounter this problem because generated content may contain:

  • HTML,
  • Markdown,
  • code,
  • links,
  • formatted text,
  • user-provided content.

Generated content should therefore be treated as untrusted unless explicitly validated and safely rendered.


48.6 Safe Rendering of AI Output

Suppose an AI model returns:

Hello <something>
Enter fullscreen mode Exit fullscreen mode

The application should not automatically interpret the result as trusted HTML.

A safer conceptual pipeline is:

AI Output
   ↓
Treat as Untrusted
   ↓
Parse/Validate
   ↓
Sanitize if HTML is required
   ↓
Render using Safe Renderer
Enter fullscreen mode Exit fullscreen mode

For ordinary text, plain-text rendering is preferable to arbitrary HTML rendering.


48.7 React and Dangerous HTML

Frameworks can provide useful defaults, but developers can bypass those protections.

For example, mechanisms equivalent to direct HTML injection should be treated as high-risk.

A secure policy is:

Default:
    Render text safely

Exceptional HTML:
    Validate
    Sanitize
    Restrict
    Audit
Enter fullscreen mode Exit fullscreen mode

Avoid allowing arbitrary model output to become executable HTML.


48.8 Content Security Policy

Content Security Policy, or CSP, is an important browser defense mechanism.

Conceptually:

Browser
   │
   ▼
CSP Policy
   │
   ├── Allowed scripts
   ├── Allowed styles
   ├── Allowed images
   ├── Allowed connections
   └── Allowed frames
Enter fullscreen mode Exit fullscreen mode

A carefully designed CSP can reduce the impact of some classes of injection attacks.

The policy should be developed around the application's actual architecture rather than copied blindly.


48.9 CSP Example

A conceptual policy might look like:

default-src 'self';
script-src 'self';
style-src 'self';
img-src 'self' data: blob:;
font-src 'self';
connect-src 'self' https://approved-api.example;
object-src 'none';
frame-ancestors 'none';
base-uri 'self';
Enter fullscreen mode Exit fullscreen mode

The exact policy must be adapted to the application.

External AI providers, analytics, CDNs, authentication services, and media infrastructure may require additional carefully restricted sources.


48.10 Clickjacking Protection

Clickjacking occurs when a legitimate interface is embedded into an unexpected framing context.

A frontend can reduce this risk through appropriate frame restrictions.

Conceptually:

Application
     │
     ├── allowed framing contexts
     └── blocked framing contexts
Enter fullscreen mode Exit fullscreen mode

For applications that should never be embedded, a restrictive policy is generally appropriate.


48.11 CSRF

Cross-Site Request Forgery can occur when a browser automatically includes authentication credentials with an unwanted request.

A conceptual attack path is:

Victim Browser
      │
      ▼
Malicious Site
      │
      ▼
Unwanted Request
      │
      ▼
Authenticated Application
Enter fullscreen mode Exit fullscreen mode

Defenses depend on the authentication architecture.

Potential controls include:

  • SameSite cookies,
  • CSRF tokens,
  • origin verification,
  • appropriate CORS policies,
  • state-changing request protections.

48.12 Cookies

Authentication cookies should be configured carefully.

Common security attributes include:

Secure
HttpOnly
SameSite
Enter fullscreen mode Exit fullscreen mode

Secure

Helps ensure the cookie is transmitted only over HTTPS.

HttpOnly

Prevents ordinary JavaScript from reading the cookie.

SameSite

Controls cross-site cookie behavior.

The exact configuration should match the application's authentication architecture.


48.13 Token Protection

Sensitive access tokens should not be casually placed in:

URL parameters
console logs
DOM elements
localStorage
error messages
analytics payloads
Enter fullscreen mode Exit fullscreen mode

The architecture should minimize token exposure.

For browser applications, an HttpOnly secure session-cookie model can often reduce direct JavaScript access to authentication credentials.


48.14 Local Storage

Browser local storage is convenient but should not automatically be treated as a secure secret store.

Data stored there may be accessible to JavaScript executing in the application's origin.

Therefore:

Public UI Preference
    → localStorage may be reasonable

Sensitive authentication secret
    → carefully evaluate alternative architecture
Enter fullscreen mode Exit fullscreen mode

Examples of suitable local preferences include:

theme
language
editor layout
non-sensitive UI settings
Enter fullscreen mode Exit fullscreen mode

48.15 IndexedDB

IndexedDB provides structured browser-side storage.

It can be useful for:

  • temporary editing projects,
  • offline application state,
  • cached media metadata,
  • non-sensitive drafts,
  • local processing state.

Architecture:

Browser
  │
  ▼
IndexedDB
  │
  ├── Project metadata
  ├── Temporary edits
  └── Offline state
Enter fullscreen mode Exit fullscreen mode

Sensitive information should have an explicit storage policy.


48.16 Client-Side Privacy

A privacy-aware frontend should minimize data collection.

Before sending information to a backend or external AI provider, consider:

Is this data necessary?
       ↓
Can it be minimized?
       ↓
Can it be processed locally?
       ↓
Can sensitive metadata be removed?
       ↓
Does the user understand what will happen?
Enter fullscreen mode Exit fullscreen mode

This creates a data-minimization pipeline.


48.17 Client-Side AI

Client-side AI means some AI computation happens directly on the user's device.

Possible benefits include:

  • reduced server traffic,
  • lower latency,
  • offline capabilities,
  • improved privacy for certain workloads,
  • reduced cloud processing.

Conceptually:

User
 │
 ▼
Browser
 │
 ├── Local Preprocessing
 ├── Local AI
 └── Local Rendering
       │
       ▼
Optional Server
Enter fullscreen mode Exit fullscreen mode

However, client-side AI does not automatically make data private.

Browser software itself may have network access unless the architecture restricts it.


48.18 Local AI Security Model

A local model should be considered application code plus data.

Important considerations include:

  • model integrity,
  • memory usage,
  • resource exhaustion,
  • model artifact provenance,
  • browser compatibility,
  • data persistence,
  • cache behavior.

A secure architecture should define what data may leave the device.


48.19 Web Workers

CPU-intensive client-side processing should often be moved into Web Workers where practical.

For example:

Main Thread
     │
     ├── UI
     ├── Controls
     └── Rendering
            │
            ▼
        Web Worker
            │
            ├── Image Processing
            ├── Parsing
            └── Local AI
Enter fullscreen mode Exit fullscreen mode

This improves responsiveness.

Workers should still follow the same data-validation and resource-control principles as other application components.


48.20 Worker Isolation

A worker should not automatically receive every piece of application state.

A safer conceptual design is:

Main Application
      │
      │ minimal message
      ▼
Worker
      │
      ▼
Processing
      │
      ▼
Sanitized Result
Enter fullscreen mode Exit fullscreen mode

Instead of:

Main Application
      │
      ▼
Worker
      │
      ▼
Entire application state
Enter fullscreen mode Exit fullscreen mode

Minimal data transfer reduces accidental exposure.


48.21 Message Validation

Communication between the main thread and workers should validate message types.

Example:

```ts id="9gxw8x"
type WorkerMessage =
| {
type: "resize";
width: number;
height: number;
}
| {
type: "filter";
filter: "grayscale" | "blur" | "sharpen";
};

function isWorkerMessage(value: unknown): value is WorkerMessage {
if (!value || typeof value !== "object") {
return false;
}

const message = value as Record;

if (message.type === "resize") {
return (
typeof message.width === "number" &&
typeof message.height === "number"
);
}

if (message.type === "filter") {
return ["grayscale", "blur", "sharpen"].includes(
message.filter as string
);
}

return false;
}




Validation prevents unexpected application states from entering processing logic.

---

# 48.22 Secure File Upload Architecture

AI media applications frequently accept:

* JPEG,
* PNG,
* WebP,
* video,
* audio,
* PDF,
* text documents.

File extensions alone are insufficient for security.

A safer upload pipeline is:



```text
User
 ↓
Frontend Validation
 ↓
Upload Gateway
 ↓
Authentication
 ↓
Size Limit
 ↓
Content-Type Check
 ↓
File Signature Validation
 ↓
Malware/Security Scan
 ↓
Isolated Storage
 ↓
Processing Queue
 ↓
Sanitized Processing
Enter fullscreen mode Exit fullscreen mode

The frontend can perform early validation, but the backend must repeat security-critical checks.


48.23 File Size Limits

Large media files can consume:

  • bandwidth,
  • memory,
  • storage,
  • CPU,
  • GPU resources,
  • processing time.

Therefore, limits should exist at multiple levels:

Browser
 ↓
API Gateway
 ↓
Upload Service
 ↓
Processing Worker
Enter fullscreen mode Exit fullscreen mode

Example policy:

```ts id="8n9qgv"
interface UploadPolicy {
maxBytes: number;
allowedMimeTypes: string[];
maxProcessingDurationMs: number;
}




---

# 48.24 File Type Validation

Do not trust only the filename.

For example:



```text
photo.jpg
Enter fullscreen mode Exit fullscreen mode

does not prove that the underlying bytes represent a valid JPEG.

The backend should inspect the file appropriately before processing.

A secure architecture therefore separates:

Filename
Extension
Declared MIME type
Detected file format
Actual processing requirements
Enter fullscreen mode Exit fullscreen mode

48.25 Media Processing Isolation

Media processing libraries can be complex.

For AI applications that process untrusted media, processing should ideally occur in an isolated worker environment.

Upload
  ↓
Quarantine
  ↓
Processing Worker
  ↓
Validation
  ↓
Transformation
  ↓
Sanitized Output
  ↓
Application Storage
Enter fullscreen mode Exit fullscreen mode

The worker should have limited access to the rest of the infrastructure.


48.26 Temporary Files

Temporary media should have a lifecycle.

Created
  ↓
Processing
  ↓
Result Stored
  ↓
Temporary Data Deleted
Enter fullscreen mode Exit fullscreen mode

Temporary storage should not become a permanent hidden archive of user files.

This connects directly to the data-retention policies discussed in Chapter 46.


48.27 Image Metadata

Images can contain metadata such as:

  • timestamps,
  • device information,
  • location metadata,
  • editing information.

Depending on the use case, metadata may need to be removed or minimized before sharing generated output.

A privacy-aware media pipeline can therefore include:

Image
 ↓
Metadata Inspection
 ↓
Privacy Policy
 ↓
Remove / Preserve
 ↓
Output
Enter fullscreen mode Exit fullscreen mode

48.28 Video Security

Video processing introduces additional resource concerns.

A video may contain:

  • very high resolution,
  • long duration,
  • multiple streams,
  • large frame counts,
  • complex codecs.

Security controls can include:

Maximum file size
Maximum duration
Maximum resolution
Maximum frame rate
Maximum processing time
Maximum concurrent jobs
Enter fullscreen mode Exit fullscreen mode

This helps protect infrastructure against accidental or abusive resource consumption.


48.29 Audio Security

Audio processing should similarly consider:

  • file size,
  • duration,
  • codec,
  • sample rate,
  • channel count,
  • processing time.

A safe processing service should reject unsupported or excessive workloads before expensive processing begins.


48.30 Drag-and-Drop Security

Drag-and-drop interfaces are convenient but should not bypass normal validation.

The same validation pipeline should apply whether a file arrives through:

File picker
Drag-and-drop
Clipboard
Mobile share
Programmatic browser input
Enter fullscreen mode Exit fullscreen mode

The UI path should not determine the security policy.


48.31 Clipboard Security

Applications that read clipboard data should request or use the appropriate browser permissions and should avoid collecting clipboard information unnecessarily.

A privacy-preserving policy is:

User explicitly initiates action
       ↓
Read clipboard
       ↓
Process requested content
       ↓
Do not retain unnecessarily
Enter fullscreen mode Exit fullscreen mode

48.32 Camera and Microphone Permissions

If the application uses camera or microphone capabilities, permissions should be requested only when needed.

Avoid requesting:

camera
microphone
location
notifications
Enter fullscreen mode Exit fullscreen mode

simply at application startup when they are not immediately required.

Permission minimization improves both privacy and user trust.


48.33 Secure UI State

Frontend state should be divided into categories.

UI State
Application State
Server State
Security-Sensitive State
Enter fullscreen mode Exit fullscreen mode

Examples:

UI State

theme
sidebar
selected tab
Enter fullscreen mode Exit fullscreen mode

Application State

current project
editor configuration
selected media
Enter fullscreen mode Exit fullscreen mode

Server State

generation status
job history
account information
Enter fullscreen mode Exit fullscreen mode

Security-Sensitive State

authentication context
authorization information
temporary security challenges
Enter fullscreen mode Exit fullscreen mode

Security-sensitive state deserves special treatment.


48.34 Never Trust Client-Supplied Roles

A browser might contain:

```json id="z6t4hi"
{
"role": "admin"
}




That does not prove the user is an administrator.

Client state is user-controlled.

Therefore:



```text
Client Role
    ≠
Authoritative Role
Enter fullscreen mode Exit fullscreen mode

The server must determine authorization from trusted server-side state.


48.35 Frontend API Design

Frontend requests should be explicit.

Example:

```ts id="i5d9cw"
interface CreateGenerationRequest {
prompt: string;
model: string;
width: number;
height: number;
}




The backend should independently validate:

* prompt size,
* model availability,
* resolution limits,
* user permissions,
* quotas,
* policy restrictions.

---

# 48.36 CORS

Cross-Origin Resource Sharing controls which browser origins may interact with an API.

A dangerous pattern is broadly allowing arbitrary origins without understanding credential behavior.

A more controlled approach is:



```text
Approved Frontend Origin
       ↓
API
       ↓
Allowed
Enter fullscreen mode Exit fullscreen mode

Unknown origins should not automatically receive privileged access.

CORS should complement authentication and authorization rather than replace them.


48.37 Subresource Integrity

When appropriate, Subresource Integrity can allow browsers to verify the expected cryptographic hash of externally loaded resources.

Conceptually:

Expected Resource Hash
          │
          ▼
Downloaded Resource
          │
          ▼
Hash Comparison
          │
      ┌───┴───┐
      │       │
    Match   Mismatch
      │       │
    Load    Block
Enter fullscreen mode Exit fullscreen mode

Its usefulness depends on how third-party resources are integrated.


48.38 Third-Party JavaScript

Every third-party script increases the application's trust boundary.

Examples include:

  • analytics,
  • payment interfaces,
  • support widgets,
  • advertising,
  • monitoring,
  • authentication integrations.

A third-party script may potentially access information available to the page depending on how it is integrated.

Therefore:

Third Party
    ↓
Need identified
    ↓
Data access minimized
    ↓
Permissions restricted
    ↓
Dependency monitored
Enter fullscreen mode Exit fullscreen mode

48.39 Frontend Dependency Security

Frontend dependencies should be managed like backend dependencies.

Controls include:

  • lockfiles,
  • version review,
  • vulnerability scanning,
  • dependency updates,
  • removal of unused packages,
  • software inventory,
  • build verification.

A small dependency graph is often easier to secure.


48.40 Error Handling

Frontend errors should not expose sensitive implementation details.

Avoid displaying:

database credentials
internal hostnames
stack traces
provider secrets
internal authorization information
Enter fullscreen mode Exit fullscreen mode

A user-facing error can be:

"Generation could not be completed. Please try again."
Enter fullscreen mode Exit fullscreen mode

while detailed diagnostic information remains in controlled server-side logs.


48.41 Secure Debugging

Development debugging tools should not accidentally remain enabled in production.

Production builds should be reviewed for:

  • debug endpoints,
  • verbose logs,
  • development credentials,
  • test accounts,
  • mock APIs,
  • development flags.

Environment configuration should be explicit.


48.42 Source Maps

Source maps can improve debugging but may expose application source details if publicly served.

Organizations should determine whether production source maps should be:

  • public,
  • access-controlled,
  • stored privately,
  • uploaded only to monitoring infrastructure.

This is an architectural decision rather than a universal rule.


48.43 Browser Caching

Caching can improve performance but may create privacy risks.

Sensitive responses should have appropriate cache behavior.

Conceptually:

Public static asset
    → cache aggressively

Sensitive account data
    → controlled caching

Private generated media
    → carefully controlled caching
Enter fullscreen mode Exit fullscreen mode

Cache policies should match data sensitivity.


48.44 Service Workers

Service workers can provide:

  • offline functionality,
  • caching,
  • background processing,
  • application-shell support.

However, service workers operate with significant capabilities within their scope.

Their lifecycle and update mechanisms should therefore be controlled.

A compromised service worker can have broad effects within its origin.


48.45 Browser Privacy Boundaries

The application should understand the distinction between:

Browser memory
Browser storage
Network requests
Server storage
External provider processing
Enter fullscreen mode Exit fullscreen mode

A user should not be told that data is “local” if the application subsequently sends it to a cloud service.

Transparency is part of security.


48.46 Client-Side Encryption

Some applications may encrypt sensitive content before transmission or storage.

However, encryption design must consider where the keys exist.

For example:

Encrypt Data
     ↓
Where is Key?
     │
     ├── Browser
     ├── Server
     └── External Key Service
Enter fullscreen mode Exit fullscreen mode

If JavaScript can access the key, XSS may potentially undermine the protection.

Therefore client-side encryption is not a replacement for frontend security.


48.47 Secure Download Architecture

Generated files should be served through controlled authorization.

A safe conceptual flow is:

User
 ↓
Request Download
 ↓
Authenticate
 ↓
Authorize Resource
 ↓
Generate Controlled Access
 ↓
Download
Enter fullscreen mode Exit fullscreen mode

The server should verify that the requested file belongs to the user or that the user otherwise has permission to access it.


48.48 Object Storage URLs

Applications sometimes use temporary signed URLs for private files.

Conceptually:

Application
   ↓
Authorization
   ↓
Short-Lived Access URL
   ↓
Object Storage
Enter fullscreen mode Exit fullscreen mode

This can avoid exposing permanent public object URLs.

The expiration and scope should match the intended operation.


48.49 Frontend Threat Model Table

Threat Example Primary Controls
XSS Untrusted AI output rendered as HTML Safe rendering, sanitization, CSP
CSRF Unwanted authenticated request SameSite, CSRF protection, origin checks
Token leakage Credential exposed in URL/log Secure session architecture
Malicious upload Unexpected file content Validation, scanning, isolation
Resource exhaustion Huge media file Size/time/resource limits
Clickjacking UI embedded elsewhere Frame restrictions
Dependency compromise Malicious package Lockfiles, scanning, review
Data leakage Sensitive data sent externally Data classification, provider policy
Client-side tampering Modified UI state Server-side authorization
Privacy leakage Metadata retained unnecessarily Minimization and deletion
Cache leakage Private content cached Controlled cache policy

48.50 Secure Frontend Architecture

A comprehensive architecture can be represented as:

                         USER
                           │
                           ▼
                    ┌─────────────┐
                    │   Browser   │
                    └──────┬──────┘
                           │
          ┌────────────────┼────────────────┐
          │                │                │
          ▼                ▼                ▼
       UI Layer       Local Processing   Local Storage
          │                │                │
          │             Worker              │
          │                │                │
          └────────────────┼────────────────┘
                           │
                           ▼
                     HTTPS / TLS
                           │
                           ▼
                      WAF / API
                        Gateway
                           │
                           ▼
                    Authentication
                           │
                           ▼
                    Authorization
                           │
                           ▼
                     Application
                           │
             ┌─────────────┼─────────────┐
             │             │             │
             ▼             ▼             ▼
          Storage        AI Gateway    Database
                           │
                    ┌──────┴──────┐
                    │             │
                    ▼             ▼
                Local AI     External AI
Enter fullscreen mode Exit fullscreen mode

48.51 Security Boundary Matrix

A useful way to design the frontend is to identify where each control belongs.

Control Frontend Backend Infrastructure
UI validation
File-size precheck
Authentication
Authorization
Rate limiting
CSP
Database access
Secret management
AI provider credentials
Malware scanning
Resource quotas
Audit logging
Secure rendering
Backup

The same security objective can therefore be protected at multiple layers.


48.52 Secure Frontend Development Lifecycle

A mature frontend security lifecycle is:

Threat Model
     ↓
Secure Design
     ↓
Input Validation
     ↓
Safe Rendering
     ↓
Dependency Review
     ↓
Security Testing
     ↓
Production Build
     ↓
Deployment Verification
     ↓
Runtime Monitoring
     ↓
Continuous Improvement
Enter fullscreen mode Exit fullscreen mode

Security should be considered before the interface is implemented, not after it is finished.


48.53 Frontend Security Testing

Testing should cover:

Functional security

  • unauthorized UI actions,
  • session expiration,
  • logout behavior,
  • permission changes.

Input security

  • malformed text,
  • unexpected Unicode,
  • oversized files,
  • invalid media,
  • unsupported formats.

Browser security

  • CSP,
  • cookie configuration,
  • CORS,
  • frame restrictions,
  • secure transport.

AI security

  • untrusted generated output,
  • uploaded prompt-injection content,
  • unsafe links,
  • malicious document content.

Privacy

  • browser storage,
  • cache,
  • logs,
  • analytics,
  • third-party integrations.

48.54 Security Regression Testing

Security fixes should become permanent tests.

For example:

Security Bug Found
      ↓
Fix
      ↓
Add Regression Test
      ↓
CI Pipeline
      ↓
Future Builds
Enter fullscreen mode Exit fullscreen mode

This prevents previously resolved vulnerabilities from silently returning.


48.55 Frontend Security Checklist

Browser

  • [ ] HTTPS
  • [ ] secure cookie configuration
  • [ ] CSP
  • [ ] frame restrictions
  • [ ] controlled CORS
  • [ ] safe rendering

Authentication

  • [ ] server-authoritative sessions
  • [ ] secure logout
  • [ ] session expiration
  • [ ] no sensitive tokens in URLs
  • [ ] appropriate cookie attributes

Files

  • [ ] client-side validation
  • [ ] server-side validation
  • [ ] MIME/type verification
  • [ ] file-size limits
  • [ ] processing isolation
  • [ ] temporary-file lifecycle

AI

  • [ ] model output treated as untrusted
  • [ ] prompt content validated
  • [ ] external-provider policy
  • [ ] client/server trust separation
  • [ ] resource limits

Storage

  • [ ] minimal local storage
  • [ ] controlled IndexedDB use
  • [ ] privacy-aware caching
  • [ ] sensitive-data retention policy

Dependencies

  • [ ] lockfiles
  • [ ] dependency scanning
  • [ ] unused package removal
  • [ ] controlled third-party scripts

Operations

  • [ ] production debugging disabled
  • [ ] security logging
  • [ ] monitoring
  • [ ] regression tests
  • [ ] incident-response integration

48.56 Final Principle

The frontend should be considered a security-aware client, not the final security authority.

A strong AI application therefore follows:

Frontend
   ↓
Validate early
   ↓
Protect user experience
   ↓
Minimize data
   ↓
Render safely
   ↓
Communicate securely
   ↓
Backend
   ↓
Authenticate
   ↓
Authorize
   ↓
Validate again
   ↓
Enforce policy
   ↓
Infrastructure
   ↓
Isolate
   ↓
Monitor
   ↓
Recover
Enter fullscreen mode Exit fullscreen mode

This layered approach recognizes a fundamental property of browser applications:

the client can be modified, inspected, automated, or replaced by the user.

Consequently, security-critical decisions must remain enforceable on trusted server-side infrastructure.

For AI applications, this becomes even more important because the frontend may handle untrusted prompts, generated content, media, documents, local models, and external AI services.

The secure frontend is therefore not simply a beautiful interface.

It is a carefully controlled boundary between the user, the browser, local computation, external networks, and trusted backend infrastructure.

END OF CHAPTER 48

Implementation snippets

  1. Security-aware session cookie configuration

export const sessionCookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
maxAge: 60 * 60 * 24 * 7,
};

  1. Safe worker message validation

type WorkerMessage =
| {
type: "resize";
width: number;
height: number;
}
| {
type: "filter";
filter: "grayscale" | "blur" | "sharpen";
};

export function validateWorkerMessage(
input: unknown
): input is WorkerMessage {
if (!input || typeof input !== "object") {
return false;
}

const value = input as Record;

if (value.type === "resize") {
return (
Number.isFinite(value.width) &&
Number.isFinite(value.height) &&
Number(value.width) > 0 &&
Number(value.height) > 0
);
}

if (value.type === "filter") {
return ["grayscale", "blur", "sharpen"].includes(
String(value.filter)
);
}

return false;
}

  1. Server-side authorization must remain authoritative

interface AuthContext {
userId: string;
permissions: string[];
}

function requirePermission(
context: AuthContext,
permission: string
): void {
if (!context.permissions.includes(permission)) {
throw new Error("Forbidden");
}
}

export async function createGeneration(
context: AuthContext,
input: unknown
) {
requirePermission(context, "generation:create");

// Validate input again on the server.
// Apply quota and safety policies.
// Create the AI job only after authorization succeeds.
}

  1. Upload policy

const uploadPolicy = {
maxBytes: 50 * 1024 * 1024,

allowedMimeTypes: [
"image/jpeg",
"image/png",
"image/webp",
"video/mp4",
],
};

export function validateUpload(
size: number,
mimeType: string
): boolean {
if (size <= 0 || size > uploadPolicy.maxBytes) {
return false;
}

return uploadPolicy.allowedMimeTypes.includes(mimeType);
}

  1. Client-side data-minimization helper

interface GenerationRequest {
prompt: string;
model: string;
width: number;
height: number;
}

export function minimizeGenerationRequest(
request: GenerationRequest
): GenerationRequest {
return {
prompt: request.prompt.trim(),
model: request.model,
width: Math.floor(request.width),
height: Math.floor(request.height),
};
}

Top comments (0)