Stable admin import map without R2 env, read-only media, Cookie Settings save-button migration

buildR2Storage registered nothing without R2_* env, so `pnpm dev` / generate:importmap in dev
wrote an importMap.js without S3ClientUploadHandler — committed, the production admin (R2 on)
rendered a blank page with no console error (hit vanstev.pl). The injected s3Storage is now
always registered (enabled: false without R2 → local disk); storage-s3 still adds its client
handler, so the import map is identical in every environment. ipal-audit flags an import map
without the handler.

R2_PUBLIC_URL alone (absolute, outside production) = read-only media: URLs from the media
domain, upload/delete refused with 403 — local dev against a production database without
bucket keys. ipalEnvRules allows it in development.

Cookie Settings (MongoDB): the 1.11.1 rename buttons.save → savePreferences lost the texts on
the first save; onInit copies the old value (all locales) when the new field is missing.
getConsentTexts read the old field as a string, Mongo returns the raw { pl, en } map.

Also: context.ipalSkipAutoFill (SKIP_AUTO_FILL) — save without meta / aiSummary auto-fill;
createPageRoute redirects the homepage under its own slug (homeAlias, default 'redirect');
ipal-audit: multi-line tsconfig exclude, numeronyms (a11y) not "numbered fields",
`${prefix}/${slug}` links and slugs typed into links detected, clearer panel-language message.
Docs: fallback-on-save in i18n.md, `pnpm up --latest` and the stale-token 401 in PROGRAMISTA §1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-21 16:45:03 +02:00
co-authored by Claude Opus 5.5
parent 2c3195c4e1
commit e1431a7c49
25 changed files with 511 additions and 23 deletions
+108 -6
View File
@@ -1,4 +1,6 @@
import type { Plugin } from 'payload'
import type { CollectionConfig, Plugin } from 'payload'
import { APIError } from 'payload'
type GenerateFileURL = (args: { filename: string; prefix?: string }) => string
@@ -16,6 +18,8 @@ export type S3StorageFactory = (options: {
forcePathStyle: boolean
region: string
}
/** false = registered but inactive: no S3 client, local disk, admin import map unchanged. */
enabled?: boolean
}) => Plugin
export type BuildR2StorageDeps = {
@@ -58,17 +62,43 @@ export const buildR2Storage = (
const accessKeyId = process.env.R2_ACCESS_KEY_ID
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY
// Any missing → skip R2, fall back to local disk. Warn so it's not silent.
const { s3Storage } = deps
// Any missing → local disk. The adapter is still REGISTERED (enabled: false) when the
// project injects it: storage-s3 adds its admin client handler to the import map even
// when disabled, so `pnpm dev` / `generate:importmap` without R2 env writes the same
// importMap.js as production. Before 1.12.2 a no-op was returned here — an import map
// generated in dev lacked S3ClientUploadHandler and the production admin rendered blank.
if (!bucket || !endpoint || !accessKeyId || !secretAccessKey) {
const readOnly = readOnlyPublicUrl({ accessKeyId, bucket, endpoint, secretAccessKey })
const disabled: Plugin | undefined = s3Storage
? s3Storage({
bucket: bucket ?? '',
collections: Object.fromEntries(collections.map((slug) => [slug, true as const])),
config: {
credentials: { accessKeyId: accessKeyId ?? '', secretAccessKey: secretAccessKey ?? '' },
endpoint: endpoint ?? '',
forcePathStyle: true,
region: 'auto',
},
enabled: false,
})
: undefined
return (config) => {
// Only warn when SOME vars are set (partial config = likely a mistake).
if (bucket || endpoint || accessKeyId || secretAccessKey) {
if (readOnly) {
console.warn(
`[ipal] R2 storage: read-only media from ${readOnly} (R2_PUBLIC_URL without credentials) — ` +
'uploads are disabled. Set all R2_* to upload, or none for local disk.',
)
} else if (bucket || endpoint || accessKeyId || secretAccessKey) {
// Only warn when SOME vars are set (partial config = likely a mistake).
console.warn(
'[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' +
'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.',
)
}
return config
const next = disabled ? disabled(config) : config
return readOnly ? withReadOnlyMedia(next as Parameters<Plugin>[0], collections, readOnly) : next
}
}
@@ -95,7 +125,6 @@ export const buildR2Storage = (
// R2 env is complete → the adapter is required. Fail loudly at boot rather
// than silently storing media on the container disk (lost on redeploy).
const { s3Storage } = deps
if (!s3Storage) {
throw new Error(
'[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +
@@ -121,3 +150,76 @@ export const buildR2Storage = (
},
})
}
/**
* Read-only media: outside production, R2_PUBLIC_URL (absolute) with none of the
* credentials → files are read from the public domain. For a local dev pointed at
* a production database: images show, nothing can be uploaded to (or deleted from)
* the real bucket. Returns the base URL, or null when the mode doesn't apply.
*/
function readOnlyPublicUrl(env: {
accessKeyId?: string
bucket?: string
endpoint?: string
secretAccessKey?: string
}): null | string {
if (process.env.NODE_ENV === 'production') {return null}
if (env.accessKeyId || env.bucket || env.endpoint || env.secretAccessKey) {return null}
const url = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '')
return url && /^https?:\/\/[^/\s]+/i.test(url) ? url : null
}
type UploadDoc = {
filename?: null | string
sizes?: Record<string, { filename?: null | string; url?: null | string } | null>
thumbnailURL?: null | string
url?: null | string
}
function withReadOnlyMedia(
config: Parameters<Plugin>[0],
collections: string[],
publicUrl: string,
): Parameters<Plugin>[0] {
const fileUrl = (filename: string) => `${publicUrl}/${encodeURIComponent(filename)}`
return {
...config,
collections: (config.collections ?? []).map((collection): CollectionConfig => {
if (!collections.includes(collection.slug)) {return collection}
return {
...collection,
hooks: {
...collection.hooks,
afterRead: [
...(collection.hooks?.afterRead ?? []),
({ doc }: { doc: UploadDoc }) => {
if (!doc?.filename) {return doc}
doc.url = fileUrl(doc.filename)
if (doc.thumbnailURL) {
const thumb = doc.sizes?.thumbnail?.filename
doc.thumbnailURL = thumb ? fileUrl(thumb) : doc.url
}
for (const size of Object.values(doc.sizes ?? {})) {
if (size?.filename) {size.url = fileUrl(size.filename)}
}
return doc
},
],
beforeOperation: [
...(collection.hooks?.beforeOperation ?? []),
({ args, operation }) => {
const req = (args as { req?: { file?: unknown } }).req
if (operation === 'delete' || ((operation === 'create' || operation === 'update') && req?.file)) {
throw new APIError(
'Media is read-only here (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.',
403,
)
}
return args
},
],
},
}
}),
}
}