@supatype/client 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +25 -22
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/dist/auth.d.ts +1 -1
  5. package/dist/auth.d.ts.map +1 -1
  6. package/dist/identity.d.ts +29 -0
  7. package/dist/identity.d.ts.map +1 -0
  8. package/dist/identity.js +30 -0
  9. package/dist/identity.js.map +1 -0
  10. package/dist/index.d.ts +15 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +25 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/query-cache.d.ts +1 -1
  15. package/dist/query-cache.d.ts.map +1 -1
  16. package/dist/query-cache.js +2 -8
  17. package/dist/query-cache.js.map +1 -1
  18. package/dist/query.d.ts +13 -1
  19. package/dist/query.d.ts.map +1 -1
  20. package/dist/query.js +18 -2
  21. package/dist/query.js.map +1 -1
  22. package/dist/realtime.d.ts +61 -3
  23. package/dist/realtime.d.ts.map +1 -1
  24. package/dist/realtime.js +162 -22
  25. package/dist/realtime.js.map +1 -1
  26. package/dist/storage.d.ts +12 -0
  27. package/dist/storage.d.ts.map +1 -1
  28. package/dist/storage.js +17 -1
  29. package/dist/storage.js.map +1 -1
  30. package/package.json +1 -1
  31. package/src/auth.ts +1 -1
  32. package/src/identity.ts +43 -0
  33. package/src/index.ts +42 -1
  34. package/src/query-cache.ts +3 -10
  35. package/src/query.ts +18 -2
  36. package/src/realtime.ts +166 -25
  37. package/src/storage.ts +17 -1
  38. package/tests/helpers/mock-websocket.ts +70 -0
  39. package/tests/identity-change.test.ts +120 -0
  40. package/tests/realtime-multi-tenant-integration.test.ts +5 -50
  41. package/tests/realtime-session-auth.test.ts +177 -0
  42. package/tests/signed-url-absolute.test.ts +84 -0
  43. package/tests/subscribe-frame.test.ts +102 -0
  44. package/tsconfig.tsbuildinfo +1 -1
@@ -7,58 +7,13 @@
7
7
 
8
8
  import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
9
9
  import { RealtimeClient, type RealtimePayload } from "../src/realtime.js"
10
+ import {
11
+ createMockWebSocketClass,
12
+ simulateServerMessage,
13
+ type MockWebSocketInstance,
14
+ } from "./helpers/mock-websocket.js"
10
15
 
11
- // ─── Mock WebSocket ──────────────────────────────────────────────────────────
12
-
13
- interface MockWebSocketInstance {
14
- url: string
15
- readyState: number
16
- onopen: ((event: Event) => void) | null
17
- onclose: ((event: CloseEvent) => void) | null
18
- onmessage: ((event: MessageEvent) => void) | null
19
- onerror: ((event: Event) => void) | null
20
- send: ReturnType<typeof vi.fn>
21
- close: ReturnType<typeof vi.fn>
22
- }
23
-
24
- function createMockWebSocketClass() {
25
- const instances: MockWebSocketInstance[] = []
26
-
27
- class MockWebSocket {
28
- static OPEN = 1
29
- static CONNECTING = 0
30
- static CLOSED = 3
31
-
32
- url: string
33
- readyState = 0
34
- onopen: ((event: Event) => void) | null = null
35
- onclose: ((event: CloseEvent) => void) | null = null
36
- onmessage: ((event: MessageEvent) => void) | null = null
37
- onerror: ((event: Event) => void) | null = null
38
- send = vi.fn()
39
- close = vi.fn()
40
-
41
- constructor(url: string) {
42
- this.url = url
43
- instances.push(this as unknown as MockWebSocketInstance)
44
-
45
- // Auto-open after a microtask
46
- queueMicrotask(() => {
47
- this.readyState = 1 // OPEN
48
- this.onopen?.({} as Event)
49
- })
50
- }
51
- }
52
-
53
- return { MockWebSocket, instances }
54
- }
55
-
56
- /** Simulate a server message arriving on a WebSocket instance. */
57
- function simulateServerMessage(ws: MockWebSocketInstance, msg: Record<string, unknown>): void {
58
- ws.onmessage?.({ data: JSON.stringify(msg) } as MessageEvent)
59
- }
60
16
 
