Skip to content

Commit 5d3f82b

Browse files
fix(plugin-auth): a rate limit admits no more than its limit inside one process, and the auth counters count in a registered cache service (#29216)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9BGM7juMNkdWGizy26YiKxj)_ Fixes #29053 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:plugin-auth 的限流计数在同一进程内按键串行,同一个键的更新一次只做一个,每次都读到上一次写下的计数,所以固定窗口限额是多少就只放行多少;按手机号的 OTP 发送记录同样如此。计数器改为通过插件上下文真正提供的内核访问器去拿 `cache` 服务(值注册、工厂注册都能拿到),注册了真正的 cache 就计在 cache 里。 - 为什么改:按 #29053 与维护者裁决(「A+C 同意」):限流必须在并发下守住限额,并且要计在已注册的共享 cache 里(ADR-0069 D2)。原来两条都不成立:同进程内两次更新可以交错,cache 解析走的是插件上下文上并不存在的方法,从来没拿到过 cache。 - 风险与回滚:同一个键的更新会排队(进程内存兜底下是微任务级,远端 cache 下每次要等上一次的读写往返),不同键互不影响。没有 cache 插件时内核自带的 degraded 内存 cache 不当共享库用,计数仍走有界的进程内兜底并照旧告警。跨节点仍没有原子自增(契约在 spec,本 PR 不动)。回滚即撤销本 PR。 - 先看:`packages/plugins/plugin-auth/src/per-key-serial.ts`(串行规则本身)、`packages/plugins/plugin-auth/src/kernel-cache.ts`(cache 解析和 degraded 跳过)、`packages/plugins/plugin-auth/src/rate-limit-storage.ts` 的 `incrementFixedWindow`。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/rate-limit-concurrency.test.ts src/kernel-cache.test.ts`,预期 2 个测试文件、19 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes The rule, for every counter in `@objectstack/plugin-auth` (ADR-0069 D2): inside one process a limit admits no more than its limit however many requests for one key arrive at once, and when a `cache` service is registered the counters count in it. - **Per-key serialisation** (`src/per-key-serial.ts`, new, internal, not re-exported): `serializePerKey(key, task)` runs the updates of one key one at a time, in call order. Other keys run concurrently. A failing update releases the next one, and its error reaches only its own caller. A key has an entry only while an update for it is in flight. - **`incrementFixedWindow`** (`src/rate-limit-storage.ts`) runs its read, compute and write through it. That covers every caller of the one fixed-window counter: better-auth's `rateLimit.customStorage` (`createLazyCacheRateLimitStorage`), the signed-out invitation preview, `cacheSecondaryStorage().increment`, and the subpath's external callers. Its docblock now states the in-process rule and keeps the cross-node caveat. - **`OtpSendGuard.checkAndRecord`** (`src/otp-send-guard.ts`) runs its read, decide and write per number through the same serialiser. The body moved unchanged into a private `checkAndRecordOnce`; the fail-open `catch` stays where it was. This is a declared in-place fix: the same defect class, a reader the card names (the OTP budget), the same file surface and the same test family. - **Cache resolution** (`src/kernel-cache.ts`, new, internal; `src/auth-plugin.ts` calls it): `resolveKernelCache(ctx)` asks `ctx.getKernel().getServiceAsync('cache')`, which answers a value registration and a factory registration alike. On a host with no `getServiceAsync` (`LiteKernel`, which has no service factories either) it asks `ctx.getService('cache')`. No `PluginContext` member is added and no `packages/core` or `packages/spec` file changes. - **The kernel's own stand-in is not a shared store.** An `ObjectKernel` with no cache plugin injects an in-memory `cache` that self-describes as `degraded` (ADR-0076 D12, read with `readServiceSelfInfo`). It is as process-local as the package's own fallback, and that fallback (`InProcessCounterStore`) is the store this package bounds for these counters: it prunes expired keys and caps how many it holds. `resolveKernelCache` answers `undefined` for it, so the bounded per-process fallback and its one-shot "no shared cache" warning stay in charge. A value without `get`/`set` answers `undefined` too. - **Changeset**: `.changeset/29053-auth-counters-per-key.md`, `@objectstack/plugin-auth` patch. ## Why better-auth's own `consume` contract says the check and the increment happen in one step, so that simultaneous requests cannot all pass a stale read. ADR-0069 D2 promises one count across nodes when a shared cache is registered. Neither held. In one process nothing ordered two updates of one key across the awaits between the read and the write. And the cache was resolved through a `getServiceAsync` member that the plugin context does not carry, so the optional call answered `undefined` on every host and the counters never reached a registered cache. ## Tests - `src/rate-limit-concurrency.test.ts` (new, 9 cases). - A concurrent burst against one key admits exactly the limit: in the per-process store, and in an async cache stand-in whose calls each cross a macrotask, where the stored count also equals the burst size. - `incrementFixedWindow` hands a concurrent burst the counts 1 to N, each exactly once. - A key parked inside its read does not hold up another key. - OTP: the cooldown grants exactly one of a burst to one number; the hourly cap grants exactly `maxPerHour`; the cache path holds the cooldown too. - `serializePerKey`: a failing update releases the next and its error reaches only its caller; no key is left behind once a burst drains. - `src/kernel-cache.test.ts` (new, 10 cases), against real kernels, never a hand-built context. - `ObjectKernel` context: a factory-registered cache (and the synchronous accessor cannot answer it), a value, none, the kernel's `degraded` stand-in, a value that is not a counter store. `LiteKernel` context: a value. - Composed stack (SQL driver, ObjectQL, `AuthPlugin`) with a `cache` registered by factory: the limiter's counter lands in it; a concurrent burst against one key admits exactly the limit while counting there; the OTP budget and the invitation preview resolve the same cache. - Composed stack with no cache plugin: the kernel's stand-in is present (the control), and the counters keep the bounded per-process store, still admitting exactly the limit. - **Forced test edits**: `src/auth-plugin.test.ts`. The `bootWith` helper and the host-`secondaryStorage` case stubbed `getServiceAsync` on the context itself, a member no kernel hands a plugin, which is why the suite passed while production never reached the cache. They now stub it on the kernel `getKernel()` returns. With the old accessor put back (ablation 3 below), the two cases that count in a cache registered after init go red. ## Acceptance notes - **Across nodes, unchanged.** `ICacheService` (`packages/spec/src/contracts/cache-service.ts`) has no atomic increment, so two nodes sharing one cache still read-modify-write against each other, as the docblocks state. Adding one is a contract change in `packages/spec`, outside this lane; reported to the seat. - **What the rule costs.** Updates of one key wait for each other. Against the per-process store that is a microtask each; against a networked cache each update waits for the previous one's read and write. Different keys are unaffected. - **The stand-in rule is a choice**, recorded as an open question in the report. The alternative counts in any registered `cache`, the kernel's `degraded` stand-in included; that would move every cache-less `ObjectKernel` deployment's counters off the bounded fallback for no cross-node gain. - **One serialiser per bundle.** The package ships its root and its `./rate-limit-storage` subpath as self-contained bundles (`splitting: false`), so each carries its own copy of the per-key map. Callers of one key are ordered when they reach the counter through the same entry. Today the two entries count disjoint keys (the auth counters through the root, the SMS day quota through the subpath). - **Not touched**: `auth-plugin.ts`'s `invitationPlacement` resolver also calls the context's absent `getServiceAsync` first. It works through its synchronous `getService` fallback, because plugin-security registers that service as a value. Dead first leg, noted here only. ## Verification Final head `7f52bb00` (origin/main merged at `0d6d4061` in `259b269f`; the last commit rewords one docblock in `src/kernel-cache.ts` and changes no code). Every reading below names the head it was taken on. <details><summary>Tests and typecheck</summary> - On `259b269f`: `pnpm --filter '@objectstack/plugin-auth...' build` under the verify lock, exit 0; `pnpm --filter @objectstack/plugin-auth test`, Test Files 210 passed (210), Tests 3629 passed, 10 skipped (3639); `pnpm --filter @objectstack/spec check:generated`, all 14 generated artifacts up to date (spec moved on main's side only). - On `7f52bb00`: the six new and touched test files (`rate-limit-concurrency`, `kernel-cache`, `auth-plugin`, `rate-limit-storage`, `rate-limit-storage-isolation`, `otp-send-guard`), 6 files, 175 tests passed; `pnpm --filter @objectstack/plugin-auth typecheck`, exit 0 (`check:test-typecheck` OK, debt ledger held). </details> <details><summary>Ablations (each through scripts/ablation-replace.mjs, restored to the HEAD blob, git diff HEAD empty)</summary> The suites read the mutated modules from `src/` by relative import, so no build sits between mutation and run. 1. `incrementFixedWindow` without the serialiser: 5 cases red. The burst cases in the per-process store, in the async cache and on both composed stacks admit the whole burst where they expect the limit; the counts case reads 1 for every increment. 2. `OtpSendGuard.checkAndRecord` without the serialiser: the 3 OTP cases red (every send of the burst granted). 3. `resolveKernelCache`'s `ObjectKernel` leg put back to the context's optional `getServiceAsync`: 7 cases red. Factory and value resolution answer `undefined`, the composed stack's counter never reaches the registered cache, and the two `auth-plugin.test.ts` cases that count in a cache registered after init go red. 4. The `LiteKernel` leg removed: the `LiteKernel` case red. 5. The `degraded` skip removed: 2 cases red (the stand-in unit case, and the composed no-cache stack now counting in the stand-in). </details> <details><summary>Dispatch gates and lint</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on `7f52bb00` derived 65 commands (9 paths, under the 3000-line threshold), the same list as on `259b269f`. All 65 run with stdin from /dev/null and the exit captured before any pipe: 65 exit 0. - On `259b269f`, two of them first answered exit 3 (prerequisite, nothing measured) and read exit 0 once it was met: `check-plugin-teardown-shape --self-test` after fetching its pinned fixture commit, and `check:dual-build-cjs-loads` after `turbo run build --filter='./packages/**'` (115 require entry points across 70 packages load). Both were in place for the final-head run. - Reconciliation on `7f52bb00`, `dispatch-gates --ran`: 65 derived, 65 run, 0 NOT-MEASURED, 0 UNRUN (a derived zero). - `eslint --no-inline-config packages/plugins/plugin-auth` (the `pnpm lint` command scoped to the touched package) on `7f52bb00`: exit 0, no findings. The repo-wide run is CI's. - `test:repo` is not run locally (no file of that project changed); it is CI's `Test Core`. - CI check-runs on this PR: not read yet (in progress at the time of writing). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No schema touched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint over the touched package; the repo-wide run is CI's.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (The 维护者速读 section is Chinese by the repo's maintainer rule.) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmPtGEJ1jqz6awM6fkJ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent eed73a3 commit 5d3f82b

9 files changed

Lines changed: 564 additions & 51 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): a rate limit admits no more than its limit inside one process, and the auth counters count in a registered `cache` service
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- **A limit holds under concurrency inside one process.** Updates of one counter key are now serialised in the process: a fixed-window limit of `max` admits at most `max` requests per window for one key however many arrive at once, and every request is counted. This holds in the per-process store and in the kernel `cache` alike. It covers better-auth's sign-in and sign-up rate limits (`rateLimit.customStorage`), the counters of the exported `cacheSecondaryStorage()` adapter, the signed-out invitation preview, and every other caller of `incrementFixedWindow` (`@objectstack/plugin-auth/rate-limit-storage`). The per-number OTP send budget follows the same rule: one number is granted no more sends than its cooldown and hourly cap allow. Other keys keep counting concurrently.
11+
- **The counters count in the registered `cache`.** When a `cache` service is registered, as a value or as a factory, the rate limits, the OTP send budget and the invitation preview count in it. They fall back to a per-process store only when none is registered, and say so once. The service is resolved through the kernel the plugin context hands out (`getKernel().getServiceAsync`), or through `getService` on a host without service factories (`LiteKernel`).
12+
- **Across nodes, unchanged.** `ICacheService` has no atomic increment, so two nodes that share one cache can still over-admit slightly between them (ADR-0069 D2), as documented. That is still strictly better than counting per node.

