@clegra/sdk 0.0.0-stage → 0.1.0-next.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/CHANGELOG.md +158 -0
- package/LICENSE +21 -0
- package/NOTICE.md +25 -0
- package/README.md +258 -2
- package/dist/spec/kinds.json +211 -0
- package/dist/spec/schema/clegra.schema.json +1249 -0
- package/dist/spec/src/cli.d.ts +2 -0
- package/dist/spec/src/cli.js +21 -0
- package/dist/spec/src/cli.js.map +1 -0
- package/dist/spec/src/conformance.d.ts +34 -0
- package/dist/spec/src/conformance.js +704 -0
- package/dist/spec/src/conformance.js.map +1 -0
- package/dist/spec/src/init/index.d.ts +31 -0
- package/dist/spec/src/init/index.js +151 -0
- package/dist/spec/src/init/index.js.map +1 -0
- package/dist/spec/src/init/next-config.d.ts +19 -0
- package/dist/spec/src/init/next-config.js +77 -0
- package/dist/spec/src/init/next-config.js.map +1 -0
- package/dist/spec/src/init/project.d.ts +44 -0
- package/dist/spec/src/init/project.js +141 -0
- package/dist/spec/src/init/project.js.map +1 -0
- package/dist/spec/src/init/templates.d.ts +20 -0
- package/dist/spec/src/init/templates.js +166 -0
- package/dist/spec/src/init/templates.js.map +1 -0
- package/dist/spec/src/init/ui.d.ts +30 -0
- package/dist/spec/src/init/ui.js +82 -0
- package/dist/spec/src/init/ui.js.map +1 -0
- package/dist/spec/src/kinds.d.ts +89 -0
- package/dist/spec/src/kinds.js +319 -0
- package/dist/spec/src/kinds.js.map +1 -0
- package/dist/spec/src/protocol.d.ts +50 -0
- package/dist/spec/src/protocol.js +52 -0
- package/dist/spec/src/protocol.js.map +1 -0
- package/dist/spec/src/rules.d.ts +132 -0
- package/dist/spec/src/rules.js +282 -0
- package/dist/spec/src/rules.js.map +1 -0
- package/dist/src/auth.d.ts +371 -0
- package/dist/src/auth.js +964 -0
- package/dist/src/auth.js.map +1 -0
- package/dist/src/define.d.ts +249 -0
- package/dist/src/define.js +83 -0
- package/dist/src/define.js.map +1 -0
- package/dist/src/embed.d.ts +98 -0
- package/dist/src/embed.js +256 -0
- package/dist/src/embed.js.map +1 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +11 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/labels.d.ts +10 -0
- package/dist/src/labels.js +22 -0
- package/dist/src/labels.js.map +1 -0
- package/dist/src/manifest.d.ts +499 -0
- package/dist/src/manifest.js +188 -0
- package/dist/src/manifest.js.map +1 -0
- package/dist/src/meaning.d.ts +64 -0
- package/dist/src/meaning.js +116 -0
- package/dist/src/meaning.js.map +1 -0
- package/dist/src/next/index.d.ts +101 -0
- package/dist/src/next/index.js +187 -0
- package/dist/src/next/index.js.map +1 -0
- package/dist/src/node.d.ts +14 -0
- package/dist/src/node.js +64 -0
- package/dist/src/node.js.map +1 -0
- package/dist/src/server.d.ts +229 -0
- package/dist/src/server.js +2256 -0
- package/dist/src/server.js.map +1 -0
- package/dist/src/store.d.ts +129 -0
- package/dist/src/store.js +213 -0
- package/dist/src/store.js.map +1 -0
- package/dist/src/testing.d.ts +133 -0
- package/dist/src/testing.js +81 -0
- package/dist/src/testing.js.map +1 -0
- package/dist/src/types.d.ts +352 -0
- package/dist/src/types.js +2 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/view.d.ts +35 -0
- package/dist/src/view.js +442 -0
- package/dist/src/view.js.map +1 -0
- package/docs/quickstart.md +350 -0
- package/docs/spec.md +997 -0
- package/package.json +89 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"define.js","sourceRoot":"","sources":["../../src/define.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAuB,MAAM,UAAU,CAAA;AA6NzD,MAAM,SAAS,GAAG,CAAC,CAAgC,EAAuB,EAAE,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC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,EAAE,CAA4B;QAAE,GAAG,CAAC,gBAAgB,CAAC,IAAI,EAAE,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,MAAM,EAAE,aAAa,IAAI,GAAG,CAAC,EAAE,CAAC,CAAA;IAC1K,KAAK,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,IAAI,EAAE,CAAgC;QAAE,GAAG,CAAC,wBAAwB,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IACjI,IAAI,SAAS;QAAE,GAAG,CAAC,iBAAiB,CAAC,SAAS,CAAC,CAAA;IAC/C,6HAA6H;IAC7H,GAAG,CAAC,QAAQ,EAAE,CAAA;IACd,OAAO,GAAG,CAAA;AACZ,CAAC","sourcesContent":["import type { Icon, McpServer } from \"@modelcontextprotocol/server\"\nimport type { z } from \"zod\"\n\nimport type { EntityKind } from \"../spec/src/kinds\"\nimport type { AuthOptions, Caller } from \"./auth\"\nimport type { EmbedOptions } from \"./embed\"\nimport type { Label } from \"./labels\"\nimport { AppServer, type PeopleResolver } from \"./server\"\nimport type { IdempotencyStore } from \"./store\"\nimport type { ActionHandle, ActionResult, Confirm, Context, EntityHandle, Exposure, FragmentInstance, KindConfig, LaterConfig, LifecycleConfig, ListResult, PageConfig, PermissionConfig, Publisher, Query, SettingConfig, Target, TemplateData, ViewSource, Visibility } from \"./types\"\n\n/**\n * defineApp: THE authoring API (spec §1). One typed object holds the whole\n * app — what it is (the manifest part: plain data) and what it does (the\n * handlers: get, list, run, data). The SDK splits the two, serves the\n * manifest, and generates a plain, conformant MCP server from it.\n */\n\ntype Schemas = Record<string, z.ZodObject>\ntype Awaitable<T> = T | Promise<T>\n\nexport type EntityDef<S extends z.ZodObject, P extends string = string> = {\n label: Label\n plural?: Label\n description?: Label\n /** A lucide icon name. */\n icon?: string\n /**\n * What the entity is, the same in every app (spec §3.1): `\"person\"`, `\"organization\"`, `\"event\"`, `\"task\"`,\n * `\"document\"`, `\"product\"`, `\"order\"`, or a namespaced kind (`\"com.example.shipment\"`). Or one kind per record:\n * `{ by: \"type\", map: { company: \"organization\", private: \"person\" } }` over a required enum field. Fields say\n * which property of the kind they hold with `.meta({ as: \"email\" })`. Leave it out for the app's own entities (a deal).\n */\n kind?: EntityKind\n /** A Zod object; fields carry their meaning with `.meta({ role, label, filter, as, … })`. Needs a string `id` and one `role: \"title\"`. */\n schema: S\n /** Who may see records of this entity at all. */\n permission?: P\n get: (id: string, ctx: Context) => Awaitable<z.infer<S> | null>\n /** `query.text` is searched only in `query.textFields` (the search fields the caller may see). */\n list: (query: Query, ctx: Context) => Awaitable<ListResult<z.infer<S>>>\n /** Plain MCP clients: `plain: false` hides the entity's tools; `list` / `get` rename them (default `<entity>_list`, `<entity>_get`). */\n expose?: { plain?: boolean; list?: string; get?: string }\n /** Your own ui:// view for one record, instead of the generated one. */\n view?: ViewSource\n /** `\"app\"`: its tools are for views and the host's own UI only, never for a model (search and fetch leave its records out). */\n visibility?: Visibility\n}\n\ntype ActionBase<I extends z.ZodObject, P extends string> = {\n title: Label\n description?: Label\n icon?: string\n /** The input, a Zod object (`z.object({})` for none). On a record action the SDK adds `id`. */\n input: I\n /** A read: changes nothing. */\n readOnly?: boolean\n /** Writes ask the person first by default (`true` / \"always\"); \"optional\" lets the host decide; `false` / \"never\" never asks. */\n confirm?: boolean | Confirm\n permission?: P\n /** Plain MCP clients: reads are listed by default, writes only with `plain: true`; `tool` renames the tool (default `<entity>_<action>` or `<action>`). */\n expose?: Exposure\n /** `\"app\"`: for views and the host's own UI only, never for a model. */\n visibility?: Visibility\n /**\n * «Approve now, act later», on a write the person confirms: `at` names a required date-time input; the confirmed\n * call is kept (the store's `later` part) and runs at that time, at most `window` minutes late (10–10080, default 60).\n */\n later?: LaterConfig<z.infer<I>>\n}\n\nexport type ActionDef<I extends z.ZodObject, E extends Schemas, P extends string = string> =\n | (ActionBase<I, P> & {\n on?: undefined\n /** Where a host offers the action on something else: an email (`mail.message`) or a record of a kind (`record:organization`), with its input filled from it. At most 4. */\n targets?: Target<z.infer<I>>[]\n run: (input: z.infer<I>, ctx: Context) => Awaitable<ActionResult | void>\n })\n | { [N in keyof E]: ActionBase<I, P> & { /** The entity whose record the action works on. */ on: N; targets?: never; run: (input: z.infer<I>, ctx: Context, record: z.infer<E[N]>) => Awaitable<ActionResult | void> } }[keyof E]\n\ntype FragmentBase<Pm extends z.ZodObject, P extends string, A extends string> = {\n title: Label\n description: Label\n icon?: string\n /** The parameters, a Zod object (`z.object({})` for none). */\n params: Pm\n permission?: P\n /** Actions shown inside, by name (actions without `on`). */\n actions?: A[]\n size?: \"small\" | \"medium\" | \"large\"\n /** Plain MCP clients: `plain: false` hides its tool; `tool` renames it (default `show_<fragment>`). */\n expose?: Exposure\n /** Its texts are written by outsiders (records' names, notes): marked as data for models. */\n untrusted?: boolean\n /** `\"app\"`: its tool is for views and the host's own UI only, never for a model. */\n visibility?: Visibility\n}\n\nexport type FragmentDef<Pm extends z.ZodObject, P extends string = string, A extends string = string> =\n | { [T in keyof TemplateData]: FragmentBase<Pm, P, A> & { /** Drawn by the host (and by the generated view). */ template: T; data: (params: z.infer<Pm>, ctx: Context) => Awaitable<TemplateData[T] | null>; /** Your own ui:// view instead of the generated one. */ view?: ViewSource } }[keyof TemplateData]\n | (FragmentBase<Pm, P, A> & { template?: undefined; /** Your own ui:// view (an MCP Apps document). */ view: ViewSource; data: (params: z.infer<Pm>, ctx: Context) => Awaitable<Record<string, unknown> | null> })\n\ntype PageBase<P extends string, A extends string, F extends string> = {\n title: Label\n icon?: string\n description?: Label\n permission?: P\n /** Plain MCP clients: `plain: false` hides its tool; `tool` renames it (default `open_<page>`). */\n expose?: Exposure\n /** Global actions (without `on`) offered on the page, at most 8; the first is its primary. Page params prefill inputs of the same name. */\n actions?: A[]\n /** A `stat` fragment type without required params: its value is the page's count in the navigation. */\n badge?: F\n}\n\n/** A page is one of: `list`, `record`, `dashboard`, a custom `view`, or a custom `url`. */\nexport type PageDef<E extends Schemas, P extends string = string, A extends string = string, F extends string = string> =\n | (PageBase<P, A, F> & {\n /** A list of this entity's records. */\n list: keyof E & string\n columns: string[]\n /** Parameters of the page (default: the entity's filter fields). With `params`, give `query`. */\n params?: z.ZodObject\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- annotate it with z.infer of your params\n query?: (params: any) => Partial<Pick<Query, \"filters\" | \"text\" | \"sort\">>\n /** Your own ui:// view instead of the generated one. */\n view?: ViewSource\n })\n | (Omit<PageBase<P, A, F>, \"title\" | \"actions\" | \"badge\"> & { /** The page of one record of this entity (every entity has a default one). */ record: keyof E & string; title?: Label; sections?: { title: Label; fields: string[] }[]; view?: ViewSource; actions?: never; badge?: never })\n | (PageBase<P, A, F> & {\n /** Fragments on a grid. */\n dashboard: FragmentInstance[] | ((params: any, ctx: Context) => Awaitable<FragmentInstance[]>) // eslint-disable-line @typescript-eslint/no-explicit-any\n params?: z.ZodObject\n view?: ViewSource\n })\n | (PageBase<P, A, F> & { /** A custom page: your own MCP Apps document. */ view: ViewSource; params?: z.ZodObject })\n | (PageBase<P, A, F> & { /** A custom page: your own site, in an isolated frame. */ url: string; params?: z.ZodObject })\n\nexport type AgentDef = {\n title: Label\n description: Label\n instructions: string\n /** What the agent may use: entity names (their reads), action names, or tool names. */\n uses: string[]\n tier?: \"fast\" | \"standard\" | \"strong\"\n starters?: Label[]\n}\n\n/** A schedule: a global action (readOnly, or a write whose confirm is `never` or `optional`) the workspace host runs as the installation. */\nexport type ScheduleDef<A extends string = string> = {\n action: A\n /** Minutes between runs, 5–1440. */\n every: number\n /** How long a run may take, 1–300 seconds (default 60). */\n maxSeconds?: number\n}\n\n/** A notification type: people mute it per app. */\nexport type NotificationDef<P extends string = string> = {\n label: Label\n description?: Label\n /** false: off until the person turns it on (default true). */\n default?: boolean\n /** Only holders of this permission receive it. */\n permission?: P\n}\n\nexport type AppDefinition<E extends Schemas, A extends Schemas, F extends Schemas, P extends string, G extends string = string> = {\n /** The app id: lowercase letters, digits, `-`; 2–40 characters. */\n name: string\n title: Label\n version: string\n description?: Label\n icons?: Icon[]\n /**\n * Who publishes the app (spec §2): a name and the publisher's web address (https). A claim, granting nothing: a\n * store or host may verify it against the address's domain and show it as verified.\n */\n publisher?: Publisher\n /** The locale of bare-string labels and of tool names and descriptions (default `en`). */\n locale?: string\n /** MCP `instructions` for models. */\n instructions?: string\n websiteUrl?: string\n /**\n * MCP authorization (spec §7): `resolve` for the app's own tokens (its users, from its auth library), `issuers`\n * for workspace hosts, with this server's public MCP address (`resource`); or `dev` locally.\n */\n auth?: AuthOptions\n /** Where the app's own routes live on its public address (default none: MCP at `/mcp`). */\n path?: string\n permissions?: Record<P, PermissionConfig>\n settings?: Record<string, SettingConfig>\n /** Namespaced kinds this app defines (spec §3.1), by name with a dot: `{ \"com.example.shipment\": { label, properties: { trackingNumber: { type: \"string\", key: true } } } }`. */\n kinds?: Record<string, KindConfig>\n entities: { [K in keyof E]: EntityDef<E[K], NoInfer<P>> }\n actions?: { [K in keyof A]: ActionDef<A[K], E, NoInfer<P>> }\n fragments?: { [K in keyof F]: FragmentDef<F[K], NoInfer<P>, keyof A & string> }\n pages?: Record<G, PageDef<E, NoInfer<P>, NoInfer<keyof A & string>, NoInfer<keyof F & string>>>\n /** The navigation: sections of pages, in order (no record pages; each page once). Without it a host shows every non-record page, ungrouped. */\n nav?: { section?: Label; pages: NoInfer<G>[] }[]\n agents?: Record<string, AgentDef>\n /** Actions the workspace host runs as the installation, with nobody at the screen: `{ digest: { action: \"send_digest\", every: 60 } }`. At most 10. */\n schedules?: Record<string, ScheduleDef<NoInfer<keyof A & string>>>\n /** The notification types the app sends (`ctx.notify({ type })`). Without them its notifications are untyped. */\n notifications?: Record<string, NotificationDef<NoInfer<P>>>\n /** Told by the workspace host of its installation's changes; the tenant's data exported and deleted on request. */\n lifecycle?: LifecycleConfig\n /** Escape hatch: the raw McpServer of each request (official MCP SDK), to add hand-written tools, resources and views. `caller` is null before sign-in. */\n mcp?: (server: McpServer, caller: Caller | null) => void\n /** Where write results are kept for idempotency (default: in memory). */\n store?: IdempotencyStore\n /**\n * The names of people of the installation by id: the values of `role: \"person\"` fields. With it (or the dev\n * sign-in) hosts show names, and a person nobody can name as an unknown person, never the id. Without it a\n * person field holds the name itself.\n */\n people?: PeopleResolver\n /**\n * Pages on the app's own site that hosts frame (spec §5.1): the hosts that may frame them (`frameAncestors`), the\n * signing secret (default `CLEGRA_EMBED_SECRET`), their path (default `/embed`). Required with a same-site `url` page.\n */\n embed?: EmbedOptions\n}\n\n/** What defineApp returns: the app, ready to serve. */\nexport type App = Pick<AppServer, \"name\" | \"locale\" | \"manifest\" | \"fetch\" | \"start\" | \"devMode\" | \"uri\" | \"fragmentUri\" | \"parseUri\" | \"createMcpServer\" | \"devToken\" | \"devConfirmation\" | \"embed\" | \"runLater\">\n\nconst confirmOf = (c: boolean | Confirm | undefined): Confirm | undefined => (c === true ? \"always\" : c === false ? \"never\" : c)\n\nexport function defineApp<E extends Schemas, A extends Schemas = Schemas, F extends Schemas = Schemas, P extends string = string, G extends string = string>(def: AppDefinition<E, A, F, P, G>): App {\n const { permissions, settings, kinds, entities, actions, fragments, pages, agents, nav, schedules, notifications, lifecycle, ...options } = def\n const app = new AppServer(options)\n if (kinds) app.defineKinds(kinds)\n for (const [id, p] of Object.entries(permissions ?? {})) app.registerPermission(id, p as PermissionConfig)\n for (const [id, s] of Object.entries(settings ?? {})) app.registerSetting(id, s)\n\n const entityHandles = new Map<string, EntityHandle>()\n for (const [name, e] of Object.entries(entities) as [string, EntityDef<z.ZodObject>][]) entityHandles.set(name, app.registerEntity(name, e) as unknown as EntityHandle)\n const entity = (name: string, where: string) => {\n const h = entityHandles.get(name)\n if (!h) throw new Error(`${where}: \"${name}\" is not an entity of this app`)\n return h\n }\n\n const actionHandles = new Map<string, ActionHandle>()\n type AnyAction = ActionBase<z.ZodObject, string> & { on?: string; run: (input: unknown, ctx: Context, record?: unknown) => Awaitable<ActionResult | void> }\n for (const [name, a] of Object.entries(actions ?? {}) as [string, AnyAction][]) {\n const { on, run, confirm, ...config } = a\n const c = confirmOf(confirm)\n actionHandles.set(name, app.registerAction(name, { ...config, ...(c ? { confirm: c } : {}), ...(on ? { entity: entity(on, `action \"${name}\"`) } : {}) }, (input, ctx, record) => run(input, ctx, record)))\n }\n\n type AnyFragment = FragmentBase<z.ZodObject, string, string> & { template?: keyof TemplateData; view?: ViewSource; data: (params: unknown, ctx: Context) => Awaitable<Record<string, unknown> | null> }\n for (const [type, f] of Object.entries(fragments ?? {}) as [string, AnyFragment][]) {\n const { actions: names, ...config } = f\n const handles = (names ?? []).map((n) => {\n const h = actionHandles.get(n)\n if (!h) throw new Error(`fragment \"${type}\": \"${n}\" is not an action of this app`)\n return h\n })\n app.registerFragment(type, { ...config, ...(handles.length ? { actions: handles } : {}) } as never)\n }\n\n const actionOf = (n: string, where: string) => {\n const h = actionHandles.get(n)\n if (!h) throw new Error(`${where}: \"${n}\" is not an action of this app`)\n return h\n }\n for (const [name, def] of Object.entries(pages ?? {}) as [string, PageDef<Schemas>][]) {\n const where = `page \"${name}\"`\n const { actions: names, ...p } = def as PageDef<Schemas> & { actions?: string[] }\n if (names?.length) Object.assign(p, { actions: names.map((n) => actionOf(n, where)) })\n let config: PageConfig\n if (\"list\" in p) {\n const { list, ...rest } = p\n config = { kind: \"list\", entity: entity(list, where), ...rest } as PageConfig\n } else if (\"record\" in p) {\n const { record, ...rest } = p\n config = { kind: \"record\", entity: entity(record, where), ...rest } as PageConfig\n } else if (\"dashboard\" in p) {\n const { dashboard, ...rest } = p\n config = { kind: \"dashboard\", fragments: dashboard, ...rest } as PageConfig\n } else if (\"url\" in p || \"view\" in p) config = { kind: \"custom\", ...p } as PageConfig\n else throw new Error(`${where}: give one of list, record, dashboard, view or url`)\n app.registerPage(name, config)\n }\n\n for (const [name, a] of Object.entries(agents ?? {})) {\n const { uses, ...config } = a\n app.registerAgent(name, { ...config, tools: uses })\n }\n if (nav) app.registerNav(nav)\n for (const [name, s] of Object.entries(schedules ?? {}) as [string, ScheduleDef][]) app.registerSchedule(name, { ...s, action: actionOf(s.action, `schedule \"${name}\"`) })\n for (const [type, n] of Object.entries(notifications ?? {}) as [string, NotificationDef][]) app.registerNotificationType(type, n)\n if (lifecycle) app.registerLifecycle(lifecycle)\n // The manifest is built (and its references checked) at definition time: a wrong name fails at start, not at the first call.\n app.manifest()\n return app\n}\n"]}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { Caller, Person } from "./auth.js";
|
|
2
|
+
import type { IdempotencyStore } from "./store.js";
|
|
3
|
+
/**
|
|
4
|
+
* EMBEDDED PAGES (spec §5.1). A `url` page on the app's own site (`/embed/pipeline`) is framed by a host on another
|
|
5
|
+
* site, where the app's own session cookie is a third-party cookie and never arrives. So the host, which holds the
|
|
6
|
+
* viewer's token for the app, asks the app for a TICKET (the `clegra_embed` tool): one minute, signed, for one
|
|
7
|
+
* page and one framing origin, used once. The host's frame POSTs it to `<embed path>/_ticket` (a form whose target
|
|
8
|
+
* is the frame: the ticket is never in a URL, the history or a Referer, and the browser itself states the poster's
|
|
9
|
+
* `Origin`, which must be the ticket's). The app answers with a partitioned session cookie for that page's path
|
|
10
|
+
* (`Secure; HttpOnly; SameSite=None; Partitioned`: CHIPS, kept under the host's top-level site only) and a 303 to the
|
|
11
|
+
* page. The page reads the caller from that cookie (`session`). Every embed response says who may frame it:
|
|
12
|
+
* `Content-Security-Policy: frame-ancestors` with the hosts the app declares, never `X-Frame-Options`.
|
|
13
|
+
*
|
|
14
|
+
* Framework-neutral: `exchange(request)` returns a standard Response; `@clegra/sdk/next` wires it into proxy.ts.
|
|
15
|
+
*/
|
|
16
|
+
export type EmbedOptions = {
|
|
17
|
+
/**
|
|
18
|
+
* The hosts that may frame the embed pages (CSP `frame-ancestors` sources). Every frame up to the top-level page
|
|
19
|
+
* must match one, and a ticket is issued only for a framing origin that matches one. Entries: `https://host`
|
|
20
|
+
* (`:port` optional), `https://*.host` (any subdomain), `'self'` (the app's own origin), and outside production
|
|
21
|
+
* `http://localhost[:port|:*]` / `http://127.0.0.1[:port|:*]`.
|
|
22
|
+
*/
|
|
23
|
+
frameAncestors: string[];
|
|
24
|
+
/**
|
|
25
|
+
* The secret tickets and sessions are signed with (HMAC keys derived from it with HKDF, one per use, so a secret
|
|
26
|
+
* the app also uses elsewhere stays separated). 32 characters at least. Default: `CLEGRA_EMBED_SECRET`.
|
|
27
|
+
* Required: without it the ticket tool and the exchange fail with a clear `misconfigured`.
|
|
28
|
+
*/
|
|
29
|
+
secret?: string;
|
|
30
|
+
/** Where the embed pages live (default `/embed`): every same-site `url` page is under it, the exchange at `<path>/_ticket`. */
|
|
31
|
+
path?: string;
|
|
32
|
+
/** How long the session a ticket opens lives, in seconds (default 600, at most 3600). The caller's permissions are the ticket's until then. */
|
|
33
|
+
sessionSeconds?: number;
|
|
34
|
+
};
|
|
35
|
+
/** Who looks at an embedded page: the caller the ticket was issued to, as the app's `resolve` (or a host's token) named it. */
|
|
36
|
+
export type EmbedCaller = {
|
|
37
|
+
readonly page: string;
|
|
38
|
+
/** The tenant, exactly as handlers get it (`ctx.installation`). */
|
|
39
|
+
readonly installation: string;
|
|
40
|
+
readonly person: Person | null;
|
|
41
|
+
readonly permissions: ReadonlySet<string>;
|
|
42
|
+
can(permission: string): boolean;
|
|
43
|
+
readonly locale?: string;
|
|
44
|
+
readonly host: Caller["host"];
|
|
45
|
+
/** The origin of the frame the ticket was posted from. */
|
|
46
|
+
readonly origin: string;
|
|
47
|
+
readonly expiresAt: Date;
|
|
48
|
+
};
|
|
49
|
+
/** The ticket a host posts into its frame: `<form method="post" action={action} target={frame}><input name={field} value={ticket}>`. */
|
|
50
|
+
export type EmbedTicket = {
|
|
51
|
+
page: string;
|
|
52
|
+
action: string;
|
|
53
|
+
field: string;
|
|
54
|
+
ticket: string;
|
|
55
|
+
expiresAt: string;
|
|
56
|
+
};
|
|
57
|
+
/** Why a ticket or a request is refused: a status and a message for the person (the frame shows it). */
|
|
58
|
+
export declare class EmbedError extends Error {
|
|
59
|
+
readonly status: 400 | 401 | 403 | 404 | 405 | 500;
|
|
60
|
+
readonly code: "misconfigured" | "invalid_request" | "invalid_ticket" | "wrong_origin" | "not_framed" | "not_found";
|
|
61
|
+
constructor(status: 400 | 401 | 403 | 404 | 405 | 500, code: "misconfigured" | "invalid_request" | "invalid_ticket" | "wrong_origin" | "not_framed" | "not_found", message: string);
|
|
62
|
+
}
|
|
63
|
+
type EmbedPage = {
|
|
64
|
+
name: string;
|
|
65
|
+
path: string;
|
|
66
|
+
};
|
|
67
|
+
export declare class EmbedAuthority {
|
|
68
|
+
#private;
|
|
69
|
+
readonly path: string;
|
|
70
|
+
readonly exchangePath: string;
|
|
71
|
+
readonly frameAncestors: readonly string[];
|
|
72
|
+
readonly sessionSeconds: number;
|
|
73
|
+
constructor(options: EmbedOptions, store: IdempotencyStore, pages: () => EmbedPage[]);
|
|
74
|
+
/** `frame-ancestors` for every embed response: the declared hosts (CSP sources), nothing else. */
|
|
75
|
+
contentSecurityPolicy(): string;
|
|
76
|
+
/** The headers of every embed response (pages, the exchange, its refusals). */
|
|
77
|
+
headers(): Record<string, string>;
|
|
78
|
+
/** The session cookie of a page. */
|
|
79
|
+
cookieName(page: string): string;
|
|
80
|
+
/** Whether `origin` (a serialized origin) may frame the pages: it matches a declared source. */
|
|
81
|
+
allows(origin: string, appOrigin: string): boolean;
|
|
82
|
+
/** A ticket for `caller` to open `page` in a frame whose document has `origin` (spec §5.1). */
|
|
83
|
+
issue(caller: Caller, pageName: string, origin: string, appOrigin: string): Promise<EmbedTicket>;
|
|
84
|
+
/**
|
|
85
|
+
* `POST <embed path>/_ticket`: the ticket for a session cookie and a 303 to the page. Refused (with a page the frame
|
|
86
|
+
* shows): not a POST, a request that is not a frame's (`Sec-Fetch-Dest` other than `iframe`), an `Origin` that is not
|
|
87
|
+
* the ticket's, a ticket that is expired, from the future, tampered, for another app, page or origin, or used before.
|
|
88
|
+
*/
|
|
89
|
+
exchange(request: Request, appOrigin: string): Promise<Response>;
|
|
90
|
+
/** What a refused embed request answers: a short page the frame shows, framable by the declared hosts. */
|
|
91
|
+
refusal(error: EmbedError): Response;
|
|
92
|
+
/**
|
|
93
|
+
* The caller of an embedded page, from its session cookie: null when there is none, it expired, it is for another
|
|
94
|
+
* page or app, or the request is a top-level navigation (`Sec-Fetch-Dest: document`: the session is for frames).
|
|
95
|
+
*/
|
|
96
|
+
session(pageName: string, cookie: string | undefined, fetchDest: string | null, appOrigin: string): Promise<EmbedCaller | null>;
|
|
97
|
+
}
|
|
98
|
+
export {};
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { hkdfSync, randomUUID } from "node:crypto";
|
|
2
|
+
import { jwtVerify, SignJWT } from "jose";
|
|
3
|
+
import { EMBED_COOKIE_PREFIX, EMBED_EXCHANGE_SEGMENT, EMBED_SESSION_TYPE, EMBED_SKEW_SECONDS, EMBED_TICKET_FIELD, EMBED_TICKET_SECONDS, EMBED_TICKET_TYPE, PROTOCOL_ID } from "../spec/src/protocol.js";
|
|
4
|
+
/** Why a ticket or a request is refused: a status and a message for the person (the frame shows it). */
|
|
5
|
+
export class EmbedError extends Error {
|
|
6
|
+
status;
|
|
7
|
+
code;
|
|
8
|
+
constructor(status, code, message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.name = "EmbedError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const SOURCE = /^(?:'self'|https:\/\/(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*(?::\d{1,5})?|http:\/\/(?:localhost|127\.0\.0\.1)(?::(?:\d{1,5}|\*))?)$/;
|
|
16
|
+
const DEV_SOURCE = /^http:\/\//;
|
|
17
|
+
const EMBED_PATH = /^(\/[a-z0-9][a-z0-9._~-]*)+$/;
|
|
18
|
+
const CLAIM = PROTOCOL_ID;
|
|
19
|
+
export class EmbedAuthority {
|
|
20
|
+
path;
|
|
21
|
+
exchangePath;
|
|
22
|
+
frameAncestors;
|
|
23
|
+
sessionSeconds;
|
|
24
|
+
#secret;
|
|
25
|
+
#store;
|
|
26
|
+
#pages;
|
|
27
|
+
#keys = null;
|
|
28
|
+
constructor(options, store, pages) {
|
|
29
|
+
const path = (options.path ?? "/embed").replace(/\/+$/, "");
|
|
30
|
+
if (!EMBED_PATH.test(path))
|
|
31
|
+
throw new Error(`embed.path "${options.path}": a URL path like /embed (lowercase, no trailing slash)`);
|
|
32
|
+
if (!Array.isArray(options.frameAncestors) || options.frameAncestors.length === 0)
|
|
33
|
+
throw new Error("embed.frameAncestors: name the hosts that may frame the embed pages (https origins, https://*.domain, 'self')");
|
|
34
|
+
for (const s of options.frameAncestors) {
|
|
35
|
+
if (!SOURCE.test(s))
|
|
36
|
+
throw new Error(`embed.frameAncestors: "${s}" is not an origin source (https://host[:port], https://*.host, 'self', or http://localhost / http://127.0.0.1 in development)`);
|
|
37
|
+
if (DEV_SOURCE.test(s) && process.env.NODE_ENV === "production")
|
|
38
|
+
throw new Error(`embed.frameAncestors: "${s}" is a development origin; it is refused in production`);
|
|
39
|
+
}
|
|
40
|
+
const seconds = options.sessionSeconds ?? 600;
|
|
41
|
+
if (!Number.isInteger(seconds) || seconds < 60 || seconds > 3600)
|
|
42
|
+
throw new Error("embed.sessionSeconds: whole seconds from 60 to 3600");
|
|
43
|
+
this.path = path;
|
|
44
|
+
this.exchangePath = `${path}/${EMBED_EXCHANGE_SEGMENT}`;
|
|
45
|
+
this.frameAncestors = [...new Set(options.frameAncestors)];
|
|
46
|
+
this.sessionSeconds = seconds;
|
|
47
|
+
this.#secret = options.secret ?? process.env.CLEGRA_EMBED_SECRET;
|
|
48
|
+
// A missing secret is said when a ticket is asked for (a build may define the app without its environment); a weak one at once.
|
|
49
|
+
if (this.#secret !== undefined && this.#secret.length < 32)
|
|
50
|
+
throw new Error("embed: the signing secret must have 32 characters at least (openssl rand -base64 32)");
|
|
51
|
+
this.#store = store;
|
|
52
|
+
this.#pages = pages;
|
|
53
|
+
}
|
|
54
|
+
/** The keys, derived once from the secret: a clear error without one (in development too: tickets cross processes). */
|
|
55
|
+
#key(use) {
|
|
56
|
+
if (!this.#keys) {
|
|
57
|
+
const secret = this.#secret;
|
|
58
|
+
if (!secret)
|
|
59
|
+
throw new EmbedError(500, "misconfigured", "embed: no signing secret. Set CLEGRA_EMBED_SECRET (32+ random characters: openssl rand -base64 32) or pass embed.secret to defineApp");
|
|
60
|
+
const derive = (info) => new Uint8Array(hkdfSync("sha256", secret, `${PROTOCOL_ID}-embed`, info, 32));
|
|
61
|
+
this.#keys = { ticket: derive("ticket v1"), session: derive("session v1") };
|
|
62
|
+
}
|
|
63
|
+
return this.#keys[use];
|
|
64
|
+
}
|
|
65
|
+
/** `frame-ancestors` for every embed response: the declared hosts (CSP sources), nothing else. */
|
|
66
|
+
contentSecurityPolicy() {
|
|
67
|
+
return `frame-ancestors ${this.frameAncestors.join(" ")}`;
|
|
68
|
+
}
|
|
69
|
+
/** The headers of every embed response (pages, the exchange, its refusals). */
|
|
70
|
+
headers() {
|
|
71
|
+
return { "content-security-policy": this.contentSecurityPolicy(), "referrer-policy": "no-referrer" };
|
|
72
|
+
}
|
|
73
|
+
/** The session cookie of a page. */
|
|
74
|
+
cookieName(page) {
|
|
75
|
+
return `${EMBED_COOKIE_PREFIX}${page}`;
|
|
76
|
+
}
|
|
77
|
+
/** Whether `origin` (a serialized origin) may frame the pages: it matches a declared source. */
|
|
78
|
+
allows(origin, appOrigin) {
|
|
79
|
+
const o = parseOrigin(origin);
|
|
80
|
+
if (!o)
|
|
81
|
+
return false;
|
|
82
|
+
return this.frameAncestors.some((s) => {
|
|
83
|
+
if (s === "'self'")
|
|
84
|
+
return origin === appOrigin;
|
|
85
|
+
const m = /^(https?):\/\/(\*\.)?([^:]+)(?::(\d+|\*))?$/.exec(s);
|
|
86
|
+
if (!m)
|
|
87
|
+
return false;
|
|
88
|
+
const [, scheme, wild, host, port] = m;
|
|
89
|
+
if (o.protocol !== `${scheme}:`)
|
|
90
|
+
return false;
|
|
91
|
+
if (wild ? !o.hostname.endsWith(`.${host}`) : o.hostname !== host)
|
|
92
|
+
return false;
|
|
93
|
+
return port === "*" || (port ?? "") === o.port;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
#page(name) {
|
|
97
|
+
return this.#pages().find((p) => p.name === name) ?? null;
|
|
98
|
+
}
|
|
99
|
+
/** A ticket for `caller` to open `page` in a frame whose document has `origin` (spec §5.1). */
|
|
100
|
+
async issue(caller, pageName, origin, appOrigin) {
|
|
101
|
+
const page = this.#page(pageName);
|
|
102
|
+
if (!page)
|
|
103
|
+
throw new EmbedError(404, "not_found", `"${pageName}" is not an embed page of this app`);
|
|
104
|
+
if (origin === "null")
|
|
105
|
+
throw new EmbedError(400, "wrong_origin", "The frame has no origin (an opaque sandbox): this host can't sign the viewer in to an embedded page. Open the page in a new tab.");
|
|
106
|
+
if (!parseOrigin(origin))
|
|
107
|
+
throw new EmbedError(400, "wrong_origin", `"${origin}" is not an origin (scheme://host[:port])`);
|
|
108
|
+
if (!this.allows(origin, appOrigin))
|
|
109
|
+
throw new EmbedError(403, "wrong_origin", `${origin} may not frame this app's pages (embed.frameAncestors)`);
|
|
110
|
+
const now = Math.floor(Date.now() / 1000);
|
|
111
|
+
const claim = { installation: caller.installation, person: caller.person, permissions: [...caller.permissions], ...(caller.locale ? { locale: caller.locale } : {}), host: caller.host };
|
|
112
|
+
const ticket = await new SignJWT({ page: page.name, origin, [CLAIM]: claim })
|
|
113
|
+
.setProtectedHeader({ alg: "HS256", typ: EMBED_TICKET_TYPE })
|
|
114
|
+
.setIssuer(appOrigin)
|
|
115
|
+
.setAudience(`${appOrigin}${page.path}`)
|
|
116
|
+
.setSubject(caller.person?.id ?? caller.subject)
|
|
117
|
+
.setJti(randomUUID())
|
|
118
|
+
.setIssuedAt(now)
|
|
119
|
+
.setExpirationTime(now + EMBED_TICKET_SECONDS)
|
|
120
|
+
.sign(this.#key("ticket"));
|
|
121
|
+
return { page: page.name, action: `${appOrigin}${this.exchangePath}`, field: EMBED_TICKET_FIELD, ticket, expiresAt: new Date((now + EMBED_TICKET_SECONDS) * 1000).toISOString() };
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* `POST <embed path>/_ticket`: the ticket for a session cookie and a 303 to the page. Refused (with a page the frame
|
|
125
|
+
* shows): not a POST, a request that is not a frame's (`Sec-Fetch-Dest` other than `iframe`), an `Origin` that is not
|
|
126
|
+
* the ticket's, a ticket that is expired, from the future, tampered, for another app, page or origin, or used before.
|
|
127
|
+
*/
|
|
128
|
+
async exchange(request, appOrigin) {
|
|
129
|
+
try {
|
|
130
|
+
return await this.#exchange(request, appOrigin);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
if (error instanceof EmbedError)
|
|
134
|
+
return this.refusal(error);
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
async #exchange(request, appOrigin) {
|
|
139
|
+
if (request.method !== "POST")
|
|
140
|
+
throw new EmbedError(405, "invalid_request", "An embed ticket is posted by the host's frame.");
|
|
141
|
+
const dest = request.headers.get("sec-fetch-dest");
|
|
142
|
+
if (dest !== "iframe")
|
|
143
|
+
throw new EmbedError(403, "not_framed", "An embed ticket opens a page inside a frame only.");
|
|
144
|
+
const origin = request.headers.get("origin");
|
|
145
|
+
if (!origin)
|
|
146
|
+
throw new EmbedError(403, "wrong_origin", "The request has no Origin.");
|
|
147
|
+
const type = request.headers.get("content-type") ?? "";
|
|
148
|
+
if (!/^(application\/x-www-form-urlencoded|multipart\/form-data)\b/i.test(type))
|
|
149
|
+
throw new EmbedError(400, "invalid_request", "The ticket comes in a form.");
|
|
150
|
+
const value = (await request.formData()).get(EMBED_TICKET_FIELD);
|
|
151
|
+
if (typeof value !== "string" || !value)
|
|
152
|
+
throw new EmbedError(400, "invalid_request", "The form has no ticket.");
|
|
153
|
+
let payload;
|
|
154
|
+
try {
|
|
155
|
+
;
|
|
156
|
+
({ payload } = await jwtVerify(value, this.#key("ticket"), { algorithms: ["HS256"], typ: EMBED_TICKET_TYPE, issuer: appOrigin, clockTolerance: EMBED_SKEW_SECONDS, requiredClaims: ["exp", "iat", "jti", "aud"] }));
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
if (error instanceof EmbedError)
|
|
160
|
+
throw error;
|
|
161
|
+
const expired = error.code === "ERR_JWT_EXPIRED";
|
|
162
|
+
throw new EmbedError(401, "invalid_ticket", expired ? "The embed ticket has expired: open the page again from the host." : "The embed ticket is not valid.");
|
|
163
|
+
}
|
|
164
|
+
const now = Math.floor(Date.now() / 1000);
|
|
165
|
+
if (payload.iat > now + EMBED_SKEW_SECONDS || payload.exp - payload.iat > EMBED_TICKET_SECONDS)
|
|
166
|
+
throw new EmbedError(401, "invalid_ticket", "The embed ticket is not valid (its times).");
|
|
167
|
+
const page = typeof payload.page === "string" ? this.#page(payload.page) : null;
|
|
168
|
+
if (!page || payload.aud !== `${appOrigin}${page.path}`)
|
|
169
|
+
throw new EmbedError(401, "invalid_ticket", "The embed ticket is for another page.");
|
|
170
|
+
if (typeof payload.origin !== "string" || payload.origin !== origin)
|
|
171
|
+
throw new EmbedError(403, "wrong_origin", "The embed ticket was issued for another frame.");
|
|
172
|
+
if (!this.allows(origin, appOrigin))
|
|
173
|
+
throw new EmbedError(403, "wrong_origin", `${origin} may not frame this app's pages.`);
|
|
174
|
+
const claim = callerClaim(payload[CLAIM]);
|
|
175
|
+
if (!claim)
|
|
176
|
+
throw new EmbedError(401, "invalid_ticket", "The embed ticket is not valid.");
|
|
177
|
+
if (!(await this.#store.once(`embed:${payload.jti}`, (payload.exp - now + EMBED_SKEW_SECONDS + 1) * 1000)))
|
|
178
|
+
throw new EmbedError(401, "invalid_ticket", "The embed ticket was already used: open the page again from the host.");
|
|
179
|
+
const session = await new SignJWT({ page: page.name, origin, [CLAIM]: claim })
|
|
180
|
+
.setProtectedHeader({ alg: "HS256", typ: EMBED_SESSION_TYPE })
|
|
181
|
+
.setIssuer(appOrigin)
|
|
182
|
+
.setAudience(`${appOrigin}${page.path}`)
|
|
183
|
+
.setSubject(String(payload.sub ?? ""))
|
|
184
|
+
.setIssuedAt(now)
|
|
185
|
+
.setExpirationTime(now + this.sessionSeconds)
|
|
186
|
+
.sign(this.#key("session"));
|
|
187
|
+
const headers = new Headers({ ...this.headers(), "cache-control": "no-store", location: `${appOrigin}${page.path}` });
|
|
188
|
+
headers.append("set-cookie", `${this.cookieName(page.name)}=${session}; Path=${page.path}; Max-Age=${this.sessionSeconds}; Secure; HttpOnly; SameSite=None; Partitioned`);
|
|
189
|
+
return new Response(null, { status: 303, headers });
|
|
190
|
+
}
|
|
191
|
+
/** What a refused embed request answers: a short page the frame shows, framable by the declared hosts. */
|
|
192
|
+
refusal(error) {
|
|
193
|
+
const text = error.message.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
194
|
+
return new Response(`<!doctype html><meta charset="utf-8"><title>Embedded page</title><p style="font:14px system-ui;margin:16px" data-embed-error="${error.code}">${text}</p>`, {
|
|
195
|
+
status: error.status,
|
|
196
|
+
headers: { ...this.headers(), "cache-control": "no-store", "content-type": "text/html; charset=utf-8" },
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* The caller of an embedded page, from its session cookie: null when there is none, it expired, it is for another
|
|
201
|
+
* page or app, or the request is a top-level navigation (`Sec-Fetch-Dest: document`: the session is for frames).
|
|
202
|
+
*/
|
|
203
|
+
async session(pageName, cookie, fetchDest, appOrigin) {
|
|
204
|
+
if (!cookie || fetchDest === "document")
|
|
205
|
+
return null;
|
|
206
|
+
const page = this.#page(pageName);
|
|
207
|
+
if (!page)
|
|
208
|
+
throw new Error(`embed: "${pageName}" is not an embed page of this app (a same-site url page under ${this.path})`);
|
|
209
|
+
let payload;
|
|
210
|
+
try {
|
|
211
|
+
;
|
|
212
|
+
({ payload } = await jwtVerify(cookie, this.#key("session"), { algorithms: ["HS256"], typ: EMBED_SESSION_TYPE, issuer: appOrigin, audience: `${appOrigin}${page.path}`, clockTolerance: EMBED_SKEW_SECONDS, requiredClaims: ["exp", "iat"] }));
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (error instanceof EmbedError)
|
|
216
|
+
throw error;
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
const claim = callerClaim(payload[CLAIM]);
|
|
220
|
+
if (payload.page !== page.name || typeof payload.origin !== "string" || !this.allows(payload.origin, appOrigin) || !claim)
|
|
221
|
+
return null;
|
|
222
|
+
const permissions = new Set(claim.permissions);
|
|
223
|
+
return {
|
|
224
|
+
page: page.name,
|
|
225
|
+
installation: claim.installation,
|
|
226
|
+
person: claim.person,
|
|
227
|
+
permissions,
|
|
228
|
+
can: (p) => permissions.has(p),
|
|
229
|
+
...(claim.locale ? { locale: claim.locale } : {}),
|
|
230
|
+
host: claim.host,
|
|
231
|
+
origin: payload.origin,
|
|
232
|
+
expiresAt: new Date(payload.exp * 1000),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/** `scheme://host[:port]` exactly as a browser serializes an origin (lowercase, no default port, no path), else null. */
|
|
237
|
+
function parseOrigin(value) {
|
|
238
|
+
if (!URL.canParse(value))
|
|
239
|
+
return null;
|
|
240
|
+
const url = new URL(value);
|
|
241
|
+
if (!/^https?:$/.test(url.protocol) || url.origin !== value)
|
|
242
|
+
return null;
|
|
243
|
+
return url;
|
|
244
|
+
}
|
|
245
|
+
function callerClaim(value) {
|
|
246
|
+
if (!value || typeof value !== "object")
|
|
247
|
+
return null;
|
|
248
|
+
const c = value;
|
|
249
|
+
if (typeof c.installation !== "string" || !Array.isArray(c.permissions) || !c.permissions.every((p) => typeof p === "string"))
|
|
250
|
+
return null;
|
|
251
|
+
if (c.host !== "plain" && c.host !== "workspace")
|
|
252
|
+
return null;
|
|
253
|
+
const person = c.person && typeof c.person === "object" && typeof c.person.id === "string" && typeof c.person.name === "string" ? { id: c.person.id, name: c.person.name } : null;
|
|
254
|
+
return { installation: c.installation, person, permissions: c.permissions, ...(typeof c.locale === "string" ? { locale: c.locale } : {}), host: c.host };
|
|
255
|
+
}
|
|
256
|
+
//# sourceMappingURL=embed.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"embed.js","sourceRoot":"","sources":["../../src/embed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAElD,OAAO,EAAE,SAAS,EAAE,OAAO,EAAmB,MAAM,MAAM,CAAA;AAE1D,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAwDpM,wGAAwG;AACxG,MAAM,OAAO,UAAW,SAAQ,KAAK;IAExB;IACA;IAFX,YACW,MAAyC,EACzC,IAA0G,EACnH,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAA;QAJL,WAAM,GAAN,MAAM,CAAmC;QACzC,SAAI,GAAJ,IAAI,CAAsG;QAInH,IAAI,CAAC,IAAI,GAAG,YAAY,CAAA;IAC1B,CAAC;CACF;AAKD,MAAM,MAAM,GAAG,kIAAkI,CAAA;AACjJ,MAAM,UAAU,GAAG,YAAY,CAAA;AAC/B,MAAM,UAAU,GAAG,8BAA8B,CAAA;AACjD,MAAM,KAAK,GAAG,WAAW,CAAA;AAEzB,MAAM,OAAO,cAAc;IAChB,IAAI,CAAQ;IACZ,YAAY,CAAQ;IACpB,cAAc,CAAmB;IACjC,cAAc,CAAQ;IACtB,OAAO,CAAoB;IAC3B,MAAM,CAAkB;IACxB,MAAM,CAAmB;IAClC,KAAK,GAAuD,IAAI,CAAA;IAEhE,YAAY,OAAqB,E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AM,EAAE,WAAW,EAAE,CAAC,CAAC,WAAuB,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAA;AACtK,CAAC","sourcesContent":["import { hkdfSync, randomUUID } from \"node:crypto\"\n\nimport { jwtVerify, SignJWT, type JWTPayload } from \"jose\"\n\nimport { EMBED_COOKIE_PREFIX, EMBED_EXCHANGE_SEGMENT, EMBED_SESSION_TYPE, EMBED_SKEW_SECONDS, EMBED_TICKET_FIELD, EMBED_TICKET_SECONDS, EMBED_TICKET_TYPE, PROTOCOL_ID } from \"../spec/src/protocol\"\nimport type { Caller, Person } from \"./auth\"\nimport type { IdempotencyStore } from \"./store\"\n\n/**\n * EMBEDDED PAGES (spec §5.1). A `url` page on the app's own site (`/embed/pipeline`) is framed by a host on another\n * site, where the app's own session cookie is a third-party cookie and never arrives. So the host, which holds the\n * viewer's token for the app, asks the app for a TICKET (the `clegra_embed` tool): one minute, signed, for one\n * page and one framing origin, used once. The host's frame POSTs it to `<embed path>/_ticket` (a form whose target\n * is the frame: the ticket is never in a URL, the history or a Referer, and the browser itself states the poster's\n * `Origin`, which must be the ticket's). The app answers with a partitioned session cookie for that page's path\n * (`Secure; HttpOnly; SameSite=None; Partitioned`: CHIPS, kept under the host's top-level site only) and a 303 to the\n * page. The page reads the caller from that cookie (`session`). Every embed response says who may frame it:\n * `Content-Security-Policy: frame-ancestors` with the hosts the app declares, never `X-Frame-Options`.\n *\n * Framework-neutral: `exchange(request)` returns a standard Response; `@clegra/sdk/next` wires it into proxy.ts.\n */\n\nexport type EmbedOptions = {\n /**\n * The hosts that may frame the embed pages (CSP `frame-ancestors` sources). Every frame up to the top-level page\n * must match one, and a ticket is issued only for a framing origin that matches one. Entries: `https://host`\n * (`:port` optional), `https://*.host` (any subdomain), `'self'` (the app's own origin), and outside production\n * `http://localhost[:port|:*]` / `http://127.0.0.1[:port|:*]`.\n */\n frameAncestors: string[]\n /**\n * The secret tickets and sessions are signed with (HMAC keys derived from it with HKDF, one per use, so a secret\n * the app also uses elsewhere stays separated). 32 characters at least. Default: `CLEGRA_EMBED_SECRET`.\n * Required: without it the ticket tool and the exchange fail with a clear `misconfigured`.\n */\n secret?: string\n /** Where the embed pages live (default `/embed`): every same-site `url` page is under it, the exchange at `<path>/_ticket`. */\n path?: string\n /** How long the session a ticket opens lives, in seconds (default 600, at most 3600). The caller's permissions are the ticket's until then. */\n sessionSeconds?: number\n}\n\n/** Who looks at an embedded page: the caller the ticket was issued to, as the app's `resolve` (or a host's token) named it. */\nexport type EmbedCaller = {\n readonly page: string\n /** The tenant, exactly as handlers get it (`ctx.installation`). */\n readonly installation: string\n readonly person: Person | null\n readonly permissions: ReadonlySet<string>\n can(permission: string): boolean\n readonly locale?: string\n readonly host: Caller[\"host\"]\n /** The origin of the frame the ticket was posted from. */\n readonly origin: string\n readonly expiresAt: Date\n}\n\n/** The ticket a host posts into its frame: `<form method=\"post\" action={action} target={frame}><input name={field} value={ticket}>`. */\nexport type EmbedTicket = { page: string; action: string; field: string; ticket: string; expiresAt: string }\n\n/** Why a ticket or a request is refused: a status and a message for the person (the frame shows it). */\nexport class EmbedError extends Error {\n constructor(\n readonly status: 400 | 401 | 403 | 404 | 405 | 500,\n readonly code: \"misconfigured\" | \"invalid_request\" | \"invalid_ticket\" | \"wrong_origin\" | \"not_framed\" | \"not_found\",\n message: string,\n ) {\n super(message)\n this.name = \"EmbedError\"\n }\n}\n\ntype EmbedPage = { name: string; path: string }\ntype CallerClaim = { installation: string; person: Person | null; permissions: string[]; locale?: string; host: Caller[\"host\"] }\n\nconst SOURCE = /^(?:'self'|https:\\/\\/(?:\\*\\.)?[a-z0-9-]+(?:\\.[a-z0-9-]+)*(?::\\d{1,5})?|http:\\/\\/(?:localhost|127\\.0\\.0\\.1)(?::(?:\\d{1,5}|\\*))?)$/\nconst DEV_SOURCE = /^http:\\/\\//\nconst EMBED_PATH = /^(\\/[a-z0-9][a-z0-9._~-]*)+$/\nconst CLAIM = PROTOCOL_ID\n\nexport class EmbedAuthority {\n readonly path: string\n readonly exchangePath: string\n readonly frameAncestors: readonly string[]\n readonly sessionSeconds: number\n readonly #secret: string | undefined\n readonly #store: IdempotencyStore\n readonly #pages: () => EmbedPage[]\n #keys: { ticket: Uint8Array; session: Uint8Array } | null = null\n\n constructor(options: EmbedOptions, store: IdempotencyStore, pages: () => EmbedPage[]) {\n const path = (options.path ?? \"/embed\").replace(/\\/+$/, \"\")\n if (!EMBED_PATH.test(path)) throw new Error(`embed.path \"${options.path}\": a URL path like /embed (lowercase, no trailing slash)`)\n if (!Array.isArray(options.frameAncestors) || options.frameAncestors.length === 0) throw new Error(\"embed.frameAncestors: name the hosts that may frame the embed pages (https origins, https://*.domain, 'self')\")\n for (const s of options.frameAncestors) {\n if (!SOURCE.test(s)) throw new Error(`embed.frameAncestors: \"${s}\" is not an origin source (https://host[:port], https://*.host, 'self', or http://localhost / http://127.0.0.1 in development)`)\n if (DEV_SOURCE.test(s) && process.env.NODE_ENV === \"production\") throw new Error(`embed.frameAncestors: \"${s}\" is a development origin; it is refused in production`)\n }\n const seconds = options.sessionSeconds ?? 600\n if (!Number.isInteger(seconds) || seconds < 60 || seconds > 3600) throw new Error(\"embed.sessionSeconds: whole seconds from 60 to 3600\")\n this.path = path\n this.exchangePath = `${path}/${EMBED_EXCHANGE_SEGMENT}`\n this.frameAncestors = [...new Set(options.frameAncestors)]\n this.sessionSeconds = seconds\n this.#secret = options.secret ?? process.env.CLEGRA_EMBED_SECRET\n // A missing secret is said when a ticket is asked for (a build may define the app without its environment); a weak one at once.\n if (this.#secret !== undefined && this.#secret.length < 32) throw new Error(\"embed: the signing secret must have 32 characters at least (openssl rand -base64 32)\")\n this.#store = store\n this.#pages = pages\n }\n\n /** The keys, derived once from the secret: a clear error without one (in development too: tickets cross processes). */\n #key(use: \"ticket\" | \"session\"): Uint8Array {\n if (!this.#keys) {\n const secret = this.#secret\n if (!secret) throw new EmbedError(500, \"misconfigured\", \"embed: no signing secret. Set CLEGRA_EMBED_SECRET (32+ random characters: openssl rand -base64 32) or pass embed.secret to defineApp\")\n const derive = (info: string) => new Uint8Array(hkdfSync(\"sha256\", secret, `${PROTOCOL_ID}-embed`, info, 32))\n this.#keys = { ticket: derive(\"ticket v1\"), session: derive(\"session v1\") }\n }\n return this.#keys[use]\n }\n\n /** `frame-ancestors` for every embed response: the declared hosts (CSP sources), nothing else. */\n contentSecurityPolicy(): string {\n return `frame-ancestors ${this.frameAncestors.join(\" \")}`\n }\n\n /** The headers of every embed response (pages, the exchange, its refusals). */\n headers(): Record<string, string> {\n return { \"content-security-policy\": this.contentSecurityPolicy(), \"referrer-policy\": \"no-referrer\" }\n }\n\n /** The session cookie of a page. */\n cookieName(page: string): string {\n return `${EMBED_COOKIE_PREFIX}${page}`\n }\n\n /** Whether `origin` (a serialized origin) may frame the pages: it matches a declared source. */\n allows(origin: string, appOrigin: string): boolean {\n const o = parseOrigin(origin)\n if (!o) return false\n return this.frameAncestors.some((s) => {\n if (s === \"'self'\") return origin === appOrigin\n const m = /^(https?):\\/\\/(\\*\\.)?([^:]+)(?::(\\d+|\\*))?$/.exec(s)\n if (!m) return false\n const [, scheme, wild, host, port] = m\n if (o.protocol !== `${scheme}:`) return false\n if (wild ? !o.hostname.endsWith(`.${host}`) : o.hostname !== host) return false\n return port === \"*\" || (port ?? \"\") === o.port\n })\n }\n\n #page(name: string): EmbedPage | null {\n return this.#pages().find((p) => p.name === name) ?? null\n }\n\n /** A ticket for `caller` to open `page` in a frame whose document has `origin` (spec §5.1). */\n async issue(caller: Caller, pageName: string, origin: string, appOrigin: string): Promise<EmbedTicket> {\n const page = this.#page(pageName)\n if (!page) throw new EmbedError(404, \"not_found\", `\"${pageName}\" is not an embed page of this app`)\n if (origin === \"null\") throw new EmbedError(400, \"wrong_origin\", \"The frame has no origin (an opaque sandbox): this host can't sign the viewer in to an embedded page. Open the page in a new tab.\")\n if (!parseOrigin(origin)) throw new EmbedError(400, \"wrong_origin\", `\"${origin}\" is not an origin (scheme://host[:port])`)\n if (!this.allows(origin, appOrigin)) throw new EmbedError(403, \"wrong_origin\", `${origin} may not frame this app's pages (embed.frameAncestors)`)\n const now = Math.floor(Date.now() / 1000)\n const claim: CallerClaim = { installation: caller.installation, person: caller.person, permissions: [...caller.permissions], ...(caller.locale ? { locale: caller.locale } : {}), host: caller.host }\n const ticket = await new SignJWT({ page: page.name, origin, [CLAIM]: claim })\n .setProtectedHeader({ alg: \"HS256\", typ: EMBED_TICKET_TYPE })\n .setIssuer(appOrigin)\n .setAudience(`${appOrigin}${page.path}`)\n .setSubject(caller.person?.id ?? caller.subject)\n .setJti(randomUUID())\n .setIssuedAt(now)\n .setExpirationTime(now + EMBED_TICKET_SECONDS)\n .sign(this.#key(\"ticket\"))\n return { page: page.name, action: `${appOrigin}${this.exchangePath}`, field: EMBED_TICKET_FIELD, ticket, expiresAt: new Date((now + EMBED_TICKET_SECONDS) * 1000).toISOString() }\n }\n\n /**\n * `POST <embed path>/_ticket`: the ticket for a session cookie and a 303 to the page. Refused (with a page the frame\n * shows): not a POST, a request that is not a frame's (`Sec-Fetch-Dest` other than `iframe`), an `Origin` that is not\n * the ticket's, a ticket that is expired, from the future, tampered, for another app, page or origin, or used before.\n */\n async exchange(request: Request, appOrigin: string): Promise<Response> {\n try {\n return await this.#exchange(request, appOrigin)\n } catch (error) {\n if (error instanceof EmbedError) return this.refusal(error)\n throw error\n }\n }\n\n async #exchange(request: Request, appOrigin: string): Promise<Response> {\n if (request.method !== \"POST\") throw new EmbedError(405, \"invalid_request\", \"An embed ticket is posted by the host's frame.\")\n const dest = request.headers.get(\"sec-fetch-dest\")\n if (dest !== \"iframe\") throw new EmbedError(403, \"not_framed\", \"An embed ticket opens a page inside a frame only.\")\n const origin = request.headers.get(\"origin\")\n if (!origin) throw new EmbedError(403, \"wrong_origin\", \"The request has no Origin.\")\n const type = request.headers.get(\"content-type\") ?? \"\"\n if (!/^(application\\/x-www-form-urlencoded|multipart\\/form-data)\\b/i.test(type)) throw new EmbedError(400, \"invalid_request\", \"The ticket comes in a form.\")\n const value = (await request.formData()).get(EMBED_TICKET_FIELD)\n if (typeof value !== \"string\" || !value) throw new EmbedError(400, \"invalid_request\", \"The form has no ticket.\")\n\n let payload: JWTPayload & { page?: unknown; origin?: unknown; [CLAIM]?: unknown }\n try {\n ;({ payload } = await jwtVerify(value, this.#key(\"ticket\"), { algorithms: [\"HS256\"], typ: EMBED_TICKET_TYPE, issuer: appOrigin, clockTolerance: EMBED_SKEW_SECONDS, requiredClaims: [\"exp\", \"iat\", \"jti\", \"aud\"] }))\n } catch (error) {\n if (error instanceof EmbedError) throw error\n const expired = (error as { code?: string }).code === \"ERR_JWT_EXPIRED\"\n throw new EmbedError(401, \"invalid_ticket\", expired ? \"The embed ticket has expired: open the page again from the host.\" : \"The embed ticket is not valid.\")\n }\n const now = Math.floor(Date.now() / 1000)\n if (payload.iat! > now + EMBED_SKEW_SECONDS || payload.exp! - payload.iat! > EMBED_TICKET_SECONDS) throw new EmbedError(401, \"invalid_ticket\", \"The embed ticket is not valid (its times).\")\n const page = typeof payload.page === \"string\" ? this.#page(payload.page) : null\n if (!page || payload.aud !== `${appOrigin}${page.path}`) throw new EmbedError(401, \"invalid_ticket\", \"The embed ticket is for another page.\")\n if (typeof payload.origin !== \"string\" || payload.origin !== origin) throw new EmbedError(403, \"wrong_origin\", \"The embed ticket was issued for another frame.\")\n if (!this.allows(origin, appOrigin)) throw new EmbedError(403, \"wrong_origin\", `${origin} may not frame this app's pages.`)\n const claim = callerClaim(payload[CLAIM])\n if (!claim) throw new EmbedError(401, \"invalid_ticket\", \"The embed ticket is not valid.\")\n if (!(await this.#store.once(`embed:${payload.jti}`, (payload.exp! - now + EMBED_SKEW_SECONDS + 1) * 1000))) throw new EmbedError(401, \"invalid_ticket\", \"The embed ticket was already used: open the page again from the host.\")\n\n const session = await new SignJWT({ page: page.name, origin, [CLAIM]: claim })\n .setProtectedHeader({ alg: \"HS256\", typ: EMBED_SESSION_TYPE })\n .setIssuer(appOrigin)\n .setAudience(`${appOrigin}${page.path}`)\n .setSubject(String(payload.sub ?? \"\"))\n .setIssuedAt(now)\n .setExpirationTime(now + this.sessionSeconds)\n .sign(this.#key(\"session\"))\n const headers = new Headers({ ...this.headers(), \"cache-control\": \"no-store\", location: `${appOrigin}${page.path}` })\n headers.append(\"set-cookie\", `${this.cookieName(page.name)}=${session}; Path=${page.path}; Max-Age=${this.sessionSeconds}; Secure; HttpOnly; SameSite=None; Partitioned`)\n return new Response(null, { status: 303, headers })\n }\n\n /** What a refused embed request answers: a short page the frame shows, framable by the declared hosts. */\n refusal(error: EmbedError): Response {\n const text = error.message.replace(/[&<>\"]/g, (c) => ({ \"&\": \"&\", \"<\": \"<\", \">\": \">\", '\"': \""\" })[c]!)\n return new Response(`<!doctype html><meta charset=\"utf-8\"><title>Embedded page</title><p style=\"font:14px system-ui;margin:16px\" data-embed-error=\"${error.code}\">${text}</p>`, {\n status: error.status,\n headers: { ...this.headers(), \"cache-control\": \"no-store\", \"content-type\": \"text/html; charset=utf-8\" },\n })\n }\n\n /**\n * The caller of an embedded page, from its session cookie: null when there is none, it expired, it is for another\n * page or app, or the request is a top-level navigation (`Sec-Fetch-Dest: document`: the session is for frames).\n */\n async session(pageName: string, cookie: string | undefined, fetchDest: string | null, appOrigin: string): Promise<EmbedCaller | null> {\n if (!cookie || fetchDest === \"document\") return null\n const page = this.#page(pageName)\n if (!page) throw new Error(`embed: \"${pageName}\" is not an embed page of this app (a same-site url page under ${this.path})`)\n let payload: JWTPayload & { page?: unknown; origin?: unknown; [CLAIM]?: unknown }\n try {\n ;({ payload } = await jwtVerify(cookie, this.#key(\"session\"), { algorithms: [\"HS256\"], typ: EMBED_SESSION_TYPE, issuer: appOrigin, audience: `${appOrigin}${page.path}`, clockTolerance: EMBED_SKEW_SECONDS, requiredClaims: [\"exp\", \"iat\"] }))\n } catch (error) {\n if (error instanceof EmbedError) throw error\n return null\n }\n const claim = callerClaim(payload[CLAIM])\n if (payload.page !== page.name || typeof payload.origin !== \"string\" || !this.allows(payload.origin, appOrigin) || !claim) return null\n const permissions: ReadonlySet<string> = new Set(claim.permissions)\n return {\n page: page.name,\n installation: claim.installation,\n person: claim.person,\n permissions,\n can: (p) => permissions.has(p),\n ...(claim.locale ? { locale: claim.locale } : {}),\n host: claim.host,\n origin: payload.origin,\n expiresAt: new Date(payload.exp! * 1000),\n }\n }\n}\n\n/** `scheme://host[:port]` exactly as a browser serializes an origin (lowercase, no default port, no path), else null. */\nfunction parseOrigin(value: string): URL | null {\n if (!URL.canParse(value)) return null\n const url = new URL(value)\n if (!/^https?:$/.test(url.protocol) || url.origin !== value) return null\n return url\n}\n\nfunction callerClaim(value: unknown): CallerClaim | null {\n if (!value || typeof value !== \"object\") return null\n const c = value as Record<string, unknown>\n if (typeof c.installation !== \"string\" || !Array.isArray(c.permissions) || !c.permissions.every((p) => typeof p === \"string\")) return null\n if (c.host !== \"plain\" && c.host !== \"workspace\") return null\n const person = c.person && typeof c.person === \"object\" && typeof (c.person as Person).id === \"string\" && typeof (c.person as Person).name === \"string\" ? { id: (c.person as Person).id, name: (c.person as Person).name } : null\n return { installation: c.installation, person, permissions: c.permissions as string[], ...(typeof c.locale === \"string\" ? { locale: c.locale } : {}), host: c.host }\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { defineApp, type ActionDef, type AgentDef, type App, type AppDefinition, type EntityDef, type FragmentDef, type NotificationDef, type PageDef, type ScheduleDef } from "./define.js";
|
|
2
|
+
export { AppError, META_KEY, OWN_ISSUER, type AppEmbed, type ErrorCode, type LaterReport, type PeopleResolver, type SentNotification } from "./server.js";
|
|
3
|
+
export { EmbedError, type EmbedCaller, type EmbedOptions, type EmbedTicket } from "./embed.js";
|
|
4
|
+
export { ref, ROLES, TONES, type FieldMeta, type Role, type Tone } from "./meaning.js";
|
|
5
|
+
export { localize, type Label } from "./labels.js";
|
|
6
|
+
export { argsHash, AuthError, canonicalJson, CONFIRMATION_TYPE, generateSigningKey, laterDeadline, signAccessToken, signConfirmation, type AuthOptions, type Caller, type CallerResolver, type HostClaim, type Issuer, type Person, type ResolvedCaller, type ResolveInfo, type SigningKey } from "./auth.js";
|
|
7
|
+
export { MANIFEST_PATH, manifestJsonSchema, manifestSchema, manifestUri, SPEC_VERSION, type Manifest, type ManifestAction, type ManifestEntity, type ManifestField, type ManifestFragment, type ManifestNotificationType, type ManifestPage, type ManifestSchedule, type ManifestTarget } from "./manifest.js";
|
|
8
|
+
export { MemoryLater, MemoryStore, SqlStore, type IdempotencyStore, type LaterOutcome, type LaterRun, type LaterStore, type SqlQuery } from "./store.js";
|
|
9
|
+
export type { ActionResult, Confirm, Context, ExportFile, Exposure, Filter, FragmentInstance, InstallationState, KindConfig, LaterConfig, LaterInfo, LifecycleConfig, ListResult, Notification, PermissionConfig, Publisher, Query, SettingConfig, Target, TargetName, Template, TemplateData, Value, ViewSource, Visibility } from "./types.js";
|
|
10
|
+
export { LATER_TOOL, INSTALLATION_TOOL, EXPORT_TOOL, DELETE_TOOL } from "../spec/src/protocol.js";
|
|
11
|
+
export { KINDS, RESERVED_KINDS, UNIVERSAL, type EntityKind, type PropertyDef, type PropertyType } from "../spec/src/kinds.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { defineApp } from "./define.js";
|
|
2
|
+
export { AppError, META_KEY, OWN_ISSUER } from "./server.js";
|
|
3
|
+
export { EmbedError } from "./embed.js";
|
|
4
|
+
export { ref, ROLES, TONES } from "./meaning.js";
|
|
5
|
+
export { localize } from "./labels.js";
|
|
6
|
+
export { argsHash, AuthError, canonicalJson, CONFIRMATION_TYPE, generateSigningKey, laterDeadline, signAccessToken, signConfirmation } from "./auth.js";
|
|
7
|
+
export { MANIFEST_PATH, manifestJsonSchema, manifestSchema, manifestUri, SPEC_VERSION } from "./manifest.js";
|
|
8
|
+
export { MemoryLater, MemoryStore, SqlStore } from "./store.js";
|
|
9
|
+
export { LATER_TOOL, INSTALLATION_TOOL, EXPORT_TOOL, DELETE_TOOL } from "../spec/src/protocol.js";
|
|
10
|
+
export { KINDS, RESERVED_KINDS, UNIVERSAL } from "../spec/src/kinds.js";
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAuJ,MAAM,UAAU,CAAA;AACzL,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAA+F,MAAM,UAAU,CAAA;AACtJ,OAAO,EAAE,UAAU,EAAyD,MAAM,SAAS,CAAA;AAC3F,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAwC,MAAM,WAAW,CAAA;AACnF,OAAO,EAAE,QAAQ,EAAc,MAAM,UAAU,CAAA;AAC/C,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,aAAa,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAwJ,MAAM,QAAQ,CAAA;AAC1S,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,cAAc,EAAE,WAAW,EAAE,YAAY,EAAoM,MAAM,YAAY,CAAA;AAC3S,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,QAAQ,EAA2F,MAAM,SAAS,CAAA;AAErJ,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAC9F,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,SAAS,EAAwD,MAAM,mBAAmB,CAAA","sourcesContent":["export { defineApp, type ActionDef, type AgentDef, type App, type AppDefinition, type EntityDef, type FragmentDef, type NotificationDef, type PageDef, type ScheduleDef } from \"./define\"\nexport { AppError, META_KEY, OWN_ISSUER, type AppEmbed, type ErrorCode, type LaterReport, type PeopleResolver, type SentNotification } from \"./server\"\nexport { EmbedError, type EmbedCaller, type EmbedOptions, type EmbedTicket } from \"./embed\"\nexport { ref, ROLES, TONES, type FieldMeta, type Role, type Tone } from \"./meaning\"\nexport { localize, type Label } from \"./labels\"\nexport { argsHash, AuthError, canonicalJson, CONFIRMATION_TYPE, generateSigningKey, laterDeadline, signAccessToken, signConfirmation, type AuthOptions, type Caller, type CallerResolver, type HostClaim, type Issuer, type Person, type ResolvedCaller, type ResolveInfo, type SigningKey } from \"./auth\"\nexport { MANIFEST_PATH, manifestJsonSchema, manifestSchema, manifestUri, SPEC_VERSION, type Manifest, type ManifestAction, type ManifestEntity, type ManifestField, type ManifestFragment, type ManifestNotificationType, type ManifestPage, type ManifestSchedule, type ManifestTarget } from \"./manifest\"\nexport { MemoryLater, MemoryStore, SqlStore, type IdempotencyStore, type LaterOutcome, type LaterRun, type LaterStore, type SqlQuery } from \"./store\"\nexport type { ActionResult, Confirm, Context, ExportFile, Exposure, Filter, FragmentInstance, InstallationState, KindConfig, LaterConfig, LaterInfo, LifecycleConfig, ListResult, Notification, PermissionConfig, Publisher, Query, SettingConfig, Target, TargetName, Template, TemplateData, Value, ViewSource, Visibility } from \"./types\"\nexport { LATER_TOOL, INSTALLATION_TOOL, EXPORT_TOOL, DELETE_TOOL } from \"../spec/src/protocol\"\nexport { KINDS, RESERVED_KINDS, UNIVERSAL, type EntityKind, type PropertyDef, type PropertyType } from \"../spec/src/kinds\"\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LABELS (spec §3): a string in the app's locale, or a map per locale.
|
|
3
|
+
* The card carries the maps; `localize` picks one for a caller.
|
|
4
|
+
*/
|
|
5
|
+
export type Label = string | Readonly<Record<string, string>>;
|
|
6
|
+
/** The label in `locale` (exact, then its language), else the app's `fallback` locale, else the first entry. */
|
|
7
|
+
export declare function localize(label: Label | undefined, locale: string | undefined, fallback: string): string;
|
|
8
|
+
/** A label as the card carries it: always a map, so a host never guesses the language of a bare string. */
|
|
9
|
+
export declare function labelMap(label: Label | undefined, fallback: string): Record<string, string> | undefined;
|
|
10
|
+
export declare function isLabel(value: unknown): value is Label;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** The label in `locale` (exact, then its language), else the app's `fallback` locale, else the first entry. */
|
|
2
|
+
export function localize(label, locale, fallback) {
|
|
3
|
+
if (label === undefined)
|
|
4
|
+
return "";
|
|
5
|
+
if (typeof label === "string")
|
|
6
|
+
return label;
|
|
7
|
+
const tries = [locale, locale?.split("-")[0], fallback, fallback.split("-")[0]].filter((l) => Boolean(l));
|
|
8
|
+
for (const l of tries)
|
|
9
|
+
if (typeof label[l] === "string")
|
|
10
|
+
return label[l];
|
|
11
|
+
return Object.values(label)[0] ?? "";
|
|
12
|
+
}
|
|
13
|
+
/** A label as the card carries it: always a map, so a host never guesses the language of a bare string. */
|
|
14
|
+
export function labelMap(label, fallback) {
|
|
15
|
+
if (label === undefined)
|
|
16
|
+
return undefined;
|
|
17
|
+
return typeof label === "string" ? { [fallback]: label } : { ...label };
|
|
18
|
+
}
|
|
19
|
+
export function isLabel(value) {
|
|
20
|
+
return typeof value === "string" || (typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((v) => typeof v === "string"));
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=labels.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"labels.js","sourceRoot":"","sources":["../../src/labels.ts"],"names":[],"mappings":"AAMA,gHAAgH;AAChH,MAAM,UAAU,QAAQ,CAAC,KAAwB,EAAE,MAA0B,EAAE,QAAgB;IAC7F,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,CAAA;IAClC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAA;IAC3C,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAA;IACtH,KAAK,MAAM,CAAC,IAAI,KAAK;QAAE,IAAI,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,QAAQ;YAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAA;IACxE,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;AACtC,CAAC;AAED,2GAA2G;AAC3G,MAAM,UAAU,QAAQ,CAAC,KAAwB,EAAE,QAAgB;IACjE,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IACzC,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,CAAA;AACzE,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,KAAc;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAA;AACxK,CAAC","sourcesContent":["/**\n * LABELS (spec §3): a string in the app's locale, or a map per locale.\n * The card carries the maps; `localize` picks one for a caller.\n */\nexport type Label = string | Readonly<Record<string, string>>\n\n/** The label in `locale` (exact, then its language), else the app's `fallback` locale, else the first entry. */\nexport function localize(label: Label | undefined, locale: string | undefined, fallback: string): string {\n if (label === undefined) return \"\"\n if (typeof label === \"string\") return label\n const tries = [locale, locale?.split(\"-\")[0], fallback, fallback.split(\"-\")[0]].filter((l): l is string => Boolean(l))\n for (const l of tries) if (typeof label[l] === \"string\") return label[l]\n return Object.values(label)[0] ?? \"\"\n}\n\n/** A label as the card carries it: always a map, so a host never guesses the language of a bare string. */\nexport function labelMap(label: Label | undefined, fallback: string): Record<string, string> | undefined {\n if (label === undefined) return undefined\n return typeof label === \"string\" ? { [fallback]: label } : { ...label }\n}\n\nexport function isLabel(value: unknown): value is Label {\n return typeof value === \"string\" || (typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.values(value).every((v) => typeof v === \"string\"))\n}\n"]}
|