-
-
Notifications
You must be signed in to change notification settings - Fork 39
Add Cloudflare Turnstile to grant applications #909
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
3501e59
feat: add Cloudflare Turnstile siteverify helper
dergigi 82ff442
feat: require Turnstile verification on grant apply APIs
dergigi 2fcd911
feat: embed Turnstile on grant application submit
dergigi d863dde
test: cover Turnstile gating on grant apply APIs
dergigi 48b52ae
style: fix prettier lint failures for Turnstile changes
dergigi 2daf590
fix: clear stale Turnstile readiness and split reset APIs
dergigi ec50f20
fix: explain disabled submit when Turnstile is not ready
dergigi 78598e5
chore: update Turnstile site key after domain refresh
dergigi 5c2bc13
fix: use implicit Turnstile render for dynamic grant forms
dergigi 2dfedc5
fix: allow Cloudflare Turnstile in Content-Security-Policy
dergigi df40c16
style: center Turnstile widget with more vertical space
dergigi a2645c6
chore: add preview-only ?step= shortcut for apply forms
dergigi 1561a21
style: remove Turnstile helper copy under apply submit
dergigi aace483
style: left-align Turnstile widget on apply forms
dergigi 8c0c96a
style: center Turnstile widget on apply forms
dergigi 7b87b2a
chore: remove temporary apply form ?step= shortcut
dergigi 910090e
fix: remount Turnstile and submit with a single token
dergigi e33f387
style: fix prettier lint on turnstile submit path
dergigi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import Script from 'next/script' | ||
| import { | ||
| forwardRef, | ||
| useCallback, | ||
| useEffect, | ||
| useImperativeHandle, | ||
| useRef, | ||
| useState, | ||
| } from 'react' | ||
|
|
||
| const TURNSTILE_SCRIPT = 'https://challenges.cloudflare.com/turnstile/v0/api.js' | ||
| const SITE_KEY = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY | ||
|
|
||
| declare global { | ||
| interface Window { | ||
| turnstile?: { | ||
| render: ( | ||
| element: HTMLElement, | ||
| options: { | ||
| sitekey: string | ||
| action?: string | ||
| callback?: (token: string) => void | ||
| 'expired-callback'?: () => void | ||
| 'error-callback'?: () => void | ||
| } | ||
| ) => string | ||
| reset: (widgetId?: string) => void | ||
| remove: (widgetId?: string) => void | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export interface TurnstileWidgetHandle { | ||
| getToken: () => string | undefined | ||
| waitForToken: () => Promise<string> | ||
| reset: () => Promise<string> | ||
| } | ||
|
|
||
| interface TurnstileWidgetProps { | ||
| onTokenChange?: (token: string | undefined) => void | ||
| } | ||
|
|
||
| const TurnstileWidget = forwardRef<TurnstileWidgetHandle, TurnstileWidgetProps>( | ||
| function TurnstileWidget({ onTokenChange }, ref) { | ||
| const containerRef = useRef<HTMLDivElement>(null) | ||
| const widgetIdRef = useRef<string>() | ||
| const tokenRef = useRef<string>() | ||
| const waitersRef = useRef<Array<(token: string) => void>>([]) | ||
| const [scriptReady, setScriptReady] = useState(false) | ||
|
|
||
| const setToken = useCallback( | ||
| (token: string | undefined) => { | ||
| tokenRef.current = token | ||
| onTokenChange?.(token) | ||
| if (token) { | ||
| const waiters = waitersRef.current | ||
| waitersRef.current = [] | ||
| waiters.forEach((resolve) => resolve(token)) | ||
| } | ||
| }, | ||
| [onTokenChange] | ||
| ) | ||
|
|
||
| const waitForToken = useCallback(() => { | ||
| if (tokenRef.current) return Promise.resolve(tokenRef.current) | ||
| return new Promise<string>((resolve) => { | ||
| waitersRef.current.push(resolve) | ||
| }) | ||
| }, []) | ||
|
|
||
| const reset = useCallback(() => { | ||
| setToken(undefined) | ||
| if (widgetIdRef.current && window.turnstile) { | ||
| window.turnstile.reset(widgetIdRef.current) | ||
| } | ||
| return waitForToken() | ||
| }, [setToken, waitForToken]) | ||
|
dergigi marked this conversation as resolved.
Outdated
|
||
|
|
||
| useImperativeHandle( | ||
| ref, | ||
| () => ({ | ||
| getToken: () => tokenRef.current, | ||
| waitForToken, | ||
| reset, | ||
| }), | ||
| [reset, waitForToken] | ||
| ) | ||
|
|
||
| useEffect(() => { | ||
| if (!scriptReady || !SITE_KEY || !containerRef.current || !window.turnstile) { | ||
| return | ||
| } | ||
| if (widgetIdRef.current) return | ||
|
|
||
| widgetIdRef.current = window.turnstile.render(containerRef.current, { | ||
| sitekey: SITE_KEY, | ||
| action: 'turnstile-spin-v2', | ||
| callback: (token) => setToken(token), | ||
| 'expired-callback': () => setToken(undefined), | ||
| 'error-callback': () => setToken(undefined), | ||
| }) | ||
|
|
||
| return () => { | ||
| if (widgetIdRef.current && window.turnstile) { | ||
| window.turnstile.remove(widgetIdRef.current) | ||
| widgetIdRef.current = undefined | ||
| } | ||
| } | ||
| }, [scriptReady, setToken]) | ||
|
|
||
| if (!SITE_KEY) { | ||
| return ( | ||
| <p className="text-sm text-red-600"> | ||
| Turnstile is not configured (`NEXT_PUBLIC_TURNSTILE_SITE_KEY`). | ||
| </p> | ||
| ) | ||
| } | ||
|
|
||
| return ( | ||
| <> | ||
| <Script | ||
| src={`${TURNSTILE_SCRIPT}?render=explicit`} | ||
| strategy="afterInteractive" | ||
| onLoad={() => setScriptReady(true)} | ||
| /> | ||
| <div | ||
| ref={containerRef} | ||
| className="cf-turnstile" | ||
| data-sitekey={SITE_KEY} | ||
| data-action="turnstile-spin-v2" | ||
| /> | ||
| </> | ||
| ) | ||
| } | ||
| ) | ||
|
|
||
| export default TurnstileWidget | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| /** @jest-environment node */ | ||
| /* eslint-env jest, node */ | ||
|
|
||
| process.env.GH_ACCESS_TOKEN = 'test-token' | ||
| process.env.GH_ORG = 'OpenSats' | ||
| process.env.GH_APP_REPO = 'applications' | ||
| process.env.TURNSTILE_SECRET = 'test-turnstile-secret' | ||
|
|
||
| jest.mock('@octokit/rest', () => { | ||
| const create = jest.fn() | ||
| return { | ||
| Octokit: jest.fn().mockImplementation(() => ({ | ||
| rest: { issues: { create } }, | ||
| })), | ||
| __create: create, | ||
| } | ||
| }) | ||
|
|
||
| jest.mock('@/utils/turnstile', () => { | ||
| const actual = jest.requireActual('@/utils/turnstile') | ||
| return { | ||
| ...actual, | ||
| assertTurnstile: jest.fn(), | ||
| } | ||
| }) | ||
|
|
||
| const { __create: createIssue } = require('@octokit/rest') | ||
| const { assertTurnstile } = require('@/utils/turnstile') | ||
| const handler = require('../../pages/api/github.ts').default | ||
|
|
||
| function responseMock() { | ||
| return { | ||
| statusCode: undefined, | ||
| payload: undefined, | ||
| headers: {}, | ||
| status(code) { | ||
| this.statusCode = code | ||
| return this | ||
| }, | ||
| json(payload) { | ||
| this.payload = payload | ||
| return this | ||
| }, | ||
| setHeader(name, value) { | ||
| this.headers[name] = value | ||
| }, | ||
| end(payload) { | ||
| this.payload = payload | ||
| return this | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| const validApplication = { | ||
| project_name: 'Test project', | ||
| your_name: 'Applicant', | ||
| short_description: 'Description', | ||
| potential_impact: 'Impact', | ||
| proposed_budget: '1 BTC', | ||
| main_focus: 'nostr', | ||
| 'cf-turnstile-response': 'test-token', | ||
| } | ||
|
|
||
| describe('/api/github', () => { | ||
| beforeEach(() => { | ||
| createIssue.mockReset() | ||
| createIssue.mockResolvedValue({ data: { number: 1 } }) | ||
| assertTurnstile.mockReset() | ||
| assertTurnstile.mockResolvedValue(true) | ||
| jest.spyOn(console, 'log').mockImplementation(() => undefined) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| jest.restoreAllMocks() | ||
| }) | ||
|
|
||
| it('creates an issue when Turnstile verification succeeds', async () => { | ||
| const response = responseMock() | ||
|
|
||
| await handler({ method: 'POST', body: validApplication }, response) | ||
|
|
||
| expect(response.statusCode).toBe(200) | ||
| expect(response.payload).toEqual({ message: 'success' }) | ||
| expect(createIssue).toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('rejects requests that fail Turnstile verification', async () => { | ||
| assertTurnstile.mockResolvedValue(false) | ||
| const response = responseMock() | ||
|
|
||
| await handler({ method: 'POST', body: validApplication }, response) | ||
|
|
||
| expect(response.statusCode).toBe(403) | ||
| expect(response.payload.message).not.toBe('success') | ||
| expect(createIssue).not.toHaveBeenCalled() | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.