@owlmeans/server-api 0.1.18-rc.5 → 0.1.18-rc.50
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.
- package/README.md +202 -46
- package/agent-meta/manifest.json +2 -2
- package/agent-meta/skills/server-api/SKILL.md +128 -22
- package/build/consts.local.d.ts +2 -0
- package/build/consts.local.d.ts.map +1 -0
- package/build/consts.local.js +2 -0
- package/build/consts.local.js.map +1 -0
- package/build/errors.d.ts +12 -0
- package/build/errors.d.ts.map +1 -1
- package/build/errors.js +16 -0
- package/build/errors.js.map +1 -1
- package/build/helper.d.ts +3 -6
- package/build/helper.d.ts.map +1 -1
- package/build/helper.js +10 -1
- package/build/helper.js.map +1 -1
- package/build/hold.d.ts +35 -0
- package/build/hold.d.ts.map +1 -0
- package/build/hold.js +57 -0
- package/build/hold.js.map +1 -0
- package/build/index.d.ts +2 -0
- package/build/index.d.ts.map +1 -1
- package/build/index.js +2 -0
- package/build/index.js.map +1 -1
- package/build/protocol.d.ts +18 -0
- package/build/protocol.d.ts.map +1 -0
- package/build/protocol.js +87 -0
- package/build/protocol.js.map +1 -0
- package/build/server.d.ts +2 -3
- package/build/server.d.ts.map +1 -1
- package/build/server.js +37 -32
- package/build/server.js.map +1 -1
- package/build/types.d.ts +31 -2
- package/build/types.d.ts.map +1 -1
- package/build/types.local.d.ts +38 -0
- package/build/types.local.d.ts.map +1 -0
- package/build/types.local.js +2 -0
- package/build/types.local.js.map +1 -0
- package/build/utils/consts.d.ts +2 -0
- package/build/utils/consts.d.ts.map +1 -0
- package/build/utils/consts.js +2 -0
- package/build/utils/consts.js.map +1 -0
- package/build/utils/consts.local.d.ts +5 -0
- package/build/utils/consts.local.d.ts.map +1 -0
- package/build/utils/consts.local.js +5 -0
- package/build/utils/consts.local.js.map +1 -0
- package/build/utils/error.d.ts +47 -1
- package/build/utils/error.d.ts.map +1 -1
- package/build/utils/error.js +192 -9
- package/build/utils/error.js.map +1 -1
- package/build/utils/guards.d.ts +1 -5
- package/build/utils/guards.d.ts.map +1 -1
- package/build/utils/guards.js +11 -15
- package/build/utils/guards.js.map +1 -1
- package/build/utils/index.d.ts +2 -0
- package/build/utils/index.d.ts.map +1 -1
- package/build/utils/index.js +1 -0
- package/build/utils/index.js.map +1 -1
- package/build/utils/log.d.ts +11 -0
- package/build/utils/log.d.ts.map +1 -0
- package/build/utils/log.js +57 -0
- package/build/utils/log.js.map +1 -0
- package/build/utils/payload.d.ts.map +1 -1
- package/build/utils/payload.js +6 -2
- package/build/utils/payload.js.map +1 -1
- package/build/utils/server.d.ts +3 -6
- package/build/utils/server.d.ts.map +1 -1
- package/build/utils/server.js +8 -9
- package/build/utils/server.js.map +1 -1
- package/build/utils/types.d.ts +18 -0
- package/build/utils/types.d.ts.map +1 -0
- package/build/utils/types.js +2 -0
- package/build/utils/types.js.map +1 -0
- package/build/utils/types.local.d.ts +9 -0
- package/build/utils/types.local.d.ts.map +1 -0
- package/build/utils/types.local.js +2 -0
- package/build/utils/types.local.js.map +1 -0
- package/package.json +22 -18
- package/src/consts.local.ts +1 -0
- package/src/errors.ts +18 -0
- package/src/helper.ts +13 -8
- package/src/hold.ts +66 -0
- package/src/index.ts +2 -0
- package/src/protocol.ts +149 -0
- package/src/server.ts +67 -67
- package/src/types.local.ts +44 -0
- package/src/types.ts +38 -4
- package/src/utils/consts.local.ts +7 -0
- package/src/utils/consts.ts +1 -0
- package/src/utils/error.ts +213 -11
- package/src/utils/guards.ts +12 -22
- package/src/utils/index.ts +2 -0
- package/src/utils/log.ts +62 -0
- package/src/utils/payload.ts +6 -2
- package/src/utils/server.ts +12 -17
- package/src/utils/types.local.ts +12 -0
- package/src/utils/types.ts +18 -0
- package/tests/error-status.spec.ts +349 -0
- package/tests/handlers.spec.ts +83 -0
- package/tests/json-body.spec.ts +72 -0
- package/tests/log-adapter.spec.ts +52 -0
- package/tests/tsconfig.json +12 -0
- package/tsconfig.json +1 -0
- package/build/.gitkeep +0 -0
package/src/types.ts
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
|
|
2
|
-
import type { InitializedService
|
|
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'
|
|
6
|
+
import type { MultipartFile } from '@fastify/multipart'
|
|
6
7
|
|
|
7
8
|
export interface ApiServer extends InitializedService {
|
|
8
9
|
server: FastifyInstance
|
|
9
10
|
|
|
10
|
-
layers: [Layer.System]
|
|
11
|
-
|
|
12
11
|
listen: () => Promise<void>
|
|
13
12
|
}
|
|
14
13
|
|
|
@@ -20,7 +19,42 @@ export interface ApiServerAppend {
|
|
|
20
19
|
getApiServer: () => ApiServer
|
|
21
20
|
}
|
|
22
21
|
|
|
23
|
-
export
|
|
22
|
+
export type HttpErrorExposure = 'production' | 'development'
|
|
23
|
+
|
|
24
|
+
export interface HttpErrorsConfig {
|
|
25
|
+
/** Production is the safe default; development is the only mode that exposes stacks. */
|
|
26
|
+
exposure?: HttpErrorExposure
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface HttpConfig {
|
|
30
|
+
errors?: HttpErrorsConfig
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface Config extends ServerConfig {
|
|
34
|
+
http?: HttpConfig
|
|
35
|
+
}
|
|
24
36
|
|
|
25
37
|
export interface Context<C extends Config = Config> extends ServerContext<C>,
|
|
26
38
|
ApiServerAppend { }
|
|
39
|
+
|
|
40
|
+
export interface UploadedFile extends MultipartFile { }
|
|
41
|
+
|
|
42
|
+
export interface ApiPortHoldOptions {
|
|
43
|
+
/**
|
|
44
|
+
* The one path answered 200 while the hold is in place — the app's health endpoint, so
|
|
45
|
+
* whatever supervises the process keeps a conventional liveness answer through the boot.
|
|
46
|
+
* Everything else answers 503 with the same body. Absent, everything is 503.
|
|
47
|
+
*/
|
|
48
|
+
okPath?: string
|
|
49
|
+
/** Body of every answer, evaluated per request so a changing boot phase is reported live. */
|
|
50
|
+
payload?: () => unknown
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ApiPortHold {
|
|
54
|
+
/**
|
|
55
|
+
* Free the port for the real server. Awaits the actual close — `listen()` follows immediately,
|
|
56
|
+
* and a predecessor still bound makes it throw — and force-closes keep-alive sockets, so a
|
|
57
|
+
* supervisor's own poller cannot hold the release open.
|
|
58
|
+
*/
|
|
59
|
+
release: () => Promise<void>
|
|
60
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const INCIDENT_ID_HEADER = 'X-Incident-ID'
|
package/src/utils/error.ts
CHANGED
|
@@ -1,18 +1,220 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
FORBIDDEN_ERROR, SERVER_ERROR, UNAUTHORIZED_ERROR, DENIAL_KIND_HEADER, ACCESS_DENIED_KIND,
|
|
3
|
+
} from '@owlmeans/api'
|
|
2
4
|
import type { FastifyReply } from 'fastify'
|
|
3
5
|
import { AccessError, AuthFailedError } from '../errors.js'
|
|
4
|
-
import {
|
|
6
|
+
import { AuthForbidden, AuthorizationError } from '@owlmeans/auth'
|
|
7
|
+
import { isResilientError, ResilientError, SEPARATOR } from '@owlmeans/error'
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
import { logger } from '@owlmeans/log'
|
|
10
|
+
import type { Config, HttpErrorExposure } from '../types.js'
|
|
11
|
+
import { CLIENT_ERROR_FIRST, CLIENT_ERROR_LAST, SERVER_ERROR_FIRST, SERVER_ERROR_LAST } from './consts.local.js'
|
|
12
|
+
import { INCIDENT_ID_HEADER } from './consts.js'
|
|
13
|
+
import type { HttpStatusDeclaration, SerializedHttpError } from './types.js'
|
|
5
14
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The HTTP status an error's class declares, or `null` when it declares none that may be honoured.
|
|
18
|
+
*
|
|
19
|
+
* Read through the constructor chain — a static property is inherited, so a subclass answers what
|
|
20
|
+
* its nearest declaring ancestor says, and redeclares to change it. An integer 4xx is honoured
|
|
21
|
+
* directly. A 5xx is honoured only with `allowServerErrorStatus = true`, so a domain class must
|
|
22
|
+
* explicitly opt in to exposing a precise availability response. The read is structural, so a
|
|
23
|
+
* class from a duplicate module copy declares exactly what the imported one does.
|
|
24
|
+
*/
|
|
25
|
+
export const declaredErrorStatus = (error: unknown): number | null => {
|
|
26
|
+
if (error == null || typeof error !== 'object') {
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
const declaration = error.constructor as HttpStatusDeclaration | undefined
|
|
30
|
+
const status = declaration?.httpStatus
|
|
31
|
+
if (typeof status !== 'number' || !Number.isInteger(status)) {
|
|
32
|
+
return null
|
|
33
|
+
}
|
|
34
|
+
if (status >= CLIENT_ERROR_FIRST && status <= CLIENT_ERROR_LAST) return status
|
|
35
|
+
if (status >= SERVER_ERROR_FIRST && status <= SERVER_ERROR_LAST
|
|
36
|
+
&& declaration?.allowServerErrorStatus === true) return status
|
|
37
|
+
|
|
38
|
+
return null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The registered type names an error carries: its own `type`, and the static `typeName` of every
|
|
43
|
+
* class on its constructor chain.
|
|
44
|
+
*
|
|
45
|
+
* This is how a class is recognised when `instanceof` cannot see it. A process that loads a package
|
|
46
|
+
* twice — `bun --preserve-symlinks` over a linked workspace resolves one package through several
|
|
47
|
+
* `node_modules` paths — holds several copies of every error class, and an error built by one copy
|
|
48
|
+
* is not an instance of another. The registered names are the same in every copy. A subclass's
|
|
49
|
+
* `typeName` does not reliably embed its parent's (`EntitlementRefusal` extends `AuthForbidden`), so
|
|
50
|
+
* a family is recognised by walking the chain and matching names exactly, never by a substring.
|
|
51
|
+
*/
|
|
52
|
+
const typeNamesOf = (error: object): Set<string> => {
|
|
53
|
+
const names = new Set<string>()
|
|
54
|
+
const type = (error as { type?: unknown }).type
|
|
55
|
+
if (typeof type === 'string') {
|
|
56
|
+
names.add(type)
|
|
57
|
+
}
|
|
58
|
+
let ctor: unknown = error.constructor
|
|
59
|
+
while (typeof ctor === 'function') {
|
|
60
|
+
const name = (ctor as { typeName?: unknown }).typeName
|
|
61
|
+
if (typeof name === 'string') {
|
|
62
|
+
names.add(name)
|
|
63
|
+
}
|
|
64
|
+
ctor = Object.getPrototypeOf(ctor)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return names
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const isOfFamily = (names: Set<string>, family: string[]): boolean =>
|
|
71
|
+
family.some(typeName => names.has(typeName))
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The HTTP status an error is answered with, read off the error exactly as given.
|
|
75
|
+
*
|
|
76
|
+
* Two families reach here and both must be recognised. `AuthFailedError` / `AccessError` are this
|
|
77
|
+
* package's own, raised by the request pipeline itself. `AuthorizationError` / `AuthForbidden`
|
|
78
|
+
* come from `@owlmeans/auth` and are what the guards and gates actually throw — an unrecognised
|
|
79
|
+
* one answers 500, which reports a refused request as a crashed server: the client cannot tell
|
|
80
|
+
* "sign in again" from "the service is broken", and a consumer watching statuses concludes the
|
|
81
|
+
* application fell over. A family member is recognised by class OR by registered type name
|
|
82
|
+
* ({@link typeNamesOf}), so a class from a duplicate module copy answers the same status.
|
|
83
|
+
*
|
|
84
|
+
* **Order matters.** `AuthForbidden extends AuthorizationError`, so the 403 branch has to be
|
|
85
|
+
* tested first or every refusal of a permission is reported as a failure to authenticate. Both
|
|
86
|
+
* auth branches come before a class's own declaration, so an auth refusal can never be restated
|
|
87
|
+
* as something else. Everything that is neither an auth error nor a class declaring an allowed
|
|
88
|
+
* {@link declaredErrorStatus} answers 500.
|
|
89
|
+
*/
|
|
90
|
+
export const errorStatus = (error: unknown): number => {
|
|
91
|
+
if (error == null || typeof error !== 'object') {
|
|
92
|
+
return SERVER_ERROR
|
|
93
|
+
}
|
|
94
|
+
const names = typeNamesOf(error)
|
|
95
|
+
if (error instanceof AuthForbidden || error instanceof AccessError
|
|
96
|
+
|| isOfFamily(names, [AuthForbidden.typeName, AccessError.typeName])) {
|
|
97
|
+
// An established identity that lacks the permission. Re-authenticating changes nothing.
|
|
98
|
+
return FORBIDDEN_ERROR
|
|
99
|
+
}
|
|
100
|
+
if (error instanceof AuthorizationError || error instanceof AuthFailedError
|
|
101
|
+
|| isOfFamily(names, [AuthorizationError.typeName, AuthFailedError.typeName])) {
|
|
102
|
+
// No usable credential — absent, expired, revoked, or naming a session this server no longer
|
|
103
|
+
// holds. The caller is told to sign in, not that signing in would not help.
|
|
104
|
+
return UNAUTHORIZED_ERROR
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return declaredErrorStatus(error) ?? SERVER_ERROR
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Invalid or absent configuration always resolves to the production-safe policy. */
|
|
111
|
+
export const errorExposure = (config?: Pick<Config, 'http'>): HttpErrorExposure =>
|
|
112
|
+
config?.http?.errors?.exposure === 'development' ? 'development' : 'production'
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Preserve a typed/marshalled error when possible without asking `ensure` to convert a plain
|
|
116
|
+
* error. In particular, `ensure` deliberately rethrows SyntaxError; an HTTP boundary still has
|
|
117
|
+
* to serialize it safely and let the incident log retain the original object.
|
|
118
|
+
*/
|
|
119
|
+
const normalizeForWire = (error: Error): Error => {
|
|
120
|
+
if (error instanceof SyntaxError || isResilientError(error)) {
|
|
121
|
+
return error
|
|
122
|
+
}
|
|
123
|
+
if (error.message.includes(SEPARATOR)) {
|
|
124
|
+
const ensured = ResilientError.ensure(error)
|
|
125
|
+
// The catch-all converter's legacy constructor shape shifts an ordinary error's fields.
|
|
126
|
+
// Only keep `ensure`'s result when a registered wire prefix actually rebuilt something.
|
|
127
|
+
if (ensured.type !== error.message || ensured.message !== error.stack) {
|
|
128
|
+
return ensured
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return error
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** One central wire shape for every server error. */
|
|
135
|
+
export const serializeError = (
|
|
136
|
+
error: Error, exposure: HttpErrorExposure = 'production'
|
|
137
|
+
): SerializedHttpError => {
|
|
138
|
+
const normalized = normalizeForWire(error)
|
|
139
|
+
const thrown = errorStatus(error)
|
|
140
|
+
const status = thrown !== SERVER_ERROR ? thrown : errorStatus(normalized)
|
|
141
|
+
const incidentId = randomUUID()
|
|
142
|
+
// The server log owns every diagnostic. Production callers receive only its correlation key;
|
|
143
|
+
// development keeps the typed wire form so local clients can retain their usual error details.
|
|
144
|
+
Object.assign(error, { incidentId })
|
|
145
|
+
if (isResilientError(normalized)) normalized.incidentId = incidentId
|
|
146
|
+
const body = exposure === 'production'
|
|
147
|
+
? incidentId
|
|
148
|
+
: ResilientError.marshal(normalized, { includeStack: true, incidentId }).message
|
|
149
|
+
|
|
150
|
+
return { status, body, incidentId }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Apply safe response metadata carried by an error without coupling its package to Fastify. */
|
|
154
|
+
export const applyErrorHeaders = (error: unknown, reply: FastifyReply): void => {
|
|
155
|
+
if (error == null || typeof error !== 'object') {
|
|
156
|
+
return
|
|
12
157
|
}
|
|
158
|
+
const retryAfter = (error as { retryAfter?: unknown }).retryAfter
|
|
159
|
+
if (typeof retryAfter === 'number' && Number.isFinite(retryAfter) && retryAfter > 0) {
|
|
160
|
+
reply.header('Retry-After', String(Math.ceil(retryAfter)))
|
|
161
|
+
}
|
|
162
|
+
// Match exact registered types. EntitlementRefusal also extends AuthForbidden but is a plan
|
|
163
|
+
// decision, not a person's IAM permission denial.
|
|
164
|
+
const type = (error as { type?: unknown }).type
|
|
165
|
+
if (type === AuthForbidden.typeName || type === AccessError.typeName) {
|
|
166
|
+
reply.header(DENIAL_KIND_HEADER, ACCESS_DENIED_KIND)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const http = logger('http')
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The one log entry of a failed request, by what the failure means:
|
|
174
|
+
*
|
|
175
|
+
* | Status | Level | Why |
|
|
176
|
+
* |---|---|---|
|
|
177
|
+
* | 5xx | error | a fault — the one entry that owns type, message and stack, keyed by the incident id |
|
|
178
|
+
* | 403 | warn, `access.forbidden` | an established identity was refused; worth an operator's eye |
|
|
179
|
+
* | 401 | debug, `auth.refused` | an absent or expired credential is the ordinary shape of a sign-in |
|
|
180
|
+
* | other 4xx | debug | the caller's mistake, not the server's |
|
|
181
|
+
*
|
|
182
|
+
* The method and path are logged; the query string is not — it can carry a token.
|
|
183
|
+
*/
|
|
184
|
+
const logFailure = (error: Error, reply: FastifyReply, status: number, incidentId: string): void => {
|
|
185
|
+
const request = reply.request
|
|
186
|
+
const where = { method: request?.method, path: request?.url?.split('?')[0], status, incidentId }
|
|
187
|
+
if (status >= SERVER_ERROR) {
|
|
188
|
+
http.error('Request failed', { err: error, ...where })
|
|
189
|
+
} else if (status === FORBIDDEN_ERROR) {
|
|
190
|
+
http.warn('Access forbidden', { type: (error as { type?: unknown }).type, message: error.message, ...where },
|
|
191
|
+
{ event: 'access.forbidden' })
|
|
192
|
+
} else if (status === UNAUTHORIZED_ERROR) {
|
|
193
|
+
http.debug('Authentication refused', { message: error.message, ...where }, { event: 'auth.refused' })
|
|
194
|
+
} else {
|
|
195
|
+
http.debug('Request refused', { message: error.message, ...where })
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Answer a thrown error: a status, and the marshalled `ResilientError` as the body.
|
|
201
|
+
*
|
|
202
|
+
* The status is resolved in two steps. The error AS THROWN comes first: it is the one object whose
|
|
203
|
+
* class is certainly the class that was raised, while `ResilientError.ensure` rebuilds through the
|
|
204
|
+
* registry of whichever `@owlmeans/error` copy this module loaded — under duplicate module copies
|
|
205
|
+
* that turns a perfectly recognisable auth refusal into a plain `ResilientError` answering 500.
|
|
206
|
+
* Only when the thrown error answers 500 is the ENSURED error asked, because the rebuild is what
|
|
207
|
+
* gives a status to a marshalled error that crossed a hop as a plain `Error`.
|
|
208
|
+
*/
|
|
209
|
+
export const handleError = (
|
|
210
|
+
error: Error, reply: FastifyReply, exposure: HttpErrorExposure = 'production'
|
|
211
|
+
) => {
|
|
13
212
|
if (!reply.sent) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
)
|
|
213
|
+
const serialized = serializeError(error, exposure)
|
|
214
|
+
applyErrorHeaders(error, reply)
|
|
215
|
+
logFailure(error, reply, serialized.status, serialized.incidentId)
|
|
216
|
+
reply.header(INCIDENT_ID_HEADER, serialized.incidentId)
|
|
217
|
+
.code(serialized.status)
|
|
218
|
+
.send(serialized.body)
|
|
17
219
|
}
|
|
18
220
|
}
|
package/src/utils/guards.ts
CHANGED
|
@@ -1,15 +1,12 @@
|
|
|
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
|
-
import type
|
|
5
|
-
import { provideResponse } from '@owlmeans/entrypoint'
|
|
6
|
-
import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
|
|
3
|
+
import { type GuardService, provideResponse } from '@owlmeans/entrypoint'
|
|
7
4
|
import { executeResponse, provideRequest } from './payload.js'
|
|
8
5
|
import { AuthFailedError } from '../errors.js'
|
|
9
6
|
import type { Auth } from '@owlmeans/auth'
|
|
7
|
+
import { attachEntity } from '@owlmeans/auth-common'
|
|
8
|
+
import type { Config, Context } from './types.local.js'
|
|
10
9
|
|
|
11
|
-
type Config = ServerConfig
|
|
12
|
-
interface Context<C extends Config = Config> extends ServerContext<C> { }
|
|
13
10
|
|
|
14
11
|
export const authorize = async <C extends Config, T extends Context<C>>(
|
|
15
12
|
context: T, module: ServerEntrypoint<FastifyRequest>,
|
|
@@ -50,22 +47,15 @@ export const authorize = async <C extends Config, T extends Context<C>>(
|
|
|
50
47
|
(req as any)._auth = request.auth
|
|
51
48
|
}
|
|
52
49
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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()
|
|
50
|
+
// The token names the organization by slug; everything downstream — grants, records, minted
|
|
51
|
+
// infrastructure names — keys on the entity's stable id. Resolving here, once, is what keeps a
|
|
52
|
+
// rename from being a sweep of every handler: the id arrives on the request, and a slug that
|
|
53
|
+
// has since been retired still resolves to the entity that retired it.
|
|
54
|
+
const entity = await attachEntity(context, request)
|
|
55
|
+
if (entity != null) {
|
|
56
|
+
// Carried on the raw request the same way `_auth` is, so the request the handler is given
|
|
57
|
+
// later — a different object, built after this runs — sees the same resolution.
|
|
58
|
+
;(req as any)._entity = entity
|
|
69
59
|
}
|
|
70
60
|
}
|
|
71
61
|
// Update context in request object
|
package/src/utils/index.ts
CHANGED
package/src/utils/log.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { FastifyBaseLogger } from 'fastify'
|
|
2
|
+
import { logger, type LogLevel, type Logger } from '@owlmeans/log'
|
|
3
|
+
import type { Severity } from './types.local.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What Fastify says about itself, mapped to what an operator needs at each level.
|
|
7
|
+
*
|
|
8
|
+
* Fastify writes a pair of `info` lines for EVERY request and one for each unknown route, and
|
|
9
|
+
* announces its own listening address. The server writes one `debug` record per request itself
|
|
10
|
+
* (`onResponse`), a failed request is classified once in `handleError`, and the listening line is
|
|
11
|
+
* `server.listening` — so these are dropped or lowered here, by their fixed wording, rather than by
|
|
12
|
+
* a Fastify option (`disableRequestLogging` is deprecated from 5.12, `logController` does not exist
|
|
13
|
+
* before it).
|
|
14
|
+
*/
|
|
15
|
+
const levelOf = (level: Severity, message: unknown): Severity | undefined => {
|
|
16
|
+
if (typeof message !== 'string' || level !== 'info') {
|
|
17
|
+
return level
|
|
18
|
+
}
|
|
19
|
+
if (message === 'incoming request' || message === 'request completed') {
|
|
20
|
+
return undefined
|
|
21
|
+
}
|
|
22
|
+
if (message.startsWith('Server listening at') || /^Route .* not found$/.test(message)) {
|
|
23
|
+
return 'debug'
|
|
24
|
+
}
|
|
25
|
+
return level
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A pino-shaped logger over `@owlmeans/log`, handed to Fastify as its `loggerInstance`.
|
|
30
|
+
*
|
|
31
|
+
* Fastify then logs through the process's own level, format and plugins instead of a second pino
|
|
32
|
+
* instance that ignores them. `(object, message)` and `(message)` are the two shapes Fastify and
|
|
33
|
+
* its plugins call with; an `err` in the object travels as the record's error.
|
|
34
|
+
*/
|
|
35
|
+
export const fastifyLogger = (log: Logger = logger('http'), bindings?: Record<string, unknown>): FastifyBaseLogger => {
|
|
36
|
+
const call = (requested: Severity) => (first: unknown, second?: unknown): void => {
|
|
37
|
+
const [object, message] = typeof first === 'string' || first instanceof Error
|
|
38
|
+
? [undefined, first] : [first, second]
|
|
39
|
+
const level = levelOf(requested, message)
|
|
40
|
+
if (level == null) {
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
const data = bindings != null && Object.keys(bindings).length > 0
|
|
44
|
+
? { ...bindings, ...(object != null && typeof object === 'object' ? object : {}) } : object
|
|
45
|
+
log[level](message == null ? '' : message instanceof Error ? message : String(message), data)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const adapter = {
|
|
49
|
+
get level(): string { return levelName(log) },
|
|
50
|
+
set level(_value: string) { /* the level belongs to the process, not to this server */ },
|
|
51
|
+
fatal: call('error'), error: call('error'), warn: call('warn'),
|
|
52
|
+
info: call('info'), debug: call('debug'), trace: call('debug'),
|
|
53
|
+
silent: () => undefined,
|
|
54
|
+
child: (extra: Record<string, unknown>) => fastifyLogger(log, { ...bindings, ...extra }),
|
|
55
|
+
}
|
|
56
|
+
return adapter as unknown as FastifyBaseLogger
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const levelName = (log: Logger): string => {
|
|
60
|
+
const order: LogLevel[] = ['debug', 'info', 'warn', 'error']
|
|
61
|
+
return order.find(level => log.enabled(level)) ?? 'silent'
|
|
62
|
+
}
|
package/src/utils/payload.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import { EntrypointOutcome } from '@owlmeans/entrypoint'
|
|
2
2
|
import type { AbstractResponse, AbstractRequest } from '@owlmeans/entrypoint'
|
|
3
3
|
import type { Request, Response } from '../types.js'
|
|
4
|
-
import { ACCEPTED, CREATED, OK
|
|
4
|
+
import { ACCEPTED, CREATED, OK } from '@owlmeans/api'
|
|
5
5
|
import type { AnySchemaObject } from 'ajv'
|
|
6
|
+
import { handleError } from './error.js'
|
|
6
7
|
|
|
7
8
|
export const provideRequest = (alias: string, req: Request, provision?: boolean): AbstractRequest => {
|
|
8
9
|
provision = provision ?? false
|
|
9
10
|
return {
|
|
10
11
|
alias,
|
|
11
12
|
auth: (req as any)._auth ?? undefined,
|
|
13
|
+
// Resolved once by `authorize` and carried by reference, exactly like `_auth`, so a handler
|
|
14
|
+
// reached through any path sees the same entity the guard admitted.
|
|
15
|
+
entity: (req as any)._entity ?? undefined,
|
|
12
16
|
params: req.params as Record<string, string | number | undefined | null>,
|
|
13
17
|
body: req.body as Record<string, any>,
|
|
14
18
|
headers: req.headers,
|
|
@@ -32,7 +36,7 @@ export const executeResponse = <T>(response: AbstractResponse<T>, reply: Respons
|
|
|
32
36
|
if (throwOnError ?? false) {
|
|
33
37
|
throw response.error
|
|
34
38
|
}
|
|
35
|
-
|
|
39
|
+
handleError(response.error, reply)
|
|
36
40
|
return true
|
|
37
41
|
} else if (response.outcome != null) {
|
|
38
42
|
switch (response.outcome) {
|
package/src/utils/server.ts
CHANGED
|
@@ -1,29 +1,27 @@
|
|
|
1
|
-
import { AppType } from '@owlmeans/context'
|
|
1
|
+
import { AppType, assertContext } from '@owlmeans/context'
|
|
2
2
|
import type { FastifyReply, FastifyRequest } from 'fastify'
|
|
3
|
-
import { assertContext } from '@owlmeans/context'
|
|
4
3
|
import type { FixerService, ServerEntrypoint } from '@owlmeans/server-entrypoint'
|
|
5
|
-
import type
|
|
6
|
-
import type { GateService } from '@owlmeans/entrypoint'
|
|
7
|
-
import { provideResponse } from '@owlmeans/entrypoint'
|
|
8
|
-
import type { ServerContext, ServerConfig } from '@owlmeans/server-context'
|
|
4
|
+
import { type CommonEntrypoint, type GateService, provideResponse } from '@owlmeans/entrypoint'
|
|
9
5
|
import { ResilientError } from '@owlmeans/error'
|
|
10
6
|
import { OK } from '@owlmeans/api'
|
|
11
|
-
import {
|
|
7
|
+
import { logger } from '@owlmeans/log'
|
|
8
|
+
import { errorExposure, handleError } from './error.js'
|
|
12
9
|
import { executeResponse, provideRequest } from './payload.js'
|
|
13
10
|
import { authorize } from './guards.js'
|
|
14
11
|
import { RouteProtocols } from '@owlmeans/route'
|
|
12
|
+
import type { ServerConfig2, ServerContext2 } from './types.local.js'
|
|
15
13
|
|
|
16
|
-
type Config = ServerConfig
|
|
17
|
-
type Context = ServerContext<Config>
|
|
18
14
|
|
|
19
|
-
export const canServeModule = (context:
|
|
15
|
+
export const canServeModule = (context: ServerContext2, module: CommonEntrypoint): module is ServerEntrypoint<unknown> => {
|
|
20
16
|
if (module.route.route.type !== AppType.Backend) {
|
|
21
17
|
return false
|
|
22
18
|
}
|
|
23
19
|
if (module.route.route.service != null && module.route.route.service !== context.cfg.service) {
|
|
24
20
|
return false
|
|
25
21
|
}
|
|
26
|
-
|
|
22
|
+
// HTTP serves only its own protocol. Custom transports are handled by their owning packages.
|
|
23
|
+
if (module.route.route.protocol != null
|
|
24
|
+
&& module.route.route.protocol !== RouteProtocols.WEB) {
|
|
27
25
|
return false
|
|
28
26
|
}
|
|
29
27
|
|
|
@@ -33,7 +31,7 @@ export const canServeModule = (context: Context, module: CommonEntrypoint): modu
|
|
|
33
31
|
export const createServerHandler = (module: ServerEntrypoint<FastifyRequest>, location: string) =>
|
|
34
32
|
async (req: FastifyRequest, reply: FastifyReply) => {
|
|
35
33
|
// We passed context using fastify request object
|
|
36
|
-
let context = assertContext<
|
|
34
|
+
let context = assertContext<ServerConfig2, ServerContext2>((req as any)._ctx, location)
|
|
37
35
|
try {
|
|
38
36
|
const authorized = await authorize(context, module, req, reply)
|
|
39
37
|
context = authorized[0]
|
|
@@ -59,18 +57,15 @@ export const createServerHandler = (module: ServerEntrypoint<FastifyRequest>, lo
|
|
|
59
57
|
// neither `executeResponse` nor the handler itself (hijack) replied.
|
|
60
58
|
const responded = executeResponse(response, reply, true)
|
|
61
59
|
if (!responded && !reply.sent) {
|
|
62
|
-
|
|
60
|
+
logger('http').warn(`SENDS DEFAULT RESPONSE: ${module.alias}`)
|
|
63
61
|
reply.code(OK).send(response.value)
|
|
64
62
|
}
|
|
65
63
|
} catch (error) {
|
|
66
|
-
console.error(`Error in ${module.alias} (${location})`)
|
|
67
|
-
console.error(JSON.stringify(error, null, 2))
|
|
68
|
-
console.error(error)
|
|
69
64
|
if (module.fixer != null) {
|
|
70
65
|
const fixer: FixerService = context.service(module.fixer)
|
|
71
66
|
fixer.handle(reply, ResilientError.ensure(error as Error))
|
|
72
67
|
return
|
|
73
68
|
}
|
|
74
|
-
handleError(error as Error, reply)
|
|
69
|
+
handleError(error as Error, reply, errorExposure(context.cfg))
|
|
75
70
|
}
|
|
76
71
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
|
|
2
|
+
import type { Config as ApiConfig } from '../types.js'
|
|
3
|
+
|
|
4
|
+
export type Config = ServerConfig
|
|
5
|
+
|
|
6
|
+
export interface Context<C extends Config = Config> extends ServerContext<C> { }
|
|
7
|
+
|
|
8
|
+
export type Severity = 'debug' | 'info' | 'warn' | 'error'
|
|
9
|
+
|
|
10
|
+
export type ServerConfig2 = ApiConfig
|
|
11
|
+
|
|
12
|
+
export type ServerContext2 = ServerContext<ServerConfig2>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an error class may declare about the HTTP status it is answered with.
|
|
3
|
+
*
|
|
4
|
+
* Structural on purpose: the classes that declare it live in packages that must not depend on an
|
|
5
|
+
* HTTP server (`@owlmeans/payment`, a product's contract package), so they write a plain
|
|
6
|
+
* `public static httpStatus = 409` and nothing imports this type.
|
|
7
|
+
*/
|
|
8
|
+
export interface HttpStatusDeclaration {
|
|
9
|
+
httpStatus?: unknown
|
|
10
|
+
/** Explicit opt-in for a declared 5xx response. Client-error declarations need no opt-in. */
|
|
11
|
+
allowServerErrorStatus?: unknown
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SerializedHttpError {
|
|
15
|
+
status: number
|
|
16
|
+
body: string
|
|
17
|
+
incidentId: string
|
|
18
|
+
}
|