@supatype/client 0.2.0 → 0.3.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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +22 -21
- package/.turbo/turbo-typecheck.log +1 -1
- package/dist/index.d.ts +31 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +71 -13
- package/dist/index.js.map +1 -1
- package/dist/preview.d.ts +45 -0
- package/dist/preview.d.ts.map +1 -0
- package/dist/preview.js +92 -0
- package/dist/preview.js.map +1 -0
- package/dist/query-cache.d.ts +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query.d.ts +1 -1
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +7 -1
- package/dist/query.js.map +1 -1
- package/dist/storage.d.ts +15 -2
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +18 -7
- package/dist/storage.js.map +1 -1
- package/dist/types.d.ts +50 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +9 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +81 -15
- package/src/preview.ts +102 -0
- package/src/query-cache.ts +1 -1
- package/src/query.ts +7 -1
- package/src/storage.ts +26 -12
- package/src/types.ts +52 -0
- package/tests/draft-profile.test.ts +296 -0
- package/tests/storage-quota-integration.test.ts +2 -1
- package/tests/storage-upload-limit-integration.test.ts +2 -1
- package/tsconfig.tsbuildinfo +1 -1
package/src/preview.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A preview link's credential, and the exchange that turns it into a usable token.
|
|
3
|
+
*
|
|
4
|
+
* # Why there is an exchange at all
|
|
5
|
+
*
|
|
6
|
+
* The link used to *be* the token: a signed JWT carrying the preview claim, pasted into a URL. That
|
|
7
|
+
* worked, and it had two costs. The URL ran to about 400 characters, and a signed token cannot be
|
|
8
|
+
* recalled, so withdrawing one link meant bumping a counter that stranded every other link in the
|
|
9
|
+
* project at the same time.
|
|
10
|
+
*
|
|
11
|
+
* So the link is now a short code naming a row, and the server hands back a token that lives about
|
|
12
|
+
* a minute. Revoking the row stops the next exchange, which is what makes per-link revocation mean
|
|
13
|
+
* anything. The token is still what the database sees, so no policy changed.
|
|
14
|
+
*
|
|
15
|
+
* # Why the token is cached here
|
|
16
|
+
*
|
|
17
|
+
* A page render issues several queries. Exchanging per query would multiply a page load by the
|
|
18
|
+
* number of tables it touches, for a credential that does not change between them. One exchange is
|
|
19
|
+
* shared, and a second caller arriving mid-flight waits on the same promise rather than starting
|
|
20
|
+
* its own.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Seconds of slack before expiry at which the token is treated as spent. */
|
|
24
|
+
const REFRESH_SKEW_MS = 5_000
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Thrown when a code will not resolve, for any reason.
|
|
28
|
+
*
|
|
29
|
+
* The server does not say which reason and neither does this: distinguishing "revoked" from "never
|
|
30
|
+
* existed" would confirm to a stranger that a draft is there to be found. The message is written
|
|
31
|
+
* for the person holding the link rather than for the developer, because it is usually shown to
|
|
32
|
+
* them directly.
|
|
33
|
+
*/
|
|
34
|
+
export class PreviewLinkError extends Error {
|
|
35
|
+
constructor(message = "This preview link is not valid. It may have expired, or been revoked.") {
|
|
36
|
+
super(message)
|
|
37
|
+
this.name = "PreviewLinkError"
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface ExchangeResponse {
|
|
42
|
+
token?: unknown
|
|
43
|
+
expiresAt?: unknown
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Holds one preview code and the short-lived token most recently bought with it.
|
|
48
|
+
*
|
|
49
|
+
* A class rather than a closure on purpose: a closure here would capture the whole client config
|
|
50
|
+
* for as long as any request is outstanding, and this needs two strings.
|
|
51
|
+
*/
|
|
52
|
+
export class PreviewCredential {
|
|
53
|
+
readonly #endpoint: string
|
|
54
|
+
readonly #code: string
|
|
55
|
+
#token: string | null = null
|
|
56
|
+
#expiresAtMs = 0
|
|
57
|
+
#inFlight: Promise<string> | null = null
|
|
58
|
+
|
|
59
|
+
constructor(baseUrl: string, code: string) {
|
|
60
|
+
this.#endpoint = `${baseUrl.replace(/\/$/, "")}/preview-links/resolve`
|
|
61
|
+
this.#code = code
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A token good right now, exchanging first if the one in hand is spent. */
|
|
65
|
+
async token(): Promise<string> {
|
|
66
|
+
if (this.#token !== null && Date.now() < this.#expiresAtMs - REFRESH_SKEW_MS) {
|
|
67
|
+
return this.#token
|
|
68
|
+
}
|
|
69
|
+
// Whoever gets here first does the exchange; everyone else waits on it.
|
|
70
|
+
this.#inFlight ??= this.#exchange().finally(() => {
|
|
71
|
+
this.#inFlight = null
|
|
72
|
+
})
|
|
73
|
+
return this.#inFlight
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async #exchange(): Promise<string> {
|
|
77
|
+
let response: Response
|
|
78
|
+
try {
|
|
79
|
+
response = await fetch(this.#endpoint, {
|
|
80
|
+
method: "POST",
|
|
81
|
+
headers: { "Content-Type": "application/json" },
|
|
82
|
+
body: JSON.stringify({ code: this.#code }),
|
|
83
|
+
})
|
|
84
|
+
} catch {
|
|
85
|
+
// A network failure is not an invalid link, and saying so would send the reader to ask for a
|
|
86
|
+
// replacement that would work no better.
|
|
87
|
+
throw new PreviewLinkError("Could not reach the server to check this preview link.")
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (!response.ok) throw new PreviewLinkError()
|
|
91
|
+
|
|
92
|
+
const body = (await response.json().catch(() => ({}))) as ExchangeResponse
|
|
93
|
+
if (typeof body.token !== "string" || body.token === "") throw new PreviewLinkError()
|
|
94
|
+
|
|
95
|
+
const expiresAt = typeof body.expiresAt === "string" ? Date.parse(body.expiresAt) : NaN
|
|
96
|
+
this.#token = body.token
|
|
97
|
+
// An unparseable expiry means exchanging again next time rather than trusting a token for an
|
|
98
|
+
// unknown length of time.
|
|
99
|
+
this.#expiresAtMs = Number.isNaN(expiresAt) ? 0 : expiresAt
|
|
100
|
+
return body.token
|
|
101
|
+
}
|
|
102
|
+
}
|
package/src/query-cache.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { sha256Hex } from "./sha256-hex.js"
|
|
|
4
4
|
export interface QueryCacheOptions {
|
|
5
5
|
/** Client-side TTL in milliseconds. */
|
|
6
6
|
ttl: number
|
|
7
|
-
/** When true, send `X-Supatype-Cache: max-age=N`
|
|
7
|
+
/** When true, send `X-Supatype-Cache: max-age=N` so the server caches the response too. */
|
|
8
8
|
server?: boolean | undefined
|
|
9
9
|
/** When true (with server), request shared public cache scope when allowed for the table. */
|
|
10
10
|
public?: boolean | undefined
|
package/src/query.ts
CHANGED
|
@@ -125,9 +125,15 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
125
125
|
if (this.countMode !== undefined) {
|
|
126
126
|
this.extraHeaders["Prefer"] = `count=${this.countMode}`
|
|
127
127
|
}
|
|
128
|
+
// A profile picks the schema that answers, which is how a draft is read: same table name, same
|
|
129
|
+
// row type, one header. Set at construction rather than as a chainable step, so it cannot be
|
|
130
|
+
// added to a request that has already been described.
|
|
131
|
+
if (selectOptions?.profile !== undefined) {
|
|
132
|
+
this.extraHeaders["Accept-Profile"] = selectOptions.profile
|
|
133
|
+
}
|
|
128
134
|
}
|
|
129
135
|
|
|
130
|
-
/** Enable GET caching. Use `{ server: true }`
|
|
136
|
+
/** Enable GET caching. Use `{ server: true }` to cache the response on the server too. */
|
|
131
137
|
cache(options: QueryCacheOptions): this {
|
|
132
138
|
this.cacheOptions = options
|
|
133
139
|
return this
|
package/src/storage.ts
CHANGED
|
@@ -29,11 +29,25 @@ export interface StorageBucketMeta {
|
|
|
29
29
|
updated_at: string
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
/** Resolved fresh per request, so a session that arrives later is used. */
|
|
33
|
+
export type AuthHeaders = () => Promise<Record<string, string>>
|
|
34
|
+
|
|
32
35
|
export class StorageClient {
|
|
33
36
|
private readonly url: string
|
|
34
|
-
private readonly headers:
|
|
35
|
-
|
|
36
|
-
|
|
37
|
+
private readonly headers: AuthHeaders
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Headers are asked for per request, not captured here.
|
|
41
|
+
*
|
|
42
|
+
* They used to be a plain object built when the client was constructed, which is before anybody
|
|
43
|
+
* has signed in. Every storage request therefore carried the anon key for the life of the page,
|
|
44
|
+
* whatever session the caller later had: an app's per-user storage policies saw `anon`, and
|
|
45
|
+
* Studio's proxy refused the request outright because an anon key carries no subject.
|
|
46
|
+
*
|
|
47
|
+
* Every other client on this object already took the same function. Storage was the one that did
|
|
48
|
+
* not.
|
|
49
|
+
*/
|
|
50
|
+
constructor(url: string, headers: AuthHeaders) {
|
|
37
51
|
this.url = url
|
|
38
52
|
this.headers = headers
|
|
39
53
|
}
|
|
@@ -44,7 +58,7 @@ export class StorageClient {
|
|
|
44
58
|
|
|
45
59
|
async listBuckets(): Promise<{ data: StorageBucketMeta[] | null; error: SupatypeError | null }> {
|
|
46
60
|
try {
|
|
47
|
-
const res = await fetch(`${this.url}/bucket`, { headers: this.headers })
|
|
61
|
+
const res = await fetch(`${this.url}/bucket`, { headers: await this.headers() })
|
|
48
62
|
if (!res.ok) {
|
|
49
63
|
const err = await res.json().catch(() => ({ message: "Error" })) as { message?: string }
|
|
50
64
|
return { data: null, error: { message: err.message ?? "Failed to list buckets" } }
|
|
@@ -70,7 +84,7 @@ export class StorageClient {
|
|
|
70
84
|
}
|
|
71
85
|
const res = await fetch(`${this.url}/bucket`, {
|
|
72
86
|
method: "POST",
|
|
73
|
-
headers: { ...this.headers, "Content-Type": "application/json" },
|
|
87
|
+
headers: { ...(await this.headers()), "Content-Type": "application/json" },
|
|
74
88
|
body: JSON.stringify(body),
|
|
75
89
|
})
|
|
76
90
|
if (!res.ok) {
|
|
@@ -87,9 +101,9 @@ export class StorageClient {
|
|
|
87
101
|
export class BucketClient {
|
|
88
102
|
private readonly url: string
|
|
89
103
|
private readonly bucket: string
|
|
90
|
-
private readonly headers:
|
|
104
|
+
private readonly headers: AuthHeaders
|
|
91
105
|
|
|
92
|
-
constructor(url: string, bucket: string, headers:
|
|
106
|
+
constructor(url: string, bucket: string, headers: AuthHeaders) {
|
|
93
107
|
this.url = url
|
|
94
108
|
this.bucket = bucket
|
|
95
109
|
this.headers = headers
|
|
@@ -102,7 +116,7 @@ export class BucketClient {
|
|
|
102
116
|
): Promise<{ data: { path: string } | null; error: SupatypeError | null }> {
|
|
103
117
|
const inferredType = file instanceof File && file.type ? file.type : "application/octet-stream"
|
|
104
118
|
const headers: Record<string, string> = {
|
|
105
|
-
...this.headers,
|
|
119
|
+
...(await this.headers()),
|
|
106
120
|
"Content-Type": options?.contentType ?? inferredType,
|
|
107
121
|
}
|
|
108
122
|
if (options?.upsert === true) {
|
|
@@ -125,7 +139,7 @@ export class BucketClient {
|
|
|
125
139
|
options?: { transform?: TransformOptions | undefined } | undefined,
|
|
126
140
|
): Promise<{ data: Blob | null; error: SupatypeError | null }> {
|
|
127
141
|
const url = this.buildObjectUrl("authenticated", path, options?.transform)
|
|
128
|
-
const res = await fetch(url, { headers: this.headers })
|
|
142
|
+
const res = await fetch(url, { headers: await this.headers() })
|
|
129
143
|
if (!res.ok) {
|
|
130
144
|
const err = await res.json().catch(() => ({ message: "Download failed" })) as Record<string, unknown>
|
|
131
145
|
return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Download failed"), status: res.status } }
|
|
@@ -148,7 +162,7 @@ export class BucketClient {
|
|
|
148
162
|
): Promise<{ data: { signedUrl: string } | null; error: SupatypeError | null }> {
|
|
149
163
|
const res = await fetch(`${this.url}/object/sign/${this.bucket}/${path}`, {
|
|
150
164
|
method: "POST",
|
|
151
|
-
headers: { ...this.headers, "Content-Type": "application/json" },
|
|
165
|
+
headers: { ...(await this.headers()), "Content-Type": "application/json" },
|
|
152
166
|
body: JSON.stringify({ expiresIn }),
|
|
153
167
|
})
|
|
154
168
|
if (!res.ok) {
|
|
@@ -178,7 +192,7 @@ export class BucketClient {
|
|
|
178
192
|
async remove(paths: string[]): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
|
|
179
193
|
const res = await fetch(`${this.url}/object/${this.bucket}`, {
|
|
180
194
|
method: "DELETE",
|
|
181
|
-
headers: { ...this.headers, "Content-Type": "application/json" },
|
|
195
|
+
headers: { ...(await this.headers()), "Content-Type": "application/json" },
|
|
182
196
|
body: JSON.stringify({ prefixes: paths }),
|
|
183
197
|
})
|
|
184
198
|
if (!res.ok) {
|
|
@@ -200,7 +214,7 @@ export class BucketClient {
|
|
|
200
214
|
}
|
|
201
215
|
const res = await fetch(`${this.url}/object/list/${this.bucket}`, {
|
|
202
216
|
method: "POST",
|
|
203
|
-
headers: { ...this.headers, "Content-Type": "application/json" },
|
|
217
|
+
headers: { ...(await this.headers()), "Content-Type": "application/json" },
|
|
204
218
|
body: JSON.stringify(body),
|
|
205
219
|
})
|
|
206
220
|
if (!res.ok) {
|
package/src/types.ts
CHANGED
|
@@ -177,6 +177,23 @@ export interface QueryResult<TData> {
|
|
|
177
177
|
|
|
178
178
|
// ─── RPC result ──────────────────────────────────────────────────────────────
|
|
179
179
|
|
|
180
|
+
/**
|
|
181
|
+
* Options for {@link SupatypeClient.rpc}.
|
|
182
|
+
*
|
|
183
|
+
* `schema` is not decoration. PostgREST resolves `/rpc/<name>` against the
|
|
184
|
+
* **default profile**, which is the first schema on the exposed list, so a
|
|
185
|
+
* function living anywhere else is unreachable without naming its schema. The
|
|
186
|
+
* generated publishing functions live in `supatype` for exactly the reason they
|
|
187
|
+
* are generated at all: they are the stack's, not the project's, and putting them
|
|
188
|
+
* in the managed schema would collide with a model called `publish`.
|
|
189
|
+
*/
|
|
190
|
+
export interface RpcOptions {
|
|
191
|
+
head?: boolean | undefined
|
|
192
|
+
count?: "exact" | "planned" | "estimated" | undefined
|
|
193
|
+
/** Postgres schema holding the function, sent as `Content-Profile`. */
|
|
194
|
+
schema?: string | undefined
|
|
195
|
+
}
|
|
196
|
+
|
|
180
197
|
export interface RpcResult<TData> {
|
|
181
198
|
data: TData | null
|
|
182
199
|
error: SupatypeError | null
|
|
@@ -276,9 +293,27 @@ export interface AuthStorage {
|
|
|
276
293
|
removeItem(key: string): void | Promise<void>
|
|
277
294
|
}
|
|
278
295
|
|
|
296
|
+
/**
|
|
297
|
+
* The schema holding one draft view per versioned model, selected by `Accept-Profile`.
|
|
298
|
+
*
|
|
299
|
+
* Stated here as well as in the CLI (`project-config.ts`, which puts it on `PGRST_DB_SCHEMA`) and
|
|
300
|
+
* the engine (which creates the views), because the SDK ships standalone and depending on a
|
|
301
|
+
* workspace package for one identifier would be a worse trade than three call sites naming it.
|
|
302
|
+
* Changing it means changing all three, the same as `api` for the field-masking views.
|
|
303
|
+
*/
|
|
304
|
+
export const DRAFT_SCHEMA = "draft"
|
|
305
|
+
|
|
279
306
|
export interface SelectQueryOptions {
|
|
280
307
|
count?: "exact" | "planned" | "estimated" | undefined
|
|
281
308
|
head?: boolean | undefined
|
|
309
|
+
/**
|
|
310
|
+
* PostgREST schema to read from, sent as `Accept-Profile`.
|
|
311
|
+
*
|
|
312
|
+
* Set by `.draft()` rather than by hand: the point of a profile here is that a draft has the same
|
|
313
|
+
* table name and the same row type as what it is a draft of, so the only thing that changes
|
|
314
|
+
* between reading live content and reading the pending edit is which schema answers.
|
|
315
|
+
*/
|
|
316
|
+
profile?: string | undefined
|
|
282
317
|
}
|
|
283
318
|
|
|
284
319
|
export interface SupatypeClientConfig {
|
|
@@ -329,6 +364,23 @@ export interface SupatypeClientConfig {
|
|
|
329
364
|
* before any requests are made.
|
|
330
365
|
*/
|
|
331
366
|
initialSession?: Session | undefined
|
|
367
|
+
/**
|
|
368
|
+
* A preview link's code, used as this client's whole credential.
|
|
369
|
+
*
|
|
370
|
+
* Set it on a client built to serve one preview request. The code names a link the project can
|
|
371
|
+
* revoke, and the client exchanges it for a token that lives about a minute. That token carries
|
|
372
|
+
* no subject, so the bearer is nobody in particular: the database's own policy decides what they
|
|
373
|
+
* may read, and there is no admin key anywhere on the path.
|
|
374
|
+
*
|
|
375
|
+
* **It wins over a signed-in session, deliberately.** A preview route is opened by whoever was
|
|
376
|
+
* sent the link, and some of them will already be logged in as someone with no access to the
|
|
377
|
+
* draft. Falling back to that session would show them "not found" and send them to ask why the
|
|
378
|
+
* post had been deleted.
|
|
379
|
+
*
|
|
380
|
+
* Refused alongside `serviceRoleKey`: a route that has both is a route sending admin credentials
|
|
381
|
+
* down a path meant for strangers, which is the mistake this feature exists to remove.
|
|
382
|
+
*/
|
|
383
|
+
previewCode?: string | undefined
|
|
332
384
|
/**
|
|
333
385
|
* Extra headers merged into every request (e.g. Studio `X-Supatype-Environment`).
|
|
334
386
|
*/
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
+
import { QueryBuilder } from "../src/query.js"
|
|
3
|
+
import { DRAFT_SCHEMA } from "../src/types.js"
|
|
4
|
+
import { createClient } from "../src/index.js"
|
|
5
|
+
|
|
6
|
+
// Reading a draft changes one thing about the request: which schema answers it. Same table name,
|
|
7
|
+
// same row type, one header. These tests pin that the header is actually sent, because a silently
|
|
8
|
+
// dropped `Accept-Profile` reads as "there is no draft" rather than as a failure.
|
|
9
|
+
|
|
10
|
+
const BASE = "http://localhost:18473"
|
|
11
|
+
const HEADERS: Record<string, string> = { apikey: "anon-key" }
|
|
12
|
+
|
|
13
|
+
function captureHeaders(): {
|
|
14
|
+
headers: () => Record<string, string>
|
|
15
|
+
fetch: ReturnType<typeof vi.fn>
|
|
16
|
+
} {
|
|
17
|
+
const fetch = vi.fn().mockResolvedValue({
|
|
18
|
+
ok: true,
|
|
19
|
+
status: 200,
|
|
20
|
+
json: vi.fn().mockResolvedValue([]),
|
|
21
|
+
headers: { get: () => null },
|
|
22
|
+
})
|
|
23
|
+
vi.stubGlobal("fetch", fetch)
|
|
24
|
+
return {
|
|
25
|
+
fetch,
|
|
26
|
+
headers: () => {
|
|
27
|
+
const init = (fetch.mock.calls[0] as [string, { headers: Record<string, string> }])[1]
|
|
28
|
+
return init.headers
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const SESSION_JWT =
|
|
34
|
+
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
|
|
35
|
+
// { "sub": "u1", "role": "authenticated" }
|
|
36
|
+
"eyJzdWIiOiJ1MSIsInJvbGUiOiJhdXRoZW50aWNhdGVkIn0.sig"
|
|
37
|
+
|
|
38
|
+
describe("the draft profile", () => {
|
|
39
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
40
|
+
|
|
41
|
+
it("is sent as Accept-Profile when the query asks for it", async () => {
|
|
42
|
+
const captured = captureHeaders()
|
|
43
|
+
await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id", undefined, undefined, {
|
|
44
|
+
profile: DRAFT_SCHEMA,
|
|
45
|
+
})
|
|
46
|
+
expect(captured.headers()["Accept-Profile"]).toBe("draft")
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it("is absent from an ordinary read, so published content is what a caller gets by default", async () => {
|
|
50
|
+
const captured = captureHeaders()
|
|
51
|
+
await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id")
|
|
52
|
+
expect(captured.headers()["Accept-Profile"]).toBeUndefined()
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it("reaches the request through `from().draft().select()`", async () => {
|
|
56
|
+
const captured = captureHeaders()
|
|
57
|
+
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
58
|
+
await client.from("posts").draft().select("id, title")
|
|
59
|
+
expect(captured.headers()["Accept-Profile"]).toBe("draft")
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it("does not leak onto the next query from the same client", async () => {
|
|
63
|
+
// `from()` builds a fresh table client per call, which is what makes `draft()` safe to be a
|
|
64
|
+
// mutating step. If it ever stopped doing so, one draft read would silently make every
|
|
65
|
+
// subsequent read a draft read.
|
|
66
|
+
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
67
|
+
const drafted = captureHeaders()
|
|
68
|
+
await client.from("posts").draft().select("id")
|
|
69
|
+
expect(drafted.headers()["Accept-Profile"]).toBe("draft")
|
|
70
|
+
|
|
71
|
+
vi.restoreAllMocks()
|
|
72
|
+
const plain = captureHeaders()
|
|
73
|
+
await client.from("posts").select("id")
|
|
74
|
+
expect(plain.headers()["Accept-Profile"]).toBeUndefined()
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it("leaves the count header alone, since a draft read can still be counted", async () => {
|
|
78
|
+
const captured = captureHeaders()
|
|
79
|
+
await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id", undefined, undefined, {
|
|
80
|
+
profile: DRAFT_SCHEMA,
|
|
81
|
+
count: "exact",
|
|
82
|
+
})
|
|
83
|
+
expect(captured.headers()["Accept-Profile"]).toBe("draft")
|
|
84
|
+
expect(captured.headers()["Prefer"]).toBe("count=exact")
|
|
85
|
+
})
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
describe("calling a function outside the default schema", () => {
|
|
89
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
90
|
+
|
|
91
|
+
it("sends Content-Profile so PostgREST looks in the right schema", async () => {
|
|
92
|
+
// Without this the generated publishing functions are unreachable: PostgREST resolves
|
|
93
|
+
// `/rpc/<name>` against the first schema on the exposed list, and `supatype.publish` is not
|
|
94
|
+
// in it. The failure is a 404 that reads as "no such function" rather than as a routing
|
|
95
|
+
// mistake.
|
|
96
|
+
const captured = captureHeaders()
|
|
97
|
+
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
98
|
+
await client.rpc("publish" as never, { model_table: "posts" } as never, { schema: "supatype" })
|
|
99
|
+
expect(captured.headers()["Content-Profile"]).toBe("supatype")
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it("sends none for a function in the default schema", async () => {
|
|
103
|
+
const captured = captureHeaders()
|
|
104
|
+
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
105
|
+
await client.rpc("calculate_shipping" as never, {} as never)
|
|
106
|
+
expect(captured.headers()["Content-Profile"]).toBeUndefined()
|
|
107
|
+
})
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
describe("a preview link as the client's credential", () => {
|
|
111
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* A fetch that answers the exchange and records every other request.
|
|
115
|
+
*
|
|
116
|
+
* The link is a short code now rather than a signed token, so the first thing a preview client
|
|
117
|
+
* does is trade it in. That trade is why revoking one link works at all, and it means the header
|
|
118
|
+
* these tests care about is on the *second* request, not the first.
|
|
119
|
+
*/
|
|
120
|
+
function previewFetch(exchange: { ok: boolean; token?: string; expiresAt?: string }): {
|
|
121
|
+
calls: () => Array<[string, { headers: Record<string, string> }]>
|
|
122
|
+
queryHeaders: () => Record<string, string>
|
|
123
|
+
exchanges: () => number
|
|
124
|
+
} {
|
|
125
|
+
const fetch = vi.fn().mockImplementation((url: string) => {
|
|
126
|
+
if (url.endsWith("/preview-links/resolve")) {
|
|
127
|
+
return Promise.resolve({
|
|
128
|
+
ok: exchange.ok,
|
|
129
|
+
status: exchange.ok ? 200 : 404,
|
|
130
|
+
json: () =>
|
|
131
|
+
Promise.resolve(
|
|
132
|
+
exchange.ok
|
|
133
|
+
? { token: exchange.token, expiresAt: exchange.expiresAt }
|
|
134
|
+
: { error: "gone" },
|
|
135
|
+
),
|
|
136
|
+
headers: { get: () => null },
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
return Promise.resolve({
|
|
140
|
+
ok: true,
|
|
141
|
+
status: 200,
|
|
142
|
+
json: () => Promise.resolve([]),
|
|
143
|
+
headers: { get: () => null },
|
|
144
|
+
})
|
|
145
|
+
})
|
|
146
|
+
vi.stubGlobal("fetch", fetch)
|
|
147
|
+
const calls = (): Array<[string, { headers: Record<string, string> }]> =>
|
|
148
|
+
fetch.mock.calls as Array<[string, { headers: Record<string, string> }]>
|
|
149
|
+
return {
|
|
150
|
+
calls,
|
|
151
|
+
exchanges: () => calls().filter(([url]) => url.endsWith("/preview-links/resolve")).length,
|
|
152
|
+
queryHeaders: () => {
|
|
153
|
+
const call = calls().find(([url]) => !url.endsWith("/preview-links/resolve"))
|
|
154
|
+
if (call === undefined) throw new Error("no query was made")
|
|
155
|
+
return call[1].headers
|
|
156
|
+
},
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const anHour = (): string => new Date(Date.now() + 3_600_000).toISOString()
|
|
161
|
+
|
|
162
|
+
it("exchanges the code and sends what it gets back", async () => {
|
|
163
|
+
const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
|
|
164
|
+
const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
|
|
165
|
+
await client.from("posts").draft().select("id")
|
|
166
|
+
expect(f.queryHeaders()["Authorization"]).toBe("Bearer exchanged.jwt")
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
it("never puts the code itself on the query", async () => {
|
|
170
|
+
// The code is the credential and the exchange endpoint is the only thing that should ever see
|
|
171
|
+
// it. Sending it onward would put it in the logs of everything downstream.
|
|
172
|
+
const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
|
|
173
|
+
const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
|
|
174
|
+
await client.from("posts").draft().select("id")
|
|
175
|
+
expect(JSON.stringify(f.queryHeaders())).not.toContain("pl_abc")
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
it("keeps the anon apikey beside it, which the gateway still wants", async () => {
|
|
179
|
+
const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
|
|
180
|
+
const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
|
|
181
|
+
await client.from("posts").draft().select("id")
|
|
182
|
+
expect(f.queryHeaders()["apikey"]).toBe("anon-key")
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
it("exchanges once for several queries in flight together", async () => {
|
|
186
|
+
// Concurrent callers must share one exchange rather than each starting their own.
|
|
187
|
+
const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
|
|
188
|
+
const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
|
|
189
|
+
await Promise.all([
|
|
190
|
+
client.from("posts").draft().select("id"),
|
|
191
|
+
client.from("posts").draft().select("title"),
|
|
192
|
+
client.from("authors").draft().select("id"),
|
|
193
|
+
])
|
|
194
|
+
expect(f.exchanges()).toBe(1)
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
it("keeps the exchanged token for queries that come later", async () => {
|
|
198
|
+
// Sequential, deliberately. Awaiting each one in turn means nothing is in flight to share, so
|
|
199
|
+
// this is the only one of the two that fails if the token stops being cached: a page that
|
|
200
|
+
// loads, then filters, then paginates would otherwise pay a round trip every time.
|
|
201
|
+
const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
|
|
202
|
+
const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
|
|
203
|
+
await client.from("posts").draft().select("id")
|
|
204
|
+
await client.from("posts").draft().select("title")
|
|
205
|
+
await client.from("authors").draft().select("id")
|
|
206
|
+
expect(f.exchanges()).toBe(1)
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
it("reports a revoked link as an error rather than throwing", async () => {
|
|
210
|
+
// The whole point of per-link revocation is that this happens. It has to arrive as a message a
|
|
211
|
+
// preview route can render, not as an exception that takes the page down.
|
|
212
|
+
previewFetch({ ok: false })
|
|
213
|
+
const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_dead.secret" })
|
|
214
|
+
const { data, error } = await client.from("posts").draft().select("id")
|
|
215
|
+
expect(data).toBeNull()
|
|
216
|
+
expect(error?.message).toMatch(/expired, or been revoked/)
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
it("refuses to be built beside a service role key", () => {
|
|
220
|
+
// The two are never both correct: a route with both is sending admin credentials down a path
|
|
221
|
+
// meant for strangers, which is what the preview link exists to remove.
|
|
222
|
+
expect(() =>
|
|
223
|
+
createClient({
|
|
224
|
+
url: BASE,
|
|
225
|
+
anonKey: "anon-key",
|
|
226
|
+
previewCode: "pl_abc.secret",
|
|
227
|
+
serviceRoleKey: "service.jwt",
|
|
228
|
+
}),
|
|
229
|
+
).toThrow(/cannot carry both/)
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
it("leaves an ordinary client alone", async () => {
|
|
233
|
+
const captured = captureHeaders()
|
|
234
|
+
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
235
|
+
await client.from("posts").select("id")
|
|
236
|
+
expect(captured.headers()["Authorization"]).toBe("Bearer anon-key")
|
|
237
|
+
})
|
|
238
|
+
})
|
|
239
|
+
|
|
240
|
+
describe("what storage sends as its credential", () => {
|
|
241
|
+
// Storage was handed a plain headers object built when the client was constructed — before
|
|
242
|
+
// anybody has signed in. Every storage request therefore carried the anon key for the life of the
|
|
243
|
+
// page: an app's per-user storage policies saw `anon` rather than the caller, and through Studio's
|
|
244
|
+
// proxy the request was refused outright, because an anon key carries no `sub` and the proxy
|
|
245
|
+
// requires one. The symptom was "Token missing subject claim" on a page that lists buckets.
|
|
246
|
+
//
|
|
247
|
+
// Every other client on the object already resolved its headers per request. Storage was the one
|
|
248
|
+
// that did not.
|
|
249
|
+
|
|
250
|
+
function captureHeaders(): { headers: () => Record<string, string> } {
|
|
251
|
+
const fetchMock = vi.fn().mockResolvedValue({
|
|
252
|
+
ok: true,
|
|
253
|
+
status: 200,
|
|
254
|
+
json: vi.fn().mockResolvedValue([]),
|
|
255
|
+
headers: { get: () => null },
|
|
256
|
+
})
|
|
257
|
+
vi.stubGlobal("fetch", fetchMock)
|
|
258
|
+
return {
|
|
259
|
+
headers: () => {
|
|
260
|
+
const call = fetchMock.mock.calls[0] as [string, { headers: Record<string, string> }]
|
|
261
|
+
return call[1].headers
|
|
262
|
+
},
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
it("uses the signed-in session, not the anon key it was built with", async () => {
|
|
267
|
+
const captured = captureHeaders()
|
|
268
|
+
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
269
|
+
// A session arriving after construction, which is the ordinary case: the client is built while
|
|
270
|
+
// the page loads and the person signs in afterwards.
|
|
271
|
+
;(client.auth as unknown as { currentSession: unknown }).currentSession = {
|
|
272
|
+
accessToken: SESSION_JWT,
|
|
273
|
+
refreshToken: "r",
|
|
274
|
+
expiresAt: Math.floor(Date.now() / 1000) + 3600,
|
|
275
|
+
user: { id: "u1" },
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
await client.storage.listBuckets()
|
|
279
|
+
expect(captured.headers()["Authorization"]).toBe(`Bearer ${SESSION_JWT}`)
|
|
280
|
+
})
|
|
281
|
+
|
|
282
|
+
it("falls back to the anon key when nobody is signed in", async () => {
|
|
283
|
+
const captured = captureHeaders()
|
|
284
|
+
const client = createClient({ url: BASE, anonKey: "anon-key" })
|
|
285
|
+
await client.storage.listBuckets()
|
|
286
|
+
expect(captured.headers()["Authorization"]).toBe("Bearer anon-key")
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
it("uses the service role when the caller holds one", async () => {
|
|
290
|
+
// Studio's own admin tooling, and anything else listing every bucket regardless of policy.
|
|
291
|
+
const captured = captureHeaders()
|
|
292
|
+
const client = createClient({ url: BASE, anonKey: "anon-key", serviceRoleKey: "service.jwt" })
|
|
293
|
+
await client.storage.listBuckets()
|
|
294
|
+
expect(captured.headers()["Authorization"]).toBe("Bearer service.jwt")
|
|
295
|
+
})
|
|
296
|
+
})
|
|
@@ -13,7 +13,8 @@ const STORAGE_URL = "http://localhost:18473/storage/v1"
|
|
|
13
13
|
const HEADERS = { apikey: "test-anon-key", Authorization: "Bearer test-token" }
|
|
14
14
|
|
|
15
15
|
function freshClient(): StorageClient {
|
|
16
|
-
|
|
16
|
+
// Headers are asked for per request now, so a session arriving after construction is used.
|
|
17
|
+
return new StorageClient(STORAGE_URL, () => Promise.resolve(HEADERS))
|
|
17
18
|
}
|
|
18
19
|
|
|
19
20
|
function createMockBlob(sizeBytes: number): Blob {
|
|
@@ -13,7 +13,8 @@ const STORAGE_URL = "http://localhost:18473/storage/v1"
|
|
|
13
13
|
const HEADERS = { apikey: "test-anon-key", Authorization: "Bearer test-token" }
|
|
14
14
|
|
|
15
15
|
function freshClient(): StorageClient {
|
|
16
|
-
|
|
16
|
+
// Headers are asked for per request now, so a session arriving after construction is used.
|
|
17
|
+
return new StorageClient(STORAGE_URL, () => Promise.resolve(HEADERS))
|
|
17
18
|
}
|
|
18
19
|
|
|
19
20
|
function createMockBlob(sizeBytes: number): Blob {
|