@panomc/client 0.0.0-stage → 1.0.0-dev.62
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/package.json +22 -4
- package/src/client.js +267 -0
- package/src/client.test.js +348 -0
- package/src/core/index.js +522 -0
- package/src/core/openapi.json +5820 -0
- package/src/core/operations.js +69 -0
- package/src/core/types.js +360 -0
- package/src/errors.js +55 -0
- package/src/index.js +2 -0
- package/src/types.js +61 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@panomc/client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0-dev.62",
|
|
4
|
+
"description": "Typed JavaScript client for the Pano HTTP API (JSDoc types, no dependencies, no framework).",
|
|
5
|
+
"author": "PanoMC",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"repository": {
|
|
9
|
+
"url": "https://github.com/PanoMC/sdk"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./src/client.js",
|
|
13
|
+
"./core": "./src/core/index.js",
|
|
14
|
+
"./core/types": "./src/core/types.js",
|
|
15
|
+
"./core/openapi.json": "./src/core/openapi.json",
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { PanoApiError, failure, failureFromBody } from './errors.js'
|
|
2
|
+
|
|
3
|
+
/** @typedef {import('./types.js').PanoClientOptions} PanoClientOptions */
|
|
4
|
+
/** @typedef {import('./types.js').PanoClient} PanoClient */
|
|
5
|
+
/** @typedef {import('./types.js').PanoOperation} PanoOperation */
|
|
6
|
+
/** @typedef {import('./types.js').RequestParams} RequestParams */
|
|
7
|
+
/** @typedef {import('./types.js').ApiFailure} ApiFailure */
|
|
8
|
+
/** @template T @typedef {import('./types.js').ApiResult<T>} ApiResult */
|
|
9
|
+
|
|
10
|
+
const CSRF_PATH = '/api/v1/auth/csrf'
|
|
11
|
+
const AUTH_PREFIX = '/api/v1/auth/'
|
|
12
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
|
13
|
+
|
|
14
|
+
/** @param {any} body */
|
|
15
|
+
function isRawBody(body) {
|
|
16
|
+
return (
|
|
17
|
+
typeof body === 'string' ||
|
|
18
|
+
(typeof FormData !== 'undefined' && body instanceof FormData) ||
|
|
19
|
+
(typeof Blob !== 'undefined' && body instanceof Blob) ||
|
|
20
|
+
(typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) ||
|
|
21
|
+
(typeof ArrayBuffer !== 'undefined' && (body instanceof ArrayBuffer || ArrayBuffer.isView(body))) ||
|
|
22
|
+
(typeof ReadableStream !== 'undefined' && body instanceof ReadableStream)
|
|
23
|
+
)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {string} path @param {Record<string, any>|undefined} values */
|
|
27
|
+
function fillPath(path, values) {
|
|
28
|
+
return path.replace(/\{([^}]+)\}/g, (whole, name) => {
|
|
29
|
+
const value = values?.[name]
|
|
30
|
+
return value === undefined || value === null ? whole : encodeURIComponent(String(value))
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {Record<string, any>|undefined} query */
|
|
35
|
+
function queryString(query) {
|
|
36
|
+
if (!query) return ''
|
|
37
|
+
const search = new URLSearchParams()
|
|
38
|
+
|
|
39
|
+
for (const [key, value] of Object.entries(query)) {
|
|
40
|
+
if (value === undefined || value === null) continue
|
|
41
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
42
|
+
if (item === undefined || item === null) continue
|
|
43
|
+
search.append(key, item instanceof Date ? item.toISOString() : String(item))
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const text = search.toString()
|
|
48
|
+
return text ? `?${text}` : ''
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** @param {Response} response */
|
|
52
|
+
async function readBody(response) {
|
|
53
|
+
if (response.status === 204 || response.status === 205) return undefined
|
|
54
|
+
|
|
55
|
+
const text = await response.text()
|
|
56
|
+
if (!text) return undefined
|
|
57
|
+
|
|
58
|
+
const type = response.headers.get('content-type') || ''
|
|
59
|
+
if (type.includes('json') || /^\s*[[{]/.test(text)) {
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(text)
|
|
62
|
+
} catch {
|
|
63
|
+
return text
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return text
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {PanoClientOptions} options
|
|
72
|
+
* @returns {PanoClient}
|
|
73
|
+
*/
|
|
74
|
+
export function createClient(options) {
|
|
75
|
+
if (!options || typeof options.baseUrl !== 'string') {
|
|
76
|
+
throw new TypeError('createClient: options.baseUrl is required (Pano origin or proxy prefix, e.g. "/pano")')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const baseUrl = options.baseUrl.replace(/\/+$/, '')
|
|
80
|
+
const inBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'
|
|
81
|
+
const credentials = options.credentials ?? (inBrowser ? 'include' : 'omit')
|
|
82
|
+
const csrfMode = options.csrf ?? (credentials === 'include' && !options.sessionToken ? 'auto' : 'off')
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* CSRF cache. `undefined` = unknown, `null` = probed and there is none (anonymous or Bearer), string = token.
|
|
86
|
+
* @type {string|null|undefined}
|
|
87
|
+
*/
|
|
88
|
+
let csrfToken
|
|
89
|
+
/** @type {Promise<void>|null} */
|
|
90
|
+
let probing = null
|
|
91
|
+
|
|
92
|
+
/** @param {Record<string, string>|undefined} extra */
|
|
93
|
+
async function buildHeaders(extra) {
|
|
94
|
+
/** @type {Record<string, string>} */
|
|
95
|
+
const headers = { Accept: 'application/json' }
|
|
96
|
+
|
|
97
|
+
if (options.locale) headers['Accept-Language'] = options.locale
|
|
98
|
+
|
|
99
|
+
if (options.frontendKey) {
|
|
100
|
+
headers['X-Pano-Frontend-Key'] = options.frontendKey
|
|
101
|
+
if (options.clientIp) headers['X-Pano-Client-Ip'] = options.clientIp
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const token = typeof options.sessionToken === 'function' ? await options.sessionToken() : options.sessionToken
|
|
105
|
+
if (token) headers.Authorization = `Bearer ${token}`
|
|
106
|
+
|
|
107
|
+
if (extra) {
|
|
108
|
+
for (const [name, value] of Object.entries(extra)) {
|
|
109
|
+
if (value === undefined || value === null) continue
|
|
110
|
+
const lower = name.toLowerCase()
|
|
111
|
+
// The key and the visitor IP travel together or not at all: a per-request header cannot add one without the other.
|
|
112
|
+
if (lower === 'x-pano-frontend-key' || lower === 'x-pano-client-ip') continue
|
|
113
|
+
headers[name] = value
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return headers
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* One fetch with the shared error handling. Never throws.
|
|
122
|
+
* @param {string} method
|
|
123
|
+
* @param {string} path resolved path, starting with "/api/v1/"
|
|
124
|
+
* @param {string} search
|
|
125
|
+
* @param {Record<string, string>} headers
|
|
126
|
+
* @param {any} body
|
|
127
|
+
* @param {AbortSignal|undefined} signal
|
|
128
|
+
* @returns {Promise<{ result: ApiResult<any> }>}
|
|
129
|
+
*/
|
|
130
|
+
async function send(method, path, search, headers, body, signal) {
|
|
131
|
+
const fetchImpl = options.fetch ?? globalThis.fetch
|
|
132
|
+
|
|
133
|
+
if (typeof fetchImpl !== 'function') {
|
|
134
|
+
return { result: failure(0, 'NETWORK_ERROR', { message: 'No fetch implementation available' }) }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** @type {RequestInit} */
|
|
138
|
+
const init = { method, headers, credentials }
|
|
139
|
+
if (body !== undefined) init.body = body
|
|
140
|
+
if (signal) init.signal = signal
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
const response = await fetchImpl(`${baseUrl}${path}${search}`, init)
|
|
144
|
+
const parsed = await readBody(response)
|
|
145
|
+
|
|
146
|
+
if (response.ok) {
|
|
147
|
+
return { result: { ok: true, status: response.status, data: parsed } }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return { result: failureFromBody(response.status, parsed) }
|
|
151
|
+
} catch (error) {
|
|
152
|
+
const aborted = /** @type {any} */ (error)?.name === 'AbortError'
|
|
153
|
+
return {
|
|
154
|
+
result: failure(0, 'NETWORK_ERROR', {
|
|
155
|
+
message: error instanceof Error ? error.message : 'Network request failed',
|
|
156
|
+
...(aborted ? { details: { aborted: true } } : {})
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** @param {any} data */
|
|
163
|
+
function adoptToken(data) {
|
|
164
|
+
if (data && typeof data === 'object' && typeof data.csrfToken === 'string') csrfToken = data.csrfToken
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** GET /auth/csrf once at a time. Never reports to onUnauthorized. */
|
|
168
|
+
function probe() {
|
|
169
|
+
if (!probing) {
|
|
170
|
+
probing = (async () => {
|
|
171
|
+
try {
|
|
172
|
+
const headers = await buildHeaders(undefined)
|
|
173
|
+
const { result } = await send('GET', CSRF_PATH, '', headers, undefined, undefined)
|
|
174
|
+
|
|
175
|
+
if (result.ok) {
|
|
176
|
+
const token = result.data?.csrfToken
|
|
177
|
+
csrfToken = typeof token === 'string' ? token : null
|
|
178
|
+
} else if (result.status === 401) {
|
|
179
|
+
csrfToken = null
|
|
180
|
+
}
|
|
181
|
+
// any other failure (network, 5xx): stay unknown, the next mutation probes again
|
|
182
|
+
} finally {
|
|
183
|
+
probing = null
|
|
184
|
+
}
|
|
185
|
+
})()
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return probing
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* @param {PanoOperation} operation
|
|
193
|
+
* @param {RequestParams} [params]
|
|
194
|
+
* @returns {Promise<ApiResult<any>>}
|
|
195
|
+
*/
|
|
196
|
+
async function request(operation, params = {}) {
|
|
197
|
+
try {
|
|
198
|
+
const method = String(operation.method).toUpperCase()
|
|
199
|
+
const path = fillPath(operation.path, params.path)
|
|
200
|
+
const search = queryString(params.query)
|
|
201
|
+
const mutation = !SAFE_METHODS.has(method)
|
|
202
|
+
const useCsrf = csrfMode === 'auto' && mutation && path !== CSRF_PATH
|
|
203
|
+
|
|
204
|
+
let body = params.body
|
|
205
|
+
let jsonBody = false
|
|
206
|
+
if (body !== undefined && body !== null && !isRawBody(body)) {
|
|
207
|
+
body = JSON.stringify(body)
|
|
208
|
+
jsonBody = true
|
|
209
|
+
} else if (body === null) {
|
|
210
|
+
body = undefined
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** @param {string|null|undefined} token */
|
|
214
|
+
const attempt = async (token) => {
|
|
215
|
+
const headers = await buildHeaders(params.headers)
|
|
216
|
+
if (jsonBody && !Object.keys(headers).some((name) => name.toLowerCase() === 'content-type')) {
|
|
217
|
+
headers['Content-Type'] = 'application/json'
|
|
218
|
+
}
|
|
219
|
+
if (token) headers['X-CSRF-Token'] = token
|
|
220
|
+
return send(method, path, search, headers, body, params.signal)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (useCsrf && csrfToken === undefined) await probe()
|
|
224
|
+
|
|
225
|
+
let { result } = await attempt(useCsrf ? csrfToken : undefined)
|
|
226
|
+
|
|
227
|
+
if (useCsrf && !result.ok && result.error.code === 'INVALID_CSRF_TOKEN') {
|
|
228
|
+
csrfToken = undefined
|
|
229
|
+
await probe()
|
|
230
|
+
|
|
231
|
+
if (csrfToken) {
|
|
232
|
+
;({ result } = await attempt(csrfToken))
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (result.ok) {
|
|
237
|
+
if (mutation && path.startsWith(AUTH_PREFIX)) csrfToken = undefined
|
|
238
|
+
adoptToken(result.data)
|
|
239
|
+
} else if (result.status === 401 && options.onUnauthorized) {
|
|
240
|
+
try {
|
|
241
|
+
options.onUnauthorized(result)
|
|
242
|
+
} catch {
|
|
243
|
+
// a throwing callback must not turn a failed request into a rejected promise
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return result
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return failure(0, 'NETWORK_ERROR', {
|
|
250
|
+
message: error instanceof Error ? error.message : 'Request failed before it was sent'
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return { request, options: Object.freeze({ ...options }) }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The data of a successful result, or a thrown PanoApiError.
|
|
260
|
+
* @template T
|
|
261
|
+
* @param {ApiResult<T>} result
|
|
262
|
+
* @returns {T}
|
|
263
|
+
*/
|
|
264
|
+
export function unwrap(result) {
|
|
265
|
+
if (result.ok) return result.data
|
|
266
|
+
throw new PanoApiError(result)
|
|
267
|
+
}
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { createClient, unwrap, PanoApiError } from './index.js'
|
|
3
|
+
|
|
4
|
+
const json = (status, body, headers = {}) =>
|
|
5
|
+
new Response(body === undefined ? null : JSON.stringify(body), {
|
|
6
|
+
status,
|
|
7
|
+
headers: { 'content-type': 'application/json', ...headers }
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
/** fake fetch: handlers queue per "METHOD path", falls back to 200 {} ; records every call */
|
|
11
|
+
function fakeFetch(routes = {}) {
|
|
12
|
+
const calls = []
|
|
13
|
+
const fn = async (url, init = {}) => {
|
|
14
|
+
const u = new URL(url, 'http://pano.test')
|
|
15
|
+
const key = `${init.method || 'GET'} ${u.pathname}`
|
|
16
|
+
calls.push({ key, url: String(url), method: init.method || 'GET', headers: { ...init.headers }, body: init.body, init })
|
|
17
|
+
const handler = routes[key]
|
|
18
|
+
const next = Array.isArray(handler) ? handler.shift() : handler
|
|
19
|
+
if (next instanceof Error) throw next
|
|
20
|
+
if (typeof next === 'function') return next(init)
|
|
21
|
+
return next ?? json(200, {})
|
|
22
|
+
}
|
|
23
|
+
fn.calls = calls
|
|
24
|
+
fn.count = (key) => calls.filter((c) => c.key === key).length
|
|
25
|
+
return fn
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const base = 'http://pano.test'
|
|
29
|
+
const POST = { method: 'POST', path: '/api/v1/things' }
|
|
30
|
+
|
|
31
|
+
describe('request building', () => {
|
|
32
|
+
test('url, query, path params, accept and locale', async () => {
|
|
33
|
+
const f = fakeFetch({ 'GET /api/v1/posts/a%20b': json(200, { items: [] }) })
|
|
34
|
+
const c = createClient({ baseUrl: base + '/', fetch: f, locale: 'tr', csrf: 'off' })
|
|
35
|
+
const r = await c.request(
|
|
36
|
+
{ method: 'GET', path: '/api/v1/posts/{slug}' },
|
|
37
|
+
{ path: { slug: 'a b' }, query: { page: 2, tag: ['x', 'y'], skip: undefined, none: null } }
|
|
38
|
+
)
|
|
39
|
+
expect(r).toEqual({ ok: true, status: 200, data: { items: [] } })
|
|
40
|
+
expect(f.calls[0].url).toBe(`${base}/api/v1/posts/a%20b?page=2&tag=x&tag=y`)
|
|
41
|
+
expect(f.calls[0].headers.Accept).toBe('application/json')
|
|
42
|
+
expect(f.calls[0].headers['Accept-Language']).toBe('tr')
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
test('proxy prefix as baseUrl', async () => {
|
|
46
|
+
const f = fakeFetch()
|
|
47
|
+
await createClient({ baseUrl: '/pano', fetch: f, csrf: 'off' }).request({ method: 'GET', path: '/api/v1/posts' })
|
|
48
|
+
expect(f.calls[0].url).toBe('/pano/api/v1/posts')
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
test('json body gets content-type, FormData passes through', async () => {
|
|
52
|
+
const f = fakeFetch()
|
|
53
|
+
const c = createClient({ baseUrl: base, fetch: f, csrf: 'off' })
|
|
54
|
+
await c.request(POST, { body: { a: 1 } })
|
|
55
|
+
expect(f.calls[0].body).toBe('{"a":1}')
|
|
56
|
+
expect(f.calls[0].headers['Content-Type']).toBe('application/json')
|
|
57
|
+
|
|
58
|
+
const form = new FormData()
|
|
59
|
+
form.append('f', 'v')
|
|
60
|
+
await c.request(POST, { body: form })
|
|
61
|
+
expect(f.calls[1].body).toBe(form)
|
|
62
|
+
expect(f.calls[1].headers['Content-Type']).toBeUndefined()
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
test('credentials default omit outside a browser, option wins, signal and headers pass', async () => {
|
|
66
|
+
const f = fakeFetch()
|
|
67
|
+
const ctl = new AbortController()
|
|
68
|
+
await createClient({ baseUrl: base, fetch: f }).request(
|
|
69
|
+
{ method: 'GET', path: '/api/v1/x' },
|
|
70
|
+
{ signal: ctl.signal, headers: { 'X-Extra': '1' } }
|
|
71
|
+
)
|
|
72
|
+
expect(f.calls[0].init.credentials).toBe('omit')
|
|
73
|
+
expect(f.calls[0].init.signal).toBe(ctl.signal)
|
|
74
|
+
expect(f.calls[0].headers['X-Extra']).toBe('1')
|
|
75
|
+
await createClient({ baseUrl: base, fetch: f, credentials: 'include', csrf: 'off' }).request({ method: 'GET', path: '/api/v1/x' })
|
|
76
|
+
expect(f.calls[1].init.credentials).toBe('include')
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
test('204 and empty bodies give undefined data', async () => {
|
|
80
|
+
const f = fakeFetch({ 'DELETE /api/v1/things': new Response(null, { status: 204 }) })
|
|
81
|
+
const r = await createClient({ baseUrl: base, fetch: f, csrf: 'off' }).request({ method: 'DELETE', path: '/api/v1/things' })
|
|
82
|
+
expect(r).toEqual({ ok: true, status: 204, data: undefined })
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
test('baseUrl is required', () => {
|
|
86
|
+
expect(() => createClient({})).toThrow(TypeError)
|
|
87
|
+
})
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
describe('front-end key, client IP, session token', () => {
|
|
91
|
+
test('key and ip are sent together', async () => {
|
|
92
|
+
const f = fakeFetch()
|
|
93
|
+
await createClient({ baseUrl: base, fetch: f, frontendKey: 'pfk_1', clientIp: '203.0.113.9' }).request({ method: 'GET', path: '/api/v1/x' })
|
|
94
|
+
expect(f.calls[0].headers['X-Pano-Frontend-Key']).toBe('pfk_1')
|
|
95
|
+
expect(f.calls[0].headers['X-Pano-Client-Ip']).toBe('203.0.113.9')
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
test('ip without key is never sent, also not through per-request headers', async () => {
|
|
99
|
+
const f = fakeFetch()
|
|
100
|
+
const c = createClient({ baseUrl: base, fetch: f, clientIp: '203.0.113.9' })
|
|
101
|
+
await c.request({ method: 'GET', path: '/api/v1/x' }, { headers: { 'x-pano-client-ip': '1.2.3.4', 'X-Pano-Frontend-Key': 'pfk_forged' } })
|
|
102
|
+
const names = Object.keys(f.calls[0].headers).map((n) => n.toLowerCase())
|
|
103
|
+
expect(names).not.toContain('x-pano-client-ip')
|
|
104
|
+
expect(names).not.toContain('x-pano-frontend-key')
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
test('key without ip sends the key only', async () => {
|
|
108
|
+
const f = fakeFetch()
|
|
109
|
+
await createClient({ baseUrl: base, fetch: f, frontendKey: 'pfk_1' }).request({ method: 'GET', path: '/api/v1/x' })
|
|
110
|
+
expect(f.calls[0].headers['X-Pano-Frontend-Key']).toBe('pfk_1')
|
|
111
|
+
expect(f.calls[0].headers['X-Pano-Client-Ip']).toBeUndefined()
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
test('sessionToken string and (async) function become Bearer; null sends none', async () => {
|
|
115
|
+
const f = fakeFetch()
|
|
116
|
+
await createClient({ baseUrl: base, fetch: f, sessionToken: 'tok' }).request({ method: 'GET', path: '/api/v1/x' })
|
|
117
|
+
expect(f.calls[0].headers.Authorization).toBe('Bearer tok')
|
|
118
|
+
let n = 0
|
|
119
|
+
const c = createClient({ baseUrl: base, fetch: f, sessionToken: async () => (n++ === 0 ? 'a' : null) })
|
|
120
|
+
await c.request({ method: 'GET', path: '/api/v1/x' })
|
|
121
|
+
await c.request({ method: 'GET', path: '/api/v1/x' })
|
|
122
|
+
expect(f.calls[1].headers.Authorization).toBe('Bearer a')
|
|
123
|
+
expect(f.calls[2].headers.Authorization).toBeUndefined()
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
test('a sessionToken turns csrf off by default', async () => {
|
|
127
|
+
const f = fakeFetch()
|
|
128
|
+
await createClient({ baseUrl: base, fetch: f, sessionToken: 'tok', credentials: 'include' }).request(POST, { body: {} })
|
|
129
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(0)
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
describe('errors', () => {
|
|
134
|
+
test('envelope is parsed with message, details and fields', async () => {
|
|
135
|
+
const f = fakeFetch({
|
|
136
|
+
'POST /api/v1/things': json(400, { error: { code: 'INVALID_INPUT', message: 'bad', fields: { name: 'REQUIRED' }, details: { a: 1 } } })
|
|
137
|
+
})
|
|
138
|
+
const r = await createClient({ baseUrl: base, fetch: f, csrf: 'off' }).request(POST, { body: {} })
|
|
139
|
+
expect(r).toEqual({ ok: false, status: 400, error: { code: 'INVALID_INPUT', message: 'bad', fields: { name: 'REQUIRED' }, details: { a: 1 } } })
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
test('a body that is not the envelope becomes HTTP_<status>', async () => {
|
|
143
|
+
const f = fakeFetch({ 'GET /api/v1/x': new Response('<html>bad gateway</html>', { status: 502 }) })
|
|
144
|
+
const r = await createClient({ baseUrl: base, fetch: f }).request({ method: 'GET', path: '/api/v1/x' })
|
|
145
|
+
expect(r.ok).toBe(false)
|
|
146
|
+
expect(r.status).toBe(502)
|
|
147
|
+
expect(r.error.code).toBe('HTTP_502')
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
test('network failure does not throw', async () => {
|
|
151
|
+
const f = fakeFetch({ 'GET /api/v1/x': new TypeError('fetch failed') })
|
|
152
|
+
const r = await createClient({ baseUrl: base, fetch: f }).request({ method: 'GET', path: '/api/v1/x' })
|
|
153
|
+
expect(r.ok).toBe(false)
|
|
154
|
+
expect(r.status).toBe(0)
|
|
155
|
+
expect(r.error.code).toBe('NETWORK_ERROR')
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
test('abort is a NETWORK_ERROR marked aborted', async () => {
|
|
159
|
+
const abort = new Error('aborted')
|
|
160
|
+
abort.name = 'AbortError'
|
|
161
|
+
const f = fakeFetch({ 'GET /api/v1/x': abort })
|
|
162
|
+
const r = await createClient({ baseUrl: base, fetch: f }).request({ method: 'GET', path: '/api/v1/x' })
|
|
163
|
+
expect(r.error.code).toBe('NETWORK_ERROR')
|
|
164
|
+
expect(r.error.details).toEqual({ aborted: true })
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
test('missing fetch gives NETWORK_ERROR', async () => {
|
|
168
|
+
const original = globalThis.fetch
|
|
169
|
+
globalThis.fetch = undefined
|
|
170
|
+
try {
|
|
171
|
+
const r = await createClient({ baseUrl: base }).request({ method: 'GET', path: '/api/v1/x' })
|
|
172
|
+
expect(r.error.code).toBe('NETWORK_ERROR')
|
|
173
|
+
} finally {
|
|
174
|
+
globalThis.fetch = original
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
test('onUnauthorized fires on 401, its throw is swallowed', async () => {
|
|
179
|
+
const f = fakeFetch({ 'GET /api/v1/me': json(401, { error: { code: 'NOT_LOGGED_IN' } }) })
|
|
180
|
+
const seen = []
|
|
181
|
+
const c = createClient({ baseUrl: base, fetch: f, onUnauthorized: (r) => { seen.push(r); throw new Error('boom') } })
|
|
182
|
+
const r = await c.request({ method: 'GET', path: '/api/v1/me' })
|
|
183
|
+
expect(r.status).toBe(401)
|
|
184
|
+
expect(seen).toHaveLength(1)
|
|
185
|
+
expect(seen[0].error.code).toBe('NOT_LOGGED_IN')
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
test('unwrap returns data or throws PanoApiError', async () => {
|
|
189
|
+
expect(unwrap({ ok: true, status: 200, data: 5 })).toBe(5)
|
|
190
|
+
try {
|
|
191
|
+
unwrap({ ok: false, status: 422, error: { code: 'INVALID_INPUT', message: 'bad', fields: { a: 'X' } } })
|
|
192
|
+
throw new Error('should throw')
|
|
193
|
+
} catch (e) {
|
|
194
|
+
expect(e).toBeInstanceOf(PanoApiError)
|
|
195
|
+
expect(e.code).toBe('INVALID_INPUT')
|
|
196
|
+
expect(e.status).toBe(422)
|
|
197
|
+
expect(e.fields).toEqual({ a: 'X' })
|
|
198
|
+
expect(e.message).toBe('bad')
|
|
199
|
+
}
|
|
200
|
+
})
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
describe('csrf auto', () => {
|
|
204
|
+
const auto = (routes) => {
|
|
205
|
+
const f = fakeFetch(routes)
|
|
206
|
+
return { f, c: createClient({ baseUrl: base, fetch: f, credentials: 'include' }) }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
test('probes before the first mutation, caches, sends X-CSRF-Token', async () => {
|
|
210
|
+
const { f, c } = auto({ 'GET /api/v1/auth/csrf': json(200, { csrfToken: 'T1' }) })
|
|
211
|
+
await c.request({ method: 'GET', path: '/api/v1/x' })
|
|
212
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(0)
|
|
213
|
+
await c.request(POST, { body: {} })
|
|
214
|
+
await c.request({ method: 'PUT', path: '/api/v1/things/1' }, { body: {} })
|
|
215
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
|
|
216
|
+
expect(f.calls[1].key).toBe('GET /api/v1/auth/csrf')
|
|
217
|
+
expect(f.calls[2].headers['X-CSRF-Token']).toBe('T1')
|
|
218
|
+
expect(f.calls[3].headers['X-CSRF-Token']).toBe('T1')
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
test('concurrent first mutations share one probe', async () => {
|
|
222
|
+
const { f, c } = auto({ 'GET /api/v1/auth/csrf': json(200, { csrfToken: 'T1' }) })
|
|
223
|
+
await Promise.all([c.request(POST, { body: {} }), c.request(POST, { body: {} })])
|
|
224
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
test('401 on the probe: no header, no onUnauthorized, cached as none', async () => {
|
|
228
|
+
const f = fakeFetch({ 'GET /api/v1/auth/csrf': json(401, { error: { code: 'NOT_LOGGED_IN' } }) })
|
|
229
|
+
let unauthorized = 0
|
|
230
|
+
const c = createClient({ baseUrl: base, fetch: f, credentials: 'include', onUnauthorized: () => unauthorized++ })
|
|
231
|
+
const r = await c.request(POST, { body: {} })
|
|
232
|
+
expect(r.ok).toBe(true)
|
|
233
|
+
await c.request(POST, { body: {} })
|
|
234
|
+
expect(unauthorized).toBe(0)
|
|
235
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
|
|
236
|
+
expect(f.calls[1].headers['X-CSRF-Token']).toBeUndefined()
|
|
237
|
+
expect(f.calls[2].headers['X-CSRF-Token']).toBeUndefined()
|
|
238
|
+
})
|
|
239
|
+
|
|
240
|
+
test('null token (Bearer) means no header', async () => {
|
|
241
|
+
const { f, c } = auto({ 'GET /api/v1/auth/csrf': json(200, { csrfToken: null }) })
|
|
242
|
+
await c.request(POST, { body: {} })
|
|
243
|
+
expect(f.calls[1].headers['X-CSRF-Token']).toBeUndefined()
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
test('a failed probe is not cached; the next mutation probes again', async () => {
|
|
247
|
+
const { f, c } = auto({ 'GET /api/v1/auth/csrf': [new TypeError('down'), json(200, { csrfToken: 'T2' })] })
|
|
248
|
+
await c.request(POST, { body: {} })
|
|
249
|
+
await c.request(POST, { body: {} })
|
|
250
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(2)
|
|
251
|
+
expect(f.calls[3].headers['X-CSRF-Token']).toBe('T2')
|
|
252
|
+
})
|
|
253
|
+
|
|
254
|
+
test('a csrfToken in any response body replaces the cache', async () => {
|
|
255
|
+
const { f, c } = auto({
|
|
256
|
+
'GET /api/v1/auth/csrf': json(200, { csrfToken: 'T1' }),
|
|
257
|
+
'GET /api/v1/me': json(200, { csrfToken: 'T9' })
|
|
258
|
+
})
|
|
259
|
+
await c.request(POST, { body: {} })
|
|
260
|
+
await c.request({ method: 'GET', path: '/api/v1/me' })
|
|
261
|
+
await c.request(POST, { body: {} })
|
|
262
|
+
expect(f.calls.at(-1).headers['X-CSRF-Token']).toBe('T9')
|
|
263
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
|
|
264
|
+
})
|
|
265
|
+
|
|
266
|
+
test('cleared after a successful /api/v1/auth/ mutation, then probed again', async () => {
|
|
267
|
+
const { f, c } = auto({
|
|
268
|
+
'GET /api/v1/auth/csrf': [json(200, { csrfToken: 'T1' }), json(401, { error: { code: 'NOT_LOGGED_IN' } })],
|
|
269
|
+
'POST /api/v1/auth/logout': json(200, {})
|
|
270
|
+
})
|
|
271
|
+
await c.request({ method: 'POST', path: '/api/v1/auth/logout' }, { body: {} })
|
|
272
|
+
expect(f.calls[1].headers['X-CSRF-Token']).toBe('T1')
|
|
273
|
+
await c.request(POST, { body: {} })
|
|
274
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(2)
|
|
275
|
+
expect(f.calls.at(-1).headers['X-CSRF-Token']).toBeUndefined()
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
test('a login body token is kept after the clear', async () => {
|
|
279
|
+
const { f, c } = auto({
|
|
280
|
+
'GET /api/v1/auth/csrf': json(401, { error: { code: 'NOT_LOGGED_IN' } }),
|
|
281
|
+
'POST /api/v1/auth/login': json(200, { csrfToken: 'L1' })
|
|
282
|
+
})
|
|
283
|
+
await c.request({ method: 'POST', path: '/api/v1/auth/login' }, { body: {} })
|
|
284
|
+
await c.request(POST, { body: {} })
|
|
285
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
|
|
286
|
+
expect(f.calls.at(-1).headers['X-CSRF-Token']).toBe('L1')
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
test('a failed /auth/ mutation does not clear', async () => {
|
|
290
|
+
const { f, c } = auto({
|
|
291
|
+
'GET /api/v1/auth/csrf': json(200, { csrfToken: 'T1' }),
|
|
292
|
+
'POST /api/v1/auth/login': json(400, { error: { code: 'WRONG_PASSWORD' } })
|
|
293
|
+
})
|
|
294
|
+
await c.request({ method: 'POST', path: '/api/v1/auth/login' }, { body: {} })
|
|
295
|
+
await c.request(POST, { body: {} })
|
|
296
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
test('INVALID_CSRF_TOKEN: clear, refetch, retry exactly once', async () => {
|
|
300
|
+
const invalid = () => json(403, { error: { code: 'INVALID_CSRF_TOKEN' } })
|
|
301
|
+
const { f, c } = auto({
|
|
302
|
+
'GET /api/v1/auth/csrf': [json(200, { csrfToken: 'OLD' }), json(200, { csrfToken: 'NEW' })],
|
|
303
|
+
'POST /api/v1/things': [invalid(), json(200, { done: true })]
|
|
304
|
+
})
|
|
305
|
+
const r = await c.request(POST, { body: { a: 1 } })
|
|
306
|
+
expect(r).toEqual({ ok: true, status: 200, data: { done: true } })
|
|
307
|
+
const posts = f.calls.filter((x) => x.key === 'POST /api/v1/things')
|
|
308
|
+
expect(posts.map((p) => p.headers['X-CSRF-Token'])).toEqual(['OLD', 'NEW'])
|
|
309
|
+
expect(posts[1].body).toBe('{"a":1}')
|
|
310
|
+
})
|
|
311
|
+
|
|
312
|
+
test('a second INVALID_CSRF_TOKEN is returned, no third attempt', async () => {
|
|
313
|
+
const invalid = () => json(403, { error: { code: 'INVALID_CSRF_TOKEN' } })
|
|
314
|
+
const { f, c } = auto({
|
|
315
|
+
'GET /api/v1/auth/csrf': () => json(200, { csrfToken: 'T' }),
|
|
316
|
+
'POST /api/v1/things': [invalid(), invalid(), invalid()]
|
|
317
|
+
})
|
|
318
|
+
const r = await c.request(POST, { body: {} })
|
|
319
|
+
expect(r.ok).toBe(false)
|
|
320
|
+
expect(r.error.code).toBe('INVALID_CSRF_TOKEN')
|
|
321
|
+
expect(f.count('POST /api/v1/things')).toBe(2)
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
test('GET never probes and never sends the header', async () => {
|
|
325
|
+
const { f, c } = auto({})
|
|
326
|
+
await c.request({ method: 'GET', path: '/api/v1/x' })
|
|
327
|
+
expect(f.calls).toHaveLength(1)
|
|
328
|
+
expect(f.calls[0].headers['X-CSRF-Token']).toBeUndefined()
|
|
329
|
+
})
|
|
330
|
+
})
|
|
331
|
+
|
|
332
|
+
describe('csrf off', () => {
|
|
333
|
+
test('never calls the endpoint, even on INVALID_CSRF_TOKEN', async () => {
|
|
334
|
+
const f = fakeFetch({ 'POST /api/v1/things': json(403, { error: { code: 'INVALID_CSRF_TOKEN' } }) })
|
|
335
|
+
const c = createClient({ baseUrl: base, fetch: f, credentials: 'include', csrf: 'off' })
|
|
336
|
+
const r = await c.request(POST, { body: {} })
|
|
337
|
+
expect(r.error.code).toBe('INVALID_CSRF_TOKEN')
|
|
338
|
+
expect(f.calls).toHaveLength(1)
|
|
339
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(0)
|
|
340
|
+
expect(f.calls[0].headers['X-CSRF-Token']).toBeUndefined()
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
test('omit credentials defaults to off', async () => {
|
|
344
|
+
const f = fakeFetch()
|
|
345
|
+
await createClient({ baseUrl: base, fetch: f, credentials: 'omit' }).request(POST, { body: {} })
|
|
346
|
+
expect(f.count('GET /api/v1/auth/csrf')).toBe(0)
|
|
347
|
+
})
|
|
348
|
+
})
|