From e2929fa99fc9bca596011a4f630379d07f8996df Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Wed, 18 Nov 2026 20:07:04 -0500 Subject: [PATCH] Validation parity with vcon 1.0.4: content_hash checks, lawful basis body validator, keep created_at --- CHANGELOG.md | 16 ++ CLAUDE.md | 1 + README.md | 12 +- .../content-and-lawful-basis.test.ts | 260 ++++++++++++++++++ src/__tests__/core05-changes.test.ts | 9 +- src/__tests__/migration.test.ts | 4 +- src/index.ts | 11 +- src/lawful-basis.ts | 234 ++++++++++++++++ src/util.ts | 143 ++++++++++ src/validation.ts | 87 +++++- src/vcon.ts | 39 ++- 11 files changed, 793 insertions(+), 23 deletions(-) create mode 100644 src/__tests__/content-and-lawful-basis.test.ts create mode 100644 src/lawful-basis.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fa2f71..e268a85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,19 @@ Objects. Readers accept `0.4.0` and `0.5.0`; writers emit `0.5.0`. - `Vcon.migrate040To050()` static method, `Vcon.migrationReport`, and the `migrateLegacy` and `strictMigration` options on `new Vcon()` and `Vcon.buildFromJson()`. - `Vcon.isValid()` and `Vcon.getValidationWarnings()`, backed by `validateVconDict()`. +- Validation parity with the reference library vcon 1.0.4, with the same messages: + - A malformed `content_hash` (not `-`, an empty list, or a + `sha512`/`sha256` digest of the wrong length) on a Dialog, attachment, analysis, + `redacted_from` or `amended_from` is an error. `contentHashProblems()` is exported. + - Warnings for a Dialog, analysis or inline attachment with a `url` but no `content_hash` + (an error from the next minor release), and for a serialized JSON string body under + `encoding: "json"`. + - `isValid()` runs the lawful basis body validator on every `purpose: "lawful_basis"` + attachment (`src/lawful-basis.ts`, a port of the reference `LawfulBasisValidator`), with + errors and warnings prefixed `Attachment at index N (lawful_basis): `. Unknown proof + types, hash algorithms and canonicalization methods are warnings. Exported as + `validateLawfulBasisAttachment()` and `validateLawfulBasisBody()`. + - An unparseable `created_at` or `updated_at` error quotes the reason, as the reference does. - `Vcon.sign(key, alg = "RS256")`, `Vcon.verify(key)` and `Vcon.generateKeyPair()` (JWS with Node `crypto`, no new dependency); `AlgorithmNotPermittedError`. This restores a signing surface that 0.5.2 removed, because core-05 section 6.2.2 now forbids `alg` "none" and the @@ -88,6 +101,9 @@ Objects. Readers accept `0.4.0` and `0.5.0`; writers emit `0.5.0`. - `Dialog.validate()` rejects unknown Dialog types, content on an `incomplete` Dialog and media types outside the known set (text, message and multipart subtypes are accepted). - The vendored test schema is now the core-05 Appendix C schema (was the `0.4.0` schema). +- `created_at` is kept exactly as written on load; only a missing or empty value is set to + now. `getValidationWarnings()` no longer adds its own no-party/no-session notes for + `lawful_basis` attachments (`isValid()` already requires `party` and `dialog` or `session`). - Date-time parsing rejects out-of-range fields (February 30, hour 24, offset of 24 hours) instead of rolling them over, and keeps microseconds. `migrate040To050` derives Session start and duration, and a consultation-end Event time, with microsecond precision and the reference's diff --git a/CLAUDE.md b/CLAUDE.md index c9b1f92..f87a771 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,6 +18,7 @@ src/ ├── event.ts # Event class, the per-type parameter table, validateEvent ├── attachment.ts # Attachment class for related files ├── validation.ts # validateVconDict: the core-05 structural checks behind Vcon.isValid() +├── lawful-basis.ts # Lawful basis attachment body validator (port of the reference's) ├── migration.ts # migrate040To050 and MigrationReport (Appendix A.1) ├── util.ts # Shared helpers (date parsing, base64url, warnings) ├── index.ts # Public API exports diff --git a/README.md b/README.md index a07fd0d..f3c67b9 100644 --- a/README.md +++ b/README.md @@ -278,7 +278,11 @@ vcon.addAttachment({ party: 0, session: 0, encoding: 'json', - body: { lawful_basis: 'consent', /* ...per the lawful basis extension draft */ } + body: { + lawful_basis: 'consent', + expiration: null, + purpose_grants: [{ purpose: 'recording', granted: true, granted_at: '2026-01-15T10:30:00Z' }] + } }); vcon.addExtension('lawful_basis'); @@ -286,7 +290,11 @@ vcon.hasLawfulBasis(); // true vcon.findLawfulBasisAttachments(0); // lawful_basis attachments for party 0 ``` -`getValidationWarnings()` flags a `lawful_basis` attachment that has no `party` or no `session`. +`isValid()` checks the body of every `lawful_basis` attachment (required fields, purpose grants, the `content_hash` object, proof mechanisms and registry), reporting each finding as `Attachment at index N (lawful_basis): ...`. An expired basis and unknown proof types, hash algorithms or canonicalization methods are warnings in `getValidationWarnings()`. `validateLawfulBasisAttachment()` checks a bare attachment. + +### Content hashes and bodies + +`isValid()` rejects a malformed `content_hash` (it must be `-`, or a non-empty list of them; `sha512` and `sha256` digests must have the right length) on Dialogs, attachments, analysis, `redacted_from` and `amended_from`. `getValidationWarnings()` notes a Dialog, analysis or inline attachment with a `url` but no `content_hash` (this will be an error in a later release), and a body under `encoding: "json"` that is a serialized JSON string rather than the JSON value. `contentHashProblems(value)` gives the reasons for one value. ### Working with Tags diff --git a/src/__tests__/content-and-lawful-basis.test.ts b/src/__tests__/content-and-lawful-basis.test.ts new file mode 100644 index 0000000..39407e2 --- /dev/null +++ b/src/__tests__/content-and-lawful-basis.test.ts @@ -0,0 +1,260 @@ +import { Vcon } from '../vcon'; +import { Party } from '../party'; +import { contentHashProblems } from '../validation'; +import { validateLawfulBasisAttachment } from '../lawful-basis'; +import { parsePyIsoformat, pyRepr } from '../util'; + +/** + * Rules added to the reference library in vcon 1.0.4: content_hash form, + * url without content_hash, serialized JSON bodies, created_at kept as + * written, and the lawful basis body validator run by isValid(). + */ + +const T = '2026-01-15T10:30:00Z'; +const H512 = 'sha512-' + 'A'.repeat(86); +const H256 = 'sha256-' + 'B'.repeat(43); + +function withSession(): Vcon { + const v = Vcon.buildNew(); + v.addParty(new Party({ name: 'Alice' })); + v.addSession({ start: T, parties: [0] }); + return v; +} + +const recording = (extra: Record) => ({ + type: 'recording', start: T, parties: [0], mediatype: 'audio/wav', ...extra +}); + +describe('contentHashProblems', () => { + it('accepts well formed tokens and lists of them', () => { + expect(contentHashProblems(H512)).toEqual([]); + expect(contentHashProblems([H512, H256])).toEqual([]); + expect(contentHashProblems('blake3-abc')).toEqual([]); + }); + + it('reports each problem in the reference library wording', () => { + expect(contentHashProblems([])).toEqual(['must not be an empty array']); + expect(contentHashProblems(5)).toEqual(['5 is not a string']); + expect(contentHashProblems([null, true])).toEqual(['None is not a string', 'True is not a string']); + expect(contentHashProblems('md5:abc')).toEqual(["'md5:abc' is not of the form '-'"]); + expect(contentHashProblems('sha256-x')).toEqual([ + "'sha256-x' has a sha256 digest of 1 base64url characters, expected 43" + ]); + expect(contentHashProblems(H512 + '\n')[0]).toMatch(/is not of the form/); + }); +}); + +describe('content checks in isValid() and getValidationWarnings()', () => { + it('rejects a malformed content_hash on a Dialog', () => { + const v = withSession(); + v.data.dialog = [recording({ url: 'https://x/a.wav', content_hash: 'sha512-abc' })]; + v.data.sessions![0].dialog = [0]; + expect(v.isValid().errors).toEqual([ + "Dialog at index 0 has an invalid content_hash: 'sha512-abc' has a sha512 digest of 3 base64url characters, expected 86." + ]); + v.data.dialog[0].content_hash = H512; + expect(v.isValid().valid).toBe(true); + }); + + it('warns about a Dialog url without content_hash', () => { + const v = withSession(); + v.data.dialog = [recording({ url: 'https://x/a.wav' })]; + v.data.sessions![0].dialog = [0]; + expect(v.isValid().valid).toBe(true); + expect(v.getValidationWarnings()).toContain( + 'Dialog at index 0 has a url but no content_hash (an external reference MUST have both; this will be an error in vcon 1.1).' + ); + }); + + it('does not check an incomplete Dialog', () => { + const v = withSession(); + v.data.dialog = [{ type: 'incomplete', start: T, parties: [0], disposition: 'busy' }]; + v.data.sessions![0].dialog = [0]; + expect(v.getValidationWarnings().some(w => /content_hash|serialized/.test(w))).toBe(false); + }); + + it('checks Attachment content_hash, and url only next to inline content', () => { + const v = withSession(); + v.data.attachments = [ + { purpose: 'doc', start: T, party: 0, session: 0, url: 'https://x', content_hash: ['sha256-short'] }, + { purpose: 'doc', start: T, party: 0, session: 0, url: 'https://x', body: 'a', encoding: 'none', mediatype: 'text/plain' } + ]; + expect(v.isValid().errors).toEqual([ + "Attachment at index 0 has an invalid content_hash: 'sha256-short' has a sha256 digest of 5 base64url characters, expected 43." + ]); + expect(v.getValidationWarnings()).toEqual([ + 'Attachment at index 1 has a url but no content_hash (an external reference MUST have both; this will be an error in vcon 1.1).' + ]); + }); + + it('checks Analysis content and warns about a serialized JSON body', () => { + const v = withSession(); + v.data.analysis = [ + { type: 'summary', vendor: 'v', sessions: 0, encoding: 'json', body: ' {"a": 1} ' }, + { type: 'summary', vendor: 'v', sessions: 0, encoding: 'json', body: '{not json' }, + { type: 'summary', vendor: 'v', sessions: 0, url: 'https://x', content_hash: [] } + ]; + expect(v.isValid().errors).toEqual([ + 'Analysis at index 2 has an invalid content_hash: must not be an empty array.' + ]); + expect(v.getValidationWarnings()).toEqual([ + "Analysis at index 0 has encoding 'json' and a body that is a serialized JSON string; the body should be the JSON value itself (section 2.3.2)." + ]); + }); + + it('checks the content_hash of redacted_from and amended_from (url is checked elsewhere)', () => { + const v = withSession(); + v.data.redacted_from = { type: 'pii', url: 'https://x', content_hash: 'nope' }; + expect(v.isValid().errors).toEqual([ + "redacted_from has an invalid content_hash: 'nope' is not of the form '-'." + ]); + delete v.data.redacted_from; + v.data.amended_from = { uuid: 'u', content_hash: 7 as any }; + expect(v.isValid().errors).toEqual(['amended_from has an invalid content_hash: 7 is not a string.']); + }); +}); + +describe('created_at', () => { + it('is kept exactly as written on load', () => { + const v = new Vcon({ uuid: 'u', created_at: '2026-01-15T10:30:00.5Z' }); + expect(v.created_at).toBe('2026-01-15T10:30:00.5Z'); + expect(new Vcon({ uuid: 'u', created_at: '{{now}}' }).created_at).toBe('{{now}}'); + }); + + it('defaults to now when missing or empty', () => { + expect(new Vcon({ uuid: 'u', created_at: '' }).created_at).not.toBe(''); + }); + + it('reports an unparseable value with the reason the reference library gives', () => { + const errors = (c: unknown) => new Vcon({ uuid: 'u', created_at: c as string }).isValid().errors; + expect(errors('{{now}}')).toEqual([ + 'Invalid created_at format. Must be an ISO 8601 datetime string: Unknown string format: {{now}}' + ]); + expect(errors('2024-13-01T00:00:00Z')).toEqual([ + 'Invalid created_at format. Must be an ISO 8601 datetime string: month must be in 1..12: 2024-13-01T00:00:00Z' + ]); + expect(errors(5)).toEqual([ + 'Invalid created_at format. Must be an ISO 8601 datetime string: Parser must be a string or character stream, not int' + ]); + }); +}); + +describe('lawful basis attachments in isValid()', () => { + const grant = { purpose: 'recording', granted: true, granted_at: T }; + const goodBody = { lawful_basis: 'consent', expiration: '2099-01-01T00:00:00Z', purpose_grants: [grant] }; + + function withBasis(body: unknown, extra: Record = {}): Vcon { + const v = withSession(); + v.data.extensions = ['lawful_basis']; + v.data.attachments = [{ + purpose: 'lawful_basis', start: T, party: 0, session: 0, encoding: 'json', mediatype: 'application/json', body, ...extra + }]; + return v; + } + + it('accepts a complete body', () => { + const v = withBasis(goodBody); + expect(v.isValid()).toEqual({ valid: true, errors: [] }); + expect(v.getValidationWarnings()).toEqual([]); + }); + + it('prefixes errors with the attachment index', () => { + const v = withBasis({}); + expect(v.isValid().errors).toEqual([ + 'Attachment at index 0 (lawful_basis): Missing required field: lawful_basis', + 'Attachment at index 0 (lawful_basis): Missing required field: expiration', + 'Attachment at index 0 (lawful_basis): Missing required field: purpose_grants' + ]); + }); + + it('checks purpose grants', () => { + const v = withBasis({ + ...goodBody, + purpose_grants: [{ purpose: 'x', granted: 'yes', granted_at: 'soon', conditions: [1] }, { purpose: 'y' }] + }); + expect(v.isValid().errors).toEqual([ + 'Attachment at index 0 (lawful_basis): Purpose grant 0: granted field must be a boolean, Invalid granted_at timestamp format, All conditions must be strings', + 'Attachment at index 0 (lawful_basis): Purpose grant 1: Missing required field in purpose grant: granted, Missing required field in purpose grant: granted_at' + ]); + }); + + it('warns about an expired basis and unknown proof types, algorithms and canonicalization', () => { + const v = withBasis({ + ...goodBody, + expiration: '2020-01-01T00:00:00Z', + content_hash: { algorithm: 'sha-512', canonicalization: 'c14n', value: 'abc123' }, + proof_mechanisms: [{ proof_type: 'magic', timestamp: T, proof_data: {} }], + registry: { type: 'other', url: 'https://r' } + }); + expect(v.isValid().valid).toBe(true); + expect(v.getValidationWarnings()).toEqual([ + 'Attachment at index 0 (lawful_basis): Lawful basis has expired', + "Attachment at index 0 (lawful_basis): Content hash: Hash algorithm 'sha-512' is not one this library can verify", + "Attachment at index 0 (lawful_basis): Content hash: Canonicalization method 'c14n' is not one this library can apply", + "Attachment at index 0 (lawful_basis): Proof mechanism 0: Proof type 'magic' is not one of the types the draft defines" + ]); + }); + + it('reports content hash, proof and registry errors', () => { + const v = withBasis({ + ...goodBody, + lawful_basis: 'whim', + content_hash: { algorithm: 'sha-256', value: 'xyz' }, + proof_mechanisms: [{ proof_type: 'signed_document', timestamp: 'bad', proof_data: 'x' }, {}], + registry: { type: 'scitt', url: 'ftp://r' } + }); + expect(v.isValid().errors).toEqual([ + 'Attachment at index 0 (lawful_basis): Unsupported lawful basis: whim', + 'Attachment at index 0 (lawful_basis): Content hash validation failed: Missing required field in content_hash: canonicalization, Hash value must be a hexadecimal string', + 'Attachment at index 0 (lawful_basis): Proof mechanism 0: Invalid timestamp format in proof mechanism, proof_data must be a dictionary', + 'Attachment at index 0 (lawful_basis): Proof mechanism 1: Missing required field in proof mechanism: proof_type, Missing required field in proof mechanism: timestamp, Missing required field in proof mechanism: proof_data', + 'Attachment at index 0 (lawful_basis): Registry validation failed: Registry URL must be a valid HTTP/HTTPS URL' + ]); + }); + + it('decodes a JSON string body and rejects a body that is not an object', () => { + expect(withBasis(JSON.stringify(goodBody)).isValid().valid).toBe(true); + expect(withBasis([1]).isValid().errors).toEqual([ + 'Attachment at index 0 (lawful_basis): Lawful basis attachment body must be a dictionary' + ]); + expect(withBasis(goodBody, { encoding: 'none' }).isValid().errors).toEqual([ + "Attachment at index 0 (lawful_basis): Lawful basis attachment must use 'json' encoding" + ]); + }); + + it('skips a lawful_basis attachment whose body was redacted', () => { + const v = withBasis(goodBody); + delete v.data.attachments![0].body; + v.data.redacted_from = { type: 'pii' }; + expect(v.isValid().valid).toBe(true); + }); + + it('reports scope warnings on the bare attachment but not through the vCon', () => { + const bare = validateLawfulBasisAttachment({ purpose: 'lawful_basis', encoding: 'json', body: goodBody }); + expect(bare.warnings).toEqual([ + 'Lawful basis attachment has no party (core-05 requires it)', + 'Lawful basis attachment has no session; core-05 scopes a basis to Sessions and an attachment needs dialog or session' + ]); + }); +}); + +describe('Python-compatible helpers', () => { + it('parsePyIsoformat follows datetime.fromisoformat', () => { + for (const ok of ['2024-01-01', '20240101', '2024-W01-1', '2024-01-01T10', '2024-01-01T1030', '2024-01-01x10:30', + '2024-01-01T10:30:00,5', '2024-01-01T10:30:00+05', '2024-01-01T10:30:00+05:30:15.5', '2020-W53-1']) { + expect(parsePyIsoformat(ok)).toBeDefined(); + } + for (const bad of ['2024-01-01T10:3', '2024-01-01T24:00:00', '2024-01-01T10:3000', '2024-01-01T10:30:00.', + '2021-W53-1', ' 2024-01-01', '2024-1-01', '2024-01-01T10:30:00+24:00', '0000-01-01', '2024-01-01T10:30:00z']) { + expect(parsePyIsoformat(bad)).toBeUndefined(); + } + expect(parsePyIsoformat('2024-01-01T10:00:00+01:00')).toEqual({ micros: Date.UTC(2024, 0, 1, 9) * 1000, aware: true }); + expect(parsePyIsoformat('2024-01-01')!.aware).toBe(false); + }); + + it('pyRepr matches Python repr', () => { + expect(pyRepr("it's")).toBe('"it\'s"'); + expect(pyRepr({ a: [1, null, false] })).toBe("{'a': [1, None, False]}"); + expect(pyRepr('a\nb')).toBe("'a\\nb'"); + }); +}); diff --git a/src/__tests__/core05-changes.test.ts b/src/__tests__/core05-changes.test.ts index de6a352..f8dc0bc 100644 --- a/src/__tests__/core05-changes.test.ts +++ b/src/__tests__/core05-changes.test.ts @@ -187,7 +187,7 @@ describe('Dialog rules', () => { describe('extensions enforcement', () => { it('requires lawful_basis and wtf_transcription to be listed', () => { const v = withSession(); - v.addAttachment({ purpose: 'lawful_basis', party: 0, session: 0, body: { lawful_basis: 'consent' } as any, encoding: 'json' }); + v.addAttachment({ purpose: 'lawful_basis', party: 0, session: 0, body: { lawful_basis: 'consent', expiration: null, purpose_grants: [{ purpose: 'recording', granted: true, granted_at: T }] } as any, encoding: 'json' }); expect(v.isValid().errors).toContain("Extension 'lawful_basis' is in use but is not listed in the extensions parameter."); v.addExtension('lawful_basis'); expect(v.isValid().valid).toBe(true); @@ -231,13 +231,14 @@ describe('lawful basis', () => { expect(v.getValidationWarnings().some(w => /lawful_basis/.test(w))).toBe(false); }); - it('warns when a lawful_basis attachment has no session or no party', () => { + it('leaves lawful_basis scope to the core rules (no extra no-party/no-session warnings)', () => { const v = withSession(); v.data.extensions = ['lawful_basis']; v.data.attachments = [{ purpose: 'lawful_basis', start: T, dialog: 0, body: {}, encoding: 'json', mediatype: 'application/json' }]; const warnings = v.getValidationWarnings(); - expect(warnings.some(w => /no party/.test(w))).toBe(true); - expect(warnings.some(w => /no session/.test(w))).toBe(true); + expect(warnings.some(w => /no party/.test(w))).toBe(false); + expect(warnings.some(w => /no session/.test(w))).toBe(false); + expect(v.isValid().errors).toContain('Attachment at index 0 is missing required field: party'); }); }); diff --git a/src/__tests__/migration.test.ts b/src/__tests__/migration.test.ts index 5f7d014..51c98cc 100644 --- a/src/__tests__/migration.test.ts +++ b/src/__tests__/migration.test.ts @@ -39,7 +39,7 @@ function v04(extra: D = {}): D { const rec = (extra: D = {}): D => ({ type: 'recording', start: T0, duration: 10, parties: [0, 1], - mediatype: 'audio/x-wav', url: 'https://e.com/a.wav', content_hash: 'sha512-x', ...extra + mediatype: 'audio/x-wav', url: 'https://e.com/a.wav', content_hash: 'sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A', ...extra }); const text = (extra: D = {}): D => ({ type: 'text', start: T1, parties: [0, 1], body: 'hi', encoding: 'none', mediatype: 'text/plain', ...extra @@ -740,7 +740,7 @@ describe('index stability', () => { describe('T11 and T12 renames', () => { it('renames redacted', () => { - const r = { uuid: '01a16b86-96e7-80a8-b9a2-279e0d16bc46', type: 'PII Redaction', url: 'https://e.com/u', content_hash: 'sha512-x' }; + const r = { uuid: '01a16b86-96e7-80a8-b9a2-279e0d16bc46', type: 'PII Redaction', url: 'https://e.com/u', content_hash: 'sha512-vBUU3xDKpjrwFoYiMR63DejHKvgyz4N7xT7Ukx6wHQNuzU4_LY32LMljsTeCGJ_zxqjeS4PcdM0Mlg0mksM06A' }; const { out } = migrate(v04({ redacted: r })); expect(out.redacted_from).toEqual(r); expect('redacted' in out).toBe(false); diff --git a/src/index.ts b/src/index.ts index 0cba0b5..aa1ced2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,7 +11,12 @@ import { CORE_EVENT_TYPES, RuleCode } from './event'; -import { validateVconDict, extensionsInUse } from './validation'; +import { validateVconDict, extensionsInUse, contentHashProblems } from './validation'; +import { + validateLawfulBasisAttachment, + validateLawfulBasisBody, + LawfulBasisValidationResult +} from './lawful-basis'; import { migrate040To050, MigrationError, @@ -72,6 +77,10 @@ export { validateSession, validateEvent, extensionsInUse, + contentHashProblems, + validateLawfulBasisAttachment, + validateLawfulBasisBody, + LawfulBasisValidationResult, EVENT_PARAMETER_RULES, CORE_EVENT_TYPES, SESSION_REFERENCE_TYPES, diff --git a/src/lawful-basis.ts b/src/lawful-basis.ts new file mode 100644 index 0000000..eaedccc --- /dev/null +++ b/src/lawful-basis.ts @@ -0,0 +1,234 @@ +/** + * Validation of lawful basis attachments (draft-howe-vcon-lawful-basis). + * + * A port of the reference library's LawfulBasisValidator + * (vcon.extensions.lawful_basis.validation) with the same messages. Vcon.isValid() + * and Vcon.getValidationWarnings() run it on every `purpose: "lawful_basis"` + * attachment. + */ +import { isPlainObject, parsePyIsoformat, pyRepr, pyStr } from './util'; + +export const LAWFUL_BASIS_TYPES = [ + 'consent', + 'contract', + 'legal_obligation', + 'vital_interests', + 'public_task', + 'legitimate_interests' +]; +export const LAWFUL_BASIS_PROOF_TYPES = [ + 'verbal_confirmation', + 'signed_document', + 'cryptographic_signature', + 'external_system' +]; +export const LAWFUL_BASIS_HASH_ALGORITHMS = ['sha-256', 'sha-3-256', 'blake2b-256']; +export const LAWFUL_BASIS_CANONICALIZATION = ['jcs']; + +export interface LawfulBasisValidationResult { + valid: boolean; + errors: string[]; + warnings: string[]; +} + +function newResult(): LawfulBasisValidationResult { + return { valid: true, errors: [], warnings: [] }; +} + +function addError(result: LawfulBasisValidationResult, error: string): void { + result.errors.push(error); + result.valid = false; +} + +/** + * Read a field of a value that should be an object. A value that is not an + * object is treated as an empty one, so it reports its required fields as + * missing (the reference library raises on most such input). + */ +function fields(value: unknown): Record { + return isPlainObject(value) ? value : {}; +} + +function isoTimestampOk(value: unknown): boolean { + return typeof value === 'string' && parsePyIsoformat(value.replace(/Z/g, '+00:00')) !== undefined; +} + +/** The decoded body: a JSON string under encoding json (or none) is parsed. */ +function decodeBody(attachment: Record): unknown { + const body = attachment.body; + if (body === undefined || body === null) return null; + if (typeof body === 'string' && (attachment.encoding === undefined || attachment.encoding === null || attachment.encoding === 'json')) { + try { + return JSON.parse(body); + } catch { + return body; + } + } + return body; +} + +/** Validate a lawful basis attachment object. */ +export function validateLawfulBasisAttachment(attachment: Record): LawfulBasisValidationResult { + const result = newResult(); + if (attachment.purpose !== 'lawful_basis') { + addError(result, 'Invalid attachment purpose for lawful basis extension'); + return result; + } + if (attachment.encoding !== 'json') { + addError(result, "Lawful basis attachment must use 'json' encoding"); + } + // Core-05 scope (4.6.3 to 4.6.5). Warnings, so a bare attachment can be + // checked before it is placed in a vCon; Vcon.isValid() enforces party and + // dialog/session. + if (!('party' in attachment)) { + result.warnings.push('Lawful basis attachment has no party (core-05 requires it)'); + } + if (!('session' in attachment)) { + result.warnings.push( + 'Lawful basis attachment has no session; core-05 scopes a basis to Sessions' + + ('dialog' in attachment ? '' : ' and an attachment needs dialog or session') + ); + } + const body = decodeBody(attachment); + if (!isPlainObject(body)) { + addError(result, 'Lawful basis attachment body must be a dictionary'); + return result; + } + const bodyResult = validateLawfulBasisBody(body); + result.warnings.push(...bodyResult.warnings); + if (!bodyResult.valid) { + result.errors.push(...bodyResult.errors); + result.valid = false; + } + return result; +} + +/** Validate the body of a lawful basis attachment. */ +export function validateLawfulBasisBody(body: Record): LawfulBasisValidationResult { + const result = newResult(); + for (const field of ['lawful_basis', 'expiration', 'purpose_grants']) { + if (!(field in body)) addError(result, `Missing required field: ${field}`); + } + if ('lawful_basis' in body && !LAWFUL_BASIS_TYPES.includes(body.lawful_basis)) { + addError(result, `Unsupported lawful basis: ${pyStr(body.lawful_basis)}`); + } + if ('expiration' in body && body.expiration !== null) { + const exp = typeof body.expiration === 'string' ? parsePyIsoformat(body.expiration.replace(/Z/g, '+00:00')) : undefined; + if (exp === undefined) { + addError(result, 'Invalid expiration timestamp format'); + } else if (exp.micros <= Date.now() * 1000) { + // A value without an offset is read as UTC (the reference library raises). + result.warnings.push('Lawful basis has expired'); + } + } + if ('purpose_grants' in body) { + const grants = body.purpose_grants; + if (!Array.isArray(grants)) { + addError(result, 'purpose_grants must be a list'); + } else { + grants.forEach((grant, i) => { + const g = validatePurposeGrant(grant); + if (!g.valid) addError(result, `Purpose grant ${i}: ${g.errors.join(', ')}`); + result.warnings.push(...g.warnings.map(w => `Grant ${i}: ${w}`)); + }); + } + } + if ('content_hash' in body) { + const h = validateLawfulBasisContentHash(body.content_hash); + result.warnings.push(...h.warnings.map(w => `Content hash: ${w}`)); + if (!h.valid) addError(result, `Content hash validation failed: ${h.errors.join(', ')}`); + } + if ('proof_mechanisms' in body) { + const proofs = body.proof_mechanisms; + if (!Array.isArray(proofs)) { + addError(result, 'proof_mechanisms must be a list'); + } else { + proofs.forEach((proof, i) => { + const p = validateProofMechanism(proof); + result.warnings.push(...p.warnings.map(w => `Proof mechanism ${i}: ${w}`)); + if (!p.valid) addError(result, `Proof mechanism ${i}: ${p.errors.join(', ')}`); + }); + } + } + if ('registry' in body) { + const r = validateRegistryInfo(body.registry); + if (!r.valid) addError(result, `Registry validation failed: ${r.errors.join(', ')}`); + } + return result; +} + +function validatePurposeGrant(value: unknown): LawfulBasisValidationResult { + const result = newResult(); + const grant = fields(value); + for (const field of ['purpose', 'granted', 'granted_at']) { + if (!(field in grant)) addError(result, `Missing required field in purpose grant: ${field}`); + } + if ('granted' in grant && typeof grant.granted !== 'boolean') { + addError(result, 'granted field must be a boolean'); + } + if ('granted_at' in grant && !isoTimestampOk(grant.granted_at)) { + addError(result, 'Invalid granted_at timestamp format'); + } + if ('conditions' in grant) { + const conditions = grant.conditions; + if (!Array.isArray(conditions)) addError(result, 'conditions must be a list'); + else if (!conditions.every(c => typeof c === 'string')) addError(result, 'All conditions must be strings'); + } + return result; +} + +function validateLawfulBasisContentHash(value: unknown): LawfulBasisValidationResult { + const result = newResult(); + const contentHash = fields(value); + for (const field of ['algorithm', 'canonicalization', 'value']) { + if (!(field in contentHash)) addError(result, `Missing required field in content_hash: ${field}`); + } + if ('algorithm' in contentHash && !LAWFUL_BASIS_HASH_ALGORITHMS.includes(contentHash.algorithm)) { + result.warnings.push(`Hash algorithm ${pyRepr(contentHash.algorithm)} is not one this library can verify`); + } + if ('canonicalization' in contentHash && !LAWFUL_BASIS_CANONICALIZATION.includes(contentHash.canonicalization)) { + result.warnings.push( + `Canonicalization method ${pyRepr(contentHash.canonicalization)} is not one this library can apply` + ); + } + if ('value' in contentHash && !(typeof contentHash.value === 'string' && /^[0-9a-fA-F]*$/.test(contentHash.value))) { + addError(result, 'Hash value must be a hexadecimal string'); + } + return result; +} + +function validateProofMechanism(value: unknown): LawfulBasisValidationResult { + const result = newResult(); + const proof = fields(value); + for (const field of ['proof_type', 'timestamp', 'proof_data']) { + if (!(field in proof)) addError(result, `Missing required field in proof mechanism: ${field}`); + } + if ('proof_type' in proof && !LAWFUL_BASIS_PROOF_TYPES.includes(proof.proof_type)) { + result.warnings.push(`Proof type ${pyRepr(proof.proof_type)} is not one of the types the draft defines`); + } + if ('timestamp' in proof && !isoTimestampOk(proof.timestamp)) { + addError(result, 'Invalid timestamp format in proof mechanism'); + } + if ('proof_data' in proof && !isPlainObject(proof.proof_data)) { + addError(result, 'proof_data must be a dictionary'); + } + return result; +} + +function validateRegistryInfo(value: unknown): LawfulBasisValidationResult { + const result = newResult(); + const registry = fields(value); + for (const field of ['type', 'url']) { + if (!(field in registry)) addError(result, `Missing required field in registry: ${field}`); + } + if ('type' in registry && registry.type !== 'scitt') { + result.warnings.push(`Unknown registry type: ${pyStr(registry.type)}`); + } + if ('url' in registry) { + const url = registry.url; + if (typeof url !== 'string' || !(url.startsWith('http://') || url.startsWith('https://'))) { + addError(result, 'Registry URL must be a valid HTTP/HTTPS URL'); + } + } + return result; +} diff --git a/src/util.ts b/src/util.ts index 985d8f7..f17d816 100644 --- a/src/util.ts +++ b/src/util.ts @@ -65,6 +65,107 @@ export function parseDateTimeMicros(value: unknown): number | undefined { return date.getTime() * 1000 + micros - offsetMinutes * 60_000_000; } +/** + * Why the Python reference (dateutil's parser) rejects a date-time value, as + * the text of its exception, for messages that quote it. Only meaningful for a + * value parseDateTime() rejects. + */ +export function dateTimeProblem(value: unknown): string { + if (typeof value !== 'string') { + return `Parser must be a string or character stream, not ${pyTypeName(value)}`; + } + if (value.trim() === '') return `String does not contain a date: ${value}`; + const m = DATE_RE.exec(value.trim()); + if (m) { + const [, ys, mos, ds, hs = '00', mis = '00', ss = '00', , tz = 'Z'] = m; + const [y, mo, d, h, mi, s] = [ys, mos, ds, hs, mis, ss].map(Number); + if (y < 1) return `year ${y} is out of range: ${value}`; + if (mo < 1 || mo > 12) return `month must be in 1..12: ${value}`; + const dim = mo === 2 && isLeapYear(y) ? 29 : DAYS_IN_MONTH[mo - 1]; + if (d < 1 || d > dim) return `day is out of range for month: ${value}`; + if (h > 23) return `hour must be in 0..23: ${value}`; + if (mi > 59) return `minute must be in 0..59: ${value}`; + if (s > 59) return `second must be in 0..59: ${value}`; + if (tz.toUpperCase() !== 'Z') { + return 'offset must be a timedelta strictly between -timedelta(hours=24) and timedelta(hours=24).'; + } + } + return `Unknown string format: ${value}`; +} + +const ISO_TIME_PART = /^(\d{2})(?:(:?)(\d{2})(?:\2(\d{2}))?)?(?:[.,](\d+))?$/; + +function parseIsoTimePart(s: string): { h: number; mi: number; sec: number; micros: number } | undefined { + const m = ISO_TIME_PART.exec(s); + if (!m) return undefined; + const h = Number(m[1]); + const mi = Number(m[3] ?? '0'); + const sec = Number(m[4] ?? '0'); + const micros = m[5] ? Number(m[5].slice(0, 6).padEnd(6, '0')) : 0; + return { h, mi, sec, micros }; +} + +function isoWeekToDate(year: number, week: number, day: number): Date | undefined { + const jan1 = new Date(Date.UTC(2000, 0, 1)); + jan1.setUTCFullYear(year); + const jan1Weekday = (jan1.getUTCDay() + 6) % 7; // Monday = 0 + if (week < 1 || week > 53 || day < 1 || day > 7) return undefined; + if (week === 53 && !(jan1Weekday === 3 || (jan1Weekday === 2 && isLeapYear(year)))) return undefined; + const jan4 = new Date(jan1.getTime() + 3 * 86_400_000); + const jan4Weekday = (jan4.getUTCDay() + 6) % 7; + return new Date(jan4.getTime() + ((week - 1) * 7 + (day - 1) - jan4Weekday) * 86_400_000); +} + +/** + * Parse a string the way Python's `datetime.fromisoformat` (3.11+) does, which + * the reference library's lawful basis validator uses. Returns epoch + * microseconds (a naive value read as UTC) and whether it carried an offset, or + * undefined if Python would raise ValueError. + */ +export function parsePyIsoformat(value: string): { micros: number; aware: boolean } | undefined { + if (!/^[\x21-\x7e]/.test(value) || value.length < 7) return undefined; + let dateLen: number; + if (value[4] === '-') { + dateLen = value[5] === 'W' ? (value.length > 8 && value[8] === '-' ? 10 : 8) : 10; + } else if (value[4] === 'W') { + dateLen = value.length > 7 && /\d/.test(value[7]) ? 8 : 7; + } else { + dateLen = 8; + } + const dateStr = value.slice(0, dateLen); + let date: Date | undefined; + let m: RegExpExecArray | null; + if ((m = /^(\d{4})-?W(\d{2})(?:-?(\d))?$/.exec(dateStr))) { + const y = Number(m[1]); + if (y < 1) return undefined; + date = isoWeekToDate(y, Number(m[2]), Number(m[3] ?? '1')); + } else if ((m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateStr) || /^(\d{4})(\d{2})(\d{2})$/.exec(dateStr))) { + const [y, mo, d] = [m[1], m[2], m[3]].map(Number); + if (y < 1 || mo < 1 || mo > 12 || d < 1) return undefined; + if (d > (mo === 2 && isLeapYear(y) ? 29 : DAYS_IN_MONTH[mo - 1])) return undefined; + date = new Date(Date.UTC(2000, mo - 1, d)); + date.setUTCFullYear(y); + } + if (!date) return undefined; + const rest = value.slice(dateLen); + if (rest === '') return { micros: date.getTime() * 1000, aware: false }; + const timeStr = rest.slice(1); + const tzPos = timeStr.search(/[-+Z]/); + const clock = parseIsoTimePart(tzPos < 0 ? timeStr : timeStr.slice(0, tzPos)); + if (!clock || clock.h > 23 || clock.mi > 59 || clock.sec > 59) return undefined; + let micros = date.getTime() * 1000 + ((clock.h * 60 + clock.mi) * 60 + clock.sec) * 1_000_000 + clock.micros; + if (tzPos < 0) return { micros, aware: false }; + const tz = timeStr.slice(tzPos); + if (tz !== 'Z') { + const off = parseIsoTimePart(tz.slice(1)); + if (!off || off.mi > 59 || off.sec > 59) return undefined; + const offMicros = ((off.h * 60 + off.mi) * 60 + off.sec) * 1_000_000 + off.micros; + if (offMicros >= 86_400_000_000) return undefined; + micros -= (tz[0] === '-' ? -1 : 1) * offMicros; + } + return { micros, aware: true }; +} + /** * Parse an ISO 8601 / RFC 3339 date-time string to epoch milliseconds, or * undefined if it is not one. See parseDateTimeMicros for the rules. @@ -117,6 +218,48 @@ export function repr(value: unknown): string { return JSON.stringify(value); } +/** The Python type name of a JSON value (int, float, str, bool, NoneType, list, dict). */ +export function pyTypeName(value: unknown): string { + if (value === null || value === undefined) return 'NoneType'; + if (typeof value === 'boolean') return 'bool'; + if (typeof value === 'number') return Number.isInteger(value) ? 'int' : 'float'; + if (typeof value === 'string') return 'str'; + if (Array.isArray(value)) return 'list'; + return 'dict'; +} + +function pyStringRepr(s: string): string { + const quote = s.includes("'") && !s.includes('"') ? '"' : "'"; + let out = ''; + for (const ch of s) { + const code = ch.codePointAt(0)!; + if (ch === '\\') out += '\\\\'; + else if (ch === quote) out += '\\' + ch; + else if (ch === '\n') out += '\\n'; + else if (ch === '\r') out += '\\r'; + else if (ch === '\t') out += '\\t'; + else if (code < 0x20 || (code >= 0x7f && code < 0xa0)) out += '\\x' + code.toString(16).padStart(2, '0'); + else out += ch; + } + return quote + out + quote; +} + +/** Python `repr()` of a JSON value, e.g. `'a'`, `None`, `[1, 'b']`, `{'k': True}`. */ +export function pyRepr(value: unknown): string { + if (typeof value === 'string') return pyStringRepr(value); + if (value === null || value === undefined) return 'None'; + if (value === true) return 'True'; + if (value === false) return 'False'; + if (typeof value === 'number') return String(value); + if (Array.isArray(value)) return `[${value.map(pyRepr).join(', ')}]`; + return `{${Object.entries(value as Record).map(([k, v]) => `${pyStringRepr(k)}: ${pyRepr(v)}`).join(', ')}}`; +} + +/** Python `str()` of a JSON value: strings as they are, anything else as pyRepr. */ +export function pyStr(value: unknown): string { + return typeof value === 'string' ? value : pyRepr(value); +} + /** Python-style repr of a list of strings, e.g. ['a', 'b']. */ export function reprList(values: unknown[]): string { return `[${values.map(repr).join(', ')}]`; diff --git a/src/validation.ts b/src/validation.ts index e349d4d..33971fa 100644 --- a/src/validation.ts +++ b/src/validation.ts @@ -6,7 +6,7 @@ */ import { CORE_EVENT_TYPES, validateEvent } from './event'; import { SESSION_REFERENCE_TYPES, validateSession } from './session'; -import { asList, isIndex, isPlainObject, parseDateTime } from './util'; +import { asList, dateTimeProblem, isIndex, isPlainObject, parseDateTime, pyRepr } from './util'; export const SYNTAX_VERSION = '0.5.0'; @@ -77,6 +77,79 @@ export const DIALOG_MIME_TYPES = [ const REDACTED_REF_RE = /__REDACTED_REF_(\d{1,5})(?!\d)/g; +/** ContentHash token (section 2.2): "-". */ +const CONTENT_HASH_RE = /^([a-z0-9]+)-([A-Za-z0-9_-]+)$/; +/** Unpadded base64url length of the digests this library knows. */ +const DIGEST_B64_LENGTHS: Record = { sha512: 86, sha256: 43 }; + +/** Return why `value` is not a ContentHash or ContentHash[] (empty if it is). */ +export function contentHashProblems(value: unknown): string[] { + if (Array.isArray(value) && value.length === 0) return ['must not be an empty array']; + const tokens = Array.isArray(value) ? value : [value]; + const problems: string[] = []; + for (const token of tokens) { + if (typeof token !== 'string') { + problems.push(`${pyRepr(token)} is not a string`); + continue; + } + const m = CONTENT_HASH_RE.exec(token); + if (!m) { + problems.push(`${pyRepr(token)} is not of the form '-'`); + continue; + } + const expected = Object.prototype.hasOwnProperty.call(DIGEST_B64_LENGTHS, m[1]) ? DIGEST_B64_LENGTHS[m[1]] : undefined; + if (expected !== undefined && m[2].length !== expected) { + problems.push( + `${pyRepr(token)} has a ${m[1]} digest of ${m[2].length} base64url characters, expected ${expected}` + ); + } + } + return problems; +} + +function isSerializedJson(body: string): boolean { + const s = body.trim(); + if (s[0] !== '{' && s[0] !== '[') return false; + try { + JSON.parse(s); + return true; + } catch { + return false; + } +} + +/** + * Integrity and body-form checks shared by Dialog, Attachment, Analysis and the + * redacted_from / amended_from references (section 2.4). + */ +function checkContent( + obj: Record, + label: string, + errors: string[], + warnings: string[], + checkUrl = true +): void { + if (checkUrl && 'url' in obj && !('content_hash' in obj)) { + // A MUST in section 2.4. A warning in 1.0.x, as in the reference library, + // so producers that only hold a carrier URL keep validating. + warnings.push( + `${label} has a url but no content_hash (an external reference MUST have both; ` + + 'this will be an error in vcon 1.1).' + ); + } + if ('content_hash' in obj) { + for (const problem of contentHashProblems(obj.content_hash)) { + errors.push(`${label} has an invalid content_hash: ${problem}.`); + } + } + if (obj.encoding === 'json' && typeof obj.body === 'string' && isSerializedJson(obj.body)) { + warnings.push( + `${label} has encoding 'json' and a body that is a serialized JSON string; ` + + 'the body should be the JSON value itself (section 2.3.2).' + ); + } +} + /** * True if `mediatype` is acceptable for a Dialog. Media type parameters * (`; boundary=...`) are ignored. Any multipart/, message/ or text/ subtype is @@ -179,7 +252,7 @@ export function validateVconDict( } for (const ts of ['created_at', 'updated_at']) { if (ts in vcon && parseDateTime(vcon[ts]) === undefined) { - errors.push(`Invalid ${ts} format. Must be an ISO 8601 datetime string.`); + errors.push(`Invalid ${ts} format. Must be an ISO 8601 datetime string: ${dateTimeProblem(vcon[ts])}`); } } if ('vcon' in vcon && vcon.vcon !== SYNTAX_VERSION) { @@ -246,6 +319,7 @@ export function validateVconDict( } else { if (!('type' in rf)) errors.push('redacted_from is missing required field: type'); if ('url' in rf && !('content_hash' in rf)) errors.push('redacted_from with url must include content_hash.'); + checkContent(rf, 'redacted_from', errors, warnings, false); } } if ('amended_from' in vcon) { @@ -257,6 +331,7 @@ export function validateVconDict( errors.push('amended_from must include uuid, or an external reference (url).'); } if ('url' in af && !('content_hash' in af)) errors.push('amended_from with url must include content_hash.'); + checkContent(af, 'amended_from', errors, warnings, false); } } @@ -379,6 +454,12 @@ export function validateVconDict( } }); + dialogs.forEach((dialog, i) => { + if (isPlainObject(dialog) && dialog.type !== 'incomplete') { + checkContent(dialog, `Dialog at index ${i}`, errors, warnings); + } + }); + // --- sessions ----------------------------------------------------------------- if ((dialogCount || events.length) && sessions.length === 0) { errors.push('At least one Session Object MUST exist if the events array or the dialog array contains Objects.'); @@ -442,6 +523,7 @@ export function validateVconDict( if (!(hasInline || hasExternal || redacted)) { errors.push(`Attachment at index ${i} must include body+encoding or url+content_hash.`); } + checkContent(attachment, `Attachment at index ${i}`, errors, warnings, hasInline || redacted); if ('encoding' in attachment && !CORE_ENCODINGS.includes(attachment.encoding) && extListed.length === 0) { errors.push(`Attachment at index ${i} has invalid encoding: ${attachment.encoding}`); } @@ -494,6 +576,7 @@ export function validateVconDict( if ('encoding' in analysis && !CORE_ENCODINGS.includes(analysis.encoding) && extListed.length === 0) { errors.push(`Analysis at index ${i} has invalid encoding: ${analysis.encoding}`); } + checkContent(analysis, `Analysis at index ${i}`, errors, warnings); const refs: Array<[string, number, string]> = [ ['dialog', dialogCount, 'dialog'], ['sessions', sessionCount, 'session'], diff --git a/src/vcon.ts b/src/vcon.ts index 16bd6c9..a4b0b9f 100644 --- a/src/vcon.ts +++ b/src/vcon.ts @@ -22,6 +22,7 @@ import { Session as SessionClass } from './session'; import { Event as EventClass } from './event'; import { migrate040To050, MigrationReport } from './migration'; import { validateVconDict } from './validation'; +import { validateLawfulBasisAttachment } from './lawful-basis'; import { base64UrlDecodeToString, clone, isPlainObject, warn } from './util'; /** A JWS used `alg` "none" (forbidden by core-05) or an unsupported algorithm. */ @@ -165,7 +166,9 @@ export class Vcon { analysis: input.analysis || [], ...input } as VconData; - this.data.created_at = created || this.data.created_at; + // A string is kept exactly as written (rewriting it would change the + // document and break a signature over it); a missing or empty value gets now. + this.data.created_at = created || new Date().toISOString(); if (this.data.vcon === undefined) delete this.data.vcon; } @@ -578,28 +581,40 @@ export class Vcon { * exists when there are Dialogs or Events, that attachments have `party` and * `dialog` or `session`, that `redacted_from` and `amended_from` are * exclusive, that `extensions` lists every extension in use (and every - * `critical` entry), and that every `__REDACTED_REF_#` has a - * `redacted_strings` entry. + * `critical` entry), that every `__REDACTED_REF_#` has a `redacted_strings` + * entry, that every `url` has a `content_hash` and every `content_hash` is + * well formed, and the body of every `lawful_basis` attachment. * * SHOULD-level findings are not errors; see getValidationWarnings(). */ isValid(): { valid: boolean; errors: string[] } { - const { errors } = validateVconDict(clone(this.data) as Record); + const { errors } = this.validateAll(); return { valid: errors.length === 0, errors }; } /** SHOULD-level findings (for example SHOULD NOT parameters on Events). */ getValidationWarnings(): string[] { + return this.validateAll().warnings; + } + + /** Core rules plus the body of every lawful_basis attachment. */ + private validateAll(): { errors: string[]; warnings: string[] } { const data = clone(this.data) as Record; - const { warnings } = validateVconDict(data); - // A lawful_basis attachment is scoped with party plus session (extension draft). - (data.attachments ?? []).forEach((a: any, i: number) => { - if (isPlainObject(a) && a.purpose === 'lawful_basis') { - if (!('party' in a)) warnings.push(`lawful_basis attachment at index ${i} has no party.`); - if (!('session' in a)) warnings.push(`lawful_basis attachment at index ${i} has no session; core-05 scopes a lawful basis to Sessions.`); - } + const { errors, warnings } = validateVconDict(data); + const attachments = Array.isArray(data.attachments) ? data.attachments : []; + attachments.forEach((attachment: unknown, i: number) => { + if (!isPlainObject(attachment) || attachment.purpose !== 'lawful_basis') return; + if (isPlainObject(data.redacted_from) && !('body' in attachment)) return; + // Scope (party, dialog/session) is checked by the core rules above. + const result = validateLawfulBasisAttachment(attachment); + errors.push(...result.errors.map(e => `Attachment at index ${i} (lawful_basis): ${e}`)); + warnings.push( + ...result.warnings + .filter(w => !w.includes('no party') && !w.includes('no session')) + .map(w => `Attachment at index ${i} (lawful_basis): ${w}`) + ); }); - return warnings; + return { errors, warnings }; } // Signing (JWS, general serialization with one signature)