Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,17 @@ jobs:
Arguments+=(--force-publish)
fi
npm run release:check -w builder -- "${Arguments[@]}"
- name: Set next patch version
- name: Set next version
if: steps.comparison.outputs.changed == 'true'
env:
BREAKING: ${{ steps.comparison.outputs.breaking }}
run: |
npm pkg set version="${{ steps.previous.outputs.version }}"
npm version patch --no-git-tag-version --workspaces=false
if [[ "${BREAKING}" == "true" ]]; then
npm version major --no-git-tag-version --workspaces=false
else
npm version patch --no-git-tag-version --workspaces=false
fi
- name: Inspect publish contents
if: steps.comparison.outputs.changed == 'true'
run: npm run pack:check
Expand Down
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const domains = getDomainsList()
const allowed = isAllowedToRun(new URL('https://sub.example.com/path'))
```

`getDomainsList()` returns a fresh copy of the sorted, wildcard-expanded `Full` domain list. `isAllowedToRun()` uses binary search to match either the exact URL hostname or a parent domain at a DNS label boundary.
`getDomainsList()` returns a fresh copy of the sorted `Full` list of collected domains and original suffix-wildcard patterns. `isAllowedToRun()` accepts HTTP(S) URLs, matches exact or parent domains at a DNS label boundary, and recognizes original patterns such as `example.*`, including multi-label suffixes. An original `example.*` also matches `example.com.evil` because all suffixes are allowed.

```js
isAllowedToRun(new URL('https://example.com/'))
Expand All @@ -34,7 +34,7 @@ isAllowedToRun(new URL('https://notexample.com/'))

The same functions are available from the typed `@filteringdev/tinyshield-domain-collection/lib` subpath. tinyShield should call `getDomainsList()` only from its builder so this data package is not bundled into the userscript. Runtime consumers such as Extra can use `isAllowedToRun()` to decide whether tinyShield should run for a URL.

The `Full` list is used because `Normal` may contain wildcard suffix patterns such as `domain.*`. Existing data constants remain available for compatibility:
The `Full` list is used for matching because `Normal` may contain synthetic wildcard groups that must not match uncollected suffixes. The data constants remain available:

