@nexum-hub/agent 0.0.0-stage → 0.0.2

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 (343) hide show
  1. package/README.md +133 -2
  2. package/contracts/v2/common.schema.json +262 -0
  3. package/contracts/v2/fixtures/inputs.json +244 -0
  4. package/contracts/v2/fixtures/wire.json +6493 -0
  5. package/contracts/v2/model/agent.close.input.schema.json +14 -0
  6. package/contracts/v2/model/agent.close.output.schema.json +101 -0
  7. package/contracts/v2/model/agent.list.input.schema.json +57 -0
  8. package/contracts/v2/model/agent.list.output.schema.json +220 -0
  9. package/contracts/v2/model/agent.open.input.schema.json +35 -0
  10. package/contracts/v2/model/agent.open.output.schema.json +41 -0
  11. package/contracts/v2/model/agent.run.cancel.input.schema.json +18 -0
  12. package/contracts/v2/model/agent.run.cancel.output.schema.json +100 -0
  13. package/contracts/v2/model/agent.run.get.input.schema.json +41 -0
  14. package/contracts/v2/model/agent.run.get.output.schema.json +100 -0
  15. package/contracts/v2/model/agent.run.input.input.schema.json +30 -0
  16. package/contracts/v2/model/agent.run.input.output.schema.json +100 -0
  17. package/contracts/v2/model/agent.run.list.input.schema.json +47 -0
  18. package/contracts/v2/model/agent.run.list.output.schema.json +41 -0
  19. package/contracts/v2/model/agent.run.start.input.schema.json +73 -0
  20. package/contracts/v2/model/agent.run.start.output.schema.json +100 -0
  21. package/contracts/v2/wire/bodies.schema.json +383 -0
  22. package/contracts/v2/wire/envelope.schema.json +2280 -0
  23. package/contracts/v2/wire/events.schema.json +242 -0
  24. package/contracts/v2/wire/maintenance.schema.json +308 -0
  25. package/contracts/v2/wire/operations.schema.json +1791 -0
  26. package/contracts/v2/wire/stream.schema.json +74 -0
  27. package/contracts/v2/wire/types.schema.json +2616 -0
  28. package/dist/adapters/mcp-http.d.ts +22 -0
  29. package/dist/adapters/mcp-http.js +472 -0
  30. package/dist/adapters/mcp-http.js.map +1 -0
  31. package/dist/adapters/mcp-oauth.d.ts +29 -0
  32. package/dist/adapters/mcp-oauth.js +653 -0
  33. package/dist/adapters/mcp-oauth.js.map +1 -0
  34. package/dist/adapters/mcp-wire.d.ts +21 -0
  35. package/dist/adapters/mcp-wire.js +307 -0
  36. package/dist/adapters/mcp-wire.js.map +1 -0
  37. package/dist/adapters/mcp.d.ts +56 -0
  38. package/dist/adapters/mcp.js +1989 -0
  39. package/dist/adapters/mcp.js.map +1 -0
  40. package/dist/adapters/openapi-http.d.ts +29 -0
  41. package/dist/adapters/openapi-http.js +504 -0
  42. package/dist/adapters/openapi-http.js.map +1 -0
  43. package/dist/adapters/openapi-request.d.ts +26 -0
  44. package/dist/adapters/openapi-request.js +597 -0
  45. package/dist/adapters/openapi-request.js.map +1 -0
  46. package/dist/adapters/openapi-schema.d.ts +22 -0
  47. package/dist/adapters/openapi-schema.js +471 -0
  48. package/dist/adapters/openapi-schema.js.map +1 -0
  49. package/dist/adapters/openapi-typegen.d.ts +11 -0
  50. package/dist/adapters/openapi-typegen.js +185 -0
  51. package/dist/adapters/openapi-typegen.js.map +1 -0
  52. package/dist/adapters/openapi-types.d.ts +99 -0
  53. package/dist/adapters/openapi-types.js +2 -0
  54. package/dist/adapters/openapi-types.js.map +1 -0
  55. package/dist/adapters/openapi.d.ts +7 -0
  56. package/dist/adapters/openapi.js +768 -0
  57. package/dist/adapters/openapi.js.map +1 -0
  58. package/dist/application/activation.d.ts +28 -0
  59. package/dist/application/activation.js +289 -0
  60. package/dist/application/activation.js.map +1 -0
  61. package/dist/application/attachments.d.ts +24 -0
  62. package/dist/application/attachments.js +87 -0
  63. package/dist/application/attachments.js.map +1 -0
  64. package/dist/application/authority.d.ts +32 -0
  65. package/dist/application/authority.js +213 -0
  66. package/dist/application/authority.js.map +1 -0
  67. package/dist/application/catalog.d.ts +11 -0
  68. package/dist/application/catalog.js +177 -0
  69. package/dist/application/catalog.js.map +1 -0
  70. package/dist/application/config.d.ts +24 -0
  71. package/dist/application/config.js +140 -0
  72. package/dist/application/config.js.map +1 -0
  73. package/dist/application/connection.d.ts +35 -0
  74. package/dist/application/connection.js +465 -0
  75. package/dist/application/connection.js.map +1 -0
  76. package/dist/application/data-plane.d.ts +35 -0
  77. package/dist/application/data-plane.js +437 -0
  78. package/dist/application/data-plane.js.map +1 -0
  79. package/dist/application/diagnostics.d.ts +4 -0
  80. package/dist/application/diagnostics.js +65 -0
  81. package/dist/application/diagnostics.js.map +1 -0
  82. package/dist/application/dispatcher.d.ts +4 -0
  83. package/dist/application/dispatcher.js +16 -0
  84. package/dist/application/dispatcher.js.map +1 -0
  85. package/dist/application/main.d.ts +12 -0
  86. package/dist/application/main.js +167 -0
  87. package/dist/application/main.js.map +1 -0
  88. package/dist/application/maintenance.d.ts +27 -0
  89. package/dist/application/maintenance.js +244 -0
  90. package/dist/application/maintenance.js.map +1 -0
  91. package/dist/application/packages.d.ts +25 -0
  92. package/dist/application/packages.js +208 -0
  93. package/dist/application/packages.js.map +1 -0
  94. package/dist/application/processes.d.ts +49 -0
  95. package/dist/application/processes.js +180 -0
  96. package/dist/application/processes.js.map +1 -0
  97. package/dist/application/run-view.d.ts +17 -0
  98. package/dist/application/run-view.js +286 -0
  99. package/dist/application/run-view.js.map +1 -0
  100. package/dist/application/runtime.d.ts +78 -0
  101. package/dist/application/runtime.js +1747 -0
  102. package/dist/application/runtime.js.map +1 -0
  103. package/dist/application/tasks.d.ts +38 -0
  104. package/dist/application/tasks.js +23 -0
  105. package/dist/application/tasks.js.map +1 -0
  106. package/dist/application/user-state.d.ts +20 -0
  107. package/dist/application/user-state.js +52 -0
  108. package/dist/application/user-state.js.map +1 -0
  109. package/dist/application/work-git.d.ts +14 -0
  110. package/dist/application/work-git.js +67 -0
  111. package/dist/application/work-git.js.map +1 -0
  112. package/dist/cli.d.ts +2 -0
  113. package/dist/cli.js +40 -0
  114. package/dist/cli.js.map +1 -0
  115. package/dist/contracts/caller.d.ts +51 -0
  116. package/dist/contracts/caller.js +95 -0
  117. package/dist/contracts/caller.js.map +1 -0
  118. package/dist/contracts/error-data.d.ts +6 -0
  119. package/dist/contracts/error-data.js +51 -0
  120. package/dist/contracts/error-data.js.map +1 -0
  121. package/dist/contracts/errors.d.ts +10 -0
  122. package/dist/contracts/errors.js +28 -0
  123. package/dist/contracts/errors.js.map +1 -0
  124. package/dist/contracts/json.d.ts +9 -0
  125. package/dist/contracts/json.js +104 -0
  126. package/dist/contracts/json.js.map +1 -0
  127. package/dist/contracts/types.d.ts +122 -0
  128. package/dist/contracts/types.js +19 -0
  129. package/dist/contracts/types.js.map +1 -0
  130. package/dist/contracts/validation.d.ts +4 -0
  131. package/dist/contracts/validation.js +157 -0
  132. package/dist/contracts/validation.js.map +1 -0
  133. package/dist/contracts/wire-validation.d.ts +9 -0
  134. package/dist/contracts/wire-validation.js +399 -0
  135. package/dist/contracts/wire-validation.js.map +1 -0
  136. package/dist/contracts/wire.d.ts +1083 -0
  137. package/dist/contracts/wire.js +62 -0
  138. package/dist/contracts/wire.js.map +1 -0
  139. package/dist/extension-api.d.ts +12 -0
  140. package/dist/extension-api.js +2 -0
  141. package/dist/extension-api.js.map +1 -0
  142. package/dist/extensions/api.d.ts +72 -0
  143. package/dist/extensions/api.js +2 -0
  144. package/dist/extensions/api.js.map +1 -0
  145. package/dist/extensions/host-requests.d.ts +23 -0
  146. package/dist/extensions/host-requests.js +60 -0
  147. package/dist/extensions/host-requests.js.map +1 -0
  148. package/dist/extensions/materials.d.ts +37 -0
  149. package/dist/extensions/materials.js +691 -0
  150. package/dist/extensions/materials.js.map +1 -0
  151. package/dist/extensions/package-loader.d.ts +28 -0
  152. package/dist/extensions/package-loader.js +177 -0
  153. package/dist/extensions/package-loader.js.map +1 -0
  154. package/dist/extensions/packages.d.ts +73 -0
  155. package/dist/extensions/packages.js +441 -0
  156. package/dist/extensions/packages.js.map +1 -0
  157. package/dist/extensions/registry.d.ts +92 -0
  158. package/dist/extensions/registry.js +1540 -0
  159. package/dist/extensions/registry.js.map +1 -0
  160. package/dist/extensions/resources.d.ts +105 -0
  161. package/dist/extensions/resources.js +595 -0
  162. package/dist/extensions/resources.js.map +1 -0
  163. package/dist/extensions/state.d.ts +25 -0
  164. package/dist/extensions/state.js +10 -0
  165. package/dist/extensions/state.js.map +1 -0
  166. package/dist/extensions/transfer.d.ts +81 -0
  167. package/dist/extensions/transfer.js +16 -0
  168. package/dist/extensions/transfer.js.map +1 -0
  169. package/dist/index.d.ts +7 -0
  170. package/dist/index.js +25 -0
  171. package/dist/index.js.map +1 -0
  172. package/dist/maintenance/configuration.d.ts +79 -0
  173. package/dist/maintenance/configuration.js +1503 -0
  174. package/dist/maintenance/configuration.js.map +1 -0
  175. package/dist/maintenance/credentials.d.ts +23 -0
  176. package/dist/maintenance/credentials.js +177 -0
  177. package/dist/maintenance/credentials.js.map +1 -0
  178. package/dist/maintenance/files.d.ts +2 -0
  179. package/dist/maintenance/files.js +40 -0
  180. package/dist/maintenance/files.js.map +1 -0
  181. package/dist/maintenance/npm.d.ts +71 -0
  182. package/dist/maintenance/npm.js +1013 -0
  183. package/dist/maintenance/npm.js.map +1 -0
  184. package/dist/maintenance/oauth.d.ts +45 -0
  185. package/dist/maintenance/oauth.js +686 -0
  186. package/dist/maintenance/oauth.js.map +1 -0
  187. package/dist/maintenance/requests.d.ts +347 -0
  188. package/dist/maintenance/requests.js +959 -0
  189. package/dist/maintenance/requests.js.map +1 -0
  190. package/dist/maintenance/work-git.d.ts +29 -0
  191. package/dist/maintenance/work-git.js +776 -0
  192. package/dist/maintenance/work-git.js.map +1 -0
  193. package/dist/process/backend.d.ts +54 -0
  194. package/dist/process/backend.js +39 -0
  195. package/dist/process/backend.js.map +1 -0
  196. package/dist/process/environment-windows.d.ts +15 -0
  197. package/dist/process/environment-windows.js +151 -0
  198. package/dist/process/environment-windows.js.map +1 -0
  199. package/dist/process/environment.d.ts +28 -0
  200. package/dist/process/environment.js +410 -0
  201. package/dist/process/environment.js.map +1 -0
  202. package/dist/process/launch.d.ts +31 -0
  203. package/dist/process/launch.js +281 -0
  204. package/dist/process/launch.js.map +1 -0
  205. package/dist/process/managed.d.ts +36 -0
  206. package/dist/process/managed.js +459 -0
  207. package/dist/process/managed.js.map +1 -0
  208. package/dist/process/output-log.d.ts +50 -0
  209. package/dist/process/output-log.js +552 -0
  210. package/dist/process/output-log.js.map +1 -0
  211. package/dist/process/pipes.d.ts +16 -0
  212. package/dist/process/pipes.js +588 -0
  213. package/dist/process/pipes.js.map +1 -0
  214. package/dist/process/pty.d.ts +22 -0
  215. package/dist/process/pty.js +512 -0
  216. package/dist/process/pty.js.map +1 -0
  217. package/dist/process/windows-conout-worker.d.ts +1 -0
  218. package/dist/process/windows-conout-worker.js +90 -0
  219. package/dist/process/windows-conout-worker.js.map +1 -0
  220. package/dist/process/windows-conout.d.ts +46 -0
  221. package/dist/process/windows-conout.js +140 -0
  222. package/dist/process/windows-conout.js.map +1 -0
  223. package/dist/process/windows-helper.d.ts +43 -0
  224. package/dist/process/windows-helper.js +255 -0
  225. package/dist/process/windows-helper.js.map +1 -0
  226. package/dist/process/windows-job.d.ts +39 -0
  227. package/dist/process/windows-job.js +224 -0
  228. package/dist/process/windows-job.js.map +1 -0
  229. package/dist/process/windows-pipes.d.ts +16 -0
  230. package/dist/process/windows-pipes.js +475 -0
  231. package/dist/process/windows-pipes.js.map +1 -0
  232. package/dist/results/artifacts.d.ts +118 -0
  233. package/dist/results/artifacts.js +873 -0
  234. package/dist/results/artifacts.js.map +1 -0
  235. package/dist/results/encoder.d.ts +57 -0
  236. package/dist/results/encoder.js +1179 -0
  237. package/dist/results/encoder.js.map +1 -0
  238. package/dist/results/mcp.d.ts +95 -0
  239. package/dist/results/mcp.js +656 -0
  240. package/dist/results/mcp.js.map +1 -0
  241. package/dist/results/media.d.ts +19 -0
  242. package/dist/results/media.js +301 -0
  243. package/dist/results/media.js.map +1 -0
  244. package/dist/results/normalize.d.ts +29 -0
  245. package/dist/results/normalize.js +464 -0
  246. package/dist/results/normalize.js.map +1 -0
  247. package/dist/runtime/control-scripts.d.ts +23 -0
  248. package/dist/runtime/control-scripts.js +242 -0
  249. package/dist/runtime/control-scripts.js.map +1 -0
  250. package/dist/runtime/engine.d.ts +177 -0
  251. package/dist/runtime/engine.js +1159 -0
  252. package/dist/runtime/engine.js.map +1 -0
  253. package/dist/runtime/globals.d.ts +1 -0
  254. package/dist/runtime/globals.js +31 -0
  255. package/dist/runtime/globals.js.map +1 -0
  256. package/dist/runtime/material-retention.d.ts +34 -0
  257. package/dist/runtime/material-retention.js +671 -0
  258. package/dist/runtime/material-retention.js.map +1 -0
  259. package/dist/runtime/modules.d.ts +50 -0
  260. package/dist/runtime/modules.js +320 -0
  261. package/dist/runtime/modules.js.map +1 -0
  262. package/dist/runtime/names.d.ts +2 -0
  263. package/dist/runtime/names.js +22 -0
  264. package/dist/runtime/names.js.map +1 -0
  265. package/dist/runtime/operations.d.ts +20 -0
  266. package/dist/runtime/operations.js +137 -0
  267. package/dist/runtime/operations.js.map +1 -0
  268. package/dist/runtime/paths.d.ts +3 -0
  269. package/dist/runtime/paths.js +38 -0
  270. package/dist/runtime/paths.js.map +1 -0
  271. package/dist/runtime/promises.d.ts +9 -0
  272. package/dist/runtime/promises.js +78 -0
  273. package/dist/runtime/promises.js.map +1 -0
  274. package/dist/runtime/retention.d.ts +88 -0
  275. package/dist/runtime/retention.js +735 -0
  276. package/dist/runtime/retention.js.map +1 -0
  277. package/dist/runtime/run-log.d.ts +30 -0
  278. package/dist/runtime/run-log.js +207 -0
  279. package/dist/runtime/run-log.js.map +1 -0
  280. package/dist/runtime/scripts.d.ts +84 -0
  281. package/dist/runtime/scripts.js +387 -0
  282. package/dist/runtime/scripts.js.map +1 -0
  283. package/dist/runtime/tasks.d.ts +54 -0
  284. package/dist/runtime/tasks.js +290 -0
  285. package/dist/runtime/tasks.js.map +1 -0
  286. package/dist/sdk/maintenance.d.ts +3 -0
  287. package/dist/sdk/maintenance.js +80 -0
  288. package/dist/sdk/maintenance.js.map +1 -0
  289. package/dist/sdk/output-extension.d.ts +3 -0
  290. package/dist/sdk/output-extension.js +44 -0
  291. package/dist/sdk/output-extension.js.map +1 -0
  292. package/dist/sdk/output.d.ts +52 -0
  293. package/dist/sdk/output.js +350 -0
  294. package/dist/sdk/output.js.map +1 -0
  295. package/dist/sdk/runtime.d.ts +3 -0
  296. package/dist/sdk/runtime.js +26 -0
  297. package/dist/sdk/runtime.js.map +1 -0
  298. package/dist/sdk/sh.d.ts +3 -0
  299. package/dist/sdk/sh.js +384 -0
  300. package/dist/sdk/sh.js.map +1 -0
  301. package/dist/sdk/state.d.ts +2 -0
  302. package/dist/sdk/state.js +69 -0
  303. package/dist/sdk/state.js.map +1 -0
  304. package/dist/sdk/transfer.d.ts +3 -0
  305. package/dist/sdk/transfer.js +141 -0
  306. package/dist/sdk/transfer.js.map +1 -0
  307. package/dist/services/extensions.d.ts +19 -0
  308. package/dist/services/extensions.js +183 -0
  309. package/dist/services/extensions.js.map +1 -0
  310. package/dist/services/state.d.ts +37 -0
  311. package/dist/services/state.js +125 -0
  312. package/dist/services/state.js.map +1 -0
  313. package/dist/services/transfer.d.ts +86 -0
  314. package/dist/services/transfer.js +948 -0
  315. package/dist/services/transfer.js.map +1 -0
  316. package/dist/storage/schema.d.ts +8 -0
  317. package/dist/storage/schema.js +241 -0
  318. package/dist/storage/schema.js.map +1 -0
  319. package/dist/storage/sqlite.d.ts +241 -0
  320. package/dist/storage/sqlite.js +1855 -0
  321. package/dist/storage/sqlite.js.map +1 -0
  322. package/dist/storage/transfers.d.ts +90 -0
  323. package/dist/storage/transfers.js +2 -0
  324. package/dist/storage/transfers.js.map +1 -0
  325. package/dist/transfer/io.d.ts +74 -0
  326. package/dist/transfer/io.js +425 -0
  327. package/dist/transfer/io.js.map +1 -0
  328. package/dist/transfer/offers.d.ts +72 -0
  329. package/dist/transfer/offers.js +380 -0
  330. package/dist/transfer/offers.js.map +1 -0
  331. package/dist/transfer/stream-slots.d.ts +12 -0
  332. package/dist/transfer/stream-slots.js +28 -0
  333. package/dist/transfer/stream-slots.js.map +1 -0
  334. package/dist/work/catalog.d.ts +43 -0
  335. package/dist/work/catalog.js +198 -0
  336. package/dist/work/catalog.js.map +1 -0
  337. package/dist/work/discovery.d.ts +70 -0
  338. package/dist/work/discovery.js +465 -0
  339. package/dist/work/discovery.js.map +1 -0
  340. package/dist/work/service.d.ts +83 -0
  341. package/dist/work/service.js +703 -0
  342. package/dist/work/service.js.map +1 -0
  343. package/package.json +66 -4
