@mblaney/holster-browser 2.0.1 → 2.0.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mblaney/holster-browser",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "React components for holster applications",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -32,11 +32,13 @@
32
32
  "test": "vitest --run"
33
33
  },
34
34
  "devDependencies": {
35
+ "@mblaney/holster": "^2.1.0",
35
36
  "@testing-library/jest-dom": "^5.17.0",
36
37
  "@testing-library/react": "^14.0.0",
37
38
  "@testing-library/user-event": "^13.5.0",
38
39
  "@vitejs/plugin-react": "^4.3.1",
39
40
  "jsdom": "^22.0.0",
41
+ "mock-socket": "^9.3.1",
40
42
  "prettier": "^3.4.2",
41
43
  "vitest": "^4.1.5"
42
44
  },
@@ -0,0 +1,76 @@
1
+ import fs from "fs/promises"
2
+ import {afterAll} from "vitest"
3
+ import {Server} from "mock-socket"
4
+ import Holster from "@mblaney/holster/src/holster.js"
5
+ import {graph} from "@mblaney/holster/src/utils.js"
6
+
7
+ const testUsername = "testuser"
8
+ const testPassword = "testpassword"
9
+
10
+ // Each createTestUser call gets its own isolated mock-socket server/port
11
+ // and on-disk storage dir, so concurrently-running test files never share
12
+ // state. process.pid keeps concurrently-running files from picking the
13
+ // same port (vitest runs each file in its own forked process by default).
14
+ let nextPort = 0
15
+ const testDirs = []
16
+
17
+ afterAll(async () => {
18
+ for (const dir of testDirs) {
19
+ await fs.rm(dir, {recursive: true, force: true})
20
+ }
21
+ })
22
+
23
+ // A fresh, unauthenticated holster instance - for tests that need to drive
24
+ // user.create()/user.auth() themselves (e.g. a signup flow), rather than
25
+ // starting from an already-logged-in user.
26
+ export function createTestHolster() {
27
+ const port = 20000 + (process.pid % 500) * 100 + (nextPort++ % 100)
28
+ const file = `holster-browser-test-${port}`
29
+ testDirs.push(file)
30
+ const wss = new Server(`ws://localhost:${port}`)
31
+ const holster = Holster({wss, file})
32
+ return {holster, port, dir: file}
33
+ }
34
+
35
+ export async function createTestUser() {
36
+ const {holster, port, dir} = createTestHolster()
37
+ const user = holster.user()
38
+
39
+ await new Promise((resolve, reject) => {
40
+ user.create(testUsername, testPassword, err => {
41
+ if (err && !err.includes("already exists")) reject(new Error(err))
42
+ else resolve()
43
+ })
44
+ })
45
+
46
+ await new Promise((resolve, reject) => {
47
+ user.auth(testUsername, testPassword, err => {
48
+ if (err) reject(new Error(err))
49
+ else resolve()
50
+ })
51
+ })
52
+
53
+ return {holster, user, port, dir}
54
+ }
55
+
56
+ // Publishes data directly under a keypair's own soul via the wire API -
57
+ // mirrors what user.create() does internally for a real signup (see
58
+ // holster/src/user.js), without needing a second authenticated session
59
+ // just to write something discoverable under that pub's graph. A contact's
60
+ // public data is something you look up, not something you need to be
61
+ // logged in as.
62
+ export async function publishData(holster, pair, data) {
63
+ const timestamp = Date.now()
64
+ const sig = await holster.SEA.signTimestamp(timestamp, pair)
65
+ const soul = "~" + pair.pub
66
+ const graphData = graph(soul, data, sig, pair.pub, timestamp)
67
+ await new Promise((resolve, reject) => {
68
+ holster.wire.put(graphData, err =>
69
+ err ? reject(new Error(err)) : resolve(),
70
+ )
71
+ })
72
+ }
73
+
74
+ export async function publishEpub(holster, pair) {
75
+ await publishData(holster, pair, {pub: pair.pub, epub: pair.epub})
76
+ }
@@ -0,0 +1,214 @@
1
+ import {describe, it, expect, beforeEach, vi} from "vitest"
2
+ import {render, screen, waitFor, act} from "@testing-library/react"
3
+ import userEvent from "@testing-library/user-event"
4
+ import {createTestHolster} from "../../__tests__/setup.js"
5
+ import Login from "../Login.jsx"
6
+
7
+ // The host and the account being logged into are the same real account here
8
+ // - Login addresses "the host's own map/accounts data" via [host, key],
9
+ // which resolves correctly whether or not host is your own pub. Using one
10
+ // account for both avoids needing a second, separately-keyed identity.
11
+ async function createHostedAccount({
12
+ username = "alice",
13
+ password = "hunter2",
14
+ accountCode = "acc1",
15
+ accountName = "Alice",
16
+ } = {}) {
17
+ const {holster} = createTestHolster()
18
+ const user = holster.user()
19
+ await new Promise(resolve => user.create(username, password, resolve))
20
+ await new Promise(resolve => user.auth(username, password, resolve))
21
+ const host = user.is.pub
22
+
23
+ await new Promise(resolve => {
24
+ user
25
+ .get([host, "map"])
26
+ .next("account:" + host)
27
+ .put(accountCode, resolve)
28
+ })
29
+ await new Promise(resolve => {
30
+ user
31
+ .get([host, "accounts"])
32
+ .next(accountCode)
33
+ .put({pub: host, name: accountName}, resolve)
34
+ })
35
+
36
+ user.leave()
37
+ return {holster, user, host, username, password, accountCode, accountName}
38
+ }
39
+
40
+ async function fillAndSubmit({username, password}) {
41
+ if (username !== undefined) {
42
+ await userEvent.type(screen.getByLabelText("Username"), username)
43
+ }
44
+ if (password !== undefined) {
45
+ await userEvent.type(screen.getByLabelText("Password"), password)
46
+ }
47
+ await userEvent.click(screen.getByRole("button", {name: "Submit"}))
48
+ }
49
+
50
+ describe("Login Component", () => {
51
+ beforeEach(() => {
52
+ sessionStorage.clear()
53
+ localStorage.clear()
54
+ delete window.location
55
+ window.location = {href: "", reload: vi.fn()}
56
+ window.indexedDB = {deleteDatabase: vi.fn()}
57
+ })
58
+
59
+ it("renders the login form", () => {
60
+ const {holster} = createTestHolster()
61
+ render(<Login user={holster.user()} host="some-host" />)
62
+ expect(screen.getByText("Login")).toBeTruthy()
63
+ expect(screen.getByLabelText("Username")).toBeTruthy()
64
+ expect(screen.getByLabelText("Password")).toBeTruthy()
65
+ })
66
+
67
+ it("shows already logged in and disables submit when a user is present", async () => {
68
+ const {user, host} = await createHostedAccount()
69
+ // Re-auth to get a real, populated user.is - leave() nulled it above.
70
+ await new Promise(resolve => user.auth("alice", "hunter2", resolve))
71
+ render(<Login user={user} host={host} />)
72
+ expect(screen.getByText("Already logged in")).toBeTruthy()
73
+ expect(screen.getByRole("button", {name: "Submit"})).toBeDisabled()
74
+ })
75
+
76
+ it("shows Host not available and reloads when host is missing", async () => {
77
+ const {holster} = createTestHolster()
78
+ localStorage.setItem("host", "something")
79
+ render(<Login user={holster.user()} host={null} />)
80
+
81
+ await act(async () => {
82
+ await userEvent.click(screen.getByRole("button", {name: "Submit"}))
83
+ })
84
+
85
+ expect(screen.getByText("Host not available")).toBeTruthy()
86
+ expect(localStorage.getItem("host")).toBeNull()
87
+ await waitFor(() => expect(window.location.reload).toHaveBeenCalled(), {
88
+ timeout: 1500,
89
+ })
90
+ })
91
+
92
+ it("logs in, verifies the account, and redirects home", async () => {
93
+ const {user, host, username, password, accountCode, accountName} =
94
+ await createHostedAccount()
95
+ render(<Login user={user} host={host} />)
96
+
97
+ await act(async () => {
98
+ await fillAndSubmit({username, password})
99
+ })
100
+
101
+ await waitFor(() => expect(window.location).toBe("/"))
102
+
103
+ expect(sessionStorage.getItem("code")).toBe(accountCode)
104
+ expect(sessionStorage.getItem("name")).toBe(accountName)
105
+ // "Stay logged in" wasn't checked, so nothing should be persisted to
106
+ // localStorage - only the in-memory/session copy.
107
+ expect(localStorage.getItem("code")).toBeNull()
108
+ expect(localStorage.getItem("name")).toBeNull()
109
+ })
110
+
111
+ it("also persists to localStorage when Stay logged in is checked", async () => {
112
+ const {user, host, username, password, accountCode, accountName} =
113
+ await createHostedAccount()
114
+ render(<Login user={user} host={host} />)
115
+
116
+ await act(async () => {
117
+ await userEvent.click(screen.getByLabelText("Stay logged in"))
118
+ await fillAndSubmit({username, password})
119
+ })
120
+
121
+ await waitFor(() => expect(window.location).toBe("/"))
122
+
123
+ expect(localStorage.getItem("code")).toBe(accountCode)
124
+ expect(localStorage.getItem("name")).toBe(accountName)
125
+ })
126
+
127
+ it("gives up with Wrong username or password after exhausting username variants", async () => {
128
+ const {holster} = createTestHolster()
129
+ render(<Login user={holster.user()} host="some-host" />)
130
+
131
+ // A real auth attempt against a nonexistent username takes ~1s here.
132
+ // Starting from a ".8" suffix reaches the give-up branch (increment
133
+ // hits 10) after one real retry instead of ten.
134
+ await act(async () => {
135
+ await fillAndSubmit({username: "nobody.8", password: "whatever"})
136
+ })
137
+
138
+ await waitFor(
139
+ () => {
140
+ expect(screen.getByText("Wrong username or password")).toBeTruthy()
141
+ },
142
+ {timeout: 4000},
143
+ )
144
+ expect(screen.getByRole("button", {name: "Submit"})).not.toBeDisabled()
145
+ })
146
+
147
+ it("rejects a login whose account record no longer matches the current pub", async () => {
148
+ const {holster} = createTestHolster()
149
+ const user = holster.user()
150
+ // Named "alice.8" so the mismatch's retry (see below) only needs one
151
+ // real extra attempt ("alice.9") to reach the give-up branch, instead
152
+ // of working through every suffix from "alice.1".
153
+ await new Promise(resolve => user.create("alice.8", "hunter2", resolve))
154
+ await new Promise(resolve => user.auth("alice.8", "hunter2", resolve))
155
+ const host = user.is.pub
156
+ const stalePub = "some-other-pub.some-other-epub"
157
+
158
+ await new Promise(resolve => {
159
+ user
160
+ .get([host, "map"])
161
+ .next("account:" + host)
162
+ .put("acc1", resolve)
163
+ })
164
+ await new Promise(resolve => {
165
+ user
166
+ .get([host, "accounts"])
167
+ .next("acc1")
168
+ .put({pub: stalePub, name: "Alice"}, resolve)
169
+ })
170
+ user.leave()
171
+
172
+ render(<Login user={user} host={host} />)
173
+ await act(async () => {
174
+ await fillAndSubmit({username: "alice.8", password: "hunter2"})
175
+ })
176
+
177
+ // The mismatch reuses the "Wrong username or password" message, which
178
+ // also triggers the same username-variant retry as a wrong password.
179
+ await waitFor(
180
+ () => {
181
+ expect(screen.getByText("Wrong username or password")).toBeTruthy()
182
+ },
183
+ {timeout: 4000},
184
+ )
185
+ expect(sessionStorage.getItem("code")).toBeNull()
186
+ })
187
+
188
+ it("reports account not found, cleans up local storage, and logs out when there's no matching account", async () => {
189
+ const {holster} = createTestHolster()
190
+ const user = holster.user()
191
+ await new Promise(resolve => user.create("alice", "hunter2", resolve))
192
+ // No map/accounts data seeded for this (fake) host at all.
193
+
194
+ localStorage.setItem("host", "something")
195
+ render(<Login user={user} host="some-host" />)
196
+
197
+ await act(async () => {
198
+ await fillAndSubmit({username: "alice", password: "hunter2"})
199
+ })
200
+
201
+ await waitFor(() => {
202
+ expect(
203
+ screen.getByText("Account not found. Please try logging in again"),
204
+ ).toBeTruthy()
205
+ })
206
+
207
+ expect(window.indexedDB.deleteDatabase).toHaveBeenCalledWith("radata")
208
+ expect(localStorage.getItem("host")).toBeNull()
209
+ expect(user.is).toBeFalsy()
210
+ await waitFor(() => expect(window.location.reload).toHaveBeenCalled(), {
211
+ timeout: 2500,
212
+ })
213
+ })
214
+ })
@@ -0,0 +1,120 @@
1
+ import {describe, it, expect, vi} from "vitest"
2
+ import {render, screen, waitFor, act} from "@testing-library/react"
3
+ import userEvent from "@testing-library/user-event"
4
+ import {createTestUser} from "../../__tests__/setup.js"
5
+ import LoginCodes from "../LoginCodes.jsx"
6
+
7
+ // The host and the logged-in user are the same real account here - the
8
+ // component addresses "the host's own epub/shared data" via [host, key],
9
+ // which resolves correctly whether or not host is your own pub. Using one
10
+ // account for both avoids needing a second, separately-keyed identity just
11
+ // to exercise the ECDH secret computation.
12
+ async function shareCode(user, code, key, value) {
13
+ const secret = await user.SEA.secret({epub: user.is.epub}, user.is)
14
+ const enc = value === null ? null : await user.SEA.encrypt(value, secret)
15
+ await new Promise(resolve => {
16
+ user
17
+ .get([user.is.pub, "shared"])
18
+ .next("login_codes")
19
+ .next(code)
20
+ .put({[key]: enc}, resolve)
21
+ })
22
+ }
23
+
24
+ describe("LoginCodes Component", () => {
25
+ it("renders nothing when there are no shared codes", async () => {
26
+ const {user} = await createTestUser()
27
+ const {container} = render(
28
+ <LoginCodes user={user} host={user.is.pub} code="my-code" />,
29
+ )
30
+ expect(container.firstChild).toBeNull()
31
+ })
32
+
33
+ it("renders nothing when host or code is missing", async () => {
34
+ const {user} = await createTestUser()
35
+ const {container} = render(<LoginCodes user={user} host={user.is.pub} />)
36
+ expect(container.firstChild).toBeNull()
37
+ })
38
+
39
+ it("shows a pre-existing shared login code, decrypted", async () => {
40
+ const {user} = await createTestUser()
41
+ await shareCode(user, "my-code", "codeA", "ABC123")
42
+
43
+ const {container} = render(
44
+ <LoginCodes user={user} host={user.is.pub} code="my-code" />,
45
+ )
46
+
47
+ await waitFor(() => {
48
+ expect(screen.getByDisplayValue("ABC123")).toBeTruthy()
49
+ })
50
+ expect(container.textContent).toContain("You have")
51
+ expect(container.textContent).toContain("1")
52
+ expect(container.textContent).not.toContain("login codes")
53
+ })
54
+
55
+ it("shows the plural count for more than one code", async () => {
56
+ const {user} = await createTestUser()
57
+ await shareCode(user, "my-code", "codeA", "ABC123")
58
+ await shareCode(user, "my-code", "codeB", "DEF456")
59
+
60
+ const {container} = render(
61
+ <LoginCodes user={user} host={user.is.pub} code="my-code" />,
62
+ )
63
+
64
+ await waitFor(() => {
65
+ expect(screen.getByDisplayValue("ABC123")).toBeTruthy()
66
+ expect(screen.getByDisplayValue("DEF456")).toBeTruthy()
67
+ })
68
+ expect(container.textContent).toContain("login codes you can share")
69
+ })
70
+
71
+ it("live-updates when a new code is shared after mount", async () => {
72
+ const {user} = await createTestUser()
73
+ await shareCode(user, "my-code", "codeA", "ABC123")
74
+
75
+ render(<LoginCodes user={user} host={user.is.pub} code="my-code" />)
76
+ await waitFor(() => {
77
+ expect(screen.getByDisplayValue("ABC123")).toBeTruthy()
78
+ })
79
+
80
+ await shareCode(user, "my-code", "codeB", "DEF456")
81
+
82
+ await waitFor(() => {
83
+ expect(screen.getByDisplayValue("DEF456")).toBeTruthy()
84
+ })
85
+ })
86
+
87
+ it("removes a code from the list once it's revoked", async () => {
88
+ const {user} = await createTestUser()
89
+ await shareCode(user, "my-code", "codeA", "ABC123")
90
+
91
+ render(<LoginCodes user={user} host={user.is.pub} code="my-code" />)
92
+ await waitFor(() => {
93
+ expect(screen.getByDisplayValue("ABC123")).toBeTruthy()
94
+ })
95
+
96
+ await shareCode(user, "my-code", "codeA", null)
97
+
98
+ await waitFor(() => {
99
+ expect(screen.queryByDisplayValue("ABC123")).toBeNull()
100
+ })
101
+ })
102
+
103
+ it("selects the code's text when its copy button is clicked", async () => {
104
+ const {user} = await createTestUser()
105
+ await shareCode(user, "my-code", "codeA", "ABC123")
106
+ const selectSpy = vi.spyOn(HTMLInputElement.prototype, "select")
107
+
108
+ render(<LoginCodes user={user} host={user.is.pub} code="my-code" />)
109
+ await waitFor(() => {
110
+ expect(screen.getByDisplayValue("ABC123")).toBeTruthy()
111
+ })
112
+
113
+ await act(async () => {
114
+ await userEvent.click(screen.getByLabelText("copy login code"))
115
+ })
116
+ expect(selectSpy).toHaveBeenCalled()
117
+
118
+ selectSpy.mockRestore()
119
+ })
120
+ })
@@ -0,0 +1,223 @@
1
+ import {describe, it, expect, beforeEach, vi} from "vitest"
2
+ import {render, screen, waitFor, act} from "@testing-library/react"
3
+ import userEvent from "@testing-library/user-event"
4
+ import {createTestHolster} from "../../__tests__/setup.js"
5
+ import Register from "../Register.jsx"
6
+
7
+ function mockFetchResponse(ok, text) {
8
+ return Promise.resolve({ok, text: () => Promise.resolve(text)})
9
+ }
10
+
11
+ async function fillAndSubmit({username, password, email, code}) {
12
+ if (username !== undefined) {
13
+ await userEvent.type(screen.getByLabelText("Username"), username)
14
+ }
15
+ if (password !== undefined) {
16
+ await userEvent.type(screen.getByLabelText("Password"), password)
17
+ }
18
+ if (email !== undefined) {
19
+ await userEvent.type(screen.getByLabelText("Email"), email)
20
+ }
21
+ if (code !== undefined) {
22
+ await userEvent.type(screen.getByLabelText("Login code"), code)
23
+ }
24
+ await userEvent.click(screen.getByRole("button", {name: "Submit"}))
25
+ }
26
+
27
+ describe("Register Component", () => {
28
+ beforeEach(() => {
29
+ vi.stubGlobal("fetch", vi.fn())
30
+ delete window.location
31
+ window.location = {href: ""}
32
+ })
33
+
34
+ it("renders the register form", () => {
35
+ const {holster} = createTestHolster()
36
+ render(<Register user={holster.user()} />)
37
+ expect(screen.getByText("Register")).toBeTruthy()
38
+ expect(screen.getByLabelText("Username")).toBeTruthy()
39
+ expect(screen.getByLabelText("Email")).toBeTruthy()
40
+ expect(screen.getByLabelText("Login code")).toBeTruthy()
41
+ })
42
+
43
+ it("shows already logged in and disables submit when a user is present", async () => {
44
+ const {holster} = createTestHolster()
45
+ const user = holster.user()
46
+ await new Promise(resolve => {
47
+ user.create("alice", "hunter2", () =>
48
+ user.auth("alice", "hunter2", resolve),
49
+ )
50
+ })
51
+ render(<Register user={user} />)
52
+ expect(screen.getByText("Already logged in")).toBeTruthy()
53
+ expect(screen.getByRole("button", {name: "Submit"})).toBeDisabled()
54
+ })
55
+
56
+ it("requires a username", async () => {
57
+ const {holster} = createTestHolster()
58
+ const user = holster.user()
59
+ render(<Register user={user} />)
60
+ await act(async () => {
61
+ await fillAndSubmit({email: "alice@test.com"})
62
+ })
63
+ expect(screen.getByText("Please choose a username")).toBeTruthy()
64
+ expect(user.is).toBeFalsy()
65
+ expect(fetch).not.toHaveBeenCalled()
66
+ })
67
+
68
+ it("rejects a username with invalid characters", async () => {
69
+ const {holster} = createTestHolster()
70
+ const user = holster.user()
71
+ render(<Register user={user} />)
72
+ await act(async () => {
73
+ await fillAndSubmit({username: "alice!", email: "alice@test.com"})
74
+ })
75
+ expect(
76
+ screen.getByText(
77
+ "Username must contain only numbers, letters and underscore",
78
+ ),
79
+ ).toBeTruthy()
80
+ expect(user.is).toBeFalsy()
81
+ expect(fetch).not.toHaveBeenCalled()
82
+ })
83
+
84
+ it("requires an email", async () => {
85
+ const {holster} = createTestHolster()
86
+ const user = holster.user()
87
+ render(<Register user={user} />)
88
+ await act(async () => {
89
+ await fillAndSubmit({username: "alice"})
90
+ })
91
+ expect(screen.getByText("Please provide your email")).toBeTruthy()
92
+ expect(user.is).toBeFalsy()
93
+ expect(fetch).not.toHaveBeenCalled()
94
+ })
95
+
96
+ it("checks the login code first, and stops without creating an account when it's rejected", async () => {
97
+ const {holster} = createTestHolster()
98
+ const user = holster.user()
99
+ fetch.mockReturnValue(mockFetchResponse(false, "Invalid login code"))
100
+ render(<Register user={user} />)
101
+
102
+ await act(async () => {
103
+ await fillAndSubmit({
104
+ username: "alice",
105
+ password: "hunter2",
106
+ email: "alice@test.com",
107
+ code: "bad-code",
108
+ })
109
+ })
110
+
111
+ expect(fetch).toHaveBeenCalledWith(
112
+ expect.stringContaining("/check-login-code"),
113
+ expect.objectContaining({
114
+ method: "POST",
115
+ body: JSON.stringify({code: "bad-code"}),
116
+ }),
117
+ )
118
+ expect(fetch).toHaveBeenCalledTimes(1)
119
+ expect(screen.getByText("Invalid login code")).toBeTruthy()
120
+ expect(user.is).toBeFalsy()
121
+ })
122
+
123
+ it("creates the account, verifies the login code, and redirects on success", async () => {
124
+ const {holster} = createTestHolster()
125
+ const user = holster.user()
126
+ fetch
127
+ .mockReturnValueOnce(mockFetchResponse(true, ""))
128
+ .mockReturnValueOnce(mockFetchResponse(true, ""))
129
+ render(<Register user={user} />)
130
+
131
+ await act(async () => {
132
+ await fillAndSubmit({
133
+ username: "alice",
134
+ password: "hunter2",
135
+ email: "alice@test.com",
136
+ code: "good-code",
137
+ })
138
+ })
139
+
140
+ await waitFor(() => expect(user.is).toBeTruthy())
141
+ const {pub, epub} = user.is
142
+
143
+ expect(fetch).toHaveBeenCalledTimes(2)
144
+ expect(fetch).toHaveBeenNthCalledWith(
145
+ 1,
146
+ expect.stringContaining("/check-login-code"),
147
+ expect.objectContaining({body: JSON.stringify({code: "good-code"})}),
148
+ )
149
+ const secondCallBody = JSON.parse(fetch.mock.calls[1][1].body)
150
+ expect(secondCallBody).toEqual({
151
+ code: "good-code",
152
+ pub,
153
+ epub,
154
+ signed: expect.anything(),
155
+ })
156
+
157
+ const verified = await holster.SEA.verify(secondCallBody.signed, {pub})
158
+ expect(verified).toEqual({
159
+ username: "alice",
160
+ email: "alice@test.com",
161
+ timestamp: expect.any(Number),
162
+ })
163
+
164
+ expect(screen.getByText("Account created")).toBeTruthy()
165
+ expect(window.location).toBe("/login")
166
+ })
167
+
168
+ it("deletes the local account and shows the error when verification fails", async () => {
169
+ const {holster} = createTestHolster()
170
+ const user = holster.user()
171
+ fetch
172
+ .mockReturnValueOnce(mockFetchResponse(true, ""))
173
+ .mockReturnValueOnce(mockFetchResponse(false, "Login code already used"))
174
+ render(<Register user={user} />)
175
+
176
+ await act(async () => {
177
+ await fillAndSubmit({
178
+ username: "alice",
179
+ password: "hunter2",
180
+ email: "alice@test.com",
181
+ code: "used-code",
182
+ })
183
+ })
184
+
185
+ await waitFor(() => {
186
+ expect(screen.getByText("Login code already used")).toBeTruthy()
187
+ })
188
+ expect(window.location).toEqual({href: ""})
189
+
190
+ // Prove the account was actually deleted locally, not just left behind.
191
+ await waitFor(async () => {
192
+ const err = await new Promise(resolve => {
193
+ user.auth("alice", "hunter2", resolve)
194
+ })
195
+ expect(err).toBe("Wrong username or password")
196
+ })
197
+ })
198
+
199
+ it("shows the error and stops when user.create fails", async () => {
200
+ const {holster} = createTestHolster()
201
+ const user = holster.user()
202
+ await new Promise(resolve => {
203
+ user.create("alice", "existing-password", resolve)
204
+ })
205
+ fetch.mockReturnValue(mockFetchResponse(true, ""))
206
+ render(<Register user={user} />)
207
+
208
+ await act(async () => {
209
+ await fillAndSubmit({
210
+ username: "alice",
211
+ password: "hunter2",
212
+ email: "alice@test.com",
213
+ code: "good-code",
214
+ })
215
+ })
216
+
217
+ await waitFor(() => {
218
+ expect(screen.getByText("Username already exists")).toBeTruthy()
219
+ })
220
+ expect(user.is).toBeFalsy()
221
+ expect(fetch).toHaveBeenCalledTimes(1)
222
+ })
223
+ })