@qvac/core 0.3.1 → 0.3.3

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 (61) hide show
  1. package/README.md +4 -4
  2. package/dist-lib/lib/assistant/history.d.ts +10 -1
  3. package/dist-lib/lib/assistant/history.js +36 -1
  4. package/dist-lib/lib/assistant/message.d.ts +2 -0
  5. package/dist-lib/lib/assistant/message.js +11 -0
  6. package/dist-lib/lib/assistant/skill-encode.js +27 -1
  7. package/dist-lib/lib/assistant.d.ts +5 -2
  8. package/dist-lib/lib/assistant.js +41 -8
  9. package/dist-lib/lib/core/chat-activity.js +2 -8
  10. package/dist-lib/lib/core/skill-secrets.js +3 -6
  11. package/dist-lib/lib/core.d.ts +1 -0
  12. package/dist-lib/lib/core.js +51 -9
  13. package/dist-lib/lib/credential-pusher.d.ts +2 -3
  14. package/dist-lib/lib/credential-pusher.js +67 -39
  15. package/dist-lib/lib/integrations/index.d.ts +1 -2
  16. package/dist-lib/lib/integrations/index.js +0 -1
  17. package/dist-lib/lib/integrations/setup-routes.js +0 -15
  18. package/dist-lib/lib/oauth/flow-core.js +1 -1
  19. package/dist-lib/lib/oauth/flow.d.ts +4 -2
  20. package/dist-lib/lib/oauth/flow.js +3 -4
  21. package/dist-lib/lib/oauth/host.d.ts +3 -1
  22. package/dist-lib/lib/oauth/host.js +3 -1
  23. package/dist-lib/lib/oauth/keys.d.ts +21 -20
  24. package/dist-lib/lib/oauth/keys.js +59 -85
  25. package/dist-lib/lib/oauth/loopback.d.ts +2 -2
  26. package/dist-lib/lib/oauth/loopback.js +32 -19
  27. package/dist-lib/lib/oauth/loopback.stub.d.ts +2 -2
  28. package/dist-lib/lib/oauth/loopback.stub.js +2 -2
  29. package/dist-lib/lib/oauth/providers.d.ts +3 -5
  30. package/dist-lib/lib/oauth/providers.js +20 -67
  31. package/dist-lib/lib/oauth/redirect-types.d.ts +1 -0
  32. package/dist-lib/lib/oauth/registry.d.ts +10 -0
  33. package/dist-lib/lib/oauth/registry.js +25 -0
  34. package/dist-lib/lib/oauth/resolve.js +1 -1
  35. package/dist-lib/lib/oauth/token-exchange-core.js +2 -1
  36. package/dist-lib/lib/oauth/types.d.ts +1 -1
  37. package/dist-lib/lib/oauth.client.d.ts +3 -1
  38. package/dist-lib/lib/oauth.client.js +3 -1
  39. package/dist-lib/lib/oauth.d.ts +4 -7
  40. package/dist-lib/lib/oauth.js +4 -7
  41. package/dist-lib/lib/skill-types.d.ts +12 -0
  42. package/dist-lib/schema/engine.js +21 -1
  43. package/dist-lib/spec/hrpc/messages.js +114 -5
  44. package/dist-lib/spec/hyperschema/index.js +114 -5
  45. package/dist-lib/spec/hyperschema/schema.json +84 -1
  46. package/dist-lib/spec/hyperschema/types.d.ts +18 -1
  47. package/package.json +4 -4
  48. package/tui/app.mjs +98 -155
  49. package/tui/lib/save-file.mjs +1 -1
  50. package/dist-lib/lib/integrations/oauth-providers.d.ts +0 -14
  51. package/dist-lib/lib/integrations/oauth-providers.js +0 -116
  52. package/dist-lib/lib/oauth/asana.d.ts +0 -35
  53. package/dist-lib/lib/oauth/asana.js +0 -71
  54. package/dist-lib/lib/oauth/google.d.ts +0 -37
  55. package/dist-lib/lib/oauth/google.js +0 -77
  56. package/dist-lib/lib/oauth/notion.d.ts +0 -34
  57. package/dist-lib/lib/oauth/notion.js +0 -82
  58. package/dist-lib/lib/oauth/spotify.d.ts +0 -32
  59. package/dist-lib/lib/oauth/spotify.js +0 -74
  60. package/dist-lib/lib/oauth/verify.d.ts +0 -8
  61. package/dist-lib/lib/oauth/verify.js +0 -58
@@ -1,18 +1,12 @@
1
1
  import { OBSIDIAN_VAULT_PATH_CREDENTIAL_KEY } from './obsidian-key.js';
