@estiva-app/protocol 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -47,7 +47,7 @@
47
47
  /** Bumped by hand with the version in package.json — `test/version.test.ts`
48
48
  * pins the two together. It exists so "the upgrade reached the app" can be
49
49
  * checked by grepping a built bundle rather than by trusting a lockfile. */
50
- export const PROTOCOL_VERSION = '0.14.0'
50
+ export const PROTOCOL_VERSION = '0.16.0'
51
51
 
52
52
  export {
53
53
  // types
@@ -147,6 +147,7 @@ export {
147
147
  parseQueryResponse,
148
148
  RELAY_PAGE_CEILING,
149
149
  DEFAULT_QUERY_CONCURRENCY,
150
+ MAX_FILTERS_PER_QUERY,
150
151
  Relay,
151
152
  } from './bridge.js'
152
153
 
@@ -226,3 +227,12 @@ export {
226
227
  blockAnchorOf,
227
228
  resolveBlockAnchor,
228
229
  } from './anchors.js'
230
+ export {
231
+ type BlossomVerb,
232
+ type Imeta,
233
+ BLOSSOM_AUTH_TTL_SECS,
234
+ buildBlossomAuth,
235
+ blossomAuthHeader,
236
+ imetaTag,
237
+ imetaOf,
238
+ } from './media.js'
package/src/media.ts ADDED
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Blobs — Blossom authorization and the `imeta` tag that references one.
3
+ *
4
+ * ## Why this is here and not in an app
5
+ *
6
+ * A message's attachment has to be readable by an app that did not post it,
7
+ * which is the whole of CON-12: Peek stored files in Convex, so every other
8
+ * reader saw a message with nothing on it. The wire form is Buzz's own — a
9
+ * content-addressed blob plus an `imeta` tag — and two apps writing that by
10
+ * hand is exactly the drift SHA-3 spent 5,400 lines removing.
11
+ *
12
+ * Nothing here talks to the network. These are the bytes; the fetching belongs
13
+ * to whoever holds a token.
14
+ */
15
+ import type { NostrTag, SignedEvent, UnsignedEvent } from './events.js'
16
+ import { KIND, toNostrSeconds } from './events.js'
17
+ import { authorizationHeaderFor } from './nip98.js'
18
+
19
+ /** What a Blossom authorization permits. One verb per event. */
20
+ export type BlossomVerb = 'upload' | 'get' | 'list' | 'delete'
21
+
22
+ /** How long an authorization stays valid unless the caller says otherwise. */
23
+ export const BLOSSOM_AUTH_TTL_SECS = 300
24
+
25
+ /**
26
+ * A `kind:24242` Blossom authorization — BUD-01/BUD-11.
27
+ *
28
+ * **It is `27235` for blobs.** Never stored and never published: signed, put in
29
+ * an `Authorization: Nostr <base64url(event)>` header, read once and discarded.
30
+ * `buildUnsignedAuthEvent` is its NIP-98 sibling and the same shape of thing.
31
+ *
32
+ * The relay verifies more of this than is obvious, and each of these is a
33
+ * refusal rather than a default (`verify_blossom_auth_event_for_verb`):
34
+ *
35
+ * - **`content` must be non-empty.** BUD-11 calls it a human-readable string,
36
+ * and an empty one is rejected — the easiest of these to omit, because
37
+ * nothing reads it.
38
+ * - **`t` must match the verb being attempted**, so an upload token cannot
39
+ * fetch and a fetch token cannot upload.
40
+ * - **`expiration` is required and must be in the future.**
41
+ * - **`created_at` must sit inside the window**: no more than 5 s ahead of the
42
+ * relay's clock, and no older than its `max_age` (3600 s for a GET).
43
+ * - **`x` must include the blob's sha256** for an upload — BUD-11 §6 asks that
44
+ * *at least one* `x` matches, which is why this takes one and emits one.
45
+ *
46
+ * `server` is optional and omitted by default. The relay accepts a token with
47
+ * no `server` tag; one that carries a *mismatched* host is refused, so a caller
48
+ * that cannot be sure of the canonical host is safer leaving it out.
49
+ */
50
+ export function buildBlossomAuth(
51
+ pubkey: string,
52
+ createdAtMs: number,
53
+ args: {
54
+ verb: BlossomVerb
55
+ /** The blob, lowercase hex. */
56
+ sha256: string
57
+ /** Human-readable, and **required** — the relay refuses an empty one. */
58
+ reason?: string
59
+ /** Seconds from now. Defaults to {@link BLOSSOM_AUTH_TTL_SECS}. */
60
+ ttlSecs?: number
61
+ /** The relay's host, when the caller knows it canonically. */
62
+ server?: string
63
+ },
64
+ ): UnsignedEvent {
65
+ if (!/^[0-9a-f]{64}$/.test(args.sha256)) {
66
+ throw new Error('sha256 must be 64 lowercase hex characters')
67
+ }
68
+ const createdAt = toNostrSeconds(createdAtMs)
69
+ const tags: NostrTag[] = [
70
+ ['t', args.verb],
71
+ ['x', args.sha256],
72
+ ['expiration', String(createdAt + (args.ttlSecs ?? BLOSSOM_AUTH_TTL_SECS))],
73
+ ]
74
+ if (args.server) tags.push(['server', args.server])
75
+ return {
76
+ pubkey,
77
+ created_at: createdAt,
78
+ kind: KIND.BLOSSOM_AUTH,
79
+ tags,
80
+ // Defaulted rather than left to the caller: an empty content is a refusal,
81
+ // and the failure reads as a signature problem rather than a missing field.
82
+ content: args.reason?.trim() || `${args.verb} blob`,
83
+ }
84
+ }
85
+
86
+ /**
87
+ * The header a Blossom request carries: `Nostr <base64(signed event JSON)>`.
88
+ *
89
+ * **The same encoding NIP-98 uses**, and deliberately the same function. BUD-01
90
+ * specifies base64url-without-padding, so a first version of this hand-rolled
91
+ * one — but the relay decodes `URL_SAFE_NO_PAD` and **falls back to `STANDARD`**
92
+ * (`extract_blossom_auth`), so the encoder already in this package is accepted
93
+ * as-is. One encoder, already covered by the NIP-98 tests, rather than a second
94
+ * that differs only in its edge cases.
95
+ */
96
+ export function blossomAuthHeader(signed: SignedEvent): string {
97
+ return authorizationHeaderFor(signed)
98
+ }
99
+
100
+ /** What a message says about one attached blob. */
101
+ export interface Imeta {
102
+ /** The relay-local path, e.g. `/media/<sha256>.jpg`. */
103
+ url: string
104
+ /** MIME type. */
105
+ m: string
106
+ /** sha256, lowercase hex — the blob's identity. */
107
+ x: string
108
+ /** Bytes. */
109
+ size: number
110
+ /** `<width>x<height>`, where the app knows it. */
111
+ dim?: string
112
+ /** Alt text. */
113
+ alt?: string
114
+ /** The relay's generated thumbnail path, `<sha256>.thumb.jpg`. */
115
+ thumb?: string
116
+ /** The name a person gave it. Display only — storage is content-addressed. */
117
+ filename?: string
118
+ }
119
+
120
+ /**
121
+ * One `imeta` tag — NIP-92, as Buzz validates it.
122
+ *
123
+ * Emitted as `["imeta", "url …", "m …", …]`: space-separated key/value pairs
124
+ * inside a single tag, not one tag per field.
125
+ *
126
+ * The relay's allowlist is `url m x size dim blurhash alt thumb fallback
127
+ * duration bitrate image filename`, each at most once, and it checks two things
128
+ * this cannot: that `url` is a **local** `/media/` path, and — through
129
+ * `verify_imeta_blobs` — that **the blob is already stored**. So the upload has
130
+ * to land before the message that names it, and a dangling reference cannot be
131
+ * published at all.
132
+ */
133
+ export function imetaTag(meta: Imeta): NostrTag {
134
+ const parts = [`url ${meta.url}`, `m ${meta.m}`, `x ${meta.x}`, `size ${meta.size}`]
135
+ if (meta.dim) parts.push(`dim ${meta.dim}`)
136
+ if (meta.alt) parts.push(`alt ${meta.alt}`)
137
+ if (meta.thumb) parts.push(`thumb ${meta.thumb}`)
138
+ if (meta.filename) parts.push(`filename ${meta.filename}`)
139
+ return ['imeta', ...parts]
140
+ }
141
+
142
+ /**
143
+ * Read the `imeta` tags off an event.
144
+ *
145
+ * The reader's half, and the reason this file is shared: Ship has to draw what
146
+ * Peek attached without re-deriving the format. Anything missing the four
147
+ * required fields is skipped rather than half-rendered — a tag the relay would
148
+ * not have accepted is not one to guess at.
149
+ */
150
+ export function imetaOf(event: { tags: NostrTag[] }): Imeta[] {
151
+ const out: Imeta[] = []
152
+ for (const tag of event.tags) {
153
+ if (tag[0] !== 'imeta') continue
154
+ const fields: Record<string, string> = {}
155
+ for (const part of tag.slice(1)) {
156
+ const space = part.indexOf(' ')
157
+ if (space <= 0) continue
158
+ const key = part.slice(0, space)
159
+ // First wins: the relay rejects duplicates, so a second is a malformed
160
+ // event rather than an override.
161
+ if (!(key in fields)) fields[key] = part.slice(space + 1)
162
+ }
163
+ const size = Number.parseInt(fields.size ?? '', 10)
164
+ if (!fields.url || !fields.m || !fields.x || !Number.isFinite(size)) continue
165
+ out.push({
166
+ url: fields.url,
167
+ m: fields.m,
168
+ x: fields.x,
169
+ size,
170
+ dim: fields.dim,
171
+ alt: fields.alt,
172
+ thumb: fields.thumb,
173
+ filename: fields.filename,
174
+ })
175
+ }
176
+ return out
177
+ }