nostr-veil 0.0.1 → 0.2.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.
Files changed (64) hide show
  1. package/LICENCE +21 -0
  2. package/README.md +187 -0
  3. package/bin/cli.js +153 -0
  4. package/bin/config.js +38 -0
  5. package/dist/index.d.ts +4 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +4 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/nip85/builders.d.ts +73 -0
  10. package/dist/nip85/builders.d.ts.map +1 -0
  11. package/dist/nip85/builders.js +126 -0
  12. package/dist/nip85/builders.js.map +1 -0
  13. package/dist/nip85/filters.d.ts +36 -0
  14. package/dist/nip85/filters.d.ts.map +1 -0
  15. package/dist/nip85/filters.js +41 -0
  16. package/dist/nip85/filters.js.map +1 -0
  17. package/dist/nip85/index.d.ts +6 -0
  18. package/dist/nip85/index.d.ts.map +1 -0
  19. package/dist/nip85/index.js +6 -0
  20. package/dist/nip85/index.js.map +1 -0
  21. package/dist/nip85/parsers.d.ts +44 -0
  22. package/dist/nip85/parsers.d.ts.map +1 -0
  23. package/dist/nip85/parsers.js +71 -0
  24. package/dist/nip85/parsers.js.map +1 -0
  25. package/dist/nip85/types.d.ts +84 -0
  26. package/dist/nip85/types.d.ts.map +1 -0
  27. package/dist/nip85/types.js +16 -0
  28. package/dist/nip85/types.js.map +1 -0
  29. package/dist/nip85/validators.d.ts +26 -0
  30. package/dist/nip85/validators.d.ts.map +1 -0
  31. package/dist/nip85/validators.js +53 -0
  32. package/dist/nip85/validators.js.map +1 -0
  33. package/dist/proof/aggregate.d.ts +23 -0
  34. package/dist/proof/aggregate.d.ts.map +1 -0
  35. package/dist/proof/aggregate.js +101 -0
  36. package/dist/proof/aggregate.js.map +1 -0
  37. package/dist/proof/circle.d.ts +50 -0
  38. package/dist/proof/circle.d.ts.map +1 -0
  39. package/dist/proof/circle.js +97 -0
  40. package/dist/proof/circle.js.map +1 -0
  41. package/dist/proof/contribute.d.ts +17 -0
  42. package/dist/proof/contribute.d.ts.map +1 -0
  43. package/dist/proof/contribute.js +27 -0
  44. package/dist/proof/contribute.js.map +1 -0
  45. package/dist/proof/index.d.ts +6 -0
  46. package/dist/proof/index.d.ts.map +1 -0
  47. package/dist/proof/index.js +6 -0
  48. package/dist/proof/index.js.map +1 -0
  49. package/dist/proof/types.d.ts +37 -0
  50. package/dist/proof/types.d.ts.map +1 -0
  51. package/dist/proof/types.js +2 -0
  52. package/dist/proof/types.js.map +1 -0
  53. package/dist/proof/verify.d.ts +7 -0
  54. package/dist/proof/verify.d.ts.map +1 -0
  55. package/dist/proof/verify.js +109 -0
  56. package/dist/proof/verify.js.map +1 -0
  57. package/dist/signing.d.ts +54 -0
  58. package/dist/signing.d.ts.map +1 -0
  59. package/dist/signing.js +58 -0
  60. package/dist/signing.js.map +1 -0
  61. package/llms-full.txt +573 -0
  62. package/llms.txt +71 -0
  63. package/package.json +82 -4
  64. package/index.js +0 -1
