@introspection-ai/recipes 0.36.2 → 0.38.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 (141) hide show
  1. package/dist/ask-user-question.d.ts +82 -0
  2. package/dist/ask-user-question.d.ts.map +1 -0
  3. package/dist/ask-user-question.js +314 -0
  4. package/dist/ask-user-question.js.map +1 -0
  5. package/dist/connector-tools.d.ts.map +1 -1
  6. package/dist/connector-tools.js +10 -2
  7. package/dist/connector-tools.js.map +1 -1
  8. package/dist/documents/index.d.ts +7 -0
  9. package/dist/documents/index.d.ts.map +1 -0
  10. package/dist/documents/index.js +4 -0
  11. package/dist/documents/index.js.map +1 -0
  12. package/dist/documents/module.d.ts +61 -0
  13. package/dist/documents/module.d.ts.map +1 -0
  14. package/dist/documents/module.js +133 -0
  15. package/dist/documents/module.js.map +1 -0
  16. package/dist/documents/profile.d.ts +34 -0
  17. package/dist/documents/profile.d.ts.map +1 -0
  18. package/dist/documents/profile.js +94 -0
  19. package/dist/documents/profile.js.map +1 -0
  20. package/dist/documents/tools.d.ts +40 -0
  21. package/dist/documents/tools.d.ts.map +1 -0
  22. package/dist/documents/tools.js +327 -0
  23. package/dist/documents/tools.js.map +1 -0
  24. package/dist/documents/types.d.ts +144 -0
  25. package/dist/documents/types.d.ts.map +1 -0
  26. package/dist/documents/types.js +10 -0
  27. package/dist/documents/types.js.map +1 -0
  28. package/dist/extensions.d.ts +2 -0
  29. package/dist/extensions.d.ts.map +1 -1
  30. package/dist/extensions.js +3 -0
  31. package/dist/extensions.js.map +1 -1
  32. package/dist/interaction-tui.d.ts +1 -1
  33. package/dist/interaction-tui.d.ts.map +1 -1
  34. package/dist/interaction-tui.js +2 -2
  35. package/dist/interaction-tui.js.map +1 -1
  36. package/dist/mcp-chunks/{auth-command-GMMLBU24.js → auth-command-M7TQE3AL.js} +26 -23
  37. package/dist/mcp-chunks/call-arguments-GCXZA4HC.js +16 -0
  38. package/dist/mcp-chunks/{call-command-2VF6IKAZ.js → call-command-7LD7UEFK.js} +33 -33
  39. package/dist/mcp-chunks/{chunk-TYL2NVXI.js → chunk-2AKSS7WR.js} +2 -2
  40. package/dist/mcp-chunks/{chunk-LZUKBEQZ.js → chunk-2YV72LUA.js} +12 -12
  41. package/dist/mcp-chunks/{chunk-2JTXIMGE.js → chunk-3ETUDW7N.js} +1 -1
  42. package/dist/mcp-chunks/{chunk-5UK2JLTN.js → chunk-3FRLDHVD.js} +5 -5
  43. package/dist/mcp-chunks/{chunk-ENBJFQ6H.js → chunk-3HSC6NHZ.js} +1 -1
  44. package/dist/mcp-chunks/{chunk-IHOU2BEL.js → chunk-3LENTPGE.js} +2 -2
  45. package/dist/mcp-chunks/{chunk-ZJWZY54X.js → chunk-3P3KGT4H.js} +2 -2
  46. package/dist/mcp-chunks/{chunk-IMXPLUKE.js → chunk-3SXP4S2A.js} +2 -2
  47. package/dist/mcp-chunks/{chunk-22WCLO4D.js → chunk-5Z6WSV5D.js} +5 -5
  48. package/dist/mcp-chunks/{chunk-QNZGFUKC.js → chunk-63L6SHK3.js} +2 -2
  49. package/dist/mcp-chunks/{chunk-OI3RTQXY.js → chunk-66VSGFXA.js} +1 -1
  50. package/dist/mcp-chunks/{chunk-DUBQHYW4.js → chunk-6O42UGLI.js} +9 -9
  51. package/dist/mcp-chunks/{chunk-R4OYHQ4V.js → chunk-6P3KAQ5N.js} +1 -1
  52. package/dist/mcp-chunks/{chunk-5OO6WVPL.js → chunk-7U5NSQ5T.js} +1 -1
  53. package/dist/mcp-chunks/{chunk-O2C3HXGS.js → chunk-B6S43WID.js} +1 -1
  54. package/dist/mcp-chunks/{chunk-VWPKJFK4.js → chunk-BHXCAVFP.js} +1 -1
  55. package/dist/mcp-chunks/{chunk-WXNGATQ7.js → chunk-BUOGKTKK.js} +2 -1
  56. package/dist/mcp-chunks/{chunk-4U4BUXQD.js → chunk-CXST5CVH.js} +33 -17
  57. package/dist/mcp-chunks/{chunk-YWFQPA4D.js → chunk-DU4SDPEV.js} +2 -2
  58. package/dist/mcp-chunks/{chunk-ZI5XYM4C.js → chunk-E76ZUBOJ.js} +4 -4
  59. package/dist/mcp-chunks/{chunk-D2SZ7KRY.js → chunk-ELHS763C.js} +1 -1
  60. package/dist/mcp-chunks/chunk-EQCSXVQ7.js +10650 -0
  61. package/dist/mcp-chunks/{chunk-RHXZKYM7.js → chunk-F2X4Y2TQ.js} +1 -1
  62. package/dist/mcp-chunks/{chunk-6XC5JJWD.js → chunk-GTETFUPQ.js} +28 -25
  63. package/dist/mcp-chunks/{chunk-UQUM7ICD.js → chunk-GZ53GNFP.js} +10 -10
  64. package/dist/mcp-chunks/{chunk-LUVLTUKR.js → chunk-H5PBSJP3.js} +1 -1
  65. package/dist/mcp-chunks/{chunk-FLUF2FRN.js → chunk-HNQSUT44.js} +3 -3
  66. package/dist/mcp-chunks/{chunk-CN5KSNWG.js → chunk-I6UFV7RW.js} +1 -1
  67. package/dist/mcp-chunks/{chunk-OSTHIELS.js → chunk-IRARVOUM.js} +1 -1
  68. package/dist/mcp-chunks/{webapi-NNCZGUMZ.js → chunk-IRSL7JRH.js} +255 -249
  69. package/dist/mcp-chunks/{chunk-ZXIF7MKN.js → chunk-IWCVZ46B.js} +2 -2
  70. package/dist/mcp-chunks/{chunk-RZZO3ZD4.js → chunk-JEHI2YU4.js} +3 -3
  71. package/dist/mcp-chunks/{chunk-ANNJGB6F.js → chunk-JTPTAO4M.js} +13 -13
  72. package/dist/mcp-chunks/{chunk-U5QZHPCC.js → chunk-KJ5FPQF6.js} +1 -1
  73. package/dist/mcp-chunks/{chunk-7IVXKYTI.js → chunk-L2MSWQDL.js} +1 -1
  74. package/dist/mcp-chunks/{chunk-DBNBEWRX.js → chunk-MEQXX43K.js} +1 -1
  75. package/dist/mcp-chunks/{chunk-3AAF3FSI.js → chunk-MHUMLEBO.js} +1 -1
  76. package/dist/mcp-chunks/{chunk-HFHIY5TO.js → chunk-N2U2FODH.js} +4 -4
  77. package/dist/mcp-chunks/{chunk-YFCNRWLV.js → chunk-N6YUOYDS.js} +2 -2
  78. package/dist/mcp-chunks/{chunk-C4TJGC4F.js → chunk-O3RTM5HD.js} +1 -1
  79. package/dist/mcp-chunks/{chunk-35LLRCRA.js → chunk-O7SIXJM6.js} +1308 -912
  80. package/dist/mcp-chunks/{chunk-QDFL757K.js → chunk-PSE442BC.js} +91 -77
  81. package/dist/mcp-chunks/{chunk-YPSODIQX.js → chunk-QNXOIF5U.js} +15 -14
  82. package/dist/mcp-chunks/{chunk-RKQC2EE6.js → chunk-RUF27IUF.js} +2 -2
  83. package/dist/mcp-chunks/{chunk-SS7V7GVT.js → chunk-S2F7DDP5.js} +4 -4
  84. package/dist/mcp-chunks/{chunk-D65GOMYV.js → chunk-TC2JPBFB.js} +2 -2
  85. package/dist/mcp-chunks/{chunk-7BVYBZ4J.js → chunk-THRMUZZD.js} +39 -14
  86. package/dist/mcp-chunks/{chunk-P5YLK5G2.js → chunk-UFV6SVQG.js} +11 -11
  87. package/dist/mcp-chunks/{chunk-LISNXOIQ.js → chunk-US63Y6XE.js} +1 -1
  88. package/dist/mcp-chunks/{chunk-HI6VG5LR.js → chunk-UVRJ3AAD.js} +2 -2
  89. package/dist/mcp-chunks/{chunk-6TIU2CDB.js → chunk-V42T3QNK.js} +456 -64
  90. package/dist/mcp-chunks/{chunk-347GOMV4.js → chunk-WDWSA7RL.js} +4 -4
  91. package/dist/mcp-chunks/{chunk-4PN2J74H.js → chunk-WQL7FJQ3.js} +4 -4
  92. package/dist/mcp-chunks/{chunk-LRGMFF5S.js → chunk-ZEA3Y5ZD.js} +7 -7
  93. package/dist/mcp-chunks/{cli-4OQD3H4N.js → cli-IYD7Y7MO.js} +67 -67
  94. package/dist/mcp-chunks/client-5MNBV3Z7.js +32 -0
  95. package/dist/mcp-chunks/{config-command-72TCIWPV.js → config-command-6DXILFNO.js} +129 -34
  96. package/dist/mcp-chunks/daemon-command-V3B3EMXD.js +32 -0
  97. package/dist/mcp-chunks/{dist-74UCKZK5.js → dist-Q7WSCBBK.js} +74 -55
  98. package/dist/mcp-chunks/{emit-ts-command-KD4ON2SE.js → emit-ts-command-NDCDFDRM.js} +17 -17
  99. package/dist/mcp-chunks/{generate-cli-runner-HWGI6HPL.js → generate-cli-runner-PW5WJ7KI.js} +136 -92
  100. package/dist/mcp-chunks/generated-daemon-runtime-3C4NWGAU.js +32 -0
  101. package/dist/mcp-chunks/{inspect-cli-command-FT5JSB7V.js → inspect-cli-command-4MGF5CPP.js} +9 -9
  102. package/dist/mcp-chunks/{launch-AHLKP2VM.js → launch-UG7IH27P.js} +1 -1
  103. package/dist/mcp-chunks/{lifecycle-BJDITFWN.js → lifecycle-QBYGUHQ3.js} +1 -1
  104. package/dist/mcp-chunks/{list-command-YKF7RN6Y.js → list-command-SDITI3ZM.js} +36 -35
  105. package/dist/mcp-chunks/{output-utils-LYB5IJRD.js → output-utils-YTMZTA7J.js} +3 -3
  106. package/dist/mcp-chunks/{prompt-CH6TK0bC-B3USYOND.js → prompt-DkftHXS7-N7UENQ4C.js} +1 -1
  107. package/dist/mcp-chunks/{record-command-MJW3Z5E5.js → record-command-JGTMATYI.js} +5 -5
  108. package/dist/mcp-chunks/{replay-command-5ZHBUOLE.js → replay-command-S2VAC4RW.js} +6 -6
  109. package/dist/mcp-chunks/{resource-command-L4I24AX5.js → resource-command-SRFQQROJ.js} +9 -9
  110. package/dist/mcp-chunks/{result-utils-5WRI66KV.js → result-utils-JASGNHXK.js} +3 -3
  111. package/dist/mcp-chunks/runtime-RMI3XCYJ.js +39 -0
  112. package/dist/mcp-chunks/{runtime-wrapper-WFMNIHD5.js → runtime-wrapper-7HYO3NM5.js} +3 -3
  113. package/dist/mcp-chunks/{serve-command-KNCSJUXS.js → serve-command-UF5SVREV.js} +1111 -697
  114. package/dist/mcp-chunks/{timeouts-2ZHGSB3R.js → timeouts-BJWDJEMH.js} +3 -3
  115. package/dist/mcp-chunks/{vault-command-7EDL45AA.js → vault-command-EYOIFWEY.js} +5 -4
  116. package/dist/mcp-chunks/webapi-WMMA3OEC.js +82 -0
  117. package/dist/mcp-daemon.js +28 -27
  118. package/dist/mcp-run-worker.js +28 -27
  119. package/dist/pi-extension.d.ts.map +1 -1
  120. package/dist/pi-extension.js +6 -0
  121. package/dist/pi-extension.js.map +1 -1
  122. package/dist/recipe/package.d.ts +15 -0
  123. package/dist/recipe/package.d.ts.map +1 -1
  124. package/dist/recipe/package.js +96 -2
  125. package/dist/recipe/package.js.map +1 -1
  126. package/dist/session.d.ts.map +1 -1
  127. package/dist/session.js +6 -0
  128. package/dist/session.js.map +1 -1
  129. package/docs/documents.md +344 -0
  130. package/docs/index.md +1 -0
  131. package/docs/interactions.md +76 -8
  132. package/docs/mcp-configuration.md +10 -5
  133. package/docs/recipe-format.md +69 -1
  134. package/documents/SKILL.md +63 -0
  135. package/package.json +16 -11
  136. package/dist/mcp-chunks/call-arguments-WSURHOLV.js +0 -16
  137. package/dist/mcp-chunks/chunk-BIVX2WFX.js +0 -3349
  138. package/dist/mcp-chunks/client-LXKCCVMT.js +0 -31
  139. package/dist/mcp-chunks/daemon-command-QHS3ACBM.js +0 -31
  140. package/dist/mcp-chunks/generated-daemon-runtime-7ORS5KBR.js +0 -31
  141. package/dist/mcp-chunks/runtime-IKWDQLZF.js +0 -38
