nostr-veil 0.30.2 → 0.30.3

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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +173 -20
  3. package/llms-full.txt +108 -22
  4. package/llms.txt +112 -12
  5. package/package.json +2 -2
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TheCryptoDonkey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -96,26 +96,55 @@ npm install nostr-veil
96
96
  ```
97
97
 
98
98
  ```ts
99
- import { createTrustCircle, contributeAssertion, aggregateContributions, verifyProof } from 'nostr-veil'
99
+ import { schnorr } from '@noble/curves/secp256k1.js'
100
+ import { bytesToHex } from '@noble/hashes/utils.js'
101
+ import {
102
+ createTrustCircle, contributeAssertion, aggregateContributions, verifyProof, signEvent, NIP85_KINDS,
103
+ } from 'nostr-veil'
104
+
105
+ // 0. Generate keys. nostr-veil takes 64-char lowercase hex strings everywhere.
106
+ function generateKeypair() {
107
+ const secret = schnorr.utils.randomSecretKey() // Uint8Array (noble v2)
108
+ return { privkey: bytesToHex(secret), pubkey: bytesToHex(schnorr.getPublicKey(secret)) }
109
+ }
110
+ const alice = generateKeypair()
111
+ const bob = generateKeypair()
112
+ const carol = generateKeypair()
113
+ const subject = generateKeypair() // the account being scored; only its pubkey is used
114
+ const aggregator = generateKeypair() // publishes the result; does not need to be a circle member
115
+ const subjectPubkey = subject.pubkey
100
116
 
101
117
  // 1. Define the circle (three anonymous members)
102
- const circle = createTrustCircle([alicePubkey, bobPubkey, carolPubkey])
118
+ const circle = createTrustCircle([alice.pubkey, bob.pubkey, carol.pubkey])
103
119
 
104
120
  // 2. Each member contributes independently -- their identity is hidden inside the ring
105
- const alice = contributeAssertion(circle, subjectPubkey, { followers: 820, rank: 74 }, alicePrivkey, 0)
106
- const bob = contributeAssertion(circle, subjectPubkey, { followers: 900, rank: 80 }, bobPrivkey, 1)
121
+ const aliceContribution = contributeAssertion(
122
+ circle, subjectPubkey, { followers: 820, rank: 74 }, alice.privkey, circle.members.indexOf(alice.pubkey),
123
+ )
124
+ const bobContribution = contributeAssertion(
125
+ circle, subjectPubkey, { followers: 900, rank: 80 }, bob.privkey, circle.members.indexOf(bob.pubkey),
126
+ )
127
+
128
+ // 3. Aggregate into a standard NIP-85 kind 30382 user assertion (an unsigned EventTemplate)
129
+ const assertion = aggregateContributions(circle, subjectPubkey, [aliceContribution, bobContribution])
107
130
 
108
- // 3. Aggregate into a standard NIP-85 kind 30382 user assertion
109
- const assertion = aggregateContributions(circle, subjectPubkey, [alice, bob])
131
+ // 4. The aggregator signs it as an ordinary Nostr event and publishes it
132
+ const signed = signEvent(assertion, aggregator.privkey)
110
133
 
111
- // 4. Any client verifies -- two distinct members agreed, no names attached
112
- const result = verifyProof(assertion)
134
+ // 5. Any client verifies -- two distinct members agreed, no names attached
135
+ const result = verifyProof(signed, { expectedKind: NIP85_KINDS.USER })
113
136
  // { valid: true, circleSize: 3, threshold: 2, distinctSigners: 2, errors: [] }
