diff --git a/docs/contributing/architecture/data-storage.md b/docs/contributing/architecture/data-storage.md index fd9a0b9cc8..15bf7f0da9 100644 --- a/docs/contributing/architecture/data-storage.md +++ b/docs/contributing/architecture/data-storage.md @@ -1170,13 +1170,13 @@ on write unless a migration backfills existing rows. - `published_bundle_artifacts.dependencies_json` (`0001-squashed-init.sql`) stores package dependency pointers queried with SQLite JSON functions in `packages/worker/src/repo/published-bundle-artifacts-repo.ts`. -- `package_invocation_tokens.package_ids_json`, - `package_invocation_tokens.package_kody_ids_json`, - `package_invocation_tokens.export_names_json`, and - `package_invocation_tokens.sources_json` (`0001-squashed-init.sql`) store - invocation-token scope projections. Keyed invocation replay lives in the - RunLog Durable Object ledger (see [Run records](./run-records.md)); the - current D1 schema has no `package_invocations` table. +- `package_invocation_tokens.export_names_json` and + `package_invocation_tokens.sources_json` + (`0017-package-owned-invocation-tokens.sql`) store per-package + invocation-token scope projections. Each token row also has a required + `package_id`. Keyed invocation replay lives in the RunLog Durable Object + ledger (see [Run records](./run-records.md)); the current D1 schema has no + `package_invocations` table. - `webhook_endpoints` (`0001-squashed-init.sql`) stores per-user minted URL state for `package.json#kody.webhooks`, keyed by `(user_id, package_id, webhook_name)`. URL secrets are SHA-256 hashed; diff --git a/docs/contributing/decisions/0026-package-owned-invocation-tokens.md b/docs/contributing/decisions/0026-package-owned-invocation-tokens.md new file mode 100644 index 0000000000..852988e6fb --- /dev/null +++ b/docs/contributing/decisions/0026-package-owned-invocation-tokens.md @@ -0,0 +1,51 @@ +# 0026: Package-owned invocation tokens + +- **Status:** accepted +- **Date:** 2026-08-19 + +## Context + +Package invocation tokens let a trusted external client call +`POST /@:username/api/package-invocations/:kodyId/:exportName`. The HTTP path +already names the owner and the package. The token table nevertheless stored +cross-package JSON allowlists (`package_ids_json`, `package_kody_ids_json`, +including `*`), denormalized user identity, and a global unique `token_hash` +index. Auth hashed the bearer and looked up across every user, then checked that +the path matched the grant. A standalone `/account/package-invocation-tokens` +page existed to edit those grants. + +That model treated a token as a personal access token. Webhooks already do the +opposite: resolve `@username` and the package from the URL, then compare a +secret on that package's row. Production had seven token rows across three +users; the multi-package and `*` rows were launchers and deploy clients, not a +reason to keep a grant table. + +## Decision + +An invocation token belongs to exactly one saved package. Auth resolves the +owner and package from the URL, then looks up +`(user_id, package_id, token_hash)`. There is no cross-package grant, no +account-level token page, and no global hash index. Export and source allowlists +stay as restrictions _within_ that package. Tokens are created, rotated, and +revoked from the package details page. + +Cross-package HTTP clients call one package (an orchestrator or a discovery +package) and use `packages.invoke` inside Kody, or they speak MCP. They do not +hold a wildcard bearer. + +## Consequences + +Package delete removes that package's tokens. The same raw bearer may exist on +two packages only if two rows share the hash. `last_used_at` is a `waitUntil` +write and does not gate authentication. Identity for audit comes from the +resolved user, not columns on the token row. MCP lists tokens for one package; +`package_get` includes the same metadata. + +The 0017 migration maps single-package grants, expands concrete multi-package +grants into one row per owned package (same hash, new ids), and drops `*` and +other unmapped rows. A row that lists packages in both legacy arrays is treated +as multi-package and exploded from the union. Rewrite `*` rows to a concrete +owned package (typically `raycast`) before 0017 runs. Do not apply 0017 on +production until the new worker is deployed: older workers still read the grant +columns. Cross-package HTTP launchers call the `raycast` package's `invoke` +export, which uses `packages.invoke` internally. diff --git a/docs/contributing/decisions/index.md b/docs/contributing/decisions/index.md index 8582afce73..9d245410f6 100644 --- a/docs/contributing/decisions/index.md +++ b/docs/contributing/decisions/index.md @@ -46,3 +46,4 @@ behavior (see [documentation principles](../documentation.md)). - [0023 — Progressive search disclosure](./0023-progressive-search-disclosure.md) - [0024 — Packages outrank synthesized providers](./0024-packages-outrank-synthesized-providers.md) - [0025 — No package services primitive](./0025-no-package-services-primitive.md) +- [0026 — Package-owned invocation tokens](./0026-package-owned-invocation-tokens.md) diff --git a/docs/contributing/package-invocation-api.md b/docs/contributing/package-invocation-api.md index b9dacce380..a432d84c4a 100644 --- a/docs/contributing/package-invocation-api.md +++ b/docs/contributing/package-invocation-api.md @@ -33,18 +33,20 @@ Authentication uses a private bearer token stored in Kody's database-backed package invocation token table. Kody stores only the token hash for request-time lookup. The raw bearer token is -generated by a trusted client or operator, pasted into the account token -creation flow once, and then sent by the trusted external service as: +generated by a trusted client or operator, pasted into the package details token +form once, and then sent by the trusted external service as: ```http Authorization: Bearer ``` +Each token belongs to exactly one saved package. Auth resolves the owner and +package from the URL, then looks up `(user_id, package_id, token_hash)`. + Each token row includes: - token id and human-readable name -- owning `user_id`, `email`, and `display_name` -- package scope (`package_ids_json` and/or `package_kody_ids_json`) +- owning `user_id` and `package_id` - allowed package exports (`export_names_json`) - allowed request sources (`sources_json`) - `last_used_at` @@ -52,19 +54,18 @@ Each token row includes: The token is not a global backdoor: -- package lookup is user-owned -- package access is scoped by the token row -- export access requires an explicit allowlist +- the path names the owner and package +- the bearer proves access to that package only +- export access requires an explicit allowlist (including per-package `*`) - `source` metadata is checked against the allowlist when provided - tokens can be revoked without deploys - execution uses normal package runtime machinery +- `last_used_at` is a best-effort write and does not gate authentication ### Managing tokens -Signed-in users manage package invocation tokens from: - -- `/account/package-invocation-tokens` -- `/account/package-invocation-tokens/new` +Signed-in users manage invocation tokens on the package details page at +`/account/packages/:packageId`. The creation form accepts the raw token exactly once, hashes it server-side, and stores only the hash. Token list/detail payloads never return the raw token or @@ -72,52 +73,48 @@ token hash. The backing same-origin JSON endpoint is: -- `GET /account/package-invocation-tokens.json` — list owned packages and token - metadata -- `POST /account/package-invocation-tokens.json` with `action: "create"` — - create a token from a raw token and allowlists -- `POST /account/package-invocation-tokens.json` with `action: "update"` — - update token name, allowlists, and optionally replace the stored token hash - from a new raw token -- `POST /account/package-invocation-tokens.json` with `action: "revoke"` — - revoke a token by id -- `POST /account/package-invocation-tokens.json` with `action: "reinstate"` — - reinstate a revoked token by id -- `POST /account/package-invocation-tokens.json` with `action: "delete"` — - permanently delete a token row by id +- `GET /account/packages.json` — list packages; include `selected=` + to load that package's token metadata +- `POST /account/packages.json` with `action: "create-token"` — create a token + for one owned package +- `POST /account/packages.json` with `action: "update-token"` — update token + name, allowlists, and optionally replace the stored token hash from a new raw + token +- `POST /account/packages.json` with `action: "revoke-token"` — revoke a token + by id +- `POST /account/packages.json` with `action: "reinstate-token"` — reinstate a + revoked token by id +- `POST /account/packages.json` with `action: "delete-token"` — permanently + delete a token row by id Create payload shape: ```json { - "action": "create", + "action": "create-token", + "packageId": "", "name": "Trusted external client", "rawToken": "", - "packageKodyIds": ["*"], - "packageIds": [], "exportNames": ["*"], "sources": ["trusted-client"] } ``` -Concrete `packageIds` and `packageKodyIds` must refer to packages owned by the -signed-in user. Package and export allowlists support the deliberate wildcard -value `*`. Source values do not use wildcard matching: if a request includes +Export allowlists support the deliberate wildcard value `*` for every export on +that package. Source values do not use wildcard matching: if a request includes `source`, that exact value must be present in the token's `sources` list. -The `/new` page supports metadata prefill query parameters for setup flows: +Package details support metadata prefill query parameters for setup flows: +- `newToken=1` opens the create form - `name` -- `packageKodyId` / `packageKodyIds` / `kodyId` / `kodyIds` -- `packageId` / `packageIds` - `exportName` / `exportNames` - `allowedSource` / `allowedSources` / `source` / `sources` Snake case and kebab case aliases are accepted for list fields, such as -`package_kody_ids`, `package-kody-ids`, `export_names`, `export-names`, -`allowed_sources`, and `allowed-sources`. Repeat parameters or comma-separate -values. Do not put the raw token in the URL; paste it into the form or submit it -over the authenticated same-origin JSON API. +`export_names`, `export-names`, `allowed_sources`, and `allowed-sources`. Repeat +parameters or comma-separate values. Do not put the raw token in the URL; paste +it into the form or submit it over the authenticated same-origin JSON API. When editing an existing token in the account UI, the raw token field is write-only and optional: leave it blank to preserve the current token hash, or @@ -150,7 +147,8 @@ Fields: - `params` — JSON object passed as the first argument to the package export - `idempotencyKey` — required stable key for replay protection - `source` — optional source label for auditing and token scoping; when present, - it must match the token's `sources_json` allowlist + it must match the token's `sources` list. Omit it or send null when that list + is empty. - `topic` — optional event topic label for downstream logic and logs ## Idempotency @@ -284,13 +282,16 @@ Recommended flow for a trusted external client: 2. copy the raw token to the clipboard or keep it in the client's local secret storage 3. open Kody at - `/account/package-invocation-tokens/new?name=Trusted%20External%20Client&packageKodyIds=*&exportNames=*&sources=trusted-client` + `/account/packages/?newToken=1&name=Trusted%20External%20Client&exportNames=*&sources=trusted-client` 4. paste the raw token into the form and create the token 5. send invocation requests with `Authorization: Bearer ` and `"source": "trusted-client"` -A wildcard token can call any package/export owned by the signed-in Kody user, -but only for requests that identify themselves with an allowed source. +A token with `exportNames: ["*"]` can call any export on that package. When the +token lists allowed sources, the request must send one of those labels as JSON +`source`. An empty source list allows unlabeled requests only; a named `source` +is rejected. Cross-package callers invoke one package (an orchestrator or +discovery package) and use `packages.invoke` inside Kody, or they speak MCP. ## Related diff --git a/docs/contributing/setup-manifest.md b/docs/contributing/setup-manifest.md index bd5b9f145f..7b48e3e604 100644 --- a/docs/contributing/setup-manifest.md +++ b/docs/contributing/setup-manifest.md @@ -533,8 +533,8 @@ Configure these GitHub Actions secrets and variables for workflows: uses it to `POST` `https://kody.codes/@kentcdodds/api/package-invocations/weekly-site-perf/__root__`. Create a token scoped to `weekly-site-perf` / `.` / source `weekly-site-perf` - at `/account/package-invocation-tokens/new`. Not a Worker secret; the weekly - job skips invoke when this is unset.) + on that package's details page. Not a Worker secret; the weekly job skips + invoke when this is unset.) - `SENTRY_AUTH_TOKEN` (optional GitHub **secret**; Sentry auth token with `project:releases` / source map upload permissions — used only by CI to run `npm run sentry:upload-sourcemaps` after deploy) @@ -624,7 +624,7 @@ How to get/set each value: sync a different worker secret than production. - `KODY_PACKAGE_INVOCATION_TOKEN` (optional) - In Kody: open - `/account/package-invocation-tokens/new?name=Weekly%20site%20perf&packageKodyIds=weekly-site-perf&exportNames=.&allowedSources=weekly-site-perf`, + `/account/packages/?newToken=1&name=Weekly%20site%20perf&exportNames=.&allowedSources=weekly-site-perf`, generate a raw token in the browser, and store that value as the repository secret `KODY_PACKAGE_INVOCATION_TOKEN`. Scope it to the `weekly-site-perf` package and source `weekly-site-perf`. The weekly workflow uses it only to diff --git a/docs/contributing/weekly-site-perf.md b/docs/contributing/weekly-site-perf.md index 91cccaaede..59c5ac34f1 100644 --- a/docs/contributing/weekly-site-perf.md +++ b/docs/contributing/weekly-site-perf.md @@ -42,8 +42,9 @@ package. The agent implements an obvious local fix when it can, follows [`.agents/skills/ship-pr/SKILL.md`](../../.agents/skills/ship-pr/SKILL.md), or leaves the tracking issue open when a human should decide. -Create a scoped invocation token at -`https://kody.codes/account/package-invocation-tokens/new?name=Weekly%20site%20perf&packageKodyIds=weekly-site-perf&exportNames=.&allowedSources=weekly-site-perf` +Create a scoped invocation token on the `weekly-site-perf` package details page +(`exportNames=.`, source `weekly-site-perf`) at +`https://kody.codes/account/packages/?newToken=1&name=Weekly%20site%20perf&exportNames=.&allowedSources=weekly-site-perf` and store the raw value as the repository (or org) secret `KODY_PACKAGE_INVOCATION_TOKEN`. Do not put the raw token in the URL. See [setup manifest](./setup-manifest.md). diff --git a/docs/guides/README.md b/docs/guides/README.md index 2d33c1b25b..0b6f710022 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -31,7 +31,7 @@ content: | [values.md](./values.md) | Do not write new values; map existing rows to memories, package storage, repos, secrets, or integrations | | [oauth.md](./oauth.md) | **Start here** for third-party OAuth (`/connect/oauth`, redirect URI, params) | | [account-secret-setup.md](./account-secret-setup.md) | `/account/secrets/new` URL parameters and policies | -| [account-package-invocation-token-setup.md](./account-package-invocation-token-setup.md) | `/account/package-invocation-tokens/new` URL parameters and bearer-token safety policy | +| [account-package-invocation-token-setup.md](./account-package-invocation-token-setup.md) | `/account/packages/:packageId?newToken=1` URL parameters and bearer-token safety policy | ## Provider guides diff --git a/docs/guides/account-package-invocation-token-setup.md b/docs/guides/account-package-invocation-token-setup.md index 8e8ae2e062..14b1cd18ea 100644 --- a/docs/guides/account-package-invocation-token-setup.md +++ b/docs/guides/account-package-invocation-token-setup.md @@ -1,20 +1,19 @@ --- id: package_invocation_token_setup -title: Account package invocation token setup guide +title: Package invocation token setup guide summary: - Hosted /account/package-invocation-tokens/new setup URL shape, owner-scoped + Hosted /account/packages/:packageId?newToken=1 setup URL shape, owner-scoped /@:username/api/package-invocations invocation route shape, query params, and bearer-token safety policy for external package invocation clients. category: platform --- -# Account package invocation token setup guide +# Package invocation token setup guide -Use the hosted **`/account/package-invocation-tokens/new`** page when an -external trusted client needs to call Kody package exports through the package -invocation HTTP API. The agent may construct a prefilled setup URL, but the -agent must never see, generate for chat, or place the raw bearer token in the -URL. +Use the hosted **package details** page when an external trusted client needs to +call one Kody package export through the package invocation HTTP API. The agent +may construct a prefilled setup URL, but the agent must never see, generate for +chat, or place the raw bearer token in the URL. For code that runs inside Kody, never use bearer tokens: statically import the target package (`kody:@scope/package/export`) when its name is known when the @@ -23,32 +22,29 @@ the call must be dynamic. Package invocation tokens are for external systems such as webhooks, gateway proxies, CLIs, or other trusted personal clients that call Kody over HTTP. -## When to use `/account/package-invocation-tokens/new` +## When to use `/account/packages/:packageId?newToken=1` Use it when: -- a non-Kody process must invoke a saved package export +- a non-Kody process must invoke one saved package export - the user will store the raw bearer token in that external system -- package access should be scoped to specific packages, exports, and optional - source labels +- export access should be scoped to specific exports and optional source labels + on that package Do **not** ask the user to paste bearer tokens into chat. Do **not** include a `rawToken`, `token`, `bearer`, or token hash query parameter. -Existing token values can be rotated from the account token editor. That field +Existing token values can be rotated from the package's token editor. That field is write-only and optional: leaving it blank keeps the current bearer value, while pasting a new raw token replaces the stored hash. The UI never shows the existing raw token or token hash. Agents can inspect existing token record metadata with -`package_invocation_token_list` and `package_invocation_token_get`. These -capabilities return record ids, names, package/export/source scopes, timestamps, -last-used metadata, and revocation status for the signed-in user's own records. -They never return raw bearer token values or stored token hashes. - -In the editor, look for the **Token value** section. The **New raw token value** -field is where the user pastes or generates a replacement token value before -saving. +`package_invocation_token_list` (requires `package_id`), +`package_invocation_token_get`, and `package_get` (includes `tokens`). These +capabilities return record ids, names, the owning package, export/source scopes, +timestamps, last-used metadata, and revocation status for the signed-in user's +own records. They never return raw bearer token values or stored token hashes. When the exact bearer value does not matter, the user can click **Generate** in the raw-token field. Kody generates a high-entropy browser-side token, fills the @@ -59,18 +55,18 @@ will not show the raw value again. ## URL format This section is only for token setup. Setup URLs under -`/account/package-invocation-tokens/new` open the browser UI where the signed-in -user creates or rotates a token. They are **not** package invocation URLs and -must not be used by external workers, webhooks, or CLIs as the HTTP API -endpoint. +`/account/packages/:packageId?newToken=1` open the browser UI where the +signed-in user creates a token for that package. They are **not** package +invocation URLs and must not be used by external workers, webhooks, or CLIs as +the HTTP API endpoint. Provide the user a URL like: -`https:///account/package-invocation-tokens/new?name=Webhook%20Dispatcher&packageKodyIds=webhook-dispatcher&exportNames=dispatch-event&allowedSources=webhook-dispatcher` +`https:///account/packages/?newToken=1&name=Webhook%20Dispatcher&exportNames=dispatch-event&allowedSources=webhook-dispatcher` -Wildcard package/export setup for a highly trusted personal client: +Wildcard export setup for a highly trusted client of one package: -`https:///account/package-invocation-tokens/new?name=Trusted%20External%20Client&packageKodyIds=*&exportNames=*&allowedSources=trusted-client` +`https:///account/packages/?newToken=1&name=Trusted%20External%20Client&exportNames=*&allowedSources=trusted-client` ## Query params @@ -78,19 +74,14 @@ Repeat params or comma-separate values for list fields. The form also accepts common snake_case and kebab-case aliases so agents can construct URLs from API field names without extra translation. -| Param | Required | Description | -| ------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------- | -| `name` | yes | Human-readable token name. | -| `packageKodyIds` / `packageKodyId` | yes\* | Saved package `kody.id` values, or `*` for all packages owned by the signed-in Kody user. | -| `kodyIds` / `kodyId` | yes\* | Alias for `packageKodyIds`. | -| `packageIds` / `packageId` | yes\* | Saved package ids, or `*` for all packages owned by the signed-in Kody user. | -| `exportNames` / `exportName` | yes | Package export names. `dispatch-event` is normalized to `./dispatch-event`; `*` allows all exports. | -| `allowedSources` / `allowedSource` | no | Optional exact source labels the external caller may send in request JSON. | -| `sources` / `source` | no | Alias for `allowedSources`. | -| `package_kody_ids`, `package-kody-ids`, etc | no | Snake_case and kebab-case aliases are accepted for the fields above. | - -\* At least one package scope is required: either a package Kody id scope or a -package id scope. +| Param | Required | Description | +| ----------------------------------- | -------- | --------------------------------------------------------------------------------------------------- | +| `newToken` | yes | Set to `1` to open the create form on this package. | +| `name` | no | Human-readable token name. | +| `exportNames` / `exportName` | no | Package export names. `dispatch-event` is normalized to `./dispatch-event`; `*` allows all exports. | +| `allowedSources` / `allowedSource` | no | Optional exact source labels the external caller may send in request JSON. | +| `sources` / `source` | no | Alias for `allowedSources`. | +| `export_names`, `export-names`, etc | no | Snake_case and kebab-case aliases are accepted for the fields above. | ## Invocation URL format @@ -122,62 +113,69 @@ curl -X POST \ }' ``` -When a token is scoped to allowed sources, the request JSON `source` must match -one of those source labels exactly. For Kent's YouTube Worker, use -`"source": "youtube-websub-proxy"`. +When a token lists allowed sources, the request JSON `source` must match one of +those labels exactly. For Kent's YouTube Worker, use +`"source": "youtube-websub-proxy"`. When the list is empty, omit `source` or +send null; a named `source` is rejected. Prefer canonical URL metadata from package discovery over manual string construction. `package_get` and package entity search details include canonical external invocation metadata with the URL, path, route export name, normalized -export name used for token scope checks, and source guidance for each callable -export. +export name used for token scope checks, token setup URL, and source guidance +for each callable export. + +A token belongs to one package. Cross-package HTTP clients call one package (an +orchestrator or discovery package) and use `packages.invoke` inside Kody, or +they speak MCP. ## Agent instructions 1. Identify the saved package and export the external system needs to call. - - Use package Kody ids when possible because they are human-readable. - - Use `*` only for highly trusted personal clients. -2. If debugging an existing setup, call `package_invocation_token_list` or - `package_invocation_token_get` first to confirm which token record exists and - whether its package, export, and allowed-source scopes match the external - caller. Do not ask the user to read token metadata out of the browser UI - unless the capability response is insufficient. -3. Generate a `/account/package-invocation-tokens/new` URL with `name`, package - scope, export scope, and optional `allowedSources`. + - Use `package_get` so the setup URL includes the saved package id. + - Use `*` only when the client should call every export on that package. +2. If debugging an existing setup, call `package_invocation_token_list` with + that `package_id`, `package_invocation_token_get`, or read `tokens` from + `package_get` first to confirm which token record exists and whether its + export and allowed-source scopes match the external caller. Do not ask the + user to read token metadata out of the browser UI unless the capability + response is insufficient. +3. Generate an `/account/packages/?newToken=1` URL with `name`, + export scope, and optional `allowedSources`. 4. Ask the user to open the URL, paste their locally generated raw token into the Raw token field, or click **Generate** and copy/deliver the generated value before creating the token. - - For rotation, ask the user to open the existing token detail URL and paste - or generate the new raw token in the **Token value** section. + - For rotation, ask the user to open the package details page, select the + token, and paste or generate the new raw token. - The external service or secret store must receive the exact raw value that was pasted/generated. 5. Instruct the external caller to send: - `POST` to the canonical owner-scoped invocation URL from package metadata, - not to a `/account/package-invocation-tokens/...` setup URL + not to an `/account/packages/...` setup URL - `Authorization: Bearer ` - - JSON `source` matching one of the allowed sources when sources are scoped + - JSON `source` matching one of the allowed sources when the token lists + sources; omit `source` when the list is empty 6. Never display, log, store in docs, or send raw token material through chat or query params. ## Verification notes for agents -The account token pages are browser-session UI routes. Fetching -`/account/package-invocation-tokens` from MCP `execute` returns an HTML app -shell, not the client-loaded token list, and -`/account/package-invocation-tokens.json` requires the signed-in browser session -cookie. Agents should not treat missing token metadata in the HTML shell as -proof that a token was not saved. +The package details page is a browser-session UI route. Fetching +`/account/packages/:packageId` from MCP `execute` returns an HTML app shell, not +the client-loaded token list, and `/account/packages.json` requires the +signed-in browser session cookie. Agents should not treat missing token metadata +in the HTML shell as proof that a token was not saved. For external invocation smoke tests, check failures in this order: 1. `owner_slug_required`: the endpoint is missing the `@:username` owner slug. Use `/@:username/api/package-invocations/:kodyId/:exportName`; `/api/package-invocations/...` is not an invocation route. -2. `not_found`: verify the owner slug matches the package owner. +2. `not_found`: verify the owner slug matches the package owner and the kody id + names a package that user owns. 3. `invalid_token` or `Invalid package invocation token`: the request reached bearer-token authentication on a correctly shaped owner-scoped endpoint. Rotate the package invocation token or check that the external secret - contains the exact active raw bearer value. + contains the exact active raw bearer value scoped to that package. Package export names and `source` policy are checked only after bearer-token authentication succeeds. diff --git a/docs/use/packages.md b/docs/use/packages.md index ec5081bde1..f5e8ceafbd 100644 --- a/docs/use/packages.md +++ b/docs/use/packages.md @@ -250,7 +250,7 @@ to prevent runaway loops. External trusted clients that must call package exports over HTTP use package invocation tokens instead. Before sending a user to create one, agents should load `coding_guide_get` with `guide: "package_invocation_token_setup"` and -construct a prefilled `/account/package-invocation-tokens/new` URL without raw +construct a prefilled `/account/packages/:packageId?newToken=1` URL without raw token material. Static package imports from ad hoc MCP `execute` code, such as diff --git a/packages/worker/client/client-router.node.test.ts b/packages/worker/client/client-router.node.test.ts index 775bd355fe..7659a1ddc2 100644 --- a/packages/worker/client/client-router.node.test.ts +++ b/packages/worker/client/client-router.node.test.ts @@ -20,18 +20,16 @@ import { routePattern } from '#universal/route-pattern.ts' import { routes } from '#universal/routes.ts' test('client route and loader matching prefer specific static routes over dynamic parents', () => { - const tokenDetailRoute = 'token-detail-route' as unknown as JSX.Element - const newTokenRoute = 'new-token-route' as unknown as JSX.Element + const serverDetailRoute = 'server-detail-route' as unknown as JSX.Element + const newServerRoute = 'new-server-route' as unknown as JSX.Element const routes = { - '/account/package-invocation-tokens/:tokenId': tokenDetailRoute, - '/account/package-invocation-tokens/new': newTokenRoute, + '/account/mcp-servers/:serverId': serverDetailRoute, + '/account/mcp-servers/new': newServerRoute, } - expect(matchRoute('/account/package-invocation-tokens/new', routes)).toBe( - newTokenRoute, - ) - expect(matchRoute('/account/package-invocation-tokens/token-1', routes)).toBe( - tokenDetailRoute, + expect(matchRoute('/account/mcp-servers/new', routes)).toBe(newServerRoute) + expect(matchRoute('/account/mcp-servers/server-1', routes)).toBe( + serverDetailRoute, ) const genericSecretRoute = 'generic-secret-route' as unknown as JSX.Element @@ -51,22 +49,22 @@ test('client route and loader matching prefer specific static routes over dynami const accountLoader = (async () => ({ accountProfile: { ok: true }, })) as RouteLoader - const tokenLoader = (async () => ({ - accountPackageInvocationTokens: { ok: true }, + const serverLoader = (async () => ({ + accountMcpServers: { ok: true }, })) as RouteLoader const loaders = { - '/account/package-invocation-tokens/:tokenId': tokenLoader, - '/account/package-invocation-tokens/new': tokenLoader, + '/account/mcp-servers/:serverId': serverLoader, + '/account/mcp-servers/new': serverLoader, '/account': accountLoader, } expect(matchRouteLoader('/account', loaders)).toBe(accountLoader) - expect( - matchRouteLoader('/account/package-invocation-tokens/new', loaders), - ).toBe(tokenLoader) - expect( - matchRouteLoader('/account/package-invocation-tokens/token-1', loaders), - ).toBe(tokenLoader) + expect(matchRouteLoader('/account/mcp-servers/new', loaders)).toBe( + serverLoader, + ) + expect(matchRouteLoader('/account/mcp-servers/server-1', loaders)).toBe( + serverLoader, + ) const genericSecretLoader = (async () => ({ accountSecrets: { ok: true }, diff --git a/packages/worker/client/lazy-route.tsx b/packages/worker/client/lazy-route.tsx index 88e4f1d69a..da440f31d4 100644 --- a/packages/worker/client/lazy-route.tsx +++ b/packages/worker/client/lazy-route.tsx @@ -254,9 +254,6 @@ registerPreloadPatterns( routePattern(routes.accountMcpServers), routePattern(routes.accountMcpServerNew), routePattern(routes.accountMcpServerDetail), - routePattern(routes.accountPackageInvocationTokens), - routePattern(routes.accountPackageInvocationTokenNew), - routePattern(routes.accountPackageInvocationTokenDetail), routePattern(routes.accountPackages), routePattern(routes.accountPackageDetail), routePattern(routes.accountStars), diff --git a/packages/worker/client/loader-data-context.node.test.ts b/packages/worker/client/loader-data-context.node.test.ts index 10d89a4619..7e011d33b4 100644 --- a/packages/worker/client/loader-data-context.node.test.ts +++ b/packages/worker/client/loader-data-context.node.test.ts @@ -28,16 +28,10 @@ test('loader href helpers normalize URLs and compare pathname and search', () => expect(hrefMatchesSsrUrl('/community?q=beta', '/community')).toBe(false) expect(hrefMatchesSsrUrl('/community', '/community?q=beta')).toBe(false) expect( - hrefMatchesSsrUrl( - '/account/package-invocation-tokens/token-1', - '/account/package-invocation-tokens/token-1', - ), + hrefMatchesSsrUrl('/account/packages/pkg-1', '/account/packages/pkg-1'), ).toBe(true) expect( - hrefMatchesSsrUrl( - '/account/package-invocation-tokens/token-2', - '/account/package-invocation-tokens/token-1', - ), + hrefMatchesSsrUrl('/account/packages/pkg-2', '/account/packages/pkg-1'), ).toBe(false) }) diff --git a/packages/worker/client/routes/account-area.ts b/packages/worker/client/routes/account-area.ts index 6a222f3526..72d6b94698 100644 --- a/packages/worker/client/routes/account-area.ts +++ b/packages/worker/client/routes/account-area.ts @@ -22,10 +22,6 @@ export { AccountMemoriesRoute, accountMemoriesRouteLoader, } from './account-memories.tsx' -export { - AccountPackageInvocationTokensRoute, - accountPackageInvocationTokensRouteLoader, -} from './account-package-invocation-tokens.tsx' export { AccountPackagesRoute, accountPackagesRouteLoader, diff --git a/packages/worker/client/routes/account-management-components.tsx b/packages/worker/client/routes/account-management-components.tsx index 305ab513ee..39759e7215 100644 --- a/packages/worker/client/routes/account-management-components.tsx +++ b/packages/worker/client/routes/account-management-components.tsx @@ -444,7 +444,6 @@ const accountNavItems = [ { href: '/account/stars', label: 'Stars' }, { href: '/account/secrets', label: 'Secrets' }, { href: '/account/integrations', label: 'Integrations' }, - { href: '/account/package-invocation-tokens', label: 'Package tokens' }, { href: '/account/mcp-servers', label: 'MCP servers' }, { href: '/account/memories', label: 'Memories' }, { href: '/account/email', label: 'Email' }, diff --git a/packages/worker/client/routes/account-package-invocation-tokens.tsx b/packages/worker/client/routes/account-package-invocation-tokens.tsx deleted file mode 100644 index a525a750bf..0000000000 --- a/packages/worker/client/routes/account-package-invocation-tokens.tsx +++ /dev/null @@ -1,1856 +0,0 @@ -import { formatTimestamp } from '#client/format-timestamp.ts' -import { readCommaListParams, readTrimmedParam } from '#client/url-params.ts' -import { bytesToBase64Url } from '@kody-internal/shared/base64.ts' -import { - type AccountPackageInvocationTokenListItem, - type AccountPackageInvocationTokensLoaderData, -} from '#universal/loader-data.ts' -import { type Handle, css } from 'remix/ui' -import { on } from '#client/event-mixin.ts' -import { passwordManagerIgnoreProps } from '#client/password-manager-ignore.ts' -import { navigate, readCurrentRouterHref } from '#client/client-router.tsx' -import { createDoubleCheck } from '#client/double-check.ts' -import { createListDetailRoute } from '#client/list-detail-route.ts' -import { createRouteLoadLatch } from '#client/route-load-latch.ts' -import { replaceLocation } from '#client/replace-location.ts' -import { matchesSearchQuery } from '#client/search-filter.ts' -import { writeClipboardText } from '#client/clipboard.ts' -import { tryConsumeRouteLoaderData } from '#client/loader-data-context.tsx' -import { consumeStaleNavigationData } from '#client/navigation-data.ts' -import { - type AccountStatus, - readJson, -} from '#client/routes/account-approval-shared.ts' -import { - routeLoaderRedirect, - type RouteLoaderResult, -} from '#client/route-loader.ts' -import { - colors, - mq, - radius, - spacing, - typography, -} from '#universal/styles/tokens.ts' -import { - cardCss, - cardTitleCss, - descriptionCss, - fieldCss, - fieldLabelCss, - getDangerPillCss, - getGhostButtonCss, - getPillButtonCss, -} from '#universal/styles/style-primitives.ts' -import { - AccountManagementMessage, - AccountManagementShell, - AccountPageHeader, - MetadataGrid, - TimestampValue, - accountInputCss, - accountTextareaCss, -} from './account-management-components.tsx' -import { - RecordTable, - RecordTableSearch, - recordBodyCss, - recordCellClamp, - recordStampCss, -} from './record-table.tsx' - -type PackageOption = - AccountPackageInvocationTokensLoaderData['packages'][number] - -type EditorState = { - name: string - rawToken: string - packageIdsText: string - packageKodyIdsText: string - exportNamesText: string - sourcesText: string -} - -const accountPackageInvocationTokensApiPath = - '/account/package-invocation-tokens.json' -const accountPackageInvocationTokensBasePath = - '/account/package-invocation-tokens' -const packageInvocationTokensRoute = createListDetailRoute( - accountPackageInvocationTokensBasePath, -) -const wildcardScope = '*' - -/** - * Latch key for the list payload. Selection segments and the client-side `q` - * filter do not change the GET response, so keying the latch on the base path - * avoids spurious refetches when only those URL parts change. - */ -function getDataLatchKey(_href: string) { - return accountPackageInvocationTokensBasePath -} - -function readFilterState(href: string) { - return { - search: - new URL(href, 'http://localhost').searchParams.get('q')?.trim() ?? '', - } -} - -const clampedCellCss = css(recordCellClamp(26)) - -function createEmptyEditorState(): EditorState { - return { - name: '', - rawToken: '', - packageIdsText: '', - packageKodyIdsText: '', - exportNamesText: '', - sourcesText: '', - } -} -function createEditorStateFromNewTokenQuery(href: string): EditorState { - const params = new URL(href, 'http://localhost').searchParams - const state = createEmptyEditorState() - const packageIds = readCommaListParams(params, [ - 'packageId', - 'packageIds', - 'package_id', - 'package_ids', - 'package-id', - 'package-ids', - ]) - const packageKodyIds = readCommaListParams(params, [ - 'packageKodyId', - 'packageKodyIds', - 'package_kody_id', - 'package_kody_ids', - 'package-kody-id', - 'package-kody-ids', - 'kodyId', - 'kodyIds', - 'kody_id', - 'kody_ids', - 'kody-id', - 'kody-ids', - ]) - const exportNames = readCommaListParams(params, [ - 'exportName', - 'exportNames', - 'export_name', - 'export_names', - 'export-name', - 'export-names', - ]) - const sources = readCommaListParams(params, [ - 'source', - 'sources', - 'source_name', - 'source_names', - 'source-name', - 'source-names', - 'allowedSource', - 'allowedSources', - 'allowed_source', - 'allowed_sources', - 'allowed-source', - 'allowed-sources', - ]) - return { - ...state, - name: readTrimmedParam(params, 'name') ?? state.name, - packageIdsText: packageIds.join('\n'), - packageKodyIdsText: packageKodyIds.join('\n'), - exportNamesText: exportNames.join('\n'), - sourcesText: sources.join('\n'), - } -} - -export async function accountPackageInvocationTokensRouteLoader( - _url: URL, - signal: AbortSignal, -): Promise { - const response = await fetch(accountPackageInvocationTokensApiPath, { - headers: { Accept: 'application/json' }, - credentials: 'include', - signal, - }) - if (response.status === 401) { - return routeLoaderRedirect('/login') - } - const payload = - await readJson(response) - if (!response.ok || !payload?.ok) { - throw new Error('Unable to load package invocation tokens.') - } - return { accountPackageInvocationTokens: payload } -} - -function getNewTokenQueryKey(href: string) { - const url = new URL(href, 'http://localhost') - if (url.pathname !== `${accountPackageInvocationTokensBasePath}/new`) - return '' - const keys = [ - 'name', - 'packageId', - 'packageIds', - 'package_id', - 'package_ids', - 'package-id', - 'package-ids', - 'packageKodyId', - 'packageKodyIds', - 'package_kody_id', - 'package_kody_ids', - 'package-kody-id', - 'package-kody-ids', - 'kodyId', - 'kodyIds', - 'kody_id', - 'kody_ids', - 'kody-id', - 'kody-ids', - 'exportName', - 'exportNames', - 'export_name', - 'export_names', - 'export-name', - 'export-names', - 'source', - 'sources', - 'source_name', - 'source_names', - 'source-name', - 'source-names', - 'allowedSource', - 'allowedSources', - 'allowed_source', - 'allowed_sources', - 'allowed-source', - 'allowed-sources', - ] - return keys - .map((key) => `${key}=${url.searchParams.getAll(key).join('\u0000')}`) - .join('&') -} - -function parseListText(value: string) { - return value - .split(/[\n,]/) - .map((entry) => entry.trim()) - .filter((entry) => entry.length > 0) -} - -function generatePackageInvocationRawToken() { - const cryptoApi = globalThis.crypto - if (!cryptoApi?.getRandomValues) { - throw new Error('This browser cannot generate secure random tokens.') - } - const bytes = new Uint8Array(32) - cryptoApi.getRandomValues(bytes) - return `kody_${bytesToBase64Url(bytes)}` -} - -function formatScope(values: Array) { - if (values.length === 0) return 'None' - if (values.includes(wildcardScope)) return 'Any' - return values.join(', ') -} - -function tokenStatus(token: AccountPackageInvocationTokenListItem) { - return token.revokedAt ? 'Revoked' : 'Active' -} - -function filterTokens( - tokens: Array, - search: string, - packages: Array, -) { - return tokens.filter((token) => { - const packageNames = packages - .filter( - (pkg) => - token.packageIds.includes(pkg.id) || - token.packageIds.includes(wildcardScope) || - token.packageKodyIds.includes(pkg.kodyId) || - token.packageKodyIds.includes(wildcardScope), - ) - .flatMap((pkg) => [pkg.name, pkg.kodyId]) - return matchesSearchQuery(search, [ - token.name, - tokenStatus(token), - ...token.packageIds, - ...token.packageKodyIds, - ...token.exportNames, - ...token.sources, - ...packageNames, - ]) - }) -} - -function tokenPackageSummary(token: AccountPackageInvocationTokenListItem) { - const scopes = [...token.packageIds, ...token.packageKodyIds] - if (scopes.includes(wildcardScope)) return 'Any package' - const count = scopes.length - if (count === 0) return 'No packages' - return `${count} package${count === 1 ? '' : 's'}` -} - -function tokenStatusCss(token: AccountPackageInvocationTokenListItem) { - return { - display: 'inline-flex', - alignItems: 'center', - width: 'max-content', - padding: `${spacing.xs} ${spacing.sm}`, - borderRadius: radius.full, - fontSize: typography.fontSize.sm, - fontWeight: typography.fontWeight.medium, - backgroundColor: token.revokedAt - ? 'color-mix(in srgb, var(--color-danger) 8%, transparent)' - : colors.primarySoftest, - color: token.revokedAt ? colors.error : colors.primaryText, - } -} - -function createEditorStateFromToken( - token: AccountPackageInvocationTokenListItem, -): EditorState { - return { - name: token.name, - rawToken: '', - packageIdsText: token.packageIds.join('\n'), - packageKodyIdsText: token.packageKodyIds.join('\n'), - exportNamesText: token.exportNames.join('\n'), - sourcesText: token.sources.join('\n'), - } -} - -export function AccountPackageInvocationTokensRoute(handle: Handle) { - let status: AccountStatus = 'loading' - let saveState: - | 'idle' - | 'creating' - | 'updating' - | 'revoking' - | 'reinstating' - | 'deleting' = 'idle' - let username = '' - let invocationUrlOrigin = '' - let packages: Array = [] - let tokens: Array = [] - let editorState = createEmptyEditorState() - let selectedTokenId: string | null = null - let message: string | null = null - let messageTone: 'info' | 'error' = 'info' - const loadLatch = createRouteLoadLatch() - let lastNewTokenQueryKey = '' - let mutationVersion = 0 - let revokeConfirm = false - const deleteTokenCheck = createDoubleCheck(handle) - let editMode = false - - const primaryButtonCss = getPillButtonCss({ size: 'sm' }) - const dangerButtonCss = getDangerPillCss({ size: 'sm' }) - const secondaryButtonCss = getGhostButtonCss({ size: 'sm' }) - - function redirectToLogin() { - saveState = 'idle' - status = 'ready' - if (typeof window !== 'undefined') { - window.location.assign('/login') - } - } - - function getCurrentHref() { - return readCurrentRouterHref(handle) - } - - function getCurrentSearch() { - return new URL(getCurrentHref(), 'http://localhost').search - } - - function buildHrefWithUpdatedSearch(search: string) { - const nextUrl = new URL(getCurrentHref(), 'http://localhost') - if (search) nextUrl.searchParams.set('q', search) - else nextUrl.searchParams.delete('q') - return `${nextUrl.pathname}${nextUrl.search}` - } - - function getCurrentSelectedTokenId() { - return ( - packageInvocationTokensRoute.getSelection(getCurrentHref()).selectedId ?? - selectedTokenId - ) - } - - function syncRouterLocation(nextPath: string) { - // Do not pre-mark the destination as loaded: `navigate` is async - // (preload-then-commit), so until it commits the current href is - // unchanged and a pre-set would make interim renders look like a - // location change and fire a spurious fallback fetch for the old URL. - // The commit render consumes the navigation's preloaded data (or the - // stale marker) and marks the latch itself. - navigate(nextPath) - } - - async function loadTokens(signal: AbortSignal) { - const loadStartedAtMutationVersion = mutationVersion - const href = getCurrentHref() - const latchKey = getDataLatchKey(href) - try { - const response = await fetch(accountPackageInvocationTokensApiPath, { - headers: { Accept: 'application/json' }, - credentials: 'include', - signal, - }) - if (signal.aborted) return - if (response.status === 401) { - redirectToLogin() - return - } - const payload = - await readJson(response) - if (!response.ok || !payload?.ok) { - throw new Error('Unable to load package invocation tokens.') - } - if (loadStartedAtMutationVersion !== mutationVersion) return - if (getDataLatchKey(getCurrentHref()) !== latchKey) return - applyPayload(payload, getCurrentHref()) - status = 'ready' - message = null - messageTone = 'info' - loadLatch.markLoaded(latchKey) - handle.update() - } catch (error) { - if (signal.aborted) return - if (loadStartedAtMutationVersion !== mutationVersion) return - status = 'error' - message = - error instanceof Error - ? error.message - : 'Unable to load package invocation tokens.' - messageTone = 'error' - loadLatch.markFailed(latchKey) - handle.update() - } - } - - function applyPayload( - payload: AccountPackageInvocationTokensLoaderData, - href: string, - ) { - username = payload.username - invocationUrlOrigin = payload.invocationUrlOrigin - packages = payload.packages - tokens = payload.tokens - revokeConfirm = false - deleteTokenCheck.reset() - if (payload.selectedTokenId) { - selectedTokenId = payload.selectedTokenId - const selectedToken = tokens.find( - (token) => token.id === payload.selectedTokenId, - ) - editorState = - selectedToken && !selectedToken.revokedAt - ? createEditorStateFromToken(selectedToken) - : createEmptyEditorState() - lastNewTokenQueryKey = '' - editMode = Boolean(selectedToken && !selectedToken.revokedAt) - return - } - const selection = packageInvocationTokensRoute.getSelection(href) - if (selection.isCreating) { - const queryKey = getNewTokenQueryKey(href) - if (queryKey !== lastNewTokenQueryKey) { - lastNewTokenQueryKey = queryKey - editorState = createEditorStateFromNewTokenQuery(href) - selectedTokenId = null - editMode = false - } - return - } - if (selection.selectedId) { - selectedTokenId = selection.selectedId - const selectedToken = tokens.find( - (token) => token.id === selection.selectedId, - ) - editorState = - selectedToken && !selectedToken.revokedAt - ? createEditorStateFromToken(selectedToken) - : createEmptyEditorState() - lastNewTokenQueryKey = '' - editMode = Boolean(selectedToken && !selectedToken.revokedAt) - return - } - editorState = createEmptyEditorState() - lastNewTokenQueryKey = '' - editMode = false - selectedTokenId = null - } - - function setEditorField(field: keyof EditorState, value: string) { - editorState = { - ...editorState, - [field]: value, - } - } - - function generateEditorRawToken() { - try { - setEditorField('rawToken', generatePackageInvocationRawToken()) - message = - 'Generated a raw token. Copy, save, or deliver it now; Kody will not show it again after saving.' - messageTone = 'info' - } catch (error) { - message = - error instanceof Error - ? error.message - : 'Unable to generate a secure token.' - messageTone = 'error' - } - handle.update() - } - - async function copyEditorRawToken() { - if (!editorState.rawToken || saveState !== 'idle') return - try { - await writeClipboardText(editorState.rawToken) - message = 'Copied raw token to clipboard.' - messageTone = 'info' - } catch { - message = 'Unable to copy token. Select the field and copy it manually.' - messageTone = 'error' - } - handle.update() - } - - function readEditorStateFromForm(form: HTMLFormElement) { - const formData = new FormData(form) - return { - name: String(formData.get('name') ?? '').trim(), - rawToken: String(formData.get('rawToken') ?? '').trim(), - packageIdsText: String(formData.get('packageIds') ?? ''), - packageKodyIdsText: String(formData.get('packageKodyIds') ?? ''), - exportNamesText: String(formData.get('exportNames') ?? ''), - sourcesText: String(formData.get('sources') ?? ''), - } satisfies EditorState - } - - function startNewToken() { - editorState = createEmptyEditorState() - selectedTokenId = null - revokeConfirm = false - deleteTokenCheck.reset() - editMode = false - message = null - messageTone = 'info' - const nextPath = - packageInvocationTokensRoute.buildNewHref(getCurrentSearch()) - syncRouterLocation(nextPath) - lastNewTokenQueryKey = getNewTokenQueryKey(nextPath) - handle.update() - } - - function startEditToken(token: AccountPackageInvocationTokenListItem) { - if (token.revokedAt) return - editorState = createEditorStateFromToken(token) - selectedTokenId = token.id - editMode = true - revokeConfirm = false - deleteTokenCheck.reset() - message = null - messageTone = 'info' - handle.update() - } - - function cancelEditToken() { - const tokenId = getCurrentSelectedTokenId() - selectedTokenId = tokenId - editorState = createEmptyEditorState() - editMode = false - revokeConfirm = false - deleteTokenCheck.reset() - message = null - messageTone = 'info' - syncRouterLocation( - tokenId - ? packageInvocationTokensRoute.buildDetailHref( - tokenId, - getCurrentSearch(), - ) - : packageInvocationTokensRoute.buildListHref(getCurrentSearch()), - ) - handle.update() - } - - async function createToken(form?: HTMLFormElement) { - if (saveState !== 'idle') return - const nextEditorState = form ? readEditorStateFromForm(form) : editorState - editorState = nextEditorState - const packageIds = parseListText(nextEditorState.packageIdsText) - const packageKodyIds = parseListText(nextEditorState.packageKodyIdsText) - const exportNames = parseListText(nextEditorState.exportNamesText) - const sources = parseListText(nextEditorState.sourcesText) - - if (!nextEditorState.name) { - message = 'Token name is required.' - messageTone = 'error' - handle.update() - return - } - if (!nextEditorState.rawToken) { - message = 'Paste the raw token before creating it.' - messageTone = 'error' - handle.update() - return - } - if (packageIds.length === 0 && packageKodyIds.length === 0) { - message = - 'Add at least one package id, Kody id, or wildcard package scope.' - messageTone = 'error' - handle.update() - return - } - if (exportNames.length === 0) { - message = 'Add at least one export name or wildcard export scope.' - messageTone = 'error' - handle.update() - return - } - - saveState = 'creating' - message = null - messageTone = 'info' - handle.update() - try { - const response = await fetch(accountPackageInvocationTokensApiPath, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - credentials: 'include', - body: JSON.stringify({ - action: 'create', - name: nextEditorState.name, - rawToken: nextEditorState.rawToken, - packageIds, - packageKodyIds, - exportNames, - sources, - }), - }) - if (response.status === 401) { - redirectToLogin() - return - } - const payload = await readJson< - AccountPackageInvocationTokensLoaderData & { - error?: string - ok?: boolean - } - >(response) - if (!response.ok || !payload?.ok) { - throw new Error(payload?.error || 'Unable to create token.') - } - mutationVersion += 1 - applyPayload( - payload, - packageInvocationTokensRoute.buildListHref(getCurrentSearch()), - ) - saveState = 'idle' - message = - 'Created token. The raw token was not stored and will not be shown again.' - messageTone = 'info' - const nextPath = payload.selectedTokenId - ? packageInvocationTokensRoute.buildDetailHref( - payload.selectedTokenId, - getCurrentSearch(), - ) - : packageInvocationTokensRoute.buildListHref(getCurrentSearch()) - syncRouterLocation(nextPath) - handle.update() - } catch (error) { - saveState = 'idle' - message = - error instanceof Error ? error.message : 'Unable to create token.' - messageTone = 'error' - handle.update() - } - } - - async function updateSelectedToken(form?: HTMLFormElement) { - const tokenId = getCurrentSelectedTokenId() - if (!tokenId || saveState !== 'idle') return - const nextEditorState = form ? readEditorStateFromForm(form) : editorState - editorState = nextEditorState - const packageIds = parseListText(nextEditorState.packageIdsText) - const packageKodyIds = parseListText(nextEditorState.packageKodyIdsText) - const exportNames = parseListText(nextEditorState.exportNamesText) - const sources = parseListText(nextEditorState.sourcesText) - - if (!nextEditorState.name) { - message = 'Token name is required.' - messageTone = 'error' - handle.update() - return - } - if (packageIds.length === 0 && packageKodyIds.length === 0) { - message = - 'Add at least one package id, Kody id, or wildcard package scope.' - messageTone = 'error' - handle.update() - return - } - if (exportNames.length === 0) { - message = 'Add at least one export name or wildcard export scope.' - messageTone = 'error' - handle.update() - return - } - - saveState = 'updating' - message = null - messageTone = 'info' - handle.update() - try { - const response = await fetch(accountPackageInvocationTokensApiPath, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - credentials: 'include', - body: JSON.stringify({ - action: 'update', - id: tokenId, - name: nextEditorState.name, - rawToken: nextEditorState.rawToken, - packageIds, - packageKodyIds, - exportNames, - sources, - }), - }) - if (response.status === 401) { - redirectToLogin() - return - } - const payload = await readJson< - AccountPackageInvocationTokensLoaderData & { - error?: string - ok?: boolean - } - >(response) - if (!response.ok || !payload?.ok) { - throw new Error(payload?.error || 'Unable to update token.') - } - mutationVersion += 1 - const detailHref = packageInvocationTokensRoute.buildDetailHref( - tokenId, - getCurrentSearch(), - ) - applyPayload(payload, detailHref) - saveState = 'idle' - message = nextEditorState.rawToken - ? 'Saved token and replaced its raw value.' - : 'Saved token.' - messageTone = 'info' - syncRouterLocation(detailHref) - handle.update() - } catch (error) { - saveState = 'idle' - message = - error instanceof Error ? error.message : 'Unable to update token.' - messageTone = 'error' - handle.update() - } - } - - async function revokeSelectedToken() { - const tokenId = getCurrentSelectedTokenId() - if (!tokenId || saveState !== 'idle') return - saveState = 'revoking' - message = null - messageTone = 'info' - handle.update() - try { - const response = await fetch(accountPackageInvocationTokensApiPath, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - credentials: 'include', - body: JSON.stringify({ - action: 'revoke', - id: tokenId, - }), - }) - if (response.status === 401) { - redirectToLogin() - return - } - const payload = await readJson< - AccountPackageInvocationTokensLoaderData & { - error?: string - ok?: boolean - } - >(response) - if (!response.ok || !payload?.ok) { - throw new Error(payload?.error || 'Unable to revoke token.') - } - mutationVersion += 1 - const detailHref = packageInvocationTokensRoute.buildDetailHref( - tokenId, - getCurrentSearch(), - ) - applyPayload({ ...payload, selectedTokenId: tokenId }, detailHref) - saveState = 'idle' - message = 'Revoked token.' - messageTone = 'info' - syncRouterLocation(detailHref) - handle.update() - } catch (error) { - saveState = 'idle' - message = - error instanceof Error ? error.message : 'Unable to revoke token.' - messageTone = 'error' - handle.update() - } - } - - async function reinstateSelectedToken() { - const tokenId = getCurrentSelectedTokenId() - if (!tokenId || saveState !== 'idle') return - saveState = 'reinstating' - message = null - messageTone = 'info' - handle.update() - try { - const response = await fetch(accountPackageInvocationTokensApiPath, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - credentials: 'include', - body: JSON.stringify({ - action: 'reinstate', - id: tokenId, - }), - }) - if (response.status === 401) { - redirectToLogin() - return - } - const payload = await readJson< - AccountPackageInvocationTokensLoaderData & { - error?: string - ok?: boolean - } - >(response) - if (!response.ok || !payload?.ok) { - throw new Error(payload?.error || 'Unable to reinstate token.') - } - mutationVersion += 1 - const detailHref = packageInvocationTokensRoute.buildDetailHref( - tokenId, - getCurrentSearch(), - ) - applyPayload(payload, detailHref) - saveState = 'idle' - message = 'Reinstated token.' - messageTone = 'info' - syncRouterLocation(detailHref) - handle.update() - } catch (error) { - saveState = 'idle' - message = - error instanceof Error ? error.message : 'Unable to reinstate token.' - messageTone = 'error' - handle.update() - } - } - - async function deleteSelectedToken() { - const tokenId = getCurrentSelectedTokenId() - if (!tokenId || saveState !== 'idle') return - saveState = 'deleting' - message = null - messageTone = 'info' - handle.update() - try { - const response = await fetch(accountPackageInvocationTokensApiPath, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - credentials: 'include', - body: JSON.stringify({ - action: 'delete', - id: tokenId, - }), - }) - if (response.status === 401) { - redirectToLogin() - return - } - const payload = await readJson< - AccountPackageInvocationTokensLoaderData & { - error?: string - ok?: boolean - } - >(response) - if (!response.ok || !payload?.ok) { - throw new Error(payload?.error || 'Unable to delete token.') - } - mutationVersion += 1 - const listHref = - packageInvocationTokensRoute.buildListHref(getCurrentSearch()) - applyPayload(payload, listHref) - saveState = 'idle' - selectedTokenId = null - editorState = createEmptyEditorState() - editMode = false - message = 'Deleted token permanently.' - messageTone = 'info' - syncRouterLocation(listHref) - handle.update() - } catch (error) { - saveState = 'idle' - message = - error instanceof Error ? error.message : 'Unable to delete token.' - messageTone = 'error' - handle.update() - } - } - - /** - * Local cleanup when a sidebar link starts navigating to another token. - * Editor state is deliberately NOT seeded here: until the navigation - * commits, the URL (and therefore `getCurrentSelectedTokenId`) still - * points at the previous token, and a save during that window would write - * the new token's editor fields onto the old token. `applyPayload` - * initializes the editor from the committed payload instead. - */ - function resetTokenSelectionState() { - revokeConfirm = false - deleteTokenCheck.reset() - message = null - messageTone = 'info' - handle.update() - } - - function applyRouteLoaderData(href: string) { - if (!packageInvocationTokensRoute.isRoutePath(href)) return false - const routeData = tryConsumeRouteLoaderData( - handle, - 'accountPackageInvocationTokens', - href, - ) - if (!routeData) return false - applyPayload(routeData, href) - status = 'ready' - message = null - messageTone = 'info' - loadLatch.markLoaded(getDataLatchKey(href)) - return true - } - - return () => { - const currentHref = getCurrentHref() - const appliedRouteData = applyRouteLoaderData(currentHref) - // A same-path refresh whose loader failed leaves no preload and no - // href change; the stale marker forces the fallback refetch. - const needsStaleRefresh = - consumeStaleNavigationData(currentHref) && !appliedRouteData - const latchKey = getDataLatchKey(currentHref) - const isRefreshingForLocationChange = - status !== 'loading' && !loadLatch.isLoadedFor(latchKey) - const needsLoad = loadLatch.needsLoad({ - currentHref: latchKey, - appliedRouteData, - needsStaleRefresh, - }) - if (needsLoad && typeof document !== 'undefined') { - handle.queueTask(loadTokens) - } - const isMutating = saveState !== 'idle' - const selection = packageInvocationTokensRoute.getSelection(currentHref) - const filters = readFilterState(currentHref) - const filteredTokens = filterTokens(tokens, filters.search, packages) - // The URL is the source of truth for selection in every environment: - // the base tokens path (no token segment) means nothing is selected, - // so falling back to module state here would keep a stale detail - // panel open after navigating back to the list. - const effectiveSelectedTokenId = selection.selectedId - const selectedToken = - tokens.find((token) => token.id === effectiveSelectedTokenId) ?? null - const isEditingSelectedToken = - editMode && - !isRefreshingForLocationChange && - selectedToken != null && - !selectedToken.revokedAt - const showTokenNotFound = - selection.selectedId != null && - !selectedToken && - !isRefreshingForLocationChange - const showSupportingSections = - selection.isCreating || selection.selectedId != null - const endpointTemplate = username - ? `${invocationUrlOrigin}/@${username}/api/package-invocations//` - : '' - - return ( - - - New token - - } - /> - - {status === 'loading' ? ( -

