Repository navigation
Fix HTTP transport and isolate branch previews #419
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
Open
admdly
wants to merge
11
commits into
main
Choose a base branch
from
codex/preview-http-transport
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
754995b
Preserve native fetch binding for HTTP API requests
admdly 1e2df6c
Use the staging API for directory branch previews
admdly f6d9ea6
Merge branch 'main' into codex/preview-http-transport
admdly f690aa0
Merge remote-tracking branch 'origin/main' into codex/preview-http-tr…
admdly 7cc4f95
Cover native HTTP fetch binding and clarify preview OAuth setup
admdly 9582585
Synchronize branch Preview OAuth callbacks
admdly fef26cd
Document the dedicated Preview OAuth client
admdly 9459caa
Use a named staging Preview for the directory
admdly dee45ce
Deploy the named staging Preview with the main build
admdly 1566558
Merge branch 'main' into codex/preview-http-transport
admdly c161ff5
Merge branch 'main' into codex/preview-http-transport
admdly 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| name: Preview Authentication | ||
|
|
||
| on: | ||
| check_run: | ||
| types: [completed] | ||
| delete: | ||
| workflow_dispatch: | ||
| schedule: | ||
| - cron: '17 * * * *' | ||
|
|
||
| permissions: | ||
| contents: read | ||
| id-token: write | ||
|
|
||
| concurrency: | ||
| group: preview-auth | ||
| cancel-in-progress: false | ||
|
|
||
| jobs: | ||
| callbacks: | ||
| if: >- | ||
| github.event_name != 'check_run' || | ||
| (github.event.check_run.app.slug == 'cloudflare-workers-and-pages' && | ||
| github.event.check_run.name == 'Workers Builds: extensions' && | ||
| github.event.check_run.conclusion == 'success') | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 5 | ||
| steps: | ||
| - name: Checkout trusted workflow code | ||
| uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 | ||
| with: | ||
| ref: main | ||
| persist-credentials: false | ||
| - name: Setup Node.js | ||
| uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 | ||
| with: | ||
| node-version: '26' | ||
| - name: Reconcile Preview callbacks | ||
| run: node scripts/sync-preview-callbacks.ts | ||
| env: | ||
| GITHUB_TOKEN: ${{ github.token }} | ||
| CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} | ||
| CLOUDFLARE_PREVIEW_READ_TOKEN: ${{ secrets.CLOUDFLARE_PREVIEW_READ_TOKEN }} |
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,110 @@ | ||||||
| import { pathToFileURL } from 'node:url'; | ||||||
|
|
||||||
| type Preview = { name: string; urls: string[] }; | ||||||
| type Page<T> = { result: T[]; result_info?: { total_count?: number } }; | ||||||
|
|
||||||
| async function readJson<T>( | ||||||
| fetcher: typeof fetch, | ||||||
| url: string, | ||||||
| token: string, | ||||||
| ): Promise<T> { | ||||||
| const response = await fetcher(url, { | ||||||
| headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' }, | ||||||
| signal: AbortSignal.timeout(30_000), | ||||||
| }); | ||||||
| if (!response.ok) | ||||||
| throw new Error(`Metadata request failed: HTTP ${response.status}`); | ||||||
| return response.json() as Promise<T>; | ||||||
| } | ||||||
|
|
||||||
| export async function syncPreviewCallbacks( | ||||||
| options: { | ||||||
| githubToken: string; | ||||||
| cloudflareToken: string; | ||||||
| cloudflareAccount: string; | ||||||
| oidcRequestUrl: string; | ||||||
| oidcRequestToken: string; | ||||||
| }, | ||||||
| fetcher: typeof fetch = (...args) => globalThis.fetch(...args), | ||||||
| ) { | ||||||
| const branches = new Set<string>(); | ||||||
| for (let page = 1; ; page++) { | ||||||
| const rows = await readJson<Array<{ name: string }>>( | ||||||
| fetcher, | ||||||
| `https://api.github.com/repos/FOSSBilling/extensions/branches?per_page=100&page=${page}`, | ||||||
| options.githubToken, | ||||||
| ); | ||||||
| rows.forEach((row) => branches.add(row.name)); | ||||||
| if (rows.length < 100) break; | ||||||
| } | ||||||
| const base = `https://api.cloudflare.com/client/v4/accounts/${options.cloudflareAccount}`; | ||||||
| const service = await readJson<{ | ||||||
| result: { default_environment: { script: { tag: string } } }; | ||||||
| }>(fetcher, `${base}/workers/services/extensions`, options.cloudflareToken); | ||||||
| const previews: Preview[] = []; | ||||||
| for (let page = 1; ; page++) { | ||||||
| const data = await readJson<Page<Preview>>( | ||||||
| fetcher, | ||||||
| `${base}/workers/workers/${service.result.default_environment.script.tag}/previews?per_page=100&page=${page}`, | ||||||
| options.cloudflareToken, | ||||||
| ); | ||||||
| previews.push(...data.result); | ||||||
| if ( | ||||||
| data.result.length < 100 || | ||||||
| previews.length >= (data.result_info?.total_count ?? Infinity) | ||||||
| ) | ||||||
| break; | ||||||
| } | ||||||
| const callbacks = [ | ||||||
| ...new Set( | ||||||
| previews | ||||||
| .filter( | ||||||
| (preview) => | ||||||
| preview.name === 'staging' || | ||||||
| (preview.name !== 'main' && branches.has(preview.name)), | ||||||
| ) | ||||||
| .flatMap((preview) => preview.urls) | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: A Preview without a routable Prompt for AI agents
Suggested change
|
||||||
| .map((origin) => new URL('/auth/callback', origin).href), | ||||||
| ), | ||||||
| ].sort(); | ||||||
| const endpoint = | ||||||
| 'https://auth.fossbilling.net/integrations/extensions-preview-callbacks'; | ||||||
| const oidcUrl = new URL(options.oidcRequestUrl); | ||||||
| oidcUrl.searchParams.set('audience', endpoint); | ||||||
| const { value } = await readJson<{ value: string }>( | ||||||
| fetcher, | ||||||
| oidcUrl.href, | ||||||
| options.oidcRequestToken, | ||||||
| ); | ||||||
| const response = await fetcher(endpoint, { | ||||||
| method: 'PUT', | ||||||
| headers: { | ||||||
| Authorization: `Bearer ${value}`, | ||||||
| 'Content-Type': 'application/json', | ||||||
| }, | ||||||
| body: JSON.stringify(callbacks), | ||||||
| signal: AbortSignal.timeout(30_000), | ||||||
| }); | ||||||
| if (response.status !== 204) | ||||||
| throw new Error(`Callback registration failed: HTTP ${response.status}`); | ||||||
| return callbacks.length; | ||||||
| } | ||||||
|
|
||||||
| if ( | ||||||
| process.argv[1] && | ||||||
| import.meta.url === pathToFileURL(process.argv[1]).href | ||||||
| ) { | ||||||
| function required(name: string) { | ||||||
| const value = process.env[name]; | ||||||
| if (!value) throw new Error(`${name} is required`); | ||||||
| return value; | ||||||
| } | ||||||
| const count = await syncPreviewCallbacks({ | ||||||
| githubToken: required('GITHUB_TOKEN'), | ||||||
| cloudflareToken: required('CLOUDFLARE_PREVIEW_READ_TOKEN'), | ||||||
| cloudflareAccount: required('CLOUDFLARE_ACCOUNT_ID'), | ||||||
| oidcRequestUrl: required('ACTIONS_ID_TOKEN_REQUEST_URL'), | ||||||
| oidcRequestToken: required('ACTIONS_ID_TOKEN_REQUEST_TOKEN'), | ||||||
| }); | ||||||
| console.log(`Registered ${count} active Preview callbacks.`); | ||||||
| } | ||||||
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,28 @@ | ||
| import { afterEach, describe, expect, it, vi } from 'vitest'; | ||
| import { getApplicationEnv } from '@/platform/cloudflare'; | ||
|
|
||
| vi.mock('cloudflare:workers', () => ({ | ||
|
admdly marked this conversation as resolved.
Resolved
|
||
| env: { | ||
| EXTENSIONS_API_TRANSPORT: 'http', | ||
| EXTENSIONS_API_BASE_URL: 'https://staging-api.example.test', | ||
| }, | ||
| })); | ||
|
|
||
| afterEach(() => vi.unstubAllGlobals()); | ||
|
|
||
| describe('Cloudflare HTTP transport', () => { | ||
| it('calls native fetch with its global receiver', async () => { | ||
| const request = new Request( | ||
| 'https://staging-api.example.test/extensions/v2', | ||
| ); | ||
| const response = new Response('{}'); | ||
| vi.stubGlobal('fetch', function (this: unknown, input: RequestInfo | URL) { | ||
| expect(this).toBe(globalThis); | ||
| expect(input).toBe(request); | ||
| return Promise.resolve(response); | ||
| }); | ||
|
|
||
| const env = getApplicationEnv(); | ||
| await expect(env.extensionsApi.fetch(request)).resolves.toBe(response); | ||
| }); | ||
| }); | ||
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,82 @@ | ||
| import { describe, expect, it } from 'vitest'; | ||
| import { syncPreviewCallbacks } from '../scripts/sync-preview-callbacks'; | ||
|
|
||
| const options = { | ||
| githubToken: 'github-token', | ||
| cloudflareToken: 'read-only-cloudflare-token', | ||
| cloudflareAccount: 'account', | ||
| oidcRequestUrl: 'https://oidc.example.test/token?request=1', | ||
| oidcRequestToken: 'oidc-request-token', | ||
| }; | ||
|
|
||
| describe('Preview callback reconciliation', () => { | ||
| it('registers staging and live branch Preview URLs and removes orphaned callbacks', async () => { | ||
| let callbacks: unknown; | ||
| const fetcher = (async ( | ||
| input: string | URL | Request, | ||
| init?: RequestInit, | ||
| ) => { | ||
| const url = String(input); | ||
| if (url.startsWith('https://api.github.com/')) { | ||
| return Response.json([{ name: 'feature/test' }, { name: 'main' }]); | ||
| } | ||
| if (url.endsWith('/workers/services/extensions')) { | ||
| return Response.json({ | ||
| result: { default_environment: { script: { tag: 'worker' } } }, | ||
| }); | ||
| } | ||
| if (url.includes('/previews?')) { | ||
| return Response.json({ | ||
| result: [ | ||
| { | ||
| name: 'staging', | ||
| urls: ['https://staging-extensions.fossbilling.workers.dev'], | ||
| }, | ||
| { | ||
| name: 'feature/test', | ||
| urls: ['https://feature-test-extensions.fossbilling.workers.dev'], | ||
| }, | ||
| { | ||
| name: 'deleted-branch', | ||
| urls: [ | ||
| 'https://deleted-branch-extensions.fossbilling.workers.dev', | ||
| ], | ||
| }, | ||
| ], | ||
| }); | ||
| } | ||
| if (url.startsWith('https://oidc.example.test/')) { | ||
| expect(new URL(url).searchParams.get('audience')).toBe( | ||
| 'https://auth.fossbilling.net/integrations/extensions-preview-callbacks', | ||
| ); | ||
| return Response.json({ value: 'short-lived-oidc-token' }); | ||
| } | ||
| expect(url).toBe( | ||
| 'https://auth.fossbilling.net/integrations/extensions-preview-callbacks', | ||
| ); | ||
| expect(init?.method).toBe('PUT'); | ||
| expect(new Headers(init?.headers).get('Authorization')).toBe( | ||
| 'Bearer short-lived-oidc-token', | ||
| ); | ||
| callbacks = JSON.parse(String(init?.body)); | ||
| return new Response(null, { status: 204 }); | ||
| }) as typeof fetch; | ||
| expect(await syncPreviewCallbacks(options, fetcher)).toBe(2); | ||
| expect(callbacks).toEqual([ | ||
| 'https://feature-test-extensions.fossbilling.workers.dev/auth/callback', | ||
| 'https://staging-extensions.fossbilling.workers.dev/auth/callback', | ||
| ]); | ||
| }); | ||
|
|
||
| it('does not clear callbacks when metadata cannot be read', async () => { | ||
| const calls: string[] = []; | ||
| const fetcher = (async (input: string | URL | Request) => { | ||
| calls.push(String(input)); | ||
| return new Response(null, { status: 403 }); | ||
| }) as typeof fetch; | ||
| await expect(syncPreviewCallbacks(options, fetcher)).rejects.toThrow( | ||
| 'HTTP 403', | ||
| ); | ||
| expect(calls).toHaveLength(1); | ||
| }); | ||
| }); |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1: The Preview API is being addressed with
script.tag, which is an immutable deployed script tag rather than theextensionsWorker name. Use the configured Worker name/ID for/workers/workers/{worker}/previews; otherwise the workflow cannot read previews and never reconciles callbacks.Prompt for AI agents