@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.
@@ -0,0 +1,134 @@
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
+ compact,
19
+ flow,
20
+ isEmpty,
21
+ join,
22
+ map,
23
+ size,
24
+ toPairs,
25
+ } = require('lodash/fp');
26
+ const { count, formatNumber } = require('./count');
27
+ const { describeError } = require('./describe-error');
28
+ const { formatErrors } = require('./format-report');
29
+
30
+ // Such as "2 created, 1 reused, 0 skipped".
31
+ const formatCounts = flow(
32
+ toPairs,
33
+ map(([outcome, number]) => `${formatNumber(number)} ${outcome}`),
34
+ join(', '),
35
+ );
36
+
37
+ /**
38
+ * Formats a finished load.
39
+ * @param {{ load: object }} report the load's counts, its shared link, and its output and state files
40
+ * @returns {string} the report
41
+ */
42
+ const formatLoadReport = ({ load }) => {
43
+ const lines = compact([
44
+ `Depots: ${formatCounts(load.depots)}.`,
45
+ `Credentials: ${formatCounts(load.credentials)}.`,
46
+ load.resolvedDepots != null &&
47
+ `Deferred credentials resolved: ${count(load.resolvedDepots, 'depot')}.`,
48
+ load.link != null && `Issue link: ${load.link}`,
49
+ `Links: ${load.output}`,
50
+ `State: ${load.state}`,
51
+ ]);
52
+ return `${join('\n', lines)}\n`;
53
+ };
54
+
55
+ // How far the batch got, in this run and the earlier ones.
56
+ const formatProgress = ({ summary, load }) => {
57
+ const depots = load.depots.skipped + load.depots.created;
58
+ const newDepots = summary.rows - load.depots.reused;
59
+ const credentials = load.credentials.skipped + load.credentials.created;
60
+ return (
61
+ `The load stopped after creating ${formatNumber(depots)} of ${count(newDepots, 'depot')} ` +
62
+ `and ${formatNumber(credentials)} of ${count(summary.credentials, 'credential')}. ` +
63
+ `${load.state} records what was created. Rerun the same command to continue.`
64
+ );
65
+ };
66
+
67
+ /**
68
+ * Formats a load that stopped: the rows the Hub refused, if any, the error,
69
+ * and how far the load got.
70
+ * @param {{ summary: object, load: object, error: Error }} report
71
+ * @returns {string} the report
72
+ */
73
+ const formatLoadFailure = (report) => {
74
+ const { error } = report;
75
+ const lines = [
76
+ ...(error.errors == null ? [] : formatErrors(error.errors)),
77
+ `Error: ${describeError(error)}`,
78
+ formatProgress(report),
79
+ ];
80
+ return `${join('\n', lines)}\n`;
81
+ };
82
+
83
+ /**
84
+ * Formats a load, finished or stopped, as JSON.
85
+ * @param {{ summary: object, load: object, error?: Error }} report
86
+ * @returns {string} `{ valid, errors, summary, load }`, where load has an error when the load stopped
87
+ */
88
+ const formatJsonLoadReport = ({ summary, load, error }) => {
89
+ const loadError = error && {
90
+ message: describeError(error),
91
+ errors: error.errors,
92
+ };
93
+ const report = {
94
+ valid: true,
95
+ errors: [],
96
+ summary,
97
+ load: { ...load, error: loadError },
98
+ };
99
+ return `${JSON.stringify(report, null, 2)}\n`;
100
+ };
101
+
102
+ const toNotificationError = ({ row, depotId, error }) => ({
103
+ row,
104
+ reason: join(
105
+ ': ',
106
+ compact([`the wallet message about depot ${depotId} failed`, error]),
107
+ ),
108
+ });
109
+
110
+ /**
111
+ * Formats the wallet messages that failed when a finished load resolved
112
+ * deferred credentials, by row.
113
+ * @param {{ load: { failedNotifications: Array<{ row: number, depotId: string, error?: string }> } }} report
114
+ * @returns {string} the report, or nothing when none failed
115
+ */
116
+ const formatFailedNotifications = ({ load }) => {
117
+ const failed = load.failedNotifications;
118
+ if (isEmpty(failed)) {
119
+ return '';
120
+ }
121
+ const lines = [
122
+ ...formatErrors(map(toNotificationError, failed)),
123
+ `Error: the waiting wallets of ${count(size(failed), 'depot')} weren't told that their deferred credentials are ready. ` +
124
+ 'Rerun the same command to retry.',
125
+ ];
126
+ return `${join('\n', lines)}\n`;
127
+ };
128
+
129
+ module.exports = {
130
+ formatFailedNotifications,
131
+ formatJsonLoadReport,
132
+ formatLoadFailure,
133
+ formatLoadReport,
134
+ };
@@ -0,0 +1,100 @@
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
+ flatMap,
19
+ isEmpty,
20
+ join,
21
+ map,
22
+ replace,
23
+ size,
24
+ sortBy,
25
+ } = require('lodash/fp');
26
+ const { count } = require('./count');
27
+
28
+ const NOTHING_WRITTEN = 'Nothing was written to the Hub.';
29
+
30
+ // Errors without a row first, then by row. The sort is stable, so each row's
31
+ // errors keep their order.
32
+ const orderErrors = sortBy(({ row }) => row ?? 0);
33
+
34
+ // A multi-line reason, such as a Handlebars parse error, stays indented.
35
+ const indentLines = replace(/\n/g, '\n ');
36
+
37
+ const formatError = ({ column, template, reason }) => {
38
+ const columnPrefix = column == null ? '' : `${column}: `;
39
+ const templateSuffix = template == null ? '' : ` (template ${template})`;
40
+ return ` - ${columnPrefix}${indentLines(reason)}${templateSuffix}`;
41
+ };
42
+
43
+ // Errors without a row are about the spec, the service or the whole CSV.
44
+ const formatSection = ([row, rowErrors]) => [
45
+ row == null ? 'Batch:' : `Row ${row}:`,
46
+ ...map(formatError, rowErrors),
47
+ '',
48
+ ];
49
+
50
+ // Map.groupBy keeps the order of the ordered errors, so the sections follow
51
+ // the JSON report's order.
52
+ const formatErrors = (errors) => {
53
+ const sections = Map.groupBy(orderErrors(errors), ({ row }) => row);
54
+ return flatMap(formatSection, [...sections]);
55
+ };
56
+
57
+ const formatSummary = (summary) =>
58
+ join(', ', [
59
+ count(summary.rows, 'row'),
60
+ count(summary.newDepots, 'new depot'),
61
+ count(summary.existingDepots, 'existing depot'),
62
+ count(summary.credentials, 'credential'),
63
+ ]);
64
+
65
+ /**
66
+ * Formats a validation result as a readable report, grouped by row.
67
+ * @param {{ errors: Array<object>, summary?: object }} result
68
+ * @returns {string} the report
69
+ */
70
+ const formatTextReport = ({ errors, summary }) => {
71
+ if (isEmpty(errors)) {
72
+ return `The batch is valid: ${formatSummary(summary)}. ${NOTHING_WRITTEN}\n`;
73
+ }
74
+ const lines = [
75
+ ...formatErrors(errors),
76
+ `The batch is not valid: ${count(size(errors), 'error')}. ${NOTHING_WRITTEN}`,
77
+ ];
78
+ return `${join('\n', lines)}\n`;
79
+ };
80
+
81
+ /**
82
+ * Formats a validation result as JSON.
83
+ * @param {{ errors: Array<object>, summary?: object }} result
84
+ * @returns {string} `{ valid, errors, summary }`, where summary is missing when the spec has errors
85
+ */
86
+ const formatJsonReport = ({ errors, summary }) => {
87
+ const report = {
88
+ valid: isEmpty(errors),
89
+ errors: orderErrors(errors),
90
+ summary,
91
+ };
92
+ return `${JSON.stringify(report, null, 2)}\n`;
93
+ };
94
+
95
+ module.exports = {
96
+ formatErrors,
97
+ formatJsonReport,
98
+ formatSummary,
99
+ formatTextReport,
100
+ };
@@ -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 { readFile } = require('node:fs/promises');
18
+ const path = require('node:path');
19
+ const Ajv = require('ajv');
20
+ const YAML = require('yaml');
21
+ const {
22
+ cond,
23
+ constant,
24
+ flatMap,
25
+ flow,
26
+ get,
27
+ has,
28
+ includes,
29
+ isEmpty,
30
+ isPlainObject,
31
+ isString,
32
+ join,
33
+ map,
34
+ replace,
35
+ stubTrue,
36
+ } = require('lodash/fp');
37
+ const { extractCredentialType } = require('@verii/vc-checks');
38
+ const { specSchema } = require('./spec-schema');
39
+ const { checkTemplateSyntax } = require('../templates/render-template');
40
+
41
+ const specAjv = new Ajv({ allErrors: true });
42
+ const validateSpecSchema = specAjv.compile(specSchema);
43
+
44
+ // AJV's messages don't name an unknown property or the allowed values.
45
+ const errorDetail = cond([
46
+ [
47
+ has(['params', 'additionalProperty']),
48
+ ({ params }) => `: ${params.additionalProperty}`,
49
+ ],
50
+ [
51
+ has(['params', 'allowedValues']),
52
+ ({ params }) => `: ${join(', ', params.allowedValues)}`,
53
+ ],
54
+ [stubTrue, constant('')],
55
+ ]);
56
+
57
+ // /depot/authValues/0 becomes spec.depot.authValues.0
58
+ const specPath = flow(
59
+ replace(/\//g, '.'),
60
+ (instancePath) => `spec${instancePath}`,
61
+ );
62
+
63
+ const toSchemaError = (error) => ({
64
+ reason: `${specPath(error.instancePath)} ${error.message}${errorDetail(error)}`,
65
+ });
66
+
67
+ const checkSchema = (spec) =>
68
+ validateSpecSchema(spec) ? [] : map(toSchemaError, validateSpecSchema.errors);
69
+
70
+ // A holder who opens the link before their credentials exist would otherwise
71
+ // get nothing to wait for.
72
+ const checkDepotOnly = (spec) =>
73
+ has('credentials', spec) ||
74
+ get(['depot', 'deferredCredentials'], spec) === true
75
+ ? []
76
+ : [
77
+ {
78
+ reason:
79
+ 'a spec without credentials loads depots only, so it needs depot.deferredCredentials: true',
80
+ },
81
+ ];
82
+
83
+ const checkSpecTemplates = (spec) => {
84
+ const credentialStrings = flatMap(
85
+ ({ credentialReference, tags = [] }) => [credentialReference, ...tags],
86
+ spec.credentials,
87
+ );
88
+ const syntaxErrors = checkTemplateSyntax([
89
+ spec.depot.userReference,
90
+ ...credentialStrings,
91
+ ]);
92
+ return map(
93
+ (reason) => ({ reason: `the spec has a template error: ${reason}` }),
94
+ syntaxErrors,
95
+ );
96
+ };
97
+
98
+ const checkTemplateType = ({ template: name, type }) => {
99
+ if (!isString(type) || isEmpty(type)) {
100
+ return [{ reason: `template ${name} has no credential type` }];
101
+ }
102
+ return includes('{{', type)
103
+ ? [{ reason: `template ${name}'s type must not be a Handlebars template` }]
104
+ : [];
105
+ };
106
+
107
+ const checkTemplateContent = (template) => {
108
+ const syntaxErrors = map(
109
+ (reason) => ({
110
+ reason: `template ${template.template} has a template error: ${reason}`,
111
+ }),
112
+ checkTemplateSyntax(template.content),
113
+ );
114
+ return [...checkTemplateType(template), ...syntaxErrors];
115
+ };
116
+
117
+ // JSON.parse throws a SyntaxError. Any other error is from reading the file.
118
+ const loadTemplate = (specDir) => async (credential) => {
119
+ const name = credential.template;
120
+ try {
121
+ const text = await readFile(path.resolve(specDir, name), 'utf8');
122
+ const content = JSON.parse(text);
123
+ if (!isPlainObject(content)) {
124
+ return { errors: [{ reason: `template ${name} is not a JSON object` }] };
125
+ }
126
+ const type = extractCredentialType(content);
127
+ const template = { ...credential, content, type };
128
+ return { template, errors: checkTemplateContent(template) };
129
+ } catch (error) {
130
+ const problem =
131
+ error instanceof SyntaxError ? 'is not valid JSON' : "can't be read";
132
+ return {
133
+ errors: [{ reason: `template ${name} ${problem}: ${error.message}` }],
134
+ };
135
+ }
136
+ };
137
+
138
+ const loadTemplates = async (spec, specDir) => {
139
+ const results = await Promise.all(
140
+ map(loadTemplate(specDir), spec.credentials ?? []),
141
+ );
142
+ return {
143
+ templates: map('template', results),
144
+ errors: flatMap('errors', results),
145
+ };
146
+ };
147
+
148
+ /**
149
+ * Reads a spec file and checks it against the spec's JSON schema.
150
+ * @param {string} specFile the YAML spec file
151
+ * @returns {Promise<{ spec?: object, errors: Array<{ reason: string }> }>} the spec, which is only valid when there are no errors
152
+ * @throws when the spec file can't be read
153
+ */
154
+ const readSpec = async (specFile) => {
155
+ const text = await readFile(specFile, 'utf8');
156
+ try {
157
+ const spec = YAML.parse(text);
158
+ return { spec, errors: checkSchema(spec) };
159
+ } catch (error) {
160
+ if (!(error instanceof YAML.YAMLParseError)) {
161
+ throw error;
162
+ }
163
+ return {
164
+ errors: [{ reason: `the spec is not valid YAML: ${error.message}` }],
165
+ };
166
+ }
167
+ };
168
+
169
+ /**
170
+ * Reads a spec file and loads its templates, and checks them all.
171
+ * @param {string} specFile the YAML spec file
172
+ * @returns {Promise<{ spec?: object, templates?: Array<object>, errors: Array<{ reason: string }> }>}
173
+ * the spec and its templates, which are only complete when there are no errors
174
+ * @throws when the spec file can't be read
175
+ */
176
+ const loadSpec = async (specFile) => {
177
+ const { spec, errors: specErrors } = await readSpec(specFile);
178
+ if (!isEmpty(specErrors)) {
179
+ return { errors: specErrors };
180
+ }
181
+ const { templates, errors: templateErrors } = await loadTemplates(
182
+ spec,
183
+ path.dirname(specFile),
184
+ );
185
+ const errors = [
186
+ ...checkDepotOnly(spec),
187
+ ...checkSpecTemplates(spec),
188
+ ...templateErrors,
189
+ ];
190
+ return { spec, templates, errors };
191
+ };
192
+
193
+ module.exports = { loadSpec, readSpec };
@@ -0,0 +1,109 @@
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 { get } = require('lodash/fp');
18
+ const { newDepotSchema } = require('@verii/credentialing-hub-operator-api');
19
+ const { VALUE_TYPES } = require('../values/convert-value');
20
+
21
+ const nonEmptyString = { type: 'string', minLength: 1 };
22
+
23
+ const authValueSchema = {
24
+ type: 'object',
25
+ additionalProperties: false,
26
+ required: ['column'],
27
+ properties: {
28
+ column: {
29
+ ...nonEmptyString,
30
+ description: 'the CSV column that holds the value',
31
+ },
32
+ },
33
+ };
34
+
35
+ const depotSchema = {
36
+ type: 'object',
37
+ additionalProperties: false,
38
+ required: ['userReference'],
39
+ properties: {
40
+ userReference: {
41
+ ...nonEmptyString,
42
+ description: "a Handlebars template of the depot's userReference",
43
+ },
44
+ authValues: {
45
+ type: 'array',
46
+ description:
47
+ "one entry for each of the service's auth rules, in valueIndex order",
48
+ maxItems: get(['properties', 'authValues', 'maxItems'], newDepotSchema),
49
+ items: authValueSchema,
50
+ },
51
+ expectedCredentialTypes: get(
52
+ ['properties', 'expectedCredentialTypes'],
53
+ newDepotSchema,
54
+ ),
55
+ deferredCredentials: { type: 'boolean' },
56
+ },
57
+ };
58
+
59
+ const credentialSchema = {
60
+ type: 'object',
61
+ additionalProperties: false,
62
+ required: ['template', 'credentialReference'],
63
+ properties: {
64
+ template: {
65
+ ...nonEmptyString,
66
+ description:
67
+ "a JSON template of the credential's content, relative to the spec",
68
+ },
69
+ credentialReference: {
70
+ ...nonEmptyString,
71
+ description:
72
+ "a Handlebars template of the credential's credentialReference",
73
+ },
74
+ tags: {
75
+ type: 'array',
76
+ description: 'Handlebars templates of the tags',
77
+ items: nonEmptyString,
78
+ },
79
+ },
80
+ };
81
+
82
+ /**
83
+ * The JSON schema of a batch-issuer spec file.
84
+ */
85
+ const specSchema = {
86
+ $id: 'batch-issuer-spec',
87
+ type: 'object',
88
+ additionalProperties: false,
89
+ required: ['tenantId', 'serviceId', 'depot'],
90
+ properties: {
91
+ tenantId: nonEmptyString,
92
+ serviceId: nonEmptyString,
93
+ depot: depotSchema,
94
+ columns: {
95
+ type: 'object',
96
+ description: 'the type of each typed column. Other columns are strings',
97
+ additionalProperties: { enum: VALUE_TYPES },
98
+ },
99
+ credentials: {
100
+ type: 'array',
101
+ description:
102
+ 'the credentials of each row. Without them, the load creates depots only',
103
+ minItems: 1,
104
+ items: credentialSchema,
105
+ },
106
+ },
107
+ };
108
+
109
+ module.exports = { specSchema };