Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Reject malformed backup protection assessments
pulse-triage[bot]b8b69a2565d3
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 34f42f7418..3603b04bd7 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -111,6 +111,16 @@ primitives, access boundaries and routes are unchanged.### Backup posture failure and retry stay source-local (24 October 2026)+The same unavailable notice and Unknown projection apply when HTTP-success+posture JSON has invalid rows, provider evidence or policy, duplicate subject+IDs, or mixed policies across batches. Validation completes before publishing+any batch. The existing retry remains disabled while pending and restores health+only after an accepted complete read; independently readable restore points and+open details stay usable. The parser, hook and consuming Backups tests pin this+boundary; source-bound desktop/narrow pixels and keyboard/touch interactions+establish the rendered result. No new control, route or shared query behaviour+is introduced.+The Backups posture notice offers a keyboard-operable retry with the existinginventory-notice styling, wrapping action and disabled pending state. Itrefreshes only posture, not independently readable PVE/PBS inventories. Rows,diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 5637614157..a4bc29bb87 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -21,6 +21,24 @@## Purpose+### Protection posture reads validate the whole response++Backups accepts a batched protection assessment only when every returned row,+provider state and policy has the existing transport shape. Duplicate subject+IDs and inconsistent policies across batches are ambiguous reads, not a reason+to choose the last health state or first policy. Invalid HTTP-success responses+follow the existing failed-read withdrawal and source-local retry path: no+retained health, provider explanation or policy is published, while independent+restore evidence remains inspectable. Explicit null Go collections normalise to+empty lists; missing collections do not. Extra fields remain compatible.++The registered `protectionPostureResponse.test.ts`, `useProtectionPostures.test.ts`+and consuming `ProxmoxBackupsTable.test.tsx` cover shape, ambiguity, whole-read+withdrawal and recovery. The client does not recompute server posture, infer a+missing subject's protection, or change policy, API, identity, access or native+backup/recovery operations. Desktop and narrow consuming browser proof checks+the visible unavailable, pending and recovered states.+### Phone protection summaries prioritise completion and outcomeTrueNAS Protection uses the existing container-led phone projection to keepdiff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupsTable.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupsTable.test.tsxindex 4f0f715a1d..44cb195441 100644--- a/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupsTable.test.tsx+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupsTable.test.tsx@@ -23,6 +23,7 @@ import {import { TABLE_CARD_FRAME_CLASS } from '@/components/shared/TableCard';import type { Resource } from '@/types/resource';import type { ProtectionPosturesResponse } from '@/types/recovery';+import { protectionPolicy } from '@/utils/__fixtures__/protectionPosture';import { getRecoveryFullDateLabel } from '@/utils/recoveryDatePresentation';import { eventBus } from '@/stores/events';import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';@@ -745,7 +746,7 @@ describe('ProxmoxBackupsTable', () => {explanation,evaluatedAt: '2026-05-25T02:05:00Z',})),- policy: { freshnessWindowSeconds: 604800, verificationWindowSeconds: 604800 },+ policy: protectionPolicy,});renderInRouter(() => (<ProxmoxBackupsTable emptyIcon={<span />} workloads={[retainedGuest, workloadResource]} />@@ -964,7 +965,7 @@ const sourceCalls = (source: 'pve' | 'pbs') =>describe('independent Proxmox backup inventory reads', () => {beforeEach(() => {window.history.replaceState({}, '', '/proxmox/backups/date');- apiFetchJSONMock.mockResolvedValue({ data: [], policy: {} });+ apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });});it.each(['pve', 'pbs'] as const)(@@ -1412,7 +1413,7 @@ describe('backup-identity: connected Coverage and By date', () => {}),),);- apiFetchJSONMock.mockResolvedValue({ data: [], policy: {} });+ apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });vi.spyOn(Date, 'now').mockReturnValue(BACKUP_IDENTITY_NOW);};afterEach(() => vi.restoreAllMocks());@@ -1522,7 +1523,7 @@ describe('Coverage qualifies missing restore evidence through the consuming APIapiFetchMock.mockImplementation((url: string) =>Promise.resolve(jsonResponse(url.endsWith('/pve') ? emptyPVE : emptyPBS)),);- apiFetchJSONMock.mockResolvedValue({ data: [posture], policy: {} });+ apiFetchJSONMock.mockResolvedValue({ data: [posture], policy: protectionPolicy });});it.each(['partial', 'unavailable'])(@@ -1537,7 +1538,7 @@ describe('Coverage qualifies missing restore evidence through the consuming APIproviderStates: [{ ...posture.providerStates[0], historyCompleteness }],},],- policy: {},+ policy: protectionPolicy,});mount();const detail = await open();@@ -1605,7 +1606,7 @@ describe('Coverage qualifies missing restore evidence through the consuming API],},],- policy: {},+ policy: protectionPolicy,});mount();const detail = await open();@@ -1619,6 +1620,59 @@ describe('Coverage qualifies missing restore evidence through the consuming API});describe('Coverage withdraws failed protection assessments', () => {+ it.each(['duplicate', 'provider', 'policy'])(+ 'treats HTTP200 malformed %s evidence as unavailable and preserves independent restore points',+ async (invalid) => {+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });+ try {+ mockBackupAPIs();+ window.history.replaceState({}, '', '/proxmox/backups/coverage');+ renderInRouter(() => (+ <ProxmoxBackupsTable emptyIcon={<span />} workloads={[workloadResource]} />+ ));+ const row = () =>+ document.querySelector('[data-proxmox-backup-row="coverage"]') as HTMLElement;+ await waitFor(() => expect(row()).toHaveTextContent('Protected'));+ fireEvent.click(within(row()).getByRole('button', { name: /expand details/i }));+ const detail = await screen.findByTestId('proxmox-coverage-detail');+ const accepted = (await apiFetchJSONMock.mock.results[0]+ .value) as ProtectionPosturesResponse;+ const privateValue = { private: 'SYNTHETIC_PRIVATE_VALUE' };+ const malformed =+ invalid === 'duplicate'+ ? {+ ...accepted,+ data: [{ ...accepted.data[0], state: 'unprotected' }, accepted.data[0]],+ }+ : invalid === 'provider'+ ? { ...accepted, data: [{ ...accepted.data[0], providerStates: [privateValue] }] }+ : { ...accepted, policy: { ...accepted.policy, requireVerification: privateValue } };+ apiFetchJSONMock.mockResolvedValue(malformed);+ await vi.advanceTimersByTimeAsync(30_000);+ await screen.findByText(/Protection posture is unavailable/);+ expect(row()).toHaveTextContent('Unknown');+ expect(row()).not.toHaveTextContent('Protected');+ expect(screen.getByRole('button', { name: '1 unknown' })).toBeInTheDocument();+ expect(detail).not.toHaveTextContent('A current verified backup is available.');+ expect(detail).toHaveTextContent('Restore evidence');+ expect(within(detail).getByText('PVE file', { exact: true })).toBeInTheDocument();+ expect(document.querySelector('[data-coverage-strip-footnote]')).toBeNull();+ expect(document.body).not.toHaveTextContent('SYNTHETIC_PRIVATE_VALUE');++ const beforePVE = sourceCalls('pve').length;+ const beforePBS = sourceCalls('pbs').length;+ apiFetchJSONMock.mockResolvedValue(accepted);+ fireEvent.click(screen.getByRole('button', { name: 'Retry protection posture' }));+ await waitFor(() => expect(row()).toHaveTextContent('Protected'));+ expect(screen.queryByText(/Protection posture is unavailable/)).not.toBeInTheDocument();+ expect(sourceCalls('pve')).toHaveLength(beforePVE);+ expect(sourceCalls('pbs')).toHaveLength(beforePBS);+ } finally {+ vi.useRealTimers();+ }+ },+ );+it('replaces retained healthy rows, counts and explanations with Unknown, then retries only posture', async () => {vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });try {@@ -1708,7 +1762,7 @@ describe('completed restore-point summary and activity', () => {}),),);- apiFetchJSONMock.mockResolvedValue({ data: [], policy: {} });+ apiFetchJSONMock.mockResolvedValue({ data: [], policy: protectionPolicy });window.history.replaceState({}, '', '/proxmox/backups/date');return renderInRouter(() => (<ProxmoxBackupsTablediff --git a/frontend-modern/src/hooks/__tests__/useProtectionPostures.test.ts b/frontend-modern/src/hooks/__tests__/useProtectionPostures.test.tsindex 4d53792f7f..3970ccf112 100644--- a/frontend-modern/src/hooks/__tests__/useProtectionPostures.test.ts+++ b/frontend-modern/src/hooks/__tests__/useProtectionPostures.test.ts@@ -8,6 +8,8 @@ import {useProtectionPostures,} from '@/hooks/useProtectionPostures';import type { ProtectionPosturesResponse, ProtectionState } from '@/types/recovery';+import { protectionPolicy, protectionPosture } from '@/utils/__fixtures__/protectionPosture';+import { ProtectionPostureFormatError } from '@/utils/protectionPostureResponse';const apiFetchJSONMock = vi.hoisted(() => vi.fn());vi.mock('@/utils/apiClient', () => ({ apiFetchJSON: apiFetchJSONMock }));@@ -59,7 +61,7 @@ describe('useProtectionPostures transport', () => {data: requested.slice().reverse()- .map((subjectResourceId) => ({ subjectResourceId, state: 'protected' })),+ .map((subjectResourceId) => protectionPosture(subjectResourceId)),policy,meta: { page: 1, limit: 200, total: requested.length, totalPages: 1 },};@@ -173,8 +175,8 @@ describe('useProtectionPostures transport', () => {it('does not restore a failed cached assessment when Coverage remounts', async () => {apiFetchJSONMock.mockResolvedValue({- data: [{ subjectResourceId: 'vm:1', state: 'protected' }],- policy: { freshnessWindowSeconds: 604800 },+ data: [protectionPosture('vm:1')],+ policy: protectionPolicy,});let dispose = () => {};const mount = () =>@@ -199,4 +201,48 @@ describe('useProtectionPostures transport', () => {dispose();}});++ it.each(['row', 'policy', 'duplicate', 'mixed policies'])(+ 'withdraws the whole 201-subject read after a malformed %s in the last batch',+ async (invalid) => {+ const ids = Array.from({ length: 201 }, (_, index) => `vm:${index}`);+ const validResponse = (url: string) => ({+ data: new URL(url, 'https://pulse.invalid').searchParams+ .getAll('resourceId')+ .map(protectionPosture),+ policy: { ...protectionPolicy },+ });+ apiFetchJSONMock.mockImplementation(async (url: string) => validResponse(url));+ let dispose = () => {};+ const hook = createRoot((rootDispose) => {+ dispose = rootDispose;+ return useProtectionPostures(() => ids);+ });+ try {+ await vi.waitFor(() => expect(hook.postures()).toHaveLength(201));+ apiFetchJSONMock.mockImplementation(async (url: string) => {+ const response = validResponse(url);+ if (response.data.length > 1) return response;+ if (invalid === 'row') return { ...response, data: [null] };+ if (invalid === 'policy')+ return { ...response, policy: { requireVerification: 'false' } };+ if (invalid === 'duplicate') return { ...response, data: [protectionPosture('vm:0')] };+ return { ...response, policy: { ...protectionPolicy, requireVerification: false } };+ });+ await hook.refetch();+ expect(hook.response.error).toBeInstanceOf(ProtectionPostureFormatError);+ expect(hook.postures()).toEqual([]);+ expect(hook.postureByResourceID().size).toBe(0);+ expect(hook.policy().freshnessWindowSeconds).toBe(0);++ apiFetchJSONMock.mockImplementation(async (url: string) => validResponse(url));+ await hook.refetch();+ expect(hook.response.error).toBeNull();+ expect(hook.postures()).toHaveLength(201);+ expect(hook.policy()).toEqual(protectionPolicy);+ } finally {+ dispose();+ }+ },+ );});diff --git a/frontend-modern/src/hooks/useProtectionPostures.ts b/frontend-modern/src/hooks/useProtectionPostures.tsindex eab269d6e4..413d2e3cff 100644--- a/frontend-modern/src/hooks/useProtectionPostures.ts+++ b/frontend-modern/src/hooks/useProtectionPostures.ts@@ -6,6 +6,7 @@ import type {ProtectionPosturesResponse,} from '@/types/recovery';import { apiFetchJSON } from '@/utils/apiClient';+import { parseProtectionPostureBatches } from '@/utils/protectionPostureResponse';const PROTECTION_POSTURES_URL = '/api/recovery/postures';export const MAX_PROTECTION_POSTURE_BATCH_SIZE = 200;@@ -48,7 +49,7 @@ export function buildProtectionPostureBatchURL(resourceIDs: readonly string[]):}async function fetchProtectionPostures(resourceIDs: readonly string[]) {- return apiFetchJSON<ProtectionPosturesResponse>(buildProtectionPostureBatchURL(resourceIDs));+ return apiFetchJSON<unknown>(buildProtectionPostureBatchURL(resourceIDs));}/**@@ -63,10 +64,7 @@ async function fetchAllProtectionPostures(batches.push(resourceIDs.slice(offset, offset + MAX_PROTECTION_POSTURE_BATCH_SIZE));}const responses = await Promise.all(batches.map(fetchProtectionPostures));- return {- data: responses.flatMap((response) => response.data ?? []),- policy: responses[0]?.policy ?? EMPTY_POLICY,- };+ return parseProtectionPostureBatches(responses);}export function useProtectionPostures(resourceIDs: Accessor<readonly string[] | null | undefined>) {diff --git a/frontend-modern/src/utils/__fixtures__/protectionPosture.ts b/frontend-modern/src/utils/__fixtures__/protectionPosture.tsnew file mode 100644index 0000000000..e36bbbb8cb--- /dev/null+++ b/frontend-modern/src/utils/__fixtures__/protectionPosture.ts@@ -0,0 +1,32 @@+import type { ProtectionPosture, ProtectionPosturePolicy } from '@/types/recovery';++export const protectionPolicy: ProtectionPosturePolicy = {+ freshnessWindowSeconds: 604800,+ verificationWindowSeconds: 604800,+ requireVerification: true,+};++export function protectionPosture(subjectResourceId = 'vm:1'): ProtectionPosture {+ return {+ subjectResourceId,+ state: 'protected',+ freshness: 'current',+ verification: 'verified',+ coverage: 'complete',+ providerStates: [+ {+ provider: 'proxmox-pbs',+ source: 'pbs-backup-enumeration',+ scope: 'pbs-fixture/main',+ jobState: 'success',+ historyCompleteness: 'complete',+ permissions: 'sufficient',+ evidenceIds: [],+ },+ ],+ repositoryResourceIds: [],+ evidenceIds: [],+ explanation: 'A current verified backup is available.',+ evaluatedAt: '2026-10-26T12:00:00Z',+ };+}diff --git a/frontend-modern/src/utils/__tests__/protectionPostureResponse.test.ts b/frontend-modern/src/utils/__tests__/protectionPostureResponse.test.tsnew file mode 100644index 0000000000..d106e1e975--- /dev/null+++ b/frontend-modern/src/utils/__tests__/protectionPostureResponse.test.ts@@ -0,0 +1,171 @@+import { describe, expect, it } from 'vitest';+import { protectionPolicy, protectionPosture } from '../__fixtures__/protectionPosture';+import {+ parseProtectionPostureBatches,+ ProtectionPostureFormatError,+} from '../protectionPostureResponse';++const response = (row: unknown = protectionPosture()) => ({+ data: [row],+ policy: { ...protectionPolicy },+});++describe('protection posture response boundary', () => {+ it('keeps server-owned assessments, row order, scopes and extra fields without re-evaluation', () => {+ const row = protectionPosture();+ row.state = 'attention';+ row.providerStates[0].permissions = 'partial';+ row.providerStates[0].historyCompleteness = 'partial';+ const result = parseProtectionPostureBatches([+ { ...response(row), meta: { total: 1 }, futureField: true },+ response({ ...protectionPosture('vm:2'), futureField: { harmless: true } }),+ ]);+ expect(result.data).toEqual([+ row,+ { ...protectionPosture('vm:2'), futureField: { harmless: true } },+ ]);+ expect(result.policy).toEqual(protectionPolicy);+ expect(Object.keys(result).sort()).toEqual(['data', 'policy']);+ });++ it.each([null, []])('accepts an explicit empty Go collection %j', (data) => {+ expect(parseProtectionPostureBatches([{ data, policy: protectionPolicy }])).toEqual({+ data: [],+ policy: protectionPolicy,+ });+ });++ it('normalises nil evidence lists without inventing provider or recovery evidence', () => {+ const row = { ...protectionPosture(), evidenceIds: null, repositoryResourceIds: null };+ const result = parseProtectionPostureBatches([+ response({ ...row, providerStates: [{ ...row.providerStates[0], evidenceIds: null }] }),+ ]);+ expect(result.data[0]).toEqual(protectionPosture());+ expect(+ parseProtectionPostureBatches([response({ ...row, providerStates: null })]).data[0]+ .providerStates,+ ).toEqual([]);+ });++ it('permits optional absent/null dates and verification expectation, including unknown provider evidence', () => {+ const row = protectionPosture();+ row.lastAttemptAt = null;+ row.lastVerifiedAt = '2026-10-26T11:00:00Z';+ row.providerStates[0].verificationExpected = false;+ row.providerStates[0].lastSuccessAt = null;+ row.providerStates[0].provider = 'future-provider';+ row.providerStates[0].jobState = 'unknown';+ expect(parseProtectionPostureBatches([response(row)]).data).toEqual([row]);+ });++ it.each([+ ['no batches', []],+ ['null envelope', [null]],+ ['array envelope', [[]]],+ ['no collection', [{ policy: protectionPolicy }]],+ ['object collection', [{ data: {}, policy: protectionPolicy }]],+ ['no policy', [{ data: [] }]],+ ['null row', [response(null)]],+ ['array row', [response([])]],+ ])('rejects %s', (_name, payloads) => {+ expect(() => parseProtectionPostureBatches(payloads)).toThrow(ProtectionPostureFormatError);+ });++ it.each([+ ['subjectResourceId', ''],+ ['subjectResourceId', 112],+ ['state', 'healthy'],+ ['state', null],+ ['freshness', true],+ ['verification', 'success'],+ ['coverage', {}],+ ['explanation', { private: 'SYNTHETIC_PRIVATE_VALUE' }],+ ['explanation', ' '],+ ['evaluatedAt', 'not-a-date'],+ ['evaluatedAt', undefined],+ ['lastAttemptAt', 123],+ ['lastSuccessfulPointAt', {}],+ ['lastVerifiedAt', 'not-a-date'],+ ['evidenceIds', undefined],+ ['evidenceIds', [1]],+ ['repositoryResourceIds', {}],+ ['providerStates', undefined],+ ['providerStates', {}],+ ])('rejects malformed row field %s=%j without dropping only that row', (key, value) => {+ expect(() =>+ parseProtectionPostureBatches([+ {+ ...response(),+ data: [protectionPosture('vm:valid'), { ...protectionPosture(), [key]: value }],+ },+ ]),+ ).toThrow(ProtectionPostureFormatError);+ });++ it.each([+ ['provider', ''],+ ['source', undefined],+ ['scope', { private: 'SYNTHETIC_PRIVATE_VALUE' }],+ ['jobState', true],+ ['historyCompleteness', 'available'],+ ['permissions', 'granted'],+ ['evidenceIds', [false]],+ ['lastAttemptAt', {}],+ ['lastSuccessAt', 'not-a-date'],+ ['lastVerifiedAt', 123],+ ['verificationExpected', 'false'],+ ])('rejects malformed provider field %s=%j', (key, value) => {+ const row = protectionPosture();+ expect(() =>+ parseProtectionPostureBatches([+ response({ ...row, providerStates: [{ ...row.providerStates[0], [key]: value }] }),+ ]),+ ).toThrow(ProtectionPostureFormatError);+ });++ it.each([+ ['freshnessWindowSeconds', 0],+ ['freshnessWindowSeconds', 0.5],+ ['freshnessWindowSeconds', Infinity],+ ['verificationWindowSeconds', -1],+ ['verificationWindowSeconds', '604800'],+ ['requireVerification', 'false'],+ ['requireVerification', undefined],+ ])('rejects malformed policy field %s=%j', (key, value) => {+ expect(() =>+ parseProtectionPostureBatches([+ { ...response(), policy: { ...protectionPolicy, [key]: value } },+ ]),+ ).toThrow(ProtectionPostureFormatError);+ });++ it('rejects duplicate subjects within or across batches instead of choosing the last health state', () => {+ const protectedRow = protectionPosture();+ const unprotectedRow = { ...protectedRow, state: 'unprotected' };+ expect(() =>+ parseProtectionPostureBatches([{ ...response(), data: [unprotectedRow, protectedRow] }]),+ ).toThrow(ProtectionPostureFormatError);+ expect(() =>+ parseProtectionPostureBatches([response(unprotectedRow), response(protectedRow)]),+ ).toThrow(ProtectionPostureFormatError);+ });++ it.each(['freshnessWindowSeconds', 'verificationWindowSeconds', 'requireVerification'] as const)(+ 'rejects mixed %s policies across otherwise valid batches',+ (key) => {+ const changed = { ...protectionPolicy, [key]: key === 'requireVerification' ? false : 3600 };+ expect(() =>+ parseProtectionPostureBatches([+ response(),+ { ...response(protectionPosture('vm:2')), policy: changed },+ ]),+ ).toThrow(ProtectionPostureFormatError);+ },+ );++ it('uses one fixed error without including private row contents or native parser details', () => {+ expect(() =>+ parseProtectionPostureBatches([response({ private: 'SYNTHETIC_PRIVATE_VALUE' })]),+ ).toThrow('The protection posture response format is invalid.');+ });+});diff --git a/frontend-modern/src/utils/protectionPostureResponse.ts b/frontend-modern/src/utils/protectionPostureResponse.tsnew file mode 100644index 0000000000..7f18ddf314--- /dev/null+++ b/frontend-modern/src/utils/protectionPostureResponse.ts@@ -0,0 +1,124 @@+import type {+ ProtectionPosture,+ ProtectionPosturePolicy,+ ProtectionPosturesResponse,+ ProtectionProviderState,+} from '@/types/recovery';++export class ProtectionPostureFormatError extends Error {+ constructor() {+ // The response may contain private source identifiers or proxy content.+ super('The protection posture response format is invalid.');+ this.name = 'ProtectionPostureFormatError';+ }+}++type Check = (value: unknown) => boolean;+const text: Check = (value) => typeof value === 'string' && value.trim().length > 0;+const timestamp: Check = (value) => text(value) && Number.isFinite(Date.parse(value as string));+const optionalTime: Check = (value) => value == null || timestamp(value);+const boolean: Check = (value) => typeof value === 'boolean';+const positiveSeconds: Check = (value) =>+ typeof value === 'number' && Number.isSafeInteger(value) && value > 0;+const choice =+ (...values: string[]): Check =>+ (value) =>+ typeof value === 'string' && values.includes(value);+const idList: Check = (value) => value === null || (Array.isArray(value) && value.every(text));++function record(value: unknown, shape: Readonly<Record<string, Check>>): Record<string, unknown> {+ if (+ value === null ||+ typeof value !== 'object' ||+ Array.isArray(value) ||+ !Object.entries(shape).every(([key, check]) => check((value as Record<string, unknown>)[key]))+ ) {+ throw new ProtectionPostureFormatError();+ }+ return value as Record<string, unknown>;+}++function list(value: unknown): unknown[] {+ // Empty Go slices may be encoded as null, but a missing collection is not+ // an observed empty result. Never drop an invalid row and accept the rest.+ if (value === null) return [];+ if (!Array.isArray(value)) throw new ProtectionPostureFormatError();+ return value;+}++const providerShape = {+ provider: text,+ source: text,+ scope: text,+ jobState: choice('success', 'warning', 'failed', 'running', 'unknown'),+ historyCompleteness: choice('complete', 'partial', 'unavailable', 'unknown'),+ permissions: choice('sufficient', 'partial', 'denied', 'unknown'),+ lastAttemptAt: optionalTime,+ lastSuccessAt: optionalTime,+ lastVerifiedAt: optionalTime,+ evidenceIds: idList,+ verificationExpected: (value: unknown) => value === undefined || boolean(value),+};+const postureShape = {+ subjectResourceId: text,+ state: choice('protected', 'attention', 'unprotected', 'unknown'),+ freshness: choice('current', 'stale', 'unknown'),+ verification: choice('verified', 'unverified', 'stale', 'unknown'),+ coverage: choice('complete', 'partial', 'none', 'unknown'),+ lastAttemptAt: optionalTime,+ lastSuccessfulPointAt: optionalTime,+ lastVerifiedAt: optionalTime,+ repositoryResourceIds: idList,+ evidenceIds: idList,+ explanation: text,+ evaluatedAt: timestamp,+};+const policyShape = {+ freshnessWindowSeconds: positiveSeconds,+ verificationWindowSeconds: positiveSeconds,+ requireVerification: boolean,+};++/** Validate the whole read before publishing any batch's assessments or policy. */+export function parseProtectionPostureBatches(+ payloads: readonly unknown[],+): ProtectionPosturesResponse {+ const data: ProtectionPosture[] = [];+ const subjects = new Set<string>();+ let policy: ProtectionPosturePolicy | undefined;+ for (const payload of payloads) {+ const batch = record(payload, {});+ const batchPolicy = record(batch.policy, policyShape) as unknown as ProtectionPosturePolicy;+ if (+ policy &&+ (policy.freshnessWindowSeconds !== batchPolicy.freshnessWindowSeconds ||+ policy.verificationWindowSeconds !== batchPolicy.verificationWindowSeconds ||+ policy.requireVerification !== batchPolicy.requireVerification)+ ) {+ throw new ProtectionPostureFormatError();+ }+ policy = batchPolicy;+ for (const value of list(batch.data)) {+ const row = record(value, postureShape);+ const subject = row.subjectResourceId as string;+ // A Map would otherwise silently choose the last conflicting assessment.+ if (subjects.has(subject)) throw new ProtectionPostureFormatError();+ subjects.add(subject);+ const providerStates = list(row.providerStates).map((provider) => {+ const checked = record(provider, providerShape);+ return {+ ...checked,+ evidenceIds: checked.evidenceIds ?? [],+ } as unknown as ProtectionProviderState;+ });+ data.push({+ ...row,+ providerStates,+ repositoryResourceIds: row.repositoryResourceIds ?? [],+ evidenceIds: row.evidenceIds ?? [],+ } as unknown as ProtectionPosture);+ }+ }+ if (!policy) throw new ProtectionPostureFormatError();+ return { data, policy };+}