Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/core/src/contracts/adapters/rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type RateLimitResult = {

export type RateLimiterAdapter = {
consume(key: string, opts: RateLimitOptions): Promise<RateLimitResult>;
reset(key: string): Promise<void>;
};

export const RATE_LIMITER: Token<RateLimiterAdapter> = createToken('RATE_LIMITER');
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,35 @@ describe('IdentityService - unlockUser', () => {
const svc = new IdentityService({ drizzle: drizzle as never, events: makeEvents() as never });
await expect(svc.unlockUser('missing', 'admin1')).rejects.toThrow();
});

it('resets the login rate-limit window for the unlocked user', async () => {
const drizzle = makeDrizzle({
selectRows: [
[
{
id: 'u1',
email: 'A@B.DEV',
failedLoginAttempts: 5,
lockoutUntil: new Date('2020-01-01'),
},
],
],
});
const resetMock = vi.fn().mockResolvedValue(undefined);
const limiter = {
consume: vi.fn(),
reset: resetMock,
} satisfies import('@openora/core/contracts').RateLimiterAdapter;
const svc = new IdentityService({
drizzle: drizzle as never,
events: makeEvents() as never,
limiter,
});

await svc.unlockUser('u1', 'admin1');

expect(resetMock).toHaveBeenCalledWith('login:a@b.dev');
});
});

describe('IdentityService.updateProfile language validation', () => {
Expand Down
9 changes: 8 additions & 1 deletion packages/core/src/pam/identity/contract/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,14 @@ export const identityContract = {

streamSession: oc
.route({ method: 'GET', path: '/identity/session/stream' })
.output(eventIterator(z.object({ type: z.literal('revoked') }))),
.output(
eventIterator(
z.discriminatedUnion('type', [
z.object({ type: z.literal('revoked') }),
z.object({ type: z.literal('unlocked') }),
]),
),
),

enable2fa: oc
.route({ method: 'POST', path: '/identity/2fa/enable' })
Expand Down
12 changes: 10 additions & 2 deletions packages/core/src/pam/identity/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,20 @@ export function createIdentityRouter(
const userId = getUserId(context);
return createEventStreamGenerator(
(push) => {
const unsubscribe = eventBus.on('identity.sessions.revoked_all', (event) => {
const unsubscribeRevoked = eventBus.on('identity.sessions.revoked_all', (event) => {
if (event.userId === userId) {
push({ type: 'revoked' });
}
});
return unsubscribe;
const unsubscribeUnlocked = eventBus.on('identity.user.unlocked', (event) => {
if (event.userId === userId) {
push({ type: 'unlocked' });
}
});
return () => {
unsubscribeRevoked();
unsubscribeUnlocked();
};
},
{ signal },
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,7 @@ export class IdentityService {
}

await this.clearLockout(userId);
await this.limiter?.reset(`login:${existingUser.email.toLowerCase()}`);

this.events.emit('identity.user.unlocked', {
userId,
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/server/kernel/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ export class InProcessRateLimiter implements RateLimiterAdapter {
return Promise.resolve({ allowed: false, retryAfterMs: existing.resetAt - now });
}

reset(key: string): Promise<void> {
this.windows.delete(key);
return Promise.resolve();
}

private sweep(): void {
const now = Date.now();
for (const [key, window] of this.windows) {
Expand Down
9 changes: 9 additions & 0 deletions packages/core/src/server/kernel/redis-rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ export class RedisRateLimiter implements RateLimiterAdapter {
}
}

async reset(key: string): Promise<void> {
if (!this.client.isReady) return;
try {
await this.client.del(PREFIX + key);
} catch (err) {
this.logger.warn({ keyPrefix: key.split(':')[0], err }, 'rate limiter reset failed');
}
}

// Backend unreachable: fail-open by default to keep availability (throttling pauses
// during an outage); fail-closed for keys that opt into 'deny' where an unthrottled
// window is worse than a 429 (credential guessing).
Expand Down
Loading