@camstack/server 0.1.6 → 0.1.8

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 (60) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/addon-upload.spec.ts +58 -0
  3. package/src/__tests__/bulk-update-coordinator.spec.ts +286 -0
  4. package/src/__tests__/cap-ownership-authority.spec.ts +400 -0
  5. package/src/__tests__/cap-providers/cap-providers-location-import.spec.ts +186 -0
  6. package/src/__tests__/cap-providers/integrations-delete-cascade.spec.ts +243 -0
  7. package/src/__tests__/cap-providers-bulk-update.spec.ts +388 -0
  8. package/src/__tests__/cap-route-adapter.spec.ts +289 -0
  9. package/src/__tests__/cap-routers/broker-routing.router.spec.ts +169 -0
  10. package/src/__tests__/cap-routers/cap-route-error-formatter.spec.ts +123 -0
  11. package/src/__tests__/cap-routers/capabilities-node.spec.ts +55 -0
  12. package/src/__tests__/cap-routers/device-link-overlay.spec.ts +132 -0
  13. package/src/__tests__/dev-bootstrap-shm-ring.spec.ts +30 -0
  14. package/src/__tests__/device-settings-contribution-dispatch.spec.ts +249 -0
  15. package/src/__tests__/framework-installer-defer-restart.spec.ts +165 -0
  16. package/src/__tests__/moleculer/uds-readiness.spec.ts +143 -0
  17. package/src/__tests__/moleculer/uds-topology.spec.ts +390 -0
  18. package/src/__tests__/moleculer/uds-unowned-call.spec.ts +329 -0
  19. package/src/__tests__/moleculer-register-node-idempotency.spec.ts +39 -4
  20. package/src/__tests__/native-cap-route.spec.ts +404 -0
  21. package/src/__tests__/oauth2-account-linking.spec.ts +85 -0
  22. package/src/__tests__/uds-addon-call-wiring.spec.ts +237 -0
  23. package/src/__tests__/uds-log-ingest.spec.ts +183 -0
  24. package/src/api/addon-upload.ts +27 -1
  25. package/src/api/capabilities.router.ts +1 -1
  26. package/src/api/core/__tests__/integration-markers.spec.ts +10 -0
  27. package/src/api/core/bulk-update-coordinator.ts +302 -0
  28. package/src/api/core/cap-providers.ts +211 -9
  29. package/src/api/core/capabilities.router.ts +26 -3
  30. package/src/api/core/logs.router.ts +4 -0
  31. package/src/api/oauth2/oauth2-routes.ts +5 -1
  32. package/src/api/trpc/__tests__/client-ip.spec.ts +146 -0
  33. package/src/api/trpc/__tests__/webrtc-session-ua-enrich.spec.ts +128 -0
  34. package/src/api/trpc/cap-mount-helpers.ts +12 -1
  35. package/src/api/trpc/cap-route-error-formatter.ts +163 -0
  36. package/src/api/trpc/client-ip.ts +147 -0
  37. package/src/api/trpc/generated-cap-mounts.ts +299 -8
  38. package/src/api/trpc/generated-cap-routers.ts +2384 -302
  39. package/src/api/trpc/trpc.middleware.ts +5 -1
  40. package/src/api/trpc/trpc.router.ts +84 -3
  41. package/src/boot/__tests__/integration-id-backfill.spec.ts +116 -0
  42. package/src/boot/integration-id-backfill.ts +109 -0
  43. package/src/core/addon/__tests__/addon-row-manifest.spec.ts +62 -0
  44. package/src/core/addon/addon-call-gateway.ts +157 -0
  45. package/src/core/addon/addon-package.service.ts +9 -0
  46. package/src/core/addon/addon-registry.service.ts +453 -107
  47. package/src/core/addon/addon-row-manifest.ts +29 -0
  48. package/src/core/addon/addon-settings-provider.ts +40 -116
  49. package/src/core/capability/capability.service.ts +9 -0
  50. package/src/core/logging/logging.service.ts +7 -2
  51. package/src/core/moleculer/cap-call-fn.spec.ts +166 -0
  52. package/src/core/moleculer/cap-call-fn.ts +103 -0
  53. package/src/core/moleculer/cap-route-authority.ts +182 -0
  54. package/src/core/moleculer/moleculer.service.ts +408 -36
  55. package/src/core/network/network-quality.service.spec.ts +2 -1
  56. package/src/main.ts +137 -12
  57. package/src/core/storage/settings-store.spec.ts +0 -213
  58. package/src/core/storage/settings-store.ts +0 -2
  59. package/src/core/storage/sql-schema.spec.ts +0 -140
  60. package/src/core/storage/sql-schema.ts +0 -3
