standdown 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dupe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/POLICIES.md ADDED
@@ -0,0 +1,44 @@
1
+ # standdown.js policy packs
2
+
3
+ All bundled policies were last verified on `2026-07-10`. Each policy carries
4
+ `metadata.sourceUrl`, `metadata.lastVerified`, and optional `metadata.notes`.
5
+
6
+ ## Defaults
7
+
8
+ `cocDefaults` implements the Affiliate Software Code of Conduct duration model
9
+ used when a network-specific duration is not available: advertiser scope,
10
+ 60-minute inactivity window, 90-minute fallback minimum, and complete
11
+ suppression behaviors (`suppress-prompts`, `no-cookie-write`, `no-redirect`,
12
+ `no-background-tracking`).
13
+
14
+ ## Pack sources
15
+
16
+ | Policy | Signals | Stand-down | Activation | Primary citation |
17
+ | --- | --- | --- | --- | --- |
18
+ | `cj` | `cjevent`, `cjdata`, `utm_source=cj`, `sf_cs=cj`, `afsrc=1`, CJ rotating domains, `cje` / `cjevent_dc` cookie names | Session-or-minimum 30m | User click | https://www.cj.com/legal/software-policy and https://github.com/piedotorg/standdown-domains |
19
+ | `impact` | `afsrc=1`, `irclickid`, `irgwc`, `im_ref` cookie names | Session-or-minimum 30m | User click | https://impact.com/stand-down-policy.ihtml |
20
+ | `rakuten` | `ranMID` + `ranEAID` + `ranSiteID`, `ranEAID` + `ranSiteID`, `ranSiteID`, `siteID`, LinkSynergy/JRS redirect domains, LinkShare cookie names | Session-or-minimum with CoC fallback minimum | User click | https://github.com/rakutenrewards/PublisherStandown-SDK |
21
+ | `awin` | `awc`, `utm_source=aw`, `source=aw`, `awin1.com` | CoC defaults | User click | https://success.awin.com/s/article/Downloadable-Software-Guidelines, https://success.awin.com/s/article/Soft-Click-Cookie-Status, and https://github.com/piedotorg/standdown-domains |
22
+ | `shareasale` | `sscid`, `shareasale.com`, `shrsl.com`, `sscid` cookie names | CoC defaults | User click | https://success.awin.com/s/article/Downloadable-Software-Guidelines and https://github.com/piedotorg/standdown-domains |
23
+ | `ebay-epn` | `campid`, `pubid`, `mkevt`, `mkcid`, `mkrid`, `[campid + _trkparms]`, `[mktype + gclid]`, `rover.ebay.com`, non-approved referrer class scoped to `ebay.<tld>` | CoC defaults | User click, max 2 prompts, own-site/organic/direct only | https://partnernetwork.ebay.com/browser-extension-policy and https://github.com/piedotorg/standdown-domains |
24
+ | `amazon` | `tag` | CoC fallback minimum for detected attribution visibility | Never | https://affiliate-program.amazon.com/help/operating/policies |
25
+ | `sovrn-skimlinks` | `go.skimresources.com`, `go.redirectingat.com` | CoC defaults | User click | https://www.sovrn.com/sovrn-commerce-publisher-code-of-conduct/ |
26
+ | `partnerize` | `clickref`, `prf.hn` | CoC defaults | User click | https://partnerize.com/legal/terms-and-conditions/ |
27
+ | `universal` | Full piedotorg/standdown-domains regex rule list, plus `afsrc=1` final-URL detection | CoC defaults | User click | https://github.com/piedotorg/standdown-domains and https://raw.githubusercontent.com/piedotorg/standdown-domains/main/standdown-domains.json |
28
+
29
+ Low-confidence entries remain bundled but are explicitly marked in
30
+ `metadata.notes`: `sovrn-skimlinks` redirect domains and `partnerize` `prf.hn`
31
+ were taken from research/domain knowledge rather than verified network policy
32
+ docs.
33
+
34
+ ## Third-party data attribution
35
+
36
+ The `universal` policy imports the full
37
+ `piedotorg/standdown-domains` rule set from
38
+ https://raw.githubusercontent.com/piedotorg/standdown-domains/main/standdown-domains.json.
39
+ That repository is licensed MIT:
40
+
41
+ > Copyright (c) 2025 The People's Internet Experiment Inc.
42
+
43
+ The bundled rules preserve the upstream comments as `DomainRule.comment`
44
+ values, with wording adjusted only to make the attribution explicit.
package/README.md ADDED
@@ -0,0 +1,171 @@
1
+ # standdown
2
+
3
+ Affiliate stand-down, done right, for browser extensions.
4
+
5
+ Built and maintained by Dupe.
6
+
7
+ `standdown` is a zero-runtime-dependency TypeScript library for extension
8
+ developers who need to detect existing affiliate attribution, suppress
9
+ competing activation, and prove that suppression decisions were made locally and
10
+ deterministically.
11
+
12
+ It ships four surfaces:
13
+
14
+ | Import | Purpose |
15
+ | --- | --- |
16
+ | `standdown` | Pure core: detection, session state machine, activation guard, policy validation, signed bundle verification, Rakuten converters |
17
+ | `standdown/policies` | Bundled policy packs and helpers |
18
+ | `standdown/webext` | Manifest V3 background/service-worker adapter |
19
+ | `standdown/content` | Content-script signal collector and evaluator |
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ npm install standdown
25
+ ```
26
+
27
+ This package is pre-release. Publishing is a human launch step; the repo should
28
+ not publish from CI.
29
+
30
+ ## Webext Quickstart
31
+
32
+ ```ts
33
+ import { allPolicies } from 'standdown/policies';
34
+ import { createStanddown } from 'standdown/webext';
35
+
36
+ const standdown = createStanddown({
37
+ policies: allPolicies,
38
+ selfPatterns: [{ name: 'my_click_id', networkId: 'cj' }],
39
+ publisherSites: ['example-publisher.com'],
40
+ });
41
+ ```
42
+
43
+ The adapter observes `chrome.webRequest.onBeforeRequest` redirect chains when
44
+ available and falls back to `chrome.webNavigation.onCommitted` final-URL signal
45
+ collection when reduced permissions or Safari-style APIs require it. Content
46
+ scripts and popups can query the background worker with:
47
+
48
+ `chrome.webNavigation.onCommitted` is required. `createStanddown()` throws when
49
+ that API is unavailable because an adapter that observes no navigations would
50
+ fail open.
51
+
52
+ ```ts
53
+ const response = await chrome.runtime.sendMessage({
54
+ type: 'standdown:shouldStandDown',
55
+ tabId,
56
+ url,
57
+ });
58
+ ```
59
+
60
+ Signed policy refresh is optional and runs outside the decision path:
61
+
62
+ ```ts
63
+ createStanddown({
64
+ policies: allPolicies,
65
+ refresh: {
66
+ url: 'https://static.example.com/standdown.bundle.json',
67
+ publicKeyJwk,
68
+ intervalMs: 60 * 60 * 1000,
69
+ },
70
+ });
71
+ ```
72
+
73
+ Only monotone updates are applied: detection coverage may broaden, durations may
74
+ lengthen, and activation rules must remain unchanged. Added overlapping
75
+ policies cannot downgrade a decision because the session layer unions behaviors
76
+ from every policy matching the advertiser. Signed bundles also reject overly
77
+ complex regex `DomainRule` patterns before they can enter local detection.
78
+
79
+ ## Content Quickstart
80
+
81
+ ```ts
82
+ import { allPolicies } from 'standdown/policies';
83
+ import { createContentStanddown } from 'standdown/content';
84
+
85
+ const standdown = createContentStanddown({
86
+ policies: allPolicies,
87
+ storage: 'session',
88
+ publisherSites: ['example-publisher.com'],
89
+ });
90
+
91
+ const decision = await standdown.ready;
92
+ ```
93
+
94
+ The content adapter collects only local page signals: `location.href`,
95
+ `document.referrer`, and first-party cookie names. Cookie values are never
96
+ included. SPA navigations are re-evaluated via `pushState`, `replaceState`, and
97
+ `popstate` hooks.
98
+
99
+ `storage: 'local-ttl'` stores session records in `localStorage` with a sliding
100
+ 24-hour envelope TTL by default. The TTL clears session records, not audit
101
+ history; per-policy stand-down durations remain enforced by the core state
102
+ machine.
103
+
104
+ ## Core Usage
105
+
106
+ ```ts
107
+ import { MemoryStateStore, StanddownSession, guardActivation } from 'standdown';
108
+ import { cjPolicy } from 'standdown/policies';
109
+
110
+ const session = new StanddownSession(new MemoryStateStore());
111
+ const decision = await session.ingest(
112
+ { url: 'https://merchant.example/?cjevent=abc', now: Date.now() },
113
+ [cjPolicy],
114
+ );
115
+
116
+ const guard = guardActivation({
117
+ decision,
118
+ userGesture: { isTrusted: true, type: 'click', timeStamp: performance.now() },
119
+ benefit: { kind: 'cashback', description: 'Activate cashback.' },
120
+ policy: cjPolicy,
121
+ });
122
+ ```
123
+
124
+ ## Public Commitments
125
+
126
+ - **I1: Client-side decisions only.** No network call participates in a
127
+ stand-down decision. Refresh may update the already-applied local policy
128
+ bundle asynchronously, but decisions use local state synchronously.
129
+ - **I2: No user profiling.** Signals are a closed type and exclude user identity,
130
+ accounts, balances, emails, login state, and tester-differentiating data.
131
+ - **I3: Fail toward standing down.** Unknown, ambiguous, malformed, or storage
132
+ error states suppress activation.
133
+ - **I4: Monotone remote updates.** Signed refresh bundles may only broaden
134
+ detection or lengthen durations and may not edit activation rules.
135
+ - **I5: Audit log on by default.** Decisions and refresh outcomes are locally
136
+ auditable.
137
+ - **I6: No remote code.** Policies are data. No eval, remote scripts, or dynamic
138
+ code loading.
139
+ - **I7: Deterministic and loggable.** Given the same local signals, policies,
140
+ state, and clock, decisions are reproducible.
141
+
142
+ ## Interop
143
+
144
+ `fromRakutenPolicy()` and `toRakutenPolicy()` convert Rakuten
145
+ `NetworkPolicy` schemaVersion 2 data. Rakuten's schema is detection-only, so
146
+ native fields such as cookie rules, initiator rules, activation guard details,
147
+ stand-down behaviors, citations, audit semantics, multi-group `anyOf` param
148
+ rules, and `match: 'contains'` params are lossy when emitting Rakuten v2. The
149
+ bundled `rakuten` policy itself intentionally does not round-trip exactly.
150
+
151
+ ## Policy Packs
152
+
153
+ | Policy | Main signals | Stand-down | Activation |
154
+ | --- | --- | --- | --- |
155
+ | `cj` | `cjevent`, `cjdata`, `utm_source=cj`, `sf_cs=cj`, `afsrc=1`, CJ redirect domains, CJ cookie names | Session-or-min 30m | User click |
156
+ | `impact` | `afsrc=1`, `irclickid`, `irgwc`, `im_ref` cookie names | Session-or-min 30m | User click |
157
+ | `rakuten` | `ranMID`, `ranEAID`, `ranSiteID`, `siteID`, LinkSynergy redirect domains, LinkShare cookie names | Session-or-min fallback | User click |
158
+ | `awin` | `awc`, `utm_source=aw`, `source=aw`, `awin1.com` | CoC defaults | User click |
159
+ | `shareasale` | `sscid`, ShareASale redirect domains, `sscid` cookie name | CoC defaults | User click |
160
+ | `ebay-epn` | eBay EPN params, `rover.ebay.com`, scoped referrer classification | CoC defaults | User click, max 2 prompts |
161
+ | `amazon` | Amazon `tag` on Amazon advertiser hosts | Suppression visibility only | Never |
162
+ | `sovrn-skimlinks` | Skimlinks redirect domains | CoC defaults | User click |
163
+ | `partnerize` | `clickref`, `prf.hn` | CoC defaults | User click |
164
+ | `universal` | Full `piedotorg/standdown-domains` list plus `afsrc=1` | CoC defaults | User click |
165
+
166
+ See [POLICIES.md](./POLICIES.md) for citations and attribution.
167
+
168
+ ## Example
169
+
170
+ See [examples/mv3-extension](./examples/mv3-extension) for a minimal Manifest V3
171
+ background worker and popup using `standdown/webext`.
@@ -0,0 +1,274 @@
1
+ import { validatePolicies } from './chunk-SVN6UWA4.mjs';
2
+
3
+ // src/bundle.ts
4
+ var textEncoder = new TextEncoder();
5
+ var MAX_SIGNED_BUNDLE_REGEX_LENGTH = 256;
6
+ async function verifyPolicyBundle(current, update, publicKeyJwk) {
7
+ try {
8
+ validatePolicies(current);
9
+ validatePolicies(update.policies);
10
+ } catch (error) {
11
+ return { ok: false, violation: `malformed-policy: ${messageFromError(error)}` };
12
+ }
13
+ if (update.schemaVersion !== 1) {
14
+ return { ok: false, violation: "unsupported-bundle-version" };
15
+ }
16
+ const signatureOk = await verifySignature(
17
+ update.signature.algorithm,
18
+ publicKeyJwk,
19
+ update.signature.value,
20
+ canonicalPolicyBundlePayload(update)
21
+ );
22
+ if (!signatureOk) {
23
+ return { ok: false, violation: "bad-signature" };
24
+ }
25
+ const regexViolation = regexComplexityViolation(update.policies);
26
+ if (regexViolation !== void 0) {
27
+ return { ok: false, violation: regexViolation };
28
+ }
29
+ const monotonicityViolation = checkMonotonicity(current, update.policies);
30
+ if (monotonicityViolation !== void 0) {
31
+ return { ok: false, violation: monotonicityViolation };
32
+ }
33
+ return { ok: true, policies: update.policies.map(clonePolicy) };
34
+ }
35
+ function canonicalPolicyBundlePayload(bundle) {
36
+ return canonicalJson({
37
+ schemaVersion: bundle.schemaVersion,
38
+ policies: bundle.policies
39
+ });
40
+ }
41
+ function canonicalJson(value) {
42
+ if (value === null || typeof value !== "object") {
43
+ if (typeof value === "number" && !Number.isFinite(value)) {
44
+ throw new TypeError("canonical JSON only supports finite numbers");
45
+ }
46
+ return JSON.stringify(value);
47
+ }
48
+ if (Array.isArray(value)) {
49
+ return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
50
+ }
51
+ const record = value;
52
+ const entries = Object.keys(record).filter((key) => record[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);
53
+ return `{${entries.join(",")}}`;
54
+ }
55
+ function checkMonotonicity(current, update) {
56
+ const updateById = new Map(update.map((policy) => [policy.id, policy]));
57
+ for (const currentPolicy of current) {
58
+ const updatedPolicy = updateById.get(currentPolicy.id);
59
+ if (updatedPolicy === void 0) {
60
+ return `policy-removed:${currentPolicy.id}`;
61
+ }
62
+ const detectionResult = detectionViolation(currentPolicy, updatedPolicy);
63
+ if (detectionResult !== void 0) {
64
+ return `${currentPolicy.id}:${detectionResult}`;
65
+ }
66
+ const standdownResult = standdownViolation(currentPolicy, updatedPolicy);
67
+ if (standdownResult !== void 0) {
68
+ return `${currentPolicy.id}:${standdownResult}`;
69
+ }
70
+ if (!sameJson(currentPolicy.activation, updatedPolicy.activation)) {
71
+ return `${currentPolicy.id}:activation-edited`;
72
+ }
73
+ }
74
+ return void 0;
75
+ }
76
+ function detectionViolation(currentPolicy, updatedPolicy) {
77
+ if (!domainRulesSurvive(
78
+ currentPolicy.detection.advertiserHosts,
79
+ updatedPolicy.detection.advertiserHosts,
80
+ { advertiserHosts: true }
81
+ )) {
82
+ return "advertiser-hosts-narrowed";
83
+ }
84
+ if (!paramRulesSurvive(
85
+ currentPolicy.detection.landingParams,
86
+ updatedPolicy.detection.landingParams
87
+ )) {
88
+ return "landing-params-narrowed";
89
+ }
90
+ if (!domainRulesSurvive(
91
+ currentPolicy.detection.redirectDomains,
92
+ updatedPolicy.detection.redirectDomains
93
+ )) {
94
+ return "redirect-domains-narrowed";
95
+ }
96
+ if (!cookieRulesSurvive(
97
+ currentPolicy.detection.cookiePatterns,
98
+ updatedPolicy.detection.cookiePatterns
99
+ )) {
100
+ return "cookie-patterns-narrowed";
101
+ }
102
+ if (!initiatorRulesSurvive(
103
+ currentPolicy.detection.initiatorRules,
104
+ updatedPolicy.detection.initiatorRules
105
+ )) {
106
+ return "initiator-rules-narrowed";
107
+ }
108
+ return void 0;
109
+ }
110
+ function standdownViolation(currentPolicy, updatedPolicy) {
111
+ if (updatedPolicy.standdown.scope !== currentPolicy.standdown.scope) {
112
+ return "standdown-scope-edited";
113
+ }
114
+ if (updatedPolicy.standdown.sessionRule !== currentPolicy.standdown.sessionRule) {
115
+ return "session-rule-edited";
116
+ }
117
+ if (updatedPolicy.standdown.minDurationMs < currentPolicy.standdown.minDurationMs) {
118
+ return "min-duration-shortened";
119
+ }
120
+ if (currentPolicy.standdown.inactivityMs !== void 0 && (updatedPolicy.standdown.inactivityMs === void 0 || updatedPolicy.standdown.inactivityMs < currentPolicy.standdown.inactivityMs)) {
121
+ return "inactivity-duration-shortened";
122
+ }
123
+ for (const behavior of currentPolicy.standdown.behaviors) {
124
+ if (!updatedPolicy.standdown.behaviors.includes(behavior)) {
125
+ return "standdown-behavior-removed";
126
+ }
127
+ }
128
+ return void 0;
129
+ }
130
+ function domainRulesSurvive(current, update, opts = {}) {
131
+ if (opts.advertiserHosts && current === void 0) {
132
+ return update === void 0;
133
+ }
134
+ if (current === void 0 || current.length === 0) {
135
+ return true;
136
+ }
137
+ if (opts.advertiserHosts && update === void 0) {
138
+ return true;
139
+ }
140
+ if (update === void 0 || update.length === 0) {
141
+ return false;
142
+ }
143
+ return current.every(
144
+ (rule) => update.some((candidate) => domainRuleCovers(rule, candidate))
145
+ );
146
+ }
147
+ function regexComplexityViolation(policies) {
148
+ for (const policy of policies) {
149
+ for (const [field, rules] of domainRuleEntries(policy)) {
150
+ for (const rule of rules ?? []) {
151
+ if (rule.kind === "regex" && isComplexRegex(rule.pattern)) {
152
+ return `${policy.id}:complex-regex:${field}`;
153
+ }
154
+ }
155
+ }
156
+ }
157
+ return void 0;
158
+ }
159
+ function domainRuleEntries(policy) {
160
+ return [
161
+ ["detection.advertiserHosts", policy.detection.advertiserHosts],
162
+ ["detection.redirectDomains", policy.detection.redirectDomains]
163
+ ];
164
+ }
165
+ function isComplexRegex(pattern) {
166
+ return pattern.length > MAX_SIGNED_BUNDLE_REGEX_LENGTH || hasRegexBackreference(pattern) || hasRegexLookaround(pattern) || hasNestedUnboundedQuantifier(pattern);
167
+ }
168
+ function hasRegexBackreference(pattern) {
169
+ return /(^|[^\\])\\[1-9]/.test(pattern);
170
+ }
171
+ function hasRegexLookaround(pattern) {
172
+ return /\(\?(?:[=!]|<[=!])/.test(pattern);
173
+ }
174
+ function hasNestedUnboundedQuantifier(pattern) {
175
+ return /\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\)(?:[+*]|\{\d*,?\})/.test(
176
+ pattern
177
+ );
178
+ }
179
+ function domainRuleCovers(current, update) {
180
+ if (current.kind === "suffix" && update.kind === "suffix") {
181
+ return domainSuffixMatches(current.pattern, update.pattern);
182
+ }
183
+ return sameJson(current, update);
184
+ }
185
+ function paramRulesSurvive(current, update) {
186
+ return exactRulesSurvive(current, update);
187
+ }
188
+ function cookieRulesSurvive(current, update) {
189
+ return exactRulesSurvive(current, update);
190
+ }
191
+ function initiatorRulesSurvive(current, update) {
192
+ return exactRulesSurvive(current, update);
193
+ }
194
+ function exactRulesSurvive(current, update) {
195
+ if (current === void 0 || current.length === 0) {
196
+ return true;
197
+ }
198
+ if (update === void 0 || update.length === 0) {
199
+ return false;
200
+ }
201
+ const updatedRules = new Set(update.map((rule) => canonicalJson(rule)));
202
+ return current.every((rule) => updatedRules.has(canonicalJson(rule)));
203
+ }
204
+ async function verifySignature(algorithm, publicKeyJwk, signatureValue, payload) {
205
+ try {
206
+ const publicKey = await importVerificationKey(algorithm, publicKeyJwk);
207
+ const signature = base64UrlToBytes(signatureValue);
208
+ const data = bytesToArrayBuffer(textEncoder.encode(payload));
209
+ if (algorithm === "ECDSA-P256") {
210
+ return crypto.subtle.verify(
211
+ { name: "ECDSA", hash: "SHA-256" },
212
+ publicKey,
213
+ bytesToArrayBuffer(signature),
214
+ data
215
+ );
216
+ }
217
+ return crypto.subtle.verify(
218
+ "Ed25519",
219
+ publicKey,
220
+ bytesToArrayBuffer(signature),
221
+ data
222
+ );
223
+ } catch {
224
+ return false;
225
+ }
226
+ }
227
+ async function importVerificationKey(algorithm, publicKeyJwk) {
228
+ if (algorithm === "ECDSA-P256") {
229
+ return crypto.subtle.importKey(
230
+ "jwk",
231
+ publicKeyJwk,
232
+ { name: "ECDSA", namedCurve: "P-256" },
233
+ false,
234
+ ["verify"]
235
+ );
236
+ }
237
+ return crypto.subtle.importKey("jwk", publicKeyJwk, "Ed25519", false, [
238
+ "verify"
239
+ ]);
240
+ }
241
+ function base64UrlToBytes(value) {
242
+ const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
243
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
244
+ const binary = atob(padded);
245
+ const bytes = new Uint8Array(binary.length);
246
+ for (let index = 0; index < binary.length; index += 1) {
247
+ bytes[index] = binary.charCodeAt(index);
248
+ }
249
+ return bytes;
250
+ }
251
+ function bytesToArrayBuffer(bytes) {
252
+ return bytes.buffer.slice(
253
+ bytes.byteOffset,
254
+ bytes.byteOffset + bytes.byteLength
255
+ );
256
+ }
257
+ function sameJson(left, right) {
258
+ return canonicalJson(left) === canonicalJson(right);
259
+ }
260
+ function domainSuffixMatches(host, pattern) {
261
+ const normalizedHost = host.toLowerCase().replace(/^\./, "").replace(/\.$/, "");
262
+ const normalizedPattern = pattern.toLowerCase().replace(/^\./, "").replace(/\.$/, "");
263
+ return normalizedHost === normalizedPattern || normalizedHost.endsWith(`.${normalizedPattern}`);
264
+ }
265
+ function clonePolicy(policy) {
266
+ return JSON.parse(JSON.stringify(policy));
267
+ }
268
+ function messageFromError(error) {
269
+ return error instanceof Error ? error.message : String(error);
270
+ }
271
+
272
+ export { canonicalJson, canonicalPolicyBundlePayload, verifyPolicyBundle };
273
+ //# sourceMappingURL=chunk-25A7QG5Z.mjs.map
274
+ //# sourceMappingURL=chunk-25A7QG5Z.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/bundle.ts"],"names":[],"mappings":";;;AAYA,IAAM,WAAA,GAAc,IAAI,WAAA,EAAY;AACpC,IAAM,8BAAA,GAAiC,GAAA;AAEvC,eAAsB,kBAAA,CACpB,OAAA,EACA,MAAA,EACA,YAAA,EACyC;AACzC,EAAA,IAAI;AACF,IAAA,gBAAA,CAAiB,OAAO,CAAA;AACxB,IAAA,gBAAA,CAAiB,OAAO,QAAQ,CAAA;AAAA,EAClC,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,EAAE,IAAI,KAAA,EAAO,SAAA,EAAW,qBAAqB,gBAAA,CAAiB,KAAK,CAAC,CAAA,CAAA,EAAG;AAAA,EAChF;AAEA,EAAA,IAAI,MAAA,CAAO,kBAAkB,CAAA,EAAG;AAC9B,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,SAAA,EAAW,4BAAA,EAA6B;AAAA,EAC9D;AAEA,EAAA,MAAM,cAAc,MAAM,eAAA;AAAA,IACxB,OAAO,SAAA,CA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AQ,OAAO,EAAE,CAAA,CACjB,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AAEpB,EAAA,OACE,mBAAmB,iBAAA,IACnB,cAAA,CAAe,QAAA,CAAS,CAAA,CAAA,EAAI,iBAAiB,CAAA,CAAE,CAAA;AAEnD;AAEA,SAAS,YAAY,MAAA,EAA0C;AAC7D,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAU,MAAM,CAAC,CAAA;AAC1C;AAEA,SAAS,iBAAiB,KAAA,EAAwB;AAChD,EAAA,OAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AAC9D","file":"chunk-25A7QG5Z.mjs","sourcesContent":["import type {\n CookieRule,\n DomainRule,\n InitiatorRule,\n ParamRule,\n PolicyBundleVerificationResult,\n SignedBundleSignatureAlgorithm,\n SignedPolicyBundle,\n StanddownPolicy,\n} from './types';\nimport { validatePolicies } from './validation';\n\nconst textEncoder = new TextEncoder();\nconst MAX_SIGNED_BUNDLE_REGEX_LENGTH = 256;\n\nexport async function verifyPolicyBundle(\n current: readonly StanddownPolicy[],\n update: SignedPolicyBundle,\n publicKeyJwk: JsonWebKey,\n): Promise<PolicyBundleVerificationResult> {\n try {\n validatePolicies(current);\n validatePolicies(update.policies);\n } catch (error) {\n return { ok: false, violation: `malformed-policy: ${messageFromError(error)}` };\n }\n\n if (update.schemaVersion !== 1) {\n return { ok: false, violation: 'unsupported-bundle-version' };\n }\n\n const signatureOk = await verifySignature(\n update.signature.algorithm,\n publicKeyJwk,\n update.signature.value,\n canonicalPolicyBundlePayload(update),\n );\n\n if (!signatureOk) {\n return { ok: false, violation: 'bad-signature' };\n }\n\n const regexViolation = regexComplexityViolation(update.policies);\n\n if (regexViolation !== undefined) {\n return { ok: false, violation: regexViolation };\n }\n\n const monotonicityViolation = checkMonotonicity(current, update.policies);\n\n if (monotonicityViolation !== undefined) {\n return { ok: false, violation: monotonicityViolation };\n }\n\n return { ok: true, policies: update.policies.map(clonePolicy) };\n}\n\nexport function canonicalPolicyBundlePayload(\n bundle: Pick<SignedPolicyBundle, 'schemaVersion' | 'policies'>,\n): string {\n return canonicalJson({\n schemaVersion: bundle.schemaVersion,\n policies: bundle.policies,\n });\n}\n\nexport function canonicalJson(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n if (typeof value === 'number' && !Number.isFinite(value)) {\n throw new TypeError('canonical JSON only supports finite numbers');\n }\n\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return `[${value.map((item) => canonicalJson(item)).join(',')}]`;\n }\n\n const record = value as Record<string, unknown>;\n const entries = Object.keys(record)\n .filter((key) => record[key] !== undefined)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);\n\n return `{${entries.join(',')}}`;\n}\n\nfunction checkMonotonicity(\n current: readonly StanddownPolicy[],\n update: readonly StanddownPolicy[],\n): string | undefined {\n const updateById = new Map(update.map((policy) => [policy.id, policy]));\n\n for (const currentPolicy of current) {\n const updatedPolicy = updateById.get(currentPolicy.id);\n\n if (updatedPolicy === undefined) {\n return `policy-removed:${currentPolicy.id}`;\n }\n\n const detectionResult = detectionViolation(currentPolicy, updatedPolicy);\n\n if (detectionResult !== undefined) {\n return `${currentPolicy.id}:${detectionResult}`;\n }\n\n const standdownResult = standdownViolation(currentPolicy, updatedPolicy);\n\n if (standdownResult !== undefined) {\n return `${currentPolicy.id}:${standdownResult}`;\n }\n\n if (!sameJson(currentPolicy.activation, updatedPolicy.activation)) {\n return `${currentPolicy.id}:activation-edited`;\n }\n }\n\n return undefined;\n}\n\nfunction detectionViolation(\n currentPolicy: StanddownPolicy,\n updatedPolicy: StanddownPolicy,\n): string | undefined {\n if (\n !domainRulesSurvive(\n currentPolicy.detection.advertiserHosts,\n updatedPolicy.detection.advertiserHosts,\n { advertiserHosts: true },\n )\n ) {\n return 'advertiser-hosts-narrowed';\n }\n\n if (\n !paramRulesSurvive(\n currentPolicy.detection.landingParams,\n updatedPolicy.detection.landingParams,\n )\n ) {\n return 'landing-params-narrowed';\n }\n\n if (\n !domainRulesSurvive(\n currentPolicy.detection.redirectDomains,\n updatedPolicy.detection.redirectDomains,\n )\n ) {\n return 'redirect-domains-narrowed';\n }\n\n if (\n !cookieRulesSurvive(\n currentPolicy.detection.cookiePatterns,\n updatedPolicy.detection.cookiePatterns,\n )\n ) {\n return 'cookie-patterns-narrowed';\n }\n\n if (\n !initiatorRulesSurvive(\n currentPolicy.detection.initiatorRules,\n updatedPolicy.detection.initiatorRules,\n )\n ) {\n return 'initiator-rules-narrowed';\n }\n\n return undefined;\n}\n\nfunction standdownViolation(\n currentPolicy: StanddownPolicy,\n updatedPolicy: StanddownPolicy,\n): string | undefined {\n if (updatedPolicy.standdown.scope !== currentPolicy.standdown.scope) {\n return 'standdown-scope-edited';\n }\n\n if (updatedPolicy.standdown.sessionRule !== currentPolicy.standdown.sessionRule) {\n return 'session-rule-edited';\n }\n\n if (updatedPolicy.standdown.minDurationMs < currentPolicy.standdown.minDurationMs) {\n return 'min-duration-shortened';\n }\n\n if (\n currentPolicy.standdown.inactivityMs !== undefined &&\n (updatedPolicy.standdown.inactivityMs === undefined ||\n updatedPolicy.standdown.inactivityMs < currentPolicy.standdown.inactivityMs)\n ) {\n return 'inactivity-duration-shortened';\n }\n\n for (const behavior of currentPolicy.standdown.behaviors) {\n if (!updatedPolicy.standdown.behaviors.includes(behavior)) {\n return 'standdown-behavior-removed';\n }\n }\n\n return undefined;\n}\n\nfunction domainRulesSurvive(\n current: readonly DomainRule[] | undefined,\n update: readonly DomainRule[] | undefined,\n opts: { advertiserHosts?: boolean } = {},\n): boolean {\n if (opts.advertiserHosts && current === undefined) {\n return update === undefined;\n }\n\n if (current === undefined || current.length === 0) {\n return true;\n }\n\n if (opts.advertiserHosts && update === undefined) {\n return true;\n }\n\n if (update === undefined || update.length === 0) {\n return false;\n }\n\n return current.every((rule) =>\n update.some((candidate) => domainRuleCovers(rule, candidate)),\n );\n}\n\nfunction regexComplexityViolation(\n policies: readonly StanddownPolicy[],\n): string | undefined {\n for (const policy of policies) {\n for (const [field, rules] of domainRuleEntries(policy)) {\n for (const rule of rules ?? []) {\n if (rule.kind === 'regex' && isComplexRegex(rule.pattern)) {\n return `${policy.id}:complex-regex:${field}`;\n }\n }\n }\n }\n\n return undefined;\n}\n\nfunction domainRuleEntries(\n policy: StanddownPolicy,\n): readonly (readonly [string, readonly DomainRule[] | undefined])[] {\n return [\n ['detection.advertiserHosts', policy.detection.advertiserHosts],\n ['detection.redirectDomains', policy.detection.redirectDomains],\n ] as const;\n}\n\nfunction isComplexRegex(pattern: string): boolean {\n return (\n pattern.length > MAX_SIGNED_BUNDLE_REGEX_LENGTH ||\n hasRegexBackreference(pattern) ||\n hasRegexLookaround(pattern) ||\n hasNestedUnboundedQuantifier(pattern)\n );\n}\n\nfunction hasRegexBackreference(pattern: string): boolean {\n return /(^|[^\\\\])\\\\[1-9]/.test(pattern);\n}\n\nfunction hasRegexLookaround(pattern: string): boolean {\n return /\\(\\?(?:[=!]|<[=!])/.test(pattern);\n}\n\nfunction hasNestedUnboundedQuantifier(pattern: string): boolean {\n return /\\((?:[^()\\\\]|\\\\.)*[+*](?:[^()\\\\]|\\\\.)*\\)(?:[+*]|\\{\\d*,?\\})/.test(\n pattern,\n );\n}\n\nfunction domainRuleCovers(current: DomainRule, update: DomainRule): boolean {\n if (current.kind === 'suffix' && update.kind === 'suffix') {\n return domainSuffixMatches(current.pattern, update.pattern);\n }\n\n return sameJson(current, update);\n}\n\nfunction paramRulesSurvive(\n current: readonly ParamRule[] | undefined,\n update: readonly ParamRule[] | undefined,\n): boolean {\n return exactRulesSurvive(current, update);\n}\n\nfunction cookieRulesSurvive(\n current: readonly CookieRule[] | undefined,\n update: readonly CookieRule[] | undefined,\n): boolean {\n return exactRulesSurvive(current, update);\n}\n\nfunction initiatorRulesSurvive(\n current: readonly InitiatorRule[] | undefined,\n update: readonly InitiatorRule[] | undefined,\n): boolean {\n return exactRulesSurvive(current, update);\n}\n\nfunction exactRulesSurvive<T>(\n current: readonly T[] | undefined,\n update: readonly T[] | undefined,\n): boolean {\n if (current === undefined || current.length === 0) {\n return true;\n }\n\n if (update === undefined || update.length === 0) {\n return false;\n }\n\n const updatedRules = new Set(update.map((rule) => canonicalJson(rule)));\n\n return current.every((rule) => updatedRules.has(canonicalJson(rule)));\n}\n\nasync function verifySignature(\n algorithm: SignedBundleSignatureAlgorithm,\n publicKeyJwk: JsonWebKey,\n signatureValue: string,\n payload: string,\n): Promise<boolean> {\n try {\n const publicKey = await importVerificationKey(algorithm, publicKeyJwk);\n const signature = base64UrlToBytes(signatureValue);\n const data = bytesToArrayBuffer(textEncoder.encode(payload));\n\n if (algorithm === 'ECDSA-P256') {\n return crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n publicKey,\n bytesToArrayBuffer(signature),\n data,\n );\n }\n\n return crypto.subtle.verify(\n 'Ed25519',\n publicKey,\n bytesToArrayBuffer(signature),\n data,\n );\n } catch {\n return false;\n }\n}\n\nasync function importVerificationKey(\n algorithm: SignedBundleSignatureAlgorithm,\n publicKeyJwk: JsonWebKey,\n): Promise<CryptoKey> {\n if (algorithm === 'ECDSA-P256') {\n return crypto.subtle.importKey(\n 'jwk',\n publicKeyJwk,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['verify'],\n );\n }\n\n return crypto.subtle.importKey('jwk', publicKeyJwk, 'Ed25519', false, [\n 'verify',\n ]);\n}\n\nfunction base64UrlToBytes(value: string): Uint8Array {\n const base64 = value.replace(/-/g, '+').replace(/_/g, '/');\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=');\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n return bytes;\n}\n\nfunction bytesToArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n return bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n ) as ArrayBuffer;\n}\n\nfunction sameJson(left: unknown, right: unknown): boolean {\n return canonicalJson(left) === canonicalJson(right);\n}\n\nfunction domainSuffixMatches(host: string, pattern: string): boolean {\n const normalizedHost = host.toLowerCase().replace(/^\\./, '').replace(/\\.$/, '');\n const normalizedPattern = pattern\n .toLowerCase()\n .replace(/^\\./, '')\n .replace(/\\.$/, '');\n\n return (\n normalizedHost === normalizedPattern ||\n normalizedHost.endsWith(`.${normalizedPattern}`)\n );\n}\n\nfunction clonePolicy(policy: StanddownPolicy): StanddownPolicy {\n return JSON.parse(JSON.stringify(policy)) as StanddownPolicy;\n}\n\nfunction messageFromError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"]}