# Security Model

This document outlines the security architecture, threat model, and best practices for the Network-Agnostic Secure Payment Instruction Protocol (NASPIP).

## Security Architecture

### Cryptographic Foundation

NASPIP is built on **PASETO v4 public tokens** with Ed25519 keys:

#### PASETO v4 Public Tokens

- **Signing**: Ed25519 via PASETO v4 (`v4.public.*`)
- **Payload encoding**: Protobuf (not raw JSON)
- **Claims**: Standard PASETO claims plus NASPIP-specific `kis`, `kid`, `kep`
- **Purpose**: Integrity and authenticity of payment instructions (not confidentiality — public tokens are verifiable by anyone with the public key)

#### Key identification

- **`kis` (key issuer)**: Identifies the key-issuing entity (e.g. `fluxis.us`)
- **`kid` (key ID)**: Selects the specific signing key for verification
- **`kep` (key expiration)**: When the signing key itself expires

### Key Management

#### Key Generation

```javascript
// Secure key generation using cryptographically secure random number generator
const keyPair = await crypto.subtle.generateKey(
  {
    name: "Ed25519",
  },
  true, // extractable
  ["sign", "verify"],
);
```

#### Key Storage Best Practices

1. **Hardware Security Modules (HSM)**: Store private keys in dedicated hardware
2. **Key Derivation**: Use PBKDF2 or Argon2 for key derivation from passwords
3. **Key Rotation**: Implement regular key rotation procedures
4. **Access Control**: Limit access to private keys to authorized personnel only

## Threat Model

### Attack Vectors

NASPIP is designed to protect against the following attack vectors:

#### 1. Data Tampering

**Threat**: Malicious modification of payment instructions
**Protection**: Digital signatures ensure data integrity
**Mitigation**:

- All payment instructions are cryptographically signed
- PASETO v4 signature verification prevents unauthorized modifications
- Protobuf payload encoding prevents signature bypass via JSON reordering

#### 2. Replay Attacks

**Threat**: Reusing valid payment instructions multiple times
**Protection**: Unique identifiers and expiration times
**Mitigation**:

- Each payment instruction has a unique ID
- Expiration times prevent indefinite reuse
- Server-side validation of payment status

#### 3. Man-in-the-Middle (MITM) Attacks

**Threat**: Interception and modification of payment data in transit
**Protection**: Cryptographic signatures on every token (PASETO v4)
**Mitigation**:

- Payment instructions are signed at issuance with the issuer's private key
- Wallets verify signatures using the issuer's public key (`kis` + `kid` lookup)
- TLS protects transport; signature verification protects payload integrity independent of TLS

#### 4. Impersonation Attacks

**Threat**: Malicious actors pretending to be legitimate payment providers
**Protection**: Public key verification
**Mitigation**:

- Public keys are used to verify signature authenticity
- Key fingerprint verification
- Certificate pinning for known entities

#### 5. Brute Force Attacks

**Threat**: Attempting to guess private keys or signatures
**Protection**: Cryptographically secure key generation
**Mitigation**:

- 256-bit Ed25519 keys provide 128-bit security
- Secure random number generation
- Rate limiting on verification attempts

### Security Assumptions

NASPIP's security relies on the following assumptions:

1. **Cryptographic Primitives**: PASETO v4 and Ed25519 are secure
2. **Random Number Generation**: Cryptographically secure RNG is available
3. **Key Management**: Private keys are kept secure by the issuer
4. **Network Transport**: Transport layer security (TLS) for data in transit
5. **Implementation**: Correct use of naspip-go or Fluxis API for sign/verify

## Security Features

### 1. Data Integrity

Every payment instruction is wrapped in a PASETO v4 public token to ensure it hasn't been tampered with:

```javascript
// Verification via Fluxis API (recommended)
const response = await fetch("https://api.fluxis.us/v1/naspip/read", {
  method: "POST",
  headers: {
    Authorization: "Bearer <token>",
    "x-fluxis-api-key": "<api_key_id>",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ token: naspipToken }),
});
// PASETO signature is verified server-side; invalid tokens return MD0004/MD0006
```

### 2. Authentication

PASETO v4 signatures provide proof of origin. Verifiers resolve the issuer's public key using `kis` and `kid` from the token string, then validate the PASETO signature and expiration claims. Fluxis performs this automatically in `POST /v1/naspip/read`.

### 3. Non-repudiation

Payment instructions cannot be denied by the signer:

- Digital signatures provide mathematical proof of origin
- Signatures are tied to specific private keys
- Audit trails can be maintained

### 4. Expiration and Timeouts

Payment instruction tokens include PASETO `exp` claims (default **1 hour**). Instruction payloads may also set `payment.expires_at`:

```json
{
  "payment": {
    "expires_at": 1759397652
  }
}
```

### 5. Unique Identifiers

Each payment instruction has a unique identifier to prevent replay attacks:

```json
{
  "payment": {
    "id": "550e8400-e29b-41d4-a716-446655440000"
  }
}
```

### 6. URL Payload Trust Boundary (Fluxis)

URL payloads defer payment details to an HTTPS endpoint. When Fluxis resolves a URL during `POST /v1/naspip/read`:

- The NASPIP token signature is verified **before** the URL fetch
- The fetched response replaces `payload.data` — callers must treat resolved data with the same validation as direct instruction payloads
- URL endpoints must be trusted Fluxis checkout URLs; arbitrary URLs are rejected on fetch failure