2
- import { resolveAsanaCredential, resolveGoogleCredential, resolveNotionCredential, resolveSpotifyCredential, scopedKey } from './oauth.js';
3
- import { OAUTH_KEY_SPECS, oauthStateKeyFor as specStateKeyFor } from './oauth/keys.js';
2
+ import { scopedKey } from './oauth.js';
3
+ import { oauthSpecs } from './oauth/registry.js';
4
+ import { resolveOAuthCredential } from './oauth/resolve.js';
5
+ import { buildProviderConfig } from './oauth/providers.js';
6
+ import { refreshOAuthTokens } from './oauth/token-exchange.js';
4
7
  import ScopeLock from 'scope-lock';
5
8
  import { credentialSlots } from '@qvac/harness/lib/tools/skills/credential-slots.ts';
6
9
  import { REFRESH_SKEW_MS } from './oauth/common.js';
7
- const RESOLVE_BY_PROVIDER = {
8
- google: resolveGoogleCredential,
9
- spotify: resolveSpotifyCredential,
10
- notion: resolveNotionCredential,
11
- asana: resolveAsanaCredential
12
- };
13
- export function oauthStateKeyFor(credentialKey) {
14
- return specStateKeyFor(credentialKey);
15
- }
16
10
  const PLAIN_KEYS = ['github_access_token', OBSIDIAN_VAULT_PATH_CREDENTIAL_KEY];
17
11
  const REFRESH_INTERVAL = 10 * 60 * 1000;
18
12
  const MIN_REFRESH_DELAY = 30_000;
@@ -31,9 +25,16 @@ export function nextRefreshDelay(entries, now = Date.now()) {
31
25
  return REFRESH_INTERVAL;
32
26
  return Math.min(REFRESH_INTERVAL, Math.max(MIN_REFRESH_DELAY, nearest - now - REFRESH_SKEW_MS));
33
27
  }
