Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 36 additions & 33 deletions apps/extension/background/messages/fetch-frame.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,25 @@
import type { getFrame } from "frames.js"
import {
isParseFramesWithReportsResult,
isParseResult
} from "@frames.js/render/helpers"
import type { GETResponse } from "@frames.js/render/next"

import type { PlasmoMessaging } from "@plasmohq/messaging"

import { framesProxyUrl } from "~constants"

export interface FetchFrameRequestParams {
postType?: string
}

export interface FetchFrameRequestOptions extends Omit<RequestInit, "body"> {
body?: object
}

export type FetchFrameRequest = {
url: string
options?: FetchFrameRequestOptions
params?: FetchFrameRequestParams
}

export type FetchFrameResponseSuccess =
| ReturnType<typeof getFrame>
| { message: string }

export type FetchFrameResponse =
| { body: FetchFrameResponseSuccess }
| { error: string }
export type FetchFrameResponse = GETResponse | { error: string }

const defaultHeaders = {
"User-Agent": "fetch"
}

// @todo refactor, also provide status of the response, headers, etc
// @todo this probably doesn't need a POST handling because it apparently loads only GET requests
const handler: PlasmoMessaging.MessageHandler<
FetchFrameRequest,
FetchFrameResponse
Expand All @@ -39,27 +29,40 @@ const handler: PlasmoMessaging.MessageHandler<
throw new Error("Request body is missing")
}

const { url, options, params } = req.body
const { url } = req.body

const targetUrl = new URL(framesProxyUrl)

if (options?.method === "POST") {
targetUrl.searchParams.set("postType", params?.postType || "post")
targetUrl.searchParams.set("postUrl", url)
} else {
targetUrl.searchParams.set("url", url)
}
targetUrl.searchParams.set("url", url)

const body = await fetch(targetUrl.toString(), {
method: options?.method || "GET",
const response = await fetch(targetUrl.toString(), {
method: "GET",
headers: {
...defaultHeaders,
...options?.headers
},
body: options?.body ? JSON.stringify(options.body) : undefined
}).then((resp) => resp.json())
...defaultHeaders
}
})

console.log(await response.clone().text())

