@@ -57,12 +57,12 @@ export type ReportingData = ReportToData | CspReportUriData;
5757
5858// TODO: find out what's required and what's optional
5959export const isReportToItem = ( x : any ) : x is ReportToItem => {
60- const requiredKeys = [ "age" , "type" , "body" ] ;
61- return (
62- typeof x === "object" &&
63- Object . keys ( x ) . filter ( ( key ) => key in requiredKeys ) . length ===
64- requiredKeys . length
65- ) ;
60+ if ( typeof x !== "object" ) {
61+ return false ;
62+ }
63+ const requiredKeys = [ "type" , "body" ] ;
64+ const itemKeys = Object . keys ( x ) ;
65+ return requiredKeys . every ( ( key ) => itemKeys . includes ( key ) ) ;
6666} ;
6767
6868export const isReportToPayload = ( x : any ) : x is ReportToPayload => {
@@ -73,21 +73,43 @@ export const isCspReportUriPayload = (x: any): x is CspReportUriPayload => {
7373 return typeof x === "object" && ! ! x [ "csp-report" ] ;
7474} ;
7575
76- export const extractReportingData = (
77- data : unknown
78- ) : ReportingData | undefined => {
79- if ( isReportToPayload ( data ) ) {
80- return {
81- kind : "report-to" ,
82- data,
83- } ;
76+ const maybeArr = ( x : string ) => x . startsWith ( "[" ) ;
77+ const maybeObj = ( x : string ) => x . startsWith ( "{" ) ;
78+
79+ const deepJsonParse = ( x : unknown ) => {
80+ if ( typeof x === "string" && ( maybeArr ( x ) || maybeObj ( x ) ) ) {
81+ try {
82+ return JSON . parse ( x ) ;
83+ } catch {
84+ return x ;
85+ }
86+ }
87+ if ( typeof x === "object" ) {
88+ return Object . fromEntries (
89+ Object . entries ( x ) . map ( ( [ k , v ] ) => [ k , deepJsonParse ( v ) ] )
90+ ) ;
91+ }
92+ if ( Array . isArray ( x ) ) {
93+ return x . map ( deepJsonParse ) ;
8494 }
95+ return x ;
96+ } ;
97+
98+ export const extractReportingData = ( x : unknown ) : ReportingData | undefined => {
99+ const data = deepJsonParse ( x ) ;
85100 if ( isCspReportUriPayload ( data ) ) {
86101 const kind = "csp-report" ;
87102 return {
88103 kind,
89104 data : data [ kind ] ,
90105 } ;
91106 }
107+ if ( isReportToPayload ( data ) ) {
108+ return {
109+ kind : "report-to" ,
110+ data,
111+ } ;
112+ }
113+
92114 return undefined ;
93115} ;
0 commit comments