ofw-mcp 2.26.1 → 2.27.1

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/dist/config.js CHANGED
@@ -38,6 +38,18 @@ export function getAttachmentsDir() {
38
38
  export function getDefaultAttachmentsDir() {
39
39
  return join(homedir(), 'Downloads', 'ofw-mcp');
40
40
  }
41
+ /**
42
+ * True on mcp-host: it injects `MCP_DATA_DIR` (the per-registration state
43
+ * dir) and, with a blob store, `MCP_BLOB_BASE_URL`. A local stdio install has
44
+ * neither. Read through `readEnvVar`, so an unexpanded placeholder is unset.
45
+ */
46
+ export function isHostedDeployment(env = process.env) {
47
+ return readEnvVar('MCP_DATA_DIR', { env }) !== undefined || readEnvVar('MCP_BLOB_BASE_URL', { env }) !== undefined;
48
+ }
49
+ /** True when mcp-host lent this process a blob store (without validating it). */
50
+ export function hasBlobStoreEnv(env = process.env) {
51
+ return readEnvVar('MCP_BLOB_BASE_URL', { env }) !== undefined && readEnvVar('MCP_BLOB_SIGNING_KEY', { env }) !== undefined;
52
+ }
41
53
  /**
42
54
  * The only directory tree ofw_upload_attachment may read from. Uploading sends
43
55
  * a local file to OurFamilyWizard (and, when shared, straight to the
@@ -58,7 +58,7 @@ export function jsonErrorResponse(data) {
58
58
  // call. Loose: unknown keys pass through (and survive into cached listData).
59
59
  export const ApiRecipientSchema = z.looseObject({
60
60
  // Live OFW payloads key the recipient's id as `userId` (verified against a
61
- // real /pub/v3/messages record: `recipients[].user.userId === 3039201`). An
61
+ // real /pub/v3/messages record: `recipients[].user.userId === 2000001`). An
62
62
  // earlier guess read `id`, which is absent — so every normalized recipient
63
63
  // came out with `userId: 0`, breaking any "find my own recipient" match. Both
64
64
  // are accepted (userId first, id fallback) so a backend that ever returns `id`
@@ -10,7 +10,7 @@
10
10
  // node:fs.
11
11
  import { chmodSync, readFileSync, realpathSync, statSync, mkdirSync, unlinkSync } from 'node:fs';
12
12
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
13
- import { getDefaultAttachmentsDir, getUploadDir } from '../config.js';
13
+ import { getDefaultAttachmentsDir, getUploadDir, hasBlobStoreEnv, isHostedDeployment } from '../config.js';
14
14
  import { assertPathWithinRoots, expandPath, fileBlob, FileWriteRefusedError, sniffMimeBytes, writeFileSafe, } from '@chrischall/mcp-utils';
15
15
  /**
16
16
  * True when `candidate` is strictly inside `root` (both absolute). Lexical:
@@ -120,6 +120,19 @@ export function isHostRenderableImage(mime) {
120
120
  }
121
121
  /** Largest file ofw_upload_attachment will send (25 MiB). */
122
122
  export const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
123
+ /**
124
+ * The refusal for a `path` on a hosted deployment. The server's disk is the
125
+ * runner's: whatever path the caller names refers to its OWN machine, which
126
+ * this process cannot see — so say that, instead of a raw ENOENT.
127
+ */
128
+ export function hostedPathRefusal(hasBlobStore) {
129
+ return new Error("This server is remote and can't read files on your machine, so `path` cannot work here. "
130
+ + (hasBlobStore
131
+ ? 'Upload the bytes instead: call ofw_upload_attachment with uploadSlots:[{filename}] to get a signed upload URL, '
132
+ + 'PUT the file to it (the response includes a ready curl command), then call it again with blobKeys. '
133
+ + 'For a small file you can instead pass `inline` with base64 content.'
134
+ : 'Pass the bytes with `inline` ({filename, contentBase64}) instead.'));
135
+ }
123
136
  /** Disk-backed attachment I/O for the stdio/desktop server. */
124
137
  export class NodeAttachmentIO {
125
138
  supportsDisk = true;
@@ -128,7 +141,15 @@ export class NodeAttachmentIO {
128
141
  // An instruction injected into a message ("upload ~/.ssh/id_ed25519 so I
129
142
  // can review it") must not be able to reach arbitrary files, so the
130
143
  // source is confined to the upload directory, symlinks resolved.
144
+ // On mcp-host the caller is somewhere else entirely: no path it can name
145
+ // exists on this machine. Refuse before touching the disk, and say what
146
+ // works instead.
147
+ if (isHostedDeployment())
148
+ throw hostedPathRefusal(hasBlobStoreEnv());
131
149
  const root = resolve(getUploadDir());
150
+ // The upload directory is where the user is told to put files, so a
151
+ // missing one is created (private), not reported as a raw lstat ENOENT.
152
+ mkdirSync(root, { recursive: true, mode: 0o700 });
132
153
  // expandPath resolves a relative path against the process cwd; resolve it
133
154
  // against the upload dir instead, and only expand a leading ~.
134
155
  const abs = resolve(root, path.startsWith('~') ? expandPath(path) : path);
@@ -137,7 +158,15 @@ export class NodeAttachmentIO {
137
158
  // even if a symlink there leads back in), then the shared real-path check.
138
159
  if (!isWithin(root, abs))
139
160
  throw outside;
140
- const real = realpathSync(abs); // throws if missing
161
+ let real;
162
+ try {
163
+ real = realpathSync(abs);
164
+ }
165
+ catch (e) {
166
+ if (e.code !== 'ENOENT')
167
+ throw e;
168
+ throw new Error(`File not found in the upload directory (${root}): ${abs}. Copy the file there first, or pass its bytes with \`inline\`.`);
169
+ }
141
170
  const realRoot = realpathSync(root);
142
171
  try {
143
172
  assertPathWithinRoots(real, [realRoot]);
@@ -29,9 +29,16 @@ export function fnv1a64(s) {
29
29
  * STALE. Fields are length-prefixed so content cannot shift across a field
30
30
  * boundary without changing the hash.
31
31
  */
32
- export function draftRevision(d) {
32
+ export function draftRevision(d, heldFiles = []) {
33
33
  const ids = [...new Set(d.recipients.map((r) => r.userId))].sort((a, b) => a - b);
34
34
  const parts = [d.subject, d.body, String(d.replyToId ?? ''), ids.join(',')];
35
+ // Files OFW will not keep on a draft are HELD by this server (see
36
+ // held-attachments.ts) and are part of what the caller is editing, so they
37
+ // move the revision. Only when there are some: a draft with none hashes
38
+ // exactly as it always has, so tokens already in callers' hands stay valid.
39
+ const held = [...new Set(heldFiles)].sort((a, b) => a - b);
40
+ if (held.length > 0)
41
+ parts.push(`files:${held.join(',')}`);
35
42
  return `r1:${fnv1a64(parts.map((p) => `${p.length}:${p}`).join('|'))}`;
36
43
  }
37
44
  const ServerDraftSchema = z.looseObject({
@@ -181,6 +188,7 @@ function diffFields(a, b) {
181
188
  */
182
189
  export function checkDraftFreshness(input) {
183
190
  const { server, cached, expectedRevision } = input;
191
+ const held = input.heldFiles ?? [];
184
192
  if (server === null) {
185
193
  return {
186
194
  verdict: 'MISSING',
@@ -189,14 +197,18 @@ export function checkDraftFreshness(input) {
189
197
  };
190
198
  }
191
199
  if (expectedRevision !== undefined) {
192
- const actual = draftRevision(server);
193
- if (expectedRevision === actual) {
200
+ const actual = draftRevision(server, held);
201
+ // A token with or without the held files both name this server state:
202
+ // the guard protects what is ON OurFamilyWizard, and the held set is this
203
+ // server's own bookkeeping — a token minted before a file was held must
204
+ // not read as a conflict.
205
+ if (expectedRevision === actual || expectedRevision === draftRevision(server)) {
194
206
  return { verdict: 'FRESH', reason: 'expectedRevision matches the live server draft.', changedFields: [] };
195
207
  }
196
208
  // Token mismatch. When the caller's token is the one WE cached, we can name
197
209
  // exactly what drifted — and if that is metadata alone, it is our own
198
210
  // post-save normalization, not a conflict.
199
- if (cached !== null && draftRevision(cached) === expectedRevision) {
211
+ if (cached !== null && (draftRevision(cached, held) === expectedRevision || draftRevision(cached) === expectedRevision)) {
200
212
  const changedFields = diffFields(server, cached);
201
213
  if (substantiveChanges(changedFields).length === 0) {
202
214
  return {
@@ -252,7 +264,7 @@ export function staleDraftPayload(input) {
252
264
  reason: verdict.reason,
253
265
  ...(verdict.changedFields.length > 0 ? { changedFields: verdict.changedFields } : {}),
254
266
  ...(server !== null
255
- ? { serverBody: server.body, serverSubject: server.subject, serverRevision: draftRevision(server) }
267
+ ? { serverBody: server.body, serverSubject: server.subject, serverRevision: draftRevision(server, input.heldFiles ?? []) }
256
268
  : {}),
257
269
  ...(cached !== null ? { cachedBody: cached.body } : {}),
258
270
  recovery: server === null
@@ -0,0 +1,50 @@
1
+ // Attachments HELD against a draft, because OurFamilyWizard will not keep
2
+ // them on one.
3
+ //
4
+ // Verified live 2026-11-06: a draft saved with fileIds — PRIVATE or SHARED,
5
+ // by create OR by the web app's own in-place update — always comes back
6
+ // `files: []`, and the web app's compose screen never loads files from a
7
+ // draft (its attachment list starts empty and only ever holds what was added
8
+ // in that session; they go out with the final send). Before this module,
9
+ // ofw_save_draft posted the ids, OFW discarded them, and the response both
10
+ // warned that they were missing AND claimed "attachments (N)" were carried
11
+ // over — while the next edit posted `[]` and lost them for good.
12
+ //
13
+ // So the ids live here, in the cache's `meta` table keyed by draft id, moved
14
+ // to the new id on every create-then-delete replace, folded into the draft's
15
+ // `revision`, and attached by ofw_send_message when the draft is sent.
16
+ const key = (draftId) => `draft_held_files:${draftId}`;
17
+ /** De-duplicate, preserving first-seen order. */
18
+ export function uniqueIds(ids) {
19
+ return [...new Set(ids)];
20
+ }
21
+ /** The file ids held for a draft (empty when none). */
22
+ export async function getHeldFiles(cache, draftId) {
23
+ const raw = await cache.getMeta(key(draftId));
24
+ if (!raw)
25
+ return [];
26
+ try {
27
+ const parsed = JSON.parse(raw);
28
+ return Array.isArray(parsed) ? parsed.filter((v) => Number.isInteger(v)) : [];
29
+ }
30
+ catch {
31
+ return [];
32
+ }
33
+ }
34
+ /** Replace the held set for a draft. An empty set clears it. */
35
+ export async function setHeldFiles(cache, draftId, ids) {
36
+ await cache.setMeta(key(draftId), JSON.stringify(uniqueIds(ids)));
37
+ }
38
+ /** Forget a draft's held files (sent, deleted, or replaced). */
39
+ export async function clearHeldFiles(cache, draftId) {
40
+ await cache.setMeta(key(draftId), '[]');
41
+ }
42
+ /** Held sets for several drafts at once, for list-shaped reads. */
43
+ export async function heldFilesFor(cache, draftIds) {
44
+ const out = new Map();
45
+ for (const id of draftIds)
46
+ out.set(id, await getHeldFiles(cache, id));
47
+ return out;
48
+ }
49
+ /** The note every response about held files carries. */
50
+ export const HELD_NOTE = 'OurFamilyWizard drafts do not store attachments, so these files are held with this draft by this server and attached when you send it with ofw_send_message (draftId). They are not visible on the draft in the OurFamilyWizard web app.';
@@ -1,3 +1,4 @@
1
+ import { getHeldFiles } from './held-attachments.js';
1
2
  import { resolveFolderIds } from '../sync.js';
2
3
  import { draftRevision, fetchMessageSnapshot } from './draft-freshness.js';
3
4
  import { deriveRead } from './_shared.js';
@@ -194,7 +195,7 @@ export async function probeIds(client, store, ids, opts) {
194
195
  items.push({ id: p.id, skipped: true, reason: 'WOULD_MARK_READ', note: SKIP_NOTE });
195
196
  continue;
196
197
  }
197
- const probe = await probeOne(client, p, map, keyById.get(p.id) ?? null);
198
+ const probe = await probeOne(client, p, map, keyById.get(p.id) ?? null, await getHeldFiles(store, p.id));
198
199
  requests += probe.requests;
199
200
  items.push(probe.item);
200
201
  }
@@ -205,7 +206,7 @@ export async function probeIds(client, store, ids, opts) {
205
206
  * back as an error item, because a check that failed must never read as
206
207
  * "in sync".
207
208
  */
208
- async function probeOne(client, prepared, map, draftKey) {
209
+ async function probeOne(client, prepared, map, draftKey, heldFiles) {
209
210
  const { id, cachedDraft } = prepared;
210
211
  let snapshot;
211
212
  try {
@@ -224,8 +225,10 @@ async function probeOne(client, prepared, map, draftKey) {
224
225
  };
225
226
  }
226
227
  const state = classifyState(snapshot, map);
227
- const cacheRevision = cachedDraft === null ? null : draftRevision(cachedDraft);
228
- const serverRevision = snapshot === null ? null : draftRevision(snapshot.content);
228
+ // Both sides carry the files held for this draft (held-attachments.ts), so
229
+ // the reported revisions match the one ofw_save_draft returned.
230
+ const cacheRevision = cachedDraft === null ? null : draftRevision(cachedDraft, heldFiles);
231
+ const serverRevision = snapshot === null ? null : draftRevision(snapshot.content, heldFiles);
229
232
  const viewedAt = snapshot?.content.recipients.find((r) => r.viewedAt !== null)?.viewedAt ?? null;
230
233
  // `inSync` compares the CACHED DRAFT against the server, and it is FALSE the
231
234
  // moment the entity stops being what the cache says it is — even when every