114
137
  ```
115
138
 
116
- **Important:** `memberIndex` must match the member's position in the *sorted* pubkey array. `createTrustCircle` sorts pubkeys lexicographically -- the index you pass to `contributeAssertion` must reflect that sorted order, not the order you passed to `createTrustCircle`. Use `circle.members.indexOf(myPubkey)` to find the correct index.
139
+ The `@noble/curves` and `@noble/hashes` imports are only used for key generation; nostr-veil already depends on both, so install them directly if your package manager does not hoist them.
140
+
141
+ **Formats.** Pubkeys (circle members, subjects, bundle signers) are 64-char lowercase hex x-only strings. Every `privateKey` argument (`contributeAssertion`, `signEvent`, `createSignedDeploymentBundle`) is a 64-char hex string. A `Uint8Array` is rejected (for example `ValidationError: privateKey must be a string`), so convert noble's byte keys with `bytesToHex` as above.
142
+
143
+ **Important:** `memberIndex` must match the member's position in the *sorted* pubkey array. `createTrustCircle` sorts pubkeys lexicographically -- the index you pass to `contributeAssertion` must reflect that sorted order, not the order you passed to `createTrustCircle`. Always use `circle.members.indexOf(myPubkey)`. A wrong index throws `Private key does not match ring member at signerIndex`.
117
144
 
118
- The resulting `assertion` is a plain `EventTemplate` you sign and publish like any other Nostr event.
145
+ **Who signs what.** The ring signatures live in the `veil-sig` tags. The outer Nostr signature from `signEvent` is made by the aggregator, the party that collects the contributions and publishes the event. Any Nostr key will do and it need not belong to a circle member. `verifyProof` checks the ring proofs only; use `verifySignedEvent(event)` to check the outer id and signature after fetching an event from an untrusted relay.
146
+
147
+ Passing `expectedKind` matters because v1 proofs are not bound to the event kind; see [Proof v2](#proof-v2).
119
148
 
120
149
  ---
121
150
 
@@ -171,6 +200,7 @@ The resulting `assertion` is a plain `EventTemplate` you sign and publish like a
171
200
  | `createDeploymentPolicy(profile, options)` | Build a fail-closed deployment policy with accepted circles, expected subject, metric bounds, freshness, threshold, signature requirements, and optional companion evidence requirements |
172
201
  | `verifyDeploymentPolicy(events, policy, options?)` | Verify a profile plus deployment-specific controls and supplied companion evidence before acting on a score |
173
202
  | `createSignedDeploymentBundle(policy, options)` | Sign a deployment policy and its manifests as trusted operator configuration |
203
+ | `verifySignedDeploymentBundle(bundle, options?)` | Verify only the bundle: shape, expiry and future-`issuedAt` against `now`, the signer's BIP-340 signature, and `trustedPublishers`. Does not look at any events |
174
204
  | `verifyDeploymentBundle(events, bundle, options?)` | Verify a signed bundle from trusted publishers, then verify the bundled deployment policy |
175
205
  | `verifyProductionDeployment(events, bundle, options?)` | One-call production gate that also requires an expiring bundle and signed relay-fetched events by default |
176
206
  | `createProductionDecisionReport(result)`, `verifyProductionDeploymentReport(events, bundle, options?)` | Produce an audit/UI-ready decision report with recommended action, issue remediation, and control status |
@@ -186,7 +216,7 @@ The resulting `assertion` is a plain `EventTemplate` you sign and publish like a
186
216
  | `canonicalRelaySubject`, `canonicalServiceSubject`, `canonicalNip05Subject`, `canonicalDomainSubject`, `canonicalLnurlpSubject`, `canonicalNip96Subject`, `canonicalNpmPackageSubject`, `canonicalPackageDigestSubject`, `canonicalGitRepositorySubject`, `canonicalGithubRepositorySubject`, `canonicalMaintainerSubject` | Canonical subject helpers for common real-world identifiers |
187
217
  | `canonicalPubkeySubject`, `canonicalEventSubject`, `canonicalAddressSubject` | Canonical subject helpers for Nostr-native subjects |
188
218
 
189
- Freshness checks in `verifyCircleManifest`, `verifyDeploymentBundle`,
219
+ Freshness checks in `verifyCircleManifest`, `verifySignedDeploymentBundle`, `verifyDeploymentBundle`,
190
220
  `verifyAdmissionPresentation`, and the verifiers built on them are fail closed:
191
221
  expiry and future-`issuedAt` checks run against the current time unless you
192
222
  pass an explicit `now` (intended for tests and historical verification).
@@ -210,14 +240,130 @@ can fetch or normalise the observation for you, and the resolver helpers when
210
240
  your application already has registry, service, or list observations from its
211
241
  own infrastructure. Avoid hand-written `pass` records in production.
212
242
 
213
- ### Signing utility (root export)
243
+ ### Root export (`nostr-veil`) -- everything, plus signing
244
+
245
+ The root entry point re-exports all of `nostr-veil/nip85`, `nostr-veil/proof` and `nostr-veil/profiles`, and adds the signing helpers below. One `import ... from 'nostr-veil'` reaches every export in this reference; the subpath exports exist only so you can import a single layer. The signing helpers are available from the root only.
214
246
 
215
247
  | Export | Description |
216
248
  |--------|-------------|
217
- | `signEvent(template, privateKey)` | Sign an unsigned event template with BIP-340 Schnorr -- returns a complete `SignedEvent` |
249
+ | `signEvent(template, privateKey)` | Sign an unsigned event template with BIP-340 Schnorr (`privateKey` is a 64-char hex string) -- returns a complete `SignedEvent` |
218
250
  | `verifySignedEvent(event)` | Verify a signed Nostr event id and BIP-340 signature after fetching from an untrusted relay |
219
251
  | `computeEventId(event)` | Compute the NIP-01 event ID (SHA-256 of canonical serialisation) |
220
252
 
253
+ ### Options and types
254
+
255
+ **Metrics.** Contributions take `Record<string, number>`. Values must be finite (`NaN` and `Infinity` throw `Metric "<key>" must be a finite number`); integers are not required, and the published tag is `String(value)`. Metric names must not be `d`, `p`, `e`, `a` or `k` or start with `veil-`, because those tag names are reserved and verification then fails with `Missing metric "<name>" derived from signed contributions`. By default `verifyProof` accepts at most 128 metrics per signed message and names up to 64 characters. The `nostr-veil/nip85` builders take typed metrics instead (all fields optional): `UserMetrics` (kind 30382: `followers`, `rank`, `first_created_at`, `post_cnt`, `reply_cnt`, `reactions_cnt`, `zap_amt_recd`, `zap_amt_sent`, `zap_cnt_recd`, `zap_cnt_sent`, `zap_avg_amt_day_recd`, `zap_avg_amt_day_sent`, `reports_cnt_recd`, `reports_cnt_sent`, `t` (string), `active_hours_start`, `active_hours_end`), `EventMetrics` (kinds 30383 and 30384: `rank`, `comment_cnt`, `quote_cnt`, `repost_cnt`, `reaction_cnt`, `zap_cnt`, `zap_amount`) and `IdentifierMetrics` (kind 30385: `rank`, `comment_cnt`, `reaction_cnt`).
256
+
257
+ **Aggregation options.** The `options` argument of `aggregateContributions` and the typed `aggregate*Contributions` helpers is either a bare function `(values: number[]) => number` or an object:
258
+
259
+ ```ts
260
+ {
261
+ aggregate?: 'median' | 'mean' | 'sum' | 'min' | 'max' // built-in, default 'median'
262
+ aggregateFn?: (values: number[]) => number // custom; ignored if `aggregate` is set
263
+ proofVersion?: 'v1' | 'v2' // default 'v1'
264
+ kind?: number // aggregateContributions only; legacy, default 30382
265
+ }
266
+ ```
267
+
268
+ `median` and `mean` round to an integer; `sum`, `min` and `max` do not. A non-finite result throws, and an unknown `aggregate` name throws `Unknown aggregate function: <name>`. A built-in name is written to the `veil-agg` tag and `verifyProof` reads it from there, so verifying a summed tally needs no option: `aggregateContributions(circle, subject, contributions, { aggregate: 'sum' })` verifies with a bare `verifyProof(event)`. A custom function is written as `veil-agg: custom` and must be passed to the verifier too (`verifyProof(event, { aggregateFn })` or a bare function), otherwise it fails with `veil-agg is "custom": pass the aggregate function via options to verify the metric tags`.
269
+
270
+ **`verifyProof(event, options?)`.** `options` is a bare aggregate function or an object `{ aggregateFn?, expectedKind?, requireProofVersion?, limits? }`:
271
+
272
+ | Option | Type | Meaning |
273
+ |--------|------|---------|
274
+ | `aggregateFn` | `(values: number[]) => number` | Needed only when `veil-agg` is `custom` |
275
+ | `expectedKind` | `number` | Reject events of any other NIP-85 kind. Recommended for v1 proofs, which are not kind-bound |
276
+ | `requireProofVersion` | `'v1' \| 'v2'` | Reject signatures of the other proof version |
277
+ | `limits` | `Partial<VerifyLimits>` | Override `DEFAULT_VERIFY_LIMITS`: `maxRingSize` 1000, `maxSigPayloadBytes` 128000, `maxSignedMessageBytes` 16384, `maxMetricCount` 128, `maxMetricNameLength` 64 |
278
+
279
+ It returns `{ valid, circleSize, threshold, distinctSigners, errors }`.
280
+
281
+ **`contributeAssertion` options and `canonicalMessageV2`.** `contributeAssertion(..., options?)` takes `{ proofVersion?: 'v1' | 'v2', kind?: number, subjectTag?: 'p' | 'e' | 'a' | 'k', subjectTagValue?: string }`; for v2 the defaults are kind 30382, tag `p` and the subject itself. The typed helpers (`contributeEventAssertion`, `contributeAddressableAssertion`, `contributeIdentifierAssertion`) take only `{ proofVersion?: 'v1' | 'v2' }` and fill in the kind and tag. `canonicalMessageV2(circleId, subject, metrics, context)` takes `context` as `{ kind, subjectTag, subjectTagValue }`, all required: `kind` a non-negative safe integer, `subjectTag` one of `p`, `e`, `a`, `k`, and `subjectTagValue` a non-empty string.
282
+
283
+ **NIP-85 parse results.** `parseAssertion(event)` returns `{ kind: number, subject: string, metrics: Record<string, string | number> }`: `subject` is the `d` tag value (empty string if absent) and `metrics` holds every tag except `d`, `p`, `e`, `a`, `k` and `veil-*`; the values are the raw tag strings. `parseProviderDeclaration(event)` returns `ParsedProvider[]`, each `{ kind: number, metric: string, servicePubkey: string, relayHint: string }` (the same shape as the `ProviderEntry` passed to `buildProviderDeclaration`). With a `decryptFn: (ciphertext: string) => Promise<string>` it returns a `Promise<ParsedProvider[]>`.
284
+
285
+ **Profiles options.** All timestamps are Unix seconds. `now` defaults to the current time wherever it appears.
286
+
287
+ | Function | Options |
288
+ |----------|---------|
289
+ | `createCircleManifest(options)` | Required: `issuedAt`, `members`, `name`, `profileIds`, `purpose`. Optional: `expiresAt`, `status` (`'active' \| 'revoked' \| 'superseded'`), `supersedes`, `revokedCircleIds`, `contact`, `evidenceProcess`, `policyUri` |
290
+ | `verifyCircleManifest(manifest, options?)` | `allowSuperseded`, `now`, `profileId`, `revokedCircleIds` |
291
+ | `createDeploymentPolicy(profile, options)` | Required: `expectedSubject`, plus at least one active circle from `acceptedCircleIds` or `circleManifests`. Optional: `expectedSubjectTagValue`, `id` (default: the profile id), `maxAgeSeconds` and `minDistinctSigners` (default: the profile's), `metricPolicies` (`{ [metric]: { required?, min?, max?, integer? } }`), `rejectUnknownMetrics` (default `false`), `requireNostrSignature` (default `false`), `companionEvidence`, `allowSupersededCircleIds` (default `false`), `now` |
292
+ | `createSignedDeploymentBundle(policy, options)` | Required: `id`, `issuedAt`, `privateKey` (hex). Optional: `expiresAt` (must be greater than `issuedAt`). Returns a frozen bundle carrying the `signer` pubkey and `signature` |
293
+ | `verifyUseCaseProfile(events, profile, options?)` | `acceptedCircleIds`, `aggregateFn`, `expectedSubject`, `expectedSubjectTagValue`, `maxAgeSeconds`, `minDistinctSigners`, `now`, `requireKnownCircle` (fails when no accepted circle is supplied unless set to `false`) |
294
+ | `verifyDeploymentPolicy(events, policy, options?)` | `aggregateFn`, `companionEvidence` (the supplied `CompanionEvidence[]`), `now` |
295
+ | `verifySignedDeploymentBundle(bundle, options?)` | `now`, `trustedPublishers` |
296
+ | `verifyDeploymentBundle(events, bundle, options?)` | The `verifyDeploymentPolicy` options plus `trustedPublishers` |
297
+ | `verifyProductionDeployment(events, bundle, options?)` | The `verifyDeploymentBundle` options plus `requireBundleExpiry` and `requireSignedEvents`, both `true` unless set to `false` |
298
+
299
+ `trustedPublishers` is effectively required for bundle verification: without at least one valid pubkey it fails with `no trusted bundle publishers configured`. `verifyProductionDeployment` returns the bundle and policy results plus `{ decision: 'accept' | 'reject', valid, errors, issues }`.
300
+
301
+ ### Profiles example
302
+
303
+ A production verifier pins the operator's publisher pubkey, loads a signed deployment bundle, and checks fetched assertions against it. This continues from the quick start (`alice`, `bob`, `carol`, `circle`, `subjectPubkey`, `aggregator`). The built-in `USER_REPUTATION_ABUSE_REPORTING_PROFILE` (id `user-reputation-abuse-reporting`) requires proof v2, at least three distinct signers, and an assertion no older than 300 seconds, so the contributions below are v2 and all three members sign.
304
+
305
+ ```ts
306
+ import {
307
+ USER_REPUTATION_ABUSE_REPORTING_PROFILE,
308
+ createDeploymentPolicy,
309
+ createSignedDeploymentBundle,
310
+ verifyProductionDeployment,
311
+ } from 'nostr-veil/profiles'
312
+
313
+ const operator = generateKeypair() // the deployment operator, separate from circle members
314
+
315
+ // Three members contribute with proof v2, then the aggregator signs and publishes
316
+ const contributions = [alice, bob, carol].map(member => contributeAssertion(
317
+ circle, subjectPubkey, { rank: 80 }, member.privkey, circle.members.indexOf(member.pubkey), { proofVersion: 'v2' },
318
+ ))
319
+ const event = signEvent(
320
+ aggregateContributions(circle, subjectPubkey, contributions, { proofVersion: 'v2' }),
321
+ aggregator.privkey,
322
+ )
323
+
324
+ // The operator builds a policy and signs it as a bundle
325
+ const policy = createDeploymentPolicy(USER_REPUTATION_ABUSE_REPORTING_PROFILE, {
326
+ acceptedCircleIds: [circle.circleId],
327
+ expectedSubject: subjectPubkey,
328
+ requireNostrSignature: true, // verifyProductionDeployment rejects a policy without this
329
+ })
330
+ const now = Math.floor(Date.now() / 1000)
331
+ const bundle = createSignedDeploymentBundle(policy, {
332
+ id: 'abuse-reporting-2026-01',
333
+ issuedAt: now,
334
+ expiresAt: now + 24 * 60 * 60, // verifyProductionDeployment rejects a bundle without expiry
335
+ privateKey: operator.privkey,
336
+ })
337
+
338
+ // The verifier pins the operator's pubkey and checks the fetched events
339
+ const verdict = verifyProductionDeployment([event], bundle, { trustedPublishers: [operator.pubkey] })
340
+ // verdict.decision === 'accept', verdict.valid === true, verdict.errors === []
341
+ ```
342
+
343
+ A bundle signed by any other key fails with the issue code `bundle.signer_untrusted`. For the other built-in profiles, companion evidence and the report helpers, see [examples/production-recipes.ts](./examples/production-recipes.ts), which runs six production-shaped gates (`npm run test:production-recipes`).
344
+
345
+ ---
346
+
347
+ ## CLI
348
+
349
+ Installing the package puts a `nostr-veil` binary on your path (`npx nostr-veil --help` also works).
350
+
351
+ ```bash
352
+ nostr-veil assert user <pubkey> [--json '<metrics>']
353
+ nostr-veil assert event <event-id> [--json '<metrics>']
354
+ nostr-veil assert address <address> [--json '<metrics>']
355
+ nostr-veil assert identifier <id> <k-tag> [--json '<metrics>']
356
+ nostr-veil provider-declare [--json '<entries>']
357
+ nostr-veil verify '<event-json>' [--kind <n>]
358
+ nostr-veil --help
359
+ ```
360
+
361
+ - `assert` builds a plain NIP-85 assertion (kind 30382, 30383, 30384 or 30385 respectively) and signs it with one key. It does not make ring signatures; use the library for that. `--json` takes a JSON object of metrics, for example `--json '{"rank":74}'`. Without it the metrics are empty.
362
+ - `provider-declare` builds and signs a kind 10040 provider declaration. `--json` takes a JSON array of `{ kind, metric, servicePubkey, relayHint }` entries.
363
+ - `assert` and `provider-declare` read the signing key from `NOSTR_SECRET_KEY` (64-char hex) or from the file named by `NOSTR_SECRET_KEY_FILE`, which takes precedence. They print the signed event as JSON on stdout, ready to pipe to a relay publisher.
364
+ - `verify` needs no key. `<event-json>` is the event itself as an inline JSON string, not a file path, and it must be the first argument after `verify` (for a file use `nostr-veil verify "$(cat event.json)" --kind 30382`). The event must be a JSON object with a `tags` array. `--kind <n>` takes a non-negative integer and applies the `expectedKind` check; it is recommended for v1 proofs.
365
+ - `verify` prints the `verifyProof` result as JSON. It exits 0 even when `valid` is `false`, and exits 1 only for bad arguments or unparseable JSON, so read the `valid` field rather than the exit code.
366
+
221
367
  ---
222
368
 
223
369
  ## How it works
@@ -228,7 +374,7 @@ The published event carries extra tags on top of the standard NIP-85 format:
228
374
 
229
375
  - `veil-ring` -- the full list of circle members (the group who could have contributed)
230
376
  - `veil-threshold` -- how many members actually contributed vs. total circle size
231
- - `veil-agg` -- which aggregate function produced the metric tags (median by default)
377
+ - `veil-agg` -- which aggregate function produced the metric tags: `median` (default), `mean`, `sum`, `min`, `max`, or `custom`
232
378
  - `veil-sig` (one per contributor) -- the ring signature and a duplicate-detection token
233
379
  - `veil-version` -- present only for opt-in proof v2 events
234
380
  - `veil-scope` -- present only for a federated circle; see [Cross-circle deduplication](#cross-circle-deduplication)
@@ -242,7 +388,7 @@ A verifier calls `verifyProof`, which:
242
388
 
243
389
  At no point does verification require knowing which member produced which signature. The group membership is public. The identities of the actual contributors are not. The signed metric values are public inside the proof, so nostr-veil hides contributor identity, not the fact that an anonymous contributor submitted a particular score.
244
390
 
245
- By default, verification expects the same median aggregation used by `aggregateContributions`. If you pass a custom `aggregateFn` to `aggregateContributions`, pass the same function to `verifyProof`.
391
+ Aggregation is median by default. Pass `{ aggregate: 'mean' | 'sum' | 'min' | 'max' }` to `aggregateContributions` (or any typed `aggregate*Contributions` helper) to choose another built-in. The name is recorded in the `veil-agg` tag and `verifyProof` reads it from there, so a summed tally verifies with a bare `verifyProof(event)`. Only a custom function (`{ aggregateFn }`, recorded as `veil-agg: custom`) must be passed to `verifyProof` as well, otherwise verification fails. See [Options and types](#options-and-types).
246
392
 
247
393
  ### Proof v2
248
394
 
@@ -250,20 +396,26 @@ The original proof format remains the default. It signs the circle ID, the `d`-t
250
396
 
251
397
  Proof v2 is additive and opt-in. It signs the same data plus the NIP-85 assertion kind and the subject hint tag/value (`p`, `e`, `a`, or `k`), and derives the key image from that semantic context. That prevents a valid contribution for one assertion class being replayed as another when a subject string is reused.
252
398
 
399
+ This continues from the [Quick start](#quick-start): `alice` and `circle` are defined there. `eventId` is the 64-char lowercase hex id of the Nostr event being assessed; the typed helpers throw if it is not.
400
+
253
401
  ```ts
