@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/src/cli.js ADDED
@@ -0,0 +1,190 @@
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 { Command, InvalidArgumentError, Option } = require('commander');
18
+ const { isSupportedCountry } = require('libphonenumber-js');
19
+ const { isEmpty, join, split, toLower, toUpper } = require('lodash/fp');
20
+ const packageJson = require('../package.json');
21
+ const { ExitCodes } = require('./commands/exit-codes');
22
+ const { runLoad } = require('./commands/load');
23
+ const { runCheckRules } = require('./commands/check-rules');
24
+ const { describeError } = require('./report/describe-error');
25
+
26
+ const AUTH_TOKEN_ENV = 'BATCH_ISSUER_AUTH_TOKEN';
27
+
28
+ // Runs a command. An error that stops it, such as an unreadable file or a Hub
29
+ // or registrar failure, is printed, and exits with ERROR.
30
+ const runCommand = async (command, io) => {
31
+ try {
32
+ return await command();
33
+ } catch (error) {
34
+ io.stderr(`Error: ${describeError(error)}\n`);
35
+ return ExitCodes.ERROR;
36
+ }
37
+ };
38
+
39
+ // A value may itself hold "=", so only the first one separates the name.
40
+ const parseVar = (text, vars) => {
41
+ const [name, ...valueParts] = split('=', text);
42
+ if (isEmpty(name) || isEmpty(valueParts)) {
43
+ throw new InvalidArgumentError('Use name=value.');
44
+ }
45
+ return { ...vars, [name]: join('=', valueParts) };
46
+ };
47
+
48
+ const parseCountry = (text) => {
49
+ const country = toUpper(text);
50
+ if (!isSupportedCountry(country)) {
51
+ throw new InvalidArgumentError(
52
+ 'Use a two-letter country code, such as US.',
53
+ );
54
+ }
55
+ return country;
56
+ };
57
+
58
+ const addHubOptions = (command) =>
59
+ command
60
+ .requiredOption('-e, --endpoint <url>', "the Credentialing Hub's base URL")
61
+ .addOption(
62
+ new Option(
63
+ '-a, --auth-token <token>',
64
+ `an operator API token. Prefer ${AUTH_TOKEN_ENV}, which keeps it out of the shell history`,
65
+ )
66
+ .env(AUTH_TOKEN_ENV)
67
+ .makeOptionMandatory(),
68
+ )
69
+ .option('--json', 'print the report as JSON');
70
+
71
+ // The arguments and options of validate and load.
72
+ const addBatchOptions = (command) =>
73
+ addHubOptions(
74
+ command
75
+ .argument('<spec>', 'the YAML spec file')
76
+ .argument('<csv>', 'the CSV file, with a header line'),
77
+ )
78
+ .requiredOption(
79
+ '--network <name>',
80
+ "the Hub's Velocity network, such as devnet, testnet or mainnet, which the state file is tied to",
81
+ toLower,
82
+ )
83
+ .option(
84
+ '-r, --registrar <url>',
85
+ "the registrar's base URL, to check credentials against their types' schemas",
86
+ )
87
+ .option(
88
+ '--default-country <code>',
89
+ 'the country of phone numbers written without a country code',
90
+ parseCountry,
91
+ )
92
+ .option(
93
+ '--var <name=value>',
94
+ 'a value that overrides the CSV column of the same name. Repeatable',
95
+ parseVar,
96
+ {},
97
+ )
98
+ .option(
99
+ '--no-reuse',
100
+ 'treat rows whose auth values already belong to a depot as errors',
101
+ )
102
+ .option(
103
+ '--state <file>',
104
+ "the batch's state file, which records what loading it created (default: the CSV's name with .state.jsonl)",
105
+ );
106
+
107
+ const addValidateCommand = (program, io, resolve) =>
108
+ addBatchOptions(
109
+ program
110
+ .command('validate')
111
+ .description(
112
+ 'Validate a batch against its spec, the registrar and the Hub. Nothing is written to the Hub. The same as load --dryrun.',
113
+ ),
114
+ ).action(async (specFile, csvFile, options) => {
115
+ const validate = () =>
116
+ runLoad({ specFile, csvFile, options: { ...options, dryrun: true } }, io);
117
+ resolve(await runCommand(validate, io));
118
+ });
119
+
120
+ const addLoadCommand = (program, io, resolve) =>
121
+ addBatchOptions(
122
+ program
123
+ .command('load')
124
+ .description(
125
+ 'Validate a batch, then load its depots and credentials into the Hub, and write their links.',
126
+ ),
127
+ )
128
+ .option('--dryrun', 'stop after validating, as validate does')
129
+ .option(
130
+ '--resolve-deferred',
131
+ 'resolve the deferred credentials of reused depots that receive credentials',
132
+ )
133
+ .option(
134
+ '-o, --output <file>',
135
+ "the CSV of each row's link (default: the CSV's name with .links.csv)",
136
+ )
137
+ .action(async (specFile, csvFile, options) => {
138
+ const load = () => runLoad({ specFile, csvFile, options }, io);
139
+ resolve(await runCommand(load, io));
140
+ });
141
+
142
+ const addCheckRulesCommand = (program, io, resolve) =>
143
+ addHubOptions(
144
+ program
145
+ .command('check-rules')
146
+ .description(
147
+ "Show what the service's auth rules read from sample credentials.",
148
+ )
149
+ .argument('<spec>', 'the YAML spec file, for its tenantId and serviceId'),
150
+ )
151
+ .requiredOption(
152
+ '-s, --sample <credential...>',
153
+ 'a credential, as a JSON file or a file holding a JWT',
154
+ )
155
+ .action(async (specFile, options) => {
156
+ const checkRules = () => runCheckRules({ specFile, options }, io);
157
+ resolve(await runCommand(checkRules, io));
158
+ });
159
+
160
+ // Commander throws instead of exiting. Help and the version exit with 0.
161
+ const exitCodeOf = (error) =>
162
+ error.exitCode === 0 ? ExitCodes.OK : ExitCodes.ERROR;
163
+
164
+ /**
165
+ * Runs the batch-issuer command line.
166
+ * @param {Array<string>} argv the arguments, as process.argv gives them
167
+ * @param {{ stdout: Function, stderr: Function }} io where output and errors go
168
+ * @returns {Promise<number>} the exit code
169
+ */
170
+ const runCli = (argv, io) =>
171
+ new Promise((resolve) => {
172
+ const program = new Command('batch-issuer')
173
+ .description(
174
+ 'Load Credentialing Hub depots and credentials from a CSV file.',
175
+ )
176
+ .version(packageJson.version)
177
+ .exitOverride()
178
+ .configureOutput({ writeOut: io.stdout, writeErr: io.stderr });
179
+ addValidateCommand(program, io, resolve);
180
+ addLoadCommand(program, io, resolve);
181
+ addCheckRulesCommand(program, io, resolve);
182
+ // A command resolves with its exit code before parseAsync settles, so the
183
+ // then only applies to a parse that runs no command.
184
+ program
185
+ .parseAsync(argv)
186
+ .then(() => resolve(ExitCodes.ERROR))
187
+ .catch((error) => resolve(exitCodeOf(error)));
188
+ });
189
+
190
+ module.exports = { runCli };
@@ -0,0 +1,181 @@
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
+ chunk,
19
+ find,
20
+ flatten,
21
+ flow,
22
+ get,
23
+ has,
24
+ isArray,
25
+ isEqual,
26
+ isString,
27
+ map,
28
+ toLower,
29
+ } = require('lodash/fp');
30
+ const {
31
+ findDepotsRequestSchema,
32
+ } = require('@verii/credentialing-hub-operator-api');
33
+ const { initClient } = require('./init-client');
34
+
35
+ // The most auth values tuples that one POST depots/get takes, from its
36
+ // request schema.
37
+ const MAX_AUTH_VALUES_PER_REQUEST = get(
38
+ ['properties', 'authValues', 'maxItems'],
39
+ findDepotsRequestSchema,
40
+ );
41
+
42
+ const ISSUER_SERVICES_PATH = 'operator/issuer-services/get';
43
+ const DEPOTS_PATH = 'operator/depots/get';
44
+ const CREATE_DEPOT_PATH = 'operator/depots/create';
45
+ const CREATE_CREDENTIALS_PATH = 'operator/credentials/create-many';
46
+ const RESOLVE_DEFERRED_PATH = 'operator/depots/resolve-deferred-credentials';
47
+ const REFRESH_ISSUE_LINKS_PATH = 'operator/issue-links/refresh';
48
+
49
+ // http-client's json() gives {} for a body that isn't JSON, such as a proxy's
50
+ // HTML page, so a response without what it should hold is an error rather
51
+ // than an empty result, which would pass the checks it was meant for.
52
+ const readResponse =
53
+ (key, isExpected, description) => async (response, path) => {
54
+ const value = get([key], await response.json());
55
+ if (!isExpected(value)) {
56
+ throw new Error(
57
+ `${path} did not return ${description}. Check that --endpoint is the Credentialing Hub's base URL`,
58
+ );
59
+ }
60
+ return value;
61
+ };
62
+
63
+ const readServices = readResponse('services', isArray, 'a list of services');
64
+ const readDepots = readResponse('depots', isArray, 'a list of depots');
65
+ const readDepot = readResponse('depot', has('id'), 'a depot');
66
+ const readCredentials = readResponse(
67
+ 'credentials',
68
+ isArray,
69
+ 'a list of credentials',
70
+ );
71
+ const readNotification = readResponse(
72
+ 'notification',
73
+ has('status'),
74
+ 'a notification',
75
+ );
76
+ const readRedirectUrl = readResponse('redirectUrl', isString, 'a redirectUrl');
77
+
78
+ // Service ids are ObjectIds, which the Hub accepts in either case and
79
+ // returns in lower case.
80
+ const hasServiceId = (serviceId) =>
81
+ flow(get('id'), toLower, isEqual(toLower(serviceId)));
82
+
83
+ /**
84
+ * A client of the Credentialing Hub's operator API.
85
+ * @param {{ endpoint: string, authToken: string }} options the Hub's base URL and an operator token
86
+ */
87
+ const initHubClient = ({ endpoint, authToken }) => {
88
+ const client = initClient({ prefixUrl: endpoint, bearerToken: authToken });
89
+
90
+ const post = async (path, body, read) =>
91
+ read(await client.post(path, body), path);
92
+
93
+ /**
94
+ * Gets an issuer service with issuer-services/get.
95
+ * @param {{ tenantId: string, serviceId: string }} ids
96
+ * @returns {Promise<object|undefined>} the service, or undefined when the tenant has no such service
97
+ * @throws when the response has no list of services
98
+ */
99
+ const getIssuerService = async ({ tenantId, serviceId }) => {
100
+ const searchParams = new URLSearchParams({ tenantId, serviceId });
101
+ const response = await client.get(ISSUER_SERVICES_PATH, { searchParams });
102
+ const services = await readServices(response, ISSUER_SERVICES_PATH);
103
+ return find(hasServiceId(serviceId), services);
104
+ };
105
+
106
+ const findDepotsChunk = ({ tenantId, serviceId }, authValues) =>
107
+ post(DEPOTS_PATH, { tenantId, serviceId, authValues }, readDepots);
108
+
109
+ /**
110
+ * Finds the service's depots whose auth values match any of the tuples,
111
+ * with POST depots/get, in requests of at most the tuples it takes.
112
+ * @param {{ tenantId: string, serviceId: string }} ids
113
+ * @param {Array<Array<string|number|boolean>>} authValues the distinct tuples
114
+ * @returns {Promise<Array<object>>} the depots
115
+ * @throws when a response has no list of depots
116
+ */
117
+ const findDepotsByAuthValues = async (ids, authValues) => {
118
+ const chunks = chunk(MAX_AUTH_VALUES_PER_REQUEST, authValues);
119
+ const pages = await Promise.all(
120
+ map((tuples) => findDepotsChunk(ids, tuples), chunks),
121
+ );
122
+ return flatten(pages);
123
+ };
124
+
125
+ /**
126
+ * Creates a depot with depots/create.
127
+ * @param {{ tenantId: string, serviceId: string }} ids
128
+ * @param {object} depot the new depot
129
+ * @returns {Promise<object>} the depot
130
+ * @throws an HTTP error with status 409 when another depot holds the auth values
131
+ */
132
+ const createDepot = ({ tenantId, serviceId }, depot) =>
133
+ post(CREATE_DEPOT_PATH, { tenantId, serviceId, depot }, readDepot);
134
+
135
+ /**
136
+ * Creates credentials with credentials/create-many, which creates all of
137
+ * them or none.
138
+ * @param {{ tenantId: string }} ids
139
+ * @param {Array<{ depotId: string, credential: object }>} items at most CREDENTIALS_CREATE_MANY_MAX_ITEMS
140
+ * @returns {Promise<Array<object>>} the credentials, in the items' order
141
+ * @throws an HTTP error with status 400, whose body lists the invalid items, when any item is invalid
142
+ */
143
+ const createCredentials = ({ tenantId }, items) =>
144
+ post(CREATE_CREDENTIALS_PATH, { tenantId, items }, readCredentials);
145
+
146
+ /**
147
+ * Resolves a depot's deferred credentials with
148
+ * depots/resolve-deferred-credentials.
149
+ * @param {{ tenantId: string }} ids
150
+ * @param {string} depotId
151
+ * @returns {Promise<{ status: string, error?: string }>} the notification of a waiting wallet, whose status
152
+ * is sent, failed, skipped_no_messaging_settings or skipped_no_waiting_exchange
153
+ */
154
+ const resolveDeferredCredentials = ({ tenantId }, depotId) =>
155
+ post(RESOLVE_DEFERRED_PATH, { tenantId, depotId }, readNotification);
156
+
157
+ /**
158
+ * Gets an issue link with issue-links/refresh. A depot's link replaces its
159
+ * pre-authorized code, which breaks the links sent before.
160
+ * @param {{ tenantId: string, serviceId: string }} ids
161
+ * @param {string} [depotId] the depot, or none for the service's shared link
162
+ * @returns {Promise<string>} the link's redirectUrl
163
+ */
164
+ const refreshIssueLink = ({ tenantId, serviceId }, depotId) =>
165
+ post(
166
+ REFRESH_ISSUE_LINKS_PATH,
167
+ { tenantId, serviceId, depotId },
168
+ readRedirectUrl,
169
+ );
170
+
171
+ return {
172
+ getIssuerService,
173
+ findDepotsByAuthValues,
174
+ createDepot,
175
+ createCredentials,
176
+ resolveDeferredCredentials,
177
+ refreshIssueLink,
178
+ };
179
+ };
180
+
181
+ module.exports = { initHubClient };
@@ -0,0 +1,40 @@
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 { randomUUID } = require('node:crypto');
18
+ const { env } = require('node:process');
19
+ const { initHttpClient } = require('@verii/http-client');
20
+ const { noop } = require('lodash/fp');
21
+
22
+ // The HTTP client logs each request with its headers, which hold the operator
23
+ // token, so it gets a log that drops everything.
24
+ const silentLog = { info: noop, warn: noop, error: noop, debug: noop };
25
+
26
+ /**
27
+ * Builds an HTTP client for one base URL, as data-loader does.
28
+ * NODE_TLS_REJECT_UNAUTHORIZED=0 turns off TLS verification.
29
+ * @param {{ prefixUrl: string, bearerToken?: string }} options
30
+ * @returns {{ get: Function, post: Function }} the client
31
+ */
32
+ const initClient = ({ prefixUrl, bearerToken }) =>
33
+ initHttpClient({
34
+ prefixUrl,
35
+ bearerToken,
36
+ isTest: env.NODE_ENV === 'test',
37
+ tlsRejectUnauthorized: env.NODE_TLS_REJECT_UNAUTHORIZED !== '0',
38
+ })({ log: silentLog, traceId: randomUUID() });
39
+
40
+ module.exports = { initClient };
@@ -0,0 +1,37 @@
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
+ fetchJson,
19
+ getCredentialTypeMetadata,
20
+ } = require('@verii/common-fetchers');
21
+ const { initClient } = require('./init-client');
22
+
23
+ /**
24
+ * A client of the registrar, for credential types and their schemas, which
25
+ * credentials/create loads the same way.
26
+ * @param {{ registrar: string }} options the registrar's base URL
27
+ */
28
+ const initRegistrarClient = ({ registrar }) => {
29
+ const registrarFetch = initClient({ prefixUrl: registrar });
30
+ return {
31
+ getCredentialTypeMetadata: (credentialTypes) =>
32
+ getCredentialTypeMetadata(credentialTypes, { registrarFetch }),
33
+ getSchema: (schemaUrl) => fetchJson(schemaUrl, { fetch: registrarFetch }),
34
+ };
35
+ };
36
+
37
+ module.exports = { initRegistrarClient };
@@ -0,0 +1,187 @@
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 {
19
+ every,
20
+ filter,
21
+ flatMap,
22
+ isEmpty,
23
+ isNil,
24
+ join,
25
+ map,
26
+ pick,
27
+ reject,
28
+ size,
29
+ sortBy,
30
+ startsWith,
31
+ trim,
32
+ } = require('lodash/fp');
33
+ const {
34
+ ruleValues,
35
+ selectClaims,
36
+ } = require('@verii/credentialing-hub-operator-api');
37
+ const { decodeCredentialJwt } = require('@verii/jwt');
38
+ const { extractCredentialType } = require('@verii/vc-checks');
39
+ const { initHubClient } = require('../clients/hub-client');
40
+ const { readSpec } = require('../spec/load-spec');
41
+ const { count } = require('../report/count');
42
+ const { ExitCodes } = require('./exit-codes');
43
+
44
+ // A JSON credential is an object. Anything else is a JWT, decoded as the Hub
45
+ // decodes a presented credential, so a VC 1.1 JWT's claims are read from the
46
+ // credential it carries.
47
+ const parseSample = (text) => {
48
+ const trimmed = trim(text);
49
+ return startsWith('{', trimmed)
50
+ ? JSON.parse(trimmed)
51
+ : decodeCredentialJwt(trimmed);
52
+ };
53
+
54
+ const readSample = async (file) => {
55
+ try {
56
+ const credential = parseSample(await readFile(file, 'utf8'));
57
+ return { file, type: extractCredentialType(credential), credential };
58
+ } catch (error) {
59
+ throw new Error(
60
+ `the sample ${file} is not a JSON credential or a JWT: ${error.message}`,
61
+ {
62
+ cause: error,
63
+ },
64
+ );
65
+ }
66
+ };
67
+
68
+ // The Hub's equal rule uses a value only when the credentials give exactly one.
69
+ const candidateValues = (rule, values) =>
70
+ rule.rule === 'equal' && size(values) !== 1 ? [] : values;
71
+
72
+ const pointerSelections = (rule) => (sample) => ({
73
+ file: sample.file,
74
+ pointers: map(
75
+ (pointer) => ({
76
+ pointer,
77
+ selected: selectClaims(pointer, sample.credential),
78
+ }),
79
+ rule.path,
80
+ ),
81
+ });
82
+
83
+ const checkRule = (samples) => (rule) => {
84
+ const values = ruleValues(rule, samples);
85
+ const ruleSamples = filter({ type: rule.type }, samples);
86
+ return {
87
+ rule,
88
+ samples: map(pointerSelections(rule), ruleSamples),
89
+ values,
90
+ candidateValues: candidateValues(rule, values),
91
+ };
92
+ };
93
+
94
+ const describeRule = ({ rule, valueIndex, type, valueType, valueFormat }) => {
95
+ const details = reject(isNil, [type, rule, valueType, valueFormat]);
96
+ return `Rule ${valueIndex}: ${join(', ', details)}`;
97
+ };
98
+
99
+ const formatSample = ({ file, pointers }) => [
100
+ ` ${file}`,
101
+ ...map(
102
+ ({ pointer, selected }) =>
103
+ ` ${JSON.stringify(pointer)} selects ${JSON.stringify(selected)}`,
104
+ pointers,
105
+ ),
106
+ ];
107
+
108
+ const formatValues = ({ values, candidateValues: usable }) => {
109
+ const listed = isEmpty(values)
110
+ ? 'none'
111
+ : join(', ', map(JSON.stringify, values));
112
+ const note =
113
+ size(usable) === size(values)
114
+ ? ''
115
+ : ', but equal uses a value only when there is exactly one, so the rule reads nothing';
116
+ return ` values: ${listed}${note}`;
117
+ };
118
+
119
+ const formatRuleResult = (result) => {
120
+ const sampleLines = isEmpty(result.samples)
121
+ ? [` no sample is a ${result.rule.type}`]
122
+ : flatMap(formatSample, result.samples);
123
+ return [describeRule(result.rule), ...sampleLines, formatValues(result), ''];
124
+ };
125
+
126
+ const readsValue = ({ candidateValues: usable }) => !isEmpty(usable);
127
+
128
+ const describeSample = ({ file, type }) => `${file} (${type})`;
129
+
130
+ const formatText = ({ samples, results }) => {
131
+ const sampleList = join(', ', map(describeSample, samples));
132
+ const readingRules = size(filter(readsValue, results));
133
+ const lines = [
134
+ `Samples: ${sampleList}`,
135
+ '',
136
+ ...flatMap(formatRuleResult, results),
137
+ `${readingRules} of ${count(size(results), 'rule')} read a value from the samples.`,
138
+ ];
139
+ return `${join('\n', lines)}\n`;
140
+ };
141
+
142
+ const formatJson = ({ samples, results }) => {
143
+ const report = {
144
+ samples: map(pick(['file', 'type']), samples),
145
+ rules: results,
146
+ };
147
+ return `${JSON.stringify(report, null, 2)}\n`;
148
+ };
149
+
150
+ const loadRules = async (specFile, options) => {
151
+ const { spec, errors } = await readSpec(specFile);
152
+ if (!isEmpty(errors)) {
153
+ throw new Error(join('; ', map('reason', errors)));
154
+ }
155
+ const hub = initHubClient(options);
156
+ const service = await hub.getIssuerService(spec);
157
+ if (service == null) {
158
+ throw new Error(
159
+ `tenant ${spec.tenantId} has no issuer service ${spec.serviceId}`,
160
+ );
161
+ }
162
+ if (isEmpty(service.verifiablePresentationAuthRules)) {
163
+ throw new Error(
164
+ `service ${spec.serviceId} has no verifiablePresentationAuthRules`,
165
+ );
166
+ }
167
+ return sortBy('valueIndex', service.verifiablePresentationAuthRules);
168
+ };
169
+
170
+ /**
171
+ * `batch-issuer check-rules <spec> --sample <credential>`: shows what each of
172
+ * the service's auth rules reads from sample credentials, with the rule
173
+ * evaluation the Hub uses.
174
+ * @param {{ specFile: string, options: object }} input the spec file and the command's options
175
+ * @param {{ stdout: Function }} io where the report goes
176
+ * @returns {Promise<number>} the exit code: OK when every rule reads a value
177
+ */
178
+ const runCheckRules = async ({ specFile, options }, io) => {
179
+ const rules = await loadRules(specFile, options);
180
+ const samples = await Promise.all(map(readSample, options.sample));
181
+ const results = map(checkRule(samples), rules);
182
+ const report = { samples, results };
183
+ io.stdout(options.json ? formatJson(report) : formatText(report));
184
+ return every(readsValue, results) ? ExitCodes.OK : ExitCodes.FAILED;
185
+ };
186
+
187
+ module.exports = { runCheckRules };
@@ -0,0 +1,30 @@
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 ExitCodes = {
18
+ // validate: the batch is valid. load: the batch is loaded. check-rules:
19
+ // every rule reads a value
20
+ OK: 0,
21
+ // validate and load: the batch has errors, and nothing was written.
22
+ // check-rules: a rule reads nothing
23
+ FAILED: 1,
24
+ // The command couldn't run: bad options, an unreadable file, a state file
25
+ // of another batch, or a Hub or registrar error. load: a write failed, and
26
+ // the state file records what was written before it
27
+ ERROR: 2,
28
+ };
29
+
30
+ module.exports = { ExitCodes };