libp2r2p 0.8.0 → 0.10.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 (49) hide show
  1. package/README.md +72 -45
  2. package/base16/index.js +6 -3
  3. package/base36/index.js +12 -8
  4. package/base62/index.js +15 -11
  5. package/base64/index.js +18 -2
  6. package/base93/index.js +19 -7
  7. package/content-key/event/index.js +40 -12
  8. package/double-dh/index.js +21 -6
  9. package/ecdh/index.js +12 -1
  10. package/error/index.js +32 -0
  11. package/event/helpers/serialize.js +31 -0
  12. package/event/index.js +116 -0
  13. package/idb/index.js +5 -3
  14. package/idb-queue/index.js +21 -20
  15. package/index.js +10 -1
  16. package/key/index.js +31 -18
  17. package/kind/index.js +244 -0
  18. package/nip04/index.js +47 -0
  19. package/nip05/index.js +61 -0
  20. package/nip19/index.js +176 -43
  21. package/nip44/helpers.js +95 -0
  22. package/nip44/index.js +14 -0
  23. package/nip44-v3/index.js +35 -16
  24. package/nip46/helpers/frame.js +6 -6
  25. package/nip46/helpers/url.js +8 -6
  26. package/nip46/services/bunker-signer.js +7 -6
  27. package/nip46/services/client.js +8 -7
  28. package/nip46/services/server-session.js +8 -7
  29. package/nip46/services/transport.js +9 -8
  30. package/nip96/index.js +285 -0
  31. package/nip98/index.js +56 -0
  32. package/nwt/index.js +241 -0
  33. package/package.json +22 -5
  34. package/private-channel/helpers/chunks.js +7 -6
  35. package/private-channel/helpers/event.js +5 -4
  36. package/private-channel/index.js +63 -61
  37. package/private-channel/services/received-chunks.js +4 -3
  38. package/private-message/index.js +32 -31
  39. package/private-messenger/index.js +23 -22
  40. package/private-messenger/recovery/index.js +15 -14
  41. package/private-messenger/services/channel-state.js +2 -1
  42. package/relay/helpers/hll.js +3 -1
  43. package/relay/services/query.js +3 -3
  44. package/relay/services/relay-connection.js +222 -121
  45. package/relay/services/relay-pool.js +13 -10
  46. package/temporary-storage/index.js +3 -1
  47. package/url/index.js +131 -0
  48. package/web-storage-queue/index.js +8 -6
  49. package/i18n/index.js +0 -235
