@crewhaus/tool-kyc 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +216 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +821 -0
- package/dist/lib/entity.d.ts +94 -0
- package/dist/lib/entity.js +230 -0
- package/dist/lib/names.d.ts +136 -0
- package/dist/lib/names.js +330 -0
- package/dist/lib/net.d.ts +151 -0
- package/dist/lib/net.js +399 -0
- package/dist/lib/screen.d.ts +186 -0
- package/dist/lib/screen.js +409 -0
- package/dist/lib/vat.d.ts +137 -0
- package/dist/lib/vat.js +388 -0
- package/dist/paths.d.ts +42 -0
- package/dist/paths.js +158 -0
- package/package.json +47 -0
package/dist/lib/vat.js
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VAT identification numbers: the local grammar, and how each register's
|
|
3
|
+
* answer maps onto the three outcomes.
|
|
4
|
+
*
|
|
5
|
+
* The rule that shapes this whole file: **`unavailable` never collapses into
|
|
6
|
+
* `notFound`.** VIES is a proxy — it forwards the question to the member
|
|
7
|
+
* state's own system, and those systems go down, individually, routinely, for
|
|
8
|
+
* hours. A tool that reports an outage as "this VAT number is not valid" makes
|
|
9
|
+
* a harness charge domestic VAT on an intra-community supply, or refuse to,
|
|
10
|
+
* because a government server was being rebooted. So every code VIES publishes
|
|
11
|
+
* is mapped explicitly here, and anything unrecognised fails to `unavailable`
|
|
12
|
+
* rather than to a verdict.
|
|
13
|
+
*
|
|
14
|
+
* The second rule: a syntax pass is not a registration, and a registration is
|
|
15
|
+
* not an identity. Both facts travel with the answer instead of being folded
|
|
16
|
+
* into one boolean.
|
|
17
|
+
*/
|
|
18
|
+
const c = (code, name, pattern, shape, register = "vies", note) => ({
|
|
19
|
+
code,
|
|
20
|
+
name,
|
|
21
|
+
pattern,
|
|
22
|
+
shape,
|
|
23
|
+
register,
|
|
24
|
+
...(note === undefined ? {} : { note }),
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* Per-country syntax, as a table.
|
|
28
|
+
*
|
|
29
|
+
* A generic "two letters then 8-12 alphanumerics" check passes ids that VIES
|
|
30
|
+
* then rejects, which is the worst of both: a local check that gives false
|
|
31
|
+
* confidence and a remote call that was avoidable. The awkward ones are the
|
|
32
|
+
* point of having a table at all — Ireland's letter in the MIDDLE, the
|
|
33
|
+
* Netherlands' mandatory B in position ten, Spain's letter-or-digit at each
|
|
34
|
+
* end, Greece filing under EL.
|
|
35
|
+
*/
|
|
36
|
+
export const VAT_COUNTRIES = Object.freeze({
|
|
37
|
+
AT: c("AT", "Austria", /^U\d{8}$/, "U followed by 8 digits"),
|
|
38
|
+
BE: c("BE", "Belgium", /^[01]\d{9}$/, "10 digits beginning 0 or 1"),
|
|
39
|
+
BG: c("BG", "Bulgaria", /^\d{9,10}$/, "9 or 10 digits"),
|
|
40
|
+
CY: c("CY", "Cyprus", /^\d{8}[A-Z]$/, "8 digits then a letter"),
|
|
41
|
+
CZ: c("CZ", "Czechia", /^\d{8,10}$/, "8, 9 or 10 digits"),
|
|
42
|
+
DE: c("DE", "Germany", /^\d{9}$/, "9 digits"),
|
|
43
|
+
DK: c("DK", "Denmark", /^\d{8}$/, "8 digits"),
|
|
44
|
+
EE: c("EE", "Estonia", /^\d{9}$/, "9 digits"),
|
|
45
|
+
EL: c("EL", "Greece", /^\d{9}$/, "9 digits", "vies", "Greece files under EL, not its ISO code GR; an id written GR… is accepted here and sent as EL"),
|
|
46
|
+
ES: c("ES", "Spain", /^[A-Z0-9]\d{7}[A-Z0-9]$/, "a letter or digit, 7 digits, then a letter or digit"),
|
|
47
|
+
FI: c("FI", "Finland", /^\d{8}$/, "8 digits"),
|
|
48
|
+
FR: c("FR", "France", /^[A-HJ-NP-Z0-9]{2}\d{9}$/, "2 check characters (letters excluding I and O, or digits) then 9 digits"),
|
|
49
|
+
HR: c("HR", "Croatia", /^\d{11}$/, "11 digits"),
|
|
50
|
+
HU: c("HU", "Hungary", /^\d{8}$/, "8 digits"),
|
|
51
|
+
IE: c("IE", "Ireland", /^(?:\d{7}[A-W]|\d[A-Z+*]\d{5}[A-W]|\d{7}[A-W][AH])$/, "7 digits and a letter, or a digit, a letter/+/*, 5 digits and a letter, or 7 digits, a letter and A or H", "vies", "the middle-character form (1X34567A) is the one a length-only check accepts and a digits-only check rejects; the 9-character form's last character is only ever A or H"),
|
|
52
|
+
IT: c("IT", "Italy", /^\d{11}$/, "11 digits"),
|
|
53
|
+
LT: c("LT", "Lithuania", /^(?:\d{9}|\d{12})$/, "9 or 12 digits"),
|
|
54
|
+
LU: c("LU", "Luxembourg", /^\d{8}$/, "8 digits"),
|
|
55
|
+
LV: c("LV", "Latvia", /^\d{11}$/, "11 digits"),
|
|
56
|
+
MT: c("MT", "Malta", /^\d{8}$/, "8 digits"),
|
|
57
|
+
NL: c("NL", "the Netherlands", /^[A-Z0-9+*]{9}B[A-Z0-9+*]{2}$/, "12 characters with B in position 10", "vies", "the B is positional, not a suffix: a sole trader's number since 2020 is not derived from anything and only the B is fixed"),
|
|
58
|
+
PL: c("PL", "Poland", /^\d{10}$/, "10 digits"),
|
|
59
|
+
PT: c("PT", "Portugal", /^\d{9}$/, "9 digits"),
|
|
60
|
+
RO: c("RO", "Romania", /^\d{2,10}$/, "2 to 10 digits"),
|
|
61
|
+
SE: c("SE", "Sweden", /^\d{12}$/, "12 digits"),
|
|
62
|
+
SI: c("SI", "Slovenia", /^\d{8}$/, "8 digits"),
|
|
63
|
+
SK: c("SK", "Slovakia", /^\d{10}$/, "10 digits"),
|
|
64
|
+
XI: c("XI", "Northern Ireland", /^(?:\d{9}|\d{12}|GD\d{3}|HA\d{3})$/, "9 or 12 digits, or GD/HA and 3 digits", "vies", "Northern Ireland stayed in VIES for goods after 2020; Great Britain did not"),
|
|
65
|
+
GB: c("GB", "the United Kingdom", /^(?:\d{9}|\d{12}|GD\d{3}|HA\d{3})$/, "9 or 12 digits, or GD/HA and 3 digits", "hmrc", "VIES has not answered for GB since 2021; this goes to HMRC's own checker"),
|
|
66
|
+
});
|
|
67
|
+
/** Greece's ISO code is GR and its VAT prefix is EL. Both are accepted. */
|
|
68
|
+
const ALIASES = Object.freeze({ GR: "EL", UK: "GB" });
|
|
69
|
+
/**
|
|
70
|
+
* Split an id into country and number.
|
|
71
|
+
*
|
|
72
|
+
* Spaces, dots and hyphens are removed because every register prints them
|
|
73
|
+
* differently and none of them stores them. The country either prefixes the
|
|
74
|
+
* id or is passed separately; when both are given and disagree, that is an
|
|
75
|
+
* error rather than a silent preference, because guessing which one the caller
|
|
76
|
+
* meant is how an Irish number gets checked against Italy's grammar.
|
|
77
|
+
*/
|
|
78
|
+
export function parseVatId(raw, declaredCountry) {
|
|
79
|
+
const cleaned = raw.toUpperCase().replace(/[\s.\-/]/g, "");
|
|
80
|
+
if (cleaned.length === 0)
|
|
81
|
+
return { ok: false, reason: "the VAT id is empty" };
|
|
82
|
+
const declared = declaredCountry === undefined
|
|
83
|
+
? undefined
|
|
84
|
+
: (ALIASES[declaredCountry.toUpperCase()] ?? declaredCountry.toUpperCase());
|
|
85
|
+
const prefix = cleaned.slice(0, 2);
|
|
86
|
+
const prefixed = ALIASES[prefix] ?? prefix;
|
|
87
|
+
const hasKnownPrefix = Object.hasOwn(VAT_COUNTRIES, prefixed);
|
|
88
|
+
let code;
|
|
89
|
+
let number;
|
|
90
|
+
if (hasKnownPrefix) {
|
|
91
|
+
code = prefixed;
|
|
92
|
+
number = cleaned.slice(2);
|
|
93
|
+
if (declared !== undefined && declared !== code) {
|
|
94
|
+
return {
|
|
95
|
+
ok: false,
|
|
96
|
+
reason: `the id is prefixed ${prefix} but country was given as ${declaredCountry} — one of them is wrong, and this tool will not pick`,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else if (declared !== undefined) {
|
|
101
|
+
code = declared;
|
|
102
|
+
number = cleaned;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
return {
|
|
106
|
+
ok: false,
|
|
107
|
+
reason: `"${cleaned.slice(0, 4)}…" carries no recognised country prefix — pass country explicitly when the id is written without one`,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const country = VAT_COUNTRIES[code];
|
|
111
|
+
if (country === undefined) {
|
|
112
|
+
return {
|
|
113
|
+
ok: false,
|
|
114
|
+
reason: `"${code}" is not an EU member state, Northern Ireland or the United Kingdom — this tool reads VIES and HMRC, and nothing else`,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
if (number.length === 0) {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
reason: `the id is only the country code ${code}, with no number after it`,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
return { ok: true, country, number, canonical: `${code}${number}` };
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The UK's check digits, which are real arithmetic rather than a shape.
|
|
127
|
+
*
|
|
128
|
+
* Two variants are in circulation: the original "mod 97" and the "mod 9755"
|
|
129
|
+
* used for numbers issued from 2004, which differs only by adding 55 before
|
|
130
|
+
* the modulus. Both are accepted, because a number issued under one is not
|
|
131
|
+
* invalid for failing the other — and which one applies is not recorded
|
|
132
|
+
* anywhere on the number.
|
|
133
|
+
*
|
|
134
|
+
* This is the only country whose arithmetic is implemented here. The other
|
|
135
|
+
* twenty-seven have twenty-seven different algorithms, and a checksum written
|
|
136
|
+
* from memory that reports `passed: true` for everything is worse than no
|
|
137
|
+
* checksum at all: it converts "we did not check" into "we checked and it was
|
|
138
|
+
* fine". So they report `passed: null`.
|
|
139
|
+
*/
|
|
140
|
+
export function gbCheckDigits(number) {
|
|
141
|
+
if (/^(?:GD|HA)\d{3}$/.test(number)) {
|
|
142
|
+
return {
|
|
143
|
+
algorithm: "none",
|
|
144
|
+
passed: null,
|
|
145
|
+
note: "government department and health authority numbers carry no check digits",
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
const digits = number.slice(0, 9);
|
|
149
|
+
if (!/^\d{9}$/.test(digits)) {
|
|
150
|
+
return { algorithm: "none", passed: null, note: "not a 9-digit VRN" };
|
|
151
|
+
}
|
|
152
|
+
const weights = [8, 7, 6, 5, 4, 3, 2];
|
|
153
|
+
let sum = 0;
|
|
154
|
+
for (let i = 0; i < 7; i++) {
|
|
155
|
+
sum += Number(digits[i]) * weights[i];
|
|
156
|
+
}
|
|
157
|
+
const check = Number(digits.slice(7));
|
|
158
|
+
const mod97 = (sum + check) % 97 === 0;
|
|
159
|
+
const mod9755 = (sum + 55 + check) % 97 === 0;
|
|
160
|
+
return {
|
|
161
|
+
algorithm: mod97 ? "mod-97" : mod9755 ? "mod-9755" : "mod-97 and mod-9755",
|
|
162
|
+
passed: mod97 || mod9755,
|
|
163
|
+
...(mod97 || mod9755 ? {} : { note: "the last two digits match neither variant" }),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/** Check one parsed id against its country's grammar, and its check digits if we own them. */
|
|
167
|
+
export function checkSyntax(parsed) {
|
|
168
|
+
const { country, number, canonical } = parsed;
|
|
169
|
+
const wellFormed = country.pattern.test(number);
|
|
170
|
+
const checksum = country.code === "GB" || country.code === "XI"
|
|
171
|
+
? gbCheckDigits(number)
|
|
172
|
+
: {
|
|
173
|
+
algorithm: "not implemented",
|
|
174
|
+
passed: null,
|
|
175
|
+
note: `this package does not carry ${country.name}'s check-digit algorithm, so a well-formed id here means well-formed and nothing more`,
|
|
176
|
+
};
|
|
177
|
+
return {
|
|
178
|
+
wellFormed,
|
|
179
|
+
country: country.code,
|
|
180
|
+
countryName: country.name,
|
|
181
|
+
number,
|
|
182
|
+
canonical,
|
|
183
|
+
shape: country.shape,
|
|
184
|
+
checksum,
|
|
185
|
+
...(wellFormed
|
|
186
|
+
? {}
|
|
187
|
+
: { reason: `${canonical} is not shaped like a ${country.name} VAT id (${country.shape})` }),
|
|
188
|
+
...(country.note === undefined ? {} : { note: country.note }),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Every `userError` VIES publishes, and which outcome it is.
|
|
193
|
+
*
|
|
194
|
+
* The temptation is a two-line mapping: `isValid ? valid : invalid`. Six of
|
|
195
|
+
* these nine codes come back with `isValid: false` and mean nothing whatsoever
|
|
196
|
+
* about the number.
|
|
197
|
+
*/
|
|
198
|
+
const VIES_CODES = Object.freeze({
|
|
199
|
+
VALID: { outcome: "found", meaning: "the member state answered" },
|
|
200
|
+
INVALID: { outcome: "notFound", meaning: "the member state answered: not a registered number" },
|
|
201
|
+
INVALID_INPUT: {
|
|
202
|
+
outcome: "unavailable",
|
|
203
|
+
meaning: "VIES rejected the request as malformed and never asked the member state — this says nothing about whether the number is registered",
|
|
204
|
+
retryable: false,
|
|
205
|
+
},
|
|
206
|
+
INVALID_REQUESTER_INFO: {
|
|
207
|
+
outcome: "unavailable",
|
|
208
|
+
meaning: "VIES rejected the REQUESTER's own VAT id, so the whole call failed — retry without requesterVatId to get an answer without a consultation number",
|
|
209
|
+
retryable: false,
|
|
210
|
+
},
|
|
211
|
+
SERVICE_UNAVAILABLE: {
|
|
212
|
+
outcome: "unavailable",
|
|
213
|
+
meaning: "VIES itself is down",
|
|
214
|
+
retryable: true,
|
|
215
|
+
},
|
|
216
|
+
MS_UNAVAILABLE: {
|
|
217
|
+
outcome: "unavailable",
|
|
218
|
+
meaning: "the member state's own system did not answer",
|
|
219
|
+
retryable: true,
|
|
220
|
+
},
|
|
221
|
+
MS_MAX_CONCURRENT_REQ: {
|
|
222
|
+
outcome: "unavailable",
|
|
223
|
+
meaning: "the member state is refusing further concurrent requests",
|
|
224
|
+
retryable: true,
|
|
225
|
+
},
|
|
226
|
+
GLOBAL_MAX_CONCURRENT_REQ: {
|
|
227
|
+
outcome: "unavailable",
|
|
228
|
+
meaning: "VIES is refusing further concurrent requests",
|
|
229
|
+
retryable: true,
|
|
230
|
+
},
|
|
231
|
+
TIMEOUT: {
|
|
232
|
+
outcome: "unavailable",
|
|
233
|
+
meaning: "the member state did not answer in time",
|
|
234
|
+
retryable: true,
|
|
235
|
+
},
|
|
236
|
+
IP_BLOCKED: {
|
|
237
|
+
outcome: "unavailable",
|
|
238
|
+
meaning: "VIES has blocked this caller's address",
|
|
239
|
+
retryable: false,
|
|
240
|
+
},
|
|
241
|
+
VAT_BLOCKED: {
|
|
242
|
+
outcome: "unavailable",
|
|
243
|
+
meaning: "VIES has blocked lookups of this number",
|
|
244
|
+
retryable: false,
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
function str(value) {
|
|
248
|
+
return typeof value === "string" && value.trim() !== "" ? value : undefined;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Read a VIES answer.
|
|
252
|
+
*
|
|
253
|
+
* `isValid: true` is the only shape that produces `found`, and only when the
|
|
254
|
+
* accompanying code agrees. An unrecognised code produces `unavailable` with
|
|
255
|
+
* the code quoted — a code this package has never seen is a reason to stop,
|
|
256
|
+
* not a reason to guess which side of the line it falls on.
|
|
257
|
+
*/
|
|
258
|
+
export function mapViesResponse(body, requesterSupplied) {
|
|
259
|
+
const doc = (body ?? {});
|
|
260
|
+
const rawCode = str(doc["userError"]);
|
|
261
|
+
const isValid = doc["isValid"];
|
|
262
|
+
const code = rawCode ?? (isValid === true ? "VALID" : isValid === false ? "INVALID" : undefined);
|
|
263
|
+
if (code === undefined) {
|
|
264
|
+
return {
|
|
265
|
+
outcome: "unavailable",
|
|
266
|
+
basis: "VIES answered with neither isValid nor userError — the response shape is not one this tool can read",
|
|
267
|
+
retryable: false,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
const known = VIES_CODES[code];
|
|
271
|
+
if (known === undefined) {
|
|
272
|
+
return {
|
|
273
|
+
outcome: "unavailable",
|
|
274
|
+
basis: `VIES answered with the code "${code}", which this tool does not recognise — refusing to guess whether that means registered or not`,
|
|
275
|
+
code,
|
|
276
|
+
retryable: false,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
// A code of VALID with isValid false is the member state saying "asked and
|
|
280
|
+
// answered: no such registration". Both halves have to agree before this
|
|
281
|
+
// reports a registration.
|
|
282
|
+
const outcome = known.outcome === "found" ? (isValid === true ? "found" : "notFound") : known.outcome;
|
|
283
|
+
const name = str(doc["name"]);
|
|
284
|
+
const address = str(doc["address"]);
|
|
285
|
+
const consultation = str(doc["requestIdentifier"]);
|
|
286
|
+
const approximate = doc["viesApproximate"];
|
|
287
|
+
return {
|
|
288
|
+
outcome,
|
|
289
|
+
basis: outcome === "found"
|
|
290
|
+
? "VIES: the member state confirmed this number is registered"
|
|
291
|
+
: outcome === "notFound"
|
|
292
|
+
? "VIES: the member state confirmed this number is not registered"
|
|
293
|
+
: `VIES: ${known.meaning}`,
|
|
294
|
+
code,
|
|
295
|
+
...(outcome === "found" && (name !== undefined || address !== undefined)
|
|
296
|
+
? {
|
|
297
|
+
registration: {
|
|
298
|
+
...(name === undefined ? {} : { name }),
|
|
299
|
+
...(address === undefined ? {} : { address }),
|
|
300
|
+
},
|
|
301
|
+
}
|
|
302
|
+
: {}),
|
|
303
|
+
...(str(doc["requestDate"]) === undefined ? {} : { requestDate: str(doc["requestDate"]) }),
|
|
304
|
+
...(consultation === undefined
|
|
305
|
+
? {
|
|
306
|
+
consultationNumberAbsent: requesterSupplied
|
|
307
|
+
? "a requester was supplied but VIES issued no consultation number for this call"
|
|
308
|
+
: "no requesterVatId was supplied, so VIES issues none — the consultation number is the two-party call's receipt",
|
|
309
|
+
}
|
|
310
|
+
: { consultationNumber: consultation }),
|
|
311
|
+
...(approximate === undefined || str(approximate["matchName"]) === undefined
|
|
312
|
+
? {}
|
|
313
|
+
: { nameMatch: String(approximate["matchName"]) }),
|
|
314
|
+
...(outcome === "unavailable" ? { retryable: known.retryable === true } : {}),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Read an HMRC answer.
|
|
319
|
+
*
|
|
320
|
+
* HMRC's shape is different in a way that matters: it answers 404 for a number
|
|
321
|
+
* that is not registered, which the HTTP layer classifies as `notFound`, and
|
|
322
|
+
* 503 with a maintenance code for an outage. The failure path lives in the
|
|
323
|
+
* caller; this reads the 200 body.
|
|
324
|
+
*/
|
|
325
|
+
export function mapHmrcResponse(body, requesterSupplied) {
|
|
326
|
+
const doc = (body ?? {});
|
|
327
|
+
const target = (doc["target"] ?? {});
|
|
328
|
+
const name = str(target["name"]);
|
|
329
|
+
if (name === undefined && str(target["vatNumber"]) === undefined) {
|
|
330
|
+
return {
|
|
331
|
+
outcome: "unavailable",
|
|
332
|
+
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
|
+
retryable: false,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
const address = target["address"];
|
|
337
|
+
const addressLine = address === undefined
|
|
338
|
+
? undefined
|
|
339
|
+
: [
|
|
340
|
+
str(address["line1"]),
|
|
341
|
+
str(address["line2"]),
|
|
342
|
+
str(address["line3"]),
|
|
343
|
+
str(address["line4"]),
|
|
344
|
+
str(address["postcode"]),
|
|
345
|
+
str(address["countryCode"]),
|
|
346
|
+
]
|
|
347
|
+
.filter((part) => part !== undefined)
|
|
348
|
+
.join(", ") || undefined;
|
|
349
|
+
const consultation = str(doc["consultationNumber"]);
|
|
350
|
+
return {
|
|
351
|
+
outcome: "found",
|
|
352
|
+
basis: "HMRC: this number is registered for VAT",
|
|
353
|
+
...(name === undefined && addressLine === undefined
|
|
354
|
+
? {}
|
|
355
|
+
: {
|
|
356
|
+
registration: {
|
|
357
|
+
...(name === undefined ? {} : { name }),
|
|
358
|
+
...(addressLine === undefined ? {} : { address: addressLine }),
|
|
359
|
+
},
|
|
360
|
+
}),
|
|
361
|
+
...(str(doc["processingDate"]) === undefined
|
|
362
|
+
? {}
|
|
363
|
+
: { requestDate: str(doc["processingDate"]) }),
|
|
364
|
+
...(consultation === undefined
|
|
365
|
+
? {
|
|
366
|
+
consultationNumberAbsent: requesterSupplied
|
|
367
|
+
? "a requester was supplied but HMRC issued no consultation number for this call"
|
|
368
|
+
: "no requesterVatId was supplied, so HMRC issues none — the consultation number is the two-party call's receipt",
|
|
369
|
+
}
|
|
370
|
+
: { consultationNumber: consultation }),
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/** The codes HMRC returns in an error body, and what each one means for us. */
|
|
374
|
+
export function hmrcErrorMeaning(code, status) {
|
|
375
|
+
switch (code) {
|
|
376
|
+
case "NOT_FOUND":
|
|
377
|
+
return "HMRC: this number is not registered for VAT";
|
|
378
|
+
case "INVALID_REQUEST":
|
|
379
|
+
return "HMRC rejected the request as malformed and did not look the number up";
|
|
380
|
+
case "SCHEDULED_MAINTENANCE":
|
|
381
|
+
return "HMRC's checker is down for scheduled maintenance";
|
|
382
|
+
case "SERVER_ERROR":
|
|
383
|
+
case "INTERNAL_SERVER_ERROR":
|
|
384
|
+
return "HMRC's checker failed internally";
|
|
385
|
+
default:
|
|
386
|
+
return `HMRC answered ${status ?? "an error"}${code === undefined ? "" : ` with the code "${code}"`}`;
|
|
387
|
+
}
|
|
388
|
+
}
|
package/dist/paths.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { CrewhausError } from "@crewhaus/errors";
|
|
2
|
+
/** Raised when a caller-supplied path resolves outside the workspace root. */
|
|
3
|
+
export declare class ToolPermissionError extends CrewhausError {
|
|
4
|
+
readonly name = "ToolPermissionError";
|
|
5
|
+
readonly toolName: string;
|
|
6
|
+
readonly path: string;
|
|
7
|
+
constructor(toolName: string, attemptedPath: string);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A validated path, in both forms the tools need.
|
|
11
|
+
*
|
|
12
|
+
* `real` has every in-workspace symlink already resolved and is what I/O
|
|
13
|
+
* should use — operating on it closes most of the check-to-use window.
|
|
14
|
+
* `abs` is the lexical resolution, which is what a tool must use when the
|
|
15
|
+
* question is about the link ITSELF (`Stat` reporting a symlink target,
|
|
16
|
+
* `RemovePath` deleting a link rather than its destination).
|
|
17
|
+
*/
|
|
18
|
+
export type SafePath = {
|
|
19
|
+
readonly abs: string;
|
|
20
|
+
readonly real: string;
|
|
21
|
+
/** The path as the caller wrote it, for echoing back in results. */
|
|
22
|
+
readonly given: string;
|
|
23
|
+
/** Slash-separated path relative to the workspace root. */
|
|
24
|
+
readonly rel: string;
|
|
25
|
+
};
|
|
26
|
+
/** The workspace root, resolved. Every path is contained within it. */
|
|
27
|
+
export declare function workspaceRoot(): string;
|
|
28
|
+
export declare function resolveSafe(toolName: string, rel: string, root?: string): SafePath;
|
|
29
|
+
/** A path relative to the workspace root, with `/` separators on every OS. */
|
|
30
|
+
export declare function toPosix(p: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* True when `candidate` is `parent` or lives underneath it. Both must already
|
|
33
|
+
* be absolute. Used to keep an archive entry, or a symlink inside an
|
|
34
|
+
* extracted tree, from reaching outside its destination.
|
|
35
|
+
*/
|
|
36
|
+
export declare function isInside(parent: string, candidate: string): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Reject an archive member name that would escape its destination: an
|
|
39
|
+
* absolute path, a Windows drive prefix, or any `..` segment. Checked on the
|
|
40
|
+
* NAME, before extraction, because after extraction the damage is done.
|
|
41
|
+
*/
|
|
42
|
+
export declare function archiveEntryEscapes(name: string): boolean;
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Path containment — the gate every caller-supplied path in this package
|
|
3
|
+
* passes through before any syscall touches it.
|
|
4
|
+
*
|
|
5
|
+
* The approach is the one `@crewhaus/tool-fs` uses, and for the same reasons:
|
|
6
|
+
* a lexical check alone is fooled by a symlink that lives inside the
|
|
7
|
+
* workspace and points outside it (CWE-59), so the real path is checked too.
|
|
8
|
+
* The workspace root is `process.cwd()`, matching tool-fs, so a harness that
|
|
9
|
+
* trusts one tool's boundary gets the same boundary here.
|
|
10
|
+
*/
|
|
11
|
+
import { lstatSync, readlinkSync, realpathSync } from "node:fs";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
import { CrewhausError } from "@crewhaus/errors";
|
|
14
|
+
/** Raised when a caller-supplied path resolves outside the workspace root. */
|
|
15
|
+
export class ToolPermissionError extends CrewhausError {
|
|
16
|
+
name = "ToolPermissionError";
|
|
17
|
+
toolName;
|
|
18
|
+
path;
|
|
19
|
+
constructor(toolName, attemptedPath) {
|
|
20
|
+
super("tool", `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`);
|
|
21
|
+
this.toolName = toolName;
|
|
22
|
+
this.path = attemptedPath;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** The workspace root, resolved. Every path is contained within it. */
|
|
26
|
+
export function workspaceRoot() {
|
|
27
|
+
return path.resolve(process.cwd());
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Resolve `rel` inside the workspace, or throw `ToolPermissionError`.
|
|
31
|
+
*
|
|
32
|
+
* The leaf is allowed not to exist — every tool here that creates something
|
|
33
|
+
* needs to validate a destination before it is made — so the deepest
|
|
34
|
+
* EXISTING ancestor is realpath'd and the missing tail re-appended. Any
|
|
35
|
+
* failure other than that walk fails closed.
|
|
36
|
+
*/
|
|
37
|
+
/**
|
|
38
|
+
* True when the NAME exists, whether or not it leads anywhere.
|
|
39
|
+
*
|
|
40
|
+
* `existsSync` FOLLOWS symlinks, so it answers false for a link whose target
|
|
41
|
+
* is missing — and that is exactly the case that matters: a dangling link is
|
|
42
|
+
* still a door, because `open(…, "w")` through `evil -> /outside/x` CREATES
|
|
43
|
+
* `/outside/x`. Probing with `lstat` keeps the link's name in the part of the
|
|
44
|
+
* path that gets resolved, rather than in the "does not exist yet" tail that
|
|
45
|
+
* is re-appended to the root verbatim and so passes the containment check.
|
|
46
|
+
*/
|
|
47
|
+
function nameExists(p) {
|
|
48
|
+
try {
|
|
49
|
+
lstatSync(p);
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Where `target` would actually land, with every symlink on the way already
|
|
58
|
+
* followed — including one whose own target does not exist yet.
|
|
59
|
+
*
|
|
60
|
+
* `realpathSync` gives up with ENOENT on a dangling link, which would leave
|
|
61
|
+
* that link unresolved and let it stand in for a plain missing file. So the
|
|
62
|
+
* deepest ancestor that exists as a NAME is resolved, a dangling one is
|
|
63
|
+
* followed a hop by hand, and the components that do not exist are appended.
|
|
64
|
+
* The result is the path an `open` would create, which is the only path worth
|
|
65
|
+
* checking containment against.
|
|
66
|
+
*/
|
|
67
|
+
function resolveLocation(target, depth = 0) {
|
|
68
|
+
if (depth > 40)
|
|
69
|
+
throw new Error(`symlink chain at "${target}" is too long to resolve`);
|
|
70
|
+
let probe = target;
|
|
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
|
+
}
|
|
79
|
+
let probeReal;
|
|
80
|
+
try {
|
|
81
|
+
probeReal = realpathSync(probe);
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
if (err.code !== "ENOENT")
|
|
85
|
+
throw err;
|
|
86
|
+
// The name is there but `realpath` cannot finish it: a symlink with a
|
|
87
|
+
// missing target. `readlinkSync` throws EINVAL on anything else, which
|
|
88
|
+
// fails closed.
|
|
89
|
+
const link = readlinkSync(probe);
|
|
90
|
+
// A RELATIVE target resolves against the directory that actually CONTAINS
|
|
91
|
+
// the link, which is not the link's lexical parent when that parent is
|
|
92
|
+
// itself reached through a symlink. `<root>/dirlink/x -> ../y` with
|
|
93
|
+
// `dirlink` pointing out of the root really lands at `<elsewhere>/y`, but
|
|
94
|
+
// measured from the lexical parent it reads as `<root>/y` — an in-root
|
|
95
|
+
// path the caller's path does not lead to. So the parent is made real
|
|
96
|
+
// first. An absolute target ignores the base.
|
|
97
|
+
const base = realpathSync(path.dirname(probe));
|
|
98
|
+
probeReal = resolveLocation(path.resolve(base, link), depth + 1);
|
|
99
|
+
}
|
|
100
|
+
return tail.length > 0 ? path.join(probeReal, ...tail) : probeReal;
|
|
101
|
+
}
|
|
102
|
+
export function resolveSafe(toolName, rel, root = workspaceRoot()) {
|
|
103
|
+
const rootResolved = path.resolve(root);
|
|
104
|
+
const abs = path.resolve(rootResolved, rel);
|
|
105
|
+
// 1) Lexical containment — rejects `..` and absolute escapes. The trailing
|
|
106
|
+
// separator avoids the `/root` vs `/root-sibling` prefix pitfall.
|
|
107
|
+
if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
|
|
108
|
+
throw new ToolPermissionError(toolName, rel);
|
|
109
|
+
}
|
|
110
|
+
let real;
|
|
111
|
+
try {
|
|
112
|
+
const rootReal = realpathSync(rootResolved);
|
|
113
|
+
real = resolveLocation(abs);
|
|
114
|
+
// 2) Symlink-aware containment. The real path must land inside the real
|
|
115
|
+
// root, so an in-workspace symlink pointing at /etc is refused here.
|
|
116
|
+
if (real !== rootReal && !real.startsWith(`${rootReal}${path.sep}`)) {
|
|
117
|
+
throw new ToolPermissionError(toolName, rel);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
if (err instanceof ToolPermissionError)
|
|
122
|
+
throw err;
|
|
123
|
+
throw new ToolPermissionError(toolName, rel);
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
abs,
|
|
127
|
+
real,
|
|
128
|
+
given: rel,
|
|
129
|
+
rel: toPosix(path.relative(rootResolved, abs)),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** A path relative to the workspace root, with `/` separators on every OS. */
|
|
133
|
+
export function toPosix(p) {
|
|
134
|
+
return path.sep === "/" ? p : p.split(path.sep).join("/");
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* True when `candidate` is `parent` or lives underneath it. Both must already
|
|
138
|
+
* be absolute. Used to keep an archive entry, or a symlink inside an
|
|
139
|
+
* extracted tree, from reaching outside its destination.
|
|
140
|
+
*/
|
|
141
|
+
export function isInside(parent, candidate) {
|
|
142
|
+
const p = path.resolve(parent);
|
|
143
|
+
const c = path.resolve(candidate);
|
|
144
|
+
return c === p || c.startsWith(`${p}${path.sep}`);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Reject an archive member name that would escape its destination: an
|
|
148
|
+
* absolute path, a Windows drive prefix, or any `..` segment. Checked on the
|
|
149
|
+
* NAME, before extraction, because after extraction the damage is done.
|
|
150
|
+
*/
|
|
151
|
+
export function archiveEntryEscapes(name) {
|
|
152
|
+
const normalized = name.replace(/\\/g, "/");
|
|
153
|
+
if (normalized.startsWith("/"))
|
|
154
|
+
return true;
|
|
155
|
+
if (/^[A-Za-z]:/.test(normalized))
|
|
156
|
+
return true;
|
|
157
|
+
return normalized.split("/").some((segment) => segment === "..");
|
|
158
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@crewhaus/tool-kyc",
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Deterministic counterparty checks against public registries and sanctions lists, with versioned evidence",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "bun test src"
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@crewhaus/errors": "0.7.0",
|
|
19
|
+
"@crewhaus/tool-builder": "0.7.0",
|
|
20
|
+
"@crewhaus/tool-catalog": "0.7.0",
|
|
21
|
+
"@crewhaus/tool-fetch": "0.7.0",
|
|
22
|
+
"@crewhaus/tool-text": "0.7.0",
|
|
23
|
+
"zod": "^3.23.8"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@crewhaus/tool-executor": "workspace:*"
|
|
27
|
+
},
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
|
+
"author": {
|
|
30
|
+
"name": "Max Meier",
|
|
31
|
+
"email": "max@crewhaus.ai",
|
|
32
|
+
"url": "https://crewhaus.ai"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/crewhaus/factory.git",
|
|
37
|
+
"directory": "packages/tool-kyc"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://github.com/crewhaus/factory/tree/main/packages/tool-kyc#readme",
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/crewhaus/factory/issues"
|
|
42
|
+
},
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public"
|
|
45
|
+
},
|
|
46
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"]
|
|
47
|
+
}
|