@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
@@ -0,0 +1,21 @@
1
+ import type { LoginMethod } from './login-method.js';
2
+ export declare const LOGIN_PATH = "/oauth/login";
3
+ export declare const MAX_FAILURES_PER_USERNAME = 4;
4
+ export declare const MAX_FAILURES_PER_IP = 20;
5
+ /** Counts failed attempts per key in a sliding-from-first-failure window. Bounded, because the keys are attacker-chosen. */
6
+ export declare class FailureLimiter {
7
+ private readonly max;
8
+ private readonly windowMs;
9
+ private readonly now;
10
+ private readonly failures;
11
+ constructor(max: number, windowMs?: number, now?: () => number);
12
+ private live;
13
+ isBlocked(key: string): boolean;
14
+ recordFailure(key: string): void;
15
+ clear(key: string): void;
16
+ }
17
+ export declare function escapeHtml(value: string): string;
18
+ /** Chrome applies form-action to the redirect after submit, so the client's callback origin must be listed. */
19
+ export declare function formActionSource(redirectUri: string): string;
20
+ export declare function passwordLogin(): LoginMethod;
21
+ //# sourceMappingURL=password-login.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"password-login.d.ts","sourceRoot":"","sources":["../../src/auth/password-login.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAgB,WAAW,EAAe,MAAM,mBAAmB,CAAC;AAGhF,eAAO,MAAM,UAAU,iBAAiB,CAAC;AAGzC,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAC3C,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAGtC,4HAA4H;AAC5H,qBAAa,cAAc;IAIvB,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,GAAG;IALtB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA2D;IAEpF,YACmB,GAAG,EAAE,MAAM,EACX,QAAQ,GAAE,MAAkB,EAC5B,GAAG,GAAE,MAAM,MAAiB,EAC3C;IAEJ,OAAO,CAAC,IAAI;IASZ,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAE9B;IAED,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAW/B;IAED,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEvB;CACF;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED,+GAA+G;AAC/G,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAG5D;AAgED,wBAAgB,aAAa,IAAI,WAAW,CAuD3C"}
@@ -0,0 +1,168 @@
1
+ import express from 'express';
2
+ import { MealieSessionApi, MealieUnavailableError } from './mealie-session.js';
3
+ export const LOGIN_PATH = '/oauth/login';
4
+ const WINDOW_MS = 15 * 60 * 1000;
5
+ // Below Mealie's default of 5 failed attempts, so this form can't be used to lock an account out.
6
+ export const MAX_FAILURES_PER_USERNAME = 4;
7
+ export const MAX_FAILURES_PER_IP = 20;
8
+ const MAX_TRACKED_KEYS = 10_000;
9
+ /** Counts failed attempts per key in a sliding-from-first-failure window. Bounded, because the keys are attacker-chosen. */
10
+ export class FailureLimiter {
11
+ max;
12
+ windowMs;
13
+ now;
14
+ failures = new Map();
15
+ constructor(max, windowMs = WINDOW_MS, now = Date.now) {
16
+ this.max = max;
17
+ this.windowMs = windowMs;
18
+ this.now = now;
19
+ }
20
+ live(key) {
21
+ const entry = this.failures.get(key);
22
+ if (entry && this.now() - entry.startedAt > this.windowMs) {
23
+ this.failures.delete(key);
24
+ return undefined;
25
+ }
26
+ return entry;
27
+ }
28
+ isBlocked(key) {
29
+ return (this.live(key)?.count ?? 0) >= this.max;
30
+ }
31
+ recordFailure(key) {
32
+ const entry = this.live(key);
33
+ if (entry) {
34
+ entry.count++;
35
+ return;
36
+ }
37
+ if (this.failures.size >= MAX_TRACKED_KEYS) {
38
+ const oldest = this.failures.keys().next().value;
39
+ if (oldest !== undefined)
40
+ this.failures.delete(oldest);
41
+ }
42
+ this.failures.set(key, { count: 1, startedAt: this.now() });
43
+ }
44
+ clear(key) {
45
+ this.failures.delete(key);
46
+ }
47
+ }
48
+ export function escapeHtml(value) {
49
+ return value.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
50
+ }
51
+ /** Chrome applies form-action to the redirect after submit, so the client's callback origin must be listed. */
52
+ export function formActionSource(redirectUri) {
53
+ const parsed = new URL(redirectUri);
54
+ return parsed.origin === 'null' ? parsed.protocol : parsed.origin;
55
+ }
56
+ function renderPage(flow, baseUrl, message) {
57
+ const serverHost = new URL(baseUrl).host;
58
+ const redirect = new URL(flow.params.redirectUri);
59
+ const clientHost = redirect.host || redirect.protocol;
60
+ const clientName = flow.client.client_name ?? 'An MCP client';
61
+ return `<!doctype html>
62
+ <html lang="en">
63
+ <head>
64
+ <meta charset="utf-8">
65
+ <meta name="viewport" content="width=device-width, initial-scale=1">
66
+ <title>Log in to Mealie MCP</title>
67
+ <style>
68
+ :root { color-scheme: light dark; }
69
+ body { font: 16px/1.5 system-ui, sans-serif; max-width: 26rem; margin: 2rem auto; padding: 0 1rem; }
70
+ h1 { font-size: 1.4rem; margin-bottom: .25rem; }
71
+ .warning { border-left: 4px solid #d97706; padding: .5rem .75rem; margin: 1rem 0; background: rgba(217,119,6,.12); }
72
+ .error { border-left: 4px solid #dc2626; padding: .5rem .75rem; margin: 1rem 0; background: rgba(220,38,38,.12); }
73
+ label { display: block; margin-top: .75rem; font-weight: 600; }
74
+ input { box-sizing: border-box; width: 100%; padding: .5rem; font: inherit; margin-top: .25rem; }
75
+ button { margin-top: 1rem; padding: .6rem 1rem; font: inherit; width: 100%; cursor: pointer; }
76
+ .detail { font-size: .9rem; opacity: .85; }
77
+ </style>
78
+ </head>
79
+ <body>
80
+ <h1>Log in with your Mealie account</h1>
81
+ <p class="detail"><strong>${escapeHtml(clientName)}</strong> at <code>${escapeHtml(clientHost)}</code> is asking to use Mealie as you.</p>
82
+ <div class="warning"><strong>This page is not Mealie.</strong> Your password goes to the MCP server at <code>${escapeHtml(serverHost)}</code>, which passes it on to Mealie once and does not store it. Only continue if you trust this server. If you aren't sure, stop and ask whoever runs it.</div>
83
+ ${message ? `<div class="error" role="alert">${escapeHtml(message)}</div>` : ''}
84
+ <form method="post" action="${LOGIN_PATH}" autocomplete="on">
85
+ <input type="hidden" name="flow" value="${escapeHtml(flow.id)}">
86
+ <label for="username">Email or username</label>
87
+ <input id="username" name="username" autocomplete="username" required autofocus>
88
+ <label for="password">Password</label>
89
+ <input id="password" name="password" type="password" autocomplete="current-password" required>
90
+ <button type="submit">Log in</button>
91
+ </form>
92
+ </body>
93
+ </html>`;
94
+ }
95
+ function sendPage(res, status, flow, baseUrl, message) {
96
+ res
97
+ .status(status)
98
+ .set({
99
+ 'Content-Type': 'text/html; charset=utf-8',
100
+ 'Content-Security-Policy': `default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'self' ${formActionSource(flow.params.redirectUri)}; frame-ancestors 'none'`,
101
+ 'X-Frame-Options': 'DENY',
102
+ 'X-Content-Type-Options': 'nosniff',
103
+ 'Cache-Control': 'no-store',
104
+ 'Referrer-Policy': 'no-referrer',
105
+ })
106
+ .send(renderPage(flow, baseUrl, message));
107
+ }
108
+ const MESSAGES = {
109
+ invalid: "Mealie didn't accept that email and password. Accounts that sign in through SSO or an external provider can't use this form.",
110
+ locked: 'Mealie has locked this account after too many failed attempts. An administrator can unlock it.',
111
+ throttled: 'Too many failed attempts. Wait 15 minutes and try again.',
112
+ unavailable: "The server couldn't reach Mealie. Try again in a moment.",
113
+ };
114
+ export function passwordLogin() {
115
+ let baseUrl = '';
116
+ return {
117
+ id: 'password',
118
+ paths: [LOGIN_PATH],
119
+ begin(flow, res) {
120
+ sendPage(res, 200, flow, baseUrl);
121
+ },
122
+ register(app, context) {
123
+ baseUrl = context.baseUrl;
124
+ const api = new MealieSessionApi(context.mealieUrl);
125
+ const byUsername = new FailureLimiter(MAX_FAILURES_PER_USERNAME);
126
+ const byIp = new FailureLimiter(MAX_FAILURES_PER_IP);
127
+ app.post(LOGIN_PATH, express.urlencoded({ extended: false, limit: '64kb' }), async (req, res) => {
128
+ const { flow: flowId, username, password } = (req.body ?? {});
129
+ const taken = typeof flowId === 'string' ? context.takeFlow(flowId) : undefined;
130
+ if (!taken) {
131
+ res
132
+ .status(400)
133
+ .set({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' })
134
+ .send('This login page has expired. Start again from your MCP client.');
135
+ return;
136
+ }
137
+ if (typeof username !== 'string' || typeof password !== 'string' || !username || !password) {
138
+ sendPage(res, 400, context.renewFlow(taken), baseUrl, MESSAGES.invalid);
139
+ return;
140
+ }
141
+ const ip = context.clientIp(req);
142
+ const userKey = username.trim().toLowerCase();
143
+ if (byUsername.isBlocked(userKey) || byIp.isBlocked(ip)) {
144
+ sendPage(res, 429, context.renewFlow(taken), baseUrl, MESSAGES.throttled);
145
+ return;
146
+ }
147
+ try {
148
+ const result = await api.login(username.trim(), password);
149
+ if (result.status === 'ok') {
150
+ byUsername.clear(userKey);
151
+ await context.completeLogin(taken, result.sessionJwt, res);
152
+ return;
153
+ }
154
+ byUsername.recordFailure(userKey);
155
+ byIp.recordFailure(ip);
156
+ sendPage(res, 401, context.renewFlow(taken), baseUrl, MESSAGES[result.status]);
157
+ }
158
+ catch (err) {
159
+ if (!(err instanceof MealieUnavailableError))
160
+ throw err;
161
+ process.stderr.write(`Login failed: ${err.message}\n`);
162
+ sendPage(res, 502, context.renewFlow(taken), baseUrl, MESSAGES.unavailable);
163
+ }
164
+ });
165
+ },
166
+ };
167
+ }
168
+ //# sourceMappingURL=password-login.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"password-login.js","sourceRoot":"","sources":["../../src/auth/password-login.ts"],"names":[],"mappings":"AAAA,OAAO,OAA0B,MAAM,SAAS,CAAC;AAEjD,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE/E,MAAM,CAAC,MAAM,UAAU,GAAG,cAAc,CAAC;AACzC,MAAM,SAAS,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACjC,kGAAkG;AAClG,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AAC3C,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AACtC,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,4HAA4H;AAC5H,MAAM,OAAO,cAAc;IAIN,GAAG;IACH,QAAQ;IACR,GAAG;IALL,QAAQ,GAAG,IAAI,GAAG,EAAgD,CAAC;IAEpF,YACmB,GAAW,EACX,QAAQ,GAAW,SAAS,EAC5B,GAAG,GAAiB,IAAI,CAAC,GAAG;mBAF5B,GAAG;wBACH,QAAQ;mBACR,GAAG;IACnB,CAAC;IAEI,IAAI,CAAC,GAAW;QACtB,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACrC,IAAI,KAAK,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC1D,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC1B,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,SAAS,CAAC,GAAW;QACnB,OAAO,CAAC,IAAI,CAAC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E,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;gBACjF,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,CAAC,GAAG,YAAY,sBAAsB,CAAC;wBAAE,MAAM,GAAG,CAAC;oBACxD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,GAAG,CAAC,OAAO,IAAI,CAAC,CAAC;oBACvD,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,WAAW,CAAC,CAAC;gBAC9E,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,41 @@
1
+ import type { OAuthRegisteredClientsStore } from '@modelcontextprotocol/sdk/server/auth/clients.js';
2
+ import type { AuthorizationParams, OAuthServerProvider } from '@modelcontextprotocol/sdk/server/auth/provider.js';
3
+ import type { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
4
+ import type { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
5
+ import type { Response } from 'express';
6
+ import type { LoginMethod, PendingFlow } from './login-method.js';
7
+ import { type MealieSessionApi } from './mealie-session.js';
8
+ import { type TokenStore } from './store.js';
9
+ export declare const MAX_PENDING_FLOWS = 1000;
10
+ /** A retried refresh whose response got lost still works for this long; later reuse looks like theft. */
11
+ export declare const REFRESH_REUSE_GRACE_MS: number;
12
+ export declare class MealieOAuthProvider implements OAuthServerProvider {
13
+ private readonly store;
14
+ private readonly mealie;
15
+ private readonly loginMethods;
16
+ private readonly baseUrl;
17
+ private readonly now;
18
+ private readonly flows;
19
+ private readonly codes;
20
+ readonly clientsStore: OAuthRegisteredClientsStore;
21
+ constructor(store: TokenStore, mealie: MealieSessionApi, loginMethods: LoginMethod[], baseUrl: string, now?: () => number);
22
+ private addFlow;
23
+ private evict;
24
+ takeFlow(id: string): PendingFlow | undefined;
25
+ renewFlow(flow: PendingFlow): PendingFlow;
26
+ authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise<void>;
27
+ /** Accepts this server's origin and paths under it, since the MCP endpoint answers on any path. */
28
+ private isOwnResource;
29
+ completeLogin(flow: PendingFlow, sessionJwt: string, res: Response): Promise<void>;
30
+ private liveCode;
31
+ challengeForAuthorizationCode(client: OAuthClientInformationFull, code: string): Promise<string>;
32
+ exchangeAuthorizationCode(client: OAuthClientInformationFull, code: string, _codeVerifier?: string, redirectUri?: string, resource?: URL): Promise<OAuthTokens>;
33
+ exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, _scopes?: string[], resource?: URL): Promise<OAuthTokens>;
34
+ verifyAccessToken(token: string): Promise<AuthInfo>;
35
+ revokeToken(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise<void>;
36
+ /** Removes the local grant whatever Mealie says; the leftover token row is visible in the user's profile. */
37
+ private endGrant;
38
+ /** Drops expired tokens and abandoned grants. A grant is kept for the next run if Mealie can't be reached. */
39
+ purge(): Promise<void>;
40
+ }
41
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/auth/provider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,kDAAkD,CAAC;AAOpG,OAAO,KAAK,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,mDAAmD,CAAC;AAClH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gDAAgD,CAAC;AAC/E,OAAO,KAAK,EACV,0BAA0B,EAC1B,2BAA2B,EAC3B,WAAW,EACZ,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC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,EAAE,0BAA0B,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAErG;IAEK,yBAAyB,CAC7B,MAAM,EAAE,0BAA0B,EAClC,IAAI,EAAE,MAAM,EACZ,aAAa,CAAC,EAAE,MAAM,EACtB,WAAW,CAAC,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,GAAG,GACb,OAAO,CAAC,WAAW,CAAC,CAQtB;IAEK,oBAAoB,CACxB,MAAM,EAAE,0BAA0B,EAClC,YAAY,EAAE,MAAM,EACpB,OAAO,CAAC,EAAE,MAAM,EAAE,EAClB,QAAQ,CAAC,EAAE,GAAG,GACb,OAAO,CAAC,WAAW,CAAC,CA2BtB;IAEK,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAUxD;IAEK,WAAW,CAAC,MAAM,EAAE,0BAA0B,EAAE,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAMzG;IAED,6GAA6G;YAC/F,QAAQ;IAKtB,8GAA8G;IACxG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAM3B;CACF"}
@@ -0,0 +1,201 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { InvalidClientMetadataError, InvalidGrantError, InvalidTargetError, ServerError, } from '@modelcontextprotocol/sdk/server/auth/errors.js';
3
+ import { MealieUnavailableError } from './mealie-session.js';
4
+ import { isRedirectUriAllowed } from './redirects.js';
5
+ import { REFRESH_TOKEN_PREFIX } from './store.js';
6
+ const FLOW_TTL_MS = 10 * 60 * 1000;
7
+ const CODE_TTL_MS = 60 * 1000;
8
+ export const MAX_PENDING_FLOWS = 1000;
9
+ /** A retried refresh whose response got lost still works for this long; later reuse looks like theft. */
10
+ export const REFRESH_REUSE_GRACE_MS = 60 * 1000;
11
+ /** A grant with no tokens yet may belong to a login still between code issue and exchange. */
12
+ const ABANDONED_GRANT_MIN_AGE_MS = 5 * 60 * 1000;
13
+ function toOAuthTokens(pair) {
14
+ return {
15
+ access_token: pair.accessToken,
16
+ token_type: 'bearer',
17
+ expires_in: pair.expiresInSeconds,
18
+ refresh_token: pair.refreshToken,
19
+ };
20
+ }
21
+ export class MealieOAuthProvider {
22
+ store;
23
+ mealie;
24
+ loginMethods;
25
+ baseUrl;
26
+ now;
27
+ flows = new Map();
28
+ codes = new Map();
29
+ clientsStore;
30
+ constructor(store, mealie, loginMethods, baseUrl, now = () => Date.now()) {
31
+ this.store = store;
32
+ this.mealie = mealie;
33
+ this.loginMethods = loginMethods;
34
+ this.baseUrl = baseUrl;
35
+ this.now = now;
36
+ this.clientsStore = {
37
+ getClient: (clientId) => store.getClient(clientId),
38
+ registerClient: (client) => {
39
+ if (client.redirect_uris.some((uri) => !isRedirectUriAllowed(String(uri)))) {
40
+ throw new InvalidClientMetadataError("redirect_uri is not allowed. Loopback addresses and Claude's hosted callback are allowed by default; add any other prefix to MCP_ALLOWED_REDIRECT_PREFIXES.");
41
+ }
42
+ const full = {
43
+ ...client,
44
+ client_id: randomUUID(),
45
+ client_id_issued_at: Math.floor(this.now() / 1000),
46
+ };
47
+ store.saveClient(full);
48
+ return full;
49
+ },
50
+ };
51
+ }
52
+ addFlow(flow) {
53
+ this.evict();
54
+ // The route is unauthenticated, so the map is capped: the oldest flow goes, new logins keep working.
55
+ if (this.flows.size >= MAX_PENDING_FLOWS) {
56
+ const oldest = this.flows.keys().next().value;
57
+ if (oldest !== undefined)
58
+ this.flows.delete(oldest);
59
+ }
60
+ const entry = { ...flow, id: randomBytes(32).toString('base64url'), createdAt: this.now() };
61
+ this.flows.set(entry.id, entry);
62
+ return entry;
63
+ }
64
+ evict() {
65
+ const now = this.now();
66
+ for (const [id, flow] of this.flows)
67
+ if (now - flow.createdAt > FLOW_TTL_MS)
68
+ this.flows.delete(id);
69
+ for (const [code, entry] of this.codes)
70
+ if (now - entry.createdAt > CODE_TTL_MS)
71
+ this.codes.delete(code);
72
+ }
73
+ takeFlow(id) {
74
+ this.evict();
75
+ const flow = this.flows.get(id);
76
+ this.flows.delete(id);
77
+ return flow;
78
+ }
79
+ renewFlow(flow) {
80
+ return this.addFlow({ client: flow.client, params: flow.params });
81
+ }
82
+ async authorize(client, params, res) {
83
+ if (params.resource && !this.isOwnResource(params.resource)) {
84
+ throw new InvalidTargetError('This token is not for this server.');
85
+ }
86
+ // One method today. With several, this becomes a chooser page.
87
+ this.loginMethods[0].begin(this.addFlow({ client, params }), res);
88
+ }
89
+ /** Accepts this server's origin and paths under it, since the MCP endpoint answers on any path. */
90
+ isOwnResource(resource) {
91
+ return resource.origin === new URL(this.baseUrl).origin;
92
+ }
93
+ async completeLogin(flow, sessionJwt, res) {
94
+ const minted = await this.mealie.mintToken(sessionJwt);
95
+ const grantId = this.store.createGrant({
96
+ clientId: flow.client.client_id,
97
+ mealieToken: minted.token,
98
+ mealieTokenId: minted.id,
99
+ resource: this.baseUrl,
100
+ });
101
+ const code = randomBytes(32).toString('base64url');
102
+ this.codes.set(code, {
103
+ clientId: flow.client.client_id,
104
+ grantId,
105
+ challenge: flow.params.codeChallenge,
106
+ redirectUri: flow.params.redirectUri,
107
+ createdAt: this.now(),
108
+ });
109
+ const target = new URL(flow.params.redirectUri);
110
+ target.searchParams.set('code', code);
111
+ if (flow.params.state !== undefined)
112
+ target.searchParams.set('state', flow.params.state);
113
+ res.redirect(303, target.toString());
114
+ }
115
+ liveCode(client, code) {
116
+ this.evict();
117
+ const entry = this.codes.get(code);
118
+ if (!entry || entry.clientId !== client.client_id)
119
+ throw new InvalidGrantError('Invalid authorization code');
120
+ return entry;
121
+ }
122
+ async challengeForAuthorizationCode(client, code) {
123
+ return this.liveCode(client, code).challenge;
124
+ }
125
+ async exchangeAuthorizationCode(client, code, _codeVerifier, redirectUri, resource) {
126
+ const entry = this.liveCode(client, code);
127
+ this.codes.delete(code); // single use, even when a check below fails
128
+ if (redirectUri !== undefined && redirectUri !== entry.redirectUri) {
129
+ throw new InvalidGrantError('redirect_uri does not match the authorization request');
130
+ }
131
+ if (resource && !this.isOwnResource(resource))
132
+ throw new InvalidTargetError('This token is not for this server.');
133
+ return toOAuthTokens(this.store.issueTokens(entry.grantId));
134
+ }
135
+ async exchangeRefreshToken(client, refreshToken, _scopes, resource) {
136
+ if (resource && !this.isOwnResource(resource))
137
+ throw new InvalidTargetError('This token is not for this server.');
138
+ const record = refreshToken.startsWith(REFRESH_TOKEN_PREFIX) ? this.store.findToken(refreshToken) : undefined;
139
+ if (record?.kind !== 'refresh' || record.expiresAt <= this.now()) {
140
+ throw new InvalidGrantError('Invalid refresh token');
141
+ }
142
+ const grant = this.store.getGrant(record.grantId);
143
+ if (!grant || grant.clientId !== client.client_id)
144
+ throw new InvalidGrantError('Invalid refresh token');
145
+ if (record.supersededAt !== null && this.now() - record.supersededAt > REFRESH_REUSE_GRACE_MS) {
146
+ await this.endGrant(grant.id, grant.mealieToken, grant.mealieTokenId);
147
+ throw new InvalidGrantError('Refresh token was already used');
148
+ }
149
+ let valid;
150
+ try {
151
+ valid = await this.mealie.isTokenValid(grant.mealieToken);
152
+ }
153
+ catch (err) {
154
+ // A Mealie outage must not cost anyone their login: invalid_grant would force a new one.
155
+ if (err instanceof MealieUnavailableError)
156
+ throw new ServerError('Mealie is unavailable, try again later');
157
+ throw err;
158
+ }
159
+ if (!valid) {
160
+ this.store.deleteGrant(grant.id);
161
+ throw new InvalidGrantError('The Mealie token behind this login was revoked');
162
+ }
163
+ return toOAuthTokens(this.store.issueTokens(grant.id, refreshToken));
164
+ }
165
+ async verifyAccessToken(token) {
166
+ const resolved = this.store.resolveAccessToken(token);
167
+ if (!resolved)
168
+ throw new InvalidGrantError('Invalid access token');
169
+ return {
170
+ token,
171
+ clientId: resolved.grant.clientId,
172
+ scopes: [],
173
+ expiresAt: Math.floor(resolved.expiresAt / 1000),
174
+ resource: new URL(resolved.grant.resource),
175
+ };
176
+ }
177
+ async revokeToken(client, request) {
178
+ const record = this.store.findToken(request.token);
179
+ if (!record)
180
+ return;
181
+ const grant = this.store.getGrant(record.grantId);
182
+ if (!grant || grant.clientId !== client.client_id)
183
+ return;
184
+ await this.endGrant(grant.id, grant.mealieToken, grant.mealieTokenId);
185
+ }
186
+ /** Removes the local grant whatever Mealie says; the leftover token row is visible in the user's profile. */
187
+ async endGrant(grantId, mealieToken, mealieTokenId) {
188
+ this.store.deleteGrant(grantId);
189
+ await this.mealie.deleteToken(mealieToken, mealieTokenId).catch(() => false);
190
+ }
191
+ /** Drops expired tokens and abandoned grants. A grant is kept for the next run if Mealie can't be reached. */
192
+ async purge() {
193
+ this.store.deleteExpiredTokens();
194
+ for (const grant of this.store.findAbandonedGrants(ABANDONED_GRANT_MIN_AGE_MS)) {
195
+ const removed = await this.mealie.deleteToken(grant.mealieToken, grant.mealieTokenId).catch(() => false);
196
+ if (removed)
197
+ this.store.deleteGrant(grant.id);
198
+ }
199
+ }
200
+ }
201
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/auth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEtD,OAAO,EACL,0BAA0B,EAC1B,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,GACZ,MAAM,iDAAiD,CAAC;AAUzD,OAAO,EAAyB,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AACpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAmC,MAAM,YAAY,CAAC;AAEnF,MAAM,WAAW,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACnC,MAAM,WAAW,GAAG,EAAE,GAAG,IAAI,CAAC;AAC9B,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AACtC,yGAAyG;AACzG,MAAM,CAAC,MAAM,sBAAsB,GAAG,EAAE,GAAG,IAAI,CAAC;AAChD,8FAA8F;AAC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AAO,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,aAAa,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;YACzG,IAAI,OAAO;gBAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,2 @@
1
+ export declare function isRedirectUriAllowed(uri: string): boolean;
2
+ //# sourceMappingURL=redirects.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redirects.d.ts","sourceRoot":"","sources":["../../src/auth/redirects.ts"],"names":[],"mappings":"AAkDA,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAgBzD"}
@@ -0,0 +1,71 @@
1
+ // Hostnames only — matched against parsed.hostname, never against the raw string.
2
+ // Note new URL('http://[::1]:3000/').hostname is '[::1]' WITH brackets in Node.
3
+ const LOOPBACK_REDIRECT_HOSTNAMES = ['127.0.0.1', 'localhost', '[::1]'];
4
+ // Claude's hosted surfaces (claude.ai web, Desktop, mobile, Cowork) all complete
5
+ // OAuth against this callback. claude.ai is the URI Anthropic documents today;
6
+ // claude.com is allowed ahead of Anthropic's domain migration. Each is matched
7
+ // exactly on origin+pathname — a prefix match would also admit
8
+ // https://claude.ai/api/mcp/auth_callbackEVIL.
9
+ const CLAUDE_HOSTED_REDIRECT_URIS = [
10
+ 'https://claude.ai/api/mcp/auth_callback',
11
+ 'https://claude.com/api/mcp/auth_callback',
12
+ ];
13
+ // Matching is done on components of the PARSED URL, never on the raw string. A raw
14
+ // `uri.startsWith(...)` check is unsafe: URL userinfo lets the raw string lie about
15
+ // the real host, e.g. 'http://127.0.0.1:@evil.example.com/steal' starts with
16
+ // 'http://127.0.0.1:' but its parsed origin is 'http://evil.example.com'. Such a URI
17
+ // reached /oauth/callback, which redirected the authorization code to the attacker.
18
+ // Rejecting any URI that carries userinfo closes that bypass for every branch below,
19
+ // including the env-var prefix branch (an entry like 'https://my-client.example.com'
20
+ // would otherwise also match 'https://my-client.example.com@evil.example.com/').
21
+ // Do not reintroduce a startsWith(rawUri) check.
22
+ //
23
+ // MCP_ALLOWED_REDIRECT_PREFIXES entries are compared in *canonical* form too. A raw
24
+ // startsWith on the prefix as typed is unsafe even without userinfo: 'https://example.com'
25
+ // also matches 'https://example.com.attacker.test/steal', and a prefix spelled in a
26
+ // non-canonical way ('https://Example.com', 'https://example.com:443', an IDN) never
27
+ // equals its own parsed origin, so an origin-equality guard keyed on the raw string
28
+ // silently fell back to that raw startsWith. Each entry is therefore parsed and matched
29
+ // as: same parsed origin, and the URI's normalized href starts with the prefix's (so a
30
+ // prefix with a path only admits that path, and '/cb/../admin' is resolved before
31
+ // comparing). The one exception is the port-wildcard form 'http://192.168.1.10:' (a
32
+ // trailing ':' right after the host), which means "this scheme and host, any port".
33
+ const PORT_WILDCARD_PREFIX = /^[a-z][a-z0-9+.-]*:\/\/[^/?#@]+:$/i;
34
+ function matchesAllowedPrefix(parsed, prefix) {
35
+ let parsedPrefix;
36
+ try {
37
+ parsedPrefix = new URL(prefix);
38
+ }
39
+ catch {
40
+ return false; // an unparseable entry admits nothing
41
+ }
42
+ if (parsedPrefix.username !== '' || parsedPrefix.password !== '')
43
+ return false;
44
+ if (PORT_WILDCARD_PREFIX.test(prefix)) {
45
+ return parsed.protocol === parsedPrefix.protocol && parsed.hostname === parsedPrefix.hostname;
46
+ }
47
+ return parsed.origin === parsedPrefix.origin && parsed.href.startsWith(parsedPrefix.href);
48
+ }
49
+ export function isRedirectUriAllowed(uri) {
50
+ let parsed;
51
+ try {
52
+ parsed = new URL(uri);
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ if (parsed.username !== '' || parsed.password !== '')
58
+ return false;
59
+ if (parsed.protocol === 'http:' && LOOPBACK_REDIRECT_HOSTNAMES.includes(parsed.hostname))
60
+ return true;
61
+ if (CLAUDE_HOSTED_REDIRECT_URIS.includes(`${parsed.origin}${parsed.pathname}`))
62
+ return true;
63
+ const extra = process.env.MCP_ALLOWED_REDIRECT_PREFIXES?.trim();
64
+ if (!extra)
65
+ return false;
66
+ return extra
67
+ .split(',')
68
+ .map((s) => s.trim())
69
+ .some((p) => p !== '' && matchesAllowedPrefix(parsed, p));
70
+ }
71
+ //# sourceMappingURL=redirects.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redirects.js","sourceRoot":"","sources":["../../src/auth/redirects.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,gFAAgF;AAChF,MAAM,2BAA2B,GAAG,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;AAExE,iFAAiF;AACjF,+EAA+E;AAC/E,+EAA+E;AAC/E,+DAA+D;AAC/D,+CAA+C;AAC/C,MAAM,2BAA2B,GAAG;IAClC,yCAAyC;IACzC,0CAA0C;CAC3C,CAAC;AAEF,mFAAmF;AACnF,oFAAoF;AACpF,6EAA6E;AAC7E,qFAAqF;AACrF,oFAAoF;AACpF,qFAAqF;AACrF,qFAAqF;AACrF,iFAAiF;AACjF,iDAAiD;AACjD,EAAE;AACF,oFAAoF;AACpF,2FAA2F;AAC3F,oFAAoF;AACpF,qFAAqF;AACrF,oFAAoF;AACpF,wFAAwF;AACxF,uFAAuF;AACvF,kFAAkF;AAClF,oFAAoF;AACpF,oFAAoF;AACpF,MAAM,oBAAoB,GAAG,oCAAoC,CAAC;AAElE,SAAS,oBAAoB,CAAC,MAAW,EAAE,MAAc;IACvD,IAAI,YAAiB,CAAC;IACtB,IAAI,CAAC;QACH,YAAY,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC,CAAC,sCAAsC;IACtD,CAAC;IACD,IAAI,YAAY,CAAC,QAAQ,KAAK,EAAE,IAAI,YAAY,CAAC,QAAQ,KAAK,EAAE;QAAE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,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC;AAC9D,CAAC"}
@@ -0,0 +1,61 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ import type { OAuthClientInformationFull } from '@modelcontextprotocol/sdk/shared/auth.js';
3
+ export declare const ACCESS_TOKEN_PREFIX = "mcp_at_";
4
+ export declare const REFRESH_TOKEN_PREFIX = "mcp_rt_";
5
+ export declare const ACCESS_TOKEN_TTL_MS: number;
6
+ export declare const REFRESH_TOKEN_TTL_MS: number;
7
+ export declare const MIGRATIONS: string[];
8
+ export interface Grant {
9
+ id: string;
10
+ clientId: string;
11
+ mealieToken: string;
12
+ mealieTokenId: number;
13
+ resource: string;
14
+ createdAt: number;
15
+ }
16
+ export interface TokenRecord {
17
+ grantId: string;
18
+ kind: 'access' | 'refresh';
19
+ expiresAt: number;
20
+ supersededAt: number | null;
21
+ }
22
+ export interface TokenPair {
23
+ accessToken: string;
24
+ refreshToken: string;
25
+ expiresInSeconds: number;
26
+ }
27
+ export declare class TokenStore {
28
+ private readonly db;
29
+ private readonly key;
30
+ private readonly now;
31
+ private constructor();
32
+ static open(dataDir: string, secret: string, now?: () => number): Promise<TokenStore>;
33
+ /** Fails at startup, rather than logging every user out one request at a time. */
34
+ private verifyKey;
35
+ close(): void;
36
+ saveClient(client: OAuthClientInformationFull): void;
37
+ getClient(clientId: string): OAuthClientInformationFull | undefined;
38
+ createGrant(input: {
39
+ clientId: string;
40
+ mealieToken: string;
41
+ mealieTokenId: number;
42
+ resource: string;
43
+ }): string;
44
+ getGrant(id: string): Grant | undefined;
45
+ private toGrant;
46
+ deleteGrant(id: string): void;
47
+ findToken(rawToken: string): TokenRecord | undefined;
48
+ /** The Mealie token behind a live access token, or undefined. Refresh tokens never authorize a request. */
49
+ resolveAccessToken(rawToken: string): {
50
+ grant: Grant;
51
+ expiresAt: number;
52
+ } | undefined;
53
+ /** Issues a fresh pair and, when rotating, marks the refresh token it replaces. Atomic. */
54
+ issueTokens(grantId: string, replacing?: string): TokenPair;
55
+ deleteExpiredTokens(): void;
56
+ /** Grants with no usable refresh token left, older than `minAgeMs` so a login in progress is never caught. */
57
+ findAbandonedGrants(minAgeMs: number): Grant[];
58
+ private transaction;
59
+ }
60
+ export declare function migrate(db: DatabaseSync): void;
61
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/auth/store.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AAI3F,eAAO,MAAM,mBAAmB,YAAY,CAAC;AAC7C,eAAO,MAAM,oBAAoB,YAAY,CAAC;AAC9C,eAAO,MAAM,mBAAmB,QAAiB,CAAC;AAClD,eAAO,MAAM,oBAAoB,QAA2B,CAAC;AAK7D,eAAO,MAAM,UAAU,UAoBtB,CAAC;AAEF,MAAM,WAAW,KAAK;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,SAAS;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAWD,qBAAa,UAAU;IAEnB,OAAO,CAAC,QAAQ,CAAC,EAAE;IACnB,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAA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