@blockcast/mmt-container 2.2.0-main.ea9223dc11de → 2.2.0-main.ec45bee1b9cc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +125 -2
  2. package/dist/__tests__/ad-creative-signer.d.ts +11 -0
  3. package/dist/__tests__/ad-creative-signer.d.ts.map +1 -0
  4. package/dist/__tests__/test-utils.d.ts +1 -0
  5. package/dist/__tests__/test-utils.d.ts.map +1 -1
  6. package/dist/ad-beacon.d.ts +39 -0
  7. package/dist/ad-beacon.d.ts.map +1 -0
  8. package/dist/ad-beacon.js +23 -0
  9. package/dist/ad-beacon.js.map +7 -0
  10. package/dist/ad-creative-record.d.ts +65 -0
  11. package/dist/ad-creative-record.d.ts.map +1 -0
  12. package/dist/ad-creative-record.js +2281 -0
  13. package/dist/ad-creative-record.js.map +7 -0
  14. package/dist/ad-creative-timeline.d.ts +103 -0
  15. package/dist/ad-creative-timeline.d.ts.map +1 -0
  16. package/dist/ad-creative-timeline.js +2550 -0
  17. package/dist/ad-creative-timeline.js.map +7 -0
  18. package/dist/block-policy.d.ts +128 -14
  19. package/dist/block-policy.d.ts.map +1 -1
  20. package/dist/block-policy.js +472 -27
  21. package/dist/block-policy.js.map +2 -2
  22. package/dist/browser-runtime.js +1039 -120
  23. package/dist/browser-runtime.js.map +4 -4
  24. package/dist/carp-catalog.d.ts +1 -0
  25. package/dist/carp-catalog.d.ts.map +1 -1
  26. package/dist/carp-catalog.js +34 -0
  27. package/dist/carp-catalog.js.map +4 -4
  28. package/dist/catalog-fec-params.js.map +1 -1
  29. package/dist/catalog-network-source.d.ts +1 -17
  30. package/dist/catalog-network-source.d.ts.map +1 -1
  31. package/dist/catalog-network-source.js +25 -19
  32. package/dist/catalog-network-source.js.map +3 -3
  33. package/dist/cmaf-block-assembler.d.ts +10 -2
  34. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  35. package/dist/cmaf-block-assembler.js +30 -8
  36. package/dist/cmaf-block-assembler.js.map +3 -3
  37. package/dist/codec-utils.d.ts.map +1 -1
  38. package/dist/codec-utils.js +16 -3
  39. package/dist/codec-utils.js.map +2 -2
  40. package/dist/conceal-timeline.d.ts +24 -1
  41. package/dist/conceal-timeline.d.ts.map +1 -1
  42. package/dist/conceal-timeline.js +201 -4
  43. package/dist/conceal-timeline.js.map +3 -3
  44. package/dist/datagram-leg-deadline.d.ts +4 -0
  45. package/dist/datagram-leg-deadline.d.ts.map +1 -1
  46. package/dist/datagram-leg-deadline.js.map +2 -2
  47. package/dist/event-timeline-mmtp.d.ts +17 -0
  48. package/dist/event-timeline-mmtp.d.ts.map +1 -0
  49. package/dist/event-timeline-mmtp.js +3117 -0
  50. package/dist/event-timeline-mmtp.js.map +7 -0
  51. package/dist/fec-manager.d.ts +24 -3
  52. package/dist/fec-manager.d.ts.map +1 -1
  53. package/dist/fec-manager.js +531 -38
  54. package/dist/fec-manager.js.map +2 -2
  55. package/dist/feed-gate.d.ts +114 -0
  56. package/dist/feed-gate.d.ts.map +1 -0
  57. package/dist/feed-gate.js +175 -0
  58. package/dist/feed-gate.js.map +7 -0
  59. package/dist/index.d.ts +3 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +13 -1
  62. package/dist/index.js.map +2 -2
  63. package/dist/iso-bmff-timing.d.ts +16 -0
  64. package/dist/iso-bmff-timing.d.ts.map +1 -1
  65. package/dist/iso-bmff-timing.js +28 -0
  66. package/dist/iso-bmff-timing.js.map +2 -2
  67. package/dist/mfu-reassembler.d.ts +2 -0
  68. package/dist/mfu-reassembler.d.ts.map +1 -1
  69. package/dist/mfu-reassembler.js +4 -2
  70. package/dist/mfu-reassembler.js.map +2 -2
  71. package/dist/mmtp-container-parser.d.ts +12 -0
  72. package/dist/mmtp-container-parser.d.ts.map +1 -1
  73. package/dist/mmtp-container-parser.js +73 -3
  74. package/dist/mmtp-container-parser.js.map +2 -2
  75. package/dist/mmtp-container-parser.no-modules.js +103 -25
  76. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  77. package/dist/mmtp-decode-pipeline.js +73 -3
  78. package/dist/mmtp-decode-pipeline.js.map +2 -2
  79. package/dist/mmtp-router.d.ts +20 -2
  80. package/dist/mmtp-router.d.ts.map +1 -1
  81. package/dist/mmtp-router.js +150 -23
  82. package/dist/mmtp-router.js.map +3 -3
  83. package/dist/multicast-auth-catalog.js.map +1 -1
  84. package/dist/multicast-input.js.map +1 -1
  85. package/dist/multicast-manager.d.ts +23 -2
  86. package/dist/multicast-manager.d.ts.map +1 -1
  87. package/dist/multicast-manager.js +749 -87
  88. package/dist/multicast-manager.js.map +3 -3
  89. package/dist/multicast-transport.d.ts +8 -0
  90. package/dist/multicast-transport.d.ts.map +1 -1
  91. package/dist/multicast-transport.js +56 -23
  92. package/dist/multicast-transport.js.map +2 -2
  93. package/dist/no-modules.js +98 -22
  94. package/dist/no-modules.js.map +4 -4
  95. package/dist/repair-fetch.d.ts +15 -7
  96. package/dist/repair-fetch.d.ts.map +1 -1
  97. package/dist/repair-fetch.js +34 -7
  98. package/dist/repair-fetch.js.map +2 -2
  99. package/dist/wasm-mfu-reassembler.js.map +2 -2
  100. package/dist/wasm-mmtp-container-parser.js +73 -3
  101. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  102. package/package.json +17 -5
  103. package/schemas/catalog.schema.json +7 -2
  104. package/src/ad-beacon.ts +54 -0
  105. package/src/ad-creative-record.ts +276 -0
  106. package/src/ad-creative-timeline.ts +410 -0
  107. package/src/block-policy.ts +673 -42
  108. package/src/carp-catalog.ts +9 -0
  109. package/src/catalog-network-source.ts +3 -37
  110. package/src/cmaf-block-assembler.ts +17 -0
  111. package/src/codec-utils.ts +19 -3
  112. package/src/conceal-timeline.ts +60 -5
  113. package/src/datagram-leg-deadline.ts +4 -0
  114. package/src/event-timeline-mmtp.ts +55 -0
  115. package/src/fec-manager.ts +84 -12
  116. package/src/feed-gate.ts +295 -0
  117. package/src/index.ts +21 -0
  118. package/src/iso-bmff-timing.ts +33 -0
  119. package/src/mfu-reassembler.ts +4 -0
  120. package/src/mmtp-container-parser.ts +51 -5
  121. package/src/mmtp-router.ts +116 -4
  122. package/src/multicast-manager.ts +31 -0
  123. package/src/multicast-transport.ts +27 -2
  124. package/src/repair-fetch.ts +70 -19
  125. package/test-vectors/catalog/README.md +1 -0
  126. package/test-vectors/catalog/negative/event-timeline-empty-event-type.json +41 -0
  127. package/test-vectors/catalog/positive/event-timeline-ad-creative.json +41 -0
  128. package/test-vectors/catalog/positive/event-timeline-wallclock-no-depends.json +38 -0
  129. package/test-vectors/catalog/positive/multicast-event-timeline.json +81 -0
  130. package/test-vectors/catalog/section-codes.json +1 -0
  131. package/test-vectors/frame-needs-v1.json +295 -0
  132. package/test-vectors/repair-policy-v1.json +98 -18
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockcast/mmt-container",
3
- "version": "2.2.0-main.ea9223dc11de",
3
+ "version": "2.2.0-main.ec45bee1b9cc",
4
4
  "description": "MMTP/LOC container parsing for MMT over MoQ and SSM",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -46,6 +46,10 @@
