@antelopejs/dms-api 0.2.0 → 0.4.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.
@@ -0,0 +1,18 @@
1
+ import { computed, onMounted, ref, type ComputedRef } from 'vue'
2
+
3
+ /**
4
+ * `read()` once the browser has mounted the component, `undefined` before:
5
+ * for a value the server and the browser may write differently, which the
6
+ * server's HTML must not hold. A date written with its weekday is one: the
7
+ * ICU of Node and the one of the browser disagree on its punctuation
8
+ * ("Thursday, 15 October" against "Thursday 15 October" in `en-GB`), and the
9
+ * hydration would report the mismatch. Meant for what the first paint can do
10
+ * without, such as a tooltip.
11
+ */
12
+ export function useClientValue<T>(read: () => T): ComputedRef<T | undefined> {
13
+ const mounted = ref(false)
14
+ onMounted(() => {
15
+ mounted.value = true
16
+ })
17
+ return computed(() => (mounted.value ? read() : undefined))
18
+ }
@@ -1,4 +1,5 @@
1
- import { computed, markRaw, onBeforeUnmount, ref, watch } from 'vue'
1
+ import { computed } from 'vue'
2
+ import { errorStatus } from '../utils/http'
2
3
  import type { RouteState } from '../utils/routeExplorer'
3
4
 
4
5
  /** One step of the request pipeline of a route, in the order it runs. */
@@ -134,120 +135,35 @@ export interface RouteDetail {
134
135
  apiOrigin: string | null
135
136
  }
136
137
 
137
- /** The detail every block of the page reads, fetched once per route. */
138
- interface DetailSlot {
139
- url: string | null
140
- data: RouteDetail | null
141
- error: unknown
142
- pending: boolean
143
- refreshing: boolean
144
- receivedAt: number | null
145
- }
146
-
147
- const emptySlot = (): DetailSlot => ({
148
- url: null,
149
- data: null,
150
- error: null,
151
- pending: true,
152
- refreshing: false,
153
- receivedAt: null,
154
- })
155
-
156
- /** The request still running for a slot, and the blocks reading it. */
157
- const running = new WeakMap<object, AbortController>()
158
- const readers = new WeakMap<object, number>()
159
-
160
138
  /**
161
139
  * The route the page's `?route=` names, shared by the blocks that show it:
162
140
  * the header, the documentation, the tester and the parts of the page that
163
- * wait for a valid route read one payload, loaded once per route rather than
164
- * once per block. A newer route cancels the request still running; a failed
165
- * refresh keeps the last data and says so through `error`.
141
+ * wait for a valid route read one `useApiData` payload (one request per
142
+ * route, which a server render reads and hands over). Another route shows
143
+ * nothing until its payload is in; a failed refresh keeps the last data and
144
+ * says so through `error`.
166
145
  */
