@humain/humain-code 0.5.0 → 0.5.4
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/CHANGELOG.md +47 -1
- package/README.md +5 -3
- package/dist/agent-monitor/client.d.ts +2 -2
- package/dist/agent-monitor/client.d.ts.map +1 -1
- package/dist/agent-monitor/client.js +3 -2
- package/dist/agent-monitor/client.js.map +1 -1
- package/dist/bundle/chunks/anthropic.js +10 -9
- package/dist/bundle/chunks/{chunk-DR37WKFZ.js → chunk-AO6FF5JL.js} +1 -1
- package/dist/bundle/chunks/{chunk-Q3SFYT2X.js → chunk-EY3LZOUP.js} +1356 -1358
- package/dist/bundle/chunks/{chunk-T3HXWZG4.js → chunk-L2VKM23Q.js} +76 -2
- package/dist/bundle/chunks/{chunk-5C4VL2AR.js → chunk-ODJUBJK2.js} +2 -2
- package/dist/bundle/chunks/{chunk-A6YBWW4T.js → chunk-UJLCKIMZ.js} +646 -495
- package/dist/bundle/chunks/{chunk-476XBL3W.js → chunk-Y3OPKKDR.js} +3 -77
- package/dist/bundle/chunks/{cli-VXU7OWFU.js → cli-ENEFJH2B.js} +1 -1
- package/dist/bundle/chunks/{compat-S2IBVV6V.js → compat-CJBWWYHE.js} +1 -1
- package/dist/bundle/chunks/{dist-645GFIWH.js → dist-RKNCFFGM.js} +2 -2
- package/dist/bundle/chunks/github-copilot.js +28 -26
- package/dist/bundle/chunks/openai-chatgpt.js +2 -2
- package/dist/bundle/chunks/openai-codex.js +10 -9
- package/dist/bundle/chunks/openrouter.js +10 -9
- package/dist/bundle/chunks/radius.js +9 -8
- package/dist/bundle/chunks/{runtime-5VFZTMWL.js → runtime-K3F2QDQP.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-GU6AW5ZK.js → virtual-modules-5D6QIJPN.js} +2 -2
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +4 -4
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +19 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +24 -2
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/safe-credential-error.d.ts +11 -0
- package/dist/core/safe-credential-error.d.ts.map +1 -0
- package/dist/core/safe-credential-error.js +14 -0
- package/dist/core/safe-credential-error.js.map +1 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +4 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-schema.d.ts +3 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +6 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/humain/gateway/catalog.d.ts +36 -0
- package/dist/humain/gateway/catalog.d.ts.map +1 -0
- package/dist/humain/gateway/catalog.js +74 -0
- package/dist/humain/gateway/catalog.js.map +1 -0
- package/dist/humain/gateway/client.d.ts +58 -0
- package/dist/humain/gateway/client.d.ts.map +1 -0
- package/dist/humain/gateway/client.js +212 -0
- package/dist/humain/gateway/client.js.map +1 -0
- package/dist/humain/gateway/constants.d.ts +23 -0
- package/dist/humain/gateway/constants.d.ts.map +1 -0
- package/dist/humain/gateway/constants.js +32 -0
- package/dist/humain/gateway/constants.js.map +1 -0
- package/dist/humain/gateway/http.d.ts +18 -0
- package/dist/humain/gateway/http.d.ts.map +1 -0
- package/dist/humain/gateway/http.js +274 -0
- package/dist/humain/gateway/http.js.map +1 -0
- package/dist/humain/gateway/login.d.ts +13 -0
- package/dist/humain/gateway/login.d.ts.map +1 -0
- package/dist/humain/gateway/login.js +121 -0
- package/dist/humain/gateway/login.js.map +1 -0
- package/dist/humain/gateway/provider.d.ts +34 -0
- package/dist/humain/gateway/provider.d.ts.map +1 -0
- package/dist/humain/gateway/provider.js +253 -0
- package/dist/humain/gateway/provider.js.map +1 -0
- package/dist/humain/gateway/secret-store.d.ts +19 -0
- package/dist/humain/gateway/secret-store.d.ts.map +1 -0
- package/dist/humain/gateway/secret-store.js +252 -0
- package/dist/humain/gateway/secret-store.js.map +1 -0
- package/dist/humain/gateway/session-store.d.ts +42 -0
- package/dist/humain/gateway/session-store.d.ts.map +1 -0
- package/dist/humain/gateway/session-store.js +175 -0
- package/dist/humain/gateway/session-store.js.map +1 -0
- package/dist/humain/index.d.ts.map +1 -1
- package/dist/humain/index.js +2 -0
- package/dist/humain/index.js.map +1 -1
- package/dist/humain/login-menu.d.ts +14 -0
- package/dist/humain/login-menu.d.ts.map +1 -0
- package/dist/humain/login-menu.js +21 -0
- package/dist/humain/login-menu.js.map +1 -0
- package/dist/humain/node-http.d.ts.map +1 -1
- package/dist/humain/node-http.js +6 -31
- package/dist/humain/node-http.js.map +1 -1
- package/dist/humain/redact-assistant-message.d.ts +4 -0
- package/dist/humain/redact-assistant-message.d.ts.map +1 -0
- package/dist/humain/redact-assistant-message.js +34 -0
- package/dist/humain/redact-assistant-message.js.map +1 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +17 -4
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +3 -2
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +11 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +16 -3
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.d.ts +5 -4
- package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.js +11 -9
- package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +53 -36
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/sleep.d.ts +1 -1
- package/dist/utils/sleep.d.ts.map +1 -1
- package/dist/utils/sleep.js +10 -6
- package/dist/utils/sleep.js.map +1 -1
- package/docs/assets/humain-code-logo.svg +8 -0
- package/docs/humain-code.md +13 -1
- package/docs/index.md +1 -1
- package/docs/models.md +3 -1
- package/docs/providers.md +58 -2
- package/docs/quickstart.md +8 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/schemas/settings.schema.json +19 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { createProvider, } from "@earendil-works/pi-ai";
|
|
2
|
+
import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
|
|
3
|
+
import { getAgentDir } from "../../config.js";
|
|
4
|
+
import { ReadOnlyAuthStorage } from "../../core/auth-storage.js";
|
|
5
|
+
import { SettingsManager } from "../../core/settings-manager.js";
|
|
6
|
+
import { DEFAULT_BLOCK_REASON, deriveGatewayCatalog, GATEWAY_SETUP_WARNING } from "./catalog.js";
|
|
7
|
+
import { fetchGatewayAccess, fetchGatewayModels, GatewayBudgetExhaustedError, GatewaySessionUnavailableError, } from "./client.js";
|
|
8
|
+
import { GATEWAY_BASE_URLS, GATEWAY_ENV_ENVIRONMENT, GATEWAY_ENV_SESSION_ID, GATEWAY_ENV_USER_ID, HUMAIN_GATEWAY_PROVIDER, } from "./constants.js";
|
|
9
|
+
import { withHumainGatewayHttp } from "./http.js";
|
|
10
|
+
import { loginToGateway, revokePendingSessions } from "./login.js";
|
|
11
|
+
import { createGatewaySecretStore } from "./secret-store.js";
|
|
12
|
+
import { GatewaySessionStore } from "./session-store.js";
|
|
13
|
+
const ACCESS_RETRY_MS = 60_000;
|
|
14
|
+
const ACCESS_READ_WARNING = "HUMAIN Gateway could not read account restrictions; showing all listed models.";
|
|
15
|
+
const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
16
|
+
/** Used when no access answer exists: `/v1/models` stays authoritative and stored blocks are kept. */
|
|
17
|
+
const NULL_LABEL_ACCESS = {
|
|
18
|
+
accessKind: "unrestricted",
|
|
19
|
+
models: [],
|
|
20
|
+
modelModes: {},
|
|
21
|
+
harnessLabels: null,
|
|
22
|
+
degraded: null,
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Global user settings only: a repository's project settings must never redirect Gateway credentials.
|
|
26
|
+
* `ok` is false when the global settings read failed (e.g. a lock held by another process), so the
|
|
27
|
+
* production fallback must not be cached.
|
|
28
|
+
*/
|
|
29
|
+
export function readGatewayEnvironment(cwd, agentDir) {
|
|
30
|
+
const settings = SettingsManager.create(cwd, agentDir);
|
|
31
|
+
const gateway = settings.getGlobalSettings().humainGateway;
|
|
32
|
+
const environment = gateway?.environment === "staging" ? "staging" : "production";
|
|
33
|
+
return {
|
|
34
|
+
environment,
|
|
35
|
+
ok: !settings.drainErrors().some((error) => error.scope === "global"),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const baseUrlFor = (environment) => `${GATEWAY_BASE_URLS[environment]}/v1`;
|
|
39
|
+
/** Non-secret session reference from `auth.json`, only when it belongs to the selected environment. */
|
|
40
|
+
function sessionOf(credential, environment) {
|
|
41
|
+
const env = credential?.type === "api_key" ? credential.env : undefined;
|
|
42
|
+
const id = env?.[GATEWAY_ENV_SESSION_ID];
|
|
43
|
+
if (env?.[GATEWAY_ENV_ENVIRONMENT] !== environment || typeof id !== "string" || !id)
|
|
44
|
+
return undefined;
|
|
45
|
+
const userId = env[GATEWAY_ENV_USER_ID];
|
|
46
|
+
return { id, userId: typeof userId === "string" ? userId : "" };
|
|
47
|
+
}
|
|
48
|
+
function toModel(entry, environment) {
|
|
49
|
+
return {
|
|
50
|
+
id: entry.id,
|
|
51
|
+
name: environment === "staging" ? `${entry.id} (staging)` : entry.id,
|
|
52
|
+
api: "openai-responses",
|
|
53
|
+
provider: HUMAIN_GATEWAY_PROVIDER,
|
|
54
|
+
baseUrl: baseUrlFor(environment),
|
|
55
|
+
reasoning: false,
|
|
56
|
+
input: ["text"],
|
|
57
|
+
cost: ZERO_COST,
|
|
58
|
+
contextWindow: entry.contextWindow,
|
|
59
|
+
maxTokens: entry.maxTokens,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** Defers platform detection to first use: a missing keychain must fail sign-in, not provider registration. */
|
|
63
|
+
function lazySecretStore() {
|
|
64
|
+
let store;
|
|
65
|
+
const resolve = () => {
|
|
66
|
+
store ??= createGatewaySecretStore();
|
|
67
|
+
return store;
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
get: async (account) => resolve().get(account),
|
|
71
|
+
set: async (account, secret) => resolve().set(account, secret),
|
|
72
|
+
delete: async (account) => resolve().delete(account),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
let processEnvironment;
|
|
76
|
+
/**
|
|
77
|
+
* Cached per process after a clean read: settings reads take file locks and fall back to production when
|
|
78
|
+
* another process holds them, so a failed read is retried. Changing `humainGateway.environment` therefore needs a restart.
|
|
79
|
+
*/
|
|
80
|
+
const defaultEnvironment = () => {
|
|
81
|
+
if (processEnvironment)
|
|
82
|
+
return processEnvironment;
|
|
83
|
+
const { environment, ok } = readGatewayEnvironment(process.cwd(), getAgentDir());
|
|
84
|
+
if (ok)
|
|
85
|
+
processEnvironment = environment;
|
|
86
|
+
return environment;
|
|
87
|
+
};
|
|
88
|
+
export function resetGatewayEnvironmentCacheForTests() {
|
|
89
|
+
processEnvironment = undefined;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Only interactive sessions reconcile at startup: print, JSON and RPC processes are short-lived, and a
|
|
93
|
+
* background revocation would keep them alive.
|
|
94
|
+
*/
|
|
95
|
+
export function shouldReconcileGatewayOnStartup(mode, offline, listModels = false) {
|
|
96
|
+
return mode === "interactive" && !offline && !listModels;
|
|
97
|
+
}
|
|
98
|
+
/** Maps the settled reads of a refresh to the listed models or the error to report. */
|
|
99
|
+
function mapRefreshResults(listed, accessed) {
|
|
100
|
+
for (const result of [listed, accessed]) {
|
|
101
|
+
if (result.status === "rejected" && result.reason instanceof GatewaySessionUnavailableError) {
|
|
102
|
+
return { error: result.reason, clearCatalog: true };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (listed.status === "fulfilled")
|
|
106
|
+
return { models: listed.value };
|
|
107
|
+
// Budget: keep the last good list for this scope; other failures never fabricate a catalog.
|
|
108
|
+
const setupPending = !(listed.reason instanceof GatewayBudgetExhaustedError) &&
|
|
109
|
+
accessed.status === "fulfilled" &&
|
|
110
|
+
accessed.value.accessKind === "unknown";
|
|
111
|
+
return { error: setupPending ? new Error(GATEWAY_SETUP_WARNING) : listed.reason, clearCatalog: false };
|
|
112
|
+
}
|
|
113
|
+
async function saveBlockedModels(sessions, environment, userId, previous, next) {
|
|
114
|
+
if (JSON.stringify(next) !== JSON.stringify(previous))
|
|
115
|
+
await sessions.setBlockedModels(environment, userId, next);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Startup reconciliation: revokes sessions orphaned by `/logout`, which leaves no credential and so
|
|
119
|
+
* never reaches the refresh network phase. Touches the keychain only when pending records exist.
|
|
120
|
+
*/
|
|
121
|
+
export async function revokeGatewayOrphans(deps = {}) {
|
|
122
|
+
const env = (deps.environment ?? defaultEnvironment)();
|
|
123
|
+
const sessions = deps.sessions ?? new GatewaySessionStore({ secrets: lazySecretStore() });
|
|
124
|
+
const readCredential = deps.readCredential ?? (() => new ReadOnlyAuthStorage().readRaw(HUMAIN_GATEWAY_PROVIDER));
|
|
125
|
+
await sessions.markOrphansPending(env, sessionOf(await readCredential(), env)?.id);
|
|
126
|
+
await revokePendingSessions(GATEWAY_BASE_URLS[env], env, sessions, deps.fetch);
|
|
127
|
+
}
|
|
128
|
+
export function createHumainGatewayProvider(deps = {}) {
|
|
129
|
+
const environment = deps.environment ?? defaultEnvironment;
|
|
130
|
+
const sessions = deps.sessions ?? new GatewaySessionStore({ secrets: lazySecretStore() });
|
|
131
|
+
let models = [];
|
|
132
|
+
let activeScope;
|
|
133
|
+
// Last successful access read, for one scope only.
|
|
134
|
+
let lastAccess;
|
|
135
|
+
const lastAccessFor = (scope) => (lastAccess?.scope === scope ? lastAccess.access : undefined);
|
|
136
|
+
// Last blocked set shown for one scope, so an unchanged set is not repeated.
|
|
137
|
+
let shownBlocked;
|
|
138
|
+
/** Refetched every refresh, except within 60 s of an unknown or degraded answer. */
|
|
139
|
+
const loadAccess = async (scope, baseUrl, token, options) => {
|
|
140
|
+
const now = Date.now();
|
|
141
|
+
const last = lastAccess?.scope === scope ? lastAccess : undefined;
|
|
142
|
+
if (last &&
|
|
143
|
+
(last.access.accessKind === "unknown" || last.access.degraded !== null) &&
|
|
144
|
+
now - last.at < ACCESS_RETRY_MS) {
|
|
145
|
+
return last.access;
|
|
146
|
+
}
|
|
147
|
+
const access = await fetchGatewayAccess(baseUrl, token, options);
|
|
148
|
+
if (!options.signal.aborted)
|
|
149
|
+
lastAccess = { scope, access, at: now };
|
|
150
|
+
return access;
|
|
151
|
+
};
|
|
152
|
+
const apiKeyAuth = {
|
|
153
|
+
name: "HUMAIN Gateway",
|
|
154
|
+
login: (interaction) => loginToGateway(interaction, { environment: environment(), sessions, fetch: deps.fetch }),
|
|
155
|
+
// Metadata only: listing must not touch the keychain or the network.
|
|
156
|
+
check: async ({ credential, signal }) => {
|
|
157
|
+
signal.throwIfAborted();
|
|
158
|
+
const env = environment();
|
|
159
|
+
return sessionOf(credential, env)
|
|
160
|
+
? { type: "api_key", source: `HUMAIN Gateway (${env})` }
|
|
161
|
+
: undefined;
|
|
162
|
+
},
|
|
163
|
+
resolve: async ({ credential, signal }) => {
|
|
164
|
+
signal.throwIfAborted();
|
|
165
|
+
const env = environment();
|
|
166
|
+
const session = sessionOf(credential, env);
|
|
167
|
+
const token = session ? await sessions.getToken(session.id) : undefined;
|
|
168
|
+
if (!token)
|
|
169
|
+
return undefined;
|
|
170
|
+
// `env` carries only the non-secret session reference so catalog refreshes keep their scope.
|
|
171
|
+
return {
|
|
172
|
+
auth: { apiKey: token, baseUrl: baseUrlFor(env) },
|
|
173
|
+
env: { ...credential?.env },
|
|
174
|
+
source: `HUMAIN Gateway (${env})`,
|
|
175
|
+
};
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
const base = createProvider({
|
|
179
|
+
id: HUMAIN_GATEWAY_PROVIDER,
|
|
180
|
+
name: "HUMAIN Gateway",
|
|
181
|
+
baseUrl: baseUrlFor("production"),
|
|
182
|
+
auth: { apiKey: apiKeyAuth },
|
|
183
|
+
models: [],
|
|
184
|
+
api: { "openai-responses": withHumainGatewayHttp(openAIResponsesApi()) },
|
|
185
|
+
});
|
|
186
|
+
return {
|
|
187
|
+
...base,
|
|
188
|
+
getModels: () => models,
|
|
189
|
+
refreshModels: async (context) => {
|
|
190
|
+
const env = environment();
|
|
191
|
+
const session = sessionOf(context.credential, env);
|
|
192
|
+
const scope = session ? `${env}\0${session.id}` : undefined;
|
|
193
|
+
const publish = (next) => context.publish({
|
|
194
|
+
persist: null,
|
|
195
|
+
update: () => {
|
|
196
|
+
models = next;
|
|
197
|
+
activeScope = scope;
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
if (scope !== activeScope && !(await publish([])))
|
|
201
|
+
return;
|
|
202
|
+
// No session can mean an unreadable auth.json, a runtime key override, or another agentDir;
|
|
203
|
+
// logout cleanup is left to revokeGatewayOrphans, which stops when the credential read fails.
|
|
204
|
+
if (session)
|
|
205
|
+
await sessions.markOrphansPending(env, session.id);
|
|
206
|
+
if (!context.allowNetwork || context.signal.aborted)
|
|
207
|
+
return;
|
|
208
|
+
const baseUrl = GATEWAY_BASE_URLS[env];
|
|
209
|
+
await revokePendingSessions(baseUrl, env, sessions, deps.fetch);
|
|
210
|
+
// The network phase receives the token resolved in-process as `key`.
|
|
211
|
+
const token = context.credential?.type === "api_key" ? context.credential.key : undefined;
|
|
212
|
+
if (!session || !scope || !token)
|
|
213
|
+
return;
|
|
214
|
+
const options = { fetch: deps.fetch, signal: context.signal };
|
|
215
|
+
const [listed, accessed] = await Promise.allSettled([
|
|
216
|
+
fetchGatewayModels(baseUrl, token, options),
|
|
217
|
+
loadAccess(scope, baseUrl, token, options),
|
|
218
|
+
]);
|
|
219
|
+
if (context.signal.aborted)
|
|
220
|
+
return;
|
|
221
|
+
const listing = mapRefreshResults(listed, accessed);
|
|
222
|
+
if ("error" in listing) {
|
|
223
|
+
if (listing.clearCatalog)
|
|
224
|
+
await publish([]);
|
|
225
|
+
throw listing.error;
|
|
226
|
+
}
|
|
227
|
+
// A failed access read reuses this scope's last answer; without one, `/v1/models` alone decides.
|
|
228
|
+
const access = accessed.status === "fulfilled" ? accessed.value : lastAccessFor(scope);
|
|
229
|
+
const previouslyBlocked = await sessions.getBlockedModels(env, session.userId);
|
|
230
|
+
const catalog = deriveGatewayCatalog({
|
|
231
|
+
models: listing.models,
|
|
232
|
+
access: access ?? NULL_LABEL_ACCESS,
|
|
233
|
+
previouslyBlocked,
|
|
234
|
+
});
|
|
235
|
+
await saveBlockedModels(sessions, env, session.userId, previouslyBlocked, catalog.blocked);
|
|
236
|
+
if (!(await publish(catalog.eligible.map((entry) => toModel(entry, env)))))
|
|
237
|
+
return;
|
|
238
|
+
const warnings = access ? catalog.warnings : [...catalog.warnings, ACCESS_READ_WARNING];
|
|
239
|
+
const listedIds = new Set(listing.models.map((entry) => entry.id));
|
|
240
|
+
const blocked = Object.entries(catalog.blocked)
|
|
241
|
+
.filter(([id]) => listedIds.has(id))
|
|
242
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
243
|
+
const blockedKey = JSON.stringify(blocked);
|
|
244
|
+
if (blocked.length > 0 && (shownBlocked?.scope !== scope || shownBlocked.key !== blockedKey)) {
|
|
245
|
+
warnings.push(`Blocked for HUMAIN Code by HUMAIN Gateway: ${blocked.map(([id, reason]) => (reason === DEFAULT_BLOCK_REASON ? id : `${id} (${reason})`)).join("; ")}`);
|
|
246
|
+
}
|
|
247
|
+
shownBlocked = { scope, key: blockedKey };
|
|
248
|
+
if (warnings.length > 0)
|
|
249
|
+
throw new Error(warnings.join(" "));
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/humain/gateway/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,cAAc,GAId,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AACjG,OAAO,EACN,kBAAkB,EAClB,kBAAkB,EAElB,2BAA2B,EAE3B,8BAA8B,GAC9B,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,iBAAiB,EACjB,uBAAuB,EACvB,sBAAsB,EACtB,mBAAmB,EAEnB,uBAAuB,GACvB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,wBAAwB,EAA2B,MAAM,mBAAmB,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAQzD,MAAM,eAAe,GAAG,MAAM,CAAC;AAC/B,MAAM,mBAAmB,GAAG,gFAAgF,CAAC;AAC7G,MAAM,SAAS,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS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,IAAI,CACZ,8CAA8C,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,MAAM,KAAK,oBAAoB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACtJ,CAAC;YACH,CAAC;YACD,YAAY,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC;YAC1C,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAC9D,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\ttype Api,\n\ttype ApiKeyAuth,\n\ttype AuthResult,\n\ttype Credential,\n\tcreateProvider,\n\ttype Model,\n\ttype Provider,\n\ttype RefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { openAIResponsesApi } from \"@earendil-works/pi-ai/api/openai-responses.lazy\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { ReadOnlyAuthStorage } from \"../../core/auth-storage.ts\";\nimport type { AppMode } from \"../../core/project-trust.ts\";\nimport { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { DEFAULT_BLOCK_REASON, deriveGatewayCatalog, GATEWAY_SETUP_WARNING } from \"./catalog.ts\";\nimport {\n\tfetchGatewayAccess,\n\tfetchGatewayModels,\n\ttype GatewayAccess,\n\tGatewayBudgetExhaustedError,\n\ttype GatewayModelEntry,\n\tGatewaySessionUnavailableError,\n} from \"./client.ts\";\nimport {\n\tGATEWAY_BASE_URLS,\n\tGATEWAY_ENV_ENVIRONMENT,\n\tGATEWAY_ENV_SESSION_ID,\n\tGATEWAY_ENV_USER_ID,\n\ttype GatewayEnvironment,\n\tHUMAIN_GATEWAY_PROVIDER,\n} from \"./constants.ts\";\nimport { withHumainGatewayHttp } from \"./http.ts\";\nimport { loginToGateway, revokePendingSessions } from \"./login.ts\";\nimport { createGatewaySecretStore, type GatewaySecretStore } from \"./secret-store.ts\";\nimport { GatewaySessionStore } from \"./session-store.ts\";\n\ninterface HumainGatewayProviderDeps {\n\tenvironment?: () => GatewayEnvironment;\n\tsessions?: GatewaySessionStore;\n\tfetch?: typeof fetch;\n}\n\nconst ACCESS_RETRY_MS = 60_000;\nconst ACCESS_READ_WARNING = \"HUMAIN Gateway could not read account restrictions; showing all listed models.\";\nconst ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n/** Used when no access answer exists: `/v1/models` stays authoritative and stored blocks are kept. */\nconst NULL_LABEL_ACCESS: GatewayAccess = {\n\taccessKind: \"unrestricted\",\n\tmodels: [],\n\tmodelModes: {},\n\tharnessLabels: null,\n\tdegraded: null,\n};\n\n/**\n * Global user settings only: a repository's project settings must never redirect Gateway credentials.\n * `ok` is false when the global settings read failed (e.g. a lock held by another process), so the\n * production fallback must not be cached.\n */\nexport function readGatewayEnvironment(\n\tcwd: string,\n\tagentDir: string,\n): { environment: GatewayEnvironment; ok: boolean } {\n\tconst settings = SettingsManager.create(cwd, agentDir);\n\tconst gateway = settings.getGlobalSettings().humainGateway;\n\tconst environment = gateway?.environment === \"staging\" ? \"staging\" : \"production\";\n\treturn {\n\t\tenvironment,\n\t\tok: !settings.drainErrors().some((error) => error.scope === \"global\"),\n\t};\n}\n\nconst baseUrlFor = (environment: GatewayEnvironment) => `${GATEWAY_BASE_URLS[environment]}/v1`;\n\n/** Non-secret session reference from `auth.json`, only when it belongs to the selected environment. */\nfunction sessionOf(\n\tcredential: Credential | undefined,\n\tenvironment: GatewayEnvironment,\n): { id: string; userId: string } | undefined {\n\tconst env = credential?.type === \"api_key\" ? credential.env : undefined;\n\tconst id = env?.[GATEWAY_ENV_SESSION_ID];\n\tif (env?.[GATEWAY_ENV_ENVIRONMENT] !== environment || typeof id !== \"string\" || !id) return undefined;\n\tconst userId = env[GATEWAY_ENV_USER_ID];\n\treturn { id, userId: typeof userId === \"string\" ? userId : \"\" };\n}\n\nfunction toModel(\n\tentry: { id: string; contextWindow: number; maxTokens: number },\n\tenvironment: GatewayEnvironment,\n): Model<Api> {\n\treturn {\n\t\tid: entry.id,\n\t\tname: environment === \"staging\" ? `${entry.id} (staging)` : entry.id,\n\t\tapi: \"openai-responses\",\n\t\tprovider: HUMAIN_GATEWAY_PROVIDER,\n\t\tbaseUrl: baseUrlFor(environment),\n\t\treasoning: false,\n\t\tinput: [\"text\"],\n\t\tcost: ZERO_COST,\n\t\tcontextWindow: entry.contextWindow,\n\t\tmaxTokens: entry.maxTokens,\n\t};\n}\n\n/** Defers platform detection to first use: a missing keychain must fail sign-in, not provider registration. */\nfunction lazySecretStore(): GatewaySecretStore {\n\tlet store: GatewaySecretStore | undefined;\n\tconst resolve = () => {\n\t\tstore ??= createGatewaySecretStore();\n\t\treturn store;\n\t};\n\treturn {\n\t\tget: async (account) => resolve().get(account),\n\t\tset: async (account, secret) => resolve().set(account, secret),\n\t\tdelete: async (account) => resolve().delete(account),\n\t};\n}\n\nlet processEnvironment: GatewayEnvironment | undefined;\n/**\n * Cached per process after a clean read: settings reads take file locks and fall back to production when\n * another process holds them, so a failed read is retried. Changing `humainGateway.environment` therefore needs a restart.\n */\nconst defaultEnvironment = () => {\n\tif (processEnvironment) return processEnvironment;\n\tconst { environment, ok } = readGatewayEnvironment(process.cwd(), getAgentDir());\n\tif (ok) processEnvironment = environment;\n\treturn environment;\n};\n\nexport function resetGatewayEnvironmentCacheForTests(): void {\n\tprocessEnvironment = undefined;\n}\n\n/**\n * Only interactive sessions reconcile at startup: print, JSON and RPC processes are short-lived, and a\n * background revocation would keep them alive.\n */\nexport function shouldReconcileGatewayOnStartup(mode: AppMode, offline: boolean, listModels = false): boolean {\n\treturn mode === \"interactive\" && !offline && !listModels;\n}\n\ntype RefreshListing = { models: GatewayModelEntry[] } | { error: unknown; clearCatalog: boolean };\n\n/** Maps the settled reads of a refresh to the listed models or the error to report. */\nfunction mapRefreshResults(\n\tlisted: PromiseSettledResult<GatewayModelEntry[]>,\n\taccessed: PromiseSettledResult<GatewayAccess>,\n): RefreshListing {\n\tfor (const result of [listed, accessed]) {\n\t\tif (result.status === \"rejected\" && result.reason instanceof GatewaySessionUnavailableError) {\n\t\t\treturn { error: result.reason, clearCatalog: true };\n\t\t}\n\t}\n\tif (listed.status === \"fulfilled\") return { models: listed.value };\n\t// Budget: keep the last good list for this scope; other failures never fabricate a catalog.\n\tconst setupPending =\n\t\t!(listed.reason instanceof GatewayBudgetExhaustedError) &&\n\t\taccessed.status === \"fulfilled\" &&\n\t\taccessed.value.accessKind === \"unknown\";\n\treturn { error: setupPending ? new Error(GATEWAY_SETUP_WARNING) : listed.reason, clearCatalog: false };\n}\n\nasync function saveBlockedModels(\n\tsessions: GatewaySessionStore,\n\tenvironment: GatewayEnvironment,\n\tuserId: string,\n\tprevious: Record<string, string>,\n\tnext: Record<string, string>,\n): Promise<void> {\n\tif (JSON.stringify(next) !== JSON.stringify(previous)) await sessions.setBlockedModels(environment, userId, next);\n}\n\n/**\n * Startup reconciliation: revokes sessions orphaned by `/logout`, which leaves no credential and so\n * never reaches the refresh network phase. Touches the keychain only when pending records exist.\n */\nexport async function revokeGatewayOrphans(\n\tdeps: HumainGatewayProviderDeps & { readCredential?: () => Promise<Credential | undefined> } = {},\n): Promise<void> {\n\tconst env = (deps.environment ?? defaultEnvironment)();\n\tconst sessions = deps.sessions ?? new GatewaySessionStore({ secrets: lazySecretStore() });\n\tconst readCredential = deps.readCredential ?? (() => new ReadOnlyAuthStorage().readRaw(HUMAIN_GATEWAY_PROVIDER));\n\tawait sessions.markOrphansPending(env, sessionOf(await readCredential(), env)?.id);\n\tawait revokePendingSessions(GATEWAY_BASE_URLS[env], env, sessions, deps.fetch);\n}\n\nexport function createHumainGatewayProvider(deps: HumainGatewayProviderDeps = {}): Provider {\n\tconst environment = deps.environment ?? defaultEnvironment;\n\tconst sessions = deps.sessions ?? new GatewaySessionStore({ secrets: lazySecretStore() });\n\tlet models: readonly Model<Api>[] = [];\n\tlet activeScope: string | undefined;\n\t// Last successful access read, for one scope only.\n\tlet lastAccess: { scope: string; access: GatewayAccess; at: number } | undefined;\n\tconst lastAccessFor = (scope: string) => (lastAccess?.scope === scope ? lastAccess.access : undefined);\n\t// Last blocked set shown for one scope, so an unchanged set is not repeated.\n\tlet shownBlocked: { scope: string; key: string } | undefined;\n\n\t/** Refetched every refresh, except within 60 s of an unknown or degraded answer. */\n\tconst loadAccess = async (\n\t\tscope: string,\n\t\tbaseUrl: string,\n\t\ttoken: string,\n\t\toptions: { fetch?: typeof fetch; signal: AbortSignal },\n\t): Promise<GatewayAccess> => {\n\t\tconst now = Date.now();\n\t\tconst last = lastAccess?.scope === scope ? lastAccess : undefined;\n\t\tif (\n\t\t\tlast &&\n\t\t\t(last.access.accessKind === \"unknown\" || last.access.degraded !== null) &&\n\t\t\tnow - last.at < ACCESS_RETRY_MS\n\t\t) {\n\t\t\treturn last.access;\n\t\t}\n\t\tconst access = await fetchGatewayAccess(baseUrl, token, options);\n\t\tif (!options.signal.aborted) lastAccess = { scope, access, at: now };\n\t\treturn access;\n\t};\n\n\tconst apiKeyAuth: ApiKeyAuth = {\n\t\tname: \"HUMAIN Gateway\",\n\t\tlogin: (interaction) => loginToGateway(interaction, { environment: environment(), sessions, fetch: deps.fetch }),\n\t\t// Metadata only: listing must not touch the keychain or the network.\n\t\tcheck: async ({ credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst env = environment();\n\t\t\treturn sessionOf(credential, env)\n\t\t\t\t? { type: \"api_key\" as const, source: `HUMAIN Gateway (${env})` }\n\t\t\t\t: undefined;\n\t\t},\n\t\tresolve: async ({ credential, signal }): Promise<AuthResult | undefined> => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst env = environment();\n\t\t\tconst session = sessionOf(credential, env);\n\t\t\tconst token = session ? await sessions.getToken(session.id) : undefined;\n\t\t\tif (!token) return undefined;\n\t\t\t// `env` carries only the non-secret session reference so catalog refreshes keep their scope.\n\t\t\treturn {\n\t\t\t\tauth: { apiKey: token, baseUrl: baseUrlFor(env) },\n\t\t\t\tenv: { ...credential?.env },\n\t\t\t\tsource: `HUMAIN Gateway (${env})`,\n\t\t\t};\n\t\t},\n\t};\n\n\tconst base = createProvider({\n\t\tid: HUMAIN_GATEWAY_PROVIDER,\n\t\tname: \"HUMAIN Gateway\",\n\t\tbaseUrl: baseUrlFor(\"production\"),\n\t\tauth: { apiKey: apiKeyAuth },\n\t\tmodels: [],\n\t\tapi: { \"openai-responses\": withHumainGatewayHttp(openAIResponsesApi()) },\n\t});\n\n\treturn {\n\t\t...base,\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext) => {\n\t\t\tconst env = environment();\n\t\t\tconst session = sessionOf(context.credential, env);\n\t\t\tconst scope = session ? `${env}\\0${session.id}` : undefined;\n\t\t\tconst publish = (next: readonly Model<Api>[]) =>\n\t\t\t\tcontext.publish({\n\t\t\t\t\tpersist: null,\n\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\tmodels = next;\n\t\t\t\t\t\tactiveScope = scope;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\tif (scope !== activeScope && !(await publish([]))) return;\n\t\t\t// No session can mean an unreadable auth.json, a runtime key override, or another agentDir;\n\t\t\t// logout cleanup is left to revokeGatewayOrphans, which stops when the credential read fails.\n\t\t\tif (session) await sessions.markOrphansPending(env, session.id);\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\tconst baseUrl = GATEWAY_BASE_URLS[env];\n\t\t\tawait revokePendingSessions(baseUrl, env, sessions, deps.fetch);\n\t\t\t// The network phase receives the token resolved in-process as `key`.\n\t\t\tconst token = context.credential?.type === \"api_key\" ? context.credential.key : undefined;\n\t\t\tif (!session || !scope || !token) return;\n\n\t\t\tconst options = { fetch: deps.fetch, signal: context.signal };\n\t\t\tconst [listed, accessed] = await Promise.allSettled([\n\t\t\t\tfetchGatewayModels(baseUrl, token, options),\n\t\t\t\tloadAccess(scope, baseUrl, token, options),\n\t\t\t]);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst listing = mapRefreshResults(listed, accessed);\n\t\t\tif (\"error\" in listing) {\n\t\t\t\tif (listing.clearCatalog) await publish([]);\n\t\t\t\tthrow listing.error;\n\t\t\t}\n\n\t\t\t// A failed access read reuses this scope's last answer; without one, `/v1/models` alone decides.\n\t\t\tconst access = accessed.status === \"fulfilled\" ? accessed.value : lastAccessFor(scope);\n\t\t\tconst previouslyBlocked = await sessions.getBlockedModels(env, session.userId);\n\t\t\tconst catalog = deriveGatewayCatalog({\n\t\t\t\tmodels: listing.models,\n\t\t\t\taccess: access ?? NULL_LABEL_ACCESS,\n\t\t\t\tpreviouslyBlocked,\n\t\t\t});\n\t\t\tawait saveBlockedModels(sessions, env, session.userId, previouslyBlocked, catalog.blocked);\n\t\t\tif (!(await publish(catalog.eligible.map((entry) => toModel(entry, env))))) return;\n\t\t\tconst warnings = access ? catalog.warnings : [...catalog.warnings, ACCESS_READ_WARNING];\n\t\t\tconst listedIds = new Set(listing.models.map((entry) => entry.id));\n\t\t\tconst blocked = Object.entries(catalog.blocked)\n\t\t\t\t.filter(([id]) => listedIds.has(id))\n\t\t\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\t\t\tconst blockedKey = JSON.stringify(blocked);\n\t\t\tif (blocked.length > 0 && (shownBlocked?.scope !== scope || shownBlocked.key !== blockedKey)) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Blocked for HUMAIN Code by HUMAIN Gateway: ${blocked.map(([id, reason]) => (reason === DEFAULT_BLOCK_REASON ? id : `${id} (${reason})`)).join(\"; \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tshownBlocked = { scope, key: blockedKey };\n\t\t\tif (warnings.length > 0) throw new Error(warnings.join(\" \"));\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { SafeCredentialError } from "../../core/safe-credential-error.ts";
|
|
2
|
+
import { type CommandRunner } from "../../core/trace-client/credential-store.ts";
|
|
3
|
+
export interface GatewaySecretStore {
|
|
4
|
+
get(account: string): Promise<string | undefined>;
|
|
5
|
+
set(account: string, secret: string): Promise<void>;
|
|
6
|
+
delete(account: string): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export declare class GatewaySecretStoreError extends SafeCredentialError {
|
|
9
|
+
constructor(message: string);
|
|
10
|
+
}
|
|
11
|
+
interface CreateGatewaySecretStoreOptions {
|
|
12
|
+
platform?: NodeJS.Platform;
|
|
13
|
+
run?: CommandRunner;
|
|
14
|
+
env?: NodeJS.ProcessEnv;
|
|
15
|
+
findExecutable?: (name: string) => string | undefined;
|
|
16
|
+
}
|
|
17
|
+
export declare function createGatewaySecretStore(options?: CreateGatewaySecretStoreOptions): GatewaySecretStore;
|
|
18
|
+
export {};
|
|
19
|
+
//# sourceMappingURL=secret-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"secret-store.d.ts","sourceRoot":"","sources":["../../../src/humain/gateway/secret-store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EACN,KAAK,aAAa,EAGlB,MAAM,6CAA6C,CAAC;AAErD,MAAM,WAAW,kBAAkB;IAClC,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAClD,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACpD,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvC;AAED,qBAAa,uBAAwB,SAAQ,mBAAmB;IAC/D,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAED,UAAU,+BAA+B;IACxC,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;IAC3B,GAAG,CAAC,EAAE,aAAa,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,cAAc,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;CACtD;AA+OD,wBAAgB,wBAAwB,CAAC,OAAO,GAAE,+BAAoC,GAAG,kBAAkB,CAgC1G"}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { win32 } from "node:path";
|
|
2
|
+
import { SafeCredentialError } from "../../core/safe-credential-error.js";
|
|
3
|
+
import { spawnCommand, systemTraceCredentialProbes, } from "../../core/trace-client/credential-store.js";
|
|
4
|
+
export class GatewaySecretStoreError extends SafeCredentialError {
|
|
5
|
+
constructor(message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "GatewaySecretStoreError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const SERVICE_NAME = "humain-code-gateway";
|
|
11
|
+
const ACCOUNT_PATTERN = /^[A-Za-z0-9:._-]{1,128}$/;
|
|
12
|
+
/** Secrets embedded in a double-quoted `security -i` line must not need escaping. */
|
|
13
|
+
const MACOS_SAFE_SECRET = /^[\x21\x23-\x5b\x5d-\x7e]{1,3000}$/;
|
|
14
|
+
const KEYCHAIN_ITEM_NOT_FOUND = 44;
|
|
15
|
+
const WINDOWS_NOT_FOUND = 3;
|
|
16
|
+
function assertAccount(account) {
|
|
17
|
+
if (!ACCOUNT_PATTERN.test(account)) {
|
|
18
|
+
throw new GatewaySecretStoreError("Invalid credential account name");
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
async function run(runner, command, args, stdin) {
|
|
22
|
+
try {
|
|
23
|
+
return await runner(command, args, stdin);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw new GatewaySecretStoreError("Could not run the credential store command");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
class KeychainSecretStore {
|
|
30
|
+
runner;
|
|
31
|
+
securityPath;
|
|
32
|
+
constructor(runner, securityPath) {
|
|
33
|
+
this.runner = runner;
|
|
34
|
+
this.securityPath = securityPath;
|
|
35
|
+
}
|
|
36
|
+
async get(account) {
|
|
37
|
+
assertAccount(account);
|
|
38
|
+
const result = await run(this.runner, this.securityPath, [
|
|
39
|
+
"find-generic-password",
|
|
40
|
+
"-s",
|
|
41
|
+
SERVICE_NAME,
|
|
42
|
+
"-a",
|
|
43
|
+
account,
|
|
44
|
+
"-w",
|
|
45
|
+
]);
|
|
46
|
+
if (result.code === KEYCHAIN_ITEM_NOT_FOUND)
|
|
47
|
+
return undefined;
|
|
48
|
+
if (result.code !== 0)
|
|
49
|
+
throw new GatewaySecretStoreError(`Keychain lookup failed (exit ${result.code})`);
|
|
50
|
+
return result.stdout.replace(/\r?\n$/, "");
|
|
51
|
+
}
|
|
52
|
+
async set(account, secret) {
|
|
53
|
+
assertAccount(account);
|
|
54
|
+
if (!MACOS_SAFE_SECRET.test(secret))
|
|
55
|
+
throw new GatewaySecretStoreError("Secret cannot be stored in the keychain");
|
|
56
|
+
// The secret travels only on stdin.
|
|
57
|
+
const command = `add-generic-password -U -s "${SERVICE_NAME}" -a "${account}" -w "${secret}"\n`;
|
|
58
|
+
const result = await run(this.runner, this.securityPath, ["-i"], command);
|
|
59
|
+
if (result.code !== 0 || result.stderr.trim().length > 0) {
|
|
60
|
+
throw new GatewaySecretStoreError(`Keychain write failed (exit ${result.code})`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async delete(account) {
|
|
64
|
+
assertAccount(account);
|
|
65
|
+
const result = await run(this.runner, this.securityPath, [
|
|
66
|
+
"delete-generic-password",
|
|
67
|
+
"-s",
|
|
68
|
+
SERVICE_NAME,
|
|
69
|
+
"-a",
|
|
70
|
+
account,
|
|
71
|
+
]);
|
|
72
|
+
if (result.code !== 0 && result.code !== KEYCHAIN_ITEM_NOT_FOUND) {
|
|
73
|
+
throw new GatewaySecretStoreError(`Keychain delete failed (exit ${result.code})`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
class SecretServiceStore {
|
|
78
|
+
runner;
|
|
79
|
+
secretToolPath;
|
|
80
|
+
constructor(runner, secretToolPath) {
|
|
81
|
+
this.runner = runner;
|
|
82
|
+
this.secretToolPath = secretToolPath;
|
|
83
|
+
}
|
|
84
|
+
async get(account) {
|
|
85
|
+
assertAccount(account);
|
|
86
|
+
const result = await run(this.runner, this.secretToolPath, [
|
|
87
|
+
"lookup",
|
|
88
|
+
"service",
|
|
89
|
+
SERVICE_NAME,
|
|
90
|
+
"account",
|
|
91
|
+
account,
|
|
92
|
+
]);
|
|
93
|
+
if (result.code === 0)
|
|
94
|
+
return result.stdout.length === 0 ? undefined : result.stdout;
|
|
95
|
+
// Unlike the trace credential store, Gateway fails closed here instead of treating every exit 1 as missing.
|
|
96
|
+
// Exit 1 with stderr means a D-Bus/Secret Service failure, not a missing item.
|
|
97
|
+
if (result.code === 1 && result.stderr.trim().length === 0)
|
|
98
|
+
return undefined;
|
|
99
|
+
throw new GatewaySecretStoreError(`Secret Service lookup failed (exit ${result.code})`);
|
|
100
|
+
}
|
|
101
|
+
async set(account, secret) {
|
|
102
|
+
assertAccount(account);
|
|
103
|
+
const result = await run(this.runner, this.secretToolPath, ["store", "--label=HUMAIN Code Gateway", "service", SERVICE_NAME, "account", account], secret);
|
|
104
|
+
if (result.code !== 0)
|
|
105
|
+
throw new GatewaySecretStoreError(`Secret Service write failed (exit ${result.code})`);
|
|
106
|
+
}
|
|
107
|
+
async delete(account) {
|
|
108
|
+
assertAccount(account);
|
|
109
|
+
const result = await run(this.runner, this.secretToolPath, [
|
|
110
|
+
"clear",
|
|
111
|
+
"service",
|
|
112
|
+
SERVICE_NAME,
|
|
113
|
+
"account",
|
|
114
|
+
account,
|
|
115
|
+
]);
|
|
116
|
+
if (result.code !== 0 && !(result.code === 1 && result.stderr.trim().length === 0)) {
|
|
117
|
+
throw new GatewaySecretStoreError(`Secret Service delete failed (exit ${result.code})`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Constant PowerShell script. Operation and account arrive as trailing arguments (validated before spawning;
|
|
123
|
+
* `-Command` appends them to the script block call), the secret only on stdin. Exit 3 = not found.
|
|
124
|
+
*/
|
|
125
|
+
const WINDOWS_CREDENTIAL_SCRIPT = `& {
|
|
126
|
+
param([string]$Op, [string]$Account)
|
|
127
|
+
$ErrorActionPreference = 'Stop'
|
|
128
|
+
Add-Type -TypeDefinition '
|
|
129
|
+
using System;
|
|
130
|
+
using System.Runtime.InteropServices;
|
|
131
|
+
public static class HumainCred {
|
|
132
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
133
|
+
public struct CREDENTIAL {
|
|
134
|
+
public UInt32 Flags; public UInt32 Type; public string TargetName; public string Comment;
|
|
135
|
+
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
|
|
136
|
+
public UInt32 CredentialBlobSize; public IntPtr CredentialBlob; public UInt32 Persist;
|
|
137
|
+
public UInt32 AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName;
|
|
138
|
+
}
|
|
139
|
+
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
140
|
+
public static extern bool CredWriteW(ref CREDENTIAL cred, UInt32 flags);
|
|
141
|
+
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
142
|
+
public static extern bool CredReadW(string target, UInt32 type, UInt32 flags, out IntPtr cred);
|
|
143
|
+
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
144
|
+
public static extern bool CredDeleteW(string target, UInt32 type, UInt32 flags);
|
|
145
|
+
[DllImport("advapi32.dll")]
|
|
146
|
+
public static extern void CredFree(IntPtr buffer);
|
|
147
|
+
public static int Write(ref CREDENTIAL cred) {
|
|
148
|
+
return CredWriteW(ref cred, 0) ? 0 : Marshal.GetLastWin32Error();
|
|
149
|
+
}
|
|
150
|
+
public static int Read(string target, out IntPtr cred) {
|
|
151
|
+
return CredReadW(target, 1, 0, out cred) ? 0 : Marshal.GetLastWin32Error();
|
|
152
|
+
}
|
|
153
|
+
public static int Delete(string target) {
|
|
154
|
+
return CredDeleteW(target, 1, 0) ? 0 : Marshal.GetLastWin32Error();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
'
|
|
158
|
+
$target = 'humain-code-gateway:' + $Account
|
|
159
|
+
$notFound = 1168
|
|
160
|
+
if ($Op -eq 'set') {
|
|
161
|
+
$secret = [Console]::In.ReadToEnd()
|
|
162
|
+
$bytes = [System.Text.Encoding]::Unicode.GetBytes($secret)
|
|
163
|
+
$blob = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length)
|
|
164
|
+
try {
|
|
165
|
+
[System.Runtime.InteropServices.Marshal]::Copy($bytes, 0, $blob, $bytes.Length)
|
|
166
|
+
$cred = New-Object HumainCred+CREDENTIAL
|
|
167
|
+
$cred.Type = 1
|
|
168
|
+
$cred.TargetName = $target
|
|
169
|
+
$cred.CredentialBlobSize = $bytes.Length
|
|
170
|
+
$cred.CredentialBlob = $blob
|
|
171
|
+
$cred.Persist = 2
|
|
172
|
+
$cred.UserName = 'humain-code'
|
|
173
|
+
if ([HumainCred]::Write([ref]$cred) -ne 0) { exit 4 }
|
|
174
|
+
} finally { [System.Runtime.InteropServices.Marshal]::FreeHGlobal($blob) }
|
|
175
|
+
} elseif ($Op -eq 'get') {
|
|
176
|
+
$ptr = [IntPtr]::Zero
|
|
177
|
+
$err = [HumainCred]::Read($target, [ref]$ptr)
|
|
178
|
+
if ($err -ne 0) {
|
|
179
|
+
if ($err -eq $notFound) { exit 3 }
|
|
180
|
+
exit 4
|
|
181
|
+
}
|
|
182
|
+
try {
|
|
183
|
+
$cred = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [Type][HumainCred+CREDENTIAL])
|
|
184
|
+
$text = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($cred.CredentialBlob, [int]($cred.CredentialBlobSize / 2))
|
|
185
|
+
[Console]::Out.Write($text)
|
|
186
|
+
} finally { [HumainCred]::CredFree($ptr) }
|
|
187
|
+
} elseif ($Op -eq 'delete') {
|
|
188
|
+
$err = [HumainCred]::Delete($target)
|
|
189
|
+
if ($err -ne 0) {
|
|
190
|
+
if ($err -eq $notFound) { exit 3 }
|
|
191
|
+
exit 4
|
|
192
|
+
}
|
|
193
|
+
} else { exit 5 }
|
|
194
|
+
}`;
|
|
195
|
+
class WindowsCredentialStore {
|
|
196
|
+
runner;
|
|
197
|
+
powershellPath;
|
|
198
|
+
constructor(runner, powershellPath) {
|
|
199
|
+
this.runner = runner;
|
|
200
|
+
this.powershellPath = powershellPath;
|
|
201
|
+
}
|
|
202
|
+
exec(operation, account, stdin) {
|
|
203
|
+
assertAccount(account);
|
|
204
|
+
return run(this.runner, this.powershellPath, ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_CREDENTIAL_SCRIPT, operation, account], stdin);
|
|
205
|
+
}
|
|
206
|
+
async get(account) {
|
|
207
|
+
const result = await this.exec("get", account);
|
|
208
|
+
if (result.code === WINDOWS_NOT_FOUND)
|
|
209
|
+
return undefined;
|
|
210
|
+
if (result.code !== 0)
|
|
211
|
+
throw new GatewaySecretStoreError(`Credential Manager lookup failed (exit ${result.code})`);
|
|
212
|
+
return result.stdout;
|
|
213
|
+
}
|
|
214
|
+
async set(account, secret) {
|
|
215
|
+
const result = await this.exec("set", account, secret);
|
|
216
|
+
if (result.code !== 0)
|
|
217
|
+
throw new GatewaySecretStoreError(`Credential Manager write failed (exit ${result.code})`);
|
|
218
|
+
}
|
|
219
|
+
async delete(account) {
|
|
220
|
+
const result = await this.exec("delete", account);
|
|
221
|
+
if (result.code !== 0 && result.code !== WINDOWS_NOT_FOUND) {
|
|
222
|
+
throw new GatewaySecretStoreError(`Credential Manager delete failed (exit ${result.code})`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
export function createGatewaySecretStore(options = {}) {
|
|
227
|
+
const platform = options.platform ?? process.platform;
|
|
228
|
+
const runner = options.run ?? spawnCommand;
|
|
229
|
+
const env = options.env ?? process.env;
|
|
230
|
+
const findExecutable = options.findExecutable ?? systemTraceCredentialProbes.findExecutable;
|
|
231
|
+
if (platform === "darwin") {
|
|
232
|
+
const security = findExecutable("/usr/bin/security");
|
|
233
|
+
if (security)
|
|
234
|
+
return new KeychainSecretStore(runner, security);
|
|
235
|
+
throw new GatewaySecretStoreError("macOS Keychain is unavailable: /usr/bin/security was not found.");
|
|
236
|
+
}
|
|
237
|
+
if (platform === "linux") {
|
|
238
|
+
const secretTool = findExecutable("secret-tool");
|
|
239
|
+
if (secretTool && env.DBUS_SESSION_BUS_ADDRESS)
|
|
240
|
+
return new SecretServiceStore(runner, secretTool);
|
|
241
|
+
throw new GatewaySecretStoreError("HUMAIN Gateway needs the Linux Secret Service: install libsecret's secret-tool and run in a desktop session with DBUS_SESSION_BUS_ADDRESS set.");
|
|
242
|
+
}
|
|
243
|
+
if (platform === "win32") {
|
|
244
|
+
const systemRoot = env.SystemRoot;
|
|
245
|
+
if (!systemRoot || !/^[a-z]:[\\/]/i.test(systemRoot)) {
|
|
246
|
+
throw new GatewaySecretStoreError("Windows Credential Manager is unavailable: SystemRoot is not set to a drive path.");
|
|
247
|
+
}
|
|
248
|
+
return new WindowsCredentialStore(runner, win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"));
|
|
249
|
+
}
|
|
250
|
+
throw new GatewaySecretStoreError(`HUMAIN Gateway sign-in is not supported on ${platform}: it requires macOS Keychain, Linux Secret Service, or Windows Credential Manager.`);
|
|
251
|
+
}
|
|
252
|
+
//# sourceMappingURL=secret-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"secret-store.js","sourceRo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AI,uBAAuB,CAChC,8CAA8C,QAAQ,oFAAoF,CAC1I,CAAC;AACH,CAAC","sourcesContent":["import { win32 } from \"node:path\";\nimport { SafeCredentialError } from \"../../core/safe-credential-error.ts\";\nimport {\n\ttype CommandRunner,\n\tspawnCommand,\n\tsystemTraceCredentialProbes,\n} from \"../../core/trace-client/credential-store.ts\";\n\nexport interface GatewaySecretStore {\n\tget(account: string): Promise<string | undefined>;\n\tset(account: string, secret: string): Promise<void>;\n\tdelete(account: string): Promise<void>;\n}\n\nexport class GatewaySecretStoreError extends SafeCredentialError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"GatewaySecretStoreError\";\n\t}\n}\n\ninterface CreateGatewaySecretStoreOptions {\n\tplatform?: NodeJS.Platform;\n\trun?: CommandRunner;\n\tenv?: NodeJS.ProcessEnv;\n\tfindExecutable?: (name: string) => string | undefined;\n}\n\nconst SERVICE_NAME = \"humain-code-gateway\";\nconst ACCOUNT_PATTERN = /^[A-Za-z0-9:._-]{1,128}$/;\n/** Secrets embedded in a double-quoted `security -i` line must not need escaping. */\nconst MACOS_SAFE_SECRET = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]{1,3000}$/;\nconst KEYCHAIN_ITEM_NOT_FOUND = 44;\nconst WINDOWS_NOT_FOUND = 3;\n\nfunction assertAccount(account: string): void {\n\tif (!ACCOUNT_PATTERN.test(account)) {\n\t\tthrow new GatewaySecretStoreError(\"Invalid credential account name\");\n\t}\n}\n\nasync function run(runner: CommandRunner, command: string, args: readonly string[], stdin?: string) {\n\ttry {\n\t\treturn await runner(command, args, stdin);\n\t} catch {\n\t\tthrow new GatewaySecretStoreError(\"Could not run the credential store command\");\n\t}\n}\n\nclass KeychainSecretStore implements GatewaySecretStore {\n\tprivate readonly runner: CommandRunner;\n\tprivate readonly securityPath: string;\n\n\tconstructor(runner: CommandRunner, securityPath: string) {\n\t\tthis.runner = runner;\n\t\tthis.securityPath = securityPath;\n\t}\n\n\tasync get(account: string): Promise<string | undefined> {\n\t\tassertAccount(account);\n\t\tconst result = await run(this.runner, this.securityPath, [\n\t\t\t\"find-generic-password\",\n\t\t\t\"-s\",\n\t\t\tSERVICE_NAME,\n\t\t\t\"-a\",\n\t\t\taccount,\n\t\t\t\"-w\",\n\t\t]);\n\t\tif (result.code === KEYCHAIN_ITEM_NOT_FOUND) return undefined;\n\t\tif (result.code !== 0) throw new GatewaySecretStoreError(`Keychain lookup failed (exit ${result.code})`);\n\t\treturn result.stdout.replace(/\\r?\\n$/, \"\");\n\t}\n\n\tasync set(account: string, secret: string): Promise<void> {\n\t\tassertAccount(account);\n\t\tif (!MACOS_SAFE_SECRET.test(secret)) throw new GatewaySecretStoreError(\"Secret cannot be stored in the keychain\");\n\t\t// The secret travels only on stdin.\n\t\tconst command = `add-generic-password -U -s \"${SERVICE_NAME}\" -a \"${account}\" -w \"${secret}\"\\n`;\n\t\tconst result = await run(this.runner, this.securityPath, [\"-i\"], command);\n\t\tif (result.code !== 0 || result.stderr.trim().length > 0) {\n\t\t\tthrow new GatewaySecretStoreError(`Keychain write failed (exit ${result.code})`);\n\t\t}\n\t}\n\n\tasync delete(account: string): Promise<void> {\n\t\tassertAccount(account);\n\t\tconst result = await run(this.runner, this.securityPath, [\n\t\t\t\"delete-generic-password\",\n\t\t\t\"-s\",\n\t\t\tSERVICE_NAME,\n\t\t\t\"-a\",\n\t\t\taccount,\n\t\t]);\n\t\tif (result.code !== 0 && result.code !== KEYCHAIN_ITEM_NOT_FOUND) {\n\t\t\tthrow new GatewaySecretStoreError(`Keychain delete failed (exit ${result.code})`);\n\t\t}\n\t}\n}\n\nclass SecretServiceStore implements GatewaySecretStore {\n\tprivate readonly runner: CommandRunner;\n\tprivate readonly secretToolPath: string;\n\n\tconstructor(runner: CommandRunner, secretToolPath: string) {\n\t\tthis.runner = runner;\n\t\tthis.secretToolPath = secretToolPath;\n\t}\n\n\tasync get(account: string): Promise<string | undefined> {\n\t\tassertAccount(account);\n\t\tconst result = await run(this.runner, this.secretToolPath, [\n\t\t\t\"lookup\",\n\t\t\t\"service\",\n\t\t\tSERVICE_NAME,\n\t\t\t\"account\",\n\t\t\taccount,\n\t\t]);\n\t\tif (result.code === 0) return result.stdout.length === 0 ? undefined : result.stdout;\n\t\t// Unlike the trace credential store, Gateway fails closed here instead of treating every exit 1 as missing.\n\t\t// Exit 1 with stderr means a D-Bus/Secret Service failure, not a missing item.\n\t\tif (result.code === 1 && result.stderr.trim().length === 0) return undefined;\n\t\tthrow new GatewaySecretStoreError(`Secret Service lookup failed (exit ${result.code})`);\n\t}\n\n\tasync set(account: string, secret: string): Promise<void> {\n\t\tassertAccount(account);\n\t\tconst result = await run(\n\t\t\tthis.runner,\n\t\t\tthis.secretToolPath,\n\t\t\t[\"store\", \"--label=HUMAIN Code Gateway\", \"service\", SERVICE_NAME, \"account\", account],\n\t\t\tsecret,\n\t\t);\n\t\tif (result.code !== 0) throw new GatewaySecretStoreError(`Secret Service write failed (exit ${result.code})`);\n\t}\n\n\tasync delete(account: string): Promise<void> {\n\t\tassertAccount(account);\n\t\tconst result = await run(this.runner, this.secretToolPath, [\n\t\t\t\"clear\",\n\t\t\t\"service\",\n\t\t\tSERVICE_NAME,\n\t\t\t\"account\",\n\t\t\taccount,\n\t\t]);\n\t\tif (result.code !== 0 && !(result.code === 1 && result.stderr.trim().length === 0)) {\n\t\t\tthrow new GatewaySecretStoreError(`Secret Service delete failed (exit ${result.code})`);\n\t\t}\n\t}\n}\n\n/**\n * Constant PowerShell script. Operation and account arrive as trailing arguments (validated before spawning;\n * `-Command` appends them to the script block call), the secret only on stdin. Exit 3 = not found.\n */\nconst WINDOWS_CREDENTIAL_SCRIPT = `& {\nparam([string]$Op, [string]$Account)\n$ErrorActionPreference = 'Stop'\nAdd-Type -TypeDefinition '\nusing System;\nusing System.Runtime.InteropServices;\npublic static class HumainCred {\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n public struct CREDENTIAL {\n public UInt32 Flags; public UInt32 Type; public string TargetName; public string Comment;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;\n public UInt32 CredentialBlobSize; public IntPtr CredentialBlob; public UInt32 Persist;\n public UInt32 AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName;\n }\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n public static extern bool CredWriteW(ref CREDENTIAL cred, UInt32 flags);\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n public static extern bool CredReadW(string target, UInt32 type, UInt32 flags, out IntPtr cred);\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n public static extern bool CredDeleteW(string target, UInt32 type, UInt32 flags);\n [DllImport(\"advapi32.dll\")]\n public static extern void CredFree(IntPtr buffer);\n public static int Write(ref CREDENTIAL cred) {\n return CredWriteW(ref cred, 0) ? 0 : Marshal.GetLastWin32Error();\n }\n public static int Read(string target, out IntPtr cred) {\n return CredReadW(target, 1, 0, out cred) ? 0 : Marshal.GetLastWin32Error();\n }\n public static int Delete(string target) {\n return CredDeleteW(target, 1, 0) ? 0 : Marshal.GetLastWin32Error();\n }\n}\n'\n$target = 'humain-code-gateway:' + $Account\n$notFound = 1168\nif ($Op -eq 'set') {\n $secret = [Console]::In.ReadToEnd()\n $bytes = [System.Text.Encoding]::Unicode.GetBytes($secret)\n $blob = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length)\n try {\n [System.Runtime.InteropServices.Marshal]::Copy($bytes, 0, $blob, $bytes.Length)\n $cred = New-Object HumainCred+CREDENTIAL\n $cred.Type = 1\n $cred.TargetName = $target\n $cred.CredentialBlobSize = $bytes.Length\n $cred.CredentialBlob = $blob\n $cred.Persist = 2\n $cred.UserName = 'humain-code'\n if ([HumainCred]::Write([ref]$cred) -ne 0) { exit 4 }\n } finally { [System.Runtime.InteropServices.Marshal]::FreeHGlobal($blob) }\n} elseif ($Op -eq 'get') {\n $ptr = [IntPtr]::Zero\n $err = [HumainCred]::Read($target, [ref]$ptr)\n if ($err -ne 0) {\n if ($err -eq $notFound) { exit 3 }\n exit 4\n }\n try {\n $cred = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ptr, [Type][HumainCred+CREDENTIAL])\n $text = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($cred.CredentialBlob, [int]($cred.CredentialBlobSize / 2))\n [Console]::Out.Write($text)\n } finally { [HumainCred]::CredFree($ptr) }\n} elseif ($Op -eq 'delete') {\n $err = [HumainCred]::Delete($target)\n if ($err -ne 0) {\n if ($err -eq $notFound) { exit 3 }\n exit 4\n }\n} else { exit 5 }\n}`;\n\nclass WindowsCredentialStore implements GatewaySecretStore {\n\tprivate readonly runner: CommandRunner;\n\tprivate readonly powershellPath: string;\n\n\tconstructor(runner: CommandRunner, powershellPath: string) {\n\t\tthis.runner = runner;\n\t\tthis.powershellPath = powershellPath;\n\t}\n\n\tprivate exec(operation: \"set\" | \"get\" | \"delete\", account: string, stdin?: string) {\n\t\tassertAccount(account);\n\t\treturn run(\n\t\t\tthis.runner,\n\t\t\tthis.powershellPath,\n\t\t\t[\"-NoProfile\", \"-NonInteractive\", \"-Command\", WINDOWS_CREDENTIAL_SCRIPT, operation, account],\n\t\t\tstdin,\n\t\t);\n\t}\n\n\tasync get(account: string): Promise<string | undefined> {\n\t\tconst result = await this.exec(\"get\", account);\n\t\tif (result.code === WINDOWS_NOT_FOUND) return undefined;\n\t\tif (result.code !== 0)\n\t\t\tthrow new GatewaySecretStoreError(`Credential Manager lookup failed (exit ${result.code})`);\n\t\treturn result.stdout;\n\t}\n\n\tasync set(account: string, secret: string): Promise<void> {\n\t\tconst result = await this.exec(\"set\", account, secret);\n\t\tif (result.code !== 0) throw new GatewaySecretStoreError(`Credential Manager write failed (exit ${result.code})`);\n\t}\n\n\tasync delete(account: string): Promise<void> {\n\t\tconst result = await this.exec(\"delete\", account);\n\t\tif (result.code !== 0 && result.code !== WINDOWS_NOT_FOUND) {\n\t\t\tthrow new GatewaySecretStoreError(`Credential Manager delete failed (exit ${result.code})`);\n\t\t}\n\t}\n}\n\nexport function createGatewaySecretStore(options: CreateGatewaySecretStoreOptions = {}): GatewaySecretStore {\n\tconst platform = options.platform ?? process.platform;\n\tconst runner = options.run ?? spawnCommand;\n\tconst env = options.env ?? process.env;\n\tconst findExecutable = options.findExecutable ?? systemTraceCredentialProbes.findExecutable;\n\tif (platform === \"darwin\") {\n\t\tconst security = findExecutable(\"/usr/bin/security\");\n\t\tif (security) return new KeychainSecretStore(runner, security);\n\t\tthrow new GatewaySecretStoreError(\"macOS Keychain is unavailable: /usr/bin/security was not found.\");\n\t}\n\tif (platform === \"linux\") {\n\t\tconst secretTool = findExecutable(\"secret-tool\");\n\t\tif (secretTool && env.DBUS_SESSION_BUS_ADDRESS) return new SecretServiceStore(runner, secretTool);\n\t\tthrow new GatewaySecretStoreError(\n\t\t\t\"HUMAIN Gateway needs the Linux Secret Service: install libsecret's secret-tool and run in a desktop session with DBUS_SESSION_BUS_ADDRESS set.\",\n\t\t);\n\t}\n\tif (platform === \"win32\") {\n\t\tconst systemRoot = env.SystemRoot;\n\t\tif (!systemRoot || !/^[a-z]:[\\\\/]/i.test(systemRoot)) {\n\t\t\tthrow new GatewaySecretStoreError(\n\t\t\t\t\"Windows Credential Manager is unavailable: SystemRoot is not set to a drive path.\",\n\t\t\t);\n\t\t}\n\t\treturn new WindowsCredentialStore(\n\t\t\trunner,\n\t\t\twin32.join(systemRoot, \"System32\", \"WindowsPowerShell\", \"v1.0\", \"powershell.exe\"),\n\t\t);\n\t}\n\tthrow new GatewaySecretStoreError(\n\t\t`HUMAIN Gateway sign-in is not supported on ${platform}: it requires macOS Keychain, Linux Secret Service, or Windows Credential Manager.`,\n\t);\n}\n"]}
|