File size: 16,264 Bytes
d4c6e81
 
 
d1cde70
d4c6e81
401c4a8
 
 
 
 
 
 
 
 
454186b
 
d4c6e81
 
454186b
d4c6e81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454186b
 
 
 
 
 
401c4a8
 
 
5748a9d
 
 
 
401c4a8
 
 
 
d4c6e81
 
 
 
 
 
 
 
 
 
 
 
 
 
5748a9d
 
d1cde70
 
 
5748a9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254e7f6
 
15fae7a
 
 
 
 
254e7f6
15fae7a
254e7f6
 
 
 
 
 
15fae7a
 
254e7f6
 
 
 
5748a9d
 
 
254e7f6
15fae7a
 
 
401c4a8
 
 
 
 
 
15fae7a
5748a9d
 
 
 
 
 
 
 
 
 
d1cde70
 
 
 
 
 
 
 
 
 
d4c6e81
 
 
d1cde70
d4c6e81
 
 
7dd0d81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c6e81
d1cde70
 
d4c6e81
 
454186b
 
 
 
d4c6e81
 
 
 
d1cde70
 
 
d4c6e81
d1cde70
 
d4c6e81
 
454186b
d4c6e81
 
 
 
 
 
454186b
d4c6e81
5748a9d
454186b
5748a9d
454186b
 
 
5748a9d
 
 
 
 
 
 
 
 
d4c6e81
 
 
 
 
 
 
 
 
 
dd61d52
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c6e81
 
 
5748a9d
d4c6e81
454186b
 
 
 
 
 
 
 
 
 
 
 
 
d4c6e81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1cde70
d4c6e81
d1cde70
d4c6e81
d1cde70
d4c6e81
 
d1cde70
454186b
d4c6e81
 
 
454186b
 
d1cde70
 
 
 
 
 
 
401c4a8
 
 
d1cde70
 
 
 
 
401c4a8
fb84c92
d1cde70
 
 
 
 
 
 
 
 
 
 
454186b
 
d1cde70
454186b
d4c6e81
 
 
 
 
5748a9d
 
 
d4c6e81
 
 
 
454186b
d4c6e81
 
 
 
 
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import { useState, useRef } from "react"
import { supabase } from "../lib/supabase"

const G = "linear-gradient(135deg, #1d4ed8 0%, #0891b2 100%)"

// No hosted web copy of the app exists (mirrorai.live is a landing page
// only) — any email link (reset, confirmation) has to redirect into the
// extension's own fullpage view, which is what actually runs the React app.
function extensionRedirectUrl() {
  return typeof chrome !== "undefined" && chrome.runtime?.id
    ? chrome.runtime.getURL("index.html") + "?fullpage=1"
    : window.location.origin
}

