@kaviox/auth 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # @kaviox/auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sign-in for Kaviox apps on Cloudflare Workers, through the Kaviox sign-in gateway
4
+ (`auth.kaviox.com`, and `staging.auth.kaviox.com` for staging and PR previews). The app needs no
5
+ Google client, client secret or preview relay of its own. See
6
+ [docs/sign-in-gateway.md](https://github.com/kaviox/platform/blob/main/docs/sign-in-gateway.md)
7
+ in kaviox/platform.
8
+
9
+ ## What the platform does for you
10
+
11
+ When the app's entry in kaviox/platform's `cloudflare/apps.json` has `"signIn"`, the platform:
12
+
13
+ - adds the `KAVIOX_AUTH` Service Binding to every deploy (production binds the production
14
+ gateway, staging and previews the staging one), naming the app's repository. The app never
15
+ declares it.
16
+ - generates `AUTH_SESSION_SECRET` on the app's Workers. Previews inherit staging's.
17
+ - sends sign-ins only to the app's `hosts` in `apps.json`, plus its PR previews on staging.
18
+
19
+ ## Web sign-in
20
+
21
+ ```ts
22
+ import { allowEmails, createAuth } from '@kaviox/auth';
23
+
24
+ const auth = createAuth<Env>({
25
+ cookieName: '__Host-myapp_session',
26
+ sessionDays: 30,
27
+ // Leave allow out and only kaviox.com Google Workspace accounts get in.
28
+ allow: (user, env) => allowEmails(env.AUTH_ALLOWED_EMAILS ?? '')(user),
29
+ publicPaths: ['/privacy', '/favicon.ico', '/robots.txt'],
30
+ signInPage: '/signin', // optional: your own page, linking to /auth/signin?return_to=…
31
+ });
32
+
33
+ export default {
34
+ async fetch(request: Request, env: Env, ctx: ExecutionContext) {
35
+ const result = await auth.authenticate(request, env);
36
+ if (result instanceof Response) return result; // sign-in steps, redirects, 401s
37
+ return app.fetch(result, env, ctx); // with x-kaviox-user-id, -email, -name
38
+ },
39
+ };
40
+ ```
41
+
42
+ `authenticate` serves `/auth/signin`, `/auth/callback` and `/auth/signout`, and removes any
43
+ identity header a browser sends before setting its own. The allow check runs at sign-in and on
44
+ every request.
45
+
46
+ **Nothing is open by default.** Without an `allow` check, only kaviox.com Google Workspace
47
+ accounts get in, checked by Google's Workspace claim (`hd`), so a personal Google account made for
48
+ an `@kaviox.com` address doesn't count. An app opens up only by saying so: its own check, or
49
+ `allow: allowAnyone`, which a review will see. Addresses Google hasn't verified are refused either
50
+ way, unless the app sets `allowUnverifiedEmail`.
51
+
52
+ | Option | Default | |
53
+ |---|---|---|
54
+ | `cookieName` | required | The session cookie, a `__Host-` name |
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 |
57
+ | `onSignIn(user, env)` | none | Runs after a sign-in is allowed, for example to record it |
58
+ | `identityHeaders` | `x-kaviox-user-id`, `-email`, `-name` | Fleet-OS keeps its `oai-authenticated-user-*` names |
59
+ | `publicPaths` | none | Exact paths anyone may load |
60
+ | `apiPrefixes` | `['/api/']` | Signed-out requests here get 401 JSON instead of a redirect |
61
+ | `signInPage` | none | Your page for signed-out visitors and failures (`?return_to=`, `?error=`) |
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 |
64
+
65
+ Users are `{ id, email, name, hd }`; `id` is `google:<sub>`, the format Fleet-OS and Habits store.
66
+
67
+ ## Claude connectors (MCP)
68
+
69
+ ```ts
70
+ import { createMcp } from '@kaviox/auth/mcp';
71
+
72
+ const mcp = createMcp<Env>({
73
+ allow: (user, env) => allowEmails(env.AUTH_ALLOWED_EMAILS ?? '')(user), // default: allowKaviox
74
+ handler: (request, env, ctx, user) => mcpServer.fetch(request, env, ctx, user),
75
+ });
76
+
77
+ // In fetch, before authenticate:
78
+ if (mcp.matches(new URL(request.url))) return mcp.fetch(request, env, ctx);
79
+ ```
80
+
81
+ The endpoint is `/mcp` on each of the app's hosts in `apps.json`. It publishes its protected
82
+ resource metadata naming the gateway, answers unauthenticated requests with the Bearer challenge,
83
+ and checks each token over the binding. The gateway binds every token to that one endpoint.
84
+ Previews have no MCP endpoint: their hosts change with every PR.
85
+
86
+ Workers that import `@kaviox/auth/mcp` log one warning per isolate, "CIMD (Client ID Metadata
87
+ Document) is disabled". It comes from the OAuth library and matters only to an authorization
88
+ server, which here is the gateway. Apps don't need that compatibility flag.
89
+
90
+ ## Development
91
+
92
+ ```bash
93
+ npm test # node:test, against a fake gateway binding
94
+ npm run build # dist/, what npm publishes
95
+ ```
96
+
97
+ The real gateway and binding run end to end in workerd in kaviox/platform's
98
+ `gateway/test/flow.test.ts`. Versions publish to npm from kaviox/platform's main with
99
+ `.github/workflows/package-auth-publish.yml` (npm trusted publishing, no token).
@@ -0,0 +1,22 @@
1
+ export declare function base64url(bytes: Uint8Array): string;
2
+ export declare function fromBase64url(value: string): Uint8Array;
3
+ /** A random URL-safe token with `size` bytes of entropy. */
4
+ export declare const randomToken: (size?: number) => string;
5
+ export declare function sha256(value: string): Promise<string>;
6
+ /** The S256 PKCE challenge for a verifier (RFC 7636). */
7
+ export declare const pkceChallenge: (verifier: string) => Promise<string>;
8
+ export declare const PKCE_VERIFIER: RegExp;
9
+ export declare const PKCE_CHALLENGE: RegExp;
10
+ export declare const now: () => number;
11
+ /** Constant-time comparison of two strings. */
12
+ export declare function sameString(a: string, b: string): boolean;
13
+ /**
14
+ * A tamper-proof value: base64url(JSON).signature. `purpose` keeps a value made for one use from
15
+ * being accepted for another. Expired values read as null.
16
+ */
17
+ export declare function seal(payload: Record<string, unknown> & {
18
+ exp: number;
19
+ }, secret: string, purpose: string): Promise<string>;
20
+ export declare function unseal(token: string | null | undefined, secret: string, purpose: string): Promise<Record<string, unknown> | null>;
21
+ /** The secret, if it is set and long enough to sign with. */
22
+ export declare function usableSecret(value: string | undefined): string | null;
package/dist/crypto.js ADDED
@@ -0,0 +1,63 @@
1
+ // Encoding, random values, hashing and sealed values, on Web Crypto only (Workers and Node 22).
2
+ const encoder = new TextEncoder();
3
+ export function base64url(bytes) {
4
+ let binary = '';
5
+ for (const byte of bytes)
6
+ binary += String.fromCharCode(byte);
7
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
8
+ }
9
+ export function fromBase64url(value) {
10
+ const normalized = value.replaceAll('-', '+').replaceAll('_', '/');
11
+ const binary = atob(normalized + '='.repeat((4 - (normalized.length % 4)) % 4));
12
+ return Uint8Array.from(binary, character => character.charCodeAt(0));
13
+ }
14
+ /** A random URL-safe token with `size` bytes of entropy. */
15
+ export const randomToken = (size = 32) => base64url(crypto.getRandomValues(new Uint8Array(size)));
16
+ export async function sha256(value) {
17
+ return base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(value))));
18
+ }
19
+ /** The S256 PKCE challenge for a verifier (RFC 7636). */
20
+ export const pkceChallenge = (verifier) => sha256(verifier);
21
+ // RFC 7636: 43 to 128 unreserved characters. S256 challenges are always 43 base64url characters.
22
+ export const PKCE_VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
23
+ export const PKCE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
24
+ export const now = () => Math.floor(Date.now() / 1000);
25
+ /** Constant-time comparison of two strings. */
26
+ export function sameString(a, b) {
27
+ if (a.length !== b.length)
28
+ return false;
29
+ let difference = 0;
30
+ for (let i = 0; i < a.length; i++)
31
+ difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
32
+ return difference === 0;
33
+ }
34
+ const hmacKey = (secret) => crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
35
+ /**
36
+ * A tamper-proof value: base64url(JSON).signature. `purpose` keeps a value made for one use from
37
+ * being accepted for another. Expired values read as null.
38
+ */
39
+ export async function seal(payload, secret, purpose) {
40
+ const body = base64url(encoder.encode(JSON.stringify(payload)));
41
+ const signature = new Uint8Array(await crypto.subtle.sign('HMAC', await hmacKey(secret), encoder.encode(`${purpose}.${body}`)));
42
+ return `${body}.${base64url(signature)}`;
43
+ }
44
+ export async function unseal(token, secret, purpose) {
45
+ const [body, signature, ...rest] = token?.split('.') ?? [];
46
+ if (!body || !signature || rest.length)
47
+ return null;
48
+ try {
49
+ const valid = await crypto.subtle.verify('HMAC', await hmacKey(secret), fromBase64url(signature), encoder.encode(`${purpose}.${body}`));
50
+ if (!valid)
51
+ return null;
52
+ const payload = JSON.parse(new TextDecoder().decode(fromBase64url(body)));
53
+ return payload && typeof payload === 'object' && typeof payload.exp === 'number' && payload.exp > now() ? payload : null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ /** The secret, if it is set and long enough to sign with. */
60
+ export function usableSecret(value) {
61
+ const secret = value?.trim();
62
+ return secret && secret.length >= 32 ? secret : null;
63
+ }
@@ -0,0 +1,97 @@
1
+ import { safeReturnTo } from './return-to.ts';
2
+ export type { GatewayBinding, Identity, ValidatedToken } from './types.ts';
3
+ export { safeReturnTo };
4
+ export declare const PATHS: {
5
+ readonly signIn: "/auth/signin";
6
+ readonly callback: "/auth/callback";
7
+ readonly signOut: "/auth/signout";
8
+ };
9
+ export declare const DEFAULT_BINDING = "KAVIOX_AUTH";
10
+ export declare const DEFAULT_SECRET = "AUTH_SESSION_SECRET";
11
+ /** What a session holds, and what the allow check sees. */
12
+ export interface User {
13
+ /** `google:<sub>`. */
14
+ id: string;
15
+ email: string;
16
+ name: string;
17
+ hd: string | null;
18
+ }
19
+ export interface Session extends User {
20
+ exp: number;
21
+ }
22
+ export interface IdentityHeaders {
23
+ id: string;
24
+ email: string;
25
+ name: string;
26
+ /** Also set to "percent-encoded-utf-8", for apps that read it (Fleet-OS). */
27
+ nameEncoding?: string;
28
+ }
29
+ export interface AuthOptions<Env> {
30
+ /** The session cookie. Must start with __Host-. */
31
+ cookieName: string;
32
+ /** How long a session lasts. Default 30 days. */
33
+ sessionDays?: number;
34
+ /**
35
+ * Who may use the app. Checked at sign-in and on every request. Default: kaviox.com Google
36
+ * Workspace accounts only (allowKaviox). Pass allowAnyone, or your own check, to open it up.
37
+ */
38
+ allow?: (user: User, env: Env) => boolean | Promise<boolean>;
39
+ /** Runs after a sign-in is allowed, before the session starts (for example, to record it). */
40
+ onSignIn?: (user: User, env: Env) => void | Promise<void>;
41
+ /** What to tell someone the allow check refused. */
42
+ deniedMessage?: (user: User) => string;
43
+ /** The headers the app reads. Default x-kaviox-user-id, x-kaviox-user-email and x-kaviox-user-name. */
44
+ identityHeaders?: IdentityHeaders;
45
+ /** Paths anyone may load (exact matches). They must never show the app's data. */
46
+ publicPaths?: Iterable<string>;
47
+ /** Path prefixes that answer 401 JSON instead of redirecting. Default ['/api/']. */
48
+ apiPrefixes?: string[];
49
+ /**
50
+ * The app's own sign-in page, shown to signed-out visitors, with ?return_to= and, after a
51
+ * failure, ?error=. It links to /auth/signin?return_to=…. Without one, visitors go straight to
52
+ * the gateway and failures show a plain page.
53
+ */
54
+ signInPage?: string;
55
+ /** Accept Google addresses Google hasn't verified. Off by default: allow checks trust the email. */
56
+ allowUnverifiedEmail?: boolean;
57
+ /**
58
+ * Local development: when DEV_AUTH_BYPASS is "true" on localhost, requests pass without a
59
+ * sign-in. As this user when given (Habits), or unchanged when null (Fleet-OS). Default null.
60
+ */
61
+ devUser?: User | null;
62
+ /** The binding's name in env. Default KAVIOX_AUTH. */
63
+ binding?: string;
64
+ /** The session secret's name in env. Default AUTH_SESSION_SECRET. */
65
+ secret?: string;
66
+ }
67
+ export declare const DEFAULT_HEADERS: IdentityHeaders;
68
+ /** Allows these addresses (a list, or a comma- or space-separated string such as a Worker var). */
69
+ 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). */
71
+ export declare const allowDomains: (domains: string | Iterable<string>) => (user: User) => boolean;
72
+ /** The default: kaviox.com Google Workspace accounts. */
73
+ export declare const KAVIOX_DOMAIN = "kaviox.com";
74
+ export declare const allowKaviox: (user: User) => boolean;
75
+ /**
76
+ * Anyone with a Google account whose address Google has verified. For apps meant to be public;
77
+ * named so that a review sees an app opening itself to everyone.
78
+ */
79
+ export declare const allowAnyone: (_user: User) => boolean;
80
+ /** Allows anyone any of the checks allow. */
81
+ export declare const allowAny: <Env>(...checks: Array<(user: User, env: Env) => boolean | Promise<boolean>>) => (user: User, env: Env) => Promise<boolean>;
82
+ export declare function readCookie(request: Request, name: string): string | null;
83
+ export declare function isLocalBypass(url: URL, env: unknown): boolean;
84
+ export interface Auth<Env> {
85
+ /** Runs before the app on every request: a Response to send as is, or the request to pass on. */
86
+ authenticate(request: Request, env: Env): Promise<Response | Request>;
87
+ /** The signed-in, allowed person, or null. */
88
+ readSession(request: Request, env: Env): Promise<Session | null>;
89
+ signIn(request: Request, env: Env): Promise<Response>;
90
+ callback(request: Request, env: Env): Promise<Response>;
91
+ signOut(request: Request): Response;
92
+ /** The headers this app reads. */
93
+ headers: IdentityHeaders;
94
+ }
95
+ export declare function createAuth<Env>(options: AuthOptions<Env>): Auth<Env>;
96
+ /** A random value for AUTH_SESSION_SECRET, for tests and local development. */
97
+ export declare const newSessionSecret: () => string;
package/dist/index.js ADDED
@@ -0,0 +1,200 @@
1
+ // Sign-in for Kaviox apps on Cloudflare Workers, through the Kaviox sign-in gateway.
2
+ //
3
+ // Started from kaviox/fleet-os lib/auth.ts, with what differs between Fleet-OS and Habits made
4
+ // options. The app's Worker runs `authenticate` before the app sees each request. A signed-in,
5
+ // allowed person gets the identity headers the app reads; anything a browser sends under those
6
+ // names is removed first. Everyone else is sent to sign in (pages) or gets a 401 (API).
7
+ //
8
+ // Signing in: /auth/signin sends the browser to the gateway (auth.kaviox.com, or
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
11
+ // KAVIOX_AUTH Service Binding with the PKCE verifier. The platform adds that binding to every
12
+ // deploy, so the app needs no Google client, client secret or preview relay of its own.
13
+ //
14
+ // The session stays in the app: its own __Host- cookie, signed with AUTH_SESSION_SECRET (which
15
+ // the platform generates), lasting as long as the app chooses. The allow check runs at sign-in and
16
+ // again on every request, so removing someone takes effect at once. Without one, only kaviox.com
17
+ // Google Workspace accounts get in: an app opens up only by saying so (allowAnyone, or its own check).
18
+ import { base64url, now, pkceChallenge, randomToken, seal, unseal, usableSecret } from "./crypto.js";
19
+ import { safeReturnTo } from "./return-to.js";
20
+ export { safeReturnTo };
21
+ export const PATHS = { signIn: '/auth/signin', callback: '/auth/callback', signOut: '/auth/signout' };
22
+ export const DEFAULT_BINDING = 'KAVIOX_AUTH';
23
+ export const DEFAULT_SECRET = 'AUTH_SESSION_SECRET';
24
+ const FLOW_SECONDS = 10 * 60;
25
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
26
+ export const DEFAULT_HEADERS = { id: 'x-kaviox-user-id', email: 'x-kaviox-user-email', name: 'x-kaviox-user-name' };
27
+ // ---- Allow checks ------------------------------------------------------------------------------
28
+ const list = (value) => (typeof value === 'string' ? value.split(/[\s,]+/) : [...(value ?? [])]).map(item => item.trim().toLowerCase()).filter(Boolean);
29
+ /** Allows these addresses (a list, or a comma- or space-separated string such as a Worker var). */
30
+ export const allowEmails = (emails) => {
31
+ const allowed = new Set(list(emails));
32
+ return (user) => allowed.has(user.email.toLowerCase());
33
+ };
34
+ /** Allows Google Workspace accounts on these domains, by Google's `hd` claim (not the email's domain). */
35
+ export const allowDomains = (domains) => {
36
+ const allowed = new Set(list(domains));
37
+ return (user) => user.hd !== null && allowed.has(user.hd.toLowerCase());
38
+ };
39
+ /** The default: kaviox.com Google Workspace accounts. */
40
+ export const KAVIOX_DOMAIN = 'kaviox.com';
41
+ export const allowKaviox = allowDomains(KAVIOX_DOMAIN);
42
+ /**
43
+ * Anyone with a Google account whose address Google has verified. For apps meant to be public;
44
+ * named so that a review sees an app opening itself to everyone.
45
+ */
46
+ export const allowAnyone = (_user) => true;
47
+ /** Allows anyone any of the checks allow. */
48
+ export const allowAny = (...checks) => async (user, env) => {
49
+ for (const check of checks)
50
+ if (await check(user, env))
51
+ return true;
52
+ return false;
53
+ };
54
+ // ---- Responses ---------------------------------------------------------------------------------
55
+ const cookie = (name, value, maxAge) => `${name}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
56
+ export function readCookie(request, name) {
57
+ const prefix = `${name}=`;
58
+ return request.headers.get('cookie')?.split(';').map(part => part.trim()).find(part => part.startsWith(prefix))?.slice(prefix.length) ?? null;
59
+ }
60
+ function redirect(location, cookies = []) {
61
+ const headers = new Headers({ Location: location.toString(), 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
62
+ for (const value of cookies)
63
+ headers.append('Set-Cookie', value);
64
+ return new Response(null, { status: 302, headers });
65
+ }
66
+ const plain = (message, status, cookies = []) => {
67
+ const headers = new Headers({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
68
+ for (const value of cookies)
69
+ headers.append('Set-Cookie', value);
70
+ return new Response(message, { status, headers });
71
+ };
72
+ export function isLocalBypass(url, env) {
73
+ return env?.DEV_AUTH_BYPASS === 'true' && LOCAL_HOSTS.has(url.hostname);
74
+ }
75
+ export function createAuth(options) {
76
+ const cookieName = options.cookieName;
77
+ if (!/^__Host-[A-Za-z0-9_-]+$/.test(cookieName))
78
+ throw new Error('cookieName must be a __Host- cookie name');
79
+ const flowCookie = `${cookieName}_flow`;
80
+ const sessionSeconds = Math.round((options.sessionDays ?? 30) * 86400);
81
+ if (!(sessionSeconds > 0))
82
+ throw new Error('sessionDays must be positive');
83
+ const headerNames = options.identityHeaders ?? DEFAULT_HEADERS;
84
+ const publicPaths = new Set(options.publicPaths ?? []);
85
+ const apiPrefixes = options.apiPrefixes ?? ['/api/'];
86
+ const bindingName = options.binding ?? DEFAULT_BINDING;
87
+ const secretName = options.secret ?? DEFAULT_SECRET;
88
+ const devUser = options.devUser ?? null;
89
+ const gateway = (env) => (env?.[bindingName] ?? null);
90
+ const secret = (env) => usableSecret(env?.[secretName]);
91
+ const allow = options.allow ?? allowKaviox;
92
+ const allowed = async (user, env) => Boolean(await allow(user, env));
93
+ // Where to send someone who needs to sign in, or who just failed to.
94
+ const signInLocation = (base, returnTo = '/', error) => {
95
+ const url = new URL(options.signInPage ?? PATHS.signIn, base);
96
+ if (returnTo !== '/')
97
+ url.searchParams.set('return_to', returnTo);
98
+ if (error && options.signInPage)
99
+ url.searchParams.set('error', error);
100
+ return url;
101
+ };
102
+ const fail = (url, returnTo, message, cookies = []) => options.signInPage ? redirect(signInLocation(url, returnTo, message), cookies) : plain(`${message}\n\nTry again: ${new URL(`${PATHS.signIn}${returnTo === '/' ? '' : `?return_to=${encodeURIComponent(returnTo)}`}`, url)}`, 400, cookies);
103
+ function strip(request) {
104
+ const headers = new Headers(request.headers);
105
+ for (const name of [headerNames.id, headerNames.email, headerNames.name, headerNames.nameEncoding])
106
+ if (name)
107
+ headers.delete(name);
108
+ return headers;
109
+ }
110
+ function withUser(request, headers, user) {
111
+ headers.set(headerNames.id, user.id);
112
+ headers.set(headerNames.email, user.email);
113
+ headers.set(headerNames.name, encodeURIComponent(user.name));
114
+ if (headerNames.nameEncoding)
115
+ headers.set(headerNames.nameEncoding, 'percent-encoded-utf-8');
116
+ return new Request(request, { headers });
117
+ }
118
+ async function signIn(request, env) {
119
+ const url = new URL(request.url);
120
+ const returnTo = safeReturnTo(url.searchParams.get('return_to'));
121
+ const key = secret(env), binding = gateway(env);
122
+ if (!key || !binding)
123
+ return fail(url, returnTo, 'Sign-in isn\'t set up here yet.');
124
+ const verifier = randomToken(48);
125
+ const state = randomToken();
126
+ let location;
127
+ try {
128
+ location = await binding.authorizeUrl({ redirectUri: `${url.origin}${PATHS.callback}`, codeChallenge: await pkceChallenge(verifier), state });
129
+ }
130
+ catch {
131
+ return fail(url, returnTo, 'Sign-in isn\'t available on this address.');
132
+ }
133
+ const flow = await seal({ state, verifier, returnTo, exp: now() + FLOW_SECONDS }, key, 'flow');
134
+ return redirect(location, [cookie(flowCookie, flow, FLOW_SECONDS)]);
135
+ }
136
+ async function callback(request, env) {
137
+ const url = new URL(request.url);
138
+ const key = secret(env), binding = gateway(env);
139
+ const flow = key ? await unseal(readCookie(request, flowCookie), key, 'flow') : null;
140
+ const returnTo = safeReturnTo(typeof flow?.returnTo === 'string' ? flow.returnTo : '/');
141
+ const clear = cookie(flowCookie, '', 0);
142
+ const failed = (message) => fail(url, returnTo, message, [clear]);
143
+ if (!key || !binding)
144
+ return failed('Sign-in isn\'t set up here yet.');
145
+ if (url.searchParams.get('error') === 'access_denied')
146
+ return failed('Sign-in was cancelled. Try again when you\'re ready.');
147
+ if (url.searchParams.get('error'))
148
+ return failed('Google couldn\'t complete sign-in. Try again.');
149
+ const code = url.searchParams.get('code');
150
+ if (!flow || !code || url.searchParams.get('state') !== flow.state)
151
+ return failed('That sign-in took too long or was opened in another browser. Try again.');
152
+ const identity = await binding.redeem(code, String(flow.verifier)).catch(() => null);
153
+ if (!identity)
154
+ return failed('That sign-in took too long or was opened in another browser. Try again.');
155
+ 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 };
158
+ if (!(await allowed(user, env)))
159
+ return failed(options.deniedMessage?.(user) ?? `${user.email} doesn't have access. Ask the app's owner for access.`);
160
+ await options.onSignIn?.(user, env);
161
+ const session = await seal({ ...user, exp: now() + sessionSeconds }, key, 'session');
162
+ return redirect(new URL(returnTo, url), [cookie(cookieName, session, sessionSeconds), clear]);
163
+ }
164
+ function signOut(request) {
165
+ return redirect(new URL(options.signInPage ?? '/', request.url), [cookie(cookieName, '', 0)]);
166
+ }
167
+ async function readSession(request, env) {
168
+ const key = secret(env);
169
+ const payload = key ? await unseal(readCookie(request, cookieName), key, 'session') : null;
170
+ if (!payload || typeof payload.id !== 'string' || typeof payload.email !== 'string' || typeof payload.name !== 'string')
171
+ 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 };
173
+ return (await allowed(user, env)) ? user : null;
174
+ }
175
+ async function authenticate(request, env) {
176
+ const url = new URL(request.url);
177
+ const headers = strip(request);
178
+ if (isLocalBypass(url, env))
179
+ return devUser ? withUser(request, headers, devUser) : new Request(request, { headers });
180
+ if (url.pathname === PATHS.signIn)
181
+ return signIn(request, env);
182
+ if (url.pathname === PATHS.callback)
183
+ return callback(request, env);
184
+ if (url.pathname === PATHS.signOut)
185
+ return signOut(request);
186
+ const user = await readSession(request, env);
187
+ if (user)
188
+ return withUser(request, headers, user);
189
+ if (publicPaths.has(url.pathname) || (options.signInPage && url.pathname === options.signInPage))
190
+ return new Request(request, { headers });
191
+ const noStore = { 'Cache-Control': 'no-store' };
192
+ if (apiPrefixes.some(prefix => url.pathname.startsWith(prefix)))
193
+ return Response.json({ error: 'Sign in to continue.' }, { status: 401, headers: noStore });
194
+ const wantsPage = (request.method === 'GET' || request.method === 'HEAD') && (request.headers.get('accept') ?? '').includes('text/html');
195
+ return wantsPage ? redirect(signInLocation(url, safeReturnTo(`${url.pathname}${url.search}`))) : plain('Sign in to continue.', 401);
196
+ }
197
+ return { authenticate, readSession, signIn, callback, signOut, headers: headerNames };
198
+ }
199
+ /** A random value for AUTH_SESSION_SECRET, for tests and local development. */
200
+ export const newSessionSecret = () => base64url(crypto.getRandomValues(new Uint8Array(32)));
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { type User } from './index.ts';
2
+ export declare const MCP_PATH = "/mcp";
3
+ /** The one scope the gateway grants. */
4
+ export declare const MCP_SCOPES: string[];
5
+ export interface McpUser extends User {
6
+ /** The Claude connector the token was issued to. */
7
+ clientId: string;
8
+ }
9
+ export interface McpOptions<Env> {
10
+ /**
11
+ * Who may use the app's tools: usually the same check as the app's web sign-in. Default:
12
+ * kaviox.com Google Workspace accounts only (allowKaviox).
13
+ */
14
+ allow?: (user: User, env: Env) => boolean | Promise<boolean>;
15
+ /** The MCP server, called with the person the token was issued to. */
16
+ handler: (request: Request, env: Env, ctx: ExecutionContext, user: McpUser) => Response | Promise<Response>;
17
+ /** Shown to clients in the resource metadata. */
18
+ name?: string;
19
+ /** Accept Google addresses Google hasn't verified. Off by default. */
20
+ allowUnverifiedEmail?: boolean;
21
+ /** The binding's name in env. Default KAVIOX_AUTH. */
22
+ binding?: string;
23
+ }
24
+ export interface Mcp<Env> {
25
+ /** Whether this request is for the MCP endpoint or its metadata. */
26
+ matches(url: URL): boolean;
27
+ fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
28
+ }
29
+ export declare function createMcp<Env>(options: McpOptions<Env>): Mcp<Env>;
package/dist/mcp.js ADDED
@@ -0,0 +1,63 @@
1
+ // An app's MCP endpoint (Claude connectors), with the Kaviox sign-in gateway as its authorization
2
+ // server. The endpoint is /mcp on each of the app's hosts in cloudflare/apps.json; the gateway
3
+ // binds every token to one of those, and this checks each token over the KAVIOX_AUTH binding.
4
+ //
5
+ // Built on @cloudflare/workers-oauth-provider's OAuthResourceServer: it publishes the RFC 9728
6
+ // metadata pointing at the gateway, answers unauthenticated requests with the Bearer challenge,
7
+ // and accepts only tokens whose audience is this endpoint. The app's allow check runs on top.
8
+ import { OAuthResourceServer } from '@cloudflare/workers-oauth-provider';
9
+ import { DEFAULT_BINDING, allowKaviox } from "./index.js";
10
+ export const MCP_PATH = '/mcp';
11
+ /** The one scope the gateway grants. */
12
+ export const MCP_SCOPES = ['mcp'];
13
+ const METADATA_PATH = `/.well-known/oauth-protected-resource${MCP_PATH}`;
14
+ const forbidden = (message) => Response.json({ error: 'forbidden', error_description: message }, { status: 403, headers: { 'Cache-Control': 'no-store' } });
15
+ export function createMcp(options) {
16
+ const bindingName = options.binding ?? DEFAULT_BINDING;
17
+ const allow = options.allow ?? allowKaviox;
18
+ const gateway = (env) => (env?.[bindingName] ?? null);
19
+ const issuers = new WeakMap();
20
+ const servers = new Map();
21
+ const handler = {
22
+ async fetch(request, env, ctx) {
23
+ const identity = ctx.props;
24
+ if (!identity?.id || typeof identity.email !== 'string')
25
+ return forbidden('This token carries no identity.');
26
+ 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 ?? '' };
29
+ if (!(await allow(user, env)))
30
+ return forbidden(`${user.email} doesn't have access to this app.`);
31
+ return options.handler(request, env, ctx, user);
32
+ },
33
+ };
34
+ function server(resource, issuer) {
35
+ const key = `${resource} ${issuer}`;
36
+ let found = servers.get(key);
37
+ if (!found) {
38
+ found = new OAuthResourceServer({
39
+ resourceMetadata: { resource, authorization_servers: [issuer], ...(options.name ? { resource_name: options.name } : {}) },
40
+ requiredScopes: MCP_SCOPES,
41
+ validateToken: env => (target, token) => gateway(env).validateToken(target, token),
42
+ handler,
43
+ });
44
+ servers.set(key, found);
45
+ }
46
+ return found;
47
+ }
48
+ return {
49
+ matches: url => url.pathname === MCP_PATH || url.pathname.startsWith(`${MCP_PATH}/`) || url.pathname === METADATA_PATH,
50
+ async fetch(request, env, ctx) {
51
+ const binding = gateway(env);
52
+ if (!binding)
53
+ return Response.json({ error: 'temporarily_unavailable', error_description: 'Sign-in isn\'t set up here yet.' }, { status: 503 });
54
+ let issuer = issuers.get(binding);
55
+ if (!issuer) {
56
+ issuer = binding.issuer().catch(error => { issuers.delete(binding); throw error; });
57
+ issuers.set(binding, issuer);
58
+ }
59
+ const resource = `${new URL(request.url).origin}${MCP_PATH}`;
60
+ return server(resource, await issuer).fetch(request, env, ctx);
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Where to go after signing in: a path on this app, never another site and never a sign-in step.
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.
9
+ */
10
+ export declare function safeReturnTo(value: string | null | undefined): string;
@@ -0,0 +1,26 @@
1
+ const BASE = 'https://app.invalid';
2
+ /**
3
+ * Where to go after signing in: a path on this app, never another site and never a sign-in step.
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.
10
+ */
11
+ export function safeReturnTo(value) {
12
+ if (typeof value !== 'string' || !value.startsWith('/') || /[\u0000-\u001f\\]/.test(value))
13
+ return '/';
14
+ try {
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)
18
+ return '/';
19
+ if (url.pathname === '/auth' || url.pathname.startsWith('/auth/'))
20
+ return '/';
21
+ return path;
22
+ }
23
+ catch {
24
+ return '/';
25
+ }
26
+ }
@@ -0,0 +1,39 @@
1
+ /** Who signed in. Google's own tokens never leave the gateway. */
2
+ export interface Identity {
3
+ /** `google:<sub>`, stable for the Google account. */
4
+ id: string;
5
+ /** Lowercased. */
6
+ email: string;
7
+ email_verified: boolean;
8
+ name: string;
9
+ /** The Google Workspace domain, for Workspace accounts only. */
10
+ hd: string | null;
11
+ provider: 'google';
12
+ }
13
+ /** A Claude connector's token, checked by the gateway for one of the app's MCP resources. */
14
+ export interface ValidatedToken {
15
+ props: Identity;
16
+ audience: string;
17
+ expiresAt: number;
18
+ scope: string[];
19
+ userId: string;
20
+ clientId: string;
21
+ }
22
+ /**
23
+ * The gateway's binding, which the platform adds to every deploy of an app that signs in (as
24
+ * KAVIOX_AUTH). Every method acts for the app the binding names; the app can't choose another.
25
+ */
26
+ export interface GatewayBinding {
27
+ /** The gateway's issuer: https://auth.kaviox.com or https://staging.auth.kaviox.com. */
28
+ issuer(): Promise<string>;
29
+ /** Where to send the browser to sign in. Rejects a callback that isn't on one of the app's hosts. */
30
+ authorizeUrl(request: {
31
+ redirectUri: string;
32
+ codeChallenge: string;
33
+ state: string;
34
+ }): Promise<string>;
35
+ /** The identity a one-time code was issued for, or null. Any attempt uses the code up. */
36
+ redeem(code: string, verifier: string): Promise<Identity | null>;
37
+ /** Checks a bearer token for one of the app's MCP resources. */
38
+ validateToken(resource: string, token: string): Promise<ValidatedToken | null>;
39
+ }
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ // The contract between the sign-in gateway and the apps: what its Service Binding offers and what
2
+ // it returns. The gateway (kaviox/platform gateway/) implements it; this package calls it.
3
+ export {};
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@kaviox/auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
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
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "sideEffects": false,
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
+ },
16
+ "exports": {
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"
32
+ },
33
+ "scripts": {
34
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
35
+ "typecheck": "tsc --noEmit",
36
+ "test": "node --experimental-strip-types --no-warnings=ExperimentalWarning --test 'test/**/*.test.ts'",
37
+ "prepublishOnly": "npm run build"
38
+ },
39
+ "dependencies": {
40
+ "@cloudflare/workers-oauth-provider": "1.2.4"
41
+ },
42
+ "devDependencies": {
43
+ "@cloudflare/workers-types": "4.20260702.1",
44
+ "@types/node": "22.19.19",
45
+ "typescript": "5.9.3"
46
+ }
47
+ }