@mblaney/holster-browser 2.0.0 → 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/README.md CHANGED
@@ -64,14 +64,14 @@ const appBar = {
64
64
 
65
65
  Each component's props:
66
66
 
67
- | Component | Props |
68
- | --- | --- |
69
- | `Login` | `user`, `host` |
70
- | `Register` | `user` |
71
- | `Signup` | `user` |
72
- | `RequestCode` | *(none)* |
73
- | `ValidateEmail` | `code`, `validate` |
74
- | `ResetPassword` | `loggedIn` |
67
+ | Component | Props |
68
+ | ---------------- | ---------------------------------------------- |
69
+ | `Login` | `user`, `host` |
70
+ | `Register` | `user` |
71
+ | `Signup` | `user` |
72
+ | `RequestCode` | _(none)_ |
73
+ | `ValidateEmail` | `code`, `validate` |
74
+ | `ResetPassword` | `loggedIn` |
75
75
  | `UpdatePassword` | `user`, `loggedIn`, `current`, `code`, `reset` |
76
76
 
77
77
  `ValidateEmail`'s `code`/`validate` and `UpdatePassword`'s `current`/`code`/`reset` come from the query params on the links in the sign up and reset-password emails respectively.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mblaney/holster-browser",
3
- "version": "2.0.0",
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
+ }
@@ -55,13 +55,17 @@ const Register = ({user}) => {
55
55
  return
56
56
  }
57
57
 
