@owlmeans/server-api 0.1.18-rc.3 → 0.1.18-rc.31

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 (56) hide show
  1. package/README.md +179 -47
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/server-api/SKILL.md +45 -22
  4. package/build/errors.d.ts +12 -0
  5. package/build/errors.d.ts.map +1 -1
  6. package/build/errors.js +16 -0
  7. package/build/errors.js.map +1 -1
  8. package/build/helper.d.ts.map +1 -1
  9. package/build/helper.js +10 -1
  10. package/build/helper.js.map +1 -1
  11. package/build/hold.d.ts +52 -0
  12. package/build/hold.d.ts.map +1 -0
  13. package/build/hold.js +56 -0
  14. package/build/hold.js.map +1 -0
  15. package/build/index.d.ts +2 -0
  16. package/build/index.d.ts.map +1 -1
  17. package/build/index.js +2 -0
  18. package/build/index.js.map +1 -1
  19. package/build/protocol.d.ts +45 -0
  20. package/build/protocol.d.ts.map +1 -0
  21. package/build/protocol.js +86 -0
  22. package/build/protocol.js.map +1 -0
  23. package/build/server.d.ts.map +1 -1
  24. package/build/server.js +7 -12
  25. package/build/server.js.map +1 -1
  26. package/build/types.d.ts +1 -2
  27. package/build/types.d.ts.map +1 -1
  28. package/build/utils/error.d.ts +13 -0
  29. package/build/utils/error.d.ts.map +1 -1
  30. package/build/utils/error.js +21 -4
  31. package/build/utils/error.js.map +1 -1
  32. package/build/utils/guards.d.ts.map +1 -1
  33. package/build/utils/guards.js +11 -15
  34. package/build/utils/guards.js.map +1 -1
  35. package/build/utils/payload.d.ts.map +1 -1
  36. package/build/utils/payload.js +3 -0
  37. package/build/utils/payload.js.map +1 -1
  38. package/build/utils/server.d.ts.map +1 -1
  39. package/build/utils/server.js +4 -1
  40. package/build/utils/server.js.map +1 -1
  41. package/package.json +13 -11
  42. package/src/errors.ts +18 -0
  43. package/src/helper.ts +10 -1
  44. package/src/hold.ts +84 -0
  45. package/src/index.ts +2 -0
  46. package/src/protocol.ts +185 -0
  47. package/src/server.ts +34 -43
  48. package/src/types.ts +1 -3
  49. package/src/utils/error.ts +20 -3
  50. package/src/utils/guards.ts +10 -17
  51. package/src/utils/payload.ts +3 -0
  52. package/src/utils/server.ts +4 -1
  53. package/tests/handlers.spec.ts +83 -0
  54. package/tests/tsconfig.json +12 -0
  55. package/tsconfig.json +1 -0
  56. package/build/.gitkeep +0 -0
