@supatype/client 0.9.0 → 0.9.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 +71 -68
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +82 -0
- package/dist/auth.d.ts +41 -6
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +102 -32
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +3 -0
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +2 -0
- package/dist/bindings.js.map +1 -1
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +7 -0
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +81 -21
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +133 -46
- package/dist/errors.js.map +1 -1
- package/dist/graphql-transport.d.ts +8 -1
- package/dist/graphql-transport.d.ts.map +1 -1
- package/dist/graphql-transport.js +5 -5
- package/dist/graphql-transport.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +52 -37
- package/dist/index.js.map +1 -1
- package/dist/latest-rows.d.ts +29 -0
- package/dist/latest-rows.d.ts.map +1 -0
- package/dist/latest-rows.js +51 -0
- package/dist/latest-rows.js.map +1 -0
- package/dist/mutation-request.d.ts +2 -1
- package/dist/mutation-request.d.ts.map +1 -1
- package/dist/mutation-request.js +2 -1
- package/dist/mutation-request.js.map +1 -1
- package/dist/page-env-script.d.ts +12 -0
- package/dist/page-env-script.d.ts.map +1 -0
- package/dist/page-env-script.js +30 -0
- package/dist/page-env-script.js.map +1 -0
- package/dist/preview.d.ts +2 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +7 -3
- package/dist/preview.js.map +1 -1
- package/dist/query.d.ts +11 -5
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +22 -13
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +5 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +13 -6
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts +59 -0
- package/dist/runtime-env.d.ts.map +1 -0
- package/dist/runtime-env.js +167 -0
- package/dist/runtime-env.js.map +1 -0
- package/dist/setup-fault.d.ts +13 -0
- package/dist/setup-fault.d.ts.map +1 -0
- package/dist/setup-fault.js +17 -0
- package/dist/setup-fault.js.map +1 -0
- package/dist/storage.d.ts +10 -5
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +22 -13
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +1 -1
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +3 -2
- package/dist/table-subscription.js.map +1 -1
- package/dist/thrown-error.d.ts +16 -0
- package/dist/thrown-error.d.ts.map +1 -0
- package/dist/thrown-error.js +31 -0
- package/dist/thrown-error.js.map +1 -0
- package/dist/types.d.ts +59 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -1
- package/src/auth.ts +106 -36
- package/src/bindings.ts +3 -0
- package/src/error-codes-doc.ts +9 -1
- package/src/errors.ts +155 -57
- package/src/graphql-transport.ts +5 -6
- package/src/index.ts +62 -44
- package/src/latest-rows.ts +78 -0
- package/src/mutation-request.ts +3 -2
- package/src/page-env-script.ts +27 -0
- package/src/preview.ts +8 -4
- package/src/query.ts +27 -16
- package/src/realtime.ts +15 -6
- package/src/runtime-env.ts +220 -0
- package/src/setup-fault.ts +18 -0
- package/src/storage.ts +26 -16
- package/src/table-subscription.ts +3 -3
- package/src/thrown-error.ts +31 -0
- package/src/types.ts +65 -14
- package/tests/auth-errors.test.ts +3 -3
- package/tests/auth-events.test.ts +3 -7
- package/tests/auth-sso.test.ts +260 -0
- package/tests/auth-url-session.test.ts +6 -25
- package/tests/entry-points.test.ts +9 -0
- package/tests/error-family.test.ts +79 -0
- package/tests/helpers/auth-unmount-binding.ts +63 -0
- package/tests/helpers/oauth-binding.ts +4 -3
- package/tests/helpers/stale-read-binding.ts +113 -0
- package/tests/helpers/thrown-error-binding.ts +127 -0
- package/tests/postgrest-error-codes.test.ts +4 -4
- package/tests/rate-limit-integration.test.ts +1 -1
- package/tests/result-error-class.test.ts +107 -0
- package/tests/retry-policy.test.ts +1 -1
- package/tests/runtime-env-bundle.test.ts +121 -0
- package/tests/runtime-env-page-script.test.ts +174 -0
- package/tests/runtime-env.test.ts +224 -0
- package/tests/server-bodies.test.ts +3 -3
- package/tests/support/browser.ts +28 -0
- package/tests/support/jwt.ts +5 -0
- package/tests/thrown-error.test.ts +59 -0
- package/tsconfig.tsbuildinfo +1 -1
package/src/storage.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { transportFailure } from "./errors.js"
|
|
1
|
+
import { SupatypeError, transportFailure } from "./errors.js"
|
|
3
2
|
import { plainFetch, type RequestTransport } from "./fetch-with-retry.js"
|
|
3
|
+
import { settle, type Deferred } from "./runtime-env.js"
|
|
4
4
|
import {
|
|
5
5
|
isArrayOf,
|
|
6
6
|
isBoolean,
|
|
@@ -191,7 +191,7 @@ async function storageRefusal(res: Response, fallback: string): Promise<string>
|
|
|
191
191
|
}
|
|
192
192
|
|
|
193
193
|
export class StorageClient {
|
|
194
|
-
private readonly
|
|
194
|
+
private readonly base: Deferred<string>
|
|
195
195
|
private readonly headers: AuthHeaders
|
|
196
196
|
private readonly send: RequestTransport
|
|
197
197
|
|
|
@@ -206,14 +206,19 @@ export class StorageClient {
|
|
|
206
206
|
* Every other client on this object already took the same function. Storage was the one that did
|
|
207
207
|
* not.
|
|
208
208
|
*/
|
|
209
|
-
constructor(url: string
|
|
209
|
+
constructor(url: Deferred<string>, headers: AuthHeaders, transport: RequestTransport = plainFetch) {
|
|
210
210
|
this.send = transport
|
|
211
|
-
this.
|
|
211
|
+
this.base = url
|
|
212
212
|
this.headers = headers
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
+
/** The storage address, read now: a deferred one is only known when a request is made. */
|
|
216
|
+
private get url(): string {
|
|
217
|
+
return settle(this.base)
|
|
218
|
+
}
|
|
219
|
+
|
|
215
220
|
from(bucket: string): BucketClient {
|
|
216
|
-
return new BucketClient(this.
|
|
221
|
+
return new BucketClient(this.base, bucket, this.headers, this.send)
|
|
217
222
|
}
|
|
218
223
|
|
|
219
224
|
/**
|
|
@@ -240,7 +245,7 @@ export class StorageClient {
|
|
|
240
245
|
async listBuckets(): Promise<{ data: StorageBucketMeta[] | null; error: SupatypeError | null }> {
|
|
241
246
|
try {
|
|
242
247
|
const res = await this.send(`${this.url}/bucket`, { headers: await this.headers() })
|
|
243
|
-
if (!res.ok) return { data: null, error: { message: await storageRefusal(res, "Failed to list buckets") } }
|
|
248
|
+
if (!res.ok) return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Failed to list buckets") }) }
|
|
244
249
|
return { data: await readBuckets(res), error: null }
|
|
245
250
|
} catch (e) {
|
|
246
251
|
return { data: null, error: transportFailure(e) }
|
|
@@ -264,7 +269,7 @@ export class StorageClient {
|
|
|
264
269
|
headers: { ...(await this.headers()), "Content-Type": "application/json" },
|
|
265
270
|
body: JSON.stringify(body),
|
|
266
271
|
})
|
|
267
|
-
if (!res.ok) return { data: null, error: { message: await storageRefusal(res, "Failed to create bucket") } }
|
|
272
|
+
if (!res.ok) return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Failed to create bucket") }) }
|
|
268
273
|
return { data: { name }, error: null }
|
|
269
274
|
} catch (e) {
|
|
270
275
|
return { data: null, error: transportFailure(e) }
|
|
@@ -273,18 +278,23 @@ export class StorageClient {
|
|
|
273
278
|
}
|
|
274
279
|
|
|
275
280
|
export class BucketClient {
|
|
276
|
-
private readonly
|
|
281
|
+
private readonly base: Deferred<string>
|
|
277
282
|
private readonly bucket: string
|
|
278
283
|
private readonly headers: AuthHeaders
|
|
279
284
|
private readonly send: RequestTransport
|
|
280
285
|
|
|
281
|
-
constructor(url: string
|
|
286
|
+
constructor(url: Deferred<string>, bucket: string, headers: AuthHeaders, transport: RequestTransport = plainFetch) {
|
|
282
287
|
this.send = transport
|
|
283
|
-
this.
|
|
288
|
+
this.base = url
|
|
284
289
|
this.bucket = bucket
|
|
285
290
|
this.headers = headers
|
|
286
291
|
}
|
|
287
292
|
|
|
293
|
+
/** The storage address, read now: a deferred one is only known when a request is made. */
|
|
294
|
+
private get url(): string {
|
|
295
|
+
return settle(this.base)
|
|
296
|
+
}
|
|
297
|
+
|
|
288
298
|
async upload(
|
|
289
299
|
path: string,
|
|
290
300
|
file: Blob | File | ArrayBuffer,
|
|
@@ -304,7 +314,7 @@ export class BucketClient {
|
|
|
304
314
|
body: file,
|
|
305
315
|
})
|
|
306
316
|
if (!res.ok) {
|
|
307
|
-
return { data: null, error: { message: await storageRefusal(res, "Upload failed"), status: res.status } }
|
|
317
|
+
return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Upload failed"), status: res.status }) }
|
|
308
318
|
}
|
|
309
319
|
return { data: { path }, error: null }
|
|
310
320
|
}
|
|
@@ -316,7 +326,7 @@ export class BucketClient {
|
|
|
316
326
|
const url = this.buildObjectUrl("authenticated", path, options?.transform)
|
|
317
327
|
const res = await this.send(url, { headers: await this.headers() })
|
|
318
328
|
if (!res.ok) {
|
|
319
|
-
return { data: null, error: { message: await storageRefusal(res, "Download failed"), status: res.status } }
|
|
329
|
+
return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Download failed"), status: res.status }) }
|
|
320
330
|
}
|
|
321
331
|
const blob = await res.blob()
|
|
322
332
|
return { data: blob, error: null }
|
|
@@ -358,7 +368,7 @@ export class BucketClient {
|
|
|
358
368
|
body: JSON.stringify({ expiresIn }),
|
|
359
369
|
})
|
|
360
370
|
if (!res.ok) {
|
|
361
|
-
return { data: null, error: { message: await storageRefusal(res, "Failed to create signed URL"), status: res.status } }
|
|
371
|
+
return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Failed to create signed URL"), status: res.status }) }
|
|
362
372
|
}
|
|
363
373
|
const json = await readJson(res, isShape({ signedURL: isString }))
|
|
364
374
|
return { data: { signedUrl: this.absoluteObjectUrl(json.signedURL) }, error: null }
|
|
@@ -387,7 +397,7 @@ export class BucketClient {
|
|
|
387
397
|
body: JSON.stringify({ prefixes: paths }),
|
|
388
398
|
})
|
|
389
399
|
if (!res.ok) {
|
|
390
|
-
return { data: null, error: { message: await storageRefusal(res, "Delete failed"), status: res.status } }
|
|
400
|
+
return { data: null, error: new SupatypeError({ message: await storageRefusal(res, "Delete failed"), status: res.status }) }
|
|
391
401
|
}
|
|
392
402
|
return { data: await readJson(res, isRemovedObjects), error: null }
|
|
393
403
|
}
|
|
@@ -415,7 +425,7 @@ export class BucketClient {
|
|
|
415
425
|
body: JSON.stringify(body),
|
|
416
426
|
})
|
|
417
427
|
if (!res.ok) {
|
|
418
|
-
return { data: null, count: null, error: { message: await storageRefusal(res, "List failed"), status: res.status } }
|
|
428
|
+
return { data: null, count: null, error: new SupatypeError({ message: await storageRefusal(res, "List failed"), status: res.status }) }
|
|
419
429
|
}
|
|
420
430
|
return { data: await readJson(res, isStorageEntries), count: countHeader(res), error: null }
|
|
421
431
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ChannelStatus, RealtimeClient, RealtimeEvent, RealtimePayload } from "./realtime.js"
|
|
2
|
-
import
|
|
2
|
+
import { SupatypeError } from "./errors.js"
|
|
3
3
|
import { isJsonObject } from "./json.js"
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -101,9 +101,9 @@ export function subscriptionViewOf(status: ChannelStatus): SubscriptionView {
|
|
|
101
101
|
case "CLOSED":
|
|
102
102
|
return { status: "disconnected", error: null }
|
|
103
103
|
case "CHANNEL_ERROR":
|
|
104
|
-
return { status: "error", error: { message: "Subscription error" } }
|
|
104
|
+
return { status: "error", error: new SupatypeError({ message: "Subscription error" }) }
|
|
105
105
|
case "TIMED_OUT":
|
|
106
|
-
return { status: "error", error: { message: "Realtime connection timed out" } }
|
|
106
|
+
return { status: "error", error: new SupatypeError({ message: "Realtime connection timed out" }) }
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { SupatypeError } from "./errors.js"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A request a binding made that threw instead of answering `{ data, error }`, as the binding's
|
|
5
|
+
* `error`, reported once with `console.error`.
|
|
6
|
+
*
|
|
7
|
+
* The client answers a refusal or a failed network call with `{ data, error }`, but some faults are
|
|
8
|
+
* thrown on purpose: a client with no API address or anon key throws from its first request. A hook
|
|
9
|
+
* that only awaited the request left its `loading` set for good and the rejection unhandled, so
|
|
10
|
+
* every binding catches it and holds this as its `error` instead.
|
|
11
|
+
*
|
|
12
|
+
* The console line is the point: the error is usually a fault in the app's setup, and an app that
|
|
13
|
+
* never reads `error` would otherwise show an empty page with no word of why. `where` names the
|
|
14
|
+
* hook, so the line says which one.
|
|
15
|
+
*/
|
|
16
|
+
export function reportThrown(where: string, thrown: unknown): SupatypeError {
|
|
17
|
+
console.error(`[supatype] ${where}: the request threw.`, thrown)
|
|
18
|
+
return thrownAsError(thrown)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The thrown value as a binding's `error`.
|
|
23
|
+
*
|
|
24
|
+
* One of the SDK's own errors is kept as it is, so `error instanceof` still names it, a setup fault
|
|
25
|
+
* included. Anything else becomes a `SupatypeError` with its message, holding it as `cause`.
|
|
26
|
+
*/
|
|
27
|
+
function thrownAsError(thrown: unknown): SupatypeError {
|
|
28
|
+
if (thrown instanceof SupatypeError) return thrown
|
|
29
|
+
const message = thrown instanceof Error ? thrown.message : typeof thrown === "string" ? thrown : "Unknown error"
|
|
30
|
+
return new SupatypeError({ message }, { cause: thrown })
|
|
31
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { TableRelationship } from "./select-types.js"
|
|
2
|
+
import type { SupatypeError } from "./errors.js"
|
|
2
3
|
|
|
3
4
|
// ─── Auth types ───────────────────────────────────────────────────────────────
|
|
4
5
|
|
|
@@ -64,6 +65,50 @@ export type AuthChangeEvent =
|
|
|
64
65
|
*/
|
|
65
66
|
export type AuthFlowType = "pkce" | "implicit"
|
|
66
67
|
|
|
68
|
+
// ─── SAML single sign-on ────────────────────────────────────────────────────
|
|
69
|
+
|
|
70
|
+
/** How `signInWithSSO` starts and ends. */
|
|
71
|
+
export interface SignInWithSSOOptions {
|
|
72
|
+
/** Where the browser lands once signed in; honoured on the site URL's host or the redirect allow list. */
|
|
73
|
+
redirectTo?: string | undefined
|
|
74
|
+
/** The CAPTCHA token, when the project requires one. */
|
|
75
|
+
captchaToken?: string | undefined
|
|
76
|
+
/** Return the identity provider's URL and leave the browser where it is. */
|
|
77
|
+
skipBrowserRedirect?: boolean | undefined
|
|
78
|
+
/**
|
|
79
|
+
* Default: `pkce`, so the session comes back as a `?code=` only this browser can exchange, never
|
|
80
|
+
* as tokens in the URL. `implicit` returns tokens in the fragment. (`signInWithOAuth` defaults to
|
|
81
|
+
* `implicit`.) A sign-in the identity provider starts always comes back implicit, and the client
|
|
82
|
+
* accepts it either way.
|
|
83
|
+
*/
|
|
84
|
+
flowType?: AuthFlowType | undefined
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Sign in through the SAML identity provider registered for the user's email domain. */
|
|
88
|
+
export interface SignInWithSSODomain {
|
|
89
|
+
/** The domain of the user's email address: `acme.com`. */
|
|
90
|
+
domain: string
|
|
91
|
+
providerId?: never
|
|
92
|
+
options?: SignInWithSSOOptions | undefined
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Sign in through one SAML identity provider, named by its ID. */
|
|
96
|
+
export interface SignInWithSSOProvider {
|
|
97
|
+
/** The provider's UUID, as the admin API reports it. */
|
|
98
|
+
providerId: string
|
|
99
|
+
domain?: never
|
|
100
|
+
options?: SignInWithSSOOptions | undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** What `signInWithSSO` takes: an email domain or a provider's ID, never both. */
|
|
104
|
+
export type SignInWithSSOCredentials = SignInWithSSODomain | SignInWithSSOProvider
|
|
105
|
+
|
|
106
|
+
/** What `signInWithSSO` answers: the identity provider's URL, or why there is none. */
|
|
107
|
+
export interface SignInWithSSOResult {
|
|
108
|
+
data: { url: string }
|
|
109
|
+
error: SupatypeError | null
|
|
110
|
+
}
|
|
111
|
+
|
|
67
112
|
// ─── MFA types ──────────────────────────────────────────────────────────────
|
|
68
113
|
|
|
69
114
|
export interface AuthMFAEnrollResponse {
|
|
@@ -126,7 +171,11 @@ export type OtpType =
|
|
|
126
171
|
|
|
127
172
|
// ─── Error type ───────────────────────────────────────────────────────────────
|
|
128
173
|
|
|
129
|
-
|
|
174
|
+
/** The class every result error is; its fields are `SupatypeErrorFields`. */
|
|
175
|
+
export type { SupatypeError }
|
|
176
|
+
|
|
177
|
+
/** The fields a `SupatypeError` carries, as given to its constructor and as its JSON. */
|
|
178
|
+
export interface SupatypeErrorFields {
|
|
130
179
|
message: string
|
|
131
180
|
status?: number | undefined
|
|
132
181
|
code?: string | undefined
|
|
@@ -153,15 +202,8 @@ export interface SupatypeError {
|
|
|
153
202
|
details?: string | undefined
|
|
154
203
|
}
|
|
155
204
|
|
|
156
|
-
/**
|
|
157
|
-
|
|
158
|
-
*
|
|
159
|
-
* `provider` names the OAuth provider this browser started the sign-in with, when the client
|
|
160
|
-
* remembers one, so an app showing one button per provider can put the message by the right one.
|
|
161
|
-
*/
|
|
162
|
-
export interface AuthRedirectError extends SupatypeError {
|
|
163
|
-
provider?: string | undefined
|
|
164
|
-
}
|
|
205
|
+
/** A sign-in refused in the redirect URL: the class, with the provider it was started with. */
|
|
206
|
+
export type { AuthRedirectError } from "./errors.js"
|
|
165
207
|
|
|
166
208
|
// ─── Query result ─────────────────────────────────────────────────────────────
|
|
167
209
|
|
|
@@ -414,10 +456,19 @@ export interface SelectQueryOptions {
|
|
|
414
456
|
}
|
|
415
457
|
|
|
416
458
|
export interface SupatypeClientConfig {
|
|
417
|
-
/**
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
459
|
+
/**
|
|
460
|
+
* Base URL of the Supatype gateway (e.g. http://localhost:18473). Left out, or empty as a bundler
|
|
461
|
+
* leaves an unset name, it is read from `window.__SUPATYPE_ENV__` (set by
|
|
462
|
+
* `<script src="/supatype-env.js">`) when the first request is made. It is never guessed from the
|
|
463
|
+
* page's own address: with neither, that request throws `MissingClientValuesError`.
|
|
464
|
+
*/
|
|
465
|
+
url?: string | undefined
|
|
466
|
+
/**
|
|
467
|
+
* Anon JWT key. Left out, or empty, it is read from `window.__SUPATYPE_ENV__` when the first
|
|
468
|
+
* request is made; with neither, that request throws `MissingClientValuesError` naming the
|
|
469
|
+
* variables to set. `createClient` itself never throws for either.
|
|
470
|
+
*/
|
|
471
|
+
anonKey?: string | undefined
|
|
421
472
|
/**
|
|
422
473
|
* Service role key: bypasses row-level security.
|
|
423
474
|
* Only set this in trusted server-side or developer-tool contexts.
|
|
@@ -51,7 +51,7 @@ describe("auth errors carry the server's error code", () => {
|
|
|
51
51
|
const client = await signedIn()
|
|
52
52
|
vi.stubGlobal("fetch", fetchReturning(API_ERROR, 422))
|
|
53
53
|
const { error } = await call(client)
|
|
54
|
-
expect(error).toEqual({ message: API_ERROR.msg, status: 422, code: "weak_password" })
|
|
54
|
+
expect({ ...error }).toEqual({ message: API_ERROR.msg, status: 422, code: "weak_password" })
|
|
55
55
|
})
|
|
56
56
|
}
|
|
57
57
|
|
|
@@ -59,7 +59,7 @@ describe("auth errors carry the server's error code", () => {
|
|
|
59
59
|
const client = await signedIn()
|
|
60
60
|
vi.stubGlobal("fetch", fetchReturning(OAUTH_ERROR, 400))
|
|
61
61
|
const { error } = await client.refreshSession()
|
|
62
|
-
expect(error).toEqual({ message: OAUTH_ERROR.error_description, status: 400, code: "invalid_grant" })
|
|
62
|
+
expect({ ...error }).toEqual({ message: OAUTH_ERROR.error_description, status: 400, code: "invalid_grant" })
|
|
63
63
|
})
|
|
64
64
|
|
|
65
65
|
it("a body that is not JSON still gives a message and the status", async () => {
|
|
@@ -79,6 +79,6 @@ describe("redirect errors carry the server's error code", () => {
|
|
|
79
79
|
const { error } = await client.getSessionFromUrl(
|
|
80
80
|
"https://app.example/#error=access_denied&error_code=otp_expired&error_description=Email+link+is+invalid+or+has+expired",
|
|
81
81
|
)
|
|
82
|
-
expect(error).toEqual({ message: "Email link is invalid or has expired", status: 400, code: "otp_expired" })
|
|
82
|
+
expect({ ...error }).toEqual({ message: "Email link is invalid or has expired", status: 400, code: "otp_expired" })
|
|
83
83
|
})
|
|
84
84
|
})
|
|
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
|
2
2
|
import { AuthClient } from "../src/auth.js"
|
|
3
3
|
import type { AuthChangeEvent } from "../src/types.js"
|
|
4
4
|
import { fetchReturning } from "./support/fetch-mock.js"
|
|
5
|
+
import { liveAccessToken } from "./support/jwt.js"
|
|
5
6
|
|
|
6
7
|
const AUTH_URL = "http://localhost:9999"
|
|
7
8
|
const HEADERS = { apikey: "test-anon-key", "Content-Type": "application/json" }
|
|
@@ -24,11 +25,6 @@ const TOKEN_RESPONSE = {
|
|
|
24
25
|
user: RAW_USER,
|
|
25
26
|
}
|
|
26
27
|
|
|
27
|
-
function accessTokenWithExp(): string {
|
|
28
|
-
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")
|
|
29
|
-
return `eyJhbGciOiJub25lIn0.${payload}.sig`
|
|
30
|
-
}
|
|
31
|
-
|
|
32
28
|
/** Every event a listener sees after registration, without the registration emission itself. */
|
|
33
29
|
function recordEvents(client: AuthClient): AuthChangeEvent[] {
|
|
34
30
|
const events: AuthChangeEvent[] = []
|
|
@@ -94,7 +90,7 @@ describe("PASSWORD_RECOVERY", () => {
|
|
|
94
90
|
vi.stubGlobal("fetch", fetchReturning(RAW_USER))
|
|
95
91
|
|
|
96
92
|
const { error } = await client.getSessionFromUrl(
|
|
97
|
-
`https://app.example/reset#access_token=${
|
|
93
|
+
`https://app.example/reset#access_token=${liveAccessToken()}&refresh_token=rt-1&expires_in=3600&token_type=bearer&type=recovery`,
|
|
98
94
|
)
|
|
99
95
|
|
|
100
96
|
expect(error).toBeNull()
|
|
@@ -107,7 +103,7 @@ describe("PASSWORD_RECOVERY", () => {
|
|
|
107
103
|
vi.stubGlobal("fetch", fetchReturning(RAW_USER))
|
|
108
104
|
|
|
109
105
|
await client.getSessionFromUrl(
|
|
110
|
-
`https://app.example/#access_token=${
|
|
106
|
+
`https://app.example/#access_token=${liveAccessToken()}&refresh_token=rt-1&type=magiclink`,
|
|
111
107
|
)
|
|
112
108
|
|
|
113
109
|
expect(events).toEqual(["SIGNED_IN"])
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { describe, it, expect, vi, afterEach } from "vitest"
|
|
2
|
+
import { AuthClient } from "../src/auth.js"
|
|
3
|
+
import { SupatypeError } from "../src/errors.js"
|
|
4
|
+
import { createCodeChallengeS256, PKCE_METHOD_S256 } from "../src/pkce.js"
|
|
5
|
+
import { fetchCall, fetchReturning, jsonBody } from "./support/fetch-mock.js"
|
|
6
|
+
import { stubBrowser } from "./support/browser.js"
|
|
7
|
+
import { liveAccessToken } from "./support/jwt.js"
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `signInWithSSO`: SAML single sign-on, started by the user's email domain or a provider's ID.
|
|
11
|
+
*
|
|
12
|
+
* The client asks `POST /sso` for the identity provider's URL (`skip_http_redirect`, since a fetch
|
|
13
|
+
* cannot follow the server's 303 to another origin) and sends the browser there, unless asked not to.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const AUTH_URL = "http://localhost:9999/auth/v1"
|
|
17
|
+
const HEADERS = { apikey: "anon", "Content-Type": "application/json" }
|
|
18
|
+
const IDP_URL = "https://idp.example/sso?SAMLRequest=abc&RelayState=r1"
|
|
19
|
+
const VERIFIER_KEY = "supatype.auth.session-code-verifier"
|
|
20
|
+
const PROVIDER_KEY = "supatype.auth.session-oauth-provider"
|
|
21
|
+
const PROVIDER_ID = "8a6f1f4e-2b1c-4f5e-9d3a-6b7c8d9e0f1a"
|
|
22
|
+
|
|
23
|
+
const PAGE = "https://app.example/login"
|
|
24
|
+
|
|
25
|
+
/** The challenge fields a PKCE sign-in adds to the /sso body. */
|
|
26
|
+
const ANY_STRING: unknown = expect.any(String)
|
|
27
|
+
const PKCE_FIELDS = { code_challenge: ANY_STRING, code_challenge_method: PKCE_METHOD_S256 }
|
|
28
|
+
|
|
29
|
+
afterEach(() => {
|
|
30
|
+
vi.unstubAllGlobals()
|
|
31
|
+
vi.restoreAllMocks()
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
describe("signInWithSSO request", () => {
|
|
35
|
+
it("posts the email domain to /sso and asks for the URL rather than a redirect", async () => {
|
|
36
|
+
stubBrowser(PAGE)
|
|
37
|
+
const fetch = fetchReturning({ url: IDP_URL })
|
|
38
|
+
vi.stubGlobal("fetch", fetch)
|
|
39
|
+
|
|
40
|
+
await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
|
|
41
|
+
|
|
42
|
+
const { url, init } = fetchCall(fetch)
|
|
43
|
+
expect(url).toBe(`${AUTH_URL}/sso`)
|
|
44
|
+
expect(init.method).toBe("POST")
|
|
45
|
+
expect(jsonBody(init)).toEqual({ domain: "acme.com", skip_http_redirect: true, ...PKCE_FIELDS })
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it("posts a provider ID as provider_id, with no domain", async () => {
|
|
49
|
+
stubBrowser(PAGE)
|
|
50
|
+
const fetch = fetchReturning({ url: IDP_URL })
|
|
51
|
+
vi.stubGlobal("fetch", fetch)
|
|
52
|
+
|
|
53
|
+
await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ providerId: PROVIDER_ID })
|
|
54
|
+
|
|
55
|
+
expect(jsonBody(fetchCall(fetch).init)).toEqual({ provider_id: PROVIDER_ID, skip_http_redirect: true, ...PKCE_FIELDS })
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it("sends redirectTo as redirect_to and the captcha token where the server checks it", async () => {
|
|
59
|
+
stubBrowser(PAGE)
|
|
60
|
+
const fetch = fetchReturning({ url: IDP_URL })
|
|
61
|
+
vi.stubGlobal("fetch", fetch)
|
|
62
|
+
|
|
63
|
+
await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({
|
|
64
|
+
domain: "acme.com",
|
|
65
|
+
options: { redirectTo: "https://app.example/welcome", captchaToken: "cap-1" },
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
expect(jsonBody(fetchCall(fetch).init)).toEqual({
|
|
69
|
+
domain: "acme.com",
|
|
70
|
+
skip_http_redirect: true,
|
|
71
|
+
redirect_to: "https://app.example/welcome",
|
|
72
|
+
supatype_meta_security: { captcha_token: "cap-1" },
|
|
73
|
+
...PKCE_FIELDS,
|
|
74
|
+
})
|
|
75
|
+
})
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
describe("signInWithSSO PKCE", () => {
|
|
79
|
+
it("sends the S256 challenge of a stored verifier by default", async () => {
|
|
80
|
+
const { store } = stubBrowser(PAGE)
|
|
81
|
+
const fetch = fetchReturning({ url: IDP_URL })
|
|
82
|
+
vi.stubGlobal("fetch", fetch)
|
|
83
|
+
|
|
84
|
+
await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
|
|
85
|
+
|
|
86
|
+
const verifier = store.get(VERIFIER_KEY)
|
|
87
|
+
expect(verifier).toMatch(/^[A-Za-z0-9_-]{43}$/)
|
|
88
|
+
const body = jsonBody(fetchCall(fetch).init)
|
|
89
|
+
expect(body["code_challenge"]).toBe(createCodeChallengeS256(verifier!))
|
|
90
|
+
expect(body["code_challenge_method"]).toBe(PKCE_METHOD_S256)
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it("sends no challenge for flowType implicit", async () => {
|
|
94
|
+
const { store } = stubBrowser(PAGE)
|
|
95
|
+
const fetch = fetchReturning({ url: IDP_URL })
|
|
96
|
+
vi.stubGlobal("fetch", fetch)
|
|
97
|
+
|
|
98
|
+
await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com", options: { flowType: "implicit" } })
|
|
99
|
+
|
|
100
|
+
const body = jsonBody(fetchCall(fetch).init)
|
|
101
|
+
expect(body["code_challenge"]).toBeUndefined()
|
|
102
|
+
expect(body["code_challenge_method"]).toBeUndefined()
|
|
103
|
+
expect(store.has(VERIFIER_KEY)).toBe(false)
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it("leaves signInWithOAuth's default implicit", async () => {
|
|
107
|
+
const { store } = stubBrowser(PAGE)
|
|
108
|
+
vi.stubGlobal("fetch", fetchReturning({ external: { github: true } }))
|
|
109
|
+
|
|
110
|
+
const { data } = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "github" })
|
|
111
|
+
|
|
112
|
+
expect(new URL(data.url).searchParams.has("code_challenge")).toBe(false)
|
|
113
|
+
expect(store.has(VERIFIER_KEY)).toBe(false)
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
it("remembers the sign-in as SSO, so a refusal sent back in the URL names it", async () => {
|
|
117
|
+
const { store } = stubBrowser(PAGE)
|
|
118
|
+
vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
|
|
119
|
+
|
|
120
|
+
await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
|
|
121
|
+
|
|
122
|
+
expect(store.get(PROVIDER_KEY)).toBe("sso")
|
|
123
|
+
})
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
describe("signInWithSSO redirect", () => {
|
|
127
|
+
it("returns the identity provider's URL and sends the browser there", async () => {
|
|
128
|
+
const { assign } = stubBrowser(PAGE)
|
|
129
|
+
vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
|
|
130
|
+
|
|
131
|
+
const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
|
|
132
|
+
|
|
133
|
+
expect(error).toBeNull()
|
|
134
|
+
expect(data.url).toBe(IDP_URL)
|
|
135
|
+
expect(assign).toHaveBeenCalledWith(IDP_URL)
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
it("returns the URL and stays put with skipBrowserRedirect", async () => {
|
|
139
|
+
const { assign } = stubBrowser(PAGE)
|
|
140
|
+
vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
|
|
141
|
+
|
|
142
|
+
const { data } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({
|
|
143
|
+
domain: "acme.com",
|
|
144
|
+
options: { skipBrowserRedirect: true },
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
expect(data.url).toBe(IDP_URL)
|
|
148
|
+
expect(assign).not.toHaveBeenCalled()
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
it("returns the URL outside a browser without touching window", async () => {
|
|
152
|
+
vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
|
|
153
|
+
|
|
154
|
+
const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
|
|
155
|
+
|
|
156
|
+
expect(error).toBeNull()
|
|
157
|
+
expect(data.url).toBe(IDP_URL)
|
|
158
|
+
})
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
describe("signInWithSSO errors", () => {
|
|
162
|
+
it("returns the server's refusal as a SupatypeError with its code, and does not navigate", async () => {
|
|
163
|
+
const { assign } = stubBrowser(PAGE)
|
|
164
|
+
vi.stubGlobal("fetch", fetchReturning(
|
|
165
|
+
{ code: 404, error_code: "sso_provider_not_found", msg: "No SSO provider assigned for this domain" },
|
|
166
|
+
404,
|
|
167
|
+
))
|
|
168
|
+
|
|
169
|
+
const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "nope.com" })
|
|
170
|
+
|
|
171
|
+
expect(error).toBeInstanceOf(SupatypeError)
|
|
172
|
+
expect(error?.code).toBe("sso_provider_not_found")
|
|
173
|
+
expect(error?.status).toBe(404)
|
|
174
|
+
expect(error?.message).toBe("No SSO provider assigned for this domain")
|
|
175
|
+
expect(data.url).toBe("")
|
|
176
|
+
expect(assign).not.toHaveBeenCalled()
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
it("refuses an answer with no URL rather than navigating nowhere", async () => {
|
|
180
|
+
const { assign } = stubBrowser(PAGE)
|
|
181
|
+
vi.stubGlobal("fetch", fetchReturning({}))
|
|
182
|
+
|
|
183
|
+
const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.com" })
|
|
184
|
+
|
|
185
|
+
expect(error).toBeInstanceOf(SupatypeError)
|
|
186
|
+
expect(data.url).toBe("")
|
|
187
|
+
expect(assign).not.toHaveBeenCalled()
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
it("rejects both a domain and a provider ID at compile time", () => {
|
|
191
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
192
|
+
const both = (): unknown =>
|
|
193
|
+
// @ts-expect-error: one of domain or providerId, never both
|
|
194
|
+
client.signInWithSSO({ domain: "acme.com", providerId: PROVIDER_ID })
|
|
195
|
+
expect(typeof both).toBe("function")
|
|
196
|
+
})
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
const RAW_USER = {
|
|
200
|
+
id: "user-sso",
|
|
201
|
+
email: "sso-tester@acme.supatype.test",
|
|
202
|
+
created_at: "2026-11-06T00:00:00Z",
|
|
203
|
+
updated_at: "2026-11-06T00:00:00Z",
|
|
204
|
+
app_metadata: { provider: "sso:0b4a7c1e" },
|
|
205
|
+
user_metadata: {},
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
describe("an SSO sign-in coming back to the app", () => {
|
|
209
|
+
it("exchanges the code of a sign-in this browser started for a session", async () => {
|
|
210
|
+
const started = stubBrowser(PAGE)
|
|
211
|
+
vi.stubGlobal("fetch", fetchReturning({ url: IDP_URL }))
|
|
212
|
+
await new AuthClient(AUTH_URL, HEADERS).signInWithSSO({ domain: "acme.supatype.test" })
|
|
213
|
+
const verifier = started.store.get(VERIFIER_KEY)
|
|
214
|
+
|
|
215
|
+
const { replaceState } = stubBrowser("https://app.example/home?code=sso-code-1", Object.fromEntries(started.store))
|
|
216
|
+
const fetch = fetchReturning({ access_token: liveAccessToken(), refresh_token: "rt-sso", expires_in: 3600, token_type: "bearer", user: RAW_USER })
|
|
217
|
+
vi.stubGlobal("fetch", fetch)
|
|
218
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
219
|
+
const { error } = await client.initialize()
|
|
220
|
+
|
|
221
|
+
expect(error).toBeNull()
|
|
222
|
+
const { url, init } = fetchCall(fetch)
|
|
223
|
+
expect(url).toBe(`${AUTH_URL}/token?grant_type=pkce`)
|
|
224
|
+
expect(jsonBody(init)).toEqual({ auth_code: "sso-code-1", code_verifier: verifier })
|
|
225
|
+
expect((await client.getSession()).data.session?.user.id).toBe("user-sso")
|
|
226
|
+
expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/home")
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
it("signs in from tokens in the fragment for an identity-provider-initiated login it did not start", async () => {
|
|
230
|
+
const token = liveAccessToken()
|
|
231
|
+
const { replaceState } = stubBrowser(`https://app.example/#access_token=${token}&refresh_token=rt-idp&expires_in=3600&token_type=bearer`)
|
|
232
|
+
const fetch = fetchReturning(RAW_USER)
|
|
233
|
+
vi.stubGlobal("fetch", fetch)
|
|
234
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
235
|
+
const { error } = await client.initialize()
|
|
236
|
+
|
|
237
|
+
expect(error).toBeNull()
|
|
238
|
+
expect(fetchCall(fetch).url).toBe(`${AUTH_URL}/user`)
|
|
239
|
+
const { data } = await client.getSession()
|
|
240
|
+
expect(data.session?.accessToken).toBe(token)
|
|
241
|
+
expect(data.session?.user.id).toBe("user-sso")
|
|
242
|
+
expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/")
|
|
243
|
+
})
|
|
244
|
+
|
|
245
|
+
it("takes fragment tokens even while a PKCE sign-in it started is still waiting", async () => {
|
|
246
|
+
const token = liveAccessToken()
|
|
247
|
+
stubBrowser(`https://app.example/#access_token=${token}&refresh_token=rt-idp&expires_in=3600&token_type=bearer`, {
|
|
248
|
+
[VERIFIER_KEY]: "abandoned-verifier",
|
|
249
|
+
[PROVIDER_KEY]: "sso",
|
|
250
|
+
})
|
|
251
|
+
const fetch = fetchReturning(RAW_USER)
|
|
252
|
+
vi.stubGlobal("fetch", fetch)
|
|
253
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
254
|
+
const { error } = await client.initialize()
|
|
255
|
+
|
|
256
|
+
expect(error).toBeNull()
|
|
257
|
+
expect(fetch.mock.calls.map(([input]) => String(input))).toEqual([`${AUTH_URL}/user`])
|
|
258
|
+
expect((await client.getSession()).data.session?.accessToken).toBe(token)
|
|
259
|
+
})
|
|
260
|
+
})
|