# Mypinpad Auth & Transaction Security Flow This document details the proposed production-grade security flow for the Mypinpad Host emulation. ## 1. OAuth2 Token Generation (POST /api/v1/oauth/token) When a request is received with `client_id` and `client_secret`: 1. **Host Identification**: - Search the `mypinpad_hosts` table for the provided `client_id`. - **Scenario A (New Client)**: If not found, automatically create a new Host entry with the provided `client_id`, `client_secret`, and a default name (e.g., "Auto-Registered Host"). - **Scenario B (Existing Client)**: If found, verify that the provided `client_secret` matches the one stored in the database. If it doesn't match, return `401 Unauthorized`. 2. **Token Issuance**: - Generate a cryptographically secure random string for the `access_token`. - Set an expiration timestamp (e.g., 3600 seconds from now). - **Cleanup**: Delete any previously existing tokens in `mypinpad_tokens` for this specific `host_id` (enforcing the "One Token per Client" rule). - **Persistence**: Save the new token linked to the `host_id`. 3. **Response**: - Return the `access_token`, `token_type` ("Bearer"), and `expires_in` seconds. --- ## 2. Secure Transaction Processing (POST /api/mypinpad/transactions) When a request is received with a `Authorization: Bearer ` header: 1. **Authentication (The Plug)**: - Extract the Bearer token from the header. - Query `mypinpad_tokens` to find a record where `access_token == token` AND `expires_at > now`. - If found: Retrieve the associated `host_id` and store it in the connection context (`conn.assigns.mypinpad_host_id`). - If not found or expired: Return `401 Unauthorized` and halt the request. 2. **Authorization & Lockdown**: - The controller receives the transaction payload. - **Identity Enforcement**: The system ignores any identity claims inside the JSON payload and strictly uses the `host_id` retrieved from the database token in Step 1. - **Persistence**: The transaction is saved in the `mypinpad_transactions` table with the mandatory `host_id` foreign key. 3. **Cross-Client Prevention**: - Because the `host_id` is derived directly from the validated token, Client A can NEVER process a transaction as Client B unless they possess Client B's secret token. - If Client A attempts to use Client B's token, the transaction will be recorded under Client B's account, preventing Client A from "poisoning" their own transaction history with invalid data or spoofing their account. --- ## 3. Database Schema Requirements To support this flow, the following tables must be maintained: - **mypinpad_hosts**: `id`, `client_id` (unique), `client_secret`, `name`. - **mypinpad_tokens**: `id`, `access_token` (unique), `expires_at`, `host_id` (belongs_to host). - **mypinpad_transactions**: `id`, `transaction_id` (unique), `payload`, `response`, `status`, `host_id` (belongs_to host).