```js
import {
Expand All @@ -57,9 +57,9 @@ import Normal from '@filteringdev/tinyshield-domain-collection/normal.json' with
| Export | JSON shape | Description |
| --- | --- | --- |
| `normal.json` | `string[]` | Deduplicated domain patterns from the tinyShield fetcher. |
| `full.json` | `string[]` | Patterns after wildcard suffix expansion. |
| `full.json` | `string[]` | Collected domains and original suffix-wildcard patterns, without expansion. |
| `each-domain.json` | `string[][]` | Normal patterns grouped by registrable domain. |
| `each-domain-full.json` | `string[][]` | Grouped patterns after wildcard suffix expansion. |
| `each-domain-full.json` | `string[][]` | Collected matching rules grouped by registrable domain name. |
| `manifest.json` | object | Schema, source package, counts, and canonical content hash. |

Every flat list, every group, and the list of groups are sorted by Unicode code point. The generated files do not contain timestamps, so identical source content produces byte-for-byte identical output.
Expand All @@ -68,7 +68,7 @@ Every flat list, every group, and the list of groups are sorted by Unicode code

```ts
type DomainCollectionManifest = {
readonly SchemaVersion: 1
readonly SchemaVersion: 2
readonly ContentHash: string
readonly SourcePackage: '@filteringdev/tinyshield-lib'
readonly SourcePackageVersion: string
Expand All @@ -85,13 +85,15 @@ type DomainCollectionManifest = {

## Updating

The scheduled workflow runs daily at 00:00 UTC and can also be started manually. It performs these steps:
The scheduled workflow runs daily at 00:00 UTC and can also be started manually. Before enabling schema 2 builds, publish a wildcard-preserving `@filteringdev/tinyshield-lib` release and update the builder's pinned dependency. The build rejects older expanded data. Schema 2 changes the meaning of `Full` and `EachDomainFull`; consumers must handle original `.*` patterns and must not interpret synthetic `Normal` groups as matching rules.

The workflow performs these steps:

1. Lint and test the generator.
2. Fetch live domain data through the npm release of `@filteringdev/tinyshield-lib`.
3. Download the latest npm package with retries and compare its manifest with the generated hash.
4. Exit without publishing when the hash is unchanged.
5. Increment only the patch version and publish through npm trusted publishing when content changed or a prerelease is promoted.
5. Increment the major version for a schema upgrade, otherwise increment the patch version, and publish through npm trusted publishing when content changed or a prerelease is promoted.

When the latest npm package is a prerelease, the workflow promotes it to a stable version even when the domain hash is unchanged. The workflow fails without publishing when an upstream request, repeated npm registry lookup, schema validation, or build fails. A decrease of more than 25 percent in the `Normal` count is also blocked. A maintainer can review the change and use the manual `allow-large-change` input to permit it.

Expand Down
2 changes: 1 addition & 1 deletion builder/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"test": "vitest run"
},
"dependencies": {
"@filteringdev/tinyshield-lib": "4.0.5"
"@filteringdev/tinyshield-lib": "4.1.0"
},
"devDependencies": {
"@types/node": "^24.12.2",
Expand Down
1 change: 1 addition & 0 deletions builder/source/check-release.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ async function CheckRelease(): Promise<void> {
const Status = Decision.Changed ? 'changed' : 'unchanged'

await AppendWorkflowFile(Process.env.GITHUB_OUTPUT, `changed=${Decision.Changed}\n`)
await AppendWorkflowFile(Process.env.GITHUB_OUTPUT, `breaking=${Current.SchemaVersion > Previous.SchemaVersion}\n`)
await AppendWorkflowFile(Process.env.GITHUB_STEP_SUMMARY, [
'## Domain release check',
'',
Expand Down
7 changes: 5 additions & 2 deletions builder/source/domain-artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createHash } from 'node:crypto'
const SourcePackage = '@filteringdev/tinyshield-lib'

export type DomainCollectionManifest = {
SchemaVersion: 1
SchemaVersion: 2
ContentHash: string
SourcePackage: typeof SourcePackage
SourcePackageVersion: string
Expand Down Expand Up @@ -91,6 +91,9 @@ export function CreateDomainArtifacts(Container: unknown, SourcePackageVersion:
if (!(Container instanceof Map)) {
throw new TypeError('Domain container must be a Map')
}
if (!(Container.get('Groups') instanceof Map)) {
throw new TypeError('Domain container must come from a wildcard-preserving tinyshield-lib release')
}
if (SourcePackageVersion.length === 0) {
throw new TypeError('Source package version must not be empty')
}
Expand All @@ -100,7 +103,7 @@ export function CreateDomainArtifacts(Container: unknown, SourcePackageVersion:
const EachDomain = NormalizeGroupedView(Container.get('EachDomain'), 'EachDomain')
const EachDomainFull = NormalizeGroupedView(Container.get('EachDomainFull'), 'EachDomainFull')
const Manifest: DomainCollectionManifest = {
SchemaVersion: 1,
SchemaVersion: 2,
ContentHash: CreateContentHash(Normal, Full, EachDomain, EachDomainFull),
SourcePackage,
SourcePackageVersion,
Expand Down
15 changes: 9 additions & 6 deletions builder/source/release-comparison.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { DomainCollectionManifest } from './domain-artifacts.js'

export type ComparableManifest = Omit<DomainCollectionManifest, 'SchemaVersion'> & { SchemaVersion: 1 | 2 }

export type ReleaseDecision = {
Changed: boolean
LargeDecrease: boolean
Expand All @@ -18,9 +20,9 @@ function ParseCount(Counts: Record<string, unknown>, Name: string): number {
return Count as number
}

export function ParseDomainCollectionManifest(Value: unknown, Name: string): DomainCollectionManifest {
export function ParseDomainCollectionManifest(Value: unknown, Name: string): ComparableManifest {
if (!IsRecord(Value)) throw new TypeError(`${Name} must contain an object`)
if (Value['SchemaVersion'] !== 1) throw new TypeError(`${Name} has an unsupported SchemaVersion`)
if (Value['SchemaVersion'] !== 1 && Value['SchemaVersion'] !== 2) throw new TypeError(`${Name} has an unsupported SchemaVersion`)
if (typeof Value['ContentHash'] !== 'string' || !/^[a-f0-9]{64}$/.test(Value['ContentHash'])) {
throw new TypeError(`${Name} must contain a SHA-256 ContentHash`)
}
Expand All @@ -33,7 +35,7 @@ export function ParseDomainCollectionManifest(Value: unknown, Name: string): Dom
if (!IsRecord(Value['Counts'])) throw new TypeError(`${Name} must contain Counts`)

return {
SchemaVersion: 1,
SchemaVersion: Value['SchemaVersion'],
ContentHash: Value['ContentHash'],
SourcePackage: '@filteringdev/tinyshield-lib',
SourcePackageVersion: Value['SourcePackageVersion'],
Expand All @@ -47,12 +49,13 @@ export function ParseDomainCollectionManifest(Value: unknown, Name: string): Dom
}

export function CompareReleaseManifests(
Current: DomainCollectionManifest,
Previous: DomainCollectionManifest,
Current: ComparableManifest,
Previous: ComparableManifest,
AllowLargeChange: boolean = false,
ForcePublish: boolean = false
): ReleaseDecision {
if (Current.ContentHash === Previous.ContentHash) {
if (Current.SchemaVersion < Previous.SchemaVersion) throw new Error('Cannot publish an older domain collection schema')
if (Current.SchemaVersion === Previous.SchemaVersion && Current.ContentHash === Previous.ContentHash) {
return { Changed: ForcePublish, LargeDecrease: false, DecreasePercentage: 0 }
}

Expand Down
21 changes: 14 additions & 7 deletions builder/test/domain-artifacts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import { pathToFileURL } from 'node:url'
import { test, expect, onTestFinished } from 'vitest'
import { CreateDomainArtifacts, type DomainArtifacts } from '../source/domain-artifacts.js'

function CreateContainer(Reverse: boolean = false): Map<string, Set<string> | Set<Set<string>>> {
function CreateContainer(Reverse: boolean = false): Map<string, Set<string> | Set<Set<string>> | Map<unknown, unknown>> {
const Order = <Value>(Values: Value[]): Value[] => Reverse ? Values.reverse() : Values

return new Map<string, Set<string> | Set<Set<string>>>([
return new Map<string, Set<string> | Set<Set<string>> | Map<unknown, unknown>>([
['Groups', new Map()],
['Normal', new Set(Order(['z.example', 'example.*', 'm.example']))],
['Full', new Set(Order(['z.example', 'test.org', 'middle.net', 'example.com', 'a.example']))],
['Full', new Set(Order(['z.example', 'test.org', 'middle.net', 'example.com', 'a.example', 'wild.*']))],
['EachDomain', new Set(Order([
new Set(Order(['z.example', 'a.example'])),
new Set(Order(['beta.test', 'alpha.test']))
Expand Down Expand Up @@ -85,21 +86,22 @@ test('records source metadata and view counts', () => {

expect(Artifacts.Manifest.ContentHash).toMatch(/^[a-f0-9]{64}$/)
expect(Artifacts.Manifest).toEqual({
SchemaVersion: 1,
SchemaVersion: 2,
ContentHash: Artifacts.Manifest.ContentHash,
SourcePackage: '@filteringdev/tinyshield-lib',
SourcePackageVersion: '4.0.5',
Counts: {
Normal: 3,
Full: 5,
Full: 6,
EachDomain: 2,
EachDomainFull: 2
}
})
})

test('rejects missing and empty views', () => {
expect(() => CreateDomainArtifacts(new Map(), '4.0.5')).toThrow('Normal must be a non-empty Set')
expect(() => CreateDomainArtifacts(new Map(), '4.0.5')).toThrow('wildcard-preserving tinyshield-lib release')
expect(() => CreateDomainArtifacts(new Map([['Groups', new Map()]]), '4.0.5')).toThrow('Normal must be a non-empty Set')

const EmptyGroup = CreateContainer()
EmptyGroup.set('EachDomain', new Set([new Set()]))
Expand All @@ -116,7 +118,7 @@ test('rejects non-string domains and an empty source version', () => {

test('generated library exposes a sorted, mutation-isolated domain API', async () => {
const { Library, Root } = await ImportGeneratedLibrary()
const ExpectedDomains = ['a.example', 'example.com', 'middle.net', 'test.org', 'z.example']
const ExpectedDomains = ['a.example', 'example.com', 'middle.net', 'test.org', 'wild.*', 'z.example']

const FirstList = Library.getDomainsList()
const SecondList = Library.getDomainsList()
Expand Down Expand Up @@ -144,4 +146,9 @@ test('isAllowedToRun matches exact domains and label-boundary suffixes', async (
expect(Library.isAllowedToRun(new URL('https://example.com./'))).toBe(true)
expect(Library.isAllowedToRun(new URL('https://notexample.com/'))).toBe(false)
expect(Library.isAllowedToRun(new URL('https://other.org/'))).toBe(false)
expect(Library.isAllowedToRun(new URL('https://sub.wild.co.uk/'))).toBe(true)
expect(Library.isAllowedToRun(new URL('https://wild.com.evil/'))).toBe(true)
expect(Library.isAllowedToRun(new URL('https://notwild.com/'))).toBe(false)
expect(Library.isAllowedToRun(new URL('https://wild/'))).toBe(false)
expect(Library.isAllowedToRun(new URL('ftp://example.com/'))).toBe(false)
})
10 changes: 9 additions & 1 deletion builder/test/release-comparison.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { CompareReleaseManifests, ParseDomainCollectionManifest } from '../sourc

function CreateManifest(Normal: number, HashCharacter: string = 'a'): DomainCollectionManifest {
return {
SchemaVersion: 1,
SchemaVersion: 2,
ContentHash: HashCharacter.repeat(64),
SourcePackage: '@filteringdev/tinyshield-lib',
SourcePackageVersion: '4.0.5',
Expand Down Expand Up @@ -61,4 +61,12 @@ test('parses a valid manifest and rejects malformed counts', () => {
Counts: { ...Manifest.Counts, Normal: 0 }
}
expect(() => ParseDomainCollectionManifest(InvalidManifest, 'Fixture')).toThrow('Manifest Counts.Normal must be a positive safe integer')
})

test('accepts a version 1 baseline and publishes a schema change', () => {
const Current = CreateManifest(100)
const Previous = { ...Current, SchemaVersion: 1 as const }
expect(ParseDomainCollectionManifest(Previous, 'Previous')).toEqual(Previous)
expect(CompareReleaseManifests(Current, Previous).Changed).toBe(true)
expect(() => CompareReleaseManifests(Previous, Current)).toThrow('older domain collection schema')
})
2 changes: 1 addition & 1 deletion source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from './domain-data.js'

export type DomainCollectionManifest = {
readonly SchemaVersion: 1
readonly SchemaVersion: 2
readonly ContentHash: string
readonly SourcePackage: '@filteringdev/tinyshield-lib'
readonly SourcePackageVersion: string
Expand Down
4 changes: 4 additions & 0 deletions source/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export function getDomainsList(): string[] {
}

export function isAllowedToRun(Url: URL): boolean {
if (Url.protocol !== 'http:' && Url.protocol !== 'https:') return false
let Hostname = Url.hostname.toLowerCase()
if (Hostname.endsWith('.')) Hostname = Hostname.slice(0, -1)
if (Hostname.length === 0) return false
Expand All @@ -44,6 +45,9 @@ export function isAllowedToRun(Url: URL): boolean {
for (let Index = 0; Index < Parts.length; Index += 1) {
const Candidate = Parts.slice(Index).join('.')
if (BinarySearch(Candidate)) return true
for (let End = Index + 1; End < Parts.length; End += 1) {
if (BinarySearch(`${Parts.slice(Index, End).join('.')}.*`)) return true
}
}

return false
Expand Down
Loading