Create idempotent confirmation token flows: single-use semantics, replay defense, and…
- User
Create idempotent confirmation token flows: single-use semantics, replay defense, and expiries.
Assistant
Create idempotent confirmation token flows: single-use semantics, replay defense, and expiries.
The user wants to create idempotent confirmation token flows. The core requirements are:
I need to design a system architecture for this, likely involving a database schema and logic flow. I should probably use a standard scenario like "Email Verification" or "Password Reset" as the base for the explanation.
Key Components:
Design Options:
Database Schema Design:
token_id (PK)user_id (FK)token_hash (We shouldn't store the raw token if it's sensitive like a password reset, but for email confirmation, it's less critical. Let's assume best practice: store hash or use a "selector/verifier" split pattern).action_type (e.g., 'confirm_email', 'reset_password')expires_atused_at (NULLABLE) - This makes it idempotent. If used_at is set, we know it's done.The Logic Flow (Step-by-Step):
Creation:
Consumption (The Idempotent Part):
UPDATE ... SET used_at = NOW()).user.email_verified == true).Refining "Idempotency" vs "Single-Use":
Strictly speaking, f(x) = y. If I run f(x) again, I expect y.
If x is a single-use token:
Run 1: Token consumed -> Action performed -> Result: Success.
Run 2: Token already consumed -> Action cannot be performed via this token -> Result: "Token Invalid" or "Already Done".
To make it idempotent, the second run should simply say "The goal you wanted to achieve (e.g., verifying the email) is already achieved," rather than "You provided an invalid input."
Structure of the Answer:
Drafting the Content:
token = selector (unhashed, searchable) + verifier (hashed, validates possession).Let's refine the Idempotency aspect.
If I use a token, it marks the user as "Verified".
If I click the link again, the system sees used_at is set.
Does it return 400 Bad Request? Or 200 OK "Already Verified"?
For a truly idempotent flow, it should return 200 OK "Already Verified".
This protects the UX (user sees "Success") even if the network lagged and they double-clicked.
Code Implementation Language: I'll use TypeScript/Node.js for broad applicability, with SQL concepts.
Steps:
confirmation_tokens table.crypto.randomBytes.Race Condition: Two requests hit the server at the exact same millisecond with the same token.
UPDATE tokens SET used_at = NOW() WHERE token_id = ? AND used_at IS NULL.Plan:
id, selector, hashed_validator, user_id, type, expires_at, used_at.POST /request-confirmation: Generates and sends.POST /confirm: Validates and consumes.Let's write it out.
Self-Correction during drafting: Make sure to distinguish between Idempotency of the Request and Single-Use of the Token.
I will focus on the Selector/Verifier pattern because it mitigates timing attacks and database scraping, which is best practice for auth tokens.
Selector/Verifier details:
Token sent to user: base64url(random_bytes(16) + random_bytes(32)) -> Split into Selector (16) and Verifier (32).
DB stores:
selector (plaintext, unique index) -> allows fast lookup.hashedVerifier (bcrypt/argon2 or even SHA256) -> validates authority.The Flow for Validation:
selector.hashedVerifier against input verifier.expires_at.UPDATE ... SET used_at = NOW() WHERE used_at IS NULL).affected_rows == 0: The token was already used.
-> Now we check Idempotency: Is the User already verified?
-> Yes: Return 200 OK (Idempotent success).
-> No: This is a weird state (Token used, action not done). Return 500 or Error.affected_rows == 1: We "won" the lock.
-> Perform business logic (Verify User).
-> Return 200 OK.This covers all bases: Security, Single-use, Replay defense, Idempotency.
Let's organize the answer clearly.
Here is a robust architectural pattern for implementing this, focusing on the Selector/Verifier split, atomic database locks, and state checks.
To prevent timing attacks and database scraping, never store the raw token in the database.
base64(url_safe(selector) + url_safe(verbatim_verifier))You need a dedicated table for these tokens. Do not overload the user table.
CREATE TABLE confirmation_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL, -- FK to users
type VARCHAR(50) NOT NULL, -- 'email_verify', 'password_reset', 'mfa'
-- Lookup & Security
selector VARCHAR(255) NOT NULL UNIQUE, -- Used to find the row
hashed_verifier VARCHAR(255) NOT NULL, -- Hashed version of the verifier
-- Lifecycle
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
-- Idempotency & Replay Defense
consumed_at TIMESTAMP WITH TIME ZONE DEFAULT NULL -- NULL = Active, Set = Used
);
-- Index for fast lookup
CREATE INDEX idx_confirmation_tokens_selector ON confirmation_tokens(selector);
When a user requests a confirmation (e.g., "Send Verification Email"):
type for this user_id.selector (16 bytes) and verifier (32 bytes).selector and HASH(verifier) into the DB with expires_at = NOW() + TTL.selector and verifier (base64 encoded) and send to the user.This is where Idempotency and Replay Defense happen.
The API endpoint receives the full token string.
// pseudo-code (TypeScript/Node style)
async function confirmAction(rawToken: string, userIdFromContext: string) {
// 1. Decode and Split
const { selector, verifier } = decodeToken(rawToken);
// 2. Find Token by Selector
const tokenRecord = await db.get('SELECT * FROM confirmation_tokens WHERE selector = ?', [selector]);
// --- FAILURE CASES (Security & Validation) ---
if (!tokenRecord) {
// Do not reveal if token exists or not specifically (use generic message)
throw new Error('Invalid or expired token');
}
// Check Expiry
if (new Date() > tokenRecord.expires_at) {
throw new Error('Token has expired');
}
// Check Ownership (Optional depending on flow, but good for security)
if (tokenRecord.user_id !== userIdFromContext) {
throw new Error('Security violation');
}
// Verify the Hash (Prevents DB leak forgery)
const isValid = await bcrypt.compare(verifier, tokenRecord.hashed_verifier);
if (!isValid) {
throw new Error('Invalid token');
}
// --- IDEMPOTENCY & SINGLE-USE LOGIC ---
// 3. ATOMIC UPDATE (The "Compare-And-Swap")
// This is the critical replay defense.
// We attempt to update the row ONLY IF consumed_at is currently NULL.
const updateResult = await db.query(
`UPDATE confirmation_tokens
SET consumed_at = NOW()
WHERE id = ? AND consumed_at IS NULL`,
[tokenRecord.id]
);
// 4. Handle the Result
if (updateResult.rowsAffected === 1) {
// --- SUCCESS: We secured the lock. Perform the action. ---
// Perform the side effect (verify email, reset password, etc.)
// Ideally, wrap this and the UPDATE above in a DB Transaction.
await performBusinessLogic(tokenRecord.user_id, tokenRecord.type);
return { status: 'SUCCESS', message: 'Action completed' };
} else {
// --- IDEMPOTENCY: rowsAffected is 0 ---
// This means the token was ALREADY used (consumed_at was NOT NULL).
// Check if the token was used for the *same* purpose successfully.
// If the user is just clicking the link again, we act idempotently.
// Check actual application state (e.g., is email already verified?)
const user = await getUser(tokenRecord.user_id);
if (user.email_verified) {
// Return success to the user (it's already done)
return { status: 'SUCCESS', message: 'Email already verified' };
} else {
// Token is marked used, but the action didn't persist (System Error/Partial Failure)
// This is a rare edge case. Return an error requiring support or new token.
throw new Error('Token already used, but action pending. Please contact support.');
}
}
}
By using the UPDATE ... WHERE consumed_at IS NULL query, we rely on the database's ACID properties.
consumed_at. The other will see rowsAffected = 0.consumed_at. Logic runs. Success.WHERE consumed_at IS NULL clause fails. The code proceeds to the Idempotency block.
expires_at column is checked strictly.DELETE FROM confirmation_tokens WHERE expires_at < NOW(). This keeps the table clean and prevents an attacker from browsing old links years later.| Feature | Implementation | Why? |
|---|---|---|
| Storage | hashed_verifier | If DB is leaked, attackers cannot forge tokens, only replay them (if unexpired). |
| Lookup | selector (Index) | Prevents timing attacks (looking up by hash takes variable time; looking up by index is constant). |
| Atomicity | UPDATE ... IS NULL | Handles race conditions where a user double-clicks a button. |
| Idempotency | Check target state | If token is used but user asks "Am I verified?", return Success, not Error. |
| Cleanup | Hard Delete | Reduces surface area for replay attacks. |