‎packages/plugins/plugin-auth/src/auth-plugin.test.ts‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2040,14 +2040,23 @@ describe('AuthPlugin', () => {
20402040
};
20412041
};
20422042

2043-
/** Boot the plugin against a context whose `cache` resolution is under test control. */
2043+
/**
2044+
* Boot the plugin against a context whose `cache` resolution is under test
2045+
* control — through the accessor a plugin context really carries: the
2046+
* kernel `getKernel()` hands out, whose `getServiceAsync` answers value and
2047+
* factory registrations alike. (A `getServiceAsync` stubbed on the context
2048+
* itself is a member no kernel provides; this suite used to stub exactly
2049+
* that, and passed while production never reached the cache.)
2050+
*/
20442051
const bootWith = async (resolveCache: () => Promise<unknown>) => {
20452052
const ctx = {
20462053
...mockContext,
2047-
getServiceAsync: vi.fn(async (name: string) => {
2048-
if (name === 'cache') return await resolveCache();
2049-
return undefined;
2050-
}),
2054+
getKernel: vi.fn(() => ({
2055+
getServiceAsync: vi.fn(async (name: string) => {
2056+
if (name === 'cache') return await resolveCache();
2057+
return undefined;
2058+
}),
2059+
})),
20512060
} as unknown as PluginContext;
20522061
const plugin = new AuthPlugin({
20532062
secret: 'test-secret-at-least-32-chars-long',
@@ -2103,7 +2112,7 @@ describe('AuthPlugin', () => {
21032112
it('leaves the counters to better-auth when the host supplies its own secondaryStorage', async () => {
21042113
const ctx = {
21052114
...mockContext,
2106-
getServiceAsync: vi.fn(async () => undefined),
2115+
getKernel: vi.fn(() => ({ getServiceAsync: vi.fn(async () => undefined) })),
21072116
} as unknown as PluginContext;
21082117
const plugin = new AuthPlugin({
21092118
secret: 'test-secret-at-least-32-chars-long',

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ import {
8686
type CurrencySettingsDoor,
8787
} from './organization-default-currency.js';
8888
import type { CounterStore } from './rate-limit-storage.js';
89+
import { resolveKernelCache } from './kernel-cache.js';
8990
import { authIdentityManifest } from './manifest.js';
9091
import { scheduleLegacySsoSecretMigration } from './sso-client-secret.js';
9192
import {
@@ -670,20 +671,12 @@ export class AuthPlugin implements Plugin {
670671
// The currency there is paid SMS, so an N-node deployment was billed for up
671672
// to N× the declared budget.
672673
//
673-
// The `cache` service is registered ASYNC — `getService` throws for it, so
674-
// resolve via `getServiceAsync` and treat any failure (not registered, or
675-
// not yet ready) as "no shared cache, ask again later".
676-
const resolveCache = async (): Promise<CounterStore | undefined> => {
677-
let cache: any;
678-
try {
679-
cache = await (ctx as { getServiceAsync?: (n: string) => Promise<unknown> })
680-
.getServiceAsync?.('cache');
681-
} catch {
682-
return undefined;
683-
}
684-
if (cache && typeof cache.get === 'function' && typeof cache.set === 'function') return cache;
685-
return undefined;
686-
};
674+
// The `cache` service may be registered as a value or as a factory, and
675+
// the plugin context carries no `getServiceAsync` of its own: resolve it
676+
// through the kernel the context hands out (`resolveKernelCache`), and
677+
// treat any failure (not registered, or not yet ready) as "no shared cache,
678+
// ask again later".
679+
const resolveCache = (): Promise<CounterStore | undefined> => resolveKernelCache(ctx);
687680

688681
{
689682
const { createLazyCacheRateLimitStorage, createLazyCounterStore } = await import(
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The rule these pin (ADR-0069 D2): when a `cache` service is registered — as
5+
* a value or as a factory — the auth counters count in it; only when none is
6+
* registered do they fall back to the per-process store.
7+
*
8+
* Measured against REAL kernels, never a hand-built context: a mocked context
9+
* can carry any member it likes, including one the kernel never hands a
10+
* plugin, and a test against it passes while production counts elsewhere.
11+
*
12+
* - `resolveKernelCache` against an `ObjectKernel` context (factory, value,
13+
* none, not a store, the kernel's own `degraded` stand-in) and a
14+
* `LiteKernel` context (value).
15+
* - The composed stack — SQL driver, ObjectQL, `AuthPlugin`, a `cache`
16+
* registered by FACTORY — writes the rate-limit counter into that cache,
17+
* admits exactly `max` of a concurrent burst against one key while counting
18+
* there, and hands the OTP budget and the invitation preview the same store.
19+
* - The composed stack with NO cache plugin: the kernel injects its own
20+
* in-memory stand-in, and the counters keep the package's bounded
21+
* per-process store instead of counting in it.
22+
*/
23+
24+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
25+
import { createMemoryCache, LiteKernel, ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core';
26+
import { readServiceSelfInfo } from '@objectstack/spec/api';
27+
import { ObjectQLPlugin } from '@objectstack/objectql';
28+
import { SqlDriver } from '@objectstack/driver-sql';
29+
30+
import { AuthPlugin } from './auth-plugin.js';
31+
import type { AuthManager } from './auth-manager.js';
32+
import { resolveKernelCache } from './kernel-cache.js';
33+
import { InProcessCounterStore, type CounterStore } from './rate-limit-storage.js';
34+
35+
/** A counter-capable cache: an `InProcessCounterStore` is exactly the slice the counters use. */
36+
const makeCache = (): CounterStore => new InProcessCounterStore();
37+
38+
/** A plugin that registers `cache` the way the test asks, and keeps the context it was handed. */
39+
function cachePlugin(mode: 'factory' | 'value' | 'none', cache: unknown): Plugin & { ctx?: PluginContext } {
40+
const plugin: Plugin & { ctx?: PluginContext } = {
41+
name: `test.cache.${mode}`,
42+
type: 'standard',
43+
version: '1.0.0',
44+
async init(ctx: PluginContext) {
45+
plugin.ctx = ctx;
46+
if (mode === 'factory') ctx.registerServiceFactory('cache', () => cache);
47+
if (mode === 'value') ctx.registerService('cache', cache);
48+
},
49+
};
50+
return plugin;
51+
}
52+
53+
async function objectKernelContext(mode: 'factory' | 'value' | 'none', cache: unknown): Promise<PluginContext> {
54+
// No data plane here, so the system-requirement pass (which also injects the
55+
// kernel's own `cache` stand-in) is skipped: "none" really is none.
56+
const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false, skipSystemValidation: true });
57+
const plugin = cachePlugin(mode, cache);
58+
await kernel.use(plugin);
59+
await kernel.bootstrap();
60+
return plugin.ctx!;
61+
}
62+
63+
describe('resolveKernelCache — through the accessors a plugin context really carries', () => {
64+
it('ObjectKernel, `cache` registered by FACTORY: answers the factory-built cache', async () => {
65+
const cache = makeCache();
66+
const ctx = await objectKernelContext('factory', cache);
67+
// The synchronous accessor cannot answer a factory that has not been built.
68+
expect(() => ctx.getService('cache')).toThrow('is async');
69+
await expect(resolveKernelCache(ctx)).resolves.toBe(cache);
70+
});
71+
72+
it('ObjectKernel, `cache` registered as a VALUE: answers that value', async () => {
73+
const cache = makeCache();
74+
const ctx = await objectKernelContext('value', cache);
75+
await expect(resolveKernelCache(ctx)).resolves.toBe(cache);
76+
});
77+
78+
it('ObjectKernel, no `cache` registered: answers undefined (the per-process fallback is right)', async () => {
79+
const ctx = await objectKernelContext('none', undefined);
80+
await expect(resolveKernelCache(ctx)).resolves.toBeUndefined();
81+
});
82+
83+
it("the kernel's own in-memory stand-in (self-described `degraded`): answers undefined", async () => {
84+
const standIn = createMemoryCache();
85+
expect(readServiceSelfInfo(standIn)?.status).toBe('degraded');
86+
const ctx = await objectKernelContext('value', standIn);
87+
await expect(resolveKernelCache(ctx)).resolves.toBeUndefined();
88+
});
89+
90+
it('a registered `cache` without get/set is not a counter store: answers undefined', async () => {
91+
const ctx = await objectKernelContext('value', { stats: () => ({}) });
92+
await expect(resolveKernelCache(ctx)).resolves.toBeUndefined();
93+
});
94+
95+
it('LiteKernel (no getServiceAsync, no factories), `cache` as a VALUE: answers that value', async () => {
96+
const cache = makeCache();
97+
const kernel = new LiteKernel({ logger: { level: 'silent' } });
98+
const plugin = cachePlugin('value', cache);
99+
kernel.use(plugin);
100+
await kernel.bootstrap();
101+
await expect(resolveKernelCache(plugin.ctx!)).resolves.toBe(cache);
102+
});
103+
});
104+
105+
function sqliteDriverPlugin(): Plugin {
106+
return {
107+
name: 'test.driver.sqlite',
108+
type: 'standard',
109+
version: '1.0.0',
110+
async init(ctx: PluginContext) {
111+
ctx.registerService(
112+
'driver.default',
113+
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }),
114+
);
115+
},
116+
};
117+
}
118+
119+
type ConsumeStorage = { consume: (key: string, rule: { window: number; max: number }) => Promise<{ allowed: boolean }> };
120+
type CounterConfig = { rateLimitStorage: ConsumeStorage; sharedCounterStore: () => Promise<CounterStore> };
121+
122+
/** Boot SQL driver + ObjectQL (+ the given cache plugin) + AuthPlugin, with the kernel's system pass ON. */
123+
async function bootStack(extra: Plugin[]): Promise<{ kernel: ObjectKernel; auth: AuthPlugin; config: CounterConfig }> {
124+
const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false });
125+
await kernel.use(sqliteDriverPlugin());
126+
await kernel.use(new ObjectQLPlugin());
127+
for (const p of extra) await kernel.use(p);
128+
const auth = new AuthPlugin({ secret: 'test-secret-at-least-32-chars-long-29053', baseUrl: 'http://localhost:3000' });
129+
await kernel.use(auth);
130+
await kernel.bootstrap();
131+
const manager = kernel.getService<AuthManager>('auth');
132+
return { kernel, auth, config: (manager as unknown as { config: CounterConfig }).config };
133+
}
134+
135+
const previewCounters = (auth: AuthPlugin): (() => Promise<CounterStore>) =>
136+
(auth as unknown as { invitationPreviewCounters: () => Promise<CounterStore> }).invitationPreviewCounters;
137+
138+
describe('on the composed stack, the auth counters count in a cache registered by factory', () => {
139+
let kernel: ObjectKernel;
140+
let auth: AuthPlugin;
141+
let config: CounterConfig;
142+
const cache = makeCache();
143+
144+
beforeAll(async () => {
145+
({ kernel, auth, config } = await bootStack([cachePlugin('factory', cache)]));
146+
});
147+
148+
afterAll(async () => {
149+
await kernel?.shutdown().catch(() => undefined);
150+
});
151+
152+
it('the rate limiter writes its counter into the registered cache', async () => {
153+
await expect(config.rateLimitStorage.consume('wiring:first', { window: 10, max: 3 })).resolves.toMatchObject({ allowed: true });
154+
expect(await cache.get('wiring:first')).toBeDefined();
155+
});
156+
157+
it('a concurrent burst against one key admits exactly `max` while counting in that cache', async () => {
158+
const decisions = await Promise.all(
159+
Array.from({ length: 20 }, () => config.rateLimitStorage.consume('wiring:burst', { window: 10, max: 3 })),
160+
);
161+
expect(decisions.filter((d) => d.allowed)).toHaveLength(3);
162+
expect(JSON.parse((await cache.get<string>('wiring:burst'))!)).toMatchObject({ n: 20 });
163+
});
164+
165+
it('the OTP send budget and the invitation preview resolve the same cache', async () => {
166+
await expect(config.sharedCounterStore()).resolves.toBe(cache);
167+
await expect(previewCounters(auth)()).resolves.toBe(cache);
168+
});
169+
});
170+
171+
describe("on the composed stack with no cache plugin, the counters keep the bounded per-process store", () => {
172+
let kernel: ObjectKernel;
173+
let auth: AuthPlugin;
174+
let config: CounterConfig;
175+
176+
beforeAll(async () => {
177+
({ kernel, auth, config } = await bootStack([]));
178+
});
179+
180+
afterAll(async () => {
181+
await kernel?.shutdown().catch(() => undefined);
182+
});
183+
184+
it("the kernel's own `degraded` stand-in is there, and the counters do not count in it", async () => {
185+
// Control: the kernel really did inject a `cache` — this case is not vacuous.
186+
const standIn = await kernel.getServiceAsync<unknown>('cache');
187+
expect(readServiceSelfInfo(standIn)?.status).toBe('degraded');
188+
189+
const store = await config.sharedCounterStore();
190+
expect(store).toBeInstanceOf(InProcessCounterStore);
191+
expect(store).not.toBe(standIn);
192+
await expect(previewCounters(auth)()).resolves.toBeInstanceOf(InProcessCounterStore);
193+
194+
const decisions = await Promise.all(
195+
Array.from({ length: 20 }, () => config.rateLimitStorage.consume('fallback:burst', { window: 10, max: 3 })),
196+
);
197+
expect(decisions.filter((d) => d.allowed)).toHaveLength(3);
198+
expect(await (standIn as CounterStore).get('fallback:burst')).toBeUndefined();
199+
});
200+
});
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import type { PluginContext } from '@objectstack/core';
4+
import { readServiceSelfInfo } from '@objectstack/spec/api';
5+
6+
import type { CounterStore } from './rate-limit-storage.js';
7+
8+
/**
9+
* ADR-0069 D2 — resolve the kernel `cache` service for this package's
10+
* cross-node counters (better-auth's rate limits, the per-number OTP send
11+
* budget, the signed-out invitation preview), through the accessors a
12+
* `PluginContext` really carries.
13+
*
14+
* The rule: when a `cache` service is registered — as a value or as a factory —
15+
* the counters count in it; only when none is registered do they fall back to
16+
* the per-process store.
17+
*
18+
* "None registered" includes the kernel's OWN stand-in: an `ObjectKernel` with
19+
* no cache plugin injects an in-memory `cache` that self-describes as
20+
* `degraded` (ADR-0076 D12, `readServiceSelfInfo`). Counting in it buys nothing
21+
* the per-process fallback does not — it is just as process-local — and the
22+
* fallback is the store this package bounds for these counters
23+
* (`InProcessCounterStore` prunes expired keys and caps how many it holds). So
24+
* a `degraded` cache answers `undefined`, the counters keep the bounded
25+
* fallback, and the one-shot warning that there is no shared cache stays true.
26+
*
27+
* - `ObjectKernel`: `ctx.getKernel().getServiceAsync('cache')`. It is the one
28+
* accessor that answers a value registration AND a factory registration; the
29+
* synchronous `ctx.getService` throws `is async - use await` for a factory
30+
* that has not been built yet. The context itself has no `getServiceAsync`
31+
* member, so an optional call on it answers `undefined` on every host — the
32+
* counters would never reach a registered cache.
33+
* - A `KernelBase`-shaped host (`LiteKernel`) has no `getServiceAsync` and no
34+
* service factories at all, so `ctx.getService('cache')` is complete there.
35+
*
36+
* Any failure — not registered, not buildable right now — answers `undefined`:
37+
* "no shared cache right now", asked again at the next count
38+
* (`createLazyCounterStore`'s contract). A value without `get`/`set` is not a
39+
* counter store and answers `undefined` too.
40+
*
41+
* Internal to `@objectstack/plugin-auth`: not re-exported from the package root.
42+
*/
43+
export async function resolveKernelCache(
44+
ctx: Pick<PluginContext, 'getKernel' | 'getService'>,
45+
): Promise<CounterStore | undefined> {
46+
let cache: unknown;
47+
try {
48+
const kernel = (typeof ctx.getKernel === 'function' ? ctx.getKernel() : undefined) as
49+
| { getServiceAsync?: (name: string) => Promise<unknown> }
50+
| undefined;
51+
cache =
52+
kernel && typeof kernel.getServiceAsync === 'function'
53+
? await kernel.getServiceAsync('cache')
54+
: ctx.getService<unknown>('cache');
55+
} catch {
56+
return undefined;
57+
}
58+
if (!cache || typeof (cache as CounterStore).get !== 'function' || typeof (cache as CounterStore).set !== 'function') {
59+
return undefined;
60+
}
61+
if (readServiceSelfInfo(cache)?.status === 'degraded') return undefined;
62+
return cache as CounterStore;
63+
}

0 commit comments

Comments
 (0)