@kaviox/auth 0.3.0 → 0.4.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/README.md +79 -1
- package/dist/connectors.d.ts +32 -0
- package/dist/connectors.js +76 -0
- package/dist/index.d.ts +1 -1
- package/dist/testing.d.ts +26 -0
- package/dist/testing.js +103 -0
- package/dist/types.d.ts +94 -0
- package/package.json +10 -2
package/README.md
CHANGED
|
@@ -88,7 +88,8 @@ tenant proved it owns) or the token says so (`xms_edov`). A tenant can put any a
|
|
|
88
88
|
users' `email` claim, so an app must never let a Microsoft user in on an unverified address alone.
|
|
89
89
|
|
|
90
90
|
The gateway asks Microsoft for sign-in only (`openid email profile`). An app that needs Microsoft
|
|
91
|
-
Graph (
|
|
91
|
+
Graph (a mailbox) connects it through the gateway's connectors instead (below), never with an
|
|
92
|
+
Entra app of its own.
|
|
92
93
|
|
|
93
94
|
## Claude connectors (MCP)
|
|
94
95
|
|
|
@@ -150,3 +151,80 @@ npm run build # dist/, what npm publishes
|
|
|
150
151
|
The real gateway and binding run end to end in workerd in kaviox/platform's
|
|
151
152
|
`gateway/test/flow.test.ts`. Versions publish to npm from kaviox/platform's main with
|
|
152
153
|
`.github/workflows/package-auth-publish.yml` (npm trusted publishing, no token).
|
|
154
|
+
|
|
155
|
+
## Connectors (Microsoft 365 mail)
|
|
156
|
+
|
|
157
|
+
When the app's `apps.json` entry has `"connectors"`, the platform adds a `KAVIOX_CONNECTORS`
|
|
158
|
+
binding. The gateway runs Microsoft's consent with its own Entra app, keeps the refresh token, and
|
|
159
|
+
gives the app short-lived access tokens for the app's own connections. The app stores a
|
|
160
|
+
connection id, nothing secret. See
|
|
161
|
+
[docs/connector-gateway.md](https://github.com/kaviox/platform/blob/main/docs/connector-gateway.md).
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
import { beginConnect, finishConnect } from '@kaviox/auth/connectors';
|
|
165
|
+
import type { ConnectorsBinding } from '@kaviox/auth';
|
|
166
|
+
|
|
167
|
+
type Env = { KAVIOX_CONNECTORS: ConnectorsBinding };
|
|
168
|
+
|
|
169
|
+
// "Connect mailbox": to Microsoft by way of the gateway, tied to this browser with a cookie.
|
|
170
|
+
if (url.pathname === '/settings/mailbox/connect') {
|
|
171
|
+
return beginConnect(env.KAVIOX_CONNECTORS, {
|
|
172
|
+
connector: 'microsoft-mail',
|
|
173
|
+
returnTo: `${url.origin}/settings/mailbox/done`, // https://<one of the app's hosts>/<path>
|
|
174
|
+
mailbox: 'sales@customer.example', // optional: a shared mailbox, checked now
|
|
175
|
+
// scopes: optional, defaults to every scope apps.json allows the app
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
// Back from Microsoft.
|
|
179
|
+
if (url.pathname === '/settings/mailbox/done') {
|
|
180
|
+
const result = await finishConnect(env.KAVIOX_CONNECTORS, request);
|
|
181
|
+
if (!result.ok) return page(result.message, { headers: result.headers }); // result.error says which
|
|
182
|
+
await saveConnection(workspace, result.connection); // { connectionId, account, mailbox, scopes }
|
|
183
|
+
return redirect('/settings', { headers: result.headers });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Any time after, unattended (a cron, a queue):
|
|
187
|
+
const token = await env.KAVIOX_CONNECTORS.accessToken(connectionId);
|
|
188
|
+
if ('error' in token) {
|
|
189
|
+
if (token.error === 'reconnect_needed') await markReconnect(workspace); // show "Reconnect"
|
|
190
|
+
return; // not_found, rate_limited, unavailable: see below
|
|
191
|
+
}
|
|
192
|
+
await fetch(`https://graph.microsoft.com/v1.0/users/${mailbox}/messages`, { headers: { Authorization: `Bearer ${token.token}` } });
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
| Method | Returns |
|
|
196
|
+
|---|---|
|
|
197
|
+
| `connectUrl({ connector, scopes?, returnTo, mailbox?, state? })` | `{ url }` to send the browser to. Rejects with `E_CONNECTOR_NOT_ALLOWED`, `E_SCOPE_NOT_ALLOWED`, `E_RETURN_TO_NOT_ALLOWED`, `E_VALIDATION_ERROR` or `E_CONNECTOR_NOT_SET_UP` (`"<code>: <detail>"`): what apps.json doesn't allow is a bug, not a runtime condition. (Not `connect`: every Service Binding already has a `connect()`, for TCP sockets.) |
|
|
198
|
+
| `complete(code)` | `{ connectionId, connector, account: { email, name, tenantId, objectId }, mailbox, scopes }`, or `{ error: 'invalid_code' }` |
|
|
199
|
+
| `accessToken(connectionId)` | `{ token, expiresAt }` (seconds; at least 5 minutes left), or `{ error, message }` |
|
|
200
|
+
| `revoke(connectionId)` | `{ revoked }`: the gateway forgets the tokens at once |
|
|
201
|
+
| `activity(connectionId)` | The connection's audit trail, newest first |
|
|
202
|
+
|
|
203
|
+
`error` is one of `reconnect_needed` (Microsoft refused the refresh token: consent withdrawn,
|
|
204
|
+
password reset, long inactivity; connect again), `not_found` (never made, revoked, or another
|
|
205
|
+
app's), `invalid_code`, `rate_limited` (120 token requests a minute per connection: reuse a token
|
|
206
|
+
until it expires) or `unavailable` (Microsoft or the gateway failed; try again). The browser comes
|
|
207
|
+
back to `returnTo` with `?error=` instead of a code for `access_denied`, `admin_consent_required`
|
|
208
|
+
(the customer's admin must approve Kaviox once), `mailbox_not_accessible` and `server_error`;
|
|
209
|
+
`finishConnect` adds `state_mismatch` for a code arriving in a browser that didn't start the
|
|
210
|
+
connection. `CONNECT_MESSAGES` has plain words for each.
|
|
211
|
+
|
|
212
|
+
Reconnecting makes a new connection id: save it, and `revoke` the old one.
|
|
213
|
+
|
|
214
|
+
### Testing
|
|
215
|
+
|
|
216
|
+
`@kaviox/auth/testing` has an in-memory binding for the app's own tests:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
import { fakeConnectors } from '@kaviox/auth/testing';
|
|
220
|
+
|
|
221
|
+
const connectors = fakeConnectors(); // kaviox/workflow's microsoft-mail scopes by default
|
|
222
|
+
const start = await app.fetch(new Request(`${origin}/settings/mailbox/connect`), { ...env, KAVIOX_CONNECTORS: connectors });
|
|
223
|
+
const back = connectors.approve(start.headers.get('location')!); // or connectors.deny(url, 'admin_consent_required')
|
|
224
|
+
const cookie = start.headers.getSetCookie().map(line => line.split(';')[0]).join('; ');
|
|
225
|
+
await app.fetch(new Request(back, { headers: { cookie } }), { ...env, KAVIOX_CONNECTORS: connectors });
|
|
226
|
+
connectors.reconnectNeeded(connectionId); // from now on accessToken answers reconnect_needed
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
It refuses scopes and return URLs the way the gateway does, makes codes work once, and records
|
|
230
|
+
`connections` and `activity` for assertions.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ConnectError, ConnectRequest, Connection, ConnectorErrorCode, ConnectorsBinding } from './types.ts';
|
|
2
|
+
export type { AccessToken, ConnectError, ConnectRequest, ConnectedAccount, Connection, ConnectionEvent, ConnectorErrorCode, ConnectorFailure, ConnectorName, ConnectorsBinding } from './types.ts';
|
|
3
|
+
export declare const DEFAULT_CONNECTORS_BINDING = "KAVIOX_CONNECTORS";
|
|
4
|
+
/**
|
|
5
|
+
* Starts connecting an account: a redirect to the gateway, with a cookie tying the connection to
|
|
6
|
+
* this browser (one per connection, so two tabs don't collide). Rejects like `connectUrl` when
|
|
7
|
+
* apps.json doesn't allow the request.
|
|
8
|
+
*/
|
|
9
|
+
export declare function beginConnect(binding: ConnectorsBinding, request: Omit<ConnectRequest, 'state'>): Promise<Response>;
|
|
10
|
+
export type FinishConnectResult = {
|
|
11
|
+
ok: true;
|
|
12
|
+
connection: Connection;
|
|
13
|
+
headers: Headers;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* `state_mismatch`: this browser didn't start the connection (or took longer than 10 minutes):
|
|
17
|
+
* someone else's code, never redeemed. The others are the gateway's ({@link ConnectError}) or
|
|
18
|
+
* `complete`'s ({@link ConnectorErrorCode}).
|
|
19
|
+
*/
|
|
20
|
+
| {
|
|
21
|
+
ok: false;
|
|
22
|
+
error: ConnectError | ConnectorErrorCode | 'state_mismatch';
|
|
23
|
+
message: string;
|
|
24
|
+
headers: Headers;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Finishes connecting on the app's `returnTo`: checks the browser started it, then redeems the
|
|
28
|
+
* code. Send `headers` with your response: they clear the cookie.
|
|
29
|
+
*/
|
|
30
|
+
export declare function finishConnect(binding: ConnectorsBinding, request: Request): Promise<FinishConnectResult>;
|
|
31
|
+
/** Plain words for each way a connection can fail to start, for the app to show or adapt. */
|
|
32
|
+
export declare const CONNECT_MESSAGES: Record<ConnectError, string>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Connecting outside accounts (a Microsoft 365 mailbox) through the Kaviox connector gateway.
|
|
2
|
+
// See docs/connector-gateway.md in kaviox/platform.
|
|
3
|
+
//
|
|
4
|
+
// The gateway holds the OAuth client and the refresh tokens; the app keeps only a connection id.
|
|
5
|
+
// The binding (KAVIOX_CONNECTORS, added by the platform for apps with "connectors" in apps.json)
|
|
6
|
+
// is enough on its own. These two helpers add the one thing an app should do around it: tie the
|
|
7
|
+
// connection to the browser that started it, so a code from someone else's connection, sent to
|
|
8
|
+
// this browser in a link, is refused.
|
|
9
|
+
//
|
|
10
|
+
// // GET /settings/mailbox/connect
|
|
11
|
+
// return beginConnect(env.KAVIOX_CONNECTORS, { connector: 'microsoft-mail', returnTo: `${origin}/settings/mailbox/done`, mailbox: 'sales@example.com' });
|
|
12
|
+
//
|
|
13
|
+
// // GET /settings/mailbox/done
|
|
14
|
+
// const result = await finishConnect(env.KAVIOX_CONNECTORS, request);
|
|
15
|
+
// if (!result.ok) return errorPage(result.error, result.headers);
|
|
16
|
+
// await saveConnection(workspace, result.connection); // connectionId, account, mailbox, scopes
|
|
17
|
+
//
|
|
18
|
+
// // Later, unattended:
|
|
19
|
+
// const token = await env.KAVIOX_CONNECTORS.accessToken(connectionId);
|
|
20
|
+
// if ('error' in token) { if (token.error === 'reconnect_needed') markReconnect(); return; }
|
|
21
|
+
// await fetch('https://graph.microsoft.com/v1.0/…', { headers: { Authorization: `Bearer ${token.token}` } });
|
|
22
|
+
import { randomToken, sameString } from "./crypto.js";
|
|
23
|
+
export const DEFAULT_CONNECTORS_BINDING = 'KAVIOX_CONNECTORS';
|
|
24
|
+
const COOKIE_PREFIX = '__Host-kaviox_connect_';
|
|
25
|
+
const FLOW_SECONDS = 10 * 60;
|
|
26
|
+
const STATE = /^[A-Za-z0-9_-]{43}$/;
|
|
27
|
+
const cookieName = (state) => `${COOKIE_PREFIX}${state.slice(0, 16)}`;
|
|
28
|
+
const cookie = (name, value, maxAge) => `${name}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
|
|
29
|
+
function readCookie(request, name) {
|
|
30
|
+
const prefix = `${name}=`;
|
|
31
|
+
return request.headers.get('cookie')?.split(';').map(part => part.trim()).find(part => part.startsWith(prefix))?.slice(prefix.length) ?? null;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Starts connecting an account: a redirect to the gateway, with a cookie tying the connection to
|
|
35
|
+
* this browser (one per connection, so two tabs don't collide). Rejects like `connectUrl` when
|
|
36
|
+
* apps.json doesn't allow the request.
|
|
37
|
+
*/
|
|
38
|
+
export async function beginConnect(binding, request) {
|
|
39
|
+
const state = randomToken();
|
|
40
|
+
const { url } = await binding.connectUrl({ ...request, state });
|
|
41
|
+
const headers = new Headers({ Location: url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
|
|
42
|
+
headers.append('Set-Cookie', cookie(cookieName(state), state, FLOW_SECONDS));
|
|
43
|
+
return new Response(null, { status: 302, headers });
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Finishes connecting on the app's `returnTo`: checks the browser started it, then redeems the
|
|
47
|
+
* code. Send `headers` with your response: they clear the cookie.
|
|
48
|
+
*/
|
|
49
|
+
export async function finishConnect(binding, request) {
|
|
50
|
+
const query = new URL(request.url).searchParams;
|
|
51
|
+
const state = query.get('state') ?? '';
|
|
52
|
+
const headers = new Headers({ 'Cache-Control': 'no-store' });
|
|
53
|
+
const valid = STATE.test(state);
|
|
54
|
+
if (valid)
|
|
55
|
+
headers.append('Set-Cookie', cookie(cookieName(state), '', 0));
|
|
56
|
+
const kept = valid ? readCookie(request, cookieName(state)) : null;
|
|
57
|
+
if (!kept || !sameString(kept, state))
|
|
58
|
+
return { ok: false, error: 'state_mismatch', message: 'This connection was started in another browser, or took too long. Start connecting again.', headers };
|
|
59
|
+
const error = query.get('error');
|
|
60
|
+
if (error) {
|
|
61
|
+
const known = ['access_denied', 'admin_consent_required', 'mailbox_not_accessible', 'server_error'];
|
|
62
|
+
const code = known.includes(error) ? error : 'server_error';
|
|
63
|
+
return { ok: false, error: code, message: CONNECT_MESSAGES[code], headers };
|
|
64
|
+
}
|
|
65
|
+
const result = await binding.complete(query.get('code') ?? '');
|
|
66
|
+
if ('error' in result)
|
|
67
|
+
return { ok: false, error: result.error, message: result.message, headers };
|
|
68
|
+
return { ok: true, connection: result, headers };
|
|
69
|
+
}
|
|
70
|
+
/** Plain words for each way a connection can fail to start, for the app to show or adapt. */
|
|
71
|
+
export const CONNECT_MESSAGES = {
|
|
72
|
+
access_denied: 'The connection was cancelled, or Microsoft refused it. Try again.',
|
|
73
|
+
admin_consent_required: 'Your organization needs an administrator to approve Kaviox before this mailbox can be connected. Ask your Microsoft 365 admin, or have them connect it.',
|
|
74
|
+
mailbox_not_accessible: 'That account can\'t open the mailbox. Ask your admin to give it full access to the mailbox, or sign in with an account that has it.',
|
|
75
|
+
server_error: 'Something went wrong connecting the account. Try again.',
|
|
76
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { safeReturnTo } from './return-to.ts';
|
|
2
2
|
import type { Provider } from './types.ts';
|
|
3
|
-
export type { GatewayBinding, Identity, MailBinding, MailMessage, Provider, ValidatedToken } from './types.ts';
|
|
3
|
+
export type { AccessToken, ConnectError, ConnectRequest, ConnectedAccount, Connection, ConnectionEvent, ConnectorErrorCode, ConnectorFailure, ConnectorName, ConnectorsBinding, GatewayBinding, Identity, MailBinding, MailMessage, Provider, ValidatedToken } from './types.ts';
|
|
4
4
|
export { safeReturnTo };
|
|
5
5
|
export declare const PATHS: {
|
|
6
6
|
readonly signIn: "/auth/signin";
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ConnectError, ConnectedAccount, Connection, ConnectorsBinding } from './types.ts';
|
|
2
|
+
export interface FakeConnectorsOptions {
|
|
3
|
+
/** The scopes apps.json allows, per connector. Default: kaviox/workflow's microsoft-mail. */
|
|
4
|
+
allowed?: Record<string, string[]>;
|
|
5
|
+
/** Who approves, unless approve() says otherwise. */
|
|
6
|
+
account?: ConnectedAccount;
|
|
7
|
+
/** Access token lifetime, in seconds. Default 3600. */
|
|
8
|
+
tokenSeconds?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface FakeConnectors extends ConnectorsBinding {
|
|
11
|
+
/** The person approves at Microsoft: the URL the browser is sent back to, with a code. */
|
|
12
|
+
approve(url: string, options?: {
|
|
13
|
+
account?: Partial<ConnectedAccount>;
|
|
14
|
+
scopes?: string[];
|
|
15
|
+
}): string;
|
|
16
|
+
/** The person (or Microsoft) refuses: the URL the browser is sent back to, with the error. */
|
|
17
|
+
deny(url: string, error?: ConnectError): string;
|
|
18
|
+
/** From now on, this connection answers reconnect_needed, as when Microsoft refuses its refresh token. */
|
|
19
|
+
reconnectNeeded(connectionId: string): void;
|
|
20
|
+
/** Every connection made, by id, with how many tokens each served. */
|
|
21
|
+
readonly connections: Map<string, Connection & {
|
|
22
|
+
status: 'active' | 'reconnect_needed' | 'revoked';
|
|
23
|
+
tokensServed: number;
|
|
24
|
+
}>;
|
|
25
|
+
}
|
|
26
|
+
export declare function fakeConnectors({ allowed, account, tokenSeconds }?: FakeConnectorsOptions): FakeConnectors;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
const DEFAULT_ALLOWED = { 'microsoft-mail': ['Mail.ReadWrite', 'Mail.ReadWrite.Shared', 'offline_access', 'User.Read'] };
|
|
2
|
+
const DEFAULT_ACCOUNT = { email: 'owner@customer.example', name: 'Customer Owner', tenantId: '00000000-0000-4000-8000-00000000c0de', objectId: '00000000-0000-4000-8000-0000000000a1' };
|
|
3
|
+
const FAKE_GATEWAY = 'https://connectors.fake.test/connect/start';
|
|
4
|
+
const now = () => Math.floor(Date.now() / 1000);
|
|
5
|
+
const random = () => [...crypto.getRandomValues(new Uint8Array(16))].map(byte => byte.toString(16).padStart(2, '0')).join('');
|
|
6
|
+
const failure = (error, message) => ({ error, message });
|
|
7
|
+
export function fakeConnectors({ allowed = DEFAULT_ALLOWED, account = DEFAULT_ACCOUNT, tokenSeconds = 3600 } = {}) {
|
|
8
|
+
const requests = new Map();
|
|
9
|
+
const codes = new Map();
|
|
10
|
+
const connections = new Map();
|
|
11
|
+
const events = new Map();
|
|
12
|
+
const record = (id, event) => events.get(id)?.unshift({ at: now(), event });
|
|
13
|
+
const pending = (url) => {
|
|
14
|
+
const id = new URL(url).searchParams.get('request') ?? '';
|
|
15
|
+
const request = requests.get(id);
|
|
16
|
+
if (!request)
|
|
17
|
+
throw new Error(`fakeConnectors: ${url} is not a URL this fake's connectUrl() returned, or it was already used`);
|
|
18
|
+
requests.delete(id);
|
|
19
|
+
return request;
|
|
20
|
+
};
|
|
21
|
+
const back = (returnTo, params) => {
|
|
22
|
+
const target = new URL(returnTo);
|
|
23
|
+
target.search = new URLSearchParams(params).toString();
|
|
24
|
+
return target.toString();
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
connections,
|
|
28
|
+
async connectUrl(request) {
|
|
29
|
+
const grants = allowed[request?.connector];
|
|
30
|
+
if (!grants)
|
|
31
|
+
throw new Error(`E_CONNECTOR_NOT_ALLOWED: this app may not use the connector ${String(request?.connector)}`);
|
|
32
|
+
const scopes = request.scopes ?? grants;
|
|
33
|
+
const refused = scopes.find(scope => !grants.includes(scope));
|
|
34
|
+
if (refused !== undefined)
|
|
35
|
+
throw new Error(`E_SCOPE_NOT_ALLOWED: ${request.connector} may not ask for ${refused}`);
|
|
36
|
+
let returnTo;
|
|
37
|
+
try {
|
|
38
|
+
returnTo = new URL(request.returnTo);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new Error(`E_RETURN_TO_NOT_ALLOWED: ${String(request.returnTo)} is not a URL`);
|
|
42
|
+
}
|
|
43
|
+
if ((returnTo.protocol !== 'https:' && returnTo.hostname !== 'localhost') || returnTo.search || returnTo.hash)
|
|
44
|
+
throw new Error(`E_RETURN_TO_NOT_ALLOWED: ${request.returnTo} must be https://<host>/<path>, with no query`);
|
|
45
|
+
const id = random();
|
|
46
|
+
requests.set(id, { connector: request.connector, returnTo: request.returnTo, scopes: [...scopes], mailbox: request.mailbox?.toLowerCase() ?? null, state: request.state });
|
|
47
|
+
return { url: `${FAKE_GATEWAY}?request=${id}` };
|
|
48
|
+
},
|
|
49
|
+
approve(url, options = {}) {
|
|
50
|
+
const request = pending(url);
|
|
51
|
+
const connection = {
|
|
52
|
+
connectionId: `conn_${random()}`, connector: request.connector, account: { ...account, ...options.account },
|
|
53
|
+
mailbox: request.mailbox, scopes: options.scopes ?? request.scopes,
|
|
54
|
+
};
|
|
55
|
+
const code = `${connection.connectionId}.${random()}`;
|
|
56
|
+
codes.set(code, connection);
|
|
57
|
+
return back(request.returnTo, { code, ...(request.state ? { state: request.state } : {}) });
|
|
58
|
+
},
|
|
59
|
+
deny(url, error = 'access_denied') {
|
|
60
|
+
const request = pending(url);
|
|
61
|
+
return back(request.returnTo, { error, ...(request.state ? { state: request.state } : {}) });
|
|
62
|
+
},
|
|
63
|
+
async complete(code) {
|
|
64
|
+
const connection = codes.get(code);
|
|
65
|
+
codes.delete(code);
|
|
66
|
+
if (!connection)
|
|
67
|
+
return failure('invalid_code', 'That code is unknown, already used, expired, or another app\'s.');
|
|
68
|
+
connections.set(connection.connectionId, { ...connection, status: 'active', tokensServed: 0 });
|
|
69
|
+
events.set(connection.connectionId, []);
|
|
70
|
+
record(connection.connectionId, 'connected');
|
|
71
|
+
return connection;
|
|
72
|
+
},
|
|
73
|
+
async accessToken(connectionId) {
|
|
74
|
+
const connection = connections.get(connectionId);
|
|
75
|
+
if (!connection || connection.status === 'revoked')
|
|
76
|
+
return failure('not_found', 'This app has no such connection.');
|
|
77
|
+
if (connection.status === 'reconnect_needed')
|
|
78
|
+
return failure('reconnect_needed', `Microsoft no longer accepts this connection to ${connection.account.email}.`);
|
|
79
|
+
connection.tokensServed++;
|
|
80
|
+
record(connectionId, 'token');
|
|
81
|
+
return { token: `fake-access-token.${connectionId}.${connection.tokensServed}`, expiresAt: now() + tokenSeconds };
|
|
82
|
+
},
|
|
83
|
+
async revoke(connectionId) {
|
|
84
|
+
const connection = connections.get(connectionId);
|
|
85
|
+
if (!connection || connection.status === 'revoked')
|
|
86
|
+
return { revoked: false };
|
|
87
|
+
connection.status = 'revoked';
|
|
88
|
+
record(connectionId, 'revoked');
|
|
89
|
+
return { revoked: true };
|
|
90
|
+
},
|
|
91
|
+
async activity(connectionId) {
|
|
92
|
+
const connection = connections.get(connectionId);
|
|
93
|
+
return connection ? [...(events.get(connectionId) ?? [])] : failure('not_found', 'This app has no such connection.');
|
|
94
|
+
},
|
|
95
|
+
reconnectNeeded(connectionId) {
|
|
96
|
+
const connection = connections.get(connectionId);
|
|
97
|
+
if (!connection)
|
|
98
|
+
throw new Error(`fakeConnectors: no connection ${connectionId}`);
|
|
99
|
+
connection.status = 'reconnect_needed';
|
|
100
|
+
record(connectionId, 'reconnect_needed');
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -67,3 +67,97 @@ export interface MailBinding {
|
|
|
67
67
|
messageId: string;
|
|
68
68
|
}>;
|
|
69
69
|
}
|
|
70
|
+
/** The connectors the gateway offers. Each is one provider's API with its own Entra or Google app. */
|
|
71
|
+
export type ConnectorName = 'microsoft-mail';
|
|
72
|
+
/** What an app asks for when it starts a connection. */
|
|
73
|
+
export interface ConnectRequest {
|
|
74
|
+
connector: ConnectorName;
|
|
75
|
+
/**
|
|
76
|
+
* The delegated scopes to ask for, each one listed for the app and connector in apps.json.
|
|
77
|
+
* Defaults to all of them. The gateway always adds `openid profile email offline_access`.
|
|
78
|
+
*/
|
|
79
|
+
scopes?: string[];
|
|
80
|
+
/**
|
|
81
|
+
* Where the browser comes back: `https://<one of the app's hosts><path>`, with no query or
|
|
82
|
+
* fragment (PR previews on staging only). It gets `?code=…&state=…`, or `?error=…&state=…`.
|
|
83
|
+
*/
|
|
84
|
+
returnTo: string;
|
|
85
|
+
/**
|
|
86
|
+
* The mailbox the app will use, when it isn't the signed-in person's own (a shared mailbox, with
|
|
87
|
+
* `Mail.ReadWrite.Shared`). The gateway checks the person can open it before the connection is made.
|
|
88
|
+
*/
|
|
89
|
+
mailbox?: string;
|
|
90
|
+
/** Echoed back on `returnTo` as `state`. Tie it to the browser (a cookie) and check it. */
|
|
91
|
+
state?: string;
|
|
92
|
+
}
|
|
93
|
+
/** Why the browser came back to `returnTo` without a code. */
|
|
94
|
+
export type ConnectError = 'access_denied' | 'admin_consent_required' | 'mailbox_not_accessible' | 'server_error';
|
|
95
|
+
/** The account a connection reads, as Microsoft identified it. */
|
|
96
|
+
export interface ConnectedAccount {
|
|
97
|
+
/** The person's sign-in address (UPN), lowercased. */
|
|
98
|
+
email: string;
|
|
99
|
+
name: string;
|
|
100
|
+
/** The Entra tenant (lowercased GUID). */
|
|
101
|
+
tenantId: string;
|
|
102
|
+
/** The person's object id in that tenant. */
|
|
103
|
+
objectId: string;
|
|
104
|
+
}
|
|
105
|
+
export interface Connection {
|
|
106
|
+
/** Keep this, and nothing else: the gateway holds the tokens. Only this app can use it. */
|
|
107
|
+
connectionId: string;
|
|
108
|
+
connector: ConnectorName;
|
|
109
|
+
account: ConnectedAccount;
|
|
110
|
+
/** The mailbox checked at connect time, lowercased, or null for the person's own. */
|
|
111
|
+
mailbox: string | null;
|
|
112
|
+
/** The delegated scopes Microsoft granted (some tenants grant fewer than asked). */
|
|
113
|
+
scopes: string[];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* What a connection can't do right now:
|
|
117
|
+
* - `reconnect_needed`: the provider refused the refresh token (revoked consent, password reset,
|
|
118
|
+
* long inactivity, app removed from the tenant). Show "Reconnect" and start a new connection.
|
|
119
|
+
* - `not_found`: no such connection for this app (never made, made by another app, or revoked).
|
|
120
|
+
* - `invalid_code`: a code from `returnTo` that is unknown, used, expired or another app's.
|
|
121
|
+
* - `rate_limited`: too many token requests for this connection; wait a minute.
|
|
122
|
+
* - `unavailable`: the provider or the gateway failed; try again later.
|
|
123
|
+
*/
|
|
124
|
+
export type ConnectorErrorCode = 'reconnect_needed' | 'not_found' | 'invalid_code' | 'rate_limited' | 'unavailable';
|
|
125
|
+
export interface ConnectorFailure {
|
|
126
|
+
error: ConnectorErrorCode;
|
|
127
|
+
message: string;
|
|
128
|
+
}
|
|
129
|
+
export interface AccessToken {
|
|
130
|
+
/** A bearer token for the provider's API (Microsoft Graph). Don't store it. */
|
|
131
|
+
token: string;
|
|
132
|
+
/** When it stops working, in seconds since the epoch. At least 5 minutes away when issued. */
|
|
133
|
+
expiresAt: number;
|
|
134
|
+
}
|
|
135
|
+
/** One entry of a connection's audit trail. */
|
|
136
|
+
export interface ConnectionEvent {
|
|
137
|
+
/** Seconds since the epoch. */
|
|
138
|
+
at: number;
|
|
139
|
+
event: 'connected' | 'token' | 'refreshed' | 'reconnect_needed' | 'revoked' | 'refused';
|
|
140
|
+
detail?: string;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The connector gateway's binding, which the platform adds to every deploy of an app with
|
|
144
|
+
* "connectors" in apps.json (as KAVIOX_CONNECTORS). Every method acts for the app the binding
|
|
145
|
+
* names. `connectUrl` rejects with "<code>: <detail>" for requests apps.json doesn't allow (a bug, not
|
|
146
|
+
* a runtime condition); the others resolve with a {@link ConnectorFailure} instead of throwing.
|
|
147
|
+
*/
|
|
148
|
+
export interface ConnectorsBinding {
|
|
149
|
+
/**
|
|
150
|
+
* Where to send the browser to connect an account. Not `connect`: every Service Binding already
|
|
151
|
+
* has `connect()`, for TCP sockets.
|
|
152
|
+
*/
|
|
153
|
+
connectUrl(request: ConnectRequest): Promise<{
|
|
154
|
+
url: string;
|
|
155
|
+
}>;
|
|
156
|
+
complete(code: string): Promise<Connection | ConnectorFailure>;
|
|
157
|
+
accessToken(connectionId: string): Promise<AccessToken | ConnectorFailure>;
|
|
158
|
+
revoke(connectionId: string): Promise<{
|
|
159
|
+
revoked: boolean;
|
|
160
|
+
}>;
|
|
161
|
+
/** The connection's audit trail, newest first (at most 100 entries). */
|
|
162
|
+
activity(connectionId: string): Promise<ConnectionEvent[] | ConnectorFailure>;
|
|
163
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaviox/auth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Sign-in for Kaviox apps on Cloudflare Workers, through the Kaviox
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Sign-in and connected accounts for Kaviox apps on Cloudflare Workers, through the Kaviox gateway: middleware, callback, sign-out, sessions, MCP token checks, and connectors (Microsoft 365 mail).",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"sideEffects": false,
|
|
@@ -21,6 +21,14 @@
|
|
|
21
21
|
"./mcp": {
|
|
22
22
|
"types": "./dist/mcp.d.ts",
|
|
23
23
|
"default": "./dist/mcp.js"
|
|
24
|
+
},
|
|
25
|
+
"./connectors": {
|
|
26
|
+
"types": "./dist/connectors.d.ts",
|
|
27
|
+
"default": "./dist/connectors.js"
|
|
28
|
+
},
|
|
29
|
+
"./testing": {
|
|
30
|
+
"types": "./dist/testing.d.ts",
|
|
31
|
+
"default": "./dist/testing.js"
|
|
24
32
|
}
|
|
25
33
|
},
|
|
26
34
|
"files": [
|