@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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AAEH;;4EAE4E;AAC5E,eAAO,MAAM,gBAAgB,WAAW,CAAA;AAExC,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,OAAO,EACZ,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,KAAK,EACV,KAAK,gBAAgB,EAErB,IAAI,EACJ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,mBAAmB,EACnB,yBAAyB,EACzB,iBAAiB,EAEjB,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EAEZ,YAAY,EACZ,YAAY,EACZ,kBAAkB,EAClB,kBAAkB,EAClB,wBAAwB,EACxB,cAAc,EACd,aAAa,EACb,aAAa,EACb,SAAS,EACT,YAAY,EACZ,eAAe,EACf,SAAS,EACT,cAAc,EACd,cAAc,EACd,2BAA2B,GAC5B,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,QAAQ,EACR,UAAU,EACV,WAAW,EACX,UAAU,EACV,UAAU,EACV,YAAY,EACZ,aAAa,GACd,MAAM,YAAY,CAAA;AAEnB,OAAO,EACL,KAAK,aAAa,EAClB,wBAAwB,EACxB,YAAY,EAC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AkB,EAClB,qBAAqB,EACrB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,mBAAmB,EACnB,YAAY,GACb,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EACL,KAAK,WAAW,EAChB,gBAAgB,EAChB,aAAa,EACb,kBAAkB,GACnB,MAAM,cAAc,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AAEH;;4EAE4E;AAC5E,eAAO,MAAM,gBAAgB,WAAW,CAAA;AAExC,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,OAAO,EACZ,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,KAAK,EACV,KAAK,gBAAgB,EAErB,IAAI,EACJ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,mBAAmB,EACnB,yBAAyB,EACzB,iBAAiB,EAEjB,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EAEZ,YAAY,EACZ,YAAY,EACZ,kBAAkB,EAClB,kBAAkB,EAClB,wBAAwB,EACxB,cAAc,EACd,aAAa,EACb,aAAa,EACb,SAAS,EACT,YAAY,EACZ,eAAe,EACf,SAAS,EACT,cAAc,EACd,cAAc,EACd,2BAA2B,GAC5B,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,kBAAkB,EAClB,QAAQ,EACR,UA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AQ,EACR,SAAS,EACT,YAAY,EACZ,YAAY,GACb,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,kBAAkB,EAClB,qBAAqB,EACrB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,mBAAmB,EACnB,YAAY,GACb,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EACL,KAAK,WAAW,EAChB,gBAAgB,EAChB,aAAa,EACb,kBAAkB,GACnB,MAAM,cAAc,CAAA;AACrB,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,KAAK,EACV,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,EACR,OAAO,GACR,MAAM,YAAY,CAAA"}
package/dist/index.js CHANGED
@@ -46,7 +46,7 @@
46
46
  /** Bumped by hand with the version in package.json — `test/version.test.ts`
47
47
  * pins the two together. It exists so "the upgrade reached the app" can be
48
48
  * checked by grepping a built bundle rather than by trusting a lockfile. */