254
402
  import { contributeEventAssertion, aggregateEventContributions, verifyProof } from 'nostr-veil'
255
403
 
404
+ const eventId = '0123456789abcdef'.repeat(4) // placeholder: use the real event id
405
+
256
406
  const contribution = contributeEventAssertion(
257
407
  circle,
258
408
  eventId,
259
409
  { rank: 90 },
260
- alicePrivkey,
261
- circle.members.indexOf(alicePubkey),
410
+ alice.privkey,
411
+ circle.members.indexOf(alice.pubkey),
262
412
  { proofVersion: 'v2' },
263
413
  )
264
414
 
265
- const assertion = aggregateEventContributions(circle, eventId, [contribution], { proofVersion: 'v2' })
266
- const result = verifyProof(assertion, { requireProofVersion: 'v2' })
415
+ // One contribution keeps the example short; a real workflow collects several.
416
+ const eventAssertion = aggregateEventContributions(circle, eventId, [contribution], { proofVersion: 'v2' })
417
+ const eventResult = verifyProof(eventAssertion, { requireProofVersion: 'v2' })
418
+ // { valid: true, circleSize: 3, threshold: 1, distinctSigners: 1, errors: [] }
267
419
  ```
268
420
 
269
421
  Old v1 events still verify without changes. Use `requireProofVersion: 'v2'` only when your application policy wants to reject legacy proofs for that workflow.
@@ -275,10 +427,11 @@ example, a user assertion re-tagged as an event assertion) and still pass bare
275
427
  fails unless the event carries the kind your workflow expects:
276
428
 
277
429
  ```ts
