@supatype/client 0.3.5 → 0.7.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.
Files changed (205) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +58 -31
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/dist/auth-redirect.d.ts +48 -0
  6. package/dist/auth-redirect.d.ts.map +1 -0
  7. package/dist/auth-redirect.js +70 -0
  8. package/dist/auth-redirect.js.map +1 -0
  9. package/dist/auth.d.ts +78 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +373 -274
  12. package/dist/auth.js.map +1 -1
  13. package/dist/bindings.d.ts +16 -0
  14. package/dist/bindings.d.ts.map +1 -0
  15. package/dist/bindings.js +13 -0
  16. package/dist/bindings.js.map +1 -0
  17. package/dist/caller-types.d.ts +18 -0
  18. package/dist/caller-types.d.ts.map +1 -0
  19. package/dist/caller-types.js +22 -0
  20. package/dist/caller-types.js.map +1 -0
  21. package/dist/draft-create.d.ts +12 -0
  22. package/dist/draft-create.d.ts.map +1 -0
  23. package/dist/draft-create.js +47 -0
  24. package/dist/draft-create.js.map +1 -0
  25. package/dist/draft-models-registry.d.ts +27 -0
  26. package/dist/draft-models-registry.d.ts.map +1 -0
  27. package/dist/draft-models-registry.js +61 -0
  28. package/dist/draft-models-registry.js.map +1 -0
  29. package/dist/error-codes-doc.d.ts +1 -1
  30. package/dist/error-codes-doc.d.ts.map +1 -1
  31. package/dist/error-codes-doc.js +42 -34
  32. package/dist/error-codes-doc.js.map +1 -1
  33. package/dist/errors.d.ts +102 -60
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +69 -28
  36. package/dist/errors.js.map +1 -1
  37. package/dist/exact-response.d.ts.map +1 -1
  38. package/dist/exact-response.js +2 -1
  39. package/dist/exact-response.js.map +1 -1
  40. package/dist/exact-values.d.ts +2 -0
  41. package/dist/exact-values.d.ts.map +1 -1
  42. package/dist/exact-values.js +12 -10
  43. package/dist/exact-values.js.map +1 -1
  44. package/dist/fetch-with-retry.d.ts +21 -6
  45. package/dist/fetch-with-retry.d.ts.map +1 -1
  46. package/dist/fetch-with-retry.js +67 -53
  47. package/dist/fetch-with-retry.js.map +1 -1
  48. package/dist/field-kinds-registry.d.ts +11 -3
  49. package/dist/field-kinds-registry.d.ts.map +1 -1
  50. package/dist/field-kinds-registry.js +10 -6
  51. package/dist/field-kinds-registry.js.map +1 -1
  52. package/dist/filters.d.ts +51 -0
  53. package/dist/filters.d.ts.map +1 -0
  54. package/dist/filters.js +117 -0
  55. package/dist/filters.js.map +1 -0
  56. package/dist/generated-client.d.ts +7 -0
  57. package/dist/generated-client.d.ts.map +1 -0
  58. package/dist/generated-client.js +7 -0
  59. package/dist/generated-client.js.map +1 -0
  60. package/dist/graphql-document.d.ts +39 -0
  61. package/dist/graphql-document.d.ts.map +1 -0
  62. package/dist/graphql-document.js +228 -0
  63. package/dist/graphql-document.js.map +1 -0
  64. package/dist/graphql-json.d.ts +56 -0
  65. package/dist/graphql-json.d.ts.map +1 -0
  66. package/dist/graphql-json.js +220 -0
  67. package/dist/graphql-json.js.map +1 -0
  68. package/dist/graphql-transport.d.ts +28 -0
  69. package/dist/graphql-transport.d.ts.map +1 -0
  70. package/dist/graphql-transport.js +77 -0
  71. package/dist/graphql-transport.js.map +1 -0
  72. package/dist/index.d.ts +103 -40
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +153 -157
  75. package/dist/index.js.map +1 -1
  76. package/dist/json.d.ts +61 -0
  77. package/dist/json.d.ts.map +1 -0
  78. package/dist/json.js +83 -0
  79. package/dist/json.js.map +1 -0
  80. package/dist/jwt.d.ts +16 -0
  81. package/dist/jwt.d.ts.map +1 -0
  82. package/dist/jwt.js +37 -0
  83. package/dist/jwt.js.map +1 -0
  84. package/dist/live-preview.d.ts +23 -0
  85. package/dist/live-preview.d.ts.map +1 -0
  86. package/dist/live-preview.js +28 -0
  87. package/dist/live-preview.js.map +1 -0
  88. package/dist/mutation-request.d.ts +17 -0
  89. package/dist/mutation-request.d.ts.map +1 -0
  90. package/dist/mutation-request.js +41 -0
  91. package/dist/mutation-request.js.map +1 -0
  92. package/dist/preview.d.ts.map +1 -1
  93. package/dist/preview.js +8 -6
  94. package/dist/preview.js.map +1 -1
  95. package/dist/query-cache.d.ts.map +1 -1
  96. package/dist/query-cache.js +19 -13
  97. package/dist/query-cache.js.map +1 -1
  98. package/dist/query.d.ts +108 -29
  99. package/dist/query.d.ts.map +1 -1
  100. package/dist/query.js +294 -224
  101. package/dist/query.js.map +1 -1
  102. package/dist/realtime.d.ts +20 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +105 -12
  105. package/dist/realtime.js.map +1 -1
  106. package/dist/select-types.d.ts +99 -0
  107. package/dist/select-types.d.ts.map +1 -0
  108. package/dist/select-types.js +2 -0
  109. package/dist/select-types.js.map +1 -0
  110. package/dist/storage.d.ts +81 -11
  111. package/dist/storage.d.ts.map +1 -1
  112. package/dist/storage.js +129 -37
  113. package/dist/storage.js.map +1 -1
  114. package/dist/table-subscription.d.ts +69 -0
  115. package/dist/table-subscription.d.ts.map +1 -0
  116. package/dist/table-subscription.js +93 -0
  117. package/dist/table-subscription.js.map +1 -0
  118. package/dist/types.d.ts +84 -5
  119. package/dist/types.d.ts.map +1 -1
  120. package/dist/types.js +6 -1
  121. package/dist/types.js.map +1 -1
  122. package/package.json +6 -2
  123. package/src/auth-redirect.ts +90 -0
  124. package/src/auth.ts +421 -280
  125. package/src/bindings.ts +22 -0
  126. package/src/caller-types.ts +27 -0
  127. package/src/draft-create.ts +51 -0
  128. package/src/draft-models-registry.ts +81 -0
  129. package/src/error-codes-doc.ts +44 -35
  130. package/src/errors.ts +72 -28
  131. package/src/exact-response.ts +2 -1
  132. package/src/exact-values.ts +16 -9
  133. package/src/fetch-with-retry.ts +80 -70
  134. package/src/field-kinds-registry.ts +22 -9
  135. package/src/filters.ts +133 -0
  136. package/src/generated-client.ts +6 -0
  137. package/src/graphql-document.ts +234 -0
  138. package/src/graphql-json.ts +243 -0
  139. package/src/graphql-transport.ts +97 -0
  140. package/src/index.ts +272 -201
  141. package/src/json.ts +117 -0
  142. package/src/jwt.ts +37 -0
  143. package/src/live-preview.ts +37 -0
  144. package/src/mutation-request.ts +66 -0
  145. package/src/preview.ts +9 -11
  146. package/src/query-cache.ts +19 -16
  147. package/src/query.ts +389 -270
  148. package/src/realtime.ts +116 -13
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +214 -43
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +90 -5
  153. package/tests/auth-error-codes.test.ts +53 -0
  154. package/tests/auth-errors.test.ts +84 -0
  155. package/tests/auth-events.test.ts +136 -0
  156. package/tests/auth-url-session.test.ts +204 -0
  157. package/tests/auth.test.ts +122 -26
  158. package/tests/count.test.ts +60 -0
  159. package/tests/data-plane-auth.test.ts +21 -46
  160. package/tests/draft-insert.integration.test.ts +118 -0
  161. package/tests/draft-insert.test.ts +225 -0
  162. package/tests/draft-profile.test.ts +55 -84
  163. package/tests/draft-update.integration.test.ts +122 -0
  164. package/tests/draft-update.test.ts +174 -0
  165. package/tests/dynamic-headers.test.ts +45 -0
  166. package/tests/entry-points.test.ts +42 -0
  167. package/tests/exact-response.test.ts +4 -4
  168. package/tests/exact-values.test.ts +14 -25
  169. package/tests/field-kinds-registry.test.ts +3 -3
  170. package/tests/filters.test.ts +146 -0
  171. package/tests/graphql-json.test.ts +199 -0
  172. package/tests/helpers/mock-websocket.ts +44 -11
  173. package/tests/helpers/oauth-binding.ts +92 -0
  174. package/tests/helpers/signup-binding.ts +73 -0
  175. package/tests/helpers/socket-swap.ts +139 -0
  176. package/tests/mfa-totp-integration.test.ts +13 -20
  177. package/tests/postgrest-error-codes.test.ts +85 -0
  178. package/tests/query-cache.test.ts +116 -117
  179. package/tests/query.test.ts +29 -31
  180. package/tests/rate-limit-integration.test.ts +4 -12
  181. package/tests/realtime-exact-values.test.ts +2 -4
  182. package/tests/realtime-presence.test.ts +75 -0
  183. package/tests/realtime-session-auth.test.ts +2 -4
  184. package/tests/realtime-swap-status.test.ts +62 -0
  185. package/tests/retry-integration.test.ts +3 -8
  186. package/tests/retry-policy.test.ts +166 -0
  187. package/tests/rpc-resend.test.ts +24 -0
  188. package/tests/server-bodies.test.ts +139 -0
  189. package/tests/serverless.test.ts +2 -2
  190. package/tests/signed-url-absolute.test.ts +2 -5
  191. package/tests/storage-object-shape.test.ts +101 -0
  192. package/tests/storage-quota-integration.test.ts +3 -2
  193. package/tests/storage-reference-url.test.ts +51 -0
  194. package/tests/storage-upload-browser.test.ts +71 -0
  195. package/tests/storage-upload-limit-integration.test.ts +12 -22
  196. package/tests/subscribe-frame.test.ts +5 -11
  197. package/tests/support/fetch-mock.ts +64 -0
  198. package/tests/support/storage-object.ts +37 -0
  199. package/tests/table-subscribe.test.ts +13 -13
  200. package/tests/table-subscription.test.ts +105 -0
  201. package/tests/table-transport.test.ts +94 -0
  202. package/tests/tsconfig.json +1 -1
  203. package/tests/types.test.ts +153 -1
  204. package/tsconfig.json +1 -1
  205. package/tsconfig.tsbuildinfo +1 -1