@@ -0,0 +1,404 @@
1
+ /**
2
+ * Task 5 — TDD tests: device-scoped native cap routing through CapRouteResolver.
3
+ *
4
+ * Covers:
5
+ * 1. A device-scoped native cap on a HUB-LOCAL child resolves to hub-local-uds
6
+ * and dispatches via callCapOnChild with {capName, method, args:{...deviceId}, deviceId}.
7
+ * 2. d9ba709 regression guard: a singleton cap on BOTH a hub-local child AND a remote
8
+ * node, resolved WITHOUT explicit nodeId, classifies to hub-local (not remote).
9
+ * 3. A remote device-scoped native cap builds the ${addonId}.native-provider.${cap}.${method}
10
+ * action (NATIVE_PROVIDER_SERVICE_INFIX).
11
+ * 4. nodeKnowsCap returns true for native caps (not just manifest caps).
12
+ */
13
+
14
+ import { describe, it, expect, vi } from 'vitest'
15
+ import { CapRouteResolver, NATIVE_PROVIDER_SERVICE_INFIX } from '@camstack/kernel'
16
+ import type {
17
+ NodeCapAuthority,
18
+ HubLocalChildDispatcher,
19
+ CapRouteResolverDeps,
20
+ InProcessProviderRef,
21
+ } from '@camstack/kernel'
22
+ import { CapRouteError } from '@camstack/kernel'
23
+
24
+ const HUB_NODE_ID = 'hub'
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Fake HubLocalChildDispatcher with deviceId-aware resolveChildId
28
+ // ---------------------------------------------------------------------------
29
+
30
+ interface FakeHubLocalRegistry extends HubLocalChildDispatcher {
31
+ readonly callCapOnChildSpy: ReturnType<typeof vi.fn>
32
+ }
33
+
34
+ /**
35
+ * Build a fake registry that supports device-scoped cap resolution.
36
+ * The caps map is {capName → {deviceId? → childId}} or {capName → childId} for singletons.
37
+ */
38
+ function makeDeviceAwareHubLocalRegistry(
39
+ caps: ReadonlyMap<string, ReadonlyMap<number | 'singleton', string>>,
40
+ ): FakeHubLocalRegistry {
41
+ const callCapOnChildSpy = vi.fn(async (_childId: string, _input: unknown) => ({ ok: true, from: 'uds' }))
42
+ return {
43
+ resolveChildId: (capName: string, deviceId?: number): string | null => {
44
+ const capMap = caps.get(capName)
45
+ if (capMap === undefined) return null
46
+ if (deviceId !== undefined) {
47
+ const deviceSpecific = capMap.get(deviceId)
48
+ if (deviceSpecific !== undefined) return deviceSpecific
49
+ }
50
+ return capMap.get('singleton') ?? null
51
+ },
52
+ callCapOnChild: callCapOnChildSpy,
53
+ callCapOnChildSpy,
54
+ }
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // Fake NodeCapAuthority with native-cap awareness
59
+ // ---------------------------------------------------------------------------
60
+
61
+ interface NativeCapSpec {
62
+ readonly nodeId: string
63
+ readonly addonId: string
64
+ readonly capName: string
65
+ readonly deviceId: number
66
+ }
67
+
68
+ function makeNativeAwareNodeAuthority(
69
+ systemCaps: ReadonlyMap<string, { addonId: string; nodeId: string }>,
70
+ onlineNodes: ReadonlySet<string>,
71
+ nativeCaps: readonly NativeCapSpec[],
72
+ ): NodeCapAuthority {
73
+ return {
74
+ nodeKnowsCap: (nodeId: string, capName: string): boolean => {
75
+ // Check system (manifest) caps
76
+ const sys = systemCaps.get(capName)
77
+ if (sys !== undefined && sys.nodeId === nodeId) return true
78
+ // Check native caps (any deviceId for this node+capName)
79
+ return nativeCaps.some((n) => n.nodeId === nodeId && n.capName === capName)
80
+ },
81
+
82
+ nodeIsAgent: (nodeId: string): boolean =>
83
+ nodeId !== HUB_NODE_ID && !nodeId.includes('/'),
84
+
85
+ nodeOnline: (nodeId: string): boolean => onlineNodes.has(nodeId),
86
+
87
+ listNodeIds: (): readonly string[] => {
88
+ const ids = new Set<string>()
89
+ for (const spec of systemCaps.values()) ids.add(spec.nodeId)
90
+ for (const n of nativeCaps) ids.add(n.nodeId)
91
+ return [...ids]
92
+ },
93
+
94
+ getAddonId: (nodeId: string, capName: string): string | null => {
95
+ // Check system (manifest) caps
96
+ const sys = systemCaps.get(capName)
97
+ if (sys !== undefined && sys.nodeId === nodeId) return sys.addonId
98
+ // Check native caps
99
+ const nat = nativeCaps.find((n) => n.nodeId === nodeId && n.capName === capName)
100
+ return nat?.addonId ?? null
101
+ },
102
+
103
+ getAgentChildId: (_agentNodeId: string, _capName: string): string | null => null,
104
+
105
+ isNativeCap: (nodeId: string, capName: string, deviceId?: number): boolean => {
106
+ if (deviceId !== undefined) {
107
+ return nativeCaps.some((n) => n.nodeId === nodeId && n.capName === capName && n.deviceId === deviceId)
108
+ }
109
+ return nativeCaps.some((n) => n.nodeId === nodeId && n.capName === capName)
110
+ },
111
+ }
112
+ }
113
+
114
+ // ---------------------------------------------------------------------------
115
+ // Test 1: device-scoped native cap on hub-local child → hub-local-uds dispatch
116
+ // ---------------------------------------------------------------------------
117
+
118
+ describe('Task5 – device-scoped native cap on hub-local child', () => {
119
+ it('resolves to hub-local-uds and calls callCapOnChild with {capName, method, args+deviceId, deviceId}', async () => {
120
+ // ptz is a device-scoped native cap owned by hub child 'provider-reolink'
121
+ const hubLocalCaps = makeDeviceAwareHubLocalRegistry(
122
+ new Map([
123
+ ['ptz', new Map([[7, 'provider-reolink']])],
124
+ ]),
125
+ )
126
+
127
+ const nativeCaps: NativeCapSpec[] = [
128
+ { nodeId: 'hub/provider-reolink', addonId: 'addon-provider-reolink', capName: 'ptz', deviceId: 7 },
129
+ ]
130
+ const nodeAuthority = makeNativeAwareNodeAuthority(new Map(), new Set(['hub/provider-reolink']), nativeCaps)
131
+
132
+ const deps: CapRouteResolverDeps = {
133
+ hubNodeId: HUB_NODE_ID,
134
+ broker: { call: vi.fn(), waitForServices: vi.fn() },
135
+ hubLocalRegistry: hubLocalCaps,
136
+ nodeAuthority,
137
+ inProcessProviders: () => null,
138
+ }
139
+
140
+ const resolver = new CapRouteResolver(deps)
141
+
142
+ // Resolve with deviceId = 7 so the snapshot uses the device-aware accessor
143
+ const route = resolver.resolveCapRoute('ptz', { nodeId: HUB_NODE_ID, deviceId: 7 })
144
+ expect(route.kind).toBe('hub-local-uds')
145
+ if (route.kind !== 'hub-local-uds') return
146
+ expect(route.childId).toBe('provider-reolink')
147
+
148
+ const result = await resolver.dispatch(route, 'move', { pan: 10, deviceId: 7 })
149
+ expect(result).toEqual({ ok: true, from: 'uds' })
150
+
151
+ expect(hubLocalCaps.callCapOnChildSpy).toHaveBeenCalledOnce()
152
+ const [calledChildId, calledInput] = hubLocalCaps.callCapOnChildSpy.mock.calls[0] as [string, unknown]
153
+ expect(calledChildId).toBe('provider-reolink')
154
+ expect(calledInput).toMatchObject({
155
+ capName: 'ptz',
156
+ method: 'move',
157
+ args: { pan: 10, deviceId: 7 },
158
+ deviceId: 7,
159
+ })
160
+ })
161
+
162
+ it('resolving ptz WITHOUT deviceId does NOT match the device-scoped child (no spurious route)', () => {
163
+ // When no deviceId hint is given, the singleton fallback fires — no deviceId-less descriptor exists
164
+ const hubLocalCaps = makeDeviceAwareHubLocalRegistry(
165
+ new Map([
166
+ ['ptz', new Map([[7, 'provider-reolink']])],
167
+ // No 'singleton' entry for ptz — ptz is strictly device-scoped
168
+ ]),
169
+ )
170
+ const nodeAuthority = makeNativeAwareNodeAuthority(new Map(), new Set(), [])
171
+
172
+ const deps: CapRouteResolverDeps = {
173
+ hubNodeId: HUB_NODE_ID,
174
+ broker: { call: vi.fn(), waitForServices: vi.fn() },
175
+ hubLocalRegistry: hubLocalCaps,
176
+ nodeAuthority,
177
+ inProcessProviders: () => null,
178
+ }
179
+
180
+ const resolver = new CapRouteResolver(deps)
181
+ // Without deviceId, no hub-local-uds route → CapRouteError
182
+ expect(() => resolver.resolveCapRoute('ptz', { nodeId: HUB_NODE_ID })).toThrow(CapRouteError)
183
+ })
184
+ })
185
+
186
+ // ---------------------------------------------------------------------------
187
+ // Test 2: d9ba709 regression guard — hub-local singleton beats remote
188
+ // ---------------------------------------------------------------------------
189
+
190
+ describe('Task5 – d9ba709 regression: singleton prefers hub-local over remote', () => {
191
+ it('singleton cap provided by both hub-local child AND remote node classifies to hub-local-uds (no nodeId given)', () => {
192
+ // 'pipeline-executor' is on BOTH local child addon-detection-pipeline AND remote-agent-0
193
+ const hubLocalCaps = makeDeviceAwareHubLocalRegistry(
194
+ new Map([
195
+ ['pipeline-executor', new Map([['singleton', 'addon-detection-pipeline']])],
196
+ ]),
197
+ )
198
+
199
+ const systemCaps = new Map([
200
+ ['pipeline-executor', { addonId: 'addon-detection-pipeline', nodeId: 'remote-agent-0' }],
201
+ ])
202
+ const nodeAuthority = makeNativeAwareNodeAuthority(
203
+ systemCaps,
204
+ new Set(['hub/addon-detection-pipeline', 'remote-agent-0']),
205
+ [],
206
+ )
207
+
208
+ const deps: CapRouteResolverDeps = {
209
+ hubNodeId: HUB_NODE_ID,
210
+ broker: { call: vi.fn(), waitForServices: vi.fn() },
211
+ hubLocalRegistry: hubLocalCaps,
212
+ nodeAuthority,
213
+ inProcessProviders: () => null,
214
+ }
215
+
216
+ const resolver = new CapRouteResolver(deps)
217
+ // Singleton resolution (no nodeId) — must prefer hub-local-uds
218
+ const route = resolver.resolveCapRoute('pipeline-executor', {})
219
+ expect(route.kind).toBe('hub-local-uds')
220
+ if (route.kind === 'hub-local-uds') {
221
+ expect(route.childId).toBe('addon-detection-pipeline')
222
+ }
223
+ })
224
+ })
225
+
226
+ // ---------------------------------------------------------------------------
227
+ // Test 3: remote device-scoped native cap uses NATIVE_PROVIDER_SERVICE_INFIX
228
+ // (Remote-moleculer path: non-agent remote node hosting a native device cap,
229
+ // e.g. a secondary hub or a directly-wired remote runner)
230
+ // ---------------------------------------------------------------------------
231
+
232
+ describe('Task5 – remote native cap uses NATIVE_PROVIDER_SERVICE_INFIX in action name', () => {
233
+ it('dispatches remote native cap (on non-agent remote node) with action ${addonId}.native-provider.${cap}.${method}', async () => {
234
+ const callSpy = vi.fn(async () => ({ ok: true }))
235
+ const broker = { call: callSpy, waitForServices: vi.fn(async () => {}) }
236
+
237
+ // ptz is provided by a REMOTE non-agent node (contains '/' so nodeIsAgent=false)
238
+ const remoteNodeId = 'hub-secondary/provider-reolink'
239
+ const nativeCaps: NativeCapSpec[] = [
240
+ { nodeId: remoteNodeId, addonId: 'addon-provider-reolink', capName: 'ptz', deviceId: 7 },
241
+ ]
242
+ const nodeAuthority = makeNativeAwareNodeAuthority(
243
+ new Map(),
244
+ new Set([remoteNodeId]),
245
+ nativeCaps,
246
+ )
247
+
248
+ const deps: CapRouteResolverDeps = {
249
+ hubNodeId: HUB_NODE_ID,
250
+ broker,
251
+ hubLocalRegistry: null,
252
+ nodeAuthority,
253
+ inProcessProviders: () => null,
254
+ }
255
+
256
+ const resolver = new CapRouteResolver(deps)
257
+ const route = resolver.resolveCapRoute('ptz', { nodeId: remoteNodeId, deviceId: 7 })
258
+ expect(route.kind).toBe('remote-moleculer')
259
+
260
+ await resolver.dispatch(route, 'move', { pan: 10, deviceId: 7 })
261
+
262
+ expect(callSpy).toHaveBeenCalledOnce()
263
+ const [action, , opts] = callSpy.mock.calls[0] as [string, unknown, { nodeID?: string }]
264
+ expect(action).toBe(`addon-provider-reolink${NATIVE_PROVIDER_SERVICE_INFIX}.ptz.move`)
265
+ expect((opts as { nodeID?: string }).nodeID).toBe(remoteNodeId)
266
+ })
267
+
268
+ it('non-native remote cap still uses plain ${addonId}.${cap}.${method} action', async () => {
269
+ const callSpy = vi.fn(async () => ({ ok: true }))
270
+ const broker = { call: callSpy, waitForServices: vi.fn(async () => {}) }
271
+
272
+ const remoteNodeId = 'hub-secondary/addon-analytics-suite'
273
+ const systemCaps = new Map([
274
+ ['analytics', { addonId: 'addon-analytics-suite', nodeId: remoteNodeId }],
275
+ ])
276
+ const nodeAuthority = makeNativeAwareNodeAuthority(
277
+ systemCaps,
278
+ new Set([remoteNodeId]),
279
+ [], // no native caps
280
+ )
281
+
282
+ const deps: CapRouteResolverDeps = {
283
+ hubNodeId: HUB_NODE_ID,
284
+ broker,
285
+ hubLocalRegistry: null,
286
+ nodeAuthority,
287
+ inProcessProviders: () => null,
288
+ }
289
+
290
+ const resolver = new CapRouteResolver(deps)
291
+ const route = resolver.resolveCapRoute('analytics', { nodeId: remoteNodeId })
292
+ expect(route.kind).toBe('remote-moleculer')
293
+
294
+ await resolver.dispatch(route, 'getReport', { period: 'day' })
295
+
296
+ const [action] = callSpy.mock.calls[0] as [string]
297
+ expect(action).toBe('addon-analytics-suite.analytics.getReport')
298
+ // Must NOT have the native infix
299
+ expect(action).not.toContain(NATIVE_PROVIDER_SERVICE_INFIX)
300
+ })
301
+ })
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // Test 4: nodeKnowsCap returns true for native caps (not just manifest)
305
+ // ---------------------------------------------------------------------------
306
+
307
+ describe('Task5 – nodeKnowsCap includes native caps', () => {
308
+ it('nodeKnowsCap returns true when the node has a native cap entry (even with no manifest cap)', () => {
309
+ const nativeCaps: NativeCapSpec[] = [
310
+ { nodeId: 'hub/provider-reolink', addonId: 'addon-provider-reolink', capName: 'ptz', deviceId: 7 },
311
+ ]
312
+ const nodeAuthority = makeNativeAwareNodeAuthority(
313
+ new Map(), // no system caps
314
+ new Set(['hub/provider-reolink']),
315
+ nativeCaps,
316
+ )
317
+
318
+ expect(nodeAuthority.nodeKnowsCap('hub/provider-reolink', 'ptz')).toBe(true)
319
+ expect(nodeAuthority.nodeKnowsCap('hub/provider-reolink', 'stream-broker')).toBe(false)
320
+ expect(nodeAuthority.nodeKnowsCap('other-node', 'ptz')).toBe(false)
321
+ })
322
+ })
323
+
324
+ // ---------------------------------------------------------------------------
325
+ // Test 5: native-fallback regression — an in-hub WRAPPER must not shadow the
326
+ // hub-local-uds NATIVE child for the same cap name.
327
+ //
328
+ // Reproduces the snapshot bug: the `snapshot` cap has an in-hub wrapper
329
+ // (SnapshotAddon, registered as a system singleton, so inProcessProviders
330
+ // returns a ref) AND a per-device native provider in a forked vendor child
331
+ // (provider-reolink). `resolveCapRoute` gives Priority 1 to hub-in-process,
332
+ // so it returns the WRAPPER route — never reaching the hub-local-uds native.
333
+ // The setNativeFallback resolver wants the NATIVE child specifically; it must
334
+ // use `resolveHubLocalUdsRoute`, which skips the in-process branch.
335
+ // ---------------------------------------------------------------------------
336
+
337
+ describe('native-fallback – wrapper must not shadow the hub-local native child', () => {
338
+ // snapshot has an in-hub wrapper AND a forked native child for device 7.
339
+ const wrapperRef: InProcessProviderRef = { invoke: vi.fn(async () => ({ from: 'wrapper' })) }
340
+
341
+ function makeSnapshotResolver(): { resolver: CapRouteResolver; hubLocalCaps: FakeHubLocalRegistry } {
342
+ const hubLocalCaps = makeDeviceAwareHubLocalRegistry(
343
+ new Map([
344
+ ['snapshot', new Map([[7, 'provider-reolink']])],
345
+ ]),
346
+ )
347
+ const nativeCaps: NativeCapSpec[] = [
348
+ { nodeId: 'hub/provider-reolink', addonId: 'addon-provider-reolink', capName: 'snapshot', deviceId: 7 },
349
+ ]
350
+ const nodeAuthority = makeNativeAwareNodeAuthority(
351
+ new Map(),
352
+ new Set(['hub/provider-reolink']),
353
+ nativeCaps,
354
+ )
355
+ const deps: CapRouteResolverDeps = {
356
+ hubNodeId: HUB_NODE_ID,
357
+ broker: { call: vi.fn(), waitForServices: vi.fn() },
358
+ hubLocalRegistry: hubLocalCaps,
359
+ nodeAuthority,
360
+ // The wrapper occupies the in-hub slot for 'snapshot'.
361
+ inProcessProviders: (cap: string): InProcessProviderRef | null =>
362
+ cap === 'snapshot' ? wrapperRef : null,
363
+ }
364
+ return { resolver: new CapRouteResolver(deps), hubLocalCaps }
365
+ }
366
+
367
+ it('documents the shadow: resolveCapRoute picks the in-hub wrapper (hub-in-process)', () => {
368
+ const { resolver } = makeSnapshotResolver()
369
+ const route = resolver.resolveCapRoute('snapshot', { nodeId: HUB_NODE_ID, deviceId: 7 })
370
+ // The wrapper shadows the native — this is the existing (correct for the
371
+ // generic dispatch path) behaviour the native fallback must NOT rely on.
372
+ expect(route.kind).toBe('hub-in-process')
373
+ })
374
+
375
+ it('resolveHubLocalUdsRoute returns the native child route, bypassing the wrapper shadow', () => {
376
+ const { resolver } = makeSnapshotResolver()
377
+ const route = resolver.resolveHubLocalUdsRoute('snapshot', 7)
378
+ expect(route).not.toBeNull()
379
+ expect(route?.kind).toBe('hub-local-uds')
380
+ expect(route?.childId).toBe('provider-reolink')
381
+ })
382
+
383
+ it('resolveHubLocalUdsRoute returns null when no hub-local child owns the cap (lets fallback try remote)', () => {
384
+ const { resolver } = makeSnapshotResolver()
385
+ // device 999 has no hub-local native child
386
+ expect(resolver.resolveHubLocalUdsRoute('snapshot', 999)).toBeNull()
387
+ // a cap with neither wrapper nor hub-local child
388
+ expect(resolver.resolveHubLocalUdsRoute('nonexistent', 7)).toBeNull()
389
+ })
390
+
391
+ it('dispatching the resolved hub-local-uds route reaches the native child (not the wrapper)', async () => {
392
+ const { resolver, hubLocalCaps } = makeSnapshotResolver()
393
+ const route = resolver.resolveHubLocalUdsRoute('snapshot', 7)
394
+ expect(route).not.toBeNull()
395
+ if (route === null) return
396
+ const result = await resolver.dispatch(route, 'getSnapshot', { deviceId: 7 })
397
+ expect(result).toEqual({ ok: true, from: 'uds' })
398
+ expect(hubLocalCaps.callCapOnChildSpy).toHaveBeenCalledOnce()
399
+ const [childId] = hubLocalCaps.callCapOnChildSpy.mock.calls[0] as [string]
400
+ expect(childId).toBe('provider-reolink')
401
+ // The wrapper's invoke must NOT have been called.
402
+ expect(wrapperRef.invoke).not.toHaveBeenCalled()
403
+ })
404
+ })
@@ -734,3 +734,88 @@ describe('OAuth2 account-linking flow', () => {
734
734
  })
735
735
  })