46
46
  "import": "./dist/conceal-timeline.js",
47
47
  "types": "./dist/conceal-timeline.d.ts"
48
48
  },
49
+ "./feed-gate": {
50
+ "import": "./dist/feed-gate.js",
51
+ "types": "./dist/feed-gate.d.ts"
52
+ },
49
53
  "./mmtp-router": {
50
54
  "import": "./dist/mmtp-router.js",
51
55
  "types": "./dist/mmtp-router.d.ts"
@@ -90,6 +94,14 @@
90
94
  "import": "./dist/cmcd-producer.js",
91
95
  "types": "./dist/cmcd-producer.d.ts"
92
96
  },
97
+ "./ad-creative-timeline": {
98
+ "import": "./dist/ad-creative-timeline.js",
99
+ "types": "./dist/ad-creative-timeline.d.ts"
100
+ },
101
+ "./event-timeline-mmtp": {
102
+ "import": "./dist/event-timeline-mmtp.js",
103
+ "types": "./dist/event-timeline-mmtp.d.ts"
104
+ },
93
105
  "./cmaf-group-batcher": {
94
106
  "import": "./dist/cmaf-group-batcher.js",
95
107
  "types": "./dist/cmaf-group-batcher.d.ts"
@@ -169,10 +181,10 @@
169
181
  "test:watch": "vitest"
170
182
  },