167
146
  export function useRouteDetail(fetchUrl: string, queryKey = 'route') {
168
147
  const selection = useRouteSelection(queryKey)
169
- const target = computed(() =>
170
- selection.ref.value
171
- ? `${fetchUrl}?${new URLSearchParams({ route: selection.ref.value })}`
172
- : null,
148
+ // The header reads it again, on the Statistics tab only: the
149
+ // documentation and the tester must not move with the page's refreshes.
150
+ const detail = useApiData<RouteDetail>(
151
+ () =>
152
+ selection.ref.value
153
+ ? `${fetchUrl}?${new URLSearchParams({ route: selection.ref.value })}`
154
+ : null,
155
+ { refreshOnPageRefresh: false },
173
156
  )
174
-
175
- // The server renders the page before anything is fetched.
176
- if (import.meta.env.SSR) {
177
- return {
178
- selection,
179
- missing: computed(() => false),
180
- data: ref<RouteDetail | null>(null),
181
- error: ref<unknown>(null),
182
- pending: ref(true),
183
- refreshing: ref(false),
184
- receivedAt: ref<number | null>(null),
185
- refresh: async () => {},
186
- }
187
- }
188
-
189
- const { $authFetch } = useAuthFetch()
190
- const state = useDmsState<DetailSlot>(
191
- `dms-api-route-detail:${fetchUrl}`,
192
- emptySlot,
157
+ const data = computed(() =>
158
+ detail.placeholder.value ? null : detail.data.value,
193
159
  )
194
-
195
- async function load(url: string | null, force = false) {
196
- const slot = state.value
197
- if (!force && slot.url === url) return
198
- running.get(slot)?.abort()
199
- running.delete(slot)
200
- if (slot.url !== url) {
201
- slot.url = url
202
- slot.data = null
203
- slot.error = null
204
- }
205
- if (!url) {
206
- slot.pending = false
207
- return
208
- }
209
- const controller = new AbortController()
210
- running.set(slot, controller)
211
- slot.pending = slot.data === null
212
- slot.refreshing = slot.data !== null
213
- try {
214
- const response = await $authFetch<RouteDetail>(url, {
215
- signal: controller.signal,
216
- })
217
- if (running.get(slot) !== controller) return
218
- slot.data = markRaw(response)
219
- slot.error = null
220
- slot.receivedAt = Date.now()
221
- } catch (cause) {
222
- if (running.get(slot) !== controller) return
223
- if ((cause as { name?: string })?.name !== 'AbortError')
224
- slot.error = cause
225
- } finally {
226
- if (running.get(slot) === controller) {
227
- running.delete(slot)
228
- slot.pending = false
229
- slot.refreshing = false
230
- }
231
- }
232
- }
233
-
234
- // The first block of a page visit refreshes what an earlier visit left.
235
- const slot = state.value
236
- const count = readers.get(slot) ?? 0
237
- readers.set(slot, count + 1)
238
- onBeforeUnmount(() => readers.set(slot, (readers.get(slot) ?? 1) - 1))
239
- if (count === 0 && slot.url !== null) void load(target.value, true)
240
-
241
- watch(target, (url) => void load(url), { immediate: true })
242
-
243
160
  return {
244
161
  selection,
245
- missing: computed(() => errorStatus(state.value.error) === 404),
246
- data: computed(() => state.value.data),
247
- error: computed(() => state.value.error),
248
- pending: computed(() => state.value.pending),
249
- refreshing: computed(() => state.value.refreshing),
250
- receivedAt: computed(() => state.value.receivedAt),
251
- refresh: () => load(target.value, true),
162
+ data,
163
+ error: detail.error,
164
+ /** Nothing to show yet for the route named: its first read is running. */
165
+ pending: computed(() => detail.pending.value && data.value === null),
166
+ refresh: () => detail.refresh(),
167
+ missing: computed(() => errorStatus(detail.error.value) === 404),
252
168
  }
253
169
  }
@@ -125,3 +125,13 @@ export function parseRouteRef(
125
125
  const match = ref?.trim().match(/^([A-Za-z]+)\s+(\/\S*)$/)
126
126
  return match ? { method: match[1].toUpperCase(), path: match[2] } : null
127
127
  }
128
+
129
+ /** The HTTP status of a failed request, when it has one. */
130
+ export function errorStatus(error: unknown): number | undefined {
131
+ const value = error as {
132
+ statusCode?: number
133
+ status?: number
134
+ response?: { status?: number }
135
+ }
136
+ return value?.statusCode ?? value?.status ?? value?.response?.status
137
+ }
@@ -29,20 +29,22 @@ export type BodyMode = 'json' | 'text' | 'form' | 'none'
29
29
  /** Who the call is authenticated as, as the DMS proxy sends it. */
30
30
  export type AuthMode = 'session' | 'manual' | 'none'
31
31
 
32
- // --- The DMS proxy (`/api/_dms/tester`) ---
33
- // dms-frontend `templates/vue/server/tester.mjs`: the limits it applies, and
34
- // what it answers when it does not forward a call. Its error bodies hold one
32
+ // --- The tester's server route (`/api/_dms-api/tester`) ---
33
+ // `server/tester.ts`, in this module's `dms.server.ts`: the limits it applies,
34
+ // and what it answers when it does not forward a call. Its error bodies hold one
35
35
  // generic text per status, so the status, the elapsed time and the checks
36
36
  // below are what tell the causes apart.
37
37
 
38
+ /** Where the tester's server route answers. */
39
+ export const TESTER_ROUTE = '/api/_dms-api/tester'
38
40
  /** The proxy reads at most this much of the request (the JSON envelope). */
39
41
  export const PROXY_BODY_LIMIT = 64 * 1024
40
42
  /**
41
43
  * The proxy fails (502) when the API answers more than this, and returns
42
44
  * neither the status nor the start of the body: `limitedText()` throws
43
- * "Backend response too large" past `RESPONSE_LIMIT` (tester.mjs, lines 5
44
- * and 131-141), and `handleTester()` turns every error into the same 502
45
- * "DMS tester request failed" (lines 220-226), as for an API down. Only the
45
+ * "Backend response too large" past `RESPONSE_LIMIT` (`server/tester.ts`),
46
+ * and `testerRoute()` turns every error into the same 502 "DMS tester request
47
+ * failed", as for an API down. Only the
46
48
  * capture of the call tells the two apart. For the DMS: return the status,
47
49
  * the headers and the first 64 KiB with a `truncated: true` flag instead of
48
50
  * throwing, and give the 502 a `reason` (`too_large`, `timeout`,
@@ -481,7 +483,7 @@ export async function sendTesterRequest(
481
483
  try {
482
484
  let response: Response
483
485
  try {
484
- response = await fetch('/api/_dms/tester', {
486
+ response = await fetch(TESTER_ROUTE, {
485
487
  method: 'POST',
486
488
  headers: { 'content-type': 'application/json' },
487
489
  credentials: 'same-origin',
@@ -0,0 +1,9 @@
1
+ import { defineDmsServer } from '#dms/server'
2
+ import { testerRoute } from './server/tester'
3
+
4
+ // The API tester's call forwarding: served by this module, under its own
5
+ // namespace. The frontend server has no tester route of its own, and answers
6
+ // the path's other methods with a 405 itself.
7
+ export default defineDmsServer((server) => {
8
+ server.registerRoute('POST', '/api/_dms-api/tester', testerRoute)
9
+ })
@@ -6,7 +6,7 @@
6
6
  "main": "./dms.frontend.ts",
7
7
  "packageManager": "pnpm@10.6.5",
8
8
  "engines": {
9
- "@antelopejs/dms-frontend": ">=0.5.2 <0.6.0"
9
+ "@antelopejs/dms-frontend": ">=0.6.0 <0.7.0"
10
10
  },
11
11
  "scripts": {
12
12
  "dev": "pnpm --dir ../playground frontend:dev",
@@ -0,0 +1,266 @@
1
+ import type { DmsServerEvent, DmsSession } from '#dms/server'
2
+
3
+ // The API tester's server half: forwards one call the owner composes to the
4
+ // backend, with the session's credential when asked, and returns the answer
5
+ // without the session's tokens. Owner-only: the session must belong to the
6
+ // instance owner, which the backend confirms on every call.
7
+
8
+ const RESPONSE_LIMIT = 64 * 1024
9
+ const REQUEST_TIMEOUT_MS = 30_000
10
+ const METHODS = new Set([
11
+ 'GET',
12
+ 'HEAD',
13
+ 'POST',
14
+ 'PUT',
15
+ 'PATCH',
16
+ 'DELETE',
17
+ 'OPTIONS',
18
+ ])
19
+ const BLOCKED_HEADERS = new Set([
20
+ 'host',
21
+ 'cookie',
22
+ 'cookie2',
23
+ 'set-cookie',
24
+ 'set-cookie2',
25
+ 'connection',
26
+ 'keep-alive',
27
+ 'proxy-authenticate',
28
+ 'proxy-authorization',
29
+ 'te',
30
+ 'trailer',
31
+ 'transfer-encoding',
32
+ 'upgrade',
33
+ 'content-length',
34
+ 'expect',
35
+ 'forwarded',
36
+ 'origin',
37
+ 'referer',
38
+ 'via',
39
+ 'authorization',
40
+ ])
41
+ const CONTROL_HEADER =
42
+ /^(?:sec-|proxy-|x-forwarded-|x-dms-|x-inertia|x-http-method|x-method-override|x-original-|x-rewrite-)/i
43
+ // URL paths must reject literal control characters before forwarding.
44
+ const UNSAFE_PATH = /[\\#\u0000- \u007f]/
45
+ // Decoded path segments need the same boundary after every decoding pass.
46
+ const UNSAFE_DECODED_SEGMENT = /[\\/#\u0000- \u007f]/
47
+
48
+ interface TesterInput {
49
+ path?: unknown
50
+ method?: unknown
51
+ headers?: unknown
52
+ body?: unknown
53
+ useSession?: unknown
54
+ }
55
+
56
+ interface ValidInput {
57
+ method: string
58
+ headers: Record<string, string>
59
+ body?: string
60
+ useSession: boolean
61
+ }
62
+
63
+ class InvalidInput extends Error {
64
+ readonly status = 400
65
+ }
66
+
67
+ function invalidInput(): never {
68
+ throw new InvalidInput('Invalid tester request')
69
+ }
70
+
71
+ function validatePathSegment(segment: string) {
72
+ let decoded = segment
73
+ for (;;) {
74
+ if (['.', '..'].includes(decoded) || UNSAFE_DECODED_SEGMENT.test(decoded))
75
+ invalidInput()
76
+ let next: string
77
+ try {
78
+ next = decodeURIComponent(decoded)
79
+ } catch {
80
+ invalidInput()
81
+ }
82
+ if (next === decoded) break
83
+ decoded = next
84
+ }
85
+ }
86
+
87
+ function targetUrl(event: DmsServerEvent, path: unknown): URL {
88
+ if (
89
+ typeof path !== 'string' ||
90
+ !path.startsWith('/') ||
91
+ path.startsWith('//') ||
92
+ UNSAFE_PATH.test(path)
93
+ )
94
+ invalidInput()
95
+ path.split('?', 1)[0].split('/').forEach(validatePathSegment)
96
+ const target = event.backendUrl(path)
97
+ if (target.hash) invalidInput()
98
+ return target
99
+ }
100
+
101
+ function filteredHeaders(input: HeadersInit, allowAuthorization = false) {
102
+ const source = new Headers(input)
103
+ const connection = new Set(
104
+ (source.get('connection') ?? '')
105
+ .toLowerCase()
106
+ .split(',')
107
+ .map((name) => name.trim()),
108
+ )
109
+ return new Headers(
110
+ [...source].filter(
111
+ ([name]) =>
112
+ !connection.has(name) &&
113
+ !CONTROL_HEADER.test(name) &&
114
+ (!BLOCKED_HEADERS.has(name) ||
115
+ (allowAuthorization && name === 'authorization')),
116
+ ),
117
+ )
118
+ }
119
+
120
+ function validateInput(event: DmsServerEvent, input: TesterInput) {
121
+ if (!input || typeof input !== 'object' || Array.isArray(input))
122
+ invalidInput()
123
+ if (
124
+ typeof input.method !== 'string' ||
125
+ !METHODS.has(input.method) ||
126
+ typeof input.useSession !== 'boolean'
127
+ )
128
+ invalidInput()
129
+ const headers = input.headers
130
+ if (!headers || typeof headers !== 'object' || Array.isArray(headers))
131
+ invalidInput()
132
+ if (Object.values(headers).some((value) => typeof value !== 'string'))
133
+ invalidInput()
134
+ if (
135
+ input.body !== undefined &&
136
+ (typeof input.body !== 'string' || ['GET', 'HEAD'].includes(input.method))
137
+ )
138
+ invalidInput()
139
+ try {
140
+ new Headers(headers as Record<string, string>)
141
+ } catch {
142
+ invalidInput()
143
+ }
144
+ return {
145
+ target: targetUrl(event, input.path),
146
+ input: input as ValidInput,
147
+ }
148
+ }
149
+
150
+ async function limitedText(response: Response): Promise<string> {
151
+ if (!response.body) return ''
152
+ const reader = response.body.getReader()
153
+ const chunks: Uint8Array[] = []
154
+ let size = 0
155
+ for (;;) {
156
+ const { done, value } = await reader.read()
157
+ if (done) break
158
+ size += value.length
159
+ if (size > RESPONSE_LIMIT) {
160
+ await reader.cancel()
161
+ throw new Error('Backend response too large')
162
+ }
163
+ chunks.push(value)
164
+ }
165
+ return Buffer.concat(chunks).toString('utf8')
166
+ }
167
+
168
+ async function isOwner(
169
+ event: DmsServerEvent,
170
+ session: DmsSession,
171
+ signal: AbortSignal,
172
+ ) {
173
+ const response = await fetch(event.backendUrl('/api/auth/me'), {
174
+ headers: {
175
+ authorization: `Bearer ${session.accessToken}`,
176
+ 'x-antelopejs-namespace': 'default',
177
+ },
178
+ redirect: 'manual',
179
+ signal,
180
+ })
181
+ const text = await limitedText(response)
182
+ if (!response.ok) return false
183
+ return JSON.parse(text)?.owner === true
184
+ }
185
+
186
+ function redact(value: string, session: DmsSession): string {
187
+ const secrets = [session.accessToken, session.refreshToken].filter(
188
+ (secret): secret is string => typeof secret === 'string' && !!secret.length,
189
+ )
190
+ return secrets.reduce((result, secret) => {
191
+ const variants = [
192
+ secret,
193
+ encodeURIComponent(secret),
194
+ JSON.stringify(secret).slice(1, -1),
195
+ ]
196
+ return variants.reduce(
197
+ (text, variant) => text.replaceAll(variant, '[REDACTED]'),
198
+ result,
199
+ )
200
+ }, value)
201
+ }
202
+
203
+ async function forward(
204
+ input: ValidInput,
205
+ target: URL,
206
+ session: DmsSession,
207
+ signal: AbortSignal,
208
+ ) {
209
+ const headers = filteredHeaders(input.headers, true)
210
+ if (input.useSession && !headers.has('authorization')) {
211
+ headers.set('authorization', `Bearer ${session.accessToken}`)
212
+ if (!headers.has('x-antelopejs-namespace'))
213
+ headers.set('x-antelopejs-namespace', 'default')
214
+ }
215
+ const upstream = await fetch(target, {
216
+ method: input.method,
217
+ headers,
218
+ redirect: 'manual',
219
+ signal,
220
+ body: input.body,
221
+ })
222
+ const responseHeaders = Object.fromEntries(
223
+ [...filteredHeaders(upstream.headers)].map(([name, value]) => [
224
+ redact(name, session),
225
+ redact(value, session),
226
+ ]),
227
+ )
228
+ return {
229
+ status: upstream.status,
230
+ headers: responseHeaders,
231
+ body: redact(await limitedText(upstream), session),
232
+ }
233
+ }
234
+
235
+ function failure(status: number, error: string): Response {
236
+ return Response.json({ error }, { status })
237
+ }
238
+
239
+ function inputFailureStatus(error: unknown): number | undefined {
240
+ const status = (error as { status?: unknown } | undefined)?.status
241
+ return status === 400 || status === 413 ? status : undefined
242
+ }
243
+
244
+ /**
245
+ * `POST /api/_dms-api/tester`: forwards an owner's tester call without
246
+ * returning the session's credentials.
247
+ */
248
+ export async function testerRoute(event: DmsServerEvent): Promise<Response> {
249
+ try {
250
+ const session = event.session.read()
251
+ if (!session?.accessToken) return failure(401, 'Not authenticated')
252
+ const { input, target } = validateInput(
253
+ event,
254
+ await event.readJson<TesterInput>(),
255
+ )
256
+ const signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS)
257
+ if (!(await isOwner(event, session, signal)))
258
+ return failure(403, 'Forbidden')
259
+ return Response.json(await forward(input, target, session, signal))
260
+ } catch (error) {
261
+ const status = inputFailureStatus(error)
262
+ return status
263
+ ? failure(status, 'Invalid tester request')
264
+ : failure(502, 'DMS tester request failed')
265
+ }
266
+ }
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import { createRenderer, createSSRApp, defineComponent, h, nextTick } from 'vue'
3
+ import { renderToString } from 'vue/server-renderer'
4
+ import { useClientValue } from '../app/composables/useClientValue'
5
+
6
+ // A value the server and the browser may write differently (a weekday
7
+ // written by two ICU versions: "Thursday, 15 October" in Node, "Thursday 15
8
+ // October" in a recent Chrome) must not reach the server's HTML, or the
9
+ // hydration of every page showing it reports a mismatch.
10
+
11
+ const Tooltip = (read: () => string) =>
12
+ defineComponent({
13
+ setup() {
14
+ const title = useClientValue(read)
15
+ return () => h('time', { title: title.value }, 'for 3 min')
16
+ },
17
+ })
18
+
19
+ interface TestNode {
20
+ tag: string
21
+ props: Record<string, unknown>
22
+ children: TestNode[]
23
+ text?: string
24
+ }
25
+
26
+ // A renderer without a DOM: enough to mount a component in Node.
27
+ const { createApp } = createRenderer<TestNode, TestNode>({
28
+ createElement: (tag) => ({ tag, props: {}, children: [] }),
29
+ createText: (text) => ({ tag: '#text', props: {}, children: [], text }),
30
+ createComment: (text) => ({ tag: '#comment', props: {}, children: [], text }),
31
+ setText: (node, text) => {
32
+ node.text = text
33
+ },
34
+ setElementText: (node, text) => {
35
+ node.children = [{ tag: '#text', props: {}, children: [], text }]
36
+ },
37
+ insert: (child, parent) => {
38
+ parent.children.push(child)
39
+ },
40
+ remove: () => {},
41
+ parentNode: () => null,
42
+ nextSibling: () => null,
43
+ patchProp: (node, key, _previous, next) => {
44
+ node.props[key] = next
45
+ },
46
+ })
47
+
48
+ describe('useClientValue', () => {
49
+ it('leaves the value out of the server render', async () => {
50
+ const read = vi.fn(() => 'Thursday, 15 October 2026 at 19:58')
51
+ const html = await renderToString(createSSRApp(Tooltip(read)))
52
+ expect(html).toBe('<time>for 3 min</time>')
53
+ expect(read).not.toHaveBeenCalled()
54
+ })
55
+
56
+ it('gives the value once the browser has mounted the component', async () => {
57
+ const root: TestNode = { tag: 'root', props: {}, children: [] }
58
+ createApp(Tooltip(() => 'Thursday 15 October 2026 at 19:58')).mount(root)
59
+ await nextTick()
60
+ expect(root.children[0]?.props.title).toBe(
61
+ 'Thursday 15 October 2026 at 19:58',
62
+ )
63
+ })
64
+ })
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import { testerRoute } from '../server/tester'
3
+
4
+ // The frontend server (dms-frontend 0.6) serves no tester route of its own:
5
+ // the module's `dms.server.ts` is the only one to declare it.
6
+
7
+ vi.mock('#dms/server', () => ({
8
+ defineDmsServer: (setup: unknown) => setup,
9
+ }))
10
+
11
+ interface Registration {
12
+ method: unknown
13
+ path: string
14
+ handler: unknown
15
+ options: unknown
16
+ }
17
+
18
+ async function registrations(): Promise<Registration[]> {
19
+ const { default: setup } = await import('../dms.server')
20
+ const routes: Registration[] = []
21
+ const server = {
22
+ registerRoute: (
23
+ method: unknown,
24
+ path: string,
25
+ handler: unknown,
26
+ options?: unknown,
27
+ ) => routes.push({ method, path, handler, options }),
28
+ }
29
+ ;(setup as unknown as (server: unknown) => void)(server)
30
+ return routes
31
+ }
32
+
33
+ describe('dms.server.ts', () => {
34
+ it("serves the tester's POST under the module's own namespace, and nothing else", async () => {
35
+ expect(await registrations()).toEqual([
36
+ {
37
+ method: 'POST',
38
+ path: '/api/_dms-api/tester',
39
+ handler: testerRoute,
40
+ options: undefined,
41
+ },
42
+ ])
43
+ })
44
+ })
@@ -53,7 +53,7 @@ describe('sending through the proxy', () => {
53
53
  )
54
54
  expect(result).toEqual(reply)
55
55
  const [url, init] = fetch.mock.calls[0]
56
- expect(url).toBe('/api/_dms/tester')
56
+ expect(url).toBe('/api/_dms-api/tester')
57
57
  expect(init).toMatchObject({
58
58
  method: 'POST',
59
59
  headers: { 'content-type': 'application/json' },