@silverprotocol/google-adk 0.6.7 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,407 @@
1
+ /**
2
+ * ADK auth objects inside anything the facet carries: the flat AgAuthConfig
3
+ * view, the member allowlists, the shared-state credential omission and the
4
+ * node-data reduction. Internal to @silverprotocol/google-adk (not part of its
5
+ * package exports); index.ts is the only importer, and the tests call these
6
+ * helpers directly.
7
+ */
8
+ import { JsonValue, type AgAuthConfig } from "@silverprotocol/core";
9
+ import { isJsonObject, stringMember } from "./json-guards.js";
10
+
11
+ // ─── ADK AuthConfig → flat AgAuthConfig view (SPEC §8.0 item 12) ─────────────
12
+ // ADK's AuthConfig (@google/adk 2.1.0 dist/types/auth/auth_tool.d.ts:12-42) is
13
+ // `{ authScheme, rawAuthCredential?, exchangedAuthCredential?, credentialKey }`,
14
+ // with authScheme an OpenAPI v3 SecuritySchemeObject or OIDC-with-config
15
+ // (auth_schemes.d.ts:12, :25). The view maps ONLY what has a native value:
16
+ // - scheme ← authScheme.type, verbatim; no string type → no view at all (the
17
+ // field is required and never invented);
18
+ // - authorizationUrl / tokenUrl / scopes follow ADK's own derivation
19
+ // (dist/esm/auth/auth_handler.js:112-128): OIDC-with-config's
20
+ // authorizationEndpoint / tokenEndpoint / scopes; for oauth2, the first
21
+ // present flow of implicit > authorizationCode > clientCredentials >
22
+ // password, with scopes = the keys of its OpenAPI scopes map;
23
+ // - clientId / audience ← rawAuthCredential.oauth2 (auth_credential.d.ts:35-62).
24
+ // credentialKey, secrets and exchange state never enter the view.
25
+ // ─── ADK auth objects: carry only members known to be non-secret ─────────────
26
+ // An ADK AuthConfig, and the credential objects inside it, can hold credential
27
+ // material. Anything the facet forwards is persisted by hosts (hitl.ask →
28
+ // turn.done paused asks[]; tool-call blocks). So every carrier of an ADK auth
29
+ // object is an ALLOWLIST: a member is forwarded only when it is known to be
30
+ // non-secret, and every other member, at any depth, is omitted. The list is
31
+ // checked against @google/adk 2.1.0 dist/types/auth/auth_tool.d.ts and
32
+ // auth_credential.d.ts. Keys match in camelCase or snake_case (the reserved
33
+ // call's args arrive snake_case at the top level); a kept key keeps its wire
34
+ // spelling.
35
+ //
36
+ // Resume safety (ADK 2.1.0, a tool's credential request inside an LlmAgent):
37
+ // the credential resume rebuilds the request
38
+ // server-side from the session's own reserved call (auth_preprocessor.js
39
+ // requestedAuthConfigs) and takes only the auth code / response URI from the
40
+ // client's answer (credential_response_binding.js bindCredential; the raw
41
+ // credential is restored from the request). An oauth2/OIDC request always
42
+ // carries a generated authUri (auth_handler.js generateAuthRequest). So what
43
+ // the allowlist omits is never needed to answer the ask.
44
+ export const ADK_REQUEST_CREDENTIAL = "adk_request_credential";
45
+
46
+ type AllowSpec = { [key: string]: true | ((v: JsonValue) => JsonValue | undefined) };
47
+
48
+ export function snakeKey(k: string): string {
49
+ return k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
50
+ }
51
+
52
+ /** Copy only the allowlisted members of `v` (camel or snake spelling), each
53
+ * either verbatim (`true`) or through its nested allowlist. */
54
+ export function pickAllowed(v: JsonValue | undefined, spec: AllowSpec): JsonValue | undefined {
55
+ if (!isJsonObject(v)) return undefined;
56
+ const out: { [k: string]: JsonValue } = {};
57
+ for (const [name, rule] of Object.entries(spec)) {
58
+ for (const key of name === snakeKey(name) ? [name] : [name, snakeKey(name)]) {
59
+ if (!Object.hasOwn(v, key)) continue;
60
+ const member = v[key];
61
+ if (member === undefined) continue;
62
+ const kept = rule === true ? member : rule(member);
63
+ if (kept !== undefined) out[key] = kept;
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+
69
+ const OAUTH2_ALLOW: AllowSpec = {
70
+ clientId: true,
71
+ authUri: true,
72
+ redirectUri: true,
73
+ scopes: true,
74
+ codeChallengeMethod: true,
75
+ tokenEndpointAuthMethod: true,
76
+ expiresAt: true,
77
+ expiresIn: true,
78
+ audience: true,
79
+ };
80
+ const SERVICE_ACCOUNT_ALLOW: AllowSpec = {
81
+ scopes: true,
82
+ useDefaultCredential: true,
83
+ useIdToken: true,
84
+ audience: true,
85
+ serviceAccountCredential: (v) =>
86
+ pickAllowed(v, { projectId: true, clientEmail: true, tokenUri: true, universeDomain: true }),
87
+ };
88
+ const AUTH_CREDENTIAL_ALLOW: AllowSpec = {
89
+ authType: true,
90
+ resourceRef: true,
91
+ oauth2: (v) => pickAllowed(v, OAUTH2_ALLOW),
92
+ serviceAccount: (v) => pickAllowed(v, SERVICE_ACCOUNT_ALLOW),
93
+ };
94
+ // The security scheme, member by member: an OpenAPI 3.0 SecuritySchemeObject
95
+ // (openapi-types 12.1.3 OpenAPIV3: http, apiKey, oauth2 and openIdConnect,
96
+ // the type @google/adk 2.1.0's auth_schemes.d.ts names) or ADK's
97
+ // OpenIdConnectWithConfig. Every leaf is a string, a string list or a map of
98
+ // strings, and only those survive. A scheme member no type declares (a vendor
99
+ // extension, a stray field) never rides.
100
+ const schemeString = (v: JsonValue): JsonValue | undefined => (typeof v === "string" ? v : undefined);
101
+ const schemeStringList = (v: JsonValue): JsonValue | undefined =>
102
+ Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
103
+ /** A map this facet rebuilds from native entries never carries an own
104
+ * `__proto__` key (SPEC §13.7): JsonValue.parse drops one, and
105
+ * Object.fromEntries would re-create it as an own property. */
106
+ function isReservedMapKey(k: string): boolean {
107
+ return k === "__proto__";
108
+ }
109
+ /** OAuth2 flow scopes are a map of scope name -> description; OIDC config
110
+ * scopes are a list. Either keeps only its string entries. */
111
+ const schemeScopes = (v: JsonValue): JsonValue | undefined =>
112
+ Array.isArray(v)
113
+ ? schemeStringList(v)
114
+ : isJsonObject(v)
115
+ ? Object.fromEntries(
116
+ Object.entries(v).filter((e): e is [string, string] => !isReservedMapKey(e[0]) && typeof e[1] === "string"),
117
+ )
118
+ : undefined;
119
+ const OAUTH2_FLOW_ALLOW: AllowSpec = {
120
+ authorizationUrl: schemeString,
121
+ tokenUrl: schemeString,
122
+ refreshUrl: schemeString,
123
+ scopes: schemeScopes,
124
+ };
125
+ const AUTH_SCHEME_ALLOW: AllowSpec = {
126
+ type: schemeString,
127
+ description: schemeString,
128
+ // http
129
+ scheme: schemeString,
130
+ bearerFormat: schemeString,
131
+ // apiKey (the header/query parameter's name and location, never its value)
132
+ name: schemeString,
133
+ in: schemeString,
134
+ // oauth2 (flows.password is the password-GRANT flow: a tokenUrl and scopes)
135
+ flows: (v) =>
136
+ pickAllowed(v, {
137
+ implicit: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
138
+ password: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
139
+ clientCredentials: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
140
+ authorizationCode: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
141
+ }),
142
+ // openIdConnect
143
+ openIdConnectUrl: schemeString,
144
+ // OpenIdConnectWithConfig
145
+ authorizationEndpoint: schemeString,
146
+ tokenEndpoint: schemeString,
147
+ userinfoEndpoint: schemeString,
148
+ revocationEndpoint: schemeString,
149
+ tokenEndpointAuthMethodsSupported: schemeStringList,
150
+ grantTypesSupported: schemeStringList,
151
+ scopes: schemeScopes,
152
+ };
153
+ const AUTH_CONFIG_ALLOW: AllowSpec = {
154
+ authScheme: (v) => pickAllowed(v, AUTH_SCHEME_ALLOW),
155
+ credentialKey: true,
156
+ rawAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
157
+ exchangedAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
158
+ };
159
+
160
+ // ─── shared state (state.delta) ──────────────────────────────────────────────
161
+ // ADK itself writes an exchanged AuthCredential into the event's
162
+ // actions.stateDelta on two paths (@google/adk 2.1.0):
163
+ // - a Runner configured with SessionStateCredentialService saves it under the
164
+ // bare credentialKey (session_state_credential_service.js; ToolContext's
165
+ // State writes value AND delta, agents/context.js:37-39, sessions/state.js:97-102);
166
+ // - a Workflow FunctionNode whose auth step runs again on resume stores it
167
+ // under "temp:" + credentialKey (auth_handler.js:35-38, :47), and function_node.js
168
+ // copies every new delta entry into the event it yields (:93-127). A Runner
169
+ // removes "temp:" entries from a non-partial event as it appends it to the
170
+ // session, before yielding it; a partial event, or an event read before
171
+ // that append, still carries them.
172
+ // ADK treats any value under the key as a stored credential
173
+ // (hitl_utils.js:131-133), so the entry is omitted whole: a redacted value left
174
+ // behind would read as a credential. Every "temp:" entry is omitted too
175
+ // (invocation-scoped by ADK's contract). Every other entry rides unchanged.
176
+ const ADK_TEMP_STATE_PREFIX = "temp:";
177
+ const AUTH_CREDENTIAL_TYPES: ReadonlySet<string> = new Set(["apiKey", "http", "oauth2", "openIdConnect", "serviceAccount"]);
178
+ // resourceRef (auth_credential.d.ts:244) names a stored credential: ADK's
179
+ // presence readers treat an object holding it as a held credential.
180
+ const AUTH_CREDENTIAL_MEMBERS = [
181
+ "apiKey",
182
+ "api_key",
183
+ "http",
184
+ "oauth2",
185
+ "serviceAccount",
186
+ "service_account",
187
+ "resourceRef",
188
+ "resource_ref",
189
+ ] as const;
190
+
191
+ function isObjectRecord(v: unknown): v is { readonly [k: string]: unknown } {
192
+ return v !== null && typeof v === "object" && !Array.isArray(v);
193
+ }
194
+
195
+ /** An ADK AuthCredential: `authType` (either spelling) is one of ADK's
196
+ * credential types (auth_credential.d.ts) and a credential member is present
197
+ * and non-null. */
198
+ function isAuthCredentialObject(v: { readonly [k: string]: unknown }): boolean {
199
+ const typed = ["authType", "auth_type"].some((k) => {
200
+ const t = Object.hasOwn(v, k) ? v[k] : undefined;
201
+ return typeof t === "string" && AUTH_CREDENTIAL_TYPES.has(t);
202
+ });
203
+ return typed && AUTH_CREDENTIAL_MEMBERS.some((m) => Object.hasOwn(v, m) && v[m] !== null && v[m] !== undefined);
204
+ }
205
+
206
+ /** Whether `v` is, or holds at any depth (arrays included), an ADK
207
+ * AuthCredential. Iterative and cycle-safe over the raw native value; a value
208
+ * that cannot be walked counts as holding one, so this never throws. */
209
+ export function holdsAuthCredential(v: unknown): boolean {
210
+ return holdsObject(v, isAuthCredentialObject);
211
+ }
212
+
213
+ /** Whether `v` is, or holds at any depth (arrays included), an object `match`
214
+ * accepts. Iterative and cycle-safe over the raw native value; a value that
215
+ * cannot be walked counts as holding one, so this never throws. */
216
+ function holdsObject(v: unknown, match: (o: { readonly [k: string]: unknown }) => boolean): boolean {
217
+ try {
218
+ const seen = new Set<object>();
219
+ const stack: unknown[] = [v];
220
+ while (stack.length > 0) {
221
+ const x = stack.pop();
222
+ if (x === null || typeof x !== "object" || seen.has(x)) continue;
223
+ seen.add(x);
224
+ if (Array.isArray(x)) {
225
+ for (const y of x) stack.push(y);
226
+ } else if (isObjectRecord(x)) {
227
+ if (match(x)) return true;
228
+ for (const k of Object.keys(x)) stack.push(x[k]);
229
+ }
230
+ }
231
+ return false;
232
+ } catch {
233
+ return true;
234
+ }
235
+ }
236
+
237
+ /** The state map ADK yields, minus its "temp:" entries and every entry that
238
+ * holds an ADK AuthCredential, in the original key order. A map with none of
239
+ * those is carried exactly as before. When entries were omitted, a remaining
240
+ * entry that is not JSON is dropped rather than thrown on, since a throw would
241
+ * hand the raw native event to the host's error path. A value that is not a
242
+ * map of entries (an array, a scalar, or an ADK AuthCredential itself) is
243
+ * carried as before, or as {} if it holds a credential. */
244
+ export function scrubStateMap(raw: unknown): JsonValue {
245
+ if (!isObjectRecord(raw) || isAuthCredentialObject(raw)) return holdsAuthCredential(raw) ? {} : JsonValue.parse(raw);
246
+ const keys = Object.keys(raw);
247
+ const omitted = keys.map((k) => k.startsWith(ADK_TEMP_STATE_PREFIX) || holdsAuthCredential(raw[k]));
248
+ if (!omitted.includes(true)) return JsonValue.parse(raw);
249
+ const kept: [string, JsonValue][] = [];
250
+ keys.forEach((k, i) => {
251
+ if (omitted[i] === true || isReservedMapKey(k)) return;
252
+ const parsed = JsonValue.safeParse(raw[k]);
253
+ if (parsed.success) kept.push([k, parsed.data]);
254
+ });
255
+ return Object.fromEntries(kept);
256
+ }
257
+
258
+ /** The ADK AuthConfig reduced to its non-secret members ({} for a non-object). */
259
+ export function scrubAdkAuthConfig(native: JsonValue): JsonValue {
260
+ return pickAllowed(native, AUTH_CONFIG_ALLOW) ?? {};
261
+ }
262
+
263
+ /** A reserved-credential functionResponse (the client's answer) scrubbed the
264
+ * same way; undefined when the response is not an object. */
265
+ export function scrubbedResponse(response: unknown): { readonly [k: string]: JsonValue } | undefined {
266
+ if (!isJsonObject(response)) return undefined;
267
+ const scrubbed = scrubAdkAuthConfig(response);
268
+ return isJsonObject(scrubbed) ? scrubbed : undefined;
269
+ }
270
+
271
+ // ─── provider-raw carries of node data ───────────────────────────────────────
272
+ // A Workflow event's `output` and `actions.agentState` ride verbatim in
273
+ // provider-raw. Inside them, each ADK AuthCredential (detected as for shared
274
+ // state) is reduced to its allowlisted members, and each response named
275
+ // adk_request_credential (matched by that name at any depth, never by id)
276
+ // keeps only its id, its name and the reserved-credential answer's
277
+ // allowlisted response, so an untyped reply becomes {}. Every other member
278
+ // rides unchanged. A value with neither is parsed exactly as before; a value
279
+ // that cannot be walked or reduced is omitted, never thrown on.
280
+
281
+ /** A response named adk_request_credential (a functionResponse object). */
282
+ function isCredentialRequestResponse(v: { readonly [k: string]: unknown }): boolean {
283
+ return v["name"] === ADK_REQUEST_CREDENTIAL && Object.hasOwn(v, "name") && Object.hasOwn(v, "response");
284
+ }
285
+
286
+ /** One JSON value with every credential object and credential-request
287
+ * response reduced (see above); recursion stops at a reduced unit. */
288
+ function reduceCredentialCarry(v: JsonValue): JsonValue {
289
+ if (Array.isArray(v)) return v.map(reduceCredentialCarry);
290
+ if (!isJsonObject(v)) return v;
291
+ if (isAuthCredentialObject(v)) return pickAllowed(v, AUTH_CREDENTIAL_ALLOW) ?? {};
292
+ if (isCredentialRequestResponse(v))
293
+ return pickAllowed(v, { id: true, name: true, response: (r) => scrubbedResponse(r) }) ?? {};
294
+ return Object.fromEntries(
295
+ Object.entries(v)
296
+ .filter(([k]) => !isReservedMapKey(k))
297
+ .map(([k, x]): [string, JsonValue] => [k, reduceCredentialCarry(x)]),
298
+ );
299
+ }
300
+
301
+ /** Any value the facet carries in a provider-raw block, with every ADK
302
+ * AuthCredential and every response named adk_request_credential reduced as
303
+ * for node data (see above). A value holding neither is returned unchanged;
304
+ * one that cannot be reduced is carried as {}. Never throws. */
305
+ export function reduceCarried(v: JsonValue): JsonValue {
306
+ if (!holdsAuthCredential(v) && !holdsObject(v, isCredentialRequestResponse)) return v;
307
+ try {
308
+ return reduceCredentialCarry(v);
309
+ } catch {
310
+ return {};
311
+ }
312
+ }
313
+
314
+ /** JSON with object keys in sorted order: "did the reduction change it"
315
+ * compares members, not the order an allowlist writes them in. */
316
+ function canonicalJson(v: JsonValue): string {
317
+ if (Array.isArray(v)) return `[${v.map(canonicalJson).join(",")}]`;
318
+ if (!isJsonObject(v)) return JSON.stringify(v);
319
+ return `{${Object.keys(v)
320
+ .sort()
321
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k] ?? null)}`)
322
+ .join(",")}}`;
323
+ }
324
+
325
+ /** A node-data value for a provider-raw carry. `changed` says whether the
326
+ * reduction altered it; `undefined` omits the unit. */
327
+ export function carryNodeValue(raw: unknown): { value: JsonValue; changed: boolean } | undefined {
328
+ if (!holdsAuthCredential(raw) && !holdsObject(raw, isCredentialRequestResponse))
329
+ return { value: JsonValue.parse(raw), changed: false };
330
+ try {
331
+ const before = JsonValue.parse(JSON.parse(JSON.stringify(raw)));
332
+ const value = reduceCredentialCarry(before);
333
+ return { value, changed: canonicalJson(value) !== canonicalJson(before) };
334
+ } catch {
335
+ return undefined;
336
+ }
337
+ }
338
+
339
+ /** JSON.stringify of a raw `output` whose node-data reduction changed or
340
+ * omitted it: the text ADK renders from that output. `undefined` otherwise
341
+ * (including a string output, which ADK renders as itself). */
342
+ export function changedOutputRendering(output: unknown): string | undefined {
343
+ if (output === undefined || output === null || typeof output !== "object") return undefined;
344
+ // Detection first, so an output holding neither is never parsed here.
345
+ if (!holdsAuthCredential(output) && !holdsObject(output, isCredentialRequestResponse)) return undefined;
346
+ const carried = carryNodeValue(output);
347
+ if (carried !== undefined && !carried.changed) return undefined;
348
+ try {
349
+ const rendered: unknown = JSON.stringify(output);
350
+ return typeof rendered === "string" ? rendered : undefined;
351
+ } catch {
352
+ return undefined;
353
+ }
354
+ }
355
+
356
+ /** The reserved credential call's args: its id, its message and the scrubbed
357
+ * AuthConfig. Nothing else is forwarded. */
358
+ export function scrubCredentialCallArgs(args: JsonValue): JsonValue {
359
+ return (
360
+ pickAllowed(args, {
361
+ functionCallId: true,
362
+ message: true,
363
+ authConfig: (v) => scrubAdkAuthConfig(v),
364
+ }) ?? {}
365
+ );
366
+ }
367
+
368
+ export function adkAuthConfigView(native: JsonValue): AgAuthConfig | undefined {
369
+ if (!isJsonObject(native)) return undefined;
370
+ const authScheme = native["authScheme"];
371
+ const scheme = stringMember(authScheme, "type");
372
+ if (scheme === undefined || !isJsonObject(authScheme)) return undefined;
373
+ let authorizationUrl: string | undefined;
374
+ let tokenUrl: string | undefined;
375
+ let scopes: string[] | undefined;
376
+ if ("authorizationEndpoint" in authScheme) {
377
+ authorizationUrl = stringMember(authScheme, "authorizationEndpoint");
378
+ tokenUrl = stringMember(authScheme, "tokenEndpoint");
379
+ const s = authScheme["scopes"];
380
+ if (Array.isArray(s)) scopes = s.filter((x): x is string => typeof x === "string");
381
+ } else if (scheme === "oauth2") {
382
+ const flows = authScheme["flows"];
383
+ const flow = isJsonObject(flows)
384
+ ? [flows["implicit"], flows["authorizationCode"], flows["clientCredentials"], flows["password"]].find(
385
+ isJsonObject,
386
+ )
387
+ : undefined;
388
+ if (flow !== undefined) {
389
+ authorizationUrl = stringMember(flow, "authorizationUrl");
390
+ tokenUrl = stringMember(flow, "tokenUrl");
391
+ const s = flow["scopes"];
392
+ if (isJsonObject(s)) scopes = Object.keys(s);
393
+ }
394
+ }
395
+ const raw = native["rawAuthCredential"];
396
+ const oauth2 = isJsonObject(raw) ? raw["oauth2"] : undefined;
397
+ const clientId = stringMember(oauth2, "clientId");
398
+ const audience = stringMember(oauth2, "audience");
399
+ return {
400
+ scheme,
401
+ ...(scopes !== undefined ? { scopes } : {}),
402
+ ...(authorizationUrl !== undefined ? { authorizationUrl } : {}),
403
+ ...(tokenUrl !== undefined ? { tokenUrl } : {}),
404
+ ...(clientId !== undefined ? { clientId } : {}),
405
+ ...(audience !== undefined ? { audience } : {}),
406
+ };
407
+ }