@@ -4,13 +4,160 @@ import {
4
4
  withFileLock,
5
5
  writeJsonFile,
6
6
  writeTextFileAtomic
7
- } from "./chunk-IHOU2BEL.js";
7
+ } from "./chunk-3LENTPGE.js";
8
+ import {
9
+ CompactEncrypt,
10
+ compactDecrypt,
11
+ decodeProtectedHeader,
12
+ errors_exports
13
+ } from "./chunk-IRSL7JRH.js";
8
14
 
9
- // node_modules/.pnpm/mcporter@0.15.0/node_modules/mcporter/dist/oauth-vault.js
15
+ // node_modules/.pnpm/mcporter@0.16.1/node_modules/mcporter/dist/oauth-vault-encryption.js
16
+ var VAULT_PASSWORD_ENV = "MCPORTER_VAULT_PASSWORD";
17
+ var VAULT_ENCRYPTION_POLICY_ENV = "MCPORTER_VAULT_ENCRYPTION";
18
+ var VAULT_SECRET_ENV_NAMES = [VAULT_PASSWORD_ENV, VAULT_ENCRYPTION_POLICY_ENV];
19
+ var VAULT_JWE_ALG = "PBES2-HS512+A256KW";
20
+ var VAULT_JWE_ENC = "A256GCM";
21
+ var VAULT_JWE_TYP = "mcporter-vault+jwe";
22
+ var VAULT_PBES2_ITERATIONS = 8192;
23
+ var VAULT_PBES2_MAX_ITERATIONS = 1e5;
24
+ var MIN_VAULT_PASSWORD_LENGTH = 32;
25
+ var VAULT_SECRET_FIELDS = [
26
+ ["tokens", "access_token"],
27
+ ["tokens", "refresh_token"],
28
+ ["tokens", "id_token"],
29
+ ["clientInfo", "client_secret"],
30
+ ["clientInfo", "registration_access_token"],
31
+ ["codeVerifier"],
32
+ ["state"]
33
+ ];
34
+ var VaultEncryptionError = class extends Error {
35
+ code;
36
+ constructor(code, message) {
37
+ super(message);
38
+ this.code = code;
39
+ this.name = "VaultEncryptionError";
40
+ }
41
+ };
42
+ function hasVaultEncryptionMarker(marker, location) {
43
+ if (marker === void 0)
44
+ return false;
45
+ if (!marker || typeof marker !== "object" || marker.version !== 1) {
46
+ throw new VaultEncryptionError("payload_invalid", `Unsupported OAuth encryption format at ${location}; use a compatible mcporter version. Nothing was changed.`);
47
+ }
48
+ return true;
49
+ }
50
+ var encoder = new TextEncoder();
51
+ var decoder = new TextDecoder();
52
+ var COMPACT_JWE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
53
+ function readPassword(env, name) {
54
+ const value = env[name];
55
+ if (value === void 0)
56
+ return void 0;
57
+ if (value.length < MIN_VAULT_PASSWORD_LENGTH) {
58
+ throw new VaultEncryptionError("password_invalid", `${name} must be at least ${MIN_VAULT_PASSWORD_LENGTH} characters and should be generated, not chosen; use \`openssl rand -base64 32\`.`);
59
+ }
60
+ return value;
61
+ }
62
+ function readVaultEncryptionSettings(env = process.env, configuredPolicy) {
63
+ const raw = (env[VAULT_ENCRYPTION_POLICY_ENV] ?? "").trim().toLowerCase();
64
+ if (raw !== "" && raw !== "optional" && raw !== "required") {
65
+ throw new VaultEncryptionError("policy_invalid", `${VAULT_ENCRYPTION_POLICY_ENV} must be 'optional' or 'required'.`);
66
+ }
67
+ const policy = raw !== "" ? raw : configuredPolicy ?? "optional";
68
+ const password = readPassword(env, VAULT_PASSWORD_ENV);
69
+ if (policy === "required" && password === void 0) {
70
+ throw new VaultEncryptionError("password_missing", `${raw !== "" ? `${VAULT_ENCRYPTION_POLICY_ENV}=required` : 'oauthVaultEncryption is "required"'} but ${VAULT_PASSWORD_ENV} is not set; the OAuth vault cannot be used.`);
71
+ }
72
+ return { policy, password };
73
+ }
74
+ function childEnvWithoutVaultSecrets(env) {
75
+ const copy = { ...env };
76
+ for (const name of VAULT_SECRET_ENV_NAMES)
77
+ delete copy[name];
78
+ return copy;
79
+ }
80
+ function vaultSecretKid(vaultKey, path4) {
81
+ return `${vaultKey}/${path4.join("/")}`;
82
+ }
83
+ function header(token) {
84
+ if (typeof token !== "string" || !COMPACT_JWE.test(token))
85
+ return void 0;
86
+ try {
87
+ return decodeProtectedHeader(token);
88
+ } catch {
89
+ return void 0;
90
+ }
91
+ }
92
+ function isVaultSecretJwe(value) {
93
+ return header(value)?.typ === VAULT_JWE_TYP;
94
+ }
95
+ async function sealVaultSecret(plaintext, kid, password) {
96
+ const token = await new CompactEncrypt(encoder.encode(plaintext)).setProtectedHeader({ alg: VAULT_JWE_ALG, enc: VAULT_JWE_ENC, typ: VAULT_JWE_TYP, kid }).setKeyManagementParameters({ p2c: VAULT_PBES2_ITERATIONS }).encrypt(encoder.encode(password));
97
+ if (await openVaultSecret(token, kid, password) !== plaintext) {
98
+ throw new VaultEncryptionError("payload_invalid", `OAuth vault self-check failed for ${kid}; nothing was written.`);
99
+ }
100
+ return token;
101
+ }
102
+ async function openWith(token, password) {
103
+ try {
104
+ const { plaintext } = await compactDecrypt(token, encoder.encode(password), {
105
+ keyManagementAlgorithms: [VAULT_JWE_ALG],
106
+ contentEncryptionAlgorithms: [VAULT_JWE_ENC],
107
+ maxPBES2Count: VAULT_PBES2_MAX_ITERATIONS
108
+ });
109
+ return decoder.decode(plaintext);
110
+ } catch (error) {
111
+ if (error instanceof errors_exports.JWEDecryptionFailed)
112
+ return void 0;
113
+ if (error instanceof errors_exports.JOSEError) {
114
+ throw new VaultEncryptionError("payload_invalid", "An OAuth vault value is not a JWE mcporter can read; refusing to use it.");
115
+ }
116
+ throw error;
117
+ }
118
+ }
119
+ async function openVaultSecret(token, kid, password) {
120
+ const h = header(token);
121
+ if (!h || h.alg !== VAULT_JWE_ALG || h.enc !== VAULT_JWE_ENC || h.typ !== VAULT_JWE_TYP || typeof h.p2c !== "number" || h.p2c < 1 || h.p2c > VAULT_PBES2_MAX_ITERATIONS) {
122
+ throw new VaultEncryptionError("payload_invalid", `OAuth vault value ${kid} is not in the vault JWE profile; refusing to use it.`);
123
+ }
124
+ if (h.kid !== kid) {
125
+ throw new VaultEncryptionError("payload_invalid", `OAuth vault value ${kid} carries another identity; refusing to use it.`);
126
+ }
127
+ const value = await openWith(token, password);
128
+ if (value !== void 0)
129
+ return value;
130
+ throw new VaultEncryptionError("decrypt_failed", `Cannot decrypt OAuth vault value ${kid} with ${VAULT_PASSWORD_ENV}; the file was left untouched.`);
131
+ }
132
+ function readPath(node, path4) {
133
+ return path4.reduce((cur, key) => cur && typeof cur === "object" ? cur[key] : void 0, node);
134
+ }
135
+ function describeVaultSecrets(entries) {
136
+ const stats = { entries: 0, sealed: 0, plaintext: 0 };
137
+ if (!entries || typeof entries !== "object")
138
+ return stats;
139
+ for (const entry of Object.values(entries)) {
140
+ if (!entry || typeof entry !== "object" || typeof entry.serverName !== "string")
141
+ continue;
142
+ stats.entries += 1;
143
+ for (const path4 of VAULT_SECRET_FIELDS) {
144
+ const value = readPath(entry, path4);
145
+ if (typeof value !== "string")
146
+ continue;
147
+ if (isVaultSecretJwe(value))
148
+ stats.sealed += 1;
149
+ else
150
+ stats.plaintext += 1;
151
+ }
152
+ }
153
+ return stats;
154
+ }
155
+
156
+ // node_modules/.pnpm/mcporter@0.16.1/node_modules/mcporter/dist/oauth-vault.js
10
157
  import crypto from "node:crypto";
