mcp-google-multi 6.0.0-beta.2 → 6.0.0-beta.3

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 (165) hide show
  1. package/dist/accounts.d.ts +17 -1
  2. package/dist/accounts.js +52 -15
  3. package/dist/api-probe.d.ts +5 -0
  4. package/dist/api-probe.js +20 -15
  5. package/dist/arg-normalize.js +6 -5
  6. package/dist/arg-strict.d.ts +7 -0
  7. package/dist/arg-strict.js +34 -4
  8. package/dist/auth.d.ts +4 -3
  9. package/dist/auth.js +11 -13
  10. package/dist/boot-gates.d.ts +26 -0
  11. package/dist/boot-gates.js +38 -0
  12. package/dist/cimd-cache.d.ts +38 -0
  13. package/dist/cimd-cache.js +117 -0
  14. package/dist/client.d.ts +32 -2
  15. package/dist/client.js +0 -0
  16. package/dist/compose.d.ts +11 -0
  17. package/dist/compose.js +109 -0
  18. package/dist/config-file.d.ts +13 -0
  19. package/dist/config-file.js +37 -1
  20. package/dist/discover.js +3 -1
  21. package/dist/discovery-client.d.ts +3 -0
  22. package/dist/discovery-client.js +25 -2
  23. package/dist/doctor.d.ts +6 -2
  24. package/dist/doctor.js +119 -23
  25. package/dist/executor.d.ts +3 -0
  26. package/dist/executor.js +4 -2
  27. package/dist/fanout.d.ts +9 -1
  28. package/dist/fanout.js +44 -10
  29. package/dist/fs-atomic.d.ts +11 -0
  30. package/dist/fs-atomic.js +219 -28
  31. package/dist/hint-provider.d.ts +129 -0
  32. package/dist/hint-provider.js +64 -0
  33. package/dist/http-transport.d.ts +62 -4
  34. package/dist/http-transport.js +343 -24
  35. package/dist/identity.d.ts +4 -1
  36. package/dist/identity.js +25 -6
  37. package/dist/index.js +66 -138
  38. package/dist/master-key.js +13 -5
  39. package/dist/mcp-token.d.ts +136 -19
  40. package/dist/mcp-token.js +569 -72
  41. package/dist/migrate-config.js +2 -2
  42. package/dist/oauth-as.d.ts +103 -3
  43. package/dist/oauth-as.js +374 -79
  44. package/dist/oauth-consent.d.ts +10 -0
  45. package/dist/oauth-consent.js +16 -0
  46. package/dist/outbound-allowlist.js +5 -2
  47. package/dist/reauth-hint.d.ts +1 -1
  48. package/dist/reauth-hint.js +12 -8
  49. package/dist/registry-transfer.d.ts +5 -0
  50. package/dist/registry-transfer.js +65 -5
  51. package/dist/registry.d.ts +18 -1
  52. package/dist/registry.js +71 -15
  53. package/dist/scope-catalog.d.ts +11 -0
  54. package/dist/scope-catalog.js +23 -6
  55. package/dist/scope-observability.d.ts +8 -6
  56. package/dist/scope-observability.js +29 -13
  57. package/dist/services.d.ts +15 -10
  58. package/dist/services.js +59 -15
  59. package/dist/ssrf-guard.d.ts +23 -9
  60. package/dist/ssrf-guard.js +101 -62
  61. package/dist/tenant-purge.d.ts +26 -0
  62. package/dist/tenant-purge.js +67 -0
  63. package/dist/token-store.d.ts +20 -2
  64. package/dist/token-store.js +0 -0
  65. package/dist/tools/_errors.d.ts +3 -0
  66. package/dist/tools/_errors.js +53 -24
  67. package/dist/tools/_local-files.d.ts +9 -0
  68. package/dist/tools/_local-files.js +18 -0
  69. package/dist/tools/account-wizard.d.ts +10 -1
  70. package/dist/tools/account-wizard.js +74 -17
  71. package/dist/tools/accounts-tool.d.ts +7 -0
  72. package/dist/tools/accounts-tool.js +34 -18
  73. package/dist/tools/admin.d.ts +10 -1
  74. package/dist/tools/admin.js +15 -11
  75. package/dist/tools/analytics.d.ts +10 -1
  76. package/dist/tools/analytics.js +13 -8
  77. package/dist/tools/calendar.d.ts +2 -1
  78. package/dist/tools/calendar.js +18 -14
  79. package/dist/tools/chat.d.ts +10 -1
  80. package/dist/tools/chat.js +13 -8
  81. package/dist/tools/contacts.d.ts +2 -1
  82. package/dist/tools/contacts.js +17 -13
  83. package/dist/tools/docs.d.ts +2 -1
  84. package/dist/tools/docs.js +34 -30
  85. package/dist/tools/drive.d.ts +2 -1
  86. package/dist/tools/drive.js +65 -50
  87. package/dist/tools/forms.d.ts +10 -1
  88. package/dist/tools/forms.js +19 -12
  89. package/dist/tools/generated/_shared.d.ts +2 -1
  90. package/dist/tools/generated/_shared.js +7 -3
  91. package/dist/tools/generated/admin.d.ts +2 -1
  92. package/dist/tools/generated/admin.js +265 -265
  93. package/dist/tools/generated/analytics.d.ts +2 -1
  94. package/dist/tools/generated/analytics.js +125 -125
  95. package/dist/tools/generated/appsmarket.d.ts +2 -1
  96. package/dist/tools/generated/appsmarket.js +5 -5
  97. package/dist/tools/generated/calendar.d.ts +2 -1
  98. package/dist/tools/generated/calendar.js +55 -55
  99. package/dist/tools/generated/chat.d.ts +2 -1
  100. package/dist/tools/generated/chat.js +95 -95
  101. package/dist/tools/generated/classroom.d.ts +2 -1
  102. package/dist/tools/generated/classroom.js +209 -209
  103. package/dist/tools/generated/cloudidentity.d.ts +2 -1
  104. package/dist/tools/generated/cloudidentity.js +133 -133
  105. package/dist/tools/generated/cloudsearch.d.ts +2 -1
  106. package/dist/tools/generated/cloudsearch.js +99 -99
  107. package/dist/tools/generated/contacts.d.ts +2 -1
  108. package/dist/tools/generated/contacts.js +29 -29
  109. package/dist/tools/generated/drive.d.ts +2 -1
  110. package/dist/tools/generated/drive.js +71 -71
  111. package/dist/tools/generated/driveactivity.d.ts +2 -1
  112. package/dist/tools/generated/driveactivity.js +3 -3
  113. package/dist/tools/generated/drivelabels.d.ts +2 -1
  114. package/dist/tools/generated/drivelabels.js +53 -53
  115. package/dist/tools/generated/forms.d.ts +2 -1
  116. package/dist/tools/generated/forms.js +7 -7
  117. package/dist/tools/generated/gmail.d.ts +2 -1
  118. package/dist/tools/generated/gmail.js +117 -117
  119. package/dist/tools/generated/groupsmigration.d.ts +2 -1
  120. package/dist/tools/generated/groupsmigration.js +3 -3
  121. package/dist/tools/generated/groupssettings.d.ts +2 -1
  122. package/dist/tools/generated/groupssettings.js +7 -7
  123. package/dist/tools/generated/index.d.ts +2 -1
  124. package/dist/tools/generated/keep.d.ts +2 -1
  125. package/dist/tools/generated/keep.js +15 -15
  126. package/dist/tools/generated/licensing.d.ts +2 -1
  127. package/dist/tools/generated/licensing.js +15 -15
  128. package/dist/tools/generated/meet.d.ts +2 -1
  129. package/dist/tools/generated/meet.js +27 -27
  130. package/dist/tools/generated/postmaster.d.ts +2 -1
  131. package/dist/tools/generated/postmaster.js +9 -9
  132. package/dist/tools/generated/reseller.d.ts +2 -1
  133. package/dist/tools/generated/reseller.js +35 -35
  134. package/dist/tools/generated/script.d.ts +2 -1
  135. package/dist/tools/generated/script.js +33 -33
  136. package/dist/tools/generated/searchconsole.d.ts +2 -1
  137. package/dist/tools/generated/searchconsole.js +3 -3
  138. package/dist/tools/generated/sheets.d.ts +2 -1
  139. package/dist/tools/generated/sheets.js +15 -15
  140. package/dist/tools/generated/tasks.d.ts +2 -1
  141. package/dist/tools/generated/tasks.js +5 -5
  142. package/dist/tools/generated/vault.d.ts +2 -1
  143. package/dist/tools/generated/vault.js +67 -67
  144. package/dist/tools/generated/workspaceevents.d.ts +2 -1
  145. package/dist/tools/generated/workspaceevents.js +31 -31
  146. package/dist/tools/gmail.d.ts +2 -1
  147. package/dist/tools/gmail.js +45 -33
  148. package/dist/tools/google-api.d.ts +2 -3
  149. package/dist/tools/google-api.js +30 -16
  150. package/dist/tools/meet.d.ts +10 -1
  151. package/dist/tools/meet.js +13 -9
  152. package/dist/tools/searchconsole.d.ts +2 -1
  153. package/dist/tools/searchconsole.js +17 -13
  154. package/dist/tools/sheets.d.ts +2 -1
  155. package/dist/tools/sheets.js +36 -32
  156. package/dist/tools/slides.d.ts +10 -1
  157. package/dist/tools/slides.js +17 -10
  158. package/dist/tools/tasks.d.ts +2 -1
  159. package/dist/tools/tasks.js +19 -15
  160. package/dist/trim.d.ts +5 -0
  161. package/dist/trim.js +20 -0
  162. package/dist/usage-metrics.d.ts +23 -0
  163. package/dist/usage-metrics.js +65 -47
  164. package/dist/write-control.js +10 -2
  165. package/package.json +27 -1
