@daften/mealie-mcp 0.1.0-alpha.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.
Files changed (101) hide show
  1. package/.env.example +36 -0
  2. package/CHANGELOG.md +17 -0
  3. package/LICENSE +21 -0
  4. package/README.md +73 -0
  5. package/dist/args.d.ts +14 -0
  6. package/dist/args.d.ts.map +1 -0
  7. package/dist/args.js +132 -0
  8. package/dist/args.js.map +1 -0
  9. package/dist/auth/crypto.d.ts +9 -0
  10. package/dist/auth/crypto.d.ts.map +1 -0
  11. package/dist/auth/crypto.js +34 -0
  12. package/dist/auth/crypto.js.map +1 -0
  13. package/dist/auth/index.d.ts +15 -0
  14. package/dist/auth/index.d.ts.map +1 -0
  15. package/dist/auth/index.js +77 -0
  16. package/dist/auth/index.js.map +1 -0
  17. package/dist/auth/login-method.d.ts +28 -0
  18. package/dist/auth/login-method.d.ts.map +1 -0
  19. package/dist/auth/login-method.js +2 -0
  20. package/dist/auth/login-method.js.map +1 -0
  21. package/dist/auth/mealie-session.d.ts +28 -0
  22. package/dist/auth/mealie-session.d.ts.map +1 -0
  23. package/dist/auth/mealie-session.js +81 -0
  24. package/dist/auth/mealie-session.js.map +1 -0
  25. package/dist/auth/password-login.d.ts +21 -0
  26. package/dist/auth/password-login.d.ts.map +1 -0
  27. package/dist/auth/password-login.js +168 -0
  28. package/dist/auth/password-login.js.map +1 -0
  29. package/dist/auth/provider.d.ts +41 -0
  30. package/dist/auth/provider.d.ts.map +1 -0
  31. package/dist/auth/provider.js +201 -0
  32. package/dist/auth/provider.js.map +1 -0
  33. package/dist/auth/redirects.d.ts +2 -0
  34. package/dist/auth/redirects.d.ts.map +1 -0
  35. package/dist/auth/redirects.js +71 -0
  36. package/dist/auth/redirects.js.map +1 -0
  37. package/dist/auth/store.d.ts +61 -0
  38. package/dist/auth/store.d.ts.map +1 -0
  39. package/dist/auth/store.js +201 -0
  40. package/dist/auth/store.js.map +1 -0
  41. package/dist/client.d.ts +39 -0
  42. package/dist/client.d.ts.map +1 -0
  43. package/dist/client.js +180 -0
  44. package/dist/client.js.map +1 -0
  45. package/dist/config.d.ts +16 -0
  46. package/dist/config.d.ts.map +1 -0
  47. package/dist/config.js +82 -0
  48. package/dist/config.js.map +1 -0
  49. package/dist/http.d.ts +54 -0
  50. package/dist/http.d.ts.map +1 -0
  51. package/dist/http.js +227 -0
  52. package/dist/http.js.map +1 -0
  53. package/dist/index.d.ts +3 -0
  54. package/dist/index.d.ts.map +1 -0
  55. package/dist/index.js +82 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/server.d.ts +5 -0
  58. package/dist/server.d.ts.map +1 -0
  59. package/dist/server.js +10 -0
  60. package/dist/server.js.map +1 -0
  61. package/dist/tools/_annotations.d.ts +17 -0
  62. package/dist/tools/_annotations.d.ts.map +1 -0
  63. package/dist/tools/_annotations.js +9 -0
  64. package/dist/tools/_annotations.js.map +1 -0
  65. package/dist/tools/_helpers.d.ts +50 -0
  66. package/dist/tools/_helpers.d.ts.map +1 -0
  67. package/dist/tools/_helpers.js +67 -0
  68. package/dist/tools/_helpers.js.map +1 -0
  69. package/dist/tools/index.d.ts +18 -0
  70. package/dist/tools/index.d.ts.map +1 -0
  71. package/dist/tools/index.js +53 -0
  72. package/dist/tools/index.js.map +1 -0
  73. package/dist/tools/ingredients.d.ts +4 -0
  74. package/dist/tools/ingredients.d.ts.map +1 -0
  75. package/dist/tools/ingredients.js +68 -0
  76. package/dist/tools/ingredients.js.map +1 -0
  77. package/dist/tools/mealplans.d.ts +4 -0
  78. package/dist/tools/mealplans.d.ts.map +1 -0
  79. package/dist/tools/mealplans.js +71 -0
  80. package/dist/tools/mealplans.js.map +1 -0
  81. package/dist/tools/organizers.d.ts +4 -0
  82. package/dist/tools/organizers.d.ts.map +1 -0
  83. package/dist/tools/organizers.js +49 -0
  84. package/dist/tools/organizers.js.map +1 -0
  85. package/dist/tools/recipe-assets.d.ts +4 -0
  86. package/dist/tools/recipe-assets.d.ts.map +1 -0
  87. package/dist/tools/recipe-assets.js +55 -0
  88. package/dist/tools/recipe-assets.js.map +1 -0
  89. package/dist/tools/recipes.d.ts +89 -0
  90. package/dist/tools/recipes.d.ts.map +1 -0
  91. package/dist/tools/recipes.js +206 -0
  92. package/dist/tools/recipes.js.map +1 -0
  93. package/dist/tools/shopping.d.ts +4 -0
  94. package/dist/tools/shopping.d.ts.map +1 -0
  95. package/dist/tools/shopping.js +94 -0
  96. package/dist/tools/shopping.js.map +1 -0
  97. package/dist/types.d.ts +2 -0
  98. package/dist/types.d.ts.map +1 -0
  99. package/dist/types.js +2 -0
  100. package/dist/types.js.map +1 -0
  101. package/package.json +82 -0