430
+ // `assertion` is the v1 user assertion from the Quick start
278
431
  const result = verifyProof(assertion, { expectedKind: NIP85_KINDS.USER })
279
432
  ```
280
433
 
281
- The CLI equivalent is `nostr-veil verify <event-json> --kind 30382`.
434
+ The CLI equivalent is `nostr-veil verify '<event-json>' --kind 30382`; see [CLI](#cli).
282
435
 
283
436
  ---
284
437
 
package/llms-full.txt CHANGED
@@ -549,14 +549,14 @@ Produce an anonymous ring-signed contribution to a trust circle assertion.
549
549
  - **`circle`** `TrustCircle` — Created via `createTrustCircle`
550
550
  - **`subject`** `string` — The d-tag value the assertion is about
551
551
  - **`metrics`** `Record<string, number>` — Metric key-value pairs
552
- - **`privateKey`** `string` — 32-byte hex private key of the contributing member
553
- - **`memberIndex`** `number` — 0-based index in `circle.members` (sorted order)
552
+ - **`privateKey`** `string` -- 64-char hex private key of the contributing member (a `Uint8Array` is rejected with `privateKey must be a string`)
553
+ - **`memberIndex`** `number` -- 0-based index in `circle.members` (sorted order); always use `circle.members.indexOf(memberPubkey)`
554
554
  - **`options`** `ProofContext | undefined` — Omit for v1; pass `{ proofVersion: 'v2', kind, subjectTag, subjectTagValue }` for semantic binding
555
555
  - **Returns** `Contribution` with ring signature, duplicate-detection token, and metrics
556
- - **Throws** if `memberIndex` is out of range or the private key doesn't match the expected public key
556
+ - **Throws** if `memberIndex` is out of range (`Signer index out of range`) or the private key doesn't match the pubkey at that index (`Private key does not match ring member at signerIndex`)
557
557
 
558
558
  ```ts