package/src/hold.ts ADDED
@@ -0,0 +1,84 @@
1
+ import Fastify from 'fastify'
2
+ import type { ServerConfig } from '@owlmeans/server-context'
3
+ import { CLOSED_HOST, OPENED_HOST, PORT } from './consts.js'
4
+
5
+ export interface ApiPortHoldOptions {
6
+ /**
7
+ * The one path answered 200 while the hold is in place — the app's health endpoint, so
8
+ * whatever supervises the process keeps a conventional liveness answer through the boot.
9
+ * Everything else answers 503 with the same body. Absent, everything is 503.
10
+ */
11
+ okPath?: string
12
+ /** Body of every answer, evaluated per request so a changing boot phase is reported live. */
13
+ payload?: () => unknown
14
+ }
15
+
16
+ export interface ApiPortHold {
17
+ /**
18
+ * Free the port for the real server. Awaits the actual close — `listen()` follows immediately,
19
+ * and a predecessor still bound makes it throw — and force-closes keep-alive sockets, so a
20
+ * supervisor's own poller cannot hold the release open.
21
+ */
22
+ release: () => Promise<void>
23
+ }
24
+
25
+ /**
26
+ * Own the app's port while the context initializes, and answer for the app until `listen()`
27
+ * takes over.
28
+ *
29
+ * The API server itself cannot do this: it builds its route table from the entrypoints the
30
+ * context knows about, so it can only bind AFTER `init()` resolves — and Fastify refuses new
31
+ * routes once it is listening. Without a hold, the whole boot window, and every way a boot can
32
+ * fail, leaves nothing on the port; the edge then answers a bare upstream connect error that
33
+ * names neither the app nor the reason, which is indistinguishable from a crashed pod or an app
34
+ * that was never installed.
35
+ *
36
+ * So the boot sequence an app wants is:
37
+ *
38
+ * const hold = await holdApiPort(cfg, { okPath, payload }) // bind FIRST
39
+ * try { ...initialize... } catch { record the failure; return } // hold keeps answering
40
+ * await hold.release()
41
+ * await context.getApiServer().listen()
42
+ *
43
+ * Everything that is not the health path answers **503, not 404**: the routes the app really
44
+ * serves do not exist yet, and "no such route" would be a lie that outlives the boot.
45
+ *
46
+ * The port and host are resolved exactly as `listen()` resolves them — from the service's own
47
+ * declaration in `cfg.services[cfg.service]` — so the hold and the server can never disagree
48
+ * about which socket they are trading.
49
+ *
50
+ * A bind failure here (EADDRINUSE above all) throws to the caller and must be treated as fatal:
51
+ * a process that continues past it ends the boot with nothing listening and nothing holding the
52
+ * event loop, i.e. a clean exit 0 while a predecessor keeps serving stale code. Name the error
53
+ * and exit non-zero — that is what makes a supervisor reclaim the port instead of respawning
54
+ * into it.
55
+ */
56
+ export const holdApiPort = async (
57
+ cfg: ServerConfig, opts: ApiPortHoldOptions = {}
58
+ ): Promise<ApiPortHold> => {
59
+ const config = cfg.services[cfg.service]
60
+ const port = config?.internalPort ?? config?.port ?? PORT
61
+ const host = config?.opened === true ? OPENED_HOST : CLOSED_HOST
62
+
63
+ const payload = opts.payload ?? (() => ({ status: 'OK' }))
64
+
65
+ // Quiet and disposable: no logger, no plugins, and connections are force-closed on release so
66
+ // the handover to the real server is bounded rather than waiting out a keep-alive.
67
+ const server = Fastify({ logger: false, forceCloseConnections: true })
68
+
69
+ if (opts.okPath != null) {
70
+ server.all(opts.okPath, async (_request, reply) => {
71
+ return await reply.code(200).send(payload())
72
+ })
73
+ }
74
+ server.setNotFoundHandler(async (_request, reply) => {
75
+ return await reply.code(503).send(payload())
76
+ })
77
+
78
+ await server.listen({ port, host })
79
+ console.log(`api-server: holding ${host}:${port} for the boot${opts.okPath != null ? ` (${opts.okPath})` : ''}`)
80
+
81
+ return {
82
+ release: async () => { await server.close() },
83
+ }
84
+ }
package/src/index.ts CHANGED
@@ -4,3 +4,5 @@ export * from './server.js'
4
4
  export * from './consts.js'
5
5
  export * from './errors.js'
6
6
  export * from './helper.js'
