@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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +58 -31
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- 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 +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +153 -157
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +129 -37
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +84 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +421 -280
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +272 -201
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +122 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +139 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +139 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +3 -2
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pg_graphql types every json and jsonb column as its `JSON` scalar, which it serializes as a string.
|
|
3
|
+
* A rich text, blocks or json field therefore arrives as `"{\"root\":...}"`, and an app would have to
|
|
4
|
+
* know which fields to `JSON.parse`. The client knows instead: it reads the schema's field types once
|
|
5
|
+
* and decodes exactly the response keys whose field is a `JSON` scalar, following the query through
|
|
6
|
+
* aliases, fragments, nested relations and lists. A key it cannot place stays as returned.
|
|
7
|
+
*/
|
|
8
|
+
import { beforeEach, describe, expect, it, vi } from "vitest"
|
|
9
|
+
import { createClient, decodeGraphqlJsonFields, readGraphqlSchema } from "../src/index.js"
|
|
10
|
+
import { fetchCalls, jsonBody, jsonResponse, mockFetch, type FetchMock } from "./support/fetch-mock.js"
|
|
11
|
+
|
|
12
|
+
type TypeRef = { kind: string; name: string | null; ofType: TypeRef | null }
|
|
13
|
+
|
|
14
|
+
const named = (kind: string, name: string): TypeRef => ({ kind, name, ofType: null })
|
|
15
|
+
const nonNull = (type: TypeRef): TypeRef => ({ kind: "NON_NULL", name: null, ofType: type })
|
|
16
|
+
const list = (type: TypeRef): TypeRef => ({ kind: "LIST", name: null, ofType: type })
|
|
17
|
+
const object = (name: string): TypeRef => named("OBJECT", name)
|
|
18
|
+
const JSON_TYPE = named("SCALAR", "JSON")
|
|
19
|
+
const STRING = named("SCALAR", "String")
|
|
20
|
+
|
|
21
|
+
function objectType(name: string, fields: Record<string, TypeRef>, kind = "OBJECT"): Record<string, unknown> {
|
|
22
|
+
return { name, kind, fields: Object.entries(fields).map(([field, type]) => ({ name: field, type })) }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The shape pg_graphql gives a `talk` table with a `speaker` relation, trimmed to what the tests use. */
|
|
26
|
+
const INTROSPECTION = {
|
|
27
|
+
data: {
|
|
28
|
+
__schema: {
|
|
29
|
+
queryType: { name: "Query" },
|
|
30
|
+
mutationType: { name: "Mutation" },
|
|
31
|
+
types: [
|
|
32
|
+
objectType("Query", { talkCollection: object("TalkConnection"), node: named("INTERFACE", "Node") }),
|
|
33
|
+
objectType("Mutation", { insertIntoTalkCollection: object("TalkInsertResponse") }),
|
|
34
|
+
objectType("TalkInsertResponse", { records: nonNull(list(nonNull(object("Talk")))) }),
|
|
35
|
+
objectType("TalkConnection", { edges: nonNull(list(nonNull(object("TalkEdge")))) }),
|
|
36
|
+
objectType("TalkEdge", { node: nonNull(object("Talk")) }),
|
|
37
|
+
objectType("Talk", {
|
|
38
|
+
nodeId: nonNull(named("SCALAR", "ID")),
|
|
39
|
+
title: STRING,
|
|
40
|
+
abstract: JSON_TYPE,
|
|
41
|
+
body: JSON_TYPE,
|
|
42
|
+
tags: list(JSON_TYPE),
|
|
43
|
+
speaker: object("Speaker"),
|
|
44
|
+
}),
|
|
45
|
+
objectType("Speaker", { name: STRING, bio: JSON_TYPE, talkCollection: object("TalkConnection") }),
|
|
46
|
+
objectType("Node", { nodeId: nonNull(named("SCALAR", "ID")) }, "INTERFACE"),
|
|
47
|
+
{ name: "JSON", kind: "SCALAR", fields: null },
|
|
48
|
+
{ name: "String", kind: "SCALAR", fields: null },
|
|
49
|
+
],
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const ABSTRACT = { root: { type: "root", children: [{ type: "paragraph", children: [] }] } }
|
|
55
|
+
const BLOCKS = [{ type: "quote", data: { text: "Ship it" } }]
|
|
56
|
+
const BIO = { en: { root: { type: "root", children: [] } } }
|
|
57
|
+
const encoded = (value: unknown): string => JSON.stringify(value)
|
|
58
|
+
|
|
59
|
+
let introspect: () => Response
|
|
60
|
+
let answer: unknown
|
|
61
|
+
|
|
62
|
+
/** A GraphQL endpoint: the schema for an introspection query, `answer` for anything else. */
|
|
63
|
+
function serve(): FetchMock {
|
|
64
|
+
const fetch = mockFetch((_input, init) => {
|
|
65
|
+
const query = jsonBody(init ?? {})["query"]
|
|
66
|
+
const isIntrospection = typeof query === "string" && query.includes("__schema")
|
|
67
|
+
return Promise.resolve(isIntrospection ? introspect() : jsonResponse({ data: answer }))
|
|
68
|
+
})
|
|
69
|
+
vi.stubGlobal("fetch", fetch)
|
|
70
|
+
return fetch
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const client = () => createClient({ url: "http://api.test", anonKey: "anon", auth: { persistSession: false } })
|
|
74
|
+
|
|
75
|
+
beforeEach(() => {
|
|
76
|
+
vi.restoreAllMocks()
|
|
77
|
+
introspect = () => jsonResponse(INTROSPECTION)
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
describe("graphql: JSON scalar fields come back as values, not strings", () => {
|
|
81
|
+
it("decodes a rich text field", async () => {
|
|
82
|
+
serve()
|
|
83
|
+
answer = { talkCollection: { edges: [{ node: { title: "Keynote", abstract: encoded(ABSTRACT) } }] } }
|
|
84
|
+
const { data, error } = await client().graphql("{ talkCollection { edges { node { title abstract } } } }")
|
|
85
|
+
expect(error).toBeNull()
|
|
86
|
+
expect(data).toEqual({ talkCollection: { edges: [{ node: { title: "Keynote", abstract: ABSTRACT } }] } })
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it("follows an alias to the field it names, and leaves a text field aliased to a JSON field's name alone", async () => {
|
|
90
|
+
serve()
|
|
91
|
+
answer = { talkCollection: { edges: [{ node: { summary: encoded(ABSTRACT), abstract: "{\"looks\":\"like json\"}" } }] } }
|
|
92
|
+
const { data } = await client().graphql("{ talkCollection { edges { node { summary: abstract abstract: title } } } }")
|
|
93
|
+
expect(data).toEqual({ talkCollection: { edges: [{ node: { summary: ABSTRACT, abstract: "{\"looks\":\"like json\"}" } }] } })
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
it("decodes fields selected through a named fragment and an inline fragment on an interface", async () => {
|
|
97
|
+
serve()
|
|
98
|
+
answer = { node: { nodeId: "WyJ0YWxrIl0=", abstract: encoded(ABSTRACT), body: encoded(BLOCKS) } }
|
|
99
|
+
const query = `query Read($id: ID!) { node(nodeId: $id) { nodeId ...TalkBody ... on Talk { abstract } } }
|
|
100
|
+
fragment TalkBody on Talk { body }`
|
|
101
|
+
const { data } = await client().graphql(query, { id: "WyJ0YWxrIl0=" })
|
|
102
|
+
expect(data).toEqual({ node: { nodeId: "WyJ0YWxrIl0=", abstract: ABSTRACT, body: BLOCKS } })
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
it("decodes inside a nested relation's list, and every item of a list of JSON", async () => {
|
|
106
|
+
serve()
|
|
107
|
+
const talk = { abstract: encoded(ABSTRACT), tags: [encoded({ a: 1 }), encoded("plain")] }
|
|
108
|
+
answer = { talkCollection: { edges: [{ node: { speaker: { bio: encoded(BIO), talkCollection: { edges: [{ node: talk }] } } } }] } }
|
|
109
|
+
const query = "{ talkCollection { edges { node { speaker { bio talkCollection { edges { node { abstract tags } } } } } } } }"
|
|
110
|
+
const { data } = await client().graphql(query)
|
|
111
|
+
const inner = { edges: [{ node: { abstract: ABSTRACT, tags: [{ a: 1 }, "plain"] } }] }
|
|
112
|
+
expect(data).toEqual({ talkCollection: { edges: [{ node: { speaker: { bio: BIO, talkCollection: inner } } }] } })
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it("decodes the records a mutation returns", async () => {
|
|
116
|
+
serve()
|
|
117
|
+
answer = { insertIntoTalkCollection: { records: [{ abstract: encoded(ABSTRACT) }] } }
|
|
118
|
+
const { data } = await client().graphql("mutation { insertIntoTalkCollection(objects: [{title: \"a } b\"}]) { records { abstract } } }")
|
|
119
|
+
expect(data).toEqual({ insertIntoTalkCollection: { records: [{ abstract: ABSTRACT }] } })
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
it("reads past comments, block strings, arguments and directives", async () => {
|
|
123
|
+
serve()
|
|
124
|
+
answer = { talkCollection: { edges: [{ node: { abstract: encoded(ABSTRACT) } }] } }
|
|
125
|
+
const query = `# a comment { with a brace
|
|
126
|
+
query ($skip: Boolean = false) {
|
|
127
|
+
talkCollection(filter: { title: { eq: """a } "quoted" { b""" } }) @cached {
|
|
128
|
+
edges { node { abstract @skip(if: $skip) } }
|
|
129
|
+
}
|
|
130
|
+
}`
|
|
131
|
+
const { data } = await client().graphql(query)
|
|
132
|
+
expect(data).toEqual({ talkCollection: { edges: [{ node: { abstract: ABSTRACT } }] } })
|
|
133
|
+
})
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
describe("graphql: a field the client cannot place stays as returned", () => {
|
|
137
|
+
it("leaves the answer alone when the schema cannot be read", async () => {
|
|
138
|
+
serve()
|
|
139
|
+
introspect = () => jsonResponse({ message: "introspection is off" }, 403)
|
|
140
|
+
answer = { talkCollection: { edges: [{ node: { abstract: encoded(ABSTRACT) } }] } }
|
|
141
|
+
const { data, error } = await client().graphql("{ talkCollection { edges { node { abstract } } } }")
|
|
142
|
+
expect(error).toBeNull()
|
|
143
|
+
expect(data).toEqual(answer)
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
it("leaves a field the schema does not have, and reads the schema again on the next call", async () => {
|
|
147
|
+
const fetch = serve()
|
|
148
|
+
answer = { talkCollection: { edges: [{ node: { addedSincePush: encoded({ a: 1 }) } }] } }
|
|
149
|
+
const c = client()
|
|
150
|
+
const { data } = await c.graphql("{ talkCollection { edges { node { addedSincePush } } } }")
|
|
151
|
+
expect(data).toEqual(answer)
|
|
152
|
+
await c.graphql("{ talkCollection { edges { node { addedSincePush } } } }")
|
|
153
|
+
expect(introspections(fetch)).toBe(2)
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
it("leaves a document with more than one operation, since the server picks which runs", async () => {
|
|
157
|
+
serve()
|
|
158
|
+
answer = { talkCollection: { edges: [{ node: { abstract: encoded(ABSTRACT) } }] } }
|
|
159
|
+
const { data } = await client().graphql("query A { talkCollection { edges { node { abstract } } } } query B { __typename }")
|
|
160
|
+
expect(data).toEqual(answer)
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
it("leaves a string that is not JSON", () => {
|
|
164
|
+
const schema = readGraphqlSchema(INTROSPECTION.data)
|
|
165
|
+
if (schema === null) throw new Error("the fixture schema did not read")
|
|
166
|
+
const raw = { talkCollection: { edges: [{ node: { abstract: "not json" } }] } }
|
|
167
|
+
const decoded = decodeGraphqlJsonFields("{ talkCollection { edges { node { abstract } } } }", raw, schema)
|
|
168
|
+
expect(decoded).toEqual({ data: raw, schemaIsStale: false })
|
|
169
|
+
})
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
describe("graphql: the schema is read once, after the query", () => {
|
|
173
|
+
it("sends the query first and introspects once across calls", async () => {
|
|
174
|
+
const fetch = serve()
|
|
175
|
+
answer = { talkCollection: { edges: [{ node: { abstract: encoded(ABSTRACT) } }] } }
|
|
176
|
+
const c = client()
|
|
177
|
+
await c.graphql("{ talkCollection { edges { node { abstract } } } }")
|
|
178
|
+
await c.graphql("{ talkCollection { edges { node { abstract } } } }")
|
|
179
|
+
expect(introspections(fetch)).toBe(1)
|
|
180
|
+
expect(queryOf(fetch, 0)).not.toContain("__schema")
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
it("does not introspect for an answer with no strings in it", async () => {
|
|
184
|
+
const fetch = serve()
|
|
185
|
+
answer = { talkCollection: { edges: [] } }
|
|
186
|
+
await client().graphql("{ talkCollection { edges { node { abstract } } } }")
|
|
187
|
+
expect(introspections(fetch)).toBe(0)
|
|
188
|
+
})
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
function queryOf(fetch: FetchMock, n: number): string {
|
|
192
|
+
const call = fetchCalls(fetch)[n]
|
|
193
|
+
const query = call === undefined ? undefined : jsonBody(call.init)["query"]
|
|
194
|
+
return typeof query === "string" ? query : ""
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function introspections(fetch: FetchMock): number {
|
|
198
|
+
return fetchCalls(fetch).filter((_, n) => queryOf(fetch, n).includes("__schema")).length
|
|
199
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { vi } from "vitest"
|
|
1
|
+
import { vi, type Mock } from "vitest"
|
|
2
|
+
import { isJsonObject } from "../../src/json.js"
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* A stand-in WebSocket for the realtime suites.
|
|
@@ -17,17 +18,26 @@ export interface MockWebSocketInstance {
|
|
|
17
18
|
onclose: ((event: CloseEvent) => void) | null
|
|
18
19
|
onmessage: ((event: MessageEvent) => void) | null
|
|
19
20
|
onerror: ((event: Event) => void) | null
|
|
20
|
-
|
|
21
|
-
|
|
21
|
+
/** The client only ever sends JSON text. */
|
|
22
|
+
send: Mock<(data: string) => void>
|
|
23
|
+
close: Mock<() => void>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** What the realtime client uses of the WebSocket constructor: `new` and the ready states. */
|
|
27
|
+
export interface MockWebSocketClass {
|
|
28
|
+
new (url: string): MockWebSocketInstance
|
|
29
|
+
readonly OPEN: number
|
|
30
|
+
readonly CONNECTING: number
|
|
31
|
+
readonly CLOSED: number
|
|
22
32
|
}
|
|
23
33
|
|
|
24
34
|
export function createMockWebSocketClass(): {
|
|
25
|
-
MockWebSocket:
|
|
35
|
+
MockWebSocket: MockWebSocketClass
|
|
26
36
|
instances: MockWebSocketInstance[]
|
|
27
37
|
} {
|
|
28
38
|
const instances: MockWebSocketInstance[] = []
|
|
29
39
|
|
|
30
|
-
class MockWebSocket {
|
|
40
|
+
class MockWebSocket implements MockWebSocketInstance {
|
|
31
41
|
static OPEN = 1
|
|
32
42
|
static CONNECTING = 0
|
|
33
43
|
static CLOSED = 3
|
|
@@ -38,22 +48,22 @@ export function createMockWebSocketClass(): {
|
|
|
38
48
|
onclose: ((event: CloseEvent) => void) | null = null
|
|
39
49
|
onmessage: ((event: MessageEvent) => void) | null = null
|
|
40
50
|
onerror: ((event: Event) => void) | null = null
|
|
41
|
-
send = vi.fn()
|
|
42
|
-
close = vi.fn()
|
|
51
|
+
send = vi.fn<(data: string) => void>()
|
|
52
|
+
close = vi.fn<() => void>()
|
|
43
53
|
|
|
44
54
|
constructor(url: string) {
|
|
45
55
|
this.url = url
|
|
46
|
-
instances.push(this
|
|
56
|
+
instances.push(this)
|
|
47
57
|
|
|
48
58
|
// Auto-open after a microtask
|
|
49
59
|
queueMicrotask(() => {
|
|
50
60
|
this.readyState = 1 // OPEN
|
|
51
|
-
this.onopen?.(
|
|
61
|
+
this.onopen?.(new Event("open"))
|
|
52
62
|
})
|
|
53
63
|
}
|
|
54
64
|
}
|
|
55
65
|
|
|
56
|
-
return { MockWebSocket
|
|
66
|
+
return { MockWebSocket, instances }
|
|
57
67
|
}
|
|
58
68
|
|
|
59
69
|
/** Simulate a server message arriving on a WebSocket instance. */
|
|
@@ -61,10 +71,33 @@ export function simulateServerMessage(
|
|
|
61
71
|
ws: MockWebSocketInstance,
|
|
62
72
|
msg: Record<string, unknown>,
|
|
63
73
|
): void {
|
|
64
|
-
ws.onmessage?.({ data: JSON.stringify(msg) }
|
|
74
|
+
ws.onmessage?.(new MessageEvent("message", { data: JSON.stringify(msg) }))
|
|
65
75
|
}
|
|
66
76
|
|
|
67
77
|
/** The token a socket was opened with, read back out of its URL. */
|
|
68
78
|
export function tokenOf(ws: MockWebSocketInstance): string | null {
|
|
69
79
|
return new URL(ws.url.replace(/^ws/, "http")).searchParams.get("token")
|
|
70
80
|
}
|
|
81
|
+
|
|
82
|
+
/** Every frame the client sent on a socket, parsed. A frame that is not a JSON object fails the test. */
|
|
83
|
+
export function sentFrames(ws: MockWebSocketInstance): Array<Record<string, unknown>> {
|
|
84
|
+
return ws.send.mock.calls.map(([raw]) => {
|
|
85
|
+
const frame = JSON.parse(raw)
|
|
86
|
+
if (!isJsonObject(frame)) throw new Error(`the client sent a frame that is not a JSON object: ${raw}`)
|
|
87
|
+
return frame
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The channels a socket was asked to join, in the order the subscribe frames went out. */
|
|
92
|
+
export function subscribedChannels(ws: MockWebSocketInstance): string[] {
|
|
93
|
+
return sentFrames(ws)
|
|
94
|
+
.filter((frame) => frame["type"] === "subscribe")
|
|
95
|
+
.map(channelOf)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The channel a frame names. Fails the test when it names none. */
|
|
99
|
+
export function channelOf(frame: Record<string, unknown> | undefined): string {
|
|
100
|
+
const channel = frame?.["channel"]
|
|
101
|
+
if (typeof channel !== "string") throw new Error(`the frame names no channel: ${JSON.stringify(frame)}`)
|
|
102
|
+
return channel
|
|
103
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"
|
|
2
|
+
import type { AuthRedirectError, Session, SupatypeError } from "../../src/types.js"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What every framework binding's auth primitive owes an OAuth sign-in.
|
|
6
|
+
*
|
|
7
|
+
* Shared by the Vue, Svelte and Solid suites, because each must start the redirect and surface the
|
|
8
|
+
* server's refusal the same way; a copy per binding would let one drift. Not named `*.test.ts`, so
|
|
9
|
+
* vitest's default include does not collect it as a suite.
|
|
10
|
+
*/
|
|
11
|
+
type OAuthResult = { data: { url: string; provider: string }; error: SupatypeError | null }
|
|
12
|
+
|
|
13
|
+
export interface OAuthBindingHarness {
|
|
14
|
+
auth: {
|
|
15
|
+
initialize: () => Promise<{ error: AuthRedirectError | null }>
|
|
16
|
+
getSession: () => Promise<{ data: { session: Session | null }; error: null }>
|
|
17
|
+
onAuthStateChange: () => { data: { subscription: { unsubscribe(): void } } }
|
|
18
|
+
signInWithOAuth: ReturnType<typeof vi.fn<(opts: { provider: string }) => Promise<OAuthResult>>>
|
|
19
|
+
}
|
|
20
|
+
/** The refusal the next mount's `initialize()` reports. */
|
|
21
|
+
redirectError: AuthRedirectError | null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface OAuthBindingProbe {
|
|
25
|
+
error(): AuthRedirectError | null | undefined
|
|
26
|
+
signInWithOAuth(provider: string): Promise<{ error: SupatypeError | null }>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function createHarness(): OAuthBindingHarness {
|
|
30
|
+
const harness: OAuthBindingHarness = {
|
|
31
|
+
redirectError: null,
|
|
32
|
+
auth: {
|
|
33
|
+
initialize: () => Promise.resolve({ error: harness.redirectError }),
|
|
34
|
+
getSession: () => Promise.resolve({ data: { session: null }, error: null }),
|
|
35
|
+
onAuthStateChange: () => ({ data: { subscription: { unsubscribe: () => undefined } } }),
|
|
36
|
+
signInWithOAuth: vi.fn<(opts: { provider: string }) => Promise<OAuthResult>>(),
|
|
37
|
+
},
|
|
38
|
+
}
|
|
39
|
+
return harness
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
|
|
43
|
+
|
|
44
|
+
export function describeOAuthBinding(
|
|
45
|
+
name: string,
|
|
46
|
+
mount: (harness: OAuthBindingHarness) => OAuthBindingProbe,
|
|
47
|
+
unmount: () => void,
|
|
48
|
+
): void {
|
|
49
|
+
describe(`${name} OAuth`, () => {
|
|
50
|
+
let harness: OAuthBindingHarness
|
|
51
|
+
let assign: ReturnType<typeof vi.fn<(url: string) => void>>
|
|
52
|
+
|
|
53
|
+
beforeEach(() => {
|
|
54
|
+
harness = createHarness()
|
|
55
|
+
assign = vi.fn<(url: string) => void>()
|
|
56
|
+
vi.stubGlobal("window", { location: { href: "https://app.example/", assign } })
|
|
57
|
+
})
|
|
58
|
+
afterEach(() => {
|
|
59
|
+
unmount()
|
|
60
|
+
vi.unstubAllGlobals()
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it("sends the browser to the provider", async () => {
|
|
64
|
+
const url = "http://localhost:9999/auth/v1/authorize?provider=github"
|
|
65
|
+
harness.auth.signInWithOAuth.mockResolvedValue({ data: { url, provider: "github" }, error: null })
|
|
66
|
+
|
|
67
|
+
const { error } = await mount(harness).signInWithOAuth("github")
|
|
68
|
+
|
|
69
|
+
expect(error).toBeNull()
|
|
70
|
+
expect(assign).toHaveBeenCalledWith(url)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it("stays on the page and returns the error when the provider is not enabled", async () => {
|
|
74
|
+
const refusal = { message: "Sign-in with github is not enabled for this project.", code: "provider_disabled" }
|
|
75
|
+
harness.auth.signInWithOAuth.mockResolvedValue({ data: { url: "", provider: "github" }, error: refusal })
|
|
76
|
+
|
|
77
|
+
const { error } = await mount(harness).signInWithOAuth("github")
|
|
78
|
+
|
|
79
|
+
expect(error).toEqual(refusal)
|
|
80
|
+
expect(assign).not.toHaveBeenCalled()
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it("exposes a refusal the server sent back in the URL", async () => {
|
|
84
|
+
harness.redirectError = { message: "Signups not allowed", code: "signup_disabled", provider: "github" }
|
|
85
|
+
|
|
86
|
+
const probe = mount(harness)
|
|
87
|
+
await settle()
|
|
88
|
+
|
|
89
|
+
expect(probe.error()).toEqual(harness.redirectError)
|
|
90
|
+
})
|
|
91
|
+
})
|
|
92
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"
|
|
2
|
+
import { AuthClient } from "../../src/auth.js"
|
|
3
|
+
import type { Session, SupatypeError, User } from "../../src/types.js"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What every framework binding's auth primitive owes a sign-up that waits for email confirmation.
|
|
7
|
+
*
|
|
8
|
+
* The auth server answers such a sign-up with the bare user and no tokens. The binding must stay
|
|
9
|
+
* signed out and hand the caller what it needs to say "check your email". Shared by the Vue,
|
|
10
|
+
* Svelte and Solid suites over a real AuthClient, so the client's answer is what is under test.
|
|
11
|
+
* Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
|
|
12
|
+
*/
|
|
13
|
+
export type SignUpBindingResult = {
|
|
14
|
+
data: { session: Session | null; user: User | null }
|
|
15
|
+
error: SupatypeError | null
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SignUpBindingProbe {
|
|
19
|
+
user(): User | null | undefined
|
|
20
|
+
signUp(email: string, password: string): Promise<SignUpBindingResult>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const PENDING_USER = {
|
|
24
|
+
id: "user-pending",
|
|
25
|
+
email: "ada@example.com",
|
|
26
|
+
confirmation_sent_at: "2024-01-01T00:00:00Z",
|
|
27
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
28
|
+
updated_at: "2024-01-01T00:00:00Z",
|
|
29
|
+
app_metadata: { provider: "email" },
|
|
30
|
+
user_metadata: {},
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
|
|
34
|
+
|
|
35
|
+
export function describeSignUpBinding(
|
|
36
|
+
name: string,
|
|
37
|
+
mount: (auth: AuthClient) => SignUpBindingProbe,
|
|
38
|
+
unmount: () => void,
|
|
39
|
+
): void {
|
|
40
|
+
describe(`${name} sign-up waiting for email confirmation`, () => {
|
|
41
|
+
let probe: SignUpBindingProbe
|
|
42
|
+
|
|
43
|
+
beforeEach(async () => {
|
|
44
|
+
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
|
|
45
|
+
ok: true,
|
|
46
|
+
status: 200,
|
|
47
|
+
json: () => Promise.resolve(PENDING_USER),
|
|
48
|
+
headers: { get: () => null },
|
|
49
|
+
}))
|
|
50
|
+
probe = mount(new AuthClient("http://localhost:9999/auth/v1", { apikey: "anon" }))
|
|
51
|
+
await settle()
|
|
52
|
+
})
|
|
53
|
+
afterEach(() => {
|
|
54
|
+
unmount()
|
|
55
|
+
vi.unstubAllGlobals()
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it("stays signed out", async () => {
|
|
59
|
+
await probe.signUp("ada@example.com", "secret")
|
|
60
|
+
await settle()
|
|
61
|
+
|
|
62
|
+
expect(probe.user()).toBeNull()
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it("returns the user and no session, so the app can ask for the confirmation", async () => {
|
|
66
|
+
const { data, error } = await probe.signUp("ada@example.com", "secret")
|
|
67
|
+
|
|
68
|
+
expect(error).toBeNull()
|
|
69
|
+
expect(data.session).toBeNull()
|
|
70
|
+
expect(data.user?.id).toBe("user-pending")
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"
|
|
2
|
+
import { RealtimeClient } from "../../src/realtime.js"
|
|
3
|
+
import {
|
|
4
|
+
createMockWebSocketClass,
|
|
5
|
+
simulateServerMessage,
|
|
6
|
+
subscribedChannels,
|
|
7
|
+
type MockWebSocketInstance,
|
|
8
|
+
} from "./mock-websocket.js"
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A realtime client on a stand-in socket, with the sign-in that swaps that socket for a new one.
|
|
12
|
+
*
|
|
13
|
+
* Shared by the client's suite and by every framework binding's, because each binding must show
|
|
14
|
+
* the same status sequence across the same swap. A copy per binding would let one of them drift
|
|
15
|
+
* into testing a socket that no longer behaves like the client's.
|
|
16
|
+
*
|
|
17
|
+
* Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
|
|
18
|
+
*/
|
|
19
|
+
export interface SocketSwapHarness {
|
|
20
|
+
realtime: RealtimeClient
|
|
21
|
+
/** Every socket opened so far, oldest first. */
|
|
22
|
+
sockets: MockWebSocketInstance[]
|
|
23
|
+
/** Let queued connects and opens run. */
|
|
24
|
+
settle(): Promise<void>
|
|
25
|
+
/** The server acknowledges every join sent on the newest socket. */
|
|
26
|
+
ackJoins(): void
|
|
27
|
+
/** The server refuses a join on the newest socket. */
|
|
28
|
+
refuseJoin(): void
|
|
29
|
+
/** Change identity, which replaces the socket, and let the replacement open. */
|
|
30
|
+
signIn(): Promise<void>
|
|
31
|
+
/** Put the real WebSocket back. */
|
|
32
|
+
restore(): void
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function newestOf(sockets: MockWebSocketInstance[]): MockWebSocketInstance {
|
|
36
|
+
const socket = sockets[sockets.length - 1]
|
|
37
|
+
if (socket === undefined) throw new Error("no socket has been opened")
|
|
38
|
+
return socket
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function createSocketSwapHarness(): SocketSwapHarness {
|
|
42
|
+
const mock = createMockWebSocketClass()
|
|
43
|
+
vi.stubGlobal("WebSocket", mock.MockWebSocket)
|
|
44
|
+
let token = "anon"
|
|
45
|
+
const realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: `Bearer ${token}` }))
|
|
46
|
+
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
47
|
+
const reply = (status: "ok" | "error", message: string): void =>
|
|
48
|
+
simulateServerMessage(newestOf(mock.instances), { type: "system", status, message })
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
realtime,
|
|
52
|
+
sockets: mock.instances,
|
|
53
|
+
settle,
|
|
54
|
+
ackJoins: () => {
|
|
55
|
+
for (const channel of subscribedChannels(newestOf(mock.instances))) reply("ok", `subscribed to ${channel}`)
|
|
56
|
+
},
|
|
57
|
+
refuseJoin: () => reply("error", "permission denied"),
|
|
58
|
+
signIn: async () => {
|
|
59
|
+
token = "user"
|
|
60
|
+
await realtime.reauthenticate()
|
|
61
|
+
await settle()
|
|
62
|
+
},
|
|
63
|
+
restore: () => vi.unstubAllGlobals(),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The status a subscription shows at each point of a sign-in: subscribed, joined, swapped, and
|
|
69
|
+
* then joined again on the new socket, or refused there.
|
|
70
|
+
*
|
|
71
|
+
* `read` is whatever the subject under test exposes, read as it stands at that moment.
|
|
72
|
+
*/
|
|
73
|
+
export async function statusesAcrossSwap(
|
|
74
|
+
harness: SocketSwapHarness,
|
|
75
|
+
read: () => string,
|
|
76
|
+
{ refuse = false }: { refuse?: boolean } = {},
|
|
77
|
+
): Promise<string[]> {
|
|
78
|
+
const seen: string[] = []
|
|
79
|
+
await harness.settle()
|
|
80
|
+
seen.push(read())
|
|
81
|
+
harness.ackJoins()
|
|
82
|
+
seen.push(read())
|
|
83
|
+
await harness.signIn()
|
|
84
|
+
seen.push(read())
|
|
85
|
+
if (refuse) harness.refuseJoin()
|
|
86
|
+
else harness.ackJoins()
|
|
87
|
+
seen.push(read())
|
|
88
|
+
return seen
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** What a binding under test exposes, read as it stands. */
|
|
92
|
+
export interface StatusProbe {
|
|
93
|
+
status(): string
|
|
94
|
+
/** The error it exposes, when it exposes one. */
|
|
95
|
+
error?(): unknown
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What the Vue, Svelte and Solid bindings read at each point of `statusesAcrossSwap`. */
|
|
99
|
+
export const BINDING_STATES = {
|
|
100
|
+
swap: ["connecting", "connected", "connecting", "connected"],
|
|
101
|
+
refused: ["connecting", "connected", "connecting", "error"],
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The two cases every binding's suite asserts, written once.
|
|
106
|
+
*
|
|
107
|
+
* `mount` starts the subscription against the harness it is given. `unmount` runs the cleanup the
|
|
108
|
+
* binding registered. The framework mocks stay in each suite, because `vi.mock` is hoisted per file.
|
|
109
|
+
*/
|
|
110
|
+
export function describeStatusAcrossSignIn(
|
|
111
|
+
subject: string,
|
|
112
|
+
mount: (harness: SocketSwapHarness) => StatusProbe,
|
|
113
|
+
unmount: () => void,
|
|
114
|
+
expected: { swap: string[]; refused: string[] } = BINDING_STATES,
|
|
115
|
+
): void {
|
|
116
|
+
describe(`${subject} status across sign-in`, () => {
|
|
117
|
+
let harness: SocketSwapHarness
|
|
118
|
+
|
|
119
|
+
beforeEach(() => {
|
|
120
|
+
harness = createSocketSwapHarness()
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
afterEach(() => {
|
|
124
|
+
unmount()
|
|
125
|
+
harness.restore()
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
it("reads connecting from the swap until the new socket acknowledges the join", async () => {
|
|
129
|
+
const probe = mount(harness)
|
|
130
|
+
expect(await statusesAcrossSwap(harness, probe.status)).toEqual(expected.swap)
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it("reads error when the new socket refuses the join", async () => {
|
|
134
|
+
const probe = mount(harness)
|
|
135
|
+
expect(await statusesAcrossSwap(harness, probe.status, { refuse: true })).toEqual(expected.refused)
|
|
136
|
+
if (probe.error) expect(probe.error()).not.toBeNull()
|
|
137
|
+
})
|
|
138
|
+
})
|
|
139
|
+
}
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
9
9
|
import { AuthClient } from "../src/auth.js"
|
|
10
|
+
import { fetchCall, fetchReturning, jsonBody, type FetchMock } from "./support/fetch-mock.js"
|
|
10
11
|
|
|
11
12
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
12
13
|
|
|
@@ -59,13 +60,8 @@ function makeTokenResponse(overrides?: Record<string, unknown>) {
|
|
|
59
60
|
}
|
|
60
61
|
}
|
|
61
62
|
|
|
62
|
-
function mockFetch(body: unknown, ok = true, status?: number):
|
|
63
|
-
return
|
|
64
|
-
ok,
|
|
65
|
-
status: status ?? (ok ? 200 : 400),
|
|
66
|
-
json: vi.fn().mockResolvedValue(body),
|
|
67
|
-
headers: { get: () => null },
|
|
68
|
-
})
|
|
63
|
+
function mockFetch(body: unknown, ok = true, status?: number): FetchMock {
|
|
64
|
+
return fetchReturning(body, status ?? (ok ? 200 : 400))
|
|
69
65
|
}
|
|
70
66
|
|
|
71
67
|
function freshClient(): AuthClient {
|
|
@@ -110,11 +106,10 @@ describe("Task 89: MFA TOTP integration", () => {
|
|
|
110
106
|
expect(data!.type).toBe("totp")
|
|
111
107
|
|
|
112
108
|
// Verify POST was sent to /factors
|
|
113
|
-
const
|
|
109
|
+
const { url, init } = fetchCall(enrollFetch)
|
|
114
110
|
expect(url).toBe(`${SUPATYPE_URL}/factors`)
|
|
115
|
-
expect(
|
|
116
|
-
|
|
117
|
-
expect(body["factor_type"]).toBe("totp")
|
|
111
|
+
expect(init.method).toBe("POST")
|
|
112
|
+
expect(jsonBody(init)["factor_type"]).toBe("totp")
|
|
118
113
|
})
|
|
119
114
|
|
|
120
115
|
it("returns QR code and secret for TOTP enrollment", async () => {
|
|
@@ -243,8 +238,8 @@ describe("Task 89: MFA TOTP integration", () => {
|
|
|
243
238
|
expect(data.session).not.toBeNull()
|
|
244
239
|
// Decode JWT to check AAL
|
|
245
240
|
const parts = data.session!.accessToken.split(".")
|
|
246
|
-
const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString())
|
|
247
|
-
expect(payload
|
|
241
|
+
const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString())
|
|
242
|
+
expect(payload).toHaveProperty("aal", "aal1")
|
|
248
243
|
})
|
|
249
244
|
|
|
250
245
|
it("second step: TOTP verification elevates to AAL2", async () => {
|
|
@@ -271,11 +266,9 @@ describe("Task 89: MFA TOTP integration", () => {
|
|
|
271
266
|
|
|
272
267
|
expect(data.session).not.toBeNull()
|
|
273
268
|
const parts = data.session!.accessToken.split(".")
|
|
274
|
-
const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString())
|
|
275
|
-
expect(payload
|
|
276
|
-
expect(payload
|
|
277
|
-
expect.arrayContaining([{ method: "password" }, { method: "totp" }]),
|
|
278
|
-
)
|
|
269
|
+
const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString())
|
|
270
|
+
expect(payload).toHaveProperty("aal", "aal2")
|
|
271
|
+
expect(payload).toHaveProperty("amr", expect.arrayContaining([{ method: "password" }, { method: "totp" }]))
|
|
279
272
|
})
|
|
280
273
|
})
|
|
281
274
|
|
|
@@ -336,9 +329,9 @@ describe("Task 89: MFA TOTP integration", () => {
|
|
|
336
329
|
expect(data).not.toBeNull()
|
|
337
330
|
expect(data!.id).toBe(FACTOR_ID)
|
|
338
331
|
|
|
339
|
-
const
|
|
332
|
+
const { url, init } = fetchCall(unenrollFetch)
|
|
340
333
|
expect(url).toBe(`${SUPATYPE_URL}/factors/${FACTOR_ID}`)
|
|
341
|
-
expect(
|
|
334
|
+
expect(init.method).toBe("DELETE")
|
|
342
335
|
})
|
|
343
336
|
|
|
344
337
|
it("after unenroll, listFactors returns empty", async () => {
|