@supatype/client 0.2.1 → 0.3.1
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 +25 -21
- package/.turbo/turbo-typecheck.log +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/identity.d.ts +29 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +30 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +46 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +96 -14
- 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.map +1 -1
- package/dist/query-cache.js +2 -8
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +12 -0
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +23 -1
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +61 -3
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +162 -22
- package/dist/realtime.js.map +1 -1
- package/dist/storage.d.ts +27 -2
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +35 -8
- 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/auth.ts +1 -1
- package/src/identity.ts +43 -0
- package/src/index.ts +123 -16
- package/src/preview.ts +102 -0
- package/src/query-cache.ts +2 -9
- package/src/query.ts +23 -1
- package/src/realtime.ts +166 -25
- package/src/storage.ts +42 -12
- package/src/types.ts +52 -0
- package/tests/draft-profile.test.ts +296 -0
- package/tests/helpers/mock-websocket.ts +70 -0
- package/tests/identity-change.test.ts +120 -0
- package/tests/realtime-multi-tenant-integration.test.ts +5 -50
- package/tests/realtime-session-auth.test.ts +177 -0
- package/tests/signed-url-absolute.test.ts +84 -0
- package/tests/storage-quota-integration.test.ts +2 -1
- package/tests/storage-upload-limit-integration.test.ts +2 -1
- package/tests/subscribe-frame.test.ts +102 -0
- package/tsconfig.tsbuildinfo +1 -1
package/package.json
CHANGED
package/src/auth.ts
CHANGED
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
PKCE_METHOD_S256,
|
|
18
18
|
} from "./pkce.js"
|
|
19
19
|
|
|
20
|
-
type AuthListener = (event: AuthChangeEvent, session: Session | null) => void
|
|
20
|
+
export type AuthListener = (event: AuthChangeEvent, session: Session | null) => void
|
|
21
21
|
|
|
22
22
|
interface AuthClientOptions {
|
|
23
23
|
initialSession?: Session | undefined
|
package/src/identity.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { AuthListener } from "./auth.js"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The part of `AuthClient` this needs.
|
|
5
|
+
*
|
|
6
|
+
* Structural rather than the class itself so a caller, and a test, can supply anything that emits
|
|
7
|
+
* auth changes without constructing a whole client. The callback is `AuthListener`, the same type
|
|
8
|
+
* the real `onAuthStateChange` takes, so the stand-in cannot drift from what it stands in for.
|
|
9
|
+
*/
|
|
10
|
+
export interface IdentitySource {
|
|
11
|
+
onAuthStateChange(callback: AuthListener): {
|
|
12
|
+
data: { subscription: { unsubscribe(): void } }
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Call `onChange` whenever the signed-in identity changes, and not otherwise.
|
|
18
|
+
*
|
|
19
|
+
* `onAuthStateChange` also fires once at registration and again on every token refresh. A data hook
|
|
20
|
+
* subscribed to it raw would refetch on a timer for as long as the page stayed open, and would
|
|
21
|
+
* refetch once more immediately after the fetch it already makes on mount. This narrows the stream
|
|
22
|
+
* to the only transition that changes what a query is allowed to read: a different user, or none.
|
|
23
|
+
*
|
|
24
|
+
* Returns the unsubscribe function, so a caller can hand it straight to its own teardown hook.
|
|
25
|
+
*/
|
|
26
|
+
export function onIdentityChange(auth: IdentitySource, onChange: () => void): () => void {
|
|
27
|
+
// `undefined` until the registration emission has established the baseline, so that emission is
|
|
28
|
+
// not itself read as a change.
|
|
29
|
+
let known: string | null | undefined
|
|
30
|
+
const { data } = auth.onAuthStateChange((_event, session) => {
|
|
31
|
+
const userId = session?.user.id ?? null
|
|
32
|
+
if (known === undefined) {
|
|
33
|
+
known = userId
|
|
34
|
+
return
|
|
35
|
+
}
|
|
36
|
+
if (userId === known) return
|
|
37
|
+
known = userId
|
|
38
|
+
onChange()
|
|
39
|
+
})
|
|
40
|
+
return () => {
|
|
41
|
+
data.subscription.unsubscribe()
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { AuthClient } from "./auth.js"
|
|
2
|
+
import { onIdentityChange } from "./identity.js"
|
|
3
|
+
import { PreviewCredential } from "./preview.js"
|
|
2
4
|
import { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
|
|
3
5
|
import { defaultQueryCache, type QueryCache } from "./query-cache.js"
|
|
4
6
|
import { StorageClient } from "./storage.js"
|
|
@@ -15,8 +17,10 @@ import type {
|
|
|
15
17
|
SupatypeFunctions,
|
|
16
18
|
SupatypeClientConfig,
|
|
17
19
|
SupatypeError,
|
|
20
|
+
RpcOptions,
|
|
18
21
|
SelectQueryOptions,
|
|
19
22
|
} from "./types.js"
|
|
23
|
+
import { DRAFT_SCHEMA } from "./types.js"
|
|
20
24
|
|
|
21
25
|
export type {
|
|
22
26
|
User,
|
|
@@ -31,6 +35,7 @@ export type {
|
|
|
31
35
|
SupatypeClientConfig,
|
|
32
36
|
FunctionDef,
|
|
33
37
|
AuthStorage,
|
|
38
|
+
RpcOptions,
|
|
34
39
|
SelectQueryOptions,
|
|
35
40
|
TableDef,
|
|
36
41
|
TableInsert,
|
|
@@ -44,8 +49,25 @@ export {
|
|
|
44
49
|
createCodeChallengeS256,
|
|
45
50
|
PKCE_METHOD_S256,
|
|
46
51
|
} from "./pkce.js"
|
|
52
|
+
export { DRAFT_SCHEMA } from "./types.js"
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A client whose database type the holder does not know.
|
|
56
|
+
*
|
|
57
|
+
* What every framework binding's context, provider or injection key is typed at. A context is one
|
|
58
|
+
* value shared by many consumers, so it cannot be generic, and at the `AugmentedDatabase` default
|
|
59
|
+
* it rejected `createClient<Database>(...)`, the client every real project builds. `AnyDatabase` is
|
|
60
|
+
* the constraint every generated database satisfies, so the typed client goes in unchanged and each
|
|
61
|
+
* binding's `useSupatype<TDatabase>()` narrows it on the way back out.
|
|
62
|
+
*
|
|
63
|
+
* Named here rather than spelled out in four packages so the decision has one home. It is also not
|
|
64
|
+
* `any`: that widening is one TypeScript already allows, so `any` bought nothing and cost every
|
|
65
|
+
* consumer its checking.
|
|
66
|
+
*/
|
|
67
|
+
export type AnyClient = SupatypeClient<AnyDatabase>
|
|
47
68
|
export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
48
69
|
export { AuthClient } from "./auth.js"
|
|
70
|
+
export { onIdentityChange, type IdentitySource } from "./identity.js"
|
|
49
71
|
export { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
|
|
50
72
|
export { QueryCache, defaultQueryCache } from "./query-cache.js"
|
|
51
73
|
export { StorageClient, BucketClient } from "./storage.js"
|
|
@@ -61,6 +83,7 @@ export { ERROR_CODES_DOCUMENTATION, getErrorDocumentation, getErrorCodesByCatego
|
|
|
61
83
|
export type { ErrorCodeEntry } from "./error-codes-doc.js"
|
|
62
84
|
export { CONNECTION_MODES, SERVERLESS_CONNECTION_WARNING, CONNECTION_FAQ } from "./serverless-docs.js"
|
|
63
85
|
export type { ConnectionModeDoc } from "./serverless-docs.js"
|
|
86
|
+
export { PreviewLinkError } from "./preview.js"
|
|
64
87
|
|
|
65
88
|
// ─── Table client ─────────────────────────────────────────────────────────────
|
|
66
89
|
|
|
@@ -78,6 +101,14 @@ class TableClient<TDef extends TableDef> {
|
|
|
78
101
|
private readonly onUnauthorized: (() => Promise<void>) | undefined
|
|
79
102
|
private readonly queryCache: QueryCache
|
|
80
103
|
private readonly realtime: RealtimeClient
|
|
104
|
+
/**
|
|
105
|
+
* The schema this table's reads come from, set by `draft()`.
|
|
106
|
+
*
|
|
107
|
+
* Mutable, and safe to be: `from()` builds a fresh client per call, so nothing is shared between
|
|
108
|
+
* two queries. Reads only; a draft view is not writable and a write is an ordinary update that
|
|
109
|
+
* records a new version.
|
|
110
|
+
*/
|
|
111
|
+
private profile: string | undefined
|
|
81
112
|
|
|
82
113
|
constructor(
|
|
83
114
|
baseUrl: string,
|
|
@@ -96,6 +127,28 @@ class TableClient<TDef extends TableDef> {
|
|
|
96
127
|
this.queryCache = queryCache
|
|
97
128
|
}
|
|
98
129
|
|
|
130
|
+
/**
|
|
131
|
+
* Read the pending draft instead of what is published.
|
|
132
|
+
*
|
|
133
|
+
* ```typescript
|
|
134
|
+
* const { data } = await supatype.from("posts").draft().select("id, title, body")
|
|
135
|
+
* ```
|
|
136
|
+
*
|
|
137
|
+
* Selects the generated `draft` schema, whose views carry the same row type as the table, so the
|
|
138
|
+
* only thing that changes is which schema answers. Available on models that declare `versions`;
|
|
139
|
+
* anything else has no draft view and answers `PGRST106`.
|
|
140
|
+
*
|
|
141
|
+
* **Read-only, and permission is not the read rule.** A draft is visible to the record's creator
|
|
142
|
+
* and to the project's elevated Studio roles, or to a caller holding a signed preview link. A
|
|
143
|
+
* caller who may read published content is not thereby entitled to read what has not been
|
|
144
|
+
* published. Write with the ordinary `update`, which records a new draft version; publish with
|
|
145
|
+
* `supatype.publish`.
|
|
146
|
+
*/
|
|
147
|
+
draft(): this {
|
|
148
|
+
this.profile = DRAFT_SCHEMA
|
|
149
|
+
return this
|
|
150
|
+
}
|
|
151
|
+
|
|
99
152
|
select<TResult = TDef["Row"]>(
|
|
100
153
|
columns?: string | undefined,
|
|
101
154
|
options?: SelectQueryOptions | undefined,
|
|
@@ -107,7 +160,9 @@ class TableClient<TDef extends TableDef> {
|
|
|
107
160
|
columns,
|
|
108
161
|
this.queryCache,
|
|
109
162
|
this.onUnauthorized,
|
|
110
|
-
options
|
|
163
|
+
// The profile joins the select options rather than riding a longer constructor: it is a
|
|
164
|
+
// property of the request being described, like `count` and `head` beside it.
|
|
165
|
+
{ ...options, ...(this.profile !== undefined && { profile: this.profile }) },
|
|
111
166
|
)
|
|
112
167
|
}
|
|
113
168
|
|
|
@@ -418,7 +473,7 @@ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabas
|
|
|
418
473
|
rpc<TFn extends FunctionNames<TDatabase>>(
|
|
419
474
|
fn: TFn,
|
|
420
475
|
params?: FunctionArgs<TDatabase, TFn> | undefined,
|
|
421
|
-
options?:
|
|
476
|
+
options?: RpcOptions | undefined,
|
|
422
477
|
): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>>
|
|
423
478
|
}
|
|
424
479
|
|
|
@@ -428,6 +483,24 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
428
483
|
// Warn early if a direct Postgres URL is used in a serverless environment
|
|
429
484
|
warnIfServerlessDirectConnection(config.url)
|
|
430
485
|
|
|
486
|
+
// A client with both is a route sending admin credentials down a path meant for strangers, which
|
|
487
|
+
// is precisely what the preview link exists to remove. Thrown rather than warned: the two are
|
|
488
|
+
// never both correct, and a warning in a server log is not read by whoever wrote the route.
|
|
489
|
+
if (config.previewCode !== undefined && config.serviceRoleKey !== undefined) {
|
|
490
|
+
throw new Error(
|
|
491
|
+
"A Supatype client cannot carry both `previewCode` and `serviceRoleKey`. A preview link is " +
|
|
492
|
+
"the bearer's whole credential and needs no admin key; sending one anyway would let " +
|
|
493
|
+
"anybody who reached that route read everything.",
|
|
494
|
+
)
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// Built once and shared by every request this client makes, so a page rendering several queries
|
|
498
|
+
// exchanges the code once rather than once per table.
|
|
499
|
+
const previewCredential =
|
|
500
|
+
config.previewCode === undefined || config.previewCode === ""
|
|
501
|
+
? null
|
|
502
|
+
: new PreviewCredential(config.url, config.previewCode)
|
|
503
|
+
|
|
431
504
|
const baseHeaders: Record<string, string> = {
|
|
432
505
|
apikey: config.anonKey,
|
|
433
506
|
Authorization: `Bearer ${config.anonKey}`,
|
|
@@ -448,19 +521,6 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
448
521
|
cookiePrefix: config.auth?.cookiePrefix,
|
|
449
522
|
storage: config.auth?.storage,
|
|
450
523
|
})
|
|
451
|
-
// Storage admin operations (listBuckets, createBucket, etc.) require service_role.
|
|
452
|
-
// When a service role key is provided (developer tools like Studio), use it for
|
|
453
|
-
// storage so admin calls are authorised; otherwise fall back to the anon headers.
|
|
454
|
-
const storageHeaders: Record<string, string> = config.serviceRoleKey
|
|
455
|
-
? {
|
|
456
|
-
apikey: config.serviceRoleKey,
|
|
457
|
-
Authorization: `Bearer ${config.serviceRoleKey}`,
|
|
458
|
-
"Content-Type": "application/json",
|
|
459
|
-
...config.headers,
|
|
460
|
-
}
|
|
461
|
-
: baseHeaders
|
|
462
|
-
const storage = new StorageClient(`${config.url}/storage/v1`, storageHeaders)
|
|
463
|
-
const realtime = new RealtimeClient(`${config.url}/realtime/v1`, baseHeaders)
|
|
464
524
|
const queryCache = config.queryCache ?? defaultQueryCache
|
|
465
525
|
|
|
466
526
|
const getAuthHeaders = async (): Promise<Record<string, string>> => {
|
|
@@ -474,6 +534,14 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
474
534
|
...config.headers,
|
|
475
535
|
}
|
|
476
536
|
}
|
|
537
|
+
// A preview link is the whole credential, and it comes before any session on purpose: whoever
|
|
538
|
+
// opened the link may well be signed in as someone with no access to the draft, and quietly
|
|
539
|
+
// using that identity would show them "not found".
|
|
540
|
+
if (previewCredential !== null) {
|
|
541
|
+
// Throws when the link will not resolve. The query layer turns that into an ordinary
|
|
542
|
+
// `{ data: null, error }`, so a revoked link reads as a message rather than as a crash.
|
|
543
|
+
return { ...baseHeaders, Authorization: `Bearer ${await previewCredential.token()}` }
|
|
544
|
+
}
|
|
477
545
|
await auth.ensureValidSession()
|
|
478
546
|
const token = auth.currentAccessToken
|
|
479
547
|
if (token !== null) {
|
|
@@ -487,12 +555,45 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
487
555
|
return baseHeaders
|
|
488
556
|
}
|
|
489
557
|
|
|
558
|
+
// Storage asks for headers per request, like every other client here.
|
|
559
|
+
//
|
|
560
|
+
// It used to be handed a plain object built above, before anybody had signed in, so every storage
|
|
561
|
+
// request carried the anon key for the life of the page. An app's per-user storage policies saw
|
|
562
|
+
// `anon` rather than the caller, and through Studio's proxy the request was refused outright,
|
|
563
|
+
// because an anon key carries no `sub` and the proxy requires one.
|
|
564
|
+
const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders)
|
|
565
|
+
|
|
566
|
+
// The same provider the other sub-clients get, not `baseHeaders`.
|
|
567
|
+
//
|
|
568
|
+
// `baseHeaders` is built once and never mutated, so handing it over pinned every socket to the
|
|
569
|
+
// anon key for the life of the page. Realtime enforces RLS, so on a table that is not
|
|
570
|
+
// anon-readable the socket reported SUBSCRIBED and delivered nothing, which is exactly the
|
|
571
|
+
// failure the storage note above describes.
|
|
572
|
+
const realtime = new RealtimeClient(`${config.url}/realtime/v1`, getAuthHeaders)
|
|
573
|
+
|
|
490
574
|
const onUnauthorized = config.serviceRoleKey
|
|
491
575
|
? undefined
|
|
492
576
|
: (): Promise<void> => auth.ensureValidSession()
|
|
493
577
|
|
|
494
578
|
const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
|
|
495
579
|
|
|
580
|
+
// Signing in has to reach an already-open socket.
|
|
581
|
+
//
|
|
582
|
+
// Every binding subscribes when its component mounts, which is before the user has signed in, so
|
|
583
|
+
// the socket that matters is always one opened while signed out. Resolving the token per
|
|
584
|
+
// connection is not enough on its own; something has to tell the connection it is now stale.
|
|
585
|
+
//
|
|
586
|
+
// `onIdentityChange`, not `onAuthStateChange`: a refreshed token is a different string for the
|
|
587
|
+
// same person, and reconnecting on it would close and re-open the socket once an hour for the
|
|
588
|
+
// life of the tab, losing every change committed in the gap. That is the silent miss this whole
|
|
589
|
+
// change exists to remove, so it must not be reintroduced by the fix.
|
|
590
|
+
//
|
|
591
|
+
// The subscription is never torn down. The listener is held by `auth` and closes over `realtime`,
|
|
592
|
+
// both owned by this client, so the cycle is collected whole when the client is dropped.
|
|
593
|
+
onIdentityChange(auth, () => {
|
|
594
|
+
void realtime.reauthenticate()
|
|
595
|
+
})
|
|
596
|
+
|
|
496
597
|
return {
|
|
497
598
|
url: config.url,
|
|
498
599
|
serviceRoleKey: config.serviceRoleKey,
|
|
@@ -576,7 +677,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
576
677
|
async rpc<TFn extends FunctionNames<TDatabase>>(
|
|
577
678
|
fn: TFn,
|
|
578
679
|
params?: FunctionArgs<TDatabase, TFn> | undefined,
|
|
579
|
-
options?:
|
|
680
|
+
options?: RpcOptions | undefined,
|
|
580
681
|
): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>> {
|
|
581
682
|
const headers: Record<string, string> = { ...(await getAuthHeaders()) }
|
|
582
683
|
const method = options?.head === true ? "HEAD" : "POST"
|
|
@@ -584,6 +685,12 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
584
685
|
if (options?.count !== undefined) {
|
|
585
686
|
headers["Prefer"] = `count=${options.count}`
|
|
586
687
|
}
|
|
688
|
+
// PostgREST resolves `/rpc/<name>` against the default profile, so a function in any other
|
|
689
|
+
// schema is unreachable without this. `Content-Profile` rather than `Accept-Profile`, because
|
|
690
|
+
// an RPC call is a POST and PostgREST reads the write-side header for it.
|
|
691
|
+
if (options?.schema !== undefined) {
|
|
692
|
+
headers["Content-Profile"] = options.schema
|
|
693
|
+
}
|
|
587
694
|
|
|
588
695
|
let res: Response
|
|
589
696
|
try {
|
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
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { QueryResult } from "./types.js"
|
|
2
2
|
import { sha256Hex } from "./sha256-hex.js"
|
|
3
|
+
import { bearerToken } from "./query.js"
|
|
3
4
|
|
|
4
5
|
export interface QueryCacheOptions {
|
|
5
6
|
/** Client-side TTL in milliseconds. */
|
|
@@ -26,14 +27,6 @@ interface JwtPayload {
|
|
|
26
27
|
role?: string
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
function bearerOrApikey(headers: Record<string, string>): string {
|
|
30
|
-
const auth = headers["Authorization"] ?? headers["authorization"] ?? ""
|
|
31
|
-
if (auth.startsWith("Bearer ")) {
|
|
32
|
-
return auth.slice("Bearer ".length)
|
|
33
|
-
}
|
|
34
|
-
return headers["apikey"] ?? headers["Apikey"] ?? ""
|
|
35
|
-
}
|
|
36
|
-
|
|
37
30
|
function parseJwtPayload(token: string): JwtPayload | null {
|
|
38
31
|
const parts = token.split(".")
|
|
39
32
|
if (parts.length !== 3) return null
|
|
@@ -51,7 +44,7 @@ export function identityFingerprint(
|
|
|
51
44
|
scope: "public" | "user",
|
|
52
45
|
): string {
|
|
53
46
|
if (scope === "public") return "global"
|
|
54
|
-
const token =
|
|
47
|
+
const token = bearerToken(headers)
|
|
55
48
|
if (!token) return "anon"
|
|
56
49
|
const claims = parseJwtPayload(token)
|
|
57
50
|
const role = claims?.role?.trim() || "authenticated"
|
package/src/query.ts
CHANGED
|
@@ -64,13 +64,29 @@ function withMeta<T>(
|
|
|
64
64
|
/** Resolves auth (and other) headers at request time so token refresh can run first. */
|
|
65
65
|
export type HeadersProvider = () => Promise<Record<string, string>>
|
|
66
66
|
|
|
67
|
-
function asHeadersProvider(
|
|
67
|
+
export function asHeadersProvider(
|
|
68
68
|
headers: Record<string, string> | HeadersProvider,
|
|
69
69
|
): HeadersProvider {
|
|
70
70
|
if (typeof headers === "function") return headers
|
|
71
71
|
return () => Promise.resolve(headers)
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
/**
|
|
75
|
+
* The caller's own token out of a header set: the session's bearer, else the apikey.
|
|
76
|
+
*
|
|
77
|
+
* One home for a rule three places had implemented separately. The realtime socket had the
|
|
78
|
+
* precedence the other way round, which is how it came to authenticate as anon on every
|
|
79
|
+
* connection: `apikey` is always set, so it never reached the Authorization header.
|
|
80
|
+
*
|
|
81
|
+
* Header names are matched in both casings because `config.headers` is caller-supplied and
|
|
82
|
+
* lowercase is just as valid over the wire.
|
|
83
|
+
*/
|
|
84
|
+
export function bearerToken(headers: Record<string, string>): string {
|
|
85
|
+
const authorization = headers["Authorization"] ?? headers["authorization"] ?? ""
|
|
86
|
+
if (authorization.startsWith("Bearer ")) return authorization.slice("Bearer ".length)
|
|
87
|
+
return headers["apikey"] ?? headers["Apikey"] ?? ""
|
|
88
|
+
}
|
|
89
|
+
|
|
74
90
|
async function fetchWithOptional401Retry(
|
|
75
91
|
url: string,
|
|
76
92
|
init: RequestInit,
|
|
@@ -125,6 +141,12 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
125
141
|
if (this.countMode !== undefined) {
|
|
126
142
|
this.extraHeaders["Prefer"] = `count=${this.countMode}`
|
|
127
143
|
}
|
|
144
|
+
// A profile picks the schema that answers, which is how a draft is read: same table name, same
|
|
145
|
+
// row type, one header. Set at construction rather than as a chainable step, so it cannot be
|
|
146
|
+
// added to a request that has already been described.
|
|
147
|
+
if (selectOptions?.profile !== undefined) {
|
|
148
|
+
this.extraHeaders["Accept-Profile"] = selectOptions.profile
|
|
149
|
+
}
|
|
128
150
|
}
|
|
129
151
|
|
|
130
152
|
/** Enable GET caching. Use `{ server: true }` for Valkey-backed server cache. */
|