7
+ export * from './hold.js'
8
+ export * from './protocol.js'
@@ -0,0 +1,185 @@
1
+ import { assertContext } from '@owlmeans/context'
2
+ import type { BasicConfig, BasicContext } from '@owlmeans/context'
3
+ import { EntrypointOutcome } from '@owlmeans/entrypoint'
4
+ import type {
5
+ BodyOf, EntrypointProtocolDeclaration, HandlerRequest, OpenRequest, OpenValue, ParamsOf, RequestOf, ResponseOf,
6
+ } from '@owlmeans/entrypoint'
7
+ import type { AbstractRequest } from '@owlmeans/entrypoint'
8
+ import type { BoundEntrypointHandler } from '@owlmeans/server-entrypoint'
9
+ import { HandlerMisconfiguredError } from './errors.js'
10
+
11
+ /**
12
+ * True for a response the declaration left with no compile-time contract: `typed<any>()` (an
13
+ * `[any] extends [X]` conditional does not produce `any`'s usual both-branches union once the
14
+ * checked type is wrapped in a tuple, so it resolves to a single branch like any other type) and
15
+ * a response inferred as bare `typed()` with nothing to infer from, which resolves to `undefined`
16
+ * with no shape to validate a handler's return against — the same signal a zero-argument
17
+ * `contract()` produces for a genuinely response-less route. Neither means "this handler must
18
+ * return void": it means the declaration did not constrain the response, so the handler is free to
19
+ * return whatever its route actually sends.
20
+ */
21
+ type IsUntypedResponse<T> = 0 extends (1 & T) ? true : [T] extends [undefined] ? true : false
22
+
23
+ /**
24
+ * The type a bound handler is allowed to return for a given protocol response.
25
+ *
26
+ * A concretely typed or schema-backed `Response` is returned unchanged — the handler must produce
27
+ * exactly that shape. An untyped one (see `IsUntypedResponse` above) relaxes to `any`: the
28
+ * declaration made no promise about the response, so nothing here should force a handler bound to
29
+ * it into returning `void`.
30
+ */
31
+ type HandlerResponse<Response> = IsUntypedResponse<Response> extends true ? any : Response
32
+ type MaybePromise<Value> = Value | Promise<Value>
33
+ type BodyProtocol<Protocol extends EntrypointProtocolDeclaration> = RequestOf<Protocol> extends { body: OpenValue }
34
+ ? Protocol : never
35
+ type ParamsProtocol<Protocol extends EntrypointProtocolDeclaration> = RequestOf<Protocol> extends { params: object }
36
+ ? Protocol : never
37
+
38
+ interface ContextCarrier<Context> {
39
+ _ctx?: Context
40
+ }
41
+
42
+ const contextFor = <Context extends BasicContext<BasicConfig>>(
43
+ request: AbstractRequest,
44
+ fallback: Context,
45
+ ): Context => {
46
+ const original = request.original
47
+ if (original != null && typeof original === 'object' && '_ctx' in original) {
48
+ return (original as ContextCarrier<Context>)._ctx ?? fallback
49
+ }
50
+
51
+ return fallback
52
+ }
53
+
54
+ const bind = <Protocol extends EntrypointProtocolDeclaration, Context extends BasicContext<BasicConfig>>(
55
+ protocol: Protocol,
56
+ execute: (request: HandlerRequest<RequestOf<Protocol>>, context: Context) => MaybePromise<HandlerResponse<ResponseOf<Protocol>>>,
57
+ ): BoundEntrypointHandler<Protocol> => ({
58
+ protocol,
59
+ bind: ref => async (request, response) => {
60
+ const fallback = assertContext<BasicConfig, Context>(ref.ref?.ctx, protocol.alias)
61
+
62
+ try {
63
+ const typedRequest = (request as HandlerRequest<OpenRequest>) as HandlerRequest<RequestOf<Protocol>>
64
+ const value = await execute(
65
+ typedRequest,
66
+ contextFor(request, fallback),
67
+ )
68
+ response.resolve(value as ResponseOf<Protocol>, EntrypointOutcome.Ok)
69
+ } catch (error) {
70
+ response.reject(error as Error)
71
+ }
72
+
73
+ return response.value
74
+ },
75
+ })
76
+
77
+ /** Structural, not `instanceof`: a `BoundEntrypointHandler` crosses no class boundary a runtime check could use. */
78
+ type AnyBoundHandler = BoundEntrypointHandler<EntrypointProtocolDeclaration>
79
+
80
+ /**
81
+ * `value` is shaped like a `BoundEntrypointHandler` — never a plain function, which also carries
82
+ * its own `.bind` and would otherwise pass a `typeof value.bind === 'function'` check alone.
83
+ */
84
+ const isBoundHandler = (value: unknown): value is AnyBoundHandler =>
85
+ typeof value === 'object' && value != null
86
+ && typeof (value as { bind?: unknown }).bind === 'function'
87
+ && (value as { protocol?: unknown }).protocol != null
88
+
89
+ const warnedAliases = new Set<string>()
90
+
91
+ /**
92
+ * What `body`/`params`/`request` do with something that is not the plain callback they declare —
93
+ * the shape a handler module wraps its own export in when it is bound TWICE. `null` means the
94
+ * second argument really is a callback and the caller should wrap it as usual.
95
+ *
96
+ * A handler bound to THIS protocol is returned unchanged, with a one-time warning: the module
97
+ * already produced a working `BoundEntrypointHandler`, and re-wrapping it here would only wrap it
98
+ * again — returning it as-is is what makes `bind(protocol, api.body(protocol, alreadyBound))`
99
+ * behave exactly like `bind(protocol, alreadyBound)`, which is what a wrap-once file looks like at
100
+ * this call site. Anything else — a handler bound to a DIFFERENT protocol, or a value that is
101
+ * neither a function nor a bound handler at all — answers every request on this route with
102
+ * {@link HandlerMisconfiguredError} instead of throwing `TypeError: handler is not a function`
103
+ * out of the request pipeline's own `try`, where the type name and the alias it happened on are
104
+ * both lost.
105
+ */
106
+ const toleratedHandler = <Protocol extends EntrypointProtocolDeclaration>(
107
+ protocol: Protocol, handler: unknown
108
+ ): BoundEntrypointHandler<Protocol> | null => {
109
+ if (typeof handler === 'function') return null
110
+
111
+ if (isBoundHandler(handler)) {
112
+ if (handler.protocol.alias === protocol.alias) {
113
+ if (!warnedAliases.has(protocol.alias)) {
114
+ warnedAliases.add(protocol.alias)
115
+ console.warn(
116
+ `[server-api] ${protocol.alias}: handler is already bound — pass it to bind() directly; `
117
+ + 'wrapping it again here is a type error (TS2345 "BoundEntrypointHandler<…> is not '
118
+ + 'assignable"), tolerated at runtime for a project generated before the wrap-once rule.'
119
+ )
120
+ }
121
+
122
+ return handler as unknown as BoundEntrypointHandler<Protocol>
123
+ }
124
+
125
+ return bind<Protocol, BasicContext<BasicConfig>>(protocol, () => {
126
+ throw new HandlerMisconfiguredError(
127
+ `${protocol.alias}: handler is bound to a different protocol ('${handler.protocol.alias}')`
128
+ )
129
+ })
130
+ }
131
+
132
+ return bind<Protocol, BasicContext<BasicConfig>>(protocol, () => {
133
+ throw new HandlerMisconfiguredError(`${protocol.alias}: handler is not a function`)
134
+ })
135
+ }
136
+
137
+ /**
138
+ * Make server handlers that infer request sections and response values from their protocol.
139
+ * The protocol is passed once; application callbacks never name request or reply generics.
140
+ */
141
+ export const handlers = <Context extends BasicContext<BasicConfig>>() => ({
142
+ body: <Protocol extends EntrypointProtocolDeclaration>(
143
+ protocol: Protocol,
144
+ handler: Protocol extends BodyProtocol<Protocol> ? (
145
+ payload: BodyOf<Protocol>,
146
+ context: Context,
147
+ request: HandlerRequest<RequestOf<Protocol>>,
148
+ ) => MaybePromise<HandlerResponse<ResponseOf<Protocol>>>
149
+ : never,
150
+ ): BoundEntrypointHandler<Protocol> => toleratedHandler(protocol, handler) ?? bind<Protocol, Context>(protocol, (request, context) =>
151
+ (handler as (
152
+ payload: BodyOf<Protocol>, context: Context, request: HandlerRequest<RequestOf<Protocol>>,
153
+ ) => MaybePromise<HandlerResponse<ResponseOf<Protocol>>>)(request.body as BodyOf<Protocol>, context, request)),
154
+
155
+ params: <Protocol extends EntrypointProtocolDeclaration>(
156
+ protocol: Protocol,
157
+ handler: Protocol extends ParamsProtocol<Protocol> ? (
158
+ payload: ParamsOf<Protocol>,
159
+ context: Context,
160
+ request: HandlerRequest<RequestOf<Protocol>>,
161
+ ) => MaybePromise<HandlerResponse<ResponseOf<Protocol>>>
162
+ : never,
163
+ ): BoundEntrypointHandler<Protocol> => toleratedHandler(protocol, handler) ?? bind<Protocol, Context>(protocol, (request, context) =>
164
+ (handler as (
165
+ payload: ParamsOf<Protocol>, context: Context, request: HandlerRequest<RequestOf<Protocol>>,
166
+ ) => MaybePromise<HandlerResponse<ResponseOf<Protocol>>>)(request.params as ParamsOf<Protocol>, context, request)),
167
+
168
+ request: <Protocol extends EntrypointProtocolDeclaration>(
169
+ protocol: Protocol,
170
+ handler: (
171
+ request: HandlerRequest<RequestOf<Protocol>>,
172
+ context: Context,
173
+ ) => MaybePromise<HandlerResponse<ResponseOf<Protocol>>>,
174
+ ): BoundEntrypointHandler<Protocol> => toleratedHandler(protocol, handler) ?? bind<Protocol, Context>(protocol, handler),
175
+ })
176
+
177
+ /** Access a Fastify-specific upload through an explicit boundary helper, never `request.original`. */
178
+ export const uploadedFile = async (
179
+ request: HandlerRequest<{ body: object }>,
180
+ ): Promise<import('@fastify/multipart').MultipartFile | undefined> => {
181
+ const original = (request as AbstractRequest).original
182
+ if (original == null || typeof original !== 'object' || !('file' in original)) return undefined
183
+
184
+ return (original as import('fastify').FastifyRequest).file()
185
+ }
package/src/server.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
2
2
  import type { ApiServer, ApiServerAppend } from './types.js'