736
736
  })
737
+
738
+ // ─── Phase A: integration-driven hubUrl claim ───────────────────────────────
739
+ //
740
+ // The OAuth code/token JWT carries a `hubUrl` claim the cloud Lambda routes
741
+ // back on. A forked exporter addon (which can't set the hub's env) declares its
742
+ // operator-selected external-access endpoint on the oauth-integration
743
+ // descriptor; the authorize route must prefer it over the hub-global
744
+ // publicHubUrl() (which is localhost in dev — the cause of "linking fails after
745
+ // consent").
746
+
747
+ describe('integration-driven hubUrl claim (Phase A public-origin bridge)', () => {
748
+ const GLOBAL_FALLBACK = 'https://hub-global.example'
749
+
750
+ function buildAppWithDescriptor(descriptorHubUrl?: string) {
751
+ const sm = fakeSessionManager()
752
+ const g = createOauthGrants(realSsoBridge, sm as any)
753
+ const fastify = Fastify({ logger: false })
754
+ void fastify.register(cookie)
755
+
756
+ const descriptor = descriptorHubUrl
757
+ ? { ...ALEXA_DESCRIPTOR, hubUrl: descriptorHubUrl }
758
+ : { ...ALEXA_DESCRIPTOR }
759
+ const alexaProvider: IOauthIntegrationProvider = { getDescriptor: async () => descriptor }
760
+
761
+ const userMgmt: IUserManagementProvider = {
762
+ ...({} as IUserManagementProvider),
763
+ oauthIssueCode: g.oauthIssueCode.bind(g),
764
+ oauthExchangeCode: g.oauthExchangeCode.bind(g),
765
+ oauthRefresh: g.oauthRefresh.bind(g),
766
+ oauthVerifyAccessToken: g.oauthVerifyAccessToken.bind(g),
767
+ listOauthSessions: async () => [],
768
+ revokeOauthSession: async () => ({ success: true }),
769
+ }
770
+
771
+ const reg = {
772
+ getCollectionEntries: (cap: string) =>
773
+ cap === 'oauth-integration' ? [['export-alexa-addon', alexaProvider]] : [],
774
+ getSingleton: (cap: string) => (cap === 'user-management' ? userMgmt : null),
775
+ }
776
+
777
+ registerOauth2Routes(fastify, {
778
+ getRegistry: () => reg as any,
779
+ verifyToken: (token: string) => {
780
+ if (token === VALID_SESSION_TOKEN) return { userId: OPERATOR_USER_ID, username: OPERATOR_USERNAME }
781
+ throw new Error('invalid token')
782
+ },
783
+ publicHubUrl: () => GLOBAL_FALLBACK,
784
+ })
785
+ return fastify
786
+ }
787
+
788
+ async function issuedCodeHubUrl(app: ReturnType<typeof buildAppWithDescriptor>): Promise<unknown> {
789
+ const body = new URLSearchParams({
790
+ consent: 'allow',
791
+ integration: 'export-alexa',
792
+ redirect_uri: REDIRECT_URI,
793
+ state: STATE,
794
+ response_type: 'code',
795
+ }).toString()
796
+ const res = await app.inject({
797
+ method: 'POST',
798
+ url: '/api/oauth2/authorize',
799
+ headers: {
800
+ 'content-type': 'application/x-www-form-urlencoded',
801
+ cookie: `${SESSION_COOKIE}=${VALID_SESSION_TOKEN}`,
802
+ },
803
+ body,
804
+ })
805
+ expect(res.statusCode).toBe(302)
806
+ const loc = res.headers['location'] as string
807
+ const code = decodeURIComponent(loc.match(/[?&]code=([^&]+)/)![1]!)
808
+ const payload = JSON.parse(Buffer.from(code.split('.')[1]!, 'base64url').toString('utf8')) as Record<string, unknown>
809
+ return payload['hubUrl']
810
+ }
811
+
812
+ it('bakes the integration descriptor hubUrl into the issued code', async () => {
813
+ const app = buildAppWithDescriptor('https://tunnel.example.test')
814
+ expect(await issuedCodeHubUrl(app)).toBe('https://tunnel.example.test')
815
+ })
816
+
817
+ it('falls back to publicHubUrl() when the descriptor has no hubUrl', async () => {
818
+ const app = buildAppWithDescriptor()
819
+ expect(await issuedCodeHubUrl(app)).toBe(GLOBAL_FALLBACK)
820
+ })
821
+ })