11
158
  import path2 from "node:path";
12
159
 
13
- // node_modules/.pnpm/mcporter@0.15.0/node_modules/mcporter/dist/oauth-credential-validation.js
160
+ // node_modules/.pnpm/mcporter@0.16.1/node_modules/mcporter/dist/oauth-credential-validation.js
14
161
  function isRecord(value) {
15
162
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
16
163
  }
@@ -31,7 +178,7 @@ function isStoredOAuthClientInformation(value) {
31
178
  return isOptionalString(value, "issuer");
32
179
  }
33
180
 
34
- // node_modules/.pnpm/mcporter@0.15.0/node_modules/mcporter/dist/oauth-token-generation.js
181
+ // node_modules/.pnpm/mcporter@0.16.1/node_modules/mcporter/dist/oauth-token-generation.js
35
182
  import { randomUUID } from "node:crypto";
36
183
  import { isDeepStrictEqual } from "node:util";
37
184
  var TOKEN_GENERATION_FIELD = "__mcporter_generation";
@@ -111,7 +258,7 @@ function sameOAuthClientValue(left, right) {
111
258
  return isDeepStrictEqual(withoutClientGeneration(left), withoutClientGeneration(right));
112
259
  }
113
260
 
114
- // node_modules/.pnpm/mcporter@0.15.0/node_modules/mcporter/dist/runtime/environment.js
261
+ // node_modules/.pnpm/mcporter@0.16.1/node_modules/mcporter/dist/runtime/environment.js
115
262
  import { AsyncLocalStorage } from "node:async_hooks";
