@verii/batch-issuer 0.0.0-stage → 1.3.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/LICENSE +202 -0
- package/NOTICE +1 -0
- package/README.md +296 -2
- package/package.json +50 -3
- package/src/cli.js +190 -0
- package/src/clients/hub-client.js +181 -0
- package/src/clients/init-client.js +40 -0
- package/src/clients/registrar-client.js +37 -0
- package/src/commands/check-rules.js +187 -0
- package/src/commands/exit-codes.js +30 -0
- package/src/commands/load.js +175 -0
- package/src/csv/load-csv.js +113 -0
- package/src/index.js +28 -0
- package/src/load/load-batch.js +313 -0
- package/src/report/count.js +24 -0
- package/src/report/describe-error.js +37 -0
- package/src/report/format-load-report.js +134 -0
- package/src/report/format-report.js +100 -0
- package/src/spec/load-spec.js +193 -0
- package/src/spec/spec-schema.js +109 -0
- package/src/state/state-file.js +212 -0
- package/src/templates/render-template.js +159 -0
- package/src/validation/check-credential-subjects.js +129 -0
- package/src/validation/check-rows.js +193 -0
- package/src/validation/check-service.js +127 -0
- package/src/validation/find-duplicates.js +147 -0
- package/src/validation/match-existing-depots.js +142 -0
- package/src/validation/reasons.js +21 -0
- package/src/validation/validate-batch.js +105 -0
- package/src/values/auth-values.js +130 -0
- package/src/values/convert-value.js +65 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const { createHash } = require('node:crypto');
|
|
18
|
+
const {
|
|
19
|
+
appendFile,
|
|
20
|
+
readFile,
|
|
21
|
+
truncate,
|
|
22
|
+
writeFile,
|
|
23
|
+
} = require('node:fs/promises');
|
|
24
|
+
const path = require('node:path');
|
|
25
|
+
const {
|
|
26
|
+
flatMap,
|
|
27
|
+
flow,
|
|
28
|
+
getOr,
|
|
29
|
+
isEqual,
|
|
30
|
+
isUndefined,
|
|
31
|
+
join,
|
|
32
|
+
last,
|
|
33
|
+
map,
|
|
34
|
+
replace,
|
|
35
|
+
size,
|
|
36
|
+
split,
|
|
37
|
+
take,
|
|
38
|
+
zipObject,
|
|
39
|
+
} = require('lodash/fp');
|
|
40
|
+
|
|
41
|
+
// Only its owner can read or write a file that can hold links that claim a
|
|
42
|
+
// holder's credentials: the state file and the links file.
|
|
43
|
+
const PRIVATE_FILE_MODE = 0o600;
|
|
44
|
+
|
|
45
|
+
// The lists of a state. Each line after the batch's adds records to one.
|
|
46
|
+
const STATE_LISTS = ['depots', 'credentials', 'resolvedDepots', 'links'];
|
|
47
|
+
|
|
48
|
+
const mapWithIndex = map.convert({ cap: false });
|
|
49
|
+
|
|
50
|
+
const toLine = (record) => `${JSON.stringify(record)}\n`;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Identifies a batch: its network, tenant and service, and a hash of
|
|
54
|
+
* everything that decides what a load writes, which is the spec, its
|
|
55
|
+
* templates, the CSV, and the --var and --default-country values.
|
|
56
|
+
* @param {{ specFile: string, csvFile: string, vars: object, options: { network: string, defaultCountry?: string } }} input
|
|
57
|
+
* @param {object} spec the batch's spec
|
|
58
|
+
* @returns {Promise<{ network: string, tenantId: string, serviceId: string, hash: string }>}
|
|
59
|
+
*/
|
|
60
|
+
const identifyBatch = async ({ specFile, csvFile, vars, options }, spec) => {
|
|
61
|
+
const templateFiles = map(
|
|
62
|
+
({ template }) => path.resolve(path.dirname(specFile), template),
|
|
63
|
+
spec.credentials,
|
|
64
|
+
);
|
|
65
|
+
const files = await Promise.all(
|
|
66
|
+
map(
|
|
67
|
+
(file) => readFile(file, 'utf8'),
|
|
68
|
+
[specFile, ...templateFiles, csvFile],
|
|
69
|
+
),
|
|
70
|
+
);
|
|
71
|
+
const hash = createHash('sha256')
|
|
72
|
+
.update(
|
|
73
|
+
JSON.stringify({ files, vars, defaultCountry: options.defaultCountry }),
|
|
74
|
+
)
|
|
75
|
+
.digest('hex');
|
|
76
|
+
return {
|
|
77
|
+
network: options.network,
|
|
78
|
+
tenantId: spec.tenantId,
|
|
79
|
+
serviceId: spec.serviceId,
|
|
80
|
+
hash,
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const readText = async (file) => {
|
|
85
|
+
try {
|
|
86
|
+
return await readFile(file, 'utf8');
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (error.code === 'ENOENT') {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
throw new Error(`the state file ${file} can't be read: ${error.message}`, {
|
|
92
|
+
cause: error,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
// The last line can be a write that a crash tore. It's ignored, so its record
|
|
98
|
+
// counts as not done. Any other line must be JSON.
|
|
99
|
+
const parseLine = (file, lineCount) => (line, index) => {
|
|
100
|
+
try {
|
|
101
|
+
return JSON.parse(line);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (index === lineCount - 1) {
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
throw new Error(
|
|
107
|
+
`the state file ${file} has a line that isn't JSON: line ${index + 1}`,
|
|
108
|
+
{ cause: error },
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const foldRecords = ([first, ...records]) => {
|
|
114
|
+
const listOf = (key) => flatMap(getOr([], [key]), records);
|
|
115
|
+
return {
|
|
116
|
+
batch: first.batch,
|
|
117
|
+
...zipObject(STATE_LISTS, map(listOf, STATE_LISTS)),
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Reads a state file, which is JSON Lines: the batch's identity, then a line
|
|
123
|
+
* for each write that the Hub confirmed, such as `{"depots":[{"row":3,"id":"…"}]}`.
|
|
124
|
+
* @param {string} file the state file
|
|
125
|
+
* @returns {Promise<{ state: object, length: number }|undefined>} the state, and the length in bytes of its
|
|
126
|
+
* whole lines, or undefined when there's no such file or it has no whole line
|
|
127
|
+
* @throws when the file can't be read, or a line other than the last isn't JSON
|
|
128
|
+
*/
|
|
129
|
+
const readState = async (file) => {
|
|
130
|
+
const text = await readText(file);
|
|
131
|
+
if (text == null) {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
const lines = flow(replace(/\n$/, ''), split('\n'))(text);
|
|
135
|
+
const records = mapWithIndex(parseLine(file, size(lines)), lines);
|
|
136
|
+
const wholeLines = isUndefined(last(records)) ? size(lines) - 1 : size(lines);
|
|
137
|
+
if (wholeLines === 0) {
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
state: foldRecords(take(wholeLines, records)),
|
|
142
|
+
length: Buffer.byteLength(join('\n', take(wholeLines, lines))),
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Gives the state of a batch: the one read from its state file, or an empty
|
|
148
|
+
* one when there was none.
|
|
149
|
+
* @param {{ state: object }} [saved] what readState read from the state file
|
|
150
|
+
* @param {{ network: string, tenantId: string, serviceId: string, hash: string }} batch the batch's identity
|
|
151
|
+
* @param {string} file the state file
|
|
152
|
+
* @returns {object} the state
|
|
153
|
+
* @throws when the state file belongs to another batch
|
|
154
|
+
*/
|
|
155
|
+
const openState = (saved, batch, file) => {
|
|
156
|
+
if (saved == null) {
|
|
157
|
+
return {
|
|
158
|
+
batch,
|
|
159
|
+
...zipObject(
|
|
160
|
+
STATE_LISTS,
|
|
161
|
+
map(() => [], STATE_LISTS),
|
|
162
|
+
),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
if (!isEqual(saved.state.batch, batch)) {
|
|
166
|
+
throw new Error(
|
|
167
|
+
`the state file ${file} belongs to a different batch: the spec, its templates, the CSV, --network, --var or --default-country ` +
|
|
168
|
+
'have changed since it was written. Rerun the batch it belongs to, or pass another --state',
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
return saved.state;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Gets a state file ready for a load's appends. A new file starts with the
|
|
176
|
+
* batch's line. An existing one keeps its whole lines, which cuts off a line
|
|
177
|
+
* that a crash tore, and ends with a newline.
|
|
178
|
+
* @param {string} file the state file
|
|
179
|
+
* @param {{ length: number }} [saved] what readState read from it
|
|
180
|
+
* @param {object} batch the batch's identity
|
|
181
|
+
* @returns {Promise<void>}
|
|
182
|
+
*/
|
|
183
|
+
const startState = async (file, saved, batch) => {
|
|
184
|
+
if (saved == null) {
|
|
185
|
+
await writeFile(file, toLine({ batch }), { mode: PRIVATE_FILE_MODE });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
await truncate(file, saved.length);
|
|
189
|
+
await appendFile(file, '\n');
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Gives a function that appends a line of records to a state file.
|
|
194
|
+
* @param {string} file the state file
|
|
195
|
+
* @returns {(key: string, records: Array) => Promise<Array>} it takes one of the state's lists and the
|
|
196
|
+
* records to add to it, and gives the records
|
|
197
|
+
*/
|
|
198
|
+
const appendRecords = (file) => async (key, records) => {
|
|
199
|
+
await appendFile(file, toLine({ [key]: records }), {
|
|
200
|
+
mode: PRIVATE_FILE_MODE,
|
|
201
|
+
});
|
|
202
|
+
return records;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
module.exports = {
|
|
206
|
+
PRIVATE_FILE_MODE,
|
|
207
|
+
appendRecords,
|
|
208
|
+
identifyBatch,
|
|
209
|
+
openState,
|
|
210
|
+
readState,
|
|
211
|
+
startState,
|
|
212
|
+
};
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const Handlebars = require('handlebars');
|
|
18
|
+
const {
|
|
19
|
+
cond,
|
|
20
|
+
flatMap,
|
|
21
|
+
flow,
|
|
22
|
+
get,
|
|
23
|
+
has,
|
|
24
|
+
isArray,
|
|
25
|
+
isPlainObject,
|
|
26
|
+
isString,
|
|
27
|
+
map,
|
|
28
|
+
mapValues,
|
|
29
|
+
memoize,
|
|
30
|
+
stubTrue,
|
|
31
|
+
values,
|
|
32
|
+
} = require('lodash/fp');
|
|
33
|
+
const { convertValue } = require('../values/convert-value');
|
|
34
|
+
const { MISSING } = require('../validation/reasons');
|
|
35
|
+
|
|
36
|
+
// A separate environment, so no helper or partial registered elsewhere applies.
|
|
37
|
+
const handlebars = Handlebars.create();
|
|
38
|
+
|
|
39
|
+
// Strict, so a missing column is an error rather than an empty string. Values
|
|
40
|
+
// aren't HTML-escaped, because they end up in JSON strings, not in HTML.
|
|
41
|
+
const COMPILE_OPTIONS = { strict: true, noEscape: true };
|
|
42
|
+
|
|
43
|
+
const compile = memoize((text) => handlebars.compile(text, COMPILE_OPTIONS));
|
|
44
|
+
|
|
45
|
+
// A value that is exactly one placeholder, `{{column}}` or `{{[a column]}}`.
|
|
46
|
+
const PLACEHOLDER = /^\{\{\s*(?:\[([^\]]+)\]|([^\s{}[\]]+))\s*\}\}$/;
|
|
47
|
+
|
|
48
|
+
// Handlebars' strict mode names the missing variable in its message.
|
|
49
|
+
const MISSING_VARIABLE = /^"(.+)" not defined in /;
|
|
50
|
+
|
|
51
|
+
// Strict mode finds a variable with `in`, so a name that every object
|
|
52
|
+
// inherits, such as "constructor", would render as an empty string rather than
|
|
53
|
+
// be missing. The row's values get a prototype that has nothing but the
|
|
54
|
+
// toString that strict mode's message uses.
|
|
55
|
+
const ROW_PROTOTYPE = { __proto__: null, toString: () => 'the row' };
|
|
56
|
+
|
|
57
|
+
const toRowScope = (data) => ({ __proto__: ROW_PROTOTYPE, ...data });
|
|
58
|
+
|
|
59
|
+
const placeholderColumn = (text) => {
|
|
60
|
+
const match = PLACEHOLDER.exec(text);
|
|
61
|
+
return match == null ? undefined : (match[1] ?? match[2]);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const renderError = (error) => {
|
|
65
|
+
const match = MISSING_VARIABLE.exec(error.message);
|
|
66
|
+
return match == null
|
|
67
|
+
? { reason: error.message }
|
|
68
|
+
: { column: match[1], reason: MISSING };
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const renderText = (text, data) => {
|
|
72
|
+
try {
|
|
73
|
+
return { value: compile(text)(data), errors: [] };
|
|
74
|
+
} catch (error) {
|
|
75
|
+
return { errors: [renderError(error)] };
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// A placeholder of a typed column takes the column's type.
|
|
80
|
+
const renderTyped = (column, data, columns) => {
|
|
81
|
+
if (!has([column], data)) {
|
|
82
|
+
return { errors: [{ column, reason: MISSING }] };
|
|
83
|
+
}
|
|
84
|
+
const { value, reason } = convertValue(
|
|
85
|
+
get([column], columns),
|
|
86
|
+
get([column], data),
|
|
87
|
+
);
|
|
88
|
+
return reason == null
|
|
89
|
+
? { value, errors: [] }
|
|
90
|
+
: { errors: [{ column, reason }] };
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const renderString = (text, { data, columns }) => {
|
|
94
|
+
const column = placeholderColumn(text);
|
|
95
|
+
return column != null && has([column], columns)
|
|
96
|
+
? renderTyped(column, data, columns)
|
|
97
|
+
: renderText(text, data);
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const keepValue = (value) => ({ value, errors: [] });
|
|
101
|
+
|
|
102
|
+
// Walks a JSON template, applying visitString to each string, and gathers the
|
|
103
|
+
// result and every string's errors. Keys, numbers, booleans and nulls are kept
|
|
104
|
+
// as they are.
|
|
105
|
+
const walkTemplate = (visitString) => {
|
|
106
|
+
const walkArray = (array) => {
|
|
107
|
+
const results = map(walk, array);
|
|
108
|
+
return { value: map('value', results), errors: flatMap('errors', results) };
|
|
109
|
+
};
|
|
110
|
+
const walkObject = (object) => {
|
|
111
|
+
const results = mapValues(walk, object);
|
|
112
|
+
return {
|
|
113
|
+
value: mapValues('value', results),
|
|
114
|
+
errors: flow(values, flatMap('errors'))(results),
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
const walk = cond([
|
|
118
|
+
[isString, visitString],
|
|
119
|
+
[isArray, walkArray],
|
|
120
|
+
[isPlainObject, walkObject],
|
|
121
|
+
[stubTrue, keepValue],
|
|
122
|
+
]);
|
|
123
|
+
return walk;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Renders a JSON template value by value. Each string is rendered with
|
|
128
|
+
* Handlebars on its own, so a CSV value can only ever become part of a string,
|
|
129
|
+
* never change the JSON's structure. A string that is exactly `{{column}}`
|
|
130
|
+
* takes the column's type from `columns`.
|
|
131
|
+
* @param {unknown} template the parsed JSON template, or a single string
|
|
132
|
+
* @param {object} data the values by column
|
|
133
|
+
* @param {object} [columns] the declared type of each typed column
|
|
134
|
+
* @returns {{ value: unknown, errors: Array<{ column?: string, reason: string }> }}
|
|
135
|
+
* the rendered value, which is only complete when there are no errors
|
|
136
|
+
*/
|
|
137
|
+
const renderTemplate = (template, data, columns = {}) => {
|
|
138
|
+
const scope = { data: toRowScope(data), columns };
|
|
139
|
+
const render = walkTemplate((text) => renderString(text, scope));
|
|
140
|
+
return render(template);
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const checkSyntax = (text) => {
|
|
144
|
+
try {
|
|
145
|
+
handlebars.parse(text);
|
|
146
|
+
return keepValue(text);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
return { value: text, errors: [error.message] };
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Checks the Handlebars syntax of every string in a template.
|
|
154
|
+
* @param {unknown} template the parsed JSON template, or a single string
|
|
155
|
+
* @returns {Array<string>} the syntax errors
|
|
156
|
+
*/
|
|
157
|
+
const checkTemplateSyntax = flow(walkTemplate(checkSyntax), get('errors'));
|
|
158
|
+
|
|
159
|
+
module.exports = { checkTemplateSyntax, renderTemplate };
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const Ajv2019 = require('ajv/dist/2019');
|
|
18
|
+
const addFormats = require('ajv-formats');
|
|
19
|
+
const draft7MetaSchema = require('ajv/dist/refs/json-schema-draft-07.json');
|
|
20
|
+
const {
|
|
21
|
+
cloneDeep,
|
|
22
|
+
difference,
|
|
23
|
+
filter,
|
|
24
|
+
flatMap,
|
|
25
|
+
flow,
|
|
26
|
+
forEach,
|
|
27
|
+
get,
|
|
28
|
+
includes,
|
|
29
|
+
isEmpty,
|
|
30
|
+
map,
|
|
31
|
+
uniq,
|
|
32
|
+
uniqBy,
|
|
33
|
+
zipObject,
|
|
34
|
+
} = require('lodash/fp');
|
|
35
|
+
const {
|
|
36
|
+
operatorApiAjvFormats,
|
|
37
|
+
} = require('@verii/credentialing-hub-operator-api');
|
|
38
|
+
const { initValidation, wrapValidationError } = require('@verii/validation');
|
|
39
|
+
|
|
40
|
+
// credentials/create checks a credentialSubject with the validation plugin's
|
|
41
|
+
// AJV: Ajv2019 with the draft-07 meta-schema, the Hub's formats, and the
|
|
42
|
+
// credentials controller's options. It reports every error rather than the
|
|
43
|
+
// first, which doesn't change what's valid.
|
|
44
|
+
const initSubjectValidation = () => {
|
|
45
|
+
const ajv = new Ajv2019({
|
|
46
|
+
useDefaults: true,
|
|
47
|
+
strictTypes: false,
|
|
48
|
+
allErrors: true,
|
|
49
|
+
});
|
|
50
|
+
ajv.addMetaSchema(draft7MetaSchema);
|
|
51
|
+
addFormats(ajv, operatorApiAjvFormats);
|
|
52
|
+
return initValidation(ajv);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const loadSubjectValidators = async (metadatas, registrar) => {
|
|
56
|
+
const schemas = await Promise.all(
|
|
57
|
+
map(({ schemaUrl }) => registrar.getSchema(schemaUrl), metadatas),
|
|
58
|
+
);
|
|
59
|
+
const { addDocSchema, getDocValidator } = initSubjectValidation();
|
|
60
|
+
forEach((schema) => addDocSchema(schema, true), schemas);
|
|
61
|
+
const validators = map(({ $id }) => getDocValidator($id), schemas);
|
|
62
|
+
return zipObject(map('credentialType', metadatas), validators);
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// The validator applies schema defaults to what it checks, so it checks a copy.
|
|
66
|
+
const checkSubject =
|
|
67
|
+
(row, validators) =>
|
|
68
|
+
({ template, type, credential }) => {
|
|
69
|
+
const validateSubject = get([type], validators);
|
|
70
|
+
const subject = cloneDeep(credential.content.credentialSubject);
|
|
71
|
+
if (validateSubject == null || validateSubject(subject)) {
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
return map(
|
|
75
|
+
(error) => ({
|
|
76
|
+
row,
|
|
77
|
+
template,
|
|
78
|
+
reason: wrapValidationError([error], 'credentialSubject').message,
|
|
79
|
+
}),
|
|
80
|
+
validateSubject.errors,
|
|
81
|
+
);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const isRendered = ({ errors }) => isEmpty(errors);
|
|
85
|
+
|
|
86
|
+
const checkRowSubjects =
|
|
87
|
+
(validators) =>
|
|
88
|
+
({ row, credentials }) =>
|
|
89
|
+
flow(
|
|
90
|
+
filter(isRendered),
|
|
91
|
+
flatMap(checkSubject(row, validators)),
|
|
92
|
+
)(credentials);
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Step 3: checks each credential's credentialSubject against its type's
|
|
96
|
+
* schema from the registrar, as credentials/create does. Credentials that
|
|
97
|
+
* didn't render are skipped.
|
|
98
|
+
* @param {Array<object>} rows the checked rows, from step 2
|
|
99
|
+
* @param {Array<object>} templates the spec's templates
|
|
100
|
+
* @param {{ getCredentialTypeMetadata: Function, getSchema: Function }} [registrar] the registrar client,
|
|
101
|
+
* which a spec without credentials doesn't need
|
|
102
|
+
* @throws when there are credentials and no registrar client
|
|
103
|
+
* @returns {Promise<Array<object>>} the errors
|
|
104
|
+
*/
|
|
105
|
+
const checkCredentialSubjects = async (rows, templates, registrar) => {
|
|
106
|
+
const types = flow(map('type'), uniq)(templates);
|
|
107
|
+
if (isEmpty(types)) {
|
|
108
|
+
return [];
|
|
109
|
+
}
|
|
110
|
+
if (registrar == null) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
'the spec has credentials, so --registrar is required to check them',
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
const metadatas = await registrar.getCredentialTypeMetadata(types);
|
|
116
|
+
const foundMetadatas = flow(
|
|
117
|
+
filter(({ credentialType }) => includes(credentialType, types)),
|
|
118
|
+
uniqBy('credentialType'),
|
|
119
|
+
)(metadatas);
|
|
120
|
+
const foundTypes = map('credentialType', foundMetadatas);
|
|
121
|
+
const missingTypeErrors = map(
|
|
122
|
+
(type) => ({ reason: `the registrar has no credential type ${type}` }),
|
|
123
|
+
difference(types, foundTypes),
|
|
124
|
+
);
|
|
125
|
+
const validators = await loadSubjectValidators(foundMetadatas, registrar);
|
|
126
|
+
return [...missingTypeErrors, ...flatMap(checkRowSubjects(validators), rows)];
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
module.exports = { checkCredentialSubjects };
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Velocity Team
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const {
|
|
18
|
+
countBy,
|
|
19
|
+
flatMap,
|
|
20
|
+
flow,
|
|
21
|
+
identity,
|
|
22
|
+
includes,
|
|
23
|
+
isEmpty,
|
|
24
|
+
isUndefined,
|
|
25
|
+
keys,
|
|
26
|
+
map,
|
|
27
|
+
omitBy,
|
|
28
|
+
partition,
|
|
29
|
+
pickBy,
|
|
30
|
+
set,
|
|
31
|
+
size,
|
|
32
|
+
uniqBy,
|
|
33
|
+
} = require('lodash/fp');
|
|
34
|
+
const {
|
|
35
|
+
initOperatorApiValidator,
|
|
36
|
+
} = require('@verii/credentialing-hub-operator-api');
|
|
37
|
+
const { wrapValidationError } = require('@verii/validation');
|
|
38
|
+
const { renderTemplate } = require('../templates/render-template');
|
|
39
|
+
const { buildAuthValues } = require('../values/auth-values');
|
|
40
|
+
const {
|
|
41
|
+
findDuplicateAuthValues,
|
|
42
|
+
findDuplicateCredentialReferences,
|
|
43
|
+
} = require('./find-duplicates');
|
|
44
|
+
const { MISSING } = require('./reasons');
|
|
45
|
+
|
|
46
|
+
const operatorApi = initOperatorApiValidator();
|
|
47
|
+
|
|
48
|
+
// Validates as the Hub does, with the package's validator, which reports the
|
|
49
|
+
// first error in Fastify's format, such as "depot/userReference must be string".
|
|
50
|
+
const checkOperatorApiSchema = (schemaId, data, dataVar) => {
|
|
51
|
+
const errors = operatorApi.validate(schemaId, data);
|
|
52
|
+
return isEmpty(errors)
|
|
53
|
+
? []
|
|
54
|
+
: [{ reason: wrapValidationError(errors, dataVar).message }];
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const checkCellCount = ({ cellCount }, { headers }) =>
|
|
58
|
+
cellCount > size(headers)
|
|
59
|
+
? [
|
|
60
|
+
{
|
|
61
|
+
reason: `has ${cellCount} cells, but the header has ${size(headers)} columns`,
|
|
62
|
+
},
|
|
63
|
+
]
|
|
64
|
+
: [];
|
|
65
|
+
|
|
66
|
+
// Without authColumns the spec doesn't fit the service, so there are no auth
|
|
67
|
+
// values to check.
|
|
68
|
+
const buildRowAuthValues = ({ authColumns, options }, data) =>
|
|
69
|
+
authColumns == null
|
|
70
|
+
? { errors: [] }
|
|
71
|
+
: buildAuthValues(authColumns, data, options);
|
|
72
|
+
|
|
73
|
+
// A service without auth rules takes depots without authValues.
|
|
74
|
+
const buildDepot = (spec, userReference, authValues) =>
|
|
75
|
+
omitBy(isUndefined, {
|
|
76
|
+
userReference,
|
|
77
|
+
authValues: isEmpty(authValues) ? undefined : authValues,
|
|
78
|
+
expectedCredentialTypes: spec.depot.expectedCredentialTypes,
|
|
79
|
+
deferredCredentials: spec.depot.deferredCredentials,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// userReference, credentialReference and tags are strings, so they're
|
|
83
|
+
// rendered without the typed columns.
|
|
84
|
+
const renderDepot = ({ spec }, data, authValues) => {
|
|
85
|
+
const { value: userReference, errors } = renderTemplate(
|
|
86
|
+
spec.depot.userReference,
|
|
87
|
+
data,
|
|
88
|
+
);
|
|
89
|
+
if (!isEmpty(errors)) {
|
|
90
|
+
return { errors };
|
|
91
|
+
}
|
|
92
|
+
const depot = buildDepot(spec, userReference, authValues);
|
|
93
|
+
return { depot, errors: checkOperatorApiSchema('new-depot', depot, 'depot') };
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const renderCredential =
|
|
97
|
+
({ spec }, data) =>
|
|
98
|
+
(template) => {
|
|
99
|
+
const content = renderTemplate(template.content, data, spec.columns);
|
|
100
|
+
const reference = renderTemplate(template.credentialReference, data);
|
|
101
|
+
const tags = renderTemplate(template.tags, data);
|
|
102
|
+
const renderErrors = [
|
|
103
|
+
...content.errors,
|
|
104
|
+
...reference.errors,
|
|
105
|
+
...tags.errors,
|
|
106
|
+
];
|
|
107
|
+
const credential = omitBy(isUndefined, {
|
|
108
|
+
credentialReference: reference.value,
|
|
109
|
+
content: content.value,
|
|
110
|
+
tags: tags.value,
|
|
111
|
+
});
|
|
112
|
+
const errors = isEmpty(renderErrors)
|
|
113
|
+
? checkOperatorApiSchema('new-credential', credential, 'credential')
|
|
114
|
+
: renderErrors;
|
|
115
|
+
return {
|
|
116
|
+
template: template.template,
|
|
117
|
+
type: template.type,
|
|
118
|
+
credential,
|
|
119
|
+
errors: map(set('template', template.template), errors),
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
// --var values override the CSV's values of the same name.
|
|
124
|
+
const checkRow = (context) => (csvRow) => {
|
|
125
|
+
const data = { ...csvRow.data, ...context.vars };
|
|
126
|
+
const auth = buildRowAuthValues(context, data);
|
|
127
|
+
const depot = renderDepot(context, data, auth.authValues);
|
|
128
|
+
const credentials = map(renderCredential(context, data), context.templates);
|
|
129
|
+
const errors = [
|
|
130
|
+
...checkCellCount(csvRow, context.csv),
|
|
131
|
+
...auth.errors,
|
|
132
|
+
...depot.errors,
|
|
133
|
+
...flatMap('errors', credentials),
|
|
134
|
+
];
|
|
135
|
+
return {
|
|
136
|
+
row: csvRow.row,
|
|
137
|
+
depot: depot.depot,
|
|
138
|
+
authValues: auth.authValues,
|
|
139
|
+
credentials,
|
|
140
|
+
errors,
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const checkHeaders = (headers, rows) => {
|
|
145
|
+
const duplicateHeaders = flow(
|
|
146
|
+
countBy(identity),
|
|
147
|
+
pickBy((count) => count > 1),
|
|
148
|
+
keys,
|
|
149
|
+
)(headers);
|
|
150
|
+
const duplicateErrors = map(
|
|
151
|
+
(column) => ({ column, reason: 'is in the header more than once' }),
|
|
152
|
+
duplicateHeaders,
|
|
153
|
+
);
|
|
154
|
+
return isEmpty(rows)
|
|
155
|
+
? [{ reason: 'the CSV has no rows' }, ...duplicateErrors]
|
|
156
|
+
: duplicateErrors;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
// A column that's missing from every row, because the CSV doesn't have it, is
|
|
160
|
+
// one error rather than one for each row.
|
|
161
|
+
const liftAbsentColumns = (rowErrors, knownColumns) => {
|
|
162
|
+
const isAbsentColumn = ({ column, reason }) =>
|
|
163
|
+
reason === MISSING && !includes(column, knownColumns);
|
|
164
|
+
const [absent, present] = partition(isAbsentColumn, rowErrors);
|
|
165
|
+
const absentErrors = flow(
|
|
166
|
+
uniqBy('column'),
|
|
167
|
+
map(({ column }) => ({
|
|
168
|
+
column,
|
|
169
|
+
reason: 'is used by the spec, but the CSV has no such column',
|
|
170
|
+
})),
|
|
171
|
+
)(absent);
|
|
172
|
+
return [...absentErrors, ...present];
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const errorsOfRow = ({ row, errors }) =>
|
|
176
|
+
map((error) => ({ row, ...error }), errors);
|
|
177
|
+
|
|
178
|
+
// Step 2: each row against the spec, and the rows against each other.
|
|
179
|
+
const checkRows = (context) => {
|
|
180
|
+
const { csv, vars, authColumns } = context;
|
|
181
|
+
const rows = map(checkRow(context), csv.rows);
|
|
182
|
+
const rowErrors = flatMap(errorsOfRow, rows);
|
|
183
|
+
const knownColumns = [...csv.headers, ...keys(vars)];
|
|
184
|
+
const errors = [
|
|
185
|
+
...checkHeaders(csv.headers, csv.rows),
|
|
186
|
+
...liftAbsentColumns(rowErrors, knownColumns),
|
|
187
|
+
...findDuplicateAuthValues(rows, authColumns),
|
|
188
|
+
...findDuplicateCredentialReferences(rows),
|
|
189
|
+
];
|
|
190
|
+
return { rows, errors };
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
module.exports = { checkRows };
|