@supatype/client 0.1.0-alpha.6
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 +4 -0
- package/.turbo/turbo-test.log +7 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/dist/auth.d.ts +243 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +560 -0
- package/dist/auth.js.map +1 -0
- package/dist/error-codes-doc.d.ts +31 -0
- package/dist/error-codes-doc.d.ts.map +1 -0
- package/dist/error-codes-doc.js +294 -0
- package/dist/error-codes-doc.js.map +1 -0
- package/dist/errors.d.ts +197 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +162 -0
- package/dist/errors.js.map +1 -0
- package/dist/fetch-with-retry.d.ts +49 -0
- package/dist/fetch-with-retry.d.ts.map +1 -0
- package/dist/fetch-with-retry.js +150 -0
- package/dist/fetch-with-retry.js.map +1 -0
- package/dist/index.d.ts +137 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +225 -0
- package/dist/index.js.map +1 -0
- package/dist/query.d.ts +53 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +216 -0
- package/dist/query.js.map +1 -0
- package/dist/realtime.d.ts +69 -0
- package/dist/realtime.d.ts.map +1 -0
- package/dist/realtime.js +279 -0
- package/dist/realtime.js.map +1 -0
- package/dist/retry.d.ts +24 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +25 -0
- package/dist/retry.js.map +1 -0
- package/dist/serverless-docs.d.ts +38 -0
- package/dist/serverless-docs.d.ts.map +1 -0
- package/dist/serverless-docs.js +83 -0
- package/dist/serverless-docs.js.map +1 -0
- package/dist/storage.d.ts +79 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +130 -0
- package/dist/storage.js.map +1 -0
- package/dist/types.d.ts +141 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +26 -0
- package/src/auth.ts +713 -0
- package/src/error-codes-doc.ts +315 -0
- package/src/errors.ts +201 -0
- package/src/fetch-with-retry.ts +200 -0
- package/src/index.ts +418 -0
- package/src/query.ts +280 -0
- package/src/realtime.ts +418 -0
- package/src/retry.ts +35 -0
- package/src/serverless-docs.ts +107 -0
- package/src/storage.ts +182 -0
- package/src/types.ts +184 -0
- package/tests/auth.test.ts +282 -0
- package/tests/mfa-totp-integration.test.ts +359 -0
- package/tests/query.test.ts +286 -0
- package/tests/rate-limit-integration.test.ts +185 -0
- package/tests/realtime-multi-tenant-integration.test.ts +372 -0
- package/tests/retry-integration.test.ts +212 -0
- package/tests/serverless.test.ts +115 -0
- package/tests/storage-quota-integration.test.ts +189 -0
- package/tests/storage-upload-limit-integration.test.ts +185 -0
- package/tests/types.test.ts +123 -0
- package/tsconfig.json +11 -0
- package/tsconfig.tsbuildinfo +1 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
+
import { AuthClient } from "../src/auth.js"
|
|
3
|
+
|
|
4
|
+
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
5
|
+
|
|
6
|
+
const GOTRUE_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: "test@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: { name: "Test" },
|
|
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 mockFetch(body: unknown, ok = true, status?: number): ReturnType<typeof vi.fn> {
|
|
28
|
+
return vi.fn().mockResolvedValue({
|
|
29
|
+
ok,
|
|
30
|
+
status: status ?? (ok ? 200 : 400),
|
|
31
|
+
json: vi.fn().mockResolvedValue(body),
|
|
32
|
+
headers: { get: () => null },
|
|
33
|
+
})
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function freshClient(): AuthClient {
|
|
37
|
+
return new AuthClient(GOTRUE_URL, HEADERS)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ─── Tests ────────────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
describe("AuthClient.signUp()", () => {
|
|
43
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
44
|
+
|
|
45
|
+
it("sends POST to /signup", async () => {
|
|
46
|
+
const fetch = mockFetch(TOKEN_RESPONSE)
|
|
47
|
+
vi.stubGlobal("fetch", fetch)
|
|
48
|
+
|
|
49
|
+
const { error } = await freshClient().signUp({ email: "a@b.com", password: "secret" })
|
|
50
|
+
|
|
51
|
+
expect(error).toBeNull()
|
|
52
|
+
expect(fetch).toHaveBeenCalledWith(
|
|
53
|
+
`${GOTRUE_URL}/signup`,
|
|
54
|
+
expect.objectContaining({ method: "POST" }),
|
|
55
|
+
)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it("includes optional user metadata in request body", async () => {
|
|
59
|
+
const fetch = mockFetch(TOKEN_RESPONSE)
|
|
60
|
+
vi.stubGlobal("fetch", fetch)
|
|
61
|
+
|
|
62
|
+
await freshClient().signUp({ email: "a@b.com", password: "s", options: { data: { name: "Alice" } } })
|
|
63
|
+
|
|
64
|
+
const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
|
|
65
|
+
const body = JSON.parse(opts.body as string) as Record<string, unknown>
|
|
66
|
+
expect(body["data"]).toEqual({ name: "Alice" })
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it("returns error on 400", async () => {
|
|
70
|
+
vi.stubGlobal("fetch", mockFetch({ error_description: "Email taken" }, false, 400))
|
|
71
|
+
|
|
72
|
+
const { data, error } = await freshClient().signUp({ email: "a@b.com", password: "s" })
|
|
73
|
+
|
|
74
|
+
expect(data.session).toBeNull()
|
|
75
|
+
expect(error?.message).toBe("Email taken")
|
|
76
|
+
expect(error?.status).toBe(400)
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it("parses session and user from response", async () => {
|
|
80
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
81
|
+
|
|
82
|
+
const { data, error } = await freshClient().signUp({ email: "a@b.com", password: "s" })
|
|
83
|
+
|
|
84
|
+
expect(error).toBeNull()
|
|
85
|
+
expect(data.session?.accessToken).toBe("access-token-123")
|
|
86
|
+
expect(data.session?.refreshToken).toBe("refresh-token-abc")
|
|
87
|
+
expect(data.user?.id).toBe("user-1")
|
|
88
|
+
expect(data.user?.email).toBe("test@example.com")
|
|
89
|
+
})
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
describe("AuthClient.signInWithPassword()", () => {
|
|
93
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
94
|
+
|
|
95
|
+
it("sends POST to /token?grant_type=password", async () => {
|
|
96
|
+
const fetch = mockFetch(TOKEN_RESPONSE)
|
|
97
|
+
vi.stubGlobal("fetch", fetch)
|
|
98
|
+
|
|
99
|
+
await freshClient().signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
100
|
+
|
|
101
|
+
const [url] = fetch.mock.calls[0] as [string, unknown]
|
|
102
|
+
expect(url).toBe(`${GOTRUE_URL}/token?grant_type=password`)
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
it("returns error on invalid credentials", async () => {
|
|
106
|
+
vi.stubGlobal("fetch", mockFetch({ error_description: "Invalid login credentials" }, false, 400))
|
|
107
|
+
|
|
108
|
+
const { error } = await freshClient().signInWithPassword({ email: "a@b.com", password: "wrong" })
|
|
109
|
+
|
|
110
|
+
expect(error?.message).toBe("Invalid login credentials")
|
|
111
|
+
expect(error?.status).toBe(400)
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
it("updates internal session state", async () => {
|
|
115
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
116
|
+
|
|
117
|
+
const client = freshClient()
|
|
118
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
119
|
+
const { data } = await client.getSession()
|
|
120
|
+
|
|
121
|
+
expect(data.session?.accessToken).toBe("access-token-123")
|
|
122
|
+
})
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
describe("AuthClient.signInWithOAuth()", () => {
|
|
126
|
+
it("returns redirect URL without making a fetch call", async () => {
|
|
127
|
+
const fetchSpy = vi.fn()
|
|
128
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
129
|
+
|
|
130
|
+
const { data, error } = await freshClient().signInWithOAuth({ provider: "google" })
|
|
131
|
+
|
|
132
|
+
expect(fetchSpy).not.toHaveBeenCalled()
|
|
133
|
+
expect(error).toBeNull()
|
|
134
|
+
expect(data.url).toContain("authorize")
|
|
135
|
+
expect(data.url).toContain("provider=google")
|
|
136
|
+
expect(data.provider).toBe("google")
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it("appends redirect_to param when provided", async () => {
|
|
140
|
+
vi.stubGlobal("fetch", vi.fn())
|
|
141
|
+
|
|
142
|
+
const { data } = await freshClient().signInWithOAuth({
|
|
143
|
+
provider: "github",
|
|
144
|
+
options: { redirectTo: "http://localhost:3000/auth/callback" },
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
expect(data.url).toContain("redirect_to=")
|
|
148
|
+
})
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
describe("AuthClient.signOut()", () => {
|
|
152
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
153
|
+
|
|
154
|
+
it("calls /logout when a session exists", async () => {
|
|
155
|
+
const client = freshClient()
|
|
156
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
157
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
158
|
+
|
|
159
|
+
const logoutFetch = vi.fn().mockResolvedValue({ ok: true, status: 204 })
|
|
160
|
+
vi.stubGlobal("fetch", logoutFetch)
|
|
161
|
+
await client.signOut()
|
|
162
|
+
|
|
163
|
+
const [url, opts] = logoutFetch.mock.calls[0] as [string, RequestInit]
|
|
164
|
+
expect(url).toBe(`${GOTRUE_URL}/logout`)
|
|
165
|
+
expect(opts.method).toBe("POST")
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
it("clears session after sign out", async () => {
|
|
169
|
+
const client = freshClient()
|
|
170
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
171
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
172
|
+
|
|
173
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, status: 204 }))
|
|
174
|
+
await client.signOut()
|
|
175
|
+
|
|
176
|
+
const { data } = await client.getSession()
|
|
177
|
+
expect(data.session).toBeNull()
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
it("does not call /logout when no session exists", async () => {
|
|
181
|
+
const fetchSpy = vi.fn()
|
|
182
|
+
vi.stubGlobal("fetch", fetchSpy)
|
|
183
|
+
|
|
184
|
+
await freshClient().signOut()
|
|
185
|
+
|
|
186
|
+
expect(fetchSpy).not.toHaveBeenCalled()
|
|
187
|
+
})
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
describe("AuthClient.onAuthStateChange()", () => {
|
|
191
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
192
|
+
|
|
193
|
+
it("emits SIGNED_OUT immediately when not signed in", () => {
|
|
194
|
+
const events: string[] = []
|
|
195
|
+
const client = freshClient()
|
|
196
|
+
const { data: { subscription } } = client.onAuthStateChange((event) => events.push(event))
|
|
197
|
+
|
|
198
|
+
expect(events).toContain("SIGNED_OUT")
|
|
199
|
+
subscription.unsubscribe()
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
it("emits SIGNED_IN after successful sign in", async () => {
|
|
203
|
+
const events: string[] = []
|
|
204
|
+
const client = freshClient()
|
|
205
|
+
const { data: { subscription } } = client.onAuthStateChange((event) => events.push(event))
|
|
206
|
+
|
|
207
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
208
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
209
|
+
|
|
210
|
+
expect(events).toContain("SIGNED_IN")
|
|
211
|
+
subscription.unsubscribe()
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
it("emits SIGNED_OUT after sign out", async () => {
|
|
215
|
+
const events: string[] = []
|
|
216
|
+
const client = freshClient()
|
|
217
|
+
|
|
218
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
219
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
220
|
+
|
|
221
|
+
const { data: { subscription } } = client.onAuthStateChange((event) => events.push(event))
|
|
222
|
+
events.length = 0 // clear SIGNED_IN from subscription creation
|
|
223
|
+
|
|
224
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, status: 204 }))
|
|
225
|
+
await client.signOut()
|
|
226
|
+
|
|
227
|
+
expect(events).toContain("SIGNED_OUT")
|
|
228
|
+
subscription.unsubscribe()
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
it("unsubscribe stops future notifications", async () => {
|
|
232
|
+
let callCount = 0
|
|
233
|
+
const client = freshClient()
|
|
234
|
+
const { data: { subscription } } = client.onAuthStateChange(() => callCount++)
|
|
235
|
+
const countAtUnsubscribe = callCount
|
|
236
|
+
subscription.unsubscribe()
|
|
237
|
+
|
|
238
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
239
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
240
|
+
|
|
241
|
+
expect(callCount).toBe(countAtUnsubscribe) // no new calls
|
|
242
|
+
})
|
|
243
|
+
|
|
244
|
+
it("multiple listeners each receive events", async () => {
|
|
245
|
+
const events1: string[] = []
|
|
246
|
+
const events2: string[] = []
|
|
247
|
+
const client = freshClient()
|
|
248
|
+
|
|
249
|
+
const { data: { subscription: s1 } } = client.onAuthStateChange((e) => events1.push(e))
|
|
250
|
+
const { data: { subscription: s2 } } = client.onAuthStateChange((e) => events2.push(e))
|
|
251
|
+
|
|
252
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
253
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
254
|
+
|
|
255
|
+
expect(events1).toContain("SIGNED_IN")
|
|
256
|
+
expect(events2).toContain("SIGNED_IN")
|
|
257
|
+
s1.unsubscribe()
|
|
258
|
+
s2.unsubscribe()
|
|
259
|
+
})
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
describe("AuthClient.getSession() / getUser()", () => {
|
|
263
|
+
it("getSession returns null when not authenticated", async () => {
|
|
264
|
+
const { data } = await freshClient().getSession()
|
|
265
|
+
expect(data.session).toBeNull()
|
|
266
|
+
})
|
|
267
|
+
|
|
268
|
+
it("getUser fetches /user with Authorization header when session exists", async () => {
|
|
269
|
+
const client = freshClient()
|
|
270
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
271
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
272
|
+
|
|
273
|
+
const userFetch = mockFetch(RAW_USER)
|
|
274
|
+
vi.stubGlobal("fetch", userFetch)
|
|
275
|
+
const { data, error } = await client.getUser()
|
|
276
|
+
|
|
277
|
+
expect(error).toBeNull()
|
|
278
|
+
expect(data.user?.id).toBe("user-1")
|
|
279
|
+
const [, opts] = userFetch.mock.calls[0] as [string, RequestInit]
|
|
280
|
+
expect((opts.headers as Record<string, string>)["Authorization"]).toContain("Bearer access-token-123")
|
|
281
|
+
})
|
|
282
|
+
})
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration test — Task 89: MFA TOTP flow
|
|
3
|
+
*
|
|
4
|
+
* Tests: enroll -> QR code -> verify code -> login requires 2 steps ->
|
|
5
|
+
* JWT aal2 -> unenroll -> single step.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
9
|
+
import { AuthClient } from "../src/auth.js"
|
|
10
|
+
|
|
11
|
+
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
12
|
+
|
|
13
|
+
const GOTRUE_URL = "http://localhost:9999"
|
|
14
|
+
const HEADERS = { apikey: "test-anon-key", "Content-Type": "application/json" }
|
|
15
|
+
|
|
16
|
+
const FACTOR_ID = "factor-totp-001"
|
|
17
|
+
const CHALLENGE_ID = "challenge-001"
|
|
18
|
+
const TOTP_SECRET = "JBSWY3DPEHPK3PXP"
|
|
19
|
+
|
|
20
|
+
const RAW_USER = {
|
|
21
|
+
id: "user-1",
|
|
22
|
+
email: "mfa@example.com",
|
|
23
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
24
|
+
updated_at: "2024-01-01T00:00:00Z",
|
|
25
|
+
app_metadata: { provider: "email" },
|
|
26
|
+
user_metadata: {},
|
|
27
|
+
role: "authenticated",
|
|
28
|
+
factors: [] as Record<string, unknown>[],
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function makeAal1Token(): string {
|
|
32
|
+
const header = Buffer.from(JSON.stringify({ alg: "HS256" })).toString("base64url")
|
|
33
|
+
const payload = Buffer.from(
|
|
34
|
+
JSON.stringify({ sub: "user-1", aal: "aal1", amr: [{ method: "password" }] }),
|
|
35
|
+
).toString("base64url")
|
|
36
|
+
return `${header}.${payload}.mock-sig`
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function makeAal2Token(): string {
|
|
40
|
+
const header = Buffer.from(JSON.stringify({ alg: "HS256" })).toString("base64url")
|
|
41
|
+
const payload = Buffer.from(
|
|
42
|
+
JSON.stringify({
|
|
43
|
+
sub: "user-1",
|
|
44
|
+
aal: "aal2",
|
|
45
|
+
amr: [{ method: "password" }, { method: "totp" }],
|
|
46
|
+
}),
|
|
47
|
+
).toString("base64url")
|
|
48
|
+
return `${header}.${payload}.mock-sig`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function makeTokenResponse(overrides?: Record<string, unknown>) {
|
|
52
|
+
return {
|
|
53
|
+
access_token: makeAal1Token(),
|
|
54
|
+
refresh_token: "refresh-token-abc",
|
|
55
|
+
token_type: "bearer",
|
|
56
|
+
expires_in: 3600,
|
|
57
|
+
user: { ...RAW_USER },
|
|
58
|
+
...overrides,
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function mockFetch(body: unknown, ok = true, status?: number): ReturnType<typeof vi.fn> {
|
|
63
|
+
return vi.fn().mockResolvedValue({
|
|
64
|
+
ok,
|
|
65
|
+
status: status ?? (ok ? 200 : 400),
|
|
66
|
+
json: vi.fn().mockResolvedValue(body),
|
|
67
|
+
headers: { get: () => null },
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function freshClient(): AuthClient {
|
|
72
|
+
return new AuthClient(GOTRUE_URL, HEADERS)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ─── Tests ───────────────────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
describe("Task 89 — MFA TOTP integration", () => {
|
|
78
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
79
|
+
|
|
80
|
+
describe("Step 1 — Enroll TOTP factor", () => {
|
|
81
|
+
it("calls POST /factors with factor_type=totp", async () => {
|
|
82
|
+
// First sign in to have a session
|
|
83
|
+
const client = freshClient()
|
|
84
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse()))
|
|
85
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
86
|
+
|
|
87
|
+
// Now mock the enroll response
|
|
88
|
+
const enrollResponse = {
|
|
89
|
+
id: FACTOR_ID,
|
|
90
|
+
type: "totp",
|
|
91
|
+
friendly_name: "My Authenticator",
|
|
92
|
+
totp: {
|
|
93
|
+
qr_code: "data:image/svg+xml;base64,PHN2Zy...",
|
|
94
|
+
secret: TOTP_SECRET,
|
|
95
|
+
uri: `otpauth://totp/Supatype:mfa@example.com?secret=${TOTP_SECRET}&issuer=Supatype`,
|
|
96
|
+
},
|
|
97
|
+
}
|
|
98
|
+
const enrollFetch = mockFetch(enrollResponse)
|
|
99
|
+
vi.stubGlobal("fetch", enrollFetch)
|
|
100
|
+
|
|
101
|
+
const { data, error } = await client.mfa.enroll({
|
|
102
|
+
factorType: "totp",
|
|
103
|
+
friendlyName: "My Authenticator",
|
|
104
|
+
issuer: "Supatype",
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
expect(error).toBeNull()
|
|
108
|
+
expect(data).not.toBeNull()
|
|
109
|
+
expect(data!.id).toBe(FACTOR_ID)
|
|
110
|
+
expect(data!.type).toBe("totp")
|
|
111
|
+
|
|
112
|
+
// Verify POST was sent to /factors
|
|
113
|
+
const [url, opts] = enrollFetch.mock.calls[0] as [string, RequestInit]
|
|
114
|
+
expect(url).toBe(`${GOTRUE_URL}/factors`)
|
|
115
|
+
expect(opts.method).toBe("POST")
|
|
116
|
+
const body = JSON.parse(opts.body as string) as Record<string, string>
|
|
117
|
+
expect(body["factor_type"]).toBe("totp")
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it("returns QR code and secret for TOTP enrollment", async () => {
|
|
121
|
+
const client = freshClient()
|
|
122
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse()))
|
|
123
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
124
|
+
|
|
125
|
+
vi.stubGlobal("fetch", mockFetch({
|
|
126
|
+
id: FACTOR_ID,
|
|
127
|
+
type: "totp",
|
|
128
|
+
friendly_name: "App",
|
|
129
|
+
totp: {
|
|
130
|
+
qr_code: "data:image/svg+xml;base64,PHN2Zy...",
|
|
131
|
+
secret: TOTP_SECRET,
|
|
132
|
+
uri: `otpauth://totp/Supatype:mfa@example.com?secret=${TOTP_SECRET}`,
|
|
133
|
+
},
|
|
134
|
+
}))
|
|
135
|
+
|
|
136
|
+
const { data } = await client.mfa.enroll({ factorType: "totp" })
|
|
137
|
+
|
|
138
|
+
expect(data!.totp).toBeDefined()
|
|
139
|
+
expect(data!.totp!.qrCode).toContain("data:image/svg+xml")
|
|
140
|
+
expect(data!.totp!.secret).toBe(TOTP_SECRET)
|
|
141
|
+
expect(data!.totp!.uri).toContain("otpauth://totp/")
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
it("returns error when not authenticated", async () => {
|
|
145
|
+
const client = freshClient()
|
|
146
|
+
const { data, error } = await client.mfa.enroll({ factorType: "totp" })
|
|
147
|
+
|
|
148
|
+
expect(data).toBeNull()
|
|
149
|
+
expect(error).not.toBeNull()
|
|
150
|
+
expect(error!.message).toContain("Not authenticated")
|
|
151
|
+
})
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
describe("Step 2 — Verify TOTP code (challenge + verify)", () => {
|
|
155
|
+
it("creates a challenge and verifies the TOTP code", async () => {
|
|
156
|
+
const client = freshClient()
|
|
157
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse()))
|
|
158
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
159
|
+
|
|
160
|
+
// Mock challenge
|
|
161
|
+
const challengeCall = mockFetch({
|
|
162
|
+
id: CHALLENGE_ID,
|
|
163
|
+
type: "totp",
|
|
164
|
+
expires_at: Math.floor(Date.now() / 1000) + 300,
|
|
165
|
+
})
|
|
166
|
+
vi.stubGlobal("fetch", challengeCall)
|
|
167
|
+
|
|
168
|
+
const challengeResult = await client.mfa.challenge({ factorId: FACTOR_ID })
|
|
169
|
+
expect(challengeResult.error).toBeNull()
|
|
170
|
+
expect(challengeResult.data!.id).toBe(CHALLENGE_ID)
|
|
171
|
+
|
|
172
|
+
// Mock verify — returns AAL2 token
|
|
173
|
+
const aal2Response = makeTokenResponse({
|
|
174
|
+
access_token: makeAal2Token(),
|
|
175
|
+
})
|
|
176
|
+
aal2Response.user.factors = [
|
|
177
|
+
{ id: FACTOR_ID, factor_type: "totp", status: "verified", created_at: "", updated_at: "" },
|
|
178
|
+
]
|
|
179
|
+
vi.stubGlobal("fetch", mockFetch(aal2Response))
|
|
180
|
+
|
|
181
|
+
const verifyResult = await client.mfa.verify({
|
|
182
|
+
factorId: FACTOR_ID,
|
|
183
|
+
challengeId: CHALLENGE_ID,
|
|
184
|
+
code: "123456",
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
expect(verifyResult.error).toBeNull()
|
|
188
|
+
expect(verifyResult.data.session).not.toBeNull()
|
|
189
|
+
expect(verifyResult.data.session!.accessToken).toBe(aal2Response.access_token)
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
it("challengeAndVerify is a single-call convenience", async () => {
|
|
193
|
+
const client = freshClient()
|
|
194
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse()))
|
|
195
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
196
|
+
|
|
197
|
+
// First call is challenge, second is verify
|
|
198
|
+
let callCount = 0
|
|
199
|
+
const mockFn = vi.fn().mockImplementation(async () => {
|
|
200
|
+
callCount++
|
|
201
|
+
if (callCount === 1) {
|
|
202
|
+
// Challenge response
|
|
203
|
+
return {
|
|
204
|
+
ok: true,
|
|
205
|
+
status: 200,
|
|
206
|
+
json: async () => ({
|
|
207
|
+
id: CHALLENGE_ID,
|
|
208
|
+
type: "totp",
|
|
209
|
+
expires_at: Math.floor(Date.now() / 1000) + 300,
|
|
210
|
+
}),
|
|
211
|
+
headers: { get: () => null },
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Verify response
|
|
215
|
+
return {
|
|
216
|
+
ok: true,
|
|
217
|
+
status: 200,
|
|
218
|
+
json: async () => makeTokenResponse({ access_token: makeAal2Token() }),
|
|
219
|
+
headers: { get: () => null },
|
|
220
|
+
}
|
|
221
|
+
})
|
|
222
|
+
vi.stubGlobal("fetch", mockFn)
|
|
223
|
+
|
|
224
|
+
const { data, error } = await client.mfa.challengeAndVerify({
|
|
225
|
+
factorId: FACTOR_ID,
|
|
226
|
+
code: "654321",
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
expect(error).toBeNull()
|
|
230
|
+
expect(data.session).not.toBeNull()
|
|
231
|
+
expect(mockFn).toHaveBeenCalledTimes(2)
|
|
232
|
+
})
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
describe("Step 3 — Login requires two steps with MFA enrolled", () => {
|
|
236
|
+
it("first step: password login returns AAL1 session", async () => {
|
|
237
|
+
const client = freshClient()
|
|
238
|
+
const aal1Response = makeTokenResponse()
|
|
239
|
+
vi.stubGlobal("fetch", mockFetch(aal1Response))
|
|
240
|
+
|
|
241
|
+
const { data } = await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
242
|
+
|
|
243
|
+
expect(data.session).not.toBeNull()
|
|
244
|
+
// Decode JWT to check AAL
|
|
245
|
+
const parts = data.session!.accessToken.split(".")
|
|
246
|
+
const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString()) as Record<string, string>
|
|
247
|
+
expect(payload["aal"]).toBe("aal1")
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
it("second step: TOTP verification elevates to AAL2", async () => {
|
|
251
|
+
const client = freshClient()
|
|
252
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse()))
|
|
253
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
254
|
+
|
|
255
|
+
// Challenge
|
|
256
|
+
vi.stubGlobal("fetch", mockFetch({
|
|
257
|
+
id: CHALLENGE_ID,
|
|
258
|
+
type: "totp",
|
|
259
|
+
expires_at: Math.floor(Date.now() / 1000) + 300,
|
|
260
|
+
}))
|
|
261
|
+
await client.mfa.challenge({ factorId: FACTOR_ID })
|
|
262
|
+
|
|
263
|
+
// Verify — AAL2
|
|
264
|
+
const aal2Token = makeAal2Token()
|
|
265
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse({ access_token: aal2Token })))
|
|
266
|
+
const { data } = await client.mfa.verify({
|
|
267
|
+
factorId: FACTOR_ID,
|
|
268
|
+
challengeId: CHALLENGE_ID,
|
|
269
|
+
code: "123456",
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
expect(data.session).not.toBeNull()
|
|
273
|
+
const parts = data.session!.accessToken.split(".")
|
|
274
|
+
const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString()) as Record<string, unknown>
|
|
275
|
+
expect(payload["aal"]).toBe("aal2")
|
|
276
|
+
expect(payload["amr"]).toEqual(
|
|
277
|
+
expect.arrayContaining([{ method: "password" }, { method: "totp" }]),
|
|
278
|
+
)
|
|
279
|
+
})
|
|
280
|
+
})
|
|
281
|
+
|
|
282
|
+
describe("Step 4 — getAuthenticatorAssuranceLevel", () => {
|
|
283
|
+
it("returns aal1 before TOTP verification", async () => {
|
|
284
|
+
const client = freshClient()
|
|
285
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse()))
|
|
286
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
287
|
+
|
|
288
|
+
// Mock getUser to return user without verified factors
|
|
289
|
+
vi.stubGlobal("fetch", mockFetch({ ...RAW_USER, factors: [] }))
|
|
290
|
+
|
|
291
|
+
const { data } = await client.mfa.getAuthenticatorAssuranceLevel()
|
|
292
|
+
expect(data).not.toBeNull()
|
|
293
|
+
expect(data!.currentLevel).toBe("aal1")
|
|
294
|
+
expect(data!.currentAuthenticationMethods).toContain("password")
|
|
295
|
+
})
|
|
296
|
+
|
|
297
|
+
it("returns aal2 after TOTP verification", async () => {
|
|
298
|
+
const client = freshClient()
|
|
299
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse({ access_token: makeAal2Token() })))
|
|
300
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
301
|
+
|
|
302
|
+
// Mock getUser to return user with verified factor
|
|
303
|
+
vi.stubGlobal("fetch", mockFetch({
|
|
304
|
+
...RAW_USER,
|
|
305
|
+
factors: [{ id: FACTOR_ID, factor_type: "totp", status: "verified", created_at: "", updated_at: "" }],
|
|
306
|
+
}))
|
|
307
|
+
|
|
308
|
+
const { data } = await client.mfa.getAuthenticatorAssuranceLevel()
|
|
309
|
+
expect(data).not.toBeNull()
|
|
310
|
+
expect(data!.currentLevel).toBe("aal2")
|
|
311
|
+
expect(data!.currentAuthenticationMethods).toContain("password")
|
|
312
|
+
expect(data!.currentAuthenticationMethods).toContain("totp")
|
|
313
|
+
})
|
|
314
|
+
|
|
315
|
+
it("returns error when not authenticated", async () => {
|
|
316
|
+
const client = freshClient()
|
|
317
|
+
const { data, error } = await client.mfa.getAuthenticatorAssuranceLevel()
|
|
318
|
+
|
|
319
|
+
expect(data).toBeNull()
|
|
320
|
+
expect(error).not.toBeNull()
|
|
321
|
+
})
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
describe("Step 5 — Unenroll factor, back to single step", () => {
|
|
325
|
+
it("calls DELETE /factors/:id to unenroll", async () => {
|
|
326
|
+
const client = freshClient()
|
|
327
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse({ access_token: makeAal2Token() })))
|
|
328
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
329
|
+
|
|
330
|
+
const unenrollFetch = mockFetch({ id: FACTOR_ID })
|
|
331
|
+
vi.stubGlobal("fetch", unenrollFetch)
|
|
332
|
+
|
|
333
|
+
const { data, error } = await client.mfa.unenroll({ factorId: FACTOR_ID })
|
|
334
|
+
|
|
335
|
+
expect(error).toBeNull()
|
|
336
|
+
expect(data).not.toBeNull()
|
|
337
|
+
expect(data!.id).toBe(FACTOR_ID)
|
|
338
|
+
|
|
339
|
+
const [url, opts] = unenrollFetch.mock.calls[0] as [string, RequestInit]
|
|
340
|
+
expect(url).toBe(`${GOTRUE_URL}/factors/${FACTOR_ID}`)
|
|
341
|
+
expect(opts.method).toBe("DELETE")
|
|
342
|
+
})
|
|
343
|
+
|
|
344
|
+
it("after unenroll, listFactors returns empty", async () => {
|
|
345
|
+
const client = freshClient()
|
|
346
|
+
vi.stubGlobal("fetch", mockFetch(makeTokenResponse()))
|
|
347
|
+
await client.signInWithPassword({ email: "mfa@example.com", password: "pass" })
|
|
348
|
+
|
|
349
|
+
// Mock getUser returning no factors
|
|
350
|
+
vi.stubGlobal("fetch", mockFetch({ ...RAW_USER, factors: [] }))
|
|
351
|
+
|
|
352
|
+
const { data } = await client.mfa.listFactors()
|
|
353
|
+
expect(data).not.toBeNull()
|
|
354
|
+
expect(data!.totp).toHaveLength(0)
|
|
355
|
+
expect(data!.phone).toHaveLength(0)
|
|
356
|
+
expect(data!.all).toHaveLength(0)
|
|
357
|
+
})
|
|
358
|
+
})
|
|
359
|
+
})
|