IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are not touched. package.json keeps the five old bin names beside the five new ones. The old names stop working in this commit and come back as aliases in the next; docs follow. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
414a4702df
commit
0a4f001797
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* Entry point: @intecion/ipal-kit/doctor
|
||||
*
|
||||
* ipal-doctor's building blocks — the rules, the runner, the formatters and the status
|
||||
* iapl-doctor's building blocks — the rules, the runner, the formatters and the status
|
||||
* collector — for a project that wants to wrap, filter or extend the checks (docs/doctor.md).
|
||||
* Node only (reads files, runs commands). The command itself: `pnpm exec ipal-doctor`.
|
||||
* Node only (reads files, runs commands). The command itself: `pnpm exec iapl-doctor`.
|
||||
*/
|
||||
export { DOCTOR_USAGE, expandSites, parseDoctorArgs, runDoctorCli } from '../modules/doctor/cli.js'
|
||||
export { formatDriftTable, formatReport } from '../modules/doctor/format.js'
|
||||
|
||||
+4
-4
@@ -8,10 +8,10 @@
|
||||
* doesn't exist in target module").
|
||||
*
|
||||
* // src/instrumentation.ts
|
||||
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'
|
||||
* import { assertEnv, iaplEnvRules } from '@intecion/ipal-kit/env'
|
||||
* export function register() {
|
||||
* if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true }))
|
||||
* if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(iaplEnvRules({ storage: true }))
|
||||
* }
|
||||
*/
|
||||
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from '../modules/env/index.js'
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from '../modules/env/index.js'
|
||||
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules } from '../modules/env/index.js'
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures } from '../modules/env/index.js'
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Entry point: @intecion/ipal-kit/starter
|
||||
*
|
||||
* The building blocks of `ipal-kit create` (docs/project-starter.md): the answers schema, the variant and
|
||||
* The building blocks of `iapl create` (docs/project-starter.md): the answers schema, the variant and
|
||||
* placeholder transforms, the bundle and the renderer — Node built-ins only, no Payload. Use them to script
|
||||
* your own generator or to check a reference tree; the command itself is `pnpm dlx @intecion/ipal-kit create`.
|
||||
*/
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Entry point: @intecion/ipal-kit/tokens
|
||||
*
|
||||
* Design tokens with no Payload, React or Next import — safe in src/design/tokens.ts,
|
||||
* the `ipal-tokens` CLI, next/og images and e-mail templates. docs/design-tokens.md.
|
||||
* the `iapl-tokens` CLI, next/og images and e-mail templates. docs/design-tokens.md.
|
||||
*/
|
||||
export {
|
||||
COLOR_DEFAULTS,
|
||||
@@ -17,9 +17,9 @@ export {
|
||||
fluidClamp,
|
||||
INVERSE_SCOPE,
|
||||
INVERSE_SELECTOR,
|
||||
IPAL_BREAKPOINTS,
|
||||
IPAL_TOKENS,
|
||||
ipalVar,
|
||||
IAPL_BREAKPOINTS,
|
||||
IAPL_TOKENS,
|
||||
iaplVar,
|
||||
LEGACY_DARK_ROLES,
|
||||
LIGHT_SELECTOR,
|
||||
parseColor,
|
||||
@@ -27,4 +27,4 @@ export {
|
||||
STATIC_DEFAULTS,
|
||||
tokensToCss,
|
||||
} from '../modules/tokens/index.js'
|
||||
export type { ColorInput, ColorRole, ContrastRow, FluidRange, IpalTokenName, RemValue, TokensInput } from '../modules/tokens/index.js'
|
||||
export type { ColorInput, ColorRole, ContrastRow, FluidRange, IaplTokenName, RemValue, TokensInput } from '../modules/tokens/index.js'
|
||||
|
||||
@@ -31,9 +31,9 @@ export async function migrateCookieSettingsSaveButton(payload: BasePayload): Pro
|
||||
[{ $set: { 'buttons.savePreferences': '$buttons.save' } }],
|
||||
)
|
||||
if (result.modifiedCount) {
|
||||
payload.logger.info('[ipal] Cookie Settings: buttons.save copied to buttons.savePreferences (1.11.1 rename).')
|
||||
payload.logger.info('[iapl] Cookie Settings: buttons.save copied to buttons.savePreferences (1.11.1 rename).')
|
||||
}
|
||||
} catch (error) {
|
||||
payload.logger.error({ err: error, msg: '[ipal] Cookie Settings: could not migrate buttons.save → buttons.savePreferences' })
|
||||
payload.logger.error({ err: error, msg: '[iapl] Cookie Settings: could not migrate buttons.save → buttons.savePreferences' })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ const lightboxText = (
|
||||
|
||||
/**
|
||||
* The "Image viewer" group (`lightbox`) — labels of the image viewer (<LightboxProvider texts>).
|
||||
* Added by ipalKit `lightbox: true`; exported so a project can place it in its
|
||||
* Added by iapl `lightbox: true`; exported so a project can place it in its
|
||||
* own global instead.
|
||||
*/
|
||||
export const lightboxNotificationFields: Field = {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { lightboxNotificationFields, notificationsFields } from './fields.js'
|
||||
* Builds the Notifications global (shown as "Form messages") — localized action-result texts. Readable by
|
||||
* any authenticated panel user; server-side helpers read it with overrideAccess
|
||||
* so the frontend can resolve texts without a session. `lightbox` adds the
|
||||
* image-viewer labels (ipalKit `lightbox: true`).
|
||||
* image-viewer labels (iapl `lightbox: true`).
|
||||
*/
|
||||
export function buildNotifications({ lightbox = false }: { lightbox?: boolean } = {}): GlobalConfig {
|
||||
return {
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { TextFieldClientComponent } from 'payload'
|
||||
import { FieldDescription, FieldLabel, useField, useTranslation } from '@payloadcms/ui'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { ipalT } from '../../../modules/admin-i18n/t.js'
|
||||
import { iaplT } from '../../../modules/admin-i18n/t.js'
|
||||
import { SECRET_CLEAR, SECRET_MASK } from '../../../modules/secrets/constants.js'
|
||||
|
||||
/**
|
||||
@@ -55,15 +55,15 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
|
||||
/>
|
||||
{stored ? (
|
||||
<button onClick={() => setValue(SECRET_CLEAR)} style={link} type="button">
|
||||
{ipalT(t as never, 'maskedRemove')}
|
||||
{iaplT(t as never, 'maskedRemove')}
|
||||
</button>
|
||||
) : removing ? (
|
||||
<button onClick={() => setValue(SECRET_MASK)} style={link} type="button">
|
||||
{ipalT(t as never, 'maskedKeep')}
|
||||
{iaplT(t as never, 'maskedKeep')}
|
||||
</button>
|
||||
) : (
|
||||
<button onClick={() => setRevealed((r) => !r)} style={link} type="button">
|
||||
{ipalT(t as never, revealed ? 'maskedHide' : 'maskedShow')}
|
||||
{iaplT(t as never, revealed ? 'maskedHide' : 'maskedShow')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
@@ -76,7 +76,7 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
|
||||
|
||||
{stored || removing ? (
|
||||
<p className="field-description" role="status" style={{ margin: '.25rem 0 0' }}>
|
||||
{ipalT(t as never, stored ? 'maskedSet' : 'maskedRemoved')}
|
||||
{iaplT(t as never, stored ? 'maskedSet' : 'maskedRemoved')}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useTranslation } from '@payloadcms/ui'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { ipalT } from '../../../modules/admin-i18n/t.js'
|
||||
import { iaplT } from '../../../modules/admin-i18n/t.js'
|
||||
|
||||
/**
|
||||
* Admin UI: a small "send test e-mail" tool for the SiteIntegrations e-mail tab.
|
||||
@@ -15,7 +15,7 @@ import { ipalT } from '../../../modules/admin-i18n/t.js'
|
||||
*/
|
||||
export const TestEmailButton = () => {
|
||||
const { t } = useTranslation()
|
||||
const text = (key: Parameters<typeof ipalT>[1], vars?: Record<string, unknown>) => ipalT(t as never, key, vars)
|
||||
const text = (key: Parameters<typeof iaplT>[1], vars?: Record<string, unknown>) => iaplT(t as never, key, vars)
|
||||
const [to, setTo] = useState('')
|
||||
const [withFile, setWithFile] = useState(false)
|
||||
const [status, setStatus] = useState<
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { GlobalConfig } from 'payload'
|
||||
|
||||
/** Slugs of the globals the plugin adds. */
|
||||
export type IpalGlobalSlug = 'cookie-settings' | 'notifications' | 'site-integrations' | 'site-settings'
|
||||
export type IaplGlobalSlug = 'cookie-settings' | 'notifications' | 'site-integrations' | 'site-settings'
|
||||
|
||||
/**
|
||||
* A project's change to one plugin global:
|
||||
@@ -13,7 +13,7 @@ export type IpalGlobalSlug = 'cookie-settings' | 'notifications' | 'site-integra
|
||||
*/
|
||||
export type GlobalOverride = ((global: GlobalConfig) => GlobalConfig) | Partial<GlobalConfig>
|
||||
|
||||
export type GlobalOverrides = Partial<Record<IpalGlobalSlug, GlobalOverride>>
|
||||
export type GlobalOverrides = Partial<Record<IaplGlobalSlug, GlobalOverride>>
|
||||
|
||||
type Hooks = NonNullable<GlobalConfig['hooks']>
|
||||
|
||||
@@ -30,7 +30,7 @@ function mergeHooks(base: GlobalConfig['hooks'], extra: GlobalConfig['hooks']):
|
||||
export function applyGlobalOverrides(globals: GlobalConfig[], overrides: GlobalOverrides | undefined): GlobalConfig[] {
|
||||
if (!overrides) {return globals}
|
||||
return globals.map((global) => {
|
||||
const override = overrides[global.slug as IpalGlobalSlug]
|
||||
const override = overrides[global.slug as IaplGlobalSlug]
|
||||
if (!override) {return global}
|
||||
if (typeof override === 'function') {return override(global)}
|
||||
return {
|
||||
|
||||
+8
-8
@@ -1,6 +1,6 @@
|
||||
export { lightboxNotificationFields } from './globals/Notifications/fields.js'
|
||||
export { applyGlobalOverrides } from './globals/overrides.js'
|
||||
export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js'
|
||||
export type { GlobalOverride, GlobalOverrides, IaplGlobalSlug } from './globals/overrides.js'
|
||||
export type { AccessOption, Role } from './modules/access/index.js'
|
||||
export {
|
||||
adminOnly,
|
||||
@@ -55,7 +55,7 @@ export type { AccountsOptions } from './modules/access/types.js'
|
||||
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js'
|
||||
export type { A11yState } from './modules/accessibility/state.js'
|
||||
export { applyAdminI18n } from './modules/admin-i18n/apply.js'
|
||||
export { ADMIN_LANGUAGES, adminDocumentTitle, adminTexts, defineTexts, formatDateTime, formatNumber, ipalT } from './modules/admin-i18n/index.js'
|
||||
export { ADMIN_LANGUAGES, adminDocumentTitle, adminTexts, defineTexts, formatDateTime, formatNumber, iaplT } from './modules/admin-i18n/index.js'
|
||||
export type { AdminLanguage, AdminText, AdminTextKey } from './modules/admin-i18n/index.js'
|
||||
export { rowLabel } from './modules/admin-ui/index.js'
|
||||
export type { RowLabelProps } from './modules/admin-ui/index.js'
|
||||
@@ -216,8 +216,8 @@ export type { MailAdapterArgs } from './modules/email/mailAdapter.js'
|
||||
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
|
||||
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
|
||||
// Boot-time environment validation (fail fast on misconfigured deploys).
|
||||
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from './modules/env/index.js'
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
|
||||
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules } from './modules/env/index.js'
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures } from './modules/env/index.js'
|
||||
export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js'
|
||||
export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js'
|
||||
export { FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS } from './modules/forms/attachments/fileTypes.js'
|
||||
@@ -459,9 +459,9 @@ export { isTheme, isThemeSetting, LEGACY_THEME_STORAGE_KEY, THEME_ATTRIBUTE, THE
|
||||
export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js'
|
||||
// Imported from the file, not the turnstile barrel — that one re-exports verify,
|
||||
// which imports 'server-only'.
|
||||
export { defineTokens, IPAL_BREAKPOINTS, IPAL_TOKENS, ipalVar } from './modules/tokens/index.js'
|
||||
export type { IpalTokenName, TokensInput } from './modules/tokens/index.js'
|
||||
export { defineTokens, IAPL_BREAKPOINTS, IAPL_TOKENS, iaplVar } from './modules/tokens/index.js'
|
||||
export type { IaplTokenName, TokensInput } from './modules/tokens/index.js'
|
||||
export { getTurnstileConfig, TURNSTILE_SECRET_ENV, turnstileSecretFromEnv } from './modules/turnstile/config.js'
|
||||
export type { TurnstileConfig } from './modules/turnstile/config.js'
|
||||
export { ipalKit } from './plugin.js'
|
||||
export type { IpalOptions, ThemeOptions } from './types.js'
|
||||
export { iapl } from './plugin.js'
|
||||
export type { IaplOptions, ThemeOptions } from './types.js'
|
||||
|
||||
@@ -30,7 +30,7 @@ export function resolvePanelRole(option: false | Role | undefined): null | Role
|
||||
if (option === false) {return null}
|
||||
const role = option ?? DEFAULT_PANEL_ROLE
|
||||
if (!ROLE_HIERARCHY.includes(role)) {
|
||||
throw new Error(`[ipal] accounts.panelRole must be one of ${ROLE_HIERARCHY.join(', ')} or false, got ${JSON.stringify(option)}.`)
|
||||
throw new Error(`[iapl] accounts.panelRole must be one of ${ROLE_HIERARCHY.join(', ')} or false, got ${JSON.stringify(option)}.`)
|
||||
}
|
||||
return role === ROLE_HIERARCHY[0] ? null : role
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ export function resolvePasswordRule(option: false | PasswordRuleOptions | undefi
|
||||
if (option === false) {return null}
|
||||
const minLength = option?.minLength ?? DEFAULT_PASSWORD_MIN_LENGTH
|
||||
if (typeof minLength !== 'number' || !Number.isInteger(minLength) || minLength < 1) {
|
||||
throw new Error(`[ipal] accounts.password.minLength must be a whole number of 1 or more, got ${JSON.stringify(option?.minLength) ?? String(option?.minLength)}. Use accounts: { password: false } to turn the rule off.`)
|
||||
throw new Error(`[iapl] accounts.password.minLength must be a whole number of 1 or more, got ${JSON.stringify(option?.minLength) ?? String(option?.minLength)}. Use accounts: { password: false } to turn the rule off.`)
|
||||
}
|
||||
return { minLength }
|
||||
}
|
||||
|
||||
@@ -23,14 +23,14 @@ type StaffConfig = { admin?: { user?: string }; custom?: unknown }
|
||||
type MaybePayload = Pick<BasePayload, 'config'> | StaffSource
|
||||
|
||||
/**
|
||||
* The staff lists of the configs ipalKit built in this process, by owner: the
|
||||
* The staff lists of the configs iapl built in this process, by owner: the
|
||||
* running Payload instance once it exists, a token of the config before that.
|
||||
* Used when a predicate gets no source (`isAdmin(req.user)` in a hook).
|
||||
*/
|
||||
const registered = new Map<object, string[]>()
|
||||
|
||||
/**
|
||||
* Called by ipalKit: at config time with a token, then with the Payload
|
||||
* Called by iapl: at config time with a token, then with the Payload
|
||||
* instance (`replaces` = that config's token) on init and after every reload.
|
||||
* Not for projects.
|
||||
*/
|
||||
@@ -49,7 +49,7 @@ export const staffRegistrySize = (): number => registered.size
|
||||
|
||||
/**
|
||||
* The staff collections every config in this process agrees on, or null when
|
||||
* ipalKit never ran here (a browser bundle, Next middleware, the edge
|
||||
* iapl never ran here (a browser bundle, Next middleware, the edge
|
||||
* runtime). Two configs with different lists: only what both call staff — a
|
||||
* call that does not say which config it means must not get the wider answer.
|
||||
*/
|
||||
@@ -83,7 +83,7 @@ export function staffCollectionSlugs(source?: MaybePayload): string[] {
|
||||
* Whether this account's roles may count at all: it belongs to a staff
|
||||
* collection. Checked before any role, and it fails closed:
|
||||
* - an account without `collection` (a user object built by hand) is not staff;
|
||||
* - where the staff collections are not known — no source given and ipalKit
|
||||
* - where the staff collections are not known — no source given and iapl
|
||||
* never ran in this bundle (client components, Next middleware, the edge
|
||||
* runtime) — nobody is staff. Pass the source there: `isAdmin(user, config)`
|
||||
* with the config from `useConfig()` (client components import from
|
||||
@@ -116,7 +116,7 @@ function highestRoleIndex(user: MaybeUser): number {
|
||||
*
|
||||
* Pass `req.payload` as the third argument where you have it (access
|
||||
* functions, hooks, endpoints); without it the staff collections of the
|
||||
* config ipalKit built in this process are used — and where there is none
|
||||
* config iapl built in this process are used — and where there is none
|
||||
* (a browser bundle, middleware) the answer is false: pass the config from
|
||||
* `useConfig()` or `{ staffCollections: ['users'] }` there. A client component
|
||||
* imports it from '@intecion/ipal-kit/client': the main entry does not build there with webpack.
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* The mark lets the plugin see that. It is on the function itself, so it:
|
||||
* - travels with every copy (it is the same function object);
|
||||
* - is on the function that ends up on the collection (set after the 2FA package wrapped the
|
||||
* rule; ipal-kit's own 2FA guard gets a mark of its own for its wrapper);
|
||||
* rule; IAPL's own 2FA guard gets a mark of its own for its wrapper);
|
||||
* - is the same for every instance of this module (`Symbol.for`): after a `next dev` reload the
|
||||
* config was built by one instance and is adopted by another.
|
||||
* It counts only on the very function it was made for (`self`): a Proxy around a marked rule, a
|
||||
|
||||
@@ -160,15 +160,15 @@ export function canHoldStaffRole(collection: Staffish): boolean {
|
||||
export type StaffAccountRules = { applied: string[]; ownRoles: boolean; slug?: string }
|
||||
|
||||
/**
|
||||
* The "seen" marker (`custom.ipalAccounts`): which collection ipalKit handled, and whether as a staff
|
||||
* The "seen" marker (`custom.ipalAccounts`): which collection iapl handled, and whether as a staff
|
||||
* collection. Not a plain `true`: a later plugin may spread a collection into a new slug
|
||||
* (`{ ...staff, slug: 'copy' }`) and the marker travels with it; and in `next dev` a collection object can
|
||||
* outlive a reload in which it became staff.
|
||||
*/
|
||||
export type AccountsMarker = {
|
||||
/**
|
||||
* The operations that had a rule in the project's config when ipalKit ran (before Payload and the 2FA package
|
||||
* filled the missing ones). A collection of the config that becomes staff LATER — a plugin listed after ipalKit
|
||||
* The operations that had a rule in the project's config when iapl ran (before Payload and the 2FA package
|
||||
* filled the missing ones). A collection of the config that becomes staff LATER — a plugin listed after iapl
|
||||
* sets `admin.user` to it — keeps exactly those rules; an operation that had none gets the plugin's.
|
||||
*/
|
||||
own?: string[]
|
||||
@@ -182,7 +182,7 @@ const markerOf = (collection: { custom?: unknown }): AccountsMarker | undefined
|
||||
|
||||
/**
|
||||
* BOTH rules must allow: the plugin's and the one the collection already has. For a collection
|
||||
* that arrives after ipalKit ran (a later plugin), whose config is already sanitized: Payload has
|
||||
* that arrives after iapl ran (a later plugin), whose config is already sanitized: Payload has
|
||||
* filled every missing rule with its default by then, and that default cannot be told from a
|
||||
* rule somebody wrote — not by its name (a production build minifies it away) and not safely by
|
||||
* identity. So nothing is guessed: the plugin's rule is put in FRONT of whatever is there. With
|
||||
@@ -230,10 +230,10 @@ const bothAllowField =
|
||||
* are involved.
|
||||
*
|
||||
* `mode`:
|
||||
* - `'config'` (ipalKit is running, nothing is sanitized): an operation without a rule gets the plugin's;
|
||||
* - `'config'` (iapl is running, nothing is sanitized): an operation without a rule gets the plugin's;
|
||||
* - `'late'` (a staff collection a later plugin added; the config is sanitized, so Payload's default cannot be
|
||||
* told from a written rule): the plugin's rule in front of every rule — except the operations named in `kept`:
|
||||
* the collection was in the config when ipalKit ran and had a rule of the project's for them then (the marker's
|
||||
* the collection was in the config when iapl ran and had a rule of the project's for them then (the marker's
|
||||
* `own`), so they are left as a rule the project wrote, exactly as at config time;
|
||||
* - `'copied'` (a late collection that is not staff, or that keeps its own rules — `custom.ipal.accountRules:
|
||||
* false`): the plugin's rule goes in front ONLY of a rule the plugin wrote for another collection (its mark,
|
||||
@@ -273,7 +273,7 @@ function ruleStaffCollection(collection: CollectionConfig, { create = true, plug
|
||||
if (mark && mark.slug !== slug) {copied = true}
|
||||
if (mode === 'config') {
|
||||
if (there || !enabled) {continue} // a rule the project wrote
|
||||
access[operation] = rule // marked when ipalKit finishes (markStaffRules): the 2FA package wraps it first
|
||||
access[operation] = rule // marked when iapl finishes (markStaffRules): the 2FA package wraps it first
|
||||
} else if ((mode === 'late' && enabled && !kept.includes(operation)) || mark) {
|
||||
access[operation] = markedStaffRule(bothAllow(rule, there), slug)
|
||||
} else {continue}
|
||||
@@ -352,7 +352,7 @@ export function applyStaffAccountAccess(config: Config, staffSlugs: string[], op
|
||||
collections: (config.collections ?? []).map((collection) => {
|
||||
if (!collection.auth) {return collection}
|
||||
// Which operations have a rule of the project's NOW — later nobody can tell (Payload and the 2FA package fill
|
||||
// the missing ones). Kept in the marker for a collection that becomes staff after ipalKit ran.
|
||||
// the missing ones). Kept in the marker for a collection that becomes staff after iapl ran.
|
||||
const own = OPERATIONS.filter((operation) => Boolean((collection.access as Record<string, unknown> | undefined)?.[operation]))
|
||||
if (!staffSlugs.includes(collection.slug)) {
|
||||
return { ...collection, custom: { ...collection.custom, ipalAccounts: { slug: collection.slug, own, staff: false } satisfies AccountsMarker } }
|
||||
@@ -370,14 +370,14 @@ export type LateAdoption = {
|
||||
firstUser: boolean
|
||||
/** The operations whose rule from the project's config was left as it is (a config collection that became staff later). */
|
||||
kept: string[]
|
||||
/** True when the collection was in the config when ipalKit ran (and became staff afterwards); false when a later plugin added it. */
|
||||
/** True when the collection was in the config when iapl ran (and became staff afterwards); false when a later plugin added it. */
|
||||
known: boolean
|
||||
password: boolean
|
||||
slug: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Collections that were not in the config when ipalKit ran — a plugin listed after it added them.
|
||||
* Collections that were not in the config when iapl ran — a plugin listed after it added them.
|
||||
* Called when a config goes live (start, dev reload) with THAT config: a late STAFF collection
|
||||
* gets the account rules (in front of whatever rules it has — `bothAllow`), the roles-field rule
|
||||
* and the password hook; every late auth collection gets the first-user endpoint. Changes the
|
||||
@@ -398,7 +398,7 @@ export function adoptLateAuthCollections(
|
||||
// a copy; a marker that says "not staff" on a collection that is staff now was made before it was named as one.
|
||||
const marker = markerOf(collection)
|
||||
if (marker?.slug === collection.slug && (marker.staff || !staff)) {continue}
|
||||
// In the config when ipalKit ran, not staff then (a later plugin made it the panel's): the rules it had then stay.
|
||||
// In the config when iapl ran, not staff then (a later plugin made it the panel's): the rules it had then stay.
|
||||
const known = marker?.slug === collection.slug
|
||||
const kept = known && Array.isArray(marker.own) ? marker.own : []
|
||||
const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, kept: [], known, password: false }
|
||||
@@ -429,7 +429,7 @@ export function adoptLateAuthCollections(
|
||||
/**
|
||||
* Puts the plugin's mark on the rules it filled in during this run (`custom.ipalAccountRules.applied`, for the
|
||||
* collection's own slug). Called AFTER the 2FA package has wrapped them — the mark must be on the function that is
|
||||
* on the collection — and BEFORE ipal-kit's own 2FA guard, which carries the mark to its wrapper. Already marked
|
||||
* on the collection — and BEFORE IAPL's own 2FA guard, which carries the mark to its wrapper. Already marked
|
||||
* functions are left, so it can run more than once.
|
||||
*/
|
||||
export function markStaffRules(config: Config): Config {
|
||||
@@ -449,7 +449,7 @@ export function markStaffRules(config: Config): Config {
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the auth collections ipalKit has seen at config time — with their slug and whether they are staff — so
|
||||
* Marks the auth collections iapl has seen at config time — with their slug and whether they are staff — so
|
||||
* `adoptLateAuthCollections` leaves exactly those alone.
|
||||
*/
|
||||
export function markSeenAuthCollections(config: Config, staffSlugs: string[] = []): Config {
|
||||
@@ -518,7 +518,7 @@ export function buildFirstUserEndpoint(option: FirstUserRouteOption = 'panel'):
|
||||
export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption = 'panel'): Config {
|
||||
if (option === 'all') {return config}
|
||||
if (option !== 'panel' && !Array.isArray(option)) {
|
||||
throw new Error(`[ipal] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`)
|
||||
throw new Error(`[iapl] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`)
|
||||
}
|
||||
return {
|
||||
...config,
|
||||
|
||||
@@ -11,7 +11,7 @@ export const ROLE_HIERARCHY = ['user', 'editor', 'admin'] as const
|
||||
export type Role = (typeof ROLE_HIERARCHY)[number]
|
||||
|
||||
/**
|
||||
* `ipalKit({ accounts })` — rules for the accounts of the staff collection. On by default
|
||||
* `iapl({ accounts })` — rules for the accounts of the staff collection. On by default
|
||||
* where they apply; each one has its own switch, `accounts: false` turns them all off.
|
||||
*/
|
||||
export type AccountsOptions = {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Client-safe: types, texts and helpers. The config transform (applyAdminI18n) lives in apply.ts.
|
||||
export type { AdminLanguage, AdminText } from './define.js'
|
||||
export { ADMIN_LANGUAGES, defineTexts } from './define.js'
|
||||
export { adminDocumentTitle, formatDateTime, formatNumber, ipalT } from './t.js'
|
||||
export { adminDocumentTitle, formatDateTime, formatNumber, iaplT } from './t.js'
|
||||
export { adminTexts } from './texts/index.js'
|
||||
export type { AdminTextKey } from './texts/index.js'
|
||||
|
||||
@@ -7,7 +7,7 @@ type TFunction = (key: never, vars?: Record<string, unknown>) => string
|
||||
* components, `i18n.t` in server components), so a project's own
|
||||
* `i18n.translations.<lang>.ipal.<key>` wins over the plugin's.
|
||||
*/
|
||||
export function ipalT(t: TFunction, key: AdminTextKey, vars?: Record<string, unknown>): string {
|
||||
export function iaplT(t: TFunction, key: AdminTextKey, vars?: Record<string, unknown>): string {
|
||||
return t(`ipal:${key}` as never, vars)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useRowLabel, useTranslation } from '@payloadcms/ui'
|
||||
|
||||
import type { AdminText } from '../admin-i18n/define.js'
|
||||
|
||||
import { ipalT } from '../admin-i18n/t.js'
|
||||
import { iaplT } from '../admin-i18n/t.js'
|
||||
|
||||
export type RowLabelProps = {
|
||||
/**
|
||||
@@ -48,6 +48,6 @@ export function RowLabel({ fallback, fields = ['heading', 'title', 'label', 'lin
|
||||
? fallback
|
||||
: fallback
|
||||
? ((fallback as Record<string, string>)[i18n.language] ?? fallback.en ?? Object.values(fallback)[0])
|
||||
: ipalT(t, 'rowLabelItem')
|
||||
: iaplT(t, 'rowLabelItem')
|
||||
return <span>{`${name} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`}</span>
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export const CONTACT_PARTS = {
|
||||
export async function ContactBlock(props: LibraryBlockProps<ContactBlockData>) {
|
||||
const { classNames, content, ctx, form, header, isFirst, locale, settings, ui, variant } = props
|
||||
if (!ctx.sendForm || !ctx.content.getFormTexts) {
|
||||
console.warn('[ipal] contact block: pass sendForm and content with getFormTexts to createBlockRegistry')
|
||||
console.warn('[iapl] contact block: pass sendForm and content with getFormTexts to createBlockRegistry')
|
||||
return null
|
||||
}
|
||||
const c = parts(CONTACT_PARTS, classNames)
|
||||
|
||||
@@ -6,7 +6,7 @@ import { adminText, defineLibraryBlock, variantOption } from '../../define.js'
|
||||
export const ENTRY_LIST_VARIANTS = [variantOption('cards', 'Cards', 'Karty'), variantOption('list', 'List', 'Lista')] as const
|
||||
|
||||
export type EntryListOptions = {
|
||||
/** Content collections the editor picks from (they need URLs: ipalKit `content`). Default posts. */
|
||||
/** Content collections the editor picks from (they need URLs: iapl `content`). Default posts. */
|
||||
collections?: readonly { label: AdminText; value: string }[]
|
||||
} & BlockOptions
|
||||
|
||||
|
||||
@@ -82,6 +82,6 @@ export function buildBlockLibraryManifest(): BlockLibraryManifest {
|
||||
|
||||
/**
|
||||
* Names of the library's blocks, variants, primitives, field builders and templates —
|
||||
* plain data for checks such as ipal-doctor. Built from the block configs themselves.
|
||||
* plain data for checks such as iapl-doctor. Built from the block configs themselves.
|
||||
*/
|
||||
export const blockLibraryManifest: BlockLibraryManifest = buildBlockLibraryManifest()
|
||||
|
||||
@@ -47,7 +47,7 @@ export function pickVariants(defaults: readonly VariantOption[], chosen: BlockOp
|
||||
return chosen.map((v) => {
|
||||
if (typeof v !== 'string') {return v}
|
||||
const known = defaults.find((d) => d.value === v)
|
||||
if (!known) {throw new Error(`[ipal] unknown variant "${v}" — pass { label, value } for a variant of your own`)}
|
||||
if (!known) {throw new Error(`[iapl] unknown variant "${v}" — pass { label, value } for a variant of your own`)}
|
||||
return known
|
||||
})
|
||||
}
|
||||
|
||||
@@ -102,6 +102,6 @@ export function buildTemplate(name: string, defaults: { slug: TemplateValue; tit
|
||||
}
|
||||
return [{ ...b, blockType: slug }]
|
||||
})
|
||||
if (missing.length) {console.warn(`[ipal] template ${name}: left out blocks that are off: ${missing.join(', ')}`)}
|
||||
if (missing.length) {console.warn(`[iapl] template ${name}: left out blocks that are off: ${missing.join(', ')}`)}
|
||||
return { slug: options.slug ?? defaults.slug, layout, title: options.title ?? defaults.title }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { ipalT } from '../admin-i18n/t.js'
|
||||
import { iaplT } from '../admin-i18n/t.js'
|
||||
import { settingsTexts } from '../admin-i18n/texts/settings.js'
|
||||
import { secondFactorPassed } from '../security/totp/secondFactor.js'
|
||||
import { publicImageDataUri, siteOrigin } from './publicImage.js'
|
||||
@@ -9,7 +9,7 @@ import { publicImageDataUri, siteOrigin } from './publicImage.js'
|
||||
* White-label admin branding: the Payload admin panel's logo (login + nav) and
|
||||
* icon, pulled from the project's SiteSettings so each client sees THEIR brand,
|
||||
* set by the editor in the panel — not hardcoded per project. Wired
|
||||
* automatically by `ipalKit({ whiteLabel: true })` (it injects
|
||||
* automatically by `iapl({ whiteLabel: true })` (it injects
|
||||
* admin.components.graphics.Logo/Icon pointing here).
|
||||
*
|
||||
* Server Components — they read the SiteSettings global at render, using the
|
||||
@@ -85,7 +85,7 @@ async function loadBranding(
|
||||
}
|
||||
return { name, url }
|
||||
} catch (error) {
|
||||
console.warn('[ipal] admin branding: falling back to Payload default:', error)
|
||||
console.warn('[iapl] admin branding: falling back to Payload default:', error)
|
||||
return { name: null, url: null }
|
||||
}
|
||||
}
|
||||
@@ -130,14 +130,14 @@ export async function AdminIcon(props: BrandingProps = {}) {
|
||||
|
||||
/**
|
||||
* Discreet vendor credit: "Technology support: Intecion.com". This is the
|
||||
* PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client
|
||||
* PLUGIN VENDOR's credit (Intecion ships IAPL, the framework), not client
|
||||
* data — a sensible default here is fine and A0-safe. The client's own brand
|
||||
* still owns the logo/name; this is a small line stating who supports the tech.
|
||||
* Text/URL overridable; turn it off with `whiteLabel: { credit: false }`.
|
||||
* The default text follows the admin language (`ipal:brandingCredit`, which a
|
||||
* project can also override in `i18n.translations`).
|
||||
*
|
||||
* Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin
|
||||
* Wired by iapl into admin.components.afterNavLinks (nav) AND afterLogin
|
||||
* (login screen footer). `variant` adjusts placement:
|
||||
* - 'nav' → left-aligned line under the nav links
|
||||
* - 'login' → centered line below the login form
|
||||
@@ -156,7 +156,7 @@ export function IntecionCredit(
|
||||
// A project's own text wins; otherwise the plugin's text in the admin language.
|
||||
const text =
|
||||
props.text ??
|
||||
(i18n ? ipalT(i18n.t, 'brandingCredit', { agency }) : settingsTexts.en.brandingCredit.replace('{{agency}}', agency))
|
||||
(i18n ? iaplT(i18n.t, 'brandingCredit', { agency }) : settingsTexts.en.brandingCredit.replace('{{agency}}', agency))
|
||||
const style =
|
||||
variant === 'login'
|
||||
? {
|
||||
|
||||
@@ -193,6 +193,6 @@ export async function syncAdminMeta(
|
||||
if (!resolved.own.description && resolved.options.description !== false && description) {meta.description = description}
|
||||
if (!resolved.own.titleSuffix && resolved.options.titleSuffix !== false && titleSuffix) {meta.titleSuffix = titleSuffix}
|
||||
} catch (error) {
|
||||
payload?.logger?.warn({ err: error, msg: '[ipal] admin meta: could not read Site settings; Payload defaults stay.' })
|
||||
payload?.logger?.warn({ err: error, msg: '[iapl] admin meta: could not read Site settings; Payload defaults stay.' })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js'
|
||||
* the time. NO IP address, user agent or other personal data — the id alone
|
||||
* links a record to the browser that holds the cookie.
|
||||
*
|
||||
* Opt-in: `ipalKit({ consentLog: true })` adds the collection and the endpoint
|
||||
* Opt-in: `iapl({ consentLog: true })` adds the collection and the endpoint
|
||||
* POST /api/ipal/consent; the layout passes `<ConsentProvider logEndpoint="/api/ipal/consent">`.
|
||||
* Records older than `retentionDays` (default 3 years) are purged automatically.
|
||||
*/
|
||||
@@ -110,7 +110,7 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti
|
||||
purge(req.payload, { createdAt: { less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString() } })
|
||||
return Response.json({ ok: true }, { status: 201 })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] consent log write failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
req.payload.logger.error(`[iapl] consent log write failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return Response.json({ ok: false }, { status: 500 })
|
||||
}
|
||||
},
|
||||
|
||||
@@ -142,7 +142,7 @@ async function readPrivacyPage(payload: BasePayload, settingsSlug: string): Prom
|
||||
return page && typeof page === 'object' ? (page as PrivacyPage) : null
|
||||
} catch (error) {
|
||||
// No pages option / no privacyPolicy field / DB unreachable at build → no link.
|
||||
console.warn('[ipal] getConsentTexts: privacy page lookup failed, banner without link:', error)
|
||||
console.warn('[iapl] getConsentTexts: privacy page lookup failed, banner without link:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ export function buildCookieApprovalEndpoints(options: CookieScannerOptions): End
|
||||
const result = await approveCookies({ addToList: options.syncAccepted !== false, ids, payload: req.payload, req, unknownCategory: approval.unknownCategory })
|
||||
return Response.json({ ok: true, result })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] cookie approval failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
req.payload.logger.error(`[iapl] cookie approval failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return Response.json({ ok: false }, { status: 500 })
|
||||
}
|
||||
},
|
||||
|
||||
@@ -12,7 +12,7 @@ import { addToCookieList } from './sync.js'
|
||||
* Cookie review list — drafts from "Scan cookies" that an editor accepts,
|
||||
* edits or rejects. Accepting adds the cookie to Cookie Settings → Cookies
|
||||
* (the banner's detailed window and <CookieTable>). Opt-in:
|
||||
* `ipalKit({ cookieScanner: true })`.
|
||||
* `iapl({ cookieScanner: true })`.
|
||||
*/
|
||||
export const COOKIE_REVIEW_SLUG = 'cookie-review'
|
||||
|
||||
@@ -46,7 +46,7 @@ function buildSyncHook(): CollectionAfterChangeHook {
|
||||
req,
|
||||
})) as unknown as { name: string } & CookieReviewValues
|
||||
const result = await addToCookieList({ entry: full, payload: req.payload, req })
|
||||
req.payload.logger.info(`[ipal] cookie review: "${full.name}" accepted → Cookie Settings (${result})`)
|
||||
req.payload.logger.info(`[iapl] cookie review: "${full.name}" accepted → Cookie Settings (${result})`)
|
||||
if (!doc.listed) {
|
||||
await req.payload.update({
|
||||
id: doc.id,
|
||||
|
||||
@@ -7,8 +7,8 @@ import { DEFAULT_TRACKER_HOSTS } from './violations.js'
|
||||
export const COOKIE_CRAWL_SLUG = 'cookie-crawl'
|
||||
export const COOKIE_CRAWL_PATH = '/ipal/cookie-crawl'
|
||||
export const COOKIE_CRAWL_RESULTS_PATH = '/ipal/cookie-crawl/results'
|
||||
export const COOKIE_SCAN_URL_ENV = 'IPAL_COOKIE_SCAN_URL'
|
||||
export const COOKIE_SCAN_TOKEN_ENV = 'IPAL_COOKIE_SCAN_TOKEN'
|
||||
export const COOKIE_SCAN_URL_ENV = 'IAPL_COOKIE_SCAN_URL'
|
||||
export const COOKIE_SCAN_TOKEN_ENV = 'IAPL_COOKIE_SCAN_TOKEN'
|
||||
/** A crawl still "running" after this long is treated as lost (the service never called back). */
|
||||
export const CRAWL_TIMEOUT_MS = 30 * 60_000
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ export function buildCookieCrawlEndpoints({
|
||||
if (!res.ok) {throw new Error(`scanner service answered HTTP ${res.status}`)}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
req.payload.logger.error(`[ipal] cookie crawl: could not start — ${message}`)
|
||||
req.payload.logger.error(`[iapl] cookie crawl: could not start — ${message}`)
|
||||
await write(req, { error: 'The checking service could not be reached. Please try again later.', finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
|
||||
return Response.json({ error: 'service_unreachable', ok: false }, { status: 502 })
|
||||
}
|
||||
@@ -155,7 +155,7 @@ export function buildCookieCrawlEndpoints({
|
||||
return Response.json({ ok: true })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
req.payload.logger.error(`[ipal] cookie crawl: saving the result failed — ${message}`)
|
||||
req.payload.logger.error(`[iapl] cookie crawl: saving the result failed — ${message}`)
|
||||
await write(req, { error: 'The result could not be saved. Please run the check again.', finishedAt: new Date().toISOString(), jobId: null, status: 'failed' })
|
||||
return Response.json({ ok: false }, { status: 500 })
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ ${pending ? `<p><strong>${esc(fill(t('emailPending'), { count: pending }))}</str
|
||||
await payload.sendEmail({ html, subject, to })
|
||||
return true
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] cookie crawl warning e-mail failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
payload.logger.error(`[iapl] cookie crawl warning e-mail failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ export function buildCookieScanEndpoints(options: CookieScannerOptions, plugin:
|
||||
const { enabled, summary } = await runCookieScan({ names: parseCookieNames(body.names), options, payload: req.payload, plugin, req })
|
||||
return Response.json({ integrations: list(enabled, req), ok: true, summary })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[ipal] cookie scan failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
req.payload.logger.error(`[iapl] cookie scan failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return Response.json({ ok: false }, { status: 500 })
|
||||
}
|
||||
},
|
||||
|
||||
@@ -63,7 +63,7 @@ export async function enabledCookieIntegrations(
|
||||
try {
|
||||
if (await integration.isEnabled(ctx)) {on.push(integration)}
|
||||
} catch (err) {
|
||||
ctx.payload.logger.warn(`[ipal] cookie scan: could not check "${integration.key}": ${err instanceof Error ? err.message : String(err)}`)
|
||||
ctx.payload.logger.warn(`[iapl] cookie scan: could not check "${integration.key}": ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
return on
|
||||
|
||||
@@ -38,7 +38,7 @@ export type CookieScanContext = {
|
||||
language?: string
|
||||
payload: BasePayload
|
||||
/** Plugin options that switch modules on. */
|
||||
/** Plugin options that switch modules on; `themeStorageKey` = `ipalKit({ theme: { storageKey } })`. */
|
||||
/** Plugin options that switch modules on; `themeStorageKey` = `iapl({ theme: { storageKey } })`. */
|
||||
plugin: { localeCount: number; stats: boolean; themeStorageKey?: string }
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ export type CookieScanSummary = {
|
||||
}
|
||||
|
||||
/**
|
||||
* `ipalKit({ cookieScanner })` — the Cookie review list and the "Scan cookies"
|
||||
* `iapl({ cookieScanner })` — the Cookie review list and the "Scan cookies"
|
||||
* action. Every key is optional.
|
||||
*/
|
||||
export type CookieScannerOptions = {
|
||||
@@ -163,11 +163,11 @@ export type CookieCrawlOptions = {
|
||||
globalOverride?: GlobalOverride
|
||||
/** Sitemap pages crawled besides the home page. Default 20, at most 100. */
|
||||
maxPages?: number
|
||||
/** Scanner service base URL. Default env `IPAL_COOKIE_SCAN_URL`. */
|
||||
/** Scanner service base URL. Default env `IAPL_COOKIE_SCAN_URL`. */
|
||||
serviceUrl?: string
|
||||
/** Public origin of this site the service crawls and calls back. Default `serverURL`, else `NEXT_PUBLIC_SERVER_URL`. */
|
||||
siteUrl?: string
|
||||
/** Shared secret with the service. Default env `IPAL_COOKIE_SCAN_TOKEN`. */
|
||||
/** Shared secret with the service. Default env `IAPL_COOKIE_SCAN_TOKEN`. */
|
||||
token?: string
|
||||
/** Hosts whose requests before consent are violations: `(defaults) => hosts`. */
|
||||
trackerHosts?: (defaults: string[]) => string[]
|
||||
|
||||
@@ -208,7 +208,7 @@ export function createMarkdownRoute(
|
||||
const md = await render({ slug, locale, payload: await getCachedPayload() })
|
||||
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
|
||||
} catch (err) {
|
||||
console.warn('[ipal] createMarkdownRoute: render failed:', err)
|
||||
console.warn('[iapl] createMarkdownRoute: render failed:', err)
|
||||
return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 })
|
||||
}
|
||||
},
|
||||
|
||||
@@ -99,7 +99,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
|
||||
)
|
||||
} catch (err) {
|
||||
// DB unreachable (build) or unexpected — empty result rather than 500.
|
||||
console.warn('[ipal] createSearchRoute: search failed:', err)
|
||||
console.warn('[iapl] createSearchRoute: search failed:', err)
|
||||
return Response.json(
|
||||
{ count: 0, query, results: [] },
|
||||
{ headers: { 'cache-control': 'no-store' }, status: 200 },
|
||||
|
||||
@@ -51,7 +51,7 @@ export async function resolveNotFoundPage({
|
||||
})
|
||||
return (doc as null | Record<string, unknown>) ?? null
|
||||
} catch (error) {
|
||||
console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)
|
||||
console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import type { DoctorReport, DoctorSeverity } from './types.js'
|
||||
import { formatDriftTable, formatReport } from './format.js'
|
||||
import { runDoctor } from './run.js'
|
||||
|
||||
export const DOCTOR_USAGE = `Usage: ipal-doctor [dir] [options]
|
||||
Checks a site against the ipal-kit team rules and lists every gap with a fix hint.
|
||||
export const DOCTOR_USAGE = `Usage: iapl-doctor [dir] [options]
|
||||
Checks a site against the IAPL team rules and lists every gap with a fix hint.
|
||||
|
||||
--json machine-readable report (schema 1)
|
||||
--md Markdown table (with --sites: rule × site)
|
||||
@@ -24,10 +24,10 @@ export const DOCTOR_USAGE = `Usage: ipal-doctor [dir] [options]
|
||||
--sites <glob> many projects, e.g. '../*-web' (read-only report; never a gate)
|
||||
|
||||
Exit: 0 ok · 1 findings at or above --fail-on · 2 could not run · 3 a rule crashed
|
||||
Silence a rule with a reason in ipal-doctor.json — docs/doctor.md`
|
||||
Silence a rule with a reason in iapl-doctor.json — docs/doctor.md`
|
||||
|
||||
/**
|
||||
* Whether this run stores first-seen dates in ipal-doctor.json: not with --sites or --json, and
|
||||
* Whether this run stores first-seen dates in iapl-doctor.json: not with --sites or --json, and
|
||||
* never when CI is set (a CI run must not change a tracked file).
|
||||
*/
|
||||
export function shouldWriteSeen(args: { json?: boolean; sites?: unknown }, env: Record<string, string | undefined> = process.env): boolean {
|
||||
@@ -113,18 +113,18 @@ export async function runDoctorCli(argv: string[], { cwd = process.cwd(), log =
|
||||
}
|
||||
const args = parseDoctorArgs(argv)
|
||||
if (typeof args === 'string') {
|
||||
console.error(`ipal-doctor: ${args}\n\n${DOCTOR_USAGE}`)
|
||||
console.error(`iapl-doctor: ${args}\n\n${DOCTOR_USAGE}`)
|
||||
return 2
|
||||
}
|
||||
const dirs = args.sites ? expandSites(args.sites, cwd) : [resolve(cwd, args.dir)]
|
||||
if (!dirs.length) {
|
||||
console.error(`ipal-doctor: no folder matches ${args.sites}`)
|
||||
console.error(`iapl-doctor: no folder matches ${args.sites}`)
|
||||
return 2
|
||||
}
|
||||
const reports: DoctorReport[] = []
|
||||
for (const dir of dirs) {
|
||||
if (!existsSync(join(dir, 'package.json'))) {
|
||||
console.error(`ipal-doctor: ${dir} is not a project root (no package.json)`)
|
||||
console.error(`iapl-doctor: ${dir} is not a project root (no package.json)`)
|
||||
if (!args.sites) {return 2}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ const summaryLine = (r: DoctorReport) =>
|
||||
/** Human-readable report: header, findings worst first with fix and doc link, summary. */
|
||||
export function formatReport(report: DoctorReport, { color = false }: { color?: boolean } = {}): string {
|
||||
const c = (sev: DoctorSeverity, text: string) => (color ? `${COLOR[sev]}${text}\x1b[0m` : text)
|
||||
const lines = [`ipal-doctor ${report.rulesVersion} — ${report.site.path}`, `site: ${report.site.domain ?? '(no domain)'} · ipal-kit ${report.site.plugin ?? 'not installed'}`, '']
|
||||
const lines = [`iapl-doctor ${report.rulesVersion} — ${report.site.path}`, `site: ${report.site.domain ?? '(no domain)'} · IAPL ${report.site.plugin ?? 'not installed'}`, '']
|
||||
const active = report.findings.filter((f) => !f.silenced)
|
||||
if (!active.length) {lines.push('No findings.')}
|
||||
for (const f of active) {
|
||||
@@ -24,7 +24,7 @@ export function formatReport(report: DoctorReport, { color = false }: { color?:
|
||||
for (const f of silenced) {lines.push(` - ${f.rule}: ${f.message} — ${f.reason}`)}
|
||||
}
|
||||
if (report.skipped.length) {lines.push('', `Not run: ${report.skipped.join(', ')} (--url, --deep, or without --offline)`)}
|
||||
lines.push('', `ipal-doctor: ${summaryLine(report)}`)
|
||||
lines.push('', `iapl-doctor: ${summaryLine(report)}`)
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { SanitizedConfig } from 'payload'
|
||||
|
||||
/**
|
||||
* ipal-doctor --deep: run inside the project by `pnpm exec payload run <this file>`.
|
||||
* iapl-doctor --deep: run inside the project by `pnpm exec payload run <this file>`.
|
||||
* Read-only Local API counts (collectDoctorStatus), an exact import-map comparison and the
|
||||
* project's own env rules. Prints one line `IPAL_DOCTOR_STATUS <json>` and exits.
|
||||
* project's own env rules. Prints one line `IAPL_DOCTOR_STATUS <json>` and exits.
|
||||
*
|
||||
* The import map is generated into a temporary file NEXT TO the committed one (the imports are
|
||||
* relative to it), compared, then removed. Nothing else is written.
|
||||
@@ -47,9 +47,9 @@ async function main() {
|
||||
Object.assign(status, await collectDoctorStatus(payload))
|
||||
|
||||
// The doctor passes the committed import map it found (relative to the project root).
|
||||
const committed = config.admin?.importMap?.importMapFile ?? (process.env.IPAL_DOCTOR_IMPORT_MAP ? join(root, process.env.IPAL_DOCTOR_IMPORT_MAP) : '')
|
||||
const committed = config.admin?.importMap?.importMapFile ?? (process.env.IAPL_DOCTOR_IMPORT_MAP ? join(root, process.env.IAPL_DOCTOR_IMPORT_MAP) : '')
|
||||
if (committed && existsSync(committed)) {
|
||||
const temp = join(dirname(committed), 'importMap.ipal-doctor.tmp.js')
|
||||
const temp = join(dirname(committed), 'importMap.iapl-doctor.tmp.js')
|
||||
try {
|
||||
const copy = { ...config, admin: { ...config.admin, importMap: { ...config.admin.importMap, importMapFile: temp } } }
|
||||
await generateImportMap(copy, { force: true, log: false })
|
||||
@@ -67,5 +67,5 @@ try {
|
||||
} catch (err) {
|
||||
status.error = err instanceof Error ? (err.message.split('\n')[0] ?? 'failed') : String(err)
|
||||
}
|
||||
process.stdout.write(`IPAL_DOCTOR_STATUS ${JSON.stringify(status)}\n`)
|
||||
process.stdout.write(`IAPL_DOCTOR_STATUS ${JSON.stringify(status)}\n`)
|
||||
process.exit(0)
|
||||
|
||||
@@ -7,7 +7,7 @@ import { databaseNameFromUri } from '../env/databaseName.js'
|
||||
|
||||
/** Everything a rule may read about the project. Files only — nothing is written. */
|
||||
export type DoctorContext = {
|
||||
/** Keys from `ipal-audit-skip: <keys> — <reason>` lines in AGENTS.md, with the reason. */
|
||||
/** Keys from `iapl-audit-skip: <keys> — <reason>` lines in AGENTS.md, with the reason. */
|
||||
auditSkips: Map<string, string>
|
||||
config: DoctorConfig
|
||||
configError: null | string
|
||||
@@ -75,11 +75,11 @@ export function bareHost(value: string): string {
|
||||
|
||||
const isLocalHost = (host: string) => /^(?:localhost|127\.0\.0\.1|\[?::1\]?|0\.0\.0\.0)$|^[^.]+$/.test(host)
|
||||
|
||||
/** Reads `ipal-audit-skip: a, b — reason` lines (AGENT.md §0b). */
|
||||
/** Reads `iapl-audit-skip: a, b — reason` lines (AGENT.md §0b). */
|
||||
export function readAuditSkips(agents: string): Map<string, string> {
|
||||
const out = new Map<string, string>()
|
||||
for (const line of agents.split('\n')) {
|
||||
const m = line.match(/^[-* ]*ipal-audit-skip:(.*)$/i)
|
||||
const m = line.match(/^[-* ]*iapl-audit-skip:(.*)$/i)
|
||||
if (!m) {continue}
|
||||
const [keys = '', ...rest] = m[1].trim().split(/\s+—\s+|\s+-\s+/)
|
||||
const reason = rest.join(' — ').trim()
|
||||
@@ -89,14 +89,14 @@ export function readAuditSkips(agents: string): Map<string, string> {
|
||||
}
|
||||
|
||||
export function loadDoctorConfig(root: string): { config: DoctorConfig; error: null | string } {
|
||||
const file = join(root, 'ipal-doctor.json')
|
||||
const file = join(root, 'iapl-doctor.json')
|
||||
if (!existsSync(file)) {return { config: {}, error: null }}
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: 'ipal-doctor.json must hold an object' }}
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: 'iapl-doctor.json must hold an object' }}
|
||||
return { config: parsed as DoctorConfig, error: null }
|
||||
} catch (err) {
|
||||
return { config: {}, error: `ipal-doctor.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` }
|
||||
return { config: {}, error: `iapl-doctor.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ export function createDoctorContext(options: ProjectOptions): DoctorContext {
|
||||
}
|
||||
const src = exists('src') ? 'src/' : ''
|
||||
|
||||
// Domain: ipal-doctor.json → a non-local NEXT_PUBLIC_SERVER_URL → the folder name minus -web (docs: D6).
|
||||
// Domain: iapl-doctor.json → a non-local NEXT_PUBLIC_SERVER_URL → the folder name minus -web (docs: D6).
|
||||
const urls = [env.local?.NEXT_PUBLIC_SERVER_URL, env.example?.NEXT_PUBLIC_SERVER_URL].filter(Boolean).map((u) => bareHost(u!))
|
||||
const fromDir = basename(root).replace(/-web$/, '')
|
||||
// The folder name (`intecioncom-web`) is already the domain without dots — enough for the database names.
|
||||
|
||||
@@ -19,7 +19,7 @@ export function hashDir(dir: string): string {
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
/** What `ipal-skills` would change in a skills folder: missing, stale (different content) and retired skills. */
|
||||
/** What `iapl-skills` would change in a skills folder: missing, stale (different content) and retired skills. */
|
||||
export function planSkills({ dest, source }: { dest: string; source: string }): { missing: string[]; retired: string[]; stale: string[] } {
|
||||
const ls = (d: string) => {
|
||||
try {
|
||||
@@ -42,7 +42,7 @@ export const agentRules: DoctorRule[] = [
|
||||
id: 'agents-md',
|
||||
check: (ctx) => {
|
||||
const agents = ctx.read('AGENTS.md')
|
||||
if (!agents) {return [{ fix: 'AGENT.md §13 template, then pnpm exec ipal-skills', message: 'no AGENTS.md', severity: 'error' }]}
|
||||
if (!agents) {return [{ fix: 'AGENT.md §13 template, then pnpm exec iapl-skills', message: 'no AGENTS.md', severity: 'error' }]}
|
||||
const out: RuleFinding[] = []
|
||||
const parts = agents.split(/^## Project decisions[ \t]*$/m)
|
||||
if (parts.length < 2) {out.push({ file: 'AGENTS.md', fix: 'add "## Project decisions" with the architecture answers (AGENT.md "Ask before you build")', message: 'AGENTS.md has no "## Project decisions" section', severity: 'error' })}
|
||||
@@ -50,12 +50,12 @@ export const agentRules: DoctorRule[] = [
|
||||
const body = parts[1].split(/^## /m)[0].replace(/<!--[\s\S]*?-->/g, '')
|
||||
if (!/^\s*[-*] +\S/m.test(body)) {out.push({ file: 'AGENTS.md', message: '"## Project decisions" is empty', severity: 'warning' })}
|
||||
}
|
||||
const pointer = agents.match(/<!-- ipal-kit:start -->[\s\S]*?## ipal-kit ([\w.-]+) — agent guide[\s\S]*?<!-- ipal-kit:end -->/)
|
||||
if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec ipal-skills', message: 'no ipal-kit pointer block in AGENTS.md', severity: 'warning' })}
|
||||
else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec ipal-skills', message: `the pointer block names ipal-kit ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })}
|
||||
const pointer = agents.match(/<!-- iapl:start -->[\s\S]*?## IAPL ([\w.-]+) — agent guide[\s\S]*?<!-- iapl:end -->/)
|
||||
if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: 'no IAPL pointer block in AGENTS.md', severity: 'warning' })}
|
||||
else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: `the pointer block names IAPL ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })}
|
||||
const claude = ctx.read('CLAUDE.md')
|
||||
if (!claude) {out.push({ fix: 'pnpm exec ipal-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })}
|
||||
else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('<!-- ipal-kit:start -->')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })}
|
||||
if (!claude) {out.push({ fix: 'pnpm exec iapl-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })}
|
||||
else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('<!-- iapl:start -->')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/agent/AGENT.md#13-agentsmd-template-for-a-project',
|
||||
@@ -66,8 +66,8 @@ export const agentRules: DoctorRule[] = [
|
||||
id: 'skills-current',
|
||||
check: (ctx) => {
|
||||
const dest = ['.agents/skills', '.claude/skills'].find((d) => ctx.list(d).some((n) => n.startsWith('ipal-')))
|
||||
if (!dest) {return [{ fix: 'pnpm exec ipal-skills', message: 'no ipal-* skills in .agents/skills or .claude/skills', severity: 'error' }]}
|
||||
// Compare with the skills the project's installed plugin ships (what `pnpm exec ipal-skills` copies).
|
||||
if (!dest) {return [{ fix: 'pnpm exec iapl-skills', message: 'no iapl-* skills in .agents/skills or .claude/skills', severity: 'error' }]}
|
||||
// Compare with the skills the project's installed plugin ships (what `pnpm exec iapl-skills` copies).
|
||||
const installedSkills = join(ctx.root, 'node_modules/@intecion/ipal-kit/docs/agent/skills')
|
||||
const source = ctx.exists('node_modules/@intecion/ipal-kit/docs/agent/skills') ? installedSkills : join(ctx.packageRoot, 'docs/agent/skills')
|
||||
const plan = planSkills({ dest: join(ctx.root, dest), source })
|
||||
@@ -76,7 +76,7 @@ export const agentRules: DoctorRule[] = [
|
||||
plan.missing.length ? `missing ${plan.missing.join(', ')}` : '',
|
||||
plan.retired.length ? `retired ${plan.retired.join(', ')}` : '',
|
||||
].filter(Boolean)
|
||||
return parts.length ? [{ file: dest, fix: 'pnpm exec ipal-skills and commit', message: `skills differ from the installed ipal-kit: ${parts.join('; ')}`, severity: 'warning' }] : []
|
||||
return parts.length ? [{ file: dest, fix: 'pnpm exec iapl-skills and commit', message: `skills differ from the installed ipal-kit: ${parts.join('; ')}`, severity: 'warning' }] : []
|
||||
},
|
||||
docs: 'docs/agent/AGENT.md#14-skills-antigravity-claude-code-cursor',
|
||||
group: 'agents',
|
||||
|
||||
@@ -109,7 +109,7 @@ export const blockRules: DoctorRule[] = [
|
||||
const iface = config.match(/\binterfaceName\s*:\s*['"](\w+)['"]/)?.[1]
|
||||
if (!slug) {continue}
|
||||
if ((librarySlugs.has(slug) || (iface && libraryInterfaces.has(iface))) && !overrides.has(slug)) {
|
||||
out.push({ file, fix: 'use the library block (+ variant), or eject it (pnpm exec ipal-blocks eject) and pass it in createBlockRegistry({ components })', message: `project block "${slug}" duplicates a library block`, severity: 'warning' })
|
||||
out.push({ file, fix: 'use the library block (+ variant), or eject it (pnpm exec iapl-blocks eject) and pass it in createBlockRegistry({ components })', message: `project block "${slug}" duplicates a library block`, severity: 'warning' })
|
||||
}
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -16,7 +16,7 @@ export const envRules: DoctorRule[] = [
|
||||
check: (ctx) => {
|
||||
const out: RuleFinding[] = []
|
||||
if (!ctx.domain) {
|
||||
return [{ fix: 'add "domain": "<site domain>" to ipal-doctor.json', message: 'no site domain (ipal-doctor.json "domain", or a non-local NEXT_PUBLIC_SERVER_URL) — database names not checked', severity: 'warning' }]
|
||||
return [{ fix: 'add "domain": "<site domain>" to iapl-doctor.json', message: 'no site domain (iapl-doctor.json "domain", or a non-local NEXT_PUBLIC_SERVER_URL) — database names not checked', severity: 'warning' }]
|
||||
}
|
||||
const { dev, prod } = databaseNamesFor(ctx.domain)
|
||||
for (const [file, env] of [['.env', ctx.env.local], ['.env.example', ctx.env.example]] as const) {
|
||||
@@ -51,17 +51,17 @@ export const envRules: DoctorRule[] = [
|
||||
const file = ctx.exists(`${ctx.src}instrumentation.ts`) ? `${ctx.src}instrumentation.ts` : 'instrumentation.ts'
|
||||
const code = stripComments(ctx.read(file))
|
||||
if (!/assertEnv\s*\(/.test(code)) {
|
||||
return [{ file, fix: "register(): assertEnv(ipalEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(ipalEnvRules(…))', severity: 'error' }]
|
||||
return [{ file, fix: "register(): assertEnv(iaplEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(iaplEnvRules(…))', severity: 'error' }]
|
||||
}
|
||||
const out: RuleFinding[] = []
|
||||
if (!/ipalEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without ipalEnvRules — the plugin variables are not checked', severity: 'warning' })}
|
||||
if (!/iaplEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without iaplEnvRules — the plugin variables are not checked', severity: 'warning' })}
|
||||
if (/from\s+['"]@intecion\/ipal-kit['"]/.test(code)) {out.push({ file, fix: "import from '@intecion/ipal-kit/env'", message: 'instrumentation.ts imports the package root (Edge build breaks)', severity: 'error' })}
|
||||
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
|
||||
const flag = (name: string) => new RegExp(`\\b${name}\\s*:`).test(code)
|
||||
if (/buildR2Storage/.test(cfg) && !flag('storage')) {out.push({ file, fix: 'ipalEnvRules({ storage: true })', message: 'R2 is wired but ipalEnvRules has no storage flag', severity: 'warning' })}
|
||||
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg) && !flag('cookieCrawl')) {out.push({ file, fix: 'ipalEnvRules({ cookieCrawl: true })', message: 'cookieScanner.crawl is on but ipalEnvRules has no cookieCrawl flag', severity: 'warning' })}
|
||||
if (!flag('ipHeader')) {out.push({ file, fix: 'ipalEnvRules({ ipHeader: true })', message: 'ipalEnvRules has no ipHeader flag — rate limits trust no client-IP header', severity: 'warning' })}
|
||||
if (!flag('databaseName')) {out.push({ file, fix: "ipalEnvRules({ databaseName: { domain: '<domain>' } })", message: 'ipalEnvRules has no databaseName check', severity: 'info' })}
|
||||
if (/buildR2Storage/.test(cfg) && !flag('storage')) {out.push({ file, fix: 'iaplEnvRules({ storage: true })', message: 'R2 is wired but iaplEnvRules has no storage flag', severity: 'warning' })}
|
||||
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg) && !flag('cookieCrawl')) {out.push({ file, fix: 'iaplEnvRules({ cookieCrawl: true })', message: 'cookieScanner.crawl is on but iaplEnvRules has no cookieCrawl flag', severity: 'warning' })}
|
||||
if (!flag('ipHeader')) {out.push({ file, fix: 'iaplEnvRules({ ipHeader: true })', message: 'iaplEnvRules has no ipHeader flag — rate limits trust no client-IP header', severity: 'warning' })}
|
||||
if (!flag('databaseName')) {out.push({ file, fix: "iaplEnvRules({ databaseName: { domain: '<domain>' } })", message: 'iaplEnvRules has no databaseName check', severity: 'info' })}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/env.md',
|
||||
@@ -74,15 +74,15 @@ export const envRules: DoctorRule[] = [
|
||||
if (!ctx.env.example) {return [{ fix: 'add .env.example (names, placeholder values)', message: 'no .env.example', severity: 'error' }]}
|
||||
const out: RuleFinding[] = []
|
||||
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
|
||||
const want = ['DATABASE_URI', 'PAYLOAD_SECRET', 'NEXT_PUBLIC_SERVER_URL', 'IPAL_IP_HEADER']
|
||||
const want = ['DATABASE_URI', 'PAYLOAD_SECRET', 'NEXT_PUBLIC_SERVER_URL', 'IAPL_IP_HEADER']
|
||||
if (/buildR2Storage/.test(cfg) && !ctx.auditSkips.has('r2')) {want.push('R2_BUCKET', 'R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_PUBLIC_URL')}
|
||||
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg)) {want.push('IPAL_COOKIE_SCAN_URL', 'IPAL_COOKIE_SCAN_TOKEN')}
|
||||
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg)) {want.push('IAPL_COOKIE_SCAN_URL', 'IAPL_COOKIE_SCAN_TOKEN')}
|
||||
const missing = want.filter((v) => !(v in ctx.env.example!))
|
||||
if (missing.length) {out.push({ file: '.env.example', fix: 'add the names (empty or placeholder values)', message: `.env.example lacks ${missing.join(', ')}`, severity: 'warning' })}
|
||||
// A real-looking credential in a committed file.
|
||||
const creds = (ctx.env.example.DATABASE_URI ?? '').match(/^[a-z+]+:\/\/([^@/]+)@/i)?.[1]
|
||||
if (creds && !PLACEHOLDER.test(creds)) {out.push({ file: '.env.example', fix: 'replace with USER:PASS', message: 'DATABASE_URI in .env.example carries credentials', severity: 'error' })}
|
||||
for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IPAL_DOCTOR_TOKEN']) {
|
||||
for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IAPL_DOCTOR_TOKEN']) {
|
||||
const value = ctx.env.example[key]
|
||||
if (value && value.length >= 16 && !PLACEHOLDER.test(value)) {out.push({ file: '.env.example', fix: `leave ${key} empty`, message: `${key} in .env.example has a value`, severity: 'error' })}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ const has = (ctx: DoctorContext, dir: string, names: string[]) => names.some((n)
|
||||
|
||||
/**
|
||||
* The frontend folder, found by structure rather than by name (a route group's name never reaches the URL):
|
||||
* `ipal-doctor.json` `layout.frontend` wins; else every `app/(<group>)` except `(payload)`, and `app` itself,
|
||||
* `iapl-doctor.json` `layout.frontend` wins; else every `app/(<group>)` except `(payload)`, and `app` itself,
|
||||
* holding the catch-all page — one with a `[locale]` page first. No match → `app/(frontend)` (the convention).
|
||||
*/
|
||||
export function findFrontend(ctx: DoctorContext): FrontendLayout {
|
||||
@@ -67,7 +67,7 @@ export function findFrontend(ctx: DoctorContext): FrontendLayout {
|
||||
return { ambiguous: best.filter((g) => g !== dir), dir, multi: localized.length > 0 }
|
||||
}
|
||||
|
||||
/** Files AGENT.md §3 expects — each as its accepted names — with the `ipal-audit-skip` key that drops it. */
|
||||
/** Files AGENT.md §3 expects — each as its accepted names — with the `iapl-audit-skip` key that drops it. */
|
||||
function requiredFiles(ctx: DoctorContext, frontend: FrontendLayout): Array<[string[], string?]> {
|
||||
const fe = frontend.multi ? `${frontend.dir}/[locale]` : frontend.dir
|
||||
const ts = (base: string) => [`${base}.ts`, `${base}.tsx`]
|
||||
@@ -114,14 +114,14 @@ export const layoutRules: DoctorRule[] = [
|
||||
const frontend = findFrontend(ctx)
|
||||
const out: RuleFinding[] = []
|
||||
if (frontend.missingOverride) {
|
||||
out.push({ file: 'ipal-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' })
|
||||
out.push({ file: 'iapl-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' })
|
||||
}
|
||||
if (frontend.ambiguous.length) {
|
||||
out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in ipal-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' })
|
||||
out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in iapl-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' })
|
||||
}
|
||||
const missing = requiredFiles(ctx, frontend).filter(([names, key]) => !(key && ctx.auditSkips.has(key)) && !names.some((n) => ctx.exists(`${ctx.src}${n}`)))
|
||||
if (missing.length) {
|
||||
out.push({ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' })
|
||||
out.push({ fix: 'the iapl-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' })
|
||||
}
|
||||
return out
|
||||
},
|
||||
@@ -149,7 +149,7 @@ export const layoutRules: DoctorRule[] = [
|
||||
const allow = new Set([...(ctx.config.layout?.allow ?? []), ...DEFAULT_SRC_ALLOW])
|
||||
const extra = ctx.list('src').filter((n) => !allow.has(n) && !n.startsWith('.'))
|
||||
return extra.length
|
||||
? [{ fix: 'move into the convention, or add to ipal-doctor.json "layout": { "allow": [...] }', message: `src/ entries outside the convention: ${extra.join(', ')}`, severity: 'info' }]
|
||||
? [{ fix: 'move into the convention, or add to iapl-doctor.json "layout": { "allow": [...] }', message: `src/ entries outside the convention: ${extra.join(', ')}`, severity: 'info' }]
|
||||
: []
|
||||
},
|
||||
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
|
||||
@@ -236,7 +236,7 @@ export const layoutRules: DoctorRule[] = [
|
||||
if (ctx.deep?.importMapCurrent === false) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: 'the committed import map differs from a freshly generated one', severity: 'error' })}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/agent/skills/ipal-reference/SKILL.md',
|
||||
docs: 'docs/agent/skills/iapl-reference/SKILL.md',
|
||||
group: 'layout',
|
||||
source: 'static',
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@ export function createLiveFetcher(url: string, options: { adminRoute?: string; s
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch(base + path, {
|
||||
headers: { 'user-agent': 'ipal-doctor (+https://intecion.com; read-only)' },
|
||||
headers: { 'user-agent': 'iapl-doctor (+https://intecion.com; read-only)' },
|
||||
redirect: init.redirect ?? 'follow',
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
})
|
||||
@@ -62,8 +62,8 @@ export const liveRules: DoctorRule[] = [
|
||||
const home = await ctx.live!.fetch('/')
|
||||
if (!home.status) {return []}
|
||||
const isNoindex = noindex(home.text, home.headers.get('x-robots-tag'))
|
||||
if (ctx.live!.staging) {return isNoindex ? [] : [{ fix: 'IPAL_NOINDEX=1 on the staging app', message: 'the staging site is indexable', severity: 'error' }]}
|
||||
return isNoindex ? [{ fix: 'unset IPAL_NOINDEX on production and redeploy', message: 'the production home page is noindex', severity: 'error' }] : []
|
||||
if (ctx.live!.staging) {return isNoindex ? [] : [{ fix: 'IAPL_NOINDEX=1 on the staging app', message: 'the staging site is indexable', severity: 'error' }]}
|
||||
return isNoindex ? [{ fix: 'unset IAPL_NOINDEX on production and redeploy', message: 'the production home page is noindex', severity: 'error' }] : []
|
||||
},
|
||||
docs: 'docs/seo.md',
|
||||
group: 'live',
|
||||
@@ -72,9 +72,9 @@ export const liveRules: DoctorRule[] = [
|
||||
{
|
||||
id: 'live-seo',
|
||||
check: async (ctx) => {
|
||||
// ipal-seo-check of the doctor's own version: robots, sitemap, canonical, hreflang, noindex, JSON-LD, llms, MCP.
|
||||
const script = join(ctx.packageRoot, 'docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs')
|
||||
if (!existsSync(script)) {return [{ message: 'ipal-seo-check not found', severity: 'warning' }]}
|
||||
// iapl-seo-check of the doctor's own version: robots, sitemap, canonical, hreflang, noindex, JSON-LD, llms, MCP.
|
||||
const script = join(ctx.packageRoot, 'docs/agent/skills/iapl-seo-check/scripts/seo-check.mjs')
|
||||
if (!existsSync(script)) {return [{ message: 'iapl-seo-check not found', severity: 'warning' }]}
|
||||
const home = await ctx.live!.fetch('/', { redirect: 'manual' })
|
||||
if (!home.status) {return []}
|
||||
const res = run(process.execPath, [script, ctx.live!.url, '--max', '10'], ctx.root, 300_000)
|
||||
@@ -84,10 +84,10 @@ export const liveRules: DoctorRule[] = [
|
||||
const items = line.items.length ? `: ${line.items.slice(0, 3).join('; ')}${line.items.length > 3 ? ` … +${line.items.length - 3}` : ''}` : ''
|
||||
out.push({ fix: line.rule, message: `${line.title}${items}`, rule: `live-seo:${titleSlug(line.title.replace(/[\d/]+/g, ' '))}`, severity: line.level })
|
||||
}
|
||||
if (res.code === 2) {out.push({ message: `ipal-seo-check: ${res.stderr.trim()}`, severity: 'error' })}
|
||||
if (res.code === 2) {out.push({ message: `iapl-seo-check: ${res.stderr.trim()}`, severity: 'error' })}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/agent/skills/ipal-seo-check/SKILL.md',
|
||||
docs: 'docs/agent/skills/iapl-seo-check/SKILL.md',
|
||||
group: 'live',
|
||||
source: 'live',
|
||||
},
|
||||
|
||||
@@ -104,9 +104,9 @@ export const securityRules: DoctorRule[] = [
|
||||
const code = cfg(ctx)
|
||||
const twoFactor = code.match(/twoFactor\s*:([^\n]*)/)?.[1] ?? ''
|
||||
if (/\?\s*false\b|:\s*false\b|&&/.test(twoFactor) && /payloadTotp/.test(twoFactor)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor: { issuer, plugin: payloadTotp } without a switch', message: '2FA can be turned off at runtime (a condition on twoFactor)', severity: 'warning' })}
|
||||
if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
|
||||
if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "iapl({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
|
||||
else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })}
|
||||
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in ipal-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
|
||||
if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in iapl-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })}
|
||||
if (/windowHours\s*:\s*(?:false|0)\b/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor.requireSetup.windowHours: 72 (the default)', message: 'no time limit for 2FA setup: an account that never sets it up can be taken over with its password at any time', severity: 'info' })}
|
||||
// Postgres / SQLite: the 2FA collection has the column `totp_setup_from` (whenever 2FA is on). Without a
|
||||
// migration that adds it, every query on the collection fails in production — nobody can log in.
|
||||
@@ -146,12 +146,12 @@ export const securityRules: DoctorRule[] = [
|
||||
id: 'access-missing',
|
||||
check: (ctx) => {
|
||||
const code = cfg(ctx)
|
||||
if (!/ipalKit\s*\(/.test(code)) {return []}
|
||||
if (!/iapl\s*\(/.test(code)) {return []}
|
||||
// `access: { authCollection | defaultRole | … }`, an empty `access: {}`, or a variable whose name says so
|
||||
const set = /\baccess\s*:\s*\{\}/.test(code.replace(/\s+/g, '')) || /\baccess\s*:\s*\{[^{}]*\b(?:authCollection|defaultRole|authAccess|firstUserAdmin|staffCollections|panelRole|selfRegistration|password)\b/.test(code) || /\baccess\s*:\s*\w*[aA]ccess\w*\s*[,}]/.test(code)
|
||||
return set
|
||||
? []
|
||||
: [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in ipal-doctor.json", message: 'ipalKit has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }]
|
||||
: [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "iapl({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in iapl-doctor.json", message: 'iapl has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }]
|
||||
},
|
||||
docs: 'docs/access.md',
|
||||
group: 'security',
|
||||
@@ -175,7 +175,7 @@ export const securityRules: DoctorRule[] = [
|
||||
id: 'open-signup',
|
||||
check: (ctx) =>
|
||||
(ctx.deep?.openSignUp ?? []).map((slug) => ({
|
||||
fix: `intended (a customer zone)? silence it with a reason in ipal-doctor.json; otherwise give "${slug}" a create rule`,
|
||||
fix: `intended (a customer zone)? silence it with a reason in iapl-doctor.json; otherwise give "${slug}" a create rule`,
|
||||
message: `sign-up is open on "${slug}": an anonymous request can create an account there`,
|
||||
severity: 'info' as const,
|
||||
})),
|
||||
@@ -261,7 +261,7 @@ export const securityRules: DoctorRule[] = [
|
||||
check: (ctx) => {
|
||||
const code = cfg(ctx)
|
||||
if (!/cookieScanner\s*:/.test(code) || /cookieScanner\s*:\s*false/.test(code)) {
|
||||
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: 'ipalKit({ cookieScanner: { crawl: true } }) + generate:importmap', message: 'the cookie scanner is off', severity: 'error' }]
|
||||
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: 'iapl({ cookieScanner: { crawl: true } }) + generate:importmap', message: 'the cookie scanner is off', severity: 'error' }]
|
||||
}
|
||||
const out: RuleFinding[] = []
|
||||
if (!/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(code)) {out.push({ fix: 'cookieScanner: { crawl: true } (shared cookie-crawler service)', message: 'cookie scanner without crawl — no scheduled site check', severity: 'info' })}
|
||||
@@ -277,7 +277,7 @@ export const securityRules: DoctorRule[] = [
|
||||
check: async (ctx) => {
|
||||
const out: RuleFinding[] = []
|
||||
const code = cfg(ctx)
|
||||
if (lt(ctx.pluginVersion, '1.14.5')) {out.push({ message: `admin link previews (adminMeta) need ipal-kit ≥ 1.14.5 (installed ${ctx.pluginVersion ?? 'none'})`, severity: 'warning' })}
|
||||
if (lt(ctx.pluginVersion, '1.14.5')) {out.push({ message: `admin link previews (adminMeta) need IAPL ≥ 1.14.5 (installed ${ctx.pluginVersion ?? 'none'})`, severity: 'warning' })}
|
||||
if (/adminMeta\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'adminMeta: false — the panel has no link preview and no noindex from the plugin', severity: 'warning' })}
|
||||
if (/agency\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'agency: false — no technology credit', severity: 'warning' })}
|
||||
if (ctx.live && !out.length) {
|
||||
|
||||
@@ -32,20 +32,20 @@ export const seedRules: DoctorRule[] = [
|
||||
for (const [name, command] of Object.entries(ctx.pkg.scripts ?? {})) {
|
||||
if (!/seed/i.test(name)) {continue}
|
||||
if (/fresh|reset/i.test(name)) {out.push({ file: 'package.json', fix: 'remove it — seeds never delete (seeding.md)', message: `script "${name}" re-creates content from scratch`, severity: 'error' })}
|
||||
if (/IPAL_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IPAL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })}
|
||||
if (/IAPL_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IAPL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })}
|
||||
const entry = command.match(/(?:^|\s)([\w./@-]+\.[cm]?[jt]s)(?:\s|$)/)?.[1]?.replace(/^\.\//, '')
|
||||
if (!entry) {continue}
|
||||
if (!ctx.exists(entry)) {out.push({ file: 'package.json', message: `script "${name}" runs ${entry}, which does not exist`, severity: 'warning' }); continue}
|
||||
const files = seedFiles(ctx, entry)
|
||||
const code = files.map((f) => stripComments(ctx.read(f))).join('\n')
|
||||
if (!/createSeeder\s*\(/.test(code)) {out.push({ file: entry, fix: "createSeeder(payload) from '@intecion/ipal-kit/seed' (only / SEED_ONLY, full-seed guard)", message: `script "${name}" does not use the ipal-kit seed helper`, severity: 'warning' })}
|
||||
if (!/createSeeder\s*\(/.test(code)) {out.push({ file: entry, fix: "createSeeder(payload) from '@intecion/ipal-kit/seed' (only / SEED_ONLY, full-seed guard)", message: `script "${name}" does not use the IAPL seed helper`, severity: 'warning' })}
|
||||
const deleting = files.filter((f) => DELETES.test(stripComments(ctx.read(f))))
|
||||
if (deleting.length) {out.push({ file: deleting[0], fix: 'seeds never delete — an editor removes records in the panel (seeding.md)', message: `script "${name}" deletes records (${deleting.join(', ')})`, severity: 'error' })}
|
||||
if (/guard\s*:\s*false|allowFull\s*:\s*true/.test(code)) {out.push({ file: entry, fix: 'keep the guard; IPAL_SEED_ALLOW_FULL=1 for one run with the owner\'s OK', message: `script "${name}" turns the full-seed guard off in code`, severity: 'error' })}
|
||||
if (/guard\s*:\s*false|allowFull\s*:\s*true/.test(code)) {out.push({ file: entry, fix: 'keep the guard; IAPL_SEED_ALLOW_FULL=1 for one run with the owner\'s OK', message: `script "${name}" turns the full-seed guard off in code`, severity: 'error' })}
|
||||
if (ctx.launched && /createSeeder\s*\(/.test(code) && !/\bonly\s*:/.test(code)) {out.push({ file: entry, fix: 'run it with SEED_ONLY="pages:<slug>,global:<slug>" or pass only: [...] (seeding.md → after launch)', message: `script "${name}" has no record list — after launch every run needs SEED_ONLY`, severity: 'warning' })}
|
||||
}
|
||||
for (const file of ['.env.example', '.env.production']) {
|
||||
if (/^\s*IPAL_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IPAL_SEED_ALLOW_FULL=1`, severity: 'error' })}
|
||||
if (/^\s*IAPL_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IAPL_SEED_ALLOW_FULL=1`, severity: 'error' })}
|
||||
}
|
||||
return out
|
||||
},
|
||||
|
||||
@@ -23,7 +23,7 @@ export function parseToolOutput(text: string): ToolLine[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* ipal-audit titles that are a doctor rule of their own — the finding is reported under that id
|
||||
* iapl-audit titles that are a doctor rule of their own — the finding is reported under that id
|
||||
* (one place per check: the audit script). Everything else lands under `audit`.
|
||||
*/
|
||||
export const AUDIT_RULE_MAP: Array<[RegExp, string]> = [
|
||||
@@ -37,7 +37,7 @@ export const AUDIT_RULE_MAP: Array<[RegExp, string]> = [
|
||||
[/^middleware\.ts exists$/, 'layout-forbidden'],
|
||||
[/^barrel index\.ts$/, 'naming'],
|
||||
[/^hardcoded text in (blocks|components\/layout)$|^hardcoded Polish text in code$/, 'i18n-literals'],
|
||||
[/^hex colors in (classes|inline styles)$|^design-token standard not wired$|^ipal-tokens --check$/, 'blocks-tokens'],
|
||||
[/^hex colors in (classes|inline styles)$|^design-token standard not wired$|^iapl-tokens --check$/, 'blocks-tokens'],
|
||||
[/^own block renderer switch$/, 'blocks-registry'],
|
||||
]
|
||||
|
||||
@@ -52,11 +52,11 @@ export const toolingRules: DoctorRule[] = [
|
||||
id: 'audit',
|
||||
check: (ctx) => {
|
||||
// The audit script of the doctor's own version (the project's copy in .agents may be stale).
|
||||
const script = join(ctx.packageRoot, 'docs/agent/skills/ipal-audit/scripts/audit.sh')
|
||||
if (!existsSync(script)) {return [{ message: `ipal-audit not found (${script})`, severity: 'warning' }]}
|
||||
const script = join(ctx.packageRoot, 'docs/agent/skills/iapl-audit/scripts/audit.sh')
|
||||
if (!existsSync(script)) {return [{ message: `iapl-audit not found (${script})`, severity: 'warning' }]}
|
||||
if (!ctx.src) {return []}
|
||||
const res = run('bash', [script, '--quick'], ctx.root, 300_000)
|
||||
if (res.code !== 0 && res.code !== 1) {return [{ message: `ipal-audit --quick could not run (exit ${res.code}): ${res.stderr.trim().split('\n')[0] ?? ''}`, severity: 'warning' }]}
|
||||
if (res.code !== 0 && res.code !== 1) {return [{ message: `iapl-audit --quick could not run (exit ${res.code}): ${res.stderr.trim().split('\n')[0] ?? ''}`, severity: 'warning' }]}
|
||||
const out: RuleFinding[] = []
|
||||
for (const line of parseToolOutput(res.stdout)) {
|
||||
const mapped = AUDIT_RULE_MAP.find(([re]) => re.test(line.title))?.[1]
|
||||
@@ -76,7 +76,7 @@ export const toolingRules: DoctorRule[] = [
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/agent/skills/ipal-audit/SKILL.md',
|
||||
docs: 'docs/agent/skills/iapl-audit/SKILL.md',
|
||||
group: 'audit',
|
||||
source: 'static',
|
||||
},
|
||||
|
||||
@@ -43,7 +43,7 @@ export const versionRules: DoctorRule[] = [
|
||||
}
|
||||
return []
|
||||
},
|
||||
docs: 'docs/agent/skills/ipal-upgrade/SKILL.md',
|
||||
docs: 'docs/agent/skills/iapl-upgrade/SKILL.md',
|
||||
group: 'versions',
|
||||
source: 'static',
|
||||
},
|
||||
@@ -145,12 +145,12 @@ export const versionRules: DoctorRule[] = [
|
||||
const [a, b] = [parseVersion(ctx.pluginVersion)!, parseVersion(latest)!]
|
||||
const minorsBehind = a[0] < b[0] ? 99 : b[1] - a[1]
|
||||
return [{
|
||||
fix: `pnpm add ${PKG}@${latest} — then the ipal-upgrade skill`,
|
||||
fix: `pnpm add ${PKG}@${latest} — then the iapl-upgrade skill`,
|
||||
message: `${PKG} ${ctx.pluginVersion} installed, ${latest} is out`,
|
||||
severity: minorsBehind >= 2 ? 'error' : 'warning',
|
||||
}]
|
||||
},
|
||||
docs: 'docs/agent/skills/ipal-upgrade/SKILL.md',
|
||||
docs: 'docs/agent/skills/iapl-upgrade/SKILL.md',
|
||||
group: 'versions',
|
||||
source: 'registry',
|
||||
},
|
||||
|
||||
+15
-15
@@ -39,7 +39,7 @@ export const doctorRules: DoctorRule[] = [
|
||||
...deepRules,
|
||||
]
|
||||
|
||||
/** `ipal-audit-skip` keys (AGENTS.md) → doctor rules they silence (the audit script honours the rest itself). */
|
||||
/** `iapl-audit-skip` keys (AGENTS.md) → doctor rules they silence (the audit script honours the rest itself). */
|
||||
export const AUDIT_SKIP_RULES: Record<string, string[]> = {
|
||||
csp: ['csp'],
|
||||
twofactor: ['2fa'],
|
||||
@@ -60,14 +60,14 @@ export type RunDoctorOptions = {
|
||||
/** The doctor's package root (bin/, docs/, dist/). */
|
||||
packageRoot: string
|
||||
root: string
|
||||
/** Extra rules (a project's own, `extraRules` in ipal-doctor.json are added too). */
|
||||
/** Extra rules (a project's own, `extraRules` in iapl-doctor.json are added too). */
|
||||
rules?: DoctorRule[]
|
||||
skip?: string[]
|
||||
staging?: boolean
|
||||
today?: string
|
||||
/** Live site; with IPAL_DOCTOR_TOKEN set (and no --deep) the deep rules read GET /api/ipal/doctor. */
|
||||
/** Live site; with IAPL_DOCTOR_TOKEN set (and no --deep) the deep rules read GET /api/ipal/doctor. */
|
||||
url?: string
|
||||
/** Store first-seen dates (CSP report-only) in ipal-doctor.json. Default: only outside CI. */
|
||||
/** Store first-seen dates (CSP report-only) in iapl-doctor.json. Default: only outside CI. */
|
||||
writeSeen?: boolean
|
||||
}
|
||||
|
||||
@@ -76,10 +76,10 @@ export function runDeepProbe(ctx: DoctorContext): DoctorStatus {
|
||||
const probe = join(ctx.packageRoot, 'dist/modules/doctor/probe.js')
|
||||
if (!existsSync(probe)) {return { error: `the probe is missing (${probe}) — build the plugin` }}
|
||||
const res = run('pnpm', ['exec', 'payload', 'run', probe], ctx.root, 300_000)
|
||||
const line = res.stdout.split('\n').find((l) => l.startsWith('IPAL_DOCTOR_STATUS '))
|
||||
const line = res.stdout.split('\n').find((l) => l.startsWith('IAPL_DOCTOR_STATUS '))
|
||||
if (!line) {return { error: `payload run gave no status (exit ${res.code}): ${(res.stderr || res.stdout).trim().split('\n').slice(-1)[0] ?? ''}` }}
|
||||
try {
|
||||
return JSON.parse(line.slice('IPAL_DOCTOR_STATUS '.length)) as DoctorStatus
|
||||
return JSON.parse(line.slice('IAPL_DOCTOR_STATUS '.length)) as DoctorStatus
|
||||
} catch {
|
||||
return { error: 'payload run printed an unreadable status' }
|
||||
}
|
||||
@@ -105,19 +105,19 @@ export function globToRegExp(glob: string): RegExp {
|
||||
|
||||
const inFiles = (file: string | undefined, globs: string[] | undefined) => !globs?.length || (!!file && globs.some((g) => globToRegExp(g).test(file)))
|
||||
|
||||
/** Applies ipal-doctor.json `rules` and `ipal-audit-skip` lines: off (silenced, kept in JSON), severity, until. */
|
||||
/** Applies iapl-doctor.json `rules` and `iapl-audit-skip` lines: off (silenced, kept in JSON), severity, until. */
|
||||
export function applySettings(findings: DoctorFinding[], ctx: DoctorContext): DoctorFinding[] {
|
||||
const settings = ctx.config.rules ?? {}
|
||||
const out: DoctorFinding[] = []
|
||||
for (const [id, s] of Object.entries(settings)) {
|
||||
if (!s || typeof s !== 'object') {continue}
|
||||
if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "<why>" — an entry without one is ignored', message: `ipal-doctor.json: rule "${id}" has no reason, so it is ignored`, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
||||
else if (s.severity && !SEVERITIES.includes(s.severity)) {out.push({ message: `ipal-doctor.json: rule "${id}" has an unknown severity "${s.severity}"`, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
||||
else if (s.until && ctx.today > s.until) {out.push({ fix: 'fix the finding, or extend "until" with a new reason', message: `ipal-doctor.json: the setting for "${id}" expired on ${s.until}`, rule: 'doctor-config', severity: 'warning', source: 'static' })}
|
||||
if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "<why>" — an entry without one is ignored', message: `iapl-doctor.json: rule "${id}" has no reason, so it is ignored`, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
||||
else if (s.severity && !SEVERITIES.includes(s.severity)) {out.push({ message: `iapl-doctor.json: rule "${id}" has an unknown severity "${s.severity}"`, rule: 'doctor-config', severity: 'error', source: 'static' })}
|
||||
else if (s.until && ctx.today > s.until) {out.push({ fix: 'fix the finding, or extend "until" with a new reason', message: `iapl-doctor.json: the setting for "${id}" expired on ${s.until}`, rule: 'doctor-config', severity: 'warning', source: 'static' })}
|
||||
}
|
||||
const skips = new Map<string, string>()
|
||||
for (const [key, reason] of ctx.auditSkips) {
|
||||
for (const id of AUDIT_SKIP_RULES[key] ?? []) {skips.set(id, reason || `ipal-audit-skip: ${key}`)}
|
||||
for (const id of AUDIT_SKIP_RULES[key] ?? []) {skips.set(id, reason || `iapl-audit-skip: ${key}`)}
|
||||
}
|
||||
for (const f of findings) {
|
||||
const s = settings[f.rule] ?? settings[f.rule.split(':')[0]]
|
||||
@@ -152,8 +152,8 @@ export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport
|
||||
const live = options.url ? createLiveFetcher(options.url, { adminRoute: options.adminRoute, staging: options.staging }) : null
|
||||
const ctx = createDoctorContext({ config: options.config, envFile: options.envFile, live, offline: options.offline, packageRoot: options.packageRoot, root, today: options.today })
|
||||
|
||||
// Deep status: the probe (--deep), the endpoint (--url + IPAL_DOCTOR_TOKEN), or none.
|
||||
const token = process.env.IPAL_DOCTOR_TOKEN?.trim()
|
||||
// Deep status: the probe (--deep), the endpoint (--url + IAPL_DOCTOR_TOKEN), or none.
|
||||
const token = process.env.IAPL_DOCTOR_TOKEN?.trim()
|
||||
if (options.deepStatus !== undefined) {ctx.deep = options.deepStatus}
|
||||
else if (options.deep) {ctx.deep = runDeepProbe({ ...ctx, root })}
|
||||
else if (options.url && token && token.length >= 32) {ctx.deep = await fetchDeepStatus(options.url, token)}
|
||||
@@ -182,9 +182,9 @@ export async function runDoctor(options: RunDoctorOptions): Promise<DoctorReport
|
||||
|
||||
// First-seen dates (CSP report-only → warning after 4 weeks): stored outside CI when the file exists.
|
||||
const writeSeen = options.writeSeen ?? !process.env.CI
|
||||
if (writeSeen && findings.some((f) => f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, 'ipal-doctor.json'))) {
|
||||
if (writeSeen && findings.some((f) => f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, 'iapl-doctor.json'))) {
|
||||
const current = loadDoctorConfig(root).config
|
||||
writeFileSync(join(root, 'ipal-doctor.json'), `${JSON.stringify({ ...current, seen: { ...current.seen, 'csp-report-only': ctx.today } }, null, 2)}\n`)
|
||||
writeFileSync(join(root, 'iapl-doctor.json'), `${JSON.stringify({ ...current, seen: { ...current.seen, 'csp-report-only': ctx.today } }, null, 2)}\n`)
|
||||
}
|
||||
|
||||
const final = applySettings(findings, ctx).sort((a, b) => Number(!!a.silenced) - Number(!!b.silenced) || RANK[a.severity] - RANK[b.severity])
|
||||
|
||||
@@ -21,7 +21,7 @@ export function pluginVersion(): string {
|
||||
type CollectionLike = { fields?: Array<{ name?: string }>; slug: string }
|
||||
|
||||
/**
|
||||
* Read-only counts for ipal-doctor's deep rules: users without TOTP, cookies waiting for approval,
|
||||
* Read-only counts for iapl-doctor's deep rules: users without TOTP, cookies waiting for approval,
|
||||
* the versions. Counts and booleans only — never names, e-mails or values.
|
||||
*/
|
||||
export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorStatus> {
|
||||
@@ -82,7 +82,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
export type DoctorEndpointOptions = {
|
||||
/** Who may read the status besides a valid token, e.g. `({ req }) => isAdmin(req.user, req.payload)` (a staff admin; the second factor is checked for you). */
|
||||
access?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
|
||||
/** Env variable that holds the token (≥ 32 characters). Default IPAL_DOCTOR_TOKEN. */
|
||||
/** Env variable that holds the token (≥ 32 characters). Default IAPL_DOCTOR_TOKEN. */
|
||||
tokenVar?: string
|
||||
}
|
||||
|
||||
@@ -93,17 +93,17 @@ const sameToken = (given: string, expected: string) => {
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/ipal/doctor — the deep status for `ipal-doctor --url`. Off (404) until the token variable
|
||||
* GET /api/ipal/doctor — the deep status for `iapl-doctor --url`. Off (404) until the token variable
|
||||
* holds at least 32 characters; then `Authorization: Bearer <token>` (or `access`) is required.
|
||||
* Rate-limited per client IP. `ipalKit({ doctor: false })` removes the endpoint.
|
||||
* Rate-limited per client IP. `iapl({ doctor: false })` removes the endpoint.
|
||||
*/
|
||||
export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoint {
|
||||
const tokenVar = options.tokenVar ?? 'IPAL_DOCTOR_TOKEN'
|
||||
const tokenVar = options.tokenVar ?? 'IAPL_DOCTOR_TOKEN'
|
||||
return {
|
||||
handler: async (req: PayloadRequest) => {
|
||||
const token = process.env[tokenVar]?.trim() ?? ''
|
||||
if (token.length < 32) {return Response.json({ error: 'Not found' }, { status: 404 })}
|
||||
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'ipal-doctor', windowMs: 60_000 })
|
||||
const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'iapl-doctor', windowMs: 60_000 })
|
||||
if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })}
|
||||
const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim()
|
||||
const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && (await options.access({ req })) : false)
|
||||
|
||||
@@ -12,7 +12,7 @@ export type DoctorFinding = {
|
||||
file?: string
|
||||
fix?: string
|
||||
message: string
|
||||
/** Why the project silenced it (from ipal-doctor.json or an `ipal-audit-skip` line). */
|
||||
/** Why the project silenced it (from iapl-doctor.json or an `iapl-audit-skip` line). */
|
||||
reason?: string
|
||||
rule: string
|
||||
severity: DoctorSeverity
|
||||
@@ -23,7 +23,7 @@ export type DoctorFinding = {
|
||||
/** What a rule returns — the runner adds rule, source and docs. */
|
||||
export type RuleFinding = { rule?: string } & Omit<DoctorFinding, 'reason' | 'rule' | 'silenced' | 'source'>
|
||||
|
||||
/** One silencing / override entry in ipal-doctor.json. */
|
||||
/** One silencing / override entry in iapl-doctor.json. */
|
||||
export type DoctorRuleSetting = {
|
||||
/** Only findings in these files (globs: `*` within a folder, `**` across folders), e.g. an approved exception. */
|
||||
files?: string[]
|
||||
@@ -34,7 +34,7 @@ export type DoctorRuleSetting = {
|
||||
until?: string
|
||||
}
|
||||
|
||||
/** ipal-doctor.json in the project root. Every key is optional. */
|
||||
/** iapl-doctor.json in the project root. Every key is optional. */
|
||||
export type DoctorConfig = {
|
||||
/** The site's production domain (dots allowed) — the base of the database names. */
|
||||
domain?: string
|
||||
|
||||
@@ -167,7 +167,7 @@ export const graphAdapter =
|
||||
const env = readGraphEnv()
|
||||
if (!env) {
|
||||
payload.logger.error(
|
||||
'[ipal] Email not sent: Graph is not configured. Set GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER.',
|
||||
'[iapl] Email not sent: Graph is not configured. Set GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER.',
|
||||
)
|
||||
return {
|
||||
code: 'graph-not-configured',
|
||||
@@ -192,7 +192,7 @@ export const graphAdapter =
|
||||
|
||||
const to = toRecipients(message.to)
|
||||
if (to.length === 0) {
|
||||
payload.logger.error('[ipal] Email not sent: no valid recipient.')
|
||||
payload.logger.error('[iapl] Email not sent: no valid recipient.')
|
||||
return { error: 'Enter a valid recipient address.', sent: false }
|
||||
}
|
||||
|
||||
@@ -226,7 +226,7 @@ export const graphAdapter =
|
||||
// Attachments: small ones ride in the same call; larger ones need a draft and an upload session.
|
||||
const attachments = toGraphAttachments(message)
|
||||
if (!attachments) {
|
||||
payload.logger.error('[ipal] Graph: an attachment is not in memory (a path or a stream) — pass its content as a Buffer.')
|
||||
payload.logger.error('[iapl] Graph: an attachment is not in memory (a path or a stream) — pass its content as a Buffer.')
|
||||
return { detail: 'Attachment content must be a Buffer or a string.', error: 'The e-mail was not sent.', sent: false }
|
||||
}
|
||||
const fetchImpl = args.fetchImpl ?? fetch
|
||||
@@ -245,7 +245,7 @@ export const graphAdapter =
|
||||
const roles = tokenRoles(token)
|
||||
if (roles && !roles.includes(GRAPH_LARGE_PERMISSION)) {
|
||||
const detail = `The Microsoft Graph app lacks the ${GRAPH_LARGE_PERMISSION} application permission, so it cannot send attachments of 3 MB and more.`
|
||||
payload.logger.error(`[ipal] ${detail}`)
|
||||
payload.logger.error(`[iapl] ${detail}`)
|
||||
return { code: 'graph-permission', detail, error: 'The e-mail was not sent.', sent: false }
|
||||
}
|
||||
const large = await sendLargeGraphMail(attachments, {
|
||||
@@ -277,11 +277,11 @@ export const graphAdapter =
|
||||
return { sent: true }
|
||||
}
|
||||
const detail = await res.text()
|
||||
payload.logger.error(`[ipal] Graph sendMail failed (${res.status}): ${detail}`)
|
||||
payload.logger.error(`[iapl] Graph sendMail failed (${res.status}): ${detail}`)
|
||||
return { detail: `Microsoft Graph refused the e-mail (${res.status}).`, error: 'The e-mail was not sent.', sent: false }
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
payload.logger.error(`[ipal] Graph send error: ${msg}`)
|
||||
payload.logger.error(`[iapl] Graph send error: ${msg}`)
|
||||
return { detail: msg, error: 'The e-mail was not sent.', sent: false }
|
||||
}
|
||||
},
|
||||
|
||||
@@ -126,7 +126,7 @@ export async function sendLargeGraphMail(attachments: GraphAttachment[], { clean
|
||||
method: 'POST',
|
||||
})
|
||||
if (created.status === 401 || created.status === 403) {
|
||||
log.error(`[ipal] ${permissionDetail} (${await describe(created)})`)
|
||||
log.error(`[iapl] ${permissionDetail} (${await describe(created)})`)
|
||||
return { code: 'graph-permission', detail: permissionDetail, sent: false }
|
||||
}
|
||||
if (created.status !== 201 && created.status !== 200) {
|
||||
@@ -167,10 +167,10 @@ export async function sendLargeGraphMail(attachments: GraphAttachment[], { clean
|
||||
if (sent.status !== 202) {throw new Error(`send failed (${await describe(sent)})`)}
|
||||
} catch (err) {
|
||||
const detail = err instanceof Error ? err.message : String(err)
|
||||
log.error(`[ipal] Graph send with a large attachment failed: ${detail}`)
|
||||
log.error(`[iapl] Graph send with a large attachment failed: ${detail}`)
|
||||
// Nothing went out: take the draft (and the file in it) out of the mailbox.
|
||||
if (draftId && !(await remove(draftId))) {
|
||||
log.error(`[ipal] Graph: could not delete the draft ${draftId} from ${sender} — delete it by hand (it holds a form file).`)
|
||||
log.error(`[iapl] Graph: could not delete the draft ${draftId} from ${sender} — delete it by hand (it holds a form file).`)
|
||||
}
|
||||
return { code: 'graph-error', detail, sent: false }
|
||||
}
|
||||
@@ -190,7 +190,7 @@ export async function sendLargeGraphMail(attachments: GraphAttachment[], { clean
|
||||
/* try again after the next delay */
|
||||
}
|
||||
}
|
||||
log.warn(`[ipal] Graph: the sent copy ${sentId} is still in the mailbox ${sender} — delete it by hand (it holds a form file).`)
|
||||
log.warn(`[iapl] Graph: the sent copy ${sentId} is still in the mailbox ${sender} — delete it by hand (it holds a form file).`)
|
||||
return 'left'
|
||||
})()
|
||||
cleanup.catch(() => undefined)
|
||||
|
||||
@@ -109,7 +109,7 @@ export const mailAdapter =
|
||||
// Panel asked for Graph but the agency creds aren't configured for
|
||||
// this project. Fall back to SMTP rather than silently dropping mail.
|
||||
payload.logger.warn(
|
||||
'[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
|
||||
'[iapl] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ export const panelSmtpAdapter =
|
||||
|
||||
if (!host || !user || !pass) {
|
||||
payload.logger.error(
|
||||
'[ipal] Email not sent: SMTP host, user or password is empty in Site integrations → E-mail sending.',
|
||||
'[iapl] Email not sent: SMTP host, user or password is empty in Site integrations → E-mail sending.',
|
||||
)
|
||||
return { code: 'not-configured', error: 'Fill in the server, user name and password.', sent: false }
|
||||
}
|
||||
@@ -100,7 +100,7 @@ export const panelSmtpAdapter =
|
||||
} catch (err) {
|
||||
// Never surface SMTP internals to the caller — a form submission
|
||||
// shouldn't fail loudly because the mailbox is misconfigured.
|
||||
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
|
||||
payload.logger.error(`[iapl] Email send failed: ${(err as Error).message}`)
|
||||
// `detail` is for the panel status (mailAdapter), not for end users.
|
||||
return { detail: (err as Error).message, error: 'The e-mail was not sent.', sent: false }
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ export async function sendEmail({
|
||||
})
|
||||
return { messageId: info.messageId, sent: true }
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
|
||||
payload.logger.error(`[iapl] Email send failed: ${(err as Error).message}`)
|
||||
return { error: 'The e-mail was not sent.', sent: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ export const testEmailEndpoint: Endpoint = {
|
||||
try {
|
||||
const info = await req.payload.sendEmail({
|
||||
...(attachmentMB
|
||||
? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'ipal-kit test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] }
|
||||
? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'IAPL test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] }
|
||||
: {}),
|
||||
html: `<p>${escapeHtml(text)}</p>`,
|
||||
subject,
|
||||
@@ -84,7 +84,7 @@ export const testEmailEndpoint: Endpoint = {
|
||||
|
||||
if (!sent) {
|
||||
const failed = info as { code?: string; detail?: string; error?: string }
|
||||
req.payload.logger.error(`[ipal] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`)
|
||||
req.payload.logger.error(`[iapl] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`)
|
||||
const error =
|
||||
failed?.code === 'not-configured'
|
||||
? serverText(i18n, 'testEmailNotConfigured')
|
||||
@@ -95,7 +95,7 @@ export const testEmailEndpoint: Endpoint = {
|
||||
return Response.json({ message: serverText(i18n, 'testEmailSent', { to }), ok: true })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
req.payload.logger.error(`[ipal] Test email failed: ${message}`)
|
||||
req.payload.logger.error(`[iapl] Test email failed: ${message}`)
|
||||
return Response.json({ error: serverText(i18n, 'testEmailFailed'), ok: false }, { status: 502 })
|
||||
}
|
||||
},
|
||||
|
||||
Vendored
+4
-4
@@ -27,7 +27,7 @@ export type EnvRule = {
|
||||
export type AssertEnvOptions = {
|
||||
/** Source of values. Default process.env. */
|
||||
env?: Record<string, string | undefined>
|
||||
/** Error prefix. Default '[ipal]'. */
|
||||
/** Error prefix. Default '[iapl]'. */
|
||||
label?: string
|
||||
}
|
||||
|
||||
@@ -86,8 +86,8 @@ function checkValue(rule: EnvRule, value: string): null | string {
|
||||
* aggregated error listing every problem at once (not just the first). Call it
|
||||
* once at boot — in payload.config.ts, or Next's instrumentation.ts register().
|
||||
*
|
||||
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
|
||||
* assertEnv(ipalEnvRules({ storage: true, turnstile: true }))
|
||||
* import { assertEnv, iaplEnvRules } from '@intecion/ipal-kit'
|
||||
* assertEnv(iaplEnvRules({ storage: true, turnstile: true }))
|
||||
*
|
||||
* or with hand-written rules:
|
||||
*
|
||||
@@ -102,7 +102,7 @@ function checkValue(rule: EnvRule, value: string): null | string {
|
||||
*/
|
||||
export function assertEnv(rules: EnvRule[], options: AssertEnvOptions = {}): void {
|
||||
const env = options.env ?? process.env
|
||||
const label = options.label ?? '[ipal]'
|
||||
const label = options.label ?? '[iapl]'
|
||||
const problems: string[] = []
|
||||
|
||||
for (const rule of rules) {
|
||||
|
||||
@@ -4,7 +4,7 @@ type TurnstileNames = { secretVar?: string; siteKeyVar?: string }
|
||||
|
||||
import { checkDatabaseName } from './databaseName.js'
|
||||
|
||||
export type IpalEnvFeatures = {
|
||||
export type IaplEnvFeatures = {
|
||||
/**
|
||||
* Cookie crawl (cookieScanner.crawl): the scanner service URL and the shared
|
||||
* token (at least 16 characters). Required in production only.
|
||||
@@ -22,7 +22,7 @@ export type IpalEnvFeatures = {
|
||||
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
|
||||
emailGraph?: boolean
|
||||
/**
|
||||
* Require IPAL_IP_HEADER in production — the header the rate limit trusts for
|
||||
* Require IAPL_IP_HEADER in production — the header the rate limit trusts for
|
||||
* the client IP (see clientIp). Outside production it stays optional.
|
||||
*/
|
||||
ipHeader?: boolean
|
||||
@@ -55,7 +55,7 @@ export type IpalEnvFeatures = {
|
||||
}
|
||||
|
||||
/**
|
||||
* The env schema for a standard ipal-kit deploy, assembled from the features the
|
||||
* The env schema for a standard IAPL deploy, assembled from the features the
|
||||
* project actually uses — so a site on local-disk storage isn't forced to set
|
||||
* R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a
|
||||
* fixed required set (A0: the plugin never demands config a project doesn't use).
|
||||
@@ -64,16 +64,16 @@ export type IpalEnvFeatures = {
|
||||
* NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core.
|
||||
* Override any name via the options if your project names them differently.
|
||||
*
|
||||
* assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))
|
||||
* assertEnv(iaplEnvRules({ storage: true, emailGraph: true, turnstile: true }))
|
||||
*
|
||||
* Extend with project-specific vars by spreading:
|
||||
*
|
||||
* assertEnv([
|
||||
* ...ipalEnvRules({ storage: true }),
|
||||
* ...iaplEnvRules({ storage: true }),
|
||||
* { name: 'MY_API_KEY', description: 'Third-party integration key' },
|
||||
* ])
|
||||
*/
|
||||
export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
||||
export function iaplEnvRules(features: IaplEnvFeatures = {}): EnvRule[] {
|
||||
const {
|
||||
cookieCrawl = false,
|
||||
databaseName = false,
|
||||
@@ -95,7 +95,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
||||
...(secretMinLength > 0 && process.env.NODE_ENV === 'production' && {
|
||||
validate: (value: string) =>
|
||||
value.length >= secretMinLength ||
|
||||
`${secretVar} must be at least ${secretMinLength} characters in production (got ${value.length}) — use a long random value, or ipalEnvRules({ secretMinLength }) to change the minimum (0 turns the check off)`,
|
||||
`${secretVar} must be at least ${secretMinLength} characters in production (got ${value.length}) — use a long random value, or iaplEnvRules({ secretMinLength }) to change the minimum (0 turns the check off)`,
|
||||
}),
|
||||
},
|
||||
{ name: serverUrlVar, description: 'Public site origin, e.g. https://example.com', kind: 'url' },
|
||||
@@ -148,22 +148,22 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
||||
|
||||
if (ipHeader) {
|
||||
rules.push({
|
||||
name: 'IPAL_IP_HEADER',
|
||||
name: 'IAPL_IP_HEADER',
|
||||
description: 'Header holding the real client IP, e.g. cf-connecting-ip (Cloudflare) or x-forwarded-for',
|
||||
required: process.env.NODE_ENV === 'production',
|
||||
validate: (v) => (/^[a-z0-9-]+$/i.test(v) ? true : `IPAL_IP_HEADER must be a header name (got "${v}")`),
|
||||
validate: (v) => (/^[a-z0-9-]+$/i.test(v) ? true : `IAPL_IP_HEADER must be a header name (got "${v}")`),
|
||||
})
|
||||
}
|
||||
|
||||
if (cookieCrawl) {
|
||||
const required = process.env.NODE_ENV === 'production'
|
||||
rules.push(
|
||||
{ name: 'IPAL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required },
|
||||
{ name: 'IAPL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required },
|
||||
{
|
||||
name: 'IPAL_COOKIE_SCAN_TOKEN',
|
||||
description: 'Token shared with the cookie crawler (this site\'s entry in IPAL_CRAWLER_SITES)',
|
||||
name: 'IAPL_COOKIE_SCAN_TOKEN',
|
||||
description: 'Token shared with the cookie crawler (this site\'s entry in IAPL_CRAWLER_SITES)',
|
||||
required,
|
||||
validate: (v) => (v.length >= 16 ? true : 'IPAL_COOKIE_SCAN_TOKEN must be at least 16 characters'),
|
||||
validate: (v) => (v.length >= 16 ? true : 'IAPL_COOKIE_SCAN_TOKEN must be at least 16 characters'),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -183,7 +183,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
||||
}
|
||||
|
||||
if (databaseName) {
|
||||
const { domain, warn = (message: string) => console.warn(`[ipal] ${message}`) } = databaseName === true ? {} : databaseName
|
||||
const { domain, warn = (message: string) => console.warn(`[iapl] ${message}`) } = databaseName === true ? {} : databaseName
|
||||
rules.push({
|
||||
name: databaseVar,
|
||||
description: 'Database name: <domain without dots>_prod / _dev (warning only)',
|
||||
Vendored
+2
-2
@@ -1,5 +1,5 @@
|
||||
export { assertEnv } from './assertEnv.js'
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule } from './assertEnv.js'
|
||||
export { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from './databaseName.js'
|
||||
export { ipalEnvRules } from './ipalEnvRules.js'
|
||||
export type { IpalEnvFeatures } from './ipalEnvRules.js'
|
||||
export { iaplEnvRules } from './iaplEnvRules.js'
|
||||
export type { IaplEnvFeatures } from './iaplEnvRules.js'
|
||||
|
||||
@@ -20,7 +20,7 @@ export type FormFileScanInput = {
|
||||
export type FormFileScanResult = { ok: boolean; reason?: string }
|
||||
|
||||
/**
|
||||
* `ipalKit({ forms: { attachments } })` — files on panel forms. They are
|
||||
* `iapl({ forms: { attachments } })` — files on panel forms. They are
|
||||
* NEVER stored: a file is checked, attached to the company e-mail, and dropped.
|
||||
*/
|
||||
export type FormAttachmentsOption = {
|
||||
|
||||
@@ -178,12 +178,12 @@ export function buildFileDeliveryHook({ formsSlug = 'forms' }: { formsSlug?: str
|
||||
|
||||
const detail = firstLine(outcomes.find((o) => o.detail)?.detail)
|
||||
delivery.result = { note: detail ? `The mail server did not take the message: ${detail}` : 'The mail server did not take the message.', state: 'failed' }
|
||||
payload.logger.error(`[ipal] Form file not delivered (${fileList(delivery.files)}): ${detail || 'send failed'}`)
|
||||
payload.logger.error(`[iapl] Form file not delivered (${fileList(delivery.files)}): ${detail || 'send failed'}`)
|
||||
await Promise.all(carriers.map((email) => send(payload, withFailureNotice(email, delivery.files, locale))))
|
||||
return []
|
||||
} catch (err) {
|
||||
delivery.result = { note: firstLine(err instanceof Error ? err.message : String(err)), state: 'failed' }
|
||||
payload.logger.error(`[ipal] Form file delivery failed: ${(err as Error).message}`)
|
||||
payload.logger.error(`[iapl] Form file delivery failed: ${(err as Error).message}`)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,7 +310,7 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
|
||||
open.delete(stream)
|
||||
if (settled) {return} // aborted: already answered, nothing to add
|
||||
stream.resume()
|
||||
payload.logger.error(`[ipal] Form file could not be read: ${(err as Error).message}`)
|
||||
payload.logger.error(`[iapl] Form file could not be read: ${(err as Error).message}`)
|
||||
stop({ reason: 'error', success: false })
|
||||
})
|
||||
})
|
||||
@@ -335,7 +335,7 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
|
||||
stop(await storeSubmission({ ...(stored), files: (gate).accepted }))
|
||||
}
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Form submit failed: ${(err as Error).message}`)
|
||||
payload.logger.error(`[iapl] Form submit failed: ${(err as Error).message}`)
|
||||
stop({ reason: 'error', success: false })
|
||||
}
|
||||
conclude(outcome ?? { reason: 'error', success: false })
|
||||
|
||||
@@ -11,7 +11,7 @@ import { HONEYPOT_FIELD, isHoneypotTripped } from './honeypot.js'
|
||||
import { submitForm } from './submitForm.js'
|
||||
|
||||
type CreateSubmitActionArgs = {
|
||||
/** Optional: IP options (default IPAL_IP_HEADER env / clientIp defaults). */
|
||||
/** Optional: IP options (default IAPL_IP_HEADER env / clientIp defaults). */
|
||||
clientIp?: ClientIpOptions
|
||||
getCachedPayload: () => Promise<BasePayload>
|
||||
/**
|
||||
@@ -69,7 +69,7 @@ export async function splitFormFiles(values: Record<string, unknown>): Promise<{
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* export const sendForm = createSubmitAction({ getCachedPayload, headers })
|
||||
*
|
||||
* Signature matches the ipal-form FormRenderer: `sendForm(formId, locale, values,
|
||||
* Signature matches the iapl-form FormRenderer: `sendForm(formId, locale, values,
|
||||
* turnstileToken?)` — bind formId and locale in the block (`sendForm.bind(null, id, locale)`).
|
||||
* A tripped honeypot gets a fake success and stores nothing.
|
||||
*/
|
||||
|
||||
@@ -203,7 +203,7 @@ export function buildEmailLayoutHook({ formsSlug = 'forms' }: { formsSlug?: stri
|
||||
}),
|
||||
}))
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] E-mail layout skipped: ${(err as Error).message}`)
|
||||
payload.logger.error(`[iapl] E-mail layout skipped: ${(err as Error).message}`)
|
||||
return emails
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { Field } from 'payload'
|
||||
* `dataLayer` push fired on successful submit — without any code change. Add
|
||||
* them to the Forms collection via the plugin's `formOverrides`:
|
||||
*
|
||||
* ipalKit({
|
||||
* iapl({
|
||||
* forms: {
|
||||
* formOverrides: {
|
||||
* fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],
|
||||
|
||||
@@ -195,7 +195,7 @@ function hideEmails(fields: Field[]): Field[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
|
||||
* Configures @payloadcms/plugin-form-builder from IAPL's FormsOption.
|
||||
*
|
||||
* Provides the forms / form-submissions collections and field types. E-mails
|
||||
* after a submission are the form-builder's own (Forms → Emails), sent through
|
||||
|
||||
@@ -25,7 +25,7 @@ export type SubmitFormArgs = {
|
||||
/**
|
||||
* Name of the GDPR consent checkbox. A field with this name must be checked
|
||||
* for the submission to succeed (enforced server-side). Defaults to
|
||||
* ipalKit({ forms: { consentFieldName } }), then 'consent'.
|
||||
* iapl({ forms: { consentFieldName } }), then 'consent'.
|
||||
*/
|
||||
consentFieldName?: string
|
||||
/** Submitted field data — shape matches the form's fields. */
|
||||
@@ -212,7 +212,7 @@ export async function validateSubmitFields({
|
||||
locale,
|
||||
payload,
|
||||
}: Pick<SubmitFormArgs, 'consentFieldName' | 'data' | 'formId' | 'locale' | 'payload'>): Promise<{ failure: SubmitFailure } | { validation: ValidSubmission }> {
|
||||
// Explicit argument → ipalKit({ forms: { consentFieldName } }) → 'consent'.
|
||||
// Explicit argument → iapl({ forms: { consentFieldName } }) → 'consent'.
|
||||
const configured = (payload.config?.custom as { ipal?: { consentFieldName?: unknown } } | undefined)?.ipal?.consentFieldName
|
||||
const consentField = consentFieldName ?? (typeof configured === 'string' && configured ? configured : undefined)
|
||||
const validation = await validateSubmission(payload, formId, data, consentField)
|
||||
@@ -342,7 +342,7 @@ export async function storeSubmission({
|
||||
depth: 0,
|
||||
})
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`)
|
||||
payload.logger.error(`[iapl] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`)
|
||||
}
|
||||
if (result.state === 'sent') {return { submissionId: submission.id, success: true }}
|
||||
// The message belongs at the File field and names the file — never the mail server's own words.
|
||||
@@ -356,7 +356,7 @@ export async function storeSubmission({
|
||||
...(fileField && !fileField.required ? { optional: true } : {}),
|
||||
}
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
|
||||
payload.logger.error(`[iapl] Form submission failed: ${(err as Error).message}`)
|
||||
return { reason: 'error', success: false }
|
||||
} finally {
|
||||
// The buffers are not needed past this point — drop the references now.
|
||||
@@ -402,8 +402,8 @@ export async function submitForm(args: SubmitFormArgs): Promise<SubmitFormResult
|
||||
// Never dropped silently: the caller sent files this site (or this form) does not take.
|
||||
payload.logger.warn(
|
||||
attachments
|
||||
? `[ipal] submitForm: files were sent to form ${formId}, which has no File field — refused.`
|
||||
: '[ipal] submitForm: files were sent, but forms.attachments is off — refused. Turn it on in ipalKit({ forms: { attachments: true } }).',
|
||||
? `[iapl] submitForm: files were sent to form ${formId}, which has no File field — refused.`
|
||||
: '[iapl] submitForm: files were sent, but forms.attachments is off — refused. Turn it on in iapl({ forms: { attachments: true } }).',
|
||||
)
|
||||
return { kind: 'unknown_fields', reason: 'validation', success: false }
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ export type FormsOption = {
|
||||
/**
|
||||
* What a form does while Turnstile CANNOT check — the secret is missing or
|
||||
* wrong, Cloudflare is down (the "degraded" state, shown in Site
|
||||
* integrations and by ipal-doctor). Default: a text form is accepted
|
||||
* integrations and by iapl-doctor). Default: a text form is accepted
|
||||
* (`'allow'`: an enquiry matters more than spam), a form that can carry
|
||||
* files — the file endpoint — is refused (`'reject'`: an accepted bot
|
||||
* submission would put an attachment into a mailbox).
|
||||
|
||||
@@ -37,7 +37,7 @@ export type SiteProvidersProps = {
|
||||
* yourself in a client component.
|
||||
*/
|
||||
lightbox?: boolean | Omit<LightboxProviderProps, 'children' | 'renderDialog' | 'renderImage'>
|
||||
/** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */
|
||||
/** Consent log endpoint, e.g. '/api/ipal/consent' (iapl consentLog: true). */
|
||||
logEndpoint?: string
|
||||
/**
|
||||
* CSP nonce for a nonce-based policy (createProxy `csp`): read it in the layout
|
||||
@@ -50,7 +50,7 @@ export type SiteProvidersProps = {
|
||||
/** getSiteShell(locale) from lib/content. */
|
||||
shell: SiteShell
|
||||
/**
|
||||
* Built-in statistics (ipalKit stats: true): mounts <PageStats>. `true` or
|
||||
* Built-in statistics (iapl stats: true): mounts <PageStats>. `true` or
|
||||
* `{ locale, endpoint }`. Default off.
|
||||
*/
|
||||
stats?: boolean | PageStatsProps
|
||||
|
||||
@@ -78,7 +78,7 @@ type CreateContentHelpersArgs = {
|
||||
/**
|
||||
* Options for the ready-made `robots` handler, e.g.
|
||||
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
|
||||
* `{ adminRoute: false }` when the admin path is hidden (ipalKit adminRoute).
|
||||
* `{ adminRoute: false }` when the admin path is hidden (iapl adminRoute).
|
||||
*/
|
||||
robots?: RobotsOptions
|
||||
/**
|
||||
@@ -172,7 +172,7 @@ export type PageJsonLdOptions = {
|
||||
*
|
||||
* ```ts
|
||||
* // src/lib/content.ts
|
||||
* import { createContentHelpers } from 'ipal-kit'
|
||||
* import { createContentHelpers } from 'IAPL'
|
||||
* import config from '@/payload.config'
|
||||
* import { contentConfig } from '@/content.config'
|
||||
*
|
||||
@@ -270,7 +270,7 @@ export function createContentHelpers({
|
||||
page = 1,
|
||||
): Promise<PageMetadata> => {
|
||||
if (!i18n) {
|
||||
throw new Error('[ipal] createContentHelpers: pass `i18n` to use generatePageMetadata.')
|
||||
throw new Error('[iapl] createContentHelpers: pass `i18n` to use generatePageMetadata.')
|
||||
}
|
||||
pageMetadata ??= createPageMetadata({
|
||||
baseUrl: origin || undefined,
|
||||
@@ -456,7 +456,7 @@ export function createContentHelpers({
|
||||
const sitemap = cache(async (): Promise<SitemapEntry[]> => {
|
||||
if (!i18n) {
|
||||
throw new Error(
|
||||
'[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.',
|
||||
'[iapl] createContentHelpers: pass `i18n` to use the sitemap handler.',
|
||||
)
|
||||
}
|
||||
try {
|
||||
@@ -484,7 +484,7 @@ export function createContentHelpers({
|
||||
// return an empty sitemap instead of failing the build. Runtime regeneration
|
||||
// produces the real one. See dynamic='force-dynamic'.
|
||||
console.warn(
|
||||
'[ipal] sitemap: could not reach the database, returning empty entries ' +
|
||||
'[iapl] sitemap: could not reach the database, returning empty entries ' +
|
||||
"(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to " +
|
||||
'generate at runtime and avoid build-time DB access):',
|
||||
error,
|
||||
@@ -647,7 +647,7 @@ export function createContentHelpers({
|
||||
// reachable at runtime. Without this every project would need its own
|
||||
// try/catch here. (Same graceful-degradation as the sitemap handler.)
|
||||
console.warn(
|
||||
'[ipal] generateStaticParams: database not reachable during build ' +
|
||||
'[iapl] generateStaticParams: database not reachable during build ' +
|
||||
'(Docker/CI) — returning empty params; routes render on-demand at runtime:',
|
||||
err,
|
||||
)
|
||||
@@ -665,7 +665,7 @@ export function createContentHelpers({
|
||||
const sitemapRoute = createSitemapRouteHandler(sitemap, { ...sitemapOptions, style: sitemapStyle ?? {} })
|
||||
|
||||
const needI18n = (what: string): I18nConfig => {
|
||||
if (!i18n) {throw new Error(`[ipal] createContentHelpers: pass \`i18n\` to use ${what}.`)}
|
||||
if (!i18n) {throw new Error(`[iapl] createContentHelpers: pass \`i18n\` to use ${what}.`)}
|
||||
return i18n
|
||||
}
|
||||
|
||||
@@ -912,7 +912,7 @@ export type SiteShell = {
|
||||
formTexts: FormNotificationTexts
|
||||
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
|
||||
jsonLd: Record<string, unknown>[]
|
||||
/** Notifications → Lightbox (English fallbacks without ipalKit `lightbox`) — <SiteProviders lightbox> reads it. */
|
||||
/** Notifications → Lightbox (English fallbacks without iapl `lightbox`) — <SiteProviders lightbox> reads it. */
|
||||
lightboxTexts?: LightboxTexts
|
||||
settings: Record<string, unknown>
|
||||
/** Site Settings → Theme, for <ThemeScript> / <SiteProviders theme> and <ThemeSwitcher label>. */
|
||||
|
||||
@@ -86,11 +86,11 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
|
||||
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
const { blockProps, blocks, homeAlias = 'redirect', jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
|
||||
if (onMissing === 'redirectHome' && !redirect) {
|
||||
throw new Error("[ipal] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.")
|
||||
throw new Error("[iapl] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.")
|
||||
}
|
||||
const localeOf = (locale: string | undefined) => {
|
||||
const l = locale ?? helpers.i18n?.defaultLocale
|
||||
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
|
||||
if (!l) {throw new Error('[iapl] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
|
||||
return l
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ export function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Re
|
||||
// Log the real error for ops; keep the PUBLIC body generic — a 503 with
|
||||
// `db: 'down'` is all an orchestrator needs, and raw DB error text (host,
|
||||
// credentials-in-URL, driver internals) must not leak on a public route.
|
||||
console.warn('[ipal] createHealthRoute: database unreachable:', err)
|
||||
console.warn('[iapl] createHealthRoute: database unreachable:', err)
|
||||
const body = {
|
||||
db: 'down',
|
||||
status: 'error',
|
||||
|
||||
@@ -170,7 +170,7 @@ export function buildCrossLocaleFieldSync(
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
payload.logger?.error?.({ err, msg: `[ipal] cross-locale ${arrayField} sync failed` })
|
||||
payload.logger?.error?.({ err, msg: `[iapl] cross-locale ${arrayField} sync failed` })
|
||||
} finally {
|
||||
reqAny[guardFlag] = false
|
||||
req.locale = requestLocale
|
||||
|
||||
@@ -128,7 +128,7 @@ export function buildRevalidateHook({
|
||||
* import { revalidatePath } from 'next/cache'
|
||||
* hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] }
|
||||
*
|
||||
* ipalKit({ revalidatePath }) attaches it to the plugin's own globals.
|
||||
* iapl({ revalidatePath }) attaches it to the plugin's own globals.
|
||||
*/
|
||||
export function buildGlobalRevalidateHook({ revalidatePath }: { revalidatePath: RevalidatePathFn }): GlobalAfterChangeHook {
|
||||
return ({ context, doc }) => {
|
||||
|
||||
@@ -85,7 +85,7 @@ async function keepingLocale(req: PayloadRequest, fn: () => Promise<unknown>) {
|
||||
try {
|
||||
await fn()
|
||||
} catch (err) {
|
||||
req.payload?.logger?.error(`[ipal] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
req.payload?.logger?.error(`[iapl] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
} finally {
|
||||
req.locale = locale
|
||||
req.fallbackLocale = fallbackLocale
|
||||
|
||||
@@ -10,7 +10,7 @@ export function validateI18nConfig(config: I18nConfig): void {
|
||||
const { defaultLocale, locales } = config
|
||||
|
||||
if (!locales?.length) {
|
||||
throw new Error('[ipal] i18n: "locales" must contain at least one locale.')
|
||||
throw new Error('[iapl] i18n: "locales" must contain at least one locale.')
|
||||
}
|
||||
|
||||
const codes = new Set<string>()
|
||||
@@ -18,18 +18,18 @@ export function validateI18nConfig(config: I18nConfig): void {
|
||||
for (const locale of locales) {
|
||||
if (!locale.code || !locale.label) {
|
||||
throw new Error(
|
||||
`[ipal] i18n: Every locale must have "code" and "label". Received: ${JSON.stringify(locale)}`,
|
||||
`[iapl] i18n: Every locale must have "code" and "label". Received: ${JSON.stringify(locale)}`,
|
||||
)
|
||||
}
|
||||
|
||||
if (!LOCALE_CODE_PATTERN.test(locale.code)) {
|
||||
throw new Error(
|
||||
`[ipal] i18n: Invalid locale code "${locale.code}". Expected format: "pl", "en", "pt-BR".`,
|
||||
`[iapl] i18n: Invalid locale code "${locale.code}". Expected format: "pl", "en", "pt-BR".`,
|
||||
)
|
||||
}
|
||||
|
||||
if (codes.has(locale.code)) {
|
||||
throw new Error(`[ipal] i18n: Duplicate locale code "${locale.code}".`)
|
||||
throw new Error(`[iapl] i18n: Duplicate locale code "${locale.code}".`)
|
||||
}
|
||||
|
||||
codes.add(locale.code)
|
||||
@@ -37,7 +37,7 @@ export function validateI18nConfig(config: I18nConfig): void {
|
||||
|
||||
if (!codes.has(defaultLocale)) {
|
||||
throw new Error(
|
||||
`[ipal] i18n: defaultLocale "${defaultLocale}" not found in locales [${[...codes].join(', ')}].`,
|
||||
`[iapl] i18n: defaultLocale "${defaultLocale}" not found in locales [${[...codes].join(', ')}].`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useFormFields, useTranslation } from '@payloadcms/ui'
|
||||
|
||||
import type { IntegrationBannerTexts } from './status.js'
|
||||
|
||||
import { formatDateTime, ipalT } from '../admin-i18n/t.js'
|
||||
import { formatDateTime, iaplT } from '../admin-i18n/t.js'
|
||||
import { type IntegrationLabel, resolveLabel, STATUS_CODE_TEXTS } from './texts.js'
|
||||
|
||||
type Props = {
|
||||
@@ -36,7 +36,7 @@ export function IntegrationStatusBanner({ label, statusField, texts = {} }: Prop
|
||||
return formatDateTime(iso, i18n.language)
|
||||
}
|
||||
// Project-provided keys are not in AdminTextKey; read them through `t` the same way.
|
||||
const text = (key: string, vars?: Record<string, unknown>) => ipalT(t as never, key as never, vars)
|
||||
const text = (key: string, vars?: Record<string, unknown>) => iaplT(t as never, key as never, vars)
|
||||
|
||||
if (state === 'ok') {
|
||||
const sinceText = date(since)
|
||||
|
||||
@@ -116,6 +116,6 @@ export async function recordIntegrationStatus(
|
||||
depth: 0,
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err)
|
||||
console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { LightboxTexts } from './types.js'
|
||||
|
||||
/**
|
||||
* English fallbacks, per field — the same philosophy as NOTIFICATION_FALLBACK.
|
||||
* Editors translate them in Form messages → Image viewer (ipalKit `lightbox: true`).
|
||||
* Editors translate them in Form messages → Image viewer (iapl `lightbox: true`).
|
||||
*/
|
||||
export const LIGHTBOX_FALLBACK: LightboxTexts = {
|
||||
close: 'Close',
|
||||
|
||||
@@ -22,7 +22,7 @@ export type LightboxImage = {
|
||||
|
||||
/**
|
||||
* Labels of the viewer. The plugin's i18n: the Notifications global → Lightbox
|
||||
* (ipalKit `lightbox: true`), read with getNotificationTexts(...).lightbox.
|
||||
* (iapl `lightbox: true`), read with getNotificationTexts(...).lightbox.
|
||||
* Every missing text falls back to LIGHTBOX_FALLBACK (English).
|
||||
*/
|
||||
export type LightboxTexts = {
|
||||
|
||||
@@ -71,7 +71,7 @@ export type CreateMcpRouteArgs = {
|
||||
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
|
||||
*/
|
||||
rateLimit?: { max?: number; windowMs?: number } | false
|
||||
/** Server name advertised in `initialize`. Default 'ipal-site'. */
|
||||
/** Server name advertised in `initialize`. Default 'iapl-site'. */
|
||||
serverName?: string
|
||||
/** Server version advertised in `initialize`. Default '1.0.0'. */
|
||||
serverVersion?: string
|
||||
@@ -104,7 +104,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
|
||||
getCachedPayload,
|
||||
isPathVisible,
|
||||
maxBatch = 10,
|
||||
serverName = 'ipal-site',
|
||||
serverName = 'iapl-site',
|
||||
serverVersion = '1.0.0',
|
||||
settingsSlug = 'site-settings',
|
||||
summaryField,
|
||||
@@ -306,7 +306,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
|
||||
// Log the real error server-side; return a GENERIC message to the
|
||||
// (anonymous) caller so internal details — DB schema, host, stack —
|
||||
// never leak over a public endpoint.
|
||||
console.warn('[ipal] createMcpRoute: tool execution failed:', err)
|
||||
console.warn('[iapl] createMcpRoute: tool execution failed:', err)
|
||||
return rpcResult(id, toolText('Tool execution failed.', true))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ export function buildOptimizeUploadHook(
|
||||
}
|
||||
|
||||
if (!sharp) {
|
||||
req.payload.logger?.error?.('[ipal] Image optimisation needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.')
|
||||
req.payload.logger?.error?.('[iapl] Image optimisation needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.')
|
||||
throw new APIError(
|
||||
pl
|
||||
? 'Optymalizacja obrazów nie jest dostępna na tym serwerze. Zapytaj administratora.'
|
||||
|
||||
@@ -57,7 +57,7 @@ export function buildMediaPlaceholderHook({ field = FIELD, size = 16 }: { field?
|
||||
}
|
||||
} catch (err) {
|
||||
// A placeholder is a nicety — never block the upload.
|
||||
req.payload.logger.warn(`[ipal] media placeholder skipped: ${err instanceof Error ? err.message : String(err)}`)
|
||||
req.payload.logger.warn(`[iapl] media placeholder skipped: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ export type FormNotificationTexts = {
|
||||
|
||||
export type NotificationTexts = {
|
||||
form: FormNotificationTexts
|
||||
/** Image viewer labels — pass to <LightboxProvider texts>. Fallbacks when ipalKit `lightbox` is off. */
|
||||
/** Image viewer labels — pass to <LightboxProvider texts>. Fallbacks when iapl `lightbox` is off. */
|
||||
lightbox: LightboxTexts
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderP
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
// the status is already 404 — without the content the page stays empty, the error goes to the console
|
||||
console.error('[ipal] NotFoundLoader: the 404 content could not be loaded', error)
|
||||
console.error('[iapl] NotFoundLoader: the 404 content could not be loaded', error)
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { CollectionAfterReadHook, Field, FieldHook, GlobalAfterReadHook } f
|
||||
|
||||
import { ValidationError } from 'payload'
|
||||
|
||||
import { ipalT } from '../admin-i18n/t.js'
|
||||
import { iaplT } from '../admin-i18n/t.js'
|
||||
import { SECRET_CLEAR, SECRET_MASK } from './constants.js'
|
||||
|
||||
/**
|
||||
@@ -98,7 +98,7 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp
|
||||
const value = siblingData && name ? (siblingData as Record<string, unknown>)[name] : given
|
||||
if (value === SECRET_CLEAR) {return null}
|
||||
const refuse = (key: 'secretNotText' | 'secretReenter', fallback: string): never => {
|
||||
const message = req?.t ? ipalT(req.t as never, key) : fallback
|
||||
const message = req?.t ? iaplT(req.t as never, key) : fallback
|
||||
throw new ValidationError({ collection: collection?.slug, errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t)
|
||||
}
|
||||
const nothing = value === undefined || value === null || value === '' || value === SECRET_MASK
|
||||
|
||||
@@ -124,7 +124,7 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
|
||||
headers.push({ key: 'Cross-Origin-Opener-Policy', value: coop })
|
||||
}
|
||||
|
||||
// Staging / preview (IPAL_NOINDEX=1): keep every response out of search engines.
|
||||
// Staging / preview (IAPL_NOINDEX=1): keep every response out of search engines.
|
||||
if (isSiteNoindex()) {
|
||||
headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' })
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ const CLIENT_PROPS = ['browseByFolderSlugs', 'clientConfig', 'collectionSlug', '
|
||||
* the wrapped factory) gets only what can cross to the browser — Payload's client props, its own
|
||||
* `clientProps`, `searchParams` and `back`, both checked.
|
||||
*
|
||||
* ipalKit registers it (twoFactor.safeBack, on by default). A project that registers 2FA views
|
||||
* iapl registers it (twoFactor.safeBack, on by default). A project that registers 2FA views
|
||||
* itself can use it too: `wrapTotpViews`, or give it `ipalTotpView` and list that path in
|
||||
* `admin.dependencies`.
|
||||
*/
|
||||
@@ -53,7 +53,7 @@ export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
|
||||
|
||||
if (!getFromImportMap({ importMap: props.importMap, PayloadComponent: ipalTotpView, schemaPath: '', silent: true })) {
|
||||
throw new Error(
|
||||
`[ipal] The admin import map has no "${totpViewImportKey(ipalTotpView)}" (the 2FA screen ipal-kit puts its back-link check in front of). ` +
|
||||
`[iapl] The admin import map has no "${totpViewImportKey(ipalTotpView)}" (the 2FA screen IAPL puts its back-link check in front of). ` +
|
||||
'Run `pnpm payload generate:importmap` and commit the result.',
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useEffect } from 'react'
|
||||
|
||||
import type { TotpUser } from './totpRedirect.js'
|
||||
|
||||
import { formatDateTime, ipalT } from '../../admin-i18n/t.js'
|
||||
import { formatDateTime, iaplT } from '../../admin-i18n/t.js'
|
||||
import { totpAdminPath, totpRedirectTarget } from './totpRedirect.js'
|
||||
|
||||
export type TotpRedirectProviderProps = {
|
||||
@@ -94,10 +94,10 @@ export function TotpRedirectProvider({ children, forceSetup = true, requireSetup
|
||||
const deadline = setupWindowHours > 0 && Number.isFinite(start) ? start + setupWindowHours * 3_600_000 : null
|
||||
const closed = deadline !== null && deadline < Date.now()
|
||||
const notice = closed
|
||||
? ipalT(t as never, 'twoFactorSetupClosed')
|
||||
? iaplT(t as never, 'twoFactorSetupClosed')
|
||||
: deadline !== null
|
||||
? ipalT(t as never, 'twoFactorSetupDeadline', { date: formatDateTime(new Date(deadline).toISOString(), i18n.language) })
|
||||
: ipalT(t as never, 'twoFactorSetupRequired')
|
||||
? iaplT(t as never, 'twoFactorSetupDeadline', { date: formatDateTime(new Date(deadline).toISOString(), i18n.language) })
|
||||
: iaplT(t as never, 'twoFactorSetupRequired')
|
||||
setup = (
|
||||
<div
|
||||
id="ipal-two-factor-notice"
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { toast, useConfig, useTranslation } from '@payloadcms/ui'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { ipalT } from '../../admin-i18n/t.js'
|
||||
import { iaplT } from '../../admin-i18n/t.js'
|
||||
|
||||
type Props = {
|
||||
/** `reopen`: the account has no TOTP (window passed or still open). `reset`: it has one (lost phone). */
|
||||
@@ -14,7 +14,7 @@ type Props = {
|
||||
/** The admin's button on an account: clears its TOTP so it can (or must) set it up again. */
|
||||
export function TwoFactorResetButton({ kind, userId }: Props) {
|
||||
const { t } = useTranslation()
|
||||
const text = (key: Parameters<typeof ipalT>[1]) => ipalT(t as never, key)
|
||||
const text = (key: Parameters<typeof iaplT>[1]) => iaplT(t as never, key)
|
||||
const { config } = useConfig()
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Is the project's committed admin import map older than the config?
|
||||
*
|
||||
* ipalKit registers `SafeTotpView` in front of the 2FA screens. Payload resolves view components
|
||||
* iapl registers `SafeTotpView` in front of the 2FA screens. Payload resolves view components
|
||||
* through the import map file, and a path that is not in it renders NOTHING: the 2FA screen comes
|
||||
* back empty (HTTP 200, no code form), so nobody can sign in — after an upgrade where
|
||||
* `pnpm payload generate:importmap` was forgotten. In development Payload regenerates the file
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* URL sends the user off-site straight after a genuine login step (GHSA-rffw-fq79-g3ch in the
|
||||
* original `payload-totp`, fixed there in 3.0.5; the fork does not have the fix).
|
||||
*
|
||||
* ipal-kit therefore cleans the value on the server before the package's view sees it
|
||||
* IAPL therefore cleans the value on the server before the package's view sees it
|
||||
* (SafeTotpView.tsx): `twoFactor.safeBack` — on by default, a function replaces the rule,
|
||||
* `false` turns it off.
|
||||
*/
|
||||
@@ -75,7 +75,7 @@ export const safeAdminBack: SafeBackRule = (back, { adminRoute, origin }) => {
|
||||
/** The package's views that take `back` — matched by the route the package gives them. */
|
||||
const TOTP_VIEW_PATH = /^\/?(?:setup|verify)-totp$/
|
||||
|
||||
/** Import-map path of the wrapper ipalKit registers. */
|
||||
/** Import-map path of the wrapper iapl registers. */
|
||||
export const SAFE_TOTP_VIEW = '@intecion/ipal-kit/admin#SafeTotpView'
|
||||
|
||||
/** A view component as it stands in a Payload config. */
|
||||
@@ -94,9 +94,9 @@ export const totpViewImportKey = (component: TotpViewComponent): string => {
|
||||
export const totpViewDependencyKey = (component: TotpViewComponent) => `ipal-totp-view:${totpViewImportKey(component)}`
|
||||
|
||||
/**
|
||||
* Puts ipal-kit's wrapper in front of the 2FA views for which `added(key)` is true and whose
|
||||
* Puts IAPL's wrapper in front of the 2FA views for which `added(key)` is true and whose
|
||||
* route is `setup-totp` / `verify-totp`: the wrapper cleans `back` and renders the original
|
||||
* view, which it finds in the import map (`admin.dependencies` keeps it there). ipal-kit still
|
||||
* view, which it finds in the import map (`admin.dependencies` keeps it there). IAPL still
|
||||
* never imports the optional package. The original's `serverProps` stay server props; its
|
||||
* `clientProps` travel as `ipalTotpClientProps`, so the wrapper can hand them to a client view.
|
||||
*/
|
||||
|
||||
@@ -101,7 +101,7 @@ export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boo
|
||||
`or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. `
|
||||
: 'The browser did not name an origin this site knows. '
|
||||
req.payload?.logger?.warn(
|
||||
`[ipal] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` +
|
||||
`[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` +
|
||||
how +
|
||||
'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.',
|
||||
)
|
||||
|
||||
@@ -3,14 +3,14 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa
|
||||
import { carryStaffRule } from '../../access/ruleMark.js'
|
||||
|
||||
/**
|
||||
* ipal-kit's own second-factor check, next to the access wrapper of
|
||||
* IAPL's own second-factor check, next to the access wrapper of
|
||||
* @clocklimited/payload-2fa.
|
||||
*
|
||||
* Why it exists: the package wraps the `access` functions of the collections
|
||||
* and globals that are in the config at the moment it runs. Whatever is added
|
||||
* afterwards — ipal-kit's globals and collections, a plugin listed after
|
||||
* ipalKit — was left unwrapped, so a staff password without the TOTP code
|
||||
* opened it over the API. This check does not depend on that order: ipalKit
|
||||
* afterwards — IAPL's globals and collections, a plugin listed after
|
||||
* iapl — was left unwrapped, so a staff password without the TOTP code
|
||||
* opened it over the API. This check does not depend on that order: iapl
|
||||
* applies it to everything in the config when it finishes, and again in onInit
|
||||
* to whatever other plugins added later; `userMeetsRole` asks it too.
|
||||
*
|
||||
@@ -19,7 +19,7 @@ import { carryStaffRule } from '../../access/ruleMark.js'
|
||||
* 2. 2FA off or `twoFactor.guard: false` → there is no check (the project's choice);
|
||||
* 3. an account of another auth collection → 2FA is about ONE collection; such an
|
||||
* account is not staff unless the project names its collection in
|
||||
* `access.staffCollections` (then it is staff WITHOUT a second factor — ipalKit
|
||||
* `access.staffCollections` (then it is staff WITHOUT a second factor — iapl
|
||||
* logs a warning at start);
|
||||
* 4. `_strategy === 'totp'` → set by the package's strategy after password and code;
|
||||
* 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule);
|
||||
@@ -52,7 +52,7 @@ import { carryStaffRule } from '../../access/ruleMark.js'
|
||||
* and its code. The package alone only redirects such an account in the panel.
|
||||
*/
|
||||
|
||||
/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
|
||||
/** What iapl records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */
|
||||
export type TwoFactorGuardConfig = {
|
||||
collection: string
|
||||
/** The project's exemption for accounts that never set TOTP up (a service account logging in with a password). */
|
||||
@@ -169,8 +169,8 @@ type ConfigCustom = { totp?: { pluginOptions?: { disableAccessWrapper?: boolean
|
||||
* Per-entity opt-out, operation by operation — the project's decision that
|
||||
* this collection or global may be reached with the password alone:
|
||||
* - the 2FA package's own key: `custom.totp.disableAccessWrapper.<operation>: true`
|
||||
* (the package leaves that operation unwrapped; so does ipal-kit);
|
||||
* - ipal-kit's key, for entities the package never sees (added after it ran):
|
||||
* (the package leaves that operation unwrapped; so does IAPL);
|
||||
* - IAPL's key, for entities the package never sees (added after it ran):
|
||||
* `custom.ipal.secondFactor: false` (every operation) or `{ <operation>: false }`.
|
||||
*/
|
||||
function optedOut(entity: GuardedEntity, operation: string): boolean {
|
||||
@@ -183,7 +183,7 @@ function optedOut(entity: GuardedEntity, operation: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Before the 2FA package runs: ipal-kit's opt-out written in the package's own
|
||||
* Before the 2FA package runs: IAPL's opt-out written in the package's own
|
||||
* key as well, so the package leaves those operations unwrapped too.
|
||||
*/
|
||||
export function passOptOutsToPackage(config: Config): Config {
|
||||
@@ -255,7 +255,7 @@ export function guardConfigAccess(config: Config): Config {
|
||||
}
|
||||
|
||||
/**
|
||||
* The same for a running Payload, in place: what plugins listed after ipalKit
|
||||
* The same for a running Payload, in place: what plugins listed after iapl
|
||||
* added, and what Payload itself adds when it sanitizes the config. Returns
|
||||
* the slugs it had to guard.
|
||||
*
|
||||
@@ -309,7 +309,7 @@ export function ensurePayloadGuarded(payload: Pick<BasePayload, 'config'>): null
|
||||
* onInit) `onConfig` is called — before any request or Local API call can use
|
||||
* the new config. Without it the first HTTP request would do the same (the
|
||||
* guard strategy), but a Local API call made before that request would meet
|
||||
* unguarded entities from plugins listed after ipalKit. Never throws.
|
||||
* unguarded entities from plugins listed after iapl. Never throws.
|
||||
*/
|
||||
export function watchPayloadConfig(payload: BasePayload, onConfig: (payload: BasePayload) => void): void {
|
||||
try {
|
||||
@@ -334,13 +334,13 @@ export function watchPayloadConfig(payload: BasePayload, onConfig: (payload: Bas
|
||||
}
|
||||
}
|
||||
|
||||
/** Name of the auth strategy ipalKit adds to the 2FA collection (see buildGuardStrategy). */
|
||||
/** Name of the auth strategy iapl adds to the 2FA collection (see buildGuardStrategy). */
|
||||
export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard'
|
||||
|
||||
/**
|
||||
* An auth strategy that authenticates nobody. Payload runs every strategy at
|
||||
* the start of every request, before any access function, so this is the one
|
||||
* place ipal-kit is called on each request with the config that is live right
|
||||
* place IAPL is called on each request with the config that is live right
|
||||
* now. It makes sure that config is guarded — also after a dev hot reload,
|
||||
* where Payload swaps in a freshly built config and does not run onInit, and
|
||||
* when Payload was started with `disableOnInit`.
|
||||
@@ -443,7 +443,7 @@ export function guardNewEntityEndpoints<T extends { endpoints?: unknown; slug: s
|
||||
* after the injected factory ran. A missing part means a version this guard
|
||||
* was not written for: it would refuse every staff request, or — worse — the
|
||||
* package itself may no longer protect what it used to. Returns what is
|
||||
* missing; ipalKit refuses to start with it.
|
||||
* missing; iapl refuses to start with it.
|
||||
*/
|
||||
export function missingTotpParts(config: Config, collection: string): string[] {
|
||||
const target = (config.collections ?? []).find((c) => c.slug === collection)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user