@steerable/agent-shell 0.12.7 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/credentials.d.ts +83 -0
- package/dist/auth/credentials.js +426 -0
- package/dist/auth/index.d.ts +33 -9
- package/dist/auth/index.js +85 -0
- package/dist/host/external-pack-loader.d.ts +40 -0
- package/dist/host/external-pack-loader.js +247 -0
- package/dist/host/http-routes.d.ts +6 -2
- package/dist/host/http-routes.js +5 -2
- package/dist/host/pack-assembly.d.ts +9 -1
- package/dist/host/runtime.js +54 -1
- package/dist/local-backend/coreloop-stream.d.ts +4 -0
- package/dist/local-backend/coreloop-stream.js +4 -0
- package/dist/local-backend/fact-chain.d.ts +38 -0
- package/dist/local-backend/fact-chain.js +145 -0
- package/dist/local-backend/router.d.ts +3 -1
- package/dist/local-backend/router.js +329 -35
- package/dist/local-backend/state-reconcile.d.ts +42 -0
- package/dist/local-backend/state-reconcile.js +81 -0
- package/dist/local-backend/title-refresh.d.ts +39 -0
- package/dist/local-backend/title-refresh.js +80 -0
- package/dist/local-backend/turn-security-context.d.ts +42 -0
- package/dist/local-backend/turn-security-context.js +62 -0
- package/dist/local-backend/ui-surface.d.ts +75 -0
- package/dist/local-backend/ui-surface.js +368 -0
- package/dist/local-executor.d.ts +3 -0
- package/dist/local-executor.js +40 -1
- package/dist/memory/authoring-candidates.d.ts +26 -0
- package/dist/memory/authoring-candidates.js +73 -0
- package/dist/memory/injector.d.ts +34 -0
- package/dist/memory/injector.js +111 -0
- package/dist/memory/routes.d.ts +16 -0
- package/dist/memory/routes.js +146 -0
- package/dist/memory/store.d.ts +176 -0
- package/dist/memory/store.js +623 -0
- package/dist/memory/tools.d.ts +83 -0
- package/dist/memory/tools.js +143 -0
- package/dist/present-files.d.ts +25 -1
- package/dist/present-files.js +170 -2
- package/dist/scenario/applications.d.ts +52 -0
- package/dist/scenario/applications.js +143 -0
- package/dist/scenario/pack.d.ts +1 -1
- package/dist/security/policy-digest.d.ts +28 -0
- package/dist/security/policy-digest.js +104 -0
- package/dist/server/http-server.js +23 -6
- package/dist/sidecar/boot.d.ts +1 -0
- package/dist/sidecar/boot.js +2 -0
- package/dist/sidecar/rejected-before-effect.d.ts +22 -0
- package/dist/sidecar/rejected-before-effect.js +63 -0
- package/dist/sidecar/reverse-approval.d.ts +2 -0
- package/dist/sidecar/reverse-approval.js +28 -5
- package/dist/sidecar/reverse-tools.d.ts +3 -0
- package/dist/sidecar/reverse-tools.js +129 -17
- package/dist/sidecar/types.d.ts +6 -0
- package/dist/storage/fde-fallback.d.ts +4 -0
- package/dist/storage/fde-fallback.js +354 -0
- package/dist/storage/fde-types.d.ts +215 -0
- package/dist/storage/fde-types.js +1 -0
- package/dist/storage/index.d.ts +113 -1
- package/dist/storage/index.js +797 -0
- package/dist/storage/insights-redact.d.ts +4 -1
- package/dist/storage/insights-redact.js +6 -1
- package/dist/storage/process-locks.d.ts +1 -1
- package/dist/storage/process-locks.js +1 -1
- package/dist/storage/scoped-store.d.ts +3 -1
- package/dist/tool-presentation.js +20 -0
- package/dist/tool-router.d.ts +20 -1
- package/dist/tool-router.js +76 -12
- package/package.json +5 -5
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { CredentialInjection, PackCredentialClient, PackDataSource, Principal } from '@steerable/pack-sdk';
|
|
2
|
+
import type { ScopedStore } from '../storage/scoped-store.js';
|
|
3
|
+
export declare const REDACTED_CREDENTIAL_MARKER = "[REDACTED:credential]";
|
|
4
|
+
export declare const TENANT_CREDENTIAL_OWNER = "__tenant__";
|
|
5
|
+
/**
|
|
6
|
+
* Tracks active plaintext secrets and scrubs their raw, URL-encoded, and
|
|
7
|
+
* base64-encoded forms from strings and structured JSON payloads.
|
|
8
|
+
*/
|
|
9
|
+
export declare class SecretRedactor {
|
|
10
|
+
private readonly needles;
|
|
11
|
+
/** Registers one or more secret strings for scrubbing. */
|
|
12
|
+
registerSecret(secret: string): void;
|
|
13
|
+
/** Registers every string leaf inside a CredentialInjection payload. */
|
|
14
|
+
registerInjection(injection: CredentialInjection): void;
|
|
15
|
+
get hasSecrets(): boolean;
|
|
16
|
+
/** Alias for `redactString` matching `SideCallPort` / `diag-bundle` callers. */
|
|
17
|
+
redact(input: string): string;
|
|
18
|
+
/** Scrubs all registered secret needles in `input` (longest match first). */
|
|
19
|
+
redactString(input: string): string;
|
|
20
|
+
/** Deeply scrubs any string fields inside a JSON-compatible value. */
|
|
21
|
+
redactUnknown<T>(value: T): T;
|
|
22
|
+
private walk;
|
|
23
|
+
}
|
|
24
|
+
export interface StoredSecretPayload {
|
|
25
|
+
/** Bearer token, password, API key, or OAuth access token. */
|
|
26
|
+
secret?: string;
|
|
27
|
+
/** Optional username for Basic auth. */
|
|
28
|
+
username?: string;
|
|
29
|
+
/** Optional header name when `authKind === 'header'`. */
|
|
30
|
+
headerName?: string;
|
|
31
|
+
/** Optional explicit injection map when `authKind === 'custom_env'` or multi-header. */
|
|
32
|
+
headers?: Record<string, string>;
|
|
33
|
+
query?: Record<string, string>;
|
|
34
|
+
env?: Record<string, string>;
|
|
35
|
+
}
|
|
36
|
+
export interface CredentialMetadataItem {
|
|
37
|
+
readonly sourceId: string;
|
|
38
|
+
readonly label: Readonly<Record<string, string>>;
|
|
39
|
+
readonly authKind: NonNullable<PackDataSource['authKind']>;
|
|
40
|
+
readonly scope: NonNullable<PackDataSource['scope']>;
|
|
41
|
+
readonly requiredRoles: readonly string[];
|
|
42
|
+
readonly configured: boolean;
|
|
43
|
+
readonly updatedBy: string | null;
|
|
44
|
+
readonly updatedAt: string | null;
|
|
45
|
+
}
|
|
46
|
+
export declare class CredentialAccessError extends Error {
|
|
47
|
+
readonly status: 400 | 403 | 404;
|
|
48
|
+
constructor(status: 400 | 403 | 404, message: string);
|
|
49
|
+
}
|
|
50
|
+
export declare class CredentialBroker {
|
|
51
|
+
private readonly explicitKey?;
|
|
52
|
+
private readonly requireExplicitMasterKey?;
|
|
53
|
+
private readonly fetchImpl;
|
|
54
|
+
private readonly cache;
|
|
55
|
+
constructor(options?: {
|
|
56
|
+
masterKey?: Buffer;
|
|
57
|
+
requireExplicitMasterKey?: boolean;
|
|
58
|
+
fetchImpl?: typeof fetch;
|
|
59
|
+
});
|
|
60
|
+
private key;
|
|
61
|
+
/** Asserts that master key resolution succeeds (used at multi-tenant boot). */
|
|
62
|
+
assertReady(): void;
|
|
63
|
+
/** Stores or updates an encrypted credential for a registered PackDataSource. */
|
|
64
|
+
setCredential(store: ScopedStore, principal: Principal, sourceId: string, payload: StoredSecretPayload): Promise<CredentialMetadataItem>;
|
|
65
|
+
/** Deletes a stored credential. */
|
|
66
|
+
deleteCredential(store: ScopedStore, principal: Principal, sourceId: string): Promise<boolean>;
|
|
67
|
+
/** Lists registered PackDataSources and whether each has a configured secret (never returns secrets). */
|
|
68
|
+
listMetadata(store: ScopedStore, principal: Principal): Promise<CredentialMetadataItem[]>;
|
|
69
|
+
/**
|
|
70
|
+
* Resolves a decrypted `CredentialInjection` for `principal`, checking `updatedAt`
|
|
71
|
+
* against the store so rotated secrets in multi-process deployments invalidate
|
|
72
|
+
* stale caches immediately, and registers every secret value in `redactor`.
|
|
73
|
+
*/
|
|
74
|
+
resolveForTool(store: ScopedStore, principal: Principal, sourceId: string, redactor: SecretRedactor): Promise<CredentialInjection | null>;
|
|
75
|
+
/**
|
|
76
|
+
* Executes an outbound HTTP request with host-injected credentials and
|
|
77
|
+
* automatic cross-origin redirect stripping (R1-2).
|
|
78
|
+
*/
|
|
79
|
+
fetchWithCredential(store: ScopedStore, principal: Principal, sourceId: string, target: string | URL, init: RequestInit | undefined, redactor: SecretRedactor, fetchOverride?: typeof fetch): Promise<Response>;
|
|
80
|
+
/** Creates the `PackCredentialClient` passed on `PackToolContext.credentials`. */
|
|
81
|
+
createClient(store: ScopedStore, principal: Principal, redactor: SecretRedactor, fetchOverride?: typeof fetch): PackCredentialClient;
|
|
82
|
+
}
|
|
83
|
+
export declare const defaultCredentialBroker: CredentialBroker;
|
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-managed CredentialBroker & SecretRedactor (R1).
|
|
3
|
+
*
|
|
4
|
+
* Plaintext credentials never enter LLM context, tool schemas, persisted
|
|
5
|
+
* traces, or diagnostic bundles:
|
|
6
|
+
* - Encrypted at rest with AES-256-GCM using `STEERABLE_CREDENTIAL_MASTER_KEY`
|
|
7
|
+
* (required in multi-tenant mode) or a mode-0600 local master secret under
|
|
8
|
+
* `<userDataDir>/credential-master-key.bin` in single-user local mode.
|
|
9
|
+
* - Scoped to `'tenant'` (`owner_user_id = '__tenant__'`) or `'user'`
|
|
10
|
+
* (`owner_user_id = principal.id`) with role-based access checks against
|
|
11
|
+
* `PackDataSource.requiredRoles`.
|
|
12
|
+
* - Outbound `credentials.fetch(...)` injects auth headers/query at the egress
|
|
13
|
+
* boundary and strips injected auth headers on cross-origin HTTP redirects.
|
|
14
|
+
* - Every resolved secret is automatically registered into `SecretRedactor`
|
|
15
|
+
* so plaintext, URL-encoded, and Base64-encoded occurrences are scrubbed to
|
|
16
|
+
* `[REDACTED:credential]` before tool outputs reach the model or trace DB.
|
|
17
|
+
*/
|
|
18
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, } from 'node:crypto';
|
|
19
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { getAuthProvider } from './index.js';
|
|
22
|
+
import { getUserDataDir } from '../runtime.js';
|
|
23
|
+
import { ensurePhase9Store } from '../storage/fde-fallback.js';
|
|
24
|
+
import { getRegisteredDataSource, listRegisteredDataSources } from '../scenario/applications.js';
|
|
25
|
+
export const REDACTED_CREDENTIAL_MARKER = '[REDACTED:credential]';
|
|
26
|
+
export const TENANT_CREDENTIAL_OWNER = '__tenant__';
|
|
27
|
+
const MIN_REDACT_SECRET_LEN = 4;
|
|
28
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
29
|
+
const MAX_CREDENTIAL_REDIRECTS = 5;
|
|
30
|
+
/**
|
|
31
|
+
* Tracks active plaintext secrets and scrubs their raw, URL-encoded, and
|
|
32
|
+
* base64-encoded forms from strings and structured JSON payloads.
|
|
33
|
+
*/
|
|
34
|
+
export class SecretRedactor {
|
|
35
|
+
needles = new Set();
|
|
36
|
+
/** Registers one or more secret strings for scrubbing. */
|
|
37
|
+
registerSecret(secret) {
|
|
38
|
+
const trimmed = secret.trim();
|
|
39
|
+
if (trimmed.length < MIN_REDACT_SECRET_LEN)
|
|
40
|
+
return;
|
|
41
|
+
this.needles.add(trimmed);
|
|
42
|
+
const urlEncoded = encodeURIComponent(trimmed);
|
|
43
|
+
if (urlEncoded.length >= MIN_REDACT_SECRET_LEN) {
|
|
44
|
+
this.needles.add(urlEncoded);
|
|
45
|
+
}
|
|
46
|
+
const b64 = Buffer.from(trimmed, 'utf8').toString('base64');
|
|
47
|
+
if (b64.length >= MIN_REDACT_SECRET_LEN) {
|
|
48
|
+
this.needles.add(b64);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Registers every string leaf inside a CredentialInjection payload. */
|
|
52
|
+
registerInjection(injection) {
|
|
53
|
+
for (const group of [injection.headers, injection.query, injection.env]) {
|
|
54
|
+
if (!group)
|
|
55
|
+
continue;
|
|
56
|
+
for (const value of Object.values(group)) {
|
|
57
|
+
if (typeof value === 'string') {
|
|
58
|
+
this.registerSecret(value);
|
|
59
|
+
const parts = value.trim().split(/\s+/);
|
|
60
|
+
if (parts.length >= 2 && /^(bearer|basic|token|apikey)$/i.test(parts[0] ?? '')) {
|
|
61
|
+
this.registerSecret(parts.slice(1).join(' '));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
get hasSecrets() {
|
|
68
|
+
return this.needles.size > 0;
|
|
69
|
+
}
|
|
70
|
+
/** Alias for `redactString` matching `SideCallPort` / `diag-bundle` callers. */
|
|
71
|
+
redact(input) {
|
|
72
|
+
return this.redactString(input);
|
|
73
|
+
}
|
|
74
|
+
/** Scrubs all registered secret needles in `input` (longest match first). */
|
|
75
|
+
redactString(input) {
|
|
76
|
+
if (!input || this.needles.size === 0)
|
|
77
|
+
return input;
|
|
78
|
+
let out = input;
|
|
79
|
+
const ordered = [...this.needles].sort((a, b) => b.length - a.length);
|
|
80
|
+
for (const needle of ordered) {
|
|
81
|
+
if (out.includes(needle)) {
|
|
82
|
+
out = out.split(needle).join(REDACTED_CREDENTIAL_MARKER);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
/** Deeply scrubs any string fields inside a JSON-compatible value. */
|
|
88
|
+
redactUnknown(value) {
|
|
89
|
+
if (this.needles.size === 0)
|
|
90
|
+
return value;
|
|
91
|
+
return this.walk(value, new WeakSet());
|
|
92
|
+
}
|
|
93
|
+
walk(value, seen) {
|
|
94
|
+
if (typeof value === 'string')
|
|
95
|
+
return this.redactString(value);
|
|
96
|
+
if (!value || typeof value !== 'object')
|
|
97
|
+
return value;
|
|
98
|
+
if (value instanceof Uint8Array || Buffer.isBuffer(value))
|
|
99
|
+
return value;
|
|
100
|
+
if (seen.has(value))
|
|
101
|
+
return value;
|
|
102
|
+
seen.add(value);
|
|
103
|
+
if (Array.isArray(value)) {
|
|
104
|
+
return value.map((item) => this.walk(item, seen));
|
|
105
|
+
}
|
|
106
|
+
const out = {};
|
|
107
|
+
for (const [k, v] of Object.entries(value)) {
|
|
108
|
+
out[k] = this.walk(v, seen);
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
export class CredentialAccessError extends Error {
|
|
114
|
+
status;
|
|
115
|
+
constructor(status, message) {
|
|
116
|
+
super(message);
|
|
117
|
+
this.status = status;
|
|
118
|
+
this.name = 'CredentialAccessError';
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function isMultiTenantRuntime() {
|
|
122
|
+
return process.env.DEEPPATH_TEAM_MODE === '1' || getAuthProvider() !== null;
|
|
123
|
+
}
|
|
124
|
+
function resolveMasterKey(explicitKey, requireExplicitMasterKey) {
|
|
125
|
+
if (explicitKey) {
|
|
126
|
+
if (explicitKey.byteLength !== 32) {
|
|
127
|
+
throw new Error('[credentials] explicit master key must be 32 bytes');
|
|
128
|
+
}
|
|
129
|
+
return explicitKey;
|
|
130
|
+
}
|
|
131
|
+
const envKey = process.env.STEERABLE_CREDENTIAL_MASTER_KEY?.trim();
|
|
132
|
+
if (envKey) {
|
|
133
|
+
if (/^[0-9a-fA-F]{64}$/.test(envKey)) {
|
|
134
|
+
return Buffer.from(envKey, 'hex');
|
|
135
|
+
}
|
|
136
|
+
const asBase64 = Buffer.from(envKey, 'base64');
|
|
137
|
+
if (asBase64.byteLength === 32)
|
|
138
|
+
return asBase64;
|
|
139
|
+
return createHash('sha256').update(envKey, 'utf8').digest();
|
|
140
|
+
}
|
|
141
|
+
if (requireExplicitMasterKey ?? isMultiTenantRuntime()) {
|
|
142
|
+
throw new Error('[credentials] STEERABLE_CREDENTIAL_MASTER_KEY is required in multi-tenant mode');
|
|
143
|
+
}
|
|
144
|
+
const dir = getUserDataDir();
|
|
145
|
+
mkdirSync(dir, { recursive: true });
|
|
146
|
+
// File uses .bin (never .pem/.key) with mode 0600 for owner-only local persistence.
|
|
147
|
+
const filePath = path.join(dir, 'credential-master-key.bin');
|
|
148
|
+
if (existsSync(filePath)) {
|
|
149
|
+
const raw = readFileSync(filePath);
|
|
150
|
+
if (raw.byteLength === 32)
|
|
151
|
+
return raw;
|
|
152
|
+
}
|
|
153
|
+
const generated = randomBytes(32);
|
|
154
|
+
writeFileSync(filePath, generated, { mode: 0o600 });
|
|
155
|
+
if (process.platform !== 'win32') {
|
|
156
|
+
try {
|
|
157
|
+
chmodSync(filePath, 0o600);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// Read-only / non-POSIX filesystem fallback
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return generated;
|
|
164
|
+
}
|
|
165
|
+
function encryptPayload(payload, key) {
|
|
166
|
+
const iv = randomBytes(12);
|
|
167
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
168
|
+
const plain = Buffer.from(JSON.stringify(payload), 'utf8');
|
|
169
|
+
const encrypted = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
170
|
+
const authTag = cipher.getAuthTag();
|
|
171
|
+
return {
|
|
172
|
+
cipherText: encrypted.toString('base64'),
|
|
173
|
+
iv: iv.toString('base64'),
|
|
174
|
+
authTag: authTag.toString('base64'),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function decryptPayload(record, key) {
|
|
178
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(record.iv, 'base64'));
|
|
179
|
+
decipher.setAuthTag(Buffer.from(record.authTag, 'base64'));
|
|
180
|
+
const decrypted = Buffer.concat([
|
|
181
|
+
decipher.update(Buffer.from(record.cipherText, 'base64')),
|
|
182
|
+
decipher.final(),
|
|
183
|
+
]);
|
|
184
|
+
return JSON.parse(decrypted.toString('utf8'));
|
|
185
|
+
}
|
|
186
|
+
function effectiveAuthKind(source) {
|
|
187
|
+
return source.authKind ?? 'bearer';
|
|
188
|
+
}
|
|
189
|
+
function effectiveScope(source) {
|
|
190
|
+
return source.scope ?? 'tenant';
|
|
191
|
+
}
|
|
192
|
+
function effectiveLabel(source) {
|
|
193
|
+
return source.label ?? { en: source.id, zh: source.id };
|
|
194
|
+
}
|
|
195
|
+
function toCredentialInjection(authKind, payload) {
|
|
196
|
+
const headers = { ...(payload.headers ?? {}) };
|
|
197
|
+
const query = { ...(payload.query ?? {}) };
|
|
198
|
+
const env = { ...(payload.env ?? {}) };
|
|
199
|
+
if (payload.secret) {
|
|
200
|
+
if (authKind === 'bearer' || authKind === 'oauth2') {
|
|
201
|
+
headers.Authorization ??= `Bearer ${payload.secret}`;
|
|
202
|
+
}
|
|
203
|
+
else if (authKind === 'basic') {
|
|
204
|
+
const user = payload.username ?? '';
|
|
205
|
+
const encoded = Buffer.from(`${user}:${payload.secret}`, 'utf8').toString('base64');
|
|
206
|
+
headers.Authorization ??= `Basic ${encoded}`;
|
|
207
|
+
}
|
|
208
|
+
else if (authKind === 'header') {
|
|
209
|
+
const headerName = payload.headerName?.trim() || 'X-API-Key';
|
|
210
|
+
headers[headerName] ??= payload.secret;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
...(Object.keys(headers).length > 0 ? { headers } : {}),
|
|
215
|
+
...(Object.keys(query).length > 0 ? { query } : {}),
|
|
216
|
+
...(Object.keys(env).length > 0 ? { env } : {}),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function hasRequiredRoles(principal, source) {
|
|
220
|
+
if (principal.isAdmin)
|
|
221
|
+
return true;
|
|
222
|
+
const required = source.requiredRoles ?? [];
|
|
223
|
+
if (required.length === 0)
|
|
224
|
+
return true;
|
|
225
|
+
const held = new Set(principal.roles);
|
|
226
|
+
return required.some((r) => held.has(r));
|
|
227
|
+
}
|
|
228
|
+
function ownerUserIdForSource(principal, source) {
|
|
229
|
+
return effectiveScope(source) === 'tenant' ? TENANT_CREDENTIAL_OWNER : principal.id;
|
|
230
|
+
}
|
|
231
|
+
export class CredentialBroker {
|
|
232
|
+
explicitKey;
|
|
233
|
+
requireExplicitMasterKey;
|
|
234
|
+
fetchImpl;
|
|
235
|
+
cache = new Map();
|
|
236
|
+
constructor(options) {
|
|
237
|
+
this.explicitKey = options?.masterKey;
|
|
238
|
+
this.requireExplicitMasterKey = options?.requireExplicitMasterKey;
|
|
239
|
+
this.fetchImpl = options?.fetchImpl ?? globalThis.fetch;
|
|
240
|
+
}
|
|
241
|
+
key() {
|
|
242
|
+
return resolveMasterKey(this.explicitKey, this.requireExplicitMasterKey);
|
|
243
|
+
}
|
|
244
|
+
/** Asserts that master key resolution succeeds (used at multi-tenant boot). */
|
|
245
|
+
assertReady() {
|
|
246
|
+
this.key();
|
|
247
|
+
}
|
|
248
|
+
/** Stores or updates an encrypted credential for a registered PackDataSource. */
|
|
249
|
+
async setCredential(store, principal, sourceId, payload) {
|
|
250
|
+
const source = getRegisteredDataSource(sourceId);
|
|
251
|
+
if (!source) {
|
|
252
|
+
throw new CredentialAccessError(404, `Unknown data source: ${sourceId}`);
|
|
253
|
+
}
|
|
254
|
+
const scope = effectiveScope(source);
|
|
255
|
+
const authKind = effectiveAuthKind(source);
|
|
256
|
+
if (scope === 'tenant' && !principal.isAdmin && !hasRequiredRoles(principal, source)) {
|
|
257
|
+
throw new CredentialAccessError(403, `Principal ${principal.id} is not authorized to configure tenant data source ${sourceId}`);
|
|
258
|
+
}
|
|
259
|
+
if (!hasRequiredRoles(principal, source)) {
|
|
260
|
+
throw new CredentialAccessError(403, `Principal ${principal.id} lacks required role for data source ${sourceId}`);
|
|
261
|
+
}
|
|
262
|
+
const encrypted = encryptPayload(payload, this.key());
|
|
263
|
+
const ownerUserId = ownerUserIdForSource(principal, source);
|
|
264
|
+
const p9 = ensurePhase9Store(store);
|
|
265
|
+
const saved = await p9.upsertPackCredential({
|
|
266
|
+
ownerUserId,
|
|
267
|
+
sourceId,
|
|
268
|
+
authKind,
|
|
269
|
+
cipherText: encrypted.cipherText,
|
|
270
|
+
iv: encrypted.iv,
|
|
271
|
+
authTag: encrypted.authTag,
|
|
272
|
+
updatedBy: principal.id,
|
|
273
|
+
});
|
|
274
|
+
this.cache.set(`${principal.tenantId}\u0000${ownerUserId}\u0000${sourceId}`, {
|
|
275
|
+
updatedAt: saved.updatedAt,
|
|
276
|
+
payload,
|
|
277
|
+
});
|
|
278
|
+
return {
|
|
279
|
+
sourceId: source.id,
|
|
280
|
+
label: effectiveLabel(source),
|
|
281
|
+
authKind,
|
|
282
|
+
scope,
|
|
283
|
+
requiredRoles: source.requiredRoles ?? [],
|
|
284
|
+
configured: true,
|
|
285
|
+
updatedBy: saved.updatedBy,
|
|
286
|
+
updatedAt: saved.updatedAt,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
/** Deletes a stored credential. */
|
|
290
|
+
async deleteCredential(store, principal, sourceId) {
|
|
291
|
+
const source = getRegisteredDataSource(sourceId);
|
|
292
|
+
if (!source) {
|
|
293
|
+
throw new CredentialAccessError(404, `Unknown data source: ${sourceId}`);
|
|
294
|
+
}
|
|
295
|
+
if (effectiveScope(source) === 'tenant' && !principal.isAdmin) {
|
|
296
|
+
throw new CredentialAccessError(403, `Only tenant administrators can delete tenant data source ${sourceId}`);
|
|
297
|
+
}
|
|
298
|
+
const ownerUserId = ownerUserIdForSource(principal, source);
|
|
299
|
+
this.cache.delete(`${principal.tenantId}\u0000${ownerUserId}\u0000${sourceId}`);
|
|
300
|
+
const p9 = ensurePhase9Store(store);
|
|
301
|
+
return p9.deletePackCredential(ownerUserId, sourceId);
|
|
302
|
+
}
|
|
303
|
+
/** Lists registered PackDataSources and whether each has a configured secret (never returns secrets). */
|
|
304
|
+
async listMetadata(store, principal) {
|
|
305
|
+
const p9 = ensurePhase9Store(store);
|
|
306
|
+
const rows = await p9.listPackCredentials([principal.id, TENANT_CREDENTIAL_OWNER]);
|
|
307
|
+
const byKey = new Map(rows.map((r) => [`${r.ownerUserId}\u0000${r.sourceId}`, r]));
|
|
308
|
+
return listRegisteredDataSources()
|
|
309
|
+
.filter((source) => source.authKind !== undefined || !source.query)
|
|
310
|
+
.map((source) => {
|
|
311
|
+
const owner = ownerUserIdForSource(principal, source);
|
|
312
|
+
const found = hasRequiredRoles(principal, source)
|
|
313
|
+
? byKey.get(`${owner}\u0000${source.id}`)
|
|
314
|
+
: undefined;
|
|
315
|
+
return {
|
|
316
|
+
sourceId: source.id,
|
|
317
|
+
label: effectiveLabel(source),
|
|
318
|
+
authKind: effectiveAuthKind(source),
|
|
319
|
+
scope: effectiveScope(source),
|
|
320
|
+
requiredRoles: source.requiredRoles ?? [],
|
|
321
|
+
configured: Boolean(found),
|
|
322
|
+
updatedBy: found?.updatedBy ?? null,
|
|
323
|
+
updatedAt: found?.updatedAt ?? null,
|
|
324
|
+
};
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Resolves a decrypted `CredentialInjection` for `principal`, checking `updatedAt`
|
|
329
|
+
* against the store so rotated secrets in multi-process deployments invalidate
|
|
330
|
+
* stale caches immediately, and registers every secret value in `redactor`.
|
|
331
|
+
*/
|
|
332
|
+
async resolveForTool(store, principal, sourceId, redactor) {
|
|
333
|
+
const source = getRegisteredDataSource(sourceId);
|
|
334
|
+
if (!source)
|
|
335
|
+
return null;
|
|
336
|
+
if (!hasRequiredRoles(principal, source))
|
|
337
|
+
return null;
|
|
338
|
+
const ownerUserId = ownerUserIdForSource(principal, source);
|
|
339
|
+
const p9 = ensurePhase9Store(store);
|
|
340
|
+
const row = await p9.getPackCredential(ownerUserId, sourceId);
|
|
341
|
+
const cacheKey = `${principal.tenantId}\u0000${ownerUserId}\u0000${sourceId}`;
|
|
342
|
+
if (!row || row.tenantId !== principal.tenantId) {
|
|
343
|
+
this.cache.delete(cacheKey);
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
const cached = this.cache.get(cacheKey);
|
|
347
|
+
const payload = cached && cached.updatedAt === row.updatedAt
|
|
348
|
+
? cached.payload
|
|
349
|
+
: decryptPayload(row, this.key());
|
|
350
|
+
if (!cached || cached.updatedAt !== row.updatedAt) {
|
|
351
|
+
this.cache.set(cacheKey, { updatedAt: row.updatedAt, payload });
|
|
352
|
+
}
|
|
353
|
+
if (payload.secret)
|
|
354
|
+
redactor.registerSecret(payload.secret);
|
|
355
|
+
const injection = toCredentialInjection(effectiveAuthKind(source), payload);
|
|
356
|
+
redactor.registerInjection(injection);
|
|
357
|
+
return injection;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Executes an outbound HTTP request with host-injected credentials and
|
|
361
|
+
* automatic cross-origin redirect stripping (R1-2).
|
|
362
|
+
*/
|
|
363
|
+
async fetchWithCredential(store, principal, sourceId, target, init, redactor, fetchOverride) {
|
|
364
|
+
const injection = await this.resolveForTool(store, principal, sourceId, redactor);
|
|
365
|
+
const doFetch = fetchOverride ?? this.fetchImpl;
|
|
366
|
+
const initialUrl = new URL(String(target));
|
|
367
|
+
const initialOrigin = initialUrl.origin;
|
|
368
|
+
const injectedHeaderNames = [];
|
|
369
|
+
const baseHeaders = new Headers(init?.headers);
|
|
370
|
+
if (injection?.headers) {
|
|
371
|
+
for (const [k, v] of Object.entries(injection.headers)) {
|
|
372
|
+
baseHeaders.set(k, v);
|
|
373
|
+
injectedHeaderNames.push(k);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (injection?.query) {
|
|
377
|
+
for (const [k, v] of Object.entries(injection.query)) {
|
|
378
|
+
initialUrl.searchParams.set(k, v);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
let currentUrl = initialUrl;
|
|
382
|
+
let currentHeaders = new Headers(baseHeaders);
|
|
383
|
+
let currentMethod = init?.method ?? 'GET';
|
|
384
|
+
let currentBody = init?.body;
|
|
385
|
+
for (let hop = 0; hop <= MAX_CREDENTIAL_REDIRECTS; hop += 1) {
|
|
386
|
+
const response = await doFetch(currentUrl.toString(), {
|
|
387
|
+
...init,
|
|
388
|
+
method: currentMethod,
|
|
389
|
+
headers: currentHeaders,
|
|
390
|
+
body: currentBody,
|
|
391
|
+
redirect: 'manual',
|
|
392
|
+
});
|
|
393
|
+
if (!REDIRECT_STATUSES.has(response.status)) {
|
|
394
|
+
return response;
|
|
395
|
+
}
|
|
396
|
+
const location = response.headers.get('location');
|
|
397
|
+
if (!location || hop === MAX_CREDENTIAL_REDIRECTS) {
|
|
398
|
+
return response;
|
|
399
|
+
}
|
|
400
|
+
const nextUrl = new URL(location, currentUrl);
|
|
401
|
+
if (nextUrl.origin !== initialOrigin) {
|
|
402
|
+
for (const headerName of injectedHeaderNames) {
|
|
403
|
+
currentHeaders.delete(headerName);
|
|
404
|
+
}
|
|
405
|
+
currentHeaders.delete('authorization');
|
|
406
|
+
currentHeaders.delete('cookie');
|
|
407
|
+
}
|
|
408
|
+
if (response.status === 303 ||
|
|
409
|
+
((response.status === 301 || response.status === 302) &&
|
|
410
|
+
currentMethod.toUpperCase() === 'POST')) {
|
|
411
|
+
currentMethod = 'GET';
|
|
412
|
+
currentBody = undefined;
|
|
413
|
+
}
|
|
414
|
+
currentUrl = nextUrl;
|
|
415
|
+
}
|
|
416
|
+
throw new Error('[credentials] redirect limit exceeded');
|
|
417
|
+
}
|
|
418
|
+
/** Creates the `PackCredentialClient` passed on `PackToolContext.credentials`. */
|
|
419
|
+
createClient(store, principal, redactor, fetchOverride) {
|
|
420
|
+
return {
|
|
421
|
+
resolve: (sourceId) => this.resolveForTool(store, principal, sourceId, redactor),
|
|
422
|
+
fetch: (sourceId, url, init) => this.fetchWithCredential(store, principal, sourceId, url, init, redactor, fetchOverride),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
export const defaultCredentialBroker = new CredentialBroker();
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Product-neutral authenticated identity
|
|
2
|
+
* Product-neutral authenticated identity, origin channel, and unauthenticated
|
|
3
|
+
* bootstrap discovery contracts.
|
|
3
4
|
*/
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
5
|
+
import type { OriginChannel, Principal, PublicBootstrapPayload } from '@steerable/pack-sdk';
|
|
6
|
+
export type { OriginChannel, Principal, PublicAuthMethod, PublicBootstrapPayload, } from '@steerable/pack-sdk';
|
|
7
|
+
/**
|
|
8
|
+
* Default local identity injected when running in single-user desktop, CLI,
|
|
9
|
+
* or loopback BS mode without an external AuthProvider.
|
|
10
|
+
*/
|
|
11
|
+
export declare const LOCAL_DEFAULT_PRINCIPAL: Principal;
|
|
12
|
+
/**
|
|
13
|
+
* Normalizes an incoming channel hint from request headers, IPC metadata, or
|
|
14
|
+
* CLI options, falling back to `fallback` ('web' by default).
|
|
15
|
+
*/
|
|
16
|
+
export declare function parseOriginChannel(value: unknown, fallback?: OriginChannel): OriginChannel;
|
|
17
|
+
/** True when a channel cannot host rich interactive approvals or workbenches. */
|
|
18
|
+
export declare function isRestrictedOriginChannel(channel: OriginChannel | undefined): boolean;
|
|
12
19
|
export type AuthDecision = {
|
|
13
20
|
ok: true;
|
|
14
21
|
principal: Principal;
|
|
@@ -27,7 +34,13 @@ export interface AuthProvider {
|
|
|
27
34
|
readonly id: string;
|
|
28
35
|
authenticate(headers: Readonly<Record<string, string | string[] | undefined>>): Promise<AuthDecision>;
|
|
29
36
|
describeSelf(principal: Principal): Promise<unknown>;
|
|
37
|
+
/**
|
|
38
|
+
* Optional public bootstrap descriptor returned before authentication by
|
|
39
|
+
* `GET /api/v2/auth/bootstrap`. Must never include secrets or private user data.
|
|
40
|
+
*/
|
|
41
|
+
describeBootstrap?(headers: Readonly<Record<string, string | string[] | undefined>>): Promise<Partial<PublicBootstrapPayload>> | Partial<PublicBootstrapPayload>;
|
|
30
42
|
}
|
|
43
|
+
export type PublicBootstrapResolver = (headers: Readonly<Record<string, string | string[] | undefined>>) => Promise<Partial<PublicBootstrapPayload>> | Partial<PublicBootstrapPayload>;
|
|
31
44
|
/**
|
|
32
45
|
* Registers the process-wide provider before the BS host starts.
|
|
33
46
|
*
|
|
@@ -36,3 +49,14 @@ export interface AuthProvider {
|
|
|
36
49
|
export declare function registerAuthProvider(provider: AuthProvider): () => void;
|
|
37
50
|
/** Returns the provider registered by the product composition root, if any. */
|
|
38
51
|
export declare function getAuthProvider(): AuthProvider | null;
|
|
52
|
+
/**
|
|
53
|
+
* Registers an optional override for `GET /api/v2/auth/bootstrap`.
|
|
54
|
+
*/
|
|
55
|
+
export declare function registerBootstrapProvider(resolver: PublicBootstrapResolver): () => void;
|
|
56
|
+
/** Resets bootstrap override in tests. */
|
|
57
|
+
export declare function resetBootstrapProvider(): void;
|
|
58
|
+
/**
|
|
59
|
+
* Computes the unauthenticated `PublicBootstrapPayload` for login gates and
|
|
60
|
+
* preflight checks (`GET /api/v2/auth/bootstrap`).
|
|
61
|
+
*/
|
|
62
|
+
export declare function resolvePublicBootstrap(headers?: Readonly<Record<string, string | string[] | undefined>>, extras?: Partial<PublicBootstrapPayload>): Promise<PublicBootstrapPayload>;
|
package/dist/auth/index.js
CHANGED
|
@@ -1,4 +1,42 @@
|
|
|
1
|
+
import { getBrand } from '../brand.js';
|
|
2
|
+
/**
|
|
3
|
+
* Default local identity injected when running in single-user desktop, CLI,
|
|
4
|
+
* or loopback BS mode without an external AuthProvider.
|
|
5
|
+
*/
|
|
6
|
+
export const LOCAL_DEFAULT_PRINCIPAL = Object.freeze({
|
|
7
|
+
id: 'local',
|
|
8
|
+
tenantId: 'local',
|
|
9
|
+
displayName: 'Local User',
|
|
10
|
+
email: null,
|
|
11
|
+
roles: Object.freeze(['owner']),
|
|
12
|
+
isAdmin: true,
|
|
13
|
+
});
|
|
14
|
+
const VALID_ORIGIN_CHANNELS = new Set([
|
|
15
|
+
'desktop',
|
|
16
|
+
'web',
|
|
17
|
+
'cli',
|
|
18
|
+
'im',
|
|
19
|
+
'webhook',
|
|
20
|
+
]);
|
|
21
|
+
/**
|
|
22
|
+
* Normalizes an incoming channel hint from request headers, IPC metadata, or
|
|
23
|
+
* CLI options, falling back to `fallback` ('web' by default).
|
|
24
|
+
*/
|
|
25
|
+
export function parseOriginChannel(value, fallback = 'web') {
|
|
26
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
27
|
+
if (typeof raw === 'string') {
|
|
28
|
+
const trimmed = raw.trim().toLowerCase();
|
|
29
|
+
if (VALID_ORIGIN_CHANNELS.has(trimmed))
|
|
30
|
+
return trimmed;
|
|
31
|
+
}
|
|
32
|
+
return fallback;
|
|
33
|
+
}
|
|
34
|
+
/** True when a channel cannot host rich interactive approvals or workbenches. */
|
|
35
|
+
export function isRestrictedOriginChannel(channel) {
|
|
36
|
+
return channel === 'im' || channel === 'webhook';
|
|
37
|
+
}
|
|
1
38
|
let activeProvider = null;
|
|
39
|
+
let bootstrapResolver = null;
|
|
2
40
|
/**
|
|
3
41
|
* Registers the process-wide provider before the BS host starts.
|
|
4
42
|
*
|
|
@@ -18,3 +56,50 @@ export function registerAuthProvider(provider) {
|
|
|
18
56
|
export function getAuthProvider() {
|
|
19
57
|
return activeProvider;
|
|
20
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Registers an optional override for `GET /api/v2/auth/bootstrap`.
|
|
61
|
+
*/
|
|
62
|
+
export function registerBootstrapProvider(resolver) {
|
|
63
|
+
bootstrapResolver = resolver;
|
|
64
|
+
return () => {
|
|
65
|
+
if (bootstrapResolver === resolver)
|
|
66
|
+
bootstrapResolver = null;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** Resets bootstrap override in tests. */
|
|
70
|
+
export function resetBootstrapProvider() {
|
|
71
|
+
bootstrapResolver = null;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Computes the unauthenticated `PublicBootstrapPayload` for login gates and
|
|
75
|
+
* preflight checks (`GET /api/v2/auth/bootstrap`).
|
|
76
|
+
*/
|
|
77
|
+
export async function resolvePublicBootstrap(headers = {}, extras) {
|
|
78
|
+
const brand = getBrand();
|
|
79
|
+
const fromProvider = activeProvider?.describeBootstrap
|
|
80
|
+
? await activeProvider.describeBootstrap(headers)
|
|
81
|
+
: undefined;
|
|
82
|
+
const fromOverride = bootstrapResolver
|
|
83
|
+
? await bootstrapResolver(headers)
|
|
84
|
+
: undefined;
|
|
85
|
+
const merged = {
|
|
86
|
+
...fromProvider,
|
|
87
|
+
...fromOverride,
|
|
88
|
+
...extras,
|
|
89
|
+
};
|
|
90
|
+
const authRequired = merged.authRequired ?? Boolean(activeProvider);
|
|
91
|
+
const authMethods = merged.authMethods ??
|
|
92
|
+
(authRequired
|
|
93
|
+
? [{ kind: 'password', showTenantSlugInput: true }]
|
|
94
|
+
: []);
|
|
95
|
+
return {
|
|
96
|
+
productName: merged.productName ?? brand.displayName,
|
|
97
|
+
authRequired,
|
|
98
|
+
authMethods,
|
|
99
|
+
...(merged.iamMode !== undefined ? { iamMode: merged.iamMode } : {}),
|
|
100
|
+
...(merged.defaultApplicationId !== undefined
|
|
101
|
+
? { defaultApplicationId: merged.defaultApplicationId }
|
|
102
|
+
: {}),
|
|
103
|
+
...(merged.safeMode !== undefined ? { safeMode: merged.safeMode } : {}),
|
|
104
|
+
};
|
|
105
|
+
}
|