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:
Radosław Smoliński
2026-11-25 00:39:12 +01:00
co-authored by Claude Fable 5.2
parent cff355a541
commit 8fa71238ce
11 changed files with 345 additions and 35 deletions
+3 -1
View File
@@ -249,6 +249,8 @@ test('API: a staff password without the 2FA code opens nothing; with the code it
for (const path of guarded) {expect((await api.get(path)).status(), `${path} with the code`).toBe(200)}
const after = await (await api.post('/api/graphql', { data: { query } })).json()
expect(after.errors).toBeUndefined()
expect(after.data.SiteIntegration.smtpPassword).toBe('e2e-sink')
// the secret is stored (create-test-admin.ts) and never returned, also to a fully signed-in admin
expect(after.data.SiteIntegration.smtpPassword).toBe('********')
expect(JSON.stringify(after)).not.toContain('e2e-sink')
await api.dispose()
})
@@ -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}
+11 -2
View File
@@ -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' } }]
+10
View File
@@ -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}}.',
+81
View File
@@ -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
View File
@@ -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 }),
]
+10
View File
@@ -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 */
+2 -2
View File
@@ -270,7 +270,7 @@ describe('what must keep working', () => {
}
expect(closed).toEqual([])
const integrations = (await (await api('/globals/site-integrations', sessions.verified)).json()) as { smtpPassword?: string }
expect(integrations.smtpPassword).toBe('S3CRET')
expect(integrations.smtpPassword).toBe('********') // set, never returned (write-only secrets)
expect((await api('/globals/site-settings', sessions.verified, { body: JSON.stringify({ siteName: 'Verified' }), method: 'POST' })).status).toBe(200)
expect((await api('/ipal/cookie-scan', sessions.verified)).status).toBe(200)
// 400 = past the login and role gates, stopped by the missing recipient
@@ -280,7 +280,7 @@ describe('what must keep working', () => {
test('a fully verified admin reads Site integrations (GraphQL)', async () => {
const out = await gql(sessions.verified, '{ SiteIntegration { smtpPassword } FormSubmissions { totalDocs } }')
expect(out.errors).toBeUndefined()
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('********')
})
test('anonymous visitors still read the public globals and forms', async () => {
+1 -1
View File
@@ -76,7 +76,7 @@ test('beta.1: password only → refused; password and code → allowed (REST and
const full = [cookie, ...cookiesOf(verify)].join('; ')
const integrations = await get('/globals/site-integrations', { cookie: full })
expect(integrations.status).toBe(200)
expect(((await integrations.json()) as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
expect(((await integrations.json()) as { smtpPassword: string }).smtpPassword).toBe('********') // set, never returned (write-only secrets)
expect((await get('/form-submissions', { cookie: full })).status).toBe(200)
})
+183
View File
@@ -0,0 +1,183 @@
/**
* Write-only secrets over real HTTP: the SMTP password and the Turnstile secret key stored in the Site
* integrations global never come back — not over REST, not over GraphQL, not to an admin — while server code
* still reads them, and a save that does not carry a new value keeps the old one.
* Runs on SQLite by default, on Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js'
import { keepSecretBeforeValidate, maskSecretAfterRead, SECRET_CLEAR, SECRET_MASK, writeOnlySecret, writeOnlySecrets } from '../src/modules/secrets/writeOnly.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
const PASSWORD = 'a-long-test-password-1'
const SMTP = 'S3CRET-smtp-value'
const TURNSTILE = 'S3CRET-turnstile-value'
let server: TestServer
let payload: Payload
let auth: Record<string, string>
const stored = async () => (await payload.findGlobal({ slug: 'site-integrations' as never })) as unknown as Record<string, null | string | undefined>
const get = async () => fetch(`${server.url}/api/globals/site-integrations`, { headers: auth })
const save = async (data: Record<string, unknown>) => fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify(data), headers: { 'content-type': 'application/json', ...auth }, method: 'POST' })
const gql = async (query: string) => (await (await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: { 'content-type': 'application/json', ...auth }, method: 'POST' })).json()) as { data?: Record<string, Record<string, unknown>>; errors?: unknown[] }
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
db: testDatabase('secrets'),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
auth = { authorization: `JWT ${login.token}` }
// as a seed or the panel's first save would
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpUser: 'mailer', turnstileSecretKey: TURNSTILE, turnstileSiteKey: 'site-key' } as never })
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
describe('reading', () => {
test('REST: an admin gets "a value is set", never the value', async () => {
const res = await get()
expect(res.status).toBe(200)
const text = await res.text()
expect(text).not.toContain('S3CRET')
const body = JSON.parse(text) as Record<string, unknown>
expect(body.smtpPassword).toBe(SECRET_MASK)
expect(body.turnstileSecretKey).toBe(SECRET_MASK)
expect(body.smtpUser).toBe('mailer') // the rest of the global is as before
expect(body.turnstileSiteKey).toBe('site-key')
})
test('GraphQL: the same', async () => {
const out = await gql('{ SiteIntegration { smtpPassword turnstileSecretKey smtpUser } }')
expect(out.errors).toBeUndefined()
expect(JSON.stringify(out)).not.toContain('S3CRET')
expect(out.data?.SiteIntegration).toMatchObject({ smtpPassword: SECRET_MASK, smtpUser: 'mailer', turnstileSecretKey: SECRET_MASK })
})
test('server code (the Local API, access control off) reads the real values', async () => {
expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
})
test('the Local API WITH access control (a user, overrideAccess: false) is masked like the API', async () => {
const user = { ...(await payload.find({ collection: 'users' as never })).docs[0], collection: 'users' }
const doc = (await payload.findGlobal({ slug: 'site-integrations' as never, overrideAccess: false, user: user as never })) as unknown as Record<string, unknown>
expect(doc.smtpPassword).toBe(SECRET_MASK)
expect(doc.turnstileSecretKey).toBe(SECRET_MASK)
})
})
describe('saving', () => {
test('another field alone: the secrets stay, and the answer does not carry them', async () => {
const res = await save({ smtpHost: 'smtp2.example.com' })
expect(res.status).toBe(200)
expect(await res.text()).not.toContain('S3CRET')
expect(await stored()).toMatchObject({ smtpHost: 'smtp2.example.com', smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
})
test('what the panel sends back when nothing was typed (the mask), an empty value, null: kept', async () => {
for (const value of [SECRET_MASK, '', null]) {
expect((await save({ smtpPassword: value, turnstileSecretKey: value })).status).toBe(200)
expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
}
})
test('a whole document read over the API and saved back unchanged keeps the secrets', async () => {
const doc = (await (await get()).json()) as Record<string, unknown>
for (const key of ['id', 'createdAt', 'updatedAt', 'globalType']) {delete doc[key]}
expect((await save(doc)).status).toBe(200)
expect(await stored()).toMatchObject({ smtpPassword: SMTP, turnstileSecretKey: TURNSTILE })
})
test('a new value replaces the old one; the answer shows the mask', async () => {
const res = await save({ smtpPassword: 'S3CRET-new-value' })
const body = (await res.json()) as { result: Record<string, unknown> }
expect(JSON.stringify(body)).not.toContain('S3CRET')
expect(body.result.smtpPassword).toBe(SECRET_MASK)
expect(await stored()).toMatchObject({ smtpPassword: 'S3CRET-new-value', turnstileSecretKey: TURNSTILE })
})
test('SECRET_CLEAR removes the stored value; an empty field then reads as empty, not as "set"', async () => {
expect((await save({ smtpPassword: SECRET_CLEAR })).status).toBe(200)
expect((await stored()).smtpPassword ?? null).toBeNull()
const body = (await (await get()).json()) as Record<string, unknown>
expect(body.smtpPassword ?? null).toBeNull()
expect(body.turnstileSecretKey).toBe(SECRET_MASK)
// and an empty save on an empty field stays empty
expect((await save({ smtpPassword: '' })).status).toBe(200)
expect((await stored()).smtpPassword ?? null).toBeNull()
})
test('GraphQL mutation: the mask keeps, a value replaces', async () => {
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpPassword: SMTP } as never })
let out = await gql(`mutation { updateSiteIntegration(data: { smtpPassword: "${SECRET_MASK}", smtpUser: "mailer2" }) { smtpPassword smtpUser } }`)
expect(out.errors).toBeUndefined()
expect(out.data?.updateSiteIntegration).toMatchObject({ smtpPassword: SECRET_MASK, smtpUser: 'mailer2' })
expect((await stored()).smtpPassword).toBe(SMTP)
out = await gql('mutation { updateSiteIntegration(data: { smtpPassword: "S3CRET-by-graphql" }) { smtpPassword } }')
expect(JSON.stringify(out)).not.toContain('S3CRET')
expect((await stored()).smtpPassword).toBe('S3CRET-by-graphql')
})
})
describe('the building blocks', () => {
test('the hooks', () => {
const read = (value: unknown, overrideAccess?: boolean) => maskSecretAfterRead({ overrideAccess, value } as never)
expect(read('x', false)).toBe(SECRET_MASK)
expect(read('x', undefined)).toBe(SECRET_MASK) // not told that access control is off → masked
expect(read('x', true)).toBe('x')
expect(read('', false)).toBe('')
expect(read(null, false)).toBeNull()
const write = (value: unknown, originalDoc: unknown, p: (number | string)[] = ['token']) => keepSecretBeforeValidate({ originalDoc, path: p, value } as never)
expect(write('new', { token: 'old' })).toBe('new')
for (const nothing of [undefined, null, '', SECRET_MASK]) {expect(write(nothing, { token: 'old' })).toBe('old')}
expect(write(SECRET_CLEAR, { token: 'old' })).toBeNull()
expect(write(SECRET_MASK, undefined)).toBeNull() // nothing stored: never the mask itself
expect(write(SECRET_MASK, { token: SECRET_MASK })).toBe(SECRET_MASK) // (a stored mask is left; it cannot get there through these hooks)
expect(write('', { group: { items: [{ token: 'deep' }] } }, ['group', 'items', 0, 'token'])).toBe('deep')
})
test('writeOnlySecret keeps a field\'s own hooks; writeOnlySecrets finds fields inside tabs, rows and groups', () => {
const mine = () => 'mine'
const field = writeOnlySecret({ name: 'apiToken', type: 'text', hooks: { afterRead: [mine], beforeValidate: [mine] } })
expect(field.hooks?.afterRead).toEqual([mine, maskSecretAfterRead])
expect(field.hooks?.beforeValidate).toEqual([keepSecretBeforeValidate, mine])
const tree = writeOnlySecrets(
[{ type: 'tabs', tabs: [{ fields: [{ type: 'row', fields: [{ name: 'a', type: 'text' }, { name: 'b', type: 'text' }] }], label: 'T' }] }, { name: 'g', type: 'group', fields: [{ name: 'a', type: 'text' }] }],
['a'],
)
const flat = JSON.stringify(tree, (_k, v) => (typeof v === 'function' ? v.name : v))
expect(flat.match(/maskSecretAfterRead/g)).toHaveLength(2)
expect(flat).toContain('"name":"b","type":"text"}')
})
test('the opt-out: secrets: { writeOnly: false } leaves the fields as plain text fields', async () => {
const hooked = (fields: unknown) => JSON.stringify(fields, (_k, v) => (typeof v === 'function' ? v.name : v)).includes('maskSecretAfterRead')
expect(hooked(buildSiteIntegrations().fields)).toBe(true)
expect(hooked(buildSiteIntegrations({ writeOnlySecrets: false }).fields)).toBe(false)
const off = await ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, secrets: { writeOnly: false }, twoFactor: false })({ collections: [], secret: 'x' } as never)
expect(hooked(off.globals!.find((g) => g.slug === 'site-integrations')!.fields)).toBe(false)
})
})