@crewhaus/tool-kyc 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +9 -0
- package/README.md +17 -3
- package/dist/index.js +56 -24
- package/dist/lib/net.d.ts +19 -3
- package/dist/lib/net.js +67 -54
- package/dist/lib/vat.d.ts +1 -1
- package/dist/lib/vat.js +20 -3
- package/dist/paths.d.ts +21 -2
- package/dist/paths.js +72 -13
- package/package.json +13 -8
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
CrewHaus Factory
|
|
2
|
+
Copyright 2026 Max Meier
|
|
3
|
+
|
|
4
|
+
This product includes software developed by Max Meier
|
|
5
|
+
(operating as StudioMax — https://studiomax.io) and contributors.
|
|
6
|
+
|
|
7
|
+
The CrewHaus name and logo are trademarks of Max Meier. See
|
|
8
|
+
https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
|
|
9
|
+
use-of-marks policy.
|
package/README.md
CHANGED
|
@@ -28,7 +28,20 @@ So every code VIES publishes is mapped explicitly, and a code we have never
|
|
|
28
28
|
seen becomes *could-not-check* with the code quoted, rather than a guess about
|
|
29
29
|
which side of the line it falls on. The same rule covers HTTP: a 500, a 429 or
|
|
30
30
|
a 403 is *could-not-check*. The only 404 that means anything about the subject
|
|
31
|
-
is HMRC's, which is documented to mean "not
|
|
31
|
+
is HMRC's carrying its `NOT_FOUND` code, which is documented to mean "not
|
|
32
|
+
registered". Any other 404 — no code, a body that is not JSON, or
|
|
33
|
+
`MATCHING_RESOURCE_NOT_FOUND` — is *could-not-check* with the code quoted, and
|
|
34
|
+
an HMRC answer about a different number than the one asked is too.
|
|
35
|
+
|
|
36
|
+
**GB lookups are could-not-check today.** HMRC removed version 1.0 of its
|
|
37
|
+
unauthenticated VAT checker in February 2025 and answers a version-1.0 request
|
|
38
|
+
with `MATCHING_RESOURCE_NOT_FOUND`; version 2.0 needs registered API
|
|
39
|
+
credentials, which this package does not hold. So a GB number gets its format
|
|
40
|
+
and check digits checked, and registration reads as unchecked, with that
|
|
41
|
+
reason. (0.7.0 read that 404 as "not registered" for every GB number.)
|
|
42
|
+
|
|
43
|
+
`requesterVatId` is held to its country's format like the subject's own id,
|
|
44
|
+
before anything is dialled.
|
|
32
45
|
|
|
33
46
|
`syntaxOnly` fits the same grammar: the format is well-formed, and registration
|
|
34
47
|
reads as unchecked rather than as fine.
|
|
@@ -188,8 +201,9 @@ and it was fine".
|
|
|
188
201
|
is a recorded fixture per publisher, because a mis-read alias-quality field
|
|
189
202
|
reports a weak match as a strong one and nothing downstream can tell.
|
|
190
203
|
- **It reads two registers, not four.** Companies House and OpenCorporates need
|
|
191
|
-
an API key; GLEIF, EDGAR
|
|
192
|
-
credential.
|
|
204
|
+
an API key; GLEIF, EDGAR and VIES do not, and no schema here accepts a
|
|
205
|
+
credential. HMRC's current VAT checker (version 2.0) does need one, which is
|
|
206
|
+
why GB registration is could-not-check (see above).
|
|
193
207
|
- **EDGAR by name covers listed filers only**, through EDGAR's own ticker map,
|
|
194
208
|
and each row says so. Not finding a company there is not evidence it does not
|
|
195
209
|
exist.
|
package/dist/index.js
CHANGED
|
@@ -28,15 +28,15 @@
|
|
|
28
28
|
* leave the process are a VAT id or a company identifier going to a public
|
|
29
29
|
* register. `index.test.ts` asserts both over every schema in the package.
|
|
30
30
|
*/
|
|
31
|
-
import { readFileSync, statSync } from "node:fs";
|
|
32
31
|
import { buildTool } from "@crewhaus/tool-builder";
|
|
32
|
+
import { openForReadSync } from "@crewhaus/tool-safety/fs";
|
|
33
33
|
import { z } from "zod";
|
|
34
34
|
import { LEI_PATTERN, leiChecksumValid, normalizeEdgar, normalizeGleif, padCik, tickerIndex, } from "./lib/entity";
|
|
35
35
|
import { canonicalizeName, rankNames, round6 } from "./lib/names";
|
|
36
36
|
import { DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, ORIGINS, getJson, json, parseInstant, safeLabel, startDeadline, } from "./lib/net";
|
|
37
37
|
import { checkSnapshot, screenSubjects, } from "./lib/screen";
|
|
38
38
|
import { checkSyntax, hmrcErrorMeaning, mapHmrcResponse, mapViesResponse, parseVatId, } from "./lib/vat";
|
|
39
|
-
import { resolveSafe } from "./paths";
|
|
39
|
+
import { resolveSafe, workspaceRoot } from "./paths";
|
|
40
40
|
export { _setKycFetch, ORIGINS } from "./lib/net";
|
|
41
41
|
const LIMITS = {
|
|
42
42
|
subjects: 500,
|
|
@@ -84,6 +84,7 @@ function retryable(kind) {
|
|
|
84
84
|
// ---------------------------------------------------------------------------
|
|
85
85
|
export const vatIdValidate = buildTool({
|
|
86
86
|
name: "VatIdValidate",
|
|
87
|
+
operativeArgs: [],
|
|
87
88
|
description: "Check an EU, Northern Irish or UK VAT number: its country's own format first, then VIES or HMRC for whether it is actually registered, with the consultation number when a requester id is supplied. Use it before zero-rating an intra-community supply or paying an invoice that claims a VAT number. It reports THREE outcomes — registered, not registered, and could-not-check with the reason — because VIES is a proxy to member states' systems that are routinely down, and reading an outage as 'not valid' gets the invoice wrong. A registered number means the number exists, not that it belongs to whoever sent you the invoice.",
|
|
88
89
|
inputSchema: z
|
|
89
90
|
.object({
|
|
@@ -156,11 +157,21 @@ export const vatIdValidate = buildTool({
|
|
|
156
157
|
retryable: true,
|
|
157
158
|
});
|
|
158
159
|
}
|
|
159
|
-
const
|
|
160
|
-
if (
|
|
161
|
-
return `VatIdValidate could not read requesterVatId "${input.requesterVatId}": ${
|
|
160
|
+
const parsedRequester = input.requesterVatId === undefined ? undefined : parseVatId(input.requesterVatId);
|
|
161
|
+
if (parsedRequester !== undefined && !parsedRequester.ok) {
|
|
162
|
+
return `VatIdValidate could not read requesterVatId "${input.requesterVatId}": ${parsedRequester.reason}`;
|
|
162
163
|
}
|
|
163
|
-
|
|
164
|
+
// The requester is held to its country's grammar too, before anything is
|
|
165
|
+
// dialled: it becomes part of HMRC's request path, and an unchecked one
|
|
166
|
+
// rewrote that path to ask about a different number.
|
|
167
|
+
const requesterSyntax = parsedRequester === undefined ? undefined : checkSyntax(parsedRequester);
|
|
168
|
+
if (requesterSyntax !== undefined && !requesterSyntax.wellFormed) {
|
|
169
|
+
return `VatIdValidate will not use requesterVatId "${input.requesterVatId}": ${requesterSyntax.reason}`;
|
|
170
|
+
}
|
|
171
|
+
const requester = requesterSyntax === undefined
|
|
172
|
+
? undefined
|
|
173
|
+
: { country: { code: requesterSyntax.country }, number: requesterSyntax.number };
|
|
174
|
+
if (requester !== undefined && requesterSyntax !== undefined) {
|
|
164
175
|
// The two registers issue their receipt to their OWN kind of requester:
|
|
165
176
|
// HMRC takes a GB VRN, VIES takes a member state's number. Sending the
|
|
166
177
|
// wrong one means the number part is read as if it belonged to the other
|
|
@@ -170,7 +181,7 @@ export const vatIdValidate = buildTool({
|
|
|
170
181
|
const targetIsGb = syntax.country === "GB";
|
|
171
182
|
const requesterIsGb = requester.country.code === "GB";
|
|
172
183
|
if (targetIsGb !== requesterIsGb) {
|
|
173
|
-
return `VatIdValidate will not use requesterVatId ${
|
|
184
|
+
return `VatIdValidate will not use requesterVatId ${requesterSyntax.canonical} for ${syntax.canonical}: ${targetIsGb
|
|
174
185
|
? "HMRC issues a consultation number only to a GB requester"
|
|
175
186
|
: "VIES issues a consultation number only to a requester registered in a member state, and GB is no longer one"}. Drop requesterVatId to get the registration answer without a consultation number.`;
|
|
176
187
|
}
|
|
@@ -178,8 +189,8 @@ export const vatIdValidate = buildTool({
|
|
|
178
189
|
const deadline = startDeadline(input.timeoutMs ?? DEFAULT_TIMEOUT_MS, ctx?.signal);
|
|
179
190
|
try {
|
|
180
191
|
const answer = syntax.country === "GB"
|
|
181
|
-
? await askHmrc(syntax.number, requester?.
|
|
182
|
-
: await askVies(syntax.country, syntax.number, requester
|
|
192
|
+
? await askHmrc(syntax.number, requester?.number, deadline.signal)
|
|
193
|
+
: await askVies(syntax.country, syntax.number, requester, deadline.signal);
|
|
183
194
|
return json({
|
|
184
195
|
...base,
|
|
185
196
|
...answer.answer,
|
|
@@ -206,7 +217,7 @@ async function askVies(country, number, requester, signal) {
|
|
|
206
217
|
const twoParty = requester !== undefined;
|
|
207
218
|
const url = twoParty
|
|
208
219
|
? `${ORIGINS.vies}/taxation_customs/vies/rest-api/check-vat-number`
|
|
209
|
-
: `${ORIGINS.vies}/taxation_customs/vies/rest-api/ms/${country}/vat/${number}`;
|
|
220
|
+
: `${ORIGINS.vies}/taxation_customs/vies/rest-api/ms/${encodeURIComponent(country)}/vat/${encodeURIComponent(number)}`;
|
|
210
221
|
const result = await getJson(url, {
|
|
211
222
|
signal,
|
|
212
223
|
...(twoParty
|
|
@@ -230,15 +241,20 @@ async function askVies(country, number, requester, signal) {
|
|
|
230
241
|
};
|
|
231
242
|
}
|
|
232
243
|
async function askHmrc(number, requesterNumber, signal) {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
244
|
+
// Both numbers passed their country's grammar before this is reached (GB:
|
|
245
|
+
// digits, or GD/HA and digits); encoding them anyway means no value can
|
|
246
|
+
// ever be read as more path.
|
|
247
|
+
const segments = [number, ...(requesterNumber === undefined ? [] : [requesterNumber])];
|
|
248
|
+
const path = `/organisations/vat/check-vat-number/lookup/${segments.map(encodeURIComponent).join("/")}`;
|
|
236
249
|
const url = `${ORIGINS.hmrc}${path}`;
|
|
237
250
|
// HMRC versions its APIs through the Accept header and answers 406 without
|
|
238
251
|
// one. It is not a credential — every caller sends the same string.
|
|
239
252
|
const result = await getJson(url, { signal, accept: "application/vnd.hmrc.1.0+json" });
|
|
240
253
|
if (!result.ok) {
|
|
241
|
-
|
|
254
|
+
// A 404 is about the subject only when HMRC's own code says so. Any other
|
|
255
|
+
// 404 — no code, a body that is not JSON, or a route that matches nothing
|
|
256
|
+
// — says nothing about whether the number is registered.
|
|
257
|
+
if (result.kind === "notFound" && result.code === "NOT_FOUND") {
|
|
242
258
|
return {
|
|
243
259
|
answer: {
|
|
244
260
|
outcome: "notFound",
|
|
@@ -249,10 +265,22 @@ async function askHmrc(number, requesterNumber, signal) {
|
|
|
249
265
|
sourceUrl: safeLabel(url),
|
|
250
266
|
};
|
|
251
267
|
}
|
|
268
|
+
if (result.kind === "notFound") {
|
|
269
|
+
return {
|
|
270
|
+
answer: {
|
|
271
|
+
outcome: "unavailable",
|
|
272
|
+
basis: hmrcErrorMeaning(result.code, result.status),
|
|
273
|
+
retryable: false,
|
|
274
|
+
code: result.code ?? `HTTP ${result.status ?? 404}`,
|
|
275
|
+
},
|
|
276
|
+
register: "hmrc",
|
|
277
|
+
sourceUrl: safeLabel(url),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
252
280
|
return { answer: unavailableFrom(result, "HMRC"), register: "hmrc", sourceUrl: safeLabel(url) };
|
|
253
281
|
}
|
|
254
282
|
return {
|
|
255
|
-
answer: mapHmrcResponse(result.value, requesterNumber !== undefined),
|
|
283
|
+
answer: mapHmrcResponse(result.value, requesterNumber !== undefined, number),
|
|
256
284
|
register: "hmrc",
|
|
257
285
|
sourceUrl: safeLabel(url),
|
|
258
286
|
};
|
|
@@ -263,6 +291,7 @@ async function askHmrc(number, requesterNumber, signal) {
|
|
|
263
291
|
const REGISTRIES = ["gleif", "sec-edgar"];
|
|
264
292
|
export const entityRegistryLookup = buildTool({
|
|
265
293
|
name: "EntityRegistryLookup",
|
|
294
|
+
operativeArgs: [],
|
|
266
295
|
description: "Look one company up in GLEIF and SEC EDGAR by LEI, CIK, ticker or name, and return one row per register with its own source URL and retrieval time. Use it to check a counterparty exists and is who the invoice says. The rows are NOT merged into one confident record: the registers disagree about legal names, and GLEIF's two statuses answer different questions — a LAPSED LEI usually means an unpaid renewal, not a dissolved company. The result shows the differences and lets the caller judge them, and a register that could not be read is reported as could-not-check, never as 'no such company'.",
|
|
267
296
|
inputSchema: z
|
|
268
297
|
.object({
|
|
@@ -756,22 +785,25 @@ export const sanctionsScreen = buildTool({
|
|
|
756
785
|
const snapshots = [...(input.lists ?? [])];
|
|
757
786
|
for (const file of input.listFiles ?? []) {
|
|
758
787
|
const at = resolveSafe("SanctionsScreen", file);
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
788
|
+
// Opened without blocking, and only as a regular file: a FIFO with no
|
|
789
|
+
// writer blocks an ordinary open for ever, and this read was
|
|
790
|
+
// synchronous, so a named pipe named as a list stopped the whole
|
|
791
|
+
// harness (C074). The limit is enforced while reading.
|
|
792
|
+
const read = openForReadSync(workspaceRoot(), file, { maxBytes: LIMITS.snapshotBytes });
|
|
793
|
+
if (!read.ok) {
|
|
764
794
|
// A refusal in the package's own words, with the path as the caller
|
|
765
795
|
// wrote it. The raw ENOENT carries an absolute path from this machine,
|
|
766
796
|
// which is both unreadable and more than the caller asked for.
|
|
767
|
-
return
|
|
797
|
+
return read.code === "not-found"
|
|
798
|
+
? `SanctionsScreen refused ${at.rel}: there is no such file in the workspace`
|
|
799
|
+
: `SanctionsScreen refused ${at.rel}: ${read.reason}`;
|
|
768
800
|
}
|
|
769
|
-
if (
|
|
770
|
-
return `SanctionsScreen refused ${at.rel}: it is ${size} bytes, over the ${LIMITS.snapshotBytes}-byte limit`;
|
|
801
|
+
if (read.truncated) {
|
|
802
|
+
return `SanctionsScreen refused ${at.rel}: it is ${read.size} bytes, over the ${LIMITS.snapshotBytes}-byte limit`;
|
|
771
803
|
}
|
|
772
804
|
let document;
|
|
773
805
|
try {
|
|
774
|
-
document = JSON.parse(
|
|
806
|
+
document = JSON.parse(read.text);
|
|
775
807
|
}
|
|
776
808
|
catch (err) {
|
|
777
809
|
return `SanctionsScreen refused ${at.rel}: it is not JSON (${err.message})`;
|
package/dist/lib/net.d.ts
CHANGED
|
@@ -93,6 +93,12 @@ export type JsonFetch = {
|
|
|
93
93
|
readonly message: string;
|
|
94
94
|
/** Seconds the server asked us to wait, when it said. */
|
|
95
95
|
readonly retryAfter?: string;
|
|
96
|
+
/**
|
|
97
|
+
* On `notFound`: the `code` field of the register's JSON error body,
|
|
98
|
+
* when it had one. A 404 says a route matched nothing, which is only
|
|
99
|
+
* about the subject when the register's code says so.
|
|
100
|
+
*/
|
|
101
|
+
readonly code?: string;
|
|
96
102
|
};
|
|
97
103
|
export type GetJsonOptions = {
|
|
98
104
|
readonly signal?: AbortSignal;
|
|
@@ -123,12 +129,22 @@ export type CappedBody = {
|
|
|
123
129
|
readonly text: string;
|
|
124
130
|
readonly bytes: number;
|
|
125
131
|
readonly truncated: boolean;
|
|
132
|
+
/**
|
|
133
|
+
* Set when the body could not be read as what it claims to be (an
|
|
134
|
+
* unsupported or corrupt content-encoding, a connection that closed
|
|
135
|
+
* early): `text` is then empty, and nothing was parsed.
|
|
136
|
+
*/
|
|
137
|
+
readonly unreadable?: string;
|
|
126
138
|
};
|
|
127
139
|
/**
|
|
128
|
-
* Drain a body with a hard
|
|
129
|
-
* is
|
|
140
|
+
* Drain a body with a hard cap on its DECODED size. The cap bounds MEMORY,
|
|
141
|
+
* not just what is kept: the body arrives raw (see `pinnedFetch`), a gzip,
|
|
142
|
+
* deflate, br or zstd body is decoded here in small steps, and the decoder
|
|
143
|
+
* stops once `maxBytes` exist. A body past the cap comes back truncated and
|
|
144
|
+
* EMPTY, so no caller can parse a prefix. An aborted read throws, as the
|
|
145
|
+
* runtime's own reader did.
|
|
130
146
|
*/
|
|
131
|
-
export declare function readCapped(res: Response, maxBytes: number): Promise<CappedBody>;
|
|
147
|
+
export declare function readCapped(res: Response, maxBytes: number, signal?: AbortSignal): Promise<CappedBody>;
|
|
132
148
|
export type Deadline = {
|
|
133
149
|
readonly signal: AbortSignal;
|
|
134
150
|
/** Clear the timer. Always call it, or the process keeps a handle alive. */
|
package/dist/lib/net.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
*/
|
|
22
22
|
import { CrewhausError } from "@crewhaus/errors";
|
|
23
23
|
import { assertNotSsrf } from "@crewhaus/tool-fetch";
|
|
24
|
+
import { fetchRaw, readResponseBounded } from "@crewhaus/tool-safety/streams";
|
|
24
25
|
/** A refusal by the origin rule, the redirect rule or the byte cap. */
|
|
25
26
|
export class KycNetworkError extends CrewhausError {
|
|
26
27
|
name = "KycNetworkError";
|
|
@@ -80,8 +81,13 @@ export const json = (value) => JSON.stringify(value);
|
|
|
80
81
|
function pinnedFetch(req, pinnedIp) {
|
|
81
82
|
const original = new URL(req.url);
|
|
82
83
|
const host = original.hostname;
|
|
84
|
+
// Both branches keep the body RAW (`fetchRaw`, Bun's `decompress: false`):
|
|
85
|
+
// otherwise Bun inflates a gzip, deflate, br or zstd body in native code
|
|
86
|
+
// before any reader sees a byte, and a 260 KB gzip of zeros cost about
|
|
87
|
+
// 1 GB of RSS before the byte cap fired (C093). `readCapped` decodes it,
|
|
88
|
+
// under the cap.
|
|
83
89
|
if (pinnedIp === "" || host === pinnedIp)
|
|
84
|
-
return
|
|
90
|
+
return fetchRaw(req);
|
|
85
91
|
const pinnedUrl = new URL(original.toString());
|
|
86
92
|
pinnedUrl.hostname = pinnedIp.includes(":") ? `[${pinnedIp}]` : pinnedIp;
|
|
87
93
|
const headers = new Headers(req.headers);
|
|
@@ -93,7 +99,7 @@ function pinnedFetch(req, pinnedIp) {
|
|
|
93
99
|
signal: req.signal,
|
|
94
100
|
tls: { serverName: host },
|
|
95
101
|
};
|
|
96
|
-
return
|
|
102
|
+
return fetchRaw(pinnedUrl.toString(), init);
|
|
97
103
|
}
|
|
98
104
|
const guardedFetch = async (req) => {
|
|
99
105
|
const url = new URL(req.url);
|
|
@@ -216,12 +222,13 @@ export async function getJson(rawUrl, options = {}) {
|
|
|
216
222
|
continue;
|
|
217
223
|
}
|
|
218
224
|
if (res.status === 404 || res.status === 410) {
|
|
219
|
-
await
|
|
225
|
+
const code = await errorCode(res);
|
|
220
226
|
return {
|
|
221
227
|
ok: false,
|
|
222
228
|
kind: "notFound",
|
|
223
229
|
status: res.status,
|
|
224
|
-
message: `${safeLabel(current)} answered ${res.status}`,
|
|
230
|
+
message: `${safeLabel(current)} answered ${res.status}${code === undefined ? "" : ` (${code})`}`,
|
|
231
|
+
...(code === undefined ? {} : { code }),
|
|
225
232
|
};
|
|
226
233
|
}
|
|
227
234
|
if (res.status === 401 || res.status === 403) {
|
|
@@ -257,7 +264,15 @@ export async function getJson(rawUrl, options = {}) {
|
|
|
257
264
|
message: `${safeLabel(current)} answered ${res.status} ${res.statusText}`.trimEnd(),
|
|
258
265
|
};
|
|
259
266
|
}
|
|
260
|
-
const body = await readCapped(res, maxBytes);
|
|
267
|
+
const body = await readCapped(res, maxBytes, options.signal);
|
|
268
|
+
if (body.unreadable !== undefined) {
|
|
269
|
+
return {
|
|
270
|
+
ok: false,
|
|
271
|
+
kind: "malformed",
|
|
272
|
+
status: res.status,
|
|
273
|
+
message: `${safeLabel(current)} answered with a body that ${body.unreadable}`,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
261
276
|
if (body.truncated) {
|
|
262
277
|
// Parsing the prefix is the tempting mistake: half an EDGAR submissions
|
|
263
278
|
// document still parses into a shorter, plausible, WRONG answer.
|
|
@@ -291,6 +306,27 @@ export function safeLabel(url) {
|
|
|
291
306
|
return String(url);
|
|
292
307
|
}
|
|
293
308
|
}
|
|
309
|
+
/** An error body is small; anything past this is not one worth reading. */
|
|
310
|
+
const ERROR_BODY_BYTES = 4096;
|
|
311
|
+
/**
|
|
312
|
+
* The `code` of a JSON error body — `{"code":"NOT_FOUND","message":…}` —
|
|
313
|
+
* read under a small cap, or undefined when there is none to read.
|
|
314
|
+
*/
|
|
315
|
+
async function errorCode(res) {
|
|
316
|
+
const body = await readCapped(res, ERROR_BODY_BYTES);
|
|
317
|
+
if (body.truncated)
|
|
318
|
+
return undefined;
|
|
319
|
+
try {
|
|
320
|
+
const parsed = JSON.parse(body.text);
|
|
321
|
+
const code = typeof parsed === "object" && parsed !== null
|
|
322
|
+
? parsed["code"]
|
|
323
|
+
: undefined;
|
|
324
|
+
return typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code) ? code : undefined;
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
return undefined;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
294
330
|
async function discard(res) {
|
|
295
331
|
try {
|
|
296
332
|
await res.body?.cancel();
|
|
@@ -300,60 +336,37 @@ async function discard(res) {
|
|
|
300
336
|
}
|
|
301
337
|
}
|
|
302
338
|
/**
|
|
303
|
-
* Drain a body with a hard
|
|
304
|
-
* is
|
|
339
|
+
* Drain a body with a hard cap on its DECODED size. The cap bounds MEMORY,
|
|
340
|
+
* not just what is kept: the body arrives raw (see `pinnedFetch`), a gzip,
|
|
341
|
+
* deflate, br or zstd body is decoded here in small steps, and the decoder
|
|
342
|
+
* stops once `maxBytes` exist. A body past the cap comes back truncated and
|
|
343
|
+
* EMPTY, so no caller can parse a prefix. An aborted read throws, as the
|
|
344
|
+
* runtime's own reader did.
|
|
305
345
|
*/
|
|
306
|
-
export async function readCapped(res, maxBytes) {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
const chunks = [];
|
|
316
|
-
let total = 0;
|
|
317
|
-
let truncated = false;
|
|
318
|
-
try {
|
|
319
|
-
while (true) {
|
|
320
|
-
const { done, value } = await reader.read();
|
|
321
|
-
if (done || value === undefined)
|
|
322
|
-
break;
|
|
323
|
-
if (total + value.byteLength > maxBytes) {
|
|
324
|
-
truncated = true;
|
|
325
|
-
try {
|
|
326
|
-
await reader.cancel();
|
|
327
|
-
}
|
|
328
|
-
catch {
|
|
329
|
-
// already aborting
|
|
330
|
-
}
|
|
331
|
-
break;
|
|
332
|
-
}
|
|
333
|
-
chunks.push(value);
|
|
334
|
-
total += value.byteLength;
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
finally {
|
|
338
|
-
try {
|
|
339
|
-
reader.releaseLock();
|
|
340
|
-
}
|
|
341
|
-
catch {
|
|
342
|
-
// already released
|
|
343
|
-
}
|
|
346
|
+
export async function readCapped(res, maxBytes, signal) {
|
|
347
|
+
const read = await readResponseBounded(res, {
|
|
348
|
+
maxBytes,
|
|
349
|
+
...(signal !== undefined ? { signal } : {}),
|
|
350
|
+
});
|
|
351
|
+
if (read.ok) {
|
|
352
|
+
return read.truncated
|
|
353
|
+
? { text: "", bytes: read.decodedBytes, truncated: true }
|
|
354
|
+
: { text: read.text, bytes: read.bytes.byteLength, truncated: false };
|
|
344
355
|
}
|
|
345
|
-
if (
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
for (const chunk of chunks) {
|
|
350
|
-
merged.set(chunk, offset);
|
|
351
|
-
offset += chunk.byteLength;
|
|
356
|
+
if (read.code === "aborted" || read.code === "stalled") {
|
|
357
|
+
const err = new Error("the read was aborted before the body ended");
|
|
358
|
+
err.name = "AbortError";
|
|
359
|
+
throw err;
|
|
352
360
|
}
|
|
353
361
|
return {
|
|
354
|
-
text:
|
|
355
|
-
bytes:
|
|
362
|
+
text: "",
|
|
363
|
+
bytes: 0,
|
|
356
364
|
truncated: false,
|
|
365
|
+
unreadable: read.code === "unsupported-encoding"
|
|
366
|
+
? "uses a stack of content-encodings this tool cannot decode within its cap"
|
|
367
|
+
: read.code === "read-error"
|
|
368
|
+
? "ended before it was complete"
|
|
369
|
+
: "is labelled as compressed but could not be decoded",
|
|
357
370
|
};
|
|
358
371
|
}
|
|
359
372
|
/**
|
package/dist/lib/vat.d.ts
CHANGED
|
@@ -132,6 +132,6 @@ export declare function mapViesResponse(body: unknown, requesterSupplied: boolea
|
|
|
132
132
|
* 503 with a maintenance code for an outage. The failure path lives in the
|
|
133
133
|
* caller; this reads the 200 body.
|
|
134
134
|
*/
|
|
135
|
-
export declare function mapHmrcResponse(body: unknown, requesterSupplied: boolean): RegisterAnswer;
|
|
135
|
+
export declare function mapHmrcResponse(body: unknown, requesterSupplied: boolean, askedNumber: string): RegisterAnswer;
|
|
136
136
|
/** The codes HMRC returns in an error body, and what each one means for us. */
|
|
137
137
|
export declare function hmrcErrorMeaning(code: string | undefined, status: number | undefined): string;
|
package/dist/lib/vat.js
CHANGED
|
@@ -322,17 +322,29 @@ export function mapViesResponse(body, requesterSupplied) {
|
|
|
322
322
|
* 503 with a maintenance code for an outage. The failure path lives in the
|
|
323
323
|
* caller; this reads the 200 body.
|
|
324
324
|
*/
|
|
325
|
-
export function mapHmrcResponse(body, requesterSupplied) {
|
|
325
|
+
export function mapHmrcResponse(body, requesterSupplied, askedNumber) {
|
|
326
326
|
const doc = (body ?? {});
|
|
327
327
|
const target = (doc["target"] ?? {});
|
|
328
328
|
const name = str(target["name"]);
|
|
329
|
-
|
|
329
|
+
const answeredNumber = str(target["vatNumber"]);
|
|
330
|
+
if (name === undefined && answeredNumber === undefined) {
|
|
330
331
|
return {
|
|
331
332
|
outcome: "unavailable",
|
|
332
333
|
basis: "HMRC answered 200 with no target — the response shape is not one this tool can read, and an empty body is not evidence that a number is unregistered",
|
|
333
334
|
retryable: false,
|
|
334
335
|
};
|
|
335
336
|
}
|
|
337
|
+
// The answer must be about the number asked about. A branch trader's 12
|
|
338
|
+
// digits are its 9-digit VRN plus a branch, so either form matches.
|
|
339
|
+
if (answeredNumber !== undefined &&
|
|
340
|
+
answeredNumber !== askedNumber &&
|
|
341
|
+
answeredNumber !== askedNumber.slice(0, 9)) {
|
|
342
|
+
return {
|
|
343
|
+
outcome: "unavailable",
|
|
344
|
+
basis: `HMRC answered about ${answeredNumber}, not the number asked about (${askedNumber}), so its answer says nothing about this one`,
|
|
345
|
+
retryable: false,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
336
348
|
const address = target["address"];
|
|
337
349
|
const addressLine = address === undefined
|
|
338
350
|
? undefined
|
|
@@ -375,6 +387,11 @@ export function hmrcErrorMeaning(code, status) {
|
|
|
375
387
|
switch (code) {
|
|
376
388
|
case "NOT_FOUND":
|
|
377
389
|
return "HMRC: this number is not registered for VAT";
|
|
390
|
+
case "MATCHING_RESOURCE_NOT_FOUND":
|
|
391
|
+
// HMRC's answer for a request no API route or version matches. It is
|
|
392
|
+
// what version 1.0 of the checker has answered since HMRC removed it
|
|
393
|
+
// (February 2025); version 2.0 needs registered API credentials.
|
|
394
|
+
return "HMRC answered MATCHING_RESOURCE_NOT_FOUND: no API route matches the request, which is what HMRC answers since it removed version 1.0 of its unauthenticated VAT checker (February 2025). Version 2.0 needs registered API credentials, which this tool does not hold, so GB registration could not be checked";
|
|
378
395
|
case "INVALID_REQUEST":
|
|
379
396
|
return "HMRC rejected the request as malformed and did not look the number up";
|
|
380
397
|
case "SCHEDULED_MAINTENANCE":
|
|
@@ -383,6 +400,6 @@ export function hmrcErrorMeaning(code, status) {
|
|
|
383
400
|
case "INTERNAL_SERVER_ERROR":
|
|
384
401
|
return "HMRC's checker failed internally";
|
|
385
402
|
default:
|
|
386
|
-
return `HMRC answered ${status ?? "an error"}${code === undefined ? "" : ` with the code "${code}"`}`;
|
|
403
|
+
return `HMRC answered ${status ?? "an error"}${code === undefined ? " with no error code, which says nothing about the number" : ` with the code "${code}"`}`;
|
|
387
404
|
}
|
|
388
405
|
}
|
package/dist/paths.d.ts
CHANGED
|
@@ -1,10 +1,29 @@
|
|
|
1
1
|
import { CrewhausError } from "@crewhaus/errors";
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
3
|
+
* The longest path this resolves, in UTF-16 code units; a longer one is
|
|
4
|
+
* refused before it is walked. Nothing that long can be opened or created:
|
|
5
|
+
* PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
|
|
6
|
+
* 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
|
|
7
|
+
* UTF-16 one. The limit is twice that because the part of a path that exists
|
|
8
|
+
* is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
|
|
9
|
+
* own: no spelling of the place reaches it, not even one through a symlink
|
|
10
|
+
* that shortens the part that exists.
|
|
11
|
+
*/
|
|
12
|
+
export declare const MAX_PATH_CHARS: number;
|
|
13
|
+
/**
|
|
14
|
+
* Raised when a caller-supplied path resolves outside the workspace root, or
|
|
15
|
+
* is longer than any path can be.
|
|
16
|
+
*/
|
|
3
17
|
export declare class ToolPermissionError extends CrewhausError {
|
|
4
18
|
readonly name = "ToolPermissionError";
|
|
5
19
|
readonly toolName: string;
|
|
6
20
|
readonly path: string;
|
|
7
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Why, when it is not that the location escapes the workspace root: a path
|
|
23
|
+
* longer than any path can be. A caller that rewords the refusal says this.
|
|
24
|
+
*/
|
|
25
|
+
readonly reason: string | undefined;
|
|
26
|
+
constructor(toolName: string, attemptedPath: string, reason?: string);
|
|
8
27
|
}
|
|
9
28
|
/**
|
|
10
29
|
* A validated path, in both forms the tools need.
|
package/dist/paths.js
CHANGED
|
@@ -11,15 +11,45 @@
|
|
|
11
11
|
import { lstatSync, readlinkSync, realpathSync } from "node:fs";
|
|
12
12
|
import * as path from "node:path";
|
|
13
13
|
import { CrewhausError } from "@crewhaus/errors";
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* The longest path this resolves, in UTF-16 code units; a longer one is
|
|
16
|
+
* refused before it is walked. Nothing that long can be opened or created:
|
|
17
|
+
* PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
|
|
18
|
+
* 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
|
|
19
|
+
* UTF-16 one. The limit is twice that because the part of a path that exists
|
|
20
|
+
* is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
|
|
21
|
+
* own: no spelling of the place reaches it, not even one through a symlink
|
|
22
|
+
* that shortens the part that exists.
|
|
23
|
+
*/
|
|
24
|
+
export const MAX_PATH_CHARS = 2 * (process.platform === "darwin" ? 1_024 : process.platform === "win32" ? 32_767 : 4_096);
|
|
25
|
+
/** A path as a refusal quotes it: whole, unless it is past {@link MAX_PATH_CHARS}. */
|
|
26
|
+
function shownPath(given) {
|
|
27
|
+
return given.length > MAX_PATH_CHARS ? `${given.slice(0, 64)}…` : given;
|
|
28
|
+
}
|
|
29
|
+
/** Why a path past {@link MAX_PATH_CHARS} is refused: its length and the limit. */
|
|
30
|
+
function tooLong(abs) {
|
|
31
|
+
return `it is ${abs.length} characters once resolved, over the ${MAX_PATH_CHARS}-character limit: no path that long can be opened or created`;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Raised when a caller-supplied path resolves outside the workspace root, or
|
|
35
|
+
* is longer than any path can be.
|
|
36
|
+
*/
|
|
15
37
|
export class ToolPermissionError extends CrewhausError {
|
|
16
38
|
name = "ToolPermissionError";
|
|
17
39
|
toolName;
|
|
18
40
|
path;
|
|
19
|
-
|
|
20
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Why, when it is not that the location escapes the workspace root: a path
|
|
43
|
+
* longer than any path can be. A caller that rewords the refusal says this.
|
|
44
|
+
*/
|
|
45
|
+
reason;
|
|
46
|
+
constructor(toolName, attemptedPath, reason) {
|
|
47
|
+
super("tool", reason === undefined
|
|
48
|
+
? `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`
|
|
49
|
+
: `tool "${toolName}" rejected path "${shownPath(attemptedPath)}": ${reason}`);
|
|
21
50
|
this.toolName = toolName;
|
|
22
51
|
this.path = attemptedPath;
|
|
52
|
+
this.reason = reason;
|
|
23
53
|
}
|
|
24
54
|
}
|
|
25
55
|
/** The workspace root, resolved. Every path is contained within it. */
|
|
@@ -67,15 +97,7 @@ function nameExists(p) {
|
|
|
67
97
|
function resolveLocation(target, depth = 0) {
|
|
68
98
|
if (depth > 40)
|
|
69
99
|
throw new Error(`symlink chain at "${target}" is too long to resolve`);
|
|
70
|
-
|
|
71
|
-
const tail = [];
|
|
72
|
-
while (!nameExists(probe)) {
|
|
73
|
-
tail.unshift(path.basename(probe));
|
|
74
|
-
const parent = path.dirname(probe);
|
|
75
|
-
if (parent === probe)
|
|
76
|
-
break; // reached the filesystem root
|
|
77
|
-
probe = parent;
|
|
78
|
-
}
|
|
100
|
+
const { probe, tail } = deepestName(target);
|
|
79
101
|
let probeReal;
|
|
80
102
|
try {
|
|
81
103
|
probeReal = realpathSync(probe);
|
|
@@ -97,7 +119,41 @@ function resolveLocation(target, depth = 0) {
|
|
|
97
119
|
const base = realpathSync(path.dirname(probe));
|
|
98
120
|
probeReal = resolveLocation(path.resolve(base, link), depth + 1);
|
|
99
121
|
}
|
|
100
|
-
|
|
122
|
+
// One string, not one argument per name: Bun's `path.join` keeps only
|
|
123
|
+
// (argument count mod 65,536) of its arguments.
|
|
124
|
+
return tail.length > 0 ? path.join(probeReal, tail) : probeReal;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* `target`, an absolute path, split where its deepest prefix that exists as
|
|
128
|
+
* a NAME ends: that prefix, and the names below it, which do not exist, as
|
|
129
|
+
* one string ("" when `target` itself exists). This is `path.dirname` and
|
|
130
|
+
* `path.basename` worked by index on `target` itself: handing them each
|
|
131
|
+
* shorter prefix in turn copied the rest of the path once per missing name,
|
|
132
|
+
* the square of a count the caller picks.
|
|
133
|
+
*/
|
|
134
|
+
function deepestName(target) {
|
|
135
|
+
const top = path.parse(target).root.length;
|
|
136
|
+
const isSep = (i) => target[i] === "/" || target[i] === path.sep;
|
|
137
|
+
let probe = target;
|
|
138
|
+
let start = target.length;
|
|
139
|
+
let stop = -1;
|
|
140
|
+
while (!nameExists(probe)) {
|
|
141
|
+
// `path.basename(probe)` is `target.slice(start, end)`, and
|
|
142
|
+
// `path.dirname(probe)` is `target.slice(0, up)`.
|
|
143
|
+
let end = probe.length;
|
|
144
|
+
while (end > top && isSep(end - 1))
|
|
145
|
+
end--;
|
|
146
|
+
if (stop < 0)
|
|
147
|
+
stop = end;
|
|
148
|
+
start = end;
|
|
149
|
+
while (start > top && !isSep(start - 1))
|
|
150
|
+
start--;
|
|
151
|
+
const up = start > top ? start - 1 : top;
|
|
152
|
+
if (up === probe.length)
|
|
153
|
+
break; // reached the filesystem root
|
|
154
|
+
probe = target.slice(0, up);
|
|
155
|
+
}
|
|
156
|
+
return { probe, tail: stop < 0 ? "" : target.slice(start, stop) };
|
|
101
157
|
}
|
|
102
158
|
export function resolveSafe(toolName, rel, root = workspaceRoot()) {
|
|
103
159
|
const rootResolved = path.resolve(root);
|
|
@@ -107,6 +163,9 @@ export function resolveSafe(toolName, rel, root = workspaceRoot()) {
|
|
|
107
163
|
if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
|
|
108
164
|
throw new ToolPermissionError(toolName, rel);
|
|
109
165
|
}
|
|
166
|
+
// Longer than any path can be: refused before the walk below reads it.
|
|
167
|
+
if (abs.length > MAX_PATH_CHARS)
|
|
168
|
+
throw new ToolPermissionError(toolName, rel, tooLong(abs));
|
|
110
169
|
let real;
|
|
111
170
|
try {
|
|
112
171
|
const rootReal = realpathSync(rootResolved);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/tool-kyc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Deterministic counterparty checks against public registries and sanctions lists, with versioned evidence",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -8,18 +8,20 @@
|
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
|
-
"import": "./dist/index.js"
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
12
13
|
}
|
|
13
14
|
},
|
|
14
15
|
"scripts": {
|
|
15
16
|
"test": "bun test src"
|
|
16
17
|
},
|
|
17
18
|
"dependencies": {
|
|
18
|
-
"@crewhaus/errors": "0.
|
|
19
|
-
"@crewhaus/tool-builder": "0.
|
|
20
|
-
"@crewhaus/tool-catalog": "0.
|
|
21
|
-
"@crewhaus/tool-fetch": "0.
|
|
22
|
-
"@crewhaus/tool-
|
|
19
|
+
"@crewhaus/errors": "0.8.1",
|
|
20
|
+
"@crewhaus/tool-builder": "0.8.1",
|
|
21
|
+
"@crewhaus/tool-catalog": "0.8.1",
|
|
22
|
+
"@crewhaus/tool-fetch": "0.8.1",
|
|
23
|
+
"@crewhaus/tool-safety": "0.8.1",
|
|
24
|
+
"@crewhaus/tool-text": "0.8.1",
|
|
23
25
|
"zod": "^3.23.8"
|
|
24
26
|
},
|
|
25
27
|
"devDependencies": {
|
|
@@ -43,5 +45,8 @@
|
|
|
43
45
|
"publishConfig": {
|
|
44
46
|
"access": "public"
|
|
45
47
|
},
|
|
46
|
-
"files": ["dist", "README.md", "LICENSE", "NOTICE"]
|
|
48
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"],
|
|
49
|
+
"engines": {
|
|
50
|
+
"bun": ">=1.3.14"
|
|
51
|
+
}
|
|
47
52
|
}
|