@kaviox/auth 0.1.0 → 0.2.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 CHANGED
@@ -53,17 +53,43 @@ way, unless the app sets `allowUnverifiedEmail`.
53
53
  |---|---|---|
54
54
  | `cookieName` | required | The session cookie, a `__Host-` name |
55
55
  | `sessionDays` | 30 | Habits uses 180 for its Home Screen app |
56
- | `allow(user, env)` | `allowKaviox`: kaviox.com Google Workspace accounts only | `allowEmails`, `allowDomains` (Google's `hd`), `allowAny`, your own (a D1 lookup), or `allowAnyone` for a public app |
56
+ | `allow(user, env)` | `allowKaviox`: kaviox.com Google Workspace accounts only | `allowEmails`, `allowDomains` (Google's `hd`, or a Microsoft address Microsoft verified), `allowTenants` (Microsoft Entra tenant ids), `allowAny`, your own (a D1 lookup), or `allowAnyone` for a public app |
57
57
  | `onSignIn(user, env)` | none | Runs after a sign-in is allowed, for example to record it |
58
58
  | `identityHeaders` | `x-kaviox-user-id`, `-email`, `-name` | Fleet-OS keeps its `oai-authenticated-user-*` names |
59
59
  | `publicPaths` | none | Exact paths anyone may load |
60
60
  | `apiPrefixes` | `['/api/']` | Signed-out requests here get 401 JSON instead of a redirect |
61
61
  | `signInPage` | none | Your page for signed-out visitors and failures (`?return_to=`, `?error=`) |
62
62
  | `devUser` | null | With `DEV_AUTH_BYPASS=true` on localhost only: who requests run as (null: unchanged) |
63
- | `allowUnverifiedEmail` | false | Accept addresses Google hasn't verified |
63
+ | `allowUnverifiedEmail` | false | Accept addresses the provider hasn't verified (Microsoft guests and personal accounts among them); allow by tenant then |
64
64
 
65
65
  Users are `{ id, email, name, hd }`; `id` is `google:<sub>`, the format Fleet-OS and Habits store.
66
66
 
67
+ ## Microsoft
68
+
69
+ The gateway also signs people in with Microsoft (work, school and personal accounts). Link to
70
+ `/auth/signin?provider=microsoft` (with `return_to` as usual); `/auth/signin` alone is Google. The
71
+ user then has `id` `microsoft:<tid>:<oid>`, `provider: 'microsoft'`, `tid` (the Entra tenant) and
72
+ `emailVerified`.
73
+
74
+ ```ts
75
+ import { allowAny, allowDomains, allowTenants, createAuth } from '@kaviox/auth';
76
+
77
+ createAuth<Env>({
78
+ cookieName: '__Host-build_session',
79
+ // One company's tenant (members and guests, whom only its admin can add), or verified addresses on its domain.
80
+ allow: allowAny(allowTenants(['9d2eb354-…']), allowDomains('example.com')),
81
+ // Guests' and personal accounts' addresses aren't verified by Microsoft; allow those by tenant.
82
+ allowUnverifiedEmail: true,
83
+ });
84
+ ```
85
+
86
+ Microsoft only vouches for an address when it is a tenant member's username (its domain is one the
87
+ tenant proved it owns) or the token says so (`xms_edov`). A tenant can put any address in its
88
+ users' `email` claim, so an app must never let a Microsoft user in on an unverified address alone.
89
+
90
+ The gateway asks Microsoft for sign-in only (`openid email profile`). An app that needs Microsoft
91
+ Graph (files, mail, calendar) asks for it in its own connect step, with its own Entra app.
92
+
67
93
  ## Claude connectors (MCP)
68
94
 
69
95
  ```ts
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { safeReturnTo } from './return-to.ts';
2
- export type { GatewayBinding, Identity, ValidatedToken } from './types.ts';
2
+ import type { Provider } from './types.ts';
3
+ export type { GatewayBinding, Identity, Provider, ValidatedToken } from './types.ts';
3
4
  export { safeReturnTo };
4
5
  export declare const PATHS: {
5
6
  readonly signIn: "/auth/signin";
@@ -10,11 +11,18 @@ export declare const DEFAULT_BINDING = "KAVIOX_AUTH";
10
11
  export declare const DEFAULT_SECRET = "AUTH_SESSION_SECRET";
11
12
  /** What a session holds, and what the allow check sees. */
12
13
  export interface User {
13
- /** `google:<sub>`. */
14
+ /** `google:<sub>` or `microsoft:<tid>:<oid>`. */
14
15
  id: string;
15
16
  email: string;
16
17
  name: string;
18
+ /** Google Workspace domain; null for Microsoft. */
17
19
  hd: string | null;
20
+ /** Which provider signed them in. Sessions from before Microsoft existed are Google's. */
21
+ provider?: Provider;
22
+ /** Microsoft only: the Entra tenant they signed in from. */
23
+ tid?: string | null;
24
+ /** Whether the provider vouched for the email address (see the gateway's microsoft.ts). */
25
+ emailVerified?: boolean;
18
26
  }
19
27
  export interface Session extends User {
20
28
  exp: number;
@@ -52,7 +60,11 @@ export interface AuthOptions<Env> {
52
60
  * the gateway and failures show a plain page.
53
61
  */
54
62
  signInPage?: string;
55
- /** Accept Google addresses Google hasn't verified. Off by default: allow checks trust the email. */
63
+ /**
64
+ * Accept addresses the provider hasn't verified: Google's unverified addresses, and Microsoft
65
+ * guests, personal accounts and tenant-set email claims. Off by default: allow checks trust the
66
+ * email. An app that turns it on should allow by tenant (allowTenants) rather than by email.
67
+ */
56
68
  allowUnverifiedEmail?: boolean;
57
69
  /**
58
70
  * Local development: when DEV_AUTH_BYPASS is "true" on localhost, requests pass without a
@@ -67,13 +79,22 @@ export interface AuthOptions<Env> {
67
79
  export declare const DEFAULT_HEADERS: IdentityHeaders;
68
80
  /** Allows these addresses (a list, or a comma- or space-separated string such as a Worker var). */
69
81
  export declare const allowEmails: (emails: string | Iterable<string>) => (user: User) => boolean;
70
- /** Allows Google Workspace accounts on these domains, by Google's `hd` claim (not the email's domain). */
82
+ /**
83
+ * Allows accounts on these domains: Google Workspace accounts by Google's `hd` claim (not the
84
+ * email's domain), and Microsoft work accounts whose address Microsoft verified (a tenant member's
85
+ * username, whose domain the tenant had to prove it owns).
86
+ */
71
87
  export declare const allowDomains: (domains: string | Iterable<string>) => (user: User) => boolean;
88
+ /**
89
+ * Allows Microsoft accounts signed in from these Entra tenants (directory ids), members and guests
90
+ * alike: only the tenant's own admin can add someone to it.
91
+ */
92
+ export declare const allowTenants: (tenants: string | Iterable<string>) => (user: User) => boolean;
72
93
  /** The default: kaviox.com Google Workspace accounts. */
73
94
  export declare const KAVIOX_DOMAIN = "kaviox.com";
74
95
  export declare const allowKaviox: (user: User) => boolean;
75
96
  /**
76
- * Anyone with a Google account whose address Google has verified. For apps meant to be public;
97
+ * Anyone with a Google or Microsoft account whose address the provider has verified. For apps meant to be public;
77
98
  * named so that a review sees an app opening itself to everyone.
78
99
  */
79
100
  export declare const allowAnyone: (_user: User) => boolean;
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  //
8
8
  // Signing in: /auth/signin sends the browser to the gateway (auth.kaviox.com, or
9
9
  // staging.auth.kaviox.com for staging and PR previews) with a PKCE challenge. The gateway signs
10
- // the person in with Google and sends a one-time code to /auth/callback, which redeems it over the
10
+ // the person in with Google, or Microsoft when /auth/signin?provider=microsoft, and sends a one-time code to /auth/callback, which redeems it over the
11
11
  // KAVIOX_AUTH Service Binding with the PKCE verifier. The platform adds that binding to every
12
12
  // deploy, so the app needs no Google client, client secret or preview relay of its own.
13
13
  //
@@ -31,16 +31,33 @@ export const allowEmails = (emails) => {
31
31
  const allowed = new Set(list(emails));
32
32
  return (user) => allowed.has(user.email.toLowerCase());
33
33
  };
34
- /** Allows Google Workspace accounts on these domains, by Google's `hd` claim (not the email's domain). */
34
+ const providerOf = (user) => user.provider ?? (user.id.startsWith('microsoft:') ? 'microsoft' : 'google');
35
+ /**
36
+ * Allows accounts on these domains: Google Workspace accounts by Google's `hd` claim (not the
37
+ * email's domain), and Microsoft work accounts whose address Microsoft verified (a tenant member's
38
+ * username, whose domain the tenant had to prove it owns).
39
+ */
35
40
  export const allowDomains = (domains) => {
36
41
  const allowed = new Set(list(domains));
37
- return (user) => user.hd !== null && allowed.has(user.hd.toLowerCase());
42
+ return (user) => {
43
+ if (providerOf(user) === 'microsoft')
44
+ return user.emailVerified === true && allowed.has(user.email.toLowerCase().split('@').pop() ?? '');
45
+ return user.hd !== null && allowed.has(user.hd.toLowerCase());
46
+ };
47
+ };
48
+ /**
49
+ * Allows Microsoft accounts signed in from these Entra tenants (directory ids), members and guests
50
+ * alike: only the tenant's own admin can add someone to it.
51
+ */
52
+ export const allowTenants = (tenants) => {
53
+ const allowed = new Set(list(tenants));
54
+ return (user) => providerOf(user) === 'microsoft' && typeof user.tid === 'string' && allowed.has(user.tid.toLowerCase());
38
55
  };
39
56
  /** The default: kaviox.com Google Workspace accounts. */
40
57
  export const KAVIOX_DOMAIN = 'kaviox.com';
41
58
  export const allowKaviox = allowDomains(KAVIOX_DOMAIN);
42
59
  /**
43
- * Anyone with a Google account whose address Google has verified. For apps meant to be public;
60
+ * Anyone with a Google or Microsoft account whose address the provider has verified. For apps meant to be public;
44
61
  * named so that a review sees an app opening itself to everyone.
45
62
  */
46
63
  export const allowAnyone = (_user) => true;
@@ -121,11 +138,15 @@ export function createAuth(options) {
121
138
  const key = secret(env), binding = gateway(env);
122
139
  if (!key || !binding)
123
140
  return fail(url, returnTo, 'Sign-in isn\'t set up here yet.');
141
+ const requested = url.searchParams.get('provider');
142
+ if (requested !== null && requested !== 'google' && requested !== 'microsoft')
143
+ return fail(url, returnTo, 'That sign-in link is incomplete. Try again.');
144
+ const provider = requested ?? undefined;
124
145
  const verifier = randomToken(48);
125
146
  const state = randomToken();
126
147
  let location;
127
148
  try {
128
- location = await binding.authorizeUrl({ redirectUri: `${url.origin}${PATHS.callback}`, codeChallenge: await pkceChallenge(verifier), state });
149
+ location = await binding.authorizeUrl({ redirectUri: `${url.origin}${PATHS.callback}`, codeChallenge: await pkceChallenge(verifier), state, ...(provider ? { provider } : {}) });
129
150
  }
130
151
  catch {
131
152
  return fail(url, returnTo, 'Sign-in isn\'t available on this address.');
@@ -145,16 +166,17 @@ export function createAuth(options) {
145
166
  if (url.searchParams.get('error') === 'access_denied')
146
167
  return failed('Sign-in was cancelled. Try again when you\'re ready.');
147
168
  if (url.searchParams.get('error'))
148
- return failed('Google couldn\'t complete sign-in. Try again.');
169
+ return failed('Sign-in couldn\'t be completed. Try again.');
149
170
  const code = url.searchParams.get('code');
150
171
  if (!flow || !code || url.searchParams.get('state') !== flow.state)
151
172
  return failed('That sign-in took too long or was opened in another browser. Try again.');
152
173
  const identity = await binding.redeem(code, String(flow.verifier)).catch(() => null);
153
174
  if (!identity)
154
175
  return failed('That sign-in took too long or was opened in another browser. Try again.');
176
+ const providerName = identity.provider === 'microsoft' ? 'Microsoft' : 'Google';
155
177
  if (!identity.email_verified && !options.allowUnverifiedEmail)
156
- return failed('Google hasn\'t verified that email address. Use an address Google has verified.');
157
- const user = { id: identity.id, email: identity.email.toLowerCase(), name: identity.name, hd: identity.hd };
178
+ return failed(`${providerName} hasn't verified that email address. Use an address ${providerName} has verified.`);
179
+ const user = { id: identity.id, email: identity.email.toLowerCase(), name: identity.name, hd: identity.hd, provider: identity.provider ?? 'google', tid: identity.tid ?? null, emailVerified: identity.email_verified };
158
180
  if (!(await allowed(user, env)))
159
181
  return failed(options.deniedMessage?.(user) ?? `${user.email} doesn't have access. Ask the app's owner for access.`);
160
182
  await options.onSignIn?.(user, env);
@@ -169,7 +191,14 @@ export function createAuth(options) {
169
191
  const payload = key ? await unseal(readCookie(request, cookieName), key, 'session') : null;
170
192
  if (!payload || typeof payload.id !== 'string' || typeof payload.email !== 'string' || typeof payload.name !== 'string')
171
193
  return null;
172
- const user = { id: payload.id, email: payload.email, name: payload.name, hd: typeof payload.hd === 'string' ? payload.hd : null, exp: payload.exp };
194
+ const provider = payload.provider === 'microsoft' || (payload.provider === undefined && payload.id.startsWith('microsoft:')) ? 'microsoft' : 'google';
195
+ const user = {
196
+ id: payload.id, email: payload.email, name: payload.name, hd: typeof payload.hd === 'string' ? payload.hd : null, provider,
197
+ tid: typeof payload.tid === 'string' ? payload.tid : null,
198
+ // Sessions from before this field only exist for addresses that passed the verified-email check, unless the app turned it off.
199
+ emailVerified: typeof payload.emailVerified === 'boolean' ? payload.emailVerified : !options.allowUnverifiedEmail,
200
+ exp: payload.exp,
201
+ };
173
202
  return (await allowed(user, env)) ? user : null;
174
203
  }
175
204
  async function authenticate(request, env) {
package/dist/mcp.d.ts CHANGED
@@ -16,7 +16,7 @@ export interface McpOptions<Env> {
16
16
  handler: (request: Request, env: Env, ctx: ExecutionContext, user: McpUser) => Response | Promise<Response>;
17
17
  /** Shown to clients in the resource metadata. */
18
18
  name?: string;
19
- /** Accept Google addresses Google hasn't verified. Off by default. */
19
+ /** Accept addresses the provider hasn't verified (see createAuth's allowUnverifiedEmail). Off by default. */
20
20
  allowUnverifiedEmail?: boolean;
21
21
  /** The binding's name in env. Default KAVIOX_AUTH. */
22
22
  binding?: string;
package/dist/mcp.js CHANGED
@@ -23,9 +23,10 @@ export function createMcp(options) {
23
23
  const identity = ctx.props;
24
24
  if (!identity?.id || typeof identity.email !== 'string')
25
25
  return forbidden('This token carries no identity.');
26
+ const providerName = identity.provider === 'microsoft' ? 'Microsoft' : 'Google';
26
27
  if (!identity.email_verified && !options.allowUnverifiedEmail)
27
- return forbidden('Google hasn\'t verified this account\'s email address.');
28
- const user = { id: identity.id, email: identity.email.toLowerCase(), name: identity.name, hd: identity.hd, clientId: ctx.auth?.clientId ?? '' };
28
+ return forbidden(`${providerName} hasn't verified this account's email address.`);
29
+ const user = { id: identity.id, email: identity.email.toLowerCase(), name: identity.name, hd: identity.hd, provider: identity.provider ?? 'google', tid: identity.tid ?? null, emailVerified: identity.email_verified, clientId: ctx.auth?.clientId ?? '' };
29
30
  if (!(await allow(user, env)))
30
31
  return forbidden(`${user.email} doesn't have access to this app.`);
31
32
  return options.handler(request, env, ctx, user);
@@ -1,5 +1,10 @@
1
1
  /**
2
2
  * Where to go after signing in: a path on this app, never another site and never a sign-in step.
3
3
  * Anything else becomes "/".
4
+ *
5
+ * The answer is checked in the form it is used: as a path that the callback resolves against the
6
+ * app's origin. Checking only the input isn't enough, because normalising it can change what it
7
+ * points at: "/.//evil.example" and "/a/..//evil.example" become "//evil.example", which a browser
8
+ * reads as another site.
4
9
  */
5
10
  export declare function safeReturnTo(value: string | null | undefined): string;
package/dist/return-to.js CHANGED
@@ -1,15 +1,24 @@
1
+ const BASE = 'https://app.invalid';
1
2
  /**
2
3
  * Where to go after signing in: a path on this app, never another site and never a sign-in step.
3
4
  * Anything else becomes "/".
5
+ *
6
+ * The answer is checked in the form it is used: as a path that the callback resolves against the
7
+ * app's origin. Checking only the input isn't enough, because normalising it can change what it
8
+ * points at: "/.//evil.example" and "/a/..//evil.example" become "//evil.example", which a browser
9
+ * reads as another site.
4
10
  */
5
11
  export function safeReturnTo(value) {
6
- if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\') || /[\u0000-\u001f\\]/.test(value))
12
+ if (typeof value !== 'string' || !value.startsWith('/') || /[\u0000-\u001f\\]/.test(value))
7
13
  return '/';
8
14
  try {
9
- const url = new URL(value, 'https://app.invalid');
10
- if (url.origin !== 'https://app.invalid' || url.pathname === '/auth' || url.pathname.startsWith('/auth/'))
15
+ const url = new URL(value, BASE);
16
+ const path = `${url.pathname}${url.search}${url.hash}`;
17
+ if (url.origin !== BASE || path.startsWith('//') || new URL(path, BASE).origin !== BASE)
11
18
  return '/';
12
- return `${url.pathname}${url.search}${url.hash}`;
19
+ if (url.pathname === '/auth' || url.pathname.startsWith('/auth/'))
20
+ return '/';
21
+ return path;
13
22
  }
14
23
  catch {
15
24
  return '/';
package/dist/types.d.ts CHANGED
@@ -1,14 +1,20 @@
1
- /** Who signed in. Google's own tokens never leave the gateway. */
1
+ /** The providers the gateway signs people in with. */
2
+ export type Provider = 'google' | 'microsoft';
3
+ /** Who signed in. The provider's own tokens never leave the gateway. */
2
4
  export interface Identity {
3
- /** `google:<sub>`, stable for the Google account. */
5
+ /** `google:<sub>`, or `microsoft:<tid>:<oid>`: stable for the account. */
4
6
  id: string;
5
7
  /** Lowercased. */
6
8
  email: string;
7
9
  email_verified: boolean;
8
10
  name: string;
9
- /** The Google Workspace domain, for Workspace accounts only. */
11
+ /** The Google Workspace domain, for Workspace accounts only. Always null for Microsoft. */
10
12
  hd: string | null;
11
- provider: 'google';
13
+ provider: Provider;
14
+ /** Microsoft only: the Entra tenant the account signed in from (lowercased GUID). */
15
+ tid?: string | null;
16
+ /** Microsoft only: the account's object id in that tenant. */
17
+ oid?: string | null;
12
18
  }
13
19
  /** A Claude connector's token, checked by the gateway for one of the app's MCP resources. */
14
20
  export interface ValidatedToken {
@@ -31,6 +37,7 @@ export interface GatewayBinding {
31
37
  redirectUri: string;
32
38
  codeChallenge: string;
33
39
  state: string;
40
+ provider?: Provider;
34
41
  }): Promise<string>;
35
42
  /** The identity a one-time code was issued for, or null. Any attempt uses the code up. */
36
43
  redeem(code: string, verifier: string): Promise<Identity | null>;
package/package.json CHANGED
@@ -1,18 +1,35 @@
1
1
  {
2
2
  "name": "@kaviox/auth",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Sign-in for Kaviox apps on Cloudflare Workers, through the Kaviox sign-in gateway: middleware, callback, sign-out, sessions and MCP token checks.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
- "repository": { "type": "git", "url": "git+https://github.com/kaviox/platform.git", "directory": "packages/auth" },
9
- "engines": { "node": ">=22.13.0" },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kaviox/platform.git",
11
+ "directory": "packages/auth"
12
+ },
13
+ "engines": {
14
+ "node": ">=22.13.0"
15
+ },
10
16
  "exports": {
11
- ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
12
- "./mcp": { "types": "./dist/mcp.d.ts", "default": "./dist/mcp.js" }
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./mcp": {
22
+ "types": "./dist/mcp.d.ts",
23
+ "default": "./dist/mcp.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public"
13
32
  },
14
- "files": ["dist", "README.md"],
15
- "publishConfig": { "access": "public" },
16
33
  "scripts": {
17
34
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
18
35
  "typecheck": "tsc --noEmit",