gemi 0.113.0 → 0.114.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.
- package/dist/ai/index.js +32 -32
- package/dist/ai/index.js.map +3 -5
- package/dist/app/App.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bin/gemi.js +8 -1
- package/dist/bin/gemi.js.map +3 -3
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/chunk-0n9vs1ad.js +14 -0
- package/dist/{chunk-cqnfp0n9.js.map → chunk-0n9vs1ad.js.map} +4 -4
- package/dist/{chunk-68s1f5d5.js → chunk-1f9sqht5.js} +2 -2
- package/dist/{chunk-68s1f5d5.js.map → chunk-1f9sqht5.js.map} +1 -1
- package/dist/{chunk-qt8nvpqp.js → chunk-1p0dazvk.js} +2 -2
- package/dist/{chunk-qt8nvpqp.js.map → chunk-1p0dazvk.js.map} +1 -1
- package/dist/{chunk-3f1kq32g.js → chunk-2rphhsr7.js} +2 -2
- package/dist/{chunk-3f1kq32g.js.map → chunk-2rphhsr7.js.map} +1 -1
- package/dist/{chunk-qx87cdfg.js → chunk-2z1981d0.js} +2 -2
- package/dist/{chunk-qx87cdfg.js.map → chunk-2z1981d0.js.map} +1 -1
- package/dist/{chunk-zng3qexn.js → chunk-329ggbcw.js} +2 -2
- package/dist/{chunk-zng3qexn.js.map → chunk-329ggbcw.js.map} +1 -1
- package/dist/{chunk-v4gwmhtf.js → chunk-37qk5dh8.js} +2 -2
- package/dist/{chunk-v4gwmhtf.js.map → chunk-37qk5dh8.js.map} +1 -1
- package/dist/{chunk-7jnpnjth.js → chunk-3ma9m432.js} +2 -2
- package/dist/{chunk-7jnpnjth.js.map → chunk-3ma9m432.js.map} +1 -1
- package/dist/{chunk-fnkjmq94.js → chunk-4szjp84e.js} +2 -2
- package/dist/{chunk-fnkjmq94.js.map → chunk-4szjp84e.js.map} +1 -1
- package/dist/{chunk-fr0arqdj.js → chunk-56fgk5rq.js} +2 -2
- package/dist/{chunk-fr0arqdj.js.map → chunk-56fgk5rq.js.map} +1 -1
- package/dist/{chunk-y6v0x869.js → chunk-583vxa2v.js} +2 -2
- package/dist/{chunk-y6v0x869.js.map → chunk-583vxa2v.js.map} +1 -1
- package/dist/{chunk-vqa3agzw.js → chunk-5j76r5q8.js} +3 -3
- package/dist/{chunk-vqa3agzw.js.map → chunk-5j76r5q8.js.map} +1 -1
- package/dist/chunk-60nyk1w8.js +10 -0
- package/dist/chunk-60nyk1w8.js.map +38 -0
- package/dist/{chunk-vwprq300.js → chunk-6h9j3f1x.js} +2 -2
- package/dist/{chunk-vwprq300.js.map → chunk-6h9j3f1x.js.map} +1 -1
- package/dist/{chunk-r7b12dmm.js → chunk-75wk4jxd.js} +2 -2
- package/dist/{chunk-r7b12dmm.js.map → chunk-75wk4jxd.js.map} +1 -1
- package/dist/{chunk-de03dewf.js → chunk-7fwp7vwh.js} +2 -2
- package/dist/{chunk-de03dewf.js.map → chunk-7fwp7vwh.js.map} +1 -1
- package/dist/{chunk-9vsj0ksk.js → chunk-7rmjr8p7.js} +3 -3
- package/dist/{chunk-9vsj0ksk.js.map → chunk-7rmjr8p7.js.map} +1 -1
- package/dist/{chunk-atmzm0z3.js → chunk-7v8sgqen.js} +2 -2
- package/dist/{chunk-atmzm0z3.js.map → chunk-7v8sgqen.js.map} +1 -1
- package/dist/{chunk-4t1pbt9p.js → chunk-8c2fs0n0.js} +3 -3
- package/dist/{chunk-4t1pbt9p.js.map → chunk-8c2fs0n0.js.map} +1 -1
- package/dist/{chunk-vzf5pbx3.js → chunk-8h7dh2h2.js} +2 -2
- package/dist/{chunk-vzf5pbx3.js.map → chunk-8h7dh2h2.js.map} +1 -1
- package/dist/{chunk-c7mp2kyp.js → chunk-8k8534kg.js} +2 -2
- package/dist/{chunk-c7mp2kyp.js.map → chunk-8k8534kg.js.map} +1 -1
- package/dist/{chunk-g8kx549d.js → chunk-8rt4wx8z.js} +3 -3
- package/dist/{chunk-g8kx549d.js.map → chunk-8rt4wx8z.js.map} +1 -1
- package/dist/{chunk-bq5nqqeq.js → chunk-a5sbgffr.js} +1 -1
- package/dist/{chunk-szr1k584.js → chunk-ap5gek56.js} +2 -2
- package/dist/{chunk-szr1k584.js.map → chunk-ap5gek56.js.map} +1 -1
- package/dist/{chunk-4tp2cr02.js → chunk-awp3n119.js} +2 -2
- package/dist/{chunk-4tp2cr02.js.map → chunk-awp3n119.js.map} +1 -1
- package/dist/{chunk-5q4a7yqf.js → chunk-cna105t6.js} +2 -2
- package/dist/{chunk-5q4a7yqf.js.map → chunk-cna105t6.js.map} +1 -1
- package/dist/{chunk-rg4hhxj3.js → chunk-d4m4amy4.js} +2 -2
- package/dist/{chunk-rg4hhxj3.js.map → chunk-d4m4amy4.js.map} +1 -1
- package/dist/{chunk-8mbyyh8j.js → chunk-e6fp6dxx.js} +2 -2
- package/dist/{chunk-8mbyyh8j.js.map → chunk-e6fp6dxx.js.map} +1 -1
- package/dist/{chunk-1se4t9rg.js → chunk-e7axa0d5.js} +3 -3
- package/dist/{chunk-1se4t9rg.js.map → chunk-e7axa0d5.js.map} +1 -1
- package/dist/{chunk-9tpx9ag3.js → chunk-erxv1jz7.js} +2 -2
- package/dist/{chunk-9tpx9ag3.js.map → chunk-erxv1jz7.js.map} +1 -1
- package/dist/chunk-fakvf9wb.js +5 -0
- package/dist/{chunk-fsfbyg5e.js.map → chunk-fakvf9wb.js.map} +1 -1
- package/dist/{chunk-nysqgzp1.js → chunk-fv9mr1t4.js} +2 -2
- package/dist/{chunk-nysqgzp1.js.map → chunk-fv9mr1t4.js.map} +1 -1
- package/dist/{chunk-p3zmc8k8.js → chunk-gdmsn3f5.js} +2 -2
- package/dist/{chunk-p3zmc8k8.js.map → chunk-gdmsn3f5.js.map} +1 -1
- package/dist/{chunk-y6frz1vm.js → chunk-gv91vjeb.js} +1 -1
- package/dist/{chunk-5x0aacrn.js → chunk-h2r2rdhj.js} +2 -2
- package/dist/{chunk-5x0aacrn.js.map → chunk-h2r2rdhj.js.map} +1 -1
- package/dist/{chunk-1p85fdrk.js → chunk-h4pazcgg.js} +2 -2
- package/dist/{chunk-1p85fdrk.js.map → chunk-h4pazcgg.js.map} +1 -1
- package/dist/{chunk-mk0rtgd1.js → chunk-hrvzchxd.js} +2 -2
- package/dist/{chunk-mk0rtgd1.js.map → chunk-hrvzchxd.js.map} +1 -1
- package/dist/{chunk-w45agtch.js → chunk-hytt9qyj.js} +2 -2
- package/dist/{chunk-w45agtch.js.map → chunk-hytt9qyj.js.map} +1 -1
- package/dist/{chunk-5nqkwa2w.js → chunk-hz6yzzbz.js} +1 -1
- package/dist/{chunk-z5hrymvn.js → chunk-j3nr4cg0.js} +3 -3
- package/dist/{chunk-z5hrymvn.js.map → chunk-j3nr4cg0.js.map} +1 -1
- package/dist/{chunk-dbwhgyg3.js → chunk-jk97wv0q.js} +2 -2
- package/dist/{chunk-dbwhgyg3.js.map → chunk-jk97wv0q.js.map} +1 -1
- package/dist/{chunk-x5sert1k.js → chunk-jv4g8grc.js} +2 -2
- package/dist/{chunk-x5sert1k.js.map → chunk-jv4g8grc.js.map} +1 -1
- package/dist/{chunk-yyzexrnb.js → chunk-jyrsd1dn.js} +2 -2
- package/dist/{chunk-yyzexrnb.js.map → chunk-jyrsd1dn.js.map} +1 -1
- package/dist/{chunk-y596ghpz.js → chunk-jzp0fs6h.js} +2 -2
- package/dist/{chunk-y596ghpz.js.map → chunk-jzp0fs6h.js.map} +1 -1
- package/dist/{chunk-kz4yp5n7.js → chunk-kcx468qv.js} +2 -2
- package/dist/{chunk-kz4yp5n7.js.map → chunk-kcx468qv.js.map} +1 -1
- package/dist/{chunk-zyer1g7k.js → chunk-kg1nbxvm.js} +4 -4
- package/dist/{chunk-zyer1g7k.js.map → chunk-kg1nbxvm.js.map} +1 -1
- package/dist/{chunk-qpttgn4k.js → chunk-kqb4s1r0.js} +3 -3
- package/dist/{chunk-qpttgn4k.js.map → chunk-kqb4s1r0.js.map} +1 -1
- package/dist/{chunk-rh2fad7n.js → chunk-m17ktssc.js} +1 -1
- package/dist/{chunk-k2fh4r0p.js → chunk-m2yfvwrn.js} +2 -2
- package/dist/{chunk-k2fh4r0p.js.map → chunk-m2yfvwrn.js.map} +1 -1
- package/dist/{chunk-wr3e4sez.js → chunk-mqcy5vja.js} +2 -2
- package/dist/{chunk-wr3e4sez.js.map → chunk-mqcy5vja.js.map} +1 -1
- package/dist/{chunk-f1y8eggf.js → chunk-n672d4g8.js} +2 -2
- package/dist/{chunk-f1y8eggf.js.map → chunk-n672d4g8.js.map} +1 -1
- package/dist/{chunk-xqwdn9kb.js → chunk-nek1gzz2.js} +3 -3
- package/dist/{chunk-xqwdn9kb.js.map → chunk-nek1gzz2.js.map} +1 -1
- package/dist/{chunk-01qd6xx3.js → chunk-pmywkp1w.js} +3 -3
- package/dist/{chunk-01qd6xx3.js.map → chunk-pmywkp1w.js.map} +1 -1
- package/dist/chunk-q95k1ymq.js +4 -0
- package/dist/{chunk-kp7k4s5c.js.map → chunk-q95k1ymq.js.map} +3 -3
- package/dist/{chunk-vdwagp7y.js → chunk-r4namj39.js} +2 -2
- package/dist/{chunk-vdwagp7y.js.map → chunk-r4namj39.js.map} +1 -1
- package/dist/{chunk-571rvxe6.js → chunk-rrqr1dwq.js} +2 -2
- package/dist/{chunk-571rvxe6.js.map → chunk-rrqr1dwq.js.map} +1 -1
- package/dist/{chunk-sr18y2ck.js → chunk-tp3mzj4v.js} +2 -2
- package/dist/{chunk-sr18y2ck.js.map → chunk-tp3mzj4v.js.map} +1 -1
- package/dist/{chunk-6wymbbes.js → chunk-ty4aj41k.js} +3 -3
- package/dist/{chunk-6wymbbes.js.map → chunk-ty4aj41k.js.map} +1 -1
- package/dist/chunk-v9na3dny.js +46 -0
- package/dist/{chunk-6g20zec2.js.map → chunk-v9na3dny.js.map} +6 -6
- package/dist/{chunk-d04r0hdf.js → chunk-w2fpr99k.js} +2 -2
- package/dist/{chunk-d04r0hdf.js.map → chunk-w2fpr99k.js.map} +1 -1
- package/dist/{chunk-vc9phr57.js → chunk-wwmdqhzy.js} +2 -2
- package/dist/{chunk-vc9phr57.js.map → chunk-wwmdqhzy.js.map} +1 -1
- package/dist/chunk-wysm6qte.js +5 -0
- package/dist/chunk-wysm6qte.js.map +12 -0
- package/dist/{chunk-mepaedy5.js → chunk-x157wrgy.js} +2 -2
- package/dist/{chunk-mepaedy5.js.map → chunk-x157wrgy.js.map} +1 -1
- package/dist/{chunk-nksn6xcd.js → chunk-xrh6k13s.js} +2 -2
- package/dist/{chunk-nksn6xcd.js.map → chunk-xrh6k13s.js.map} +1 -1
- package/dist/{chunk-g8sc6scv.js → chunk-y0wx6w80.js} +2 -2
- package/dist/{chunk-g8sc6scv.js.map → chunk-y0wx6w80.js.map} +1 -1
- package/dist/{chunk-kexsfyjj.js → chunk-yp5979we.js} +2 -2
- package/dist/{chunk-kexsfyjj.js.map → chunk-yp5979we.js.map} +1 -1
- package/dist/{chunk-essqp1ek.js → chunk-z32xfe8c.js} +2 -2
- package/dist/{chunk-essqp1ek.js.map → chunk-z32xfe8c.js.map} +1 -1
- package/dist/{chunk-x5yq097b.js → chunk-zgn0p8qr.js} +3 -3
- package/dist/{chunk-x5yq097b.js.map → chunk-zgn0p8qr.js.map} +1 -1
- package/dist/{chunk-agw3anaf.js → chunk-zns7xcz9.js} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/HttpRequest.d.ts +31 -0
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/McpRouter.d.ts +54 -1
- package/dist/http/McpRouter.d.ts.map +1 -1
- package/dist/http/RateLimitMiddleware.d.ts +4 -1
- package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
- package/dist/http/index.d.ts +1 -0
- package/dist/http/index.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/http/modelOriginated.d.ts +36 -2
- package/dist/http/modelOriginated.d.ts.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/Kernel.d.ts +3 -0
- package/dist/kernel/Kernel.d.ts.map +1 -1
- package/dist/kernel/index.js +3 -3
- package/dist/kernel/index.js.map +3 -3
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.d.ts +6 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +44 -9
- package/dist/services/index.js.map +6 -3
- package/dist/services/mcp/McpRegistry.d.ts +190 -29
- package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
- package/dist/services/mcp/http/McpHttpServer.d.ts +153 -0
- package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -0
- package/dist/services/mcp/http/callers.d.ts +131 -0
- package/dist/services/mcp/http/callers.d.ts.map +1 -0
- package/dist/services/mcp/http/limits.d.ts +11 -0
- package/dist/services/mcp/http/limits.d.ts.map +1 -0
- package/dist/services/mcp/http/oauth/McpOAuthServer.d.ts +150 -0
- package/dist/services/mcp/http/oauth/McpOAuthServer.d.ts.map +1 -0
- package/dist/services/mcp/http/oauth/consentPage.d.ts +14 -0
- package/dist/services/mcp/http/oauth/consentPage.d.ts.map +1 -0
- package/dist/services/mcp/http/oauth/store.d.ts +98 -0
- package/dist/services/mcp/http/oauth/store.d.ts.map +1 -0
- package/dist/services/mcp/http/protocol.d.ts +95 -0
- package/dist/services/mcp/http/protocol.d.ts.map +1 -0
- package/dist/services/mcp/http/signedState.d.ts +25 -0
- package/dist/services/mcp/http/signedState.d.ts.map +1 -0
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ApiRouteDispatcher.d.ts +29 -0
- package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/RouteServiceProvider.d.ts +6 -0
- package/dist/services/router/RouteServiceProvider.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +16 -0
- package/dist/services/router/config.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3z9vhjd7.js +0 -5
- package/dist/chunk-3z9vhjd7.js.map +0 -10
- package/dist/chunk-5zzhypmt.js +0 -5
- package/dist/chunk-5zzhypmt.js.map +0 -33
- package/dist/chunk-6g20zec2.js +0 -46
- package/dist/chunk-cqnfp0n9.js +0 -14
- package/dist/chunk-fsfbyg5e.js +0 -5
- package/dist/chunk-kp7k4s5c.js +0 -4
- /package/dist/{chunk-bq5nqqeq.js.map → chunk-a5sbgffr.js.map} +0 -0
- /package/dist/{chunk-y6frz1vm.js.map → chunk-gv91vjeb.js.map} +0 -0
- /package/dist/{chunk-5nqkwa2w.js.map → chunk-hz6yzzbz.js.map} +0 -0
- /package/dist/{chunk-rh2fad7n.js.map → chunk-m17ktssc.js.map} +0 -0
- /package/dist/{chunk-agw3anaf.js.map → chunk-zns7xcz9.js.map} +0 -0
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import { constants } from \"node:os\";\nimport type { ShutdownReport } from \"../foundation/Application\";\nimport type { Instrumentation } from \"./types\";\n\n// On `globalThis` under a registry symbol rather than in a module variable, so\n// the flag an app's health route reads is the one the server set even when two\n// copies of this module are loaded — the built CLI bundles its own gemi (see\n// `app/App.ts`), and `bun --hot` re-evaluates every module on a reload.\nconst STATE = Symbol.for(\"gemi.server.shutdown\");\n\ntype ShutdownState = { shuttingDown: boolean; drained: boolean };\n\nfunction state(): ShutdownState {\n const global = globalThis as { [STATE]?: ShutdownState };\n global[STATE] ??= { shuttingDown: false, drained: false };\n return global[STATE];\n}\n\n/**\n * True from the moment this server process has been told to stop — before it\n * stops accepting connections — until it exits.\n *\n * gemi has no health endpoint of its own, so taking an instance out of a load\n * balancer is the app's health route's job: answer it with a `503` while this\n * is true, and the platform's probe pulls the instance while the in-flight\n * requests are still draining. Every response sent in that window also carries\n * `Connection: close`, so a client that honours it opens its next request on a\n * new connection — one the load balancer can route elsewhere — instead of\n * reusing this one.\n */\nexport function isShuttingDown(): boolean {\n return state().shuttingDown;\n}\n\nexport function markShuttingDown() {\n state().shuttingDown = true;\n}\n\n/**\n * The request drain is over and the providers' `shutdown()` may be running:\n * from here on a request must not reach the app. See `serveForShutdown`.\n */\nexport function markDrained() {\n state().drained = true;\n}\n\n/** Test seam: a fresh process starts false, and so should each test. */\nexport function resetShuttingDown() {\n state().shuttingDown = false;\n state().drained = false;\n}\n\nexport type ShutdownSettings = {\n /**\n * From the signal to the end of the request drain, in milliseconds — the\n * delay below included. Requests still in flight when it runs out are\n * abandoned. `GEMI_SHUTDOWN_TIMEOUT`, in seconds; default 20. `0` means\n * \"close the listener and do not wait\": a shutdown with nothing in flight is\n * still a clean one.\n */\n timeoutMs: number;\n /**\n * How long to keep accepting new requests after `isShuttingDown()` turns\n * true, in milliseconds, so a health probe can see the `503` and the load\n * balancer stop routing here before the listener closes.\n * `GEMI_SHUTDOWN_DELAY`, in seconds; default 0.\n */\n delayMs: number;\n /**\n * The shared deadline for every provider's `shutdown()`, in milliseconds,\n * after the drain. `GEMI_SHUTDOWN_PROVIDER_TIMEOUT`, in seconds; default 5.\n * `0` skips the hooks — deliberately, so it is not reported as a failure.\n */\n providerTimeoutMs: number;\n};\n\n/**\n * 20s to drain plus 5s for providers is 25s: under the 30s that Kubernetes,\n * Azure Container Apps and ECS give by default between `SIGTERM` and `SIGKILL`,\n * with 5s left for the `gemi start` relay, the process exit and clock skew\n * between the platform's timer and ours. A platform with a shorter window\n * (Cloud Run's 10s, Fly's 5s) needs these lowered, not the other way round —\n * a drain that outlives the grace period ends in the same `SIGKILL` as no drain.\n *\n * The delay defaults to 0 because it only helps where a probe is watching, and\n * otherwise every shutdown would pay it for nothing.\n */\nexport function shutdownSettings(\n env: Record<string, string | undefined> = process.env,\n): ShutdownSettings {\n const settings = {\n timeoutMs: seconds(env.GEMI_SHUTDOWN_TIMEOUT, 20),\n delayMs: seconds(env.GEMI_SHUTDOWN_DELAY, 0),\n providerTimeoutMs: seconds(env.GEMI_SHUTDOWN_PROVIDER_TIMEOUT, 5),\n };\n // Warned, not clamped: the delay is sized to a probe, the timeout to the\n // platform's grace period, and which one is wrong only the operator knows.\n // Left alone, every shutdown spends the whole timeout in the delay and then\n // abandons whatever is in flight without draining it.\n if (settings.delayMs > 0 && settings.delayMs >= settings.timeoutMs) {\n console.warn(\n `[gemi] GEMI_SHUTDOWN_DELAY (${settings.delayMs / 1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${settings.timeoutMs / 1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`,\n );\n }\n return settings;\n}\n\nfunction seconds(value: string | undefined, fallback: number): number {\n const parsed = value === undefined || value.trim() === \"\" ? NaN : Number(value);\n if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1000;\n if (value !== undefined) {\n console.warn(`[gemi] Ignoring shutdown setting \"${value}\": expected a number of seconds.`);\n }\n return fallback * 1000;\n}\n\n/** The part of `Bun.Server` a drain needs. */\nexport type Stoppable = {\n stop(closeActiveConnections?: boolean): Promise<void>;\n readonly pendingRequests: number;\n};\n\n/**\n * The shutdown sequence, in its order:\n *\n * 1. `isShuttingDown()` turns true — first, so the health route answers `503`\n * and responses carry `Connection: close` while the listener is still open.\n * 2. After `delayMs`, the listener closes (`server.stop()` without force):\n * new connections are refused, while every request in flight — a streamed\n * response included, to its last chunk — runs to completion.\n * 3. That completion is awaited until `timeoutMs` from the start.\n * 4. From here a request is refused with a `503` before it reaches the app\n * (`serveForShutdown`), and every provider's `shutdown()` runs, reverse\n * order, `providerTimeoutMs`.\n *\n * Resolves with the exit code: 0 when every step finished in time, 1 when the\n * drain was cut short or a provider failed or overran.\n *\n * Two things `stop()` does not do, both measured on Bun 1.3.14, and both why\n * the process exit that follows is what actually ends the server:\n *\n * - It does not close a kept-alive connection. One that is idle when the\n * listener closes stays open, and a request sent down it afterwards is\n * served. That is what the `Connection: close` on every response in the\n * window is for: a client (or a proxy in front) that honours it opens its\n * next request on a new connection, which the closed listener refuses. A\n * client that does not honour it is what step 4's `503` is for — Bun does\n * not close the socket after a `Connection: close` response either (#566).\n * - `stop(true)` issued after a graceful `stop()` does not cut the remaining\n * requests off; it waits for the same ones. It is still called when the\n * drain times out, for a Bun that does, but nothing here depends on it. Nor\n * does it close an idle kept-alive connection. Only a `stop(true)` issued\n * *first* does that, and it cuts off the requests in flight with it, which\n * is the drain given up — so the idle ones are refused, not closed.\n */\nexport async function drain(params: {\n server: Stoppable | undefined;\n shutdownProviders: (options: { timeoutMs: number }) => Promise<ShutdownReport>;\n settings: ShutdownSettings;\n}): Promise<number> {\n const { server, settings } = params;\n const deadline = Date.now() + settings.timeoutMs;\n\n markShuttingDown();\n console.log(\n `[gemi] Shutting down: draining in-flight requests (up to ${settings.timeoutMs / 1000}s).`,\n );\n\n let drained = true;\n if (server) {\n if (settings.delayMs > 0) {\n await sleep(Math.min(settings.delayMs, deadline - Date.now()));\n }\n const stopped = server.stop();\n // No time left to wait — a `GEMI_SHUTDOWN_TIMEOUT` of 0, or a delay that\n // spent all of it — is \"do not wait for what is in flight\", and that is\n // only a failure when something *is* in flight. Reading it as one made\n // every clean shutdown log an abandonment and exit 1 for the operator who\n // zeroed the budget to fit a 5s grace period, with nothing to abandon.\n const remaining = deadline - Date.now();\n drained =\n remaining > 0 ? await settlesWithin(stopped, remaining) : server.pendingRequests === 0;\n if (!drained) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${server.pendingRequests} request(s) still in flight; abandoning them.`,\n );\n void server.stop(true).catch(() => {});\n }\n }\n\n // Whether or not the drain finished: a request that arrives now, down a\n // kept-alive connection the listener's close left open, would run against\n // providers that are being shut down underneath it.\n markDrained();\n const report = await params.shutdownProviders({ timeoutMs: settings.providerTimeoutMs });\n const clean = drained && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n}\n\nasync function settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n // `drain` decides for itself what a budget that is already spent means, so\n // this is only a guard: a race against `setTimeout(0)` is a coin toss, and\n // \"did not settle within no time at all\" is the honest answer to it.\n if (ms <= 0) return false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const result = await Promise.race([\n promise.then(\n () => true,\n () => true,\n ),\n new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), ms);\n }),\n ]);\n clearTimeout(timer);\n return result;\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\n/**\n * `Connection: close` on a response sent while shutting down, so the client's\n * next request opens a connection — which the load balancer can send elsewhere\n * — instead of reusing this one.\n *\n * The spec makes some responses' headers immutable (a `Response.redirect`, a\n * proxied `fetch`), and setting one throws. Bun 1.3.14 lets both be set, so\n * the copy is for a Bun that follows the spec — a throw here would turn every\n * such response in the drain window into a 500.\n */\nexport function closeConnectionWhileShuttingDown(res: Response): Response {\n if (!isShuttingDown()) return res;\n try {\n res.headers.set(\"Connection\", \"close\");\n return res;\n } catch {\n const copy = new Response(res.body, res);\n copy.headers.set(\"Connection\", \"close\");\n return copy;\n }\n}\n\n/**\n * What every response goes through while this process serves: the app's\n * instrumentation, with the two changes a shutdown makes to it.\n *\n * - While the requests in flight drain, a response carries `Connection: close`\n * (`closeConnectionWhileShuttingDown`).\n * - Once they have drained, a request is answered `503` with\n * `Connection: close` and reaches neither the app nor its instrumentation.\n * The listener is closed by then, so only a kept-alive connection can still\n * deliver one, and `server.stop()` leaves those open. Serving it would run a\n * handler against providers whose `shutdown()` is closing the pool, the\n * queue or the cache it uses — until the process exits. The instrumentation\n * is skipped too because it is app code, and a tracer or error reporter is\n * exactly what a provider flushes and closes at this point.\n */\nexport function serveForShutdown(instrumentation: Instrumentation): Instrumentation {\n return async (req, next) => {\n if (state().drained) {\n return new Response(\"Service Unavailable\", {\n status: 503,\n headers: { Connection: \"close\" },\n });\n }\n return closeConnectionWhileShuttingDown(await instrumentation(req, next));\n };\n}\n\n// Installed once per process, not once per `Server`: a listener per instance\n// would each start a shutdown of its own, and read the other's signal as the\n// second one.\nconst SIGNALS_INSTALLED = Symbol.for(\"gemi.server.signalsInstalled\");\n\n/**\n * A repeat of the first signal inside this window is the same shutdown\n * delivered twice, not an operator asking to skip the drain. One shutdown\n * routinely arrives more than once, milliseconds apart: Ctrl+C on\n * `bun run start` reaches the server directly (the whole foreground group is\n * signalled), and again through `gemi start`'s relay — twice over, since\n * `bun run` forwards it to `gemi start` too. systemd's default\n * `KillMode=control-group` and `tini -g` do the same to every process in the\n * group. A person pressing Ctrl+C again is well outside a second.\n */\nconst REPEAT_WINDOW_MS = 1000;\n\n/**\n * `SIGTERM` or `SIGINT` runs `stop` and exits with the code it resolves with.\n * Another signal of either kind, more than `repeatWindowMs` after the first,\n * exits at once with `128 + n` — an operator pressing Ctrl+C again does not\n * want to wait out the grace period. Without a listener the first signal would\n * do that too: the default action for both is to terminate the process on the\n * spot.\n */\nexport function installShutdownSignals(\n stop: () => Promise<number>,\n options: { repeatWindowMs?: number } = {},\n) {\n const global = globalThis as { [SIGNALS_INSTALLED]?: boolean };\n if (global[SIGNALS_INSTALLED]) return;\n global[SIGNALS_INSTALLED] = true;\n\n const repeatWindowMs = options.repeatWindowMs ?? REPEAT_WINDOW_MS;\n let receivedAt: number | undefined;\n const onSignal = (signal: \"SIGTERM\" | \"SIGINT\") => {\n if (receivedAt !== undefined) {\n if (Date.now() - receivedAt < repeatWindowMs) return;\n console.error(`[gemi] ${signal} received again; exiting without waiting for the drain.`);\n process.exit(128 + constants.signals[signal]);\n }\n receivedAt = Date.now();\n console.log(`[gemi] ${signal} received.`);\n stop().then(\n (code) => process.exit(code),\n (error) => {\n console.error(\"[gemi] Shutdown failed:\", error);\n process.exit(1);\n },\n );\n };\n process.on(\"SIGTERM\", onSignal);\n process.on(\"SIGINT\", onSignal);\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAAA,oBAAS,WAQT,IAAM,EAAQ,OAAO,IAAI,sBAAsB,EAI/C,SAAS,CAAK,EAAkB,CAC9B,IAAM,EAAS,WAEf,OADA,EAAO,KAAW,CAAE,aAAc,GAAO,QAAS,EAAM,EACjD,EAAO,GAeT,SAAS,CAAc,EAAY,CACxC,OAAO,EAAM,EAAE,aAGV,SAAS,CAAgB,EAAG,CACjC,EAAM,EAAE,aAAe,GAOlB,SAAS,CAAW,EAAG,CAC5B,EAAM,EAAE,QAAU,GA4Cb,SAAS,CAAgB,CAC9B,EAA0C,QAAQ,IAChC,CAClB,IAAM,EAAW,CACf,UAAW,EAAQ,EAAI,sBAAuB,EAAE,EAChD,QAAS,EAAQ,EAAI,oBAAqB,CAAC,EAC3C,kBAAmB,EAAQ,EAAI,+BAAgC,CAAC,CAClE,EAKA,GAAI,EAAS,QAAU,GAAK,EAAS,SAAW,EAAS,UACvD,QAAQ,KACN,+BAA+B,EAAS,QAAU,gEAAgE,EAAS,UAAY,oFACzI,EAEF,OAAO,EAGT,SAAS,CAAO,CAAC,EAA2B,EAA0B,CACpE,IAAM,EAAS,IAAU,QAAa,EAAM,KAAK,IAAM,GAAK,IAAM,OAAO,CAAK,EAC9E,GAAI,OAAO,SAAS,CAAM,GAAK,GAAU,EAAG,OAAO,EAAS,KAC5D,GAAI,IAAU,OACZ,QAAQ,KAAK,qCAAqC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ai as P}from"./chunk-j3nr4cg0.js";class C{spent=new Map;sweepAt=1024;async consume(J,Q){return this.consumeSync(J,Q)}consumeSync(J,Q,Z=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Z);let W=this.spent.get(J);if(W!==void 0&&W>Z)return!1;return this.spent.set(J,Q),!0}get size(){return this.spent.size}sweep(J){for(let[Q,Z]of this.spent)if(Z<=J)this.spent.delete(Q);this.sweepAt=Math.max(1024,this.spent.size*2)}}class N{injectedClient;prefix;constructor(J={}){this.injectedClient=J.client,this.prefix=J.prefix??"gemi:ai:nonce"}async consume(J,Q){let Z=Math.max(1,Math.ceil(Q-Date.now()));return await this.client.send("SET",[`${this.prefix}:${J}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let J=P(),Q=J.bound(M)?J.make(M).client:void 0;if(!Q)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return Q}}var S=new C;class D extends Error{retryable;constructor(J,Q={}){super(J,Q.cause!==void 0?{cause:Q.cause}:void 0);this.name="ToolError",this.retryable=Q.retryable??!0}}var u={provider_error:"The model provider returned an error.",rate_limited:"The model provider is rate limiting requests. Try again shortly.",context_length_exceeded:"The conversation is too long for the model.",content_filtered:"The model provider's content filter blocked this request.",invalid_tool_input:"The model provider rejected the request.",tool_error:"A tool failed.",unknown:"The run failed unexpectedly."};function V(J,Q){if(Q.source==="tool"){if(Q.cause instanceof D)return J;return{...J,message:`The tool "${Q.toolName}" failed with an unexpected error.`}}let Z=u[J.code];return Z===void 0?J:{...J,message:Z}}function e(J,Q,Z,W){let $;try{$=(J??V)(Q,Z)}catch(X){W(X),$=V(Q,Z)}return{code:$.code,message:$.message,...$.toolCallId!==void 0?{toolCallId:$.toolCallId}:{},retryable:$.retryable}}var L=new WeakMap;function JJ(J,Q){if(J!==Q)L.set(J,Q)}function QJ(J){return L.get(J)??J}import{createHmac as E,hkdfSync as m,randomBytes as k,timingSafeEqual as d}from"crypto";var z="agt2",j="agt1",O=[z,j],G=86400000,p=Date.now()+G;function f(J){return J<=p}var v="gemi.ai.pending-call.v1",I="gemi.ai.nested-run.v1",l="gemi.ai.execution-receipt.v1",t="gemi.ai.signing",b=new Map;function H(J,Q){let Z=K(Q),W=`${J}\x00${Z}`,$=b.get(W);if(!$){if($=Buffer.from(m("sha256",Z,t,J,32)),b.size>64)b.clear();b.set(W,$)}return $}function K(J){let Q=J??process.env.SECRET;if(!Q)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return Q}function q(J){if(J===null||typeof J!=="object")return JSON.stringify(J)??"null";if(Array.isArray(J))return`[${J.map(q).join(",")}]`;let Q=J;return`{${Object.keys(Q).filter((W)=>Q[W]!==void 0).sort().map((W)=>`${JSON.stringify(W)}:${q(Q[W])}`).join(",")}}`}function c(J){return J.map((Q)=>`${Q.length}:${Q}`).join("")}function B(J,Q){return E("sha256",J).update(c(Q)).digest()}function x(J,Q){let Z=Buffer.from(J.split(".")[4],"base64url");return Z.length===Q.length&&d(Z,Q)}function U(J){return q(J??null)}function R(J,Q,Z){return[z,J.runId,J.toolCallId,J.name,J.kind,Q,String(Z),q(J.input),q(J.path??[]),U(J.subject)]}function n(J,Q,Z){let W=[j,J.runId,J.toolCallId,J.name,J.kind,Q,String(Z),q(J.input)];if(J.path&&J.path.length>0)W.push(q(J.path));return W}var T=(J)=>Buffer.from(J,"utf8").toString("base64url"),o=(J)=>Buffer.from(J,"base64url").toString("utf8");function qJ(J,Q={}){let Z=H(v,Q.secret),$=(Q.now??Date.now())+(Q.ttlMs??G),X=k(12).toString("base64url"),h=B(Z,R(J,X,$)).toString("base64url");return[z,T(J.runId),X,$.toString(36),h].join(".")}function a(J){return Y(J,O)}function Y(J,Q){let Z=J.split(".");if(Z.length!==5||!Q.includes(Z[0]))return null;let W=Number.parseInt(Z[3],36);if(!Number.isFinite(W))return null;try{return{runId:o(Z[1]),nonce:Z[2],expiresAt:W,version:Z[0]}}catch{return null}}function XJ(J,Q,Z={}){let W=Y(J,O);if(!W)return{ok:!1,reason:"malformed"};if(W.version===j&&!f(W.expiresAt))return{ok:!1,reason:"forged"};let $=W.version===j?B(K(Z.secret),n(Q,W.nonce,W.expiresAt)):B(H(v,Z.secret),R(Q,W.nonce,W.expiresAt));if(!x(J,$))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>W.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:W.runId,nonce:W.nonce,expiresAt:W.expiresAt}}var F="agn2",w="agn1",A=[F,w];function _(J,Q,Z){return[...y(J,Q,Z,F),U(J.subject)]}function y(J,Q,Z,W=w){return[W,J.runId,q(J.path),J.nestedRunId,Q,String(Z),q([...J.open].sort()),q(J.input)]}function BJ(J,Q={}){let Z=H(I,Q.secret),$=(Q.now??Date.now())+(Q.ttlMs??G),X=k(12).toString("base64url"),h=B(Z,_(J,X,$)).toString("base64url");return[F,T(J.runId),X,$.toString(36),h].join(".")}function HJ(J,Q,Z={}){let W=Y(J,A);if(!W)return{ok:!1,reason:"malformed"};if(W.version===w&&!f(W.expiresAt))return{ok:!1,reason:"forged"};let $={...Q,runId:W.runId},X=W.version===w?B(K(Z.secret),y($,W.nonce,W.expiresAt)):B(H(I,Z.secret),_($,W.nonce,W.expiresAt));if(!x(J,X))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>W.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:W.runId,nonce:W.nonce,expiresAt:W.expiresAt}}function bJ(J,Q,Z={}){let W=H(l,Z.secret);return B(W,[J,Q.runId,Q.toolCallId,Q.name,Q.kind,q(Q.input),q(Q.path??[]),U(Q.subject)]).toString("base64url")}function jJ(J,Q){return g(Q,a(J))}function wJ(J,Q){return g(Q,Y(J,A))}async function g(J,Q){if(!Q)return!1;return J.consume(Q.nonce,Q.expiresAt)}
|
|
3
|
+
export{C as Sb,N as Tb,S as Ub,H as Vb,q as Wb,qJ as Xb,a as Yb,XJ as Zb,BJ as _b,HJ as $b,bJ as ac,jJ as bc,wJ as cc,D as dc,V as ec,e as fc,JJ as gc,QJ as hc};
|
|
4
|
+
|
|
5
|
+
//# debugId=D632A8739B1CA6A964756E2164756E21
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../ai/store/Nonces.ts", "../ai/redact.ts", "../ai/signing.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { app } from \"../../foundation/app\";\nimport { RedisManager } from \"../../services/redis/RedisManager\";\n\n/**\n * SPENT NONCES: what makes a signed answer single-use (#445).\n *\n * A pending call's signature (and a parked sub-run's record) carries a nonce\n * and an expiry. Verifying the MAC says the server once asked this exact\n * question; spending the nonce says nobody has answered it yet. Without that a\n * stateless client rewinds its history to before the result and replays the\n * same signed approval, and the human who approved once has approved forever.\n *\n * Spending has to be shared by every process that can receive the answer, and\n * it has to be atomic: insert-if-absent, so two instances handed the same\n * answer at the same moment cannot both be told \"first\". A check followed by a\n * write is not enough, since both reads can happen before either write.\n *\n * Implementations:\n *\n * MemoryNonceStore — the default. One process, lost on restart. Correct for\n * a single instance; with several, each instance accepts\n * the same answer once.\n * RedisNonceStore — `SET key 1 PX <ttl> NX` on the app's Redis. Shared,\n * atomic, and Redis drops each key at the token's expiry.\n * your own — e.g. a table with the nonce as its primary key:\n *\n * class DbNonceStore implements NonceStore {\n * async consume(nonce, expiresAt) {\n * // INSERT ... ON CONFLICT (nonce) DO NOTHING, then look at the row count.\n * const inserted = await db.$executeRaw`\n * INSERT INTO agent_nonces (nonce, expires_at)\n * VALUES (${nonce}, ${new Date(expiresAt)})\n * ON CONFLICT (nonce) DO NOTHING`;\n * return inserted === 1;\n * }\n * }\n * // and, from a cron: DELETE FROM agent_nonces WHERE expires_at < now()\n *\n * Expired tokens fail verification on their own, so a store only has to\n * remember a nonce until `expiresAt`; anything older may be dropped.\n */\nexport interface NonceStore {\n /**\n * Records `nonce` as spent until `expiresAt` (epoch milliseconds). Resolves\n * `true` when this call is the one that spent it, `false` when it was\n * already spent. Must be atomic across every process sharing the store.\n *\n * A rejection is treated as \"could not be spent\": the answer is refused,\n * and the user is asked again. A replay guard that silently lets an answer\n * through when its backing store is down is not a guard.\n */\n consume(nonce: string, expiresAt: number): Promise<boolean>;\n}\n\n/**\n * The in-process store. Bounded by the tokens issued in one TTL window: an\n * entry is dropped once its token expires, swept amortized O(1) per insert.\n */\nexport class MemoryNonceStore implements NonceStore {\n private readonly spent = new Map<string, number>();\n /** Sweep when the map has grown past this, so sweeping costs O(1) per insert\n * amortized instead of walking every entry on every answer. */\n private sweepAt = 1024;\n\n async consume(nonce: string, expiresAt: number): Promise<boolean> {\n return this.consumeSync(nonce, expiresAt);\n }\n\n /**\n * The same decision without the promise. JavaScript runs it to completion,\n * so within one process it is atomic. `now` is injectable for tests.\n */\n consumeSync(nonce: string, expiresAt: number, now = Date.now()): boolean {\n if (this.spent.size >= this.sweepAt) this.sweep(now);\n const spentUntil = this.spent.get(nonce);\n // A record past its own expiry binds nothing: the token it refers to fails\n // verification on its own, so holding the nonce would only grow the map.\n if (spentUntil !== undefined && spentUntil > now) return false;\n this.spent.set(nonce, expiresAt);\n return true;\n }\n\n get size(): number {\n return this.spent.size;\n }\n\n private sweep(now: number) {\n for (const [nonce, expiresAt] of this.spent) {\n if (expiresAt <= now) this.spent.delete(nonce);\n }\n this.sweepAt = Math.max(1024, this.spent.size * 2);\n }\n}\n\n/** The slice of Bun's `RedisClient` this store needs: `send(command, args)`. */\nexport interface NonceRedisClient {\n send(command: string, args: string[]): Promise<any>;\n}\n\nexport interface RedisNonceStoreOptions {\n /**\n * Client to run against. Defaults to the app's shared client from\n * `RedisServiceProvider`, resolved on first use so constructing the store\n * never needs a kernel or a connection.\n */\n client?: NonceRedisClient;\n /** Key namespace. Defaults to `gemi:ai:nonce`. */\n prefix?: string;\n}\n\n/**\n * Spent nonces in Redis, shared by every instance of the app. `SET ... NX` is\n * a single command, so the insert-if-absent is atomic in Redis; `PX` hands the\n * cleanup to Redis at the token's own expiry.\n *\n * ```ts\n * const nonces = new RedisNonceStore();\n *\n * class ChatController extends AgentController<typeof chat> {\n * agent = chat;\n * nonces = nonces;\n * }\n * ```\n *\n * A Redis failure rejects, and the answer it was checking is refused (see\n * `NonceStore.consume`).\n */\nexport class RedisNonceStore implements NonceStore {\n private readonly injectedClient?: NonceRedisClient;\n private readonly prefix: string;\n\n constructor(options: RedisNonceStoreOptions = {}) {\n this.injectedClient = options.client;\n this.prefix = options.prefix ?? \"gemi:ai:nonce\";\n }\n\n async consume(nonce: string, expiresAt: number): Promise<boolean> {\n // At least 1ms: `PX 0` is an error, and an already-expired token never\n // reaches here (verification refuses it first) unless the clock moved.\n const ttl = Math.max(1, Math.ceil(expiresAt - Date.now()));\n const reply = await this.client.send(\"SET\", [\n `${this.prefix}:${nonce}`,\n \"1\",\n \"PX\",\n String(ttl),\n \"NX\",\n ]);\n // `OK` when the key was set, nil when it already existed.\n return reply === \"OK\";\n }\n\n private get client(): NonceRedisClient {\n if (this.injectedClient) return this.injectedClient;\n const container = app();\n const client = container.bound(RedisManager)\n ? container.make(RedisManager).client\n : undefined;\n if (!client) {\n throw new Error(\n \"RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).\",\n );\n }\n return client;\n }\n}\n\n/** The process-wide default, shared by every agent that is not given a store. */\nexport const defaultNonceStore = new MemoryNonceStore();\n",
|
|
6
|
+
"import type { AgentError, AgentErrorCode } from \"./types\";\n\n/**\n * A tool failure whose message is meant to be read: by the model, which can\n * act on it, and by the client, which shows it.\n *\n * Any other exception a tool throws reaches the model and the client as a\n * generic sentence (see `redactError`), because its message is whatever the\n * code underneath happened to say: a database driver's connection string, an\n * internal hostname, a third party's error body. The full error is logged.\n * Throw this instead when the message is written for the person:\n *\n * ```ts\n * if (!order) throw new ToolError(`There is no order ${input.orderId}.`);\n * ```\n */\nexport class ToolError extends Error {\n /** Whether the model may try the call again. Default `true`. */\n readonly retryable: boolean;\n\n constructor(message: string, options: { retryable?: boolean; cause?: unknown } = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = \"ToolError\";\n this.retryable = options.retryable ?? true;\n }\n}\n\n/**\n * Where an error being redacted came from, with the unredacted detail.\n *\n * - `run`: the run's own failure, on its `error` frame. `failure` is what\n * `result().error` returns: the provider's own message, its HTTP status and\n * request id.\n * - `tool`: a tool threw. `cause` is what it threw; the result the model and\n * the client read is the redacted one.\n */\nexport type ErrorRedactionInfo =\n | {\n source: \"run\";\n failure: AgentError & { status?: number; requestId?: string };\n }\n | {\n source: \"tool\";\n toolName: string;\n cause: unknown;\n };\n\n/**\n * Decides what a client (and, for a tool, the model) is told about a failure.\n * Return the error to send. Full detail is never lost: it stays on\n * `result().error`, in the log and in the controller's `onError`.\n */\nexport type ErrorRedactor = (error: AgentError, info: ErrorRedactionInfo) => AgentError;\n\n/**\n * The run failures whose message comes from outside gemi: a provider's error\n * body or an exception's text. Those can carry resource and deployment names,\n * internal URLs, request ids and, in a provider's validation message, pieces of\n * the request itself. The rest (`timeout`, `invalid_output`, `aborted`, ...)\n * are sentences gemi wrote and are kept.\n */\nconst GENERIC_RUN_MESSAGES: Partial<Record<AgentErrorCode, string>> = {\n provider_error: \"The model provider returned an error.\",\n rate_limited: \"The model provider is rate limiting requests. Try again shortly.\",\n context_length_exceeded: \"The conversation is too long for the model.\",\n content_filtered: \"The model provider's content filter blocked this request.\",\n invalid_tool_input: \"The model provider rejected the request.\",\n tool_error: \"A tool failed.\",\n unknown: \"The run failed unexpectedly.\",\n};\n\n/**\n * The default redaction, and what an override of `AgentController.redactError`\n * falls back to.\n *\n * Keeps `code`, `retryable` and `toolCallId`, which are what a client branches\n * on, and replaces a message that did not come from gemi with a fixed sentence\n * for its code. A tool's exception keeps its message only when it is a\n * `ToolError`.\n */\nexport function redactError(error: AgentError, info: ErrorRedactionInfo): AgentError {\n if (info.source === \"tool\") {\n if (info.cause instanceof ToolError) return error;\n return {\n ...error,\n message: `The tool \"${info.toolName}\" failed with an unexpected error.`,\n };\n }\n const generic = GENERIC_RUN_MESSAGES[error.code];\n return generic === undefined ? error : { ...error, message: generic };\n}\n\n/**\n * Runs an app's redactor and keeps only the `AgentError` fields of what it\n * returns, so a redactor that spreads the failure (`{ ...info.failure }`)\n * cannot put its status or request id on the wire by accident. A redactor\n * that throws falls back to the default rather than to the unredacted error.\n */\nexport function applyRedaction(\n redactor: ErrorRedactor | undefined,\n error: AgentError,\n info: ErrorRedactionInfo,\n onFailure: (err: unknown) => void,\n): AgentError {\n let out: AgentError;\n try {\n out = (redactor ?? redactError)(error, info);\n } catch (err) {\n onFailure(err);\n out = redactError(error, info);\n }\n return {\n code: out.code,\n message: out.message,\n ...(out.toolCallId !== undefined ? { toolCallId: out.toolCallId } : {}),\n retryable: out.retryable,\n };\n}\n\n/**\n * The unredacted error behind a redacted one, for the server-side hooks.\n *\n * Keyed by the object put on the frame, which is the object the controller's\n * event hooks are handed in the same process; it never crosses a wire.\n */\nconst unredacted = new WeakMap<AgentError, AgentError>();\n\nexport function rememberUnredacted(redacted: AgentError, original: AgentError): void {\n if (redacted !== original) unredacted.set(redacted, original);\n}\n\n/** The original of `error` when it was redacted in this process, else `error`. */\nexport function unredactedError(error: AgentError): AgentError {\n return unredacted.get(error) ?? error;\n}\n",
|
|
7
|
+
"import { createHmac, hkdfSync, randomBytes, timingSafeEqual } from \"crypto\";\nimport { defaultNonceStore, type NonceStore } from \"./store/Nonces\";\n\n/**\n * Signing for pending tool calls.\n *\n * A pending call travels through the browser and comes back — in stateless mode\n * the whole history does — so the server cannot trust that what it gets back is\n * what it sent. Without a signature the client asserts not just *that* a call\n * was approved but *what* was approved, and nothing would stop it from\n * returning `approve: true` against an input it rewrote on the way. Signing is\n * what makes the round trip safe, and it is why approvals need no server-side\n * storage at all.\n *\n * What is signed, and what deliberately is not:\n *\n * signed — `runId`, `toolCallId`, the tool `name`, the `kind` of pending call\n * and a canonical serialization of the input, plus a nonce, an\n * expiry, and — for a call a sub-agent asked — the `path` of\n * tool-call ids it is nested under.\n * not — the client's answer. `approve: true` / `approve: false` and a\n * question's output are the *point* of asking; a client that flips\n * its own answer has refused, not forged. What the signature buys is\n * that the answer is bound to the call the server actually made,\n * with the input the server actually saw.\n *\n * A verified token is not yet an answer the server may act on: it says the\n * question was asked, not that it is still open. `consumePendingCall` at the\n * bottom of this file spends the nonce, which is what makes an approval\n * single-use — see the note there for what that guarantee is worth.\n *\n * `kind` is in there for a specific attack: an `approval`-kind call is one the\n * *server* runs, so a client that reused its signature on the \"here is the\n * output\" arm of `ClientToolResult` would be fabricating a server tool's result\n * rather than approving it. Binding the kind makes that a forgery instead of a\n * shape the caller has to remember to check.\n *\n * Keys and principals (#447). Neither token kind is MACed with `SECRET`\n * itself: each is keyed with its own HKDF-derived key (`purposeKey` below), so\n * a MAC minted for one purpose — a pending call, a parked-run record, or\n * anything else in the app keyed off `SECRET` (CSRF, sessions) — is never a\n * MAC for another. And each binds the `subject`, the principal the run was\n * started for (`AgentController.runOwner`), so a token minted while user A was\n * asked cannot be answered by user B, even with A's history in hand.\n */\n\n/** Everything the signature commits to. */\nexport type PendingCallClaims = {\n runId: string;\n toolCallId: string;\n name: string;\n kind: \"approval\" | \"question\" | \"client\";\n input: unknown;\n /**\n * The chain of tool-call ids the call is nested under, outermost first.\n * Absent — or empty, which means the same thing — for a top-level call.\n *\n * A sub-agent's question reaches the user through its parent's pending list,\n * so `toolCallId` stops being an address on its own: two sub-runs under two\n * different tools can each hold a call the outer run never made. Binding the\n * path is what stops a token minted for a call nested under tool call X from\n * being replayed as a top-level call, or as one nested under Y.\n */\n path?: string[];\n /**\n * Who the question was asked of: the run's owner (`AgentController.runOwner`,\n * `user:<id>` by default). `null` or absent is nobody in particular — an\n * anonymous run — and the two are the same claim. A token minted for one\n * subject fails verification for any other, `null` included, so an approval\n * cannot be carried from one user's session to another's.\n */\n subject?: string | null;\n};\n\nexport type SignOptions = {\n /** Overrides `process.env.SECRET`. Exists for tests; apps use the app key. */\n secret?: string;\n /**\n * Default 24 hours. An approval waits on a human, and humans go to lunch —\n * a short expiry turns \"I approved it after standup\" into an unexplained\n * failure. Long enough to survive a working day, short enough that a token\n * lifted from a log is not useful next month.\n */\n ttlMs?: number;\n /** Injected clock, so the expiry path is testable without waiting. */\n now?: number;\n};\n\nexport type VerifyOptions = {\n secret?: string;\n now?: number;\n};\n\n/**\n * A discriminated result rather than a boolean, because the two failures are\n * different events: `expired` is a sentence to show the user, `forged` is worth\n * logging and possibly alerting on. Collapsing them loses the only signal that\n * says someone is probing.\n */\nexport type VerifyResult =\n | { ok: true; runId: string; nonce: string; expiresAt: number }\n | { ok: false; reason: \"malformed\" | \"expired\" | \"forged\" };\n\n/**\n * `agt2` is minted; `agt1` is still verified. A v1 token was MACed with the raw\n * `SECRET` and binds no subject — it is accepted so that a question asked\n * before the upgrade can still be answered after it, and it stops mattering on\n * its own when the last one expires (`DEFAULT_TTL_MS` after the deploy). Drop\n * `LEGACY_VERSION` from the accepted set once that window is long past.\n */\nconst VERSION = \"agt2\";\nconst LEGACY_VERSION = \"agt1\";\nconst PENDING_VERSIONS = [VERSION, LEGACY_VERSION];\nconst DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;\n\n/**\n * The latest expiry a legacy token may claim. Every v1 token this process can\n * legitimately see was minted by an earlier deploy with the default TTL, so it\n * expires no later than one TTL after this module loaded. Bounding it here\n * means a v1 token — MACed with the raw `SECRET`, the key this change exists to\n * stop relying on — cannot be forged with a far-future expiry, and that after\n * one TTL of uptime no v1 token verifies at all.\n */\nconst LEGACY_ACCEPTED_UNTIL = Date.now() + DEFAULT_TTL_MS;\n\nfunction legacyExpiryOk(expiresAt: number): boolean {\n return expiresAt <= LEGACY_ACCEPTED_UNTIL;\n}\n\n/**\n * HKDF `info` labels, one per thing a key signs. Changing a label is a key\n * rotation for that purpose alone.\n */\nconst PENDING_CALL_PURPOSE = \"gemi.ai.pending-call.v1\";\nconst NESTED_RUN_PURPOSE = \"gemi.ai.nested-run.v1\";\nconst EXECUTION_RECEIPT_PURPOSE = \"gemi.ai.execution-receipt.v1\";\nconst HKDF_SALT = \"gemi.ai.signing\";\n\nconst derivedKeys = new Map<string, Buffer>();\n\n/**\n * A key for one purpose, derived from the app secret with HKDF-SHA256.\n *\n * `SECRET` is also what CSRF tokens and sessions are keyed with. Using it as\n * the HMAC key here would make every one of those a potential oracle for the\n * others; HKDF with a purpose label gives each its own independent key, so a\n * weakness or leak in one use cannot be turned against another — including\n * the two token kinds in this file against each other.\n *\n * Memoized per (purpose, secret): verification is on the request path and the\n * derivation is pure. The map is bounded by the number of purposes times the\n * secrets a process ever sees, which is one outside of tests.\n */\nexport function purposeKey(purpose: string, override?: string): Buffer {\n const secret = secretKey(override);\n const cacheKey = `${purpose}\\u0000${secret}`;\n let key = derivedKeys.get(cacheKey);\n if (!key) {\n key = Buffer.from(hkdfSync(\"sha256\", secret, HKDF_SALT, purpose, 32));\n if (derivedKeys.size > 64) derivedKeys.clear();\n derivedKeys.set(cacheKey, key);\n }\n return key;\n}\n\nfunction secretKey(override?: string): string {\n const secret = override ?? process.env.SECRET;\n if (!secret) {\n // Refusing is the only safe answer. A fallback constant would make every\n // approval in every deployment forgeable by anyone who read this file, and\n // it would do it silently — the feature would appear to work.\n throw new Error(\n \"Signing a pending tool call needs an app secret. Set SECRET in the environment.\",\n );\n }\n return secret;\n}\n\n/**\n * Serializes a value so that the same value always produces the same string.\n *\n * `JSON.stringify` is not enough: it preserves insertion order, so an input\n * that made a round trip through a client — parsed and re-serialized, with the\n * keys in whatever order the parser produced — would hash differently and a\n * legitimate approval would come back looking forged. Keys are sorted,\n * `undefined` members are dropped (they do not survive JSON anyway), and arrays\n * keep their order because in an array order *is* the value.\n */\nexport function canonicalize(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value) ?? \"null\";\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalize).join(\",\")}]`;\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter((key) => record[key] !== undefined)\n .sort();\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalize(record[key])}`).join(\",\")}}`;\n}\n\n/**\n * Length-prefixed rather than delimiter-joined. A separator is a place for two\n * different claim sets to hash the same — `runId: \"a\", toolCallId: \"b|c\"` and\n * `runId: \"a|b\", toolCallId: \"c\"` — and while neither field contains the\n * separator today, that is a property of the id generator, not of this code.\n */\nfunction payload(fields: string[]): string {\n return fields.map((field) => `${field.length}:${field}`).join(\"\");\n}\n\nfunction mac(key: string | Buffer, fields: string[]): Buffer {\n return createHmac(\"sha256\", key).update(payload(fields)).digest();\n}\n\nfunction macMatches(signature: string, expected: Buffer): boolean {\n const presented = Buffer.from(signature.split(\".\")[4], \"base64url\");\n // `timingSafeEqual` throws on a length mismatch, and a wrong length is\n // already a public fact about the token — nothing is leaked by checking it\n // first, and everything is leaked by comparing the bytes with `===`.\n return presented.length === expected.length && timingSafeEqual(presented, expected);\n}\n\n/** The principal as a field: absent and `null` are the same claim. */\nfunction subjectField(subject: string | null | undefined): string {\n return canonicalize(subject ?? null);\n}\n\n/**\n * The v2 claim set. Fixed-length: the path is always present (`[]` at the top\n * level) and so is the subject, so there is no optional field to reason about.\n */\nfunction claimFields(claims: PendingCallClaims, nonce: string, expiresAt: number): string[] {\n return [\n VERSION,\n claims.runId,\n claims.toolCallId,\n claims.name,\n claims.kind,\n nonce,\n String(expiresAt),\n canonicalize(claims.input),\n canonicalize(claims.path ?? []),\n subjectField(claims.subject),\n ];\n}\n\n/**\n * The v1 claim set, kept only to verify tokens minted before #447.\n *\n * The path is appended, and only when there is one.\n *\n * Byte-identical output for a call with no path is the whole requirement here:\n * every approval already in flight was minted from the eight fields below, and\n * a ninth field carrying `\"[]\"` or `\"undefined\"` would invalidate all of them\n * on deploy — the user who clicked Approve before the release would be told\n * their answer was forged. So an absent path adds nothing at all, and an empty\n * array is treated as absent because it says the same thing.\n *\n * `payload` is length-prefixed, so appending a field cannot collide with a\n * longer value in the one before it; that is why this can be an append rather\n * than a new version tag.\n */\nfunction legacyClaimFields(claims: PendingCallClaims, nonce: string, expiresAt: number): string[] {\n const fields = [\n LEGACY_VERSION,\n claims.runId,\n claims.toolCallId,\n claims.name,\n claims.kind,\n nonce,\n String(expiresAt),\n canonicalize(claims.input),\n ];\n if (claims.path && claims.path.length > 0) {\n fields.push(canonicalize(claims.path));\n }\n return fields;\n}\n\nconst encode = (value: string) => Buffer.from(value, \"utf8\").toString(\"base64url\");\nconst decode = (value: string) => Buffer.from(value, \"base64url\").toString(\"utf8\");\n\n/** `agt2.<runId>.<nonce>.<expiry>.<mac>`, all base64url or base36. */\nexport function signPendingCall(claims: PendingCallClaims, options: SignOptions = {}): string {\n const key = purposeKey(PENDING_CALL_PURPOSE, options.secret);\n const now = options.now ?? Date.now();\n const expiresAt = now + (options.ttlMs ?? DEFAULT_TTL_MS);\n const nonce = randomBytes(12).toString(\"base64url\");\n const signature = mac(key, claimFields(claims, nonce, expiresAt)).toString(\"base64url\");\n return [VERSION, encode(claims.runId), nonce, expiresAt.toString(36), signature].join(\".\");\n}\n\n/**\n * The metadata a signature carries in the clear.\n *\n * `Agent` needs the issuing `runId` before it can verify anything: the call was\n * signed under the run that made it, and the turn answering it is a *new* run\n * with a new id. Reading it out of the token is safe because the token's own\n * MAC covers it — a client that edits the runId here fails verification, so\n * this is \"which run does this claim to belong to\", not \"which run does the\n * client say it belongs to\".\n */\nexport function readSignature(\n signature: string,\n): { runId: string; nonce: string; expiresAt: number } | null {\n return readToken(signature, PENDING_VERSIONS);\n}\n\n/**\n * The version tag is checked here and nowhere else, which is what keeps the\n * two token kinds apart: a parked-run record presented where a pending call's\n * signature is expected fails as malformed before its MAC is even looked at,\n * and the other way round. Their claim sets are different lengths and would\n * not collide anyway, but a tag makes that a rule rather than an accident of\n * the field count.\n */\nfunction readToken(\n signature: string,\n versions: readonly string[],\n): { runId: string; nonce: string; expiresAt: number; version: string } | null {\n const parts = signature.split(\".\");\n if (parts.length !== 5 || !versions.includes(parts[0])) {\n return null;\n }\n const expiresAt = Number.parseInt(parts[3], 36);\n if (!Number.isFinite(expiresAt)) {\n return null;\n }\n try {\n return { runId: decode(parts[1]), nonce: parts[2], expiresAt, version: parts[0] };\n } catch {\n return null;\n }\n}\n\nexport function verifyPendingCall(\n signature: string,\n claims: PendingCallClaims,\n options: VerifyOptions = {},\n): VerifyResult {\n const parsed = readToken(signature, PENDING_VERSIONS);\n if (!parsed) {\n return { ok: false, reason: \"malformed\" };\n }\n\n if (parsed.version === LEGACY_VERSION && !legacyExpiryOk(parsed.expiresAt)) {\n return { ok: false, reason: \"forged\" };\n }\n const expected =\n parsed.version === LEGACY_VERSION\n ? // Raw secret, no subject: see `LEGACY_VERSION`.\n mac(secretKey(options.secret), legacyClaimFields(claims, parsed.nonce, parsed.expiresAt))\n : mac(\n purposeKey(PENDING_CALL_PURPOSE, options.secret),\n claimFields(claims, parsed.nonce, parsed.expiresAt),\n );\n if (!macMatches(signature, expected)) {\n return { ok: false, reason: \"forged\" };\n }\n\n // Expiry is checked *after* the MAC on purpose: only a genuine token can be\n // \"expired\". Reporting a forgery as expired would tell the UI to say \"your\n // approval timed out\" to someone who was tampering.\n if ((options.now ?? Date.now()) > parsed.expiresAt) {\n return { ok: false, reason: \"expired\" };\n }\n\n return { ok: true, runId: parsed.runId, nonce: parsed.nonce, expiresAt: parsed.expiresAt };\n}\n\n// --- parked sub-runs -----------------------------------------------------\n\n/**\n * What a parked sub-run's record is signed over.\n *\n * `ToolCallPart.nested` is the parent's own record of where a sub-run stopped,\n * and in stateless mode it makes the same trip through the browser a pending\n * call does. The next turn *runs a tool* on the strength of that record — the\n * tool is re-entered because the record says a sub-run under it is waiting on\n * the question being answered — so an unsigned record lets the client choose\n * which tools run, with what input, before any answer is verified. A MAC over\n * what the server actually recorded is what makes the record safe to carry.\n *\n * Only a parked record is signed, because only a parked record executes\n * anything: a finished sub-run is replayed out of its transcript and spends\n * nothing, and a client that forges one has fed its own tool a made-up answer,\n * which a client-carried history already allows everywhere.\n *\n * Deliberately not signed: the transcript. The sub-run resumes from messages\n * the client carried, exactly as the parent does in stateless mode, and the\n * same argument applies — what the signature pins is that the server parked\n * *here*, on *these* calls, with *this* input, and not what was said on the\n * way.\n */\nexport type NestedRunClaims = {\n /** The root run's id, the one every pending call of the tree is minted under. */\n runId: string;\n /**\n * Tool-call ids from the root down to and including the call the record\n * hangs off. A sub-run's id is not an address on its own for the same reason\n * a nested call's is not: two sub-runs under two different tools can carry\n * the same one.\n */\n path: string[];\n /** The sub-run's own id, so a record cannot be moved between sub-runs. */\n nestedRunId: string;\n /** The tool calls the sub-run is waiting on: every call left open in its transcript. */\n open: string[];\n /**\n * The input the tool that parked was running on, as the transcript carries\n * it. Re-entry runs the tool body with the input the history holds, and the\n * history is the client's — so a record that pinned where the sub-run parked\n * but not what its tool was given would let the client keep the run and\n * rewrite the arguments to anything the schema accepts. The same bargain a\n * pending call makes: the input executed is the input signed.\n */\n input: unknown;\n /** The run's owner, as on `PendingCallClaims.subject`: a record parked for\n * one principal does not re-enter a tool for another. */\n subject?: string | null;\n};\n\n/** `agn2` is minted; `agn1` (raw secret, no subject) is still verified. See\n * `LEGACY_VERSION`. */\nconst NESTED_VERSION = \"agn2\";\nconst LEGACY_NESTED_VERSION = \"agn1\";\nconst NESTED_VERSIONS = [NESTED_VERSION, LEGACY_NESTED_VERSION];\n\nfunction nestedFields(claims: NestedRunClaims, nonce: string, expiresAt: number): string[] {\n return [\n ...legacyNestedFields(claims, nonce, expiresAt, NESTED_VERSION),\n subjectField(claims.subject),\n ];\n}\n\nfunction legacyNestedFields(\n claims: NestedRunClaims,\n nonce: string,\n expiresAt: number,\n version = LEGACY_NESTED_VERSION,\n): string[] {\n return [\n version,\n claims.runId,\n canonicalize(claims.path),\n claims.nestedRunId,\n nonce,\n String(expiresAt),\n // A set, so it is sorted: the ids are read back out of a transcript the\n // client re-serialized, and message order is not part of the claim.\n canonicalize([...claims.open].sort()),\n canonicalize(claims.input),\n ];\n}\n\n/**\n * Same shape as a pending call's token, so the same reader serves both — nonce\n * included, and the nonce is spent, by `consumeNestedRun` below. A verified\n * record is permission to run the tool it hangs off, and the tool body runs\n * before the sub-run gets to look at the answer's own nonce; a record that\n * could be presented twice would run the body twice before anything refused\n * the replay. Every park mints a fresh record, so spending one costs a\n * legitimate re-park nothing.\n */\nexport function signNestedRun(claims: NestedRunClaims, options: SignOptions = {}): string {\n const key = purposeKey(NESTED_RUN_PURPOSE, options.secret);\n const now = options.now ?? Date.now();\n const expiresAt = now + (options.ttlMs ?? DEFAULT_TTL_MS);\n const nonce = randomBytes(12).toString(\"base64url\");\n const signature = mac(key, nestedFields(claims, nonce, expiresAt)).toString(\"base64url\");\n return [NESTED_VERSION, encode(claims.runId), nonce, expiresAt.toString(36), signature].join(\".\");\n}\n\n/**\n * The run that verifies a record is never the run that minted it — the turn\n * answering a question is a new run with a new id — so the minting run's id is\n * read out of the token rather than asked of the caller, which has no other\n * source for it. The MAC covers it, so a client that edits the id in the clear\n * fails here rather than being believed.\n */\nexport function verifyNestedRun(\n signature: string,\n claims: Omit<NestedRunClaims, \"runId\">,\n options: VerifyOptions = {},\n): VerifyResult {\n const parsed = readToken(signature, NESTED_VERSIONS);\n if (!parsed) {\n return { ok: false, reason: \"malformed\" };\n }\n\n if (parsed.version === LEGACY_NESTED_VERSION && !legacyExpiryOk(parsed.expiresAt)) {\n return { ok: false, reason: \"forged\" };\n }\n const full = { ...claims, runId: parsed.runId };\n const expected =\n parsed.version === LEGACY_NESTED_VERSION\n ? mac(secretKey(options.secret), legacyNestedFields(full, parsed.nonce, parsed.expiresAt))\n : mac(\n purposeKey(NESTED_RUN_PURPOSE, options.secret),\n nestedFields(full, parsed.nonce, parsed.expiresAt),\n );\n if (!macMatches(signature, expected)) {\n return { ok: false, reason: \"forged\" };\n }\n\n // A parked record outlives its usefulness with the answers it exists to\n // deliver: those expire on the pending call's TTL, and a record older than\n // that can route nothing that would still verify.\n if ((options.now ?? Date.now()) > parsed.expiresAt) {\n return { ok: false, reason: \"expired\" };\n }\n\n return { ok: true, runId: parsed.runId, nonce: parsed.nonce, expiresAt: parsed.expiresAt };\n}\n\n// --- single use ----------------------------------------------------------\n\n/**\n * Spending a nonce.\n *\n * The MAC makes a token unforgeable; it does not make it single-use. Without\n * this a captured signature approves the same call again every time it is\n * presented, because a token that carries its own `runId` is a token that\n * asserts its own binding — which is no binding at all. Verifying tells you the\n * server once asked this exact question; spending the nonce is what says nobody\n * has answered it yet.\n *\n * Where spent nonces live is a `NonceStore` (`store/Nonces.ts`, #445). The\n * default is the process-wide `MemoryNonceStore`, which is exact for one\n * instance; an app with several instances gives the agent a shared store\n * (`RedisNonceStore`, or a table) so a rewound history cannot be replayed once\n * against each of them. The store's `consume` is insert-if-absent, so two\n * instances answering at once cannot both win.\n *\n * The other guard is the app's own message store: once a call has a result\n * next to it, the call is no longer open and the answer has nothing to attach\n * to. This is what stands in for that in stateless mode, where the history the\n * client returns can be rewound to before the result existed.\n */\n\n/**\n * The id an approved call's execution receipt is kept under (#458).\n *\n * Deterministic in the call the signature covers — the issuing run, the tool\n * call id, the tool, its canonical input, the nesting path and the subject —\n * and in nothing else, so every presentation of one approval, on any instance,\n * names the same receipt. Not in the nonce or expiry: those identify one\n * *token*, and a receipt identifies the *execution* it authorizes.\n *\n * An HMAC under its own HKDF-derived key rather than a plain hash, so an id in\n * a shared store is neither a MAC for anything else nor something a client can\n * compute to probe the store for another user's calls.\n */\nexport function executionReceiptId(\n agent: string,\n claims: PendingCallClaims,\n options: { secret?: string } = {},\n): string {\n const key = purposeKey(EXECUTION_RECEIPT_PURPOSE, options.secret);\n return mac(key, [\n agent,\n claims.runId,\n claims.toolCallId,\n claims.name,\n claims.kind,\n canonicalize(claims.input),\n canonicalize(claims.path ?? []),\n subjectField(claims.subject),\n ]).toString(\"base64url\");\n}\n\n/**\n * Spends a signature's nonce in `store`. `false` means it was already spent —\n * the answer is a replay and must not be acted on — or the token is malformed.\n * A store that throws rejects; the caller refuses the answer.\n *\n * Separate from `verifyPendingCall` rather than folded into it, because verify\n * is a pure question a caller may want to ask twice (logging a forgery, say)\n * and this one is a state change that must happen exactly once per answer.\n */\nexport function spendPendingCall(signature: string, store: NonceStore): Promise<boolean> {\n return spendIn(store, readSignature(signature));\n}\n\n/**\n * Spends a parked-run record's nonce, on the same store and the same terms.\n * `false` means the record has already re-entered its tool once — the turn is\n * a replay of a history from before the answer was delivered, and the body\n * must not run again on it.\n */\nexport function spendNestedRun(signature: string, store: NonceStore): Promise<boolean> {\n return spendIn(store, readToken(signature, NESTED_VERSIONS));\n}\n\nasync function spendIn(\n store: NonceStore,\n parsed: { nonce: string; expiresAt: number } | null,\n): Promise<boolean> {\n if (!parsed) return false;\n return store.consume(parsed.nonce, parsed.expiresAt);\n}\n\n/** `spendPendingCall` on the process-wide default store, synchronously.\n * `now` is injectable for tests. */\nexport function consumePendingCall(signature: string, options: VerifyOptions = {}): boolean {\n const parsed = readSignature(signature);\n return parsed\n ? defaultNonceStore.consumeSync(parsed.nonce, parsed.expiresAt, options.now)\n : false;\n}\n\n/** `spendNestedRun` on the process-wide default store, synchronously. */\nexport function consumeNestedRun(signature: string, options: VerifyOptions = {}): boolean {\n const parsed = readToken(signature, NESTED_VERSIONS);\n return parsed\n ? defaultNonceStore.consumeSync(parsed.nonce, parsed.expiresAt, options.now)\n : false;\n}\n"
|
|
8
|
+
],
|
|
9
|
+
"mappings": ";wFA0DO,AAAM,CAAuC,CACjC,MAAQ,IAAI,IAGrB,QAAU,UAEZ,QAAO,CAAC,EAAe,EAAqC,CAChE,OAAO,KAAK,YAAY,EAAO,CAAS,EAO1C,WAAW,CAAC,EAAe,EAAmB,EAAM,KAAK,IAAI,EAAY,CACvE,GAAI,KAAK,MAAM,MAAQ,KAAK,QAAS,KAAK,MAAM,CAAG,EACnD,IAAM,EAAa,KAAK,MAAM,IAAI,CAAK,EAGvC,GAAI,IAAe,QAAa,EAAa,EAAK,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CAAC,CAAC,EAC9B,EAAa,EAAO,OAAO,CAC7B,CAAC,EAAE,SAAS,WAAW,EAYlB,SAAS,EAAgB,CAAC,EAAmB,EAAqC,CACvF,OAAO,EAAQ,EAAO,EAAc,CAAS,CAAC,EASzC,SAAS,EAAc,CAAC,EAAmB,EAAqC,CACrF,OAAO,EAAQ,EAAO,EAAU,EAAW,CAAe,CAAC,EAG7D,eAAe,CAAO,CACpB,EACA,EACkB,CAClB,GAAI,CAAC,EAAQ,MAAO,GACpB,OAAO,EAAM,QAAQ,EAAO,MAAO,EAAO,SAAS",
|
|
10
|
+
"debugId": "D632A8739B1CA6A964756E2164756E21",
|
|
11
|
+
"names": []
|
|
12
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_ as F}from"./chunk-
|
|
2
|
+
import{_ as F}from"./chunk-gdmsn3f5.js";import{aa as w}from"./chunk-2rphhsr7.js";import{qi as h}from"./chunk-e6fp6dxx.js";var P=h((p)=>{var t=w(),l=F();function d(e){try{let o=new Set(Array.from(e.match(/([A-Z_]){3,}/g)??[]));return o.delete("CONFIG"),o.delete("CONFIG_PREFIX_SEPARATOR"),o.delete("ENV"),[...o].join(", ")}catch(o){return e}}var u=(e,o)=>async()=>{try{let r=e(process.env,o);if(r===void 0)throw Error();return r}catch(r){throw new t.CredentialsProviderError(r.message||`Not found in ENV: ${d(e.toString())}`,{logger:o?.logger})}},C=(e,{preferredFile:o="config",...r}={})=>async()=>{let n=l.getProfileName(r),{configFile:i,credentialsFile:c}=await l.loadSharedConfigFiles(r),s=c[n]||{},g=i[n]||{},m=o==="config"?{...s,...g}:{...g,...s};try{let f=e(m,o==="config"?i:c);if(f===void 0)throw Error();return f}catch(a){throw new t.CredentialsProviderError(a.message||`Not found in config files w/ profile [${n}]: ${d(e.toString())}`,{logger:r.logger})}},y=(e)=>typeof e==="function",E=(e)=>y(e)?async()=>await e():t.fromStatic(e),N=({environmentVariableSelector:e,configFileSelector:o,default:r},n={})=>{let{signingName:i,logger:c}=n,s={signingName:i,logger:c};return t.memoize(t.chain(u(e,s),C(o,n),E(r)))};p.loadConfig=N});
|
|
3
3
|
export{P as Y};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=4643DCF4CD43A3E264756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"'use strict';\n\nvar propertyProvider = require('@smithy/property-provider');\nvar sharedIniFileLoader = require('@smithy/shared-ini-file-loader');\n\nfunction getSelectorName(functionString) {\n try {\n const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? []));\n constants.delete(\"CONFIG\");\n constants.delete(\"CONFIG_PREFIX_SEPARATOR\");\n constants.delete(\"ENV\");\n return [...constants].join(\", \");\n }\n catch (e) {\n return functionString;\n }\n}\n\nconst fromEnv = (envVarSelector, options) => async () => {\n try {\n const config = envVarSelector(process.env, options);\n if (config === undefined) {\n throw new Error();\n }\n return config;\n }\n catch (e) {\n throw new propertyProvider.CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger });\n }\n};\n\nconst fromSharedConfigFiles = (configSelector, { preferredFile = \"config\", ...init } = {}) => async () => {\n const profile = sharedIniFileLoader.getProfileName(init);\n const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init);\n const profileFromCredentials = credentialsFile[profile] || {};\n const profileFromConfig = configFile[profile] || {};\n const mergedProfile = preferredFile === \"config\"\n ? { ...profileFromCredentials, ...profileFromConfig }\n : { ...profileFromConfig, ...profileFromCredentials };\n try {\n const cfgFile = preferredFile === \"config\" ? configFile : credentialsFile;\n const configValue = configSelector(mergedProfile, cfgFile);\n if (configValue === undefined) {\n throw new Error();\n }\n return configValue;\n }\n catch (e) {\n throw new propertyProvider.CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger });\n }\n};\n\nconst isFunction = (func) => typeof func === \"function\";\nconst fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue);\n\nconst loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => {\n const { signingName, logger } = configuration;\n const envOptions = { signingName, logger };\n return propertyProvider.memoize(propertyProvider.chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue)));\n};\n\nexports.loadConfig = loadConfig;\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";oJAEA,FAAI,AACA,MAEJ,SAAS,CAAe,CAAC,EAAgB,CACrC,GAAI,CACA,IAAM,EAAY,IAAI,IAAI,MAAM,KAAK,EAAe,MAAM,eAAe,GAAK,CAAC,CAAC,CAAC,EAIjF,OAHA,EAAU,OAAO,QAAQ,EACzB,EAAU,OAAO,yBAAyB,EAC1C,EAAU,OAAO,KAAK,EACf,CAAC,GAAG,CAAS,EAAE,KAAK,IAAI,EAEnC,MAAO,EAAG,CACN,OAAO,GAIf,IAAM,EAAU,CAAC,EAAgB,IAAY,SAAY,CACrD,GAAI,CACA,IAAM,EAAS,EAAe,QAAQ,IAAK,CAAO,EAClD,GAAI,IAAW,OACX,MAAU,MAAM,EAEpB,OAAO,EAEX,MAAO,EAAG,CACN,MAAM,IAAI,EAAiB,yBAAyB,EAAE,SAAW,qBAAqB,EAAgB,EAAe,SAAS,CAAC,IAAK,CAAE,OAAQ,GAAS,MAAO,CAAC,IAIjK,EAAwB,CAAC,GAAkB,gBAAgB,YAAa,GAAS,CAAC,IAAM,SAAY,CACtG,IAAM,EAAU,EAAoB,eAAe,CAAI,GAC/C,aAAY,mBAAoB,MAAM,EAAoB,sBAAsB,CAAI,EACtF,EAAyB,EAAgB,IAAY,CAAC,EACtD,EAAoB,EAAW,IAAY,CAAC,EAC5C,EAAgB,IAAkB,SAClC,IAAK,KAA2B,CAAkB,EAClD,IAAK,KAAsB,CAAuB,EACxD,GAAI,CAEA,IAAM,EAAc,EAAe,EADnB,IAAkB,SAAW,EAAa,CACD,EACzD,GAAI,IAAgB,OAChB,MAAU,MAAM,EAEpB,OAAO,EAEX,MAAO,EAAG,CACN,MAAM,IAAI,EAAiB,yBAAyB,EAAE,SAAW,yCAAyC,OAAa,EAAgB,EAAe,SAAS,CAAC,IAAK,CAAE,OAAQ,EAAK,MAAO,CAAC,IAI9L,EAAa,CAAC,IAAS,OAAO,IAAS,WACvC,EAAa,CAAC,IAAiB,EAAW,CAAY,EAAI,SAAY,MAAM,EAAa,EAAI,EAAiB,WAAW,CAAY,EAErI,EAAa,EAAG,8BAA6B,qBAAoB,QAAS,GAAgB,EAAgB,CAAC,IAAM,CACnH,IAAQ,cAAa,UAAW,EAC1B,EAAa,CAAE,cAAa,QAAO,EACzC,OAAO,EAAiB,QAAQ,EAAiB,MAAM,EAAQ,EAA6B,CAAU,EAAG,EAAsB,EAAoB,CAAa,EAAG,EAAW,CAAY,CAAC,CAAC,GAGxL,aAAa",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "4643DCF4CD43A3E264756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{P as ue}from"./chunk-szr1k584.js";import{Q as w}from"./chunk-k2fh4r0p.js";import{_}from"./chunk-p3zmc8k8.js";import"./chunk-dbwhgyg3.js";import{aa as l}from"./chunk-3f1kq32g.js";import{Uh as o,Yh as d}from"./chunk-8mbyyh8j.js";var g=o(_(),1);var ie=o(l(),1);var O=o(w(),1),R=o(l(),1),J=o(_(),1);var j=o(w(),1),E=o(l(),1),U=(e,s,t)=>{let n={EcsContainer:async(r)=>{let{fromHttp:a}=await import("./chunk-sr18y2ck.js"),{fromContainerMetadata:c}=await import("./chunk-kexsfyjj.js");return t?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>E.chain(a(r??{}),c(r))().then(L)},Ec2InstanceMetadata:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-kexsfyjj.js");return async()=>a(r)().then(L)},Environment:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-y6frz1vm.js");return async()=>a(r)().then(L)}};if(e in n)return n[e];else throw new E.CredentialsProviderError(`Unsupported credential source in profile ${s}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:t})},L=(e)=>j.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var N=(e,{profile:s="default",logger:t}={})=>{return Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(he(e,{profile:s,logger:t})||ye(e,{profile:s,logger:t}))},he=(e,{profile:s,logger:t})=>{let n=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(n)t?.debug?.(` ${s} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return n},ye=(e,{profile:s,logger:t})=>{let n=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(n)t?.debug?.(` ${s} isCredentialSourceProfile credential_source=${e.credential_source}`);return n},v=async(e,s,t,n,r={},a)=>{t.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let c=s[e],{source_profile:h,region:I}=c;if(!t.roleAssumer){let{getDefaultRoleAssumer:i}=await import("./chunk-qt8nvpqp.js").then((m)=>o(m.default,1));t.roleAssumer=i({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...n,...t?.parentClientConfig,region:I??t?.parentClientConfig?.region??n?.region}},t.clientPlugins)}if(h&&h in r)throw new R.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${J.getProfileName(t)}. Profiles visited: `+Object.keys(r).join(", "),{logger:t.logger});t.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${h?`source_profile=[${h}]`:`profile=[${e}]`}`);let T=h?a(h,s,t,n,{...r,[h]:!0},G(s[h]??{})):(await U(c.credential_source,e,t.logger)(t))();if(G(c))return T.then((i)=>O.setCredentialFeature(i,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let i={RoleArn:c.role_arn,RoleSessionName:c.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:c.external_id,DurationSeconds:parseInt(c.duration_seconds||"3600",10)},{mfa_serial:u}=c;if(u){if(!t.mfaCodeProvider)throw new R.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:t.logger,tryNextLink:!1});i.SerialNumber=u,i.TokenCode=await t.mfaCodeProvider(u)}let y=await T;return t.roleAssumer(y,i).then((m)=>O.setCredentialFeature(m,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},G=(e)=>{return!e.role_arn&&!!e.credential_source};var V=o(w(),1);var C=o(w(),1),X=o(l(),1),K=o(_(),1);var k=o(l(),1),W=o(ue(),1),z=o(_(),1);import{createHash as de,createPrivateKey as we,createPublicKey as ke,sign as me}from"crypto";import{promises as D}from"fs";import{homedir as fe}from"os";import{dirname as Ie,join as Y}from"path";class b{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(e,s,t){this.profileData=e,this.init=s,this.callerClientConfig=t}async loadCredentials(){let e=await this.loadToken();if(!e)throw new k.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let s=e.accessToken,t=Date.now();if(new Date(s.expiresAt).getTime()-t<=b.REFRESH_THRESHOLD)return this.refresh(e);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,accountId:s.accountId,expiration:new Date(s.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){let{SigninClient:s,CreateOAuth2TokenCommand:t}=await import("./chunk-wr3e4sez.js").then((m)=>o(m.default,1)),{logger:n,userAgentAppId:r}=this.callerClientConfig??{},c=((i)=>{return i?.metadata?.handlerProtocol==="h2"})(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,I=new s({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:c,logger:n,userAgentAppId:r,...this.init?.clientConfig});this.createDPoPInterceptor(I.middlewareStack);let T={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{let i=await I.send(new t(T)),{accessKeyId:u,secretAccessKey:y,sessionToken:m}=i.tokenOutput?.accessToken??{},{refreshToken:x,expiresIn:H}=i.tokenOutput??{};if(!u||!y||!m||!x)throw new k.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let A=(H??900)*1000,f=new Date(Date.now()+A),q={...e,accessToken:{...e.accessToken,accessKeyId:u,secretAccessKey:y,sessionToken:m,expiresAt:f.toISOString()},refreshToken:x};await this.saveToken(q);let S=q.accessToken;return{accessKeyId:S.accessKeyId,secretAccessKey:S.secretAccessKey,sessionToken:S.sessionToken,accountId:S.accountId,expiration:f}}catch(i){if(i.name==="AccessDeniedException"){let u=i.error,y;switch(u){case"TOKEN_EXPIRED":y="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":y="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":y="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:y=`Failed to refresh token: ${String(i)}. Please re-authenticate using \`aws login\``}throw new k.CredentialsProviderError(y,{logger:this.logger,tryNextLink:!1})}throw new k.CredentialsProviderError(`Failed to refresh token: ${String(i)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let s;try{s=await z.readFile(e,{ignoreCache:this.init?.ignoreCache})}catch{s=await D.readFile(e,"utf8")}let t=JSON.parse(s),n=["accessToken","clientId","refreshToken","dpopKey"].filter((r)=>!t[r]);if(!t.accessToken?.accountId)n.push("accountId");if(n.length>0)throw new k.CredentialsProviderError(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return t}catch(s){throw new k.CredentialsProviderError(`Failed to load token from ${e}: ${String(s)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let s=this.getTokenFilePath(),t=Ie(s);try{await D.mkdir(t,{recursive:!0})}catch(n){}await D.writeFile(s,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??Y(fe(),".aws","login","cache"),s=Buffer.from(this.loginSession,"utf8"),t=de("sha256").update(s).digest("hex");return Y(e,`${t}.json`)}derToRawSignature(e){let s=2;if(e[s]!==2)throw Error("Invalid DER signature");s++;let t=e[s++],n=e.subarray(s,s+t);if(s+=t,e[s]!==2)throw Error("Invalid DER signature");s++;let r=e[s++],a=e.subarray(s,s+r);n=n[0]===0?n.subarray(1):n,a=a[0]===0?a.subarray(1):a;let c=Buffer.concat([Buffer.alloc(32-n.length),n]),h=Buffer.concat([Buffer.alloc(32-a.length),a]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add((s)=>async(t)=>{if(W.HttpRequest.isInstance(t.request)){let n=t.request,r=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,a=await this.generateDpop(n.method,r);n.headers={...n.headers,DPoP:a}}return s(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",s){let t=await this.loadToken();try{let n=we({key:t.dpopKey,format:"pem",type:"sec1"}),a=ke(n).export({format:"der",type:"spki"}),c=-1;for(let f=0;f<a.length;f++)if(a[f]===4){c=f;break}let h=a.slice(c+1,c+33),I=a.slice(c+33,c+65),T={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:I.toString("base64url")}},i={jti:crypto.randomUUID(),htm:e,htu:s,iat:Math.floor(Date.now()/1000)},u=Buffer.from(JSON.stringify(T)).toString("base64url"),y=Buffer.from(JSON.stringify(i)).toString("base64url"),m=`${u}.${y}`,x=me("sha256",Buffer.from(m),n),A=this.derToRawSignature(x).toString("base64url");return`${m}.${A}`}catch(n){throw new k.CredentialsProviderError(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}}var Q=(e)=>async({callerClientConfig:s}={})=>{e?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await K.parseKnownFiles(e||{}),n=K.getProfileName({profile:e?.profile??s?.profile}),r=t[n];if(!r?.login_session)throw new X.CredentialsProviderError(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:e?.logger});let c=await new b(r,e,s).loadCredentials();return C.setCredentialFeature(c,"CREDENTIALS_LOGIN","AD")};var Z=(e)=>{return Boolean(e&&e.login_session)},M=async(e,s,t)=>{let n=await Q({...s,profile:e})({callerClientConfig:t});return V.setCredentialFeature(n,"CREDENTIALS_PROFILE_LOGIN","AC")};var p=o(w(),1),ee=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",te=async(e,s)=>import("./chunk-g8sc6scv.js").then(({fromProcess:t})=>t({...e,profile:s})().then((n)=>p.setCredentialFeature(n,"CREDENTIALS_PROFILE_PROCESS","v")));var $=o(w(),1),se=async(e,s,t={},n)=>{let{fromSSO:r}=await import("./chunk-essqp1ek.js");return r({profile:e,logger:t.logger,parentClientConfig:t.parentClientConfig,clientConfig:t.clientConfig})({callerClientConfig:n}).then((a)=>{if(s.sso_session)return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},ne=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var ce=o(w(),1),P=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,F=async(e,s)=>{s?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let t={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return ce.setCredentialFeature(t,"CREDENTIALS_PROFILE","n")};var re=o(w(),1),ae=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,oe=async(e,s,t)=>import("./chunk-4tp2cr02.js").then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:s.roleAssumerWithWebIdentity,logger:s.logger,parentClientConfig:s.parentClientConfig})({callerClientConfig:t}).then((r)=>re.setCredentialFeature(r,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")));var B=async(e,s,t,n,r={},a=!1)=>{let c=s[e];if(Object.keys(r).length>0&&P(c))return F(c,t);if(a||N(c,{profile:e,logger:t.logger}))return v(e,s,t,n,r,B);if(P(c))return F(c,t);if(ae(c))return oe(c,t,n);if(ee(c))return te(t,e);if(ne(c))return await se(e,c,t,n);if(Z(c))return M(e,t,n);throw new ie.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:t.logger})};var Ne=(e={})=>async({callerClientConfig:s}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let t=await g.parseKnownFiles(e);return B(g.getProfileName({profile:e.profile??s?.profile}),t,e,s)};export{Ne as fromIni};
|
|
2
|
+
import{P as ue}from"./chunk-ap5gek56.js";import{Q as w}from"./chunk-m2yfvwrn.js";import{_}from"./chunk-gdmsn3f5.js";import"./chunk-jk97wv0q.js";import{aa as l}from"./chunk-2rphhsr7.js";import{pi as o,ti as d}from"./chunk-e6fp6dxx.js";var g=o(_(),1);var ie=o(l(),1);var O=o(w(),1),R=o(l(),1),J=o(_(),1);var j=o(w(),1),E=o(l(),1),U=(e,s,t)=>{let n={EcsContainer:async(r)=>{let{fromHttp:a}=await import("./chunk-tp3mzj4v.js"),{fromContainerMetadata:c}=await import("./chunk-yp5979we.js");return t?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>E.chain(a(r??{}),c(r))().then(L)},Ec2InstanceMetadata:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-yp5979we.js");return async()=>a(r)().then(L)},Environment:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-gv91vjeb.js");return async()=>a(r)().then(L)}};if(e in n)return n[e];else throw new E.CredentialsProviderError(`Unsupported credential source in profile ${s}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:t})},L=(e)=>j.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var N=(e,{profile:s="default",logger:t}={})=>{return Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(he(e,{profile:s,logger:t})||ye(e,{profile:s,logger:t}))},he=(e,{profile:s,logger:t})=>{let n=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(n)t?.debug?.(` ${s} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return n},ye=(e,{profile:s,logger:t})=>{let n=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(n)t?.debug?.(` ${s} isCredentialSourceProfile credential_source=${e.credential_source}`);return n},v=async(e,s,t,n,r={},a)=>{t.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let c=s[e],{source_profile:h,region:I}=c;if(!t.roleAssumer){let{getDefaultRoleAssumer:i}=await import("./chunk-1p0dazvk.js").then((m)=>o(m.default,1));t.roleAssumer=i({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...n,...t?.parentClientConfig,region:I??t?.parentClientConfig?.region??n?.region}},t.clientPlugins)}if(h&&h in r)throw new R.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${J.getProfileName(t)}. Profiles visited: `+Object.keys(r).join(", "),{logger:t.logger});t.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${h?`source_profile=[${h}]`:`profile=[${e}]`}`);let T=h?a(h,s,t,n,{...r,[h]:!0},G(s[h]??{})):(await U(c.credential_source,e,t.logger)(t))();if(G(c))return T.then((i)=>O.setCredentialFeature(i,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let i={RoleArn:c.role_arn,RoleSessionName:c.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:c.external_id,DurationSeconds:parseInt(c.duration_seconds||"3600",10)},{mfa_serial:u}=c;if(u){if(!t.mfaCodeProvider)throw new R.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:t.logger,tryNextLink:!1});i.SerialNumber=u,i.TokenCode=await t.mfaCodeProvider(u)}let y=await T;return t.roleAssumer(y,i).then((m)=>O.setCredentialFeature(m,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},G=(e)=>{return!e.role_arn&&!!e.credential_source};var V=o(w(),1);var C=o(w(),1),X=o(l(),1),K=o(_(),1);var k=o(l(),1),W=o(ue(),1),z=o(_(),1);import{createHash as de,createPrivateKey as we,createPublicKey as ke,sign as me}from"crypto";import{promises as D}from"fs";import{homedir as fe}from"os";import{dirname as Ie,join as Y}from"path";class b{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(e,s,t){this.profileData=e,this.init=s,this.callerClientConfig=t}async loadCredentials(){let e=await this.loadToken();if(!e)throw new k.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let s=e.accessToken,t=Date.now();if(new Date(s.expiresAt).getTime()-t<=b.REFRESH_THRESHOLD)return this.refresh(e);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,accountId:s.accountId,expiration:new Date(s.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){let{SigninClient:s,CreateOAuth2TokenCommand:t}=await import("./chunk-mqcy5vja.js").then((m)=>o(m.default,1)),{logger:n,userAgentAppId:r}=this.callerClientConfig??{},c=((i)=>{return i?.metadata?.handlerProtocol==="h2"})(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,I=new s({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:c,logger:n,userAgentAppId:r,...this.init?.clientConfig});this.createDPoPInterceptor(I.middlewareStack);let T={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{let i=await I.send(new t(T)),{accessKeyId:u,secretAccessKey:y,sessionToken:m}=i.tokenOutput?.accessToken??{},{refreshToken:x,expiresIn:H}=i.tokenOutput??{};if(!u||!y||!m||!x)throw new k.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let A=(H??900)*1000,f=new Date(Date.now()+A),q={...e,accessToken:{...e.accessToken,accessKeyId:u,secretAccessKey:y,sessionToken:m,expiresAt:f.toISOString()},refreshToken:x};await this.saveToken(q);let S=q.accessToken;return{accessKeyId:S.accessKeyId,secretAccessKey:S.secretAccessKey,sessionToken:S.sessionToken,accountId:S.accountId,expiration:f}}catch(i){if(i.name==="AccessDeniedException"){let u=i.error,y;switch(u){case"TOKEN_EXPIRED":y="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":y="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":y="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:y=`Failed to refresh token: ${String(i)}. Please re-authenticate using \`aws login\``}throw new k.CredentialsProviderError(y,{logger:this.logger,tryNextLink:!1})}throw new k.CredentialsProviderError(`Failed to refresh token: ${String(i)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let s;try{s=await z.readFile(e,{ignoreCache:this.init?.ignoreCache})}catch{s=await D.readFile(e,"utf8")}let t=JSON.parse(s),n=["accessToken","clientId","refreshToken","dpopKey"].filter((r)=>!t[r]);if(!t.accessToken?.accountId)n.push("accountId");if(n.length>0)throw new k.CredentialsProviderError(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return t}catch(s){throw new k.CredentialsProviderError(`Failed to load token from ${e}: ${String(s)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let s=this.getTokenFilePath(),t=Ie(s);try{await D.mkdir(t,{recursive:!0})}catch(n){}await D.writeFile(s,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??Y(fe(),".aws","login","cache"),s=Buffer.from(this.loginSession,"utf8"),t=de("sha256").update(s).digest("hex");return Y(e,`${t}.json`)}derToRawSignature(e){let s=2;if(e[s]!==2)throw Error("Invalid DER signature");s++;let t=e[s++],n=e.subarray(s,s+t);if(s+=t,e[s]!==2)throw Error("Invalid DER signature");s++;let r=e[s++],a=e.subarray(s,s+r);n=n[0]===0?n.subarray(1):n,a=a[0]===0?a.subarray(1):a;let c=Buffer.concat([Buffer.alloc(32-n.length),n]),h=Buffer.concat([Buffer.alloc(32-a.length),a]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add((s)=>async(t)=>{if(W.HttpRequest.isInstance(t.request)){let n=t.request,r=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,a=await this.generateDpop(n.method,r);n.headers={...n.headers,DPoP:a}}return s(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",s){let t=await this.loadToken();try{let n=we({key:t.dpopKey,format:"pem",type:"sec1"}),a=ke(n).export({format:"der",type:"spki"}),c=-1;for(let f=0;f<a.length;f++)if(a[f]===4){c=f;break}let h=a.slice(c+1,c+33),I=a.slice(c+33,c+65),T={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:I.toString("base64url")}},i={jti:crypto.randomUUID(),htm:e,htu:s,iat:Math.floor(Date.now()/1000)},u=Buffer.from(JSON.stringify(T)).toString("base64url"),y=Buffer.from(JSON.stringify(i)).toString("base64url"),m=`${u}.${y}`,x=me("sha256",Buffer.from(m),n),A=this.derToRawSignature(x).toString("base64url");return`${m}.${A}`}catch(n){throw new k.CredentialsProviderError(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}}var Q=(e)=>async({callerClientConfig:s}={})=>{e?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await K.parseKnownFiles(e||{}),n=K.getProfileName({profile:e?.profile??s?.profile}),r=t[n];if(!r?.login_session)throw new X.CredentialsProviderError(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:e?.logger});let c=await new b(r,e,s).loadCredentials();return C.setCredentialFeature(c,"CREDENTIALS_LOGIN","AD")};var Z=(e)=>{return Boolean(e&&e.login_session)},M=async(e,s,t)=>{let n=await Q({...s,profile:e})({callerClientConfig:t});return V.setCredentialFeature(n,"CREDENTIALS_PROFILE_LOGIN","AC")};var p=o(w(),1),ee=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",te=async(e,s)=>import("./chunk-y0wx6w80.js").then(({fromProcess:t})=>t({...e,profile:s})().then((n)=>p.setCredentialFeature(n,"CREDENTIALS_PROFILE_PROCESS","v")));var $=o(w(),1),se=async(e,s,t={},n)=>{let{fromSSO:r}=await import("./chunk-z32xfe8c.js");return r({profile:e,logger:t.logger,parentClientConfig:t.parentClientConfig,clientConfig:t.clientConfig})({callerClientConfig:n}).then((a)=>{if(s.sso_session)return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},ne=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var ce=o(w(),1),P=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,F=async(e,s)=>{s?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let t={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return ce.setCredentialFeature(t,"CREDENTIALS_PROFILE","n")};var re=o(w(),1),ae=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,oe=async(e,s,t)=>import("./chunk-awp3n119.js").then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:s.roleAssumerWithWebIdentity,logger:s.logger,parentClientConfig:s.parentClientConfig})({callerClientConfig:t}).then((r)=>re.setCredentialFeature(r,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")));var B=async(e,s,t,n,r={},a=!1)=>{let c=s[e];if(Object.keys(r).length>0&&P(c))return F(c,t);if(a||N(c,{profile:e,logger:t.logger}))return v(e,s,t,n,r,B);if(P(c))return F(c,t);if(ae(c))return oe(c,t,n);if(ee(c))return te(t,e);if(ne(c))return await se(e,c,t,n);if(Z(c))return M(e,t,n);throw new ie.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:t.logger})};var Ne=(e={})=>async({callerClientConfig:s}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let t=await g.parseKnownFiles(e);return B(g.getProfileName({profile:e.profile??s?.profile}),t,e,s)};export{Ne as fromIni};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=CBB4FDD521EEBEB964756E2164756E21
|
|
@@ -15,6 +15,6 @@
|
|
|
15
15
|
"import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => import(\"@aws-sdk/credential-provider-web-identity\").then(({ fromTokenFile }) => fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n})({\n callerClientConfig,\n}).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN\", \"q\")));\n"
|
|
16
16
|
],
|
|
17
17
|
"mappings": ";wQAAA,SCAA,UCAA,SACA,KACA,KCFA,eACA,WACa,EAA0B,CAAC,EAAkB,EAAa,IAAW,CAC9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,KAAU,CACrJ,IAAM,EAAO,EAAS,GACtB,GAAI,OAAO,KAAK,CAAe,EAAE,OAAS,GAAK,EAAqB,CAAI,EACpE,OAAO,EAAyB,EAAM,CAAO,EAEjD,GAAI,GAA6B,EAAoB,EAAM,CAAE,QAAS,EAAa,OAAQ,EAAQ,MAAO,CAAC,EACvG,OAAO,EAA6B,EAAa,EAAU,EAAS,EAAoB,EAAiB,CAAkB,EAE/H,GAAI,EAAqB,CAAI,EACzB,OAAO,EAAyB,EAAM,CAAO,EAEjD,GAAI,GAAqB,CAAI,EACzB,OAAO,GAA8B,EAAM,EAAS,CAAkB,EAE1E,GAAI,GAAiB,CAAI,EACrB,OAAO,GAA0B,EAAS,CAAW,EAEzD,GAAI,GAAa,CAAI,EACjB,OAAO,MAAM,GAAsB,EAAa,EAAM,EAAS,CAAkB,EAErF,GAAI,EAAe,CAAI,EACnB,OAAO,EAAwB,EAAa,EAAS,CAAkB,EAE3E,MAAM,IAAI,4BAAyB,iDAAiD,2CAAsD,CAAE,OAAQ,EAAQ,MAAO,CAAC,GD5BjK,IAAM,GAAU,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CACzE,EAAK,QAAQ,MAAM,4CAA4C,EAC/D,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAAmB,iBAAe,CACrC,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAM,CAAkB",
|
|
18
|
-
"debugId": "
|
|
18
|
+
"debugId": "CBB4FDD521EEBEB964756E2164756E21",
|
|
19
19
|
"names": []
|
|
20
20
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Q as T}from"./chunk-
|
|
2
|
+
import{Q as T}from"./chunk-m2yfvwrn.js";import{_ as A}from"./chunk-gdmsn3f5.js";import"./chunk-jk97wv0q.js";import{aa as y}from"./chunk-2rphhsr7.js";import{pi as r}from"./chunk-e6fp6dxx.js";var u=r(A(),1);var i=r(y(),1),E=r(A(),1);import{exec as d}from"child_process";import{promisify as I}from"util";var x=r(T(),1),_=(c,n,e)=>{if(n.Version!==1)throw Error(`Profile ${c} credential_process did not return Version 1.`);if(n.AccessKeyId===void 0||n.SecretAccessKey===void 0)throw Error(`Profile ${c} credential_process returned invalid credentials.`);if(n.Expiration){let w=new Date;if(new Date(n.Expiration)<w)throw Error(`Profile ${c} credential_process returned expired credentials.`)}let s=n.AccountId;if(!s&&e?.[c]?.aws_account_id)s=e[c].aws_account_id;let t={accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,...n.SessionToken&&{sessionToken:n.SessionToken},...n.Expiration&&{expiration:new Date(n.Expiration)},...n.CredentialScope&&{credentialScope:n.CredentialScope},...s&&{accountId:s}};return x.setCredentialFeature(t,"CREDENTIALS_PROCESS","w"),t};var K=async(c,n,e)=>{let s=n[c];if(n[c]){let t=s.credential_process;if(t!==void 0){let w=I(E.externalDataInterceptor?.getTokenRecord?.().exec??d);try{let{stdout:o}=await w(t),S;try{S=JSON.parse(o.trim())}catch{throw Error(`Profile ${c} credential_process returned invalid JSON.`)}return _(c,S,n)}catch(o){throw new i.CredentialsProviderError(o.message,{logger:e})}}else throw new i.CredentialsProviderError(`Profile ${c} did not contain credential_process.`,{logger:e})}else throw new i.CredentialsProviderError(`Profile ${c} could not be found in shared credentials file.`,{logger:e})};var R=(c={})=>async({callerClientConfig:n}={})=>{c.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");let e=await u.parseKnownFiles(c);return K(u.getProfileName({profile:c.profile??n?.profile}),e,c.logger)};export{R as fromProcess};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=9FE8CFC29CBC270864756E2164756E21
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const getValidatedProcessCredentials = (profileName, data, profiles) => {\n if (data.Version !== 1) {\n throw Error(`Profile ${profileName} credential_process did not return Version 1.`);\n }\n if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {\n throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);\n }\n if (data.Expiration) {\n const currentTime = new Date();\n const expireTime = new Date(data.Expiration);\n if (expireTime < currentTime) {\n throw Error(`Profile ${profileName} credential_process returned expired credentials.`);\n }\n }\n let accountId = data.AccountId;\n if (!accountId && profiles?.[profileName]?.aws_account_id) {\n accountId = profiles[profileName].aws_account_id;\n }\n const credentials = {\n accessKeyId: data.AccessKeyId,\n secretAccessKey: data.SecretAccessKey,\n ...(data.SessionToken && { sessionToken: data.SessionToken }),\n ...(data.Expiration && { expiration: new Date(data.Expiration) }),\n ...(data.CredentialScope && { credentialScope: data.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_PROCESS\", \"w\");\n return credentials;\n};\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";sNAAA,SCAA,SACA,KACA,SAAS,sBACT,oBAAS,aCHT,eACa,EAAiC,CAAC,EAAa,EAAM,IAAa,CAC3E,GAAI,EAAK,UAAY,EACjB,MAAM,MAAM,WAAW,gDAA0D,EAErF,GAAI,EAAK,cAAgB,QAAa,EAAK,kBAAoB,OAC3D,MAAM,MAAM,WAAW,oDAA8D,EAEzF,GAAI,EAAK,WAAY,CACjB,IAAM,EAAc,IAAI,KAExB,GADmB,IAAI,KAAK,EAAK,UAAU,EAC1B,EACb,MAAM,MAAM,WAAW,oDAA8D,EAG7F,IAAI,EAAY,EAAK,UACrB,GAAI,CAAC,GAAa,IAAW,IAAc,eACvC,EAAY,EAAS,GAAa,eAEtC,IAAM,EAAc,CAChB,YAAa,EAAK,YAClB,gBAAiB,EAAK,mBAClB,EAAK,cAAgB,CAAE,aAAc,EAAK,YAAa,KACvD,EAAK,YAAc,CAAE,WAAY,IAAI,KAAK,EAAK,UAAU,CAAE,KAC3D,EAAK,iBAAmB,CAAE,gBAAiB,EAAK,eAAgB,KAChE,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,sBAAuB,GAAG,EACrD,GDvBJ,IAAM,EAA4B,MAAO,EAAa,EAAU,IAAW,CAC9E,IAAM,EAAU,EAAS,GACzB,GAAI,EAAS,GAAc,CACvB,IAAM,EAAoB,EAAQ,mBAClC,GAAI,IAAsB,OAAW,CACjC,IAAM,EAAc,EAAU,2BAAyB,iBAAiB,EAAE,MAAQ,CAAI,EACtF,GAAI,CACA,IAAQ,UAAW,MAAM,EAAY,CAAiB,EAClD,EACJ,GAAI,CACA,EAAO,KAAK,MAAM,EAAO,KAAK,CAAC,EAEnC,KAAM,CACF,MAAM,MAAM,WAAW,6CAAuD,EAElF,OAAO,EAA+B,EAAa,EAAM,CAAQ,EAErE,MAAO,EAAO,CACV,MAAM,IAAI,2BAAyB,EAAM,QAAS,CAAE,QAAO,CAAC,GAIhE,WAAM,IAAI,2BAAyB,WAAW,wCAAmD,CAAE,QAAO,CAAC,EAI/G,WAAM,IAAI,2BAAyB,WAAW,mDAA8D,CACxG,QACJ,CAAC,GD/BF,IAAM,EAAc,CAAC,EAAO,CAAC,IAAM,OAAS,sBAAuB,CAAC,IAAM,CAC7E,EAAK,QAAQ,MAAM,oDAAoD,EACvE,IAAM,EAAW,MAAM,kBAAgB,CAAI,EAC3C,OAAO,EAA0B,iBAAe,CAC5C,QAAS,EAAK,SAAW,GAAoB,OACjD,CAAC,EAAG,EAAU,EAAK,MAAM",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "9FE8CFC29CBC270864756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Y as r}from"./chunk-
|
|
2
|
+
import{Y as r}from"./chunk-x157wrgy.js";import{Z as mc}from"./chunk-hrvzchxd.js";import"./chunk-gdmsn3f5.js";import"./chunk-jk97wv0q.js";import{aa as _}from"./chunk-2rphhsr7.js";import{pi as u,si as O}from"./chunk-e6fp6dxx.js";import{Buffer as hc}from"buffer";import{request as Yc}from"http";function E(c){return new Promise((I,x)=>{let N=Yc({method:"GET",...c,hostname:c.hostname?.replace(/^\[(.+)\]$/,"$1")});N.on("error",(T)=>{x(Object.assign(new K.ProviderError("Unable to connect to instance metadata service"),T)),N.destroy()}),N.on("timeout",()=>{x(new K.ProviderError("TimeoutError from instance metadata service")),N.destroy()}),N.on("response",(T)=>{let{statusCode:y=400}=T;if(y<200||300<=y)x(Object.assign(new K.ProviderError("Error response received from instance metadata service"),{statusCode:y})),N.destroy();let $=[];T.on("data",(w)=>{$.push(w)}),T.on("end",()=>{I(hc.concat($)),N.destroy()})}),N.end()})}var K;var D=O(()=>{K=u(_(),1)});var G=(c)=>Boolean(c)&&typeof c==="object"&&typeof c.AccessKeyId==="string"&&typeof c.SecretAccessKey==="string"&&typeof c.Token==="string"&&typeof c.Expiration==="string",L=(c)=>({accessKeyId:c.AccessKeyId,secretAccessKey:c.SecretAccessKey,sessionToken:c.Token,expiration:new Date(c.Expiration),...c.AccountId&&{accountId:c.AccountId}});var W=()=>{};var Hc=1000,qc=0,Q=({maxRetries:c=0,timeout:I=1000})=>({maxRetries:c,timeout:I});var X=()=>{};var v=(c,I)=>{let x=c();for(let N=0;N<I;N++)x=x.catch(c);return x};var b=()=>{};import{parse as Sc}from"url";var z,H="AWS_CONTAINER_CREDENTIALS_FULL_URI",q="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",M="AWS_CONTAINER_AUTHORIZATION_TOKEN",kc=(c={})=>{let{timeout:I,maxRetries:x}=Q(c);return()=>v(async()=>{let N=await jc({logger:c.logger}),T=JSON.parse(await fc(I,N));if(!G(T))throw new z.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:c.logger});return L(T)},x)},fc=async(c,I)=>{if(process.env[M])I.headers={...I.headers,Authorization:process.env[M]};return(await E({...I,timeout:c})).toString()},uc="169.254.170.2",Ec,$c,jc=async({logger:c})=>{if(process.env[q])return{hostname:uc,path:process.env[q]};if(process.env[H]){let I=Sc(process.env[H]);if(!I.hostname||!(I.hostname in Ec))throw new z.CredentialsProviderError(`${I.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:c});if(!I.protocol||!(I.protocol in $c))throw new z.CredentialsProviderError(`${I.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:c});return{...I,port:I.port?parseInt(I.port,10):void 0}}throw new z.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${q} or ${H} environment variable is set`,{tryNextLink:!1,logger:c})};var p=O(()=>{D();W();X();b();z=u(_(),1),Ec={localhost:!0,"127.0.0.1":!0},$c={"http:":!0,"https:":!0}});var C,Z;var a=O(()=>{C=u(_(),1);Z=class Z extends C.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(c,I=!0){super(c,I);this.tryNextLink=I,Object.setPrototypeOf(this,Z.prototype)}}});var J;var B=O(()=>{(function(c){c.IPv4="http://169.254.169.254",c.IPv6="http://[fd00:ec2::254]"})(J||(J={}))});var n;var o=O(()=>{n={environmentVariableSelector:(c)=>c.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(c)=>c.ec2_metadata_service_endpoint,default:void 0}});var f;var t=O(()=>{(function(c){c.IPv4="IPv4",c.IPv6="IPv6"})(f||(f={}))});var Ac="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",Jc="ec2_metadata_service_endpoint_mode",s;var g=O(()=>{t();s={environmentVariableSelector:(c)=>c[Ac],configFileSelector:(c)=>c[Jc],default:f.IPv4}});var U,l,F=async()=>l.parseUrl(await vc()||await zc()),vc=async()=>U.loadConfig(n)(),zc=async()=>{let c=await U.loadConfig(s)();switch(c){case f.IPv4:return J.IPv4;case f.IPv6:return J.IPv6;default:throw Error(`Unsupported endpoint mode: ${c}. Select from ${Object.values(f)}`)}};var P=O(()=>{B();o();t();g();U=u(r(),1),l=u(mc(),1)});var V=(c,I)=>{let x=300+Math.floor(Math.random()*300),N=new Date(Date.now()+x*1000);I.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(N)}.
|
|
3
3
|
For more information, please visit: https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html`);let T=c.originalExpiration??c.expiration;return{...c,...T?{originalExpiration:T}:{},expiration:N}};var d=()=>{};var e=(c,I={})=>{let x=I?.logger||console,N;return async()=>{let T;try{if(T=await c(),T.expiration&&T.expiration.getTime()<Date.now())T=V(T,x)}catch(y){if(N)x.warn("Credential renew failed: ",y),T=V(N,x);else throw y}return N=T,T}};var i=O(()=>{d()});var Nc,k,Tc="/latest/meta-data/iam/security-credentials/",Kc="/latest/api/token",R="AWS_EC2_METADATA_V1_DISABLED",cc="ec2_metadata_v1_disabled",Ic="x-aws-ec2-metadata-token",YI=(c={})=>e(_c(c),{logger:c.logger}),_c=(c={})=>{let I=!1,{logger:x,profile:N}=c,{timeout:T,maxRetries:y}=Q(c),$=async(w,j)=>{if(I||j.headers?.[Ic]==null){let h=!1,Y=!1,wc=await Nc.loadConfig({environmentVariableSelector:(S)=>{let A=S[R];if(Y=!!A&&A!=="false",A===void 0)throw new k.CredentialsProviderError(`${R} not set in env, checking config file next.`,{logger:c.logger});return Y},configFileSelector:(S)=>{let A=S[cc];return h=!!A&&A!=="false",h},default:!1},{profile:N})();if(c.ec2MetadataV1Disabled||wc){let S=[];if(c.ec2MetadataV1Disabled)S.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");if(h)S.push(`config file profile (${cc})`);if(Y)S.push(`process environment variable (${R})`);throw new Z(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${S.join(", ")}].`)}}let yc=(await v(async()=>{let h;try{h=await Gc(j)}catch(Y){if(Y.statusCode===401)I=!1;throw Y}return h},w)).trim();return v(async()=>{let h;try{h=await Lc(yc,j,c)}catch(Y){if(Y.statusCode===401)I=!1;throw Y}return h},w)};return async()=>{let w=await F();if(I)return x?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),$(y,{...w,timeout:T});else{let j;try{j=(await Dc({...w,timeout:T})).toString()}catch(m){if(m?.statusCode===400)throw Object.assign(m,{message:"EC2 Metadata token request returned error"});else if(m.message==="TimeoutError"||[403,404,405].includes(m.statusCode))I=!0;return x?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),$(y,{...w,timeout:T})}return $(y,{...w,headers:{[Ic]:j},timeout:T})}}},Dc=async(c)=>E({...c,path:Kc,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),Gc=async(c)=>(await E({...c,path:Tc})).toString(),Lc=async(c,I,x)=>{let N=JSON.parse((await E({...I,path:Tc+c})).toString());if(!G(N))throw new k.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:x.logger});return L(N)};var xc=O(()=>{a();D();W();X();b();P();i();Nc=u(r(),1),k=u(_(),1)});var Oc=()=>{};var Qc=O(()=>{D();P();B();p();xc();X();Oc()});Qc();export{Q as providerConfigFromInit,E as httpRequest,F as getInstanceMetadataEndpoint,YI as fromInstanceMetadata,kc as fromContainerMetadata,J as Endpoint,q as ENV_CMDS_RELATIVE_URI,H as ENV_CMDS_FULL_URI,M as ENV_CMDS_AUTH_TOKEN,Hc as DEFAULT_TIMEOUT,qc as DEFAULT_MAX_RETRIES};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=47E1744E6AF5D93364756E2164756E21
|
|
@@ -19,6 +19,6 @@
|
|
|
19
19
|
"export * from \"./fromContainerMetadata\";\nexport * from \"./fromInstanceMetadata\";\nexport * from \"./remoteProvider/RemoteProviderInit\";\nexport * from \"./types\";\nexport { httpRequest } from \"./remoteProvider/httpRequest\";\nexport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nexport { Endpoint } from \"./config/Endpoint\";\n"
|
|
20
20
|
],
|
|
21
21
|
"mappings": ";iQACA,WAAS,UACT,YAAS,QACF,GAAS,CAAW,CAAC,EAAS,CACjC,OAAO,IAAI,QAAQ,CAA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A6B,6BAA6B,EACjE,EAAe,EAAY,IAAK,EAAU,SAAQ,CAAC,EAE9D,OAAO,EAAe,EAAY,IAC3B,EACH,QAAS,EACJ,IAA2B,CAChC,EACA,SACJ,CAAC,KAIP,GAAmB,MAAO,IAAY,EAAY,IACjD,EACH,KAAM,GACN,OAAQ,MACR,QAAS,CACL,uCAAwC,OAC5C,CACJ,CAAC,EACK,GAAa,MAAO,KAAa,MAAM,EAAY,IAAK,EAAS,KAAM,EAAU,CAAC,GAAG,SAAS,EAC9F,GAA4B,MAAO,EAAS,EAAS,IAAS,CAChE,IAAM,EAAsB,KAAK,OAAO,MAAM,EAAY,IACnD,EACH,KAAM,GAAY,CACtB,CAAC,GAAG,SAAS,CAAC,EACd,GAAI,CAAC,EAAkB,CAAmB,EACtC,MAAM,IAAI,2BAAyB,4DAA6D,CAC5F,OAAQ,EAAK,MACjB,CAAC,EAEL,OAAO,EAAoB,CAAmB,iBAlIlD,IACA,IACA,IACA,IACA,IACA,IACA,IARA,YACA,yCCGA,IACA,IACA,IANA,IACA,KACA,IACA",
|
|
22
|
-
"debugId": "
|
|
22
|
+
"debugId": "47E1744E6AF5D93364756E2164756E21",
|
|
23
23
|
"names": []
|
|
24
24
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Q as ne}from"./chunk-
|
|
2
|
+
import{Q as ne}from"./chunk-m2yfvwrn.js";import{_ as C}from"./chunk-gdmsn3f5.js";import"./chunk-jk97wv0q.js";import{aa as _}from"./chunk-2rphhsr7.js";import{pi as c,ti as F}from"./chunk-e6fp6dxx.js";var x=c(_(),1),T=c(C(),1);var q=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var D=c(ne(),1);var u=c(_(),1),m=c(C(),1);var W=300000,h="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var j=async(e,o={},r)=>{let{SSOOIDCClient:t}=await import("./chunk-jv4g8grc.js").then((m)=>c(m.default,1)),n=(f)=>o.clientConfig?.[f]??o.parentClientConfig?.[f]??r?.[f];return new t(Object.assign({},o.clientConfig??{},{region:e??o.clientConfig?.region,logger:n("logger"),userAgentAppId:n("userAgentAppId")}))};var X=async(e,o,r={},t)=>{let{CreateTokenCommand:n}=await import("./chunk-jv4g8grc.js").then((m)=>c(m.default,1));return(await j(o,r,t)).send(new n({clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken,grantType:"refresh_token"}))};var z=c(_(),1);var P=(e)=>{if(e.expiration&&e.expiration.getTime()<Date.now())throw new z.TokenProviderError(`Token is expired. ${h}`,!1)};var J=c(_(),1);var g=(e,o,r=!1)=>{if(typeof o>"u")throw new J.TokenProviderError(`Value not present for '${e}' in SSO Token${r?". Cannot refresh":""}. ${h}`,!1)};var V=c(C(),1);import{promises as re}from"fs";var{writeFile:te}=re,Y=(e,o)=>{let r=V.getSSOTokenFilepath(e),t=JSON.stringify(o,null,2);return te(r,t)};var B=new Date(0),Q=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/token-providers - fromSso");let r=await m.parseKnownFiles(e),t=m.getProfileName({profile:e.profile??o?.profile}),n=r[t];if(!n)throw new u.TokenProviderError(`Profile '${t}' could not be found in shared credentials file.`,!1);else if(!n.sso_session)throw new u.TokenProviderError(`Profile '${t}' is missing required property 'sso_session'.`);let a=n.sso_session,p=(await m.loadSsoSessionData(e))[a];if(!p)throw new u.TokenProviderError(`Sso session '${a}' could not be found in shared credentials file.`,!1);for(let i of["sso_start_url","sso_region"])if(!p[i])throw new u.TokenProviderError(`Sso session '${a}' is missing required property '${i}'.`,!1);let{sso_start_url:S,sso_region:I}=p,s;try{s=await m.getSSOTokenFromFile(a)}catch(i){throw new u.TokenProviderError(`The SSO session token associated with profile=${t} was not found or is invalid. ${h}`,!1)}g("accessToken",s.accessToken),g("expiresAt",s.expiresAt);let{accessToken:y,expiresAt:E}=s,l={token:y,expiration:new Date(E)};if(l.expiration.getTime()-Date.now()>W)return l;if(Date.now()-B.getTime()<30000)return P(l),l;g("clientId",s.clientId,!0),g("clientSecret",s.clientSecret,!0),g("refreshToken",s.refreshToken,!0);try{B.setTime(Date.now());let i=await X(s,I,e,o);g("accessToken",i.accessToken),g("expiresIn",i.expiresIn);let O=new Date(Date.now()+i.expiresIn*1000);try{await Y(a,{...s,accessToken:i.accessToken,expiresAt:O.toISOString(),refreshToken:i.refreshToken})}catch(R){}return{token:i.accessToken,expiration:O}}catch(i){return P(l),l}};var k=c(_(),1),Z=c(C(),1),A=!1,$=async({ssoStartUrl:e,ssoSession:o,ssoAccountId:r,ssoRegion:t,ssoRoleName:n,ssoClient:a,clientConfig:f,parentClientConfig:p,callerClientConfig:S,profile:I,filepath:s,configFilepath:y,ignoreCache:E,logger:l})=>{let i,O="To refresh this SSO session run aws sso login with the corresponding profile.";if(o)try{let w=await Q({profile:I,filepath:s,configFilepath:y,ignoreCache:E})();i={accessToken:w.token,expiresAt:new Date(w.expiration).toISOString()}}catch(w){throw new k.CredentialsProviderError(w.message,{tryNextLink:A,logger:l})}else try{i=await Z.getSSOTokenFromFile(e)}catch(w){throw new k.CredentialsProviderError("The SSO session associated with this profile is invalid. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:A,logger:l})}if(new Date(i.expiresAt).getTime()-Date.now()<=0)throw new k.CredentialsProviderError("The SSO session associated with this profile has expired. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:A,logger:l});let{accessToken:R}=i,{SSOClient:d,GetRoleCredentialsCommand:N}=await import("./chunk-1f9sqht5.js"),se=a||new d(Object.assign({},f??{},{logger:f?.logger??S?.logger??p?.logger,region:f?.region??t,userAgentAppId:f?.userAgentAppId??S?.userAgentAppId??p?.userAgentAppId})),L;try{L=await se.send(new N({accountId:r,roleName:n,accessToken:R}))}catch(w){throw new k.CredentialsProviderError(w,{tryNextLink:A,logger:l})}let{roleCredentials:{accessKeyId:M,secretAccessKey:G,sessionToken:K,expiration:b,credentialScope:H,accountId:U}={}}=L;if(!M||!G||!K||!b)throw new k.CredentialsProviderError("SSO returns an invalid temporary credential.",{tryNextLink:A,logger:l});let v={accessKeyId:M,secretAccessKey:G,sessionToken:K,expiration:new Date(b),...H&&{credentialScope:H},...U&&{accountId:U}};if(o)D.setCredentialFeature(v,"CREDENTIALS_SSO","s");else D.setCredentialFeature(v,"CREDENTIALS_SSO_LEGACY","u");return v};var ee=c(_(),1),oe=(e,o)=>{let{sso_start_url:r,sso_account_id:t,sso_region:n,sso_role_name:a}=e;if(!r||!t||!n||!a)throw new ee.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(e).join(", ")}
|
|
3
3
|
Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:o});return e};var Ce=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");let{ssoStartUrl:r,ssoAccountId:t,ssoRegion:n,ssoRoleName:a,ssoSession:f}=e,{ssoClient:p}=e,S=T.getProfileName({profile:e.profile??o?.profile});if(!r&&!t&&!n&&!a&&!f){let s=(await T.parseKnownFiles(e))[S];if(!s)throw new x.CredentialsProviderError(`Profile ${S} was not found.`,{logger:e.logger});if(!q(s))throw new x.CredentialsProviderError(`Profile ${S} is not configured with SSO credentials.`,{logger:e.logger});if(s?.sso_session){let d=(await T.loadSsoSessionData(e))[s.sso_session],N=` configurations in profile ${S} and sso-session ${s.sso_session}`;if(n&&n!==d.sso_region)throw new x.CredentialsProviderError("Conflicting SSO region"+N,{tryNextLink:!1,logger:e.logger});if(r&&r!==d.sso_start_url)throw new x.CredentialsProviderError("Conflicting SSO start_url"+N,{tryNextLink:!1,logger:e.logger});s.sso_region=d.sso_region,s.sso_start_url=d.sso_start_url}let{sso_start_url:y,sso_account_id:E,sso_region:l,sso_role_name:i,sso_session:O}=oe(s,e.logger);return $({ssoStartUrl:y,ssoSession:O,ssoAccountId:E,ssoRegion:l,ssoRoleName:i,ssoClient:p,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:S,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})}else if(!r||!t||!n||!a)throw new x.CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',{tryNextLink:!1,logger:e.logger});else return $({ssoStartUrl:r,ssoSession:f,ssoAccountId:t,ssoRegion:n,ssoRoleName:a,ssoClient:p,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:S,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})};export{oe as validateSsoProfile,q as isSsoProfile,Ce as fromSSO};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=6579BB10BCB3668A64756E2164756E21
|
|
@@ -15,6 +15,6 @@
|
|
|
15
15
|
"import { CredentialsProviderError } from \"@smithy/property-provider\";\nexport const validateSsoProfile = (profile, logger) => {\n const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;\n if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {\n throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters \"sso_account_id\", ` +\n `\"sso_region\", \"sso_role_name\", \"sso_start_url\". Got ${Object.keys(profile).join(\", \")}\\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger });\n }\n return profile;\n};\n"
|
|
16
16
|
],
|
|
17
17
|
"mappings": ";+NAAA,SACA,KCDO,FAAM,JAAe,CAAC,IAAQ,IAChC,OAAO,EAAI,gBAAkB,UAC1B,OAAO,EAAI,iBAAmB,UAC9B,OAAO,EAAI,cAAgB,UAC3B,OAAO,EAAI,aAAe,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,mBACzB,QAAS,EACT,SAAU,EAAK,SACf,eAAgB,EAAK,eACrB,YAAa,EAAK,YAClB,OAAQ,EAAK,MACjB,CAAC",
|
|
18
|
-
"debugId": "
|
|
18
|
+
"debugId": "6579BB10BCB3668A64756E2164756E21",
|
|
19
19
|
"names": []
|
|
20
20
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{B as
|
|
2
|
+
import{Vh as x}from"./chunk-fv9mr1t4.js";function B(j){return j}function C(){return{supportedLocales:[],defaultLocale:"en-US",prefetch:{},components:{},detectLocale:()=>null,onLocaleChange:(j)=>{console.log(`Locale changed to ${j}`)},timeZone:x,detectTimeZone:()=>null}}
|
|
3
|
+
export{B as Jc,C as Kc};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
5
|
+
//# debugId=519BF2CF3FDE2D1564756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"import { DEFAULT_TIME_ZONE } from \"./formatter\";\nimport type { Dictionary } from \"./Dictionary\";\nimport type { HttpRequest } from \"../http/HttpRequest\";\n\n// Config key: `translation`. Derived from `I18nServiceProvider`.\nexport interface TranslationConfig {\n supportedLocales?: string[];\n defaultLocale?: string;\n /**\n * @deprecated Only for `Dictionary.create` dictionaries. A `defineDictionary`\n * dictionary needs no entry here — the component that reads it pulls it in,\n * and the bundler ships only the active locale.\n */\n prefetch?: Record<string, Array<Dictionary<any>>>;\n /** @deprecated Only for `Dictionary.create` dictionaries. See `prefetch`. */\n components?: Record<string, Dictionary<any>>;\n\n // Returning `null` falls back to gemi's own locale detection.\n detectLocale?: (req: HttpRequest) => string | null;\n onLocaleChange?: (locale: string) => Promise<void> | void;\n\n /**\n * The IANA time zone dates are formatted in by `useFormatter`,\n * `useDictionary(...).format` and `Lang.formatter()`. Defaults to `UTC`.\n *\n * One zone for server and browser alike, so a server-rendered date and its\n * hydrated copy print the same text. Override per call with\n * `format.date(value, { timeZone })`.\n */\n timeZone?: string;\n /**\n * Resolve the zone for one request, e.g. from a cookie or the signed-in\n * user's profile. Returning `null` (or a zone `Intl` does not know) falls back\n * to `timeZone`. Runs on the server; the result ships with the page.\n */\n detectTimeZone?: (req: HttpRequest) => string | null;\n}\n\nexport function defineTranslationConfig(\n config: TranslationConfig,\n): TranslationConfig {\n return config;\n}\n\nexport function translationConfigDefaults(): Required<TranslationConfig> {\n return {\n supportedLocales: [],\n defaultLocale: \"en-US\",\n prefetch: {},\n components: {},\n detectLocale: () => null,\n onLocaleChange: (locale) => {\n console.log(`Locale changed to ${locale}`);\n },\n timeZone: DEFAULT_TIME_ZONE,\n detectTimeZone: () => null,\n };\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";yCAsCO,SAAS,CAAuB,CACrC,EACmB,CACnB,OAAO,EAGF,SAAS,CAAyB,EAAgC,CACvE,MAAO,CACL,iBAAkB,CAAC,EACnB,cAAe,QACf,SAAU,CAAC,EACX,WAAY,CAAC,EACb,aAAc,IAAM,KACpB,eAAgB,CAAC,IAAW,CAC1B,QAAQ,IAAI,qBAAqB,GAAQ,GAE3C,SAAU,EACV,eAAgB,IAAM,IACxB",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "519BF2CF3FDE2D1564756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|