@geminixiang/mama 0.2.0-beta.1 → 0.2.0-beta.10
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/README.md +168 -371
- package/dist/adapter.d.ts +36 -12
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js.map +1 -1
- package/dist/adapters/discord/bot.d.ts +12 -7
- package/dist/adapters/discord/bot.d.ts.map +1 -1
- package/dist/adapters/discord/bot.js +358 -135
- package/dist/adapters/discord/bot.js.map +1 -1
- package/dist/adapters/discord/context.d.ts +1 -1
- package/dist/adapters/discord/context.d.ts.map +1 -1
- package/dist/adapters/discord/context.js +100 -36
- package/dist/adapters/discord/context.js.map +1 -1
- package/dist/adapters/shared.d.ts +71 -0
- package/dist/adapters/shared.d.ts.map +1 -0
- package/dist/adapters/shared.js +168 -0
- package/dist/adapters/shared.js.map +1 -0
- package/dist/adapters/slack/bot.d.ts +30 -24
- package/dist/adapters/slack/bot.d.ts.map +1 -1
- package/dist/adapters/slack/bot.js +620 -224
- package/dist/adapters/slack/bot.js.map +1 -1
- package/dist/adapters/slack/branch-manager.d.ts +22 -0
- package/dist/adapters/slack/branch-manager.d.ts.map +1 -0
- package/dist/adapters/slack/branch-manager.js +97 -0
- package/dist/adapters/slack/branch-manager.js.map +1 -0
- package/dist/adapters/slack/context.d.ts +1 -1
- package/dist/adapters/slack/context.d.ts.map +1 -1
- package/dist/adapters/slack/context.js +127 -72
- package/dist/adapters/slack/context.js.map +1 -1
- package/dist/adapters/slack/session.d.ts +3 -0
- package/dist/adapters/slack/session.d.ts.map +1 -0
- package/dist/adapters/slack/session.js +16 -0
- package/dist/adapters/slack/session.js.map +1 -0
- package/dist/adapters/slack/tools/attach.d.ts +1 -1
- package/dist/adapters/slack/tools/attach.d.ts.map +1 -1
- package/dist/adapters/slack/tools/attach.js.map +1 -1
- package/dist/adapters/telegram/bot.d.ts +4 -2
- package/dist/adapters/telegram/bot.d.ts.map +1 -1
- package/dist/adapters/telegram/bot.js +193 -147
- package/dist/adapters/telegram/bot.js.map +1 -1
- package/dist/adapters/telegram/context.d.ts.map +1 -1
- package/dist/adapters/telegram/context.js +58 -111
- package/dist/adapters/telegram/context.js.map +1 -1
- package/dist/adapters/telegram/html.d.ts +3 -0
- package/dist/adapters/telegram/html.d.ts.map +1 -0
- package/dist/adapters/telegram/html.js +98 -0
- package/dist/adapters/telegram/html.js.map +1 -0
- package/dist/agent.d.ts +9 -13
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +601 -567
- package/dist/agent.js.map +1 -1
- package/dist/commands/auto-reply.d.ts +16 -0
- package/dist/commands/auto-reply.d.ts.map +1 -0
- package/dist/commands/auto-reply.js +69 -0
- package/dist/commands/auto-reply.js.map +1 -0
- package/dist/commands/index.d.ts +5 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/index.js +19 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/commands/login.d.ts +5 -0
- package/dist/commands/login.d.ts.map +1 -0
- package/dist/commands/login.js +76 -0
- package/dist/commands/login.js.map +1 -0
- package/dist/commands/model.d.ts +14 -0
- package/dist/commands/model.d.ts.map +1 -0
- package/dist/commands/model.js +112 -0
- package/dist/commands/model.js.map +1 -0
- package/dist/commands/new.d.ts +9 -0
- package/dist/commands/new.d.ts.map +1 -0
- package/dist/commands/new.js +28 -0
- package/dist/commands/new.js.map +1 -0
- package/dist/commands/registry.d.ts +7 -0
- package/dist/commands/registry.d.ts.map +1 -0
- package/dist/commands/registry.js +14 -0
- package/dist/commands/registry.js.map +1 -0
- package/dist/commands/sandbox.d.ts +10 -0
- package/dist/commands/sandbox.d.ts.map +1 -0
- package/dist/commands/sandbox.js +88 -0
- package/dist/commands/sandbox.js.map +1 -0
- package/dist/commands/session-view.d.ts +5 -0
- package/dist/commands/session-view.d.ts.map +1 -0
- package/dist/commands/session-view.js +62 -0
- package/dist/commands/session-view.js.map +1 -0
- package/dist/commands/types.d.ts +41 -0
- package/dist/commands/types.d.ts.map +1 -0
- package/dist/commands/types.js +2 -0
- package/dist/commands/types.js.map +1 -0
- package/dist/commands/utils.d.ts +8 -0
- package/dist/commands/utils.d.ts.map +1 -0
- package/dist/commands/utils.js +14 -0
- package/dist/commands/utils.js.map +1 -0
- package/dist/config.d.ts +49 -30
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +313 -75
- package/dist/config.js.map +1 -1
- package/dist/context.d.ts +10 -42
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +14 -127
- package/dist/context.js.map +1 -1
- package/dist/events.d.ts +13 -6
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +118 -64
- package/dist/events.js.map +1 -1
- package/dist/execution-resolver.d.ts +9 -5
- package/dist/execution-resolver.d.ts.map +1 -1
- package/dist/execution-resolver.js +82 -18
- package/dist/execution-resolver.js.map +1 -1
- package/dist/file-guards.d.ts +6 -0
- package/dist/file-guards.d.ts.map +1 -0
- package/dist/file-guards.js +48 -0
- package/dist/file-guards.js.map +1 -0
- package/dist/fs-atomic.d.ts +10 -0
- package/dist/fs-atomic.d.ts.map +1 -0
- package/dist/fs-atomic.js +45 -0
- package/dist/fs-atomic.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/instrument.d.ts.map +1 -1
- package/dist/instrument.js +4 -11
- package/dist/instrument.js.map +1 -1
- package/dist/log.d.ts +1 -5
- package/dist/log.d.ts.map +1 -1
- package/dist/log.js +13 -38
- package/dist/log.js.map +1 -1
- package/dist/{login.d.ts → login/index.d.ts} +16 -4
- package/dist/login/index.d.ts.map +1 -0
- package/dist/{login.js → login/index.js} +55 -17
- package/dist/login/index.js.map +1 -0
- package/dist/{link-server.d.ts → login/portal.d.ts} +7 -4
- package/dist/login/portal.d.ts.map +1 -0
- package/dist/login/portal.js +1453 -0
- package/dist/login/portal.js.map +1 -0
- package/dist/{link-token.d.ts → login/session.d.ts} +4 -3
- package/dist/login/session.d.ts.map +1 -0
- package/dist/{link-token.js → login/session.js} +1 -1
- package/dist/login/session.js.map +1 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +151 -373
- package/dist/main.js.map +1 -1
- package/dist/provisioner.d.ts +38 -52
- package/dist/provisioner.d.ts.map +1 -1
- package/dist/provisioner.js +212 -111
- package/dist/provisioner.js.map +1 -1
- package/dist/runtime/conversation-orchestrator.d.ts +42 -0
- package/dist/runtime/conversation-orchestrator.d.ts.map +1 -0
- package/dist/runtime/conversation-orchestrator.js +150 -0
- package/dist/runtime/conversation-orchestrator.js.map +1 -0
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.d.ts.map +1 -0
- package/dist/runtime/index.js +2 -0
- package/dist/runtime/index.js.map +1 -0
- package/dist/runtime/session-runtime.d.ts +27 -0
- package/dist/runtime/session-runtime.d.ts.map +1 -0
- package/dist/runtime/session-runtime.js +211 -0
- package/dist/runtime/session-runtime.js.map +1 -0
- package/dist/sandbox/cloudflare.d.ts +15 -0
- package/dist/sandbox/cloudflare.d.ts.map +1 -0
- package/dist/sandbox/cloudflare.js +137 -0
- package/dist/sandbox/cloudflare.js.map +1 -0
- package/dist/sandbox/container.d.ts +2 -1
- package/dist/sandbox/container.d.ts.map +1 -1
- package/dist/sandbox/container.js +5 -1
- package/dist/sandbox/container.js.map +1 -1
- package/dist/sandbox/firecracker.d.ts +2 -1
- package/dist/sandbox/firecracker.d.ts.map +1 -1
- package/dist/sandbox/firecracker.js +6 -0
- package/dist/sandbox/firecracker.js.map +1 -1
- package/dist/sandbox/host.d.ts +2 -3
- package/dist/sandbox/host.d.ts.map +1 -1
- package/dist/sandbox/host.js +5 -5
- package/dist/sandbox/host.js.map +1 -1
- package/dist/sandbox/index.d.ts +6 -4
- package/dist/sandbox/index.d.ts.map +1 -1
- package/dist/sandbox/index.js +9 -6
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/path-context.d.ts +4 -0
- package/dist/sandbox/path-context.d.ts.map +1 -0
- package/dist/sandbox/path-context.js +20 -0
- package/dist/sandbox/path-context.js.map +1 -0
- package/dist/sandbox/types.d.ts +17 -1
- package/dist/sandbox/types.d.ts.map +1 -1
- package/dist/sandbox/types.js.map +1 -1
- package/dist/sentry.d.ts +1 -1
- package/dist/sentry.d.ts.map +1 -1
- package/dist/sentry.js +4 -2
- package/dist/sentry.js.map +1 -1
- package/dist/session-policy.d.ts +13 -0
- package/dist/session-policy.d.ts.map +1 -0
- package/dist/session-policy.js +23 -0
- package/dist/session-policy.js.map +1 -0
- package/dist/session-store.d.ts +34 -3
- package/dist/session-store.d.ts.map +1 -1
- package/dist/session-store.js +184 -22
- package/dist/session-store.js.map +1 -1
- package/dist/session-view/command.d.ts +5 -0
- package/dist/session-view/command.d.ts.map +1 -0
- package/dist/session-view/command.js +11 -0
- package/dist/session-view/command.js.map +1 -0
- package/dist/session-view/portal.d.ts +16 -0
- package/dist/session-view/portal.d.ts.map +1 -0
- package/dist/session-view/portal.js +1742 -0
- package/dist/session-view/portal.js.map +1 -0
- package/dist/session-view/service.d.ts +34 -0
- package/dist/session-view/service.d.ts.map +1 -0
- package/dist/session-view/service.js +427 -0
- package/dist/session-view/service.js.map +1 -0
- package/dist/session-view/store.d.ts +18 -0
- package/dist/session-view/store.d.ts.map +1 -0
- package/dist/session-view/store.js +39 -0
- package/dist/session-view/store.js.map +1 -0
- package/dist/store.d.ts +3 -6
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +22 -48
- package/dist/store.js.map +1 -1
- package/dist/tool-diagnostics.d.ts +2 -0
- package/dist/tool-diagnostics.d.ts.map +1 -0
- package/dist/tool-diagnostics.js +7 -0
- package/dist/tool-diagnostics.js.map +1 -0
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.d.ts.map +1 -1
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/edit.d.ts +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/event.d.ts +43 -2
- package/dist/tools/event.d.ts.map +1 -1
- package/dist/tools/event.js +48 -13
- package/dist/tools/event.js.map +1 -1
- package/dist/tools/index.d.ts +2 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +3 -3
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/read.d.ts +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/write.d.ts +1 -1
- package/dist/tools/write.d.ts.map +1 -1
- package/dist/tools/write.js.map +1 -1
- package/dist/trigger.d.ts +31 -0
- package/dist/trigger.d.ts.map +1 -0
- package/dist/trigger.js +98 -0
- package/dist/trigger.js.map +1 -0
- package/dist/ui-copy.d.ts +1 -0
- package/dist/ui-copy.d.ts.map +1 -1
- package/dist/ui-copy.js +3 -0
- package/dist/ui-copy.js.map +1 -1
- package/dist/vault-routing.d.ts +1 -7
- package/dist/vault-routing.d.ts.map +1 -1
- package/dist/vault-routing.js +6 -48
- package/dist/vault-routing.js.map +1 -1
- package/dist/vault.d.ts +21 -55
- package/dist/vault.d.ts.map +1 -1
- package/dist/vault.js +138 -263
- package/dist/vault.js.map +1 -1
- package/package.json +12 -10
- package/dist/bindings.d.ts +0 -63
- package/dist/bindings.d.ts.map +0 -1
- package/dist/bindings.js +0 -94
- package/dist/bindings.js.map +0 -1
- package/dist/link-server.d.ts.map +0 -1
- package/dist/link-server.js +0 -839
- package/dist/link-server.js.map +0 -1
- package/dist/link-token.d.ts.map +0 -1
- package/dist/link-token.js.map +0 -1
- package/dist/login.d.ts.map +0 -1
- package/dist/login.js.map +0 -1
- package/dist/vault.test.d.ts +0 -2
- package/dist/vault.test.d.ts.map +0 -1
- package/dist/vault.test.js +0 -67
- package/dist/vault.test.js.map +0 -1
|
@@ -0,0 +1,1453 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "crypto";
|
|
2
|
+
import { createServer } from "http";
|
|
3
|
+
import { resolveLinkBaseUrl } from "../config.js";
|
|
4
|
+
import { handleSessionViewRequest, } from "../session-view/portal.js";
|
|
5
|
+
import { getOAuthServices, resolveOAuthService, } from "./index.js";
|
|
6
|
+
import * as log from "../log.js";
|
|
7
|
+
import { PRODUCT_NAME } from "../ui-copy.js";
|
|
8
|
+
import { defaultVaultTargetPath } from "../vault.js";
|
|
9
|
+
const OAUTH_STATE_TTL_MS = 10 * 60 * 1000;
|
|
10
|
+
const DEFAULT_SECRET_CONFIG_ID = "manual";
|
|
11
|
+
const SECRET_PRESETS = [
|
|
12
|
+
{
|
|
13
|
+
id: "cloudflare_wrangler",
|
|
14
|
+
label: "Cloudflare / Wrangler",
|
|
15
|
+
description: "Store a Cloudflare API token and account ID for Wrangler, Workers, Pages, D1, and KV.",
|
|
16
|
+
note: "Create a scoped API Token from Cloudflare Dashboard → My Profile → API Tokens. Do not use the Global API Key.",
|
|
17
|
+
fields: [
|
|
18
|
+
{
|
|
19
|
+
envKey: "CLOUDFLARE_API_TOKEN",
|
|
20
|
+
label: "Cloudflare API Token",
|
|
21
|
+
type: "password",
|
|
22
|
+
placeholder: "cfut_...",
|
|
23
|
+
helpText: "Recommended for Wrangler, CI, and sandbox use.",
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
envKey: "CLOUDFLARE_ACCOUNT_ID",
|
|
27
|
+
label: "Cloudflare Account ID",
|
|
28
|
+
type: "text",
|
|
29
|
+
placeholder: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
|
30
|
+
helpText: "Find this via wrangler whoami or in the Cloudflare dashboard account page.",
|
|
31
|
+
pattern: "^[A-Fa-f0-9]{32}$",
|
|
32
|
+
patternMessage: "Account ID must be a 32-character hexadecimal string.",
|
|
33
|
+
},
|
|
34
|
+
],
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
id: "openai",
|
|
38
|
+
label: "OpenAI",
|
|
39
|
+
description: "Store an OpenAI API key for tools and SDKs that use OPENAI_API_KEY.",
|
|
40
|
+
note: "Create a standard API key from the OpenAI dashboard. Paste the key exactly as issued.",
|
|
41
|
+
fields: [
|
|
42
|
+
{
|
|
43
|
+
envKey: "OPENAI_API_KEY",
|
|
44
|
+
label: "OpenAI API Key",
|
|
45
|
+
type: "password",
|
|
46
|
+
placeholder: "sk-...",
|
|
47
|
+
helpText: "Used by the OpenAI SDK, CLI wrappers, and many coding tools.",
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
id: "anthropic",
|
|
53
|
+
label: "Anthropic",
|
|
54
|
+
description: "Store an Anthropic API key for Claude and tools that use ANTHROPIC_API_KEY.",
|
|
55
|
+
note: "Create this key from the Anthropic Console. Use a workspace-scoped key when possible.",
|
|
56
|
+
fields: [
|
|
57
|
+
{
|
|
58
|
+
envKey: "ANTHROPIC_API_KEY",
|
|
59
|
+
label: "Anthropic API Key",
|
|
60
|
+
type: "password",
|
|
61
|
+
placeholder: "sk-ant-...",
|
|
62
|
+
helpText: "Used by Claude integrations and Anthropic-compatible tooling.",
|
|
63
|
+
},
|
|
64
|
+
],
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
id: "gemini",
|
|
68
|
+
label: "Gemini",
|
|
69
|
+
description: "Store one Google AI Studio key and expose it as both GEMINI_API_KEY and GOOGLE_API_KEY.",
|
|
70
|
+
note: "Create a Gemini / Google AI Studio API key, then paste it once here for compatibility with both env names.",
|
|
71
|
+
fields: [
|
|
72
|
+
{
|
|
73
|
+
envKey: "GEMINI_API_KEY",
|
|
74
|
+
envKeys: ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
|
|
75
|
+
label: "Gemini API Key",
|
|
76
|
+
type: "password",
|
|
77
|
+
placeholder: "AIza...",
|
|
78
|
+
helpText: "One value will be written to both GEMINI_API_KEY and GOOGLE_API_KEY.",
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
id: "openrouter",
|
|
84
|
+
label: "OpenRouter",
|
|
85
|
+
description: "Store an OpenRouter API key for tools that route models through OpenRouter.",
|
|
86
|
+
note: "Create a key from the OpenRouter dashboard and paste it here.",
|
|
87
|
+
fields: [
|
|
88
|
+
{
|
|
89
|
+
envKey: "OPENROUTER_API_KEY",
|
|
90
|
+
label: "OpenRouter API Key",
|
|
91
|
+
type: "password",
|
|
92
|
+
placeholder: "sk-or-v1-...",
|
|
93
|
+
helpText: "Used by OpenRouter SDKs and compatible model gateways.",
|
|
94
|
+
},
|
|
95
|
+
],
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
id: "github_pat",
|
|
99
|
+
label: "GitHub PAT",
|
|
100
|
+
description: "Store one GitHub personal access token and expose it as both GH_TOKEN and GITHUB_TOKEN.",
|
|
101
|
+
note: "Create a fine-grained or classic personal access token from GitHub Settings → Developer settings.",
|
|
102
|
+
fields: [
|
|
103
|
+
{
|
|
104
|
+
envKey: "GH_TOKEN",
|
|
105
|
+
envKeys: ["GH_TOKEN", "GITHUB_TOKEN"],
|
|
106
|
+
label: "GitHub Personal Access Token",
|
|
107
|
+
type: "password",
|
|
108
|
+
placeholder: "github_pat_...",
|
|
109
|
+
helpText: "One value will be written to both GH_TOKEN and GITHUB_TOKEN.",
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
id: "vercel",
|
|
115
|
+
label: "Vercel",
|
|
116
|
+
description: "Store a Vercel token plus optional org and project IDs for deployment tooling.",
|
|
117
|
+
note: "Create a token from the Vercel dashboard. Org ID and Project ID are optional but useful for scripted deploys.",
|
|
118
|
+
fields: [
|
|
119
|
+
{
|
|
120
|
+
envKey: "VERCEL_TOKEN",
|
|
121
|
+
label: "Vercel Token",
|
|
122
|
+
type: "password",
|
|
123
|
+
placeholder: "vercel_...",
|
|
124
|
+
helpText: "Required for Vercel CLI and API access.",
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
envKey: "VERCEL_ORG_ID",
|
|
128
|
+
label: "Vercel Org ID",
|
|
129
|
+
type: "text",
|
|
130
|
+
placeholder: "team_...",
|
|
131
|
+
helpText: "Optional. Set this when you want to target a specific team or account.",
|
|
132
|
+
optional: true,
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
envKey: "VERCEL_PROJECT_ID",
|
|
136
|
+
label: "Vercel Project ID",
|
|
137
|
+
type: "text",
|
|
138
|
+
placeholder: "prj_...",
|
|
139
|
+
helpText: "Optional. Set this when deploy scripts need a fixed project reference.",
|
|
140
|
+
optional: true,
|
|
141
|
+
},
|
|
142
|
+
],
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
id: "sentry",
|
|
146
|
+
label: "Sentry",
|
|
147
|
+
description: "Store a Sentry auth token plus optional org and project identifiers.",
|
|
148
|
+
note: "Create an auth token from Sentry Settings → Account → API → Auth Tokens. Org and project are optional helpers.",
|
|
149
|
+
fields: [
|
|
150
|
+
{
|
|
151
|
+
envKey: "SENTRY_AUTH_TOKEN",
|
|
152
|
+
label: "Sentry Auth Token",
|
|
153
|
+
type: "password",
|
|
154
|
+
placeholder: "sntrys_...",
|
|
155
|
+
helpText: "Required for Sentry CLI, releases, and sourcemap uploads.",
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
envKey: "SENTRY_ORG",
|
|
159
|
+
label: "Sentry Org Slug",
|
|
160
|
+
type: "text",
|
|
161
|
+
placeholder: "my-org",
|
|
162
|
+
helpText: "Optional. Helpful for Sentry CLI commands and CI automation.",
|
|
163
|
+
optional: true,
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
envKey: "SENTRY_PROJECT",
|
|
167
|
+
label: "Sentry Project Slug",
|
|
168
|
+
type: "text",
|
|
169
|
+
placeholder: "my-project",
|
|
170
|
+
helpText: "Optional. Helpful for release and sourcemap commands.",
|
|
171
|
+
optional: true,
|
|
172
|
+
},
|
|
173
|
+
],
|
|
174
|
+
},
|
|
175
|
+
];
|
|
176
|
+
// ── startLinkServer ────────────────────────────────────────────────────────────
|
|
177
|
+
/**
|
|
178
|
+
* Start a small HTTP server that receives credential onboarding callbacks from the web portal.
|
|
179
|
+
*
|
|
180
|
+
* Routes:
|
|
181
|
+
* GET /health — health check
|
|
182
|
+
* GET /link?token=xxx — credential onboarding page
|
|
183
|
+
* POST /api/link/complete — API key completion endpoint
|
|
184
|
+
* POST /api/oauth/start — creates provider OAuth redirect URL
|
|
185
|
+
* GET /oauth/callback — OAuth callback endpoint
|
|
186
|
+
*/
|
|
187
|
+
export function startLinkServer(port, linkTokenStore, vaultManager, notify, sessionViewTokenStore, sessionViewInteractive) {
|
|
188
|
+
const oauthStates = new Map();
|
|
189
|
+
const server = createServer(async (req, res) => {
|
|
190
|
+
try {
|
|
191
|
+
const url = new URL(req.url ?? "/", requestBaseUrl(req));
|
|
192
|
+
if (req.method === "GET" && url.pathname === "/health") {
|
|
193
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
194
|
+
res.end(JSON.stringify({ ok: true }));
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (await handleSessionViewRequest(req, res, url, sessionViewTokenStore, sessionViewInteractive)) {
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (req.method === "GET" && url.pathname === "/link") {
|
|
201
|
+
const rawToken = url.searchParams.get("token") ?? "";
|
|
202
|
+
const linkToken = linkTokenStore.peek(rawToken);
|
|
203
|
+
if (!linkToken) {
|
|
204
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
205
|
+
res.end(renderErrorPage("This link is invalid or has expired. Ask the bot for a new /login link."));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const oauthServiceHint = linkToken.providerId
|
|
209
|
+
? resolveOAuthService(linkToken.providerId)
|
|
210
|
+
: undefined;
|
|
211
|
+
const oauthServices = getOAuthServices();
|
|
212
|
+
const defaultMode = oauthServiceHint ? "oauth" : "api_key";
|
|
213
|
+
const existingSecrets = describeVaultSecrets(vaultManager, linkToken.vaultId);
|
|
214
|
+
const title = oauthServiceHint ? `${oauthServiceHint.label} OAuth` : "Store Secret";
|
|
215
|
+
const helpText = oauthServiceHint
|
|
216
|
+
? `Authorize ${oauthServiceHint.label} and store tokens in your vault.`
|
|
217
|
+
: "Set any environment variable key/value pair in your vault.";
|
|
218
|
+
const secretLabel = "Secret value";
|
|
219
|
+
const placeholder = "sk-...";
|
|
220
|
+
const initialEnvKey = "";
|
|
221
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
222
|
+
res.end(renderCredentialPage(rawToken, title, defaultMode, initialEnvKey, secretLabel, placeholder, helpText, oauthServices, oauthServiceHint?.id, existingSecrets));
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (req.method === "POST" && url.pathname === "/api/link/complete") {
|
|
226
|
+
if (!enforceCsrf(req, res))
|
|
227
|
+
return;
|
|
228
|
+
void readJsonBody(req, res, async (body) => {
|
|
229
|
+
await handleLinkComplete(body, linkTokenStore, vaultManager, notify, res);
|
|
230
|
+
});
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (req.method === "POST" && url.pathname === "/api/oauth/start") {
|
|
234
|
+
if (!enforceCsrf(req, res))
|
|
235
|
+
return;
|
|
236
|
+
void readJsonBody(req, res, async (body) => {
|
|
237
|
+
await handleOAuthStart(body, req, linkTokenStore, oauthStates, res);
|
|
238
|
+
});
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (req.method === "GET" && url.pathname === "/oauth/callback") {
|
|
242
|
+
void handleOAuthCallback(url, req, linkTokenStore, vaultManager, notify, oauthStates, res).catch((err) => {
|
|
243
|
+
log.logWarning("OAuth callback failed", err.message);
|
|
244
|
+
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
|
245
|
+
res.end(renderErrorPage("OAuth callback failed. Please retry /login."));
|
|
246
|
+
});
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
res.writeHead(404);
|
|
250
|
+
res.end();
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
log.logWarning("Link server request error", err instanceof Error ? err.message : String(err));
|
|
254
|
+
if (!res.headersSent) {
|
|
255
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
256
|
+
}
|
|
257
|
+
res.end(JSON.stringify({ error: "Internal server error" }));
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
// Bind to loopback when MAMA_LINK_URL is unset so the credential UI and OAuth
|
|
261
|
+
// callbacks are not exposed on public interfaces by default. Production
|
|
262
|
+
// deployments set MAMA_LINK_URL and are expected to front this server with a
|
|
263
|
+
// reverse proxy, which can still reach it via 0.0.0.0.
|
|
264
|
+
const bindHost = resolveLinkBaseUrl() ? undefined : "127.0.0.1";
|
|
265
|
+
server.listen(port, bindHost, () => {
|
|
266
|
+
log.logInfo(`Link callback server listening on ${bindHost ?? "0.0.0.0"}:${port}`);
|
|
267
|
+
if (!resolveLinkBaseUrl()) {
|
|
268
|
+
log.logWarning("MAMA_LINK_URL is not set — bound to 127.0.0.1 and OAuth redirect_uri will be " +
|
|
269
|
+
"derived from request headers (Host / X-Forwarded-*). Set " +
|
|
270
|
+
"MAMA_LINK_URL=https://your-host.example.com for production.");
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
server.on("error", (err) => {
|
|
274
|
+
log.logWarning("Link server error", err.message);
|
|
275
|
+
});
|
|
276
|
+
return server;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Resolve the externally-visible base URL of this server.
|
|
280
|
+
*
|
|
281
|
+
* Prefers MAMA_LINK_URL (see config.ts) so the OAuth `redirect_uri` is
|
|
282
|
+
* deterministic and not influenced by attacker-controlled request headers.
|
|
283
|
+
* Falls back to Host / X-Forwarded-* only when no base URL is configured
|
|
284
|
+
* — intended for local development.
|
|
285
|
+
*/
|
|
286
|
+
function requestBaseUrl(req) {
|
|
287
|
+
const configured = resolveLinkBaseUrl();
|
|
288
|
+
if (configured)
|
|
289
|
+
return configured;
|
|
290
|
+
const protoRaw = req.headers["x-forwarded-proto"]?.split(",")[0]?.trim();
|
|
291
|
+
const proto = protoRaw || "http";
|
|
292
|
+
const host = (req.headers["x-forwarded-host"]?.split(",")[0]?.trim() ??
|
|
293
|
+
req.headers.host ??
|
|
294
|
+
`localhost`) ||
|
|
295
|
+
`localhost`;
|
|
296
|
+
return `${proto}://${host}`;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Block cross-site POSTs to the credential endpoints. Two defenses:
|
|
300
|
+
* 1. Require Content-Type: application/json, which forces a CORS preflight
|
|
301
|
+
* for any cross-origin fetch and rules out `<form enctype="text/plain">`
|
|
302
|
+
* tricks that could otherwise smuggle a JSON body.
|
|
303
|
+
* 2. When MAMA_LINK_URL is configured, require that the Origin (or Referer,
|
|
304
|
+
* as a fallback for browsers that strip Origin) matches that base URL.
|
|
305
|
+
* This stops an attacker-controlled page — even one that somehow stole a
|
|
306
|
+
* victim's link token — from completing the flow.
|
|
307
|
+
*/
|
|
308
|
+
function enforceCsrf(req, res) {
|
|
309
|
+
const contentType = req.headers["content-type"]
|
|
310
|
+
?.split(";")[0]
|
|
311
|
+
?.trim()
|
|
312
|
+
.toLowerCase();
|
|
313
|
+
if (contentType !== "application/json") {
|
|
314
|
+
res.writeHead(415, { "Content-Type": "application/json" });
|
|
315
|
+
res.end(JSON.stringify({ error: "Content-Type must be application/json" }));
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
const configured = resolveLinkBaseUrl();
|
|
319
|
+
if (!configured) {
|
|
320
|
+
// No trusted origin to compare against in local/dev mode; the loopback
|
|
321
|
+
// bind already prevents cross-host access.
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
let configuredOrigin;
|
|
325
|
+
try {
|
|
326
|
+
configuredOrigin = new URL(configured).origin;
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
// Misconfigured MAMA_LINK_URL — fail closed.
|
|
330
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
331
|
+
res.end(JSON.stringify({ error: "Server misconfiguration" }));
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
if (requestOrigin(req) !== configuredOrigin) {
|
|
335
|
+
res.writeHead(403, { "Content-Type": "application/json" });
|
|
336
|
+
res.end(JSON.stringify({ error: "Cross-origin request rejected" }));
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
return true;
|
|
340
|
+
}
|
|
341
|
+
/** Best-effort origin of the request, derived from Origin or Referer. */
|
|
342
|
+
function requestOrigin(req) {
|
|
343
|
+
const origin = req.headers.origin?.trim();
|
|
344
|
+
if (origin && origin !== "null")
|
|
345
|
+
return origin;
|
|
346
|
+
const referer = req.headers.referer?.trim();
|
|
347
|
+
if (!referer)
|
|
348
|
+
return undefined;
|
|
349
|
+
try {
|
|
350
|
+
return new URL(referer).origin;
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
async function readJsonBody(req, res, onBody) {
|
|
357
|
+
let body = "";
|
|
358
|
+
let bodyTooLarge = false;
|
|
359
|
+
req.on("data", (chunk) => {
|
|
360
|
+
if (bodyTooLarge)
|
|
361
|
+
return;
|
|
362
|
+
body += chunk.toString();
|
|
363
|
+
if (body.length > 16 * 1024) {
|
|
364
|
+
bodyTooLarge = true;
|
|
365
|
+
res.writeHead(413);
|
|
366
|
+
res.end();
|
|
367
|
+
req.destroy();
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
req.on("end", async () => {
|
|
371
|
+
if (bodyTooLarge)
|
|
372
|
+
return;
|
|
373
|
+
await onBody(body);
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
// ── HTML helpers ───────────────────────────────────────────────────────────────
|
|
377
|
+
function esc(s) {
|
|
378
|
+
return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
379
|
+
}
|
|
380
|
+
const sharedPageStyles = `
|
|
381
|
+
:root {
|
|
382
|
+
color-scheme: light;
|
|
383
|
+
--bg: #f5f1e8;
|
|
384
|
+
--panel: rgba(255, 255, 255, 0.9);
|
|
385
|
+
--panel-border: rgba(28, 30, 33, 0.08);
|
|
386
|
+
--text: #1c1e21;
|
|
387
|
+
--muted: #5d5f64;
|
|
388
|
+
--button: #1c1e21;
|
|
389
|
+
--button-hover: #2c3035;
|
|
390
|
+
--button-disabled: #8f949b;
|
|
391
|
+
--field-border: #c9cfd6;
|
|
392
|
+
--field-focus: #1c1e21;
|
|
393
|
+
--ok-bg: #dff4e4;
|
|
394
|
+
--ok-text: #1f5b34;
|
|
395
|
+
--err-bg: #fde2e2;
|
|
396
|
+
--err-text: #8a2f2f;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
* { box-sizing: border-box; }
|
|
400
|
+
|
|
401
|
+
body {
|
|
402
|
+
margin: 0;
|
|
403
|
+
min-height: 100vh;
|
|
404
|
+
padding: 32px 20px;
|
|
405
|
+
display: grid;
|
|
406
|
+
grid-template-columns: minmax(0, 560px);
|
|
407
|
+
justify-content: center;
|
|
408
|
+
align-content: start;
|
|
409
|
+
background:
|
|
410
|
+
radial-gradient(circle at top, rgba(255, 255, 255, 0.7), transparent 45%),
|
|
411
|
+
linear-gradient(180deg, #faf7f0 0%, var(--bg) 100%);
|
|
412
|
+
color: var(--text);
|
|
413
|
+
font-family:
|
|
414
|
+
"SF Pro Text",
|
|
415
|
+
"Segoe UI",
|
|
416
|
+
system-ui,
|
|
417
|
+
sans-serif;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
.shell {
|
|
421
|
+
width: 100%;
|
|
422
|
+
min-width: 0;
|
|
423
|
+
display: grid;
|
|
424
|
+
gap: 16px;
|
|
425
|
+
align-content: start;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
.card {
|
|
429
|
+
padding: 28px;
|
|
430
|
+
border: 1px solid var(--panel-border);
|
|
431
|
+
border-radius: 20px;
|
|
432
|
+
background: var(--panel);
|
|
433
|
+
box-shadow: 0 18px 48px rgba(28, 30, 33, 0.08);
|
|
434
|
+
backdrop-filter: blur(8px);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
.eyebrow {
|
|
438
|
+
margin: 0 0 10px;
|
|
439
|
+
color: var(--muted);
|
|
440
|
+
font-size: 0.82rem;
|
|
441
|
+
font-weight: 700;
|
|
442
|
+
letter-spacing: 0.08em;
|
|
443
|
+
text-transform: uppercase;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
h1 {
|
|
447
|
+
margin: 0 0 10px;
|
|
448
|
+
font-size: clamp(1.5rem, 2vw, 1.8rem);
|
|
449
|
+
line-height: 1.15;
|
|
450
|
+
text-wrap: balance;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
p {
|
|
454
|
+
margin: 0;
|
|
455
|
+
color: var(--muted);
|
|
456
|
+
font-size: 0.98rem;
|
|
457
|
+
line-height: 1.5;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
.stack > * + * {
|
|
461
|
+
margin-top: 14px;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
label {
|
|
465
|
+
display: block;
|
|
466
|
+
margin-bottom: 6px;
|
|
467
|
+
font-size: 0.92rem;
|
|
468
|
+
font-weight: 650;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
input,
|
|
472
|
+
select,
|
|
473
|
+
button {
|
|
474
|
+
font: inherit;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
input,
|
|
478
|
+
select {
|
|
479
|
+
width: 100%;
|
|
480
|
+
padding: 12px 14px;
|
|
481
|
+
border: 1px solid var(--field-border);
|
|
482
|
+
border-radius: 12px;
|
|
483
|
+
background: #fff;
|
|
484
|
+
color: var(--text);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
input:focus-visible,
|
|
488
|
+
select:focus-visible,
|
|
489
|
+
button:focus-visible {
|
|
490
|
+
outline: 2px solid var(--field-focus);
|
|
491
|
+
outline-offset: 2px;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
code {
|
|
495
|
+
font-family: "SFMono-Regular", ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
496
|
+
font-size: 0.92em;
|
|
497
|
+
overflow-wrap: anywhere;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
.primary-button {
|
|
501
|
+
width: 100%;
|
|
502
|
+
padding: 13px 18px;
|
|
503
|
+
border: none;
|
|
504
|
+
border-radius: 12px;
|
|
505
|
+
background: var(--button);
|
|
506
|
+
color: #fff;
|
|
507
|
+
cursor: pointer;
|
|
508
|
+
transition: background-color 160ms ease;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
.primary-button:hover {
|
|
512
|
+
background: var(--button-hover);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
.primary-button:disabled {
|
|
516
|
+
background: var(--button-disabled);
|
|
517
|
+
cursor: default;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
.service-logo {
|
|
521
|
+
display: inline-flex;
|
|
522
|
+
align-items: center;
|
|
523
|
+
justify-content: center;
|
|
524
|
+
width: 36px;
|
|
525
|
+
height: 36px;
|
|
526
|
+
border-radius: 10px;
|
|
527
|
+
flex: 0 0 36px;
|
|
528
|
+
background: #1c1e21;
|
|
529
|
+
color: #fff;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
.service-logo svg {
|
|
533
|
+
display: block;
|
|
534
|
+
width: 20px;
|
|
535
|
+
height: 20px;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
.service-logo-text {
|
|
539
|
+
font-size: 11px;
|
|
540
|
+
font-weight: 800;
|
|
541
|
+
letter-spacing: 0.04em;
|
|
542
|
+
text-transform: uppercase;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
.service-logo.cloudflare {
|
|
546
|
+
background: linear-gradient(180deg, #ffb66d 0%, #f48120 100%);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
.service-logo.openai {
|
|
550
|
+
background: linear-gradient(180deg, #3e4045 0%, #111315 100%);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
.service-logo.anthropic {
|
|
554
|
+
background: linear-gradient(180deg, #d6b48c 0%, #9a6d3a 100%);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
.service-logo.gemini {
|
|
558
|
+
background: linear-gradient(180deg, #8ab4ff 0%, #5b6cff 100%);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
.service-logo.openrouter {
|
|
562
|
+
background: linear-gradient(180deg, #8c8cff 0%, #4f46e5 100%);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
.service-logo.github {
|
|
566
|
+
background: linear-gradient(180deg, #4a4f57 0%, #1b1f23 100%);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
.service-logo.vercel {
|
|
570
|
+
background: linear-gradient(180deg, #4a4f57 0%, #000 100%);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
.service-logo.sentry {
|
|
574
|
+
background: linear-gradient(180deg, #7c5cff 0%, #3f2e8c 100%);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
.service-logo.manual {
|
|
578
|
+
background: linear-gradient(180deg, #43474d 0%, #1c1e21 100%);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
.provider-card > * + * {
|
|
582
|
+
margin-top: 14px;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
.provider-header {
|
|
586
|
+
display: flex;
|
|
587
|
+
align-items: center;
|
|
588
|
+
gap: 12px;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
.provider-title {
|
|
592
|
+
flex: 1;
|
|
593
|
+
margin: 0;
|
|
594
|
+
font-size: 1rem;
|
|
595
|
+
font-weight: 650;
|
|
596
|
+
line-height: 1.3;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
.provider-field label {
|
|
600
|
+
display: inline-flex;
|
|
601
|
+
align-items: center;
|
|
602
|
+
gap: 6px;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
.help {
|
|
606
|
+
position: relative;
|
|
607
|
+
display: inline-flex;
|
|
608
|
+
align-items: center;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
.help-trigger {
|
|
612
|
+
width: 18px;
|
|
613
|
+
height: 18px;
|
|
614
|
+
padding: 0;
|
|
615
|
+
border: 1px solid var(--field-border);
|
|
616
|
+
border-radius: 50%;
|
|
617
|
+
background: rgba(255, 255, 255, 0.9);
|
|
618
|
+
color: var(--muted);
|
|
619
|
+
font-size: 11px;
|
|
620
|
+
font-weight: 700;
|
|
621
|
+
line-height: 1;
|
|
622
|
+
cursor: pointer;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
.help-trigger:hover {
|
|
626
|
+
color: var(--text);
|
|
627
|
+
border-color: var(--text);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
.help-content {
|
|
631
|
+
display: none;
|
|
632
|
+
position: absolute;
|
|
633
|
+
top: calc(100% + 6px);
|
|
634
|
+
left: 0;
|
|
635
|
+
z-index: 10;
|
|
636
|
+
width: max-content;
|
|
637
|
+
max-width: 280px;
|
|
638
|
+
padding: 10px 12px;
|
|
639
|
+
border: 1px solid var(--panel-border);
|
|
640
|
+
border-radius: 10px;
|
|
641
|
+
background: #fff;
|
|
642
|
+
color: var(--text);
|
|
643
|
+
font-size: 0.85rem;
|
|
644
|
+
font-weight: 400;
|
|
645
|
+
line-height: 1.45;
|
|
646
|
+
box-shadow: 0 8px 24px rgba(28, 30, 33, 0.12);
|
|
647
|
+
white-space: normal;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
.help-trigger[aria-expanded="true"] + .help-content {
|
|
651
|
+
display: block;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
.help-trigger[aria-expanded="true"] {
|
|
655
|
+
color: var(--text);
|
|
656
|
+
border-color: var(--text);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
.mode {
|
|
660
|
+
display: flex;
|
|
661
|
+
flex-wrap: wrap;
|
|
662
|
+
gap: 10px;
|
|
663
|
+
margin-top: 22px;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
.mode label {
|
|
667
|
+
display: inline-flex;
|
|
668
|
+
align-items: center;
|
|
669
|
+
gap: 8px;
|
|
670
|
+
margin: 0;
|
|
671
|
+
padding: 10px 12px;
|
|
672
|
+
border: 1px solid var(--field-border);
|
|
673
|
+
border-radius: 999px;
|
|
674
|
+
background: rgba(255, 255, 255, 0.85);
|
|
675
|
+
font-weight: 500;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
.mode input {
|
|
679
|
+
width: auto;
|
|
680
|
+
margin: 0;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
.panel {
|
|
684
|
+
display: none;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
.panel.active {
|
|
688
|
+
display: block;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
#api-panel.active {
|
|
692
|
+
display: grid;
|
|
693
|
+
gap: 16px;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
.panel-note {
|
|
697
|
+
margin-top: 10px;
|
|
698
|
+
font-size: 0.92rem;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
.result,
|
|
702
|
+
.status {
|
|
703
|
+
margin-top: 20px;
|
|
704
|
+
padding: 14px 16px;
|
|
705
|
+
border-radius: 14px;
|
|
706
|
+
font-size: 0.95rem;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
.result {
|
|
710
|
+
display: none;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
.result.ok,
|
|
714
|
+
.status.ok {
|
|
715
|
+
background: var(--ok-bg);
|
|
716
|
+
color: var(--ok-text);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
.result.err,
|
|
720
|
+
.status.err {
|
|
721
|
+
background: var(--err-bg);
|
|
722
|
+
color: var(--err-text);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
.secrets-summary {
|
|
726
|
+
margin-top: 18px;
|
|
727
|
+
padding: 14px 16px;
|
|
728
|
+
border: 1px solid var(--panel-border);
|
|
729
|
+
border-radius: 14px;
|
|
730
|
+
background: rgba(255, 255, 255, 0.72);
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
.secrets-summary h2 {
|
|
734
|
+
margin: 0 0 8px;
|
|
735
|
+
font-size: 0.98rem;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
.secrets-summary p {
|
|
739
|
+
font-size: 0.92rem;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
.secrets-summary ul {
|
|
743
|
+
margin: 10px 0 0;
|
|
744
|
+
padding-left: 18px;
|
|
745
|
+
color: var(--text);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
.secrets-summary li + li {
|
|
749
|
+
margin-top: 6px;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
.close-note {
|
|
753
|
+
margin-top: 14px;
|
|
754
|
+
font-size: 0.92rem;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
@media (max-width: 640px) {
|
|
758
|
+
body {
|
|
759
|
+
padding: 16px 12px;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
.shell {
|
|
763
|
+
gap: 12px;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
.card {
|
|
767
|
+
padding: 20px;
|
|
768
|
+
border-radius: 16px;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/* Mode toggle pills fill the row evenly */
|
|
772
|
+
.mode label {
|
|
773
|
+
flex: 1;
|
|
774
|
+
justify-content: center;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/* Larger touch targets */
|
|
778
|
+
input,
|
|
779
|
+
select {
|
|
780
|
+
padding: 14px;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
.primary-button {
|
|
784
|
+
padding: 15px 18px;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/* Prevent help popover from overflowing the viewport */
|
|
788
|
+
.help-content {
|
|
789
|
+
max-width: min(260px, calc(100vw - 40px));
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/* Right-align popovers that sit near the right edge */
|
|
793
|
+
.provider-header .help-content {
|
|
794
|
+
left: auto;
|
|
795
|
+
right: 0;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
`;
|
|
799
|
+
function renderHtmlDocument(title, shellContent) {
|
|
800
|
+
return `<!DOCTYPE html>
|
|
801
|
+
<html lang="en">
|
|
802
|
+
<head>
|
|
803
|
+
<meta charset="utf-8">
|
|
804
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
805
|
+
<title>${esc(title)} — ${PRODUCT_NAME}</title>
|
|
806
|
+
<style>${sharedPageStyles}</style>
|
|
807
|
+
</head>
|
|
808
|
+
<body>
|
|
809
|
+
<main class="shell">
|
|
810
|
+
${shellContent}
|
|
811
|
+
</main>
|
|
812
|
+
</body>
|
|
813
|
+
</html>`;
|
|
814
|
+
}
|
|
815
|
+
function renderPageDocument(title, body) {
|
|
816
|
+
return renderHtmlDocument(title, `<section class="card">${body}</section>`);
|
|
817
|
+
}
|
|
818
|
+
function renderStatusPage(title, message, tone, options) {
|
|
819
|
+
const closeNote = options?.closeNote ? '<p class="close-note">You can close this tab.</p>' : "";
|
|
820
|
+
return renderPageDocument(title, `<div class="stack">
|
|
821
|
+
<p class="eyebrow">${PRODUCT_NAME}</p>
|
|
822
|
+
<h1>${esc(title)}</h1>
|
|
823
|
+
<div class="status ${tone}">${esc(message)}</div>
|
|
824
|
+
${closeNote}
|
|
825
|
+
</div>`);
|
|
826
|
+
}
|
|
827
|
+
function describeVaultSecrets(vaultManager, vaultId) {
|
|
828
|
+
const vault = vaultManager.resolve(vaultId);
|
|
829
|
+
if (!vault) {
|
|
830
|
+
return { envKeys: [], mountTargets: [] };
|
|
831
|
+
}
|
|
832
|
+
return {
|
|
833
|
+
envKeys: Object.keys(vault.env).toSorted((left, right) => left.localeCompare(right)),
|
|
834
|
+
mountTargets: [...new Set(vault.mounts.map((mount) => mount.target))].toSorted((left, right) => left.localeCompare(right)),
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
function renderSecretsSummary(summary) {
|
|
838
|
+
if (summary.envKeys.length === 0 && summary.mountTargets.length === 0) {
|
|
839
|
+
return `
|
|
840
|
+
<section class="secrets-summary">
|
|
841
|
+
<h2>Currently stored</h2>
|
|
842
|
+
<p>No secrets are stored in this vault yet.</p>
|
|
843
|
+
</section>`;
|
|
844
|
+
}
|
|
845
|
+
const envItems = summary.envKeys.map((envKey) => `<li><code>${esc(envKey)}</code></li>`).join("");
|
|
846
|
+
const mountItems = summary.mountTargets
|
|
847
|
+
.map((target) => `<li><code>${esc(target)}</code></li>`)
|
|
848
|
+
.join("");
|
|
849
|
+
return `
|
|
850
|
+
<section class="secrets-summary">
|
|
851
|
+
<h2>Currently stored</h2>
|
|
852
|
+
<p>Only secret names and mounted paths are shown here. Secret values are never displayed.</p>
|
|
853
|
+
${summary.envKeys.length > 0 ? `<p><strong>Environment keys</strong></p><ul>${envItems}</ul>` : ""}
|
|
854
|
+
${summary.mountTargets.length > 0 ? `<p><strong>Mounted secret files</strong></p><ul>${mountItems}</ul>` : ""}
|
|
855
|
+
</section>`;
|
|
856
|
+
}
|
|
857
|
+
function renderServiceLogo(kind) {
|
|
858
|
+
if (kind === "cloudflare_wrangler") {
|
|
859
|
+
return `<span class="service-logo cloudflare" aria-hidden="true">
|
|
860
|
+
<svg viewBox="0 0 24 24" fill="none">
|
|
861
|
+
<path d="M8.5 17.5h8.2a2.9 2.9 0 0 0 .4-5.78A4.45 4.45 0 0 0 8.9 10.4a3.7 3.7 0 0 0-.4 7.1Z" fill="white" fill-opacity="0.98"/>
|
|
862
|
+
<path d="M6.6 17.5h5.1a2.3 2.3 0 0 0 0-4.6 3.1 3.1 0 0 0-3-2.2 3.23 3.23 0 0 0-3.18 3.64A2.67 2.67 0 0 0 6.6 17.5Z" fill="white"/>
|
|
863
|
+
</svg>
|
|
864
|
+
</span>`;
|
|
865
|
+
}
|
|
866
|
+
const textLogos = {
|
|
867
|
+
openai: { className: "openai", text: "OA" },
|
|
868
|
+
anthropic: { className: "anthropic", text: "AI" },
|
|
869
|
+
gemini: { className: "gemini", text: "G" },
|
|
870
|
+
openrouter: { className: "openrouter", text: "OR" },
|
|
871
|
+
github_pat: { className: "github", text: "GH" },
|
|
872
|
+
vercel: { className: "vercel", text: "V" },
|
|
873
|
+
sentry: { className: "sentry", text: "S" },
|
|
874
|
+
manual: { className: "manual", text: ">_" },
|
|
875
|
+
};
|
|
876
|
+
const logo = textLogos[kind] ?? textLogos.manual;
|
|
877
|
+
return `<span class="service-logo ${logo.className}" aria-hidden="true"><span class="service-logo-text">${logo.text}</span></span>`;
|
|
878
|
+
}
|
|
879
|
+
function resolveFieldEnvKeys(field) {
|
|
880
|
+
return field.envKeys && field.envKeys.length > 0 ? field.envKeys : [field.envKey];
|
|
881
|
+
}
|
|
882
|
+
function renderStoredEnvKeysInline(field) {
|
|
883
|
+
return resolveFieldEnvKeys(field)
|
|
884
|
+
.map((envKey) => `<code>${esc(envKey)}</code>`)
|
|
885
|
+
.join(", ");
|
|
886
|
+
}
|
|
887
|
+
function renderHelpIcon(html) {
|
|
888
|
+
return `<span class="help">
|
|
889
|
+
<button type="button" class="help-trigger" aria-label="More info" aria-expanded="false">?</button>
|
|
890
|
+
<span class="help-content" role="tooltip">${html}</span>
|
|
891
|
+
</span>`;
|
|
892
|
+
}
|
|
893
|
+
function renderPresetProviderCard(preset) {
|
|
894
|
+
const headerHelp = preset.note ? renderHelpIcon(esc(preset.note)) : "";
|
|
895
|
+
const fields = preset.fields
|
|
896
|
+
.map((field) => {
|
|
897
|
+
const storedKeys = renderStoredEnvKeysInline(field);
|
|
898
|
+
const helpText = `${esc(field.helpText)} Stored as ${storedKeys}.${field.optional ? " Optional." : ""}`;
|
|
899
|
+
return `<div class="provider-field">
|
|
900
|
+
<label for="preset-${esc(preset.id)}-${esc(field.envKey)}">
|
|
901
|
+
${esc(field.label)}
|
|
902
|
+
${renderHelpIcon(helpText)}
|
|
903
|
+
</label>
|
|
904
|
+
<input
|
|
905
|
+
id="preset-${esc(preset.id)}-${esc(field.envKey)}"
|
|
906
|
+
type="${field.type}"
|
|
907
|
+
autocomplete="off"
|
|
908
|
+
placeholder="${esc(field.placeholder)}"
|
|
909
|
+
data-env-key="${esc(field.envKey)}"
|
|
910
|
+
data-env-keys="${esc(resolveFieldEnvKeys(field).join(","))}"
|
|
911
|
+
data-field-label="${esc(field.label)}"
|
|
912
|
+
${field.optional ? 'data-optional="true"' : ""}
|
|
913
|
+
${field.pattern ? `data-pattern="${esc(field.pattern)}"` : ""}
|
|
914
|
+
${field.patternMessage ? `data-pattern-message="${esc(field.patternMessage)}"` : ""}
|
|
915
|
+
>
|
|
916
|
+
</div>`;
|
|
917
|
+
})
|
|
918
|
+
.join("\n");
|
|
919
|
+
return `<section class="card provider-card" data-provider-kind="preset" data-provider-id="${esc(preset.id)}">
|
|
920
|
+
<div class="provider-header">
|
|
921
|
+
${renderServiceLogo(preset.id)}
|
|
922
|
+
<h2 class="provider-title">${esc(preset.label)}</h2>
|
|
923
|
+
${headerHelp}
|
|
924
|
+
</div>
|
|
925
|
+
${fields}
|
|
926
|
+
</section>`;
|
|
927
|
+
}
|
|
928
|
+
function renderManualProviderCard(initialEnvKey, secretLabel, placeholder) {
|
|
929
|
+
const headerHelp = renderHelpIcon(esc("Set any environment variable key/value pair manually. Use this when no provider preset fits."));
|
|
930
|
+
return `<section class="card provider-card" data-provider-kind="manual" data-provider-id="${esc(DEFAULT_SECRET_CONFIG_ID)}">
|
|
931
|
+
<div class="provider-header">
|
|
932
|
+
${renderServiceLogo("manual")}
|
|
933
|
+
<h2 class="provider-title">Manual entry</h2>
|
|
934
|
+
${headerHelp}
|
|
935
|
+
</div>
|
|
936
|
+
<div class="provider-field">
|
|
937
|
+
<label for="envKey">Environment key</label>
|
|
938
|
+
<input id="envKey" type="text" name="envKey" placeholder="OPENAI_API_KEY" value="${esc(initialEnvKey)}" autocomplete="off">
|
|
939
|
+
</div>
|
|
940
|
+
<div class="provider-field">
|
|
941
|
+
<label for="credential">${esc(secretLabel)}</label>
|
|
942
|
+
<input id="credential" type="password" name="credential" placeholder="${esc(placeholder)}" autocomplete="off">
|
|
943
|
+
</div>
|
|
944
|
+
</section>`;
|
|
945
|
+
}
|
|
946
|
+
function renderCredentialPage(token, title, defaultMode, initialEnvKey, secretLabel, placeholder, helpText, oauthServices, oauthServiceIdHint, existingSecrets) {
|
|
947
|
+
const oauthOptions = oauthServices
|
|
948
|
+
.map((service) => {
|
|
949
|
+
const selected = service.id === oauthServiceIdHint ? ' selected="selected"' : "";
|
|
950
|
+
return `<option value="${esc(service.id)}"${selected}>${esc(service.label)}</option>`;
|
|
951
|
+
})
|
|
952
|
+
.join("\n");
|
|
953
|
+
const presetCards = SECRET_PRESETS.map(renderPresetProviderCard).join("\n");
|
|
954
|
+
return renderHtmlDocument("Login", `<section class="card stack">
|
|
955
|
+
<p class="eyebrow">${PRODUCT_NAME}</p>
|
|
956
|
+
<h1>${esc(title)}</h1>
|
|
957
|
+
<p>Your personal sandbox is already provisioned automatically.</p>
|
|
958
|
+
<p>${esc(helpText)}</p>
|
|
959
|
+
${renderSecretsSummary(existingSecrets)}
|
|
960
|
+
<div class="mode">
|
|
961
|
+
<label><input type="radio" name="mode" value="api_key" ${defaultMode === "api_key" ? "checked" : ""}> Secrets / API tokens</label>
|
|
962
|
+
<label><input type="radio" name="mode" value="oauth" ${defaultMode === "oauth" ? "checked" : ""}> OAuth login</label>
|
|
963
|
+
</div>
|
|
964
|
+
</section>
|
|
965
|
+
|
|
966
|
+
<div id="api-panel" class="panel">
|
|
967
|
+
${presetCards}
|
|
968
|
+
${renderManualProviderCard(initialEnvKey, secretLabel, placeholder)}
|
|
969
|
+
</div>
|
|
970
|
+
|
|
971
|
+
<div id="oauth-panel" class="panel card stack">
|
|
972
|
+
<label for="oauthService">OAuth service</label>
|
|
973
|
+
<select id="oauthService" name="oauthService">${oauthOptions}</select>
|
|
974
|
+
<p class="panel-note">You'll be redirected to the selected service's authorization page.</p>
|
|
975
|
+
</div>
|
|
976
|
+
|
|
977
|
+
<div>
|
|
978
|
+
<button id="btn" class="primary-button" onclick="connect()">Continue</button>
|
|
979
|
+
<div id="result" class="result" aria-live="polite"></div>
|
|
980
|
+
</div>
|
|
981
|
+
<script>
|
|
982
|
+
const envKeyPattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
983
|
+
|
|
984
|
+
function selectedMode() {
|
|
985
|
+
return document.querySelector('input[name="mode"]:checked').value;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
function showResult(message, ok) {
|
|
989
|
+
const result = document.getElementById('result');
|
|
990
|
+
result.style.display = 'block';
|
|
991
|
+
result.className = ok ? 'result ok' : 'result err';
|
|
992
|
+
result.textContent = message;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
function resetContinueButton() {
|
|
996
|
+
const btn = document.getElementById('btn');
|
|
997
|
+
btn.disabled = false;
|
|
998
|
+
btn.textContent = 'Continue';
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function syncPanels() {
|
|
1002
|
+
const mode = selectedMode();
|
|
1003
|
+
document.getElementById('api-panel').classList.toggle('active', mode === 'api_key');
|
|
1004
|
+
document.getElementById('oauth-panel').classList.toggle('active', mode === 'oauth');
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
function collectManualCard(card) {
|
|
1008
|
+
const envKey = card.querySelector('#envKey').value.trim();
|
|
1009
|
+
const credential = card.querySelector('#credential').value.trim();
|
|
1010
|
+
if (!envKey && !credential) return { skip: true };
|
|
1011
|
+
if (!envKeyPattern.test(envKey)) return { error: 'Manual entry: please enter a valid environment key.' };
|
|
1012
|
+
if (!credential) return { error: 'Manual entry: please enter a secret value.' };
|
|
1013
|
+
return { env: { [envKey]: credential } };
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
function collectPresetCard(card) {
|
|
1017
|
+
const inputs = card.querySelectorAll('input[data-env-key]');
|
|
1018
|
+
const filled = Array.from(inputs).some((input) => input.value.trim() !== '');
|
|
1019
|
+
if (!filled) return { skip: true };
|
|
1020
|
+
|
|
1021
|
+
const env = {};
|
|
1022
|
+
for (const input of inputs) {
|
|
1023
|
+
const value = input.value.trim();
|
|
1024
|
+
const label = input.dataset.fieldLabel || input.dataset.envKey || 'a value';
|
|
1025
|
+
const optional = input.dataset.optional === 'true';
|
|
1026
|
+
if (!value) {
|
|
1027
|
+
if (optional) continue;
|
|
1028
|
+
return { error: 'Please enter ' + label + '.' };
|
|
1029
|
+
}
|
|
1030
|
+
if (input.dataset.pattern && !(new RegExp(input.dataset.pattern).test(value))) {
|
|
1031
|
+
return { error: input.dataset.patternMessage || ('Invalid ' + label + '.') };
|
|
1032
|
+
}
|
|
1033
|
+
const envKeys = (input.dataset.envKeys || input.dataset.envKey || '')
|
|
1034
|
+
.split(',')
|
|
1035
|
+
.map((entry) => entry.trim())
|
|
1036
|
+
.filter(Boolean);
|
|
1037
|
+
for (const envKey of envKeys) {
|
|
1038
|
+
env[envKey] = value;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
return { env };
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
function collectApiEnv() {
|
|
1045
|
+
const env = {};
|
|
1046
|
+
let any = false;
|
|
1047
|
+
for (const card of document.querySelectorAll('.provider-card')) {
|
|
1048
|
+
const result = card.dataset.providerKind === 'manual'
|
|
1049
|
+
? collectManualCard(card)
|
|
1050
|
+
: collectPresetCard(card);
|
|
1051
|
+
if (result.skip) continue;
|
|
1052
|
+
if (result.error) return { error: result.error };
|
|
1053
|
+
Object.assign(env, result.env);
|
|
1054
|
+
any = true;
|
|
1055
|
+
}
|
|
1056
|
+
if (!any) return { error: 'Fill in at least one provider before continuing.' };
|
|
1057
|
+
return { env };
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
async function startOAuthFlow() {
|
|
1061
|
+
const serviceId = document.getElementById('oauthService').value;
|
|
1062
|
+
const r = await fetch('/api/oauth/start', {
|
|
1063
|
+
method: 'POST',
|
|
1064
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1065
|
+
body: JSON.stringify({ token: '${esc(token)}', serviceId }),
|
|
1066
|
+
});
|
|
1067
|
+
const data = await r.json();
|
|
1068
|
+
if (!r.ok) {
|
|
1069
|
+
showResult('Error: ' + (data.error ?? r.status), false);
|
|
1070
|
+
resetContinueButton();
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
window.location.href = data.redirectUrl;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
async function saveApiSecrets() {
|
|
1077
|
+
const payload = collectApiEnv();
|
|
1078
|
+
if (payload.error) {
|
|
1079
|
+
showResult(payload.error, false);
|
|
1080
|
+
resetContinueButton();
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
const r = await fetch('/api/link/complete', {
|
|
1085
|
+
method: 'POST',
|
|
1086
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1087
|
+
body: JSON.stringify({ token: '${esc(token)}', mode: 'api_key', env: payload.env }),
|
|
1088
|
+
});
|
|
1089
|
+
const data = await r.json();
|
|
1090
|
+
if (r.ok) {
|
|
1091
|
+
showResult(data.message ?? 'Credential stored. You can close this tab.', true);
|
|
1092
|
+
document.getElementById('btn').style.display = 'none';
|
|
1093
|
+
for (const input of document.querySelectorAll('input,select,button')) input.disabled = true;
|
|
1094
|
+
} else {
|
|
1095
|
+
showResult('Error: ' + (data.error ?? r.status), false);
|
|
1096
|
+
resetContinueButton();
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
let openHelp = null;
|
|
1101
|
+
function closeOpenHelp() {
|
|
1102
|
+
if (openHelp) {
|
|
1103
|
+
openHelp.setAttribute('aria-expanded', 'false');
|
|
1104
|
+
openHelp = null;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
for (const trigger of document.querySelectorAll('.help-trigger')) {
|
|
1109
|
+
trigger.addEventListener('click', (event) => {
|
|
1110
|
+
event.stopPropagation();
|
|
1111
|
+
const wasOpen = trigger.getAttribute('aria-expanded') === 'true';
|
|
1112
|
+
closeOpenHelp();
|
|
1113
|
+
if (!wasOpen) {
|
|
1114
|
+
trigger.setAttribute('aria-expanded', 'true');
|
|
1115
|
+
openHelp = trigger;
|
|
1116
|
+
}
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
document.addEventListener('click', closeOpenHelp);
|
|
1121
|
+
document.addEventListener('keydown', (event) => {
|
|
1122
|
+
if (event.key === 'Escape') closeOpenHelp();
|
|
1123
|
+
});
|
|
1124
|
+
|
|
1125
|
+
for (const radio of document.querySelectorAll('input[name="mode"]')) {
|
|
1126
|
+
radio.addEventListener('change', syncPanels);
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
syncPanels();
|
|
1130
|
+
|
|
1131
|
+
async function connect() {
|
|
1132
|
+
const btn = document.getElementById('btn');
|
|
1133
|
+
const mode = selectedMode();
|
|
1134
|
+
btn.disabled = true;
|
|
1135
|
+
btn.textContent = mode === 'oauth' ? 'Redirecting…' : 'Saving…';
|
|
1136
|
+
|
|
1137
|
+
try {
|
|
1138
|
+
if (mode === 'oauth') {
|
|
1139
|
+
await startOAuthFlow();
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
await saveApiSecrets();
|
|
1143
|
+
} catch (err) {
|
|
1144
|
+
showResult('Network error: ' + (err?.message ?? err), false);
|
|
1145
|
+
resetContinueButton();
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
</script>`);
|
|
1149
|
+
}
|
|
1150
|
+
function renderErrorPage(message) {
|
|
1151
|
+
return renderStatusPage("Login Error", message, "err");
|
|
1152
|
+
}
|
|
1153
|
+
function renderSuccessPage(message) {
|
|
1154
|
+
return renderStatusPage("Connected", message, "ok", { closeNote: true });
|
|
1155
|
+
}
|
|
1156
|
+
function isValidEnvKey(value) {
|
|
1157
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
|
|
1158
|
+
}
|
|
1159
|
+
function extractEnvUpdates(data) {
|
|
1160
|
+
if (data.env && typeof data.env === "object" && !Array.isArray(data.env)) {
|
|
1161
|
+
const rawEntries = Object.entries(data.env);
|
|
1162
|
+
if (rawEntries.length === 0)
|
|
1163
|
+
return { error: "Missing required field: env" };
|
|
1164
|
+
const updates = {};
|
|
1165
|
+
for (const [rawKey, rawValue] of rawEntries) {
|
|
1166
|
+
const envKey = rawKey.trim();
|
|
1167
|
+
const credential = typeof rawValue === "string" ? rawValue.trim() : "";
|
|
1168
|
+
if (!isValidEnvKey(envKey))
|
|
1169
|
+
return { error: `Invalid envKey format: ${rawKey}` };
|
|
1170
|
+
if (!credential)
|
|
1171
|
+
return { error: `Missing value for envKey: ${envKey}` };
|
|
1172
|
+
updates[envKey] = credential;
|
|
1173
|
+
}
|
|
1174
|
+
return { updates };
|
|
1175
|
+
}
|
|
1176
|
+
const envKey = data.envKey?.trim() ?? "";
|
|
1177
|
+
const credential = data.credential?.trim() ?? "";
|
|
1178
|
+
if (!isValidEnvKey(envKey))
|
|
1179
|
+
return { error: "Invalid envKey format" };
|
|
1180
|
+
if (!credential)
|
|
1181
|
+
return { error: "Missing required field: credential" };
|
|
1182
|
+
return { updates: { [envKey]: credential } };
|
|
1183
|
+
}
|
|
1184
|
+
function renderStoredEnvMessage(envKeys) {
|
|
1185
|
+
if (envKeys.length === 1) {
|
|
1186
|
+
return `${envKeys[0]} stored successfully in vault.`;
|
|
1187
|
+
}
|
|
1188
|
+
return `${envKeys.length} secrets stored successfully in vault: ${envKeys.join(", ")}.`;
|
|
1189
|
+
}
|
|
1190
|
+
// ── API-key completion ────────────────────────────────────────────────────────
|
|
1191
|
+
async function handleLinkComplete(body, linkTokenStore, vaultManager, notify, res) {
|
|
1192
|
+
let data;
|
|
1193
|
+
try {
|
|
1194
|
+
data = JSON.parse(body);
|
|
1195
|
+
}
|
|
1196
|
+
catch {
|
|
1197
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1198
|
+
res.end(JSON.stringify({ error: "Invalid JSON" }));
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
if (!data.token) {
|
|
1202
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1203
|
+
res.end(JSON.stringify({ error: "Missing required field: token" }));
|
|
1204
|
+
return;
|
|
1205
|
+
}
|
|
1206
|
+
const { updates, error } = extractEnvUpdates(data);
|
|
1207
|
+
if (!updates || error) {
|
|
1208
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1209
|
+
res.end(JSON.stringify({ error: error ?? "Invalid env payload" }));
|
|
1210
|
+
return;
|
|
1211
|
+
}
|
|
1212
|
+
const envKeys = Object.keys(updates).toSorted((left, right) => left.localeCompare(right));
|
|
1213
|
+
// Atomic consume prevents two concurrent requests from both passing the
|
|
1214
|
+
// validity check before either deletes the token.
|
|
1215
|
+
const linkToken = linkTokenStore.consume(data.token);
|
|
1216
|
+
if (!linkToken) {
|
|
1217
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1218
|
+
res.end(JSON.stringify({ error: "Invalid or expired token" }));
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
try {
|
|
1222
|
+
vaultManager.upsertEnv(linkToken.vaultId, updates);
|
|
1223
|
+
}
|
|
1224
|
+
catch (persistError) {
|
|
1225
|
+
log.logWarning(`Failed to persist [${envKeys.join(", ")}] for ${linkToken.platform}/${linkToken.platformUserId}`, persistError instanceof Error ? persistError.message : String(persistError));
|
|
1226
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
1227
|
+
res.end(JSON.stringify({
|
|
1228
|
+
error: "Failed to store credential on server. Please fix the server issue and run /login again.",
|
|
1229
|
+
}));
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
log.logInfo(`Stored [${envKeys.join(", ")}] for ${linkToken.platform}/${linkToken.platformUserId} in vault:${linkToken.vaultId}`);
|
|
1233
|
+
const message = renderStoredEnvMessage(envKeys);
|
|
1234
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1235
|
+
res.end(JSON.stringify({ ok: true, message }));
|
|
1236
|
+
notify(linkToken.platform, linkToken.conversationId, `${message} Vault: \`${linkToken.vaultId}\`.`).catch((err) => {
|
|
1237
|
+
log.logWarning("Failed to notify user after credential login", err.message);
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
// ── OAuth flow ────────────────────────────────────────────────────────────────
|
|
1241
|
+
async function handleOAuthStart(body, req, linkTokenStore, oauthStates, res) {
|
|
1242
|
+
let data;
|
|
1243
|
+
try {
|
|
1244
|
+
data = JSON.parse(body);
|
|
1245
|
+
}
|
|
1246
|
+
catch {
|
|
1247
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1248
|
+
res.end(JSON.stringify({ error: "Invalid JSON" }));
|
|
1249
|
+
return;
|
|
1250
|
+
}
|
|
1251
|
+
if (!data.token || !data.serviceId) {
|
|
1252
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1253
|
+
res.end(JSON.stringify({ error: "Missing required fields: token/serviceId" }));
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
const linkToken = linkTokenStore.peek(data.token);
|
|
1257
|
+
if (!linkToken) {
|
|
1258
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1259
|
+
res.end(JSON.stringify({ error: "Invalid or expired token" }));
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
const service = resolveOAuthService(data.serviceId);
|
|
1263
|
+
if (!service) {
|
|
1264
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1265
|
+
res.end(JSON.stringify({ error: `Unsupported OAuth service: ${data.serviceId}` }));
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1268
|
+
const clientId = process.env[service.clientIdEnvKey];
|
|
1269
|
+
const clientSecret = process.env[service.clientSecretEnvKey];
|
|
1270
|
+
if (!clientId || !clientSecret) {
|
|
1271
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1272
|
+
res.end(JSON.stringify({
|
|
1273
|
+
error: `OAuth service ${service.label} is not configured. ` +
|
|
1274
|
+
`Missing ${service.clientIdEnvKey}/${service.clientSecretEnvKey}.`,
|
|
1275
|
+
}));
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
const state = randomBytes(16).toString("hex");
|
|
1279
|
+
const codeVerifier = randomBytes(32).toString("base64url");
|
|
1280
|
+
oauthStates.set(state, {
|
|
1281
|
+
linkToken: data.token,
|
|
1282
|
+
serviceId: service.id,
|
|
1283
|
+
codeVerifier,
|
|
1284
|
+
expiresAt: Date.now() + OAUTH_STATE_TTL_MS,
|
|
1285
|
+
});
|
|
1286
|
+
for (const [k, v] of oauthStates) {
|
|
1287
|
+
if (Date.now() > v.expiresAt)
|
|
1288
|
+
oauthStates.delete(k);
|
|
1289
|
+
}
|
|
1290
|
+
const redirectUri = `${requestBaseUrl(req)}/oauth/callback`;
|
|
1291
|
+
const authorizeUrl = new URL(service.authorizationUrl);
|
|
1292
|
+
authorizeUrl.searchParams.set("response_type", "code");
|
|
1293
|
+
authorizeUrl.searchParams.set("client_id", clientId);
|
|
1294
|
+
authorizeUrl.searchParams.set("redirect_uri", redirectUri);
|
|
1295
|
+
authorizeUrl.searchParams.set("state", state);
|
|
1296
|
+
if (service.scopes.length > 0) {
|
|
1297
|
+
authorizeUrl.searchParams.set("scope", service.scopes.join(" "));
|
|
1298
|
+
}
|
|
1299
|
+
for (const [key, value] of Object.entries(service.authorizationParams ?? {})) {
|
|
1300
|
+
authorizeUrl.searchParams.set(key, value);
|
|
1301
|
+
}
|
|
1302
|
+
const codeChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
|
|
1303
|
+
authorizeUrl.searchParams.set("code_challenge", codeChallenge);
|
|
1304
|
+
authorizeUrl.searchParams.set("code_challenge_method", "S256");
|
|
1305
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1306
|
+
res.end(JSON.stringify({ ok: true, redirectUrl: authorizeUrl.toString() }));
|
|
1307
|
+
}
|
|
1308
|
+
async function handleOAuthCallback(url, req, linkTokenStore, vaultManager, notify, oauthStates, res) {
|
|
1309
|
+
const state = url.searchParams.get("state") ?? "";
|
|
1310
|
+
const code = url.searchParams.get("code") ?? "";
|
|
1311
|
+
const oauthError = url.searchParams.get("error");
|
|
1312
|
+
// Atomic pop: whatever path we take from here, this state is spent.
|
|
1313
|
+
// Done before any `await` to close the TOCTOU window between the state
|
|
1314
|
+
// lookup and the final delete.
|
|
1315
|
+
const pending = oauthStates.get(state);
|
|
1316
|
+
if (pending)
|
|
1317
|
+
oauthStates.delete(state);
|
|
1318
|
+
if (oauthError) {
|
|
1319
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
1320
|
+
res.end(renderErrorPage(`OAuth authorization failed: ${oauthError}`));
|
|
1321
|
+
return;
|
|
1322
|
+
}
|
|
1323
|
+
if (!pending || Date.now() > pending.expiresAt) {
|
|
1324
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
1325
|
+
res.end(renderErrorPage("OAuth state is invalid or expired. Please run /login again."));
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
if (!code) {
|
|
1329
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
1330
|
+
res.end(renderErrorPage("Missing OAuth authorization code."));
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
const service = resolveOAuthService(pending.serviceId);
|
|
1334
|
+
if (!service) {
|
|
1335
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
1336
|
+
res.end(renderErrorPage("Unsupported OAuth service."));
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
const clientId = process.env[service.clientIdEnvKey];
|
|
1340
|
+
const clientSecret = process.env[service.clientSecretEnvKey];
|
|
1341
|
+
if (!clientId || !clientSecret) {
|
|
1342
|
+
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
|
1343
|
+
res.end(renderErrorPage("OAuth service is not configured on server."));
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
1346
|
+
// Atomic consume: pairs with the callback being one-shot. Two concurrent
|
|
1347
|
+
// callbacks for the same state would previously both pass `peek` and both
|
|
1348
|
+
// run `exchangeOAuthCode` across the await; only one reaches `consume`.
|
|
1349
|
+
const linkToken = linkTokenStore.consume(pending.linkToken);
|
|
1350
|
+
if (!linkToken) {
|
|
1351
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
1352
|
+
res.end(renderErrorPage("Login link is invalid or expired. Please run /login again."));
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
const redirectUri = `${requestBaseUrl(req)}/oauth/callback`;
|
|
1356
|
+
const tokenResp = await exchangeOAuthCode(service, code, clientId, clientSecret, redirectUri, pending.codeVerifier);
|
|
1357
|
+
const accessToken = tokenResp.access_token?.trim();
|
|
1358
|
+
const refreshToken = tokenResp.refresh_token?.trim();
|
|
1359
|
+
if (!accessToken) {
|
|
1360
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
1361
|
+
res.end(renderErrorPage("OAuth token exchange did not return an access_token."));
|
|
1362
|
+
return;
|
|
1363
|
+
}
|
|
1364
|
+
const updates = {};
|
|
1365
|
+
if (service.accessTokenEnvKey) {
|
|
1366
|
+
updates[service.accessTokenEnvKey] = accessToken;
|
|
1367
|
+
}
|
|
1368
|
+
for (const key of service.additionalAccessTokenEnvKeys ?? []) {
|
|
1369
|
+
updates[key] = accessToken;
|
|
1370
|
+
}
|
|
1371
|
+
if (refreshToken && service.refreshTokenEnvKey) {
|
|
1372
|
+
updates[service.refreshTokenEnvKey] = refreshToken;
|
|
1373
|
+
}
|
|
1374
|
+
const fileOutput = service.fileOutput;
|
|
1375
|
+
let mountedPath;
|
|
1376
|
+
if (fileOutput?.type === "authorized_user") {
|
|
1377
|
+
if (!refreshToken) {
|
|
1378
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
1379
|
+
res.end(renderErrorPage("OAuth token exchange did not return a refresh_token. " +
|
|
1380
|
+
"Retry after revoking prior consent or ensure prompt=consent is applied."));
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
mountedPath = fileOutput.targetPath ?? defaultVaultTargetPath(fileOutput.relativePath);
|
|
1384
|
+
if (fileOutput.envKey) {
|
|
1385
|
+
updates[fileOutput.envKey] = mountedPath;
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
const storedTargets = [];
|
|
1389
|
+
try {
|
|
1390
|
+
if (Object.keys(updates).length > 0) {
|
|
1391
|
+
vaultManager.upsertEnv(linkToken.vaultId, updates);
|
|
1392
|
+
storedTargets.push(...Object.keys(updates).toSorted());
|
|
1393
|
+
}
|
|
1394
|
+
if (fileOutput?.type === "authorized_user" && refreshToken) {
|
|
1395
|
+
vaultManager.upsertFile(linkToken.vaultId, fileOutput.relativePath, renderAuthorizedUserCredential(clientId, clientSecret, refreshToken), fileOutput.targetPath);
|
|
1396
|
+
if (mountedPath)
|
|
1397
|
+
storedTargets.push(mountedPath);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
catch (persistError) {
|
|
1401
|
+
log.logWarning(`Failed to persist OAuth credentials for ${linkToken.platform}/${linkToken.platformUserId}`, persistError instanceof Error ? persistError.message : String(persistError));
|
|
1402
|
+
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
|
1403
|
+
res.end(renderErrorPage("OAuth tokens were received but could not be stored on the server. Fix the server issue and run /login again."));
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
log.logInfo(`Stored [${storedTargets.join(", ")}] for ${linkToken.platform}/${linkToken.platformUserId} in vault:${linkToken.vaultId}`);
|
|
1407
|
+
notify(linkToken.platform, linkToken.conversationId, `${service.label} OAuth stored (${storedTargets.join(", ")}) in vault \`${linkToken.vaultId}\`.`).catch((err) => {
|
|
1408
|
+
log.logWarning("Failed to notify user after OAuth login", err.message);
|
|
1409
|
+
});
|
|
1410
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
1411
|
+
res.end(renderSuccessPage(`${service.label} OAuth connected successfully.`));
|
|
1412
|
+
}
|
|
1413
|
+
async function exchangeOAuthCode(service, code, clientId, clientSecret, redirectUri, codeVerifier) {
|
|
1414
|
+
const params = new URLSearchParams();
|
|
1415
|
+
params.set("grant_type", "authorization_code");
|
|
1416
|
+
params.set("code", code);
|
|
1417
|
+
params.set("client_id", clientId);
|
|
1418
|
+
params.set("client_secret", clientSecret);
|
|
1419
|
+
params.set("redirect_uri", redirectUri);
|
|
1420
|
+
params.set("code_verifier", codeVerifier);
|
|
1421
|
+
const response = await fetch(service.tokenUrl, {
|
|
1422
|
+
method: "POST",
|
|
1423
|
+
headers: {
|
|
1424
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1425
|
+
Accept: "application/json",
|
|
1426
|
+
},
|
|
1427
|
+
body: params.toString(),
|
|
1428
|
+
});
|
|
1429
|
+
const text = await response.text();
|
|
1430
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
1431
|
+
let parsed = {};
|
|
1432
|
+
if (contentType.includes("application/json")) {
|
|
1433
|
+
parsed = JSON.parse(text);
|
|
1434
|
+
}
|
|
1435
|
+
else {
|
|
1436
|
+
const form = new URLSearchParams(text);
|
|
1437
|
+
parsed = Object.fromEntries(form.entries());
|
|
1438
|
+
}
|
|
1439
|
+
if (!response.ok) {
|
|
1440
|
+
const message = parsed.error_description ?? parsed.error ?? `${response.status}`;
|
|
1441
|
+
throw new Error(`OAuth token exchange failed for ${service.id}: ${message}`);
|
|
1442
|
+
}
|
|
1443
|
+
return parsed;
|
|
1444
|
+
}
|
|
1445
|
+
function renderAuthorizedUserCredential(clientId, clientSecret, refreshToken) {
|
|
1446
|
+
return (JSON.stringify({
|
|
1447
|
+
client_id: clientId,
|
|
1448
|
+
client_secret: clientSecret,
|
|
1449
|
+
refresh_token: refreshToken,
|
|
1450
|
+
type: "authorized_user",
|
|
1451
|
+
}, null, 2) + "\n");
|
|
1452
|
+
}
|
|
1453
|
+
//# sourceMappingURL=portal.js.map
|