package/dist/mcp-token.js CHANGED
@@ -1,17 +1,18 @@
1
1
  // B13 token model (oauth-authorization-server.md §Data model): the MCP access
2
2
  // token (HS256 JWT, jose-only — AS==RS so no JWKS), the signed self-contained
3
3
  // `state` and authorization code, the in-memory single-use replay guard, and
4
- // the opaque rotated refresh-token store. Keyed by the provisioned MCP_JWT_KEY
4
+ // the rotated refresh-token store. Keyed by the provisioned MCP_JWT_KEY
5
5
  // (B5), so tokens survive a restart as long as the key persists.
6
- import { randomBytes } from 'node:crypto';
6
+ import { createHash, createHmac, hkdfSync, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
7
7
  import { existsSync, readFileSync } from 'node:fs';
8
+ import { basename } from 'node:path';
8
9
  import { SignJWT, jwtVerify } from 'jose';
9
10
  import { deriveKey, encryptToken, decryptToken } from './token-store.js';
10
11
  import { atomicWriteFileSync, withFileLock } from './fs-atomic.js';
11
12
  export const ACCESS_TTL_DEFAULT = 600; // seconds
12
13
  export const STATE_TTL_DEFAULT = 600;
13
14
  export const CODE_TTL_DEFAULT = 60;
14
- export const REPLAY_CAP_DEFAULT = 10_000;
15
+ export const REPLAY_CAP_DEFAULT = 100_000;
15
16
  /** Derive the HS256 secret (32 bytes) from the provisioned MCP_JWT_KEY string. */
16
17
  export function jwtSecretFrom(jwtKey) {
17
18
  return new Uint8Array(deriveKey(jwtKey));
@@ -20,11 +21,13 @@ function newJti() {
20
21
  return randomBytes(16).toString('base64url');
21
22
  }
22
23
  export async function signAccessToken(p) {
24
+ if (typeof p.sub !== 'string' || p.sub === '')
25
+ throw new Error('signAccessToken: sub must be a non-empty string');
23
26
  const ttl = p.ttlSec ?? ACCESS_TTL_DEFAULT;
24
27
  return new SignJWT({ scope: 'mcp:use', purpose: 'mcp_access' })
25
28
  .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
26
29
  .setIssuer(p.base)
27
- .setSubject('owner')
30
+ .setSubject(p.sub)
28
31
  .setAudience(`${p.base}/mcp`)
29
32
  .setIssuedAt(p.iat)
30
33
  .setExpirationTime(p.iat + ttl)
@@ -36,7 +39,9 @@ export async function verifyAccessToken(token, base, secret) {
36
39
  const { payload } = await jwtVerify(token, secret, { issuer: base, audience: `${base}/mcp` });
37
40
  if (payload.purpose !== 'mcp_access')
38
41
  throw new Error('wrong token purpose');
39
- return { sub: String(payload.sub), scope: String(payload.scope ?? ''), jti: String(payload.jti ?? '') };
42
+ if (typeof payload.sub !== 'string' || payload.sub === '')
43
+ throw new Error('access token has no subject');
44
+ return { sub: payload.sub, scope: String(payload.scope ?? ''), jti: String(payload.jti ?? '') };
40
45
  }
41
46
  async function signArtifact(claims, purpose, base, secret, iat, ttlSec) {
42
47
  return new SignJWT({ ...claims, purpose })
@@ -47,130 +52,622 @@ async function signArtifact(claims, purpose, base, secret, iat, ttlSec) {
47
52
  .setJti(newJti())
48
53
  .sign(secret);
49
54
  }
50
- async function verifyArtifact(token, purpose, base, secret) {
51
- const { payload } = await jwtVerify(token, secret, { issuer: base });
55
+ // `nowSec`: the caller's clock, so expiry is judged by the same clock as the
56
+ // replay guard that records the artifact's spend.
57
+ async function verifyArtifact(token, purpose, base, secret, nowSec) {
58
+ const { payload } = await jwtVerify(token, secret, { issuer: base, ...(nowSec !== undefined ? { currentDate: new Date(nowSec * 1000) } : {}) });
52
59
  if (payload.purpose !== purpose)
53
60
  throw new Error(`wrong artifact purpose (${String(payload.purpose)})`);
54
- return { ...payload, jti: String(payload.jti ?? '') };
61
+ return { ...payload, jti: String(payload.jti ?? ''), exp: Number(payload.exp ?? 0) };
55
62
  }
56
63
  export function signState(payload, base, secret, iat, ttlSec = STATE_TTL_DEFAULT) {
57
64
  return signArtifact(payload, 'mcp_state', base, secret, iat, ttlSec);
58
65
  }
59
- export async function verifyState(token, base, secret) {
60
- return (await verifyArtifact(token, 'mcp_state', base, secret));
66
+ export async function verifyState(token, base, secret, nowSec) {
67
+ return (await verifyArtifact(token, 'mcp_state', base, secret, nowSec));
68
+ }
69
+ // --- alias_reauth link -------------------------------------------------------
70
+ /** A re-auth link is handed out in a tool error, so it has to survive until
71
+ * the user clicks it; an hour, not the 10-minute state TTL. */
72
+ export const REAUTH_LINK_TTL_SEC = 3600;
73
+ function reauthMac(base, secret, alias, exp) {
74
+ // The newline-separated input can never be a JWT signing input (two
75
+ // base64url segments and one dot), so the shared key stays unambiguous.
76
+ return createHmac('sha256', secret).update(`alias_reauth\n${base}\n${alias}\n${exp}`).digest();
77
+ }
78
+ /** Query string of a server-issued alias_reauth link: the alias, an expiry and
79
+ * an HMAC over both. Synchronous, so the error hints that carry it stay so. */
80
+ export function signReauthLink(base, secret, alias, nowSec) {
81
+ const exp = nowSec + REAUTH_LINK_TTL_SEC;
82
+ return `alias=${encodeURIComponent(alias)}&exp=${exp}&sig=${reauthMac(base, secret, alias, exp).toString('base64url')}`;
83
+ }
84
+ /** The alias a link was issued for, or null when it is missing, forged or expired. */
85
+ export function verifyReauthLink(base, secret, params, nowSec) {
86
+ const exp = Number(params.exp);
87
+ if (!params.alias || !/^\d+$/.test(params.exp) || exp < nowSec)
88
+ return null;
89
+ const want = reauthMac(base, secret, params.alias, exp);
90
+ const got = Buffer.from(params.sig, 'base64url');
91
+ return got.length === want.length && timingSafeEqual(got, want) ? params.alias : null;
61
92
  }
62
93
  /** A pending-authorization artifact for the DCR consent interstitial (same
63
94
  * shape as `state`, distinct purpose so the two can't be confused). */
64
95
  export function signPending(payload, base, secret, iat, ttlSec = STATE_TTL_DEFAULT) {
65
96
  return signArtifact(payload, 'mcp_pending', base, secret, iat, ttlSec);
66
97
  }
67
- export async function verifyPending(token, base, secret) {
68
- return (await verifyArtifact(token, 'mcp_pending', base, secret));
98
+ export async function verifyPending(token, base, secret, nowSec) {
99
+ return (await verifyArtifact(token, 'mcp_pending', base, secret, nowSec));
69
100
  }
70
101
  export function signAuthzCode(payload, base, secret, iat, ttlSec = CODE_TTL_DEFAULT) {
71
102
  return signArtifact(payload, 'mcp_code', base, secret, iat, ttlSec);
72
103
  }
73
- export async function verifyAuthzCode(token, base, secret) {
74
- return (await verifyArtifact(token, 'mcp_code', base, secret));
104
+ export async function verifyAuthzCode(token, base, secret, nowSec) {
105
+ return (await verifyArtifact(token, 'mcp_code', base, secret, nowSec));
75
106
  }
76
- // --- Replay guard (C10/C17: single-use, capped, TTL-evicted) ----------------
107
+ /** A full guard refuses rather than sweeping again sooner than this. */
108
+ const FULL_SWEEP_EVERY_MS = 1000;
77
109
  export class ReplayGuard {
78
110
  cap;
79
- seen = new Map(); // jti -> expiry (ms)
111
+ seen = new Map();
112
+ // A lower bound on every entry's expiry: below it nothing can have expired.
113
+ earliest = Infinity;
114
+ sweptAt = -Infinity;
80
115
  constructor(cap = REPLAY_CAP_DEFAULT) {
81
116
  this.cap = cap;
82
117
  }
83
- /** Record a jti as spent. Returns false if it was already spent (replay). */
84
- consume(jti, ttlMs, nowMs) {
85
- this.evictExpired(nowMs);
86
- if (this.seen.has(jti))
87
- return false;
88
- if (this.seen.size >= this.cap) {
89
- // drop the oldest-inserted entry to bound memory (C17)
90
- const oldest = this.seen.keys().next().value;
91
- if (oldest !== undefined)
92
- this.seen.delete(oldest);
118
+ /** Hold a slot for an artifact about to be handed out, so its spend can
119
+ * never meet a full guard. The flood then lands where the artifact is
120
+ * minted, and refusing there loses nothing. */
121
+ reserve(jti, ttlMs, nowMs) {
122
+ if (!this.room(nowMs))
123
+ return 'full';
124
+ this.record(jti, nowMs + ttlMs, false);
125
+ return 'ok';
126
+ }
127
+ /** Record a jti as spent. A full guard refuses instead of evicting a live
128
+ * jti: a flood of spends would otherwise make a spent artifact usable again,
129
+ * such as a callback the browser binding refused (H4 F1). `artifactExpMs`
130
+ * keeps the record alive as long as the artifact itself, even when the clock
131
+ * stepped back between its signing and this spend. */
132
+ spend(jti, ttlMs, nowMs, artifactExpMs = 0) {
133
+ const exp = Math.max(nowMs + ttlMs, artifactExpMs);
134
+ const held = this.seen.get(jti);
135
+ if (held && held.exp > nowMs) {
136
+ if (held.spent)
137
+ return 'replay';
138
+ held.spent = true;
139
+ held.exp = Math.max(held.exp, exp);
140
+ return 'ok';
93
141
  }
94
- this.seen.set(jti, nowMs + ttlMs);
95
- return true;
142
+ if (held)
143
+ this.seen.delete(jti);
144
+ if (!this.room(nowMs))
145
+ return 'full';
146
+ this.record(jti, exp, true);
147
+ return 'ok';
148
+ }
149
+ /** Undo a spend whose next step could not go ahead. The slot stays held, so
150
+ * nothing is forgotten, and the artifact can be spent once more. */
151
+ unspend(jti) {
152
+ const held = this.seen.get(jti);
153
+ if (held)
154
+ held.spent = false;
155
+ }
156
+ /** `spend` as a boolean: false for a replay and for a full guard alike. */
157
+ consume(jti, ttlMs, nowMs) {
158
+ return this.spend(jti, ttlMs, nowMs) === 'ok';
96
159
  }
97
160
  get size() {
98
161
  return this.seen.size;
99
162
  }
100
- evictExpired(nowMs) {
101
- for (const [jti, exp] of this.seen) {
102
- if (exp <= nowMs)
163
+ record(jti, exp, spent) {
164
+ this.seen.set(jti, { exp, spent });
165
+ if (exp < this.earliest)
166
+ this.earliest = exp;
167
+ }
168
+ // Expired entries are dropped only here, when the map is at the cap: a refusal
169
+ // costs O(1), and a sweep runs only once something can have expired, at most
170
+ // once a second. Walking the map from its head on every call is not cheap: a
171
+ // Map iterator steps over every deleted slot until the table is rebuilt.
172
+ room(nowMs) {
173
+ if (this.seen.size < this.cap)
174
+ return true;
175
+ if (nowMs < this.earliest)
176
+ return false;
177
+ if (nowMs >= this.sweptAt && nowMs - this.sweptAt < FULL_SWEEP_EVERY_MS)
178
+ return false;
179
+ this.sweptAt = nowMs;
180
+ let earliest = Infinity;
181
+ for (const [jti, e] of this.seen) {
182
+ if (e.exp <= nowMs)
103
183
  this.seen.delete(jti);
184
+ else if (e.exp < earliest)
185
+ earliest = e.exp;
104
186
  }
187
+ this.earliest = earliest;
188
+ return this.seen.size < this.cap;
105
189
  }
106
190
  }
107
- const SPENT_CAP = 2000;
191
+ /** Store files this release writes; an absent `format` is an earlier release's. */
192
+ const REFRESH_FORMAT = 2;
193
+ // r1 token: "r1." + base64url(fid 16 || gen uint32 BE || rand 16 || HMAC-SHA256
194
+ // of those 36 bytes). The dot is outside the base64url alphabet, so an r1
195
+ // token can never be read as an earlier release's 43-character token.
196
+ const R1_PREFIX = 'r1.';
197
+ const R1_LENGTH = 94;
198
+ const R1_BODY = 36;
199
+ const R1_BYTES = 68;
200
+ const R1_MAC_DOMAIN = Buffer.from('mcp-google-multi refresh r1\n');
201
+ const R1_KEY_INFO = 'mcp-google-multi:refresh-mac:v1';
202
+ // Every r1 token carries a MAC under a key from MASTER_KEY, so a passphrase
203
+ // key (deriveKey's bare-sha256 branch) would let one leaked token test
204
+ // guesses offline at hash speed. scrypt gives that branch a work factor.
205
+ const R1_SCRYPT_SALT = 'mcp-google-multi:refresh-mac:scrypt:v1';
206
+ const R1_SCRYPT = { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
207
+ const GEN_MAX = 0xffffffff;
208
+ const LEGACY_TOKEN = /^[A-Za-z0-9_-]{43}$/;
209
+ /** With a lifetime set, a stored time further ahead than this is pulled back to the clock. */
210
+ const CLOCK_SKEW_MS = 5 * 60_000;
211
+ const B64URL = /^[A-Za-z0-9_-]+$/;
212
+ const sha256 = (b) => createHash('sha256').update(b).digest();
213
+ /** A non-secret tag for log lines and rate-limit keys: never the token. */
214
+ const familyTag = (family) => sha256(family).toString('hex').slice(0, 8);
215
+ // Keyed on the master key: scrypt runs once per process, not once per store.
216
+ const macKeyMemo = new Map();
217
+ function refreshMacKey(masterKey) {
218
+ const hit = macKeyMemo.get(masterKey);
219
+ if (hit)
220
+ return hit;
221
+ const raw = deriveKey(masterKey);
222
+ const ikm = Buffer.from(masterKey, 'base64').length === 32 ? raw : scryptSync(masterKey, R1_SCRYPT_SALT, 32, R1_SCRYPT);
223
+ const key = Buffer.from(hkdfSync('sha256', ikm, Buffer.alloc(0), R1_KEY_INFO, 32));
224
+ macKeyMemo.set(masterKey, key);
225
+ return key;
226
+ }
227
+ function r1Mac(key, body) {
228
+ return createHmac('sha256', key).update(R1_MAC_DOMAIN).update(body).digest();
229
+ }
230
+ /** A token this key minted, or null. Pure CPU: runs before the file lock. */
231
+ function parseR1(t, key) {
232
+ if (typeof t !== 'string' || t.length !== R1_LENGTH || !t.startsWith(R1_PREFIX))
233
+ return null;
234
+ const text = t.slice(R1_PREFIX.length);
235
+ const buf = Buffer.from(text, 'base64url');
236
+ // The decoder skips stray characters and ignores the last one's pad bits;
237
+ // re-encoding leaves one spelling per token.
238
+ if (buf.length !== R1_BYTES || buf.toString('base64url') !== text)
239
+ return null;
240
+ if (!timingSafeEqual(buf.subarray(R1_BODY), r1Mac(key, buf.subarray(0, R1_BODY))))
241
+ return null;
242
+ const fidBytes = buf.subarray(0, 16);
243
+ return { fidBytes, fid: fidBytes.toString('base64url'), gen: buf.readUInt32BE(16), digest: sha256(buf) };
244
+ }
245
+ function mintR1(key, fid, gen) {
246
+ const body = Buffer.alloc(R1_BODY);
247
+ fid.copy(body, 0);
248
+ body.writeUInt32BE(gen, 16);
249
+ randomBytes(16).copy(body, 20);
250
+ const buf = Buffer.concat([body, r1Mac(key, body)]);
251
+ return { token: R1_PREFIX + buf.toString('base64url'), cur: sha256(buf).toString('base64url') };
252
+ }
108
253
  /**
109
- * Persisted (encrypted under MASTER_KEY) opaque refresh-token store. Rotates on
110
- * every use (a stolen token is usable at most once), and detects REUSE of a
111
- * rotated-away token as theft: the whole token family is revoked (#7 / C14).
112
- * All read-modify-write goes through a file lock so concurrent stdio+HTTP
113
- * processes can't lost-update or double-spend (#12).
254
+ * The family tag of a refresh token this `masterKey`'s store minted, or null
255
+ * for anything else. Derives the key once; the returned function does no I/O,
256
+ * so a host can key a pre-auth rate limit on it.
257
+ */
258
+ export function refreshFamilyTagger(masterKey) {
259
+ const key = refreshMacKey(masterKey);
260
+ return (token) => {
261
+ const p = parseR1(token, key);
262
+ return p ? familyTag(p.fidBytes) : null;
263
+ };
264
+ }
265
+ function ownEntries(o) {
266
+ // An own `__proto__` key (JSON.parse makes one) would set the prototype when copied.
267
+ return o !== null && typeof o === 'object' && !Array.isArray(o) ? Object.entries(o).filter(([k]) => k !== '__proto__') : [];
268
+ }
269
+ function isLegacyRecord(r) {
270
+ if (r === null || typeof r !== 'object')
271
+ return false;
272
+ const x = r;
273
+ return typeof x.sub === 'string' && x.sub !== '' && typeof x.family === 'string' && typeof x.issuedAt === 'number' && Number.isFinite(x.issuedAt);
274
+ }
275
+ function isCanonicalB64(s, bytes) {
276
+ return B64URL.test(s) && Buffer.from(s, 'base64url').length === bytes && Buffer.from(s, 'base64url').toString('base64url') === s;
277
+ }
278
+ function isFamilyRecord(key, r) {
279
+ if (r === null || typeof r !== 'object')
280
+ return false;
281
+ const x = r;
282
+ return (isCanonicalB64(key, 16) &&
283
+ typeof x.sub === 'string' && x.sub !== '' &&
284
+ Number.isInteger(x.gen) && x.gen >= 0 && x.gen <= GEN_MAX &&
285
+ typeof x.cur === 'string' && x.cur.length === 43 && isCanonicalB64(x.cur, 32) &&
286
+ Number.isFinite(x.createdAt) && Number.isFinite(x.usedAt) &&
287
+ (x.legacy === undefined || typeof x.legacy === 'string'));
288
+ }
289
+ function formatError(file, format) {
290
+ const name = basename(file);
291
+ return new Error(`E_REFRESH_STORE_FORMAT: ${name} was written by a newer release (format ${JSON.stringify(format)}): upgrade, or delete ${name} to sign every MCP client out`);
292
+ }
293
+ /** The decrypted plaintext, or null when the file is absent. Throws when it
294
+ * does not decrypt; the caller decides what that means. */
295
+ function readPlain(file, masterKey) {
296
+ if (!existsSync(file))
297
+ return null;
298
+ return decryptToken(readFileSync(file, 'utf-8'), masterKey);
299
+ }
300
+ // Outside any decrypt catch: a file from a newer release loaded as empty
301
+ // would be erased by the next write.
302
+ function checkFormat(file, d) {
303
+ if (d !== null && typeof d === 'object' && Object.hasOwn(d, 'format') && d.format !== REFRESH_FORMAT) {
304
+ throw formatError(file, d.format);
305
+ }
306
+ }
307
+ /** Only well-formed own entries survive, so no lookup lands on an inherited
308
+ * key and no malformed record reaches a liveness test or the token codec.
309
+ * `dirty` says something was dropped. */
310
+ function decodeData(d) {
311
+ const data = { families: {}, active: {}, spent: {} };
312
+ const x = (d ?? {});
313
+ let dropped = 0;
314
+ for (const [k, f] of ownEntries(x.families)) {
315
+ if (isFamilyRecord(k, f)) {
316
+ data.families[k] = { sub: f.sub, gen: f.gen, cur: f.cur, createdAt: f.createdAt, usedAt: f.usedAt, ...(f.legacy === undefined ? {} : { legacy: f.legacy }) };
317
+ }
318
+ else
319
+ dropped += 1;
320
+ }
321
+ for (const [t, r] of ownEntries(x.active)) {
322
+ if (isLegacyRecord(r))
323
+ data.active[t] = { sub: r.sub, issuedAt: r.issuedAt, family: r.family };
324
+ else
325
+ dropped += 1;
326
+ }
327
+ for (const [t, fam] of ownEntries(x.spent)) {
328
+ if (typeof fam === 'string')
329
+ data.spent[t] = fam;
330
+ else
331
+ dropped += 1;
332
+ }
333
+ return { data, dirty: dropped > 0 };
334
+ }
335
+ /** Every session of `sub`, in both formats. */
336
+ function dropSub(data, sub) {
337
+ let n = 0;
338
+ for (const [k, f] of Object.entries(data.families)) {
339
+ if (f.sub === sub) {
340
+ delete data.families[k];
341
+ n += 1;
342
+ }
343
+ }
344
+ for (const [t, r] of Object.entries(data.active)) {
345
+ if (r.sub === sub) {
346
+ delete data.active[t];
347
+ n += 1;
348
+ }
349
+ }
350
+ return n;
351
+ }
352
+ /** Boot check for a refresh store file: returns when it is absent or this
353
+ * release can read it; throws when it does not decrypt under `masterKey`
354
+ * (E_REFRESH_STORE_UNREADABLE) or a newer release wrote it
355
+ * (E_REFRESH_STORE_FORMAT). */
356
+ export function assertRefreshStoreReadable(file, masterKey) {
357
+ let d;
358
+ try {
359
+ d = readPlain(file, masterKey);
360
+ }
361
+ catch (e) {
362
+ throw new Error(`E_REFRESH_STORE_UNREADABLE: ${basename(file)} does not decrypt with this MASTER_KEY`, { cause: e });
363
+ }
364
+ checkFormat(file, d);
365
+ }
366
+ function positiveInt(name, v) {
367
+ if (v === undefined)
368
+ return undefined;
369
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v <= 0)
370
+ throw new Error(`E_REFRESH_OPTION_INVALID: ${name} must be a positive whole number`);
371
+ return v;
372
+ }
373
+ function lifetimeMs(name, v) {
374
+ const n = positiveInt(name, v);
375
+ return n === undefined ? undefined : n * 1000;
376
+ }
377
+ /**
378
+ * Persisted (encrypted under MASTER_KEY) refresh-token store. Rotates on every
379
+ * use, and a token carries its family and generation under a MAC, so
380
+ * presenting any generation the family has rotated past is REUSE: the family
381
+ * is revoked for the rest of its life (#7 / C14, H4 F2). The store keeps one
382
+ * record per family, whatever its rotation count. Every read-modify-write goes
383
+ * through a file lock so concurrent stdio+HTTP processes can't lost-update or
384
+ * double-spend (#12). See docs/internals.md.
114
385
  */
115
386
  export class RefreshStore {
116
387
  path;
117
388
  masterKey;
118
- constructor(path, masterKey) {
389
+ log;
390
+ maxAgeMs;
391
+ idleMs;
392
+ maxFamiliesPerSub;
393
+ macKey;
394
+ // Set once a load finds no earlier-release record. Nothing here adds one,
395
+ // so from then on a legacy-shaped token is refused before the lock.
396
+ legacyEmpty = false;
397
+ constructor(path, masterKey, options = {}) {
119
398
  this.path = path;
120
399
  this.masterKey = masterKey;
400
+ this.maxAgeMs = lifetimeMs('maxAgeSec', options.maxAgeSec);
401
+ this.idleMs = lifetimeMs('idleSec', options.idleSec);
402
+ this.maxFamiliesPerSub = positiveInt('maxFamiliesPerSub', options.maxFamiliesPerSub);
403
+ this.log = options.log ?? (() => undefined);
404
+ }
405
+ get timed() {
406
+ return this.maxAgeMs !== undefined || this.idleMs !== undefined;
407
+ }
408
+ // Positive form: a non-finite time can only make a session dead.
409
+ live(createdAt, usedAt, nowMs) {
410
+ return (this.maxAgeMs === undefined || nowMs < createdAt + this.maxAgeMs) && (this.idleMs === undefined || nowMs < usedAt + this.idleMs);
411
+ }
412
+ /** Drop expired sessions in both formats; the count of those dropped. */
413
+ prune(data, nowMs, lines) {
414
+ if (!this.timed)
415
+ return 0;
416
+ let n = 0;
417
+ for (const [k, f] of Object.entries(data.families)) {
418
+ if (!this.live(f.createdAt, f.usedAt, nowMs)) {
419
+ delete data.families[k];
420
+ n += 1;
421
+ }
422
+ }
423
+ for (const [t, r] of Object.entries(data.active)) {
424
+ if (!this.live(r.issuedAt, r.issuedAt, nowMs)) {
425
+ delete data.active[t];
426
+ n += 1;
427
+ }
428
+ }
429
+ if (n > 0) {
430
+ lines.push(`refresh families expired n=${n}`);
431
+ if (Object.keys(data.families).length === 0 && Object.keys(data.active).length === 0)
432
+ lines.push('refresh store: every session expired at once (check the host clock)');
433
+ }
434
+ return n;
435
+ }
436
+ /** A session written while the clock ran ahead would otherwise outlive its
437
+ * limit by the size of the jump. */
438
+ clamp(data, nowMs, lines) {
439
+ if (!this.timed)
440
+ return false;
441
+ const limit = nowMs + CLOCK_SKEW_MS;
442
+ let n = 0;
443
+ const pull = (t) => {
444
+ if (t <= limit)
445
+ return t;
446
+ n += 1;
447
+ return nowMs;
448
+ };
449
+ for (const f of Object.values(data.families)) {
450
+ f.createdAt = pull(f.createdAt);
451
+ f.usedAt = pull(f.usedAt);
452
+ }
453
+ for (const r of Object.values(data.active))
454
+ r.issuedAt = pull(r.issuedAt);
455
+ if (n > 0)
456
+ lines.push(`refresh store clock: n=${n} timestamps ahead of the clock were clamped`);
457
+ return n > 0;
458
+ }
459
+ key() {
460
+ return (this.macKey ??= refreshMacKey(this.masterKey));
121
461
  }
122
- load() {
123
- if (!existsSync(this.path))
124
- return { active: {}, spent: {} };
462
+ /** With `nowMs` (every issue and rotation), also clamps and prunes. */
463
+ load(nowMs, lines = []) {
464
+ let d;
465
+ let readOk = true;
125
466
  try {
126
- const d = decryptToken(readFileSync(this.path, 'utf-8'), this.masterKey);
127
- return { active: d.active ?? {}, spent: d.spent ?? {} };
467
+ d = readPlain(this.path, this.masterKey);
128
468
  }
129
469
  catch {
130
- return { active: {}, spent: {} };
470
+ d = null;
471
+ readOk = false;
472
+ }
473
+ checkFormat(this.path, d);
474
+ const loaded = decodeData(d);
475
+ if (nowMs !== undefined) {
476
+ if (this.clamp(loaded.data, nowMs, lines))
477
+ loaded.dirty = true;
478
+ if (this.prune(loaded.data, nowMs, lines) > 0)
479
+ loaded.dirty = true;
131
480
  }
481
+ // A failed read is not evidence that the file holds no legacy record.
482
+ if (readOk && Object.keys(loaded.data.active).length === 0 && Object.keys(loaded.data.spent).length === 0)
483
+ this.legacyEmpty = true;
484
+ return loaded;
132
485
  }
133
486
  save(data) {
134
- // bound the spent set (drop oldest-inserted) so it can't grow forever.
135
- const keys = Object.keys(data.spent);
136
- if (keys.length > SPENT_CAP) {
137
- for (const k of keys.slice(0, keys.length - SPENT_CAP))
138
- delete data.spent[k];
487
+ // Earlier-release evidence matters only while its family lives on, as a
488
+ // legacy record or as the family it migrated into.
489
+ const live = new Set();
490
+ for (const r of Object.values(data.active))
491
+ live.add(r.family);
492
+ for (const f of Object.values(data.families))
493
+ if (f.legacy !== undefined)
494
+ live.add(f.legacy);
495
+ for (const [t, fam] of Object.entries(data.spent))
496
+ if (!live.has(fam))
497
+ delete data.spent[t];
498
+ atomicWriteFileSync(this.path, encryptToken({ format: REFRESH_FORMAT, families: data.families, active: data.active, spent: data.spent }, this.masterKey), 0o600);
499
+ }
500
+ // After the write, so a failed save or a throwing accept logs nothing.
501
+ emit(lines) {
502
+ for (const line of lines) {
503
+ try {
504
+ this.log(line);
505
+ }
506
+ catch {
507
+ // The rotation is already on disk; a log sink must not lose its token.
508
+ }
509
+ }
510
+ }
511
+ /** Evict `sub`'s own least-recently-used sessions (both formats) so at
512
+ * most `limit` of its live sessions remain; dropping one here is the same
513
+ * as deleting it from `data.families` / `data.active` on a revoke, so it
514
+ * can never be presented again (reuse detection for every OTHER family is
515
+ * untouched). Only `sub`'s own entries are ever inspected.
516
+ *
517
+ * `keepKey` is the family just issued: it is excluded from the ranking so
518
+ * a clock step back, or a concurrent rotate's `usedAt = max(usedAt, nowMs)`
519
+ * racing ahead of it under the lock, can never make the brand-new family
520
+ * look like the least recently used one and drop itself. */
521
+ enforceFamilyCap(data, sub, limit, lines, keepKey) {
522
+ const entries = [];
523
+ for (const [k, f] of Object.entries(data.families)) {
524
+ if (f.sub !== sub || k === keepKey)
525
+ continue;
526
+ entries.push({
527
+ at: f.usedAt,
528
+ drop: () => {
529
+ delete data.families[k];
530
+ lines.push(`refresh family dropped: cap tag=${familyTag(Buffer.from(k, 'base64url'))}`);
531
+ },
532
+ });
533
+ }
534
+ for (const [t, r] of Object.entries(data.active)) {
535
+ if (r.sub !== sub)
536
+ continue;
537
+ entries.push({
538
+ at: r.issuedAt,
539
+ drop: () => {
540
+ delete data.active[t];
541
+ lines.push(`refresh family dropped: cap tag=${familyTag(r.family)}`);
542
+ },
543
+ });
139
544
  }
140
- atomicWriteFileSync(this.path, encryptToken(data, this.masterKey), 0o600);
545
+ // +1 accounts for the kept family, which stays live but is never ranked.
546
+ if (entries.length + 1 <= limit)
547
+ return;
548
+ entries.sort((a, b) => a.at - b.at);
549
+ for (const e of entries.slice(0, entries.length + 1 - limit))
550
+ e.drop();
141
551
  }
142
- issue(nowMs, family) {
552
+ newFamilyId(data) {
553
+ let fid;
554
+ do
555
+ fid = randomBytes(16);
556
+ while (Object.hasOwn(data.families, fid.toString('base64url')));
557
+ return fid;
558
+ }
559
+ issue(nowMs, sub) {
560
+ if (typeof sub !== 'string' || sub === '')
561
+ throw new Error('RefreshStore.issue: sub must be a non-empty string');
562
+ const key = this.key();
143
563
  return withFileLock(this.path, () => {
144
- const token = randomBytes(32).toString('base64url');
145
- const data = this.load();
146
- data.active[token] = { sub: 'owner', issuedAt: nowMs, family: family ?? randomBytes(12).toString('hex') };
564
+ const lines = [];
565
+ const { data } = this.load(nowMs, lines);
566
+ const fid = this.newFamilyId(data);
567
+ const fidKey = fid.toString('base64url');
568
+ const { token, cur } = mintR1(key, fid, 0);
569
+ data.families[fidKey] = { sub, gen: 0, cur, createdAt: nowMs, usedAt: nowMs };
570
+ if (this.maxFamiliesPerSub !== undefined)
571
+ this.enforceFamilyCap(data, sub, this.maxFamiliesPerSub, lines, fidKey);
147
572
  this.save(data);
573
+ this.emit(lines);
148
574
  return token;
149
575
  });
150
576
  }
151
- /** Rotate a presented refresh token; null if unknown OR if the presented
152
- * token was already rotated away (reuse => the family is revoked). */
153
- rotate(oldToken, nowMs) {
577
+ /** Rotate a presented refresh token; null if it is unknown, malformed, or
578
+ * rotated away (reuse => the family is revoked). The record's sub is copied
579
+ * forward and returned so the caller can mint the matching access token
580
+ * without trusting anything client-supplied.
581
+ *
582
+ * `accept` (optional) is called inside the store lock, before any mutation,
583
+ * with the record's sub. false: every session of that sub is dropped and
584
+ * null returned. A throw: nothing is written and the error propagates, so
585
+ * the presented token stays valid. Absent: unchanged. */
586
+ rotate(oldToken, nowMs, accept) {
587
+ const key = this.key();
588
+ const r1 = parseR1(oldToken, key);
589
+ if (!r1 && !(typeof oldToken === 'string' && LEGACY_TOKEN.test(oldToken) && !this.legacyEmpty))
590
+ return null;
154
591
  return withFileLock(this.path, () => {
155
- const data = this.load();
156
- const rec = data.active[oldToken];
157
- if (!rec) {
158
- // Reuse of a rotated-away token signals theft: revoke the whole family.
159
- const fam = data.spent[oldToken];
160
- if (fam) {
161
- for (const [t, r] of Object.entries(data.active))
162
- if (r.family === fam)
163
- delete data.active[t];
592
+ const lines = [];
593
+ // Expiry runs first: a dead session is refused without consulting accept.
594
+ const { data, dirty } = this.load(nowMs, lines);
595
+ const done = (result, write) => {
596
+ if (write)
164
597
  this.save(data);
165
- }
166
- return null;
598
+ this.emit(lines);
599
+ return result;
600
+ };
601
+ const refuse = (sub) => {
602
+ lines.push(`refresh sessions dropped: accept n=${dropSub(data, sub)}`);
603
+ return done(null, true);
604
+ };
605
+ if (r1) {
606
+ const f = Object.hasOwn(data.families, r1.fid) ? data.families[r1.fid] : undefined;
607
+ if (!f)
608
+ return done(null, dirty);
609
+ const drop = (why) => {
610
+ delete data.families[r1.fid];
611
+ lines.push(`refresh family ${why === 'reuse' ? 'revoked' : 'dropped'}: ${why} tag=${familyTag(r1.fidBytes)}`);
612
+ return done(null, true);
613
+ };
614
+ // Older: a rotated-away token, and the MAC proves this server minted it.
615
+ if (r1.gen < f.gen)
616
+ return drop('reuse');
617
+ // Newer, or the same generation with another random part: the store
618
+ // lost a write the client saw. Not evidence of theft.
619
+ if (r1.gen > f.gen)
620
+ return drop('ahead');
621
+ if (!timingSafeEqual(r1.digest, Buffer.from(f.cur, 'base64url')))
622
+ return drop('mismatch');
623
+ if (accept && !accept(f.sub))
624
+ return refuse(f.sub);
625
+ if (f.gen === GEN_MAX)
626
+ return drop('overflow');
627
+ const next = mintR1(key, r1.fidBytes, f.gen + 1);
628
+ f.gen += 1;
629
+ f.cur = next.cur;
630
+ // now() is read before the lock wait, so a later writer can hold an earlier time.
631
+ f.usedAt = Math.max(f.usedAt, nowMs);
632
+ return done({ token: next.token, sub: f.sub }, true);
633
+ }
634
+ const rec = Object.hasOwn(data.active, oldToken) ? data.active[oldToken] : undefined;
635
+ if (!rec) {
636
+ const fam = Object.hasOwn(data.spent, oldToken) ? data.spent[oldToken] : undefined;
637
+ if (fam === undefined)
638
+ return done(null, dirty);
639
+ // Reuse of an earlier-release rotated-away token: revoke the family in
640
+ // both formats.
641
+ for (const [t, r] of Object.entries(data.active))
642
+ if (r.family === fam)
643
+ delete data.active[t];
644
+ for (const [k, f] of Object.entries(data.families))
645
+ if (f.legacy === fam)
646
+ delete data.families[k];
647
+ lines.push(`refresh family revoked: reuse tag=${familyTag(fam)}`);
648
+ return done(null, true);
167
649
  }
650
+ if (accept && !accept(rec.sub))
651
+ return refuse(rec.sub);
652
+ // Migrate: the presented token stays behind as reuse evidence.
168
653
  delete data.active[oldToken];
169
654
  data.spent[oldToken] = rec.family;
170
- const next = randomBytes(32).toString('base64url');
171
- data.active[next] = { sub: 'owner', issuedAt: nowMs, family: rec.family };
172
- this.save(data);
173
- return next;
655
+ const fid = this.newFamilyId(data);
656
+ const next = mintR1(key, fid, 0);
657
+ data.families[fid.toString('base64url')] = { sub: rec.sub, gen: 0, cur: next.cur, createdAt: rec.issuedAt, usedAt: Math.max(rec.issuedAt, nowMs), legacy: rec.family };
658
+ return done({ token: next.token, sub: rec.sub }, true);
659
+ });
660
+ }
661
+ /** Drop every session minted under `sub`, in both formats (linear scan under
662
+ * the store lock); the save then drops the earlier-release spent entries of
663
+ * the families that died with them. Returns the number of sessions dropped. */
664
+ purgeTenant(sub) {
665
+ return withFileLock(this.path, () => {
666
+ const { data } = this.load();
667
+ const dropped = dropSub(data, sub);
668
+ if (dropped > 0)
669
+ this.save(data);
670
+ return dropped;
174
671
  });
175
672
  }
176
673
  }