3
- import { Layer, assertContext, createService } from '@owlmeans/context'
3
+ import { assertContext, createService } from '@owlmeans/context'
4
4
  import { canServeModule, executeResponse, provideRequest } from './utils/index.js'
5
5
  import { DEFAULT_ALIAS, CLOSED_HOST, PORT, OPENED_HOST } from './consts.js'
6
6
  import type { ServerEntrypoint } from '@owlmeans/server-entrypoint'
@@ -57,8 +57,6 @@ export const createApiServer = (alias: string): ApiServer => {
57
57
  }*/
58
58
  }),
59
59
 
60
- layers: [Layer.System],
61
-
62
60
  listen: async () => {
63
61
  const context = _assertContext(service.ctx as Context)
64
62
 
@@ -133,10 +131,8 @@ export const createApiServer = (alias: string): ApiServer => {
133
131
  return context
134
132
  }
135
133
 
136
- // await module.route.resolve(context as any)
137
- await module.resolve()
138
- // Actually intermediate module can be created without handler by elevate function
139
- if (module.route.match(request) && module.handle != null) {
134
+ // An intermediate route can be created without a handler by the binding layer.
135
+ if (module.route.match(request, module.mount()) && module.handle != null) {
140
136
  const response = provideResponse(reply)
141
137
  const currentRequest = provideRequest(module.alias, request, true)
142
138
  currentRequest.original._ctx = context
@@ -150,42 +146,38 @@ export const createApiServer = (alias: string): ApiServer => {
150
146
  }, Promise.resolve(context))
151
147
  })
