Spaces:
Running
Running
Sync from felladrin/MiniSearch@757fca5 (part 2)
Browse files- package-lock.json +51 -51
- server/biEncoderService.test.ts +125 -0
- server/biEncoderService.ts +34 -5
- server/cacheServerHook.test.ts +65 -0
- server/cacheServerHook.ts +20 -1
- server/configEndpointServerHook.test.ts +48 -0
- server/configEndpointServerHook.ts +3 -1
- server/dynamicCacheHeaders.test.ts +152 -0
- server/fallbackSearchService.test.ts +108 -1
- server/fallbackSearchService.ts +93 -11
- server/internalApiEndpointServerHook.test.ts +55 -3
- server/internalApiEndpointServerHook.ts +14 -7
- server/outboundUserAgent.ts +11 -0
- server/pageContentEndpointServerHook.test.ts +28 -0
- server/pageContentEndpointServerHook.ts +9 -2
- server/pageContentService.test.ts +63 -0
- server/pageContentService.ts +20 -7
- server/parseCommaSeparatedList.test.ts +26 -0
- server/parseCommaSeparatedList.ts +11 -0
- server/searchEndpointServerHook.test.ts +22 -0
- server/searchEndpointServerHook.ts +9 -5
- server/statusEndpointServerHook.test.ts +81 -1
- server/statusEndpointServerHook.ts +12 -1
- server/thumbnailEndpointServerHook.test.ts +112 -3
- server/thumbnailEndpointServerHook.ts +37 -38
- server/utils/pinnedFetch.test.ts +7 -1
- server/utils/pinnedFetch.ts +5 -2
- server/utils/publicUrl.ts +34 -0
- server/utils/requestUrl.test.ts +51 -0
- server/utils/requestUrl.ts +39 -0
- server/utils/streamUtils.test.ts +111 -0
- server/utils/streamUtils.ts +20 -17
- server/validateAccessKeyServerHook.test.ts +52 -0
- server/validateAccessKeyServerHook.ts +4 -1
- server/viteConfigAllowedHosts.test.ts +34 -0
- shared/relativeDates.test.ts +264 -0
- shared/relativeDates.ts +165 -51
- vite.config.ts +4 -4
package-lock.json
CHANGED
|
@@ -96,13 +96,13 @@
|
|
| 96 |
"license": "MIT"
|
| 97 |
},
|
| 98 |
"node_modules/@ai-sdk/gateway": {
|
| 99 |
-
"version": "4.0.
|
| 100 |
-
"resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.
|
| 101 |
-
"integrity": "sha512-
|
| 102 |
"license": "Apache-2.0",
|
| 103 |
"dependencies": {
|
| 104 |
"@ai-sdk/provider": "4.0.39",
|
| 105 |
-
"@ai-sdk/provider-utils": "5.0.
|
| 106 |
"@vercel/oidc": "3.2.0"
|
| 107 |
},
|
| 108 |
"engines": {
|
|
@@ -113,13 +113,13 @@
|
|
| 113 |
}
|
| 114 |
},
|
| 115 |
"node_modules/@ai-sdk/openai-compatible": {
|
| 116 |
-
"version": "3.0.
|
| 117 |
-
"resolved": "https://registry.npmjs.org/@ai-sdk/openai-compatible/-/openai-compatible-3.0.
|
| 118 |
-
"integrity": "sha512-
|
| 119 |
"license": "Apache-2.0",
|
| 120 |
"dependencies": {
|
| 121 |
"@ai-sdk/provider": "4.0.39",
|
| 122 |
-
"@ai-sdk/provider-utils": "5.0.
|
| 123 |
},
|
| 124 |
"engines": {
|
| 125 |
"node": ">=22"
|
|
@@ -129,9 +129,9 @@
|
|
| 129 |
}
|
| 130 |
},
|
| 131 |
"node_modules/@ai-sdk/openai-compatible/node_modules/@ai-sdk/provider-utils": {
|
| 132 |
-
"version": "5.0.
|
| 133 |
-
"resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.
|
| 134 |
-
"integrity": "sha512-
|
| 135 |
"license": "Apache-2.0",
|
| 136 |
"dependencies": {
|
| 137 |
"@ai-sdk/provider": "4.0.39",
|
|
@@ -159,9 +159,9 @@
|
|
| 159 |
}
|
| 160 |
},
|
| 161 |
"node_modules/@ai-sdk/provider-utils": {
|
| 162 |
-
"version": "5.0.
|
| 163 |
-
"resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.
|
| 164 |
-
"integrity": "sha512-
|
| 165 |
"license": "Apache-2.0",
|
| 166 |
"dependencies": {
|
| 167 |
"@ai-sdk/provider": "4.0.39",
|
|
@@ -644,13 +644,13 @@
|
|
| 644 |
"license": "MIT"
|
| 645 |
},
|
| 646 |
"node_modules/@mantine/carousel": {
|
| 647 |
-
"version": "9.8.
|
| 648 |
-
"resolved": "https://registry.npmjs.org/@mantine/carousel/-/carousel-9.8.
|
| 649 |
-
"integrity": "sha512-
|
| 650 |
"license": "MIT",
|
| 651 |
"peerDependencies": {
|
| 652 |
-
"@mantine/core": "9.8.
|
| 653 |
-
"@mantine/hooks": "9.8.
|
| 654 |
"embla-carousel": ">=8.0.0",
|
| 655 |
"embla-carousel-react": ">=8.0.0",
|
| 656 |
"react": "^19.2.0",
|
|
@@ -658,25 +658,25 @@
|
|
| 658 |
}
|
| 659 |
},
|
| 660 |
"node_modules/@mantine/code-highlight": {
|
| 661 |
-
"version": "9.8.
|
| 662 |
-
"resolved": "https://registry.npmjs.org/@mantine/code-highlight/-/code-highlight-9.8.
|
| 663 |
-
"integrity": "sha512-
|
| 664 |
"license": "MIT",
|
| 665 |
"dependencies": {
|
| 666 |
"clsx": "^2.1.1",
|
| 667 |
"diff": "^9.0.0"
|
| 668 |
},
|
| 669 |
"peerDependencies": {
|
| 670 |
-
"@mantine/core": "9.8.
|
| 671 |
-
"@mantine/hooks": "9.8.
|
| 672 |
"react": "^19.2.0",
|
| 673 |
"react-dom": "^19.2.0"
|
| 674 |
}
|
| 675 |
},
|
| 676 |
"node_modules/@mantine/core": {
|
| 677 |
-
"version": "9.8.
|
| 678 |
-
"resolved": "https://registry.npmjs.org/@mantine/core/-/core-9.8.
|
| 679 |
-
"integrity": "sha512-+
|
| 680 |
"license": "MIT",
|
| 681 |
"dependencies": {
|
| 682 |
"@floating-ui/react": "^0.27.20",
|
|
@@ -686,15 +686,15 @@
|
|
| 686 |
"type-fest": "^5.10.0"
|
| 687 |
},
|
| 688 |
"peerDependencies": {
|
| 689 |
-
"@mantine/hooks": "9.8.
|
| 690 |
"react": "^19.2.0",
|
| 691 |
"react-dom": "^19.2.0"
|
| 692 |
}
|
| 693 |
},
|
| 694 |
"node_modules/@mantine/form": {
|
| 695 |
-
"version": "9.8.
|
| 696 |
-
"resolved": "https://registry.npmjs.org/@mantine/form/-/form-9.8.
|
| 697 |
-
"integrity": "sha512-
|
| 698 |
"license": "MIT",
|
| 699 |
"dependencies": {
|
| 700 |
"@standard-schema/spec": "^1.1.0",
|
|
@@ -706,34 +706,34 @@
|
|
| 706 |
}
|
| 707 |
},
|
| 708 |
"node_modules/@mantine/hooks": {
|
| 709 |
-
"version": "9.8.
|
| 710 |
-
"resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.8.
|
| 711 |
-
"integrity": "sha512-
|
| 712 |
"license": "MIT",
|
| 713 |
"peerDependencies": {
|
| 714 |
"react": "^19.2.0"
|
| 715 |
}
|
| 716 |
},
|
| 717 |
"node_modules/@mantine/notifications": {
|
| 718 |
-
"version": "9.8.
|
| 719 |
-
"resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.8.
|
| 720 |
-
"integrity": "sha512-
|
| 721 |
"license": "MIT",
|
| 722 |
"dependencies": {
|
| 723 |
-
"@mantine/store": "9.8.
|
| 724 |
"react-transition-group": "4.4.5"
|
| 725 |
},
|
| 726 |
"peerDependencies": {
|
| 727 |
-
"@mantine/core": "9.8.
|
| 728 |
-
"@mantine/hooks": "9.8.
|
| 729 |
"react": "^19.2.0",
|
| 730 |
"react-dom": "^19.2.0"
|
| 731 |
}
|
| 732 |
},
|
| 733 |
"node_modules/@mantine/store": {
|
| 734 |
-
"version": "9.8.
|
| 735 |
-
"resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.8.
|
| 736 |
-
"integrity": "sha512-
|
| 737 |
"license": "MIT",
|
| 738 |
"peerDependencies": {
|
| 739 |
"react": "^19.2.0"
|
|
@@ -2839,14 +2839,14 @@
|
|
| 2839 |
}
|
| 2840 |
},
|
| 2841 |
"node_modules/ai": {
|
| 2842 |
-
"version": "7.0.
|
| 2843 |
-
"resolved": "https://registry.npmjs.org/ai/-/ai-7.0.
|
| 2844 |
-
"integrity": "sha512-
|
| 2845 |
"license": "Apache-2.0",
|
| 2846 |
"dependencies": {
|
| 2847 |
-
"@ai-sdk/gateway": "4.0.
|
| 2848 |
"@ai-sdk/provider": "4.0.39",
|
| 2849 |
-
"@ai-sdk/provider-utils": "5.0.
|
| 2850 |
},
|
| 2851 |
"engines": {
|
| 2852 |
"node": ">=22"
|
|
@@ -4507,9 +4507,9 @@
|
|
| 4507 |
}
|
| 4508 |
},
|
| 4509 |
"node_modules/knip": {
|
| 4510 |
-
"version": "6.
|
| 4511 |
-
"resolved": "https://registry.npmjs.org/knip/-/knip-6.
|
| 4512 |
-
"integrity": "sha512-
|
| 4513 |
"dev": true,
|
| 4514 |
"funding": [
|
| 4515 |
{
|
|
|
|
| 96 |
"license": "MIT"
|
| 97 |
},
|
| 98 |
"node_modules/@ai-sdk/gateway": {
|
| 99 |
+
"version": "4.0.152",
|
| 100 |
+
"resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.152.tgz",
|
| 101 |
+
"integrity": "sha512-8LYMe0uMPbT3XW/Urhca52TSgHXAlQok74EUkWL3qXWJI7naTxJGSF6B7hvIHur+V6ttSyLLZN0rJk+Qu9psqA==",
|
| 102 |
"license": "Apache-2.0",
|
| 103 |
"dependencies": {
|
| 104 |
"@ai-sdk/provider": "4.0.39",
|
| 105 |
+
"@ai-sdk/provider-utils": "5.0.83",
|
| 106 |
"@vercel/oidc": "3.2.0"
|
| 107 |
},
|
| 108 |
"engines": {
|
|
|
|
| 113 |
}
|
| 114 |
},
|
| 115 |
"node_modules/@ai-sdk/openai-compatible": {
|
| 116 |
+
"version": "3.0.94",
|
| 117 |
+
"resolved": "https://registry.npmjs.org/@ai-sdk/openai-compatible/-/openai-compatible-3.0.94.tgz",
|
| 118 |
+
"integrity": "sha512-UY2AE3/QT110AMpiBoBOBXlUJJG8NAL61y8yID6X8dPe9RjRy9QPfW9XdrifEnTOEM5MdEJP+A4Mf+NTJ93g4A==",
|
| 119 |
"license": "Apache-2.0",
|
| 120 |
"dependencies": {
|
| 121 |
"@ai-sdk/provider": "4.0.39",
|
| 122 |
+
"@ai-sdk/provider-utils": "5.0.83"
|
| 123 |
},
|
| 124 |
"engines": {
|
| 125 |
"node": ">=22"
|
|
|
|
| 129 |
}
|
| 130 |
},
|
| 131 |
"node_modules/@ai-sdk/openai-compatible/node_modules/@ai-sdk/provider-utils": {
|
| 132 |
+
"version": "5.0.83",
|
| 133 |
+
"resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.83.tgz",
|
| 134 |
+
"integrity": "sha512-5lInsmNnh64eKi2L3fQjPy5VnV2y69lwyGnZ3vfz82Tlkgy8pWsvYueUrSJGxi8gXOM67jB9tN7LtDjjEFsNLQ==",
|
| 135 |
"license": "Apache-2.0",
|
| 136 |
"dependencies": {
|
| 137 |
"@ai-sdk/provider": "4.0.39",
|
|
|
|
| 159 |
}
|
| 160 |
},
|
| 161 |
"node_modules/@ai-sdk/provider-utils": {
|
| 162 |
+
"version": "5.0.83",
|
| 163 |
+
"resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.83.tgz",
|
| 164 |
+
"integrity": "sha512-5lInsmNnh64eKi2L3fQjPy5VnV2y69lwyGnZ3vfz82Tlkgy8pWsvYueUrSJGxi8gXOM67jB9tN7LtDjjEFsNLQ==",
|
| 165 |
"license": "Apache-2.0",
|
| 166 |
"dependencies": {
|
| 167 |
"@ai-sdk/provider": "4.0.39",
|
|
|
|
| 644 |
"license": "MIT"
|
| 645 |
},
|
| 646 |
"node_modules/@mantine/carousel": {
|
| 647 |
+
"version": "9.8.2",
|
| 648 |
+
"resolved": "https://registry.npmjs.org/@mantine/carousel/-/carousel-9.8.2.tgz",
|
| 649 |
+
"integrity": "sha512-bN5e+mwxYquyMEfU7CP/tnhpP7mls0wmMYIroaFJOZpQyWiGRfezSqGkGqPV0cDnwn+9yn4rG77obU6yAHW32g==",
|
| 650 |
"license": "MIT",
|
| 651 |
"peerDependencies": {
|
| 652 |
+
"@mantine/core": "9.8.2",
|
| 653 |
+
"@mantine/hooks": "9.8.2",
|
| 654 |
"embla-carousel": ">=8.0.0",
|
| 655 |
"embla-carousel-react": ">=8.0.0",
|
| 656 |
"react": "^19.2.0",
|
|
|
|
| 658 |
}
|
| 659 |
},
|
| 660 |
"node_modules/@mantine/code-highlight": {
|
| 661 |
+
"version": "9.8.2",
|
| 662 |
+
"resolved": "https://registry.npmjs.org/@mantine/code-highlight/-/code-highlight-9.8.2.tgz",
|
| 663 |
+
"integrity": "sha512-L+69TylIuDw5T45DQWTnC/JbOckpyl5JFtdPjSVTrgTS3LLCAsQk+BVF2fZXhKG2/YrxlV7LYvTR1gJXrNpowA==",
|
| 664 |
"license": "MIT",
|
| 665 |
"dependencies": {
|
| 666 |
"clsx": "^2.1.1",
|
| 667 |
"diff": "^9.0.0"
|
| 668 |
},
|
| 669 |
"peerDependencies": {
|
| 670 |
+
"@mantine/core": "9.8.2",
|
| 671 |
+
"@mantine/hooks": "9.8.2",
|
| 672 |
"react": "^19.2.0",
|
| 673 |
"react-dom": "^19.2.0"
|
| 674 |
}
|
| 675 |
},
|
| 676 |
"node_modules/@mantine/core": {
|
| 677 |
+
"version": "9.8.2",
|
| 678 |
+
"resolved": "https://registry.npmjs.org/@mantine/core/-/core-9.8.2.tgz",
|
| 679 |
+
"integrity": "sha512-PEBlIr5A80Indc8mIp+JcMzmmtv2YioubzXsLossk4cDhgm3YX2DBFQi/hQknmOaU6wt9h8l4T8s4gh6WPM21Q==",
|
| 680 |
"license": "MIT",
|
| 681 |
"dependencies": {
|
| 682 |
"@floating-ui/react": "^0.27.20",
|
|
|
|
| 686 |
"type-fest": "^5.10.0"
|
| 687 |
},
|
| 688 |
"peerDependencies": {
|
| 689 |
+
"@mantine/hooks": "9.8.2",
|
| 690 |
"react": "^19.2.0",
|
| 691 |
"react-dom": "^19.2.0"
|
| 692 |
}
|
| 693 |
},
|
| 694 |
"node_modules/@mantine/form": {
|
| 695 |
+
"version": "9.8.2",
|
| 696 |
+
"resolved": "https://registry.npmjs.org/@mantine/form/-/form-9.8.2.tgz",
|
| 697 |
+
"integrity": "sha512-+wMxQ5NwSUt/WTc5dNI1J/c9WIF3jGRv8yu9SpzVFscmFGMAXhoquaHIOGM4gnF8JpM4bMQ5KukH45T+o9o6mA==",
|
| 698 |
"license": "MIT",
|
| 699 |
"dependencies": {
|
| 700 |
"@standard-schema/spec": "^1.1.0",
|
|
|
|
| 706 |
}
|
| 707 |
},
|
| 708 |
"node_modules/@mantine/hooks": {
|
| 709 |
+
"version": "9.8.2",
|
| 710 |
+
"resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-9.8.2.tgz",
|
| 711 |
+
"integrity": "sha512-BZa+6fLEvAxaos2qInPZfNzq0k1WSIIkHA3CdD4quozJhmp7Kt1KE05YAkVPNrPisCx3c5YgmkRqtu9NcRegCw==",
|
| 712 |
"license": "MIT",
|
| 713 |
"peerDependencies": {
|
| 714 |
"react": "^19.2.0"
|
| 715 |
}
|
| 716 |
},
|
| 717 |
"node_modules/@mantine/notifications": {
|
| 718 |
+
"version": "9.8.2",
|
| 719 |
+
"resolved": "https://registry.npmjs.org/@mantine/notifications/-/notifications-9.8.2.tgz",
|
| 720 |
+
"integrity": "sha512-kKhT1jEl6sadOvB7efMJZuWfSRiyCDrAzWw0u4oaCKfOlAgrSo8wooIQ9gIgWct6jejdzIUK8ovBOVeLLx/dnA==",
|
| 721 |
"license": "MIT",
|
| 722 |
"dependencies": {
|
| 723 |
+
"@mantine/store": "9.8.2",
|
| 724 |
"react-transition-group": "4.4.5"
|
| 725 |
},
|
| 726 |
"peerDependencies": {
|
| 727 |
+
"@mantine/core": "9.8.2",
|
| 728 |
+
"@mantine/hooks": "9.8.2",
|
| 729 |
"react": "^19.2.0",
|
| 730 |
"react-dom": "^19.2.0"
|
| 731 |
}
|
| 732 |
},
|
| 733 |
"node_modules/@mantine/store": {
|
| 734 |
+
"version": "9.8.2",
|
| 735 |
+
"resolved": "https://registry.npmjs.org/@mantine/store/-/store-9.8.2.tgz",
|
| 736 |
+
"integrity": "sha512-22kVzhs231cpcXdsKcQlRrmpzkbEMdJ7C+YKOVUBk5sUiP6bSAu4XY4Avj23Yjxy949G7Y4X4eAVSzjPgSUURA==",
|
| 737 |
"license": "MIT",
|
| 738 |
"peerDependencies": {
|
| 739 |
"react": "^19.2.0"
|
|
|
|
| 2839 |
}
|
| 2840 |
},
|
| 2841 |
"node_modules/ai": {
|
| 2842 |
+
"version": "7.0.179",
|
| 2843 |
+
"resolved": "https://registry.npmjs.org/ai/-/ai-7.0.179.tgz",
|
| 2844 |
+
"integrity": "sha512-WT2ad3qEQPLne/5RDE/utNMSKYUuNpnGkI46AO/6Lv+IbEJ3kRwbatLX3HNfk25Y7N8LpdqOcSnMLcdw11VyIQ==",
|
| 2845 |
"license": "Apache-2.0",
|
| 2846 |
"dependencies": {
|
| 2847 |
+
"@ai-sdk/gateway": "4.0.152",
|
| 2848 |
"@ai-sdk/provider": "4.0.39",
|
| 2849 |
+
"@ai-sdk/provider-utils": "5.0.83"
|
| 2850 |
},
|
| 2851 |
"engines": {
|
| 2852 |
"node": ">=22"
|
|
|
|
| 4507 |
}
|
| 4508 |
},
|
| 4509 |
"node_modules/knip": {
|
| 4510 |
+
"version": "6.47.0",
|
| 4511 |
+
"resolved": "https://registry.npmjs.org/knip/-/knip-6.47.0.tgz",
|
| 4512 |
+
"integrity": "sha512-nYmQnk0YqDXIJrYViJz88c8xw3tBDkpuAmofo58EkVPnKr6DnRKYtf6oIqcGVHZvXDE+gtmFuYx277/QsWng+A==",
|
| 4513 |
"dev": true,
|
| 4514 |
"funding": [
|
| 4515 |
{
|
server/biEncoderService.test.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
| 2 |
+
import {
|
| 3 |
+
SCORE_TIMEOUT_MS,
|
| 4 |
+
scorePassages,
|
| 5 |
+
startBiEncoderService,
|
| 6 |
+
stopBiEncoderService,
|
| 7 |
+
} from "./biEncoderService";
|
| 8 |
+
import type { BiEncoderRequest } from "./biEncoderWorkerProtocol";
|
| 9 |
+
|
| 10 |
+
const { FakeWorker } = await vi.hoisted(async () => {
|
| 11 |
+
const { EventEmitter } = await import("node:events");
|
| 12 |
+
|
| 13 |
+
/**
|
| 14 |
+
* Stands in for the worker thread: it reports nothing on its own, so each
|
| 15 |
+
* test decides whether a request gets a reply, a late reply or none at all.
|
| 16 |
+
*/
|
| 17 |
+
class FakeWorker extends EventEmitter {
|
| 18 |
+
static latest: FakeWorker;
|
| 19 |
+
readonly requests: BiEncoderRequest[] = [];
|
| 20 |
+
|
| 21 |
+
constructor() {
|
| 22 |
+
super();
|
| 23 |
+
FakeWorker.latest = this;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
postMessage(request: BiEncoderRequest) {
|
| 27 |
+
this.requests.push(request);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
async terminate() {
|
| 31 |
+
return 0;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
reply(id: number, scores: number[]) {
|
| 35 |
+
this.emit("message", { type: "scores", id, scores });
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
return { FakeWorker };
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
vi.mock("node:worker_threads", () => ({ Worker: FakeWorker }));
|
| 43 |
+
|
| 44 |
+
async function startWithFakeWorker() {
|
| 45 |
+
const started = startBiEncoderService();
|
| 46 |
+
FakeWorker.latest.emit("message", { type: "ready" });
|
| 47 |
+
await started;
|
| 48 |
+
return FakeWorker.latest;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
/** Settles a promise without awaiting it, so a test can see it is pending. */
|
| 52 |
+
function track<T>(promise: Promise<T>) {
|
| 53 |
+
const state: { settled: boolean; value?: T } = { settled: false };
|
| 54 |
+
promise.then((value) => {
|
| 55 |
+
state.settled = true;
|
| 56 |
+
state.value = value;
|
| 57 |
+
});
|
| 58 |
+
return state;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
describe("scorePassages", () => {
|
| 62 |
+
beforeEach(() => {
|
| 63 |
+
vi.useFakeTimers();
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
afterEach(async () => {
|
| 67 |
+
await stopBiEncoderService();
|
| 68 |
+
vi.useRealTimers();
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
it("answers empty scores when a ready worker never replies", async () => {
|
| 72 |
+
await startWithFakeWorker();
|
| 73 |
+
|
| 74 |
+
const result = track(scorePassages("query", ["a", "b"]));
|
| 75 |
+
await vi.advanceTimersByTimeAsync(SCORE_TIMEOUT_MS - 1);
|
| 76 |
+
expect(result.settled).toBe(false);
|
| 77 |
+
|
| 78 |
+
await vi.advanceTimersByTimeAsync(1);
|
| 79 |
+
expect(result).toEqual({ settled: true, value: [] });
|
| 80 |
+
expect(vi.getTimerCount()).toBe(0);
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
it("resolves with the reply's scores and clears its timer", async () => {
|
| 84 |
+
const fakeWorker = await startWithFakeWorker();
|
| 85 |
+
|
| 86 |
+
const scores = scorePassages("query", ["a", "b"]);
|
| 87 |
+
fakeWorker.reply(fakeWorker.requests[0].id, [0.25, 0.75]);
|
| 88 |
+
|
| 89 |
+
await expect(scores).resolves.toEqual([0.25, 0.75]);
|
| 90 |
+
expect(vi.getTimerCount()).toBe(0);
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
it("ignores a reply after the timeout and still serves the next request", async () => {
|
| 94 |
+
const fakeWorker = await startWithFakeWorker();
|
| 95 |
+
|
| 96 |
+
const timedOut = scorePassages("query", ["a"]);
|
| 97 |
+
await vi.advanceTimersByTimeAsync(SCORE_TIMEOUT_MS);
|
| 98 |
+
await expect(timedOut).resolves.toEqual([]);
|
| 99 |
+
fakeWorker.reply(fakeWorker.requests[0].id, [0.5]);
|
| 100 |
+
|
| 101 |
+
const next = scorePassages("query", ["b"]);
|
| 102 |
+
fakeWorker.reply(fakeWorker.requests[1].id, [0.9]);
|
| 103 |
+
await expect(next).resolves.toEqual([0.9]);
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
it("answers empty scores and clears timers when the service stops", async () => {
|
| 107 |
+
await startWithFakeWorker();
|
| 108 |
+
|
| 109 |
+
const scores = scorePassages("query", ["a"]);
|
| 110 |
+
await stopBiEncoderService();
|
| 111 |
+
|
| 112 |
+
await expect(scores).resolves.toEqual([]);
|
| 113 |
+
expect(vi.getTimerCount()).toBe(0);
|
| 114 |
+
});
|
| 115 |
+
|
| 116 |
+
it("answers empty scores and clears timers when the worker exits", async () => {
|
| 117 |
+
const fakeWorker = await startWithFakeWorker();
|
| 118 |
+
|
| 119 |
+
const scores = scorePassages("query", ["a"]);
|
| 120 |
+
fakeWorker.emit("exit", 1);
|
| 121 |
+
|
| 122 |
+
await expect(scores).resolves.toEqual([]);
|
| 123 |
+
expect(vi.getTimerCount()).toBe(0);
|
| 124 |
+
});
|
| 125 |
+
});
|
server/biEncoderService.ts
CHANGED
|
@@ -22,7 +22,21 @@ let worker: Worker | null = null;
|
|
| 22 |
let isReady = false;
|
| 23 |
let nextRequestId = 0;
|
| 24 |
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
/**
|
| 28 |
* Answers every in-flight request with empty scores. Empty is the signal
|
|
@@ -31,7 +45,10 @@ const pendingScores = new Map<number, (scores: number[]) => void>();
|
|
| 31 |
* page-content reads waiting for a reply that is never coming.
|
| 32 |
*/
|
| 33 |
function resolvePendingEmpty() {
|
| 34 |
-
for (const resolve of pendingScores.values())
|
|
|
|
|
|
|
|
|
|
| 35 |
pendingScores.clear();
|
| 36 |
}
|
| 37 |
|
|
@@ -58,9 +75,11 @@ export async function startBiEncoderService() {
|
|
| 58 |
biEncoderWorker.on("message", (message: BiEncoderResponse) => {
|
| 59 |
if (message.type === "ready") return;
|
| 60 |
|
| 61 |
-
const
|
| 62 |
-
if (!
|
| 63 |
pendingScores.delete(message.id);
|
|
|
|
|
|
|
| 64 |
|
| 65 |
if (message.type === "failed") {
|
| 66 |
printMessage(`Bi-encoder scoring failed: ${message.message}`);
|
|
@@ -138,7 +157,16 @@ export async function scorePassages(
|
|
| 138 |
const id = nextRequestId++;
|
| 139 |
|
| 140 |
return new Promise<number[]>((resolve) => {
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
const request: BiEncoderRequest = { type: "score", id, query, passages };
|
| 144 |
try {
|
|
@@ -146,6 +174,7 @@ export async function scorePassages(
|
|
| 146 |
} catch (error) {
|
| 147 |
// The worker was terminated between the check above and this send.
|
| 148 |
pendingScores.delete(id);
|
|
|
|
| 149 |
printMessage(
|
| 150 |
`Could not reach the bi-encoder worker: ${error instanceof Error ? error.message : String(error)}`,
|
| 151 |
);
|
|
|
|
| 22 |
let isReady = false;
|
| 23 |
let nextRequestId = 0;
|
| 24 |
|
| 25 |
+
/**
|
| 26 |
+
* How long a scoring request may wait for the worker before it is answered
|
| 27 |
+
* with empty scores, so a worker that is alive but stuck degrades ranking to
|
| 28 |
+
* lexical instead of holding every page-content read. Sized from the budget
|
| 29 |
+
* the client already enforces: its 20 s `/page-content` abort, minus the 6 s
|
| 30 |
+
* page-read deadline, minus margin for the rest of the request.
|
| 31 |
+
*/
|
| 32 |
+
export const SCORE_TIMEOUT_MS = 10_000;
|
| 33 |
+
|
| 34 |
+
interface PendingScore {
|
| 35 |
+
resolve: (scores: number[]) => void;
|
| 36 |
+
timer: ReturnType<typeof setTimeout>;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
const pendingScores = new Map<number, PendingScore>();
|
| 40 |
|
| 41 |
/**
|
| 42 |
* Answers every in-flight request with empty scores. Empty is the signal
|
|
|
|
| 45 |
* page-content reads waiting for a reply that is never coming.
|
| 46 |
*/
|
| 47 |
function resolvePendingEmpty() {
|
| 48 |
+
for (const { resolve, timer } of pendingScores.values()) {
|
| 49 |
+
clearTimeout(timer);
|
| 50 |
+
resolve([]);
|
| 51 |
+
}
|
| 52 |
pendingScores.clear();
|
| 53 |
}
|
| 54 |
|
|
|
|
| 75 |
biEncoderWorker.on("message", (message: BiEncoderResponse) => {
|
| 76 |
if (message.type === "ready") return;
|
| 77 |
|
| 78 |
+
const pending = pendingScores.get(message.id);
|
| 79 |
+
if (!pending) return;
|
| 80 |
pendingScores.delete(message.id);
|
| 81 |
+
clearTimeout(pending.timer);
|
| 82 |
+
const { resolve } = pending;
|
| 83 |
|
| 84 |
if (message.type === "failed") {
|
| 85 |
printMessage(`Bi-encoder scoring failed: ${message.message}`);
|
|
|
|
| 157 |
const id = nextRequestId++;
|
| 158 |
|
| 159 |
return new Promise<number[]>((resolve) => {
|
| 160 |
+
// A late reply after the timeout finds no entry and is ignored.
|
| 161 |
+
const timer = setTimeout(() => {
|
| 162 |
+
pendingScores.delete(id);
|
| 163 |
+
printMessage(
|
| 164 |
+
`Bi-encoder scoring did not answer within ${SCORE_TIMEOUT_MS} ms; falling back to lexical ranking.`,
|
| 165 |
+
);
|
| 166 |
+
resolve([]);
|
| 167 |
+
}, SCORE_TIMEOUT_MS);
|
| 168 |
+
timer.unref();
|
| 169 |
+
pendingScores.set(id, { resolve, timer });
|
| 170 |
|
| 171 |
const request: BiEncoderRequest = { type: "score", id, query, passages };
|
| 172 |
try {
|
|
|
|
| 174 |
} catch (error) {
|
| 175 |
// The worker was terminated between the check above and this send.
|
| 176 |
pendingScores.delete(id);
|
| 177 |
+
clearTimeout(timer);
|
| 178 |
printMessage(
|
| 179 |
`Could not reach the bi-encoder worker: ${error instanceof Error ? error.message : String(error)}`,
|
| 180 |
);
|
server/cacheServerHook.test.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
| 2 |
+
import { tmpdir } from "node:os";
|
| 3 |
+
import path from "node:path";
|
| 4 |
+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
| 5 |
+
import { cacheServerHook } from "./cacheServerHook";
|
| 6 |
+
|
| 7 |
+
let root: string;
|
| 8 |
+
|
| 9 |
+
beforeAll(() => {
|
| 10 |
+
root = mkdtempSync(path.join(tmpdir(), "cache-hook-"));
|
| 11 |
+
mkdirSync(path.join(root, "dist", "assets"), { recursive: true });
|
| 12 |
+
writeFileSync(path.join(root, "dist", "assets", "index-abc123.js"), "");
|
| 13 |
+
writeFileSync(path.join(root, "dist", "secret.txt"), "");
|
| 14 |
+
});
|
| 15 |
+
|
| 16 |
+
afterAll(() => {
|
| 17 |
+
rmSync(root, { recursive: true, force: true });
|
| 18 |
+
});
|
| 19 |
+
|
| 20 |
+
async function cacheControlFor(url: string) {
|
| 21 |
+
const use = vi.fn();
|
| 22 |
+
cacheServerHook({
|
| 23 |
+
middlewares: { use },
|
| 24 |
+
config: { root, build: { outDir: "dist" } },
|
| 25 |
+
} as never);
|
| 26 |
+
const handler = use.mock.calls[0][0] as (
|
| 27 |
+
req: { url: string },
|
| 28 |
+
res: { setHeader: (name: string, value: string) => void },
|
| 29 |
+
next: () => void,
|
| 30 |
+
) => Promise<void>;
|
| 31 |
+
const setHeader = vi.fn();
|
| 32 |
+
const next = vi.fn();
|
| 33 |
+
await handler({ url }, { setHeader }, next);
|
| 34 |
+
expect(next).toHaveBeenCalled();
|
| 35 |
+
return setHeader.mock.calls[0][1] as string;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
describe("cacheServerHook", () => {
|
| 39 |
+
it("marks an existing hashed asset immutable", async () => {
|
| 40 |
+
expect(await cacheControlFor("/assets/index-abc123.js")).toBe(
|
| 41 |
+
"public, max-age=31536000, immutable",
|
| 42 |
+
);
|
| 43 |
+
expect(await cacheControlFor("/assets/index-abc123.js?v=1")).toBe(
|
| 44 |
+
"public, max-age=31536000, immutable",
|
| 45 |
+
);
|
| 46 |
+
});
|
| 47 |
+
|
| 48 |
+
it("does not mark a missing asset immutable", async () => {
|
| 49 |
+
expect(await cacheControlFor("/assets/index-OLD.js")).toBe("no-cache");
|
| 50 |
+
expect(await cacheControlFor("/assets/")).toBe("no-cache");
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
it("does not look outside the assets folder", async () => {
|
| 54 |
+
expect(await cacheControlFor("/assets/..%2fsecret.txt")).toBe("no-cache");
|
| 55 |
+
expect(await cacheControlFor("/assets/%E0%A4%A.js")).toBe("no-cache");
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
it("keeps HTML on no-cache and other files on a one-day cache", async () => {
|
| 59 |
+
expect(await cacheControlFor("/")).toBe("no-cache");
|
| 60 |
+
expect(await cacheControlFor("/index.html")).toBe("no-cache");
|
| 61 |
+
expect(await cacheControlFor("/favicon.png")).toBe(
|
| 62 |
+
"public, max-age=86400, must-revalidate",
|
| 63 |
+
);
|
| 64 |
+
});
|
| 65 |
+
});
|
server/cacheServerHook.ts
CHANGED
|
@@ -1,13 +1,22 @@
|
|
|
|
|
|
|
|
| 1 |
import type { PreviewServer, ViteDevServer } from "vite";
|
| 2 |
|
| 3 |
/** Cache-Control per asset class: immutable for hashed assets, no-cache for HTML. */
|
| 4 |
export function cacheServerHook<T extends ViteDevServer | PreviewServer>(
|
| 5 |
server: T,
|
| 6 |
) {
|
|
|
|
|
|
|
|
|
|
| 7 |
server.middlewares.use(async (request, response, next) => {
|
| 8 |
let cacheControlValue = "public, max-age=86400, must-revalidate";
|
| 9 |
if (request.url?.startsWith("/assets/")) {
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
} else if (
|
| 12 |
request.url === "/" ||
|
| 13 |
request.url?.startsWith("/?") ||
|
|
@@ -21,3 +30,13 @@ export function cacheServerHook<T extends ViteDevServer | PreviewServer>(
|
|
| 21 |
next();
|
| 22 |
});
|
| 23 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { stat } from "node:fs/promises";
|
| 2 |
+
import path from "node:path";
|
| 3 |
import type { PreviewServer, ViteDevServer } from "vite";
|
| 4 |
|
| 5 |
/** Cache-Control per asset class: immutable for hashed assets, no-cache for HTML. */
|
| 6 |
export function cacheServerHook<T extends ViteDevServer | PreviewServer>(
|
| 7 |
server: T,
|
| 8 |
) {
|
| 9 |
+
const outDir = path.resolve(server.config.root, server.config.build.outDir);
|
| 10 |
+
const assetsDir = path.join(outDir, "assets");
|
| 11 |
+
|
| 12 |
server.middlewares.use(async (request, response, next) => {
|
| 13 |
let cacheControlValue = "public, max-age=86400, must-revalidate";
|
| 14 |
if (request.url?.startsWith("/assets/")) {
|
| 15 |
+
// A missing asset falls through to the SPA fallback or a 404, and caching
|
| 16 |
+
// that body for a year would poison the URL once the real file is deployed.
|
| 17 |
+
cacheControlValue = (await isFileIn(assetsDir, outDir, request.url))
|
| 18 |
+
? "public, max-age=31536000, immutable"
|
| 19 |
+
: "no-cache";
|
| 20 |
} else if (
|
| 21 |
request.url === "/" ||
|
| 22 |
request.url?.startsWith("/?") ||
|
|
|
|
| 30 |
next();
|
| 31 |
});
|
| 32 |
}
|
| 33 |
+
|
| 34 |
+
async function isFileIn(dir: string, outDir: string, url: string) {
|
| 35 |
+
try {
|
| 36 |
+
const { pathname } = new URL(url, "http://localhost");
|
| 37 |
+
const file = path.join(outDir, decodeURIComponent(pathname));
|
| 38 |
+
return file.startsWith(dir + path.sep) && (await stat(file)).isFile();
|
| 39 |
+
} catch {
|
| 40 |
+
return false;
|
| 41 |
+
}
|
| 42 |
+
}
|
server/configEndpointServerHook.test.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
| 2 |
+
|
| 3 |
+
vi.mock("./searchToken", () => ({
|
| 4 |
+
getSearchToken: () => "test-search-token",
|
| 5 |
+
}));
|
| 6 |
+
|
| 7 |
+
afterEach(() => {
|
| 8 |
+
vi.unstubAllEnvs();
|
| 9 |
+
});
|
| 10 |
+
|
| 11 |
+
async function requestConfig() {
|
| 12 |
+
const { configEndpointServerHook } = await import(
|
| 13 |
+
"./configEndpointServerHook"
|
| 14 |
+
);
|
| 15 |
+
const use = vi.fn();
|
| 16 |
+
configEndpointServerHook({ middlewares: { use } } as never);
|
| 17 |
+
const handler = use.mock.calls[0][0] as (
|
| 18 |
+
req: { url: string; method: string },
|
| 19 |
+
res: { setHeader: unknown; end: (body: string) => void },
|
| 20 |
+
next: () => void,
|
| 21 |
+
) => void;
|
| 22 |
+
const end = vi.fn();
|
| 23 |
+
handler(
|
| 24 |
+
{ url: "/api/config", method: "GET" },
|
| 25 |
+
{ setHeader: vi.fn(), end },
|
| 26 |
+
vi.fn(),
|
| 27 |
+
);
|
| 28 |
+
return JSON.parse(end.mock.calls[0][0] as string) as {
|
| 29 |
+
accessKeysEnabled: boolean;
|
| 30 |
+
};
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
describe("configEndpointServerHook", () => {
|
| 34 |
+
it("reports access keys as enabled when a key is configured", async () => {
|
| 35 |
+
vi.stubEnv("ACCESS_KEYS", "key1, key2");
|
| 36 |
+
expect((await requestConfig()).accessKeysEnabled).toBe(true);
|
| 37 |
+
});
|
| 38 |
+
|
| 39 |
+
it("reports access keys as disabled when none are configured", async () => {
|
| 40 |
+
vi.stubEnv("ACCESS_KEYS", "");
|
| 41 |
+
expect((await requestConfig()).accessKeysEnabled).toBe(false);
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
it("reports access keys as disabled when the list holds no usable key", async () => {
|
| 45 |
+
vi.stubEnv("ACCESS_KEYS", " , ,");
|
| 46 |
+
expect((await requestConfig()).accessKeysEnabled).toBe(false);
|
| 47 |
+
});
|
| 48 |
+
});
|
server/configEndpointServerHook.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
| 6 |
DEFAULT_WLLAMA_MODEL_ID,
|
| 7 |
type ServerConfig,
|
| 8 |
} from "../shared/serverConfig.ts";
|
|
|
|
| 9 |
import { getSearchToken } from "./searchToken.ts";
|
| 10 |
|
| 11 |
/**
|
|
@@ -21,7 +22,8 @@ export function configEndpointServerHook<
|
|
| 21 |
}
|
| 22 |
|
| 23 |
const config: ServerConfig = {
|
| 24 |
-
accessKeysEnabled:
|
|
|
|
| 25 |
accessKeyTimeoutHours: Number(process.env.ACCESS_KEY_TIMEOUT_HOURS) || 0,
|
| 26 |
wllamaDefaultModelId:
|
| 27 |
process.env.WLLAMA_DEFAULT_MODEL_ID || DEFAULT_WLLAMA_MODEL_ID,
|
|
|
|
| 6 |
DEFAULT_WLLAMA_MODEL_ID,
|
| 7 |
type ServerConfig,
|
| 8 |
} from "../shared/serverConfig.ts";
|
| 9 |
+
import { parseCommaSeparatedList } from "./parseCommaSeparatedList.ts";
|
| 10 |
import { getSearchToken } from "./searchToken.ts";
|
| 11 |
|
| 12 |
/**
|
|
|
|
| 22 |
}
|
| 23 |
|
| 24 |
const config: ServerConfig = {
|
| 25 |
+
accessKeysEnabled:
|
| 26 |
+
parseCommaSeparatedList(process.env.ACCESS_KEYS).length > 0,
|
| 27 |
accessKeyTimeoutHours: Number(process.env.ACCESS_KEY_TIMEOUT_HOURS) || 0,
|
| 28 |
wllamaDefaultModelId:
|
| 29 |
process.env.WLLAMA_DEFAULT_MODEL_ID || DEFAULT_WLLAMA_MODEL_ID,
|
server/dynamicCacheHeaders.test.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
| 2 |
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
| 3 |
+
import { tmpdir } from "node:os";
|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
| 6 |
+
|
| 7 |
+
// Every request is refused before it reaches a service, so the test needs no
|
| 8 |
+
// network: an unverified token, an exhausted rate limit.
|
| 9 |
+
vi.mock("./handleTokenVerification", () => ({
|
| 10 |
+
handleTokenVerification: vi.fn(
|
| 11 |
+
async (_token: unknown, response: ServerResponse) => {
|
| 12 |
+
response.statusCode = 401;
|
| 13 |
+
response.end("Unauthorized");
|
| 14 |
+
return { shouldContinue: false };
|
| 15 |
+
},
|
| 16 |
+
),
|
| 17 |
+
}));
|
| 18 |
+
vi.mock("./verifyTokenAndRateLimit", async (importOriginal) => ({
|
| 19 |
+
...(await importOriginal<typeof import("./verifyTokenAndRateLimit")>()),
|
| 20 |
+
consumeRateLimitPoint: vi.fn(async () => false),
|
| 21 |
+
}));
|
| 22 |
+
vi.mock("./fallbackSearchService", () => ({
|
| 23 |
+
assertSearchFallbackConfiguration: vi.fn(),
|
| 24 |
+
fetchFallbackTextResults: vi.fn(),
|
| 25 |
+
isSearchFallbackEnabled: vi.fn(() => false),
|
| 26 |
+
getFallbackProviderStats: vi.fn(() => ({})),
|
| 27 |
+
}));
|
| 28 |
+
vi.mock("./biEncoderService.ts", () => ({
|
| 29 |
+
getBiEncoderStatus: async () => true,
|
| 30 |
+
}));
|
| 31 |
+
vi.mock("./rerankerService.ts", () => ({
|
| 32 |
+
getRerankerStatus: async () => true,
|
| 33 |
+
}));
|
| 34 |
+
vi.mock("./webSearchService.ts", () => ({
|
| 35 |
+
getWebSearchServiceStatus: async () => "healthy",
|
| 36 |
+
getSearchCircuitStats: () => ({ circuitState: "closed", circuitOpens: 0 }),
|
| 37 |
+
}));
|
| 38 |
+
|
| 39 |
+
import { cacheServerHook } from "./cacheServerHook";
|
| 40 |
+
import { configEndpointServerHook } from "./configEndpointServerHook";
|
| 41 |
+
import { internalApiEndpointServerHook } from "./internalApiEndpointServerHook";
|
| 42 |
+
import { pageContentEndpointServerHook } from "./pageContentEndpointServerHook";
|
| 43 |
+
import { searchEndpointServerHook } from "./searchEndpointServerHook";
|
| 44 |
+
import { statusEndpointServerHook } from "./statusEndpointServerHook";
|
| 45 |
+
import { validateAccessKeyServerHook } from "./validateAccessKeyServerHook";
|
| 46 |
+
|
| 47 |
+
type Middleware = (
|
| 48 |
+
request: IncomingMessage,
|
| 49 |
+
response: ServerResponse,
|
| 50 |
+
next: () => void,
|
| 51 |
+
) => unknown;
|
| 52 |
+
|
| 53 |
+
let root: string;
|
| 54 |
+
const middlewares: Middleware[] = [];
|
| 55 |
+
|
| 56 |
+
beforeAll(() => {
|
| 57 |
+
root = mkdtempSync(path.join(tmpdir(), "dynamic-cache-"));
|
| 58 |
+
mkdirSync(path.join(root, "dist", "assets"), { recursive: true });
|
| 59 |
+
writeFileSync(path.join(root, "dist", "assets", "index-abc123.js"), "");
|
| 60 |
+
|
| 61 |
+
const server = {
|
| 62 |
+
middlewares: { use: (handler: Middleware) => middlewares.push(handler) },
|
| 63 |
+
config: {
|
| 64 |
+
root,
|
| 65 |
+
build: { outDir: "dist" },
|
| 66 |
+
define: { VITE_BUILD_DATE_TIME: new Date().toISOString() },
|
| 67 |
+
},
|
| 68 |
+
} as never;
|
| 69 |
+
// The order of the preview server in vite.config.ts.
|
| 70 |
+
for (const hook of [
|
| 71 |
+
configEndpointServerHook,
|
| 72 |
+
searchEndpointServerHook,
|
| 73 |
+
pageContentEndpointServerHook,
|
| 74 |
+
statusEndpointServerHook,
|
| 75 |
+
cacheServerHook,
|
| 76 |
+
validateAccessKeyServerHook,
|
| 77 |
+
internalApiEndpointServerHook,
|
| 78 |
+
]) {
|
| 79 |
+
hook(server);
|
| 80 |
+
}
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
afterAll(() => {
|
| 84 |
+
rmSync(root, { recursive: true, force: true });
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
/** The Cache-Control a request leaves with, answered or passed through. */
|
| 88 |
+
function cacheControlFor(url: string, method = "GET"): Promise<unknown> {
|
| 89 |
+
return new Promise((resolve) => {
|
| 90 |
+
const headers = new Map<string, unknown>();
|
| 91 |
+
const response = {
|
| 92 |
+
statusCode: 200,
|
| 93 |
+
headersSent: false,
|
| 94 |
+
writableEnded: false,
|
| 95 |
+
setHeader: (name: string, value: unknown) =>
|
| 96 |
+
headers.set(name.toLowerCase(), value),
|
| 97 |
+
getHeader: (name: string) => headers.get(name.toLowerCase()),
|
| 98 |
+
hasHeader: (name: string) => headers.has(name.toLowerCase()),
|
| 99 |
+
removeHeader: (name: string) => headers.delete(name.toLowerCase()),
|
| 100 |
+
write: () => true,
|
| 101 |
+
end: () => resolve(headers.get("cache-control")),
|
| 102 |
+
on: () => response,
|
| 103 |
+
once: () => response,
|
| 104 |
+
};
|
| 105 |
+
const request = {
|
| 106 |
+
url,
|
| 107 |
+
method,
|
| 108 |
+
headers: { host: "localhost" },
|
| 109 |
+
socket: { remoteAddress: "127.0.0.1" },
|
| 110 |
+
on: () => request,
|
| 111 |
+
once: () => request,
|
| 112 |
+
};
|
| 113 |
+
let index = 0;
|
| 114 |
+
const next = () => {
|
| 115 |
+
const middleware = middlewares[index++];
|
| 116 |
+
if (!middleware) {
|
| 117 |
+
resolve(headers.get("cache-control"));
|
| 118 |
+
return;
|
| 119 |
+
}
|
| 120 |
+
middleware(
|
| 121 |
+
request as unknown as IncomingMessage,
|
| 122 |
+
response as unknown as ServerResponse,
|
| 123 |
+
next,
|
| 124 |
+
);
|
| 125 |
+
};
|
| 126 |
+
next();
|
| 127 |
+
});
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
describe("Cache-Control across the preview middleware stack", () => {
|
| 131 |
+
it.each([
|
| 132 |
+
["/api/validate-access-key", "POST"],
|
| 133 |
+
["/inference", "GET"],
|
| 134 |
+
["/search/text?q=a&token=x", "GET"],
|
| 135 |
+
["/search/images?q=a&token=x", "GET"],
|
| 136 |
+
["/page-content?token=x", "GET"],
|
| 137 |
+
["/status", "GET"],
|
| 138 |
+
["/api/config", "GET"],
|
| 139 |
+
])("answers %s (%s) with no-store", async (url, method) => {
|
| 140 |
+
expect(await cacheControlFor(url, method)).toBe("no-store");
|
| 141 |
+
});
|
| 142 |
+
|
| 143 |
+
it("leaves the static paths to the cache hook", async () => {
|
| 144 |
+
expect(await cacheControlFor("/assets/index-abc123.js")).toBe(
|
| 145 |
+
"public, max-age=31536000, immutable",
|
| 146 |
+
);
|
| 147 |
+
expect(await cacheControlFor("/")).toBe("no-cache");
|
| 148 |
+
expect(await cacheControlFor("/favicon.png")).toBe(
|
| 149 |
+
"public, max-age=86400, must-revalidate",
|
| 150 |
+
);
|
| 151 |
+
});
|
| 152 |
+
});
|
server/fallbackSearchService.test.ts
CHANGED
|
@@ -89,6 +89,8 @@ function youcomDocumentWith(web: unknown[]): string {
|
|
| 89 |
const PARALLEL_URL = "https://search.parallel.ai/mcp";
|
| 90 |
const YOUCOM_KEYLESS_URL = "https://api.you.com/mcp?profile=free";
|
| 91 |
const YOUCOM_AUTHENTICATED_URL = "https://api.you.com/mcp";
|
|
|
|
|
|
|
| 92 |
|
| 93 |
const DESCRIPTION =
|
| 94 |
"A plain description that You.com returns for a page that matched the query, long enough to read as a summary.";
|
|
@@ -112,6 +114,7 @@ const FALLBACK_VARIABLES = [
|
|
| 112 |
"SEARCH_FALLBACK_PROVIDERS",
|
| 113 |
"SEARCH_FALLBACK_PARALLEL_API_KEY",
|
| 114 |
"SEARCH_FALLBACK_YOUCOM_API_KEY",
|
|
|
|
| 115 |
"SEARCH_FALLBACK_PROVIDER",
|
| 116 |
"SEARCH_FALLBACK_API_KEY",
|
| 117 |
] as const;
|
|
@@ -1356,7 +1359,7 @@ describe("configuration", () => {
|
|
| 1356 |
listProviders("parallel, Bing");
|
| 1357 |
|
| 1358 |
expect(() => assertSearchFallbackConfiguration()).toThrow(
|
| 1359 |
-
"SEARCH_FALLBACK_PROVIDERS has unknown provider names: bing; valid names: parallel, youcom.",
|
| 1360 |
);
|
| 1361 |
await expect(
|
| 1362 |
fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),
|
|
@@ -1907,6 +1910,110 @@ describe("getFallbackProviderStats", () => {
|
|
| 1907 |
expect(getFallbackProviderStats()).toEqual({
|
| 1908 |
parallel: zero,
|
| 1909 |
youcom: zero,
|
|
|
|
| 1910 |
});
|
| 1911 |
});
|
| 1912 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
const PARALLEL_URL = "https://search.parallel.ai/mcp";
|
| 90 |
const YOUCOM_KEYLESS_URL = "https://api.you.com/mcp?profile=free";
|
| 91 |
const YOUCOM_AUTHENTICATED_URL = "https://api.you.com/mcp";
|
| 92 |
+
const KEENABLE_KEYLESS_URL = "https://api.keenable.ai/mcp-public";
|
| 93 |
+
const KEENABLE_AUTHENTICATED_URL = "https://api.keenable.ai/mcp";
|
| 94 |
|
| 95 |
const DESCRIPTION =
|
| 96 |
"A plain description that You.com returns for a page that matched the query, long enough to read as a summary.";
|
|
|
|
| 114 |
"SEARCH_FALLBACK_PROVIDERS",
|
| 115 |
"SEARCH_FALLBACK_PARALLEL_API_KEY",
|
| 116 |
"SEARCH_FALLBACK_YOUCOM_API_KEY",
|
| 117 |
+
"SEARCH_FALLBACK_KEENABLE_API_KEY",
|
| 118 |
"SEARCH_FALLBACK_PROVIDER",
|
| 119 |
"SEARCH_FALLBACK_API_KEY",
|
| 120 |
] as const;
|
|
|
|
| 1359 |
listProviders("parallel, Bing");
|
| 1360 |
|
| 1361 |
expect(() => assertSearchFallbackConfiguration()).toThrow(
|
| 1362 |
+
"SEARCH_FALLBACK_PROVIDERS has unknown provider names: bing; valid names: parallel, youcom, keenable.",
|
| 1363 |
);
|
| 1364 |
await expect(
|
| 1365 |
fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),
|
|
|
|
| 1910 |
expect(getFallbackProviderStats()).toEqual({
|
| 1911 |
parallel: zero,
|
| 1912 |
youcom: zero,
|
| 1913 |
+
keenable: zero,
|
| 1914 |
});
|
| 1915 |
});
|
| 1916 |
});
|
| 1917 |
+
|
| 1918 |
+
describe("Keenable", () => {
|
| 1919 |
+
const KEENABLE_KEY_VARIABLE = "SEARCH_FALLBACK_KEENABLE_API_KEY";
|
| 1920 |
+
const keenableDocumentWith = (results: unknown[]) =>
|
| 1921 |
+
toolReply({ query: QUERY, mode: "pro", results });
|
| 1922 |
+
const runKeenable = async (results: unknown[], limit = 10) => {
|
| 1923 |
+
process.env.SEARCH_FALLBACK_PROVIDERS = "keenable";
|
| 1924 |
+
mockExchange(keenableDocumentWith(results), { initializeSession: null });
|
| 1925 |
+
return fetchFallbackTextResults(QUERY, limit, FULL_BUDGET_MS);
|
| 1926 |
+
};
|
| 1927 |
+
|
| 1928 |
+
it("is left out of the default list while it has no key", async () => {
|
| 1929 |
+
delete process.env.SEARCH_FALLBACK_PROVIDERS;
|
| 1930 |
+
vi.spyOn(Math, "random").mockReturnValue(0.99);
|
| 1931 |
+
mockExchange(documentWith([]));
|
| 1932 |
+
mockExchange(youcomDocumentWith([]), { initializeSession: null });
|
| 1933 |
+
|
| 1934 |
+
await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
|
| 1935 |
+
|
| 1936 |
+
const urls = fetchMock.mock.calls.map(([requestUrl]) => String(requestUrl));
|
| 1937 |
+
expect(new Set(urls)).toEqual(new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL]));
|
| 1938 |
+
});
|
| 1939 |
+
|
| 1940 |
+
it("joins the default list when its key is set", async () => {
|
| 1941 |
+
delete process.env.SEARCH_FALLBACK_PROVIDERS;
|
| 1942 |
+
process.env[KEENABLE_KEY_VARIABLE] = "keenable-test-value";
|
| 1943 |
+
vi.spyOn(Math, "random").mockReturnValue(0.99);
|
| 1944 |
+
mockExchange(documentWith([]));
|
| 1945 |
+
mockExchange(youcomDocumentWith([]), { initializeSession: null });
|
| 1946 |
+
mockExchange(keenableDocumentWith([]), { initializeSession: null });
|
| 1947 |
+
|
| 1948 |
+
await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
|
| 1949 |
+
|
| 1950 |
+
const urls = fetchMock.mock.calls.map(([requestUrl]) => String(requestUrl));
|
| 1951 |
+
expect(new Set(urls)).toEqual(
|
| 1952 |
+
new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL, KEENABLE_AUTHENTICATED_URL]),
|
| 1953 |
+
);
|
| 1954 |
+
});
|
| 1955 |
+
|
| 1956 |
+
it("calls the keyless endpoint with the app name and no key header", async () => {
|
| 1957 |
+
await runKeenable([]);
|
| 1958 |
+
|
| 1959 |
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
| 1960 |
+
for (const [index, [requestUrl]] of fetchMock.mock.calls.entries()) {
|
| 1961 |
+
expect(String(requestUrl)).toBe(KEENABLE_KEYLESS_URL);
|
| 1962 |
+
expect(requestHeaders(index)["X-Keenable-Title"]).toBe("MiniSearch");
|
| 1963 |
+
expect(requestHeaders(index)["X-API-Key"]).toBeUndefined();
|
| 1964 |
+
expect(requestHeaders(index).Authorization).toBeUndefined();
|
| 1965 |
+
}
|
| 1966 |
+
expect(requestBody(1).params?.name).toBe("search_web_pages");
|
| 1967 |
+
expect(requestBody(1).params?.arguments).toEqual({
|
| 1968 |
+
query: QUERY,
|
| 1969 |
+
max_results: 10,
|
| 1970 |
+
output_format: "json",
|
| 1971 |
+
disable_cards: true,
|
| 1972 |
+
});
|
| 1973 |
+
});
|
| 1974 |
+
|
| 1975 |
+
it("sends a key as X-API-Key, never as a Bearer token, on the keyed endpoint", async () => {
|
| 1976 |
+
process.env[KEENABLE_KEY_VARIABLE] = "keenable-test-value";
|
| 1977 |
+
|
| 1978 |
+
await runKeenable([]);
|
| 1979 |
+
|
| 1980 |
+
for (const [index, [requestUrl]] of fetchMock.mock.calls.entries()) {
|
| 1981 |
+
expect(String(requestUrl)).toBe(KEENABLE_AUTHENTICATED_URL);
|
| 1982 |
+
expect(requestHeaders(index)["X-API-Key"]).toBe("keenable-test-value");
|
| 1983 |
+
expect(requestHeaders(index).Authorization).toBeUndefined();
|
| 1984 |
+
}
|
| 1985 |
+
});
|
| 1986 |
+
|
| 1987 |
+
it("asks for at most 50 results", async () => {
|
| 1988 |
+
await runKeenable([], 80);
|
| 1989 |
+
|
| 1990 |
+
expect(requestBody(1).params?.arguments?.max_results).toBe(50);
|
| 1991 |
+
});
|
| 1992 |
+
|
| 1993 |
+
it("maps the snippet like an excerpt and keeps the endpoint's order", async () => {
|
| 1994 |
+
const results = await runKeenable([
|
| 1995 |
+
{
|
| 1996 |
+
title: "First",
|
| 1997 |
+
url: "https://example.com/1",
|
| 1998 |
+
snippet: `# Heading\n${EXCERPT}`,
|
| 1999 |
+
},
|
| 2000 |
+
{ title: "No snippet", url: "https://example.com/2", snippet: "" },
|
| 2001 |
+
{ title: "Second", url: "https://example.com/3", snippet: EXCERPT },
|
| 2002 |
+
"not an object",
|
| 2003 |
+
]);
|
| 2004 |
+
|
| 2005 |
+
expect(results).toEqual([
|
| 2006 |
+
["First", EXCERPT, "https://example.com/1"],
|
| 2007 |
+
["Second", EXCERPT, "https://example.com/3"],
|
| 2008 |
+
]);
|
| 2009 |
+
});
|
| 2010 |
+
|
| 2011 |
+
it("throws when the document has no results array", async () => {
|
| 2012 |
+
process.env.SEARCH_FALLBACK_PROVIDERS = "keenable";
|
| 2013 |
+
mockExchange(toolReply({ query: QUERY }), { initializeSession: null });
|
| 2014 |
+
|
| 2015 |
+
await expect(
|
| 2016 |
+
fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),
|
| 2017 |
+
).rejects.toThrow("without a results array");
|
| 2018 |
+
});
|
| 2019 |
+
});
|
server/fallbackSearchService.ts
CHANGED
|
@@ -25,6 +25,8 @@ const MIN_SNIPPET_LINE_LENGTH = 40;
|
|
| 25 |
const DEFAULT_RATE_LIMIT_PAUSE_MS = 60_000;
|
| 26 |
const MAX_RATE_LIMIT_PAUSE_MS = 3_600_000;
|
| 27 |
const MIN_RATE_LIMIT_PAUSE_MS = 1_000;
|
|
|
|
|
|
|
| 28 |
|
| 29 |
// One per server process: Parallel uses it for free-tier rate limiting and
|
| 30 |
// one MiniSearch instance is one client, so a fresh one per request would shed
|
|
@@ -62,13 +64,22 @@ interface YoucomSearchDocument {
|
|
| 62 |
results?: { web?: YoucomWebResult[] };
|
| 63 |
}
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
type TextualResult = [title: string, content: string, url: string];
|
| 66 |
|
| 67 |
-
type ProviderName = "parallel" | "youcom";
|
| 68 |
|
| 69 |
interface MappedResults {
|
| 70 |
results: TextualResult[];
|
| 71 |
-
received: number;
|
| 72 |
/** The provider's longer text per result URL, kept for `/page-content`. */
|
| 73 |
pageTexts?: Map<string, string>;
|
| 74 |
}
|
|
@@ -76,7 +87,15 @@ interface MappedResults {
|
|
| 76 |
interface FallbackProvider {
|
| 77 |
name: ProviderName;
|
| 78 |
apiKeyVariable: string;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
endpointUrl: (apiKey: string) => string;
|
|
|
|
|
|
|
| 80 |
toolCall: (
|
| 81 |
query: string,
|
| 82 |
limit: number,
|
|
@@ -116,6 +135,36 @@ const PROVIDERS: readonly FallbackProvider[] = [
|
|
| 116 |
mapResults: (document, limit) =>
|
| 117 |
mapYoucomResults(document as YoucomSearchDocument, limit),
|
| 118 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
];
|
| 120 |
|
| 121 |
const PROVIDER_NAMES = PROVIDERS.map((provider) => provider.name);
|
|
@@ -207,7 +256,12 @@ function readConfiguredProviders(): FallbackProvider[] {
|
|
| 207 |
}
|
| 208 |
|
| 209 |
const value = process.env.SEARCH_FALLBACK_PROVIDERS ?? "";
|
| 210 |
-
if (value.trim() === "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
const names = value
|
| 213 |
.split(",")
|
|
@@ -427,7 +481,11 @@ async function searchWithProvider(
|
|
| 427 |
const headers: Record<string, string> = {
|
| 428 |
"Content-Type": "application/json",
|
| 429 |
Accept: "application/json, text/event-stream",
|
| 430 |
-
...(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
};
|
| 432 |
|
| 433 |
const initializeResponse = await fetch(endpointUrl, {
|
|
@@ -505,11 +563,7 @@ async function searchWithProvider(
|
|
| 505 |
}
|
| 506 |
|
| 507 |
const document = await readSearchDocument<object>(callResponse, 2);
|
| 508 |
-
|
| 509 |
-
printMessage(
|
| 510 |
-
`Fallback search usable text results from ${provider.name}: ${mapped.results.length} of ${mapped.received}.`,
|
| 511 |
-
);
|
| 512 |
-
return mapped;
|
| 513 |
}
|
| 514 |
|
| 515 |
/**
|
|
@@ -633,7 +687,7 @@ function mapParallelResults(
|
|
| 633 |
return toSnippet(text);
|
| 634 |
});
|
| 635 |
|
| 636 |
-
return { results,
|
| 637 |
}
|
| 638 |
|
| 639 |
function mapYoucomResults(
|
|
@@ -648,10 +702,38 @@ function mapYoucomResults(
|
|
| 648 |
|
| 649 |
return {
|
| 650 |
results: mapEntries(document.results.web, limit, buildYoucomSnippet),
|
| 651 |
-
received: document.results.web.length,
|
| 652 |
};
|
| 653 |
}
|
| 654 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 655 |
function mapEntries<Entry extends { url?: string; title?: string | null }>(
|
| 656 |
entries: Entry[],
|
| 657 |
limit: number,
|
|
|
|
| 25 |
const DEFAULT_RATE_LIMIT_PAUSE_MS = 60_000;
|
| 26 |
const MAX_RATE_LIMIT_PAUSE_MS = 3_600_000;
|
| 27 |
const MIN_RATE_LIMIT_PAUSE_MS = 1_000;
|
| 28 |
+
// The most results one Keenable search returns; it refuses a larger count.
|
| 29 |
+
const KEENABLE_MAX_RESULTS = 50;
|
| 30 |
|
| 31 |
// One per server process: Parallel uses it for free-tier rate limiting and
|
| 32 |
// one MiniSearch instance is one client, so a fresh one per request would shed
|
|
|
|
| 64 |
results?: { web?: YoucomWebResult[] };
|
| 65 |
}
|
| 66 |
|
| 67 |
+
interface KeenableSearchResult {
|
| 68 |
+
url?: string;
|
| 69 |
+
title?: string | null;
|
| 70 |
+
snippet?: string | null;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
interface KeenableSearchDocument {
|
| 74 |
+
results?: KeenableSearchResult[];
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
type TextualResult = [title: string, content: string, url: string];
|
| 78 |
|
| 79 |
+
type ProviderName = "parallel" | "youcom" | "keenable";
|
| 80 |
|
| 81 |
interface MappedResults {
|
| 82 |
results: TextualResult[];
|
|
|
|
| 83 |
/** The provider's longer text per result URL, kept for `/page-content`. */
|
| 84 |
pageTexts?: Map<string, string>;
|
| 85 |
}
|
|
|
|
| 87 |
interface FallbackProvider {
|
| 88 |
name: ProviderName;
|
| 89 |
apiKeyVariable: string;
|
| 90 |
+
/**
|
| 91 |
+
* Left out of the default list: tried only when SEARCH_FALLBACK_PROVIDERS
|
| 92 |
+
* names it or its key is set, so adding it changes nothing for an instance
|
| 93 |
+
* that already runs the fallback.
|
| 94 |
+
*/
|
| 95 |
+
optIn?: boolean;
|
| 96 |
endpointUrl: (apiKey: string) => string;
|
| 97 |
+
/** The headers that carry the key, and any the provider needs on every request. Bearer when absent. */
|
| 98 |
+
headers?: (apiKey: string) => Record<string, string>;
|
| 99 |
toolCall: (
|
| 100 |
query: string,
|
| 101 |
limit: number,
|
|
|
|
| 135 |
mapResults: (document, limit) =>
|
| 136 |
mapYoucomResults(document as YoucomSearchDocument, limit),
|
| 137 |
},
|
| 138 |
+
{
|
| 139 |
+
name: "keenable",
|
| 140 |
+
apiKeyVariable: "SEARCH_FALLBACK_KEENABLE_API_KEY",
|
| 141 |
+
optIn: true,
|
| 142 |
+
endpointUrl: (apiKey) =>
|
| 143 |
+
apiKey
|
| 144 |
+
? "https://api.keenable.ai/mcp"
|
| 145 |
+
: "https://api.keenable.ai/mcp-public",
|
| 146 |
+
// Keenable reads a key from X-API-Key; a Bearer token there is taken for
|
| 147 |
+
// an OAuth sign-in and refused. The app name identifies the caller on the
|
| 148 |
+
// keyless endpoint.
|
| 149 |
+
headers: (apiKey) => ({
|
| 150 |
+
"X-Keenable-Title": "MiniSearch",
|
| 151 |
+
...(apiKey ? { "X-API-Key": apiKey } : {}),
|
| 152 |
+
}),
|
| 153 |
+
// `output_format: json` returns the raw search response instead of the
|
| 154 |
+
// readable text the tool sends by default. Cards (prices, rates) carry
|
| 155 |
+
// URLs that expire after a day, so they are left out.
|
| 156 |
+
toolCall: (query, limit) => ({
|
| 157 |
+
name: "search_web_pages",
|
| 158 |
+
arguments: {
|
| 159 |
+
query,
|
| 160 |
+
max_results: Math.min(limit, KEENABLE_MAX_RESULTS),
|
| 161 |
+
output_format: "json",
|
| 162 |
+
disable_cards: true,
|
| 163 |
+
},
|
| 164 |
+
}),
|
| 165 |
+
mapResults: (document, limit) =>
|
| 166 |
+
mapKeenableResults(document as KeenableSearchDocument, limit),
|
| 167 |
+
},
|
| 168 |
];
|
| 169 |
|
| 170 |
const PROVIDER_NAMES = PROVIDERS.map((provider) => provider.name);
|
|
|
|
| 256 |
}
|
| 257 |
|
| 258 |
const value = process.env.SEARCH_FALLBACK_PROVIDERS ?? "";
|
| 259 |
+
if (value.trim() === "") {
|
| 260 |
+
return PROVIDERS.filter(
|
| 261 |
+
({ optIn, apiKeyVariable }) =>
|
| 262 |
+
!optIn || (process.env[apiKeyVariable] ?? "").trim() !== "",
|
| 263 |
+
);
|
| 264 |
+
}
|
| 265 |
|
| 266 |
const names = value
|
| 267 |
.split(",")
|
|
|
|
| 481 |
const headers: Record<string, string> = {
|
| 482 |
"Content-Type": "application/json",
|
| 483 |
Accept: "application/json, text/event-stream",
|
| 484 |
+
...(provider.headers
|
| 485 |
+
? provider.headers(apiKey)
|
| 486 |
+
: apiKey
|
| 487 |
+
? { Authorization: `Bearer ${apiKey}` }
|
| 488 |
+
: {}),
|
| 489 |
};
|
| 490 |
|
| 491 |
const initializeResponse = await fetch(endpointUrl, {
|
|
|
|
| 563 |
}
|
| 564 |
|
| 565 |
const document = await readSearchDocument<object>(callResponse, 2);
|
| 566 |
+
return provider.mapResults(document, limit);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
}
|
| 568 |
|
| 569 |
/**
|
|
|
|
| 687 |
return toSnippet(text);
|
| 688 |
});
|
| 689 |
|
| 690 |
+
return { results, pageTexts };
|
| 691 |
}
|
| 692 |
|
| 693 |
function mapYoucomResults(
|
|
|
|
| 702 |
|
| 703 |
return {
|
| 704 |
results: mapEntries(document.results.web, limit, buildYoucomSnippet),
|
|
|
|
| 705 |
};
|
| 706 |
}
|
| 707 |
|
| 708 |
+
/**
|
| 709 |
+
* Keenable's snippet is markdown cut from the page for the query, the same
|
| 710 |
+
* kind of text as a Parallel excerpt, so each result is read as a Parallel
|
| 711 |
+
* result with that one excerpt: cleaned the same way, and kept whole for
|
| 712 |
+
* `/page-content`.
|
| 713 |
+
*/
|
| 714 |
+
function mapKeenableResults(
|
| 715 |
+
document: KeenableSearchDocument,
|
| 716 |
+
limit: number,
|
| 717 |
+
): MappedResults {
|
| 718 |
+
if (!Array.isArray(document.results)) return mapParallelResults({}, limit);
|
| 719 |
+
|
| 720 |
+
return mapParallelResults(
|
| 721 |
+
{
|
| 722 |
+
results: document.results.map((result) =>
|
| 723 |
+
result && typeof result === "object"
|
| 724 |
+
? {
|
| 725 |
+
url: result.url,
|
| 726 |
+
title: result.title,
|
| 727 |
+
excerpts:
|
| 728 |
+
typeof result.snippet === "string" ? [result.snippet] : [],
|
| 729 |
+
}
|
| 730 |
+
: result,
|
| 731 |
+
),
|
| 732 |
+
},
|
| 733 |
+
limit,
|
| 734 |
+
);
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
function mapEntries<Entry extends { url?: string; title?: string | null }>(
|
| 738 |
entries: Entry[],
|
| 739 |
limit: number,
|
server/internalApiEndpointServerHook.test.ts
CHANGED
|
@@ -178,6 +178,25 @@ describe("internalApiEndpointServerHook", () => {
|
|
| 178 |
expect(response.end).not.toHaveBeenCalled();
|
| 179 |
});
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
it("passes on a request without a URL instead of answering for it", async () => {
|
| 182 |
const handler = getRegisteredHandler();
|
| 183 |
const next = vi.fn();
|
|
@@ -408,6 +427,14 @@ describe("internalApiEndpointServerHook", () => {
|
|
| 408 |
"Content-Type",
|
| 409 |
"text/event-stream",
|
| 410 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
const writeCalls = response.write.mock.calls.map((c) => c[0]);
|
| 412 |
expect(
|
| 413 |
writeCalls.some((s: string) => s.includes('"content":"Hello"')),
|
|
@@ -764,7 +791,10 @@ describe("internalApiEndpointServerHook", () => {
|
|
| 764 |
response,
|
| 765 |
vi.fn(),
|
| 766 |
);
|
| 767 |
-
expect(response.setHeader).not.
|
|
|
|
|
|
|
|
|
|
| 768 |
expect(streamText).not.toHaveBeenCalled();
|
| 769 |
});
|
| 770 |
|
|
@@ -1184,8 +1214,12 @@ describe("internalApiEndpointServerHook", () => {
|
|
| 1184 |
try {
|
| 1185 |
const handler = getRegisteredHandler();
|
| 1186 |
const response = createResponse();
|
| 1187 |
-
|
| 1188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1189 |
});
|
| 1190 |
await handler(
|
| 1191 |
createRequest({ messages: [{ role: "user", content: "hi" }] }),
|
|
@@ -1580,3 +1614,21 @@ describe("internalApiEndpointServerHook", () => {
|
|
| 1580 |
});
|
| 1581 |
});
|
| 1582 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
expect(response.end).not.toHaveBeenCalled();
|
| 179 |
});
|
| 180 |
|
| 181 |
+
it.each([
|
| 182 |
+
["GET", "/inferences"],
|
| 183 |
+
["POST", "/inferenceX?token=abc"],
|
| 184 |
+
["POST", "/inference/extra?token=abc"],
|
| 185 |
+
])(
|
| 186 |
+
"passes through %s %s, which is not the /inference route",
|
| 187 |
+
async (method, url) => {
|
| 188 |
+
const handler = getRegisteredHandler();
|
| 189 |
+
const next = vi.fn();
|
| 190 |
+
const response = createResponse();
|
| 191 |
+
const request = createRequest({}, method);
|
| 192 |
+
request.url = url;
|
| 193 |
+
await handler(request, response, next);
|
| 194 |
+
expect(next).toHaveBeenCalledTimes(1);
|
| 195 |
+
expect(response.end).not.toHaveBeenCalled();
|
| 196 |
+
expect(handleTokenVerification).not.toHaveBeenCalled();
|
| 197 |
+
},
|
| 198 |
+
);
|
| 199 |
+
|
| 200 |
it("passes on a request without a URL instead of answering for it", async () => {
|
| 201 |
const handler = getRegisteredHandler();
|
| 202 |
const next = vi.fn();
|
|
|
|
| 427 |
"Content-Type",
|
| 428 |
"text/event-stream",
|
| 429 |
);
|
| 430 |
+
expect(response.setHeader).toHaveBeenCalledWith(
|
| 431 |
+
"Cache-Control",
|
| 432 |
+
"no-store",
|
| 433 |
+
);
|
| 434 |
+
expect(response.setHeader).not.toHaveBeenCalledWith(
|
| 435 |
+
"Cache-Control",
|
| 436 |
+
"no-cache",
|
| 437 |
+
);
|
| 438 |
const writeCalls = response.write.mock.calls.map((c) => c[0]);
|
| 439 |
expect(
|
| 440 |
writeCalls.some((s: string) => s.includes('"content":"Hello"')),
|
|
|
|
| 791 |
response,
|
| 792 |
vi.fn(),
|
| 793 |
);
|
| 794 |
+
expect(response.setHeader).not.toHaveBeenCalledWith(
|
| 795 |
+
"Content-Type",
|
| 796 |
+
"text/event-stream",
|
| 797 |
+
);
|
| 798 |
expect(streamText).not.toHaveBeenCalled();
|
| 799 |
});
|
| 800 |
|
|
|
|
| 1214 |
try {
|
| 1215 |
const handler = getRegisteredHandler();
|
| 1216 |
const response = createResponse();
|
| 1217 |
+
let thrown = false;
|
| 1218 |
+
response.setHeader.mockImplementation((name: string) => {
|
| 1219 |
+
if (!thrown && name === "Content-Type") {
|
| 1220 |
+
thrown = true;
|
| 1221 |
+
throw new Error("setHeader exploded");
|
| 1222 |
+
}
|
| 1223 |
});
|
| 1224 |
await handler(
|
| 1225 |
createRequest({ messages: [{ role: "user", content: "hi" }] }),
|
|
|
|
| 1614 |
});
|
| 1615 |
});
|
| 1616 |
});
|
| 1617 |
+
|
| 1618 |
+
describe("internalApiEndpointServerHook with a malformed Host header", () => {
|
| 1619 |
+
it("answers 400 and keeps the handler promise from rejecting", async () => {
|
| 1620 |
+
vi.mocked(handleTokenVerification).mockClear();
|
| 1621 |
+
const request = createRequest({ messages: [] });
|
| 1622 |
+
request.headers.host = "bad host";
|
| 1623 |
+
const response = createResponse();
|
| 1624 |
+
const next = vi.fn();
|
| 1625 |
+
|
| 1626 |
+
await expect(
|
| 1627 |
+
getRegisteredHandler()(request, response, next),
|
| 1628 |
+
).resolves.toBeUndefined();
|
| 1629 |
+
|
| 1630 |
+
expect(response.statusCode).toBe(400);
|
| 1631 |
+
expect(handleTokenVerification).not.toHaveBeenCalled();
|
| 1632 |
+
expect(next).not.toHaveBeenCalled();
|
| 1633 |
+
});
|
| 1634 |
+
});
|
server/internalApiEndpointServerHook.ts
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
| 23 |
recordStreamEndedWithoutFinish,
|
| 24 |
} from "./inferencesSinceLastRestart.ts";
|
| 25 |
import { sendJsonError } from "./utils/httpResponse.ts";
|
|
|
|
| 26 |
import {
|
| 27 |
calculateBackoffTime,
|
| 28 |
isResponseWritable,
|
|
@@ -80,7 +81,7 @@ function ensureSseHeaders(response: ServerResponse): void {
|
|
| 80 |
if (response.headersSent) return;
|
| 81 |
|
| 82 |
response.setHeader("Content-Type", "text/event-stream");
|
| 83 |
-
response.setHeader("Cache-Control", "no-
|
| 84 |
response.setHeader("Connection", "keep-alive");
|
| 85 |
}
|
| 86 |
|
|
@@ -138,6 +139,13 @@ export function internalApiEndpointServerHook<
|
|
| 138 |
return next();
|
| 139 |
}
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
if (request.method !== "POST") {
|
| 142 |
response.setHeader("Allow", "POST");
|
| 143 |
sendJsonError(response, 405, { error: "Method Not Allowed" });
|
|
@@ -149,12 +157,11 @@ export function internalApiEndpointServerHook<
|
|
| 149 |
return;
|
| 150 |
}
|
| 151 |
|
| 152 |
-
const
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
const url = new URL(request.url, baseUrl);
|
| 158 |
const token = url.searchParams.get("token");
|
| 159 |
const { shouldContinue } = await handleTokenVerification(
|
| 160 |
token,
|
|
|
|
| 23 |
recordStreamEndedWithoutFinish,
|
| 24 |
} from "./inferencesSinceLastRestart.ts";
|
| 25 |
import { sendJsonError } from "./utils/httpResponse.ts";
|
| 26 |
+
import { parseRequestUrl } from "./utils/requestUrl.ts";
|
| 27 |
import {
|
| 28 |
calculateBackoffTime,
|
| 29 |
isResponseWritable,
|
|
|
|
| 81 |
if (response.headersSent) return;
|
| 82 |
|
| 83 |
response.setHeader("Content-Type", "text/event-stream");
|
| 84 |
+
response.setHeader("Cache-Control", "no-store");
|
| 85 |
response.setHeader("Connection", "keep-alive");
|
| 86 |
}
|
| 87 |
|
|
|
|
| 139 |
return next();
|
| 140 |
}
|
| 141 |
|
| 142 |
+
// The gate above is only cheap; the route is the exact pathname.
|
| 143 |
+
if (new URL(request.url, "http://localhost").pathname !== "/inference") {
|
| 144 |
+
return next();
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
response.setHeader("Cache-Control", "no-store");
|
| 148 |
+
|
| 149 |
if (request.method !== "POST") {
|
| 150 |
response.setHeader("Allow", "POST");
|
| 151 |
sendJsonError(response, 405, { error: "Method Not Allowed" });
|
|
|
|
| 157 |
return;
|
| 158 |
}
|
| 159 |
|
| 160 |
+
const url = parseRequestUrl(request);
|
| 161 |
+
if (!url) {
|
| 162 |
+
sendJsonError(response, 400, { error: "Malformed request" });
|
| 163 |
+
return;
|
| 164 |
+
}
|
|
|
|
| 165 |
const token = url.searchParams.get("token");
|
| 166 |
const { shouldContinue } = await handleTokenVerification(
|
| 167 |
token,
|
server/outboundUserAgent.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { repository, version } from "../package.json" with { type: "json" };
|
| 2 |
+
|
| 3 |
+
const appName = repository.url.slice(repository.url.lastIndexOf("/") + 1);
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* How the server identifies itself on its outbound requests to third
|
| 7 |
+
* parties: name, version and where to read about it. Some hosts refuse a
|
| 8 |
+
* request that carries no User-Agent; upload.wikimedia.org answers it with
|
| 9 |
+
* 403.
|
| 10 |
+
*/
|
| 11 |
+
export const OUTBOUND_USER_AGENT = `Mozilla/5.0 (compatible; ${appName}/${version}; +${repository.url})`;
|
server/pageContentEndpointServerHook.test.ts
CHANGED
|
@@ -235,3 +235,31 @@ describe("pageContentEndpointServerHook", () => {
|
|
| 235 |
expect(getPageReadStats().grounding.requests).toBe(before.requests + 2);
|
| 236 |
});
|
| 237 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
expect(getPageReadStats().grounding.requests).toBe(before.requests + 2);
|
| 236 |
});
|
| 237 |
});
|
| 238 |
+
|
| 239 |
+
describe("pageContentEndpointServerHook with a malformed Host header", () => {
|
| 240 |
+
it("answers 400 and keeps the handler promise from rejecting", async () => {
|
| 241 |
+
vi.clearAllMocks();
|
| 242 |
+
const use = vi.fn();
|
| 243 |
+
pageContentEndpointServerHook({
|
| 244 |
+
middlewares: { use },
|
| 245 |
+
} as unknown as Parameters<typeof pageContentEndpointServerHook>[0]);
|
| 246 |
+
const response = {
|
| 247 |
+
statusCode: 200,
|
| 248 |
+
setHeader: vi.fn(),
|
| 249 |
+
end: vi.fn(),
|
| 250 |
+
} as unknown as RecordedResponse;
|
| 251 |
+
const next = vi.fn();
|
| 252 |
+
const request = {
|
| 253 |
+
url: "/page-content?url=http://example.com&token=abc",
|
| 254 |
+
headers: { host: "bad host" },
|
| 255 |
+
} as unknown as IncomingMessage;
|
| 256 |
+
|
| 257 |
+
await expect(
|
| 258 |
+
(use.mock.calls[0][0] as Handler)(request, response, next),
|
| 259 |
+
).resolves.toBeUndefined();
|
| 260 |
+
|
| 261 |
+
expect(response.statusCode).toBe(400);
|
| 262 |
+
expect(handleTokenVerification).not.toHaveBeenCalled();
|
| 263 |
+
expect(next).not.toHaveBeenCalled();
|
| 264 |
+
});
|
| 265 |
+
});
|
server/pageContentEndpointServerHook.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { z } from "zod";
|
|
| 3 |
import { handleTokenVerification } from "./handleTokenVerification.ts";
|
| 4 |
import { fetchPageContents } from "./pageContentService.ts";
|
| 5 |
import { recordGroundingOutcome } from "./pageReadsSinceLastRestart.ts";
|
| 6 |
-
import { sendValidationError } from "./utils/httpResponse.ts";
|
|
|
|
| 7 |
|
| 8 |
const MAX_QUERY_LENGTH = 2000;
|
| 9 |
const MAX_URL_LENGTH = 2048;
|
|
@@ -50,7 +51,13 @@ export function pageContentEndpointServerHook<
|
|
| 50 |
server.middlewares.use(async (request, response, next) => {
|
| 51 |
if (!request.url?.startsWith("/page-content")) return next();
|
| 52 |
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
if (url.pathname !== "/page-content") return next();
|
| 55 |
|
| 56 |
// Verified before the parameters are read, so malformed requests from an
|
|
|
|
| 3 |
import { handleTokenVerification } from "./handleTokenVerification.ts";
|
| 4 |
import { fetchPageContents } from "./pageContentService.ts";
|
| 5 |
import { recordGroundingOutcome } from "./pageReadsSinceLastRestart.ts";
|
| 6 |
+
import { sendJsonError, sendValidationError } from "./utils/httpResponse.ts";
|
| 7 |
+
import { parseRequestUrl } from "./utils/requestUrl.ts";
|
| 8 |
|
| 9 |
const MAX_QUERY_LENGTH = 2000;
|
| 10 |
const MAX_URL_LENGTH = 2048;
|
|
|
|
| 51 |
server.middlewares.use(async (request, response, next) => {
|
| 52 |
if (!request.url?.startsWith("/page-content")) return next();
|
| 53 |
|
| 54 |
+
response.setHeader("Cache-Control", "no-store");
|
| 55 |
+
|
| 56 |
+
const url = parseRequestUrl(request);
|
| 57 |
+
if (!url) {
|
| 58 |
+
sendJsonError(response, 400, { error: "Malformed request" });
|
| 59 |
+
return;
|
| 60 |
+
}
|
| 61 |
if (url.pathname !== "/page-content") return next();
|
| 62 |
|
| 63 |
// Verified before the parameters are read, so malformed requests from an
|
server/pageContentService.test.ts
CHANGED
|
@@ -96,6 +96,25 @@ async function countOutcomes(url: string, breaker = new PageReadHostBreaker()) {
|
|
| 96 |
};
|
| 97 |
}
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
describe("extractReadableText", () => {
|
| 100 |
it("keeps the article and drops site chrome, scripts and styles", () => {
|
| 101 |
const text = extractReadableText(articlePage);
|
|
@@ -842,6 +861,24 @@ describe("page read counters", () => {
|
|
| 842 |
).toEqual({ failed: 1 });
|
| 843 |
});
|
| 844 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 845 |
it("counts a page that yielded almost no text", async () => {
|
| 846 |
respondWithHtml("<html><body><p>Accept cookies</p></body></html>");
|
| 847 |
|
|
@@ -980,6 +1017,32 @@ describe("host circuit breaker", () => {
|
|
| 980 |
).toEqual({ skippedByBreaker: 1 });
|
| 981 |
});
|
| 982 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 983 |
it("does not count a dead link or a thin page, and either one ends a run of refusals", async () => {
|
| 984 |
const breaker = new PageReadHostBreaker(breakerOptions);
|
| 985 |
|
|
|
|
| 96 |
};
|
| 97 |
}
|
| 98 |
|
| 99 |
+
/**
|
| 100 |
+
* `AbortSignal.timeout` runs on Node's own timer, which fake timers do not
|
| 101 |
+
* move, so a test that needs the 6 s deadline to pass hands out signals
|
| 102 |
+
* driven by the faked `setTimeout` instead of waiting it out for real.
|
| 103 |
+
*/
|
| 104 |
+
function useFakeDeadlines() {
|
| 105 |
+
return vi.spyOn(AbortSignal, "timeout").mockImplementation((ms) => {
|
| 106 |
+
const controller = new AbortController();
|
| 107 |
+
setTimeout(
|
| 108 |
+
() =>
|
| 109 |
+
controller.abort(
|
| 110 |
+
new DOMException("The operation timed out.", "TimeoutError"),
|
| 111 |
+
),
|
| 112 |
+
ms,
|
| 113 |
+
);
|
| 114 |
+
return controller.signal;
|
| 115 |
+
});
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
describe("extractReadableText", () => {
|
| 119 |
it("keeps the article and drops site chrome, scripts and styles", () => {
|
| 120 |
const text = extractReadableText(articlePage);
|
|
|
|
| 861 |
).toEqual({ failed: 1 });
|
| 862 |
});
|
| 863 |
|
| 864 |
+
it("bounds a hanging DNS lookup with the same deadline and counts it as a timeout", async () => {
|
| 865 |
+
// Matches REQUEST_TIMEOUT_MS in pageContentService.ts.
|
| 866 |
+
const requestTimeoutMs = 6000;
|
| 867 |
+
lookupMock.mockImplementation(() => new Promise(() => {}));
|
| 868 |
+
vi.useFakeTimers();
|
| 869 |
+
const deadlines = useFakeDeadlines();
|
| 870 |
+
try {
|
| 871 |
+
const counted = countOutcomes("https://hanging-dns.example.com/");
|
| 872 |
+
await vi.advanceTimersByTimeAsync(requestTimeoutMs);
|
| 873 |
+
|
| 874 |
+
expect((await counted).skipped).toEqual({ timedOut: 1 });
|
| 875 |
+
expect(fetchMock).not.toHaveBeenCalled();
|
| 876 |
+
} finally {
|
| 877 |
+
deadlines.mockRestore();
|
| 878 |
+
vi.useRealTimers();
|
| 879 |
+
}
|
| 880 |
+
});
|
| 881 |
+
|
| 882 |
it("counts a page that yielded almost no text", async () => {
|
| 883 |
respondWithHtml("<html><body><p>Accept cookies</p></body></html>");
|
| 884 |
|
|
|
|
| 1017 |
).toEqual({ skippedByBreaker: 1 });
|
| 1018 |
});
|
| 1019 |
|
| 1020 |
+
it("counts a DNS lookup that outlasts the deadline toward the box", async () => {
|
| 1021 |
+
const breaker = new PageReadHostBreaker(breakerOptions);
|
| 1022 |
+
lookupMock.mockImplementation(() => new Promise(() => {}));
|
| 1023 |
+
const deadlines = useFakeDeadlines();
|
| 1024 |
+
try {
|
| 1025 |
+
for (const page of ["a", "b", "c"]) {
|
| 1026 |
+
const counted = countOutcomes(
|
| 1027 |
+
`https://hanging-dns.example.com/${page}`,
|
| 1028 |
+
breaker,
|
| 1029 |
+
);
|
| 1030 |
+
await vi.advanceTimersByTimeAsync(6000);
|
| 1031 |
+
await counted;
|
| 1032 |
+
}
|
| 1033 |
+
} finally {
|
| 1034 |
+
deadlines.mockRestore();
|
| 1035 |
+
}
|
| 1036 |
+
|
| 1037 |
+
lookupMock.mockResolvedValue([{ address: "93.184.216.34", family: 4 }]);
|
| 1038 |
+
respondWithHtml(articlePage);
|
| 1039 |
+
expect(
|
| 1040 |
+
(await countOutcomes("https://hanging-dns.example.com/d", breaker))
|
| 1041 |
+
.skipped,
|
| 1042 |
+
).toEqual({ skippedByBreaker: 1 });
|
| 1043 |
+
expect(breaker.getOpens()).toBe(1);
|
| 1044 |
+
});
|
| 1045 |
+
|
| 1046 |
it("does not count a dead link or a thin page, and either one ends a run of refusals", async () => {
|
| 1047 |
const breaker = new PageReadHostBreaker(breakerOptions);
|
| 1048 |
|
server/pageContentService.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import { convert as convertHtmlToPlainText } from "html-to-text";
|
| 2 |
import { PDFParse } from "pdf-parse";
|
| 3 |
-
import { repository, version } from "../package.json" with { type: "json" };
|
| 4 |
import { scorePassages } from "./biEncoderService.ts";
|
|
|
|
| 5 |
import {
|
| 6 |
type PageReadHostBreaker,
|
| 7 |
pageReadHostBreaker,
|
|
@@ -12,7 +12,7 @@ import {
|
|
| 12 |
recordPageServedFromSearchExcerpts,
|
| 13 |
} from "./pageReadsSinceLastRestart.ts";
|
| 14 |
import { recallSearchExcerpts } from "./searchExcerptStore.ts";
|
| 15 |
-
import { resolvePublicUrl } from "./utils/publicUrl.ts";
|
| 16 |
import { readCappedBytes } from "./utils/streamUtils.ts";
|
| 17 |
|
| 18 |
const REQUEST_TIMEOUT_MS = 6000;
|
|
@@ -28,15 +28,13 @@ const OVERLAP_CHARS = 200;
|
|
| 28 |
const MAX_DENSE_PASSAGES = 256;
|
| 29 |
const RRF_K = 60;
|
| 30 |
|
| 31 |
-
const appName = repository.url.slice(repository.url.lastIndexOf("/") + 1);
|
| 32 |
-
|
| 33 |
const REQUEST_HEADERS = {
|
| 34 |
Accept: "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.8",
|
| 35 |
// No language preference: searches arrive in every language, and asking for
|
| 36 |
// English made a multilingual site serve its English edition for a query
|
| 37 |
// written in something else.
|
| 38 |
"Accept-Language": "*",
|
| 39 |
-
"User-Agent":
|
| 40 |
} as const;
|
| 41 |
|
| 42 |
const READABLE_CONTENT_TYPES =
|
|
@@ -551,6 +549,20 @@ async function readHop(url: URL, deadline: AbortSignal): Promise<HopResult> {
|
|
| 551 |
}
|
| 552 |
}
|
| 553 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 554 |
/**
|
| 555 |
* Follows redirects by hand so that every hop is validated: `redirect:
|
| 556 |
* "follow"` would let a public URL bounce the server into a private address.
|
|
@@ -574,8 +586,9 @@ async function downloadDocument(
|
|
| 574 |
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
| 575 |
let url: URL;
|
| 576 |
try {
|
| 577 |
-
url = await resolvePublicUrl(target);
|
| 578 |
-
} catch {
|
|
|
|
| 579 |
return { outcome: "blocked" };
|
| 580 |
}
|
| 581 |
|
|
|
|
| 1 |
import { convert as convertHtmlToPlainText } from "html-to-text";
|
| 2 |
import { PDFParse } from "pdf-parse";
|
|
|
|
| 3 |
import { scorePassages } from "./biEncoderService.ts";
|
| 4 |
+
import { OUTBOUND_USER_AGENT } from "./outboundUserAgent.ts";
|
| 5 |
import {
|
| 6 |
type PageReadHostBreaker,
|
| 7 |
pageReadHostBreaker,
|
|
|
|
| 12 |
recordPageServedFromSearchExcerpts,
|
| 13 |
} from "./pageReadsSinceLastRestart.ts";
|
| 14 |
import { recallSearchExcerpts } from "./searchExcerptStore.ts";
|
| 15 |
+
import { resolvePublicUrl, resolveWithinDeadline } from "./utils/publicUrl.ts";
|
| 16 |
import { readCappedBytes } from "./utils/streamUtils.ts";
|
| 17 |
|
| 18 |
const REQUEST_TIMEOUT_MS = 6000;
|
|
|
|
| 28 |
const MAX_DENSE_PASSAGES = 256;
|
| 29 |
const RRF_K = 60;
|
| 30 |
|
|
|
|
|
|
|
| 31 |
const REQUEST_HEADERS = {
|
| 32 |
Accept: "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.8",
|
| 33 |
// No language preference: searches arrive in every language, and asking for
|
| 34 |
// English made a multilingual site serve its English edition for a query
|
| 35 |
// written in something else.
|
| 36 |
"Accept-Language": "*",
|
| 37 |
+
"User-Agent": OUTBOUND_USER_AGENT,
|
| 38 |
} as const;
|
| 39 |
|
| 40 |
const READABLE_CONTENT_TYPES =
|
|
|
|
| 549 |
}
|
| 550 |
}
|
| 551 |
|
| 552 |
+
/**
|
| 553 |
+
* A lookup that runs out the deadline never reaches `admit`, so the host it
|
| 554 |
+
* was resolving is charged here: it cost the batch the whole wait, the way a
|
| 555 |
+
* read that hangs does. Admitting first keeps a half-open host to one probe.
|
| 556 |
+
*/
|
| 557 |
+
function chargeLookupTimeout(
|
| 558 |
+
target: string,
|
| 559 |
+
breaker: PageReadHostBreaker,
|
| 560 |
+
): DownloadResult {
|
| 561 |
+
const host = URL.parse(target)?.host;
|
| 562 |
+
if (host && breaker.admit(host)) breaker.settle(host, "timedOut");
|
| 563 |
+
return { outcome: "timedOut" };
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
/**
|
| 567 |
* Follows redirects by hand so that every hop is validated: `redirect:
|
| 568 |
* "follow"` would let a public URL bounce the server into a private address.
|
|
|
|
| 586 |
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
| 587 |
let url: URL;
|
| 588 |
try {
|
| 589 |
+
url = await resolveWithinDeadline(deadline, resolvePublicUrl(target));
|
| 590 |
+
} catch (error) {
|
| 591 |
+
if (isTimeout(error)) return chargeLookupTimeout(target, breaker);
|
| 592 |
return { outcome: "blocked" };
|
| 593 |
}
|
| 594 |
|
server/parseCommaSeparatedList.test.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import { parseCommaSeparatedList } from "./parseCommaSeparatedList";
|
| 3 |
+
|
| 4 |
+
describe("parseCommaSeparatedList", () => {
|
| 5 |
+
it("splits on commas", () => {
|
| 6 |
+
expect(parseCommaSeparatedList("a,b,c")).toEqual(["a", "b", "c"]);
|
| 7 |
+
});
|
| 8 |
+
|
| 9 |
+
it("trims whitespace around each entry", () => {
|
| 10 |
+
expect(parseCommaSeparatedList("localhost, example.com ")).toEqual([
|
| 11 |
+
"localhost",
|
| 12 |
+
"example.com",
|
| 13 |
+
]);
|
| 14 |
+
});
|
| 15 |
+
|
| 16 |
+
it("drops empty entries", () => {
|
| 17 |
+
expect(parseCommaSeparatedList("key1, key2,")).toEqual(["key1", "key2"]);
|
| 18 |
+
expect(parseCommaSeparatedList(",")).toEqual([]);
|
| 19 |
+
expect(parseCommaSeparatedList(" , ,")).toEqual([]);
|
| 20 |
+
});
|
| 21 |
+
|
| 22 |
+
it("returns an empty list for an unset or empty value", () => {
|
| 23 |
+
expect(parseCommaSeparatedList(undefined)).toEqual([]);
|
| 24 |
+
expect(parseCommaSeparatedList("")).toEqual([]);
|
| 25 |
+
});
|
| 26 |
+
});
|
server/parseCommaSeparatedList.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Splits a comma-separated environment value into its entries, trimming each
|
| 3 |
+
* one and dropping the empty ones. `.env` files commonly carry `A, B,`, and
|
| 4 |
+
* the spaces and the trailing comma are never part of an entry.
|
| 5 |
+
*/
|
| 6 |
+
export function parseCommaSeparatedList(value: string | undefined): string[] {
|
| 7 |
+
return (value ?? "")
|
| 8 |
+
.split(",")
|
| 9 |
+
.map((entry) => entry.trim())
|
| 10 |
+
.filter(Boolean);
|
| 11 |
+
}
|
server/searchEndpointServerHook.test.ts
CHANGED
|
@@ -939,3 +939,25 @@ describe("searchEndpointServerHook", () => {
|
|
| 939 |
});
|
| 940 |
});
|
| 941 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 939 |
});
|
| 940 |
});
|
| 941 |
});
|
| 942 |
+
|
| 943 |
+
describe("searchEndpointServerHook with a malformed Host header", () => {
|
| 944 |
+
it("answers 400 and keeps the handler promise from rejecting", async () => {
|
| 945 |
+
vi.mocked(handleTokenVerification).mockResolvedValue({
|
| 946 |
+
shouldContinue: true,
|
| 947 |
+
});
|
| 948 |
+
const request = {
|
| 949 |
+
url: "/search/text?q=cats&token=abc",
|
| 950 |
+
headers: { host: "bad host" },
|
| 951 |
+
} as unknown as IncomingMessage;
|
| 952 |
+
const response = createResponse();
|
| 953 |
+
const next = vi.fn();
|
| 954 |
+
|
| 955 |
+
await expect(
|
| 956 |
+
getRegisteredHandler()(request, response, next),
|
| 957 |
+
).resolves.toBeUndefined();
|
| 958 |
+
|
| 959 |
+
expect(response.statusCode).toBe(400);
|
| 960 |
+
expect(handleTokenVerification).not.toHaveBeenCalled();
|
| 961 |
+
expect(next).not.toHaveBeenCalled();
|
| 962 |
+
});
|
| 963 |
+
});
|
server/searchEndpointServerHook.ts
CHANGED
|
@@ -28,7 +28,8 @@ import {
|
|
| 28 |
recordSearchDuration,
|
| 29 |
type SearchType,
|
| 30 |
} from "./searchesSinceLastRestart.ts";
|
| 31 |
-
import { sendValidationError } from "./utils/httpResponse.ts";
|
|
|
|
| 32 |
import { fetchSearXNG, fetchSupplementarySearXNG } from "./webSearchService.ts";
|
| 33 |
|
| 34 |
const DEFAULT_SEARCH_LIMIT = 30;
|
|
@@ -178,7 +179,13 @@ export function searchEndpointServerHook<
|
|
| 178 |
server.middlewares.use(async (request, response, next) => {
|
| 179 |
if (!request.url?.startsWith("/search/")) return next();
|
| 180 |
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
// Verified before the parameters are read, matching `/page-content`: a
|
| 184 |
// malformed query from an unauthenticated caller has to cost the caller a
|
|
@@ -242,9 +249,6 @@ export function searchEndpointServerHook<
|
|
| 242 |
remainingMs,
|
| 243 |
);
|
| 244 |
incrementSearchesServedByFallback();
|
| 245 |
-
console.log(
|
| 246 |
-
"SearXNG failed, served text results from the fallback search",
|
| 247 |
-
);
|
| 248 |
} catch (fallbackError) {
|
| 249 |
incrementSearchesFailedOnFallback();
|
| 250 |
// Fixed text plus the error's message, which by construction
|
|
|
|
| 28 |
recordSearchDuration,
|
| 29 |
type SearchType,
|
| 30 |
} from "./searchesSinceLastRestart.ts";
|
| 31 |
+
import { sendJsonError, sendValidationError } from "./utils/httpResponse.ts";
|
| 32 |
+
import { parseRequestUrl } from "./utils/requestUrl.ts";
|
| 33 |
import { fetchSearXNG, fetchSupplementarySearXNG } from "./webSearchService.ts";
|
| 34 |
|
| 35 |
const DEFAULT_SEARCH_LIMIT = 30;
|
|
|
|
| 179 |
server.middlewares.use(async (request, response, next) => {
|
| 180 |
if (!request.url?.startsWith("/search/")) return next();
|
| 181 |
|
| 182 |
+
response.setHeader("Cache-Control", "no-store");
|
| 183 |
+
|
| 184 |
+
const url = parseRequestUrl(request);
|
| 185 |
+
if (!url) {
|
| 186 |
+
sendJsonError(response, 400, { error: "Malformed request" });
|
| 187 |
+
return;
|
| 188 |
+
}
|
| 189 |
|
| 190 |
// Verified before the parameters are read, matching `/page-content`: a
|
| 191 |
// malformed query from an unauthenticated caller has to cost the caller a
|
|
|
|
| 249 |
remainingMs,
|
| 250 |
);
|
| 251 |
incrementSearchesServedByFallback();
|
|
|
|
|
|
|
|
|
|
| 252 |
} catch (fallbackError) {
|
| 253 |
incrementSearchesFailedOnFallback();
|
| 254 |
// Fixed text plus the error's message, which by construction
|
server/statusEndpointServerHook.test.ts
CHANGED
|
@@ -59,6 +59,53 @@ function callStatus(): Promise<Record<string, unknown>> {
|
|
| 59 |
}
|
| 60 |
|
| 61 |
describe("statusEndpointServerHook", () => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
it("publishes the web search verdict and the per-engine tally", async () => {
|
| 63 |
const status = await callStatus();
|
| 64 |
|
|
@@ -101,7 +148,7 @@ describe("statusEndpointServerHook", () => {
|
|
| 101 |
Object.keys(
|
| 102 |
(status.searches as { fallbackProviders: object }).fallbackProviders,
|
| 103 |
),
|
| 104 |
-
).toEqual(["parallel", "youcom"]);
|
| 105 |
});
|
| 106 |
|
| 107 |
it("publishes the page-read circuit count beside the outcome counters", async () => {
|
|
@@ -135,3 +182,36 @@ describe("statusEndpointServerHook", () => {
|
|
| 135 |
}
|
| 136 |
});
|
| 137 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
}
|
| 60 |
|
| 61 |
describe("statusEndpointServerHook", () => {
|
| 62 |
+
it.each(["/statuses", "/statusX?token=abc", "/status/extra"])(
|
| 63 |
+
"passes through %s, which is not the /status route",
|
| 64 |
+
async (url) => {
|
| 65 |
+
const use = vi.fn();
|
| 66 |
+
statusEndpointServerHook({
|
| 67 |
+
middlewares: { use },
|
| 68 |
+
config: { define: { VITE_BUILD_DATE_TIME: new Date().toISOString() } },
|
| 69 |
+
} as unknown as Parameters<typeof statusEndpointServerHook>[0]);
|
| 70 |
+
const response = {
|
| 71 |
+
setHeader: vi.fn(),
|
| 72 |
+
end: vi.fn(),
|
| 73 |
+
} as unknown as RecordedResponse;
|
| 74 |
+
const next = vi.fn();
|
| 75 |
+
|
| 76 |
+
await (use.mock.calls[0][0] as Handler)(
|
| 77 |
+
{ url, headers: {} } as unknown as IncomingMessage,
|
| 78 |
+
response,
|
| 79 |
+
next,
|
| 80 |
+
);
|
| 81 |
+
|
| 82 |
+
expect(next).toHaveBeenCalledTimes(1);
|
| 83 |
+
expect(response.end).not.toHaveBeenCalled();
|
| 84 |
+
},
|
| 85 |
+
);
|
| 86 |
+
|
| 87 |
+
it("still answers /status with a query string", async () => {
|
| 88 |
+
const use = vi.fn();
|
| 89 |
+
statusEndpointServerHook({
|
| 90 |
+
middlewares: { use },
|
| 91 |
+
config: { define: { VITE_BUILD_DATE_TIME: new Date().toISOString() } },
|
| 92 |
+
} as unknown as Parameters<typeof statusEndpointServerHook>[0]);
|
| 93 |
+
const response = {
|
| 94 |
+
setHeader: vi.fn(),
|
| 95 |
+
end: vi.fn(),
|
| 96 |
+
} as unknown as RecordedResponse;
|
| 97 |
+
const next = vi.fn();
|
| 98 |
+
|
| 99 |
+
await (use.mock.calls[0][0] as Handler)(
|
| 100 |
+
{ url: "/status?probe=1", headers: {} } as unknown as IncomingMessage,
|
| 101 |
+
response,
|
| 102 |
+
next,
|
| 103 |
+
);
|
| 104 |
+
|
| 105 |
+
expect(next).not.toHaveBeenCalled();
|
| 106 |
+
expect(response.end).toHaveBeenCalledTimes(1);
|
| 107 |
+
});
|
| 108 |
+
|
| 109 |
it("publishes the web search verdict and the per-engine tally", async () => {
|
| 110 |
const status = await callStatus();
|
| 111 |
|
|
|
|
| 148 |
Object.keys(
|
| 149 |
(status.searches as { fallbackProviders: object }).fallbackProviders,
|
| 150 |
),
|
| 151 |
+
).toEqual(["parallel", "youcom", "keenable"]);
|
| 152 |
});
|
| 153 |
|
| 154 |
it("publishes the page-read circuit count beside the outcome counters", async () => {
|
|
|
|
| 182 |
}
|
| 183 |
});
|
| 184 |
});
|
| 185 |
+
|
| 186 |
+
describe("statusEndpointServerHook with a malformed build define", () => {
|
| 187 |
+
it("answers 500 instead of rejecting the middleware", async () => {
|
| 188 |
+
const use = vi.fn();
|
| 189 |
+
statusEndpointServerHook({
|
| 190 |
+
middlewares: { use },
|
| 191 |
+
config: {
|
| 192 |
+
define: {
|
| 193 |
+
VITE_BUILD_DATE_TIME: new Date().toISOString(),
|
| 194 |
+
VITE_COMMIT_SHORT_HASH: "{not json",
|
| 195 |
+
},
|
| 196 |
+
},
|
| 197 |
+
} as unknown as Parameters<typeof statusEndpointServerHook>[0]);
|
| 198 |
+
const response = {
|
| 199 |
+
statusCode: 200,
|
| 200 |
+
setHeader: vi.fn(),
|
| 201 |
+
end: vi.fn(),
|
| 202 |
+
} as unknown as RecordedResponse;
|
| 203 |
+
|
| 204 |
+
await expect(
|
| 205 |
+
(use.mock.calls[0][0] as Handler)(
|
| 206 |
+
{ url: "/status", headers: {} } as unknown as IncomingMessage,
|
| 207 |
+
response,
|
| 208 |
+
() => undefined,
|
| 209 |
+
),
|
| 210 |
+
).resolves.toBeUndefined();
|
| 211 |
+
|
| 212 |
+
expect(response.statusCode).toBe(500);
|
| 213 |
+
expect(JSON.parse(response.end.mock.calls[0][0])).toEqual({
|
| 214 |
+
error: "Malformed VITE_COMMIT_SHORT_HASH build define",
|
| 215 |
+
});
|
| 216 |
+
});
|
| 217 |
+
});
|
server/statusEndpointServerHook.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
| 22 |
getThumbnailStats,
|
| 23 |
getUnresponsiveEngineStats,
|
| 24 |
} from "./searchesSinceLastRestart.ts";
|
|
|
|
| 25 |
import {
|
| 26 |
getActiveSessionsAmount,
|
| 27 |
getVerifiedTokensAmount,
|
|
@@ -39,6 +40,11 @@ export function statusEndpointServerHook<
|
|
| 39 |
>(server: T) {
|
| 40 |
server.middlewares.use(async (request, response, next) => {
|
| 41 |
if (!request.url?.startsWith("/status")) return next();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
const sessions = getVerifiedTokensAmount();
|
| 44 |
const textualSearches = getTextualSearchesSinceLastRestart();
|
|
@@ -66,7 +72,12 @@ export function statusEndpointServerHook<
|
|
| 66 |
server.config.define?.VITE_COMMIT_SHORT_HASH || '""',
|
| 67 |
);
|
| 68 |
} catch {
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
}
|
| 71 |
|
| 72 |
const status = {
|
|
|
|
| 22 |
getThumbnailStats,
|
| 23 |
getUnresponsiveEngineStats,
|
| 24 |
} from "./searchesSinceLastRestart.ts";
|
| 25 |
+
import { sendJsonError } from "./utils/httpResponse.ts";
|
| 26 |
import {
|
| 27 |
getActiveSessionsAmount,
|
| 28 |
getVerifiedTokensAmount,
|
|
|
|
| 40 |
>(server: T) {
|
| 41 |
server.middlewares.use(async (request, response, next) => {
|
| 42 |
if (!request.url?.startsWith("/status")) return next();
|
| 43 |
+
if (new URL(request.url, "http://localhost").pathname !== "/status") {
|
| 44 |
+
return next();
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
response.setHeader("Cache-Control", "no-store");
|
| 48 |
|
| 49 |
const sessions = getVerifiedTokensAmount();
|
| 50 |
const textualSearches = getTextualSearchesSinceLastRestart();
|
|
|
|
| 72 |
server.config.define?.VITE_COMMIT_SHORT_HASH || '""',
|
| 73 |
);
|
| 74 |
} catch {
|
| 75 |
+
// Throwing here would reject the async middleware, which Node treats as
|
| 76 |
+
// an unhandled rejection and exits the process.
|
| 77 |
+
sendJsonError(response, 500, {
|
| 78 |
+
error: "Malformed VITE_COMMIT_SHORT_HASH build define",
|
| 79 |
+
});
|
| 80 |
+
return;
|
| 81 |
}
|
| 82 |
|
| 83 |
const status = {
|
server/thumbnailEndpointServerHook.test.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
|
|
| 2 |
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
| 3 |
|
| 4 |
const lookupMock = vi.hoisted(() => vi.fn());
|
|
@@ -112,6 +113,9 @@ function imageResponse(
|
|
| 112 |
}
|
| 113 |
|
| 114 |
describe("thumbnailEndpointServerHook", () => {
|
|
|
|
|
|
|
|
|
|
| 115 |
beforeEach(() => {
|
| 116 |
vi.clearAllMocks();
|
| 117 |
pinnedRequestMock.mockReset();
|
|
@@ -119,10 +123,15 @@ describe("thumbnailEndpointServerHook", () => {
|
|
| 119 |
vi.mocked(handleTokenVerification).mockResolvedValue({
|
| 120 |
shouldContinue: true,
|
| 121 |
});
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
});
|
| 124 |
|
| 125 |
afterEach(() => {
|
|
|
|
| 126 |
vi.restoreAllMocks();
|
| 127 |
});
|
| 128 |
|
|
@@ -136,6 +145,23 @@ describe("thumbnailEndpointServerHook", () => {
|
|
| 136 |
expect(pinnedRequestMock).not.toHaveBeenCalled();
|
| 137 |
});
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
it("stops processing when token verification fails", async () => {
|
| 140 |
vi.mocked(handleTokenVerification).mockResolvedValue({
|
| 141 |
shouldContinue: false,
|
|
@@ -361,6 +387,24 @@ describe("thumbnailEndpointServerHook", () => {
|
|
| 361 |
expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
|
| 362 |
});
|
| 363 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
it("answers 502 when the upstream answer is not an accepted image type", async () => {
|
| 365 |
pinnedRequestMock.mockResolvedValue(
|
| 366 |
fakeIncoming(new TextEncoder().encode("<html></html>"), 200, {
|
|
@@ -530,7 +574,9 @@ describe("thumbnailEndpointServerHook", () => {
|
|
| 530 |
expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
|
| 531 |
});
|
| 532 |
|
| 533 |
-
it("
|
|
|
|
|
|
|
| 534 |
const bigBody = new Uint8Array(600_000).fill(7);
|
| 535 |
pinnedRequestMock.mockResolvedValue(imageResponse(bigBody));
|
| 536 |
const handler = getRegisteredHandler();
|
|
@@ -542,10 +588,53 @@ describe("thumbnailEndpointServerHook", () => {
|
|
| 542 |
vi.fn(),
|
| 543 |
);
|
| 544 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
expect(response.statusCode).toBe(200);
|
| 546 |
const body = response.end.mock.calls[0][0] as Buffer;
|
| 547 |
-
// The cap is 500_000 bytes; a 600_000-byte body must be truncated.
|
| 548 |
expect(body.length).toBe(500_000);
|
|
|
|
| 549 |
});
|
| 550 |
|
| 551 |
it("evicts the least recently used entry, not the least recently loaded one", async () => {
|
|
@@ -584,3 +673,23 @@ describe("thumbnailEndpointServerHook", () => {
|
|
| 584 |
expect(fetched(secondUrl)).toBe(2);
|
| 585 |
});
|
| 586 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import type { IncomingMessage, ServerResponse } from "node:http";
|
| 2 |
+
import debug from "debug";
|
| 3 |
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
| 4 |
|
| 5 |
const lookupMock = vi.hoisted(() => vi.fn());
|
|
|
|
| 113 |
}
|
| 114 |
|
| 115 |
describe("thumbnailEndpointServerHook", () => {
|
| 116 |
+
let logLines: string[];
|
| 117 |
+
let originalLog: typeof debug.log;
|
| 118 |
+
|
| 119 |
beforeEach(() => {
|
| 120 |
vi.clearAllMocks();
|
| 121 |
pinnedRequestMock.mockReset();
|
|
|
|
| 123 |
vi.mocked(handleTokenVerification).mockResolvedValue({
|
| 124 |
shouldContinue: true,
|
| 125 |
});
|
| 126 |
+
logLines = [];
|
| 127 |
+
originalLog = debug.log;
|
| 128 |
+
debug.log = (...args: unknown[]) => {
|
| 129 |
+
logLines.push(args.map(String).join(" "));
|
| 130 |
+
};
|
| 131 |
});
|
| 132 |
|
| 133 |
afterEach(() => {
|
| 134 |
+
debug.log = originalLog;
|
| 135 |
vi.restoreAllMocks();
|
| 136 |
});
|
| 137 |
|
|
|
|
| 145 |
expect(pinnedRequestMock).not.toHaveBeenCalled();
|
| 146 |
});
|
| 147 |
|
| 148 |
+
it.each([
|
| 149 |
+
"/thumbnails",
|
| 150 |
+
"/thumbnailX?token=abc",
|
| 151 |
+
"/thumbnail/extra?token=abc",
|
| 152 |
+
])("passes through %s, which is not the /thumbnail route", async (url) => {
|
| 153 |
+
const handler = getRegisteredHandler();
|
| 154 |
+
const next = vi.fn();
|
| 155 |
+
const response = createResponse();
|
| 156 |
+
|
| 157 |
+
await handler(createRequest(url), response, next);
|
| 158 |
+
|
| 159 |
+
expect(next).toHaveBeenCalledTimes(1);
|
| 160 |
+
expect(response.end).not.toHaveBeenCalled();
|
| 161 |
+
expect(handleTokenVerification).not.toHaveBeenCalled();
|
| 162 |
+
expect(pinnedRequestMock).not.toHaveBeenCalled();
|
| 163 |
+
});
|
| 164 |
+
|
| 165 |
it("stops processing when token verification fails", async () => {
|
| 166 |
vi.mocked(handleTokenVerification).mockResolvedValue({
|
| 167 |
shouldContinue: false,
|
|
|
|
| 387 |
expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
|
| 388 |
});
|
| 389 |
|
| 390 |
+
it("logs why a fetch failed, never the thumbnail URL or its host", async () => {
|
| 391 |
+
pinnedRequestMock.mockResolvedValue(
|
| 392 |
+
fakeIncoming(new Uint8Array(), 403, {}),
|
| 393 |
+
);
|
| 394 |
+
const handler = getRegisteredHandler();
|
| 395 |
+
const thumbnailUrl = publicThumbnailUrl();
|
| 396 |
+
|
| 397 |
+
await handler(
|
| 398 |
+
createRequest(requestUrlFor(thumbnailUrl)),
|
| 399 |
+
createResponse(),
|
| 400 |
+
vi.fn(),
|
| 401 |
+
);
|
| 402 |
+
|
| 403 |
+
const output = logLines.join("\n");
|
| 404 |
+
expect(output).toContain("Thumbnail fetch failed: HTTP 403");
|
| 405 |
+
expect(output).not.toContain(new URL(thumbnailUrl).hostname);
|
| 406 |
+
});
|
| 407 |
+
|
| 408 |
it("answers 502 when the upstream answer is not an accepted image type", async () => {
|
| 409 |
pinnedRequestMock.mockResolvedValue(
|
| 410 |
fakeIncoming(new TextEncoder().encode("<html></html>"), 200, {
|
|
|
|
| 574 |
expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
|
| 575 |
});
|
| 576 |
|
| 577 |
+
it("answers 502 instead of serving a body over the byte cap cut off", async () => {
|
| 578 |
+
// The cap is 500_000 bytes; the first 500_000 of this body would decode
|
| 579 |
+
// as a damaged image.
|
| 580 |
const bigBody = new Uint8Array(600_000).fill(7);
|
| 581 |
pinnedRequestMock.mockResolvedValue(imageResponse(bigBody));
|
| 582 |
const handler = getRegisteredHandler();
|
|
|
|
| 588 |
vi.fn(),
|
| 589 |
);
|
| 590 |
|
| 591 |
+
expect(response.statusCode).toBe(502);
|
| 592 |
+
expect(response.setHeader).toHaveBeenCalledWith(
|
| 593 |
+
"Cache-Control",
|
| 594 |
+
"no-store",
|
| 595 |
+
);
|
| 596 |
+
expect(response.end).toHaveBeenCalledWith(
|
| 597 |
+
JSON.stringify({ error: "Thumbnail could not be fetched" }),
|
| 598 |
+
);
|
| 599 |
+
expect(recordThumbnailDropped).toHaveBeenCalledTimes(1);
|
| 600 |
+
expect(logLines.join("\n")).toContain(
|
| 601 |
+
"Thumbnail fetch failed: larger than 500000 bytes",
|
| 602 |
+
);
|
| 603 |
+
});
|
| 604 |
+
|
| 605 |
+
it("does not cache a body over the byte cap, so the next load fetches again", async () => {
|
| 606 |
+
const url = publicThumbnailUrl();
|
| 607 |
+
pinnedRequestMock
|
| 608 |
+
.mockResolvedValueOnce(imageResponse(new Uint8Array(600_000).fill(7)))
|
| 609 |
+
.mockResolvedValueOnce(imageResponse());
|
| 610 |
+
const handler = getRegisteredHandler();
|
| 611 |
+
|
| 612 |
+
const first = createResponse();
|
| 613 |
+
await handler(createRequest(requestUrlFor(url)), first, vi.fn());
|
| 614 |
+
expect(first.statusCode).toBe(502);
|
| 615 |
+
|
| 616 |
+
const second = createResponse();
|
| 617 |
+
await handler(createRequest(requestUrlFor(url)), second, vi.fn());
|
| 618 |
+
expect(second.statusCode).toBe(200);
|
| 619 |
+
expect(pinnedRequestMock).toHaveBeenCalledTimes(2);
|
| 620 |
+
});
|
| 621 |
+
|
| 622 |
+
it("serves a body of exactly the byte cap", async () => {
|
| 623 |
+
const capSizedBody = new Uint8Array(500_000).fill(7);
|
| 624 |
+
pinnedRequestMock.mockResolvedValue(imageResponse(capSizedBody));
|
| 625 |
+
const handler = getRegisteredHandler();
|
| 626 |
+
const response = createResponse();
|
| 627 |
+
|
| 628 |
+
await handler(
|
| 629 |
+
createRequest(requestUrlFor(publicThumbnailUrl())),
|
| 630 |
+
response,
|
| 631 |
+
vi.fn(),
|
| 632 |
+
);
|
| 633 |
+
|
| 634 |
expect(response.statusCode).toBe(200);
|
| 635 |
const body = response.end.mock.calls[0][0] as Buffer;
|
|
|
|
| 636 |
expect(body.length).toBe(500_000);
|
| 637 |
+
expect(recordThumbnailDropped).not.toHaveBeenCalled();
|
| 638 |
});
|
| 639 |
|
| 640 |
it("evicts the least recently used entry, not the least recently loaded one", async () => {
|
|
|
|
| 673 |
expect(fetched(secondUrl)).toBe(2);
|
| 674 |
});
|
| 675 |
});
|
| 676 |
+
|
| 677 |
+
describe("thumbnailEndpointServerHook with a malformed Host header", () => {
|
| 678 |
+
it("answers 400 instead of 500", async () => {
|
| 679 |
+
vi.mocked(handleTokenVerification).mockClear();
|
| 680 |
+
const request = {
|
| 681 |
+
url: "/thumbnail?u=https%3A%2F%2Fexample.com%2Fa.png&token=abc",
|
| 682 |
+
headers: { host: "bad host" },
|
| 683 |
+
} as unknown as IncomingMessage;
|
| 684 |
+
const response = createResponse();
|
| 685 |
+
const next = vi.fn();
|
| 686 |
+
|
| 687 |
+
await expect(
|
| 688 |
+
getRegisteredHandler()(request, response, next),
|
| 689 |
+
).resolves.toBeUndefined();
|
| 690 |
+
|
| 691 |
+
expect(response.statusCode).toBe(400);
|
| 692 |
+
expect(handleTokenVerification).not.toHaveBeenCalled();
|
| 693 |
+
expect(next).not.toHaveBeenCalled();
|
| 694 |
+
});
|
| 695 |
+
});
|
server/thumbnailEndpointServerHook.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
| 1 |
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
|
|
|
|
|
| 2 |
import type { PreviewServer, ViteDevServer } from "vite";
|
| 3 |
import { handleTokenVerification } from "./handleTokenVerification.ts";
|
| 4 |
import {
|
|
@@ -10,10 +12,18 @@ import {
|
|
| 10 |
readCappedStream,
|
| 11 |
requestPinnedToVettedAddress,
|
| 12 |
} from "./utils/pinnedFetch.ts";
|
| 13 |
-
import {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
import { safeEndResponse } from "./utils/streamUtils.ts";
|
| 15 |
import { thumbnailRateLimiter } from "./verifyTokenAndRateLimit.ts";
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
/**
|
| 18 |
* Where each SSRF defense of this endpoint lives:
|
| 19 |
*
|
|
@@ -36,7 +46,8 @@ import { thumbnailRateLimiter } from "./verifyTokenAndRateLimit.ts";
|
|
| 36 |
* shared deadline.
|
| 37 |
* - Content-Type: raster-only allowlist below; SVG is deliberately
|
| 38 |
* excluded because served same-origin it is a script-carrying document.
|
| 39 |
-
* - Response size: `MAX_THUMBNAIL_BYTES` via `readCappedStream`
|
|
|
|
| 40 |
* - Timeout: `THUMBNAIL_TIMEOUT_MS`, shared across DNS and every hop.
|
| 41 |
* - Rate limiting: per client IP via `thumbnailRateLimiter`, a dedicated
|
| 42 |
* 60-per-10s budget so a grid of tiles cannot exhaust the search
|
|
@@ -153,39 +164,6 @@ function isRedirect(status: number): boolean {
|
|
| 153 |
return status >= 300 && status < 400 && status !== 304;
|
| 154 |
}
|
| 155 |
|
| 156 |
-
/**
|
| 157 |
-
* `resolvePublicUrlAndAddress`'s DNS lookup does not take a signal, so it
|
| 158 |
-
* is raced against the hop deadline: a hanging resolver would otherwise
|
| 159 |
-
* add its own timeout on top of the one that is documented to bound the
|
| 160 |
-
* whole chain.
|
| 161 |
-
*/
|
| 162 |
-
function timeoutError(): Error {
|
| 163 |
-
const error = new Error("The operation was aborted");
|
| 164 |
-
error.name = "TimeoutError";
|
| 165 |
-
return error;
|
| 166 |
-
}
|
| 167 |
-
|
| 168 |
-
function resolveWithinDeadline<T>(
|
| 169 |
-
deadline: AbortSignal,
|
| 170 |
-
work: Promise<T>,
|
| 171 |
-
): Promise<T> {
|
| 172 |
-
if (deadline.aborted) return Promise.reject(timeoutError());
|
| 173 |
-
return new Promise<T>((resolve, reject) => {
|
| 174 |
-
const onAbort = () => reject(timeoutError());
|
| 175 |
-
deadline.addEventListener("abort", onAbort, { once: true });
|
| 176 |
-
work.then(
|
| 177 |
-
(value) => {
|
| 178 |
-
deadline.removeEventListener("abort", onAbort);
|
| 179 |
-
resolve(value);
|
| 180 |
-
},
|
| 181 |
-
(error) => {
|
| 182 |
-
deadline.removeEventListener("abort", onAbort);
|
| 183 |
-
reject(error);
|
| 184 |
-
},
|
| 185 |
-
);
|
| 186 |
-
});
|
| 187 |
-
}
|
| 188 |
-
|
| 189 |
/**
|
| 190 |
* Follows redirects by hand so that every hop is validated and pinned, the
|
| 191 |
* way `pageContentService` follows them: `redirect: "follow"` would let a
|
|
@@ -263,8 +241,12 @@ async function fetchThumbnail(rawUrl: string): Promise<ThumbnailOutcome> {
|
|
| 263 |
}
|
| 264 |
|
| 265 |
let bytes: Uint8Array;
|
|
|
|
| 266 |
try {
|
| 267 |
-
({ bytes } = await readCappedStream(
|
|
|
|
|
|
|
|
|
|
| 268 |
} catch (error) {
|
| 269 |
return {
|
| 270 |
kind: "failed",
|
|
@@ -272,6 +254,16 @@ async function fetchThumbnail(rawUrl: string): Promise<ThumbnailOutcome> {
|
|
| 272 |
};
|
| 273 |
}
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
if (bytes.byteLength === 0) {
|
| 276 |
return { kind: "failed", reason: "empty body" };
|
| 277 |
}
|
|
@@ -325,9 +317,16 @@ export function thumbnailEndpointServerHook<
|
|
| 325 |
>(server: T) {
|
| 326 |
server.middlewares.use(async (request, response, next) => {
|
| 327 |
if (!request.url?.startsWith("/thumbnail")) return next();
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
try {
|
| 330 |
-
const url =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
const { shouldContinue } = await handleTokenVerification(
|
| 333 |
url.searchParams.get("token"),
|
|
@@ -376,7 +375,7 @@ export function thumbnailEndpointServerHook<
|
|
| 376 |
|
| 377 |
if (outcome.kind === "failed") {
|
| 378 |
recordThumbnailDropped();
|
| 379 |
-
|
| 380 |
serveError(response, 502, "Thumbnail could not be fetched");
|
| 381 |
return;
|
| 382 |
}
|
|
|
|
| 1 |
import type { IncomingMessage, ServerResponse } from "node:http";
|
| 2 |
+
import { basename } from "node:path";
|
| 3 |
+
import debug from "debug";
|
| 4 |
import type { PreviewServer, ViteDevServer } from "vite";
|
| 5 |
import { handleTokenVerification } from "./handleTokenVerification.ts";
|
| 6 |
import {
|
|
|
|
| 12 |
readCappedStream,
|
| 13 |
requestPinnedToVettedAddress,
|
| 14 |
} from "./utils/pinnedFetch.ts";
|
| 15 |
+
import {
|
| 16 |
+
resolvePublicUrlAndAddress,
|
| 17 |
+
resolveWithinDeadline,
|
| 18 |
+
} from "./utils/publicUrl.ts";
|
| 19 |
+
import { parseRequestUrl } from "./utils/requestUrl.ts";
|
| 20 |
import { safeEndResponse } from "./utils/streamUtils.ts";
|
| 21 |
import { thumbnailRateLimiter } from "./verifyTokenAndRateLimit.ts";
|
| 22 |
|
| 23 |
+
const fileName = basename(import.meta.url);
|
| 24 |
+
const printMessage = debug(fileName);
|
| 25 |
+
printMessage.enabled = true;
|
| 26 |
+
|
| 27 |
/**
|
| 28 |
* Where each SSRF defense of this endpoint lives:
|
| 29 |
*
|
|
|
|
| 46 |
* shared deadline.
|
| 47 |
* - Content-Type: raster-only allowlist below; SVG is deliberately
|
| 48 |
* excluded because served same-origin it is a script-carrying document.
|
| 49 |
+
* - Response size: `MAX_THUMBNAIL_BYTES` via `readCappedStream`; a body
|
| 50 |
+
* over the cap is refused, never served or cached cut off.
|
| 51 |
* - Timeout: `THUMBNAIL_TIMEOUT_MS`, shared across DNS and every hop.
|
| 52 |
* - Rate limiting: per client IP via `thumbnailRateLimiter`, a dedicated
|
| 53 |
* 60-per-10s budget so a grid of tiles cannot exhaust the search
|
|
|
|
| 164 |
return status >= 300 && status < 400 && status !== 304;
|
| 165 |
}
|
| 166 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
/**
|
| 168 |
* Follows redirects by hand so that every hop is validated and pinned, the
|
| 169 |
* way `pageContentService` follows them: `redirect: "follow"` would let a
|
|
|
|
| 241 |
}
|
| 242 |
|
| 243 |
let bytes: Uint8Array;
|
| 244 |
+
let truncated: boolean;
|
| 245 |
try {
|
| 246 |
+
({ bytes, truncated } = await readCappedStream(
|
| 247 |
+
response,
|
| 248 |
+
MAX_THUMBNAIL_BYTES,
|
| 249 |
+
));
|
| 250 |
} catch (error) {
|
| 251 |
return {
|
| 252 |
kind: "failed",
|
|
|
|
| 254 |
};
|
| 255 |
}
|
| 256 |
|
| 257 |
+
// An image cut at the cap is a damaged image: a baseline JPEG loses
|
| 258 |
+
// everything below the cut, other formats may not decode at all. Served,
|
| 259 |
+
// it would also sit in the LRU and the browser cache for an hour.
|
| 260 |
+
if (truncated) {
|
| 261 |
+
return {
|
| 262 |
+
kind: "failed",
|
| 263 |
+
reason: `larger than ${MAX_THUMBNAIL_BYTES} bytes`,
|
| 264 |
+
};
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
if (bytes.byteLength === 0) {
|
| 268 |
return { kind: "failed", reason: "empty body" };
|
| 269 |
}
|
|
|
|
| 317 |
>(server: T) {
|
| 318 |
server.middlewares.use(async (request, response, next) => {
|
| 319 |
if (!request.url?.startsWith("/thumbnail")) return next();
|
| 320 |
+
if (new URL(request.url, "http://localhost").pathname !== "/thumbnail") {
|
| 321 |
+
return next();
|
| 322 |
+
}
|
| 323 |
|
| 324 |
try {
|
| 325 |
+
const url = parseRequestUrl(request);
|
| 326 |
+
if (!url) {
|
| 327 |
+
serveError(response, 400, "Malformed request");
|
| 328 |
+
return;
|
| 329 |
+
}
|
| 330 |
|
| 331 |
const { shouldContinue } = await handleTokenVerification(
|
| 332 |
url.searchParams.get("token"),
|
|
|
|
| 375 |
|
| 376 |
if (outcome.kind === "failed") {
|
| 377 |
recordThumbnailDropped();
|
| 378 |
+
printMessage(`Thumbnail fetch failed: ${outcome.reason}`);
|
| 379 |
serveError(response, 502, "Thumbnail could not be fetched");
|
| 380 |
return;
|
| 381 |
}
|
server/utils/pinnedFetch.test.ts
CHANGED
|
@@ -145,13 +145,15 @@ describe("requestPinnedToVettedAddress", () => {
|
|
| 145 |
expect(httpsRequestMock).not.toHaveBeenCalled();
|
| 146 |
});
|
| 147 |
|
| 148 |
-
it("dials the pinned address end-to-end while the server sees the original Host", async () => {
|
| 149 |
// pinned-host.test has no DNS record: the request can only succeed if
|
| 150 |
// the socket goes where the pin says, not where a resolver would.
|
| 151 |
let seenHost = "";
|
|
|
|
| 152 |
let seenTarget = "";
|
| 153 |
const server = http.createServer((request, response) => {
|
| 154 |
seenHost = request.headers.host ?? "";
|
|
|
|
| 155 |
seenTarget = request.url ?? "";
|
| 156 |
response.writeHead(200, { "content-type": "image/png" });
|
| 157 |
response.end(Buffer.from([9, 8, 7]));
|
|
@@ -169,6 +171,10 @@ describe("requestPinnedToVettedAddress", () => {
|
|
| 169 |
expect(response.statusCode).toBe(200);
|
| 170 |
expect(Array.from(bytes)).toEqual([9, 8, 7]);
|
| 171 |
expect(seenHost).toBe(`pinned-host.test:${port}`);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
expect(seenTarget).toBe("/img.png?v=1");
|
| 173 |
} finally {
|
| 174 |
server.close();
|
|
|
|
| 145 |
expect(httpsRequestMock).not.toHaveBeenCalled();
|
| 146 |
});
|
| 147 |
|
| 148 |
+
it("dials the pinned address end-to-end while the server sees the original Host and the User-Agent", async () => {
|
| 149 |
// pinned-host.test has no DNS record: the request can only succeed if
|
| 150 |
// the socket goes where the pin says, not where a resolver would.
|
| 151 |
let seenHost = "";
|
| 152 |
+
let seenUserAgent = "";
|
| 153 |
let seenTarget = "";
|
| 154 |
const server = http.createServer((request, response) => {
|
| 155 |
seenHost = request.headers.host ?? "";
|
| 156 |
+
seenUserAgent = request.headers["user-agent"] ?? "";
|
| 157 |
seenTarget = request.url ?? "";
|
| 158 |
response.writeHead(200, { "content-type": "image/png" });
|
| 159 |
response.end(Buffer.from([9, 8, 7]));
|
|
|
|
| 171 |
expect(response.statusCode).toBe(200);
|
| 172 |
expect(Array.from(bytes)).toEqual([9, 8, 7]);
|
| 173 |
expect(seenHost).toBe(`pinned-host.test:${port}`);
|
| 174 |
+
// upload.wikimedia.org answers a request without a User-Agent with 403.
|
| 175 |
+
expect(seenUserAgent).toMatch(
|
| 176 |
+
/^Mozilla\/5\.0 \(compatible; MiniSearch\/[^;]+; \+https:\/\/github\.com\/felladrin\/MiniSearch\)$/,
|
| 177 |
+
);
|
| 178 |
expect(seenTarget).toBe("/img.png?v=1");
|
| 179 |
} finally {
|
| 180 |
server.close();
|
server/utils/pinnedFetch.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { IncomingMessage } from "node:http";
|
|
| 2 |
import http from "node:http";
|
| 3 |
import https from "node:https";
|
| 4 |
import { isIP } from "node:net";
|
|
|
|
| 5 |
|
| 6 |
/**
|
| 7 |
* What the capped reader needs from a response body: an async stream of
|
|
@@ -22,7 +23,9 @@ export interface CappedReadable extends AsyncIterable<Uint8Array> {
|
|
| 22 |
* The original hostname survives the pin three ways: it stays the request's
|
| 23 |
* `hostname`, so TLS SNI and certificate verification run against it, not
|
| 24 |
* against the IP being dialled, and the `Host` header is set explicitly so
|
| 25 |
-
* virtual-host routing is unaffected.
|
|
|
|
|
|
|
| 26 |
*
|
| 27 |
* @throws When the protocol is not http(s) or the request fails
|
| 28 |
*/
|
|
@@ -51,7 +54,7 @@ export function requestPinnedToVettedAddress(
|
|
| 51 |
// SNI and certificate verification follow the hostname, not the pinned
|
| 52 |
// address, so a wrong-host certificate still fails the request.
|
| 53 |
servername: isTls ? hostname : undefined,
|
| 54 |
-
headers: { Host: hostHeader },
|
| 55 |
// The pin itself: the socket connects to the vetted address and no
|
| 56 |
// resolver is consulted, so the address checked is the address reached.
|
| 57 |
// Node's Happy Eyeballs path (autoSelectFamily, on by default since
|
|
|
|
| 2 |
import http from "node:http";
|
| 3 |
import https from "node:https";
|
| 4 |
import { isIP } from "node:net";
|
| 5 |
+
import { OUTBOUND_USER_AGENT } from "../outboundUserAgent.ts";
|
| 6 |
|
| 7 |
/**
|
| 8 |
* What the capped reader needs from a response body: an async stream of
|
|
|
|
| 23 |
* The original hostname survives the pin three ways: it stays the request's
|
| 24 |
* `hostname`, so TLS SNI and certificate verification run against it, not
|
| 25 |
* against the IP being dialled, and the `Host` header is set explicitly so
|
| 26 |
+
* virtual-host routing is unaffected. Every request also carries the
|
| 27 |
+
* server's `User-Agent`, because some image hosts refuse a request without
|
| 28 |
+
* one (upload.wikimedia.org answers 403).
|
| 29 |
*
|
| 30 |
* @throws When the protocol is not http(s) or the request fails
|
| 31 |
*/
|
|
|
|
| 54 |
// SNI and certificate verification follow the hostname, not the pinned
|
| 55 |
// address, so a wrong-host certificate still fails the request.
|
| 56 |
servername: isTls ? hostname : undefined,
|
| 57 |
+
headers: { Host: hostHeader, "User-Agent": OUTBOUND_USER_AGENT },
|
| 58 |
// The pin itself: the socket connects to the vetted address and no
|
| 59 |
// resolver is consulted, so the address checked is the address reached.
|
| 60 |
// Node's Happy Eyeballs path (autoSelectFamily, on by default since
|
server/utils/publicUrl.ts
CHANGED
|
@@ -190,3 +190,37 @@ export async function resolvePublicUrlAndAddress(
|
|
| 190 |
export async function resolvePublicUrl(rawUrl: string): Promise<URL> {
|
| 191 |
return (await resolvePublicUrlAndAddress(rawUrl)).url;
|
| 192 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
export async function resolvePublicUrl(rawUrl: string): Promise<URL> {
|
| 191 |
return (await resolvePublicUrlAndAddress(rawUrl)).url;
|
| 192 |
}
|
| 193 |
+
|
| 194 |
+
function timeoutError(): Error {
|
| 195 |
+
const error = new Error("The operation was aborted");
|
| 196 |
+
error.name = "TimeoutError";
|
| 197 |
+
return error;
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
/**
|
| 201 |
+
* The DNS lookup behind `resolvePublicUrl` and `resolvePublicUrlAndAddress`
|
| 202 |
+
* does not take a signal, so callers race it against their request deadline:
|
| 203 |
+
* a hanging resolver would otherwise add its own timeout on top of the one
|
| 204 |
+
* that is documented to bound the whole redirect chain. The lookup itself
|
| 205 |
+
* keeps running, but the caller settles on time with a `TimeoutError`.
|
| 206 |
+
*/
|
| 207 |
+
export function resolveWithinDeadline<T>(
|
| 208 |
+
deadline: AbortSignal,
|
| 209 |
+
work: Promise<T>,
|
| 210 |
+
): Promise<T> {
|
| 211 |
+
if (deadline.aborted) return Promise.reject(timeoutError());
|
| 212 |
+
return new Promise<T>((resolve, reject) => {
|
| 213 |
+
const onAbort = () => reject(timeoutError());
|
| 214 |
+
deadline.addEventListener("abort", onAbort, { once: true });
|
| 215 |
+
work.then(
|
| 216 |
+
(value) => {
|
| 217 |
+
deadline.removeEventListener("abort", onAbort);
|
| 218 |
+
resolve(value);
|
| 219 |
+
},
|
| 220 |
+
(error) => {
|
| 221 |
+
deadline.removeEventListener("abort", onAbort);
|
| 222 |
+
reject(error);
|
| 223 |
+
},
|
| 224 |
+
);
|
| 225 |
+
});
|
| 226 |
+
}
|
server/utils/requestUrl.test.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it } from "vitest";
|
| 2 |
+
import { parseRequestUrl } from "./requestUrl.ts";
|
| 3 |
+
|
| 4 |
+
function parse(url: string | undefined, host?: string) {
|
| 5 |
+
return parseRequestUrl({
|
| 6 |
+
url,
|
| 7 |
+
headers: host === undefined ? {} : { host },
|
| 8 |
+
});
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
describe("parseRequestUrl", () => {
|
| 12 |
+
it("reads the path and query parameters the same way for a valid Host", () => {
|
| 13 |
+
const url = parse("/search/text?q=a%20b&token=t", "localhost:7860");
|
| 14 |
+
expect(url?.pathname).toBe("/search/text");
|
| 15 |
+
expect(url?.searchParams.get("q")).toBe("a b");
|
| 16 |
+
expect(url?.searchParams.get("token")).toBe("t");
|
| 17 |
+
});
|
| 18 |
+
|
| 19 |
+
it.each([
|
| 20 |
+
undefined,
|
| 21 |
+
"",
|
| 22 |
+
"localhost",
|
| 23 |
+
"localhost:7860",
|
| 24 |
+
"example.com",
|
| 25 |
+
"my_service:3000",
|
| 26 |
+
"127.0.0.1:80",
|
| 27 |
+
"[::1]:7860",
|
| 28 |
+
])("accepts the Host header %j", (host) => {
|
| 29 |
+
expect(parse("/x", host)).not.toBeNull();
|
| 30 |
+
});
|
| 31 |
+
|
| 32 |
+
it.each([
|
| 33 |
+
"bad host",
|
| 34 |
+
"localhost:99999",
|
| 35 |
+
"local host:80",
|
| 36 |
+
"host/path",
|
| 37 |
+
"host?x=1",
|
| 38 |
+
"host:80:80",
|
| 39 |
+
"[::1",
|
| 40 |
+
"a b\tc",
|
| 41 |
+
])("returns null for the malformed Host header %j", (host) => {
|
| 42 |
+
expect(parse("/x", host)).toBeNull();
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
it("does not let the Host header change the parsed path or query", () => {
|
| 46 |
+
const url = parse("/page-content?url=http://a.test", "evil.test:1");
|
| 47 |
+
expect(url?.pathname).toBe("/page-content");
|
| 48 |
+
expect(url?.searchParams.get("url")).toBe("http://a.test");
|
| 49 |
+
expect(url?.host).toBe("localhost");
|
| 50 |
+
});
|
| 51 |
+
});
|
server/utils/requestUrl.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { IncomingMessage } from "node:http";
|
| 2 |
+
|
| 3 |
+
const REQUEST_URL_BASE = "http://localhost";
|
| 4 |
+
|
| 5 |
+
// A hostname (letters, digits, dot, hyphen, underscore) or a bracketed IPv6
|
| 6 |
+
// literal, with an optional port.
|
| 7 |
+
const HOST_HEADER_PATTERN =
|
| 8 |
+
/^(?:[A-Za-z0-9._-]+|\[[0-9A-Fa-f:.]+\])(?::(\d{1,5}))?$/;
|
| 9 |
+
|
| 10 |
+
function isValidHostHeader(host: string): boolean {
|
| 11 |
+
const match = HOST_HEADER_PATTERN.exec(host);
|
| 12 |
+
if (!match) return false;
|
| 13 |
+
return match[1] === undefined || Number(match[1]) <= 65535;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
/**
|
| 17 |
+
* Parses the request target, or returns `null` for a request that should be
|
| 18 |
+
* answered with a 400.
|
| 19 |
+
*
|
| 20 |
+
* The URL is parsed against a fixed base instead of the Host header: the
|
| 21 |
+
* endpoint hooks read only `pathname` and `searchParams`, and a Host header such
|
| 22 |
+
* as `bad host` makes `new URL(path, "http://bad host")` throw. Inside an async
|
| 23 |
+
* middleware that throw is an unhandled rejection, and Node exits. A Host
|
| 24 |
+
* header that is present but malformed is refused here, as RFC 9112 asks.
|
| 25 |
+
*/
|
| 26 |
+
export function parseRequestUrl(
|
| 27 |
+
request: Pick<IncomingMessage, "url" | "headers">,
|
| 28 |
+
): URL | null {
|
| 29 |
+
const host = request.headers.host;
|
| 30 |
+
if (typeof host === "string" && host.length > 0 && !isValidHostHeader(host)) {
|
| 31 |
+
return null;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
try {
|
| 35 |
+
return new URL(request.url ?? "/", REQUEST_URL_BASE);
|
| 36 |
+
} catch {
|
| 37 |
+
return null;
|
| 38 |
+
}
|
| 39 |
+
}
|
server/utils/streamUtils.test.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { describe, expect, it, vi } from "vitest";
|
| 2 |
+
import { readCappedBytes } from "./streamUtils";
|
| 3 |
+
|
| 4 |
+
function fakeResponse(chunks: Uint8Array[]) {
|
| 5 |
+
let index = 0;
|
| 6 |
+
const cancel = vi.fn().mockResolvedValue(undefined);
|
| 7 |
+
const reader = {
|
| 8 |
+
read: vi.fn(async () => {
|
| 9 |
+
if (index < chunks.length) {
|
| 10 |
+
return { done: false, value: chunks[index++] };
|
| 11 |
+
}
|
| 12 |
+
return { done: true, value: undefined };
|
| 13 |
+
}),
|
| 14 |
+
cancel,
|
| 15 |
+
};
|
| 16 |
+
const response = {
|
| 17 |
+
body: {
|
| 18 |
+
getReader: () => reader,
|
| 19 |
+
},
|
| 20 |
+
} as unknown as Response;
|
| 21 |
+
return { response, reader, cancel };
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
describe("readCappedBytes", () => {
|
| 25 |
+
it("reads an exact-fit body in a single chunk without truncation", async () => {
|
| 26 |
+
const { response, cancel } = fakeResponse([new Uint8Array([1, 2, 3, 4])]);
|
| 27 |
+
const { bytes, truncated } = await readCappedBytes(response, 4);
|
| 28 |
+
|
| 29 |
+
expect(Array.from(bytes)).toEqual([1, 2, 3, 4]);
|
| 30 |
+
expect(truncated).toBe(false);
|
| 31 |
+
expect(cancel).toHaveBeenCalled();
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
it("reads an exact-fit body split across chunks without truncation", async () => {
|
| 35 |
+
const { response, cancel } = fakeResponse([
|
| 36 |
+
new Uint8Array([1, 2]),
|
| 37 |
+
new Uint8Array([3, 4]),
|
| 38 |
+
]);
|
| 39 |
+
const { bytes, truncated } = await readCappedBytes(response, 4);
|
| 40 |
+
|
| 41 |
+
expect(Array.from(bytes)).toEqual([1, 2, 3, 4]);
|
| 42 |
+
expect(truncated).toBe(false);
|
| 43 |
+
expect(cancel).toHaveBeenCalled();
|
| 44 |
+
});
|
| 45 |
+
|
| 46 |
+
it("truncates at the cap when a single chunk exceeds maxBytes", async () => {
|
| 47 |
+
const { response, cancel } = fakeResponse([
|
| 48 |
+
new Uint8Array([1, 2, 3, 4, 5]),
|
| 49 |
+
]);
|
| 50 |
+
const { bytes, truncated } = await readCappedBytes(response, 4);
|
| 51 |
+
|
| 52 |
+
expect(Array.from(bytes)).toEqual([1, 2, 3, 4]);
|
| 53 |
+
expect(truncated).toBe(true);
|
| 54 |
+
expect(cancel).toHaveBeenCalled();
|
| 55 |
+
});
|
| 56 |
+
|
| 57 |
+
it("truncates at the cap when the boundary lands on a chunk boundary", async () => {
|
| 58 |
+
const { response, cancel } = fakeResponse([
|
| 59 |
+
new Uint8Array([1, 2, 3, 4]),
|
| 60 |
+
new Uint8Array([5]),
|
| 61 |
+
]);
|
| 62 |
+
const { bytes, truncated } = await readCappedBytes(response, 4);
|
| 63 |
+
|
| 64 |
+
expect(Array.from(bytes)).toEqual([1, 2, 3, 4]);
|
| 65 |
+
expect(truncated).toBe(true);
|
| 66 |
+
expect(cancel).toHaveBeenCalled();
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
it("returns all bytes and truncated false when body is under cap", async () => {
|
| 70 |
+
const { response, cancel } = fakeResponse([new Uint8Array([1, 2, 3])]);
|
| 71 |
+
const { bytes, truncated } = await readCappedBytes(response, 10);
|
| 72 |
+
|
| 73 |
+
expect(Array.from(bytes)).toEqual([1, 2, 3]);
|
| 74 |
+
expect(truncated).toBe(false);
|
| 75 |
+
expect(cancel).toHaveBeenCalled();
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
it("returns empty buffer and truncated false for an empty body", async () => {
|
| 79 |
+
const { response, cancel } = fakeResponse([]);
|
| 80 |
+
const { bytes, truncated } = await readCappedBytes(response, 10);
|
| 81 |
+
|
| 82 |
+
expect(bytes.byteLength).toBe(0);
|
| 83 |
+
expect(truncated).toBe(false);
|
| 84 |
+
expect(cancel).toHaveBeenCalled();
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
it("returns empty buffer and truncated false when response has no body", async () => {
|
| 88 |
+
const { bytes, truncated } = await readCappedBytes({} as Response, 10);
|
| 89 |
+
|
| 90 |
+
expect(bytes.byteLength).toBe(0);
|
| 91 |
+
expect(truncated).toBe(false);
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it("cancels reader even if an error occurs during reading", async () => {
|
| 95 |
+
const cancel = vi.fn().mockResolvedValue(undefined);
|
| 96 |
+
const reader = {
|
| 97 |
+
read: vi.fn().mockRejectedValue(new Error("network failure")),
|
| 98 |
+
cancel,
|
| 99 |
+
};
|
| 100 |
+
const response = {
|
| 101 |
+
body: {
|
| 102 |
+
getReader: () => reader,
|
| 103 |
+
},
|
| 104 |
+
} as unknown as Response;
|
| 105 |
+
|
| 106 |
+
await expect(readCappedBytes(response, 10)).rejects.toThrow(
|
| 107 |
+
"network failure",
|
| 108 |
+
);
|
| 109 |
+
expect(cancel).toHaveBeenCalled();
|
| 110 |
+
});
|
| 111 |
+
});
|
server/utils/streamUtils.ts
CHANGED
|
@@ -15,33 +15,36 @@ export async function readCappedBytes(
|
|
| 15 |
|
| 16 |
const chunks: Uint8Array[] = [];
|
| 17 |
let bytesRead = 0;
|
| 18 |
-
let
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
break;
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
const remaining = maxBytes - bytesRead;
|
| 28 |
-
const chunk =
|
| 29 |
-
value.byteLength > remaining ? value.subarray(0, remaining) : value;
|
| 30 |
-
bytesRead += chunk.byteLength;
|
| 31 |
-
chunks.push(chunk);
|
| 32 |
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
}
|
| 35 |
|
| 36 |
-
await reader.cancel().catch(() => {});
|
| 37 |
-
|
| 38 |
const bytes = new Uint8Array(bytesRead);
|
| 39 |
let offset = 0;
|
| 40 |
for (const chunk of chunks) {
|
| 41 |
bytes.set(chunk, offset);
|
| 42 |
offset += chunk.byteLength;
|
| 43 |
}
|
| 44 |
-
return { bytes, truncated
|
| 45 |
}
|
| 46 |
|
| 47 |
export function calculateBackoffTime(
|
|
|
|
| 15 |
|
| 16 |
const chunks: Uint8Array[] = [];
|
| 17 |
let bytesRead = 0;
|
| 18 |
+
let truncated = false;
|
| 19 |
|
| 20 |
+
try {
|
| 21 |
+
while (true) {
|
| 22 |
+
const { done, value } = await reader.read();
|
| 23 |
+
if (done) break;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
const remaining = maxBytes - bytesRead;
|
| 26 |
+
if (value.byteLength > remaining) {
|
| 27 |
+
if (remaining > 0) {
|
| 28 |
+
chunks.push(value.subarray(0, remaining));
|
| 29 |
+
bytesRead = maxBytes;
|
| 30 |
+
}
|
| 31 |
+
truncated = true;
|
| 32 |
+
break;
|
| 33 |
+
}
|
| 34 |
+
chunks.push(value);
|
| 35 |
+
bytesRead += value.byteLength;
|
| 36 |
+
}
|
| 37 |
+
} finally {
|
| 38 |
+
await reader.cancel().catch(() => {});
|
| 39 |
}
|
| 40 |
|
|
|
|
|
|
|
| 41 |
const bytes = new Uint8Array(bytesRead);
|
| 42 |
let offset = 0;
|
| 43 |
for (const chunk of chunks) {
|
| 44 |
bytes.set(chunk, offset);
|
| 45 |
offset += chunk.byteLength;
|
| 46 |
}
|
| 47 |
+
return { bytes, truncated };
|
| 48 |
}
|
| 49 |
|
| 50 |
export function calculateBackoffTime(
|
server/validateAccessKeyServerHook.test.ts
CHANGED
|
@@ -138,6 +138,58 @@ describe("validateAccessKeyServerHook", () => {
|
|
| 138 |
expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);
|
| 139 |
});
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
it("responds 429 and skips the argon2 loop when the limiter refuses", async () => {
|
| 142 |
process.env.ACCESS_KEYS = "test-key";
|
| 143 |
mockConsumeRateLimitPoint.mockResolvedValue(false);
|
|
|
|
| 138 |
expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);
|
| 139 |
});
|
| 140 |
|
| 141 |
+
it("ignores spaces and empty entries in the configured ACCESS_KEYS list", async () => {
|
| 142 |
+
process.env.ACCESS_KEYS = "test-key, other-key,";
|
| 143 |
+
mockArgon2Verify.mockImplementation(
|
| 144 |
+
async ({ password }: { password: string }) => {
|
| 145 |
+
if (password === "") throw new Error("Password must be specified");
|
| 146 |
+
return password === "other-key";
|
| 147 |
+
},
|
| 148 |
+
);
|
| 149 |
+
const { validateAccessKeyServerHook } = await import(
|
| 150 |
+
"./validateAccessKeyServerHook"
|
| 151 |
+
);
|
| 152 |
+
const use = vi.fn();
|
| 153 |
+
validateAccessKeyServerHook({
|
| 154 |
+
middlewares: { use },
|
| 155 |
+
} as never);
|
| 156 |
+
const handler = use.mock.calls[0][0] as (
|
| 157 |
+
req: {
|
| 158 |
+
url: string;
|
| 159 |
+
method: string;
|
| 160 |
+
on: (event: string, cb: (chunk: string) => void) => void;
|
| 161 |
+
},
|
| 162 |
+
res: {
|
| 163 |
+
setHeader: ReturnType<typeof vi.fn>;
|
| 164 |
+
end: ReturnType<typeof vi.fn>;
|
| 165 |
+
},
|
| 166 |
+
next: () => void,
|
| 167 |
+
) => void;
|
| 168 |
+
|
| 169 |
+
const res = makeMockResponse();
|
| 170 |
+
const req = makeMockRequest(
|
| 171 |
+
"/api/validate-access-key",
|
| 172 |
+
"POST",
|
| 173 |
+
JSON.stringify({ accessKeyHash: makeValidAccessKeyHash("valid") }),
|
| 174 |
+
);
|
| 175 |
+
|
| 176 |
+
await new Promise<void>((resolve) => {
|
| 177 |
+
void handler(req as never, res as never, () => {});
|
| 178 |
+
setImmediate(() => {
|
| 179 |
+
for (const cb of req.endCallbacks) {
|
| 180 |
+
cb();
|
| 181 |
+
}
|
| 182 |
+
setTimeout(resolve, 50);
|
| 183 |
+
});
|
| 184 |
+
});
|
| 185 |
+
|
| 186 |
+
expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));
|
| 187 |
+
const verifiedPasswords = mockArgon2Verify.mock.calls.map(
|
| 188 |
+
([options]) => (options as { password: string }).password,
|
| 189 |
+
);
|
| 190 |
+
expect(verifiedPasswords).toEqual(["test-key", "other-key"]);
|
| 191 |
+
});
|
| 192 |
+
|
| 193 |
it("responds 429 and skips the argon2 loop when the limiter refuses", async () => {
|
| 194 |
process.env.ACCESS_KEYS = "test-key";
|
| 195 |
mockConsumeRateLimitPoint.mockResolvedValue(false);
|
server/validateAccessKeyServerHook.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import { argon2Verify } from "hash-wasm";
|
| 2 |
import type { PreviewServer, ViteDevServer } from "vite";
|
| 3 |
import { ARGON2_HASH_PREFIX } from "../shared/argon2Parameters.ts";
|
|
|
|
| 4 |
import { consumeRateLimitPoint } from "./verifyTokenAndRateLimit.ts";
|
| 5 |
|
| 6 |
/**
|
|
@@ -18,6 +19,8 @@ export function validateAccessKeyServerHook<
|
|
| 18 |
return next();
|
| 19 |
}
|
| 20 |
|
|
|
|
|
|
|
| 21 |
// Consume a rate-limit point before the argon2 loop. A wrong hash costs one
|
| 22 |
// full argon2 verification per configured key, so nothing may bound that
|
| 23 |
// work other than the limiter - the same lever the search token path closes.
|
|
@@ -31,7 +34,7 @@ export function validateAccessKeyServerHook<
|
|
| 31 |
return;
|
| 32 |
}
|
| 33 |
|
| 34 |
-
const accessKeys = process.env.ACCESS_KEYS
|
| 35 |
|
| 36 |
const chunks: Buffer[] = [];
|
| 37 |
let bodyBytes = 0;
|
|
|
|
| 1 |
import { argon2Verify } from "hash-wasm";
|
| 2 |
import type { PreviewServer, ViteDevServer } from "vite";
|
| 3 |
import { ARGON2_HASH_PREFIX } from "../shared/argon2Parameters.ts";
|
| 4 |
+
import { parseCommaSeparatedList } from "./parseCommaSeparatedList.ts";
|
| 5 |
import { consumeRateLimitPoint } from "./verifyTokenAndRateLimit.ts";
|
| 6 |
|
| 7 |
/**
|
|
|
|
| 19 |
return next();
|
| 20 |
}
|
| 21 |
|
| 22 |
+
res.setHeader("Cache-Control", "no-store");
|
| 23 |
+
|
| 24 |
// Consume a rate-limit point before the argon2 loop. A wrong hash costs one
|
| 25 |
// full argon2 verification per configured key, so nothing may bound that
|
| 26 |
// work other than the limiter - the same lever the search token path closes.
|
|
|
|
| 34 |
return;
|
| 35 |
}
|
| 36 |
|
| 37 |
+
const accessKeys = parseCommaSeparatedList(process.env.ACCESS_KEYS);
|
| 38 |
|
| 39 |
const chunks: Buffer[] = [];
|
| 40 |
let bodyBytes = 0;
|
server/viteConfigAllowedHosts.test.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
| 2 |
+
|
| 3 |
+
afterEach(() => {
|
| 4 |
+
vi.unstubAllEnvs();
|
| 5 |
+
vi.resetModules();
|
| 6 |
+
});
|
| 7 |
+
|
| 8 |
+
async function loadAllowedHosts() {
|
| 9 |
+
const { default: defineViteConfig } = await import("../vite.config");
|
| 10 |
+
const config = await (
|
| 11 |
+
defineViteConfig as unknown as (env: {
|
| 12 |
+
command: string;
|
| 13 |
+
mode: string;
|
| 14 |
+
}) => Promise<{ preview?: { allowedHosts?: unknown } }>
|
| 15 |
+
)({ command: "serve", mode: "test" });
|
| 16 |
+
return config.preview?.allowedHosts;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
describe("vite.config preview allowedHosts", () => {
|
| 20 |
+
it("allows any host when ALLOWED_HOSTS is not set", async () => {
|
| 21 |
+
vi.stubEnv("ALLOWED_HOSTS", "");
|
| 22 |
+
expect(await loadAllowedHosts()).toBe(true);
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
it("accepts a host that follows a comma and a space", async () => {
|
| 26 |
+
vi.stubEnv("ALLOWED_HOSTS", "localhost, example.com");
|
| 27 |
+
expect(await loadAllowedHosts()).toEqual(["localhost", "example.com"]);
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
it("does not open the preview server to every host for a list without hosts", async () => {
|
| 31 |
+
vi.stubEnv("ALLOWED_HOSTS", ",");
|
| 32 |
+
expect(await loadAllowedHosts()).toEqual([]);
|
| 33 |
+
});
|
| 34 |
+
});
|
shared/relativeDates.test.ts
CHANGED
|
@@ -114,6 +114,12 @@ describe("normalizeRelativeDates", () => {
|
|
| 114 |
);
|
| 115 |
});
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
it("leaves an empty query alone", () => {
|
| 118 |
for (const query of ["", " "]) {
|
| 119 |
expect(normalizeRelativeDates(query, AS_OF)).toEqual({
|
|
@@ -245,6 +251,181 @@ describe("normalizeRelativeDates", () => {
|
|
| 245 |
expect(searchQuery).not.toContain("December 2026");
|
| 246 |
expect(searchQuery.length).toBeLessThanOrEqual(2000);
|
| 247 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
});
|
| 249 |
|
| 250 |
describe("normalizeFollowUpDates", () => {
|
|
@@ -328,4 +509,87 @@ describe("normalizeFollowUpDates", () => {
|
|
| 328 |
}).searchQuery,
|
| 329 |
).toBe("who won");
|
| 330 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
});
|
|
|
|
| 114 |
);
|
| 115 |
});
|
| 116 |
|
| 117 |
+
it("trims the query on both sides when an anchor is appended", () => {
|
| 118 |
+
expect(normalizeRelativeDates(" next year ", AS_OF).searchQuery).toBe(
|
| 119 |
+
"next year 2027",
|
| 120 |
+
);
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
it("leaves an empty query alone", () => {
|
| 124 |
for (const query of ["", " "]) {
|
| 125 |
expect(normalizeRelativeDates(query, AS_OF)).toEqual({
|
|
|
|
| 251 |
expect(searchQuery).not.toContain("December 2026");
|
| 252 |
expect(searchQuery.length).toBeLessThanOrEqual(2000);
|
| 253 |
});
|
| 254 |
+
|
| 255 |
+
it("cuts an over-long query with no relative date to the limit", () => {
|
| 256 |
+
const long = "x".repeat(2100);
|
| 257 |
+
|
| 258 |
+
expect(
|
| 259 |
+
normalizeRelativeDates(long, new Date(2026, 10, 3), { maxLength: 2000 }),
|
| 260 |
+
).toEqual({ searchQuery: "x".repeat(2000), replacements: [] });
|
| 261 |
+
});
|
| 262 |
+
|
| 263 |
+
it("cuts an over-long query whose anchor no longer fits to the limit", () => {
|
| 264 |
+
const long = `${"x".repeat(2095)} next year`;
|
| 265 |
+
|
| 266 |
+
expect(
|
| 267 |
+
normalizeRelativeDates(long, new Date(2026, 10, 3), { maxLength: 2000 }),
|
| 268 |
+
).toEqual({ searchQuery: "x".repeat(2000), replacements: [] });
|
| 269 |
+
});
|
| 270 |
+
|
| 271 |
+
it("drops the trailing space left by the cut", () => {
|
| 272 |
+
const long = `${"x".repeat(1999)} ${"y".repeat(100)}`;
|
| 273 |
+
|
| 274 |
+
expect(
|
| 275 |
+
normalizeRelativeDates(long, new Date(2026, 10, 3), { maxLength: 2000 })
|
| 276 |
+
.searchQuery,
|
| 277 |
+
).toBe("x".repeat(1999));
|
| 278 |
+
});
|
| 279 |
+
|
| 280 |
+
describe("spelling variants", () => {
|
| 281 |
+
it.each(["'", "\u2018", "\u2019", "\u02bc", "\uff07"])(
|
| 282 |
+
"skips the possessive headline form with the apostrophe %j",
|
| 283 |
+
(apostrophe) => {
|
| 284 |
+
const query = `next year${apostrophe}s champion`;
|
| 285 |
+
|
| 286 |
+
expect(normalizeRelativeDates(query, AS_OF)).toEqual({
|
| 287 |
+
searchQuery: query,
|
| 288 |
+
replacements: [],
|
| 289 |
+
});
|
| 290 |
+
},
|
| 291 |
+
);
|
| 292 |
+
|
| 293 |
+
it.each([
|
| 294 |
+
"last\u00a0month\u00a0of pregnancy symptoms",
|
| 295 |
+
"last month of pregnancy symptoms",
|
| 296 |
+
"the last\u00a0year\u00a0of college",
|
| 297 |
+
])("skips a blacklisted phrase written with odd spacing: %j", (query) => {
|
| 298 |
+
expect(normalizeRelativeDates(query, AS_OF)).toEqual({
|
| 299 |
+
searchQuery: query,
|
| 300 |
+
replacements: [],
|
| 301 |
+
});
|
| 302 |
+
});
|
| 303 |
+
|
| 304 |
+
it.each(["next\u00a0year", "next year"])(
|
| 305 |
+
"anchors a trigger written with the spacing %j",
|
| 306 |
+
(phrase) => {
|
| 307 |
+
expect(normalizeRelativeDates(`${phrase} champion`, AS_OF)).toEqual({
|
| 308 |
+
searchQuery: `${phrase} champion 2027`,
|
| 309 |
+
replacements: [{ phrase, anchor: "2027" }],
|
| 310 |
+
});
|
| 311 |
+
},
|
| 312 |
+
);
|
| 313 |
+
|
| 314 |
+
it("reports the phrase as typed after a letter that grows when lowercased", () => {
|
| 315 |
+
// "İ".toLowerCase() is two code units, which used to shift every index
|
| 316 |
+
// computed on the lowercased copy.
|
| 317 |
+
expect(normalizeRelativeDates("İstanbul next year", AS_OF)).toEqual({
|
| 318 |
+
searchQuery: "İstanbul next year 2027",
|
| 319 |
+
replacements: [{ phrase: "next year", anchor: "2027" }],
|
| 320 |
+
});
|
| 321 |
+
});
|
| 322 |
+
});
|
| 323 |
+
|
| 324 |
+
describe("dates the query already carries", () => {
|
| 325 |
+
it.each([
|
| 326 |
+
"events in 2026 December next month",
|
| 327 |
+
"events in December 2026 next month",
|
| 328 |
+
"events in Dec 2026 next month",
|
| 329 |
+
"events in Dec. 2026 next month",
|
| 330 |
+
"events in Sept 2026 and 2026-12 next month",
|
| 331 |
+
"events in 2026-12 next month",
|
| 332 |
+
"events in 2026/12 next month",
|
| 333 |
+
])("does not add December 2026 to %j", (query) => {
|
| 334 |
+
expect(normalizeRelativeDates(query, AS_OF)).toEqual({
|
| 335 |
+
searchQuery: query,
|
| 336 |
+
replacements: [],
|
| 337 |
+
});
|
| 338 |
+
});
|
| 339 |
+
|
| 340 |
+
it.each(["2026年12月的活动 下个月", "2026 年 12 月的活动 下个月"])(
|
| 341 |
+
"does not add 2026年12月 to %j",
|
| 342 |
+
(query) => {
|
| 343 |
+
expect(normalizeRelativeDates(query, AS_OF)).toEqual({
|
| 344 |
+
searchQuery: query,
|
| 345 |
+
replacements: [],
|
| 346 |
+
});
|
| 347 |
+
},
|
| 348 |
+
);
|
| 349 |
+
|
| 350 |
+
it("still adds a month when the query names only the year", () => {
|
| 351 |
+
expect(
|
| 352 |
+
normalizeRelativeDates("events in 2026 next month", AS_OF),
|
| 353 |
+
).toEqual({
|
| 354 |
+
searchQuery: "events in 2026 next month December 2026",
|
| 355 |
+
replacements: [{ phrase: "next month", anchor: "December 2026" }],
|
| 356 |
+
});
|
| 357 |
+
});
|
| 358 |
+
|
| 359 |
+
it("still adds a month when the query names another month", () => {
|
| 360 |
+
expect(
|
| 361 |
+
normalizeRelativeDates("events in January 2026 next month", AS_OF)
|
| 362 |
+
.replacements,
|
| 363 |
+
).toEqual([{ phrase: "next month", anchor: "December 2026" }]);
|
| 364 |
+
});
|
| 365 |
+
|
| 366 |
+
it("does not take a year inside a longer number for a year", () => {
|
| 367 |
+
expect(normalizeRelativeDates("ticket 120265 this year", AS_OF)).toEqual({
|
| 368 |
+
searchQuery: "ticket 120265 this year 2026",
|
| 369 |
+
replacements: [{ phrase: "this year", anchor: "2026" }],
|
| 370 |
+
});
|
| 371 |
+
});
|
| 372 |
+
|
| 373 |
+
it("does not take a season for a month", () => {
|
| 374 |
+
// 2011-12 is a season (the second number follows the first year), not
|
| 375 |
+
// December 2011, so next month's anchor is still worth adding.
|
| 376 |
+
expect(
|
| 377 |
+
normalizeRelativeDates(
|
| 378 |
+
"2011-12 season next month",
|
| 379 |
+
new Date(2011, 10, 3, 12),
|
| 380 |
+
).replacements,
|
| 381 |
+
).toEqual([{ phrase: "next month", anchor: "December 2011" }]);
|
| 382 |
+
});
|
| 383 |
+
});
|
| 384 |
+
|
| 385 |
+
describe("which month a written date carries", () => {
|
| 386 |
+
const JANUARY_2026 = new Date(2026, 0, 10, 12);
|
| 387 |
+
|
| 388 |
+
it("takes the month written inside the date over a month name behind it", () => {
|
| 389 |
+
// "Nov" belongs to "Nov 2026", not to 2026-12, so December is written.
|
| 390 |
+
expect(
|
| 391 |
+
normalizeRelativeDates("report 2026-12 Nov 2026 next month", AS_OF),
|
| 392 |
+
).toEqual({
|
| 393 |
+
searchQuery: "report 2026-12 Nov 2026 next month",
|
| 394 |
+
replacements: [],
|
| 395 |
+
});
|
| 396 |
+
expect(
|
| 397 |
+
normalizeRelativeDates("2026年12月 November 2026 next month", AS_OF)
|
| 398 |
+
.replacements,
|
| 399 |
+
).toEqual([]);
|
| 400 |
+
});
|
| 401 |
+
|
| 402 |
+
it("gives a month name to the date it stands in front of, not the one before", () => {
|
| 403 |
+
// "2023-2025 Dec 2026" is a range, then December 2026. December 2025,
|
| 404 |
+
// which last month resolves to in January 2026, is not written.
|
| 405 |
+
expect(
|
| 406 |
+
normalizeRelativeDates("2023-2025 Dec 2026 last month", JANUARY_2026)
|
| 407 |
+
.replacements,
|
| 408 |
+
).toEqual([{ phrase: "last month", anchor: "December 2025" }]);
|
| 409 |
+
});
|
| 410 |
+
|
| 411 |
+
it("does not give a month to a year range", () => {
|
| 412 |
+
expect(
|
| 413 |
+
normalizeRelativeDates("2023-2025 December last month", JANUARY_2026)
|
| 414 |
+
.replacements,
|
| 415 |
+
).toEqual([{ phrase: "last month", anchor: "December 2025" }]);
|
| 416 |
+
});
|
| 417 |
+
|
| 418 |
+
it("gives a month name in front of a range to its first year only", () => {
|
| 419 |
+
expect(
|
| 420 |
+
normalizeRelativeDates("December 2025-2027 last month", JANUARY_2026)
|
| 421 |
+
.replacements,
|
| 422 |
+
).toEqual([]);
|
| 423 |
+
expect(
|
| 424 |
+
normalizeRelativeDates("December 2023-2025 last month", JANUARY_2026)
|
| 425 |
+
.replacements,
|
| 426 |
+
).toEqual([{ phrase: "last month", anchor: "December 2025" }]);
|
| 427 |
+
});
|
| 428 |
+
});
|
| 429 |
});
|
| 430 |
|
| 431 |
describe("normalizeFollowUpDates", () => {
|
|
|
|
| 509 |
}).searchQuery,
|
| 510 |
).toBe("who won");
|
| 511 |
});
|
| 512 |
+
|
| 513 |
+
it("cuts an over-long query to the limit", () => {
|
| 514 |
+
const long = "x".repeat(2100);
|
| 515 |
+
|
| 516 |
+
expect(
|
| 517 |
+
normalizeFollowUpDates(long, [long], AS_OF, { maxLength: 2000 })
|
| 518 |
+
.searchQuery,
|
| 519 |
+
).toBe("x".repeat(2000));
|
| 520 |
+
expect(
|
| 521 |
+
normalizeFollowUpDates(long, ["who won it last year"], AS_OF, {
|
| 522 |
+
maxLength: 2000,
|
| 523 |
+
}).searchQuery,
|
| 524 |
+
).toHaveLength(2000);
|
| 525 |
+
});
|
| 526 |
+
|
| 527 |
+
describe("anchors already written", () => {
|
| 528 |
+
it("does not repeat a year the user typed that the anchor resolves to", () => {
|
| 529 |
+
expect(
|
| 530 |
+
normalizeFollowUpDates(
|
| 531 |
+
"2025 election results",
|
| 532 |
+
["2025 election results", "what happened last year?"],
|
| 533 |
+
AS_OF,
|
| 534 |
+
),
|
| 535 |
+
).toEqual({ searchQuery: "2025 election results", replacements: [] });
|
| 536 |
+
});
|
| 537 |
+
|
| 538 |
+
it("does not repeat a month the user typed, written another way", () => {
|
| 539 |
+
expect(
|
| 540 |
+
normalizeFollowUpDates(
|
| 541 |
+
"new releases in Dec 2026",
|
| 542 |
+
["new releases in Dec 2026", "and next month?"],
|
| 543 |
+
AS_OF,
|
| 544 |
+
),
|
| 545 |
+
).toEqual({ searchQuery: "new releases in Dec 2026", replacements: [] });
|
| 546 |
+
});
|
| 547 |
+
|
| 548 |
+
it("keeps the anchor that is not already written", () => {
|
| 549 |
+
expect(
|
| 550 |
+
normalizeFollowUpDates(
|
| 551 |
+
"2025 election results",
|
| 552 |
+
["2025 election results", "and what about next year?"],
|
| 553 |
+
AS_OF,
|
| 554 |
+
).searchQuery,
|
| 555 |
+
).toBe("2025 election results 2027");
|
| 556 |
+
});
|
| 557 |
+
});
|
| 558 |
+
|
| 559 |
+
describe("a query that is only a written date", () => {
|
| 560 |
+
it("gets its anchor without a leading space", () => {
|
| 561 |
+
expect(
|
| 562 |
+
normalizeFollowUpDates("2025", ["what happened last year?"], AS_OF),
|
| 563 |
+
).toEqual({
|
| 564 |
+
searchQuery: "2025",
|
| 565 |
+
replacements: [{ phrase: "last year", anchor: "2025" }],
|
| 566 |
+
});
|
| 567 |
+
});
|
| 568 |
+
|
| 569 |
+
it.each(["2025", " 2025 ", "2024-25", "2026年"])(
|
| 570 |
+
"returns a trimmed query for the model's %j",
|
| 571 |
+
(query) => {
|
| 572 |
+
const result = normalizeFollowUpDates(
|
| 573 |
+
query,
|
| 574 |
+
["what happened last year?"],
|
| 575 |
+
AS_OF,
|
| 576 |
+
);
|
| 577 |
+
|
| 578 |
+
expect(result.replacements).not.toEqual([]);
|
| 579 |
+
expect(result.searchQuery).toBe(result.searchQuery.trim());
|
| 580 |
+
},
|
| 581 |
+
);
|
| 582 |
+
});
|
| 583 |
+
|
| 584 |
+
describe("abbreviated months", () => {
|
| 585 |
+
it("drops the model's abbreviated month together with its year", () => {
|
| 586 |
+
// Only the year used to go, which left a dangling "Dec" in the query.
|
| 587 |
+
expect(
|
| 588 |
+
normalizeFollowUpDates("results and Dec 2026", ["what 去年"], AS_OF),
|
| 589 |
+
).toEqual({
|
| 590 |
+
searchQuery: "results and 2025年",
|
| 591 |
+
replacements: [{ phrase: "去年", anchor: "2025年" }],
|
| 592 |
+
});
|
| 593 |
+
});
|
| 594 |
+
});
|
| 595 |
});
|
shared/relativeDates.ts
CHANGED
|
@@ -55,6 +55,12 @@ interface Hit extends Occurrence {
|
|
| 55 |
anchor: string;
|
| 56 |
}
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
/**
|
| 59 |
* Month arithmetic in local calendar terms: December plus one month is January
|
| 60 |
* of the next year, not a wrapped month inside the same one.
|
|
@@ -175,40 +181,40 @@ const BLACKLIST_PHRASES: readonly string[] = [
|
|
| 175 |
"last year of",
|
| 176 |
];
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
}
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
): Occurrence[] {
|
| 187 |
-
const haystack = text.toLowerCase();
|
| 188 |
-
const needle = phrase.toLowerCase();
|
| 189 |
-
const occurrences: Occurrence[] = [];
|
| 190 |
-
let from = 0;
|
| 191 |
-
|
| 192 |
-
while (from + needle.length <= haystack.length) {
|
| 193 |
-
const start = haystack.indexOf(needle, from);
|
| 194 |
-
if (start === -1) break;
|
| 195 |
-
|
| 196 |
-
const end = start + needle.length;
|
| 197 |
-
const touchesWord =
|
| 198 |
-
wordBounded &&
|
| 199 |
-
(isAsciiLetter(haystack.charAt(start - 1)) ||
|
| 200 |
-
isAsciiLetter(haystack.charAt(end)));
|
| 201 |
-
|
| 202 |
-
if (touchesWord) {
|
| 203 |
-
from = start + 1;
|
| 204 |
-
continue;
|
| 205 |
-
}
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
}
|
| 213 |
|
| 214 |
function overlaps(occurrence: Occurrence, ranges: readonly Occurrence[]) {
|
|
@@ -223,23 +229,19 @@ export function normalizeRelativeDates(
|
|
| 223 |
options?: { maxLength?: number },
|
| 224 |
): { searchQuery: string; replacements: RelativeDateReplacement[] } {
|
| 225 |
const unchanged = {
|
| 226 |
-
searchQuery: query,
|
| 227 |
replacements: [] as RelativeDateReplacement[],
|
| 228 |
};
|
| 229 |
|
| 230 |
if (query.trim() === "") return unchanged;
|
| 231 |
|
| 232 |
-
const blacklistRanges =
|
| 233 |
-
findOccurrences(query,
|
| 234 |
);
|
| 235 |
|
| 236 |
const hits: Hit[] = [];
|
| 237 |
-
for (const rule of
|
| 238 |
-
for (const occurrence of findOccurrences(
|
| 239 |
-
query,
|
| 240 |
-
rule.phrase,
|
| 241 |
-
rule.wordBounded,
|
| 242 |
-
)) {
|
| 243 |
// A trigger inside a title or a longer word is a false positive; the
|
| 244 |
// blacklist owns that run of text.
|
| 245 |
if (overlaps(occurrence, blacklistRanges)) continue;
|
|
@@ -254,6 +256,8 @@ export function normalizeRelativeDates(
|
|
| 254 |
|
| 255 |
if (hits.length === 0) return unchanged;
|
| 256 |
|
|
|
|
|
|
|
| 257 |
hits.sort(
|
| 258 |
(left, right) =>
|
| 259 |
left.start - right.start ||
|
|
@@ -269,8 +273,9 @@ export function normalizeRelativeDates(
|
|
| 269 |
if (selected.some((chosen) => overlaps(hit, [chosen]))) continue;
|
| 270 |
// An anchor the query already spells out is not worth repeating: the
|
| 271 |
// search engine has that year already, and a doubled anchor only dilutes
|
| 272 |
-
// the query.
|
| 273 |
-
|
|
|
|
| 274 |
|
| 275 |
usedAnchors.add(hit.anchor);
|
| 276 |
selected.push(hit);
|
|
@@ -283,39 +288,142 @@ export function normalizeRelativeDates(
|
|
| 283 |
);
|
| 284 |
}
|
| 285 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
function appendAnchors(
|
| 287 |
query: string,
|
| 288 |
replacements: RelativeDateReplacement[],
|
| 289 |
maxLength = Number.POSITIVE_INFINITY,
|
| 290 |
): { searchQuery: string; replacements: RelativeDateReplacement[] } {
|
| 291 |
-
// The search endpoint rejects an over-long query, so
|
| 292 |
-
//
|
| 293 |
-
// failed request. No anchor left over
|
|
|
|
|
|
|
| 294 |
const appended: RelativeDateReplacement[] = [];
|
| 295 |
-
|
|
|
|
|
|
|
| 296 |
for (const replacement of replacements) {
|
| 297 |
-
const candidate =
|
|
|
|
|
|
|
| 298 |
if (candidate.length > maxLength) break;
|
| 299 |
searchQuery = candidate;
|
| 300 |
appended.push(replacement);
|
| 301 |
}
|
| 302 |
-
if (appended.length === 0) return { searchQuery:
|
| 303 |
|
| 304 |
return { searchQuery, replacements: appended };
|
| 305 |
}
|
| 306 |
|
| 307 |
const YEAR = "(?<!\\d)(?:19|20)\\d{2}(?!\\d)";
|
| 308 |
|
|
|
|
|
|
|
|
|
|
| 309 |
/**
|
| 310 |
* A year a model writes into a query, alone, as a range or a season, after a
|
| 311 |
-
* month name, or glued to Chinese text: "2023",
|
| 312 |
-
* "November 2026", "2026
|
|
|
|
| 313 |
*/
|
| 314 |
const WRITTEN_DATE = new RegExp(
|
| 315 |
-
`(?:\\b
|
| 316 |
"gi",
|
| 317 |
);
|
| 318 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
/**
|
| 320 |
* Anchors the relative dates of the question the user typed onto the query a
|
| 321 |
* model wrote for it. The model often replaces "last year" with a year of its
|
|
@@ -344,9 +452,15 @@ export function normalizeFollowUpDates(
|
|
| 344 |
.replace(/\s+/g, " ")
|
| 345 |
.trim();
|
| 346 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
return appendAnchors(
|
| 348 |
queryWithoutModelDates,
|
| 349 |
-
replacements
|
|
|
|
|
|
|
| 350 |
options?.maxLength,
|
| 351 |
);
|
| 352 |
}
|
|
|
|
| 55 |
anchor: string;
|
| 56 |
}
|
| 57 |
|
| 58 |
+
/** A date as a query writes it; `month` is 1 to 12 when the query names one. */
|
| 59 |
+
interface WrittenDate {
|
| 60 |
+
year: number;
|
| 61 |
+
month?: number;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
/**
|
| 65 |
* Month arithmetic in local calendar terms: December plus one month is January
|
| 66 |
* of the next year, not a wrapped month inside the same one.
|
|
|
|
| 181 |
"last year of",
|
| 182 |
];
|
| 183 |
|
| 184 |
+
/** Keyboards type any of these: ' U+2018 U+2019 U+02BC U+FF07. */
|
| 185 |
+
const APOSTROPHES = "'\u2018\u2019\u02bc\uff07";
|
| 186 |
+
|
| 187 |
+
/**
|
| 188 |
+
* Whitespace of any kind matches a space and any apostrophe variant matches
|
| 189 |
+
* `'`. The pattern runs on the original text rather than a lowercased copy, so
|
| 190 |
+
* a match keeps its position: "İ".toLowerCase() is two code units.
|
| 191 |
+
*/
|
| 192 |
+
function compilePhrase(phrase: string, wordBounded: boolean): RegExp {
|
| 193 |
+
const body = phrase
|
| 194 |
+
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
| 195 |
+
.replace(/ /g, "\\s+")
|
| 196 |
+
.replace(/'/g, `[${APOSTROPHES}]`);
|
| 197 |
+
|
| 198 |
+
return new RegExp(
|
| 199 |
+
wordBounded ? `(?<![A-Za-z])${body}(?![A-Za-z])` : body,
|
| 200 |
+
"gi",
|
| 201 |
+
);
|
| 202 |
}
|
| 203 |
|
| 204 |
+
const COMPILED_RULES = RULES.map((rule) => ({
|
| 205 |
+
rule,
|
| 206 |
+
pattern: compilePhrase(rule.phrase, rule.wordBounded),
|
| 207 |
+
}));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
+
const BLACKLIST_PATTERNS = BLACKLIST_PHRASES.map((phrase) =>
|
| 210 |
+
compilePhrase(phrase, false),
|
| 211 |
+
);
|
| 212 |
|
| 213 |
+
function findOccurrences(text: string, pattern: RegExp): Occurrence[] {
|
| 214 |
+
return [...text.matchAll(pattern)].map((match) => ({
|
| 215 |
+
start: match.index,
|
| 216 |
+
end: match.index + match[0].length,
|
| 217 |
+
}));
|
| 218 |
}
|
| 219 |
|
| 220 |
function overlaps(occurrence: Occurrence, ranges: readonly Occurrence[]) {
|
|
|
|
| 229 |
options?: { maxLength?: number },
|
| 230 |
): { searchQuery: string; replacements: RelativeDateReplacement[] } {
|
| 231 |
const unchanged = {
|
| 232 |
+
searchQuery: clampToMaxLength(query, options?.maxLength),
|
| 233 |
replacements: [] as RelativeDateReplacement[],
|
| 234 |
};
|
| 235 |
|
| 236 |
if (query.trim() === "") return unchanged;
|
| 237 |
|
| 238 |
+
const blacklistRanges = BLACKLIST_PATTERNS.flatMap((pattern) =>
|
| 239 |
+
findOccurrences(query, pattern),
|
| 240 |
);
|
| 241 |
|
| 242 |
const hits: Hit[] = [];
|
| 243 |
+
for (const { rule, pattern } of COMPILED_RULES) {
|
| 244 |
+
for (const occurrence of findOccurrences(query, pattern)) {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
// A trigger inside a title or a longer word is a false positive; the
|
| 246 |
// blacklist owns that run of text.
|
| 247 |
if (overlaps(occurrence, blacklistRanges)) continue;
|
|
|
|
| 256 |
|
| 257 |
if (hits.length === 0) return unchanged;
|
| 258 |
|
| 259 |
+
const writtenInQuery = writtenDates(query);
|
| 260 |
+
|
| 261 |
hits.sort(
|
| 262 |
(left, right) =>
|
| 263 |
left.start - right.start ||
|
|
|
|
| 273 |
if (selected.some((chosen) => overlaps(hit, [chosen]))) continue;
|
| 274 |
// An anchor the query already spells out is not worth repeating: the
|
| 275 |
// search engine has that year already, and a doubled anchor only dilutes
|
| 276 |
+
// the query. Compared as dates, so "Dec 2026" meets December 2026 and the
|
| 277 |
+
// "2026" inside "120265" meets nothing.
|
| 278 |
+
if (isAlreadyWritten(writtenInQuery, hit.anchor)) continue;
|
| 279 |
|
| 280 |
usedAnchors.add(hit.anchor);
|
| 281 |
selected.push(hit);
|
|
|
|
| 288 |
);
|
| 289 |
}
|
| 290 |
|
| 291 |
+
/**
|
| 292 |
+
* The query cut to `maxLength` characters, so the result never exceeds the
|
| 293 |
+
* limit the search endpoint enforces. A query within the limit is returned
|
| 294 |
+
* as is.
|
| 295 |
+
*/
|
| 296 |
+
function clampToMaxLength(query: string, maxLength?: number): string {
|
| 297 |
+
if (maxLength === undefined || query.length <= maxLength) return query;
|
| 298 |
+
return query.slice(0, maxLength).trimEnd();
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
function appendAnchors(
|
| 302 |
query: string,
|
| 303 |
replacements: RelativeDateReplacement[],
|
| 304 |
maxLength = Number.POSITIVE_INFINITY,
|
| 305 |
): { searchQuery: string; replacements: RelativeDateReplacement[] } {
|
| 306 |
+
// The search endpoint rejects an over-long query, so the query itself is cut
|
| 307 |
+
// to the limit, and an anchor that would push it past the limit is dropped
|
| 308 |
+
// rather than turning a search into a failed request. No anchor left over
|
| 309 |
+
// means the query goes out as it came, cut only when it was too long.
|
| 310 |
+
const base = clampToMaxLength(query, maxLength);
|
| 311 |
const appended: RelativeDateReplacement[] = [];
|
| 312 |
+
// Both ends, so a query that is only a written date gets no leading space,
|
| 313 |
+
// which would give the same search a second cache key.
|
| 314 |
+
let searchQuery = base.trim();
|
| 315 |
for (const replacement of replacements) {
|
| 316 |
+
const candidate = searchQuery
|
| 317 |
+
? `${searchQuery} ${replacement.anchor}`
|
| 318 |
+
: replacement.anchor;
|
| 319 |
if (candidate.length > maxLength) break;
|
| 320 |
searchQuery = candidate;
|
| 321 |
appended.push(replacement);
|
| 322 |
}
|
| 323 |
+
if (appended.length === 0) return { searchQuery: base, replacements: [] };
|
| 324 |
|
| 325 |
return { searchQuery, replacements: appended };
|
| 326 |
}
|
| 327 |
|
| 328 |
const YEAR = "(?<!\\d)(?:19|20)\\d{2}(?!\\d)";
|
| 329 |
|
| 330 |
+
/** A month name or its three-letter abbreviation ("Sept" too), as a whole word. */
|
| 331 |
+
const MONTH_WORD = `(?:${MONTH_NAMES.flatMap((name) => [name, name.slice(0, 3)]).join("|")}|Sept)\\b`;
|
| 332 |
+
|
| 333 |
/**
|
| 334 |
* A year a model writes into a query, alone, as a range or a season, after a
|
| 335 |
+
* month name (written out or abbreviated), or glued to Chinese text: "2023",
|
| 336 |
+
* "2023-2025", "2024-25", "November 2026", "Dec 2026", "2026年11月",
|
| 337 |
+
* "2025 年 3 月".
|
| 338 |
*/
|
| 339 |
const WRITTEN_DATE = new RegExp(
|
| 340 |
+
`(?:\\b${MONTH_WORD}\\.?\\s+)?${YEAR}(?:\\s*[-–/]\\s*${YEAR}|[-–/]\\d{2}(?!\\d))?(?:\\s*年(?:\\s*\\d{1,2}\\s*月)?)?`,
|
| 341 |
"gi",
|
| 342 |
);
|
| 343 |
|
| 344 |
+
function monthNumber(word: string): number {
|
| 345 |
+
const prefix = word.slice(0, 3).toLowerCase();
|
| 346 |
+
return (
|
| 347 |
+
MONTH_NAMES.findIndex((name) => name.slice(0, 3).toLowerCase() === prefix) +
|
| 348 |
+
1
|
| 349 |
+
);
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
/**
|
| 353 |
+
* A month written inside the date wins ("2026年12月", "2026-12", which is a
|
| 354 |
+
* season rather than a month when it reads "2024-25"), then a name in front of
|
| 355 |
+
* the year, then one behind it, unless the next date starts with that name. A
|
| 356 |
+
* range takes a month only from a name in front, and only for its first year.
|
| 357 |
+
*/
|
| 358 |
+
function monthOfWrittenDate(
|
| 359 |
+
match: RegExpExecArray,
|
| 360 |
+
nextMatch: RegExpExecArray | undefined,
|
| 361 |
+
text: string,
|
| 362 |
+
yearCount: number,
|
| 363 |
+
): number | undefined {
|
| 364 |
+
const written = match[0];
|
| 365 |
+
|
| 366 |
+
if (yearCount === 1) {
|
| 367 |
+
const chinese = written.match(/年\s*(\d{1,2})\s*月/);
|
| 368 |
+
if (chinese) return Number(chinese[1]);
|
| 369 |
+
|
| 370 |
+
const iso = written.match(/(?:19|20)(\d{2})[-/](\d{2})(?!\d)/);
|
| 371 |
+
if (iso) {
|
| 372 |
+
const [yearDigits, month] = [Number(iso[1]), Number(iso[2])];
|
| 373 |
+
const isSeason = month === (yearDigits + 1) % 100;
|
| 374 |
+
if (!isSeason && month >= 1 && month <= 12) return month;
|
| 375 |
+
}
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
const leading = written.match(new RegExp(`^${MONTH_WORD}`, "i"));
|
| 379 |
+
if (leading) return monthNumber(leading[0]);
|
| 380 |
+
|
| 381 |
+
if (yearCount !== 1) return undefined;
|
| 382 |
+
|
| 383 |
+
const end = match.index + written.length;
|
| 384 |
+
const trailing = text
|
| 385 |
+
.slice(end)
|
| 386 |
+
.match(new RegExp(`^[,\\s]+(${MONTH_WORD})`, "i"));
|
| 387 |
+
if (!trailing) return undefined;
|
| 388 |
+
|
| 389 |
+
const wordStart = end + trailing[0].length - trailing[1].length;
|
| 390 |
+
return nextMatch?.index === wordStart ? undefined : monthNumber(trailing[1]);
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
function writtenDates(text: string): WrittenDate[] {
|
| 394 |
+
const matches = [...text.matchAll(WRITTEN_DATE)];
|
| 395 |
+
|
| 396 |
+
return matches.flatMap((match, index) => {
|
| 397 |
+
const years = (match[0].match(new RegExp(YEAR, "g")) ?? []).map(Number);
|
| 398 |
+
const month = monthOfWrittenDate(
|
| 399 |
+
match,
|
| 400 |
+
matches[index + 1],
|
| 401 |
+
text,
|
| 402 |
+
years.length,
|
| 403 |
+
);
|
| 404 |
+
|
| 405 |
+
return years.map((year, position) => ({
|
| 406 |
+
year,
|
| 407 |
+
month: position === 0 ? month : undefined,
|
| 408 |
+
}));
|
| 409 |
+
});
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
/** A year-only anchor is met by any written date in that year. */
|
| 413 |
+
function isAlreadyWritten(
|
| 414 |
+
written: readonly WrittenDate[],
|
| 415 |
+
anchor: string,
|
| 416 |
+
): boolean {
|
| 417 |
+
const [wanted] = writtenDates(anchor);
|
| 418 |
+
if (!wanted) return false;
|
| 419 |
+
|
| 420 |
+
return written.some(
|
| 421 |
+
(date) =>
|
| 422 |
+
date.year === wanted.year &&
|
| 423 |
+
(wanted.month === undefined || date.month === wanted.month),
|
| 424 |
+
);
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
/**
|
| 428 |
* Anchors the relative dates of the question the user typed onto the query a
|
| 429 |
* model wrote for it. The model often replaces "last year" with a year of its
|
|
|
|
| 452 |
.replace(/\s+/g, " ")
|
| 453 |
.trim();
|
| 454 |
|
| 455 |
+
// A date the user typed survives the cleaning above, and its anchor would
|
| 456 |
+
// repeat it.
|
| 457 |
+
const writtenInQuery = writtenDates(queryWithoutModelDates);
|
| 458 |
+
|
| 459 |
return appendAnchors(
|
| 460 |
queryWithoutModelDates,
|
| 461 |
+
replacements.filter(
|
| 462 |
+
({ anchor }) => !isAlreadyWritten(writtenInQuery, anchor),
|
| 463 |
+
),
|
| 464 |
options?.maxLength,
|
| 465 |
);
|
| 466 |
}
|
vite.config.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { configEndpointServerHook } from "./server/configEndpointServerHook.ts";
|
|
| 13 |
import { crossOriginServerHook } from "./server/crossOriginServerHook.ts";
|
| 14 |
import { internalApiEndpointServerHook } from "./server/internalApiEndpointServerHook.ts";
|
| 15 |
import { pageContentEndpointServerHook } from "./server/pageContentEndpointServerHook.ts";
|
|
|
|
| 16 |
import { rerankerServiceHook } from "./server/rerankerServiceHook.ts";
|
| 17 |
import { searchEndpointServerHook } from "./server/searchEndpointServerHook.ts";
|
| 18 |
import { statusEndpointServerHook } from "./server/statusEndpointServerHook.ts";
|
|
@@ -63,10 +64,9 @@ export default defineConfig((): UserConfig => {
|
|
| 63 |
preview: {
|
| 64 |
host: process.env.HOST,
|
| 65 |
port: process.env.PORT ? Number(process.env.PORT) : undefined,
|
| 66 |
-
allowedHosts:
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
: true,
|
| 70 |
},
|
| 71 |
build: {
|
| 72 |
target: "esnext",
|
|
|
|
| 13 |
import { crossOriginServerHook } from "./server/crossOriginServerHook.ts";
|
| 14 |
import { internalApiEndpointServerHook } from "./server/internalApiEndpointServerHook.ts";
|
| 15 |
import { pageContentEndpointServerHook } from "./server/pageContentEndpointServerHook.ts";
|
| 16 |
+
import { parseCommaSeparatedList } from "./server/parseCommaSeparatedList.ts";
|
| 17 |
import { rerankerServiceHook } from "./server/rerankerServiceHook.ts";
|
| 18 |
import { searchEndpointServerHook } from "./server/searchEndpointServerHook.ts";
|
| 19 |
import { statusEndpointServerHook } from "./server/statusEndpointServerHook.ts";
|
|
|
|
| 64 |
preview: {
|
| 65 |
host: process.env.HOST,
|
| 66 |
port: process.env.PORT ? Number(process.env.PORT) : undefined,
|
| 67 |
+
allowedHosts: process.env.ALLOWED_HOSTS
|
| 68 |
+
? parseCommaSeparatedList(process.env.ALLOWED_HOSTS)
|
| 69 |
+
: true,
|
|
|
|
| 70 |
},
|
| 71 |
build: {
|
| 72 |
target: "esnext",
|