58
- user.auth(username, password, err => {
58
+ user.auth(username, password, async err => {
59
59
  if (err) {
60
60
  setDisabledButton(false)
61
61
  setMessage(err)
62
62
  return
63
63
  }
64
64
 
65
+ const signed = await user.SEA.sign(
66
+ {username, email, timestamp: Date.now()},
67
+ user.is,
68
+ )
65
69
  fetch(`${window.location.origin}/verify-login-code`, {
66
70
  method: "POST",
67
71
  headers: {"Content-Type": "application/json;charset=utf-8"},
@@ -69,8 +73,7 @@ const Register = ({user}) => {
69
73
  code: code,
70
74
  pub: user.is.pub,
71
75
  epub: user.is.epub,
72
- username: username,
73
- email: email,
76
+ signed,
74
77
  }),
75
78
  })
76
79
  .then(res => res.text().then(text => ({ok: res.ok, text: text})))
@@ -12,6 +12,7 @@ import Switch from "@mui/material/Switch"
12
12
  import Toolbar from "@mui/material/Toolbar"
13
13
  import Typography from "@mui/material/Typography"
14
14
  import AccountCircleIcon from "@mui/icons-material/AccountCircle"
15
+ import ClearIcon from "@mui/icons-material/Clear"
15
16
  import DarkModeIcon from "@mui/icons-material/DarkMode"
16
17
  import LightModeIcon from "@mui/icons-material/LightMode"
17
18
  import MoreIcon from "@mui/icons-material/MoreVert"
@@ -56,7 +57,7 @@ const StyledInputBase = styled(InputBase, {
56
57
  })(({theme, collapsed}) => ({
57
58
  color: "inherit",
58
59
  "& .MuiInputBase-input": {
59
- padding: theme.spacing(1, 1, 1, 0),
60
+ padding: theme.spacing(1, 4, 1, 0),
60
61
  paddingLeft: `calc(1em + ${theme.spacing(4)})`,
61
62
  transition: theme.transitions.create("width"),
62
63
  width: collapsed ? 0 : "100%",
@@ -93,6 +94,12 @@ const SearchAppBar = ({
93
94
  const [anchorEl, setAnchorEl] = useState(null)
94
95
  const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null)
95
96
 
97
+ const handleClear = () => {
98
+ setSearchValue("")
99
+ onSearch?.("")
100
+ searchInputRef.current?.focus()
101
+ }
102
+
96
103
  const isMenuOpen = Boolean(anchorEl)
97
104
  const isMobileMenuOpen = Boolean(mobileMoreAnchorEl)
98
105
 
@@ -233,6 +240,10 @@ const SearchAppBar = ({
233
240
  onKeyDown={e => {
234
241
  if (e.key === "Enter") {
235
242
  const trimmed = searchValue.trim()
243
+ if (trimmed === "") {
244
+ if (onSearch) onSearch("")
245
+ return
246
+ }
236
247
  if (trimmed.length >= 3) {
237
248
  setSearchValue(trimmed)
238
249
  if (onSearch) {
@@ -240,7 +251,6 @@ const SearchAppBar = ({
240
251
  } else {
241
252
  window.location = `/?search=${encodeURIComponent(trimmed)}`
242
253
  }
243
- searchInputRef.current?.blur()
244
254
  }
245
255
  } else if (e.key === "Escape") {
246
256
  setSearchValue("")
@@ -249,6 +259,24 @@ const SearchAppBar = ({
249
259
  }
250
260
  }}
251
261
  />
262
+ {searchValue && (
263
+ <IconButton
264
+ size="small"
265
+ aria-label="clear search"
266
+ onClick={event => {
267
+ event.stopPropagation()
268
+ handleClear()
269
+ }}
270
+ sx={{
271
+ position: "absolute",
272
+ right: 4,
273
+ top: "50%",
274
+ transform: "translateY(-50%)",
275
+ }}
276
+ >
277
+ <ClearIcon fontSize="small" />
278
+ </IconButton>
279
+ )}
252
280
  </Search>
253
281
  <Box sx={{display: {xs: "none", md: "flex"}}}>
254
282
  <Switch checked={mode === "dark"} onChange={changeMode} />
@@ -42,21 +42,24 @@ const Signup = ({user}) => {
42
42
  return
43
43
  }
44
44
 
45
- user.auth(username, password, err => {
45
+ user.auth(username, password, async err => {
46
46
  if (err) {
47
47
  setDisabledButton(false)
48
48
  setMessage(err)
49
49
  return
50
50
  }
51
51
 
52
+ const signed = await user.SEA.sign(
53
+ {username, email, timestamp: Date.now()},
54
+ user.is,
55
+ )
52
56
  fetch(`${window.location.origin}/signup`, {
53
57
  method: "POST",
54
58
  headers: {"Content-Type": "application/json;charset=utf-8"},
55
59
  body: JSON.stringify({
56
60
  pub: user.is.pub,
57
61
  epub: user.is.epub,
58
- username: username,
59
- email: email,
62
+ signed,
60
63
  }),
61
64
  })
62
65
  .then(res => res.text().then(text => ({ok: res.ok, text: text})))
@@ -12,8 +12,10 @@ import VisibilityOff from "@mui/icons-material/VisibilityOff"
12
12
 
13
13
  const UpdatePassword = ({user, loggedIn, current, code, reset}) => {
14
14
  const [name, setName] = useState(current ?? "")
15
- const [password, setPassword] = useState("")
16
- const [showPassword, setShowPassword] = useState(false)
15
+ const [newPassword, setNewPassword] = useState("")
16
+ const [showNewPassword, setShowNewPassword] = useState(false)
17
+ const [repeatPassword, setRepeatPassword] = useState("")
18
+ const [showRepeatPassword, setShowRepeatPassword] = useState(false)
17
19
  const [message, setMessage] = useState(loggedIn ? "Already logged in" : "")
18
20
  const [disabledButton, setDisabledButton] = useState(loggedIn)
19
21
 
@@ -26,7 +28,7 @@ const UpdatePassword = ({user, loggedIn, current, code, reset}) => {
26
28
  setDisabledButton(true)
27
29
  setMessage("Updating password...")
28
30
 
29
- user.create(username, password, err => {
31
+ user.create(username, newPassword, err => {
30
32
  if (err) {
31
33
  if (err === "Username already exists") {
32
34
  let match = username.match(/^(\w+)\.(\d)$/)
@@ -48,9 +50,10 @@ const UpdatePassword = ({user, loggedIn, current, code, reset}) => {
48
50
  return
49
51
  }
50
52
 
51
- user.auth(username, password, err => {
53
+ user.auth(username, newPassword, err => {
52
54
  if (err) {
53
55
  setDisabledButton(false)
56
+ user.delete(username, newPassword)
54
57
  setMessage(err)
55
58
  return
56
59
  }
@@ -71,7 +74,7 @@ const UpdatePassword = ({user, loggedIn, current, code, reset}) => {
71
74
  .then(res => {
72
75
  if (!res.ok) {
73
76
  setDisabledButton(false)
74
- user.delete(username, password)
77
+ user.delete(username, newPassword)
75
78
  setMessage(res.text)
76
79
  return
77
80
  }
@@ -93,6 +96,14 @@ const UpdatePassword = ({user, loggedIn, current, code, reset}) => {
93
96
  })
94
97
  }
95
98
 
99
+ const submit = () => {
100
+ if (newPassword !== repeatPassword) {
101
+ setMessage("Passwords do not match")
102
+ return
103
+ }
104
+ update(name)
105
+ }
106
+
96
107
  return (
97
108
  <>
98
109
  <Typography variant="h5">Update Password</Typography>
@@ -106,31 +117,54 @@ const UpdatePassword = ({user, loggedIn, current, code, reset}) => {
106
117
  onChange={event => setName(event.target.value)}
107
118
  />
108
119
  <FormControl variant="outlined" fullWidth={true} margin="normal">
109
- <InputLabel htmlFor="update-password">Password</InputLabel>
120
+ <InputLabel htmlFor="update-new-password">New Password</InputLabel>
121
+ <OutlinedInput
122
+ id="update-new-password"
123
+ type={showNewPassword ? "text" : "password"}
124
+ value={newPassword}
125
+ onChange={event => setNewPassword(event.target.value)}
126
+ endAdornment={
127
+ <InputAdornment position="end">
128
+ <IconButton
129
+ aria-label="toggle new password visibility"
130
+ onClick={() => setShowNewPassword(show => !show)}
131
+ edge="end"
132
+ >
133
+ {showNewPassword ? <VisibilityOff /> : <Visibility />}
134
+ </IconButton>
135
+ </InputAdornment>
136
+ }
137
+ label="New Password"
138
+ />
139
+ </FormControl>
140
+ <FormControl variant="outlined" fullWidth={true} margin="normal">
141
+ <InputLabel htmlFor="update-repeat-password">
142
+ Repeat Password
143
+ </InputLabel>
110
144
  <OutlinedInput
111
- id="update-password"
112
- type={showPassword ? "text" : "password"}
113
- value={password}
114
- onChange={event => setPassword(event.target.value)}
145
+ id="update-repeat-password"
146
+ type={showRepeatPassword ? "text" : "password"}
147
+ value={repeatPassword}
148
+ onChange={event => setRepeatPassword(event.target.value)}
115
149
  endAdornment={
116
150
  <InputAdornment position="end">
117
151
  <IconButton
118
- aria-label="toggle password visibility"
119
- onClick={() => setShowPassword(show => !show)}
152
+ aria-label="toggle repeat password visibility"
153
+ onClick={() => setShowRepeatPassword(show => !show)}
120
154
  edge="end"
121
155
  >
122
- {showPassword ? <VisibilityOff /> : <Visibility />}
156
+ {showRepeatPassword ? <VisibilityOff /> : <Visibility />}
123
157
  </IconButton>
124
158
  </InputAdornment>
125
159
  }
126
- label="Password"
160
+ label="Repeat Password"
127
161
  />
128
162
  </FormControl>
129
163
  <Button
130
164
  sx={{mt: 1}}
131
165
  variant="contained"
132
166
  disabled={disabledButton}
133
- onClick={() => update(name)}
167
+ onClick={submit}
134
168
  >
135
169
  Submit
136
170
  </Button>
@@ -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
+ })