152
148
 
153
- await Promise.all(
154
- context.entrypoints<ServerEntrypoint<FastifyRequest>>()
155
- .filter(module => canServeModule(context, module) && !module.route.isIntermediate())
156
- .map(async module => {
157
- // await module.route.resolve(context as any)
158
- await module.resolve()
159
- const method = module.route.route.method ?? RouteMethod.GET
160
- if (module.handle == null) {
161
- return
162
- }
163
- server.route({
164
- url: module.getPath(), method,
165
- schema: {
166
- consumes: [
167
- 'application/json',
168
- 'application/x-www-form-urlencoded',
169
- 'multipart/form-data',
170
- ],
171
- querystring: fixFormatDates(module.filter?.query ?? {}),
172
- ...(
173
- [
174
- RouteMethod.POST,
175
- RouteMethod.PATCH,
176
- RouteMethod.PUT
177
- ].includes(method)
178
- ? { body: fixFormatDates(module.filter?.body ?? {}) }
179
- : {}
180
- ),
181
- params: fixFormatDates(module.filter?.params ?? {}),
182
- response: module.filter?.response,
183
- headers: fixFormatDates(module.filter?.headers ?? {})
184
- },
185
- handler: createServerHandler(module, location)
186
- })
149
+ context.entrypoints<ServerEntrypoint<FastifyRequest>>()
150
+ .filter(module => canServeModule(context, module) && !module.route.isIntermediate())
151
+ .forEach(module => {
152
+ const method = module.route.route.method ?? RouteMethod.GET
153
+ if (module.handle == null) {
154
+ return
155
+ }
156
+ server.route({
157
+ url: module.mount(), method,
158
+ schema: {
159
+ consumes: [
160
+ 'application/json',
161
+ 'application/x-www-form-urlencoded',
162
+ 'multipart/form-data',
163
+ ],
164
+ querystring: fixFormatDates(module.filter?.query ?? {}),
165
+ ...(
166
+ [
167
+ RouteMethod.POST,
168
+ RouteMethod.PATCH,
169
+ RouteMethod.PUT
170
+ ].includes(method)
171
+ ? { body: fixFormatDates(module.filter?.body ?? {}) }
172
+ : {}
173
+ ),
174
+ params: fixFormatDates(module.filter?.params ?? {}),
175
+ response: module.filter?.response,
176
+ headers: fixFormatDates(module.filter?.headers ?? {})
177
+ },
178
+ handler: createServerHandler(module, location)
187
179
  })
188
- )
180
+ })
189
181
 
190
182
  service.initialized = true
191
183
  })
