cauthy-auth 0.13.0 → 0.15.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 +8 -0
- package/dist/client.d.mts +27 -1
- package/dist/client.d.ts +27 -1
- package/dist/client.js +5 -0
- package/dist/client.js.map +1 -1
- package/dist/client.mjs +5 -0
- package/dist/client.mjs.map +1 -1
- package/dist/index.js +27 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +27 -1
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.d.mts +114 -0
- package/dist/mcp.d.ts +114 -0
- package/dist/mcp.js +242 -0
- package/dist/mcp.js.map +1 -0
- package/dist/mcp.mjs +215 -0
- package/dist/mcp.mjs.map +1 -0
- package/dist/react.d.mts +31 -1
- package/dist/react.d.ts +31 -1
- package/dist/react.js +43 -0
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +43 -0
- package/dist/react.mjs.map +1 -1
- package/dist/svelte.js +5 -0
- package/dist/svelte.js.map +1 -1
- package/dist/svelte.mjs +5 -0
- package/dist/svelte.mjs.map +1 -1
- package/dist/vue.js +5 -0
- package/dist/vue.js.map +1 -1
- package/dist/vue.mjs +5 -0
- package/dist/vue.mjs.map +1 -1
- package/package.json +6 -1
package/dist/mcp.mjs
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// src/mcp.ts
|
|
2
|
+
import { jwtVerify as jwtVerify2 } from "jose";
|
|
3
|
+
|
|
4
|
+
// src/verify.ts
|
|
5
|
+
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
6
|
+
var keys = /* @__PURE__ */ new Map();
|
|
7
|
+
function keysOf(issuer) {
|
|
8
|
+
let set = keys.get(issuer);
|
|
9
|
+
if (set === void 0) {
|
|
10
|
+
set = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), { cooldownDuration: 3e4 });
|
|
11
|
+
keys.set(issuer, set);
|
|
12
|
+
}
|
|
13
|
+
return set;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// src/mcp.ts
|
|
17
|
+
var McpAuthError = class extends Error {
|
|
18
|
+
constructor(status, code, description) {
|
|
19
|
+
super(`cauthy-auth: ${description}`);
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.description = description;
|
|
23
|
+
this.name = "McpAuthError";
|
|
24
|
+
}
|
|
25
|
+
status;
|
|
26
|
+
code;
|
|
27
|
+
description;
|
|
28
|
+
};
|
|
29
|
+
function env(name) {
|
|
30
|
+
return typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
31
|
+
}
|
|
32
|
+
function canonicalResource(raw) {
|
|
33
|
+
let u;
|
|
34
|
+
try {
|
|
35
|
+
u = new URL(raw.trim());
|
|
36
|
+
} catch {
|
|
37
|
+
throw new Error(`cauthy-auth: resource ${JSON.stringify(raw)} is not an absolute address`);
|
|
38
|
+
}
|
|
39
|
+
const local = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
|
|
40
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) {
|
|
41
|
+
throw new Error("cauthy-auth: resource must be an https address");
|
|
42
|
+
}
|
|
43
|
+
if (u.search !== "" || u.hash !== "") throw new Error("cauthy-auth: resource may not have a query or a fragment");
|
|
44
|
+
return `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/, "")}`;
|
|
45
|
+
}
|
|
46
|
+
function bearer(from) {
|
|
47
|
+
if (typeof from === "string") return from.replace(/^Bearer\s+/i, "").trim();
|
|
48
|
+
const header = (from instanceof Headers ? from : from.headers).get("authorization") ?? "";
|
|
49
|
+
return /^Bearer\s+/i.test(header) ? header.replace(/^Bearer\s+/i, "").trim() : "";
|
|
50
|
+
}
|
|
51
|
+
function quoted(v) {
|
|
52
|
+
return `"${v.replace(/["\\]/g, "")}"`;
|
|
53
|
+
}
|
|
54
|
+
function mcpAuth(options = {}) {
|
|
55
|
+
const rawResource = options.resource ?? env("CAUTHY_MCP_RESOURCE") ?? "";
|
|
56
|
+
if (rawResource === "") throw new Error("cauthy-auth: resource (CAUTHY_MCP_RESOURCE) is not set");
|
|
57
|
+
const resource = canonicalResource(rawResource);
|
|
58
|
+
const issuer = (options.issuer ?? env("CAUTHY_ISSUER") ?? "").replace(/\/+$/, "");
|
|
59
|
+
if (issuer === "") throw new Error("cauthy-auth: issuer (CAUTHY_ISSUER) is not set");
|
|
60
|
+
const required = options.scopes ?? [];
|
|
61
|
+
const url = new URL(resource);
|
|
62
|
+
const path = url.pathname === "/" ? "" : url.pathname;
|
|
63
|
+
const metadataPaths = [.../* @__PURE__ */ new Set([`/.well-known/oauth-protected-resource${path}`, "/.well-known/oauth-protected-resource"])];
|
|
64
|
+
const metadataUrl = `${url.origin}${metadataPaths[0]}`;
|
|
65
|
+
const metadata = () => ({
|
|
66
|
+
resource,
|
|
67
|
+
authorization_servers: [issuer],
|
|
68
|
+
bearer_methods_supported: ["header"],
|
|
69
|
+
scopes_supported: options.scopesSupported ?? required,
|
|
70
|
+
...options.resourceName ? { resource_name: options.resourceName } : {}
|
|
71
|
+
});
|
|
72
|
+
const introspect = options.introspect ? { cacheMs: ((typeof options.introspect === "object" ? options.introspect.cacheSeconds : void 0) ?? 30) * 1e3 } : null;
|
|
73
|
+
const answers = /* @__PURE__ */ new Map();
|
|
74
|
+
const stillAllowed = async (token, cacheMs) => {
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const kept = answers.get(token);
|
|
77
|
+
if (kept && kept.until > now) return kept.active;
|
|
78
|
+
let active = false;
|
|
79
|
+
try {
|
|
80
|
+
const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/introspect`, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
83
|
+
body: new URLSearchParams({ token })
|
|
84
|
+
});
|
|
85
|
+
if (!res.ok) throw new Error(`introspection answered ${res.status}`);
|
|
86
|
+
active = (await res.json()).active === true;
|
|
87
|
+
} catch (err) {
|
|
88
|
+
if (kept) return kept.active;
|
|
89
|
+
throw new McpAuthError(401, "invalid_token", `could not check the token with Cauthy: ${err instanceof Error ? err.message : "unreachable"}`);
|
|
90
|
+
}
|
|
91
|
+
if (answers.size > 1e4) answers.clear();
|
|
92
|
+
answers.set(token, { active, until: now + cacheMs });
|
|
93
|
+
return active;
|
|
94
|
+
};
|
|
95
|
+
const verify = async (from, needs = []) => {
|
|
96
|
+
const token = bearer(from);
|
|
97
|
+
if (token === "") throw new McpAuthError(401, "invalid_request", "no access token");
|
|
98
|
+
let claims;
|
|
99
|
+
try {
|
|
100
|
+
const verified = await jwtVerify2(token, options.jwks ?? keysOf(issuer), {
|
|
101
|
+
algorithms: ["RS256"],
|
|
102
|
+
issuer,
|
|
103
|
+
audience: resource,
|
|
104
|
+
requiredClaims: ["exp", "sub"],
|
|
105
|
+
currentDate: options.now?.()
|
|
106
|
+
});
|
|
107
|
+
claims = verified.payload;
|
|
108
|
+
} catch (err) {
|
|
109
|
+
throw new McpAuthError(401, "invalid_token", err instanceof Error ? err.message : "the token is not valid");
|
|
110
|
+
}
|
|
111
|
+
const clientId = typeof claims.client_id === "string" ? claims.client_id : "";
|
|
112
|
+
if (clientId === "") throw new McpAuthError(401, "invalid_token", "not a token issued to an agent");
|
|
113
|
+
const scopes = typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
|
|
114
|
+
if (introspect && !await stillAllowed(token, introspect.cacheMs)) throw new McpAuthError(401, "invalid_token", "the person disconnected this agent");
|
|
115
|
+
const missing = [...required, ...needs].filter((s) => !scopes.includes(s));
|
|
116
|
+
if (missing.length > 0) throw new McpAuthError(403, "insufficient_scope", `this needs ${missing.join(" ")}`);
|
|
117
|
+
return {
|
|
118
|
+
userId: String(claims.sub),
|
|
119
|
+
tenantId: typeof claims.tid === "string" ? claims.tid : "",
|
|
120
|
+
...typeof claims.email === "string" && claims.email !== "" ? { email: claims.email } : {},
|
|
121
|
+
roles: Array.isArray(claims.roles) ? claims.roles.filter((r) => typeof r === "string") : [],
|
|
122
|
+
scopes,
|
|
123
|
+
clientId,
|
|
124
|
+
expiresAt: new Date(claims.exp * 1e3).toISOString(),
|
|
125
|
+
token
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
const authenticate = (error) => {
|
|
129
|
+
const parts = [`resource_metadata=${quoted(metadataUrl)}`];
|
|
130
|
+
if (error && error.code !== "invalid_request") {
|
|
131
|
+
parts.push(`error=${quoted(error.code)}`, `error_description=${quoted(error.description)}`);
|
|
132
|
+
}
|
|
133
|
+
const scope = error?.code === "invalid_token" ? [] : required;
|
|
134
|
+
if (scope.length > 0) parts.push(`scope=${quoted(scope.join(" "))}`);
|
|
135
|
+
return `Bearer ${parts.join(", ")}`;
|
|
136
|
+
};
|
|
137
|
+
const challenge = (error) => {
|
|
138
|
+
const status = error?.status ?? 401;
|
|
139
|
+
return new Response(JSON.stringify({ error: error?.code ?? "invalid_request", error_description: error?.description ?? "an access token is required" }), {
|
|
140
|
+
status,
|
|
141
|
+
headers: { "content-type": "application/json", "www-authenticate": authenticate(error) }
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
const metadataResponse = () => new Response(JSON.stringify(metadata()), {
|
|
145
|
+
headers: { "content-type": "application/json", "cache-control": "public, max-age=3600", "access-control-allow-origin": "*" }
|
|
146
|
+
});
|
|
147
|
+
const isMetadata = (pathname, method = "GET") => method === "GET" && metadataPaths.includes(pathname.replace(/\/+$/, "") || "/");
|
|
148
|
+
const handleMetadata = (request) => isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null;
|
|
149
|
+
const toAuthInfo = (a) => ({
|
|
150
|
+
token: a.token,
|
|
151
|
+
clientId: a.clientId,
|
|
152
|
+
scopes: a.scopes,
|
|
153
|
+
expiresAt: Math.floor(new Date(a.expiresAt).getTime() / 1e3),
|
|
154
|
+
resource: new URL(resource),
|
|
155
|
+
extra: { userId: a.userId, tenantId: a.tenantId, ...a.email ? { email: a.email } : {}, roles: a.roles }
|
|
156
|
+
});
|
|
157
|
+
return {
|
|
158
|
+
resource,
|
|
159
|
+
metadataUrl,
|
|
160
|
+
metadataPaths,
|
|
161
|
+
metadata,
|
|
162
|
+
verify,
|
|
163
|
+
challenge,
|
|
164
|
+
handleMetadata,
|
|
165
|
+
protect(handler, needs) {
|
|
166
|
+
return async (request) => {
|
|
167
|
+
const meta = handleMetadata(request);
|
|
168
|
+
if (meta) return meta;
|
|
169
|
+
let agent;
|
|
170
|
+
try {
|
|
171
|
+
agent = await verify(request, needs);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
if (err instanceof McpAuthError) return challenge(err);
|
|
174
|
+
throw err;
|
|
175
|
+
}
|
|
176
|
+
return handler(request, agent);
|
|
177
|
+
};
|
|
178
|
+
},
|
|
179
|
+
middleware(needs) {
|
|
180
|
+
return (req, res, next) => {
|
|
181
|
+
const pathname = (req.originalUrl ?? req.url ?? "/").split("?")[0] ?? "/";
|
|
182
|
+
if (isMetadata(pathname, req.method)) {
|
|
183
|
+
res.statusCode = 200;
|
|
184
|
+
res.setHeader("content-type", "application/json");
|
|
185
|
+
res.setHeader("cache-control", "public, max-age=3600");
|
|
186
|
+
res.setHeader("access-control-allow-origin", "*");
|
|
187
|
+
res.end(JSON.stringify(metadata()));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const raw = req.headers.authorization;
|
|
191
|
+
const header = Array.isArray(raw) ? raw[0] ?? "" : raw ?? "";
|
|
192
|
+
verify(/^Bearer\s+/i.test(header) ? header : "", needs).then(
|
|
193
|
+
(agent) => {
|
|
194
|
+
req.agent = agent;
|
|
195
|
+
req.auth = toAuthInfo(agent);
|
|
196
|
+
next();
|
|
197
|
+
},
|
|
198
|
+
(err) => {
|
|
199
|
+
if (!(err instanceof McpAuthError)) return next(err);
|
|
200
|
+
res.statusCode = err.status;
|
|
201
|
+
res.setHeader("content-type", "application/json");
|
|
202
|
+
res.setHeader("www-authenticate", authenticate(err));
|
|
203
|
+
res.end(JSON.stringify({ error: err.code, error_description: err.description }));
|
|
204
|
+
}
|
|
205
|
+
);
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
export {
|
|
211
|
+
McpAuthError,
|
|
212
|
+
canonicalResource,
|
|
213
|
+
mcpAuth
|
|
214
|
+
};
|
|
215
|
+
//# sourceMappingURL=mcp.mjs.map
|
package/dist/mcp.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp.ts","../src/verify.ts"],"sourcesContent":["// An MCP server (or any API) that AI agents use as one of your people.\n//\n// import { mcpAuth } from 'cauthy-auth/mcp'\n// const auth = mcpAuth({ resource: 'https://mcp.example.com/mcp', scopes: ['books:read'] })\n//\n// // Fetch-style (Hono, Next.js, Workers, Bun, Deno):\n// export default { fetch: auth.protect((request, agent) => handleMcp(request, agent)) }\n//\n// // Express or plain Node, with the MCP TypeScript SDK (its transport reads req.auth):\n// app.use(auth.middleware())\n//\n// How an agent gets in, as the MCP specification lays it out: it calls the\n// server, which answers 401 and points at its protected resource metadata\n// (RFC 9728); that names Cauthy as the authorization server; the agent\n// registers itself there, sends the person to sign in and allow it, and comes\n// back with a token issued for this server alone (its `aud`). This module is\n// the server's half: the metadata, the 401 that points at it, and checking\n// the token. The resource must be registered in Cauthy's dashboard (AI\n// agents), with the same address, for the workspace whose people use it.\n\nimport { jwtVerify, type JWTVerifyGetKey } from 'jose'\nimport { keysOf } from './verify'\n\n/** The person an agent acts for, and what they allowed it. */\nexport interface AgentIdentity {\n /** The person. */\n userId: string\n tenantId: string\n email?: string\n /** The person's roles in the workspace. */\n roles: string[]\n /** What the person allowed the agent to do here. */\n scopes: string[]\n /** The agent (its client_id at Cauthy). */\n clientId: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived. */\n token: string\n}\n\nexport interface McpAuthOptions {\n /** This server's address, as registered in Cauthy. Default: `CAUTHY_MCP_RESOURCE`. */\n resource?: string\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** Scopes every call needs. Default: none. */\n scopes?: string[]\n /** The scopes this server understands, to tell agents (`scopes_supported`). Default: `scopes`. */\n scopesSupported?: string[]\n /** A name for the server, shown by some agents. */\n resourceName?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: () => Date\n /**\n * Ask Cauthy, besides checking the token here, whether the person still\n * allows the agent (RFC 7662). Then an agent is cut off the moment it is\n * disconnected, not when its token runs out, at the price of a call to\n * Cauthy per token every `cacheSeconds` (default 30). Default: off.\n */\n introspect?: boolean | { cacheSeconds?: number }\n /** The fetch to call Cauthy with. Default: the global one. */\n fetch?: typeof fetch\n}\n\n/** A token refused: `status` is 401 (no token, or not a good one) or 403 (a scope missing). */\nexport class McpAuthError extends Error {\n constructor(\n readonly status: 401 | 403,\n readonly code: 'invalid_request' | 'invalid_token' | 'insufficient_scope',\n readonly description: string,\n ) {\n super(`cauthy-auth: ${description}`)\n this.name = 'McpAuthError'\n }\n}\n\n/** What the MCP TypeScript SDK reads from `req.auth` (its AuthInfo). */\nexport interface McpAuthInfo {\n token: string\n clientId: string\n scopes: string[]\n /** Seconds since the epoch. */\n expiresAt: number\n resource: URL\n extra: { userId: string; tenantId: string; email?: string; roles: string[] }\n}\n\nexport interface McpAuth {\n /** This server's address, in the form Cauthy compares it in. */\n resource: string\n /** Where the protected resource metadata is served. */\n metadataUrl: string\n /** The protected resource metadata (RFC 9728). */\n metadata(): Record<string, unknown>\n /** The metadata's paths: `/.well-known/oauth-protected-resource` plus this server's path. */\n metadataPaths: string[]\n /** Verifies the `Authorization: Bearer` of a request (or a token). Throws `McpAuthError`. */\n verify(from: string | Request | Headers, needs?: string[]): Promise<AgentIdentity>\n /** The answer to a refused token: 401 or 403, with the `WWW-Authenticate` that points an agent at Cauthy. */\n challenge(error?: McpAuthError): Response\n /** The metadata, when the request asks for it; `null` otherwise. */\n handleMetadata(request: Request): Response | null\n /** Wraps a fetch-style handler: serves the metadata, refuses what has no good token, passes the rest with who it is. */\n protect(handler: (request: Request, agent: AgentIdentity) => Response | Promise<Response>, needs?: string[]): (request: Request) => Promise<Response>\n /**\n * Connect-style middleware (Express, Node's http): serves the metadata,\n * refuses what has no good token, and sets `req.agent` and `req.auth` —\n * what the MCP TypeScript SDK's transport hands its tools as `authInfo`.\n */\n middleware(needs?: string[]): (req: NodeRequest, res: NodeResponse, next: (err?: unknown) => void) => void\n}\n\n// The slice of Node's (and Express's) request and response this needs.\ninterface NodeRequest {\n method?: string\n url?: string\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n auth?: McpAuthInfo\n agent?: AgentIdentity\n}\ninterface NodeResponse {\n statusCode: number\n setHeader(name: string, value: string): unknown\n end(body?: string): unknown\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\n/**\n * The address in the one form Cauthy keeps it: scheme and host in lower case,\n * no default port, no trailing slash, no query, no fragment.\n */\nexport function canonicalResource(raw: string): string {\n let u: URL\n try {\n u = new URL(raw.trim())\n } catch {\n throw new Error(`cauthy-auth: resource ${JSON.stringify(raw)} is not an absolute address`)\n }\n const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]'\n if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {\n throw new Error('cauthy-auth: resource must be an https address')\n }\n if (u.search !== '' || u.hash !== '') throw new Error('cauthy-auth: resource may not have a query or a fragment')\n return `${u.protocol}//${u.host}${u.pathname.replace(/\\/+$/, '')}`\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\nfunction quoted(v: string): string {\n return `\"${v.replace(/[\"\\\\]/g, '')}\"`\n}\n\n/** Protects an MCP server with Cauthy. */\nexport function mcpAuth(options: McpAuthOptions = {}): McpAuth {\n const rawResource = options.resource ?? env('CAUTHY_MCP_RESOURCE') ?? ''\n if (rawResource === '') throw new Error('cauthy-auth: resource (CAUTHY_MCP_RESOURCE) is not set')\n const resource = canonicalResource(rawResource)\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new Error('cauthy-auth: issuer (CAUTHY_ISSUER) is not set')\n const required = options.scopes ?? []\n const url = new URL(resource)\n const path = url.pathname === '/' ? '' : url.pathname\n const metadataPaths = [...new Set([`/.well-known/oauth-protected-resource${path}`, '/.well-known/oauth-protected-resource'])]\n const metadataUrl = `${url.origin}${metadataPaths[0]}`\n\n const metadata = () => ({\n resource,\n authorization_servers: [issuer],\n bearer_methods_supported: ['header'],\n scopes_supported: options.scopesSupported ?? required,\n ...(options.resourceName ? { resource_name: options.resourceName } : {}),\n })\n\n const introspect = options.introspect ? { cacheMs: ((typeof options.introspect === 'object' ? options.introspect.cacheSeconds : undefined) ?? 30) * 1000 } : null\n const answers = new Map<string, { active: boolean; until: number }>()\n const stillAllowed = async (token: string, cacheMs: number): Promise<boolean> => {\n const now = Date.now()\n const kept = answers.get(token)\n if (kept && kept.until > now) return kept.active\n let active = false\n try {\n const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/introspect`, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body: new URLSearchParams({ token }),\n })\n if (!res.ok) throw new Error(`introspection answered ${res.status}`)\n active = ((await res.json()) as { active?: unknown }).active === true\n } catch (err) {\n // Cauthy could not be asked: what it last said holds.\n if (kept) return kept.active\n throw new McpAuthError(401, 'invalid_token', `could not check the token with Cauthy: ${err instanceof Error ? err.message : 'unreachable'}`)\n }\n if (answers.size > 10_000) answers.clear()\n answers.set(token, { active, until: now + cacheMs })\n return active\n }\n\n const verify = async (from: string | Request | Headers, needs: string[] = []): Promise<AgentIdentity> => {\n const token = bearer(from)\n if (token === '') throw new McpAuthError(401, 'invalid_request', 'no access token')\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: resource,\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now?.(),\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new McpAuthError(401, 'invalid_token', err instanceof Error ? err.message : 'the token is not valid')\n }\n const clientId = typeof claims.client_id === 'string' ? claims.client_id : ''\n if (clientId === '') throw new McpAuthError(401, 'invalid_token', 'not a token issued to an agent')\n const scopes = typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : []\n if (introspect && !(await stillAllowed(token, introspect.cacheMs))) throw new McpAuthError(401, 'invalid_token', 'the person disconnected this agent')\n const missing = [...required, ...needs].filter((s) => !scopes.includes(s))\n if (missing.length > 0) throw new McpAuthError(403, 'insufficient_scope', `this needs ${missing.join(' ')}`)\n return {\n userId: String(claims.sub),\n tenantId: typeof claims.tid === 'string' ? claims.tid : '',\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n scopes,\n clientId,\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n }\n\n const authenticate = (error?: McpAuthError): string => {\n const parts = [`resource_metadata=${quoted(metadataUrl)}`]\n if (error && error.code !== 'invalid_request') {\n parts.push(`error=${quoted(error.code)}`, `error_description=${quoted(error.description)}`)\n }\n // What to ask the person for: said when there is no token or it falls short.\n const scope = error?.code === 'invalid_token' ? [] : required\n if (scope.length > 0) parts.push(`scope=${quoted(scope.join(' '))}`)\n return `Bearer ${parts.join(', ')}`\n }\n\n const challenge = (error?: McpAuthError): Response => {\n const status = error?.status ?? 401\n return new Response(JSON.stringify({ error: error?.code ?? 'invalid_request', error_description: error?.description ?? 'an access token is required' }), {\n status,\n headers: { 'content-type': 'application/json', 'www-authenticate': authenticate(error) },\n })\n }\n\n const metadataResponse = () =>\n new Response(JSON.stringify(metadata()), {\n headers: { 'content-type': 'application/json', 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' },\n })\n\n const isMetadata = (pathname: string, method = 'GET') => method === 'GET' && metadataPaths.includes(pathname.replace(/\\/+$/, '') || '/')\n\n const handleMetadata = (request: Request): Response | null =>\n isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null\n\n const toAuthInfo = (a: AgentIdentity): McpAuthInfo => ({\n token: a.token,\n clientId: a.clientId,\n scopes: a.scopes,\n expiresAt: Math.floor(new Date(a.expiresAt).getTime() / 1000),\n resource: new URL(resource),\n extra: { userId: a.userId, tenantId: a.tenantId, ...(a.email ? { email: a.email } : {}), roles: a.roles },\n })\n\n return {\n resource,\n metadataUrl,\n metadataPaths,\n metadata,\n verify,\n challenge,\n handleMetadata,\n protect(handler, needs) {\n return async (request) => {\n const meta = handleMetadata(request)\n if (meta) return meta\n let agent: AgentIdentity\n try {\n agent = await verify(request, needs)\n } catch (err) {\n if (err instanceof McpAuthError) return challenge(err)\n throw err\n }\n return handler(request, agent)\n }\n },\n middleware(needs) {\n return (req, res, next) => {\n const pathname = (req.originalUrl ?? req.url ?? '/').split('?')[0] ?? '/'\n if (isMetadata(pathname, req.method)) {\n res.statusCode = 200\n res.setHeader('content-type', 'application/json')\n res.setHeader('cache-control', 'public, max-age=3600')\n res.setHeader('access-control-allow-origin', '*')\n res.end(JSON.stringify(metadata()))\n return\n }\n const raw = req.headers.authorization\n const header = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '')\n verify(/^Bearer\\s+/i.test(header) ? header : '', needs).then(\n (agent) => {\n req.agent = agent\n req.auth = toAuthInfo(agent)\n next()\n },\n (err: unknown) => {\n if (!(err instanceof McpAuthError)) return next(err)\n res.statusCode = err.status\n res.setHeader('content-type', 'application/json')\n res.setHeader('www-authenticate', authenticate(err))\n res.end(JSON.stringify({ error: err.code, error_description: err.description }))\n },\n )\n }\n },\n }\n}\n","// A backend that is handed a Cauthy access token: is it real, and whose is it?\n//\n// const who = await verifyToken(request) // or the token itself\n// who.userId, who.tenantId, who.roles\n//\n// Cauthy signs its tokens with a key it publishes (/.well-known/jwks.json), so\n// checking one needs no secret and no call to Cauthy per request: the keys are\n// fetched once and cached. Throws `CauthyTokenError` for anything else: answer\n// it 401.\n\nimport { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'\n\n/** Who a verified access token belongs to. */\nexport interface TokenIdentity {\n /** The person. For a system's own token, the client it identifies as. */\n userId: string\n tenantId: string\n email?: string\n roles: string[]\n /** Set when the token is a system's own and not a person's. */\n system?: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived, to pass on. */\n token: string\n}\n\nexport class CauthyTokenError extends Error {\n constructor(readonly reason: string) {\n super(`cauthy-auth: token refused: ${reason}`)\n this.name = 'CauthyTokenError'\n }\n}\n\nexport interface VerifyTokenOptions {\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** The audience the tokens must carry. Default: `CAUTHY_AUDIENCE`; unchecked when neither is set. */\n audience?: string\n /** Refuse a token of any other workspace. Default: `CAUTHY_TENANT_ID`; unchecked when neither is set. */\n tenantId?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: Date\n}\n\nconst keys = new Map<string, JWTVerifyGetKey>()\n\n/** Cauthy's published keys, fetched once per issuer and cached. */\nexport function keysOf(issuer: string): JWTVerifyGetKey {\n let set = keys.get(issuer)\n if (set === undefined) {\n set = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), { cooldownDuration: 30_000 })\n keys.set(issuer, set)\n }\n return set\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\n/**\n * Verifies an access token (or the `Authorization: Bearer` of a request) and\n * answers who it belongs to. Checked: the signature, against Cauthy's\n * published keys; that Cauthy issued it; that it has not expired; and the\n * audience and the workspace, when given.\n */\nexport async function verifyToken(from: string | Request | Headers, options: VerifyTokenOptions = {}): Promise<TokenIdentity> {\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new CauthyTokenError('issuer (CAUTHY_ISSUER) is not set')\n const token = bearer(from)\n if (token === '') throw new CauthyTokenError('no token')\n\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: options.audience ?? env('CAUTHY_AUDIENCE'),\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now,\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new CauthyTokenError(err instanceof Error ? err.message : 'bad signature')\n }\n\n const tenantId = typeof claims.tid === 'string' ? claims.tid : ''\n const wanted = options.tenantId ?? env('CAUTHY_TENANT_ID')\n if (wanted && tenantId !== wanted) throw new CauthyTokenError('issued for another workspace')\n\n return {\n userId: String(claims.sub),\n tenantId,\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n ...(typeof claims.sys === 'string' && claims.sys !== '' ? { system: claims.sys } : {}),\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n}\n"],"mappings":";AAoBA,SAAS,aAAAA,kBAAuC;;;ACVhD,SAAS,oBAAoB,iBAAuC;AAqCpE,IAAM,OAAO,oBAAI,IAA6B;AAGvC,SAAS,OAAO,QAAiC;AACtD,MAAI,MAAM,K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|
package/dist/react.d.mts
CHANGED
|
@@ -286,6 +286,26 @@ interface Account$1 {
|
|
|
286
286
|
mfaEnabled: boolean;
|
|
287
287
|
}
|
|
288
288
|
/** Somewhere the person is signed in. Moments are UTC. */
|
|
289
|
+
/** An AI agent the person allowed to act for them on one of the workspace's servers. */
|
|
290
|
+
interface ConnectedAgent {
|
|
291
|
+
id: string;
|
|
292
|
+
/** The name the agent gave itself (Claude, Cursor…): not checked by anyone. */
|
|
293
|
+
name: string;
|
|
294
|
+
/** Where the agent receives its access: the one thing about it that is sure. */
|
|
295
|
+
redirectHost: string;
|
|
296
|
+
resource: {
|
|
297
|
+
name: string;
|
|
298
|
+
uri: string;
|
|
299
|
+
};
|
|
300
|
+
/** What the person allowed it, in their words. */
|
|
301
|
+
scopes: {
|
|
302
|
+
name: string;
|
|
303
|
+
description: string;
|
|
304
|
+
}[];
|
|
305
|
+
/** UTC, ISO 8601. */
|
|
306
|
+
connectedAt: string;
|
|
307
|
+
lastUsedAt: string;
|
|
308
|
+
}
|
|
289
309
|
interface AccountSession {
|
|
290
310
|
/** "Mac · Chrome", or "" when the browser did not say. */
|
|
291
311
|
device: string;
|
|
@@ -412,6 +432,12 @@ interface AccountClient {
|
|
|
412
432
|
sessions(): Promise<AccountSession[]>;
|
|
413
433
|
/** Signs the account out everywhere, here too. */
|
|
414
434
|
signOutEverywhere(): Promise<AuthResult<'signed_out'>>;
|
|
435
|
+
/** The AI agents the person connected. */
|
|
436
|
+
agents(): Promise<ConnectedAgent[]>;
|
|
437
|
+
/** Disconnects an agent: it loses its access within minutes. */
|
|
438
|
+
disconnectAgent(id: string): Promise<AuthResult<'disconnected', {
|
|
439
|
+
id: string;
|
|
440
|
+
}>>;
|
|
415
441
|
/** The account's passkeys. */
|
|
416
442
|
passkeys(): Promise<Passkey[]>;
|
|
417
443
|
/**
|
|
@@ -654,6 +680,10 @@ interface AuthTexts {
|
|
|
654
680
|
passkeyUnnamed: string;
|
|
655
681
|
sessions: string;
|
|
656
682
|
signOutEverywhere: string;
|
|
683
|
+
agents: string;
|
|
684
|
+
agentsHelp: string;
|
|
685
|
+
disconnect: string;
|
|
686
|
+
anAgent: string;
|
|
657
687
|
unknownDevice: string;
|
|
658
688
|
emailAddress: string;
|
|
659
689
|
newEmail: string;
|
|
@@ -807,4 +837,4 @@ declare function useSession(): SessionContext;
|
|
|
807
837
|
*/
|
|
808
838
|
declare function useAuth(): AuthClient & Pick<SessionContext, 'session' | 'status' | 'refresh'>;
|
|
809
839
|
|
|
810
|
-
export { Account, type AccountClient, type Account$1 as AccountDetails, type AccountProps, type AccountSession, type AuthClient, type AuthError, type AuthFormProps, type AuthMethods, type AuthResult, type AuthTexts, CauthyProvider, type CauthyProviderProps, ForgotPassword, GoogleOneTap, type GoogleOneTapProps, type JsonValue, type LinkedIdentity, type Passkey, type PermissionOf, type Policy, type PublicSession, ResetPassword, type RoleOf, type SecondStep, type SessionContext, type SessionOrganization, type SessionUser, SignIn, SignUp, VerifyEmail, can, canAutofillPasskeys, canUsePasskeys, createAuthClient, definePolicy, useAuth, useSession };
|
|
840
|
+
export { Account, type AccountClient, type Account$1 as AccountDetails, type AccountProps, type AccountSession, type AuthClient, type AuthError, type AuthFormProps, type AuthMethods, type AuthResult, type AuthTexts, CauthyProvider, type CauthyProviderProps, type ConnectedAgent, ForgotPassword, GoogleOneTap, type GoogleOneTapProps, type JsonValue, type LinkedIdentity, type Passkey, type PermissionOf, type Policy, type PublicSession, ResetPassword, type RoleOf, type SecondStep, type SessionContext, type SessionOrganization, type SessionUser, SignIn, SignUp, VerifyEmail, can, canAutofillPasskeys, canUsePasskeys, createAuthClient, definePolicy, useAuth, useSession };
|
package/dist/react.d.ts
CHANGED
|
@@ -286,6 +286,26 @@ interface Account$1 {
|
|
|
286
286
|
mfaEnabled: boolean;
|
|
287
287
|
}
|
|
288
288
|
/** Somewhere the person is signed in. Moments are UTC. */
|
|
289
|
+
/** An AI agent the person allowed to act for them on one of the workspace's servers. */
|
|
290
|
+
interface ConnectedAgent {
|
|
291
|
+
id: string;
|
|
292
|
+
/** The name the agent gave itself (Claude, Cursor…): not checked by anyone. */
|
|
293
|
+
name: string;
|
|
294
|
+
/** Where the agent receives its access: the one thing about it that is sure. */
|
|
295
|
+
redirectHost: string;
|
|
296
|
+
resource: {
|
|
297
|
+
name: string;
|
|
298
|
+
uri: string;
|
|
299
|
+
};
|
|
300
|
+
/** What the person allowed it, in their words. */
|
|
301
|
+
scopes: {
|
|
302
|
+
name: string;
|
|
303
|
+
description: string;
|
|
304
|
+
}[];
|
|
305
|
+
/** UTC, ISO 8601. */
|
|
306
|
+
connectedAt: string;
|
|
307
|
+
lastUsedAt: string;
|
|
308
|
+
}
|
|
289
309
|
interface AccountSession {
|
|
290
310
|
/** "Mac · Chrome", or "" when the browser did not say. */
|
|
291
311
|
device: string;
|
|
@@ -412,6 +432,12 @@ interface AccountClient {
|
|
|
412
432
|
sessions(): Promise<AccountSession[]>;
|
|
413
433
|
/** Signs the account out everywhere, here too. */
|
|
414
434
|
signOutEverywhere(): Promise<AuthResult<'signed_out'>>;
|
|
435
|
+
/** The AI agents the person connected. */
|
|
436
|
+
agents(): Promise<ConnectedAgent[]>;
|
|
437
|
+
/** Disconnects an agent: it loses its access within minutes. */
|
|
438
|
+
disconnectAgent(id: string): Promise<AuthResult<'disconnected', {
|
|
439
|
+
id: string;
|
|
440
|
+
}>>;
|
|
415
441
|
/** The account's passkeys. */
|
|
416
442
|
passkeys(): Promise<Passkey[]>;
|
|
417
443
|
/**
|
|
@@ -654,6 +680,10 @@ interface AuthTexts {
|
|
|
654
680
|
passkeyUnnamed: string;
|
|
655
681
|
sessions: string;
|
|
656
682
|
signOutEverywhere: string;
|
|
683
|
+
agents: string;
|
|
684
|
+
agentsHelp: string;
|
|
685
|
+
disconnect: string;
|
|
686
|
+
anAgent: string;
|
|
657
687
|
unknownDevice: string;
|
|
658
688
|
emailAddress: string;
|
|
659
689
|
newEmail: string;
|
|
@@ -807,4 +837,4 @@ declare function useSession(): SessionContext;
|
|
|
807
837
|
*/
|
|
808
838
|
declare function useAuth(): AuthClient & Pick<SessionContext, 'session' | 'status' | 'refresh'>;
|
|
809
839
|
|
|
810
|
-
export { Account, type AccountClient, type Account$1 as AccountDetails, type AccountProps, type AccountSession, type AuthClient, type AuthError, type AuthFormProps, type AuthMethods, type AuthResult, type AuthTexts, CauthyProvider, type CauthyProviderProps, ForgotPassword, GoogleOneTap, type GoogleOneTapProps, type JsonValue, type LinkedIdentity, type Passkey, type PermissionOf, type Policy, type PublicSession, ResetPassword, type RoleOf, type SecondStep, type SessionContext, type SessionOrganization, type SessionUser, SignIn, SignUp, VerifyEmail, can, canAutofillPasskeys, canUsePasskeys, createAuthClient, definePolicy, useAuth, useSession };
|
|
840
|
+
export { Account, type AccountClient, type Account$1 as AccountDetails, type AccountProps, type AccountSession, type AuthClient, type AuthError, type AuthFormProps, type AuthMethods, type AuthResult, type AuthTexts, CauthyProvider, type CauthyProviderProps, type ConnectedAgent, ForgotPassword, GoogleOneTap, type GoogleOneTapProps, type JsonValue, type LinkedIdentity, type Passkey, type PermissionOf, type Policy, type PublicSession, ResetPassword, type RoleOf, type SecondStep, type SessionContext, type SessionOrganization, type SessionUser, SignIn, SignUp, VerifyEmail, can, canAutofillPasskeys, canUsePasskeys, createAuthClient, definePolicy, useAuth, useSession };
|
package/dist/react.js
CHANGED
|
@@ -427,6 +427,11 @@ function createAuthClient(options = {}) {
|
|
|
427
427
|
return body && Array.isArray(body.sessions) ? body.sessions : [];
|
|
428
428
|
},
|
|
429
429
|
signOutEverywhere: () => post("/me/sessions/end", {}, null),
|
|
430
|
+
async agents() {
|
|
431
|
+
const body = await read("/me/agents");
|
|
432
|
+
return body && Array.isArray(body.agents) ? body.agents : [];
|
|
433
|
+
},
|
|
434
|
+
disconnectAgent: (id) => post("/me/agents/disconnect", { id }, null),
|
|
430
435
|
async passkeys() {
|
|
431
436
|
const body = await read("/me/passkeys");
|
|
432
437
|
return body && Array.isArray(body.passkeys) ? body.passkeys : [];
|
|
@@ -578,6 +583,10 @@ var TEXTS = {
|
|
|
578
583
|
passkeyUnnamed: "Passkey",
|
|
579
584
|
sessions: "Where you are signed in",
|
|
580
585
|
signOutEverywhere: "Sign out everywhere",
|
|
586
|
+
agents: "AI agents",
|
|
587
|
+
agentsHelp: "Agents you allowed to act for you. Disconnect one and it loses its access within minutes.",
|
|
588
|
+
disconnect: "Disconnect",
|
|
589
|
+
anAgent: "An AI agent",
|
|
581
590
|
unknownDevice: "Unknown device",
|
|
582
591
|
emailAddress: "Email address",
|
|
583
592
|
newEmail: "New email address",
|
|
@@ -686,6 +695,10 @@ var TEXTS = {
|
|
|
686
695
|
passkeyUnnamed: "Llave de acceso",
|
|
687
696
|
sessions: "D\xF3nde tienes la sesi\xF3n abierta",
|
|
688
697
|
signOutEverywhere: "Cerrar sesi\xF3n en todas partes",
|
|
698
|
+
agents: "Agentes de IA",
|
|
699
|
+
agentsHelp: "Los agentes a los que permitiste actuar por ti. Si desconectas uno, pierde el acceso en pocos minutos.",
|
|
700
|
+
disconnect: "Desconectar",
|
|
701
|
+
anAgent: "Un agente de IA",
|
|
689
702
|
unknownDevice: "Dispositivo desconocido",
|
|
690
703
|
emailAddress: "Correo",
|
|
691
704
|
newEmail: "Correo nuevo",
|
|
@@ -1215,6 +1228,7 @@ function Account(props) {
|
|
|
1215
1228
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SecondStepPart, { props, account, onChanged: (mfaEnabled) => setAccount({ ...account, mfaEnabled }) }),
|
|
1216
1229
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PhonePart, { props, account, onChanged: (mfaEnabled) => setAccount({ ...account, mfaEnabled }) }),
|
|
1217
1230
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PasskeysPart, { props, account, accountUrl: accountUrl(), when }),
|
|
1231
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AgentsPart, { props, when }),
|
|
1218
1232
|
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { className: cx("section"), children: [
|
|
1219
1233
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { className: cx("heading"), children: t.sessions }),
|
|
1220
1234
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { className: cx("sessions"), children: sessions.map((s, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { className: cx("session"), children: [
|
|
@@ -1514,6 +1528,35 @@ function PhonePart({ props, account, onChanged }) {
|
|
|
1514
1528
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(f.Button, { type: "submit", disabled: f.busy, className: f.cx("button"), children: ways.phone ? f.t.removePhone : f.t.addPhone })
|
|
1515
1529
|
] });
|
|
1516
1530
|
}
|
|
1531
|
+
function AgentsPart({ props, when }) {
|
|
1532
|
+
const auth = useAuth();
|
|
1533
|
+
const { f, run, general } = useSection(props);
|
|
1534
|
+
const [list, setList] = (0, import_react.useState)([]);
|
|
1535
|
+
(0, import_react.useEffect)(() => {
|
|
1536
|
+
void auth.account.agents().then(setList);
|
|
1537
|
+
}, []);
|
|
1538
|
+
if (list.length === 0) return null;
|
|
1539
|
+
const disconnect = async (id) => {
|
|
1540
|
+
const r = await run(() => auth.account.disconnectAgent(id));
|
|
1541
|
+
if (r.ok) setList(list.filter((a) => a.id !== id));
|
|
1542
|
+
};
|
|
1543
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { className: f.cx("section"), children: [
|
|
1544
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { className: f.cx("heading"), children: f.t.agents }),
|
|
1545
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: f.cx("notice"), children: f.t.agentsHelp }),
|
|
1546
|
+
general && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { role: "alert", className: f.cx("error"), children: f.say(general) }),
|
|
1547
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { className: f.cx("sessions"), children: list.map((a) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { className: f.cx("session"), children: [
|
|
1548
|
+
a.name || f.t.anAgent,
|
|
1549
|
+
a.redirectHost ? ` (${a.redirectHost})` : "",
|
|
1550
|
+
" \u2192 ",
|
|
1551
|
+
a.resource.name,
|
|
1552
|
+
a.scopes.length > 0 ? ` \xB7 ${a.scopes.map((s) => s.description || s.name).join(", ")}` : "",
|
|
1553
|
+
" \xB7 ",
|
|
1554
|
+
when(a.lastUsedAt),
|
|
1555
|
+
" ",
|
|
1556
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(f.Button, { type: "button", disabled: f.busy, className: f.cx("providerButton"), onClick: () => void disconnect(a.id), children: f.t.disconnect })
|
|
1557
|
+
] }, a.id)) })
|
|
1558
|
+
] });
|
|
1559
|
+
}
|
|
1517
1560
|
function SignOutEverywhere({ props }) {
|
|
1518
1561
|
const auth = useAuth();
|
|
1519
1562
|
const { f, run, general } = useSection(props);
|