@@ -0,0 +1,686 @@
1
+ import * as client from "openid-client";
2
+ import { createHash } from "node:crypto";
3
+ import { authorizeCall } from "../contracts/caller.js";
4
+ import { AgentError, isAgentError, } from "../contracts/errors.js";
5
+ import { canonicalJson, isPlainRecord } from "../contracts/json.js";
6
+ import { privateMaintenanceRead, privateMaintenanceWrite, } from "./credentials.js";
7
+ const providers = new WeakMap();
8
+ const sessionsBusy = new Set();
9
+ const ownErrors = new WeakSet();
10
+ const denied = new Set([
11
+ "forbidden",
12
+ "permission_denied",
13
+ "access_denied",
14
+ "unauthorized",
15
+ "authorization_configuration",
16
+ ]);
17
+ const copy = (value) => JSON.parse(canonicalJson(value, 1024 * 1024));
18
+ const hash = (value) => createHash("sha256")
19
+ .update(canonicalJson(value, 1024 * 1024))
20
+ .digest("hex");
21
+ function fail(code, message) {
22
+ const error = new AgentError(code, message);
23
+ ownErrors.add(error);
24
+ return error;
25
+ }
26
+ function check(condition, code, message) {
27
+ if (!condition)
28
+ throw fail(code, message);
29
+ }
30
+ function state(provider) {
31
+ return providers.get(provider);
32
+ }
33
+ function current(scope) {
34
+ scope.signal.throwIfAborted();
35
+ authorizeCall(() => scope.assertCurrent());
36
+ }
37
+ function interactiveIdentity(binding, scheme, scope) {
38
+ current(scope);
39
+ check(typeof binding.owner === "string" &&
40
+ binding.owner.length > 0 &&
41
+ binding.owner === scope.caller.principalId &&
42
+ binding.scheme === scheme &&
43
+ ["agentId", "profile", "target", "name", "authRevision"].every((key) => typeof binding[key] === "string" && binding[key].length > 0) &&
44
+ typeof scope.requestId === "string" &&
45
+ scope.requestId.length > 0 &&
46
+ Number.isSafeInteger(scope.revision) &&
47
+ scope.revision > 0, "oauth_owner_mismatch", "The OAuth attempt must belong to the current owner and fixed Agent/profile/target/scheme request.");
48
+ }
49
+ function endpoint(value, config) {
50
+ let url;
51
+ try {
52
+ url = new URL(value);
53
+ }
54
+ catch {
55
+ throw fail("oauth_invalid_configuration", "OAuth endpoints must be absolute HTTP(S) URLs.");
56
+ }
57
+ check(url.protocol === "https:" ||
58
+ (url.protocol === "http:" && config.allowHttp === true), "oauth_insecure_endpoint", "HTTP OAuth endpoints require explicit configuration and current endpoint authorization.");
59
+ check(!url.username && !url.password && !url.hash && url.href.length <= 8192, "oauth_invalid_configuration", "OAuth endpoint URLs cannot embed credentials or fragments.");
60
+ return url;
61
+ }
62
+ function fixedConfig(value) {
63
+ const config = copy(value);
64
+ check(isPlainRecord(config) &&
65
+ Object.keys(config).every((key) => [
66
+ "flow",
67
+ "issuer",
68
+ "clientId",
69
+ "scopes",
70
+ "tokenEndpoint",
71
+ "authorizationEndpoint",
72
+ "deviceAuthorizationEndpoint",
73
+ "jwksUri",
74
+ "clientAuthentication",
75
+ "oidc",
76
+ "allowHttp",
77
+ ].includes(key)), "oauth_invalid_configuration", "Only supported non-secret OAuth configuration fields are accepted.");
78
+ check(["authorizationCode", "clientCredentials", "device"].includes(config.flow) &&
79
+ typeof config.clientId === "string" &&
80
+ config.clientId.length > 0 &&
81
+ Buffer.byteLength(config.clientId) <= 4096 &&
82
+ !/[\0\r\n]/.test(config.clientId), "oauth_invalid_configuration", "OAuth requires its supported flow and bounded client identity.");
83
+ check(Array.isArray(config.scopes) &&
84
+ config.scopes.length <= 128 &&
85
+ config.scopes.every((scope) => typeof scope === "string" &&
86
+ /^[\x21\x23-\x5b\x5d-\x7e]+$/.test(scope) &&
87
+ scope.length <= 1024) &&
88
+ new Set(config.scopes).size === config.scopes.length, "oauth_invalid_configuration", "OAuth scopes must be distinct bounded scope tokens.");
89
+ check(config.clientAuthentication === undefined ||
90
+ ["none", "client_secret_basic", "client_secret_post"].includes(config.clientAuthentication), "oauth_invalid_configuration", "The OAuth client authentication method is unsupported.");
91
+ check((config.oidc === undefined || typeof config.oidc === "boolean") &&
92
+ (config.allowHttp === undefined || typeof config.allowHttp === "boolean"), "oauth_invalid_configuration", "OAuth feature flags must be booleans.");
93
+ const issuer = endpoint(config.issuer, config);
94
+ check(!issuer.search, "oauth_invalid_configuration", "OAuth issuers cannot contain query parameters.");
95
+ if (config.oidc)
96
+ check(config.scopes.includes("openid"), "oauth_invalid_configuration", "OIDC authorization must explicitly request the openid scope.");
97
+ for (const key of [
98
+ "tokenEndpoint",
99
+ "authorizationEndpoint",
100
+ "deviceAuthorizationEndpoint",
101
+ "jwksUri",
102
+ ])
103
+ if (config[key] !== undefined)
104
+ endpoint(config[key], config);
105
+ return config;
106
+ }
107
+ export { fixedConfig as validateOAuthConfig };
108
+ function authorize(operation, url) {
109
+ operation.assertCurrent();
110
+ authorizeCall(() => operation.scope.authorize({ type: "url", value: url, access: "oauth" }));
111
+ }
112
+ function safeError(error, signal, timeout) {
113
+ if (error && typeof error === "object" && ownErrors.has(error))
114
+ return new AgentError(error.code, error.message);
115
+ if (signal.aborted)
116
+ return new AgentError(signal.reason === timeout.reason ? "oauth_timeout" : "oauth_cancelled", signal.reason === timeout.reason
117
+ ? "The OAuth operation timed out after its native work settled."
118
+ : "The OAuth operation was cancelled after its native work settled.");
119
+ if (isAgentError(error) && error.code === "storage_quota_exceeded")
120
+ return new AgentError(error.code, "Managed storage is full; the OAuth update could not be persisted.");
121
+ if (isAgentError(error) && denied.has(error.code))
122
+ return new AgentError(error.code, "The OAuth operation is not currently authorized.");
123
+ if (error instanceof client.AuthorizationResponseError ||
124
+ error instanceof client.ResponseBodyError)
125
+ return new AgentError(error.error === "access_denied"
126
+ ? "oauth_access_denied"
127
+ : error.error === "invalid_grant"
128
+ ? "oauth_reauthentication_required"
129
+ : "oauth_provider_rejected", "The OAuth provider rejected the operation; protected response details were not exposed.");
130
+ return new AgentError("oauth_operation_failed", "The OAuth operation failed; provider responses and credentials were not exposed.");
131
+ }
132
+ async function run(provider, scope, action) {
133
+ const timeout = AbortSignal.timeout(state(provider).limits.timeoutMs), signal = AbortSignal.any([scope.signal, timeout]);
134
+ const operation = {
135
+ scope,
136
+ signal,
137
+ assertCurrent() {
138
+ signal.throwIfAborted();
139
+ current(scope);
140
+ },
141
+ };
142
+ try {
143
+ operation.assertCurrent();
144
+ const result = await action(operation);
145
+ operation.assertCurrent();
146
+ return result;
147
+ }
148
+ catch (error) {
149
+ throw safeError(error, signal, timeout);
150
+ }
151
+ }
152
+ /** The library consumes only a bounded, fully settled native response snapshot. */
153
+ function transport(provider, config, operation) {
154
+ const limits = state(provider).limits;
155
+ return async (target, options) => {
156
+ const url = endpoint(target, config).href;
157
+ authorize(operation, url);
158
+ const controller = new AbortController(), signal = AbortSignal.any([
159
+ operation.signal,
160
+ controller.signal,
161
+ ...(options.signal ? [options.signal] : []),
162
+ ]);
163
+ let reader;
164
+ let pending;
165
+ const headers = new Headers(options.headers);
166
+ let size = Buffer.byteLength(url);
167
+ for (const [name, value] of headers) {
168
+ check(![
169
+ "host",
170
+ "content-length",
171
+ "transfer-encoding",
172
+ "connection",
173
+ "proxy-authorization",
174
+ ].includes(name), "oauth_invalid_transport", "OAuth cannot replace HTTP routing or framing headers.");
175
+ size += Buffer.byteLength(name) + Buffer.byteLength(value) + 4;
176
+ }
177
+ if (typeof options.body === "string")
178
+ size += Buffer.byteLength(options.body);
179
+ else if (options.body instanceof URLSearchParams)
180
+ size += Buffer.byteLength(options.body.toString());
181
+ else if (options.body !== undefined && options.body !== null)
182
+ throw fail("oauth_invalid_transport", "OAuth request bodies must use the library's bounded form encoding.");
183
+ check(size <= limits.maxRequestBytes, "oauth_request_too_large", "The OAuth request exceeds its byte budget.");
184
+ try {
185
+ const response = await fetch(url, {
186
+ ...options,
187
+ headers,
188
+ redirect: "manual",
189
+ signal,
190
+ body: options.body,
191
+ });
192
+ reader = response.body?.getReader();
193
+ authorize(operation, url);
194
+ check(response.status < 300 || response.status >= 400, "oauth_redirect_not_allowed", "OAuth endpoint redirects are not followed.");
195
+ const declared = response.headers.get("content-length");
196
+ check(declared === null ||
197
+ !/^\d+$/.test(declared) ||
198
+ Number(declared) <= limits.maxResponseBytes, "oauth_response_too_large", "The OAuth endpoint declares a response beyond its byte budget.");
199
+ const chunks = [];
200
+ let length = 0, headerBytes = 0;
201
+ for (const [name, value] of response.headers) {
202
+ headerBytes += Buffer.byteLength(name) + Buffer.byteLength(value) + 4;
203
+ check(headerBytes <= limits.maxResponseBytes, "oauth_response_too_large", "OAuth response headers exceed their byte budget.");
204
+ }
205
+ if (reader)
206
+ while (true) {
207
+ authorize(operation, url);
208
+ pending = reader.read();
209
+ const chunk = await pending;
210
+ pending = undefined;
211
+ authorize(operation, url);
212
+ if (chunk.done)
213
+ break;
214
+ check(chunk.value.byteLength <= limits.maxResponseBytes - length, "oauth_response_too_large", "The OAuth response exceeds its actual byte budget.");
215
+ length += chunk.value.byteLength;
216
+ chunks.push(chunk.value);
217
+ }
218
+ const fixed = new Response(length ? Buffer.concat(chunks, length) : null, {
219
+ status: response.status,
220
+ statusText: response.statusText,
221
+ headers: response.headers,
222
+ });
223
+ Object.defineProperty(fixed, "url", { value: response.url });
224
+ return fixed;
225
+ }
226
+ finally {
227
+ controller.abort();
228
+ if (reader) {
229
+ await Promise.allSettled([
230
+ reader.cancel(),
231
+ reader.closed,
232
+ ...(pending ? [pending] : []),
233
+ ]);
234
+ reader.releaseLock();
235
+ }
236
+ }
237
+ };
238
+ }
239
+ async function prepare(provider, config, ref, binding, operation) {
240
+ operation.assertCurrent();
241
+ const record = await state(provider).vault.read(ref, binding);
242
+ operation.assertCurrent();
243
+ const authentication = config.clientAuthentication ??
244
+ (record.clientSecret === undefined ? "none" : "client_secret_basic");
245
+ let secret;
246
+ if (authentication !== "none") {
247
+ check(typeof record.clientSecret === "string" &&
248
+ record.clientSecret.length > 0 &&
249
+ Buffer.byteLength(record.clientSecret) <= 65536 &&
250
+ !/[\0\r\n]/.test(record.clientSecret), "oauth_credential_unavailable", "The configured OAuth client secret is unavailable.");
251
+ secret = record.clientSecret;
252
+ }
253
+ const clientAuth = authentication === "none"
254
+ ? client.None()
255
+ : authentication === "client_secret_post"
256
+ ? client.ClientSecretPost(secret)
257
+ : client.ClientSecretBasic(secret);
258
+ const metadata = { token_endpoint_auth_method: authentication };
259
+ const fetch = transport(provider, config, operation);
260
+ const enough = !!(config.tokenEndpoint &&
261
+ (config.flow !== "authorizationCode" || config.authorizationEndpoint) &&
262
+ (config.flow !== "device" || config.deviceAuthorizationEndpoint) &&
263
+ (!config.oidc || config.jwksUri));
264
+ let configuration;
265
+ if (enough)
266
+ configuration = new client.Configuration({
267
+ issuer: config.issuer,
268
+ token_endpoint: config.tokenEndpoint,
269
+ authorization_endpoint: config.authorizationEndpoint,
270
+ device_authorization_endpoint: config.deviceAuthorizationEndpoint,
271
+ jwks_uri: config.jwksUri,
272
+ }, config.clientId, metadata, clientAuth);
273
+ else
274
+ configuration = await client.discovery(new URL(config.issuer), config.clientId, metadata, clientAuth, {
275
+ algorithm: config.oidc ? "oidc" : "oauth2",
276
+ [client.customFetch]: fetch,
277
+ timeout: state(provider).limits.timeoutMs / 1000,
278
+ ...(config.allowHttp
279
+ ? { execute: [client.allowInsecureRequests] }
280
+ : {}),
281
+ });
282
+ operation.assertCurrent();
283
+ const discovered = JSON.parse(JSON.stringify(configuration.serverMetadata()));
284
+ check(discovered.issuer === config.issuer, "oauth_issuer_mismatch", "OAuth discovery returned a different issuer.");
285
+ const server = {
286
+ ...discovered,
287
+ ...(config.tokenEndpoint ? { token_endpoint: config.tokenEndpoint } : {}),
288
+ ...(config.authorizationEndpoint
289
+ ? { authorization_endpoint: config.authorizationEndpoint }
290
+ : {}),
291
+ ...(config.deviceAuthorizationEndpoint
292
+ ? { device_authorization_endpoint: config.deviceAuthorizationEndpoint }
293
+ : {}),
294
+ ...(config.jwksUri ? { jwks_uri: config.jwksUri } : {}),
295
+ };
296
+ for (const key of [
297
+ "token_endpoint",
298
+ "authorization_endpoint",
299
+ "device_authorization_endpoint",
300
+ "jwks_uri",
301
+ ])
302
+ if (server[key])
303
+ endpoint(server[key], config);
304
+ check(typeof server.token_endpoint === "string", "oauth_endpoint_unavailable", "The OAuth issuer has no configured token endpoint.");
305
+ configuration = new client.Configuration(server, config.clientId, metadata, clientAuth);
306
+ configuration[client.customFetch] = fetch;
307
+ configuration.timeout = state(provider).limits.timeoutMs / 1000;
308
+ if (config.allowHttp)
309
+ client.allowInsecureRequests(configuration);
310
+ if (config.oidc) {
311
+ check(typeof server.jwks_uri === "string", "oauth_endpoint_unavailable", "OIDC requires its issuer JWKS endpoint.");
312
+ client.enableNonRepudiationChecks(configuration);
313
+ }
314
+ return { configuration, record, hash: hash(config) };
315
+ }
316
+ function tokenRecord(config, response, old, refreshing = false) {
317
+ check(typeof response.access_token === "string" &&
318
+ response.access_token.length > 0 &&
319
+ Buffer.byteLength(response.access_token) <= 65536 &&
320
+ !/[\0\r\n]/.test(response.access_token) &&
321
+ typeof response.token_type === "string" &&
322
+ response.token_type.toLowerCase() === "bearer", "oauth_unsupported_token_type", "Only a valid provider-issued Bearer access token is supported.");
323
+ check(response.expires_in === undefined ||
324
+ (Number.isFinite(response.expires_in) &&
325
+ response.expires_in >= 0 &&
326
+ response.expires_in <= 315360000), "oauth_invalid_token_response", "The provider returned invalid token lifetime metadata.");
327
+ check(response.refresh_token === undefined ||
328
+ (typeof response.refresh_token === "string" &&
329
+ response.refresh_token.length > 0 &&
330
+ Buffer.byteLength(response.refresh_token) <= 65536), "oauth_invalid_token_response", "The provider returned an invalid refresh token.");
331
+ if (response.scope !== undefined)
332
+ check(typeof response.scope === "string" &&
333
+ config.scopes.every((scope) => response.scope.split(" ").includes(scope)), "oauth_insufficient_scope", "The provider did not grant the configured OAuth scopes.");
334
+ const previous = isPlainRecord(old.tokens) ? old.tokens : {};
335
+ let identity;
336
+ if (config.oidc) {
337
+ const helpers = response;
338
+ const claims = helpers.claims?.();
339
+ if (claims) {
340
+ check(typeof claims.iss === "string" &&
341
+ typeof claims.sub === "string" &&
342
+ claims.sub.length > 0, "oauth_invalid_identity", "The OIDC response has no validated issuer and subject identity.");
343
+ identity = {
344
+ issuer: claims.iss,
345
+ subject: claims.sub,
346
+ audience: (Array.isArray(claims.aud)
347
+ ? [...claims.aud]
348
+ : [claims.aud]).sort(),
349
+ ...(typeof claims.nonce === "string" ? { nonce: claims.nonce } : {}),
350
+ };
351
+ if (refreshing && config.flow !== "clientCredentials") {
352
+ check(isPlainRecord(previous.identity), "oauth_reauthentication_required", "The original OIDC account binding is unavailable; authorize again.");
353
+ const original = previous.identity;
354
+ check(identity.issuer === original.issuer &&
355
+ identity.subject === original.subject &&
356
+ canonicalJson(identity.audience) ===
357
+ canonicalJson(original.audience) &&
358
+ (identity.nonce === undefined || identity.nonce === original.nonce), "oauth_identity_mismatch", "Token refresh cannot replace the originally authorized OIDC account or nonce binding.");
359
+ if (identity.nonce === undefined && typeof original.nonce === "string")
360
+ identity.nonce = original.nonce;
361
+ }
362
+ }
363
+ else {
364
+ check(refreshing || config.flow === "clientCredentials", "oauth_invalid_identity", "OIDC authorization requires a validated identity token.");
365
+ if (isPlainRecord(previous.identity))
366
+ identity = previous.identity;
367
+ }
368
+ }
369
+ return {
370
+ access_token: response.access_token,
371
+ token_type: "Bearer",
372
+ expiresAt: response.expires_in === undefined
373
+ ? null
374
+ : Date.now() + response.expires_in * 1000,
375
+ ...(response.refresh_token
376
+ ? { refresh_token: response.refresh_token }
377
+ : typeof previous.refresh_token === "string"
378
+ ? { refresh_token: previous.refresh_token }
379
+ : {}),
380
+ ...(response.scope === undefined ? {} : { scope: response.scope }),
381
+ ...(identity ? { identity } : {}),
382
+ };
383
+ }
384
+ async function saveTokens(provider, config, ref, binding, old, response, operation, refreshing = false) {
385
+ operation.assertCurrent();
386
+ const tokens = tokenRecord(config, response, old, refreshing);
387
+ await state(provider).vault.update(ref, binding, {
388
+ ...old,
389
+ tokens,
390
+ oauthConfigHash: hash(config),
391
+ });
392
+ operation.assertCurrent();
393
+ return ref;
394
+ }
395
+ function usable(record, config) {
396
+ const tokens = isPlainRecord(record.tokens) ? record.tokens : null;
397
+ if (!tokens ||
398
+ record.oauthConfigHash !== hash(config) ||
399
+ tokens.token_type !== "Bearer" ||
400
+ typeof tokens.access_token !== "string")
401
+ return null;
402
+ return tokens.expiresAt === null ||
403
+ (typeof tokens.expiresAt === "number" &&
404
+ tokens.expiresAt > Date.now() + 5000)
405
+ ? tokens.access_token
406
+ : null;
407
+ }
408
+ /** Trusted credential backend only. No token-bearing result is a maintenance/public DTO. */
409
+ export class OAuthProvider {
410
+ constructor(vault, options = {}) {
411
+ const limits = {
412
+ timeoutMs: options.timeoutMs ?? 30000,
413
+ maxRequestBytes: options.maxRequestBytes ?? 256 * 1024,
414
+ maxResponseBytes: options.maxResponseBytes ?? 1024 * 1024,
415
+ };
416
+ check(Object.values(limits).every((value) => Number.isSafeInteger(value) && value > 0 && value <= 2_147_483_647), "oauth_invalid_limits", "OAuth operation budgets must be positive bounded integers.");
417
+ providers.set(this, { vault, limits, refreshing: new Map() });
418
+ }
419
+ async prepareAuth(value, ref, binding, scope) {
420
+ const config = fixedConfig(value), fixedBinding = copy(binding);
421
+ return run(this, scope, async (operation) => {
422
+ const record = await state(this).vault.read(ref, fixedBinding);
423
+ operation.assertCurrent();
424
+ if (usable(record, config))
425
+ return ref;
426
+ if (config.flow !== "clientCredentials") {
427
+ await this.getAccessToken(config, ref, fixedBinding, scope);
428
+ return ref;
429
+ }
430
+ const prepared = await prepare(this, config, ref, fixedBinding, operation);
431
+ const tokens = await client.clientCredentialsGrant(prepared.configuration, { scope: config.scopes.join(" ") });
432
+ return saveTokens(this, config, ref, fixedBinding, prepared.record, tokens, operation);
433
+ });
434
+ }
435
+ async getAccessToken(value, ref, binding, scope) {
436
+ const config = fixedConfig(value), fixedBinding = copy(binding);
437
+ return run(this, scope, async (operation) => {
438
+ const record = await state(this).vault.read(ref, fixedBinding);
439
+ operation.assertCurrent();
440
+ const ready = usable(record, config);
441
+ if (ready)
442
+ return ready;
443
+ check(isPlainRecord(record.tokens) && record.oauthConfigHash === hash(config), "oauth_authentication_required", "Complete the configured OAuth authorization before using this credential.");
444
+ const key = hash({ ref, binding: fixedBinding, config });
445
+ let refreshing = state(this).refreshing.get(key);
446
+ if (!refreshing) {
447
+ refreshing = (async () => {
448
+ const prepared = await prepare(this, config, ref, fixedBinding, operation), latest = usable(prepared.record, config);
449
+ if (latest)
450
+ return latest;
451
+ const old = isPlainRecord(prepared.record.tokens)
452
+ ? prepared.record.tokens
453
+ : {};
454
+ let tokens;
455
+ if (typeof old.refresh_token === "string")
456
+ tokens = await client.refreshTokenGrant(prepared.configuration, old.refresh_token);
457
+ else {
458
+ check(config.flow === "clientCredentials", "oauth_reauthentication_required", "This OAuth credential requires the user to authorize again.");
459
+ tokens = await client.clientCredentialsGrant(prepared.configuration, { scope: config.scopes.join(" ") });
460
+ }
461
+ await saveTokens(this, config, ref, fixedBinding, prepared.record, tokens, operation, true);
462
+ return tokens.access_token;
463
+ })();
464
+ state(this).refreshing.set(key, refreshing);
465
+ void refreshing.then(() => {
466
+ if (state(this).refreshing.get(key) === refreshing)
467
+ state(this).refreshing.delete(key);
468
+ }, () => {
469
+ if (state(this).refreshing.get(key) === refreshing)
470
+ state(this).refreshing.delete(key);
471
+ });
472
+ }
473
+ const token = await refreshing;
474
+ operation.assertCurrent();
475
+ return token;
476
+ });
477
+ }
478
+ }
479
+ export class OAuthSessionService {
480
+ #provider;
481
+ #root;
482
+ #reserve;
483
+ constructor(provider, options) {
484
+ this.#provider = provider;
485
+ this.#root = options.root;
486
+ this.#reserve = options.reserve;
487
+ }
488
+ #parts(state) {
489
+ return ["oauth", `${hash(state)}.json`];
490
+ }
491
+ async #exclusive(state, action) {
492
+ const key = this.#root + ":" + hash(state);
493
+ check(!sessionsBusy.has(key), "oauth_session_busy", "This OAuth attempt is already being processed.");
494
+ sessionsBusy.add(key);
495
+ try {
496
+ return await action();
497
+ }
498
+ finally {
499
+ sessionsBusy.delete(key);
500
+ }
501
+ }
502
+ #matches(attempt, config, ref, binding, scope, scheme, revision) {
503
+ check(attempt.requestId === scope.requestId &&
504
+ attempt.revision === scope.revision &&
505
+ attempt.candidateRevision === revision &&
506
+ attempt.schemeId === scheme &&
507
+ attempt.credentialRef === ref &&
508
+ attempt.configHash === hash(config) &&
509
+ canonicalJson(attempt.binding) === canonicalJson(binding), "oauth_session_mismatch", "The OAuth attempt does not belong to this exact pending candidate and credential binding.");
510
+ check(attempt.expiresAt > Date.now(), "oauth_session_expired", "The OAuth authorization attempt expired.");
511
+ }
512
+ async start(value, ref, binding, input, scope) {
513
+ interactiveIdentity(binding, input.schemeId, scope);
514
+ const config = fixedConfig(value), fixedBinding = copy(binding), launchBinding = copy(input);
515
+ check(config.flow !== "clientCredentials", "oauth_interactive_flow_required", "Client Credentials must use explicit prepareAuth instead of an interactive authorization launch.");
516
+ check(typeof launchBinding.state === "string" &&
517
+ launchBinding.state.length > 0 &&
518
+ launchBinding.state.length <= 4096 &&
519
+ typeof launchBinding.schemeId === "string" &&
520
+ launchBinding.schemeId.length > 0, "oauth_invalid_binding", "An OAuth attempt needs its trusted state and source scheme.");
521
+ let callback;
522
+ try {
523
+ callback = new URL(launchBinding.callbackUrl);
524
+ }
525
+ catch {
526
+ throw fail("oauth_invalid_binding", "The trusted OAuth callback must be an absolute URL.");
527
+ }
528
+ check(callback.protocol === "https:" ||
529
+ (callback.protocol === "http:" && config.allowHttp === true), "oauth_invalid_binding", "The OAuth callback must use its explicitly configured HTTP(S) transport.");
530
+ check(!callback.search &&
531
+ !callback.hash &&
532
+ !callback.username &&
533
+ !callback.password, "oauth_invalid_binding", "The trusted OAuth callback cannot contain query, fragments or credentials.");
534
+ return this.#exclusive(launchBinding.state, () => run(this.#provider, scope, async (operation) => {
535
+ const existing = (await privateMaintenanceRead(this.#root, this.#parts(launchBinding.state), 1024 * 1024));
536
+ operation.assertCurrent();
537
+ if (existing) {
538
+ this.#matches(existing, config, ref, fixedBinding, scope, launchBinding.schemeId, launchBinding.candidateRevision);
539
+ check(existing.callbackUrl === callback.href &&
540
+ existing.phase === "pending", "oauth_session_consumed", "This OAuth authorization attempt has already been consumed.");
541
+ return copy(existing.launch);
542
+ }
543
+ const prepared = await prepare(this.#provider, config, ref, fixedBinding, operation), metadata = prepared.configuration.serverMetadata();
544
+ const requireIssuer = config.flow === "authorizationCode" &&
545
+ metadata.authorization_response_iss_parameter_supported === true;
546
+ let launch, verifier, nonce, device;
547
+ if (config.flow === "authorizationCode") {
548
+ check(typeof metadata.authorization_endpoint === "string", "oauth_endpoint_unavailable", "The issuer has no authorization endpoint.");
549
+ authorize(operation, metadata.authorization_endpoint);
550
+ verifier = client.randomPKCECodeVerifier();
551
+ const challenge = await client.calculatePKCECodeChallenge(verifier);
552
+ operation.assertCurrent();
553
+ if (config.oidc)
554
+ nonce = client.randomNonce();
555
+ const url = client.buildAuthorizationUrl(prepared.configuration, {
556
+ redirect_uri: callback.href,
557
+ scope: config.scopes.join(" "),
558
+ state: launchBinding.state,
559
+ code_challenge: challenge,
560
+ code_challenge_method: "S256",
561
+ ...(nonce ? { nonce } : {}),
562
+ });
563
+ launch = {
564
+ authorizationUrl: url.href,
565
+ issuer: metadata.issuer,
566
+ requireIssuer,
567
+ };
568
+ }
569
+ else {
570
+ const response = await client.initiateDeviceAuthorization(prepared.configuration, { scope: config.scopes.join(" ") });
571
+ operation.assertCurrent();
572
+ endpoint(response.verification_uri, config);
573
+ if (response.verification_uri_complete)
574
+ endpoint(response.verification_uri_complete, config);
575
+ authorize(operation, response.verification_uri);
576
+ if (response.verification_uri_complete)
577
+ authorize(operation, response.verification_uri_complete);
578
+ device = copy(response);
579
+ launch = {
580
+ verificationUri: response.verification_uri_complete ?? response.verification_uri,
581
+ userCode: response.user_code,
582
+ issuer: metadata.issuer,
583
+ requireIssuer: false,
584
+ };
585
+ }
586
+ const expiresAt = Date.now() +
587
+ Math.min(600000, device && typeof device.expires_in === "number"
588
+ ? device.expires_in * 1000
589
+ : 600000);
590
+ const attempt = {
591
+ state: launchBinding.state,
592
+ requestId: scope.requestId,
593
+ revision: scope.revision,
594
+ candidateRevision: launchBinding.candidateRevision,
595
+ schemeId: launchBinding.schemeId,
596
+ callbackUrl: callback.href,
597
+ credentialRef: ref,
598
+ binding: fixedBinding,
599
+ configHash: prepared.hash,
600
+ issuer: metadata.issuer,
601
+ requireIssuer,
602
+ expiresAt,
603
+ phase: "pending",
604
+ launch: copy(launch),
605
+ ...(verifier ? { verifier } : {}),
606
+ ...(nonce ? { nonce } : {}),
607
+ ...(device ? { device } : {}),
608
+ };
609
+ operation.assertCurrent();
610
+ await privateMaintenanceWrite(this.#root, this.#parts(launchBinding.state), attempt, true, this.#reserve);
611
+ operation.assertCurrent();
612
+ return launch;
613
+ }));
614
+ }
615
+ async complete(value, ref, binding, input, scope) {
616
+ interactiveIdentity(binding, input.schemeId, scope);
617
+ const config = fixedConfig(value), fixedBinding = copy(binding), completion = copy(input);
618
+ check(typeof completion.callback?.state === "string" &&
619
+ completion.callback.state.length > 0 &&
620
+ completion.callback.state.length <= 4096, "oauth_invalid_binding", "OAuth completion needs its original state.");
621
+ return this.#exclusive(completion.callback.state, () => run(this.#provider, scope, async (operation) => {
622
+ const attempt = (await privateMaintenanceRead(this.#root, this.#parts(completion.callback.state), 1024 * 1024));
623
+ operation.assertCurrent();
624
+ check(attempt, "oauth_session_unavailable", "The OAuth attempt is unavailable; begin a new authorization.");
625
+ this.#matches(attempt, config, ref, fixedBinding, scope, completion.schemeId, completion.candidateRevision);
626
+ check(attempt.phase === "pending", "oauth_session_consumed", "The authorization code has already entered an exchange and cannot be replayed.");
627
+ check(!completion.callback.error, "oauth_access_denied", "The OAuth authorization was denied by the provider.");
628
+ check((!attempt.requireIssuer ||
629
+ completion.callback.issuer !== undefined) &&
630
+ (completion.callback.issuer === undefined ||
631
+ completion.callback.issuer === attempt.issuer), "oauth_issuer_mismatch", "The authorization response issuer does not match the original attempt.");
632
+ const prepared = await prepare(this.#provider, config, ref, fixedBinding, operation);
633
+ check(prepared.configuration.serverMetadata().issuer === attempt.issuer, "oauth_issuer_mismatch", "The configured OAuth issuer changed during authorization.");
634
+ attempt.phase = "exchanging";
635
+ await privateMaintenanceWrite(this.#root, this.#parts(attempt.state), attempt, false, this.#reserve);
636
+ operation.assertCurrent();
637
+ let received = false;
638
+ try {
639
+ let response;
640
+ if (config.flow === "authorizationCode") {
641
+ check(typeof completion.callback.code === "string" &&
642
+ completion.callback.code.length > 0 &&
643
+ completion.callback.code.length <= 65536 &&
644
+ typeof attempt.verifier === "string", "oauth_invalid_callback", "The authorization response has no valid code or PKCE binding.");
645
+ check(!config.oidc ||
646
+ (typeof attempt.nonce === "string" && attempt.nonce.length > 0), "oauth_invalid_callback", "The OIDC attempt has no original nonce binding.");
647
+ const callback = new URL(attempt.callbackUrl);
648
+ callback.searchParams.set("state", attempt.state);
649
+ callback.searchParams.set("code", completion.callback.code);
650
+ if (completion.callback.issuer)
651
+ callback.searchParams.set("iss", completion.callback.issuer);
652
+ response = await client.authorizationCodeGrant(prepared.configuration, callback, {
653
+ expectedState: attempt.state,
654
+ pkceCodeVerifier: attempt.verifier,
655
+ ...(config.oidc
656
+ ? { expectedNonce: attempt.nonce, idTokenExpected: true }
657
+ : {}),
658
+ });
659
+ }
660
+ else {
661
+ check(config.flow === "device" && isPlainRecord(attempt.device), "oauth_invalid_callback", "This OAuth attempt has no device authorization state.");
662
+ response = await client.pollDeviceAuthorizationGrant(prepared.configuration, attempt.device, {}, { signal: operation.signal });
663
+ }
664
+ received = true;
665
+ await saveTokens(this.#provider, config, ref, fixedBinding, prepared.record, response, operation);
666
+ attempt.phase = "completed";
667
+ delete attempt.verifier;
668
+ delete attempt.nonce;
669
+ delete attempt.device;
670
+ await privateMaintenanceWrite(this.#root, this.#parts(attempt.state), attempt, false, this.#reserve);
671
+ operation.assertCurrent();
672
+ return ref;
673
+ }
674
+ catch (error) {
675
+ if (config.flow === "device" &&
676
+ !received &&
677
+ operation.signal.aborted) {
678
+ attempt.phase = "pending";
679
+ await privateMaintenanceWrite(this.#root, this.#parts(attempt.state), attempt, false, this.#reserve);
680
+ }
681
+ throw error;
682
+ }
683
+ }));
684
+ }
685
+ }
686
+ //# sourceMappingURL=oauth.js.map