@chrischall/hellofresh-mcp 0.0.0-stage → 0.1.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.
@@ -0,0 +1,219 @@
1
+ // The weekly-planner scoring: pure functions over a projected menu, no I/O.
2
+ //
3
+ // Everything household-specific comes from a planner PROFILE (src/profiles.ts):
4
+ // how many people and meals, which recipe categories are allowed, and which
5
+ // traits to favour. The scoring, per dish (one per recipe: see dishes()):
6
+ // - kidFriendly profiles: family-friendly recipes boosted, spicy marked down;
7
+ // - maxMinutes: recipes within it boosted strongly, slower ones marked down
8
+ // (without maxMinutes a mild preference for ≤ 30 min);
9
+ // - adventurous profiles: less familiar cuisines boosted, and premiums within
10
+ // the cap only lightly penalised;
11
+ // - premiums over the profile's per-serving cap are excluded; under it they
12
+ // cost points in proportion to the upcharge × servings.
13
+ // Picks then favour protein diversity (distinct categories, and within
14
+ // Seafood distinct kinds — e.g. one shrimp + one fish) and never repeat a
15
+ // recently picked recipe. Each recipe is ONE dish: a base course in the allowed
16
+ // categories stands for itself (never an upgrade swap such as "2x Tilapia");
17
+ // only a base outside them is replaced by its cheapest allowed protein swap.
18
+ // Picks and alternates are always distinct recipes.
19
+ import { profileLabel } from './profiles.js';
20
+ /** The bonus for a pick whose protein is not yet in the box. */
21
+ const DIVERSITY_BONUS = 15;
22
+ const QUICK_MINUTES = 30;
23
+ /** Cuisines that do not count as adventurous. */
24
+ const FAMILIAR_CUISINES = new Set(['American', 'Italian', 'Irish', 'British']);
25
+ export const dollars = (cents) => `$${(cents / 100).toFixed(2)}`;
26
+ const normalName = (name) => name.trim().toLowerCase().replace(/\s+/g, ' ');
27
+ const courseOf = (c) => c.baseIndex ?? c.index;
28
+ /** A double-protein swap ("2x Shrimp", "… with 2x Tilapia"): an upgrade, not a swap. */
29
+ const isDouble = (v) => /\b2x\b/i.test(`${v.title ?? ''} ${v.name ?? ''}`);
30
+ /**
31
+ * One dish per recipe (a base course and its protein swaps are ONE recipe):
32
+ * the base course itself when it is in the allowed categories (or there is no
33
+ * allowlist) — never an upgrade swap of it; otherwise the cheapest swap that
34
+ * IS allowed (e.g. a shrimp swap of a chicken dish), a double-protein swap
35
+ * only when no single-protein swap qualifies; none when nothing qualifies.
36
+ */
37
+ function dishes(menu, allowed) {
38
+ return menu.meals.flatMap((course) => {
39
+ if (allowed(course.category)) {
40
+ return [
41
+ {
42
+ dish: {
43
+ index: course.index,
44
+ name: course.name,
45
+ category: course.category,
46
+ seafoodKind: course.seafoodKind,
47
+ premiumPerServingCents: course.premiumPerServingCents,
48
+ selected: course.selectedQuantity > 0,
49
+ },
50
+ course,
51
+ },
52
+ ];
53
+ }
54
+ const [swap] = course.variants
55
+ .filter((v) => allowed(v.category))
56
+ .sort((a, b) => Number(isDouble(a)) - Number(isDouble(b)) || a.premiumPerServingCents - b.premiumPerServingCents || a.index - b.index);
57
+ if (!swap)
58
+ return [];
59
+ return [
60
+ {
61
+ dish: {
62
+ index: swap.index,
63
+ baseIndex: course.index,
64
+ name: swap.name ?? swap.title,
65
+ category: swap.category,
66
+ seafoodKind: swap.seafoodKind,
67
+ premiumPerServingCents: swap.premiumPerServingCents,
68
+ selected: swap.selectedQuantity > 0,
69
+ },
70
+ course,
71
+ },
72
+ ];
73
+ });
74
+ }
75
+ const proteinOf = (d) => d.seafoodKind ?? d.category ?? 'unknown';
76
+ function score(dish, course, profile, people) {
77
+ const reasons = [];
78
+ let points = 0;
79
+ const add = (n, why) => {
80
+ points += n;
81
+ reasons.push(why);
82
+ };
83
+ const minutes = course.totalMinutes;
84
+ const premiumBoxCents = dish.premiumPerServingCents * people;
85
+ if (profile.kidFriendly) {
86
+ if (course.kidFriendly)
87
+ add(30, 'kid friendly');
88
+ if (course.tags.some((t) => /spicy/i.test(t)))
89
+ add(-10, 'spicy');
90
+ }
91
+ if (minutes !== undefined) {
92
+ const limit = profile.maxMinutes ?? QUICK_MINUTES;
93
+ const [bonus, penalty] = profile.maxMinutes !== undefined ? [20, -15] : [5, -5];
94
+ if (minutes <= limit)
95
+ add(bonus, `ready in ${minutes} min`);
96
+ else
97
+ add(penalty, `takes ${minutes} min (over ${limit})`);
98
+ }
99
+ if (profile.adventurous && course.cuisine && !FAMILIAR_CUISINES.has(course.cuisine))
100
+ add(15, `adventurous: ${course.cuisine}`);
101
+ if (premiumBoxCents > 0) {
102
+ const why = `premium +${dollars(dish.premiumPerServingCents)}/serving (+${dollars(premiumBoxCents)} for ${people} servings)`;
103
+ add(profile.adventurous ? 5 - Math.round(premiumBoxCents / 200) : -Math.round(premiumBoxCents / 100), why);
104
+ }
105
+ return {
106
+ ...dish,
107
+ protein: proteinOf(dish),
108
+ kidFriendly: course.kidFriendly,
109
+ quick: course.quick,
110
+ totalMinutes: minutes,
111
+ cuisine: course.cuisine,
112
+ premiumBoxCents,
113
+ score: points,
114
+ reasons,
115
+ };
116
+ }
117
+ /** Greedy: each next pick is the best score (+ the diversity bonus for a new protein) from a course not yet used. */
118
+ function choose(ranked, count) {
119
+ const picks = [];
120
+ while (picks.length < count) {
121
+ const courses = new Set(picks.map(courseOf));
122
+ const proteins = new Set(picks.map((p) => p.protein));
123
+ let best;
124
+ for (const c of ranked) {
125
+ if (courses.has(courseOf(c)))
126
+ continue;
127
+ const total = c.score + (picks.length > 0 && !proteins.has(c.protein) ? DIVERSITY_BONUS : 0);
128
+ if (!best || total > best.total)
129
+ best = { c, total };
130
+ }
131
+ if (!best)
132
+ break;
133
+ picks.push(best.c);
134
+ }
135
+ return picks;
136
+ }
137
+ /** Rank the week's menu for a profile and choose its meals plus 2 alternates per slot. */
138
+ export function suggestMeals(menu, opts) {
139
+ const { profile } = opts;
140
+ const people = opts.people ?? profile.people;
141
+ const cap = opts.maxPremiumPerServingCents ?? profile.premiumCapCents;
142
+ const categories = profile.categories ? new Set(profile.categories.map((c) => c.toLowerCase())) : undefined;
143
+ const avoidIndexes = new Set(opts.avoidIndexes ?? []);
144
+ const avoidNames = new Set((opts.avoidNames ?? []).map(normalName));
145
+ const allowed = (category) => !categories || categories.has((category ?? '').toLowerCase());
146
+ const excluded = [];
147
+ const eligible = [];
148
+ for (const { dish, course } of dishes(menu, allowed)) {
149
+ const reason = avoidIndexes.has(dish.index)
150
+ ? 'avoided by request'
151
+ : dish.name && avoidNames.has(normalName(dish.name))
152
+ ? 'picked in a recent week'
153
+ : dish.premiumPerServingCents > cap
154
+ ? `premium ${dollars(dish.premiumPerServingCents)}/serving over the ${dollars(cap)} cap`
155
+ : undefined;
156
+ if (reason)
157
+ excluded.push({ index: dish.index, name: dish.name, reason });
158
+ else
159
+ eligible.push(score(dish, course, profile, people));
160
+ }
161
+ const ranked = eligible.sort((a, b) => b.score - a.score || a.index - b.index);
162
+ const picks = choose(ranked, profile.meals);
163
+ // Every pick and alternate is a distinct RECIPE (a swap shares its base course's recipe).
164
+ const usedRecipes = new Set(picks.map(courseOf));
165
+ const alternates = picks.map((pick, slot) => {
166
+ const options = ranked
167
+ .filter((c) => !usedRecipes.has(courseOf(c)))
168
+ .sort((a, b) => Number(b.protein === pick.protein) - Number(a.protein === pick.protein))
169
+ .slice(0, 2);
170
+ for (const o of options)
171
+ usedRecipes.add(courseOf(o));
172
+ return { slot: slot + 1, for: pick.name, options };
173
+ });
174
+ const scope = profile.categories ? ` (${profile.categories.join(', ')})` : '';
175
+ return {
176
+ profile: profile.name,
177
+ meals: profile.meals,
178
+ people,
179
+ maxPremiumPerServingCents: cap,
180
+ picks,
181
+ alternates,
182
+ ranked,
183
+ excluded,
184
+ ...(picks.length < profile.meals
185
+ ? {
186
+ warning: `Only ${picks.length} of the ${profile.meals} meals could be suggested: the menu has too few distinct courses ` +
187
+ `matching the profile${scope} within the premium cap and not recently picked. Raise the cap, allow repeats, ` +
188
+ 'or pick the rest by hand.',
189
+ }
190
+ : {}),
191
+ };
192
+ }
193
+ // ---- the approval line -------------------------------------------------------------
194
+ const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
195
+ /** `Mon 11/30` from an ISO date/timestamp as HelloFresh wrote it (its own offset), or undefined. */
196
+ export function dayLabel(iso) {
197
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso ?? '');
198
+ if (!m)
199
+ return undefined;
200
+ const [year, month, day] = [Number(m[1]), Number(m[2]), Number(m[3])];
201
+ return `${WEEKDAYS[new Date(Date.UTC(year, month - 1, day)).getUTCDay()]} ${month}/${day}`;
202
+ }
203
+ /**
204
+ * The approval line:
205
+ * `Family week (4 servings) — delivering Mon 11/30: <A> + <B>. Est. box total $X (−$Y CODE).`
206
+ */
207
+ export function summaryText({ profile, people, deliveryDate, picks, estimate }) {
208
+ const meals = picks.length > 0 ? picks.map((p) => p.name?.trim() || '(unnamed meal)').join(' + ') : 'no picks fit';
209
+ let total = 'Box total not estimated.';
210
+ if (estimate) {
211
+ const discount = estimate.discountCents > 0
212
+ ? `−${dollars(estimate.discountCents)}${estimate.voucher?.code ? ` ${estimate.voucher.code}` : ''}`
213
+ : 'no voucher discount';
214
+ total = `Est. box total ${dollars(estimate.totalCents)} (${discount}).`;
215
+ }
216
+ const label = profileLabel(profile);
217
+ const week = /week$/i.test(label.trim()) ? label.trim() : `${label} week`;
218
+ return `${week} (${people ?? profile.people} servings) — delivering ${dayLabel(deliveryDate) ?? '(date unknown)'}: ${meals}. ${total}`;
219
+ }
@@ -0,0 +1,121 @@
1
+ // Planner profiles: named, reusable descriptions of who a week's box feeds and
2
+ // how to rank its menu. Loaded from local config so nothing about a particular
3
+ // household lives in this repo:
4
+ //
5
+ // 1. HELLOFRESH_PROFILES — an inline JSON array;
6
+ // 2. HELLOFRESH_PROFILES_FILE — a JSON file (default ~/.config/hellofresh-mcp/profiles.json,
7
+ // used only when it exists);
8
+ // 3. the generic built-ins — "couple" and "family".
9
+ //
10
+ // Parsed once per process. A malformed config never stops the server booting
11
+ // (deferred-config-error pattern): it surfaces as a clear tool error, naming
12
+ // the variable or file, the first time a planner tool needs it.
13
+ import { readFileSync } from 'node:fs';
14
+ import { z } from 'zod';
15
+ import { McpToolError, expandPath, readEnvVar } from '@chrischall/mcp-utils';
16
+ export const PROFILES_ENV = 'HELLOFRESH_PROFILES';
17
+ export const PROFILES_FILE_ENV = 'HELLOFRESH_PROFILES_FILE';
18
+ export const DEFAULT_PROFILES_FILE = '~/.config/hellofresh-mcp/profiles.json';
19
+ const profileSchema = z.strictObject({
20
+ name: z
21
+ .string()
22
+ .regex(/^[a-z0-9][a-z0-9_-]*$/, 'name must be a lowercase slug (a-z, 0-9, - and _)')
23
+ .max(40),
24
+ label: z.string().trim().min(1).max(60).optional(),
25
+ people: z.union([z.literal(2), z.literal(3), z.literal(4), z.literal(6)]),
26
+ meals: z.number().int().min(2).max(6).default(2),
27
+ categories: z.array(z.string().trim().min(1)).min(1).optional(),
28
+ kidFriendly: z.boolean().optional(),
29
+ maxMinutes: z.number().int().positive().optional(),
30
+ premiumCapCents: z.number().int().min(0),
31
+ adventurous: z.boolean().optional(),
32
+ avoidRepeatWeeks: z.number().int().min(0).max(12).default(4),
33
+ });
34
+ const profilesSchema = z.array(profileSchema).min(1, 'at least one profile is required');
35
+ export const BUILTIN_PROFILES = [
36
+ { name: 'couple', people: 2, meals: 2, premiumCapCents: 1000, adventurous: true, avoidRepeatWeeks: 4 },
37
+ { name: 'family', people: 4, meals: 2, kidFriendly: true, maxMinutes: 30, premiumCapCents: 500, avoidRepeatWeeks: 4 },
38
+ ];
39
+ export class ProfileConfigError extends McpToolError {
40
+ constructor(message) {
41
+ super(message, {
42
+ hint: `Fix ${PROFILES_ENV} (an inline JSON array) or the ${PROFILES_FILE_ENV} file (default ${DEFAULT_PROFILES_FILE}): ` +
43
+ 'each profile needs name, people (2/3/4/6) and premiumCapCents. Restart the server after editing.',
44
+ });
45
+ this.name = 'ProfileConfigError';
46
+ }
47
+ }
48
+ function parse(text, source) {
49
+ let raw;
50
+ try {
51
+ raw = JSON.parse(text);
52
+ }
53
+ catch {
54
+ throw new ProfileConfigError(`Planner profiles from ${source} are not valid JSON.`);
55
+ }
56
+ const result = profilesSchema.safeParse(raw);
57
+ if (!result.success) {
58
+ const issues = result.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; ');
59
+ throw new ProfileConfigError(`Planner profiles from ${source} are invalid — ${issues}`);
60
+ }
61
+ const seen = new Set();
62
+ for (const p of result.data) {
63
+ if (seen.has(p.name))
64
+ throw new ProfileConfigError(`Planner profiles from ${source} are invalid — duplicate profile name "${p.name}".`);
65
+ seen.add(p.name);
66
+ }
67
+ return result.data;
68
+ }
69
+ const isMissing = (e) => e?.code === 'ENOENT';
70
+ /** Load the profiles (env → file → built-ins). Throws {@link ProfileConfigError} on a bad config. */
71
+ export function loadProfiles({ env = process.env, readFile = (p) => readFileSync(p, 'utf8') } = {}) {
72
+ const inline = readEnvVar(PROFILES_ENV, { env });
73
+ if (inline !== undefined)
74
+ return { profiles: parse(inline, PROFILES_ENV), source: PROFILES_ENV };
75
+ const configured = readEnvVar(PROFILES_FILE_ENV, { env });
76
+ const path = configured ?? DEFAULT_PROFILES_FILE;
77
+ let text;
78
+ try {
79
+ text = readFile(expandPath(path));
80
+ }
81
+ catch (e) {
82
+ if (configured === undefined && isMissing(e))
83
+ return { profiles: BUILTIN_PROFILES, source: 'built-in defaults' };
84
+ const why = e instanceof Error ? e.message : String(e);
85
+ const via = configured === undefined ? path : `${PROFILES_FILE_ENV} (${path})`;
86
+ throw new ProfileConfigError(`Could not read planner profiles from ${via}: ${why}`);
87
+ }
88
+ return { profiles: parse(text, path), source: path };
89
+ }
90
+ /** A load-once accessor: the first call loads, later calls return (or rethrow) the same result. */
91
+ export function createProfileStore(load = () => loadProfiles()) {
92
+ let cached;
93
+ return () => {
94
+ if (!cached) {
95
+ try {
96
+ cached = { ok: true, value: load() };
97
+ }
98
+ catch (error) {
99
+ cached = { ok: false, error };
100
+ }
101
+ }
102
+ if (!cached.ok)
103
+ throw cached.error;
104
+ return cached.value;
105
+ };
106
+ }
107
+ /** The named profile; an unknown name is a tool error listing the configured ones. */
108
+ export function resolveProfile(loaded, name) {
109
+ const wanted = name.trim().toLowerCase();
110
+ const found = loaded.profiles.find((p) => p.name === wanted);
111
+ if (!found) {
112
+ throw new McpToolError(`No profile "${name}". Configured profiles: ${loaded.profiles.map((p) => p.name).join(', ')}.`, {
113
+ hint: 'hf_list_profiles shows each profile and where they were loaded from.',
114
+ });
115
+ }
116
+ return found;
117
+ }
118
+ /** The display label: the configured one, else the capitalised name. */
119
+ export const profileLabel = (p) => p.label ?? p.name.charAt(0).toUpperCase() + p.name.slice(1);
120
+ /** The box SKU a profile's week needs (`people` overrides the profile's). */
121
+ export const profileSku = (p, people = p.people) => `US-CBU-${p.meals}-${people}-0`;
@@ -0,0 +1,287 @@
1
+ // The HelloFresh session: the `apiV2Auth` token set the web app keeps in a
2
+ // cookie on www.hellofresh.com, read (and, after a refresh, written back)
3
+ // through ContextMint Bridge. Every API call is a plain Node fetch with the
4
+ // access token as a Bearer.
5
+ //
6
+ // Lifecycle (single-flight, see docs/PLAN.md):
7
+ // 1. A cached access token with > 60 s left is used as is.
8
+ // 2. Otherwise read the browser cookie; if ITS access token has > 60 s left
9
+ // (the browser refreshed itself), use it.
10
+ // 3. Otherwise refresh from Node (`POST /gw/refresh`). The refresh token
11
+ // ROTATES and the response sets no cookie, so the new set is written back
12
+ // into the browser's cookie — or the browser keeps a spent refresh token
13
+ // and is signed out. A failed write-back still uses the new tokens, but
14
+ // surfaces WRITE_BACK_WARNING.
15
+ // 4. A 401 from any call invalidates the token, re-runs the lifecycle once
16
+ // (never trusting the rejected token again) and retries the call once.
17
+ //
18
+ // No token value is ever logged, put in an error message or returned.
19
+ import { EdgeBlockedError, McpToolError, SessionNotAuthenticatedError, createCachedTokenSource, decodeJwtClaim, detectEdgeBlock, messageOf, parseJsonBody, redactValues, truncateErrorMessage, } from '@chrischall/mcp-utils';
20
+ import { AUTH_COOKIE } from './transport.js';
21
+ export const WEB_ORIGIN = 'https://www.hellofresh.com';
22
+ /** Refresh endpoint (VERIFIED). Note the lower-case `country=us` the web app sends. */
23
+ export const REFRESH_URL = `${WEB_ORIGIN}/gw/refresh?country=us&locale=en-US`;
24
+ /** A token with this little life left is treated as expired. */
25
+ export const EXPIRY_SKEW_MS = 60_000;
26
+ /** Bound on the refresh POST. Never tied to the caller's cancellation: the refresh token rotates in flight. */
27
+ export const REFRESH_TIMEOUT_MS = 30_000;
28
+ export const WRITE_BACK_WARNING = 'HelloFresh session was refreshed, but the new tokens could not be written back to the browser: ' +
29
+ 'the browser session may be signed out; sign in again at https://www.hellofresh.com if it is.';
30
+ /** The documented key order of the cookie JSON. */
31
+ const KEY_ORDER = [
32
+ 'access_token',
33
+ 'expires_in',
34
+ 'refresh_token',
35
+ 'token_type',
36
+ 'user_data',
37
+ 'refresh_expires_in',
38
+ 'issued_at',
39
+ ];
40
+ export function signInHint() {
41
+ return `Sign in at ${WEB_ORIGIN} in the browser running ContextMint Bridge, then retry.`;
42
+ }
43
+ /** No usable HelloFresh session in the browser. */
44
+ export class HelloFreshSessionError extends SessionNotAuthenticatedError {
45
+ constructor(reason, hint = signInHint()) {
46
+ super('HelloFresh', 'www.hellofresh.com');
47
+ this.message = `Not signed in to HelloFresh: ${reason}.`;
48
+ Object.defineProperty(this, 'hint', { value: hint, enumerable: true, configurable: true });
49
+ }
50
+ }
51
+ /** Reading through the bridge failed for an unclassified reason. */
52
+ export class HelloFreshBridgeError extends McpToolError {
53
+ constructor(message, cause, hint = signInHint()) {
54
+ super(message, { hint, cause });
55
+ this.name = 'HelloFreshBridgeError';
56
+ }
57
+ }
58
+ /**
59
+ * The fleet's `fetchproxyHintOf` rule: a `Fetchproxy*` error carrying a typed
60
+ * hint (pairing pending, no tab, bridge down) already names its remedy, so it is
61
+ * surfaced unmodified. Duck-typed — a duplicated package breaks `instanceof`.
62
+ */
63
+ export function isHintedFetchproxyError(err) {
64
+ if (!(err instanceof Error) || !err.name.startsWith('Fetchproxy'))
65
+ return false;
66
+ const hint = err.hint;
67
+ return typeof hint === 'string' && hint.length > 0;
68
+ }
69
+ /**
70
+ * @fetchproxy/server rejects calls while a pairing is pending with an error
71
+ * carrying no `.hint` — only the code in its message. Pull the code out so the
72
+ * user is told to approve it, not to sign in.
73
+ */
74
+ export function pendingPairCode(err) {
75
+ const msg = messageOf(err);
76
+ if (!/pairing required/i.test(msg))
77
+ return undefined;
78
+ return /pair code is:?\s*(\d{4}-\d{4})/i.exec(msg)?.[1];
79
+ }
80
+ export function approvePairHint(code) {
81
+ return `Open the ContextMint Bridge extension popup in the browser signed in to ${WEB_ORIGIN}, approve pair code ${code} for hellofresh-mcp, then retry.`;
82
+ }
83
+ /**
84
+ * Encode a token set exactly as the site's js-cookie v3 does:
85
+ * `encodeURIComponent`, then DE-code `# $ & + / : < = > ? @ [ ] ^ \` { | }`
86
+ * back to literals — so `"` → `%22` and `,` → `%2C` while `{ } : [ ]` stay.
87
+ */
88
+ export function encodeAuthCookie(set) {
89
+ const ordered = {};
90
+ for (const key of KEY_ORDER)
91
+ if (set[key] !== undefined)
92
+ ordered[key] = set[key];
93
+ for (const [key, value] of Object.entries(set))
94
+ if (!(key in ordered))
95
+ ordered[key] = value;
96
+ return encodeURIComponent(JSON.stringify(ordered)).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, decodeURIComponent);
97
+ }
98
+ /** Decode a raw `apiV2Auth` value (js-cookie v3 read semantics). Never echoes the value. */
99
+ export function decodeAuthCookie(raw) {
100
+ let parsed;
101
+ try {
102
+ const unquoted = raw.startsWith('"') ? raw.slice(1, -1) : raw;
103
+ parsed = JSON.parse(unquoted.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent));
104
+ }
105
+ catch {
106
+ throw new HelloFreshSessionError(`the ${AUTH_COOKIE} cookie could not be read`);
107
+ }
108
+ if (!isTokenSet(parsed)) {
109
+ throw new HelloFreshSessionError(`the ${AUTH_COOKIE} cookie holds no token set`);
110
+ }
111
+ return parsed;
112
+ }
113
+ function isTokenSet(value) {
114
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
115
+ return false;
116
+ const v = value;
117
+ return typeof v['access_token'] === 'string' && v['access_token'] !== '' &&
118
+ typeof v['refresh_token'] === 'string' && v['refresh_token'] !== '';
119
+ }
120
+ /** Absolute access-token expiry, epoch ms: `issued_at + expires_in`, else the JWT `exp`, else 0 (expired). */
121
+ export function tokenExpiresAtMs(set) {
122
+ if (typeof set.issued_at === 'number' && typeof set.expires_in === 'number') {
123
+ return (set.issued_at + set.expires_in) * 1000;
124
+ }
125
+ const exp = decodeJwtClaim(set.access_token, 'exp');
126
+ return typeof exp === 'number' ? exp * 1000 : 0;
127
+ }
128
+ /** How many token values to remember for redaction. */
129
+ const REDACT_HISTORY = 8;
130
+ export class HelloFreshSession {
131
+ opts;
132
+ source;
133
+ fetchImpl;
134
+ now;
135
+ /** The newest token set this process knows of (browser's or our own refresh). */
136
+ latest;
137
+ /** The access token the cache currently holds. */
138
+ current;
139
+ /** An access token the API rejected: never trusted again, even if the cookie still holds it. */
140
+ rejected;
141
+ writeBackWarning;
142
+ seen = [];
143
+ constructor(opts) {
144
+ this.opts = opts;
145
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
146
+ this.now = opts.now ?? Date.now;
147
+ this.source = createCachedTokenSource({
148
+ mint: async () => {
149
+ const set = await this.lifecycle();
150
+ this.current = set.access_token;
151
+ return { token: set.access_token, expiresAt: tokenExpiresAtMs(set) };
152
+ },
153
+ bufferMs: EXPIRY_SKEW_MS,
154
+ now: this.now,
155
+ });
156
+ }
157
+ /** A valid access token (cached, the browser's, or freshly refreshed). */
158
+ getToken() {
159
+ return this.source.getToken();
160
+ }
161
+ /** Drop `token` (the API rejected it). A no-op when it is no longer the current token. */
162
+ invalidate(token) {
163
+ if (token !== this.current)
164
+ return;
165
+ this.rejected = token;
166
+ this.current = undefined;
167
+ this.source.invalidate();
168
+ }
169
+ /**
170
+ * Run `call` with a valid token; on a 401, re-run the lifecycle once and
171
+ * replay once. A 401 that is a CDN/WAF page is returned as is (no credential
172
+ * was judged), and a 401 for a token a concurrent caller already replaced
173
+ * replays with the current one without a second refresh.
174
+ */
175
+ async withAuth(call) {
176
+ const token = await this.getToken();
177
+ const res = await call(token);
178
+ if (res.status !== 401)
179
+ return res;
180
+ const body = await res.clone().text();
181
+ if (detectEdgeBlock({ status: 401, headers: res.headers, body }))
182
+ return res;
183
+ this.invalidate(token);
184
+ return call(await this.getToken());
185
+ }
186
+ /** The write-back warning, while the browser may hold a spent refresh token. */
187
+ warning() {
188
+ return this.writeBackWarning;
189
+ }
190
+ /** Minutes left on the newest known access token, or undefined before any. */
191
+ expiresInMinutes() {
192
+ if (!this.latest)
193
+ return undefined;
194
+ return Math.floor((tokenExpiresAtMs(this.latest) - this.now()) / 60_000);
195
+ }
196
+ /** Scrub every token value this session has seen out of `text`. */
197
+ redact(text) {
198
+ return redactValues(text, this.seen);
199
+ }
200
+ remember(set) {
201
+ this.seen.unshift(set.access_token, set.refresh_token);
202
+ this.seen.length = Math.min(this.seen.length, REDACT_HISTORY);
203
+ }
204
+ fresh(set) {
205
+ return set.access_token !== this.rejected && tokenExpiresAtMs(set) - this.now() > EXPIRY_SKEW_MS;
206
+ }
207
+ async lifecycle() {
208
+ const raw = await this.bridged(() => this.opts.bridge.readAuthCookie());
209
+ if (!raw)
210
+ throw new HelloFreshSessionError(`no ${AUTH_COOKIE} cookie was found on www.hellofresh.com`);
211
+ const browser = decodeAuthCookie(raw);
212
+ this.remember(browser);
213
+ // Our own refresh is newer than the cookie only when its write-back failed:
214
+ // then the cookie's refresh token is already spent and ours must be used.
215
+ const ours = this.latest;
216
+ const browserIsNewest = !ours || browser.issued_at >= ours.issued_at;
217
+ const newest = browserIsNewest ? browser : ours;
218
+ if (browserIsNewest)
219
+ this.writeBackWarning = undefined;
220
+ if (this.fresh(newest)) {
221
+ this.latest = newest;
222
+ return newest;
223
+ }
224
+ const next = await this.refresh(newest);
225
+ this.latest = next;
226
+ this.remember(next);
227
+ try {
228
+ await this.opts.bridge.writeAuthCookie(encodeAuthCookie(next));
229
+ this.writeBackWarning = undefined;
230
+ }
231
+ catch (err) {
232
+ this.writeBackWarning = WRITE_BACK_WARNING;
233
+ console.error(`[hellofresh-mcp] could not write the refreshed session back to the browser: ${truncateErrorMessage(this.redact(messageOf(err)), 200)}`);
234
+ }
235
+ return next;
236
+ }
237
+ async bridged(fn) {
238
+ try {
239
+ return await fn();
240
+ }
241
+ catch (err) {
242
+ if (isHintedFetchproxyError(err))
243
+ throw err;
244
+ const code = pendingPairCode(err);
245
+ if (code) {
246
+ throw new HelloFreshBridgeError(`HelloFresh pairing is pending: approve pair code ${code} in ContextMint Bridge.`, err, approvePairHint(code));
247
+ }
248
+ throw new HelloFreshBridgeError(`Could not read the HelloFresh session from the browser: ${truncateErrorMessage(messageOf(err), 200)}`, err);
249
+ }
250
+ }
251
+ async refresh(from) {
252
+ const where = { service: 'HelloFresh', method: 'POST', path: '/gw/refresh' };
253
+ let res;
254
+ let text;
255
+ try {
256
+ res = await this.fetchImpl(REFRESH_URL, {
257
+ method: 'POST',
258
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
259
+ body: JSON.stringify({ refresh_token: from.refresh_token }),
260
+ signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
261
+ });
262
+ text = await res.text();
263
+ }
264
+ catch (err) {
265
+ throw new McpToolError(`Could not refresh the HelloFresh session: ${truncateErrorMessage(this.redact(messageOf(err)), 200)}`, { kind: 'transport', cause: err });
266
+ }
267
+ if (!res.ok) {
268
+ const edge = detectEdgeBlock({ status: res.status, headers: res.headers, body: text });
269
+ if (edge)
270
+ throw new EdgeBlockedError(res.status, edge.vendor, where);
271
+ if (res.status === 401 || /"error"\s*:\s*"invalid_grant"/.test(text)) {
272
+ throw new HelloFreshSessionError('the browser session has expired or was signed out (the refresh was rejected)');
273
+ }
274
+ throw new McpToolError(`HelloFresh session refresh failed: HTTP ${res.status}: ${truncateErrorMessage(this.redact(text), 200)}`, { status: res.status, kind: 'http' });
275
+ }
276
+ const body = parseJsonBody(text, { ...where, expect: 'object', status: res.status, headers: res.headers });
277
+ if (!isTokenSet(body)) {
278
+ throw new McpToolError('HelloFresh session refresh did not return a token set.', { status: res.status });
279
+ }
280
+ return {
281
+ ...from,
282
+ ...body,
283
+ issued_at: typeof body.issued_at === 'number' ? body.issued_at : Math.floor(this.now() / 1000),
284
+ user_data: body.user_data ?? from.user_data,
285
+ };
286
+ }
287
+ }