Package: maatify/php-rate-limiter
Namespace: Maatify\RateLimiter
Status: LOCKED — Behavioral Contract
Scope: Login, OTP, API Heavy Endpoints
This document defines the deterministic decision rules used by the Rate Limiter. It is a behavioral contract, not explanatory documentation.
Any implementation, policy, or test MUST comply with this matrix exactly.
IP— Client IP address (IPv4 or IPv6 prefix-aware)UA— Normalized User-Agent (major version only)DeviceFP— Device Fingerprint (passive / client / session)DeviceConfidence—{LOW, MEDIUM, HIGH}derived perDEVICE_FINGERPRINT.mdAccountID— Account identifier (blind index or internal ID)CorrelationID— Optional stable opaque Host-provided subject identity for correlationAction— Logical action (e.g.auth.login,auth.otp,api.heavy)PreviouslyVerifiedForAccount— host-provided boolean proving a prior verified device ↔AccountIDassociation (defaultfalse; seeDEVICE_FINGERPRINT.md§4.3)
ALLOWSOFT_BLOCK— Temporary throttle with Retry-AfterHARD_BLOCK— Active block for a calculated duration
K1 = IP_PREFIXK2 = IP_PREFIX + UAK3 = IP_PREFIX + DeviceFPK4 = AccountIDK5 = AccountID + DeviceFP
For credential-spray correlation only:
correlationSubject = CorrelationID if present, else AccountID if present, else null
present(v) = v !== null && v !== ''
The Host owns the stable opaque CorrelationID. "0" is a present value and "" is absence (#185, F-185-04). When neither value is present (each is null or ""), the package does not create a spray observation. The package derives a domain-separated keyed-HMAC member from the subject before calling CorrelationStoreInterface; raw account, username, email, or correlation values are never stored as members. AccountID remains the enforcement identity for K4/K5.
A request is considered from a trusted session device only if:
- A Level 3 session-bound device identifier is present (per
DEVICE_FINGERPRINT.md), and - It is bound to the same
AccountID, and - It matches the server’s stored association for that account.
No other “trust” signal is allowed for the trusted-session definition.
A device is known for an account (isKnownForAccount) if either:
- It is a trusted session device for that account (definition above), or
- It is a previously verified device for this account — the host proves a prior
verified association between the device and the
AccountID(PreviouslyVerifiedForAccount = true, host-provided).
isKnownForAccount = isTrustedSession OR isDevicePreviouslyVerifiedForAccount
Rules:
- The host is the only authority for proving a previous verified association.
- The existence of a
K5counter in RateLimiter storage is NOT, by itself, proof that the device was previously verified. DeviceConfidence = HIGHalone is NOT a substitute for “previously verified”.- Full device semantics are owned by
DEVICE_FINGERPRINT.md§4.3.
Evaluation order is strict and non-negotiable:
- Resolve device/account signals (trusted session, previously-verified device, confidence).
- Resolve active HARD_BLOCK state on all relevant keys (
K4/K5/K3/K1/K2). An activeHARD_BLOCKfails fast and terminates evaluation. - Load effective
V2/V1budget state (count + epoch start). Loading is non-enforcing. - Evaluate normal scores / thresholds / correlation (
K4,K5,K3,K1/K2). - On failure, process all score, correlation, and eligible budget updates
(
recordFailureMUST continue even whileBudgetActive). - Apply the OTP Recovery Collision Guard if the exact transition qualifies.
- On
recordFailure, evaluate Anti-Equilibrium escalation using only soft-block events recorded by prior requests, per source scope (§2.5.3). If at least 3 prior actually-issued account-scopedSOFT_BLOCKevents exist within 6 hours, add an Anti-EquilibriumHARD_BLOCK(Account)candidate (K4) at minimum L2. If at least 3 prior actually-issued device-scoped (K5-only)SOFT_BLOCKevents exist within 6 hours for the same account and device, add an Anti-EquilibriumHARD_BLOCKcandidate on that account + device (K5) at minimum L2. Device-scoped events never count as account evidence. The current request MUST NOT count toward either prerequisite. - Resolve the normal, Recovery Guard, and Anti-Equilibrium candidate class.
If any
HARD_BLOCKcandidate exists, the budgetSOFT_BLOCKis ineligible and budget cooldown MUST NOT be acquired. - Otherwise, if
BudgetActiveand the command is eligible, atomically acquire the budget cooldown. If acquired, add the budgetSOFT_BLOCKcandidate. - Aggregate by decision class first:
HARD_BLOCK > SOFT_BLOCK > ALLOW
Then resolve the highest level and longest duration only among candidates in the
winning class.
11. After final aggregation, if and only if the final issued decision is SOFT_BLOCK,
record exactly one Anti-Equilibrium soft event for future requests. A current
request MUST NOT record a soft event and then read that same event to become hard.
The budget is a decision candidate, not a fail-fast gate. An active budget MUST NOT short-circuit stages 4–6. Normative budget behavior is defined in §2.4, §2.5, §3.3.
| Condition | Key | Decision |
|---|---|---|
| Active block on account | K4 | HARD_BLOCK |
| Active block on account+device | K5 | HARD_BLOCK |
| Active block on device | K3 | HARD_BLOCK |
| Active block on IP / IP prefix | K1 | HARD_BLOCK |
Invariant: Safety-valves (ephemeral routing, degraded mode, etc.) MUST NOT bypass this step.
| Scenario | Key | Score Delta | Notes |
|---|---|---|---|
| Failure from same known device | K5 | +2 | Lower risk, not safe |
| Failure from new / unverified device | K4 | +3 | Suspicious |
| Missing device fingerprint | K2 | +4 | Evasion indicator |
| Repeated missing fingerprint (same account) | K4 | +6 | Accelerated escalation |
| IP attempts multiple accounts | K1 | +5 | Credential spray |
The missing-fingerprint rows (and §2.2.1) are reachable only with a custom resolver that returns
no fingerprint; the default resolver (DeviceIdentityResolver) always produces one.
A “Repeated missing fingerprint (same account)” event applies if:
DeviceFPis missing, and- The previous failed login for the same
AccountIDand the same policy flow within the last 30 minutes was also missingDeviceFP.
The marker is policy-scoped: Login history MUST NOT satisfy the OTP rule, and OTP history MUST NOT satisfy the Login rule. API Heavy has no repeated-missing-fingerprint contract and MUST NOT create or read this marker.
A known device (isKnownForAccount) is scored on K5, and K5 is bounded:
| K5 score | Decision on that account + device |
|---|---|
| < 8 | ALLOW |
| 8 – 11 | SOFT_BLOCK (L1) |
| 12 – 15 | HARD_BLOCK (L2) |
| ≥ 16 | HARD_BLOCK (L3+) |
- A level derived from K5 is persisted on the K5 key only, never on K4, for every policy. Levels derived from other keys keep their K4 persistence. The owner's other devices on the same account are not blocked by a K5 level.
- Known-device account allowance (
KnownDeviceAccountAllowancePolicyInterface; Login = 8): while active, every known-device failure consumes one unit of a fingerprint-independent account counter with a fixed 24-hour epoch (KEY_STRATEGY.md§4.6, purposeknown_device_allowance). Every known-device failure beyond the allowance also adds the new-device delta (+3) to K4 and is budget-eligible (§2.4.1). This is a per-failure K4 scoring rule, not an absolute cap on verifier reaches: K4 protection decays and depends on recorded outcomes, and pre-checks reserve nothing. Ephemeral and missing-fingerprint failures keep their existing K4 scoring and do not consume it. - The opt-in is an authentication capability: all authentication prerequisites apply,
API_OVERUSEcannot be combined with it, and an active allowance requires a positivek5_failureand positive monotonic K5 thresholds. Anullallowance disables it. - K5 L1 decisions are actually-issued
SOFT_BLOCKs with device scope: they count toward the device Anti-Equilibrium watcher (§2.5.3), whose escalation is a K5HARD_BLOCKL2 on that device only, not toward the account watcher. - A backend failure while consuming the allowance is a typed backend failure (DEC-015); it is never converted into a normal-mode allowance.
| Account Score | Decision | Block Level |
|---|---|---|
| < 5 | ALLOW | — |
| 5 – 7 | SOFT_BLOCK | L1 |
| 8 – 11 | HARD_BLOCK | L2 |
| ≥ 12 | HARD_BLOCK | L3+ |
A budget exists to stop low-and-slow abuse without enabling remote permanent lockout.
| Condition | Decision |
|---|---|
| ≥ 20 failed login attempts within 24 hours | SOFT_BLOCK (Account) with minimum block level L3 |
- An active login budget is a candidate in the final aggregation (§1, §8) only.
- It MUST NOT hide a stronger decision: K4/K5 score thresholds and correlation
HARD_BLOCKstill apply and win over the budgetSOFT_BLOCK. - Decision class wins before level or duration. A budget
SOFT_BLOCKMUST NOT contribute its level, duration,retryAfter, or persistence to a winningHARD_BLOCKcandidate; it can never upgrade hard-block semantics directly or indirectly. checkOnly()MUST evaluate normal score/correlation state before selecting the final result.recordFailure()MUST continue normal failure scoring, correlation, and budget counting even whileBudgetActive.- The budget MUST NOT stop
processUpdates().
Budget-issued SOFT_BLOCK is not BlockState:
- The budget
SOFT_BLOCKis not stored throughRateLimitStoreInterface::block(). - It does not create a K4 hard block and is not a level-1
BlockStatecooldown marker. - It does not change the semantics of an active hard block.
- Its repetition is governed by the independent budget cooldown state (§2.4.4).
- Normal score / anti-equilibrium
HARD_BLOCKkeeps usingBlockStateas usual.
Login failures are classified, not all scored with K4 + K5 together:
| Classification | Scoring | Budget eligibility |
|---|---|---|
| Known device failure | K5 score delta applies (+2); K4 “new device” delta does NOT apply within the known-device account allowance (§2.2.2) and also applies beyond it | Budget-eligible only after failed_login_count(K5) ≥ 8 within the fixed epoch (known-device micro-cap), or immediately once beyond the account allowance |
| New / unverified device failure | K4 new-device delta applies (+3) | Budget-eligible immediately |
- “Known device” means
isKnownForAccount(§0;DEVICE_FINGERPRINT.md§4.3). - Missing-fingerprint rules (§2.2) remain an independent contract and are neither removed nor weakened by this classification.
Budget counters are counted at K4 (AccountID) and include:
-
Any failed login that increments K4 (new/unverified device, repeated missing fingerprint), and
-
Any failed login without DeviceFP (K2 missing fingerprint), and
-
Any failed login from a known device (K5) after a per-device micro-cap:
- If
failed_login_count(K5) ≥ 8 within 24h, subsequent failures from that sameK5become budget-eligible.
- If
This prevents “same-device equilibrium” from bypassing the budget indefinitely.
To prevent “rolling-window prisoning”, the budget uses a fixed Budget Epoch:
- The epoch starts at the timestamp of the first budget-eligible failure that contributes to the threshold crossing.
- Once the threshold is crossed, the epoch becomes BudgetActive and ends exactly 24h after epoch start.
- Additional failures MUST NOT extend the epoch end time.
- No cooldown, key rotation, or Recovery Collision Guard MAY move
epochStartor extend the epoch end. - The budget counter MAY continue counting for analytics, but must not extend enforcement.
This is a behavioral guarantee: “44 attempts cannot stretch a 24h prison into an infinite prison.”
While BudgetActive, the budget SOFT_BLOCK candidate is permitted only on:
recordFailure(login_protection)— a failed login attempt, andcheckOnly(login_protection)— an unauthenticated attempt/preflight that would have becomeALLOWwere it not for the active budget.
For checkOnly(login_protection), the budget candidate is eligible only when the
normal result is ALLOW. If the normal result is SOFT_BLOCK or HARD_BLOCK, the
budget candidate MUST NOT be attempted and its cooldown MUST NOT be acquired.
For recordFailure(login_protection), the budget candidate may participate after all
normal updates: it may join a normal SOFT_BLOCK in the SOFT_BLOCK class, may be
issued when the normal result is ALLOW, and MUST NOT be attempted when a normal or
recovery HARD_BLOCK exists.
The budget MUST NOT affect:
recordSuccess(login_protection)— a successful login MUST returnALLOWand MUST NOT be blocked by an account budget.
The budget MUST NOT re-issue on a timer.
A budget-issued SOFT_BLOCK(Account) has an enforcement cooldown:
- Login budget cooldown: 60 minutes (
BudgetConfigDTO.cooldown_seconds = 3600).
Cooldown semantics:
- Cooldown belongs to Budget enforcement, not to the budget epoch.
- The cooldown marker represents an actually issued budget
SOFT_BLOCK, not merely the presence ofBudgetActive. It may be acquired only after the normal/recovery candidate is resolved and the budget candidate can participate in the winningSOFT_BLOCKresult. - While
BudgetActive, the first eligible budget issuance outside cooldown MAY produce the budgetSOFT_BLOCK; during cooldown, the budget alone MUST NOT re-issue it. - If cooldown acquisition fails or loses the atomic race, the budget
SOFT_BLOCKis not issued and the normal/recovery candidate is not altered. - During (and after) cooldown, the request still completes normal score/correlation/failure
processing; any normal
HARD_BLOCKstill wins (§8). - Cooldown MUST NOT extend the budget epoch and MUST NOT restart it.
- Cooldown acquisition is atomic (see
KEY_STRATEGY.md§4.5).
Budget-issued retryAfter = remaining/current budget cooldown — not the remaining 24h
epoch. The 24h epoch is the lifetime of the budget state; it is not a client
retry-prevention window.
If a request is from a trusted session device:
- The budget decision MUST be downgraded by one level (e.g., L3 → L2),
- but never below the trusted-session floor level L2 while BudgetActive.
To prevent mathematically planned “low-and-slow” equilibrium:
On the current recordFailure, and before budget cooldown acquisition, read only
Anti-Equilibrium soft events from prior requests for the same AccountID and the same
policy flow. Only account-scoped events are recorded there; device-scoped events have their
own watcher and escalation (§2.5.3).
If ≥ 3 actually-issued SOFT_BLOCK events within 6 hours exist in that prior
history:
- Add
HARD_BLOCK (Account)at minimum level L2 as an Anti-Equilibrium candidate. - The current request MUST NOT count toward the three-event prerequisite.
- This
HARD_BLOCKcandidate makes the budgetSOFT_BLOCKineligible; budget cooldown MUST NOT be acquired.
The Anti-Equilibrium read/escalation operation is separate from recording the current request. It occurs before budget cooldown acquisition so an eligible prior history cannot be bypassed by a budget soft. Login and OTP histories are independent.
After final aggregation, if and only if the final issued decision is SOFT_BLOCK,
record exactly one Anti-Equilibrium event, on the watcher selected by its source scope
(§2.5.3). This event affects future requests only.
The third SOFT_BLOCK remains a SOFT_BLOCK; recording it MUST NOT turn that same
request into HARD_BLOCK. A request whose final decision is ALLOW or HARD_BLOCK
records no Anti-Equilibrium soft event.
Therefore, Anti-Equilibrium has two distinct operations:
READ / ESCALATION:
current failure → read prior soft-event history → may add HARD_BLOCK L2
WRITE / RECORD:
final result is SOFT_BLOCK → record exactly one event for future requests
This is deterministic, testable, and breaks stable decay arithmetic.
Each issued SOFT_BLOCK carries the scopes of its winning SOFT_BLOCK candidates:
- device — the candidate's level comes from K5 alone (known-device score);
- account — every other source (K4 score, budget, flood, Recovery Guard, other keys). This is the conservative default and keeps the §2.5.1 / §2.5.2 behavior.
Recording (§2.5.2) writes exactly one event per issued SOFT_BLOCK, on one watcher:
- the account watcher whenever any winning candidate has account scope, including a
SOFT_BLOCKthat aggregates a K5 level with an account level (the stronger, existing account protection); - the device watcher for the same account and device (
KEY_STRATEGY.md§4.6, purposeanti_equilibrium_device) only when every winning candidate is device-scoped (K5 alone) and the device watcher is eligible; - the account watcher otherwise (for example a device-only
SOFT_BLOCKwithout a durable device identity).
The device watcher exists only for a policy that the account watcher also covers (a
budgeted policy), that is not API_OVERUSE, and that defines K5 thresholds; otherwise it
is never read, written, or escalated, even if events are stored under the same policy name.
With a single write there is no two-key partial publication; an operational exception
around that one write keeps the existing store semantics (DEC-015).
Escalation (§2.5.1) reads both watchers on recordFailure: three prior account events add
HARD_BLOCK (Account) L2 on K4 as before; three prior device events add HARD_BLOCK L2 on
that account + device (K5) only. Both watchers follow outer-secret rotation (current is
writable, previous is read-only); the device watcher also follows the previous fingerprint
generation.
OTP actions are stricter than password attempts.
| Scenario | Key | Score Delta |
|---|---|---|
| OTP failure from same device | K5 | +4 |
| OTP failure from new device | K4 | +5 |
| OTP failure without device fingerprint | K2 | +6 |
| Repeated OTP failures without fingerprint | K4 | +8 |
Applies if:
DeviceFPis missing, and- The previous OTP failure for the same
AccountIDand the OTP policy flow within the last 30 minutes was also missingDeviceFP.
OTP uses the §2.2.2 contract with the OTP deltas: K5 thresholds 8 / 12 / 16 (L1 at the
2nd known-device failure, L2 at the 3rd, L3 at the 4th), K5 levels persisted on K5 only,
and a known-device account allowance of 2 per fixed 24-hour epoch, beyond which the
OTP new-device delta (+5) also applies to K4. OTP budget eligibility (§3.3) is unchanged.
| Score | Decision | Block Level |
|---|---|---|
| < 4 | ALLOW | — |
| 4 – 6 | SOFT_BLOCK | L1 |
| 7 – 9 | HARD_BLOCK | L2 |
| ≥ 10 | HARD_BLOCK | L3+ |
| Condition | Decision |
|---|---|
| ≥ 10 OTP failures within 24 hours | SOFT_BLOCK (Account) with minimum block level L4 |
- The same non-short-circuit rules as §2.4.0 apply to the OTP budget.
- The OTP budget MUST NOT prevent
recordFailure(otp_protection)from continuing normal OTP failure scoring, correlation, and budget counting. - Decision class wins before level or duration; the OTP budget
SOFT_BLOCKcannot contribute properties to a winningHARD_BLOCKcandidate. - The OTP budget-issued
SOFT_BLOCKis not stored as hard-block persistence and is not a level-1BlockStatecooldown marker.
- Every OTP failure is budget-eligible at K4; there is no Login-style K5 micro-cap for OTP.
- OTP budget uses the same fixed Budget Epoch rules as §2.4.2
(
epochStartfixed inside the 24h epoch; failures never extend the epoch end).
While OTP BudgetActive, the budget SOFT_BLOCK candidate is permitted only on:
recordFailure(otp_protection).
Budget enforcement is forbidden on:
checkOnly(otp_protection), andrecordSuccess(otp_protection)— a successful OTP MUST returnALLOWand MUST NOT be blocked by an account budget.
- OTP budget cooldown: 120 minutes (
BudgetConfigDTO.cooldown_seconds = 7200). - Cooldown semantics are identical to §2.4.4 (enforcement-owned; no epoch extension or
restart; budget
retryAfter= remaining budget cooldown, not the epoch remainder).
Trusted session devices downgrade by one level, never below the trusted-session floor level L3 while BudgetActive.
To mitigate “preload 9 then wait for victim” attacks:
If the effective OTP budget count before failure = 9 within the epoch, and the failing request is from:
- a device with
DeviceConfidence = HIGH(session-bound device), OR - a device previously verified for this
AccountID(isKnownForAccount, §0),
THEN the atomic budget increment returns count = 10, but:
- BudgetActive MUST NOT start on this request.
- Instead, apply
SOFT_BLOCK (L2)once; the count stays10inside the same epoch. - The next failure (
count = 11) activatesBudgetActivenormally.
Decision rule — no persistent Recovery-Guard flag is needed because the trigger keys off the atomic returned budget count:
returned count == threshold (10) AND qualifying recovery device
Because it keys off the atomic increment result, exactly one request is guarded even under concurrency (concurrent initializations cannot duplicate the guard).
Duration:
- The Recovery Guard
SOFT_BLOCK (L2)uses the PenaltyLadder L2 duration (60 s), NOT the OTP budget cooldown (BudgetActive has not started yet). - The Recovery Guard is a normal
SOFT_BLOCKcandidate and MUST NOT acquire the budget cooldown. If a normal or Anti-EquilibriumHARD_BLOCKis also present,HARD_BLOCKwins without budget cooldown acquisition; otherwise it aggregates with otherSOFT_BLOCKcandidates by the class-local rule in §8.
| Condition | Key | Decision / maximum level |
|---|---|---|
| Minor limit exceeded | K2 | SOFT_BLOCK / L1 |
| Moderate limit exceeded | K3 | HARD_BLOCK / L2 |
| Severe limit exceeded | K1 | HARD_BLOCK / L3 |
API Heavy persists each scope's own enforcement candidate. It does not create
K4 or K5 thresholds, candidates, or blocks, and active current or previous K4
or K5 blocks do not block an API Heavy request. It also does not create or read
the account-only repeated-missing-fingerprint auxiliary marker. A LOW-confidence moderate K3
signal remains HARD_BLOCK L2 but is persisted against K2, never K3.
Interim posture (DEC-027, which superseded DEC-019 on 2026-10-20): for every policy that does not opt into the admission reservation, and for an opted policy while its fleet fence is closed, the correlation rules in this section remain the shipped behavior under the Owner-approved interim Security-first posture, recorded in DEC-027. That posture is not a fix: issues #97 (LOW passive-UA), #100 (K2 shared-NAT churn), and #106 (K1 spray on shared NAT) remain OPEN for those policies, and legitimate shared-NAT users can still be denied. A policy that opts in follows §12 and DEC-022 instead. This note changes no rule, threshold, or table.
Many rules use thresholds. To prevent stable N-1 bypass:
- If a correlation metric reaches (threshold − 1) within a window,
- set a WATCH flag for the same scope (key) with TTL 30 minutes.
- If the same WATCH flag is observed twice within its TTL,
- upgrade the decision to the same action as if the threshold were met.
Credential-spray observation is performed by checkOnly() for authentication policies only. recordFailure() and recordSuccess() do not repeat that observation for the same command lifecycle; checkOnly() therefore is not globally read-only because bounded correlation state may be updated during the pre-check.
When previousKeySecret is configured, spray observation requires the additive
CorrelationRotationStoreInterface capability. The existing CorrelationStoreInterface
remains the source-compatible base contract for the no-rotation path. Missing rotation
capability, corrupt previous state, or a previous state without a valid TTL is an explicit
failure through the normal engine failure semantics; it must not become a current-only
reset.
All distinct correlation observations use the additive bounded capability. The no-rotation
path requires BoundedCorrelationStoreInterface; a current/previous observation requires
BoundedCorrelationRotationStoreInterface. BoundedDistinctResultDTO reports the logical
count and whether the member was accepted. Duplicates are accepted without mutation, while
new members at the cap are rejected atomically without set growth. Bounded scopes use
purpose/version/environment-separated keyed-HMAC references; raw account, IP, correlation,
and fingerprint values never cross the store boundary. Missing capabilities and corrupt
bounded state fail explicitly rather than falling back to unbounded operations.
IPv6 hierarchy activation is a separate scope-activation primitive and does not
inherit the N-1 WATCH rule: /48 requires 2/2 participating /64s, /40
requires 4/4 active /48s, and /32 requires 8/8 active /40s. These
thresholds produce no decision, level, retry-after, score, or block persistence.
Distributed-account device observations additionally require the additive
BoundedCorrelationSnapshotStoreInterface (or its rotation companion). The snapshot returns
the complete bounded logical member set, fixed expiry, and separate accepted/added flags;
the pipeline validates count, uniqueness, membership, expiry, and flag consistency before
using it for enforcement. Snapshot members are canonical opaque K5 keys and are applied
directly to the involved-device block candidates.
This is deterministic and testable (no randomness), and blocks “hover forever at N-1”.
| Rule | Condition | Decision |
|---|---|---|
| IP attempts many correlation subjects | distinct(correlationSubject) ≥ 5 within 10 minutes |
HARD_BLOCK (IP) |
Advisory Constraint: IP-only K1 blocks and K1 score-derived candidates are advisory for trusted session devices under Login and OTP. The K1 state remains stored and active for untrusted traffic; K2/K3/K4/K5 remain authoritative. IPv6 macro scopes are detection-only and never create an IP block state of their own.
During key-secret rotation, the previous K1 spray set is read-only. The current K1
uses current-secret HMAC members, and a current bridge namespace
credential_spray:bridge:{currentK1} carries only subjects absent from the previous
set. While the previous window is active, the distinct count is previous cardinality
plus bridge cardinality; the differently-keyed current and previous sets are never
unioned or added directly. The current and bridge windows have fixed TTLs, with the
bridge capped by the previous remaining TTL, and the previous set and WATCH flag are
never written or extended.
The spray distinct set is capped at five members in its 600-second window. This cap is a storage-safety invariant as well as an enforcement threshold; rejected new subjects do not create additional members or keys.
For IPv6, each active /48, /40, or /32 detection scope has an independent
bounded spray set with the same 5/5 threshold and 600-second window. Every
macro observation is completed before a candidate is selected, while the only
persisted enforcement key remains the current canonical /64 K1. A trusted
session treats macro K1 spray as advisory exactly as base K1 spray: state is
stored for untrusted traffic, but the trusted request is not rejected solely by
that macro signal. Macro scopes never create RateLimitStore score or block state.
| Rule | Condition | Decision |
|---|---|---|
| Account accessed from many devices | distinct(DeviceFP) ≥ 4 within 10 minutes |
HARD_BLOCK (each involved K5) |
IMPORTANT:
- The AccountID MUST NOT be hard-blocked immediately by this rule.
- Only the involved devices for that account are blocked (apply blocks on each K5).
- Account-wide blocking requires repeated occurrences (see 5.2.1).
If the condition in 5.2 occurs ≥ 3 times within 24 hours for the same AccountID, then:
- Apply HARD_BLOCK (Account) at minimum level L4.
This is the only correlation-based path that may hard-block the account.
Operational contract:
- The device window is a 600-second fixed-TTL bounded set capped at four logical K5 members.
- Three members create a 30-minute account watch marker. The second qualifying three-member observation is equivalent to the threshold; the fourth member meets it directly.
first qualification → all involved snapshot K5s: whenoccurrenceSnapshot.added = true, persist every member in the complete bounded snapshot at HARD L2.later same-window qualification → current non-ephemeral K5 only: whenoccurrenceSnapshot.added = false, do not refresh historical K5 TTLs; persist only the current non-ephemeral K5. An Ephemeral request creates no new K5 persistence. The distributed set remains capped at four members.- These involved-device decisions do not block K4 on the first or second occurrence.
- A qualifying device snapshot contributes exactly one account-only occurrence member derived from that snapshot's fixed expiry. The occurrence window is 86400 seconds and is capped at three members; rejected overflow does not create a fourth member.
- Exactly the third occurrence adds HARD_BLOCK K4 at L4 for 1800 seconds. There is no K4 escalation at occurrence N-1.
- Login and OTP
checkOnly()are the only observation path. API Heavy, missing account or fingerprint, and missing real K4/K5 do not observe this rule or require its capability. - During rotation, the previous device set is read-only, new logical members belong to the current generation and bridge, and the bridge expiry is bounded by the previous expiry. Outer-only, fingerprint-only, and both-rotated inputs use one coordinated pair; no Cartesian generation pairing is allowed. Fingerprint-only rotation has no prior occurrence namespace.
| Rule | Condition | Decision |
|---|---|---|
| Rapid fingerprint changes | ≥ 3 distinct DeviceFP on one K2 (IP prefix + normalized UA) within 600 s, or a second observation of 2 distinct DeviceFP within 1,800 s |
HARD_BLOCK L2 on K2 (IP + UA), 60 s |
| Same fingerprint across many IPs | distinct(IP) ≥ 6 within 10 minutes |
HARD_BLOCK (DeviceFP) |
Confidence Constraint (Anti-Passive Poisoning):
HARD_BLOCK(DeviceFP) in 5.3 is allowed only if:
DeviceConfidence ≥ MEDIUM(client-assisted or session-bound), AND- the dilution is confirmed in a second window (two consecutive 10-minute windows).
If DeviceConfidence = LOW (passive-only), the decision MUST downgrade to:
HARD_BLOCK (IP + UA)(K2), not DeviceFP.
Churn uses a bounded 600-second distinct set capped at three members. The third logical member produces a K2 hard-block candidate, and the second qualifying N-1 WATCH observation also produces the same candidate. During current/previous generation rotation, the previous set is read-only and a current-secret bridge is used with its TTL capped by the previous remaining TTL.
Active IPv6 macro scopes observe churn using an opaque scope-plus-normalized-UA
anchor and current/previous fingerprint members. Their 3/3 threshold and
2/3 WATCH behavior are independent per macro scope, but enforcement persists
only the current canonical /64 + UA K2. Outer-only, fingerprint-only, and
both-rotated requests use the coordinated bounded-generation model without
Cartesian history.
Fingerprint dilution uses a separate bounded 600-second set capped at six IP-scope members. The fifth member creates a 30-minute WATCH; a second qualifying WATCH or the sixth member meets the threshold. LOW confidence targets K2 directly. MEDIUM/HIGH confidence requires a confirmation observation in a second 10-minute window before K3 enforcement. Ephemeral overflow does not create or update per-fingerprint dilution state or confirmation, but the bounded churn signal remains active.
| Rule | Condition | Decision |
|---|---|---|
| Excessive new devices per account | ≥ 6 new DeviceFP within 15 minutes |
SOFT_BLOCK (Account) |
| Continued flood after soft block | Same window | HARD_BLOCK (admitted new K5 only) |
New DeviceFP creation MUST be capped to prevent storage exhaustion.
Flood-stage state is policy-scoped. A Login stage MUST NOT make the first qualifying OTP flood hard, and an OTP stage MUST NOT make the first qualifying Login flood hard. The stage uses current-generation writes and may read one active previous outer-key generation.
Invariant: Ephemeral routing MUST NOT erase active blocks (see DEVICE_FINGERPRINT.md).
Device-cap observations use a 900-second bounded contract: at most 10 distinct account members and 50 distinct IP-scope members. The pipeline performs the observation once using the real current/previous generation tuple, routes only rejected new members to ephemeral, and never creates a fake K3/K5 key. Flood evaluation begins at the sixth logical account member even when that member is admitted; a rejected overflow remains eligible for the active flood HARD decision but cannot create or persist new K5 score/block state. When a distributed- account HARD candidate and the flood SOFT candidate coexist, the HARD candidate wins while the flood state still advances. A distributed overflow does not admit a new K5 member.
| Block Level | Duration |
|---|---|
| L1 | 15 seconds |
| L2 | 60 seconds |
| L3 | 5 minutes |
| L4 | 30 minutes |
| L5 | 6 hours |
| L6 | 24 hours |
Each escalation increases the level. Levels decay slower as severity increases.
| Scope | Base Decay (whole intervals since the last write) |
|---|---|
| Account score | −1 per full 10 minutes |
| Device score | −1 per full 5 minutes |
| IP score | −1 per full 3 minutes |
How decay is applied (intended behavior, #121, #183). Decay counts whole intervals since
the score's last write: every write to a score (updatedAt) restarts its interval, and any
remainder is dropped. Decay therefore happens during idle periods; steady traffic on a key at
a spacing shorter than its interval does not decay it. Example (K1, IP, 180-second interval):
six writes at t = 0 leave an effective score of 4 at t = 500; six writes at t = 0, 100, …, 500
leave 6. A decay at a true rate (updatedAt += n × interval) is a post-1.0 roadmap candidate
with its own decision record.
- After reaching L2 or higher, decay rate is halved
- The multiple-block-cycle pause is a fixed 600-second pause after the second retained real hard-block cycle. Its full contract is defined below.
- Budgets (Section 2.4, 3.3) are fixed 24h epochs and are not affected by score decay
For a score-threshold candidate with no active persisted block, retryAfter
means the time until the score becomes strictly lower than the threshold that
ends the current decision class:
SOFT_BLOCKexits below L1.HARD_BLOCKexits below L2 for both L2 and L3 score levels.- The calculation uses the raw stored score,
updatedAt, the current block level used by decay, the scope-specific package interval, and elapsed partial or complete intervals.DecayCalculatoris the single source of truth. - A LOW-confidence K3 decision downgraded to effective L1 uses L1.
- If multiple score scopes participate in the winning class, the longest applicable decay wait is selected within that class.
An active persisted block always takes precedence and returns its remaining TTL;
it is not combined with the decay wait. Score-derived response retry time does
not change the PenaltyLadder persistence duration. Budget cooldown and all
non-score candidates retain their existing retry semantics.
Hard-block cycle history is scoped to the tuple:
policy + canonical enforcement key type + logical enforcement identity
K1, K2, K3, K4, and K5 therefore maintain independent cycle histories. A cycle
is recorded only when an operation transitions from no active persisted HARD
BLOCK at L2+ to an active persisted HARD BLOCK at L2+. L1 does not count;
escalation, refresh, and reads while the same hard block is active do not create
another cycle. A block with expiresAt === now is expired and does not prevent
a new cycle.
The rolling cycle window is 21,600 seconds (six hours), and the timestamp at
exactly now - 21600 remains in the window. When a new cycle makes the retained
count reach two, the store starts one fixed 600-second pause when no pause is
active. The pause interval is half-open, [pauseStartedAt, pauseUntil), so
decay resumes at exact pauseUntil. Refreshes and escalations do not renew the
pause; a real cycle during an active pause is retained but does not extend it.
After the pause ends, a later real cycle may start another pause when the
rolling condition still holds.
The pause affects score decay only. It does not change persisted block TTLs, PenaltyLadder durations, budget epochs or cooldowns, correlation/WATCH TTLs, LocalFallback, or circuit-breaker state. Completed pauses remain part of lazy decay accounting for 86,400 seconds, and pause intersections are unioned without double counting. Active persisted-block Retry-After remains authoritative; score-derived Retry-After uses the same effective elapsed arithmetic and adds remaining active pause time.
When multiple rules produce decisions:
HARD_BLOCK > SOFT_BLOCK > ALLOW
- The budget candidate participates in final aggregation only; it MUST NOT short-circuit earlier evaluation stages (§1, §2.4.0, §3.3.0).
- First select the winning decision class. A
HARD_BLOCKfrom normal scoring, anti-equilibrium, recovery, or correlation always wins over a budgetSOFT_BLOCK. - Lower-ranked candidates MUST NOT contribute
blockLevel, duration,retryAfter, persistence, or any other decision property to the winning class.
If multiple blocks apply:
- Among candidates in the winning class only, select the highest block level.
- Among candidates in the winning class only, select the longest duration or
retryAfterapplicable to that class.
Therefore, a budget SOFT_BLOCK can never upgrade a HARD_BLOCK level or duration,
and a lower-ranked SOFT_BLOCK cannot affect a winning HARD_BLOCK's persistence.
Account safety always overrides IP convenience.
Normal HARD L2 / 60s
Budget SOFT L3 / 3600s
Final:
HARD L2 / 60s
No budget cooldown acquired
Normal SOFT L1 / 15s
recordFailure
BudgetActive
Cooldown acquired
Final:
SOFT L3 / 3600s
Normal SOFT L1
checkOnly(login)
BudgetActive
Final:
SOFT L1
Budget not attempted
No budget cooldown acquired
Normal ALLOW
checkOnly(login)
BudgetActive
Cooldown acquired
Final:
Budget SOFT L3 / 3600s
Normal ALLOW
recordFailure(otp)
Recovery transition count 9 → 10
qualifying recovery device
Final:
SOFT L2 / 60s
No budget cooldown
BudgetActive suppressed for this request
Three prior actually-issued SOFT_BLOCK events exist within 6h.
Next recordFailure:
Normal = ALLOW
BudgetActive = true
Anti-Equilibrium candidate:
HARD L2
Final:
HARD L2
Budget not attempted
No budget cooldown acquired
No new Anti-Equilibrium soft event recorded
Three prior actually-issued SOFT_BLOCK events exist within 6h.
Recovery Guard = SOFT L2
Anti-Equilibrium = HARD minimum L2
Final:
HARD L2
No budget cooldown acquired
No new Anti-Equilibrium soft event recorded
| Context | Failure Mode |
|---|---|
| Login / OTP | FAIL_CLOSED |
| API Heavy | FAIL_OPEN |
(See FAILURE_SEMANTICS.md for authoritative rules.)
- No decision is based on a single signal
- Remote permanent account lockout via budget-only rules is impossible
- Budget epochs cannot be extended (“no renewable 24h prisons”)
- An active budget never hides a stronger score/correlation
HARD_BLOCK - Budget
SOFT_BLOCKnever uses hard-block persistence (RateLimitStoreInterface::block()) - Budget cooldown never extends or restarts the fixed budget epoch
- Same-device equilibrium cannot bypass budgets indefinitely
- Device rotation does not reset account memory
- K4 budget / K5 micro-cap counters are never merged with
max(v1.count, v2.count)across key rotation (KEY_STRATEGY.md§4.3.1) - IP-only blocking is never final (a source capacity refusal of a policy that opts into the
admission reservation is a non-persisted capacity bound, not a block: §12,
KEY_STRATEGY.md§2, DEC-022) - Device awareness is mandatory
- Progressive escalation with persistence
- Deterministic and atomic behavior
- Fully testable and auditable
These limits are intended behavior approved by the Owner (#183, 2026-11-03) on the evidence of #181. They name what the decision model does not protect.
- Collective harm behind shared NAT (policies that do not opt into admission). K1 and K2
are shared-scope keys (IP prefix; IP prefix + normalized UA). Unrelated clients behind one
NAT share them, so one client's failures, churn or credential spray can block the others
(#100, #106). This is the DEC-027 posture (DEC-019 carried verbatim). The supported
alternative is the admission reservation (the active decisions DEC-022, DEC-023, DEC-024, DEC-026, DEC-033, DEC-034 and DEC-035, §12), where K1 credential spray is
not evaluated and is replaced by the source capacity
U_srcand the net failure capF(DEC-022). - Trusted sessions on several accounts (policies that do not opt into admission). The
known-device bound (DEC-026) holds per account: at most 3 verifier reaches per account in
pre+outin the measured stream (12 accounts). Across accounts it is weaker by design: an attacker holding correctly bound trusted sessions on 12 accounts and rotating 20 browser majors reached the verifier 36 times in 200 attempts (TMUA), against 2 in 200 with one browser major (TMSd) (#120, measured onmainin #181). For policies that opt into admission, the declared cost is TMSd 40 in 200 (DEC-022). - What is not protected. The library bounds attempts; it does not authenticate. No limit here lets a request pass verification on an account without that account's proof: every reach counted above is a verifier attempt that the Host still verifies.
This document is authoritative. Any deviation requires a version bump and changelog entry.
For opted-in Login and OTP policies, K4 score state and punishment evidence
form one generation-bound lifecycle. A K4 mutation returns the generation and
score expiry atomically; a qualifying L2+ punishment publishes the block and
evidence in one backend atomic primitive. Evidence is valid only for the
selected current/previous score generation and exact score expiry, and active
K4 blocks suppress it for checkOnly, recordFailure, and recordSuccess.
The public checkOnly ALLOW may expose metadata. Claiming does not consume
punishment satisfaction or evidence; it consumes only an independent
current-generation application handoff marker, so replay returns false. Current
is writable, previous is read-only, and a newer mutation
invalidates older evidence. Generation conflicts on the K4 score mutation retry at
most three times; exhaustion, before any K4 or K5 write of the request, is an
explicit transient HARD failure with RateLimitConcurrencyException provenance
(unchanged). The publication of the L2+ block makes at most four calls and three
reads and never throws after the request's K4 and K5 writes (DEC-029): when it is
still not applied the decision of the written state is returned with the cause
k4_publication_deferred and the block is left to the next successful publisher.
Active since 2026-10-20 for the policies that opt in: the official variant
LoginProtectionAdmissionPolicy (name login_protection, budget group login) chosen explicitly by
the Host, and custom policies that declare the capability. No default preset opts in. The builder
constructs the admission runtime with the package constants (DEC-035) when a registered policy
declares the capability. The figures recorded in DEC-034 (for example the co-located office replay, legitimate refusals 26/61 and capped attacker reach 40 under sliding windows, against 21/61 and 72 under the fixed windows of DEC-025) are measured trade-offs of registered replays that the Owner accepted (#220). They are not production guarantees: the bounds a deployment gets are the package constants, and its own traffic can measure differently. For such a policy, while its fleet fence is open, the evaluation order of
§1 gains one stage:
- identity resolution, then the lane (a verified credential selects the proven lane
P, anything else the unproven laneU; a closed fleet fence means no admission at all and the policy runs the path of a policy that did not opt in); - the pipeline decides
ALLOWor a block with the lane as a parameter (penalties read first); - admission, only on an allowed
checkOnly: all-or-nothing reservation of the lane's scopes. A refusal is a non-persistedSOFT_BLOCK(source_capacity,source_failure_cap,account_bucket,proof_capacity,new_device_cap,source_proof_failure_cap); - outcomes (
recordFailure/recordSuccess) claim the permit, then score once. OnUa failure enters the source's net failure set and a success leaves it and refunds the account bucket; onPa success refunds the proof counters and a failure enters the cross-account failure set (D8), which a success never reduces. An outcome without a valid claim scores nothing. An admission whose outcome never arrives changes no bound: the Host that drops outcomes is held only by the bounds of apreHost (DEC-023 A-2, a Host duty; the library does not compensate).
Changes of meaning for opted policies, and only for them:
- K1 / K2 / K3 collective penalties are not written. K2 stays an observation: its score is
written, including the missing-fingerprint deltas; K2 churn and LOW dilution are not observed on
this path (DEC-022 Decision 2 as amended at activation). On
Pthe K1/K2/K3 blocks are not read and no K1/K2/K3 candidate is formed; onUblocks written before are read until they expire. - Observations of a refused pre-check. A pre-check refused by the admission stage keeps the observations the pipeline wrote before that stage; the refusal itself writes no admission state, no score, budget, watcher or cycle.
- Allowance and device watcher by family. The known-device allowance counter, K5 device state,
micro-cap and device Anti-Equilibrium watcher are kept per lane (
known_device_allowance_p,K5p,k5p,anti_equilibrium_device_ponP; the unsuffixed state onU). - A known device on
Uis bounded by the account bucket only. No account-scoped candidate persists onU; the known-device allowance and K4 overflow enforce nothing there (declared cost of DEC-034 5.1 and DEC-026). - K4P. The account key on
Pis a separate key from K4 (rule A: account-wide, not cleared at a password change); cycles, pauses and DEC-007 lifecycles of K4 and K4P are independent. - Source capacity. An IP prefix stays an advisory key for identity; as a source capacity
ceiling for unproven traffic only it may refuse (the amendment of §10 and of
KEY_STRATEGY.md§2 under DEC-022). The source is an IPv4 address or an IPv6/64; a/48holder has 65,536 such sources (the hierarchy isUNPROVEN). - Degraded mode and
FAIL_OPENrun no admission stage (FAILURE_SEMANTICS.md§4.5).