## Security Best Practices

### For Implementers

#### 1. Key Management

```javascript
// ✅ Good: Use secure key generation
const keyPair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
  "sign",
  "verify",
]);

// ❌ Bad: Don't use predictable keys
const predictableKey = "my-secret-key-123";
```

#### 2. Input Validation

```javascript
// ✅ Good: Validate all inputs
function validatePaymentInstruction(instruction) {
  if (!instruction.amount || !instruction.amount.value) {
    throw new Error("Amount is required");
  }
  if (parseFloat(instruction.amount.value) <= 0) {
    throw new Error("Amount must be positive");
  }
  // ... more validation
}

// ❌ Bad: Trusting input without validation
function processPayment(instruction) {
  // Process without validation
  return process(instruction);
}
```

#### 3. Error Handling

```javascript
// ✅ Good: Don't expose sensitive information
try {
  const result = await verifySignature(token, publicKey);
  return result;
} catch (error) {
  // Log internally for debugging
  logger.error('Signature verification failed', { error: error.message });
  // Return generic error to user
  throw new Error('Invalid payment instruction');
}

// ❌ Bad: Exposing internal details
catch (error) {
  throw new Error(`Signature verification failed: ${error.stack}`);
}
```

#### 4. Secure Random Generation

```javascript
// ✅ Good: Use cryptographically secure random
const uniqueId = crypto.randomBytes(16).toString("hex");

// ❌ Bad: Using predictable values
const uniqueId = Date.now().toString();
```

### For Users

#### 1. Public Key Verification

- Always verify the public key of payment providers
- Use certificate pinning for known entities
- Check key fingerprints against trusted sources

#### 2. Expiration Validation

- Always check expiration times before processing payments
- Reject expired payment instructions
- Implement reasonable expiration policies

#### 3. Amount Validation

- Validate payment amounts on both sender and receiver sides
- Implement minimum and maximum amount limits
- Check for reasonable payment ranges

## Security Auditing

### Code Review Checklist

When reviewing NASPIP implementations, ensure:

- [ ] Cryptographically secure random number generation
- [ ] Proper key management and storage
- [ ] Input validation and sanitization
- [ ] Secure error handling
- [ ] No sensitive data in logs
- [ ] Proper signature verification
- [ ] Expiration time validation
- [ ] Unique identifier generation

### Security Testing

#### Automated Testing

```javascript
describe("NASPIP Security", () => {
  test("should reject tampered data", async () => {
    const token = await createValidToken();
    const tamperedToken = token.replace("100.00", "1000.00");

    await expect(verifyToken(tamperedToken)).rejects.toThrow();
  });

  test("should reject expired tokens", async () => {
    const expiredToken = await createExpiredToken();

    await expect(verifyToken(expiredToken)).rejects.toThrow();
  });

  test("should reject invalid signatures", async () => {
    const invalidToken = "naspip;fluxis.us;fluxis.qr.dyn.1;v4.public.invalid";

    await expect(verifyToken(invalidToken)).rejects.toThrow();
  });
});
```

#### Penetration Testing

- Test for signature bypass vulnerabilities
- Attempt replay attacks
- Test key management security
- Validate input sanitization
- Test error handling for information disclosure

## Compliance and Standards

### Cryptographic Standards

- **Ed25519**: RFC 8032
- **SHA-256**: FIPS 180-4
- **Random Number Generation**: NIST SP 800-90A

### Security Frameworks

- **OWASP Top 10**: Addresses common web application vulnerabilities
- **NIST Cybersecurity Framework**: Risk management approach
- **ISO 27001**: Information security management

## Incident Response

### Security Incident Types

1. **Key Compromise**: Private key exposure
2. **Signature Bypass**: Circumvention of signature verification
3. **Replay Attack**: Successful reuse of payment instructions
4. **Implementation Vulnerability**: Bugs in cryptographic operations

### Response Procedures

1. **Immediate Actions**:

   - Revoke compromised keys
   - Generate new key pairs
   - Update public key registries
   - Notify affected parties

2. **Investigation**:

   - Analyze attack vectors
   - Review logs and audit trails
   - Identify root causes
   - Assess impact scope

3. **Recovery**:
   - Implement security patches
   - Update security procedures
   - Conduct security training
   - Monitor for similar attacks

## Future Security Considerations

### Post-Quantum Cryptography

As quantum computing advances, NASPIP may need to transition to quantum-resistant algorithms:

- **Lattice-based cryptography**: NTRU, LWE
- **Hash-based signatures**: SPHINCS+
- **Code-based cryptography**: McEliece

### Advanced Security Features

- **Multi-signature support**: Require multiple signatures for high-value payments
- **Threshold signatures**: Distributed key generation and signing
- **Zero-knowledge proofs**: Privacy-preserving payment verification
- **Hardware security**: TPM/HSM integration

## Resources

- [Protocol Specification](/docs/key-concepts/naspip/protocol-specification)
- [Implementation Guide](/docs/key-concepts/naspip/implementation-guide)
- [OWASP Cryptographic Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html)
- [NIST Cryptographic Standards](https://www.nist.gov/cryptography)
- [RFC 8032 - Ed25519](https://tools.ietf.org/html/rfc8032)