@@ -208,4 +200,3 @@ export const appendApiServer = <C extends Config, T extends ServerContext<C>>(
208
200
  return context
209
201
  }
210
202
 
211
-
package/src/types.ts CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- import type { InitializedService, Layer } from '@owlmeans/context'
2
+ import type { InitializedService } from '@owlmeans/context'
3
3
  import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
4
4
  import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
5
5
  import '@fastify/middie/types/index.d.ts'
@@ -7,8 +7,6 @@ import '@fastify/middie/types/index.d.ts'
7
7
  export interface ApiServer extends InitializedService {
8
8
  server: FastifyInstance
9
9
 
10
- layers: [Layer.System]
11
-
12
10
  listen: () => Promise<void>
13
11
  }
14
12
 
@@ -1,14 +1,31 @@
1
1
  import { FORBIDDEN_ERROR, SERVER_ERROR, UNAUTHORIZED_ERROR } from '@owlmeans/api'
2
2
  import type { FastifyReply } from 'fastify'
3
3
  import { AccessError, AuthFailedError } from '../errors.js'
4
+ import { AuthForbidden, AuthorizationError } from '@owlmeans/auth'
4
5
  import { ResilientError } from '@owlmeans/error'
5
6
 
7
+ /**
8
+ * Map a thrown error onto an HTTP status.
9
+ *
10
+ * Two families reach here and both must be recognised. `AuthFailedError` / `AccessError` are this
11
+ * package's own, raised by the request pipeline itself. `AuthorizationError` / `AuthForbidden`
12
+ * come from `@owlmeans/auth` and are what the guards and gates actually throw — an unrecognised
13
+ * one answers 500, which reports a refused request as a crashed server: the client cannot tell
14
+ * "sign in again" from "the service is broken", and a consumer watching statuses concludes the
15
+ * application fell over.
16
+ *
17
+ * **Order matters.** `AuthForbidden extends AuthorizationError`, so the 403 branch has to be
18
+ * tested first or every refusal of a permission is reported as a failure to authenticate.
19
+ */
6
20
  export const handleError = (error: Error, reply: FastifyReply) => {
7
21
  let code: number = SERVER_ERROR
8
- if (error instanceof AuthFailedError) {
9
- code = UNAUTHORIZED_ERROR
10
- } else if (error instanceof AccessError) {
22
+ if (error instanceof AuthForbidden || error instanceof AccessError) {
23
+ // An established identity that lacks the permission. Re-authenticating changes nothing.
11
24
  code = FORBIDDEN_ERROR
25
+ } else if (error instanceof AuthorizationError || error instanceof AuthFailedError) {
26
+ // No usable credential — absent, expired, revoked, or naming a session this server no longer
27
+ // holds. The caller is told to sign in, not that signing in would not help.
28
+ code = UNAUTHORIZED_ERROR
12
29
  }
13
30
  if (!reply.sent) {
14
31
  reply.code(code).send(
@@ -1,4 +1,3 @@
1
- import { isContextWithoutIds, Layer } from '@owlmeans/context'
2
1
  import type { FastifyReply, FastifyRequest } from 'fastify'
3
2
  import type { ServerEntrypoint } from '@owlmeans/server-entrypoint'
4
3
  import type { GuardService } from '@owlmeans/entrypoint'
@@ -7,6 +6,7 @@ import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
7
6
  import { executeResponse, provideRequest } from './payload.js'
8
7
  import { AuthFailedError } from '../errors.js'
9
8
  import type { Auth } from '@owlmeans/auth'
9
+ import { attachEntity } from '@owlmeans/auth-common'
10
10
 
11
11
  type Config = ServerConfig
12
12
  interface Context<C extends Config = Config> extends ServerContext<C> { }
@@ -50,22 +50,15 @@ export const authorize = async <C extends Config, T extends Context<C>>(
50
50
  (req as any)._auth = request.auth
51
51
  }
52
52
 
53
- if (request.auth?.entityId != null) {
54
- // @TODO Probably we need to downgrade context in this case
55
- if (!isContextWithoutIds(context as any)) {
56
- throw SyntaxError(`Context should be without ids during authorization ${context.cfg.layer}:${context.cfg.layerId}`)
57
- }
58
-
59
- if (isContextWithoutIds(context as any) && context.cfg.layer !== Layer.Service) {
60
- context = await context.updateContext(undefined, Layer.Service)
61
- await context.waitForInitialized()
62
- }
63
- context = await context.updateContext(request.auth.entityId, Layer.Entity)
64
- await context.waitForInitialized()
65
-
66
- // We elevate module to the context level if it was changed
67
- module = context.entrypoint(module.alias)
68
- await module.resolve()
53
+ // The token names the organization by slug; everything downstream — grants, records, minted
54
+ // infrastructure names — keys on the entity's stable id. Resolving here, once, is what keeps a
55
+ // rename from being a sweep of every handler: the id arrives on the request, and a slug that
56
+ // has since been retired still resolves to the entity that retired it.
57
+ const entity = await attachEntity(context, request)
58
+ if (entity != null) {
59
+ // Carried on the raw request the same way `_auth` is, so the request the handler is given
60
+ // later — a different object, built after this runs — sees the same resolution.
61
+ ;(req as any)._entity = entity
69
62
  }
70
63
  }
71
64
  // Update context in request object
@@ -9,6 +9,9 @@ export const provideRequest = (alias: string, req: Request, provision?: boolean)
9
9
  return {
10
10
  alias,
11
11
  auth: (req as any)._auth ?? undefined,
12
+ // Resolved once by `authorize` and carried by reference, exactly like `_auth`, so a handler
13
+ // reached through any path sees the same entity the guard admitted.
14
+ entity: (req as any)._entity ?? undefined,
12
15
  params: req.params as Record<string, string | number | undefined | null>,
13
16
  body: req.body as Record<string, any>,
14
17
  headers: req.headers,
@@ -23,7 +23,10 @@ export const canServeModule = (context: Context, module: CommonEntrypoint): modu
23
23
  if (module.route.route.service != null && module.route.route.service !== context.cfg.service) {
24
24
  return false
25
25
  }
26
- if (module.route.route.protocol === RouteProtocols.SOCKET) {
26
+ // Only the protocols HTTP actually carries. A socket is upgraded elsewhere and a queued job is
27
+ // taken off the broker by the worker — mounting either on the HTTP server would answer it twice.
28
+ if (module.route.route.protocol === RouteProtocols.SOCKET
29
+ || module.route.route.protocol === RouteProtocols.QUEUE) {
27
30
  return false
28
31
  }
29
32
 
@@ -0,0 +1,83 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import type { EntrypointProtocolDeclaration } from '@owlmeans/entrypoint'
3
+ import { handlers } from '../src/protocol.js'
4
+ import { HandlerMisconfiguredError } from '../src/errors.js'
5
+
6
+ /**
7
+ * A protocol-bound implementation is run with the smallest binding context the transport needs —
8
+ * same pattern as `@owlmeans/server-auth-token`'s own `handlers.spec.ts`.
9
+ */
10
+ const invoke = async (handler: any, context: any, req: any = {}): Promise<any> => {
11
+ const res: any = { resolve: (value: unknown) => { res.value = value }, reject: (e: Error) => { res.error = e } }
12
+ await handler.bind({ ref: { ctx: context } })(req, res)
13
+ if (res.error != null) throw res.error
14
+
15
+ return res.value
16
+ }
17
+
18
+ const protocolFor = (alias: string): EntrypointProtocolDeclaration =>
19
+ ({ alias } as unknown as EntrypointProtocolDeclaration)
20
+
21
+ const context = { alias: 'test-context' } as any
22
+ const api = handlers<any>()
23
+
24
+ describe('@owlmeans/server-api — handlers() wrap-once tolerance', () => {
25
+ test('a plain function is wrapped once and called with the context', async () => {
26
+ const protocol = protocolFor('api.thing.plain')
27
+ const handler = api.request(protocol, async (_req: any, ctx: any) => ({ ok: true, ctx }))
28
+
29
+ const result = await invoke(handler, context, {})
30
+ expect(result).toEqual({ ok: true, ctx: context })
31
+ })
32
+
33
+ test('a handler already bound to the SAME protocol is returned unchanged by body/params/request and still answers', async () => {
34
+ for (const method of ['body', 'params', 'request'] as const) {
35
+ const protocol = protocolFor(`api.thing.${method}`)
36
+ const bound = api.request(protocol, async () => ({ from: method }))
37
+
38
+ const wrapped = (api as any)[method](protocol, bound)
39
+ expect(wrapped).toBe(bound)
40
+
41
+ const result = await invoke(wrapped, context, {})
42
+ expect(result).toEqual({ from: method })
43
+ }
44
+ })
45
+
46
+ test('a handler bound to a DIFFERENT protocol answers with HandlerMisconfiguredError', async () => {
47
+ const protocolA = protocolFor('api.thing.mismatch-a')
48
+ const protocolB = protocolFor('api.thing.mismatch-b')
49
+ const boundToA = api.request(protocolA, async () => ({ from: 'a' }))
50
+
51
+ const wrapped = api.request(protocolB, boundToA as any)
52
+ expect(wrapped).not.toBe(boundToA)
53
+ await expect(invoke(wrapped, context, {})).rejects.toThrow(HandlerMisconfiguredError)
54
+ })
55
+
56
+ test('a value that is neither a function nor a bound handler answers with HandlerMisconfiguredError', async () => {
57
+ const protocol = protocolFor('api.thing.not-a-function')
58
+ const wrapped = api.request(protocol, { not: 'a function' } as any)
59
+
60
+ await expect(invoke(wrapped, context, {})).rejects.toThrow(HandlerMisconfiguredError)
61
+ })
62
+
63
+ test('the double-wrap warning fires once per alias, not once per call', async () => {
64
+ const protocol = protocolFor('api.thing.warn-once')
65
+ const bound = api.request(protocol, async () => 'ok')
66
+
67
+ const warnings: unknown[][] = []
68
+ const original = console.warn
69
+ console.warn = (...args: unknown[]) => { warnings.push(args) }
70
+ try {
71
+ // Each call is a deliberate double wrap — the exact shape `tsc` rejects at the real call
72
+ // site (TS2345) — so it is exercised here through `any`, the same way `body`/`params`
73
+ // are reached dynamically above.
74
+ (api as any).request(protocol, bound);
75
+ (api as any).body(protocol, bound);
76
+ (api as any).params(protocol, bound)
77
+ } finally {
78
+ console.warn = original
79
+ }
80
+
81
+ expect(warnings.length).toBe(1)
82
+ })
83
+ })
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": [
3
+ "@owlmeans/dep-config/tsconfig.base.json",
4
+ "@owlmeans/dep-config/tsconfig.node.json"
5
+ ],
6
+ "compilerOptions": {
7
+ "types": ["bun"],
8
+ "rootDir": "../",
9
+ "noEmit": true
10
+ },
11
+ "include": ["./**/*", "../src/**/*"]
12
+ }
package/tsconfig.json CHANGED
@@ -10,6 +10,7 @@
10
10
  "exclude": [
11
11
  "./dist/**/*",
12
12
  "./build/**/*",
13
+ "./tests/**/*",
13
14
  "./*.ts"
14
15
  ]
15
16
  }
package/build/.gitkeep DELETED
File without changes