export default function AuthView({ onAuth, initialMode = "login" }) {
  const [mode, setMode] = useState(initialMode)
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [message, setMessage] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const hideTimerRef = useRef(null)

  const togglePassword = () => {
    if (showPassword) {
      setShowPassword(false)
      clearTimeout(hideTimerRef.current)
    } else {
      setShowPassword(true)
      clearTimeout(hideTimerRef.current)
      hideTimerRef.current = setTimeout(() => setShowPassword(false), 7000)
    }
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    setLoading(true)
    setError("")
    setMessage("")
    try {
      if (mode === "update-password") {
        if (password !== confirmPassword) throw new Error("Passwords don't match.")
        const { error } = await supabase.auth.updateUser({ password })
        if (error) throw error
        onAuth()
      } else if (mode === "reset") {
        const { error } = await supabase.auth.resetPasswordForEmail(email, {
          redirectTo: extensionRedirectUrl(),
        })
        if (error) throw error
        setMessage("Password reset link sent — check your email.")
        setMode("login")
      } else if (mode === "signup") {
        const { error } = await supabase.auth.signUp({
          email, password,
          options: { emailRedirectTo: extensionRedirectUrl() },
        })
        if (error) throw error
        setMessage("Check your email for a confirmation link.")
      } else {
        const { data, error } = await supabase.auth.signInWithPassword({ email, password })
        if (error) throw error
        onAuth(data.session)
      }
    } catch (e) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }

  const isExtension = typeof chrome !== "undefined" && !!chrome.runtime?.id

  const handleGoogle = async () => {
    setLoading(true)
    setError("")

    if (isExtension) {
      try {
        const redirectUrl = chrome.identity.getRedirectURL()
        const { data, error } = await supabase.auth.signInWithOAuth({
          provider: "google",
          options: { redirectTo: redirectUrl, skipBrowserRedirect: true },
        })
        if (error || !data?.url) throw error || new Error("No auth URL returned")

        chrome.identity.launchWebAuthFlow(
          { url: data.url, interactive: true },
          async (callbackUrl) => {
            if (chrome.runtime.lastError || !callbackUrl) {
              setError("Google sign-in was cancelled or failed.")
              setLoading(false)
              return
            }
            const parsed = new URL(callbackUrl)
            const hashParams = new URLSearchParams(parsed.hash.substring(1))

            // Tokens can be in hash (implicit) or query params (some Supabase versions)
            const accessToken = hashParams.get("access_token") || parsed.searchParams.get("access_token")
            const refreshToken = hashParams.get("refresh_token") || parsed.searchParams.get("refresh_token") || ""

            if (accessToken) {
              const { data: s, error: se } = await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken })
              if (se) setError(se.message)
              else onAuth(s.session)
              setLoading(false)
              return
            }

            // PKCE: exchange authorization code
            const code = parsed.searchParams.get("code") || hashParams.get("code")
            if (code) {
              const { data: s, error: se } = await supabase.auth.exchangeCodeForSession(code)
              if (se) setError(se.message)
              else onAuth(s.session)
              setLoading(false)
              return
            }

            // Show the actual error from the URL if present
            const oauthError = hashParams.get("error_description") || parsed.searchParams.get("error_description")
              || hashParams.get("error") || parsed.searchParams.get("error")
            // Neither a token nor a code nor a labeled error came back — almost
            // always an external config problem (Supabase's redirect-URL
            // allowlist, or the Google Cloud OAuth client), not a JS bug. Log
            // the full callback URL so a failed real-world test is diagnosable
            // from the console instead of a silent guess.
            if (!oauthError) console.error("[mirror] Google OAuth: no token/code/error in callback URL:", callbackUrl)
            setError(oauthError || "Could not retrieve session from Google.")
            setLoading(false)
          }
        )
      } catch (e) {
        setError(e.message)
        setLoading(false)
      }
      return
    }

    const { error } = await supabase.auth.signInWithOAuth({
      provider: "google",
      options: { redirectTo: window.location.origin },
    })
    if (error) {
      setError(error.message)
      setLoading(false)
    }
  }

  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center",
      justifyContent: "center", padding: 24 }}>
      <div style={{ width: "100%", maxWidth: 360 }} className="view-enter">

        {/* Logo */}
        <div style={{ textAlign: "center", marginBottom: 36 }}>
          <svg width="48" height="48" viewBox="0 0 52 52" fill="none" style={{ marginBottom: 14 }}>
            <defs>
              <linearGradient id="auth-g" x1="0" y1="0" x2="52" y2="0" gradientUnits="userSpaceOnUse">
                <stop stopColor="#1d4ed8"/><stop offset="1" stopColor="#0891b2"/>
              </linearGradient>
            </defs>
            <rect x="2"  y="20" width="6"  height="6"  rx="3" fill="url(#auth-g)" opacity=".35"/>
            <rect x="11" y="13" width="6"  height="13" rx="3" fill="url(#auth-g)" opacity=".6"/>
            <rect x="20" y="6"  width="8"  height="20" rx="4" fill="url(#auth-g)"/>
            <rect x="31" y="13" width="6"  height="13" rx="3" fill="url(#auth-g)" opacity=".6"/>
            <rect x="40" y="20" width="6"  height="6"  rx="3" fill="url(#auth-g)" opacity=".35"/>
            <line x1="0" y1="28" x2="52" y2="28" stroke="#1e2438" strokeWidth="1.25"/>
            <rect x="2"  y="29" width="6"  height="6"  rx="3" fill="url(#auth-g)" opacity=".15"/>
            <rect x="11" y="29" width="6"  height="13" rx="3" fill="url(#auth-g)" opacity=".27"/>
            <rect x="20" y="29" width="8"  height="20" rx="4" fill="url(#auth-g)" opacity=".33"/>
            <rect x="31" y="29" width="6"  height="13" rx="3" fill="url(#auth-g)" opacity=".27"/>
            <rect x="40" y="29" width="6"  height="6"  rx="3" fill="url(#auth-g)" opacity=".15"/>
          </svg>
          <h1 style={{ fontSize: 24, fontWeight: 700, margin: "0 0 6px",
            letterSpacing: "-0.5px", color: "#f0eeff" }}>
            mirror<span style={{ color: "#1d4ed8" }}>.</span>
          </h1>
          <p style={{ color: "#4a4865", fontSize: 13, margin: 0 }}>
            {mode === "login" && "Sign in to access your sessions."}
            {mode === "signup" && "Create an account to get started."}
            {mode === "reset" && "Enter your email to get a reset link."}
            {mode === "update-password" && "Choose a new password for your account."}
          </p>
        </div>

        {/* Card */}
        <div style={{
          background: "linear-gradient(#151922, #151922) padding-box, linear-gradient(135deg, rgba(29,78,216,0.35), rgba(34,211,238,0.35)) border-box",
          border: "1px solid transparent",
          borderRadius: 16, padding: 28,
          boxShadow: "0 8px 40px rgba(0,0,0,0.5)"
        }}>

          <form onSubmit={handleSubmit}>
            {mode !== "update-password" && (
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: "block", fontSize: 13, fontWeight: 500,
                marginBottom: 6, color: "#8b89aa" }}>Email</label>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)}
                required style={{ width: "100%", padding: "10px 12px", fontSize: 14 }} />
            </div>
            )}

            {mode === "reset" ? null : (
            <div style={{ marginBottom: mode === "update-password" ? 16 : 24 }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                <label style={{ fontSize: 13, fontWeight: 500, color: "#8b89aa" }}>
                  {mode === "update-password" ? "New password" : "Password"}
                </label>
                {mode === "login" && (
                  <button type="button"
                    onClick={() => { setMode("reset"); setError(""); setMessage("") }}
                    style={{ background: "none", border: "none", cursor: "pointer",
                      fontSize: 12, color: "#4a4865", padding: 0 }}>
                    Forgot password?
                  </button>
                )}
              </div>
              <div style={{ position: "relative" }}>
                <input
                  type={showPassword ? "text" : "password"}
                  value={password} onChange={e => setPassword(e.target.value)}
                  required minLength={6}
                  style={{ width: "100%", padding: "10px 40px 10px 12px", fontSize: 14 }}
                />
                <button type="button" onClick={togglePassword}
                  style={{ position: "absolute", right: 10, top: "50%",
                    transform: "translateY(-50%)", background: "none", border: "none",
                    cursor: "pointer", padding: 4, color: "#4a4865", lineHeight: 1,
                    display: "flex", alignItems: "center" }}>
                  {showPassword ? (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/>
                      <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/>
                      <line x1="1" y1="1" x2="23" y2="23"/>
                    </svg>
                  ) : (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                      <circle cx="12" cy="12" r="3"/>
                    </svg>
                  )}
                </button>
              </div>
            </div>
            )}

            {mode === "update-password" && (
            <div style={{ marginBottom: 24 }}>
              <label style={{ display: "block", fontSize: 13, fontWeight: 500,
                marginBottom: 6, color: "#8b89aa" }}>Confirm new password</label>
              <input
                type={showPassword ? "text" : "password"}
                value={confirmPassword} onChange={e => setConfirmPassword(e.target.value)}
                required minLength={6}
                style={{ width: "100%", padding: "10px 12px", fontSize: 14 }}
              />
            </div>
            )}

            {error && (
              <div style={{ background: "rgba(248,113,113,0.08)",
                border: "1px solid rgba(248,113,113,0.25)",
                borderRadius: 8, padding: 12, marginBottom: 16,
                fontSize: 13, color: "#f87171" }}>
                {error}
              </div>
            )}

            {message && (
              <div style={{ background: "rgba(52,211,153,0.08)",
                border: "1px solid rgba(52,211,153,0.25)",
                borderRadius: 8, padding: 12, marginBottom: 16,
                fontSize: 13, color: "#34d399" }}>
                {message}
              </div>
            )}

            <button type="submit" disabled={loading}
              className={loading ? "" : "btn-grad"}
              style={{ width: "100%", padding: "13px 24px",
                background: loading ? "#151922" : G,
                color: loading ? "#4a4865" : "white",
                border: loading ? "1px solid #1e2438" : "none",
                borderRadius: 8, fontSize: 15,
                cursor: loading ? "not-allowed" : "pointer", fontWeight: 600,
                boxShadow: loading ? "none" : "0 0 24px rgba(29,78,216,0.3)" }}>
              {loading ? "…" : mode === "login" ? "Sign in" : mode === "reset" ? "Send reset link" : mode === "update-password" ? "Update password" : "Create account"}
            </button>
          </form>

          {mode !== "update-password" && (
          <>
          {/* Divider */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "20px 0" }}>
            <div style={{ flex: 1, height: 1, background: "#1e2438" }} />
            <span style={{ fontSize: 12, color: "#4a4865" }}>or</span>
            <div style={{ flex: 1, height: 1, background: "#1e2438" }} />
          </div>

          {/* Google OAuth — handleGoogle() branches on isExtension internally
              (chrome.identity.launchWebAuthFlow vs. a normal redirect), so the
              button itself is shown in both contexts. */}
          <button type="button" onClick={handleGoogle} disabled={loading}
            style={{ width: "100%", padding: "11px 24px", fontSize: 14, fontWeight: 500,
              cursor: loading ? "not-allowed" : "pointer",
              background: "#0e1320", color: "#d4d2e8",
              border: "1px solid #1e2438", borderRadius: 8,
              display: "flex",
              alignItems: "center", justifyContent: "center", gap: 10,
              transition: "border-color 0.15s", opacity: loading ? 0.5 : 1 }}
            onMouseEnter={e => e.currentTarget.style.borderColor = "#4a4865"}
            onMouseLeave={e => e.currentTarget.style.borderColor = "#1e2438"}>
            <svg width="17" height="17" viewBox="0 0 24 24">
              <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
              <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
              <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/>
              <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
            </svg>
            Continue with Google
          </button>
          </>
          )}

          {mode !== "update-password" && (
          <div style={{ textAlign: "center", marginTop: 20 }}>
            <button
              onClick={() => { setMode(mode === "login" ? "signup" : "login"); setError(""); setMessage("") }}
              style={{ background: "none", border: "none", cursor: "pointer",
                color: "#4a4865", fontSize: 13 }}>
              {mode === "reset"
                ? "Back to sign in"
                : mode === "login"
                ? "Don't have an account? Sign up"
                : "Already have an account? Sign in"}
            </button>
          </div>
          )}
        </div>
      </div>
    </div>
  )
}