-
Notifications
You must be signed in to change notification settings - Fork 17
Handle tenant API auth failures gracefully and drop Server Actions #1464
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
camilb
wants to merge
2
commits into
main
Choose a base branch
from
fix/api-auth-errors-and-server-actions
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 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
Some comments aren't visible on the classic Files Changed page.
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,35 @@ | ||
| import { routing } from '@prezly/sdk'; | ||
| import { type NextRequest, NextResponse } from 'next/server'; | ||
|
|
||
| import { environment } from '@/adapters/server'; | ||
|
|
||
| const PREZLY_API_URL = 'https://api.prezly.com'; | ||
|
|
||
| const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; | ||
|
|
||
| interface Props { | ||
| params: Promise<{ uuid: string }>; | ||
| } | ||
|
|
||
| export async function GET(request: NextRequest, { params }: Props) { | ||
| const { uuid } = await params; | ||
|
|
||
| if (!UUID_PATTERN.test(uuid)) { | ||
| return new NextResponse('Bad Request', { status: 400 }); | ||
| } | ||
|
|
||
| const env = environment(request.headers); | ||
|
|
||
| const { PREZLY_ACCESS_TOKEN, PREZLY_API_BASEURL = PREZLY_API_URL } = env; | ||
| const STORIES_ENDPOINT = `${PREZLY_API_BASEURL}${routing.storiesUrl}`; | ||
|
|
||
| const response = await fetch(`${STORIES_ENDPOINT}/${uuid}`, { | ||
|
camilb marked this conversation as resolved.
|
||
| headers: { | ||
| Authorization: `Bearer ${PREZLY_ACCESS_TOKEN}`, | ||
| Accept: 'application/pdf', | ||
| }, | ||
| redirect: 'manual', | ||
| }); | ||
|
|
||
| return NextResponse.json({ url: response.headers.get('location') }); | ||
|
camilb marked this conversation as resolved.
Outdated
|
||
| } | ||
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 @@ | ||
| const pino = require('pino'); | ||
|
|
||
| /** | ||
| * The Prezly SDK attaches the full API response headers (including a multi-KB | ||
| * CSP policy) to every `ApiError` it throws. They carry no diagnostic signal | ||
| * but multiply the size of every logged error, so strip them before the error | ||
| * is serialized. | ||
| */ | ||
| function serializeError(error) { | ||
| const serialized = pino.stdSerializers.err(error); | ||
|
|
||
| if (serialized && typeof serialized === 'object' && 'headers' in serialized) { | ||
|
camilb marked this conversation as resolved.
Outdated
|
||
| const { headers, ...rest } = serialized; | ||
| return rest; | ||
| } | ||
|
|
||
| return serialized; | ||
| } | ||
|
|
||
| const logger = (defaultConfig) => | ||
| pino({ | ||
| ...defaultConfig, | ||
| serializers: { | ||
| err: serializeError, | ||
| }, | ||
| }); | ||
|
|
||
| module.exports = { logger }; | ||
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,86 @@ | ||
| import { environment } from './environment'; | ||
|
|
||
| /* | ||
| * Rejected tenant credentials (revoked or rotated newsroom token) surface as | ||
| * SDK `ApiError`s on every request, but the framework-logged error does not | ||
| * identify the tenant. The helpers here detect those errors and log them with | ||
| * the request host and newsroom UUID, so the broken tenant can be found from | ||
| * the logs. | ||
| */ | ||
|
|
||
| const LOG_THROTTLE_MS = 60_000; | ||
|
|
||
| const lastLoggedAt = new Map<string, number>(); | ||
|
camilb marked this conversation as resolved.
|
||
|
|
||
| /** | ||
| * Detected by shape rather than `instanceof ApiError` — multiple copies of | ||
| * `@prezly/sdk` can end up in the server bundle, each with its own class. | ||
| */ | ||
| export function isApiAuthError(error: unknown): error is Error & { status: number } { | ||
| return ( | ||
| error instanceof Error && | ||
| 'status' in error && | ||
| (error.status === 401 || error.status === 403) | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Wraps a client object so that API auth failures thrown from any of its | ||
| * methods are logged with tenant identification (at most once per newsroom | ||
| * per minute). The error is rethrown untouched. | ||
| */ | ||
| export function reportApiAuthErrors<T extends object>(client: T, requestHeaders: Headers): T { | ||
|
camilb marked this conversation as resolved.
|
||
| return new Proxy(client, { | ||
| get(target, property, receiver) { | ||
| const value = Reflect.get(target, property, receiver); | ||
|
|
||
| if (typeof value !== 'function') { | ||
| return value; | ||
| } | ||
|
|
||
| return (...args: unknown[]) => { | ||
| const result = Reflect.apply(value, target, args); | ||
|
|
||
| if (result instanceof Promise) { | ||
| return result.catch((error: unknown) => { | ||
| logApiAuthError(error, requestHeaders); | ||
| throw error; | ||
| }); | ||
| } | ||
|
|
||
| return result; | ||
| }; | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| function logApiAuthError(error: unknown, requestHeaders: Headers) { | ||
| if (!isApiAuthError(error)) { | ||
| return; | ||
| } | ||
|
|
||
| const host = requestHeaders.get('x-forwarded-host') ?? requestHeaders.get('host') ?? 'unknown'; | ||
| const newsroom = identifyNewsroom(requestHeaders) ?? 'unknown'; | ||
|
|
||
| const key = `${newsroom}:${error.status}`; | ||
| const now = Date.now(); | ||
| const loggedAt = lastLoggedAt.get(key); | ||
|
|
||
| if (loggedAt !== undefined && now - loggedAt < LOG_THROTTLE_MS) { | ||
| return; | ||
| } | ||
| lastLoggedAt.set(key, now); | ||
|
|
||
| console.warn( | ||
| `Prezly API rejected the access token (${error.status}) for newsroom=${newsroom} host=${host}. ` + | ||
| 'The token configured for this site is likely revoked or rotated.', | ||
| ); | ||
| } | ||
|
|
||
| function identifyNewsroom(requestHeaders: Headers): string | undefined { | ||
| try { | ||
| return environment(requestHeaders).PREZLY_NEWSROOM_UUID; | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
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 |
|---|---|---|
| @@ -1,24 +1,13 @@ | ||
| 'use server'; | ||
| import type { Story } from '@prezly/sdk'; | ||
|
|
||
| import { routing, type Story } from '@prezly/sdk'; | ||
| import { headers } from 'next/headers'; | ||
| export async function getStoryPdfUrl(uuid: Story['uuid']): Promise<string | null> { | ||
| const response = await fetch(`/api/stories/${uuid}/pdf`); | ||
|
camilb marked this conversation as resolved.
|
||
|
|
||
| import { environment } from '@/adapters/server'; | ||
| if (!response.ok) { | ||
| return null; | ||
| } | ||
|
|
||
| const PREZLY_API_URL = 'https://api.prezly.com'; | ||
| const { url } = (await response.json()) as { url: string | null }; | ||
|
camilb marked this conversation as resolved.
Outdated
|
||
|
|
||
| export async function getStoryPdfUrl(uuid: Story['uuid']) { | ||
| const requestHeaders = await headers(); | ||
| const env = environment(requestHeaders); | ||
|
|
||
| const { PREZLY_ACCESS_TOKEN, PREZLY_API_BASEURL = PREZLY_API_URL } = env; | ||
| const STORIES_ENDPOINT = `${PREZLY_API_BASEURL}${routing.storiesUrl}`; | ||
|
|
||
| return fetch(`${STORIES_ENDPOINT}/${uuid}`, { | ||
| headers: { | ||
| Authorization: `Bearer ${PREZLY_ACCESS_TOKEN}`, | ||
| Accept: 'application/pdf', | ||
| }, | ||
| redirect: 'manual', | ||
| }).then((response) => response.headers.get('location')); | ||
| return url; | ||
| } | ||
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 |
|---|---|---|
| @@ -1,5 +1,3 @@ | ||
| 'use server'; | ||
|
|
||
| import { convert } from 'html-to-text'; | ||
|
|
||
| export async function htmlToText(html: string) { | ||
|
|
||
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.