- Loading package invocation tokens... -

- ) : null} - {message ? ( - - {message} - - ) : null} - - {status === 'ready' ? ( - { - replaceLocation(buildHrefWithUpdatedSearch(value)) - }} - /> - } - columns={[ - { key: 'name', label: 'Token', primary: true }, - { key: 'status', label: 'Status' }, - { key: 'packages', label: 'Packages', drop: 2 }, - { key: 'exports', label: 'Exports', drop: 1 }, - { key: 'created', label: 'Created' }, - ]} - rows={filteredTokens.map((token) => ({ - id: token.id, - // A create, edit, or revoke is in flight; the editor below - // owns the selection until it settles. - href: isMutating - ? undefined - : packageInvocationTokensRoute.buildDetailHref( - token.id, - getCurrentSearch(), - ), - cells: { - name: {token.name}, - status: tokenStatus(token), - packages: ( - {tokenPackageSummary(token)} - ), - exports: ( - - {formatScope(token.exportNames)} - - ), - created: ( - - {formatTimestamp(token.createdAt)} - - ), - }, - }))} - record={ - showSupportingSections ? ( -
- {selection.isCreating ? ( -
{ - event.preventDefault() - if (event.currentTarget instanceof HTMLFormElement) { - void createToken(event.currentTarget) - } - }), - css(cardCss), - ]} - > -
-

Create token

-

- Paste the raw token once. Kody stores only its hash, - so keep the raw value in the trusted client. -

-
- - - - - -
-