package/src/types.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { TableRelationship } from "./select-types.js"
2
+
1
3
  // ─── Auth types ───────────────────────────────────────────────────────────────
2
4
 
3
5
  export interface UserIdentity {
@@ -137,6 +139,28 @@ export interface SupatypeError {
137
139
  * you.
138
140
  */
139
141
  field?: string | undefined
142
+ /**
143
+ * What the server suggests doing instead, when it said. PostgREST passes a Postgres `HINT`
144
+ * through, and the gateway adds one to an insert into a drafts model that is refused for asking
145
+ * for its row back, naming `supatype.create_record` and `supatype.create_records`.
146
+ */
147
+ hint?: string | undefined
148
+ /**
149
+ * The detail line Postgres attached, when it gave one. A unique violation names its columns and
150
+ * values here (`Key (slug)=(intro) already exists.`), which is how a caller learns which of the
151
+ * values it sent collided without parsing the message.
152
+ */
153
+ details?: string | undefined
154
+ }
155
+
156
+ /**
157
+ * A sign-in the auth server refused and reported back in the redirect URL.
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
140
164
  }
141
165
 
142
166
  // ─── Query result ─────────────────────────────────────────────────────────────
@@ -192,6 +216,14 @@ export interface RpcOptions {
192
216
  count?: "exact" | "planned" | "estimated" | undefined
193
217
  /** Postgres schema holding the function, sent as `Content-Profile`. */
194
218
  schema?: string | undefined
219
+ /**
220
+ * Retry this call on a transient failure (a dropped connection, a 5xx, a 429). Default: false.
221
+ *
222
+ * An RPC is a POST, and the client cannot tell a read from a write: a call that failed in flight
223
+ * may already have run, and running it again could apply its writes twice. Set this for a
224
+ * function that only reads, or whose writes are safe to repeat. A `head` call is always retried.
225
+ */
226
+ idempotent?: boolean | undefined
195
227
  }