34
- async function oauthEntry(engine, { credentialKey, stateKey, provider }, agentId) {
35
- const resolve = RESOLVE_BY_PROVIDER[provider];
36
- const token = await resolve({ engine, agentId, credentialKey, stateKey });
28
+ async function oauthEntry(engine, spec, agentId) {
29
+ const { credentialKey, stateKey } = spec;
30
+ const token = await resolveOAuthCredential({
31
+ engine,
32
+ agentId,
33
+ credentialKey,
34
+ stateKey,
35
+ requireClientSecret: spec.tokenAuth !== 'pkce-only',
36
+ refresh: (args) => refreshOAuthTokens(buildProviderConfig(spec, { clientId: args.clientId, clientSecret: args.clientSecret }), args.refreshToken)
37
+ });
37
38
  if (!token)
38
39
  return null;
39
40
  const { value } = await engine.configGet({
@@ -92,16 +93,13 @@ export function settingFields(catalog) {
92
93
  export function settingConfigKey(agentId, skill, key) {
93
94
  return scopedKey(agentId, `settings.${skill}.${key}`);
94
95
  }
95
- export function oauthStateKey(credentialKey) {
96
- return specStateKeyFor(credentialKey) ?? undefined;
97
- }
98
96
  function fanOut(entry, owners) {
99
97
  const skills = owners.get(entry.key) ?? [];
100
98
  return skills.length > 0 ? skills.map((skill) => ({ ...entry, skill })) : [entry];
101
99
  }
102
- async function resolveScope(engine, agentId, last, owners, logger) {
100
+ async function resolveScope(engine, agentId, last, owners, specs, logger) {
103
101
  const entries = [];
104
- for (const spec of OAUTH_KEY_SPECS) {
102
+ for (const spec of specs) {
105
103
  const mk = storeKey(spec.credentialKey, agentId);
106
104
  try {
107
105
  const entry = await oauthEntry(engine, spec, agentId);
@@ -120,7 +118,10 @@ async function resolveScope(engine, agentId, last, owners, logger) {
120
118
  entries.push(...fanOut(kept, owners));
121
119
  }
122
120
  }
121
+ const specKeys = new Set(specs.map((spec) => spec.credentialKey));
123
122
  for (const key of PLAIN_KEYS) {
123
+ if (specKeys.has(key))
124
+ continue;
124
125
  const mk = storeKey(key, agentId);
125
126
  try {
126
127
  const entry = await plainEntry(engine, key, agentId);
@@ -166,10 +167,48 @@ async function resolveSettings(engine, scopes, catalog, logger) {
166
167
  }
167
168
  export function startCredentialPusher(harness, engine, logger) {
168
169
  const last = new Map();
169
- const watches = [];
170
+ const watches = new Map();
170
171
  let disposed = false;
171
172
  let timer = null;
172
173
  const pushLock = new ScopeLock({ debounce: true });
174
+ const watch = (key) => {
175
+ const stream = engine.configWatch({ key: scopedKey(undefined, key) });
176
+ watches.set(key, stream);
177
+ (async () => {
178
+ for await (const _ of stream)
179
+ schedule();
180
+ if (disposed || watches.get(key) !== stream)
181
+ return;
182
+ logger?.warn('credential-pusher', `credential watch ended for ${key}, change propagation degrades to the interval until restart`);
183
+ })().catch((err) => {
184
+ if (disposed || watches.get(key) !== stream)
185
+ return;
186
+ logger?.warn('credential-pusher', `credential watch ended for ${key}`, errorMessage(err));
187
+ });
188
+ };
189
+ const syncWatches = (oauthKeys) => {
190
+ if (disposed)
191
+ return;
192
+ const wanted = new Set([...oauthKeys, ...PLAIN_KEYS]);
193
+ for (const [key, stream] of watches) {
194
+ if (wanted.has(key))
195
+ continue;
196
+ try {
197
+ stream.destroy();
198
+ }
199
+ catch { }
200
+ watches.delete(key);
201
+ }
202
+ for (const key of wanted) {
203
+ if (!watches.has(key))
204
+ watch(key);
205
+ }
206
+ for (const mk of last.keys()) {
207
+ const key = mk.includes('\0') ? mk.slice(mk.indexOf('\0') + 1) : mk;
208
+ if (!wanted.has(key))
209
+ last.delete(mk);
210
+ }
211
+ };
173
212
  const armTimer = (delay) => {
174
213
  if (disposed)
175
214
  return;
@@ -188,18 +227,22 @@ export function startCredentialPusher(harness, engine, logger) {
188
227
  }
189
228
  catch (err) {
190
229
  logger?.warn('credential-pusher', 'skill catalog read failed', errorMessage(err));
191
- return [];
230
+ return null;
192
231
  }
193
232
  };
194
233
  const pushAll = async () => {
195
234
  const entries = [];
196
235
  try {
197
236
  const skills = await catalog();
237
+ if (skills === null)
238
+ return;
198
239
  const owners = credentialOwners(skills);
240
+ const specs = oauthSpecs(skills);
241
+ syncWatches(specs.map((spec) => spec.credentialKey));
199
242
  const ids = (await engine.listAgents({})).agents.map((agent) => agent.id);
200
243
  const scopes = [undefined, ...ids];
201
244
  for (const agentId of scopes) {
202
- entries.push(...(await resolveScope(engine, agentId, last, owners, logger)));
245
+ entries.push(...(await resolveScope(engine, agentId, last, owners, specs, logger)));
203
246
  }
204
247
  if (disposed)
205
248
  return;
@@ -250,22 +293,6 @@ export function startCredentialPusher(harness, engine, logger) {
250
293
  pushLock.unlock();
251
294
  }
252
295
  };
253
- const watchKeys = [...OAUTH_KEY_SPECS.map((s) => s.credentialKey), ...PLAIN_KEYS];
254
- for (const key of watchKeys) {
255
- const stream = engine.configWatch({ key: scopedKey(undefined, key) });
256
- watches.push(stream);
257
- (async () => {
258
- for await (const _ of stream)
259
- schedule();
260
- if (disposed)
261
- return;
262
- logger?.warn('credential-pusher', `credential watch ended for ${key}, change propagation degrades to the interval until restart`);
263
- })().catch((err) => {
264
- if (disposed)
265
- return;
266
- logger?.warn('credential-pusher', `credential watch ended for ${key}`, errorMessage(err));
267
- });
268
- }
269
296
  schedule();
270
297
  const stop = async () => {
271
298
  if (disposed)
@@ -274,12 +301,13 @@ export function startCredentialPusher(harness, engine, logger) {
274
301
  if (timer)
275
302
  clearTimeout(timer);
276
303
  timer = null;
277
- for (const stream of watches) {
304
+ for (const stream of watches.values()) {
278
305
  try {
279
306
  stream.destroy();
280
307
  }
281
308
  catch { }
282
309
  }
310
+ watches.clear();
283
311
  pushLock.destroy();
284
312
  await pushLock.flush();
285
313
  };
@@ -1,4 +1,3 @@
1
- export type { SkillSetup, SkillSetupField, SkillSetupRoute } from '../skill-types.ts';
1
+ export type { SkillOAuthConfig, SkillSetup, SkillSetupField, SkillSetupRoute } from '../skill-types.ts';
2
2
  export { isMcpTokenProvider, MCP_TOKEN_PROVIDERS, type McpProviderConfig, type McpTokenProvider, resolveMcpProvider } from './mcp-providers.ts';
3
- export { OAUTH_PROVIDERS, type OAuthIntegrationConfig, resolveOAuthProviderByCredentialKey } from './oauth-providers.ts';
4
3
  export { deriveSetupRoutes, SETUP_ROUTE_KIND } from './setup-routes.ts';
@@ -1,3 +1,2 @@
1
1
  export { isMcpTokenProvider, MCP_TOKEN_PROVIDERS, resolveMcpProvider } from './mcp-providers.js';
2
- export { OAUTH_PROVIDERS, resolveOAuthProviderByCredentialKey } from './oauth-providers.js';
3
2
  export { deriveSetupRoutes, SETUP_ROUTE_KIND } from './setup-routes.js';
@@ -1,6 +1,5 @@
1
1
  import { OBSIDIAN_VAULT_PATH_CREDENTIAL_KEY } from '../obsidian-key.js';
2
2
  import { MCP_TOKEN_PROVIDERS } from './mcp-providers.js';
3
- import { resolveOAuthProviderByCredentialKey } from './oauth-providers.js';
4
3
  const UNSUPPORTED_STATE = 'unsupported';
5
4
  export const SETUP_ROUTE_KIND = {
6
5
  oauth: 'oauth',
@@ -67,20 +66,6 @@ function credentialKeysFor(entry) {
67
66
  return entry.metadata.requires?.credentials ?? [];
68
67
  }
69
68
  function credentialRoute(credentialKey) {
70
- const oauth = resolveOAuthProviderByCredentialKey(credentialKey);
71
- if (oauth) {
72
- return {
73
- kind: SETUP_ROUTE_KIND.oauth,
74
- label: `Connect ${oauth.label}`,
75
- provider: oauth.provider,
76
- credentialKey,
77
- description: oauth.description,
78
- helpUrl: oauth.helpUrl,
79
- fields: oauth.fields,
80
- steps: oauth.guide,
81
- configSteps: oauth.configGuide
82
- };
83
- }
84
69
  const token = MCP_TOKEN_PROVIDERS.find((config) => config.credentialKey === credentialKey);
85
70
  if (token) {
86
71
  return {
@@ -18,7 +18,7 @@ function buildAuthParams(config, clientId, redirectUri, state, pkce) {
18
18
  export async function runOAuthFlowWithRuntime(config, deps, runtime) {
19
19
  const openUrl = deps.openUrl ??
20
20
  (() => Promise.reject(new Error('OAuth browser launcher is unavailable; inject openUrl or createRedirect')));
21
- const redirect = await deps.createRedirect({ port: config.port }, { openUrl });
21
+ const redirect = await deps.createRedirect({ port: config.port, credentialKey: config.credentialKey }, { openUrl });
22
22
  try {
23
23
  const clientId = config.dynamicRegistration && !config.clientId
24
24
  ? await resolveDynamicClientId(config, redirect.redirectUri, deps, runtime.fetch)
@@ -1,3 +1,5 @@
1
- import type { OAuthFlowDeps, OAuthProvider, OAuthProviderConfig, OAuthTokens } from './types.ts';
2
- export declare function cancelOAuthFlow(provider: OAuthProvider): Promise<boolean>;
1
+ import type { OAuthFlowDeps, OAuthProviderConfig, OAuthTokens } from './types.ts';
2
+ export declare function cancelOAuthFlow(target: {
3
+ credentialKey: string;
4
+ }): Promise<boolean>;
3
5
  export declare function runOAuthFlow(config: OAuthProviderConfig, deps?: OAuthFlowDeps): Promise<OAuthTokens>;
@@ -2,12 +2,11 @@ import { abortOAuthLoopback, startOAuthLoopback } from '#oauth-loopback';
2
2
  import { randomBase64Url, sha256Base64Url } from '@qvac/core/oauth/runtime/crypto';
3
3
  import defaultFetch from '@qvac/core/oauth/runtime/fetch';
4
4
  import { runOAuthFlowWithRuntime } from './flow-core.js';
5
- import { OAUTH_PROVIDER_PORTS } from './keys.js';
6
- export function cancelOAuthFlow(provider) {
7
- return abortOAuthLoopback(OAUTH_PROVIDER_PORTS[provider]);
5
+ export function cancelOAuthFlow(target) {
6
+ return abortOAuthLoopback(target.credentialKey);
8
7
  }
9
8
  const loopbackRedirect = async (target, deps) => {
10
- const loopback = await startOAuthLoopback(target.port);
9
+ const loopback = await startOAuthLoopback(target.port, target.credentialKey);
11
10
  return {
12
11
  redirectUri: loopback.redirectUri,
13
12
  async authorize(authUrl, timeoutMs, expectedState) {
@@ -1,4 +1,6 @@
1
- export { buildProviderConfig, providerRequiresSecret, providerSupportsDcr, providerSupportsSharedIosSession } from './providers.ts';
1
+ export { buildProviderConfig } from './providers.ts';
2
+ export { specFromRoute, type OAuthKeySpec, type OAuthRouteLike } from './keys.ts';
3
+ export { oauthSpecFor, oauthSpecs } from './registry.ts';
2
4
  export { isTokenExpired, refreshOAuthTokens } from './token-exchange.ts';
3
5
  export { cancelOAuthFlow, runOAuthFlow } from './flow.ts';
4
6
  export type { OAuthCredentials, OAuthFlowDeps, OAuthFlowResult, OAuthProvider, OAuthProviderConfig, OAuthTokens } from './types.ts';
@@ -1,3 +1,5 @@
1
- export { buildProviderConfig, providerRequiresSecret, providerSupportsDcr, providerSupportsSharedIosSession } from './providers.js';
1
+ export { buildProviderConfig } from './providers.js';
2
+ export { specFromRoute } from './keys.js';
3
+ export { oauthSpecFor, oauthSpecs } from './registry.js';
2
4
  export { isTokenExpired, refreshOAuthTokens } from './token-exchange.js';
3
5
  export { cancelOAuthFlow, runOAuthFlow } from './flow.js';
@@ -1,26 +1,27 @@
1
- import type { OAuthProvider } from './types.ts';
1
+ import type { SkillOAuthConfig } from '@qvac/harness';
2
2
  export declare function scopedKey(agentId: string | undefined, key: string): string;
3
- export declare const GMAIL_CREDENTIAL_KEY = "gmail_access_token";
4
- export declare const GOOGLE_CALENDAR_CREDENTIAL_KEY = "google_calendar_access_token";
5
- export declare const GOOGLE_DOCS_CREDENTIAL_KEY = "google_docs_access_token";
6
- export declare const GOOGLE_DRIVE_CREDENTIAL_KEY = "google_drive_access_token";
7
- export declare const GOOGLE_SHEETS_CREDENTIAL_KEY = "google_sheets_access_token";
8
- export declare const SPOTIFY_CREDENTIAL_KEY = "spotify_access_token";
9
- export declare const ASANA_MCP_CREDENTIAL_KEY = "asana_mcp_access_token";
10
- export declare const NOTION_MCP_CREDENTIAL_KEY = "notion_mcp_access_token";
11
- export declare const LEGACY_GOOGLE_CREDENTIAL_KEY = "google_workspace_access_token";
12
- export type OAuthKeySpec = {
3
+ export type OAuthKeySpec = SkillOAuthConfig & {
13
4
  readonly credentialKey: string;
14
- readonly stateKey: string;
15
- readonly provider: OAuthProvider;
16
- readonly scopes: ReadonlyArray<string>;
5
+ readonly provider: string;
17
6
  };
18
- export declare const OAUTH_KEY_SPECS: ReadonlyArray<OAuthKeySpec>;
19
- export declare function oauthKeySpec(credentialKey: string): OAuthKeySpec | null;
20
- export declare function oauthStateKeyFor(credentialKey: string): string | null;
21
- export declare function defaultCredentialKeyFor(provider: OAuthProvider): string;
22
- export declare const GOOGLE_CREDENTIAL_KEYS: ReadonlyArray<string>;
23
- export declare const OAUTH_PROVIDER_PORTS: Readonly<Record<OAuthProvider, number>>;
7
+ type OAuthConfigLike = {
8
+ readonly stateKey?: string | null | undefined;
9
+ readonly authUrl?: string | null | undefined;
10
+ readonly tokenUrl?: string | null | undefined;
11
+ readonly scopes?: ReadonlyArray<string> | null | undefined;
12
+ readonly tokenAuth?: string | null | undefined;
13
+ readonly extraAuthParams?: unknown;
14
+ readonly registrationEndpoint?: string | null | undefined;
15
+ readonly port?: number | null | undefined;
16
+ readonly sharedIosSession?: boolean | null | undefined;
17
+ };
18
+ export type OAuthRouteLike = {
19
+ readonly credentialKey?: string | null | undefined;
20
+ readonly provider?: string | null | undefined;
21
+ readonly oauth?: OAuthConfigLike | null | undefined;
22
+ };
23
+ export declare function specFromRoute(route: OAuthRouteLike): OAuthKeySpec | null;
24
24
  export declare const OAUTH_CALLBACK_PATH = "/callback";
25
25
  export declare const OAUTH_WAIT_FOR_CODE_TIMEOUT_MS = 120000;
26
26
  export declare function oauthRedirectUri(port: number): string;
27
+ export {};
@@ -1,95 +1,69 @@
1
1
  export function scopedKey(agentId, key) {
2
2
  return agentId ? `skills.${agentId}.${key}` : `skills.${key}`;
3
3
  }
4
- export const GMAIL_CREDENTIAL_KEY = 'gmail_access_token';
5
- export const GOOGLE_CALENDAR_CREDENTIAL_KEY = 'google_calendar_access_token';
6
- export const GOOGLE_DOCS_CREDENTIAL_KEY = 'google_docs_access_token';
7
- export const GOOGLE_DRIVE_CREDENTIAL_KEY = 'google_drive_access_token';
8
- export const GOOGLE_SHEETS_CREDENTIAL_KEY = 'google_sheets_access_token';
9
- export const SPOTIFY_CREDENTIAL_KEY = 'spotify_access_token';
10
- export const ASANA_MCP_CREDENTIAL_KEY = 'asana_mcp_access_token';
11
- export const NOTION_MCP_CREDENTIAL_KEY = 'notion_mcp_access_token';
12
- export const LEGACY_GOOGLE_CREDENTIAL_KEY = 'google_workspace_access_token';
13
- const DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
14
- export const OAUTH_KEY_SPECS = [
15
- {
16
- credentialKey: GMAIL_CREDENTIAL_KEY,
17
- stateKey: 'gmail_oauth',
18
- provider: 'google',
19
- scopes: ['https://www.googleapis.com/auth/gmail.modify']
20
- },
21
- {
22
- credentialKey: GOOGLE_CALENDAR_CREDENTIAL_KEY,
23
- stateKey: 'google_calendar_oauth',
24
- provider: 'google',
25
- scopes: ['https://www.googleapis.com/auth/calendar']
26
- },
27
- {
28
- credentialKey: GOOGLE_DOCS_CREDENTIAL_KEY,
29
- stateKey: 'google_docs_oauth',
30
- provider: 'google',
31
- scopes: ['https://www.googleapis.com/auth/documents', DRIVE_SCOPE]
32
- },
33
- {
34
- credentialKey: GOOGLE_DRIVE_CREDENTIAL_KEY,
35
- stateKey: 'google_drive_oauth',
36
- provider: 'google',
37
- scopes: [DRIVE_SCOPE]
38
- },
39
- {
40
- credentialKey: GOOGLE_SHEETS_CREDENTIAL_KEY,
41
- stateKey: 'google_sheets_oauth',
42
- provider: 'google',
43
- scopes: ['https://www.googleapis.com/auth/spreadsheets', DRIVE_SCOPE]
44
- },
45
- {
46
- credentialKey: SPOTIFY_CREDENTIAL_KEY,
47
- stateKey: 'spotify_oauth',
48
- provider: 'spotify',
49
- scopes: [
50
- 'user-read-private',
51
- 'user-read-playback-state',
52
- 'user-modify-playback-state',
53
- 'user-read-currently-playing',
54
- 'playlist-read-private',
55
- 'playlist-read-collaborative',
56
- 'user-library-read',
57
- 'user-top-read',
58
- 'user-read-recently-played'
59
- ]
60
- },
61
- {
62
- credentialKey: ASANA_MCP_CREDENTIAL_KEY,
63
- stateKey: 'asana_oauth',
64
- provider: 'asana',
65
- scopes: []
66
- },
67
- {
68
- credentialKey: NOTION_MCP_CREDENTIAL_KEY,
69
- stateKey: 'notion_oauth',
70
- provider: 'notion',
71
- scopes: []
4
+ const TOKEN_AUTH = ['pkce-only', 'secret-in-body', 'secret-in-basic'];
5
+ function tokenAuthOf(value) {
6
+ return TOKEN_AUTH.find((candidate) => candidate === value) ?? null;
7
+ }
8
+ function httpsUrl(value) {
9
+ if (!value)
10
+ return null;
11
+ try {
12
+ return new URL(value).protocol === 'https:' ? value : null;
13
+ }
14
+ catch {
15
+ return null;
72
16
  }
73
- ];
74
- export function oauthKeySpec(credentialKey) {
75
- return OAUTH_KEY_SPECS.find((spec) => spec.credentialKey === credentialKey) ?? null;
76
17
  }
77
- export function oauthStateKeyFor(credentialKey) {
78
- return oauthKeySpec(credentialKey)?.stateKey ?? null;
18
+ function portOf(value) {
19
+ if (value === undefined || value === null)
20
+ return null;
21
+ return Number.isInteger(value) && value >= 0 && value <= 65535
22
+ ? value
23
+ : null;
24
+ }
25
+ export function specFromRoute(route) {
26
+ const oauth = route.oauth;
27
+ if (!oauth)
28
+ return null;
29
+ const tokenAuth = tokenAuthOf(oauth.tokenAuth);
30
+ const authUrl = httpsUrl(oauth.authUrl);
31
+ const tokenUrl = httpsUrl(oauth.tokenUrl);
32
+ if (!route.credentialKey || !oauth.stateKey || !authUrl || !tokenUrl || !tokenAuth)
33
+ return null;
34
+ if (oauth.stateKey === route.credentialKey)
35
+ return null;
36
+ if (oauth.port !== undefined && oauth.port !== null && portOf(oauth.port) === null)
37
+ return null;
38
+ if (oauth.registrationEndpoint && !httpsUrl(oauth.registrationEndpoint))
39
+ return null;
40
+ if (oauth.registrationEndpoint && tokenAuth !== 'pkce-only')
41
+ return null;
42
+ const extraParams = stringRecord(oauth.extraAuthParams);
43
+ const port = portOf(oauth.port);
44
+ return {
45
+ credentialKey: route.credentialKey,
46
+ provider: route.provider ?? route.credentialKey,
47
+ stateKey: oauth.stateKey,
48
+ authUrl,
49
+ tokenUrl,
50
+ tokenAuth,
51
+ scopes: stringList(oauth.scopes),
52
+ ...(extraParams ? { extraAuthParams: extraParams } : {}),
53
+ ...(oauth.registrationEndpoint ? { registrationEndpoint: oauth.registrationEndpoint } : {}),
54
+ ...(port !== null ? { port } : {}),
55
+ ...(oauth.sharedIosSession === true ? { sharedIosSession: true } : {})
56
+ };
57
+ }
58
+ function stringRecord(value) {
59
+ if (!value || typeof value !== 'object' || Array.isArray(value))
60
+ return null;
61
+ const entries = Object.entries(value).filter(([, item]) => typeof item === 'string');
62
+ return entries.length > 0 ? Object.fromEntries(entries) : null;
79
63
  }
80
- export function defaultCredentialKeyFor(provider) {
81
- const spec = OAUTH_KEY_SPECS.find((candidate) => candidate.provider === provider);
82
- if (!spec)
83
- throw new Error(`Unknown OAuth provider: ${String(provider)}`);
84
- return spec.credentialKey;
64
+ function stringList(value) {
65
+ return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
85
66
  }
86
- export const GOOGLE_CREDENTIAL_KEYS = OAUTH_KEY_SPECS.filter((spec) => spec.provider === 'google').map((spec) => spec.credentialKey);
87
- export const OAUTH_PROVIDER_PORTS = {
88
- google: 18978,
89
- spotify: 18974,
90
- asana: 18981,
91
- notion: 18982
92
- };
93
67
  export const OAUTH_CALLBACK_PATH = '/callback';
94
68
  export const OAUTH_WAIT_FOR_CODE_TIMEOUT_MS = 120_000;
95
69
  export function oauthRedirectUri(port) {
@@ -1,3 +1,3 @@
1
1
  import type { OAuthLoopbackServer } from './redirect-types.ts';
2
- export declare function abortOAuthLoopback(port: number): Promise<boolean>;
3
- export declare function startOAuthLoopback(port: number): Promise<OAuthLoopbackServer>;
2
+ export declare function abortOAuthLoopback(credentialKey: string): Promise<boolean>;
3
+ export declare function startOAuthLoopback(port: number, credentialKey: string): Promise<OAuthLoopbackServer>;
@@ -1,6 +1,6 @@
1
1
  import { createServer } from 'http';
2
2
  import { OAUTH_CALLBACK_PATH, OAUTH_WAIT_FOR_CODE_TIMEOUT_MS, oauthRedirectUri } from './keys.js';
3
- const activeLoopbacks = new Map();
3
+ const activeLoopbacks = new Set();
4
4
  function closeServer(server) {
5
5
  return new Promise((resolve) => {
6
6
  if (!server.listening) {
@@ -11,17 +11,23 @@ function closeServer(server) {
11
11
  server.close(() => resolve());
12
12
  });
13
13
  }
14
- export async function abortOAuthLoopback(port) {
15
- const handle = activeLoopbacks.get(port);
16
- if (!handle)
17
- return false;
18
- await handle.abort(new Error('OAuth flow cancelled'));
19
- return true;
14
+ async function abortMatching(matches, reason) {
15
+ await Promise.all(matches.map((handle) => handle.abort(reason)));
16
+ return matches.length > 0;
20
17
  }
21
- export async function startOAuthLoopback(port) {
22
- const stale = activeLoopbacks.get(port);
23
- if (stale) {
24
- await stale.abort(new Error('OAuth loopback superseded by a new connect attempt'));
18
+ function abortFor(credentialKey, reason) {
19
+ return abortMatching([...activeLoopbacks].filter((handle) => handle.credentialKey === credentialKey), reason);
20
+ }
21
+ export function abortOAuthLoopback(credentialKey) {
22
+ return abortFor(credentialKey, new Error('OAuth flow cancelled'));
23
+ }
24
+ export async function startOAuthLoopback(port, credentialKey) {
25
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
26
+ throw new Error(`OAuth loopback port must be an integer in [0, 65535], got ${port}`);
27
+ }
28
+ await abortFor(credentialKey, new Error('OAuth loopback superseded by a new connect attempt'));
29
+ if (port !== 0) {
30
+ await abortMatching([...activeLoopbacks].filter((handle) => handle.port === port), new Error('OAuth loopback superseded by a new connect attempt on the same port'));
25
31
  }
26
32
  let resolveCode = null;
27
33
  let rejectCode = null;
@@ -46,7 +52,7 @@ export async function startOAuthLoopback(port) {
46
52
  reject?.(new Error('OAuth callback missing code or state'));
47
53
  };
48
54
  const server = createServer((request, response) => {
49
- const url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`);
55
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1');
50
56
  if (url.pathname !== OAUTH_CALLBACK_PATH) {
51
57
  response.writeHead(404, { 'Content-Type': 'text/plain' });
52
58
  response.end('Not found');
@@ -74,27 +80,34 @@ export async function startOAuthLoopback(port) {
74
80
  return;
75
81
  listenSettled = true;
76
82
  server.removeListener('listening', onListening);
77
- reject(error);
83
+ reject(error.code === 'EADDRINUSE'
84
+ ? new Error(`OAuth loopback port ${port} is already in use by another process`)
85
+ : error);
78
86
  };
79
87
  const onListening = () => {
80
88
  if (listenSettled)
81
89
  return;
82
90
  listenSettled = true;
83
91
  server.removeListener('error', onError);
92
+ const address = server.address();
93
+ if (typeof address !== 'object' || !address) {
94
+ server.close();
95
+ reject(new Error('OAuth loopback bound to no address'));
96
+ return;
97
+ }
84
98
  const handle = {
99
+ credentialKey,
100
+ port: address.port,
85
101
  abort: (reason) => {
86
102
  abortedReason = reason;
87
103
  rejectWaiter(reason);
88
104
  return closeServer(server);
89
105
  }
90
106
  };
91
- activeLoopbacks.set(port, handle);
92
- server.once('close', () => {
93
- if (activeLoopbacks.get(port) === handle)
94
- activeLoopbacks.delete(port);
95
- });
107
+ activeLoopbacks.add(handle);
108
+ server.once('close', () => activeLoopbacks.delete(handle));
96
109
  resolve({
97
- redirectUri: oauthRedirectUri(port),
110
+ redirectUri: oauthRedirectUri(address.port),
98
111
  waitForCode(timeoutMs = OAUTH_WAIT_FOR_CODE_TIMEOUT_MS, expected) {
99
112
  if (abortedReason)
100
113
  throw abortedReason;
@@ -1,3 +1,3 @@
1
1
  import type { OAuthLoopbackServer } from './redirect-types.ts';
2
- export declare function abortOAuthLoopback(_port: number): Promise<boolean>;
3
- export declare function startOAuthLoopback(_port: number): Promise<OAuthLoopbackServer>;
2
+ export declare function abortOAuthLoopback(_credentialKey: string): Promise<boolean>;
3
+ export declare function startOAuthLoopback(_port: number, _credentialKey: string): Promise<OAuthLoopbackServer>;
@@ -1,6 +1,6 @@
1
- export function abortOAuthLoopback(_port) {
1
+ export function abortOAuthLoopback(_credentialKey) {
2
2
  return Promise.resolve(false);
3
3
  }
4
- export function startOAuthLoopback(_port) {
4
+ export function startOAuthLoopback(_port, _credentialKey) {
5
5
  return Promise.reject(new Error('OAuth loopback is unavailable in this runtime; inject createRedirect instead'));
6
6
  }
@@ -1,5 +1,3 @@
1
- import type { OAuthCredentials, OAuthProvider, OAuthProviderConfig } from './types.ts';
2
- export declare function providerRequiresSecret(provider: OAuthProvider): boolean;
3
- export declare function providerSupportsDcr(provider: OAuthProvider): boolean;
4
- export declare function providerSupportsSharedIosSession(provider: OAuthProvider): boolean;
5
- export declare function buildProviderConfig(credentialKey: string, credentials: OAuthCredentials): OAuthProviderConfig;
1
+ import type { OAuthKeySpec } from './keys.ts';
2
+ import type { OAuthCredentials, OAuthProviderConfig } from './types.ts';
3
+ export declare function buildProviderConfig(spec: OAuthKeySpec, credentials: OAuthCredentials): OAuthProviderConfig;