opencode-gemini-app 0.0.0-stage → 0.1.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.
Files changed (42) hide show
  1. package/DISCLAIMER.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +46 -2
  4. package/extensions/opencode/auth.js +324 -0
  5. package/extensions/opencode/fetch.js +494 -0
  6. package/extensions/opencode/index.js +27 -0
  7. package/extensions/opencode/models.js +84 -0
  8. package/extensions/pi/auth.js +215 -0
  9. package/native-wire/consumer-tool-codec.mjs +239 -0
  10. package/native-wire/oauth-loopback.mjs +175 -0
  11. package/native-wire/protobuf.mjs +133 -0
  12. package/native-wire/robin-current.mjs +172 -0
  13. package/package.json +75 -4
  14. package/src/gateway/automatic-recovery.mjs +70 -0
  15. package/src/gateway/image-download.mjs +110 -0
  16. package/src/gateway/image-upload.mjs +262 -0
  17. package/src/gateway/native-diagnostic.mjs +190 -0
  18. package/src/gateway/native-evidence.mjs +114 -0
  19. package/src/gateway/native-response-limits.mjs +8 -0
  20. package/src/gateway/native-search-citations.mjs +196 -0
  21. package/src/gateway/native-search-diagnostic.mjs +282 -0
  22. package/src/gateway/native-search-metadata.mjs +749 -0
  23. package/src/gateway/native-transport.mjs +433 -0
  24. package/src/gateway/oauth-client-defaults.mjs +12 -0
  25. package/src/gateway/oauth-identity.mjs +67 -0
  26. package/src/gateway/outbound-proxy.mjs +320 -0
  27. package/src/gateway/output-recovery.mjs +48 -0
  28. package/src/gateway/quota-failover.mjs +14 -0
  29. package/src/gateway/quota-transport.mjs +37 -0
  30. package/src/gateway/quota.mjs +181 -0
  31. package/src/gateway/soft-error.mjs +25 -0
  32. package/src/gateway/structured-output.mjs +157 -0
  33. package/src/gateway/subscription.mjs +51 -0
  34. package/src/gateway/terms.mjs +126 -0
  35. package/src/image-input.mjs +137 -0
  36. package/src/image-url.mjs +21 -0
  37. package/src/native-provider.mjs +806 -0
  38. package/src/openai-contract.mjs +576 -0
  39. package/src/openai-usage.mjs +66 -0
  40. package/src/prompt-tool-schema.mjs +391 -0
  41. package/src/responses-tool-namespaces.mjs +84 -0
  42. package/src/tool-protocol.mjs +366 -0
