@drakkar.software/starfish-client 3.0.0-alpha.2 → 3.0.0-alpha.22

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 (53) hide show
  1. package/README.md +44 -0
  2. package/dist/_crypto_helpers.d.ts +4 -0
  3. package/dist/append-log.d.ts +228 -0
  4. package/dist/append-log.js +267 -0
  5. package/dist/bindings/legend.d.ts +23 -0
  6. package/dist/bindings/legend.js +32 -0
  7. package/dist/bindings/legend.js.map +2 -2
  8. package/dist/bindings/zustand.d.ts +72 -1
  9. package/dist/bindings/zustand.js +427 -63
  10. package/dist/bindings/zustand.js.map +3 -3
  11. package/dist/cap-mint.d.ts +20 -0
  12. package/dist/cap-mint.js +12 -0
  13. package/dist/cap-mint.js.map +7 -0
  14. package/dist/client.d.ts +128 -5
  15. package/dist/client.js +316 -37
  16. package/dist/config.d.ts +9 -0
  17. package/dist/directory.d.ts +9 -0
  18. package/dist/directory.js +24 -0
  19. package/dist/directory.js.map +7 -0
  20. package/dist/identity.d.ts +4 -82
  21. package/dist/identity.js +2 -354
  22. package/dist/identity.js.map +4 -4
  23. package/dist/index.d.ts +9 -5
  24. package/dist/index.js +578 -60
  25. package/dist/index.js.map +4 -4
  26. package/dist/keyring.d.ts +6 -0
  27. package/dist/keyring.js +26 -0
  28. package/dist/keyring.js.map +7 -0
  29. package/dist/logger.d.ts +3 -0
  30. package/dist/mobile-lifecycle.d.ts +28 -1
  31. package/dist/mobile-lifecycle.js +41 -2
  32. package/dist/mutate.d.ts +39 -0
  33. package/dist/pairing.d.ts +6 -0
  34. package/dist/pairing.js +26 -0
  35. package/dist/pairing.js.map +7 -0
  36. package/dist/polling.js +2 -2
  37. package/dist/recipients.d.ts +6 -0
  38. package/dist/recipients.js +16 -0
  39. package/dist/recipients.js.map +7 -0
  40. package/dist/sync.d.ts +28 -0
  41. package/dist/sync.js +68 -14
  42. package/dist/types.d.ts +62 -0
  43. package/package.json +2 -2
  44. package/dist/append.d.ts +0 -50
  45. package/dist/bindings/broadcast.d.ts +0 -19
  46. package/dist/bindings/broadcast.js +0 -65
  47. package/dist/bindings/react.d.ts +0 -12
  48. package/dist/bindings/react.js +0 -25
  49. package/dist/crypto.js +0 -49
  50. package/dist/entitlements.js +0 -41
  51. package/dist/group-crypto.d.ts +0 -111
  52. package/dist/group-crypto.js +0 -205
  53. package/dist/group-crypto.js.map +0 -7
package/dist/client.d.ts CHANGED
@@ -1,5 +1,17 @@
1
1
  import type { PullResult, PushSuccess } from "@drakkar.software/starfish-protocol";
2
+ import { type AppendAuthor } from "@drakkar.software/starfish-protocol";
2
3
  import type { StarfishClientOptions } from "./types.js";
4
+ /**
5
+ * Whether a {@link PullResult} was served from the offline read-through cache
6
+ * (the transport was unreachable) rather than a live server response. Used by
7
+ * {@link SyncManager} to surface a `stale` flag to the UI without treating a
8
+ * cache hit as proof the server is reachable.
9
+ */
10
+ export declare function pullWasFromCache(result: PullResult): boolean;
11
+ /** The storage `documentKey` for a push `path`: the path with the `/push/`
12
+ * action prefix stripped (the namespace lives only in the URL). The author
13
+ * signature binds to this key. */
14
+ export declare function stripPushPrefix(path: string): string;
3
15
  /** Result of pulling a binary blob from the server. */
4
16
  export interface BlobPullResult {
5
17
  data: ArrayBuffer;
@@ -19,6 +31,13 @@ export interface AppendPullOptions {
19
31
  since?: number;
20
32
  /** Return only the last K items (applied after `since` filter). Sent as `?last=`. */
21
33
  last?: number;
34
+ /** Return only the last K items. Alias of `last`; sent as `?limit=`. When both
35
+ * are given, `limit` wins. */
36
+ limit?: number;
37
+ /** Explicitly fetch the whole collection (sent as `?full=true`). Mutually
38
+ * exclusive with `since`/`limit`/`last` — the server requires a pull to declare
39
+ * exactly one of {checkpoint, limit/last, full}. */
40
+ full?: boolean;
22
41
  }
23
42
  /**
24
43
  * Options for a structured (non-append) pull.
@@ -36,20 +55,55 @@ export interface PullOptions {
36
55
  /** Include the sibling `_keyring` document in the response. Defaults to false. */
37
56
  withKeyring?: boolean;
38
57
  }
