-
Notifications
You must be signed in to change notification settings - Fork 114
/
Login.tsx
319 lines (299 loc) · 10.2 KB
/
Login.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import "./Login.css";
import { CSSProperties, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import * as secp from "@noble/secp256k1";
import { useIntl, FormattedMessage } from "react-intl";
import { HexKey } from "@snort/nostr";
import { RootState } from "State/Store";
import { setPrivateKey, setPublicKey, setRelays, setGeneratedPrivateKey } from "State/Login";
import { DefaultRelays, EmailRegex, MnemonicRegex } from "Const";
import { bech32ToHex, unwrap } from "Util";
import { generateBip39Entropy, entropyToDerivedKey } from "nip6";
import ZapButton from "Element/ZapButton";
import useImgProxy from "Hooks/useImgProxy";
import messages from "./messages";
interface ArtworkEntry {
name: string;
pubkey: HexKey;
link: string;
}
// todo: fill more
const Artwork: Array<ArtworkEntry> = [
{
name: "",
pubkey: bech32ToHex("npub1r0rs5q2gk0e3dk3nlc7gnu378ec6cnlenqp8a3cjhyzu6f8k5sgs4sq9ac"),
link: "https://void.cat/d/VKhPayp9ekeXYZGzAL9CxP",
},
{
name: "",
pubkey: bech32ToHex("npub1r0rs5q2gk0e3dk3nlc7gnu378ec6cnlenqp8a3cjhyzu6f8k5sgs4sq9ac"),
link: "https://void.cat/d/3H2h8xxc3aEN6EVeobd8tw",
},
{
name: "",
pubkey: bech32ToHex("npub1r0rs5q2gk0e3dk3nlc7gnu378ec6cnlenqp8a3cjhyzu6f8k5sgs4sq9ac"),
link: "https://void.cat/d/7i9W9PXn3TV86C4RUefNC9",
},
{
name: "",
pubkey: bech32ToHex("npub1r0rs5q2gk0e3dk3nlc7gnu378ec6cnlenqp8a3cjhyzu6f8k5sgs4sq9ac"),
link: "https://void.cat/d/KtoX4ei6RYHY7HESg3Ve3k",
},
];
export async function getNip05PubKey(addr: string): Promise<string> {
const [username, domain] = addr.split("@");
const rsp = await fetch(`https://${domain}/.well-known/nostr.json?name=${encodeURIComponent(username)}`);
if (rsp.ok) {
const data = await rsp.json();
const pKey = data.names[username];
if (pKey) {
return pKey;
}
}
throw new Error("User key not found");
}
export default function LoginPage() {
const dispatch = useDispatch();
const navigate = useNavigate();
const publicKey = useSelector<RootState, HexKey | undefined>(s => s.login.publicKey);
const [key, setKey] = useState("");
const [error, setError] = useState("");
const [art, setArt] = useState<ArtworkEntry>();
const { formatMessage } = useIntl();
const { proxy } = useImgProxy();
const hasNip7 = "nostr" in window;
const isSecure = window.location.protocol === "https:";
useEffect(() => {
if (publicKey) {
navigate("/");
}
}, [publicKey, navigate]);
useEffect(() => {
const ret = unwrap(Artwork.at(Artwork.length * Math.random()));
proxy(ret.link).then(a => setArt({ ...ret, link: a }));
}, []);
async function doLogin() {
const insecureMsg = formatMessage({
defaultMessage:
"Can't login with private key on an insecure connection, please use a Nostr key manager extension instead",
});
try {
if (key.startsWith("nsec")) {
if (!isSecure) {
throw new Error(insecureMsg);
}
const hexKey = bech32ToHex(key);
if (secp.utils.isValidPrivateKey(hexKey)) {
dispatch(setPrivateKey(hexKey));
} else {
throw new Error("INVALID PRIVATE KEY");
}
} else if (key.startsWith("npub")) {
const hexKey = bech32ToHex(key);
dispatch(setPublicKey(hexKey));
} else if (key.match(EmailRegex)) {
const hexKey = await getNip05PubKey(key);
dispatch(setPublicKey(hexKey));
} else if (key.match(MnemonicRegex)) {
if (!isSecure) {
throw new Error(insecureMsg);
}
const ent = generateBip39Entropy(key);
const keyHex = entropyToDerivedKey(ent);
dispatch(setPrivateKey(keyHex));
} else if (secp.utils.isValidPrivateKey(key)) {
if (!isSecure) {
throw new Error(insecureMsg);
}
dispatch(setPrivateKey(key));
} else {
throw new Error("INVALID PRIVATE KEY");
}
} catch (e) {
if (e instanceof Error) {
setError(e.message);
} else {
setError(
formatMessage({
defaultMessage: "Unknown login error",
})
);
}
console.error(e);
}
}
async function makeRandomKey() {
const ent = generateBip39Entropy();
const entHex = secp.utils.bytesToHex(ent);
const newKeyHex = entropyToDerivedKey(ent);
dispatch(setGeneratedPrivateKey({ key: newKeyHex, entropy: entHex }));
navigate("/new");
}
async function doNip07Login() {
const pubKey = await window.nostr.getPublicKey();
dispatch(setPublicKey(pubKey));
if ("getRelays" in window.nostr) {
const relays = await window.nostr.getRelays();
dispatch(
setRelays({
relays: {
...relays,
...Object.fromEntries(DefaultRelays.entries()),
},
createdAt: 1,
})
);
}
}
function altLogins() {
if (!hasNip7) {
return;
}
return (
<button type="button" onClick={doNip07Login}>
<FormattedMessage
defaultMessage="Login with Extension (NIP-07)"
description="Login button for NIP7 key manager extension"
/>
</button>
);
}
function generateKey() {
if (!isSecure) return;
return (
<>
<div className="flex login-or">
<FormattedMessage defaultMessage="OR" description="Seperator text for Login / Generate Key" />
<div className="divider w-max"></div>
</div>
<h1 dir="auto">
<FormattedMessage defaultMessage="Create an Account" description="Heading for generate key flow" />
</h1>
<p>
<FormattedMessage
defaultMessage="Generate a public / private key pair. Do not share your private key with anyone, this acts as your password. Once lost, it cannot be “reset” or recovered. Keep safe!"
description="Note about key security before generating a new key"
/>
</p>
<div className="login-actions">
<button type="button" onClick={() => makeRandomKey()}>
<FormattedMessage defaultMessage="Generate Key" description="Button: Generate a new key" />
</button>
</div>
</>
);
}
function installExtension() {
if (isSecure) return;
return (
<>
<div className="flex login-or">
<FormattedMessage defaultMessage="OR" description="Seperator text for Login / Generate Key" />
<div className="divider w-max"></div>
</div>
<h1 dir="auto">
<FormattedMessage
defaultMessage="Install Extension"
description="Heading for install key manager extension"
/>
</h1>
<p>
<FormattedMessage defaultMessage="Key manager extensions are more secure and allow you to easily login to any Nostr client, here are some well known extensions:" />
</p>
<ul>
<li>
<a href="https://getalby.com/" target="_blank" rel="noreferrer">
Alby
</a>
</li>
<li>
<a
href="https://chrome.google.com/webstore/detail/nos2x/kpgefcfmnafjgpblomihpgmejjdanjjp"
target="_blank"
rel="noreferrer">
nos2x
</a>
</li>
</ul>
<p>
<FormattedMessage
defaultMessage="If you want to try out some others, check out {link} for more!"
values={{
link: <a href="https://github.com/aljazceru/awesome-nostr#browser-extensions">awesome-nostr</a>,
}}
/>
</p>
<p>
<FormattedMessage defaultMessage="Once you setup your key manager extension and generated a key, you can follow our new users flow to setup your profile and help you find some interesting people on Nostr to follow." />
</p>
{hasNip7 ? (
<div className="login-actions">
<button type="button" onClick={() => doNip07Login().then(() => navigate("/new/username"))}>
<FormattedMessage defaultMessage="Setup Profile" />
</button>
</div>
) : (
<b className="error">
<FormattedMessage defaultMessage="Hmm, can't find a key manager extension.. try reloading the page." />
</b>
)}
</>
);
}
return (
<div className="login">
<div>
<div className="login-container">
<div className="logo" onClick={() => navigate("/")}>
Snort
</div>
<h1 dir="auto">
<FormattedMessage defaultMessage="Login" description="Login header" />
</h1>
<p dir="auto">
<FormattedMessage defaultMessage="Your key" description="Label for key input" />
</p>
<div className="flex">
<input
dir="auto"
type="text"
placeholder={formatMessage(messages.KeyPlaceholder)}
className="f-grow"
onChange={e => setKey(e.target.value)}
/>
</div>
{error.length > 0 ? <b className="error">{error}</b> : null}
<p className="login-note">
<FormattedMessage
defaultMessage="Only the secret key can be used to publish (sign events), everything else logs you in read-only mode."
description="Explanation for public key only login is read-only"
/>
</p>
<div dir="auto" className="login-actions">
<button type="button" onClick={doLogin}>
<FormattedMessage defaultMessage="Login" description="Login button" />
</button>
{altLogins()}
</div>
{generateKey()}
{installExtension()}
</div>
</div>
<div>
<div className="artwork" style={{ ["--img-src"]: `url('${art?.link}')` } as CSSProperties}>
<div className="attribution">
<FormattedMessage
defaultMessage="Art by {name}"
description="Artwork attribution label"
values={{
name: <span className="artist">Karnage</span>,
}}
/>
<ZapButton pubkey={art?.pubkey ?? ""} />
</div>
</div>
</div>
</div>
);
}