559
- const contrib = contributeAssertion(circle, subjectPubkey, { rank: 85 }, alicePrivkey, 0)
559
+ const contrib = contributeAssertion(circle, subjectPubkey, { rank: 85 }, alicePrivkey, circle.members.indexOf(alicePubkey))
560
560
  ```
561
561
 
562
562
  Typed contribution helpers set the v2 context for non-user assertion kinds:
@@ -576,7 +576,7 @@ Validates all ring signatures and checks for duplicate contributors before aggre
576
576
  - **`circle`** `TrustCircle` — The trust circle the contributions belong to
577
577
  - **`subject`** `string` — The d-tag value (must match what contributors signed)
578
578
  - **`contributions`** `Contribution[]` — Array of contributions from circle members
579
- - **`options`** `AggregateFn | { aggregateFn?: AggregateFn; aggregate?: AggregateName; kind?: number; proofVersion?: ProofVersion }` — Pass a function for custom aggregation (default: median), or an options object with a built-in aggregate name. The legacy `kind` option is kept for compatibility and still emits a user-style `p` subject tag. `proofVersion: 'v2'` requires matching v2 contributions.
579
+ - **`options`** `AggregateFn | { aggregateFn?: AggregateFn; aggregate?: AggregateName; kind?: number; proofVersion?: ProofVersion }` -- Pass a function for custom aggregation (default: median), or an options object with a built-in aggregate name (`'median' | 'mean' | 'sum' | 'min' | 'max'`; `aggregate` wins over `aggregateFn`). A built-in name is recorded in the `veil-agg` tag and `verifyProof` reads it from there; a custom function is recorded as `veil-agg: custom` and must also be passed to `verifyProof`. `median` and `mean` round to integers; `sum`, `min` and `max` do not. The legacy `kind` option is kept for compatibility and still emits a user-style `p` subject tag. `proofVersion: 'v2'` requires matching v2 contributions.
580
580
  - **Returns** `EventTemplate` with `veil-ring`, `veil-threshold`, and `veil-sig` tags
581
581
  - **Throws** if any ring signature is invalid or duplicate contributors are detected
582
582
 
@@ -604,7 +604,7 @@ kind-specific subject tags and can opt into proof v2:
604
604
  Verify all ring signatures in a veil-enhanced NIP-85 event.
605
605
 
606
606
  - **`event`** `{ kind, tags, content }` — A Nostr event containing proof tags
607
- - **`options`** `AggregateFn | { aggregateFn?: AggregateFn; requireProofVersion?: ProofVersion; limits?: Partial<VerifyLimits> }` — Custom aggregation, proof-version policy, or verifier size limits
607
+ - **`options`** `AggregateFn | { aggregateFn?: AggregateFn; expectedKind?: number; requireProofVersion?: ProofVersion; limits?: Partial<VerifyLimits> }` -- `aggregateFn` is needed only when `veil-agg` is `custom` (built-in names are read from the tag); `expectedKind` rejects events of any other NIP-85 kind and is recommended for v1 proofs, which are not kind-bound; `requireProofVersion` rejects the other proof version; `limits` overrides `DEFAULT_VERIFY_LIMITS` (`maxRingSize` 1000, `maxSigPayloadBytes` 128000, `maxSignedMessageBytes` 16384, `maxMetricCount` 128, `maxMetricNameLength` 64)
608
608
  - **Returns** `ProofVerification` with `valid`, `circleSize`, `threshold`, `distinctSigners`, `errors`
609
609
 
610
610
  ```ts
@@ -716,6 +716,12 @@ output into `verifyDeploymentPolicy()`, `verifyDeploymentBundle()`, or
716
716
  Sign a deployment policy and its manifests as trusted operator configuration.
717
717
  Use this when policy material is distributed separately from the verifier.
718
718
 
719
+ #### `verifySignedDeploymentBundle(bundle, options?) → SignedDeploymentBundleVerification`
720
+
721
+ Verify only the bundle: shape, expiry and future-`issuedAt` against `options.now` (default: the current time, fail closed), the signer's BIP-340 signature, and `options.trustedPublishers`. It does not look at any events. `verifyDeploymentBundle` calls it first.
722
+
723
+ ---
724
+
719
725
  #### `verifyDeploymentBundle(events, bundle, options) → DeploymentBundleVerification`
720
726
 
721
727
  Verify that the bundle signature is valid, the signer pubkey is pinned in
@@ -817,7 +823,9 @@ verification so every contributor scores the same identifier.
817
823
 
818
824
  ---
819
825
 
820
- ### `nostr-veil` root export -- Signing Utilities
826
+ ### `nostr-veil` root export -- everything, plus signing
827
+
828
+ The root entry point re-exports all of `nostr-veil/nip85`, `nostr-veil/proof` and `nostr-veil/profiles`, and adds the signing utilities below, which exist only at the root. A `privateKey` is always a 64-char hex string.
821
829
 
822
830
  #### `computeEventId(event) → string`
823
831
 