58
+ /** Per-collection result in a {@link BatchPullResult}: either the pulled
59
+ * document (`data`/`hash`/`timestamp`) or a per-collection `error` string. */
60
+ export interface BatchPullEntry {
61
+ data?: unknown;
62
+ hash?: string;
63
+ timestamp?: number;
64
+ error?: string;
65
+ }
66
+ /** Response of {@link StarfishClient.batchPull}: a map of requested collection
67
+ * name → an ARRAY of {@link BatchPullEntry}, one per requested param-set, in
68
+ * request order. A collection read with no params yields a one-element array. */
69
+ export interface BatchPullResult {
70
+ collections: Record<string, BatchPullEntry[]>;
71
+ }
72
+ /** Options for {@link StarfishClient.batchPull}. */
73
+ export interface BatchPullOptions {
74
+ /** Per-collection path params: collection name → an ARRAY of param-sets, one
75
+ * per document to read from that collection, e.g.
76
+ * `{ profile: [{ identity: "a" }, { identity: "b" }] }` reads two profiles in
77
+ * one round-trip. Serialized to a URL-encoded JSON `params` query. The
78
+ * `{identity}` param is auto-filled by the server from the authenticated
79
+ * caller when a set omits it, so a single self-doc read can pass `[{}]` — or
80
+ * omit the collection from `params` entirely (an unlisted collection reads one
81
+ * auto-filled doc). Results come back under the same name in request order. */
82
+ params?: Record<string, Record<string, string>[]>;
83
+ }
39
84
  /**
40
85
  * Low-level HTTP client for the Starfish sync protocol.
41
86
  * Handles auth headers and response parsing.
42
87
  */