package/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT Licence
2
+
3
+ Copyright (c) 2026 ForgeSworn
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 ADDED
@@ -0,0 +1,187 @@
1
+ # nostr-veil
2
+
3
+ [![CI](https://github.com/forgesworn/nostr-veil/actions/workflows/ci.yml/badge.svg)](https://github.com/forgesworn/nostr-veil/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/nostr-veil)](https://www.npmjs.com/package/nostr-veil)
5
+ [![licence: MIT](https://img.shields.io/badge/licence-MIT-blue.svg)](./LICENCE)
6
+
7
+ **Trust scores you can verify without seeing who contributed them.**
8
+
9
+ Anonymous trust assertions for Nostr. LSAG ring signatures over NIP-85 events so endorsements are verifiable but contributors are unidentifiable.
10
+
11
+ **Who is this for?** Nostr client developers building trust systems where contributor privacy matters -- abuse reporting, whistleblowing, journalism, anonymous peer review. If your users can't afford to be identified when vouching for someone, this is the library.
12
+
13
+ ---
14
+
15
+ ## The Trust Trilemma
16
+
17
+ Today's NIP-85 trust scores ask you to pick two:
18
+
19
+ | Property | NIP-85 today | nostr-veil |
20
+ |-------------|:---:|:---:|
21
+ | Verifiable | ✓ | ✓ |
22
+ | Private | ✗ | ✓ |
23
+ | Portable | ✓ | ✓ |
24
+
25
+ Anyone who can see the assertions can see exactly who judged you. That works fine for benign social signals. It fails completely the moment the subject matter is sensitive -- abuse reporting, whistleblowing, political dissent. The people who need Web of Trust most are the ones who cannot afford to be identified.
26
+
27
+ nostr-veil solves all three. Assertions are standard NIP-85 events that any existing client can consume. Veil-aware clients can go further and verify the cryptographic proofs that back them.
28
+
29
+ ---
30
+
31
+ ## Architecture
32
+
33
+ ```mermaid
34
+ graph TB
35
+ subgraph Consumers["Nostr Clients"]
36
+ any["Any NIP-85 client<br/>reads standard assertions"]
37
+ veil["Veil-aware client<br/>verifies ring proofs"]
38
+ end
39
+
40
+ subgraph Veil["nostr-veil"]
41
+ proof["nostr-veil/proof<br/>LSAG ring signatures<br/>anonymous contributions<br/>threshold aggregation"]
42
+ nip85["nostr-veil/nip85<br/>Kind 30382–30385 assertions<br/>Kind 10040 providers<br/>builders · parsers · filters"]
43
+ end
44
+
45
+ subgraph Crypto["Cryptographic Primitives"]
46
+ ringsig["@forgesworn/ring-sig<br/>SAG / LSAG on secp256k1"]
47
+ noble["@noble/curves + hashes<br/>Schnorr · SHA-256"]
48
+ end
49
+
50
+ subgraph Companions["Companion Libraries"]
51
+ nsec["nsec-tree<br/>sub-identity derivation"]
52
+ canary["canary-kit<br/>coercion detection"]
53
+ signet["signet<br/>identity verification"]
54
+ end
55
+
56
+ any -->|"read"| nip85
57
+ veil -->|"verify"| proof
58
+ proof -->|"builds on"| nip85
59
+ proof --> ringsig
60
+ nip85 --> noble
61
+ nsec -.->|"personas for"| proof
62
+ canary -.->|"liveness for"| proof
63
+
64
+ style any fill:#3b82f6,color:#fff
65
+ style veil fill:#d97706,color:#000
66
+ style proof fill:#d97706,color:#000
67
+ style nip85 fill:#0d9488,color:#fff
68
+ style ringsig fill:#8b5cf6,color:#fff
69
+ style noble fill:#8b5cf6,color:#fff
70
+ style nsec fill:#374151,color:#e5e7eb
71
+ style canary fill:#374151,color:#e5e7eb
72
+ style signet fill:#374151,color:#e5e7eb
73
+ ```
74
+
75
+ ---
76
+
77
+ ## Quick start
78
+
79
+ ```
80
+ npm install nostr-veil
81
+ ```
82
+
83
+ ```ts
84
+ import { createTrustCircle, contributeAssertion, aggregateContributions, verifyProof } from 'nostr-veil'
85
+
86
+ // 1. Define the circle (three anonymous members)
87
+ const circle = createTrustCircle([alicePubkey, bobPubkey, carolPubkey])
88
+
89
+ // 2. Each member contributes independently -- their identity is hidden inside the ring
90
+ const alice = contributeAssertion(circle, subjectPubkey, { followers: 820, rank: 74 }, alicePrivkey, 0)
91
+ const bob = contributeAssertion(circle, subjectPubkey, { followers: 900, rank: 80 }, bobPrivkey, 1)
92
+
93
+ // 3. Aggregate into a standard NIP-85 kind 30382 event
94
+ const assertion = aggregateContributions(circle, subjectPubkey, [alice, bob])
95
+
96
+ // 4. Any client verifies -- two distinct members agreed, no names attached
97
+ const result = verifyProof(assertion)
98
+ // { valid: true, circleSize: 3, threshold: 2, distinctSigners: 2, errors: [] }
99
+ ```
100
+
101
+ The resulting `assertion` is a plain `EventTemplate` you sign and publish like any other Nostr event.
102
+
103
+ ---
104
+
105
+ ## API reference
106
+
107
+ ### `nostr-veil/nip85` -- NIP-85 foundation
108
+
109
+ | Export | Description |
110
+ |--------|-------------|
111
+ | `buildUserAssertion(pubkey, metrics)` | Build a kind 30382 user assertion event template |
112
+ | `buildEventAssertion(eventId, metrics)` | Build a kind 30383 event assertion |
113
+ | `buildAddressableAssertion(address, metrics)` | Build a kind 30384 addressable assertion |
114
+ | `buildIdentifierAssertion(identifier, kTag, metrics)` | Build a kind 30385 identifier assertion |
115
+ | `buildProviderDeclaration(providers, encryptedContent?)` | Build a kind 10040 provider declaration |
116
+ | `parseAssertion(event)` | Parse a raw event into a `ParsedAssertion` |
117
+ | `validateAssertion(event)` | Validate a NIP-85 assertion -- returns `{ valid, errors }` |
118
+ | `assertionFilter({ kind, subject?, provider? })` | Build a relay query filter for assertions |
119
+ | `providerFilter(pubkey)` | Build a relay query filter for a provider declaration |
120
+ | `NIP85_KINDS` | Kind constants: `USER`, `EVENT`, `ADDRESSABLE`, `IDENTIFIER`, `PROVIDER` |
121
+
122
+ ### `nostr-veil/proof` -- Ring-signature proof layer
123
+
124
+ | Export | Description |
125
+ |--------|-------------|
126
+ | `createTrustCircle(memberPubkeys)` | Create a trust circle from an array of pubkeys |
127
+ | `contributeAssertion(circle, subject, metrics, privateKey, memberIndex)` | Produce an anonymous `Contribution` using LSAG |
128
+ | `aggregateContributions(circle, subject, contributions, options?)` | Aggregate contributions into a NIP-85 event with veil tags (default aggregation: median) |
129
+ | `verifyProof(event)` | Verify all LSAG signatures and return a `ProofVerification` |
130
+ | `canonicalMessage(circleId, subject, metrics)` | Compute the canonical message signed by contributors |
131
+ | `computeCircleId(sortedPubkeys)` | Compute the deterministic circle ID (SHA-256 of colon-joined pubkeys) |
132
+
133
+ ### Signing utility (root export)
134
+
135
+ | Export | Description |
136
+ |--------|-------------|
137
+ | `signEvent(template, privateKey)` | Sign an unsigned event template with BIP-340 Schnorr -- returns a complete `SignedEvent` |
138
+ | `computeEventId(event)` | Compute the NIP-01 event ID (SHA-256 of canonical serialisation) |
139
+
140
+ ---
141
+
142
+ ## How it works
143
+
144
+ Each member of a trust circle calls `contributeAssertion` independently. Under the hood this calls `lsagSign` from `@forgesworn/ring-sig`, which produces a Linkable Spontaneous Anonymous Group signature over the canonical message `{ circleId, subject, metrics }`.
145
+
146
+ The published NIP-85 event carries three extra tags:
147
+
148
+ - `veil-ring` -- the full set of member pubkeys (the ring)
149
+ - `veil-threshold` -- how many contributions were aggregated out of how many members
150
+ - `veil-sig` (one per contribution) -- the serialised LSAG signature and key image
151
+
152
+ A verifier calls `verifyProof`, which:
153
+
154
+ 1. Reconstructs each LSAG signature against the ring
155
+ 2. Confirms each signature is valid
156
+ 3. Checks key images are distinct -- proving each signer contributed at most once (LSAG linkability property)
157
+ 4. Confirms the number of valid, distinct signatures meets the threshold
158
+
159
+ At no point does verification require knowing which member produced which signature. The ring is public. The identities of the actual signers are not.
160
+
161
+ ---
162
+
163
+ ## Companion projects
164
+
165
+ nostr-veil is one layer of a broader identity and trust stack:
166
+
167
+ - [@forgesworn/ring-sig](https://github.com/forgesworn/ring-sig) -- LSAG ring signatures on secp256k1 (the cryptographic primitive)
168
+ - [nsec-tree](https://github.com/forgesworn/nsec-tree) -- Deterministic sub-identity derivation (compartmentalised personas for trust circles)
169
+ - [canary-kit](https://github.com/forgesworn/canary-kit) -- Coercion-resistant verification and duress detection
170
+ - [signet](https://github.com/forgesworn/signet) -- Decentralised identity verification for Nostr
171
+ - [dominion](https://github.com/forgesworn/dominion) -- Epoch-based encrypted content access control
172
+
173
+ Each project is independently maintained and published. nostr-veil focuses solely on anonymous trust assertions.
174
+
175
+ ---
176
+
177
+ ## Further reading
178
+
179
+ - [IMPACT.md](./IMPACT.md) -- Problem statement and ecosystem impact
180
+ - [CONTRIBUTING.md](./CONTRIBUTING.md) -- Setup, testing, and PR guidelines
181
+ - [SECURITY.md](./SECURITY.md) -- Vulnerability reporting and cryptographic scope
182
+ - [llms.txt](./llms.txt) -- Machine-readable project summary for LLMs
183
+ - [CLAUDE.md](./CLAUDE.md) -- AI agent instructions for contributing
184
+
185
+ ## Licence
186
+
187
+ MIT
package/bin/cli.js ADDED
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { loadConfig } from './config.js'
4
+ import { signEvent } from '../dist/signing.js'
5
+ import {
6
+ buildUserAssertion,
7
+ buildEventAssertion,
8
+ buildAddressableAssertion,
9
+ buildIdentifierAssertion,
10
+ buildProviderDeclaration,
11
+ } from '../dist/nip85/builders.js'
12
+ import { verifyProof } from '../dist/proof/verify.js'
13
+
14
+ const USAGE = `nostr-veil — anonymous trust assertions for Nostr
15
+
16
+ Usage:
17
+ nostr-veil assert user <pubkey> [--json metrics] Build kind 30382 user assertion
18
+ nostr-veil assert event <event-id> [--json metrics] Build kind 30383 event assertion
19
+ nostr-veil assert address <address> [--json metrics] Build kind 30384 addressable assertion
20
+ nostr-veil assert identifier <id> <k-tag> [--json metrics] Build kind 30385 identifier assertion
21
+ nostr-veil provider-declare [--json entries] Build kind 10040 provider declaration
22
+ nostr-veil verify <event-json> Verify veil ring proof, print result
23
+ nostr-veil --help Show this message
24
+
25
+ Environment:
26
+ NOSTR_SECRET_KEY 64-char hex private key
27
+ NOSTR_SECRET_KEY_FILE Path to secret key file (takes precedence)
28
+
29
+ Output is signed event JSON to stdout. Pipe to other tools for relay publishing.
30
+ `
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Helpers
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /** Extract --json value from args (the next arg after --json). */
37
+ function extractJsonFlag(args) {
38
+ const idx = args.indexOf('--json')
39
+ if (idx === -1 || idx + 1 >= args.length) return undefined
40
+ try {
41
+ return JSON.parse(args[idx + 1])
42
+ } catch {
43
+ console.error('Error: invalid JSON after --json flag')
44
+ process.exit(1)
45
+ }
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Commands
50
+ // ---------------------------------------------------------------------------
51
+
52
+ function cmdAssert(args) {
53
+ const subcommand = args[0]
54
+ if (!subcommand) {
55
+ console.error('Error: assert requires a subcommand (user, event, address, identifier)')
56
+ process.exit(1)
57
+ }
58
+
59
+ const { secretKey } = loadConfig()
60
+ const metrics = extractJsonFlag(args) ?? {}
61
+ let template
62
+
63
+ switch (subcommand) {
64
+ case 'user': {
65
+ const pubkey = args[1]
66
+ if (!pubkey) { console.error('Error: assert user requires <pubkey>'); process.exit(1) }
67
+ template = buildUserAssertion(pubkey, metrics)
68
+ break
69
+ }
70
+ case 'event': {
71
+ const eventId = args[1]
72
+ if (!eventId) { console.error('Error: assert event requires <event-id>'); process.exit(1) }
73
+ template = buildEventAssertion(eventId, metrics)
74
+ break
75
+ }
76
+ case 'address': {
77
+ const address = args[1]
78
+ if (!address) { console.error('Error: assert address requires <address>'); process.exit(1) }
79
+ template = buildAddressableAssertion(address, metrics)
80
+ break
81
+ }
82
+ case 'identifier': {
83
+ const id = args[1]
84
+ const kTag = args[2]
85
+ if (!id || !kTag) { console.error('Error: assert identifier requires <id> <k-tag>'); process.exit(1) }
86
+ template = buildIdentifierAssertion(id, kTag, metrics)
87
+ break
88
+ }
89
+ default:
90
+ console.error(`Error: unknown assert subcommand '${subcommand}'`)
91
+ process.exit(1)
92
+ }
93
+
94
+ const signed = signEvent(template, secretKey)
95
+ console.log(JSON.stringify(signed, null, 2))
96
+ }
97
+
98
+ function cmdProviderDeclare(args) {
99
+ const { secretKey } = loadConfig()
100
+ const entries = extractJsonFlag(args) ?? []
101
+ const template = buildProviderDeclaration(entries)
102
+ const signed = signEvent(template, secretKey)
103
+ console.log(JSON.stringify(signed, null, 2))
104
+ }
105
+
106
+ function cmdVerify(args) {
107
+ const eventJson = args[0]
108
+ if (!eventJson) {
109
+ console.error('Error: verify requires <event-json>')
110
+ process.exit(1)
111
+ }
112
+
113
+ let event
114
+ try {
115
+ event = JSON.parse(eventJson)
116
+ } catch {
117
+ console.error('Error: invalid JSON in event argument')
118
+ process.exit(1)
119
+ }
120
+ if (!event || typeof event !== 'object' || !Array.isArray(event.tags)) {
121
+ console.error('Error: event must be a JSON object with a "tags" array')
122
+ process.exit(1)
123
+ }
124
+ const result = verifyProof(event)
125
+ console.log(JSON.stringify(result, null, 2))
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Router
130
+ // ---------------------------------------------------------------------------
131
+
132
+ const args = process.argv.slice(2)
133
+ const command = args[0]
134
+
135
+ if (!command || command === '--help' || command === '-h') {
136
+ console.log(USAGE)
137
+ process.exit(0)
138
+ }
139
+
140
+ switch (command) {
141
+ case 'assert':
142
+ cmdAssert(args.slice(1))
143
+ break
144
+ case 'provider-declare':
145
+ cmdProviderDeclare(args.slice(1))
146
+ break
147
+ case 'verify':
148
+ cmdVerify(args.slice(1))
149
+ break
150
+ default:
151
+ console.error(`Error: unknown command '${command}'. Run nostr-veil --help for usage.`)
152
+ process.exit(1)
153
+ }
package/bin/config.js ADDED
@@ -0,0 +1,38 @@
1
+ import { readFileSync } from 'node:fs'
2
+
3
+ /**
4
+ * Load Nostr secret key from environment variables.
5
+ *
6
+ * Environment variables:
7
+ * NOSTR_SECRET_KEY -- 64-char hex private key
8
+ * NOSTR_SECRET_KEY_FILE -- path to secret key file (takes precedence)
9
+ *
10
+ * @returns {{ secretKey: string }}
11
+ */
12
+ export function loadConfig() {
13
+ const keyFile = process.env.NOSTR_SECRET_KEY_FILE
14
+ const keyEnv = process.env.NOSTR_SECRET_KEY
15
+
16
+ let secretKey
17
+ if (keyFile) {
18
+ secretKey = readFileSync(keyFile, 'utf-8').trim()
19
+ } else if (keyEnv) {
20
+ secretKey = keyEnv.trim()
21
+ } else {
22
+ throw new Error(
23
+ 'Set NOSTR_SECRET_KEY or NOSTR_SECRET_KEY_FILE environment variable (64-char hex)'
24
+ )
25
+ }
26
+
27
+ if (!/^[0-9a-f]{64}$/i.test(secretKey)) {
28
+ throw new Error(
29
+ 'NOSTR_SECRET_KEY must be a 64-character hex private key'
30
+ )
31
+ }
32
+
33
+ // Scrub secrets from the environment
34
+ delete process.env.NOSTR_SECRET_KEY
35
+ delete process.env.NOSTR_SECRET_KEY_FILE
36
+
37
+ return { secretKey: secretKey.toLowerCase() }
38
+ }
@@ -0,0 +1,4 @@
1
+ export * from './nip85/index.js';
2
+ export * from './proof/index.js';
3
+ export * from './signing.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAA;AAChC,cAAc,kBAAkB,CAAA;AAChC,cAAc,cAAc,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './nip85/index.js';
2
+ export * from './proof/index.js';
3
+ export * from './signing.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAA;AAChC,cAAc,kBAAkB,CAAA;AAChC,cAAc,cAAc,CAAA"}
@@ -0,0 +1,73 @@
1
+ import type { UserMetrics, EventMetrics, IdentifierMetrics, ProviderEntry, EventTemplate } from './types.js';
2
+ /**
3
+ * Build a kind 30382 user assertion event template for the given pubkey.
4
+ *
5
+ * @param pubkey - Hex-encoded x-only public key of the subject (64 chars)
6
+ * @param metrics - {@link UserMetrics} to embed as tags (undefined values are omitted)
7
+ * @returns An unsigned {@link EventTemplate} with `d` and `p` tags set to `pubkey`
8
+ *
9
+ * @example
10
+ * const tmpl = buildUserAssertion(alicePubkey, { rank: 85, followers: 1200 })
11
+ * const event = signEvent(tmpl, providerPrivkey)
12
+ * await relay.publish(event)
13
+ */
14
+ export declare function buildUserAssertion(pubkey: string, metrics: UserMetrics): EventTemplate;
15
+ /**
16
+ * Build a kind 30383 event assertion for the given event ID.
17
+ *
18
+ * @param eventId - Hex-encoded Nostr event ID (64 chars)
19
+ * @param metrics - {@link EventMetrics} to embed as tags (undefined values are omitted)
20
+ * @returns An unsigned {@link EventTemplate} with `d` and `e` tags set to `eventId`
21
+ *
22
+ * @example
23
+ * const tmpl = buildEventAssertion(noteId, { rank: 90, repost_cnt: 42 })
24
+ * const event = signEvent(tmpl, providerPrivkey)
25
+ * await relay.publish(event)
26
+ */
27
+ export declare function buildEventAssertion(eventId: string, metrics: EventMetrics): EventTemplate;
28
+ /**
29
+ * Build a kind 30384 addressable assertion for the given NIP-33 address.
30
+ *
31
+ * @param address - NIP-33 address in `kind:pubkey:d-tag` format
32
+ * @param metrics - {@link EventMetrics} to embed as tags (undefined values are omitted)
33
+ * @returns An unsigned {@link EventTemplate} with `d` and `a` tags set to `address`
34
+ *
35
+ * @example
36
+ * const tmpl = buildAddressableAssertion('30023:abc123:my-article', { rank: 70 })
37
+ * const event = signEvent(tmpl, providerPrivkey)
38
+ * await relay.publish(event)
39
+ */
40
+ export declare function buildAddressableAssertion(address: string, metrics: EventMetrics): EventTemplate;
41
+ /**
42
+ * Build a kind 30385 identifier assertion with an explicit k-tag.
43
+ *
44
+ * @param identifier - Opaque identifier string used as the `d`-tag value
45
+ * @param kTag - The kind number (as a string) the identifier belongs to
46
+ * @param metrics - {@link IdentifierMetrics} to embed as tags (undefined values are omitted)
47
+ * @returns An unsigned {@link EventTemplate} with `d` and `k` tags set accordingly
48
+ *
49
+ * @example
50
+ * const tmpl = buildIdentifierAssertion('npub1abc…', '0', { rank: 60, reaction_cnt: 15 })
51
+ * const event = signEvent(tmpl, providerPrivkey)
52
+ * await relay.publish(event)
53
+ */
54
+ export declare function buildIdentifierAssertion(identifier: string, kTag: string, metrics: IdentifierMetrics): EventTemplate;
55
+ /**
56
+ * Build a kind 10040 provider declaration listing which services provide which metrics.
57
+ *
58
+ * When `encryptedContent` is supplied, the tags are omitted from the event and the
59
+ * encrypted blob is placed in `content` instead (NIP-85 encrypted provider mode).
60
+ *
61
+ * @param providers - Array of {@link ProviderEntry} objects mapping `kind:metric` to a service pubkey
62
+ * @param encryptedContent - Optional pre-encrypted tag array; if provided, `tags` will be empty
63
+ * @returns An unsigned {@link EventTemplate} with compound `kind:metric` tag names
64
+ *
65
+ * @example
66
+ * const tmpl = buildProviderDeclaration([
67
+ * { kind: 30382, metric: 'rank', servicePubkey: providerPubkey, relayHint: 'wss://relay.example.com' },
68
+ * ])
69
+ * const event = signEvent(tmpl, providerPrivkey)
70
+ * await relay.publish(event)
71
+ */
72
+ export declare function buildProviderDeclaration(providers: ProviderEntry[], encryptedContent?: string): EventTemplate;
73
+ //# sourceMappingURL=builders.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builders.d.ts","sourceRoot":"","sources":["../../src/nip85/builders.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAwB5G;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,aAAa,CAWtF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,aAAa,CAOzF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,aAAa,CAM/F;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,aAAa,CAMpH;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,aAAa,EAAE,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,aAAa,CAO7G"}
@@ -0,0 +1,126 @@
1
+ import { NIP85_KINDS } from './types.js';
2
+ const HEX64_RE = /^[0-9a-f]{64}$/;
3
+ function validateHex64(value, label) {
4
+ if (!HEX64_RE.test(value)) {
5
+ throw new Error(`${label} must be a 64-character lowercase hex string, got "${value.slice(0, 20)}${value.length > 20 ? '...' : ''}"`);
6
+ }
7
+ }
8
+ function metricsToTags(metrics) {
9
+ return Object.entries(metrics)
10
+ .filter(([, v]) => v !== undefined)
11
+ .map(([k, v]) => {
12
+ if (typeof v === 'number' && !Number.isFinite(v)) {
13
+ throw new Error(`Metric "${k}" must be a finite number, got ${v}`);
14
+ }
15
+ return [k, String(v)];
16
+ });
17
+ }
18
+ /**
19
+ * Build a kind 30382 user assertion event template for the given pubkey.
20
+ *
21
+ * @param pubkey - Hex-encoded x-only public key of the subject (64 chars)
22
+ * @param metrics - {@link UserMetrics} to embed as tags (undefined values are omitted)
23
+ * @returns An unsigned {@link EventTemplate} with `d` and `p` tags set to `pubkey`
24
+ *
25
+ * @example
26
+ * const tmpl = buildUserAssertion(alicePubkey, { rank: 85, followers: 1200 })
27
+ * const event = signEvent(tmpl, providerPrivkey)
28
+ * await relay.publish(event)
29
+ */
30
+ export function buildUserAssertion(pubkey, metrics) {
31
+ validateHex64(pubkey, 'pubkey');
32
+ return {
33
+ kind: NIP85_KINDS.USER,
34
+ tags: [
35
+ ['d', pubkey],
36
+ ['p', pubkey],
37
+ ...metricsToTags(metrics),
38
+ ],
39
+ content: '',
40
+ };
41
+ }
42
+ /**
43
+ * Build a kind 30383 event assertion for the given event ID.
44
+ *
45
+ * @param eventId - Hex-encoded Nostr event ID (64 chars)
46
+ * @param metrics - {@link EventMetrics} to embed as tags (undefined values are omitted)
47
+ * @returns An unsigned {@link EventTemplate} with `d` and `e` tags set to `eventId`
48
+ *
49
+ * @example
50
+ * const tmpl = buildEventAssertion(noteId, { rank: 90, repost_cnt: 42 })
51
+ * const event = signEvent(tmpl, providerPrivkey)
52
+ * await relay.publish(event)
53
+ */
54
+ export function buildEventAssertion(eventId, metrics) {
55
+ validateHex64(eventId, 'eventId');
56
+ return {
57
+ kind: NIP85_KINDS.EVENT,
58
+ tags: [['d', eventId], ['e', eventId], ...metricsToTags(metrics)],
59
+ content: '',
60
+ };
61
+ }
62
+ /**
63
+ * Build a kind 30384 addressable assertion for the given NIP-33 address.
64
+ *
65
+ * @param address - NIP-33 address in `kind:pubkey:d-tag` format
66
+ * @param metrics - {@link EventMetrics} to embed as tags (undefined values are omitted)
67
+ * @returns An unsigned {@link EventTemplate} with `d` and `a` tags set to `address`
68
+ *
69
+ * @example
70
+ * const tmpl = buildAddressableAssertion('30023:abc123:my-article', { rank: 70 })
71
+ * const event = signEvent(tmpl, providerPrivkey)
72
+ * await relay.publish(event)
73
+ */
74
+ export function buildAddressableAssertion(address, metrics) {
75
+ return {
76
+ kind: NIP85_KINDS.ADDRESSABLE,
77
+ tags: [['d', address], ['a', address], ...metricsToTags(metrics)],
78
+ content: '',
79
+ };
80
+ }
81
+ /**
82
+ * Build a kind 30385 identifier assertion with an explicit k-tag.
83
+ *
84
+ * @param identifier - Opaque identifier string used as the `d`-tag value
85
+ * @param kTag - The kind number (as a string) the identifier belongs to
86
+ * @param metrics - {@link IdentifierMetrics} to embed as tags (undefined values are omitted)
87
+ * @returns An unsigned {@link EventTemplate} with `d` and `k` tags set accordingly
88
+ *
89
+ * @example
90
+ * const tmpl = buildIdentifierAssertion('npub1abc…', '0', { rank: 60, reaction_cnt: 15 })
91
+ * const event = signEvent(tmpl, providerPrivkey)
92
+ * await relay.publish(event)
93
+ */
94
+ export function buildIdentifierAssertion(identifier, kTag, metrics) {
95
+ return {
96
+ kind: NIP85_KINDS.IDENTIFIER,
97
+ tags: [['d', identifier], ['k', kTag], ...metricsToTags(metrics)],
98
+ content: '',
99
+ };
100
+ }
101
+ /**
102
+ * Build a kind 10040 provider declaration listing which services provide which metrics.
103
+ *
104
+ * When `encryptedContent` is supplied, the tags are omitted from the event and the
105
+ * encrypted blob is placed in `content` instead (NIP-85 encrypted provider mode).
106
+ *
107
+ * @param providers - Array of {@link ProviderEntry} objects mapping `kind:metric` to a service pubkey
108
+ * @param encryptedContent - Optional pre-encrypted tag array; if provided, `tags` will be empty
109
+ * @returns An unsigned {@link EventTemplate} with compound `kind:metric` tag names
110
+ *
111
+ * @example
112
+ * const tmpl = buildProviderDeclaration([
113
+ * { kind: 30382, metric: 'rank', servicePubkey: providerPubkey, relayHint: 'wss://relay.example.com' },
114
+ * ])
115
+ * const event = signEvent(tmpl, providerPrivkey)
116
+ * await relay.publish(event)
117
+ */
118
+ export function buildProviderDeclaration(providers, encryptedContent) {
119
+ const tags = providers.map(p => [`${p.kind}:${p.metric}`, p.servicePubkey, p.relayHint]);
120
+ return {
121
+ kind: NIP85_KINDS.PROVIDER,
122
+ tags: encryptedContent ? [] : tags,
123
+ content: encryptedContent ?? '',
124
+ };
125
+ }
126
+ //# sourceMappingURL=builders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builders.js","sourceRoot":"","sources":["../../src/nip85/builders.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAIxC,MAAM,QAAQ,GAAG,gBAAgB,CAAA;AAEjC,SAAS,aAAa,CAAC,KAAa,EAAE,KAAa;IACjD,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,sDAAsD,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC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ay query filter for NIP-85 assertion events.
9
+ *
10
+ * @param params - Filter parameters
11
+ * @param params.kind - The assertion kind (30382–30385)
12
+ * @param params.subject - Optional subject pubkey / identifier to filter by `#d`
13
+ * @param params.provider - Optional provider pubkey to filter by `authors`
14
+ * @returns A {@link NostrFilter} ready to pass to a relay subscription
15
+ *
16
+ * @example
17
+ * const filter = assertionFilter({ kind: 30382, subject: alicePubkey, provider: providerPubkey })
18
+ * relay.subscribe([filter], onEvent)
19
+ */
20
+ export declare function assertionFilter(params: {
21
+ kind: number;
22
+ subject?: string;
23
+ provider?: string;
24
+ }): NostrFilter;
25
+ /**
26
+ * Builds a relay query filter for a provider's kind 10040 declaration event.
27
+ *
28
+ * @param pubkey - The provider's hex-encoded public key (64 chars)
29
+ * @returns A {@link NostrFilter} scoped to kind 10040 for the given author
30
+ *
31
+ * @example
32
+ * const filter = providerFilter(providerPubkey)
33
+ * relay.subscribe([filter], onProviderDeclaration)
34
+ */
35
+ export declare function providerFilter(pubkey: string): NostrFilter;
36
+ //# sourceMappingURL=filters.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filters.d.ts","sourceRoot":"","sources":["../../src/nip85/filters.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,WAAW;IAC1B,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE;IACtC,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,GAAG,WAAW,CASd;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,CAK1D"}