61
- // ─── Tests ───────────────────────────────────────────────────────────────────
62
17
 
63
18
  describe("Task 94: Realtime multi-tenant isolation", () => {
64
19
  let MockWS: ReturnType<typeof createMockWebSocketClass>
@@ -0,0 +1,177 @@
1
+ /**
2
+ * The realtime socket authenticates as the signed-in user, not as anon.
3
+ *
4
+ * This is the defect these cover: `createClient` handed `RealtimeClient` the header bag built at
5
+ * construction, whose Authorization is the anon key and is never rewritten, and the socket then
6
+ * preferred `apikey` over Authorization anyway. Realtime enforces RLS, so on any table that is not
7
+ * anon-readable the socket reported SUBSCRIBED and delivered nothing at all. Proven against a live
8
+ * stack before it was fixed: two sockets, one insert, the anon socket saw 0 payloads and the
9
+ * signed-in socket saw 1.
10
+ *
11
+ * Every binding subscribes on mount, which is before sign-in, so the reconnect case below is the
12
+ * one that actually matters in an app.
13
+ */
14
+
15
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
16
+ import { RealtimeClient } from "../src/realtime.js"
17
+ import {
18
+ createMockWebSocketClass,
19
+ tokenOf,
20
+ type MockWebSocketInstance,
21
+ } from "./helpers/mock-websocket.js"
22
+ import { createClient } from "../src/index.js"
23
+ import type { Session } from "../src/types.js"
24
+
25
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
26
+
27
+ /** What a signed-in caller's headers look like: the bearer is the session, the apikey never is. */
28
+ function bearerHeaders(token: string): Record<string, string> {
29
+ return { apikey: "anon-key", Authorization: `Bearer ${token}` }
30
+ }
31
+
32
+ function fakeJwt(payload: Record<string, unknown>): string {
33
+ return `${btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))}.${btoa(JSON.stringify(payload))}.sig`
34
+ }
35
+
36
+ const ANON_KEY = fakeJwt({ role: "anon" })
37
+ const USER_TOKEN = fakeJwt({
38
+ role: "authenticated",
39
+ sub: "user-1",
40
+ exp: Math.floor(Date.now() / 1000) + 3600,
41
+ })
42
+
43
+ function session(accessToken: string): Session {
44
+ return {
45
+ accessToken,
46
+ tokenType: "bearer",
47
+ expiresIn: 3600,
48
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
49
+ refreshToken: "refresh-1",
50
+ user: {
51
+ id: "user-1",
52
+ email: "a@b.com",
53
+ role: "authenticated",
54
+ app_metadata: {},
55
+ user_metadata: {},
56
+ created_at: "2024-01-01T00:00:00Z",
57
+ updated_at: "2024-01-01T00:00:00Z",
58
+ },
59
+ } as Session
60
+ }
61
+
62
+ describe("realtime authenticates as the session, not as anon", () => {
63
+ let MockWS: ReturnType<typeof createMockWebSocketClass>
64
+
65
+ beforeEach(() => {
66
+ vi.restoreAllMocks()
67
+ MockWS = createMockWebSocketClass()
68
+ vi.stubGlobal("WebSocket", MockWS.MockWebSocket)
69
+ })
70
+
71
+ afterEach(() => {
72
+ vi.unstubAllGlobals()
73
+ })
74
+
75
+ it("prefers the Authorization bearer over apikey when given headers", async () => {
76
+ const client = new RealtimeClient("ws://localhost:4000/realtime", {
77
+ apikey: ANON_KEY,
78
+ Authorization: `Bearer ${USER_TOKEN}`,
79
+ })
80
+ client.channel("public:task").subscribe()
81
+ await settle()
82
+
83
+ expect(tokenOf(MockWS.instances[0]!)).toBe(USER_TOKEN)
84
+ })
85
+
86
+ it("falls back to apikey when there is no Authorization header", async () => {
87
+ const client = new RealtimeClient("ws://localhost:4000/realtime", { apikey: ANON_KEY })
88
+ client.channel("public:task").subscribe()
89
+ await settle()
90
+
91
+ expect(tokenOf(MockWS.instances[0]!)).toBe(ANON_KEY)
92
+ })
93
+
94
+ it("opens the socket with the token the provider returns at connect time", async () => {
95
+ let token = "first"
96
+ const client = new RealtimeClient("ws://localhost:4000/realtime", () => bearerHeaders(token))
97
+ client.channel("public:task").subscribe()
98
+ await settle()
99
+ expect(tokenOf(MockWS.instances[0]!)).toBe("first")
100
+
101
+ token = "second"
102
+ await client.reauthenticate()
103
+ await settle()
104
+
105
+ expect(MockWS.instances).toHaveLength(2)
106
+ expect(tokenOf(MockWS.instances[1]!)).toBe("second")
107
+ })
108
+
109
+ it("does not reconnect when the token has not changed", async () => {
110
+ const client = new RealtimeClient("ws://localhost:4000/realtime", () => bearerHeaders("same"))
111
+ client.channel("public:task").subscribe()
112
+ await settle()
113
+
114
+ await client.reauthenticate()
115
+ await settle()
116
+
117
+ expect(MockWS.instances).toHaveLength(1)
118
+ })
119
+
120
+ it("re-subscribes every channel on the replacement socket", async () => {
121
+ let token = "before"
122
+ const client = new RealtimeClient("ws://localhost:4000/realtime", () => bearerHeaders(token))
123
+ client.channel("public:task").subscribe()
124
+ await settle()
125
+
126
+ token = "after"
127
+ await client.reauthenticate()
128
+ await settle()
129
+
130
+ const replacement = MockWS.instances[1]!
131
+ const subscribes = replacement.send.mock.calls
132
+ .map(([raw]) => JSON.parse(String(raw)) as { type: string; channel: string })
133
+ .filter((m) => m.type === "subscribe")
134
+ expect(subscribes.map((m) => m.channel)).toContain("public:task")
135
+ })
136
+
137
+ it("reconnects when the identity changes while the first connect is still resolving its token", async () => {
138
+ // Not a hypothetical window. The provider `createClient` passes awaits `getAuthHeaders()`, which
139
+ // can make a session-refresh round trip, so any sign-in landing during one lands here. Every
140
+ // other test in this file uses a synchronous provider and never enters it.
141
+ let releaseFirst: (headers: Record<string, string>) => void = () => {}
142
+ const firstHeaders = new Promise<Record<string, string>>((resolve) => {
143
+ releaseFirst = resolve
144
+ })
145
+ let calls = 0
146
+ const client = new RealtimeClient("ws://localhost:4000/realtime", () => {
147
+ calls += 1
148
+ return calls === 1 ? firstHeaders : Promise.resolve(bearerHeaders("after-sign-in"))
149
+ })
150
+
151
+ client.channel("public:task").subscribe()
152
+ await Promise.resolve()
153
+
154
+ const reauthenticated = client.reauthenticate()
155
+ releaseFirst(bearerHeaders("before-sign-in"))
156
+ await reauthenticated
157
+ await settle()
158
+
159
+ // The socket must exist and must carry the new token. Abandoning the in-flight attempt without
160
+ // starting a replacement leaves the page connected to nothing, with no retry scheduled.
161
+ expect(MockWS.instances.length).toBeGreaterThan(0)
162
+ expect(tokenOf(MockWS.instances[MockWS.instances.length - 1]!)).toBe("after-sign-in")
163
+ })
164
+
165
+ it("createClient gives realtime the session token rather than the anon key", async () => {
166
+ const client = createClient({
167
+ url: "http://localhost:18473",
168
+ anonKey: ANON_KEY,
169
+ initialSession: session(USER_TOKEN),
170
+ })
171
+ client.realtime.channel("public:task").subscribe()
172
+ await settle()
173
+
174
+ // The whole bug in one assertion: this was ANON_KEY, and the socket then saw no rows.
175
+ expect(tokenOf(MockWS.instances[0]!)).toBe(USER_TOKEN)
176
+ })
177
+ })
@@ -0,0 +1,84 @@
1
+ /**
2
+ * A signed URL has to be a URL.
3
+ *
4
+ * `getPublicUrl` returns something fetchable; `createSignedUrl` used to return the storage API's
5
+ * response verbatim, and the API answers with a path (`/object/sign/<bucket>/<key>?token=…`). So
6
+ * one of the two URL methods returned a URL and the other returned half of one.
7
+ *
8
+ * The failure lands nowhere near the cause: the caller passes it to `fetch` and gets
9
+ * `TypeError: Failed to parse URL` with `ERR_INVALID_URL`, naming the path but not the method that
10
+ * produced it. Found by running the kitchen-sink example's own verification against a live stack,
11
+ * where it took out the whole private-bucket section after the signing itself had succeeded.
12
+ */
13
+
14
+ import { describe, it, expect, vi, beforeEach } from "vitest"
15
+ import { StorageClient } from "../src/storage.js"
16
+
17
+ const STORAGE_URL = "http://localhost:18473/storage/v1"
18
+ const HEADERS = { apikey: "test-anon-key", Authorization: "Bearer test-token" }
19
+ const RELATIVE = "/object/sign/ticket-files/verify/1.pdf?token=abc.def"
20
+
21
+ function client(url = STORAGE_URL): StorageClient {
22
+ return new StorageClient(url, () => Promise.resolve(HEADERS))
23
+ }
24
+
25
+ function respondWith(signedURL: string): void {
26
+ globalThis.fetch = vi.fn().mockResolvedValue({
27
+ ok: true,
28
+ status: 200,
29
+ json: () => Promise.resolve({ signedURL }),
30
+ }) as unknown as typeof fetch
31
+ }
32
+
33
+ beforeEach(() => {
34
+ vi.restoreAllMocks()
35
+ })
36
+
37
+ describe("createSignedUrl", () => {
38
+ it("returns a URL that can be parsed, not the server's path", async () => {
39
+ respondWith(RELATIVE)
40
+ const { data, error } = await client().from("ticket-files").createSignedUrl("verify/1.pdf", 60)
41
+
42
+ expect(error).toBeNull()
43
+ // The assertion that matters: `new URL` is what the caller's fetch does.
44
+ expect(() => new URL(data!.signedUrl)).not.toThrow()
45
+ expect(data!.signedUrl).toBe(`${STORAGE_URL}${RELATIVE}`)
46
+ })
47
+
48
+ it("keeps the token and path intact while making it absolute", async () => {
49
+ respondWith(RELATIVE)
50
+ const { data } = await client().from("ticket-files").createSignedUrl("verify/1.pdf", 60)
51
+ const parsed = new URL(data!.signedUrl)
52
+
53
+ expect(parsed.pathname).toBe("/storage/v1/object/sign/ticket-files/verify/1.pdf")
54
+ expect(parsed.searchParams.get("token")).toBe("abc.def")
55
+ })
56
+
57
+ it("passes an already-absolute answer through untouched", async () => {
58
+ // A deployment fronted by a CDN, or one signing straight to S3, answers with a full URL.
59
+ // Prefixing that a second time would produce a URL that parses and does not resolve.
60
+ const absolute = "https://cdn.example.com/signed/1.pdf?token=abc"
61
+ respondWith(absolute)
62
+ const { data } = await client().from("ticket-files").createSignedUrl("verify/1.pdf", 60)
63
+
64
+ expect(data!.signedUrl).toBe(absolute)
65
+ })
66
+
67
+ it("does not double the slash when the base URL has a trailing one", async () => {
68
+ respondWith(RELATIVE)
69
+ const { data } = await client(`${STORAGE_URL}/`).from("ticket-files").createSignedUrl("verify/1.pdf", 60)
70
+
71
+ expect(data!.signedUrl).toBe(`${STORAGE_URL}${RELATIVE}`)
72
+ expect(data!.signedUrl).not.toContain("v1//object")
73
+ })
74
+
75
+ it("is consistent with getPublicUrl, which was always absolute", async () => {
76
+ respondWith(RELATIVE)
77
+ const bucket = client().from("ticket-files")
78
+ const publicUrl = bucket.getPublicUrl("verify/1.pdf").data.publicUrl
79
+ const { data } = await bucket.createSignedUrl("verify/1.pdf", 60)
80
+
81
+ expect(() => new URL(publicUrl)).not.toThrow()
82
+ expect(new URL(data!.signedUrl).origin).toBe(new URL(publicUrl).origin)
83
+ })
84
+ })
@@ -0,0 +1,102 @@
1
+ /**
2
+ * What a subscribe frame tells the server.
3
+ *
4
+ * The listener resolved `table` and `schema` and then dropped them building the frame, so the
5
+ * server was left inferring the table from the channel name. That inference is right only when the
6
+ * channel is named after its table, which is what `from(table).subscribe()` produces; a channel
7
+ * named for its purpose matched nothing, and the socket reported SUBSCRIBED while delivering
8
+ * nothing at all.
9
+ *
10
+ * Asserted on the wire rather than through a round trip, because the wire is where the loss
11
+ * happened and a round trip against a fake server would only assert the fake.
12
+ */
13
+
14
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
15
+ import { RealtimeClient } from "../src/realtime.js"
16
+ import { createMockWebSocketClass, type MockWebSocketInstance } from "./helpers/mock-websocket.js"
17
+
18
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
19
+
20
+ let instances: MockWebSocketInstance[]
21
+ let originalWebSocket: typeof WebSocket
22
+
23
+ beforeEach(() => {
24
+ const mock = createMockWebSocketClass()
25
+ instances = mock.instances
26
+ originalWebSocket = globalThis.WebSocket
27
+ globalThis.WebSocket = mock.MockWebSocket
28
+ })
29
+
30
+ afterEach(() => {
31
+ globalThis.WebSocket = originalWebSocket
32
+ vi.restoreAllMocks()
33
+ })
34
+
35
+ /** Every subscribe frame the client put on the socket. */
36
+ function subscribeFrames(): Array<Record<string, unknown>> {
37
+ return instances
38
+ .flatMap((i) => i.send.mock.calls.map((c) => c[0] as string))
39
+ .map((raw) => JSON.parse(raw) as Record<string, unknown>)
40
+ .filter((m) => m["type"] === "subscribe")
41
+ }
42
+
43
+ describe("the subscribe frame", () => {
44
+ it("names the table when the channel does not", async () => {
45
+ const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
46
+ client
47
+ .channel("lobby-chat")
48
+ .on("postgres_changes", { event: "INSERT", table: "chat_message" }, () => {})
49
+ .subscribe()
50
+ await settle()
51
+
52
+ const frame = subscribeFrames()[0]
53
+ expect(frame).toBeDefined()
54
+ expect(frame!["channel"]).toBe("lobby-chat")
55
+ // The assertion the bug failed: without this the server reads "lobby-chat" as the table.
56
+ expect(frame!["table"]).toBe("chat_message")
57
+ expect(frame!["schema"]).toBe("public")
58
+ })
59
+
60
+ it("carries the event and filter alongside it", async () => {
61
+ const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
62
+ client
63
+ .channel("lobby-chat")
64
+ .on(
65
+ "postgres_changes",
66
+ { event: "INSERT", table: "chat_message", filter: "room=eq.lobby" },
67
+ () => {},
68
+ )
69
+ .subscribe()
70
+ await settle()
71
+
72
+ const frame = subscribeFrames()[0]!
73
+ expect(frame["event"]).toBe("INSERT")
74
+ expect(frame["filter"]).toEqual({ room: "eq.lobby" })
75
+ })
76
+
77
+ it("still names the table when the channel already matches it", async () => {
78
+ // `from(table).subscribe()` names the channel after the table. That worked by coincidence
79
+ // before; it should now be stated rather than inferred.
80
+ const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
81
+ client
82
+ .channel("chat_message")
83
+ .on("postgres_changes", { event: "*", table: "chat_message" }, () => {})
84
+ .subscribe()
85
+ await settle()
86
+
87
+ expect(subscribeFrames()[0]!["table"]).toBe("chat_message")
88
+ })
89
+
90
+ it("falls back to the channel's own table when no table is given", async () => {
91
+ // A channel written as `schema:table` still resolves, which is what the server's fallback
92
+ // reads too. Neither side should have to guess, but both agree when they do.
93
+ const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
94
+ client
95
+ .channel("app:orders")
96
+ .on("postgres_changes", { event: "*" }, () => {})
97
+ .subscribe()
98
+ await settle()
99
+
100
+ expect(subscribeFrames()[0]!["table"]).toBe("orders")
101
+ })
102
+ })