@supatype/client 0.3.0 → 0.3.2
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 +28 -21
- package/.turbo/turbo-typecheck.log +2 -2
- package/dist/auth.d.ts +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/exact-response.d.ts +26 -0
- package/dist/exact-response.d.ts.map +1 -0
- package/dist/exact-response.js +51 -0
- package/dist/exact-response.js.map +1 -0
- package/dist/exact-values.d.ts +50 -0
- package/dist/exact-values.d.ts.map +1 -0
- package/dist/exact-values.js +254 -0
- package/dist/exact-values.js.map +1 -0
- package/dist/field-kinds-registry.d.ts +46 -0
- package/dist/field-kinds-registry.d.ts.map +1 -0
- package/dist/field-kinds-registry.js +51 -0
- package/dist/field-kinds-registry.js.map +1 -0
- package/dist/identity.d.ts +29 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +30 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +17 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +29 -1
- package/dist/index.js.map +1 -1
- package/dist/query-cache.d.ts +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +2 -8
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +13 -1
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +36 -7
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +61 -3
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +181 -24
- package/dist/realtime.js.map +1 -1
- package/dist/storage.d.ts +12 -0
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +17 -1
- package/dist/storage.js.map +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/src/auth.ts +1 -1
- package/src/exact-response.ts +76 -0
- package/src/exact-values.ts +281 -0
- package/src/field-kinds-registry.ts +80 -0
- package/src/identity.ts +43 -0
- package/src/index.ts +54 -1
- package/src/query-cache.ts +3 -10
- package/src/query.ts +41 -7
- package/src/realtime.ts +195 -27
- package/src/storage.ts +17 -1
- package/src/types.ts +28 -0
- package/tests/data-plane-auth.test.ts +6 -4
- package/tests/draft-profile.test.ts +3 -0
- package/tests/exact-response.test.ts +95 -0
- package/tests/exact-values.test.ts +171 -0
- package/tests/field-kinds-registry.test.ts +80 -0
- package/tests/fixtures/models.ts +55 -0
- package/tests/helpers/mock-websocket.ts +70 -0
- package/tests/identity-change.test.ts +120 -0
- package/tests/query-cache.test.ts +14 -8
- package/tests/query.test.ts +1 -0
- package/tests/realtime-exact-values.test.ts +161 -0
- package/tests/realtime-multi-tenant-integration.test.ts +5 -50
- package/tests/realtime-session-auth.test.ts +177 -0
- package/tests/signed-url-absolute.test.ts +84 -0
- package/tests/subscribe-frame.test.ts +102 -0
- package/tests/tsconfig.json +9 -0
- package/tests/types.test.ts +40 -32
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The same row, read two ways, holding the same values.
|
|
3
|
+
*
|
|
4
|
+
* A row read over REST goes through `parseRowsExactly`, so a `bigInt` column arrives as a native
|
|
5
|
+
* bigint and a `decimal` as its exact string. The same row arriving over a subscription used to be
|
|
6
|
+
* a rounded number, because the realtime path had none of that: the service parsed the WAL with a
|
|
7
|
+
* plain `JSON.parse` and the client parsed the frame with another.
|
|
8
|
+
*
|
|
9
|
+
* The service now carries exact columns as strings and says which they are, reading the kinds from
|
|
10
|
+
* the database's own declared types. That is why the frames below name `exactColumns`, and why the
|
|
11
|
+
* client does not consult the local registry here: the frame is authoritative, so a project that
|
|
12
|
+
* never ran `supatype push` still reads the value correctly.
|
|
13
|
+
*/
|
|
14
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
15
|
+
import { RealtimeClient } from "../src/realtime.js"
|
|
16
|
+
import {
|
|
17
|
+
createMockWebSocketClass,
|
|
18
|
+
simulateServerMessage,
|
|
19
|
+
type MockWebSocketInstance,
|
|
20
|
+
} from "./helpers/mock-websocket.js"
|
|
21
|
+
|
|
22
|
+
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
23
|
+
|
|
24
|
+
let instances: MockWebSocketInstance[]
|
|
25
|
+
let originalWebSocket: typeof WebSocket
|
|
26
|
+
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
const mock = createMockWebSocketClass()
|
|
29
|
+
instances = mock.instances
|
|
30
|
+
originalWebSocket = globalThis.WebSocket
|
|
31
|
+
globalThis.WebSocket = mock.MockWebSocket
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
afterEach(() => {
|
|
35
|
+
globalThis.WebSocket = originalWebSocket
|
|
36
|
+
vi.restoreAllMocks()
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
/** Subscribe to a table, deliver one change frame, and hand back what the listener was given. */
|
|
40
|
+
async function deliver(frame: Record<string, unknown>): Promise<Record<string, unknown> | null> {
|
|
41
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
42
|
+
let seen: Record<string, unknown> | null = null
|
|
43
|
+
|
|
44
|
+
client
|
|
45
|
+
.channel("public:subscription")
|
|
46
|
+
.on("postgres_changes", { event: "INSERT" }, (payload) => {
|
|
47
|
+
seen = payload.new
|
|
48
|
+
})
|
|
49
|
+
.subscribe()
|
|
50
|
+
|
|
51
|
+
await settle()
|
|
52
|
+
const ws = instances[0]
|
|
53
|
+
if (!ws) throw new Error("no socket was opened")
|
|
54
|
+
simulateServerMessage(ws, frame)
|
|
55
|
+
await settle()
|
|
56
|
+
return seen
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A change frame as the service now sends one: exact columns as strings, and named. */
|
|
60
|
+
function changeFrame(
|
|
61
|
+
row: Record<string, unknown>,
|
|
62
|
+
exactColumns?: Record<string, string>,
|
|
63
|
+
): Record<string, unknown> {
|
|
64
|
+
return {
|
|
65
|
+
type: "change",
|
|
66
|
+
channel: "public:subscription",
|
|
67
|
+
event: "INSERT",
|
|
68
|
+
payload: { old: null, new: row },
|
|
69
|
+
...(exactColumns ? { exactColumns } : {}),
|
|
70
|
+
timestamp: "2026-01-01T00:00:00Z",
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
describe("a change carrying exact columns", () => {
|
|
75
|
+
it("gives a bigint column a native bigint", async () => {
|
|
76
|
+
const row = await deliver(
|
|
77
|
+
changeFrame({ id: "a", externalId: "9007199254740993" }, { externalId: "bigint" }),
|
|
78
|
+
)
|
|
79
|
+
expect(row?.["externalId"]).toBe(9007199254740993n)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it("keeps the value a double would have rounded", async () => {
|
|
83
|
+
// The control that names the defect. It cannot be written as a numeric literal, because a
|
|
84
|
+
// literal of 9007199254740993 in this file is already 9007199254740992 by the time it runs:
|
|
85
|
+
// that is the whole problem. So the rounded value is derived, and the delivered one compared
|
|
86
|
+
// against it.
|
|
87
|
+
const rounded = BigInt(Number("9007199254740993"))
|
|
88
|
+
expect(rounded).toBe(9007199254740992n)
|
|
89
|
+
|
|
90
|
+
const row = await deliver(
|
|
91
|
+
changeFrame({ id: "a", externalId: "9007199254740993" }, { externalId: "bigint" }),
|
|
92
|
+
)
|
|
93
|
+
expect(row?.["externalId"]).not.toBe(rounded)
|
|
94
|
+
expect(String(row?.["externalId"])).toBe("9007199254740993")
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it("leaves a numeric column as its exact string, scale and all", async () => {
|
|
98
|
+
// `@supatype/types` declares Decimal and Money as string, because JavaScript has no exact
|
|
99
|
+
// decimal. 10.00 and 10 are the same number and different values.
|
|
100
|
+
const row = await deliver(changeFrame({ unitAmount: "10.00" }, { unitAmount: "numeric" }))
|
|
101
|
+
expect(row?.["unitAmount"]).toBe("10.00")
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
it("touches nothing the frame did not name", async () => {
|
|
105
|
+
const row = await deliver(
|
|
106
|
+
changeFrame(
|
|
107
|
+
{ id: "a", quantity: 42, title: "unchanged", externalId: "12" },
|
|
108
|
+
{ externalId: "bigint" },
|
|
109
|
+
),
|
|
110
|
+
)
|
|
111
|
+
expect(row?.["quantity"]).toBe(42)
|
|
112
|
+
expect(row?.["title"]).toBe("unchanged")
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it("coerces a small bigint too, because the database declared it one", async () => {
|
|
116
|
+
// Not decided by whether the value happens to be large: a column typed bigint reads as a
|
|
117
|
+
// bigint every time, or an application comparing against one is wrong half the time.
|
|
118
|
+
const row = await deliver(changeFrame({ externalId: "12" }, { externalId: "bigint" }))
|
|
119
|
+
expect(row?.["externalId"]).toBe(12n)
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
it("applies the same coercion to the old record of an update", async () => {
|
|
123
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
124
|
+
let old: Record<string, unknown> | null = null
|
|
125
|
+
client
|
|
126
|
+
.channel("public:subscription")
|
|
127
|
+
.on("postgres_changes", { event: "UPDATE" }, (payload) => {
|
|
128
|
+
old = payload.old
|
|
129
|
+
})
|
|
130
|
+
.subscribe()
|
|
131
|
+
await settle()
|
|
132
|
+
const ws = instances[0]
|
|
133
|
+
if (!ws) throw new Error("no socket was opened")
|
|
134
|
+
simulateServerMessage(ws, {
|
|
135
|
+
type: "change",
|
|
136
|
+
channel: "public:subscription",
|
|
137
|
+
event: "UPDATE",
|
|
138
|
+
payload: { old: { externalId: "9007199254740993" }, new: { externalId: "9007199254740995" } },
|
|
139
|
+
exactColumns: { externalId: "bigint" },
|
|
140
|
+
timestamp: "2026-01-01T00:00:00Z",
|
|
141
|
+
})
|
|
142
|
+
await settle()
|
|
143
|
+
expect(old?.["externalId"]).toBe(9007199254740993n)
|
|
144
|
+
})
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
describe("a change from a table with nothing exact", () => {
|
|
148
|
+
it("arrives unchanged when the frame names no exact columns", async () => {
|
|
149
|
+
// Which is most tables, and the frame carries no extra field for them at all.
|
|
150
|
+
const row = await deliver(changeFrame({ id: "a", views: 3, title: "hello" }))
|
|
151
|
+
expect(row).toEqual({ id: "a", views: 3, title: "hello" })
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
it("survives a frame from a service too old to send the field", async () => {
|
|
155
|
+
// An upgrade puts a new client in front of an old service. The values are already rounded by
|
|
156
|
+
// then and nothing here can recover them, but the payload must still be delivered.
|
|
157
|
+
const row = await deliver(changeFrame({ id: "a", externalId: 9007199254740992 }))
|
|
158
|
+
expect(row?.["id"]).toBe("a")
|
|
159
|
+
expect(row?.["externalId"]).toBe(9007199254740992)
|
|
160
|
+
})
|
|
161
|
+
})
|
|
@@ -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
|
+
appMetadata: {},
|
|
55
|
+
userMetadata: {},
|
|
56
|
+
createdAt: "2024-01-01T00:00:00Z",
|
|
57
|
+
updatedAt: "2024-01-01T00:00:00Z",
|
|
58
|
+
},
|
|
59
|
+
}
|
|
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", async () => 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", async () => 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", async () => 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
|
+
})
|