@furystack/rest-service 14.0.0 → 14.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/esm/actions/error-action.d.ts +7 -2
  3. package/esm/actions/error-action.d.ts.map +1 -1
  4. package/esm/actions/error-action.js +7 -2
  5. package/esm/actions/error-action.js.map +1 -1
  6. package/esm/actions/get-current-user.d.ts +1 -4
  7. package/esm/actions/get-current-user.d.ts.map +1 -1
  8. package/esm/actions/get-current-user.js +1 -4
  9. package/esm/actions/get-current-user.js.map +1 -1
  10. package/esm/actions/is-authenticated.d.ts +3 -4
  11. package/esm/actions/is-authenticated.d.ts.map +1 -1
  12. package/esm/actions/is-authenticated.js +3 -4
  13. package/esm/actions/is-authenticated.js.map +1 -1
  14. package/esm/actions/logout.d.ts +2 -6
  15. package/esm/actions/logout.d.ts.map +1 -1
  16. package/esm/actions/logout.js +2 -6
  17. package/esm/actions/logout.js.map +1 -1
  18. package/esm/actions/not-found-action.d.ts +1 -3
  19. package/esm/actions/not-found-action.d.ts.map +1 -1
  20. package/esm/actions/not-found-action.js +1 -3
  21. package/esm/actions/not-found-action.js.map +1 -1
  22. package/esm/actions/password-login-action.d.ts +5 -12
  23. package/esm/actions/password-login-action.d.ts.map +1 -1
  24. package/esm/actions/password-login-action.js +5 -12
  25. package/esm/actions/password-login-action.js.map +1 -1
  26. package/esm/authenticate.d.ts +5 -11
  27. package/esm/authenticate.d.ts.map +1 -1
  28. package/esm/authenticate.js +5 -11
  29. package/esm/authenticate.js.map +1 -1
  30. package/esm/authentication-providers/authentication-provider.d.ts +17 -0
  31. package/esm/authentication-providers/authentication-provider.d.ts.map +1 -1
  32. package/esm/authentication-providers/basic-auth-provider.d.ts +7 -0
  33. package/esm/authentication-providers/basic-auth-provider.d.ts.map +1 -1
  34. package/esm/authentication-providers/basic-auth-provider.js +7 -0
  35. package/esm/authentication-providers/basic-auth-provider.js.map +1 -1
  36. package/esm/authentication-providers/cookie-auth-provider.d.ts.map +1 -1
  37. package/esm/authentication-providers/cookie-auth-provider.js +8 -0
  38. package/esm/authentication-providers/cookie-auth-provider.js.map +1 -1
  39. package/esm/authorize.d.ts +5 -17
  40. package/esm/authorize.d.ts.map +1 -1
  41. package/esm/authorize.js +5 -17
  42. package/esm/authorize.js.map +1 -1
  43. package/esm/get-schema-from-api.d.ts.map +1 -1
  44. package/esm/get-schema-from-api.js +1 -0
  45. package/esm/get-schema-from-api.js.map +1 -1
  46. package/esm/helpers.d.ts +6 -6
  47. package/esm/helpers.d.ts.map +1 -1
  48. package/esm/helpers.js +3 -4
  49. package/esm/helpers.js.map +1 -1
  50. package/esm/http-authentication-settings.d.ts +27 -6
  51. package/esm/http-authentication-settings.d.ts.map +1 -1
  52. package/esm/http-authentication-settings.js +6 -0
  53. package/esm/http-authentication-settings.js.map +1 -1
  54. package/esm/http-server-pool.spec.js.map +1 -1
  55. package/esm/http-user-context.d.ts +8 -5
  56. package/esm/http-user-context.d.ts.map +1 -1
  57. package/esm/http-user-context.js +26 -27
  58. package/esm/http-user-context.js.map +1 -1
  59. package/esm/http-user-context.spec.js +48 -6
  60. package/esm/http-user-context.spec.js.map +1 -1
  61. package/esm/identity-cache-keys.d.ts +28 -0
  62. package/esm/identity-cache-keys.d.ts.map +1 -0
  63. package/esm/identity-cache-keys.js +13 -0
  64. package/esm/identity-cache-keys.js.map +1 -0
  65. package/esm/identity-cache-keys.spec.d.ts +2 -0
  66. package/esm/identity-cache-keys.spec.d.ts.map +1 -0
  67. package/esm/identity-cache-keys.spec.js +21 -0
  68. package/esm/identity-cache-keys.spec.js.map +1 -0
  69. package/esm/identity-event-bus.d.ts +102 -0
  70. package/esm/identity-event-bus.d.ts.map +1 -0
  71. package/esm/identity-event-bus.js +151 -0
  72. package/esm/identity-event-bus.js.map +1 -0
  73. package/esm/identity-event-bus.spec.d.ts +2 -0
  74. package/esm/identity-event-bus.spec.d.ts.map +1 -0
  75. package/esm/identity-event-bus.spec.js +392 -0
  76. package/esm/identity-event-bus.spec.js.map +1 -0
  77. package/esm/index.d.ts +3 -0
  78. package/esm/index.d.ts.map +1 -1
  79. package/esm/index.js +3 -0
  80. package/esm/index.js.map +1 -1
  81. package/esm/login-response-strategy.d.ts.map +1 -1
  82. package/esm/login-response-strategy.js.map +1 -1
  83. package/esm/openapi/generate-openapi-document.spec.js.map +1 -1
  84. package/esm/proxy-manager.spec.js.map +1 -1
  85. package/esm/request-action-implementation.d.ts +25 -0
  86. package/esm/request-action-implementation.d.ts.map +1 -1
  87. package/esm/request-action-implementation.js +9 -0
  88. package/esm/request-action-implementation.js.map +1 -1
  89. package/esm/rest-api-runtime.spec.js.map +1 -1
  90. package/esm/server-telemetry.d.ts +6 -14
  91. package/esm/server-telemetry.d.ts.map +1 -1
  92. package/esm/server-telemetry.js +2 -3
  93. package/esm/server-telemetry.js.map +1 -1
  94. package/esm/user-resolution-cache.d.ts +65 -0
  95. package/esm/user-resolution-cache.d.ts.map +1 -0
  96. package/esm/user-resolution-cache.js +101 -0
  97. package/esm/user-resolution-cache.js.map +1 -0
  98. package/esm/user-resolution-cache.spec.d.ts +2 -0
  99. package/esm/user-resolution-cache.spec.d.ts.map +1 -0
  100. package/esm/user-resolution-cache.spec.js +220 -0
  101. package/esm/user-resolution-cache.spec.js.map +1 -0
  102. package/esm/user-store.d.ts.map +1 -1
  103. package/esm/user-store.js.map +1 -1
  104. package/esm/validate.d.ts +13 -12
  105. package/esm/validate.d.ts.map +1 -1
  106. package/esm/validate.integration.spec.js +1 -0
  107. package/esm/validate.integration.spec.js.map +1 -1
  108. package/esm/validate.js +12 -0
  109. package/esm/validate.js.map +1 -1
  110. package/package.json +14 -12
  111. package/src/actions/error-action.ts +7 -3
  112. package/src/actions/get-current-user.ts +1 -4
  113. package/src/actions/is-authenticated.ts +3 -4
  114. package/src/actions/logout.ts +2 -6
  115. package/src/actions/not-found-action.ts +1 -3
  116. package/src/actions/password-login-action.ts +5 -12
  117. package/src/authenticate.ts +5 -11
  118. package/src/authentication-providers/authentication-provider.ts +17 -0
  119. package/src/authentication-providers/basic-auth-provider.ts +7 -0
  120. package/src/authentication-providers/cookie-auth-provider.ts +8 -0
  121. package/src/authorize.ts +6 -17
  122. package/src/get-schema-from-api.ts +1 -0
  123. package/src/helpers.ts +11 -11
  124. package/src/http-authentication-settings.ts +34 -6
  125. package/src/http-server-pool.spec.ts +1 -1
  126. package/src/http-user-context.spec.ts +59 -11
  127. package/src/http-user-context.ts +38 -31
  128. package/src/identity-cache-keys.spec.ts +24 -0
  129. package/src/identity-cache-keys.ts +31 -0
  130. package/src/identity-event-bus.spec.ts +285 -0
  131. package/src/identity-event-bus.ts +230 -0
  132. package/src/index.ts +3 -0
  133. package/src/login-response-strategy.ts +1 -0
  134. package/src/openapi/generate-openapi-document.spec.ts +2 -2
  135. package/src/proxy-manager.spec.ts +6 -6
  136. package/src/request-action-implementation.ts +25 -0
  137. package/src/rest-api-runtime.spec.ts +1 -1
  138. package/src/server-telemetry.ts +6 -14
  139. package/src/user-resolution-cache.spec.ts +241 -0
  140. package/src/user-resolution-cache.ts +164 -0
  141. package/src/user-store.ts +1 -0
  142. package/src/validate.integration.spec.ts +1 -0
  143. package/src/validate.ts +14 -12
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Single source of truth for the cache key and cache tag shapes used by the
3
+ * identity-resolution path. Producer (`cookie-auth-provider.getCacheKey`),
4
+ * local invalidation (`HttpUserContext.cookieLogout`,
5
+ * `UserResolutionCache.invalidateByUser`), and any future
6
+ * `IdentityEventBus` subscribers all derive their strings here so the
7
+ * local-vs-replicated invalidation paths cannot drift.
8
+ */
9
+
10
+ /**
11
+ * Cache key shape for the cookie-authentication provider. Keying by
12
+ * session id is safe because session invalidation drops the session
13
+ * row and the {@link UserResolutionCache} TTL bounds staleness.
14
+ */
15
+ export type SessionCacheKey = `cookie:${string}`
16
+
17
+ /**
18
+ * Tag attached to every {@link UserResolutionCache} entry, derived from
19
+ * the resolved user's `username`. Enables `removeByTag` invalidation
20
+ * across every cached session that resolved to a given user — used by
21
+ * `invalidateByUser` and (later) by `IdentityEventBus` subscribers
22
+ * acting on `userRolesChanged` / `userDeleted` / `passwordChanged`
23
+ * events.
24
+ */
25
+ export type UserCacheTag = `user:${string}`
26
+
27
+ /** Builds the cookie-auth cache key for `sessionId`. */
28
+ export const sessionCacheKey = (sessionId: string): SessionCacheKey => `cookie:${sessionId}`
29
+
30
+ /** Builds the user-resolution cache tag for `username`. */
31
+ export const userCacheTag = (username: string): UserCacheTag => `user:${username}`
@@ -0,0 +1,285 @@
1
+ import type { User } from '@furystack/core'
2
+ import { CrossNodeBus, defineInProcessCrossNodeBus, type BusMessage } from '@furystack/cross-node-bus'
3
+ import { createInProcessBusNetwork } from '@furystack/cross-node-bus/testing'
4
+ import { createInjector } from '@furystack/inject'
5
+ import { usingAsync } from '@furystack/utils'
6
+ import { describe, expect, it, vi } from 'vitest'
7
+ import { sessionCacheKey, userCacheTag } from './identity-cache-keys.js'
8
+ import {
9
+ applyLocalIdentityInvalidation,
10
+ IDENTITY_EVENT_TOPIC,
11
+ IdentityEventBus,
12
+ type IdentityEvent,
13
+ } from './identity-event-bus.js'
14
+ import { UserResolutionCache } from './user-resolution-cache.js'
15
+
16
+ const userOf = (username: string, roles: readonly string[] = []): User => ({ username, roles: [...roles] })
17
+
18
+ const populateCache = async (cache: UserResolutionCache, sessionId: string, user: User): Promise<void> => {
19
+ await cache.resolve(sessionCacheKey(sessionId), async () => user)
20
+ }
21
+
22
+ describe('IdentityEventBus', () => {
23
+ describe('applyLocalIdentityInvalidation', () => {
24
+ it('invalidates by session id for `userLoggedOut`', async () => {
25
+ await usingAsync(createInjector(), async (i) => {
26
+ const cache = i.get(UserResolutionCache)
27
+ await populateCache(cache, 's1', userOf('alice'))
28
+ expect(cache.size).toBe(1)
29
+ applyLocalIdentityInvalidation({ type: 'userLoggedOut', sessionId: 's1' }, cache)
30
+ expect(cache.size).toBe(0)
31
+ })
32
+ })
33
+
34
+ it('invalidates by session id for `sessionInvalidated`', async () => {
35
+ await usingAsync(createInjector(), async (i) => {
36
+ const cache = i.get(UserResolutionCache)
37
+ await populateCache(cache, 's2', userOf('alice'))
38
+ applyLocalIdentityInvalidation({ type: 'sessionInvalidated', sessionId: 's2' }, cache)
39
+ expect(cache.size).toBe(0)
40
+ })
41
+ })
42
+
43
+ for (const type of ['userRolesChanged', 'userDeleted', 'passwordChanged'] as const) {
44
+ it(`invalidates every cached session for the named user on \`${type}\``, async () => {
45
+ await usingAsync(createInjector(), async (i) => {
46
+ const cache = i.get(UserResolutionCache)
47
+ await populateCache(cache, 's-a-1', userOf('alice'))
48
+ await populateCache(cache, 's-a-2', userOf('alice'))
49
+ await populateCache(cache, 's-b-1', userOf('bob'))
50
+ expect(cache.size).toBe(3)
51
+ applyLocalIdentityInvalidation({ type, username: 'alice' }, cache)
52
+ expect(cache.size).toBe(1)
53
+ // The remaining entry is bob's.
54
+ await populateCache(cache, 's-a-3', userOf('alice'))
55
+ expect(cache.size).toBe(2)
56
+ })
57
+ })
58
+ }
59
+ })
60
+
61
+ describe('publish', () => {
62
+ it('invalidates the local cache synchronously before awaiting the bus', async () => {
63
+ await usingAsync(createInjector(), async (i) => {
64
+ const cache = i.get(UserResolutionCache)
65
+ await populateCache(cache, 's1', userOf('alice'))
66
+ const bus = i.get(IdentityEventBus)
67
+ const pending = bus.publish({ type: 'userLoggedOut', sessionId: 's1' })
68
+ // Local invalidation must already be visible — the bus.publish promise
69
+ // is irrelevant for in-process correctness on the originating node.
70
+ expect(cache.size).toBe(0)
71
+ await pending
72
+ })
73
+ })
74
+
75
+ it('fires local subscribers with the typed payload on every event variant', async () => {
76
+ await usingAsync(createInjector(), async (i) => {
77
+ const bus = i.get(IdentityEventBus)
78
+ const events: IdentityEvent[] = []
79
+ using _u = bus.subscribe('userLoggedOut', (event) => events.push(event))
80
+ using _s = bus.subscribe('sessionInvalidated', (event) => events.push(event))
81
+ using _r = bus.subscribe('userRolesChanged', (event) => events.push(event))
82
+ using _d = bus.subscribe('userDeleted', (event) => events.push(event))
83
+ using _p = bus.subscribe('passwordChanged', (event) => events.push(event))
84
+
85
+ await bus.publish({ type: 'userLoggedOut', sessionId: 's1' })
86
+ await bus.publish({ type: 'sessionInvalidated', sessionId: 's2' })
87
+ await bus.publish({ type: 'userRolesChanged', username: 'alice' })
88
+ await bus.publish({ type: 'userDeleted', username: 'bob' })
89
+ await bus.publish({ type: 'passwordChanged', username: 'carol' })
90
+
91
+ expect(events).toEqual([
92
+ { type: 'userLoggedOut', sessionId: 's1' },
93
+ { type: 'sessionInvalidated', sessionId: 's2' },
94
+ { type: 'userRolesChanged', username: 'alice' },
95
+ { type: 'userDeleted', username: 'bob' },
96
+ { type: 'passwordChanged', username: 'carol' },
97
+ ])
98
+ })
99
+ })
100
+
101
+ it('does not fire subscribers for other event types', async () => {
102
+ await usingAsync(createInjector(), async (i) => {
103
+ const bus = i.get(IdentityEventBus)
104
+ const handler = vi.fn()
105
+ using _u = bus.subscribe('userLoggedOut', handler)
106
+
107
+ await bus.publish({ type: 'sessionInvalidated', sessionId: 'x' })
108
+ await bus.publish({ type: 'userRolesChanged', username: 'alice' })
109
+
110
+ expect(handler).not.toHaveBeenCalled()
111
+ })
112
+ })
113
+
114
+ it('rejects when called after dispose', async () => {
115
+ const injector = createInjector()
116
+ const bus = injector.get(IdentityEventBus)
117
+ await injector[Symbol.asyncDispose]()
118
+ await expect(bus.publish({ type: 'userLoggedOut', sessionId: 's1' })).rejects.toThrow(/disposed/)
119
+ })
120
+
121
+ it('publishes onto the underlying CrossNodeBus topic', async () => {
122
+ await usingAsync(createInjector(), async (i) => {
123
+ const crossNodeBus = i.get(CrossNodeBus)
124
+ const wireHandler = vi.fn<(message: BusMessage) => void>()
125
+ using _sub = crossNodeBus.subscribe(IDENTITY_EVENT_TOPIC, wireHandler)
126
+
127
+ await i.get(IdentityEventBus).publish({ type: 'userRolesChanged', username: 'alice' })
128
+
129
+ expect(wireHandler).toHaveBeenCalledTimes(1)
130
+ expect(wireHandler.mock.calls[0][0].payload).toEqual({ type: 'userRolesChanged', username: 'alice' })
131
+ })
132
+ })
133
+ })
134
+
135
+ describe('subscribe', () => {
136
+ it('returns a Disposable that removes the listener', async () => {
137
+ await usingAsync(createInjector(), async (i) => {
138
+ const bus = i.get(IdentityEventBus)
139
+ const handler = vi.fn()
140
+ const sub = bus.subscribe('userLoggedOut', handler)
141
+ await bus.publish({ type: 'userLoggedOut', sessionId: 's1' })
142
+ sub[Symbol.dispose]()
143
+ await bus.publish({ type: 'userLoggedOut', sessionId: 's2' })
144
+ expect(handler).toHaveBeenCalledTimes(1)
145
+ })
146
+ })
147
+
148
+ it('isolates listener errors so peers still run', async () => {
149
+ await usingAsync(createInjector(), async (i) => {
150
+ const bus = i.get(IdentityEventBus)
151
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
152
+ try {
153
+ const peer = vi.fn()
154
+ using _bad = bus.subscribe('userLoggedOut', () => {
155
+ throw new Error('boom')
156
+ })
157
+ using _good = bus.subscribe('userLoggedOut', peer)
158
+
159
+ await bus.publish({ type: 'userLoggedOut', sessionId: 's1' })
160
+
161
+ expect(peer).toHaveBeenCalledTimes(1)
162
+ expect(errorSpy).toHaveBeenCalled()
163
+ } finally {
164
+ errorSpy.mockRestore()
165
+ }
166
+ })
167
+ })
168
+
169
+ it('lets a handler dispose its own subscription mid-emit without skipping peers', async () => {
170
+ await usingAsync(createInjector(), async (i) => {
171
+ const bus = i.get(IdentityEventBus)
172
+ const peer = vi.fn()
173
+ let selfDispose: Disposable | null = null
174
+ selfDispose = bus.subscribe('userLoggedOut', () => {
175
+ selfDispose?.[Symbol.dispose]()
176
+ })
177
+ using _peer = bus.subscribe('userLoggedOut', peer)
178
+
179
+ await bus.publish({ type: 'userLoggedOut', sessionId: 's1' })
180
+
181
+ expect(peer).toHaveBeenCalledTimes(1)
182
+ })
183
+ })
184
+ })
185
+
186
+ describe('cross-node delivery', () => {
187
+ it('logout on node A invalidates the cached session on node B', async () => {
188
+ using network = createInProcessBusNetwork({ count: 2 })
189
+ const [busA, busB] = network.buses
190
+ await usingAsync(createInjector(), async (a) => {
191
+ await usingAsync(createInjector(), async (b) => {
192
+ a.bind(CrossNodeBus, defineInProcessCrossNodeBus({ broker: network.broker, nodeId: busA.nodeId }))
193
+ b.bind(CrossNodeBus, defineInProcessCrossNodeBus({ broker: network.broker, nodeId: busB.nodeId }))
194
+
195
+ const cacheA = a.get(UserResolutionCache)
196
+ const cacheB = b.get(UserResolutionCache)
197
+ await populateCache(cacheA, 's1', userOf('alice'))
198
+ await populateCache(cacheB, 's1', userOf('alice'))
199
+
200
+ // Force the bus singletons to materialise so subscriptions are live.
201
+ const facadeA = a.get(IdentityEventBus)
202
+ b.get(IdentityEventBus)
203
+
204
+ await facadeA.publish({ type: 'userLoggedOut', sessionId: 's1' })
205
+
206
+ expect(cacheA.size).toBe(0)
207
+ expect(cacheB.size).toBe(0)
208
+ })
209
+ })
210
+ })
211
+
212
+ it('userRolesChanged on node A drops every alice entry on node B', async () => {
213
+ using network = createInProcessBusNetwork({ count: 2 })
214
+ const [busA, busB] = network.buses
215
+ await usingAsync(createInjector(), async (a) => {
216
+ await usingAsync(createInjector(), async (b) => {
217
+ a.bind(CrossNodeBus, defineInProcessCrossNodeBus({ broker: network.broker, nodeId: busA.nodeId }))
218
+ b.bind(CrossNodeBus, defineInProcessCrossNodeBus({ broker: network.broker, nodeId: busB.nodeId }))
219
+
220
+ const cacheB = b.get(UserResolutionCache)
221
+ await populateCache(cacheB, 's-a-1', userOf('alice'))
222
+ await populateCache(cacheB, 's-a-2', userOf('alice'))
223
+ await populateCache(cacheB, 's-b-1', userOf('bob'))
224
+ a.get(IdentityEventBus)
225
+ b.get(IdentityEventBus)
226
+
227
+ await a.get(IdentityEventBus).publish({ type: 'userRolesChanged', username: 'alice' })
228
+
229
+ expect(cacheB.size).toBe(1)
230
+ })
231
+ })
232
+ })
233
+
234
+ it('local subscribers on node A see the event before the bus broadcasts', async () => {
235
+ using network = createInProcessBusNetwork({ count: 2 })
236
+ const [busA, busB] = network.buses
237
+ await usingAsync(createInjector(), async (a) => {
238
+ await usingAsync(createInjector(), async (b) => {
239
+ a.bind(CrossNodeBus, defineInProcessCrossNodeBus({ broker: network.broker, nodeId: busA.nodeId }))
240
+ b.bind(CrossNodeBus, defineInProcessCrossNodeBus({ broker: network.broker, nodeId: busB.nodeId }))
241
+
242
+ const order: string[] = []
243
+ using _localA = a.get(IdentityEventBus).subscribe('userDeleted', () => order.push('A-local'))
244
+ using _remoteB = b.get(IdentityEventBus).subscribe('userDeleted', () => order.push('B-remote'))
245
+
246
+ await a.get(IdentityEventBus).publish({ type: 'userDeleted', username: 'bob' })
247
+
248
+ // A-local fires synchronously inside `publish`; B-remote fires after
249
+ // the bus accepts the message — same tick in-process, but ordering
250
+ // is guaranteed by the publish path's local-first contract.
251
+ expect(order).toEqual(['A-local', 'B-remote'])
252
+ })
253
+ })
254
+ })
255
+
256
+ it('drops malformed payloads received over the bus without invalidating the cache', async () => {
257
+ using network = createInProcessBusNetwork({ count: 2 })
258
+ const [busA, busB] = network.buses
259
+ await usingAsync(createInjector(), async (a) => {
260
+ await usingAsync(createInjector(), async (b) => {
261
+ a.bind(CrossNodeBus, defineInProcessCrossNodeBus({ broker: network.broker, nodeId: busA.nodeId }))
262
+ b.bind(CrossNodeBus, defineInProcessCrossNodeBus({ broker: network.broker, nodeId: busB.nodeId }))
263
+
264
+ const cacheB = b.get(UserResolutionCache)
265
+ await populateCache(cacheB, 's1', userOf('alice'))
266
+ b.get(IdentityEventBus)
267
+ a.get(IdentityEventBus)
268
+
269
+ await a.get(CrossNodeBus).publish(IDENTITY_EVENT_TOPIC, { type: 'unknownEvent', sessionId: 's1' })
270
+ await a.get(CrossNodeBus).publish(IDENTITY_EVENT_TOPIC, null)
271
+ await a.get(CrossNodeBus).publish(IDENTITY_EVENT_TOPIC, { type: 'userLoggedOut' })
272
+
273
+ expect(cacheB.size).toBe(1)
274
+ })
275
+ })
276
+ })
277
+ })
278
+
279
+ describe('shared helpers', () => {
280
+ it('exposes the cache-key shape used by the facade subscribers', () => {
281
+ expect(sessionCacheKey('s1')).toBe('cookie:s1')
282
+ expect(userCacheTag('alice')).toBe('user:alice')
283
+ })
284
+ })
285
+ })
@@ -0,0 +1,230 @@
1
+ import { CrossNodeBus, type BusMessage } from '@furystack/cross-node-bus'
2
+ import { defineService, type Token } from '@furystack/inject'
3
+ import { sessionCacheKey } from './identity-cache-keys.js'
4
+ import { UserResolutionCache } from './user-resolution-cache.js'
5
+
6
+ /**
7
+ * Wire topic the facade publishes to and subscribes from on the underlying
8
+ * {@link CrossNodeBus}. A single topic is used for all event types — internal
9
+ * dispatch happens by `event.type`. Keeping one topic minimises broker
10
+ * subscriptions on networked adapters (Redis Streams, NATS) and matches the
11
+ * EventHub-style fan-out apps already use.
12
+ */
13
+ export const IDENTITY_EVENT_TOPIC = 'identity/events'
14
+
15
+ /**
16
+ * Discriminated union of cross-node identity events. Adding a new variant
17
+ * **must** also extend {@link applyLocalIdentityInvalidation} so the local
18
+ * cache stays in sync with the published intent.
19
+ *
20
+ * - `userLoggedOut` / `sessionInvalidated` invalidate the cache entry for a
21
+ * single session id (same shape — `sessionInvalidated` is meant for
22
+ * admin / forced flows where a session row is dropped server-side).
23
+ * - `userRolesChanged` / `userDeleted` / `passwordChanged` invalidate every
24
+ * cached entry that resolved to the named user, regardless of which
25
+ * session originally populated it.
26
+ */
27
+ export type IdentityEvent =
28
+ | { type: 'userLoggedOut'; sessionId: string }
29
+ | { type: 'sessionInvalidated'; sessionId: string }
30
+ | { type: 'userRolesChanged'; username: string }
31
+ | { type: 'userDeleted'; username: string }
32
+ | { type: 'passwordChanged'; username: string }
33
+
34
+ /**
35
+ * Cross-node identity event facade. Bridges the per-process
36
+ * {@link UserResolutionCache} to the shared {@link CrossNodeBus} so that
37
+ * logouts, role flips, password resets and account deletions invalidate
38
+ * cached identities across every node, not just the one that originated
39
+ * the change.
40
+ *
41
+ * Publishing collapses the staleness window from `userCacheTtlMs`
42
+ * (default 30 s) to bus latency (single-digit ms with Redis pub/sub).
43
+ *
44
+ * **Self-delivery contract.** {@link IdentityEventBus.publish} applies the
45
+ * matching local invalidation and fires local subscribers synchronously
46
+ * **before** awaiting the bus. Sibling nodes receive the message via a
47
+ * `subscribeRemoteOnly` bridge — own publishes never round-trip through the
48
+ * transport, so duplicate work is impossible.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * import type { Injector } from '@furystack/inject'
53
+ * import { IdentityEventBus } from '@furystack/rest-service'
54
+ *
55
+ * declare const injector: Injector
56
+ * const bus = injector.get(IdentityEventBus)
57
+ *
58
+ * using sub = bus.subscribe('userRolesChanged', ({ username }) => {
59
+ * console.log('roles changed for', username)
60
+ * })
61
+ *
62
+ * await bus.publish({ type: 'userRolesChanged', username: 'alice' })
63
+ * ```
64
+ */
65
+ export interface IdentityEventBus extends Disposable {
66
+ /**
67
+ * Publishes a typed identity event. Applies the matching local cache
68
+ * invalidation synchronously, fires local subscribers synchronously, then
69
+ * awaits the underlying bus broadcast. Resolves once the message has been
70
+ * accepted by the transport.
71
+ */
72
+ publish(event: IdentityEvent): Promise<void>
73
+
74
+ /**
75
+ * Subscribes to a single event type. Local emits and bus-delivered messages
76
+ * from sibling nodes both fire the handler. Returns a `Disposable` that
77
+ * removes the listener on dispose.
78
+ */
79
+ subscribe<TType extends IdentityEvent['type']>(
80
+ type: TType,
81
+ handler: (event: Extract<IdentityEvent, { type: TType }>) => void,
82
+ ): Disposable
83
+ }
84
+
85
+ /**
86
+ * Applies the cache invalidation that corresponds to `event` against
87
+ * `userCache`. Centralised so the publish path and the remote-receive path
88
+ * cannot drift — both call this single helper. Exported for the rare
89
+ * subsystem (e.g. websocket-api logout-driven socket close) that consumes
90
+ * an {@link IdentityEvent} and needs to mirror the cache effect.
91
+ */
92
+ export const applyLocalIdentityInvalidation = (event: IdentityEvent, userCache: UserResolutionCache): void => {
93
+ switch (event.type) {
94
+ case 'userLoggedOut':
95
+ case 'sessionInvalidated':
96
+ userCache.invalidate(sessionCacheKey(event.sessionId))
97
+ return
98
+ case 'userRolesChanged':
99
+ case 'userDeleted':
100
+ case 'passwordChanged':
101
+ userCache.invalidateByUser(event.username)
102
+ return
103
+ default: {
104
+ // Exhaustiveness check: every variant of {@link IdentityEvent} above
105
+ // must be handled. Adding a new variant without updating this switch
106
+ // will fail to compile.
107
+ const _exhaustive: never = event
108
+ void _exhaustive
109
+ }
110
+ }
111
+ }
112
+
113
+ const isIdentityEvent = (value: unknown): value is IdentityEvent => {
114
+ if (typeof value !== 'object' || value === null) return false
115
+ const candidate = value as { type?: unknown; sessionId?: unknown; username?: unknown }
116
+ switch (candidate.type) {
117
+ case 'userLoggedOut':
118
+ case 'sessionInvalidated':
119
+ return typeof candidate.sessionId === 'string'
120
+ case 'userRolesChanged':
121
+ case 'userDeleted':
122
+ case 'passwordChanged':
123
+ return typeof candidate.username === 'string'
124
+ default:
125
+ return false
126
+ }
127
+ }
128
+
129
+ type AnyIdentityHandler = (event: IdentityEvent) => void
130
+
131
+ class IdentityEventBusImpl implements IdentityEventBus {
132
+ readonly #bus: CrossNodeBus
133
+ readonly #userCache: UserResolutionCache
134
+ readonly #handlers: Map<IdentityEvent['type'], Set<AnyIdentityHandler>> = new Map()
135
+ readonly #busSubscription: Disposable
136
+ #disposed = false
137
+
138
+ constructor(bus: CrossNodeBus, userCache: UserResolutionCache) {
139
+ this.#bus = bus
140
+ this.#userCache = userCache
141
+ // subscribeRemoteOnly: own publishes invalidate locally inline, so we
142
+ // only handle messages originating on sibling nodes here.
143
+ this.#busSubscription = bus.subscribeRemoteOnly(IDENTITY_EVENT_TOPIC, (message) => this.#receive(message))
144
+ }
145
+
146
+ public async publish(event: IdentityEvent): Promise<void> {
147
+ if (this.#disposed) {
148
+ throw new Error('IdentityEventBus has been disposed')
149
+ }
150
+ applyLocalIdentityInvalidation(event, this.#userCache)
151
+ this.#emit(event)
152
+ await this.#bus.publish(IDENTITY_EVENT_TOPIC, event)
153
+ }
154
+
155
+ public subscribe<TType extends IdentityEvent['type']>(
156
+ type: TType,
157
+ handler: (event: Extract<IdentityEvent, { type: TType }>) => void,
158
+ ): Disposable {
159
+ let handlers = this.#handlers.get(type)
160
+ if (!handlers) {
161
+ handlers = new Set()
162
+ this.#handlers.set(type, handlers)
163
+ }
164
+ const wrapped: AnyIdentityHandler = (event) => handler(event as Extract<IdentityEvent, { type: TType }>)
165
+ handlers.add(wrapped)
166
+ return {
167
+ [Symbol.dispose]: () => {
168
+ const current = this.#handlers.get(type)
169
+ if (!current) return
170
+ current.delete(wrapped)
171
+ if (current.size === 0) this.#handlers.delete(type)
172
+ },
173
+ }
174
+ }
175
+
176
+ public [Symbol.dispose](): void {
177
+ if (this.#disposed) return
178
+ this.#disposed = true
179
+ this.#busSubscription[Symbol.dispose]()
180
+ this.#handlers.clear()
181
+ }
182
+
183
+ #receive(message: BusMessage): void {
184
+ const { payload } = message
185
+ if (!isIdentityEvent(payload)) {
186
+ // Foreign or future-version messages are silently ignored — older nodes
187
+ // see new event types as no-ops, which is the documented dual-accept
188
+ // behaviour from the cross-node-bus PRD §12.
189
+ return
190
+ }
191
+ applyLocalIdentityInvalidation(payload, this.#userCache)
192
+ this.#emit(payload)
193
+ }
194
+
195
+ #emit(event: IdentityEvent): void {
196
+ const handlers = this.#handlers.get(event.type)
197
+ if (!handlers) return
198
+ // Snapshot so a handler that disposes its own subscription mid-emit can't
199
+ // mutate the iterator. Listener errors are isolated per-handler and
200
+ // logged — one throwing handler must not poison its peers.
201
+ for (const handler of [...handlers]) {
202
+ try {
203
+ handler(event)
204
+ } catch (error) {
205
+ console.error('IdentityEventBus listener threw', { type: event.type, error })
206
+ }
207
+ }
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Singleton DI token for the {@link IdentityEventBus}. Resolves a facade that
213
+ * shares the injector's {@link CrossNodeBus} binding — apps that have not
214
+ * bound a transport adapter run against the in-process default and
215
+ * single-node deployments work without configuration.
216
+ */
217
+ export const IdentityEventBus: Token<IdentityEventBus, 'singleton'> = defineService({
218
+ name: 'furystack/rest-service/IdentityEventBus',
219
+ lifetime: 'singleton',
220
+ factory: ({ inject, onDispose }): IdentityEventBus => {
221
+ const bus = inject(CrossNodeBus)
222
+ const userCache = inject(UserResolutionCache)
223
+ const impl = new IdentityEventBusImpl(bus, userCache)
224
+ onDispose(() => {
225
+ // eslint-disable-next-line furystack/prefer-using-wrapper -- onDispose is the teardown hook
226
+ impl[Symbol.dispose]()
227
+ })
228
+ return impl
229
+ },
230
+ })
package/src/index.ts CHANGED
@@ -9,6 +9,8 @@ export * from './helpers.js'
9
9
  export * from './http-authentication-settings.js'
10
10
  export * from './http-server-pool.js'
11
11
  export * from './http-user-context.js'
12
+ export * from './identity-cache-keys.js'
13
+ export * from './identity-event-bus.js'
12
14
  export * from './login-response-strategy.js'
13
15
  export * from './mime-types.js'
14
16
  export * from './models/index.js'
@@ -20,5 +22,6 @@ export * from './schema-validator/index.js'
20
22
  export * from './server-response-extensions.js'
21
23
  export * from './server-telemetry.js'
22
24
  export * from './static-site-runtime.js'
25
+ export * from './user-resolution-cache.js'
23
26
  export * from './user-store.js'
24
27
  export * from './validate.js'
@@ -3,6 +3,7 @@ import { useSystemIdentityContext } from '@furystack/core'
3
3
  import type { Injector } from '@furystack/inject'
4
4
  import { randomBytes } from 'crypto'
5
5
 
6
+ import type { createPasswordLoginAction } from './actions/password-login-action.js'
6
7
  import { HttpAuthenticationSettings } from './http-authentication-settings.js'
7
8
  import type { ActionResult } from './request-action-implementation.js'
8
9
  import { JsonResult } from './request-action-implementation.js'
@@ -275,7 +275,7 @@ describe('generateOpenApiDocument', () => {
275
275
  it('Should use generic object schema when no schemaName', () => {
276
276
  const api: ApiEndpointSchema['endpoints'] = {
277
277
  GET: {
278
- '/test': { path: '/test', isAuthenticated: false, schemaName: '', schema: null as unknown },
278
+ '/test': { path: '/test', isAuthenticated: false, schemaName: '', schema: null },
279
279
  },
280
280
  }
281
281
 
@@ -300,7 +300,7 @@ describe('generateOpenApiDocument', () => {
300
300
  it('Should not add schema to components when schema is falsy', () => {
301
301
  const api: ApiEndpointSchema['endpoints'] = {
302
302
  GET: {
303
- '/test': { path: '/test', isAuthenticated: false, schemaName: 'Empty', schema: null as unknown },
303
+ '/test': { path: '/test', isAuthenticated: false, schemaName: 'Empty', schema: null },
304
304
  },
305
305
  }
306
306
 
@@ -897,7 +897,7 @@ describe('ProxyManager', () => {
897
897
  targetBaseUrl: `http://localhost:${targetPort}`,
898
898
  sourcePort: proxyPort,
899
899
  headers: () => ({
900
- 'X-Array-Header': ['value1', 'value2', 'value3'] as unknown as string,
900
+ 'X-Array-Header': ['value1', 'value2', 'value3'],
901
901
  }),
902
902
  })
903
903
 
@@ -935,7 +935,7 @@ describe('ProxyManager', () => {
935
935
  sourcePort: proxyPort,
936
936
  headers: () => ({
937
937
  'X-Defined-Header': 'defined',
938
- 'X-Undefined-Header': undefined as unknown as string,
938
+ 'X-Undefined-Header': undefined,
939
939
  }),
940
940
  })
941
941
 
@@ -1135,7 +1135,7 @@ describe('ProxyManager', () => {
1135
1135
  const targetWss = new WebSocketServer({ server: targetServer })
1136
1136
 
1137
1137
  targetWss.on('connection', (ws, req) => {
1138
- receivedProtocol = req.headers['sec-websocket-protocol'] as string
1138
+ receivedProtocol = req.headers['sec-websocket-protocol']
1139
1139
  ws.send('connected')
1140
1140
  })
1141
1141
 
@@ -1714,9 +1714,9 @@ describe('ProxyManager', () => {
1714
1714
  sourcePort: proxyPort,
1715
1715
  enableWebsockets: true,
1716
1716
  headers: () => ({
1717
- 'X-Number-Header': 42 as unknown as string,
1718
- 'X-Array-Header': ['val1', 'val2'] as unknown as string,
1719
- 'X-Undefined-Header': undefined as unknown as string,
1717
+ 'X-Number-Header': 42,
1718
+ 'X-Array-Header': ['val1', 'val2'],
1719
+ 'X-Undefined-Header': undefined,
1720
1720
  'X-String-Header': 'string-value',
1721
1721
  }),
1722
1722
  })