bulk-release 3.2.0 → 3.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/CHANGELOG.md CHANGED
@@ -1,3 +1,8 @@
1
+ ## [3.3.0](https://github.com/semrel-extra/zx-bulk-release/compare/v3.2.0...v3.3.0) (2026-10-03)
2
+
3
+ ### Features
4
+ * feat: add `populate` rules to check parcel manifests after env substitution (#125) ([03fd4ac](https://github.com/semrel-extra/zx-bulk-release/commit/03fd4acd761702c0ac25667c7eed8f3992a1c620))
5
+
1
6
  ## [3.2.0](https://github.com/semrel-extra/zx-bulk-release/compare/v3.1.13...v3.2.0) (2026-04-21)
2
7
 
3
8
  ### Features
package/README.md CHANGED
@@ -269,6 +269,41 @@ Set `ghUrl` to point to your GHE instance. API URL (`ghApiUrl`) is derived autom
269
269
  ```
270
270
  Or via env: `GH_URL=https://ghe.corp.com` / `GITHUB_URL=https://ghe.corp.com`.
271
271
 
272
+ #### Populate rules
273
+ Parcel manifests carry `${{VAR}}` templates that the courier resolves from env at delivery time. `populate` sets what the resolved fields must look like. Pack embeds the rules into every manifest, so a parcel stays self-contained:
274
+ - before delivery starts, the courier resolves every parcel it is about to deliver and checks it against its rules. A parcel that breaks them is not delivered and is left intact. In `--deliver` mode the rest goes on in topological order and the run fails at the end; in all-in-one mode the run stops at the package with the violation;
275
+ - `--verify` makes sure pack kept the rules: the `populate` of every manifest must match the trusted context. Without `--verify` the rules come from the build itself, so they guard against mistakes, not against a compromised build.
276
+
277
+ Errors name the field, never the value.
278
+ ```json
279
+ {
280
+ "populate": {
281
+ "schemas": {
282
+ "secret": {"type": "secret"},
283
+ "registry": {"enum": ["", "https://registry.npmjs.org", "https://registry.npmjs.org/"]},
284
+ "repo": {"const": "org/repo"},
285
+ "repoUrl": {"type": "url", "protocol": "https:", "hostname": "github.com", "pathname": {"pattern": "/org/repo(\\.git)?"}, "username": {}, "password": {}},
286
+ "ghApi": {"const": "https://api.github.com"}
287
+ },
288
+ "channels": {
289
+ "*": {"repoName": {"schema": "repo"}, "repoAuthedUrl": {"schema": "repoUrl"}},
290
+ "npm": {"registry": {"schema": "registry"}},
291
+ "gh-release": {"token": {"schema": "secret"}, "apiUrl": {"schema": "ghApi"}}
292
+ }
293
+ }
294
+ }
295
+ ```
296
+ Here git pushes (`repoAuthedUrl` — the courier derives it from `repoHost`/`repoName` and the token, or falls back to `originUrl`) may only go to `github.com/org/repo`, releases only to its API at `api.github.com`, npm publishes only to npmjs (`""` stands for an unset `NPM_REGISTRY`, which means the default registry), and a GitHub release needs a token. Rules apply to the fields a manifest has, so pin the value that is actually used (`repoAuthedUrl`) rather than its inputs.
297
+ - `schema` — a named schema the resolved field must match (`'*'` — any). Any env var may be substituted, only the result is checked. A placeholder of an unset var resolves to `""`, and that value is checked too.
298
+ - The schema of a field is picked by best match: `channel.field` → `channel.*` → `*.field` → `*.*`. Fields the courier derives at delivery time (`repoAuthedUrl`, `ghBasicAuth`) are checked as well.
299
+ - The default is `{"schemas": {"*": {}}, "channels": {"*": {"*": {"schema": "*"}}}}` — everything is accepted, as before. A malformed `populate` (a rule that isn't `{"schema": name}`, an unknown schema name) fails the release instead of falling back to the default.
300
+
301
+ Schemas:
302
+ - `{}` — any value.
303
+ - `{"type": "string"}` with optional `const`, `enum`, `pattern` (the pattern must match the whole value).
304
+ - `{"type": "secret"}` — a non-empty string.
305
+ - `{"type": "url", ...parts}` — an absolute URL. `protocol`, `username`, `password`, `hostname`, `port`, `pathname`, `search` and `hash` are matched by a string (exact), an array (one of) or a nested schema. Parts that are not described must be empty; `protocol` and `hostname` are checked only when described.
306
+
272
307
  ### env vars
273
308
  ```js
274
309
  export const parseEnv = (env = process.env) => {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bulk-release",
3
3
  "alias": "bulk-release",
4
- "version": "3.2.0",
4
+ "version": "3.3.0",
5
5
  "description": "zx-based alternative for multi-semantic-release",
6
6
  "type": "module",
7
7
  "exports": {
@@ -29,14 +29,15 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@semrel-extra/topo": "^1.14.1",
32
- "tar-stream": "^3.1.8",
32
+ "tar-stream": "^3.2.1",
33
33
  "zx-extra": "4.0.20"
34
34
  },
35
35
  "devDependencies": {
36
- "@vitest/coverage-v8": "^4.1.4",
37
- "esbuild": "^0.28.0",
38
- "verdaccio": "6.5.2",
39
- "vitest": "^4.1.4"
36
+ "@vitest/coverage-v8": "^5.0.3",
37
+ "esbuild": "^0.28.2",
38
+ "verdaccio": "6.10.4",
39
+ "vite": "^8.3.2",
40
+ "vitest": "^5.0.3"
40
41
  },
41
42
  "publishConfig": {
42
43
  "access": "public"
@@ -1,9 +1,10 @@
1
1
  import {$, tempy, within, path, semver, fs} from 'zx-extra'
2
- import {unpackTar} from '../tar.js'
2
+ import {unpackTar, readManifest} from '../tar.js'
3
3
  import {log} from '../log.js'
4
4
  import {pool} from '../../util.js'
5
5
  import {traverseQueue} from '../depot/deps.js'
6
6
  import {scanDirectives, invalidateOrphans} from '../parcel/directive.js'
7
+ import {PLACEHOLDER, mergePopulate, assertPopulate, checkManifest} from '../parcel/populate.js'
7
8
  import {tryLock, unlock, signalRebuild} from './semaphore.js'
8
9
  import gitTag from './channels/git-tag.js'
9
10
  import meta from './channels/meta.js'
@@ -30,9 +31,11 @@ export const prepare = async (names, pkg) => {
30
31
  export const runChannel = async (name, ...args) => channels[name]?.run(...args)
31
32
 
32
33
  export const resolveManifest = (manifest, env = process.env) => {
33
- const resolved = {}
34
- for (const [k, v] of Object.entries(manifest))
35
- resolved[k] = typeof v === 'string' ? v.replace(/\$\{\{(\w+)\}\}/g, (_, n) => env[n] || '') : v
34
+ // Credentials-bearing fields are derived below, never taken from the parcel.
35
+ const {repoAuthedUrl, ghBasicAuth, ...fields} = manifest
36
+ // fromEntries defines own properties: a `__proto__` key stays a plain field and can't swap the prototype
37
+ const resolved = Object.fromEntries(Object.entries(fields).map(([k, v]) =>
38
+ [k, typeof v === 'string' ? v.replace(PLACEHOLDER, (_, n) => env[n] || '') : v]))
36
39
 
37
40
  const {repoHost, repoName, originUrl} = resolved
38
41
  const token = env.GH_TOKEN || env.GITHUB_TOKEN || ''
@@ -48,27 +51,68 @@ export const resolveManifest = (manifest, env = process.env) => {
48
51
  return resolved
49
52
  }
50
53
 
54
+ // Manifest fields the channel needs to run, but that are empty after resolution.
55
+ export const missingRequires = (ch, resolved) =>
56
+ (typeof ch.requires === 'function' ? ch.requires(resolved) : (ch.requires || [])).filter(f => !resolved[f])
57
+
51
58
  const MARKERS = new Set(['released', 'skip', 'conflict', 'orphan'])
52
59
 
60
+ const own = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
61
+
62
+ // The manifest as the channel will get it — shared by the populate check and the delivery itself.
63
+ const resolveForChannel = (manifest, env, cwd) => {
64
+ const resolved = resolveManifest(manifest, env)
65
+ if (cwd) resolved.cwd = cwd
66
+ return {resolved, ch: own(channels, resolved.channel) ? channels[resolved.channel] : undefined}
67
+ }
68
+
53
69
  const openParcel = async (tarPath, env, {cwd} = {}) => {
54
70
  const content = await fs.readFile(tarPath, 'utf8').catch(() => null)
55
71
  if (MARKERS.has(content)) return null
56
72
 
57
73
  const destDir = tempy.temporaryDirectory()
58
74
  const {manifest} = await unpackTar(tarPath, destDir)
59
- const resolved = resolveManifest(manifest, env)
60
- if (cwd) resolved.cwd = cwd
61
- const ch = channels[resolved.channel]
75
+ const {resolved, ch} = resolveForChannel(manifest, env, cwd)
62
76
 
63
77
  if (!ch) return {warn: `unknown channel '${resolved.channel || '<none>'}'`}
64
78
 
65
- const reqs = typeof ch.requires === 'function' ? ch.requires(resolved) : (ch.requires || [])
66
- const missing = reqs.filter(f => !resolved[f])
79
+ const missing = missingRequires(ch, resolved)
67
80
  if (missing.length) return {warn: `missing credentials — ${missing.join(', ')}`, tarPath}
68
81
 
69
82
  return {ch, resolved, destDir, tarPath}
70
83
  }
71
84
 
85
+ // Parcels this env would deliver, but whose resolved manifest breaks the populate rules
86
+ // embedded by pack. Checked before delivery starts; such parcels are left intact.
87
+ const checkParcels = async (tars, env, {cwd} = {}) => {
88
+ const invalid = new Map()
89
+
90
+ for (const tarPath of tars) {
91
+ const manifest = await readManifest(tarPath).catch(() => null)
92
+ if (!manifest || typeof manifest !== 'object') continue
93
+
94
+ const {resolved, ch} = resolveForChannel(manifest, env, cwd)
95
+ if (!ch || missingRequires(ch, resolved).length) continue
96
+
97
+ const errors = own(manifest, '__proto__') ? ['__proto__: is not allowed'] : []
98
+ try {
99
+ const populate = manifest.populate ? assertPopulate(manifest.populate) : mergePopulate()
100
+ errors.push(...checkManifest({values: resolved, channel: resolved.channel, populate}))
101
+ } catch (e) {
102
+ errors.push(e.message)
103
+ }
104
+ if (errors.length) invalid.set(tarPath, errors)
105
+ }
106
+
107
+ return invalid
108
+ }
109
+
110
+ const reportInvalid = (invalid) => [...invalid].map(([tarPath, errors]) => {
111
+ const file = path.basename(tarPath)
112
+ log.warn(`skipping ${file}: populate rules — ${errors.join('; ')}`)
113
+ return {file, errors}
114
+ })
115
+
72
116
  export const inspect = async (tars, env = process.env, {cwd} = {}) => {
73
117
  const parcels = []
74
118
  const skipped = []
@@ -161,7 +205,7 @@ const deliverParcel = async (tarPath, channelName, pkgName, version, env, {dryRu
161
205
  return res === 'duplicate' ? 'duplicate' : 'ok'
162
206
  }
163
207
 
164
- const deliverPkg = async (pkgName, pkg, tarMap, env, {dryRun, cwd}) => {
208
+ const deliverPkg = async (pkgName, pkg, tarMap, env, {dryRun, cwd, invalid}) => {
165
209
  const entries = []
166
210
  const conflicts = []
167
211
  const skipped = []
@@ -175,13 +219,14 @@ const deliverPkg = async (pkgName, pkg, tarMap, env, {dryRun, cwd}) => {
175
219
  const parcelName = (pkg.parcels || []).find(p => p.includes(`.${channelName}.`))
176
220
  const tarPath = parcelName && tarMap.get(parcelName)
177
221
  if (!tarPath) return 'missing'
222
+ if (invalid.has(tarPath)) return 'invalid'
178
223
 
179
224
  return deliverParcel(tarPath, channelName, pkgName, pkg.version, env, {dryRun, cwd})
180
225
  }))
181
226
 
182
227
  for (let i = 0; i < step.length; i++) {
183
228
  const r = results[i]
184
- if (r === 'skip') skipped.push({channelName: step[i], pkg: pkgName})
229
+ if (r === 'skip' || r === 'invalid') skipped.push({channelName: step[i], pkg: pkgName})
185
230
  else if (r !== 'missing' && r !== 'already') entries.push({channel: step[i], name: pkgName, version: pkg.version})
186
231
  }
187
232
 
@@ -200,7 +245,7 @@ const deliverPkg = async (pkgName, pkg, tarMap, env, {dryRun, cwd}) => {
200
245
  return {entries, conflicts, skipped}
201
246
  }
202
247
 
203
- const deliverDirective = async (directive, tarMap, env, {dryRun, cwd}) => {
248
+ const deliverDirective = async (directive, tarMap, env, {dryRun, cwd, invalid}) => {
204
249
  const entries = []
205
250
  const conflicts = []
206
251
  const skipped = []
@@ -210,7 +255,7 @@ const deliverDirective = async (directive, tarMap, env, {dryRun, cwd}) => {
210
255
  await traverseQueue({queue: directive.queue, prev, cb: async (pkgName) => {
211
256
  const pkg = directive.packages[pkgName]
212
257
  if (!pkg) return
213
- const r = await deliverPkg(pkgName, pkg, tarMap, env, {dryRun, cwd})
258
+ const r = await deliverPkg(pkgName, pkg, tarMap, env, {dryRun, cwd, invalid})
214
259
  entries.push(...r.entries)
215
260
  conflicts.push(...r.conflicts)
216
261
  skipped.push(...r.skipped)
@@ -221,27 +266,39 @@ const deliverDirective = async (directive, tarMap, env, {dryRun, cwd}) => {
221
266
 
222
267
  // --- Main entry point ---
223
268
 
269
+ // Parcels that break the populate rules are not delivered and reported in `invalid`.
270
+ // The rest goes on as usual; failing the run is up to the caller.
224
271
  export const deliver = async (tars, env = process.env, {concurrency = 4, dryRun = false, cwd} = {}) => {
225
272
  const dir = tars.length ? path.dirname(tars[0]) : null
226
273
  const directives = dir ? await scanDirectives(dir) : []
227
274
 
228
- if (!directives.length) return deliverLegacy(tars, env, {concurrency, dryRun, cwd})
275
+ if (!directives.length) {
276
+ const invalid = await checkParcels(tars, env, {cwd})
277
+ const report = reportInvalid(invalid) // logged before delivery: a failing channel must not hide it
278
+ const result = await deliverLegacy(tars.filter(t => !invalid.has(t)), env, {concurrency, dryRun, cwd})
279
+ return {...result, total: tars.length, skipped: result.skipped + invalid.size, invalid: report}
280
+ }
229
281
 
230
282
  const tarMap = new Map(tars.map(t => [path.basename(t), t]))
231
283
  const allEntries = []
232
284
  const allConflicts = []
233
285
  const allSkipped = []
286
+ const allInvalid = []
234
287
 
235
288
  for (const directive of directives) {
236
289
  const gitRoot = cwd || dir
290
+ const listed = new Set([directive.parcels, ...Object.values(directive.packages || {}).map(p => p.parcels)].flat())
291
+ const invalid = await checkParcels([...listed].map(p => tarMap.get(p)).filter(Boolean), env, {cwd: gitRoot})
292
+
237
293
  if (!await tryLock(gitRoot, directive)) {
238
294
  log.info(`directive ${directive.sha.slice(0, 7)} locked, skipping`)
239
295
  continue
240
296
  }
297
+ allInvalid.push(...reportInvalid(invalid))
241
298
 
242
299
  try {
243
300
  await invalidateOrphans(dir, directive)
244
- const {entries, conflicts, skipped} = await deliverDirective(directive, tarMap, env, {dryRun, cwd: gitRoot})
301
+ const {entries, conflicts, skipped} = await deliverDirective(directive, tarMap, env, {dryRun, cwd: gitRoot, invalid})
245
302
  allEntries.push(...entries)
246
303
  allConflicts.push(...conflicts)
247
304
  allSkipped.push(...skipped)
@@ -264,5 +321,6 @@ export const deliver = async (tars, env = process.env, {concurrency = 4, dryRun
264
321
  skipped: allSkipped.length,
265
322
  entries: allEntries,
266
323
  conflicts: allConflicts,
324
+ invalid: allInvalid,
267
325
  }
268
326
  }
@@ -25,7 +25,7 @@ export const readContext = async (filePath) => {
25
25
  return data
26
26
  }
27
27
 
28
- export const buildContext = (packages, queue, sha, {getChannels} = {}) => {
28
+ export const buildContext = (packages, queue, sha, {getChannels, getPopulate, timestamp} = {}) => {
29
29
  const pkgs = {}
30
30
  for (const name of queue) {
31
31
  const pkg = packages[name]
@@ -34,6 +34,7 @@ export const buildContext = (packages, queue, sha, {getChannels} = {}) => {
34
34
  version: pkg.version,
35
35
  tag: pkg.tag,
36
36
  channels: getChannels ? getChannels(pkg) : [],
37
+ populate: getPopulate ? getPopulate(pkg) : undefined,
37
38
  }
38
39
  }
39
40
 
@@ -41,6 +42,7 @@ export const buildContext = (packages, queue, sha, {getChannels} = {}) => {
41
42
  status: 'proceed',
42
43
  sha,
43
44
  sha7: sha.slice(0, 7),
45
+ timestamp, // commit time: directives are delivered oldest first
44
46
  packages: pkgs,
45
47
  }
46
48
  }
@@ -9,7 +9,8 @@ export const publish = memoizeBy(async (pkg, ctx = pkg.ctx) => {
9
9
  const {run = exec, channels: channelNames = [], flags} = ctx
10
10
  const {tars = []} = pkg
11
11
 
12
- await deliver(tars, ctx.env)
12
+ const {invalid} = await deliver(tars, ctx.env)
13
+ if (invalid.length) throw new Error(`populate rules: ${invalid.length} parcel(s) of ${pkg.name} not delivered`)
13
14
 
14
15
  const cmd = channels.cmd
15
16
  if (channelNames.includes('cmd') && cmd?.when(pkg) && (!flags.snapshot || cmd.snapshot))
@@ -19,9 +19,15 @@ export const runDeliver = async ({env, flags}) => {
19
19
 
20
20
  report.setStatus('delivering').log(`parcels: ${tars.length}`)
21
21
  const result = await deliver(tars, env, {dryRun: flags.dryRun, cwd})
22
- report.set('delivery', result).setStatus('success')
22
+ report.set('delivery', result)
23
23
 
24
24
  log.info(`done: ${result.delivered} delivered, ${result.skipped} skipped`)
25
+
26
+ if (result.invalid.length) {
27
+ report.setStatus('failure')
28
+ throw new Error(`populate rules: ${result.invalid.length} parcel(s) not delivered`)
29
+ }
30
+ report.setStatus('success')
25
31
  }
26
32
 
27
33
  const ensureGitRepo = async (env) => {
@@ -11,6 +11,7 @@ import {consumeRebuildSignal} from '../courier/semaphore.js'
11
11
  import {getActiveChannels} from '../courier/index.js'
12
12
  import {writeContext, buildContext} from '../depot/context.js'
13
13
  import {getLatest} from '../depot/generators/meta.js'
14
+ import {mergePopulate} from '../parcel/populate.js'
14
15
 
15
16
  export const runReceive = async ({cwd, env, flags}, ctx) => {
16
17
  const {report, packages, queue, prev} = ctx
@@ -74,6 +75,8 @@ export const runReceive = async ({cwd, env, flags}, ctx) => {
74
75
  const snapshot = !!flags.snapshot
75
76
  const context = buildContext(packages, queue, sha, {
76
77
  getChannels: (pkg) => getActiveChannels(pkg, ctx.channels, snapshot),
78
+ getPopulate: (pkg) => mergePopulate(pkg.config.populate),
79
+ timestamp: Number(await api.git.getCommitTimestamp(cwd)),
77
80
  })
78
81
  await writeContext(cwd, context)
79
82
 
@@ -1,6 +1,6 @@
1
1
  import {glob, path, fs} from 'zx-extra'
2
2
  import {log} from '../log.js'
3
- import {PARCELS_DIR, verifyParcels} from '../parcel/index.js'
3
+ import {PARCELS_DIR, verifyParcels, verifyManifests} from '../parcel/index.js'
4
4
  import {CONTEXT_FILE, readContext} from '../depot/context.js'
5
5
 
6
6
  export const runVerify = async ({cwd, flags}) => {
@@ -23,6 +23,7 @@ export const runVerify = async ({cwd, flags}) => {
23
23
  }
24
24
 
25
25
  const {verified, errors} = verifyParcels(tars, context)
26
+ errors.push(...await verifyManifests(verified, context))
26
27
 
27
28
  if (errors.length) {
28
29
  for (const e of errors) log.error(`verify: ${e}`)
@@ -1,4 +1,5 @@
1
1
  import {asTuple, msgJoin} from '../../util.js'
2
+ import {mergePopulate} from './populate.js'
2
3
 
3
4
  export const sanitizePkgName = (name) => name.replace(/[^a-z0-9-]/ig, '-').replace(/^-+|-+$/g, '')
4
5
 
@@ -88,5 +89,10 @@ export const buildParcels = (pkg, ctx, {
88
89
  repoName, repoHost, originUrl,
89
90
  } = {}) => {
90
91
  const a = {npmTarball, releaseNotes, docsDir, assetsDir, repoName, repoHost, originUrl}
91
- return channelNames.map(n => (entry[n] || defaultEntry(n))(pkg, ctx, a))
92
+ // The courier checks the resolved manifest against these rules right before delivery.
93
+ const populate = mergePopulate(pkg.config?.populate)
94
+ return channelNames.map(n => {
95
+ const parcel = (entry[n] || defaultEntry(n))(pkg, ctx, a)
96
+ return {...parcel, manifest: {...parcel.manifest, populate}}
97
+ })
92
98
  }
@@ -1,4 +1,5 @@
1
1
  export {buildParcels, sanitizePkgName} from './build.js'
2
2
  export {buildDirective, parseDirective, scanDirectives, invalidateOrphans, parcelChannel} from './directive.js'
3
- export {verifyParcels} from './verify.js'
3
+ export {verifyParcels, verifyManifests} from './verify.js'
4
+ export {DEFAULT_POPULATE, mergePopulate, matchSchema, validateValue, checkManifest} from './populate.js'
4
5
  export const PARCELS_DIR = 'parcels'
@@ -0,0 +1,136 @@
1
+ // Populate rules: what manifest fields must look like after `${{VAR}}` substitution.
2
+ // Pack embeds them into every manifest, verify checks they match the context, and the courier
3
+ // checks the resolved manifests against them right before delivery.
4
+ // The default accepts anything, so substitution works as before until the config narrows it.
5
+ //
6
+ // populate: {
7
+ // schemas: {name: schema},
8
+ // channels: {[channel | '*']: {[field | '*']: {schema: name}}},
9
+ // }
10
+ //
11
+ // The schema of a field is picked by best match: channel.field → channel.* → *.field → *.*
12
+
13
+ export const PLACEHOLDER = /\$\{\{(\w+)\}\}/g
14
+
15
+ export const DEFAULT_POPULATE = {
16
+ schemas: {'*': {}},
17
+ channels: {'*': {'*': {schema: '*'}}},
18
+ }
19
+
20
+ const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
21
+
22
+ const own = (obj, key) => isObject(obj) && Object.prototype.hasOwnProperty.call(obj, key)
23
+
24
+ const entriesOf = (obj, at) => {
25
+ if (!isObject(obj)) throw new Error(`${at}: must be an object`)
26
+ if (own(obj, '__proto__')) throw new Error(`${at}: '__proto__' key is not allowed`)
27
+ return Object.entries(obj)
28
+ }
29
+
30
+ const TYPES = new Set(['string', 'secret', 'url'])
31
+
32
+ const assertSchema = (schema, at) => {
33
+ if (!isObject(schema)) throw new Error(`${at}: must be an object`)
34
+ if (schema.type !== undefined && !TYPES.has(schema.type)) throw new Error(`${at}.type: unknown type '${schema.type}'`)
35
+ if (schema.enum !== undefined && !Array.isArray(schema.enum)) throw new Error(`${at}.enum: must be an array`)
36
+ if (schema.pattern !== undefined) {
37
+ if (typeof schema.pattern !== 'string') throw new Error(`${at}.pattern: must be a string`)
38
+ try { new RegExp(schema.pattern) } catch { throw new Error(`${at}.pattern: invalid regexp`) }
39
+ }
40
+ if (schema.type === 'url') for (const part of URL_PARTS) {
41
+ const expected = schema[part]
42
+ if (expected === undefined || typeof expected === 'string') continue
43
+ if (!Array.isArray(expected)) assertSchema(expected, `${at}.${part}`)
44
+ else if (!expected.every(v => typeof v === 'string')) throw new Error(`${at}.${part}: must be strings`)
45
+ }
46
+ }
47
+
48
+ // Throws on malformed rules, so a typo can't silently turn into "accept anything". Returns the rules.
49
+ export const assertPopulate = (populate, at = 'populate') => {
50
+ entriesOf(populate, at)
51
+ const {schemas = {}, channels = {}} = populate
52
+ for (const [name, schema] of entriesOf(schemas, `${at}.schemas`))
53
+ assertSchema(schema, `${at}.schemas.${name}`)
54
+ for (const [channel, fields] of entriesOf(channels, `${at}.channels`))
55
+ for (const [field, rule] of entriesOf(fields, `${at}.channels.${channel}`)) {
56
+ if (!isObject(rule) || typeof rule.schema !== 'string') throw new Error(`${at}.channels.${channel}.${field}: must be {schema: name}`)
57
+ if (!own(schemas, rule.schema) && !own(DEFAULT_POPULATE.schemas, rule.schema)) throw new Error(`${at}.channels.${channel}.${field}: unknown schema '${rule.schema}'`)
58
+ }
59
+
60
+ return populate
61
+ }
62
+
63
+ export const mergePopulate = (populate) => {
64
+ if (populate === undefined || populate === null) populate = {}
65
+ const {schemas, channels} = assertPopulate(populate)
66
+ const merged = JSON.parse(JSON.stringify(DEFAULT_POPULATE))
67
+ Object.assign(merged.schemas, schemas)
68
+ for (const [channel, fields] of Object.entries(channels || {}))
69
+ for (const [field, rule] of Object.entries(fields))
70
+ (merged.channels[channel] ??= {})[field] = {...merged.channels[channel][field], ...rule}
71
+
72
+ return merged
73
+ }
74
+
75
+ export const matchSchema = ({channels}, channel, field) =>
76
+ [[channel, field], [channel, '*'], ['*', field], ['*', '*']]
77
+ .map(([c, f]) => own(channels, c) && own(channels[c], f) ? channels[c][f].schema : undefined)
78
+ .find(v => v !== undefined) ?? '*'
79
+
80
+ // --- schema contract ---
81
+ // {} any value
82
+ // {type: 'string'} + const / enum / pattern (the pattern must match the whole value)
83
+ // {type: 'secret'} non-empty string
84
+ // {type: 'url', ...parts} absolute URL. A part is matched by a string (exact), an array (one of)
85
+ // or a nested schema. Parts not described must be empty, except
86
+ // protocol and hostname, which are not checked unless described.
87
+ // Errors name the field and part, never the actual value.
88
+
89
+ const URL_PARTS = ['protocol', 'username', 'password', 'hostname', 'port', 'pathname', 'search', 'hash']
90
+ const ALWAYS_SET = new Set(['protocol', 'hostname'])
91
+
92
+ const isEmptyPart = (part, value) => value === '' || (part === 'pathname' && value === '/')
93
+
94
+ const matchPart = (actual, expected, at) =>
95
+ typeof expected === 'string'
96
+ ? actual === expected ? [] : [`${at}: expected ${JSON.stringify(expected)}`]
97
+ : Array.isArray(expected)
98
+ ? expected.includes(actual) ? [] : [`${at}: expected one of ${JSON.stringify(expected)}`]
99
+ : validateValue(actual, expected, at)
100
+
101
+ const validateUrl = (value, schema, at) => {
102
+ let url
103
+ try { url = new URL(value) } catch { return [`${at}: must be an absolute URL`] }
104
+
105
+ return URL_PARTS.flatMap(part => schema[part] === undefined
106
+ ? ALWAYS_SET.has(part) || isEmptyPart(part, url[part]) ? [] : [`${at}.${part}: is not allowed`]
107
+ : matchPart(url[part], schema[part], `${at}.${part}`))
108
+ }
109
+
110
+ export const validateValue = (value, schema = {}, at = 'value') => {
111
+ if (!isObject(schema)) return [`${at}: invalid schema`]
112
+ const {type} = schema
113
+
114
+ if (type === 'url') return validateUrl(value, schema, at)
115
+ if (type === 'secret') return typeof value === 'string' && value ? [] : [`${at}: must be a non-empty secret`]
116
+ if (type === 'string' && typeof value !== 'string') return [`${at}: must be a string`]
117
+ if (type !== undefined && type !== 'string') return [`${at}: unknown schema type '${type}'`]
118
+
119
+ const errors = []
120
+ if ('const' in schema && value !== schema.const)
121
+ errors.push(`${at}: expected ${JSON.stringify(schema.const)}`)
122
+ if (schema.enum && !schema.enum.includes(value))
123
+ errors.push(`${at}: expected one of ${JSON.stringify(schema.enum)}`)
124
+ if (schema.pattern && !(typeof value === 'string' && new RegExp(`^(?:${schema.pattern})$`).test(value)))
125
+ errors.push(`${at}: does not match ${schema.pattern}`)
126
+
127
+ return errors
128
+ }
129
+
130
+ // Checks manifest values (resolved or as packed) against the schemas of their fields.
131
+ export const checkManifest = ({values, channel, populate}) =>
132
+ Object.entries(values).flatMap(([field, value]) => {
133
+ if (field === 'populate') return []
134
+ const ref = matchSchema(populate, channel, field)
135
+ return own(populate.schemas, ref) ? validateValue(value, populate.schemas[ref], field) : [`${field}: unknown schema '${ref}'`]
136
+ })
@@ -1,6 +1,19 @@
1
- import {path} from 'zx-extra'
1
+ import {fs, path} from 'zx-extra'
2
2
  import {parcelChannel} from './directive.js'
3
3
  import {sanitizePkgName} from './build.js'
4
+ import {mergePopulate} from './populate.js'
5
+ import {readManifest} from '../tar.js'
6
+
7
+ const MARKERS = new Set(['released', 'skip', 'conflict', 'orphan'])
8
+
9
+ const own = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
10
+
11
+ const isMarker = async (tarPath) =>
12
+ (await fs.stat(tarPath)).size <= 16 && MARKERS.has(await fs.readFile(tarPath, 'utf8'))
13
+
14
+ const findPackage = (name, expected) => Object.entries(expected).find(([pkgName, pkg]) =>
15
+ name.includes(`.${sanitizePkgName(pkgName)}.${pkg.version}.`)
16
+ )
4
17
 
5
18
  export const verifyParcels = (tars, context) => {
6
19
  const {sha7, packages: expected} = context
@@ -26,9 +39,7 @@ export const verifyParcels = (tars, context) => {
26
39
  continue
27
40
  }
28
41
 
29
- const belongsTo = Object.entries(expected).find(([pkgName, pkg]) =>
30
- name.includes(`.${sanitizePkgName(pkgName)}.${pkg.version}.`)
31
- )
42
+ const belongsTo = findPackage(name, expected)
32
43
  if (!belongsTo) {
33
44
  errors.push(`unexpected parcel (no matching package): ${name}`)
34
45
  continue
@@ -45,3 +56,45 @@ export const verifyParcels = (tars, context) => {
45
56
 
46
57
  return {verified, errors}
47
58
  }
59
+
60
+ // Checks that pack kept what the context fixed: the channel, the release tag and the populate
61
+ // rules of every manifest, and the commit time the directives are ordered by. No env, no schemas:
62
+ // the courier checks the resolved manifests against the rules right before delivery.
63
+ export const verifyManifests = async (tars, context) => {
64
+ const errors = []
65
+
66
+ for (const tarPath of tars) {
67
+ const name = path.basename(tarPath)
68
+ const channel = parcelChannel(name)
69
+ if (await isMarker(tarPath)) continue
70
+
71
+ let raw
72
+ try { raw = await readManifest(tarPath) } catch {
73
+ errors.push(`unreadable manifest: ${name}`)
74
+ continue
75
+ }
76
+ if (raw?.channel !== channel) {
77
+ errors.push(`manifest channel does not match the parcel name: ${name}`)
78
+ continue
79
+ }
80
+ if (own(raw, '__proto__')) {
81
+ errors.push(`manifest has a '__proto__' key: ${name}`)
82
+ continue
83
+ }
84
+
85
+ if (channel === 'directive') {
86
+ const fileTs = Number(name.replace(/\.tar$/, '').split('.')[3])
87
+ if (context.timestamp !== undefined && (raw.timestamp !== context.timestamp || fileTs !== context.timestamp))
88
+ errors.push(`directive timestamp differs from the commit time: ${name}`)
89
+ continue
90
+ }
91
+
92
+ const [, pkg] = findPackage(name, context.packages)
93
+ if (own(raw, 'tag') && raw.tag !== pkg.tag)
94
+ errors.push(`manifest tag differs from the context: ${name}`)
95
+ if (JSON.stringify(raw.populate || mergePopulate()) !== JSON.stringify(pkg.populate || mergePopulate()))
96
+ errors.push(`populate rules differ from the context: ${name}`)
97
+ }
98
+
99
+ return errors
100
+ }
@@ -71,3 +71,22 @@ export const unpackTar = async (tarPath, destDir) => {
71
71
  await done
72
72
  return {manifest, dir: destDir}
73
73
  }
74
+
75
+ // Reads manifest.json only, other entries are skipped without touching the disk.
76
+ export const readManifest = async (tarPath) => {
77
+ const extract = tar.extract()
78
+ let raw = null
79
+
80
+ extract.on('entry', (header, stream, cb) => {
81
+ const chunks = []
82
+ stream.on('data', d => header.name === 'manifest.json' && chunks.push(d))
83
+ stream.on('end', () => {
84
+ if (header.name === 'manifest.json') raw = Buffer.concat(chunks).toString('utf8')
85
+ cb()
86
+ })
87
+ stream.resume()
88
+ })
89
+
90
+ await pipeline(fs.createReadStream(tarPath), extract)
91
+ return raw === null ? null : JSON.parse(raw)
92
+ }