@open-mercato/web-research 0.9.1-develop.7574.1.837288eec1 → 0.10.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/dist/contract/http.js.map +2 -2
- package/dist/contract/outcomes.js.map +2 -2
- package/dist/contract/version.js +1 -1
- package/dist/contract/version.js.map +1 -1
- package/dist/engine/engine.js +23 -8
- package/dist/engine/engine.js.map +2 -2
- package/dist/net/client.js +1 -0
- package/dist/net/client.js.map +2 -2
- package/dist/net/ssrf.js +2 -0
- package/dist/net/ssrf.js.map +2 -2
- package/dist/testing/contract.js +2 -2
- package/dist/testing/contract.js.map +2 -2
- package/package.json +4 -5
- package/src/contract/http.ts +1 -0
- package/src/contract/outcomes.ts +6 -1
- package/src/contract/version.ts +1 -1
- package/src/engine/__tests__/contentPolicy.test.ts +212 -0
- package/src/engine/engine.ts +27 -8
- package/src/engine/types.ts +1 -0
- package/src/net/__tests__/client.test.ts +173 -2
- package/src/net/__tests__/ssrf.test.ts +89 -2
- package/src/net/client.ts +1 -0
- package/src/net/ssrf.ts +2 -0
- package/src/testing/__tests__/contract.test.ts +14 -0
- package/src/testing/contract.ts +2 -2
package/dist/testing/contract.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { silentLogger } from "../contract/http.js";
|
|
2
|
-
import {
|
|
2
|
+
import { isSupportedContractVersion } from "../contract/version.js";
|
|
3
3
|
function createStubHttpClient(handler) {
|
|
4
4
|
const calls = [];
|
|
5
5
|
return {
|
|
@@ -35,7 +35,7 @@ function describeAdapterContract(module, testCase, api) {
|
|
|
35
35
|
const { describe, it, expect } = api;
|
|
36
36
|
describe(`${module.id} adapter contract`, () => {
|
|
37
37
|
it("declares the contract version it was built against", () => {
|
|
38
|
-
expect(module.contractVersion).toBe(
|
|
38
|
+
expect(isSupportedContractVersion(module.contractVersion)).toBe(true);
|
|
39
39
|
});
|
|
40
40
|
it("exposes a stable id and kind", () => {
|
|
41
41
|
expect(typeof module.id).toBe("string");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/testing/contract.ts"],
|
|
4
|
-
"sourcesContent": ["import type { AdapterContext, AdapterModule, SearchAdapter } from '../contract/adapter'\nimport { silentLogger, type HttpClient, type HttpResponse } from '../contract/http'\nimport {
|
|
5
|
-
"mappings": "AACA,SAAS,oBAAwD;AACjE,SAAS,
|
|
4
|
+
"sourcesContent": ["import type { AdapterContext, AdapterModule, SearchAdapter } from '../contract/adapter'\nimport { silentLogger, type HttpClient, type HttpResponse } from '../contract/http'\nimport { isSupportedContractVersion } from '../contract/version'\nimport type { SearchRequest } from '../contract/results'\n\nexport type StubResponse = Partial<HttpResponse> & { readonly body: string }\n\n/**\n * Minimal HTTP double. Adapters are contractually forbidden from reaching for\n * `fetch`, so a test that passes with this client has also proved the adapter\n * routes every byte through the hardened transport.\n */\nexport function createStubHttpClient(\n handler: (url: string, init: Parameters<HttpClient['request']>[1]) => StubResponse | Promise<StubResponse>,\n): HttpClient & { readonly calls: readonly string[] } {\n const calls: string[] = []\n return {\n calls,\n async request(url, init) {\n calls.push(url)\n const stub = await handler(url, init)\n return {\n url: stub.url ?? url,\n status: stub.status ?? 200,\n headers: stub.headers ?? new Map<string, string>(),\n contentType: stub.contentType ?? 'text/html',\n body: stub.body,\n truncated: stub.truncated ?? false,\n }\n },\n }\n}\n\nexport function createTestContext(overrides: Partial<AdapterContext> = {}): AdapterContext {\n return {\n signal: new AbortController().signal,\n http: createStubHttpClient(() => ({ body: '' })),\n report: () => {},\n deadlineAt: Date.now() + 10_000,\n logger: silentLogger,\n ...overrides,\n }\n}\n\nexport const SAMPLE_REQUEST: SearchRequest = { query: 'open mercato', limit: 5 }\n\nconst VALID_STATUSES = ['ok', 'empty', 'unavailable', 'blocked', 'timeout', 'error']\n\nexport type AdapterContractCase<TOptions> = {\n /** Options that leave the adapter deliberately unconfigured. */\n readonly unconfiguredOptions?: TOptions\n /** Options sufficient for the adapter to consider itself ready. */\n readonly configuredOptions: TOptions\n /** Context used for the \"returns results\" probe; stub the HTTP client here. */\n readonly context?: () => AdapterContext\n}\n\ntype TestApi = {\n describe: (name: string, body: () => void) => void\n it: (name: string, body: () => void | Promise<void>) => void\n expect: (value: unknown) => {\n toBe(expected: unknown): void\n toBeDefined(): void\n toContain(expected: string): void\n }\n}\n\n/**\n * Behavioural suite every adapter must pass, ours and third parties'. It pins the\n * parts of the contract the scheduler actually depends on \u2014 most importantly that\n * an adapter reports rather than throws, because a throwing adapter would\n * otherwise take down an entire search.\n */\nexport function describeAdapterContract<TOptions>(\n module: AdapterModule<TOptions>,\n testCase: AdapterContractCase<TOptions>,\n api: TestApi,\n): void {\n const { describe, it, expect } = api\n\n describe(`${module.id} adapter contract`, () => {\n it('declares the contract version it was built against', () => {\n expect(isSupportedContractVersion(module.contractVersion)).toBe(true)\n })\n\n it('exposes a stable id and kind', () => {\n expect(typeof module.id).toBe('string')\n expect(module.id.length > 0).toBe(true)\n expect(['serp', 'api', 'model', 'browser'].includes(module.kind)).toBe(true)\n })\n\n it('validates its own options', () => {\n const parsed = module.optionsSchema.safeParse(testCase.configuredOptions)\n expect(parsed.success).toBe(true)\n })\n\n it('reports readiness without performing I/O', () => {\n const adapter = module.createAdapter(testCase.configuredOptions)\n const readiness = adapter.readiness()\n expect(typeof readiness.ready).toBe('boolean')\n })\n\n const unconfigured = testCase.unconfiguredOptions\n if (unconfigured !== undefined) {\n it('is unavailable rather than broken when unconfigured', async () => {\n const adapter = module.createAdapter(unconfigured)\n const readiness = adapter.readiness()\n expect(readiness.ready).toBe(false)\n if (!readiness.ready) expect(readiness.reason.length > 0).toBe(true)\n\n const outcome = await adapter.search(SAMPLE_REQUEST, createTestContext())\n expect(outcome.status).toBe('unavailable')\n })\n }\n\n // The contract is \"never throws\", not \"always fails when HTTP does\" \u2014 a model\n // or browser adapter may not touch the HTTP client at all.\n it('returns an outcome rather than throwing when egress fails', async () => {\n const adapter = module.createAdapter(testCase.configuredOptions)\n const context = createTestContext({\n http: createStubHttpClient(() => {\n throw new Error('network exploded')\n }),\n })\n const outcome = await adapter.search(SAMPLE_REQUEST, context)\n expect(VALID_STATUSES.includes(outcome.status)).toBe(true)\n })\n\n it('honours an already-aborted signal without hanging', async () => {\n const adapter = module.createAdapter(testCase.configuredOptions)\n const controller = new AbortController()\n controller.abort()\n const outcome = await adapter.search(SAMPLE_REQUEST, createTestContext({ signal: controller.signal }))\n expect(typeof outcome.status).toBe('string')\n })\n\n it('never returns a result without a url', async () => {\n const adapter: SearchAdapter = module.createAdapter(testCase.configuredOptions)\n const context = testCase.context ? testCase.context() : createTestContext()\n const outcome = await adapter.search(SAMPLE_REQUEST, context)\n if (outcome.status !== 'ok') return\n for (const result of outcome.results) {\n expect(typeof result.url).toBe('string')\n expect(result.url.length > 0).toBe(true)\n }\n })\n\n // The host builds an engine per request and disposes it after, so a `dispose`\n // that throws on an adapter which was never used, or on a second call, breaks\n // teardown for every other adapter in the same engine. This is the surface\n // that leaked a browser sidecar and a Chromium per tool call.\n it('tears down cleanly even when it was never used', async () => {\n const adapter = module.createAdapter(testCase.configuredOptions)\n if (!adapter.dispose) return\n await adapter.dispose()\n await adapter.dispose()\n expect(true).toBe(true)\n })\n\n it('answers a health check without throwing', async () => {\n const adapter = module.createAdapter(testCase.configuredOptions)\n if (!adapter.healthCheck) return\n const context = createTestContext({\n http: createStubHttpClient(() => {\n throw new Error('network exploded')\n }),\n })\n const health = await adapter.healthCheck(context)\n expect(typeof health.ok).toBe('boolean')\n })\n })\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/web-research",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -42,13 +42,13 @@
|
|
|
42
42
|
}
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"zod": "^4.
|
|
45
|
+
"zod": "^4.6.6"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"@types/jest": "^30.0.0",
|
|
49
49
|
"@types/node": "^26.0.1",
|
|
50
50
|
"esbuild": "^0.28.1",
|
|
51
|
-
"glob": "^
|
|
51
|
+
"glob": "^14.0.6",
|
|
52
52
|
"jest": "^30.4.2",
|
|
53
53
|
"ts-jest": "^29.4.11",
|
|
54
54
|
"typescript": "^6.0.3"
|
|
@@ -60,6 +60,5 @@
|
|
|
60
60
|
"type": "git",
|
|
61
61
|
"url": "https://github.com/open-mercato/open-mercato",
|
|
62
62
|
"directory": "packages/web-research"
|
|
63
|
-
}
|
|
64
|
-
"stableVersion": "0.9.0"
|
|
63
|
+
}
|
|
65
64
|
}
|
package/src/contract/http.ts
CHANGED
|
@@ -7,6 +7,7 @@ export type HttpRequestInit = {
|
|
|
7
7
|
readonly maxBytes?: number
|
|
8
8
|
readonly timeoutMs?: number
|
|
9
9
|
readonly signal?: AbortSignal
|
|
10
|
+
readonly assertUrlAllowed?: (url: string) => void | Promise<void>
|
|
10
11
|
/**
|
|
11
12
|
* Content-type prefixes the caller can handle. A response outside the list is
|
|
12
13
|
* rejected with `unsupported_content_type` instead of being decoded as text —
|
package/src/contract/outcomes.ts
CHANGED
|
@@ -11,7 +11,12 @@ import type { FetchedPage, RawResult } from './results'
|
|
|
11
11
|
*/
|
|
12
12
|
export type OutcomeFailure =
|
|
13
13
|
| { readonly status: 'unavailable'; readonly reason: string }
|
|
14
|
-
| {
|
|
14
|
+
| {
|
|
15
|
+
readonly status: 'blocked'
|
|
16
|
+
readonly reason: string
|
|
17
|
+
readonly retryAfterMs?: number
|
|
18
|
+
readonly code?: 'domain_blocked'
|
|
19
|
+
}
|
|
15
20
|
| { readonly status: 'timeout'; readonly reason?: string }
|
|
16
21
|
| { readonly status: 'error'; readonly reason: string; readonly retriable: boolean }
|
|
17
22
|
|
package/src/contract/version.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* against; the loader refuses to instantiate a mismatched major rather than let a
|
|
4
4
|
* stale adapter fail in an unpredictable place at request time.
|
|
5
5
|
*/
|
|
6
|
-
export const CONTRACT_VERSION =
|
|
6
|
+
export const CONTRACT_VERSION = 2
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* Oldest adapter contract this engine still accepts.
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import type { SearchAdapter } from '../../contract/adapter'
|
|
2
|
+
import type { FetchOutcome } from '../../contract/outcomes'
|
|
3
|
+
import { resolvePolicy } from '../../contract/policy'
|
|
4
|
+
import { createStubHttpClient } from '../../testing/contract'
|
|
5
|
+
import { createFakeAdapter } from '../../testing/fakeAdapter'
|
|
6
|
+
import { createSearchEngine } from '../engine'
|
|
7
|
+
import type { EngineAdapterEntry, SearchEngineOptions, SearchEngineResult } from '../types'
|
|
8
|
+
|
|
9
|
+
const ALLOWED_URL = 'https://allowed.test/start'
|
|
10
|
+
const FINAL_URL = 'https://allowed.test/final'
|
|
11
|
+
const DENIED_URL = 'http://search.internal.local/admin'
|
|
12
|
+
const PAGE_TEXT = 'A permitted page with useful readable content for the agent.'
|
|
13
|
+
const DENIED_TEXT = 'A synthetic marker from the denied internal page.'
|
|
14
|
+
|
|
15
|
+
const entry = (adapter: SearchAdapter): EngineAdapterEntry => ({
|
|
16
|
+
adapter,
|
|
17
|
+
enabled: true,
|
|
18
|
+
order: 0,
|
|
19
|
+
weight: 1,
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const isContentUrlAllowed = (url: string): boolean => new URL(url).hostname === 'allowed.test'
|
|
23
|
+
|
|
24
|
+
function engineWith(overrides: Partial<SearchEngineOptions> = {}) {
|
|
25
|
+
return createSearchEngine({
|
|
26
|
+
policy: resolvePolicy({ minResults: 1, lastResort: null, escalateToBrowser: true }),
|
|
27
|
+
adapters: [entry(createFakeAdapter({ id: 'search', results: [{ url: ALLOWED_URL }] }))],
|
|
28
|
+
http: createStubHttpClient(() => ({ body: PAGE_TEXT, contentType: 'text/plain' })),
|
|
29
|
+
isContentUrlAllowed,
|
|
30
|
+
...overrides,
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function browserWith(fetch: NonNullable<SearchAdapter['fetch']>): SearchAdapter {
|
|
35
|
+
return {
|
|
36
|
+
...createFakeAdapter({ id: 'browser', kind: 'browser', capabilities: { fetch: true } }),
|
|
37
|
+
fetch,
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
describe('content URL authorization', () => {
|
|
42
|
+
it('skips denied result URLs before page fetching or fetch-budget charges', async () => {
|
|
43
|
+
const http = createStubHttpClient(() => ({ body: DENIED_TEXT }))
|
|
44
|
+
const engine = engineWith({
|
|
45
|
+
http,
|
|
46
|
+
adapters: [entry(createFakeAdapter({ id: 'search', results: [{ url: DENIED_URL }] }))],
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
const result = await engine.search({ query: 'internal page', includeContent: true })
|
|
50
|
+
|
|
51
|
+
expect(http.calls).toEqual([])
|
|
52
|
+
expect(result.diagnostics.pagesRead).toBe(0)
|
|
53
|
+
expect(result.results).toHaveLength(1)
|
|
54
|
+
expect(result.results[0].content).toBeNull()
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('blocks a direct denied URL before HTTP or browser navigation', async () => {
|
|
58
|
+
const http = createStubHttpClient(() => ({ body: DENIED_TEXT }))
|
|
59
|
+
const browserFetch = jest.fn(async (): Promise<FetchOutcome> => ({
|
|
60
|
+
status: 'unavailable',
|
|
61
|
+
reason: 'not expected',
|
|
62
|
+
}))
|
|
63
|
+
const engine = engineWith({ http, adapters: [entry(browserWith(browserFetch))] })
|
|
64
|
+
|
|
65
|
+
await expect(engine.fetch({ url: DENIED_URL })).resolves.toMatchObject({
|
|
66
|
+
status: 'blocked',
|
|
67
|
+
code: 'domain_blocked',
|
|
68
|
+
})
|
|
69
|
+
await expect(engine.fetch({ url: DENIED_URL, render: 'always' })).resolves.toMatchObject({
|
|
70
|
+
status: 'blocked',
|
|
71
|
+
code: 'domain_blocked',
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
expect(http.calls).toEqual([])
|
|
75
|
+
expect(browserFetch).not.toHaveBeenCalled()
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('passes per-hop authorization to HTTP and never escalates a domain denial', async () => {
|
|
79
|
+
const browserFetch = jest.fn(async (): Promise<FetchOutcome> => ({
|
|
80
|
+
status: 'unavailable',
|
|
81
|
+
reason: 'not expected',
|
|
82
|
+
}))
|
|
83
|
+
const http = createStubHttpClient((_url, init) => {
|
|
84
|
+
expect(init?.assertUrlAllowed).toBeDefined()
|
|
85
|
+
init?.assertUrlAllowed?.(DENIED_URL)
|
|
86
|
+
return { url: DENIED_URL, body: DENIED_TEXT }
|
|
87
|
+
})
|
|
88
|
+
const engine = engineWith({ http, adapters: [entry(browserWith(browserFetch))] })
|
|
89
|
+
|
|
90
|
+
await expect(engine.fetch({ url: ALLOWED_URL })).resolves.toMatchObject({
|
|
91
|
+
status: 'blocked',
|
|
92
|
+
code: 'domain_blocked',
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
expect(browserFetch).not.toHaveBeenCalled()
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it('rejects a denied final URL even when a custom HTTP client ignores the assertion', async () => {
|
|
99
|
+
const http = createStubHttpClient(() => ({ url: DENIED_URL, body: DENIED_TEXT }))
|
|
100
|
+
const engine = engineWith({ http })
|
|
101
|
+
|
|
102
|
+
const result = await engine.search({ query: 'redirected page', includeContent: true })
|
|
103
|
+
const fetched = await engine.fetch({ url: ALLOWED_URL, render: 'never' })
|
|
104
|
+
|
|
105
|
+
expect(fetched).toMatchObject({ status: 'blocked', code: 'domain_blocked' })
|
|
106
|
+
expect(result.results[0]).toMatchObject({ url: ALLOWED_URL, content: null })
|
|
107
|
+
expect(JSON.stringify(result.results)).not.toContain(DENIED_TEXT)
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it('attributes permitted redirected content to its final URL', async () => {
|
|
111
|
+
const http = createStubHttpClient((_url, init) => {
|
|
112
|
+
init?.assertUrlAllowed?.(FINAL_URL)
|
|
113
|
+
return { url: FINAL_URL, body: PAGE_TEXT, contentType: 'text/plain' }
|
|
114
|
+
})
|
|
115
|
+
const engine = engineWith({ http })
|
|
116
|
+
|
|
117
|
+
const result = await engine.search({ query: 'permitted redirect', includeContent: true })
|
|
118
|
+
|
|
119
|
+
expect(result.results[0]).toMatchObject({ url: FINAL_URL, content: PAGE_TEXT })
|
|
120
|
+
expect(result.diagnostics.pagesRead).toBe(1)
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('keeps adapter service requests independent of page-domain policy', async () => {
|
|
124
|
+
const assertions: Array<boolean> = []
|
|
125
|
+
const http = createStubHttpClient((url, init) => {
|
|
126
|
+
assertions.push(init?.assertUrlAllowed !== undefined)
|
|
127
|
+
return { body: url === DENIED_URL ? 'adapter API response' : PAGE_TEXT, contentType: 'text/plain' }
|
|
128
|
+
})
|
|
129
|
+
const adapter: SearchAdapter = {
|
|
130
|
+
...createFakeAdapter({ id: 'internal-adapter' }),
|
|
131
|
+
async search(_request, context) {
|
|
132
|
+
await context.http.request(DENIED_URL)
|
|
133
|
+
return { status: 'ok', results: [{ url: ALLOWED_URL }] }
|
|
134
|
+
},
|
|
135
|
+
}
|
|
136
|
+
const engine = engineWith({ http, adapters: [entry(adapter)] })
|
|
137
|
+
|
|
138
|
+
const result = await engine.search({ query: 'permitted adapter', includeContent: true })
|
|
139
|
+
|
|
140
|
+
expect(http.calls).toEqual([DENIED_URL, ALLOWED_URL])
|
|
141
|
+
expect(assertions).toEqual([false, true])
|
|
142
|
+
expect(result.results[0].content).toBe(PAGE_TEXT)
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it.each(['auto', 'always'] as const)('refuses unguarded browser content navigation in %s mode', async (render) => {
|
|
146
|
+
const http = createStubHttpClient(() => ({ body: '<html><body><div id="root"></div></body></html>' }))
|
|
147
|
+
const browserFetch = jest.fn(async (): Promise<FetchOutcome> => ({
|
|
148
|
+
status: 'unavailable',
|
|
149
|
+
reason: 'not expected',
|
|
150
|
+
}))
|
|
151
|
+
const engine = engineWith({ http, adapters: [entry(browserWith(browserFetch))] })
|
|
152
|
+
|
|
153
|
+
const outcome = await engine.fetch({ url: ALLOWED_URL, render })
|
|
154
|
+
|
|
155
|
+
expect(browserFetch).not.toHaveBeenCalled()
|
|
156
|
+
if (render === 'always') {
|
|
157
|
+
expect(outcome.status).toBe('blocked')
|
|
158
|
+
expect(http.calls).toEqual([])
|
|
159
|
+
} else {
|
|
160
|
+
expect(outcome).toMatchObject({ status: 'ok', page: { renderedWith: 'http' } })
|
|
161
|
+
}
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
it('preserves browser content fetching when no URL policy is supplied', async () => {
|
|
165
|
+
const browserFetch = jest.fn(async (): Promise<FetchOutcome> => ({
|
|
166
|
+
status: 'ok',
|
|
167
|
+
page: {
|
|
168
|
+
url: FINAL_URL,
|
|
169
|
+
title: null,
|
|
170
|
+
text: PAGE_TEXT,
|
|
171
|
+
contentType: 'text/html',
|
|
172
|
+
status: 200,
|
|
173
|
+
truncated: false,
|
|
174
|
+
renderedWith: 'browser',
|
|
175
|
+
},
|
|
176
|
+
}))
|
|
177
|
+
const engine = engineWith({
|
|
178
|
+
adapters: [entry(browserWith(browserFetch))],
|
|
179
|
+
isContentUrlAllowed: undefined,
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
await expect(engine.fetch({ url: ALLOWED_URL, render: 'always' })).resolves.toMatchObject({
|
|
183
|
+
status: 'ok',
|
|
184
|
+
page: { url: FINAL_URL, text: PAGE_TEXT, renderedWith: 'browser' },
|
|
185
|
+
})
|
|
186
|
+
expect(browserFetch).toHaveBeenCalledTimes(1)
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
it('bypasses cached enriched content whenever page-domain policy is supplied', async () => {
|
|
190
|
+
const unsafe = await engineWith({
|
|
191
|
+
http: createStubHttpClient(() => ({ body: DENIED_TEXT, contentType: 'text/plain' })),
|
|
192
|
+
isContentUrlAllowed: undefined,
|
|
193
|
+
}).search({ query: 'cached redirect', includeContent: true })
|
|
194
|
+
const cache = {
|
|
195
|
+
get: jest.fn(async (): Promise<SearchEngineResult | null> => unsafe),
|
|
196
|
+
set: jest.fn(async () => {}),
|
|
197
|
+
}
|
|
198
|
+
const http = createStubHttpClient(() => ({ body: PAGE_TEXT, contentType: 'text/plain' }))
|
|
199
|
+
const engine = engineWith({ http, cache })
|
|
200
|
+
|
|
201
|
+
const first = await engine.search({ query: 'cached redirect', includeContent: true })
|
|
202
|
+
const second = await engine.search({ query: 'cached redirect', includeContent: true })
|
|
203
|
+
|
|
204
|
+
expect(cache.get).not.toHaveBeenCalled()
|
|
205
|
+
expect(cache.set).not.toHaveBeenCalled()
|
|
206
|
+
expect(http.calls).toEqual([ALLOWED_URL, ALLOWED_URL])
|
|
207
|
+
expect(first.results[0].content).toBe(PAGE_TEXT)
|
|
208
|
+
expect(second.results[0].content).toBe(PAGE_TEXT)
|
|
209
|
+
expect(first.diagnostics.cached).toBe(false)
|
|
210
|
+
expect(second.diagnostics.cached).toBe(false)
|
|
211
|
+
})
|
|
212
|
+
})
|
package/src/engine/engine.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ProbeCost, SearchAdapter } from '../contract/adapter'
|
|
2
|
+
import { WebResearchError } from '../contract/errors'
|
|
2
3
|
import { silentLogger } from '../contract/http'
|
|
3
|
-
import { timedOut, toOutcomeFailure, type FetchOutcome } from '../contract/outcomes'
|
|
4
|
+
import { blocked, timedOut, toOutcomeFailure, type FetchOutcome } from '../contract/outcomes'
|
|
4
5
|
import type { SearchPolicy } from '../contract/policy'
|
|
5
6
|
import {
|
|
6
7
|
searchRequestSchema,
|
|
@@ -112,11 +113,13 @@ export function createSearchEngine(options: SearchEngineOptions): SearchEngine {
|
|
|
112
113
|
deadlineAt: number,
|
|
113
114
|
report: (event: SearchStepEvent, detail?: string, metrics?: SearchStepMetrics) => void,
|
|
114
115
|
): Promise<{ results: readonly SearchResult[]; pagesRead: number }> {
|
|
115
|
-
const targets = results
|
|
116
|
+
const targets = results
|
|
117
|
+
.filter((result) => result.content === null && (options.isContentUrlAllowed?.(result.url) ?? true))
|
|
118
|
+
.slice(0, policy.content.maxPages)
|
|
116
119
|
if (targets.length === 0) return { results, pagesRead: 0 }
|
|
117
120
|
report('started', `reading ${targets.length} page(s) for inline content`)
|
|
118
121
|
|
|
119
|
-
const contentByUrl = new Map<string,
|
|
122
|
+
const contentByUrl = new Map<string, FetchedPage>()
|
|
120
123
|
// Counts pages we actually went to the network for, not pages that yielded
|
|
121
124
|
// usable text: the budget this feeds is about egress, and a fetch that came
|
|
122
125
|
// back empty still cost a request to somebody else's server.
|
|
@@ -135,7 +138,7 @@ export function createSearchEngine(options: SearchEngineOptions): SearchEngine {
|
|
|
135
138
|
{ signal },
|
|
136
139
|
)
|
|
137
140
|
if (outcome.status === 'ok' && outcome.page.text.trim().length > 0) {
|
|
138
|
-
contentByUrl.set(next.url, outcome.page
|
|
141
|
+
contentByUrl.set(next.url, outcome.page)
|
|
139
142
|
}
|
|
140
143
|
}
|
|
141
144
|
})
|
|
@@ -147,8 +150,8 @@ export function createSearchEngine(options: SearchEngineOptions): SearchEngine {
|
|
|
147
150
|
|
|
148
151
|
return {
|
|
149
152
|
results: results.map((result) => {
|
|
150
|
-
const
|
|
151
|
-
return
|
|
153
|
+
const page = contentByUrl.get(result.url)
|
|
154
|
+
return page === undefined ? result : { ...result, url: page.url, content: page.text }
|
|
152
155
|
}),
|
|
153
156
|
pagesRead,
|
|
154
157
|
}
|
|
@@ -157,6 +160,17 @@ export function createSearchEngine(options: SearchEngineOptions): SearchEngine {
|
|
|
157
160
|
async function fetchPage(request: FetchRequest, runOptions: RunOptions = {}): Promise<FetchOutcome> {
|
|
158
161
|
const maxBytes = request.maxBytes ?? policy.content.maxBytesPerPage
|
|
159
162
|
const render = request.render ?? 'auto'
|
|
163
|
+
let policyDenied = false
|
|
164
|
+
const assertUrlAllowed = (url: string): void => {
|
|
165
|
+
if (options.isContentUrlAllowed && !options.isContentUrlAllowed(url)) {
|
|
166
|
+
policyDenied = true
|
|
167
|
+
throw new WebResearchError('blocked', `domain not allowed: ${url}`)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (options.isContentUrlAllowed && !options.isContentUrlAllowed(request.url)) {
|
|
172
|
+
return { status: 'blocked', reason: `domain not allowed: ${request.url}`, code: 'domain_blocked' }
|
|
173
|
+
}
|
|
160
174
|
|
|
161
175
|
if (render !== 'always') {
|
|
162
176
|
try {
|
|
@@ -164,7 +178,9 @@ export function createSearchEngine(options: SearchEngineOptions): SearchEngine {
|
|
|
164
178
|
maxBytes,
|
|
165
179
|
accept: TEXTUAL_CONTENT,
|
|
166
180
|
...(runOptions.signal ? { signal: runOptions.signal } : {}),
|
|
181
|
+
...(options.isContentUrlAllowed ? { assertUrlAllowed } : {}),
|
|
167
182
|
})
|
|
183
|
+
assertUrlAllowed(response.url)
|
|
168
184
|
const isHtml = response.contentType === null || response.contentType.includes('html')
|
|
169
185
|
const text = isHtml ? extractMainContent(response.body) || htmlToText(response.body) : response.body
|
|
170
186
|
const classification = classifyPage({
|
|
@@ -191,7 +207,8 @@ export function createSearchEngine(options: SearchEngineOptions): SearchEngine {
|
|
|
191
207
|
return { status: 'ok', page: { ...page, escalatedBecause: classification.verdict } }
|
|
192
208
|
} catch (error) {
|
|
193
209
|
const failure = toOutcomeFailure(error)
|
|
194
|
-
if (
|
|
210
|
+
if (policyDenied && failure.status === 'blocked') return { ...failure, code: 'domain_blocked' }
|
|
211
|
+
if (!policyDenied && render !== 'never' && failure.status === 'blocked') {
|
|
195
212
|
const escalated = await escalateFetch(request, 'blocked', maxBytes, runOptions)
|
|
196
213
|
if (escalated?.status === 'ok') return escalated
|
|
197
214
|
}
|
|
@@ -251,6 +268,7 @@ export function createSearchEngine(options: SearchEngineOptions): SearchEngine {
|
|
|
251
268
|
maxBytes: number,
|
|
252
269
|
runOptions: RunOptions,
|
|
253
270
|
): Promise<FetchOutcome | null> {
|
|
271
|
+
if (options.isContentUrlAllowed) return blocked('browser rendering cannot enforce content URL policy')
|
|
254
272
|
if (!policy.escalateToBrowser) return null
|
|
255
273
|
const entry = browserEntries.find(
|
|
256
274
|
(candidate) =>
|
|
@@ -535,7 +553,8 @@ export function createSearchEngine(options: SearchEngineOptions): SearchEngine {
|
|
|
535
553
|
// A comparison is a diagnostic: serving it from cache would show an operator
|
|
536
554
|
// yesterday's adapter behaviour while they change settings, and storing it
|
|
537
555
|
// would put every adapter's full result list in the cache for one debug run.
|
|
538
|
-
const useCache =
|
|
556
|
+
const useCache =
|
|
557
|
+
options.cache !== undefined && policy.cacheTtlMs > 0 && !compare && options.isContentUrlAllowed === undefined
|
|
539
558
|
|
|
540
559
|
if (useCache) {
|
|
541
560
|
const cached = await options.cache!.get(cacheKey).catch(() => null)
|
package/src/engine/types.ts
CHANGED
|
@@ -87,6 +87,7 @@ export type SearchEngineOptions = {
|
|
|
87
87
|
readonly policy: SearchPolicy
|
|
88
88
|
readonly adapters: readonly EngineAdapterEntry[]
|
|
89
89
|
readonly http: HttpClient
|
|
90
|
+
readonly isContentUrlAllowed?: (url: string) => boolean
|
|
90
91
|
readonly logger?: Logger
|
|
91
92
|
readonly cache?: ResultCache<SearchEngineResult>
|
|
92
93
|
readonly onStep?: StepSink
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
|
|
2
2
|
import type { AddressInfo } from 'node:net'
|
|
3
|
-
import { isWebResearchError } from '../../contract/errors'
|
|
3
|
+
import { isWebResearchError, WebResearchError } from '../../contract/errors'
|
|
4
4
|
import { createHttpClient } from '../client'
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -67,6 +67,138 @@ describe('http client against a real server', () => {
|
|
|
67
67
|
expect(response.url).toBe(`${origin}/page`)
|
|
68
68
|
})
|
|
69
69
|
|
|
70
|
+
it('checks caller URL policy before initial DNS resolution or socket egress', async () => {
|
|
71
|
+
const received = jest.fn((_req: IncomingMessage, res: ServerResponse) => res.end('denied content'))
|
|
72
|
+
const { port } = track(await listen(received))
|
|
73
|
+
const lookup = jest.fn(async () => [{ address: '127.0.0.1', family: 4 }])
|
|
74
|
+
const http = createHttpClient({ lookup, allowPrivateHosts: ['denied.test'] })
|
|
75
|
+
|
|
76
|
+
await expect(
|
|
77
|
+
http.request(`http://denied.test:${port}/admin`, {
|
|
78
|
+
assertUrlAllowed: () => {
|
|
79
|
+
throw new WebResearchError('blocked', 'domain not allowed')
|
|
80
|
+
},
|
|
81
|
+
}),
|
|
82
|
+
).rejects.toMatchObject({ code: 'blocked' })
|
|
83
|
+
|
|
84
|
+
expect(lookup).not.toHaveBeenCalled()
|
|
85
|
+
expect(received).not.toHaveBeenCalled()
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('checks caller URL policy on redirects before contacting a permitted private host', async () => {
|
|
89
|
+
const received: string[] = []
|
|
90
|
+
const { port } = track(
|
|
91
|
+
await listen((req, res) => {
|
|
92
|
+
received.push(`${req.headers.host}${req.url}`)
|
|
93
|
+
res.writeHead(302, { location: `http://denied.test:${port}/admin` })
|
|
94
|
+
res.end()
|
|
95
|
+
}),
|
|
96
|
+
)
|
|
97
|
+
const lookup = jest.fn(async () => [{ address: '127.0.0.1', family: 4 }])
|
|
98
|
+
const http = createHttpClient({ lookup, allowPrivateHosts: ['allowed.test', 'denied.test'] })
|
|
99
|
+
|
|
100
|
+
await expect(
|
|
101
|
+
http.request(`http://allowed.test:${port}/start`, {
|
|
102
|
+
assertUrlAllowed: (url) => {
|
|
103
|
+
if (new URL(url).hostname === 'denied.test') {
|
|
104
|
+
throw new WebResearchError('blocked', 'domain not allowed')
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
}),
|
|
108
|
+
).rejects.toMatchObject({ code: 'blocked' })
|
|
109
|
+
|
|
110
|
+
expect(lookup.mock.calls).toEqual([['allowed.test']])
|
|
111
|
+
expect(received).toEqual([`allowed.test:${port}/start`])
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
it.each(['initial request', 'redirect'])(
|
|
115
|
+
'awaits asynchronous authorization before %s DNS resolution or socket egress',
|
|
116
|
+
async (stage) => {
|
|
117
|
+
const received: string[] = []
|
|
118
|
+
const { port } = track(
|
|
119
|
+
await listen((req, res) => {
|
|
120
|
+
received.push(`${req.headers.host}${req.url}`)
|
|
121
|
+
if (req.url === '/start') {
|
|
122
|
+
res.writeHead(302, { location: `http://denied.test:${port}/admin` })
|
|
123
|
+
}
|
|
124
|
+
res.end('denied content')
|
|
125
|
+
}),
|
|
126
|
+
)
|
|
127
|
+
const lookup = jest.fn(async () => [{ address: '127.0.0.1', family: 4 }])
|
|
128
|
+
const http = createHttpClient({ lookup, allowPrivateHosts: ['allowed.test', 'denied.test'] })
|
|
129
|
+
const authorization = Promise.withResolvers<void>()
|
|
130
|
+
const authorizationStarted = Promise.withResolvers<void>()
|
|
131
|
+
const initialUrl = stage === 'redirect' ? `http://allowed.test:${port}/start` : `http://denied.test:${port}/admin`
|
|
132
|
+
const response = http.request(initialUrl, {
|
|
133
|
+
assertUrlAllowed: (url) => {
|
|
134
|
+
if (new URL(url).hostname !== 'denied.test') return
|
|
135
|
+
authorizationStarted.resolve()
|
|
136
|
+
return authorization.promise
|
|
137
|
+
},
|
|
138
|
+
})
|
|
139
|
+
const rejection = expect(response).rejects.toMatchObject({ code: 'blocked' })
|
|
140
|
+
|
|
141
|
+
await authorizationStarted.promise
|
|
142
|
+
|
|
143
|
+
expect(lookup.mock.calls).toEqual(stage === 'redirect' ? [['allowed.test']] : [])
|
|
144
|
+
expect(received).toEqual(stage === 'redirect' ? [`allowed.test:${port}/start`] : [])
|
|
145
|
+
|
|
146
|
+
authorization.reject(new WebResearchError('blocked', 'domain not allowed'))
|
|
147
|
+
await rejection
|
|
148
|
+
|
|
149
|
+
expect(lookup.mock.calls).toEqual(stage === 'redirect' ? [['allowed.test']] : [])
|
|
150
|
+
expect(received).toEqual(stage === 'redirect' ? [`allowed.test:${port}/start`] : [])
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
it('preserves permitted redirects and reports their final URL', async () => {
|
|
155
|
+
const { origin } = track(
|
|
156
|
+
await listen((req, res) => {
|
|
157
|
+
if (req.url === '/start') {
|
|
158
|
+
res.writeHead(302, { location: '/final' })
|
|
159
|
+
res.end()
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
res.writeHead(200, { 'content-type': 'text/plain' })
|
|
163
|
+
res.end('permitted content')
|
|
164
|
+
}),
|
|
165
|
+
)
|
|
166
|
+
const assertUrlAllowed = jest.fn(async () => {})
|
|
167
|
+
|
|
168
|
+
const response = await client().request(`${origin}/start`, { assertUrlAllowed })
|
|
169
|
+
|
|
170
|
+
expect(assertUrlAllowed.mock.calls).toEqual([[`${origin}/start`], [`${origin}/final`]])
|
|
171
|
+
expect(response).toMatchObject({ url: `${origin}/final`, body: 'permitted content' })
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
it('keeps SSRF protection active when caller policy allows a URL', async () => {
|
|
175
|
+
const received = jest.fn((_req: IncomingMessage, res: ServerResponse) => res.end('private content'))
|
|
176
|
+
const { origin } = track(await listen(received))
|
|
177
|
+
const assertUrlAllowed = jest.fn()
|
|
178
|
+
|
|
179
|
+
await expect(createHttpClient().request(origin, { assertUrlAllowed })).rejects.toMatchObject({
|
|
180
|
+
code: 'ssrf_blocked',
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
expect(assertUrlAllowed).toHaveBeenCalledWith(origin)
|
|
184
|
+
expect(received).not.toHaveBeenCalled()
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
it('does not apply one request policy to adapter service requests on the same client', async () => {
|
|
188
|
+
const { origin } = track(await listen((_req, res) => res.end('adapter response')))
|
|
189
|
+
const http = client()
|
|
190
|
+
|
|
191
|
+
await expect(
|
|
192
|
+
http.request(origin, {
|
|
193
|
+
assertUrlAllowed: () => {
|
|
194
|
+
throw new WebResearchError('blocked', 'domain not allowed')
|
|
195
|
+
},
|
|
196
|
+
}),
|
|
197
|
+
).rejects.toMatchObject({ code: 'blocked' })
|
|
198
|
+
|
|
199
|
+
await expect(http.request(origin)).resolves.toMatchObject({ body: 'adapter response' })
|
|
200
|
+
})
|
|
201
|
+
|
|
70
202
|
it('keeps caller headers on a same-origin redirect', async () => {
|
|
71
203
|
const seen: Array<string | undefined> = []
|
|
72
204
|
const { origin } = track(
|
|
@@ -120,11 +252,50 @@ describe('http client against a real server', () => {
|
|
|
120
252
|
res.end()
|
|
121
253
|
}),
|
|
122
254
|
)
|
|
255
|
+
const assertUrlAllowed = jest.fn()
|
|
123
256
|
|
|
124
257
|
// The allowlist named 127.0.0.1 only, so the metadata endpoint is still refused.
|
|
125
|
-
await expect(client().request(`${origin}/start
|
|
258
|
+
await expect(client().request(`${origin}/start`, { assertUrlAllowed })).rejects.toMatchObject({
|
|
259
|
+
code: 'ssrf_blocked',
|
|
260
|
+
})
|
|
261
|
+
expect(assertUrlAllowed.mock.calls).toEqual([
|
|
262
|
+
[`${origin}/start`],
|
|
263
|
+
['http://169.254.169.254/latest/meta-data/'],
|
|
264
|
+
])
|
|
126
265
|
})
|
|
127
266
|
|
|
267
|
+
it.each(['64:ff9b:1::a00:1', '2002:a00:1::1'])(
|
|
268
|
+
'rejects a redirect to the non-public IPv6 literal %s',
|
|
269
|
+
async (address) => {
|
|
270
|
+
const { origin } = track(
|
|
271
|
+
await listen((_req, res) => {
|
|
272
|
+
res.writeHead(302, { location: `http://[${address}]/secret` })
|
|
273
|
+
res.end()
|
|
274
|
+
}),
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
await expect(client().request(`${origin}/start`)).rejects.toMatchObject({ code: 'ssrf_blocked' })
|
|
278
|
+
},
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
it.each(['64:ff9b:1::a00:1', '2002:a00:1::1'])(
|
|
282
|
+
'rejects a redirect whose DNS answer contains %s',
|
|
283
|
+
async (address) => {
|
|
284
|
+
const { origin } = track(
|
|
285
|
+
await listen((_req, res) => {
|
|
286
|
+
res.writeHead(302, { location: 'http://translated.example.com/secret' })
|
|
287
|
+
res.end()
|
|
288
|
+
}),
|
|
289
|
+
)
|
|
290
|
+
const lookup = jest.fn(async () => [{ address, family: 6 }])
|
|
291
|
+
|
|
292
|
+
await expect(client({ lookup }).request(`${origin}/start`)).rejects.toMatchObject({
|
|
293
|
+
code: 'ssrf_blocked',
|
|
294
|
+
})
|
|
295
|
+
expect(lookup).toHaveBeenCalledWith('translated.example.com')
|
|
296
|
+
},
|
|
297
|
+
)
|
|
298
|
+
|
|
128
299
|
it('stops after the redirect limit instead of looping', async () => {
|
|
129
300
|
const { origin } = track(
|
|
130
301
|
await listen((_req, res) => {
|