M1 (1): stored secrets are write-only
smtpPassword and turnstileSecretKey in the Site integrations global are returned
as '********' to every read that goes through access control (REST, GraphQL, the
panel's form state); the Local API with access control off still gets the value.
A save that sends nothing, an empty value or the mask keeps the stored one;
'[[clear]]' removes it. MaskedField says that a value is set and offers to
remove it. Off: secrets: { writeOnly: false }. writeOnlySecret(s) and the hooks
are exported for a project's own fields.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
cff355a541
commit
8fa71238ce
@@ -6,21 +6,21 @@ import { FieldDescription, FieldLabel, useField, useTranslation } from '@payload
|
||||
import { useState } from 'react'
|
||||
|
||||
import { ipalT } from '../../../modules/admin-i18n/t.js'
|
||||
import { SECRET_CLEAR, SECRET_MASK } from '../../../modules/secrets/writeOnly.js'
|
||||
|
||||
/**
|
||||
* Masked text input for sensitive values (SMTP password, R2 secret key,
|
||||
* Turnstile secret key, etc.).
|
||||
* Text input for a secret (SMTP password, Turnstile secret key, …).
|
||||
*
|
||||
* Renders the value as a password field (••••) so secrets aren't shown in
|
||||
* plaintext on screen — protecting against shoulder-surfing and accidental
|
||||
* exposure when the panel is open. The value is still stored and returned
|
||||
* normally (UI masking, NOT hashing or encryption), because the plugin must
|
||||
* read it back to authenticate with SMTP/R2/Turnstile. A toggle reveals the
|
||||
* value when an authorised editor genuinely needs to check it.
|
||||
* With a write-only field (modules/secrets/writeOnly.ts — the default for the plugin's own
|
||||
* secrets) the stored value never reaches the browser: the field arrives as `SECRET_MASK`.
|
||||
* The input then stays empty and says that a value is set; typing replaces it, leaving it
|
||||
* alone keeps it, "Remove the stored value" clears it on save.
|
||||
*
|
||||
* Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput,
|
||||
* because TextInput doesn't expose inputProps, so there's no way to switch its
|
||||
* inner input to type="password".
|
||||
* Without write-only (`secrets: { writeOnly: false }`, or a plain text field of a project) the
|
||||
* value itself arrives; it is drawn as dots with a Show / Hide toggle, as before.
|
||||
*
|
||||
* Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput, because
|
||||
* TextInput doesn't expose inputProps, so its inner input cannot be type="password".
|
||||
*
|
||||
* Assigned via a field's admin.components.Field. Works on any `text` field.
|
||||
*/
|
||||
@@ -32,6 +32,9 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
|
||||
// A string or one string per language — FieldLabel / FieldDescription translate it.
|
||||
const label = field?.label || field?.name || path
|
||||
const description = field?.admin?.description
|
||||
const stored = value === SECRET_MASK // a value is set on the server; this is not it
|
||||
const removing = value === SECRET_CLEAR
|
||||
const link = { background: 'none', border: 'none', cursor: 'pointer', font: 'inherit', opacity: 0.75, padding: '.25rem .5rem', textDecoration: 'underline', whiteSpace: 'nowrap' } as const
|
||||
|
||||
return (
|
||||
<div className="field-type text masked-field">
|
||||
@@ -45,28 +48,32 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
|
||||
className="field-type__input"
|
||||
id={`field-${path}`}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
placeholder={stored ? '••••••••' : undefined}
|
||||
style={{ flex: 1 }}
|
||||
type={revealed ? 'text' : 'password'}
|
||||
value={value ?? ''}
|
||||
value={stored || removing ? '' : (value ?? '')}
|
||||
/>
|
||||
<button
|
||||
onClick={() => setRevealed((r) => !r)}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
font: 'inherit',
|
||||
opacity: 0.75,
|
||||
padding: '.25rem .5rem',
|
||||
textDecoration: 'underline',
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
{ipalT(t as never, revealed ? 'maskedHide' : 'maskedShow')}
|
||||
</button>
|
||||
{stored ? (
|
||||
<button onClick={() => setValue(SECRET_CLEAR)} style={link} type="button">
|
||||
{ipalT(t as never, 'maskedRemove')}
|
||||
</button>
|
||||
) : removing ? (
|
||||
<button onClick={() => setValue(SECRET_MASK)} style={link} type="button">
|
||||
{ipalT(t as never, 'maskedKeep')}
|
||||
</button>
|
||||
) : (
|
||||
<button onClick={() => setRevealed((r) => !r)} style={link} type="button">
|
||||
{ipalT(t as never, revealed ? 'maskedHide' : 'maskedShow')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{stored || removing ? (
|
||||
<p className="field-description" role="status" style={{ margin: '.25rem 0 0' }}>
|
||||
{ipalT(t as never, stored ? 'maskedSet' : 'maskedRemoved')}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{description && typeof description !== 'function' ? (
|
||||
<FieldDescription description={description} path={path} />
|
||||
) : null}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Field, GlobalConfig } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../../modules/access/index.js'
|
||||
import { INTEGRATION_SECRET_FIELDS, writeOnlySecrets } from '../../modules/secrets/writeOnly.js'
|
||||
import { indexNowFields } from '../../modules/seo/indexNow.js'
|
||||
import { analyticsFields } from './fields/analytics.js'
|
||||
import { smtpFields } from './fields/smtp.js'
|
||||
@@ -9,6 +10,12 @@ import { turnstileFields } from './fields/turnstile.js'
|
||||
type BuildSiteIntegrationsArgs = {
|
||||
/** Extra fields injected by the client project */
|
||||
additionalFields?: Field[]
|
||||
/**
|
||||
* The stored secrets (`smtpPassword`, `turnstileSecretKey`) are write-only: reads through
|
||||
* access control get `SECRET_MASK`, never the value (modules/secrets/writeOnly.ts). Default
|
||||
* true; `false` = the value is returned to whoever may read the global, as before.
|
||||
*/
|
||||
writeOnlySecrets?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,7 +32,9 @@ type BuildSiteIntegrationsArgs = {
|
||||
*/
|
||||
export function buildSiteIntegrations({
|
||||
additionalFields,
|
||||
writeOnlySecrets: writeOnly = true,
|
||||
}: BuildSiteIntegrationsArgs = {}): GlobalConfig {
|
||||
const secret = (fields: Field[]) => (writeOnly ? writeOnlySecrets(fields, INTEGRATION_SECRET_FIELDS) : fields)
|
||||
return {
|
||||
slug: 'site-integrations',
|
||||
access: {
|
||||
@@ -48,10 +57,10 @@ export function buildSiteIntegrations({
|
||||
en: 'Cloudflare Turnstile checks that forms are sent by people, not bots.',
|
||||
pl: 'Cloudflare Turnstile sprawdza, czy formularze wysyłają ludzie, a nie boty.',
|
||||
},
|
||||
fields: turnstileFields,
|
||||
fields: secret(turnstileFields),
|
||||
label: { en: 'Spam protection', pl: 'Ochrona przed spamem' },
|
||||
},
|
||||
{ fields: smtpFields, label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } },
|
||||
{ fields: secret(smtpFields), label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } },
|
||||
{ fields: indexNowFields, label: { en: 'IndexNow', pl: 'IndexNow' } },
|
||||
...(additionalFields?.length
|
||||
? [{ fields: additionalFields, label: { en: 'More', pl: 'Więcej' } }]
|
||||
|
||||
@@ -332,6 +332,16 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit
|
||||
export { findImportMapFile, missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
|
||||
export { changedViewKeys, copyViews, SAFE_TOTP_VIEW, safeAdminBack, totpViewImportKey, wrapTotpViews } from './modules/security/totp/safeBack.js'
|
||||
export type { SafeBackContext, SafeBackRule, TotpViewComponent } from './modules/security/totp/safeBack.js'
|
||||
export {
|
||||
INTEGRATION_SECRET_FIELDS,
|
||||
isSecretMask,
|
||||
keepSecretBeforeValidate,
|
||||
maskSecretAfterRead,
|
||||
SECRET_CLEAR,
|
||||
SECRET_MASK,
|
||||
writeOnlySecret,
|
||||
writeOnlySecrets,
|
||||
} from './modules/secrets/writeOnly.js'
|
||||
export { requireSecondFactor, secondFactorPassed, twoFactorSetupDeadline, twoFactorSetupState } from './modules/security/totp/secondFactor.js'
|
||||
export type { TwoFactorSetupState } from './modules/security/totp/secondFactor.js'
|
||||
export { SETUP_FROM_FIELD } from './modules/security/totp/secondFactor.js'
|
||||
|
||||
@@ -10,6 +10,10 @@ export const integrationsTexts = defineTexts({
|
||||
|
||||
// Masked secret field
|
||||
maskedHide: 'Hide',
|
||||
maskedKeep: 'Keep the stored value',
|
||||
maskedRemove: 'Remove the stored value',
|
||||
maskedRemoved: 'The stored value will be removed when you save.',
|
||||
maskedSet: 'A value is set. It is not shown; type a new one to replace it.',
|
||||
maskedShow: 'Show',
|
||||
|
||||
// Status banner on an integration's tab (IntegrationStatusBanner)
|
||||
@@ -63,6 +67,10 @@ export const integrationsTexts = defineTexts({
|
||||
alertsUnknownError: 'Nieznany błąd.',
|
||||
|
||||
maskedHide: 'Ukryj',
|
||||
maskedKeep: 'Zostaw zapisaną wartość',
|
||||
maskedRemove: 'Usuń zapisaną wartość',
|
||||
maskedRemoved: 'Zapisana wartość zostanie usunięta po zapisaniu.',
|
||||
maskedSet: 'Wartość jest ustawiona. Nie jest wyświetlana; wpisz nową, aby ją zastąpić.',
|
||||
maskedShow: 'Pokaż',
|
||||
|
||||
statusCode: 'Kod: {{code}}.',
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { Field, FieldHook } from 'payload'
|
||||
|
||||
/**
|
||||
* Write-only secrets: a field whose stored value never leaves the server.
|
||||
*
|
||||
* `smtpPassword` and `turnstileSecretKey` live in the Site integrations global — the panel is
|
||||
* their source. Until now `MaskedField` only drew dots on screen: the value itself went to the
|
||||
* browser, and REST and GraphQL returned it to whoever could read the global. A stolen admin
|
||||
* session, or any way past the global's read rule, was a working mailbox password.
|
||||
*
|
||||
* With `writeOnlySecret` the value is:
|
||||
* - **returned as `SECRET_MASK`** when it is set (and as it is when empty) to every read that
|
||||
* goes through access control — REST, GraphQL, the panel's form state, versions;
|
||||
* - **returned in full** only to a Local API read with access control off (the default of
|
||||
* `payload.findGlobal` / `payload.find` on the server) — how the plugin's own code reads it;
|
||||
* - **kept** when a save sends nothing, an empty value or the mask back;
|
||||
* - **replaced** when a save sends a new value, and **removed** when it sends `SECRET_CLEAR`.
|
||||
*
|
||||
* Off for the two built-in fields: `secrets: { writeOnly: false }`. For a field of your own:
|
||||
* `writeOnlySecret({ name: 'apiToken', type: 'text', admin: { components: { Field: '@intecion/ipal-kit/admin#MaskedField' } } })`.
|
||||
*/
|
||||
|
||||
/** What a read gets instead of a stored secret: "a value is set". */
|
||||
export const SECRET_MASK = '********'
|
||||
/** Send this as the value to remove a stored secret (an empty value keeps it). */
|
||||
export const SECRET_CLEAR = '[[clear]]'
|
||||
|
||||
/** True when a value read from the API means "a secret is stored" rather than being one. */
|
||||
export const isSecretMask = (value: unknown): boolean => value === SECRET_MASK
|
||||
|
||||
const dig = (doc: unknown, path: (number | string)[]): unknown => path.reduce<unknown>((at, key) => (at && typeof at === 'object' ? (at as Record<string, unknown>)[key as string] : undefined), doc)
|
||||
|
||||
/** Reads: the stored value only for server code that reads with access control off. */
|
||||
export const maskSecretAfterRead: FieldHook = ({ overrideAccess, value }) => {
|
||||
if (overrideAccess === true) {return value}
|
||||
return typeof value === 'string' && value !== '' ? SECRET_MASK : value
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes: nothing, an empty value or the mask keep what is stored; `SECRET_CLEAR` removes it;
|
||||
* anything else is the new secret. Runs in `beforeValidate`, so every later hook (the global's
|
||||
* own `beforeChange` included) already sees the real value.
|
||||
*/
|
||||
export const keepSecretBeforeValidate: FieldHook = ({ originalDoc, path, value }) => {
|
||||
if (value === SECRET_CLEAR) {return null}
|
||||
if (value === undefined || value === null || value === '' || value === SECRET_MASK) {
|
||||
const stored = dig(originalDoc, path)
|
||||
// The original document is read by Payload with access control off, so this is the real value;
|
||||
// a mask here would mean it was not — never store the mask.
|
||||
return typeof stored === 'string' && stored !== SECRET_MASK ? stored : (stored ?? null)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/** Adds the two hooks to a field (a text field as a rule). The field's own hooks stay, and run around them. */
|
||||
export function writeOnlySecret<F extends Field>(field: F): F {
|
||||
const own = (field as { hooks?: { afterRead?: FieldHook[]; beforeValidate?: FieldHook[] } }).hooks ?? {}
|
||||
return {
|
||||
...field,
|
||||
custom: { ...(field as { custom?: Record<string, unknown> }).custom, ipalWriteOnly: true },
|
||||
hooks: {
|
||||
...own,
|
||||
afterRead: [...(own.afterRead ?? []), maskSecretAfterRead],
|
||||
beforeValidate: [keepSecretBeforeValidate, ...(own.beforeValidate ?? [])],
|
||||
},
|
||||
} as F
|
||||
}
|
||||
|
||||
/** `writeOnlySecret` for the named fields, wherever they are in the tree (tabs, rows, groups, collapsibles). */
|
||||
export function writeOnlySecrets(fields: Field[], names: string[]): Field[] {
|
||||
return fields.map((field) => {
|
||||
const f = field as { fields?: Field[]; name?: string; tabs?: { fields: Field[] }[] } & Field
|
||||
if (f.name && names.includes(f.name) && !('fields' in f && Array.isArray(f.fields))) {return writeOnlySecret(field)}
|
||||
if (Array.isArray(f.tabs)) {return { ...f, tabs: f.tabs.map((tab) => ({ ...tab, fields: writeOnlySecrets(tab.fields, names) })) } as Field}
|
||||
if (Array.isArray(f.fields)) {return { ...f, fields: writeOnlySecrets(f.fields, names) } as Field}
|
||||
return field
|
||||
})
|
||||
}
|
||||
|
||||
/** The plugin's own stored secrets (Site integrations). */
|
||||
export const INTEGRATION_SECRET_FIELDS = ['smtpPassword', 'turnstileSecretKey']
|
||||
+1
-1
@@ -612,7 +612,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
: { searchFields: typeof searchSettings === 'function' ? searchSettings(searchSettingsFields) : searchSettingsFields }),
|
||||
systemPageFields,
|
||||
}),
|
||||
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
|
||||
buildSiteIntegrations({ additionalFields: options.integrationsFields, writeOnlySecrets: options.secrets?.writeOnly !== false }),
|
||||
withFillLocales('global', buildCookieSettings(), fillLocales['cookie-settings']),
|
||||
buildNotifications({ lightbox: options.lightbox === true }),
|
||||
]
|
||||
|
||||
@@ -186,6 +186,16 @@ export type IpalOptions = {
|
||||
* SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)
|
||||
* and enables locale-aware metadata helpers.
|
||||
*/
|
||||
/**
|
||||
* Stored secrets. `smtpPassword` and `turnstileSecretKey` (Site integrations)
|
||||
* are **write-only** by default: REST, GraphQL and the panel get `'********'`
|
||||
* ("a value is set"), never the value; a save that sends nothing, an empty
|
||||
* value or the mask keeps what is stored, `'[[clear]]'` removes it. Server
|
||||
* code reads the real value through the Local API (access control off, the
|
||||
* default). `{ writeOnly: false }` = the value is returned to whoever may
|
||||
* read the global, as before 1.16.7. docs/security.md "Stored secrets".
|
||||
*/
|
||||
secrets?: { writeOnly?: false }
|
||||
seo?: SeoOption
|
||||
|
||||
/** Additional fields injected into SiteSettings global */
|
||||
|
||||
Reference in New Issue
Block a user