43
88
  export declare class StarfishClient {
44
89
  private readonly baseUrl;
90
+ private readonly namespace?;
45
91
  private readonly capProvider?;
46
92
  private readonly fetch;
93
+ private readonly cache?;
94
+ private readonly cacheMaxAgeMs?;
47
95
  /**
48
96
  * Installed client-side plugins. Currently stored as inert data; no
49
97
  * hooks fire yet. Extensions can inspect this list if needed.
50
98
  */
51
99
  readonly plugins: ReadonlyArray<import("./types.js").ClientPlugin>;
52
100
  constructor(options: StarfishClientOptions);
101
+ /**
102
+ * Mark a `PullResult` as having been served from the offline read-through
103
+ * cache (transport was unreachable). Non-enumerable so it doesn't leak into
104
+ * JSON / equality / re-caching; read via {@link pullWasFromCache}.
105
+ */
106
+ private tagFromCache;
53
107
  /**
54
108
  * Resolve the host portion of the URL the client will send to. The host
55
109
  * is folded into the signed canonical input as the `h` field so the
@@ -63,6 +117,18 @@ export declare class StarfishClient {
63
117
  * empty-host case still verifies symmetrically when both sides agree.
64
118
  */
65
119
  private signingHost;
120
+ /**
121
+ * Rewrite a request path for the configured namespace. A no-op when no
122
+ * namespace is set; otherwise `/{action}/…` becomes `/v1/{namespace}/{action}/…`
123
+ * (the `/v1` protocol-version segment is part of the namespaced route, matching
124
+ * the Python client and the server's namespace mount).
125
+ *
126
+ * Applied to the path used for BOTH the signature and the URL so the canonical
127
+ * path the client signs equals the path the server reconstructs from the URL.
128
+ * Covers SDK-helper-built paths too — that's the point: a namespace-unaware
129
+ * helper passing `/push/spaces/x/_keyring` reaches `/v1/{ns}/push/spaces/x/_keyring`.
130
+ */
131
+ private applyNamespace;
66
132
  /**
67
133
  * Build auth headers for a request. When a `capProvider` is set, signs the
68
134
  * request with the device's Ed25519 private key and returns the v3 header
@@ -74,23 +140,78 @@ export declare class StarfishClient {
74
140
  * The host bound into the signature is derived from `baseUrl` once per call.
75
141
  */
76
142
  private buildAuthHeaders;
143
+ /**
144
+ * Build the request-signing headers from an ALREADY-fetched cap context. Split
145
+ * out of {@link buildAuthHeaders} so {@link append} can fetch the cap once and
146
+ * reuse it for BOTH the author signature (over the element data) and the
147
+ * request signature (over the body), without redeeming the cap twice — a
148
+ * second `getCap()` could rotate keys and break the `authorPubkey ===
149
+ * presenter` bind the server checks.
150
+ */
151
+ private capRequestHeaders;
152
+ /**
153
+ * Resolve the author public key to attach to a signed append: the redeemer's
154
+ * `pubHex` for an audience cap, else the cert subject `cap.sub` for a
155
+ * device/member cap. This is the SAME key that signs the request, so a server
156
+ * enforcing author proof can bind the stored element to its writer. Returns
157
+ * undefined only for a (malformed) cap with neither — the append then goes
158
+ * unsigned and a server requiring signatures rejects it.
159
+ */
160
+ private appendAuthorKey;
77
161
  /** Pull synced data from the server. Returns the raw `PullResult`. */
78
162
  pull(path: string, checkpoint?: number): Promise<PullResult>;
79
163
  /** Pull synced data with structured options (e.g. `{withKeyring: true}`). */
80
164
  pull(path: string, options: PullOptions): Promise<PullResult>;
81
165
  /** Pull an append-only collection. Extracts and returns `data[appendField]` as `T[]`. */
82
166
  pull<T = unknown>(path: string, options: AppendPullOptions): Promise<T[]>;
167
+ /**
168
+ * Read the cached snapshot for a document `path` WITHOUT hitting the network —
169
+ * the basis for cache-first paint (seed the UI from the last-synced snapshot,
170
+ * then revalidate with a live {@link pull}). Returns the tagged `PullResult`,
171
+ * or null when no cache is configured / there's no entry. Namespacing matches
172
+ * {@link pull}, so the key lines up with whatever `pull` wrote.
173
+ */
174
+ peekCache(path: string): Promise<PullResult | null>;
175
+ /** Read + parse a cached pull snapshot, tagged {@link tagFromCache}. Returns
176
+ * null on a miss or an unparseable blob (never throws — a corrupt cache entry
177
+ * must not break a pull, just miss). */
178
+ private readCache;
179
+ /**
180
+ * Pull several documents in one round-trip via `/batch/pull`. `collections` is
181
+ * the list of distinct collection names; `opts.params` supplies, per collection,
182
+ * an ARRAY of path-param sets — one per document to read — so the SAME collection
183
+ * can fan in many documents (e.g. many users' `profile`) in a single request.
184
+ * The server auto-fills the `{identity}` param from the authenticated caller for
185
+ * any set that omits it, so a self-doc collection needs no params. Returns a map
186
+ * of collection name → an ARRAY of pulled documents (or per-document `{ error }`),
187
+ * in request order. Honors the configured namespace.
188
+ *
189
+ * For the common "many docs of one collection" case prefer {@link batchPullMany}.
190
+ *
191
+ * Note: not append/checkpoint-aware — for incremental append-only reads use
192
+ * `pull(path, { since })` (or `AppendLogCursor`) per collection.
193
+ */
194
+ batchPull(collections: string[], opts?: BatchPullOptions): Promise<BatchPullResult>;
195
+ /**
196
+ * Convenience over {@link batchPull} for reading MANY documents of ONE
197
+ * collection in a single round-trip: pass the per-document param-sets and get
198
+ * back the {@link BatchPullEntry} array aligned to `paramsList` by index (each
199
+ * entry is `{ data, hash, timestamp }` or `{ error }`). An empty `paramsList`
200
+ * issues no request and returns `[]`.
201
+ */
202
+ batchPullMany(collection: string, paramsList: Record<string, string>[]): Promise<BatchPullEntry[]>;
83
203
  /**
84
204
  * Push synced data to the server.
85
205
  * @param path - The push endpoint path (e.g. "/push/users/abc/settings")
86
206
  * @param data - The full document data to push
87
207
  * @param baseHash - Hash of the document this push is based on (null for first push)
88
208
  *
89
- * v3 author fields (`authorPubkey` + `authorSignature`) live inside `data`
90
- * and are produced by `SyncManager` when a `signer` is configured.
209
+ * v3 author proof (`authorPubkey` + `authorSignature`) is passed via `author`
210
+ * (produced by `SyncManager` when a `signer` is configured) and sent as
211
+ * top-level body siblings of `data`, where the server verifies it.
91
212
  * @throws {ConflictError} if the server detects a hash mismatch (409)
92
213
  */
93
- push(path: string, data: Record<string, unknown>, baseHash: string | null): Promise<PushSuccess>;
214
+ push(path: string, data: Record<string, unknown>, baseHash: string | null, author?: AppendAuthor): Promise<PushSuccess>;
94
215
  /**
95
216
  * Append an element to an appendOnly (`by_timestamp`) collection.
96
217
  *
@@ -105,8 +226,10 @@ export declare class StarfishClient {
105
226
  * @param opts.ts - optional client-supplied element timestamp (ms). Must be a
106
227
  * non-negative integer strictly greater than the latest stored element's ts
107
228
  * (else the server responds 409). Omit to let the server assign one.
108
- * @throws {StarfishHttpError} on a non-2xx response (e.g. 409 for a
109
- * non-monotonic timestamp).
229
+ * @throws {StarfishHttpError} on a non-2xx response e.g. 409
230
+ * `{ error: "non_monotonic_timestamp" }` for a non-monotonic timestamp, or
231
+ * `{ error: "append_limit_exceeded", limit }` if the collection's `maxItems`
232
+ * cap is reached (partition by a path parameter for higher volume).
110
233
  */
111
234
  append(path: string, data: Record<string, unknown>, opts?: {
112
235
  ts?: number;
package/dist/client.js CHANGED
@@ -1,60 +1,277 @@
1
+ import { AUTHOR_PUBKEY_FIELD, AUTHOR_SIGNATURE_FIELD, DATA_FIELD, TS_FIELD, BASE_HASH_FIELD, PUSH_PATH_PREFIX, HEADER_AUTHORIZATION, HEADER_SIG, HEADER_TS, HEADER_NONCE, HEADER_PUB, HEADER_CONTENT_TYPE, HEADER_ACCEPT, signAppendAuthor, signRequest, stableStringify, } from "@drakkar.software/starfish-protocol";
1
2
  import { ConflictError, StarfishHttpError } from "./types.js";
3
+ const APPEND_DEFAULT_FIELD = "items";
4
+ /** The storage `documentKey` for a push `path`: the path with the `/push/`
5
+ * action prefix stripped (the namespace lives only in the URL). The author
6
+ * signature binds to this key. */
7
+ export function stripPushPrefix(path) {
8
+ return path.startsWith(PUSH_PATH_PREFIX) ? path.slice(PUSH_PATH_PREFIX.length) : path;
9
+ }
10
+ /**
11
+ * Base64-encode the canonical stable-stringification of a cap-cert.
12
+ *
13
+ * Used as the value of the `Authorization: Cap <…>` header in v3.0. We rely
14
+ * on the host's `btoa` for browsers and fall back to `Buffer` in Node so the
15
+ * client stays free of native dependencies.
16
+ */
17
+ function encodeCapAuth(cap) {
18
+ const json = stableStringify(cap);
19
+ if (typeof btoa === "function") {
20
+ return btoa(json);
21
+ }
22
+ const bufCtor = globalThis.Buffer;
23
+ if (bufCtor)
24
+ return bufCtor.from(json, "utf-8").toString("base64");
25
+ throw new Error("No base64 encoder available");
26
+ }
2
27
  /**
3
28
  * Low-level HTTP client for the Starfish sync protocol.
4
29
  * Handles auth headers and response parsing.
5
30
  */
6
31
  export class StarfishClient {
7
32
  baseUrl;
8
- auth;
33
+ namespace;
34
+ capProvider;
9
35
  fetch;
36
+ /**
37
+ * Installed client-side plugins. Currently stored as inert data; no
38
+ * hooks fire yet. Extensions can inspect this list if needed.
39
+ */
40
+ plugins;
10
41
  constructor(options) {
11
42
  this.baseUrl = options.baseUrl.replace(/\/$/, "");
12
- this.auth = options.auth;
43
+ // Empty string ⇒ no namespace (treat like unset), so a falsy env value
44
+ // doesn't produce a malformed `/v1//…` path.
45
+ this.namespace = options.namespace || undefined;
46
+ this.capProvider = options.capProvider;
13
47
  this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
48
+ this.plugins = options.plugins ? [...options.plugins] : [];
14
49
  }
15
50
  /**
16
- * Pull synced data from the server.
17
- * @param path - The pull endpoint path (e.g. "/pull/users/abc/settings")
18
- * @param checkpoint - Only return data updated after this timestamp (0 = full pull)
51
+ * Resolve the host portion of the URL the client will send to. The host
52
+ * is folded into the signed canonical input as the `h` field so the
53
+ * server can refuse a signature that was minted against a different
54
+ * Starfish host (replay-across-servers defence).
55
+ *
56
+ * When `baseUrl` is relative — e.g. the consumer passed a custom `fetch`
57
+ * that resolves relative URLs in its own context — there is no parseable
58
+ * host; we return `""` so signing still proceeds. The server-side
59
+ * verifier will also reconstruct host from its inbound URL, so the
60
+ * empty-host case still verifies symmetrically when both sides agree.
19
61
  */
20
- async pull(path, checkpoint) {
21
- const url = checkpoint
22
- ? `${this.baseUrl}${path}?checkpoint=${checkpoint}`
23
- : `${this.baseUrl}${path}`;
24
- const authHeaders = this.auth
25
- ? await this.auth({ method: "GET", path, body: null })
26
- : {};
62
+ signingHost() {
63
+ try {
64
+ return new URL(this.baseUrl).host;
65
+ }
66
+ catch {
67
+ return "";
68
+ }
69
+ }
70
+ /**
71
+ * Rewrite a request path for the configured namespace. A no-op when no
72
+ * namespace is set; otherwise `/{action}/…` becomes `/v1/{namespace}/{action}/…`
73
+ * (the `/v1` protocol-version segment is part of the namespaced route, matching
74
+ * the Python client and the server's namespace mount).
75
+ *
76
+ * Applied to the path used for BOTH the signature and the URL so the canonical
77
+ * path the client signs equals the path the server reconstructs from the URL.
78
+ * Covers SDK-helper-built paths too — that's the point: a namespace-unaware
79
+ * helper passing `/push/spaces/x/_keyring` reaches `/v1/{ns}/push/spaces/x/_keyring`.
80
+ */
81
+ applyNamespace(path) {
82
+ return this.namespace ? `/v1/${this.namespace}${path}` : path;
83
+ }
84
+ /**
85
+ * Build auth headers for a request. When a `capProvider` is set, signs the
86
+ * request with the device's Ed25519 private key and returns the v3 header
87
+ * set (`Authorization: Cap …`, `X-Starfish-Sig`, `X-Starfish-Ts`,
88
+ * `X-Starfish-Nonce`). Empty when no provider is configured (public reads).
89
+ *
90
+ * Body bytes signed MUST equal the bytes sent on the wire — callers pass
91
+ * the already-serialized body string here so signing and transmission agree.
92
+ * The host bound into the signature is derived from `baseUrl` once per call.
93
+ */
94
+ async buildAuthHeaders(method, pathAndQuery, body) {
95
+ if (!this.capProvider)
96
+ return {};
97
+ const capCtx = await this.capProvider.getCap();
98
+ return this.capRequestHeaders(capCtx, method, pathAndQuery, body);
99
+ }
100
+ /**
101
+ * Build the request-signing headers from an ALREADY-fetched cap context. Split
102
+ * out of {@link buildAuthHeaders} so {@link append} can fetch the cap once and
103
+ * reuse it for BOTH the author signature (over the element data) and the
104
+ * request signature (over the body), without redeeming the cap twice — a
105
+ * second `getCap()` could rotate keys and break the `authorPubkey ===
106
+ * presenter` bind the server checks.
107
+ */
108
+ async capRequestHeaders(capCtx, method, pathAndQuery, body) {
109
+ const { cap, devEdPrivHex, pubHex } = capCtx;
110
+ const req = {
111
+ method,
112
+ pathAndQuery,
113
+ body,
114
+ host: this.signingHost(),
115
+ };
116
+ const { sig, ts, nonce } = await signRequest(req, devEdPrivHex);
117
+ const headers = {
118
+ [HEADER_AUTHORIZATION]: `Cap ${encodeCapAuth(cap)}`,
119
+ [HEADER_SIG]: sig,
120
+ [HEADER_TS]: String(ts),
121
+ [HEADER_NONCE]: nonce,
122
+ };
123
+ // Audience (public-link) caps bind no single subject, so the server needs
124
+ // the presenter's pubkey to verify the signature and check the allow-list.
125
+ if (pubHex !== undefined)
126
+ headers[HEADER_PUB] = pubHex;
127
+ return headers;
128
+ }
129
+ /**
130
+ * Resolve the author public key to attach to a signed append: the redeemer's
131
+ * `pubHex` for an audience cap, else the cert subject `cap.sub` for a
132
+ * device/member cap. This is the SAME key that signs the request, so a server
133
+ * enforcing author proof can bind the stored element to its writer. Returns
134
+ * undefined only for a (malformed) cap with neither — the append then goes
135
+ * unsigned and a server requiring signatures rejects it.
136
+ */
137
+ appendAuthorKey(capCtx) {
138
+ const { cap, pubHex } = capCtx;
139
+ const authorPubHex = pubHex ?? cap.sub;
140
+ if (authorPubHex === undefined)
141
+ return null;
142
+ return { authorPubHex };
143
+ }
144
+ async pull(path, checkpointOrOptions) {
145
+ let pathAndQuery = this.applyNamespace(path);
146
+ let appendField;
147
+ if (typeof checkpointOrOptions === "number") {
148
+ if (checkpointOrOptions)
149
+ pathAndQuery += `?checkpoint=${checkpointOrOptions}`;
150
+ }
151
+ else if (checkpointOrOptions != null) {
152
+ // Disambiguate AppendPullOptions vs PullOptions.
153
+ //
154
+ // PullOptions are identified by the presence of `withKeyring` or
155
+ // `checkpoint` keys (which AppendPullOptions does not have — append
156
+ // uses `since`, not `checkpoint`). Anything else, including an empty
157
+ // `{}` object, retains the historical behavior of AppendPullOptions
158
+ // (extracts `data.items` with `?` query).
159
+ const opts = checkpointOrOptions;
160
+ const isPullOptions = opts.withKeyring !== undefined || opts.checkpoint !== undefined;
161
+ const params = new URLSearchParams();
162
+ if (isPullOptions) {
163
+ if (opts.checkpoint != null && opts.checkpoint > 0) {
164
+ params.set("checkpoint", String(opts.checkpoint));
165
+ }
166
+ if (opts.withKeyring) {
167
+ params.set("withKeyring", "1");
168
+ }
169
+ }
170
+ else {
171
+ appendField = opts.appendField ?? APPEND_DEFAULT_FIELD;
172
+ if (opts.since != null) {
173
+ if (opts.since < 0)
174
+ throw new Error("since must be non-negative");
175
+ params.set("checkpoint", String(opts.since));
176
+ }
177
+ if (opts.last != null) {
178
+ if (opts.last < 0)
179
+ throw new Error("last must be non-negative");
180
+ params.set("last", String(opts.last));
181
+ }
182
+ }
183
+ if (params.size > 0)
184
+ pathAndQuery += `?${params.toString()}`;
185
+ }
186
+ const url = `${this.baseUrl}${pathAndQuery}`;
187
+ const authHeaders = await this.buildAuthHeaders("GET", pathAndQuery, undefined);
27
188
  const res = await this.fetch(url, {
28
189
  method: "GET",
29
- headers: { Accept: "application/json", ...authHeaders },
190
+ headers: { [HEADER_ACCEPT]: "application/json", ...authHeaders },
30
191
  });
31
192
  if (!res.ok) {
32
193
  throw new StarfishHttpError(res.status, await res.text());
33
194
  }
34
- return res.json();
195
+ const result = await res.json();
196
+ if (appendField !== undefined) {
197
+ const list = result.data?.[appendField];
198
+ return (Array.isArray(list) ? list : []);
199
+ }
200
+ return result;
201
+ }
202
+ /**
203
+ * Pull several documents in one round-trip via `/batch/pull`. `collections` is
204
+ * the list of distinct collection names; `opts.params` supplies, per collection,
205
+ * an ARRAY of path-param sets — one per document to read — so the SAME collection
206
+ * can fan in many documents (e.g. many users' `profile`) in a single request.
207
+ * The server auto-fills the `{identity}` param from the authenticated caller for
208
+ * any set that omits it, so a self-doc collection needs no params. Returns a map
209
+ * of collection name → an ARRAY of pulled documents (or per-document `{ error }`),
210
+ * in request order. Honors the configured namespace.
211
+ *
212
+ * For the common "many docs of one collection" case prefer {@link batchPullMany}.
213
+ *
214
+ * Note: not append/checkpoint-aware — for incremental append-only reads use
215
+ * `pull(path, { since })` (or `AppendLogCursor`) per collection.
216
+ */
217
+ async batchPull(collections, opts = {}) {
218
+ const search = new URLSearchParams();
219
+ search.set("collections", collections.join(","));
220
+ if (opts.params && Object.keys(opts.params).length > 0) {
221
+ search.set("params", JSON.stringify(opts.params));
222
+ }
223
+ const pathAndQuery = `${this.applyNamespace("/batch/pull")}?${search.toString()}`;
224
+ const url = `${this.baseUrl}${pathAndQuery}`;
225
+ const authHeaders = await this.buildAuthHeaders("GET", pathAndQuery, undefined);
226
+ const res = await this.fetch(url, {
227
+ method: "GET",
228
+ headers: { [HEADER_ACCEPT]: "application/json", ...authHeaders },
229
+ });
230
+ if (!res.ok) {
231
+ throw new StarfishHttpError(res.status, await res.text());
232
+ }
233
+ return await res.json();
234
+ }
235
+ /**
236
+ * Convenience over {@link batchPull} for reading MANY documents of ONE
237
+ * collection in a single round-trip: pass the per-document param-sets and get
238
+ * back the {@link BatchPullEntry} array aligned to `paramsList` by index (each
239
+ * entry is `{ data, hash, timestamp }` or `{ error }`). An empty `paramsList`
240
+ * issues no request and returns `[]`.
241
+ */
242
+ async batchPullMany(collection, paramsList) {
243
+ if (paramsList.length === 0)
244
+ return [];
245
+ const res = await this.batchPull([collection], { params: { [collection]: paramsList } });
246
+ return res.collections[collection] ?? [];
35
247
  }
36
248
  /**
37
249
  * Push synced data to the server.
38
250
  * @param path - The push endpoint path (e.g. "/push/users/abc/settings")
39
251
  * @param data - The full document data to push
40
252
  * @param baseHash - Hash of the document this push is based on (null for first push)
41
- * @param authorSignature - Optional author signature for provenance
253
+ *
254
+ * v3 author proof (`authorPubkey` + `authorSignature`) is passed via `author`
255
+ * (produced by `SyncManager` when a `signer` is configured) and sent as
256
+ * top-level body siblings of `data`, where the server verifies it.
42
257
  * @throws {ConflictError} if the server detects a hash mismatch (409)
43
258
  */
44
- async push(path, data, baseHash, authorSignature) {
259
+ async push(path, data, baseHash, author) {
45
260
  const body = JSON.stringify({
46
- data,
47
- baseHash,
48
- ...(authorSignature && { authorSignature }),
261
+ [DATA_FIELD]: data,
262
+ [BASE_HASH_FIELD]: baseHash,
263
+ ...(author && {
264
+ [AUTHOR_PUBKEY_FIELD]: author.authorPubkey,
265
+ [AUTHOR_SIGNATURE_FIELD]: author.authorSignature,
266
+ }),
49
267
  });
50
- const authHeaders = this.auth
51
- ? await this.auth({ method: "POST", path, body })
52
- : {};
53
- const res = await this.fetch(`${this.baseUrl}${path}`, {
268
+ const sendPath = this.applyNamespace(path);
269
+ const authHeaders = await this.buildAuthHeaders("POST", sendPath, body);
270
+ const res = await this.fetch(`${this.baseUrl}${sendPath}`, {
54
271
  method: "POST",
55
272
  headers: {
56
- "Content-Type": "application/json",
57
- Accept: "application/json",
273
+ [HEADER_CONTENT_TYPE]: "application/json",
274
+ [HEADER_ACCEPT]: "application/json",
58
275
  ...authHeaders,
59
276
  },
60
277
  body,
@@ -67,23 +284,84 @@ export class StarfishClient {
67
284
  }
68
285
  return res.json();
69
286
  }
287
+ /**
288
+ * Append an element to an appendOnly (`by_timestamp`) collection.
289
+ *
290
+ * Unlike {@link push}, appendOnly writes carry no hash/conflict check — an
291
+ * authorized append is always accepted. Each element is stored server-side as
292
+ * `{ts, data}` and pulls can filter by `ts` via `since`/`checkpoint`.
293
+ *
294
+ * @param path - the push endpoint (e.g. "/push/events")
295
+ * @param data - the element payload. For a `delegated` collection, encrypt it
296
+ * first (e.g. `createKeyringEncryptor(keyring, kem).encrypt(data)`); the
297
+ * server stores it opaquely and never reads it.
298
+ * @param opts.ts - optional client-supplied element timestamp (ms). Must be a
299
+ * non-negative integer strictly greater than the latest stored element's ts
300
+ * (else the server responds 409). Omit to let the server assign one.
301
+ * @throws {StarfishHttpError} on a non-2xx response — e.g. 409
302
+ * `{ error: "non_monotonic_timestamp" }` for a non-monotonic timestamp, or
303
+ * `{ error: "append_limit_exceeded", limit }` if the collection's `maxItems`
304
+ * cap is reached (partition by a path parameter for higher volume).
305
+ */
306
+ async append(path, data, opts = {}) {
307
+ const sendPath = this.applyNamespace(path);
308
+ const bodyObj = { [DATA_FIELD]: data };
309
+ if (opts.ts !== undefined)
310
+ bodyObj[TS_FIELD] = opts.ts;
311
+ // Author proof. Fetch the cap ONCE and reuse it for both the author
312
+ // signature (over the element `data`) and the request signature (over the
313
+ // final body) — see {@link capRequestHeaders}. The author fields are signed
314
+ // with the same key that authenticates the request, so a collection with
315
+ // `requireAuthorSignature` (the default) binds the stored element to its
316
+ // writer. Without a cap provider the append is sent unsigned and such a
317
+ // collection rejects it.
318
+ const capCtx = this.capProvider ? await this.capProvider.getCap() : null;
319
+ if (capCtx) {
320
+ const authorKey = this.appendAuthorKey(capCtx);
321
+ if (authorKey) {
322
+ // The signature binds the author to BOTH the element data AND the
323
+ // document it is written to (the storage path = `path` minus the
324
+ // `/push/` action prefix; the namespace lives only in the URL).
325
+ const documentKey = stripPushPrefix(path);
326
+ const { authorPubkey, authorSignature } = signAppendAuthor(documentKey, data, authorKey.authorPubHex, capCtx.devEdPrivHex);
327
+ bodyObj[AUTHOR_PUBKEY_FIELD] = authorPubkey;
328
+ bodyObj[AUTHOR_SIGNATURE_FIELD] = authorSignature;
329
+ }
330
+ }
331
+ const body = JSON.stringify(bodyObj);
332
+ const authHeaders = capCtx
333
+ ? await this.capRequestHeaders(capCtx, "POST", sendPath, body)
334
+ : {};
335
+ const res = await this.fetch(`${this.baseUrl}${sendPath}`, {
336
+ method: "POST",
337
+ headers: {
338
+ [HEADER_CONTENT_TYPE]: "application/json",
339
+ [HEADER_ACCEPT]: "application/json",
340
+ ...authHeaders,
341
+ },
342
+ body,
343
+ });
344
+ if (!res.ok) {
345
+ throw new StarfishHttpError(res.status, await res.text());
346
+ }
347
+ return res.json();
348
+ }
70
349
  /**
71
350
  * Pull binary data from a blob collection.
72
351
  * Returns raw bytes with the content hash from the ETag header.
73
352
  */
74
353
  async pullBlob(path) {
75
- const authHeaders = this.auth
76
- ? await this.auth({ method: "GET", path, body: null })
77
- : {};
78
- const res = await this.fetch(`${this.baseUrl}${path}`, {
354
+ const sendPath = this.applyNamespace(path);
355
+ const authHeaders = await this.buildAuthHeaders("GET", sendPath, undefined);
356
+ const res = await this.fetch(`${this.baseUrl}${sendPath}`, {
79
357
  method: "GET",
80
- headers: { Accept: "*/*", ...authHeaders },
358
+ headers: { [HEADER_ACCEPT]: "*/*", ...authHeaders },
81
359
  });
82
360
  if (!res.ok) {
83
361
  throw new StarfishHttpError(res.status, await res.text());
84
362
  }
85
363
  const etag = res.headers.get("ETag")?.replace(/"/g, "") ?? null;
86
- const contentType = res.headers.get("Content-Type") ?? "application/octet-stream";
364
+ const contentType = res.headers.get(HEADER_CONTENT_TYPE) ?? "application/octet-stream";
87
365
  const data = await res.arrayBuffer();
88
366
  return { data, hash: etag, contentType };
89
367
  }
@@ -92,14 +370,15 @@ export class StarfishClient {
92
370
  * Binary collections use last-write-wins (no conflict detection).
93
371
  */
94
372
  async pushBlob(path, data, contentType) {
95
- const authHeaders = this.auth
96
- ? await this.auth({ method: "POST", path, body: null })
97
- : {};
98
- const res = await this.fetch(`${this.baseUrl}${path}`, {
373
+ // Blobs are not JSON; we leave body undefined when signing — server-side
374
+ // verification is expected to use a separate path for blob uploads.
375
+ const sendPath = this.applyNamespace(path);
376
+ const authHeaders = await this.buildAuthHeaders("POST", sendPath, undefined);
377
+ const res = await this.fetch(`${this.baseUrl}${sendPath}`, {
99
378
  method: "POST",
100
379
  headers: {
101
- "Content-Type": contentType,
102
- Accept: "application/json",
380
+ [HEADER_CONTENT_TYPE]: contentType,
381
+ [HEADER_ACCEPT]: "application/json",
103
382
  ...authHeaders,
104
383
  },
105
384
  body: data,
package/dist/config.d.ts CHANGED
@@ -9,6 +9,15 @@ export interface AppendOnlyClientInfo {
9
9
  /** false = no storage write (replaces queueOnly). true/absent = append to array. */
10
10
  persist?: boolean;
11
11
  }
12
+ /** Append-only configuration exposed via GET /config. */
13
+ export interface AppendOnlyClientInfo {
14
+ /** Array field name in the stored document. Defaults to "items". */
15
+ field?: string;
16
+ /** false = no storage write (replaces queueOnly). true/absent = append to array. */
17
+ persist?: boolean;
18
+ /** When true, server validates client's baseHash against hash(lastItem). */
19
+ checkLastItem?: boolean;
20
+ }
12
21
  /** Per-collection metadata returned by GET /config. */
13
22
  export interface CollectionClientInfo {
14
23
  name: string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Phase-2 transitional shim. Device-directory helpers now live in
3
+ * `@drakkar.software/starfish-identities`; member-directory helpers now live
4
+ * in `@drakkar.software/starfish-sharing`. Removed in Phase 3.
5
+ */
6
+ export { addDeviceEntry, listDevices, removeDeviceEntry, devicesPathFor, } from "@drakkar.software/starfish-identities";
7
+ export type { DirectoryEntry, Directory, DeviceEntry, ListDirectoryOpts, } from "@drakkar.software/starfish-identities";
8
+ export { addMemberEntry, listMembers, removeMemberEntry, membersPathFor, } from "@drakkar.software/starfish-sharing";
9
+ export type { MemberEntry } from "@drakkar.software/starfish-sharing";
@@ -0,0 +1,24 @@
1
+ // src/directory.ts
2
+ import {
3
+ addDeviceEntry,
4
+ listDevices,
5
+ removeDeviceEntry,
6
+ devicesPathFor
7
+ } from "@drakkar.software/starfish-identities";
8
+ import {
9
+ addMemberEntry,
10
+ listMembers,
11
+ removeMemberEntry,
12
+ membersPathFor
13
+ } from "@drakkar.software/starfish-sharing";
14
+ export {
15
+ addDeviceEntry,
16
+ addMemberEntry,
17
+ devicesPathFor,
18
+ listDevices,
19
+ listMembers,
20
+ membersPathFor,
21
+ removeDeviceEntry,
22
+ removeMemberEntry
23
+ };
24
+ //# sourceMappingURL=directory.js.map