package/.env.example ADDED
@@ -0,0 +1,36 @@
1
+ # Required for every mode
2
+ MEALIE_URL=https://your-mealie-instance.example.com
3
+
4
+ # --- Choose ONE auth mode ---------------------------------------------------
5
+
6
+ # 1. stdio (default transport): required. Create one in Mealie under Profile → API Tokens.
7
+ # Over HTTP (--transport http), setting this makes every request act as this one Mealie
8
+ # user, with no authentication: anyone who can reach the port has that account's access.
9
+ # Leave it unset over HTTP and each caller sends their own key as a Bearer token.
10
+ # MEALIE_API_TOKEN=your-mealie-api-token
11
+
12
+ # 2. Login form (HTTP only). Users type their Mealie password on a page served by this MCP
13
+ # server, not by Mealie, so only enable it on a server they trust. API keys are then not
14
+ # accepted, and MEALIE_API_TOKEN must be unset. Accepts "true" or "1".
15
+ # MEALIE_MCP_PASSWORD_LOGIN=true
16
+ # Encrypts stored Mealie tokens. Required, at least 32 characters, and must stay the same:
17
+ # changing it makes the server refuse to start until the database is reset.
18
+ # Generate with: openssl rand -base64 48
19
+ # MCP_TOKEN_KEY=
20
+ # Public origin of this server, with no path. Required off loopback, and must be https.
21
+ # MCP_BASE_URL=https://mcp.example.com
22
+ # Where logins are stored. /data in the Docker image, which docker-compose.yml puts on a
23
+ # named volume. Without a persistent volume, logins are lost when the container is replaced.
24
+ # MCP_DATA_DIR=./data
25
+ # Number of reverse proxies in front of this server, so rate limits see real client IPs.
26
+ # MCP_TRUST_PROXY_HOPS=1
27
+ # Extra redirect_uri prefixes to accept, comma-separated. Loopback addresses and Claude's
28
+ # hosted callbacks are always allowed.
29
+ # MCP_ALLOWED_REDIRECT_PREFIXES=https://my-other-client.example.com
30
+
31
+ # --- Optional tool filtering (fallbacks for --preset / --groups / --read-only) ---
32
+ # Presets: minimal, default, full. MCP_PRESET and MCP_GROUPS are mutually exclusive.
33
+ # MCP_PRESET=default
34
+ # Groups: recipes, recipe-assets, ingredients, organizers, shopping, mealplans
35
+ # MCP_GROUPS=recipes,shopping
36
+ # MCP_READ_ONLY=true
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+
12
+ - Tools for recipes, recipe images and assets, ingredients, foods and units, organizers, shopping lists and meal plans.
13
+ - stdio and streamable HTTP transports, and a Docker image.
14
+ - HTTP auth modes: per-caller API key (default), server-wide API key, and an opt-in login form.
15
+ - Encrypted SQLite token store so logins survive restarts and image updates.
16
+
17
+ [Unreleased]: https://github.com/daften/mealie-mcp/commits/develop
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dieter Blomme
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # MCP server for Mealie
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@daften/mealie-mcp.svg)](https://www.npmjs.com/package/@daften/mealie-mcp)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@daften/mealie-mcp.svg)](https://www.npmjs.com/package/@daften/mealie-mcp)
5
+ [![CI](https://github.com/daften/mealie-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/daften/mealie-mcp/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![Documentation](https://img.shields.io/badge/docs-daften.github.io-blue)](https://daften.github.io/mealie-mcp/)
8
+
9
+ Connects AI assistants to [Mealie](https://mealie.io) through the [Model Context Protocol](https://modelcontextprotocol.io): search and write recipes, manage shopping lists, and plan meals.
10
+
11
+ One Docker container can serve a whole household or team, with each person acting as their own Mealie user.
12
+
13
+ ## Quick start: stdio
14
+
15
+ Create an API token in Mealie under **Profile → API Tokens**, then add this to your MCP client:
16
+
17
+ ```json
18
+ {
19
+ "mcpServers": {
20
+ "mealie": {
21
+ "command": "npx",
22
+ "args": ["-y", "@daften/mealie-mcp"],
23
+ "env": {
24
+ "MEALIE_URL": "https://your-mealie.example.com",
25
+ "MEALIE_API_TOKEN": "your-token"
26
+ }
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ ## Quick start: Docker
33
+
34
+ ```bash
35
+ MEALIE_URL=https://your-mealie.example.com docker compose up -d
36
+ ```
37
+
38
+ Each client then sends its own Mealie API token as a Bearer token:
39
+
40
+ ```bash
41
+ claude mcp add --transport http mealie http://localhost:3000 --header "Authorization: Bearer your-token"
42
+ ```
43
+
44
+ ## Auth modes
45
+
46
+ Pick one. Over HTTP, the modes are exclusive.
47
+
48
+ | Mode | Set | Who it's for |
49
+ |---|---|---|
50
+ | Your own API key per client | nothing (default) | Several users, no extra setup |
51
+ | One server-wide API key | `MEALIE_API_TOKEN` | One person on a trusted network. Anyone who can reach the port acts as that user |
52
+ | Login form | `MEALIE_MCP_PASSWORD_LOGIN=true` | Several users who'd rather log in than copy tokens. They type their Mealie password on a page served by this server |
53
+
54
+ See the [login form guide](docs/guide/login-form.md) before enabling it.
55
+
56
+ ## Tools
57
+
58
+ 53 tools in six groups: `recipes`, `recipe-assets`, `ingredients`, `organizers`, `shopping`, `mealplans`. Limit them with `--preset minimal|default|full`, `--groups recipes,shopping` or `--read-only`. The [tool reference](docs/reference/tools.md) lists them all.
59
+
60
+ ## Documentation
61
+
62
+ - [stdio](docs/guide/stdio.md)
63
+ - [Docker and API keys](docs/guide/docker.md)
64
+ - [Login form](docs/guide/login-form.md)
65
+ - [Environment variables](docs/reference/env-vars.md)
66
+ - [Tool filtering](docs/reference/filtering.md)
67
+ - [Contributing](CONTRIBUTING.md)
68
+
69
+ Requires Mealie v3.29.0 or later (tested through v3.30.0) and Node.js 22.13 or newer.
70
+
71
+ ## License
72
+
73
+ MIT
package/dist/args.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { type ToolFilterOptions } from './tools/index.js';
2
+ export interface ParsedArgs {
3
+ transport: 'stdio' | 'http';
4
+ host: string;
5
+ port: number;
6
+ portWasExplicit: boolean;
7
+ filterOptions: ToolFilterOptions;
8
+ }
9
+ /**
10
+ * Parse CLI arguments. Anything not recognized is an error rather than being skipped: a mistyped
11
+ * `--read-only` used to start the server with full write access and no warning.
12
+ */
13
+ export declare function parseArgs(args: string[]): ParsedArgs;
14
+ //# sourceMappingURL=args.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"args.d.ts","sourceRoot":"","sources":["../src/args.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyC,KAAK,iBAAiB,EAAkB,MAAM,kBAAkB,CAAC;AAEjH,MAAM,WAAW,UAAU;IACzB,SAAS,EAAE,OAAO,GAAG,MAAM,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,eAAe,EAAE,OAAO,CAAC;IACzB,aAAa,EAAE,iBAAiB,CAAC;CAClC;AAuCD;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,UAAU,CA+FpD"}
package/dist/args.js ADDED
@@ -0,0 +1,132 @@
1
+ import { PRESETS, TOOL_GROUPS } from './tools/index.js';
2
+ const VALUE_FLAGS = ['--transport', '--host', '--port', '--preset', '--groups'];
3
+ const BOOLEAN_FLAGS = ['--read-only'];
4
+ /** Validate a preset name. Own keys only: `toString` or `__proto__` must not pass via the prototype. */
5
+ function validatePreset(val, source = '') {
6
+ if (!Object.hasOwn(PRESETS, val)) {
7
+ throw new Error(`Unknown preset "${val}"${source}. Valid presets: ${Object.keys(PRESETS).join(', ')}`);
8
+ }
9
+ return val;
10
+ }
11
+ /**
12
+ * Parse a comma-separated group list from a CLI flag or environment variable.
13
+ * Whitespace and empty entries are ignored; an unknown group throws. Returns
14
+ * an empty array when the input contains no usable group names.
15
+ */
16
+ function parseGroups(raw, source = '') {
17
+ const parts = raw
18
+ .split(',')
19
+ .map((g) => g.trim())
20
+ .filter(Boolean);
21
+ for (const g of parts) {
22
+ if (!TOOL_GROUPS.includes(g)) {
23
+ throw new Error(`Unknown group "${g}"${source}. Valid groups: ${TOOL_GROUPS.join(', ')}`);
24
+ }
25
+ }
26
+ return parts;
27
+ }
28
+ /** Suggest the flag a typo was probably meant to be, e.g. `--readonly` → `--read-only`. */
29
+ function suggestFlag(arg) {
30
+ const normalize = (s) => s.replace(/^-+/, '').replace(/[-_]/g, '').toLowerCase();
31
+ const match = [...VALUE_FLAGS, ...BOOLEAN_FLAGS].find((flag) => normalize(flag) === normalize(arg.split('=')[0]));
32
+ return match ? ` Did you mean ${match}?` : '';
33
+ }
34
+ /**
35
+ * Parse CLI arguments. Anything not recognized is an error rather than being skipped: a mistyped
36
+ * `--read-only` used to start the server with full write access and no warning.
37
+ */
38
+ export function parseArgs(args) {
39
+ let transport = 'stdio';
40
+ let host = '127.0.0.1';
41
+ let port = 3000;
42
+ let portWasExplicit = false;
43
+ let preset;
44
+ let groups;
45
+ let readOnly = false;
46
+ for (let i = 0; i < args.length; i++) {
47
+ const arg = args[i];
48
+ if (BOOLEAN_FLAGS.includes(arg)) {
49
+ readOnly = true;
50
+ continue;
51
+ }
52
+ // Accept both `--flag value` and `--flag=value`.
53
+ const eq = arg.indexOf('=');
54
+ const flag = (eq === -1 ? arg : arg.slice(0, eq));
55
+ if (!VALUE_FLAGS.includes(flag)) {
56
+ throw new Error(`Unknown argument "${arg}".${suggestFlag(arg)} Valid flags: ${[...VALUE_FLAGS, ...BOOLEAN_FLAGS].join(', ')}`);
57
+ }
58
+ let val;
59
+ if (eq !== -1) {
60
+ val = arg.slice(eq + 1);
61
+ }
62
+ else {
63
+ val = args[i + 1];
64
+ if (val === undefined || val.startsWith('--'))
65
+ throw new Error(`${flag} requires a value`);
66
+ i++;
67
+ }
68
+ if (val === '')
69
+ throw new Error(`${flag} requires a value`);
70
+ switch (flag) {
71
+ case '--transport':
72
+ if (val !== 'stdio' && val !== 'http') {
73
+ throw new Error(`--transport must be "stdio" or "http", got "${val}"`);
74
+ }
75
+ transport = val;
76
+ break;
77
+ case '--host':
78
+ host = val;
79
+ break;
80
+ case '--port': {
81
+ const parsed = /^\d+$/.test(val) ? Number(val) : Number.NaN;
82
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
83
+ throw new Error(`--port must be a whole number between 1 and 65535, got "${val}"`);
84
+ }
85
+ port = parsed;
86
+ portWasExplicit = true;
87
+ break;
88
+ }
89
+ case '--preset':
90
+ preset = validatePreset(val);
91
+ break;
92
+ case '--groups':
93
+ groups = parseGroups(val);
94
+ if (groups.length === 0)
95
+ throw new Error('--groups needs at least one group name');
96
+ break;
97
+ }
98
+ }
99
+ // Environment-variable fallbacks. CLI flags always take precedence: each is
100
+ // consulted only when the corresponding flag was omitted.
101
+ if (preset === undefined && process.env.MCP_PRESET?.trim()) {
102
+ preset = validatePreset(process.env.MCP_PRESET.trim(), ' from MCP_PRESET');
103
+ }
104
+ if (groups === undefined && process.env.MCP_GROUPS) {
105
+ const parsed = parseGroups(process.env.MCP_GROUPS, ' from MCP_GROUPS');
106
+ // An empty/whitespace-only value (e.g. "," or " ") is treated as unset
107
+ // rather than "select no groups", which would silently register no tools.
108
+ if (parsed.length > 0)
109
+ groups = parsed;
110
+ }
111
+ if (!readOnly) {
112
+ // Unrecognized values are an error, not "off": MCP_READ_ONLY=yes must not quietly mean read-write.
113
+ const flag = process.env.MCP_READ_ONLY?.trim().toLowerCase() ?? '';
114
+ if (flag === 'true' || flag === '1')
115
+ readOnly = true;
116
+ else if (flag !== '' && flag !== 'false' && flag !== '0') {
117
+ throw new Error(`MCP_READ_ONLY must be "true", "1", "false" or "0", got "${process.env.MCP_READ_ONLY}"`);
118
+ }
119
+ }
120
+ if (preset !== undefined && groups !== undefined) {
121
+ throw new Error('Cannot use both --preset and --groups. Choose one.');
122
+ }
123
+ const filterOptions = {};
124
+ if (preset !== undefined)
125
+ filterOptions.preset = preset;
126
+ if (groups !== undefined)
127
+ filterOptions.groups = groups;
128
+ if (readOnly)
129
+ filterOptions.readOnly = true;
130
+ return { transport, host, port, portWasExplicit, filterOptions };
131
+ }
132
+ //# sourceMappingURL=args.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"args.js","sourceRoot":"","sources":["../src/args.ts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KAAK,MAAM,IAAI,IAAI,KAAK,GAAG;YAAE,QAAQ,GAAG,IAAI,CAAC;aAChD,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,GAAG,EAAE,CAAC;YACzD,MAAM,IAAI,KAAK,CAAC,2DAA2D,OAAO,CAAC,GAAG,CAAC,aAAa,GAAG,CAAC,CAAC;QAC3G,CAAC;IACH,CAAC;IAED,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACjD,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,aAAa,GAAsB,EAAE,CAAC;IAC5C,IAAI,MAAM,KAAK,SAAS;QAAE,aAAa,CAAC,MAAM,GAAG,MAAM,CAAC;IACxD,IAAI,MAAM,KAAK,SAAS;QAAE,aAAa,CAAC,MAAM,GAAG,MAAM,CAAC;IACxD,IAAI,QAAQ;QAAE,aAAa,CAAC,QAAQ,GAAG,IAAI,CAAC;IAE5C,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;AACnE,CAAC"}
@@ -0,0 +1,9 @@
1
+ /** Derives the AES key, so MCP_TOKEN_KEY can be any sufficiently long string. */
2
+ export declare function deriveKey(secret: string): Buffer;
3
+ /** `context` is authenticated but not stored, so a ciphertext copied to another row won't decrypt there. */
4
+ export declare function encrypt(key: Buffer, plaintext: string, context: string): string;
5
+ /** Throws when the key, context or ciphertext don't match. */
6
+ export declare function decrypt(key: Buffer, sealed: string, context: string): string;
7
+ export declare function hashToken(token: string): string;
8
+ export declare function newToken(prefix: string): string;
9
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/auth/crypto.ts"],"names":[],"mappings":"AAMA,iFAAiF;AACjF,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED,4GAA4G;AAC5G,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAM/E;AAED,8DAA8D;AAC9D,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAQ5E;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE/C;AAED,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE/C"}
@@ -0,0 +1,34 @@
1
+ import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from 'node:crypto';
2
+ const FORMAT = 'v1';
3
+ const IV_BYTES = 12;
4
+ const TAG_BYTES = 16;
5
+ /** Derives the AES key, so MCP_TOKEN_KEY can be any sufficiently long string. */
6
+ export function deriveKey(secret) {
7
+ return Buffer.from(hkdfSync('sha256', secret, Buffer.alloc(0), 'mealie-mcp token store v1', 32));
8
+ }
9
+ /** `context` is authenticated but not stored, so a ciphertext copied to another row won't decrypt there. */
10
+ export function encrypt(key, plaintext, context) {
11
+ const iv = randomBytes(IV_BYTES);
12
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
13
+ cipher.setAAD(Buffer.from(context, 'utf8'));
14
+ const body = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
15
+ return `${FORMAT}.${Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url')}`;
16
+ }
17
+ /** Throws when the key, context or ciphertext don't match. */
18
+ export function decrypt(key, sealed, context) {
19
+ const [format, payload] = sealed.split('.');
20
+ if (format !== FORMAT || !payload)
21
+ throw new Error('Unrecognized ciphertext format');
22
+ const raw = Buffer.from(payload, 'base64url');
23
+ const decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, IV_BYTES));
24
+ decipher.setAAD(Buffer.from(context, 'utf8'));
25
+ decipher.setAuthTag(raw.subarray(IV_BYTES, IV_BYTES + TAG_BYTES));
26
+ return Buffer.concat([decipher.update(raw.subarray(IV_BYTES + TAG_BYTES)), decipher.final()]).toString('utf8');
27
+ }
28
+ export function hashToken(token) {
29
+ return createHash('sha256').update(token).digest('hex');
30
+ }
31
+ export function newToken(prefix) {
32
+ return `${prefix}${randomBytes(32).toString('base64url')}`;
33
+ }
34
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../src/auth/crypto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAElG,MAAM,MAAM,GAAG,IAAI,CAAC;AACpB,MAAM,QAAQ,GAAG,EAAE,CAAC;AACpB,MAAM,SAAS,GAAG,EAAE,CAAC;AAErB,iFAAiF;AACjF,MAAM,UAAU,SAAS,CAAC,MAAc;IACtC,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,2BAA2B,EAAE,EAAE,CAAC,CAAC,CAAC;AACnG,CAAC;AAED,4GAA4G;AAC5G,MAAM,UAAU,OAAO,CAAC,GAAW,EAAE,SAAiB,EAAE,OAAe;IACrE,MAAM,EAAE,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC;IACjC,MAAM,MAAM,GAAG,cAAc,CAAC,aAAa,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;IACtD,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;IAC5C,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,KAAK,EA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CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,MAAc;IACrC,OAAO,GAAG,MAAM,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;AAC7D,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { LoginAuth } from '../http.js';
2
+ import type { LoginMethod } from './login-method.js';
3
+ import { MealieOAuthProvider } from './provider.js';
4
+ export { passwordLogin } from './password-login.js';
5
+ export interface LoginConfig {
6
+ baseUrl: string;
7
+ tokenKey: string;
8
+ dataDir: string;
9
+ trustProxyHops: number;
10
+ }
11
+ export declare function createLoginAuth(config: LoginConfig, mealieUrl: string, methods: LoginMethod[]): Promise<LoginAuth & {
12
+ close(): Promise<void>;
13
+ provider: MealieOAuthProvider;
14
+ }>;
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,EAAgB,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAGpD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,CAAC;CACxB;AAaD,wBAAsB,eAAe,CACnC,MAAM,EAAE,WAAW,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,WAAW,EAAE,GACrB,OAAO,CAAC,SAAS,GAAG;IAAE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,QAAQ,EAAE,mBAAmB,CAAA;CAAE,CAAC,CAoEhF"}
@@ -0,0 +1,77 @@
1
+ import { mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js';
2
+ import express from 'express';
3
+ import { MealieSessionApi } from './mealie-session.js';
4
+ import { MealieOAuthProvider } from './provider.js';
5
+ import { TokenStore } from './store.js';
6
+ export { passwordLogin } from './password-login.js';
7
+ const PURGE_INTERVAL_MS = 60 * 60 * 1000;
8
+ const OAUTH_PATHS = [
9
+ '/.well-known/oauth-authorization-server',
10
+ '/.well-known/oauth-protected-resource',
11
+ '/authorize',
12
+ '/token',
13
+ '/register',
14
+ '/revoke',
15
+ ];
16
+ export async function createLoginAuth(config, mealieUrl, methods) {
17
+ const store = await TokenStore.open(config.dataDir, config.tokenKey);
18
+ const provider = new MealieOAuthProvider(store, new MealieSessionApi(mealieUrl), methods, config.baseUrl);
19
+ const app = express();
20
+ app.disable('x-powered-by');
21
+ app.set('trust proxy', config.trustProxyHops);
22
+ // express-rate-limit logs a validation error when it sees X-Forwarded-For and trust proxy is off.
23
+ // The per-route limits still apply; the check would only add noise behind a reverse proxy.
24
+ const rateLimit = { validate: false };
25
+ const baseUrl = new URL(config.baseUrl);
26
+ // Ahead of the SDK's route, which would publish `https://host/`. Clients compare `resource` with the
27
+ // URL the user typed, and Claude's connector flow requires an exact match, so it has no trailing slash.
28
+ app.get('/.well-known/oauth-protected-resource', (_req, res) => {
29
+ res.set('Access-Control-Allow-Origin', '*').json({
30
+ resource: config.baseUrl,
31
+ authorization_servers: [baseUrl.href],
32
+ bearer_methods_supported: ['header'],
33
+ resource_name: 'Mealie MCP',
34
+ });
35
+ });
36
+ app.use(mcpAuthRouter({
37
+ provider,
38
+ issuerUrl: baseUrl,
39
+ resourceServerUrl: baseUrl,
40
+ resourceName: 'Mealie MCP',
41
+ authorizationOptions: { rateLimit },
42
+ tokenOptions: { rateLimit },
43
+ revocationOptions: { rateLimit },
44
+ // The default 30-day secret expiry would force confidential clients to log in again.
45
+ clientRegistrationOptions: { rateLimit, clientIdGeneration: false, clientSecretExpirySeconds: 0 },
46
+ }));
47
+ const context = {
48
+ baseUrl: config.baseUrl,
49
+ mealieUrl,
50
+ takeFlow: (id) => provider.takeFlow(id),
51
+ renewFlow: (flow) => provider.renewFlow(flow),
52
+ completeLogin: (flow, jwt, res) => provider.completeLogin(flow, jwt, res),
53
+ clientIp: (req) => req.ip ?? 'unknown',
54
+ };
55
+ for (const method of methods)
56
+ method.register(app, context);
57
+ const authPaths = new Set([...OAUTH_PATHS, ...methods.flatMap((m) => m.paths)]);
58
+ const purge = () => {
59
+ provider.purge().catch((err) => process.stderr.write(`Token cleanup failed: ${err}\n`));
60
+ };
61
+ purge();
62
+ const timer = setInterval(purge, PURGE_INTERVAL_MS).unref();
63
+ return {
64
+ baseUrl: config.baseUrl,
65
+ provider,
66
+ isAuthPath: (pathname) => authPaths.has(pathname),
67
+ handle: (req, res) => {
68
+ app(req, res);
69
+ },
70
+ resolveBearer: (bearer) => store.resolveAccessToken(bearer)?.grant.mealieToken ?? null,
71
+ close: async () => {
72
+ clearInterval(timer);
73
+ store.close();
74
+ },
75
+ };
76
+ }
77
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,iDAAiD,CAAC;AAChF,OAAO,OAAO,MAAM,SAAS,CAAC;AAG9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AASpD,MAAM,iBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEzC,MAAM,WAAW,GAAG;IAClB,yCAAyC;IACzC,uCAAuC;IACvC,YAAY;IACZ,QAAQ;IACR,WAAW;IACX,SAAS;CACV,CAAC;AAEF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5D,OAAO;QACL,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,QAAQ;QACR,UAAU,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC;QACjD,MAAM,EAAE,CAAC,GAAyB,EAAE,GAAwB,EAAE,EAAE;YAC9D,GAAG,CAAC,GAAsB,EAAE,GAAuB,CAAC,CAAC;QACvD,CAAC;QACD,aAAa,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,WAAW,IAAI,IAAI;QACtF,KAAK,EAAE,KAAK,IAAI,EAAE;YAChB,aAAa,CAAC,KAAK,CAAC,CAAC;YACrB,KAAK,CAAC,KAAK,EAAE,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,28 @@
1
+ import type { AuthorizationParams } from '@modelcontextprotocol/sdk/server/auth/provider.js';
2
+ import type { OAuthClientInformationFull } from '@modelcontextprotocol/sdk/shared/auth.js';
3
+ import type { Express, Request, Response } from 'express';
4
+ export interface PendingFlow {
5
+ id: string;
6
+ client: OAuthClientInformationFull;
7
+ params: AuthorizationParams;
8
+ createdAt: number;
9
+ }
10
+ export interface LoginContext {
11
+ baseUrl: string;
12
+ mealieUrl: string;
13
+ /** Single use: removes the flow. A method that lets the user retry re-registers it with {@link renewFlow}. */
14
+ takeFlow(id: string): PendingFlow | undefined;
15
+ renewFlow(flow: PendingFlow): PendingFlow;
16
+ /** Every method ends here: turns a Mealie session into a stored grant and redirects back to the client. */
17
+ completeLogin(flow: PendingFlow, sessionJwt: string, res: Response): Promise<void>;
18
+ clientIp(req: Request): string;
19
+ }
20
+ /** One way of proving who the user is. Password login today; OIDC plugs in here later. */
21
+ export interface LoginMethod {
22
+ id: 'password' | 'oidc';
23
+ /** Paths this method serves, beyond the standard OAuth endpoints. */
24
+ paths: string[];
25
+ register(app: Express, context: LoginContext): void;
26
+ begin(flow: PendingFlow, res: Response): void;
27
+ }
28
+ //# sourceMappingURL=login-method.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"login-method.d.ts","sourceRoot":"","sources":["../../src/auth/login-method.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mDAAmD,CAAC;AAC7F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AAC3F,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAE1D,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,0BAA0B,CAAC;IACnC,MAAM,EAAE,mBAAmB,CAAC;IAC5B,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,8GAA8G;IAC9G,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAAC;IAC9C,SAAS,CAAC,IAAI,EAAE,WAAW,GAAG,WAAW,CAAC;IAC1C,2GAA2G;IAC3G,aAAa,CAAC,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnF,QAAQ,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC;CAChC;AAED,0FAA0F;AAC1F,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,UAAU,GAAG,MAAM,CAAC;IACxB,qEAAqE;IACrE,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,QAAQ,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;IACpD,KAAK,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,IAAI,CAAC;CAC/C"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=login-method.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"login-method.js","sourceRoot":"","sources":["../../src/auth/login-method.ts"],"names":[],"mappings":""}
@@ -0,0 +1,28 @@
1
+ export type LoginResult = {
2
+ status: 'ok';
3
+ sessionJwt: string;
4
+ } | {
5
+ status: 'invalid';
6
+ } | {
7
+ status: 'locked';
8
+ };
9
+ /** Mealie answered in a way that says nothing about the credentials. Never treated as a failed login. */
10
+ export declare class MealieUnavailableError extends Error {
11
+ }
12
+ /** The handful of Mealie auth calls the login stack makes, separate from the tool-facing MealieClient. */
13
+ export declare class MealieSessionApi {
14
+ private readonly baseUrl;
15
+ constructor(baseUrl: string);
16
+ private call;
17
+ login(username: string, password: string): Promise<LoginResult>;
18
+ /** A random suffix keeps names distinct, so repeat logins on one day stay separate rows in the profile page. */
19
+ mintToken(sessionJwt: string): Promise<{
20
+ token: string;
21
+ id: number;
22
+ }>;
23
+ /** False only when Mealie says the token is dead. An outage throws, so it can't log anyone out. */
24
+ isTokenValid(token: string): Promise<boolean>;
25
+ /** True when the token no longer exists afterwards, including when it was already gone. */
26
+ deleteToken(token: string, id: number): Promise<boolean>;
27
+ }
28
+ //# sourceMappingURL=mealie-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mealie-session.d.ts","sourceRoot":"","sources":["../../src/auth/mealie-session.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,WAAW,GAAG;IAAE,MAAM,EAAE,IAAI,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GAAG;IAAE,MAAM,EAAE,QAAQ,CAAA;CAAE,CAAC;AAE9G,yGAAyG;AACzG,qBAAa,sBAAuB,SAAQ,KAAK;CAAG;AAEpD,0GAA0G;AAC1G,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IAEjC,YAAY,OAAO,EAAE,MAAM,EAE1B;YAEa,IAAI;IAaZ,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAYpE;IAED,gHAAgH;IAC1G,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,CAe1E;IAED,mGAAmG;IAC7F,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAOlD;IAED,2FAA2F;IACrF,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAM7D;CACF"}
@@ -0,0 +1,81 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ const TIMEOUT_MS = 30_000;
3
+ /** Mealie answered in a way that says nothing about the credentials. Never treated as a failed login. */
4
+ export class MealieUnavailableError extends Error {
5
+ }
6
+ /** The handful of Mealie auth calls the login stack makes, separate from the tool-facing MealieClient. */
7
+ export class MealieSessionApi {
8
+ baseUrl;
9
+ constructor(baseUrl) {
10
+ this.baseUrl = baseUrl.replace(/\/$/, '');
11
+ }
12
+ async call(path, init) {
13
+ try {
14
+ return await fetch(`${this.baseUrl}/api${path}`, {
15
+ ...init,
16
+ redirect: 'manual',
17
+ signal: AbortSignal.timeout(TIMEOUT_MS),
18
+ });
19
+ }
20
+ catch (err) {
21
+ // Deliberately omits the cause detail: the request body of /auth/token holds a password.
22
+ throw new MealieUnavailableError(`Could not reach Mealie: ${err.name}`);
23
+ }
24
+ }
25
+ async login(username, password) {
26
+ const response = await this.call('/auth/token', {
27
+ method: 'POST',
28
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
29
+ body: new URLSearchParams({ username, password }).toString(),
30
+ });
31
+ if (response.status === 401)
32
+ return { status: 'invalid' };
33
+ if (response.status === 423)
34
+ return { status: 'locked' };
35
+ if (!response.ok)
36
+ throw new MealieUnavailableError(`Mealie answered ${response.status} to the login request`);
37
+ const body = (await response.json());
38
+ if (!body.access_token)
39
+ throw new MealieUnavailableError('Mealie returned no access token');
40
+ return { status: 'ok', sessionJwt: body.access_token };
41
+ }
42
+ /** A random suffix keeps names distinct, so repeat logins on one day stay separate rows in the profile page. */
43
+ async mintToken(sessionJwt) {
44
+ const name = `mealie-mcp ${new Date().toISOString().slice(0, 10)} ${randomBytes(3).toString('hex')}`;
45
+ const response = await this.call('/users/api-tokens', {
46
+ method: 'POST',
47
+ headers: {
48
+ Authorization: `Bearer ${sessionJwt}`,
49
+ 'Content-Type': 'application/json',
50
+ Accept: 'application/json',
51
+ },
52
+ body: JSON.stringify({ name }),
53
+ });
54
+ if (!response.ok)
55
+ throw new MealieUnavailableError(`Mealie answered ${response.status} when creating a token`);
56
+ const body = (await response.json());
57
+ if (!body.token || typeof body.id !== 'number')
58
+ throw new MealieUnavailableError('Mealie returned no API token');
59
+ return { token: body.token, id: body.id };
60
+ }
61
+ /** False only when Mealie says the token is dead. An outage throws, so it can't log anyone out. */
62
+ async isTokenValid(token) {
63
+ const response = await this.call('/users/self', {
64
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
65
+ });
66
+ if (response.status === 401)
67
+ return false;
68
+ if (!response.ok)
69
+ throw new MealieUnavailableError(`Mealie answered ${response.status} when checking a token`);
70
+ return true;
71
+ }
72
+ /** True when the token no longer exists afterwards, including when it was already gone. */
73
+ async deleteToken(token, id) {
74
+ const response = await this.call(`/users/api-tokens/${id}`, {
75
+ method: 'DELETE',
76
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
77
+ });
78
+ return response.ok || response.status === 401 || response.status === 404;
79
+ }
80
+ }
81
+ //# sourceMappingURL=mealie-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mealie-session.js","sourceRoot":"","sources":["../../src/auth/mealie-session.ts"],"names":[],"m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