171
183
  "dependencies": {
172
- "@blockcast/fec-worker": "2.2.0-main.ea9223dc11de",
173
- "@blockcast/mmt-base": "2.2.0-main.ea9223dc11de",
174
- "@blockcast/mmt-fec": "2.2.0-main.ea9223dc11de",
175
- "@blockcast/mmt-manifest-verify": "2.2.0-main.ea9223dc11de",
184
+ "@blockcast/fec-worker": "2.2.0-main.ec45bee1b9cc",
185
+ "@blockcast/mmt-base": "2.2.0-main.ec45bee1b9cc",
186
+ "@blockcast/mmt-fec": "2.2.0-main.ec45bee1b9cc",
187
+ "@blockcast/mmt-manifest-verify": "2.2.0-main.ec45bee1b9cc",
176
188
  "@noble/curves": "^1.9.7",
177
189
  "@noble/hashes": "^1.8.0",
178
190
  "ajv": "^8.17.1",
@@ -65,20 +65,25 @@
65
65
  "properties": {
66
66
  "namespace": { "type": "string", "minLength": 1 },
67
67
  "name": { "type": "string", "minLength": 1 },
68
- "packaging": { "enum": ["mmtp", "fec-repair", "fec-source"] },
68
+ "packaging": { "enum": ["mmtp", "fec-repair", "fec-source", "eventtimeline"] },
69
69
  "isLive": {
70
70
  "type": "boolean",
71
71
  "default": true,
72
72
  "description": "Whether the track is live; omission defaults to true."
73
73
  },
74
74
  "codec": { "type": "string", "minLength": 1 },
75
- "role": { "enum": ["video", "audio", "repair"] },
75
+ "role": { "enum": ["video", "audio", "repair", "eventtimeline"] },
76
76
  "trackRole": {
77
77
  "type": "string",
78
78
  "minLength": 1,
79
79
  "description": "Publisher ownership role. Canonical values include base, delta, repair, audio, and abr-rung:<track name>."
80
80
  },
81
81
  "mimeType": { "type": "string", "minLength": 1 },
82
+ "eventType": {
83
+ "type": "string",
84
+ "minLength": 1,
85
+ "description": "MSF Event Timeline type of an eventtimeline track (draft-ietf-moq-msf-01 5.2.5, 8.2; -02 5.2.6, 8.3), e.g. urn:svta:advertising-wg:ad-creative-signaling. mimeType and depends are checked per track by catalogEventTimelineTracks: a schema rule would reject the whole catalog."
86
+ },
82
87
  "samplerate": { "$ref": "#/$defs/positiveInteger" },
83
88
  "channelConfig": { "type": "string", "minLength": 1 },
84
89
  "framerate": { "type": "number", "exclusiveMinimum": 0 },
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Beacon planning for ad creative signaling (draft-riedl-moq-ad-creative-signaling-01 7, 12):
3
+ * which URL to request and when. No I/O and no timers here (the cmcd-producer.ts precedent):
4
+ * the player sends each plan at sendAtMs with
5
+ * fetch(url, { mode: 'no-cors', credentials: 'omit', keepalive: true, referrerPolicy: 'no-referrer' }).
6
+ * The player calls this only for events the timeline emitted, so only for verified records.
7
+ */
8
+ import type { AdTrackEvent } from './ad-creative-timeline.js'
9
+
10
+ export interface AdBeaconPolicy {
11
+ /** Lower-case host[:port] beacons may go to (riedl 12.1), typically the distributor's beacon proxy. Empty: nothing is sent. */
12
+ readonly authorities: readonly string[]
13
+ /** Uniform jitter window W in ms (riedl 7.2). Size it from the audience: W >= 1000 * N * k / C ms, for N receivers,
14
+ * k requests each at that instant and C beacon-proxy requests/s. */
15
+ readonly jitterMs: number
16
+ /** Event types sent at once, unjittered: the verification-critical ones (riedl 7.2). */
17
+ readonly immediate?: readonly string[]
18
+ /** Pseudonymous, session-scoped client id appended as a query parameter (riedl 7.1). Never a device id. */
19
+ readonly clientId?: { readonly param: string; readonly value: string }
20
+ /** Query parameter carrying the event's wallclock ms on a jittered request (riedl 7.2). */
21
+ readonly eventTimeParam?: string
22
+ /** URLs sent per event at most; the rest are suppressed (riedl 12.2). Default 16, also used for a NaN, infinite or negative value. */
23
+ readonly maxUrlsPerEvent?: number
24
+ }
25
+
26
+ export type AdBeaconPlan =
27
+ | { readonly url: string; readonly sendAtMs: number; readonly eventType: string }
28
+ | { readonly url: string; readonly suppressed: 'authority' | 'cap' | 'macro'; readonly eventType: string }
29
+
30
+ /** A VAST macro such as [CACHEBUSTING]: riedl 7's first pattern (client-side substitution) is not supported. */
31
+ const VAST_MACRO = /\[[A-Z0-9_]+\]/
32
+
33
+ /** `random` gives the jitter phase in [0, 1). The player passes one phase drawn per session, so a device's events
34
+ * keep their order and spacing while the audience still spreads uniformly over [0, W) (riedl 7.2). */
35
+ export function planAdBeacons(event: AdTrackEvent, policy: AdBeaconPolicy, nowMs: number, random: () => number = Math.random): AdBeaconPlan[] {
36
+ const jittered = policy.jitterMs > 0 && !(policy.immediate ?? []).includes(event.eventType)
37
+ const delay = jittered ? Math.floor(random() * policy.jitterMs) : 0
38
+ const params: string[] = []
39
+ if (policy.clientId) params.push(`${encodeURIComponent(policy.clientId.param)}=${encodeURIComponent(policy.clientId.value)}`)
40
+ if (policy.eventTimeParam && jittered) params.push(`${encodeURIComponent(policy.eventTimeParam)}=${nowMs}`)
41
+ // A malformed setting (NaN from Number(undefined)) must not turn the cap off: i >= NaN is always false.
42
+ const max = policy.maxUrlsPerEvent
43
+ const cap = max !== undefined && Number.isFinite(max) && max >= 0 ? max : 16
44
+ return event.urls.map((raw, i): AdBeaconPlan => {
45
+ if (i >= cap) return { url: raw, suppressed: 'cap', eventType: event.eventType }
46
+ // Never sent unexpanded, and a device-identifier macro is never expanded (riedl 7.1, R33).
47
+ if (VAST_MACRO.test(raw)) return { url: raw, suppressed: 'macro', eventType: event.eventType }
48
+ const url = new URL(raw) // https and parseable: checked when the record was accepted (riedl 12.3)
49
+ if (!policy.authorities.includes(url.host)) return { url: raw, suppressed: 'authority', eventType: event.eventType }
50
+ // Append without re-encoding the capability URL's own query; a fragment stays last.
51
+ if (params.length > 0) url.search = url.search ? `${url.search}&${params.join('&')}` : `?${params.join('&')}`
52
+ return { url: url.href, sendAtMs: nowMs + delay, eventType: event.eventType }
53
+ })
54
+ }
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Ad creative signaling records, draft-riedl-moq-ad-creative-signaling-01 (riedl): the record
3
+ * signature (riedl 4.5) and the record and Object rules (riedl 4.1, 4.3, 12.3). Fail closed: only verdict 'verified' may ever drive a request (riedl 4.5:
4
+ * anything else is absent for section 7).
5
+ * Imports @noble/curves: never re-export it from src/index.ts (index.ts:42-46).
6
+ */
7
+ import { ed25519 } from '@noble/curves/ed25519'
8
+ import { decodeBase64Url, decodeEd25519PublicKey } from './multicast-auth-catalog.js'
9
+
10
+ /** kid -> raw 32-byte Ed25519 public key: one channel's JWK Set (riedl 4.5). */
11
+ export type AdCreativeKeys = ReadonlyMap<string, Uint8Array>
12
+ export type AdSigVerdict = 'verified' | 'unsigned' | 'sig' | 'alg' | 'kid' | 'signature'
13
+
14
+ const DETACHED_JWS = /^([A-Za-z0-9_-]+)\.\.([A-Za-z0-9_-]+)$/
15
+ const UTF8 = new TextDecoder('utf-8', { fatal: true })
16
+ const ENCODER = new TextEncoder()
17
+
18
+ const isObject = (value: unknown): value is Record<string, unknown> =>
19
+ typeof value === 'object' && value !== null && !Array.isArray(value)
20
+
21
+ /**
22
+ * The host-provisioned JWK Set (RFC 7517): OKP/Ed25519 public keys by kid (RFC 8037). This set is
23
+ * the only key source; jku, jwk, x5u and x5c in a header are never read (riedl 4.5). Never throws:
24
+ * a private, malformed or repeated-kid entry is left out, so records under it fail with 'kid'.
25
+ * `kids` is the channel's kid allowlist: given, only those kids are imported, so a validly signed
26
+ * record substituted from another channel fails with 'kid' too (riedl 4.5).
27
+ */
28
+ export function importAdCreativeJwks(jwks: unknown, kids?: readonly string[]): AdCreativeKeys {
29
+ const keys = new Map<string, Uint8Array>()
30
+ const repeated = new Set<string>()
31
+ const list = isObject(jwks) ? jwks['keys'] : undefined
32
+ for (const jwk of Array.isArray(list) ? list : []) {
33
+ if (!isObject(jwk)) continue
34
+ const kid = jwk['kid']
35
+ const x = jwk['x']
36
+ if (jwk['kty'] !== 'OKP' || jwk['crv'] !== 'Ed25519' || typeof kid !== 'string' || typeof x !== 'string' || 'd' in jwk) continue
37
+ if (kids !== undefined && !kids.includes(kid)) continue
38
+ if (keys.has(kid)) {
39
+ repeated.add(kid)
40
+ continue
41
+ }
42
+ try {
43
+ keys.set(kid, decodeEd25519PublicKey(x))
44
+ } catch {
45
+ // not a canonical 32-byte key: left out
46
+ }
47
+ }
48
+ for (const kid of repeated) keys.delete(kid) // an ambiguous kid verifies nothing
49
+ return keys
50
+ }
51
+
52
+ /** RFC 8785 for JSON.parse output: riedl's reference canonicalize() (scripts/sign-record.mjs at 443f90b2). */
53
+ export function canonicalJson(value: unknown): string {
54
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
55
+ if (isObject(value)) {
56
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`
57
+ }
58
+ if (typeof value === 'number' && !Number.isFinite(value)) throw new RangeError('RFC 8785 has no non-finite numbers')
59
+ return JSON.stringify(value)
60
+ }
61
+
62
+ /** riedl 4.5: a JWS with a detached, unencoded payload (RFC 7797) over `canonical`, EdDSA only. */
63
+ function checkJws(sig: unknown, canonical: string, keys: AdCreativeKeys): AdSigVerdict {
64
+ if (sig === undefined) return 'unsigned'
65
+ const parts = typeof sig === 'string' ? DETACHED_JWS.exec(sig) : null
66
+ if (!parts) return 'sig'
67
+ const protectedB64 = parts[1]!
68
+ let header: unknown
69
+ let signature: Uint8Array
70
+ try {
71
+ header = JSON.parse(UTF8.decode(decodeBase64Url(protectedB64)))
72
+ signature = decodeBase64Url(parts[2]!)
73
+ } catch {
74
+ return 'sig'
75
+ }
76
+ if (!isObject(header) || signature.length !== 64) return 'sig'
77
+ const crit = header['crit']
78
+ // RFC 7797 6: b64 false is listed in crit. RFC 7515 4.1.11: any other crit name is one we do not understand.
79
+ if (header['b64'] !== false || !Array.isArray(crit) || crit.length !== 1 || crit[0] !== 'b64') return 'sig'
80
+ // riedl 4.5: EdDSA is mandatory; none and HS256/384/512 are refused. "Ed25519" is EdDSA's fully
81
+ // specified name (RFC 9864 2.2), which riedl 4.5 allows by agreement; the keys are Ed25519 only.
82
+ if (header['alg'] !== 'EdDSA' && header['alg'] !== 'Ed25519') return 'alg'
83
+ const kid = header['kid']
84
+ const key = typeof kid === 'string' ? keys.get(kid) : undefined
85
+ if (!key) return 'kid'
86
+ try {
87
+ // The header segment as received, never re-encoded: unknown members stay inside the signed bytes.
88
+ const input = ENCODER.encode(`${protectedB64}.${canonical}`)
89
+ return ed25519.verify(signature, input, key, { zip215: false }) ? 'verified' : 'signature'
90
+ } catch {
91
+ return 'signature'
92
+ }
93
+ }
94
+
95
+ /** riedl 4.5 for one record as parsed from JSON: the verification entry point. */
96
+ export function verifyAdCreativeSig(record: Readonly<Record<string, unknown>>, keys: AdCreativeKeys): AdSigVerdict {
97
+ const unsigned: Record<string, unknown> = { ...record }
98
+ delete unsigned['sig']
99
+ return checkJws(record['sig'], canonicalJson(unsigned), keys)
100
+ }
101
+
102
+ export const AD_CREATIVE_EVENT_TYPE = 'urn:svta:advertising-wg:ad-creative-signaling'
103
+ /** riedl 12.3 size limit. An Object of two signed pods is about 4.4 KB. */
104
+ export const AD_OBJECT_MAX_BYTES = 65536
105
+ /** riedl 12.3: records per Object, which bounds the Ed25519 verifies one Object costs. */
106
+ export const AD_OBJECT_MAX_RECORDS = 64
107
+ /** riedl 12.3 nesting limit. A pod record nests 9 deep. */
108
+ export const AD_JSON_MAX_DEPTH = 16
109
+
110
+ /** The record index (msf-01 8.1, riedl 4.1): media time or wallclock in ms, or a MOQT Location. */
111
+ export type AdIndex =
112
+ | { readonly kind: 'm' | 't'; readonly ms: number }
113
+ | { readonly kind: 'l'; readonly group: number; readonly object: number }
114
+
115
+ /** One SVTA 2053-1 Version 2 carriage envelope (riedl 4.3). Payload members are SVTA's. */
116
+ export interface AdEnvelope {
117
+ readonly version: 2
118
+ readonly type: 'pod' | 'slot' | 'trackingEvent' | 'verification'
119
+ readonly payload: readonly Readonly<Record<string, unknown>>[]
120
+ readonly features?: Readonly<Record<string, boolean>>
121
+ }
122
+
123
+ export interface AdCreativeRecord {
124
+ readonly index: AdIndex
125
+ /** Supersede key (riedl 10 item 3): "m:480500", "t:1793016000000", "l:120,0". */
126
+ readonly key: string
127
+ readonly data: AdEnvelope
128
+ /** RFC 8785 form of the record without sig: the signed payload and the heartbeat dedup key. */
129
+ readonly canonical: string
130
+ }
131
+
132
+ export type AdRecordDrop =
133
+ | 'shape' | 'depth' | 'index' | 'data' | 'envelope' | 'url' | 'feature' | 'timing' | 'number'
134
+ | Exclude<AdSigVerdict, 'verified'>
135
+ export type AdObjectDrop = 'size' | 'utf8' | 'json' | 'not-array' | 'count'
136
+
137
+ export interface AdRecordResult {
138
+ readonly verdict: 'verified' | AdRecordDrop
139
+ /** Set once the index parsed. */
140
+ readonly key?: string
141
+ /** Set for 'verified', and for 'unsigned' and 'kid': well formed but unverifiable here, so
142
+ * observe-only mode may show them. Never set for a forged or malformed signature. */
143
+ readonly record?: AdCreativeRecord
144
+ }
145
+
146
+ export interface AdObjectResult {
147
+ readonly verdict: 'accepted' | AdObjectDrop
148
+ readonly records: readonly AdRecordResult[]
149
+ }
150
+
151
+ /** riedl 2: the MSF editor's copy renamed t, l, m to T, L, M; accept both until MSF settles. */
152
+ const INDEX_NAMES = ['m', 't', 'l', 'M', 'T', 'L']
153
+ const ENVELOPE_TYPES: ReadonlySet<string> = new Set(['pod', 'slot', 'trackingEvent', 'verification'])
154
+ /** SVTA 2053-1 defines one flag (riedl 4.3). */
155
+ const DEFINED_FEATURES: ReadonlySet<string> = new Set(['remoteFields'])
156
+ // shortcut: no $remote resolution, so remoteFields is unsupported and its payloads are ignored (SVTA 5.2.2.1); add it here with $remote.
157
+ const SUPPORTED_FEATURES: ReadonlySet<string> = new Set()
158
+
159
+ const isMs = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0
160
+
161
+ /** True when `value` nests no deeper than `limit` containers; the walk stops at `limit`. */
162
+ function depthWithin(value: unknown, limit: number): boolean {
163
+ if (typeof value !== 'object' || value === null) return true
164
+ if (limit === 0) return false
165
+ return (Array.isArray(value) ? value : Object.values(value)).every((child) => depthWithin(child, limit - 1))
166
+ }
167
+
168
+ function indexOf(record: Record<string, unknown>): AdIndex | undefined {
169
+ const present = INDEX_NAMES.filter((name) => name in record)
170
+ if (present.length !== 1) return undefined
171
+ const value = record[present[0]!]
172
+ const kind = present[0]!.toLowerCase()
173
+ if (kind === 'l') {
174
+ return Array.isArray(value) && value.length === 2 && value.every((n) => Number.isSafeInteger(n) && (n as number) >= 0)
175
+ ? { kind: 'l', group: value[0] as number, object: value[1] as number }
176
+ : undefined
177
+ }
178
+ return isMs(value) ? { kind: kind as 'm' | 't', ms: value } : undefined
179
+ }
180
+
181
+ const keyOf = (index: AdIndex): string =>
182
+ index.kind === 'l' ? `l:${index.group},${index.object}` : `${index.kind}:${index.ms}`
183
+
184
+ function envelopeOf(data: Record<string, unknown>): AdEnvelope | undefined {
185
+ const type = data['type']
186
+ const payload = data['payload']
187
+ const features = data['features']
188
+ if (data['version'] !== 2 || typeof type !== 'string' || !ENVELOPE_TYPES.has(type)) return undefined
189
+ if (!Array.isArray(payload) || payload.length === 0 || !payload.every(isObject)) return undefined
190
+ // riedl 4.3: a flag SVTA does not define may not be true; every flag is a boolean.
191
+ if (features !== undefined && !(isObject(features) &&
192
+ Object.entries(features).every(([name, on]) => typeof on === 'boolean' && (!on || DEFINED_FEATURES.has(name))))) {
193
+ return undefined
194
+ }
195
+ return data as unknown as AdEnvelope
196
+ }
197
+
198
+ const isHttpsUrl = (value: unknown): boolean => {
199
+ if (typeof value !== 'string') return false
200
+ try {
201
+ return new URL(value).protocol === 'https:'
202
+ } catch {
203
+ return false
204
+ }
205
+ }
206
+
207
+ /** Every string at any depth is an https URL: the whole of a `$remote` member, whatever its shape. */
208
+ const allHttps = (value: unknown): boolean =>
209
+ typeof value === 'string' ? isHttpsUrl(value)
210
+ : typeof value !== 'object' || value === null || (Array.isArray(value) ? value : Object.values(value)).every(allHttps)
211
+
212
+ /** riedl 12.3: https only in tracking (`urls`), `$remote` and verification (`resource`) fields. */
213
+ function httpsOnly(value: unknown): boolean {
214
+ if (Array.isArray(value)) return value.every(httpsOnly)
215
+ if (!isObject(value)) return true
216
+ return Object.entries(value).every(([name, child]) => {
217
+ if (name === '$remote') return allHttps(child)
218
+ if (name === 'urls' && !(Array.isArray(child) && child.every(isHttpsUrl))) return false
219
+ if (name === 'resource' && !isHttpsUrl(child)) return false
220
+ return httpsOnly(child)
221
+ })
222
+ }
223
+
224
+ /** One record: riedl 4.1 and 4.3 rules, 12.3 limits, SVTA flags, then the 4.5 signature. */
225
+ export function parseAdCreativeRecord(value: unknown, keys: AdCreativeKeys): AdRecordResult {
226
+ if (!isObject(value)) return { verdict: 'shape' }
227
+ if (!depthWithin(value, AD_JSON_MAX_DEPTH)) return { verdict: 'depth' }
228
+ const index = indexOf(value)
229
+ if (!index) return { verdict: 'index' }
230
+ const key = keyOf(index)
231
+ const data = value['data']
232
+ if (!isObject(data)) return { verdict: 'data', key }
233
+ const envelope = envelopeOf(data)
234
+ if (!envelope) return { verdict: 'envelope', key }
235
+ if (!httpsOnly(data)) return { verdict: 'url', key }
236
+ // SVTA 2053-1 5.2.2.1 as riedl 4.3 restates it: a true flag this receiver does not support means ignore the payload.
237
+ if (Object.entries(envelope.features ?? {}).some(([name, on]) => on && !SUPPORTED_FEATURES.has(name))) {
238
+ return { verdict: 'feature', key }
239
+ }
240
+ // shortcut: riedl 5.2 and 5.4 leave open what Pod.start is relative to (Question 13), so a pod with a
241
+ // non-zero start is ignored rather than fired early; schedule it once Riedl answers.
242
+ if (envelope.type === 'pod' && envelope.payload.some((pod) => pod['start'] !== undefined && pod['start'] !== 0)) {
243
+ return { verdict: 'timing', key }
244
+ }
245
+ const unsigned: Record<string, unknown> = { ...value }
246
+ delete unsigned['sig']
247
+ let canonical: string
248
+ try {
249
+ canonical = canonicalJson(unsigned)
250
+ } catch {
251
+ return { verdict: 'number', key } // JSON.parse made a number such as 1e400 Infinity, which RFC 8785 cannot write
252
+ }
253
+ const record: AdCreativeRecord = { index, key, data: envelope, canonical }
254
+ const verdict = checkJws(value['sig'], record.canonical, keys)
255
+ return verdict === 'verified' || verdict === 'unsigned' || verdict === 'kid' ? { verdict, key, record } : { verdict, key }
256
+ }
257
+
258
+ /** One MoQ Object of the track (msf-01 8.1: a JSON array of records). A gzip Object (MSF_COMPRESSION, msf 12.1) is not inflated here, so it drops as 'utf8' or 'json'. */
259
+ export function parseAdCreativeObject(bytes: Uint8Array, keys: AdCreativeKeys): AdObjectResult {
260
+ if (bytes.byteLength > AD_OBJECT_MAX_BYTES) return { verdict: 'size', records: [] }
261
+ let text: string
262
+ try {
263
+ text = UTF8.decode(bytes)
264
+ } catch {
265
+ return { verdict: 'utf8', records: [] }
266
+ }
267
+ let doc: unknown
268
+ try {
269
+ doc = JSON.parse(text)
270
+ } catch {
271
+ return { verdict: 'json', records: [] }
272
+ }
273
+ if (!Array.isArray(doc)) return { verdict: 'not-array', records: [] }
274
+ if (doc.length > AD_OBJECT_MAX_RECORDS) return { verdict: 'count', records: [] }
275
+ return { verdict: 'accepted', records: doc.map((record) => parseAdCreativeRecord(record, keys)) }
276
+ }