@clegra/sdk 0.0.0-stage → 0.1.0-next.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +152 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE.md +25 -0
  4. package/README.md +258 -2
  5. package/dist/spec/kinds.json +211 -0
  6. package/dist/spec/schema/clegra.schema.json +1249 -0
  7. package/dist/spec/src/cli.d.ts +2 -0
  8. package/dist/spec/src/cli.js +21 -0
  9. package/dist/spec/src/cli.js.map +1 -0
  10. package/dist/spec/src/conformance.d.ts +34 -0
  11. package/dist/spec/src/conformance.js +703 -0
  12. package/dist/spec/src/conformance.js.map +1 -0
  13. package/dist/spec/src/init/index.d.ts +31 -0
  14. package/dist/spec/src/init/index.js +151 -0
  15. package/dist/spec/src/init/index.js.map +1 -0
  16. package/dist/spec/src/init/next-config.d.ts +19 -0
  17. package/dist/spec/src/init/next-config.js +77 -0
  18. package/dist/spec/src/init/next-config.js.map +1 -0
  19. package/dist/spec/src/init/project.d.ts +44 -0
  20. package/dist/spec/src/init/project.js +141 -0
  21. package/dist/spec/src/init/project.js.map +1 -0
  22. package/dist/spec/src/init/templates.d.ts +20 -0
  23. package/dist/spec/src/init/templates.js +166 -0
  24. package/dist/spec/src/init/templates.js.map +1 -0
  25. package/dist/spec/src/init/ui.d.ts +30 -0
  26. package/dist/spec/src/init/ui.js +82 -0
  27. package/dist/spec/src/init/ui.js.map +1 -0
  28. package/dist/spec/src/kinds.d.ts +89 -0
  29. package/dist/spec/src/kinds.js +319 -0
  30. package/dist/spec/src/kinds.js.map +1 -0
  31. package/dist/spec/src/protocol.d.ts +50 -0
  32. package/dist/spec/src/protocol.js +52 -0
  33. package/dist/spec/src/protocol.js.map +1 -0
  34. package/dist/spec/src/rules.d.ts +132 -0
  35. package/dist/spec/src/rules.js +282 -0
  36. package/dist/spec/src/rules.js.map +1 -0
  37. package/dist/src/auth.d.ts +371 -0
  38. package/dist/src/auth.js +964 -0
  39. package/dist/src/auth.js.map +1 -0
  40. package/dist/src/define.d.ts +249 -0
  41. package/dist/src/define.js +83 -0
  42. package/dist/src/define.js.map +1 -0
  43. package/dist/src/embed.d.ts +98 -0
  44. package/dist/src/embed.js +256 -0
  45. package/dist/src/embed.js.map +1 -0
  46. package/dist/src/index.d.ts +11 -0
  47. package/dist/src/index.js +11 -0
  48. package/dist/src/index.js.map +1 -0
  49. package/dist/src/labels.d.ts +10 -0
  50. package/dist/src/labels.js +22 -0
  51. package/dist/src/labels.js.map +1 -0
  52. package/dist/src/manifest.d.ts +499 -0
  53. package/dist/src/manifest.js +188 -0
  54. package/dist/src/manifest.js.map +1 -0
  55. package/dist/src/meaning.d.ts +64 -0
  56. package/dist/src/meaning.js +116 -0
  57. package/dist/src/meaning.js.map +1 -0
  58. package/dist/src/next/index.d.ts +101 -0
  59. package/dist/src/next/index.js +187 -0
  60. package/dist/src/next/index.js.map +1 -0
  61. package/dist/src/node.d.ts +14 -0
  62. package/dist/src/node.js +64 -0
  63. package/dist/src/node.js.map +1 -0
  64. package/dist/src/server.d.ts +229 -0
  65. package/dist/src/server.js +2256 -0
  66. package/dist/src/server.js.map +1 -0
  67. package/dist/src/store.d.ts +129 -0
  68. package/dist/src/store.js +213 -0
  69. package/dist/src/store.js.map +1 -0
  70. package/dist/src/testing.d.ts +133 -0
  71. package/dist/src/testing.js +81 -0
  72. package/dist/src/testing.js.map +1 -0
  73. package/dist/src/types.d.ts +352 -0
  74. package/dist/src/types.js +2 -0
  75. package/dist/src/types.js.map +1 -0
  76. package/dist/src/view.d.ts +35 -0
  77. package/dist/src/view.js +442 -0
  78. package/dist/src/view.js.map +1 -0
  79. package/docs/quickstart.md +350 -0
  80. package/docs/spec.md +997 -0
  81. package/package.json +89 -4