@@ -0,0 +1,215 @@
1
+ import { startLoopbackLogin as defaultStartLoopbackLogin, refreshNativeCredential as defaultRefreshNativeCredential } from '../../native-wire/oauth-loopback.mjs';
2
+ import { acceptGoogleMainTerms as defaultAcceptGoogleMainTerms } from '../../src/gateway/terms.mjs';
3
+ import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
4
+ import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
5
+ import { DEFAULT_OAUTH_PROFILE } from '../../src/gateway/oauth-client-defaults.mjs';
6
+
7
+ const FLEXIBLE_API_SCOPE = 'https://www.googleapis.com/auth/flexible-api';
8
+ const FALLBACK_REFRESH_SCOPES = [
9
+ 'https://www.googleapis.com/auth/assistant',
10
+ 'https://www.googleapis.com/auth/gemini',
11
+ ];
12
+
13
+ export function resolveOAuthConfig({ defaultProfile = DEFAULT_OAUTH_PROFILE, env = process.env } = {}) {
14
+ const envClientId = typeof env?.GEMINI_OAUTH_CLIENT_ID === 'string' ? env.GEMINI_OAUTH_CLIENT_ID.trim() : '';
15
+ const hasEnvClientId = envClientId.length > 0;
16
+ const clientId = hasEnvClientId
17
+ ? envClientId
18
+ : (typeof defaultProfile?.clientId === 'string' ? defaultProfile.clientId.trim() : '');
19
+ if (!clientId) {
20
+ throw new Error('OAuth client ID is not configured; set GEMINI_OAUTH_CLIENT_ID.');
21
+ }
22
+ const envClientSecret = typeof env?.GEMINI_OAUTH_CLIENT_SECRET === 'string' ? env.GEMINI_OAUTH_CLIENT_SECRET.trim() : '';
23
+ const clientSecret = hasEnvClientId
24
+ ? envClientSecret
25
+ : (envClientSecret || (typeof defaultProfile?.clientSecret === 'string' ? defaultProfile.clientSecret.trim() : ''));
26
+ const refreshScopes = Array.isArray(defaultProfile?.scopes) && defaultProfile.scopes.length > 0
27
+ ? [...defaultProfile.scopes]
28
+ : [...FALLBACK_REFRESH_SCOPES];
29
+ return {
30
+ clientId,
31
+ ...(clientSecret ? { clientSecret } : {}),
32
+ scopes: [FLEXIBLE_API_SCOPE],
33
+ refreshScopes,
34
+ port: 0,
35
+ listenHost: '127.0.0.1',
36
+ redirectHost: 'localhost',
37
+ nativeLoopback: true,
38
+ forceConsent: true,
39
+ };
40
+ }
41
+
42
+ function computeExpiresAtMs(expiresInSeconds) {
43
+ const ttlSeconds = Number.isFinite(expiresInSeconds) && expiresInSeconds > 0 ? expiresInSeconds : 3600;
44
+ return Date.now() + Math.max(60, ttlSeconds - 300) * 1000;
45
+ }
46
+
47
+ export function createGeminiOAuthAuth({
48
+ startLoopbackLogin = defaultStartLoopbackLogin,
49
+ refreshNativeCredential = defaultRefreshNativeCredential,
50
+ acceptGoogleMainTerms = defaultAcceptGoogleMainTerms,
51
+ fetchGoogleUsageInfo = defaultFetchGoogleUsageInfo,
52
+ decodeSubscription = defaultDecodeSubscription,
53
+ defaultProfile = DEFAULT_OAUTH_PROFILE,
54
+ env = process.env,
55
+ } = {}) {
56
+ async function detectSubscriptionTier(accessToken, { signal } = {}) {
57
+ try {
58
+ const { payload } = await fetchGoogleUsageInfo(accessToken, { signal, timeoutMs: 8000 });
59
+ const sub = decodeSubscription(payload);
60
+ return typeof sub?.tier === 'string' && sub.tier ? sub.tier : 'unknown';
61
+ } catch (error) {
62
+ if (signal?.aborted) throw error;
63
+ return 'unknown';
64
+ }
65
+ }
66
+ async function login(interaction) {
67
+ const config = resolveOAuthConfig({ defaultProfile, env });
68
+ const outerSignal = interaction?.signal;
69
+ if (outerSignal?.aborted) {
70
+ throw Object.assign(new Error('Login cancelled'), { code: 'LOGIN_CLOSED' });
71
+ }
72
+ const session = await startLoopbackLogin(config, { signal: outerSignal });
73
+ const manualAbort = new AbortController();
74
+ const onOuterAbort = () => manualAbort.abort(outerSignal.reason);
75
+ let tokens;
76
+ try {
77
+ outerSignal?.addEventListener('abort', onOuterAbort, { once: true });
78
+ if (outerSignal?.aborted) onOuterAbort();
79
+
80
+ const runManualPrompt = async () => {
81
+ if (typeof interaction?.prompt !== 'function') {
82
+ return new Promise(() => {});
83
+ }
84
+ while (!manualAbort.signal.aborted) {
85
+ let rawInput;
86
+ try {
87
+ rawInput = await interaction.prompt({
88
+ type: 'manual_code',
89
+ message: 'Paste the localhost redirect URL if your browser cannot reach this machine:',
90
+ placeholder: 'http://localhost:...',
91
+ signal: manualAbort.signal,
92
+ });
93
+ } catch (error) {
94
+ if (manualAbort.signal.aborted) return null;
95
+ session.close('LOGIN_CLOSED');
96
+ throw error;
97
+ }
98
+ if (manualAbort.signal.aborted) return null;
99
+ if (typeof rawInput !== 'string' || !rawInput.trim()) {
100
+ continue;
101
+ }
102
+ try {
103
+ return await session.completeCallbackUrl(rawInput);
104
+ } catch (error) {
105
+ if (error?.code === 'INVALID_CALLBACK_URL' || error?.code === 'INVALID_LOGIN_STATE') {
106
+ interaction?.notify?.({
107
+ type: 'progress',
108
+ message: 'Invalid callback URL or state; please paste the complete redirect URL.',
109
+ });
110
+ continue;
111
+ }
112
+ throw error;
113
+ }
114
+ }
115
+ return null;
116
+ };
117
+
118
+ interaction?.notify?.({
119
+ type: 'auth_url',
120
+ url: session.authorizationUrl,
121
+ instructions: 'Open the Google sign-in URL in a browser. If running over SSH/headless, paste the final localhost redirect URL below.',
122
+ });
123
+ const manualPromise = runManualPrompt();
124
+ manualPromise.catch(() => {});
125
+ tokens = await Promise.race([session.done, manualPromise]);
126
+ if (!tokens) {
127
+ tokens = await session.done;
128
+ }
129
+ } finally {
130
+ outerSignal?.removeEventListener('abort', onOuterAbort);
131
+ manualAbort.abort();
132
+ if (!tokens) {
133
+ try { session.close(); } catch {}
134
+ }
135
+ }
136
+
137
+ if (!tokens || typeof tokens.refreshToken !== 'string' || !tokens.refreshToken) {
138
+ throw new Error('Google OAuth login did not return a refresh token.');
139
+ }
140
+
141
+ interaction?.notify?.({
142
+ type: 'progress',
143
+ message: 'Exchanging scoped Gemini access token...',
144
+ });
145
+ const scoped = await refreshNativeCredential(config, tokens.refreshToken, { signal: outerSignal });
146
+
147
+ interaction?.notify?.({
148
+ type: 'progress',
149
+ message: 'Verifying Gemini Terms of Service...',
150
+ });
151
+ try {
152
+ await acceptGoogleMainTerms(scoped.accessToken, { signal: outerSignal });
153
+ } catch (error) {
154
+ if (outerSignal?.aborted) throw error;
155
+ const code = typeof error?.code === 'string' ? error.code : '';
156
+ if (!code.startsWith('TOS_')) throw error;
157
+ interaction?.notify?.({
158
+ type: 'progress',
159
+ message: `Gemini Terms of Service check deferred (${code}); sign-in succeeded.`,
160
+ });
161
+ }
162
+
163
+ interaction?.notify?.({
164
+ type: 'progress',
165
+ message: 'Checking Gemini subscription tier...',
166
+ });
167
+ const subscriptionTier = await detectSubscriptionTier(scoped.accessToken, { signal: outerSignal });
168
+ if (subscriptionTier !== 'unknown') {
169
+ interaction?.notify?.({
170
+ type: 'progress',
171
+ message:
172
+ subscriptionTier === 'free'
173
+ ? 'Detected Gemini Free account (gemini-auto enabled).'
174
+ : `Detected Gemini subscription tier: ${subscriptionTier}.`,
175
+ });
176
+ }
177
+
178
+ return {
179
+ type: 'oauth',
180
+ refresh: scoped.refreshToken || tokens.refreshToken,
181
+ access: scoped.accessToken,
182
+ expires: computeExpiresAtMs(scoped.expiresInSeconds ?? tokens.expiresInSeconds),
183
+ ...(subscriptionTier !== 'unknown' ? { subscriptionTier } : {}),
184
+ };
185
+ }
186
+
187
+ async function refresh(credential, signal) {
188
+ if (!credential || typeof credential.refresh !== 'string' || !credential.refresh) {
189
+ throw new Error('Missing OAuth refresh token.');
190
+ }
191
+ const config = resolveOAuthConfig({ defaultProfile, env });
192
+ const refreshed = await refreshNativeCredential(config, credential.refresh, { signal });
193
+ const detectedTier = await detectSubscriptionTier(refreshed.accessToken, { signal });
194
+ const subscriptionTier = detectedTier !== 'unknown' ? detectedTier : credential.subscriptionTier;
195
+ return {
196
+ ...credential,
197
+ type: 'oauth',
198
+ refresh: refreshed.refreshToken || credential.refresh,
199
+ access: refreshed.accessToken,
200
+ expires: computeExpiresAtMs(refreshed.expiresInSeconds),
201
+ ...(subscriptionTier ? { subscriptionTier } : {}),
202
+ };
203
+ }
204
+
205
+ async function toAuth(credential) {
206
+ return { apiKey: credential.access };
207
+ }
208
+
209
+ return {
210
+ name: 'Google Gemini App',
211
+ login,
212
+ refresh,
213
+ toAuth,
214
+ };
215
+ }
@@ -0,0 +1,239 @@
1
+ /** Caller-owned native tool wire codec. Pure protobuf/JSON conversion;
2
+ * zero executor, authentication, network or desktop-app I/O.
3
+ */
4
+ import crypto from 'node:crypto';
5
+ import { TextDecoder } from 'node:util';
6
+ import { parse, lengthDelimited as m, varintField as v, varint as unsignedVarint, MAX_MESSAGE_BYTES } from './protobuf.mjs';
7
+ import { buildClientGenerate, buildRequestMetadata, NATIVE_VERSION } from './robin-current.mjs';
8
+ export const TOOL_LIMITS = Object.freeze({ tools: 64, calls: 32, depth: 16, nodes: 4096, bytes: 256 * 1024, frameBytes: 1024 * 1024 });
9
+ // Native ClientCapability wire 379, distinct from in-memory enum 394 or metadata CapabilityType.
10
+ const CLIENT_TOOLS_CAPABILITY = 379;
11
+ // The proven Mac client locks BOTH the Argon mode and the deep-thinking level on
12
+ // every request. Sending mode alone was a fidelity gap, not a deliberate choice.
13
+ const ARGON_MODE_CATEGORY = 8;
14
+ const ARGON_THINKING_LEVEL = 2;
15
+ export class ConsumerToolError extends Error {
16
+ constructor(code, status = 400) { super('Native consumer tool bridge request failed'); this.name = 'ConsumerToolError'; this.code = code; this.status = status; }
17
+ }
18
+ export const rejectTool = (code, status = 400) => { throw new ConsumerToolError(code, status); };
19
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
20
+ const cat = (...parts) => Buffer.concat(parts);
21
+ const s = (n, value) => m(n, Buffer.from(value));
22
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value));
23
+ function string(value, max = TOOL_LIMITS.bytes, empty = true) {
24
+ if (typeof value !== 'string' || (!empty && !value.length) || Buffer.byteLength(value) > max || utf8.decode(Buffer.from(value)) !== value) rejectTool('INVALID_TOOL_STRING');
25
+ return value;
26
+ }
27
+ function keys(value, allowed) { if (!object(value) || Object.keys(value).some(key => !allowed.includes(key))) rejectTool('UNSUPPORTED_TOOL_SCHEMA'); }
28
+ function tick(budget, depth) { if (++budget.nodes > TOOL_LIMITS.nodes || depth > TOOL_LIMITS.depth) rejectTool('TOOL_SIZE_LIMIT'); }
29
+ const SCHEMA_ANNOTATIONS = ['\u0024schema', '\u0024id', 'title', 'default', 'examples', 'deprecated', 'readOnly', 'writeOnly', 'format'];
30
+ function schemaKeys(value, allowed) { keys(value, [...allowed, ...SCHEMA_ANNOTATIONS]); }
31
+ const types = Object.freeze({ string: 1, number: 2, integer: 3, boolean: 4, array: 5, object: 6, null: 7 });
32
+ // TypeBox/PI represents string options as anyOf string const branches.
33
+ // Only this exact enum-equivalent form is supported, not arbitrary unions.
34
+ function literalSchema(schema) {
35
+ if (!object(schema)) return schema;
36
+ if (Object.hasOwn(schema, 'anyOf')) {
37
+ schemaKeys(schema, ['anyOf', 'description', 'nullable', 'type']);
38
+ if ((schema.type !== undefined && schema.type !== 'string') || !Array.isArray(schema.anyOf) || !schema.anyOf.length || schema.anyOf.length > 128) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
39
+ const values = schema.anyOf.map(branch => {
40
+ schemaKeys(branch, ['type', 'const']);
41
+ if (branch.type !== 'string' || typeof branch.const !== 'string') rejectTool('UNSUPPORTED_TOOL_SCHEMA');
42
+ return branch.const;
43
+ });
44
+ if (new Set(values).size !== values.length) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
45
+ const { anyOf, ...rest } = schema;
46
+ return { ...rest, type: 'string', enum: values };
47
+ }
48
+ if (Object.hasOwn(schema, 'const')) {
49
+ schemaKeys(schema, ['type', 'const', 'description', 'nullable']);
50
+ if (schema.type !== 'string' || typeof schema.const !== 'string') rejectTool('UNSUPPORTED_TOOL_SCHEMA');
51
+ const { const: value, ...rest } = schema;
52
+ return { ...rest, enum: [value] };
53
+ }
54
+ return schema;
55
+ }
56
+ function schemaWire(schema, budget, depth = 0) {
57
+ tick(budget, depth);
58
+ schema = literalSchema(schema);
59
+ schemaKeys(schema, ['type', 'description', 'nullable', 'enum', 'items', 'properties', 'required', 'additionalProperties', 'minimum', 'maximum']);
60
+ if (typeof schema.type !== 'string' || !Object.hasOwn(types, schema.type)) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
61
+ // Numeric bounds are retained in the prompt/registry and enforced locally;
62
+ // no unproven native schema wire fields are invented for these constraints.
63
+ for (const key of ['minimum', 'maximum']) if (schema[key] !== undefined && (!['number', 'integer'].includes(schema.type) || typeof schema[key] !== 'number' || !Number.isFinite(schema[key]))) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
64
+ if (schema.minimum !== undefined && schema.maximum !== undefined && schema.minimum > schema.maximum) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
65
+ const out = [v(1, types[schema.type])];
66
+ if (schema.description !== undefined) out.push(s(3, string(schema.description)));
67
+ if (schema.nullable !== undefined) { if (typeof schema.nullable !== 'boolean') rejectTool('UNSUPPORTED_TOOL_SCHEMA'); out.push(v(4, Number(schema.nullable))); }
68
+ if (schema.enum !== undefined) {
69
+ if (schema.type !== 'string' || !Array.isArray(schema.enum) || !schema.enum.length || schema.enum.length > 128 || new Set(schema.enum).size !== schema.enum.length) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
70
+ for (const item of schema.enum) out.push(s(5, string(item)));
71
+ }
72
+ if (schema.type === 'array') { if (!schema.items) rejectTool('UNSUPPORTED_TOOL_SCHEMA'); out.push(m(6, schemaWire(schema.items, budget, depth + 1))); }
73
+ else if (schema.items !== undefined) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
74
+ if (schema.type === 'object') {
75
+ const props = schema.properties === undefined ? {} : schema.properties;
76
+ if (!object(props)) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
77
+ for (const [name, child] of Object.entries(props)) out.push(m(7, cat(s(1, string(name, 256, false)), m(2, schemaWire(child, budget, depth + 1)))));
78
+ if (schema.required !== undefined) {
79
+ if (!Array.isArray(schema.required) || new Set(schema.required).size !== schema.required.length) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
80
+ for (const name of schema.required) { if (typeof name !== 'string' || !Object.hasOwn(props, name)) rejectTool('UNSUPPORTED_TOOL_SCHEMA'); out.push(s(8, name)); }
81
+ }
82
+ // No guessed wire flag: this restriction is checked locally on every call.
83
+ if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
84
+ } else if (schema.properties !== undefined || schema.required !== undefined || schema.additionalProperties !== undefined) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
85
+ return Buffer.concat(out);
86
+ }
87
+ /** Current-image Beyond_Schema encoder shared by the legacy Mac facade. */
88
+ export function encodeConsumerToolSchema(schema) {
89
+ const bytes = schemaWire(schema, { nodes: 0 });
90
+ if (bytes.length > TOOL_LIMITS.bytes) rejectTool('TOOL_SIZE_LIMIT');
91
+ return bytes;
92
+ }
93
+ export function compileConsumerTools(tools = [], toolChoice = 'auto') {
94
+ if (!['auto', 'none'].includes(toolChoice)) rejectTool('UNSUPPORTED_TOOL_CHOICE');
95
+ if (!Array.isArray(tools) || tools.length > TOOL_LIMITS.tools) rejectTool('TOOL_SIZE_LIMIT');
96
+ const registry = new Map(), budget = { nodes: 0 }; let size = 0;
97
+ for (const tool of tools) {
98
+ keys(tool, ['type', 'function']); if (tool.type !== 'function') rejectTool('UNSUPPORTED_TOOL_TYPE');
99
+ const fn = tool.function; keys(fn, ['name', 'description', 'parameters', 'strict']);
100
+ if (typeof fn.name !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(fn.name) || registry.has(fn.name)) rejectTool('INVALID_TOOL_DECLARATION');
101
+ if (fn.strict !== undefined && fn.strict !== false) rejectTool('UNSUPPORTED_TOOL_SCHEMA');
102
+ const parameters = fn.parameters === undefined ? { type: 'object', properties: {} } : fn.parameters;
103
+ if (!object(parameters) || parameters.type !== 'object') rejectTool('UNSUPPORTED_TOOL_SCHEMA');
104
+ const parameterBytes = schemaWire(parameters, budget);
105
+ const declaration = cat(s(1, fn.name), ...(fn.description === undefined ? [] : [s(2, string(fn.description))]), m(3, parameterBytes));
106
+ size += declaration.length; if (size > TOOL_LIMITS.bytes) rejectTool('TOOL_SIZE_LIMIT');
107
+ registry.set(fn.name, { name: fn.name, parameters: JSON.parse(JSON.stringify(parameters)), declaration });
108
+ }
109
+ return toolChoice === 'none' ? new Map() : registry;
110
+ }
111
+ function one(bytes, number, wire = 2, required = true) {
112
+ const found = parse(bytes).filter(field => field.number === number);
113
+ if (found.length > 1 || (required && !found.length) || (found.length && found[0].wire !== wire)) rejectTool('INVALID_NATIVE_TOOL_EVENT', 502);
114
+ return found[0]?.payload;
115
+ }
116
+ function nativeText(bytes, number, max = TOOL_LIMITS.bytes, empty = false) {
117
+ try { return string(utf8.decode(one(bytes, number)), max, empty); } catch { rejectTool('INVALID_NATIVE_TOOL_EVENT', 502); }
118
+ }
119
+ function scalar(bytes) { let value = 0n; for (const [i, byte] of bytes.entries()) value |= BigInt(byte & 127) << BigInt(7 * i); if (value > BigInt(Number.MAX_SAFE_INTEGER)) rejectTool('INVALID_NATIVE_TOOL_EVENT', 502); return Number(value); }
120
+ function googleValue(bytes, budget, depth) {
121
+ tick(budget, depth); const fields = parse(bytes);
122
+ if (fields.length !== 1) rejectTool('INVALID_NATIVE_ARGUMENTS', 502);
123
+ const f = fields[0];
124
+ if (f.number === 1 && f.wire === 0 && scalar(f.payload) === 0) return null;
125
+ if (f.number === 2 && f.wire === 1) { const n = f.payload.readDoubleLE(); if (!Number.isFinite(n)) rejectTool('INVALID_NATIVE_ARGUMENTS', 502); return n; }
126
+ if (f.number === 3 && f.wire === 2) return utf8.decode(f.payload);
127
+ if (f.number === 4 && f.wire === 0) { const n = scalar(f.payload); if (n > 1) rejectTool('INVALID_NATIVE_ARGUMENTS', 502); return n === 1; }
128
+ if (f.number === 5 && f.wire === 2) return googleStruct(f.payload, budget, depth + 1);
129
+ if (f.number === 6 && f.wire === 2) return parse(f.payload).map(item => { if (item.number !== 1 || item.wire !== 2) rejectTool('INVALID_NATIVE_ARGUMENTS', 502); return googleValue(item.payload, budget, depth + 1); });
130
+ rejectTool('INVALID_NATIVE_ARGUMENTS', 502);
131
+ }
132
+ function googleStruct(bytes, budget = { nodes: 0 }, depth = 0) {
133
+ tick(budget, depth); const result = {};
134
+ for (const item of parse(bytes)) {
135
+ if (item.number !== 1 || item.wire !== 2) rejectTool('INVALID_NATIVE_ARGUMENTS', 502);
136
+ const name = nativeText(item.payload, 1, 256, true);
137
+ if (Object.hasOwn(result, name)) rejectTool('INVALID_NATIVE_ARGUMENTS', 502);
138
+ Object.defineProperty(result, name, { value: googleValue(one(item.payload, 2), budget, depth + 1), enumerable: true, writable: true, configurable: true });
139
+ }
140
+ return result;
141
+ }
142
+ function validateArguments(value, schema, depth = 0) {
143
+ if (depth > TOOL_LIMITS.depth) rejectTool('TOOL_SIZE_LIMIT');
144
+ schema = literalSchema(schema);
145
+ if (value === null && (schema.nullable || schema.type === 'null')) return;
146
+ const good = schema.type === 'object' ? object(value) : schema.type === 'array' ? Array.isArray(value) : schema.type === 'integer' ? Number.isSafeInteger(value) : schema.type === 'number' ? typeof value === 'number' && Number.isFinite(value) : schema.type === 'null' ? value === null : typeof value === schema.type;
147
+ if (!good || (schema.enum && !schema.enum.includes(value))) rejectTool('NATIVE_ARGUMENT_SCHEMA_MISMATCH', 502);
148
+ if (typeof value === 'number' && ((schema.minimum !== undefined && value < schema.minimum) || (schema.maximum !== undefined && value > schema.maximum))) rejectTool('NATIVE_ARGUMENT_SCHEMA_MISMATCH', 502);
149
+ if (schema.type === 'object') {
150
+ const props = schema.properties ?? {};
151
+ for (const key of schema.required ?? []) if (!Object.hasOwn(value, key)) rejectTool('NATIVE_ARGUMENT_SCHEMA_MISMATCH', 502);
152
+ for (const [key, child] of Object.entries(value)) {
153
+ if (Object.hasOwn(props, key)) validateArguments(child, props[key], depth + 1);
154
+ else if (schema.additionalProperties === false) rejectTool('NATIVE_ARGUMENT_SCHEMA_MISMATCH', 502);
155
+ }
156
+ }
157
+ if (schema.type === 'array') for (const item of value) validateArguments(item, schema.items, depth + 1);
158
+ }
159
+ /** Shared schema validation for already structured legacy IPC arguments. */
160
+ export function validateConsumerToolArguments(value, schema) {
161
+ validateArguments(value, schema);
162
+ }
163
+ /** PRIVATE result: operationId/functionId are never consumer-visible/loggable. */
164
+ export function decodeConsumerOperation(bytes, registry) {
165
+ if (!Buffer.isBuffer(bytes) || bytes.length > TOOL_LIMITS.frameBytes) rejectTool('TOOL_SIZE_LIMIT', 502);
166
+ const request = one(bytes, 1, 2, false), end = one(bytes, 2, 2, false);
167
+ if (request !== undefined && end !== undefined) rejectTool('INVALID_NATIVE_TOOL_EVENT', 502);
168
+ if (request === undefined) { if (end?.length === 0) return { ended: true }; rejectTool('INVALID_NATIVE_TOOL_EVENT', 502); }
169
+ const id = one(request, 1), idFields = parse(id), binary = one(id, 1);
170
+ if (idFields.length !== 1 || !binary.length || binary.length > 4096) rejectTool('INVALID_NATIVE_TOOL_EVENT', 502);
171
+ if (parse(request).some(field => field.number === 2)) rejectTool('UNSUPPORTED_OPERATION_DEPENDENCIES', 502);
172
+ const skip = one(request, 4, 0, false);
173
+ if (skip && scalar(skip) !== 0) rejectTool('UNSUPPORTED_SKIP_RESULTS', 502);
174
+ const calls=decodeClientFunctionCallArgs(one(one(request,3),1082),registry);
175
+ return { ended:false,operationId:Buffer.from(id),calls };
176
+ }
177
+ /** PRIVATE common payload for ProcessQuery and Notify; never log returned IDs/args. */
178
+ export function decodeClientFunctionCallArgs(bytes,registry){
179
+ if(!Buffer.isBuffer(bytes)||bytes.length>TOOL_LIMITS.frameBytes)rejectTool('TOOL_SIZE_LIMIT',502);
180
+ const callFields=parse(bytes);
181
+ if(!callFields.length||callFields.length>TOOL_LIMITS.calls||callFields.some(field=>field.number!==1||field.wire!==2))rejectTool('INVALID_NATIVE_TOOL_EVENT',502);
182
+ const ids=new Set();
183
+ return callFields.map(field=>{
184
+ const name=nativeText(field.payload,1,64),functionId=nativeText(field.payload,2,4096);
185
+ if(!registry.has(name))rejectTool('UNDECLARED_NATIVE_TOOL',502);
186
+ if(ids.has(functionId))rejectTool('DUPLICATE_NATIVE_TOOL_ID',502);ids.add(functionId);
187
+ const argumentsValue=googleStruct(one(field.payload,3,2,false)??Buffer.alloc(0));
188
+ validateArguments(argumentsValue,registry.get(name).parameters);
189
+ const argumentsJson=JSON.stringify(argumentsValue);
190
+ if(Buffer.byteLength(argumentsJson)>TOOL_LIMITS.bytes)rejectTool('TOOL_SIZE_LIMIT',502);
191
+ return {name,functionId,argumentsJson};
192
+ });
193
+ }
194
+ function sequence(value) { if (!Number.isSafeInteger(value) || value < 1 || value > 0x7fffffff) rejectTool('INVALID_TURN_SEQUENCE'); return v(1, value); }
195
+ /** Standard role:tool content is encoded verbatim as Beyond_Struct { output: string }
196
+ * using Beyond Value string field 3.
197
+ */
198
+ export function encodeConsumerResults(operation, contents, turnSequence) {
199
+ if(!operation||operation.ended||!Buffer.isBuffer(operation.operationId))rejectTool('INVALID_TOOL_RESULTS');
200
+ const responses=encodeClientFunctionCallResult(operation.calls,contents);
201
+ const result=cat(m(1,operation.operationId),m(2,m(1,m(1002,responses))));
202
+ return cat(sequence(turnSequence),m(1011,m(1,result)));
203
+ }
204
+ /** PRIVATE common result; names/IDs are copied from a decoded call, never minted. */
205
+ export function encodeClientFunctionCallResult(calls,contents){
206
+ if(!Array.isArray(calls)||!calls.length||calls.length>TOOL_LIMITS.calls||!Array.isArray(contents)||contents.length!==calls.length)rejectTool('INVALID_TOOL_RESULTS');
207
+ const ids=new Set();
208
+ return cat(...calls.map((call,i)=>{
209
+ const name=string(call?.name,64,false),functionId=string(call?.functionId,4096,false);
210
+ if(ids.has(functionId))rejectTool('INVALID_TOOL_RESULTS');ids.add(functionId);
211
+ return m(1,cat(s(1,name),s(2,functionId),m(3,m(1,cat(s(1,'output'),m(2,s(3,string(contents[i]))))))));
212
+ }));
213
+ }
214
+ export const encodeConsumerResultsEnd = turnSequence => cat(sequence(turnSequence), m(1011, m(2, Buffer.alloc(0))));
215
+ export function buildConsumerToolInitial({ userText, images = [], systemText, tools = [], toolChoice = 'auto', turnSequence = 1, clientMetadata, identifiers, continuation, agentChat = false, clientToolsFeature = false, operationFeature = true, halfCloseFeature = false, localSession = false, clientToolsCapability = false, clientFunctionCapabilities = false, ownedDeviceId, modeCategory, thinkingLevel = ARGON_THINKING_LEVEL, temporaryChat = true, allowNativeTools = false, smartModelSelection = false } = {}, { maxInputBytes = TOOL_LIMITS.bytes } = {}) {
216
+ if (!Number.isSafeInteger(maxInputBytes) || maxInputBytes < 1 || maxInputBytes > MAX_MESSAGE_BYTES) rejectTool('INVALID_NATIVE_INPUT_LIMIT');
217
+ string(userText, maxInputBytes); if (systemText !== undefined) string(systemText); if (typeof allowNativeTools !== 'boolean') rejectTool('INVALID_NATIVE_TOOLS_PERMISSION'); if (allowNativeTools && tools.length) rejectTool('NATIVE_TOOLS_WITH_DECLARATIONS'); if (typeof agentChat !== 'boolean') rejectTool('INVALID_AGENT_CONTEXT'); if (typeof clientToolsFeature !== 'boolean') rejectTool('INVALID_CLIENT_TOOLS_FEATURE'); if (typeof operationFeature !== 'boolean') rejectTool('INVALID_OPERATION_FEATURE'); if (typeof halfCloseFeature !== 'boolean') rejectTool('INVALID_HALF_CLOSE_FEATURE'); if (typeof localSession !== 'boolean') rejectTool('INVALID_LOCAL_SESSION'); if (typeof clientToolsCapability !== 'boolean') rejectTool('INVALID_CLIENT_TOOLS_CAPABILITY'); if (typeof clientFunctionCapabilities !== 'boolean') rejectTool('INVALID_CLIENT_FUNCTION_CAPABILITIES');
218
+ if (typeof smartModelSelection !== 'boolean') rejectTool('INVALID_SMART_MODEL_SELECTION');
219
+ if (allowNativeTools && (!Array.isArray(images) || images.length)) rejectTool('NATIVE_SEARCH_IMAGES_UNSUPPORTED');
220
+ if(ownedDeviceId!==undefined&&(typeof ownedDeviceId!=='string'||!/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/.test(ownedDeviceId)))rejectTool('INVALID_OWNED_DEVICE_ID');if(ownedDeviceId!==undefined&&!localSession)rejectTool('OWNED_DEVICE_REQUIRES_LOCAL_SESSION');
221
+ const registry = compileConsumerTools(tools, toolChoice);if(localSession&&!registry.size)rejectTool('LOCAL_TOOLS_REQUIRED');if((clientToolsCapability||clientFunctionCapabilities)&&!registry.size)rejectTool('TOOL_CAPABILITY_REQUIRES_DECLARATIONS');
222
+ if (halfCloseFeature && (!registry.size || !clientToolsFeature)) rejectTool('HALF_CLOSE_REQUIRES_CLIENT_TOOLS');
223
+ if (!operationFeature && (!registry.size || !clientToolsFeature)) rejectTool('OPERATION_OMISSION_REQUIRES_CLIENT_TOOLS');
224
+ if (halfCloseFeature && !operationFeature) rejectTool('HALF_CLOSE_REQUIRES_OPERATION_FEATURE');
225
+ const metadata = { ...(clientMetadata ?? { clientType: 21, languageCode: 'en', interfaceLanguageCode: 'en', clientVersion: NATIVE_VERSION, clientInstanceId: crypto.randomUUID(), triggerType: 1, uiSource: 1 }), clientFunctionCapabilities };
226
+ const omitThinking = smartModelSelection && thinkingLevel === null;
227
+ if (!omitThinking && (!Number.isSafeInteger(thinkingLevel) || thinkingLevel < 0 || thinkingLevel > 4)) rejectTool('INVALID_THINKING_LEVEL');
228
+ if (typeof temporaryChat !== 'boolean') rejectTool('INVALID_TEMPORARY_CHAT');
229
+ const base = buildClientGenerate({ userText, images, systemText, identifiers, clientMetadata: metadata, temporaryChat, smartModelSelection });
230
+ const desktopInfo = cat(...[...registry.values()].map(tool => m(2, tool.declaration)), ...(ownedDeviceId===undefined?[]:[s(6,ownedDeviceId)]), ...(clientToolsCapability ? [m(7, unsignedVarint(CLIENT_TOOLS_CAPABILITY))] : []));
231
+ const omitMode = smartModelSelection && (modeCategory === undefined || modeCategory === null);
232
+ const requestedMode = omitMode ? null : (modeCategory === undefined ? ARGON_MODE_CATEGORY : modeCategory);
233
+ if (!omitMode && (!Number.isSafeInteger(requestedMode) || requestedMode < 0 || requestedMode > 255)) rejectTool('INVALID_MODE_CATEGORY');
234
+ const template = cat(...parse(base).map(field => field.number === 15 ? v(15, registry.size || allowNativeTools ? 0 : 1) : field.raw), ...(omitMode ? [] : [v(47, requestedMode)]), ...(omitThinking ? [] : [v(48, thinkingLevel)]), ...(agentChat ? [v(49, 1)] : []), ...(registry.size ? [m(51, cat(...(ownedDeviceId===undefined?[]:[s(1,ownedDeviceId)]),m(3, desktopInfo), ...(localSession ? [v(5, 1)] : [])))] : []));
235
+ if (continuation !== undefined && !Buffer.isBuffer(continuation)) rejectTool('INVALID_OWN_CONTINUATION');
236
+ // Proven empty InitialRequest.ext1013 marker; NOT an outer update carrier or declaration list.
237
+ const initial = cat(m(1, buildRequestMetadata(metadata)), ...(continuation === undefined ? [] : [m(6, continuation)]), m(1001, m(1, template)), m(1004, Buffer.alloc(0)), ...(registry.size && operationFeature ? [m(1009, Buffer.alloc(0))] : []), ...(halfCloseFeature ? [m(1010, Buffer.alloc(0))] : []), ...(clientToolsFeature ? [m(1013, Buffer.alloc(0))] : []));
238
+ return cat(sequence(turnSequence), m(1000, initial));
239
+ }
@@ -0,0 +1,175 @@
1
+ /** Standard OAuth 2.0 loopback/PKCE primitives for Google account sign-in and refresh.
2
+ * Zero preset client IDs, copied credentials, desktop-app IPC or account-store I/O.
3
+ */
4
+ import http from 'node:http';
5
+ import crypto from 'node:crypto';
6
+ import { fetchWithProxy } from '../src/gateway/outbound-proxy.mjs';
7
+
8
+ const AUTH = 'https://accounts.google.com/o/oauth2/auth';
9
+ const TOKEN = 'https://oauth2.googleapis.com/token';
10
+ const NATIVE_TOKEN = 'https://www.googleapis.com/oauth2/v4/token';
11
+ function safeEqual(a, b) {
12
+ const left = Buffer.from(a || ''), right = Buffer.from(b || '');
13
+ return left.length === right.length && crypto.timingSafeEqual(left, right);
14
+ }
15
+ function validateConfig({ clientId, scopes, refreshScopes, redirectHost, listenHost, nativeLoopback }) {
16
+ if (typeof clientId !== 'string' || !/^[0-9]+-[a-z0-9]+\.apps\.googleusercontent\.com$/.test(clientId)) throw new Error('Invalid explicit OAuth client ID');
17
+ if (!Array.isArray(scopes) || !scopes.length || scopes.some(scope => typeof scope !== 'string' || /\s/.test(scope))) throw new Error('Explicit scopes required');
18
+ if (refreshScopes !== undefined && (!Array.isArray(refreshScopes) || !refreshScopes.length || refreshScopes.some(scope => typeof scope !== 'string' || /\s/.test(scope)))) throw new Error('Invalid explicit refresh scopes');
19
+ if (redirectHost !== undefined && !['localhost','127.0.0.1'].includes(redirectHost)) throw new Error('Redirect must be loopback');
20
+ if (listenHost !== undefined && !['127.0.0.1','0.0.0.0'].includes(listenHost)) throw new Error('Unsupported bind address');
21
+ if (nativeLoopback !== undefined && typeof nativeLoopback !== 'boolean') throw new Error('Invalid native mode');
22
+ }
23
+ async function tokenRequest(body, config, { fetchImpl = fetchWithProxy, timeoutMs = 12_000, signal } = {}) {
24
+ const boundedSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
25
+ const response = await fetchImpl(config.nativeLoopback ? NATIVE_TOKEN : TOKEN, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, redirect: 'error', signal: boundedSignal });
26
+ let data;
27
+ try { data = await response.json(); } catch { throw new Error(`OAuth token response invalid (HTTP ${response.status})`); }
28
+ if (!response.ok || typeof data.access_token !== 'string') {
29
+ // Never echo token endpoint bodies: they can contain credentials or account data.
30
+ const allowed = new Set(['invalid_grant','invalid_client','unauthorized_client','invalid_scope','access_denied']);
31
+ const error = new Error(`OAuth exchange rejected (HTTP ${response.status})`);
32
+ error.code = allowed.has(data?.error) ? data.error : 'OAUTH_REJECTED';
33
+ throw error;
34
+ }
35
+ return { accessToken: data.access_token, refreshToken: typeof data.refresh_token === 'string' ? data.refresh_token : null,
36
+ expiresInSeconds: Number.isFinite(Number(data.expires_in)) ? Number(data.expires_in) : null,
37
+ scope: typeof data.scope === 'string' ? data.scope : null };
38
+ }
39
+
40
+ export async function startLoopbackLogin(config, dependencies = {}) {
41
+ validateConfig(config);
42
+ const tokenController = new AbortController();
43
+ const tokenDependencies = { ...dependencies, signal: dependencies.signal ? AbortSignal.any([dependencies.signal, tokenController.signal]) : tokenController.signal };
44
+ const verifier = crypto.randomBytes(32).toString('base64url');
45
+ const state = crypto.randomBytes(32).toString('base64url');
46
+ const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
47
+ const callbackPath = config.nativeLoopback ? '/' : '/oauth/callback';
48
+ let used = false, timer, resolveDone, rejectDone;
49
+ const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
50
+ // Avoid unhandled-rejection warnings if the user closes before awaiting done.
51
+ done.catch(() => {});
52
+ const server = http.createServer(async (req, res) => {
53
+ let consumed = false;
54
+ try {
55
+ res.setHeader('Cache-Control', 'no-store'); res.setHeader('Referrer-Policy', 'no-referrer');
56
+ const url = new URL(req.url, 'http://127.0.0.1');
57
+ if (req.method !== 'GET' || url.pathname !== callbackPath) { res.writeHead(404); res.end(); return; }
58
+ if (used || !safeEqual(url.searchParams.get('state'), state)) { res.writeHead(400); res.end('Invalid or expired login state.'); return; }
59
+ // close() alone does not drain browser preconnects without an HTTP request.
60
+ // Wait until the callback response is flushed before closing all owned peers.
61
+ res.once('finish', () => server.closeAllConnections());
62
+ const code = url.searchParams.get('code');
63
+ if (url.searchParams.has('error') || !code) {
64
+ used = consumed = true; res.writeHead(400); res.end('Login was not completed.');
65
+ clearTimeout(timer); server.close(); rejectDone(Object.assign(new Error('User login not completed'), { code: 'LOGIN_DECLINED' })); return;
66
+ }
67
+ used = consumed = true;
68
+ try {
69
+ const body = new URLSearchParams({ grant_type: 'authorization_code', client_id: config.clientId, redirect_uri: redirectUri, code, code_verifier: verifier });
70
+ if (config.clientSecret) body.set('client_secret', config.clientSecret);
71
+ const tokens = await tokenRequest(body, config, tokenDependencies);
72
+ if (tokenController.signal.aborted) return;
73
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
74
+ res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'");
75
+ res.end('<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Google sign-in complete</title><h1>Google sign-in completed</h1><p>Return to the application to finish the remaining setup. You can keep this tab open or close it manually.</p><p lang="zh-HK">Google 登入已完成。請返回管理台查看其餘設定結果;你可以保留或手動關閉此分頁。</p></html>');
76
+ resolveDone(tokens);
77
+ } catch (error) {
78
+ if (!res.destroyed) { res.writeHead(400); res.end('Token exchange was rejected; no credentials were saved.'); } rejectDone(error);
79
+ } finally { clearTimeout(timer); server.close(); }
80
+ } catch {
81
+ // Invalid requests must neither escape this async listener nor cancel
82
+ // another request's valid, already-running credential exchange.
83
+ if (!res.destroyed) {
84
+ if (res.headersSent) res.destroy();
85
+ else { res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8', Connection: 'close' }); res.end('Invalid login request.'); }
86
+ }
87
+ if (consumed) {
88
+ tokenController.abort(); clearTimeout(timer); server.close();
89
+ rejectDone(Object.assign(new Error('Login callback failed.'), { code: 'LOGIN_CALLBACK_ERROR' }));
90
+ }
91
+ }
92
+ });
93
+ await new Promise((resolve, reject) => {
94
+ server.once('error', reject); server.listen(config.port ?? 0, config.listenHost ?? '127.0.0.1', resolve);
95
+ });
96
+ const redirectUri = `http://${config.redirectHost ?? '127.0.0.1'}:${server.address().port}${config.nativeLoopback ? '' : callbackPath}`;
97
+ const url = new URL(AUTH);
98
+ url.search = new URLSearchParams({ client_id: config.clientId, redirect_uri: redirectUri, response_type: 'code', scope: config.scopes.join(' '), access_type: 'offline', state, code_challenge: challenge, code_challenge_method: 'S256' }).toString();
99
+ if (config.forceConsent) url.searchParams.set('prompt', 'consent');
100
+ function close(code = 'LOGIN_CLOSED') {
101
+ used = true; tokenController.abort(); clearTimeout(timer); server.closeAllConnections(); server.close();
102
+ rejectDone(Object.assign(new Error('Login closed or timed out'), { code }));
103
+ }
104
+ async function completeCallbackUrl(rawInput) {
105
+ if (typeof rawInput !== 'string' || !rawInput.length || rawInput.length > 4096) {
106
+ throw Object.assign(new Error('Invalid callback URL'), { code: 'INVALID_CALLBACK_URL' });
107
+ }
108
+ let parsed;
109
+ try {
110
+ const trimmed = rawInput.trim();
111
+ if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
112
+ parsed = new URL(trimmed);
113
+ } else {
114
+ const queryIndex = trimmed.indexOf('?');
115
+ const query = queryIndex >= 0 ? trimmed.slice(queryIndex) : '?' + trimmed;
116
+ parsed = new URL(query, 'http://127.0.0.1');
117
+ }
118
+ } catch {
119
+ throw Object.assign(new Error('Invalid callback URL format'), { code: 'INVALID_CALLBACK_URL' });
120
+ }
121
+ if (used) {
122
+ throw Object.assign(new Error('Login already completed or closed'), { code: 'LOGIN_ALREADY_USED' });
123
+ }
124
+ const paramState = parsed.searchParams.get('state');
125
+ if (!safeEqual(paramState, state)) {
126
+ throw Object.assign(new Error('Invalid or expired login state'), { code: 'INVALID_LOGIN_STATE' });
127
+ }
128
+ const code = parsed.searchParams.get('code');
129
+ if (parsed.searchParams.has('error')) {
130
+ used = true; clearTimeout(timer);
131
+ try { server.closeAllConnections(); } catch {}
132
+ server.close();
133
+ const declError = Object.assign(new Error('User login not completed'), { code: 'LOGIN_DECLINED' });
134
+ rejectDone(declError);
135
+ throw declError;
136
+ }
137
+ if (!code) {
138
+ throw Object.assign(new Error('Callback URL is missing authorization code'), { code: 'INVALID_CALLBACK_URL' });
139
+ }
140
+ used = true;
141
+ try {
142
+ const body = new URLSearchParams({ grant_type: 'authorization_code', client_id: config.clientId, redirect_uri: redirectUri, code, code_verifier: verifier });
143
+ if (config.clientSecret) body.set('client_secret', config.clientSecret);
144
+ const tokens = await tokenRequest(body, config, tokenDependencies);
145
+ if (tokenController.signal.aborted) throw Object.assign(new Error('Login aborted'), { code: 'LOGIN_ABORTED' });
146
+ clearTimeout(timer);
147
+ try { server.closeAllConnections(); } catch {}
148
+ server.close();
149
+ resolveDone(tokens);
150
+ return tokens;
151
+ } catch (error) {
152
+ clearTimeout(timer);
153
+ try { server.closeAllConnections(); } catch {}
154
+ server.close();
155
+ rejectDone(error);
156
+ throw error;
157
+ }
158
+ }
159
+ const abort = () => close();
160
+ dependencies.signal?.addEventListener('abort', abort, { once: true });
161
+ const cleanup = () => dependencies.signal?.removeEventListener('abort', abort);
162
+ done.then(cleanup, cleanup);
163
+ timer = setTimeout(() => close('LOGIN_TIMEOUT'), config.loginTimeoutMs ?? 10 * 60 * 1000);
164
+ if (dependencies.signal?.aborted) close();
165
+ return { authorizationUrl: url.href, redirectUri, done, close, completeCallbackUrl };
166
+ }
167
+
168
+ export async function refreshNativeCredential(config, refreshToken, dependencies = {}) {
169
+ validateConfig(config);
170
+ if (typeof refreshToken !== 'string' || !refreshToken) throw new Error('Explicit refresh credential required');
171
+ const body = new URLSearchParams({ grant_type: 'refresh_token', client_id: config.clientId, refresh_token: refreshToken });
172
+ if (config.clientSecret) body.set('client_secret', config.clientSecret);
173
+ if (config.refreshScopes) body.set('scope', config.refreshScopes.join(' '));
174
+ return tokenRequest(body, config, dependencies);
175
+ }