if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`)
}

const responseBody = await response.json()

if (isParseFramesWithReportsResult(responseBody)) {
return res.send(responseBody)
} else if (isParseResult(responseBody)) {
return res.send(responseBody)
} else if (
typeof responseBody === "object" &&
!!responseBody &&
"message" in responseBody
) {
return res.send({ message: responseBody.message })
}

return res.send({ body })
throw new Error("Invalid response")
} catch (err) {
console.error(err)
return res.send({ error: err instanceof Error ? err.message : String(err) })
Expand Down
55 changes: 25 additions & 30 deletions apps/extension/background/messages/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,35 @@
import type { PlasmoMessaging } from "@plasmohq/messaging"

const DEV_USER = process.env.PLASMO_PUBLIC_DEV_USER
const isDevelopment = process.env.NODE_ENV === "development"

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
// fake login for development
if (isDevelopment && DEV_USER) {
if (
req.body.url.startsWith(
"https://api.warpcast.com/v2/signed-key-request?token="
) &&
req.body.options.method === "GET"
) {
const result = JSON.parse(DEV_USER)
return res.send({
json: { result },
status: 200
})
export type FetchResponse =
| {
error: string
}
}
try {
const resp = await fetch(req.body.url, req.body.options)
if (!resp.ok) {
return res.send({ status: resp.status, error: resp.statusText })
| {
status: number
headers: Record<string, string>
body: string
}
const text = await resp.text()
let json
try {
json = JSON.parse(text)
} catch (e) {
// ignore

const handler: PlasmoMessaging.MessageHandler<
{ url: string; options: RequestInit },
FetchResponse
> = async (req, res) => {
try {
if (!req.body) {
throw new Error("Request body is missing")
}
return res.send({ json, text, status: resp.status })

const response = await fetch(req.body.url, req.body.options)
const body = await response.text()

return res.send({
status: response.status,
headers: Object.fromEntries(response.headers),
body
})
} catch (e) {
console.error(e)
return res.send({ error: (e as any).message })
return res.send({ error: e instanceof Error ? e.message : String(e) })
}
}

Expand Down
13 changes: 8 additions & 5 deletions apps/extension/components/farcaster-auth-ui.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import type { FarcasterSigner } from "@xframes/shared/types"
import type {
FarcasterSignerImpersonating,
FarcasterSignerPendingApproval
} from "@frames.js/render"
import QRCode from "qrcode.react"

export type FarcasterAuthUIProps = {
signer?: FarcasterSigner | null
signer?: FarcasterSignerPendingApproval | FarcasterSignerImpersonating | null
logout?: () => void
}

export const FarcasterAuthUI = ({ signer, logout }: FarcasterAuthUIProps) => {
if (signer?.status !== "pending_approval") {
if (!signer || signer.status !== "pending_approval") {
return null
}

Expand Down Expand Up @@ -43,7 +46,7 @@ export const FarcasterAuthUI = ({ signer, logout }: FarcasterAuthUIProps) => {
Scan with your phone camera
</div>
<div className="aspect-square w-full bg-white border border-violet-950/10 rounded flex items-center justify-center">
<QRCode value={signer?.signerApprovalUrl} size={192} />
<QRCode value={signer.signerApprovalUrl} size={192} />
</div>
</div>
<div className="flex flex-row w-full gap-2 items-center">
Expand All @@ -53,7 +56,7 @@ export const FarcasterAuthUI = ({ signer, logout }: FarcasterAuthUIProps) => {
</div>
<div className="w-full text-center">
<a
href={signer?.signerApprovalUrl}
href={signer.signerApprovalUrl}
target="_blank"
className="text-md font-semibold hover:underline text-violet-950 hover:text-violet-950/75 active:text-violet-950/50"
rel="noopener noreferrer">
Expand Down
12 changes: 6 additions & 6 deletions apps/extension/components/frame-iframe.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default function FrameIFrame({ url, frameId, theme }: FrameIFrameProps) {
})
}, [frameId])

useEffect(() => {
/*useEffect(() => {
if (signer?.status !== "approved") {
return
}
Expand All @@ -59,19 +59,19 @@ export default function FrameIFrame({ url, frameId, theme }: FrameIFrameProps) {
signer.publicKey
)
})
}, [signer])
}, [signer])*/

useEffect(() => {
/*useEffect(() => {
const iframe = iframeRef.current?.contentWindow
if (!iframe) {
return
}
// TODO set origin
// signer === null - not loaded yet
// signer === undefined - loaded and "empty"
if (signer === undefined) {
if (!signer) {
sendMessageToEmbed(iframe, { type: "signed_out" })
} else if (signer?.status === "approved") {
} else if (signer.status === "approved") {
sendMessageToEmbed(iframe, { type: "signed_in", signer })
}
}, [signer, iframeRef])
Expand All @@ -86,7 +86,7 @@ export default function FrameIFrame({ url, frameId, theme }: FrameIFrameProps) {
return createMessageConsumer("embed_sign_out", () => {
logout?.()
})
}, [logout])
}, [logout])*/

const handleLoad = useCallback(() => {
setLoading(false)
Expand Down
2 changes: 2 additions & 0 deletions apps/extension/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ export const frameEmbedProxyUrl =
process.env.PLASMO_FRAME_EMBED_PROXY_URL || `${baseProxyUrl}/embed`
export const eventsProxyUrl =
process.env.PLASMO_EVENTS_PROXY_URL || `${baseProxyUrl}/api/v1/events`

export const FARCASTER_SIGNER_STORAGE_KEY = "farcasterSigner"
19 changes: 11 additions & 8 deletions apps/extension/contents/auth-modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,42 +59,45 @@ const AUTO_CLOSE_TIMEOUT_SECONDS = 10
const AuthModal: React.FC<PlasmoCSUIProps> = () => {
const [shown, setShown] = useState(false)

const { hasSigner, signer, logout } = useFarcasterIdentity({
const { signer, logout } = useFarcasterIdentity({
enablePolling: true
})

const loggedIn = hasSigner
const pendingApproval = signer?.status === "pending_approval"

useEffect(() => {
let timeout: NodeJS.Timeout | undefined
if (!pendingApproval && loggedIn && shown) {

if (signer?.status === "approved" && shown) {
timeout = setTimeout(
() => setShown(false),
AUTO_CLOSE_TIMEOUT_SECONDS * 1000
)
} else {
setShown(!!pendingApproval)
setShown(signer?.status === "pending_approval")
}

return () => {
if (timeout) {
clearTimeout(timeout)
}
}
}, [pendingApproval, loggedIn, shown])
}, [pendingApproval, signer?.status, shown])

const handleClose = () => {
// do not logout from this modal
if (!loggedIn) {
// remove the identity if it is not approved
// this cleans up the pending approval state
if (signer?.status !== "approved") {
logout?.()
}

setShown(false)
}

return (
<AuthModalContainer onClick={handleClose} shown={shown}>
<div className="relative p-8 flex flex-col justify-between items-center bg-white rounded-md text-violet-950 text-base min-w-72 gap-5">
{loggedIn ? (
{signer?.status === "approved" ? (
<div className="flex flex-col gap-2 max-w-72 text-center items-center">
<div className="text-xl font-semibold">Logged in succesfully!</div>
<div className="text-lg">
Expand Down
1 change: 1 addition & 0 deletions apps/extension/contents/frames.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ export const render: PlasmoRender<any> = async (
)

const frame = await fetchFrame(frameUrl)
console.log({ frame })
if (!isValidFrame(frame)) {
return
}
Expand Down
Loading
Loading