@chrischall/hellofresh-mcp 0.3.0 → 0.4.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/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { readWsPort } from './config.js';
5
5
  import { TOOL_REGISTRARS } from './tools/index.js';
6
6
  import { createProfileStore } from './profiles.js';
7
7
  import { HelloFreshSession } from './session.js';
8
+ import { createSessionCache } from './session-cache.js';
8
9
  import { createHelloFreshBridge } from './transport.js';
9
10
  import { VERSION } from './version.js';
10
11
  // The bridge bootstraps the session: it reads (and refreshes) the apiV2Auth
@@ -19,7 +20,9 @@ await bridge.start().catch(() => { });
19
20
  // Built ONCE, outside the registrars (runMcp builds a server per connection).
20
21
  // Nothing here resolves a credential at boot (deferred-config-error pattern).
21
22
  const fetchImpl = (input, init) => fetch(input, init);
22
- const session = new HelloFreshSession({ bridge, fetchImpl });
23
+ // The session survives a restart through a 0600 file (HELLOFRESH_SESSION_FILE;
24
+ // HELLOFRESH_SESSION_CACHE=false keeps it in memory only). Opening it touches no disk.
25
+ const session = new HelloFreshSession({ bridge, fetchImpl, persistence: createSessionCache() });
23
26
  const deps = {
24
27
  bridge,
25
28
  session,
@@ -0,0 +1,33 @@
1
+ // Where the HelloFresh session is kept between runs (lifecycle step 6 in
2
+ // src/session.ts). One small 0600 JSON file, replaced atomically, with a
3
+ // cross-process lock beside it — the fleet's createFileStatePersistence.
4
+ //
5
+ // It holds the token set WITHOUT `user_data` (the customer id and email). On
6
+ // mcp-host it lands in the registration's persistent data dir (MCP_DATA_DIR;
7
+ // mint.yaml declares `state.dataDir: true`), elsewhere under $HOME.
8
+ import { parseBoolEnv } from '@chrischall/mcp-utils';
9
+ import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
10
+ import { isTokenSet } from './session.js';
11
+ /** `HELLOFRESH_SESSION_FILE`, else `<MCP_DATA_DIR or HOME>/.hellofresh-mcp/session.json`. */
12
+ export function sessionCachePath(env = process.env) {
13
+ return resolveStateFile({ env, envVar: 'HELLOFRESH_SESSION_FILE', subdir: '.hellofresh-mcp', fileName: 'session.json' });
14
+ }
15
+ function asPersistedSession(raw) {
16
+ if (typeof raw !== 'object' || raw === null)
17
+ return null;
18
+ const r = raw;
19
+ if (!isTokenSet(r['set']) || typeof r['set'].issued_at !== 'number')
20
+ return null;
21
+ if (typeof r['own'] !== 'boolean' || typeof r['writtenBack'] !== 'boolean')
22
+ return null;
23
+ return { set: r['set'], own: r['own'], writtenBack: r['writtenBack'] };
24
+ }
25
+ /** The session store, or `null` when `HELLOFRESH_SESSION_CACHE` turns it off. */
26
+ export function createSessionCache(env = process.env) {
27
+ if (!parseBoolEnv('HELLOFRESH_SESSION_CACHE', { env, default: true }))
28
+ return null;
29
+ return createFileStatePersistence({
30
+ filePath: sessionCachePath(env),
31
+ validate: asPersistedSession,
32
+ });
33
+ }
package/dist/session.js CHANGED
@@ -25,9 +25,23 @@
25
25
  // out). Only its ACCESS token is used, while still valid (and not
26
26
  // rejected); otherwise the original bridge error is rethrown, its
27
27
  // pairing hint intact. /gw/refresh is never called.
28
- // A set read from the browser is never a fallback: its refresh token may
29
- // already be spent by the browser. A missing cookie (signed out) is NOT a
30
- // read failure and still fails.
28
+ // A set read from the browser is never refreshed as a fallback: its
29
+ // refresh token may already be spent by the browser. Its ACCESS token may
30
+ // stand in while still valid (and not rejected). A missing cookie (signed
31
+ // out) is NOT a read failure and still fails.
32
+ // 6. Optional persistence (`src/session-cache.ts`) carries the newest set —
33
+ // and whether it is our own refresh and was written back — across a
34
+ // restart. It is loaded once, as if this process had just used it, so
35
+ // step 5's rules decide what a stored set may do: the browser's newer
36
+ // cookie still wins, a stored ACCESS token stands in while valid, and only
37
+ // our own never-written-back refresh token is ever POSTed without the
38
+ // browser. `user_data` (customer id, email) is never stored. Refreshing
39
+ // holds the store's cross-process lock and re-reads it first, so a sibling
40
+ // process (Claude Desktop beside Claude Code) that just refreshed is
41
+ // adopted instead of racing it with the same rotating refresh token. A
42
+ // rejected refresh clears the record (unless a sibling's newer one replaced
43
+ // it), so a dead session is not read back off disk. A store failure is
44
+ // logged and never fails a call.
31
45
  //
32
46
  // No token value is ever logged, put in an error message or returned.
33
47
  import { EdgeBlockedError, McpToolError, SessionNotAuthenticatedError, createCachedTokenSource, decodeJwtClaim, detectEdgeBlock, messageOf, parseJsonBody, redactValues, truncateErrorMessage, } from '@chrischall/mcp-utils';
@@ -124,7 +138,7 @@ export function decodeAuthCookie(raw) {
124
138
  }
125
139
  return parsed;
126
140
  }