196
228
 
197
229
  export interface RpcResult<TData> {
@@ -209,8 +241,38 @@ export interface TableDef {
209
241
  */
210
242
  Insert: Record<string, unknown>
211
243
  Update: Record<string, unknown>
244
+ /**
245
+ * The foreign keys this table holds, which an embedded select is resolved through. Generated for
246
+ * every table; a hand-written definition without them can still select its own columns.
247
+ */
248
+ Relationships?: readonly TableRelationship[] | undefined
249
+ /**
250
+ * `true` on a model that keeps drafts, where `update` saves a new draft of each record and
251
+ * `{ publish: true }` publishes it in the same call. Generated; absent on every other table. A
252
+ * hand-written definition that leaves it unsaid is offered the option, and the client refuses it
253
+ * at run time on a table it does not know keeps drafts.
254
+ */
255
+ Drafts?: boolean | undefined
256
+ }
257
+
258
+ /** What `update` takes beyond the changes, on a model that keeps drafts. */
259
+ export interface DraftUpdateOptions {
260
+ /**
261
+ * Publish each new draft in the same call, so the live rows change and the history records the
262
+ * version that went live. Without it the live rows stay as they are until a version is published.
263
+ */
264
+ publish?: boolean | undefined
212
265
  }
213
266
 
267
+ /**
268
+ * The options `update` takes on `TDef`: {@link DraftUpdateOptions} on a model that keeps drafts, or
269
+ * one whose definition does not say; nothing on a generated table that keeps none.
270
+ */
271
+ export type UpdateOptions<TDef extends TableDef> =
272
+ TDef extends { Drafts: true } ? DraftUpdateOptions
273
+ : "Drafts" extends keyof TDef ? (TDef["Drafts"] extends false | undefined ? never : DraftUpdateOptions)
274
+ : never
275
+
214
276
  /**
215
277
  * Module augmentation anchors used by generated `supatype` types output.
216
278
  *
@@ -331,6 +393,13 @@ export interface AuthStorage {
331
393
  */
332
394
  export const DRAFT_SCHEMA = "draft"
333
395
 
396
+ /**
397
+ * The schema holding the generated publishing functions: `create_record`, `create_draft`, `publish`
398
+ * and the rest. PostgREST resolves `/rpc/<name>` against the default profile, so every call to one
399
+ * names this schema with `Content-Profile`.
400
+ */
401
+ export const PUBLISHING_SCHEMA = "supatype"
402
+
334
403
  export interface SelectQueryOptions {
335
404
  count?: "exact" | "planned" | "estimated" | undefined
336
405
  head?: boolean | undefined
@@ -371,15 +440,30 @@ export interface SupatypeClientConfig {
371
440
  * React Native: pass an AsyncStorage or expo-secure-store adapter.
372
441
  */
373
442
  storage?: AuthStorage | undefined
443
+ /**
444
+ * Finish a sign-in the auth server has just redirected back with (OAuth, magic link, recovery
445
+ * link): tokens in the URL fragment or a PKCE `code` in the query become the session, `SIGNED_IN`
446
+ * is emitted, and the parameters are removed from the address bar. Browser only. Default: true,
447
+ * as supabase-js's option of the same name. `auth.initialize()` reports a refusal in the URL.
448
+ */
449
+ detectSessionInUrl?: boolean | undefined
374
450
  } | undefined
375
451
  /**
376
- * Disable automatic retry for transient errors.
377
- * Default: true (retries enabled).
452
+ * Retry a transient failure (a dropped connection, a 5xx, a 429). Default: true.
453
+ *
454
+ * Only reads are retried: GET and HEAD requests (table selects, storage downloads, `getUser`), and
455
+ * the few reads sent as POST (storage `list`, signed URLs). Every other request is sent once,
456
+ * whatever this says: a write that failed in flight may still have been applied, and sending it
457
+ * again could apply it twice. `rpc`, `graphql` and `functions.invoke` take `idempotent: true` per
458
+ * call to opt in.
378
459
  */
379
460
  retry?: boolean | undefined
380
461
  /**
381
462
  * Request timeout in milliseconds. Default: 30000 (30 seconds).
382
- * Applied to every HTTP request made by the client.
463
+ *
464
+ * Applies to every HTTP request the client makes: tables, `rpc`, `graphql`, `functions`, auth and
465
+ * storage, uploads included, so raise it for large uploads on slow links. The realtime socket is
466
+ * not an HTTP request and is not covered.
383
467
  */
384
468
  timeout?: number | undefined
385
469
  /**
@@ -410,7 +494,8 @@ export interface SupatypeClientConfig {
410
494
  */
411
495
  previewCode?: string | undefined
412
496
  /**
413
- * Extra headers merged into every request (e.g. Studio `X-Supatype-Environment`).
497
+ * Extra headers merged into every request (e.g. Studio `X-Supatype-Environment`). A function is
498
+ * read on every request, for a header that changes for the life of the client.
414
499
  */
415
- headers?: Record<string, string> | undefined
500
+ headers?: Record<string, string> | (() => Record<string, string>) | undefined
416
501
  }
@@ -0,0 +1,53 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest"
2
+ import { AuthClient } from "../src/auth.js"
3
+ import { AuthErrorCodes } from "../src/errors.js"
4
+ import { getErrorDocumentation } from "../src/error-codes-doc.js"
5
+
6
+ // `AuthErrorCodes` held `AUTH_INVALID_CREDENTIALS` and the like, which the auth server never
7
+ // sends: it answers `{ error_code: "invalid_credentials", ... }`, and the client passes that code
8
+ // through. So `error.code === AuthErrorCodes.INVALID_CREDENTIALS` was false for every wrong
9
+ // password. Each constant is checked against the code the server sends in that situation
10
+ // (supatype-auth, internal/auth/apierrors/errorcode.go), through the client.
11
+
12
+ afterEach(() => {
13
+ vi.unstubAllGlobals()
14
+ })
15
+
16
+ const SERVER_SENDS: Array<[keyof typeof AuthErrorCodes, string]> = [
17
+ ["INVALID_CREDENTIALS", "invalid_credentials"],
18
+ ["USER_NOT_FOUND", "user_not_found"],
19
+ ["EMAIL_NOT_CONFIRMED", "email_not_confirmed"],
20
+ ["PHONE_NOT_CONFIRMED", "phone_not_confirmed"],
21
+ ["SESSION_EXPIRED", "session_expired"],
22
+ ["INVALID_TOKEN", "bad_jwt"],
23
+ ["MFA_REQUIRED", "insufficient_aal"],
24
+ ["MFA_CHALLENGE_EXPIRED", "mfa_challenge_expired"],
25
+ ["MFA_VERIFICATION_FAILED", "mfa_verification_failed"],
26
+ ["WEAK_PASSWORD", "weak_password"],
27
+ ["USER_ALREADY_EXISTS", "user_already_exists"],
28
+ ["OAUTH_CALLBACK_ERROR", "bad_oauth_callback"],
29
+ ["MAGIC_LINK_EXPIRED", "otp_expired"],
30
+ ]
31
+
32
+ describe("AuthErrorCodes", () => {
33
+ it.each(SERVER_SENDS)("%s is the code the server sends (%s)", async (name, serverCode) => {
34
+ vi.stubGlobal(
35
+ "fetch",
36
+ vi.fn().mockResolvedValue({
37
+ ok: false,
38
+ status: 400,
39
+ json: vi.fn().mockResolvedValue({ code: 400, error_code: serverCode, msg: "refused" }),
40
+ headers: { get: () => null },
41
+ }),
42
+ )
43
+ const client = new AuthClient("http://localhost:9999", { apikey: "k", "Content-Type": "application/json" })
44
+ const { error } = await client.signInWithPassword({ email: "a@example.com", password: "pw" })
45
+ expect(error?.code).toBe(AuthErrorCodes[name])
46
+ })
47
+ })
48
+
49
+ describe("the error documentation", () => {
50
+ it.each(SERVER_SENDS)("has an entry for %s under the code the server sends", (name) => {
51
+ expect(getErrorDocumentation(AuthErrorCodes[name])?.category).toBe("auth")
52
+ })
53
+ })
@@ -0,0 +1,84 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { AuthClient } from "../src/auth.js"
3
+ import type { SupatypeError } from "../src/types.js"
4
+ import { fetchReturning } from "./support/fetch-mock.js"
5
+
6
+ const AUTH_URL = "http://localhost:9999"
7
+ const HEADERS = { apikey: "test-anon-key", "Content-Type": "application/json" }
8
+
9
+ const TOKEN_RESPONSE = {
10
+ access_token: "access-token-123",
11
+ refresh_token: "refresh-token-abc",
12
+ token_type: "bearer",
13
+ expires_in: 3600,
14
+ user: { id: "user-1", email: "a@example.com", app_metadata: {}, user_metadata: {} },
15
+ }
16
+
17
+ /** What the auth server sends today: a numeric `code`, a string `error_code` and a `msg`. */
18
+ const API_ERROR = { code: 422, error_code: "weak_password", msg: "Password should be at least 8 characters." }
19
+
20
+ /** The OAuth token endpoint's older shape: `error` is the code and `error_description` the message. */
21
+ const OAUTH_ERROR = { error: "invalid_grant", error_description: "Invalid Refresh Token: Already Used" }
22
+
23
+ async function signedIn(): Promise<AuthClient> {
24
+ const client = new AuthClient(AUTH_URL, HEADERS)
25
+ vi.stubGlobal("fetch", fetchReturning(TOKEN_RESPONSE, 200))
26
+ await client.signInWithPassword({ email: "a@example.com", password: "pw" })
27
+ return client
28
+ }
29
+
30
+ type AuthCall = (client: AuthClient) => Promise<{ error: SupatypeError | null }>
31
+
32
+ const CALLS: Array<[string, AuthCall]> = [
33
+ ["signUp", (c) => c.signUp({ email: "a@example.com", password: "x" })],
34
+ ["signInWithPassword", (c) => c.signInWithPassword({ email: "a@example.com", password: "x" })],
35
+ ["signInAnonymously", (c) => c.signInAnonymously()],
36
+ ["signInWithOtp", (c) => c.signInWithOtp({ email: "a@example.com" })],
37
+ ["signInWithIdToken", (c) => c.signInWithIdToken({ provider: "google", token: "t" })],
38
+ ["verifyOtp", (c) => c.verifyOtp({ type: "email", token: "1", email: "a@example.com" })],
39
+ ["resend", (c) => c.resend({ type: "signup", email: "a@example.com" })],
40
+ ["resetPasswordForEmail", (c) => c.resetPasswordForEmail("a@example.com")],
41
+ ["updateUser", (c) => c.updateUser({ password: "x" })],
42
+ ["getUser", (c) => c.getUser()],
43
+ ["refreshSession", (c) => c.refreshSession()],
44
+ ]
45
+
46
+ describe("auth errors carry the server's error code", () => {
47
+ beforeEach(() => vi.restoreAllMocks())
48
+
49
+ for (const [name, call] of CALLS) {
50
+ it(`${name}: error_code becomes code, msg becomes message`, async () => {
51
+ const client = await signedIn()
52
+ vi.stubGlobal("fetch", fetchReturning(API_ERROR, 422))
53
+ const { error } = await call(client)
54
+ expect(error).toEqual({ message: API_ERROR.msg, status: 422, code: "weak_password" })
55
+ })
56
+ }
57
+
58
+ it("the OAuth shape's `error` is the code and `error_description` the message", async () => {
59
+ const client = await signedIn()
60
+ vi.stubGlobal("fetch", fetchReturning(OAUTH_ERROR, 400))
61
+ const { error } = await client.refreshSession()
62
+ expect(error).toEqual({ message: OAUTH_ERROR.error_description, status: 400, code: "invalid_grant" })
63
+ })
64
+
65
+ it("a body that is not JSON still gives a message and the status", async () => {
66
+ const client = new AuthClient(AUTH_URL, HEADERS)
67
+ const notJson = (): Promise<Response> => Promise.resolve(new Response("<html>Bad gateway</html>", { status: 502 }))
68
+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(notJson))
69
+ const { error } = await client.signInWithPassword({ email: "a@example.com", password: "x" })
70
+ expect(error?.status).toBe(502)
71
+ expect(error?.message).not.toBe("")
72
+ expect(error?.code).toBeUndefined()
73
+ })
74
+ })
75
+
76
+ describe("redirect errors carry the server's error code", () => {
77
+ it("getSessionFromUrl keeps error_code from an expired email link", async () => {
78
+ const client = new AuthClient(AUTH_URL, HEADERS)
79
+ const { error } = await client.getSessionFromUrl(
80
+ "https://app.example/#error=access_denied&error_code=otp_expired&error_description=Email+link+is+invalid+or+has+expired",
81
+ )
82
+ expect(error).toEqual({ message: "Email link is invalid or has expired", status: 400, code: "otp_expired" })
83
+ })
84
+ })
@@ -0,0 +1,136 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { AuthClient } from "../src/auth.js"
3
+ import type { AuthChangeEvent } from "../src/types.js"
4
+ import { fetchReturning } from "./support/fetch-mock.js"
5
+
6
+ const AUTH_URL = "http://localhost:9999"
7
+ const HEADERS = { apikey: "test-anon-key", "Content-Type": "application/json" }
8
+
9
+ const RAW_USER = {
10
+ id: "user-1",
11
+ email: "old@example.com",
12
+ created_at: "2024-01-01T00:00:00Z",
13
+ updated_at: "2024-01-01T00:00:00Z",
14
+ app_metadata: { provider: "email" },
15
+ user_metadata: {},
16
+ role: "authenticated",
17
+ }
18
+
19
+ const TOKEN_RESPONSE = {
20
+ access_token: "access-token-123",
21
+ refresh_token: "refresh-token-abc",
22
+ token_type: "bearer",
23
+ expires_in: 3600,
24
+ user: RAW_USER,
25
+ }
26
+
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
+ /** Every event a listener sees after registration, without the registration emission itself. */
33
+ function recordEvents(client: AuthClient): AuthChangeEvent[] {
34
+ const events: AuthChangeEvent[] = []
35
+ let registered = false
36
+ client.onAuthStateChange((event) => {
37
+ if (registered) events.push(event)
38
+ })
39
+ registered = true
40
+ return events
41
+ }
42
+
43
+ async function signedInClient(): Promise<AuthClient> {
44
+ const client = new AuthClient(AUTH_URL, HEADERS)
45
+ vi.stubGlobal("fetch", fetchReturning(TOKEN_RESPONSE))
46
+ await client.signInWithPassword({ email: "old@example.com", password: "pw" })
47
+ return client
48
+ }
49
+
50
+ describe("USER_UPDATED", () => {
51
+ beforeEach(() => vi.restoreAllMocks())
52
+
53
+ it("is emitted after a successful updateUser, with the updated user on the session", async () => {
54
+ const client = await signedInClient()
55
+ const sessions: Array<string | undefined> = []
56
+ const events: AuthChangeEvent[] = []
57
+ let registered = false
58
+ client.onAuthStateChange((event, session) => {
59
+ if (!registered) return
60
+ events.push(event)
61
+ sessions.push(session?.user.email)
62
+ })
63
+ registered = true
64
+
65
+ vi.stubGlobal("fetch", fetchReturning({ ...RAW_USER, email: "new@example.com" }))
66
+ const { error } = await client.updateUser({ email: "new@example.com" })
67
+
68
+ expect(error).toBeNull()
69
+ expect(events).toEqual(["USER_UPDATED"])
70
+ expect(sessions).toEqual(["new@example.com"])
71
+ const { data } = await client.getSession()
72
+ expect(data.session?.user.email).toBe("new@example.com")
73
+ expect(data.session?.accessToken).toBe("access-token-123")
74
+ })
75
+
76
+ it("is not emitted when updateUser fails", async () => {
77
+ const client = await signedInClient()
78
+ const events = recordEvents(client)
79
+
80
+ vi.stubGlobal("fetch", fetchReturning({ msg: "weak password" }, 422))
81
+ const { error } = await client.updateUser({ password: "x" })
82
+
83
+ expect(error?.status).toBe(422)
84
+ expect(events).toEqual([])
85
+ })
86
+ })
87
+
88
+ describe("PASSWORD_RECOVERY", () => {
89
+ beforeEach(() => vi.restoreAllMocks())
90
+
91
+ it("is emitted when a recovery link's tokens are read from the URL", async () => {
92
+ const client = new AuthClient(AUTH_URL, HEADERS)
93
+ const events = recordEvents(client)
94
+ vi.stubGlobal("fetch", fetchReturning(RAW_USER))
95
+
96
+ const { error } = await client.getSessionFromUrl(
97
+ `https://app.example/reset#access_token=${accessTokenWithExp()}&refresh_token=rt-1&expires_in=3600&token_type=bearer&type=recovery`,
98
+ )
99
+
100
+ expect(error).toBeNull()
101
+ expect(events).toEqual(["SIGNED_IN", "PASSWORD_RECOVERY"])
102
+ })
103
+
104
+ it("is not emitted for an ordinary sign-in link", async () => {
105
+ const client = new AuthClient(AUTH_URL, HEADERS)
106
+ const events = recordEvents(client)
107
+ vi.stubGlobal("fetch", fetchReturning(RAW_USER))
108
+
109
+ await client.getSessionFromUrl(
110
+ `https://app.example/#access_token=${accessTokenWithExp()}&refresh_token=rt-1&type=magiclink`,
111
+ )
112
+
113
+ expect(events).toEqual(["SIGNED_IN"])
114
+ })
115
+
116
+ it("is emitted when a recovery OTP is verified", async () => {
117
+ const client = new AuthClient(AUTH_URL, HEADERS)
118
+ const events = recordEvents(client)
119
+ vi.stubGlobal("fetch", fetchReturning(TOKEN_RESPONSE))
120
+
121
+ const { error } = await client.verifyOtp({ type: "recovery", token: "123456", email: "old@example.com" })
122
+
123
+ expect(error).toBeNull()
124
+ expect(events).toEqual(["SIGNED_IN", "PASSWORD_RECOVERY"])
125
+ })
126
+
127
+ it("is not emitted when a recovery OTP is refused", async () => {
128
+ const client = new AuthClient(AUTH_URL, HEADERS)
129
+ const events = recordEvents(client)
130
+ vi.stubGlobal("fetch", fetchReturning({ msg: "expired" }, 403))
131
+
132
+ await client.verifyOtp({ type: "recovery", token: "123456", email: "old@example.com" })
133
+
134
+ expect(events).toEqual([])
135
+ })
136
+ })
@@ -0,0 +1,204 @@
1
+ import { describe, it, expect, vi, afterEach } from "vitest"
2
+ import { AuthClient } from "../src/auth.js"
3
+ import { createClient } from "../src/index.js"
4
+ import type { AuthChangeEvent } from "../src/types.js"
5
+ import { fetchCall, fetchReturning, jsonBody } from "./support/fetch-mock.js"
6
+
7
+ /**
8
+ * The OAuth return: the auth server sends the browser back with the session in the URL, as tokens in
9
+ * the fragment (implicit) or a `code` in the query (PKCE). The client finishes the sign-in itself on
10
+ * start, as supabase-js does with `detectSessionInUrl`, so no app has to read the URL.
11
+ */
12
+
13
+ const AUTH_URL = "http://localhost:9999/auth/v1"
14
+ const HEADERS = { apikey: "anon", "Content-Type": "application/json" }
15
+ const VERIFIER_KEY = "supatype.auth.session-code-verifier"
16
+ const PROVIDER_KEY = "supatype.auth.session-oauth-provider"
17
+
18
+ const RAW_USER = {
19
+ id: "user-1",
20
+ email: "ada@example.com",
21
+ created_at: "2024-01-01T00:00:00Z",
22
+ updated_at: "2024-01-01T00:00:00Z",
23
+ app_metadata: { provider: "github" },
24
+ user_metadata: { full_name: "Ada Lovelace" },
25
+ }
26
+
27
+ function jsonResponse(body: unknown, status = 200): Response {
28
+ return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } })
29
+ }
30
+
31
+ function accessToken(): string {
32
+ const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")
33
+ return `eyJhbGciOiJub25lIn0.${payload}.sig`
34
+ }
35
+
36
+ /** A browser at `href`, with a localStorage holding `stored`. */
37
+ function stubBrowser(href: string, stored: Record<string, string> = {}) {
38
+ const store = new Map(Object.entries(stored))
39
+ const replaceState = vi.fn<(state: unknown, unused: string, url: string) => void>()
40
+ vi.stubGlobal("window", {
41
+ location: { href, protocol: "https:" },
42
+ history: { state: null, replaceState },
43
+ localStorage: {
44
+ getItem: (k: string) => store.get(k) ?? null,
45
+ setItem: (k: string, v: string) => { store.set(k, v) },
46
+ removeItem: (k: string) => { store.delete(k) },
47
+ },
48
+ })
49
+ return { replaceState, store }
50
+ }
51
+
52
+ function recordEvents(client: AuthClient): AuthChangeEvent[] {
53
+ const events: AuthChangeEvent[] = []
54
+ client.onAuthStateChange((event) => { events.push(event) })
55
+ return events
56
+ }
57
+
58
+ afterEach(() => {
59
+ vi.unstubAllGlobals()
60
+ vi.restoreAllMocks()
61
+ })
62
+
63
+ describe("detectSessionInUrl", () => {
64
+ it("signs in from implicit-grant tokens in the fragment and cleans the URL", async () => {
65
+ const token = accessToken()
66
+ const { replaceState } = stubBrowser(
67
+ `https://app.example/welcome?tab=1#access_token=${token}&refresh_token=rt-1&expires_in=3600&token_type=bearer&provider_token=gh&sb=`,
68
+ )
69
+ const fetch = vi.fn().mockResolvedValue(jsonResponse(RAW_USER))
70
+ vi.stubGlobal("fetch", fetch)
71
+
72
+ const client = new AuthClient(AUTH_URL, HEADERS)
73
+ const events = recordEvents(client)
74
+ const { error } = await client.initialize()
75
+
76
+ expect(error).toBeNull()
77
+ expect(fetch.mock.calls[0]?.[0]).toBe(`${AUTH_URL}/user`)
78
+ const { data } = await client.getSession()
79
+ expect(data.session?.accessToken).toBe(token)
80
+ expect(data.session?.user.userMetadata["full_name"]).toBe("Ada Lovelace")
81
+ expect(events).toEqual(["SIGNED_OUT", "SIGNED_IN"])
82
+ expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/welcome?tab=1")
83
+ })
84
+
85
+ it("exchanges a PKCE code from the query and keeps the app's own parameters", async () => {
86
+ const { replaceState, store } = stubBrowser("https://app.example/cb?next=%2Fhome&code=auth-code-1", {
87
+ [VERIFIER_KEY]: "verifier-1",
88
+ })
89
+ const fetch = fetchReturning({ access_token: accessToken(), refresh_token: "rt-2", expires_in: 3600, token_type: "bearer", user: RAW_USER })
90
+ vi.stubGlobal("fetch", fetch)
91
+
92
+ const client = new AuthClient(AUTH_URL, HEADERS)
93
+ const events = recordEvents(client)
94
+ const { error } = await client.initialize()
95
+
96
+ expect(error).toBeNull()
97
+ const { url, init } = fetchCall(fetch)
98
+ expect(url).toBe(`${AUTH_URL}/token?grant_type=pkce`)
99
+ expect(jsonBody(init)).toEqual({ auth_code: "auth-code-1", code_verifier: "verifier-1" })
100
+ expect(events).toEqual(["SIGNED_OUT", "SIGNED_IN"])
101
+ expect(store.has(VERIFIER_KEY)).toBe(false)
102
+ expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/cb?next=%2Fhome")
103
+ })
104
+
105
+ it("leaves a `code` alone when this client started no PKCE flow", async () => {
106
+ const { replaceState } = stubBrowser("https://app.example/invite?code=team-42")
107
+ const fetch = vi.fn()
108
+ vi.stubGlobal("fetch", fetch)
109
+
110
+ const { error } = await new AuthClient(AUTH_URL, HEADERS).initialize()
111
+
112
+ expect(error).toBeNull()
113
+ expect(fetch).not.toHaveBeenCalled()
114
+ expect(replaceState).not.toHaveBeenCalled()
115
+ })
116
+
117
+ it("reports a refused sign-in from the URL, naming the provider that was started, and cleans it", async () => {
118
+ const { replaceState } = stubBrowser(
119
+ "https://app.example/?error=access_denied&error_code=signup_disabled&error_description=Signups+not+allowed#error=access_denied&error_code=signup_disabled&error_description=Signups+not+allowed&sb=",
120
+ { [PROVIDER_KEY]: "github" },
121
+ )
122
+ vi.stubGlobal("fetch", vi.fn())
123
+
124
+ const client = new AuthClient(AUTH_URL, HEADERS)
125
+ const { error } = await client.initialize()
126
+
127
+ expect(error?.message).toBe("Signups not allowed")
128
+ expect(error?.code).toBe("signup_disabled")
129
+ expect(error?.provider).toBe("github")
130
+ expect((await client.getSession()).data.session).toBeNull()
131
+ expect(replaceState).toHaveBeenCalledWith(null, "", "https://app.example/")
132
+ })
133
+
134
+ it("does nothing when the app opts out", async () => {
135
+ const { replaceState } = stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1`)
136
+ const fetch = vi.fn()
137
+ vi.stubGlobal("fetch", fetch)
138
+
139
+ const client = createClient({ url: "http://localhost:9999", anonKey: "anon", auth: { detectSessionInUrl: false } })
140
+ const { error } = await client.auth.initialize()
141
+
142
+ expect(error).toBeNull()
143
+ expect(fetch).not.toHaveBeenCalled()
144
+ expect(replaceState).not.toHaveBeenCalled()
145
+ expect((await client.auth.getSession()).data.session).toBeNull()
146
+ })
147
+
148
+ it("is on by default through createClient", async () => {
149
+ stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1`)
150
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(RAW_USER)))
151
+
152
+ const client = createClient({ url: "http://localhost:9999", anonKey: "anon" })
153
+
154
+ expect((await client.auth.getSession()).data.session?.user.id).toBe("user-1")
155
+ })
156
+ })
157
+
158
+ describe("signInWithOAuth checks the provider is enabled", () => {
159
+ const settings = (external: Record<string, boolean>) => jsonResponse({ external, disable_signup: false })
160
+
161
+ it("refuses a provider the server has not enabled, before any redirect", async () => {
162
+ const fetch = vi.fn().mockResolvedValue(settings({ github: false, google: true }))
163
+ vi.stubGlobal("fetch", fetch)
164
+
165
+ const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "github" })
166
+
167
+ expect(fetch.mock.calls[0]?.[0]).toBe(`${AUTH_URL}/settings`)
168
+ expect(error?.code).toBe("provider_disabled")
169
+ expect(error?.message).toBe("Sign-in with github is not enabled for this project.")
170
+ expect(data.url).toBe("")
171
+ })
172
+
173
+ it("returns the authorize URL for an enabled provider and remembers which one was started", async () => {
174
+ const { store } = stubBrowser("https://app.example/")
175
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(settings({ github: true })))
176
+
177
+ const { data, error } = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "github" })
178
+
179
+ expect(error).toBeNull()
180
+ expect(data.url).toBe(`${AUTH_URL}/authorize?provider=github`)
181
+ expect(store.get(PROVIDER_KEY)).toBe("github")
182
+ })
183
+
184
+ it("matches the provider as the server does, whatever its case", async () => {
185
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(settings({ github: false, google: true })))
186
+
187
+ const off = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "GitHub" })
188
+ expect(off.error?.code).toBe("provider_disabled")
189
+
190
+ const on = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "Google" })
191
+ expect(on.error).toBeNull()
192
+ })
193
+
194
+ it("lets the server decide when the settings cannot be read or do not list the provider", async () => {
195
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("offline")))
196
+ const offline = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "github" })
197
+ expect(offline.error).toBeNull()
198
+
199
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(settings({ github: false })))
200
+ const custom = await new AuthClient(AUTH_URL, HEADERS).signInWithOAuth({ provider: "custom:acme" })
201
+ expect(custom.error).toBeNull()
202
+ expect(custom.data.url).toContain("provider=custom%3Aacme")
203
+ })
204
+ })