49
- export const PROTOCOL_VERSION = '0.14.0';
49
+ export const PROTOCOL_VERSION = '0.16.0';
50
50
  export {
51
51
  // constants
52
52
  KIND, MAX_EMOJI_CHARS, MAX_MESSAGE_BYTES, MAX_MENTIONS, MAX_RATIONALE_BYTES, RELAY_AUTH_TOLERANCE_SECS, ASSERTION_SUBTYPE,
@@ -57,7 +57,7 @@ buildProfile, parseProfile, buildCreateChannel, buildDeleteChannel, buildEditCha
57
57
  export { encodeNevent, decodeNevent, convertBits, bech32Encode, bech32Decode, encodeNaddr, decodeNaddr, pointerToAddress, addressToPointer, addrToNaddr, naddrToAddr, referenceToPointer, NADDR_RE, findNaddrs, stripNaddrs, encodeNpub, decodeNpub, NOSTR_URI_RE, findNostrUris, } from './nip19.js';
58
58
  export { TIMESTAMP_TOLERANCE_SECS, normalizeUrl, buildUnsignedAuthEvent, base64, authorizationHeaderFor, authorizationHeader, } from './nip98.js';
59
59
  export { publicKeyFromSecret, signEvent, secretKeySigner, } from './sign.js';
60
- export { parsePublishResponse, parseQueryResponse, RELAY_PAGE_CEILING, DEFAULT_QUERY_CONCURRENCY, Relay, } from './bridge.js';
60
+ export { parsePublishResponse, parseQueryResponse, RELAY_PAGE_CEILING, DEFAULT_QUERY_CONCURRENCY, MAX_FILTERS_PER_QUERY, Relay, } from './bridge.js';
61
61
  export { toWebSocketUrl, parseFrame, createLiveRelay, } from './live.js';
62
62
  export { createChannelSubscriptions, } from './subscriptions.js';
63
63
  export { parseInlineMarks, wrapInlineMarks, parseBodySegments, stripInlineFormatting, markersToInlineNodes, inlineNodesToMarkers, inlineNodesToText, } from './content.js';
@@ -65,4 +65,5 @@ export { KNOWN_BLOCK_TYPES, BlockDocumentError, validateBlockDocument, parseBloc
65
65
  export { CONTENT_FORMAT_TAG, BLOCK_DOCUMENT_FORMAT, contentFormatOf, toRenderTree, renderTreeText, standaloneReference, referencesIn, } from './render.js';
66
66
  export { markerTextToBlockDocument, blockDocumentToMarkerText, } from './bridge-content.js';
67
67
  export { BLOCK_ANCHOR_TAG, blockAnchorOf, resolveBlockAnchor, } from './anchors.js';
68
+ export { BLOSSOM_AUTH_TTL_SECS, buildBlossomAuth, blossomAuthHeader, imetaTag, imetaOf, } from './media.js';
68
69
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AAEH;;4EAE4E;AAC5E,MAAM,CAAC,MAAM,gBAAgB,GAAG,QAAQ,CAAA;AAExC,OAAO;AAYL,YAAY;AACZ,IAAI,EACJ,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,mBAAmB,EACnB,yBAAyB,EACzB,iBAAiB;AACjB,8CAA8C;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xB,YAAY,EACZ,sBAAsB,EACtB,MAAM,EACN,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,YAAY,CAAA;AAEnB,OAAO,EAGL,mBAAmB,EACnB,SAAS,EACT,eAAe,GAChB,MAAM,WAAW,CAAA;AAElB,OAAO,EAOL,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,EAClB,yBAAyB,EACzB,qBAAqB,EACrB,KAAK,GACN,MAAM,aAAa,CAAA;AAEpB,OAAO,EAOL,cAAc,EACd,UAAU,EACV,eAAe,GAChB,MAAM,WAAW,CAAA;AAElB,OAAO,EAIL,0BAA0B,GAC3B,MAAM,oBAAoB,CAAA;AAE3B,OAAO,EAML,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,cAAc,CAAA;AAErB,OAAO,EAIL,iBAAiB,EACjB,kBAAkB,EAClB,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,UAAU,EACV,qBAAqB,EACrB,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,YAAY,GACb,MAAM,aAAa,CAAA;AAEpB,OAAO,EAKL,kBAAkB,EAClB,qBAAqB,EACrB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,mBAAmB,EACnB,YAAY,GACb,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAEL,gBAAgB,EAChB,aAAa,EACb,kBAAkB,GACnB,MAAM,cAAc,CAAA;AACrB,OAAO,EAGL,qBAAqB,EACrB,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,EACR,OAAO,GACR,MAAM,YAAY,CAAA"}
@@ -0,0 +1,111 @@
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
+ /** What a Blossom authorization permits. One verb per event. */
17
+ export type BlossomVerb = 'upload' | 'get' | 'list' | 'delete';
18
+ /** How long an authorization stays valid unless the caller says otherwise. */
19
+ export declare const BLOSSOM_AUTH_TTL_SECS = 300;
20
+ /**
21
+ * A `kind:24242` Blossom authorization — BUD-01/BUD-11.
22
+ *
23
+ * **It is `27235` for blobs.** Never stored and never published: signed, put in
24
+ * an `Authorization: Nostr <base64url(event)>` header, read once and discarded.
25
+ * `buildUnsignedAuthEvent` is its NIP-98 sibling and the same shape of thing.
26
+ *
27
+ * The relay verifies more of this than is obvious, and each of these is a
28
+ * refusal rather than a default (`verify_blossom_auth_event_for_verb`):
29
+ *
30
+ * - **`content` must be non-empty.** BUD-11 calls it a human-readable string,
31
+ * and an empty one is rejected — the easiest of these to omit, because
32
+ * nothing reads it.
33
+ * - **`t` must match the verb being attempted**, so an upload token cannot
34
+ * fetch and a fetch token cannot upload.
35
+ * - **`expiration` is required and must be in the future.**
36
+ * - **`created_at` must sit inside the window**: no more than 5 s ahead of the
37
+ * relay's clock, and no older than its `max_age` (3600 s for a GET).
38
+ * - **`x` must include the blob's sha256** for an upload — BUD-11 §6 asks that
39
+ * *at least one* `x` matches, which is why this takes one and emits one.
40
+ *
41
+ * `server` is optional and omitted by default. The relay accepts a token with
42
+ * no `server` tag; one that carries a *mismatched* host is refused, so a caller
43
+ * that cannot be sure of the canonical host is safer leaving it out.
44
+ */
45
+ export declare function buildBlossomAuth(pubkey: string, createdAtMs: number, args: {
46
+ verb: BlossomVerb;
47
+ /** The blob, lowercase hex. */
48
+ sha256: string;
49
+ /** Human-readable, and **required** — the relay refuses an empty one. */
50
+ reason?: string;
51
+ /** Seconds from now. Defaults to {@link BLOSSOM_AUTH_TTL_SECS}. */
52
+ ttlSecs?: number;
53
+ /** The relay's host, when the caller knows it canonically. */
54
+ server?: string;
55
+ }): UnsignedEvent;
56
+ /**
57
+ * The header a Blossom request carries: `Nostr <base64(signed event JSON)>`.
58
+ *
59
+ * **The same encoding NIP-98 uses**, and deliberately the same function. BUD-01
60
+ * specifies base64url-without-padding, so a first version of this hand-rolled
61
+ * one — but the relay decodes `URL_SAFE_NO_PAD` and **falls back to `STANDARD`**
62
+ * (`extract_blossom_auth`), so the encoder already in this package is accepted
63
+ * as-is. One encoder, already covered by the NIP-98 tests, rather than a second
64
+ * that differs only in its edge cases.
65
+ */
66
+ export declare function blossomAuthHeader(signed: SignedEvent): string;
67
+ /** What a message says about one attached blob. */
68
+ export interface Imeta {
69
+ /** The relay-local path, e.g. `/media/<sha256>.jpg`. */
70
+ url: string;
71
+ /** MIME type. */
72
+ m: string;
73
+ /** sha256, lowercase hex — the blob's identity. */
74
+ x: string;
75
+ /** Bytes. */
76
+ size: number;
77
+ /** `<width>x<height>`, where the app knows it. */
78
+ dim?: string;
79
+ /** Alt text. */
80
+ alt?: string;
81
+ /** The relay's generated thumbnail path, `<sha256>.thumb.jpg`. */
82
+ thumb?: string;
83
+ /** The name a person gave it. Display only — storage is content-addressed. */
84
+ filename?: string;
85
+ }
86
+ /**
87
+ * One `imeta` tag — NIP-92, as Buzz validates it.
88
+ *
89
+ * Emitted as `["imeta", "url …", "m …", …]`: space-separated key/value pairs
90
+ * inside a single tag, not one tag per field.
91
+ *
92
+ * The relay's allowlist is `url m x size dim blurhash alt thumb fallback
93
+ * duration bitrate image filename`, each at most once, and it checks two things
94
+ * this cannot: that `url` is a **local** `/media/` path, and — through
95
+ * `verify_imeta_blobs` — that **the blob is already stored**. So the upload has
96
+ * to land before the message that names it, and a dangling reference cannot be
97
+ * published at all.
98
+ */
99
+ export declare function imetaTag(meta: Imeta): NostrTag;
100
+ /**
101
+ * Read the `imeta` tags off an event.
102
+ *
103
+ * The reader's half, and the reason this file is shared: Ship has to draw what
104
+ * Peek attached without re-deriving the format. Anything missing the four
105
+ * required fields is skipped rather than half-rendered — a tag the relay would
106
+ * not have accepted is not one to guess at.
107
+ */
108
+ export declare function imetaOf(event: {
109
+ tags: NostrTag[];
110
+ }): Imeta[];
111
+ //# sourceMappingURL=media.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.d.ts","sourceRoot":"","sources":["../src/media.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAIvE,gEAAgE;AAChE,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAA;AAE9D,8EAA8E;AAC9E,eAAO,MAAM,qBAAqB,MAAM,CAAA;AAExC;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,IAAI,EAAE;IACJ,IAAI,EAAE,WAAW,CAAA;IACjB,+BAA+B;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,yEAAyE;IACzE,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,mEAAmE;IACnE,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,8DAA8D;IAC9D,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,GACA,aAAa,CAoBf;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAE7D;AAED,mDAAmD;AACnD,MAAM,WAAW,KAAK;IACpB,wDAAwD;IACxD,GAAG,EAAE,MAAM,CAAA;IACX,iBAAiB;IACjB,CAAC,EAAE,MAAM,CAAA;IACT,mDAAmD;IACnD,CAAC,EAAE,MAAM,CAAA;IACT,aAAa;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,kDAAkD;IAClD,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,gBAAgB;IAChB,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,kEAAkE;IAClE,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,KAAK,GAAG,QAAQ,CAO9C;AAED;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,QAAQ,EAAE,CAAA;CAAE,GAAG,KAAK,EAAE,CA2B5D"}
package/dist/media.js ADDED
@@ -0,0 +1,130 @@
1
+ import { KIND, toNostrSeconds } from './events.js';
2
+ import { authorizationHeaderFor } from './nip98.js';
3
+ /** How long an authorization stays valid unless the caller says otherwise. */
4
+ export const BLOSSOM_AUTH_TTL_SECS = 300;
5
+ /**
6
+ * A `kind:24242` Blossom authorization — BUD-01/BUD-11.
7
+ *
8
+ * **It is `27235` for blobs.** Never stored and never published: signed, put in
9
+ * an `Authorization: Nostr <base64url(event)>` header, read once and discarded.
10
+ * `buildUnsignedAuthEvent` is its NIP-98 sibling and the same shape of thing.
11
+ *
12
+ * The relay verifies more of this than is obvious, and each of these is a
13
+ * refusal rather than a default (`verify_blossom_auth_event_for_verb`):
14
+ *
15
+ * - **`content` must be non-empty.** BUD-11 calls it a human-readable string,
16
+ * and an empty one is rejected — the easiest of these to omit, because
17
+ * nothing reads it.
18
+ * - **`t` must match the verb being attempted**, so an upload token cannot
19
+ * fetch and a fetch token cannot upload.
20
+ * - **`expiration` is required and must be in the future.**
21
+ * - **`created_at` must sit inside the window**: no more than 5 s ahead of the
22
+ * relay's clock, and no older than its `max_age` (3600 s for a GET).
23
+ * - **`x` must include the blob's sha256** for an upload — BUD-11 §6 asks that
24
+ * *at least one* `x` matches, which is why this takes one and emits one.
25
+ *
26
+ * `server` is optional and omitted by default. The relay accepts a token with
27
+ * no `server` tag; one that carries a *mismatched* host is refused, so a caller
28
+ * that cannot be sure of the canonical host is safer leaving it out.
29
+ */
30
+ export function buildBlossomAuth(pubkey, createdAtMs, args) {
31
+ if (!/^[0-9a-f]{64}$/.test(args.sha256)) {
32
+ throw new Error('sha256 must be 64 lowercase hex characters');
33
+ }
34
+ const createdAt = toNostrSeconds(createdAtMs);
35
+ const tags = [
36
+ ['t', args.verb],
37
+ ['x', args.sha256],
38
+ ['expiration', String(createdAt + (args.ttlSecs ?? BLOSSOM_AUTH_TTL_SECS))],
39
+ ];
40
+ if (args.server)
41
+ tags.push(['server', args.server]);
42
+ return {
43
+ pubkey,
44
+ created_at: createdAt,
45
+ kind: KIND.BLOSSOM_AUTH,
46
+ tags,
47
+ // Defaulted rather than left to the caller: an empty content is a refusal,
48
+ // and the failure reads as a signature problem rather than a missing field.
49
+ content: args.reason?.trim() || `${args.verb} blob`,
50
+ };
51
+ }
52
+ /**
53
+ * The header a Blossom request carries: `Nostr <base64(signed event JSON)>`.
54
+ *
55
+ * **The same encoding NIP-98 uses**, and deliberately the same function. BUD-01
56
+ * specifies base64url-without-padding, so a first version of this hand-rolled
57
+ * one — but the relay decodes `URL_SAFE_NO_PAD` and **falls back to `STANDARD`**
58
+ * (`extract_blossom_auth`), so the encoder already in this package is accepted
59
+ * as-is. One encoder, already covered by the NIP-98 tests, rather than a second
60
+ * that differs only in its edge cases.
61
+ */
62
+ export function blossomAuthHeader(signed) {
63
+ return authorizationHeaderFor(signed);
64
+ }
65
+ /**
66
+ * One `imeta` tag — NIP-92, as Buzz validates it.
67
+ *
68
+ * Emitted as `["imeta", "url …", "m …", …]`: space-separated key/value pairs
69
+ * inside a single tag, not one tag per field.
70
+ *
71
+ * The relay's allowlist is `url m x size dim blurhash alt thumb fallback
72
+ * duration bitrate image filename`, each at most once, and it checks two things
73
+ * this cannot: that `url` is a **local** `/media/` path, and — through
74
+ * `verify_imeta_blobs` — that **the blob is already stored**. So the upload has
75
+ * to land before the message that names it, and a dangling reference cannot be
76
+ * published at all.
77
+ */
78
+ export function imetaTag(meta) {
79
+ const parts = [`url ${meta.url}`, `m ${meta.m}`, `x ${meta.x}`, `size ${meta.size}`];
80
+ if (meta.dim)
81
+ parts.push(`dim ${meta.dim}`);
82
+ if (meta.alt)
83
+ parts.push(`alt ${meta.alt}`);
84
+ if (meta.thumb)
85
+ parts.push(`thumb ${meta.thumb}`);
86
+ if (meta.filename)
87
+ parts.push(`filename ${meta.filename}`);
88
+ return ['imeta', ...parts];
89
+ }
90
+ /**
91
+ * Read the `imeta` tags off an event.
92
+ *
93
+ * The reader's half, and the reason this file is shared: Ship has to draw what
94
+ * Peek attached without re-deriving the format. Anything missing the four
95
+ * required fields is skipped rather than half-rendered — a tag the relay would
96
+ * not have accepted is not one to guess at.
97
+ */
98
+ export function imetaOf(event) {
99
+ const out = [];
100
+ for (const tag of event.tags) {
101
+ if (tag[0] !== 'imeta')
102
+ continue;
103
+ const fields = {};
104
+ for (const part of tag.slice(1)) {
105
+ const space = part.indexOf(' ');
106
+ if (space <= 0)
107
+ continue;
108
+ const key = part.slice(0, space);
109
+ // First wins: the relay rejects duplicates, so a second is a malformed
110
+ // event rather than an override.
111
+ if (!(key in fields))
112
+ fields[key] = part.slice(space + 1);
113
+ }
114
+ const size = Number.parseInt(fields.size ?? '', 10);
115
+ if (!fields.url || !fields.m || !fields.x || !Number.isFinite(size))
116
+ continue;
117
+ out.push({
118
+ url: fields.url,
119
+ m: fields.m,
120
+ x: fields.x,
121
+ size,
122
+ dim: fields.dim,
123
+ alt: fields.alt,
124
+ thumb: fields.thumb,
125
+ filename: fields.filename,
126
+ });
127
+ }
128
+ return out;
129
+ }
130
+ //# sourceMappingURL=media.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.js","sourceRoot":"","sources":["../src/media.ts"],"names":[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C;YACjC,IAAI,CAAC,CAAC,GAAG,IAAI,MAAM,CAAC;gBAAE,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAA;QAC3D,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,EAAE,EAAE,CAAC,CAAA;QACnD,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,SAAQ;QAC7E,GAAG,CAAC,IAAI,CAAC;YACP,GAAG,EAAE,MAAM,CAAC,GAAG;YACf,CAAC,EAAE,MAAM,CAAC,CAAC;YACX,CAAC,EAAE,MAAM,CAAC,CAAC;YACX,IAAI;YACJ,GAAG,EAAE,MAAM,CAAC,GAAG;YACf,GAAG,EAAE,MAAM,CAAC,GAAG;YACf,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/protocol",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "The Estiva wire format: Buzz-shaped Nostr event builders, NIP-01 ids, NIP-19 naddr, NIP-98 HTTP auth, and the relay clients. Speaks the protocol; interprets nothing.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/bridge.ts CHANGED
@@ -67,6 +67,20 @@ export interface PublishResult {
67
67
  */
68
68
  export const RELAY_PAGE_CEILING = 1000
69
69
 
70
+ /**
71
+ * The most filters one `POST /query` will carry.
72
+ *
73
+ * Measured against production 2026-09-07 by binary search: **128 accepted, 129
74
+ * refused** with `too many explicit channels`. The relay counts filter
75
+ * *occurrences*, not distinct Folders — 300 filters over 36 Folders is refused
76
+ * just the same — so the bound is on the array's length and nothing else.
77
+ *
78
+ * Like {@link RELAY_PAGE_CEILING} this is a property of the relay rather than
79
+ * of this client, and it is a *page size, not a promise*: a batch that is
80
+ * refused falls back rather than assuming this number is still right.
81
+ */
82
+ export const MAX_FILTERS_PER_QUERY = 128
83
+
70
84
  /**
71
85
  * How many of a {@link Relay.queryAll} call's filters may be in flight at once.
72
86
  *
@@ -109,6 +123,14 @@ export interface QueryAllOptions {
109
123
  maxPages?: number
110
124
  /** Filters in flight at once. Defaults to {@link DEFAULT_QUERY_CONCURRENCY}; 1 is serial. */
111
125
  concurrency?: number
126
+ /**
127
+ * Ask for every filter's first page in one request. On by default.
128
+ *
129
+ * `false` restores the pre-PER-1 shape — one request per filter — which is
130
+ * what the paging tests drive, and what a caller wants if it has reason to
131
+ * distrust the relay's per-filter clamp.
132
+ */
133
+ batch?: boolean
112
134
  }
113
135
 
114
136
  export function parsePublishResponse(status: number, text: string): PublishResult {
@@ -200,6 +222,83 @@ export interface RelayOptions {
200
222
  * same class serve a script holding a secret key and a browser signing through a
201
223
  * remote service.
202
224
  */
225
+ /**
226
+ * A function saying which filter of a batch an event came from, or `null` when
227
+ * that cannot be decided with certainty.
228
+ *
229
+ * Two discriminators, both exact, and between them they cover every batched
230
+ * read the suite performs:
231
+ *
232
+ * - **`#h`**, when every filter names exactly one Folder and no two name the
233
+ * same. A filter asking for Folder A cannot match an event that is not in A,
234
+ * so the event's own `h` tag is the answer. This is the workspace read.
235
+ * - **`kinds`**, when every filter names a non-empty kind list and no kind
236
+ * appears in two of them. Then the event's `kind` is the answer, whatever
237
+ * else the filters constrain — extra constraints only ever narrow a filter,
238
+ * they cannot make it match a kind it did not ask for. This is the discovery
239
+ * pair, `{kinds:[30850]}` and `{kinds:[30851]}`.
240
+ *
241
+ * Anything else returns `null` and the chunk is paged the old way. The bar is
242
+ * "certain", not "usually right": a wrong attribution under-counts a run,
243
+ * declares a clamped filter complete, and silently drops the rest of a Folder —
244
+ * the exact bug this read path exists to prevent.
245
+ */
246
+ type Discriminator = (event: SignedEvent) => number | null
247
+
248
+ function byFolder(filters: Record<string, unknown>[]): Discriminator | null {
249
+ const slot = new Map<string, number>()
250
+ for (const [index, filter] of filters.entries()) {
251
+ const h = filter['#h']
252
+ if (!Array.isArray(h) || h.length !== 1 || typeof h[0] !== 'string') return null
253
+ if (slot.has(h[0])) return null
254
+ slot.set(h[0], index)
255
+ }
256
+ return (event) => {
257
+ let found: number | null = null
258
+ for (const tag of event.tags) {
259
+ if (tag[0] !== 'h' || typeof tag[1] !== 'string') continue
260
+ const candidate = slot.get(tag[1])
261
+ if (candidate === undefined) continue
262
+ // Two `h` tags naming two different filters: no answer exists.
263
+ if (found !== null && found !== candidate) return null
264
+ found = candidate
265
+ }
266
+ return found
267
+ }
268
+ }
269
+
270
+ function byKind(filters: Record<string, unknown>[]): Discriminator | null {
271
+ const slot = new Map<number, number>()
272
+ for (const [index, filter] of filters.entries()) {
273
+ const kinds = filter.kinds
274
+ if (!Array.isArray(kinds) || kinds.length === 0) return null
275
+ for (const kind of kinds) {
276
+ if (typeof kind !== 'number' || slot.has(kind)) return null
277
+ slot.set(kind, index)
278
+ }
279
+ }
280
+ return (event) => slot.get(event.kind) ?? null
281
+ }
282
+
283
+ function discriminate(filters: Record<string, unknown>[]): Discriminator | null {
284
+ return byFolder(filters) ?? byKind(filters)
285
+ }
286
+
287
+ /** The batched response split into one run per filter, or `null` if any event is unclaimed. */
288
+ function splitRuns(
289
+ count: number,
290
+ events: SignedEvent[],
291
+ which: Discriminator,
292
+ ): SignedEvent[][] | null {
293
+ const runs: SignedEvent[][] = Array.from({ length: count }, () => [])
294
+ for (const event of events) {
295
+ const index = which(event)
296
+ if (index === null) return null
297
+ runs[index].push(event)
298
+ }
299
+ return runs
300
+ }
301
+
203
302
  export class Relay {
204
303
  private readonly url: string
205
304
  private readonly signer: Signer
@@ -331,6 +430,45 @@ export class Relay {
331
430
  const perFilter: SignedEvent[][] = new Array(filters.length)
332
431
  const failures: unknown[] = new Array(filters.length)
333
432
 
433
+ /*
434
+ One request for every filter's first page, before any of them is paged.
435
+
436
+ The old shape spent one HTTP request per filter, and that is the unit the
437
+ relay meters: `enforce_http_admission` runs on the *call*, before the
438
+ filters are even parsed, at 300 a minute shared across every app one
439
+ person has open. Measured on Ship's `loadAll` against production
440
+ 2026-09-07: **39 requests and 1015 ms warm, 2.83 MiB down**, of which
441
+ every single request was a first page — nothing was paging at all.
442
+
443
+ What makes this safe rather than merely cheaper is that `POST /query`
444
+ **concatenates per filter, in filter order, and clamps `limit` per
445
+ filter** — all three measured, not assumed:
446
+
447
+ - 10 filters at `limit: 5` returned 48 events, not 5.
448
+ - The same filter twice in one POST returned 236 events, not 118: the
449
+ relay does not dedupe across filters, so a run's length is its own.
450
+ - Three Folder filters batched came back element-for-element identical to
451
+ the same three read one at a time.
452
+
453
+ That last one is the whole argument. `queryAll`'s contract is that the
454
+ answer is the serial concatenation; a batched response *is* that
455
+ concatenation, so this is a transport change and not a semantic one.
456
+ */
457
+ const unresolved = new Set<number>(filters.map((_, index) => index))
458
+ /*
459
+ A filter the batch could not settle keeps its first page anyway: it is
460
+ handed back as a seed so `pageFilter` resumes from that page's cursor
461
+ instead of asking for it a second time. Without this the widest filter —
462
+ which ties its own bound on every read and so is never settled — would pay
463
+ for its first page twice, and the widest filter is the one every workspace
464
+ read has.
465
+ */
466
+ const seeds: (SignedEvent[] | undefined)[] = new Array(filters.length)
467
+ if (options.batch !== false && filters.length > 1) {
468
+ await this.batchFirstPages(filters, pageSize, perFilter, unresolved, seeds)
469
+ }
470
+
471
+ const remaining = [...unresolved]
334
472
  let next = 0
335
473
  let failed = false
336
474
 
@@ -340,10 +478,11 @@ export class Relay {
340
478
  // reached them at all; this is as close as a fan-out gets, and it keeps
341
479
  // a broken read from firing the whole remaining queue at the relay.
342
480
  if (failed) return
343
- const index = next++
344
- if (index >= filters.length) return
481
+ const slot = next++
482
+ if (slot >= remaining.length) return
483
+ const index = remaining[slot]
345
484
  try {
346
- perFilter[index] = await this.pageFilter(filters[index], pageSize, maxPages)
485
+ perFilter[index] = await this.pageFilter(filters[index], pageSize, maxPages, seeds[index])
347
486
  } catch (error) {
348
487
  failures[index] = error
349
488
  failed = true
@@ -353,7 +492,7 @@ export class Relay {
353
492
  }
354
493
 
355
494
  await Promise.all(
356
- Array.from({ length: Math.min(concurrency, filters.length) }, () => worker()),
495
+ Array.from({ length: Math.min(concurrency, remaining.length) }, () => worker()),
357
496
  )
358
497
 
359
498
  /*
@@ -379,6 +518,109 @@ export class Relay {
379
518
  return out
380
519
  }
381
520
 
521
+ /**
522
+ * Every filter's first page, in as few requests as the relay will allow.
523
+ *
524
+ * Fills `perFilter` for each filter it can prove complete and removes it from
525
+ * `unresolved`; everything else is left for {@link Relay.pageFilter}, which is
526
+ * unchanged and remains the only thing that pages.
527
+ *
528
+ * **Proving a filter complete needs its own run's length**, and a flat
529
+ * response only yields that if the events can be attributed. Two ways, and
530
+ * the code takes whichever applies:
531
+ *
532
+ * 1. **By `h` tag**, when every filter in the chunk names exactly one Folder
533
+ * and no two name the same one. Exact — an event carries the Folder it is
534
+ * in — and it is the shape every workspace read in the suite actually
535
+ * sends.
536
+ * 2. **By the total**, otherwise. If the whole chunk came back under the
537
+ * largest page this relay has ever produced, no single run reached that
538
+ * bound either, so none was clamped. Weaker, and it cannot fire on a cold
539
+ * `Relay` that has no evidence yet — deliberately, per SHA-15.
540
+ *
541
+ * When neither applies the chunk is simply left unresolved: one request is
542
+ * spent and the old path runs, which is a cost in requests and never in
543
+ * correctness.
544
+ */
545
+ private async batchFirstPages(
546
+ filters: Record<string, unknown>[],
547
+ pageSize: number,
548
+ perFilter: SignedEvent[][],
549
+ unresolved: Set<number>,
550
+ seeds: (SignedEvent[] | undefined)[],
551
+ ): Promise<void> {
552
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
553
+ const indices = filters
554
+ .slice(start, start + MAX_FILTERS_PER_QUERY)
555
+ .map((_, offset) => start + offset)
556
+ if (indices.length < 2) continue
557
+
558
+ /*
559
+ Do not spend a request on a batch whose answer could not be used.
560
+
561
+ Both proofs can be checked before asking: attribution is a property of
562
+ the filters alone, and the total rule needs a ceiling this `Relay` has
563
+ actually observed. With neither available the batch would cost one
564
+ request and resolve nothing — a real regression for a cold read of
565
+ filters that carry no `#h`, which is Ship's own discovery pair.
566
+ */
567
+ const which = discriminate(indices.map((i) => filters[i]))
568
+ if (!which && this.observedPageCeiling === 0) continue
569
+
570
+ /*
571
+ A refused batch fails the whole read. It is **not** caught and retried
572
+ one filter at a time.
573
+
574
+ Falling back would be the friendlier-looking choice and it is the wrong
575
+ one: the most likely reason a batch is refused is the quota, and the
576
+ single worst response to being told to slow down is to turn one request
577
+ into another thirty-six. `queryAll` already refuses to fire the rest of
578
+ a queue once a filter has failed; this is that same rule for the batch.
579
+
580
+ The cost is error *identity* — a caller sees the batch's error rather
581
+ than the lowest-indexed filter's. For a transport refusal, which is
582
+ what this path actually meets, those are the same error.
583
+ */
584
+ const events = await this.query(indices.map((i) => ({ ...filters[i], limit: pageSize })))
585
+
586
+ const runs = which ? splitRuns(indices.length, events, which) : null
587
+ if (runs) {
588
+ /*
589
+ Update the observed ceiling from each run *before* testing it, exactly
590
+ as `pageFilter` does — so the widest filter ties its own bound and is
591
+ left to confirm itself rather than being declared complete.
592
+
593
+ Never from the chunk total. That number is the sum of several runs,
594
+ and a bound raised above what the relay actually produced would make a
595
+ genuinely clamped page look short — SHA-8, reintroduced through the
596
+ back door.
597
+ */
598
+ for (const run of runs) {
599
+ if (run.length > this.observedPageCeiling) this.observedPageCeiling = run.length
600
+ }
601
+ for (const [offset, run] of runs.entries()) {
602
+ if (run.length < pageSize && run.length < this.observedPageCeiling) {
603
+ perFilter[indices[offset]] = run
604
+ unresolved.delete(indices[offset])
605
+ } else {
606
+ seeds[indices[offset]] = run
607
+ }
608
+ }
609
+ continue
610
+ }
611
+
612
+ if (events.length < pageSize && events.length < this.observedPageCeiling) {
613
+ // No run can exceed the total, so no run reached the ceiling. The
614
+ // response is already the serial concatenation, so it can be adopted
615
+ // whole: the first slot carries it and the rest are empty, which
616
+ // concatenates to exactly the same array.
617
+ perFilter[indices[0]] = events
618
+ for (const index of indices.slice(1)) perFilter[index] = []
619
+ for (const index of indices) unresolved.delete(index)
620
+ }
621
+ }
622
+ }
623
+
382
624
  /**
383
625
  * One filter, paged to exhaustion. The sequential half, and it has to be:
384
626
  * `until` is a cursor, so page N+1's request is not known until page N has
@@ -389,9 +631,21 @@ export class Relay {
389
631
  filter: Record<string, unknown>,
390
632
  pageSize: number,
391
633
  maxPages: number,
634
+ seed?: SignedEvent[],
392
635
  ): Promise<SignedEvent[]> {
393
636
  const out: SignedEvent[] = []
394
637
  let until: number | undefined
638
+ /*
639
+ `seed` is this filter's first page, already fetched in the batch and
640
+ already judged inconclusive there — so the completeness test is not
641
+ repeated here, only the cursor is taken from it. The request that produced
642
+ it is the one this loop would otherwise make first: same filter, same
643
+ `limit`, no `until`.
644
+ */
645
+ if (seed && seed.length > 0) {
646
+ out.push(...seed)
647
+ until = Math.min(...seed.map((e) => e.created_at))
648
+ }
395
649
  for (let page = 0; ; page++) {
396
650
  if (page >= maxPages) {
397
651
  throw new Error(
package/src/events.ts CHANGED
@@ -125,6 +125,14 @@ export const KIND = {
125
125
  */
126
126
  RELAY_AUTH: 22242,
127
127
  HTTP_AUTH: 27235,
128
+ /**
129
+ * Blossom authorization (BUD-01/BUD-11) — `HTTP_AUTH` for blobs.
130
+ *
131
+ * Never stored and never published: it is signed, carried in an
132
+ * `Authorization: Nostr <base64url(event)>` header, and read once. See
133
+ * `media.ts`, which builds it and the `imeta` tag that references the blob.
134
+ */
135
+ BLOSSOM_AUTH: 24242,
128
136
  /**
129
137
  * Buzz's message edit (`KIND_STREAM_MESSAGE_EDIT`) — RFC 0.4 §7.2.1.
130
138
  *