116
263
  import os from "node:os";
117
264
  import path from "node:path";
@@ -134,18 +281,21 @@ function runtimeStateDir(kind) {
134
281
  return root && path.isAbsolute(root) ? path.join(root, "mcporter") : path.join(runtimeHome(), ".mcporter");
135
282
  }
136
283
 
137
- // node_modules/.pnpm/mcporter@0.15.0/node_modules/mcporter/dist/oauth-vault.js
284
+ // node_modules/.pnpm/mcporter@0.16.1/node_modules/mcporter/dist/oauth-vault.js
138
285
  function getOAuthVaultPath() {
139
286
  return path2.join(runtimeStateDir("data"), "credentials.json");
140
287
  }
141
- async function readVaultState() {
288
+ async function readVaultState(definition, scope = "credentials") {
289
+ const settings = readVaultEncryptionSettings(process.env, definition.oauthVaultEncryption);
142
290
  try {
143
291
  const existing = await readJsonFile(getOAuthVaultPath());
292
+ if (hasVaultEncryptionMarker(existing?.encryption, getOAuthVaultPath()) && settings.password === void 0) {
293
+ throw new VaultEncryptionError("password_missing", `The OAuth vault at ${getOAuthVaultPath()} requires ${VAULT_PASSWORD_ENV}, even when empty.`);
294
+ }
144
295
  if (existing && (existing.version === 1 || existing.version === 2) && existing.entries && typeof existing.entries === "object") {
145
- return {
146
- vault: { ...existing, version: 2 },
147
- needsRepair: existing.version !== 2
148
- };
296
+ const vault = { ...existing, version: 2 };
297
+ await openVaultSecrets(vault, definition, scope);
298
+ return { vault, needsRepair: existing.version !== 2 };
149
299
  }
150
300
  if (existing !== void 0) {
151
301
  return { vault: emptyVault(), needsRepair: true };
@@ -158,14 +308,64 @@ async function readVaultState() {
158
308
  }
159
309
  return { vault: emptyVault(), needsRepair: false };
160
310
  }
161
- async function readVault() {
162
- return (await readVaultState()).vault;
311
+ async function readVault(definition, scope = "credentials") {
312
+ return (await readVaultState(definition, scope)).vault;
163
313
  }
164
314
  function emptyVault() {
165
315
  return { version: 2, entries: {} };
166
316
  }
167
- async function writeVault(contents) {
168
- await writeJsonFile(getOAuthVaultPath(), contents);
317
+ async function writeVault(contents, definition) {
318
+ const settings = readVaultEncryptionSettings(process.env, definition.oauthVaultEncryption);
319
+ await writeJsonFile(getOAuthVaultPath(), settings.password === void 0 ? contents : await sealVaultSecrets(contents, settings.password));
320
+ }
321
+ function writePath(node, fieldPath, value) {
322
+ let current = node;
323
+ for (const key of fieldPath.slice(0, -1))
324
+ current = current[key];
325
+ current[fieldPath.at(-1)] = value;
326
+ }
327
+ async function openVaultSecrets(vault, definition, scope) {
328
+ const settings = readVaultEncryptionSettings(process.env, definition.oauthVaultEncryption);
329
+ if (settings.password === void 0) {
330
+ for (const entry of Object.values(vault.entries)) {
331
+ if (isVaultEntry(entry) && VAULT_SECRET_FIELDS.some((fieldPath) => isVaultSecretJwe(readPath(entry, fieldPath)))) {
332
+ throw new VaultEncryptionError("password_missing", `The OAuth vault at ${getOAuthVaultPath()} holds encrypted values for '${entry.serverName}'; set ${VAULT_PASSWORD_ENV} to use it.`);
333
+ }
334
+ }
335
+ return;
336
+ }
337
+ if (scope === "none")
338
+ return;
339
+ const exactKey = vaultKeyForDefinition(definition);
340
+ for (const key of /* @__PURE__ */ new Set([exactKey, ...legacyOAuthRenameKeys(vault, definition, exactKey)])) {
341
+ const entry = vault.entries[key];
342
+ if (!isVaultEntry(entry))
343
+ continue;
344
+ for (const fieldPath of VAULT_SECRET_FIELDS) {
345
+ const value = readPath(entry, fieldPath);
346
+ if (!isVaultSecretJwe(value))
347
+ continue;
348
+ writePath(entry, fieldPath, await openVaultSecret(value, vaultSecretKid(key, fieldPath), settings.password));
349
+ }
350
+ }
351
+ }
352
+ async function sealVaultSecrets(vault, password) {
353
+ const out = { ...vault, encryption: { version: 1 }, entries: {} };
354
+ for (const [key, entry] of Object.entries(vault.entries)) {
355
+ if (!isVaultEntry(entry)) {
356
+ out.entries[key] = entry;
357
+ continue;
358
+ }
359
+ const copy = structuredClone(entry);
360
+ for (const fieldPath of VAULT_SECRET_FIELDS) {
361
+ const value = readPath(copy, fieldPath);
362
+ if (typeof value === "string" && value.length > 0 && !isVaultSecretJwe(value)) {
363
+ writePath(copy, fieldPath, await sealVaultSecret(value, vaultSecretKid(key, fieldPath), password));
364
+ }
365
+ }
366
+ out.entries[key] = copy;
367
+ }
368
+ return out;
169
369
  }
170
370
  function vaultKeyForDefinition(definition) {
171
371
  const descriptor = {
@@ -182,7 +382,7 @@ async function reconcileVaultServerUrl(definition) {
182
382
  }
183
383
  const serverUrl = definition.command.url.toString();
184
384
  await withFileLock(getOAuthVaultPath(), async () => {
185
- const { vault, needsRepair } = await readVaultState();
385
+ const { vault, needsRepair } = await readVaultState(definition, "none");
186
386
  const serverUrls = stringRecord(vault.serverUrls);
187
387
  const previousUrl = serverUrls[definition.name];
188
388
  const namedEntryUrls = Object.values(vault.entries).filter((entry) => isVaultEntry(entry) && entry.serverName === definition.name).flatMap((entry) => typeof entry.serverUrl === "string" ? [entry.serverUrl] : []);
@@ -199,7 +399,7 @@ async function reconcileVaultServerUrl(definition) {
199
399
  return;
200
400
  }
201
401
  vault.serverUrls = { ...serverUrls, [definition.name]: serverUrl };
202
- await writeVault(vault);
402
+ await writeVault(vault, definition);
203
403
  });
204
404
  }
205
405
  function stringRecord(value) {
@@ -213,11 +413,11 @@ async function vaultCredentialKeys(definition) {
213
413
  if (definition.command.kind !== "http") {
214
414
  return [key];
215
415
  }
216
- const vault = await readVault();
416
+ const vault = await readVault(definition, "none");
217
417
  return [.../* @__PURE__ */ new Set([key, ...legacyOAuthRenameKeys(vault, definition, key)])];
218
418
  }
219
419
  async function loadVaultEntryForRecovery(definition) {
220
- const vault = await readVault();
420
+ const vault = await readVault(definition);
221
421
  const key = vaultKeyForDefinition(definition);
222
422
  const resolved = resolveVaultEntry(vault, definition);
223
423
  const tokenSnapshots = /* @__PURE__ */ new Map();
@@ -311,7 +511,7 @@ function clientIdFromEntry(entry) {
311
511
  }
312
512
  async function saveVaultEntry(definition, patch) {
313
513
  await withFileLock(getOAuthVaultPath(), async () => {
314
- const vault = await readVault();
514
+ const vault = await readVault(definition);
315
515
  const key = vaultKeyForDefinition(definition);
316
516
  const existing = isVaultEntry(vault.entries[key]) ? vault.entries[key] : void 0;
317
517
  const fallback = findSameUrlCredentials(vault, definition, key, existing);
@@ -327,7 +527,7 @@ async function saveVaultEntry(definition, patch) {
327
527
  clientInfo: (patch.clientInfo ? withOAuthClientGeneration(patch.clientInfo) : void 0) ?? current.clientInfo ?? (patch.tokens && !current.tokens ? fallback.clientInfo : void 0),
328
528
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
329
529
  };
330
- await writeVault(vault);
530
+ await writeVault(vault, definition);
331
531
  });
332
532
  }
333
533
  function tokensMatch(tokens, expected) {
@@ -336,7 +536,7 @@ function tokensMatch(tokens, expected) {
336
536
  async function clearVaultTokensIfMatching(definition, expectedTokens, expectedClientInfo, tokenSnapshots, clientSnapshots) {
337
537
  const key = vaultKeyForDefinition(definition);
338
538
  await withFileLock(getOAuthVaultPath(), async () => {
339
- const { vault, needsRepair } = await readVaultState();
539
+ const { vault, needsRepair } = await readVaultState(definition);
340
540
  const exact = isVaultEntry(vault.entries[key]) ? vault.entries[key] : void 0;
341
541
  const fallbackKeys = findSameUrlCredentials(vault, definition, key, exact).sourceKeys;
342
542
  const targetKeys = tokenSnapshots || clientSnapshots ? [.../* @__PURE__ */ new Set([...tokenSnapshots?.keys() ?? [], ...clientSnapshots?.keys() ?? []])] : [key, ...fallbackKeys];
@@ -367,20 +567,20 @@ async function clearVaultTokensIfMatching(definition, expectedTokens, expectedCl
367
567
  mutated = true;
368
568
  }
369
569
  if (mutated || needsRepair) {
370
- await writeVault(vault);
570
+ await writeVault(vault, definition);
371
571
  }
372
572
  });
373
573
  }
374
574
  async function clearVaultEntry(definition, scope) {
375
575
  const key = vaultKeyForDefinition(definition);
376
576
  await withFileLock(getOAuthVaultPath(), async () => {
377
- const { vault, needsRepair } = await readVaultState();
577
+ const { vault, needsRepair } = await readVaultState(definition, "none");
378
578
  const existing = isVaultEntry(vault.entries[key]) ? vault.entries[key] : void 0;
379
579
  const fallback = findSameUrlCredentials(vault, definition, key, existing);
380
580
  const inheritedKeys = scope === "all" ? legacyOAuthRenameKeys(vault, definition, key) : fallback.sourceKeys;
381
581
  if (!existing && inheritedKeys.length === 0) {
382
582
  if (needsRepair) {
383
- await writeVault(vault);
583
+ await writeVault(vault, definition);
384
584
  }
385
585
  return;
386
586
  }
@@ -427,11 +627,11 @@ async function clearVaultEntry(definition, scope) {
427
627
  updated.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
428
628
  vault.entries[fallbackKey] = updated;
429
629
  }
430
- await writeVault(vault);
630
+ await writeVault(vault, definition);
431
631
  });
432
632
  }
433
633
 
434
- // node_modules/.pnpm/mcporter@0.15.0/node_modules/mcporter/dist/oauth-persistence-stores.js
634
+ // node_modules/.pnpm/mcporter@0.16.1/node_modules/mcporter/dist/oauth-persistence-stores.js
435
635
  import fs from "node:fs/promises";
436
636
  import path3 from "node:path";
437
637
  function withStoredExpiry(tokens) {
@@ -450,11 +650,69 @@ function withStoredExpiry(tokens) {
450
650
  function prepareStoredTokens(tokens) {
451
651
  return withStoredExpiry(withOAuthTokenGeneration(tokens));
452
652
  }
653
+ var TOKEN_SECRET_FIELDS = ["access_token", "refresh_token", "id_token"];
654
+ var CLIENT_SECRET_FIELDS = ["client_secret", "registration_access_token"];
655
+ async function describeTokenCacheDir(root) {
656
+ try {
657
+ await fs.access(root);
658
+ } catch (error) {
659
+ if (error.code === "ENOENT")
660
+ return "absent";
661
+ throw error;
662
+ }
663
+ const marker = path3.join(root, "encryption.json");
664
+ const stats = { sealed: 0, plaintext: 0, encrypted: await readEncryptionMarker(marker) };
665
+ const count = (value) => {
666
+ if (typeof value !== "string" || value.length === 0)
667
+ return;
668
+ if (isVaultSecretJwe(value))
669
+ stats.sealed += 1;
670
+ else
671
+ stats.plaintext += 1;
672
+ };
673
+ const json = async (file) => {
674
+ try {
675
+ return await readJsonFile(path3.join(root, file));
676
+ } catch (error) {
677
+ if (error instanceof SyntaxError)
678
+ return void 0;
679
+ throw error;
680
+ }
681
+ };
682
+ for (const [file, fields] of [
683
+ ["tokens.json", TOKEN_SECRET_FIELDS],
684
+ ["client.json", CLIENT_SECRET_FIELDS]
685
+ ]) {
686
+ const record = await json(file);
687
+ if (record && typeof record === "object") {
688
+ for (const field of fields)
689
+ count(record[field]);
690
+ }
691
+ }
692
+ count(await json("state.txt"));
693
+ try {
694
+ count((await fs.readFile(path3.join(root, "code_verifier.txt"), "utf8")).trim());
695
+ } catch (error) {
696
+ if (error.code !== "ENOENT")
697
+ throw error;
698
+ }
699
+ return stats;
700
+ }
701
+ async function readEncryptionMarker(file) {
702
+ try {
703
+ return hasVaultEncryptionMarker(await readJsonFile(file), file);
704
+ } catch (error) {
705
+ if (!(error instanceof SyntaxError))
706
+ throw error;
707
+ throw new VaultEncryptionError("payload_invalid", `Invalid OAuth encryption marker at ${file}; nothing was changed.`);
708
+ }
709
+ }
453
710
  var DirectoryPersistence = class {
454
711
  root;
455
712
  logger;
456
713
  serverUrl;
457
714
  skipUrlMarkerWhenMissing;
715
+ vaultPolicy;
458
716
  tokenPath;
459
717
  clientInfoPath;
460
718
  codeVerifierPath;
@@ -463,11 +721,12 @@ var DirectoryPersistence = class {
463
721
  discoveryStatePath;
464
722
  authorizationServerUrlPath;
465
723
  resourceUrlPath;
466
- constructor(root, logger, serverUrl, skipUrlMarkerWhenMissing = false) {
724
+ constructor(root, logger, serverUrl, skipUrlMarkerWhenMissing = false, vaultPolicy) {
467
725
  this.root = root;
468
726
  this.logger = logger;
469
727
  this.serverUrl = serverUrl;
470
728
  this.skipUrlMarkerWhenMissing = skipUrlMarkerWhenMissing;
729
+ this.vaultPolicy = vaultPolicy;
471
730
  this.tokenPath = path3.join(root, "tokens.json");
472
731
  this.clientInfoPath = path3.join(root, "client.json");
473
732
  this.codeVerifierPath = path3.join(root, "code_verifier.txt");
@@ -483,7 +742,118 @@ var DirectoryPersistence = class {
483
742
  async ensureDir() {
484
743
  await fs.mkdir(this.root, { recursive: true });
485
744
  }
745
+ password() {
746
+ return readVaultEncryptionSettings(process.env, this.vaultPolicy).password;
747
+ }
748
+ async checkEncryptionMarker() {
749
+ if (await readEncryptionMarker(path3.join(this.root, "encryption.json")))
750
+ this.requirePassword();
751
+ }
752
+ async markEncrypted() {
753
+ await this.checkEncryptionMarker();
754
+ if (this.password() !== void 0) {
755
+ await writeJsonFile(path3.join(this.root, "encryption.json"), { version: 1 });
756
+ }
757
+ }
758
+ // Seals the named plaintext string fields of a record when a password is set.
759
+ async sealFields(record, file, fields) {
760
+ const password = this.password();
761
+ if (password === void 0)
762
+ return record;
763
+ const copy = { ...record };
764
+ for (const field of fields) {
765
+ const value = copy[field];
766
+ if (typeof value === "string" && value.length > 0 && !isVaultSecretJwe(value)) {
767
+ copy[field] = await sealVaultSecret(value, `${file}/${field}`, password);
768
+ }
769
+ }
770
+ return copy;
771
+ }
772
+ // Every write goes through here, under the tokens.json lock: without a
773
+ // password a directory that holds sealed values is refused and left as it
774
+ // is, as the vault is; with one, the files this write does not touch are
775
+ // sealed too, so the first write seals the whole directory.
776
+ async save(written, write) {
777
+ await this.reconcileServerUrl();
778
+ await this.ensureDir();
779
+ await withFileLock(this.tokenPath, async () => {
780
+ if (this.password() === void 0 && await this.holdsSealedValues())
781
+ this.requirePassword();
782
+ await this.markEncrypted();
783
+ await write();
784
+ await this.sealOtherFiles(written);
785
+ });
786
+ }
787
+ async holdsSealedValues() {
788
+ for (const [file, fields] of [
789
+ [this.tokenPath, TOKEN_SECRET_FIELDS],
790
+ [this.clientInfoPath, CLIENT_SECRET_FIELDS]
791
+ ]) {
792
+ const record = await this.readJsonOrUndefined(file);
793
+ if (record && typeof record === "object" && fields.some((field) => isVaultSecretJwe(record[field])))
794
+ return true;
795
+ }
796
+ return isVaultSecretJwe(await this.readTextAfterReconcile(this.codeVerifierPath)) || isVaultSecretJwe(await this.readJsonOrUndefined(this.statePath));
797
+ }
798
+ // The secret files this save did not write are sealed too.
799
+ async sealOtherFiles(written) {
800
+ if (this.password() === void 0)
801
+ return;
802
+ if (written !== this.tokenPath)
803
+ await this.sealJsonFile(this.tokenPath, "tokens.json", TOKEN_SECRET_FIELDS);
804
+ if (written !== this.clientInfoPath) {
805
+ await this.sealJsonFile(this.clientInfoPath, "client.json", CLIENT_SECRET_FIELDS);
806
+ }
807
+ if (written !== this.codeVerifierPath) {
808
+ const verifier = await this.readTextAfterReconcile(this.codeVerifierPath);
809
+ if (verifier && !isVaultSecretJwe(verifier)) {
810
+ await writeTextFileAtomic(this.codeVerifierPath, await this.sealValue(verifier, "code_verifier.txt"));
811
+ }
812
+ }
813
+ if (written !== this.statePath) {
814
+ const state = await this.readJsonOrUndefined(this.statePath);
815
+ if (typeof state === "string" && state && !isVaultSecretJwe(state)) {
816
+ await writeJsonFile(this.statePath, await this.sealValue(state, "state.txt"));
817
+ }
818
+ }
819
+ }
820
+ async sealJsonFile(file, name, fields) {
821
+ const record = await this.readJsonOrUndefined(file);
822
+ if (!record || typeof record !== "object")
823
+ return;
824
+ const sealed = await this.sealFields(record, name, fields);
825
+ if (fields.some((field) => sealed[field] !== record[field]))
826
+ await writeJsonFile(file, sealed);
827
+ }
828
+ // Opens the named fields that are sealed; plaintext fields are left as they are.
829
+ async openFields(record, file, fields) {
830
+ if (!record)
831
+ return record;
832
+ const copy = { ...record };
833
+ for (const field of fields) {
834
+ if (!isVaultSecretJwe(copy[field]))
835
+ continue;
836
+ copy[field] = await openVaultSecret(copy[field], `${file}/${field}`, this.requirePassword());
837
+ }
838
+ return copy;
839
+ }
840
+ async sealValue(value, kid) {
841
+ const password = this.password();
842
+ return password === void 0 ? value : await sealVaultSecret(value, kid, password);
843
+ }
844
+ async openValue(value, kid) {
845
+ return isVaultSecretJwe(value) ? await openVaultSecret(value, kid, this.requirePassword()) : value;
846
+ }
847
+ requirePassword() {
848
+ const password = this.password();
849
+ if (password === void 0) {
850
+ throw new VaultEncryptionError("password_missing", `${this.root} holds encrypted values; set ${VAULT_PASSWORD_ENV} to use it.`);
851
+ }
852
+ return password;
853
+ }
486
854
  async reconcileServerUrl() {
855
+ readVaultEncryptionSettings(process.env, this.vaultPolicy);
856
+ await this.checkEncryptionMarker();
487
857
  if (!this.serverUrl) {
488
858
  return;
489
859
  }
@@ -512,8 +882,11 @@ var DirectoryPersistence = class {
512
882
  return;
513
883
  }
514
884
  if (previousUrl !== void 0) {
885
+ if (this.password() === void 0 && await this.holdsSealedValues())
886
+ this.requirePassword();
515
887
  await this.clearFiles("all");
516
888
  }
889
+ await this.markEncrypted();
517
890
  await writeTextFileAtomic(this.serverUrlPath, serverUrl);
518
891
  });
519
892
  }
@@ -535,34 +908,44 @@ var DirectoryPersistence = class {
535
908
  return await this.readTokensAfterReconcile();
536
909
  }
537
910
  async readTokensAfterReconcile() {
538
- const tokens = await this.readJsonOrUndefined(this.tokenPath);
911
+ const tokens = await this.openFields(await this.readJsonOrUndefined(this.tokenPath), "tokens.json", TOKEN_SECRET_FIELDS);
539
912
  return isStoredOAuthTokens(tokens) ? withHiddenOAuthTokenGeneration(tokens) : void 0;
540
913
  }
541
914
  async saveTokens(tokens) {
542
- await this.reconcileServerUrl();
543
- await this.ensureDir();
544
- await withFileLock(this.tokenPath, async () => {
545
- await writeJsonFile(this.tokenPath, prepareStoredTokens(tokens));
915
+ await this.save(this.tokenPath, async () => {
916
+ await writeJsonFile(this.tokenPath, await this.sealFields(prepareStoredTokens(tokens), "tokens.json", TOKEN_SECRET_FIELDS));
546
917
  });
547
918
  this.logger?.debug?.(`Saved tokens to ${this.tokenPath}`);
548
919
  }
549
920
  async clearRejectedCredentials(expectedTokens, expectedClientInfo) {
550
921
  await this.reconcileServerUrl();
551
922
  await withFileLock(this.tokenPath, async () => {
923
+ const files = [];
552
924
  if (expectedTokens) {
553
- const current = await this.readJsonOrUndefined(this.tokenPath);
925
+ const current = await this.openFields(await this.readJsonOrUndefined(this.tokenPath), "tokens.json", TOKEN_SECRET_FIELDS);
554
926
  if (sameOAuthTokenGeneration(current, expectedTokens)) {
555
- await this.unlinkIfPresent(this.tokenPath);
927
+ files.push(this.tokenPath);
556
928
  }
557
929
  }
558
930
  if (expectedClientInfo) {
559
- const currentClientInfo = await this.readJsonOrUndefined(this.clientInfoPath);
931
+ const currentClientInfo = await this.openFields(await this.readJsonOrUndefined(this.clientInfoPath), "client.json", CLIENT_SECRET_FIELDS);
560
932
  if (sameOAuthClientGeneration(currentClientInfo, expectedClientInfo)) {
561
- await this.unlinkIfPresent(this.clientInfoPath);
933
+ files.push(this.clientInfoPath);
562
934
  }
563
935
  }
936
+ await this.removeFiles(files);
564
937
  });
565
938
  }
939
+ // Every deletion path calls this while holding the token lock. Persist the
940
+ // policy before the last secret disappears, including conditional recovery.
941
+ async removeFiles(files) {
942
+ if (files.length === 0)
943
+ return;
944
+ if (this.password() === void 0 && await this.holdsSealedValues())
945
+ this.requirePassword();
946
+ await this.markEncrypted();
947
+ await Promise.all(files.map((file) => this.unlinkIfPresent(file)));
948
+ }
566
949
  async unlinkIfPresent(file) {
567
950
  try {
568
951
  await fs.unlink(file);
@@ -577,14 +960,12 @@ var DirectoryPersistence = class {
577
960
  return await this.readClientInfoAfterReconcile();
578
961
  }
579
962
  async readClientInfoAfterReconcile() {
580
- const info = await this.readJsonOrUndefined(this.clientInfoPath);
963
+ const info = await this.openFields(await this.readJsonOrUndefined(this.clientInfoPath), "client.json", CLIENT_SECRET_FIELDS);
581
964
  return isStoredOAuthClientInformation(info) ? withHiddenOAuthClientGeneration(info) : void 0;
582
965
  }
583
966
  async saveClientInfo(info) {
584
- await this.reconcileServerUrl();
585
- await this.ensureDir();
586
- await withFileLock(this.tokenPath, async () => {
587
- await writeJsonFile(this.clientInfoPath, withOAuthClientGeneration(info));
967
+ await this.save(this.clientInfoPath, async () => {
968
+ await writeJsonFile(this.clientInfoPath, await this.sealFields(withOAuthClientGeneration(info), "client.json", CLIENT_SECRET_FIELDS));
588
969
  });
589
970
  }
590
971
  async readCodeVerifier() {
@@ -593,7 +974,7 @@ var DirectoryPersistence = class {
593
974
  }
594
975
  async readCodeVerifierAfterReconcile() {
595
976
  try {
596
- return (await fs.readFile(this.codeVerifierPath, "utf8")).trim();
977
+ return await this.openValue((await fs.readFile(this.codeVerifierPath, "utf8")).trim(), "code_verifier.txt");
597
978
  } catch (error) {
598
979
  if (error.code === "ENOENT") {
599
980
  return void 0;
@@ -602,16 +983,16 @@ var DirectoryPersistence = class {
602
983
  }
603
984
  }
604
985
  async saveCodeVerifier(value) {
605
- await this.reconcileServerUrl();
606
- await this.ensureDir();
607
- await writeTextFileAtomic(this.codeVerifierPath, value);
986
+ await this.save(this.codeVerifierPath, async () => {
987
+ await writeTextFileAtomic(this.codeVerifierPath, await this.sealValue(value, "code_verifier.txt"));
988
+ });
608
989
  }
609
990
  async readState() {
610
991
  await this.reconcileServerUrl();
611
992
  return await this.readStateAfterReconcile();
612
993
  }
613
994
  async readStateAfterReconcile() {
614
- return readJsonFile(this.statePath);
995
+ return await this.openValue(await readJsonFile(this.statePath), "state.txt");
615
996
  }
616
997
  // A present-but-corrupt credential cache (tokens/client) means "no usable
617
998
  // credentials": degrade to re-auth instead of crashing the connection,
@@ -630,9 +1011,9 @@ var DirectoryPersistence = class {
630
1011
  }
631
1012
  }
632
1013
  async saveState(value) {
633
- await this.reconcileServerUrl();
634
- await this.ensureDir();
635
- await writeJsonFile(this.statePath, value);
1014
+ await this.save(this.statePath, async () => {
1015
+ await writeJsonFile(this.statePath, await this.sealValue(value, "state.txt"));
1016
+ });
636
1017
  }
637
1018
  async readDiscoveryState() {
638
1019
  await this.reconcileServerUrl();
@@ -642,27 +1023,21 @@ var DirectoryPersistence = class {
642
1023
  return readJsonFile(this.discoveryStatePath);
643
1024
  }
644
1025
  async saveDiscoveryState(value) {
645
- await this.reconcileServerUrl();
646
- await this.ensureDir();
647
- await writeJsonFile(this.discoveryStatePath, value);
1026
+ await this.save(this.discoveryStatePath, () => writeJsonFile(this.discoveryStatePath, value));
648
1027
  }
649
1028
  async readAuthorizationServerUrl() {
650
1029
  await this.reconcileServerUrl();
651
1030
  return this.readTextAfterReconcile(this.authorizationServerUrlPath);
652
1031
  }
653
1032
  async saveAuthorizationServerUrl(value) {
654
- await this.reconcileServerUrl();
655
- await this.ensureDir();
656
- await writeTextFileAtomic(this.authorizationServerUrlPath, value);
1033
+ await this.save(this.authorizationServerUrlPath, () => writeTextFileAtomic(this.authorizationServerUrlPath, value));
657
1034
  }
658
1035
  async readResourceUrl() {
659
1036
  await this.reconcileServerUrl();
660
1037
  return this.readTextAfterReconcile(this.resourceUrlPath);
661
1038
  }
662
1039
  async saveResourceUrl(value) {
663
- await this.reconcileServerUrl();
664
- await this.ensureDir();
665
- await writeTextFileAtomic(this.resourceUrlPath, value);
1040
+ await this.save(this.resourceUrlPath, () => writeTextFileAtomic(this.resourceUrlPath, value));
666
1041
  }
667
1042
  async readTextAfterReconcile(filePath) {
668
1043
  try {
@@ -675,7 +1050,9 @@ var DirectoryPersistence = class {
675
1050
  }
676
1051
  async clear(scope) {
677
1052
  await this.reconcileServerUrl();
678
- await this.clearFiles(scope);
1053
+ await withFileLock(this.tokenPath, async () => {
1054
+ await this.clearFiles(scope);
1055
+ });
679
1056
  }
680
1057
  async clearFiles(scope) {
681
1058
  const files = [];
@@ -694,7 +1071,7 @@ var DirectoryPersistence = class {
694
1071
  if (scope === "all" || scope === "discovery") {
695
1072
  files.push(this.discoveryStatePath, this.authorizationServerUrlPath, this.resourceUrlPath);
696
1073
  }
697
- await Promise.all(files.map((file) => this.unlinkIfPresent(file)));
1074
+ await this.removeFiles(files);
698
1075
  }
699
1076
  };
700
1077
  var VaultPersistence = class {
@@ -859,6 +1236,10 @@ var CompositePersistence = class {
859
1236
  }
860
1237
  async readRecoveryValues(read, snapshots) {
861
1238
  const results = await Promise.allSettled(this.stores.map((store) => read(store)));
1239
+ for (const result of results) {
1240
+ if (result.status === "rejected" && result.reason instanceof VaultEncryptionError)
1241
+ throw result.reason;
1242
+ }
862
1243
  snapshots.clear();
863
1244
  let value;
864
1245
  let source;
@@ -941,11 +1322,11 @@ async function createOAuthPersistenceStores(definition, logger) {
941
1322
  const stores = [vault];
942
1323
  const serverUrl = definition.command.kind === "http" ? definition.command.url.toString() : void 0;
943
1324
  if (definition.tokenCacheDir) {
944
- stores.unshift(new DirectoryPersistence(definition.tokenCacheDir, logger, serverUrl));
1325
+ stores.unshift(new DirectoryPersistence(definition.tokenCacheDir, logger, serverUrl, false, definition.oauthVaultEncryption));
945
1326
  }
946
1327
  const legacyDir = path3.join(path3.join(runtimeHome(), ".mcporter"), definition.name);
947
1328
  if (!definition.tokenCacheDir) {
948
- const legacy = new DirectoryPersistence(legacyDir, logger, serverUrl, true);
1329
+ const legacy = new DirectoryPersistence(legacyDir, logger, serverUrl, true, definition.oauthVaultEncryption);
949
1330
  const snapshot = await legacy.readSnapshot();
950
1331
  if (snapshot.tokens || snapshot.clientInfo || snapshot.codeVerifier || snapshot.state || snapshot.discoveryState || snapshot.authorizationServerUrl || snapshot.resourceUrl) {
951
1332
  if (snapshot.tokens) {
@@ -970,6 +1351,9 @@ async function createOAuthPersistenceStores(definition, logger) {
970
1351
  await vault.saveResourceUrl(snapshot.resourceUrl);
971
1352
  }
972
1353
  logger?.info?.(`Migrated legacy OAuth cache for '${definition.name}' into vault.`);
1354
+ if (readVaultEncryptionSettings(process.env, definition.oauthVaultEncryption).password !== void 0) {
1355
+ await legacy.clear("all");
1356
+ }
973
1357
  }
974
1358
  }
975
1359
  return stores.length === 1 ? vault : new CompositePersistence(stores);
@@ -977,7 +1361,7 @@ async function createOAuthPersistenceStores(definition, logger) {
977
1361
  async function clearLegacyOAuthArtifacts(definition, logger, scope) {
978
1362
  const legacyDir = path3.join(path3.join(runtimeHome(), ".mcporter"), definition.name);
979
1363
  if (!definition.tokenCacheDir || legacyDir !== definition.tokenCacheDir) {
980
- const legacy = new DirectoryPersistence(legacyDir, logger);
1364
+ const legacy = new DirectoryPersistence(legacyDir, logger, void 0, false, definition.oauthVaultEncryption);
981
1365
  await legacy.clear(scope);
982
1366
  }
983
1367
  const legacyFiles = [];
@@ -997,6 +1381,13 @@ async function clearLegacyOAuthArtifacts(definition, logger, scope) {
997
1381
  }
998
1382
 
999
1383
  export {
1384
+ VAULT_PASSWORD_ENV,
1385
+ VAULT_ENCRYPTION_POLICY_ENV,
1386
+ VaultEncryptionError,
1387
+ hasVaultEncryptionMarker,
1388
+ readVaultEncryptionSettings,
1389
+ childEnvWithoutVaultSecrets,
1390
+ describeVaultSecrets,
1000
1391
  runtimeEnvironment,
1001
1392
  withRuntimeEnvironment,
1002
1393
  runtimeStateDir,
@@ -1008,6 +1399,7 @@ export {
1008
1399
  saveVaultEntry,
1009
1400
  clearVaultEntry,
1010
1401
  prepareStoredTokens,
1402
+ describeTokenCacheDir,
1011
1403
  createOAuthPersistenceStores,
1012
1404
  clearLegacyOAuthArtifacts
1013
1405
  };