127
- function isTokenSet(value) {
141
+ export function isTokenSet(value) {
128
142
  if (typeof value !== 'object' || value === null || Array.isArray(value))
129
143
  return false;
130
144
  const v = value;
@@ -139,6 +153,11 @@ export function tokenExpiresAtMs(set) {
139
153
  const exp = decodeJwtClaim(set.access_token, 'exp');
140
154
  return typeof exp === 'number' ? exp * 1000 : 0;
141
155
  }
156
+ /** The record to store for `set`: never its `user_data` (customer id, email). */
157
+ export function toPersistedSession(set, from) {
158
+ const { user_data: _userData, ...rest } = set;
159
+ return { set: rest, own: from.own, writtenBack: from.own && from.writtenBack };
160
+ }
142
161
  /** How many token values to remember for redaction. */
143
162
  const REDACT_HISTORY = 8;
144
163
  export class HelloFreshSession {
@@ -158,6 +177,10 @@ export class HelloFreshSession {
158
177
  /** Whether that refresh was written back to the browser (which may then rotate it on its own). */
159
178
  ownWrittenBack = false;
160
179
  seen = [];
180
+ /** The stored record is read once, on the first lifecycle. */
181
+ restored = false;
182
+ /** Identity of what was last saved, to skip rewriting an unchanged record. */
183
+ savedKey;
161
184
  constructor(opts) {
162
185
  this.opts = opts;
163
186
  this.fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
@@ -236,12 +259,15 @@ export class HelloFreshSession {
236
259
  }
237
260
  catch (err) {
238
261
  const ours = this.latest;
239
- if (!ours || ours.refresh_token !== this.ownRefreshToken)
262
+ if (!ours)
240
263
  throw err;
241
- // Written back: the browser may have rotated (spent) its refresh token — use the access token only.
242
- if (this.ownWrittenBack ? !this.fresh(ours) : !this.refreshable(ours))
264
+ // Only our own never-written-back refresh token is ours alone to spend; any
265
+ // other set (the browser's, or ours once written back) stands in by its
266
+ // still-valid access token only — the browser may have rotated its refresh token.
267
+ const ownUnwritten = ours.refresh_token === this.ownRefreshToken && !this.ownWrittenBack;
268
+ if (ownUnwritten ? !this.refreshable(ours) : !this.fresh(ours))
243
269
  throw err;
244
- console.error(`[hellofresh-mcp] could not read the browser session (${truncateErrorMessage(this.redact(messageOf(err)), 200)}); using this process's own refreshed session`);
270
+ console.error(`[hellofresh-mcp] could not read the browser session (${truncateErrorMessage(this.redact(messageOf(err)), 200)}); using the last session this server knew of`);
245
271
  return ours;
246
272
  }
247
273
  if (!raw)
@@ -257,12 +283,43 @@ export class HelloFreshSession {
257
283
  return browserIsNewest ? browser : ours;
258
284
  }
259
285
  async lifecycle() {
286
+ if (!this.restored) {
287
+ this.restored = true;
288
+ const stored = await this.loadStored();
289
+ if (stored)
290
+ this.adopt(stored);
291
+ }
260
292
  const newest = await this.newestSet();
261
293
  if (this.fresh(newest)) {
262
- this.latest = newest;
294
+ if (newest !== this.latest) {
295
+ this.latest = newest;
296
+ this.ownRefreshToken = undefined;
297
+ }
298
+ await this.persist();
263
299
  return newest;
264
300
  }
265
- const next = await this.refresh(newest);
301
+ return this.locked(() => this.refreshLocked(newest));
302
+ }
303
+ /** Step 3, holding the store's cross-process lock. */
304
+ async refreshLocked(newest) {
305
+ // A sibling process may have refreshed while we waited: take its set rather
306
+ // than POST a refresh token it has already spent.
307
+ const stored = await this.loadStored();
308
+ if (stored && stored.set.issued_at > newest.issued_at && this.fresh(stored.set)) {
309
+ this.adopt(stored);
310
+ return stored.set;
311
+ }
312
+ let next;
313
+ try {
314
+ next = await this.refresh(newest);
315
+ }
316
+ catch (err) {
317
+ // A dead session must not be read back off disk — unless a sibling's newer record replaced ours.
318
+ if (err instanceof HelloFreshSessionError && (!stored || stored.set.issued_at <= newest.issued_at)) {
319
+ await this.store('clear', () => this.opts.persistence?.clear?.());
320
+ }
321
+ throw err;
322
+ }
266
323
  this.latest = next;
267
324
  this.ownRefreshToken = next.refresh_token;
268
325
  this.ownWrittenBack = false;
@@ -276,8 +333,56 @@ export class HelloFreshSession {
276
333
  this.writeBackWarning = WRITE_BACK_WARNING;
277
334
  console.error(`[hellofresh-mcp] could not write the refreshed session back to the browser: ${truncateErrorMessage(this.redact(messageOf(err)), 200)}`);
278
335
  }
336
+ await this.persist();
279
337
  return next;
280
338
  }
339
+ /** Take a stored record as this process's newest known set. */
340
+ adopt(stored) {
341
+ this.latest = stored.set;
342
+ this.ownRefreshToken = stored.own ? stored.set.refresh_token : undefined;
343
+ this.ownWrittenBack = stored.own && stored.writtenBack;
344
+ this.savedKey = this.keyOf(stored.set);
345
+ this.remember(stored.set);
346
+ }
347
+ keyOf(set) {
348
+ const own = set.refresh_token === this.ownRefreshToken;
349
+ return `${set.access_token}\u0000${set.refresh_token}\u0000${own}\u0000${own && this.ownWrittenBack}`;
350
+ }
351
+ async persist() {
352
+ const set = this.latest;
353
+ if (!this.opts.persistence || !set)
354
+ return;
355
+ const key = this.keyOf(set);
356
+ if (key === this.savedKey)
357
+ return;
358
+ const own = set.refresh_token === this.ownRefreshToken;
359
+ const ok = await this.store('save', () => this.opts.persistence?.save(toPersistedSession(set, { own, writtenBack: this.ownWrittenBack })));
360
+ if (ok)
361
+ this.savedKey = key;
362
+ }
363
+ async loadStored() {
364
+ let stored = null;
365
+ await this.store('load', async () => {
366
+ stored = (await this.opts.persistence?.load()) ?? null;
367
+ });
368
+ return stored;
369
+ }
370
+ locked(fn) {
371
+ const store = this.opts.persistence;
372
+ return store?.withLock ? store.withLock(fn) : fn();
373
+ }
374
+ /** Run a store operation; a failure is logged (redacted), never thrown. */
375
+ async store(op, fn) {
376
+ try {
377
+ await fn();
378
+ return true;
379
+ }
380
+ catch (err) {
381
+ console.error(`[hellofresh-mcp] could not ${op} the ${op === 'load' ? 'saved ' : ''}HelloFresh session on disk ` +
382
+ `(${truncateErrorMessage(this.redact(messageOf(err)), 200)}); continuing without it.`);
383
+ return false;
384
+ }
385
+ }
281
386
  async bridged(fn) {
282
387
  try {
283
388
  return await fn();
package/dist/version.js CHANGED
@@ -2,4 +2,4 @@
2
2
  // literal below on release; every manifest that carries a version is listed in
3
3
  // release-please-config.json's extra-files and kept in lockstep by
4
4
  // tests/version-sync.test.ts. Keep the release marker on the export line only.
5
- export const VERSION = '0.3.0'; // x-release-please-version
5
+ export const VERSION = '0.4.0'; // x-release-please-version
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "hellofresh-mcp",
5
5
  "display_name": "HelloFresh",
6
- "version": "0.3.0",
6
+ "version": "0.4.0",
7
7
  "description": "Unofficial HelloFresh (US) tools for Claude — subscription, weekly deliveries, menus, meal picks, skips and box sizes via your signed-in browser",
8
8
  "author": {
9
9
  "name": "Chris Chall",
@@ -39,7 +39,9 @@
39
39
  "MCP_CONFIRM_ELICITATION": "${user_config.confirm_elicitation}",
40
40
  "HELLOFRESH_DEBUG": "${user_config.debug}",
41
41
  "HELLOFRESH_PROFILES": "${user_config.profiles}",
42
- "HELLOFRESH_PROFILES_FILE": "${user_config.profiles_file}"
42
+ "HELLOFRESH_PROFILES_FILE": "${user_config.profiles_file}",
43
+ "HELLOFRESH_SESSION_FILE": "${user_config.session_file}",
44
+ "HELLOFRESH_SESSION_CACHE": "${user_config.session_cache}"
43
45
  }
44
46
  }
45
47
  },
@@ -86,6 +88,18 @@
86
88
  "title": "Planner profiles file (optional)",
87
89
  "description": "Optional. Path to a JSON file of meal-planner profiles. Defaults to ~/.config/hellofresh-mcp/profiles.json (used only when it exists).",
88
90
  "required": false
91
+ },
92
+ "session_file": {
93
+ "type": "string",
94
+ "title": "Session file (optional)",
95
+ "description": "Optional. Where the HelloFresh session is kept so it survives a restart (the token set only, never your id or email; file mode 0600). Defaults to ~/.hellofresh-mcp/session.json. Leave blank for the default.",
96
+ "required": false
97
+ },
98
+ "session_cache": {
99
+ "type": "string",
100
+ "title": "Keep the session across restarts (optional)",
101
+ "description": "Optional. \"false\" keeps the HelloFresh session in memory only, so every start reads it from the browser again. Defaults to on. Leave blank for the default.",
102
+ "required": false
89
103
  }
90
104
  },
91
105
  "tools": [
package/mint.yaml CHANGED
@@ -68,12 +68,26 @@ env:
68
68
  ~/.config/hellofresh-mcp/profiles.json, read only when it exists). When
69
69
  hosted, the file must live under the persistent dataDir; otherwise use
70
70
  HELLOFRESH_PROFILES.
71
+ - name: HELLOFRESH_SESSION_FILE
72
+ required: false
73
+ help: >-
74
+ Where the HelloFresh session (token set, never the customer's id or
75
+ email) is kept so it survives a restart. Defaults to
76
+ .hellofresh-mcp/session.json under the persistent dataDir (MCP_DATA_DIR),
77
+ else under HOME.
78
+ - name: HELLOFRESH_SESSION_CACHE
79
+ required: false
80
+ help: >-
81
+ on (default) keeps the session on disk across restarts; false keeps it
82
+ in memory only, so every start reads it from the browser again.
71
83
  state:
72
84
  dataDir: true
73
85
  reason: >-
74
86
  keeps the fetchproxy identity under
75
87
  $HOME/.fetchproxy/identity/hellofresh-mcp.json so the browser pairing
76
- survives restarts; without it every cold start asks the user to re-pair
88
+ survives restarts (without it every cold start asks the user to re-pair),
89
+ and the HelloFresh session under .hellofresh-mcp/session.json so a cold
90
+ start can reuse it while the browser is away
77
91
  # The server process dials only the HelloFresh API on www.hellofresh.com. The
78
92
  # apiV2Auth cookie is read and written only by the user's browser over the
79
93
  # bridge, never by this process.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chrischall/hellofresh-mcp",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "mcpName": "io.github.chrischall/hellofresh-mcp",
6
6
  "description": "Unofficial HelloFresh (US) MCP server for Claude — subscription, weekly deliveries, menus, meal picks, skips and box sizes — developed and maintained by AI (Claude Code)",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/hellofresh-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.3.0",
9
+ "version": "0.4.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "@chrischall/hellofresh-mcp",
14
- "version": "0.3.0",
14
+ "version": "0.4.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -57,6 +57,18 @@
57
57
  "description": "Path to a JSON file of meal-planner profiles. Defaults to ~/.config/hellofresh-mcp/profiles.json, read only when it exists.",
58
58
  "isRequired": false,
59
59
  "format": "string"
60
+ },
61
+ {
62
+ "name": "HELLOFRESH_SESSION_FILE",
63
+ "description": "Where the HelloFresh session is kept across restarts (token set only, 0600). Defaults to .hellofresh-mcp/session.json under MCP_DATA_DIR, else HOME.",
64
+ "isRequired": false,
65
+ "format": "string"
66
+ },
67
+ {
68
+ "name": "HELLOFRESH_SESSION_CACHE",
69
+ "description": "on (default) keeps the session on disk across restarts; false keeps it in memory only.",
70
+ "isRequired": false,
71
+ "format": "string"
60
72
  }
61
73
  ]
62
74
  }