@byokit/connect 0.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.0 (2026-10-01)
6
+
7
+
8
+
9
+ - Document a secrets-sealed desktop store and verify encrypted refresh-token persistence.
10
+ - Add per-person third-party sign-in, token refresh and typed remote MCP connections.
11
+
12
+ - OAuth authorization-code sign-in with S256 PKCE, protected-resource discovery and dynamic client registration.
13
+ - App-supplied redirects and an optional Node loopback helper; the host supplies each person's keystore.
14
+ - Single-flight refresh, rotating refresh tokens, disconnect and full typed MCP client pass-through.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,210 @@
1
+ # @byokit/connect
2
+
3
+ Connect a person's Google, Drive, Notion, Canva or other remote MCP account.
4
+ Sign-in opens the provider's own page. Credentials stay in the keystore the app
5
+ passes, scoped to that person on their device. There is no account pool, proxy,
6
+ ambient credential lookup, logging or extra opt-in switch.
7
+
8
+ ```sh
9
+ npm install @byokit/connect
10
+ ```
11
+
12
+ The main export is portable to Node, Electron, browsers and PWAs. It needs `fetch`,
13
+ Web Crypto, `btoa`, and URL APIs; native hosts must provide those globals before
14
+ importing it. The optional `/node` export owns only the loopback callback listener.
15
+ The main entry has no runtime dependency on Node or keystore backends.
16
+
17
+ ## Sign in with an app-supplied redirect
18
+
19
+ ```ts
20
+ import { connect } from '@byokit/connect';
21
+ import type { Keystore } from '@byokit/secrets';
22
+
23
+ // Supply your app's store, scoped to this person on this device.
24
+ declare const store: Keystore;
25
+ const drive = connect('drive', {
26
+ store,
27
+ person: 'person-42',
28
+ redirectUri: 'https://your-app.example/connect/callback',
29
+ client: { id: 'your-google-client-id', secret: 'your-google-client-secret' },
30
+ });
31
+
32
+ const flow = await drive.signIn();
33
+ // Open flow.url in the host's browser/auth session.
34
+ // Route its complete callback URL to the same flow instance:
35
+ await flow.finish('https://your-app.example/connect/callback?state=...&code=...');
36
+
37
+ const accessToken = await drive.token(); // Trusted API calls only; never show/log it.
38
+ await drive.disconnect();
39
+ ```
40
+
41
+ `connect(target, options)` creates a handle. `signIn()` returns `{ url, redirectUri,
42
+ finish, cancel }`. Call `cancel()` when closing the sign-in sheet. Calls to
43
+ `connected()`, `token()` and `disconnect()` work after reconstructing the handle
44
+ with the same store, person, target and configured client ID. The redirect port
45
+ can change without losing the saved connection. A newer sign-in invalidates the
46
+ older flow; callbacks have a 15-minute deadline and can be used only once.
47
+
48
+ Google requires the host's registered client. Use a Desktop client with loopback,
49
+ or register the exact HTTPS/native redirect for that client. Presets keep Google's
50
+ offline/consent parameters and request one service at a time: `google` (identity),
51
+ `drive` (`drive.file`), `gmail` (read-only) and `calendar` (events). The host owns
52
+ Google consent-screen publishing and API enablement. The kit does not probe
53
+ undocumented provider pages or impose a product-specific approval policy.
54
+
55
+ `notion`, `canva` and arbitrary HTTPS MCP URLs discover their protected-resource
56
+ metadata, authorization server and dynamic registration endpoint. If the server
57
+ does not offer registration, pass the app's registered `client`. Custom `Provider`
58
+ objects can supply `oauth` endpoints, an `issuer`, scopes and extra authorization
59
+ parameters. Options `scopes` override the preset/discovered scopes; security
60
+ parameters (`state`, PKCE, response type, client and redirect) cannot be overridden
61
+ through `extra`. A sign-in with explicitly incomplete granted scopes is not saved.
62
+
63
+ ## Loopback on a computer
64
+
65
+ ```ts
66
+ import { connectLoopback } from '@byokit/connect/node';
67
+ import type { Keystore } from '@byokit/secrets';
68
+
69
+ declare const store: Keystore;
70
+ declare const yourApp: { openExternal(url: string): Promise<void> };
71
+
72
+ const attempt = await connectLoopback('notion', {
73
+ store, person: 'person-42',
74
+ open: url => yourApp.openExternal(url),
75
+ });
76
+ await attempt.done;
77
+ const connection = attempt.connection;
78
+ // Or attempt.cancel() to close the listener and reject done.
79
+ ```
80
+
81
+ The listener binds only `127.0.0.1`, with an OS-assigned port, and closes on success,
82
+ cancel, failure or timeout. The host opens the browser; the kit never runs a CLI.
83
+ Use `connect()` with `redirectUri` for web/PWA or native auth sessions instead.
84
+
85
+ ## Full typed MCP client
86
+
87
+ ```ts
88
+ import { connect, CallToolResultSchema } from '@byokit/connect';
89
+ import type { Keystore } from '@byokit/secrets';
90
+
91
+ declare const store: Keystore;
92
+
93
+ const notion = connect('notion', {
94
+ store, person: 'person-42', redirectUri: 'https://your-app.example/connect/callback',
95
+ });
96
+ // Sign in once, then reconstruct this handle across app restarts.
97
+ const mcp = await notion.mcp({
98
+ clientInfo: { name: 'your-app', version: '1' },
99
+ clientOptions: { capabilities: {} },
100
+ configure: client => { /* register SDK request/notification handlers here */ },
101
+ });
102
+ try {
103
+ const page = await mcp.listTools(); // Follow nextCursor when present.
104
+ const result = await mcp.callTool({ name: page.tools[0].name, arguments: {} }, CallToolResultSchema);
105
+ // result preserves text, images, structuredContent, isError and other MCP data.
106
+ const resources = await mcp.listResources();
107
+ const prompts = await mcp.listPrompts();
108
+ } finally {
109
+ await mcp.close();
110
+ }
111
+ ```
112
+
113
+ `mcp()` returns the official SDK `Client`, pinned at 1.31.0. Its typed tools,
114
+ resources, prompts, pagination, cancellation, sampling/elicitation handlers,
115
+ notifications, generic schema-validated `request()` and transport negotiation stay
116
+ available. The package re-exports `Client` and the SDK's protocol types/schemas for
117
+ pass-through. Streamable HTTP supports JSON and SSE responses and session headers.
118
+ Every request obtains the person's current token, scoped to the connected resource.
119
+ A 401 triggers one refresh/retry; redirects are refused. Close clients before
120
+ `disconnect()` to release their streams. Arbitrary unauthenticated MCP servers and
121
+ legacy HTTP+SSE transports are outside this sign-in kit's initial scope.
122
+
123
+ ## Refresh, errors and storage
124
+
125
+ Refresh runs when the token is within one minute of expiry, or after a 401. It is
126
+ single-flight across handles sharing the same keystore object/person/connection.
127
+ Rotated refresh tokens are persisted; responses that omit a refresh token keep the
128
+ previous one. Transient failures preserve the sign-in. Only explicit
129
+ `invalid_grant` removes it. An unexpired token can still be used after a network
130
+ failure; an expired token is never returned. Tokens without `expires_in` remain
131
+ valid until rejected, then refresh if possible. No background timer is needed.
132
+
133
+ `ConnectError.code` is a typed app diagnostic and `message` is a plain sentence.
134
+ OAuth errors never include provider bodies, callback codes or tokens. No errors or
135
+ tokens are logged. MCP results/errors are private application content and should
136
+ be treated accordingly. `fetch`, `now`, request and flow timeouts are injectable.
137
+
138
+ The keystore dependency supplies the shared TypeScript contract; no backend is
139
+ imported at runtime. Pass any `@byokit/secrets` backend (or a
140
+ host adapter implementing its `get`/`set`/`delete` contract). The kit writes one
141
+ JSON secret containing the grant, refresh tokens, scopes, issuer/endpoints and
142
+ client registration per person/provider/resource/client under a fixed-length hashed
143
+ name. Use a durable device
144
+ store; do not send this record to a shared server. See [SECURITY.md](SECURITY.md)
145
+ for concurrency and callback boundaries.
146
+
147
+ ## Sealed desktop token storage
148
+
149
+ In Node or Electron's main process, wrap the host's durable store before passing
150
+ it to connect. This adapter writes only authenticated ciphertext, including after
151
+ refresh; the store's names are bound inside the sealed payload.
152
+
153
+ ```ts
154
+ import { connect } from '@byokit/connect';
155
+ import { osKeyringSeal, type Keystore } from '@byokit/secrets/node';
156
+
157
+ // Your app's durable, per-person store; it receives ciphertext only.
158
+ declare const ciphertextStore: Keystore;
159
+ const seal = osKeyringSeal({ service: 'crewhouse-connect-Umer', dualWrap: true });
160
+ const store: Keystore = {
161
+ async get(name) {
162
+ const value = await ciphertextStore.get(name);
163
+ if (value === null) return null;
164
+ const record = JSON.parse(seal.decryptString(Buffer.from(value, 'base64')));
165
+ if (record.name !== name || typeof record.secret !== 'string') throw new Error('Stored sign-in could not be opened.');
166
+ return record.secret;
167
+ },
168
+ async set(name, secret) {
169
+ const bytes = seal.encryptString(JSON.stringify({ name, secret }));
170
+ await ciphertextStore.set(name, Buffer.from(bytes).toString('base64'));
171
+ },
172
+ delete: name => ciphertextStore.delete(name),
173
+ };
174
+ const notion = connect('notion', {
175
+ store, person: 'Umer', redirectUri: 'https://your-app.example/connect/callback',
176
+ });
177
+ ```
178
+
179
+ Keep one adapter/store instance per person and app, and use an app writer lock if
180
+ multiple processes share storage. Dual wrapping permits reads through an owner-only
181
+ host key when the keyring is locked; keep that key separate from ciphertext backups.
182
+ Omit `dualWrap` and pass `fallback: false` when an accessible OS keyring is required.
183
+ See [secrets' sealing guide](../secrets/README.md#seal-accounts-files-on-desktop) for
184
+ platform behavior, key protection and rotation. Sign in and refresh normally through
185
+ the connection handle; never persist its returned access token separately.
186
+
187
+ ## Crewhouse adoption
188
+
189
+ Replace the OAuth, token-file and `RemoteMcp` portions of `src/connections.ts` with
190
+ one handle per member/app. Pass the member's keystore and member ID, the host's
191
+ registered Google client when applicable, and Crewhouse's callback address. Keep
192
+ flow handles in the host's callback routing table until completion/cancellation.
193
+ Crewhouse retains its own connection screen, Google setup guidance and tool gates.
194
+ For remote apps, call `mcp()` and use `listTools`/`callTool` with their full results;
195
+ for Gmail/Calendar use `token()` until their typed kits sit on this connection.
196
+ No raw OAuth, refresh or MCP transport needs to remain in the consumer.
197
+
198
+ ## Verification
199
+
200
+ ```sh
201
+ npm run build
202
+ npm run check
203
+ sh scripts/test.sh 'packages/connect/test/*.test.ts'
204
+ ```
205
+
206
+ Tests use fake providers and a real loopback callback only. They cover PKCE/state,
207
+ replay/cancel/expiry, discovery/DCR/resource binding, refresh races and revocation,
208
+ per-person isolation, rich MCP JSON/SSE responses and browser bundling. No real
209
+ accounts or outbound network calls are used. Live provider/device sign-ins are not
210
+ claimed by these tests.
package/SECURITY.md ADDED
@@ -0,0 +1,27 @@
1
+ # Security
2
+
3
+ The host supplies a keystore and person identifier. Scope it to the person and app on
4
+ this device. Tokens and dynamic client credentials are written only to that store;
5
+ the kit never reads ambient accounts, environment keys or credential files. No
6
+ server pool or account sharing is provided. Connection keys are fixed-length SHA-256 names over person, provider,
7
+ resource, issuer/token endpoint and configured client ID. Long identities therefore
8
+ fit every keystore backend without exposing those identities in keyring labels.
9
+
10
+ Treat `token()` as trusted app code: never display or log its result. The kit does
11
+ not log credentials or include provider response bodies in OAuth errors. The full
12
+ MCP client can return private content and server error messages; handle those as
13
+ private app data. Close each MCP client when finished.
14
+
15
+ Each handle snapshots and freezes its provider settings so an existing grant cannot
16
+ be retargeted by a later settings mutation.
17
+
18
+ Remote endpoints require HTTPS, with HTTP allowed only on loopback. Requests refuse
19
+ redirects, so credentials cannot follow a server redirect. Callback addresses support
20
+ HTTPS, loopback HTTP and host-registered native app schemes. PKCE, unpredictable
21
+ state, exact callback address checks, deadlines and one-shot callbacks protect each
22
+ sign-in. The host must claim its native callback scheme or use verified app links.
23
+
24
+ Refresh is serialized across handles sharing the same store object and connection
25
+ identity. Separate processes/store objects need host coordination; do not open the
26
+ same person's writable store in multiple processes. Explicit invalid-grant refresh
27
+ responses remove the sign-in; temporary server/network failures preserve it.
@@ -0,0 +1,28 @@
1
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { type ProviderId } from './providers.ts';
3
+ import type { ConnectOptions, Provider, SignIn, McpOptions } from './types.ts';
4
+ /** One person's connection on one device; the host owns the store and browser. */
5
+ export declare class Connection {
6
+ readonly provider: Readonly<Provider>;
7
+ private options;
8
+ private key;
9
+ private storageKey?;
10
+ private slot;
11
+ constructor(target: ProviderId | Provider | string, options: ConnectOptions);
12
+ private storeKey;
13
+ private get fetcher();
14
+ private get timeout();
15
+ private get now();
16
+ private saved;
17
+ connected(): Promise<boolean>;
18
+ disconnect(): Promise<void>;
19
+ /** Starts a fresh browser sign-in. No opt-in flag or server-held account is required. */
20
+ signIn(): Promise<SignIn>;
21
+ private register;
22
+ private exchange;
23
+ /** For trusted app code (mail/calendar/API calls). Never display or log this value. */
24
+ token(rejectedAccessToken?: string): Promise<string>;
25
+ /** The full official SDK Client: typed helpers, schemas, handlers, notifications and requests. */
26
+ mcp(options?: McpOptions): Promise<Client>;
27
+ }
28
+ export declare function connect(provider: ProviderId | Provider | string, options: ConnectOptions): Connection;
@@ -0,0 +1,261 @@
1
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
3
+ import { ConnectError } from "./errors.js";
4
+ import { discover } from "./discovery.js";
5
+ import { endpoint, redirect, request, json } from "./http.js";
6
+ import { providers } from "./providers.js";
7
+ // Across handles, only the same store + person + connection share work. No global token cache.
8
+ const stores = new WeakMap();
9
+ function slotFor(store, key) {
10
+ let slots = stores.get(store);
11
+ if (!slots) {
12
+ slots = new Map();
13
+ stores.set(store, slots);
14
+ }
15
+ let slot = slots.get(key);
16
+ if (!slot) {
17
+ slot = { tail: Promise.resolve(), epoch: 0 };
18
+ slots.set(key, slot);
19
+ }
20
+ return slot;
21
+ }
22
+ function serial(slot, action) {
23
+ const next = slot.tail.then(action, action);
24
+ slot.tail = next.catch(() => { });
25
+ return next;
26
+ }
27
+ function base64url(bytes) { return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }
28
+ function random() { return base64url(crypto.getRandomValues(new Uint8Array(32))); }
29
+ /** One person's connection on one device; the host owns the store and browser. */
30
+ export class Connection {
31
+ provider;
32
+ options;
33
+ key;
34
+ storageKey;
35
+ slot;
36
+ constructor(target, options) {
37
+ const provider = typeof target === 'string'
38
+ ? (Object.hasOwn(providers, target) ? providers[target] : { id: endpoint(target).href, name: 'App', mcpUrl: endpoint(target).href })
39
+ : target;
40
+ this.provider = Object.freeze({ ...provider,
41
+ oauth: provider.oauth && Object.freeze({ ...provider.oauth }),
42
+ scopes: provider.scopes && Object.freeze([...provider.scopes]),
43
+ extra: provider.extra && Object.freeze({ ...provider.extra }),
44
+ });
45
+ if (!options.person || !this.provider.id)
46
+ throw new ConnectError('configuration');
47
+ redirect(options.redirectUri);
48
+ if (this.provider.mcpUrl)
49
+ endpoint(this.provider.mcpUrl);
50
+ this.options = { ...options, scopes: options.scopes && Object.freeze([...options.scopes]), client: options.client && { ...options.client } };
51
+ this.key = `byokit.connect:${JSON.stringify([options.person, this.provider.id, this.provider.mcpUrl ?? '', this.provider.oauth?.token ?? this.provider.issuer ?? '', options.client?.id ?? ''])}`;
52
+ this.slot = slotFor(options.store, this.key);
53
+ }
54
+ storeKey() {
55
+ return this.storageKey ??= crypto.subtle.digest('SHA-256', new TextEncoder().encode(this.key))
56
+ .then(bytes => `byokit.connect.${base64url(new Uint8Array(bytes))}`);
57
+ }
58
+ get fetcher() { return this.options.fetch ?? globalThis.fetch; }
59
+ get timeout() { return this.options.timeoutMs ?? 20_000; }
60
+ get now() { return (this.options.now ?? Date.now)(); }
61
+ async saved() {
62
+ const raw = await this.options.store.get(await this.storeKey());
63
+ if (!raw)
64
+ return null;
65
+ try {
66
+ const value = JSON.parse(raw);
67
+ if (!value.tokens?.access || typeof value.tokens.access !== 'string' || !value.client?.id || !value.endpoints?.token || !Array.isArray(value.scopes))
68
+ throw new Error();
69
+ endpoint(value.endpoints.token);
70
+ return value;
71
+ }
72
+ catch {
73
+ throw new ConnectError('token');
74
+ }
75
+ }
76
+ async connected() { return !!await this.saved(); }
77
+ async disconnect() {
78
+ ++this.slot.epoch;
79
+ await serial(this.slot, async () => { await this.options.store.delete(await this.storeKey()); });
80
+ }
81
+ /** Starts a fresh browser sign-in. No opt-in flag or server-held account is required. */
82
+ async signIn() {
83
+ const epoch = ++this.slot.epoch;
84
+ const info = await discover(this.provider, this.fetcher, this.timeout);
85
+ const scopes = this.options.scopes ?? info.scopes;
86
+ const client = this.options.client ?? await this.register(info);
87
+ if (!client.id || (client.authMethod !== 'none' && client.authMethod && !client.secret))
88
+ throw new ConnectError('configuration');
89
+ const state = random(), verifier = random();
90
+ const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
91
+ const uri = this.options.redirectUri;
92
+ const url = endpoint(info.endpoints.authorize);
93
+ const fields = { ...this.provider.extra, response_type: 'code', client_id: client.id, redirect_uri: uri, state,
94
+ code_challenge: challenge, code_challenge_method: 'S256', ...(info.resource ? { resource: info.resource } : {}) };
95
+ for (const [key, value] of Object.entries(fields))
96
+ url.searchParams.set(key, value);
97
+ if (scopes.length)
98
+ url.searchParams.set('scope', scopes.join(' '));
99
+ else
100
+ url.searchParams.delete('scope');
101
+ const ends = this.now + (this.options.flowTimeoutMs ?? 15 * 60_000);
102
+ let consumed = false, cancelled = false;
103
+ return { url: url.href, redirectUri: uri, cancel: () => { consumed = true; cancelled = true; }, finish: async (callback) => {
104
+ if (consumed || epoch !== this.slot.epoch)
105
+ throw new ConnectError('callback');
106
+ if (this.now >= ends) {
107
+ consumed = true;
108
+ throw new ConnectError('expired');
109
+ }
110
+ let returned;
111
+ try {
112
+ returned = new URL(callback);
113
+ }
114
+ catch {
115
+ throw new ConnectError('callback');
116
+ }
117
+ const expected = new URL(uri);
118
+ if (returned.protocol !== expected.protocol || returned.host !== expected.host || returned.pathname !== expected.pathname || returned.username || returned.password || returned.hash || returned.searchParams.getAll('state').length !== 1 || returned.searchParams.get('state') !== state)
119
+ throw new ConnectError('callback');
120
+ for (const [key, value] of expected.searchParams)
121
+ if (returned.searchParams.getAll(key).length !== 1 || returned.searchParams.get(key) !== value)
122
+ throw new ConnectError('callback');
123
+ consumed = true;
124
+ if (returned.searchParams.has('error'))
125
+ throw new ConnectError('declined');
126
+ if (returned.searchParams.getAll('code').length !== 1 || !returned.searchParams.get('code'))
127
+ throw new ConnectError('callback');
128
+ await serial(this.slot, async () => {
129
+ if (epoch !== this.slot.epoch)
130
+ throw new ConnectError('callback');
131
+ const tokens = await this.exchange(info, client, { grant_type: 'authorization_code', code: returned.searchParams.get('code'), redirect_uri: uri, code_verifier: verifier });
132
+ if (cancelled)
133
+ throw new ConnectError('declined');
134
+ if (this.now >= ends)
135
+ throw new ConnectError('expired');
136
+ if (tokens.scope !== undefined && !scopes.every(sc => tokens.scope.split(/\s+/).includes(sc)))
137
+ throw new ConnectError('scope');
138
+ if (epoch !== this.slot.epoch)
139
+ throw new ConnectError('callback');
140
+ await this.options.store.set(await this.storeKey(), JSON.stringify({ ...info, scopes, client, tokens }));
141
+ });
142
+ } };
143
+ }
144
+ async register(info) {
145
+ if (!info.endpoints.register)
146
+ throw new ConnectError('configuration');
147
+ const response = await request(this.fetcher, info.endpoints.register, {
148
+ method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' },
149
+ body: JSON.stringify({ client_name: this.options.clientName ?? 'BYOKit', redirect_uris: [this.options.redirectUri], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none' }),
150
+ }, this.timeout);
151
+ if (!response.ok) {
152
+ await response.body?.cancel();
153
+ throw new ConnectError('registration', response.status);
154
+ }
155
+ const m = await json(response, 'registration');
156
+ if (typeof m.client_id !== 'string' || !m.client_id || (m.token_endpoint_auth_method !== undefined && m.token_endpoint_auth_method !== 'none'))
157
+ throw new ConnectError('registration');
158
+ return { id: m.client_id, authMethod: 'none' };
159
+ }
160
+ async exchange(info, client, fields, previous) {
161
+ const form = new URLSearchParams({ ...fields, client_id: client.id, ...(info.resource ? { resource: info.resource } : {}) });
162
+ const headers = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };
163
+ const method = client.authMethod ?? (client.secret ? 'client_secret_post' : 'none');
164
+ if (method === 'client_secret_post' && client.secret)
165
+ form.set('client_secret', client.secret);
166
+ if (method === 'client_secret_basic' && client.secret) {
167
+ const encode = (s) => new URLSearchParams({ v: s }).toString().slice(2);
168
+ headers.authorization = `Basic ${btoa(`${encode(client.id)}:${encode(client.secret)}`)}`;
169
+ form.delete('client_id');
170
+ }
171
+ const response = await request(this.fetcher, info.endpoints.token, { method: 'POST', headers, body: form }, this.timeout);
172
+ const m = await json(response, 'token');
173
+ if (!response.ok || m.error) {
174
+ // Only an explicit invalid grant proves revocation. Transient failures preserve the sign-in.
175
+ if (m.error === 'invalid_grant' && previous)
176
+ throw new ConnectError('signin', response.status);
177
+ throw new ConnectError('token', response.status);
178
+ }
179
+ if (typeof m.access_token !== 'string' || !m.access_token || typeof m.token_type !== 'string' || m.token_type.toLowerCase() !== 'bearer' || (m.expires_in !== undefined && (!Number.isFinite(Number(m.expires_in)) || Number(m.expires_in) < 0)))
180
+ throw new ConnectError('token');
181
+ return { access: m.access_token, refresh: typeof m.refresh_token === 'string' ? m.refresh_token : previous?.refresh,
182
+ expires: m.expires_in === undefined ? undefined : this.now + Number(m.expires_in) * 1000,
183
+ scope: typeof m.scope === 'string' ? m.scope : previous?.scope };
184
+ }
185
+ /** For trusted app code (mail/calendar/API calls). Never display or log this value. */
186
+ async token(rejectedAccessToken) {
187
+ const epoch = this.slot.epoch;
188
+ if (this.slot.tokenFlight?.epoch === epoch)
189
+ return this.slot.tokenFlight.promise;
190
+ const promise = serial(this.slot, async () => {
191
+ if (epoch !== this.slot.epoch)
192
+ throw new ConnectError('signin');
193
+ const saved = await this.saved();
194
+ if (!saved)
195
+ throw new ConnectError('signin');
196
+ const old = saved.tokens;
197
+ const force = rejectedAccessToken !== undefined && rejectedAccessToken === old.access;
198
+ if (!force && (old.expires === undefined || old.expires - this.now > 60_000))
199
+ return old.access;
200
+ if (!old.refresh) {
201
+ if (!force && old.expires !== undefined && old.expires > this.now)
202
+ return old.access;
203
+ throw new ConnectError('signin');
204
+ }
205
+ try {
206
+ const tokens = await this.exchange(saved, saved.client, { grant_type: 'refresh_token', refresh_token: old.refresh }, old);
207
+ if (epoch !== this.slot.epoch)
208
+ throw new ConnectError('signin');
209
+ await this.options.store.set(await this.storeKey(), JSON.stringify({ ...saved, tokens }));
210
+ return tokens.access;
211
+ }
212
+ catch (error) {
213
+ if (error instanceof ConnectError && error.code === 'signin' && epoch === this.slot.epoch)
214
+ await this.options.store.delete(await this.storeKey());
215
+ if (!force && error instanceof ConnectError && error.code === 'network' && old.expires !== undefined && old.expires > this.now)
216
+ return old.access;
217
+ throw error;
218
+ }
219
+ });
220
+ this.slot.tokenFlight = { epoch, promise };
221
+ try {
222
+ return await promise;
223
+ }
224
+ finally {
225
+ if (this.slot.tokenFlight?.promise === promise)
226
+ this.slot.tokenFlight = undefined;
227
+ }
228
+ }
229
+ /** The full official SDK Client: typed helpers, schemas, handlers, notifications and requests. */
230
+ async mcp(options = {}) {
231
+ if (!this.provider.mcpUrl)
232
+ throw new ConnectError('configuration');
233
+ const url = endpoint(this.provider.mcpUrl);
234
+ const fetcher = async (input, init) => {
235
+ // Transport may issue POST/GET/DELETE; credentials remain bound to this resource.
236
+ const requested = input instanceof Request ? input.url : String(input);
237
+ if (endpoint(requested).href !== url.href)
238
+ throw new ConnectError('configuration');
239
+ const access = await this.token();
240
+ const headers = new Headers(init?.headers);
241
+ headers.set('authorization', `Bearer ${access}`);
242
+ const response = await request(this.fetcher, url, { ...init, headers }, this.timeout);
243
+ if (response.status !== 401)
244
+ return response;
245
+ await response.body?.cancel();
246
+ headers.set('authorization', `Bearer ${await this.token(access)}`);
247
+ return request(this.fetcher, url, { ...init, headers }, this.timeout);
248
+ };
249
+ const client = new Client(options.clientInfo ?? { name: this.options.clientName ?? 'byokit', version: '0.1.0' }, options.clientOptions);
250
+ try {
251
+ options.configure?.(client);
252
+ await client.connect(new StreamableHTTPClientTransport(url, { fetch: fetcher }));
253
+ return client;
254
+ }
255
+ catch (error) {
256
+ await client.close().catch(() => { });
257
+ throw error;
258
+ }
259
+ }
260
+ }
261
+ export function connect(provider, options) { return new Connection(provider, options); }
@@ -0,0 +1,7 @@
1
+ import type { OAuthEndpoints, Provider } from './types.ts';
2
+ export interface Discovered {
3
+ endpoints: OAuthEndpoints;
4
+ scopes: readonly string[];
5
+ resource?: string;
6
+ }
7
+ export declare function discover(provider: Provider, fetcher: typeof fetch, timeout: number): Promise<Discovered>;
@@ -0,0 +1,57 @@
1
+ import { checkResourceAllowed } from '@modelcontextprotocol/sdk/shared/auth-utils.js';
2
+ import { ConnectError } from "./errors.js";
3
+ import { endpoint, json, request, strings } from "./http.js";
4
+ export async function discover(provider, fetcher, timeout) {
5
+ if (provider.oauth) {
6
+ for (const url of [provider.oauth.authorize, provider.oauth.token, provider.oauth.register].filter((x) => !!x))
7
+ endpoint(url);
8
+ return { endpoints: provider.oauth, scopes: provider.scopes ?? [], resource: provider.mcpUrl };
9
+ }
10
+ let issuer = provider.issuer;
11
+ let resource;
12
+ let scopes = provider.scopes;
13
+ if (provider.mcpUrl) {
14
+ const server = endpoint(provider.mcpUrl);
15
+ // RFC 9728: use the 401 challenge when present, otherwise well-known path then origin.
16
+ const probe = await request(fetcher, server, { headers: { accept: 'application/json, text/event-stream' } }, timeout);
17
+ const challenge = probe.headers.get('www-authenticate');
18
+ await probe.body?.cancel();
19
+ const advertised = challenge?.match(/resource_metadata\s*=\s*"([^"]+)"/i)?.[1];
20
+ const candidates = advertised ? [advertised] : [...new Set([`${server.origin}/.well-known/oauth-protected-resource${server.pathname === '/' ? '' : server.pathname}`, `${server.origin}/.well-known/oauth-protected-resource`])];
21
+ let metadata;
22
+ for (const url of candidates) {
23
+ const response = await request(fetcher, url, {}, timeout);
24
+ if (response.status === 404 && !advertised) {
25
+ await response.body?.cancel();
26
+ continue;
27
+ }
28
+ if (!response.ok)
29
+ throw new ConnectError('discovery', response.status);
30
+ metadata = await json(response, 'discovery');
31
+ break;
32
+ }
33
+ if (!metadata || typeof metadata.resource !== 'string' || !strings(metadata.authorization_servers) || metadata.authorization_servers.length === 0)
34
+ throw new ConnectError('discovery');
35
+ const canonical = endpoint(metadata.resource).href;
36
+ if (!checkResourceAllowed({ requestedResource: server, configuredResource: canonical }))
37
+ throw new ConnectError('discovery');
38
+ resource = metadata.resource;
39
+ if (issuer && !metadata.authorization_servers.includes(issuer))
40
+ throw new ConnectError('discovery');
41
+ issuer ??= metadata.authorization_servers[0];
42
+ if (!scopes && strings(metadata.scopes_supported))
43
+ scopes = metadata.scopes_supported;
44
+ }
45
+ if (!issuer)
46
+ throw new ConnectError('configuration');
47
+ const base = endpoint(issuer);
48
+ const response = await request(fetcher, `${base.origin}/.well-known/oauth-authorization-server${base.pathname === '/' ? '' : base.pathname.replace(/\/$/, '')}`, {}, timeout);
49
+ if (!response.ok)
50
+ throw new ConnectError('discovery', response.status);
51
+ const m = await json(response, 'discovery');
52
+ if (m.issuer !== issuer || typeof m.authorization_endpoint !== 'string' || typeof m.token_endpoint !== 'string' || (m.code_challenge_methods_supported !== undefined && (!strings(m.code_challenge_methods_supported) || !m.code_challenge_methods_supported.includes('S256'))))
53
+ throw new ConnectError('discovery');
54
+ for (const raw of [m.authorization_endpoint, m.token_endpoint, m.registration_endpoint].filter((x) => typeof x === 'string'))
55
+ endpoint(raw);
56
+ return { endpoints: { authorize: m.authorization_endpoint, token: m.token_endpoint, register: typeof m.registration_endpoint === 'string' ? m.registration_endpoint : undefined, issuer }, scopes: scopes ?? (strings(m.scopes_supported) ? m.scopes_supported : []), resource };
57
+ }
@@ -0,0 +1,7 @@
1
+ export type ConnectErrorCode = 'configuration' | 'discovery' | 'registration' | 'callback' | 'expired' | 'declined' | 'scope' | 'token' | 'signin' | 'network';
2
+ /** Never includes provider bodies, callback codes, credentials or URLs. */
3
+ export declare class ConnectError extends Error {
4
+ readonly code: ConnectErrorCode;
5
+ readonly status?: number;
6
+ constructor(code: ConnectErrorCode, status?: number);
7
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,13 @@
1
+ import WORDS from './words.json' with { type: 'json' };
2
+ const words = WORDS.errors;
3
+ /** Never includes provider bodies, callback codes, credentials or URLs. */
4
+ export class ConnectError extends Error {
5
+ code;
6
+ status;
7
+ constructor(code, status) {
8
+ super(words[code]);
9
+ this.name = 'ConnectError';
10
+ this.code = code;
11
+ this.status = status;
12
+ }
13
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type ConnectErrorCode } from './errors.ts';
2
+ /** Remote secrets go over HTTPS; loopback HTTP is useful for local servers and tests. */
3
+ export declare function endpoint(raw: string): URL;
4
+ export declare function redirect(raw: string): URL;
5
+ export declare function request(fetcher: typeof fetch, url: string | URL, init: RequestInit, timeout: number): Promise<Response>;
6
+ export declare function json(response: Response, code: ConnectErrorCode): Promise<Record<string, unknown>>;
7
+ export declare function strings(v: unknown): v is string[];
package/dist/http.js ADDED
@@ -0,0 +1,48 @@
1
+ import { ConnectError } from "./errors.js";
2
+ /** Remote secrets go over HTTPS; loopback HTTP is useful for local servers and tests. */
3
+ export function endpoint(raw) {
4
+ let u;
5
+ try {
6
+ u = new URL(raw);
7
+ }
8
+ catch {
9
+ throw new ConnectError('configuration');
10
+ }
11
+ if (u.username || u.password || u.hash || (u.protocol !== 'https:' && !(u.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname))))
12
+ throw new ConnectError('configuration');
13
+ return u;
14
+ }
15
+ export function redirect(raw) {
16
+ let u;
17
+ try {
18
+ u = new URL(raw);
19
+ }
20
+ catch {
21
+ throw new ConnectError('configuration');
22
+ }
23
+ if (u.username || u.password || u.hash || u.searchParams.has('state') || u.searchParams.has('code') || u.searchParams.has('error'))
24
+ throw new ConnectError('configuration');
25
+ if (u.protocol === 'http:' || u.protocol === 'https:')
26
+ return endpoint(raw);
27
+ if (['javascript:', 'data:', 'file:', 'ftp:', 'ws:', 'wss:'].includes(u.protocol))
28
+ throw new ConnectError('configuration');
29
+ return u;
30
+ }
31
+ export async function request(fetcher, url, init, timeout) {
32
+ try {
33
+ return await fetcher(endpoint(String(url)), { ...init, redirect: 'error', signal: init.signal ?? AbortSignal.timeout(timeout) });
34
+ }
35
+ catch {
36
+ throw new ConnectError('network');
37
+ }
38
+ }
39
+ export async function json(response, code) {
40
+ try {
41
+ const value = await response.json();
42
+ if (value && typeof value === 'object' && !Array.isArray(value))
43
+ return value;
44
+ }
45
+ catch { /* Do not expose response text. */ }
46
+ throw new ConnectError(code, response.status);
47
+ }
48
+ export function strings(v) { return Array.isArray(v) && v.every(x => typeof x === 'string'); }
@@ -0,0 +1,8 @@
1
+ export { connect, Connection } from './connect.ts';
2
+ export { providers } from './providers.ts';
3
+ export type { ProviderId } from './providers.ts';
4
+ export { ConnectError } from './errors.ts';
5
+ export type { ConnectErrorCode } from './errors.ts';
6
+ export type { Provider, OAuthClient, OAuthEndpoints, ConnectOptions, SignIn, McpOptions } from './types.ts';
7
+ export { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
+ export * from '@modelcontextprotocol/sdk/types.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { connect, Connection } from "./connect.js";
2
+ export { providers } from "./providers.js";
3
+ export { ConnectError } from "./errors.js";
4
+ // Expose the pinned engine for typed protocol pass-through without a second SDK pin.
5
+ export { Client } from '@modelcontextprotocol/sdk/client/index.js';
6
+ export * from '@modelcontextprotocol/sdk/types.js';
package/dist/node.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type Connection } from './connect.ts';
2
+ import type { ConnectOptions, Provider } from './types.ts';
3
+ import type { ProviderId } from './providers.ts';
4
+ export interface LoopbackOptions extends Omit<ConnectOptions, 'redirectUri'> {
5
+ /** Host opens the browser; BYOKit never spawns the person's browser or CLI. */
6
+ open(url: string): Promise<void> | void;
7
+ }
8
+ /** One-shot loopback listener on an OS-assigned port; closes on completion, cancel or timeout. */
9
+ export declare function connectLoopback(target: ProviderId | Provider | string, options: LoopbackOptions): Promise<{
10
+ connection: Connection;
11
+ done: Promise<void>;
12
+ cancel(): void;
13
+ }>;
package/dist/node.js ADDED
@@ -0,0 +1,89 @@
1
+ import WORDS from './words.json' with { type: 'json' };
2
+ import { createServer } from 'node:http';
3
+ import { connect } from "./connect.js";
4
+ import { ConnectError } from "./errors.js";
5
+ /** One-shot loopback listener on an OS-assigned port; closes on completion, cancel or timeout. */
6
+ export async function connectLoopback(target, options) {
7
+ let finish;
8
+ let resolve, reject;
9
+ const done = new Promise((yes, no) => { resolve = yes; reject = no; });
10
+ // The caller receives the promise after browser opening; a timeout before then is still handled.
11
+ void done.catch(() => { });
12
+ let settled = false;
13
+ let timer;
14
+ const settle = (error) => {
15
+ if (settled)
16
+ return;
17
+ settled = true;
18
+ clearTimeout(timer);
19
+ server.close();
20
+ server.closeAllConnections();
21
+ if (error) {
22
+ cancelFlow?.();
23
+ reject(error);
24
+ }
25
+ else
26
+ resolve();
27
+ };
28
+ let origin = '';
29
+ let state;
30
+ let completing = false;
31
+ let cancelFlow;
32
+ const server = createServer(async (req, res) => {
33
+ res.setHeader('content-type', 'text/plain; charset=utf-8');
34
+ res.setHeader('cache-control', 'no-store');
35
+ res.setHeader('x-content-type-options', 'nosniff');
36
+ if (req.method !== 'GET' || req.headers.host !== new URL(origin).host || req.url?.split('?')[0] !== '/callback' || !finish || settled) {
37
+ res.writeHead(404);
38
+ res.end(WORDS.browser.unavailable);
39
+ return;
40
+ }
41
+ const callback = new URL(req.url, origin);
42
+ if (callback.searchParams.getAll('state').length !== 1 || callback.searchParams.get('state') !== state) {
43
+ res.writeHead(400);
44
+ res.end(WORDS.browser.mismatch);
45
+ return;
46
+ }
47
+ if (completing) {
48
+ res.writeHead(409);
49
+ res.end(WORDS.browser.finishing);
50
+ return;
51
+ }
52
+ completing = true;
53
+ try {
54
+ await finish(callback.href);
55
+ res.end(WORDS.browser.connected);
56
+ setImmediate(() => settle());
57
+ }
58
+ catch (error) {
59
+ res.writeHead(400);
60
+ res.end(WORDS.browser.failed);
61
+ setImmediate(() => settle(error));
62
+ }
63
+ });
64
+ await new Promise((yes, no) => { server.once('error', no); server.listen(0, '127.0.0.1', () => { server.removeListener('error', no); yes(); }); });
65
+ server.on('error', error => settle(error));
66
+ const address = server.address();
67
+ if (!address || typeof address === 'string') {
68
+ settle(new ConnectError('configuration'));
69
+ throw new ConnectError('configuration');
70
+ }
71
+ origin = `http://127.0.0.1:${address.port}`;
72
+ timer = setTimeout(() => settle(new ConnectError('expired')), options.flowTimeoutMs ?? 15 * 60_000);
73
+ try {
74
+ const connection = connect(target, { ...options, redirectUri: `${origin}/callback` });
75
+ const flow = await connection.signIn();
76
+ state = new URL(flow.url).searchParams.get('state');
77
+ finish = callback => flow.finish(callback);
78
+ cancelFlow = flow.cancel;
79
+ if (settled)
80
+ throw new ConnectError('expired');
81
+ await options.open(flow.url);
82
+ return { connection, done, cancel: () => { cancelFlow?.(); settle(new ConnectError('declined')); } };
83
+ }
84
+ catch (error) {
85
+ cancelFlow?.();
86
+ settle(error);
87
+ throw error;
88
+ }
89
+ }
@@ -0,0 +1,66 @@
1
+ export declare const providers: {
2
+ readonly google: {
3
+ readonly id: "google";
4
+ readonly name: "Google";
5
+ readonly oauth: {
6
+ authorize: string;
7
+ token: string;
8
+ };
9
+ readonly scopes: readonly ["openid", "email", "profile"];
10
+ readonly extra: {
11
+ access_type: string;
12
+ prompt: string;
13
+ };
14
+ };
15
+ readonly drive: {
16
+ readonly id: "drive";
17
+ readonly name: "Google Drive";
18
+ readonly oauth: {
19
+ authorize: string;
20
+ token: string;
21
+ };
22
+ readonly scopes: readonly ["https://www.googleapis.com/auth/drive.file"];
23
+ readonly extra: {
24
+ access_type: string;
25
+ prompt: string;
26
+ };
27
+ readonly mcpUrl: "https://drivemcp.googleapis.com/mcp/v1";
28
+ };
29
+ readonly gmail: {
30
+ readonly id: "gmail";
31
+ readonly name: "Gmail";
32
+ readonly oauth: {
33
+ authorize: string;
34
+ token: string;
35
+ };
36
+ readonly scopes: readonly ["https://www.googleapis.com/auth/gmail.readonly"];
37
+ readonly extra: {
38
+ access_type: string;
39
+ prompt: string;
40
+ };
41
+ };
42
+ readonly calendar: {
43
+ readonly id: "calendar";
44
+ readonly name: "Google Calendar";
45
+ readonly oauth: {
46
+ authorize: string;
47
+ token: string;
48
+ };
49
+ readonly scopes: readonly ["https://www.googleapis.com/auth/calendar.events"];
50
+ readonly extra: {
51
+ access_type: string;
52
+ prompt: string;
53
+ };
54
+ };
55
+ readonly notion: {
56
+ readonly id: "notion";
57
+ readonly name: "Notion";
58
+ readonly mcpUrl: "https://mcp.notion.com/mcp";
59
+ };
60
+ readonly canva: {
61
+ readonly id: "canva";
62
+ readonly name: "Canva";
63
+ readonly mcpUrl: "https://mcp.canva.com/mcp";
64
+ };
65
+ };
66
+ export type ProviderId = keyof typeof providers;
@@ -0,0 +1,10 @@
1
+ const googleOAuth = { authorize: 'https://accounts.google.com/o/oauth2/v2/auth', token: 'https://oauth2.googleapis.com/token' };
2
+ const googleExtra = { access_type: 'offline', prompt: 'consent' };
3
+ export const providers = {
4
+ google: { id: 'google', name: 'Google', oauth: googleOAuth, scopes: ['openid', 'email', 'profile'], extra: googleExtra },
5
+ drive: { id: 'drive', name: 'Google Drive', oauth: googleOAuth, scopes: ['https://www.googleapis.com/auth/drive.file'], extra: googleExtra, mcpUrl: 'https://drivemcp.googleapis.com/mcp/v1' },
6
+ gmail: { id: 'gmail', name: 'Gmail', oauth: googleOAuth, scopes: ['https://www.googleapis.com/auth/gmail.readonly'], extra: googleExtra },
7
+ calendar: { id: 'calendar', name: 'Google Calendar', oauth: googleOAuth, scopes: ['https://www.googleapis.com/auth/calendar.events'], extra: googleExtra },
8
+ notion: { id: 'notion', name: 'Notion', mcpUrl: 'https://mcp.notion.com/mcp' },
9
+ canva: { id: 'canva', name: 'Canva', mcpUrl: 'https://mcp.canva.com/mcp' },
10
+ };
@@ -0,0 +1,55 @@
1
+ import type { Keystore } from '@byokit/secrets';
2
+ import type { ClientOptions } from '@modelcontextprotocol/sdk/client/index.js';
3
+ export interface OAuthClient {
4
+ id: string;
5
+ secret?: string;
6
+ authMethod?: 'none' | 'client_secret_post' | 'client_secret_basic';
7
+ }
8
+ export interface OAuthEndpoints {
9
+ authorize: string;
10
+ token: string;
11
+ register?: string;
12
+ issuer?: string;
13
+ }
14
+ export interface Provider {
15
+ id: string;
16
+ name: string;
17
+ mcpUrl?: string;
18
+ issuer?: string;
19
+ oauth?: OAuthEndpoints;
20
+ scopes?: readonly string[];
21
+ /** Provider-specific authorization parameters; PKCE/state cannot be overridden. */
22
+ extra?: Readonly<Record<string, string>>;
23
+ }
24
+ export interface ConnectOptions {
25
+ /** A store scoped by the host to this person on this device. */
26
+ store: Keystore;
27
+ /** Distinguishes connections belonging to different people sharing a store. */
28
+ person: string;
29
+ /** HTTPS, loopback HTTP, or the host's registered native app URI. */
30
+ redirectUri: string;
31
+ client?: OAuthClient;
32
+ clientName?: string;
33
+ scopes?: readonly string[];
34
+ fetch?: typeof fetch;
35
+ now?: () => number;
36
+ timeoutMs?: number;
37
+ flowTimeoutMs?: number;
38
+ }
39
+ export interface SignIn {
40
+ readonly url: string;
41
+ readonly redirectUri: string;
42
+ /** Pass the complete callback URL; rejects mismatched, expired and reused callbacks. */
43
+ finish(callback: string | URL): Promise<void>;
44
+ cancel(): void;
45
+ }
46
+ export interface McpOptions {
47
+ clientInfo?: {
48
+ name: string;
49
+ version: string;
50
+ };
51
+ /** Includes capabilities and all official SDK client options. */
52
+ clientOptions?: ClientOptions;
53
+ /** Register sampling/elicitation/request/notification handlers before connecting. */
54
+ configure?: (client: import('@modelcontextprotocol/sdk/client/index.js').Client) => void;
55
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ {
2
+ "errors": {
3
+ "configuration": "This app needs its connection settings filled in.",
4
+ "discovery": "Could not find the app’s sign-in page.",
5
+ "registration": "The app could not set up sign-in. Try again.",
6
+ "callback": "This sign-in link does not match. Start again.",
7
+ "expired": "This sign-in link has expired. Start again.",
8
+ "declined": "Nothing was connected. Try again whenever you like.",
9
+ "scope": "Some permissions were left out. Sign in again and select them.",
10
+ "token": "The app did not finish connecting. Try again.",
11
+ "signin": "Sign in to this app again.",
12
+ "network": "Could not reach the app. Check your connection and try again."
13
+ },
14
+ "browser": {
15
+ "unavailable": "This page is not available.",
16
+ "mismatch": "This sign-in link does not match. Return to the app.",
17
+ "finishing": "Sign-in is already finishing. Return to the app.",
18
+ "connected": "Connected. You can return to the app.",
19
+ "failed": "Sign-in did not finish. Return to the app and try again."
20
+ }
21
+ }
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@byokit/connect",
3
+ "version": "0.1.0",
4
+ "description": "Connect a person's third-party apps with PKCE, refresh and typed remote MCP.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/umeranjum17/byokit.git",
10
+ "directory": "packages/connect"
11
+ },
12
+ "engines": {
13
+ "node": ">=22.18"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ },
20
+ "./node": {
21
+ "types": "./dist/node.d.ts",
22
+ "default": "./dist/node.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE",
29
+ "CHANGELOG.md",
30
+ "SECURITY.md"
31
+ ],
32
+ "scripts": {
33
+ "prepack": "tsc -b"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "dependencies": {
39
+ "@modelcontextprotocol/sdk": "1.31.0",
40
+ "@byokit/secrets": "0.5.0"
41
+ }
42
+ }