@@ -0,0 +1,371 @@
1
+ import { type CryptoKey, type JWK, type JWTPayload } from "jose";
2
+ import { CONFIRMATION_TYPE } from "../spec/src/protocol.js";
3
+ /**
4
+ * AUTH (spec §7). Two kinds of access token reach an app:
5
+ *
6
+ * - **its own** (the common case: a web app with its own users): issued by
7
+ * the app's own authorization server (better-auth, Clerk, …) to an MCP
8
+ * client such as ChatGPT, Claude or Clegra. The SDK does not read them: the
9
+ * app verifies them in `auth.resolve(token, request, { resource })` and says
10
+ * who is calling (installation, person, permissions).
11
+ * - **a workspace host's** (in-house apps a company installs into its own
12
+ * host): JWTs (`typ: at+jwt`) from a trusted issuer listed in
13
+ * `auth.issuers`,
14
+ * verified with the issuer's JWKS. Their audience is this server's own
15
+ * public MCP address (`auth.resource`, RFC 8707): a token signed for another
16
+ * app is refused whatever that app calls itself. The `clegra` claim says
17
+ * who is calling for which installation; the tenant handlers see is the
18
+ * installation of that issuer (`<installation>@<issuer>`), so one issuer
19
+ * can never name another's. A workspace host's token is for one request
20
+ * (60 seconds, used once). A workspace host proves a person's confirmation
21
+ * with a second JWT (`clegra-confirm+jwt`) bound to the installation, the
22
+ * call and the arguments as sent.
23
+ *
24
+ * Dev mode: the SDK is its own authorization server with a local key
25
+ * (DevAuthority below), for callers on a loopback address only.
26
+ */
27
+ export { CONFIRMATION_TYPE };
28
+ export declare const DEV_ISSUER = "clegra-dev";
29
+ /** The `typ` of an access token (RFC 9068). */
30
+ export declare const ACCESS_TOKEN_TYPE = "at+jwt";
31
+ /** How long a workspace host's access token may live: it is for one request. */
32
+ export declare const HOST_TOKEN_SECONDS = 60;
33
+ export declare const INSTALLATION: RegExp;
34
+ /** The tenant of a caller: the installation as its issuer names it, bound to that issuer. */
35
+ export declare const tenantOf: (installation: string, issuer: string) => string;
36
+ export type Person = {
37
+ id: string;
38
+ name: string;
39
+ };
40
+ /** Who is calling, as every handler sees it (`ctx`). */
41
+ export type Caller = {
42
+ /** The tenant: the installation bound to its issuer (`<installation>@<issuer>`). Unique across issuers. */
43
+ installation: string;
44
+ /** The installation as the issuer names it (the token's claim; what a confirmation proof repeats). */
45
+ installationId: string;
46
+ person: Person | null;
47
+ permissions: ReadonlySet<string>;
48
+ locale?: string;
49
+ /** `workspace`: a host that confirms writes itself and sends proofs; `plain`: any other MCP host. */
50
+ host: "workspace" | "plain";
51
+ issuer: string;
52
+ subject: string;
53
+ };
54
+ /** The `clegra` claim of an access token. */
55
+ export type HostClaim = {
56
+ installation: string;
57
+ person?: Person;
58
+ permissions?: string[];
59
+ locale?: string;
60
+ host?: "workspace" | "plain";
61
+ };
62
+ export type Issuer = {
63
+ /** The token's `iss`, exactly. */
64
+ issuer: string;
65
+ /** Its key set; default `<issuer>/.well-known/jwks.json`. */
66
+ jwksUri?: string;
67
+ /** Its keys given here instead (tests, a host on the same machine). */
68
+ jwks?: {
69
+ keys: JWK[];
70
+ };
71
+ };
72
+ /**
73
+ * Who a token of the app's own names, as `auth.resolve` says it. The tenant is
74
+ * the app's to say (an organization, a workspace, an account): never a value a
75
+ * request parameter carries.
76
+ */
77
+ export type ResolvedCaller = {
78
+ /** The tenant handlers scope every read and write by: `[A-Za-z0-9._:-]{1,128}` (no `@`: a host's tenants are `<installation>@<issuer>`, so the two can never meet). */
79
+ installation: string;
80
+ person: Person | null;
81
+ /** What this person may do here, from the app's own roles. */
82
+ permissions: readonly string[] | "all";
83
+ locale?: string;
84
+ /** A stable id of who is calling (default the person's id): idempotency is kept per subject. */
85
+ subject?: string;
86
+ };
87
+ /** What `auth.resolve` is told about the request beside the token. */
88
+ export type ResolveInfo = {
89
+ /** This server's public MCP address: the audience the token must have been issued for (RFC 8707). */
90
+ resource: string;
91
+ };
92
+ /**
93
+ * Verifies a token of the app's own and names its caller: null when the token is not one (the request is
94
+ * refused with a 401 and the protected-resource metadata), or throws an `AuthError` with the reason. It MUST
95
+ * check the signature, the expiry and that the token's audience is `info.resource`.
96
+ */
97
+ export type CallerResolver = (token: string, request: Request, info: ResolveInfo) => Promise<ResolvedCaller | null> | ResolvedCaller | null;
98
+ export type AuthOptions = {
99
+ /** The app's own access tokens (spec §7, «The app's own tokens»): verified by the app, mapped to a caller. */
100
+ resolve?: CallerResolver;
101
+ /**
102
+ * Answers the app's authorization-server paths that live outside its auth library's mount (RFC 8414
103
+ * metadata under `/.well-known/…`), on the same routes as MCP: null for any other path.
104
+ */
105
+ serve?: (request: Request) => Promise<Response | null> | Response | null;
106
+ /** Workspace hosts whose tokens (with the `clegra` claim) are accepted. With issuers, `resource` is required. */
107
+ issuers?: Issuer[];
108
+ /**
109
+ * This server's public MCP address, exactly as hosts and clients reach it
110
+ * (`https://crm.example.com/mcp`): the only audience (`aud`) accepted from
111
+ * the issuers, and what a host must have installed the app from.
112
+ */
113
+ resource?: string;
114
+ /** The authorization servers named in the protected-resource metadata (default: the issuers'). */
115
+ authorizationServers?: string[];
116
+ /**
117
+ * Dev mode: a local signing key, a minimal authorization server for test
118
+ * people, `app.devToken()`. Off unless set here; refused when NODE_ENV is
119
+ * `production`; answers callers on a loopback address only.
120
+ */
121
+ dev?: boolean | DevOptions;
122
+ /** Serve calls without a token as this caller (local demos only). Off by default; refused when NODE_ENV is `production`. */
123
+ anonymous?: {
124
+ installation: string;
125
+ person?: Person;
126
+ permissions: string[] | "all";
127
+ locale?: string;
128
+ };
129
+ };
130
+ export type DevOptions = {
131
+ /** Test people offered on the sign-in page (default one, «Test person»). */
132
+ people?: (Person & {
133
+ permissions?: string[] | "all";
134
+ })[];
135
+ /** The installation dev tokens are for (default `dev`). */
136
+ installation?: string;
137
+ /**
138
+ * Where the dev key is kept so tokens survive a restart (default `.clegra-dev-key.json` in the working
139
+ * directory); `false` keeps it in memory only. `CLEGRA_DEV_KEY` (a private JWK as JSON) wins over both.
140
+ */
141
+ keyFile?: string | false;
142
+ /** The one-time code the sign-in page asks for (default: random, printed on start). */
143
+ code?: string;
144
+ /** For tests: how a client's metadata document is fetched and its host resolved (default: the global `fetch` and the system resolver). */
145
+ clientMetadata?: ClientMetadataTransport;
146
+ };
147
+ /** How a Client ID Metadata Document is reached: `fetch` gets it, `lookup` gives every address of its host. */
148
+ export type ClientMetadataTransport = {
149
+ fetch?: typeof fetch;
150
+ lookup?: (host: string) => Promise<string[]>;
151
+ };
152
+ export declare class AuthError extends Error {
153
+ constructor(message: string);
154
+ }
155
+ /** JSON with object keys sorted at every depth: what `args` hashes. */
156
+ export declare function canonicalJson(value: unknown): string;
157
+ /** base64url SHA-256 of the arguments' canonical JSON (the proof's `args`). */
158
+ export declare function argsHash(args: unknown): string;
159
+ /** What one request allows: whether dev tokens are accepted (a loopback caller) and the address it came to. */
160
+ export type RequestTrust = {
161
+ dev: boolean;
162
+ requestResource: string | null;
163
+ };
164
+ export declare class TokenVerifier {
165
+ #private;
166
+ constructor(options: AuthOptions, once: (key: string, ttlMs: number) => Promise<boolean>);
167
+ useDev(dev: DevAuthority): void;
168
+ /** Whether a token is one this verifier answers for (a JWT whose `iss` is a configured issuer or the dev authority's), so it is never handed to `auth.resolve`. */
169
+ knows(token: string): boolean;
170
+ /** The caller an access token names. Throws AuthError with the reason. */
171
+ verify(token: string, trust: RequestTrust): Promise<Caller & {
172
+ claims: JWTPayload;
173
+ }>;
174
+ /**
175
+ * Checks a confirmation proof for this caller, installation, tool, arguments (as received), call id and, for a
176
+ * later run, its deadline (`until`, epoch seconds). `at`: verify it as of that moment (a stored proof, checked
177
+ * again when its run is due, at its confirmation time). Gives the proof's `iat` when it holds, else why not.
178
+ */
179
+ checkConfirmation(proof: string, expected: {
180
+ issuer: string;
181
+ subject: string;
182
+ installation: string;
183
+ tool: string;
184
+ args: unknown;
185
+ call: string | null;
186
+ until?: number;
187
+ }, trust: RequestTrust, at?: Date): Promise<{
188
+ ok: true;
189
+ iat: number;
190
+ } | {
191
+ ok: false;
192
+ why: string;
193
+ }>;
194
+ }
195
+ /** A later run's deadline, epoch seconds: its `at` (a date-time string) plus `window` minutes, rounded down. NaN when `at` is not a date-time. */
196
+ export declare function laterDeadline(at: string, windowMinutes: number): number;
197
+ export type SigningKey = {
198
+ privateKey: CryptoKey;
199
+ publicJwk: JWK;
200
+ kid: string;
201
+ };
202
+ export declare function generateSigningKey(): Promise<SigningKey>;
203
+ /** An access token as a host or the dev authority signs it. */
204
+ export declare function signAccessToken(key: SigningKey, claims: {
205
+ iss: string;
206
+ aud: string | string[];
207
+ sub: string;
208
+ clegra: HostClaim;
209
+ lifetimeSeconds?: number;
210
+ scope?: string;
211
+ }): Promise<string>;
212
+ /**
213
+ * A confirmation proof (spec §7): the person confirmed exactly these arguments, as sent, for this call of this
214
+ * installation. `until` (epoch seconds), for an action with `later`: the run's deadline, `at` + `window` minutes
215
+ * (`laterDeadline`).
216
+ */
217
+ export declare function signConfirmation(key: SigningKey, claims: {
218
+ iss: string;
219
+ aud: string;
220
+ sub: string;
221
+ installation: string;
222
+ tool: string;
223
+ args: unknown;
224
+ call: string;
225
+ until?: number;
226
+ lifetimeSeconds?: number;
227
+ }): Promise<string>;
228
+ export declare function isLoopback(host: string | null | undefined): boolean;
229
+ /** Wrong sign-in codes before the dev sign-in closes until the app restarts. */
230
+ export declare const DEV_CODE_ATTEMPTS = 5;
231
+ /**
232
+ * A client may identify itself with the https URL of a JSON document that
233
+ * describes it (OAuth Client ID Metadata Documents, what MCP clients use
234
+ * since the 2025-11-25 authorization spec). The server fetches a URL that
235
+ * whoever opens the sign-in page chose (through a tunnel that is anyone), so
236
+ * the fetch must never reach this machine or its network: everything below
237
+ * that refuses an address is there for that.
238
+ */
239
+ /** How a client with a key pair may sign its `client_assertion` (RFC 7523): asymmetric only, never `none` or a shared-secret HMAC. */
240
+ export declare const CLIENT_ASSERTION_ALGS: readonly ["RS256", "ES256", "PS256"];
241
+ export type ClientAssertionAlg = (typeof CLIENT_ASSERTION_ALGS)[number];
242
+ /** The `client_assertion_type` of a signed-JWT client authentication (RFC 7523 §2.2). */
243
+ export declare const CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
244
+ /** How long a client assertion may live (exp − now, and exp − iat), and the clock skew allowed on top. */
245
+ export declare const CLIENT_ASSERTION_MAX_SECONDS = 300;
246
+ /**
247
+ * What the dev authorization server keeps of a client's metadata document. A
248
+ * public client has only the first three; a client that authenticates with a
249
+ * key pair (`private_key_jwt`, RFC 7523) also has its signing algorithm and
250
+ * its keys, as a `jwks_uri` or inline `jwks`.
251
+ */
252
+ export type ClientMetadata = {
253
+ client_id: string;
254
+ client_name?: string;
255
+ redirect_uris: string[];
256
+ token_endpoint_auth_method?: "private_key_jwt";
257
+ token_endpoint_auth_signing_alg?: ClientAssertionAlg;
258
+ jwks_uri?: string;
259
+ jwks?: {
260
+ keys: JWK[];
261
+ };
262
+ };
263
+ /** Why a client's metadata document, or its address, is refused. */
264
+ export declare class ClientMetadataError extends Error {
265
+ constructor(message: string);
266
+ }
267
+ export declare const CLIENT_METADATA_MAX_BYTES: number;
268
+ export declare const CLIENT_METADATA_TIMEOUT_MS = 5000;
269
+ /**
270
+ * Whether an IP address (v4 or v6, brackets allowed) is one on the public
271
+ * internet. False for loopback, private, link-local, carrier-grade NAT,
272
+ * unique-local, multicast, unspecified, documentation and reserved ranges,
273
+ * for an IPv6 address that carries one of those IPv4 addresses (mapped,
274
+ * NAT64, 6to4), and for anything that is not an IP address.
275
+ */
276
+ export declare function isPublicAddress(address: string): boolean;
277
+ /** Why a `client_id` is not a valid Client ID Metadata Document URL; null when it is one. */
278
+ export declare function clientMetadataUrlProblem(clientId: string): string | null;
279
+ export declare const isClientMetadataUrl: (clientId: string) => boolean;
280
+ /** A client's key set, checked: 1–20 public keys (no private or symmetric key material). Throws ClientMetadataError. */
281
+ export declare function validateClientJwks(value: unknown, where?: string): {
282
+ keys: JWK[];
283
+ };
284
+ /** A fetched metadata document, checked: it must be the document of exactly this `client_id`, of a public client or of one that signs with a key pair (`private_key_jwt`). Throws ClientMetadataError. */
285
+ export declare function validateClientMetadata(clientId: string, document: unknown): ClientMetadata;
286
+ /**
287
+ * Whether `redirect` is one of a client's registered redirect URIs: the same
288
+ * string, with one exception (RFC 8252 §7.3): for `http://127.0.0.1`,
289
+ * `http://localhost` and `http://[::1]` the port may differ, because a native
290
+ * client listens on whatever port the system gives it.
291
+ */
292
+ export declare function redirectUriAllowed(redirect: string, registered: readonly string[]): boolean;
293
+ /** How long a fetched document may be kept, in seconds, from its `Cache-Control`: 0 for `no-store`/`no-cache`, else `max-age` held between a minute and a day, five minutes without one. */
294
+ export declare function clientMetadataCacheSeconds(cacheControl: string | null): number;
295
+ /**
296
+ * Fetches and checks the metadata document of a URL `client_id`. Nothing is
297
+ * requested unless the URL is valid and every address its host resolves to
298
+ * is public; redirects are not followed; the answer must be 200, JSON, at
299
+ * most 64 KB, within 5 seconds. Throws ClientMetadataError.
300
+ *
301
+ * The limit of this: the addresses are checked, then `fetch` resolves the
302
+ * name again, so a DNS server that answers differently the second time (DNS
303
+ * rebinding) gets the request sent to an address that was not checked. What
304
+ * it can do with that is small (https only, so the internal host would have
305
+ * to hold a certificate for the attacker's name; no redirects; the body is
306
+ * only ever parsed as a metadata document), but it is not nothing: a
307
+ * production authorization server should pin the connection to the address
308
+ * it checked.
309
+ */
310
+ export declare function fetchClientMetadata(clientId: string, transport?: ClientMetadataTransport): Promise<{
311
+ metadata: ClientMetadata;
312
+ cacheSeconds: number;
313
+ }>;
314
+ /** Fetches and checks the key set of a `private_key_jwt` client from its `jwks_uri`, with the same protections as the metadata document. Throws ClientMetadataError. */
315
+ export declare function fetchClientJwks(jwksUri: string, transport?: ClientMetadataTransport): Promise<{
316
+ jwks: {
317
+ keys: JWK[];
318
+ };
319
+ cacheSeconds: number;
320
+ }>;
321
+ /**
322
+ * A minimal OAuth 2.1 authorization server for development (spec §7): clients
323
+ * identify themselves with a Client ID Metadata Document URL (fetched and
324
+ * checked, above) or register dynamically (any client); authorization code
325
+ * with PKCE S256, a sign-in page listing test people that asks for the code
326
+ * printed on the console (five wrong codes close the sign-in until the app
327
+ * restarts), refresh tokens. Stateless but for a small cache of client
328
+ * documents: codes and refresh tokens are JWTs signed with the dev key.
329
+ * Every token's issuer is the origin the request came to (so a tunnel
330
+ * works); the key is what is checked. The server answers it only to callers
331
+ * on a loopback address (server.ts).
332
+ */
333
+ export declare class DevAuthority {
334
+ #private;
335
+ readonly options: DevOptions;
336
+ private readonly app;
337
+ readonly code: string;
338
+ readonly people: (Person & {
339
+ permissions?: string[] | "all";
340
+ })[];
341
+ readonly installation: string;
342
+ publicKey: CryptoKey;
343
+ constructor(options: DevOptions, app: {
344
+ name: string;
345
+ title: string;
346
+ allPermissions: () => string[];
347
+ });
348
+ start(): Promise<void>;
349
+ get key(): SigningKey;
350
+ /** Whether `iss` is one of the dev authority's (its fixed name or an origin it answered on). */
351
+ issues(iss: string): boolean;
352
+ permissionsOf(person: {
353
+ permissions?: string[] | "all";
354
+ } | undefined): string[];
355
+ /**
356
+ * A dev access token. `person: null`: no person — with `host: "workspace"` the installation-level caller (the host
357
+ * calling for the installation itself: schedules, later runs, lifecycle), `sub` = `installation:<installation>`,
358
+ * no permissions unless given.
359
+ */
360
+ token(input: {
361
+ person?: string | Person | null;
362
+ permissions?: string[] | "all";
363
+ host?: "workspace" | "plain";
364
+ installation?: string;
365
+ locale?: string;
366
+ audience: string;
367
+ issuer?: string;
368
+ }): Promise<string>;
369
+ /** Answers the authorization server's paths; null for any other path. */
370
+ handle(request: Request, origin: string, resource: string): Promise<Response | null>;
371
+ }