package/nip96/index.js ADDED
@@ -0,0 +1,285 @@
1
+ import { sha256 } from '@noble/hashes/sha2.js'
2
+
3
+ import { bytesToBase16 } from '../base16/index.js'
4
+ import { ValidationError } from '../error/index.js'
5
+ import { FILE_SERVER_PREFERENCE } from '../kind/index.js'
6
+
7
+ const WELL_KNOWN_PATH = '/.well-known/nostr/nip96.json'
8
+
9
+ function isValidHttpUrl (value) {
10
+ try {
11
+ const url = new URL(value)
12
+ return url.protocol === 'http:' || url.protocol === 'https:'
13
+ } catch {
14
+ return false
15
+ }
16
+ }
17
+
18
+ function combineSignal (signal, timeoutMs) {
19
+ if (signal?.aborted) throw signal.reason ?? new DOMException('This operation was aborted', 'AbortError')
20
+ const controller = new AbortController()
21
+ const onAbort = () => controller.abort(signal.reason)
22
+ signal?.addEventListener('abort', onAbort, { once: true })
23
+ const timeout = Number.isFinite(timeoutMs) && timeoutMs >= 0
24
+ ? setTimeout(() => controller.abort(new DOMException('NIP-96 request timed out', 'TimeoutError')), timeoutMs)
25
+ : null
26
+ return {
27
+ signal: controller.signal,
28
+ cleanup () {
29
+ if (timeout !== null) clearTimeout(timeout)
30
+ signal?.removeEventListener('abort', onAbort)
31
+ }
32
+ }
33
+ }
34
+
35
+ async function fetchJson (url, options, { fetch: fetchImpl = globalThis.fetch, signal, timeoutMs = 10000 } = {}) {
36
+ if (typeof fetchImpl !== 'function') throw new Error('FETCH_IS_NOT_AVAILABLE')
37
+ const combined = combineSignal(signal, timeoutMs)
38
+ try {
39
+ const response = await fetchImpl(url, { ...options, signal: combined.signal })
40
+ if (!response.ok) {
41
+ const error = new Error(`NIP-96 request failed with status ${response.status}`)
42
+ error.status = response.status
43
+ throw error
44
+ }
45
+ try {
46
+ return { response, data: await response.json() }
47
+ } catch (cause) {
48
+ throw new ValidationError('INVALID_NIP96_JSON_RESPONSE', { cause })
49
+ }
50
+ } finally {
51
+ combined.cleanup()
52
+ }
53
+ }
54
+
55
+ function serverConfigurationError (config) {
56
+ if (!config || typeof config !== 'object' || Array.isArray(config)) return 'INVALID_NIP96_SERVER_CONFIGURATION'
57
+ const hasApi = typeof config.api_url === 'string' && config.api_url.length > 0
58
+ const hasDelegation = typeof config.delegated_to_url === 'string' && config.delegated_to_url.length > 0
59
+ if (!hasApi && !hasDelegation) return 'NIP96_SERVER_CONFIGURATION_SOURCE_REQUIRED'
60
+ if (hasApi && hasDelegation) return 'NIP96_SERVER_CONFIGURATION_SOURCE_CONFLICT'
61
+ if (hasApi && !isValidHttpUrl(config.api_url)) return 'INVALID_NIP96_API_URL'
62
+ if (hasDelegation && !isValidHttpUrl(config.delegated_to_url)) return 'INVALID_NIP96_DELEGATION_URL'
63
+ if (config.download_url !== undefined && !isValidHttpUrl(config.download_url)) return 'INVALID_NIP96_DOWNLOAD_URL'
64
+ return null
65
+ }
66
+
67
+ export function isValidServerConfiguration (config) {
68
+ return serverConfigurationError(config) === null
69
+ }
70
+
71
+ export function assertValidServerConfiguration (config) {
72
+ const code = serverConfigurationError(config)
73
+ if (code) throw new ValidationError(code)
74
+ return config
75
+ }
76
+
77
+ export async function readServerConfig ({ serverUrl, fetch, signal, timeoutMs = 10000 }) {
78
+ if (!isValidHttpUrl(serverUrl)) throw new ValidationError('INVALID_SERVER_URL')
79
+ const firstUrl = new URL(WELL_KNOWN_PATH, new URL(serverUrl).origin)
80
+ const first = await fetchJson(firstUrl, { headers: { Accept: 'application/json' } }, { fetch, signal, timeoutMs })
81
+ assertValidServerConfiguration(first.data)
82
+ if (!first.data.delegated_to_url) return first.data
83
+
84
+ const delegated = await fetchJson(first.data.delegated_to_url, { headers: { Accept: 'application/json' } }, { fetch, signal, timeoutMs })
85
+ try {
86
+ assertValidServerConfiguration(delegated.data)
87
+ } catch (cause) {
88
+ throw new ValidationError('INVALID_DELEGATED_SERVER_CONFIGURATION', { cause })
89
+ }
90
+ if (delegated.data.delegated_to_url) throw new ValidationError('INVALID_DELEGATED_SERVER_CONFIGURATION')
91
+ return delegated.data
92
+ }
93
+
94
+ function fileUploadResponseError (response) {
95
+ if (!response || typeof response !== 'object' || Array.isArray(response)) return 'INVALID_NIP96_FILE_UPLOAD_RESPONSE'
96
+ if (!['success', 'error', 'processing'].includes(response.status)) return 'INVALID_NIP96_UPLOAD_STATUS'
97
+ if (typeof response.message !== 'string') return 'INVALID_NIP96_UPLOAD_MESSAGE'
98
+ if (response.status === 'processing' && !isValidHttpUrl(response.processing_url)) return 'INVALID_NIP96_PROCESSING_URL'
99
+ if (response.processing_url !== undefined && !isValidHttpUrl(response.processing_url)) return 'INVALID_NIP96_PROCESSING_URL'
100
+ if (response.status === 'success' && !response.nip94_event) return 'NIP96_FILE_METADATA_REQUIRED'
101
+ if (response.nip94_event !== undefined) {
102
+ const { tags } = response.nip94_event
103
+ if (!Array.isArray(tags) || tags.some(tag => !Array.isArray(tag) || tag.length < 2 || tag.some(value => typeof value !== 'string'))) return 'INVALID_NIP94_TAGS'
104
+ if (!tags.some(tag => tag[0] === 'url' && isValidHttpUrl(tag[1]))) return 'NIP94_URL_TAG_REQUIRED'
105
+ if (!tags.some(tag => tag[0] === 'ox' && /^[0-9a-f]{64}$/.test(tag[1]))) return 'NIP94_ORIGINAL_HASH_TAG_REQUIRED'
106
+ }
107
+ return null
108
+ }
109
+
110
+ export function isValidFileUploadResponse (response) {
111
+ return fileUploadResponseError(response) === null
112
+ }
113
+
114
+ export function assertValidFileUploadResponse (response) {
115
+ const code = fileUploadResponseError(response)
116
+ if (code) throw new ValidationError(code)
117
+ return response
118
+ }
119
+
120
+ function uploadError (status) {
121
+ const messages = {
122
+ 400: 'Bad request! Some fields are missing or invalid!',
123
+ 402: 'Payment required!',
124
+ 403: 'Forbidden! Payload tag does not match the requested file!',
125
+ 413: 'File too large!'
126
+ }
127
+ const error = new Error(messages[status] ?? 'Unknown error in uploading file!')
128
+ error.status = status
129
+ return error
130
+ }
131
+
132
+ function makeFormData (file, optionalFormDataFields) {
133
+ const formData = new FormData()
134
+ for (const [key, value] of Object.entries(optionalFormDataFields ?? {})) {
135
+ if (value !== undefined) formData.append(key, value)
136
+ }
137
+ formData.append('file', file)
138
+ return formData
139
+ }
140
+
141
+ function emitProgress (onProgress, event) {
142
+ if (typeof onProgress !== 'function') return
143
+ try { onProgress(event) } catch (error) { console.error('NIP-96 progress callback failed:', error) }
144
+ }
145
+
146
+ function uploadWithXhr ({ file, serverApiUrl, nip98AuthorizationHeader, optionalFormDataFields, onProgress, signal, timeoutMs, xhrFactory }) {
147
+ return new Promise((resolve, reject) => {
148
+ const xhr = xhrFactory ? xhrFactory() : new XMLHttpRequest()
149
+ const onAbort = () => xhr.abort()
150
+ const settle = callback => value => {
151
+ signal?.removeEventListener('abort', onAbort)
152
+ callback(value)
153
+ }
154
+ const resolveUpload = settle(resolve)
155
+ const rejectUpload = settle(reject)
156
+ xhr.open('POST', serverApiUrl, true)
157
+ if (nip98AuthorizationHeader) xhr.setRequestHeader('Authorization', nip98AuthorizationHeader)
158
+ if (Number.isFinite(timeoutMs) && timeoutMs >= 0) xhr.timeout = timeoutMs
159
+ xhr.upload.addEventListener('progress', event => emitProgress(onProgress, event))
160
+ xhr.addEventListener('abort', () => rejectUpload(signal?.reason ?? new DOMException('This operation was aborted', 'AbortError')))
161
+ xhr.addEventListener('timeout', () => rejectUpload(new DOMException('NIP-96 request timed out', 'TimeoutError')))
162
+ xhr.addEventListener('error', () => rejectUpload(new Error('NIP-96 upload failed')))
163
+ xhr.addEventListener('load', () => {
164
+ if (xhr.status < 200 || xhr.status >= 300) return rejectUpload(uploadError(xhr.status))
165
+ let data
166
+ try { data = JSON.parse(xhr.responseText) } catch (cause) {
167
+ return rejectUpload(new ValidationError('INVALID_UPLOAD_RESPONSE_JSON', { cause }))
168
+ }
169
+ try {
170
+ resolveUpload(assertValidFileUploadResponse(data))
171
+ } catch (error) {
172
+ rejectUpload(error)
173
+ }
174
+ })
175
+ if (signal?.aborted) return rejectUpload(signal.reason ?? new DOMException('This operation was aborted', 'AbortError'))
176
+ signal?.addEventListener('abort', onAbort, { once: true })
177
+ xhr.send(makeFormData(file, optionalFormDataFields))
178
+ })
179
+ }
180
+
181
+ export async function uploadFile ({
182
+ file,
183
+ serverApiUrl,
184
+ nip98AuthorizationHeader,
185
+ optionalFormDataFields = {},
186
+ onProgress,
187
+ signal,
188
+ timeoutMs = 30000,
189
+ fetch: fetchImpl,
190
+ xhrFactory
191
+ }) {
192
+ if (!file || !isValidHttpUrl(serverApiUrl)) throw new ValidationError('INVALID_UPLOAD_ARGUMENTS')
193
+ if (!fetchImpl && (xhrFactory || typeof XMLHttpRequest === 'function') && typeof onProgress === 'function') {
194
+ return uploadWithXhr({ file, serverApiUrl, nip98AuthorizationHeader, optionalFormDataFields, onProgress, signal, timeoutMs, xhrFactory })
195
+ }
196
+
197
+ const total = Number.isFinite(file.size) ? file.size : 0
198
+ emitProgress(onProgress, { lengthComputable: Number.isFinite(file.size), loaded: 0, total })
199
+ let result
200
+ try {
201
+ result = await fetchJson(serverApiUrl, {
202
+ method: 'POST',
203
+ headers: nip98AuthorizationHeader ? { Authorization: nip98AuthorizationHeader } : {},
204
+ body: makeFormData(file, optionalFormDataFields)
205
+ }, { fetch: fetchImpl, signal, timeoutMs })
206
+ } catch (error) {
207
+ if (error.status) throw uploadError(error.status)
208
+ throw error
209
+ }
210
+ assertValidFileUploadResponse(result.data)
211
+ emitProgress(onProgress, { lengthComputable: Number.isFinite(file.size), loaded: total, total })
212
+ return result.data
213
+ }
214
+
215
+ export function generateDownloadUrl ({ fileHash, serverDownloadUrl, fileExtension = '' }) {
216
+ if (typeof fileHash !== 'string' || !isValidHttpUrl(serverDownloadUrl) || typeof fileExtension !== 'string') {
217
+ throw new ValidationError('INVALID_DOWNLOAD_ARGUMENTS')
218
+ }
219
+ return `${serverDownloadUrl.replace(/\/$/, '')}/${fileHash}${fileExtension}`
220
+ }
221
+
222
+ export async function deleteFile ({ fileHash, serverApiUrl, nip98AuthorizationHeader, fetch, signal, timeoutMs = 10000 }) {
223
+ const url = generateDownloadUrl({ fileHash, serverDownloadUrl: serverApiUrl })
224
+ const result = await fetchJson(url, {
225
+ method: 'DELETE',
226
+ headers: nip98AuthorizationHeader ? { Authorization: nip98AuthorizationHeader } : {}
227
+ }, { fetch, signal, timeoutMs })
228
+ return result.data
229
+ }
230
+
231
+ function delayedProcessingResponseError (response) {
232
+ if (!response || typeof response !== 'object' || Array.isArray(response)) return 'INVALID_NIP96_DELAYED_RESPONSE'
233
+ if (!['processing', 'error'].includes(response.status)) return 'INVALID_NIP96_DELAYED_STATUS'
234
+ if (typeof response.message !== 'string') return 'INVALID_NIP96_DELAYED_MESSAGE'
235
+ if (typeof response.percentage !== 'number' || !Number.isFinite(response.percentage) ||
236
+ response.percentage < 0 || response.percentage > 100) return 'INVALID_NIP96_DELAYED_PERCENTAGE'
237
+ return null
238
+ }
239
+
240
+ export function isValidDelayedProcessingResponse (response) {
241
+ return delayedProcessingResponseError(response) === null
242
+ }
243
+
244
+ export function assertValidDelayedProcessingResponse (response) {
245
+ const code = delayedProcessingResponseError(response)
246
+ if (code) throw new ValidationError(code)
247
+ return response
248
+ }
249
+
250
+ export async function checkFileProcessingStatus ({ processingUrl, fetch, signal, timeoutMs = 10000 }) {
251
+ if (!isValidHttpUrl(processingUrl)) throw new ValidationError('INVALID_PROCESSING_URL')
252
+ const { response, data } = await fetchJson(processingUrl, {}, { fetch, signal, timeoutMs })
253
+ if (response.status === 201) return assertValidFileUploadResponse(data)
254
+ if (response.status === 200) return assertValidDelayedProcessingResponse(data)
255
+ throw new ValidationError('INVALID_PROCESSING_RESPONSE')
256
+ }
257
+
258
+ export function generateFSPEventTemplate ({ serverUrls, createdAt = Math.floor(Date.now() / 1000) }) {
259
+ if (!Array.isArray(serverUrls)) throw new ValidationError('SERVER_URLS_SHOULD_BE_AN_ARRAY')
260
+ return {
261
+ kind: FILE_SERVER_PREFERENCE,
262
+ content: '',
263
+ tags: serverUrls.filter(isValidHttpUrl).map(serverUrl => ['server', serverUrl]),
264
+ created_at: createdAt
265
+ }
266
+ }
267
+
268
+ export async function calculateFileHash (file) {
269
+ if (!file || typeof file.stream !== 'function') {
270
+ if (!file || typeof file.arrayBuffer !== 'function') throw new ValidationError('FILE_SHOULD_BE_A_BLOB')
271
+ return bytesToBase16(sha256(new Uint8Array(await file.arrayBuffer())))
272
+ }
273
+ const hash = sha256.create()
274
+ const reader = file.stream().getReader()
275
+ try {
276
+ while (true) {
277
+ const { done, value } = await reader.read()
278
+ if (done) break
279
+ hash.update(value)
280
+ }
281
+ return bytesToBase16(hash.digest())
282
+ } finally {
283
+ reader.releaseLock()
284
+ }
285
+ }
package/nip98/index.js ADDED
@@ -0,0 +1,56 @@
1
+ import { sha256 } from '@noble/hashes/sha2.js'
2
+
3
+ import { bytesToBase16 } from '../base16/index.js'
4
+ import { bytesToBase64 } from '../base64/index.js'
5
+ import { ValidationError } from '../error/index.js'
6
+ import { isValidEvent } from '../event/index.js'
7
+ import { HTTP_AUTH } from '../kind/index.js'
8
+
9
+ const encoder = new TextEncoder()
10
+ const PAYLOAD_HASH = /^[0-9a-f]{64}$/
11
+
12
+ async function payloadBytes (payload) {
13
+ if (typeof payload === 'string') return encoder.encode(payload)
14
+ if (payload instanceof Uint8Array) return payload
15
+ if (payload instanceof ArrayBuffer) return new Uint8Array(payload)
16
+ if (ArrayBuffer.isView(payload)) return new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength)
17
+ if (typeof Blob === 'function' && payload instanceof Blob) return new Uint8Array(await payload.arrayBuffer())
18
+ throw new ValidationError('INVALID_PAYLOAD')
19
+ }
20
+
21
+ export async function getToken ({
22
+ loginUrl,
23
+ httpMethod,
24
+ signEvent,
25
+ includeAuthorizationScheme = false,
26
+ payload,
27
+ payloadHash
28
+ }) {
29
+ if (typeof loginUrl !== 'string' || loginUrl.length === 0) throw new ValidationError('INVALID_LOGIN_URL')
30
+ try { new URL(loginUrl) } catch (cause) { throw new ValidationError('INVALID_LOGIN_URL', { cause }) }
31
+ if (typeof httpMethod !== 'string' || httpMethod.trim().length === 0) throw new ValidationError('INVALID_HTTP_METHOD')
32
+ if (typeof signEvent !== 'function') throw new ValidationError('SIGN_EVENT_SHOULD_BE_A_FUNCTION')
33
+ if (payload !== undefined && payloadHash !== undefined) throw new ValidationError('PAYLOAD_AND_HASH_ARE_MUTUALLY_EXCLUSIVE')
34
+
35
+ let hash = payloadHash
36
+ if (payload !== undefined) hash = bytesToBase16(sha256(await payloadBytes(payload)))
37
+ if (hash !== undefined && !PAYLOAD_HASH.test(hash)) throw new ValidationError('INVALID_PAYLOAD_HASH')
38
+
39
+ const method = httpMethod.trim().toUpperCase()
40
+ const tags = [['u', loginUrl], ['method', method]]
41
+ if (hash !== undefined) tags.push(['payload', hash])
42
+ const event = await signEvent({
43
+ kind: HTTP_AUTH,
44
+ created_at: Math.floor(Date.now() / 1000),
45
+ tags,
46
+ content: ''
47
+ })
48
+ if (!isValidEvent(event) || event.kind !== HTTP_AUTH) throw new ValidationError('INVALID_SIGNED_HTTP_AUTH_EVENT')
49
+ if (!event.tags.some(tag => tag[0] === 'u' && tag[1] === loginUrl) ||
50
+ !event.tags.some(tag => tag[0] === 'method' && tag[1] === method) ||
51
+ (hash !== undefined && !event.tags.some(tag => tag[0] === 'payload' && tag[1] === hash))) {
52
+ throw new ValidationError('SIGNED_HTTP_AUTH_EVENT_WAS_CHANGED')
53
+ }
54
+ const token = bytesToBase64(encoder.encode(JSON.stringify(event)))
55
+ return includeAuthorizationScheme ? `Nostr ${token}` : token
56
+ }
package/nwt/index.js ADDED
@@ -0,0 +1,241 @@
1
+ import { base64UrlToBytes, bytesToBase64Url } from '../base64/index.js'
2
+ import { ValidationError } from '../error/index.js'
3
+ import { isValidEvent } from '../event/index.js'
4
+ import { NWT } from '../kind/index.js'
5
+
6
+ const textDecoder = new TextDecoder('utf-8', { fatal: true })
7
+ const textEncoder = new TextEncoder()
8
+ const BASE64URL = /^[A-Za-z0-9_-]+$/
9
+ const REGISTERED_CLAIMS = new Set(['iss', 'sub', 'aud', 'iat', 'exp', 'nbf'])
10
+ const SINGLE_CLAIMS = new Set(['iss', 'sub', 'iat', 'exp', 'nbf'])
11
+ const TIMESTAMP_CLAIMS = new Set(['iat', 'exp', 'nbf'])
12
+ const MAX_CLAIMS = 512
13
+
14
+ function fail (code, { message = code, cause } = {}) {
15
+ throw new ValidationError(code, { message, cause })
16
+ }
17
+
18
+ function cloneTags (tags) {
19
+ return tags.map(tag => tag.slice())
20
+ }
21
+
22
+ function areTagsEqual (left, right) {
23
+ return left.length === right.length && left.every((tag, index) => {
24
+ const other = right[index]
25
+ return tag.length === other.length && tag.every((value, valueIndex) => value === other[valueIndex])
26
+ })
27
+ }
28
+
29
+ function normalizeTimestamp (value, code) {
30
+ if (!Number.isSafeInteger(value) || value < 0) fail(code)
31
+ return value
32
+ }
33
+
34
+ function parseTimestamp (value, code) {
35
+ if (!/^(?:0|[1-9][0-9]*)$/.test(value)) fail(code)
36
+ return normalizeTimestamp(Number(value), code)
37
+ }
38
+
39
+ function normalizeStringClaim (value, code) {
40
+ if (typeof value !== 'string' || value.length === 0) fail(code)
41
+ return value
42
+ }
43
+
44
+ function normalizeAudience (audience, { required = false } = {}) {
45
+ if (audience === undefined) {
46
+ if (required) fail('INVALID_AUDIENCE')
47
+ return []
48
+ }
49
+ const values = typeof audience === 'string' ? [audience] : audience
50
+ if (!Array.isArray(values) || (required && values.length === 0)) fail('INVALID_AUDIENCE')
51
+ return values.map(value => normalizeStringClaim(value, 'INVALID_AUDIENCE'))
52
+ }
53
+
54
+ function normalizeExtraClaims (claims) {
55
+ if (claims === undefined) return []
56
+ if (!Array.isArray(claims)) fail('INVALID_CLAIMS')
57
+ return claims.map(tag => {
58
+ if (!Array.isArray(tag) || tag.length < 2 || tag.some(value => typeof value !== 'string')) fail('INVALID_CLAIM')
59
+ if (tag[0].length === 0 || REGISTERED_CLAIMS.has(tag[0])) fail('INVALID_CUSTOM_CLAIM')
60
+ return tag.slice()
61
+ })
62
+ }
63
+
64
+ function parseClaims (event) {
65
+ if (event.tags.length > MAX_CLAIMS) fail('TOO_MANY_CLAIMS')
66
+
67
+ const single = new Map()
68
+ const audience = []
69
+ const claims = []
70
+
71
+ for (const tag of event.tags) {
72
+ if (tag.length < 2 || tag[0].length === 0) fail('INVALID_CLAIM')
73
+ const name = tag[0]
74
+
75
+ if (!REGISTERED_CLAIMS.has(name)) {
76
+ claims.push(tag.slice())
77
+ continue
78
+ }
79
+ if (tag.length !== 2 || tag[1].length === 0) fail('INVALID_REGISTERED_CLAIM')
80
+ if (name === 'aud') {
81
+ audience.push(tag[1])
82
+ continue
83
+ }
84
+ if (SINGLE_CLAIMS.has(name) && single.has(name)) fail('DUPLICATE_SINGLE_CLAIM')
85
+ single.set(name, TIMESTAMP_CLAIMS.has(name)
86
+ ? parseTimestamp(tag[1], `INVALID_${name.toUpperCase()}_CLAIM`)
87
+ : tag[1])
88
+ }
89
+
90
+ const expiration = single.get('exp') ?? null
91
+ const notBefore = single.get('nbf') ?? null
92
+ if (expiration !== null && notBefore !== null && notBefore > expiration) fail('INVALID_TIME_WINDOW')
93
+
94
+ return {
95
+ event,
96
+ id: event.id,
97
+ signer: event.pubkey,
98
+ issuer: single.get('iss') ?? event.pubkey,
99
+ subject: single.get('sub') ?? event.pubkey,
100
+ audience,
101
+ issuedAt: single.get('iat') ?? event.created_at,
102
+ expiration,
103
+ notBefore,
104
+ claims,
105
+ content: event.content
106
+ }
107
+ }
108
+
109
+ function parseVerifiedEvent (event) {
110
+ if (!isValidEvent(event)) fail('INVALID_NWT_EVENT')
111
+ if (event.kind !== NWT) fail('INVALID_NWT_KIND')
112
+ return parseClaims(event)
113
+ }
114
+
115
+ function wireEvent (event) {
116
+ return {
117
+ id: event.id,
118
+ pubkey: event.pubkey,
119
+ created_at: event.created_at,
120
+ kind: event.kind,
121
+ tags: cloneTags(event.tags),
122
+ content: event.content,
123
+ sig: event.sig
124
+ }
125
+ }
126
+
127
+ export async function createToken ({
128
+ signEvent,
129
+ issuer,
130
+ subject,
131
+ audience,
132
+ issuedAt,
133
+ expiration,
134
+ notBefore,
135
+ claims,
136
+ content = '',
137
+ createdAt = Math.floor(Date.now() / 1000)
138
+ } = {}) {
139
+ if (typeof signEvent !== 'function') fail('SIGN_EVENT_SHOULD_BE_A_FUNCTION')
140
+ if (typeof content !== 'string') fail('INVALID_CONTENT')
141
+
142
+ const tags = []
143
+ if (issuer !== undefined) tags.push(['iss', normalizeStringClaim(issuer, 'INVALID_ISSUER')])
144
+ if (subject !== undefined) tags.push(['sub', normalizeStringClaim(subject, 'INVALID_SUBJECT')])
145
+ for (const value of normalizeAudience(audience)) tags.push(['aud', value])
146
+ if (issuedAt !== undefined) tags.push(['iat', String(normalizeTimestamp(issuedAt, 'INVALID_ISSUED_AT'))])
147
+ if (expiration !== undefined) tags.push(['exp', String(normalizeTimestamp(expiration, 'INVALID_EXPIRATION'))])
148
+ if (notBefore !== undefined) tags.push(['nbf', String(normalizeTimestamp(notBefore, 'INVALID_NOT_BEFORE'))])
149
+ tags.push(...normalizeExtraClaims(claims))
150
+ if (tags.length > MAX_CLAIMS) fail('TOO_MANY_CLAIMS')
151
+
152
+ const expected = {
153
+ kind: NWT,
154
+ created_at: normalizeTimestamp(createdAt, 'INVALID_CREATED_AT'),
155
+ tags,
156
+ content
157
+ }
158
+ if (expiration !== undefined && notBefore !== undefined && notBefore > expiration) fail('INVALID_TIME_WINDOW')
159
+
160
+ const event = await signEvent({ ...expected, tags: cloneTags(expected.tags) })
161
+ parseVerifiedEvent(event)
162
+ if (
163
+ event.kind !== expected.kind ||
164
+ event.created_at !== expected.created_at ||
165
+ event.content !== expected.content ||
166
+ !areTagsEqual(event.tags, expected.tags)
167
+ ) fail('SIGNED_NWT_EVENT_WAS_CHANGED')
168
+ return event
169
+ }
170
+
171
+ export function encodeToken (event, { includeAuthorizationScheme = false } = {}) {
172
+ parseVerifiedEvent(event)
173
+ const token = bytesToBase64Url(textEncoder.encode(JSON.stringify(wireEvent(event))))
174
+ return includeAuthorizationScheme ? `Nostr ${token}` : token
175
+ }
176
+
177
+ export function decodeToken (value) {
178
+ if (typeof value !== 'string' || value.length === 0) fail('INVALID_NWT_TOKEN')
179
+ let token = value
180
+ if (value.startsWith('Nostr ')) token = value.slice(6)
181
+ else if (/\s/.test(value)) fail('INVALID_AUTHORIZATION_HEADER')
182
+ if (!BASE64URL.test(token) || token.length % 4 === 1) fail('INVALID_NWT_ENCODING')
183
+
184
+ let bytes
185
+ try {
186
+ bytes = base64UrlToBytes(token)
187
+ if (bytesToBase64Url(bytes) !== token) fail('INVALID_NWT_ENCODING')
188
+ } catch (cause) {
189
+ fail('INVALID_NWT_ENCODING', { cause })
190
+ }
191
+
192
+ try {
193
+ const event = JSON.parse(textDecoder.decode(bytes))
194
+ if (!event || typeof event !== 'object' || Array.isArray(event)) fail('INVALID_NWT_EVENT_JSON')
195
+ return event
196
+ } catch (error) {
197
+ if (error instanceof ValidationError && error.code === 'INVALID_NWT_EVENT_JSON') throw error
198
+ fail('INVALID_NWT_EVENT_JSON', { cause: error })
199
+ }
200
+ }
201
+
202
+ export function validateToken (value, {
203
+ audience,
204
+ signer,
205
+ issuer,
206
+ subject,
207
+ now = Math.floor(Date.now() / 1000),
208
+ clockSkewSeconds = 60,
209
+ requireAudience = false,
210
+ requireExpiration = false
211
+ } = {}) {
212
+ const event = typeof value === 'string' ? decodeToken(value) : value
213
+ const token = parseVerifiedEvent(event)
214
+ normalizeTimestamp(now, 'INVALID_NOW')
215
+ normalizeTimestamp(clockSkewSeconds, 'INVALID_CLOCK_SKEW')
216
+ if (!Number.isSafeInteger(now + clockSkewSeconds) || !Number.isSafeInteger(now - clockSkewSeconds)) {
217
+ fail('INVALID_CLOCK_SKEW')
218
+ }
219
+
220
+ if (token.notBefore !== null && now + clockSkewSeconds < token.notBefore) fail('NWT_NOT_YET_VALID')
221
+ if (token.expiration !== null && now - clockSkewSeconds >= token.expiration) fail('NWT_EXPIRED')
222
+ if (requireExpiration && token.expiration === null) fail('NWT_EXPIRATION_REQUIRED')
223
+
224
+ if (token.audience.length === 0) {
225
+ if (requireAudience) fail('NWT_AUDIENCE_REQUIRED')
226
+ } else {
227
+ if (audience === undefined) fail('NWT_AUDIENCE_REQUIRED')
228
+ const expectedAudience = normalizeAudience(audience, { required: true })
229
+ if (!expectedAudience.some(value => token.audience.includes(value))) fail('NWT_AUDIENCE_MISMATCH')
230
+ }
231
+
232
+ for (const [expected, actual, code] of [
233
+ [signer, token.signer, 'NWT_SIGNER_MISMATCH'],
234
+ [issuer, token.issuer, 'NWT_ISSUER_MISMATCH'],
235
+ [subject, token.subject, 'NWT_SUBJECT_MISMATCH']
236
+ ]) {
237
+ if (expected !== undefined && normalizeStringClaim(expected, code) !== actual) fail(code)
238
+ }
239
+
240
+ return token
241
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2r2p",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Peer-to-relay-to-peer",
5
5
  "keywords": [
6
6
  "p2r2p",
@@ -20,20 +20,29 @@
20
20
  "content-key",
21
21
  "double-dh",
22
22
  "ecdh",
23
+ "error",
24
+ "event",
23
25
  "idb",
24
26
  "idb-queue",
25
- "i18n",
26
27
  "index.js",
27
28
  "key",
29
+ "kind",
28
30
  "network",
31
+ "nip04",
32
+ "nip05",
29
33
  "nip19",
34
+ "nip44",
30
35
  "nip44-v3",
31
36
  "nip46",
37
+ "nip96",
38
+ "nip98",
39
+ "nwt",
32
40
  "private-channel",
33
41
  "private-message",
34
42
  "private-messenger",
35
43
  "relay",
36
44
  "temporary-storage",
45
+ "url",
37
46
  "web-storage-queue"
38
47
  ],
39
48
  "scripts": {
@@ -51,28 +60,36 @@
51
60
  "./content-key/event": "./content-key/event/index.js",
52
61
  "./double-dh": "./double-dh/index.js",
53
62
  "./ecdh": "./ecdh/index.js",
63
+ "./error": "./error/index.js",
64
+ "./event": "./event/index.js",
54
65
  "./idb": "./idb/index.js",
55
66
  "./idb-queue": "./idb-queue/index.js",
56
- "./i18n": "./i18n/index.js",
57
67
  "./key": "./key/index.js",
68
+ "./kind": "./kind/index.js",
58
69
  "./network": "./network/index.js",
70
+ "./nip04": "./nip04/index.js",
71
+ "./nip05": "./nip05/index.js",
59
72
  "./nip19": "./nip19/index.js",
73
+ "./nip44": "./nip44/index.js",
60
74
  "./nip44-v3": "./nip44-v3/index.js",
61
75
  "./nip46": "./nip46/index.js",
76
+ "./nip96": "./nip96/index.js",
77
+ "./nip98": "./nip98/index.js",
78
+ "./nwt": "./nwt/index.js",
62
79
  "./private-channel": "./private-channel/index.js",
63
80
  "./private-message": "./private-message/index.js",
64
81
  "./private-messenger": "./private-messenger/index.js",
65
82
  "./private-messenger/recovery": "./private-messenger/recovery/index.js",
66
83
  "./relay": "./relay/index.js",
67
84
  "./temporary-storage": "./temporary-storage/index.js",
85
+ "./url": "./url/index.js",
68
86
  "./web-storage-queue": "./web-storage-queue/index.js"
69
87
  },
70
88
  "dependencies": {
71
89
  "@noble/ciphers": "2.2.0",
72
90
  "@noble/curves": "2.2.0",
73
91
  "@noble/hashes": "2.2.0",
74
- "@scure/base": "2.0.0",
75
- "nostr-tools": "2.23.5"
92
+ "@scure/base": "2.0.0"
76
93
  },
77
94
  "devDependencies": {
78
95
  "fake-indexeddb": "6.2.5"