@@ -837,7 +845,7 @@ const id = computeEventId({ pubkey, created_at, kind: 1, tags: [], content: 'hel
837
845
  Sign an unsigned event template with a Schnorr private key (BIP-340).
838
846
 
839
847
  - **`template`** `UnsignedEvent` — `kind`, `tags`, `content`, optional `created_at`
840
- - **`privateKey`** `string` — 32-byte hex Schnorr private key (64 chars)
848
+ - **`privateKey`** `string` -- 32-byte hex Schnorr private key (64 chars); a `Uint8Array` is rejected
841
849
  - **Returns** `SignedEvent` with `id`, `pubkey`, `created_at`, `kind`, `tags`, `content`, `sig`
842
850
 
843
851
  ```ts
@@ -851,26 +859,104 @@ const event = signEvent(tmpl, providerPrivkey)
851
859
  ## Complete Quick-Start Example
852
860
 
853
861
  ```ts
854
- import { createTrustCircle, contributeAssertion, aggregateContributions, verifyProof } from 'nostr-veil/proof'
855
- import { signEvent } from 'nostr-veil'
862
+ import { schnorr } from '@noble/curves/secp256k1.js'
863
+ import { bytesToHex } from '@noble/hashes/utils.js'
864
+ import {
865
+ createTrustCircle, contributeAssertion, aggregateContributions, verifyProof, signEvent, NIP85_KINDS,
866
+ } from 'nostr-veil'
856
867
 
857
- // 1. Define a circle of three anonymous members
858
- const circle = createTrustCircle([alicePubkey, bobPubkey, carolPubkey])
868
+ // 0. Generate keys. nostr-veil takes 64-char lowercase hex strings everywhere.
869
+ function generateKeypair() {
870
+ const secret = schnorr.utils.randomSecretKey() // Uint8Array (noble v2)
871
+ return { privkey: bytesToHex(secret), pubkey: bytesToHex(schnorr.getPublicKey(secret)) }
872
+ }
873
+ const alice = generateKeypair()
874
+ const bob = generateKeypair()
875
+ const carol = generateKeypair()
876
+ const subject = generateKeypair() // the account being scored; only its pubkey is used
877
+ const aggregator = generateKeypair() // publishes the result; does not need to be a circle member
878
+ const subjectPubkey = subject.pubkey
879
+
880
+ // 1. Define the circle (three anonymous members)
881
+ const circle = createTrustCircle([alice.pubkey, bob.pubkey, carol.pubkey])
882
+
883
+ // 2. Each member contributes independently -- their identity is hidden inside the ring
884
+ const aliceContribution = contributeAssertion(
885
+ circle, subjectPubkey, { followers: 820, rank: 74 }, alice.privkey, circle.members.indexOf(alice.pubkey),
886
+ )
887
+ const bobContribution = contributeAssertion(
888
+ circle, subjectPubkey, { followers: 900, rank: 80 }, bob.privkey, circle.members.indexOf(bob.pubkey),
889
+ )
890
+
891
+ // 3. Aggregate into a standard NIP-85 kind 30382 user assertion (an unsigned EventTemplate)
892
+ const assertion = aggregateContributions(circle, subjectPubkey, [aliceContribution, bobContribution])
893
+
894
+ // 4. The aggregator signs it as an ordinary Nostr event and publishes it
895
+ const signed = signEvent(assertion, aggregator.privkey)
896
+
897
+ // 5. Any client verifies -- two distinct members agreed, no names attached
898
+ const result = verifyProof(signed, { expectedKind: NIP85_KINDS.USER })
899
+ // { valid: true, circleSize: 3, threshold: 2, distinctSigners: 2, errors: [] }
900
+ ```
859
901
 
860
- // 2. Each member contributes independently — identity hidden inside the ring
861
- const alice = contributeAssertion(circle, subjectPubkey, { followers: 820, rank: 74 }, alicePrivkey, 0)
862
- const bob = contributeAssertion(circle, subjectPubkey, { followers: 900, rank: 80 }, bobPrivkey, 1)
902
+ Formats: pubkeys are 64-char lowercase hex x-only strings and every `privateKey` argument is a 64-char hex string. `memberIndex` must come from `circle.members.indexOf(pubkey)`. The aggregator is whoever collects the contributions and publishes the event; it need not be a circle member. `verifyProof` does not check the outer Nostr signature, so call `verifySignedEvent(event)` on events fetched from untrusted relays. Pass `expectedKind` because v1 proofs are not kind-bound.
863
903
 
864
- // 3. Aggregate into a standard NIP-85 kind 30382 event (median of contributions)
865
- const tmpl = aggregateContributions(circle, subjectPubkey, [alice, bob])
866
- const event = signEvent(tmpl, aggregatorPrivkey)
867
- await relay.publish(event)
904
+ ## Profiles Example
868
905
 
869
- // 4. Verify: two distinct signers agreed, no names attached
870
- const result = verifyProof(event)
871
- // { valid: true, circleSize: 3, threshold: 2, distinctSigners: 2, errors: [] }
906
+ Continuing from the quick start. The built-in `USER_REPUTATION_ABUSE_REPORTING_PROFILE` needs proof v2, at least three distinct signers and an assertion no older than 300 seconds.
907
+
908
+ ```ts
909
+ import {
910
+ USER_REPUTATION_ABUSE_REPORTING_PROFILE,
911
+ createDeploymentPolicy,
912
+ createSignedDeploymentBundle,
913
+ verifyProductionDeployment,
914
+ } from 'nostr-veil/profiles'
915
+
916
+ const operator = generateKeypair() // deployment operator, separate from circle members
917
+ const contributions = [alice, bob, carol].map(member => contributeAssertion(
918
+ circle, subjectPubkey, { rank: 80 }, member.privkey, circle.members.indexOf(member.pubkey), { proofVersion: 'v2' },
919
+ ))
920
+ const event = signEvent(
921
+ aggregateContributions(circle, subjectPubkey, contributions, { proofVersion: 'v2' }),
922
+ aggregator.privkey,
923
+ )
924
+
925
+ const policy = createDeploymentPolicy(USER_REPUTATION_ABUSE_REPORTING_PROFILE, {
926
+ acceptedCircleIds: [circle.circleId],
927
+ expectedSubject: subjectPubkey,
928
+ requireNostrSignature: true, // verifyProductionDeployment rejects a policy without this
929
+ })
930
+ const now = Math.floor(Date.now() / 1000)
931
+ const bundle = createSignedDeploymentBundle(policy, {
932
+ id: 'abuse-reporting-2026-01',
933
+ issuedAt: now,
934
+ expiresAt: now + 24 * 60 * 60, // verifyProductionDeployment rejects a bundle without expiry
935
+ privateKey: operator.privkey,
936
+ })
937
+
938
+ const verdict = verifyProductionDeployment([event], bundle, { trustedPublishers: [operator.pubkey] })
939
+ // verdict.decision === 'accept'; a bundle signed by another key fails with `bundle.signer_untrusted`
872
940
  ```
873
941
 
942
+ See `examples/production-recipes.ts` in the repository for six production-shaped gates with companion evidence.
943
+
944
+ ## CLI
945
+
946
+ The package installs a `nostr-veil` binary:
947
+
948
+ ```bash
949
+ nostr-veil assert user <pubkey> [--json '<metrics>']
950
+ nostr-veil assert event <event-id> [--json '<metrics>']
951
+ nostr-veil assert address <address> [--json '<metrics>']
952
+ nostr-veil assert identifier <id> <k-tag> [--json '<metrics>']
953
+ nostr-veil provider-declare [--json '<entries>']
954
+ nostr-veil verify '<event-json>' [--kind <n>]
955
+ nostr-veil --help
956
+ ```
957
+
958
+ `assert` and `provider-declare` build plain NIP-85 events (kinds 30382 to 30385 and 10040), not ring-signed ones, sign them with the key in `NOSTR_SECRET_KEY` (64-char hex) or the file named by `NOSTR_SECRET_KEY_FILE` (takes precedence), and print the signed event as JSON on stdout. `--json` takes a JSON object of metrics (`provider-declare`: an array of `{ kind, metric, servicePubkey, relayHint }`). `verify` needs no key: `<event-json>` is an inline JSON string, not a file path, and must come first (`nostr-veil verify "$(cat event.json)" --kind 30382`). `--kind` takes a non-negative integer and applies `expectedKind`. It prints the `verifyProof` result as JSON and exits 0 even when `valid` is false, so read `valid` rather than the exit code.
959
+
874
960
  ## Companion Libraries
875
961
 
876
962
  These are not dependencies but complement nostr-veil:
package/llms.txt CHANGED
@@ -21,23 +21,57 @@ npm install nostr-veil
21
21
  ```
22
22
 
23
23
  ```ts
24
- import { createTrustCircle, contributeAssertion, aggregateContributions, verifyProof } from 'nostr-veil'
24
+ import { schnorr } from '@noble/curves/secp256k1.js'
25
+ import { bytesToHex } from '@noble/hashes/utils.js'
26
+ import {
27
+ createTrustCircle, contributeAssertion, aggregateContributions, verifyProof, signEvent, NIP85_KINDS,
28
+ } from 'nostr-veil'
29
+
30
+ // 0. Generate keys. nostr-veil takes 64-char lowercase hex strings everywhere.
31
+ function generateKeypair() {
32
+ const secret = schnorr.utils.randomSecretKey() // Uint8Array (noble v2)
33
+ return { privkey: bytesToHex(secret), pubkey: bytesToHex(schnorr.getPublicKey(secret)) }
34
+ }
35
+ const alice = generateKeypair()
36
+ const bob = generateKeypair()
37
+ const carol = generateKeypair()
38
+ const subject = generateKeypair() // the account being scored; only its pubkey is used
39
+ const aggregator = generateKeypair() // publishes the result; does not need to be a circle member
40
+ const subjectPubkey = subject.pubkey
25
41
 
26
42
  // 1. Define a circle of three anonymous members
27
- const circle = createTrustCircle([alicePubkey, bobPubkey, carolPubkey])
43
+ const circle = createTrustCircle([alice.pubkey, bob.pubkey, carol.pubkey])
44
+
45
+ // 2. Each member contributes independently -- identity hidden inside the ring.
46
+ // memberIndex is the position in the SORTED circle.members, so use indexOf.
47
+ const aliceContribution = contributeAssertion(
48
+ circle, subjectPubkey, { followers: 820, rank: 74 }, alice.privkey, circle.members.indexOf(alice.pubkey),
49
+ )
50
+ const bobContribution = contributeAssertion(
51
+ circle, subjectPubkey, { followers: 900, rank: 80 }, bob.privkey, circle.members.indexOf(bob.pubkey),
52
+ )
28
53
 
29
- // 2. Each member contributes independently -- identity hidden inside the ring
30
- const alice = contributeAssertion(circle, subjectPubkey, { followers: 820, rank: 74 }, alicePrivkey, 0)
31
- const bob = contributeAssertion(circle, subjectPubkey, { followers: 900, rank: 80 }, bobPrivkey, 1)
54
+ // 3. Aggregate into a standard NIP-85 kind 30382 event (an unsigned EventTemplate)
55
+ const assertion = aggregateContributions(circle, subjectPubkey, [aliceContribution, bobContribution])
32
56
 
33
- // 3. Aggregate into a standard NIP-85 kind 30382 event
34
- const assertion = aggregateContributions(circle, subjectPubkey, [alice, bob])
57
+ // 4. The aggregator signs it as an ordinary Nostr event and publishes it
58
+ const signed = signEvent(assertion, aggregator.privkey)
35
59
 
36
- // 4. Verify: two distinct signers agreed, no names attached
37
- const result = verifyProof(assertion)
60
+ // 5. Verify: two distinct signers agreed, no names attached
61
+ const result = verifyProof(signed, { expectedKind: NIP85_KINDS.USER })
38
62
  // { valid: true, circleSize: 3, threshold: 2, distinctSigners: 2, errors: [] }
39
63
  ```
40
64
 
65
+ Formats: pubkeys are 64-char lowercase hex x-only strings; every `privateKey`
66
+ argument (`contributeAssertion`, `signEvent`, `createSignedDeploymentBundle`) is a
67
+ 64-char hex string. A `Uint8Array` is rejected, so convert noble byte keys with
68
+ `bytesToHex`. `circle.members.indexOf(pubkey)` is the only safe `memberIndex`: a
69
+ wrong index throws `Private key does not match ring member at signerIndex`.
70
+ The aggregator is whoever collects the contributions and publishes the event;
71
+ the ring proofs are in the `veil-sig` tags and `verifyProof` does not check the
72
+ outer Nostr signature, so call `verifySignedEvent(event)` on events fetched from
73
+ untrusted relays. Pass `expectedKind` because v1 proofs are not kind-bound.
74
+
41
75
  ## Key Concepts
42
76
 
43
77
  - **Trust circle**: A fixed group of public keys that can contribute scores anonymously. Created with `createTrustCircle()`. Minimum 2 members, maximum 1000.
@@ -46,11 +80,12 @@ const result = verifyProof(assertion)
46
80
  - **Verification**: `verifyProof()` confirms each ring signature is valid, duplicate-detection tokens are distinct, election IDs match, and the threshold is met -- all without learning who signed. Pass `{ requireProofVersion: 'v2' }` when a workflow must reject legacy v1 proofs.
47
81
  - **Federation scope**: Circles sharing a `scope` (set via `createTrustCircle(members, { scope })`) produce matching key images for members they have in common, so `verifyFederation()` can verify several scoped events about one subject and count distinct contributors across circles without double-counting anyone in more than one.
48
82
  - **Election ID**: v1 format `veil:v1:<scope-or-circleId>:<subject>`. Opt-in v2 adds assertion kind and subject hint tag/value to prevent cross-kind replay.
49
- - **Signing**: `signEvent(template, privateKey)` is exported from the root package. It computes the event ID, signs with Schnorr, and returns a complete `SignedEvent`.
83
+ - **Signing**: `signEvent(template, privateKey)` is exported from the root package (not from a subpath). `privateKey` is a 64-char hex string. It computes the event ID, signs with Schnorr, and returns a complete `SignedEvent`. `verifySignedEvent(event)` and `computeEventId(event)` are root-only too.
84
+ - **Aggregation options**: `{ aggregate: 'median' | 'mean' | 'sum' | 'min' | 'max' }` (default median) is recorded in the `veil-agg` tag and `verifyProof` reads it from there, so a summed tally verifies with a bare `verifyProof(event)`. A custom `{ aggregateFn }` (or bare function) is recorded as `veil-agg: custom` and must also be passed to `verifyProof` (`{ aggregateFn }`), otherwise it fails with `veil-agg is "custom": pass the aggregate function via options to verify the metric tags`. `median` and `mean` round to integers; `sum`, `min` and `max` do not.
50
85
 
51
86
  ## API Surface
52
87
 
53
- Two subpath exports, plus a root that re-exports everything:
88
+ Three subpath exports (`nostr-veil/nip85`, `nostr-veil/proof`, `nostr-veil/profiles`), plus a root (`nostr-veil`) that re-exports all three and adds the signing helpers `signEvent`, `verifySignedEvent` and `computeEventId`, which exist only at the root:
54
89
 
55
90
  **`nostr-veil/nip85`** -- NIP-85 foundation (kinds 30382-30385 + 10040):
56
91
  `buildUserAssertion(pubkey, metrics)`, `buildEventAssertion(eventId, metrics)`, `buildAddressableAssertion(address, metrics)`, `buildIdentifierAssertion(identifier, kTag, metrics)`, `buildProviderDeclaration(providers, encryptedContent?)` where providers is `{ kind, metric, servicePubkey, relayHint }[]`, `parseAssertion(event)`, `parseProviderDeclaration(event, decryptFn?)`, `validateAssertion(event, options?)`, `validateAssertionStrict(event)`, `validateProviderDeclarationStrict(event)`, `assertionFilter({ kind, subject?, provider? })`, `providerFilter(pubkey)`, `NIP85_KINDS`
@@ -62,7 +97,7 @@ Two subpath exports, plus a root that re-exports everything:
62
97
  `USE_CASE_PROFILES`, `USE_CASE_PROFILE_BY_ID`, `verifyUseCaseProfile`,
63
98
  `createCircleManifest`, `verifyCircleManifest`, `createDeploymentPolicy`,
64
99
  `verifyDeploymentPolicy`, `createSignedDeploymentBundle`,
65
- `verifyDeploymentBundle`, `verifyProductionDeployment`,
100
+ `verifySignedDeploymentBundle`, `verifyDeploymentBundle`, `verifyProductionDeployment`,
66
101
  `createProductionDecisionReport`, `verifyProductionDeploymentReport`,
67
102
  `createAdmissionChallenge`, `createAdmissionPresentation`,
68
103
  `verifyAdmissionPresentation`, `verifyAdmissionRequest`,
@@ -90,6 +125,71 @@ digests, git repositories, GitHub repositories, maintainers, vendors, sources,
90
125
  and method-scoped credential verifiers. Prefer those helpers before signing so
91
126
  every contributor scores the same verifier-compatible identifier.
92
127
 
128
+ ## Options and Types
129
+
130
+ - Metrics: `Record<string, number>`, finite (NaN and Infinity throw), integers not required, published as `String(value)`. Names must not be `d`, `p`, `e`, `a`, `k` or start with `veil-` (verification fails with `Missing metric "<name>" derived from signed contributions`). `verifyProof` accepts at most 128 metrics of up to 64 characters by default. The `nostr-veil/nip85` builders use typed optional metrics: `UserMetrics` (30382: `followers`, `rank`, `first_created_at`, `post_cnt`, `reply_cnt`, `reactions_cnt`, `zap_amt_recd`, `zap_amt_sent`, `zap_cnt_recd`, `zap_cnt_sent`, `zap_avg_amt_day_recd`, `zap_avg_amt_day_sent`, `reports_cnt_recd`, `reports_cnt_sent`, `t`, `active_hours_start`, `active_hours_end`), `EventMetrics` (30383/30384: `rank`, `comment_cnt`, `quote_cnt`, `repost_cnt`, `reaction_cnt`, `zap_cnt`, `zap_amount`), `IdentifierMetrics` (30385: `rank`, `comment_cnt`, `reaction_cnt`).
131
+ - Aggregation options for `aggregateContributions` and the typed `aggregate*Contributions` helpers: a bare `(values: number[]) => number`, or `{ aggregate?: 'median' | 'mean' | 'sum' | 'min' | 'max', aggregateFn?, proofVersion?: 'v1' | 'v2', kind? }` (`kind` is legacy and only on `aggregateContributions`; `aggregate` wins over `aggregateFn`; an unknown name throws `Unknown aggregate function: <name>`).
132
+ - `verifyProof(event, options?)`: a bare aggregate function, or `{ aggregateFn?, expectedKind?: number, requireProofVersion?: 'v1' | 'v2', limits?: Partial<VerifyLimits> }`. `DEFAULT_VERIFY_LIMITS` is `maxRingSize` 1000, `maxSigPayloadBytes` 128000, `maxSignedMessageBytes` 16384, `maxMetricCount` 128, `maxMetricNameLength` 64. Returns `{ valid, circleSize, threshold, distinctSigners, errors }`.
133
+ - `contributeAssertion(..., options?)`: `{ proofVersion?, kind?, subjectTag?: 'p' | 'e' | 'a' | 'k', subjectTagValue? }`; the typed helpers take only `{ proofVersion? }`. `canonicalMessageV2(circleId, subject, metrics, context)` needs `context` as `{ kind, subjectTag, subjectTagValue }`, all required (non-negative safe integer kind, `p`/`e`/`a`/`k` tag, non-empty value).
134
+ - `parseAssertion(event)` returns `{ kind: number, subject: string, metrics: Record<string, string | number> }` (subject is the `d` tag value, metric values are raw tag strings). `parseProviderDeclaration(event)` returns `ParsedProvider[]` of `{ kind, metric, servicePubkey, relayHint }`, or a Promise of it when given `decryptFn: (ciphertext: string) => Promise<string>`.
135
+ - Profiles options (timestamps are Unix seconds; `now` defaults to the current time). `createCircleManifest`: required `issuedAt`, `members`, `name`, `profileIds`, `purpose`; optional `expiresAt`, `status`, `supersedes`, `revokedCircleIds`, `contact`, `evidenceProcess`, `policyUri`. `createDeploymentPolicy(profile, options)`: required `expectedSubject` plus at least one active circle via `acceptedCircleIds` or `circleManifests`; optional `expectedSubjectTagValue`, `id`, `maxAgeSeconds`, `minDistinctSigners`, `metricPolicies` (`{ [metric]: { required?, min?, max?, integer? } }`), `rejectUnknownMetrics` (default false), `requireNostrSignature` (default false), `companionEvidence`, `allowSupersededCircleIds`, `now`. `createSignedDeploymentBundle(policy, options)`: required `id`, `issuedAt`, `privateKey`; optional `expiresAt`. `verifySignedDeploymentBundle(bundle, { now?, trustedPublishers? })`. `verifyDeploymentBundle(events, bundle, options?)` takes `aggregateFn`, `companionEvidence`, `now`, `trustedPublishers`. `verifyProductionDeployment` adds `requireBundleExpiry` and `requireSignedEvents`, both true by default, and returns `{ decision: 'accept' | 'reject', valid, errors, issues, bundle, deployment }`. Without a valid `trustedPublishers` entry, bundle verification fails with `no trusted bundle publishers configured`.
136
+
137
+ ## Profiles Example
138
+
139
+ Continuing from the quick start. The built-in `USER_REPUTATION_ABUSE_REPORTING_PROFILE` needs proof v2, at least three distinct signers and an assertion no older than 300 seconds.
140
+
141
+ ```ts
142
+ import {
143
+ USER_REPUTATION_ABUSE_REPORTING_PROFILE,
144
+ createDeploymentPolicy,
145
+ createSignedDeploymentBundle,
146
+ verifyProductionDeployment,
147
+ } from 'nostr-veil/profiles'
148
+
149
+ const operator = generateKeypair() // deployment operator, separate from circle members
150
+ const contributions = [alice, bob, carol].map(member => contributeAssertion(
151
+ circle, subjectPubkey, { rank: 80 }, member.privkey, circle.members.indexOf(member.pubkey), { proofVersion: 'v2' },
152
+ ))
153
+ const event = signEvent(
154
+ aggregateContributions(circle, subjectPubkey, contributions, { proofVersion: 'v2' }),
155
+ aggregator.privkey,
156
+ )
157
+
158
+ const policy = createDeploymentPolicy(USER_REPUTATION_ABUSE_REPORTING_PROFILE, {
159
+ acceptedCircleIds: [circle.circleId],
160
+ expectedSubject: subjectPubkey,
161
+ requireNostrSignature: true, // verifyProductionDeployment rejects a policy without this
162
+ })
163
+ const now = Math.floor(Date.now() / 1000)
164
+ const bundle = createSignedDeploymentBundle(policy, {
165
+ id: 'abuse-reporting-2026-01',
166
+ issuedAt: now,
167
+ expiresAt: now + 24 * 60 * 60, // verifyProductionDeployment rejects a bundle without expiry
168
+ privateKey: operator.privkey,
169
+ })
170
+
171
+ const verdict = verifyProductionDeployment([event], bundle, { trustedPublishers: [operator.pubkey] })
172
+ // verdict.decision === 'accept'; a bundle signed by another key fails with `bundle.signer_untrusted`
173
+ ```
174
+
175
+ See [examples/production-recipes.ts](https://github.com/forgesworn/nostr-veil/blob/main/examples/production-recipes.ts) for six production-shaped gates with companion evidence.
176
+
177
+ ## CLI
178
+
179
+ The package installs a `nostr-veil` binary:
180
+
181
+ ```bash
182
+ nostr-veil assert user <pubkey> [--json '<metrics>']
183
+ nostr-veil assert event <event-id> [--json '<metrics>']
184
+ nostr-veil assert address <address> [--json '<metrics>']
185
+ nostr-veil assert identifier <id> <k-tag> [--json '<metrics>']
186
+ nostr-veil provider-declare [--json '<entries>']
187
+ nostr-veil verify '<event-json>' [--kind <n>]
188
+ nostr-veil --help
189
+ ```
190
+
191
+ `assert` and `provider-declare` build plain NIP-85 events (kinds 30382 to 30385 and 10040), not ring-signed ones, sign them with the key in `NOSTR_SECRET_KEY` (64-char hex) or the file named by `NOSTR_SECRET_KEY_FILE` (takes precedence), and print the signed event as JSON on stdout. `--json` takes a JSON object of metrics (`provider-declare`: an array of `{ kind, metric, servicePubkey, relayHint }`). `verify` needs no key: `<event-json>` is an inline JSON string, not a file path, and must come first (`nostr-veil verify "$(cat event.json)" --kind 30382`). `--kind` takes a non-negative integer and applies `expectedKind`. It prints the `verifyProof` result as JSON and exits 0 even when `valid` is false, so read `valid` rather than the exit code.
192
+
93
193
  ## Limits
94
194
 
95
195
  nostr-veil hides which public ring member contributed. It does not hide the ring
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-veil",
3
- "version": "0.30.2",
3
+ "version": "0.30.3",
4
4
  "description": "Privacy layer for Nostr reputation systems. Groups collectively score trustworthiness using ring signatures -- scores are verifiable but contributors are unidentifiable.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -95,6 +95,6 @@
95
95
  "@playwright/test": "^1.59.1",
96
96
  "tsx": "^4.21.0",
97
97
  "typescript": "^5.7.0",
98
- "vitest": "^4.1.6"
98
+ "vitest": "^5.0.0"
99
99
  }
100
100
  }