From 3f9e418556b190bb8d55ac11a22f554e2c51a4a5 Mon Sep 17 00:00:00 2001 From: Anilkumar Reddy Date: Sat, 14 Nov 2026 19:59:37 -0600 Subject: [PATCH] feat(notification-contract): add cleanup warning input context --- README.md | 2 +- compatibility/tests/release-safety.test.mjs | 2 +- compatibility/tests/types.ts | 56 ++++++ packages/notification-contract/CHANGELOG.md | 16 ++ packages/notification-contract/README.md | 37 +++- packages/notification-contract/package.json | 2 +- .../schema/notification-event-v1.schema.json | 46 ++++- .../notification-contract/src/factories.ts | 10 ++ packages/notification-contract/src/schema.ts | 44 ++++- packages/notification-contract/src/types.ts | 28 ++- .../tests/cleanup.test.ts | 159 +++++++++++++++++- scripts/pack-and-test.mjs | 4 +- 12 files changed, 392 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 3d18406..22fcc95 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Shared contracts and runtime libraries for CommerceKit GitHub Actions. This public repository is a pnpm monorepo, not a GitHub Marketplace Action. There is no root `action.yml`. -The source manifests prepare `notification-contract@0.0.4` and `ccv2-client@0.0.3` under the `preview` dist-tag. Source versions are not registry publication evidence. APIs remain pre-1.0; verify registry publication before installation. Placeholder reserved versions, if published later, are not supported dependencies. +The source manifests prepare `notification-contract@0.0.5` (unpublished candidate) and `ccv2-client@0.0.3` under the `preview` dist-tag. Source versions are not registry publication evidence. APIs remain pre-1.0; verify registry publication before installation. Placeholder reserved versions, if published later, are not supported dependencies. | Package | Responsibility | Consumers | | ------------------------------------------ | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | diff --git a/compatibility/tests/release-safety.test.mjs b/compatibility/tests/release-safety.test.mjs index b25c2e7..5b3b250 100644 --- a/compatibility/tests/release-safety.test.mjs +++ b/compatibility/tests/release-safety.test.mjs @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; it('publication requires exact package/channel/confirmation and pre-1.0 version', () => { for (const [name, version] of [ - ['notification-contract', '0.0.4'], + ['notification-contract', '0.0.5'], ['ccv2-client', '0.0.3'], ]) expect(releasePlan(name, 'preview', 'PUBLISH-COMMERCEKIT-PREVIEW')).toMatchObject({ diff --git a/compatibility/tests/types.ts b/compatibility/tests/types.ts index 1ab6fee..37624de 100644 --- a/compatibility/tests/types.ts +++ b/compatibility/tests/types.ts @@ -1,5 +1,9 @@ import { createBuildEvent, + createBuildCleanupEvent, + type BuildCleanupEvent, + type BuildCleanupStatus, + type BuildCleanupInputSnapshot, stripAngleBracketText, redactJwtLikeTokens, createDeploymentEvent, @@ -37,3 +41,55 @@ encodeCcv2PathSegment(123); stripAngleBracketText(null); // @ts-expect-error JWT-like redaction accepts strings only redactJwtLikeTokens({}); + +const cleanupInputs: BuildCleanupInputSnapshot = { + 'token-endpoint': '[REDACTED]', + 'client-id': '[REDACTED]', + 'client-secret': '[REDACTED]', + resource: '[REDACTED]', + 'subscription-code': 'synthetic', + 'api-base-url': 'https://synthetic.example', + 'application-code': '', + 'retention-days': '30', + 'keep-latest': '10', + 'dry-run': 'true', + 'max-deletions': '20', + 'exclude-build-codes': '', + 'timeout-minutes': '15', + 'continue-on-delete-error': 'false', +}; +const cleanupStatus: BuildCleanupStatus = 'warning'; +const cleanup: BuildCleanupEvent = createBuildCleanupEvent({ + status: cleanupStatus, + data: { + mode: 'dry-run', + subscriptionCode: 'synthetic', + retentionDays: 30, + keepLatest: 10, + cleanupStatus: 'blocked', + scannedCount: 1, + eligibleCount: 0, + plannedCount: 0, + deletionRequestedCount: 0, + skippedCount: 1, + failedCount: 0, + unknownCount: 0, + deferredCount: 0, + durationMs: 1, + inputs: cleanupInputs, + inputsValidated: true, + inputsTruncated: false, + protectedCount: 1, + blockedCount: 0, + issues: [{ code: 'eligibility-unverified', message: 'Safe explanation.' }], + }, +}); +void cleanup; +const invalidCleanupInputs: BuildCleanupInputSnapshot = { + ...cleanupInputs, + // @ts-expect-error credentials must be redacted before event construction + 'client-secret': 'synthetic-confidential-value', +}; +void invalidCleanupInputs; +// @ts-expect-error cleanup warning support does not widen Deploy status +createDeploymentEvent({ status: 'warning', data: {} }); diff --git a/packages/notification-contract/CHANGELOG.md b/packages/notification-contract/CHANGELOG.md index 4b7224d..ce64972 100644 --- a/packages/notification-contract/CHANGELOG.md +++ b/packages/notification-contract/CHANGELOG.md @@ -1,5 +1,21 @@ # notification-contract changelog +## 0.0.5 — unpublished candidate + +Allow the existing `warning` status specifically for build cleanup through new +public `BuildCleanupStatus`, preserving Build/Deploy `CompletedStatus` semantics. +Add optional, bounded all-input display context (`BuildCleanupInputSnapshot`), +validation/truncation flags, protected/blocked counts and safe issue explanations. +All fourteen snapshot keys are required when supplied; authentication values must +be literal `[REDACTED]`, public values are at most 256 characters, and at most three +safe issues are accepted. Issue factories project only safe code/message fields. +Old cleanup events remain valid and existing event meanings are unchanged. + +Registry checks found published 0.0.4 and no 0.0.5. This source version is not a +published registry dependency. Consumers require coordinated source/tarball tests +and separately authorized publication before normal exact-version adoption. +No OAuth/transport, provider delivery, package publication or release change. + ## 0.0.4 Add the provider-neutral `ccv2.build-cleanup.completed` event, `BuildCleanupEvent`/`BuildCleanupEventData` public types, shared schema validation and `createBuildCleanupEvent` factory. Cleanup data reports dry-run/apply mode, exact scope, combined retention settings, bounded outcome counts and duration using the existing completed-status vocabulary. Accepted deletion requests are distinct from physical removal. Existing events, schema version 1, sanitizers and factory semantics are preserved. diff --git a/packages/notification-contract/README.md b/packages/notification-contract/README.md index bff76c1..0f47ed2 100644 --- a/packages/notification-contract/README.md +++ b/packages/notification-contract/README.md @@ -2,7 +2,7 @@ Provider-neutral NotificationEvent v1 types, schema and validation for Notify, Build, Deploy, future Check and reusable workflows. No CCv2 calls, CLI diagnostics, Action I/O, polling, provider rendering or webhook delivery. -Public exports: `NotificationEvent`, `NotificationStatus`, `NotificationEventType`, `NotificationSource`, `NotificationContext`, `NotificationLink`, `SafeNotificationError`, `CheckEventData`, `BuildEventData`, `DeploymentEventData`, `BuildCleanupEvent`, `BuildCleanupEventData`; `validateNotificationEvent`, `parseNotificationEventJson`, `validateNotificationLink`, `validateGitHubRunUrl`, `extractSafeGitHubContext`, `mergeProducerContext`, `mergeNotifierContext`, `createCheckEvent`, `createBuildEvent`, `createDeploymentEvent`, `createBuildCleanupEvent`, `redactKnownSecrets`, `sanitizeBoundedText`, `sanitizeLabel`, `sanitizeErrorMessage`. +Public exports: `NotificationEvent`, `NotificationStatus`, `NotificationEventType`, `NotificationSource`, `NotificationContext`, `NotificationLink`, `SafeNotificationError`, `CheckEventData`, `BuildEventData`, `DeploymentEventData`, `BuildCleanupEvent`, `BuildCleanupEventData`, `BuildCleanupStatus`, `BuildCleanupInputSnapshot`; `validateNotificationEvent`, `parseNotificationEventJson`, `validateNotificationLink`, `validateGitHubRunUrl`, `extractSafeGitHubContext`, `mergeProducerContext`, `mergeNotifierContext`, `createCheckEvent`, `createBuildEvent`, `createDeploymentEvent`, `createBuildCleanupEvent`, `redactKnownSecrets`, `sanitizeBoundedText`, `sanitizeLabel`, `sanitizeErrorMessage`. ```ts import { createCheckEvent, parseNotificationEventJson } from '@commercekit-tools/notification-contract'; @@ -22,7 +22,7 @@ Extraction reads only approved runner fields, never event payloads. Explicit pro Install from GitHub Packages after a supported version is published. Configure `@commercekit-tools:registry=https://npm.pkg.github.com`; local users need a classic PAT with `read:packages` in user-level configuration. Consumer Actions need package Actions read access and `GITHUB_TOKEN` with `packages: read`. See the repository authentication guide. Pin exact versions, never ranges. -Source version: `0.0.4`, prepared for pre-1.0 integration under the `preview` dist-tag. This manifest is not publication evidence. Verify registry availability before installation and pin `0.0.4` exactly. Stable API and coordinated consumer/Sandbox validation remain future gates. Reservation versions are unsupported. +Source version: `0.0.5`, an **unpublished candidate**. Registry inspection verified published versions through `0.0.4`; `0.0.5` was absent. Do not pin `0.0.5` as a registry dependency until separately authorized publication is verified. The currently published `0.0.4` package lacks the additions below. Exact-source packed-tarball tests may validate candidate consumers in isolation; no machine-local link belongs in a normal lockfile. Stable API and coordinated consumer/Sandbox validation remain future gates. Reservation versions are unsupported. Independent package SemVer applies; stable breaking changes require a major increment. NotificationEvent schema version is separate from package version. Preserve current consumer contracts during migration. No telemetry or logging is performed. Use synthetic tests and register exact runtime secrets; pattern redaction cannot identify all secrets. @@ -45,3 +45,36 @@ an event. This additive event requires a compatible Notify renderer. Consumers u published 0.0.3 or older reject it. Verify 0.0.4 registry availability and the matching Notify revision before enabling this integration; a source manifest is not publication evidence. + +## Cleanup warning and input context — 0.0.5 candidate + +This additive cleanup-only extension accepts the existing global `warning` status +through public `BuildCleanupStatus`; Build and Deploy continue using unchanged +`CompletedStatus`. Old cleanup events remain valid. A published 0.0.4 validator +rejects cleanup warnings, so producer and Notify revisions must be coordinated. +No publication, tag, release or consumer migration is performed by these changes. + +`BuildCleanupEventData` adds optional `inputs`, `inputsValidated`, +`inputsTruncated`, `protectedCount`, `blockedCount` and `issues` fields. If an +`inputs` snapshot is present, it must contain exactly all 14 names from the Cleanup +Action: token-endpoint, client-id, client-secret, resource, subscription-code, +api-base-url, application-code, retention-days, keep-latest, dry-run, max-deletions, +exclude-build-codes, timeout-minutes and continue-on-delete-error. No new Action +input or retention option is introduced. + +The public `BuildCleanupInputSnapshot` type and schema require all four +technical-user authentication values to be the literal `[REDACTED]`; unredacted +values are rejected with a fixed error that does not echo the payload. Other +snapshot values are display strings bounded to 256 characters, allowing an +invalid supplied setting to be reported without inventing a valid effective +number. Producers set `inputsValidated=false` when execution stopped during +input validation and `inputsTruncated=true` when bounded display omitted text. +They must still redact registered secrets and credential-like text from public +settings with the shared sanitizers before calling the factory. + +Counts remain nonnegative safe integers. `issues` holds at most three reusable +`SafeNotificationError` values, with code at most 100 and message 1–1000 characters. +The factory retains only code/message for each issue, dropping raw nested fields, +then validates the event. Outcome/severity interpretation belongs to the producer: +a warning must not hide a deletion failure or unknown mutation result. Accepted +deletion counts still describe initiation rather than physical removal. diff --git a/packages/notification-contract/package.json b/packages/notification-contract/package.json index bee043f..b805a44 100644 --- a/packages/notification-contract/package.json +++ b/packages/notification-contract/package.json @@ -1,6 +1,6 @@ { "name": "@commercekit-tools/notification-contract", - "version": "0.0.4", + "version": "0.0.5", "description": "Provider-neutral NotificationEvent v1 contracts and factories.", "license": "MIT", "type": "module", diff --git a/packages/notification-contract/schema/notification-event-v1.schema.json b/packages/notification-contract/schema/notification-event-v1.schema.json index 06c0689..cf10c8a 100644 --- a/packages/notification-contract/schema/notification-event-v1.schema.json +++ b/packages/notification-contract/schema/notification-event-v1.schema.json @@ -115,7 +115,7 @@ "if": { "properties": { "eventType": { "const": "ccv2.build-cleanup.completed" } } }, "then": { "properties": { - "status": { "enum": ["success", "failure", "cancelled", "internal-error"] }, + "status": { "enum": ["success", "warning", "failure", "cancelled", "internal-error"] }, "data": { "$ref": "#/$defs/cleanup" } } } @@ -210,9 +210,51 @@ "unknownCount": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "deferredCount": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "durationMs": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, - "error": { "$ref": "#/$defs/error" } + "error": { "$ref": "#/$defs/error" }, + "inputs": { "$ref": "#/$defs/cleanupInputs" }, + "inputsValidated": { "type": "boolean" }, + "inputsTruncated": { "type": "boolean" }, + "protectedCount": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, + "blockedCount": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, + "issues": { "type": "array", "maxItems": 3, "items": { "$ref": "#/$defs/error" } } }, "additionalProperties": true + }, + "cleanupInputs": { + "type": "object", + "required": [ + "token-endpoint", + "client-id", + "client-secret", + "resource", + "subscription-code", + "api-base-url", + "application-code", + "retention-days", + "keep-latest", + "dry-run", + "max-deletions", + "exclude-build-codes", + "timeout-minutes", + "continue-on-delete-error" + ], + "properties": { + "token-endpoint": { "const": "[REDACTED]" }, + "client-id": { "const": "[REDACTED]" }, + "client-secret": { "const": "[REDACTED]" }, + "resource": { "const": "[REDACTED]" }, + "subscription-code": { "type": "string", "maxLength": 256 }, + "api-base-url": { "type": "string", "maxLength": 256 }, + "application-code": { "type": "string", "maxLength": 256 }, + "retention-days": { "type": "string", "maxLength": 256 }, + "keep-latest": { "type": "string", "maxLength": 256 }, + "dry-run": { "type": "string", "maxLength": 256 }, + "max-deletions": { "type": "string", "maxLength": 256 }, + "exclude-build-codes": { "type": "string", "maxLength": 256 }, + "timeout-minutes": { "type": "string", "maxLength": 256 }, + "continue-on-delete-error": { "type": "string", "maxLength": 256 } + }, + "additionalProperties": false } }, "additionalProperties": true diff --git a/packages/notification-contract/src/factories.ts b/packages/notification-contract/src/factories.ts index 1b3732b..790ec1b 100644 --- a/packages/notification-contract/src/factories.ts +++ b/packages/notification-contract/src/factories.ts @@ -35,6 +35,16 @@ function create( const e = selected.error as { code?: string; message?: string }; selected.error = { ...(e.code !== undefined ? { code: e.code } : {}), message: e.message }; } + if (Array.isArray(selected.issues)) { + selected.issues = selected.issues.map((issue: unknown) => { + if (!issue || typeof issue !== 'object') return issue; + const code = 'code' in issue ? issue.code : undefined; + return { + ...(code !== undefined ? { code } : {}), + message: 'message' in issue ? issue.message : undefined, + }; + }); + } const eventType = kind === 'cleanup' ? 'ccv2.build-cleanup.completed' diff --git a/packages/notification-contract/src/schema.ts b/packages/notification-contract/src/schema.ts index 70024f3..1516255 100644 --- a/packages/notification-contract/src/schema.ts +++ b/packages/notification-contract/src/schema.ts @@ -114,7 +114,7 @@ export const schema = { if: { properties: { eventType: { const: 'ccv2.build-cleanup.completed' } } }, then: { properties: { - status: { enum: ['success', 'failure', 'cancelled', 'internal-error'] }, + status: { enum: ['success', 'warning', 'failure', 'cancelled', 'internal-error'] }, data: { $ref: '#/$defs/cleanup' }, }, }, @@ -210,9 +210,51 @@ export const schema = { deferredCount: { type: 'integer', minimum: 0, maximum: 9007199254740991 }, durationMs: { type: 'integer', minimum: 0, maximum: 9007199254740991 }, error: { $ref: '#/$defs/error' }, + inputs: { $ref: '#/$defs/cleanupInputs' }, + inputsValidated: { type: 'boolean' }, + inputsTruncated: { type: 'boolean' }, + protectedCount: { type: 'integer', minimum: 0, maximum: 9007199254740991 }, + blockedCount: { type: 'integer', minimum: 0, maximum: 9007199254740991 }, + issues: { type: 'array', maxItems: 3, items: { $ref: '#/$defs/error' } }, }, additionalProperties: true, }, + cleanupInputs: { + type: 'object', + required: [ + 'token-endpoint', + 'client-id', + 'client-secret', + 'resource', + 'subscription-code', + 'api-base-url', + 'application-code', + 'retention-days', + 'keep-latest', + 'dry-run', + 'max-deletions', + 'exclude-build-codes', + 'timeout-minutes', + 'continue-on-delete-error', + ], + properties: { + 'token-endpoint': { const: '[REDACTED]' }, + 'client-id': { const: '[REDACTED]' }, + 'client-secret': { const: '[REDACTED]' }, + resource: { const: '[REDACTED]' }, + 'subscription-code': { type: 'string', maxLength: 256 }, + 'api-base-url': { type: 'string', maxLength: 256 }, + 'application-code': { type: 'string', maxLength: 256 }, + 'retention-days': { type: 'string', maxLength: 256 }, + 'keep-latest': { type: 'string', maxLength: 256 }, + 'dry-run': { type: 'string', maxLength: 256 }, + 'max-deletions': { type: 'string', maxLength: 256 }, + 'exclude-build-codes': { type: 'string', maxLength: 256 }, + 'timeout-minutes': { type: 'string', maxLength: 256 }, + 'continue-on-delete-error': { type: 'string', maxLength: 256 }, + }, + additionalProperties: false, + }, }, additionalProperties: true, } as const; diff --git a/packages/notification-contract/src/types.ts b/packages/notification-contract/src/types.ts index 4d759f1..70544f0 100644 --- a/packages/notification-contract/src/types.ts +++ b/packages/notification-contract/src/types.ts @@ -1,6 +1,8 @@ export type NotificationStatus = 'started' | 'success' | 'warning' | 'failure' | 'cancelled' | 'internal-error' | 'action-required'; export type CompletedStatus = 'success' | 'failure' | 'cancelled' | 'internal-error'; +/** Cleanup warning support does not change Build or Deploy completed semantics. */ +export type BuildCleanupStatus = CompletedStatus | 'warning'; export type NotificationEventType = | 'ccv2.build-cleanup.completed' | 'check.completed' @@ -97,6 +99,23 @@ export type DeploymentEvent = EventBase & ) & { data: DeploymentEventData }; export type NotificationEvent = CheckEvent | BuildEvent | DeploymentEvent | BuildCleanupEvent; +/** Bounded display context only; authentication values must never enter an event. */ +export interface BuildCleanupInputSnapshot { + 'token-endpoint': '[REDACTED]'; + 'client-id': '[REDACTED]'; + 'client-secret': '[REDACTED]'; + resource: '[REDACTED]'; + 'subscription-code': string; + 'api-base-url': string; + 'application-code': string; + 'retention-days': string; + 'keep-latest': string; + 'dry-run': string; + 'max-deletions': string; + 'exclude-build-codes': string; + 'timeout-minutes': string; + 'continue-on-delete-error': string; +} export interface BuildCleanupEventData { mode: 'dry-run' | 'apply'; subscriptionCode: string; @@ -114,9 +133,16 @@ export interface BuildCleanupEventData { deferredCount: number; durationMs: number; error?: SafeNotificationError; + /** Optional for compatibility with events emitted before 0.0.5. */ + inputs?: BuildCleanupInputSnapshot; + inputsValidated?: boolean; + inputsTruncated?: boolean; + protectedCount?: number; + blockedCount?: number; + issues?: SafeNotificationError[]; } export type BuildCleanupEvent = EventBase & { eventType: 'ccv2.build-cleanup.completed'; - status: CompletedStatus; + status: BuildCleanupStatus; data: BuildCleanupEventData; }; diff --git a/packages/notification-contract/tests/cleanup.test.ts b/packages/notification-contract/tests/cleanup.test.ts index 1e1975c..5142950 100644 --- a/packages/notification-contract/tests/cleanup.test.ts +++ b/packages/notification-contract/tests/cleanup.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { createBuildCleanupEvent, validateNotificationEvent } from '../src/index.js'; +import { + createBuildCleanupEvent, + createBuildEvent, + createDeploymentEvent, + validateNotificationEvent, + type BuildCleanupInputSnapshot, +} from '../src/index.js'; const data = { mode: 'dry-run' as const, subscriptionCode: 'test-subscription', @@ -17,7 +23,7 @@ const data = { durationMs: 1200, }; describe('cleanup event', () => { - for (const status of ['success', 'failure', 'cancelled', 'internal-error'] as const) + for (const status of ['success', 'warning', 'failure', 'cancelled', 'internal-error'] as const) it(`creates and validates ${status}`, () => { const event = createBuildCleanupEvent({ status, @@ -47,7 +53,8 @@ describe('cleanup event', () => { }); it('rejects non-completed status and missing fields', () => { const event = createBuildCleanupEvent({ status: 'success', data }); - expect(() => validateNotificationEvent({ ...event, status: 'warning' })).toThrow(); + expect(() => validateNotificationEvent({ ...event, status: 'started' })).toThrow(); + expect(() => validateNotificationEvent({ ...event, status: 'action-required' })).toThrow(); expect(() => validateNotificationEvent({ ...event, data: {} })).toThrow(); }); it('projects data and safe error fields', () => { @@ -59,3 +66,149 @@ describe('cleanup event', () => { expect(event.data.error).toEqual({ code: 'FAIL', message: 'Safe' }); }); }); + +const inputs: BuildCleanupInputSnapshot = { + 'token-endpoint': '[REDACTED]', + 'client-id': '[REDACTED]', + 'client-secret': '[REDACTED]', + resource: '[REDACTED]', + 'subscription-code': 'synthetic-subscription', + 'api-base-url': 'https://synthetic.example', + 'application-code': '(all applications)', + 'retention-days': '30', + 'keep-latest': '10', + 'dry-run': 'true', + 'max-deletions': '20', + 'exclude-build-codes': '(none)', + 'timeout-minutes': '15', + 'continue-on-delete-error': 'false', +}; +const extended = { + ...data, + inputs, + inputsValidated: true, + inputsTruncated: false, + protectedCount: 12, + blockedCount: 8, + issues: [{ code: 'eligibility-unverified', message: 'Deletion eligibility was not verified.' }], +}; + +describe('cleanup warning and redacted input context', () => { + it('round-trips all supplied input names and bounded warning detail', () => { + const event = createBuildCleanupEvent({ status: 'warning', data: extended }); + expect(event.status).toBe('warning'); + expect(event.data).toEqual(extended); + expect(Object.keys(event.data.inputs ?? {})).toHaveLength(14); + expect(validateNotificationEvent(JSON.parse(JSON.stringify(event)))).toEqual(event); + }); + + it('keeps old cleanup events and unrelated completed-status vocabularies unchanged', () => { + const event = createBuildCleanupEvent({ status: 'success', data }); + expect(event.data).not.toHaveProperty('inputs'); + for (const old of [ + createBuildEvent({ status: 'success', data: {} }), + createDeploymentEvent({ status: 'success', data: {} }), + ]) + expect(() => validateNotificationEvent({ ...old, status: 'warning' })).toThrow( + 'Invalid NotificationEvent', + ); + }); + + for (const name of ['token-endpoint', 'client-id', 'client-secret', 'resource']) + it(`rejects unredacted confidential ${name} without echoing its value`, () => { + const event = createBuildCleanupEvent({ status: 'warning', data: extended }); + expect(() => + validateNotificationEvent({ + ...event, + data: { ...extended, inputs: { ...inputs, [name]: 'synthetic-confidential-value' } }, + }), + ).toThrowError(/^Invalid NotificationEvent v1\.$/); + }); + + for (const name of Object.keys(inputs)) + it(`requires ${name} when a snapshot is supplied`, () => { + const snapshot = Object.fromEntries(Object.entries(inputs).filter(([key]) => key !== name)); + const event = createBuildCleanupEvent({ status: 'warning', data: extended }); + expect(() => validateNotificationEvent({ ...event, data: { ...extended, inputs: snapshot } })).toThrow( + 'Invalid NotificationEvent', + ); + }); + + it('rejects snapshot expansion, non-string fields and an oversized display value', () => { + const event = createBuildCleanupEvent({ status: 'warning', data: extended }); + for (const snapshot of [ + { ...inputs, raw: 'synthetic-confidential-value' }, + { ...inputs, 'keep-latest': 10 }, + { ...inputs, 'exclude-build-codes': 'x'.repeat(257) }, + null, + [], + ]) + expect(() => validateNotificationEvent({ ...event, data: { ...extended, inputs: snapshot } })).toThrow( + 'Invalid NotificationEvent', + ); + expect( + createBuildCleanupEvent({ + status: 'success', + data: { ...extended, inputs: { ...inputs, 'exclude-build-codes': 'x'.repeat(256) } }, + }).data.inputs?.['exclude-build-codes'], + ).toHaveLength(256); + }); + + it('preserves boolean and count boundary values and three safe issues', () => { + const event = createBuildCleanupEvent({ + status: 'failure', + data: { + ...extended, + inputsValidated: false, + inputsTruncated: true, + protectedCount: 0, + blockedCount: Number.MAX_SAFE_INTEGER, + issues: [{ message: 'First' }, { code: 'SECOND', message: 'Second' }, { code: '', message: 'Third' }], + }, + }); + expect(event.data).toMatchObject({ + inputsValidated: false, + inputsTruncated: true, + protectedCount: 0, + blockedCount: Number.MAX_SAFE_INTEGER, + }); + expect(event.data.issues).toHaveLength(3); + expect( + createBuildCleanupEvent({ status: 'success', data: { ...extended, issues: [] } }).data.issues, + ).toEqual([]); + }); + + for (const patch of [ + { inputsValidated: 'true' }, + { inputsTruncated: 1 }, + { protectedCount: -1 }, + { protectedCount: 0.5 }, + { blockedCount: Number.MAX_SAFE_INTEGER + 1 }, + { issues: Array(4).fill({ message: 'Too many' }) }, + { issues: [null] }, + { issues: ['unsafe'] }, + { issues: [{}] }, + { issues: [{ code: 'x'.repeat(101), message: 'Safe' }] }, + { issues: [{ message: 'x'.repeat(1001) }] }, + ]) + it(`rejects invalid optional context ${JSON.stringify(patch).slice(0, 70)}`, () => { + expect(() => + Reflect.apply(createBuildCleanupEvent, undefined, [ + { status: 'warning', data: { ...extended, ...patch } }, + ]), + ).toThrow('Invalid NotificationEvent'); + }); + + it('projects safe issue fields without retaining raw nested payloads', () => { + const source = { + ...extended, + issues: [ + { code: 'SYNTHETIC', message: 'Safe issue', raw: 'synthetic-confidential-value' }, + { message: 'No code', raw: 'synthetic-confidential-value' }, + ], + }; + const event = createBuildCleanupEvent({ status: 'warning', data: source }); + expect(event.data.issues).toEqual([{ code: 'SYNTHETIC', message: 'Safe issue' }, { message: 'No code' }]); + expect(JSON.stringify(event)).not.toContain('synthetic-confidential-value'); + }); +}); diff --git a/scripts/pack-and-test.mjs b/scripts/pack-and-test.mjs index d538d59..8ea76a3 100644 --- a/scripts/pack-and-test.mjs +++ b/scripts/pack-and-test.mjs @@ -57,10 +57,10 @@ try { const types = []; if (!selected || selected === 'notification-contract') { smoke.push( - `import {createCheckEvent,createBuildCleanupEvent,validateNotificationEvent,stripAngleBracketText,redactJwtLikeTokens} from '@commercekit-tools/notification-contract'; import schema from '@commercekit-tools/notification-contract/schema' with {type:'json'}; if(stripAngleBracketText('ac')!=='ac'||redactJwtLikeTokens('eyJheader.payload.signature')!=='[REDACTED]')throw Error('Packed text primitives'); if(schema.properties.schemaVersion.const!==1)throw Error('Schema export'); validateNotificationEvent(createCheckEvent({status:'success',data:{filesChecked:1,errors:0,warnings:0}})); const cleanup=validateNotificationEvent(createBuildCleanupEvent({status:'success',data:{mode:'dry-run',subscriptionCode:'synthetic',retentionDays:30,keepLatest:10,cleanupStatus:'dry-run',scannedCount:0,eligibleCount:0,plannedCount:0,deletionRequestedCount:0,skippedCount:0,failedCount:0,unknownCount:0,deferredCount:0,durationMs:0}})); if(cleanup.eventType!=='ccv2.build-cleanup.completed'||cleanup.data.mode!=='dry-run'||cleanup.data.deletionRequestedCount!==0)throw Error('Packed cleanup event');`, + `import {createCheckEvent,createBuildCleanupEvent,validateNotificationEvent,stripAngleBracketText,redactJwtLikeTokens} from '@commercekit-tools/notification-contract'; import schema from '@commercekit-tools/notification-contract/schema' with {type:'json'}; if(stripAngleBracketText('ac')!=='ac'||redactJwtLikeTokens('eyJheader.payload.signature')!=='[REDACTED]')throw Error('Packed text primitives'); if(schema.properties.schemaVersion.const!==1)throw Error('Schema export'); validateNotificationEvent(createCheckEvent({status:'success',data:{filesChecked:1,errors:0,warnings:0}})); const cleanup=validateNotificationEvent(createBuildCleanupEvent({status:'warning',data:{mode:'dry-run',subscriptionCode:'synthetic',retentionDays:30,keepLatest:10,cleanupStatus:'dry-run',scannedCount:0,eligibleCount:0,plannedCount:0,deletionRequestedCount:0,skippedCount:0,failedCount:0,unknownCount:0,deferredCount:0,durationMs:0,inputs:{"token-endpoint":"[REDACTED]","client-id":"[REDACTED]","client-secret":"[REDACTED]","resource":"[REDACTED]","subscription-code":"synthetic","api-base-url":"https://synthetic.example","application-code":"","retention-days":"30","keep-latest":"10","dry-run":"true","max-deletions":"20","exclude-build-codes":"","timeout-minutes":"15","continue-on-delete-error":"false"},inputsValidated:true,inputsTruncated:false,protectedCount:0,blockedCount:0,issues:[{code:'eligibility-unverified',message:'Safe packed issue.'}]}})); if(cleanup.status!=='warning'||cleanup.data.inputs['client-secret']!=='[REDACTED]'||cleanup.data.issues[0].code!=='eligibility-unverified'||cleanup.eventType!=='ccv2.build-cleanup.completed'||cleanup.data.mode!=='dry-run'||cleanup.data.deletionRequestedCount!==0)throw Error('Packed cleanup event');`, ); types.push( - `import {createCheckEvent,createBuildCleanupEvent,stripAngleBracketText,redactJwtLikeTokens,type NotificationEvent,type BuildCleanupEvent} from '@commercekit-tools/notification-contract'; const event:NotificationEvent=createCheckEvent({status:'success',data:{filesChecked:1,errors:0,warnings:0}}); void event; const text:string=stripAngleBracketText(redactJwtLikeTokens('synthetic'));void text;const cleanup:BuildCleanupEvent=createBuildCleanupEvent({status:'success',data:{mode:'dry-run',subscriptionCode:'synthetic',retentionDays:30,keepLatest:10,cleanupStatus:'dry-run',scannedCount:0,eligibleCount:0,plannedCount:0,deletionRequestedCount:0,skippedCount:0,failedCount:0,unknownCount:0,deferredCount:0,durationMs:0}});void cleanup;`, + `import {createCheckEvent,createBuildCleanupEvent,stripAngleBracketText,redactJwtLikeTokens,type NotificationEvent,type BuildCleanupEvent,type BuildCleanupInputSnapshot,type BuildCleanupStatus} from '@commercekit-tools/notification-contract'; const event:NotificationEvent=createCheckEvent({status:'success',data:{filesChecked:1,errors:0,warnings:0}}); void event; const text:string=stripAngleBracketText(redactJwtLikeTokens('synthetic'));void text;const inputs:BuildCleanupInputSnapshot={"token-endpoint":"[REDACTED]","client-id":"[REDACTED]","client-secret":"[REDACTED]","resource":"[REDACTED]","subscription-code":"synthetic","api-base-url":"https://synthetic.example","application-code":"","retention-days":"30","keep-latest":"10","dry-run":"true","max-deletions":"20","exclude-build-codes":"","timeout-minutes":"15","continue-on-delete-error":"false"};const status:BuildCleanupStatus='warning';const cleanup:BuildCleanupEvent=createBuildCleanupEvent({status,data:{mode:'dry-run',subscriptionCode:'synthetic',retentionDays:30,keepLatest:10,cleanupStatus:'dry-run',scannedCount:0,eligibleCount:0,plannedCount:0,deletionRequestedCount:0,skippedCount:0,failedCount:0,unknownCount:0,deferredCount:0,durationMs:0,inputs,inputsValidated:true,inputsTruncated:false,protectedCount:0,blockedCount:0,issues:[{message:'Safe packed issue.'}]}});void cleanup;`, ); } if (!selected || selected === 'ccv2-client') {