> ## Documentation Index
> Fetch the complete documentation index at: https://docs-terra.withunify.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Security

> Defense-in-depth security practices for Terra

# Security

> Terra uses defense-in-depth: multiple layers of protection for sensitive data.

## Security Utilities

All security functions live in `src/lib/security.ts`:

| Function                | Protects Against      |
| ----------------------- | --------------------- |
| `getSafeRedirectPath()` | Open redirect attacks |
| `sanitizeStoragePath()` | Path traversal        |
| `cleanFileName()`       | Malicious filenames   |
| `isValidExternalUrl()`  | Protocol injection    |

## XSS Prevention

All user-generated HTML is sanitized:

```typescript theme={null}
import DOMPurify from "isomorphic-dompurify";

const safeHtml = DOMPurify.sanitize(userContent);
```

## Path Traversal Protection

Three-layer validation for file paths:

```typescript theme={null}
// Layer 1: Client sanitizes filename
const safe = cleanFileName("../../evil.exe"); // "evil.exe"

// Layer 2: Server constructs safe path
const path = buildSafeStoragePath(formId, fileId, safe);

// Layer 3: Final validation
const validated = sanitizeStoragePath(path);
```

## Open Redirect Prevention

```typescript theme={null}
function getSafeRedirectPath(path: string): string {
  // Must start with /
  if (!path.startsWith("/")) return "/";

  // No protocol injection
  if (path.includes("://")) return "/";

  // No double slashes
  if (path.startsWith("//")) return "/";

  return path;
}
```

## Rate Limiting

| Endpoint         | Limit      |
| ---------------- | ---------- |
| Form submissions | 30/minute  |
| Webhooks         | 500/minute |
| API routes       | 100/minute |

## Fail-Secure Pattern

```typescript theme={null}
// When in doubt, deny access
try {
  const user = await checkPermission();
  if (!user) throw new Error("No user");
  return user;
} catch {
  // ANY error = no access
  throw new Error("Unauthorized");
}
```

***

<CardGroup cols={2}>
  <Card title="Encryption" icon="lock" href="/core-systems/data/encryption-pii">
    PII encryption
  </Card>

  <Card title="Authentication" icon="key" href="/core-systems/identity/authentication">
    Auth security
  </Card>
</CardGroup>
